From 1ce0a19abbb94eaed5f27c1772c620eede552d79 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 11:36:13 +0200 Subject: [PATCH] Give stages WorldRandom, a SplitMix64 generator whose every method IrisApi defines java.util.Random fixes only some of its methods; the ranged RandomGenerator defaults module authors reach for are left to the JDK, so an update could change existing worlds. WorldRandom does not implement RandomGenerator and exposes a curated set (ints, longs, ranges, booleans, floats, doubles, gaussian, chance) with Lemire bounds and the polar gaussian on StrictMath. StageContext, ObjectGenerationContext and BlockPalette now use it. StageRandom becomes StageStreams; the seed derivation is unchanged. Every method is pinned to values from an independent Python reference in src/test/reference. --- .gitignore | 1 + .../java/com/volmit/block/BlockPalette.java | 6 +- .../java/com/volmit/host/ChunkInvocation.java | 4 +- .../java/com/volmit/host/ChunkRunner.java | 2 +- .../java/com/volmit/host/ExecutableStage.java | 2 +- .../java/com/volmit/host/GraphResolver.java | 2 +- .../com/volmit/host/PlacementInvocation.java | 4 +- .../java/com/volmit/host/PlacementRunner.java | 2 +- .../java/com/volmit/host/StageInvocation.java | 10 +- .../{StageRandom.java => StageStreams.java} | 27 +-- .../object/ObjectGenerationContext.java | 4 +- .../java/com/volmit/random/WorldRandom.java | 204 ++++++++++++++++ .../java/com/volmit/stage/StageContext.java | 4 +- .../example/PlacementLifecyclePortTest.java | 4 +- ...eRandomTest.java => StageStreamsTest.java} | 22 +- .../com/volmit/random/WorldRandomTest.java | 185 +++++++++++++++ src/test/reference/world_random.py | 218 ++++++++++++++++++ 17 files changed, 653 insertions(+), 48 deletions(-) rename src/main/java/com/volmit/host/{StageRandom.java => StageStreams.java} (63%) create mode 100644 src/main/java/com/volmit/random/WorldRandom.java rename src/test/java/com/volmit/host/{StageRandomTest.java => StageStreamsTest.java} (89%) create mode 100644 src/test/java/com/volmit/random/WorldRandomTest.java create mode 100644 src/test/reference/world_random.py diff --git a/.gitignore b/.gitignore index e81a89f7a..c346668cb 100644 --- a/.gitignore +++ b/.gitignore @@ -2,3 +2,4 @@ build/ .idea/ *.iml +__pycache__/ diff --git a/src/main/java/com/volmit/block/BlockPalette.java b/src/main/java/com/volmit/block/BlockPalette.java index e21c1e159..504c0c1e0 100644 --- a/src/main/java/com/volmit/block/BlockPalette.java +++ b/src/main/java/com/volmit/block/BlockPalette.java @@ -1,11 +1,11 @@ package com.volmit.block; -import java.util.random.RandomGenerator; +import com.volmit.random.WorldRandom; -/** Resolved, immutable palette. Coordinates are world blocks; selection uses only this RNG. +/** Resolved, immutable palette. Coordinates are world blocks; selection uses only the given stream. * An empty/unresolvable palette is a pack-load error. Implementations must support concurrent calls. */ @FunctionalInterface public interface BlockPalette { - BlockState select(int worldX, int worldY, int worldZ, RandomGenerator random); + BlockState select(int worldX, int worldY, int worldZ, WorldRandom random); } diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index ca5329b34..e176ae10c 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -4,12 +4,12 @@ import com.volmit.config.FeatureSettings; import com.volmit.generation.GenerationContext; import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; +import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; import java.util.Objects; -import java.util.random.RandomGenerator; /** The context every stage of one chunk invocation receives. */ final class ChunkInvocation implements ChunkStageContext { @@ -76,7 +76,7 @@ final class ChunkInvocation implements ChunkStageContext { } @Override - public RandomGenerator random() { + public WorldRandom random() { return stages.random(); } } diff --git a/src/main/java/com/volmit/host/ChunkRunner.java b/src/main/java/com/volmit/host/ChunkRunner.java index f9695aea1..5905af7a9 100644 --- a/src/main/java/com/volmit/host/ChunkRunner.java +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -19,7 +19,7 @@ public final class ChunkRunner { } /** Runs one chunk. The host derives {@code invocationSeed} from the world seed and the chunk - * position; each stage draws from its own stream of that seed ({@link StageRandom}). + * position; each stage draws from its own stream of that seed ({@link StageStreams}). */ public void generate(GenerationContext inputs, long invocationSeed, ConfiguredSettings settings) { var chunk = new ChunkInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); diff --git a/src/main/java/com/volmit/host/ExecutableStage.java b/src/main/java/com/volmit/host/ExecutableStage.java index e270c7a98..ce04be771 100644 --- a/src/main/java/com/volmit/host/ExecutableStage.java +++ b/src/main/java/com/volmit/host/ExecutableStage.java @@ -5,7 +5,7 @@ import com.volmit.stage.Stage; /** Execution data of one resolved stage. Indices are positions in the resolved order. * readableStages/readablePositions are the transitive requirements whose outputs it may read. * settingsSlot indexes the graph's distinct settings types, or is NO_SETTINGS. idHash keys the - * stage's random stream ({@link StageRandom}), computed once per pack load. + * stage's random stream ({@link StageStreams}), computed once per pack load. */ record ExecutableStage( Stage stage, diff --git a/src/main/java/com/volmit/host/GraphResolver.java b/src/main/java/com/volmit/host/GraphResolver.java index 88912d402..c3d5d36b7 100644 --- a/src/main/java/com/volmit/host/GraphResolver.java +++ b/src/main/java/com/volmit/host/GraphResolver.java @@ -225,7 +225,7 @@ final class GraphResolver { .toArray(Stage[]::new), readable[index].stream().toArray(), settingsSlot(declaration, settingsTypes), - StageRandom.idHash(declaration.stage().id())); + StageStreams.idHash(declaration.stage().id())); stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(), incomingEdges(node, position), absentSoftTargets.get(node))); } diff --git a/src/main/java/com/volmit/host/PlacementInvocation.java b/src/main/java/com/volmit/host/PlacementInvocation.java index 325e3bf8c..2bc7984fb 100644 --- a/src/main/java/com/volmit/host/PlacementInvocation.java +++ b/src/main/java/com/volmit/host/PlacementInvocation.java @@ -6,13 +6,13 @@ import com.volmit.object.ObjectTransformer; import com.volmit.placement.PlacementAccess; import com.volmit.placement.PlacementContext; import com.volmit.placement.PlacementRequest; +import com.volmit.random.WorldRandom; import com.volmit.resource.PackResources; import com.volmit.stage.BlockStageContext; import com.volmit.stage.Stage; import com.volmit.world.BlockView; import com.volmit.world.TerrainSampler; import java.util.Objects; -import java.util.random.RandomGenerator; /** The context every stage of one placement attempt receives. Block accessors work only while * a block pass is running. @@ -117,7 +117,7 @@ final class PlacementInvocation implements BlockStageContext { } @Override - public RandomGenerator random() { + public WorldRandom random() { return stages.random(); } diff --git a/src/main/java/com/volmit/host/PlacementRunner.java b/src/main/java/com/volmit/host/PlacementRunner.java index a17b2c102..6e5ad79d2 100644 --- a/src/main/java/com/volmit/host/PlacementRunner.java +++ b/src/main/java/com/volmit/host/PlacementRunner.java @@ -24,7 +24,7 @@ public final class PlacementRunner { /** Takes ownership of a fresh edit and closes it on success, rejection or exception. * The host prepares the edit area, the read-only inputs and the settings configured for this * placement, and derives {@code invocationSeed} from the world seed and the placement's stable - * identity. Each stage draws from its own stream of that seed ({@link StageRandom}). Stages never + * identity. Each stage draws from its own stream of that seed ({@link StageStreams}). Stages never * receive commit/close rights. */ public PlacementOutcome place( diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java index 35b829162..862d79ad1 100644 --- a/src/main/java/com/volmit/host/StageInvocation.java +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -1,11 +1,11 @@ package com.volmit.host; import com.volmit.IrisFeature; +import com.volmit.random.WorldRandom; import com.volmit.stage.BlockStageContext; import com.volmit.stage.Stage; import java.util.Arrays; import java.util.Objects; -import java.util.random.RandomGenerator; import java.util.stream.IntStream; /** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage @@ -24,7 +24,7 @@ final class StageInvocation { private final boolean[] active; private final Object[] outputs; private final long invocationSeed; - private final RandomGenerator[] streams; + private final WorldRandom[] streams; private int current = NO_STAGE; StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) { @@ -34,7 +34,7 @@ final class StageInvocation { outputs = new Object[graph.size()]; Arrays.fill(outputs, PENDING); this.invocationSeed = invocationSeed; - streams = new RandomGenerator[graph.size()]; + streams = new WorldRandom[graph.size()]; } boolean isActive(int position) { @@ -97,12 +97,12 @@ final class StageInvocation { } /** The running stage's own stream. A block stage keeps one stream across every block of its pass. */ - RandomGenerator random() { + WorldRandom random() { if (current == NO_STAGE) { throw new IllegalStateException("A stage's random stream is only available while the stage runs"); } if (streams[current] == null) { - streams[current] = StageRandom.stream(invocationSeed, graph.executable(current).idHash()); + streams[current] = StageStreams.stream(invocationSeed, graph.executable(current).idHash()); } return streams[current]; } diff --git a/src/main/java/com/volmit/host/StageRandom.java b/src/main/java/com/volmit/host/StageStreams.java similarity index 63% rename from src/main/java/com/volmit/host/StageRandom.java rename to src/main/java/com/volmit/host/StageStreams.java index 9f8cb2baa..a078d4c6b 100644 --- a/src/main/java/com/volmit/host/StageRandom.java +++ b/src/main/java/com/volmit/host/StageStreams.java @@ -1,9 +1,8 @@ package com.volmit.host; +import com.volmit.random.WorldRandom; import com.volmit.resource.ResourceId; import java.nio.charset.StandardCharsets; -import java.util.Random; -import java.util.random.RandomGenerator; /** Derives the random stream of one stage in one invocation from the invocation seed and the * stage id alone. A stage's draws therefore never depend on which other modules or stages are @@ -14,33 +13,29 @@ import java.util.random.RandomGenerator; *
  • {@code idHash} = 64-bit FNV-1a of the UTF-8 bytes of the stage id ({@code namespace:path});
  • *
  • {@code streamSeed} = {@code mix(mix(invocationSeed) ^ idHash)}, where {@code mix} is the * SplitMix64 finalizer (Stafford variant 13);
  • - *
  • the stream is {@code new java.util.Random(streamSeed)}.
  • + *
  • the stream is {@code new WorldRandom(streamSeed)}, whose every method IrisApi defines.
  • * * {@code mix} is a bijection, so one stage gets a different stream for every invocation seed, and * within one invocation stages with different id hashes get different streams. - * - *

    {@link java.util.Random} is the only JDK generator whose algorithm the Java SE specification - * fixes for {@code nextInt()}, {@code nextInt(bound)}, {@code nextLong()}, {@code nextBoolean()}, - * {@code nextFloat()}, {@code nextDouble()}, {@code nextGaussian()} and {@code nextBytes}. - * {@code SplittableRandom} and the named {@code RandomGeneratorFactory} algorithms promise identical - * sequences only within one program. The ranged methods {@code Random} inherits from - * {@link RandomGenerator}, such as {@code nextInt(origin, bound)} or {@code nextDouble(bound)}, and - * {@code nextExponential()} are not fixed by the specification. */ -public final class StageRandom { +public final class StageStreams { private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L; private static final long FNV_PRIME = 0x100000001b3L; private static final int BYTE_MASK = 0xff; - private StageRandom() {} + private StageStreams() {} /** The stream {@code stageId} draws from in the invocation with {@code invocationSeed}. */ - public static RandomGenerator stream(long invocationSeed, ResourceId stageId) { + public static WorldRandom stream(long invocationSeed, ResourceId stageId) { return stream(invocationSeed, idHash(stageId)); } - static RandomGenerator stream(long invocationSeed, long idHash) { - return new Random(mix(mix(invocationSeed) ^ idHash)); + static WorldRandom stream(long invocationSeed, long idHash) { + return new WorldRandom(streamSeed(invocationSeed, idHash)); + } + + static long streamSeed(long invocationSeed, long idHash) { + return mix(mix(invocationSeed) ^ idHash); } /** 64-bit FNV-1a over the UTF-8 bytes of the id. */ diff --git a/src/main/java/com/volmit/object/ObjectGenerationContext.java b/src/main/java/com/volmit/object/ObjectGenerationContext.java index d5515081e..e54adc0b5 100644 --- a/src/main/java/com/volmit/object/ObjectGenerationContext.java +++ b/src/main/java/com/volmit/object/ObjectGenerationContext.java @@ -1,12 +1,12 @@ package com.volmit.object; import com.volmit.generation.InvocationContext; -import java.util.random.RandomGenerator; +import com.volmit.random.WorldRandom; /** Geometry-only invocation. The host chooses the variant seed and enforces size limits. * Placement and terrain adaptation happen later; generators return reusable local geometry. */ public interface ObjectGenerationContext extends InvocationContext { /** This generation's stream, seeded from the variant seed the host chose. Do not retain it. */ - RandomGenerator random(); + WorldRandom random(); } diff --git a/src/main/java/com/volmit/random/WorldRandom.java b/src/main/java/com/volmit/random/WorldRandom.java new file mode 100644 index 000000000..0fd1d090c --- /dev/null +++ b/src/main/java/com/volmit/random/WorldRandom.java @@ -0,0 +1,204 @@ +package com.volmit.random; + +/** A random stream whose every value is defined here, so the same seed gives the same draws on + * every machine and every JDK. World generation draws from it: stages through + * {@link com.volmit.stage.StageContext#random()}, object generators through + * {@link com.volmit.object.ObjectGenerationContext#random()}. + * + *

    It deliberately does not implement {@link java.util.random.RandomGenerator}: that interface's + * default methods, and any a later JDK adds, use algorithms the JDK may change, which would change + * existing worlds. Only the methods below exist, and each is specified exactly. + * + *

    Algorithm. The state is one {@code long}, initially the seed. {@link #nextLong()} is + * SplitMix64 (Steele, Lea and Flood, 2014): add {@code 0x9e3779b97f4a7c15} to the state, then return + * {@code mix(state)}, where {@code mix} is the finalizer + * {@code z = (z ^ (z >>> 30)) * 0xbf58476d1ce4e5b9; z = (z ^ (z >>> 27)) * 0x94d049bb133111eb; z ^ (z >>> 31)}. + * Every other method is defined on {@code nextLong()} values: + *

    + * Methods without rejection draw exactly one value. {@code nextInt(0, n)} equals {@code nextInt(n)} + * and {@code nextLong(0, n)} equals {@code nextLong(n)}. + * + *

    Not thread-safe. One stage uses its stream within one invocation; do not share or retain it. + */ +public final class WorldRandom { + private static final long GOLDEN_GAMMA = 0x9e3779b97f4a7c15L; + private static final int INT_BITS = 32; + private static final long UNSIGNED_INT_MASK = 0xffff_ffffL; + private static final long INT_RANGE = 1L << INT_BITS; + private static final int FLOAT_SHIFT = Long.SIZE - 24; + private static final float FLOAT_UNIT = 0x1.0p-24f; + private static final int DOUBLE_SHIFT = Long.SIZE - 53; + private static final double DOUBLE_UNIT = 0x1.0p-53; + + private long state; + + public WorldRandom(long seed) { + state = seed; + } + + /** A uniformly distributed {@code long}: the next SplitMix64 output. */ + public long nextLong() { + state += GOLDEN_GAMMA; + return mix(state); + } + + /** A uniformly distributed {@code long} in {@code [0, bound)}. Throws if {@code bound <= 0}. */ + public long nextLong(long bound) { + if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound); + return boundedLong(bound); + } + + /** A uniformly distributed {@code long} in {@code [origin, bound)}, for any {@code origin < bound}, + * including ranges wider than {@code Long.MAX_VALUE}. Throws if {@code origin >= bound}. + */ + public long nextLong(long origin, long bound) { + if (origin >= bound) throw invalidRange(origin, bound); + return origin + boundedLong(bound - origin); + } + + /** A uniformly distributed {@code int}: the high 32 bits of {@link #nextLong()}. */ + public int nextInt() { + return (int) (nextLong() >>> INT_BITS); + } + + /** A uniformly distributed {@code int} in {@code [0, bound)}. Throws if {@code bound <= 0}. */ + public int nextInt(int bound) { + if (bound <= 0) throw new IllegalArgumentException("bound must be positive: " + bound); + return (int) boundedInt(bound); + } + + /** A uniformly distributed {@code int} in {@code [origin, bound)}, for any {@code origin < bound}, + * including ranges wider than {@code Integer.MAX_VALUE}. Throws if {@code origin >= bound}. + */ + public int nextInt(int origin, int bound) { + if (origin >= bound) throw invalidRange(origin, bound); + return (int) (origin + boundedInt((long) bound - origin)); + } + + /** {@code true} or {@code false} with equal probability: whether {@link #nextLong()} is negative. */ + public boolean nextBoolean() { + return nextLong() < 0; + } + + /** A uniformly distributed {@code float} in {@code [0, 1)}, a multiple of 2-24. */ + public float nextFloat() { + return (nextLong() >>> FLOAT_SHIFT) * FLOAT_UNIT; + } + + /** A uniformly distributed {@code double} in {@code [0, 1)}, a multiple of 2-53. */ + public double nextDouble() { + return (nextLong() >>> DOUBLE_SHIFT) * DOUBLE_UNIT; + } + + /** A {@code double} in {@code [0, bound)}: {@code nextDouble() * bound}, never {@code bound} itself. + * Throws unless {@code bound} is positive and finite. + */ + public double nextDouble(double bound) { + if (!(bound > 0 && bound < Double.POSITIVE_INFINITY)) { + throw new IllegalArgumentException("bound must be positive and finite: " + bound); + } + return belowBound(nextDouble() * bound, bound); + } + + /** A {@code double} in {@code [origin, bound)}, never {@code bound} itself: + * {@code origin + nextDouble() * (bound - origin)}. When {@code bound - origin} exceeds the largest + * double, the range is halved first: {@code 2 * (origin / 2 + nextDouble() * (bound / 2 - origin / 2))}. + * Throws unless both are finite and {@code origin < bound}. + */ + public double nextDouble(double origin, double bound) { + if (!(origin < bound && Double.isFinite(origin) && Double.isFinite(bound))) { + throw new IllegalArgumentException("origin and bound must be finite with origin < bound: [" + origin + ", " + bound + ")"); + } + double unit = nextDouble(); + double width = bound - origin; + double value = Double.isFinite(width) ? origin + unit * width : 2 * (origin / 2 + unit * (bound / 2 - origin / 2)); + return belowBound(value, bound); + } + + /** A normally distributed {@code double} with mean 0 and standard deviation 1, by Marsaglia's polar + * method: draw {@code u = 2 * nextDouble() - 1} and {@code v = 2 * nextDouble() - 1} until + * {@code s = u * u + v * v} is in {@code (0, 1)}, then return + * {@code u * StrictMath.sqrt(-2 * StrictMath.log(s) / s)}. The second value of the pair is discarded. + */ + public double nextGaussian() { + double u; + double s; + do { + u = 2 * nextDouble() - 1; + double v = 2 * nextDouble() - 1; + s = u * u + v * v; + } while (s >= 1 || s == 0); + return u * StrictMath.sqrt(-2 * StrictMath.log(s) / s); + } + + /** Whether an event of the given probability happens: {@code nextDouble() < probability}. Always + * draws one value, so {@code chance(0)} is never and {@code chance(1)} always true. Throws unless + * {@code probability} is in {@code [0, 1]}. + */ + public boolean chance(double probability) { + if (!(probability >= 0 && probability <= 1)) { + throw new IllegalArgumentException("probability must be in [0, 1]: " + probability); + } + return nextDouble() < probability; + } + + /** Lemire's method for {@code range} in {@code [1, 2^32]}: high half of a 32-by-32-bit product. */ + private long boundedInt(long range) { + long product = (nextLong() >>> INT_BITS) * range; + long low = product & UNSIGNED_INT_MASK; + if (low < range) { + long threshold = (INT_RANGE - range) % range; + while (low < threshold) { + product = (nextLong() >>> INT_BITS) * range; + low = product & UNSIGNED_INT_MASK; + } + } + return product >>> INT_BITS; + } + + /** Lemire's method for {@code range} in {@code [1, 2^64)}, read as unsigned: high half of a + * 64-by-64-bit product. + */ + private long boundedLong(long range) { + long value = nextLong(); + long low = value * range; + if (Long.compareUnsigned(low, range) < 0) { + long threshold = Long.remainderUnsigned(-range, range); + while (Long.compareUnsigned(low, threshold) < 0) { + value = nextLong(); + low = value * range; + } + } + return Math.unsignedMultiplyHigh(value, range); + } + + private static double belowBound(double value, double bound) { + return value < bound ? value : Math.nextDown(bound); + } + + private static IllegalArgumentException invalidRange(long origin, long bound) { + return new IllegalArgumentException("origin must be below bound: [" + origin + ", " + bound + ")"); + } + + private static long mix(long value) { + value = (value ^ (value >>> 30)) * 0xbf58476d1ce4e5b9L; + value = (value ^ (value >>> 27)) * 0x94d049bb133111ebL; + return value ^ (value >>> 31); + } +} diff --git a/src/main/java/com/volmit/stage/StageContext.java b/src/main/java/com/volmit/stage/StageContext.java index 13fd9469d..dfc8cf470 100644 --- a/src/main/java/com/volmit/stage/StageContext.java +++ b/src/main/java/com/volmit/stage/StageContext.java @@ -1,6 +1,6 @@ package com.volmit.stage; -import java.util.random.RandomGenerator; +import com.volmit.random.WorldRandom; /** Per-invocation view handed to one stage body. Do not retain it after the body returns. */ public interface StageContext { @@ -9,7 +9,7 @@ public interface StageContext { * how much they draw, never changes what this stage draws. A block stage has one stream per * placement, drawn across the blocks of its pass in block order. Do not retain it. */ - RandomGenerator random(); + WorldRandom random(); /** The output the given stage produced in this invocation. Only stages the current stage * transitively requires are readable; anything else throws IllegalStateException, as does diff --git a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java index e2680a5c7..813b85b3d 100644 --- a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java +++ b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java @@ -10,7 +10,7 @@ import com.volmit.host.LoadedModules; import com.volmit.host.PlacementRunner; import com.volmit.host.ResolvedGraph; import com.volmit.host.StageGraphBuilder; -import com.volmit.host.StageRandom; +import com.volmit.host.StageStreams; import com.volmit.mantle.BlockBox; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; @@ -120,7 +120,7 @@ class PlacementLifecyclePortTest { * is the first draw of the transforms stage's own stream. */ private static BlockPosition placed(int x, int y, int z) { - var transforms = new Transforms(StageRandom.stream(TestContexts.SEED, PrepareModule.TRANSFORMS.id()).nextInt(4)); + var transforms = new Transforms(StageStreams.stream(TestContexts.SEED, PrepareModule.TRANSFORMS.id()).nextInt(4)); var rotated = transforms.rotate(new BlockPosition(x, y, z), new BlockPosition(0, 0, 0)); return rotated.add(SURFACE_ANCHOR); } diff --git a/src/test/java/com/volmit/host/StageRandomTest.java b/src/test/java/com/volmit/host/StageStreamsTest.java similarity index 89% rename from src/test/java/com/volmit/host/StageRandomTest.java rename to src/test/java/com/volmit/host/StageStreamsTest.java index 0fa3d243b..ebd106e0f 100644 --- a/src/test/java/com/volmit/host/StageRandomTest.java +++ b/src/test/java/com/volmit/host/StageStreamsTest.java @@ -22,11 +22,10 @@ import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.function.Consumer; -import java.util.random.RandomGenerator; import java.util.stream.IntStream; import static org.junit.jupiter.api.Assertions.*; -class StageRandomTest { +class StageStreamsTest { private static final BlockState STONE = new BlockState("minecraft:stone"); private static final int BLOCKS = 3; private static final int BOUND = 1_000_000; @@ -79,7 +78,7 @@ class StageRandomTest { } private static List firstDraws(long invocationSeed, String stageId, int count) { - var stream = StageRandom.stream(invocationSeed, ResourceId.parse(stageId)); + var stream = StageStreams.stream(invocationSeed, ResourceId.parse(stageId)); return IntStream.range(0, count).mapToObj(ignored -> (long) stream.nextInt(BOUND)).toList(); } @@ -123,7 +122,7 @@ class StageRandomTest { var drawn = place(graph, TestContexts.SEED); assertNotEquals(drawn.get("a:mod/pick"), drawn.get("c:mod/pick")); - assertNotEquals(StageRandom.idHash(ResourceId.parse("a:mod/pick")), StageRandom.idHash(ResourceId.parse("c:mod/pick"))); + assertNotEquals(StageStreams.idHash(ResourceId.parse("a:mod/pick")), StageStreams.idHash(ResourceId.parse("c:mod/pick"))); } @Test @@ -147,16 +146,19 @@ class StageRandomTest { } /** Pins the documented derivation with values computed outside Java from its specification, so a - * change to the derivation or to the JDK's Random fails here instead of silently changing worlds. + * change to the derivation fails here instead of silently changing worlds. {@code WorldRandomTest} + * pins the generator itself. */ @Test void derivationMatchesItsSpecification() { var stage = ResourceId.parse("iris:stilt/fill"); - assertEquals(0xd11cde74d6a9508aL, StageRandom.idHash(stage), "64-bit FNV-1a of iris:stilt/fill"); + assertEquals(0xd11cde74d6a9508aL, StageStreams.idHash(stage), "64-bit FNV-1a of iris:stilt/fill"); - RandomGenerator stream = StageRandom.stream(TestContexts.SEED, stage); - assertEquals(4203081479670090427L, stream.nextLong()); - assertEquals(-978353470, stream.nextInt()); - assertEquals(943449, stream.nextInt(BOUND)); + assertEquals(-3593301659158072667L, StageStreams.streamSeed(TestContexts.SEED, StageStreams.idHash(stage))); + + var stream = StageStreams.stream(TestContexts.SEED, stage); + assertEquals(2676194909693269196L, stream.nextLong()); + assertEquals(1649978757, stream.nextInt()); + assertEquals(868252, stream.nextInt(BOUND)); } } diff --git a/src/test/java/com/volmit/random/WorldRandomTest.java b/src/test/java/com/volmit/random/WorldRandomTest.java new file mode 100644 index 000000000..d1fcf0a12 --- /dev/null +++ b/src/test/java/com/volmit/random/WorldRandomTest.java @@ -0,0 +1,185 @@ +package com.volmit.random; + +import org.junit.jupiter.api.Test; +import java.lang.reflect.Method; +import java.lang.reflect.Modifier; +import java.util.Arrays; +import java.util.List; +import java.util.Set; +import java.util.function.Consumer; +import java.util.function.Function; +import java.util.random.RandomGenerator; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import static org.junit.jupiter.api.Assertions.*; + +/** Pins every method to values computed outside Java from the specification in {@link WorldRandom}'s + * documentation ({@code src/test/reference/world_random.py}), so any change to an algorithm fails here + * instead of silently changing existing worlds. + */ +class WorldRandomTest { + private static final long SEED = 42; + private static final int REPEATS = 1_000; + + private static List draws(int count, Function method) { + var random = new WorldRandom(SEED); + return Stream.generate(() -> method.apply(random)).limit(count).toList(); + } + + @Test + void longsAreSplitMix64Outputs() { + assertEquals(List.of(-4767286540954276203L, 2949826092126892291L, 5139283748462763858L, + 6349198060258255764L, 701532786141963250L, -2430762948046562554L), draws(6, WorldRandom::nextLong)); + } + + @Test + void intsAreTheHighHalfOfALong() { + assertEquals(List.of(-1109970394, 686809907, 1196582743, 1478287871, 163338330, -565956102), + draws(6, WorldRandom::nextInt)); + } + + @Test + void boundedIntsMatchTheirSpecification() { + assertEquals(List.of(7, 1, 2, 3, 0, 8), draws(6, random -> random.nextInt(10))); + assertEquals(List.of(2, -4, -3, -2, -5, 3), draws(6, random -> random.nextInt(-5, 5))); + assertEquals(List.of(1037513253, -1460673742, -950900906, -669195778, -1984145319, 1581527545), + draws(6, random -> random.nextInt(Integer.MIN_VALUE, Integer.MAX_VALUE))); + } + + /** A range of 3 * 2^30 values rejects one draw in four; these twelve values take fourteen draws. */ + @Test + void boundedIntsRejectDrawsThatWouldBias() { + assertEquals(List.of(241264028, -1632376218, -1250046591, -1038767745, -2024979901, 649274747, + 431532146, -1052489127, -1487448649, -559454326, -493719002, -472403562), + draws(12, random -> random.nextInt(Integer.MIN_VALUE, 1 << 30))); + } + + @Test + void boundedLongsMatchTheirSpecification() { + assertEquals(List.of(741L, 159L, 278L, 344L, 38L, 868L), draws(6, random -> random.nextLong(1000))); + assertEquals(List.of(483L, -681L, -443L, -312L, -924L, 736L), draws(6, random -> random.nextLong(-1000, 1000))); + assertEquals(List.of(4456085495900499604L, -6273545944727883518L, -4084088288392011951L, + -2874173976596520045L, -8521839250712812559L, 6792609088808213253L), + draws(6, random -> random.nextLong(Long.MIN_VALUE, Long.MAX_VALUE))); + } + + /** A range of 3 * 2^62 values rejects one draw in four; these twelve values take fourteen draws. */ + @Test + void boundedLongsRejectDrawsThatWouldBias() { + assertEquals(List.of(1036221112711680751L, -7011002467759606590L, -5368909225507702915L, + -8697222447248303371L, 2788613807392465988L, -6201723502271557115L, + -4520406378645414305L, -666636742666774078L, -6388543298285055153L, + -2402838030758921074L, -2120506962181442260L, -2028957847325109687L), + draws(12, random -> random.nextLong(Long.MIN_VALUE, 1L << 62))); + } + + @Test + void booleansAreTheHighestBitOfALong() { + assertEquals(List.of(true, false, false, false, false, true, false, true, false, true, false, false), + draws(12, WorldRandom::nextBoolean)); + } + + @Test + void floatsAndDoublesAreTheHighBitsOfALong() { + assertEquals(List.of(0.7415648698806763f, 0.1599103808403015f, 0.27860110998153687f, + 0.34419065713882446f, 0.038030147552490234f, 0.868228018283844f), draws(6, WorldRandom::nextFloat)); + assertEquals(List.of(0.7415648787718233, 0.1599103928769201, 0.27860113025513866, + 0.34419071652363753, 0.03803016854024621, 0.8682280765465323), draws(6, WorldRandom::nextDouble)); + } + + @Test + void boundedDoublesMatchTheirSpecification() { + assertEquals(List.of(7.415648787718233, 1.599103928769201, 2.786011302551387, 3.4419071652363753, + 0.3803016854024621, 8.682280765465324), draws(6, random -> random.nextDouble(10.0))); + assertEquals(List.of(4.915648787718233, -0.900896071230799, 0.28601130255138685, 0.9419071652363753, + -2.119698314597538, 6.182280765465324), draws(6, random -> random.nextDouble(-2.5, 7.5))); + } + + @Test + void doubleRangesWiderThanTheLargestDoubleAreHalvedFirst() { + assertEquals(List.of(8.685190483839085e+307, -1.2227535039263658e+308, -7.960144564132267e+307, + -5.601945585065466e+307, -1.6609599890574008e+308, 1.3239221705425129e+308), + draws(6, random -> random.nextDouble(-Double.MAX_VALUE, Double.MAX_VALUE))); + } + + /** Most draws in a range one ulp wide round up to the bound and are replaced by the origin. */ + @Test + void boundedDoublesNeverReturnTheBound() { + double bound = Math.nextUp(1.0); + assertEquals(List.of(1.0), draws(REPEATS, random -> random.nextDouble(1.0, bound)).stream().distinct().toList()); + } + + @Test + void gaussiansUseThePolarMethodWithStrictMath() { + assertEquals(List.of(0.49295065581737485, -1.2810773478777024, -0.6018779810957331, + -1.5423606818352653, -1.4515103855695575, 1.9375059271254913), draws(6, WorldRandom::nextGaussian)); + } + + @Test + void chanceIsADoubleBelowTheProbability() { + assertEquals(List.of(false, true, false, false, true, false, true, false, false, false, true, false), + draws(12, random -> random.chance(0.25))); + assertEquals(List.of(false), draws(REPEATS, random -> random.chance(0)).stream().distinct().toList()); + assertEquals(List.of(true), draws(REPEATS, random -> random.chance(1)).stream().distinct().toList()); + } + + @Test + void zeroOriginRangesEqualTheSingleBoundMethods() { + assertEquals(draws(REPEATS, random -> random.nextInt(37)), draws(REPEATS, random -> random.nextInt(0, 37))); + assertEquals(draws(REPEATS, random -> random.nextLong(37)), draws(REPEATS, random -> random.nextLong(0, 37))); + assertEquals(List.of(0), draws(REPEATS, random -> random.nextInt(1)).stream().distinct().toList()); + assertEquals(List.of(0L), draws(REPEATS, random -> random.nextLong(1)).stream().distinct().toList()); + } + + /** How many values a method draws is part of the sequence: later draws shift if it changes. */ + @Test + void methodsWithoutRejectionDrawExactlyOneValue() { + List> singleDraws = List.of(WorldRandom::nextInt, WorldRandom::nextBoolean, + WorldRandom::nextFloat, WorldRandom::nextDouble, random -> random.nextDouble(3.0), + random -> random.nextDouble(-1.0, 1.0), random -> random.chance(0.5)); + long second = draws(2, WorldRandom::nextLong).getLast(); + + for (var method : singleDraws) { + var random = new WorldRandom(SEED); + method.accept(random); + assertEquals(second, random.nextLong()); + } + } + + @Test + void invalidBoundsThrow() { + var random = new WorldRandom(SEED); + List invalid = List.of( + () -> random.nextInt(0), () -> random.nextInt(-1), () -> random.nextInt(5, 5), () -> random.nextInt(5, 4), + () -> random.nextLong(0), () -> random.nextLong(-1), () -> random.nextLong(5, 5), () -> random.nextLong(5, 4), + () -> random.nextDouble(0), () -> random.nextDouble(-1), () -> random.nextDouble(Double.NaN), + () -> random.nextDouble(Double.POSITIVE_INFINITY), () -> random.nextDouble(1, 1), + () -> random.nextDouble(2, 1), () -> random.nextDouble(Double.NaN, 1), + () -> random.nextDouble(0, Double.POSITIVE_INFINITY), () -> random.nextDouble(Double.NEGATIVE_INFINITY, 0), + () -> random.chance(-0.1), () -> random.chance(1.1), () -> random.chance(Double.NaN)); + + for (var call : invalid) assertThrows(IllegalArgumentException.class, call::run); + } + + /** No method may fall through to an algorithm the JDK defines. A new public method needs pinned + * values above before it joins this list. + */ + @Test + void exposesOnlyTheMethodsPinnedHere() { + assertFalse(RandomGenerator.class.isAssignableFrom(WorldRandom.class)); + assertTrue(Modifier.isFinal(WorldRandom.class.getModifiers())); + var methods = Arrays.stream(WorldRandom.class.getDeclaredMethods()) + .filter(method -> Modifier.isPublic(method.getModifiers())) + .map(WorldRandomTest::signature) + .collect(Collectors.toSet()); + + assertEquals(Set.of("nextLong()", "nextLong(long)", "nextLong(long,long)", "nextInt()", "nextInt(int)", + "nextInt(int,int)", "nextBoolean()", "nextFloat()", "nextDouble()", "nextDouble(double)", + "nextDouble(double,double)", "nextGaussian()", "chance(double)"), methods); + } + + private static String signature(Method method) { + return method.getName() + Arrays.stream(method.getParameterTypes()).map(Class::getName) + .collect(Collectors.joining(",", "(", ")")); + } +} diff --git a/src/test/reference/world_random.py b/src/test/reference/world_random.py new file mode 100644 index 000000000..d3784e4d6 --- /dev/null +++ b/src/test/reference/world_random.py @@ -0,0 +1,218 @@ +"""Reference values for WorldRandomTest and StageStreamsTest, computed from the specification in +WorldRandom's and StageStreams' documentation with Python integers and IEEE doubles, outside Java. + +Run from IrisApi: python3 -B src/test/reference/world_random.py +""" +import math +import struct + +MASK64 = (1 << 64) - 1 +GOLDEN_GAMMA = 0x9E3779B97F4A7C15 + + +def signed64(value): + value &= MASK64 + return value - (1 << 64) if value >= 1 << 63 else value + + +def signed32(value): + value &= (1 << 32) - 1 + return value - (1 << 32) if value >= 1 << 31 else value + + +def mix(z): + z = ((z ^ (z >> 30)) * 0xBF58476D1CE4E5B9) & MASK64 + z = ((z ^ (z >> 27)) * 0x94D049BB133111EB) & MASK64 + return z ^ (z >> 31) + + +def fnv1a64(text): + value = 0xCBF29CE484222325 + for byte in text.encode("utf-8"): + value = ((value ^ byte) * 0x100000001B3) & MASK64 + return value + + +def stream_seed(invocation_seed, stage_id): + return mix(mix(invocation_seed & MASK64) ^ fnv1a64(stage_id)) + + +# fdlibm __ieee754_log (e_log.c), the algorithm StrictMath.log specifies. +LN2_HI = 6.93147180369123816490e-01 +LN2_LO = 1.90821492927058770002e-10 +TWO54 = 1.80143985094819840000e+16 +LG = [6.666666666666735130e-01, 3.999999999940941908e-01, 2.857142874366239149e-01, + 2.222219843214978396e-01, 1.818357216161805012e-01, 1.531383769920937332e-01, + 1.479819860511658591e-01] + + +def high_word(x): + return signed32(struct.unpack("> 32) + + +def low_word(x): + return struct.unpack("= 0x7FF00000: + return x + x + k += (hx >> 20) - 1023 + hx &= 0x000FFFFF + i = (hx + 0x95F64) & 0x100000 + x = with_high_word(x, hx | (i ^ 0x3FF00000)) + k += i >> 20 + f = x - 1.0 + if (0x000FFFFF & (2 + hx)) < 3: + if f == 0.0: + if k == 0: + return 0.0 + dk = float(k) + return dk * LN2_HI + dk * LN2_LO + r = f * f * (0.5 - 0.33333333333333333 * f) + if k == 0: + return f - r + dk = float(k) + return dk * LN2_HI - ((r - dk * LN2_LO) - f) + s = f / (2.0 + f) + dk = float(k) + z = s * s + i = hx - 0x6147A + w = z * z + j = 0x6B851 - hx + t1 = w * (LG[1] + w * (LG[3] + w * LG[5])) + t2 = z * (LG[0] + w * (LG[2] + w * (LG[4] + w * LG[6]))) + i |= j + r = t2 + t1 + if i > 0: + hfsq = 0.5 * f * f + if k == 0: + return f - (hfsq - s * (hfsq + r)) + return dk * LN2_HI - ((hfsq - (s * (hfsq + r) + dk * LN2_LO)) - f) + if k == 0: + return f - s * (f - r) + return dk * LN2_HI - ((s * (f - r) - dk * LN2_LO) - f) + + +class WorldRandom: + def __init__(self, seed): + self.state = seed & MASK64 + + def raw(self): + """The next output as an unsigned 64-bit integer.""" + self.state = (self.state + GOLDEN_GAMMA) & MASK64 + return mix(self.state) + + def next_long(self): + return signed64(self.raw()) + + def next_int(self): + return signed32(self.raw() >> 32) + + def bounded(self, width, bits): + """Lemire: high half of x * width, rejecting while the low half is below 2^bits mod width.""" + threshold = (1 << bits) % width + while True: + x = self.raw() >> (64 - bits) + product = x * width + if product % (1 << bits) >= threshold: + return product >> bits + + def next_int_bound(self, bound): + return self.bounded(bound, 32) + + def next_int_range(self, origin, bound): + return origin + self.bounded(bound - origin, 32) + + def next_long_bound(self, bound): + return self.bounded(bound, 64) + + def next_long_range(self, origin, bound): + return origin + self.bounded(bound - origin, 64) + + def next_boolean(self): + return self.raw() >> 63 == 1 + + def next_float(self): + return (self.raw() >> 40) * 2.0 ** -24 + + def next_double(self): + return (self.raw() >> 11) * 2.0 ** -53 + + def next_double_bound(self, bound): + value = self.next_double() * bound + return value if value < bound else below(bound) + + def next_double_range(self, origin, bound): + unit = self.next_double() + width = bound - origin + if width != float("inf"): + value = origin + unit * width + else: + value = 2 * (origin / 2 + unit * (bound / 2 - origin / 2)) + return value if value < bound else below(bound) + + def next_gaussian(self): + while True: + u = 2 * self.next_double() - 1 + v = 2 * self.next_double() - 1 + s = u * u + v * v + if 0 < s < 1: + return u * math.sqrt(-2 * fdlibm_log(s) / s) + + def chance(self, probability): + return self.next_double() < probability + + +def below(value): + bits = struct.unpack(" 0 else bits + 1))[0] + + +def draws(label, method, count=6, seed=42): + random = WorldRandom(seed) + print(f"{label}: {[method(random) for _ in range(count)]}") + + +if __name__ == "__main__": + print(f"fnv1a64(iris:stilt/fill) = {signed64(fnv1a64('iris:stilt/fill'))}") + print(f"streamSeed(42, iris:stilt/fill) = {signed64(stream_seed(42, 'iris:stilt/fill'))}") + stage = WorldRandom(stream_seed(42, "iris:stilt/fill")) + print(f"stage stream nextLong, nextInt, nextInt(1000000): " + f"{stage.next_long()}, {stage.next_int()}, {stage.next_int_bound(1_000_000)}") + + draws("nextLong()", WorldRandom.next_long) + draws("nextInt()", WorldRandom.next_int) + draws("nextInt(10)", lambda r: r.next_int_bound(10)) + draws("nextInt(-5, 5)", lambda r: r.next_int_range(-5, 5)) + # width 3 * 2^30: one draw in four is rejected. + draws("nextInt(-2^31, 2^30)", lambda r: r.next_int_range(-(1 << 31), 1 << 30), count=12) + draws("nextInt(MIN, MAX)", lambda r: r.next_int_range(-(1 << 31), (1 << 31) - 1)) + draws("nextLong(1000)", lambda r: r.next_long_bound(1000)) + draws("nextLong(-1000, 1000)", lambda r: r.next_long_range(-1000, 1000)) + # width 3 * 2^62: one draw in four is rejected. + draws("nextLong(-2^63, 2^62)", lambda r: r.next_long_range(-(1 << 63), 1 << 62), count=12) + draws("nextLong(MIN, MAX)", lambda r: r.next_long_range(-(1 << 63), (1 << 63) - 1)) + draws("nextBoolean()", WorldRandom.next_boolean, count=12) + draws("nextFloat()", WorldRandom.next_float) + draws("nextDouble()", WorldRandom.next_double) + draws("nextDouble(10.0)", lambda r: r.next_double_bound(10.0)) + draws("nextDouble(-2.5, 7.5)", lambda r: r.next_double_range(-2.5, 7.5)) + max_double = 1.7976931348623157e308 + draws("nextDouble(-MAX, MAX)", lambda r: r.next_double_range(-max_double, max_double)) + draws("nextGaussian()", WorldRandom.next_gaussian) + draws("chance(0.25)", lambda r: r.chance(0.25), count=12)