From a325640d5d3fa1795c8fb11715a45b6293992d29 Mon Sep 17 00:00:00 2001 From: piexel Date: Tue, 6 Oct 2026 13:59:28 +0200 Subject: [PATCH] Key settings by feature id, order options as declared and declare stage reach - Packs write settings under the feature id. @Feature(field) becomes an optional alias that only built-in modules may set, so existing pack JSON keeps loading; a pack module setting one fails the load. Reserved host fields now only constrain aliases. FeatureSchema exposes key and alias. - Pack snippet names live under their module's folder (snippet///...); snippet names are folder paths. - OptionsMetadata lists options in declaration order, read from the class file, a superclass's first. - @Ref(PACK_BIOME|PACK_REGION|PACK_OBJECT) fits String only. - Stage definitions declare reach(blocks) and writesMantle(layers); ResolvedGraph.reach() collects the pipeline and per-layer maximum, and the load fails on an unregistered or mistyped layer. --- CONTRACTS.md | 29 ++-- DESIGN.md | 86 +++++++++--- README.md | 50 +++++-- .../java/com/volmit/FeatureAttachment.java | 25 +++- .../com/volmit/config/DeclaredFieldOrder.java | 55 ++++++++ src/main/java/com/volmit/config/Feature.java | 10 +- .../com/volmit/config/OptionsMetadata.java | 19 ++- .../java/com/volmit/host/BlockStageDraft.java | 13 ++ .../com/volmit/host/FeatureDescriptor.java | 17 ++- .../com/volmit/host/GraphDescription.java | 13 ++ .../java/com/volmit/host/GraphResolver.java | 2 +- .../com/volmit/host/InvocationStageDraft.java | 13 ++ .../java/com/volmit/host/LoadedModules.java | 26 +++- src/main/java/com/volmit/host/ModuleHost.java | 8 +- .../java/com/volmit/host/ModuleRegistry.java | 62 ++++++--- .../com/volmit/host/PackSchemaBuilder.java | 52 ++++++- .../java/com/volmit/host/PipelineReach.java | 32 +++++ .../java/com/volmit/host/ResolvedGraph.java | 5 + .../java/com/volmit/host/ResolvedStage.java | 7 +- .../com/volmit/host/StageDeclaration.java | 29 ++++ src/main/java/com/volmit/host/StageReach.java | 30 ++++ src/main/java/com/volmit/host/TypeDrafts.java | 2 - src/main/java/com/volmit/host/ValueKinds.java | 9 ++ .../com/volmit/host/schema/FeatureSchema.java | 17 ++- .../com/volmit/host/schema/ObjectType.java | 2 +- .../com/volmit/host/schema/PackSchema.java | 8 +- .../volmit/stage/BlockStageDefinition.java | 11 ++ .../ConditionalBlockStageDefinition.java | 6 + .../stage/ConditionalStageDefinition.java | 6 + .../com/volmit/stage/StageDefinition.java | 11 ++ .../java/com/volmit/FeatureContractTest.java | 5 +- .../volmit/example/chunk/GrassSettings.java | 2 +- .../example/placement/MossSettings.java | 2 +- .../example/placement/SnowSettings.java | 2 +- .../example/placement/StiltSettings.java | 2 +- .../com/volmit/host/ModuleRegistryTest.java | 19 +-- .../java/com/volmit/host/PackSchemaTest.java | 131 ++++++++++++++---- .../java/com/volmit/host/StageGraphTest.java | 81 ++++++++++- 38 files changed, 761 insertions(+), 138 deletions(-) create mode 100644 src/main/java/com/volmit/config/DeclaredFieldOrder.java create mode 100644 src/main/java/com/volmit/host/PipelineReach.java create mode 100644 src/main/java/com/volmit/host/StageReach.java diff --git a/CONTRACTS.md b/CONTRACTS.md index 53d6ddb79..ab90754e3 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -19,7 +19,8 @@ types that carry them and lists what the Iris adapter still owes. | 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` | -| Annotated settings | `IrisFeature`, `@Feature`, config annotations, `OptionsMetadata` | +| 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`) | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | | Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | @@ -45,8 +46,13 @@ A pack load works on copies of the module jars, so the originals are never held Modules describe their settings only through their settings classes; jars ship no schema files. The pack load turns every catalogued settings type into a `PackSchema` and fails, naming field, settings and module, on a field type it cannot describe, a `@Ref` on a field that is not text, a class without -a working no-argument constructor or a bad or repeated snippet name. Defaults come from an instance -made by that constructor. The description is in a fixed order and holds module entries only. +a working no-argument constructor, a bad or repeated snippet name, or a pack class's snippet name +outside its module's folder. Defaults come from an instance made by that constructor. Options are in +declaration order. + +Packs write settings under the feature id. Only built-in modules may set an alias, a short key that +existing pack JSON uses; a pack module setting one fails the load. Aliases are unique per target and +may not equal a reserved host field. The description is in a fixed order and holds module entries only. Modules compile against the API `compileOnly` and never ship it. At runtime they can use the API (`com.volmit.*`), the host packages the host chooses to expose, the JDK and the classes in their @@ -75,7 +81,9 @@ running Iris is the pack publisher's responsibility. work inside the ported stages. - Derive one seed per placement (world seed and the placement's stable identity) and per chunk (world seed and chunk position) and pass it to `PlacementRunner.place` / `ChunkRunner.generate`. -- Prepare the full area a placement or chunk may read or write, including neighbors. Never clip. +- 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. - 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. @@ -93,11 +101,15 @@ running Iris is the pack publisher's responsibility. packs and is part of what packs can break on. Stage output types and settings types that pack code uses through those stages must be in exposed packages too. The API is always exposed. - Consider showing `PackModules.missingClasses()` in studio. +- Decode module settings under the feature id and, for built-ins, the alias. Fail a JSON object that + holds both, naming the two keys. - Render `pack.schema()` into studio's files: merge each target's `fields(target)` into the schema - of the matching Iris file type (dimension, region, biome, object placement), write `types()` as - definitions, a `/snippet/` schema per entry of `snippets()`, and completion lists per - `Reference` from the server registries and the pack's biome, region and object folders. Fail, do - not drop, when a module snippet name equals one of Iris's own. + of the matching Iris file type (dimension, region, biome, object placement) under the key and the + alias, write `types()` as definitions, a `/snippet/` schema per entry of `snippets()`, and + completion lists per `Reference` from the server registries and the pack's biome, region and + object folders. `PACK_*` references are pack paths without a namespace, as Iris writes them. Pack + snippet names are under their module's folder, so they cannot collide with Iris's own; built-in + names are Iris's to keep distinct. - Refuse to open a pack in studio when its load fails, showing the error, rather than writing a schema without the modules. - Load the pack again and rebuild the schema files after a module jar in `/modules` changes. @@ -106,5 +118,4 @@ running Iris is the pack publisher's responsibility. ## Open -- Per-stage reach declarations, replacing the removed modifier radii. - Terrain/biome providers, pack transformations, structure assembly and the runtime family. diff --git a/DESIGN.md b/DESIGN.md index 94ab7e724..971a05a70 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -457,17 +457,61 @@ all stages of the invocation. Hunk coordinates are local; samples and mantle coo world blocks. The runner does no neighbor scheduling or rollback. A failed invocation must stop the host from publishing the chunk. +## Reach + +A stage may write outside its footprint: a carver reaches into neighbor chunks, a tree's leaves spread +past the object's trunk. The host has to prepare that area, and the mantle in it, before the stage +runs. Stages declare it in their definition: + +```java +graph.define(CARVE).reach(32).writesMantle(CarveModule.CAVES).run(CarveModule::carve); +``` + +- `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 + 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. + +Each resolved stage carries its `StageReach`. `ResolvedGraph.reach()` collects a `PipelineReach`: +the largest reach of the pipeline's stages, and per mantle layer the largest reach of the stages +that write it. Inactive stages count, because activation is per invocation and the prepared area is +decided once per pack load. `describe()` lists each stage's reach. + +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 +as its reach. Terrain samples are computed, not prepared, and need nothing. + ## Settings, geometry and storage -Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, JSON -field, attachment targets). `when(type)` validates the annotation while the module installs. The id +Settings types implement `IrisFeature` and carry `@Feature` (namespaced id, display name, optional +alias, attachment targets). `when(type)` validates the annotation while the module installs. The id must be owned by a module naming the type (see Namespaces), or the owner registers the type itself with `FeatureRegistry.registerSettings`. That is for settings no stage names, such as settings read only through `FeatureSettings.at(...)`; registering a type a stage also names changes nothing, and a type its owner registered may be named in `when(...)` by any module. `LoadedModules.load` catalogs those types with geometry generator settings and rejects duplicate -ids and JSON field collisions per attachment target, including reserved host fields. -`OptionsMetadata` reads field metadata; it does not decode JSON. +ids and alias collisions per attachment target, including reserved host fields. +`OptionsMetadata` reads field metadata, in declaration order; it does not decode JSON. + +### JSON keys and aliases + +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 `:`. + +Built-in modules may also set `@Feature(alias = "stilt")`, a short key that existing pack JSON +already uses, such as `"stilt": {...}`. An alias has no `:`, so it never equals an id. Aliases are +unique per target and may not equal a reserved host field; reserved host fields therefore constrain +aliases only. A pack module that sets an alias fails the load and is told to use its id: aliases are +for keeping existing pack files working, and a pack module has no existing files to keep. + +A JSON object that holds both a feature's alias and its id is ambiguous. That is a host decoding +rule, since IrisApi does not decode JSON: the host fails such an object, naming both keys. `GeneratedObject` is sparse, immutable local geometry with bounds, an anchor, sorted blocks, optional block entity payloads and markers. `ObjectGenerator` produces it from settings and a @@ -497,8 +541,8 @@ already keep module fields from colliding with them. - A `FeatureSchema` per catalogued type: feature id and name, role (`SETTINGS` for types named in `when(...)` or registered with `registerSettings`, `OBJECT_GENERATOR` for `registerObject`), the - owning module's `ModuleInfo`, the JSON field, its targets and the settings `ObjectType`. - `fields(target)` lists a target's features; a feature attached to several targets appears under + owning module's `ModuleInfo`, the JSON key (the feature id), the alias if any, its targets and the + settings `ObjectType`. `fields(target)` lists a target's features; a feature attached to several targets appears under each. The owner is the one module whose id owns the feature id; module ids are unique and contain no `/`, so there is never more than one. - An `ObjectType` per class reachable from module settings, keyed by binary class name: description, @@ -507,8 +551,8 @@ already keep module fields from colliding with them. directly or through others, ends the walk at its own name. Two different classes with one name fail the load; only a built-in class and a pack class can collide that way. - A `SchemaOption` per field that `OptionsMetadata` selects, which means instance fields that are - not transient, inherited ones included. Each has its name, `ValueKind`, `@Desc`, `@Required`, - `@MinNumber`/`@MaxNumber` and the default value. + not transient, inherited ones included, in declaration order. Each has its name, `ValueKind`, + `@Desc`, `@Required`, `@MinNumber`/`@MaxNumber` and the default value. ### Value kinds @@ -553,7 +597,9 @@ structures, potion effects and enchantments from the server registries, and biom objects of the pack, the resource folders Iris's own settings refer to most. More kinds come when a module needs one and the host can serve it. `@Ref` fits `String` and `ResourceId` and lists, sets and arrays of them, where it applies to the elements. On any other field, a map included, it fails the -load. `BlockState` always names a block, so its fields are block references without `@Ref`; +load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`) fit `String` only: packs name their +biomes, regions and objects by path without a namespace, such as `desert/dunes`, which a `ResourceId` +cannot hold. `BlockState` always names a block, so its fields are block references without `@Ref`; `@Ref(BLOCK)` there is accepted, any other kind fails. ### Defaults @@ -579,23 +625,31 @@ itself, such as a field holding `this`, is left out of the outer object. ### Snippets `@Snippet("name")` on a class lets a pack write that object in its own file under `snippet/name/`. -`snippets()` lists those types. A snippet name must be a folder name of lowercase letters, digits, `-` -and `_`, and it must belong to one class; otherwise the load fails naming both classes. +`snippets()` lists those types. A snippet name is a folder path: segments of lowercase letters, +digits, `-`, `_` and `.`, separated by `/`, never `.` or `..`. It must belong to one class; otherwise +the load fails naming both classes. + +A class of a pack module keeps its snippets under the folder of a module of the pack: the name is the +module's id as a path, `example/moss`, or starts with it and `/`, such as `example/moss/patch` +(folder `snippet/example/moss/patch/`). Built-in classes keep the short names Iris's snippet folders +already have. Since built-in modules ship with Iris and pack names always start with a pack module's +namespace, which no built-in uses, a pack snippet can never collide with Iris's own or another +module's. A class belongs to the pack when the pack's class loader defined it. ### Stable order The host writes schema files from this, so the order is fixed: features by id, a target's features -by JSON field, types by class name, snippets by snippet name, options by field name and enum -constants in declaration order. Options are sorted by name because `Class.getDeclaredFields()` -promises no order. Which settings an error names first follows feature id order too, so the same +by JSON key, types by class name, snippets by snippet name, and options and enum constants in +declaration order. Options of a superclass come before the subclass's own. +`Class.getDeclaredFields()` promises no order, but the class file lists fields as the source declares +them, so `OptionsMetadata` reads it with `java.lang.classfile`. A settings class therefore has to come +from a jar or a class directory, which every module class does. Which settings an error names first follows feature id order too, so the same pack always fails with the same message. ## Not implemented - Iris host wiring: JSON decoding and validation, rendering `PackSchema` into Iris's schema and workspace files, resource loaders, platform block adapters, storage and codecs. -- Reach. The old per-modifier `writeRadius` and `mantleRadius` are gone with the modifiers. The - host must prepare the whole area a pipeline may touch. Per-stage reach is an open question. - Legacy random compatibility. Existing Iris features draw from shared, positional generators in a fixed order. Where existing worlds are promised to stay the same, the adapter has to reproduce those draws inside the ported stages; per-stage streams will not match them on their own. diff --git a/README.md b/README.md index cfb0d8a98..2f05423e2 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,21 @@ 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 + +A stage that writes outside its chunk or object declares how far, so the host can prepare that area +and its mantle first: + +```java +graph.define(CARVE).reach(32).writesMantle(CarveModule.CAVES).run(CarveModule::carve); +``` + +`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. +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. + ## Module jars A pack loads its modules from `/modules/*.jar`. One jar holds one module. Its entry point @@ -136,7 +151,7 @@ completion from it. ```java @Desc("Plants flowers and bushes") -@Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME) +@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME) // packs write "example:flora": {...} public final class FloraSettings implements IrisFeature { @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) private int density = 4; // default 4 @@ -157,15 +172,22 @@ public final class FloraSettings implements IrisFeature { shows. - Field types: `boolean`, primitive or boxed numbers, `String`, `ResourceId`, `BlockState`, enums, `List`, `Set` and arrays of these, `Map`, and concrete classes, which are described the - same way. `@Snippet("name")` on a class lets packs write it as a file under `snippet/name/`. + same way. `@Snippet("example/flora/patch")` on a class lets packs write it as a file under + `snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder + path (`example/flora` for `example:flora`). Anything else fails the pack load: `char`, JDK classes such as `UUID` or `Optional`, `ResourceKey`, interfaces and abstract classes, inner (non-static) classes, collections without type arguments, concrete collections such as `ArrayList`, and maps with other keys. - `@Ref(Reference.X)` says what a `String` or `ResourceId` names, also on lists, sets and arrays of them, so studio offers the right list: `BLOCK`, `ITEM`, `ENTITY`, `BIOME`, `STRUCTURE`, `POTION_EFFECT` or `ENCHANTMENT` from the server's registries, or `PACK_BIOME`, `PACK_REGION` or - `PACK_OBJECT` of the pack. `BlockState` fields name blocks without it. `@Ref` on any other field - fails the load. + `PACK_OBJECT` of the pack. The pack kinds fit `String` only, in the form packs use (`desert/dunes`), + never `ResourceId`. `BlockState` fields name blocks without it. `@Ref` on any other field fails + the load. +- Packs write settings under the feature id. Built-in modules may also set `@Feature(alias = "stilt")`, + 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 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 @@ -177,7 +199,8 @@ A load error names the field, the settings and the module: Field com.example.flora.FloraSettings.id of settings example:flora (module example:flora from modules/flora.jar) uses java.util.UUID, a JDK class settings cannot use; settings fields can be booleans, numbers, String, ResourceId, BlockState, enums, lists, sets and arrays of these, Map with String keys and classes with a no-argument constructor Field com.example.flora.FloraSettings.count of settings example:flora (module example:flora from modules/flora.jar) has @Ref(BLOCK) on int, but @Ref fits only String and ResourceId and lists, sets and arrays of them Class com.example.flora.Shape of settings example:flora (module example:flora from modules/flora.jar) has no no-argument constructor; the host creates settings with it and reads their defaults from it, so declare one, private if nothing else should use it -Snippet name 'patch' is used by com.example.flora.Patch of settings example:flora (module example:flora from modules/flora.jar) and by com.example.flora.Plot of settings example:flora (module example:flora from modules/flora.jar); studio describes snippet/patch/ by one class, so give each its own name +Snippet name 'patch' of com.example.flora.Patch of settings example:flora (module example:flora from modules/flora.jar) is not under a module of the pack; snippets of pack modules start with their module's id as a folder path, such as 'example/flora/patch' (folder snippet/example/flora/patch/) +Settings com.example.flora.FloraSettings of module example:flora from modules/flora.jar set alias 'flora'; only modules that ship with the host may set one, so remove it: packs write these settings under their id "example:flora" ``` ## Host side @@ -293,9 +316,10 @@ have no path between them. `pack.schema()` is the `PackSchema` of the pack's modules, built-in ones included: plain Java values, no JSON. The host renders it and merges it with its own fields: -- `fields(target)`: the module features attached to a target, by JSON field. Each `FeatureSchema` has +- `fields(target)`: the module features attached to a target, by JSON key. Each `FeatureSchema` has the feature id and name, its role (`SETTINGS` or `OBJECT_GENERATOR`), the owning module's - `ModuleInfo`, the field, its targets and the settings `ObjectType`. + `ModuleInfo`, the JSON key (the id), the alias of a built-in if it has one, its targets and the + settings `ObjectType`. - `types()`: every class reachable from module settings, once each, by name. An `ObjectType` has the class name, description, snippet name and options. A `SchemaOption` has name, `ValueKind`, description, required, minimum, maximum and default value. @@ -306,10 +330,10 @@ no JSON. The host renders it and merges it with its own fields: - `snippets()` and `objectGenerators()` pick the types with a snippet name and the object generator features. -For the stilt example the host sees one `OBJECT_PLACEMENT` field. The records are abridged: +For the stilt example the host sees one `OBJECT_PLACEMENT` feature. The records are abridged: ``` -FeatureSchema[id=iris:stilt, name=Stilt, role=SETTINGS, module=Stilts (iris:stilt), field=stilt, targets=[OBJECT_PLACEMENT], +FeatureSchema[id=iris:stilt, name=Stilt, role=SETTINGS, module=Stilts (iris:stilt), key=iris:stilt, alias=Optional[stilt], targets=[OBJECT_PLACEMENT], settings=ObjectType[name=com.volmit.example.placement.StiltSettings, description=Fills the space below an object down to the ground, snippet=Optional.empty, options=[SchemaOption[name=maxDepth, kind=IntegerKind[], description=Maximum blocks filled below each lowest object block, required=false, minimum=OptionalDouble[1.0], maximum=OptionalDouble.empty, defaultValue=Optional[16]]]]] @@ -347,17 +371,19 @@ 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 (`StageGraphTest`, `ModuleRegistryTest`), and per-stage random streams: inserting a module +mantle keys, reach per stage, pipeline and mantle layer (`StageGraphTest`, `ModuleRegistryTest`), 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 independent Python reference (`python3 -B src/test/reference/world_random.py`; the build does not need Python) and fails if the type gains an unpinned method or implements `RandomGenerator`. -`PackSchemaTest` loads module jars and checks their description: fields under their targets, +`PackSchemaTest` loads module jars and checks their description: features under their targets by id, +aliases of built-ins and the load error when a pack module sets one, options in declaration order, descriptions, required, bounds, defaults (floats, nulls, sets, maps, objects, a field holding `this`), 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`, unusable class and bad or repeated snippet name. +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. `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 diff --git a/src/main/java/com/volmit/FeatureAttachment.java b/src/main/java/com/volmit/FeatureAttachment.java index 42d7130bf..9c5dcfc6f 100644 --- a/src/main/java/com/volmit/FeatureAttachment.java +++ b/src/main/java/com/volmit/FeatureAttachment.java @@ -1,16 +1,33 @@ package com.volmit; import java.util.Objects; +import java.util.Optional; import java.util.Set; -/** Maps settings to an ordinary existing JSON field, without an extension wrapper. */ -public record FeatureAttachment(String field, Set targets) { +/** Where settings appear in pack JSON: the targets, and the optional short alias a built-in module + * may set besides the feature id, which is always the JSON key. + */ +public record FeatureAttachment(Optional alias, Set targets) { public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT } + private static final char NAMESPACE_SEPARATOR = ':'; + public FeatureAttachment { - Objects.requireNonNull(field, "field"); - if (field.isBlank()) throw new IllegalArgumentException("Field must not be blank"); + Objects.requireNonNull(alias, "alias"); + alias.ifPresent(FeatureAttachment::requireFieldName); targets = Set.copyOf(targets); if (targets.isEmpty()) throw new IllegalArgumentException("At least one target is required"); } + + /** Checks a JSON field name that is not a feature id: an alias or a field the host itself uses. + * It is not blank and has no ':', which every feature id has, so the two never collide. + */ + public static String requireFieldName(String name) { + Objects.requireNonNull(name, "name"); + if (name.isBlank()) throw new IllegalArgumentException("Field must not be blank"); + if (name.indexOf(NAMESPACE_SEPARATOR) >= 0) { + throw new IllegalArgumentException("Field " + name + " contains ':', which only feature ids may contain"); + } + return name; + } } diff --git a/src/main/java/com/volmit/config/DeclaredFieldOrder.java b/src/main/java/com/volmit/config/DeclaredFieldOrder.java new file mode 100644 index 000000000..f9b34bbf9 --- /dev/null +++ b/src/main/java/com/volmit/config/DeclaredFieldOrder.java @@ -0,0 +1,55 @@ +package com.volmit.config; + +import java.io.IOException; +import java.io.InputStream; +import java.io.UncheckedIOException; +import java.lang.classfile.ClassFile; +import java.lang.reflect.Field; +import java.util.Arrays; +import java.util.Comparator; +import java.util.List; + +/** Orders a class's own fields as its source declares them. {@link Class#getDeclaredFields()} promises + * no order, but the class file lists fields in declaration order, so this reads it. + */ +final class DeclaredFieldOrder { + private static final String CLASS_FILE_SUFFIX = ".class"; + + private DeclaredFieldOrder() {} + + static List of(Class type) { + var names = fieldNames(type); + return Arrays.stream(type.getDeclaredFields()) + .sorted(Comparator.comparingInt((Field field) -> position(names, field, type))) + .toList(); + } + + private static int position(List names, Field field, Class type) { + int position = names.indexOf(field.getName()); + if (position < 0) { + throw new IllegalArgumentException("Field " + field.getName() + " of " + type.getName() + + " is not in its class file, so its declaration order is unknown"); + } + return position; + } + + private static List fieldNames(Class type) { + try (var classFile = openClassFile(type)) { + return ClassFile.of().parse(classFile.readAllBytes()).fields().stream() + .map(field -> field.fieldName().stringValue()) + .toList(); + } catch (IOException failure) { + throw new UncheckedIOException("Cannot read the class file of " + type.getName(), failure); + } + } + + private static InputStream openClassFile(Class type) { + var resource = "/" + type.getName().replace('.', '/') + CLASS_FILE_SUFFIX; + var stream = type.getResourceAsStream(resource); + if (stream == null) { + throw new IllegalArgumentException("Cannot read the class file of " + type.getName() + + " to order its options as declared; settings classes must come from a jar or a class directory"); + } + return stream; + } +} diff --git a/src/main/java/com/volmit/config/Feature.java b/src/main/java/com/volmit/config/Feature.java index 7dc783341..35a049ec7 100644 --- a/src/main/java/com/volmit/config/Feature.java +++ b/src/main/java/com/volmit/config/Feature.java @@ -2,12 +2,18 @@ package com.volmit.config; import java.lang.annotation.*; -/** Identity and JSON attachment for an IrisFeature configuration class. */ +/** Identity and JSON attachment for an IrisFeature configuration class. Packs write the settings under + * their feature id, such as {@code "example:moss": {...}}, at each of the targets. + * + *

{@code alias} is an optional short JSON key that only modules shipping with the host may set, so + * existing pack JSON such as {@code "stilt": {...}} keeps loading. A pack module that sets one fails + * the load. An alias contains no ':', so it never equals a feature id. + */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.TYPE) public @interface Feature { String id(); String name(); - String field(); + String alias() default ""; com.volmit.FeatureAttachment.Target[] targets(); } diff --git a/src/main/java/com/volmit/config/OptionsMetadata.java b/src/main/java/com/volmit/config/OptionsMetadata.java index 4274e26fe..003f92b61 100644 --- a/src/main/java/com/volmit/config/OptionsMetadata.java +++ b/src/main/java/com/volmit/config/OptionsMetadata.java @@ -25,15 +25,15 @@ public record OptionsMetadata(String description, String snippet, List

{@code
@@ -81,9 +81,9 @@ public record ModuleHost(
         return Map.copyOf(copy);
     }
 
-    /** A blank field name fails here, as it would in a settings type's {@code @Feature}. */
+    /** A blank field name, or one with ':' like a feature id, fails here, as it would as an alias. */
     private static void requireFieldNames(Map> fields) {
-        fields.forEach((target, names) -> names.forEach(name -> new FeatureAttachment(name, Set.of(target))));
+        fields.values().forEach(names -> names.forEach(FeatureAttachment::requireFieldName));
     }
 
     private static Map> merge(
diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java
index b54ddd8cb..2700f3b5e 100644
--- a/src/main/java/com/volmit/host/ModuleRegistry.java
+++ b/src/main/java/com/volmit/host/ModuleRegistry.java
@@ -9,15 +9,18 @@ import com.volmit.mantle.MantleKey;
 import com.volmit.mantle.MantleLifetime;
 import com.volmit.object.ObjectGeneratorFactory;
 import com.volmit.resource.ResourceId;
+import java.util.ArrayList;
 import java.util.HashMap;
 import java.util.HashSet;
+import java.util.List;
 import java.util.Map;
 import java.util.Objects;
 import java.util.Set;
 
 /** Reference host registry. Single-threaded registration ends with freeze(); the catalog is
- * immutable. IDs are unique across feature kinds; JSON fields are unique per attachment target.
- * Pass existing host JSON fields to reserve them before modules register. Modules register through
+ * immutable. IDs are unique across feature kinds, and every feature id is its JSON key. Aliases,
+ * which only built-in modules may set, are unique per attachment target and may not equal the
+ * host JSON fields passed in to reserve them. Modules register through
  * {@link #register(DiscoveredModule)}; object feature ids, mantle keys and explicitly registered
  * settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}). A failed registration leaves the registry unchanged. A failed module callback
  * invalidates the host's whole build. This does not decode JSON, discover modules or instantiate
@@ -31,6 +34,7 @@ public final class ModuleRegistry implements FeatureRegistry {
     private final Set> featureTypes = new HashSet<>();
     private final Set> registeredByOwner = new HashSet<>();
     private final Map fields = new HashMap<>();
+    private final List registered = new ArrayList<>();
     private FeatureCatalog catalog;
     private DiscoveredModule registering;
 
@@ -50,6 +54,7 @@ public final class ModuleRegistry implements FeatureRegistry {
             throw new IllegalStateException("Module " + discovered.info().id() + " registered during " + registering.info().id());
         }
         registering = discovered;
+        registered.add(discovered);
         try {
             discovered.module().register(this);
         } finally {
@@ -65,7 +70,7 @@ public final class ModuleRegistry implements FeatureRegistry {
         var descriptor = FeatureDescriptor.of(featureType);
         requireOwnedId("Object generator settings " + featureType.getName() + " with feature id", descriptor.id());
         var registration = new ObjectRegistration<>(descriptor, factory);
-        claim(descriptor);
+        claim(descriptor, registering);
         objects.put(featureType, registration);
     }
 
@@ -87,19 +92,21 @@ public final class ModuleRegistry implements FeatureRegistry {
         checkOpen();
         var descriptor = FeatureDescriptor.of(settingsType);
         requireOwnedId("Settings " + settingsType.getName() + " with feature id", descriptor.id());
-        catalogSettings(descriptor);
+        catalogSettings(descriptor, registering);
         registeredByOwner.add(settingsType);
     }
 
     /** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder}
-     * has checked. Several stages, and the owner's {@link #registerSettings}, may name one type.
+     * has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call
+     * it after every module has registered, so the owner is known.
      */
     void registerStageSettings(Class settingsType) {
         checkOpen();
         if (settings.containsKey(settingsType)) {
             return;
         }
-        catalogSettings(FeatureDescriptor.of(settingsType));
+        var descriptor = FeatureDescriptor.of(settingsType);
+        catalogSettings(descriptor, ownerOf(descriptor));
     }
 
     /** Whether the module owning {@code settingsType} registered it through {@link #registerSettings}. */
@@ -114,14 +121,21 @@ public final class ModuleRegistry implements FeatureRegistry {
         return catalog;
     }
 
-    private void catalogSettings(FeatureDescriptor descriptor) {
+    private void catalogSettings(FeatureDescriptor descriptor, DiscoveredModule owner) {
         if (settings.containsKey(descriptor.type())) {
             return;
         }
-        claim(descriptor);
+        claim(descriptor, owner);
         settings.put(descriptor.type(), descriptor);
     }
 
+    private DiscoveredModule ownerOf(FeatureDescriptor descriptor) {
+        return registered.stream()
+                .filter(module -> module.info().ownsId(descriptor.id()))
+                .findFirst()
+                .orElseThrow(() -> new IllegalStateException("No registered module owns feature id " + descriptor.id()));
+    }
+
     private void requireOwnedId(String registration, ResourceId id) {
         if (registering == null) {
             throw new IllegalStateException(registration + " " + id + " registered outside IrisModule.register");
@@ -141,25 +155,32 @@ public final class ModuleRegistry implements FeatureRegistry {
     }
 
     private void reserveHostField(FeatureAttachment.Target target, String name) {
-        new FeatureAttachment(name, Set.of(target));
-        fields.put(new Field(target, name), "host");
+        fields.put(new Field(target, FeatureAttachment.requireFieldName(name)), "host");
     }
 
-    private void claim(FeatureDescriptor descriptor) {
-        validateClaim(descriptor);
+    private void claim(FeatureDescriptor descriptor, DiscoveredModule owner) {
+        validateClaim(descriptor, owner);
         recordClaim(descriptor);
     }
 
-    private void validateClaim(FeatureDescriptor descriptor) {
+    private void validateClaim(FeatureDescriptor descriptor, DiscoveredModule owner) {
         if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
             throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
         }
+        descriptor.alias().ifPresent(alias -> validateAlias(descriptor, alias, owner));
+    }
 
+    private void validateAlias(FeatureDescriptor descriptor, String alias, DiscoveredModule owner) {
+        if (owner.source() == DiscoveredModule.Source.PACK) {
+            throw new IllegalArgumentException("Settings " + descriptor.type().getName() + " of module " + owner
+                    + " set alias '" + alias + "'; only modules that ship with the host may set one, so remove it:"
+                    + " packs write these settings under their id \"" + descriptor.key() + "\"");
+        }
         for (var target : descriptor.attachment().targets()) {
-            var field = new Field(target, descriptor.attachment().field());
+            var field = new Field(target, alias);
             if (fields.containsKey(field)) {
-                throw new IllegalArgumentException(
-                        "JSON field collision at " + field + ": " + fields.get(field));
+                throw new IllegalArgumentException("Alias collision at " + field + " of " + descriptor.id()
+                        + ": " + fields.get(field));
             }
         }
     }
@@ -167,10 +188,11 @@ public final class ModuleRegistry implements FeatureRegistry {
     private void recordClaim(FeatureDescriptor descriptor) {
         featureTypes.add(descriptor.type());
         featureIds.add(descriptor.id());
-        for (var target : descriptor.attachment().targets()) {
-            var field = new Field(target, descriptor.attachment().field());
-            fields.put(field, descriptor.id().toString());
-        }
+        descriptor.alias().ifPresent(alias -> {
+            for (var target : descriptor.attachment().targets()) {
+                fields.put(new Field(target, alias), descriptor.id().toString());
+            }
+        });
     }
 
     private void checkOpen() {
diff --git a/src/main/java/com/volmit/host/PackSchemaBuilder.java b/src/main/java/com/volmit/host/PackSchemaBuilder.java
index 971888610..484fefb38 100644
--- a/src/main/java/com/volmit/host/PackSchemaBuilder.java
+++ b/src/main/java/com/volmit/host/PackSchemaBuilder.java
@@ -17,10 +17,13 @@ import java.util.stream.Stream;
 
 /** Describes a loaded pack's catalogued settings for studio. Fails the load, naming the class, field
  * and module, on settings the host could not render: an unsupported field type, a misplaced
- * {@code @Ref}, a class without a usable no-argument constructor or a snippet name used twice.
+ * {@code @Ref}, a class without a usable no-argument constructor, a snippet name used twice or a pack
+ * class's snippet name outside its module's path.
  */
 final class PackSchemaBuilder {
-    private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_-]+");
+    private static final Pattern SNIPPET_NAME = Pattern.compile("[a-z0-9_.-]+(/[a-z0-9_.-]+)*");
+    private static final Pattern RELATIVE_SEGMENT = Pattern.compile("(^|/)\\.\\.?(/|$)");
+    private static final char FOLDER_SEPARATOR = '/';
 
     private final List modules;
     private final TypeDrafts drafts = new TypeDrafts();
@@ -47,8 +50,8 @@ final class PackSchemaBuilder {
     private record FeatureDraft(Catalogued catalogued, DiscoveredModule owner) {
         FeatureSchema complete(Map types) {
             var descriptor = catalogued.descriptor();
-            return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(),
-                    descriptor.attachment().field(), descriptor.attachment().targets(), types.get(descriptor.type().getName()));
+            return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(),
+                    descriptor.alias(), descriptor.attachment().targets(), types.get(descriptor.type().getName()));
         }
     }
 
@@ -80,16 +83,51 @@ final class PackSchemaBuilder {
             var snippet = draft.metadata().snippet();
             if (snippet.isEmpty()) continue;
             requireSnippetName(snippet, draft);
+            requirePackSnippetPath(snippet, draft);
             var previous = owners.putIfAbsent(snippet, draft);
             if (previous != null) throw snippetCollision(snippet, previous, draft);
         }
     }
 
     private static void requireSnippetName(String snippet, TypeDrafts.TypeDraft draft) {
-        if (SNIPPET_NAME.matcher(snippet).matches()) return;
+        if (SNIPPET_NAME.matcher(snippet).matches() && !RELATIVE_SEGMENT.matcher(snippet).find()) return;
         throw new IllegalArgumentException("Snippet name '" + snippet + "' of " + draft.type().getName() + " of "
-                + draft.source() + " is not a folder name; packs write snippets under snippet//, so use lowercase"
-                + " letters, digits, '-' and '_'");
+                + draft.source() + " is not a folder path; packs write snippets under snippet//, so use lowercase"
+                + " letters, digits, '-', '_' and '.', with '/' between folders");
+    }
+
+    /** A pack class keeps its snippets under the folder of a module of its pack,
+     * {@code snippet///}, so they can never collide with Iris's own or another module's.
+     */
+    private void requirePackSnippetPath(String snippet, TypeDrafts.TypeDraft draft) {
+        if (!isPackClass(draft.type())) return;
+        if (packModules().anyMatch(module -> isUnderModuleFolder(snippet, module))) return;
+        var example = moduleFolder(draft.source().module()) + FOLDER_SEPARATOR + lastSegment(snippet);
+        throw new IllegalArgumentException("Snippet name '" + snippet + "' of " + draft.type().getName() + " of "
+                + draft.source() + " is not under a module of the pack; snippets of pack modules start with their"
+                + " module's id as a folder path, such as '" + example + "' (folder snippet/" + example + "/)");
+    }
+
+    private boolean isPackClass(Class type) {
+        return packModules().anyMatch(module -> module.module().getClass().getClassLoader() == type.getClassLoader());
+    }
+
+    private Stream packModules() {
+        return modules.stream().filter(module -> module.source() == DiscoveredModule.Source.PACK);
+    }
+
+    private static boolean isUnderModuleFolder(String snippet, DiscoveredModule module) {
+        var folder = moduleFolder(module);
+        return snippet.equals(folder) || snippet.startsWith(folder + FOLDER_SEPARATOR);
+    }
+
+    private static String moduleFolder(DiscoveredModule module) {
+        var id = module.info().id();
+        return id.namespace() + FOLDER_SEPARATOR + id.path();
+    }
+
+    private static String lastSegment(String snippet) {
+        return snippet.substring(snippet.lastIndexOf(FOLDER_SEPARATOR) + 1);
     }
 
     private static IllegalArgumentException snippetCollision(String snippet, TypeDrafts.TypeDraft first, TypeDrafts.TypeDraft second) {
diff --git a/src/main/java/com/volmit/host/PipelineReach.java b/src/main/java/com/volmit/host/PipelineReach.java
new file mode 100644
index 000000000..168dba6f4
--- /dev/null
+++ b/src/main/java/com/volmit/host/PipelineReach.java
@@ -0,0 +1,32 @@
+package com.volmit.host;
+
+import java.util.Collections;
+import java.util.Map;
+import java.util.TreeMap;
+
+/** The most any stage of a pipeline writes beyond its footprint, so the host can prepare the area and
+ * mantle a chunk or placement may touch. Inactive stages count too: activation is decided per
+ * invocation, the area once per pack.
+ *
+ * @param blocks the largest {@link StageReach#blocks()} of the pipeline's stages, in blocks along X and Z
+ * @param mantleLayers for each mantle layer some stage writes, by layer id in id order, the largest
+ *     reach of the stages that write it
+ */
+public record PipelineReach(int blocks, Map mantleLayers) {
+    public PipelineReach {
+        if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks);
+        mantleLayers = Collections.unmodifiableMap(new TreeMap<>(mantleLayers));
+    }
+
+    static PipelineReach of(Iterable stages) {
+        int blocks = 0;
+        var layers = new TreeMap();
+        for (var stage : stages) {
+            blocks = Math.max(blocks, stage.blocks());
+            for (var layer : stage.mantleLayers()) {
+                layers.merge(layer.id(), stage.blocks(), Math::max);
+            }
+        }
+        return new PipelineReach(blocks, layers);
+    }
+}
diff --git a/src/main/java/com/volmit/host/ResolvedGraph.java b/src/main/java/com/volmit/host/ResolvedGraph.java
index 1282f481b..24f883eff 100644
--- a/src/main/java/com/volmit/host/ResolvedGraph.java
+++ b/src/main/java/com/volmit/host/ResolvedGraph.java
@@ -68,6 +68,11 @@ public final class ResolvedGraph {
         return pairs;
     }
 
+    /** The most the pipeline's stages write beyond their footprint, overall and per mantle layer. */
+    public PipelineReach reach() {
+        return PipelineReach.of(stages.stream().map(ResolvedStage::reach).toList());
+    }
+
     /** Human-readable order, owners, edges, block passes and unordered pairs. */
     public String describe() {
         return GraphDescription.describe(this);
diff --git a/src/main/java/com/volmit/host/ResolvedStage.java b/src/main/java/com/volmit/host/ResolvedStage.java
index 1fcce5ce4..54df13ada 100644
--- a/src/main/java/com/volmit/host/ResolvedStage.java
+++ b/src/main/java/com/volmit/host/ResolvedStage.java
@@ -9,18 +9,21 @@ import java.util.Optional;
 
 /** Diagnostic view of one stage at its resolved position. incoming lists every edge into this
  * stage, including soft edges other stages declared; absentSoftTargets lists this stage's soft
- * references that matched no installed stage and therefore add no ordering.
+ * references that matched no installed stage and therefore add no ordering. reach is what the stage
+ * declared it writes beyond its footprint.
  */
 public record ResolvedStage(
         Stage stage,
         ResourceId module,
         Optional> settings,
         List incoming,
-        List absentSoftTargets) {
+        List absentSoftTargets,
+        StageReach reach) {
     public ResolvedStage {
         Objects.requireNonNull(stage, "stage");
         Objects.requireNonNull(module, "module");
         Objects.requireNonNull(settings, "settings");
+        Objects.requireNonNull(reach, "reach");
         incoming = List.copyOf(incoming);
         absentSoftTargets = List.copyOf(absentSoftTargets);
     }
diff --git a/src/main/java/com/volmit/host/StageDeclaration.java b/src/main/java/com/volmit/host/StageDeclaration.java
index 11dd753d2..d04523c8a 100644
--- a/src/main/java/com/volmit/host/StageDeclaration.java
+++ b/src/main/java/com/volmit/host/StageDeclaration.java
@@ -1,6 +1,7 @@
 package com.volmit.host;
 
 import com.volmit.IrisFeature;
+import com.volmit.mantle.MantleKey;
 import com.volmit.resource.ResourceId;
 import com.volmit.stage.Stage;
 import com.volmit.stage.StageRef;
@@ -17,6 +18,8 @@ final class StageDeclaration {
     private final List softAfter = new ArrayList<>();
     private final List softBefore = new ArrayList<>();
     private FeatureDescriptor settings;
+    private Integer reachBlocks;
+    private final List> mantleLayers = new ArrayList<>();
     private StageBody body;
 
     StageDeclaration(Stage stage, ResourceId module) {
@@ -49,6 +52,28 @@ final class StageDeclaration {
         settings = FeatureDescriptor.of(settingsType);
     }
 
+    void reach(int blocks) {
+        checkOpen();
+        if (reachBlocks != null) {
+            throw new IllegalStateException("Stage " + this + " already declares a reach of " + reachBlocks + " blocks");
+        }
+        if (blocks < 0) {
+            throw new IllegalArgumentException("Stage " + this + " declares a negative reach of " + blocks + " blocks");
+        }
+        reachBlocks = blocks;
+    }
+
+    void writesMantle(MantleKey... layers) {
+        checkOpen();
+        for (var layer : layers) {
+            Objects.requireNonNull(layer, "mantle layer");
+            if (mantleLayers.stream().anyMatch(declared -> declared.id().equals(layer.id()))) {
+                throw new IllegalArgumentException("Stage " + this + " declares mantle layer " + layer.id() + " twice");
+            }
+            mantleLayers.add(layer);
+        }
+    }
+
     /** Sets the only body. alternativeMethod names the builder method for the other output kind. */
     void complete(StageBody body, boolean bodyProducesOutput, String alternativeMethod) {
         checkOpen();
@@ -91,6 +116,10 @@ final class StageDeclaration {
         return body;
     }
 
+    StageReach reach() {
+        return new StageReach(reachBlocks == null ? 0 : reachBlocks, mantleLayers);
+    }
+
     @Override
     public String toString() {
         return stage.id() + " (module " + module + ")";
diff --git a/src/main/java/com/volmit/host/StageReach.java b/src/main/java/com/volmit/host/StageReach.java
new file mode 100644
index 000000000..ef8815205
--- /dev/null
+++ b/src/main/java/com/volmit/host/StageReach.java
@@ -0,0 +1,30 @@
+package com.volmit.host;
+
+import com.volmit.mantle.MantleKey;
+import java.util.HashSet;
+import java.util.List;
+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
+ *     columns.
+ * @param mantleLayers the mantle layers the stage writes, each once, in declaration order
+ */
+public record StageReach(int blocks, List> mantleLayers) {
+    /** A stage that declared nothing: it writes blocks inside its footprint only, and no mantle layer. */
+    public static final StageReach NONE = new StageReach(0, List.of());
+
+    public StageReach {
+        if (blocks < 0) throw new IllegalArgumentException("Negative reach: " + blocks);
+        mantleLayers = List.copyOf(mantleLayers);
+        var ids = new HashSet();
+        for (var layer : mantleLayers) {
+            if (!ids.add(Objects.requireNonNull(layer, "mantle layer").id())) {
+                throw new IllegalArgumentException("Mantle layer " + layer.id() + " declared twice");
+            }
+        }
+    }
+}
diff --git a/src/main/java/com/volmit/host/TypeDrafts.java b/src/main/java/com/volmit/host/TypeDrafts.java
index b47420f62..06daefaac 100644
--- a/src/main/java/com/volmit/host/TypeDrafts.java
+++ b/src/main/java/com/volmit/host/TypeDrafts.java
@@ -10,7 +10,6 @@ import java.lang.reflect.InvocationTargetException;
 import java.lang.reflect.MalformedParameterizedTypeException;
 import java.lang.reflect.Modifier;
 import java.util.Collection;
-import java.util.Comparator;
 import java.util.HashMap;
 import java.util.HashSet;
 import java.util.LinkedHashMap;
@@ -66,7 +65,6 @@ final class TypeDrafts {
         var instance = instantiate(type, source);
         var kinds = new ValueKinds(nested -> object(nested, source));
         var options = metadata.options().stream()
-                .sorted(Comparator.comparing(OptionsMetadata.Option::name))
                 .map(option -> new OptionDraft(option, kind(option, kinds, source), defaultValue(option.field(), instance, source)))
                 .toList();
         return new TypeDraft(type, source, metadata, options);
diff --git a/src/main/java/com/volmit/host/ValueKinds.java b/src/main/java/com/volmit/host/ValueKinds.java
index 9b2c65b82..cff435385 100644
--- a/src/main/java/com/volmit/host/ValueKinds.java
+++ b/src/main/java/com/volmit/host/ValueKinds.java
@@ -23,6 +23,7 @@ import java.lang.reflect.ParameterizedType;
 import java.lang.reflect.Type;
 import java.util.Arrays;
 import java.util.Collection;
+import java.util.EnumSet;
 import java.util.List;
 import java.util.Map;
 import java.util.Set;
@@ -40,6 +41,7 @@ final class ValueKinds {
             Byte.class, Short.class, Integer.class, Long.class);
     private static final Set> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class);
     private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map";
+    private static final Set PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT);
 
     private final Function, ObjectKind> objects;
 
@@ -94,9 +96,16 @@ final class ValueKinds {
 
     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);
         return new ReferenceKind(reference, format);
     }
 
+    /** Packs name their biomes, regions and objects by path without a namespace, so a ResourceId could not hold one. */
+    private static SettingsTypeProblem packReferenceOnResourceId(Reference reference) {
+        return new SettingsTypeProblem("has @Ref(" + reference + ") on ResourceId, but packs name their biomes,"
+                + " regions and objects by path without a namespace, such as desert/dunes; use String");
+    }
+
     private static ValueKind blockState(Reference reference) {
         if (reference == null || reference == Reference.BLOCK) return new ReferenceKind(Reference.BLOCK, TextFormat.BLOCK_STATE);
         throw new SettingsTypeProblem("has @Ref(" + reference + ") on BlockState, which always names a block;"
diff --git a/src/main/java/com/volmit/host/schema/FeatureSchema.java b/src/main/java/com/volmit/host/schema/FeatureSchema.java
index 2b7c4c8e9..a6795be94 100644
--- a/src/main/java/com/volmit/host/schema/FeatureSchema.java
+++ b/src/main/java/com/volmit/host/schema/FeatureSchema.java
@@ -6,23 +6,27 @@ import com.volmit.resource.ResourceId;
 import java.util.Collections;
 import java.util.EnumSet;
 import java.util.Objects;
+import java.util.Optional;
 import java.util.Set;
 
-/** A module's settings type and the JSON field it is attached to at each of its targets.
+/** A module's settings type and the JSON keys it is written under at each of its targets.
  *
  * @param id the feature id from {@code @Feature}
  * @param name the feature's display name from {@code @Feature}
  * @param module the module that owns the feature id
- * @param field the JSON field the settings are written under, the same at every target
- * @param targets where the field appears, in {@link FeatureAttachment.Target} order
- * @param settings the settings class; its description describes the field
+ * @param key the JSON key the settings are written under, the feature id, the same at every target
+ * @param alias the short JSON key a built-in module accepts instead of {@code key}; pack modules
+ *     have none. A JSON object may use one of the two, not both.
+ * @param targets where the keys appear, in {@link FeatureAttachment.Target} order
+ * @param settings the settings class; its description describes the value
  */
 public record FeatureSchema(
         ResourceId id,
         String name,
         FeatureRole role,
         ModuleInfo module,
-        String field,
+        String key,
+        Optional alias,
         Set targets,
         ObjectType settings) {
     public FeatureSchema {
@@ -30,7 +34,8 @@ public record FeatureSchema(
         Objects.requireNonNull(name, "name");
         Objects.requireNonNull(role, "role");
         Objects.requireNonNull(module, "module");
-        Objects.requireNonNull(field, "field");
+        Objects.requireNonNull(key, "key");
+        Objects.requireNonNull(alias, "alias");
         Objects.requireNonNull(settings, "settings");
         targets = Collections.unmodifiableSet(EnumSet.copyOf(targets));
     }
diff --git a/src/main/java/com/volmit/host/schema/ObjectType.java b/src/main/java/com/volmit/host/schema/ObjectType.java
index df62ec763..836dbffb3 100644
--- a/src/main/java/com/volmit/host/schema/ObjectType.java
+++ b/src/main/java/com/volmit/host/schema/ObjectType.java
@@ -10,7 +10,7 @@ import java.util.Optional;
  * @param description the class's {@code @Desc}, or empty
  * @param snippet the class's {@code @Snippet} name: a pack may then write the object in its own file
  *     under {@code snippet//} and refer to it by path
- * @param options the class's fields, including inherited ones, in name order
+ * @param options the class's fields, including inherited ones, in declaration order, a superclass's first
  */
 public record ObjectType(String name, String description, Optional snippet, List options) {
     public ObjectType {
diff --git a/src/main/java/com/volmit/host/schema/PackSchema.java b/src/main/java/com/volmit/host/schema/PackSchema.java
index 82b6b7676..1f7264db5 100644
--- a/src/main/java/com/volmit/host/schema/PackSchema.java
+++ b/src/main/java/com/volmit/host/schema/PackSchema.java
@@ -10,8 +10,8 @@ import java.util.Objects;
  * studio completion. It holds module-provided entries only: the host describes its own fields.
  *
  * 

Everything is in a fixed order, so the same modules always give the same description: features - * by id, the features of a target by JSON field, types by name, snippets by snippet name, options by - * name and enum constants in declaration order. + * by id, the features of a target by JSON key, types by name, snippets by snippet name, options and + * enum constants in declaration order. * * @param features every catalogued settings type of the pack's modules, built-in ones included * @param types every class reachable from those settings, each once @@ -22,12 +22,12 @@ public record PackSchema(List features, List types) { types = types.stream().sorted(Comparator.comparing(ObjectType::name)).toList(); } - /** The module fields of one attachment target, by JSON field name. */ + /** The module features of one attachment target, by JSON key. */ public List fields(FeatureAttachment.Target target) { Objects.requireNonNull(target, "target"); return features.stream() .filter(feature -> feature.targets().contains(target)) - .sorted(Comparator.comparing(FeatureSchema::field)) + .sorted(Comparator.comparing(FeatureSchema::key)) .toList(); } diff --git a/src/main/java/com/volmit/stage/BlockStageDefinition.java b/src/main/java/com/volmit/stage/BlockStageDefinition.java index ac19f1bd7..982c2f43b 100644 --- a/src/main/java/com/volmit/stage/BlockStageDefinition.java +++ b/src/main/java/com/volmit/stage/BlockStageDefinition.java @@ -1,5 +1,7 @@ package com.volmit.stage; +import com.volmit.mantle.MantleKey; + import com.volmit.IrisFeature; import java.util.function.Supplier; @@ -13,6 +15,15 @@ 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. + */ + BlockStageDefinition reach(int blocks); + + /** Declares the mantle layers this stage writes; each must be registered by some module. */ + BlockStageDefinition writesMantle(MantleKey... layers); + ConditionalBlockStageDefinition when(Class settingsType); /** Body for a block stage without accumulator. */ diff --git a/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java index 04222aa23..77ff70390 100644 --- a/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java +++ b/src/main/java/com/volmit/stage/ConditionalBlockStageDefinition.java @@ -1,5 +1,7 @@ package com.volmit.stage; +import com.volmit.mantle.MantleKey; + import java.util.function.Supplier; /** A block stage active only where its settings are configured; bodies receive them. */ @@ -10,6 +12,10 @@ public interface ConditionalBlockStageDefinition { ConditionalBlockStageDefinition softBefore(StageRef... stages); + ConditionalBlockStageDefinition reach(int blocks); + + ConditionalBlockStageDefinition writesMantle(MantleKey... layers); + void run(SettingsAction action); void accumulate(Supplier initial, SettingsBlockCollector collector); diff --git a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java index 29bc1c49c..20c22dcf3 100644 --- a/src/main/java/com/volmit/stage/ConditionalStageDefinition.java +++ b/src/main/java/com/volmit/stage/ConditionalStageDefinition.java @@ -1,5 +1,7 @@ package com.volmit.stage; +import com.volmit.mantle.MantleKey; + /** An invocation stage active only where its settings are configured; bodies receive them. */ public interface ConditionalStageDefinition { ConditionalStageDefinition requires(Stage... stages); @@ -8,6 +10,10 @@ public interface ConditionalStageDefinition { ConditionalStageDefinition softBefore(StageRef... stages); + ConditionalStageDefinition reach(int blocks); + + ConditionalStageDefinition writesMantle(MantleKey... layers); + void run(SettingsAction action); void produce(SettingsFunction function); diff --git a/src/main/java/com/volmit/stage/StageDefinition.java b/src/main/java/com/volmit/stage/StageDefinition.java index bf2e317f9..0842a8162 100644 --- a/src/main/java/com/volmit/stage/StageDefinition.java +++ b/src/main/java/com/volmit/stage/StageDefinition.java @@ -1,5 +1,7 @@ package com.volmit.stage; +import com.volmit.mantle.MantleKey; + import com.volmit.IrisFeature; /** Declares one invocation stage. requires(...) is a hard dependency on another module's @@ -14,6 +16,15 @@ 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 + * host prepares that much around every chunk or placement of the pipeline. Leaving it out means 0. + */ + StageDefinition reach(int blocks); + + /** Declares the mantle layers this stage writes; each must be registered by some module. */ + 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}. diff --git a/src/test/java/com/volmit/FeatureContractTest.java b/src/test/java/com/volmit/FeatureContractTest.java index 1e5827e71..6a165edf3 100644 --- a/src/test/java/com/volmit/FeatureContractTest.java +++ b/src/test/java/com/volmit/FeatureContractTest.java @@ -11,7 +11,7 @@ import static org.junit.jupiter.api.Assertions.*; class FeatureContractTest { @Desc("Example settings") @Snippet("fill-settings") - @Feature(id = "example:fill", name = "Fill", field = "fill", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "example:fill", name = "Fill", alias = "fill", targets = FeatureAttachment.Target.BIOME) public static class FillOptions implements IrisFeature { @Desc("Replacement value") @MinNumber(0) @@ -39,7 +39,8 @@ class FeatureContractTest { void descriptorReadsFeatureIdentityAndAttachment() { var descriptor = FeatureDescriptor.of(FillOptions.class); assertEquals(ResourceId.parse("example:fill"), descriptor.id()); - assertEquals("fill", descriptor.attachment().field()); + assertEquals("example:fill", descriptor.key()); + assertEquals(java.util.Optional.of("fill"), descriptor.alias()); assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets()); assertEquals(1, descriptor.options().options().size()); } diff --git a/src/test/java/com/volmit/example/chunk/GrassSettings.java b/src/test/java/com/volmit/example/chunk/GrassSettings.java index b84f542ca..ee01b63ff 100644 --- a/src/test/java/com/volmit/example/chunk/GrassSettings.java +++ b/src/test/java/com/volmit/example/chunk/GrassSettings.java @@ -7,7 +7,7 @@ import com.volmit.config.Desc; import com.volmit.config.Feature; @Desc("Covers the top of every terrain column") -@Feature(id = "example:grass", name = "Grass", field = "grass", targets = FeatureAttachment.Target.BIOME) +@Feature(id = "example:grass", name = "Grass", targets = FeatureAttachment.Target.BIOME) public final class GrassSettings implements IrisFeature { @Desc("Block placed on top of each column") private BlockState block = new BlockState("minecraft:grass_block"); diff --git a/src/test/java/com/volmit/example/placement/MossSettings.java b/src/test/java/com/volmit/example/placement/MossSettings.java index 942142587..679a4d073 100644 --- a/src/test/java/com/volmit/example/placement/MossSettings.java +++ b/src/test/java/com/volmit/example/placement/MossSettings.java @@ -5,7 +5,7 @@ import com.volmit.IrisFeature; import com.volmit.config.Feature; import com.volmit.config.MinNumber; -@Feature(id = "example:moss", name = "Moss", field = "moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "example:moss", name = "Moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) public final class MossSettings implements IrisFeature { @MinNumber(0) private int radius; diff --git a/src/test/java/com/volmit/example/placement/SnowSettings.java b/src/test/java/com/volmit/example/placement/SnowSettings.java index 60035c3ff..4ce439a6d 100644 --- a/src/test/java/com/volmit/example/placement/SnowSettings.java +++ b/src/test/java/com/volmit/example/placement/SnowSettings.java @@ -6,7 +6,7 @@ import com.volmit.config.Feature; import com.volmit.config.MaxNumber; import com.volmit.config.MinNumber; -@Feature(id = "iris:snow", name = "Snow", field = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "iris:snow", name = "Snow", alias = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) public final class SnowSettings implements IrisFeature { @MinNumber(1) @MaxNumber(8) diff --git a/src/test/java/com/volmit/example/placement/StiltSettings.java b/src/test/java/com/volmit/example/placement/StiltSettings.java index 2d0202b32..fff59c7b0 100644 --- a/src/test/java/com/volmit/example/placement/StiltSettings.java +++ b/src/test/java/com/volmit/example/placement/StiltSettings.java @@ -7,7 +7,7 @@ import com.volmit.config.Feature; import com.volmit.config.MinNumber; @Desc("Fills the space below an object down to the ground") -@Feature(id = "iris:stilt", name = "Stilt", field = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) +@Feature(id = "iris:stilt", name = "Stilt", alias = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) public final class StiltSettings implements IrisFeature { @Desc("Maximum blocks filled below each lowest object block") @MinNumber(1) diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 947335a14..247b6343f 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -16,16 +16,16 @@ import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.*; class ModuleRegistryTest { - @Feature(id = "test:core/one", name = "One", field = "shared", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "test:core/one", name = "One", alias = "shared", targets = FeatureAttachment.Target.BIOME) static class One implements IrisFeature {} - @Feature(id = "test:core/two", name = "Two", field = "shared", targets = FeatureAttachment.Target.DIMENSION) + @Feature(id = "test:core/two", name = "Two", alias = "shared", targets = FeatureAttachment.Target.DIMENSION) static class Two implements IrisFeature {} - @Feature(id = "test:core/collision", name = "Collision", field = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME}) + @Feature(id = "test:core/collision", name = "Collision", alias = "shared", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME}) static class Collision implements IrisFeature {} - @Feature(id = "test:core/one", name = "Duplicate", field = "different", targets = FeatureAttachment.Target.REGION) + @Feature(id = "test:core/one", name = "Duplicate", alias = "different", targets = FeatureAttachment.Target.REGION) static class Duplicate implements IrisFeature {} static class MissingAnnotation implements IrisFeature {} - @Feature(id = "test:core/abstract", name = "Abstract", field = "abstract", targets = FeatureAttachment.Target.BIOME) + @Feature(id = "test:core/abstract", name = "Abstract", alias = "abstract", targets = FeatureAttachment.Target.BIOME) abstract static class AbstractFeature implements IrisFeature {} /** Runs {@code registrations} as the register(...) of a built-in module with the given id. */ @@ -40,7 +40,7 @@ class ModuleRegistryTest { @Test void validatesIdsTypesAndFieldsAcrossFeatureKindsWithoutPartialRegistration() { var registry = new ModuleRegistry(); - registry.registerStageSettings(One.class); + registerAs(registry, "test:core", settings -> settings.registerSettings(One.class)); registry.registerStageSettings(One.class); registerAs(registry, "test:core", objects -> { assertThrows(IllegalArgumentException.class, () -> objects.registerObject(Collision.class, ignored -> context -> null)); @@ -56,7 +56,10 @@ class ModuleRegistryTest { @Test void reservesHostFieldsAndRejectsInvalidFeaturesOrFactories() { var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.BIOME, Set.of("shared"))); - assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(One.class)); + assertThrows(IllegalStateException.class, () -> registry.registerStageSettings(One.class), "no module owns it yet"); + registerAs(registry, "test:core", nothing -> {}); + var reserved = assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(One.class)); + assertTrue(reserved.getMessage().startsWith("Alias collision"), reserved.getMessage()); assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(MissingAnnotation.class)); assertThrows(IllegalArgumentException.class, () -> registry.registerStageSettings(AbstractFeature.class)); registerAs(registry, "test:core", objects -> { @@ -160,7 +163,7 @@ class ModuleRegistryTest { registerAs(registry, "test:core", settings -> settings.registerObject(Two.class, ignored -> context -> null)); var collision = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:core", settings -> settings.registerSettings(Collision.class))); - assertTrue(collision.getMessage().startsWith("JSON field collision"), collision.getMessage()); + assertTrue(collision.getMessage().startsWith("Alias collision"), collision.getMessage()); assertTrue(registry.freeze().settings().isEmpty()); } diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java index f53b8c53a..45eb1271c 100644 --- a/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -69,7 +69,7 @@ class PackSchemaTest { import java.util.*; @Desc("Plants flowers and bushes") - @Feature(id = "example:flora", name = "Flora", field = "flora", targets = {Target.REGION, Target.BIOME}) + @Feature(id = "example:flora", name = "Flora", targets = {Target.REGION, Target.BIOME}) public final class FloraSettings implements IrisFeature { @Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64) private int density = 4; @@ -114,7 +114,7 @@ class PackSchemaTest { import com.volmit.config.*; @Desc("A patch of plants") - @Snippet("flora-patch") + @Snippet("example/flora/patch") final class Patch { @MinNumber(1) private int radius = 3; @@ -131,7 +131,7 @@ class PackSchemaTest { import com.volmit.IrisFeature; import com.volmit.config.*; - @Feature(id = "example:flora/wind", name = "Wind", field = "wind", targets = Target.DIMENSION) + @Feature(id = "example:flora/wind", name = "Wind", targets = Target.DIMENSION) public final class WindSettings implements IrisFeature { @Desc("How far plants sway") private double strength = 1.5; @@ -145,8 +145,8 @@ class PackSchemaTest { import com.volmit.IrisFeature; import com.volmit.config.*; - @Snippet("bush") - @Feature(id = "example:flora/bush", name = "Bush", field = "bush", targets = Target.OBJECT_PLACEMENT) + @Snippet("example/flora/bush") + @Feature(id = "example:flora/bush", name = "Bush", targets = Target.OBJECT_PLACEMENT) public final class BushSettings implements IrisFeature { private int height = 2; } @@ -190,13 +190,14 @@ class PackSchemaTest { } @Test - void attachesEveryModuleFieldToItsTargets() { + void attachesEveryModuleFeatureToItsTargetsUnderItsId() { var schema = floraSchema(); - assertEquals(List.of("flora"), names(schema.fields(Target.BIOME), FeatureSchema::field)); - assertEquals(List.of("flora"), names(schema.fields(Target.REGION), FeatureSchema::field)); - assertEquals(List.of("wind"), names(schema.fields(Target.DIMENSION), FeatureSchema::field)); - assertEquals(List.of("bush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field)); + assertEquals(List.of("example:flora"), names(schema.fields(Target.BIOME), FeatureSchema::key)); + assertEquals(List.of("example:flora"), names(schema.fields(Target.REGION), FeatureSchema::key)); + assertEquals(List.of("example:flora/wind"), names(schema.fields(Target.DIMENSION), FeatureSchema::key)); + assertEquals(List.of("example:flora/bush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key)); + assertTrue(schema.features().stream().allMatch(feature -> feature.alias().isEmpty()), "pack modules have no alias"); assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id)); var flora = schema.features().getFirst(); @@ -211,11 +212,11 @@ class PackSchemaTest { } @Test - void describesOptionsInNameOrderWithChecksAndDefaults() { + void describesOptionsInDeclarationOrderWithChecksAndDefaults() { var settings = floraSchema().type("pack.flora.FloraSettings"); - assertEquals(List.of("biomes", "chance", "density", "drops", "enabled", "extra", "flower", "ground", "label", - "palette", "patch", "season", "seasons", "seedOffset", "spread", "weights"), + assertEquals(List.of("density", "chance", "spread", "seedOffset", "enabled", "label", "palette", "ground", "biomes", + "drops", "flower", "season", "seasons", "weights", "patch", "extra"), settings.options().stream().map(SchemaOption::name).toList()); assertEquals(new SchemaOption("density", new IntegerKind(), "Plants per chunk", true, OptionalDouble.of(0), OptionalDouble.of(64), Optional.of(4L)), option(settings, "density")); @@ -273,7 +274,7 @@ class PackSchemaTest { assertEquals(Optional.of(Map.of("bloom", "SUMMER", "radius", 3L)), option(settings, "patch").defaultValue(), "an object default holds the options that have one"); assertEquals("A patch of plants", patch.description()); - assertEquals(List.of("bloom", "child", "radius"), patch.options().stream().map(SchemaOption::name).toList()); + assertEquals(List.of("radius", "bloom", "child"), patch.options().stream().map(SchemaOption::name).toList()); assertEquals(new ObjectKind("pack.flora.Patch"), option(patch, "child").kind()); assertEquals("A smaller patch inside this one", option(patch, "child").description()); assertEquals(OptionalDouble.of(1), option(patch, "radius").minimum()); @@ -283,7 +284,7 @@ class PackSchemaTest { void listsSnippetsObjectGeneratorsAndExplicitlyRegisteredSettings() { var schema = floraSchema(); - assertEquals(List.of("bush", "flora-patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList()); + assertEquals(List.of("example/flora/bush", "example/flora/patch"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList()); assertEquals(List.of("pack.flora.BushSettings", "pack.flora.Patch"), schema.snippets().stream().map(ObjectType::name).toList()); var bush = schema.objectGenerators().getFirst(); @@ -322,7 +323,9 @@ class PackSchemaTest { var schema = schemaOf(pack("empty"), ModuleHost.of(builtIns)); assertEquals(List.of("example:grass", "example:moss", "iris:snow", "iris:stilt"), names(schema.features(), FeatureSchema::id)); - assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::field)); + assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key)); + assertEquals(List.of("", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), feature -> feature.alias().orElse("")), + "built-ins keep their short aliases"); var stilt = schema.fields(Target.OBJECT_PLACEMENT).get(2); assertEquals("Stilts", stilt.module().name()); @@ -349,7 +352,7 @@ class PackSchemaTest { import com.volmit.resource.*; import java.util.*; - @Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", targets = Target.BIOME) public final class FloraSettings implements IrisFeature { %s } @@ -379,7 +382,7 @@ class PackSchemaTest { import com.volmit.config.Feature; import java.util.*; - @Feature(id = "example:flora", name = "Flora", field = "flora", targets = Target.BIOME) + @Feature(id = "example:flora", name = "Flora", targets = Target.BIOME) public final class FloraSettings implements IrisFeature { private Node node = new Node(); private double ratio = Double.NaN; @@ -449,14 +452,90 @@ class PackSchemaTest { } @Test - void snippetNamesAreFolderNamesThatBelongToOneClass() { - assertLoadFails("Snippet name 'Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not a folder name; packs write snippets under" - + " snippet//, so use lowercase letters, digits, '-' and '_'", - "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"Big Patch\") final class Patch {}"); - assertLoadFails("Snippet name 'patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE - + "; studio describes snippet/patch/ by one class, so give each its own name", + void snippetNamesAreFolderPathsThatBelongToOneClass() { + var notAPath = "is not a folder path; packs write snippets under snippet//, so use lowercase letters, digits, '-', '_'" + + " and '.', with '/' between folders"; + assertLoadFails("Snippet name 'example/flora/Big Patch' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath, + "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/Big Patch\") final class Patch {}"); + assertLoadFails("Snippet name 'example/flora/../moss' of pack.flora.Patch of " + FLORA_SOURCE + " " + notAPath, + "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/../moss\") final class Patch {}"); + assertLoadFails("Snippet name 'example/flora/patch' is used by pack.flora.Patch of " + FLORA_SOURCE + " and by pack.flora.Plot of " + FLORA_SOURCE + + "; studio describes snippet/example/flora/patch/ by one class, so give each its own name", "private Patch patch; private Plot plot;", - "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}", - "pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Plot {}"); + "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Patch {}", + "pack.flora.Plot", "package pack.flora; @com.volmit.config.Snippet(\"example/flora/patch\") final class Plot {}"); + } + + @Test + void packSnippetsLiveUnderTheirModulesFolder() { + assertLoadFails("Snippet name 'patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack; snippets of pack" + + " modules start with their module's id as a folder path, such as 'example/flora/patch' (folder snippet/example/flora/patch/)", + "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"patch\") final class Patch {}"); + assertLoadFails("Snippet name 'example/florae/patch' of pack.flora.Patch of " + FLORA_SOURCE + " is not under a module of the pack;" + + " snippets of pack modules start with their module's id as a folder path, such as 'example/flora/patch'" + + " (folder snippet/example/flora/patch/)", + "private Patch patch;", "pack.flora.Patch", "package pack.flora; @com.volmit.config.Snippet(\"example/florae/patch\") final class Patch {}"); + + var pack = pack("module-folder"); + module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.FloraSettings", """ + package pack.flora; + + @com.volmit.config.Snippet("example/flora") + @com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME) + public final class FloraSettings implements com.volmit.IrisFeature {} + """) + .writeInto(pack, "flora.jar"); + assertEquals(List.of("example/flora"), schemaOf(pack, NO_BUILT_INS).snippets().stream() + .map(type -> type.snippet().orElseThrow()).toList(), "the module's own folder is under its path"); + } + + @Test + void packModulesCannotSetAnAlias() { + var pack = pack("alias"); + module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.FloraSettings", """ + package pack.flora; + + @com.volmit.config.Feature(id = "example:flora", name = "Flora", alias = "flora", targets = com.volmit.FeatureAttachment.Target.BIOME) + public final class FloraSettings implements com.volmit.IrisFeature {} + """) + .writeInto(pack, "flora.jar"); + + var failure = assertThrows(IllegalArgumentException.class, () -> LoadedPack.load(pack, NO_BUILT_INS)); + + assertEquals("Settings pack.flora.FloraSettings of module example:flora from modules/flora.jar set alias 'flora'; only modules" + + " that ship with the host may set one, so remove it: packs write these settings under their id \"example:flora\"", + failure.getMessage()); + } + + @Test + void packReferencesFitOnlyPlainText() { + assertLoadFails("Field pack.flora.FloraSettings.home of " + FLORA_SOURCE + " has @Ref(PACK_BIOME) on ResourceId, but packs name" + + " their biomes, regions and objects by path without a namespace, such as desert/dunes; use String", + "@Ref(Reference.PACK_BIOME) private ResourceId home;"); + assertTrue(loadFailure("@Ref(Reference.PACK_OBJECT) private List objects;").getMessage() + .contains("has @Ref(PACK_OBJECT) on ResourceId")); + } + + @Test + void inheritedOptionsComeBeforeTheirSubclasssOwn() { + var pack = pack("inherited"); + module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.Base", "package pack.flora; abstract class Base { private int zeta; private int alpha; }") + .source("pack.flora.FloraSettings", """ + package pack.flora; + + @com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME) + public final class FloraSettings extends Base implements com.volmit.IrisFeature { private int omega; private int beta; } + """) + .writeInto(pack, "flora.jar"); + + var settings = schemaOf(pack, NO_BUILT_INS).type("pack.flora.FloraSettings"); + + assertEquals(List.of("zeta", "alpha", "omega", "beta"), settings.options().stream().map(SchemaOption::name).toList()); } } diff --git a/src/test/java/com/volmit/host/StageGraphTest.java b/src/test/java/com/volmit/host/StageGraphTest.java index db7ad592b..844326ca2 100644 --- a/src/test/java/com/volmit/host/StageGraphTest.java +++ b/src/test/java/com/volmit/host/StageGraphTest.java @@ -1,12 +1,16 @@ package com.volmit.host; import com.volmit.FeatureAttachment; +import com.volmit.FeatureRegistry; import com.volmit.IrisFeature; import com.volmit.IrisModule; import com.volmit.ModuleInfo; import com.volmit.block.BlockState; import com.volmit.config.Feature; import com.volmit.mantle.BlockBox; +import com.volmit.mantle.MantleCodec; +import com.volmit.mantle.MantleKey; +import com.volmit.mantle.MantleLifetime; import com.volmit.object.GeneratedObject; import com.volmit.object.ObjectBlock; import com.volmit.placement.PlacedBlock; @@ -29,14 +33,16 @@ import com.volmit.example.placement.SnowSettings; import org.junit.jupiter.api.Test; import java.util.ArrayList; import java.util.List; +import java.util.Map; import java.util.Optional; +import java.util.Set; import java.util.function.Consumer; import static org.junit.jupiter.api.Assertions.*; class StageGraphTest { private static final BlockState STONE = new BlockState("minecraft:stone"); - @Feature(id = "test:owner/toggle", name = "Toggle", field = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) + @Feature(id = "test:owner/toggle", name = "Toggle", alias = "toggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT) static final class Toggle implements IrisFeature {} static final class Unannotated implements IrisFeature {} @@ -452,4 +458,77 @@ class StageGraphTest { static final class Counter { int count; } + + @Test + 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 paint = Stage.placementBlock("test:reach/paint"); + var reach = module("test:reach", stages -> { + stages.define(carve).reach(24).writesMantle(depth).run(context -> {}); + stages.define(mark).reach(8).writesMantle(depth, marks).run(context -> {}); + 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()); + + 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 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")); + } + + @Test + void reachMustBeValidAndNameRegisteredLayers() { + var depth = new MantleKey<>("test:reach/depth", Integer.class); + var carve = Stage.chunk("test:reach/carve"); + + var negative = assertThrows(IllegalArgumentException.class, () -> resolve(Pipeline.CHUNK, + 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, + 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, + 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())); + 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())); + 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()); + } + + /** {@code module}, also registering {@code layers}. */ + private static IrisModule withMantle(IrisModule module, MantleKey... layers) { + return new IrisModule() { + public ModuleInfo info() { return module.info(); } + public void install(StageGraph graph) { module.install(graph); } + public void register(FeatureRegistry registry) { + for (var layer : layers) registerLayer(registry, layer); + } + }; + } + + private static void registerLayer(FeatureRegistry registry, MantleKey layer) { + registry.registerMantle(layer, MantleLifetime.GENERATION, codec(layer)); + } + + private static MantleCodec codec(MantleKey layer) { + return new MantleCodec<>() { + public int version() { return 0; } + public void write(java.io.DataOutput output, T value) {} + public T read(java.io.DataInput input, int storedVersion) { throw new UnsupportedOperationException(); } + }; + } }