diff --git a/CONTRACTS.md b/CONTRACTS.md index 564967b33..cec5007fd 100644 --- a/CONTRACTS.md +++ b/CONTRACTS.md @@ -25,9 +25,9 @@ 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`, `@MinItems`, `@Snippet`, `@Ref`/`Reference`, `FeatureRegistry.registerSettings`, host `LoadedPack.schema()` (`PackSchema`, `FeatureSchema`, `ObjectType`, `SchemaOption`, `ValueKind` with `HostKind`), `ModuleHost.describingHostTypesIn` | | Geometry and mantle registration | `FeatureRegistry`, host `ModuleRegistry`, `FeatureCatalog` | -| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette`, `BlockSpec` (`BlockRegistry.resolve(BlockSpec)`, `blockEntity`) | +| Block states and palettes | `BlockState`, `BlockRegistry`, `BlockPalette`, `BlockSpec` (`BlockRegistry.resolve(BlockSpec)`, `blockEntity`), `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) | | Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` | -| Values in settings | `BlockSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`, `Object` as `ValueKind.AnyKind` | +| Values in settings | `BlockSpec`, `PaletteSpec`, `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` | @@ -176,7 +176,7 @@ running Iris is the pack publisher's responsibility. searches off the server's main thread, and carry out what they return on the thread the platform needs. - Read a `StructureLocator` position's Y as a height above the dimension's bottom and convert it to the platform's Y at the boundary, like every other IrisApi height. -- Decode IrisApi's value types like settings: `BlockSpec`, `NoiseStyle`, `StyledRange`, `Range` and +- Decode IrisApi's value types like settings: `BlockSpec`, `PaletteSpec`, `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; @@ -186,6 +186,8 @@ running Iris is the pack publisher's responsibility. expression falls back to the base style, and a missing image map fails. - 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. +- Build `BlockRegistry.palette(spec, seed)` pickers: blocks expanded by weight, the style's noise at (x, y, z) over + the zoom picks the entry, resolved as above, cached per pack snapshot; refuse a palette without a block to pick. - 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 diff --git a/DESIGN.md b/DESIGN.md index 1575c5b93..febbdb4c3 100644 --- a/DESIGN.md +++ b/DESIGN.md @@ -739,6 +739,7 @@ withers return copies, and equality is by value, so the host can cache by them. | --- | --- | --- | | `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)` | +| `IrisMaterialPalette` | `com.volmit.block.PaletteSpec` | `BlockRegistry.palette(PaletteSpec, seed)`, a `PaletteSampler` | | `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)` | @@ -762,6 +763,12 @@ Why these lines: - **`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. +- **A palette is a value plus a picker, not a new `BlockPalette`.** `BlockPalette.select` takes a random stream + and a block per call, which is how a module picks by chance; `IrisMaterialPalette` picks by noise at the + position, so `PaletteSampler.at(x, y, z)` has no stream. The picker takes doubles because Iris's does (zoom + divides them), and the seed is the one the old code gave its `RNG`, so a module can keep the layout of old worlds. + A palette without a pickable block throws when the sampler is asked for, where Iris returned `null`: the API has + no absent block, and `@MinItems(1)` already says a palette needs one. - **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. diff --git a/README.md b/README.md index 1397efc1b..f4c26d504 100644 --- a/README.md +++ b/README.md @@ -430,6 +430,7 @@ Settings describe blocks, noise and ranges with IrisApi's value types, which rea | 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 | +| `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` | | `StyledRange` | `{"min": 4, "max": 12, "style": {...}}` | `range.at(resources.noise(), seed, x, z)` | | `Range` | `{"min": 0, "max": 15}` | `contains(value)`, `pick(random)` | @@ -452,11 +453,14 @@ Noise belongs to the host: a style names one of its noise generators (`@Ref(Refe 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. +have; resolving it never fails: the backup, then air, stands in. A `PaletteSpec` picks one of its blocks per position +by noise (each block counts as often as its weight, the style's noise at x, y, z over `zoom` chooses); a palette of +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. 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`). +own default says otherwise). They keep the snippet folders packs already use (`style`, `style-range`, `range`, `palette`). 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 @@ -662,7 +666,7 @@ Optional clock = pack.catalog().service(Clock.class); // a Pro 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 and resolves `BlockSpec`s. `BlockPalette` and `NoiseSampler` are typed resources; + platform and resolves `BlockSpec`s. `BlockPalette` and `NoiseSampler` are typed resources (`PaletteSampler` is the noise-picked palette of settings); `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. @@ -707,7 +711,7 @@ of a host type, for a folder two kinds claim or the host reserves, and for a mis order, the load error for a second provider of a `ONE` service and for providers of unmarked interfaces or of the wrong type. `WorldStatesTest` checks that each state is created once (also when threads race), nested creation, the error for a type asked for while it is created, factories that fail or return null, and closing newest first past -failures. `LifecycleRunnerTest` checks hook order, stops in reverse, the stop of already started modules when a start +failures. `LifecycleRunnerTest` checks hook order, warm-ups after the starts (each running even when one fails), stops in reverse, the stop of already started modules when a start fails, and that every stop runs. `WorldStateExampleTest` (`example/world`) has a chunk stage, a service and a hook share one world's state, and a new world start empty. `PackSchemaTest` also describes settings holding IrisApi's value types (`BlockSpec`, `NoiseStyle`, `StyledRange`, `Range`, `BlockPosition`) and `Object`, and `SettingsValuesTest` checks the value types themselves diff --git a/src/main/java/com/volmit/block/BlockRegistry.java b/src/main/java/com/volmit/block/BlockRegistry.java index 78ed02869..adccb766b 100644 --- a/src/main/java/com/volmit/block/BlockRegistry.java +++ b/src/main/java/com/volmit/block/BlockRegistry.java @@ -24,6 +24,16 @@ public interface BlockRegistry { */ Optional blockEntity(BlockSpec spec); + /** The picker for {@code spec}: every block counts as often as its weight, and the entry at a position is chosen by + * the style's noise at (x, y, z) divided by the zoom, so the palette changes smoothly over the world; a palette of + * one block always gives it. Blocks resolve as {@link #resolve(BlockSpec)}. Seed the noise like + * {@link com.volmit.noise.NoiseFactory#sampler}: from the world seed when the palette must line up across chunks. + * The host keeps what it builds for the pack snapshot, so asking again for the same palette and seed is cheap. + * + * @throws IllegalArgumentException when no block of the palette has a weight above zero, which includes an empty list + */ + PaletteSampler palette(PaletteSpec spec, long seed); + 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/PaletteSampler.java b/src/main/java/com/volmit/block/PaletteSampler.java new file mode 100644 index 000000000..39bf4eef2 --- /dev/null +++ b/src/main/java/com/volmit/block/PaletteSampler.java @@ -0,0 +1,11 @@ +package com.volmit.block; + +/** The block a {@link PaletteSpec} picks at a position, built by the host ({@link BlockRegistry#palette}). The + * coordinates are the noise's input, so they are the same kind the module's other noise uses: world X and Z, and Y as the + * module counts it, which is the height above the dimension's bottom unless the module documents otherwise. The same + * position always gives the same block. Safe for concurrent calls. + */ +@FunctionalInterface +public interface PaletteSampler { + BlockState at(double x, double y, double z); +} diff --git a/src/main/java/com/volmit/block/PaletteSpec.java b/src/main/java/com/volmit/block/PaletteSpec.java new file mode 100644 index 000000000..35b828eca --- /dev/null +++ b/src/main/java/com/volmit/block/PaletteSpec.java @@ -0,0 +1,94 @@ +package com.volmit.block; + +import com.volmit.config.Desc; +import com.volmit.config.MinItems; +import com.volmit.config.MinNumber; +import com.volmit.config.Required; +import com.volmit.config.Snippet; +import com.volmit.noise.NoiseStyle; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +/** A palette of blocks as packs write it in settings, such as + * {@code {"style": "SIMPLEX", "zoom": 8, "palette": [{"block": "stone"}, {"block": "andesite", "weight": 2}]}}, or a + * snippet under {@code snippet/palette/}. The blocks are picked by noise: the host picks the entry the style's noise + * 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. + */ +@Snippet("palette") +@Desc("A palette of materials") +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") + private NoiseStyle style = NoiseStyle.of(DEFAULT_STYLE); + + @MinNumber(0.0001) + @Desc("The terrain zoom mostly for zooming in on a wispy palette") + private double zoom = DEFAULT_ZOOM; + + @Required + @MinItems(1) + @Desc("The palette of blocks to be used in this layer") + private List palette = List.of(BlockSpec.of(DEFAULT_BLOCK)); + + private PaletteSpec() { + } + + private PaletteSpec(NoiseStyle style, double zoom, List palette) { + this.style = Objects.requireNonNull(style, "style"); + this.zoom = zoom; + this.palette = List.copyOf(palette); + } + + /** A palette of {@code blocks} with the default style and zoom. */ + public static PaletteSpec of(List blocks) { + return new PaletteSpec(NoiseStyle.of(DEFAULT_STYLE), DEFAULT_ZOOM, blocks); + } + + public PaletteSpec withStyle(NoiseStyle style) { + return new PaletteSpec(style, zoom, palette()); + } + + /** This palette with zoom {@code zoom}: above 1 stretches the noise that picks the blocks, below 1 squeezes it. */ + public PaletteSpec withZoom(double zoom) { + return new PaletteSpec(style(), zoom, palette()); + } + + /** 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; + } + + /** The factor the position is divided by before it is looked up in the noise. */ + public double zoom() { + return zoom; + } + + /** The blocks to pick from, as the pack wrote them. */ + public List palette() { + return palette == null ? List.of() : Collections.unmodifiableList(palette); + } + + @Override + public boolean equals(Object other) { + return other instanceof PaletteSpec spec && style().equals(spec.style()) + && Double.compare(zoom, spec.zoom) == 0 && palette().equals(spec.palette()); + } + + @Override + public int hashCode() { + return Objects.hash(style(), zoom, palette()); + } + + @Override + public String toString() { + return "PaletteSpec[" + palette() + ", " + style() + ", zoom " + zoom + "]"; + } +} diff --git a/src/test/java/com/volmit/SettingsValuesTest.java b/src/test/java/com/volmit/SettingsValuesTest.java index 96f739ee9..774f4719c 100644 --- a/src/test/java/com/volmit/SettingsValuesTest.java +++ b/src/test/java/com/volmit/SettingsValuesTest.java @@ -1,6 +1,8 @@ package com.volmit; import com.volmit.block.BlockSpec; +import com.volmit.block.PaletteSpec; +import com.volmit.config.OptionsMetadata; import com.volmit.config.Range; import com.volmit.noise.NoiseFactory; import com.volmit.noise.NoiseSampler; @@ -53,6 +55,23 @@ class SettingsValuesTest { assertEquals(Optional.empty(), simplex.fracture()); } + @Test + void palettesAreValuesWhoseDefaultsAreThoseOfIrisMaterialPalettes() { + var options = OptionsMetadata.inspect(PaletteSpec.class); + var palette = PaletteSpec.of(List.of(BlockSpec.of("stone"), BlockSpec.of("andesite").withWeight(2))); + + assertEquals(List.of("style", "zoom", "palette"), options.options().stream().map(OptionsMetadata.Option::name).toList()); + assertEquals("palette", options.snippet()); + assertEquals(1, options.options().get(2).minItems()); + assertEquals(0.0001, options.options().get(1).minimum()); + assertEquals(NoiseStyle.of("STATIC"), palette.style()); + assertEquals(5, palette.zoom()); + assertEquals(palette.withZoom(8).withStyle(NoiseStyle.of("SIMPLEX")), palette.withStyle(NoiseStyle.of("SIMPLEX")).withZoom(8)); + assertNotEquals(palette, palette.withZoom(8)); + assertEquals(palette.hashCode(), PaletteSpec.of(palette.palette()).hashCode()); + assertThrows(UnsupportedOperationException.class, () -> palette.palette().clear()); + } + @Test void styledRangesPickBetweenTheirBoundsWithTheStylesNoise() { var asked = new ArrayList(); diff --git a/src/test/java/com/volmit/host/PackSchemaTest.java b/src/test/java/com/volmit/host/PackSchemaTest.java index 89ed3d168..00b6ab21f 100644 --- a/src/test/java/com/volmit/host/PackSchemaTest.java +++ b/src/test/java/com/volmit/host/PackSchemaTest.java @@ -421,6 +421,7 @@ class PackSchemaTest { import com.volmit.FeatureAttachment.Target; import com.volmit.IrisFeature; import com.volmit.block.BlockSpec; + import com.volmit.block.PaletteSpec; import com.volmit.config.Feature; import com.volmit.config.Range; import com.volmit.noise.NoiseStyle; @@ -432,6 +433,7 @@ class PackSchemaTest { public final class FloraSettings implements IrisFeature { private List palette = List.of(BlockSpec.of("poppy")); private NoiseStyle style = NoiseStyle.of("SIMPLEX").withZoom(4); + private PaletteSpec ground = PaletteSpec.of(List.of(BlockSpec.of("grass_block"))); 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); @@ -446,6 +448,7 @@ class PackSchemaTest { 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.block.PaletteSpec"), option(settings, "ground").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()); @@ -461,13 +464,22 @@ class PackSchemaTest { assertEquals(new ObjectKind("com.volmit.block.BlockSpec"), option(block, "backup").kind()); assertEquals(Optional.of("air"), option(block, "block").defaultValue()); + var ground = schema.type("com.volmit.block.PaletteSpec"); + assertEquals(Optional.of("palette"), ground.snippet()); + assertEquals(List.of("style", "zoom", "palette"), ground.options().stream().map(SchemaOption::name).toList()); + assertEquals(new ListKind(new ObjectKind("com.volmit.block.BlockSpec"), false), option(ground, "palette").kind()); + assertTrue(option(ground, "palette").required()); + assertEquals(OptionalInt.of(1), option(ground, "palette").minItems()); + assertEquals(OptionalDouble.of(0.0001), option(ground, "zoom").minimum()); + assertEquals(Optional.of(5.0), option(ground, "zoom").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()); + assertEquals(List.of("palette", "range", "style", "style-range"), schema.snippets().stream().map(type -> type.snippet().orElseThrow()).toList()); } @Test