Settings features declare a short JSON key and may declare a root option

@Feature(key) is required: a plain field name, unique per target across all
modules and the host's own JSON fields (ModuleHost.reservingFields, back for
keys). A clash refuses the pack load naming the key, the target and both
claimants. @Feature(root) declares that the JSON under the key is one option's
value, so a settings class has exactly one shape; FeatureSchema carries it.
This commit is contained in:
piexel committed 2026-10-09 23:16:52 +02:00
1 parent 1707bb95f6
commit b82c292dcb
30 files changed
+536 -119

No files matched your search

+8 -4
View File
@@ -21,7 +21,7 @@ types that carry them and lists what the Iris adapter still owes.
| Pack-load validation and diagnostics | host `StageGraphBuilder`, `ResolvedGraph`, `LoadedModules` |
| Reference execution | host `PlacementRunner`, `ChunkRunner`, `MantleRunner` |
| Work across chunks and mantle writes | `Stage.mantle`, `MantleStage`, `MantleStageContext`, `MantleGenerationContext`; chunk stages read the mantle only |
| Annotated settings | `IrisFeature`, `@Feature` (id as JSON key), config annotations, `OptionsMetadata` |
| Annotated settings | `IrisFeature`, `@Feature` (id, short JSON `key`, optional `root`), config annotations, `OptionsMetadata` |
| Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` |
| Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, `FeatureRegistry.registerHeldType`, host `FeatureCatalog.heldTypes()`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` |
| Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` |
@@ -60,8 +60,9 @@ a working no-argument constructor, a bad or repeated snippet name, or a pack cla
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, as the settings object; there are no aliases and no bare-value
shorthand. The description is in a fixed order and holds module entries only.
Packs write settings under the short key the feature declares, as the settings object, or as the value of the
one option its `root` names; there is no second form. A key is unique per target across modules and the host's own
JSON fields. 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
@@ -139,7 +140,10 @@ 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, as a JSON object (or a snippet reference for a `@Snippet` type).
- Pass the host's own JSON fields per target to `ModuleHost.reservingFields(...)`, so a settings key can never
shadow one; a clash refuses the pack load.
- Decode module settings under the declared key, as a JSON object (or a snippet reference for a `@Snippet` type), or,
for a feature with a `root`, as exactly that option's value. Render one shape for each.
- 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) under the key, write `types()` as definitions, a `/snippet/<name>` schema per entry of `snippets()`, and
completion lists per `Reference` from the server registries and the pack's biome, region and
+28 -12
View File
@@ -47,7 +47,7 @@ name, version and optional packages; there is no separate descriptor. A pack kee
The host loads a pack with `LoadedPack.load(packRoot, host)`. `ModuleHost` is the host's fixed
configuration, built once and the same for every pack: built-in modules, exposed host packages,
host type packages and reserved folders. Each of its methods adds to what earlier calls
the JSON fields the host uses itself, host type packages and reserved folders. Each of its methods adds to what earlier calls
configured, and all names are checked when it is built. `LoadedPack` runs `PackModules.load` (below), then
`LoadedModules.load` on the built-ins followed by the pack's modules. If the second step fails it
closes the first before rethrowing, so a failed load leaves no class loader or jar copy behind.
@@ -568,13 +568,29 @@ ids. Two modules with one id never get that far: the load fails naming both ("Du
### JSON keys
Packs write a feature's settings under its feature id at each of its targets, always as the settings
object: `"example:moss": {...}`. A single option is not written bare (`"example:moss": 0.5` and a bare list
are not accepted); the object is the one shape, so a class gaining a second option never changes how packs
read. A `@Snippet` class may be written as a `"snippet/..."` string instead of the object. 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 `:`. There are no short aliases; pack files written for an older
shape are converted by the host's migration tooling, never by the loader.
Packs write a feature's settings under the short key its `@Feature` declares (`key`, required), at each of
its targets: `"moss": {...}`. The feature id (`example:moss`) is the identity everywhere else (stage graph, logs,
lookups by class) and is never a JSON key. A key is a plain field name, not blank and without `:`.
*Why a declared key and not the id.* Pack authors write these keys by hand, and a biome already says `deposits`,
`decorators`; `"iris:deposit": {"generators": [...]}` would make every existing pack unreadable and every file longer.
The id carried an implicit uniqueness guarantee (module ids are unique); a declared key has to be checked instead.
*Uniqueness.* A key is unique per target (dimension, region, biome, object placement), across all loaded modules and
the host's own JSON fields of that target. The host passes its fields with `ModuleHost.reservingFields` (the same
fields it reads itself: a module may not take `name` or `generators` for a biome). `ModuleRegistry` claims `(target,
key)` for every feature it catalogs, settings and object generators alike, including types only a stage names, and a
clash fails the registration, so the pack load, with one message naming the key, the target and both claimants (feature
id and the module's jar, or `Iris` for a host field): `biome key "deposits" is claimed by iris:deposit (host classpath)
and acme:ores (modules/acme-ores.jar)`. Claimants are listed host field first, then built-in features, then pack
features, then by feature id, so the message does not depend on which module registered first.
*One shape.* The JSON under a key is the object of the class's options, unless `@Feature(root = "<option>")` declares
that the JSON is that option's value, as `deposits` is a list (`root = "generators"`). Then the key holds exactly that
value and the object form is not accepted. `root` must name the class's only option. This replaces the one-option
shorthand wave 2 removed (a bare value accepted as an alternative to the object, so every renderer needed an `anyOf`):
the class chooses its one shape once, and the decoder, the studio schema and the pack author see only that shape.
A `@Snippet` class may still be written as a `"snippet/..."` string instead of its object.
`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
@@ -597,15 +613,15 @@ classes. The pack load instead collects what modules declare in their settings c
`LoadedModules.load` builds it right after freezing the catalog (`PackSchemaBuilder`), so a pack
that loads has a complete description and a settings class the host could not render fails the
load. It contains every catalogued settings type of every module, built-in ones too, because the
core engine is modules as well. The host's own JSON fields are not in it; they have no `:`, so they can
never equal a feature id.
core engine is modules as well. The host's own JSON fields are not in it; no key may equal one
(see JSON keys).
### Shape
- 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 key (the feature id), 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 declares, its `root` option when the key holds one
option's value (`rootOption()`), 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,
+25 -12
View File
@@ -377,7 +377,7 @@ completion from it.
```java
@Desc("Plants flowers and bushes")
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME) // packs write "example:flora": {...}
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME) // packs write "flora": {...}
public final class FloraSettings implements IrisFeature {
@Desc("Plants per chunk") @Required @MinNumber(0) @MaxNumber(64)
private int density = 4; // default 4
@@ -414,8 +414,19 @@ public final class FloraSettings implements IrisFeature {
- `@ResourceRef(Keep.class)` says that a `String`, or a list, set or array of them, names a resource of the
module resource kind read into that class, by its key (see Pack resources of a module). The class must back a
kind of the pack; anywhere else, or together with `@Ref`, it fails the load.
- Packs write settings under the feature id, as the settings object: `"example:moss": {"amount": 0.5}`. There
are no aliases and no bare-value form.
- Packs write settings under the short `key` the feature declares, which is required: a plain JSON field name
(not blank, no `:`), the same at every target: `"moss": {"amount": 0.5}`. The id (`example:moss`) stays the
feature's identity in the stage graph, logs and `settings.declared(MossSettings.class)`; packs never write it.
A key is unique per target across all loaded modules and the host's own JSON fields of that target
(`ModuleHost.reservingFields`), so a module cannot take `name` or `generators` for a biome. A clash refuses the pack
load with one message naming the key, the target and both claimants (module id and jar, or `Iris` for a host field):
`biome key "deposits" is claimed by iris:deposit (host classpath) and acme:ores (modules/acme-ores.jar); give one of the settings another key in its @Feature`.
- One shape per key. The JSON under a key is the object of the class's options, `"moss": {"amount": 0.5}`, unless the
class declares `root`, the name of its only option: then the key holds exactly that option's value and an object is
not accepted. With `@Feature(id = "example:flora", key = "flowers", root = "flowers", ...)` over
`private List<String> flowers`, packs write `"flowers": ["poppy", "daisy"]`. `root` must name the class's only option
(nothing could set another), or the load fails. There is no second form: the studio schema renders one shape and a
wrong shape fails with a message naming the key and the file.
- Options keep the order the class declares them in, a superclass's first.
- Built-in settings may hold classes the host describes itself, such as Iris's palettes, which the host
names with `ModuleHost.describingHostTypesIn(...)`. They appear as `HostKind` and pack modules cannot
@@ -462,7 +473,7 @@ Settings describe blocks, noise and ranges with IrisApi's value types, which rea
| `Object` | any JSON value | as decoded: objects as maps, arrays as lists, numbers as `Double` |
```java
@Feature(id = "example:veins", name = "Veins", targets = Target.BIOME)
@Feature(id = "example:veins", name = "Veins", key = "veins", targets = Target.BIOME)
public final class VeinSettings implements IrisFeature {
private List<BlockSpec> palette = List.of(BlockSpec.of("iron_ore"));
private NoiseStyle density = NoiseStyle.of("SIMPLEX").withZoom(16);
@@ -545,6 +556,7 @@ hold them, and packs write them as Iris always read them.
// Once, at startup: the same for every pack.
var host = ModuleHost.of(builtInModules)
.exposing("art.arcane.iris.engine.modules") // besides the API
.reservingFields(hostJsonFields) // JSON fields the host uses per target; no settings key may take one
.describingHostTypesIn("art.arcane.iris.engine.object") // classes the host describes itself
.reservingFolders("biomes", "regions", "objects") // pack folders the host reads itself
.copyingJarsTo(cacheDirectory) // default: java.io.tmpdir
@@ -567,9 +579,9 @@ try (var pack = LoadedPack.load(packRoot, host)) {
```
`ModuleHost` holds what the host passes to every pack load: built-in modules (their `info()` is read
once, here), the host packages pack modules may use, the
packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names and
reserved folders are checked when it is built. `LoadedPack.load`
once, here), the host packages pack modules may use, the JSON fields it uses itself per target, the
packages of the classes it describes itself and the pack folders it reads itself. Each method adds to what earlier calls configured. Package names,
reserved fields and reserved folders are checked when it is built. `LoadedPack.load`
loads the pack's jars, installs them after the built-ins, catalogs settings and registrations,
describes them for studio and resolves the three pipelines. It returns a complete pack or throws with nothing left open. `close()`
releases the pack's class loader and its jar copies. `PackModules` and `LoadedModules`, which it
@@ -646,7 +658,7 @@ validators and vanilla structure hooks (`catalog().resourceKinds()`, `catalog().
`catalog().vanillaStructureHooks()`), describes them and resolves the pipelines. Graph errors
(missing requirement, cycle, a stage outside its module's id, duplicate, cross-pipeline edge) fail
here, at pack load, and so do duplicate module ids and feature ids or mantle keys outside the
module's id. Errors about one module name its jar or "host classpath", and so does a module
module's id, and a settings key two features take at one target or that is a reserved host field. Errors about one module name its jar or "host classpath", and so does a module
that fails to link a class while installing, such as a jar built against an API whose methods have
since changed:
@@ -662,8 +674,9 @@ no JSON. The host renders it and merges it with its own fields:
- `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 JSON key (the id), its targets and the
settings `ObjectType`.
`ModuleInfo`, the JSON key it declares, its `root` option name when the key holds one option's value
(`rootOption()` gives that `SchemaOption`; the host renders that option's schema as the key's value and no
object form), 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, minimum item count and default value.
@@ -681,7 +694,7 @@ no JSON. The host renders it and merges it with its own fields:
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), key=iris:stilt, targets=[OBJECT_PLACEMENT],
FeatureSchema[id=iris:stilt, name=Stilt, role=SETTINGS, module=Stilts (iris:stilt), key=stilt, root=Optional.empty, 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]]]]]
@@ -748,7 +761,7 @@ and the derivation is pinned to values computed from its specification (`StageSt
`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: features under their targets by id,
`PackSchemaTest` loads module jars and checks their description: features under their targets by key, a root option,
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,
@@ -1,13 +1,28 @@
package com.volmit;
import java.util.Objects;
import java.util.Set;
/** Where settings appear in pack JSON: the targets. The JSON key is always the feature id. */
/** Where settings appear in pack JSON: the targets. The JSON key is declared by {@link com.volmit.config.Feature#key}. */
public record FeatureAttachment(Set<Target> targets) {
public enum Target { DIMENSION, REGION, BIOME, OBJECT_PLACEMENT }
private static final char NAMESPACE_SEPARATOR = ':';
public FeatureAttachment {
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: a settings key or a field the host itself uses.
* It is not blank and has no ':', which every feature id has.
*/
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;
}
}
+14 -2
View File
@@ -2,13 +2,25 @@ package com.volmit.config;
import java.lang.annotation.*;
/** 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.
/** Identity and JSON attachment for an IrisFeature configuration class. The {@code id}, such as
* {@code "example:moss"}, is the feature's identity in the stage graph, logs and lookups by class. Packs write
* the settings under the short {@code key}, such as {@code "moss": {...}}, at each of the targets.
*
* <p>The key is a plain JSON field name: not blank, no ':'. It is unique per target across all loaded modules
* and the JSON fields the host itself uses at that target, so it must not be a field of a biome, region or
* dimension; a clash refuses the pack load, naming both claimants.
*
* <p>The JSON under the key is an object of the class's options, unless {@code root} names an option. Then the
* key holds exactly that option's value, such as a list, and an object is not accepted: with
* {@code @Feature(id = "iris:deposit", key = "deposits", root = "generators", ...)} a pack writes
* {@code "deposits": [...]}. The class has no other option then, since nothing could set it.
*/
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface Feature {
String id();
String name();
String key();
String root() default "";
com.volmit.FeatureAttachment.Target[] targets();
}
@@ -6,13 +6,22 @@ import com.volmit.config.Feature;
import com.volmit.config.OptionsMetadata;
import com.volmit.resource.ResourceId;
import java.lang.reflect.Modifier;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
/** Validated settings metadata. It describes configuration, not executable ordering. */
/** Validated settings metadata. It describes configuration, not executable ordering.
*
* @param key the JSON key packs write the settings under at each target; see {@link Feature#key}
* @param root the option whose value the key holds, when the JSON is one option's value instead of an object
* of options; see {@link Feature#root}
*/
public record FeatureDescriptor<F extends IrisFeature>(
ResourceId id,
String name,
String key,
Optional<String> root,
Class<F> type,
FeatureAttachment attachment,
OptionsMetadata options) {
@@ -22,9 +31,12 @@ public record FeatureDescriptor<F extends IrisFeature>(
if (name.isBlank()) {
throw new IllegalArgumentException("Blank feature name");
}
requireKey(id, key);
Objects.requireNonNull(root, "root");
Objects.requireNonNull(type, "type");
Objects.requireNonNull(attachment, "attachment");
Objects.requireNonNull(options, "options");
root.ifPresent(option -> requireOnlyOption(type, option, options));
}
/** Reads the @Feature declaration of a concrete settings class. */
@@ -40,14 +52,29 @@ public record FeatureDescriptor<F extends IrisFeature>(
return new FeatureDescriptor<>(
ResourceId.parse(annotation.id()),
annotation.name(),
annotation.key(),
annotation.root().isEmpty() ? Optional.empty() : Optional.of(annotation.root()),
type,
new FeatureAttachment(Set.of(annotation.targets())),
OptionsMetadata.inspect(type));
}
/** The JSON key packs write these settings under: the feature id. */
public String key() {
return id.toString();
private static void requireKey(ResourceId id, String key) {
try {
FeatureAttachment.requireFieldName(key);
} catch (IllegalArgumentException invalid) {
throw new IllegalArgumentException("Invalid key of feature " + id + ": " + invalid.getMessage()
+ "; a key is a plain JSON field name such as \"deposits\"", invalid);
}
}
private static void requireOnlyOption(Class<?> type, String root, OptionsMetadata options) {
var names = options.options().stream().map(OptionsMetadata.Option::name).toList();
if (names.equals(List.of(root))) {
return;
}
throw new IllegalArgumentException("Feature root '" + root + "' of " + type.getName() + " must name its only option,"
+ " since the JSON under its key is that option's value; its options are " + names);
}
private static void requireConcreteFeature(Class<?> type) {
@@ -1,9 +1,11 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.host.schema.PackSchema;
import com.volmit.stage.Pipeline;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
@@ -23,6 +25,7 @@ public record LoadedModules(
/** Pass the built-in modules together with {@link PackModules#modules()} of the pack.
*
* @param reservedHostFields JSON fields the host itself uses, per attachment target, which no settings key may take
* @param hostTypePackages packages whose classes the host describes itself, each with its
* subpackages; only built-in modules' settings may use them (see {@link ModuleHost#describingHostTypesIn})
* @param reservedFolders pack folders the host reads itself, which no resource kind may read (see
@@ -30,9 +33,10 @@ public record LoadedModules(
*/
public static LoadedModules load(
List<DiscoveredModule> modules,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Collection<String> hostTypePackages,
Collection<String> reservedFolders) {
var registry = new ModuleRegistry(Set.copyOf(reservedFolders));
var registry = new ModuleRegistry(reservedHostFields, Set.copyOf(reservedFolders));
var stages = new StageGraphBuilder();
for (var discovered : modules) {
installModule(discovered, stages, registry);
@@ -37,7 +37,7 @@ public final class LoadedPack implements AutoCloseable {
var packModules = PackModules.load(packRoot, host.exposedHostPackages(), host.jarCopyRoot(), host.logger());
try {
var loaded = LoadedModules.load(host.withPackModules(packModules.modules()),
host.hostTypePackages(), host.reservedFolders());
host.reservedHostFields(), host.hostTypePackages(), host.reservedFolders());
return new LoadedPack(packModules, loaded);
} catch (RuntimeException | Error failure) {
closeAfterFailure(packModules, failure);
+47 -10
View File
@@ -1,34 +1,40 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.IrisModule;
import com.volmit.resource.ResourceKind;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.EnumMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.TreeSet;
/** The host's side of every pack load, the same for all packs: its built-in modules, the host
* packages pack modules may use besides the Iris API, the packages of the classes the host describes itself
* and the pack folders it reads itself (which no resource kind may read). Build it once and pass it to every
* packages pack modules may use besides the Iris API, the JSON fields the host itself uses (which no
* settings key may take), the packages of the classes the host describes itself and the pack folders it
* reads itself (which no resource kind may read). Build it once and pass it to every
* {@link LoadedPack#load(java.nio.file.Path, ModuleHost)}.
*
* <pre>{@code
* var host = ModuleHost.of(builtInModules)
* .exposing("art.arcane.iris.engine.modules")
* .reservingFields(reservedHostFields)
* .reservingFolders("biomes", "regions");
* }</pre>
*
* Every method adds to what earlier calls configured, so a host can build the configuration in steps.
* Built-in modules' {@code info()} is read here, once. Exposed package names, host type packages
* and reserved folders are checked here, so a mistake fails when the host starts rather than at the
* Built-in modules' {@code info()} is read here, once. Exposed package names, host type packages,
* reserved folders and reserved field names are checked here, so a mistake fails when the host starts rather than at the
* first pack load.
*/
public record ModuleHost(
List<DiscoveredModule> builtIns,
Set<String> exposedHostPackages,
Map<FeatureAttachment.Target, Set<String>> reservedHostFields,
Set<String> hostTypePackages,
Set<String> reservedFolders,
Path jarCopyRoot,
@@ -38,12 +44,14 @@ public record ModuleHost(
public ModuleHost {
builtIns = List.copyOf(builtIns);
exposedHostPackages = Set.copyOf(exposedHostPackages);
reservedHostFields = copyOf(reservedHostFields);
hostTypePackages = Set.copyOf(hostTypePackages);
reservedFolders = Set.copyOf(reservedFolders);
Objects.requireNonNull(jarCopyRoot, "jarCopyRoot");
Objects.requireNonNull(logger, "logger");
ExposedPackages.apiAnd(exposedHostPackages);
HostTypes.of(hostTypePackages);
requireFieldNames(reservedHostFields);
requireFolderNames(reservedFolders);
}
@@ -52,7 +60,7 @@ public record ModuleHost(
*/
public static ModuleHost of(List<? extends IrisModule> builtInModules) {
var builtIns = builtInModules.stream().map(DiscoveredModule::builtIn).toList();
return new ModuleHost(builtIns, Set.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
return new ModuleHost(builtIns, Set.of(), Map.of(), Set.of(), Set.of(), systemTemporaryDirectory(),
System.getLogger(PackModules.class.getName()));
}
@@ -60,7 +68,16 @@ public record ModuleHost(
* modules, such as the packages that hold built-in modules' stage constants.
*/
public ModuleHost exposing(String... packages) {
return new ModuleHost(builtIns, union(exposedHostPackages, packages), hostTypePackages, reservedFolders, jarCopyRoot, logger);
return new ModuleHost(builtIns, union(exposedHostPackages, packages), reservedHostFields,
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with {@code fields} also reserved as JSON fields the host itself uses,
* merged per attachment target with the fields reserved before.
*/
public ModuleHost reservingFields(Map<FeatureAttachment.Target, Set<String>> fields) {
return new ModuleHost(builtIns, exposedHostPackages, merge(reservedHostFields, fields),
hostTypePackages, reservedFolders, jarCopyRoot, logger);
}
/** This configuration with the classes in {@code packages}, each with its subpackages, described by
@@ -69,7 +86,7 @@ public record ModuleHost(
* instead of describing their fields. Pack modules' settings cannot use them.
*/
public ModuleHost describingHostTypesIn(String... packages) {
return new ModuleHost(builtIns, exposedHostPackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields,
union(hostTypePackages, packages), reservedFolders, jarCopyRoot, logger);
}
@@ -77,7 +94,7 @@ public record ModuleHost(
* itself, such as its biome and object folders. A module resource kind that reads one fails the pack load.
*/
public ModuleHost reservingFolders(String... folders) {
return new ModuleHost(builtIns, exposedHostPackages, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
union(reservedFolders, folders), jarCopyRoot, logger);
}
@@ -85,7 +102,7 @@ public record ModuleHost(
* cache directory of the host, which is created when missing. The last call wins.
*/
public ModuleHost copyingJarsTo(Path directory) {
return new ModuleHost(builtIns, exposedHostPackages, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, directory, logger);
}
@@ -93,7 +110,7 @@ public record ModuleHost(
* {@code logger}, such as an adapter to the host's own log. The last call wins.
*/
public ModuleHost loggingTo(System.Logger logger) {
return new ModuleHost(builtIns, exposedHostPackages, hostTypePackages,
return new ModuleHost(builtIns, exposedHostPackages, reservedHostFields, hostTypePackages,
reservedFolders, jarCopyRoot, logger);
}
@@ -108,6 +125,17 @@ public record ModuleHost(
return Path.of(System.getProperty(TEMPORARY_DIRECTORY_PROPERTY));
}
private static Map<FeatureAttachment.Target, Set<String>> copyOf(Map<FeatureAttachment.Target, Set<String>> fields) {
var copy = new EnumMap<FeatureAttachment.Target, Set<String>>(FeatureAttachment.Target.class);
fields.forEach((target, names) -> copy.put(target, Set.copyOf(names)));
return Map.copyOf(copy);
}
/** A blank field name, or one with ':' like a feature id, fails here, as it would as a settings key. */
private static void requireFieldNames(Map<FeatureAttachment.Target, Set<String>> fields) {
fields.values().forEach(names -> names.forEach(FeatureAttachment::requireFieldName));
}
private static void requireFolderNames(Set<String> folders) {
for (var folder : folders) {
if (!ResourceKind.isFolderName(folder)) {
@@ -117,6 +145,15 @@ public record ModuleHost(
}
}
private static Map<FeatureAttachment.Target, Set<String>> merge(
Map<FeatureAttachment.Target, Set<String>> existing,
Map<FeatureAttachment.Target, Set<String>> added) {
var merged = new EnumMap<FeatureAttachment.Target, Set<String>>(FeatureAttachment.Target.class);
existing.forEach((target, names) -> merged.put(target, new TreeSet<>(names)));
added.forEach((target, names) -> merged.computeIfAbsent(target, ignored -> new TreeSet<>()).addAll(names));
return merged;
}
private static Set<String> union(Set<String> existing, String... added) {
var names = new TreeSet<>(existing);
names.addAll(Arrays.asList(added));
@@ -1,5 +1,6 @@
package com.volmit.host;
import com.volmit.FeatureAttachment;
import com.volmit.FeatureRegistry;
import com.volmit.IrisFeature;
import com.volmit.IrisModule;
@@ -17,12 +18,15 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Locale;
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, and every feature id is its JSON key. Modules register through
* immutable. IDs are unique across feature kinds. A feature's JSON key (see {@link com.volmit.config.Feature#key})
* is unique per attachment target, and may not equal a host JSON field passed in to reserve it; a clash fails the
* registration naming the key, the target and both claimants. Modules register through
* {@link #register(DiscoveredModule)}; object feature ids, mantle keys, resource kind ids and explicitly registered
* settings ids must be the registering module's id or start with it and '/' ({@link com.volmit.ModuleInfo#ownsId}).
* Resource kinds have unique ids, types and folders, and no kind may read a folder the host reserves for its own
@@ -38,6 +42,7 @@ public final class ModuleRegistry implements FeatureRegistry {
private final Set<ResourceId> featureIds = new HashSet<>();
private final Set<Class<?>> featureTypes = new HashSet<>();
private final Set<Class<?>> registeredByOwner = new HashSet<>();
private final Map<KeyAtTarget, KeyClaimant> keyClaimants = new HashMap<>();
private final Map<ResourceId, ResourceKindRegistration> resourceKinds = new HashMap<>();
private final Map<Class<?>, HeldTypeRegistration> heldTypes = new HashMap<>();
private final List<ValidatorRegistration> validators = new ArrayList<>();
@@ -45,15 +50,20 @@ public final class ModuleRegistry implements FeatureRegistry {
private final List<ServiceRegistration> services = new ArrayList<>();
private final List<VanillaStructureHookRegistration> vanillaStructureHooks = new ArrayList<>();
private final Set<String> reservedFolders;
private final List<DiscoveredModule> registered = new ArrayList<>();
private FeatureCatalog catalog;
private DiscoveredModule registering;
public ModuleRegistry() {
this(Set.of());
this(Map.of(), Set.of());
}
/** @param reservedFolders folders below the pack root that the host reads itself, which no resource kind may read */
public ModuleRegistry(Set<String> reservedFolders) {
/**
* @param reservedHostFields JSON fields the host itself uses, per attachment target, which no settings key may take
* @param reservedFolders folders below the pack root that the host reads itself, which no resource kind may read
*/
public ModuleRegistry(Map<FeatureAttachment.Target, Set<String>> reservedHostFields, Set<String> reservedFolders) {
reservedHostFields.forEach((target, names) -> names.forEach(name -> reserveHostField(target, name)));
this.reservedFolders = Set.copyOf(reservedFolders);
}
@@ -65,6 +75,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 {
@@ -80,7 +91,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);
}
@@ -102,7 +113,7 @@ 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);
}
@@ -182,7 +193,7 @@ public final class ModuleRegistry implements FeatureRegistry {
return;
}
var descriptor = FeatureDescriptor.of(settingsType);
catalogSettings(descriptor);
catalogSettings(descriptor, ownerOf(descriptor));
}
/** Whether the module owning {@code settingsType} registered it through {@link #registerSettings}. */
@@ -198,14 +209,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");
@@ -255,12 +273,42 @@ public final class ModuleRegistry implements FeatureRegistry {
}
}
private void claim(FeatureDescriptor<?> descriptor) {
private void reserveHostField(FeatureAttachment.Target target, String name) {
keyClaimants.put(new KeyAtTarget(target, FeatureAttachment.requireFieldName(name)), KeyClaimant.hostField());
}
private void claim(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
requireNewFeature(descriptor);
requireUnclaimedKeys(descriptor, owner);
featureTypes.add(descriptor.type());
featureIds.add(descriptor.id());
descriptor.attachment().targets().forEach(target ->
keyClaimants.put(new KeyAtTarget(target, descriptor.key()), KeyClaimant.of(descriptor, owner)));
}
private void requireNewFeature(FeatureDescriptor<?> descriptor) {
if (featureTypes.contains(descriptor.type()) || featureIds.contains(descriptor.id())) {
throw new IllegalArgumentException("Duplicate feature: " + descriptor.id());
}
featureTypes.add(descriptor.type());
featureIds.add(descriptor.id());
}
/** One JSON key means one setting at a target: the pack's JSON could not say which one it meant. The message
* names the claimants in a fixed order, so it does not depend on which module registered first.
*/
private void requireUnclaimedKeys(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
for (var target : descriptor.attachment().targets()) {
var earlier = keyClaimants.get(new KeyAtTarget(target, descriptor.key()));
if (earlier == null) continue;
var later = KeyClaimant.of(descriptor, owner);
var first = earlier.compareTo(later) <= 0 ? earlier : later;
var second = first == earlier ? later : earlier;
throw new IllegalArgumentException(targetName(target) + " key \"" + descriptor.key() + "\" is claimed by " + first
+ " and " + second + "; give one of the settings another key in its @Feature");
}
}
private static String targetName(FeatureAttachment.Target target) {
return target.name().toLowerCase(Locale.ROOT).replace('_', ' ');
}
private void checkOpen() {
@@ -268,4 +316,31 @@ public final class ModuleRegistry implements FeatureRegistry {
throw new IllegalStateException("Registration has ended");
}
}
private record KeyAtTarget(FeatureAttachment.Target target, String key) {}
/** Who holds a key: a field of the host's own JSON, a built-in module's feature or a pack module's, in that order. */
private record KeyClaimant(Source source, String feature, String text) implements Comparable<KeyClaimant> {
private enum Source { HOST_FIELD, BUILT_IN, PACK }
static KeyClaimant hostField() {
return new KeyClaimant(Source.HOST_FIELD, "", "Iris");
}
static KeyClaimant of(FeatureDescriptor<?> descriptor, DiscoveredModule owner) {
var source = owner.source() == DiscoveredModule.Source.HOST ? Source.BUILT_IN : Source.PACK;
return new KeyClaimant(source, descriptor.id().toString(), descriptor.id() + " (" + owner.origin() + ")");
}
@Override
public int compareTo(KeyClaimant other) {
var bySource = source.compareTo(other.source);
return bySource != 0 ? bySource : feature.compareTo(other.feature);
}
@Override
public String toString() {
return text;
}
}
}
@@ -85,7 +85,7 @@ final class PackSchemaBuilder {
private record FeatureDraft(Catalogued catalogued, DiscoveredModule owner) {
FeatureSchema complete(Map<String, ObjectType> types) {
var descriptor = catalogued.descriptor();
return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(),
return new FeatureSchema(descriptor.id(), descriptor.name(), catalogued.role(), owner.info(), descriptor.key(), descriptor.root(),
descriptor.attachment().targets(), types.get(descriptor.type().getName()));
}
}
@@ -6,14 +6,16 @@ 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 keys it is written under at each of its targets.
/** A module's settings type and the JSON key 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 key the JSON key the settings are written under, the feature id, the same at every target
* @param key the JSON key the settings are written under, declared by the feature, the same at every target
* @param root the option whose value the key holds, when the JSON is that value and not an object of options
* @param targets where the keys appear, in {@link FeatureAttachment.Target} order
* @param settings the settings class; its description describes the value
*/
@@ -23,6 +25,7 @@ public record FeatureSchema(
FeatureRole role,
ModuleInfo module,
String key,
Optional<String> root,
Set<FeatureAttachment.Target> targets,
ObjectType settings) {
public FeatureSchema {
@@ -31,7 +34,23 @@ public record FeatureSchema(
Objects.requireNonNull(role, "role");
Objects.requireNonNull(module, "module");
Objects.requireNonNull(key, "key");
Objects.requireNonNull(root, "root");
Objects.requireNonNull(settings, "settings");
targets = Collections.unmodifiableSet(EnumSet.copyOf(targets));
root.ifPresent(option -> requireOption(settings, option));
}
/** The option the key holds the value of, when the JSON under the key is one option's value. Then the
* key takes exactly that value, such as a list, and not an object of options.
*/
public Optional<SchemaOption> rootOption() {
return root.map(option -> requireOption(settings, option));
}
private static SchemaOption requireOption(ObjectType settings, String option) {
return settings.options().stream()
.filter(candidate -> candidate.name().equals(option))
.findFirst()
.orElseThrow(() -> new IllegalArgumentException("Root " + option + " is no option of " + settings.name()));
}
}
@@ -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", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "example:fill", name = "Fill", key = "fill", targets = FeatureAttachment.Target.BIOME)
public static class FillOptions implements IrisFeature {
@Desc("Replacement value")
@MinNumber(0)
@@ -39,11 +39,55 @@ class FeatureContractTest {
void descriptorReadsFeatureIdentityAndAttachment() {
var descriptor = FeatureDescriptor.of(FillOptions.class);
assertEquals(ResourceId.parse("example:fill"), descriptor.id());
assertEquals("example:fill", descriptor.key());
assertEquals("fill", descriptor.key());
assertEquals(java.util.Optional.empty(), descriptor.root());
assertEquals(java.util.Set.of(FeatureAttachment.Target.BIOME), descriptor.attachment().targets());
assertEquals(1, descriptor.options().options().size());
}
@Feature(id = "example:blank", name = "Blank", key = " ", targets = FeatureAttachment.Target.BIOME)
static class BlankKey implements IrisFeature {}
@Feature(id = "example:namespaced", name = "Namespaced", key = "example:namespaced", targets = FeatureAttachment.Target.BIOME)
static class NamespacedKey implements IrisFeature {}
@Feature(id = "example:list", name = "List", key = "items", root = "items", targets = FeatureAttachment.Target.BIOME)
static class ListRoot implements IrisFeature {
private java.util.List<String> items = java.util.List.of();
}
@Feature(id = "example:missing", name = "Missing", key = "missing", root = "absent", targets = FeatureAttachment.Target.BIOME)
static class RootNamingNoOption implements IrisFeature {
private java.util.List<String> items = java.util.List.of();
}
@Feature(id = "example:two", name = "Two", key = "two", root = "items", targets = FeatureAttachment.Target.BIOME)
static class RootWithAnotherOption implements IrisFeature {
private java.util.List<String> items = java.util.List.of();
private int unreachable = 1;
}
@Test
void aKeyIsAPlainFieldNameNotAnId() {
var blank = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(BlankKey.class));
assertTrue(blank.getMessage().startsWith("Invalid key of feature example:blank: Field must not be blank"), blank.getMessage());
var namespaced = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(NamespacedKey.class));
assertTrue(namespaced.getMessage().contains("Field example:namespaced contains ':'"), namespaced.getMessage());
}
@Test
void aRootNamesTheOnlyOptionWhoseValueTheKeyHolds() {
var descriptor = FeatureDescriptor.of(ListRoot.class);
assertEquals("items", descriptor.key());
assertEquals(java.util.Optional.of("items"), descriptor.root());
var absent = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(RootNamingNoOption.class));
assertEquals("Feature root 'absent' of " + RootNamingNoOption.class.getName() + " must name its only option, since the JSON"
+ " under its key is that option's value; its options are [items]", absent.getMessage());
var crowded = assertThrows(IllegalArgumentException.class, () -> FeatureDescriptor.of(RootWithAnotherOption.class));
assertTrue(crowded.getMessage().endsWith("its options are [items, unreachable]"), crowded.getMessage());
}
static class InvalidOptions {
@MinNumber(10) @MaxNumber(2) private int value;
}
@@ -48,7 +48,7 @@ class ChunkPipelineTest {
private static final ResourceId PLAINS = ResourceId.parse("pack:biome/plains");
private static final ResourceId SWAMP = ResourceId.parse("pack:biome/swamp");
@Feature(id = "test:levels", name = "Levels", targets = {Target.DIMENSION, Target.BIOME})
@Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Target.DIMENSION, Target.BIOME})
static final class Marker implements IrisFeature {}
private static ChunkRunner runner() {
@@ -135,7 +135,7 @@ class ChunkPipelineTest {
@Test
void mantleStagesWriteBeyondTheirChunkAndChunkStagesReadTheirOwnPart() {
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(new VeinModule())), Map.of(), Set.of(), Set.of());
var vein = new Entry<>(Target.BIOME, PLAINS, new VeinSettings(12, 4));
int reach = loaded.mantle().stages().getFirst().reachBlocks(new DeclaredSettings(vein));
assertEquals(3, reach, "a 12 block vein from the centre column runs 3 blocks into the next chunk");
@@ -202,7 +202,7 @@ class PlacementLifecyclePortTest {
@Test
void loadingThePortCatalogsEveryConditioningSettingsType() {
var loaded = LoadedModules.load(PlacementModules.builtIns(), Set.of(), Set.of());
var loaded = LoadedModules.load(PlacementModules.builtIns(), Map.of(), Set.of(), Set.of());
assertEquals(List.of("example:moss", "iris:snow", "iris:stilt"),
loaded.catalog().settings().stream().map(settings -> settings.id().toString()).toList());
@@ -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", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "example:grass", name = "Grass", key = "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");
@@ -6,7 +6,7 @@ import com.volmit.config.Desc;
import com.volmit.config.Feature;
@Desc("Plans a horizontal ore vein from the centre of each chunk, which may run into the next chunk")
@Feature(id = "example:veins", name = "Veins", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
@Feature(id = "example:veins", name = "Veins", key = "veins", targets = {FeatureAttachment.Target.DIMENSION, FeatureAttachment.Target.BIOME})
public final class VeinSettings implements IrisFeature {
@Desc("Blocks along X, starting at the chunk's centre column")
private int length = 12;
@@ -5,7 +5,7 @@ import com.volmit.IrisFeature;
import com.volmit.config.Feature;
import com.volmit.config.MinNumber;
@Feature(id = "example:moss", name = "Moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "example:moss", name = "Moss", key = "moss", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class MossSettings implements IrisFeature {
@MinNumber(0)
private int radius;
@@ -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", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "iris:snow", name = "Snow", key = "snow", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class SnowSettings implements IrisFeature {
@MinNumber(1)
@MaxNumber(8)
@@ -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", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "iris:stilt", name = "Stilt", key = "stilt", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
public final class StiltSettings implements IrisFeature {
@Desc("Maximum blocks filled below each lowest object block")
@MinNumber(1)
@@ -8,7 +8,7 @@ import com.volmit.example.hosttypes.Palette;
import java.util.List;
/** Built-in settings holding host types, written in pack JSON as a bare list: {@code "layers": [...]}. */
@Feature(id = "iris:layers", name = "Layers", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "iris:layers", name = "Layers", key = "layers", targets = FeatureAttachment.Target.BIOME)
public final class LayersSettings implements IrisFeature {
@Desc("Rock layers from the surface down")
private List<Palette> layers = List.of();
@@ -86,7 +86,7 @@ class WorldStateExampleTest {
@Test
void stagesServicesAndHooksShareTheStateOfTheirWorldAndANewWorldStartsEmpty() {
var pack = LoadedModules.load(List.of(DiscoveredModule.builtIn(new RuinsModule())), Set.of(), Set.of());
var pack = LoadedModules.load(List.of(DiscoveredModule.builtIn(new RuinsModule())), Map.of(), Set.of(), Set.of());
var lifecycles = new LifecycleRunner(pack.catalog());
ObjectsAt objects = pack.catalog().services(ObjectsAt.class).getFirst();
@@ -14,10 +14,10 @@ class ConfiguredSettingsTest {
private static final ResourceId BIOME = ResourceId.parse("pack:biome/plains");
private static final ResourceId OBJECT = ResourceId.parse("pack:object/tree");
@Feature(id = "test:levels", name = "Levels", targets = {Target.DIMENSION, Target.BIOME, Target.OBJECT_PLACEMENT})
@Feature(id = "test:levels", name = "Levels", key = "levels", targets = {Target.DIMENSION, Target.BIOME, Target.OBJECT_PLACEMENT})
static final class Levels implements IrisFeature {}
@Feature(id = "test:other", name = "Other", targets = Target.BIOME)
@Feature(id = "test:other", name = "Other", key = "other", targets = Target.BIOME)
static final class Other implements IrisFeature {}
@Test
@@ -30,7 +30,7 @@ class DiscoveredModuleTest {
var module = new ShiftingIdentity();
var discovered = DiscoveredModule.builtIn(module);
var loaded = LoadedModules.load(List.of(discovered), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(discovered), Map.of(), Set.of(), Set.of());
assertEquals("first:core", discovered.info().id().toString());
assertEquals(List.of("first:core/mark"),
@@ -44,7 +44,7 @@ class LifecycleRunnerTest {
private static LifecycleRunner runner(IrisModule... modules) {
var discovered = Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
return new LifecycleRunner(LoadedModules.load(discovered, Set.of(), Set.of()).catalog());
return new LifecycleRunner(LoadedModules.load(discovered, Map.of(), Set.of(), Set.of()).catalog());
}
@Test
@@ -84,6 +84,8 @@ class LoadedPackTest {
void invalidHostConfigurationFailsWhenBuilt() {
var host = ModuleHost.of(List.of());
assertThrows(IllegalArgumentException.class, () -> host.exposing("org.*"));
assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Target.BIOME, Set.of(" "))));
assertThrows(IllegalArgumentException.class, () -> host.reservingFields(Map.of(Target.BIOME, Set.of("iris:carve"))));
assertEquals(List.of(), host.builtIns());
assertEquals(Set.of(), host.exposedHostPackages());
}
@@ -93,10 +95,13 @@ class LoadedPackTest {
var host = ModuleHost.of(List.of())
.exposing("example.first")
.exposing("example.second")
.reservingFields(Map.of(Target.BIOME, Set.of("carving"), Target.REGION, Set.of("spawns")))
.reservingFields(Map.of(Target.BIOME, Set.of("objects")))
.reservingFolders("biomes")
.reservingFolders("regions");
assertEquals(Set.of("example.first", "example.second"), host.exposedHostPackages());
assertEquals(Map.of(Target.BIOME, Set.of("carving", "objects"), Target.REGION, Set.of("spawns")), host.reservedHostFields());
assertEquals(Set.of("biomes", "regions"), host.reservedFolders());
}
@@ -23,14 +23,22 @@ import java.util.function.Consumer;
import static org.junit.jupiter.api.Assertions.*;
class ModuleRegistryTest {
@Feature(id = "test:core/one", name = "One", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "test:core/one", name = "One", key = "coreOne", targets = FeatureAttachment.Target.BIOME)
static class One implements IrisFeature {}
@Feature(id = "test:core/two", name = "Two", targets = FeatureAttachment.Target.DIMENSION)
@Feature(id = "test:core/two", name = "Two", key = "coreTwo", targets = FeatureAttachment.Target.DIMENSION)
static class Two implements IrisFeature {}
@Feature(id = "test:core/one", name = "Duplicate", targets = FeatureAttachment.Target.REGION)
@Feature(id = "test:core/one", name = "Duplicate", key = "coreOne", targets = FeatureAttachment.Target.REGION)
static class Duplicate implements IrisFeature {}
@Feature(id = "test:ores", name = "Ores", key = "deposits", targets = {FeatureAttachment.Target.BIOME, FeatureAttachment.Target.REGION})
static class Ores implements IrisFeature {}
@Feature(id = "test:minerals", name = "Minerals", key = "deposits", targets = FeatureAttachment.Target.REGION)
static class Minerals implements IrisFeature {}
@Feature(id = "test:veins", name = "Veins", key = "deposits", targets = FeatureAttachment.Target.DIMENSION)
static class Veins implements IrisFeature {}
@Feature(id = "test:named", name = "Named", key = "name", targets = FeatureAttachment.Target.BIOME)
static class Named implements IrisFeature {}
static class MissingAnnotation implements IrisFeature {}
@Feature(id = "test:core/abstract", name = "Abstract", targets = FeatureAttachment.Target.BIOME)
@Feature(id = "test:core/abstract", name = "Abstract", key = "coreAbstract", 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. */
@@ -128,7 +136,7 @@ class ModuleRegistryTest {
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
public void register(FeatureRegistry registry) { registry.registerObject(Two.class, ignored -> context -> null); }
};
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(conditioned)), Map.of(), Set.of(), Set.of());
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
assertEquals(1, loaded.catalog().objects().size());
assertEquals(1, loaded.placement().stages().size());
@@ -141,12 +149,93 @@ class ModuleRegistryTest {
var second = ownerOfOne("Second");
var clash = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(first), DiscoveredModule.builtIn(second)), Set.of(), Set.of()));
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(first), DiscoveredModule.builtIn(second)), Map.of(), Set.of(), Set.of()));
assertTrue(clash.getMessage().startsWith("Duplicate module test:core from "), clash.getMessage());
assertTrue(clash.getMessage().contains("already loaded from "), clash.getMessage());
}
private static IrisModule settingsModule(String id, Class<? extends IrisFeature> settings) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of(id, id, "1"); }
public void install(StageGraph graph) {}
public void register(FeatureRegistry registry) { registry.registerSettings(settings); }
};
}
private static List<DiscoveredModule> discovered(IrisModule... modules) {
return java.util.Arrays.stream(modules).map(DiscoveredModule::builtIn).toList();
}
@Test
void twoModulesTakingOneKeyAtOneTargetRefuseTheLoadNamingKeyTargetAndBothClaimants() {
var ores = settingsModule("test:ores", Ores.class);
var minerals = settingsModule("test:minerals", Minerals.class);
var clash = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(discovered(ores, minerals), Map.of(), Set.of(), Set.of()));
assertEquals("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores (host classpath);"
+ " give one of the settings another key in its @Feature", clash.getMessage());
}
@Test
void theSameKeyAtDifferentTargetsIsNotAClash() {
var loaded = LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), settingsModule("test:veins", Veins.class)),
Map.of(), Set.of(), Set.of());
assertEquals(List.of("test:ores", "test:veins"), loaded.catalog().settings().stream().map(value -> value.id().toString()).sorted().toList());
}
@Test
void aKeyTheHostUsesAsAFieldOfTheTargetIsRefusedNamingIris() {
var reserved = Map.of(FeatureAttachment.Target.BIOME, Set.of("name", "generators"));
var clash = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of()));
assertEquals("biome key \"name\" is claimed by Iris and test:named (host classpath);"
+ " give one of the settings another key in its @Feature", clash.getMessage());
}
@Test
void aHostFieldOfAnotherTargetDoesNotTakeTheKey() {
var reserved = Map.of(FeatureAttachment.Target.REGION, Set.of("name"));
var loaded = LoadedModules.load(discovered(settingsModule("test:named", Named.class)), reserved, Set.of(), Set.of());
assertEquals(1, loaded.catalog().settings().size());
}
@Test
void aClashingObjectGeneratorOrStageSettingsTypeClaimsTheKeyToo() {
var registry = new ModuleRegistry();
registerAs(registry, "test:ores", settings -> settings.registerSettings(Ores.class));
var object = assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:minerals",
objects -> objects.registerObject(Minerals.class, ignored -> context -> null)));
assertTrue(object.getMessage().startsWith("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores"), object.getMessage());
var conditioned = new IrisModule() {
static final PlacementStage<Void> WORK = Stage.placement("test:minerals/work");
public ModuleInfo info() { return ModuleInfo.of("test:minerals", "Minerals", "1"); }
public void install(StageGraph graph) { graph.define(WORK).when(Minerals.class).run((context, minerals) -> {}); }
public void register(FeatureRegistry registry) {}
};
var stage = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(discovered(settingsModule("test:ores", Ores.class), conditioned), Map.of(), Set.of(), Set.of()));
assertTrue(stage.getMessage().startsWith("region key \"deposits\" is claimed by test:minerals (host classpath) and test:ores"), stage.getMessage());
}
@Test
void aRefusedKeyLeavesNothingClaimedByTheFailedFeature() {
var registry = new ModuleRegistry(Map.of(FeatureAttachment.Target.REGION, Set.of("deposits")), Set.of());
assertThrows(IllegalArgumentException.class, () -> registerAs(registry, "test:ores", settings -> settings.registerSettings(Ores.class)));
registerAs(registry, "test:veins", settings -> settings.registerSettings(Veins.class));
assertEquals(List.of("test:veins"), registry.freeze().settings().stream().map(value -> value.id().toString()).toList());
}
private static IrisModule ownerOfOne(String name) {
return new IrisModule() {
public ModuleInfo info() { return ModuleInfo.of("test:core", name, "1"); }
@@ -197,11 +286,11 @@ class ModuleRegistryTest {
public void install(StageGraph graph) { graph.define(WORK).when(One.class).run((context, one) -> {}); }
};
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(owner), DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of());
assertEquals(List.of("test:core/one"), loaded.catalog().settings().stream().map(value -> value.id().toString()).toList());
var unowned = assertThrows(IllegalArgumentException.class,
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Set.of(), Set.of()));
() -> LoadedModules.load(List.of(DiscoveredModule.builtIn(user)), Map.of(), Set.of(), Set.of()));
assertTrue(unowned.getMessage().contains("which none of the modules naming it in when(...) owns"), unowned.getMessage());
}
@@ -210,7 +299,7 @@ class ModuleRegistryTest {
@Test
void resourceKindsHaveOwnedIdsAndOneIdTypeAndFolderEach() {
var registry = new ModuleRegistry(Set.of("biomes"));
var registry = new ModuleRegistry(Map.of(), Set.of("biomes"));
var castles = ResourceKind.of("test:core/castle", "castles", Castle.class);
registerAs(registry, "test:core", kinds -> {
kinds.registerResourceKind(castles);
@@ -43,7 +43,7 @@ class PackModulesTest {
private static LoadedModules loadWithBuiltIns(PackModules packModules) {
var modules = new ArrayList<>(PlacementModules.builtIns());
modules.addAll(packModules.modules());
return LoadedModules.load(modules, Set.of(), Set.of());
return LoadedModules.load(modules, Map.of(), Set.of(), Set.of());
}
/** Versioned entries of a multi-release jar are read like any class, so they must be real class files. */
@@ -154,7 +154,7 @@ class PackModulesTest {
packModules.modules().stream().map(found -> found.info().id().toString()).toList());
assertEquals(List.of(origin("two.jar"), origin("two.jar")),
packModules.modules().stream().map(DiscoveredModule::origin).toList());
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of()));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
}
}
@@ -378,7 +378,7 @@ class PackModulesTest {
try (var packModules = PackModules.load(pack)) {
assertEquals(List.of(new MissingClasses(origin("user.jar"), List.of(OPTIONAL_CLASS))), packModules.missingClasses());
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of()));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
}
}
@@ -512,7 +512,7 @@ class PackModulesTest {
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
var loaded = LoadedModules.load(packModules.modules(), Set.of(), Set.of());
var loaded = LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of());
assertTrue(loaded.placement().stages().stream().anyMatch(stage -> stage.stage().id().toString().equals("beta:core/size")));
var beta = packModules.modules().getLast().module().getClass();
assertEquals(0, beta.getDeclaredField("SHARED").getAnnotations().length,
@@ -529,7 +529,7 @@ class PackModulesTest {
try (var packModules = PackModules.load(pack, List.of(BUILT_IN_PACKAGE))) {
var modules = new ArrayList<>(List.of(DiscoveredModule.builtIn(new CarveModule())));
modules.addAll(packModules.modules());
var order = LoadedModules.load(modules, Set.of(), Set.of()).placement().stages().stream()
var order = LoadedModules.load(modules, Map.of(), Set.of(), Set.of()).placement().stages().stream()
.map(stage -> stage.stage().id().toString()).toList();
assertEquals(List.of("iris:carve/clear", "user:core/carved"), order);
}
@@ -607,7 +607,7 @@ class PackModulesTest {
.writeInto(pack, "once.jar");
try (var packModules = PackModules.load(pack)) {
var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of()));
var loaded = assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
assertEquals("once:core", packModules.modules().getFirst().info().id().toString());
assertEquals(1, loaded.placement().stages().size());
}
@@ -626,7 +626,7 @@ class PackModulesTest {
.writeInto(pack, "beta.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
"Module beta:core from " + origin("beta.jar") + " failed to link or initialize a class while installing",
"java.lang.NoSuchMethodError", "pack.lib.Lib.added()");
}
@@ -638,7 +638,7 @@ class PackModulesTest {
module("pack.two.Duplicate", "dup:core", NO_MEMBERS, NO_STAGES).writeInto(pack, "two.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
"Duplicate module dup:core from " + origin("two.jar") + " (pack.two.Duplicate); already loaded from "
+ origin("one.jar") + " (pack.one.Duplicate)");
}
@@ -655,6 +655,30 @@ class PackModulesTest {
}
}
@Test
void settingsKeyTakenByABuiltInFailsNamingBothModulesAndTheirJars() {
module("pack.Clash", "mine:core", "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(ClashSettings.class); }",
NO_STAGES)
.source("pack.ClashSettings", """
package pack;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.Feature;
@Feature(id = "mine:core/clash", name = "Clash", key = "moss", targets = Target.OBJECT_PLACEMENT)
public final class ClashSettings implements IrisFeature {
}
""")
.writeInto(pack, "clash.jar");
try (var packModules = PackModules.load(pack)) {
assertEquals("object placement key \"moss\" is claimed by example:moss (host classpath) and mine:core/clash ("
+ origin("clash.jar") + "); give one of the settings another key in its @Feature",
failure(() -> loadWithBuiltIns(packModules)));
}
}
@Test
void stageOutsideTheModuleIdFailsNamingTheJar() {
module("pack.Foreign", "mine:core", NO_MEMBERS,
@@ -662,7 +686,7 @@ class PackModulesTest {
.writeInto(pack, "foreign.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
"Stage mine:other/work must start with mine:core/, the id of its defining module mine:core from " + origin("foreign.jar"));
}
}
@@ -674,7 +698,7 @@ class PackModulesTest {
.writeInto(pack, "both.jar");
try (var packModules = PackModules.load(pack)) {
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of())),
assertMentions(failure(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of())),
"Duplicate module dup:core from " + origin("both.jar") + " (pack.Two); already loaded from "
+ origin("both.jar") + " (pack.One)");
}
@@ -687,7 +711,7 @@ class PackModulesTest {
.writeInto(pack, "stilt.jar");
try (var packModules = PackModules.load(pack)) {
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Set.of(), Set.of()));
assertDoesNotThrow(() -> LoadedModules.load(packModules.modules(), Map.of(), Set.of(), Set.of()));
}
}
}
@@ -81,7 +81,7 @@ class PackSchemaTest {
import java.util.*;
@Desc("Plants flowers and bushes")
@Feature(id = "example:flora", name = "Flora", targets = {Target.REGION, Target.BIOME})
@Feature(id = "example:flora", name = "Flora", key = "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;
@@ -143,7 +143,7 @@ class PackSchemaTest {
import com.volmit.IrisFeature;
import com.volmit.config.*;
@Feature(id = "example:flora/wind", name = "Wind", targets = Target.DIMENSION)
@Feature(id = "example:flora/wind", name = "Wind", key = "floraWind", targets = Target.DIMENSION)
public final class WindSettings implements IrisFeature {
@Desc("How far plants sway")
private double strength = 1.5;
@@ -158,7 +158,7 @@ class PackSchemaTest {
import com.volmit.config.*;
@Snippet("example/flora/bush")
@Feature(id = "example:flora/bush", name = "Bush", targets = Target.OBJECT_PLACEMENT)
@Feature(id = "example:flora/bush", name = "Bush", key = "floraBush", targets = Target.OBJECT_PLACEMENT)
public final class BushSettings implements IrisFeature {
private int height = 2;
}
@@ -202,13 +202,13 @@ class PackSchemaTest {
}
@Test
void attachesEveryModuleFeatureToItsTargetsUnderItsId() {
void attachesEveryModuleFeatureToItsTargetsUnderItsDeclaredKey() {
var schema = floraSchema();
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));
assertEquals(List.of("flora"), names(schema.fields(Target.BIOME), FeatureSchema::key));
assertEquals(List.of("flora"), names(schema.fields(Target.REGION), FeatureSchema::key));
assertEquals(List.of("floraWind"), names(schema.fields(Target.DIMENSION), FeatureSchema::key));
assertEquals(List.of("floraBush"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key));
assertEquals(List.of("example:flora", "example:flora/bush", "example:flora/wind"), names(schema.features(), FeatureSchema::id));
var flora = schema.features().getFirst();
@@ -336,7 +336,7 @@ 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("example:moss", "iris:snow", "iris:stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key));
assertEquals(List.of("moss", "snow", "stilt"), names(schema.fields(Target.OBJECT_PLACEMENT), FeatureSchema::key));
var stilt = schema.fields(Target.OBJECT_PLACEMENT).get(2);
assertEquals("Stilts", stilt.module().name());
@@ -419,7 +419,7 @@ class PackSchemaTest {
import com.volmit.resource.*;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME)
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
%s
}
@@ -436,6 +436,39 @@ class PackSchemaTest {
assertEquals(expected, loadFailure(body, otherSources).getMessage());
}
@Test
void settingsWhoseJsonIsOneOptionsValueNameThatOptionAsTheRoot() {
var pack = pack("rooted");
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;
import com.volmit.FeatureAttachment.Target;
import com.volmit.IrisFeature;
import com.volmit.config.*;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", key = "flowers", root = "flowers", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
@MinItems(1) private List<String> flowers = List.of("poppy");
}
""")
.writeInto(pack, "flora.jar");
var flora = schemaOf(pack, NO_BUILT_INS).fields(Target.BIOME).getFirst();
assertEquals("flowers", flora.key());
assertEquals(Optional.of("flowers"), flora.root());
assertEquals(option(flora.settings(), "flowers"), flora.rootOption().orElseThrow());
assertEquals(new ListKind(new TextKind(TextFormat.PLAIN), false), flora.rootOption().orElseThrow().kind());
}
@Test
void settingsWithoutARootHaveNoRootOption() {
assertEquals(Optional.empty(), floraSchema().features().getFirst().rootOption());
}
@Test
void settingsMayHoldTheApisValueTypesWhichAreDescribedLikeSettings() {
var pack = pack("values");
@@ -455,7 +488,7 @@ class PackSchemaTest {
import com.volmit.world.BlockPosition;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME)
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
private List<BlockSpec> palette = List.of(BlockSpec.of("poppy"));
private NoiseStyle style = NoiseStyle.of("SIMPLEX").withZoom(4);
@@ -521,7 +554,7 @@ class PackSchemaTest {
import com.volmit.config.Feature;
import java.util.*;
@Feature(id = "example:flora", name = "Flora", targets = Target.BIOME)
@Feature(id = "example:flora", name = "Flora", key = "flora", targets = Target.BIOME)
public final class FloraSettings implements IrisFeature {
private Node node = new Node();
private double ratio = Double.NaN;
@@ -622,7 +655,7 @@ class PackSchemaTest {
package pack.flora;
@com.volmit.config.Snippet("example/flora")
@com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
@com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
public final class FloraSettings implements com.volmit.IrisFeature {}
""")
.writeInto(pack, "flora.jar");
@@ -648,7 +681,7 @@ class PackSchemaTest {
.source("pack.flora.FloraSettings", """
package pack.flora;
@com.volmit.config.Feature(id = "example:flora", name = "Flora", targets = com.volmit.FeatureAttachment.Target.BIOME)
@com.volmit.config.Feature(id = "example:flora", name = "Flora", key = "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");
@@ -689,7 +722,7 @@ class PackSchemaTest {
import com.volmit.config.*;
import java.util.List;
@Feature(id = "example:castle", name = "Castle", targets = Target.BIOME)
@Feature(id = "example:castle", name = "Castle", key = "castle", targets = Target.BIOME)
public final class CastleSettings implements IrisFeature {
@ResourceRef(Keep.class)
private List<String> keeps = List.of("main");
@@ -45,7 +45,7 @@ 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", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
@Feature(id = "test:owner/toggle", name = "Toggle", key = "ownerToggle", targets = FeatureAttachment.Target.OBJECT_PLACEMENT)
static final class Toggle implements IrisFeature {}
static final class Unannotated implements IrisFeature {}
@@ -478,7 +478,7 @@ class StageGraphTest {
stages.define(plain).run(context -> {});
stages.define(paint).reach(2).run(context -> {});
});
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Set.of(), Set.of());
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(reach, depth, marks))), Map.of(), Set.of(), Set.of());
assertEquals(new StageReach(24, List.of(depth)), loaded.mantle().stages().getFirst().reach());
assertEquals(StageReach.NONE, loaded.mantle().stages().get(2).reach(), "an undeclared reach is 0 with no layers");
@@ -496,7 +496,7 @@ class StageGraphTest {
var loaded = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages -> {
stages.define(carve).reach(settings -> settings.declared(Toggle.class).isEmpty() ? 4 : 40).run(context -> {});
stages.define(mark).reach(2).run(context -> {});
}))), Set.of(), Set.of());
}))), Map.of(), Set.of(), Set.of());
var computed = loaded.mantle().stages().getFirst();
var toggled = new DeclaredSettings(new Entry<>(FeatureAttachment.Target.DIMENSION, ResourceId.parse("pack:dimension/main"), new Toggle()));
@@ -512,7 +512,7 @@ class StageGraphTest {
@Test
void onlyMantleStagesWorkOutTheirReachAndNeverANegativeOne() {
var negative = LoadedModules.load(List.of(DiscoveredModule.builtIn(module("test:reach", stages ->
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Set.of(), Set.of());
stages.define(Stage.mantle("test:reach/carve")).reach(settings -> -1).run(context -> {})))), Map.of(), Set.of(), Set.of());
var failure = assertThrows(IllegalStateException.class, () -> negative.mantle().stages().getFirst().reachBlocks(DeclaredSettings.NONE));
assertEquals("Stage test:reach/carve of module test:reach worked out a negative reach of -1 blocks for this pack", failure.getMessage());
@@ -567,13 +567,13 @@ class StageGraphTest {
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 -> {})))), Set.of(), Set.of()));
module("test:reach", stages -> stages.define(carve).writesMantle(depth).run(context -> {})))), Map.of(), Set.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth, which no module registers;"
+ " its owner registers it with FeatureRegistry.registerMantle", unregistered.getMessage());
var asText = new MantleKey<>("test:reach/depth", String.class);
var mismatch = assertThrows(IllegalArgumentException.class, () -> LoadedModules.load(List.of(DiscoveredModule.builtIn(withMantle(
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Set.of(), Set.of()));
module("test:reach", stages -> stages.define(carve).writesMantle(asText).run(context -> {})), depth))), Map.of(), Set.of(), Set.of()));
assertEquals("Stage test:reach/carve of module test:reach writes mantle layer test:reach/depth as java.lang.String,"
+ " but it is registered as java.lang.Integer", mismatch.getMessage());
}