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.
This commit is contained in:
piexel committed 2026-10-06 11:36:13 +02:00
1 parent d5aad57ad9
commit 1ce0a19abb
17 files changed
+653 -48

No files matched your search

@@ -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);
}
@@ -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();
}
}
@@ -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);
@@ -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,
@@ -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)));
}
@@ -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();
}
@@ -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(
@@ -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];
}
@@ -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;
* <li>{@code idHash} = 64-bit FNV-1a of the UTF-8 bytes of the stage id ({@code namespace:path});</li>
* <li>{@code streamSeed} = {@code mix(mix(invocationSeed) ^ idHash)}, where {@code mix} is the
* SplitMix64 finalizer (Stafford variant 13);</li>
* <li>the stream is {@code new java.util.Random(streamSeed)}.</li>
* <li>the stream is {@code new WorldRandom(streamSeed)}, whose every method IrisApi defines.</li>
* </ol>
* {@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.
*
* <p>{@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. */
@@ -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();
}
@@ -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()}.
*
* <p>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.
*
* <p><b>Algorithm.</b> 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:
* <ul>
* <li>{@code nextInt()}: the high 32 bits of one value;</li>
* <li>{@code nextBoolean()}: whether one value is negative (its highest bit);</li>
* <li>{@code nextFloat()}: the high 24 bits of one value times 2<sup>-24</sup>;</li>
* <li>{@code nextDouble()}: the high 53 bits of one value times 2<sup>-53</sup>;</li>
* <li>bounded integers: Lemire's multiply-and-reject method, which is unbiased. For a range of
* {@code n} values, {@code ints} take the high 32 bits {@code x} of one value and compute the
* 64-bit product {@code x * n}, {@code longs} take one value {@code x} and compute the
* 128-bit product; when the product's low half is below 2<sup>32</sup> (or 2<sup>64</sup>)
* {@code mod n}, they draw again; the result is the product's high half plus the origin;</li>
* <li>bounded doubles: {@code origin + nextDouble() * (bound - origin)}, a result that rounds up
* to {@code bound} replaced by the largest double below it (see {@link #nextDouble(double, double)}
* for ranges wider than the largest double);</li>
* <li>{@code nextGaussian()}: Marsaglia's polar method on pairs of {@code nextDouble()} values,
* using {@link StrictMath}, whose results are fixed;</li>
* <li>{@code chance(p)}: {@code nextDouble() < p}.</li>
* </ul>
* Methods without rejection draw exactly one value. {@code nextInt(0, n)} equals {@code nextInt(n)}
* and {@code nextLong(0, n)} equals {@code nextLong(n)}.
*
* <p>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<sup>-24</sup>. */
public float nextFloat() {
return (nextLong() >>> FLOAT_SHIFT) * FLOAT_UNIT;
}
/** A uniformly distributed {@code double} in {@code [0, 1)}, a multiple of 2<sup>-53</sup>. */
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);
}
}
@@ -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