diff --git a/CONTRACTS.md b/CONTRACTS.md index 59826f03f..5dfb1b399 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -7,7 +7,7 @@ types that carry them and lists what the Iris adapter still owes. | 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` | | 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 | @@ -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`) | | 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` | -| 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` | | 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()` | | 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` | -| 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` | | Dense chunk output | `Hunk`, `GenerationContext.blocks`, reference `ArrayHunk` | | Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` | @@ -78,8 +78,8 @@ with `--add-exports /=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 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 -its package is one the module declares optional with `ModuleInfo.withOptionalPackages(...)` -(`PackageName`). That declaration never excuses a load error. +its package is one the jar's manifest declares optional (`Iris-Optional-Packages`, read by the host's +`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, 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. - 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, - apply its jigsaw overrides, keep its memo, record its identity with every start the host publishes, and ask again (same - answer) when locating or verifying a start found in the world. -- Send the platform's locate of a structure some provider lists in `startedStructures` to that provider's - `locateStart` (module id order, the first that lists it in `locatableStarts`), convert the start's Y to the platform's, + apply its jigsaw overrides, keep its memo, and ask again (same answer) when locating or verifying a start found in + the world. +- Send the platform's locate of a structure some `StructureLocator` provider lists in `startedStructures` to that + 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. 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 diff --git a/DESIGN.md b/DESIGN.md index c561f8f2a..6f843facd 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -43,7 +43,9 @@ flowchart TD ## Module loading 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 `/modules/*.jar`, one or more modules per jar. 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`. 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. -10. Drops each jar's missing classes that lie in the optional packages its module declares in - `info()`. +10. Drops each jar's missing classes that lie in the optional packages its manifest declares + (`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. 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 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 -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 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 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 | -| 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 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 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() { - return ModuleInfo.of("example:moss", "Moss", "1.0.0") - .withOptionalPackages("org.slf4j", "org.apache.logging.log4j"); -} +``` +Iris-Optional-Packages: org.slf4j org.apache.logging.log4j ``` 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 -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 -load reports as a broken entry point of the jar. +affected. A jar with several modules declares once for all of them. Invalid names fail the load +when the jar is read, naming the jar. -The declaration lives in the entry point because all module metadata does. That fixes its timing: -`info()` exists only once the entry class is defined, after the reference check. This is safe -because 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 +The declaration lives in the manifest because it is about the jar, not about any one module: a jar shades a +library for all of its modules, and the host already applied the declarations per jar. It used to be +`ModuleInfo.withOptionalPackages`, which put class loading mechanics into a module's identity and could only be +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 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. @@ -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, 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 | | --- | --- | --- | | `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. - **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 - bottom, surface or underground, whether it takes the chunk from a platform start, jigsaw overrides, a memo, and an - identity the host persists with the start so a start found in a saved world can be traced to its placement. Across + bottom, surface or underground, whether it takes the chunk from a platform start, jigsaw overrides and a memo. No + 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` plus a `TerrainSampler`. - **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 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. -- **A memo instead of a persisted fit.** A start a module places carries a `StartMemo` (two texts, the module's to - fill). The host stores it with the start's ownership record and hands it back in `reach` and in every chunk's - `StructureFit`, so a start fits the same in every chunk it reaches, also after a restart or a pack change. Iris's - structure module writes its terrain and stilts JSON there, in the two places records always held them, so records - written before read the same. +- **A memo instead of a persisted fit.** A start a module places carries a `StartMemo` (one opaque, non-empty text, + the module's to fill and parse). The host stores it with the start's ownership record and hands it back in `reach` + and in every chunk's `StructureFit`, so a start fits the same in every chunk it reaches, also after a restart or a + pack change. Iris's structure module writes one JSON object of its terrain and stilts there; how many parts a memo + 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 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 @@ -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 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. -- **Reading.** The host creates the instance with that constructor and reads the JSON into it, exactly as it - decodes settings, so a missing field keeps its default and studio's defaults are what packs get. +- **Reading.** The host creates the instance with that constructor and reads the JSON into it under the + 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 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. @@ -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 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 - 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 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 diff --git a/README.md b/README.md index b1cef642a..d70fa926e 100644 --- a/README.md +++ b/README.md @@ -416,8 +416,7 @@ modules/moss.jar com/example/moss/MossSettings.class ``` -`info()` gives the module id, display name and version, and optionally the packages whose classes -the module expects may be missing (see below). The host reads it once, when it finds the module. +`info()` gives the module id, display name and version. 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 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 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. -A module that expects such classes to be absent declares their packages in `info()`, and the -warning leaves them out: +### Optional packages -```java -public ModuleInfo info() { - return ModuleInfo.of("example:moss", "Moss", "1.0.0") - .withOptionalPackages("org.slf4j", "org.apache.logging.log4j"); // with subpackages +A jar that expects such classes to be absent declares their packages, with their subpackages, in its manifest, and +the warning leaves them out. Which classes a jar may miss is the jar's business, not a module's identity: + +```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 declared package. Package names follow the rules of exposed packages (whole packages, trailing dot 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 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. -- 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 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 - settings that name something the dimension declares, such as a band of its caves. The host asks every dimension and biome + objects, decorators and settings take part in generation. `dimension` is a `PackSettings` of what the owner's dimension + 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. - 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 @@ -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 | | `PaletteSpec` | `{"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}` or `"snippet/palette/"` | `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/"` | `resources.noise().sampler(style, seed)` gives a `NoiseSampler` | +| `NoiseStyle` | `{"style": "SIMPLEX", "zoom": 4, "fracture": {"style": "PERLIN", "multiplier": 2}}` or `"snippet/style/"` | `resources.noise().sampler(style, seed)` gives a `NoiseSampler` | | `StyledRange` | `{"min": 4, "max": 12, "style": {...}}` | `range.at(resources.noise(), seed, x, z)` | | `Range` | `{"min": 0, "max": 15}` | `contains(value)`, `pick(random)` | | `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 `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 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. @@ -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 `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 - 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 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 @@ -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`, 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). -- `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, - searched ring by ring through the module's own placement grids. The host sends the platform's `/locate` and its own - structure commands for those structures here, then checks the start it got in the world; `accepts` lets it skip chunks - it already refused. + +Finding the starts a module makes is `StructureLocator`'s, the one locating service: `startedStructures(world)`, +`locatableStarts(world)` and `locateStart(world, structure, fromX, fromZ, maxRings, accepts)` give the platform +structures the module starts itself, the ones of them it can find, and the nearest start of one, searched ring by ring +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 @Override @@ -697,12 +703,12 @@ public List starts(int chunkX, int chunkZ, VanillaStructu if (!castleChunk(context.world().seed(), chunkX, chunkZ)) return List.of(); int surface = context.terrain().surfaceHeight((chunkX << 4) + 8, (chunkZ << 4) + 8); 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 -a start it places; the host persists them with the start and hands them back in `reach` and in every chunk's +How a start meets the terrain is the module's: the API has no fit values. A `StartMemo` is one opaque, non-empty +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 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 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 -`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 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 -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: diff --git a/api/src/main/java/com/volmit/ModuleInfo.java b/api/src/main/java/com/volmit/ModuleInfo.java index 12356ffc9..c9fb2280e 100644 --- a/api/src/main/java/com/volmit/ModuleInfo.java +++ b/api/src/main/java/com/volmit/ModuleInfo.java @@ -1,8 +1,6 @@ package com.volmit; import com.volmit.resource.ResourceId; -import java.util.Arrays; -import java.util.List; import java.util.Objects; /** 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 * version must fit on one log line, so they reject control characters such as line breaks. * - *

Optional packages are packages, with their subpackages, whose classes the module's jar uses - * but expects may be absent at runtime, typically optional integrations of a library it bundles. - * 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. + *

What the module's jar needs at load, such as packages it expects may be missing, is the jar's, declared in its + * manifest (see README, "Optional packages"), not the module's identity. */ -public record ModuleInfo(ResourceId id, String name, String version, List optionalPackages) { +public record ModuleInfo(ResourceId id, String name, String version) { private static final String STAGE_SEPARATOR = "/"; public ModuleInfo { @@ -28,26 +24,10 @@ public record ModuleInfo(ResourceId id, String name, String version, List 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")); + return new ModuleInfo(ResourceId.parse(id), name, version); } /** Whether {@code stageId} may name a stage of this module: it starts with this module's id and '/'. */ diff --git a/api/src/main/java/com/volmit/block/BlockSpec.java b/api/src/main/java/com/volmit/block/BlockSpec.java index 7a7d1c3c7..68e984804 100644 --- a/api/src/main/java/com/volmit/block/BlockSpec.java +++ b/api/src/main/java/com/volmit/block/BlockSpec.java @@ -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 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 - * constructor and reads the JSON into it, and nothing changes it afterwards. Property values are text however the + * {@link BlockRegistry#blockEntity(BlockSpec)}. A spec is a value the host decodes as every settings class (see + * 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"}. */ @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.") 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 data = Map.of(); @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.") 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; - @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 tileData = Map.of(); private BlockSpec() { @@ -82,12 +82,12 @@ public final class BlockSpec { /** The block key as the pack wrote it. */ public String block() { - return block == null ? AIR : block; + return block; } /** The properties as the pack wrote them, as text. */ public Map data() { - return data == null ? Map.of() : Collections.unmodifiableMap(data); + return Collections.unmodifiableMap(data); } 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}. */ public Map tileData() { - return tileData == null ? Map.of() : Collections.unmodifiableMap(tileData); + return Collections.unmodifiableMap(tileData); } @Override diff --git a/api/src/main/java/com/volmit/block/PaletteSpec.java b/api/src/main/java/com/volmit/block/PaletteSpec.java index 35b828eca..9771f539f 100644 --- a/api/src/main/java/com/volmit/block/PaletteSpec.java +++ b/api/src/main/java/com/volmit/block/PaletteSpec.java @@ -16,26 +16,26 @@ import java.util.Objects; * at the position over {@code zoom} selects, each block counting {@link BlockSpec#weight() weight} times. * *

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 - * constructor and reads the JSON into; nothing changes it afterwards. + * ({@link BlockRegistry#palette(PaletteSpec, long)}). It is a value the host decodes as every settings class (see + * DESIGN.md, "Decoding contract"); nothing changes it afterwards. */ @Snippet("palette") -@Desc("A palette of materials") +@Desc("Blocks picked by noise, each as often as its weight") public final class PaletteSpec { private static final String DEFAULT_STYLE = "STATIC"; private static final double DEFAULT_ZOOM = 5; 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); @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; @Required @MinItems(1) - @Desc("The palette of blocks to be used in this layer") + @Desc("The blocks to pick from.") private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); 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. */ 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. */ @@ -73,7 +73,7 @@ public final class PaletteSpec { /** The blocks to pick from, as the pack wrote them. */ public List palette() { - return palette == null ? List.of() : Collections.unmodifiableList(palette); + return Collections.unmodifiableList(palette); } @Override diff --git a/api/src/main/java/com/volmit/config/Range.java b/api/src/main/java/com/volmit/config/Range.java index b6cee3184..dadd1c392 100644 --- a/api/src/main/java/com/volmit/config/Range.java +++ b/api/src/main/java/com/volmit/config/Range.java @@ -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}}, * 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") -@Desc("Represents a range") +@Desc("A span of numbers from min to max, both included") public final class Range { - @Desc("The minimum value") + @Desc("The lowest value.") private double min = 16; - @Desc("The maximum value") + @Desc("The highest value.") private double max = 32; private Range() { diff --git a/api/src/main/java/com/volmit/noise/NoiseStyle.java b/api/src/main/java/com/volmit/noise/NoiseStyle.java index d45fc9eda..e48d24095 100644 --- a/api/src/main/java/com/volmit/noise/NoiseStyle.java +++ b/api/src/main/java/com/volmit/noise/NoiseStyle.java @@ -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 * {@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 - * style distorts its coordinates and a cellular frequency turns it into cells. + * distorts its coordinates and a cellular frequency turns it into cells. * *

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") @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"; @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; - @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; - @Desc("Cell zooms") + @Desc("How far the cells are stretched.") private double cellularZoom = 1; @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; @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; @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; @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; - @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; @MinNumber(0.01562) @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; - @MinNumber(0) - @MaxNumber(8192) - @Desc("If the cache size is set above 0, this generator will be cached") - private int cacheSize = 0; - private NoiseStyle() { } @@ -77,7 +72,6 @@ public final class NoiseStyle { multiplier = copy.multiplier; fracture = copy.fracture; exponent = copy.exponent; - cacheSize = copy.cacheSize; } /** 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. */ public String style() { - return style == null ? FLAT : style; + return style; } public double cellularFrequency() { @@ -121,10 +115,14 @@ public final class NoiseStyle { 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() { return multiplier; } + /** The style whose noise moves the coordinates this style is sampled at, by its own {@link #multiplier}. */ public Optional fracture() { return Optional.ofNullable(fracture); } @@ -133,34 +131,29 @@ public final class NoiseStyle { return exponent; } - public int cacheSize() { - return cacheSize; - } - /** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */ public boolean isFlat() { - return FLAT.equals(style()) && expression == null && imageMap == null; + return FLAT.equals(style) && expression == null && imageMap == null; } @Override 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(cellularZoom, that.cellularZoom) == 0 && Double.compare(zoom, that.zoom) == 0 && Objects.equals(expression, that.expression) && Objects.equals(imageMap, that.imageMap) && 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 public int hashCode() { - return Objects.hash(style(), cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, - exponent, cacheSize); + return Objects.hash(style, cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, exponent); } @Override 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 + "]"; } } diff --git a/api/src/main/java/com/volmit/noise/StyledRange.java b/api/src/main/java/com/volmit/noise/StyledRange.java index 568b845d2..f52120b30 100644 --- a/api/src/main/java/com/volmit/noise/StyledRange.java +++ b/api/src/main/java/com/volmit/noise/StyledRange.java @@ -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: * {@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") -@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 { private static final String DEFAULT_STYLE = "STATIC"; - @Desc("The minimum value") + @Desc("The lowest value.") private double min = 16; - @Desc("The maximum value") + @Desc("The highest value.") 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 StyledRange() { @@ -43,14 +43,14 @@ public final class StyledRange { 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() { - 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. */ 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 @@ -61,25 +61,25 @@ public final class StyledRange { if (min == max) { return min; } - if (style().isFlat()) { + if (style.isFlat()) { 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 public boolean equals(Object other) { 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 public int hashCode() { - return Objects.hash(min, max, style()); + return Objects.hash(min, max, style); } @Override public String toString() { - return "StyledRange[" + min + ".." + max + ", " + style() + "]"; + return "StyledRange[" + min + ".." + max + ", " + style + "]"; } } diff --git a/api/src/main/java/com/volmit/placement/PlacementRequest.java b/api/src/main/java/com/volmit/placement/PlacementRequest.java index 0f6d4afea..964723f12 100644 --- a/api/src/main/java/com/volmit/placement/PlacementRequest.java +++ b/api/src/main/java/com/volmit/placement/PlacementRequest.java @@ -3,17 +3,14 @@ package com.volmit.placement; import com.volmit.geometry.BlockBox; import com.volmit.geometry.BlockPosition; import com.volmit.object.GeneratedObject; -import com.volmit.resource.ResourceId; 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 * above the dimension's bottom). * 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 { - Objects.requireNonNull(id, "id"); Objects.requireNonNull(object, "object"); Objects.requireNonNull(anchor, "anchor"); } diff --git a/api/src/main/java/com/volmit/service/StructureLocator.java b/api/src/main/java/com/volmit/service/StructureLocator.java index 47808623d..c00ca7a1b 100644 --- a/api/src/main/java/com/volmit/service/StructureLocator.java +++ b/api/src/main/java/com/volmit/service/StructureLocator.java @@ -5,10 +5,11 @@ import com.volmit.resource.ResourceId; import com.volmit.world.PackWorld; import java.util.Set; -/** Finds the structures a module places, for the host's structure commands and index. Structures are named by their - * ids: a pack's own structure by the id {@link PackResources#idOf} gives its key ({@code overworld:villages/plains}), +/** Finds the structures a module places, for the host's structure commands, index and locate. Structures are named by + * 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 - * 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) public interface StructureLocator { @@ -37,4 +38,37 @@ public interface StructureLocator { * host calls it off the server's main thread. */ 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 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 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); + } } diff --git a/api/src/main/java/com/volmit/service/VanillaStructures.java b/api/src/main/java/com/volmit/service/VanillaStructures.java index 49fa021d2..c23fbf36a 100644 --- a/api/src/main/java/com/volmit/service/VanillaStructures.java +++ b/api/src/main/java/com/volmit/service/VanillaStructures.java @@ -10,10 +10,8 @@ import com.volmit.vanilla.VanillaStructureRule; import com.volmit.vanilla.VanillaStructureSetup; import com.volmit.vanilla.VanillaStructureStart; import com.volmit.vanilla.VanillaStructureStartContext; -import com.volmit.world.PackWorld; import java.util.List; 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 * 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 * {@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 - * 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) public interface VanillaStructures { @@ -93,37 +92,4 @@ public interface VanillaStructures { default VanillaStructureSetup setup(VanillaStructureContext context) { 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 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 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); - } } diff --git a/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java b/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java index 4cf126114..727dd8ad8 100644 --- a/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java +++ b/api/src/main/java/com/volmit/vanilla/JigsawOverrides.java @@ -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 * 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 - * into. + * what the registered definition says. A value the host decodes as every settings class (see DESIGN.md, "Decoding + * 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 { /** What packs write as the start connector to remove the definition's constraint. */ private static final String NO_START_JIGSAW = "NONE"; /** 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 { - @Desc("Keeps the registered structure's own heightmap projection.") + @Desc("The definition's own heightmap.") SOURCE, @Desc("Removes heightmap projection: the start piece lands at the structure's literal start height.") NONE, @@ -42,9 +42,9 @@ public final class JigsawOverrides { } /** 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 { - @Desc("Keeps the registered structure's own liquid setting.") + @Desc("The definition's own liquid setting.") SOURCE, @Desc("Places pieces dry.") IGNORE_WATERLOGGING, @@ -52,45 +52,45 @@ public final class JigsawOverrides { 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) 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 = ""; @MinNumber(0) @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; @MinNumber(1) @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; @MinNumber(1) @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; - @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; - @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; @MinNumber(0) @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; @MinNumber(0) @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; - @Desc("Waterlogging override. SOURCE preserves the registered value.") + @Desc("Whether placed pieces take on the water they replace.") private Liquids liquidSettings = Liquids.SOURCE; private JigsawOverrides() { @@ -187,11 +187,11 @@ public final class JigsawOverrides { /** Whether the start connector constraint is removed, which packs write as {@code NONE}. */ public boolean removesStartJigsaw() { - return startJigsawName != null && NO_START_JIGSAW.equalsIgnoreCase(startJigsawName.trim()); + return NO_START_JIGSAW.equalsIgnoreCase(startJigsawName.trim()); } private static Optional 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() { @@ -210,9 +210,9 @@ public final class JigsawOverrides { 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() { - return projectStartToHeightmap == null ? Heightmap.SOURCE : projectStartToHeightmap; + return projectStartToHeightmap; } public OptionalInt dimensionPaddingBottom() { @@ -223,9 +223,9 @@ public final class JigsawOverrides { 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() { - return liquidSettings == null ? Liquids.SOURCE : liquidSettings; + return liquidSettings; } private static OptionalInt optional(Integer value) { @@ -256,8 +256,8 @@ public final class JigsawOverrides { 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) { - return key == null ? "" : key.trim(); + return key.trim(); } } diff --git a/api/src/main/java/com/volmit/vanilla/StartMemo.java b/api/src/main/java/com/volmit/vanilla/StartMemo.java index e57637ed6..effa6376a 100644 --- a/api/src/main/java/com/volmit/vanilla/StartMemo.java +++ b/api/src/main/java/com/volmit/vanilla/StartMemo.java @@ -2,15 +2,17 @@ package com.volmit.vanilla; 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 - * start meets the terrain and one about its foundation. The host keeps the memo with the start for as long as the world - * does and hands it back whenever it asks the module about the start again ({@link StructureFit.Start#memo()}, - * {@link com.volmit.service.VanillaStructures#reach}), so a start that spans many chunks is finished the way it was - * begun, even after the pack changed. The host never reads the texts. +/** What a module noted about a start it placed, for itself: one text in the module's own format. The host keeps the memo + * with the start for as long as the world does and hands it back whenever it asks the module about the start again + * ({@link StructureFit.Start#memo()}, {@link com.volmit.service.VanillaStructures#reach}), so a start that spans many + * chunks is finished the way it was begun, even after the pack changed. The host never reads the text, which is not + * 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 { - Objects.requireNonNull(terrain, "terrain"); - Objects.requireNonNull(foundation, "foundation"); + Objects.requireNonNull(text, "text"); + if (text.isEmpty()) { + throw new IllegalArgumentException("A start memo's text must not be empty; give the start no memo instead"); + } } } diff --git a/api/src/main/java/com/volmit/vanilla/VanillaStructureStart.java b/api/src/main/java/com/volmit/vanilla/VanillaStructureStart.java index 7ff666429..f1f4ceb58 100644 --- a/api/src/main/java/com/volmit/vanilla/VanillaStructureStart.java +++ b/api/src/main/java/com/volmit/vanilla/VanillaStructureStart.java @@ -13,10 +13,9 @@ import java.util.Optional; * the chunk win unless the start {@link #replacesPlatformStart() replaces} them or the structure is * {@link VanillaStructureRule#REPLACE replaced} by a module. * - *

{@link #identity()} names what placed the start, stable for one pack: the host records it with every start it - * publishes, so a start found in the world later can be traced back to its placement. The {@link #memo() memo} is kept - * with that record and handed back whenever the host asks the module about the start again, so a start that spans many - * chunks keeps what the module decided for it when it was placed, even after the pack changed. + *

The {@link #memo() memo} is kept with the start and handed back whenever the host asks the module about the start + * again, so a start that spans many chunks keeps what the module decided for it when it was placed, even after the pack + * changed. */ public final class VanillaStructureStart { private final ResourceId structure; @@ -25,56 +24,49 @@ public final class VanillaStructureStart { private final int y; private final boolean underground; private final boolean replacesPlatformStart; - private final long identity; private final JigsawOverrides jigsaw; private final StartMemo memo; private VanillaStructureStart(ResourceId structure, int chunkX, int chunkZ, int y, boolean underground, - boolean replacesPlatformStart, long identity, JigsawOverrides jigsaw, - StartMemo memo) { + boolean replacesPlatformStart, JigsawOverrides jigsaw, StartMemo memo) { this.structure = Objects.requireNonNull(structure, "structure"); this.chunkX = chunkX; this.chunkZ = chunkZ; this.y = y; this.underground = underground; this.replacesPlatformStart = replacesPlatformStart; - this.identity = identity; this.jigsaw = jigsaw; this.memo = memo; } /** 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) { - 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. */ 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. */ public VanillaStructureStart replacingPlatformStart() { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, identity, jigsaw, memo); - } - - public VanillaStructureStart withIdentity(long identity) { - return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, replacesPlatformStart, identity, jigsaw, memo); + return new VanillaStructureStart(structure, chunkX, chunkZ, y, underground, true, jigsaw, memo); } /** 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. */ 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); } /** 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) { - 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")); } @@ -103,10 +95,6 @@ public final class VanillaStructureStart { return replacesPlatformStart; } - public long identity() { - return identity; - } - /** Changes to the jigsaw definition; empty assembles the registered definition as it is. */ public Optional jigsaw() { return Optional.ofNullable(jigsaw); @@ -121,13 +109,13 @@ public final class VanillaStructureStart { public boolean equals(Object other) { return other instanceof VanillaStructureStart that && structure.equals(that.structure) && chunkX == that.chunkX && 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); } @Override 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 diff --git a/api/src/main/java/com/volmit/config/LinkedBiomes.java b/api/src/main/java/com/volmit/world/LinkedBiomes.java similarity index 74% rename from api/src/main/java/com/volmit/config/LinkedBiomes.java rename to api/src/main/java/com/volmit/world/LinkedBiomes.java index 180665e7b..06ea2faf0 100644 --- a/api/src/main/java/com/volmit/config/LinkedBiomes.java +++ b/api/src/main/java/com/volmit/world/LinkedBiomes.java @@ -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.ResourceId; -import java.util.Collection; import java.util.Set; /** @@ -30,10 +29,11 @@ public interface LinkedBiomes { * generation) without joining the region's biome tree. * * @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 - * declares, such as a band of its caves + * @param dimension what the owner's dimension itself declares, each type as a stack of at most its dimension entry, + * 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 usedBiomes(PackResources pack, Collection dimension) { + default Set usedBiomes(PackResources pack, PackSettings dimension) { return Set.of(); } } diff --git a/host/src/main/java/com/volmit/host/ExposedPackages.java b/host/src/main/java/com/volmit/host/ExposedPackages.java index 197d4e62c..c80a8e47c 100644 --- a/host/src/main/java/com/volmit/host/ExposedPackages.java +++ b/host/src/main/java/com/volmit/host/ExposedPackages.java @@ -1,7 +1,6 @@ package com.volmit.host; import com.volmit.IrisModule; -import com.volmit.PackageName; import java.util.Collection; import java.util.Comparator; import java.util.List; diff --git a/host/src/main/java/com/volmit/host/HostTypes.java b/host/src/main/java/com/volmit/host/HostTypes.java index 98f7ec044..6e6da10c2 100644 --- a/host/src/main/java/com/volmit/host/HostTypes.java +++ b/host/src/main/java/com/volmit/host/HostTypes.java @@ -1,6 +1,5 @@ package com.volmit.host; -import com.volmit.PackageName; import java.util.Collection; import java.util.List; diff --git a/host/src/main/java/com/volmit/host/MissingClasses.java b/host/src/main/java/com/volmit/host/MissingClasses.java index 69ad8060f..c0d3b5a58 100644 --- a/host/src/main/java/com/volmit/host/MissingClasses.java +++ b/host/src/main/java/com/volmit/host/MissingClasses.java @@ -1,13 +1,11 @@ package com.volmit.host; -import com.volmit.ModuleInfo; -import com.volmit.PackageName; import java.util.List; import java.util.Objects; /** 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 - * {@linkplain ModuleInfo#optionalPackages() optional}. The jar still loads; code that needs one of + * dependencies of a library the jar bundles, and that the jar's manifest does not declare optional + * ({@value ModuleJar#OPTIONAL_PACKAGES_ATTRIBUTE}). The jar still loads; code that needs one of * these classes throws {@link NoClassDefFoundError} when it runs. * * @param origin the jar path relative to its pack diff --git a/host/src/main/java/com/volmit/host/ModuleJar.java b/host/src/main/java/com/volmit/host/ModuleJar.java index 4a0bd564b..5210558f1 100644 --- a/host/src/main/java/com/volmit/host/ModuleJar.java +++ b/host/src/main/java/com/volmit/host/ModuleJar.java @@ -12,6 +12,7 @@ import java.net.URL; import java.nio.charset.StandardCharsets; import java.nio.file.Path; import java.util.ArrayList; +import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Objects; @@ -19,6 +20,7 @@ import java.util.SortedSet; import java.util.function.Predicate; import java.util.jar.JarEntry; import java.util.jar.JarFile; +import java.util.jar.Manifest; import java.util.zip.ZipFile; /** 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: * {@code ServiceLoader} would also return providers from parent class loaders and could not tell * which jar a broken entry came from. + * + *

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 entryClasses, List classes) { +record ModuleJar(Path path, String origin, List entryClasses, List classes, + List optionalPackages) { 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 CLASS_FILE_SUFFIX = ".class"; private static final String MODULE_DESCRIPTOR = "module-info" + CLASS_FILE_SUFFIX; @@ -44,6 +52,7 @@ record ModuleJar(Path path, String origin, List entryClasses, List entryClasses, List entryClasses, List 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 * class names below match the classes that loader can define. */ diff --git a/host/src/main/java/com/volmit/host/PackModules.java b/host/src/main/java/com/volmit/host/PackModules.java index 33a82a85e..5b6988ccb 100644 --- a/host/src/main/java/com/volmit/host/PackModules.java +++ b/host/src/main/java/com/volmit/host/PackModules.java @@ -35,7 +35,7 @@ import java.util.stream.Stream; * 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 * 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}). * *

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 @@ -188,7 +188,7 @@ public final class PackModules implements AutoCloseable { var loader = newPackClassLoader(packRoot, jars, host); try { 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) { closeAfterFailure(loader, failure); throw failure; @@ -219,16 +219,11 @@ public final class PackModules implements AutoCloseable { .toList(); } - /** A module's optional packages excuse only its own jar's missing classes; a jar with several - * modules is excused by the optional packages of all of them. They are read from {@code info()}, - * so this runs after the entry classes exist; errors were decided before that and never depend on them. - */ - private static List withoutDeclaredOptional(List missingClasses, List modules) { - var optionalPackages = modules.stream() - .collect(Collectors.groupingBy(DiscoveredModule::origin, - Collectors.flatMapping(found -> found.info().optionalPackages().stream(), Collectors.toList()))); + /** A jar's optional packages excuse only its own missing classes; errors were decided before and never depend on them. */ + private static List withoutDeclaredOptional(List missingClasses, List jars) { + var optionalPackages = jars.stream().collect(Collectors.toMap(ModuleJar::origin, ModuleJar::optionalPackages)); 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)) .toList(); } diff --git a/api/src/main/java/com/volmit/PackageName.java b/host/src/main/java/com/volmit/host/PackageName.java similarity index 95% rename from api/src/main/java/com/volmit/PackageName.java rename to host/src/main/java/com/volmit/host/PackageName.java index 2fcce8b0c..53b21dfb4 100644 --- a/api/src/main/java/com/volmit/PackageName.java +++ b/host/src/main/java/com/volmit/host/PackageName.java @@ -1,4 +1,4 @@ -package com.volmit; +package com.volmit.host; import java.util.Arrays; 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 * {@code com.volmitx.Fake}. */ -public record PackageName(String name) implements Comparable { +record PackageName(String name) implements Comparable { private static final char SEPARATOR = '.'; private static final String SEPARATOR_PATTERN = "\\."; diff --git a/host/src/test/java/com/volmit/ApiValuesTest.java b/host/src/test/java/com/volmit/ApiValuesTest.java index 8cd873584..dd56100b0 100644 --- a/host/src/test/java/com/volmit/ApiValuesTest.java +++ b/host/src/test/java/com/volmit/ApiValuesTest.java @@ -79,23 +79,6 @@ class ApiValuesTest { 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 void moduleInfoTextFitsOnOneLogLine() { for (var broken : List.of("Moss\nINFO forged line", "Moss\r", "Moss\tTabbed", "Moss\u2028Next")) { @@ -155,10 +138,10 @@ class ApiValuesTest { @Test void placementAlignsAnchorsAndCheckedArithmeticNeverWraps() { 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 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); } diff --git a/host/src/test/java/com/volmit/VanillaStructureValuesTest.java b/host/src/test/java/com/volmit/VanillaStructureValuesTest.java index 89165748f..e3dae1246 100644 --- a/host/src/test/java/com/volmit/VanillaStructureValuesTest.java +++ b/host/src/test/java/com/volmit/VanillaStructureValuesTest.java @@ -104,17 +104,16 @@ class VanillaStructureValuesTest { assertFalse(start.isUnderground()); assertFalse(start.replacesPlatformStart()); 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()); assertNotEquals(start, start.withMemo(memo)); assertEquals(Optional.empty(), start.jigsaw()); - var underground = start.underground().replacingPlatformStart().withIdentity(-5L) + var underground = start.underground().replacingPlatformStart() .withJigsaw(JigsawOverrides.none().withMaxDepth(3)); assertTrue(underground.isUnderground()); assertTrue(underground.replacesPlatformStart()); - assertEquals(-5L, underground.identity()); 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))); } @@ -133,9 +132,6 @@ class VanillaStructureValuesTest { assertEquals(StartReach.PLATFORM, provider.reach(CITY, true, Optional.empty(), null)); assertEquals(VanillaStructureSetup.UNCHANGED, provider.setup(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 @@ -158,6 +154,9 @@ class VanillaStructureValuesTest { }; 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 diff --git a/host/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java b/host/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java index 25bb1976c..c409f7e5c 100644 --- a/host/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java +++ b/host/src/test/java/com/volmit/example/PlacementLifecyclePortTest.java @@ -100,7 +100,7 @@ class PlacementLifecyclePortTest { new ObjectBlock(new BlockPosition(1, 0, 0), PLANKS), new ObjectBlock(new BlockPosition(1, 1, 0), PLANKS)), 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() { diff --git a/host/src/test/java/com/volmit/example/placement/AnchorResult.java b/host/src/test/java/com/volmit/example/placement/AnchorResult.java index 57e40e82a..77418d889 100644 --- a/host/src/test/java/com/volmit/example/placement/AnchorResult.java +++ b/host/src/test/java/com/volmit/example/placement/AnchorResult.java @@ -6,6 +6,6 @@ import com.volmit.geometry.BlockPosition; /** The world position the object's local anchor is placed at. */ public record AnchorResult(BlockPosition anchor) { 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); } } diff --git a/host/src/test/java/com/volmit/host/PackModulesTest.java b/host/src/test/java/com/volmit/host/PackModulesTest.java index ce040200d..76ecc0aab 100644 --- a/host/src/test/java/com/volmit/host/PackModulesTest.java +++ b/host/src/test/java/com/volmit/host/PackModulesTest.java @@ -179,7 +179,7 @@ class PackModulesTest { } @Test - void optionalPackagesOfAnyModuleOfAJarExcuseItsMissingClasses(@TempDir Path build) { + void aJarsOptionalPackagesExcuseTheMissingClassesOfAllItsModules(@TempDir Path build) { module("pack.First", "first:core", List.of("org.optional"), NO_MEMBERS, NO_SETUP) .alsoModule("pack.Second", "second:core", using(OPTIONAL_CLASS), NO_SETUP) .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"); assertMentions(failure(() -> PackModules.load(pack)), - "Module jar " + origin("user.jar") + " has a broken entry point pack.user.User: info() failed", - "Optional package 'org.*' of module user:core is not a package name"); + "Module jar " + origin("user.jar") + " declares optional package 'org.*' in Iris-Optional-Packages," + + " which is not a package name"); } @Test diff --git a/host/src/test/java/com/volmit/host/StageGraphTest.java b/host/src/test/java/com/volmit/host/StageGraphTest.java index 2d38064fe..428de6d2a 100644 --- a/host/src/test/java/com/volmit/host/StageGraphTest.java +++ b/host/src/test/java/com/volmit/host/StageGraphTest.java @@ -80,7 +80,7 @@ class StageGraphTest { var object = new GeneratedObject(new BlockBox(0, 0, 0, 2, 1, 1), new BlockPosition(0, 0, 0), List.of(new ObjectBlock(new BlockPosition(0, 0, 0), STONE), new ObjectBlock(new BlockPosition(1, 0, 0), STONE)), List.of()); - return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0)); + return new PlacementRequest(object,new BlockPosition(0, 10, 0)); } private static MemoryEdit flatEdit() { diff --git a/host/src/test/java/com/volmit/host/StageStreamsTest.java b/host/src/test/java/com/volmit/host/StageStreamsTest.java index 8de7e3f28..6339a4a6a 100644 --- a/host/src/test/java/com/volmit/host/StageStreamsTest.java +++ b/host/src/test/java/com/volmit/host/StageStreamsTest.java @@ -51,7 +51,7 @@ class StageStreamsTest { private static PlacementRequest request() { 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()); - return new PlacementRequest(ResourceId.parse("test:attempt"), object, new BlockPosition(0, 10, 0)); + return new PlacementRequest(object,new BlockPosition(0, 10, 0)); } private Map> place(ResolvedGraph graph, long invocationSeed) { diff --git a/host/src/test/java/com/volmit/support/TestModuleJar.java b/host/src/test/java/com/volmit/support/TestModuleJar.java index 7f966ece9..26945ebea 100644 --- a/host/src/test/java/com/volmit/support/TestModuleJar.java +++ b/host/src/test/java/com/volmit/support/TestModuleJar.java @@ -33,7 +33,9 @@ public final class TestModuleJar { private final Map sources = new LinkedHashMap<>(); private final Map resources = new LinkedHashMap<>(); + private static final String OPTIONAL_PACKAGES_ATTRIBUTE = "Iris-Optional-Packages"; private boolean multiRelease; + private final List optionalPackages = new ArrayList<>(); private final List entryPoints = new ArrayList<>(); private final List classpath = new ArrayList<>(List.of(classesOf(IrisModule.class))); private final List compilerExports = new ArrayList<>(); @@ -43,15 +45,16 @@ public final class TestModuleJar { 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 optionalPackages, String members, String install) { - var info = moduleInfo(moduleId, optionalPackages); - return new TestModuleJar().source(className, moduleSource(className, info, members, install)).entryPoint(className); + var jar = new TestModuleJar(); + 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)}. */ 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); } @@ -159,6 +162,9 @@ public final class TestModuleJar { var manifest = new Manifest(); manifest.getMainAttributes().put(Attributes.Name.MANIFEST_VERSION, "1.0"); if (multiRelease) manifest.getMainAttributes().put(Attributes.Name.MULTI_RELEASE, "true"); + if (!optionalPackages.isEmpty()) { + manifest.getMainAttributes().putValue(OPTIONAL_PACKAGES_ATTRIBUTE, String.join(" ", optionalPackages)); + } return manifest; } @@ -177,11 +183,8 @@ public final class TestModuleJar { output.closeEntry(); } - private static String moduleInfo(String moduleId, List optionalPackages) { - var info = "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 moduleInfo(String moduleId) { + return "ModuleInfo.of(\"%s\", \"%s\", \"1.0.0\")".formatted(moduleId, displayName(moduleId)); } private static String moduleSource(String className, String info, String members, String install) {