diff --git a/src/main/java/com/volmit/generation/InvocationContext.java b/src/main/java/com/volmit/generation/InvocationContext.java index 01a2bc219..2288e1272 100644 --- a/src/main/java/com/volmit/generation/InvocationContext.java +++ b/src/main/java/com/volmit/generation/InvocationContext.java @@ -1,14 +1,13 @@ package com.volmit.generation; import com.volmit.resource.PackResources; -import java.util.random.RandomGenerator; -/** Host-owned invocation inputs. RNG and views must not be retained or used by detached tasks. - * The host derives streams from world seed, stable feature/occurrence identity and position; - * module discovery order must not affect them. Keeping legacy random behavior is adapter work. +/** Host-owned invocation inputs. Views must not be retained or used by detached tasks. + * + *
There is no shared random stream. A stage draws from {@link com.volmit.stage.StageContext#random()}, + * a stream of its own, and an object generator from {@link com.volmit.object.ObjectGenerationContext#random()}. */ public interface InvocationContext { long worldSeed(); PackResources resources(); - RandomGenerator random(); } diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index db9dd9abb..ca5329b34 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -77,6 +77,6 @@ final class ChunkInvocation implements ChunkStageContext { @Override public RandomGenerator random() { - return inputs.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 dae6a37cd..f9695aea1 100644 --- a/src/main/java/com/volmit/host/ChunkRunner.java +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -18,8 +18,11 @@ public final class ChunkRunner { } } - public void generate(GenerationContext inputs, ConfiguredSettings settings) { - var chunk = new ChunkInvocation(new StageInvocation(graph, settings), inputs); + /** 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}). + */ + public void generate(GenerationContext inputs, long invocationSeed, ConfiguredSettings settings) { + var chunk = new ChunkInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); for (int position = 0; position < graph.size(); position++) { chunk.stages().runInvocationStage(position, chunk); } diff --git a/src/main/java/com/volmit/host/ExecutableStage.java b/src/main/java/com/volmit/host/ExecutableStage.java index c99804a16..e270c7a98 100644 --- a/src/main/java/com/volmit/host/ExecutableStage.java +++ b/src/main/java/com/volmit/host/ExecutableStage.java @@ -4,7 +4,8 @@ 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. + * 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. */ record ExecutableStage( Stage> stage, @@ -12,7 +13,8 @@ record ExecutableStage( int[] requirements, Stage>[] readableStages, int[] readablePositions, - int settingsSlot) { + int settingsSlot, + long idHash) { static final int NO_SETTINGS = -1; static final int NOT_READABLE = -1; diff --git a/src/main/java/com/volmit/host/GraphResolver.java b/src/main/java/com/volmit/host/GraphResolver.java index 0f7cf5f71..88912d402 100644 --- a/src/main/java/com/volmit/host/GraphResolver.java +++ b/src/main/java/com/volmit/host/GraphResolver.java @@ -224,7 +224,8 @@ final class GraphResolver { readable[index].stream().mapToObj(readablePosition -> nodes.get(order[readablePosition]).stage()) .toArray(Stage>[]::new), readable[index].stream().toArray(), - settingsSlot(declaration, settingsTypes)); + settingsSlot(declaration, settingsTypes), + StageRandom.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 1f75c7ee9..325e3bf8c 100644 --- a/src/main/java/com/volmit/host/PlacementInvocation.java +++ b/src/main/java/com/volmit/host/PlacementInvocation.java @@ -118,7 +118,7 @@ final class PlacementInvocation implements BlockStageContext { @Override public RandomGenerator random() { - return inputs.random(); + return stages.random(); } @Override diff --git a/src/main/java/com/volmit/host/PlacementRunner.java b/src/main/java/com/volmit/host/PlacementRunner.java index af6223e75..a17b2c102 100644 --- a/src/main/java/com/volmit/host/PlacementRunner.java +++ b/src/main/java/com/volmit/host/PlacementRunner.java @@ -22,17 +22,20 @@ 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 (with a dedicated RNG) and the - * settings configured for this placement. Stages never receive commit/close rights. + * 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 + * receive commit/close rights. */ public PlacementOutcome place( PlacementRequest request, PlacementEdit edit, PlacementContext inputs, + long invocationSeed, ConfiguredSettings settings) { Objects.requireNonNull(edit, "edit"); try (edit) { - var stages = new StageInvocation(graph, settings); + var stages = new StageInvocation(graph, invocationSeed, settings); var access = PlacementViews.restrict(edit, edit.bounds()); var placement = new PlacementInvocation(stages, request, inputs, access); runSegments(placement); diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java index 3dfb32ffd..35b829162 100644 --- a/src/main/java/com/volmit/host/StageInvocation.java +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -5,13 +5,15 @@ 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 and stage outputs, all - * indexed by resolved position. Activation is computed once up front in resolved order: a stage - * is active when its settings are configured (or it has no condition) and every stage it - * requires is active, so inactivity cascades to dependents. Cost is one pass over stages and - * requirement edges plus one settings lookup per distinct settings type. +/** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage + * random streams, all indexed by resolved position. Activation is computed once up front in resolved + * order: a stage is active when its settings are configured (or it has no condition) and every + * stage it requires is active, so inactivity cascades to dependents. Cost is one pass over stages + * and requirement edges plus one settings lookup per distinct settings type. A stage's stream is + * created when it first draws and depends only on the invocation seed and the stage id. */ final class StageInvocation { private static final Object PENDING = new Object(); @@ -21,14 +23,18 @@ final class StageInvocation { private final Object[] settingsBySlot; private final boolean[] active; private final Object[] outputs; + private final long invocationSeed; + private final RandomGenerator[] streams; private int current = NO_STAGE; - StageInvocation(ResolvedGraph graph, ConfiguredSettings settings) { + StageInvocation(ResolvedGraph graph, long invocationSeed, ConfiguredSettings settings) { this.graph = graph; settingsBySlot = lookUpSettings(graph, Objects.requireNonNull(settings, "settings")); active = activation(graph, settingsBySlot); outputs = new Object[graph.size()]; Arrays.fill(outputs, PENDING); + this.invocationSeed = invocationSeed; + streams = new RandomGenerator[graph.size()]; } boolean isActive(int position) { @@ -90,6 +96,17 @@ final class StageInvocation { return (O) outputs[position]; } + /** The running stage's own stream. A block stage keeps one stream across every block of its pass. */ + RandomGenerator 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()); + } + return streams[current]; + } + private ExecutableStage currentStage() { if (current == NO_STAGE) { throw new IllegalStateException("Stage outputs can only be read while a stage runs"); diff --git a/src/main/java/com/volmit/host/StageRandom.java b/src/main/java/com/volmit/host/StageRandom.java new file mode 100644 index 000000000..9f8cb2baa --- /dev/null +++ b/src/main/java/com/volmit/host/StageRandom.java @@ -0,0 +1,62 @@ +package com.volmit.host; + +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 + * installed, their order, or how much they draw. + * + *
The derivation is fixed so the same seed gives the same world on every machine and JDK: + *
{@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 {
+ private static final long FNV_OFFSET_BASIS = 0xcbf29ce484222325L;
+ private static final long FNV_PRIME = 0x100000001b3L;
+ private static final int BYTE_MASK = 0xff;
+
+ private StageRandom() {}
+
+ /** The stream {@code stageId} draws from in the invocation with {@code invocationSeed}. */
+ public static RandomGenerator stream(long invocationSeed, ResourceId stageId) {
+ return stream(invocationSeed, idHash(stageId));
+ }
+
+ static RandomGenerator stream(long invocationSeed, long idHash) {
+ return new Random(mix(mix(invocationSeed) ^ idHash));
+ }
+
+ /** 64-bit FNV-1a over the UTF-8 bytes of the id. */
+ static long idHash(ResourceId stageId) {
+ long hash = FNV_OFFSET_BASIS;
+ for (byte value : stageId.toString().getBytes(StandardCharsets.UTF_8)) {
+ hash ^= value & BYTE_MASK;
+ hash *= FNV_PRIME;
+ }
+ return hash;
+ }
+
+ /** SplitMix64's finalizer: a bijection on 64-bit values with full avalanche. */
+ 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/object/ObjectGenerationContext.java b/src/main/java/com/volmit/object/ObjectGenerationContext.java
index a668bed39..d5515081e 100644
--- a/src/main/java/com/volmit/object/ObjectGenerationContext.java
+++ b/src/main/java/com/volmit/object/ObjectGenerationContext.java
@@ -1,8 +1,12 @@
package com.volmit.object;
import com.volmit.generation.InvocationContext;
+import java.util.random.RandomGenerator;
/** 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 {}
+public interface ObjectGenerationContext extends InvocationContext {
+ /** This generation's stream, seeded from the variant seed the host chose. Do not retain it. */
+ RandomGenerator random();
+}
diff --git a/src/main/java/com/volmit/stage/PlacementStageContext.java b/src/main/java/com/volmit/stage/PlacementStageContext.java
index 2b7058f7d..0ad5d5406 100644
--- a/src/main/java/com/volmit/stage/PlacementStageContext.java
+++ b/src/main/java/com/volmit/stage/PlacementStageContext.java
@@ -5,7 +5,7 @@ import com.volmit.placement.PlacementContext;
import com.volmit.placement.PlacementRequest;
/** One placement attempt. Writes go to a buffered edit committed only if no stage rejects
- * and none throws. All stages of an attempt share its inputs, including the RNG, in resolved order.
+ * and none throws. All stages of an attempt share its inputs; each draws from its own random stream.
*/
public interface PlacementStageContext extends PlacementContext, StageContext {
PlacementRequest request();
diff --git a/src/main/java/com/volmit/stage/StageContext.java b/src/main/java/com/volmit/stage/StageContext.java
index a42c6fb57..13fd9469d 100644
--- a/src/main/java/com/volmit/stage/StageContext.java
+++ b/src/main/java/com/volmit/stage/StageContext.java
@@ -1,7 +1,16 @@
package com.volmit.stage;
+import java.util.random.RandomGenerator;
+
/** Per-invocation view handed to one stage body. Do not retain it after the body returns. */
public interface StageContext {
+ /** This stage's own random stream in this invocation. It is derived from the invocation's seed
+ * and this stage's id only, so installing, removing or reordering other modules and stages, or
+ * 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();
+
/** The output the given stage produced in this invocation. Only stages the current stage
* transitively requires are readable; anything else throws IllegalStateException, as does
* reading a block stage's accumulator before its block pass has finished.
diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java
index 65c881a7f..753c000cb 100644
--- a/src/test/java/com/volmit/example/ChunkPipelineTest.java
+++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java
@@ -37,7 +37,7 @@ class ChunkPipelineTest {
private static Hunk