From eeb54860989996c265a4c7c40ef57d576a11cb52 Mon Sep 17 00:00:00 2001 From: piexel Date: Mon, 5 Oct 2026 17:23:31 +0200 Subject: [PATCH] Replace fixed placement hooks with a module-owned stage graph Modules now define every stage themselves through IrisModule.install(StageGraph): typed stage constants, hard requires(...) on other modules' constants, soft ordering by id, when(...) activation and typed outputs. Placement and chunk generation resolve on the same machinery; adjacent per-block stages fuse into one block pass. The host-defined PlacementModifier hooks, string Dependencies, GenerationPlan, PlacementPipeline, DependencyOrder and OccurrenceOrder are removed. --- src/main/java/com/volmit/FeatureRegistry.java | 14 +- src/main/java/com/volmit/IrisModule.java | 14 +- src/main/java/com/volmit/ModuleInfo.java | 19 + .../com/volmit/generation/Dependencies.java | 52 --- .../volmit/generation/GenerationContext.java | 8 +- .../volmit/generation/GenerationModifier.java | 34 -- .../volmit/generation/ModifierFactory.java | 9 - .../java/com/volmit/host/BlockStageDraft.java | 85 ++++ .../java/com/volmit/host/ChunkInvocation.java | 82 ++++ .../java/com/volmit/host/ChunkRunner.java | 27 ++ .../com/volmit/host/ConfiguredModifier.java | 69 --- .../host/ConfiguredPlacementModifier.java | 46 -- .../com/volmit/host/ConfiguredSettings.java | 41 ++ .../java/com/volmit/host/DependencyOrder.java | 144 ------ .../java/com/volmit/host/ExecutableStage.java | 27 ++ .../java/com/volmit/host/FeatureCatalog.java | 41 +- .../com/volmit/host/FeatureDescriptor.java | 32 +- .../java/com/volmit/host/GenerationPlan.java | 91 ---- .../volmit/host/GenerationRegistration.java | 25 -- .../com/volmit/host/GraphDescription.java | 87 ++++ .../java/com/volmit/host/GraphResolver.java | 269 ++++++++++++ .../com/volmit/host/InvocationStageDraft.java | 87 ++++ .../java/com/volmit/host/LoadedModules.java | 34 ++ .../java/com/volmit/host/ModuleRegistry.java | 81 +--- .../java/com/volmit/host/OccurrenceOrder.java | 45 -- .../com/volmit/host/PlacementInvocation.java | 149 +++++++ .../com/volmit/host/PlacementOutcome.java | 29 ++ .../com/volmit/host/PlacementPipeline.java | 374 ---------------- .../volmit/host/PlacementRegistration.java | 20 - .../java/com/volmit/host/PlacementRunner.java | 91 ++++ .../java/com/volmit/host/PlacementViews.java | 2 +- .../java/com/volmit/host/ReadyStages.java | 39 ++ .../java/com/volmit/host/ResolvedGraph.java | 144 ++++++ .../java/com/volmit/host/ResolvedStage.java | 27 ++ src/main/java/com/volmit/host/Segment.java | 8 + src/main/java/com/volmit/host/StageBody.java | 24 + .../com/volmit/host/StageDeclaration.java | 126 ++++++ src/main/java/com/volmit/host/StageEdge.java | 24 + .../com/volmit/host/StageGraphBuilder.java | 125 ++++++ .../java/com/volmit/host/StageInvocation.java | 144 ++++++ .../com/volmit/placement/PlacementAccess.java | 6 +- .../volmit/placement/PlacementContext.java | 6 +- .../volmit/placement/PlacementModifier.java | 24 - .../placement/PlacementModifierFactory.java | 8 - .../com/volmit/placement/PlacementPlan.java | 37 -- .../java/com/volmit/stage/BlockCollector.java | 6 + .../java/com/volmit/stage/BlockStage.java | 20 + .../com/volmit/stage/BlockStageContext.java | 16 + .../volmit/stage/BlockStageDefinition.java | 23 + .../java/com/volmit/stage/ChunkStage.java | 18 + .../com/volmit/stage/ChunkStageContext.java | 6 + .../ConditionalBlockStageDefinition.java | 16 + .../stage/ConditionalStageDefinition.java | 14 + src/main/java/com/volmit/stage/Pipeline.java | 9 + .../java/com/volmit/stage/PlacementStage.java | 18 + .../volmit/stage/PlacementStageContext.java | 20 + .../java/com/volmit/stage/SettingsAction.java | 6 + .../volmit/stage/SettingsBlockCollector.java | 6 + .../com/volmit/stage/SettingsFunction.java | 6 + src/main/java/com/volmit/stage/Stage.java | 73 +++ .../java/com/volmit/stage/StageAction.java | 6 + .../java/com/volmit/stage/StageContext.java | 10 + .../com/volmit/stage/StageDefinition.java | 25 ++ .../java/com/volmit/stage/StageFunction.java | 6 + .../java/com/volmit/stage/StageGraph.java | 15 + src/main/java/com/volmit/stage/StageKind.java | 9 + src/main/java/com/volmit/stage/StageRef.java | 20 + .../java/com/volmit/FeatureContractTest.java | 31 +- .../volmit/generation/DependenciesTest.java | 54 --- .../com/volmit/host/GenerationPlanTest.java | 85 ---- .../com/volmit/host/ModuleRegistryTest.java | 70 ++- .../volmit/host/PlacementPipelineTest.java | 259 ----------- .../java/com/volmit/host/StageGraphTest.java | 415 ++++++++++++++++++ .../java/com/volmit/support/MemoryEdit.java | 93 ++++ .../java/com/volmit/support/TestContexts.java | 29 +- .../java/com/volmit/support/TestTerrain.java | 30 ++ 76 files changed, 2717 insertions(+), 1567 deletions(-) create mode 100644 src/main/java/com/volmit/ModuleInfo.java delete mode 100644 src/main/java/com/volmit/generation/Dependencies.java delete mode 100644 src/main/java/com/volmit/generation/GenerationModifier.java delete mode 100644 src/main/java/com/volmit/generation/ModifierFactory.java create mode 100644 src/main/java/com/volmit/host/BlockStageDraft.java create mode 100644 src/main/java/com/volmit/host/ChunkInvocation.java create mode 100644 src/main/java/com/volmit/host/ChunkRunner.java delete mode 100644 src/main/java/com/volmit/host/ConfiguredModifier.java delete mode 100644 src/main/java/com/volmit/host/ConfiguredPlacementModifier.java create mode 100644 src/main/java/com/volmit/host/ConfiguredSettings.java delete mode 100644 src/main/java/com/volmit/host/DependencyOrder.java create mode 100644 src/main/java/com/volmit/host/ExecutableStage.java delete mode 100644 src/main/java/com/volmit/host/GenerationPlan.java delete mode 100644 src/main/java/com/volmit/host/GenerationRegistration.java create mode 100644 src/main/java/com/volmit/host/GraphDescription.java create mode 100644 src/main/java/com/volmit/host/GraphResolver.java create mode 100644 src/main/java/com/volmit/host/InvocationStageDraft.java create mode 100644 src/main/java/com/volmit/host/LoadedModules.java delete mode 100644 src/main/java/com/volmit/host/OccurrenceOrder.java create mode 100644 src/main/java/com/volmit/host/PlacementInvocation.java create mode 100644 src/main/java/com/volmit/host/PlacementOutcome.java delete mode 100644 src/main/java/com/volmit/host/PlacementPipeline.java delete mode 100644 src/main/java/com/volmit/host/PlacementRegistration.java create mode 100644 src/main/java/com/volmit/host/PlacementRunner.java create mode 100644 src/main/java/com/volmit/host/ReadyStages.java create mode 100644 src/main/java/com/volmit/host/ResolvedGraph.java create mode 100644 src/main/java/com/volmit/host/ResolvedStage.java create mode 100644 src/main/java/com/volmit/host/Segment.java create mode 100644 src/main/java/com/volmit/host/StageBody.java create mode 100644 src/main/java/com/volmit/host/StageDeclaration.java create mode 100644 src/main/java/com/volmit/host/StageEdge.java create mode 100644 src/main/java/com/volmit/host/StageGraphBuilder.java create mode 100644 src/main/java/com/volmit/host/StageInvocation.java delete mode 100644 src/main/java/com/volmit/placement/PlacementModifier.java delete mode 100644 src/main/java/com/volmit/placement/PlacementModifierFactory.java delete mode 100644 src/main/java/com/volmit/placement/PlacementPlan.java create mode 100644 src/main/java/com/volmit/stage/BlockCollector.java create mode 100644 src/main/java/com/volmit/stage/BlockStage.java create mode 100644 src/main/java/com/volmit/stage/BlockStageContext.java create mode 100644 src/main/java/com/volmit/stage/BlockStageDefinition.java create mode 100644 src/main/java/com/volmit/stage/ChunkStage.java create mode 100644 src/main/java/com/volmit/stage/ChunkStageContext.java create mode 100644 src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java create mode 100644 src/main/java/com/volmit/stage/ConditionalStageDefinition.java create mode 100644 src/main/java/com/volmit/stage/Pipeline.java create mode 100644 src/main/java/com/volmit/stage/PlacementStage.java create mode 100644 src/main/java/com/volmit/stage/PlacementStageContext.java create mode 100644 src/main/java/com/volmit/stage/SettingsAction.java create mode 100644 src/main/java/com/volmit/stage/SettingsBlockCollector.java create mode 100644 src/main/java/com/volmit/stage/SettingsFunction.java create mode 100644 src/main/java/com/volmit/stage/Stage.java create mode 100644 src/main/java/com/volmit/stage/StageAction.java create mode 100644 src/main/java/com/volmit/stage/StageContext.java create mode 100644 src/main/java/com/volmit/stage/StageDefinition.java create mode 100644 src/main/java/com/volmit/stage/StageFunction.java create mode 100644 src/main/java/com/volmit/stage/StageGraph.java create mode 100644 src/main/java/com/volmit/stage/StageKind.java create mode 100644 src/main/java/com/volmit/stage/StageRef.java delete mode 100644 src/test/java/com/volmit/generation/DependenciesTest.java delete mode 100644 src/test/java/com/volmit/host/GenerationPlanTest.java delete mode 100644 src/test/java/com/volmit/host/PlacementPipelineTest.java create mode 100644 src/test/java/com/volmit/host/StageGraphTest.java create mode 100644 src/test/java/com/volmit/support/MemoryEdit.java create mode 100644 src/test/java/com/volmit/support/TestTerrain.java diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java index a2174b341..654567789 100644 --- a/src/main/java/com/volmit/FeatureRegistry.java +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -1,16 +1,13 @@ package com.volmit; -import com.volmit.generation.ModifierFactory; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import com.volmit.object.ObjectGeneratorFactory; -import com.volmit.placement.PlacementModifierFactory; -/** Host implementation collects registrations before loading pack configuration. - * Feature IDs must be unique. JSON fields must be unique per attachment target. - * Modifiers own their IDs and dependency declarations, independently of feature IDs. - * All configured instances of a modifier follow the same ordering. +/** Host implementation collects non-stage registrations before loading pack configuration. + * Feature IDs must be unique. JSON fields must be unique per attachment target, including the + * settings types stages name in {@code when(...)}. */ public interface FeatureRegistry { /** Registers a layer before pack loading. Null arguments throw NullPointerException; @@ -21,10 +18,5 @@ public interface FeatureRegistry { */ void registerMantle(MantleKey key, MantleLifetime lifetime, MantleCodec codec); - void register(Class featureType, - Class outputType, ModifierFactory factory); - void registerObject(Class featureType, ObjectGeneratorFactory factory); - - void registerPlacement(Class featureType, PlacementModifierFactory factory); } diff --git a/src/main/java/com/volmit/IrisModule.java b/src/main/java/com/volmit/IrisModule.java index 33c48820f..87475b53c 100644 --- a/src/main/java/com/volmit/IrisModule.java +++ b/src/main/java/com/volmit/IrisModule.java @@ -1,10 +1,16 @@ package com.volmit; +import com.volmit.stage.StageGraph; + +/** A unit of world-generation behavior. The core engine is an ordinary module too. */ public interface IrisModule { + ModuleInfo info(); - String name(); + /** Defines this module's stages, before settings are decoded or generation starts. + * Called once per pack load; stage bodies must not capture per-invocation state. + */ + void install(StageGraph graph); - String displayVersion(); - /** Called during registration, before settings are decoded or generation starts. */ - void register(FeatureRegistry registry); + /** Registers non-stage contributions: geometry generators and mantle layers. */ + default void register(FeatureRegistry registry) {} } diff --git a/src/main/java/com/volmit/ModuleInfo.java b/src/main/java/com/volmit/ModuleInfo.java new file mode 100644 index 000000000..a0814707c --- /dev/null +++ b/src/main/java/com/volmit/ModuleInfo.java @@ -0,0 +1,19 @@ +package com.volmit; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** Module identity. Stages a module defines must use the namespace of its id. */ +public record ModuleInfo(ResourceId id, String version) { + public ModuleInfo { + Objects.requireNonNull(id, "id"); + Objects.requireNonNull(version, "version"); + if (version.isBlank()) { + throw new IllegalArgumentException("Blank module version: " + id); + } + } + + public static ModuleInfo of(String id, String version) { + return new ModuleInfo(ResourceId.parse(id), version); + } +} diff --git a/src/main/java/com/volmit/generation/Dependencies.java b/src/main/java/com/volmit/generation/Dependencies.java deleted file mode 100644 index b8855c0d9..000000000 --- a/src/main/java/com/volmit/generation/Dependencies.java +++ /dev/null @@ -1,52 +0,0 @@ -package com.volmit.generation; - -import java.util.HashSet; -import java.util.Set; -import com.volmit.resource.ResourceId; - -/** Immutable ordering declarations referencing modifier IDs, not feature IDs. - * Requirements must exist and finish first. Optional constraints apply only when present. - * Nothing here activates a feature. The host resolves and validates the graph at pack load. - */ -public record Dependencies(Set required, Set after, Set before) { - public Dependencies { - required = validatedCopy(required); - after = validatedCopy(after); - before = validatedCopy(before); - } - - public static Dependencies none() { - return new Dependencies(Set.of(), Set.of(), Set.of()); - } - - public static Dependencies requires(String... ids) { - return none().andRequires(ids); - } - - /** Adds required predecessors without changing this declaration. */ - public Dependencies andRequires(String... ids) { - return new Dependencies(adding(required, ids), after, before); - } - - public Dependencies afterIfPresent(String... ids) { - return new Dependencies(required, adding(after, ids), before); - } - - public Dependencies beforeIfPresent(String... ids) { - return new Dependencies(required, after, adding(before, ids)); - } - - private static Set adding(Set existing, String[] ids) { - var result = new HashSet<>(existing); - for (String id : ids) result.add(id); - return result; - } - - private static Set validatedCopy(Set ids) { - var copy = Set.copyOf(ids); - for (String id : copy) { - ResourceId.parse(id); - } - return copy; - } -} diff --git a/src/main/java/com/volmit/generation/GenerationContext.java b/src/main/java/com/volmit/generation/GenerationContext.java index 8d08cb192..a308007be 100644 --- a/src/main/java/com/volmit/generation/GenerationContext.java +++ b/src/main/java/com/volmit/generation/GenerationContext.java @@ -1,10 +1,11 @@ package com.volmit.generation; +import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.config.FeatureSettings; import com.volmit.world.TerrainSampler; -/** Per-invocation state. Must not be retained by a modifier after execution. */ +/** Per-invocation chunk generation inputs. Must not be retained after execution. */ public interface GenerationContext extends InvocationContext { /** World block coordinates corresponding to local volume coordinates (0, 0, 0). */ int originX(); @@ -16,4 +17,9 @@ public interface GenerationContext extends InvocationContext { /** Non-null mantle access scoped to this invocation; the host owns its lifetime. */ Mantle mantle(); + + /** The host-owned local volume of the given value type, shared by all stages of this + * invocation. Unsupported types throw IllegalArgumentException. + */ + Hunk hunk(Class type); } diff --git a/src/main/java/com/volmit/generation/GenerationModifier.java b/src/main/java/com/volmit/generation/GenerationModifier.java deleted file mode 100644 index f36f522ce..000000000 --- a/src/main/java/com/volmit/generation/GenerationModifier.java +++ /dev/null @@ -1,34 +0,0 @@ -package com.volmit.generation; - -import com.volmit.hunk.Hunk; - -/** Bound to one configured feature instance. - * Calls may occur concurrently for different volumes. Keep settings read-only and temporary - * state local to modify(). Exceptions propagate: the host must not publish partial output. - */ -public abstract class GenerationModifier { - /** Stable, nonblank namespaced modifier identity, independent of feature identity. - * Configured instances of the same modifier share this ID and dependency declaration. - * Different modifier implementations must not claim the same ID. - */ - public abstract String id(); - - /** Stable requirements read at pack load, not per invocation. Constructors must not - * depend on prerequisite modifiers having run. Ordering does not guarantee that - * a prerequisite changed blocks at the current location. - */ - public Dependencies depends() { - return Dependencies.none(); - } - - /** Nonnegative horizontal reach in blocks beyond the output footprint; zero by default. - * Read once per configured instance at pack load. The host must prepare this area and - * required predecessor work before invocation, bound vertical access to the world, and - * serialize overlapping writes. It must reject negative or unsupported reach, not clip it. - */ - public int mantleRadius() { - return 0; - } - - public abstract void modify(GenerationContext context, Hunk output); -} diff --git a/src/main/java/com/volmit/generation/ModifierFactory.java b/src/main/java/com/volmit/generation/ModifierFactory.java deleted file mode 100644 index 670f8274f..000000000 --- a/src/main/java/com/volmit/generation/ModifierFactory.java +++ /dev/null @@ -1,9 +0,0 @@ -package com.volmit.generation; - -import com.volmit.IrisFeature; - -/** Connects a feature's decoded options to its executable modifier. */ -@FunctionalInterface -public interface ModifierFactory { - GenerationModifier create(F feature); -} diff --git a/src/main/java/com/volmit/host/BlockStageDraft.java b/src/main/java/com/volmit/host/BlockStageDraft.java new file mode 100644 index 000000000..a62c3c5d8 --- /dev/null +++ b/src/main/java/com/volmit/host/BlockStageDraft.java @@ -0,0 +1,85 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import com.volmit.stage.BlockCollector; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.BlockStageDefinition; +import com.volmit.stage.ConditionalBlockStageDefinition; +import com.volmit.stage.SettingsAction; +import com.volmit.stage.SettingsBlockCollector; +import com.volmit.stage.Stage; +import com.volmit.stage.StageAction; +import com.volmit.stage.StageRef; +import java.util.Objects; +import java.util.function.Supplier; + +/** Builder behind both block stage definition views; S is unused until when(...). */ +final class BlockStageDraft + implements BlockStageDefinition, ConditionalBlockStageDefinition { + private final StageDeclaration declaration; + + BlockStageDraft(StageDeclaration declaration) { + this.declaration = declaration; + } + + @Override + public BlockStageDraft requires(Stage... stages) { + declaration.require(stages); + return this; + } + + @Override + public BlockStageDraft softAfter(StageRef... stages) { + declaration.softAfter(stages); + return this; + } + + @Override + public BlockStageDraft softBefore(StageRef... stages) { + declaration.softBefore(stages); + return this; + } + + @Override + @SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here. + public BlockStageDraft when(Class settingsType) { + declaration.condition(settingsType); + return (BlockStageDraft) (BlockStageDraft) this; + } + + @Override + public void run(StageAction action) { + Objects.requireNonNull(action, "action"); + complete(null, (context, settings, accumulator) -> action.run(context)); + } + + @Override + public void accumulate(Supplier initial, BlockCollector collector) { + Objects.requireNonNull(collector, "collector"); + complete(Objects.requireNonNull(initial, "initial"), + (context, settings, accumulator) -> collector.collect(context, cast(accumulator))); + } + + @Override + public void run(SettingsAction action) { + Objects.requireNonNull(action, "action"); + complete(null, (context, settings, accumulator) -> action.run(context, cast(settings))); + } + + @Override + public void accumulate(Supplier initial, SettingsBlockCollector collector) { + Objects.requireNonNull(collector, "collector"); + complete(Objects.requireNonNull(initial, "initial"), + (context, settings, accumulator) -> collector.collect(context, cast(settings), cast(accumulator))); + } + + private void complete(Supplier initial, StageBody.BlockWork work) { + boolean accumulates = initial != null; + declaration.complete(new StageBody.Block(initial, work), accumulates, accumulates ? "run" : "accumulate"); + } + + @SuppressWarnings("unchecked") // The executor passes the settings and accumulator this stage was declared with. + private static T cast(Object value) { + return (T) value; + } +} diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java new file mode 100644 index 000000000..db9dd9abb --- /dev/null +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -0,0 +1,82 @@ +package com.volmit.host; + +import com.volmit.config.FeatureSettings; +import com.volmit.generation.GenerationContext; +import com.volmit.hunk.Hunk; +import com.volmit.mantle.Mantle; +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 { + private final StageInvocation stages; + private final GenerationContext inputs; + + ChunkInvocation(StageInvocation stages, GenerationContext inputs) { + this.stages = stages; + this.inputs = Objects.requireNonNull(inputs, "inputs"); + } + + StageInvocation stages() { + return stages; + } + + @Override + public O output(Stage stage) { + return stages.output(stage); + } + + @Override + public int originX() { + return inputs.originX(); + } + + @Override + public int originY() { + return inputs.originY(); + } + + @Override + public int originZ() { + return inputs.originZ(); + } + + @Override + public TerrainSampler terrain() { + return inputs.terrain(); + } + + @Override + public FeatureSettings settings() { + return inputs.settings(); + } + + @Override + public Mantle mantle() { + return inputs.mantle(); + } + + @Override + public Hunk hunk(Class type) { + return inputs.hunk(type); + } + + @Override + public long worldSeed() { + return inputs.worldSeed(); + } + + @Override + public PackResources resources() { + return inputs.resources(); + } + + @Override + public RandomGenerator random() { + return inputs.random(); + } +} diff --git a/src/main/java/com/volmit/host/ChunkRunner.java b/src/main/java/com/volmit/host/ChunkRunner.java new file mode 100644 index 000000000..dae6a37cd --- /dev/null +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -0,0 +1,27 @@ +package com.volmit.host; + +import com.volmit.generation.GenerationContext; +import com.volmit.stage.Pipeline; +import java.util.Objects; + +/** Reference executor of a resolved chunk graph: active stages run once, in resolved order. + * It does not schedule neighbors or roll back hunks; a failed invocation must prevent the host + * from publishing the chunk. + */ +public final class ChunkRunner { + private final ResolvedGraph graph; + + public ChunkRunner(ResolvedGraph graph) { + this.graph = Objects.requireNonNull(graph, "graph"); + if (graph.pipeline() != Pipeline.CHUNK) { + throw new IllegalArgumentException("Expected a chunk graph, got " + graph.pipeline()); + } + } + + public void generate(GenerationContext inputs, ConfiguredSettings settings) { + var chunk = new ChunkInvocation(new StageInvocation(graph, settings), inputs); + for (int position = 0; position < graph.size(); position++) { + chunk.stages().runInvocationStage(position, chunk); + } + } +} diff --git a/src/main/java/com/volmit/host/ConfiguredModifier.java b/src/main/java/com/volmit/host/ConfiguredModifier.java deleted file mode 100644 index b1a811509..000000000 --- a/src/main/java/com/volmit/host/ConfiguredModifier.java +++ /dev/null @@ -1,69 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.Dependencies; -import com.volmit.generation.GenerationContext; -import com.volmit.generation.GenerationModifier; -import com.volmit.hunk.Hunk; -import com.volmit.resource.ResourceId; -import java.util.Objects; - -/** Pack-load snapshot of modifier identity, requirements, type and prepared reach. - * The occurrence identifies one configuration, independent of its shared ordering identity. - */ -public final class ConfiguredModifier { - private final ResourceId occurrence; - private final Class outputType; - private final GenerationModifier modifier; - private final ResourceId id; - private final Dependencies dependencies; - private final int mantleRadius; - - public ConfiguredModifier( - ResourceId occurrence, - Class outputType, - GenerationModifier modifier) { - this.occurrence = Objects.requireNonNull(occurrence, "occurrence"); - this.outputType = Objects.requireNonNull(outputType, "outputType"); - if (outputType.isPrimitive()) { - throw new IllegalArgumentException("Output requires a reference type"); - } - this.modifier = Objects.requireNonNull(modifier, "modifier"); - id = ResourceId.parse(modifier.id()); - dependencies = Objects.requireNonNull(modifier.depends(), "dependencies"); - mantleRadius = modifier.mantleRadius(); - if (mantleRadius < 0) { - throw new IllegalArgumentException("Negative mantle radius: " + id); - } - } - - public ResourceId occurrence() { - return occurrence; - } - - public Class outputType() { - return outputType; - } - - public ResourceId id() { - return id; - } - - public Dependencies dependencies() { - return dependencies; - } - - public int mantleRadius() { - return mantleRadius; - } - - public Class implementationType() { - return modifier.getClass(); - } - - /** Host must prepare views/predecessor work and abort publication if this throws. */ - public void modify(GenerationContext context, Hunk output) { - modifier.modify( - Objects.requireNonNull(context, "context"), - Objects.requireNonNull(output, "output")); - } -} diff --git a/src/main/java/com/volmit/host/ConfiguredPlacementModifier.java b/src/main/java/com/volmit/host/ConfiguredPlacementModifier.java deleted file mode 100644 index ac5e76394..000000000 --- a/src/main/java/com/volmit/host/ConfiguredPlacementModifier.java +++ /dev/null @@ -1,46 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.Dependencies; -import com.volmit.placement.PlacementModifier; -import com.volmit.resource.ResourceId; -import java.util.Objects; - -/** Pack-load placement declaration snapshot. The configured modifier must be immutable. */ -public final class ConfiguredPlacementModifier { - private final ResourceId occurrence; - private final PlacementModifier modifier; - private final ResourceId id; - private final Dependencies dependencies; - private final int writeRadius; - - public ConfiguredPlacementModifier(ResourceId occurrence, PlacementModifier modifier) { - this.occurrence = Objects.requireNonNull(occurrence, "occurrence"); - this.modifier = Objects.requireNonNull(modifier, "modifier"); - id = ResourceId.parse(modifier.id()); - dependencies = Objects.requireNonNull(modifier.depends(), "dependencies"); - writeRadius = modifier.writeRadius(); - if (writeRadius < 0) { - throw new IllegalArgumentException("Negative placement radius: " + id); - } - } - - public ResourceId occurrence() { - return occurrence; - } - - public PlacementModifier modifier() { - return modifier; - } - - public ResourceId id() { - return id; - } - - public Dependencies dependencies() { - return dependencies; - } - - public int writeRadius() { - return writeRadius; - } -} diff --git a/src/main/java/com/volmit/host/ConfiguredSettings.java b/src/main/java/com/volmit/host/ConfiguredSettings.java new file mode 100644 index 000000000..5840635a9 --- /dev/null +++ b/src/main/java/com/volmit/host/ConfiguredSettings.java @@ -0,0 +1,41 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** Feature settings configured for one invocation: the placement's settings, or the settings + * the host resolved for a chunk. At most one value per type; merging and precedence between + * dimension/region/biome/placement declarations stay host policy. Build once and reuse it for + * every invocation with the same configuration. + */ +public final class ConfiguredSettings { + private static final ConfiguredSettings NONE = new ConfiguredSettings(Map.of()); + + private final Map, IrisFeature> values; + + private ConfiguredSettings(Map, IrisFeature> values) { + this.values = Map.copyOf(values); + } + + public static ConfiguredSettings none() { + return NONE; + } + + public static ConfiguredSettings of(IrisFeature... settings) { + var values = new HashMap, IrisFeature>(); + for (var value : settings) { + Objects.requireNonNull(value, "settings"); + if (values.putIfAbsent(value.getClass(), value) != null) { + throw new IllegalArgumentException("Settings configured twice: " + value.getClass().getName()); + } + } + return new ConfiguredSettings(values); + } + + public Optional find(Class type) { + return Optional.ofNullable(type.cast(values.get(type))); + } +} diff --git a/src/main/java/com/volmit/host/DependencyOrder.java b/src/main/java/com/volmit/host/DependencyOrder.java deleted file mode 100644 index 17661baf6..000000000 --- a/src/main/java/com/volmit/host/DependencyOrder.java +++ /dev/null @@ -1,144 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.Dependencies; -import com.volmit.resource.ResourceId; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.PriorityQueue; -import java.util.Set; -import java.util.TreeSet; - -/** Host-independent ordering of one complete modifier graph. Ready IDs use lexical order, - * independent of discovery. Required IDs must exist. Optional edges apply only when present. - * Self-dependencies and cycles fail. This graph never activates features or permits parallel writes. - */ -public final class DependencyOrder { - private DependencyOrder() {} - - public static List resolve(Map declarations) { - var graph = Map.copyOf(declarations); - var incomingEdges = initializeIncomingEdges(graph.keySet()); - var outgoingEdges = new HashMap>(); - - addDeclaredEdges(graph, incomingEdges, outgoingEdges); - return topologicalOrder(graph, incomingEdges, outgoingEdges); - } - - private static Map initializeIncomingEdges(Set ids) { - var incomingEdges = new HashMap(); - ids.forEach(id -> incomingEdges.put(id, 0)); - return incomingEdges; - } - - private static void addDeclaredEdges( - Map graph, - Map incomingEdges, - Map> outgoingEdges) { - graph.forEach((id, dependencies) -> { - Objects.requireNonNull(dependencies, "dependencies"); - addRequiredEdges(id, dependencies, graph, incomingEdges, outgoingEdges); - addOptionalEdges(id, dependencies, graph, incomingEdges, outgoingEdges); - }); - } - - private static void addRequiredEdges( - ResourceId id, - Dependencies dependencies, - Map graph, - Map incomingEdges, - Map> outgoingEdges) { - for (var name : dependencies.required()) { - var predecessor = ResourceId.parse(name); - if (!graph.containsKey(predecessor)) { - throw new IllegalArgumentException(id + " requires missing modifier " + predecessor); - } - addEdge(predecessor, id, incomingEdges, outgoingEdges); - } - } - - private static void addOptionalEdges( - ResourceId id, - Dependencies dependencies, - Map graph, - Map incomingEdges, - Map> outgoingEdges) { - for (var name : dependencies.after()) { - var predecessor = ResourceId.parse(name); - rejectSelf(id, predecessor); - if (graph.containsKey(predecessor)) { - addEdge(predecessor, id, incomingEdges, outgoingEdges); - } - } - for (var name : dependencies.before()) { - var successor = ResourceId.parse(name); - rejectSelf(id, successor); - if (graph.containsKey(successor)) { - addEdge(id, successor, incomingEdges, outgoingEdges); - } - } - } - - private static List topologicalOrder( - Map graph, - Map incomingEdges, - Map> outgoingEdges) { - var ready = new PriorityQueue(); - incomingEdges.forEach((id, count) -> { - if (count == 0) { - ready.add(id); - } - }); - - var ordered = new ArrayList(graph.size()); - while (!ready.isEmpty()) { - var id = ready.remove(); - ordered.add(id); - releaseSuccessors(id, outgoingEdges, incomingEdges, ready); - } - - if (ordered.size() != graph.size()) { - throw cycleException(graph.keySet(), ordered); - } - return List.copyOf(ordered); - } - - private static void releaseSuccessors( - ResourceId id, - Map> outgoingEdges, - Map incomingEdges, - PriorityQueue ready) { - for (var successor : outgoingEdges.getOrDefault(id, Set.of())) { - int remainingEdges = incomingEdges.compute(successor, (ignored, count) -> count - 1); - if (remainingEdges == 0) { - ready.add(successor); - } - } - } - - private static IllegalArgumentException cycleException(Set ids, List ordered) { - var unresolved = new TreeSet<>(ids); - unresolved.removeAll(ordered); - return new IllegalArgumentException("Modifier dependency cycle: " + unresolved); - } - - private static void rejectSelf(ResourceId id, ResourceId other) { - if (id.equals(other)) { - throw new IllegalArgumentException("Self-dependency: " + id); - } - } - - private static void addEdge( - ResourceId from, - ResourceId to, - Map incomingEdges, - Map> outgoingEdges) { - rejectSelf(from, to); - if (outgoingEdges.computeIfAbsent(from, ignored -> new HashSet<>()).add(to)) { - incomingEdges.compute(to, (ignored, count) -> count + 1); - } - } -} diff --git a/src/main/java/com/volmit/host/ExecutableStage.java b/src/main/java/com/volmit/host/ExecutableStage.java new file mode 100644 index 000000000..c99804a16 --- /dev/null +++ b/src/main/java/com/volmit/host/ExecutableStage.java @@ -0,0 +1,27 @@ +package com.volmit.host; + +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. + */ +record ExecutableStage( + Stage stage, + StageBody body, + int[] requirements, + Stage[] readableStages, + int[] readablePositions, + int settingsSlot) { + static final int NO_SETTINGS = -1; + static final int NOT_READABLE = -1; + + int readablePosition(Stage requested) { + for (int index = 0; index < readableStages.length; index++) { + if (readableStages[index] == requested) { + return readablePositions[index]; + } + } + return NOT_READABLE; + } +} diff --git a/src/main/java/com/volmit/host/FeatureCatalog.java b/src/main/java/com/volmit/host/FeatureCatalog.java index cdee7dd1a..c2fc5d208 100644 --- a/src/main/java/com/volmit/host/FeatureCatalog.java +++ b/src/main/java/com/volmit/host/FeatureCatalog.java @@ -12,34 +12,28 @@ import java.util.function.Function; * Factory and codec implementations must themselves obey their concurrency contracts. */ public final class FeatureCatalog { - private final Map, GenerationRegistration> generation; + private final Map, FeatureDescriptor> settings; private final Map, ObjectRegistration> objects; - private final Map, PlacementRegistration> placement; private final Map> mantle; FeatureCatalog( - Map, GenerationRegistration> generation, + Map, FeatureDescriptor> settings, Map, ObjectRegistration> objects, - Map, PlacementRegistration> placement, Map> mantle) { - this.generation = Map.copyOf(generation); + this.settings = Map.copyOf(settings); this.objects = Map.copyOf(objects); - this.placement = Map.copyOf(placement); this.mantle = Map.copyOf(mantle); } - public List> generation() { - return sorted(generation.values(), registration -> registration.descriptor().id()); + /** Settings types that activate stages; the host decodes them from pack JSON. */ + public List> settings() { + return sorted(settings.values(), FeatureDescriptor::id); } public List> objects() { return sorted(objects.values(), registration -> registration.descriptor().id()); } - public List> placement() { - return sorted(placement.values(), registration -> registration.descriptor().id()); - } - public List> mantle() { return sorted(mantle.values(), registration -> registration.key().id()); } @@ -52,20 +46,6 @@ public final class FeatureCatalog { .toList(); } - @SuppressWarnings("unchecked") // The registry key and output type establish the generic pairing. - public GenerationRegistration generation( - Class type, - Class outputType) { - var registration = generation.get(type); - if (registration == null) { - throw new NoSuchElementException("No generation feature: " + type.getName()); - } - if (!registration.outputType().equals(outputType)) { - throw new IllegalArgumentException("Output type mismatch: " + type.getName()); - } - return (GenerationRegistration) registration; - } - @SuppressWarnings("unchecked") // The registry key is the factory's feature type. public ObjectRegistration object(Class type) { var registration = objects.get(type); @@ -74,13 +54,4 @@ public final class FeatureCatalog { } return (ObjectRegistration) registration; } - - @SuppressWarnings("unchecked") // The registry key is the factory's feature type. - public PlacementRegistration placement(Class type) { - var registration = placement.get(type); - if (registration == null) { - throw new NoSuchElementException("No placement feature: " + type.getName()); - } - return (PlacementRegistration) registration; - } } diff --git a/src/main/java/com/volmit/host/FeatureDescriptor.java b/src/main/java/com/volmit/host/FeatureDescriptor.java index 5976b8faa..5abffd44a 100644 --- a/src/main/java/com/volmit/host/FeatureDescriptor.java +++ b/src/main/java/com/volmit/host/FeatureDescriptor.java @@ -2,11 +2,14 @@ package com.volmit.host; import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; +import com.volmit.config.Feature; import com.volmit.config.OptionsMetadata; import com.volmit.resource.ResourceId; +import java.lang.reflect.Modifier; import java.util.Objects; +import java.util.Set; -/** Validated registration metadata. It describes configuration, not executable ordering. */ +/** Validated settings metadata. It describes configuration, not executable ordering. */ public record FeatureDescriptor( ResourceId id, String name, @@ -23,4 +26,31 @@ public record FeatureDescriptor( Objects.requireNonNull(attachment, "attachment"); Objects.requireNonNull(options, "options"); } + + /** Reads the @Feature declaration of a concrete settings class. */ + public static FeatureDescriptor of(Class type) { + Objects.requireNonNull(type, "featureType"); + requireConcreteFeature(type); + + var annotation = type.getDeclaredAnnotation(Feature.class); + if (annotation == null) { + throw new IllegalArgumentException("Missing @Feature: " + type.getName()); + } + + return new FeatureDescriptor<>( + ResourceId.parse(annotation.id()), + annotation.name(), + type, + new FeatureAttachment(annotation.field(), Set.of(annotation.targets())), + OptionsMetadata.inspect(type)); + } + + private static void requireConcreteFeature(Class type) { + if (!IrisFeature.class.isAssignableFrom(type) + || type.isInterface() + || Modifier.isAbstract(type.getModifiers())) { + throw new IllegalArgumentException( + "Feature type must be a concrete IrisFeature: " + type.getName()); + } + } } diff --git a/src/main/java/com/volmit/host/GenerationPlan.java b/src/main/java/com/volmit/host/GenerationPlan.java deleted file mode 100644 index adf3df316..000000000 --- a/src/main/java/com/volmit/host/GenerationPlan.java +++ /dev/null @@ -1,91 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.Dependencies; -import com.volmit.resource.ResourceId; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Set; - -/** Immutable pack-load ordering across output types. Instances sharing a modifier ID must - * have the same implementation, output type and dependencies. Occurrence IDs must be unique. - * Instances within one identity use lexical occurrence order. Resolve once, dispatch many times. - * The host includes its built-in lifecycle steps in this graph and rejects incompatible edges. - */ -public final class GenerationPlan { - private final List> ordered; - - private GenerationPlan(List> ordered) { - this.ordered = List.copyOf(ordered); - } - - public static GenerationPlan resolve(List> modifiers) { - List> instances = new ArrayList<>(modifiers); - var declarations = collectDeclarations(instances); - var modifierIds = DependencyOrder.resolve(declarations); - var orderedOccurrences = OccurrenceOrder.order( - modifierIds, - instances, - ConfiguredModifier::id, - ConfiguredModifier::occurrence); - return new GenerationPlan(orderedOccurrences); - } - - private static Map collectDeclarations(List> instances) { - var representatives = new HashMap>(); - var occurrences = new HashSet(); - var declarations = new HashMap(); - - for (var modifier : instances) { - checkUniqueOccurrence(modifier, occurrences); - checkCompatibleIdentity(modifier, representatives); - declarations.put(modifier.id(), modifier.dependencies()); - } - return declarations; - } - - private static void checkUniqueOccurrence( - ConfiguredModifier modifier, - Set occurrences) { - if (!occurrences.add(modifier.occurrence())) { - throw new IllegalArgumentException("Duplicate occurrence: " + modifier.occurrence()); - } - } - - private static void checkCompatibleIdentity( - ConfiguredModifier modifier, - Map> representatives) { - var previous = representatives.putIfAbsent(modifier.id(), modifier); - if (previous == null || isCompatible(previous, modifier)) { - return; - } - throw new IllegalArgumentException("Conflicting modifier identity: " + modifier.id()); - } - - private static boolean isCompatible(ConfiguredModifier first, ConfiguredModifier second) { - return first.implementationType().equals(second.implementationType()) - && first.outputType().equals(second.outputType()) - && first.dependencies().equals(second.dependencies()); - } - - public List> ordered() { - return ordered; - } - - /** Sequential dispatch only. Executor prepares/releases a dedicated context and typed output - * for each applicable occurrence; applicability is host-owned. Failures stop dispatch. - * This reference planner does not implement chunk scheduling, rollback or lifecycle bridging. - */ - public void execute(Executor executor) { - java.util.Objects.requireNonNull(executor, "executor"); - for (var modifier : ordered) { - executor.execute(modifier); - } - } - - public interface Executor { - void execute(ConfiguredModifier modifier); - } -} diff --git a/src/main/java/com/volmit/host/GenerationRegistration.java b/src/main/java/com/volmit/host/GenerationRegistration.java deleted file mode 100644 index 95b9a2d73..000000000 --- a/src/main/java/com/volmit/host/GenerationRegistration.java +++ /dev/null @@ -1,25 +0,0 @@ -package com.volmit.host; - -import com.volmit.IrisFeature; -import com.volmit.generation.ModifierFactory; -import com.volmit.resource.ResourceId; -import java.util.Objects; - -public record GenerationRegistration( - FeatureDescriptor descriptor, - Class outputType, - ModifierFactory factory) { - public GenerationRegistration { - Objects.requireNonNull(descriptor, "descriptor"); - Objects.requireNonNull(outputType, "outputType"); - if (outputType.isPrimitive()) { - throw new IllegalArgumentException("Output requires a reference type"); - } - Objects.requireNonNull(factory, "factory"); - } - - public ConfiguredModifier configure(ResourceId occurrence, F feature) { - var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature")); - return new ConfiguredModifier<>(occurrence, outputType, factory.create(configuredFeature)); - } -} diff --git a/src/main/java/com/volmit/host/GraphDescription.java b/src/main/java/com/volmit/host/GraphDescription.java new file mode 100644 index 000000000..b5ad585bf --- /dev/null +++ b/src/main/java/com/volmit/host/GraphDescription.java @@ -0,0 +1,87 @@ +package com.volmit.host; + +import com.volmit.resource.ResourceId; +import com.volmit.stage.StageKind; +import java.util.List; +import java.util.stream.Collectors; + +/** Text rendering of a resolved graph for pack authors and logs. */ +final class GraphDescription { + private static final String INDENT = " "; + private static final String DETAIL_INDENT = " "; + + private GraphDescription() {} + + static String describe(ResolvedGraph graph) { + var text = new StringBuilder(); + var passes = graph.blockPasses(); + text.append(graph.pipeline()).append(" pipeline: ") + .append(graph.stages().size()).append(" stages, ") + .append(passes.size()).append(passes.size() == 1 ? " block pass\n" : " block passes\n"); + appendOrder(text, graph, passes); + appendBlockPasses(text, passes); + appendUnorderedPairs(text, graph.unorderedPairs()); + return text.toString(); + } + + private static void appendOrder(StringBuilder text, ResolvedGraph graph, List> passes) { + text.append("order:\n"); + var stages = graph.stages(); + for (int position = 0; position < stages.size(); position++) { + var stage = stages.get(position); + text.append(INDENT).append(position + 1).append(". ").append(stage.stage().id()) + .append(" [").append(kindLabel(stage, passes)).append("] module ").append(stage.module()); + stage.settings().ifPresent(settings -> text.append(" when ").append(settings.id())); + text.append('\n'); + appendEdges(text, stage.incoming(), StageEdge.Kind.REQUIRED, "requires "); + appendEdges(text, stage.incoming(), StageEdge.Kind.SOFT, "soft after "); + if (!stage.absentSoftTargets().isEmpty()) { + text.append(DETAIL_INDENT).append("absent soft targets ").append(joined(stage.absentSoftTargets())).append('\n'); + } + } + } + + private static String kindLabel(ResolvedStage stage, List> passes) { + if (stage.stage().kind() == StageKind.INVOCATION) { + return "invocation"; + } + for (int pass = 0; pass < passes.size(); pass++) { + if (passes.get(pass).contains(stage.stage().id())) { + return "block pass " + (pass + 1); + } + } + throw new IllegalStateException("Block stage outside every pass: " + stage.stage()); + } + + private static void appendEdges(StringBuilder text, List edges, StageEdge.Kind kind, String label) { + var sources = edges.stream().filter(edge -> edge.kind() == kind).map(StageEdge::from).toList(); + if (sources.isEmpty()) { + return; + } + text.append(DETAIL_INDENT).append(label).append(joined(sources)).append('\n'); + } + + private static void appendBlockPasses(StringBuilder text, List> passes) { + text.append("block passes:\n"); + if (passes.isEmpty()) { + text.append(INDENT).append("none\n"); + } + for (int pass = 0; pass < passes.size(); pass++) { + text.append(INDENT).append("pass ").append(pass + 1).append(": ").append(joined(passes.get(pass))).append('\n'); + } + } + + private static void appendUnorderedPairs(StringBuilder text, List pairs) { + text.append("mutually unordered:\n"); + if (pairs.isEmpty()) { + text.append(INDENT).append("none\n"); + } + for (var pair : pairs) { + text.append(INDENT).append(pair.first()).append(" <-> ").append(pair.second()).append('\n'); + } + } + + private static String joined(List values) { + return values.stream().map(Object::toString).collect(Collectors.joining(", ")); + } +} diff --git a/src/main/java/com/volmit/host/GraphResolver.java b/src/main/java/com/volmit/host/GraphResolver.java new file mode 100644 index 000000000..0f7cf5f71 --- /dev/null +++ b/src/main/java/com/volmit/host/GraphResolver.java @@ -0,0 +1,269 @@ +package com.volmit.host; + +import com.volmit.resource.ResourceId; +import com.volmit.stage.Pipeline; +import com.volmit.stage.Stage; +import com.volmit.stage.StageKind; +import com.volmit.stage.StageRef; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.Collection; +import java.util.Collections; +import java.util.Comparator; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.TreeMap; + +/** Validates and orders the stages of one pipeline. Nodes are numbered in lexical id order, + * which makes every choice below independent of module install order. + */ +final class GraphResolver { + private final Pipeline pipeline; + private final Map installed = new HashMap<>(); + private final List nodes; + private final Map nodeById = new HashMap<>(); + private final List> predecessors = new ArrayList<>(); + private final List> absentSoftTargets = new ArrayList<>(); + + private GraphResolver(Pipeline pipeline, Collection declarations) { + this.pipeline = pipeline; + declarations.forEach(declaration -> installed.put(declaration.stage().id(), declaration)); + nodes = declarations.stream() + .filter(declaration -> declaration.stage().pipeline() == pipeline) + .sorted(Comparator.comparing(declaration -> declaration.stage().id())) + .toList(); + for (int node = 0; node < nodes.size(); node++) { + nodeById.put(nodes.get(node).stage().id(), node); + predecessors.add(new TreeMap<>()); + absentSoftTargets.add(new ArrayList<>()); + } + } + + static ResolvedGraph resolve(Pipeline pipeline, Collection declarations) { + var resolver = new GraphResolver(pipeline, declarations); + resolver.addDeclaredEdges(); + return resolver.toResolvedGraph(resolver.executionOrder()); + } + + private void addDeclaredEdges() { + for (int node = 0; node < nodes.size(); node++) { + addRequiredEdges(node); + addSoftEdges(node); + } + } + + private void addRequiredEdges(int node) { + var declaration = nodes.get(node); + for (var required : declaration.requirements()) { + var target = findRequired(declaration, required); + addEdge(nodeById.get(target.stage().id()), node, StageEdge.Kind.REQUIRED); + } + } + + private void addSoftEdges(int node) { + var declaration = nodes.get(node); + for (var reference : declaration.softAfter()) { + findSoftTarget(declaration, reference).ifPresentOrElse( + target -> addEdge(target, node, StageEdge.Kind.SOFT), + () -> absentSoftTargets.get(node).add(reference)); + } + for (var reference : declaration.softBefore()) { + findSoftTarget(declaration, reference).ifPresentOrElse( + target -> addEdge(node, target, StageEdge.Kind.SOFT), + () -> absentSoftTargets.get(node).add(reference)); + } + } + + private StageDeclaration findRequired(StageDeclaration dependent, Stage required) { + var target = installed.get(required.id()); + if (target == null) { + throw new IllegalArgumentException("Stage " + dependent + " requires " + required + + ", which no installed module defines (expected a module in namespace '" + + required.id().namespace() + "')"); + } + requireSamePipeline(dependent, target); + if (target.stage() != required) { + throw new IllegalArgumentException("Stage " + dependent + " requires a different declaration of " + + target + "; reference the owning module's stage constant"); + } + return target; + } + + private Optional findSoftTarget(StageDeclaration dependent, StageRef reference) { + var target = installed.get(reference.id()); + if (target == null) { + return Optional.empty(); + } + requireSamePipeline(dependent, target); + return Optional.of(nodeById.get(reference.id())); + } + + private void requireSamePipeline(StageDeclaration dependent, StageDeclaration target) { + if (target.stage().pipeline() == pipeline) { + return; + } + throw new IllegalArgumentException("Stage " + dependent + " in pipeline " + pipeline + + " depends on " + target + " in pipeline " + target.stage().pipeline() + + "; dependencies cannot cross pipelines"); + } + + private void addEdge(int from, int to, StageEdge.Kind kind) { + predecessors.get(to).merge(from, kind, StageEdge.Kind::strongest); + } + + private int[] executionOrder() { + int[] waitingOn = new int[nodes.size()]; + var successors = successors(); + var ready = new ReadyStages(); + for (int node = 0; node < nodes.size(); node++) { + waitingOn[node] = predecessors.get(node).size(); + if (waitingOn[node] == 0) { + ready.add(node, kind(node)); + } + } + + int[] order = new int[nodes.size()]; + int ordered = 0; + while (!ready.isEmpty()) { + int node = ready.next(); + order[ordered++] = node; + for (int successor : successors.get(node)) { + if (--waitingOn[successor] == 0) { + ready.add(successor, kind(successor)); + } + } + } + if (ordered != nodes.size()) { + throw cycleError(waitingOn); + } + return order; + } + + private List> successors() { + var successors = new ArrayList>(); + nodes.forEach(ignored -> successors.add(new ArrayList<>())); + for (int node = 0; node < nodes.size(); node++) { + for (int predecessor : predecessors.get(node).keySet()) { + successors.get(predecessor).add(node); + } + } + return successors; + } + + private StageKind kind(int node) { + return nodes.get(node).stage().kind(); + } + + private IllegalArgumentException cycleError(int[] waitingOn) { + var cycle = findCycle(waitingOn); + var description = new StringBuilder(nodes.get(cycle.getFirst()).toString()); + for (int index = 0; index < cycle.size(); index++) { + int from = cycle.get(index); + int to = cycle.get((index + 1) % cycle.size()); + var kind = predecessors.get(to).get(from).name().toLowerCase(); + description.append(" -[").append(kind).append("]-> ").append(nodes.get(to)); + } + return new IllegalArgumentException("Stage cycle in pipeline " + pipeline + ": " + description); + } + + /** Every unordered node still waits on an unordered predecessor, so walking predecessors + * from any of them must revisit a node; the revisited stretch is a cycle. + */ + private List findCycle(int[] waitingOn) { + int current = firstWaiting(waitingOn); + var walk = new ArrayList(); + var walkIndex = new HashMap(); + while (!walkIndex.containsKey(current)) { + walkIndex.put(current, walk.size()); + walk.add(current); + current = firstWaitingPredecessor(current, waitingOn); + } + var cycle = new ArrayList<>(walk.subList(walkIndex.get(current), walk.size())); + Collections.reverse(cycle); + Collections.rotate(cycle, -cycle.indexOf(Collections.min(cycle))); + return cycle; + } + + private static int firstWaiting(int[] waitingOn) { + for (int node = 0; node < waitingOn.length; node++) { + if (waitingOn[node] > 0) { + return node; + } + } + throw new IllegalStateException("No stage is waiting"); + } + + private int firstWaitingPredecessor(int node, int[] waitingOn) { + return predecessors.get(node).keySet().stream() + .filter(predecessor -> waitingOn[predecessor] > 0) + .findFirst() + .orElseThrow(); + } + + private ResolvedGraph toResolvedGraph(int[] order) { + int[] position = new int[order.length]; + for (int index = 0; index < order.length; index++) { + position[order[index]] = index; + } + + var stages = new ArrayList(order.length); + var executables = new ExecutableStage[order.length]; + var readable = new BitSet[order.length]; + var settingsTypes = new ArrayList>(); + for (int index = 0; index < order.length; index++) { + int node = order[index]; + var declaration = nodes.get(node); + int[] requirements = requiredPositions(node, position); + readable[index] = transitiveRequirements(requirements, readable); + executables[index] = new ExecutableStage( + declaration.stage(), + declaration.body(), + requirements, + readable[index].stream().mapToObj(readablePosition -> nodes.get(order[readablePosition]).stage()) + .toArray(Stage[]::new), + readable[index].stream().toArray(), + settingsSlot(declaration, settingsTypes)); + stages.add(new ResolvedStage(declaration.stage(), declaration.module(), declaration.settings(), + incomingEdges(node, position), absentSoftTargets.get(node))); + } + return new ResolvedGraph(pipeline, stages, List.of(executables), settingsTypes); + } + + private int[] requiredPositions(int node, int[] position) { + return predecessors.get(node).entrySet().stream() + .filter(edge -> edge.getValue() == StageEdge.Kind.REQUIRED) + .mapToInt(edge -> position[edge.getKey()]) + .sorted() + .toArray(); + } + + private static BitSet transitiveRequirements(int[] requirements, BitSet[] readable) { + var result = new BitSet(); + for (int required : requirements) { + result.set(required); + result.or(readable[required]); + } + return result; + } + + private static int settingsSlot(StageDeclaration declaration, List> settingsTypes) { + if (declaration.settings().isEmpty()) { + return ExecutableStage.NO_SETTINGS; + } + var type = declaration.settings().orElseThrow().type(); + if (!settingsTypes.contains(type)) { + settingsTypes.add(type); + } + return settingsTypes.indexOf(type); + } + + private List incomingEdges(int node, int[] position) { + var target = nodes.get(node).stage().id(); + return predecessors.get(node).entrySet().stream() + .sorted(Comparator.comparingInt(edge -> position[edge.getKey()])) + .map(edge -> new StageEdge(nodes.get(edge.getKey()).stage().id(), target, edge.getValue())) + .toList(); + } +} diff --git a/src/main/java/com/volmit/host/InvocationStageDraft.java b/src/main/java/com/volmit/host/InvocationStageDraft.java new file mode 100644 index 000000000..a60244311 --- /dev/null +++ b/src/main/java/com/volmit/host/InvocationStageDraft.java @@ -0,0 +1,87 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import com.volmit.stage.ConditionalStageDefinition; +import com.volmit.stage.SettingsAction; +import com.volmit.stage.SettingsFunction; +import com.volmit.stage.Stage; +import com.volmit.stage.StageAction; +import com.volmit.stage.StageContext; +import com.volmit.stage.StageDefinition; +import com.volmit.stage.StageFunction; +import com.volmit.stage.StageRef; +import java.util.Objects; + +/** Builder behind both invocation stage definition views; S is unused until when(...). */ +final class InvocationStageDraft + implements StageDefinition, ConditionalStageDefinition { + private final StageDeclaration declaration; + + InvocationStageDraft(StageDeclaration declaration) { + this.declaration = declaration; + } + + @Override + public InvocationStageDraft requires(Stage... stages) { + declaration.require(stages); + return this; + } + + @Override + public InvocationStageDraft softAfter(StageRef... stages) { + declaration.softAfter(stages); + return this; + } + + @Override + public InvocationStageDraft softBefore(StageRef... stages) { + declaration.softBefore(stages); + return this; + } + + @Override + @SuppressWarnings("unchecked") // S is a phantom parameter until the condition is recorded here. + public InvocationStageDraft when(Class settingsType) { + declaration.condition(settingsType); + return (InvocationStageDraft) (InvocationStageDraft) this; + } + + @Override + public void run(StageAction action) { + Objects.requireNonNull(action, "action"); + complete(false, "produce", (context, settings) -> { + action.run(cast(context)); + return null; + }); + } + + @Override + public void produce(StageFunction function) { + Objects.requireNonNull(function, "function"); + complete(true, "run", (context, settings) -> function.run(cast(context))); + } + + @Override + public void run(SettingsAction action) { + Objects.requireNonNull(action, "action"); + complete(false, "produce", (context, settings) -> { + action.run(cast(context), cast(settings)); + return null; + }); + } + + @Override + public void produce(SettingsFunction function) { + Objects.requireNonNull(function, "function"); + complete(true, "run", (context, settings) -> function.run(cast(context), cast(settings))); + } + + private void complete(boolean producesOutput, String alternativeMethod, StageBody.InvocationWork work) { + declaration.complete(new StageBody.Invocation(work), producesOutput, alternativeMethod); + } + + @SuppressWarnings("unchecked") // The executor passes the context and settings this stage was declared with. + private static T cast(Object value) { + return (T) value; + } +} diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java new file mode 100644 index 000000000..63eea6d50 --- /dev/null +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -0,0 +1,34 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisModule; +import com.volmit.stage.Pipeline; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Everything one pack load derives from its modules: the frozen feature catalog (including the + * settings types stages are conditioned on) and one resolved graph per pipeline. + */ +public record LoadedModules(FeatureCatalog catalog, ResolvedGraph placement, ResolvedGraph chunk) { + public LoadedModules { + Objects.requireNonNull(catalog, "catalog"); + Objects.requireNonNull(placement, "placement"); + Objects.requireNonNull(chunk, "chunk"); + } + + /** Module discovery and version gating stay host work; pass the accepted modules here. */ + public static LoadedModules load( + List modules, + Map> reservedHostFields) { + var registry = new ModuleRegistry(reservedHostFields); + var stages = new StageGraphBuilder(); + for (var module : modules) { + stages.install(module); + module.register(registry); + } + stages.settingsTypes().forEach(registry::registerSettings); + return new LoadedModules(registry.freeze(), stages.resolve(Pipeline.PLACEMENT), stages.resolve(Pipeline.CHUNK)); + } +} diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java index f9b2d52fc..b23cf7a95 100644 --- a/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/src/main/java/com/volmit/host/ModuleRegistry.java @@ -3,16 +3,11 @@ package com.volmit.host; import com.volmit.FeatureAttachment; import com.volmit.FeatureRegistry; import com.volmit.IrisFeature; -import com.volmit.config.Feature; -import com.volmit.config.OptionsMetadata; -import com.volmit.generation.ModifierFactory; import com.volmit.mantle.MantleCodec; import com.volmit.mantle.MantleKey; import com.volmit.mantle.MantleLifetime; import com.volmit.object.ObjectGeneratorFactory; -import com.volmit.placement.PlacementModifierFactory; import com.volmit.resource.ResourceId; -import java.lang.reflect.Modifier; import java.util.HashMap; import java.util.HashSet; import java.util.Map; @@ -26,9 +21,8 @@ import java.util.Set; * This does not decode JSON, discover modules or instantiate settings. */ public final class ModuleRegistry implements FeatureRegistry { - private final Map, GenerationRegistration> generation = new HashMap<>(); + private final Map, FeatureDescriptor> settings = new HashMap<>(); private final Map, ObjectRegistration> objects = new HashMap<>(); - private final Map, PlacementRegistration> placement = new HashMap<>(); private final Map> mantle = new HashMap<>(); private final Set featureIds = new HashSet<>(); private final Set> featureTypes = new HashSet<>(); @@ -43,42 +37,17 @@ public final class ModuleRegistry implements FeatureRegistry { reserveHostFields(reservedFields); } - @Override - public void register( - Class featureType, - Class outputType, - ModifierFactory factory) { - var descriptor = describe(featureType); - var registration = new GenerationRegistration<>(descriptor, outputType, factory); - claim(descriptor); - generation.put(featureType, registration); - } - @Override public void registerObject( Class featureType, ObjectGeneratorFactory factory) { - var descriptor = describe(featureType); + checkOpen(); + var descriptor = FeatureDescriptor.of(featureType); var registration = new ObjectRegistration<>(descriptor, factory); claim(descriptor); objects.put(featureType, registration); } - @Override - public void registerPlacement( - Class featureType, - PlacementModifierFactory factory) { - var descriptor = describe(featureType); - if (!isPlacementFeature(descriptor)) { - throw new IllegalArgumentException( - "Placement modifiers must attach only to OBJECT_PLACEMENT: " + descriptor.id()); - } - - var registration = new PlacementRegistration<>(descriptor, factory); - claim(descriptor); - placement.put(featureType, registration); - } - @Override public void registerMantle(MantleKey key, MantleLifetime lifetime, MantleCodec codec) { checkOpen(); @@ -91,9 +60,20 @@ public final class ModuleRegistry implements FeatureRegistry { } } + /** Claims a settings type named by a stage's when(...). Several stages may share one type. */ + public void registerSettings(Class settingsType) { + checkOpen(); + if (settings.containsKey(settingsType)) { + return; + } + var descriptor = FeatureDescriptor.of(settingsType); + claim(descriptor); + settings.put(settingsType, descriptor); + } + public FeatureCatalog freeze() { if (catalog == null) { - catalog = new FeatureCatalog(generation, objects, placement, mantle); + catalog = new FeatureCatalog(settings, objects, mantle); } return catalog; } @@ -111,37 +91,6 @@ public final class ModuleRegistry implements FeatureRegistry { fields.put(new Field(target, name), "host"); } - private FeatureDescriptor describe(Class type) { - checkOpen(); - Objects.requireNonNull(type, "featureType"); - validateFeatureType(type); - - var annotation = type.getDeclaredAnnotation(Feature.class); - if (annotation == null) { - throw new IllegalArgumentException("Missing @Feature: " + type.getName()); - } - - return new FeatureDescriptor<>( - ResourceId.parse(annotation.id()), - annotation.name(), - type, - new FeatureAttachment(annotation.field(), Set.of(annotation.targets())), - OptionsMetadata.inspect(type)); - } - - private static void validateFeatureType(Class type) { - if (!IrisFeature.class.isAssignableFrom(type) - || type.isInterface() - || Modifier.isAbstract(type.getModifiers())) { - throw new IllegalArgumentException( - "Feature type must be a concrete IrisFeature: " + type.getName()); - } - } - - private static boolean isPlacementFeature(FeatureDescriptor descriptor) { - return descriptor.attachment().targets().equals(Set.of(FeatureAttachment.Target.OBJECT_PLACEMENT)); - } - private void claim(FeatureDescriptor descriptor) { validateClaim(descriptor); recordClaim(descriptor); diff --git a/src/main/java/com/volmit/host/OccurrenceOrder.java b/src/main/java/com/volmit/host/OccurrenceOrder.java deleted file mode 100644 index 312900d54..000000000 --- a/src/main/java/com/volmit/host/OccurrenceOrder.java +++ /dev/null @@ -1,45 +0,0 @@ -package com.volmit.host; - -import com.volmit.resource.ResourceId; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.function.Function; - -/** Orders configured occurrences by dependency identity, then by occurrence ID. */ -final class OccurrenceOrder { - private OccurrenceOrder() {} - - static List order( - List orderedIds, - List occurrences, - Function identity, - Function occurrenceId) { - Map> occurrencesByIdentity = groupByIdentity(occurrences, identity); - var ordered = new ArrayList(occurrences.size()); - - for (var id : orderedIds) { - var group = occurrencesByIdentity.get(id); - if (group == null) { - continue; - } - - group.sort((left, right) -> occurrenceId.apply(left).compareTo(occurrenceId.apply(right))); - ordered.addAll(group); - } - - return List.copyOf(ordered); - } - - private static Map> groupByIdentity( - List occurrences, - Function identity) { - var occurrencesByIdentity = new HashMap>(); - for (var occurrence : occurrences) { - occurrencesByIdentity.computeIfAbsent(identity.apply(occurrence), ignored -> new ArrayList<>()) - .add(occurrence); - } - return occurrencesByIdentity; - } -} diff --git a/src/main/java/com/volmit/host/PlacementInvocation.java b/src/main/java/com/volmit/host/PlacementInvocation.java new file mode 100644 index 000000000..1f75c7ee9 --- /dev/null +++ b/src/main/java/com/volmit/host/PlacementInvocation.java @@ -0,0 +1,149 @@ +package com.volmit.host; + +import com.volmit.config.FeatureSettings; +import com.volmit.object.ObjectBlock; +import com.volmit.object.ObjectTransformer; +import com.volmit.placement.PlacementAccess; +import com.volmit.placement.PlacementContext; +import com.volmit.placement.PlacementRequest; +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. + */ +final class PlacementInvocation implements BlockStageContext { + private enum Progress { RUNNING, REJECTED } + + private enum BlockStatus { OUTSIDE_PASS, VISIBLE, SKIPPED } + + private final StageInvocation stages; + private final PlacementRequest request; + private final PlacementContext inputs; + private final PlacementAccess access; + private Progress progress = Progress.RUNNING; + private String rejection; + private BlockStatus blockStatus = BlockStatus.OUTSIDE_PASS; + private ObjectBlock block; + + PlacementInvocation(StageInvocation stages, PlacementRequest request, PlacementContext inputs, PlacementAccess access) { + this.stages = stages; + this.request = Objects.requireNonNull(request, "request"); + this.inputs = Objects.requireNonNull(inputs, "inputs"); + this.access = access; + } + + StageInvocation stages() { + return stages; + } + + boolean isRejected() { + return progress == Progress.REJECTED; + } + + String rejection() { + return rejection; + } + + void beginBlock(ObjectBlock next) { + block = next; + blockStatus = BlockStatus.VISIBLE; + } + + boolean isBlockSkipped() { + return blockStatus == BlockStatus.SKIPPED; + } + + void endBlockPass() { + block = null; + blockStatus = BlockStatus.OUTSIDE_PASS; + } + + @Override + public O output(Stage stage) { + return stages.output(stage); + } + + @Override + public PlacementRequest request() { + return request; + } + + @Override + public PlacementAccess access() { + return access; + } + + @Override + public void reject(String reason) { + Objects.requireNonNull(reason, "reason"); + if (progress == Progress.RUNNING) { + progress = Progress.REJECTED; + rejection = reason; + } + } + + @Override + public ObjectBlock block() { + requireBlockPass(); + return block; + } + + @Override + public void replace(ObjectBlock replacement) { + requireBlockPass(); + block = Objects.requireNonNull(replacement, "block"); + } + + @Override + public void skip() { + requireBlockPass(); + blockStatus = BlockStatus.SKIPPED; + } + + @Override + public long worldSeed() { + return inputs.worldSeed(); + } + + @Override + public PackResources resources() { + return inputs.resources(); + } + + @Override + public RandomGenerator random() { + return inputs.random(); + } + + @Override + public TerrainSampler terrain() { + return inputs.terrain(); + } + + @Override + public FeatureSettings settings() { + return inputs.settings(); + } + + @Override + public ObjectTransformer objects() { + return inputs.objects(); + } + + @Override + public BlockView blocks() { + return inputs.blocks(); + } + + private void requireBlockPass() { + if (blockStatus == BlockStatus.OUTSIDE_PASS) { + throw new IllegalStateException("The current block is only available to block stages"); + } + } +} diff --git a/src/main/java/com/volmit/host/PlacementOutcome.java b/src/main/java/com/volmit/host/PlacementOutcome.java new file mode 100644 index 000000000..d2f02e996 --- /dev/null +++ b/src/main/java/com/volmit/host/PlacementOutcome.java @@ -0,0 +1,29 @@ +package com.volmit.host; + +import java.util.Objects; +import java.util.Optional; + +/** Result of one placement attempt. A rejected attempt committed nothing. */ +public record PlacementOutcome(Status status, Optional rejection) { + public enum Status { PLACED, REJECTED } + + public PlacementOutcome { + Objects.requireNonNull(status, "status"); + Objects.requireNonNull(rejection, "rejection"); + if ((status == Status.REJECTED) != rejection.isPresent()) { + throw new IllegalArgumentException("Only rejected placements carry a rejection reason"); + } + } + + static PlacementOutcome placed() { + return new PlacementOutcome(Status.PLACED, Optional.empty()); + } + + static PlacementOutcome rejected(String reason) { + return new PlacementOutcome(Status.REJECTED, Optional.of(reason)); + } + + public boolean isPlaced() { + return status == Status.PLACED; + } +} diff --git a/src/main/java/com/volmit/host/PlacementPipeline.java b/src/main/java/com/volmit/host/PlacementPipeline.java deleted file mode 100644 index a872b3bb6..000000000 --- a/src/main/java/com/volmit/host/PlacementPipeline.java +++ /dev/null @@ -1,374 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.Dependencies; -import com.volmit.mantle.BlockBox; -import com.volmit.object.ObjectBlock; -import com.volmit.placement.PlacedBlock; -import com.volmit.placement.PlacedMarker; -import com.volmit.placement.PlacementAccess; -import com.volmit.placement.PlacementContext; -import com.volmit.placement.PlacementEdit; -import com.volmit.placement.PlacementModifier; -import com.volmit.placement.PlacementPlan; -import com.volmit.placement.PlacementRequest; -import com.volmit.resource.ResourceId; -import com.volmit.world.BlockPosition; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.Set; -import java.util.function.Function; -import java.util.function.Predicate; - -/** Reference placement orchestration, resolved at pack load. Same-ID instances must agree on - * implementation and dependencies; occurrences are unique and sorted lexically within an ID. - * The host supplies prepared, serialized storage and enforces platform/placement policies. - * This runner buffers all mapped candidates; host validation must reject collisions or unsupported - * writes before execution. It does not silently skip writes, transform geometry or place live blocks. - */ -public final class PlacementPipeline { - private final List ordered; - - private PlacementPipeline(List ordered) { - this.ordered = List.copyOf(ordered); - } - - public static PlacementPipeline resolve(List modifiers) { - var instances = List.copyOf(modifiers); - var declarations = collectDeclarations(instances); - var modifierIds = DependencyOrder.resolve(declarations); - var orderedOccurrences = OccurrenceOrder.order( - modifierIds, - instances, - ConfiguredPlacementModifier::id, - ConfiguredPlacementModifier::occurrence); - return new PlacementPipeline(orderedOccurrences); - } - - private static Map collectDeclarations( - List instances) { - var representatives = new HashMap(); - var occurrences = new HashSet(); - var declarations = new HashMap(); - - for (var modifier : instances) { - checkUniqueOccurrence(modifier, occurrences); - checkCompatibleIdentity(modifier, representatives); - declarations.put(modifier.id(), modifier.dependencies()); - } - return declarations; - } - - private static void checkUniqueOccurrence( - ConfiguredPlacementModifier modifier, - Set occurrences) { - if (!occurrences.add(modifier.occurrence())) { - throw new IllegalArgumentException("Duplicate placement occurrence: " + modifier.occurrence()); - } - } - - private static void checkCompatibleIdentity( - ConfiguredPlacementModifier modifier, - Map representatives) { - var previous = representatives.putIfAbsent(modifier.id(), modifier); - if (previous == null || isCompatible(previous, modifier)) { - return; - } - throw new IllegalArgumentException("Conflicting placement identity: " + modifier.id()); - } - - private static boolean isCompatible( - ConfiguredPlacementModifier first, - ConfiguredPlacementModifier second) { - return first.modifier().getClass().equals(second.modifier().getClass()) - && first.dependencies().equals(second.dependencies()); - } - - public List ordered() { - return ordered; - } - - public int writeRadius() { - return ordered.stream() - .mapToInt(ConfiguredPlacementModifier::writeRadius) - .max() - .orElse(0); - } - - /** Takes ownership of a fresh edit, closing it on success, rejection or exception. - * Contexts are opened once per occurrence and must use dedicated RNGs from one pack snapshot. - * The caller releases those invocation views after this call. The host must prepare the full - * footprint plus declared reach; a prepare hook that moves outside it fails without clipping. - * hostValidation must be read-only and covers collisions, support, protection, state/payload - * validity and any policies beyond modifier validation. Callbacks must not commit the edit. - */ - public Optional place( - PlacementRequest request, - PlacementEdit edit, - Function contexts, - Predicate hostValidation) { - Objects.requireNonNull(edit, "edit"); - try (edit) { - requireInputs(request, contexts, hostValidation); - var invocations = openInvocations(contexts); - var preparedRequest = prepareAll(request, invocations); - if (preparedRequest.isEmpty()) { - return Optional.empty(); - } - - var prepared = preparedRequest.orElseThrow(); - checkPreparedArea(prepared, edit); - var plan = createPlan(prepared, invocations, edit); - if (!validatePlan(plan, invocations, hostValidation)) { - return Optional.empty(); - } - - var hooks = openHookInvocations(prepared, invocations, edit); - runBeforeHooks(plan, hooks); - writePlan(plan, edit); - runAfterHooks(plan, hooks); - edit.commit(); - return Optional.of(plan); - } - } - - private static void requireInputs( - PlacementRequest request, - Function contexts, - Predicate hostValidation) { - Objects.requireNonNull(request, "request"); - Objects.requireNonNull(contexts, "contexts"); - Objects.requireNonNull(hostValidation, "hostValidation"); - } - - private List openInvocations( - Function contexts) { - var invocations = new ArrayList(ordered.size()); - for (var modifier : ordered) { - var context = Objects.requireNonNull(contexts.apply(modifier), "context"); - invocations.add(new PlacementInvocation(modifier, context)); - } - return List.copyOf(invocations); - } - - private static Optional prepareAll( - PlacementRequest initialRequest, - List invocations) { - var attemptId = initialRequest.id(); - var request = initialRequest; - - for (var invocation : invocations) { - var prepared = Objects.requireNonNull( - invocation.modifier().modifier().prepare(invocation.context(), request), - "prepared request"); - if (prepared.isEmpty()) { - return Optional.empty(); - } - - request = prepared.orElseThrow(); - if (!request.id().equals(attemptId)) { - throw new IllegalArgumentException("Prepare must preserve placement attempt ID"); - } - } - return Optional.of(request); - } - - private PlacementPlan createPlan( - PlacementRequest request, - List invocations, - PlacementEdit edit) { - var blocks = mapBlocks(request, invocations); - var markers = mapMarkers(request); - var plan = new PlacementPlan(request, blocks, markers); - - // Compute checked half-open bounds before any mutation, including integer extremes. - plan.writtenBounds(); - validateMappedPositions(plan, request, edit, writeRadius()); - return plan; - } - - private static List mapBlocks( - PlacementRequest request, - List invocations) { - var mappedBlocks = new ArrayList(); - for (var block : request.object().blocks()) { - var mapped = mapBlock(request, block, invocations); - mapped.ifPresent(mappedBlocks::add); - } - return mappedBlocks; - } - - private static Optional mapBlock( - PlacementRequest request, - ObjectBlock block, - List invocations) { - Optional mapped = Optional.of(new PlacedBlock( - request.worldPosition(block.position()), - block.state(), - block.blockEntity())); - - for (var invocation : invocations) { - var modifier = invocation.modifier().modifier(); - var next = Objects.requireNonNull( - modifier.mapBlock(invocation.context(), mapped.orElseThrow()), - "mapped block"); - if (next.isEmpty()) { - return Optional.empty(); - } - mapped = next; - } - return mapped; - } - - private static List mapMarkers(PlacementRequest request) { - var markers = new ArrayList(); - for (var marker : request.object().markers()) { - markers.add(new PlacedMarker( - request.worldPosition(marker.position()), - marker.type(), - marker.attributes())); - } - return markers; - } - - private static void validateMappedPositions( - PlacementPlan plan, - PlacementRequest request, - PlacementEdit edit, - int radius) { - for (var block : plan.blocks()) { - checkPosition(block.position(), request.footprint(), edit.bounds(), radius); - } - for (var marker : plan.markers()) { - checkPosition(marker.position(), request.footprint(), edit.bounds(), radius); - } - } - - private static boolean validatePlan( - PlacementPlan plan, - List invocations, - Predicate hostValidation) { - if (!hostValidation.test(plan)) { - return false; - } - for (var invocation : invocations) { - if (!invocation.modifier().modifier().validate(invocation.context(), plan)) { - return false; - } - } - return true; - } - - private List openHookInvocations( - PlacementRequest request, - List invocations, - PlacementEdit edit) { - var hooks = new ArrayList(invocations.size()); - for (var invocation : invocations) { - var access = hookAccess(invocation.modifier(), request, edit); - hooks.add(new HookInvocation(invocation, access)); - } - return List.copyOf(hooks); - } - - private static void runBeforeHooks(PlacementPlan plan, List hooks) { - for (var hook : hooks) { - hook.invocation().modifier().modifier().beforePlace( - hook.invocation().context(), - hook.access(), - plan); - } - } - - private static void writePlan(PlacementPlan plan, PlacementEdit edit) { - for (var block : plan.blocks()) { - edit.set(block); - } - for (var marker : plan.markers()) { - edit.marker(marker); - } - } - - private static void runAfterHooks(PlacementPlan plan, List hooks) { - for (var hook : hooks) { - hook.invocation().modifier().modifier().afterPlace( - hook.invocation().context(), - hook.access(), - plan); - } - } - - private static PlacementAccess hookAccess( - ConfiguredPlacementModifier modifier, - PlacementRequest request, - PlacementEdit edit) { - var footprint = request.footprint(); - int radius = modifier.writeRadius(); - var bounds = new BlockBox( - Math.subtractExact(footprint.minX(), radius), - edit.bounds().minY(), - Math.subtractExact(footprint.minZ(), radius), - Math.addExact(footprint.maxX(), radius), - edit.bounds().maxY(), - Math.addExact(footprint.maxZ(), radius)); - return PlacementViews.restrict(edit, bounds); - } - - private void checkPreparedArea(PlacementRequest request, PlacementEdit edit) { - var footprint = request.footprint(); - var preparedBounds = edit.bounds(); - if (!preparedBounds.contains(footprint) - || !containsHorizontalReach(preparedBounds, footprint, writeRadius())) { - throw new IndexOutOfBoundsException("Placement footprint/reach outside prepared bounds"); - } - } - - private static void checkPosition( - BlockPosition position, - BlockBox footprint, - BlockBox preparedBounds, - int radius) { - if (!preparedBounds.contains(position.x(), position.y(), position.z()) - || !isWithinHorizontalReach(position.x(), position.z(), footprint, radius)) { - throw new IndexOutOfBoundsException("Mapped placement write outside declared reach: " + position); - } - } - - private static boolean containsHorizontalReach(BlockBox outer, BlockBox footprint, int radius) { - return containsReachOnAxis(outer.minX(), outer.maxX(), footprint.minX(), footprint.maxX(), radius) - && containsReachOnAxis(outer.minZ(), outer.maxZ(), footprint.minZ(), footprint.maxZ(), radius); - } - - private static boolean isWithinHorizontalReach( - int x, - int z, - BlockBox footprint, - int radius) { - return isWithinReachOnAxis(x, footprint.minX(), footprint.maxX(), radius) - && isWithinReachOnAxis(z, footprint.minZ(), footprint.maxZ(), radius); - } - - private static boolean containsReachOnAxis( - int outerMin, - int outerMax, - int footprintMin, - int footprintMax, - int radius) { - return (long) footprintMin - radius >= outerMin - && (long) footprintMax + radius <= outerMax; - } - - private static boolean isWithinReachOnAxis(int position, int min, int max, int radius) { - return position >= (long) min - radius && position < (long) max + radius; - } - - private record PlacementInvocation( - ConfiguredPlacementModifier modifier, - PlacementContext context) {} - - private record HookInvocation(PlacementInvocation invocation, PlacementAccess access) {} -} diff --git a/src/main/java/com/volmit/host/PlacementRegistration.java b/src/main/java/com/volmit/host/PlacementRegistration.java deleted file mode 100644 index aa951fee9..000000000 --- a/src/main/java/com/volmit/host/PlacementRegistration.java +++ /dev/null @@ -1,20 +0,0 @@ -package com.volmit.host; - -import com.volmit.IrisFeature; -import com.volmit.placement.PlacementModifierFactory; -import com.volmit.resource.ResourceId; -import java.util.Objects; - -public record PlacementRegistration( - FeatureDescriptor descriptor, - PlacementModifierFactory factory) { - public PlacementRegistration { - Objects.requireNonNull(descriptor, "descriptor"); - Objects.requireNonNull(factory, "factory"); - } - - public ConfiguredPlacementModifier configure(ResourceId occurrence, F feature) { - var configuredFeature = descriptor.type().cast(Objects.requireNonNull(feature, "feature")); - return new ConfiguredPlacementModifier(occurrence, factory.create(configuredFeature)); - } -} diff --git a/src/main/java/com/volmit/host/PlacementRunner.java b/src/main/java/com/volmit/host/PlacementRunner.java new file mode 100644 index 000000000..af6223e75 --- /dev/null +++ b/src/main/java/com/volmit/host/PlacementRunner.java @@ -0,0 +1,91 @@ +package com.volmit.host; + +import com.volmit.placement.PlacementContext; +import com.volmit.placement.PlacementEdit; +import com.volmit.placement.PlacementRequest; +import com.volmit.stage.Pipeline; +import java.util.Objects; + +/** Reference executor of a resolved placement graph. It runs active stages in resolved order; + * each fused block pass loops once over the request object's blocks and runs every active stage + * of the pass for a block before moving to the next block. A rejection stops the attempt after + * the current stage or block; the edit is committed only when no stage rejects or throws. + */ +public final class PlacementRunner { + private final ResolvedGraph graph; + + public PlacementRunner(ResolvedGraph graph) { + this.graph = Objects.requireNonNull(graph, "graph"); + if (graph.pipeline() != Pipeline.PLACEMENT) { + throw new IllegalArgumentException("Expected a placement graph, got " + graph.pipeline()); + } + } + + /** 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. + */ + public PlacementOutcome place( + PlacementRequest request, + PlacementEdit edit, + PlacementContext inputs, + ConfiguredSettings settings) { + Objects.requireNonNull(edit, "edit"); + try (edit) { + var stages = new StageInvocation(graph, settings); + var access = PlacementViews.restrict(edit, edit.bounds()); + var placement = new PlacementInvocation(stages, request, inputs, access); + runSegments(placement); + if (placement.isRejected()) { + return PlacementOutcome.rejected(placement.rejection()); + } + edit.commit(); + return PlacementOutcome.placed(); + } + } + + private void runSegments(PlacementInvocation placement) { + for (var segment : graph.segments()) { + if (placement.isRejected()) { + return; + } + switch (segment.kind()) { + case INVOCATION -> placement.stages().runInvocationStage(segment.start(), placement); + case BLOCK -> runBlockPass(segment, placement); + } + } + } + + private static void runBlockPass(Segment segment, PlacementInvocation placement) { + var stages = placement.stages(); + int[] active = stages.activePositions(segment); + if (active.length == 0) { + return; + } + var accumulators = new Object[active.length]; + for (int index = 0; index < active.length; index++) { + accumulators[index] = stages.newAccumulator(active[index]); + } + + for (var block : placement.request().object().blocks()) { + placement.beginBlock(block); + runBlockStages(active, accumulators, placement); + if (placement.isRejected()) { + return; + } + } + placement.endBlockPass(); + for (int index = 0; index < active.length; index++) { + stages.complete(active[index], accumulators[index]); + } + } + + private static void runBlockStages(int[] active, Object[] accumulators, PlacementInvocation placement) { + for (int index = 0; index < active.length; index++) { + placement.stages().runBlockStage(active[index], placement, accumulators[index]); + if (placement.isRejected() || placement.isBlockSkipped()) { + return; + } + } + } +} diff --git a/src/main/java/com/volmit/host/PlacementViews.java b/src/main/java/com/volmit/host/PlacementViews.java index 0d88c55d7..e0ca1ba2a 100644 --- a/src/main/java/com/volmit/host/PlacementViews.java +++ b/src/main/java/com/volmit/host/PlacementViews.java @@ -13,7 +13,7 @@ import com.volmit.placement.PlacementAccess; import com.volmit.placement.PlacementEdit; import java.util.Objects; -/** Internal hook views: limit horizontal reach and hide transaction ownership. */ +/** Internal stage views: bound access to an area and hide transaction ownership. */ final class PlacementViews { private PlacementViews() {} diff --git a/src/main/java/com/volmit/host/ReadyStages.java b/src/main/java/com/volmit/host/ReadyStages.java new file mode 100644 index 000000000..c6b2a2279 --- /dev/null +++ b/src/main/java/com/volmit/host/ReadyStages.java @@ -0,0 +1,39 @@ +package com.volmit.host; + +import com.volmit.stage.StageKind; +import java.util.PriorityQueue; + +/** Choice among stages whose predecessors have all run. Node numbers follow lexical stage id + * order, so each queue yields the lexically smallest ready stage. To keep block passes fused, + * an open pass continues while a block stage is ready, and ready invocation stages run before + * a new pass opens. The choice depends only on ids and edges, never on install order. + */ +final class ReadyStages { + private final PriorityQueue invocation = new PriorityQueue<>(); + private final PriorityQueue block = new PriorityQueue<>(); + private boolean blockPassOpen; + + void add(int node, StageKind kind) { + queue(kind).add(node); + } + + boolean isEmpty() { + return invocation.isEmpty() && block.isEmpty(); + } + + int next() { + if (blockPassOpen && !block.isEmpty()) { + return block.remove(); + } + if (!invocation.isEmpty()) { + blockPassOpen = false; + return invocation.remove(); + } + blockPassOpen = true; + return block.remove(); + } + + private PriorityQueue queue(StageKind kind) { + return kind == StageKind.BLOCK ? block : invocation; + } +} diff --git a/src/main/java/com/volmit/host/ResolvedGraph.java b/src/main/java/com/volmit/host/ResolvedGraph.java new file mode 100644 index 000000000..1282f481b --- /dev/null +++ b/src/main/java/com/volmit/host/ResolvedGraph.java @@ -0,0 +1,144 @@ +package com.volmit.host; + +import com.volmit.resource.ResourceId; +import com.volmit.stage.Pipeline; +import com.volmit.stage.StageKind; +import java.util.ArrayList; +import java.util.BitSet; +import java.util.HashMap; +import java.util.List; +import java.util.Objects; + +/** Immutable, validated order of one pipeline, resolved once per pack load. Adjacent block + * stages form one fused block pass; any invocation stage between them splits the pass, even + * when that stage is inactive for a particular invocation. Execution never sorts or hashes. + */ +public final class ResolvedGraph { + private final Pipeline pipeline; + private final List stages; + private final List executables; + private final List> settingsTypes; + private final List segments; + + ResolvedGraph( + Pipeline pipeline, + List stages, + List executables, + List> settingsTypes) { + this.pipeline = Objects.requireNonNull(pipeline, "pipeline"); + this.stages = List.copyOf(stages); + this.executables = List.copyOf(executables); + this.settingsTypes = List.copyOf(settingsTypes); + segments = segments(this.executables); + } + + public Pipeline pipeline() { + return pipeline; + } + + /** Stages in execution order. */ + public List stages() { + return stages; + } + + /** Each fused block pass as stage ids in execution order. */ + public List> blockPasses() { + return segments.stream() + .filter(segment -> segment.kind() == StageKind.BLOCK) + .map(segment -> stages.subList(segment.start(), segment.end()).stream() + .map(stage -> stage.stage().id()) + .toList()) + .toList(); + } + + /** Pairs with no path between them in either direction, first stage earlier in the order. + * Their relative order comes only from the deterministic tie-break, so a pack author should + * check that they do not conflict. + */ + public List unorderedPairs() { + var reachable = reachability(); + var pairs = new ArrayList(); + for (int first = 0; first < stages.size(); first++) { + for (int second = first + 1; second < stages.size(); second++) { + if (!reachable[first].get(second)) { + pairs.add(new UnorderedPair(id(first), id(second))); + } + } + } + return pairs; + } + + /** Human-readable order, owners, edges, block passes and unordered pairs. */ + public String describe() { + return GraphDescription.describe(this); + } + + int size() { + return executables.size(); + } + + ExecutableStage executable(int position) { + return executables.get(position); + } + + List segments() { + return segments; + } + + List> settingsTypes() { + return settingsTypes; + } + + private ResourceId id(int position) { + return stages.get(position).stage().id(); + } + + /** Edges always point forward in the order, so a reverse sweep completes each stage's + * reachable set before any predecessor merges it. + */ + private BitSet[] reachability() { + var positions = new HashMap(); + var reachable = new BitSet[stages.size()]; + for (int position = 0; position < stages.size(); position++) { + positions.put(id(position), position); + reachable[position] = new BitSet(); + } + for (int position = stages.size() - 1; position >= 0; position--) { + for (var edge : stages.get(position).incoming()) { + int predecessor = positions.get(edge.from()); + reachable[predecessor].set(position); + reachable[predecessor].or(reachable[position]); + } + } + return reachable; + } + + private static List segments(List executables) { + var segments = new ArrayList(); + int position = 0; + while (position < executables.size()) { + int end = segmentEnd(executables, position); + segments.add(new Segment(executables.get(position).stage().kind(), position, end)); + position = end; + } + return List.copyOf(segments); + } + + private static int segmentEnd(List executables, int start) { + if (executables.get(start).stage().kind() != StageKind.BLOCK) { + return start + 1; + } + int end = start + 1; + while (end < executables.size() && executables.get(end).stage().kind() == StageKind.BLOCK) { + end++; + } + return end; + } + + public record UnorderedPair(ResourceId first, ResourceId second) { + public UnorderedPair { + Objects.requireNonNull(first, "first"); + Objects.requireNonNull(second, "second"); + } + } +} diff --git a/src/main/java/com/volmit/host/ResolvedStage.java b/src/main/java/com/volmit/host/ResolvedStage.java new file mode 100644 index 000000000..1fcce5ce4 --- /dev/null +++ b/src/main/java/com/volmit/host/ResolvedStage.java @@ -0,0 +1,27 @@ +package com.volmit.host; + +import com.volmit.resource.ResourceId; +import com.volmit.stage.Stage; +import com.volmit.stage.StageRef; +import java.util.List; +import java.util.Objects; +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. + */ +public record ResolvedStage( + Stage stage, + ResourceId module, + Optional> settings, + List incoming, + List absentSoftTargets) { + public ResolvedStage { + Objects.requireNonNull(stage, "stage"); + Objects.requireNonNull(module, "module"); + Objects.requireNonNull(settings, "settings"); + incoming = List.copyOf(incoming); + absentSoftTargets = List.copyOf(absentSoftTargets); + } +} diff --git a/src/main/java/com/volmit/host/Segment.java b/src/main/java/com/volmit/host/Segment.java new file mode 100644 index 000000000..a26268c52 --- /dev/null +++ b/src/main/java/com/volmit/host/Segment.java @@ -0,0 +1,8 @@ +package com.volmit.host; + +import com.volmit.stage.StageKind; + +/** Positions [start, end) of the resolved order. An INVOCATION segment holds one stage; + * a BLOCK segment is one fused block pass. + */ +record Segment(StageKind kind, int start, int end) {} diff --git a/src/main/java/com/volmit/host/StageBody.java b/src/main/java/com/volmit/host/StageBody.java new file mode 100644 index 000000000..fd6221300 --- /dev/null +++ b/src/main/java/com/volmit/host/StageBody.java @@ -0,0 +1,24 @@ +package com.volmit.host; + +import com.volmit.stage.BlockStageContext; +import java.util.function.Supplier; + +/** Type-erased stage work. Drafts build the body matching their stage kind, so executors may + * rely on invocation stages carrying Invocation bodies and block stages carrying Block bodies. + */ +sealed interface StageBody { + record Invocation(InvocationWork work) implements StageBody {} + + /** initial is null for block stages without an accumulator. */ + record Block(Supplier initial, BlockWork work) implements StageBody {} + + @FunctionalInterface + interface InvocationWork { + Object run(Object context, Object settings); + } + + @FunctionalInterface + interface BlockWork { + void run(BlockStageContext context, Object settings, Object accumulator); + } +} diff --git a/src/main/java/com/volmit/host/StageDeclaration.java b/src/main/java/com/volmit/host/StageDeclaration.java new file mode 100644 index 000000000..11dd753d2 --- /dev/null +++ b/src/main/java/com/volmit/host/StageDeclaration.java @@ -0,0 +1,126 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import com.volmit.resource.ResourceId; +import com.volmit.stage.Stage; +import com.volmit.stage.StageRef; +import java.util.ArrayList; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + +/** One stage as declared during install. It becomes immutable once its body is set. */ +final class StageDeclaration { + private final Stage stage; + private final ResourceId module; + private final List> requirements = new ArrayList<>(); + private final List softAfter = new ArrayList<>(); + private final List softBefore = new ArrayList<>(); + private FeatureDescriptor settings; + private StageBody body; + + StageDeclaration(Stage stage, ResourceId module) { + this.stage = Objects.requireNonNull(stage, "stage"); + this.module = Objects.requireNonNull(module, "module"); + } + + void require(Stage... stages) { + checkOpen(); + for (var required : stages) { + Objects.requireNonNull(required, "required stage"); + rejectSelfReference(required.id()); + requirements.add(required); + } + } + + void softAfter(StageRef... references) { + addSoftReferences(softAfter, references); + } + + void softBefore(StageRef... references) { + addSoftReferences(softBefore, references); + } + + void condition(Class settingsType) { + checkOpen(); + if (settings != null) { + throw new IllegalStateException("Stage " + this + " already has a when(...) condition"); + } + settings = FeatureDescriptor.of(settingsType); + } + + /** Sets the only body. alternativeMethod names the builder method for the other output kind. */ + void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) { + checkOpen(); + Objects.requireNonNull(body, "body"); + if (bodyProducesOutput != stage.producesOutput()) { + throw new IllegalStateException(bodyMismatch(alternativeMethod)); + } + this.body = body; + } + + boolean isComplete() { + return body != null; + } + + Stage stage() { + return stage; + } + + ResourceId module() { + return module; + } + + List> requirements() { + return List.copyOf(requirements); + } + + List softAfter() { + return List.copyOf(softAfter); + } + + List softBefore() { + return List.copyOf(softBefore); + } + + Optional> settings() { + return Optional.ofNullable(settings); + } + + StageBody body() { + return body; + } + + @Override + public String toString() { + return stage.id() + " (module " + module + ")"; + } + + private void addSoftReferences(List target, StageRef... references) { + checkOpen(); + for (var reference : references) { + Objects.requireNonNull(reference, "stage reference"); + rejectSelfReference(reference.id()); + target.add(reference); + } + } + + private void rejectSelfReference(ResourceId id) { + if (stage.id().equals(id)) { + throw new IllegalArgumentException("Stage " + this + " cannot depend on itself"); + } + } + + private String bodyMismatch(String alternativeMethod) { + var declared = stage.producesOutput() + ? "declares output " + stage.outputType().getSimpleName() + : "declares no output"; + return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)"; + } + + private void checkOpen() { + if (body != null) { + throw new IllegalStateException("Stage " + this + " is already complete"); + } + } +} diff --git a/src/main/java/com/volmit/host/StageEdge.java b/src/main/java/com/volmit/host/StageEdge.java new file mode 100644 index 000000000..b7c95d2c9 --- /dev/null +++ b/src/main/java/com/volmit/host/StageEdge.java @@ -0,0 +1,24 @@ +package com.volmit.host; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** A resolved ordering edge: from runs before to. */ +public record StageEdge(ResourceId from, ResourceId to, Kind kind) { + public enum Kind { + /** Declared with requires(...): orders, exposes output and cascades deactivation. */ + REQUIRED, + /** Declared with softAfter/softBefore against an installed stage: ordering only. */ + SOFT; + + Kind strongest(Kind other) { + return this == REQUIRED || other == REQUIRED ? REQUIRED : SOFT; + } + } + + public StageEdge { + Objects.requireNonNull(from, "from"); + Objects.requireNonNull(to, "to"); + Objects.requireNonNull(kind, "kind"); + } +} diff --git a/src/main/java/com/volmit/host/StageGraphBuilder.java b/src/main/java/com/volmit/host/StageGraphBuilder.java new file mode 100644 index 000000000..15c1b36c8 --- /dev/null +++ b/src/main/java/com/volmit/host/StageGraphBuilder.java @@ -0,0 +1,125 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import com.volmit.IrisModule; +import com.volmit.resource.ResourceId; +import com.volmit.stage.BlockStage; +import com.volmit.stage.BlockStageDefinition; +import com.volmit.stage.ChunkStage; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.Pipeline; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.PlacementStageContext; +import com.volmit.stage.Stage; +import com.volmit.stage.StageDefinition; +import com.volmit.stage.StageGraph; +import java.util.Comparator; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** Reference host collection of module stages. Install every module, then resolve each pipeline + * once per pack load. Install order never affects the result. If a module's install throws, + * discard the whole builder: it may hold a partial module. + */ +public final class StageGraphBuilder implements StageGraph { + private final Map declarations = new HashMap<>(); + private final Set modules = new HashSet<>(); + private ResourceId installingModule; + + public void install(IrisModule module) { + Objects.requireNonNull(module, "module"); + var moduleId = Objects.requireNonNull(module.info(), "module info").id(); + claimModule(moduleId); + installingModule = moduleId; + try { + module.install(this); + } finally { + installingModule = null; + } + requireCompleteDefinitions(moduleId); + } + + @Override + public StageDefinition define(PlacementStage stage) { + return new InvocationStageDraft<>(declare(stage)); + } + + @Override + public BlockStageDefinition define(BlockStage stage) { + return new BlockStageDraft<>(declare(stage)); + } + + @Override + public StageDefinition define(ChunkStage stage) { + return new InvocationStageDraft<>(declare(stage)); + } + + public ResolvedGraph resolve(Pipeline pipeline) { + Objects.requireNonNull(pipeline, "pipeline"); + return GraphResolver.resolve(pipeline, declarations.values()); + } + + /** Settings types named by when(...), ordered by feature id. */ + public List> settingsTypes() { + return declarations.values().stream() + .flatMap(declaration -> declaration.settings().stream()) + .distinct() + .sorted(Comparator.comparing(FeatureDescriptor::id)) + .>map(FeatureDescriptor::type) + .toList(); + } + + private void claimModule(ResourceId moduleId) { + if (installingModule != null) { + throw new IllegalStateException("Module " + moduleId + " installed during " + installingModule); + } + if (!modules.add(moduleId)) { + throw new IllegalArgumentException("Duplicate module: " + moduleId); + } + } + + private StageDeclaration declare(Stage stage) { + Objects.requireNonNull(stage, "stage"); + var module = requireInstallingModule(stage); + requireModuleNamespace(stage, module); + + var declaration = new StageDeclaration(stage, module); + var previous = declarations.putIfAbsent(stage.id(), declaration); + if (previous != null) { + throw new IllegalArgumentException("Duplicate definition of stage " + stage.id() + " by module " + + module + "; already defined by module " + previous.module()); + } + return declaration; + } + + private ResourceId requireInstallingModule(Stage stage) { + if (installingModule == null) { + throw new IllegalStateException("Stage " + stage + " defined outside IrisModule.install"); + } + return installingModule; + } + + private static void requireModuleNamespace(Stage stage, ResourceId module) { + if (!stage.id().namespace().equals(module.namespace())) { + throw new IllegalArgumentException("Stage " + stage + " must use namespace '" + + module.namespace() + "' of its defining module " + module); + } + } + + private void requireCompleteDefinitions(ResourceId moduleId) { + declarations.values().stream() + .filter(declaration -> declaration.module().equals(moduleId)) + .filter(declaration -> !declaration.isComplete()) + .map(StageDeclaration::toString) + .sorted() + .findFirst() + .ifPresent(incomplete -> { + throw new IllegalStateException("Stage " + incomplete + + " has no body; end its definition with run, produce or accumulate"); + }); + } +} diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java new file mode 100644 index 000000000..3dfb32ffd --- /dev/null +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -0,0 +1,144 @@ +package com.volmit.host; + +import com.volmit.IrisFeature; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.Stage; +import java.util.Arrays; +import java.util.Objects; +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. + */ +final class StageInvocation { + private static final Object PENDING = new Object(); + private static final int NO_STAGE = -1; + + private final ResolvedGraph graph; + private final Object[] settingsBySlot; + private final boolean[] active; + private final Object[] outputs; + private int current = NO_STAGE; + + StageInvocation(ResolvedGraph graph, 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); + } + + boolean isActive(int position) { + return active[position]; + } + + int[] activePositions(Segment segment) { + return IntStream.range(segment.start(), segment.end()) + .filter(position -> active[position]) + .toArray(); + } + + void runInvocationStage(int position, Object context) { + if (!active[position]) { + return; + } + var executable = graph.executable(position); + var work = ((StageBody.Invocation) executable.body()).work(); + current = position; + var output = work.run(context, settings(executable)); + current = NO_STAGE; + complete(position, requireDeclaredOutput(executable, output)); + } + + Object newAccumulator(int position) { + var initial = ((StageBody.Block) graph.executable(position).body()).initial(); + if (initial == null) { + return null; + } + return Objects.requireNonNull(initial.get(), () -> "Stage " + graph.executable(position).stage() + + " created a null accumulator"); + } + + void runBlockStage(int position, BlockStageContext context, Object accumulator) { + var executable = graph.executable(position); + var work = ((StageBody.Block) executable.body()).work(); + current = position; + work.run(context, settings(executable), accumulator); + current = NO_STAGE; + } + + void complete(int position, Object output) { + outputs[position] = output; + } + + @SuppressWarnings("unchecked") // Bodies are typed by their stage, so the stored output matches O. + O output(Stage stage) { + Objects.requireNonNull(stage, "stage"); + var reader = currentStage(); + int position = reader.readablePosition(stage); + if (position == ExecutableStage.NOT_READABLE) { + throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage + + " without requiring it; add requires(" + stage + ") to its definition"); + } + if (outputs[position] == PENDING) { + throw new IllegalStateException("Stage " + reader.stage() + " read the output of " + stage + + " before it completed; block stage outputs are available after their block pass"); + } + return (O) outputs[position]; + } + + private ExecutableStage currentStage() { + if (current == NO_STAGE) { + throw new IllegalStateException("Stage outputs can only be read while a stage runs"); + } + return graph.executable(current); + } + + private Object settings(ExecutableStage executable) { + int slot = executable.settingsSlot(); + return slot == ExecutableStage.NO_SETTINGS ? null : settingsBySlot[slot]; + } + + private static Object requireDeclaredOutput(ExecutableStage executable, Object output) { + if (output == null && executable.stage().producesOutput()) { + throw new NullPointerException("Stage " + executable.stage() + " produced a null output"); + } + return output; + } + + @SuppressWarnings("unchecked") // Settings types come from when(Class). + private static Object[] lookUpSettings(ResolvedGraph graph, ConfiguredSettings settings) { + var types = graph.settingsTypes(); + var values = new Object[types.size()]; + for (int slot = 0; slot < values.length; slot++) { + values[slot] = settings.find((Class) types.get(slot)).orElse(null); + } + return values; + } + + private static boolean[] activation(ResolvedGraph graph, Object[] settingsBySlot) { + var active = new boolean[graph.size()]; + for (int position = 0; position < active.length; position++) { + var executable = graph.executable(position); + active[position] = isConfigured(executable, settingsBySlot) && requirementsActive(executable, active); + } + return active; + } + + private static boolean isConfigured(ExecutableStage executable, Object[] settingsBySlot) { + int slot = executable.settingsSlot(); + return slot == ExecutableStage.NO_SETTINGS || settingsBySlot[slot] != null; + } + + private static boolean requirementsActive(ExecutableStage executable, boolean[] active) { + for (int requirement : executable.requirements()) { + if (!active[requirement]) { + return false; + } + } + return true; + } +} diff --git a/src/main/java/com/volmit/placement/PlacementAccess.java b/src/main/java/com/volmit/placement/PlacementAccess.java index 261e5cdb5..f7a4c46a3 100644 --- a/src/main/java/com/volmit/placement/PlacementAccess.java +++ b/src/main/java/com/volmit/placement/PlacementAccess.java @@ -3,9 +3,9 @@ package com.volmit.placement; import com.volmit.mantle.Mantle; import com.volmit.world.BlockView; -/** Buffered world-space access for placement hooks, without ownership of commit/close. - * Reads include the overlay. Bounds cover the object's footprint plus declared horizontal reach - * and host-authorized vertical area. Block/entity/marker/mantle writes share the host edit. +/** Buffered world-space access for placement stages, without ownership of commit/close. + * Reads include the overlay. Bounds are the host-prepared placement area. + * Block/entity/marker/mantle writes share the host edit. * Out-of-area access throws; nested mantle edits are unsupported. Do not retain this view. */ public interface PlacementAccess extends BlockView { diff --git a/src/main/java/com/volmit/placement/PlacementContext.java b/src/main/java/com/volmit/placement/PlacementContext.java index ff556b81e..bc9d53722 100644 --- a/src/main/java/com/volmit/placement/PlacementContext.java +++ b/src/main/java/com/volmit/placement/PlacementContext.java @@ -6,13 +6,13 @@ import com.volmit.object.ObjectTransformer; import com.volmit.world.TerrainSampler; import com.volmit.world.BlockView; -/** Read-only inputs to placement hooks. Working state is carried by returned immutable requests - * and blocks, never stored on a configured modifier. Context lifetime ends with placement. +/** Host-supplied, read-only inputs of one placement attempt. Working state is carried by stage + * outputs, never stored on a module or stage body. Context lifetime ends with the placement. */ public interface PlacementContext extends InvocationContext { TerrainSampler terrain(); FeatureSettings settings(); ObjectTransformer objects(); - /** Prepared blocks before this placement. Use hook access for reads of buffered changes. */ + /** Prepared blocks before this placement. Use stage access for reads of buffered changes. */ BlockView blocks(); } diff --git a/src/main/java/com/volmit/placement/PlacementModifier.java b/src/main/java/com/volmit/placement/PlacementModifier.java deleted file mode 100644 index 08c38b017..000000000 --- a/src/main/java/com/volmit/placement/PlacementModifier.java +++ /dev/null @@ -1,24 +0,0 @@ -package com.volmit.placement; - -import com.volmit.generation.Dependencies; -import java.util.Optional; - -/** Configured placement behavior. IDs are namespaced; dependencies refer only to placement - * modifier IDs, not chunk modifiers. Snapshot settings; calls may occur concurrently. - * The host runs prepare for all modifiers, mapBlock for each candidate, then validate for all - * modifiers before buffering any write. beforePlace runs after validation but before object - * writes, for boring/preparation. afterPlace runs only after all accepted blocks and - * markers are buffered, allowing vacuum/stilts to observe the final footprint and overlay. - * Exceptions discard the attempt. Empty prepare rejects it; empty mapBlock skips one block. - */ -public abstract class PlacementModifier { - public abstract String id(); - public Dependencies depends() { return Dependencies.none(); } - /** Horizontal access beyond the resulting object footprint; nonnegative, read at pack load. */ - public int writeRadius() { return 0; } - public Optional prepare(PlacementContext context, PlacementRequest request) { return Optional.of(request); } - public Optional mapBlock(PlacementContext context, PlacedBlock block) { return Optional.of(block); } - public boolean validate(PlacementContext context, PlacementPlan plan) { return true; } - public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan proposed) {} - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) {} -} diff --git a/src/main/java/com/volmit/placement/PlacementModifierFactory.java b/src/main/java/com/volmit/placement/PlacementModifierFactory.java deleted file mode 100644 index 4f5f9c224..000000000 --- a/src/main/java/com/volmit/placement/PlacementModifierFactory.java +++ /dev/null @@ -1,8 +0,0 @@ -package com.volmit.placement; - -import com.volmit.IrisFeature; - -@FunctionalInterface -public interface PlacementModifierFactory { - PlacementModifier create(F feature); -} diff --git a/src/main/java/com/volmit/placement/PlacementPlan.java b/src/main/java/com/volmit/placement/PlacementPlan.java deleted file mode 100644 index 359fb95cf..000000000 --- a/src/main/java/com/volmit/placement/PlacementPlan.java +++ /dev/null @@ -1,37 +0,0 @@ -package com.volmit.placement; - -import com.volmit.mantle.BlockBox; -import com.volmit.world.BlockPosition; -import java.util.Comparator; -import java.util.HashSet; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - -/** Complete proposed writes, constructed before validation or mutation. - * Block positions are unique and ordered x/y/z. writtenBounds describes block writes only; - * markers and the original object's declared footprint are tracked separately. - */ -public record PlacementPlan(PlacementRequest request, List blocks, List markers) { - public PlacementPlan { - Objects.requireNonNull(request, "request"); - blocks = List.copyOf(blocks).stream().sorted(Comparator.comparing(PlacedBlock::position)).toList(); - markers = List.copyOf(markers).stream().sorted(Comparator.comparing(PlacedMarker::position)).toList(); - var positions = new HashSet(); - for (var block : blocks) { - if (!positions.add(block.position())) throw new IllegalArgumentException("Duplicate placement write: " + block.position()); - } - } - - public Optional writtenBounds() { - if (blocks.isEmpty()) return Optional.empty(); - int minX = Integer.MAX_VALUE, minY = Integer.MAX_VALUE, minZ = Integer.MAX_VALUE; - int maxX = Integer.MIN_VALUE, maxY = Integer.MIN_VALUE, maxZ = Integer.MIN_VALUE; - for (var block : blocks) { - var position = block.position(); - minX = Math.min(minX, position.x()); minY = Math.min(minY, position.y()); minZ = Math.min(minZ, position.z()); - maxX = Math.max(maxX, position.x()); maxY = Math.max(maxY, position.y()); maxZ = Math.max(maxZ, position.z()); - } - return Optional.of(new BlockBox(minX, minY, minZ, Math.addExact(maxX, 1), Math.addExact(maxY, 1), Math.addExact(maxZ, 1))); - } -} diff --git a/src/main/java/com/volmit/stage/BlockCollector.java b/src/main/java/com/volmit/stage/BlockCollector.java new file mode 100644 index 000000000..5b419019b --- /dev/null +++ b/src/main/java/com/volmit/stage/BlockCollector.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface BlockCollector { + void collect(BlockStageContext context, O accumulator); +} diff --git a/src/main/java/com/volmit/stage/BlockStage.java b/src/main/java/com/volmit/stage/BlockStage.java new file mode 100644 index 000000000..caf78110c --- /dev/null +++ b/src/main/java/com/volmit/stage/BlockStage.java @@ -0,0 +1,20 @@ +package com.volmit.stage; + +/** Runs once per object block of a placement. Block stages that are adjacent in the resolved + * order share one loop over the object's blocks; a placement stage between them splits the pass. + */ +public final class BlockStage extends Stage { + BlockStage(String id, Class accumulatorType) { + super(id, accumulatorType); + } + + @Override + public Pipeline pipeline() { + return Pipeline.PLACEMENT; + } + + @Override + public StageKind kind() { + return StageKind.BLOCK; + } +} diff --git a/src/main/java/com/volmit/stage/BlockStageContext.java b/src/main/java/com/volmit/stage/BlockStageContext.java new file mode 100644 index 000000000..43ea4cc3c --- /dev/null +++ b/src/main/java/com/volmit/stage/BlockStageContext.java @@ -0,0 +1,16 @@ +package com.volmit.stage; + +import com.volmit.object.ObjectBlock; + +/** The current object block of a block pass, in object-local coordinates. Every pass starts + * from the request's object blocks; replacements and skips are visible only to later stages + * of the same pass for the same block. + */ +public interface BlockStageContext extends PlacementStageContext { + ObjectBlock block(); + + void replace(ObjectBlock block); + + /** Later stages of this pass do not see the current block. */ + void skip(); +} diff --git a/src/main/java/com/volmit/stage/BlockStageDefinition.java b/src/main/java/com/volmit/stage/BlockStageDefinition.java new file mode 100644 index 000000000..ac19f1bd7 --- /dev/null +++ b/src/main/java/com/volmit/stage/BlockStageDefinition.java @@ -0,0 +1,23 @@ +package com.volmit.stage; + +import com.volmit.IrisFeature; +import java.util.function.Supplier; + +/** Declares one per-block placement stage. Requiring another block stage orders the two per + * block within a fused pass. A block stage's accumulator becomes readable only after its pass. + */ +public interface BlockStageDefinition { + BlockStageDefinition requires(Stage... stages); + + BlockStageDefinition softAfter(StageRef... stages); + + BlockStageDefinition softBefore(StageRef... stages); + + ConditionalBlockStageDefinition when(Class settingsType); + + /** Body for a block stage without accumulator. */ + void run(StageAction action); + + /** Body for a block stage whose accumulator, created once per placement, is its output. */ + void accumulate(Supplier initial, BlockCollector collector); +} diff --git a/src/main/java/com/volmit/stage/ChunkStage.java b/src/main/java/com/volmit/stage/ChunkStage.java new file mode 100644 index 000000000..e1d67c662 --- /dev/null +++ b/src/main/java/com/volmit/stage/ChunkStage.java @@ -0,0 +1,18 @@ +package com.volmit.stage; + +/** Runs once per chunk generation invocation. */ +public final class ChunkStage extends Stage { + ChunkStage(String id, Class outputType) { + super(id, outputType); + } + + @Override + public Pipeline pipeline() { + return Pipeline.CHUNK; + } + + @Override + public StageKind kind() { + return StageKind.INVOCATION; + } +} diff --git a/src/main/java/com/volmit/stage/ChunkStageContext.java b/src/main/java/com/volmit/stage/ChunkStageContext.java new file mode 100644 index 000000000..dda9d0d2d --- /dev/null +++ b/src/main/java/com/volmit/stage/ChunkStageContext.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +import com.volmit.generation.GenerationContext; + +/** One chunk generation invocation with access to the host's typed local hunks. */ +public interface ChunkStageContext extends GenerationContext, StageContext {} diff --git a/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java new file mode 100644 index 000000000..04222aa23 --- /dev/null +++ b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java @@ -0,0 +1,16 @@ +package com.volmit.stage; + +import java.util.function.Supplier; + +/** A block stage active only where its settings are configured; bodies receive them. */ +public interface ConditionalBlockStageDefinition { + ConditionalBlockStageDefinition requires(Stage... stages); + + ConditionalBlockStageDefinition softAfter(StageRef... stages); + + ConditionalBlockStageDefinition softBefore(StageRef... stages); + + void run(SettingsAction action); + + void accumulate(Supplier initial, SettingsBlockCollector collector); +} diff --git a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java new file mode 100644 index 000000000..29bc1c49c --- /dev/null +++ b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java @@ -0,0 +1,14 @@ +package com.volmit.stage; + +/** An invocation stage active only where its settings are configured; bodies receive them. */ +public interface ConditionalStageDefinition { + ConditionalStageDefinition requires(Stage... stages); + + ConditionalStageDefinition softAfter(StageRef... stages); + + ConditionalStageDefinition softBefore(StageRef... stages); + + void run(SettingsAction action); + + void produce(SettingsFunction function); +} diff --git a/src/main/java/com/volmit/stage/Pipeline.java b/src/main/java/com/volmit/stage/Pipeline.java new file mode 100644 index 000000000..568778fef --- /dev/null +++ b/src/main/java/com/volmit/stage/Pipeline.java @@ -0,0 +1,9 @@ +package com.volmit.stage; + +/** Independent stage graphs. A stage belongs to exactly one pipeline; edges never cross them. */ +public enum Pipeline { + /** Runs once per object placement attempt, against one buffered placement edit. */ + PLACEMENT, + /** Runs once per chunk generation invocation, against host-owned local hunks. */ + CHUNK +} diff --git a/src/main/java/com/volmit/stage/PlacementStage.java b/src/main/java/com/volmit/stage/PlacementStage.java new file mode 100644 index 000000000..a29bbb506 --- /dev/null +++ b/src/main/java/com/volmit/stage/PlacementStage.java @@ -0,0 +1,18 @@ +package com.volmit.stage; + +/** Runs once per placement attempt. */ +public final class PlacementStage extends Stage { + PlacementStage(String id, Class outputType) { + super(id, outputType); + } + + @Override + public Pipeline pipeline() { + return Pipeline.PLACEMENT; + } + + @Override + public StageKind kind() { + return StageKind.INVOCATION; + } +} diff --git a/src/main/java/com/volmit/stage/PlacementStageContext.java b/src/main/java/com/volmit/stage/PlacementStageContext.java new file mode 100644 index 000000000..2b7058f7d --- /dev/null +++ b/src/main/java/com/volmit/stage/PlacementStageContext.java @@ -0,0 +1,20 @@ +package com.volmit.stage; + +import com.volmit.placement.PlacementAccess; +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. + */ +public interface PlacementStageContext extends PlacementContext, StageContext { + PlacementRequest request(); + + /** Buffered access bounded by the prepared edit; reads include earlier writes. */ + PlacementAccess access(); + + /** Stops the attempt after the current stage (or current block); nothing is committed. + * The first reason is kept. + */ + void reject(String reason); +} diff --git a/src/main/java/com/volmit/stage/SettingsAction.java b/src/main/java/com/volmit/stage/SettingsAction.java new file mode 100644 index 000000000..e2d9de500 --- /dev/null +++ b/src/main/java/com/volmit/stage/SettingsAction.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface SettingsAction { + void run(C context, S settings); +} diff --git a/src/main/java/com/volmit/stage/SettingsBlockCollector.java b/src/main/java/com/volmit/stage/SettingsBlockCollector.java new file mode 100644 index 000000000..07ee80cb5 --- /dev/null +++ b/src/main/java/com/volmit/stage/SettingsBlockCollector.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface SettingsBlockCollector { + void collect(BlockStageContext context, S settings, O accumulator); +} diff --git a/src/main/java/com/volmit/stage/SettingsFunction.java b/src/main/java/com/volmit/stage/SettingsFunction.java new file mode 100644 index 000000000..ca618a422 --- /dev/null +++ b/src/main/java/com/volmit/stage/SettingsFunction.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface SettingsFunction { + O run(C context, S settings); +} diff --git a/src/main/java/com/volmit/stage/Stage.java b/src/main/java/com/volmit/stage/Stage.java new file mode 100644 index 000000000..ce32b191f --- /dev/null +++ b/src/main/java/com/volmit/stage/Stage.java @@ -0,0 +1,73 @@ +package com.volmit.stage; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** A unit of pipeline work, declared as a constant by the module that defines it. + * The id is namespaced and its namespace must match the defining module. Identity is this + * declaration object: other modules require or read the owner's constant, never a copy. + * The output type is Void for stages that only act; otherwise dependents read it through + * {@link StageContext#output(Stage)}. Block stages accumulate their output across the pass. + */ +public abstract sealed class Stage permits PlacementStage, BlockStage, ChunkStage { + private final ResourceId id; + private final Class outputType; + + Stage(String id, Class outputType) { + this.id = ResourceId.parse(id); + this.outputType = Objects.requireNonNull(outputType, "outputType"); + if (outputType.isPrimitive()) { + throw new IllegalArgumentException("Stage output requires a reference type: " + id); + } + } + + public static PlacementStage placement(String id) { + return new PlacementStage<>(id, Void.class); + } + + public static PlacementStage placement(String id, Class outputType) { + return new PlacementStage<>(id, outputType); + } + + public static BlockStage placementBlock(String id) { + return new BlockStage<>(id, Void.class); + } + + /** The accumulator type is created once per placement and becomes the stage output. */ + public static BlockStage placementBlock(String id, Class accumulatorType) { + return new BlockStage<>(id, accumulatorType); + } + + public static ChunkStage chunk(String id) { + return new ChunkStage<>(id, Void.class); + } + + public static ChunkStage chunk(String id, Class outputType) { + return new ChunkStage<>(id, outputType); + } + + public final ResourceId id() { + return id; + } + + public final Class outputType() { + return outputType; + } + + public final boolean producesOutput() { + return outputType != Void.class; + } + + public final StageRef ref() { + return new StageRef(id); + } + + public abstract Pipeline pipeline(); + + public abstract StageKind kind(); + + @Override + public final String toString() { + return id.toString(); + } +} diff --git a/src/main/java/com/volmit/stage/StageAction.java b/src/main/java/com/volmit/stage/StageAction.java new file mode 100644 index 000000000..a228b4308 --- /dev/null +++ b/src/main/java/com/volmit/stage/StageAction.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface StageAction { + void run(C context); +} diff --git a/src/main/java/com/volmit/stage/StageContext.java b/src/main/java/com/volmit/stage/StageContext.java new file mode 100644 index 000000000..a42c6fb57 --- /dev/null +++ b/src/main/java/com/volmit/stage/StageContext.java @@ -0,0 +1,10 @@ +package com.volmit.stage; + +/** Per-invocation view handed to one stage body. Do not retain it after the body returns. */ +public interface StageContext { + /** 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. + */ + O output(Stage stage); +} diff --git a/src/main/java/com/volmit/stage/StageDefinition.java b/src/main/java/com/volmit/stage/StageDefinition.java new file mode 100644 index 000000000..effb151ed --- /dev/null +++ b/src/main/java/com/volmit/stage/StageDefinition.java @@ -0,0 +1,25 @@ +package com.volmit.stage; + +import com.volmit.IrisFeature; + +/** Declares one invocation stage. requires(...) is a hard dependency on another module's + * stage constant: it orders this stage after it, allows reading its output, and deactivates + * this stage wherever the requirement is inactive. Soft edges only order, and only when the + * referenced stage is installed in the same pipeline. There is deliberately no hard "before". + */ +public interface StageDefinition { + StageDefinition requires(Stage... stages); + + StageDefinition softAfter(StageRef... stages); + + StageDefinition softBefore(StageRef... stages); + + /** Activates the stage only where the given feature settings are configured. */ + ConditionalStageDefinition when(Class settingsType); + + /** Body for a stage without output. */ + void run(StageAction action); + + /** Body for a stage with output; null results fail the invocation. */ + void produce(StageFunction function); +} diff --git a/src/main/java/com/volmit/stage/StageFunction.java b/src/main/java/com/volmit/stage/StageFunction.java new file mode 100644 index 000000000..afef43367 --- /dev/null +++ b/src/main/java/com/volmit/stage/StageFunction.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +@FunctionalInterface +public interface StageFunction { + O run(C context); +} diff --git a/src/main/java/com/volmit/stage/StageGraph.java b/src/main/java/com/volmit/stage/StageGraph.java new file mode 100644 index 000000000..8beaf19c0 --- /dev/null +++ b/src/main/java/com/volmit/stage/StageGraph.java @@ -0,0 +1,15 @@ +package com.volmit.stage; + +/** Collects the stages a module defines during {@code IrisModule.install}. Each define call must + * end with exactly one body (run, produce or accumulate). The graph is resolved once at pack load: + * missing requirements, cycles, duplicate definitions, foreign namespaces and cross-pipeline + * edges are load errors. Bodies are shared by concurrent invocations and must not capture + * invocation state; everything per-invocation arrives through the context and outputs. + */ +public interface StageGraph { + StageDefinition define(PlacementStage stage); + + BlockStageDefinition define(BlockStage stage); + + StageDefinition define(ChunkStage stage); +} diff --git a/src/main/java/com/volmit/stage/StageKind.java b/src/main/java/com/volmit/stage/StageKind.java new file mode 100644 index 000000000..d5a8f39b8 --- /dev/null +++ b/src/main/java/com/volmit/stage/StageKind.java @@ -0,0 +1,9 @@ +package com.volmit.stage; + +/** How often a stage runs within one pipeline invocation. */ +public enum StageKind { + /** Once per placement or chunk. */ + INVOCATION, + /** Once per object block, inside a fused block pass. Placement pipeline only. */ + BLOCK +} diff --git a/src/main/java/com/volmit/stage/StageRef.java b/src/main/java/com/volmit/stage/StageRef.java new file mode 100644 index 000000000..26836077b --- /dev/null +++ b/src/main/java/com/volmit/stage/StageRef.java @@ -0,0 +1,20 @@ +package com.volmit.stage; + +import com.volmit.resource.ResourceId; +import java.util.Objects; + +/** A stage named by id only, for soft ordering against stages that may not be installed. */ +public record StageRef(ResourceId id) { + public StageRef { + Objects.requireNonNull(id, "id"); + } + + public static StageRef of(String id) { + return new StageRef(ResourceId.parse(id)); + } + + @Override + public String toString() { + return id.toString(); + } +} diff --git a/src/test/java/com/volmit/FeatureContractTest.java b/src/test/java/com/volmit/FeatureContractTest.java index 65faa720d..1e5827e71 100644 --- a/src/test/java/com/volmit/FeatureContractTest.java +++ b/src/test/java/com/volmit/FeatureContractTest.java @@ -1,12 +1,8 @@ package com.volmit; import com.volmit.config.*; -import com.volmit.generation.*; -import com.volmit.hunk.Hunk; -import com.volmit.host.ArrayHunk; -import com.volmit.host.ModuleRegistry; +import com.volmit.host.FeatureDescriptor; import com.volmit.resource.ResourceId; -import com.volmit.support.TestContexts; import org.junit.jupiter.api.Test; @@ -40,25 +36,12 @@ class FeatureContractTest { } @Test - void registryBindsDecodedOptionsToTheCorrectModifier() { - var host = new ModuleRegistry(); - host.register(FillOptions.class, Integer.class, FillModifier::new); - var registration = host.freeze().generation(FillOptions.class, Integer.class); - var modifier = registration.configure(ResourceId.parse("test:fill/0"), new FillOptions()); - var output = new ArrayHunk<>(Integer.class, 1, 1, 1, 0); - modifier.modify(TestContexts.generation(), output); - assertEquals(12, output.get(0, 0, 0)); - } - - private static class FillModifier extends GenerationModifier { - private final FillOptions options; - FillModifier(FillOptions options) { - this.options = options; - } - public String id() { return "example:fill-modifier"; } - public void modify(GenerationContext context, Hunk volume) { - volume.set(0, 0, 0, options.value); - } + void descriptorReadsFeatureIdentityAndAttachment() { + var descriptor = FeatureDescriptor.of(FillOptions.class); + assertEquals(ResourceId.parse("example:fill"), descriptor.id()); + assertEquals("fill", descriptor.attachment().field()); + assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets()); + assertEquals(1, descriptor.options().options().size()); } static class InvalidOptions { diff --git a/src/test/java/com/volmit/generation/DependenciesTest.java b/src/test/java/com/volmit/generation/DependenciesTest.java deleted file mode 100644 index 137a6ed10..000000000 --- a/src/test/java/com/volmit/generation/DependenciesTest.java +++ /dev/null @@ -1,54 +0,0 @@ -package com.volmit.generation; - -import org.junit.jupiter.api.Test; -import java.util.HashSet; -import java.util.Set; -import static org.junit.jupiter.api.Assertions.*; - -class DependenciesTest { - @Test - void accumulatesAndDeduplicatesWithoutMutatingEarlierDeclarations() { - var original = Dependencies.requires("iris:terrain", "iris:terrain"); - var result = original.andRequires("iris:carving") - .afterIfPresent("example:caves").afterIfPresent("example:lakes") - .beforeIfPresent("iris:ores").beforeIfPresent("iris:ores", "iris:objects"); - assertEquals(Set.of("iris:terrain"), original.required()); - assertTrue(original.after().isEmpty()); - assertTrue(original.before().isEmpty()); - assertEquals(Set.of("iris:terrain", "iris:carving"), result.required()); - assertEquals(Set.of("example:caves", "example:lakes"), result.after()); - assertEquals(Set.of("iris:ores", "iris:objects"), result.before()); - } - - @Test - void copiesInputsAndExposesImmutableSets() { - var ids = new HashSet<>(Set.of("iris:terrain")); - var result = new Dependencies(ids, ids, ids); - ids.clear(); - assertEquals(Set.of("iris:terrain"), result.required()); - assertThrows(UnsupportedOperationException.class, () -> result.required().clear()); - assertThrows(UnsupportedOperationException.class, () -> result.after().clear()); - assertThrows(UnsupportedOperationException.class, () -> result.before().clear()); - String[] input = {"iris:terrain"}; - var fromArray = Dependencies.requires(input); - input[0] = "iris:ores"; - assertEquals(Set.of("iris:terrain"), fromArray.required()); - } - - @Test - void supportsEmptyAndOptionalOnlyDeclarations() { - assertEquals(new Dependencies(Set.of(), Set.of(), Set.of()), Dependencies.none()); - assertEquals(Dependencies.none(), Dependencies.requires()); - assertEquals(Set.of("iris:ores"), Dependencies.none().beforeIfPresent("iris:ores").before()); - } - - @Test - void rejectsNullAndBlankIds() { - assertThrows(IllegalArgumentException.class, () -> Dependencies.requires(" ")); - assertThrows(IllegalArgumentException.class, () -> Dependencies.none().afterIfPresent("")); - assertThrows(IllegalArgumentException.class, () -> Dependencies.none().beforeIfPresent("\n")); - assertThrows(NullPointerException.class, () -> Dependencies.requires((String) null)); - assertThrows(NullPointerException.class, () -> Dependencies.requires((String[]) null)); - assertThrows(NullPointerException.class, () -> new Dependencies(null, Set.of(), Set.of())); - } -} diff --git a/src/test/java/com/volmit/host/GenerationPlanTest.java b/src/test/java/com/volmit/host/GenerationPlanTest.java deleted file mode 100644 index 2eaaa9487..000000000 --- a/src/test/java/com/volmit/host/GenerationPlanTest.java +++ /dev/null @@ -1,85 +0,0 @@ -package com.volmit.host; - -import com.volmit.generation.*; -import com.volmit.hunk.Hunk; -import com.volmit.resource.ResourceId; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import static org.junit.jupiter.api.Assertions.*; - -class GenerationPlanTest { - private static ResourceId id(String path) { return ResourceId.parse("test:" + path); } - - private static ConfiguredModifier binding(String occurrence, String name, Dependencies dependencies) { - return new ConfiguredModifier<>(id(occurrence), String.class, new Modifier(name, dependencies)); - } - - private static class Modifier extends GenerationModifier { - private final String name; - private final Dependencies dependencies; - Modifier(String name, Dependencies dependencies) { this.name = name; this.dependencies = dependencies; } - public String id() { return "test:" + name; } - public Dependencies depends() { return dependencies; } - public void modify(GenerationContext context, Hunk output) {} - } - - @Test - void orderingIsIndependentOfDiscoveryAndIncludesRepeatedOccurrences() { - var first = binding("terrain/1", "terrain", Dependencies.none()); - var second = binding("terrain/0", "terrain", Dependencies.none()); - var caves = binding("caves/0", "caves", Dependencies.requires("test:terrain")); - var decoration = binding("decoration/0", "decoration", Dependencies.requires("test:caves").beforeIfPresent("test:missing")); - var a = GenerationPlan.resolve(List.of(decoration, first, caves, second)); - var b = GenerationPlan.resolve(List.of(second, caves, decoration, first)); - var expected = List.of(id("terrain/0"), id("terrain/1"), id("caves/0"), id("decoration/0")); - assertEquals(expected, a.ordered().stream().map(ConfiguredModifier::occurrence).toList()); - assertEquals(expected, b.ordered().stream().map(ConfiguredModifier::occurrence).toList()); - var executed = new ArrayList(); - a.execute(new GenerationPlan.Executor() { - public void execute(ConfiguredModifier modifier) { executed.add(modifier.occurrence()); } - }); - assertEquals(expected, executed); - assertThrows(UnsupportedOperationException.class, () -> a.ordered().clear()); - } - - @Test - void rejectsMissingRequirementsSelfEdgesAndCycles() { - assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:missing")))); - assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.none().beforeIfPresent("test:a")))); - assertThrows(IllegalArgumentException.class, () -> DependencyOrder.resolve(Map.of(id("a"), Dependencies.requires("test:b"), id("b"), Dependencies.requires("test:a")))); - } - - @Test - void rejectsDuplicateOccurrencesAndConflictingImplementationsOrDeclarations() { - var a = binding("a/0", "a", Dependencies.none()); - assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, a))); - assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, - binding("a/1", "a", Dependencies.none().afterIfPresent("test:b"))))); - var otherImplementation = new ConfiguredModifier<>(id("a/2"), String.class, new Modifier("a", Dependencies.none()) {}); - assertThrows(IllegalArgumentException.class, () -> GenerationPlan.resolve(List.of(a, otherImplementation))); - } - - @Test - void repeatedEdgesAreCountedOnceAndIndependentIdsUseLexicalOrder() { - var graph = Map.of(id("a"), Dependencies.none(), id("z"), Dependencies.none(), - id("b"), Dependencies.requires("test:a").afterIfPresent("test:a")); - assertEquals(List.of(id("a"), id("b"), id("z")), DependencyOrder.resolve(graph)); - } - - @Test - void failuresStopDispatchAndNegativeReachFailsAtPackLoad() { - var plan = GenerationPlan.resolve(List.of(binding("a", "a", Dependencies.none()), binding("b", "b", Dependencies.none()))); - var visited = new ArrayList(); - assertThrows(IllegalStateException.class, () -> plan.execute(new GenerationPlan.Executor() { - public void execute(ConfiguredModifier modifier) { - visited.add(modifier.id()); - throw new IllegalStateException("Failed output"); - } - })); - assertEquals(List.of(id("a")), visited); - assertThrows(IllegalArgumentException.class, () -> new ConfiguredModifier<>(id("negative"), String.class, - new Modifier("a", Dependencies.none()) { public int mantleRadius() { return -1; } })); - } -} diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 05713804e..803104727 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -2,10 +2,10 @@ package com.volmit.host; import com.volmit.*; import com.volmit.config.Feature; -import com.volmit.generation.*; -import com.volmit.hunk.Hunk; import com.volmit.mantle.*; -import com.volmit.placement.PlacementModifier; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; import org.junit.jupiter.api.Test; import java.io.DataInput; import java.io.DataOutput; @@ -23,54 +23,34 @@ class ModuleRegistryTest { static class Collision implements IrisFeature {} @Feature(id = "test:one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION) static class Duplicate implements IrisFeature {} - @Feature(id = "test:placement", name = "Placement", field = "foundation", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) - static class Placement implements IrisFeature {} static class MissingAnnotation implements IrisFeature {} @Feature(id = "test:abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME) abstract static class AbstractFeature implements IrisFeature {} - private static GenerationModifier modifier(IrisFeature ignored) { - return new GenerationModifier<>() { - public String id() { return "test:modifier"; } - public void modify(GenerationContext context, Hunk output) {} - }; - } - @Test void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() { var registry = new ModuleRegistry(); - registry.register(One.class, String.class, ModuleRegistryTest::modifier); - assertThrows(IllegalArgumentException.class, () -> registry.register(Collision.class, String.class, ModuleRegistryTest::modifier)); - registry.register(Two.class, String.class, ModuleRegistryTest::modifier); + registry.registerSettings(One.class); + registry.registerSettings(One.class); + assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Collision.class, ignored -> context -> null)); + registry.registerObject(Two.class, ignored -> context -> null); assertThrows(IllegalArgumentException.class, () -> registry.registerObject(Duplicate.class, ignored -> context -> null)); - assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier)); + assertThrows(IllegalArgumentException.class, () -> registry.registerObject(One.class, ignored -> context -> null)); var catalog = registry.freeze(); - assertEquals(List.of("test:one", "test:two"), catalog.generation().stream().map(value -> value.descriptor().id().toString()).toList()); - assertThrows(IllegalArgumentException.class, () -> catalog.generation(One.class, Integer.class)); + assertEquals(List.of("test:one"), catalog.settings().stream().map(value -> value.id().toString()).toList()); + assertEquals(List.of("test:two"), catalog.objects().stream().map(value -> value.descriptor().id().toString()).toList()); } @Test void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() { var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared"))); - assertThrows(IllegalArgumentException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier)); - assertThrows(IllegalArgumentException.class, () -> registry.register(MissingAnnotation.class, String.class, ModuleRegistryTest::modifier)); - assertThrows(IllegalArgumentException.class, () -> registry.register(AbstractFeature.class, String.class, ModuleRegistryTest::modifier)); - assertThrows(NullPointerException.class, () -> registry.register(Two.class, String.class, null)); - registry.register(Two.class, String.class, ModuleRegistryTest::modifier); - } - - @Test - void placementMustAttachToPlacementAndFreezeEndsRegistration() { - var registry = new ModuleRegistry(); - assertThrows(IllegalArgumentException.class, () -> registry.registerPlacement(One.class, ignored -> new PlacementModifier() { - public String id() { return "test:placement"; } - })); - registry.registerPlacement(Placement.class, ignored -> new PlacementModifier() { - public String id() { return "test:placement"; } - }); - assertEquals(1, registry.freeze().placement().size()); + assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(One.class)); + assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(MissingAnnotation.class)); + assertThrows(IllegalArgumentException.class, () -> registry.registerSettings(AbstractFeature.class)); + assertThrows(NullPointerException.class, () -> registry.registerObject(Two.class, null)); + registry.registerObject(Two.class, ignored -> context -> null); assertSame(registry.freeze(), registry.freeze()); - assertThrows(IllegalStateException.class, () -> registry.register(One.class, String.class, ModuleRegistryTest::modifier)); + assertThrows(IllegalStateException.class, () -> registry.registerSettings(One.class)); } @Test @@ -85,6 +65,24 @@ class ModuleRegistryTest { assertEquals(1, registry.freeze().mantle().size()); } + @Test + void loadingModulesCatalogsStageSettingsAndRegistrationsTogether() { + var conditioned = new IrisModule() { + static final PlacementStage WORK = Stage.placement("test:conditioned/work"); + public ModuleInfo info() { return ModuleInfo.of("test:conditioned", "1"); } + public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); } + public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); } + }; + var loaded = LoadedModules.load(List.of(conditioned), Map.of()); + assertEquals(List.of("test:one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList()); + assertEquals(1, loaded.catalog().objects().size()); + assertEquals(1, loaded.placement().stages().size()); + assertTrue(loaded.chunk().stages().isEmpty()); + + var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("shared")); + assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(conditioned), reserved)); + } + private static MantleCodec codec(int version) { return new MantleCodec<>() { public int version() { return version; } diff --git a/src/test/java/com/volmit/host/PlacementPipelineTest.java b/src/test/java/com/volmit/host/PlacementPipelineTest.java deleted file mode 100644 index edd51e211..000000000 --- a/src/test/java/com/volmit/host/PlacementPipelineTest.java +++ /dev/null @@ -1,259 +0,0 @@ -package com.volmit.host; - -import com.volmit.block.BlockState; -import com.volmit.generation.Dependencies; -import com.volmit.mantle.*; -import com.volmit.object.*; -import com.volmit.placement.*; -import com.volmit.resource.ResourceId; -import com.volmit.support.TestContexts; -import com.volmit.world.BlockPosition; -import org.junit.jupiter.api.Test; -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.concurrent.atomic.AtomicReference; -import static org.junit.jupiter.api.Assertions.*; - -class PlacementPipelineTest { - private static final BlockState STONE = new BlockState("minecraft:stone"); - private static final BlockState AIR = new BlockState("minecraft:air"); - private static ResourceId id(String name) { return ResourceId.parse("test:" + name); } - - private static PlacementRequest request() { - var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(1, 0, 0), - List.of(new ObjectBlock(new BlockPosition(1, 0, 0), STONE), new ObjectBlock(new BlockPosition(0, 0, 0), STONE)), - List.of(new ObjectMarker(new BlockPosition(1, 0, 0), id("owner"), Map.of("name", "column")))); - return new PlacementRequest(id("attempt"), object, new BlockPosition(-2, -60, -3)); - } - - private static ConfiguredPlacementModifier configured(PlacementModifier modifier) { - return new ConfiguredPlacementModifier(ResourceId.parse(modifier.id() + "/0"), modifier); - } - - @Test - void validatesCompletePlanBeforeWritesAndAfterHooksSeeOverlayAndActualBounds() { - var events = new ArrayList(); - var modifier = new PlacementModifier() { - public String id() { return "test:foundation"; } - public Optional prepare(PlacementContext context, PlacementRequest request) { - events.add("prepare"); return Optional.of(request); - } - public Optional mapBlock(PlacementContext context, PlacedBlock block) { - events.add("map"); - return block.position().x() == -3 ? Optional.empty() : Optional.of(block); - } - public boolean validate(PlacementContext context, PlacementPlan plan) { - events.add("validate"); - assertEquals(1, plan.blocks().size()); - return true; - } - public void beforePlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) { - events.add("before"); - assertEquals(AIR, access.get(-2, -60, -3)); - } - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan written) { - events.add("after"); - assertEquals(STONE, access.get(-2, -60, -3)); - assertEquals(new BlockBox(-2, -60, -3, -1, -59, -2), written.writtenBounds().orElseThrow()); - assertFalse(access instanceof PlacementEdit); - access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty())); - } - }; - var pipeline = PlacementPipeline.resolve(List.of(configured(modifier))); - var edit = new RecordingEdit(events); - var result = pipeline.place(request(), edit, ignored -> TestContexts.placement(), plan -> { - events.add("host-validate"); assertEquals(0, edit.mutations); return true; - }); - assertTrue(result.isPresent()); - assertEquals(List.of("prepare", "map", "map", "host-validate", "validate", "before", "write", "marker", "after", "write", "commit", "close"), events); - assertEquals(2, edit.published.size()); - assertEquals(1, edit.publishedMarkers.size()); - assertThrows(IllegalStateException.class, () -> edit.get(-2, -60, -3)); - } - - @Test - void validationRejectionPublishesNothingAndDoesNotStartMutating() { - var modifier = new PlacementModifier() { - public String id() { return "test:reject"; } - public boolean validate(PlacementContext context, PlacementPlan plan) { return false; } - }; - var edit = new RecordingEdit(new ArrayList<>()); - assertTrue(PlacementPipeline.resolve(List.of(configured(modifier))) - .place(request(), edit, ignored -> TestContexts.placement(), ignored -> true).isEmpty()); - assertEquals(0, edit.mutations); - assertTrue(edit.published.isEmpty()); - assertTrue(edit.closed); - } - - @Test - void failureAfterBufferedObjectWritesDiscardsEntireAttempt() { - var modifier = new PlacementModifier() { - public String id() { return "test:failure"; } - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) { - access.set(new PlacedBlock(new BlockPosition(-2, -61, -3), STONE, Optional.empty())); - throw new IllegalStateException("Foundation failed"); - } - }; - var edit = new RecordingEdit(new ArrayList<>()); - assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of(configured(modifier))) - .place(request(), edit, ignored -> TestContexts.placement(), ignored -> true)); - assertTrue(edit.mutations > 0); - assertTrue(edit.published.isEmpty()); - assertTrue(edit.publishedMarkers.isEmpty()); - assertTrue(edit.closed); - } - - @Test - void prepareRejectionAndFailedCommitCloseWithoutPublication() { - var rejection = new PlacementModifier() { - public String id() { return "test:prepare-reject"; } - public Optional prepare(PlacementContext context, PlacementRequest request) { return Optional.empty(); } - }; - var rejected = new RecordingEdit(new ArrayList<>()); - assertTrue(PlacementPipeline.resolve(List.of(configured(rejection))) - .place(request(), rejected, ignored -> TestContexts.placement(), ignored -> true).isEmpty()); - assertEquals(0, rejected.mutations); - var failed = new RecordingEdit(new ArrayList<>()); - failed.failCommit = true; - assertThrows(IllegalStateException.class, () -> PlacementPipeline.resolve(List.of()) - .place(request(), failed, ignored -> TestContexts.placement(), ignored -> true)); - assertTrue(failed.closed); - assertTrue(failed.published.isEmpty()); - } - - @Test - void rejectsMappedBoundsDuplicateWritesAndInsufficientPreparedReachBeforeMutation() { - var escape = new PlacementModifier() { - public String id() { return "test:escape"; } - public Optional mapBlock(PlacementContext context, PlacedBlock block) { - return Optional.of(new PlacedBlock(new BlockPosition(5, -60, -3), block.state(), block.blockEntity())); - } - }; - var escaped = new RecordingEdit(new ArrayList<>()); - assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(escape))) - .place(request(), escaped, ignored -> TestContexts.placement(), ignored -> true)); - assertEquals(0, escaped.mutations); - var radius = new PlacementModifier() { - public String id() { return "test:radius"; } - public int writeRadius() { return 32; } - }; - var unprepared = new RecordingEdit(new ArrayList<>()); - assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(radius))) - .place(request(), unprepared, ignored -> TestContexts.placement(), ignored -> true)); - assertEquals(0, unprepared.mutations); - } - - @Test - void hooksCannotWriteBeyondReachOrRetainUsableViews() { - var retained = new AtomicReference(); - var retainedLayer = new AtomicReference>(); - var modifier = new PlacementModifier() { - public String id() { return "test:bounded"; } - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) { - retained.set(access); - retainedLayer.set(access.mantle().layer(new MantleKey<>("test:owner", String.class))); - assertThrows(IndexOutOfBoundsException.class, () -> access.set(new PlacedBlock(new BlockPosition(5, -60, -3), STONE, Optional.empty()))); - assertThrows(UnsupportedOperationException.class, () -> access.mantle().edit()); - assertThrows(IndexOutOfBoundsException.class, () -> access.mantle().layer(new MantleKey<>("test:owner", String.class)).get(5, -60, -3)); - } - }; - var edit = new RecordingEdit(new ArrayList<>()); - PlacementPipeline.resolve(List.of(configured(modifier))).place(request(), edit, ignored -> TestContexts.placement(), ignored -> true); - assertThrows(IllegalStateException.class, () -> retained.get().get(-2, -60, -3)); - assertThrows(IllegalStateException.class, () -> retainedLayer.get().get(-2, -60, -3)); - } - - @Test - void placementDependenciesStayInTheirOwnGraphAndRejectConflicts() { - var first = new PlacementModifier() { public String id() { return "test:first"; } }; - var second = new PlacementModifier() { - public String id() { return "test:second"; } - public Dependencies depends() { return Dependencies.requires("test:first"); } - }; - assertEquals(List.of(ResourceId.parse("test:first"), ResourceId.parse("test:second")), - PlacementPipeline.resolve(List.of(configured(second), configured(first))).ordered().stream().map(ConfiguredPlacementModifier::id).toList()); - assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(second)))); - assertThrows(IllegalArgumentException.class, () -> PlacementPipeline.resolve(List.of(configured(first), configured(first)))); - } - - @Test - void mappedWritesOutsideReachFailBeforeMutationAndEachHookKeepsItsOwnReach() { - var moved = new PlacementModifier() { - public String id() { return "test:moved"; } - public Optional mapBlock(PlacementContext context, PlacedBlock block) { - return Optional.of(new PlacedBlock(block.position().add(new BlockPosition(8, 0, 0)), block.state(), block.blockEntity())); - } - }; - var edit = new RecordingEdit(new ArrayList<>()); - assertThrows(IndexOutOfBoundsException.class, () -> PlacementPipeline.resolve(List.of(configured(moved))) - .place(request(), edit, ignored -> TestContexts.placement(), ignored -> true)); - assertEquals(0, edit.mutations); - var large = new PlacementModifier() { - public String id() { return "test:large"; } - public int writeRadius() { return 2; } - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) { - assertEquals(AIR, access.get(0, -60, -3)); - assertEquals(new BlockBox(-5, -64, -5, 1, 320, 0), access.mantle().bounds()); - assertNull(access.mantle().layer(new MantleKey<>("test:owner", String.class)) - .get(0, -60, -3)); - } - }; - var small = new PlacementModifier() { - public String id() { return "test:small"; } - public void afterPlace(PlacementContext context, PlacementAccess access, PlacementPlan plan) { - assertThrows(IndexOutOfBoundsException.class, () -> access.get(0, -60, -3)); - assertEquals(new BlockBox(-3, -64, -3, -1, 320, -2), access.mantle().bounds()); - assertThrows(IndexOutOfBoundsException.class, () -> access.mantle() - .layer(new MantleKey<>("test:owner", String.class)).get(0, -60, -3)); - } - }; - assertTrue(PlacementPipeline.resolve(List.of(configured(small), configured(large))) - .place(request(), new RecordingEdit(new ArrayList<>()), ignored -> TestContexts.placement(), ignored -> true).isPresent()); - } - - /** In-memory transactional test adapter; production storage/persistence is deliberately absent. */ - private static class RecordingEdit implements PlacementEdit { - final List events; - final Map pending = new HashMap<>(); - final Map published = new HashMap<>(); - final List pendingMarkers = new ArrayList<>(); - final List publishedMarkers = new ArrayList<>(); - boolean closed; - boolean failCommit; - int mutations; - RecordingEdit(List events) { this.events = events; } - private void checkOpen() { if (closed) throw new IllegalStateException("Closed edit"); } - public BlockBox bounds() { checkOpen(); return new BlockBox(-16, -64, -16, 16, 320, 16); } - public BlockState get(int x, int y, int z) { checkOpen(); return pending.getOrDefault(new BlockPosition(x, y, z), AIR); } - public void set(PlacedBlock block) { checkOpen(); mutations++; events.add("write"); pending.put(block.position(), block.state()); } - public void marker(PlacedMarker marker) { checkOpen(); mutations++; events.add("marker"); pendingMarkers.add(marker); } - public Mantle mantle() { - checkOpen(); - return new Mantle() { - public BlockBox bounds() { return RecordingEdit.this.bounds(); } - public MantleEdit edit() { throw new UnsupportedOperationException(); } - public MantleLayer layer(MantleKey key) { - return new MantleLayer<>() { - public T get(int x, int y, int z) { checkOpen(); return null; } - public void set(int x, int y, int z, T value) { throw new AssertionError("Unused mantle mutation"); } - public void remove(int x, int y, int z) { throw new AssertionError("Unused mantle mutation"); } - public void clear(BlockBox area) { throw new AssertionError("Unused mantle mutation"); } - public void visit(BlockBox area, MantleVisitor visitor) { checkOpen(); } - }; - } - }; - } - public void commit() { - checkOpen(); - if (failCommit) throw new IllegalStateException("Commit failed"); - events.add("commit"); published.putAll(pending); publishedMarkers.addAll(pendingMarkers); closed = true; - } - public void close() { - if (!events.contains("close")) events.add("close"); - closed = true; pending.clear(); pendingMarkers.clear(); - } - } -} diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java new file mode 100644 index 000000000..c3b0a27ab --- /dev/null +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -0,0 +1,415 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisFeature; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.config.Feature; +import com.volmit.mantle.BlockBox; +import com.volmit.object.GeneratedObject; +import com.volmit.object.ObjectBlock; +import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacementEdit; +import com.volmit.placement.PlacementRequest; +import com.volmit.resource.ResourceId; +import com.volmit.stage.BlockStageContext; +import com.volmit.stage.ChunkStage; +import com.volmit.stage.Pipeline; +import com.volmit.stage.PlacementStage; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; +import com.volmit.stage.StageRef; +import com.volmit.support.MemoryEdit; +import com.volmit.support.TestContexts; +import com.volmit.support.TestTerrain; +import com.volmit.world.BlockPosition; +import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; +import java.util.function.Consumer; +import static org.junit.jupiter.api.Assertions.*; + +class StageGraphTest { + private static final BlockState STONE = new BlockState("minecraft:stone"); + + @Feature(id = "test:toggle", name = "Toggle", field = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) + static final class Toggle implements IrisFeature {} + + static final class Unannotated implements IrisFeature {} + + private static IrisModule module(String id, Consumer install) { + return new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of(id, "1"); } + public void install(StageGraph graph) { install.accept(graph); } + }; + } + + private static ResolvedGraph resolve(Pipeline pipeline, IrisModule... modules) { + var builder = new StageGraphBuilder(); + for (var module : modules) builder.install(module); + return builder.resolve(pipeline); + } + + private static List order(ResolvedGraph graph) { + return graph.stages().stream().map(stage -> stage.stage().id().toString()).toList(); + } + + private static List> passes(ResolvedGraph graph) { + return graph.blockPasses().stream().map(pass -> pass.stream().map(ResourceId::toString).toList()).toList(); + } + + private static PlacementRequest twoBlockRequest() { + var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0), + List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)), + List.of()); + return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0)); + } + + private static MemoryEdit flatEdit() { + return new MemoryEdit(new TestTerrain((x, z) -> 5)); + } + + private static PlacementOutcome place(ResolvedGraph graph, MemoryEdit edit, ConfiguredSettings settings) { + return new PlacementRunner(graph).place(twoBlockRequest(), edit, TestContexts.placement(), settings); + } + + @Test + void adjacentBlockStagesShareOnePassAndRunPerBlockInOrder() { + var first = Stage.placementBlock("test:first"); + var second = Stage.placementBlock("test:second"); + var events = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:blocks", stages -> { + stages.define(second).requires(first).run(context -> events.add("second@" + context.block().position().x())); + stages.define(first).run(context -> events.add("first@" + context.block().position().x())); + })); + + assertEquals(List.of(List.of("test:first", "test:second")), passes(graph)); + assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced()); + assertEquals(List.of("first@0", "second@0", "first@1", "second@1"), events); + } + + @Test + void requiredInvocationStageBetweenBlockStagesSplitsThePass() { + var collect = Stage.placementBlock("test:collect", Counter.class); + var middle = Stage.placement("test:middle", Integer.class); + var paint = Stage.placementBlock("test:paint"); + var events = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:split", stages -> { + stages.define(collect).accumulate(Counter::new, (context, counter) -> { + counter.count++; + events.add("collect"); + }); + stages.define(middle).requires(collect).produce(context -> { + events.add("middle"); + return context.output(collect).count; + }); + stages.define(paint).requires(middle).run(context -> events.add("paint:" + context.output(middle))); + })); + + assertEquals(List.of(List.of("test:collect"), List.of("test:paint")), passes(graph)); + assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced()); + assertEquals(List.of("collect", "collect", "middle", "paint:2", "paint:2"), events); + } + + @Test + void unrelatedInvocationStagesRunOutsideBlockPassesSoTheyDoNotSplitThem() { + var graph = resolve(Pipeline.PLACEMENT, module("test:fusion", stages -> { + stages.define(Stage.placementBlock("test:a")).run(context -> {}); + stages.define(Stage.placement("test:b")).run(context -> {}); + stages.define(Stage.placementBlock("test:c")).run(context -> {}); + })); + + assertEquals(List.of("test:b", "test:a", "test:c"), order(graph)); + assertEquals(List.of(List.of("test:a", "test:c")), passes(graph)); + } + + @Test + void unorderedStagesFollowLexicalIdsRegardlessOfInstallOrder() { + var zebra = module("zeta:module", stages -> stages.define(Stage.placement("zeta:work")).run(context -> {})); + var alpha = module("alpha:module", stages -> stages.define(Stage.placement("alpha:work")).run(context -> {})); + var forward = resolve(Pipeline.PLACEMENT, zebra, alpha); + var reversed = resolve(Pipeline.PLACEMENT, alpha, zebra); + + assertEquals(List.of("alpha:work", "zeta:work"), order(forward)); + assertEquals(forward.describe(), reversed.describe()); + assertEquals(List.of(new ResolvedGraph.UnorderedPair(ResourceId.parse("alpha:work"), ResourceId.parse("zeta:work"))), + forward.unorderedPairs()); + } + + @Test + void softEdgesOrderOnlyInstalledStagesAndReportAbsentTargets() { + var late = Stage.placement("test:late"); + var early = Stage.placement("test:early"); + var graph = resolve(Pipeline.PLACEMENT, module("test:soft", stages -> { + stages.define(early).softAfter(StageRef.of("test:late")).run(context -> {}); + stages.define(late).softBefore(StageRef.of("other:missing")).run(context -> {}); + })); + + assertEquals(List.of("test:late", "test:early"), order(graph)); + var earlyStage = graph.stages().get(1); + assertEquals(List.of(new StageEdge(late.id(), early.id(), StageEdge.Kind.SOFT)), earlyStage.incoming()); + assertEquals(List.of(StageRef.of("other:missing")), graph.stages().get(0).absentSoftTargets()); + assertTrue(graph.describe().contains("absent soft targets other:missing")); + assertTrue(graph.unorderedPairs().isEmpty()); + } + + @Test + void missingRequirementNamesBothStagesAndTheirModules() { + var absent = Stage.placement("other:absent"); + var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:needy", stages -> stages.define(Stage.placement("test:needy/work")).requires(absent).run(context -> {})))); + + assertEquals("Stage test:needy/work (module test:needy) requires other:absent, which no installed module " + + "defines (expected a module in namespace 'other')", error.getMessage()); + } + + @Test + void requirementMustBeTheOwnersDeclarationNotACopyWithTheSameId() { + var owned = Stage.placement("test:owned"); + var copy = Stage.placement("test:owned"); + var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:owner", stages -> stages.define(owned).run(context -> {})), + module("test:user", stages -> stages.define(Stage.placement("test:user/work")).requires(copy).run(context -> {})))); + + assertTrue(error.getMessage().contains("different declaration of test:owned (module test:owner)"), error.getMessage()); + } + + @Test + void cyclesListEveryStageWithItsModuleAndEdgeKind() { + var a = Stage.placement("test:a"); + var b = Stage.placement("other:b"); + var c = Stage.placement("test:c"); + var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:first", stages -> { + stages.define(a).requires(b).run(context -> {}); + stages.define(c).requires(a).run(context -> {}); + }), + module("other:second", stages -> stages.define(b).softAfter(c.ref()).run(context -> {})))); + + assertEquals("Stage cycle in pipeline PLACEMENT: other:b (module other:second) -[required]-> " + + "test:a (module test:first) -[required]-> test:c (module test:first) -[soft]-> " + + "other:b (module other:second)", error.getMessage()); + } + + @Test + void stageNamespaceMustMatchItsModuleAndDefinitionsAreUnique() { + var foreign = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:module", stages -> stages.define(Stage.placement("iris:stolen")).run(context -> {})))); + assertTrue(foreign.getMessage().contains("must use namespace 'test'"), foreign.getMessage()); + + var shared = Stage.placement("test:shared"); + var duplicate = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:one", stages -> stages.define(shared).run(context -> {})), + module("test:two", stages -> stages.define(shared).run(context -> {})))); + assertTrue(duplicate.getMessage().contains("already defined by module test:one"), duplicate.getMessage()); + + var module = module("test:twice", stages -> {}); + var builder = new StageGraphBuilder(); + builder.install(module); + assertThrows(IllegalArgumentException.class, () -> builder.install(module)); + } + + @Test + void dependenciesCannotCrossPipelines() { + var placementStage = Stage.placement("test:placed"); + ChunkStage chunkStage = Stage.chunk("test:chunk"); + var hard = module("test:hard", stages -> { + stages.define(placementStage).run(context -> {}); + stages.define(chunkStage).requires(placementStage).run(context -> {}); + }); + var error = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, hard)); + assertTrue(error.getMessage().contains("in pipeline CHUNK depends on test:placed (module test:hard) in pipeline PLACEMENT"), + error.getMessage()); + + var soft = module("test:soft", stages -> { + stages.define(Stage.placement("test:soft/placed")).run(context -> {}); + stages.define(Stage.chunk("test:soft/chunk")).softAfter(StageRef.of("test:soft/placed")).run(context -> {}); + }); + assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, soft)); + } + + @Test + void definitionsNeedExactlyOneBodyOfTheRightKind() { + var withOutput = Stage.placement("test:output", Integer.class); + var withoutOutput = Stage.placement("test:plain"); + var accumulating = Stage.placementBlock("test:acc", Counter.class); + + var run = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:run", stages -> stages.define(withOutput).run(context -> {})))); + assertTrue(run.getMessage().contains("declares output Integer; define it with produce(...)"), run.getMessage()); + assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:produce", stages -> stages.define(withoutOutput).produce(context -> null)))); + assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:accrun", stages -> stages.define(accumulating).run(context -> {})))); + var missing = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, + module("test:missing", stages -> stages.define(withoutOutput).requires()))); + assertTrue(missing.getMessage().contains("has no body"), missing.getMessage()); + assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:again", stages -> { + var definition = stages.define(withoutOutput); + definition.run(context -> {}); + definition.requires(withOutput); + }))); + } + + @Test + void invalidDeclarationsFailWhileInstalling() { + assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:self", stages -> { + var self = Stage.placement("test:self/work"); + stages.define(self).requires(self).run(context -> {}); + }))); + assertThrows(IllegalStateException.class, () -> resolve(Pipeline.PLACEMENT, module("test:twice", stages -> { + var definition = stages.define(Stage.placement("test:twice/work")); + definition.when(Toggle.class); + definition.when(Toggle.class); + }))); + assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.PLACEMENT, module("test:plain", stages -> + stages.define(Stage.placement("test:plain/work")).when(Unannotated.class).run((context, settings) -> {})))); + + var retained = new ArrayList(); + new StageGraphBuilder().install(module("test:retained", retained::add)); + assertThrows(IllegalStateException.class, () -> retained.getFirst().define(Stage.placement("test:retained/late"))); + } + + @Test + void outputsAreReadableOnlyThroughTransitiveRequirementsAndAfterTheirPass() { + var height = Stage.placement("test:height", Integer.class); + var offset = Stage.placement("test:offset", Integer.class); + var counted = Stage.placementBlock("test:counted", Counter.class); + var observed = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:outputs", stages -> { + stages.define(height).produce(context -> 10); + stages.define(offset).requires(height).produce(context -> context.output(height) + 1); + stages.define(counted).requires(offset).accumulate(Counter::new, (context, counter) -> { + counter.count++; + observed.add(context.output(height)); + }); + stages.define(Stage.placementBlock("test:peek")).requires(counted).run(context -> observed.add( + assertThrows(IllegalStateException.class, () -> context.output(counted)).getMessage())); + stages.define(Stage.placement("test:reader")).requires(counted).run(context -> observed.add(context.output(counted).count)); + stages.define(Stage.placement("test:snoop")).run(context -> observed.add( + assertThrows(IllegalStateException.class, () -> context.output(height)).getMessage())); + })); + + assertTrue(place(graph, flatEdit(), ConfiguredSettings.none()).isPlaced()); + assertEquals(10, observed.get(1)); + assertTrue(observed.get(2).toString().contains("before it completed"), observed.get(2).toString()); + assertTrue(observed.contains(2)); + assertTrue(observed.contains("Stage test:snoop read the output of test:height without requiring it; " + + "add requires(test:height) to its definition")); + } + + @Test + void nullOutputsFailTheInvocation() { + var graph = resolve(Pipeline.PLACEMENT, module("test:nulls", stages -> + stages.define(Stage.placement("test:nulls/value", Integer.class)).produce(context -> null))); + var edit = flatEdit(); + assertThrows(NullPointerException.class, () -> place(graph, edit, ConfiguredSettings.none())); + assertEquals(MemoryEdit.Status.CLOSED, edit.status()); + assertFalse(edit.committed()); + } + + @Test + void conditionalStagesCascadeToDependentsWithoutAnyError() { + var toggled = Stage.placement("test:toggled", Integer.class); + var dependent = Stage.placement("test:dependent"); + var unrelated = Stage.placement("test:unrelated"); + var events = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:cascade", stages -> { + stages.define(toggled).when(Toggle.class).produce((context, toggle) -> { + events.add("toggled"); + return 1; + }); + stages.define(dependent).requires(toggled).run(context -> events.add("dependent:" + context.output(toggled))); + stages.define(unrelated).run(context -> events.add("unrelated")); + })); + + place(graph, flatEdit(), ConfiguredSettings.none()); + assertEquals(List.of("unrelated"), events); + events.clear(); + place(graph, flatEdit(), ConfiguredSettings.of(new Toggle())); + assertEquals(List.of("toggled", "dependent:1", "unrelated"), events); + } + + @Test + void skippedBlocksAreHiddenFromLaterStagesOfThePass() { + var written = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:skip", stages -> { + var filter = Stage.placementBlock("test:filter"); + stages.define(filter).run(context -> { + if (context.block().position().x() == 0) context.skip(); + }); + stages.define(Stage.placementBlock("test:write")).requires(filter).run(context -> written.add(context.block().position().x())); + })); + + place(graph, flatEdit(), ConfiguredSettings.none()); + assertEquals(List.of(1), written); + } + + @Test + void rejectionStopsTheAttemptAndCommitsNothing() { + var events = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:reject", stages -> { + var write = Stage.placementBlock("test:write"); + stages.define(write).run(context -> { + events.add("write"); + context.access().set(new PlacedBlock(new BlockPosition(0, 10, 0), STONE, Optional.empty())); + context.reject("blocked"); + context.reject("ignored"); + }); + stages.define(Stage.placement("test:after")).requires(write).run(context -> events.add("after")); + })); + var edit = flatEdit(); + + var outcome = place(graph, edit, ConfiguredSettings.none()); + assertEquals(PlacementOutcome.Status.REJECTED, outcome.status()); + assertEquals(Optional.of("blocked"), outcome.rejection()); + assertEquals(List.of("write"), events); + assertFalse(edit.committed()); + assertEquals(MemoryEdit.Status.CLOSED, edit.status()); + } + + @Test + void stagesGetBufferedAccessWithoutTransactionOwnershipAndViewsExpire() { + var retained = new ArrayList(); + var graph = resolve(Pipeline.PLACEMENT, module("test:access", stages -> + stages.define(Stage.placement("test:access/write")).run(context -> { + assertFalse(context.access() instanceof PlacementEdit); + assertThrows(IllegalStateException.class, () -> ((BlockStageContext) context).block()); + context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty())); + assertEquals(STONE, context.access().get(1, 10, 1)); + retained.add(context.access()); + }))); + var edit = flatEdit(); + + assertTrue(place(graph, edit, ConfiguredSettings.none()).isPlaced()); + assertEquals(STONE, edit.publishedAt(1, 10, 1)); + assertThrows(IllegalStateException.class, () -> retained.getFirst().get(1, 10, 1)); + } + + @Test + void failuresDiscardBufferedWrites() { + var graph = resolve(Pipeline.PLACEMENT, module("test:fail", stages -> + stages.define(Stage.placement("test:fail/work")).run(context -> { + context.access().set(new PlacedBlock(new BlockPosition(1, 10, 1), STONE, Optional.empty())); + throw new IllegalStateException("boom"); + }))); + var edit = flatEdit(); + assertThrows(IllegalStateException.class, () -> place(graph, edit, ConfiguredSettings.none())); + assertFalse(edit.committed()); + assertEquals(MemoryEdit.Status.CLOSED, edit.status()); + } + + @Test + void runnersOnlyAcceptTheirOwnPipeline() { + var empty = resolve(Pipeline.CHUNK); + assertThrows(IllegalArgumentException.class, () -> new PlacementRunner(empty)); + assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.PLACEMENT))); + assertTrue(empty.describe().contains("CHUNK pipeline: 0 stages, 0 block passes")); + } + + static final class Counter { + int count; + } +} diff --git a/src/test/java/com/volmit/support/MemoryEdit.java b/src/test/java/com/volmit/support/MemoryEdit.java new file mode 100644 index 000000000..84a8bf2b3 --- /dev/null +++ b/src/test/java/com/volmit/support/MemoryEdit.java @@ -0,0 +1,93 @@ +package com.volmit.support; + +import com.volmit.block.BlockState; +import com.volmit.mantle.BlockBox; +import com.volmit.mantle.Mantle; +import com.volmit.placement.PlacedBlock; +import com.volmit.placement.PlacedMarker; +import com.volmit.placement.PlacementEdit; +import com.volmit.world.BlockPosition; +import com.volmit.world.BlockView; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** In-memory transactional test adapter over a base view; production storage is absent. */ +public final class MemoryEdit implements PlacementEdit { + public enum Status { OPEN, COMMITTED, CLOSED } + + private final BlockView base; + private final Map pending = new HashMap<>(); + private final Map published = new HashMap<>(); + private final List pendingMarkers = new ArrayList<>(); + private final List publishedMarkers = new ArrayList<>(); + private Status status = Status.OPEN; + private boolean committed; + + public MemoryEdit(BlockView base) { + this.base = base; + } + + public boolean committed() { return committed; } + public Status status() { return status; } + public Map published() { return Map.copyOf(published); } + public List publishedMarkers() { return List.copyOf(publishedMarkers); } + + public BlockState publishedAt(int x, int y, int z) { + return published.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z)); + } + + @Override + public BlockBox bounds() { + checkOpen(); + return base.bounds(); + } + + @Override + public BlockState get(int x, int y, int z) { + checkOpen(); + return pending.getOrDefault(new BlockPosition(x, y, z), base.get(x, y, z)); + } + + @Override + public void set(PlacedBlock block) { + checkOpen(); + var position = block.position(); + if (!base.bounds().contains(position.x(), position.y(), position.z())) { + throw new IndexOutOfBoundsException("Write outside prepared area: " + position); + } + pending.put(position, block.state()); + } + + @Override + public void marker(PlacedMarker marker) { + checkOpen(); + pendingMarkers.add(marker); + } + + @Override + public Mantle mantle() { + throw new AssertionError("Unused mantle"); + } + + @Override + public void commit() { + checkOpen(); + published.putAll(pending); + publishedMarkers.addAll(pendingMarkers); + committed = true; + status = Status.COMMITTED; + } + + @Override + public void close() { + pending.clear(); + pendingMarkers.clear(); + status = Status.CLOSED; + } + + private void checkOpen() { + if (status != Status.OPEN) throw new IllegalStateException("Edit is " + status); + } +} diff --git a/src/test/java/com/volmit/support/TestContexts.java b/src/test/java/com/volmit/support/TestContexts.java index 830b25185..605f34129 100644 --- a/src/test/java/com/volmit/support/TestContexts.java +++ b/src/test/java/com/volmit/support/TestContexts.java @@ -2,44 +2,61 @@ package com.volmit.support; import com.volmit.config.FeatureSettings; import com.volmit.generation.GenerationContext; +import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.object.ObjectTransformer; import com.volmit.placement.PlacementContext; import com.volmit.resource.PackResources; import com.volmit.world.TerrainSampler; import com.volmit.world.BlockView; +import java.util.Map; import java.util.Random; import java.util.random.RandomGenerator; /** Tests needing no platform facilities fail loudly if code starts using one. */ public final class TestContexts { + public static final long SEED = 42; + private TestContexts() {} - public static GenerationContext generation() { + public static GenerationContext generation(Map, Hunk> hunks) { return new GenerationContext() { - private final RandomGenerator random = new Random(42); + private final RandomGenerator random = new Random(SEED); public int originX() { return 0; } public int originY() { return -64; } public int originZ() { return 0; } - public long worldSeed() { return 42; } + public long worldSeed() { return SEED; } public RandomGenerator random() { return random; } public PackResources resources() { throw new AssertionError("Unused resources"); } public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } public FeatureSettings settings() { throw new AssertionError("Unused settings"); } public Mantle mantle() { throw new AssertionError("Unused mantle"); } + @SuppressWarnings("unchecked") + public Hunk hunk(Class type) { + var hunk = hunks.get(type); + if (hunk == null) throw new IllegalArgumentException("No hunk of " + type.getName()); + return (Hunk) hunk; + } }; } public static PlacementContext placement() { + return placement(null); + } + + public static PlacementContext placement(BlockView blocks) { return new PlacementContext() { - private final RandomGenerator random = new Random(42); - public long worldSeed() { return 42; } + private final RandomGenerator random = new Random(SEED); + public long worldSeed() { return SEED; } public RandomGenerator random() { return random; } public PackResources resources() { throw new AssertionError("Unused resources"); } public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } public FeatureSettings settings() { throw new AssertionError("Unused settings"); } public ObjectTransformer objects() { throw new AssertionError("Unused transforms"); } - public BlockView blocks() { throw new AssertionError("Unused blocks"); } + public BlockView blocks() { + if (blocks == null) throw new AssertionError("Unused blocks"); + return blocks; + } }; } } diff --git a/src/test/java/com/volmit/support/TestTerrain.java b/src/test/java/com/volmit/support/TestTerrain.java new file mode 100644 index 000000000..a106df332 --- /dev/null +++ b/src/test/java/com/volmit/support/TestTerrain.java @@ -0,0 +1,30 @@ +package com.volmit.support; + +import com.volmit.block.BlockState; +import com.volmit.mantle.BlockBox; +import com.volmit.world.BlockView; +import java.util.function.IntBinaryOperator; + +/** Prepared pre-placement blocks: stone below a per-column ground height, air above. */ +public final class TestTerrain implements BlockView { + public static final BlockState STONE = new BlockState("minecraft:stone"); + public static final BlockState AIR = new BlockState("minecraft:air"); + public static final BlockBox BOUNDS = new BlockBox(-16, 0, -16, 16, 32, 16); + + private final IntBinaryOperator groundHeight; + + public TestTerrain(IntBinaryOperator groundHeight) { + this.groundHeight = groundHeight; + } + + @Override + public BlockBox bounds() { + return BOUNDS; + } + + @Override + public BlockState get(int x, int y, int z) { + if (!BOUNDS.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside test terrain: " + x + "," + y + "," + z); + return y < groundHeight.applyAsInt(x, z) ? STONE : AIR; + } +}