NaturalSpawner .java

net.minecraft.world.level.NaturalSpawner (class, 529 lines): members: INSCRIBED_SQUARE_SPAWN_DISTANCE_CHUNK, getFilteredSpawningCategories, spawnForChunk.

net.minecraft.world.levelclass529 linescommon21.3 KB

API Surface (11)

NaturalSpawner.SpawnState createState(final int spawnableChunkCount, final ServerLevel level, final NaturalSpawner.ChunkGetter chunkGetter, final LocalMobCapCalculator localMobCapCalculator)
List<MobCategory> getFilteredSpawningCategories(final NaturalSpawner.SpawnState state, final boolean spawnEnemies, final boolean spawnPersistent)
void spawnForChunk(final ServerLevel level, final LevelChunk chunk, final NaturalSpawner.SpawnState state, final List<MobCategory> spawningCategories)
void spawnCategoryForChunk(final MobCategory mobCategory, final ServerLevel level, final LevelChunk chunk, final NaturalSpawner.SpawnPredicate extraTest, final NaturalSpawner.AfterSpawnCallback spawnCallback)
void spawnCategoryForPosition(final MobCategory mobCategory, final ServerLevel level, final BlockPos start)
void spawnCategoryForPosition(final MobCategory mobCategory, final ServerLevel level, final ChunkAccess chunk, final BlockPos start, final NaturalSpawner.SpawnPredicate extraTest, final NaturalSpawner.AfterSpawnCallback spawnCallback)
boolean isInNetherFortressBounds(final BlockPos pos, final ServerLevel level, final MobCategory category, final StructureManager structureManager)
boolean isValidEmptySpawnBlock(final BlockGetter level, final BlockPos pos, final BlockState blockState, final FluidState fluidState, final EntityType<?> type)
void spawnMobsForChunkGeneration(final ServerLevelAccessor level, final BlockPos sourcePos, final ChunkPos chunkPos, final RandomSource random)
int getSpawnableChunkCount()
Object2IntMap<MobCategory> getMobCategoryCounts()

Fields & Constants (22)

LOGGER
MIN_SPAWN_DISTANCE
SPAWN_DISTANCE_CHUNK
SPAWN_DISTANCE_BLOCK
INSCRIBED_SQUARE_SPAWN_DISTANCE_CHUNK
MAGIC_NUMBER
SPAWNING_CATEGORIES
chunkGetter
state
mobCategory
level
chunk
extraTest
start
pos
structureManager
generator
currentSpawnData
random
spawnerData
category
fluidState

String literals (2)

"spawner"
"Failed to create mob"

Full Source

NaturalSpawner.java529 lines · Minecraft 26.3 · verbatim
1
package net.minecraft.world.level;
2
3
import com.mojang.logging.LogUtils;
4
import it.unimi.dsi.fastutil.objects.Object2IntMap;
5
import it.unimi.dsi.fastutil.objects.Object2IntMaps;
6
import it.unimi.dsi.fastutil.objects.Object2IntOpenHashMap;
7
import java.util.ArrayList;
8
import java.util.List;
9
import java.util.Objects;
10
import java.util.Optional;
11
import java.util.function.Consumer;
12
import java.util.stream.Stream;
13
import net.minecraft.SharedConstants;
14
import net.minecraft.core.BlockPos;
15
import net.minecraft.core.Direction;
16
import net.minecraft.core.Holder;
17
import net.minecraft.core.registries.BuiltInRegistries;
18
import net.minecraft.core.registries.Registries;
19
import net.minecraft.server.level.ServerLevel;
20
import net.minecraft.tags.BiomeTags;
21
import net.minecraft.tags.BlockTags;
22
import net.minecraft.util.Mth;
23
import net.minecraft.util.RandomSource;
24
import net.minecraft.util.VisibleForDebug;
25
import net.minecraft.util.profiling.Profiler;
26
import net.minecraft.util.profiling.ProfilerFiller;
27
import net.minecraft.util.random.WeightedList;
28
import net.minecraft.world.attribute.EnvironmentAttributeReader;
29
import net.minecraft.world.attribute.EnvironmentAttributes;
30
import net.minecraft.world.entity.Entity;
31
import net.minecraft.world.entity.EntitySpawnReason;
32
import net.minecraft.world.entity.EntityType;
33
import net.minecraft.world.entity.Mob;
34
import net.minecraft.world.entity.MobCategory;
35
import net.minecraft.world.entity.SpawnGroupData;
36
import net.minecraft.world.entity.SpawnPlacements;
37
import net.minecraft.world.entity.player.Player;
38
import net.minecraft.world.level.biome.Biome;
39
import net.minecraft.world.level.biome.MobSpawnSettings;
40
import net.minecraft.world.level.block.Blocks;
41
import net.minecraft.world.level.block.state.BlockState;
42
import net.minecraft.world.level.chunk.ChunkAccess;
43
import net.minecraft.world.level.chunk.ChunkGenerator;
44
import net.minecraft.world.level.chunk.LevelChunk;
45
import net.minecraft.world.level.gamerules.GameRules;
46
import net.minecraft.world.level.levelgen.Heightmap;
47
import net.minecraft.world.level.levelgen.structure.BuiltinStructures;
48
import net.minecraft.world.level.levelgen.structure.Structure;
49
import net.minecraft.world.level.levelgen.structure.structures.NetherFortressStructure;
50
import net.minecraft.world.level.material.FluidState;
51
import net.minecraft.world.level.storage.LevelData;
52
import net.minecraft.world.phys.Vec3;
53
import org.jspecify.annotations.Nullable;
54
import org.slf4j.Logger;
55
56
public final class NaturalSpawner {
57
	private static final Logger LOGGER = LogUtils.getLogger();
58
	private static final int MIN_SPAWN_DISTANCE = 24;
59
	public static final int SPAWN_DISTANCE_CHUNK = 8;
60
	public static final int SPAWN_DISTANCE_BLOCK = 128;
61
	public static final int INSCRIBED_SQUARE_SPAWN_DISTANCE_CHUNK = Mth.floor(8.0F / Mth.SQRT_OF_TWO);
62
	private static final int MAGIC_NUMBER = (int)Math.pow(17.0, 2.0);
63
	private static final MobCategory[] SPAWNING_CATEGORIES = Stream.of(MobCategory.values()).filter(c -> c != MobCategory.MISC).toArray(MobCategory[]::new);
64
65
	private NaturalSpawner() {
66
	}
67
68
	public static NaturalSpawner.SpawnState createState(
69
		final int spawnableChunkCount, final ServerLevel level, final NaturalSpawner.ChunkGetter chunkGetter, final LocalMobCapCalculator localMobCapCalculator
70
	) {
71
		Iterable<Entity> entities = level.getAllEntities();
72
		PotentialCalculator spawnPotential = new PotentialCalculator();
73
		Object2IntOpenHashMap<MobCategory> mobCounts = new Object2IntOpenHashMap<>();
74
75
		for (Entity entity : entities) {
76
			if (!(entity instanceof Mob mob && (mob.isPersistenceRequired() || mob.requiresCustomPersistence()))) {
77
				MobCategory category = entity.getType().getCategory();
78
				if (category != MobCategory.MISC) {
79
					BlockPos pos = entity.blockPosition();
80
					chunkGetter.query(ChunkPos.pack(pos), chunk -> {
81
						MobSpawnSettings naturalMobSpawns = level.environmentAttributes().getValue(EnvironmentAttributes.NATURAL_MOB_SPAWNS, pos);
82
						MobSpawnSettings.MobSpawnCost mobSpawnCost = naturalMobSpawns.getMobSpawnCost(entity.getType());
83
						if (mobSpawnCost != null) {
84
							spawnPotential.addCharge(entity.blockPosition(), mobSpawnCost.charge());
85
						}
86
87
						if (entity instanceof Mob) {
88
							localMobCapCalculator.addMob(chunk.getPos(), category);
89
						}
90
91
						mobCounts.addTo(category, 1);
92
					});
93
				}
94
			}
95
		}
96
97
		return new NaturalSpawner.SpawnState(spawnableChunkCount, mobCounts, spawnPotential, localMobCapCalculator);
98
	}
99
100
	public static List<MobCategory> getFilteredSpawningCategories(final NaturalSpawner.SpawnState state, final boolean spawnEnemies, final boolean spawnPersistent) {
101
		List<MobCategory> spawningCategories = new ArrayList<>(SPAWNING_CATEGORIES.length);
102
103
		for (MobCategory mobCategory : SPAWNING_CATEGORIES) {
104
			if ((spawnEnemies || mobCategory.isFriendly()) && (spawnPersistent || !mobCategory.isPersistent()) && state.canSpawnForCategoryGlobal(mobCategory)) {
105
				spawningCategories.add(mobCategory);
106
			}
107
		}
108
109
		return spawningCategories;
110
	}
111
112
	public static void spawnForChunk(
113
		final ServerLevel level, final LevelChunk chunk, final NaturalSpawner.SpawnState state, final List<MobCategory> spawningCategories
114
	) {
115
		ProfilerFiller profiler = Profiler.get();
116
		profiler.push("spawner");
117
118
		for (MobCategory mobCategory : spawningCategories) {
119
			if (state.canSpawnForCategoryLocal(mobCategory, chunk.getPos())) {
120
				spawnCategoryForChunk(mobCategory, level, chunk, state::canSpawn, state::afterSpawn);
121
			}
122
		}
123
124
		profiler.pop();
125
	}
126
127
	public static void spawnCategoryForChunk(
128
		final MobCategory mobCategory,
129
		final ServerLevel level,
130
		final LevelChunk chunk,
131
		final NaturalSpawner.SpawnPredicate extraTest,
132
		final NaturalSpawner.AfterSpawnCallback spawnCallback
133
	) {
134
		BlockPos start = getRandomPosWithin(level, chunk);
135
		if (start.getY() >= level.getMinY() + 1) {
136
			spawnCategoryForPosition(mobCategory, level, chunk, start, extraTest, spawnCallback);
137
		}
138
	}
139
140
	@VisibleForDebug
141
	public static void spawnCategoryForPosition(final MobCategory mobCategory, final ServerLevel level, final BlockPos start) {
142
		spawnCategoryForPosition(mobCategory, level, level.getChunk(start), start, (var0, var1, var2, var3) -> true, (var0, var1) -> {});
143
	}
144
145
	public static void spawnCategoryForPosition(
146
		final MobCategory mobCategory,
147
		final ServerLevel level,
148
		final ChunkAccess chunk,
149
		final BlockPos start,
150
		final NaturalSpawner.SpawnPredicate extraTest,
151
		final NaturalSpawner.AfterSpawnCallback spawnCallback
152
	) {
153
		StructureManager structureManager = level.structureManager();
154
		ChunkGenerator generator = level.getChunkSource().getGenerator();
155
		int yStart = start.getY();
156
		BlockState state = chunk.getBlockState(start);
157
		if (!state.isRedstoneConductor(chunk, start)) {
158
			BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos();
159
			int clusterSize = 0;
160
161
			for (int groupCount = 0; groupCount < 3; groupCount++) {
162
				int x = start.getX();
163
				int z = start.getZ();
164
				int ss = 6;
165
				MobSpawnSettings.SpawnerData currentSpawnData = null;
166
				SpawnGroupData groupData = null;
167
				int max = Mth.ceil(level.random.nextFloat() * 4.0F);
168
				int groupSize = 0;
169
170
				for (int ll = 0; ll < max; ll++) {
171
					x += level.random.nextInt(6) - level.random.nextInt(6);
172
					z += level.random.nextInt(6) - level.random.nextInt(6);
173
					pos.set(x, yStart, z);
174
					double xx = x + 0.5;
175
					double zz = z + 0.5;
176
					Player nearestPlayer = level.getNearestPlayer(xx, yStart, zz, -1.0, false);
177
					if (nearestPlayer != null) {
178
						double nearestPlayerDistanceSqr = nearestPlayer.distanceToSqr(xx, yStart, zz);
179
						if (isRightDistanceToPlayerAndSpawnPoint(level, chunk, pos, nearestPlayerDistanceSqr)) {
180
							if (currentSpawnData == null) {
181
								Optional<MobSpawnSettings.SpawnerData> nextSpawnData = getRandomSpawnMobAt(level, structureManager, generator, mobCategory, level.random, pos);
182
								if (nextSpawnData.isEmpty()) {
183
									break;
184
								}
185
186
								currentSpawnData = nextSpawnData.get();
187
								max = currentSpawnData.count().sample(level.random);
188
							}
189
190
							if (isValidSpawnPostitionForType(level, mobCategory, structureManager, generator, currentSpawnData, pos, nearestPlayerDistanceSqr)
191
								&& extraTest.test(currentSpawnData.type(), level, pos, chunk)) {
192
								Mob mob = getMobForSpawn(level, currentSpawnData.type());
193
								if (mob == null) {
194
									return;
195
								}
196
197
								mob.snapTo(xx, yStart, zz, level.random.nextFloat() * 360.0F, 0.0F);
198
								if (isValidPositionForMob(level, mob, nearestPlayerDistanceSqr)) {
199
									groupData = mob.finalizeSpawn(level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.NATURAL, groupData);
200
									clusterSize++;
201
									groupSize++;
202
									level.addFreshEntityWithPassengers(mob);
203
									spawnCallback.run(mob, chunk);
204
									if (clusterSize >= mob.getMaxSpawnClusterSize()) {
205
										return;
206
									}
207
208
									if (mob.isMaxGroupSizeReached(groupSize)) {
209
										break;
210
									}
211
								}
212
							}
213
						}
214
					}
215
				}
216
			}
217
		}
218
	}
219
220
	private static boolean isRightDistanceToPlayerAndSpawnPoint(
221
		final ServerLevel level, final ChunkAccess chunk, final BlockPos.MutableBlockPos pos, final double nearestPlayerDistanceSqr
222
	) {
223
		if (nearestPlayerDistanceSqr <= 576.0) {
224
			return false;
225
		}
226
227
		LevelData.RespawnData respawnData = level.getRespawnData();
228
		if (respawnData.dimension() == level.dimension() && respawnData.pos().closerToCenterThan(new Vec3(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5), 24.0)) {
229
			return false;
230
		}
231
232
		ChunkPos chunkPos = ChunkPos.containing(pos);
233
		return Objects.equals(chunkPos, chunk.getPos()) || level.canSpawnEntitiesInChunk(chunkPos);
234
	}
235
236
	private static boolean isValidSpawnPostitionForType(
237
		final ServerLevel level,
238
		final MobCategory mobCategory,
239
		final StructureManager structureManager,
240
		final ChunkGenerator generator,
241
		final MobSpawnSettings.SpawnerData currentSpawnData,
242
		final BlockPos.MutableBlockPos pos,
243
		final double nearestPlayerDistanceSqr
244
	) {
245
		EntityType<?> type = currentSpawnData.type();
246
		if (type.getCategory() == MobCategory.MISC) {
247
			return false;
248
		} else if (!type.canSpawnFarFromPlayer() && nearestPlayerDistanceSqr > type.getCategory().getDespawnDistance() * type.getCategory().getDespawnDistance()) {
249
			return false;
250
		} else if (!type.canSummon() || !canSpawnMobAt(level, structureManager, generator, mobCategory, currentSpawnData, pos)) {
251
			return false;
252
		} else if (!SpawnPlacements.isSpawnPositionOk(type, level, pos)) {
253
			return false;
254
		} else {
255
			return !SpawnPlacements.checkSpawnRules(type, level, EntitySpawnReason.NATURAL, pos, level.random)
256
				? false
257
				: level.noCollision(type.getSpawnAABB(pos.getX() + 0.5, pos.getY(), pos.getZ() + 0.5));
258
		}
259
	}
260
261
	private static @Nullable Mob getMobForSpawn(final ServerLevel level, final EntityType<?> type) {
262
		try {
263
			if (type.create(level, EntitySpawnReason.NATURAL) instanceof Mob mob) {
264
				return mob;
265
			}
266
267
			LOGGER.warn("Can't spawn entity of type: {}", BuiltInRegistries.ENTITY_TYPE.getKey(type));
268
		} catch (Exception e) {
269
			LOGGER.warn("Failed to create mob", e);
270
		}
271
272
		return null;
273
	}
274
275
	private static boolean isValidPositionForMob(final ServerLevel level, final Mob mob, final double nearestPlayerDistanceSqr) {
276
		return nearestPlayerDistanceSqr > mob.getType().getCategory().getDespawnDistance() * mob.getType().getCategory().getDespawnDistance()
277
				&& mob.removeWhenFarAway(nearestPlayerDistanceSqr)
278
			? false
279
			: mob.checkSpawnRules(level, EntitySpawnReason.NATURAL) && mob.checkSpawnObstruction(level);
280
	}
281
282
	private static Optional<MobSpawnSettings.SpawnerData> getRandomSpawnMobAt(
283
		final ServerLevel level,
284
		final StructureManager structureManager,
285
		final ChunkGenerator generator,
286
		final MobCategory mobCategory,
287
		final RandomSource random,
288
		final BlockPos pos
289
	) {
290
		Holder<Biome> biome = level.getBiome(pos);
291
		return mobCategory == MobCategory.WATER_AMBIENT && biome.is(BiomeTags.REDUCED_WATER_AMBIENT_SPAWNS) && random.nextFloat() < 0.98F
292
			? Optional.empty()
293
			: mobsAt(level, structureManager, generator, mobCategory, pos).getRandom(random);
294
	}
295
296
	private static boolean canSpawnMobAt(
297
		final ServerLevel level,
298
		final StructureManager structureManager,
299
		final ChunkGenerator generator,
300
		final MobCategory mobCategory,
301
		final MobSpawnSettings.SpawnerData spawnerData,
302
		final BlockPos pos
303
	) {
304
		return mobsAt(level, structureManager, generator, mobCategory, pos).contains(spawnerData);
305
	}
306
307
	private static WeightedList<MobSpawnSettings.SpawnerData> mobsAt(
308
		final ServerLevel level, final StructureManager structureManager, final ChunkGenerator generator, final MobCategory mobCategory, final BlockPos pos
309
	) {
310
		return isInNetherFortressBounds(pos, level, mobCategory, structureManager)
311
			? NetherFortressStructure.FORTRESS_ENEMIES
312
			: generator.getMobsAt(level, structureManager, mobCategory, pos);
313
	}
314
315
	public static boolean isInNetherFortressBounds(
316
		final BlockPos pos, final ServerLevel level, final MobCategory category, final StructureManager structureManager
317
	) {
318
		if (category == MobCategory.MONSTER && level.getBlockState(pos.below()).is(Blocks.NETHER_BRICKS)) {
319
			Structure fortress = structureManager.registryAccess().lookupOrThrow(Registries.STRUCTURE).getValue(BuiltinStructures.FORTRESS);
320
			return fortress == null ? false : structureManager.getStructureAt(pos, fortress).isValid();
321
		} else {
322
			return false;
323
		}
324
	}
325
326
	private static BlockPos getRandomPosWithin(final Level level, final LevelChunk chunk) {
327
		ChunkPos pos = chunk.getPos();
328
		int x = pos.getMinBlockX() + level.random.nextInt(16);
329
		int z = pos.getMinBlockZ() + level.random.nextInt(16);
330
		int topEmptyY = chunk.getHeight(Heightmap.Types.WORLD_SURFACE, x, z) + 1;
331
		int y = Mth.randomBetweenInclusive(level.random, level.getMinY(), topEmptyY);
332
		return new BlockPos(x, y, z);
333
	}
334
335
	public static boolean isValidEmptySpawnBlock(
336
		final BlockGetter level, final BlockPos pos, final BlockState blockState, final FluidState fluidState, final EntityType<?> type
337
	) {
338
		if (blockState.isCollisionShapeFullBlock(level, pos)) {
339
			return false;
340
		} else if (blockState.isSignalSource()) {
341
			return false;
342
		} else if (!fluidState.isEmpty()) {
343
			return false;
344
		} else {
345
			return blockState.is(BlockTags.PREVENT_MOB_SPAWNING_INSIDE) ? false : !type.isBlockDangerous(blockState);
346
		}
347
	}
348
349
	public static void spawnMobsForChunkGeneration(final ServerLevelAccessor level, final BlockPos sourcePos, final ChunkPos chunkPos, final RandomSource random) {
350
		if (level.getLevel().getGameRules().get(GameRules.SPAWN_MOBS)) {
351
			EnvironmentAttributeReader attributes = level.environmentAttributes();
352
			MobSpawnSettings mobSettings = attributes.getValue(EnvironmentAttributes.NATURAL_MOB_SPAWNS, sourcePos);
353
			WeightedList<MobSpawnSettings.SpawnerData> mobs = mobSettings.getMobsToSpawn(MobCategory.CREATURE);
354
			if (!mobs.isEmpty()) {
355
				float creatureProbability = attributes.getValue(EnvironmentAttributes.CREATURE_WORLD_GEN_SPAWN_PROBABILITY, sourcePos);
356
				int xo = chunkPos.getMinBlockX();
357
				int zo = chunkPos.getMinBlockZ();
358
359
				while (random.nextFloat() < creatureProbability) {
360
					Optional<MobSpawnSettings.SpawnerData> nextSpawnerData = mobs.getRandom(random);
361
					if (!nextSpawnerData.isEmpty()) {
362
						MobSpawnSettings.SpawnerData spawnerData = nextSpawnerData.get();
363
						int count = spawnerData.count().sample(random);
364
						SpawnGroupData groupSpawnData = null;
365
						int x = xo + random.nextInt(16);
366
						int z = zo + random.nextInt(16);
367
						int startX = x;
368
						int startZ = z;
369
370
						for (int i = 0; i < count; i++) {
371
							boolean success = false;
372
373
							for (int attempts = 0; !success && attempts < 4; attempts++) {
374
								BlockPos pos = getTopNonCollidingPos(level, spawnerData.type(), x, z);
375
								if (spawnerData.type().canSummon() && SpawnPlacements.isSpawnPositionOk(spawnerData.type(), level, pos)) {
376
									float width = spawnerData.type().getWidth();
377
									double fx = Mth.clamp(x, (double)xo + width, xo + 16.0 - width);
378
									double fz = Mth.clamp(z, (double)zo + width, zo + 16.0 - width);
379
									if (!level.noCollision(spawnerData.type().getSpawnAABB(fx, pos.getY(), fz))
380
										|| !SpawnPlacements.checkSpawnRules(
381
											spawnerData.type(), level, EntitySpawnReason.CHUNK_GENERATION, BlockPos.containing(fx, pos.getY(), fz), level.getRandom()
382
										)) {
383
										continue;
384
									}
385
386
									Entity entity;
387
									try {
388
										entity = spawnerData.type().create(level.getLevel(), EntitySpawnReason.NATURAL);
389
									} catch (Exception e) {
390
										LOGGER.warn("Failed to create mob", e);
391
										continue;
392
									}
393
394
									if (entity == null) {
395
										continue;
396
									}
397
398
									entity.snapTo(fx, pos.getY(), fz, random.nextFloat() * 360.0F, 0.0F);
399
									if (entity instanceof Mob mob && mob.checkSpawnRules(level, EntitySpawnReason.CHUNK_GENERATION) && mob.checkSpawnObstruction(level)) {
400
										groupSpawnData = mob.finalizeSpawn(level, level.getCurrentDifficultyAt(mob.blockPosition()), EntitySpawnReason.CHUNK_GENERATION, groupSpawnData);
401
										level.addFreshEntityWithPassengers(mob);
402
										success = true;
403
									}
404
								}
405
406
								x += random.nextInt(5) - random.nextInt(5);
407
408
								for (z += random.nextInt(5) - random.nextInt(5); x < xo || x >= xo + 16 || z < zo || z >= zo + 16; z = startZ + random.nextInt(5) - random.nextInt(5)) {
409
									x = startX + random.nextInt(5) - random.nextInt(5);
410
								}
411
							}
412
						}
413
					}
414
				}
415
			}
416
		}
417
	}
418
419
	private static BlockPos getTopNonCollidingPos(final LevelReader level, final EntityType<?> type, final int x, final int z) {
420
		int levelHeight = level.getHeight(SpawnPlacements.getHeightmapType(type), x, z);
421
		BlockPos.MutableBlockPos pos = new BlockPos.MutableBlockPos(x, levelHeight, z);
422
		if (level.dimensionType().hasCeiling()) {
423
			do {
424
				pos.move(Direction.DOWN);
425
			} while (!level.getBlockState(pos).isAir());
426
427
			do {
428
				pos.move(Direction.DOWN);
429
			} while (level.getBlockState(pos).isAir() && pos.getY() > level.getMinY());
430
		}
431
432
		return SpawnPlacements.getPlacementType(type).adjustSpawnPosition(level, pos.immutable());
433
	}
434
435
	@FunctionalInterface
436
	public interface AfterSpawnCallback {
437
		void run(final Mob mob, final ChunkAccess levelChunk);
438
	}
439
440
	@FunctionalInterface
441
	public interface ChunkGetter {
442
		void query(final long chunkKey, Consumer<LevelChunk> output);
443
	}
444
445
	@FunctionalInterface
446
	public interface SpawnPredicate {
447
		boolean test(final EntityType<?> type, final ServerLevel level, final BlockPos blockPos, final ChunkAccess levelChunk);
448
	}
449
450
	public static class SpawnState {
451
		private final int spawnableChunkCount;
452
		private final Object2IntOpenHashMap<MobCategory> mobCategoryCounts;
453
		private final PotentialCalculator spawnPotential;
454
		private final Object2IntMap<MobCategory> unmodifiableMobCategoryCounts;
455
		private final LocalMobCapCalculator localMobCapCalculator;
456
		private @Nullable BlockPos lastCheckedPos;
457
		private @Nullable EntityType<?> lastCheckedType;
458
		private double lastCharge;
459
460
		private SpawnState(
461
			final int spawnableChunkCount,
462
			final Object2IntOpenHashMap<MobCategory> mobCategoryCounts,
463
			final PotentialCalculator spawnPotential,
464
			final LocalMobCapCalculator localMobCapCalculator
465
		) {
466
			this.spawnableChunkCount = spawnableChunkCount;
467
			this.mobCategoryCounts = mobCategoryCounts;
468
			this.spawnPotential = spawnPotential;
469
			this.localMobCapCalculator = localMobCapCalculator;
470
			this.unmodifiableMobCategoryCounts = Object2IntMaps.unmodifiable(mobCategoryCounts);
471
		}
472
473
		private boolean canSpawn(final EntityType<?> type, final Level level, final BlockPos testPos, final ChunkAccess chunk) {
474
			this.lastCheckedPos = testPos;
475
			this.lastCheckedType = type;
476
			MobSpawnSettings naturalMobSpawns = level.environmentAttributes().getValue(EnvironmentAttributes.NATURAL_MOB_SPAWNS, testPos);
477
			MobSpawnSettings.MobSpawnCost mobSpawnCost = naturalMobSpawns.getMobSpawnCost(type);
478
			if (mobSpawnCost == null) {
479
				this.lastCharge = 0.0;
480
				return true;
481
			} else {
482
				double charge = mobSpawnCost.charge();
483
				this.lastCharge = charge;
484
				double energyChange = this.spawnPotential.getPotentialEnergyChange(testPos, charge);
485
				return energyChange <= mobSpawnCost.energyBudget();
486
			}
487
		}
488
489
		private void afterSpawn(final Mob mob, final ChunkAccess chunk) {
490
			EntityType<?> type = mob.getType();
491
			BlockPos pos = mob.blockPosition();
492
			double charge;
493
			if (pos.equals(this.lastCheckedPos) && type == this.lastCheckedType) {
494
				charge = this.lastCharge;
495
			} else {
496
				MobSpawnSettings naturalMobSpawns = mob.level().environmentAttributes().getValue(EnvironmentAttributes.NATURAL_MOB_SPAWNS, pos);
497
				MobSpawnSettings.MobSpawnCost mobSpawnCost = naturalMobSpawns.getMobSpawnCost(type);
498
				if (mobSpawnCost != null) {
499
					charge = mobSpawnCost.charge();
500
				} else {
501
					charge = 0.0;
502
				}
503
			}
504
505
			this.spawnPotential.addCharge(pos, charge);
506
			MobCategory category = type.getCategory();
507
			this.mobCategoryCounts.addTo(category, 1);
508
			this.localMobCapCalculator.addMob(ChunkPos.containing(pos), category);
509
		}
510
511
		public int getSpawnableChunkCount() {
512
			return this.spawnableChunkCount;
513
		}
514
515
		public Object2IntMap<MobCategory> getMobCategoryCounts() {
516
			return this.unmodifiableMobCategoryCounts;
517
		}
518
519
		private boolean canSpawnForCategoryGlobal(final MobCategory mobCategory) {
520
			int maxMobCount = mobCategory.getMaxInstancesPerChunk() * this.spawnableChunkCount / NaturalSpawner.MAGIC_NUMBER;
521
			return this.mobCategoryCounts.getInt(mobCategory) < maxMobCount;
522
		}
523
524
		private boolean canSpawnForCategoryLocal(final MobCategory mobCategory, final ChunkPos chunkPos) {
525
			return this.localMobCapCalculator.canSpawn(mobCategory, chunkPos) || SharedConstants.DEBUG_IGNORE_LOCAL_MOB_CAP;
526
		}
527
	}
528
}
529

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