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; *
{@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: + *
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> 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)