Batch 6 part 3: structure locating, decoding contract, minor cuts

Finding 45: StructureLocator is the one locating service (startedStructures,
locatableStarts, locateStart, ChunkFilter moved from VanillaStructures).
StartMemo is one opaque non-empty text. VanillaStructureStart.identity is
deleted; the host only stored it. useExpansionHack and legacyAir stay: both
mirror platform structure behaviour any structure module needs.

Finding 46: DESIGN.md documents one decoding contract (fields read by name,
absent or null members keep the initialiser, unknown enum names are errors,
the host never writes null). Value type getters stop null-guarding.
NoiseStyle.cacheSize is deleted. @Desc texts rewritten. multiplier stays on
NoiseStyle: it is also an object placement's warp strength.

Finding 47: LinkedBiomes moves to world and takes the dimension's settings
as PackSettings. Optional packages move from ModuleInfo to the jar manifest
(Iris-Optional-Packages); PackageName moves into the host.
PlacementRequest.id is dropped (nothing read it).
This commit is contained in:
piexel committed 2026-10-24 09:24:12 +02:00
1 parent 6b24e6f150
commit 1bc91df048
30 files changed
+308 -314

No files matched your search

+9 -9
View File
@@ -7,7 +7,7 @@ types that carry them and lists what the Iris adapter still owes.
| Requirement | Contract | | Requirement | Contract |
| --- | --- | | --- | --- |
| Module identity and composition | `IrisModule`, `ModuleInfo` (with optional packages), `StageGraph` | | Module identity and composition | `IrisModule`, `ModuleInfo`, `StageGraph` |
| Loading and unloading a pack | host `LoadedPack`, `ModuleHost` | | Loading and unloading a pack | host `LoadedPack`, `ModuleHost` |
| Module jars in a pack | `META-INF/services/com.volmit.IrisModule`, host `PackModules` (jar copies), `DiscoveredModule`, `MissingClasses` | | Module jars in a pack | `META-INF/services/com.volmit.IrisModule`, host `PackModules` (jar copies), `DiscoveredModule`, `MissingClasses` |
| Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces | | Namespace ownership | module-prefixed stage, feature and mantle ids, `ModuleInfo.ownsStage`/`ownsId`; no reserved namespaces |
@@ -31,13 +31,13 @@ types that carry them and lists what the Iris adapter still owes.
| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`), `BlockTrait`, `BlockPalette`, `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | | Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`), `BlockTrait`, `BlockPalette`, `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) |
| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` |
| Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` | | Values in settings | `BlockSpec`, `PaletteSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `JigsawOverrides`, `Object` as `ValueKind.AnyKind` |
| Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` | | Decisions over and fit of the platform's own structures | service `VanillaStructures` (`rule`, `starts`, `shift`, `reach`, `beforePieces`, `afterPieces`, `setup`), `VanillaStructureRule`, `VanillaStructureContext`, `VanillaStructureStart`, `VanillaStructureStartContext`, `VanillaStructureSetup`, `PlatformStart`, `StartMemo`, `StartReach`, `StructureFit` (`Start`, `Piece`, `ColumnVisitor`), `DecorationStep`, `TerrainAdaptation`, `PieceKind`, `TemplateCells`, `world.BlockAccess`, host `FeatureCatalog.registrations(service)` |
| Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` | | Pack-scoped resolution | `ResourceId` (`ofPackKey`, `ofPlatformKey`), `ContentKey`, `PackResources` (`find(kind, id)`, `require`, `ids(kind)`, `idOf`; kinds `BIOMES`, `REGIONS`, `OBJECTS`, `EXPRESSIONS`, `IMAGE_MAPS`), `PackBiome`, `PackRegion`, `PackExpression`, `PackImageMap` |
| Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@Ref(kind = ...)`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@Ref(kind = ...)`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` |
| Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` |
| Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` | | Per-world module state | `PackWorld` (`state`), `InvocationContext.world()`, host `WorldStates` |
| Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` | | Module lifecycle across loads, hotloads and reloads | `ModuleLifecycle`, `PackContext`, `FeatureRegistry.registerLifecycle`, host `FeatureCatalog.lifecycles()`, `LifecycleRunner` |
| Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`), `SaplingGrowth`, `Loot`, `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) | | Host questions answered by modules | `@Service`, `Providers`, `FeatureRegistry.registerService`, host `FeatureCatalog.services(type)` / `service(type)`; services `ObjectsAt`, `StructureLocator` (`LocateResult`, `startedStructures`, `locatableStarts`, `locateStart`, `ChunkFilter`), `SaplingGrowth`, `Loot`, `BlockDrops`, `EntitySpawns`, `CaveBiomes`, `AmbientEffects`, `VanillaFeatures` (`DecorationStep`); values `ItemDrop`, `EntitySpec`, `ItemRegistry` (`PackResources.items()`) |
| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` | | Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
| Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` | | Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` |
| Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` |
@@ -78,8 +78,8 @@ with `--add-exports <module>/<package>=ALL-UNNAMED`. `sun.misc.Unsafe` from `jdk
supported way for modules to use Unsafe. A class Iris has but hides, a class of an unavailable JDK supported way for modules to use Unsafe. A class Iris has but hides, a class of an unavailable JDK
module or non-exported JDK package, or one missing from an exposed package fails the pack load, module or non-exported JDK package, or one missing from an exposed package fails the pack load,
naming the jar and the classes. A class nobody has (an optional dependency) only warns, unless naming the jar and the classes. A class nobody has (an optional dependency) only warns, unless
its package is one the module declares optional with `ModuleInfo.withOptionalPackages(...)` its package is one the jar's manifest declares optional (`Iris-Optional-Packages`, read by the host's
(`PackageName`). That declaration never excuses a load error. `ModuleJar`). That declaration never excuses a load error.
Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store, Stage bodies and service providers keep no state; what a module keeps for a world lives in that world's state store,
created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a created once per type and world. A world's state lives while the world runs with one pack snapshot: a hotload or a
@@ -271,10 +271,10 @@ running Iris is the pack publisher's responsibility.
`StructureFit`; a start without a memo stays without one. `StructureFit`; a start without a memo stays without one.
- Ask `starts` per chunk, in module id order, refuse a start outside the chunk asked for, keep the first start per - Ask `starts` per chunk, in module id order, refuse a start outside the chunk asked for, keep the first start per
structure, let a start take the chunk from a platform start only when it says so or the structure is `REPLACE`d, structure, let a start take the chunk from a platform start only when it says so or the structure is `REPLACE`d,
apply its jigsaw overrides, keep its memo, record its identity with every start the host publishes, and ask again (same apply its jigsaw overrides, keep its memo, and ask again (same answer) when locating or verifying a start found in
answer) when locating or verifying a start found in the world. the world.
- Send the platform's locate of a structure some provider lists in `startedStructures` to that provider's - Send the platform's locate of a structure some `StructureLocator` provider lists in `startedStructures` to that
`locateStart` (module id order, the first that lists it in `locatableStarts`), convert the start's Y to the platform's, provider's `locateStart` (module id order, the first that lists it in `locatableStarts`), convert the start's Y to the platform's,
check the start the platform made there before reporting it, and search again refusing that chunk when the check fails. check the start the platform made there before reporting it, and search again refusing that chunk when the check fails.
Route the host's own structure commands by `startedStructures` the same way. Route the host's own structure commands by `startedStructures` the same way.
- Ask `setup` per dimension before its worlds build their structure state and when installing data packs; multiply - Ask `setup` per dimension before its worlds build their structure state and when installing data packs; multiply
+53 -27
View File
@@ -43,7 +43,9 @@ flowchart TD
## Module loading ## Module loading
The `IrisModule` implementation is the module's entry point. `info()` returns its id, display The `IrisModule` implementation is the module's entry point. `info()` returns its id, display
name, version and optional packages; there is no separate descriptor. A pack keeps its modules in name and version; there is no separate descriptor. What the jar needs at load (its optional packages) is in the jar's
manifest, because it is the jar's, shared by every module in it, and because a module's identity should not carry
class loading mechanics. A pack keeps its modules in
`<pack>/modules/*.jar`, one or more modules per jar. `<pack>/modules/*.jar`, one or more modules per jar.
The host loads a pack with `LoadedPack.load(packRoot, host)`. `ModuleHost` is the host's fixed The host loads a pack with `LoadedPack.load(packRoot, host)`. `ModuleHost` is the host's fixed
@@ -93,8 +95,8 @@ API):
8. Creates one `URLClassLoader` for all copies, parent = `ExposedHostClassLoader`. 8. Creates one `URLClassLoader` for all copies, parent = `ExposedHostClassLoader`.
9. Loads each entry class, checks that it implements `IrisModule` and comes from its own jar, 9. Loads each entry class, checks that it implements `IrisModule` and comes from its own jar,
instantiates it with the public no-argument constructor and calls `info()`, once. instantiates it with the public no-argument constructor and calls `info()`, once.
10. Drops each jar's missing classes that lie in the optional packages its module declares in 10. Drops each jar's missing classes that lie in the optional packages its manifest declares
`info()`. (`Iris-Optional-Packages`; an invalid name fails the load when the jar is read, in step 1).
11. Logs one INFO summary of the pack's modules, and one WARNING if any missing classes remain. 11. Logs one INFO summary of the pack's modules, and one WARNING if any missing classes remain.
Any failure after step 3 closes the loader, if it exists, and deletes the copies. Any failure after step 3 closes the loader, if it exists, and deletes the copies.
@@ -178,7 +180,7 @@ intended use is the packages that hold built-in modules' stage constants, so tha
the host's class and the same stage constant, which resolution requires: a copy would be a second the host's class and the same stage constant, which resolution requires: a copy would be a second
definition of the id. Names match whole packages: `com.volmit` does not expose `com.volmitx`. A definition of the id. Names match whole packages: `com.volmit` does not expose `com.volmitx`. A
trailing dot is accepted; anything that is not a package name, such as a blank string or a trailing dot is accepted; anything that is not a package name, such as a blank string or a
wildcard, is rejected. `PackageName` holds these rules; module optional packages use them too. wildcard, is rejected. The host's `PackageName` holds these rules; a jar's optional packages use them too.
A module may use any library. A library the host does not expose it ships itself, inside its own jar or as another A module may use any library. A library the host does not expose it ships itself, inside its own jar or as another
jar of the pack, and never borrows the host's hidden copy: those can change with any host update, and two modules would jar of the pack, and never borrows the host's hidden copy: those can change with any host update, and two modules would
@@ -216,7 +218,7 @@ file, so nothing is loaded or initialized:
| in an exposed package, but the host does not have it | load error: the jar was built against a different Iris API or Iris version | | in an exposed package, but the host does not have it | load error: the jar was built against a different Iris API or Iris version |
| in a JDK module the platform loader does not provide, such as `jdk.compiler` | load error: names the JDK module, which is not available to modules | | in a JDK module the platform loader does not provide, such as `jdk.compiler` | load error: names the JDK module, which is not available to modules |
| not exposed, but the host's loader has it (Iris internals, Iris's copy of a library) | load error: modules cannot use Iris's classes; ship the library in the pack or use the API | | not exposed, but the host's loader has it (Iris internals, Iris's copy of a library) | load error: modules cannot use Iris's classes; ship the library in the pack or use the API |
| nowhere | the pack loads, with a warning unless the module declares the package optional | | nowhere | the pack loads, with a warning unless the jar's manifest declares the package optional |
The rows are checked in that order. The export row comes first because access does not depend on The rows are checked in that order. The export row comes first because access does not depend on
which loader finds the class: whoever loads `jdk.internal.misc.Unsafe`, `java.base` decides who may which loader finds the class: whoever loads `jdk.internal.misc.Unsafe`, `java.base` decides who may
@@ -240,24 +242,23 @@ logs one WARNING for the pack, one line per jar with at most five class names
class throws `NoClassDefFoundError` when it runs; the verifier may also need it while linking a class throws `NoClassDefFoundError` when it runs; the verifier may also need it while linking a
class that uses it, which then fails when that class is first used. class that uses it, which then fails when that class is first used.
A module that knows its jar uses such classes declares their packages as optional in `info()`: A jar that knows it uses such classes declares their packages as optional in its manifest, separated by spaces or
commas:
```java ```
public ModuleInfo info() { Iris-Optional-Packages: org.slf4j org.apache.logging.log4j
return ModuleInfo.of("example:moss", "Moss", "1.0.0")
.withOptionalPackages("org.slf4j", "org.apache.logging.log4j");
}
``` ```
Each package covers its subpackages. Missing classes of that jar inside them are dropped from the Each package covers its subpackages. Missing classes of that jar inside them are dropped from the
warning and from `missingClasses()`; the rest still warn, and other jars of the pack are not warning and from `missingClasses()`; the rest still warn, and other jars of the pack are not
affected. A jar with several modules is excused by the optional packages of all of them. `ModuleInfo.of(id, name, version)` declares none. Invalid names fail in `info()`, which the affected. A jar with several modules declares once for all of them. Invalid names fail the load
load reports as a broken entry point of the jar. when the jar is read, naming the jar.
The declaration lives in the entry point because all module metadata does. That fixes its timing: The declaration lives in the manifest because it is about the jar, not about any one module: a jar shades a
`info()` exists only once the entry class is defined, after the reference check. This is safe library for all of its modules, and the host already applied the declarations per jar. It used to be
because the declaration only removes warnings. Every load error is decided in step 7, without it, `ModuleInfo.withOptionalPackages`, which put class loading mechanics into a module's identity and could only be
so a declared package can never turn a hidden Iris class, an unavailable or non-exported JDK class read once the entry classes were defined. The declaration only removes warnings. Every load error is decided in
step 7, without it, so a declared package can never turn a hidden Iris class, an unavailable or non-exported JDK class
or a class missing from an exposed package into a pass. `missingClasses()` drops the excused classes instead or a class missing from an exposed package into a pass. `missingClasses()` drops the excused classes instead
of flagging them: it then says exactly what the warning says, and a class the author declared of flagging them: it then says exactly what the warning says, and a class the author declared
expected is not a problem to show in studio. expected is not a problem to show in studio.
@@ -850,6 +851,25 @@ settings, and pack JSON keeps its shape: the field names and the no-argument def
included (an omitted `Range` bound is 16 or 32). They are values: accessors return unmodifiable views, included (an omitted `Range` bound is 16 or 32). They are values: accessors return unmodifiable views,
withers return copies, and equality is by value, so the host can cache by them. withers return copies, and equality is by value, so the host can cache by them.
### Decoding contract
Every settings class, value type and pack resource kind is read the same way, by any host:
- The host creates the instance with the no-argument constructor and reads each JSON member into the field of the
same name. It calls no setter and no other constructor.
- A member the JSON leaves out keeps the field's initialiser. A member written as `null` counts as left out.
- The host never writes `null` into a field. An enum name the enum does not know is an error that lists the known
names; it does not become `null` or the default.
- So a getter returns its field as it is. Only a field whose initialiser is `null` can be absent
(`NoiseStyle.fracture`, `BlockSpec.backup`, the `JigsawOverrides` numbers), and its getter says so with `Optional`.
Constructors and withers in code reject `null` the same way.
- No performance knobs. `NoiseStyle` has no cache size: how a host caches noise is its own business.
`multiplier` stays on every style: it is how far a style moves coordinates, read both when the style is another's
fracture and when it is an object placement's warp, so it is not the fracture's alone.
Iris enforces this in its module settings decoder; a class that guards its getters against `null` is guarding against
a host bug.
| Iris class | API | Behaviour behind it | | Iris class | API | Behaviour behind it |
| --- | --- | --- | | --- | --- | --- |
| `IrisBlockData` | `com.volmit.block.BlockSpec` | `BlockRegistry.resolve(BlockSpec)`, `blockEntity(BlockSpec)` | | `IrisBlockData` | `com.volmit.block.BlockSpec` | `BlockRegistry.resolve(BlockSpec)`, `blockEntity(BlockSpec)` |
@@ -948,8 +968,8 @@ states them through the `VanillaStructures` service; the host applies them on ev
region and biome it can reach), the same view reaches are worked out from. region and biome it can reach), the same view reaches are worked out from.
- **Placing starts: `starts(chunkX, chunkZ, context)`.** Asked per chunk because the platform generates per chunk. A - **Placing starts: `starts(chunkX, chunkZ, context)`.** Asked per chunk because the platform generates per chunk. A
start carries everything the platform needs and nothing it can work out: structure, chunk, height above the start carries everything the platform needs and nothing it can work out: structure, chunk, height above the
bottom, surface or underground, whether it takes the chunk from a platform start, jigsaw overrides, a memo, and an bottom, surface or underground, whether it takes the chunk from a platform start, jigsaw overrides and a memo. No
identity the host persists with the start so a start found in a saved world can be traced to its placement. Across identity of the placement: the host only stored it and never read it back, so it was dropped in batch 6. Across
modules the host keeps the first start per structure and chunk in module id order. The context is the `PackWorld` modules the host keeps the first start per structure and chunk in module id order. The context is the `PackWorld`
plus a `TerrainSampler`. plus a `TerrainSampler`.
- **No fit values in the API.** How a start meets the terrain (Iris's SOURCE, PRESERVE, VACUUM, ENCASE, BORE, - **No fit values in the API.** How a start meets the terrain (Iris's SOURCE, PRESERVE, VACUUM, ENCASE, BORE,
@@ -969,11 +989,14 @@ states them through the `VanillaStructures` service; the host applies them on ev
go through `BlockAccess`: `get`, `column` and `set` work on plain states, traits and tags answer the platform's own go through `BlockAccess`: `get`, `column` and `set` work on plain states, traits and tags answer the platform's own
questions, so a fit scans millions of cells without a value per block. `state(type, factory)` holds a module's questions, so a fit scans millions of cells without a value per block. `state(type, factory)` holds a module's
object for the chunk from `beforePieces` to the last `afterPieces`, the only place a fit keeps state. object for the chunk from `beforePieces` to the last `afterPieces`, the only place a fit keeps state.
- **A memo instead of a persisted fit.** A start a module places carries a `StartMemo` (two texts, the module's to - **A memo instead of a persisted fit.** A start a module places carries a `StartMemo` (one opaque, non-empty text,
fill). The host stores it with the start's ownership record and hands it back in `reach` and in every chunk's the module's to fill and parse). The host stores it with the start's ownership record and hands it back in `reach`
`StructureFit`, so a start fits the same in every chunk it reaches, also after a restart or a pack change. Iris's and in every chunk's `StructureFit`, so a start fits the same in every chunk it reaches, also after a restart or a
structure module writes its terrain and stilts JSON there, in the two places records always held them, so records pack change. Iris's structure module writes one JSON object of its terrain and stilts there; how many parts a memo
written before read the same. has is the module's business, so the API holds one text.
- **One locating service.** `StructureLocator` finds both the structures a module places itself (`locate`) and the
platform structures it starts (`startedStructures`, `locatableStarts`, `locateStart`); `VanillaStructures` only
decides and fits. A second structure module implements one service to be found by `/locate`.
- **Setup before a world exists: `setup(context)`.** Structure set frequencies and protecting the platform's - **Setup before a world exists: `setup(context)`.** Structure set frequencies and protecting the platform's
definitions from installed data packs are decided when the platform builds its structure state or the host definitions from installed data packs are decided when the platform builds its structure state or the host
installs data packs, before any world of the dimension runs. Frequencies multiply across modules; protection holds installs data packs, before any world of the dimension runs. Frequencies multiply across modules; protection holds
@@ -1001,8 +1024,8 @@ the resources it serves itself.
`EXPRESSIONS`, `IMAGE_MAPS`), so one call shape serves both, and no second key type (it used to be `ResourceKey`, a `EXPRESSIONS`, `IMAGE_MAPS`), so one call shape serves both, and no second key type (it used to be `ResourceKey`, a
pair of id and class). One class still backs at most one kind, because `@Ref(kind = ...)` names the kind by its class. The class must be concrete; like settings it pair of id and class). One class still backs at most one kind, because `@Ref(kind = ...)` names the kind by its class. The class must be concrete; like settings it
needs a no-argument constructor, checked when the pack's description is built. needs a no-argument constructor, checked when the pack's description is built.
- **Reading.** The host creates the instance with that constructor and reads the JSON into it, exactly as it - **Reading.** The host creates the instance with that constructor and reads the JSON into it under the
decodes settings, so a missing field keeps its default and studio's defaults are what packs get. decoding contract, exactly as it decodes settings, so a missing field keeps its default and studio's defaults are what packs get.
- **Lifetime.** A resource is read once per pack snapshot and every caller gets the same instance, so resources - **Lifetime.** A resource is read once per pack snapshot and every caller gets the same instance, so resources
are values: nobody may change one. A reload is a new snapshot (`snapshotId()` changes) that reads the files are values: nobody may change one. A reload is a new snapshot (`snapshotId()` changes) that reads the files
again. A file that fails to read is an error from `find`, not an absent resource. again. A file that fails to read is an error from `find`, not an absent resource.
@@ -1172,7 +1195,10 @@ from a sapling, which drops a block has. A module answers such questions through
floating island. Settings say so by implementing `LinkedBiomes` (`treeBiomes`, which join a region's tree and so its terrain floating island. Settings say so by implementing `LinkedBiomes` (`treeBiomes`, which join a region's tree and so its terrain
generators, and `usedBiomes`, which the dimension reaches without joining), instead of the host reading any module's generators, and `usedBiomes`, which the dimension reaches without joining), instead of the host reading any module's
settings class. `usedBiomes` receives the dimension's own settings, since a name may stand for something the dimension settings class. `usedBiomes` receives the dimension's own settings, since a name may stand for something the dimension
declares (a floating island's `carving` is a band id or a biome key). declares (a floating island's `carving` is a band id or a biome key). They come as a `PackSettings` holding only the
dimension's level, the API's lookup by type into a `SettingsStack`, not a raw collection of features; its regions
and biomes are left out because they are what the host is working out. `LinkedBiomes` is a layout concern, so it
lives in `world`.
- **Why not per-world provider instances.** A factory per world (`world -> provider`) would let a provider hold its - **Why not per-world provider instances.** A factory per world (`world -> provider`) would let a provider hold its
world, but every service method would then hide which world it answers for, and a host could not ask a pack-level world, but every service method would then hide which world it answers for, and a host could not ask a pack-level
question without a world. Passing the world keeps providers stateless like stage bodies and puts all per-world data question without a world. Passing the world keeps providers stateless like stage bodies and puts all per-world data
+30 -24
View File
@@ -416,8 +416,7 @@ modules/moss.jar
com/example/moss/MossSettings.class com/example/moss/MossSettings.class
``` ```
`info()` gives the module id, display name and version, and optionally the packages whose classes `info()` gives the module id, display name and version. The host reads it once, when it finds the module.
the module expects may be missing (see below). The host reads it once, when it finds the module.
Every stage id of the module starts with the module id and `/`; the name is what logs show. Names Every stage id of the module starts with the module id and `/`; the name is what logs show. Names
and versions must fit on one line: line breaks and other control characters are rejected. and versions must fit on one line: line breaks and other control characters are rejected.
@@ -454,17 +453,18 @@ to Iris: module classes, and the libraries they shade, must not use them.
Libraries often reference optional integrations they only use when present. A class that neither Libraries often reference optional integrations they only use when present. A class that neither
the pack, Iris nor the JDK has therefore does not fail the load: the pack loads, logs one warning the pack, Iris nor the JDK has therefore does not fail the load: the pack loads, logs one warning
listing such classes per jar, and code that needs one throws `NoClassDefFoundError` when it runs. listing such classes per jar, and code that needs one throws `NoClassDefFoundError` when it runs.
A module that expects such classes to be absent declares their packages in `info()`, and the ### Optional packages
warning leaves them out:
```java A jar that expects such classes to be absent declares their packages, with their subpackages, in its manifest, and
public ModuleInfo info() { the warning leaves them out. Which classes a jar may miss is the jar's business, not a module's identity:
return ModuleInfo.of("example:moss", "Moss", "1.0.0")
.withOptionalPackages("org.slf4j", "org.apache.logging.log4j"); // with subpackages ```kotlin
tasks.jar {
manifest { attributes("Iris-Optional-Packages" to "org.slf4j org.apache.logging.log4j") } // spaces or commas
} }
``` ```
A declaration covers only that module's own jar. It never excuses a load error: a class Iris hides, A declaration covers only that jar, all of its modules. It never excuses a load error: a class Iris hides,
a JDK class modules cannot see or use, or a class missing from an exposed package fails even inside a JDK class modules cannot see or use, or a class missing from an exposed package fails even inside
a declared package. Package names follow the rules of exposed packages (whole packages, trailing dot a declared package. Package names follow the rules of exposed packages (whole packages, trailing dot
accepted, wildcards rejected). accepted, wildcards rejected).
@@ -539,11 +539,12 @@ public final class FloraSettings implements IrisFeature {
(nothing could set another), or the load fails. There is no second form: the studio schema renders one shape and a (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. 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. - Options keep the order the class declares them in, a superclass's first.
- Settings that bring other pack biomes into the pack's layout implement `LinkedBiomes`: `treeBiomes()` are biomes that join the - Settings that bring other pack biomes into the pack's layout implement `world.LinkedBiomes`: `treeBiomes()` are biomes that join the
biome tree of every region the owner is in (the host registers their terrain generators with the region, as it does an biome tree of every region the owner is in (the host registers their terrain generators with the region, as it does an
owner's children), and `usedBiomes(dimension)` are biomes the settings use besides, which the dimension reaches so their owner's children), and `usedBiomes(dimension)` are biomes the settings use besides, which the dimension reaches so their
objects, decorators and settings take part in generation. `dimension` is the settings the owner's dimension declares, for objects, decorators and settings take part in generation. `dimension` is a `PackSettings` of what the owner's dimension
settings that name something the dimension declares, such as a band of its caves. The host asks every dimension and biome declares itself (`dimension.declared(CarvingSettings.class).dimension()`), for settings that name something the
dimension declares, such as a band of its caves. The host asks every dimension and biome
it reaches and ignores blank keys and keys naming no biome. it reaches and ignores blank keys and keys naming no biome.
- Built-in settings may hold classes the host describes itself, such as Iris's palettes, which the host - 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 names with `ModuleHost.describingHostTypesIn(...)`. They appear as `HostKind` and pack modules cannot
@@ -595,7 +596,7 @@ Settings describe blocks, noise and ranges with IrisApi's value types, which rea
| --- | --- | --- | | --- | --- | --- |
| `BlockSpec` | `{"block": "iron_ore", "data": {"waterlogged": true}, "backup": {...}, "tileData": {...}}` | `resources.blocks().resolve(spec)` gives the `BlockState`, `blockEntity(spec)` its block entity | | `BlockSpec` | `{"block": "iron_ore", "data": {"waterlogged": true}, "backup": {...}, "tileData": {...}}` | `resources.blocks().resolve(spec)` gives the `BlockState`, `blockEntity(spec)` its block entity |
| `PaletteSpec` | `{"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}` or `"snippet/palette/<name>"` | `resources.blocks().palette(spec, seed)` gives a `PaletteSampler`: `at(x, y, z)` is the block there | | `PaletteSpec` | `{"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}` or `"snippet/palette/<name>"` | `resources.blocks().palette(spec, seed)` gives a `PaletteSampler`: `at(x, y, z)` is the block there |
| `NoiseStyle` | `{"style": "SIMPLEX", "zoom": 4, "fracture": {...}}` or `"snippet/style/<name>"` | `resources.noise().sampler(style, seed)` gives a `NoiseSampler` | | `NoiseStyle` | `{"style": "SIMPLEX", "zoom": 4, "fracture": {"style": "PERLIN", "multiplier": 2}}` or `"snippet/style/<name>"` | `resources.noise().sampler(style, seed)` gives a `NoiseSampler` |
| `StyledRange` | `{"min": 4, "max": 12, "style": {...}}` | `range.at(resources.noise(), seed, x, z)` | | `StyledRange` | `{"min": 4, "max": 12, "style": {...}}` | `range.at(resources.noise(), seed, x, z)` |
| `Range` | `{"min": 0, "max": 15}` | `contains(value)`, `pick(random)` | | `Range` | `{"min": 0, "max": 15}` | `contains(value)`, `pick(random)` |
| `BlockPosition` | `{"x": 1, "y": 2, "z": 3}` | its components | | `BlockPosition` | `{"x": 1, "y": 2, "z": 3}` | its components |
@@ -623,6 +624,10 @@ by noise (each block counts as often as its weight, the style's noise at x, y, z
one block is that block everywhere, and one without a block to pick (an empty list, or only weights of zero) is an one block is that block everywhere, and one without a block to pick (an empty list, or only weights of zero) is an
`IllegalArgumentException` when the sampler is asked for. Seed it like noise. `IllegalArgumentException` when the sampler is asked for. Seed it like noise.
Every value type and settings class is decoded the same way (DESIGN.md, "Decoding contract"): an option left out or
written as `null` keeps its field's initialiser, and an enum name the enum does not know is an error. A getter
therefore never needs a `null` check; only an option whose initialiser is `null` is optional.
`NoiseSampler.signed(...)` is `sample * 2 - 1`, which a host may answer from a per-thread memo of the coordinates it was just asked (read it `NoiseSampler.signed(...)` is `sample * 2 - 1`, which a host may answer from a per-thread memo of the coordinates it was just asked (read it
where one field is sampled at the same points again and again, as a carver does). `scaled(factor)` is the same noise with the coordinates where one field is sampled at the same points again and again, as a carver does). `scaled(factor)` is the same noise with the coordinates
multiplied by `factor`, folded into the host's generator, not a multiplication in front of it. multiplied by `factor`, folded into the host's generator, not a multiplication in front of it.
@@ -665,7 +670,7 @@ Every method has a default that changes nothing, so a provider implements only w
- `starts(chunkX, chunkZ, context)`: the platform structures the module starts in that chunk itself. A - `starts(chunkX, chunkZ, context)`: the platform structures the module starts in that chunk itself. A
`VanillaStructureStart` names the structure, its height above the bottom (`underground()` puts the structure's `VanillaStructureStart` names the structure, its height above the bottom (`underground()` puts the structure's
lowest block there; otherwise it sits on the surface), whether it takes the chunk from a platform start of the same lowest block there; otherwise it sits on the surface), whether it takes the chunk from a platform start of the same
structure, a stable `identity` the host records with it, `JigsawOverrides` for jigsaw structures and a `StartMemo`. structure, `JigsawOverrides` for jigsaw structures and a `StartMemo`.
The context gives the world (`PackWorld`) and a `TerrainSampler` over the chunk. Answer from the world and chunk The context gives the world (`PackWorld`) and a `TerrainSampler` over the chunk. Answer from the world and chunk
only: the host asks again when it locates structures and when it checks starts it finds in the world. only: the host asks again when it locates structures and when it checks starts it finds in the world.
- `shift(start, context)`: how many blocks one of the platform's own starts moves up or down before the host - `shift(start, context)`: how many blocks one of the platform's own starts moves up or down before the host
@@ -685,11 +690,12 @@ Every method has a default that changes nothing, so a provider implements only w
- `setup(context)`: before any world of the dimension exists, how often each structure set starts (`withFrequency`, - `setup(context)`: before any world of the dimension exists, how often each structure set starts (`withFrequency`,
multipliers of several modules multiply) and whether the data packs the host installs must leave the platform's own multipliers of several modules multiply) and whether the data packs the host installs must leave the platform's own
structure definitions alone (`protectingVanillaDefinitions`, for every pack once any dimension asks for it). structure definitions alone (`protectingVanillaDefinitions`, for every pack once any dimension asks for it).
- `startedStructures(world)`, `locatableStarts(world)` and `locateStart(world, structure, fromX, fromZ, maxRings,
accepts)`: the platform structures the module starts itself, the ones of them it can find, and the nearest start of one, Finding the starts a module makes is `StructureLocator`'s, the one locating service: `startedStructures(world)`,
searched ring by ring through the module's own placement grids. The host sends the platform's `/locate` and its own `locatableStarts(world)` and `locateStart(world, structure, fromX, fromZ, maxRings, accepts)` give the platform
structure commands for those structures here, then checks the start it got in the world; `accepts` lets it skip chunks structures the module starts itself, the ones of them it can find, and the nearest start of one, searched ring by ring
it already refused. through the module's own placement grids. The host sends the platform's `/locate` and its own structure commands for
those structures there, then checks the start it got in the world; `accepts` lets it skip chunks it already refused.
```java ```java
@Override @Override
@@ -697,12 +703,12 @@ public List<VanillaStructureStart> starts(int chunkX, int chunkZ, VanillaStructu
if (!castleChunk(context.world().seed(), chunkX, chunkZ)) return List.of(); if (!castleChunk(context.world().seed(), chunkX, chunkZ)) return List.of();
int surface = context.terrain().surfaceHeight((chunkX << 4) + 8, (chunkZ << 4) + 8); int surface = context.terrain().surfaceHeight((chunkX << 4) + 8, (chunkZ << 4) + 8);
return List.of(VanillaStructureStart.at(ResourceId.parse("minecraft:village_plains"), chunkX, chunkZ, surface) return List.of(VanillaStructureStart.at(ResourceId.parse("minecraft:village_plains"), chunkX, chunkZ, surface)
.withMemo(new StartMemo("{\"mode\":\"VACUUM\"}", ""))); .withMemo(new StartMemo("{\"terrain\":\"VACUUM\"}")));
} }
``` ```
How a start meets the terrain is the module's: the API has no fit values. A `StartMemo` is two texts the module gives How a start meets the terrain is the module's: the API has no fit values. A `StartMemo` is one opaque, non-empty
a start it places; the host persists them with the start and hands them back in `reach` and in every chunk's text the module gives a start it places; the host persists it with the start and hands it back in `reach` and in every chunk's
`StructureFit`, so every chunk the start reaches fits it the same way, also after a restart. `JigsawOverrides` is a `StructureFit`, so every chunk the start reaches fits it the same way, also after a restart. `JigsawOverrides` is a
value type like `PaletteSpec`: settings may hold it, and packs write it as Iris always read it. value type like `PaletteSpec`: settings may hold it, and packs write it as Iris always read it.
@@ -773,7 +779,7 @@ also in another jar of the pack (both jars are named), a class that uses a class
a class of a JDK module modules cannot see, a class of a JDK package not exported to modules, a a class of a JDK module modules cannot see, a class of a JDK package not exported to modules, a
class missing from an exposed package, or an entry class missing from an exposed package, or an entry
class that cannot be loaded, is not an `IrisModule`, is not in that jar, fails to construct or whose class that cannot be loaded, is not an `IrisModule`, is not in that jar, fails to construct or whose
`info()` fails (an invalid optional package, for example). All checks before the last run before any `info()` fails, or a manifest that declares an invalid optional package. All checks before the last run before any
class of the pack is defined. The last error below lists every kind of unusable class the jar class of the pack is defined. The last error below lists every kind of unusable class the jar
uses, one group per kind: uses, one group per kind:
@@ -798,7 +804,7 @@ The jar was built against a different Iris API or Iris version.
``` ```
Classes that nobody has only produce a warning, also available as `pack.missingClasses()`. Classes Classes that nobody has only produce a warning, also available as `pack.missingClasses()`. Classes
in the optional packages a jar's module declares appear in neither: in the optional packages a jar's manifest declares appear in neither:
``` ```
Pack overworld: module jars use classes that neither the pack, Iris nor the JDK has, usually optional dependencies of a bundled library. The jars load, but code that needs these classes throws NoClassDefFoundError when it runs: Pack overworld: module jars use classes that neither the pack, Iris nor the JDK has, usually optional dependencies of a bundled library. The jars load, but code that needs these classes throws NoClassDefFoundError when it runs:
+4 -24
View File
@@ -1,8 +1,6 @@
package com.volmit; package com.volmit;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import java.util.Arrays;
import java.util.List;
import java.util.Objects; import java.util.Objects;
/** Module identity. Every stage a module defines has an id that starts with the module id and /** Module identity. Every stage a module defines has an id that starts with the module id and
@@ -13,12 +11,10 @@ import java.util.Objects;
* people, for example in load logs; the id is what the host and other modules match on. Name and * people, for example in load logs; the id is what the host and other modules match on. Name and
* version must fit on one log line, so they reject control characters such as line breaks. * version must fit on one log line, so they reject control characters such as line breaks.
* *
* <p>Optional packages are packages, with their subpackages, whose classes the module's jar uses * <p>What the module's jar needs at load, such as packages it expects may be missing, is the jar's, declared in its
* but expects may be absent at runtime, typically optional integrations of a library it bundles. * manifest (see README, "Optional packages"), not the module's identity.
* The pack load does not warn about missing classes in them. They never excuse a class that Iris
* hides from modules or one missing from a package Iris exposes; those still fail the load.
*/ */
public record ModuleInfo(ResourceId id, String name, String version, List<PackageName> optionalPackages) { public record ModuleInfo(ResourceId id, String name, String version) {
private static final String STAGE_SEPARATOR = "/"; private static final String STAGE_SEPARATOR = "/";
public ModuleInfo { public ModuleInfo {
@@ -28,26 +24,10 @@ public record ModuleInfo(ResourceId id, String name, String version, List<Packag
requireSingleSegment(id); requireSingleSegment(id);
requireOneLineText(id, "name", name); requireOneLineText(id, "name", name);
requireOneLineText(id, "version", version); requireOneLineText(id, "version", version);
optionalPackages = List.copyOf(optionalPackages);
} }
public static ModuleInfo of(String id, String name, String version) { public static ModuleInfo of(String id, String name, String version) {
return new ModuleInfo(ResourceId.parse(id), name, version, List.of()); return new ModuleInfo(ResourceId.parse(id), name, version);
}
/** This identity with {@code packages} as its optional packages, replacing any declared before.
* A trailing dot is accepted; anything that is not a package name, such as a wildcard, is rejected.
*/
public ModuleInfo withOptionalPackages(String... packages) {
var parsed = Arrays.stream(packages).map(this::requireOptionalPackage).toList();
return new ModuleInfo(id, name, version, parsed);
}
private PackageName requireOptionalPackage(String packageName) {
Objects.requireNonNull(packageName, "optional package");
return PackageName.tryParse(packageName).orElseThrow(() -> new IllegalArgumentException("Optional package '"
+ packageName + "' of module " + id + " is not a package name; name a package such as org.slf4j,"
+ " which covers that package and its subpackages"));
} }
/** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */ /** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */
@@ -18,8 +18,8 @@ import java.util.Optional;
* the pack's {@code blocks} folder, or a block that only some versions or mods have. * the pack's {@code blocks} folder, or a block that only some versions or mods have.
* *
* <p>The host resolves it with {@link BlockRegistry#resolve(BlockSpec)} and its block entity with * <p>The host resolves it with {@link BlockRegistry#resolve(BlockSpec)} and its block entity with
* {@link BlockRegistry#blockEntity(BlockSpec)}. A spec is a value: the host creates it with the no-argument * {@link BlockRegistry#blockEntity(BlockSpec)}. A spec is a value the host decodes as every settings class (see
* constructor and reads the JSON into it, and nothing changes it afterwards. Property values are text however the * DESIGN.md, "Decoding contract"), and nothing changes it afterwards. Property values are text however the
* pack writes them, so {@code "waterlogged": true} reads as {@code "true"}. * pack writes them, so {@code "waterlogged": true} reads as {@code "true"}.
*/ */
@Desc("A block, with optional properties, block entity data and a backup for platforms without it") @Desc("A block, with optional properties, block entity data and a backup for platforms without it")
@@ -31,7 +31,7 @@ public final class BlockSpec {
@Desc("The block to use. A key without a namespace is a Minecraft block or a block of the pack's blocks folder.") @Desc("The block to use. A key without a namespace is a Minecraft block or a block of the pack's blocks folder.")
private String block = AIR; private String block = AIR;
@Desc("Optional properties for this block, such as 'waterlogged': true") @Desc("The block's properties, such as \"waterlogged\": true.")
private Map<String, String> data = Map.of(); private Map<String, String> data = Map.of();
@MinNumber(1) @MinNumber(1)
@@ -39,10 +39,10 @@ public final class BlockSpec {
@Desc("The weight of this block in a list it is picked from. A weight of two is as if the block were in the list twice.") @Desc("The weight of this block in a list it is picked from. A weight of two is as if the block were in the list twice.")
private int weight = 1; private int weight = 1;
@Desc("If the block cannot be created on this platform, this block is used instead.") @Desc("The block used instead on a platform that does not have this one.")
private BlockSpec backup; private BlockSpec backup;
@Desc("Optional block entity data for this block, such as a spawner's SpawnData") @Desc("The block entity data, such as a spawner's SpawnData.")
private Map<String, Object> tileData = Map.of(); private Map<String, Object> tileData = Map.of();
private BlockSpec() { private BlockSpec() {
@@ -82,12 +82,12 @@ public final class BlockSpec {
/** The block key as the pack wrote it. */ /** The block key as the pack wrote it. */
public String block() { public String block() {
return block == null ? AIR : block; return block;
} }
/** The properties as the pack wrote them, as text. */ /** The properties as the pack wrote them, as text. */
public Map<String, String> data() { public Map<String, String> data() {
return data == null ? Map.of() : Collections.unmodifiableMap(data); return Collections.unmodifiableMap(data);
} }
public int weight() { public int weight() {
@@ -100,7 +100,7 @@ public final class BlockSpec {
/** The block entity data as the pack wrote it: JSON objects as maps, arrays as lists, numbers as {@code Double}. */ /** The block entity data as the pack wrote it: JSON objects as maps, arrays as lists, numbers as {@code Double}. */
public Map<String, Object> tileData() { public Map<String, Object> tileData() {
return tileData == null ? Map.of() : Collections.unmodifiableMap(tileData); return Collections.unmodifiableMap(tileData);
} }
@Override @Override
@@ -16,26 +16,26 @@ import java.util.Objects;
* at the position over {@code zoom} selects, each block counting {@link BlockSpec#weight() weight} times. * at the position over {@code zoom} selects, each block counting {@link BlockSpec#weight() weight} times.
* *
* <p>A palette is a description, not a picker: the host builds the picker * <p>A palette is a description, not a picker: the host builds the picker
* ({@link BlockRegistry#palette(PaletteSpec, long)}). It is a value the host creates with the no-argument * ({@link BlockRegistry#palette(PaletteSpec, long)}). It is a value the host decodes as every settings class (see
* constructor and reads the JSON into; nothing changes it afterwards. * DESIGN.md, "Decoding contract"); nothing changes it afterwards.
*/ */
@Snippet("palette") @Snippet("palette")
@Desc("A palette of materials") @Desc("Blocks picked by noise, each as often as its weight")
public final class PaletteSpec { public final class PaletteSpec {
private static final String DEFAULT_STYLE = "STATIC"; private static final String DEFAULT_STYLE = "STATIC";
private static final double DEFAULT_ZOOM = 5; private static final double DEFAULT_ZOOM = 5;
private static final String DEFAULT_BLOCK = "stone"; private static final String DEFAULT_BLOCK = "stone";
@Desc("The style of noise") @Desc("The noise that picks the block at each position.")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE); private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
@MinNumber(0.0001) @MinNumber(0.0001)
@Desc("The terrain zoom mostly for zooming in on a wispy palette") @Desc("How far the picking noise is stretched: above 1 gives larger patches of one block.")
private double zoom = DEFAULT_ZOOM; private double zoom = DEFAULT_ZOOM;
@Required @Required
@MinItems(1) @MinItems(1)
@Desc("The palette of blocks to be used in this layer") @Desc("The blocks to pick from.")
private List<BlockSpec> palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); private List<BlockSpec> palette = List.of(BlockSpec.of(DEFAULT_BLOCK));
private PaletteSpec() { private PaletteSpec() {
@@ -63,7 +63,7 @@ public final class PaletteSpec {
/** The noise that picks the blocks; the default {@code STATIC} style where the pack wrote none. */ /** The noise that picks the blocks; the default {@code STATIC} style where the pack wrote none. */
public NoiseStyle style() { public NoiseStyle style() {
return style == null ? NoiseStyle.of(DEFAULT_STYLE) : style; return style;
} }
/** The factor the position is divided by before it is looked up in the noise. */ /** The factor the position is divided by before it is looked up in the noise. */
@@ -73,7 +73,7 @@ public final class PaletteSpec {
/** The blocks to pick from, as the pack wrote them. */ /** The blocks to pick from, as the pack wrote them. */
public List<BlockSpec> palette() { public List<BlockSpec> palette() {
return palette == null ? List.of() : Collections.unmodifiableList(palette); return Collections.unmodifiableList(palette);
} }
@Override @Override
@@ -5,15 +5,15 @@ import java.util.Objects;
/** A span of numbers from {@code min} to {@code max}, both included, as packs write it: {@code {"min": 0, "max": 15}}, /** A span of numbers from {@code min} to {@code max}, both included, as packs write it: {@code {"min": 0, "max": 15}},
* or a snippet under {@code snippet/range/}. An omitted bound keeps its default, so give a settings field its own * or a snippet under {@code snippet/range/}. An omitted bound keeps its default, so give a settings field its own
* default with {@link #of}. A value the host creates with the no-argument constructor and reads the JSON into. * default with {@link #of}. A value the host decodes as every settings class (see DESIGN.md, "Decoding contract").
*/ */
@Snippet("range") @Snippet("range")
@Desc("Represents a range") @Desc("A span of numbers from min to max, both included")
public final class Range { public final class Range {
@Desc("The minimum value") @Desc("The lowest value.")
private double min = 16; private double min = 16;
@Desc("The maximum value") @Desc("The highest value.")
private double max = 32; private double max = 32;
private Range() { private Range() {
@@ -14,10 +14,10 @@ import java.util.Optional;
/** How noise is shaped, as packs write it: {@code {"style": "SIMPLEX", "zoom": 4}}, or a snippet under /** How noise is shaped, as packs write it: {@code {"style": "SIMPLEX", "zoom": 4}}, or a snippet under
* {@code snippet/style/}. The style names one of the host's noise generators ({@link Reference#NOISE_STYLE}); an * {@code snippet/style/}. The style names one of the host's noise generators ({@link Reference#NOISE_STYLE}); an
* expression or image map of the pack replaces it. A zoom stretches the noise, an exponent bends it, a fracture * expression or image map of the pack replaces it. A zoom stretches the noise, an exponent bends it, a fracture
* style distorts its coordinates and a cellular frequency turns it into cells. * distorts its coordinates and a cellular frequency turns it into cells.
* *
* <p>A style is a description, not noise: the host builds the noise ({@link NoiseFactory#sampler}). It is a value * <p>A style is a description, not noise: the host builds the noise ({@link NoiseFactory#sampler}). It is a value
* the host creates with the no-argument constructor and reads the JSON into; nothing changes it afterwards. * the host decodes as every settings class (see DESIGN.md, "Decoding contract"); nothing changes it afterwards.
*/ */
@Snippet("style") @Snippet("style")
@Desc("A noise style: one of the host's noise generators, or an expression or image map of the pack, shaped by zoom, exponent, fracture and cells") @Desc("A noise style: one of the host's noise generators, or an expression or image map of the pack, shaped by zoom, exponent, fracture and cells")
@@ -26,44 +26,39 @@ public final class NoiseStyle {
public static final String FLAT = "FLAT"; public static final String FLAT = "FLAT";
@Ref(Reference.NOISE_STYLE) @Ref(Reference.NOISE_STYLE)
@Desc("The base noise style. Used when neither expression nor imageMap is set; a failed expression also falls back to this style.") @Desc("The noise generator. Used when neither expression nor imageMap is set, and when an expression fails.")
private String style = FLAT; private String style = FLAT;
@Desc("If set above 0, this style will be cellularized") @Desc("Above 0, the noise is turned into cells of this frequency.")
private double cellularFrequency = 0; private double cellularFrequency = 0;
@Desc("Cell zooms") @Desc("How far the cells are stretched.")
private double cellularZoom = 1; private double cellularZoom = 1;
@MinNumber(0.00001) @MinNumber(0.00001)
@Desc("The zoom of this style") @Desc("How far the noise is stretched: above 1 wider, below 1 tighter.")
private double zoom = 1; private double zoom = 1;
@Ref(kind = PackExpression.class) @Ref(kind = PackExpression.class)
@Desc("Instead of using the style property, use a custom expression to represent this style.") @Desc("An expression of the pack that gives the noise instead of the style.")
private ResourceId expression; private ResourceId expression;
@Ref(kind = PackImageMap.class) @Ref(kind = PackImageMap.class)
@Desc("Use an Image map instead of a generated value") @Desc("An image map of the pack that gives the noise instead of the style, when there is no expression.")
private ResourceId imageMap; private ResourceId imageMap;
@MinNumber(0.00001) @MinNumber(0.00001)
@Desc("The Output multiplier. Only used if parent is fracture.") @Desc("When this style moves coordinates, as another style's fracture or as a warp: up to half this many blocks either way.")
private double multiplier = 1; private double multiplier = 1;
@Desc("Apply a generator to the coordinate field fed into this parent generator. I.e. Distort your generator with another generator.") @Desc("A style whose noise moves the coordinates this style is sampled at, distorting it.")
private NoiseStyle fracture; private NoiseStyle fracture;
@MinNumber(0.01562) @MinNumber(0.01562)
@MaxNumber(64) @MaxNumber(64)
@Desc("The exponent") @Desc("The power the noise is raised to: above 1 favours low values, below 1 high ones.")
private double exponent = 1; private double exponent = 1;
@MinNumber(0)
@MaxNumber(8192)
@Desc("If the cache size is set above 0, this generator will be cached")
private int cacheSize = 0;
private NoiseStyle() { private NoiseStyle() {
} }
@@ -77,7 +72,6 @@ public final class NoiseStyle {
multiplier = copy.multiplier; multiplier = copy.multiplier;
fracture = copy.fracture; fracture = copy.fracture;
exponent = copy.exponent; exponent = copy.exponent;
cacheSize = copy.cacheSize;
} }
/** The host's noise style {@code style}, such as {@code SIMPLEX}, with every other option at its default. */ /** The host's noise style {@code style}, such as {@code SIMPLEX}, with every other option at its default. */
@@ -96,7 +90,7 @@ public final class NoiseStyle {
/** The base style's name; {@link #FLAT} where the pack wrote none. */ /** The base style's name; {@link #FLAT} where the pack wrote none. */
public String style() { public String style() {
return style == null ? FLAT : style; return style;
} }
public double cellularFrequency() { public double cellularFrequency() {
@@ -121,10 +115,14 @@ public final class NoiseStyle {
return Optional.ofNullable(imageMap); return Optional.ofNullable(imageMap);
} }
/** How far this style moves coordinates when it moves them, as another style's {@link #fracture} or as a warp: up
* to half this many blocks either way.
*/
public double multiplier() { public double multiplier() {
return multiplier; return multiplier;
} }
/** The style whose noise moves the coordinates this style is sampled at, by its own {@link #multiplier}. */
public Optional<NoiseStyle> fracture() { public Optional<NoiseStyle> fracture() {
return Optional.ofNullable(fracture); return Optional.ofNullable(fracture);
} }
@@ -133,34 +131,29 @@ public final class NoiseStyle {
return exponent; return exponent;
} }
public int cacheSize() {
return cacheSize;
}
/** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */ /** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */
public boolean isFlat() { public boolean isFlat() {
return FLAT.equals(style()) && expression == null && imageMap == null; return FLAT.equals(style) && expression == null && imageMap == null;
} }
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof NoiseStyle that && style().equals(that.style()) return other instanceof NoiseStyle that && style.equals(that.style)
&& Double.compare(cellularFrequency, that.cellularFrequency) == 0 && Double.compare(cellularFrequency, that.cellularFrequency) == 0
&& Double.compare(cellularZoom, that.cellularZoom) == 0 && Double.compare(zoom, that.zoom) == 0 && Double.compare(cellularZoom, that.cellularZoom) == 0 && Double.compare(zoom, that.zoom) == 0
&& Objects.equals(expression, that.expression) && Objects.equals(imageMap, that.imageMap) && Objects.equals(expression, that.expression) && Objects.equals(imageMap, that.imageMap)
&& Double.compare(multiplier, that.multiplier) == 0 && Objects.equals(fracture, that.fracture) && Double.compare(multiplier, that.multiplier) == 0 && Objects.equals(fracture, that.fracture)
&& Double.compare(exponent, that.exponent) == 0 && cacheSize == that.cacheSize; && Double.compare(exponent, that.exponent) == 0;
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(style(), cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, return Objects.hash(style, cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, exponent);
exponent, cacheSize);
} }
@Override @Override
public String toString() { public String toString() {
return "NoiseStyle[" + style() + expression().map(key -> ", expression " + key).orElse("") return "NoiseStyle[" + style + expression().map(key -> ", expression " + key).orElse("")
+ imageMap().map(key -> ", image map " + key).orElse("") + ", zoom " + zoom + "]"; + imageMap().map(key -> ", image map " + key).orElse("") + ", zoom " + zoom + "]";
} }
} }
@@ -6,20 +6,20 @@ import java.util.Objects;
/** A number between {@code min} and {@code max} that a noise style picks per column, as packs write it: /** A number between {@code min} and {@code max} that a noise style picks per column, as packs write it:
* {@code {"min": 4, "max": 12, "style": {"style": "SIMPLEX"}}}, or a snippet under {@code snippet/style-range/}. * {@code {"min": 4, "max": 12, "style": {"style": "SIMPLEX"}}}, or a snippet under {@code snippet/style-range/}.
* A value the host creates with the no-argument constructor and reads the JSON into. * A value the host decodes as every settings class (see DESIGN.md, "Decoding contract").
*/ */
@Snippet("style-range") @Snippet("style-range")
@Desc("Represents a range styled with a custom generator") @Desc("A number between min and max that noise picks per column")
public final class StyledRange { public final class StyledRange {
private static final String DEFAULT_STYLE = "STATIC"; private static final String DEFAULT_STYLE = "STATIC";
@Desc("The minimum value") @Desc("The lowest value.")
private double min = 16; private double min = 16;
@Desc("The maximum value") @Desc("The highest value.")
private double max = 32; private double max = 32;
@Desc("The style to pick the range") @Desc("The noise that picks the value in each column.")
private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE); private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE);
private StyledRange() { private StyledRange() {
@@ -43,14 +43,14 @@ public final class StyledRange {
return max; return max;
} }
/** The style; {@link NoiseStyle#FLAT} where the pack wrote {@code null}. */ /** The style; {@code STATIC} where the pack wrote none. */
public NoiseStyle style() { public NoiseStyle style() {
return style == null ? NoiseStyle.of(NoiseStyle.FLAT) : style; return style;
} }
/** Whether every column gets the same value: the bounds are equal or the style is flat. */ /** Whether every column gets the same value: the bounds are equal or the style is flat. */
public boolean isFlat() { public boolean isFlat() {
return min == max || style().isFlat(); return min == max || style.isFlat();
} }
/** The value at column {@code worldX}, {@code worldZ}: {@code min} when the bounds are equal, halfway between /** The value at column {@code worldX}, {@code worldZ}: {@code min} when the bounds are equal, halfway between
@@ -61,25 +61,25 @@ public final class StyledRange {
if (min == max) { if (min == max) {
return min; return min;
} }
if (style().isFlat()) { if (style.isFlat()) {
return (min + max) / 2; return (min + max) / 2;
} }
return min + (max - min) * noise.sampler(style(), seed).sample(worldX, worldZ); return min + (max - min) * noise.sampler(style, seed).sample(worldX, worldZ);
} }
@Override @Override
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof StyledRange that && Double.compare(min, that.min) == 0 return other instanceof StyledRange that && Double.compare(min, that.min) == 0
&& Double.compare(max, that.max) == 0 && style().equals(that.style()); && Double.compare(max, that.max) == 0 && style.equals(that.style);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(min, max, style()); return Objects.hash(min, max, style);
} }
@Override @Override
public String toString() { public String toString() {
return "StyledRange[" + min + ".." + max + ", " + style() + "]"; return "StyledRange[" + min + ".." + max + ", " + style + "]";
} }
} }
@@ -3,17 +3,14 @@ package com.volmit.placement;
import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockBox;
import com.volmit.geometry.BlockPosition; import com.volmit.geometry.BlockPosition;
import com.volmit.object.GeneratedObject; import com.volmit.object.GeneratedObject;
import com.volmit.resource.ResourceId;
import java.util.Objects; import java.util.Objects;
/** One placement attempt. Geometry is already transformed; anchor is a world block position (world X and Z, Y as the height /** One placement attempt. Geometry is already transformed; anchor is a world block position (world X and Z, Y as the height
* above the dimension's bottom). * above the dimension's bottom).
* World position = local position - object anchor + request anchor. Arithmetic never wraps. * World position = local position - object anchor + request anchor. Arithmetic never wraps.
* id identifies this attempt within the host's generation plan.
*/ */
public record PlacementRequest(ResourceId id, GeneratedObject object, BlockPosition anchor) { public record PlacementRequest(GeneratedObject object, BlockPosition anchor) {
public PlacementRequest { public PlacementRequest {
Objects.requireNonNull(id, "id");
Objects.requireNonNull(object, "object"); Objects.requireNonNull(object, "object");
Objects.requireNonNull(anchor, "anchor"); Objects.requireNonNull(anchor, "anchor");
} }
@@ -5,10 +5,11 @@ import com.volmit.resource.ResourceId;
import com.volmit.world.PackWorld; import com.volmit.world.PackWorld;
import java.util.Set; import java.util.Set;
/** Finds the structures a module places, for the host's structure commands and index. Structures are named by their /** Finds the structures a module places, for the host's structure commands, index and locate. Structures are named by
* ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}), * their ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}),
* a platform structure by the platform's id ({@code minecraft:ancient_city}). The host asks the providers in order and * a platform structure by the platform's id ({@code minecraft:ancient_city}). The host asks the providers in order and
* sends an id to the first that places it in the world ({@link #placed}). * sends an id to the first that places it in the world: {@link #placed} for the structures the module places itself,
* {@link #locatableStarts} for the platform structures it starts ({@link VanillaStructures#starts}).
*/ */
@Service(Providers.FIRST) @Service(Providers.FIRST)
public interface StructureLocator { public interface StructureLocator {
@@ -37,4 +38,37 @@ public interface StructureLocator {
* host calls it off the server's main thread. * host calls it off the server's main thread.
*/ */
LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks); LocateResult locate(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRadiusChunks);
/** The platform structures this module starts itself in {@code world} ({@link VanillaStructures#starts}), wherever
* its own placements put them. The host's locate and structure commands send them to {@link #locateStart}.
*/
default Set<ResourceId> startedStructures(PackWorld world) {
return Set.of();
}
/** Those of {@link #startedStructures} whose starts {@link #locateStart} can find in {@code world}: a start whose
* placement can never start in the world's height, for one, cannot be searched for.
*/
default Set<ResourceId> locatableStarts(PackWorld world) {
return Set.of();
}
/**
* The start of the platform structure {@code structure} this module makes nearest to the column {@code fromX},
* {@code fromZ} (world coordinates), searched ring by ring outward through its placements' grids up to {@code maxRings}
* rings: the nearest start of the first ring that has one. The position is the start's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Only chunks {@code accepts} allows count; the host checks the start
* the platform made there and searches again without a chunk it refuses. An exception {@code accepts} throws ends the
* search and reaches the caller. Called with a structure from {@link #locatableStarts}, off the server's main thread.
*/
default LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings,
ChunkFilter accepts) {
return LocateResult.NOT_FOUND;
}
/** Which chunks a {@link #locateStart} search may answer with. */
@FunctionalInterface
interface ChunkFilter {
boolean accepts(int chunkX, int chunkZ);
}
} }
@@ -10,10 +10,8 @@ import com.volmit.vanilla.VanillaStructureRule;
import com.volmit.vanilla.VanillaStructureSetup; import com.volmit.vanilla.VanillaStructureSetup;
import com.volmit.vanilla.VanillaStructureStart; import com.volmit.vanilla.VanillaStructureStart;
import com.volmit.vanilla.VanillaStructureStartContext; import com.volmit.vanilla.VanillaStructureStartContext;
import com.volmit.world.PackWorld;
import java.util.List; import java.util.List;
import java.util.Optional; import java.util.Optional;
import java.util.Set;
/** A module's say over the platform's own structures, the ones Minecraft, data packs and mods register, in the pack's /** A module's say over the platform's own structures, the ones Minecraft, data packs and mods register, in the pack's
* worlds. The host asks every provider, in module id order: * worlds. The host asks every provider, in module id order:
@@ -32,7 +30,8 @@ import java.util.Set;
* from the pack (its settings and resources) and never from where a start would be. Rules combine with * from the pack (its settings and resources) and never from where a start would be. Rules combine with
* {@link VanillaStructureRule#and}: any module may block the platform's starts. Shifts add up; reaches are all covered; * {@link VanillaStructureRule#and}: any module may block the platform's starts. Shifts add up; reaches are all covered;
* setups combine with {@link VanillaStructureSetup#and}. Every method may be called from any thread, concurrently, but * setups combine with {@link VanillaStructureSetup#and}. Every method may be called from any thread, concurrently, but
* one chunk's {@link StructureFit} is used on one thread. * one chunk's {@link StructureFit} is used on one thread. Finding the starts a module makes is
* {@link StructureLocator}'s, the one service that locates structures.
*/ */
@Service(Providers.ALL) @Service(Providers.ALL)
public interface VanillaStructures { public interface VanillaStructures {
@@ -93,37 +92,4 @@ public interface VanillaStructures {
default VanillaStructureSetup setup(VanillaStructureContext context) { default VanillaStructureSetup setup(VanillaStructureContext context) {
return VanillaStructureSetup.UNCHANGED; return VanillaStructureSetup.UNCHANGED;
} }
/** The platform structures this module starts itself in {@code world} ({@link #starts}), wherever its own placements put
* them. The host's locate and structure commands send them to {@link #locateStart}.
*/
default Set<ResourceId> startedStructures(PackWorld world) {
return Set.of();
}
/** Those of {@link #startedStructures} whose starts {@link #locateStart} can find in {@code world}: a start whose
* placement can never start in the world's height, for one, cannot be searched for.
*/
default Set<ResourceId> locatableStarts(PackWorld world) {
return Set.of();
}
/**
* The start of the platform structure {@code structure} this module makes nearest to the column {@code fromX},
* {@code fromZ} (world coordinates), searched ring by ring outward through its placements' grids up to {@code maxRings}
* rings: the nearest start of the first ring that has one. The position is the start's origin: world X and Z, and Y the
* height above the dimension's bottom of its base. Only chunks {@code accepts} allows count; the host checks the start
* the platform made there and searches again without a chunk it refuses. An exception {@code accepts} throws ends the
* search and reaches the caller. Called with a structure from {@link #locatableStarts}, off the server's main thread.
*/
default LocateResult locateStart(PackWorld world, ResourceId structure, int fromX, int fromZ, int maxRings,
ChunkFilter accepts) {
return LocateResult.NOT_FOUND;
}
/** Which chunks a {@link #locateStart} search may answer with. */
@FunctionalInterface
interface ChunkFilter {
boolean accepts(int chunkX, int chunkZ);
}
} }
@@ -12,18 +12,18 @@ import java.util.OptionalInt;
/** Changes to a platform jigsaw structure's definition before the platform assembles one start of it, as packs write /** Changes to a platform jigsaw structure's definition before the platform assembles one start of it, as packs write
* them: {@code {"startPool": "minecraft:village/plains/town_centers", "maxDepth": 4}}. Every option left out keeps * them: {@code {"startPool": "minecraft:village/plains/town_centers", "maxDepth": 4}}. Every option left out keeps
* what the registered definition says. A value the host creates with the no-argument constructor and reads the JSON * what the registered definition says. A value the host decodes as every settings class (see DESIGN.md, "Decoding
* into. * contract").
*/ */
@Desc("Optional overrides applied to a live vanilla, datapack, or modded jigsaw definition before Minecraft assembles it. Omitted values preserve the registered source definition.") @Desc("Changes to a platform jigsaw structure's definition before a start of it is assembled. An option left out keeps the definition's value.")
public final class JigsawOverrides { public final class JigsawOverrides {
/** What packs write as the start connector to remove the definition's constraint. */ /** What packs write as the start connector to remove the definition's constraint. */
private static final String NO_START_JIGSAW = "NONE"; private static final String NO_START_JIGSAW = "NONE";
/** Whether the start piece follows one of the platform's heightmaps. */ /** Whether the start piece follows one of the platform's heightmaps. */
@Desc("Controls whether a configured native jigsaw projects its start onto a Minecraft heightmap.") @Desc("Which heightmap the start piece is placed on.")
public enum Heightmap { public enum Heightmap {
@Desc("Keeps the registered structure's own heightmap projection.") @Desc("The definition's own heightmap.")
SOURCE, SOURCE,
@Desc("Removes heightmap projection: the start piece lands at the structure's literal start height.") @Desc("Removes heightmap projection: the start piece lands at the structure's literal start height.")
NONE, NONE,
@@ -42,9 +42,9 @@ public final class JigsawOverrides {
} }
/** Whether placed pieces take on the water they are placed into. */ /** Whether placed pieces take on the water they are placed into. */
@Desc("Controls waterlogging behavior for a configured native jigsaw.") @Desc("Whether placed pieces take on the water they replace.")
public enum Liquids { public enum Liquids {
@Desc("Keeps the registered structure's own liquid setting.") @Desc("The definition's own liquid setting.")
SOURCE, SOURCE,
@Desc("Places pieces dry.") @Desc("Places pieces dry.")
IGNORE_WATERLOGGING, IGNORE_WATERLOGGING,
@@ -52,45 +52,45 @@ public final class JigsawOverrides {
APPLY_WATERLOGGING APPLY_WATERLOGGING
} }
@Desc("Optional registered template-pool key used instead of the source jigsaw's start pool. Empty preserves the source pool.") @Desc("The template pool the start piece comes from. Left out, the definition's pool.")
@Ref(Reference.TEMPLATE_POOL) @Ref(Reference.TEMPLATE_POOL)
private String startPool = ""; private String startPool = "";
@Desc("Optional start connector name. Empty preserves the source value; the literal NONE removes the source constraint.") @Desc("The start piece's connector. Left out, the definition's; NONE removes the definition's constraint.")
private String startJigsawName = ""; private String startJigsawName = "";
@MinNumber(0) @MinNumber(0)
@MaxNumber(20) @MaxNumber(20)
@Desc("Maximum jigsaw recursion depth. Null preserves the source value.") @Desc("How many pieces deep the structure grows. Left out, the definition's depth.")
private Integer maxDepth = null; private Integer maxDepth = null;
@MinNumber(1) @MinNumber(1)
@MaxNumber(128) @MaxNumber(128)
@Desc("Exact horizontal block distance allowed from the start. Null preserves the source value.") @Desc("How many blocks sideways pieces may reach from the start. Left out, the definition's distance.")
private Integer maxDistanceHorizontal = null; private Integer maxDistanceHorizontal = null;
@MinNumber(1) @MinNumber(1)
@MaxNumber(4064) @MaxNumber(4064)
@Desc("Exact vertical block distance allowed from the start. Null preserves the source value.") @Desc("How many blocks up or down pieces may reach from the start. Left out, the definition's distance.")
private Integer maxDistanceVertical = null; private Integer maxDistanceVertical = null;
@Desc("Expansion-hack override. Null preserves the source value.") @Desc("Whether the platform's expansion hack applies. Left out, the definition's setting.")
private Boolean useExpansionHack = null; private Boolean useExpansionHack = null;
@Desc("Heightmap projection override. SOURCE preserves the registered value and NONE removes projection.") @Desc("The heightmap the start piece is placed on.")
private Heightmap projectStartToHeightmap = Heightmap.SOURCE; private Heightmap projectStartToHeightmap = Heightmap.SOURCE;
@MinNumber(0) @MinNumber(0)
@MaxNumber(Integer.MAX_VALUE) @MaxNumber(Integer.MAX_VALUE)
@Desc("Minimum distance retained above the dimension floor. Null preserves the source value.") @Desc("How many blocks pieces stay above the dimension's bottom. Left out, the definition's padding.")
private Integer dimensionPaddingBottom = null; private Integer dimensionPaddingBottom = null;
@MinNumber(0) @MinNumber(0)
@MaxNumber(Integer.MAX_VALUE) @MaxNumber(Integer.MAX_VALUE)
@Desc("Minimum distance retained below the dimension ceiling. Null preserves the source value.") @Desc("How many blocks pieces stay below the dimension's top. Left out, the definition's padding.")
private Integer dimensionPaddingTop = null; private Integer dimensionPaddingTop = null;
@Desc("Waterlogging override. SOURCE preserves the registered value.") @Desc("Whether placed pieces take on the water they replace.")
private Liquids liquidSettings = Liquids.SOURCE; private Liquids liquidSettings = Liquids.SOURCE;
private JigsawOverrides() { private JigsawOverrides() {
@@ -187,11 +187,11 @@ public final class JigsawOverrides {
/** Whether the start connector constraint is removed, which packs write as {@code NONE}. */ /** Whether the start connector constraint is removed, which packs write as {@code NONE}. */
public boolean removesStartJigsaw() { public boolean removesStartJigsaw() {
return startJigsawName != null && NO_START_JIGSAW.equalsIgnoreCase(startJigsawName.trim()); return NO_START_JIGSAW.equalsIgnoreCase(startJigsawName.trim());
} }
private static Optional<ResourceId> platformKey(String key) { private static Optional<ResourceId> platformKey(String key) {
return key == null || key.isBlank() ? Optional.empty() : Optional.of(ResourceId.ofPlatformKey(key)); return key.isBlank() ? Optional.empty() : Optional.of(ResourceId.ofPlatformKey(key));
} }
public OptionalInt maxDepth() { public OptionalInt maxDepth() {
@@ -210,9 +210,9 @@ public final class JigsawOverrides {
return Optional.ofNullable(useExpansionHack); return Optional.ofNullable(useExpansionHack);
} }
/** The heightmap projection; {@link Heightmap#SOURCE} where the pack wrote none or one the host does not know. */ /** The heightmap projection; {@link Heightmap#SOURCE} where the pack wrote none. */
public Heightmap projectStartToHeightmap() { public Heightmap projectStartToHeightmap() {
return projectStartToHeightmap == null ? Heightmap.SOURCE : projectStartToHeightmap; return projectStartToHeightmap;
} }
public OptionalInt dimensionPaddingBottom() { public OptionalInt dimensionPaddingBottom() {
@@ -223,9 +223,9 @@ public final class JigsawOverrides {
return optional(dimensionPaddingTop); return optional(dimensionPaddingTop);
} }
/** The waterlogging; {@link Liquids#SOURCE} where the pack wrote none or one the host does not know. */ /** The waterlogging; {@link Liquids#SOURCE} where the pack wrote none. */
public Liquids liquidSettings() { public Liquids liquidSettings() {
return liquidSettings == null ? Liquids.SOURCE : liquidSettings; return liquidSettings;
} }
private static OptionalInt optional(Integer value) { private static OptionalInt optional(Integer value) {
@@ -256,8 +256,8 @@ public final class JigsawOverrides {
return "JigsawOverrides[pool '" + written(startPool) + "', depth " + maxDepth + ", " + projectStartToHeightmap() + "]"; return "JigsawOverrides[pool '" + written(startPool) + "', depth " + maxDepth + ", " + projectStartToHeightmap() + "]";
} }
/** A key as the pack wrote it, without surrounding blanks; empty when it wrote none. */ /** A key as the pack wrote it, without surrounding blanks. */
private static String written(String key) { private static String written(String key) {
return key == null ? "" : key.trim(); return key.trim();
} }
} }
@@ -2,15 +2,17 @@ package com.volmit.vanilla;
import java.util.Objects; import java.util.Objects;
/** What a module noted about a start it placed, for itself: two texts in the module's own format, one about how the /** What a module noted about a start it placed, for itself: one text in the module's own format. The host keeps the memo
* start meets the terrain and one about its foundation. The host keeps the memo with the start for as long as the world * with the start for as long as the world does and hands it back whenever it asks the module about the start again
* does and hands it back whenever it asks the module about the start again ({@link StructureFit.Start#memo()}, * ({@link StructureFit.Start#memo()}, {@link com.volmit.service.VanillaStructures#reach}), so a start that spans many
* {@link com.volmit.service.VanillaStructures#reach}), so a start that spans many chunks is finished the way it was * chunks is finished the way it was begun, even after the pack changed. The host never reads the text, which is not
* begun, even after the pack changed. The host never reads the texts. * empty: a start the module noted nothing about has no memo.
*/ */
public record StartMemo(String terrain, String foundation) { public record StartMemo(String text) {
public StartMemo { public StartMemo {
Objects.requireNonNull(terrain, "terrain"); Objects.requireNonNull(text, "text");
Objects.requireNonNull(foundation, "foundation"); if (text.isEmpty()) {
throw new IllegalArgumentException("A start memo's text must not be empty; give the start no memo instead");
}
} }
} }
@@ -13,10 +13,9 @@ import java.util.Optional;
* the chunk win unless the start {@link #replacesPlatformStart() replaces} them or the structure is * the chunk win unless the start {@link #replacesPlatformStart() replaces} them or the structure is
* {@link VanillaStructureRule#REPLACE replaced} by a module. * {@link VanillaStructureRule#REPLACE replaced} by a module.
* *
* <p>{@link #identity()} names what placed the start, stable for one pack: the host records it with every start it * <p>The {@link #memo() memo} is kept with the start and handed back whenever the host asks the module about the start
* publishes, so a start found in the world later can be traced back to its placement. The {@link #memo() memo} is kept * again, so a start that spans many chunks keeps what the module decided for it when it was placed, even after the pack
* with that record and handed back whenever the host asks the module about the start again, so a start that spans many * changed.
* chunks keeps what the module decided for it when it was placed, even after the pack changed.
*/ */
public final class VanillaStructureStart { public final class VanillaStructureStart {
private final ResourceId structure; private final ResourceId structure;
@@ -25,56 +24,49 @@ public final class VanillaStructureStart {
private final int y; private final int y;
private final boolean underground; private final boolean underground;
private final boolean replacesPlatformStart; private final boolean replacesPlatformStart;
private final long identity;
private final JigsawOverrides jigsaw; private final JigsawOverrides jigsaw;
private final StartMemo memo; private final StartMemo memo;
private VanillaStructureStart(ResourceId structure, int chunkX, int chunkZ, int y, boolean underground, private VanillaStructureStart(ResourceId structure, int chunkX, int chunkZ, int y, boolean underground,
boolean replacesPlatformStart, long identity, JigsawOverrides jigsaw, boolean replacesPlatformStart, JigsawOverrides jigsaw, StartMemo memo) {
StartMemo memo) {
this.structure = Objects.requireNonNull(structure, "structure"); this.structure = Objects.requireNonNull(structure, "structure");
this.chunkX = chunkX; this.chunkX = chunkX;
this.chunkZ = chunkZ; this.chunkZ = chunkZ;
this.y = y; this.y = y;
this.underground = underground; this.underground = underground;
this.replacesPlatformStart = replacesPlatformStart; this.replacesPlatformStart = replacesPlatformStart;
this.identity = identity;
this.jigsaw = jigsaw; this.jigsaw = jigsaw;
this.memo = memo; this.memo = memo;
} }
/** A surface start of {@code structure} in chunk {@code chunkX, chunkZ}, planned at height {@code y}, with its /** A surface start of {@code structure} in chunk {@code chunkX, chunkZ}, planned at height {@code y}, with its
* registered definition, identity 0 and no memo. * registered definition and no memo.
*/ */
public static VanillaStructureStart at(ResourceId structure, int chunkX, int chunkZ, int y) { public static VanillaStructureStart at(ResourceId structure, int chunkX, int chunkZ, int y) {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, false, false, 0L, null, null); return new VanillaStructureStart(structure, chunkX, chunkZ, y, false, false, null, null);
} }
/** This start with the structure's lowest block at {@link #y()} instead of on the surface. */ /** This start with the structure's lowest block at {@link #y()} instead of on the surface. */
public VanillaStructureStart underground() { public VanillaStructureStart underground() {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, true, replacesPlatformStart, identity, jigsaw, memo); return new VanillaStructureStart(structure, chunkX, chunkZ, y, true, replacesPlatformStart, jigsaw, memo);
} }
/** This start, taking the chunk even where the platform already started the structure there. */ /** This start, taking the chunk even where the platform already started the structure there. */
public VanillaStructureStart replacingPlatformStart() { public VanillaStructureStart replacingPlatformStart() {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, identity, jigsaw, memo); return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, jigsaw, memo);
}
public VanillaStructureStart withIdentity(long identity) {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, memo);
} }
/** This start, assembled with {@code overrides} applied to a jigsaw structure's definition. Only jigsaw structures /** This start, assembled with {@code overrides} applied to a jigsaw structure's definition. Only jigsaw structures
* take overrides: the host fails the start of any other structure that has some. * take overrides: the host fails the start of any other structure that has some.
*/ */
public VanillaStructureStart withJigsaw(JigsawOverrides overrides) { public VanillaStructureStart withJigsaw(JigsawOverrides overrides) {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart,
Objects.requireNonNull(overrides, "overrides"), memo); Objects.requireNonNull(overrides, "overrides"), memo);
} }
/** This start with {@code memo}, which the host keeps with it and hands back in every later question about it. */ /** This start with {@code memo}, which the host keeps with it and hands back in every later question about it. */
public VanillaStructureStart withMemo(StartMemo memo) { public VanillaStructureStart withMemo(StartMemo memo) {
return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, jigsaw,
Objects.requireNonNull(memo, "memo")); Objects.requireNonNull(memo, "memo"));
} }
@@ -103,10 +95,6 @@ public final class VanillaStructureStart {
return replacesPlatformStart; return replacesPlatformStart;
} }
public long identity() {
return identity;
}
/** Changes to the jigsaw definition; empty assembles the registered definition as it is. */ /** Changes to the jigsaw definition; empty assembles the registered definition as it is. */
public Optional<JigsawOverrides> jigsaw() { public Optional<JigsawOverrides> jigsaw() {
return Optional.ofNullable(jigsaw); return Optional.ofNullable(jigsaw);
@@ -121,13 +109,13 @@ public final class VanillaStructureStart {
public boolean equals(Object other) { public boolean equals(Object other) {
return other instanceof VanillaStructureStart that && structure.equals(that.structure) && chunkX == that.chunkX return other instanceof VanillaStructureStart that && structure.equals(that.structure) && chunkX == that.chunkX
&& chunkZ == that.chunkZ && y == that.y && underground == that.underground && chunkZ == that.chunkZ && y == that.y && underground == that.underground
&& replacesPlatformStart == that.replacesPlatformStart && identity == that.identity && replacesPlatformStart == that.replacesPlatformStart
&& Objects.equals(jigsaw, that.jigsaw) && Objects.equals(memo, that.memo); && Objects.equals(jigsaw, that.jigsaw) && Objects.equals(memo, that.memo);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, memo); return Objects.hash(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, jigsaw, memo);
} }
@Override @Override
@@ -1,10 +1,9 @@
package com.volmit.config; package com.volmit.world;
import com.volmit.IrisFeature; import com.volmit.config.PackSettings;
import com.volmit.resource.PackResources; import com.volmit.resource.PackResources;
import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceId;
import java.util.Collection;
import java.util.Set; import java.util.Set;
/** /**
@@ -30,10 +29,11 @@ public interface LinkedBiomes {
* generation) without joining the region's biome tree. * generation) without joining the region's biome tree.
* *
* @param pack the pack the settings belong to, which turns their keys into ids * @param pack the pack the settings belong to, which turns their keys into ids
* @param dimension the settings the owner's dimension declares, for settings that name something the dimension * @param dimension what the owner's dimension itself declares, each type as a stack of at most its dimension entry,
* declares, such as a band of its caves * for settings that name something the dimension declares, such as a band of its caves. The
* dimension's regions and biomes are not in it: they are what the host is working out.
*/ */
default Set<ResourceId> usedBiomes(PackResources pack, Collection<IrisFeature> dimension) { default Set<ResourceId> usedBiomes(PackResources pack, PackSettings dimension) {
return Set.of(); return Set.of();
} }
} }
@@ -1,7 +1,6 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.IrisModule; import com.volmit.IrisModule;
import com.volmit.PackageName;
import java.util.Collection; import java.util.Collection;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
@@ -1,6 +1,5 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.PackageName;
import java.util.Collection; import java.util.Collection;
import java.util.List; import java.util.List;
@@ -1,13 +1,11 @@
package com.volmit.host; package com.volmit.host;
import com.volmit.ModuleInfo;
import com.volmit.PackageName;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
/** Classes a module jar uses that neither its pack, Iris nor the JDK has, usually optional /** Classes a module jar uses that neither its pack, Iris nor the JDK has, usually optional
* dependencies of a library the jar bundles, and that the jar's module does not declare * dependencies of a library the jar bundles, and that the jar's manifest does not declare optional
* {@linkplain ModuleInfo#optionalPackages() optional}. The jar still loads; code that needs one of * ({@value ModuleJar#OPTIONAL_PACKAGES_ATTRIBUTE}). The jar still loads; code that needs one of
* these classes throws {@link NoClassDefFoundError} when it runs. * these classes throws {@link NoClassDefFoundError} when it runs.
* *
* @param origin the jar path relative to its pack * @param origin the jar path relative to its pack
@@ -12,6 +12,7 @@ import java.net.URL;
import java.nio.charset.StandardCharsets; import java.nio.charset.StandardCharsets;
import java.nio.file.Path; import java.nio.file.Path;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator; import java.util.Comparator;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
@@ -19,6 +20,7 @@ import java.util.SortedSet;
import java.util.function.Predicate; import java.util.function.Predicate;
import java.util.jar.JarEntry; import java.util.jar.JarEntry;
import java.util.jar.JarFile; import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipFile; import java.util.zip.ZipFile;
/** One jar in a pack's modules directory, the entry classes it names and the classes it holds, /** One jar in a pack's modules directory, the entry classes it names and the classes it holds,
@@ -31,9 +33,15 @@ import java.util.zip.ZipFile;
* modules as it lists. The host reads that file from this jar only: * modules as it lists. The host reads that file from this jar only:
* {@code ServiceLoader} would also return providers from parent class loaders and could not tell * {@code ServiceLoader} would also return providers from parent class loaders and could not tell
* which jar a broken entry came from. * which jar a broken entry came from.
*
* <p>The optional packages are those the jar's manifest lists under {@value #OPTIONAL_PACKAGES_ATTRIBUTE}, separated
* by spaces or commas: packages, with their subpackages, whose classes the jar uses but expects may be absent.
*/ */
record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarClass> classes) { record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarClass> classes,
List<PackageName> optionalPackages) {
static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName(); static final String ENTRY_POINT_FILE = "META-INF/services/" + IrisModule.class.getName();
static final String OPTIONAL_PACKAGES_ATTRIBUTE = "Iris-Optional-Packages";
private static final String OPTIONAL_PACKAGE_SEPARATORS = "[\\s,]+";
private static final String COMMENT_START = "#"; private static final String COMMENT_START = "#";
private static final String CLASS_FILE_SUFFIX = ".class"; private static final String CLASS_FILE_SUFFIX = ".class";
private static final String MODULE_DESCRIPTOR = "module-info" + CLASS_FILE_SUFFIX; private static final String MODULE_DESCRIPTOR = "module-info" + CLASS_FILE_SUFFIX;
@@ -44,6 +52,7 @@ record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarCl
Objects.requireNonNull(origin, "origin"); Objects.requireNonNull(origin, "origin");
entryClasses = List.copyOf(entryClasses); entryClasses = List.copyOf(entryClasses);
classes = List.copyOf(classes); classes = List.copyOf(classes);
optionalPackages = List.copyOf(optionalPackages);
} }
/** A class in the jar, by binary name, and the binary names of the classes it links against. */ /** A class in the jar, by binary name, and the binary names of the classes it links against. */
@@ -63,7 +72,8 @@ record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarCl
try (var file = openAsClassLoaderSeesIt(jar)) { try (var file = openAsClassLoaderSeesIt(jar)) {
var entryClasses = requireEntryClasses(origin, readEntryClasses(file)); var entryClasses = requireEntryClasses(origin, readEntryClasses(file));
var classEntries = findClassEntries(file); var classEntries = findClassEntries(file);
return new ModuleJar(jar, origin, entryClasses, readClasses(origin, file, classEntries)); return new ModuleJar(jar, origin, entryClasses, readClasses(origin, file, classEntries),
readOptionalPackages(origin, file.getManifest()));
} catch (IOException exception) { } catch (IOException exception) {
throw new ModuleLoadException(null, origin, "Module jar " + origin + " is not a readable jar", exception); throw new ModuleLoadException(null, origin, "Module jar " + origin + " is not a readable jar", exception);
} }
@@ -96,6 +106,22 @@ record ModuleJar(Path path, String origin, List<String> entryClasses, List<JarCl
return DiscoveredModule.fromJar(module, readIdentity(entryClass, module), origin); return DiscoveredModule.fromJar(module, readIdentity(entryClass, module), origin);
} }
private static List<PackageName> readOptionalPackages(String origin, Manifest manifest) {
var declared = manifest == null ? null : manifest.getMainAttributes().getValue(OPTIONAL_PACKAGES_ATTRIBUTE);
if (declared == null || declared.isBlank()) {
return List.of();
}
return Arrays.stream(declared.trim().split(OPTIONAL_PACKAGE_SEPARATORS))
.map(name -> requireOptionalPackage(origin, name))
.toList();
}
private static PackageName requireOptionalPackage(String origin, String name) {
return PackageName.tryParse(name).orElseThrow(() -> ModuleLoadException.ofJar(origin, "Module jar " + origin
+ " declares optional package '" + name + "' in " + OPTIONAL_PACKAGES_ATTRIBUTE + ", which is not a package"
+ " name; name a package such as org.slf4j, which covers that package and its subpackages"));
}
/** Opens the jar with the runtime's multi-release version, like the pack class loader does, so /** Opens the jar with the runtime's multi-release version, like the pack class loader does, so
* class names below match the classes that loader can define. * class names below match the classes that loader can define.
*/ */
@@ -35,7 +35,7 @@ import java.util.stream.Stream;
* a class that Iris hides from modules or that is missing from an exposed package. * a class that Iris hides from modules or that is missing from an exposed package.
* Classes that nobody has are not an error, because the JVM only needs them when code that uses * Classes that nobody has are not an error, because the JVM only needs them when code that uses
* them runs; they are reported as {@link #missingClasses()}, except those in the optional packages * them runs; they are reported as {@link #missingClasses()}, except those in the optional packages
* the jar's module declares in its {@link com.volmit.ModuleInfo}. * the jar's manifest declares ({@value ModuleJar#OPTIONAL_PACKAGES_ATTRIBUTE}).
* *
* <p>A successful load logs one INFO summary of the pack's modules through a {@link System.Logger}, by * <p>A successful load logs one INFO summary of the pack's modules through a {@link System.Logger}, by
* default the one named after this class, or the host's from {@link ModuleHost#loggingTo}, and one * default the one named after this class, or the host's from {@link ModuleHost#loggingTo}, and one
@@ -188,7 +188,7 @@ public final class PackModules implements AutoCloseable {
var loader = newPackClassLoader(packRoot, jars, host); var loader = newPackClassLoader(packRoot, jars, host);
try { try {
var modules = createModules(jars, loader, snapshot, logger); var modules = createModules(jars, loader, snapshot, logger);
return new PackModules(modules, withoutDeclaredOptional(missingClasses, modules), loader, snapshot); return new PackModules(modules, withoutDeclaredOptional(missingClasses, jars), loader, snapshot);
} catch (RuntimeException | Error failure) { } catch (RuntimeException | Error failure) {
closeAfterFailure(loader, failure); closeAfterFailure(loader, failure);
throw failure; throw failure;
@@ -219,16 +219,11 @@ public final class PackModules implements AutoCloseable {
.toList(); .toList();
} }
/** A module's optional packages excuse only its own jar's missing classes; a jar with several /** A jar's optional packages excuse only its own missing classes; errors were decided before and never depend on them. */
* modules is excused by the optional packages of all of them. They are read from {@code info()}, private static List<MissingClasses> withoutDeclaredOptional(List<MissingClasses> missingClasses, List<ModuleJar> jars) {
* so this runs after the entry classes exist; errors were decided before that and never depend on them. var optionalPackages = jars.stream().collect(Collectors.toMap(ModuleJar::origin, ModuleJar::optionalPackages));
*/
private static List<MissingClasses> withoutDeclaredOptional(List<MissingClasses> missingClasses, List<DiscoveredModule> modules) {
var optionalPackages = modules.stream()
.collect(Collectors.groupingBy(DiscoveredModule::origin,
Collectors.flatMapping(found -> found.info().optionalPackages().stream(), Collectors.toList())));
return missingClasses.stream() return missingClasses.stream()
.map(jar -> jar.outside(optionalPackages.get(jar.origin()))) .map(jar -> jar.outside(optionalPackages.getOrDefault(jar.origin(), List.of())))
.filter(Predicate.not(MissingClasses::isEmpty)) .filter(Predicate.not(MissingClasses::isEmpty))
.toList(); .toList();
} }
@@ -1,4 +1,4 @@
package com.volmit; package com.volmit.host;
import java.util.Arrays; import java.util.Arrays;
import java.util.Objects; import java.util.Objects;
@@ -8,7 +8,7 @@ import java.util.Optional;
* names match: {@code com.volmit} contains {@code com.volmit.stage.Stage} but not * names match: {@code com.volmit} contains {@code com.volmit.stage.Stage} but not
* {@code com.volmitx.Fake}. * {@code com.volmitx.Fake}.
*/ */
public record PackageName(String name) implements Comparable<PackageName> { record PackageName(String name) implements Comparable<PackageName> {
private static final char SEPARATOR = '.'; private static final char SEPARATOR = '.';
private static final String SEPARATOR_PATTERN = "\\."; private static final String SEPARATOR_PATTERN = "\\.";
@@ -79,23 +79,6 @@ class ApiValuesTest {
assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0")); assertThrows(NullPointerException.class, () -> ModuleInfo.of("example:moss", null, "1.0.0"));
} }
@Test
void moduleInfoDeclaresOptionalPackagesWithTheirSubpackages() {
var plain = ModuleInfo.of("example:moss", "Moss", "1.0.0");
var info = plain.withOptionalPackages("org.slf4j", "org.apache.logging.");
assertEquals(List.of(), plain.optionalPackages());
assertEquals(List.of(new PackageName("org.slf4j"), new PackageName("org.apache.logging")), info.optionalPackages());
assertEquals(List.of(), info.withOptionalPackages().optionalPackages());
assertTrue(info.optionalPackages().getFirst().contains("org.slf4j.spi.LocationAwareLogger"));
assertFalse(info.optionalPackages().getFirst().contains("org.slf4jx.Logger"));
for (var invalid : List.of("", "org.*", "org..slf4j", "1org")) {
var failure = assertThrows(IllegalArgumentException.class, () -> plain.withOptionalPackages(invalid));
assertTrue(failure.getMessage().startsWith("Optional package '" + invalid + "' of module example:moss is not a package name"),
failure.getMessage());
}
}
@Test @Test
void moduleInfoTextFitsOnOneLogLine() { void moduleInfoTextFitsOnOneLogLine() {
for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) { for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) {
@@ -155,10 +138,10 @@ class ApiValuesTest {
@Test @Test
void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() { void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() {
var object = new GeneratedObject(new BlockBox(-1, -1, -1, 2, 2, 2), new BlockPosition(1, 1, 1), List.of(), List.of()); var object = new GeneratedObject(new BlockBox(-1, -1, -1, 2, 2, 2), new BlockPosition(1, 1, 1), List.of(), List.of());
var request = new PlacementRequest(ResourceId.parse("test:placement"), object, new BlockPosition(-16, 64, -16)); var request = new PlacementRequest(object, new BlockPosition(-16, 64, -16));
assertEquals(new BlockPosition(-16, 64, -16), request.worldPosition(object.anchor())); assertEquals(new BlockPosition(-16, 64, -16), request.worldPosition(object.anchor()));
assertEquals(new BlockBox(-18, 62, -18, -15, 65, -15), request.footprint()); assertEquals(new BlockBox(-18, 62, -18, -15, 65, -15), request.footprint());
var overflow = new PlacementRequest(request.id(), object, new BlockPosition(Integer.MAX_VALUE, 0, 0)); var overflow = new PlacementRequest(object, new BlockPosition(Integer.MAX_VALUE, 0, 0));
assertThrows(ArithmeticException.class, overflow::footprint); assertThrows(ArithmeticException.class, overflow::footprint);
} }
@@ -104,17 +104,16 @@ class VanillaStructureValuesTest {
assertFalse(start.isUnderground()); assertFalse(start.isUnderground());
assertFalse(start.replacesPlatformStart()); assertFalse(start.replacesPlatformStart());
assertEquals(Optional.empty(), start.memo()); assertEquals(Optional.empty(), start.memo());
var memo = new StartMemo("{\"mode\":\"VACUUM\"}", "null"); var memo = new StartMemo("{\"mode\":\"VACUUM\"}");
assertEquals(Optional.of(memo), start.withMemo(memo).memo()); assertEquals(Optional.of(memo), start.withMemo(memo).memo());
assertNotEquals(start, start.withMemo(memo)); assertNotEquals(start, start.withMemo(memo));
assertEquals(Optional.empty(), start.jigsaw()); assertEquals(Optional.empty(), start.jigsaw());
var underground = start.underground().replacingPlatformStart().withIdentity(-5L) var underground = start.underground().replacingPlatformStart()
.withJigsaw(JigsawOverrides.none().withMaxDepth(3)); .withJigsaw(JigsawOverrides.none().withMaxDepth(3));
assertTrue(underground.isUnderground()); assertTrue(underground.isUnderground());
assertTrue(underground.replacesPlatformStart()); assertTrue(underground.replacesPlatformStart());
assertEquals(-5L, underground.identity());
assertEquals(Optional.of(JigsawOverrides.none().withMaxDepth(3)), underground.jigsaw()); assertEquals(Optional.of(JigsawOverrides.none().withMaxDepth(3)), underground.jigsaw());
assertEquals(underground, start.withIdentity(-5L).replacingPlatformStart().underground() assertEquals(underground, start.replacingPlatformStart().underground()
.withJigsaw(JigsawOverrides.none().withMaxDepth(3))); .withJigsaw(JigsawOverrides.none().withMaxDepth(3)));
} }
@@ -133,9 +132,6 @@ class VanillaStructureValuesTest {
assertEquals(StartReach.PLATFORM, provider.reach(CITY, true, Optional.empty(), null)); assertEquals(StartReach.PLATFORM, provider.reach(CITY, true, Optional.empty(), null));
assertEquals(VanillaStructureSetup.UNCHANGED, provider.setup(null)); assertEquals(VanillaStructureSetup.UNCHANGED, provider.setup(null));
assertEquals(VanillaStructureRule.GENERATE, new VanillaStructures() { }.rule(CITY, null)); assertEquals(VanillaStructureRule.GENERATE, new VanillaStructures() { }.rule(CITY, null));
assertEquals(Set.of(), provider.startedStructures(null));
assertEquals(Set.of(), provider.locatableStarts(null));
assertEquals(LocateResult.NOT_FOUND, provider.locateStart(null, CITY, 0, 0, 8, (chunkX, chunkZ) -> true));
} }
@Test @Test
@@ -158,6 +154,9 @@ class VanillaStructureValuesTest {
}; };
assertEquals(Set.of(CASTLE), locator.placed(null)); assertEquals(Set.of(CASTLE), locator.placed(null));
assertEquals(Set.of(), locator.startedStructures(null), "a locator that starts no platform structure finds none");
assertEquals(Set.of(), locator.locatableStarts(null));
assertEquals(LocateResult.NOT_FOUND, locator.locateStart(null, CITY, 0, 0, 8, (chunkX, chunkZ) -> true));
} }
@Test @Test
@@ -100,7 +100,7 @@ class PlacementLifecyclePortTest {
new ObjectBlock(new BlockPosition(1, 0, 0), PLANKS), new ObjectBlock(new BlockPosition(1, 0, 0), PLANKS),
new ObjectBlock(new BlockPosition(1, 1, 0), PLANKS)), new ObjectBlock(new BlockPosition(1, 1, 0), PLANKS)),
List.of()); List.of());
return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 0, 0)); return new PlacementRequest(object,new BlockPosition(0, 0, 0));
} }
private static TestTerrain terrain() { private static TestTerrain terrain() {
@@ -6,6 +6,6 @@ import com.volmit.geometry.BlockPosition;
/** The world position the object's local anchor is placed at. */ /** The world position the object's local anchor is placed at. */
public record AnchorResult(BlockPosition anchor) { public record AnchorResult(BlockPosition anchor) {
public BlockPosition worldPosition(PlacementRequest request, BlockPosition local) { public BlockPosition worldPosition(PlacementRequest request, BlockPosition local) {
return new PlacementRequest(request.id(), request.object(), anchor).worldPosition(local); return new PlacementRequest(request.object(), anchor).worldPosition(local);
} }
} }
@@ -179,7 +179,7 @@ class PackModulesTest {
} }
@Test @Test
void optionalPackagesOfAnyModuleOfAJarExcuseItsMissingClasses(@TempDir Path build) { void aJarsOptionalPackagesExcuseTheMissingClassesOfAllItsModules(@TempDir Path build) {
module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_SETUP) module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_SETUP)
.alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_SETUP) .alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_SETUP)
.compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS)) .compileAgainst(library(build, "optional.jar", OPTIONAL_CLASS))
@@ -460,8 +460,8 @@ class PackModulesTest {
module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_SETUP).writeInto(pack, "user.jar"); module("pack.user.User", "user:core", List.of("org.*"), NO_MEMBERS, NO_SETUP).writeInto(pack, "user.jar");
assertMentions(failure(() -> PackModules.load(pack)), assertMentions(failure(() -> PackModules.load(pack)),
"Module jar " + origin("user.jar") + " has a broken entry point pack.user.User: info() failed", "Module jar " + origin("user.jar") + " declares optional package 'org.*' in Iris-Optional-Packages,"
"Optional package 'org.*' of module user:core is not a package name"); + " which is not a package name");
} }
@Test @Test
@@ -80,7 +80,7 @@ class StageGraphTest {
var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0), var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0),
List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)), List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)),
List.of()); List.of());
return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0)); return new PlacementRequest(object,new BlockPosition(0, 10, 0));
} }
private static MemoryEdit flatEdit() { private static MemoryEdit flatEdit() {
@@ -51,7 +51,7 @@ class StageStreamsTest {
private static PlacementRequest request() { private static PlacementRequest request() {
var blocks = IntStream.range(0, BLOCKS).mapToObj(x -> new ObjectBlock(new BlockPosition(x, 0, 0), STONE)).toList(); var blocks = IntStream.range(0, BLOCKS).mapToObj(x -> new ObjectBlock(new BlockPosition(x, 0, 0), STONE)).toList();
var object = new GeneratedObject(new BlockBox(0, 0, 0, BLOCKS, 1, 1), new BlockPosition(0, 0, 0), blocks, List.of()); var object = new GeneratedObject(new BlockBox(0, 0, 0, BLOCKS, 1, 1), new BlockPosition(0, 0, 0), blocks, List.of());
return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0)); return new PlacementRequest(object,new BlockPosition(0, 10, 0));
} }
private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) { private Map<String, List<Long>> place(ResolvedGraph graph, long invocationSeed) {
@@ -33,7 +33,9 @@ public final class TestModuleJar {
private final Map<String, String> sources = new LinkedHashMap<>(); private final Map<String, String> sources = new LinkedHashMap<>();
private final Map<String, byte[]> resources = new LinkedHashMap<>(); private final Map<String, byte[]> resources = new LinkedHashMap<>();
private static final String OPTIONAL_PACKAGES_ATTRIBUTE = "Iris-Optional-Packages";
private boolean multiRelease; private boolean multiRelease;
private final List<String> optionalPackages = new ArrayList<>();
private final List<String> entryPoints = new ArrayList<>(); private final List<String> entryPoints = new ArrayList<>();
private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class))); private final List<Path> classpath = new ArrayList<>(List.of(classesOf(IrisModule.class)));
private final List<String> compilerExports = new ArrayList<>(); private final List<String> compilerExports = new ArrayList<>();
@@ -43,15 +45,16 @@ public final class TestModuleJar {
return module(className, moduleId, List.of(), members, install); return module(className, moduleId, List.of(), members, install);
} }
/** Like {@link #module(String, String, String, String)}, with {@code info()} declaring {@code optionalPackages}. */ /** Like {@link #module(String, String, String, String)}, in a jar whose manifest declares {@code optionalPackages}. */
public static TestModuleJar module(String className, String moduleId, List<String> optionalPackages, String members, String install) { public static TestModuleJar module(String className, String moduleId, List<String> optionalPackages, String members, String install) {
var info = moduleInfo(moduleId, optionalPackages); var jar = new TestModuleJar();
return new TestModuleJar().source(className, moduleSource(className, info, members, install)).entryPoint(className); jar.optionalPackages.addAll(optionalPackages);
return jar.source(className, moduleSource(className, moduleInfo(moduleId), members, install)).entryPoint(className);
} }
/** Another entry class in the same jar, with the given module id; see {@link #module(String, String, String, String)}. */ /** Another entry class in the same jar, with the given module id; see {@link #module(String, String, String, String)}. */
public TestModuleJar alsoModule(String className, String moduleId, String members, String install) { public TestModuleJar alsoModule(String className, String moduleId, String members, String install) {
var info = moduleInfo(moduleId, List.of()); var info = moduleInfo(moduleId);
return source(className, moduleSource(className, info, members, install)).entryPoint(className); return source(className, moduleSource(className, info, members, install)).entryPoint(className);
} }
@@ -159,6 +162,9 @@ public final class TestModuleJar {
var manifest = new Manifest(); var manifest = new Manifest();
manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0");
if (multiRelease) manifest.getMainAttributes().put(Attributes.Name.MULTI_RELEASE, "true"); if (multiRelease) manifest.getMainAttributes().put(Attributes.Name.MULTI_RELEASE, "true");
if (!optionalPackages.isEmpty()) {
manifest.getMainAttributes().putValue(OPTIONAL_PACKAGES_ATTRIBUTE, String.join(" ", optionalPackages));
}
return manifest; return manifest;
} }
@@ -177,11 +183,8 @@ public final class TestModuleJar {
output.closeEntry(); output.closeEntry();
} }
private static String moduleInfo(String moduleId, List<String> optionalPackages) { private static String moduleInfo(String moduleId) {
var info = "ModuleInfo.of(\"%s\", \"%s\", \"1.0.0\")".formatted(moduleId, displayName(moduleId)); return "ModuleInfo.of(\"%s\", \"%s\", \"1.0.0\")".formatted(moduleId, displayName(moduleId));
if (optionalPackages.isEmpty()) return info;
var packages = optionalPackages.stream().map(name -> '"' + name + '"').collect(Collectors.joining(", "));
return info + ".withOptionalPackages(" + packages + ")";
} }
private static String moduleSource(String className, String info, String members, String install) { private static String moduleSource(String className, String info, String members, String install) {