From 97ac2a29828169ce316459bf42f0939e2ee133e5 Mon Sep 17 00:00:00 2001 From: piexel Date: Thu, 8 Oct 2026 11:31:03 +0200 Subject: [PATCH] Read settings per column with every level as its own entry, add the mantle pipeline, host types and the one-option shorthand Settings no longer resolve to one value per type. FeatureSettings.at(type, x, z) returns one entry per level that declares the type at that column (dimension, region, surface biome, placement), each with its level, source and value; levels stack and a module decides what several mean. Conditional stage bodies receive every configured entry. Chunk and mantle runners collect a chunk's settings themselves, so a stage runs when any column of the chunk configures it. Work that writes the mantle or reaches beyond its chunk moves to a new MANTLE pipeline (Stage.mantle, MantleRunner) that the host runs around a chunk before it generates. Chunk stages may no longer declare a reach or mantle writes and see the mantle read-only. Built-in settings may hold host types the host describes itself (ModuleHost.describingHostTypesIn, ValueKind.HostKind); pack modules cannot. FeatureSchema.shorthand() names the only option of settings packs may write as a bare value. --- CONTRACTS.md | 22 ++- DESIGN.md | 87 +++++++++--- README.md | 90 ++++++++++--- .../com/volmit/config/FeatureSettings.java | 36 +++-- .../volmit/generation/GenerationContext.java | 4 +- .../generation/MantleGenerationContext.java | 21 +++ .../java/com/volmit/host/ChunkInvocation.java | 4 +- .../java/com/volmit/host/ChunkRunner.java | 14 +- .../java/com/volmit/host/ChunkSettings.java | 51 +++++++ .../com/volmit/host/ConfiguredSettings.java | 61 ++++++--- .../java/com/volmit/host/DefaultValues.java | 2 + src/main/java/com/volmit/host/HostTypes.java | 32 +++++ .../java/com/volmit/host/LoadedModules.java | 16 ++- src/main/java/com/volmit/host/LoadedPack.java | 8 +- .../com/volmit/host/MantleInvocation.java | 71 ++++++++++ .../java/com/volmit/host/MantleRunner.java | 36 +++++ src/main/java/com/volmit/host/ModuleHost.java | 34 +++-- .../com/volmit/host/PackSchemaBuilder.java | 9 +- .../java/com/volmit/host/ReadOnlyMantle.java | 64 +++++++++ .../com/volmit/host/StageDeclaration.java | 11 ++ .../com/volmit/host/StageGraphBuilder.java | 7 + .../java/com/volmit/host/StageInvocation.java | 5 +- src/main/java/com/volmit/host/StageReach.java | 4 +- src/main/java/com/volmit/host/TypeDrafts.java | 11 +- src/main/java/com/volmit/host/ValueKinds.java | 24 +++- .../com/volmit/host/schema/FeatureSchema.java | 8 ++ .../com/volmit/host/schema/ValueKind.java | 10 ++ .../volmit/stage/BlockStageDefinition.java | 5 +- .../java/com/volmit/stage/ChunkStage.java | 4 +- .../ConditionalBlockStageDefinition.java | 5 +- .../stage/ConditionalStageDefinition.java | 5 +- .../java/com/volmit/stage/MantleStage.java | 18 +++ .../com/volmit/stage/MantleStageContext.java | 6 + src/main/java/com/volmit/stage/Pipeline.java | 11 +- .../java/com/volmit/stage/SettingsAction.java | 11 +- .../volmit/stage/SettingsBlockCollector.java | 11 +- .../com/volmit/stage/SettingsFunction.java | 11 +- src/main/java/com/volmit/stage/Stage.java | 10 +- .../com/volmit/stage/StageDefinition.java | 15 ++- .../java/com/volmit/stage/StageGraph.java | 2 + .../com/volmit/example/ChunkPipelineTest.java | 125 +++++++++++++++++- .../example/PlacementLifecyclePortTest.java | 9 +- .../com/volmit/example/chunk/GrassModule.java | 16 ++- .../com/volmit/example/chunk/VeinModule.java | 77 +++++++++++ .../volmit/example/chunk/VeinSettings.java | 31 +++++ .../com/volmit/example/hosttypes/Palette.java | 13 ++ .../volmit/example/placement/MossModule.java | 5 +- .../volmit/example/placement/SnowModule.java | 5 +- .../volmit/example/placement/StiltModule.java | 5 +- .../volmit/example/terrain/LayersModule.java | 22 +++ .../example/terrain/LayersSettings.java | 19 +++ .../volmit/host/ConfiguredSettingsTest.java | 43 ++++++ .../com/volmit/host/DiscoveredModuleTest.java | 2 +- .../com/volmit/host/ModuleRegistryTest.java | 8 +- .../java/com/volmit/host/PackModulesTest.java | 24 ++-- .../java/com/volmit/host/PackSchemaTest.java | 45 ++++++- .../java/com/volmit/host/StageGraphTest.java | 52 +++++--- .../com/volmit/host/StageStreamsTest.java | 2 +- .../com/volmit/support/ColumnSettings.java | 32 +++++ .../java/com/volmit/support/MemoryMantle.java | 81 ++++++++++++ .../java/com/volmit/support/TestContexts.java | 28 +++- 61 files changed, 1316 insertions(+), 184 deletions(-) create mode 100644 src/main/java/com/volmit/generation/MantleGenerationContext.java create mode 100644 src/main/java/com/volmit/host/ChunkSettings.java create mode 100644 src/main/java/com/volmit/host/HostTypes.java create mode 100644 src/main/java/com/volmit/host/MantleInvocation.java create mode 100644 src/main/java/com/volmit/host/MantleRunner.java create mode 100644 src/main/java/com/volmit/host/ReadOnlyMantle.java create mode 100644 src/main/java/com/volmit/stage/MantleStage.java create mode 100644 src/main/java/com/volmit/stage/MantleStageContext.java create mode 100644 src/test/java/com/volmit/example/chunk/VeinModule.java create mode 100644 src/test/java/com/volmit/example/chunk/VeinSettings.java create mode 100644 src/test/java/com/volmit/example/hosttypes/Palette.java create mode 100644 src/test/java/com/volmit/example/terrain/LayersModule.java create mode 100644 src/test/java/com/volmit/example/terrain/LayersSettings.java create mode 100644 src/test/java/com/volmit/host/ConfiguredSettingsTest.java create mode 100644 src/test/java/com/volmit/support/ColumnSettings.java create mode 100644 src/test/java/com/volmit/support/MemoryMantle.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 98450fcee..743f068d5 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -14,14 +14,16 @@ types that carry them and lists what the Iris adapter still owes. | Randomness independent of other modules | `StageContext.random()`, host `StageStreams`, invocation seed passed to the runners | | Random values identical on every JDK | `WorldRandom`, pinned by `WorldRandomTest` | | Module-owned work and ordering | `Stage`, `StageRef`, stage definitions, `requires`/`softAfter`/`softBefore` | -| Activation by configuration | `when(settingsType)`, host `ConfiguredSettings` | +| Activation by configuration | `when(settingsType)`, host `ConfiguredSettings` (entries per type; any column of a chunk) | +| Stacked settings levels, read per column | `FeatureSettings.at(type, x, z)`, `FeatureSettings.Entry` (level, source, value) | | Typed results between modules | stage outputs, `StageContext.output` | | Per-block work with single-pass cost | `BlockStage`, fused block passes | | Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` | -| Reference execution | host `PlacementRunner`, `ChunkRunner` | +| Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner` | +| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only | | Annotated settings | `IrisFeature`, `@Feature` (id as JSON key, built-in alias), config annotations, `OptionsMetadata` | | Area a stage writes | `reach(blocks)`, `writesMantle(...)` on stage definitions, host `StageReach`, `PipelineReach` | -| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind`) | +| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema` with `shorthand()`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | | Pack-scoped resolution | `ResourceId`, `ResourceKey`, `PackResources` | @@ -73,8 +75,15 @@ running Iris is the pack publisher's responsibility. - Port the engine as ordinary modules. Keep `iris:*` stage ids stable once packs or addons depend on them, because soft references and diagnostics use them. -- Build `ConfiguredSettings` per placement and per chunk from decoded pack JSON, with explicit - precedence between dimension, region, biome and placement declarations. +- Answer `FeatureSettings.at(type, x, z)` with one entry per level that declares the type at that + column: the dimension, the column's region, its surface biome and, in a placement, the placement, in + that order. Never merge or override levels. Pass each placement's own declarations as + `ConfiguredSettings.placement(...)`; the chunk and mantle runners collect a chunk's settings + themselves. +- Decode a value that is not a JSON object into settings with exactly one option + (`FeatureSchema.shorthand()`), and render the schema to accept both forms. +- Name the packages of the classes Iris describes itself with `ModuleHost.describingHostTypesIn(...)`, + decode them as Iris does, and render each `HostKind` with Iris's own description of the class. - Preserve pack field names and defaults, seed derivation, RNG draw order, coordinate conventions and iteration order where existing worlds must not change. Per-stage streams do not reproduce Iris's current shared draws; matching them where worlds must stay the same is adapter @@ -84,6 +93,9 @@ running Iris is the pack publisher's responsibility. - Prepare the area a placement or chunk may read or write, including neighbors: the pipeline's `reach()` around the chunk or the placed object's bounds, each mantle layer by its own maximum. Never clip. +- Run the mantle pipeline (`MantleRunner`) for every chunk within its reach of a chunk, each chunk once, + before that chunk generates, with the mantle widened by the reach. Give chunk stages that chunk's + mantle; `ChunkRunner` makes it read-only. - Make placement edits atomic across blocks, block entities, markers and mantle in generation storage. Abort chunk publication when any stage fails. - Preserve unknown persisted mantle layers or fail explicitly. diff --git a/DESIGN.md b/DESIGN.md index 928d241d2..39ccaacf9 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -22,14 +22,18 @@ flowchart TD Settings --> Catalog[Frozen feature catalog] Register --> Catalog Resolve --> Placement[Placement graph] + Resolve --> MantleGraph[Mantle graph] Resolve --> Chunk[Chunk graph] Catalog --> Schema[PackSchema for studio] Schema --> Render[Host JSON Schema and workspace] Catalog --> Decode[Host JSON decoding] Decode --> Configured[ConfiguredSettings per invocation] Configured --> Placement + Configured --> MantleGraph Configured --> Chunk Placement --> Edit[Buffered placement edit] + MantleGraph --> MantleData[Mantle around the chunk] + MantleData --> Chunk Chunk --> Hunk[Local hunks] Edit --> Publish[Host publication] Hunk --> Publish @@ -283,7 +287,7 @@ the texts and are tested on their own. ## Stages -A stage is a constant created by `Stage.placement`, `Stage.placementBlock` or `Stage.chunk`. Its +A stage is a constant created by `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` or `Stage.mantle`. Its identity is that object. Another module that wants to depend on it references the owner's constant, which makes the dependency a compile-time one. A copy with the same id is rejected at resolve time. @@ -293,6 +297,7 @@ resolve time. | `PlacementStage` | PLACEMENT | once per placement attempt | `PlacementStageContext` | | `BlockStage` | PLACEMENT | once per object block, in a block pass | `BlockStageContext` | | `ChunkStage` | CHUNK | once per chunk invocation | `ChunkStageContext` | +| `MantleStage` | MANTLE | once per chunk, before the chunks it reaches generate | `MantleStageContext` | Rules enforced by `StageGraphBuilder` and the resolver: @@ -349,18 +354,33 @@ the invocation. The graph is resolved once per pack load. Activation is decided per invocation: -1. The host passes `ConfiguredSettings`, at most one value per settings type, for the placement - or chunk. Merging dimension, region, biome and placement declarations is host policy. +1. The invocation gets `ConfiguredSettings`: for each settings type, the entries configured for it, in + level order. For a placement the host passes the placement's own declarations. For a chunk or mantle + invocation the runner collects them itself from `FeatureSettings`: every distinct entry, by level and + source, of the chunk's 16 by 16 columns. 2. The invocation looks up each distinct `when` type once. -3. One pass in resolved order marks a stage active when its settings are present (or it has no +3. One pass in resolved order marks a stage active when its settings have an entry (or it has no condition) and every stage it requires is active. So an inactive requirement deactivates its dependents. That is not an error. Soft edges never affect activation. The cost per invocation is two small arrays and one pass over stages and -REQUIRED edges. The settings value is passed to the body as its second argument. +REQUIRED edges, plus, for chunks, one settings read per column and conditioned type. The entries are +passed to the body as its second argument, a never-empty `List>`. -For chunks, activation is per chunk. A stage that varies inside the chunk still reads -`ctx.settings().at(...)` per position. +A chunk stage is active when any column of the chunk configures it, so a biome border inside a chunk +never hides a feature on either side. The body then reads `ctx.settings().at(type, x, z)` per column, +or at the chunk's centre column (local 7, 7) for behaviour that happens once per chunk. + +### Settings levels + +Settings are declared at levels: the dimension, a region, a biome (the column's surface biome) and a +placement. `FeatureSettings.at(type, x, z)` returns one entry per level that declares the type at that +column, in that order, each with its level, the declaring resource and the value. Levels stack: there is +no "most specific wins" and no field merge. A module decides what several entries mean: deposits run +once per entry, a surface block may take the most specific. The alternatives each hide a decision from +the module: overriding would make a biome's deposits silently drop the dimension's, merging would need a +rule per field. Something spanning several columns reads at one origin column: per chunk the centre +column, per placed object the column it is anchored at. Cave biomes are not a level. ### Diagnostics @@ -453,12 +473,30 @@ from the variant seed the host chooses. ## Chunk invocations -`ChunkRunner.generate(inputs, invocationSeed, settings)` runs active chunk stages once each in resolved order. +`ChunkRunner.generate(inputs, invocationSeed)` runs active chunk stages once each in resolved order. `GenerationContext.hunk(type)` returns the host-owned local volume of that value type, shared by all stages of the invocation. Hunk coordinates are local; samples and mantle coordinates are -world blocks. The runner does no neighbor scheduling or rollback. A failed invocation must stop +world blocks. A chunk stage writes only its own chunk and reads the mantle: the runner hands it a view +whose writes throw. The runner does no neighbor scheduling or rollback. A failed invocation must stop the host from publishing the chunk. +## Mantle invocations + +Some work writes beyond its chunk: a carver whose tunnels cross chunk borders, a vein running on into +the next chunk. A chunk stage cannot do that, because the host may already have generated the +neighbor. Such work is a mantle stage. `MantleRunner.generate(inputs, invocationSeed)` runs the active +mantle stages of one chunk in resolved order, against the mantle around it (`MantleGenerationContext`: +origin, terrain, settings, mantle), without a block hunk. The host runs it for every chunk within the +mantle pipeline's reach of a chunk, each chunk once, before that chunk generates, so a chunk's mantle is +complete when its chunk stages read it. In Iris it is one mantle component whose radius is the +pipeline's reach. + +The mantle pipeline is the only place that writes the mantle during generation, and mantle and chunk +pipelines meet only through mantle layers: an edge between them is a cross-pipeline edge and fails the +load. Within one invocation, stages can still require each other and read outputs. Across chunks they +cannot: a mantle stage that reads another mantle stage's layer outside its own chunk sees whatever has +run there so far, which depends on the order the host generates chunks in. + ## Reach A stage may write outside its footprint: a carver reaches into neighbor chunks, a tree's leaves spread @@ -466,16 +504,18 @@ past the object's trunk. The host has to prepare that area, and the mantle in it runs. Stages declare it in their definition: ```java -graph.define(CARVE).reach(32).writesMantle(CarveModule.CAVES).run(CarveModule::carve); +graph.define(CARVE).reach(32).writesMantle(CaveModule.CAVES).run(CaveModule::carve); // CARVE is a mantle stage ``` - `reach(blocks)`: how far, in blocks along X and Z, the stage writes blocks or mantle values beyond - its footprint. The footprint is the chunk's 16 by 16 columns for a chunk stage and the X/Z bounds of - the placed object for a placement or block stage. Whole columns: height is not limited, because - Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or + its footprint. The footprint is the chunk's 16 by 16 columns for a mantle stage and the X/Z bounds of + the placed object for a placement or block stage. A chunk stage writes only its chunk; declaring a + reach above 0 on one fails the install, naming mantle stages as the place for the work. Whole + columns: height is not limited, because Iris prepares chunks and mantle as full columns. Leaving it out means 0. Declaring it twice or negative fails while the module installs. - `writesMantle(layers...)`: the mantle layers the stage writes. Every layer must be registered by - some module with the same value type, or the pack load fails naming stage and layer. + some module with the same value type, or the pack load fails naming stage and layer. Chunk stages + cannot declare any. Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`: the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages @@ -485,7 +525,8 @@ decided once per pack load. `describe()` lists each stage's reach. One number per stage, not per layer: a stage that writes two layers at different distances declares the larger. The host can still size each layer's mantle from the per-layer maximum. Reads are not declared separately: the host prepares the pipeline's reach around every chunk or placement, so a -stage may read what others wrote that far out. A stage that must read farther declares that distance +stage may read what others wrote that far out (for mantle stages, see the ordering caveat under Mantle +invocations). A stage that must read farther declares that distance as its reach. Terrain samples are computed, not prepared, and need nothing. ## Settings, geometry and storage @@ -502,6 +543,13 @@ ids and alias collisions per attachment target, including reserved host fields. ### JSON keys and aliases +A feature whose settings class has exactly one option may be written as that option's value instead of +an object holding it: `"snow": 0.5` for `"snow": {"amount": 0.5}`, or a bare JSON list for a class holding +one list. Existing pack JSON writes several settings that way, and keeping the format meant either this +rule or a compatibility layer per key. `FeatureSchema.shorthand()` returns the option when there is +exactly one, the host decodes a value that is not a JSON object into it, and renders the schema to accept +both forms. A `@Snippet` class written as a `"snippet/..."` string stays a snippet reference. + Packs write a feature's settings under its feature id at each of its targets: `"example:moss": {...}`. The id is unique, namespaced and owned by one module, so two modules can never claim the same key, and a key can never be one of the host's own fields: those have no `:`. @@ -572,8 +620,17 @@ already keep module fields from colliding with them. | `List`, `E[]` | `ListKind(E, false)` | | `Set` | `ListKind(E, true)` | | `Map` | `MapKind(V)` | +| a class in a host type package, in built-in settings | `HostKind(class name)` | | any other concrete class | `ObjectKind(class name)` | +Host types are classes the host describes in studio itself, such as Iris's palettes and noise styles, +which built-in settings keep while their features move into modules. The host names their packages with +`ModuleHost.describingHostTypesIn(...)`; the builder neither reads their fields nor describes them, and +the host renders its own description where a `HostKind` appears. Pack modules' settings cannot use them: +pack modules never see host classes anyway, and a host type in their settings fails the load. Without +this, built-in settings would have to replace every Iris type with a describable copy before any feature +could move. + Everything else fails the load with the field, its settings and its module named, and what fits instead: diff --git a/README.md b/README.md index 05468b9d7..d3922ca3d 100644 --- a/README.md +++ b/README.md @@ -24,14 +24,16 @@ public final class MossModule implements IrisModule { .when(MossSettings.class) // only where a pack configures moss .requires(AnchorModule.HEIGHT, BlocksModule.COMPLETE) .softAfter(StageRef.of("iris:snow/finish")) // ordering only, if snow is installed - .run((ctx, moss) -> spread(ctx.output(AnchorModule.HEIGHT), moss)); + .run((ctx, moss) -> spread(ctx.output(AnchorModule.HEIGHT), moss.getFirst().value())); } } ``` -- `Stage.placement`, `Stage.placementBlock` and `Stage.chunk` create stages for the placement - pipeline (once per attempt), the placement pipeline (once per object block) and the chunk - pipeline. Pass an output class to give a stage a typed output. +- `Stage.placement`, `Stage.placementBlock`, `Stage.chunk` and `Stage.mantle` create stages for the + placement pipeline (once per attempt), the placement pipeline (once per object block), the chunk + pipeline (once per chunk, writing only that chunk) and the mantle pipeline (once per chunk, before + the chunks it reaches generate, writing only the mantle). Pass an output class to give a stage a + typed output. - A stage id starts with the id of the module that defines it and `/`: module `example:moss` defines `example:moss/spread`, never `example:other/...`. Module ids therefore contain no `/`. Defining an id twice fails. @@ -40,6 +42,8 @@ public final class MossModule implements IrisModule { - `softAfter` and `softBefore` take ids and only order. There is no hard "before". - `run(...)` ends a stage without output, `produce(...)` a stage with output and `accumulate(initial, collector)` a block stage whose accumulator becomes its output. +- `when(settingsType)` runs the stage only where those settings are configured, and the body gets every + configured entry (see Settings levels below). - `ctx.output(stage)` works only for stages the current stage transitively requires. - `ctx.random()` is the stage's own random stream, derived from the invocation seed and the stage id. Installing or removing other modules, or how much they draw, never changes what a stage @@ -53,6 +57,32 @@ for module `iris:snow`. A settings type named in `when(...)` needs a feature id module naming it owns in that sense, or its owner must have registered it, so another module may still condition its stages on it, as moss does on `iris:snow`. +## Settings levels + +Settings can be declared at several levels: the dimension, a region, a biome and, in a placement, the +placement itself. Each level's declaration is its own entry, and levels stack: nothing is merged and no +level overrides another. A module decides what several entries mean, such as running a deposit once per +entry, or using the most specific one. + +```java +for (var entry : ctx.settings().at(DepositSettings.class, worldX, worldZ)) { // every level at this column + entry.level(); // DIMENSION, REGION, BIOME or OBJECT_PLACEMENT, in that order + entry.source(); // the declaring resource, such as overworld:biome/desert/dunes + entry.value(); // the decoded settings +} +``` + +Settings are read per column, at the column's surface biome. A chunk or mantle stage conditioned with +`when(...)` runs when any column of the chunk has an entry, so a biome border inside a chunk never +hides a feature, and its body receives every distinct entry of the chunk. It then reads +`ctx.settings().at(...)` per column, or at the chunk's centre column (local 7, 7) for something that +happens once per chunk. Something that spans several columns, such as a placed object, uses the column +it treats as its origin. In a placement the body receives the placement's own entry; a placement +declares each settings type once. + +A feature whose settings class has exactly one option may be written as that option's value, such as +`"snow": 0.5` for `"snow": {"amount": 0.5}` or a bare list for a class holding one list. + ## Random streams Stages and object generators draw from `com.volmit.random.WorldRandom`, an IrisApi type whose every @@ -64,20 +94,29 @@ JDK may change, so use `pick` and `shuffle` instead of `Collections.shuffle`. Bo unbiased, `nextDouble` never returns its bound, and invalid bounds throw. It is not thread-safe: a stage uses its own stream within one invocation and must not share or keep it. -## Reach +## The mantle pipeline and reach -A stage that writes outside its chunk or object declares how far, so the host can prepare that area -and its mantle first: +A chunk stage writes only its own chunk: the host may already have generated its neighbors. Work that +writes the mantle or reaches beyond its chunk, such as a carver or a vein that runs on into the next +chunk, is a mantle stage. The host runs the mantle pipeline for every chunk within the pipeline's reach +of a chunk before that chunk generates, so the chunk's mantle is complete when its chunk stages read it. +The two pipelines meet only in the mantle. ```java -graph.define(CARVE).reach(32).writesMantle(CarveModule.CAVES).run(CarveModule::carve); +public static final MantleStage CARVE = Stage.mantle("example:caves/carve"); +public static final ChunkStage APPLY = Stage.chunk("example:caves/apply"); + +graph.define(CARVE).when(CaveSettings.class).reach(32).writesMantle(CAVES).run(CaveModule::carve); +graph.define(APPLY).run(CaveModule::apply); // reads its own chunk's CAVES and writes blocks ``` `reach(blocks)` is the distance in blocks along X and Z beyond the stage's footprint: the chunk for a -chunk stage, the X/Z bounds of the placed object for a placement stage, whole columns in both cases. +mantle stage, the X/Z bounds of the placed object for a placement stage, whole columns in both cases. It defaults to 0. `writesMantle(...)` names the mantle layers the stage writes; each must be -registered by some module. `pack.chunk().reach()` and `pack.placement().reach()` give the host the -largest reach of a pipeline and the largest per mantle layer. +registered by some module. A chunk stage that declares either fails the install, and its mantle is +read-only. `pack.mantle().reach()` and `pack.placement().reach()` give the host the largest reach of a +pipeline and the largest per mantle layer. A mantle stage should not rely on what other mantle stages +wrote in other chunks: whether they have run there yet depends on which chunk the host generates first. ## Module jars @@ -188,6 +227,11 @@ public final class FloraSettings implements IrisFeature { a short key existing pack JSON uses; a pack module that sets one fails the load. One JSON object may not hold both. - Options keep the order the class declares them in, a superclass's first. +- Settings with exactly one option have a shorthand: packs may write the option's value instead of an + object, and `FeatureSchema.shorthand()` says so. +- Built-in settings may hold classes the host describes itself, such as Iris's palettes, which the host + names with `ModuleHost.describingHostTypesIn(...)`. They appear as `HostKind` and pack modules cannot + use them. - Settings named in `when(...)` and object generator settings are described automatically. Settings that no stage names, such as ones read only through `FeatureSettings.at(...)`, are registered with `registry.registerSettings(WindSettings.class)` in `register`. Their feature id follows the module @@ -211,6 +255,7 @@ var host = ModuleHost.of(builtInModules) .exposing("art.arcane.iris.engine.modules") // besides the API .reservingNamespaces("iris") .reservingFields(reservedHostFields) + .describingHostTypesIn("art.arcane.iris.engine.object") // classes the host describes itself .copyingJarsTo(cacheDirectory) // default: java.io.tmpdir .loggingTo(serverLogger); // a System.Logger; default: System.getLogger @@ -219,18 +264,20 @@ try (var pack = LoadedPack.load(packRoot, host)) { System.out.println(pack.placement().describe()); var placer = new PlacementRunner(pack.placement()); - PlacementOutcome outcome = placer.place(request, edit, inputs, placementSeed, ConfiguredSettings.of(stilt, snow)); + PlacementOutcome outcome = placer.place(request, edit, inputs, placementSeed, + ConfiguredSettings.placement(objectId, stilt, snow)); - new ChunkRunner(pack.chunk()).generate(generationContext, chunkSeed, chunkSettings); + new MantleRunner(pack.mantle()).generate(mantleContext, chunkSeed); // each chunk within reach, first + new ChunkRunner(pack.chunk()).generate(generationContext, chunkSeed); } // stop using the runners before the pack closes ``` `ModuleHost` holds what the host passes to every pack load: built-in modules (their `info()` is read -once, here), the host packages pack modules may use, the JSON fields the host itself uses and the -reserved namespaces. Each method adds to what earlier calls configured. Package names, namespaces and +once, here), the host packages pack modules may use, the JSON fields the host itself uses, the +reserved namespaces and the packages of the classes it describes itself. Each method adds to what earlier calls configured. Package names, namespaces and reserved field names are checked when it is built. `LoadedPack.load` loads the pack's jars, installs them after the built-ins, catalogs settings and registrations, -describes them for studio and resolves both pipelines. It returns a complete pack or throws with nothing left open. `close()` +describes them for studio and resolves the three pipelines. It returns a complete pack or throws with nothing left open. `close()` releases the pack's class loader and its jar copies. `PackModules` and `LoadedModules`, which it uses, stay available for tests and special cases. @@ -373,7 +420,9 @@ concurrent invocations and must not keep views, streams or mutable state. The tests cover graph resolution and every error path, fusion, activation cascade, outputs, rejection and rollback, install-order determinism, id ownership of stages, settings, objects and -mantle keys, reach per stage, pipeline and mantle layer (`StageGraphTest`, `ModuleRegistryTest`), and per-stage random streams: inserting a module +mantle keys, reach per stage, pipeline and mantle layer, chunk stages that declare reach or mantle +writes (`StageGraphTest`, `ModuleRegistryTest`), settings entries per type in level order +(`ConfiguredSettingsTest`), and per-stage random streams: inserting a module that draws leaves the other stages' draws unchanged, block stages draw one stream across their pass, and the derivation is pinned to values computed from its specification (`StageStreamsTest`). `WorldRandomTest` pins every `WorldRandom` method, bounds and edge cases to values computed by an @@ -385,7 +434,8 @@ descriptions, required, bounds, defaults (floats, nulls, sets, maps, objects, a enums, collections, references, nested classes with a cycle, snippets, object generator settings, explicit registration, built-in modules, the same result whatever the jar order, and the load error for each unsupported field type, misplaced `@Ref` (pack kinds on `ResourceId` included), unusable -class, bad or repeated snippet name and pack snippet outside its module's folder. +class, bad or repeated snippet name and pack snippet outside its module's folder, host types in built-in +settings (and the load error when a pack module uses one), and the one-option shorthand. `DiscoveredModuleTest` checks that `info()` is read once. `LoadedPackTest` loads a pack with built-ins and checks that a failed load and `close()` leave nothing open. `PackJarSnapshotTest` checks that classes come from the copies, that the original can be replaced while loaded, that copies go @@ -407,5 +457,7 @@ which JDK packages they may not use. `PackModulesAddExportsTest` runs in its own `--add-exports java.base/jdk.internal.misc=ALL-UNNAMED`; it checks that the exported package then loads and that other internal packages are still reported. `PackModulesSummaryTest` and `MissingClassesWarningTest` check the log texts. The example ports in `src/test/java/com/volmit/example` rebuild preparation, anchoring, block writes, stilt and -snow as separate modules, add a third-party moss module, and add a two-module chunk pipeline. There +snow as separate modules, add a third-party moss module, and add a two-module chunk pipeline whose +`ChunkPipelineTest` checks any-column activation, per-column reads, stacked levels, a mantle stage +writing into the next chunk that a chunk stage then reads, and the read-only mantle of chunk stages. There is no Minecraft integration or production storage in these tests. diff --git a/src/main/java/com/volmit/config/FeatureSettings.java b/src/main/java/com/volmit/config/FeatureSettings.java index 785dc8cba..a6a31d475 100644 --- a/src/main/java/com/volmit/config/FeatureSettings.java +++ b/src/main/java/com/volmit/config/FeatureSettings.java @@ -4,23 +4,35 @@ import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; import com.volmit.resource.ResourceId; import java.util.List; +import java.util.Objects; -/** Invocation-scoped lookup of applicable settings by attachment and world position. - * Results are immutable lists in pack declaration order, after the host applies inheritance - * rules. Targets remain separate: this interface never silently merges dimension/region/biome - * values. OBJECT_PLACEMENT is read from the current placement, or returns an empty list. - * Values must be treated as read-only. Bounds and lifetime match the invocation's sampler. +/** Invocation-scoped lookup of the settings that apply at one world column. + * + *

Every level that declares the settings contributes its own entry: the dimension, the region and + * the biome of the column, and in a placement the placement itself. Levels stack: nothing is merged or + * overridden, and a module decides what several entries mean, such as running a deposit once per + * entry. Entries are immutable lists in level order ({@link FeatureAttachment.Target} order). The + * biome is the column's surface biome; cave biomes are not a level. Values must be treated as + * read-only. Bounds and lifetime match the invocation's sampler. + * + *

Something that spans several columns, such as a chunk-wide pass or a placed object, reads the + * settings at one column it treats as its origin; per-chunk behaviour reads the chunk's centre column + * (local 7, 7). */ public interface FeatureSettings { - List> at(Class featureType, FeatureAttachment.Target target, - int worldX, int worldY, int worldZ); + List> at(Class featureType, int worldX, int worldZ); - /** source identifies the configuration owner; occurrence is unique within the pack snapshot. */ - record Entry(ResourceId source, ResourceId occurrence, F value) { + /** One level's declaration of the settings. + * + * @param level where the settings are declared: the dimension, a region, a biome or the placement + * @param source the resource that declares them, such as {@code overworld:biome/desert/dunes} + * @param value the decoded settings + */ + record Entry(FeatureAttachment.Target level, ResourceId source, F value) { public Entry { - java.util.Objects.requireNonNull(source, "source"); - java.util.Objects.requireNonNull(occurrence, "occurrence"); - java.util.Objects.requireNonNull(value, "value"); + Objects.requireNonNull(level, "level"); + Objects.requireNonNull(source, "source"); + Objects.requireNonNull(value, "value"); } } } diff --git a/src/main/java/com/volmit/generation/GenerationContext.java b/src/main/java/com/volmit/generation/GenerationContext.java index a308007be..229cdd5ac 100644 --- a/src/main/java/com/volmit/generation/GenerationContext.java +++ b/src/main/java/com/volmit/generation/GenerationContext.java @@ -15,7 +15,9 @@ public interface GenerationContext extends InvocationContext { TerrainSampler terrain(); FeatureSettings settings(); - /** Non-null mantle access scoped to this invocation; the host owns its lifetime. */ + /** Non-null mantle access scoped to this invocation; the host owns its lifetime. Chunk stages read it + * only: the mantle pipeline has finished around the chunk, and writes throw. + */ Mantle mantle(); /** The host-owned local volume of the given value type, shared by all stages of this diff --git a/src/main/java/com/volmit/generation/MantleGenerationContext.java b/src/main/java/com/volmit/generation/MantleGenerationContext.java new file mode 100644 index 000000000..957d49282 --- /dev/null +++ b/src/main/java/com/volmit/generation/MantleGenerationContext.java @@ -0,0 +1,21 @@ +package com.volmit.generation; + +import com.volmit.config.FeatureSettings; +import com.volmit.mantle.Mantle; +import com.volmit.world.TerrainSampler; + +/** Per-invocation inputs of the mantle pipeline for one chunk. Must not be retained after execution. */ +public interface MantleGenerationContext extends InvocationContext { + /** The chunk's first block along X, in world coordinates. */ + int originX(); + + /** The chunk's first block along Z, in world coordinates. */ + int originZ(); + + TerrainSampler terrain(); + + FeatureSettings settings(); + + /** The mantle of the chunk widened by the pipeline's reach, full height. Writes outside it throw. */ + Mantle mantle(); +} diff --git a/src/main/java/com/volmit/host/ChunkInvocation.java b/src/main/java/com/volmit/host/ChunkInvocation.java index e176ae10c..5f32a590c 100644 --- a/src/main/java/com/volmit/host/ChunkInvocation.java +++ b/src/main/java/com/volmit/host/ChunkInvocation.java @@ -11,7 +11,7 @@ import com.volmit.stage.Stage; import com.volmit.world.TerrainSampler; import java.util.Objects; -/** The context every stage of one chunk invocation receives. */ +/** The context every stage of one chunk invocation receives. The mantle is read-only. */ final class ChunkInvocation implements ChunkStageContext { private final StageInvocation stages; private final GenerationContext inputs; @@ -57,7 +57,7 @@ final class ChunkInvocation implements ChunkStageContext { @Override public Mantle mantle() { - return inputs.mantle(); + return new ReadOnlyMantle(inputs.mantle()); } @Override diff --git a/src/main/java/com/volmit/host/ChunkRunner.java b/src/main/java/com/volmit/host/ChunkRunner.java index 5905af7a9..60f4d775f 100644 --- a/src/main/java/com/volmit/host/ChunkRunner.java +++ b/src/main/java/com/volmit/host/ChunkRunner.java @@ -6,7 +6,7 @@ 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. + * from publishing the chunk. Stages see the mantle read-only. */ public final class ChunkRunner { private final ResolvedGraph graph; @@ -18,10 +18,16 @@ public final class ChunkRunner { } } - /** Runs one chunk. The host derives {@code invocationSeed} from the world seed and the chunk - * position; each stage draws from its own stream of that seed ({@link StageStreams}). + /** Runs one chunk. A conditional stage is active when any of the chunk's 16 by 16 columns has an + * entry of its settings in {@code inputs.settings()}, and receives every distinct entry of those + * columns. The host derives {@code invocationSeed} from the world seed and the chunk position; each + * stage draws from its own stream of that seed ({@link StageStreams}). */ - public void generate(GenerationContext inputs, long invocationSeed, ConfiguredSettings settings) { + public void generate(GenerationContext inputs, long invocationSeed) { + if (graph.size() == 0) { + return; + } + var settings = ChunkSettings.collect(graph, inputs::settings, inputs.originX(), inputs.originZ()); var chunk = new ChunkInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); for (int position = 0; position < graph.size(); position++) { chunk.stages().runInvocationStage(position, chunk); diff --git a/src/main/java/com/volmit/host/ChunkSettings.java b/src/main/java/com/volmit/host/ChunkSettings.java new file mode 100644 index 000000000..a510d3b46 --- /dev/null +++ b/src/main/java/com/volmit/host/ChunkSettings.java @@ -0,0 +1,51 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.Collection; +import java.util.LinkedHashMap; +import java.util.function.Supplier; + +/** The settings one chunk's stages see: for every settings type the graph conditions on, each distinct + * entry of the chunk's 16 by 16 columns. A stage is therefore active when any column of the chunk + * configures its settings, also where a biome border crosses the chunk. Entries are distinct by level + * and source and keep the order their first column was read in, columns by X and then Z. + */ +final class ChunkSettings { + /** The chunk's width along X and Z, in blocks: the footprint of chunk and mantle stages. */ + static final int CHUNK_WIDTH = 16; + + private ChunkSettings() {} + + /** {@code settings} is asked only when the graph conditions a stage on settings. */ + static ConfiguredSettings collect(ResolvedGraph graph, Supplier settings, int originX, int originZ) { + if (graph.settingsTypes().isEmpty()) { + return ConfiguredSettings.none(); + } + var view = settings.get(); + var entries = new ArrayList>(); + for (var type : graph.settingsTypes()) { + entries.addAll(distinctEntries(type.asSubclass(IrisFeature.class), view, originX, originZ)); + } + return ConfiguredSettings.of(entries); + } + + private static Collection> distinctEntries( + Class type, FeatureSettings view, int originX, int originZ) { + var distinct = new LinkedHashMap>(); + for (int x = 0; x < CHUNK_WIDTH; x++) { + for (int z = 0; z < CHUNK_WIDTH; z++) { + for (var entry : view.at(type, originX + x, originZ + z)) { + distinct.putIfAbsent(new Declaration(entry.level(), entry.source()), entry); + } + } + } + return distinct.values(); + } + + private record Declaration(FeatureAttachment.Target level, ResourceId source) {} +} diff --git a/src/main/java/com/volmit/host/ConfiguredSettings.java b/src/main/java/com/volmit/host/ConfiguredSettings.java index 5840635a9..c49714735 100644 --- a/src/main/java/com/volmit/host/ConfiguredSettings.java +++ b/src/main/java/com/volmit/host/ConfiguredSettings.java @@ -1,41 +1,66 @@ package com.volmit.host; +import com.volmit.FeatureAttachment; import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import java.util.ArrayList; +import java.util.Comparator; import java.util.HashMap; +import java.util.List; 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. +/** The settings entries configured for one invocation, per settings type, in level order. A stage + * conditioned on a type is active when the type has at least one entry, and its body receives them + * all. For a placement these are the placement's own declarations; for a chunk the runners collect + * every distinct entry of the chunk's columns themselves. 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 static final Comparator> LEVEL_ORDER = Comparator.comparing(Entry::level); - private final Map, IrisFeature> values; + private final Map, List>> entries; - private ConfiguredSettings(Map, IrisFeature> values) { - this.values = Map.copyOf(values); + private ConfiguredSettings(Map, List>> entries) { + this.entries = Map.copyOf(entries); } 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()); - } + /** These entries, grouped by settings type, each group in level order and otherwise as given. */ + public static ConfiguredSettings of(List> entries) { + var grouped = new HashMap, List>>(); + for (var entry : entries) { + Objects.requireNonNull(entry, "entry"); + grouped.computeIfAbsent(entry.value().getClass(), ignored -> new ArrayList<>()).add(entry); } - return new ConfiguredSettings(values); + grouped.replaceAll((type, group) -> group.stream().sorted(LEVEL_ORDER).toList()); + return grouped.isEmpty() ? NONE : new ConfiguredSettings(grouped); } - public Optional find(Class type) { - return Optional.ofNullable(type.cast(values.get(type))); + /** One placement's own settings, at most one value per type, declared by {@code source}. */ + public static ConfiguredSettings placement(ResourceId source, IrisFeature... settings) { + Objects.requireNonNull(source, "source"); + var entries = new ArrayList>(); + var types = new HashMap, IrisFeature>(); + for (var value : settings) { + Objects.requireNonNull(value, "settings"); + if (types.putIfAbsent(value.getClass(), value) != null) { + throw new IllegalArgumentException("Settings configured twice: " + value.getClass().getName()); + } + entries.add(new Entry<>(FeatureAttachment.Target.OBJECT_PLACEMENT, source, value)); + } + return of(entries); + } + + /** The entries of {@code type}, in level order; empty when nothing configures it. */ + @SuppressWarnings("unchecked") // Entries are grouped by the class of their value. + public List> find(Class type) { + var found = entries.get(type); + return found == null ? List.of() : (List>) (List) found; } } diff --git a/src/main/java/com/volmit/host/DefaultValues.java b/src/main/java/com/volmit/host/DefaultValues.java index 8944bd522..4671a9bd8 100644 --- a/src/main/java/com/volmit/host/DefaultValues.java +++ b/src/main/java/com/volmit/host/DefaultValues.java @@ -5,6 +5,7 @@ import com.volmit.host.schema.ValueKind; import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.HostKind; import com.volmit.host.schema.ValueKind.IntegerKind; import com.volmit.host.schema.ValueKind.ListKind; import com.volmit.host.schema.ValueKind.MapKind; @@ -45,6 +46,7 @@ final class DefaultValues { case ListKind list -> list(elements(value), list); case MapKind map -> map((Map) value, map.value()); case ObjectKind object -> object(value, types.get(object.type())); + case HostKind _ -> Optional.empty(); }; } diff --git a/src/main/java/com/volmit/host/HostTypes.java b/src/main/java/com/volmit/host/HostTypes.java new file mode 100644 index 000000000..98f7ec044 --- /dev/null +++ b/src/main/java/com/volmit/host/HostTypes.java @@ -0,0 +1,32 @@ +package com.volmit.host; + +import com.volmit.PackageName; +import java.util.Collection; +import java.util.List; + +/** Classes the host describes in studio itself, such as Iris's palettes and noise styles, which built-in + * settings may hold. Given as packages, each with its subpackages. Pack modules cannot use them. + */ +final class HostTypes { + static final HostTypes NONE = new HostTypes(List.of()); + + private final List packages; + + private HostTypes(List packages) { + this.packages = packages; + } + + static HostTypes of(Collection packages) { + return new HostTypes(packages.stream().map(HostTypes::parse).toList()); + } + + boolean contains(Class type) { + var name = type.getName(); + return packages.stream().anyMatch(packageName -> packageName.contains(name)); + } + + private static PackageName parse(String name) { + return PackageName.tryParse(name).orElseThrow(() -> new IllegalArgumentException( + "Host type package '" + name + "' is not a package name, such as art.arcane.iris.engine.object")); + } +} diff --git a/src/main/java/com/volmit/host/LoadedModules.java b/src/main/java/com/volmit/host/LoadedModules.java index d04f49e7b..aa54777f7 100644 --- a/src/main/java/com/volmit/host/LoadedModules.java +++ b/src/main/java/com/volmit/host/LoadedModules.java @@ -13,12 +13,14 @@ import java.util.Set; * settings types stages are conditioned on), its description for studio and one resolved graph per * pipeline. */ -public record LoadedModules(FeatureCatalog catalog, PackSchema schema, ResolvedGraph placement, ResolvedGraph chunk) { +public record LoadedModules( + FeatureCatalog catalog, PackSchema schema, ResolvedGraph placement, ResolvedGraph chunk, ResolvedGraph mantle) { public LoadedModules { Objects.requireNonNull(catalog, "catalog"); Objects.requireNonNull(schema, "schema"); Objects.requireNonNull(placement, "placement"); Objects.requireNonNull(chunk, "chunk"); + Objects.requireNonNull(mantle, "mantle"); } /** Pass the built-in modules together with {@link PackModules#modules()} of the pack. @@ -26,11 +28,14 @@ public record LoadedModules(FeatureCatalog catalog, PackSchema schema, ResolvedG * @param reservedHostFields JSON fields the host itself uses, per attachment target * @param reservedNamespaces namespaces only built-in modules may use, such as {@code iris}; a * pack module whose id uses one fails the load + * @param hostTypePackages packages whose classes the host describes itself, each with its + * subpackages; only built-in modules' settings may use them (see {@link ModuleHost#describingHostTypesIn}) */ public static LoadedModules load( List modules, Map> reservedHostFields, - Collection reservedNamespaces) { + Collection reservedNamespaces, + Collection hostTypePackages) { var reserved = ReservedNamespaces.of(reservedNamespaces); modules.forEach(reserved::requireAllowed); var registry = new ModuleRegistry(reservedHostFields); @@ -40,12 +45,13 @@ public record LoadedModules(FeatureCatalog catalog, PackSchema schema, ResolvedG } stages.settingsTypes(registry::registeredByOwner).forEach(registry::registerStageSettings); var catalog = registry.freeze(); - var schema = PackSchemaBuilder.describe(catalog, modules); + var schema = PackSchemaBuilder.describe(catalog, modules, HostTypes.of(hostTypePackages)); var placement = stages.resolve(Pipeline.PLACEMENT); var chunk = stages.resolve(Pipeline.CHUNK); + var mantle = stages.resolve(Pipeline.MANTLE); requireRegisteredMantleLayers(catalog, placement); - requireRegisteredMantleLayers(catalog, chunk); - return new LoadedModules(catalog, schema, placement, chunk); + requireRegisteredMantleLayers(catalog, mantle); + return new LoadedModules(catalog, schema, placement, chunk, mantle); } /** A stage's reach names the layers it writes; a layer nobody registered has no codec or lifetime. */ diff --git a/src/main/java/com/volmit/host/LoadedPack.java b/src/main/java/com/volmit/host/LoadedPack.java index 83c005029..c8434ccb8 100644 --- a/src/main/java/com/volmit/host/LoadedPack.java +++ b/src/main/java/com/volmit/host/LoadedPack.java @@ -29,7 +29,7 @@ public final class LoadedPack implements AutoCloseable { this.loaded = loaded; } - /** Loads the pack's module jars, installs them with the host's built-in modules and resolves both + /** Loads the pack's module jars, installs them with the host's built-in modules and resolves the * pipelines. Fails with the first load error, naming the jar or module at fault. */ public static LoadedPack load(Path packRoot, ModuleHost host) { @@ -37,7 +37,7 @@ public final class LoadedPack implements AutoCloseable { var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.jarCopyRoot(), host.logger()); try { var loaded = LoadedModules.load(host.withPackModules(packModules.modules()), - host.reservedHostFields(), host.reservedNamespaces()); + host.reservedHostFields(), host.reservedNamespaces(), host.hostTypePackages()); return new LoadedPack(packModules, loaded); } catch (RuntimeException | Error failure) { closeAfterFailure(packModules, failure); @@ -74,6 +74,10 @@ public final class LoadedPack implements AutoCloseable { return loaded.chunk(); } + public ResolvedGraph mantle() { + return loaded.mantle(); + } + @Override public void close() { packModules.close(); diff --git a/src/main/java/com/volmit/host/MantleInvocation.java b/src/main/java/com/volmit/host/MantleInvocation.java new file mode 100644 index 000000000..4362cc683 --- /dev/null +++ b/src/main/java/com/volmit/host/MantleInvocation.java @@ -0,0 +1,71 @@ +package com.volmit.host; + +import com.volmit.config.FeatureSettings; +import com.volmit.generation.MantleGenerationContext; +import com.volmit.mantle.Mantle; +import com.volmit.random.WorldRandom; +import com.volmit.resource.PackResources; +import com.volmit.stage.MantleStageContext; +import com.volmit.stage.Stage; +import com.volmit.world.TerrainSampler; +import java.util.Objects; + +/** The context every stage of one mantle invocation receives. */ +final class MantleInvocation implements MantleStageContext { + private final StageInvocation stages; + private final MantleGenerationContext inputs; + + MantleInvocation(StageInvocation stages, MantleGenerationContext 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 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 long worldSeed() { + return inputs.worldSeed(); + } + + @Override + public PackResources resources() { + return inputs.resources(); + } + + @Override + public WorldRandom random() { + return stages.random(); + } +} diff --git a/src/main/java/com/volmit/host/MantleRunner.java b/src/main/java/com/volmit/host/MantleRunner.java new file mode 100644 index 000000000..269c3aa05 --- /dev/null +++ b/src/main/java/com/volmit/host/MantleRunner.java @@ -0,0 +1,36 @@ +package com.volmit.host; + +import com.volmit.generation.MantleGenerationContext; +import com.volmit.stage.Pipeline; +import java.util.Objects; + +/** Reference executor of a resolved mantle graph: active stages run once per chunk, in resolved order. + * The host runs it for every chunk within the pipeline's reach of a chunk before that chunk generates, + * each chunk once, and gives it the mantle around the chunk as far as that reach. It does not roll back + * mantle writes; a failed invocation must stop the host from generating the chunks it reaches. + */ +public final class MantleRunner { + private final ResolvedGraph graph; + + public MantleRunner(ResolvedGraph graph) { + this.graph = Objects.requireNonNull(graph, "graph"); + if (graph.pipeline() != Pipeline.MANTLE) { + throw new IllegalArgumentException("Expected a mantle graph, got " + graph.pipeline()); + } + } + + /** Runs the mantle stages of one chunk. A conditional stage is active when any of the chunk's + * 16 by 16 columns has an entry of its settings, and receives every distinct entry of those columns. + * The host derives {@code invocationSeed} from the world seed and the chunk position. + */ + public void generate(MantleGenerationContext inputs, long invocationSeed) { + if (graph.size() == 0) { + return; + } + var settings = ChunkSettings.collect(graph, inputs::settings, inputs.originX(), inputs.originZ()); + var mantle = new MantleInvocation(new StageInvocation(graph, invocationSeed, settings), inputs); + for (int position = 0; position < graph.size(); position++) { + mantle.stages().runInvocationStage(position, mantle); + } + } +} diff --git a/src/main/java/com/volmit/host/ModuleHost.java b/src/main/java/com/volmit/host/ModuleHost.java index 439eb0db7..1aa1dfe62 100644 --- a/src/main/java/com/volmit/host/ModuleHost.java +++ b/src/main/java/com/volmit/host/ModuleHost.java @@ -14,7 +14,8 @@ import java.util.TreeSet; /** The host's side of every pack load, the same for all packs: its built-in modules, the host * packages pack modules may use besides the Iris API, the JSON fields the host itself uses (which no - * built-in alias may take), and the namespaces only built-in modules may use. Build it once and pass it to every + * built-in alias may take), the namespaces only built-in modules may use and the packages of the + * classes the host describes itself. Build it once and pass it to every * {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}. * *

{@code
@@ -25,8 +26,8 @@ import java.util.TreeSet;
  * }
* * Every method adds to what earlier calls configured, so a host can build the configuration in steps. - * Built-in modules' {@code info()} is read here, once. Exposed package names, reserved namespaces and - * reserved field names are checked here, so a mistake fails when the host starts rather than at the + * Built-in modules' {@code info()} is read here, once. Exposed package names, reserved namespaces, + * host type packages and reserved field names are checked here, so a mistake fails when the host starts rather than at the * first pack load. */ public record ModuleHost( @@ -34,6 +35,7 @@ public record ModuleHost( Set exposedHostPackages, Map> reservedHostFields, Set reservedNamespaces, + Set hostTypePackages, Path jarCopyRoot, System.Logger logger) { private static final String TEMPORARY_DIRECTORY_PROPERTY = "java.io.tmpdir"; @@ -43,10 +45,12 @@ public record ModuleHost( exposedHostPackages = Set.copyOf(exposedHostPackages); reservedHostFields = copyOf(reservedHostFields); reservedNamespaces = Set.copyOf(reservedNamespaces); + hostTypePackages = Set.copyOf(hostTypePackages); Objects.requireNonNull(jarCopyRoot, "jarCopyRoot"); Objects.requireNonNull(logger, "logger"); ExposedPackages.apiAnd(exposedHostPackages); ReservedNamespaces.of(reservedNamespaces); + HostTypes.of(hostTypePackages); requireFieldNames(reservedHostFields); } @@ -55,7 +59,7 @@ public record ModuleHost( */ public static ModuleHost of(List builtInModules) { var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList(); - return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), systemTemporaryDirectory(), + return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), systemTemporaryDirectory(), System.getLogger(PackModules.class.getName())); } @@ -64,13 +68,13 @@ public record ModuleHost( */ public ModuleHost exposing(String... packages) { return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields, reservedNamespaces, - jarCopyRoot, logger); + hostTypePackages, jarCopyRoot, logger); } /** This configuration with {@code namespaces} reserved for built-in modules. */ public ModuleHost reservingNamespaces(String... namespaces) { return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, union(reservedNamespaces, namespaces), - jarCopyRoot, logger); + hostTypePackages, jarCopyRoot, logger); } /** This configuration with {@code fields} also reserved as JSON fields the host itself uses, @@ -78,21 +82,33 @@ public record ModuleHost( */ public ModuleHost reservingFields(Map> fields) { return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields), reservedNamespaces, - jarCopyRoot, logger); + hostTypePackages, jarCopyRoot, logger); + } + + /** This configuration with the classes in {@code packages}, each with its subpackages, described by + * the host itself: built-in settings may hold them, such as Iris's palettes, and the pack's + * {@link com.volmit.host.schema.PackSchema} names them as {@link com.volmit.host.schema.ValueKind.HostKind} + * instead of describing their fields. Pack modules' settings cannot use them. + */ + public ModuleHost describingHostTypesIn(String... packages) { + return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, + union(hostTypePackages, packages), jarCopyRoot, logger); } /** This configuration copying module jars into new directories below {@code directory}, such as a * cache directory of the host, which is created when missing. The last call wins. */ public ModuleHost copyingJarsTo(Path directory) { - return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, directory, logger); + return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages, + directory, logger); } /** This configuration logging each pack load's module summary and missing-classes warning to * {@code logger}, such as an adapter to the host's own log. The last call wins. */ public ModuleHost loggingTo(System.Logger logger) { - return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, jarCopyRoot, logger); + return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, reservedNamespaces, hostTypePackages, + jarCopyRoot, logger); } /** The built-in modules followed by a pack's modules, in the order {@link LoadedModules} installs them. */ diff --git a/src/main/java/com/volmit/host/PackSchemaBuilder.java b/src/main/java/com/volmit/host/PackSchemaBuilder.java index 484fefb38..4e78b01f4 100644 --- a/src/main/java/com/volmit/host/PackSchemaBuilder.java +++ b/src/main/java/com/volmit/host/PackSchemaBuilder.java @@ -26,14 +26,15 @@ final class PackSchemaBuilder { private static final char FOLDER_SEPARATOR = '/'; private final List modules; - private final TypeDrafts drafts = new TypeDrafts(); + private final TypeDrafts drafts; - private PackSchemaBuilder(List modules) { + private PackSchemaBuilder(List modules, HostTypes hostTypes) { this.modules = modules; + this.drafts = new TypeDrafts(hostTypes); } - static PackSchema describe(FeatureCatalog catalog, List modules) { - return new PackSchemaBuilder(modules).describe(catalog); + static PackSchema describe(FeatureCatalog catalog, List modules, HostTypes hostTypes) { + return new PackSchemaBuilder(modules, hostTypes).describe(catalog); } private PackSchema describe(FeatureCatalog catalog) { diff --git a/src/main/java/com/volmit/host/ReadOnlyMantle.java b/src/main/java/com/volmit/host/ReadOnlyMantle.java new file mode 100644 index 000000000..c7a810f75 --- /dev/null +++ b/src/main/java/com/volmit/host/ReadOnlyMantle.java @@ -0,0 +1,64 @@ +package com.volmit.host; + +import com.volmit.mantle.BlockBox; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleEdit; +import com.volmit.mantle.MantleKey; +import com.volmit.mantle.MantleLayer; +import com.volmit.mantle.MantleVisitor; + +/** The mantle as chunk stages see it: reads pass through, every write throws. The mantle pipeline has + * finished around the chunk by then, and its neighbors may already be generated. + */ +final class ReadOnlyMantle implements Mantle { + private static final String READ_ONLY = "Chunk stages read the mantle but do not write it;" + + " write it from a mantle stage (Stage.mantle), which runs before the chunks it reaches"; + + private final Mantle mantle; + + ReadOnlyMantle(Mantle mantle) { + this.mantle = mantle; + } + + @Override + public BlockBox bounds() { + return mantle.bounds(); + } + + @Override + public MantleLayer layer(MantleKey key) { + return new ReadOnlyLayer<>(mantle.layer(key)); + } + + @Override + public MantleEdit edit() { + throw new UnsupportedOperationException(READ_ONLY); + } + + private record ReadOnlyLayer(MantleLayer layer) implements MantleLayer { + @Override + public T get(int x, int y, int z) { + return layer.get(x, y, z); + } + + @Override + public void set(int x, int y, int z, T value) { + throw new UnsupportedOperationException(READ_ONLY); + } + + @Override + public void remove(int x, int y, int z) { + throw new UnsupportedOperationException(READ_ONLY); + } + + @Override + public void visit(BlockBox area, MantleVisitor visitor) { + layer.visit(area, visitor); + } + + @Override + public void clear(BlockBox area) { + throw new UnsupportedOperationException(READ_ONLY); + } + } +} diff --git a/src/main/java/com/volmit/host/StageDeclaration.java b/src/main/java/com/volmit/host/StageDeclaration.java index d04523c8a..9cf680457 100644 --- a/src/main/java/com/volmit/host/StageDeclaration.java +++ b/src/main/java/com/volmit/host/StageDeclaration.java @@ -3,6 +3,7 @@ package com.volmit.host; import com.volmit.IrisFeature; import com.volmit.mantle.MantleKey; import com.volmit.resource.ResourceId; +import com.volmit.stage.Pipeline; import com.volmit.stage.Stage; import com.volmit.stage.StageRef; import java.util.ArrayList; @@ -54,6 +55,7 @@ final class StageDeclaration { void reach(int blocks) { checkOpen(); + if (blocks > 0) requireOutsideChunkPipeline("a reach of " + blocks + " blocks"); if (reachBlocks != null) { throw new IllegalStateException("Stage " + this + " already declares a reach of " + reachBlocks + " blocks"); } @@ -65,6 +67,7 @@ final class StageDeclaration { void writesMantle(MantleKey... layers) { checkOpen(); + requireOutsideChunkPipeline("mantle writes"); for (var layer : layers) { Objects.requireNonNull(layer, "mantle layer"); if (mantleLayers.stream().anyMatch(declared -> declared.id().equals(layer.id()))) { @@ -147,6 +150,14 @@ final class StageDeclaration { return "Stage " + this + " " + declared + "; define it with " + alternativeMethod + "(...)"; } + /** Chunk stages write only their own chunk: the host may already have generated its neighbors. */ + private void requireOutsideChunkPipeline(String declared) { + if (stage.pipeline() != Pipeline.CHUNK) return; + throw new IllegalArgumentException("Stage " + this + " is a chunk stage and declares " + declared + + ", but chunk stages write only their own chunk and read the mantle; define work that writes the" + + " mantle or reaches beyond its chunk as a mantle stage (Stage.mantle), which runs before the chunks it reaches"); + } + private void checkOpen() { if (body != null) { throw new IllegalStateException("Stage " + this + " is already complete"); diff --git a/src/main/java/com/volmit/host/StageGraphBuilder.java b/src/main/java/com/volmit/host/StageGraphBuilder.java index fc163fe1a..004646bf8 100644 --- a/src/main/java/com/volmit/host/StageGraphBuilder.java +++ b/src/main/java/com/volmit/host/StageGraphBuilder.java @@ -6,6 +6,8 @@ import com.volmit.stage.BlockStage; import com.volmit.stage.BlockStageDefinition; import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStage; +import com.volmit.stage.MantleStageContext; import com.volmit.stage.Pipeline; import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStageContext; @@ -63,6 +65,11 @@ public final class StageGraphBuilder implements StageGraph { return new InvocationStageDraft<>(declare(stage)); } + @Override + public StageDefinition define(MantleStage stage) { + return new InvocationStageDraft<>(declare(stage)); + } + public ResolvedGraph resolve(Pipeline pipeline) { Objects.requireNonNull(pipeline, "pipeline"); return GraphResolver.resolve(pipeline, declarations.values()); diff --git a/src/main/java/com/volmit/host/StageInvocation.java b/src/main/java/com/volmit/host/StageInvocation.java index 862d79ad1..d6d3a8e31 100644 --- a/src/main/java/com/volmit/host/StageInvocation.java +++ b/src/main/java/com/volmit/host/StageInvocation.java @@ -10,7 +10,7 @@ import java.util.stream.IntStream; /** Pipeline-independent state of one invocation: activation, settings, stage outputs and stage * random streams, all indexed by resolved position. Activation is computed once up front in resolved - * order: a stage is active when its settings are configured (or it has no condition) and every + * order: a stage is active when its settings have an entry (or it has no condition) and every * stage it requires is active, so inactivity cascades to dependents. Cost is one pass over stages * and requirement edges plus one settings lookup per distinct settings type. A stage's stream is * created when it first draws and depends only on the invocation seed and the stage id. @@ -131,7 +131,8 @@ final class StageInvocation { 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); + var entries = settings.find((Class) types.get(slot)); + values[slot] = entries.isEmpty() ? null : entries; } return values; } diff --git a/src/main/java/com/volmit/host/StageReach.java b/src/main/java/com/volmit/host/StageReach.java index ef8815205..bf00521c4 100644 --- a/src/main/java/com/volmit/host/StageReach.java +++ b/src/main/java/com/volmit/host/StageReach.java @@ -8,8 +8,8 @@ import java.util.Objects; /** What one stage declares it writes outside its footprint. * * @param blocks how far, in blocks along X and Z, the stage writes blocks or mantle values beyond its - * footprint: the chunk's 16 by 16 columns for a chunk stage, the X/Z bounds of the placed object - * for a placement stage. 0 means only inside it. Height is not limited: the footprint is whole + * footprint: the chunk's 16 by 16 columns for a mantle stage, the X/Z bounds of the placed object + * for a placement stage. 0 means only inside it, and is all a chunk stage may declare. Height is not limited: the footprint is whole * columns. * @param mantleLayers the mantle layers the stage writes, each once, in declaration order */ diff --git a/src/main/java/com/volmit/host/TypeDrafts.java b/src/main/java/com/volmit/host/TypeDrafts.java index 06daefaac..f346ad576 100644 --- a/src/main/java/com/volmit/host/TypeDrafts.java +++ b/src/main/java/com/volmit/host/TypeDrafts.java @@ -17,7 +17,8 @@ import java.util.List; import java.util.Map; import java.util.Set; -/** Describes every class reachable from the settings of a pack, each once. A class is recorded before +/** Describes every class reachable from the settings of a pack, each once, except host types, which the + * host describes itself. A class is recorded before * its fields are described, so a class that contains itself, directly or through others, ends the * walk at its own name. Each class is instantiated once with its no-argument constructor, the way the * host creates settings before decoding JSON into them, and its fields' values there are the defaults. @@ -26,6 +27,11 @@ final class TypeDrafts { private final Map, TypeDraft> drafts = new LinkedHashMap<>(); private final Set> describing = new HashSet<>(); private final Map> names = new HashMap<>(); + private final HostTypes hostTypes; + + TypeDrafts(HostTypes hostTypes) { + this.hostTypes = hostTypes; + } /** One described class: its metadata and its options with their kinds and raw default values. */ record TypeDraft(Class type, SchemaSource source, OptionsMetadata metadata, List options) {} @@ -63,7 +69,8 @@ final class TypeDrafts { private TypeDraft draft(Class type, SchemaSource source) { var metadata = inspect(type, source); var instance = instantiate(type, source); - var kinds = new ValueKinds(nested -> object(nested, source)); + var kinds = new ValueKinds(nested -> object(nested, source), hostTypes, + source.module().source() == DiscoveredModule.Source.HOST); var options = metadata.options().stream() .map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source))) .toList(); diff --git a/src/main/java/com/volmit/host/ValueKinds.java b/src/main/java/com/volmit/host/ValueKinds.java index cff435385..7f512fa41 100644 --- a/src/main/java/com/volmit/host/ValueKinds.java +++ b/src/main/java/com/volmit/host/ValueKinds.java @@ -10,6 +10,7 @@ import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumConstant; import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.HostKind; import com.volmit.host.schema.ValueKind.IntegerKind; import com.volmit.host.schema.ValueKind.ListKind; import com.volmit.host.schema.ValueKind.MapKind; @@ -29,9 +30,10 @@ import java.util.Map; import java.util.Set; import java.util.function.Function; -/** Maps a settings field's declared type and {@code @Ref} to the JSON it takes. Classes that are none - * of the built-in kinds become object kinds through the given function. Throws - * {@link SettingsTypeProblem} for a type or reference that does not fit. +/** Maps a settings field's declared type and {@code @Ref} to the JSON it takes. Host types become host + * kinds where the settings may use them; other classes that are none of the built-in kinds become object + * kinds through the given function. Throws {@link SettingsTypeProblem} for a type or reference that does + * not fit. */ final class ValueKinds { static final String SUPPORTED_TYPES = "settings fields can be booleans, numbers, String, ResourceId, BlockState, enums, " @@ -44,9 +46,14 @@ final class ValueKinds { private static final Set PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT); private final Function, ObjectKind> objects; + private final HostTypes hostTypes; + private final boolean hostTypesAllowed; - ValueKinds(Function, ObjectKind> objects) { + /** {@code hostTypesAllowed} is whether the settings belong to a module that ships with the host. */ + ValueKinds(Function, ObjectKind> objects, HostTypes hostTypes, boolean hostTypesAllowed) { this.objects = objects; + this.hostTypes = hostTypes; + this.hostTypesAllowed = hostTypesAllowed; } ValueKind of(OptionsMetadata.Option option) { @@ -64,6 +71,7 @@ final class ValueKinds { } private ValueKind classKind(Class type, Reference reference) { + if (hostTypes.contains(type)) return hostKind(type, reference); if (type == String.class) return text(TextFormat.PLAIN, reference); if (type == ResourceId.class) return text(TextFormat.RESOURCE_ID, reference); if (type == BlockState.class) return blockState(reference); @@ -80,6 +88,7 @@ final class ValueKinds { private ValueKind genericKind(ParameterizedType generic, Reference reference) { var raw = (Class) generic.getRawType(); + if (hostTypes.contains(raw)) return hostKind(raw, reference); var arguments = generic.getActualTypeArguments(); if (raw == List.class || raw == Set.class) return new ListKind(kind(arguments[0], reference), raw == Set.class); if (raw == Map.class) return mapKind(generic, arguments, reference); @@ -94,6 +103,13 @@ final class ValueKinds { return new MapKind(kind(arguments[1], null)); } + private HostKind hostKind(Class type, Reference reference) { + requireNoReference(type, reference); + if (hostTypesAllowed) return new HostKind(type.getName()); + throw new SettingsTypeProblem("uses " + type.getName() + ", a class the host describes itself, which only settings of" + + " modules that ship with the host may use; " + SUPPORTED_TYPES); + } + private static ValueKind text(TextFormat format, Reference reference) { if (reference == null) return new TextKind(format); if (format == TextFormat.RESOURCE_ID && PACK_REFERENCES.contains(reference)) throw packReferenceOnResourceId(reference); diff --git a/src/main/java/com/volmit/host/schema/FeatureSchema.java b/src/main/java/com/volmit/host/schema/FeatureSchema.java index a6795be94..a2e32ef45 100644 --- a/src/main/java/com/volmit/host/schema/FeatureSchema.java +++ b/src/main/java/com/volmit/host/schema/FeatureSchema.java @@ -39,4 +39,12 @@ public record FeatureSchema( Objects.requireNonNull(settings, "settings"); targets = Collections.unmodifiableSet(EnumSet.copyOf(targets)); } + + /** The settings' only option, when they have exactly one. Packs may then write that option's value + * directly instead of an object holding it, such as {@code "snow": 0.5} for {@code "snow": {"amount": 0.5}}, + * and the host decodes a value that is not a JSON object into it. + */ + public Optional shorthand() { + return settings.options().size() == 1 ? Optional.of(settings.options().getFirst()) : Optional.empty(); + } } diff --git a/src/main/java/com/volmit/host/schema/ValueKind.java b/src/main/java/com/volmit/host/schema/ValueKind.java index a13a805fb..53e06beaf 100644 --- a/src/main/java/com/volmit/host/schema/ValueKind.java +++ b/src/main/java/com/volmit/host/schema/ValueKind.java @@ -63,6 +63,16 @@ public sealed interface ValueKind { } } + /** A value of the class named {@code type}, which the host describes itself, such as one of Iris's + * palettes or noise styles. Only built-in modules' settings use these (see + * {@link com.volmit.host.ModuleHost#describingHostTypesIn}); the host renders its own description. + */ + record HostKind(String type) implements ValueKind { + public HostKind { + Objects.requireNonNull(type, "type"); + } + } + /** An enum constant and its {@code @Desc}, or an empty description. */ record EnumConstant(String name, String description) { public EnumConstant { diff --git a/src/main/java/com/volmit/stage/BlockStageDefinition.java b/src/main/java/com/volmit/stage/BlockStageDefinition.java index 982c2f43b..1752b958b 100644 --- a/src/main/java/com/volmit/stage/BlockStageDefinition.java +++ b/src/main/java/com/volmit/stage/BlockStageDefinition.java @@ -15,9 +15,8 @@ public interface BlockStageDefinition { BlockStageDefinition softBefore(StageRef... stages); - /** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its - * footprint: the chunk for a chunk stage, the placed object's X/Z bounds for a placement stage. The - * host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0. + /** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond the + * placed object's X/Z bounds. The host prepares that much around every placement. Leaving it out means 0. */ BlockStageDefinition reach(int blocks); diff --git a/src/main/java/com/volmit/stage/ChunkStage.java b/src/main/java/com/volmit/stage/ChunkStage.java index e1d67c662..5eb81d0f2 100644 --- a/src/main/java/com/volmit/stage/ChunkStage.java +++ b/src/main/java/com/volmit/stage/ChunkStage.java @@ -1,6 +1,8 @@ package com.volmit.stage; -/** Runs once per chunk generation invocation. */ +/** Runs once per chunk generation invocation and writes only its own chunk. It may read the mantle but + * not write it, and it declares no reach: such work belongs in a {@link MantleStage}. + */ public final class ChunkStage extends Stage { ChunkStage(String id, Class outputType) { super(id, outputType); diff --git a/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java index 77ff70390..d69fa756f 100644 --- a/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java +++ b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java @@ -1,11 +1,12 @@ package com.volmit.stage; +import com.volmit.IrisFeature; import com.volmit.mantle.MantleKey; import java.util.function.Supplier; -/** A block stage active only where its settings are configured; bodies receive them. */ -public interface ConditionalBlockStageDefinition { +/** A block stage active only where its settings are configured; bodies receive every configured entry. */ +public interface ConditionalBlockStageDefinition { ConditionalBlockStageDefinition requires(Stage... stages); ConditionalBlockStageDefinition softAfter(StageRef... stages); diff --git a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java index 20c22dcf3..f38a5533d 100644 --- a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java +++ b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java @@ -1,9 +1,10 @@ package com.volmit.stage; +import com.volmit.IrisFeature; import com.volmit.mantle.MantleKey; -/** An invocation stage active only where its settings are configured; bodies receive them. */ -public interface ConditionalStageDefinition { +/** An invocation stage active only where its settings are configured; bodies receive every configured entry. */ +public interface ConditionalStageDefinition { ConditionalStageDefinition requires(Stage... stages); ConditionalStageDefinition softAfter(StageRef... stages); diff --git a/src/main/java/com/volmit/stage/MantleStage.java b/src/main/java/com/volmit/stage/MantleStage.java new file mode 100644 index 000000000..31c897864 --- /dev/null +++ b/src/main/java/com/volmit/stage/MantleStage.java @@ -0,0 +1,18 @@ +package com.volmit.stage; + +/** Runs once per chunk in the mantle pipeline, before the chunks it reaches generate. */ +public final class MantleStage extends Stage { + MantleStage(String id, Class outputType) { + super(id, outputType); + } + + @Override + public Pipeline pipeline() { + return Pipeline.MANTLE; + } + + @Override + public StageKind kind() { + return StageKind.INVOCATION; + } +} diff --git a/src/main/java/com/volmit/stage/MantleStageContext.java b/src/main/java/com/volmit/stage/MantleStageContext.java new file mode 100644 index 000000000..8eb2bca60 --- /dev/null +++ b/src/main/java/com/volmit/stage/MantleStageContext.java @@ -0,0 +1,6 @@ +package com.volmit.stage; + +import com.volmit.generation.MantleGenerationContext; + +/** One mantle invocation for one chunk: the mantle around it, without a block hunk. */ +public interface MantleStageContext extends MantleGenerationContext, StageContext {} diff --git a/src/main/java/com/volmit/stage/Pipeline.java b/src/main/java/com/volmit/stage/Pipeline.java index 568778fef..395a390f8 100644 --- a/src/main/java/com/volmit/stage/Pipeline.java +++ b/src/main/java/com/volmit/stage/Pipeline.java @@ -4,6 +4,13 @@ package com.volmit.stage; 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 + /** Runs once per chunk generation invocation, against host-owned local hunks. Its stages write only + * their own chunk and read the mantle. + */ + CHUNK, + /** Runs once per chunk before any chunk near it generates, against the mantle only: work that writes + * the mantle or reaches beyond its chunk. The host runs it around a chunk as far as the pipeline's + * reach, so a chunk's mantle is complete when the chunk pipeline reads it. + */ + MANTLE } diff --git a/src/main/java/com/volmit/stage/SettingsAction.java b/src/main/java/com/volmit/stage/SettingsAction.java index e2d9de500..c5b05f93c 100644 --- a/src/main/java/com/volmit/stage/SettingsAction.java +++ b/src/main/java/com/volmit/stage/SettingsAction.java @@ -1,6 +1,13 @@ package com.volmit.stage; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import java.util.List; + +/** Body of a conditional stage without output. {@code settings} holds every entry configured for the + * invocation, in level order, and is never empty. + */ @FunctionalInterface -public interface SettingsAction { - void run(C context, S settings); +public interface SettingsAction { + void run(C context, List> settings); } diff --git a/src/main/java/com/volmit/stage/SettingsBlockCollector.java b/src/main/java/com/volmit/stage/SettingsBlockCollector.java index 07ee80cb5..7e3dbd8dd 100644 --- a/src/main/java/com/volmit/stage/SettingsBlockCollector.java +++ b/src/main/java/com/volmit/stage/SettingsBlockCollector.java @@ -1,6 +1,13 @@ package com.volmit.stage; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import java.util.List; + +/** Body of a conditional accumulating block stage. {@code settings} holds every entry configured for + * the placement, in level order, and is never empty. + */ @FunctionalInterface -public interface SettingsBlockCollector { - void collect(BlockStageContext context, S settings, O accumulator); +public interface SettingsBlockCollector { + void collect(BlockStageContext context, List> settings, O accumulator); } diff --git a/src/main/java/com/volmit/stage/SettingsFunction.java b/src/main/java/com/volmit/stage/SettingsFunction.java index ca618a422..bea146045 100644 --- a/src/main/java/com/volmit/stage/SettingsFunction.java +++ b/src/main/java/com/volmit/stage/SettingsFunction.java @@ -1,6 +1,13 @@ package com.volmit.stage; +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings.Entry; +import java.util.List; + +/** Body of a conditional stage with output. {@code settings} holds every entry configured for the + * invocation, in level order, and is never empty. + */ @FunctionalInterface -public interface SettingsFunction { - O run(C context, S settings); +public interface SettingsFunction { + O run(C context, List> settings); } diff --git a/src/main/java/com/volmit/stage/Stage.java b/src/main/java/com/volmit/stage/Stage.java index ca82c894b..559a5b4ae 100644 --- a/src/main/java/com/volmit/stage/Stage.java +++ b/src/main/java/com/volmit/stage/Stage.java @@ -9,7 +9,7 @@ import java.util.Objects; * 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 { +public abstract sealed class Stage permits PlacementStage, BlockStage, ChunkStage, MantleStage { private final ResourceId id; private final Class outputType; @@ -46,6 +46,14 @@ public abstract sealed class Stage permits PlacementStage, BlockStage, ChunkS return new ChunkStage<>(id, outputType); } + public static MantleStage mantle(String id) { + return new MantleStage<>(id, Void.class); + } + + public static MantleStage mantle(String id, Class outputType) { + return new MantleStage<>(id, outputType); + } + public final ResourceId id() { return id; } diff --git a/src/main/java/com/volmit/stage/StageDefinition.java b/src/main/java/com/volmit/stage/StageDefinition.java index 0842a8162..89c21855b 100644 --- a/src/main/java/com/volmit/stage/StageDefinition.java +++ b/src/main/java/com/volmit/stage/StageDefinition.java @@ -17,17 +17,22 @@ public interface StageDefinition { StageDefinition softBefore(StageRef... stages); /** Declares how far, in blocks along X and Z, this stage writes blocks or mantle values beyond its - * footprint: the chunk for a chunk stage, the placed object's X/Z bounds for a placement stage. The + * footprint: the chunk for a mantle stage, the placed object's X/Z bounds for a placement stage. The * host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0. + * Chunk stages write only their own chunk, so a reach above 0 on one fails the install. */ StageDefinition reach(int blocks); - /** Declares the mantle layers this stage writes; each must be registered by some module. */ + /** Declares the mantle layers this stage writes; each must be registered by some module. Chunk stages + * only read the mantle, so declaring layers on one fails the install. + */ StageDefinition writesMantle(MantleKey... layers); - /** Activates the stage only where the given feature settings are configured. At least one module - * naming the type must own its feature id: the id is that module's id or starts with it and '/'. - * Other modules may name it too, such as moss conditioning on {@code iris:snow}. + /** Activates the stage only where the given feature settings are configured: in a placement where the + * placement declares them, in a chunk or mantle invocation where any column of the chunk has an entry. + * The body receives every configured entry, in level order. At least one module naming the type must + * own its feature id: the id is that module's id or starts with it and '/'. Other modules may name it + * too, such as moss conditioning on {@code iris:snow}. */ ConditionalStageDefinition when(Class settingsType); diff --git a/src/main/java/com/volmit/stage/StageGraph.java b/src/main/java/com/volmit/stage/StageGraph.java index 7f3b909b2..84e809983 100644 --- a/src/main/java/com/volmit/stage/StageGraph.java +++ b/src/main/java/com/volmit/stage/StageGraph.java @@ -12,4 +12,6 @@ public interface StageGraph { BlockStageDefinition define(BlockStage stage); StageDefinition define(ChunkStage stage); + + StageDefinition define(MantleStage stage); } diff --git a/src/test/java/com/volmit/example/ChunkPipelineTest.java b/src/test/java/com/volmit/example/ChunkPipelineTest.java index 753c000cb..fd0ddc90c 100644 --- a/src/test/java/com/volmit/example/ChunkPipelineTest.java +++ b/src/test/java/com/volmit/example/ChunkPipelineTest.java @@ -1,28 +1,54 @@ package com.volmit.example; +import com.volmit.FeatureAttachment.Target; +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.config.FeatureSettings.Entry; import com.volmit.example.chunk.GrassModule; import com.volmit.example.chunk.GrassSettings; import com.volmit.example.chunk.TerrainModule; +import com.volmit.example.chunk.VeinModule; +import com.volmit.example.chunk.VeinSettings; import com.volmit.host.ArrayHunk; import com.volmit.host.ChunkRunner; -import com.volmit.host.ConfiguredSettings; import com.volmit.host.DiscoveredModule; +import com.volmit.host.LoadedModules; +import com.volmit.host.MantleRunner; import com.volmit.host.StageGraphBuilder; import com.volmit.hunk.Hunk; +import com.volmit.mantle.BlockBox; +import com.volmit.resource.ResourceId; import com.volmit.stage.Pipeline; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; +import com.volmit.support.ColumnSettings; +import com.volmit.support.MemoryMantle; import com.volmit.support.TestContexts; -import org.junit.jupiter.api.Test; +import java.util.ArrayList; import java.util.List; import java.util.Map; +import java.util.Set; +import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; -/** The chunk pipeline runs on the same graph machinery as placement. */ +/** The chunk pipeline runs on the same graph machinery as placement; the mantle pipeline feeds it. */ class ChunkPipelineTest { private static final int SIZE = 4; private static final int HEIGHT = 8; + private static final int CHUNK = 16; + private static final int MIN_Y = -64; + private static final int MAX_Y = 320; private static final BlockState AIR = new BlockState("minecraft:air"); private static final BlockState GRASS = new BlockState("minecraft:grass_block"); + private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld"); + private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains"); + private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp"); + + @Feature(id = "test:levels", name = "Levels", targets = {Target.DIMENSION, Target.BIOME}) + static final class Marker implements IrisFeature {} private static ChunkRunner runner() { var builder = new StageGraphBuilder(); @@ -35,15 +61,19 @@ class ChunkPipelineTest { return new ChunkRunner(graph); } - private static Hunk generate(ConfiguredSettings settings) { + private static Hunk generate(ColumnSettings settings) { var blocks = new ArrayHunk<>(BlockState.class, SIZE, HEIGHT, SIZE, AIR); - runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks)), TestContexts.SEED, settings); + runner().generate(TestContexts.generation(Map.of(BlockState.class, blocks), settings, null), TestContexts.SEED); return blocks; } + private static Entry grass(ResourceId biome) { + return new Entry<>(Target.BIOME, biome, new GrassSettings()); + } + @Test void decorationReadsTerrainOutputWhenConfigured() { - var blocks = generate(ConfiguredSettings.of(new GrassSettings())); + var blocks = generate(ColumnSettings.everywhere(grass(PLAINS))); for (int x = 0; x < SIZE; x++) { for (int z = 0; z < SIZE; z++) { @@ -57,9 +87,90 @@ class ChunkPipelineTest { @Test void decorationIsInactiveWithoutItsSettings() { - var blocks = generate(ConfiguredSettings.none()); + var blocks = generate(ColumnSettings.NONE); int height = TerrainModule.surfaceHeight(0, 0); assertEquals(TerrainModule.STONE, blocks.get(0, height - 1, 0)); } + + @Test + void aStageRunsWhenAnyColumnHasItsSettingsAndReadsThemPerColumn() { + var farCorner = new ColumnSettings((x, z) -> x == CHUNK - 1 && z == CHUNK - 1 ? List.of(grass(PLAINS)) : List.of()); + var blocks = generate(farCorner); + assertEquals(TerrainModule.STONE, blocks.get(0, TerrainModule.surfaceHeight(0, 0) - 1, 0), + "the stage ran because one column has grass, but this column has none"); + + var border = new ColumnSettings((x, z) -> x < 2 ? List.of(grass(PLAINS)) : List.of()); + blocks = generate(border); + assertEquals(GRASS, blocks.get(1, TerrainModule.surfaceHeight(1, 0) - 1, 0)); + assertEquals(TerrainModule.STONE, blocks.get(2, TerrainModule.surfaceHeight(2, 0) - 1, 0)); + } + + @Test + void levelsStackAndTheBodyGetsEveryDistinctEntryOfTheChunkInLevelOrder() { + var dimension = new Entry<>(Target.DIMENSION, DIMENSION, new Marker()); + var plains = new Entry<>(Target.BIOME, PLAINS, new Marker()); + var swamp = new Entry<>(Target.BIOME, SWAMP, new Marker()); + var received = new ArrayList>(); + var stage = Stage.chunk("test:levels/read"); + IrisModule module = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of("test:levels", "Levels", "1"); } + public void install(StageGraph graph) { + graph.define(stage).when(Marker.class).run((context, entries) -> { + received.add(entries.stream().map(Entry::source).toList()); + received.add(context.settings().at(Marker.class, 0, 0).stream().map(Entry::source).toList()); + }); + } + }; + var builder = new StageGraphBuilder(); + builder.install(DiscoveredModule.builtIn(module)); + var settings = new ColumnSettings((x, z) -> List.of(dimension, x < 8 ? swamp : plains)); + + new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate(TestContexts.generation(Map.of(), settings, null), TestContexts.SEED); + + assertEquals(List.of(List.of(DIMENSION, SWAMP, PLAINS), List.of(DIMENSION, SWAMP)), received, + "the body sees every level of every column, a column read that column's levels"); + } + + @Test + void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() { + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of()); + assertEquals(VeinModule.REACH, loaded.mantle().reach().blocks()); + assertEquals(Map.of(VeinModule.ORE.id(), VeinModule.REACH), loaded.mantle().reach().mantleLayers()); + var mantle = new MemoryMantle(); + var veins = ColumnSettings.everywhere(new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, -60))); + var reachArea = new BlockBox(-VeinModule.REACH, MIN_Y, -VeinModule.REACH, CHUNK + VeinModule.REACH, MAX_Y, CHUNK + VeinModule.REACH); + + new MantleRunner(loaded.mantle()).generate(TestContexts.mantle(0, 0, veins, mantle.within(reachArea)), TestContexts.SEED); + assertEquals(1, mantle.get(VeinModule.ORE, 18, -60, 7), "the vein runs on into the next chunk"); + + var blocks = new ArrayHunk<>(BlockState.class, CHUNK, HEIGHT, CHUNK, AIR); + var chunkArea = new BlockBox(0, MIN_Y, 0, CHUNK, MAX_Y, CHUNK); + new ChunkRunner(loaded.chunk()).generate( + TestContexts.generation(Map.of(BlockState.class, blocks), ColumnSettings.NONE, mantle.within(chunkArea)), TestContexts.SEED); + assertEquals(VeinModule.ORE_BLOCK, blocks.get(7, 4, 7)); + assertEquals(VeinModule.ORE_BLOCK, blocks.get(15, 4, 7)); + assertEquals(AIR, blocks.get(6, 4, 7)); + } + + @Test + void chunkStagesReadTheMantleButCannotWriteIt() { + var stage = Stage.chunk("test:writer/work"); + var mantle = new MemoryMantle(); + IrisModule module = new IrisModule() { + public ModuleInfo info() { return ModuleInfo.of("test:writer", "Writer", "1"); } + public void install(StageGraph graph) { + graph.define(stage).run(context -> context.mantle().layer(VeinModule.ORE).set(0, 0, 0, 1)); + } + }; + var builder = new StageGraphBuilder(); + builder.install(DiscoveredModule.builtIn(module)); + var inputs = TestContexts.generation(Map.of(), ColumnSettings.NONE, mantle.within(new BlockBox(0, MIN_Y, 0, CHUNK, MAX_Y, CHUNK))); + + var failure = assertThrows(UnsupportedOperationException.class, + () -> new ChunkRunner(builder.resolve(Pipeline.CHUNK)).generate(inputs, TestContexts.SEED)); + assertEquals("Chunk stages read the mantle but do not write it; write it from a mantle stage (Stage.mantle)," + + " which runs before the chunks it reaches", failure.getMessage()); + assertNull(mantle.get(VeinModule.ORE, 0, 0, 0)); + } } diff --git a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java index 813b85b3d..756c4cacf 100644 --- a/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java +++ b/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java @@ -38,6 +38,7 @@ import static org.junit.jupiter.api.Assertions.*; /** The ported slice of Iris's place() lifecycle, composed only from module-owned stages. */ class PlacementLifecyclePortTest { + private static final ResourceId PLACEMENT = ResourceId.parse("pack:object/tree"); private static final BlockState PLANKS = new BlockState("minecraft:oak_planks"); private static final int ANCHOR_GROUND = 10; private static final int SURROUNDING_GROUND = 7; @@ -149,7 +150,7 @@ class PlacementLifecyclePortTest { @Test void placesObjectThenStiltSnowAndMossFromTypedOutputs() { var edit = place(resolve(PlacementModules.all()), - ConfiguredSettings.of(new StiltSettings(), new SnowSettings(2), new MossSettings())); + ConfiguredSettings.placement(PLACEMENT, new StiltSettings(), new SnowSettings(2), new MossSettings())); var bottom = placed(0, 0, 0); var corner = placed(1, 0, 0); @@ -191,17 +192,17 @@ class PlacementLifecyclePortTest { modules.add(capModule); var graph = resolve(modules); - var withoutStilt = place(graph, ConfiguredSettings.of(new SnowSettings(), new MossSettings())); + var withoutStilt = place(graph, ConfiguredSettings.placement(PLACEMENT, new SnowSettings(), new MossSettings())); assertEquals(TestTerrain.AIR, withoutStilt.publishedAt(5, 20, 5)); assertEquals(MossModule.MOSS, withoutStilt.publishedAt(0, ANCHOR_GROUND - 1, 0)); - var withStilt = place(graph, ConfiguredSettings.of(new StiltSettings())); + var withStilt = place(graph, ConfiguredSettings.placement(PLACEMENT, new StiltSettings())); assertEquals(PLANKS, withStilt.publishedAt(5, 20, 5)); } @Test void loadingThePortCatalogsEveryConditioningSettingsType() { - var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of()); + var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of()); assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"), loaded.catalog().settings().stream().map(settings -> settings.id().toString()).toList()); diff --git a/src/test/java/com/volmit/example/chunk/GrassModule.java b/src/test/java/com/volmit/example/chunk/GrassModule.java index 7b20b826c..8821409cb 100644 --- a/src/test/java/com/volmit/example/chunk/GrassModule.java +++ b/src/test/java/com/volmit/example/chunk/GrassModule.java @@ -3,12 +3,17 @@ package com.volmit.example.chunk; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.stage.ChunkStage; import com.volmit.stage.ChunkStageContext; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; +import java.util.List; -/** Third-party decoration: tops terrain columns using the terrain module's typed output. */ +/** Third-party decoration: tops terrain columns using the terrain module's typed output. It runs where any + * column of the chunk has grass and reads the settings per column, so a biome border inside the chunk + * keeps grass on its own side. + */ public final class GrassModule implements IrisModule { public static final ChunkStage TOP = Stage.chunk("example:grass/top"); @@ -25,16 +30,17 @@ public final class GrassModule implements IrisModule { .run(GrassModule::cover); } - private static void cover(ChunkStageContext context, GrassSettings grass) { - var top = grass.block(); + private static void cover(ChunkStageContext context, List> inChunk) { var heights = context.output(TerrainModule.SURFACE); var blocks = context.hunk(BlockState.class); for (int x = 0; x < blocks.getWidth(); x++) { for (int z = 0; z < blocks.getDepth(); z++) { + var here = context.settings().at(GrassSettings.class, context.originX() + x, context.originZ() + z); int height = heights.at(x, z); - if (height > 0) { - blocks.set(x, height - 1, z, top); + if (here.isEmpty() || height <= 0) { + continue; } + blocks.set(x, height - 1, z, here.getLast().value().block()); // the most specific level wins here } } } diff --git a/src/test/java/com/volmit/example/chunk/VeinModule.java b/src/test/java/com/volmit/example/chunk/VeinModule.java new file mode 100644 index 000000000..73effdec0 --- /dev/null +++ b/src/test/java/com/volmit/example/chunk/VeinModule.java @@ -0,0 +1,77 @@ +package com.volmit.example.chunk; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.mantle.BlockBox; +import com.volmit.mantle.MantleCodec; +import com.volmit.mantle.MantleKey; +import com.volmit.mantle.MantleLifetime; +import com.volmit.stage.ChunkStage; +import com.volmit.stage.ChunkStageContext; +import com.volmit.stage.MantleStage; +import com.volmit.stage.MantleStageContext; +import com.volmit.stage.Stage; +import com.volmit.stage.StageGraph; +import java.io.DataInput; +import java.io.DataOutput; +import java.io.IOException; +import java.util.List; + +/** Work across chunks: a mantle stage plans veins into the mantle, past its own chunk, and a chunk stage + * later turns its own chunk's part of the mantle into blocks. The two pipelines meet only in the mantle. + */ +public final class VeinModule implements IrisModule { + public static final MantleKey ORE = new MantleKey<>("example:veins/ore", Integer.class); + public static final MantleStage PLAN = Stage.mantle("example:veins/plan"); + public static final ChunkStage PLACE = Stage.chunk("example:veins/place"); + public static final BlockState ORE_BLOCK = new BlockState("minecraft:iron_ore"); + public static final int REACH = 16; + private static final int CHUNK_WIDTH = 16; + private static final int CHUNK_CENTRE = 7; + private static final int PLANNED = 1; + + @Override + public ModuleInfo info() { + return ModuleInfo.of("example:veins", "Veins", "1.0.0"); + } + + @Override + public void install(StageGraph graph) { + graph.define(PLAN).when(VeinSettings.class).reach(REACH).writesMantle(ORE).run(VeinModule::plan); + graph.define(PLACE).run(VeinModule::place); + } + + @Override + public void register(FeatureRegistry registry) { + registry.registerMantle(ORE, MantleLifetime.GENERATION, new IntegerCodec()); + } + + /** One vein per level that configures veins at the chunk's centre column: levels stack. */ + private static void plan(MantleStageContext context, List> inChunk) { + int startX = context.originX() + CHUNK_CENTRE; + int z = context.originZ() + CHUNK_CENTRE; + var ore = context.mantle().layer(ORE); + for (var vein : context.settings().at(VeinSettings.class, startX, z)) { + for (int step = 0; step < Math.min(vein.value().length(), REACH + CHUNK_WIDTH - CHUNK_CENTRE); step++) { + ore.set(startX + step, vein.value().y(), z, PLANNED); + } + } + } + + private static void place(ChunkStageContext context) { + var blocks = context.hunk(BlockState.class); + var chunk = new BlockBox(context.originX(), context.originY(), context.originZ(), + context.originX() + blocks.getWidth(), context.originY() + blocks.getHeight(), context.originZ() + blocks.getDepth()); + context.mantle().layer(ORE).visit(chunk, (x, y, z, planned) -> + blocks.set(x - context.originX(), y - context.originY(), z - context.originZ(), ORE_BLOCK)); + } + + private static final class IntegerCodec implements MantleCodec { + public int version() { return 0; } + public void write(DataOutput output, Integer value) throws IOException { output.writeInt(value); } + public Integer read(DataInput input, int storedVersion) throws IOException { return input.readInt(); } + } +} diff --git a/src/test/java/com/volmit/example/chunk/VeinSettings.java b/src/test/java/com/volmit/example/chunk/VeinSettings.java new file mode 100644 index 000000000..a16a8607a --- /dev/null +++ b/src/test/java/com/volmit/example/chunk/VeinSettings.java @@ -0,0 +1,31 @@ +package com.volmit.example.chunk; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; + +@Desc("Plans a horizontal ore vein from the centre of each chunk, which may run into the next chunk") +@Feature(id = "example:veins", name = "Veins", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME}) +public final class VeinSettings implements IrisFeature { + @Desc("Blocks along X, starting at the chunk's centre column") + private int length = 12; + + @Desc("World height of the vein") + private int y = -60; + + public VeinSettings() {} + + public VeinSettings(int length, int y) { + this.length = length; + this.y = y; + } + + public int length() { + return length; + } + + public int y() { + return y; + } +} diff --git a/src/test/java/com/volmit/example/hosttypes/Palette.java b/src/test/java/com/volmit/example/hosttypes/Palette.java new file mode 100644 index 000000000..d802fc4f1 --- /dev/null +++ b/src/test/java/com/volmit/example/hosttypes/Palette.java @@ -0,0 +1,13 @@ +package com.volmit.example.hosttypes; + +import java.util.List; + +/** Stands for a host class such as Iris's material palette: the host describes it in studio itself. */ +public final class Palette { + private List blocks = List.of("minecraft:stone"); + private Object anything; + + public List blocks() { + return blocks; + } +} diff --git a/src/test/java/com/volmit/example/placement/MossModule.java b/src/test/java/com/volmit/example/placement/MossModule.java index 94c7f8b92..03abe5533 100644 --- a/src/test/java/com/volmit/example/placement/MossModule.java +++ b/src/test/java/com/volmit/example/placement/MossModule.java @@ -3,6 +3,7 @@ package com.volmit.example.placement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.placement.PlacedBlock; import com.volmit.stage.PlacementStage; import com.volmit.stage.PlacementStageContext; @@ -10,6 +11,7 @@ import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; import com.volmit.stage.StageRef; import com.volmit.world.BlockPosition; +import java.util.List; import java.util.Optional; /** Third-party module: turns the ground under the anchor into moss. It requires the core @@ -33,7 +35,8 @@ public final class MossModule implements IrisModule { .run(MossModule::spread); } - private static void spread(PlacementStageContext context, MossSettings moss) { + private static void spread(PlacementStageContext context, List> settings) { + var moss = settings.getFirst().value(); // a placement declares its settings once var anchor = context.output(AnchorModule.HEIGHT).anchor(); var access = context.access(); int groundY = anchor.y() - 1; diff --git a/src/test/java/com/volmit/example/placement/SnowModule.java b/src/test/java/com/volmit/example/placement/SnowModule.java index bf41113f9..a6d71b37e 100644 --- a/src/test/java/com/volmit/example/placement/SnowModule.java +++ b/src/test/java/com/volmit/example/placement/SnowModule.java @@ -3,6 +3,7 @@ package com.volmit.example.placement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.placement.PlacedBlock; import com.volmit.stage.BlockStage; import com.volmit.stage.PlacementStage; @@ -11,6 +12,7 @@ import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; import com.volmit.stage.StageRef; import com.volmit.world.BlockPosition; +import java.util.List; import java.util.Optional; /** Port of PlacementModuleSnow: collect written tops, then cover them after the finishing work @@ -40,7 +42,8 @@ public final class SnowModule implements IrisModule { .run(SnowModule::cover); } - private static void cover(PlacementStageContext context, SnowSettings snow) { + private static void cover(PlacementStageContext context, List> settings) { + var snow = settings.getFirst().value(); // a placement declares its settings once var layer = SNOW.withProperty("layers", Integer.toString(snow.layers())); var access = context.access(); for (var top : context.output(COLLECT).tops()) { diff --git a/src/test/java/com/volmit/example/placement/StiltModule.java b/src/test/java/com/volmit/example/placement/StiltModule.java index 491e8abdb..b0af14a9c 100644 --- a/src/test/java/com/volmit/example/placement/StiltModule.java +++ b/src/test/java/com/volmit/example/placement/StiltModule.java @@ -2,6 +2,7 @@ package com.volmit.example.placement; import com.volmit.IrisModule; import com.volmit.ModuleInfo; +import com.volmit.config.FeatureSettings.Entry; import com.volmit.object.ObjectBlock; import com.volmit.placement.PlacedBlock; import com.volmit.stage.BlockStage; @@ -10,6 +11,7 @@ import com.volmit.stage.PlacementStageContext; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; import com.volmit.world.BlockPosition; +import java.util.List; import java.util.Optional; /** Port of PlacementModuleStilt: collect the lowest layer per block, then fill down after writes. */ @@ -34,7 +36,8 @@ public final class StiltModule implements IrisModule { .run(StiltModule::fill); } - private static void fill(PlacementStageContext context, StiltSettings stilt) { + private static void fill(PlacementStageContext context, List> settings) { + var stilt = settings.getFirst().value(); // a placement declares its settings once var anchor = context.output(AnchorModule.HEIGHT); for (var block : context.output(BOUNDS).lowestLayer()) { var bottom = anchor.worldPosition(context.request(), block.position()); diff --git a/src/test/java/com/volmit/example/terrain/LayersModule.java b/src/test/java/com/volmit/example/terrain/LayersModule.java new file mode 100644 index 000000000..f34f5213c --- /dev/null +++ b/src/test/java/com/volmit/example/terrain/LayersModule.java @@ -0,0 +1,22 @@ +package com.volmit.example.terrain; + +import com.volmit.FeatureRegistry; +import com.volmit.IrisModule; +import com.volmit.ModuleInfo; +import com.volmit.stage.StageGraph; + +/** A built-in module whose settings use host types; it only registers them. */ +public final class LayersModule implements IrisModule { + @Override + public ModuleInfo info() { + return ModuleInfo.of("iris:layers", "Layers", "test"); + } + + @Override + public void install(StageGraph graph) {} + + @Override + public void register(FeatureRegistry registry) { + registry.registerSettings(LayersSettings.class); + } +} diff --git a/src/test/java/com/volmit/example/terrain/LayersSettings.java b/src/test/java/com/volmit/example/terrain/LayersSettings.java new file mode 100644 index 000000000..ac8ddc75f --- /dev/null +++ b/src/test/java/com/volmit/example/terrain/LayersSettings.java @@ -0,0 +1,19 @@ +package com.volmit.example.terrain; + +import com.volmit.FeatureAttachment; +import com.volmit.IrisFeature; +import com.volmit.config.Desc; +import com.volmit.config.Feature; +import com.volmit.example.hosttypes.Palette; +import java.util.List; + +/** Built-in settings holding host types, written in pack JSON as a bare list: {@code "layers": [...]}. */ +@Feature(id = "iris:layers", name = "Layers", alias = "layers", targets = FeatureAttachment.Target.BIOME) +public final class LayersSettings implements IrisFeature { + @Desc("Rock layers from the surface down") + private List layers = List.of(); + + public List layers() { + return layers; + } +} diff --git a/src/test/java/com/volmit/host/ConfiguredSettingsTest.java b/src/test/java/com/volmit/host/ConfiguredSettingsTest.java new file mode 100644 index 000000000..87a48882c --- /dev/null +++ b/src/test/java/com/volmit/host/ConfiguredSettingsTest.java @@ -0,0 +1,43 @@ +package com.volmit.host; + +import com.volmit.FeatureAttachment.Target; +import com.volmit.IrisFeature; +import com.volmit.config.Feature; +import com.volmit.config.FeatureSettings.Entry; +import com.volmit.resource.ResourceId; +import java.util.List; +import org.junit.jupiter.api.Test; +import static org.junit.jupiter.api.Assertions.*; + +class ConfiguredSettingsTest { + private static final ResourceId DIMENSION = ResourceId.parse("pack:dimension/overworld"); + private static final ResourceId BIOME = ResourceId.parse("pack:biome/plains"); + private static final ResourceId OBJECT = ResourceId.parse("pack:object/tree"); + + @Feature(id = "test:levels", name = "Levels", targets = {Target.DIMENSION, Target.BIOME, Target.OBJECT_PLACEMENT}) + static final class Levels implements IrisFeature {} + + @Feature(id = "test:other", name = "Other", targets = Target.BIOME) + static final class Other implements IrisFeature {} + + @Test + void entriesAreGroupedByTypeInLevelOrderAndNeverMerged() { + var biome = new Entry<>(Target.BIOME, BIOME, new Levels()); + var dimension = new Entry<>(Target.DIMENSION, DIMENSION, new Levels()); + + var settings = ConfiguredSettings.of(List.of(biome, dimension)); + + assertEquals(List.of(dimension, biome), settings.find(Levels.class)); + assertEquals(List.of(), settings.find(Other.class)); + assertEquals(List.of(), ConfiguredSettings.none().find(Levels.class)); + } + + @Test + void aPlacementDeclaresEachTypeOnce() { + var levels = new Levels(); + assertEquals(List.of(new Entry<>(Target.OBJECT_PLACEMENT, OBJECT, levels)), + ConfiguredSettings.placement(OBJECT, levels).find(Levels.class)); + var twice = assertThrows(IllegalArgumentException.class, () -> ConfiguredSettings.placement(OBJECT, new Levels(), new Levels())); + assertEquals("Settings configured twice: " + Levels.class.getName(), twice.getMessage()); + } +} diff --git a/src/test/java/com/volmit/host/DiscoveredModuleTest.java b/src/test/java/com/volmit/host/DiscoveredModuleTest.java index a73655d00..de4c2f34d 100644 --- a/src/test/java/com/volmit/host/DiscoveredModuleTest.java +++ b/src/test/java/com/volmit/host/DiscoveredModuleTest.java @@ -30,7 +30,7 @@ class DiscoveredModuleTest { var module = new ShiftingIdentity(); var discovered = DiscoveredModule.builtIn(module); - var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of()); + var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of()); assertEquals("first:core", discovered.info().id().toString()); assertEquals(List.of("first:core/mark"), diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 247b6343f..669c3f79c 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -128,14 +128,14 @@ class ModuleRegistryTest { 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(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of()); assertEquals(List.of("test:core/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(DiscoveredModule.builtIn(conditioned)), reserved, Set.of())); + assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), reserved, Set.of(), Set.of())); } @Test @@ -180,11 +180,11 @@ class ModuleRegistryTest { public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); } }; - var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of()); assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList()); var unowned = assertThrows(IllegalArgumentException.class, - () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of())); + () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of())); assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage()); } diff --git a/src/test/java/com/volmit/host/PackModulesTest.java b/src/test/java/com/volmit/host/PackModulesTest.java index 53ac22abf..0e7c1ad59 100644 --- a/src/test/java/com/volmit/host/PackModulesTest.java +++ b/src/test/java/com/volmit/host/PackModulesTest.java @@ -44,7 +44,7 @@ class PackModulesTest { private static LoadedModules loadWithBuiltIns(PackModules packModules) { var modules = new ArrayList<>(PlacementModules.builtIns()); modules.addAll(packModules.modules()); - return LoadedModules.load(modules, Map.of(), Set.of()); + return LoadedModules.load(modules, Map.of(), Set.of(), Set.of()); } /** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */ @@ -343,7 +343,7 @@ class PackModulesTest { try (var packModules = PackModules.load(pack)) { assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses()); - assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); } } @@ -477,7 +477,7 @@ class PackModulesTest { .writeInto(pack, "beta.jar"); try (var packModules = PackModules.load(pack)) { - var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of()); + var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()); assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size"))); var beta = packModules.modules().getLast().module().getClass(); assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length, @@ -494,7 +494,7 @@ class PackModulesTest { try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) { var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule()))); modules.addAll(packModules.modules()); - var order = LoadedModules.load(modules, Map.of(), Set.of()).placement().stages().stream() + var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of()).placement().stages().stream() .map(stage -> stage.stage().id().toString()).toList(); assertEquals(List.of("iris:carve/clear", "user:core/carved"), order); } @@ -572,7 +572,7 @@ class PackModulesTest { .writeInto(pack, "once.jar"); try (var packModules = PackModules.load(pack)) { - var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())); + var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); assertEquals("once:core", packModules.modules().getFirst().info().id().toString()); assertEquals(1, loaded.placement().stages().size()); } @@ -591,7 +591,7 @@ class PackModulesTest { .writeInto(pack, "beta.jar"); try (var packModules = PackModules.load(pack)) { - assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())), + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), "Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing", "java.lang.NoSuchMethodError", "pack.lib.Lib.added()"); } @@ -603,7 +603,7 @@ class PackModulesTest { module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "two.jar"); try (var packModules = PackModules.load(pack)) { - assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())), + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), "Duplicate module dup:core from " + origin("two.jar") + "; already loaded from " + origin("one.jar")); } } @@ -625,7 +625,7 @@ class PackModulesTest { .writeInto(pack, "foreign.jar"); try (var packModules = PackModules.load(pack)) { - assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())), + assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())), "Stage mine:other/work must start with mine:core/, the id of its defining module mine:core from " + origin("foreign.jar")); } } @@ -640,8 +640,8 @@ class PackModulesTest { assertEquals("Module iris:stilt from " + origin("stilt.jar") + " uses reserved namespace 'iris', which only " + "modules that ship with the host may use; give the module a namespace of its own, which its stages, " + "settings ids and mantle keys then use too", - failure(() -> LoadedModules.load(packModules.modules(), Map.of(), RESERVED_NAMESPACES))); - assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of())); + failure(() -> LoadedModules.load(packModules.modules(), Map.of(), RESERVED_NAMESPACES, Set.of()))); + assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())); } } @@ -654,13 +654,13 @@ class PackModulesTest { try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) { var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule()))); modules.addAll(packModules.modules()); - assertDoesNotThrow(() -> LoadedModules.load(modules, Map.of(), RESERVED_NAMESPACES)); + assertDoesNotThrow(() -> LoadedModules.load(modules, Map.of(), RESERVED_NAMESPACES, Set.of())); } } @Test void invalidReservedNamespaceFails() { assertEquals("Reserved namespace 'iris:core' is not a namespace; name one such as iris, without ':' or a path", - failure(() -> LoadedModules.load(List.of(), Map.of(), Set.of("iris:core")))); + failure(() -> LoadedModules.load(List.of(), Map.of(), Set.of("iris:core"), Set.of()))); } } diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java index 45eb1271c..0679a9c3a 100644 --- a/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -4,7 +4,9 @@ import com.volmit.FeatureAttachment.Target; import com.volmit.config.Reference; import com.volmit.example.chunk.GrassModule; import com.volmit.example.chunk.TerrainModule; +import com.volmit.example.hosttypes.Palette; import com.volmit.example.placement.PlacementModules; +import com.volmit.example.terrain.LayersModule; import com.volmit.host.schema.FeatureRole; import com.volmit.host.schema.FeatureSchema; import com.volmit.host.schema.ObjectType; @@ -15,6 +17,7 @@ import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumConstant; import com.volmit.host.schema.ValueKind.EnumKind; +import com.volmit.host.schema.ValueKind.HostKind; import com.volmit.host.schema.ValueKind.IntegerKind; import com.volmit.host.schema.ValueKind.ListKind; import com.volmit.host.schema.ValueKind.MapKind; @@ -40,6 +43,7 @@ import static org.junit.jupiter.api.Assertions.*; class PackSchemaTest { private static final ModuleHost NO_BUILT_INS = ModuleHost.of(List.of()); private static final String FLORA = "example:flora"; + private static final String HOST_TYPES = "com.volmit.example.hosttypes"; private static final String FLORA_SOURCE = "settings example:flora (module example:flora from modules/flora.jar)"; private static final String NO_STAGES = ""; @@ -338,10 +342,49 @@ class PackSchemaTest { false, OptionalDouble.empty(), OptionalDouble.empty(), Optional.of("minecraft:grass_block")), grass.settings().options().getFirst()); } + @Test + void builtInSettingsMayHoldHostTypesWhichTheHostDescribesItself() { + var builtIns = List.of(new LayersModule()); + var schema = schemaOf(pack("layers"), ModuleHost.of(builtIns).describingHostTypesIn(HOST_TYPES)); + + var layers = schema.fields(Target.BIOME).getFirst(); + var option = layers.settings().options().getFirst(); + assertEquals(new ListKind(new HostKind(Palette.class.getName()), false), option.kind()); + assertEquals(Optional.of(List.of()), option.defaultValue()); + assertTrue(schema.types().stream().noneMatch(type -> type.name().equals(Palette.class.getName())), + "the host describes its own types, so their fields are never read"); + assertEquals(Optional.of(option), layers.shorthand(), "one option: packs may write the bare list"); + + var undeclared = assertThrows(IllegalArgumentException.class, () -> schemaOf(pack("layers"), ModuleHost.of(builtIns))); + assertTrue(undeclared.getMessage().startsWith("Field " + Palette.class.getName() + ".anything of settings iris:layers"), + undeclared.getMessage()); + assertThrows(IllegalArgumentException.class, () -> NO_BUILT_INS.describingHostTypesIn("not a package")); + } + + @Test + void packModulesCannotUseHostTypes() { + var host = NO_BUILT_INS.exposing(HOST_TYPES).describingHostTypesIn(HOST_TYPES); + assertEquals("Field pack.flora.FloraSettings.palette of " + FLORA_SOURCE + " uses " + Palette.class.getName() + + ", a class the host describes itself, which only settings of modules that ship with the host may use; " + + ValueKinds.SUPPORTED_TYPES, + loadFailure(host, "private " + Palette.class.getName() + " palette;").getMessage()); + } + + @Test + void onlySettingsWithOneOptionHaveAShorthand() { + var flora = floraSchema().fields(Target.BIOME).getFirst(); + assertEquals(Optional.empty(), flora.shorthand()); + } + /** A pack whose module example:flora registers pack.flora.FloraSettings with {@code body} as its class body. */ private IllegalArgumentException loadFailure(String body, String... otherSources) { + return loadFailure(NO_BUILT_INS, body, otherSources); + } + + private IllegalArgumentException loadFailure(ModuleHost host, String body, String... otherSources) { var jar = module("pack.flora.FloraModule", FLORA, "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .compileAgainstHostOf(Palette.class) .source("pack.flora.FloraSettings", """ package pack.flora; @@ -362,7 +405,7 @@ class PackSchemaTest { } var pack = pack("broken-" + ++brokenPacks); jar.writeInto(pack, "flora.jar"); - return assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, NO_BUILT_INS)); + return assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, host)); } private void assertLoadFails(String expected, String body, String... otherSources) { diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index 844326ca2..d4cc23094 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -374,7 +374,7 @@ class StageGraphTest { place(graph, flatEdit(), ConfiguredSettings.none()); assertEquals(List.of("unrelated"), events); events.clear(); - place(graph, flatEdit(), ConfiguredSettings.of(new Toggle())); + place(graph, flatEdit(), ConfiguredSettings.placement(ResourceId.parse("test:placement"), new Toggle())); assertEquals(List.of("toggled", "dependent:1", "unrelated"), events); } @@ -452,6 +452,8 @@ class StageGraphTest { var empty = resolve(Pipeline.CHUNK); assertThrows(IllegalArgumentException.class, () -> new PlacementRunner(empty)); assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.PLACEMENT))); + assertThrows(IllegalArgumentException.class, () -> new MantleRunner(empty)); + assertThrows(IllegalArgumentException.class, () -> new ChunkRunner(resolve(Pipeline.MANTLE))); assertTrue(empty.describe().contains("CHUNK pipeline: 0 stages, 0 block passes")); } @@ -463,9 +465,9 @@ class StageGraphTest { void reachIsDeclaredPerStageAndCollectedPerPipelineAndLayer() { var depth = new MantleKey<>("test:reach/depth", Integer.class); var marks = new MantleKey<>("test:reach/marks", String.class); - var carve = Stage.chunk("test:reach/carve"); - var mark = Stage.chunk("test:reach/mark"); - var plain = Stage.chunk("test:reach/plain"); + var carve = Stage.mantle("test:reach/carve"); + var mark = Stage.mantle("test:reach/mark"); + var plain = Stage.mantle("test:reach/plain"); var paint = Stage.placementBlock("test:reach/paint"); var reach = module("test:reach", stages -> { stages.define(carve).reach(24).writesMantle(depth).run(context -> {}); @@ -473,42 +475,60 @@ class StageGraphTest { stages.define(plain).run(context -> {}); stages.define(paint).reach(2).run(context -> {}); }); - var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of()); + var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of()); - assertEquals(new StageReach(24, List.of(depth)), loaded.chunk().stages().getFirst().reach()); - assertEquals(StageReach.NONE, loaded.chunk().stages().get(2).reach(), "an undeclared reach is 0 with no layers"); - assertEquals(new PipelineReach(24, Map.of("test:reach/depth", 24, "test:reach/marks", 8)), loaded.chunk().reach()); + assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach()); + assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers"); + assertEquals(new PipelineReach(24, Map.of("test:reach/depth", 24, "test:reach/marks", 8)), loaded.mantle().reach()); assertEquals(new PipelineReach(2, Map.of()), loaded.placement().reach()); - assertTrue(loaded.chunk().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.chunk().describe()); - assertTrue(loaded.chunk().describe().contains(" reach 8 blocks, writes mantle test:reach/depth, test:reach/marks\n")); + assertEquals(new PipelineReach(0, Map.of()), loaded.chunk().reach()); + assertTrue(loaded.mantle().describe().contains(" reach 24 blocks, writes mantle test:reach/depth\n"), loaded.mantle().describe()); + assertTrue(loaded.mantle().describe().contains(" reach 8 blocks, writes mantle test:reach/depth, test:reach/marks\n")); } @Test void reachMustBeValidAndNameRegisteredLayers() { var depth = new MantleKey<>("test:reach/depth", Integer.class); - var carve = Stage.chunk("test:reach/carve"); + var carve = Stage.mantle("test:reach/carve"); - var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, + var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages -> stages.define(carve).reach(-1).run(context -> {})))); assertEquals("Stage test:reach/carve (module test:reach) declares a negative reach of -1 blocks", negative.getMessage()); - var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.CHUNK, + var twice = assertThrows(IllegalStateException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages -> stages.define(carve).reach(1).reach(2).run(context -> {})))); assertEquals("Stage test:reach/carve (module test:reach) already declares a reach of 1 blocks", twice.getMessage()); - assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, + assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.MANTLE, module("test:reach", stages -> stages.define(carve).writesMantle(depth, depth).run(context -> {})))); var unregistered = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn( - module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of())); + module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of())); assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;" + " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage()); var asText = new MantleKey<>("test:reach/depth", String.class); var mismatch = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle( - module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of())); + module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of())); assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String," + " but it is registered as java.lang.Integer", mismatch.getMessage()); } + @Test + void chunkStagesNeitherReachBeyondTheirChunkNorWriteTheMantle() { + var depth = new MantleKey<>("test:reach/depth", Integer.class); + var carve = Stage.chunk("test:reach/carve"); + + var reach = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, + module("test:reach", stages -> stages.define(carve).reach(8).run(context -> {})))); + assertEquals("Stage test:reach/carve (module test:reach) is a chunk stage and declares a reach of 8 blocks, but chunk" + + " stages write only their own chunk and read the mantle; define work that writes the mantle or reaches beyond" + + " its chunk as a mantle stage (Stage.mantle), which runs before the chunks it reaches", reach.getMessage()); + var writes = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, + module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))); + assertTrue(writes.getMessage().startsWith("Stage test:reach/carve (module test:reach) is a chunk stage and declares mantle writes"), + writes.getMessage()); + assertDoesNotThrow(() -> resolve(Pipeline.CHUNK, module("test:reach", stages -> stages.define(carve).reach(0).run(context -> {})))); + } + /** {@code module}, also registering {@code layers}. */ private static IrisModule withMantle(IrisModule module, MantleKey... layers) { return new IrisModule() { diff --git a/src/test/java/com/volmit/host/StageStreamsTest.java b/src/test/java/com/volmit/host/StageStreamsTest.java index ebd106e0f..2a2d044a0 100644 --- a/src/test/java/com/volmit/host/StageStreamsTest.java +++ b/src/test/java/com/volmit/host/StageStreamsTest.java @@ -131,7 +131,7 @@ class StageStreamsTest { var graph = resolve(Pipeline.CHUNK, module("a:mod", stages -> stages.define(Stage.chunk("a:mod/ores")) .run(context -> drawn.add((long) context.random().nextInt(BOUND))))); - new ChunkRunner(graph).generate(TestContexts.generation(Map.of()), TestContexts.SEED, ConfiguredSettings.none()); + new ChunkRunner(graph).generate(TestContexts.generation(Map.of()), TestContexts.SEED); assertEquals(firstDraws(TestContexts.SEED, "a:mod/ores", 1), drawn); } diff --git a/src/test/java/com/volmit/support/ColumnSettings.java b/src/test/java/com/volmit/support/ColumnSettings.java new file mode 100644 index 000000000..3be7da00c --- /dev/null +++ b/src/test/java/com/volmit/support/ColumnSettings.java @@ -0,0 +1,32 @@ +package com.volmit.support; + +import com.volmit.IrisFeature; +import com.volmit.config.FeatureSettings; +import java.util.List; +import java.util.function.BiFunction; + +/** Settings declared per world column by a function, for chunk and mantle tests. */ +public final class ColumnSettings implements FeatureSettings { + public static final ColumnSettings NONE = new ColumnSettings((x, z) -> List.of()); + + private final BiFunction>> columns; + + public ColumnSettings(BiFunction>> columns) { + this.columns = columns; + } + + /** The same entries at every column. */ + public static ColumnSettings everywhere(Entry... entries) { + var all = List.of(entries); + return new ColumnSettings((x, z) -> all); + } + + @Override + @SuppressWarnings("unchecked") // Filtered by the requested type. + public List> at(Class featureType, int worldX, int worldZ) { + return columns.apply(worldX, worldZ).stream() + .filter(entry -> featureType.isInstance(entry.value())) + .map(entry -> (Entry) entry) + .toList(); + } +} diff --git a/src/test/java/com/volmit/support/MemoryMantle.java b/src/test/java/com/volmit/support/MemoryMantle.java new file mode 100644 index 000000000..0d1708acf --- /dev/null +++ b/src/test/java/com/volmit/support/MemoryMantle.java @@ -0,0 +1,81 @@ +package com.volmit.support; + +import com.volmit.mantle.BlockBox; +import com.volmit.mantle.Mantle; +import com.volmit.mantle.MantleEdit; +import com.volmit.mantle.MantleKey; +import com.volmit.mantle.MantleLayer; +import com.volmit.mantle.MantleVisitor; +import com.volmit.world.BlockPosition; +import java.util.Comparator; +import java.util.HashMap; +import java.util.Map; +import java.util.TreeMap; + +/** An in-memory mantle over fixed bounds; an invocation sees it through {@link #within(BlockBox)}. */ +public final class MemoryMantle { + private static final Comparator VISIT_ORDER = Comparator.comparingInt(BlockPosition::x) + .thenComparingInt(BlockPosition::y).thenComparingInt(BlockPosition::z); + + private final Map> layers = new HashMap<>(); + + /** A view that accepts reads and writes inside {@code bounds} only. */ + public Mantle within(BlockBox bounds) { + return new Mantle() { + public BlockBox bounds() { return bounds; } + public MantleLayer layer(MantleKey key) { return new Layer<>(key, bounds); } + public MantleEdit edit() { throw new UnsupportedOperationException("Edits are not used in these tests"); } + }; + } + + public T get(MantleKey key, int x, int y, int z) { + return key.type().cast(values(key).get(new BlockPosition(x, y, z))); + } + + private TreeMap values(MantleKey key) { + return layers.computeIfAbsent(key.id(), ignored -> new TreeMap<>(VISIT_ORDER)); + } + + private final class Layer implements MantleLayer { + private final MantleKey key; + private final BlockBox bounds; + + Layer(MantleKey key, BlockBox bounds) { + this.key = key; + this.bounds = bounds; + } + + public T get(int x, int y, int z) { + requireInside(x, y, z); + return MemoryMantle.this.get(key, x, y, z); + } + + public void set(int x, int y, int z, T value) { + requireInside(x, y, z); + values(key).put(new BlockPosition(x, y, z), key.type().cast(value)); + } + + public void remove(int x, int y, int z) { + requireInside(x, y, z); + values(key).remove(new BlockPosition(x, y, z)); + } + + public void visit(BlockBox area, MantleVisitor visitor) { + if (!bounds.contains(area)) throw new IndexOutOfBoundsException("Outside the mantle view: " + area); + values(key).forEach((position, value) -> { + if (area.contains(position.x(), position.y(), position.z())) { + visitor.accept(position.x(), position.y(), position.z(), key.type().cast(value)); + } + }); + } + + public void clear(BlockBox area) { + if (!bounds.contains(area)) throw new IndexOutOfBoundsException("Outside the mantle view: " + area); + values(key).keySet().removeIf(position -> area.contains(position.x(), position.y(), position.z())); + } + + private void requireInside(int x, int y, int z) { + if (!bounds.contains(x, y, z)) throw new IndexOutOfBoundsException("Outside the mantle view: " + x + "," + y + "," + z); + } + } +} diff --git a/src/test/java/com/volmit/support/TestContexts.java b/src/test/java/com/volmit/support/TestContexts.java index 0cc87d105..82a68bae4 100644 --- a/src/test/java/com/volmit/support/TestContexts.java +++ b/src/test/java/com/volmit/support/TestContexts.java @@ -2,6 +2,7 @@ package com.volmit.support; import com.volmit.config.FeatureSettings; import com.volmit.generation.GenerationContext; +import com.volmit.generation.MantleGenerationContext; import com.volmit.hunk.Hunk; import com.volmit.mantle.Mantle; import com.volmit.object.ObjectTransformer; @@ -18,6 +19,11 @@ public final class TestContexts { private TestContexts() {} public static GenerationContext generation(Map, Hunk> hunks) { + return generation(hunks, null, null); + } + + /** The chunk at the origin; a null {@code settings} or {@code mantle} fails when used. */ + public static GenerationContext generation(Map, Hunk> hunks, FeatureSettings settings, Mantle mantle) { return new GenerationContext() { public int originX() { return 0; } public int originY() { return -64; } @@ -25,8 +31,8 @@ public final class TestContexts { public long worldSeed() { return SEED; } 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"); } + public FeatureSettings settings() { return used(settings, "settings"); } + public Mantle mantle() { return used(mantle, "mantle"); } @SuppressWarnings("unchecked") public Hunk hunk(Class type) { var hunk = hunks.get(type); @@ -36,6 +42,19 @@ public final class TestContexts { }; } + /** The mantle invocation of the chunk whose first block is ({@code originX}, {@code originZ}). */ + public static MantleGenerationContext mantle(int originX, int originZ, FeatureSettings settings, Mantle mantle) { + return new MantleGenerationContext() { + public int originX() { return originX; } + public int originZ() { return originZ; } + public long worldSeed() { return SEED; } + public PackResources resources() { throw new AssertionError("Unused resources"); } + public TerrainSampler terrain() { throw new AssertionError("Unused terrain"); } + public FeatureSettings settings() { return settings; } + public Mantle mantle() { return mantle; } + }; + } + public static PlacementContext placement() { return placement(null); } @@ -53,4 +72,9 @@ public final class TestContexts { } }; } + + private static T used(T value, String name) { + if (value == null) throw new AssertionError("Unused " + name); + return value; + } }