diff --git a/CONTRACTS.md b/CONTRACTS.md index 8b8ac2508..62c2c019c 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -25,7 +25,10 @@ types that carry them and lists what the Iris adapter still owes. | Area a stage writes | `reach(blocks)`, `reach(PackReach)`, `writesMantle(...)` on stage definitions, `PackSettings`, host `StageReach`, `ResolvedStage.reachBlocks`, `PipelineReach` | | Settings described for studio | `@Desc`, `@Required`, `@MinNumber`, `@MaxNumber`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema` with `shorthand()`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | -| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette` | +| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette`, `BlockSpec` (`BlockRegistry.resolve(BlockSpec)`, `blockEntity`) | +| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | +| Values in settings | `BlockSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `Object` as `ValueKind.AnyKind` | +| Decisions over the platform's own structures | `VanillaStructureHook`, `VanillaStructureRule`, `VanillaStructureContext`, `FeatureRegistry.registerVanillaStructureHook`, host `FeatureCatalog.vanillaStructureHooks()` | | Pack-scoped resolution | `ResourceId`, `ResourceKey`, `PackResources` (`find`, `ids`), `PackBiome`, `PackRegion` | | Module-owned pack resources | `ResourceKind`, `FeatureRegistry.registerResourceKind`, `@ResourceRef`, host `ModuleHost.reservingFolders`, `FeatureCatalog.resourceKinds()`, `ResourceKindSchema`, `ValueKind.ResourceReferenceKind` | | Module-owned pack checks | `Validator`, `ValidationContext`, `Problem`, `Severity`, `Subject`, `FeatureRegistry.registerValidator`, host `FeatureCatalog.validators()` | @@ -74,6 +77,10 @@ A resource kind reads one folder directly below the pack root, with a class no o kinds claim, or one the host reads itself, fails the pack load naming both owners. Resources of a kind are values, read once per pack snapshot. Validators only report: an `ERROR` blocks the pack, a `WARNING` is shown. +IrisApi's value types are values: the host decodes them like settings, and nothing changes them afterwards. +Noise belongs to the host; modules describe it and get samplers built from the description. A vanilla structure +hook answers per structure and world, never per position. + There is no API version gating. Packs ship their module jars, so their compatibility with the running Iris is the pack publisher's responsibility. @@ -151,6 +158,23 @@ running Iris is the pack publisher's responsibility. `ERROR` blocks the pack, a `WARNING` is shown; show each problem with its subject. A validator that throws is an error naming its module, and the others still run. +- Decode IrisApi's value types like settings: `BlockSpec`, `NoiseStyle`, `StyledRange`, `Range` and + `BlockPosition` from the JSON shapes in their docs, `Object` as maps, lists, `Double`s, strings and booleans. + Read a `"snippet/"` or `"snippet//"` string of a `@Snippet` type from + `snippet//.json`. Complete `NOISE_STYLE`, `PACK_EXPRESSION` and `PACK_IMAGE_MAP` references; + rendering a value type with the host's own description of the same JSON is allowed. +- Serve `PackResources.noise()`: build each style's noise from the host's generators, expressions and image maps, + the same values for the same style and seed, cached per pack snapshot; an unknown style name is flat. +- Resolve `BlockSpec`s in `BlockRegistry` as packs expect (pack block, platform block, backup, air) and turn their + `tileData` into the host's block entity format. +- Ask every vanilla structure hook (`catalog().vanillaStructureHooks()`) before the platform starts one of its + structures and when it locates one, combine the rules with `VanillaStructureRule.and`, keep the result per world, + structure and pack snapshot, and apply it on every platform: block the platform's starts of a blocked + structure, and report a structure a module places as that module's. A hook that throws fails naming its module. + ## Open +- Placing the platform's structures where a module chooses (Iris's native structure planner): a hook method + returning starts per chunk, with the terrain fitting and foundations the host builds around them. + - Terrain/biome providers, pack transformations, structure assembly and the runtime family. diff --git a/DESIGN.md b/DESIGN.md index 71643a3b7..3f012ca10 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -648,6 +648,7 @@ already keep module fields from colliding with them. | `Map` | `MapKind(V)` | | `String` with `@ResourceRef(Type.class)` | `ResourceReferenceKind(id of the kind read into Type)` | | a class in a host type package, in built-in settings | `HostKind(class name)` | +| `Object` | `AnyKind`: any JSON value | | any other concrete class | `ObjectKind(class name)` | Host types are classes the host describes in studio itself, such as Iris's palettes and noise styles, @@ -662,8 +663,10 @@ Everything else fails the load with the field, its settings and its module named instead: - `char` and `Character`: no settings use them, and JSON has no character type; -- JDK classes such as `UUID`, `Optional`, `BigDecimal` or `Object`, meaning classes of named modules - in the boot layer: the host would need a format for each; +- JDK classes such as `UUID`, `Optional` or `BigDecimal`, meaning classes of named modules in the boot + layer: the host would need a format for each. `Object` is the exception: it means any JSON value + (`AnyKind`), decoded as maps, lists, `Double`s, strings and booleans, for data whose shape belongs to + someone else, such as a block entity's data in a `BlockSpec`; - `ResourceKey`: its type argument is the Java class a resource loads as, which tells studio nothing it could list; `ResourceId` with `@Ref` says what a value names; - interfaces and abstract classes: their fields depend on the subclass a pack would pick; @@ -679,11 +682,12 @@ adding anything a pack can write. `@Ref(Reference.X)` says what a text value names. The kinds are a closed enum of what the Iris host can list today through its `RegistryList*` annotations: blocks, items, entities, platform biomes, -structures, potion effects and enchantments from the server registries, and biomes, regions and -objects of the pack, the resource folders Iris's own settings refer to most. More kinds come when a +structures, potion effects and enchantments from the server registries, the host's noise styles, and +biomes, regions, objects, expressions and image maps of the pack, the resource folders Iris's own settings +refer to most. More kinds come when a module needs one and the host can serve it. `@Ref` fits `String` and `ResourceId` and lists, sets and arrays of them, where it applies to the elements. On any other field, a map included, it fails the -load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`) fit `String` only: packs name their +load. The pack kinds (`PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION`, `PACK_IMAGE_MAP`) fit `String` only: packs name their biomes, regions and objects by path without a namespace, such as `desert/dunes`, which a `ResourceId` cannot hold. `BlockState` always names a block, so its fields are block references without `@Ref`; `@Ref(BLOCK)` there is accepted, any other kind fails. @@ -732,6 +736,74 @@ them, so `OptionsMetadata` reads it with `java.lang.classfile`. A settings class from a jar or a class directory, which every module class does. Which settings an error names first follows feature id order too, so the same pack always fails with the same message. +## Value types + +Iris's features read blocks, noise, ranges and positions through Iris classes (`IrisBlockData`, +`IrisGeneratorStyle`, `IrisStyledRange`, `IrisRange`, `IrisPosition`) whose methods reach into Iris's loaders, +platform and noise. A module that may only see IrisApi needs the same JSON as API values, and the behaviour +behind them as host services. Each value type is a settings-shaped class: a final class with private fields +and defaults, a private no-argument constructor, `@Desc` and, where packs already write snippets of it, the +same `@Snippet` folder. So the schema builder describes it with no special case, the host decodes it like +settings, and pack JSON keeps its shape: the field names and the no-argument defaults are Iris's, odd ones +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. + +| Iris class | API | Behaviour behind it | +| --- | --- | --- | +| `IrisBlockData` | `com.volmit.block.BlockSpec` | `BlockRegistry.resolve(BlockSpec)`, `blockEntity(BlockSpec)` | +| `TileData` | `BlockEntityData` (existing) for placed data; a `BlockSpec`'s `tileData` (`Map`) in settings | `BlockRegistry.blockEntity(BlockSpec)` | +| `IrisGeneratorStyle` | `com.volmit.noise.NoiseStyle` | `PackResources.noise()`, a `NoiseFactory` building `NoiseSampler`s | +| `IrisStyledRange` | `com.volmit.noise.StyledRange` | `at(noise, seed, x, z)` | +| `IrisRange` | `com.volmit.config.Range` | none: `contains`, `pick(WorldRandom)` | +| `IrisPosition` | `com.volmit.world.BlockPosition` (existing record, now with a private no-argument constructor) | none | +| `IrisDirection` | none: a module declares its own enum with the same constant names, and maps to `BlockFace` | | +| `IrisObjectRotation`, `IrisObjectScale` | none: settings of the module that picks a rotation or scale | `ObjectTransform`, `ObjectTransformer` (existing) | +| `ObjectPlaceMode` | none: an enum of the placement modules | | + +Why these lines: + +- **Noise is the host's.** Styles name the host's generators, and expressions and image maps are pack + resources the host compiles. A `NoiseStyle` is only the description; `NoiseFactory.sampler(style, seed)` + builds the noise. It hangs off `PackResources`, like `blocks()`, because noise depends on the pack snapshot + (its expressions and image maps), and every context that has resources (stages, validators, hooks) can + build noise. The host caches per snapshot, so stage bodies may ask for a sampler per invocation. The seed is + the module's: noise lines up across chunks only when it comes from `worldSeed()`, not a stage's stream. +- **`NoiseSampler` moved to `com.volmit.noise`** and gained a two-dimensional `sample(x, z)`: Iris's noise + gives different fields in two and three dimensions, and most features sample columns. +- **Style names are text with `@Ref(NOISE_STYLE)`**, not an enum: the host owns the list, and an API enum would + pin it. An unknown name samples flat, as Iris has always read one. +- **`isFlat()` is stricter than Iris's**: a flat base style with an expression or image map is not flat. +- **Block properties are text.** `{"waterlogged": true}` decodes to `"true"`, which is what the platform's state + key holds; the host's studio description may accept the JSON types it accepted before. +- **Resolving a `BlockSpec` never throws.** It follows what packs rely on: a custom block of the pack's + `blocks` folder, then the platform's block, then the backup, then air. `resolve(String)` keeps throwing for + an unknown key. +- **Directions, rotations, scales and place modes stay module types.** They are small enums or settings whose + meaning is a feature's (which axes may turn, by which steps; which anchor sampling a mode uses), and applying + a rotation is already the host's `ObjectTransformer`. An API type would freeze a feature's choices. + +## Vanilla structures + +Minecraft, data packs and mods register structures the platform starts on its own. Iris blocks some (a pack +replaces them with its own structures), lets others generate, and places some itself. The decisions belonged +to core (`NativeStructurePlacementPlanner`, `NativeStructureGenerationPolicy`) reading feature classes. A module +now states them with a `VanillaStructureHook`, registered in `register`; the host applies them on every +platform. + +- **A rule per structure, not per start.** `rule(structure, context)` answers `GENERATE`, `ALSO_PLACE`, + `REPLACE` or `BLOCK` for one structure id in one world. The platform asks per start, but also when it locates + a structure, which has no position; and an answer that depended on the position could block a start + `/locate` had promised. The host caches the rule per world, structure and pack snapshot. +- **Two facts, one enum.** Whether the platform's own starts are blocked, and whether a module places the + structure itself. The second matters even where the first does not: a structure a pack's dimension disables + but a module places is reported, and located, as the module's. `and` combines two modules' rules, so the + result never depends on module order. +- **The context is the world's pack.** `resources()` and `settings()` (`PackSettings`: the dimension and every + region and biome it can reach), the same view reaches are worked out from. A hook that needs the world's own + state gets it the way stages do. +- **Placing starts is not part of it yet.** Where the platform should start a structure a module places, with the + terrain fitting and foundations that go with it, comes with the planner's move (see CONTRACTS, Open). + ## Pack resource kinds Iris loads its pack resources (biomes, regions, objects, structures...) with one hard-coded loader per type, @@ -800,7 +872,7 @@ This is an inventory of where each existing family should land, not a claim that | Surface, ceiling, shore, sea and floating decoration | Chunk stages + palette/support/sampling resources | | Slab/wall/snow post-processing, foliage cleanup, ore hiding | Chunk stages + block traits and neighbor views | | Custom block recording and deferred application | Chunk stage + persistent typed layers + host content adapter | -| Ores and deposits | Chunk stages + noise/palette resources + configured settings | +| Ores and deposits | Chunk stages + `BlockSpec` palettes + configured settings | | Object selection, transforms, height and placement modes | Geometry + placement stages per mode module | | Stilt, erosion, ceiling hang, vacuum, paint, floating | Placement modules with block and invocation stages | | Slope, support, limits, collision, protection, bore, meld, snow | Placement stages that reject or write | @@ -809,7 +881,7 @@ This is an inventory of where each existing family should land, not a claim that | Cave profiles, carving, cave fluids and decoration | Chunk stages + typed carve layers | | Floating islands and child biomes | Terrain/biome sampling + chunk and placement stages | | Structures, jigsaw pools and foundations | Structure assembly producing placement requests | -| Imported/native structures and ownership | Host native-generation policy adapter | +| Imported/native structures and ownership | `VanillaStructureHook` rules; host native-generation adapter per platform | | Terrain layers, fluids, bedrock, interpolation | Terrain providers + chunk stages | | Region/biome selection | Biome providers + platform biome writer | | Image maps, noise expressions, pack injection | Compiled immutable pack resources | diff --git a/README.md b/README.md index 3d293db62..151ddf664 100644 --- a/README.md +++ b/README.md @@ -51,8 +51,8 @@ public final class MossModule implements IrisModule { The stream is a `WorldRandom` (see Random streams below). `IrisModule.register(FeatureRegistry)` stays for non-stage contributions: geometry generators, -mantle layers, settings no stage names (see Settings for studio), pack resource kinds and validators -(see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`, +mantle layers, settings no stage names (see Settings for studio), pack resource kinds, validators and +vanilla structure hooks (see below). Their feature ids, mantle keys and kind ids are the module id or start with it and `/`, like stage ids: `iris:snow` or `iris:snow/depth` for module `iris:snow`. A settings type named in `when(...)` needs a feature id that at least one module naming it owns in that sense, or its owner must have registered it, so another module may still condition its stages on it, as moss does on `iris:snow`. @@ -296,18 +296,18 @@ public final class FloraSettings implements IrisFeature { The host creates settings with it, and the field values of that instance are the defaults studio shows. - Field types: `boolean`, primitive or boxed numbers, `String`, `ResourceId`, `BlockState`, enums, - `List`, `Set` and arrays of these, `Map`, and concrete classes, which are described the - same way. `@Snippet("example/flora/patch")` on a class lets packs write it as a file under + `List`, `Set` and arrays of these, `Map`, `Object` for any JSON value, and concrete classes, + which are described the same way, IrisApi's value types among them (see Values in settings). `@Snippet("example/flora/patch")` on a class lets packs write it as a file under `snippet/example/flora/patch/`. A pack module's snippet names start with its module id as a folder path (`example/flora` for `example:flora`). - Anything else fails the pack load: `char`, JDK classes such as `UUID` or `Optional`, `ResourceKey`, + Anything else fails the pack load: `char`, other JDK classes such as `UUID` or `Optional`, `ResourceKey`, interfaces and abstract classes, inner (non-static) classes, collections without type arguments, concrete collections such as `ArrayList`, and maps with other keys. - `@Ref(Reference.X)` says what a `String` or `ResourceId` names, also on lists, sets and arrays of them, so studio offers the right list: `BLOCK`, `ITEM`, `ENTITY`, `BIOME`, `STRUCTURE`, - `POTION_EFFECT` or `ENCHANTMENT` from the server's registries, or `PACK_BIOME`, `PACK_REGION` or - `PACK_OBJECT` of the pack. The pack kinds fit `String` only, in the form packs use (`desert/dunes`), - never `ResourceId`. `BlockState` fields name blocks without it. `@Ref` on any other field fails + `POTION_EFFECT` or `ENCHANTMENT` from the server's registries, `NOISE_STYLE` from the host's noise + styles, or `PACK_BIOME`, `PACK_REGION`, `PACK_OBJECT`, `PACK_EXPRESSION` or `PACK_IMAGE_MAP` of the pack. + The pack kinds fit `String` only, in the form packs use (`desert/dunes`), never `ResourceId`. `BlockState` fields name blocks without it. `@Ref` on any other field fails the load. - `@ResourceRef(Keep.class)` says that a `String`, or a list, set or array of them, names a resource of the module resource kind read into that class, by its key (see Pack resources of a module). The class must back a @@ -336,6 +336,66 @@ Snippet name 'patch' of com.example.flora.Patch of settings example:flora (modul Settings com.example.flora.FloraSettings of module example:flora from modules/flora.jar set alias 'flora'; only modules that ship with the host may set one, so remove it: packs write these settings under their id "example:flora" ``` +## Values in settings + +Settings describe blocks, noise and ranges with IrisApi's value types, which read the JSON packs already write: + +| Type | Packs write | Use it through | +| --- | --- | --- | +| `BlockSpec` | `{"block": "iron_ore", "data": {"waterlogged": true}, "backup": {...}, "tileData": {...}}` | `resources.blocks().resolve(spec)` gives the `BlockState`, `blockEntity(spec)` its block entity | +| `NoiseStyle` | `{"style": "SIMPLEX", "zoom": 4, "fracture": {...}}` 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 | +| `Object` | any JSON value | as decoded: objects as maps, arrays as lists, numbers as `Double` | + +```java +@Feature(id = "example:veins", name = "Veins", targets = Target.BIOME) +public final class VeinSettings implements IrisFeature { + private List palette = List.of(BlockSpec.of("iron_ore")); + private NoiseStyle density = NoiseStyle.of("SIMPLEX").withZoom(16); +} + +// in a stage +NoiseSampler density = ctx.resources().noise().sampler(veins.density(), ctx.worldSeed() ^ VEIN_SALT); +BlockState ore = ctx.resources().blocks().resolve(veins.palette().getFirst()); +``` + +Noise belongs to the host: a style names one of its noise generators (`@Ref(Reference.NOISE_STYLE)`), or an +expression or image map of the pack, and the host builds the noise. Seed it from `worldSeed()`, so the noise +lines up across chunks; the host keeps what it builds for the pack, so asking again is cheap. A `BlockSpec` may +name a block without a namespace, a custom block of the pack's `blocks` folder, or a block only some platforms +have; resolving it never fails: the backup, then air, stands in. + +The types are values the host creates with their no-argument constructors and reads the JSON into, like settings, +so an omitted option keeps the default the type declares (a `Range` is 16 to 32 unless the pack or the field's +own default says otherwise). They keep the snippet folders packs already use (`style`, `style-range`, `range`). +Studio describes them like settings; Iris may render its own description of the same JSON. + +Directions, object rotation and scale and placement modes are not API types: a module that reads them declares its +own enum or settings class with the same JSON, and applies a rotation through `ObjectTransformer`. + +## Vanilla structures + +A module decides over the platform's own structures, the ones Minecraft, data packs and mods register, with a +`VanillaStructureHook`: the platform keeps generating one (`GENERATE`), the module places it as well +(`ALSO_PLACE`), the module places it instead and the platform's own starts are blocked (`REPLACE`), or nobody +generates it (`BLOCK`). + +```java +public void register(FeatureRegistry registry) { + registry.registerVanillaStructureHook((structure, world) -> + world.settings().declared(CastleSettings.class).stream() + .anyMatch(castle -> castle.value().replaces().equals(structure.toString())) + ? VanillaStructureRule.REPLACE : VanillaStructureRule.GENERATE); +} +``` + +The host asks every hook of the pack once per world, structure and pack snapshot, before the platform starts the +structure and when it locates it, so a hook decides from the pack, never from a position. Rules combine: a +structure is blocked when any module blocks it, and placed by a module when any module places it. The host applies +the result on every platform it runs on. + ## Host side ```java @@ -441,7 +501,8 @@ A pack without jars logs `Pack overworld uses no modules: no jars in its modules `LoadedModules.load` installs every module, catalogs the settings types named in `when(...)` together with explicitly registered settings, geometry and mantle registrations, resource kinds and -validators (`catalog().resourceKinds()`, `catalog().validators()`), describes them and resolves the pipelines. Graph errors +validators and vanilla structure hooks (`catalog().resourceKinds()`, `catalog().validators()`, +`catalog().vanillaStructureHooks()`), describes them and resolves the pipelines. Graph errors (missing requirement, cycle, a stage outside its module's id, duplicate, cross-pipeline edge) fail here, at pack load, and so do reserved namespaces and feature ids or mantle keys outside the module's id. Errors about one module name its jar or "host classpath", and so does a module @@ -467,8 +528,8 @@ no JSON. The host renders it and merges it with its own fields: description, required, minimum, maximum and default value. - `ValueKind` is sealed: `BooleanKind`, `IntegerKind`, `DecimalKind`, `TextKind(format)`, `ReferenceKind(reference, format)`, `EnumKind(type, constants)`, `ListKind(element, unique)`, - `MapKind(value)`, `ObjectKind(type)`, which names an entry of `types()`, `HostKind(type)` and - `ResourceReferenceKind(kind)`. `TextFormat` is `PLAIN`, + `MapKind(value)`, `ObjectKind(type)`, which names an entry of `types()`, `HostKind(type)`, + `ResourceReferenceKind(kind)` and `AnyKind` for any JSON value. `TextFormat` is `PLAIN`, `RESOURCE_ID` or `BLOCK_STATE`. - `snippets()` and `objectGenerators()` pick the types with a snippet name and the object generator features. @@ -501,7 +562,8 @@ and closes the edit in every case. Stages get buffered `PlacementAccess` without resource kind; the requested type selects the kind, so `BiomeSample` ids look up directly. `ids(type)` lists a kind. - `BlockState` has value equality and sorted properties; `BlockRegistry` checks it against the - platform. `BlockPalette` and `NoiseSampler` are typed resources. + platform and resolves `BlockSpec`s. `BlockPalette` and `NoiseSampler` are typed resources; + `PackResources.noise()` builds noise samplers from `NoiseStyle`s. - `GeneratedObject` is sparse, immutable local geometry. `PlacementRequest` aligns its anchor with a world position using checked arithmetic. - `Hunk` is a dense local volume; `ArrayHunk` is the bounds-checked reference. @@ -540,7 +602,10 @@ settings (and the load error when a pack module uses one), and the one-option sh `PackSchemaTest` also loads a module jar with a resource kind: the kind's files described from its class, `@ResourceRef` options as references to the kind, built-in kinds of host types, the load error for a pack kind of a host type, for a folder two kinds claim or the host reserves, and for a misplaced `@ResourceRef`. -`ModuleRegistryTest` checks kind ids, types and folders, and the validator order. `DiscoveredModuleTest` +`PackSchemaTest` also describes settings holding IrisApi's value types (`BlockSpec`, `NoiseStyle`, +`StyledRange`, `Range`, `BlockPosition`) and `Object`, and `SettingsValuesTest` checks the value types themselves +and how vanilla structure rules combine. `ModuleRegistryTest` checks kind ids, types and folders, and the order of +validators and vanilla structure hooks. `DiscoveredModuleTest` checks that `info()` is read once. `LoadedPackTest` loads a pack with built-ins and checks that a failed load and `close()` leave nothing open. `PackJarSnapshotTest` checks that classes come from the copies, that the original can be replaced while loaded, that copies go diff --git a/src/main/java/com/volmit/FeatureRegistry.java b/src/main/java/com/volmit/FeatureRegistry.java index 92c36e5eb..a471ec72f 100644 --- a/src/main/java/com/volmit/FeatureRegistry.java +++ b/src/main/java/com/volmit/FeatureRegistry.java @@ -7,6 +7,7 @@ import com.volmit.object.ObjectGeneratorFactory; import com.volmit.resource.ResourceKind; import com.volmit.stage.StageGraph; import com.volmit.validation.Validator; +import com.volmit.vanilla.VanillaStructureHook; /** Host implementation collects non-stage registrations before loading pack configuration. * Feature IDs must be unique. JSON fields must be unique per attachment target, including the @@ -42,4 +43,9 @@ public interface FeatureRegistry { /** Adds a check the host runs over the whole pack wherever it validates packs. */ void registerValidator(Validator validator); + + /** Lets this module decide over the platform's own structures in the pack's worlds: block them, leave them to the + * platform, or place them itself. + */ + void registerVanillaStructureHook(VanillaStructureHook hook); } diff --git a/src/main/java/com/volmit/block/BlockRegistry.java b/src/main/java/com/volmit/block/BlockRegistry.java index 1a6147c76..78ed02869 100644 --- a/src/main/java/com/volmit/block/BlockRegistry.java +++ b/src/main/java/com/volmit/block/BlockRegistry.java @@ -1,6 +1,8 @@ package com.volmit.block; +import com.volmit.object.BlockEntityData; import com.volmit.resource.ResourceId; +import java.util.Optional; /** Host adapter for resolved states and cached behavior. No native platform objects escape. * Unknown materials, unsupported properties, and malformed states throw IllegalArgumentException. @@ -9,6 +11,19 @@ import com.volmit.resource.ResourceId; public interface BlockRegistry { BlockState resolve(String key); default BlockState resolve(BlockState state) { return resolve(state.key()); } + + /** The state {@code spec} names, resolved the way packs expect, so it never throws for a block the platform lacks: + * a block of the pack's {@code blocks} folder with the spec's properties over its own, else the platform's block + * (a key without a namespace is {@code minecraft:}) with the spec's properties, else the backup resolved the same + * way, else air. + */ + BlockState resolve(BlockSpec spec); + + /** The block entity {@code spec}'s {@code tileData} describes, in the host's format; empty when the spec has none + * or its resolved block has no block entity. + */ + Optional blockEntity(BlockSpec spec); + boolean hasTrait(BlockState state, BlockTrait trait); boolean inTag(BlockState state, ResourceId tag); /** Whether state can attach to the specified face of support, ignoring other neighbors. */ diff --git a/src/main/java/com/volmit/block/BlockSpec.java b/src/main/java/com/volmit/block/BlockSpec.java new file mode 100644 index 000000000..7a7d1c3c7 --- /dev/null +++ b/src/main/java/com/volmit/block/BlockSpec.java @@ -0,0 +1,121 @@ +package com.volmit.block; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Required; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +/** A block as packs write it in settings, such as {@code {"block": "iron_ore"}} or + * {@code {"block": "minecraft:oak_log", "data": {"axis": "y"}, "backup": {"block": "stone"}}}. Settings hold it + * where a pack picks a block it may not be able to name exactly: a key without a namespace, a custom block of + * 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 + * 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") +public final class BlockSpec { + private static final String AIR = "air"; + + @Required + @Ref(Reference.BLOCK) + @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") + private Map data = Map.of(); + + @MinNumber(1) + @MaxNumber(1000) + @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.") + private BlockSpec backup; + + @Desc("Optional block entity data for this block, such as a spawner's SpawnData") + private Map tileData = Map.of(); + + private BlockSpec() { + } + + private BlockSpec(String block, Map data, int weight, BlockSpec backup, Map tileData) { + this.block = Objects.requireNonNull(block, "block"); + this.data = Map.copyOf(data); + this.weight = weight; + this.backup = backup; + this.tileData = Collections.unmodifiableMap(new LinkedHashMap<>(tileData)); + } + + /** The block {@code block}, such as {@code minecraft:stone} or {@code stone}, without properties, weight 1. */ + public static BlockSpec of(String block) { + return new BlockSpec(block, Map.of(), 1, null, Map.of()); + } + + /** This spec with the property {@code name} set to {@code value}. */ + public BlockSpec withProperty(String name, String value) { + var changed = new LinkedHashMap<>(data()); + changed.put(name, value); + return new BlockSpec(block, changed, weight, backup, tileData()); + } + + public BlockSpec withWeight(int weight) { + return new BlockSpec(block, data(), weight, backup, tileData()); + } + + public BlockSpec withBackup(BlockSpec backup) { + return new BlockSpec(block, data(), weight, backup, tileData()); + } + + public BlockSpec withTileData(Map tileData) { + return new BlockSpec(block, data(), weight, backup, tileData); + } + + /** The block key as the pack wrote it. */ + public String block() { + return block == null ? AIR : block; + } + + /** The properties as the pack wrote them, as text. */ + public Map data() { + return data == null ? Map.of() : Collections.unmodifiableMap(data); + } + + public int weight() { + return weight; + } + + public Optional backup() { + return Optional.ofNullable(backup); + } + + /** 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); + } + + @Override + public boolean equals(Object other) { + return other instanceof BlockSpec spec && block().equals(spec.block()) && data().equals(spec.data()) + && weight == spec.weight && Objects.equals(backup, spec.backup) && tileData().equals(spec.tileData()); + } + + @Override + public int hashCode() { + return Objects.hash(block(), data(), weight, backup, tileData()); + } + + @Override + public String toString() { + return "BlockSpec[" + block() + (data().isEmpty() ? "" : " " + data()) + "]"; + } +} diff --git a/src/main/java/com/volmit/config/Range.java b/src/main/java/com/volmit/config/Range.java new file mode 100644 index 000000000..b6cee3184 --- /dev/null +++ b/src/main/java/com/volmit/config/Range.java @@ -0,0 +1,68 @@ +package com.volmit.config; + +import com.volmit.random.WorldRandom; +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. + */ +@Snippet("range") +@Desc("Represents a range") +public final class Range { + @Desc("The minimum value") + private double min = 16; + + @Desc("The maximum value") + private double max = 32; + + private Range() { + } + + private Range(double min, double max) { + this.min = min; + this.max = max; + } + + public static Range of(double min, double max) { + return new Range(min, max); + } + + public double min() { + return min; + } + + public double max() { + return max; + } + + /** Whether {@code value} lies between the bounds, both included. */ + public boolean contains(double value) { + return value >= min && value <= max; + } + + /** A number between the bounds drawn from {@code random}: {@code min + nextDouble() * (max - min)}, one draw, + * or {@code min} without a draw when the bounds are equal. + */ + public double pick(WorldRandom random) { + if (min == max) { + return min; + } + return min + random.nextDouble() * (max - min); + } + + @Override + public boolean equals(Object other) { + return other instanceof Range that && Double.compare(min, that.min) == 0 && Double.compare(max, that.max) == 0; + } + + @Override + public int hashCode() { + return Objects.hash(min, max); + } + + @Override + public String toString() { + return "Range[" + min + ".." + max + "]"; + } +} diff --git a/src/main/java/com/volmit/config/Reference.java b/src/main/java/com/volmit/config/Reference.java index cb2a2fe78..942ced307 100644 --- a/src/main/java/com/volmit/config/Reference.java +++ b/src/main/java/com/volmit/config/Reference.java @@ -25,5 +25,11 @@ public enum Reference { /** A region of the pack. */ PACK_REGION, /** An object of the pack. */ - PACK_OBJECT + PACK_OBJECT, + /** One of the host's noise styles, such as {@code SIMPLEX}; see {@link com.volmit.noise.NoiseStyle}. */ + NOISE_STYLE, + /** An expression of the pack. */ + PACK_EXPRESSION, + /** An image map of the pack. */ + PACK_IMAGE_MAP } diff --git a/src/main/java/com/volmit/host/DefaultValues.java b/src/main/java/com/volmit/host/DefaultValues.java index 32fc9014c..3e1083bf4 100644 --- a/src/main/java/com/volmit/host/DefaultValues.java +++ b/src/main/java/com/volmit/host/DefaultValues.java @@ -2,6 +2,7 @@ package com.volmit.host; import com.volmit.block.BlockState; import com.volmit.host.schema.ValueKind; +import com.volmit.host.schema.ValueKind.AnyKind; import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumKind; @@ -47,7 +48,7 @@ final class DefaultValues { case ListKind list -> list(elements(value), list); case MapKind map -> map((Map) value, map.value()); case ObjectKind object -> object(value, types.get(object.type())); - case HostKind _ -> Optional.empty(); + case HostKind _, AnyKind _ -> Optional.empty(); }; } diff --git a/src/main/java/com/volmit/host/FeatureCatalog.java b/src/main/java/com/volmit/host/FeatureCatalog.java index 0a22f196c..60184e212 100644 --- a/src/main/java/com/volmit/host/FeatureCatalog.java +++ b/src/main/java/com/volmit/host/FeatureCatalog.java @@ -8,7 +8,8 @@ import java.util.Map; import java.util.NoSuchElementException; import java.util.function.Function; -/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators are in module id order, +/** Frozen registrations. Lists use lexical feature/layer/kind ID order, and validators and vanilla structure hooks + * are in module id order, * so nothing depends on discovery. Factory, codec and validator implementations must themselves obey their * concurrency contracts. */ @@ -18,13 +19,15 @@ public final class FeatureCatalog { private final Map> mantle; private final List resourceKinds; private final List validators; + private final List vanillaStructureHooks; FeatureCatalog( Map, FeatureDescriptor> settings, Map, ObjectRegistration> objects, Map> mantle, Collection resourceKinds, - List validators) { + List validators, + List vanillaStructureHooks) { this.settings = Map.copyOf(settings); this.objects = Map.copyOf(objects); this.mantle = Map.copyOf(mantle); @@ -32,6 +35,9 @@ public final class FeatureCatalog { this.validators = validators.stream() .sorted(Comparator.comparing(registration -> registration.module().info().id())) .toList(); + this.vanillaStructureHooks = vanillaStructureHooks.stream() + .sorted(Comparator.comparing(registration -> registration.module().info().id())) + .toList(); } /** Settings types that activate stages; the host decodes them from pack JSON. */ @@ -57,6 +63,11 @@ public final class FeatureCatalog { return validators; } + /** The vanilla structure hooks modules registered, by module id, each module's in the order it registered them. */ + public List vanillaStructureHooks() { + return vanillaStructureHooks; + } + private static > List sorted( Collection registrations, Function key) { diff --git a/src/main/java/com/volmit/host/ModuleRegistry.java b/src/main/java/com/volmit/host/ModuleRegistry.java index 37903ac3b..147c90801 100644 --- a/src/main/java/com/volmit/host/ModuleRegistry.java +++ b/src/main/java/com/volmit/host/ModuleRegistry.java @@ -11,6 +11,7 @@ import com.volmit.object.ObjectGeneratorFactory; import com.volmit.resource.ResourceId; import com.volmit.resource.ResourceKind; import com.volmit.validation.Validator; +import com.volmit.vanilla.VanillaStructureHook; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; @@ -40,6 +41,7 @@ public final class ModuleRegistry implements FeatureRegistry { private final Map fields = new HashMap<>(); private final Map resourceKinds = new HashMap<>(); private final List validators = new ArrayList<>(); + private final List vanillaStructureHooks = new ArrayList<>(); private final Set reservedFolders; private final List registered = new ArrayList<>(); private FeatureCatalog catalog; @@ -129,6 +131,16 @@ public final class ModuleRegistry implements FeatureRegistry { validators.add(new ValidatorRegistration(validator, registering)); } + @Override + public void registerVanillaStructureHook(VanillaStructureHook hook) { + checkOpen(); + Objects.requireNonNull(hook, "hook"); + if (registering == null) { + throw new IllegalStateException("Vanilla structure hook " + hook + " registered outside IrisModule.register"); + } + vanillaStructureHooks.add(new VanillaStructureHookRegistration(hook, registering)); + } + /** Catalogs a settings type named by a stage's when(...), whose owner {@link StageGraphBuilder} * has checked. Several stages, and the owner's {@link #registerSettings}, may name one type. Call * it after every module has registered, so the owner is known. @@ -149,7 +161,7 @@ public final class ModuleRegistry implements FeatureRegistry { public FeatureCatalog freeze() { if (catalog == null) { - catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators); + catalog = new FeatureCatalog(settings, objects, mantle, resourceKinds.values(), validators, vanillaStructureHooks); } return catalog; } diff --git a/src/main/java/com/volmit/host/ValueKinds.java b/src/main/java/com/volmit/host/ValueKinds.java index dad52c3cb..9da5f842e 100644 --- a/src/main/java/com/volmit/host/ValueKinds.java +++ b/src/main/java/com/volmit/host/ValueKinds.java @@ -6,6 +6,7 @@ import com.volmit.config.OptionsMetadata; import com.volmit.config.Reference; import com.volmit.host.schema.TextFormat; import com.volmit.host.schema.ValueKind; +import com.volmit.host.schema.ValueKind.AnyKind; import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumConstant; @@ -39,13 +40,14 @@ import java.util.function.Function; */ final class ValueKinds { static final String SUPPORTED_TYPES = "settings fields can be booleans, numbers, String, ResourceId, BlockState, enums, " - + "lists, sets and arrays of these, Map with String keys and classes with a no-argument constructor"; + + "lists, sets and arrays of these, Map with String keys, Object for any JSON value and classes with a no-argument constructor"; private static final Set> BOOLEANS = Set.of(boolean.class, Boolean.class); private static final Set> INTEGERS = Set.of(byte.class, short.class, int.class, long.class, Byte.class, Short.class, Integer.class, Long.class); private static final Set> DECIMALS = Set.of(float.class, double.class, Float.class, Double.class); private static final String DECLARE_COLLECTION = "declare it as List<...>, Set<...> or Map"; - private static final Set PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT); + private static final Set PACK_REFERENCES = EnumSet.of(Reference.PACK_BIOME, Reference.PACK_REGION, Reference.PACK_OBJECT, + Reference.PACK_EXPRESSION, Reference.PACK_IMAGE_MAP); private final Function, ObjectKind> objects; private final HostTypes hostTypes; @@ -99,6 +101,7 @@ final class ValueKinds { if (INTEGERS.contains(type)) return new IntegerKind(); if (DECIMALS.contains(type)) return new DecimalKind(); if (type.isEnum()) return enumKind(type); + if (type == Object.class) return new AnyKind(); return objects.apply(type); } diff --git a/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java b/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java new file mode 100644 index 000000000..446fba6af --- /dev/null +++ b/src/main/java/com/volmit/host/VanillaStructureHookRegistration.java @@ -0,0 +1,12 @@ +package com.volmit.host; + +import com.volmit.vanilla.VanillaStructureHook; +import java.util.Objects; + +/** A vanilla structure hook and the module that registered it, which the host names when the hook fails. */ +public record VanillaStructureHookRegistration(VanillaStructureHook hook, DiscoveredModule module) { + public VanillaStructureHookRegistration { + Objects.requireNonNull(hook, "hook"); + Objects.requireNonNull(module, "module"); + } +} diff --git a/src/main/java/com/volmit/host/schema/ValueKind.java b/src/main/java/com/volmit/host/schema/ValueKind.java index edb426729..e30a65757 100644 --- a/src/main/java/com/volmit/host/schema/ValueKind.java +++ b/src/main/java/com/volmit/host/schema/ValueKind.java @@ -83,6 +83,13 @@ public sealed interface ValueKind { } } + /** Any JSON value, which the module reads as it is: {@code Object} fields, and the values of {@code Map} + * and {@code List}. For data whose shape the module does not own, such as a block entity's data. The host + * decodes objects as maps with string keys, arrays as lists, numbers as {@code Double}, and strings and booleans + * as themselves. + */ + record AnyKind() implements ValueKind {} + /** An enum constant and its {@code @Desc}, or an empty description. */ record EnumConstant(String name, String description) { public EnumConstant { diff --git a/src/main/java/com/volmit/noise/NoiseFactory.java b/src/main/java/com/volmit/noise/NoiseFactory.java new file mode 100644 index 000000000..aae58d69e --- /dev/null +++ b/src/main/java/com/volmit/noise/NoiseFactory.java @@ -0,0 +1,17 @@ +package com.volmit.noise; + +/** Builds noise from styles a pack describes. Noise is the host's: modules describe it with {@link NoiseStyle} in + * their settings and get samplers from here ({@link com.volmit.resource.PackResources#noise()}), never the host's + * noise classes. Safe for concurrent calls. + */ +public interface NoiseFactory { + /** The noise {@code style} describes, seeded with {@code seed}. The same style and seed give the same values + * in every world of the pack, so derive the seed from the world seed ({@code context.worldSeed()}), not from a + * stage's random stream, when the noise must line up across chunks. The host keeps what it builds for the pack + * snapshot, so asking again for the same style and seed is cheap. + * + *

A style name the host does not know samples as {@link NoiseStyle#FLAT}; an expression or image map the + * pack does not have falls back to the base style. + */ + NoiseSampler sampler(NoiseStyle style, long seed); +} diff --git a/src/main/java/com/volmit/noise/NoiseSampler.java b/src/main/java/com/volmit/noise/NoiseSampler.java new file mode 100644 index 000000000..463c63cd0 --- /dev/null +++ b/src/main/java/com/volmit/noise/NoiseSampler.java @@ -0,0 +1,12 @@ +package com.volmit.noise; + +/** Immutable, seeded noise the host built from a {@link NoiseStyle} ({@link NoiseFactory#sampler}). X and Z are + * world coordinates; Y is the height above the dimension's bottom (0 = bottom). The host's own styles give values + * from 0 to 1; expressions and image maps give what they compute. Two-dimensional and three-dimensional samples + * are separate fields, so {@code sample(x, z)} is not {@code sample(x, 0, z)}. Safe for concurrent calls. + */ +public interface NoiseSampler { + double sample(double worldX, double worldZ); + + double sample(double worldX, double y, double worldZ); +} diff --git a/src/main/java/com/volmit/noise/NoiseStyle.java b/src/main/java/com/volmit/noise/NoiseStyle.java new file mode 100644 index 000000000..e19f818ef --- /dev/null +++ b/src/main/java/com/volmit/noise/NoiseStyle.java @@ -0,0 +1,164 @@ +package com.volmit.noise; + +import com.volmit.config.Desc; +import com.volmit.config.MaxNumber; +import com.volmit.config.MinNumber; +import com.volmit.config.Ref; +import com.volmit.config.Reference; +import com.volmit.config.Snippet; +import java.util.Objects; +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. + * + *

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. + */ +@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") +public final class NoiseStyle { + /** The style without noise, the default. */ + 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.") + private String style = FLAT; + + @Desc("If set above 0, this style will be cellularized") + private double cellularFrequency = 0; + + @Desc("Cell zooms") + private double cellularZoom = 1; + + @MinNumber(0.00001) + @Desc("The zoom of this style") + private double zoom = 1; + + @Ref(Reference.PACK_EXPRESSION) + @Desc("Instead of using the style property, use a custom expression to represent this style.") + private String expression; + + @Ref(Reference.PACK_IMAGE_MAP) + @Desc("Use an Image map instead of a generated value") + private String imageMap; + + @MinNumber(0.00001) + @Desc("The Output multiplier. Only used if parent is fracture.") + 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.") + private NoiseStyle fracture; + + @MinNumber(0.01562) + @MaxNumber(64) + @Desc("The exponent") + private double exponent = 1; + + @MinNumber(0) + @MaxNumber(8192) + @Desc("If the cache size is set above 0, this generator will be cached") + private int cacheSize = 0; + + private NoiseStyle() { + } + + private NoiseStyle(NoiseStyle copy) { + style = copy.style; + cellularFrequency = copy.cellularFrequency; + cellularZoom = copy.cellularZoom; + zoom = copy.zoom; + expression = copy.expression; + imageMap = copy.imageMap; + 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. */ + public static NoiseStyle of(String style) { + var created = new NoiseStyle(); + created.style = Objects.requireNonNull(style, "style"); + return created; + } + + /** This style with zoom {@code zoom}: above 1 stretches the noise, below 1 squeezes it. */ + public NoiseStyle withZoom(double zoom) { + var changed = new NoiseStyle(this); + changed.zoom = zoom; + return changed; + } + + /** The base style's name; {@link #FLAT} where the pack wrote none. */ + public String style() { + return style == null ? FLAT : style; + } + + public double cellularFrequency() { + return cellularFrequency; + } + + public double cellularZoom() { + return cellularZoom; + } + + public double zoom() { + return zoom; + } + + /** The key of the pack expression that replaces the base style. */ + public Optional expression() { + return Optional.ofNullable(expression); + } + + /** The key of the pack image map that replaces the base style when there is no expression. */ + public Optional imageMap() { + return Optional.ofNullable(imageMap); + } + + public double multiplier() { + return multiplier; + } + + public Optional fracture() { + return Optional.ofNullable(fracture); + } + + public double exponent() { + return exponent; + } + + public int cacheSize() { + return cacheSize; + } + + /** Whether the style gives no noise: the {@link #FLAT} base style without an expression or image map. */ + public boolean isFlat() { + return FLAT.equals(style()) && expression == null && imageMap == null; + } + + @Override + public boolean equals(Object other) { + 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; + } + + @Override + public int hashCode() { + return Objects.hash(style(), cellularFrequency, cellularZoom, zoom, expression, imageMap, multiplier, fracture, + exponent, cacheSize); + } + + @Override + public String toString() { + return "NoiseStyle[" + style() + expression().map(key -> ", expression " + key).orElse("") + + imageMap().map(key -> ", image map " + key).orElse("") + ", zoom " + zoom + "]"; + } +} diff --git a/src/main/java/com/volmit/noise/StyledRange.java b/src/main/java/com/volmit/noise/StyledRange.java new file mode 100644 index 000000000..568b845d2 --- /dev/null +++ b/src/main/java/com/volmit/noise/StyledRange.java @@ -0,0 +1,85 @@ +package com.volmit.noise; + +import com.volmit.config.Desc; +import com.volmit.config.Snippet; +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. + */ +@Snippet("style-range") +@Desc("Represents a range styled with a custom generator") +public final class StyledRange { + private static final String DEFAULT_STYLE = "STATIC"; + + @Desc("The minimum value") + private double min = 16; + + @Desc("The maximum value") + private double max = 32; + + @Desc("The style to pick the range") + private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE); + + private StyledRange() { + } + + private StyledRange(double min, double max, NoiseStyle style) { + this.min = min; + this.max = max; + this.style = Objects.requireNonNull(style, "style"); + } + + public static StyledRange of(double min, double max, NoiseStyle style) { + return new StyledRange(min, max, style); + } + + public double min() { + return min; + } + + public double max() { + return max; + } + + /** The style; {@link NoiseStyle#FLAT} where the pack wrote {@code null}. */ + public NoiseStyle style() { + return style == null ? NoiseStyle.of(NoiseStyle.FLAT) : 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(); + } + + /** The value at column {@code worldX}, {@code worldZ}: {@code min} when the bounds are equal, halfway between + * them when the style is flat, otherwise {@code min + (max - min) * noise} of the style's noise seeded with + * {@code seed}. + */ + public double at(NoiseFactory noise, long seed, double worldX, double worldZ) { + if (min == max) { + return min; + } + if (style().isFlat()) { + return (min + max) / 2; + } + 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()); + } + + @Override + public int hashCode() { + return Objects.hash(min, max, style()); + } + + @Override + public String toString() { + return "StyledRange[" + min + ".." + max + ", " + style() + "]"; + } +} diff --git a/src/main/java/com/volmit/resource/PackResources.java b/src/main/java/com/volmit/resource/PackResources.java index cc09275e4..f7e164bdb 100644 --- a/src/main/java/com/volmit/resource/PackResources.java +++ b/src/main/java/com/volmit/resource/PackResources.java @@ -1,6 +1,7 @@ package com.volmit.resource; import com.volmit.block.BlockRegistry; +import com.volmit.noise.NoiseFactory; import java.util.List; import java.util.NoSuchElementException; import java.util.Optional; @@ -19,6 +20,10 @@ public interface PackResources { ResourceId packId(); UUID snapshotId(); BlockRegistry blocks(); + + /** Builds the noise of the {@link com.volmit.noise.NoiseStyle}s the pack's settings describe. */ + NoiseFactory noise(); + Optional find(ResourceKey key); /** The ids of every resource of the kind {@code type} selects, in id order. A type the host does not serve diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureContext.java b/src/main/java/com/volmit/vanilla/VanillaStructureContext.java new file mode 100644 index 000000000..5a5ec797a --- /dev/null +++ b/src/main/java/com/volmit/vanilla/VanillaStructureContext.java @@ -0,0 +1,13 @@ +package com.volmit.vanilla; + +import com.volmit.config.PackSettings; +import com.volmit.resource.PackResources; + +/** The world a {@link VanillaStructureHook} decides for. Valid only while the hook runs. */ +public interface VanillaStructureContext { + /** The resources of the world's pack, module resource kinds included. */ + PackResources resources(); + + /** The module settings the world's dimension declares: its own, and every region and biome it can reach. */ + PackSettings settings(); +} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureHook.java b/src/main/java/com/volmit/vanilla/VanillaStructureHook.java new file mode 100644 index 000000000..beef5d4b1 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/VanillaStructureHook.java @@ -0,0 +1,19 @@ +package com.volmit.vanilla; + +import com.volmit.resource.ResourceId; + +/** A module's say over the platform's own structures. Modules register it with + * {@link com.volmit.FeatureRegistry#registerVanillaStructureHook}; the host asks every hook of the pack before the + * platform starts one of its structures in a world, and when it locates one. + * + *

The host asks once per world, structure and pack snapshot and keeps the answer, so a hook decides from the + * pack (its settings and resources) and never from where a start would be. Rules of several modules combine with + * {@link VanillaStructureRule#and}: any module may block the platform's starts. + */ +@FunctionalInterface +public interface VanillaStructureHook { + /** What this module wants for the platform structure {@code structure}, such as {@code minecraft:village_plains}, + * in the world {@code context} describes. {@link VanillaStructureRule#GENERATE} when the module has no part in it. + */ + VanillaStructureRule rule(ResourceId structure, VanillaStructureContext context); +} diff --git a/src/main/java/com/volmit/vanilla/VanillaStructureRule.java b/src/main/java/com/volmit/vanilla/VanillaStructureRule.java new file mode 100644 index 000000000..421ca9427 --- /dev/null +++ b/src/main/java/com/volmit/vanilla/VanillaStructureRule.java @@ -0,0 +1,40 @@ +package com.volmit.vanilla; + +/** What a module wants for one of the platform's own structures, the ones Minecraft, data packs and mods register + * (such as {@code minecraft:village_plains}), in a world: whether the platform may start it where it would on its + * own, and whether the module places it itself. + */ +public enum VanillaStructureRule { + /** The platform generates the structure where it would; the module has no part in it. */ + GENERATE, + /** The platform generates the structure where it would, and the module also places it, where it chooses. */ + ALSO_PLACE, + /** The module places the structure instead of the platform: the platform's own starts of it are blocked. */ + REPLACE, + /** The platform's own starts of the structure are blocked, and the module does not place it either. */ + BLOCK; + + /** Whether the platform's own starts of the structure are blocked. */ + public boolean blocksPlatform() { + return this == REPLACE || this == BLOCK; + } + + /** Whether the module places the structure itself, so the host locates it through the module. */ + public boolean placedByModule() { + return this == ALSO_PLACE || this == REPLACE; + } + + /** What two modules' rules for one structure mean together: the platform's starts are blocked when either + * blocks them, and the structure is placed by a module when either places it. The order does not matter. + */ + public VanillaStructureRule and(VanillaStructureRule other) { + return of(blocksPlatform() || other.blocksPlatform(), placedByModule() || other.placedByModule()); + } + + private static VanillaStructureRule of(boolean blocksPlatform, boolean placedByModule) { + if (blocksPlatform) { + return placedByModule ? REPLACE : BLOCK; + } + return placedByModule ? ALSO_PLACE : GENERATE; + } +} diff --git a/src/main/java/com/volmit/world/BlockPosition.java b/src/main/java/com/volmit/world/BlockPosition.java index 24dcf2da4..ea0f674f2 100644 --- a/src/main/java/com/volmit/world/BlockPosition.java +++ b/src/main/java/com/volmit/world/BlockPosition.java @@ -4,6 +4,13 @@ package com.volmit.world; * world X and Z and a Y that is the height above the dimension's bottom (0 = bottom). */ public record BlockPosition(int x, int y, int z) implements Comparable { + /** The origin, which settings start from before the host reads their JSON: packs write {@code {"x": 1, "y": 2, "z": 3}}, + * and an omitted coordinate is 0. + */ + private BlockPosition() { + this(0, 0, 0); + } + public BlockPosition add(BlockPosition offset) { return new BlockPosition(Math.addExact(x, offset.x), Math.addExact(y, offset.y), Math.addExact(z, offset.z)); } diff --git a/src/main/java/com/volmit/world/NoiseSampler.java b/src/main/java/com/volmit/world/NoiseSampler.java deleted file mode 100644 index bfa92e57e..000000000 --- a/src/main/java/com/volmit/world/NoiseSampler.java +++ /dev/null @@ -1,10 +0,0 @@ -package com.volmit.world; - -/** Immutable, seeded noise resource. X and Z are world coordinates; Y is the - * height above the dimension's bottom (0 = bottom). - * Range and scale belong to the resource; no implicit normalization is performed. - */ -@FunctionalInterface -public interface NoiseSampler { - double sample(double worldX, double y, double worldZ); -} diff --git a/src/test/java/com/volmit/SettingsValuesTest.java b/src/test/java/com/volmit/SettingsValuesTest.java new file mode 100644 index 000000000..96f739ee9 --- /dev/null +++ b/src/test/java/com/volmit/SettingsValuesTest.java @@ -0,0 +1,116 @@ +package com.volmit; + +import com.volmit.block.BlockSpec; +import com.volmit.config.Range; +import com.volmit.noise.NoiseFactory; +import com.volmit.noise.NoiseSampler; +import com.volmit.noise.NoiseStyle; +import com.volmit.noise.StyledRange; +import com.volmit.random.WorldRandom; +import com.volmit.vanilla.VanillaStructureRule; +import org.junit.jupiter.api.Test; +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import static com.volmit.vanilla.VanillaStructureRule.*; +import static org.junit.jupiter.api.Assertions.*; + +/** The value types settings hold and the rules of vanilla structure hooks. */ +class SettingsValuesTest { + @Test + void blockSpecsAreValuesWithTheDefaultsPacksGetWhenTheyLeaveOptionsOut() { + var spec = BlockSpec.of("iron_ore").withProperty("waterlogged", "true").withWeight(3) + .withBackup(BlockSpec.of("stone")).withTileData(Map.of("Delay", 20.0)); + + assertEquals("iron_ore", spec.block()); + assertEquals(Map.of("waterlogged", "true"), spec.data()); + assertEquals(3, spec.weight()); + assertEquals(Optional.of(BlockSpec.of("stone")), spec.backup()); + assertEquals(Map.of("Delay", 20.0), spec.tileData()); + assertEquals(spec, BlockSpec.of("iron_ore").withProperty("waterlogged", "true").withWeight(3) + .withBackup(BlockSpec.of("stone")).withTileData(Map.of("Delay", 20.0))); + assertNotEquals(spec, spec.withWeight(1)); + assertEquals(1, BlockSpec.of("stone").weight()); + assertEquals(Optional.empty(), BlockSpec.of("stone").backup()); + assertThrows(UnsupportedOperationException.class, () -> spec.data().clear()); + assertThrows(UnsupportedOperationException.class, () -> spec.tileData().clear()); + } + + @Test + void noiseStylesNameTheHostsStyleAndAreFlatOnlyWithoutExpressionOrImageMap() { + var simplex = NoiseStyle.of("SIMPLEX").withZoom(0.08); + + assertEquals("SIMPLEX", simplex.style()); + assertEquals(0.08, simplex.zoom()); + assertEquals(1, NoiseStyle.of("SIMPLEX").zoom()); + assertEquals(simplex, NoiseStyle.of("SIMPLEX").withZoom(0.08)); + assertEquals(simplex.hashCode(), NoiseStyle.of("SIMPLEX").withZoom(0.08).hashCode()); + assertNotEquals(simplex, NoiseStyle.of("SIMPLEX")); + assertTrue(NoiseStyle.of(NoiseStyle.FLAT).isFlat()); + assertFalse(simplex.isFlat()); + assertEquals(Optional.empty(), simplex.expression()); + assertEquals(Optional.empty(), simplex.fracture()); + } + + @Test + void styledRangesPickBetweenTheirBoundsWithTheStylesNoise() { + var asked = new ArrayList(); + NoiseFactory noise = (style, seed) -> { + asked.add(style.style() + "@" + seed); + return fixed(0.25); + }; + var styled = StyledRange.of(10, 30, NoiseStyle.of("SIMPLEX")); + + assertEquals(15, styled.at(noise, 7, 100, 200)); + assertEquals(List.of("SIMPLEX@7"), asked); + assertEquals(20, StyledRange.of(10, 30, NoiseStyle.of(NoiseStyle.FLAT)).at(noise, 7, 0, 0), "flat: halfway"); + assertEquals(10, StyledRange.of(10, 10, NoiseStyle.of("SIMPLEX")).at(noise, 7, 0, 0), "equal bounds"); + assertEquals(1, asked.size(), "neither flat nor equal bounds build noise"); + assertTrue(StyledRange.of(10, 10, NoiseStyle.of("SIMPLEX")).isFlat()); + assertFalse(styled.isFlat()); + } + + @Test + void rangesIncludeBothBoundsAndPickWithOneDraw() { + var range = Range.of(2, 6); + + assertTrue(range.contains(2)); + assertTrue(range.contains(6)); + assertFalse(range.contains(6.5)); + var picks = new WorldRandom(42); + var expected = new WorldRandom(42); + assertEquals(2 + expected.nextDouble() * 4, range.pick(picks)); + assertEquals(expected.nextLong(), picks.nextLong(), "one draw per pick"); + assertEquals(3, Range.of(3, 3).pick(picks)); + assertEquals(expected.nextLong(), picks.nextLong(), "no draw when the bounds are equal"); + } + + @Test + void vanillaStructureRulesCombineBlockingAndPlacingWhateverTheOrder() { + var expected = Map.of( + List.of(GENERATE, GENERATE), GENERATE, + List.of(GENERATE, ALSO_PLACE), ALSO_PLACE, + List.of(GENERATE, BLOCK), BLOCK, + List.of(ALSO_PLACE, BLOCK), REPLACE, + List.of(GENERATE, REPLACE), REPLACE, + List.of(BLOCK, BLOCK), BLOCK); + expected.forEach((rules, combined) -> { + assertEquals(combined, rules.get(0).and(rules.get(1)), rules.toString()); + assertEquals(combined, rules.get(1).and(rules.get(0)), rules.toString()); + }); + for (VanillaStructureRule rule : VanillaStructureRule.values()) { + assertEquals(rule, rule.and(GENERATE), "GENERATE changes nothing"); + } + assertTrue(REPLACE.blocksPlatform() && REPLACE.placedByModule()); + assertTrue(BLOCK.blocksPlatform() && !BLOCK.placedByModule()); + assertTrue(!ALSO_PLACE.blocksPlatform() && ALSO_PLACE.placedByModule()); + } + + private static NoiseSampler fixed(double value) { + return new NoiseSampler() { + public double sample(double worldX, double worldZ) { return value; } + public double sample(double worldX, double y, double worldZ) { return value; } + }; + } +} diff --git a/src/test/java/com/volmit/example/hosttypes/Palette.java b/src/test/java/com/volmit/example/hosttypes/Palette.java index d802fc4f1..325b742c8 100644 --- a/src/test/java/com/volmit/example/hosttypes/Palette.java +++ b/src/test/java/com/volmit/example/hosttypes/Palette.java @@ -5,7 +5,7 @@ import java.util.List; /** Stands for a host class such as Iris's material palette: the host describes it in studio itself. */ public final class Palette { private List blocks = List.of("minecraft:stone"); - private Object anything; + private java.util.UUID anything; public List blocks() { return blocks; diff --git a/src/test/java/com/volmit/host/ModuleRegistryTest.java b/src/test/java/com/volmit/host/ModuleRegistryTest.java index 0ead31edc..6f93f55ad 100644 --- a/src/test/java/com/volmit/host/ModuleRegistryTest.java +++ b/src/test/java/com/volmit/host/ModuleRegistryTest.java @@ -5,6 +5,8 @@ import com.volmit.config.Feature; import com.volmit.mantle.*; import com.volmit.resource.ResourceKind; import com.volmit.validation.Validator; +import com.volmit.vanilla.VanillaStructureHook; +import com.volmit.vanilla.VanillaStructureRule; import com.volmit.stage.PlacementStage; import com.volmit.stage.Stage; import com.volmit.stage.StageGraph; @@ -248,6 +250,25 @@ class ModuleRegistryTest { assertThrows(IllegalStateException.class, () -> registry.registerValidator(pack -> {}), "registration has ended"); } + @Test + void vanillaStructureHooksAreCataloguedByModuleIdInTheOrderEachModuleRegisteredThem() { + var registry = new ModuleRegistry(); + VanillaStructureHook first = (structure, world) -> VanillaStructureRule.REPLACE; + VanillaStructureHook second = (structure, world) -> VanillaStructureRule.GENERATE; + VanillaStructureHook other = (structure, world) -> VanillaStructureRule.BLOCK; + registerAs(registry, "test:zeta", hooks -> hooks.registerVanillaStructureHook(other)); + registerAs(registry, "test:alpha", hooks -> { + hooks.registerVanillaStructureHook(first); + hooks.registerVanillaStructureHook(second); + }); + + assertThrows(IllegalStateException.class, () -> registry.registerVanillaStructureHook(first), "outside register"); + var hooks = registry.freeze().vanillaStructureHooks(); + assertEquals(List.of(first, second, other), hooks.stream().map(VanillaStructureHookRegistration::hook).toList()); + assertEquals("test:alpha", hooks.getFirst().module().info().id().toString()); + assertThrows(IllegalStateException.class, () -> registry.registerVanillaStructureHook(first), "registration has ended"); + } + private static MantleCodec codec(int version) { return new MantleCodec<>() { public int version() { return version; } diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java index ae340d643..03226510e 100644 --- a/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -14,6 +14,7 @@ import com.volmit.host.schema.PackSchema; import com.volmit.host.schema.ResourceKindSchema; import com.volmit.host.schema.SchemaOption; import com.volmit.host.schema.TextFormat; +import com.volmit.host.schema.ValueKind.AnyKind; import com.volmit.host.schema.ValueKind.BooleanKind; import com.volmit.host.schema.ValueKind.DecimalKind; import com.volmit.host.schema.ValueKind.EnumConstant; @@ -416,6 +417,66 @@ class PackSchemaTest { assertEquals(expected, loadFailure(body, otherSources).getMessage()); } + @Test + void settingsMayHoldTheApisValueTypesWhichAreDescribedLikeSettings() { + var pack = pack("values"); + module("pack.flora.FloraModule", FLORA, + "public void register(com.volmit.FeatureRegistry registry) { registry.registerSettings(FloraSettings.class); }", NO_STAGES) + .source("pack.flora.FloraSettings", """ + package pack.flora; + + import com.volmit.FeatureAttachment.Target; + import com.volmit.IrisFeature; + import com.volmit.block.BlockSpec; + import com.volmit.config.Feature; + import com.volmit.config.Range; + import com.volmit.noise.NoiseStyle; + import com.volmit.noise.StyledRange; + import com.volmit.world.BlockPosition; + import java.util.*; + + @Feature(id = "example:flora", name = "Flora", targets = Target.BIOME) + public final class FloraSettings implements IrisFeature { + private List palette = List.of(BlockSpec.of("poppy")); + private NoiseStyle style = NoiseStyle.of("SIMPLEX").withZoom(4); + private StyledRange height = StyledRange.of(2, 5, NoiseStyle.of("SIMPLEX")); + private Range light = Range.of(0, 15); + private BlockPosition offset = new BlockPosition(1, 2, 3); + private Object extra; + } + """) + .writeInto(pack, "flora.jar"); + var schema = schemaOf(pack, NO_BUILT_INS); + var settings = schema.type("pack.flora.FloraSettings"); + + assertEquals(new ListKind(new ObjectKind("com.volmit.block.BlockSpec"), false), option(settings, "palette").kind()); + assertEquals(Optional.of(List.of(Map.of("block", "poppy", "data", Map.of(), "tileData", Map.of(), "weight", 1L))), + option(settings, "palette").defaultValue()); + assertEquals(new ObjectKind("com.volmit.noise.NoiseStyle"), option(settings, "style").kind()); + assertEquals(new ObjectKind("com.volmit.noise.StyledRange"), option(settings, "height").kind()); + assertEquals(new ObjectKind("com.volmit.config.Range"), option(settings, "light").kind()); + assertEquals(Optional.of(Map.of("max", 15.0, "min", 0.0)), option(settings, "light").defaultValue()); + assertEquals(new ObjectKind("com.volmit.world.BlockPosition"), option(settings, "offset").kind()); + assertEquals(Optional.of(Map.of("x", 1L, "y", 2L, "z", 3L)), option(settings, "offset").defaultValue()); + assertEquals(new AnyKind(), option(settings, "extra").kind(), "Object holds any JSON value"); + + var block = schema.type("com.volmit.block.BlockSpec"); + assertEquals(List.of("block", "data", "weight", "backup", "tileData"), block.options().stream().map(SchemaOption::name).toList()); + assertEquals(new ReferenceKind(Reference.BLOCK, TextFormat.PLAIN), option(block, "block").kind()); + assertEquals(new MapKind(new TextKind(TextFormat.PLAIN)), option(block, "data").kind()); + assertEquals(new MapKind(new AnyKind()), option(block, "tileData").kind()); + assertEquals(new ObjectKind("com.volmit.block.BlockSpec"), option(block, "backup").kind()); + assertEquals(Optional.of("air"), option(block, "block").defaultValue()); + + var style = schema.type("com.volmit.noise.NoiseStyle"); + assertEquals(Optional.of("style"), style.snippet(), "API classes keep the snippet folders packs already use"); + assertEquals(new ReferenceKind(Reference.NOISE_STYLE, TextFormat.PLAIN), option(style, "style").kind()); + assertEquals(new ReferenceKind(Reference.PACK_EXPRESSION, TextFormat.PLAIN), option(style, "expression").kind()); + assertEquals(new ReferenceKind(Reference.PACK_IMAGE_MAP, TextFormat.PLAIN), option(style, "imageMap").kind()); + assertEquals(Optional.of("FLAT"), option(style, "style").defaultValue()); + assertEquals(List.of("range", "style", "style-range"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList()); + } + @Test void defaultsLeaveOutWhatJsonCannotHold() { var pack = pack("defaults");