From 900f65b5911d626af6071c88863e381e592303a9 Mon Sep 17 00:00:00 2001 From: Overlord Date: Sun, 4 Oct 2026 16:45:31 +0200 Subject: [PATCH] Optimize `ZombieVoronoi.evaluateNoise` with a hook-based implementation for Build 42.21. Replace distance calculations with a single-pass method, avoiding boxed sorting. Add associated tests and integrate new patch into the performance patch set. --- .../zomboidforge/compat/b42/B42PatchSet.java | 3 +- .../perf/ZombieVoronoiPerformancePatch.java | 121 +++++++++++ .../ZombieVoronoiPerformancePatchTest.java | 188 ++++++++++++++++++ .../compat/b42/hooks/ZombieVoronoiHooks.java | 27 +++ .../compat/b42/util/VoronoiNoise.java | 121 +++++++++++ .../compat/b42/util/VoronoiNoiseTest.java | 117 +++++++++++ 6 files changed, 576 insertions(+), 1 deletion(-) create mode 100644 compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatch.java create mode 100644 compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatchTest.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks.java create mode 100644 compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoise.java create mode 100644 compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoiseTest.java diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java index c28494a..c056012 100644 --- a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/B42PatchSet.java @@ -24,7 +24,8 @@ public final class B42PatchSet implements PatchSet new IsoZombieVehiclePerformancePatch(), new IsoZombieNetworkComponentPerformancePatch(), new IsoZombieSpotChancePerformancePatch(), - new IsoGameCharacterStateMachinePerformancePatch() + new IsoGameCharacterStateMachinePerformancePatch(), + new ZombieVoronoiPerformancePatch() ); @Override diff --git a/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatch.java b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatch.java new file mode 100644 index 0000000..30e6f02 --- /dev/null +++ b/compat/b42/patches/src/main/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatch.java @@ -0,0 +1,121 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.patcher.Anchor; +import dev.overlord.zomboidforge.patcher.Hook; +import dev.overlord.zomboidforge.patcher.Patches.PerformancePatch; + +import org.objectweb.asm.Opcodes; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.FieldNode; +import org.objectweb.asm.tree.InsnList; +import org.objectweb.asm.tree.InsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; +import org.objectweb.asm.tree.VarInsnNode; + +/** + * Replaces the body of {@code ZombieVoronoi.evaluateNoise(double, double, Random, List)} with a + * call to {@code ZombieVoronoiHooks.evaluateNoise}, which returns the same values: + * + *
{@code
+ * private double evaluateNoise(
+ *    double x, double y, Random rng, List points
+ * ) {
+ *    return ZombieVoronoiHooks.evaluateNoise(
+ *       this.closestPoint,
+ *       this.seed,
+ *       this.numberPoints,
+ *       x, y, rng, points
+ *    );
+ * }
+ * }
+ * + * The world generation evaluates it 1,024 times per cell at startup; each call creates 9 + * {@code Coord}s and lets {@code ClosestSelectionType.getClosest} sort their boxed distances. + * The hook computes the distances in one pass. + */ +public final class ZombieVoronoiPerformancePatch extends PerformancePatch +{ + private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection"; + + private static final Anchor.Call ANCHOR = new Anchor.Call( + new Anchor.Method("evaluateNoise", "(DDLjava/util/Random;Ljava/util/List;)D"), + ZombieVoronoiPerformancePatch.SELECTION, "getClosest", "(DDLjava/util/List;)D" + ); + + private static final Hook HOOK = new Hook( + "dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks", "evaluateNoise", + "(L" + ZombieVoronoiPerformancePatch.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D" + ); + + public ZombieVoronoiPerformancePatch() { + super("zombie/iso/worldgen/zombie/ZombieVoronoi", ZombieVoronoiPerformancePatch.ANCHOR, ZombieVoronoiPerformancePatch.HOOK); + } + + // + + @Override + public boolean appliesTo(GameVersion version) { return version.matches("42.21"); } + + @Override + public void apply(ClassNode node) + { + MethodNode method = ZombieVoronoiPerformancePatch.ANCHOR.in().resolve(node); + + if ((method.access & Opcodes.ACC_STATIC) != 0) + throw new IllegalStateException("'" + node.name + "." + method.name + method.desc + "' is static."); + + ZombieVoronoiPerformancePatch.requireField(node, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";"); + ZombieVoronoiPerformancePatch.requireField(node, "seed", "J"); + ZombieVoronoiPerformancePatch.requireField(node, "numberPoints", "I"); + + // The local variable table and annotations refer to labels of the old body. + method.instructions.clear(); + method.tryCatchBlocks.clear(); + method.localVariables = null; + method.visibleLocalVariableAnnotations = null; + method.invisibleLocalVariableAnnotations = null; + method.instructions.add(ZombieVoronoiPerformancePatch.callHook(node.name)); + } + + /** + * {@code return hook(this.closestPoint, this.seed, this.numberPoints, x, y, rng, points);}. + * Locals: {@code this} 0, {@code x} 1-2, {@code y} 3-4, {@code rng} 5, {@code points} 6. + */ + private static InsnList callHook(String owner) + { + InsnList code = new InsnList(); + + code.add(new VarInsnNode(Opcodes.ALOAD, 0)); + code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "closestPoint", "L" + ZombieVoronoiPerformancePatch.SELECTION + ";")); + code.add(new VarInsnNode(Opcodes.ALOAD, 0)); + code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "seed", "J")); + code.add(new VarInsnNode(Opcodes.ALOAD, 0)); + code.add(new FieldInsnNode(Opcodes.GETFIELD, owner, "numberPoints", "I")); + code.add(new VarInsnNode(Opcodes.DLOAD, 1)); + code.add(new VarInsnNode(Opcodes.DLOAD, 3)); + code.add(new VarInsnNode(Opcodes.ALOAD, 5)); + code.add(new VarInsnNode(Opcodes.ALOAD, 6)); + code.add(new MethodInsnNode( + Opcodes.INVOKESTATIC, + ZombieVoronoiPerformancePatch.HOOK.owner(), + ZombieVoronoiPerformancePatch.HOOK.name(), + ZombieVoronoiPerformancePatch.HOOK.desc(), + false + )); + code.add(new InsnNode(Opcodes.DRETURN)); + + return code; + } + + private static void requireField(ClassNode node, String name, String desc) + { + for (FieldNode field : node.fields) { + if (field.name.equals(name) && field.desc.equals(desc) && (field.access & Opcodes.ACC_STATIC) == 0) return; + } + + throw new IllegalStateException("Expected the instance field '" + node.name + "." + name + " " + desc + "'."); + } +} diff --git a/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatchTest.java b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatchTest.java new file mode 100644 index 0000000..811787d --- /dev/null +++ b/compat/b42/patches/src/test/java/dev/overlord/zomboidforge/compat/b42/perf/ZombieVoronoiPerformancePatchTest.java @@ -0,0 +1,188 @@ +package dev.overlord.zomboidforge.compat.b42.perf; + +import dev.overlord.zomboidforge.api.GameVersion; +import dev.overlord.zomboidforge.compat.b42.patches.support.ClassDefiner; + +import org.junit.jupiter.api.Test; +import org.objectweb.asm.Label; +import org.objectweb.asm.MethodVisitor; +import org.objectweb.asm.tree.AbstractInsnNode; +import org.objectweb.asm.tree.ClassNode; +import org.objectweb.asm.tree.FieldInsnNode; +import org.objectweb.asm.tree.MethodInsnNode; +import org.objectweb.asm.tree.MethodNode; + +import java.util.ArrayList; +import java.util.List; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertFalse; +import static org.junit.jupiter.api.Assertions.assertNull; +import static org.junit.jupiter.api.Assertions.assertThrows; +import static org.junit.jupiter.api.Assertions.assertTrue; +import static org.objectweb.asm.Opcodes.ACC_FINAL; +import static org.objectweb.asm.Opcodes.ACC_PRIVATE; +import static org.objectweb.asm.Opcodes.ACC_PUBLIC; +import static org.objectweb.asm.Opcodes.ACC_STATIC; +import static org.objectweb.asm.Opcodes.ALOAD; +import static org.objectweb.asm.Opcodes.DLOAD; +import static org.objectweb.asm.Opcodes.DRETURN; +import static org.objectweb.asm.Opcodes.GETFIELD; +import static org.objectweb.asm.Opcodes.INVOKEINTERFACE; +import static org.objectweb.asm.Opcodes.INVOKESPECIAL; +import static org.objectweb.asm.Opcodes.INVOKESTATIC; +import static org.objectweb.asm.Opcodes.RETURN; +import static org.objectweb.asm.Opcodes.V25; + +class ZombieVoronoiPerformancePatchTest +{ + private static final String VORONOI = "zombie/iso/worldgen/zombie/ZombieVoronoi"; + private static final String SELECTION = "zombie/iso/worldgen/zombie/ClosestSelection"; + private static final String HOOKS = "dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks"; + private static final String NOISE = "(DDLjava/util/Random;Ljava/util/List;)D"; + + /** + * {@code ZombieVoronoi} with its three fields and a reduced {@code evaluateNoise}: + * + *
{@code
+     * private double evaluateNoise(double x, double y, Random rng, List points)
+     * {
+     *     long unused = this.seed;                               // a local beyond the parameters
+     *     return this.closestPoint.getClosest(x, y, points);
+     * }
+     * }
+ */ + private static ClassNode voronoi(boolean withSeed, int noiseAccess) + { + ClassNode node = new ClassNode(); + node.visit(V25, ACC_PUBLIC, ZombieVoronoiPerformancePatchTest.VORONOI, null, "java/lang/Object", null); + + if (withSeed) node.visitField(ACC_PRIVATE | ACC_FINAL, "seed", "J", null, null); + node.visitField(ACC_PRIVATE | ACC_FINAL, "numberPoints", "I", null, null); + node.visitField(ACC_PRIVATE | ACC_FINAL, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";", null, null); + + MethodVisitor init = node.visitMethod(ACC_PUBLIC, "", "()V", null, null); + init.visitVarInsn(ALOAD, 0); + init.visitMethodInsn(INVOKESPECIAL, "java/lang/Object", "", "()V", false); + init.visitInsn(RETURN); + init.visitMaxs(0, 0); + + MethodVisitor noise = node.visitMethod(noiseAccess, "evaluateNoise", ZombieVoronoiPerformancePatchTest.NOISE, null, null); + Label start = new Label(); + Label end = new Label(); + noise.visitLabel(start); + noise.visitVarInsn(ALOAD, 0); + noise.visitFieldInsn(GETFIELD, ZombieVoronoiPerformancePatchTest.VORONOI, "closestPoint", "L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";"); + noise.visitVarInsn(DLOAD, 1); + noise.visitVarInsn(DLOAD, 3); + noise.visitVarInsn(ALOAD, 6); + noise.visitMethodInsn(INVOKEINTERFACE, ZombieVoronoiPerformancePatchTest.SELECTION, "getClosest", "(DDLjava/util/List;)D", true); + noise.visitInsn(DRETURN); + noise.visitLabel(end); + noise.visitLocalVariable("unused", "J", null, start, end, 7); + noise.visitMaxs(0, 0); + + return node; + } + + private static ClassNode voronoi() + { + return ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE); + } + + private static MethodNode evaluateNoise(ClassNode node) + { + return node.methods.stream().filter(method -> method.name.equals("evaluateNoise")).findFirst().orElseThrow(); + } + + /** The real instructions: no labels, line numbers, or frames. */ + private static List instructions(MethodNode method) + { + List instructions = new ArrayList<>(); + + for (AbstractInsnNode instruction : method.instructions) { + if (instruction.getOpcode() != -1) instructions.add(instruction); + } + + return instructions; + } + + @Test + void anchorMatchesTheTarget() + { + new ZombieVoronoiPerformancePatch().anchor().verify(ZombieVoronoiPerformancePatchTest.voronoi()); + } + + @Test + void replacesTheBodyWithTheHookCall() + { + ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(); + new ZombieVoronoiPerformancePatch().apply(node); + + List instructions = ZombieVoronoiPerformancePatchTest.instructions(ZombieVoronoiPerformancePatchTest.evaluateNoise(node)); + + assertEquals( + List.of(ALOAD, GETFIELD, ALOAD, GETFIELD, ALOAD, GETFIELD, DLOAD, DLOAD, ALOAD, ALOAD, INVOKESTATIC, DRETURN), + instructions.stream().map(AbstractInsnNode::getOpcode).toList() + ); + assertEquals( + List.of("closestPoint", "seed", "numberPoints"), + instructions.stream().filter(FieldInsnNode.class::isInstance).map(field -> ((FieldInsnNode) field).name).toList() + ); + + MethodInsnNode call = (MethodInsnNode) instructions.get(10); + assertEquals(ZombieVoronoiPerformancePatchTest.HOOKS, call.owner); + assertEquals("evaluateNoise", call.name); + assertEquals("(L" + ZombieVoronoiPerformancePatchTest.SELECTION + ";JIDDLjava/util/Random;Ljava/util/List;)D", call.desc); + assertFalse(call.itf); + } + + @Test + void dropsTheLocalVariablesOfTheOldBody() + { + ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(); + new ZombieVoronoiPerformancePatch().apply(node); + + assertNull(ZombieVoronoiPerformancePatchTest.evaluateNoise(node).localVariables); + } + + @Test + void patchedClassIsValid() throws ClassNotFoundException + { + ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(); + new ZombieVoronoiPerformancePatch().apply(node); + + // Initializing links the class, which runs the bytecode verifier on the new body. + ClassDefiner definer = new ClassDefiner(); + definer.define(node); + Class.forName(node.name.replace('/', '.'), true, definer); + } + + @Test + void failsWithoutTheSeedField() + { + ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(false, ACC_PRIVATE); + + IllegalStateException e = assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node)); + assertTrue(e.getMessage().contains("'" + ZombieVoronoiPerformancePatchTest.VORONOI + ".seed J'"), e.getMessage()); + } + + @Test + void failsWhenTheMethodIsStatic() + { + ClassNode node = ZombieVoronoiPerformancePatchTest.voronoi(true, ACC_PRIVATE | ACC_STATIC); + + assertThrows(IllegalStateException.class, () -> new ZombieVoronoiPerformancePatch().apply(node)); + } + + @Test + void appliesOnlyToVerifiedVersions() + { + ZombieVoronoiPerformancePatch patch = new ZombieVoronoiPerformancePatch(); + + assertTrue(patch.appliesTo(GameVersion.parse("42.21.0"))); + assertTrue(patch.appliesTo(GameVersion.parse("42.21.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.20.3"))); + assertFalse(patch.appliesTo(GameVersion.parse("42.22.0"))); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks.java new file mode 100644 index 0000000..bedadae --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/hooks/ZombieVoronoiHooks.java @@ -0,0 +1,27 @@ +package dev.overlord.zomboidforge.compat.b42.hooks; + +import dev.overlord.zomboidforge.compat.b42.util.VoronoiNoise; + +import java.util.List; +import java.util.Random; + +import zombie.iso.worldgen.zombie.ClosestSelection; +import zombie.iso.worldgen.zombie.Coord; + +/** Hooks called by patched {@code zombie.iso.worldgen.zombie.ZombieVoronoi} code. */ +public final class ZombieVoronoiHooks +{ + private ZombieVoronoiHooks() {} + + /** + * Replaces the body of {@code ZombieVoronoi.evaluateNoise(x, y, rng, points)}, which passes + * the voronoi's fields {@code closestPoint}, {@code seed} and {@code numberPoints}. Returns + * what the vanilla body returns ({@link VoronoiNoise}). + */ + public static double evaluateNoise( + ClosestSelection selection, long seed, int numberPoints, + double x, double y, Random rng, List points + ) { + return VoronoiNoise.evaluate(selection, seed, numberPoints, x, y, rng, points); + } +} diff --git a/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoise.java b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoise.java new file mode 100644 index 0000000..5e3211b --- /dev/null +++ b/compat/b42/runtime/src/main/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoise.java @@ -0,0 +1,121 @@ +package dev.overlord.zomboidforge.compat.b42.util; + +import java.util.List; +import java.util.Objects; +import java.util.Random; + +import zombie.iso.worldgen.zombie.ClosestSelection; +import zombie.iso.worldgen.zombie.ClosestSelectionType; +import zombie.iso.worldgen.zombie.Coord; +import zombie.iso.worldgen.zombie.HashUtil; + +/** + * The value of {@code ZombieVoronoi.evaluateNoise} without its {@link Coord} list for the + * {@link ClosestSelectionType}s. + * + *

Vanilla clears {@code points}, adds {@code numberPoints} {@link Coord}s for each of the 9 + * sectors around {@code (x, y)}, reseeding {@code rng} per sector, and returns + * {@code closestPoint.getClosest(x, y, points)}. The three {@link ClosestSelectionType}s map the + * points to boxed squared distances, sort them, and return the smallest, the second smallest, + * or the second minus the smallest. + * + *

Here the same random numbers in the same order feed the same distance expression, and one + * pass keeps the two smallest distances in the order of {@code Double.compare}, which + * {@code sorted()} uses. The results are identical without the {@code Coord}s, the boxing and + * the sort. {@code points} stays untouched: the only caller, {@code evaluateCellNoise}, passes a + * list it does not read. Any other selection gets the filled list as in vanilla. + */ +public final class VoronoiNoise +{ + private VoronoiNoise() {} + + public static double evaluate( + ClosestSelection selection, long seed, int numberPoints, + double x, double y, Random rng, List points + ) { + int rank = VoronoiNoise.rank(selection); + if (rank < 0) return VoronoiNoise.evaluateWithPoints(selection, seed, numberPoints, x, y, rng, points); + + int sectorX = (int) Math.floor(x); + int sectorY = (int) Math.floor(y); + double smallest = 0.0; + double second = 0.0; + int count = 0; + + for (int offsetX = -1; offsetX <= 1; ++offsetX) + { + int pointSectorX = sectorX + offsetX; + + for (int offsetY = -1; offsetY <= 1; ++offsetY) + { + int pointSectorY = sectorY + offsetY; + rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY)); + + for (int i = 0; i < numberPoints; ++i) + { + double pointX = rng.nextDouble() + (double) pointSectorX; + double pointY = rng.nextDouble() + (double) pointSectorY; + double distance = (x - pointX) * (x - pointX) + (y - pointY) * (y - pointY); + + if (count == 0) smallest = distance; + else if (Double.compare(distance, smallest) < 0) + { + second = smallest; + smallest = distance; + } + else if (count == 1 || Double.compare(distance, second) < 0) second = distance; + + count++; + } + } + } + + // Vanilla reads index 0, or index 1 first, of the sorted list: same exception when it is too short. + Objects.checkIndex(rank == 0 ? 0 : 1, count); + + return switch (rank) + { + case 0 -> smallest; + case 1 -> second; + default -> second - smallest; + }; + } + + /** 0 for {@code FIRST}, 1 for {@code SECOND}, 2 for {@code SECOND_MINUS_FIRST}, -1 for any other selection. */ + private static int rank(ClosestSelection selection) + { + return switch (selection) { + case ClosestSelectionType.FIRST -> 0; + case ClosestSelectionType.SECOND -> 1; + case ClosestSelectionType.SECOND_MINUS_FIRST -> 2; + default -> -1; + }; + } + + /** The vanilla body. */ + private static double evaluateWithPoints( + ClosestSelection selection, long seed, int numberPoints, + double x, double y, Random rng, List points + ) { + points.clear(); + int sectorX = (int) Math.floor(x); + int sectorY = (int) Math.floor(y); + + for (int offsetX = -1; offsetX <= 1; ++offsetX) + { + int pointSectorX = sectorX + offsetX; + + for (int offsetY = -1; offsetY <= 1; ++offsetY) + { + int pointSectorY = sectorY + offsetY; + rng.setSeed(HashUtil.hash2D(seed, pointSectorX, pointSectorY)); + + for (int i = 0; i < numberPoints; ++i) { + points.add(new Coord(rng.nextDouble() + (double) pointSectorX, rng.nextDouble() + (double) pointSectorY)); + } + } + } + + return selection.getClosest(x, y, points); + } +} diff --git a/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoiseTest.java b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoiseTest.java new file mode 100644 index 0000000..6ed44f8 --- /dev/null +++ b/compat/b42/runtime/src/test/java/dev/overlord/zomboidforge/compat/b42/util/VoronoiNoiseTest.java @@ -0,0 +1,117 @@ +package dev.overlord.zomboidforge.compat.b42.util; + +import org.junit.jupiter.api.Test; + +import zombie.iso.worldgen.zombie.ClosestSelection; +import zombie.iso.worldgen.zombie.ClosestSelectionType; +import zombie.iso.worldgen.zombie.Coord; +import zombie.iso.worldgen.zombie.ZombieVoronoi; + +import java.lang.reflect.InvocationTargetException; +import java.lang.reflect.Method; +import java.util.ArrayList; +import java.util.List; +import java.util.Random; + +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.junit.jupiter.api.Assertions.assertInstanceOf; +import static org.junit.jupiter.api.Assertions.assertThrows; + +/** Compares {@link VoronoiNoise} with the vanilla {@code ZombieVoronoi.evaluateNoise} of the game jar. */ +class VoronoiNoiseTest +{ + private static final long[] SEEDS = { 0L, 12345L, -987654321L, Long.MAX_VALUE }; + + private static double vanilla(ZombieVoronoi voronoi, double x, double y, List points) throws ReflectiveOperationException + { + Method method = ZombieVoronoi.class.getDeclaredMethod("evaluateNoise", double.class, double.class, Random.class, List.class); + method.setAccessible(true); + + return (double) method.invoke(voronoi, x, y, new Random(), points); + } + + /** Random coordinates, and coordinates on and next to sector borders, including negative ones. */ + private static List coordinates() + { + List coordinates = new ArrayList<>(); + Random random = new Random(42L); + + for (int i = 0; i < 500; i++) coordinates.add(new double[] { random.nextDouble() * 2000.0 - 1000.0, random.nextDouble() * 2000.0 - 1000.0 }); + + for (double border : new double[] { -2.0, -1.0, 0.0, 1.0, 37.0 }) + { + coordinates.add(new double[] { border, border }); + coordinates.add(new double[] { Math.nextDown(border), Math.nextUp(border) }); + coordinates.add(new double[] { -0.0, border }); + } + + return coordinates; + } + + @Test + void returnsTheVanillaValueForEveryClosestSelectionType() throws ReflectiveOperationException + { + int compared = 0; + + for (ClosestSelectionType type : ClosestSelectionType.values()) + { + for (int numberPoints = 1; numberPoints <= 3; numberPoints++) + { + for (long seed : VoronoiNoiseTest.SEEDS) + { + ZombieVoronoi voronoi = new ZombieVoronoi(seed, numberPoints, type, 1.0, 0.0); + + for (double[] point : VoronoiNoiseTest.coordinates()) + { + double expected = VoronoiNoiseTest.vanilla(voronoi, point[0], point[1], new ArrayList<>()); + double actual = VoronoiNoise.evaluate(type, seed, numberPoints, point[0], point[1], new Random(), new ArrayList<>()); + + assertEquals( + Double.doubleToRawLongBits(expected), Double.doubleToRawLongBits(actual), + () -> type + ", " + seed + ", " + point[0] + ", " + point[1] + ); + compared++; + } + } + } + } + + assertEquals(3 * 3 * VoronoiNoiseTest.SEEDS.length * VoronoiNoiseTest.coordinates().size(), compared); + } + + @Test + void otherSelectionsGetTheVanillaPoints() throws ReflectiveOperationException + { + // Sums every coordinate, so any difference in the points shows in the result. + ClosestSelection sum = (x, y, points) -> { + double total = 0.0; + for (Object point : points) total += ((Coord) point).x() * 3.0 + ((Coord) point).y(); + return total; + }; + + ZombieVoronoi voronoi = new ZombieVoronoi(777L, 2, sum, 1.0, 0.0); + List vanillaPoints = new ArrayList<>(); + List noisePoints = new ArrayList<>(List.of(new Coord(9.0, 9.0))); + double expected = VoronoiNoiseTest.vanilla(voronoi, 12.5, -3.25, vanillaPoints); + double actual = VoronoiNoise.evaluate(sum, 777L, 2, 12.5, -3.25, new Random(), noisePoints); + + assertEquals(expected, actual); + assertEquals(vanillaPoints, noisePoints); + assertEquals(18, noisePoints.size()); + } + + @Test + void withoutPointsThrowsLikeVanilla() + { + for (ClosestSelectionType type : ClosestSelectionType.values()) + { + ZombieVoronoi voronoi = new ZombieVoronoi(1L, 0, type, 1.0, 0.0); + + InvocationTargetException vanilla = assertThrows(InvocationTargetException.class, () -> VoronoiNoiseTest.vanilla(voronoi, 1.0, 1.0, new ArrayList<>())); + IndexOutOfBoundsException noise = assertThrows(IndexOutOfBoundsException.class, () -> VoronoiNoise.evaluate(type, 1L, 0, 1.0, 1.0, new Random(), new ArrayList<>())); + + assertInstanceOf(IndexOutOfBoundsException.class, vanilla.getCause()); + assertEquals(vanilla.getCause().getMessage(), noise.getMessage()); + } + } +}