| 1 | package net.minecraft.world.level.levelgen;
|
| 2 |
|
| 3 | import java.util.List;
|
| 4 | import net.minecraft.core.BlockPos;
|
| 5 | import net.minecraft.core.QuartPos;
|
| 6 | import net.minecraft.util.Mth;
|
| 7 | import net.minecraft.world.level.levelgen.densityfunction.DensitySamplerSet;
|
| 8 |
|
| 9 | public class NoiseSpawnFinder {
|
| 10 | private static final long MAX_RADIUS = 2048L;
|
| 11 | private NoiseSpawnFinder.Result result;
|
| 12 |
|
| 13 | private NoiseSpawnFinder(final List<SpawnTargetPoint> targetPoints, final DensitySamplerSet samplers) {
|
| 14 | this.result = getSpawnPositionAndFitness(samplers, targetPoints, 0, 0);
|
| 15 | this.radialSearch(samplers, targetPoints, 2048.0F, 512.0F);
|
| 16 | this.radialSearch(samplers, targetPoints, 512.0F, 32.0F);
|
| 17 | }
|
| 18 |
|
| 19 | public static BlockPos findSpawnPosition(final List<SpawnTargetPoint> targetPoints, final DensitySamplerSet samplers) {
|
| 20 | return (new NoiseSpawnFinder(targetPoints, samplers)).result.location();
|
| 21 | }
|
| 22 |
|
| 23 | private void radialSearch(final DensitySamplerSet samplers, final List<SpawnTargetPoint> targetPoints, final float maxRadius, final float radiusIncrement) {
|
| 24 | float angle = 0.0F;
|
| 25 | float radius = radiusIncrement;
|
| 26 | BlockPos searchOrigin = this.result.location();
|
| 27 |
|
| 28 | while (radius <= maxRadius) {
|
| 29 | int x = searchOrigin.getX() + (int)(Math.sin(angle) * radius);
|
| 30 | int z = searchOrigin.getZ() + (int)(Math.cos(angle) * radius);
|
| 31 | NoiseSpawnFinder.Result candidate = getSpawnPositionAndFitness(samplers, targetPoints, x, z);
|
| 32 | if (candidate.fitness() < this.result.fitness()) {
|
| 33 | this.result = candidate;
|
| 34 | }
|
| 35 |
|
| 36 | angle += radiusIncrement / radius;
|
| 37 | if (angle > Math.PI * 2) {
|
| 38 | angle = 0.0F;
|
| 39 | radius += radiusIncrement;
|
| 40 | }
|
| 41 | }
|
| 42 | }
|
| 43 |
|
| 44 | private static NoiseSpawnFinder.Result getSpawnPositionAndFitness(
|
| 45 | final DensitySamplerSet samplers, final List<SpawnTargetPoint> targetPoints, final int blockX, final int blockZ
|
| 46 | ) {
|
| 47 | int quartBlockX = QuartPos.toBlock(QuartPos.fromBlock(blockX));
|
| 48 | int quartBlockZ = QuartPos.toBlock(QuartPos.fromBlock(blockZ));
|
| 49 | long minFitness = Long.MAX_VALUE;
|
| 50 |
|
| 51 | for (SpawnTargetPoint point : targetPoints) {
|
| 52 | minFitness = Math.min(minFitness, point.sampleFitness(samplers, quartBlockX, 0, quartBlockZ));
|
| 53 | }
|
| 54 |
|
| 55 | long distanceBiasToWorldOrigin = Mth.square((long)blockX) + Mth.square((long)blockZ);
|
| 56 | long fitnessWithDistance = minFitness * Mth.square(2048L) + distanceBiasToWorldOrigin;
|
| 57 | return new NoiseSpawnFinder.Result(new BlockPos(blockX, 0, blockZ), fitnessWithDistance);
|
| 58 | }
|
| 59 |
|
| 60 | private record Result(BlockPos location, long fitness) {
|
| 61 | }
|
| 62 | }
|
| 63 |
|