PlayerSpawnFinder .java

net.minecraft.server.level.PlayerSpawnFinder (class): members: ABSOLUTE_MAX_ATTEMPTS, getLevelRespawnPos, getSpawnPosInChunk, nextCandidateIndex, coprime.

net.minecraft.server.levelclass192 linesserver7.3 KB

API Surface (1)

CompletableFuture<Vec3> findSpawn(final ServerLevel level, final BlockPos spawnSuggestion)

Fields & Constants (10)

PLAYER_DIMENSIONS
ABSOLUTE_MAX_ATTEMPTS
level
spawnSuggestion
radius
candidateCount
coprime
offset
nextCandidateIndex
finishedFuture

String literals (7)

"Searching for spawn"
"Spawn Lookup"
"Origin"
"Radius"
"Candidate"
"Progress"
" out of "

Full Source

PlayerSpawnFinder.java192 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.server.level;
2
3
import java.util.Optional;
4
import java.util.concurrent.CompletableFuture;
5
import java.util.function.Supplier;
6
import net.minecraft.CrashReport;
7
import net.minecraft.CrashReportCategory;
8
import net.minecraft.ReportedException;
9
import net.minecraft.SharedConstants;
10
import net.minecraft.core.BlockPos;
11
import net.minecraft.core.Direction;
12
import net.minecraft.core.SectionPos;
13
import net.minecraft.util.Mth;
14
import net.minecraft.util.RandomSource;
15
import net.minecraft.world.entity.EntityDimensions;
16
import net.minecraft.world.entity.EntityTypes;
17
import net.minecraft.world.level.ChunkPos;
18
import net.minecraft.world.level.CollisionGetter;
19
import net.minecraft.world.level.GameType;
20
import net.minecraft.world.level.block.Block;
21
import net.minecraft.world.level.block.state.BlockState;
22
import net.minecraft.world.level.chunk.LevelChunk;
23
import net.minecraft.world.level.gamerules.GameRules;
24
import net.minecraft.world.level.levelgen.Heightmap;
25
import net.minecraft.world.phys.Vec3;
26
import org.jspecify.annotations.Nullable;
27
28
public class PlayerSpawnFinder {
29
	private static final EntityDimensions PLAYER_DIMENSIONS = EntityTypes.PLAYER.getDimensions();
30
	private static final int ABSOLUTE_MAX_ATTEMPTS = 1024;
31
	private final ServerLevel level;
32
	private final BlockPos spawnSuggestion;
33
	private final int radius;
34
	private final int candidateCount;
35
	private final int coprime;
36
	private final int offset;
37
	private int nextCandidateIndex;
38
	private final CompletableFuture<Vec3> finishedFuture = new CompletableFuture<>();
39
40
	private PlayerSpawnFinder(final ServerLevel level, final BlockPos spawnSuggestion, final int radius) {
41
		this.level = level;
42
		this.spawnSuggestion = spawnSuggestion;
43
		this.radius = radius;
44
		long squareSide = radius * 2L + 1L;
45
		this.candidateCount = (int)Math.min(1024L, squareSide * squareSide);
46
		this.coprime = getCoprime(this.candidateCount);
47
		this.offset = RandomSource.createThreadLocalInstance().nextInt(this.candidateCount);
48
	}
49
50
	public static CompletableFuture<Vec3> findSpawn(final ServerLevel level, final BlockPos spawnSuggestion) {
51
		if (level.getServer().getWorldData().getGameType() == GameType.ADVENTURE) {
52
			return CompletableFuture.completedFuture(fixupSpawnHeight(level, spawnSuggestion));
53
		}
54
55
		int radius = Math.max(0, level.getGameRules().get(GameRules.RESPAWN_RADIUS));
56
		int distToBorder = Mth.floor(level.getWorldBorder().getDistanceToBorder(spawnSuggestion.getX(), spawnSuggestion.getZ()));
57
		if (distToBorder < radius) {
58
			radius = distToBorder;
59
		}
60
61
		if (distToBorder <= 1) {
62
			radius = 1;
63
		}
64
65
		PlayerSpawnFinder finder = new PlayerSpawnFinder(level, spawnSuggestion, radius);
66
		finder.scheduleNext();
67
		return finder.finishedFuture;
68
	}
69
70
	private void scheduleNext() {
71
		int candidateIndex = this.nextCandidateIndex++;
72
		if (candidateIndex < this.candidateCount) {
73
			int value = (this.offset + this.coprime * candidateIndex) % this.candidateCount;
74
			int deltaX = value % (this.radius * 2 + 1);
75
			int deltaZ = value / (this.radius * 2 + 1);
76
			int targetX = this.spawnSuggestion.getX() + deltaX - this.radius;
77
			int targetZ = this.spawnSuggestion.getZ() + deltaZ - this.radius;
78
			this.scheduleCandidate(targetX, targetZ, candidateIndex, () -> {
79
				BlockPos spawnPos = getLevelRespawnPos(this.level, targetX, targetZ);
80
				return spawnPos != null && noCollisionNoLiquid(this.level, spawnPos) ? Optional.of(Vec3.atBottomCenterOf(spawnPos)) : Optional.empty();
81
			});
82
		} else {
83
			this.scheduleCandidate(
84
				this.spawnSuggestion.getX(), this.spawnSuggestion.getZ(), candidateIndex, () -> Optional.of(fixupSpawnHeight(this.level, this.spawnSuggestion))
85
			);
86
		}
87
	}
88
89
	private static Vec3 fixupSpawnHeight(final CollisionGetter level, final BlockPos spawnPos) {
90
		BlockPos.MutableBlockPos mutablePos = spawnPos.mutable();
91
92
		while (!noCollisionNoLiquid(level, mutablePos) && mutablePos.getY() < level.getMaxY()) {
93
			mutablePos.move(Direction.UP);
94
		}
95
96
		mutablePos.move(Direction.DOWN);
97
98
		while (noCollisionNoLiquid(level, mutablePos) && mutablePos.getY() > level.getMinY()) {
99
			mutablePos.move(Direction.DOWN);
100
		}
101
102
		mutablePos.move(Direction.UP);
103
		return Vec3.atBottomCenterOf(mutablePos);
104
	}
105
106
	private static boolean noCollisionNoLiquid(final CollisionGetter level, final BlockPos pos) {
107
		return level.noCollision(null, PLAYER_DIMENSIONS.makeBoundingBox(Vec3.atBottomCenterOf(pos)), true);
108
	}
109
110
	private static int getCoprime(final int possibleOrigins) {
111
		return possibleOrigins <= 16 ? possibleOrigins - 1 : 17;
112
	}
113
114
	private void scheduleCandidate(final int candidateX, final int candidateZ, final int candidateIndex, final Supplier<Optional<Vec3>> candidateChecker) {
115
		if (!this.finishedFuture.isDone()) {
116
			int chunkX = SectionPos.blockToSectionCoord(candidateX);
117
			int chunkZ = SectionPos.blockToSectionCoord(candidateZ);
118
			this.level.getChunkSource().addTicketAndLoadWithRadius(TicketType.SPAWN_SEARCH, new ChunkPos(chunkX, chunkZ), 0).whenCompleteAsync((ignored, throwable) -> {
119
				if (throwable == null) {
120
					try {
121
						Optional<Vec3> spawnPos = candidateChecker.get();
122
						if (spawnPos.isPresent()) {
123
							this.finishedFuture.complete(spawnPos.get());
124
						} else {
125
							this.scheduleNext();
126
						}
127
					} catch (Throwable t) {
128
						throwable = t;
129
					}
130
				}
131
132
				if (throwable != null) {
133
					CrashReport report = CrashReport.forThrowable(throwable, "Searching for spawn");
134
					CrashReportCategory details = report.addCategory("Spawn Lookup");
135
					details.setDetail("Origin", this.spawnSuggestion::toString);
136
					details.setDetail("Radius", () -> Integer.toString(this.radius));
137
					details.setDetail("Candidate", () -> "[" + candidateX + "," + candidateZ + "]");
138
					details.setDetail("Progress", () -> candidateIndex + " out of " + this.candidateCount);
139
					this.finishedFuture.completeExceptionally(new ReportedException(report));
140
				}
141
			}, this.level.getServer());
142
		}
143
	}
144
145
	protected static @Nullable BlockPos getLevelRespawnPos(final ServerLevel level, final int x, final int z) {
146
		boolean caveWorld = level.dimensionType().hasCeiling();
147
		LevelChunk chunk = level.getChunk(SectionPos.blockToSectionCoord(x), SectionPos.blockToSectionCoord(z));
148
		int topY = caveWorld ? level.getChunkSource().getGenerator().getSpawnHeight(level) : chunk.getHeight(Heightmap.Types.MOTION_BLOCKING, x & 15, z & 15);
149
		if (topY < level.getMinY()) {
150
			return null;
151
		}
152
153
		int surface = chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x & 15, z & 15);
154
		if (surface <= topY && surface > chunk.getHeight(Heightmap.Types.OCEAN_FLOOR, x & 15, z & 15)) {
155
			return null;
156
		}
157
158
		BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
159
160
		for (int y = topY + 1; y >= level.getMinY(); y--) {
161
			pos.set(x, y, z);
162
			BlockState blockState = level.getBlockState(pos);
163
			if (!blockState.getFluidState().isEmpty()) {
164
				break;
165
			}
166
167
			if (Block.isFaceFull(blockState.getCollisionShape(level, pos), Direction.UP)) {
168
				return pos.above().immutable();
169
			}
170
		}
171
172
		return null;
173
	}
174
175
	public static @Nullable BlockPos getSpawnPosInChunk(final ServerLevel level, final ChunkPos chunkPos) {
176
		if (SharedConstants.debugVoidTerrain(chunkPos)) {
177
			return null;
178
		}
179
180
		for (int x = chunkPos.getMinBlockX(); x <= chunkPos.getMaxBlockX(); x++) {
181
			for (int z = chunkPos.getMinBlockZ(); z <= chunkPos.getMaxBlockZ(); z++) {
182
				BlockPos validSpawnPosition = getLevelRespawnPos(level, x, z);
183
				if (validSpawnPosition != null) {
184
					return validSpawnPosition;
185
				}
186
			}
187
		}
188
189
		return null;
190
	}
191
}
192

Decompiled Minecraft 26.3 source of PlayerSpawnFinder (net/minecraft/server/level/PlayerSpawnFinder.java) with Mojang official mappings, stored verbatim on the site.