From 50f51db8b26351239ea438753e996503f06e4a40 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 12:35:04 +0200 Subject: [PATCH] Run each mantle stage as its own pass and let mantle stages work out their reach per pack MantleRunner.generate(stage, inputs, seed) runs one mantle stage for one chunk. The host runs every mantle stage as its own pass in resolved order, so a stage sees what earlier stages wrote into the chunks around it. Activation still follows requires(...): the runner collects the settings of the stage and of everything it requires, and only those. Because the stages of one chunk now run in different invocations, mantle stages have no output (Stage.mantle declares Void) and pass data on through mantle layers. A mantle stage whose reach depends on the pack declares reach(PackReach). The host works it out once per pack load from PackSettings, every entry the dimension and its regions and biomes declare, with ResolvedStage.reachBlocks(settings); a negative result fails naming the stage. Placement and chunk stages may not declare one, and ResolvedGraph.reach() throws for a mantle pipeline that has one. VeinModule now sizes its reach from the pack's longest vein. --- CONTRACTS.md | 17 +++-- DESIGN.md | 43 ++++++++---- README.md | 48 +++++++++---- .../java/com/volmit/config/PackSettings.java | 19 ++++++ .../java/com/volmit/host/ChunkRunner.java | 2 +- .../java/com/volmit/host/ChunkSettings.java | 13 ++-- src/main/java/com/volmit/host/FixedReach.java | 18 +++++ .../com/volmit/host/GraphDescription.java | 10 ++- .../com/volmit/host/InvocationStageDraft.java | 7 ++ .../java/com/volmit/host/MantleRunner.java | 68 +++++++++++++++---- .../java/com/volmit/host/PipelineReach.java | 9 +-- .../java/com/volmit/host/ResolvedGraph.java | 8 ++- .../java/com/volmit/host/ResolvedStage.java | 28 +++++++- .../com/volmit/host/StageDeclaration.java | 35 ++++++++-- src/main/java/com/volmit/host/StageReach.java | 17 +++-- .../stage/ConditionalStageDefinition.java | 2 + .../java/com/volmit/stage/MantleStage.java | 6 +- src/main/java/com/volmit/stage/PackReach.java | 13 ++++ src/main/java/com/volmit/stage/Pipeline.java | 5 +- src/main/java/com/volmit/stage/Stage.java | 5 +- .../com/volmit/stage/StageDefinition.java | 8 ++- .../com/volmit/example/ChunkPipelineTest.java | 12 ++-- .../com/volmit/example/chunk/VeinModule.java | 14 +++- .../java/com/volmit/host/StageGraphTest.java | 66 ++++++++++++++++++ .../com/volmit/support/DeclaredSettings.java | 26 +++++++ 25 files changed, 410 insertions(+), 89 deletions(-) create mode 100644 src/main/java/com/volmit/config/PackSettings.java create mode 100644 src/main/java/com/volmit/host/FixedReach.java create mode 100644 src/main/java/com/volmit/stage/PackReach.java create mode 100644 src/test/java/com/volmit/support/DeclaredSettings.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 743f068d5..8787e8994 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -22,7 +22,7 @@ types that carry them and lists what the Iris adapter still owes. | Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner` | | Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only | | Annotated settings | `IrisFeature`, `@Feature` (id as JSON key, built-in alias), config annotations, `OptionsMetadata` | -| Area a stage writes | `reach(blocks)`, `writesMantle(...)` on stage definitions, host `StageReach`, `PipelineReach` | +| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema` with `shorthand()`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | @@ -90,12 +90,15 @@ running Iris is the pack publisher's responsibility. work inside the ported stages. - Derive one seed per placement (world seed and the placement's stable identity) and per chunk (world seed and chunk position) and pass it to `PlacementRunner.place` / `ChunkRunner.generate`. -- Prepare the area a placement or chunk may read or write, including neighbors: the pipeline's - `reach()` around the chunk or the placed object's bounds, each mantle layer by its own maximum. - Never clip. -- Run the mantle pipeline (`MantleRunner`) for every chunk within its reach of a chunk, each chunk once, - before that chunk generates, with the mantle widened by the reach. Give chunk stages that chunk's - mantle; `ChunkRunner` makes it read-only. +- Prepare the area a placement may read or write, including neighbors: the placement pipeline's + `reach()` around the placed object's bounds, each mantle layer by its own maximum. Never clip. +- Work out each mantle stage's reach once per pack load (`ResolvedStage.reachBlocks(PackSettings)`), + answering `PackSettings.declared(type)` with every entry of the dimension and of the regions and + biomes it can reach. +- Run each mantle stage (`MantleRunner.generate(stage, ...)`) as its own pass, in resolved order: for + every chunk within that stage's reach plus the reach of every later stage of a chunk, each chunk once, + before the next stage and before that chunk generates, with the mantle widened by the stage's reach. + Give chunk stages that chunk's mantle; `ChunkRunner` makes it read-only. - Make placement edits atomic across blocks, block entities, markers and mantle in generation storage. Abort chunk publication when any stage fails. - Preserve unknown persisted mantle layers or fail explicitly. diff --git a/DESIGN.md b/DESIGN.md index 39ccaacf9..e42efb7b2 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -297,7 +297,7 @@ resolve time. | `PlacementStage` | PLACEMENT | once per placement attempt | `PlacementStageContext` | | `BlockStage` | PLACEMENT | once per object block, in a block pass | `BlockStageContext` | | `ChunkStage` | CHUNK | once per chunk invocation | `ChunkStageContext` | -| `MantleStage` | MANTLE | once per chunk, before the chunks it reaches generate | `MantleStageContext` | +| `MantleStage` | MANTLE | once per chunk, before the chunks it reaches generate, each stage its own pass | `MantleStageContext` | Rules enforced by `StageGraphBuilder` and the resolver: @@ -484,18 +484,24 @@ the host from publishing the chunk. Some work writes beyond its chunk: a carver whose tunnels cross chunk borders, a vein running on into the next chunk. A chunk stage cannot do that, because the host may already have generated the -neighbor. Such work is a mantle stage. `MantleRunner.generate(inputs, invocationSeed)` runs the active -mantle stages of one chunk in resolved order, against the mantle around it (`MantleGenerationContext`: -origin, terrain, settings, mantle), without a block hunk. The host runs it for every chunk within the -mantle pipeline's reach of a chunk, each chunk once, before that chunk generates, so a chunk's mantle is -complete when its chunk stages read it. In Iris it is one mantle component whose radius is the -pipeline's reach. +neighbor. Such work is a mantle stage. `MantleRunner.generate(stage, inputs, invocationSeed)` runs one +mantle stage for one chunk, if it is active there, against the mantle around it +(`MantleGenerationContext`: origin, terrain, settings, mantle), without a block hunk. + +Every mantle stage is its own pass. Before a chunk generates, the host runs the first stage in resolved +order for every chunk within that stage's reach plus the reach of every later stage, each chunk once, +then the next stage the same way. A stage therefore sees, in the chunks around it, everything earlier +stages wrote, and a chunk's mantle is complete when its chunk stages read it. In Iris each mantle stage +is one mantle component, a pass of its own, whose radius is the stage's reach. Because stages of one +chunk run in different invocations, mantle stages have no outputs: `Stage.mantle` declares `Void`, and +stages pass data on through mantle layers. `requires(...)` still orders mantle stages and still +deactivates a stage in a chunk where a stage it requires is inactive; the runner works that out from +the settings of the stage and everything it requires, and collects only those. The mantle pipeline is the only place that writes the mantle during generation, and mantle and chunk pipelines meet only through mantle layers: an edge between them is a cross-pipeline edge and fails the -load. Within one invocation, stages can still require each other and read outputs. Across chunks they -cannot: a mantle stage that reads another mantle stage's layer outside its own chunk sees whatever has -run there so far, which depends on the order the host generates chunks in. +load. A mantle stage may rely on what earlier stages wrote around its chunk, but not on what a stage of +its own pass wrote in other chunks: that depends on the order the host generates chunks in. ## Reach @@ -513,6 +519,13 @@ graph.define(CARVE).reach(32).writesMantle(CaveModule.CAVES).run(CaveModule::car reach above 0 on one fails the install, naming mantle stages as the place for the work. Whole columns: height is not limited, because Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or negative fails while the module installs. +- `reach(PackReach)`: for a mantle stage whose reach depends on the pack, such as the largest object + or the longest vein any level configures. The host works it out once per pack load from + `PackSettings`, every entry of a settings type the dimension and its reachable regions and biomes + declare, and asks each stage with `ResolvedStage.reachBlocks(settings)`; a negative result fails + there, naming the stage. Placement and chunk stages may not declare one: placement areas and chunks + are sized without the pack's settings. It counts as declaring the reach, so it cannot be combined + with `reach(blocks)`. - `writesMantle(layers...)`: the mantle layers the stage writes. Every layer must be registered by some module with the same value type, or the pack load fails naming stage and layer. Chunk stages cannot declare any. @@ -520,13 +533,15 @@ graph.define(CARVE).reach(32).writesMantle(CaveModule.CAVES).run(CaveModule::car Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`: the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages that write it. Inactive stages count, because activation is per invocation and the prepared area is -decided once per pack load. `describe()` lists each stage's reach. +decided once per pack load. A mantle pipeline with a reach worked out per pack has no such number, so +`reach()` throws there; the host sizes each mantle pass from its own stage instead. `describe()` lists +each stage's reach. One number per stage, not per layer: a stage that writes two layers at different distances declares the larger. The host can still size each layer's mantle from the per-layer maximum. Reads are not -declared separately: the host prepares the pipeline's reach around every chunk or placement, so a -stage may read what others wrote that far out (for mantle stages, see the ordering caveat under Mantle -invocations). A stage that must read farther declares that distance +declared separately: the host prepares the pipeline's reach around every placement, and each mantle +stage's own reach around its chunk, so a stage may read what others wrote that far out (for mantle +stages, see the ordering caveat under Mantle invocations). A stage that must read farther declares that distance as its reach. Terrain samples are computed, not prepared, and need nothing. ## Settings, geometry and storage diff --git a/README.md b/README.md index d3922ca3d..0de5049f1 100644 --- a/README.md +++ b/README.md @@ -32,8 +32,8 @@ public final class MossModule implements IrisModule { - `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` and `Stage.mantle` create stages for the placement pipeline (once per attempt), the placement pipeline (once per object block), the chunk pipeline (once per chunk, writing only that chunk) and the mantle pipeline (once per chunk, before - the chunks it reaches generate, writing only the mantle). Pass an output class to give a stage a - typed output. + the chunks it reaches generate, writing only the mantle). Pass an output class to give a placement + or chunk stage a typed output; mantle stages have none. - A stage id starts with the id of the module that defines it and `/`: module `example:moss` defines `example:moss/spread`, never `example:other/...`. Module ids therefore contain no `/`. Defining an id twice fails. @@ -98,9 +98,11 @@ stage uses its own stream within one invocation and must not share or keep it. A chunk stage writes only its own chunk: the host may already have generated its neighbors. Work that writes the mantle or reaches beyond its chunk, such as a carver or a vein that runs on into the next -chunk, is a mantle stage. The host runs the mantle pipeline for every chunk within the pipeline's reach -of a chunk before that chunk generates, so the chunk's mantle is complete when its chunk stages read it. -The two pipelines meet only in the mantle. +chunk, is a mantle stage. Every mantle stage is its own pass: before a chunk generates, the host runs +the first mantle stage for every chunk within that stage's reach plus the reach of every later stage, +then the next stage the same way, in resolved order. So a stage sees what earlier stages wrote into the +chunks around it, and the chunk's mantle is complete when its chunk stages read it. Mantle stages have +no outputs: they pass data on through mantle layers. The two pipelines meet only in the mantle. ```java public static final MantleStage CARVE = Stage.mantle("example:caves/carve"); @@ -114,9 +116,27 @@ graph.define(APPLY).run(CaveModule::apply); // reads its own chunk's CAVES and mantle stage, the X/Z bounds of the placed object for a placement stage, whole columns in both cases. It defaults to 0. `writesMantle(...)` names the mantle layers the stage writes; each must be registered by some module. A chunk stage that declares either fails the install, and its mantle is -read-only. `pack.mantle().reach()` and `pack.placement().reach()` give the host the largest reach of a -pipeline and the largest per mantle layer. A mantle stage should not rely on what other mantle stages -wrote in other chunks: whether they have run there yet depends on which chunk the host generates first. +read-only. `pack.placement().reach()` gives the host the largest reach of a pipeline and the largest +per mantle layer. + +When how far a mantle stage writes depends on the pack, such as the longest vein or the largest object +any level configures, it declares a `PackReach` instead of a number. The host works it out from the +pack's settings (`PackSettings.declared(type)`: every entry of the dimension and of the regions and +biomes it can reach) when the pack loads, and asks each mantle stage with +`ResolvedStage.reachBlocks(settings)`. Only mantle stages may declare one. + +```java +graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan); + +static int reach(PackSettings settings) { + int longest = settings.declared(VeinSettings.class).stream().mapToInt(vein -> vein.value().length()).max().orElse(0); + return Math.max(0, longest - 9); // a vein starts at the chunk's centre column +} +``` + +A mantle stage may rely on what earlier stages wrote around its chunk, but not on what a stage of its +own pass wrote in other chunks: whether it has run there yet depends on which chunk the host generates +first. ## Module jars @@ -267,7 +287,10 @@ try (var pack = LoadedPack.load(packRoot, host)) { PlacementOutcome outcome = placer.place(request, edit, inputs, placementSeed, ConfiguredSettings.placement(objectId, stilt, snow)); - new MantleRunner(pack.mantle()).generate(mantleContext, chunkSeed); // each chunk within reach, first + var mantle = new MantleRunner(pack.mantle()); + for (var stage : pack.mantle().stages()) { // each stage its own pass, first + mantle.generate(stage.stage(), mantleContext, chunkSeed); // for each chunk it reaches + } new ChunkRunner(pack.chunk()).generate(generationContext, chunkSeed); } // stop using the runners before the pack closes ``` @@ -420,8 +443,9 @@ concurrent invocations and must not keep views, streams or mutable state. The tests cover graph resolution and every error path, fusion, activation cascade, outputs, rejection and rollback, install-order determinism, id ownership of stages, settings, objects and -mantle keys, reach per stage, pipeline and mantle layer, chunk stages that declare reach or mantle -writes (`StageGraphTest`, `ModuleRegistryTest`), settings entries per type in level order +mantle keys, reach per stage, pipeline and mantle layer, reach worked out when the pack loads (mantle +stages only, never negative), one mantle stage per runner call with activation that follows its +requirements, chunk stages that declare reach or mantle writes (`StageGraphTest`, `ModuleRegistryTest`), settings entries per type in level order (`ConfiguredSettingsTest`), and per-stage random streams: inserting a module that draws leaves the other stages' draws unchanged, block stages draw one stream across their pass, and the derivation is pinned to values computed from its specification (`StageStreamsTest`). @@ -459,5 +483,5 @@ loads and that other internal packages are still reported. `PackModulesSummaryTe ports in `src/test/java/com/volmit/example` rebuild preparation, anchoring, block writes, stilt and snow as separate modules, add a third-party moss module, and add a two-module chunk pipeline whose `ChunkPipelineTest` checks any-column activation, per-column reads, stacked levels, a mantle stage -writing into the next chunk that a chunk stage then reads, and the read-only mantle of chunk stages. There +whose reach follows the pack's longest vein writing into the next chunk that a chunk stage then reads, and the read-only mantle of chunk stages. There is no Minecraft integration or production storage in these tests. diff --git a/src/main/java/com/volmit/config/PackSettings.java b/src/main/java/com/volmit/config/PackSettings.java new file mode 100644 index 000000000..0727a239e --- /dev/null +++ b/src/main/java/com/volmit/config/PackSettings.java @@ -0,0 +1,19 @@ +package com.volmit.config; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import java.util.List; + +/** Every settings declaration of the pack the host is loading, for what depends on the whole pack rather + * than one column, such as how far a mantle stage reaches ({@link com.volmit.stage.PackReach}). + * + *

The levels are those chunk and mantle stages see: the dimension being generated, and every region + * and biome it can reach. Placements are not a level here. Values must be treated as read-only and not + * retained. + */ +public interface PackSettings { + /** Every entry of {@code featureType} the pack declares, dimension first, then regions, then biomes; + * empty when nothing declares it. + */ + List> declared(Class featureType); +} diff --git a/src/main/java/com/volmit/host/ChunkRunner.java b/src/main/java/com/volmit/host/ChunkRunner.java index 60f4d775f..7f2c00bad 100644 --- a/src/main/java/com/volmit/host/ChunkRunner.java +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -27,7 +27,7 @@ public final class ChunkRunner { if (graph.size() == 0) { return; } - var settings = ChunkSettings.collect(graph, inputs::settings, inputs.originX(), inputs.originZ()); + var settings = ChunkSettings.collect(graph.settingsTypes(), inputs::settings, inputs.originX(), inputs.originZ()); 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/ChunkSettings.java b/src/main/java/com/volmit/host/ChunkSettings.java index a510d3b46..762ab526c 100644 --- a/src/main/java/com/volmit/host/ChunkSettings.java +++ b/src/main/java/com/volmit/host/ChunkSettings.java @@ -8,10 +8,11 @@ import com.volmit.resource.ResourceId; import java.util.ArrayList; import java.util.Collection; import java.util.LinkedHashMap; +import java.util.List; import java.util.function.Supplier; -/** The settings one chunk's stages see: for every settings type the graph conditions on, each distinct - * entry of the chunk's 16 by 16 columns. A stage is therefore active when any column of the chunk +/** The settings one chunk's stages see: for every settings type the running stages condition on, each + * distinct entry of the chunk's 16 by 16 columns. A stage is therefore active when any column of the chunk * configures its settings, also where a biome border crosses the chunk. Entries are distinct by level * and source and keep the order their first column was read in, columns by X and then Z. */ @@ -21,14 +22,14 @@ final class ChunkSettings { private ChunkSettings() {} - /** {@code settings} is asked only when the graph conditions a stage on settings. */ - static ConfiguredSettings collect(ResolvedGraph graph, Supplier settings, int originX, int originZ) { - if (graph.settingsTypes().isEmpty()) { + /** {@code settings} is asked only when {@code types} is not empty. */ + static ConfiguredSettings collect(List> types, Supplier settings, int originX, int originZ) { + if (types.isEmpty()) { return ConfiguredSettings.none(); } var view = settings.get(); var entries = new ArrayList>(); - for (var type : graph.settingsTypes()) { + for (var type : types) { entries.addAll(distinctEntries(type.asSubclass(IrisFeature.class), view, originX, originZ)); } return ConfiguredSettings.of(entries); diff --git a/src/main/java/com/volmit/host/FixedReach.java b/src/main/java/com/volmit/host/FixedReach.java new file mode 100644 index 000000000..0f77b3511 --- /dev/null +++ b/src/main/java/com/volmit/host/FixedReach.java @@ -0,0 +1,18 @@ +package com.volmit.host; + +import com.volmit.config.PackSettings; +import com.volmit.stage.PackReach; + +/** A reach declared as a number at install, the same for every pack. */ +record FixedReach(int blocks) implements PackReach { + static final FixedReach NONE = new FixedReach(0); + + FixedReach { + if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks); + } + + @Override + public int blocks(PackSettings settings) { + return blocks; + } +} diff --git a/src/main/java/com/volmit/host/GraphDescription.java b/src/main/java/com/volmit/host/GraphDescription.java index 1bd0e69f8..a08f06b8f 100644 --- a/src/main/java/com/volmit/host/GraphDescription.java +++ b/src/main/java/com/volmit/host/GraphDescription.java @@ -2,6 +2,7 @@ package com.volmit.host; import com.volmit.mantle.MantleKey; import com.volmit.resource.ResourceId; +import com.volmit.stage.PackReach; import com.volmit.stage.StageKind; import java.util.List; import java.util.stream.Collectors; @@ -47,13 +48,20 @@ final class GraphDescription { if (reach.equals(StageReach.NONE)) { return; } - text.append(DETAIL_INDENT).append("reach ").append(reach.blocks()).append(reach.blocks() == 1 ? " block" : " blocks"); + text.append(DETAIL_INDENT).append("reach ").append(reachText(reach.blocks())); if (!reach.mantleLayers().isEmpty()) { text.append(", writes mantle ").append(joined(reach.mantleLayers().stream().map(MantleKey::id).toList())); } text.append('\n'); } + private static String reachText(PackReach reach) { + if (!(reach instanceof FixedReach fixed)) { + return "worked out when the pack loads"; + } + return fixed.blocks() + (fixed.blocks() == 1 ? " block" : " blocks"); + } + private static String kindLabel(ResolvedStage stage, List> passes) { if (stage.stage().kind() == StageKind.INVOCATION) { return "invocation"; diff --git a/src/main/java/com/volmit/host/InvocationStageDraft.java b/src/main/java/com/volmit/host/InvocationStageDraft.java index 069754c72..e5d5272cc 100644 --- a/src/main/java/com/volmit/host/InvocationStageDraft.java +++ b/src/main/java/com/volmit/host/InvocationStageDraft.java @@ -3,6 +3,7 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.mantle.MantleKey; import com.volmit.stage.ConditionalStageDefinition; +import com.volmit.stage.PackReach; import com.volmit.stage.SettingsAction; import com.volmit.stage.SettingsFunction; import com.volmit.stage.Stage; @@ -46,6 +47,12 @@ final class InvocationStageDraft reach(PackReach reach) { + declaration.reach(reach); + return this; + } + @Override public InvocationStageDraft writesMantle(MantleKey... layers) { declaration.writesMantle(layers); diff --git a/src/main/java/com/volmit/host/MantleRunner.java b/src/main/java/com/volmit/host/MantleRunner.java index 269c3aa05..312585da1 100644 --- a/src/main/java/com/volmit/host/MantleRunner.java +++ b/src/main/java/com/volmit/host/MantleRunner.java @@ -2,35 +2,75 @@ package com.volmit.host; import com.volmit.generation.MantleGenerationContext; import com.volmit.stage.Pipeline; +import com.volmit.stage.Stage; +import java.util.BitSet; +import java.util.IdentityHashMap; +import java.util.List; +import java.util.Map; import java.util.Objects; +import java.util.stream.IntStream; -/** Reference executor of a resolved mantle graph: active stages run once per chunk, in resolved order. - * The host runs it for every chunk within the pipeline's reach of a chunk before that chunk generates, - * each chunk once, and gives it the mantle around the chunk as far as that reach. It does not roll back - * mantle writes; a failed invocation must stop the host from generating the chunks it reaches. +/** Reference executor of a resolved mantle graph, one stage at a time. Every mantle stage is its own pass: + * the host runs a stage for every chunk within that stage's reach plus the reach of every later stage of + * a chunk, each chunk once, before the next stage starts, and before that chunk generates. Each call gives + * the stage the mantle around one chunk as far as the stage's own reach. It does not roll back mantle + * writes; a failed invocation must stop the host from generating the chunks it reaches. */ public final class MantleRunner { private final ResolvedGraph graph; + private final Map, Integer> positions = new IdentityHashMap<>(); + private final List>> activationSettings; public MantleRunner(ResolvedGraph graph) { this.graph = Objects.requireNonNull(graph, "graph"); if (graph.pipeline() != Pipeline.MANTLE) { throw new IllegalArgumentException("Expected a mantle graph, got " + graph.pipeline()); } + for (int position = 0; position < graph.size(); position++) { + positions.put(graph.executable(position).stage(), position); + } + activationSettings = activationSettings(graph); } - /** Runs the mantle stages of one chunk. A conditional stage is active when any of the chunk's - * 16 by 16 columns has an entry of its settings, and receives every distinct entry of those columns. - * The host derives {@code invocationSeed} from the world seed and the chunk position. + /** Runs {@code stage} for one chunk, if it is active there. A conditional stage is active when any of + * the chunk's 16 by 16 columns has an entry of its settings, and receives every distinct entry of those + * columns; it is inactive wherever a stage it requires is. The host derives {@code invocationSeed} from + * the world seed and the chunk position; each stage draws from its own stream of it. */ - public void generate(MantleGenerationContext inputs, long invocationSeed) { - if (graph.size() == 0) { - return; - } - var settings = ChunkSettings.collect(graph, inputs::settings, inputs.originX(), inputs.originZ()); + public void generate(Stage stage, MantleGenerationContext inputs, long invocationSeed) { + int position = position(stage); + var settings = ChunkSettings.collect(activationSettings.get(position), inputs::settings, inputs.originX(), inputs.originZ()); var mantle = new MantleInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); - for (int position = 0; position < graph.size(); position++) { - mantle.stages().runInvocationStage(position, mantle); + mantle.stages().runInvocationStage(position, mantle); + } + + private int position(Stage stage) { + Integer position = positions.get(Objects.requireNonNull(stage, "stage")); + if (position == null) { + throw new IllegalArgumentException("Stage " + stage + " is not a stage of this mantle graph"); } + return position; + } + + /** Per position, the settings types that decide whether the stage is active: its own and those of every + * stage it transitively requires, in the graph's order. Requirements come earlier in the order, so one + * forward sweep completes each stage's set before a dependent merges it. + */ + private static List>> activationSettings(ResolvedGraph graph) { + var slots = new BitSet[graph.size()]; + for (int position = 0; position < slots.length; position++) { + var executable = graph.executable(position); + slots[position] = new BitSet(); + if (executable.settingsSlot() != ExecutableStage.NO_SETTINGS) { + slots[position].set(executable.settingsSlot()); + } + for (int requirement : executable.requirements()) { + slots[position].or(slots[requirement]); + } + } + var types = graph.settingsTypes(); + return IntStream.range(0, slots.length) + .mapToObj(position -> slots[position].stream().>mapToObj(types::get).toList()) + .toList(); } } diff --git a/src/main/java/com/volmit/host/PipelineReach.java b/src/main/java/com/volmit/host/PipelineReach.java index 168dba6f4..43d3996cb 100644 --- a/src/main/java/com/volmit/host/PipelineReach.java +++ b/src/main/java/com/volmit/host/PipelineReach.java @@ -18,13 +18,14 @@ public record PipelineReach(int blocks, Map mantleLayers) { mantleLayers = Collections.unmodifiableMap(new TreeMap<>(mantleLayers)); } - static PipelineReach of(Iterable stages) { + static PipelineReach of(Iterable stages) { int blocks = 0; var layers = new TreeMap(); for (var stage : stages) { - blocks = Math.max(blocks, stage.blocks()); - for (var layer : stage.mantleLayers()) { - layers.merge(layer.id(), stage.blocks(), Math::max); + int stageBlocks = stage.fixedReachBlocks(); + blocks = Math.max(blocks, stageBlocks); + for (var layer : stage.reach().mantleLayers()) { + layers.merge(layer.id(), stageBlocks, Math::max); } } return new PipelineReach(blocks, layers); diff --git a/src/main/java/com/volmit/host/ResolvedGraph.java b/src/main/java/com/volmit/host/ResolvedGraph.java index 24f883eff..f7ee4c306 100644 --- a/src/main/java/com/volmit/host/ResolvedGraph.java +++ b/src/main/java/com/volmit/host/ResolvedGraph.java @@ -68,9 +68,13 @@ public final class ResolvedGraph { return pairs; } - /** The most the pipeline's stages write beyond their footprint, overall and per mantle layer. */ + /** The most the pipeline's stages write beyond their footprint, overall and per mantle layer. + * + * @throws IllegalStateException when a mantle stage works out its reach when the pack loads: the host + * runs each mantle stage as its own pass and asks it with {@link ResolvedStage#reachBlocks} + */ public PipelineReach reach() { - return PipelineReach.of(stages.stream().map(ResolvedStage::reach).toList()); + return PipelineReach.of(stages); } /** Human-readable order, owners, edges, block passes and unordered pairs. */ diff --git a/src/main/java/com/volmit/host/ResolvedStage.java b/src/main/java/com/volmit/host/ResolvedStage.java index 54df13ada..8f3c7daf5 100644 --- a/src/main/java/com/volmit/host/ResolvedStage.java +++ b/src/main/java/com/volmit/host/ResolvedStage.java @@ -1,5 +1,6 @@ package com.volmit.host; +import com.volmit.config.PackSettings; import com.volmit.resource.ResourceId; import com.volmit.stage.Stage; import com.volmit.stage.StageRef; @@ -10,7 +11,7 @@ import java.util.Optional; /** Diagnostic view of one stage at its resolved position. incoming lists every edge into this * stage, including soft edges other stages declared; absentSoftTargets lists this stage's soft * references that matched no installed stage and therefore add no ordering. reach is what the stage - * declared it writes beyond its footprint. + * declared it writes beyond its footprint; {@link #reachBlocks(PackSettings)} works it out for a pack. */ public record ResolvedStage( Stage stage, @@ -27,4 +28,29 @@ public record ResolvedStage( incoming = List.copyOf(incoming); absentSoftTargets = List.copyOf(absentSoftTargets); } + + /** How far, in blocks along X and Z, the stage writes beyond its footprint in the pack whose settings + * are {@code settings}: the declared number, or what the stage's {@link com.volmit.stage.PackReach} + * works out. The host asks once per pack load, before generating. + * + * @throws IllegalStateException when the stage works out a negative reach + */ + public int reachBlocks(PackSettings settings) { + Objects.requireNonNull(settings, "settings"); + int blocks = reach.blocks().blocks(settings); + if (blocks < 0) { + throw new IllegalStateException("Stage " + stage + " of module " + module + " worked out a negative reach of " + + blocks + " blocks for this pack"); + } + return blocks; + } + + /** The declared number of blocks; for a pipeline whose reaches do not depend on the pack. */ + int fixedReachBlocks() { + if (!(reach.blocks() instanceof FixedReach fixed)) { + throw new IllegalStateException("Stage " + stage + " of module " + module + " works out its reach when the pack" + + " loads; ask each mantle stage with ResolvedStage.reachBlocks(settings)"); + } + return fixed.blocks(); + } } diff --git a/src/main/java/com/volmit/host/StageDeclaration.java b/src/main/java/com/volmit/host/StageDeclaration.java index 9cf680457..1e7fdaf67 100644 --- a/src/main/java/com/volmit/host/StageDeclaration.java +++ b/src/main/java/com/volmit/host/StageDeclaration.java @@ -3,11 +3,13 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.mantle.MantleKey; import com.volmit.resource.ResourceId; +import com.volmit.stage.PackReach; import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; import com.volmit.stage.StageRef; import java.util.ArrayList; import java.util.List; +import java.util.Locale; import java.util.Objects; import java.util.Optional; @@ -19,7 +21,7 @@ final class StageDeclaration { private final List softAfter = new ArrayList<>(); private final List softBefore = new ArrayList<>(); private FeatureDescriptor settings; - private Integer reachBlocks; + private PackReach reach; private final List> mantleLayers = new ArrayList<>(); private StageBody body; @@ -56,13 +58,34 @@ final class StageDeclaration { void reach(int blocks) { checkOpen(); if (blocks > 0) requireOutsideChunkPipeline("a reach of " + blocks + " blocks"); - if (reachBlocks != null) { - throw new IllegalStateException("Stage " + this + " already declares a reach of " + reachBlocks + " blocks"); - } if (blocks < 0) { throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks"); } - reachBlocks = blocks; + declareReach(new FixedReach(blocks)); + } + + void reach(PackReach computed) { + checkOpen(); + Objects.requireNonNull(computed, "reach"); + if (stage.pipeline() != Pipeline.MANTLE) { + throw new IllegalArgumentException("Stage " + this + " is a " + stage.pipeline().name().toLowerCase(Locale.ROOT) + + " stage and declares a reach worked out when the pack loads, which only mantle stages may;" + + " declare a number of blocks with reach(blocks)"); + } + declareReach(computed); + } + + private void declareReach(PackReach declared) { + if (reach != null) { + throw new IllegalStateException("Stage " + this + " already declares " + describe(reach)); + } + reach = declared; + } + + private static String describe(PackReach reach) { + return reach instanceof FixedReach fixed + ? "a reach of " + fixed.blocks() + " blocks" + : "a reach worked out when the pack loads"; } void writesMantle(MantleKey... layers) { @@ -120,7 +143,7 @@ final class StageDeclaration { } StageReach reach() { - return new StageReach(reachBlocks == null ? 0 : reachBlocks, mantleLayers); + return new StageReach(reach == null ? FixedReach.NONE : reach, mantleLayers); } @Override diff --git a/src/main/java/com/volmit/host/StageReach.java b/src/main/java/com/volmit/host/StageReach.java index bf00521c4..09a6f16ad 100644 --- a/src/main/java/com/volmit/host/StageReach.java +++ b/src/main/java/com/volmit/host/StageReach.java @@ -1,6 +1,7 @@ package com.volmit.host; import com.volmit.mantle.MantleKey; +import com.volmit.stage.PackReach; import java.util.HashSet; import java.util.List; import java.util.Objects; @@ -9,16 +10,17 @@ import java.util.Objects; * * @param blocks how far, in blocks along X and Z, the stage writes blocks or mantle values beyond its * footprint: the chunk's 16 by 16 columns for a mantle stage, the X/Z bounds of the placed object - * for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not limited: the footprint is whole - * columns. + * for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not + * limited: the footprint is whole columns. A number declared at install, or for a mantle stage a + * {@link PackReach} worked out from the pack's settings when the pack loads. * @param mantleLayers the mantle layers the stage writes, each once, in declaration order */ -public record StageReach(int blocks, List> mantleLayers) { +public record StageReach(PackReach blocks, List> mantleLayers) { /** A stage that declared nothing: it writes blocks inside its footprint only, and no mantle layer. */ - public static final StageReach NONE = new StageReach(0, List.of()); + public static final StageReach NONE = new StageReach(FixedReach.NONE, List.of()); public StageReach { - if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks); + Objects.requireNonNull(blocks, "blocks"); mantleLayers = List.copyOf(mantleLayers); var ids = new HashSet(); for (var layer : mantleLayers) { @@ -27,4 +29,9 @@ public record StageReach(int blocks, List> mantleLayers) { } } } + + /** A reach of a number of blocks declared at install. */ + public StageReach(int blocks, List> mantleLayers) { + this(new FixedReach(blocks), mantleLayers); + } } diff --git a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java index f38a5533d..6157b2865 100644 --- a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java +++ b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java @@ -13,6 +13,8 @@ public interface ConditionalStageDefinition reach(int blocks); + ConditionalStageDefinition reach(PackReach reach); + ConditionalStageDefinition writesMantle(MantleKey... layers); void run(SettingsAction action); diff --git a/src/main/java/com/volmit/stage/MantleStage.java b/src/main/java/com/volmit/stage/MantleStage.java index 31c897864..1933995f9 100644 --- a/src/main/java/com/volmit/stage/MantleStage.java +++ b/src/main/java/com/volmit/stage/MantleStage.java @@ -1,6 +1,10 @@ package com.volmit.stage; -/** Runs once per chunk in the mantle pipeline, before the chunks it reaches generate. */ +/** Runs once per chunk in the mantle pipeline, before the chunks it reaches generate. Every mantle stage is + * its own pass: the host runs it for every chunk around a generating chunk before the next stage starts, + * so a stage sees what earlier stages wrote into neighboring chunks. Mantle stages therefore have no + * output; they pass data on through mantle layers. + */ public final class MantleStage extends Stage { MantleStage(String id, Class outputType) { super(id, outputType); diff --git a/src/main/java/com/volmit/stage/PackReach.java b/src/main/java/com/volmit/stage/PackReach.java new file mode 100644 index 000000000..76c15d110 --- /dev/null +++ b/src/main/java/com/volmit/stage/PackReach.java @@ -0,0 +1,13 @@ +package com.volmit.stage; + +import com.volmit.config.PackSettings; + +/** How far a mantle stage writes beyond its chunk, worked out when the pack loads, for work whose size + * depends on the pack, such as the largest object or the longest vein any level configures. The host + * calls it once per pack load, before generating, and prepares that much around every chunk. + */ +@FunctionalInterface +public interface PackReach { + /** Blocks along X and Z beyond the chunk's 16 by 16 columns; never negative. */ + int blocks(PackSettings settings); +} diff --git a/src/main/java/com/volmit/stage/Pipeline.java b/src/main/java/com/volmit/stage/Pipeline.java index 395a390f8..7e2f44710 100644 --- a/src/main/java/com/volmit/stage/Pipeline.java +++ b/src/main/java/com/volmit/stage/Pipeline.java @@ -9,8 +9,9 @@ public enum Pipeline { */ CHUNK, /** Runs once per chunk before any chunk near it generates, against the mantle only: work that writes - * the mantle or reaches beyond its chunk. The host runs it around a chunk as far as the pipeline's - * reach, so a chunk's mantle is complete when the chunk pipeline reads it. + * the mantle or reaches beyond its chunk. The host runs each stage as its own pass, in resolved order, + * around a chunk as far as that stage's reach plus every later stage's, so a chunk's mantle is + * complete when the chunk pipeline reads it. */ MANTLE } diff --git a/src/main/java/com/volmit/stage/Stage.java b/src/main/java/com/volmit/stage/Stage.java index 559a5b4ae..db1b34a36 100644 --- a/src/main/java/com/volmit/stage/Stage.java +++ b/src/main/java/com/volmit/stage/Stage.java @@ -46,14 +46,11 @@ public abstract sealed class Stage permits PlacementStage, BlockStage, ChunkS return new ChunkStage<>(id, outputType); } + /** Mantle stages have no output: each runs as its own pass, so they pass data on through mantle layers. */ public static MantleStage mantle(String id) { return new MantleStage<>(id, Void.class); } - public static MantleStage mantle(String id, Class outputType) { - return new MantleStage<>(id, outputType); - } - public final ResourceId id() { return id; } diff --git a/src/main/java/com/volmit/stage/StageDefinition.java b/src/main/java/com/volmit/stage/StageDefinition.java index 89c21855b..1037d271d 100644 --- a/src/main/java/com/volmit/stage/StageDefinition.java +++ b/src/main/java/com/volmit/stage/StageDefinition.java @@ -18,11 +18,17 @@ public interface StageDefinition { /** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its * footprint: the chunk for a mantle stage, the placed object's X/Z bounds for a placement stage. The - * host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0. + * host prepares that much around every chunk the stage runs for, or every placement. Leaving it out means 0. * Chunk stages write only their own chunk, so a reach above 0 on one fails the install. */ StageDefinition reach(int blocks); + /** Declares a reach the host works out from the pack's settings when the pack loads, for a mantle + * stage whose reach depends on the pack. Only mantle stages may declare one: placement areas and + * chunks are sized without the pack's settings, so it fails the install on any other stage. + */ + StageDefinition reach(PackReach reach); + /** Declares the mantle layers this stage writes; each must be registered by some module. Chunk stages * only read the mantle, so declaring layers on one fails the install. */ diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java index fd0ddc90c..c91a275e4 100644 --- a/src/test/java/com/volmit/example/ChunkPipelineTest.java +++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java @@ -25,6 +25,7 @@ import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; import com.volmit.support.ColumnSettings; +import com.volmit.support.DeclaredSettings; import com.volmit.support.MemoryMantle; import com.volmit.support.TestContexts; import java.util.ArrayList; @@ -135,13 +136,14 @@ class ChunkPipelineTest { @Test void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() { var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of()); - assertEquals(VeinModule.REACH, loaded.mantle().reach().blocks()); - assertEquals(Map.of(VeinModule.ORE.id(), VeinModule.REACH), loaded.mantle().reach().mantleLayers()); + var vein = new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, -60)); + int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein)); + assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk"); var mantle = new MemoryMantle(); - var veins = ColumnSettings.everywhere(new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, -60))); - var reachArea = new BlockBox(-VeinModule.REACH, MIN_Y, -VeinModule.REACH, CHUNK + VeinModule.REACH, MAX_Y, CHUNK + VeinModule.REACH); + var reachArea = new BlockBox(-reach, MIN_Y, -reach, CHUNK + reach, MAX_Y, CHUNK + reach); - new MantleRunner(loaded.mantle()).generate(TestContexts.mantle(0, 0, veins, mantle.within(reachArea)), TestContexts.SEED); + new MantleRunner(loaded.mantle()).generate(VeinModule.PLAN, + TestContexts.mantle(0, 0, ColumnSettings.everywhere(vein), mantle.within(reachArea)), TestContexts.SEED); assertEquals(1, mantle.get(VeinModule.ORE, 18, -60, 7), "the vein runs on into the next chunk"); var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR); diff --git a/src/test/java/com/volmit/example/chunk/VeinModule.java b/src/test/java/com/volmit/example/chunk/VeinModule.java index 73effdec0..aef26b590 100644 --- a/src/test/java/com/volmit/example/chunk/VeinModule.java +++ b/src/test/java/com/volmit/example/chunk/VeinModule.java @@ -5,6 +5,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; import com.volmit.mantle.BlockBox; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; @@ -22,13 +23,14 @@ import java.util.List; /** Work across chunks: a mantle stage plans veins into the mantle, past its own chunk, and a chunk stage * later turns its own chunk's part of the mantle into blocks. The two pipelines meet only in the mantle. + * How far a vein runs past its chunk depends on the longest vein the pack configures, so the stage works + * its reach out when the pack loads. */ public final class VeinModule implements IrisModule { public static final MantleKey ORE = new MantleKey<>("example:veins/ore", Integer.class); public static final MantleStage PLAN = Stage.mantle("example:veins/plan"); public static final ChunkStage PLACE = Stage.chunk("example:veins/place"); public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore"); - public static final int REACH = 16; private static final int CHUNK_WIDTH = 16; private static final int CHUNK_CENTRE = 7; private static final int PLANNED = 1; @@ -40,7 +42,7 @@ public final class VeinModule implements IrisModule { @Override public void install(StageGraph graph) { - graph.define(PLAN).when(VeinSettings.class).reach(REACH).writesMantle(ORE).run(VeinModule::plan); + graph.define(PLAN).when(VeinSettings.class).reach(VeinModule::reach).writesMantle(ORE).run(VeinModule::plan); graph.define(PLACE).run(VeinModule::place); } @@ -49,13 +51,19 @@ public final class VeinModule implements IrisModule { registry.registerMantle(ORE, MantleLifetime.GENERATION, new IntegerCodec()); } + /** How far the longest vein any level of the pack declares runs past its chunk. */ + public static int reach(PackSettings settings) { + int longest = settings.declared(VeinSettings.class).stream().mapToInt(vein -> vein.value().length()).max().orElse(0); + return Math.max(0, longest - (CHUNK_WIDTH - CHUNK_CENTRE)); + } + /** One vein per level that configures veins at the chunk's centre column: levels stack. */ private static void plan(MantleStageContext context, List> inChunk) { int startX = context.originX() + CHUNK_CENTRE; int z = context.originZ() + CHUNK_CENTRE; var ore = context.mantle().layer(ORE); for (var vein : context.settings().at(VeinSettings.class, startX, z)) { - for (int step = 0; step < Math.min(vein.value().length(), REACH + CHUNK_WIDTH - CHUNK_CENTRE); step++) { + for (int step = 0; step < vein.value().length(); step++) { ore.set(startX + step, vein.value().y(), z, PLANNED); } } diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index d4cc23094..11562ff03 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -7,6 +7,7 @@ import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; import com.volmit.config.Feature; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.mantle.BlockBox; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; @@ -24,6 +25,8 @@ import com.volmit.stage.PlacementStage; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; import com.volmit.stage.StageRef; +import com.volmit.support.ColumnSettings; +import com.volmit.support.DeclaredSettings; import com.volmit.support.MemoryEdit; import com.volmit.support.TestContexts; import com.volmit.support.TestTerrain; @@ -486,6 +489,69 @@ class StageGraphTest { assertTrue(loaded.mantle().describe().contains(" reach 8 blocks, writes mantle test:reach/depth, test:reach/marks\n")); } + @Test + void aMantleStageWorksOutItsReachWhenThePackLoads() { + var carve = Stage.mantle("test:reach/carve"); + var mark = Stage.mantle("test:reach/mark"); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> { + stages.define(carve).reach(settings -> settings.declared(Toggle.class).isEmpty() ? 4 : 40).run(context -> {}); + stages.define(mark).reach(2).run(context -> {}); + }))), Map.of(), Set.of(), Set.of()); + var computed = loaded.mantle().stages().getFirst(); + var toggled = new DeclaredSettings(new Entry<>(FeatureAttachment.Target.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle())); + + assertEquals(4, computed.reachBlocks(DeclaredSettings.NONE)); + assertEquals(40, computed.reachBlocks(toggled)); + assertEquals(2, loaded.mantle().stages().get(1).reachBlocks(toggled), "a declared number is the same for every pack"); + assertTrue(loaded.mantle().describe().contains(" reach worked out when the pack loads\n"), loaded.mantle().describe()); + var pipeline = assertThrows(IllegalStateException.class, () -> loaded.mantle().reach()); + assertEquals("Stage test:reach/carve of module test:reach works out its reach when the pack loads;" + + " ask each mantle stage with ResolvedStage.reachBlocks(settings)", pipeline.getMessage()); + } + + @Test + void onlyMantleStagesWorkOutTheirReachAndNeverANegativeOne() { + var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> + stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of()); + var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE)); + assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage()); + + var placement = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:reach", stages -> + stages.define(Stage.placement("test:reach/work")).reach(settings -> 1).run(context -> {})))); + assertEquals("Stage test:reach/work (module test:reach) is a placement stage and declares a reach worked out when the pack" + + " loads, which only mantle stages may; declare a number of blocks with reach(blocks)", placement.getMessage()); + assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, module("test:reach", stages -> + stages.define(Stage.chunk("test:reach/work")).reach(settings -> 0).run(context -> {})))); + var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages -> + stages.define(Stage.mantle("test:reach/carve")).reach(2).reach(settings -> 1).run(context -> {})))); + assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 2 blocks", twice.getMessage()); + } + + @Test + void theMantleRunnerRunsOneStageWhereItAndWhatItRequiresAreActive() { + var toggled = Stage.mantle("test:owner/toggled"); + var follower = Stage.mantle("test:owner/follower"); + var ran = new ArrayList(); + var graph = resolve(Pipeline.MANTLE, module("test:owner", stages -> { + stages.define(toggled).when(Toggle.class).run((context, entries) -> ran.add("toggled")); + stages.define(follower).requires(toggled).run(context -> ran.add("follower")); + })); + var runner = new MantleRunner(graph); + var toggle = new Entry<>(FeatureAttachment.Target.BIOME, ResourceId.parse("pack:biome/plains"), new Toggle()); + var nowhere = TestContexts.mantle(0, 0, ColumnSettings.NONE, null); + var oneColumn = TestContexts.mantle(0, 0, new ColumnSettings((x, z) -> x == 15 && z == 0 ? List.of(toggle) : List.of()), null); + + runner.generate(follower, nowhere, TestContexts.SEED); + assertEquals(List.of(), ran, "a stage whose requirement is inactive in the chunk is inactive too"); + runner.generate(follower, oneColumn, TestContexts.SEED); + assertEquals(List.of("follower"), ran, "only the asked stage runs; its requirement ran in its own pass"); + runner.generate(toggled, oneColumn, TestContexts.SEED); + assertEquals(List.of("follower", "toggled"), ran); + var foreign = assertThrows(IllegalArgumentException.class, + () -> runner.generate(Stage.mantle("test:owner/absent"), nowhere, TestContexts.SEED)); + assertEquals("Stage test:owner/absent is not a stage of this mantle graph", foreign.getMessage()); + } + @Test void reachMustBeValidAndNameRegisteredLayers() { var depth = new MantleKey<>("test:reach/depth", Integer.class); diff --git a/src/test/java/com/volmit/support/DeclaredSettings.java b/src/test/java/com/volmit/support/DeclaredSettings.java new file mode 100644 index 000000000..033b6f2de --- /dev/null +++ b/src/test/java/com/volmit/support/DeclaredSettings.java @@ -0,0 +1,26 @@ +package com.volmit.support; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.config.PackSettings; +import java.util.List; + +/** A pack's settings as a fixed list of declarations, for reach tests. */ +public final class DeclaredSettings implements PackSettings { + public static final DeclaredSettings NONE = new DeclaredSettings(); + + private final List> entries; + + public DeclaredSettings(Entry... entries) { + this.entries = List.of(entries); + } + + @Override + @SuppressWarnings("unchecked") // Filtered by the requested type. + public List> declared(Class featureType) { + return entries.stream() + .filter(entry -> featureType.isInstance(entry.value())) + .map(entry -> (Entry) entry) + .toList(); + } +}