Tighten the tooling package and document it

JsonText only reads now; splicing text is the host's, as the studio makes
every write. JsonPath steps are a sealed Key or Index. Absent values are
empty instead of -1 or blank: GraphNode.part, BlockPattern.pickAt and the
entries' group. GraphNode's child list, movability and additions are one
Edits record.

README and DESIGN describe the tooling package, CONTRACTS maps it, and the
docs no longer name the types the last batch removed.
This commit is contained in:
piexel committed 2026-11-06 06:09:12 +01:00
1 parent 2b6f96e5c2
commit cdd138d9f4
13 files changed
+213 -298

No files matched your search

+4 -3
View File
@@ -28,7 +28,7 @@ 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` (with `resources()`, for a reach that depends on the size of the pack's objects), 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` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `merge`, `withProperty`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockPalette`, `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) |
| Block states and palettes | `BlockState`, `BlockRegistry` (`resolve(BlockSpec)`, `find(key)`, `blockEntity`, `hasTrait`, `oreFor`, `rotate(state, BlockTurn)`, `merge`, `withProperty`, `matches`), `BlockTurn`, `BlockTrait` (with `STORAGE`), `BlockSpec`, `PaletteSpec` and `PaletteSampler` (`BlockRegistry.palette`) |
| A pack's objects | `PlaceableObject` (`name`, size, `center`, `geometry`), `PackObjects` (`object`, `sizeOf`, `scaled` with `ScaleMethod`, `smartBored`, `build`), `PackResources.objects()` |
| Placing through the pack's placement graph | `Placements.place(PlacementRun)` (`PackWorld.placements()`), `PlacementRun` (request, name, settings JSON, area, terrain, input, seed), `PlacementTerrain` (`recordPlacement` / `placementAt` with a `PlacementRecord`), `StructureVolumes`, `PlacedMarker`, `PlacementOutcome`; stages read `PlacementContext.placementTerrain()` and `input(type)`; mantle stages get a terrain from `MantleGenerationContext.placementTerrain()`; `RunningWorld.placementAt` reads what a placement recorded; `FeatureRegistry.registerPlacementType` names the type packs write placements as (host `FeatureCatalog.placementType()`, `PackSchema.placementType()`) |
| Noise from pack-described styles | `NoiseStyle`, `StyledRange`, `PackResources.noise()`, `NoiseFactory`, `NoiseSampler` |
@@ -43,7 +43,8 @@ types that carry them and lists what the Iris adapter still owes.
| Terrain and settings sampling | `TerrainSampler`, `BiomeSample`, `TerrainSample`, `FeatureSettings` |
| Dense chunk output | `Hunk<T>`, `GenerationContext.blocks`, reference `ArrayHunk<T>` |
| Positions, boxes and faces | `com.volmit.geometry`: `BlockPosition`, `BlockBox`, `BlockFace` |
| Sparse geometry and transforms | `ObjectGenerator`, `GeneratedObject`, `ObjectTransform`, `ObjectTransformer` |
| Sparse geometry | `GeneratedObject` |
| Studio views of what a module builds | `com.volmit.tooling`: `ModuleSetup.tooling()` (`ToolingRegistry.registerView`), sealed `StudioView` (`SceneView` with `SceneEntry`, `PatternView` with `PatternEntry`, `PatternArea`, `BlockPattern`), `EditableSceneView` (`SceneFile`, `NodeGraph`, `GraphNode` with `Link`, `NodeSettings`, `Edits`, `Addition`), `JsonText`, `JsonPath` (`Key`, `Index`), host `StudioViewRegistration` |
| Buffered placement writes | `PlacementRequest`, `PlacementAccess`, host-owned `PlacementEdit` |
| Typed generation and persistent storage | `mantle` package |
@@ -236,7 +237,7 @@ running Iris is the pack publisher's responsibility.
`EntitySpawns` and `SaplingGrowth`.
- Create what `ItemDrop` and `EntitySpec` describe on the platform, skip what the platform lacks (an unknown enchantment,
attribute or item flag) with a warning, route a `ContentKey.Provided` (and a `Registered` id of a namespace another
plugin owns) to that plugin, apply the `EntitySpec.extensions()` of the host's own types and ignore the rest, and run the checks that come with an `EntitySpawns.Attempt` (light, surface,
plugin owns) to that plugin, and run the checks that come with an `EntitySpawns.Attempt` (light, surface,
free space) before spawning. Report how many entities appeared with `EntitySpawns.spawned`. Apply `Arrival.reason`
(the platform's own name for the spawn reason, natural when it is empty or unknown), `Arrival.risesFromGround`, a
panda's `Appearance` genes, and `adjustsProvidedMob` (a `ContentKey.Provided` mob is otherwise left as its provider set it up).
+31 -19
View File
@@ -537,15 +537,12 @@ A block stage gets one stream per placement and draws from it across the blocks
order. Fused block stages interleave per block, but each still draws only from its own stream. A
stage that never draws never creates its stream.
Object generators are not stages. `ObjectGenerationContext.random()` stays, a `WorldRandom` seeded
from the variant seed the host chooses.
## Coordinates
X and Z are world coordinates. Y is the height above the dimension's bottom: 0 is always the dimension's
bottom block, whatever its minimum height is in the platform, so Y is never negative. That applies to
every value that carries a height: `TerrainSample` heights, `TerrainSampler` and `BlockView` positions and
bounds, `BlockPalette` and `NoiseSampler` sample positions, `PlacedBlock` and `PlacedMarker` positions,
bounds, `PaletteSampler` and `NoiseSampler` sample positions, `PlacedBlock` and `PlacedMarker` positions,
placement anchors, `Mantle` positions and bounds, and a chunk `Hunk`'s local y. `BlockBox` carries
whichever coordinates its owner defines; an object's bounds are local to the object, and a placed
footprint can extend below height 0 where the object overhangs the bottom. The host converts to and from
@@ -701,8 +698,8 @@ key, the JSON field packs write the settings under; add key = "floraWildPatch" (
rebuild the jar`.
`GeneratedObject` is sparse, immutable local geometry with bounds, an anchor, sorted blocks,
optional block entity payloads and markers. `ObjectGenerator` produces it from settings and a
`WorldRandom`. `ObjectTransformer` is host-owned.
optional block entity payloads and markers. A module builds it (`PackObjects.build`, or from the blocks it
chose) and turns it itself; the API has no generator or transformer type, as no module needed one.
The mantle contracts are unchanged: namespaced typed keys, versioned codecs, generation and
persistent lifetimes, ordered sparse visits and buffered edits. Only owners register a layer.
@@ -726,9 +723,8 @@ core engine is modules as well. The host's own JSON fields are not in it; no key
### Shape
- A `FeatureSchema` per catalogued type: feature id and name, role (`SETTINGS` for types named in
`when(...)` or registered with `registerSettings`, `OBJECT_GENERATOR` for `registerObject`), the
owning module's `ModuleInfo`, the JSON key the feature declares, its `root` option when the key holds one
- A `FeatureSchema` per catalogued type (named in `when(...)` or registered with `registerSettings`): feature id
and name, the owning module's `ModuleInfo`, the JSON key the feature declares, its `root` option when the key holds one
option's value (`rootOption()`), its targets and the settings `ObjectType`. `fields(target)` lists a target's features; a feature attached to several targets appears under
each. The owner is the one module whose id owns the feature id; module ids are unique and contain
no `/`, so there is never more than one.
@@ -897,7 +893,7 @@ a host bug.
| `IrisRange` | `com.volmit.config.Range` | none: `contains`, `pick(WorldRandom)` |
| `IrisPosition` | `com.volmit.geometry.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) |
| `IrisObjectRotation`, `IrisObjectScale` | none: settings of the module that picks a rotation or scale | none: the module turns the blocks (`BlockRegistry.rotate`) |
| `ObjectPlaceMode` | none: an enum of the placement modules | |
Why these lines:
@@ -946,9 +942,8 @@ 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
- **A palette is a value plus a picker.** `IrisMaterialPalette` picks by noise at the position, so
`PaletteSampler.at(x, y, z)` has no stream; a module that picks by chance draws from its own 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.
@@ -960,8 +955,8 @@ Why these lines:
answering them was work for nothing. `BlockAccess.is` answers every trait the registry answers instead of throwing
for the ones outside the structure fit's set.
- **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.
meaning is a feature's (which axes may turn, by which steps; which anchor sampling a mode uses), and the module
turns its own blocks. An API type would freeze a feature's choices.
## Vanilla structures
@@ -1201,9 +1196,8 @@ from a sapling, which drops a block has. A module answers such questions through
(`Look`, `Wear`, `PlatformExtras`; `Appearance`, `Behaviour`, `Company`, `Drops`, `Arrival`), each with a named
default, so a reader sees a dozen meaningful parts instead of seventeen positional ones. What platforms commonly have
(a spawn reason by the platform's name, a panda's genes, rising out of the ground, whether the spec applies to a
provider's mob) is a field of the spec, optional where a platform may lack it. What only one host can apply is not: the
module puts a value of the host's own type in `EntitySpec.extensions()`, the host finds it with `extension(type)`, and
other hosts ignore it.
provider's mob) is a field of the spec, optional where a platform may lack it. The spec has no slot for what only one
host could apply: nothing needed one once those fields moved in.
`AmbientEffects` follows the same rule: the module decides which effects are due (interval and chance, kept in the world's
state) and every random value they carry, the host only plays them.
- **Services now.** `ObjectsAt` (`ALL`): the ids of pack objects a module would place in a chunk, predicted without
@@ -1308,6 +1302,24 @@ API now: `world.running()`, `world.seed(purpose)`, `TerrainSampler`, `FeatureSet
- **Random parameters (`RNG`) in these facades and `loot.LootResolver`**. They are the legacy streams existing worlds were
generated from. They go when a world format change lets them be stage streams.
## Studio tooling
`com.volmit.tooling` is how a module shows its work in the studio. It is a second registry beside the feature one
(`ModuleSetup.tooling()`), so nothing in generation depends on it and a host without a studio ignores it.
- **Views, not widgets.** A module answers what to show (`SceneView`: blocks per entry and variant;
`PatternView`: blocks per column at a depth) and the studio decides how to draw it. `StudioView` is sealed to the
kinds the studio can draw, so a module cannot register a view nothing renders; a new kind is an API change.
- **Views hold no state**, for the same reason as services: the studio calls from several threads, for any world of
the pack. A view keeps what it needs in the world's state.
- **Editing is the host's.** An `EditableSceneView` only reads: which file an entry is (`SceneFile`) and how its text
reads as nodes (`NodeGraph`). The studio makes every write, so one implementation keeps the author's layout,
checks the result is still JSON, refuses edits outside a studio world and moves the file in atomically for the pack
watcher. `JsonText` is in the API because a view reads positions from it; splicing text is not.
- **Paths are typed.** A `JsonPath` step is a `Key` or an `Index`, so a view cannot write a step the file cannot hold.
- **The wire is the host's.** The studio protocol may encode an absent part or block as it likes (Iris sends `-1`);
the API types say absent with `Optional`/`OptionalInt`.
## Not implemented
- Host wiring, which lives in Iris: JSON decoding and validation, rendering `PackSchema` into Iris's schema and
@@ -1331,7 +1343,7 @@ This is an inventory of where each existing family should land, not a claim that
| 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 |
| Markers, tile data, tree and loot metadata | Object metadata + placement edit + typed storage |
| Procedural trees, crystals, fungi, coral, ruins | Object generators returning sparse geometry |
| Procedural trees, crystals, fungi, coral, ruins | Module placements building sparse geometry |
| 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 |
+45 -5
View File
@@ -462,6 +462,47 @@ final class RuinsObjects implements ObjectsAt {
Service example.Clock is provided by module example:alpha from modules/alpha.jar already, and module example:beta from modules/beta.jar provides it too; a pack has one provider of it (Providers.ONE), so remove one of them
```
## Studio tools
A module shows what it builds in the studio through views in `com.volmit.tooling`, registered with
`setup.tooling()` while `setup` runs. The studio draws them; the module only answers what they show.
```java
public void setup(ModuleSetup setup) {
setup.tooling().registerView(new RuinScenes());
}
final class RuinScenes implements SceneView {
public ResourceId id() { return ResourceId.parse("example:ruins"); }
public String label() { return "Ruins"; }
public String description() { return "Each ruin the pack writes, as it is placed"; }
public List<SceneEntry> entries(PackWorld world) {
return List.of(new SceneEntry("arch", "Arch", Optional.empty(), 1));
}
public Optional<GeneratedObject> scene(PackWorld world, String key, int variant) {
return world.resources().objects().object(world.resources().idOf("ruins/" + key)).map(PlaceableObject::geometry);
}
}
```
- A `SceneView` lists entries (`SceneEntry`) and gives each variant's blocks as a `GeneratedObject`, drawn in 3D. A
`PatternView` lists entries (`PatternEntry`) and gives the blocks one lays over a `PatternArea` at a depth as a
`BlockPattern`, drawn from above. `StudioView` is sealed to these two kinds: the studio draws nothing else.
- A view's id is the module's id or starts with it and `/`. A second view with an id already registered fails the
pack load, naming both modules.
- The studio asks from its own threads, several at once, for a world of the pack it shows. A view keeps what it
needs between calls in the world's state, like a service.
- An `EditableSceneView` also names the file an entry is written in (`SceneFile`) and reads that file's text
(`JsonText`, which keeps where each value is written) as a `NodeGraph`: a `GraphNode` per JSON object, with its
settings (`NodeSettings`, shown as the pack's schema describes their type), the nodes it holds and the `Edits` the
studio may make (a child list to move nodes into, whether it moves, the `Addition`s it offers). Places in the file
are `JsonPath`s of `Key` and `Index` steps. The studio writes the file itself, rewriting only what changes; the
view never writes.
- Absent values are empty, never blank or `-1`: an entry without a group, a node that draws no part of the scene
(`GraphNode.part()`), a column a pattern places nothing at (`BlockPattern.pickAt`).
## Module jars
A pack loads its modules from `<pack>/modules/*.jar`. A jar holds one or more modules. Each module's
@@ -573,7 +614,7 @@ public final class FloraSettings implements IrisFeature {
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`, `STRUCTURE_PREFIX`
them, so studio offers the right list: `BLOCK`, `ITEM`, `ENTITY`, `STRUCTURE`, `STRUCTURE_PREFIX`
(a structure or a family prefix such as `minecraft:village`), `STRUCTURE_SET`, `TEMPLATE_POOL` (a jigsaw template pool),
`POTION_EFFECT`, `ENCHANTMENT`, `LOOT_TABLE` or `SPECIAL_ENTITY` (a mob of another plugin) from the server's registries, or `NOISE_STYLE` from the host's noise
styles. `BlockState` fields name blocks without it. `@Ref` on any other field fails the load.
@@ -693,7 +734,7 @@ own default says otherwise). They keep the snippet folders packs already use (`s
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`.
own enum or settings class with the same JSON, and turns its blocks itself (`BlockRegistry.rotate` turns a state).
## Vanilla structures
@@ -911,8 +952,7 @@ no JSON. The host renders it and merges it with its own fields:
`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.
- `snippets()` picks the types with a snippet name.
- `resources()`: every resource kind, by id. A `ResourceKindSchema` has the kind's id, module, folder and the
files' type: an `ObjectKind` naming an entry of `types()`, or a `HostKind` for a built-in kind whose class the
host describes itself. `ResourceReferenceKind(kind)` is an option naming a resource of a kind by its key.
@@ -968,7 +1008,7 @@ Optional<Clock> clock = pack.catalog().service(Clock.class); // a Pro
- `BlockState` has value equality and sorted properties; `BlockRegistry` checks it against the
platform and resolves `BlockSpec`s. It answers a state's traits (`AIR`, `SOLID`, `FLUID`, `FOLIAGE`, `DECORATION`,
`VINE`, ...), tags, whether it attaches to a face (`canAttach`) and whether it can stand on a block (`canPlaceOn`, the
rule decorations need), as the platform does. `BlockPalette` and `NoiseSampler` are typed resources (`PaletteSampler` is the noise-picked palette of settings);
rule decorations need), as the platform does. `NoiseSampler` is a typed resource and `PaletteSampler` 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.
+2 -2
View File
@@ -10,8 +10,8 @@ public interface IrisModule {
ModuleInfo info();
/** Defines this module's stages and registers its other contributions (geometry generators, mantle layers,
* settings no stage names, pack resource kinds, validators, lifecycle hooks and services), before settings are
* decoded or generation starts. Called once per pack load, in any order relative to other modules; stage bodies
* settings no stage names, pack resource kinds, validators, lifecycle hooks and services) and its studio views
* ({@link ModuleSetup#tooling()}), before settings are decoded or generation starts. Called once per pack load, in any order relative to other modules; stage bodies
* must not capture per-invocation state.
*/
void setup(ModuleSetup setup);
@@ -6,14 +6,14 @@ import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalInt;
/**
* What a {@link PatternView} places over a square of columns: the distinct blocks, and which of them each column holds,
* row by row from the north west.
*/
public final class BlockPattern {
/** What {@link #pickAt} gives for a column the pattern places nothing at. */
public static final int NO_BLOCK = -1;
private static final int NOTHING_PLACED = -1;
private final int columns;
private final List<BlockState> blocks;
@@ -39,7 +39,7 @@ public final class BlockPattern {
int[] picks = new int[columnBlocks.length];
for (int column = 0; column < columnBlocks.length; column++) {
BlockState block = columnBlocks[column];
picks[column] = block == null ? NO_BLOCK : indexByBlock.computeIfAbsent(block, added -> {
picks[column] = block == null ? NOTHING_PLACED :indexByBlock.computeIfAbsent(block, added -> {
blocks.add(added);
return blocks.size() - 1;
});
@@ -56,8 +56,9 @@ public final class BlockPattern {
return blocks;
}
/** Which of {@link #blocks()} the column holds, or {@link #NO_BLOCK}. */
public int pickAt(int column, int row) {
return picks[row * columns + column];
/** Which of {@link #blocks()} the column holds; empty where the pattern places nothing. */
public OptionalInt pickAt(int column, int row) {
int pick = picks[row * columns + column];
return pick == NOTHING_PLACED ? OptionalInt.empty() : OptionalInt.of(pick);
}
}
@@ -15,7 +15,7 @@ public interface EditableSceneView extends SceneView {
/**
* {@code text}, the file of entry {@code key}, as nodes. The pack may not have read this text yet, so a node whose
* part the scene does not show yet has {@link GraphNode#NO_PART}.
* part the scene does not show yet has no {@link GraphNode#part()}.
*
* @throws IllegalArgumentException when {@code text} does not hold what this view edits
*/
@@ -3,36 +3,33 @@ package com.volmit.tooling;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.OptionalInt;
import java.util.Set;
/**
* One node of a {@link NodeGraph}: a JSON object of the file, shown as a box of its settings, with the nodes it holds.
*
* @param kind what it is, such as {@code Stem}; nodes of one kind are drawn alike
* @param title what its box is headed, such as the object's name
* @param path where it is written; a node in an array can be duplicated and deleted, the root can't be deleted
* @param partId the part of the scene it draws, so choosing one chooses the other; {@link #NO_PART} for none
* @param roles the block roles it places or decorates, shown as tags
* @param settings the objects whose settings its box shows, its own first
* @param children the nodes it holds, each with what the wire to it means
* @param childList the array a node moved under this one is added to; empty when nothing can be moved here
* @param movable whether it can be moved under another node with a child list
* @param additions the nodes that can be added under it
* @param kind what it is, such as {@code Stem}; nodes of one kind are drawn alike
* @param title what its box is headed, such as the object's name
* @param path where it is written; a node in an array can be duplicated and deleted, the root can't be deleted
* @param part the part of the scene it draws, so choosing one chooses the other; empty when it draws none
* @param roles the block roles it places or decorates, shown as tags
* @param settings the objects whose settings its box shows, its own first
* @param children the nodes it holds, each with what the wire to it means
* @param edits how the studio may change it beyond its settings
*/
public record GraphNode(String kind, String title, JsonPath path, int partId, List<String> roles, List<NodeSettings> settings,
List<Link> children, Optional<JsonPath> childList, boolean movable, List<Addition> additions) {
public static final int NO_PART = -1;
public record GraphNode(String kind, String title, JsonPath path, OptionalInt part, List<String> roles,
List<NodeSettings> settings, List<Link> children, Edits edits) {
public GraphNode {
Objects.requireNonNull(kind, "kind");
Objects.requireNonNull(title, "title");
Objects.requireNonNull(path, "path");
Objects.requireNonNull(childList, "childList");
Objects.requireNonNull(part, "part");
roles = List.copyOf(roles);
settings = List.copyOf(settings);
children = List.copyOf(children);
additions = List.copyOf(additions);
if (movable && !path.isElement()) {
Objects.requireNonNull(edits, "edits");
if (edits.movable() && !path.isElement()) {
throw new IllegalArgumentException("Only a node in an array can move, not the one at " + path);
}
}
@@ -59,6 +56,22 @@ public record GraphNode(String kind, String title, JsonPath path, int partId, Li
}
}
/**
* How the studio may change a node beyond its settings.
*
* @param childList the array a node moved under this one is added to; empty when nothing can be moved here
* @param movable whether it can be moved under another node with a child list
* @param additions the nodes that can be added under it
*/
public record Edits(Optional<JsonPath> childList, boolean movable, List<Addition> additions) {
public static final Edits NONE = new Edits(Optional.empty(), false, List.of());
public Edits {
Objects.requireNonNull(childList, "childList");
additions = List.copyOf(additions);
}
}
/** A node that can be added: {@code literal} appended to the array at {@code list}, which is written when missing. */
public record Addition(String label, JsonPath list, String literal) {
public Addition {
@@ -3,42 +3,60 @@ package com.volmit.tooling;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
/**
* Where a value sits in a JSON file: member names and element indices from the root, such as
* {@code parts, 0, stem} for the stem of the first part.
*
* @param steps each a {@link String} member name or a non-negative {@link Integer} element index
* {@code parts, 0, stem} for the stem of the first part, built as {@code ROOT.member("parts").element(0).member("stem")}.
*/
public record JsonPath(List<Object> steps) {
public record JsonPath(List<JsonPath.Step> steps) {
public static final JsonPath ROOT = new JsonPath(List.of());
public JsonPath {
steps = List.copyOf(steps);
for (Object step : steps) {
boolean index = step instanceof Integer at && at >= 0;
if (!(step instanceof String) && !index) {
throw new IllegalArgumentException("A JSON path step is a member name or an index from 0, not " + step);
}
}
/** One step down from a value: into a member of an object or an element of an array. */
public sealed interface Step permits Key, Index {
}
/** The member named {@code name} of an object. */
public record Key(String name) implements Step {
public Key {
Objects.requireNonNull(name, "name");
}
@Override
public String toString() {
return name;
}
}
public static JsonPath of(Object... steps) {
return new JsonPath(List.of(steps));
/** The element at {@code position} of an array, from 0. */
public record Index(int position) implements Step {
public Index {
if (position < 0) {
throw new IllegalArgumentException("An element index counts from 0, not " + position);
}
}
@Override
public String toString() {
return String.valueOf(position);
}
}
public JsonPath member(String key) {
Objects.requireNonNull(key, "key");
return then(key);
public JsonPath member(String name) {
return then(new Key(name));
}
public JsonPath element(int index) {
return then(index);
public JsonPath element(int position) {
return then(new Index(position));
}
/** This path with {@code suffix}'s steps after its own. */
public JsonPath resolve(JsonPath suffix) {
List<Object> longer = new ArrayList<>(steps);
List<Step> longer = new ArrayList<>(steps);
longer.addAll(suffix.steps);
return new JsonPath(longer);
}
@@ -54,14 +72,14 @@ public record JsonPath(List<Object> steps) {
}
/** @throws IllegalStateException at the root */
public Object last() {
public Step last() {
requireStep();
return steps.getLast();
}
/** Whether the value here is an element of an array. */
public boolean isElement() {
return !isRoot() && last() instanceof Integer;
return !isRoot() && last() instanceof Index;
}
public boolean startsWith(JsonPath prefix) {
@@ -72,8 +90,8 @@ public record JsonPath(List<Object> steps) {
return steps.size();
}
private JsonPath then(Object step) {
List<Object> longer = new ArrayList<>(steps);
private JsonPath then(Step step) {
List<Step> longer = new ArrayList<>(steps);
longer.add(step);
return new JsonPath(longer);
}
@@ -86,6 +104,6 @@ public record JsonPath(List<Object> steps) {
@Override
public String toString() {
return steps.isEmpty() ? "the root" : steps.stream().map(String::valueOf).reduce((first, second) -> first + "." + second).orElseThrow();
return steps.isEmpty() ? "the root" : steps.stream().map(Step::toString).collect(Collectors.joining("."));
}
}
@@ -1,14 +1,13 @@
package com.volmit.tooling;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* A JSON file that remembers where each value is written, so an edit rewrites only the value it changes and the rest
* of the file keeps the layout its author gave it. Comments are passed over, as the pack reader allows them.
* A JSON file that remembers where each value is written, so the studio can edit one value and leave the rest of the
* file as its author laid it out. Comments are passed over, as the pack reader allows them.
*/
public final class JsonText {
private final String text;
@@ -41,28 +40,6 @@ public final class JsonText {
}
}
/** {@code plain} as a JSON string literal. */
public static String quote(String plain) {
StringBuilder quoted = new StringBuilder("\"");
for (char character : plain.toCharArray()) {
switch (character) {
case '"' -> quoted.append("\\\"");
case '\\' -> quoted.append("\\\\");
case '\n' -> quoted.append("\\n");
case '\r' -> quoted.append("\\r");
case '\t' -> quoted.append("\\t");
default -> {
if (character < 0x20) {
quoted.append(String.format("\\u%04x", (int) character));
} else {
quoted.append(character);
}
}
}
}
return quoted.append('"').toString();
}
public String text() {
return text;
}
@@ -74,7 +51,7 @@ public final class JsonText {
/** The value at {@code path}; empty when the file has none there. */
public Optional<Value> at(JsonPath path) {
Value value = root;
for (Object step : path.steps()) {
for (JsonPath.Step step : path.steps()) {
Optional<Value> inside = stepInto(value, step);
if (inside.isEmpty()) {
return Optional.empty();
@@ -89,121 +66,16 @@ public final class JsonText {
return text.substring(value.start(), value.end());
}
/** The text of {@code value}, its later lines indented as if it started a line with no indent. */
public String detachedTextOf(Value value) {
return reindented(textOf(value), indentOfLine(value.start()), "");
}
public Splice replace(Value value, String literal) {
return new Splice(value.start(), value.end(), literal);
}
/** Sets the member, written after the last one in the object's own style when it is new. */
public Splice put(Obj object, String key, String literal) {
Optional<Member> existing = object.member(key);
if (existing.isPresent()) {
return replace(existing.get().value(), literal);
private static Optional<Value> stepInto(Value value, JsonPath.Step step) {
if (step instanceof JsonPath.Key(String name) && value instanceof Obj object) {
return object.get(name);
}
if (object.members().isEmpty()) {
return replace(object, "{" + quote(key) + ": " + reindented(literal, "", indentOfLine(object.start())) + "}");
}
Member last = object.members().getLast();
String indent = indentOfLine(last.keyStart());
String entry = quote(key) + ": " + reindented(literal, "", indent);
String separator = isMultiline(object) ? ",\n" + indent : ", ";
return new Splice(last.value().end(), last.value().end(), separator + entry);
}
/** @throws IllegalArgumentException when the object has no member {@code key} */
public Splice remove(Obj object, String key) {
List<Member> members = object.members();
int index = members.indexOf(object.member(key).orElseThrow(() -> new IllegalArgumentException("No " + key + " to remove")));
if (members.size() == 1) {
return replace(object, "{}");
}
if (index > 0) {
return new Splice(members.get(index - 1).value().end(), members.get(index).value().end(), "");
}
return new Splice(members.getFirst().keyStart(), members.get(1).keyStart(), "");
}
/** Adds an element after the last one, a multi-line one indented to match the array. */
public Splice append(Arr array, String literal) {
if (array.elements().isEmpty()) {
return replace(array, "[" + reindented(literal, "", indentOfLine(array.start())) + "]");
}
Value last = array.elements().getLast();
String indent = indentOfLine(last.start());
String separator = isMultiline(array) ? ",\n" + indent : ", ";
return new Splice(last.end(), last.end(), separator + reindented(literal, "", indent));
}
public Splice removeElement(Arr array, int index) {
List<Value> elements = array.elements();
Objects.checkIndex(index, elements.size());
if (elements.size() == 1) {
return replace(array, "[]");
}
if (index > 0) {
return new Splice(elements.get(index - 1).end(), elements.get(index).end(), "");
}
return new Splice(elements.getFirst().start(), elements.get(1).start(), "");
}
/**
* The text with {@code splices} made, each placed by where it was in this text.
*
* @throws IllegalArgumentException when two splices overlap
*/
public String apply(List<Splice> splices) {
List<Splice> fromLast = new ArrayList<>(splices);
fromLast.sort(Comparator.comparingInt(Splice::start).reversed());
StringBuilder edited = new StringBuilder(text);
int earliestStart = Integer.MAX_VALUE;
for (Splice splice : fromLast) {
if (splice.end() > earliestStart) {
throw new IllegalArgumentException("Overlapping edits");
}
edited.replace(splice.start(), splice.end(), splice.replacement());
earliestStart = splice.start();
}
return edited.toString();
}
private static Optional<Value> stepInto(Value value, Object step) {
if (step instanceof String key && value instanceof Obj object) {
return object.get(key);
}
if (step instanceof Integer index && value instanceof Arr array && index < array.elements().size()) {
return Optional.of(array.elements().get(index));
if (step instanceof JsonPath.Index(int position) && value instanceof Arr array && position < array.elements().size()) {
return Optional.of(array.elements().get(position));
}
return Optional.empty();
}
private boolean isMultiline(Value value) {
return textOf(value).indexOf('\n') >= 0;
}
// The blanks before the first character on the line holding position.
private String indentOfLine(int position) {
int lineStart = text.lastIndexOf('\n', position - 1) + 1;
int indentEnd = lineStart;
while (indentEnd < position && (text.charAt(indentEnd) == ' ' || text.charAt(indentEnd) == '\t')) {
indentEnd++;
}
return text.substring(lineStart, indentEnd);
}
private static String reindented(String literal, String fromIndent, String toIndent) {
String[] lines = literal.split("\n", -1);
StringBuilder result = new StringBuilder(lines[0]);
for (int index = 1; index < lines.length; index++) {
String line = lines[index].startsWith(fromIndent) ? lines[index].substring(fromIndent.length()) : lines[index].stripLeading();
result.append('\n').append(toIndent).append(line);
}
return result.toString();
}
/** A value of the file, from {@code start} up to {@code end} in its text. */
public sealed interface Value permits Obj, Arr, Literal {
int start();
@@ -242,16 +114,6 @@ public final class JsonText {
}
}
/** Replaces the text from {@code start} up to {@code end} with {@code replacement}. */
public record Splice(int start, int end, String replacement) {
public Splice {
Objects.requireNonNull(replacement, "replacement");
if (start < 0 || end < start) {
throw new IllegalArgumentException("A splice runs forwards from 0, not " + start + " to " + end);
}
}
}
private static final class Parser {
private final String text;
private int position;
@@ -2,17 +2,18 @@ package com.volmit.tooling;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
/**
* One entry of a {@link PatternView}'s catalogue.
*
* @param key what the view names the entry by in {@link PatternView#pattern}
* @param name what the studio lists it as, such as "Layer 1"
* @param group what the studio lists it under, such as its biome's name; blank for none
* @param group what the studio lists it under, such as its biome's name; empty to list it at the top
* @param depths how many blocks deep the entry can reach, at least 1
* @param facts short lines the studio shows with the entry, such as "2 to 4 blocks thick"
*/
public record PatternEntry(String key, String name, String group, int depths, List<String> facts) {
public record PatternEntry(String key, String name, Optional<String> group, int depths, List<String> facts) {
public PatternEntry {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(name, "name");
@@ -21,6 +22,9 @@ public record PatternEntry(String key, String name, String group, int depths, Li
if (key.isBlank()) {
throw new IllegalArgumentException("A pattern entry needs a key");
}
if (group.isPresent() && group.get().isBlank()) {
throw new IllegalArgumentException("Pattern entry " + key + " has a blank group; leave it empty instead");
}
if (depths < 1) {
throw new IllegalArgumentException("Pattern entry " + key + " reaches " + depths + " blocks deep; an entry reaches at least 1");
}
@@ -1,16 +1,17 @@
package com.volmit.tooling;
import java.util.Objects;
import java.util.Optional;
/**
* One entry of a {@link SceneView}'s catalogue.
*
* @param key what the view names the entry by in {@link SceneView#scene}, such as an object's {@code trees/oak}
* @param name what the studio lists it as
* @param group the folder the studio lists it under, such as {@code trees}; blank for none
* @param group the folder the studio lists it under, such as {@code trees}; empty to list it at the top
* @param variants how many scenes the entry has, at least 1
*/
public record SceneEntry(String key, String name, String group, int variants) {
public record SceneEntry(String key, String name, Optional<String> group, int variants) {
public SceneEntry {
Objects.requireNonNull(key, "key");
Objects.requireNonNull(name, "name");
@@ -18,6 +19,9 @@ public record SceneEntry(String key, String name, String group, int variants) {
if (key.isBlank()) {
throw new IllegalArgumentException("A scene entry needs a key");
}
if (group.isPresent() && group.get().isBlank()) {
throw new IllegalArgumentException("Scene entry " + key + " has a blank group; leave it empty instead");
}
if (variants < 1) {
throw new IllegalArgumentException("Scene entry " + key + " has " + variants + " variants; an entry has at least 1");
}
@@ -4,6 +4,8 @@ import com.volmit.block.BlockState;
import org.junit.jupiter.api.Test;
import java.util.List;
import java.util.Optional;
import java.util.OptionalInt;
import static org.junit.jupiter.api.Assertions.*;
@@ -15,10 +17,10 @@ class BlockPatternTest {
void keepsEachBlockOnceAndWhichColumnHoldsIt() {
BlockPattern pattern = BlockPattern.of(2, new BlockState[]{GRASS, DIRT, null, BlockState.parse("minecraft:grass_block")});
assertEquals(List.of(GRASS, DIRT), pattern.blocks());
assertEquals(0, pattern.pickAt(0, 0));
assertEquals(1, pattern.pickAt(1, 0));
assertEquals(BlockPattern.NO_BLOCK, pattern.pickAt(0, 1));
assertEquals(0, pattern.pickAt(1, 1));
assertEquals(OptionalInt.of(0), pattern.pickAt(0, 0));
assertEquals(OptionalInt.of(1), pattern.pickAt(1, 0));
assertEquals(OptionalInt.empty(), pattern.pickAt(0, 1));
assertEquals(OptionalInt.of(0), pattern.pickAt(1, 1));
}
@Test
@@ -37,6 +39,13 @@ class BlockPatternTest {
@Test
void anEntryReachesAtLeastOneBlockDeep() {
assertThrows(IllegalArgumentException.class, () -> new PatternEntry("plains#layer/0", "Layer 1", "Plains", 0, List.of()));
assertThrows(IllegalArgumentException.class, () -> new PatternEntry("plains#layer/0", "Layer 1", Optional.of("Plains"), 0, List.of()));
}
@Test
void anEntryWithoutAGroupLeavesItEmptyRatherThanBlank() {
assertThrows(IllegalArgumentException.class, () -> new PatternEntry("plains#layer/0", "Layer 1", Optional.of(" "), 1, List.of()));
assertThrows(IllegalArgumentException.class, () -> new SceneEntry("oak", "oak", Optional.of(""), 1));
assertTrue(new SceneEntry("oak", "oak", Optional.empty(), 1).group().isEmpty());
}
}
@@ -12,86 +12,27 @@ class JsonTextTest {
{
"variants": 8,
"parts": [
{
"stem": {"length": [16.0, 26.0], "radius": 0.5},
"children": [
{
"blob": {
"radius": 3
}
}
]
}
{"stem": {"length": [16.0, 26.0], "radius": 0.5}}
]
}
""";
private static final JsonPath STEM = JsonPath.ROOT.member("parts").element(0).member("stem");
@Test
void replacingAValueKeepsTheRestOfTheText() {
void findsAValueByItsPathAndKeepsItsText() {
JsonText source = JsonText.parse(TREE);
JsonText.Value length = source.at(JsonPath.of("parts", 0, "stem", "length")).orElseThrow();
String edited = source.apply(List.of(source.replace(length, "[12, 20]")));
assertEquals(TREE.replace("[16.0, 26.0]", "[12, 20]"), edited);
}
@Test
void aNewMemberFollowsAnInlineObjectsStyle() {
JsonText source = JsonText.parse(TREE);
JsonText.Obj stem = (JsonText.Obj) source.at(JsonPath.of("parts", 0, "stem")).orElseThrow();
String edited = source.apply(List.of(source.put(stem, "lean", "7")));
assertTrue(edited.contains("\"stem\": {\"length\": [16.0, 26.0], \"radius\": 0.5, \"lean\": 7},"));
}
@Test
void aNewMemberFollowsAMultilineObjectsStyle() {
JsonText source = JsonText.parse(TREE);
JsonText.Obj blob = (JsonText.Obj) source.at(JsonPath.of("parts", 0, "children", 0, "blob")).orElseThrow();
String edited = source.apply(List.of(source.put(blob, "depth", "0")));
assertTrue(edited.contains("\"radius\": 3,\n \"depth\": 0\n"));
}
@Test
void removingMembersLeavesValidJson() {
JsonText source = JsonText.parse(TREE);
JsonText.Obj stem = (JsonText.Obj) source.at(JsonPath.of("parts", 0, "stem")).orElseThrow();
String withoutFirst = source.apply(List.of(source.remove(stem, "length")));
String withoutLast = source.apply(List.of(source.remove(stem, "radius")));
assertTrue(withoutFirst.contains("\"stem\": {\"radius\": 0.5},"));
assertTrue(withoutLast.contains("\"stem\": {\"length\": [16.0, 26.0]},"));
assertTrue(JsonText.isValue(withoutFirst));
assertTrue(JsonText.isValue(withoutLast));
}
@Test
void aMovedSubtreeIsIndentedForItsNewPlace() {
JsonText source = JsonText.parse(TREE);
JsonText.Arr children = (JsonText.Arr) source.at(JsonPath.of("parts", 0, "children")).orElseThrow();
JsonText.Arr parts = (JsonText.Arr) source.at(JsonPath.of("parts")).orElseThrow();
JsonText.Obj parent = (JsonText.Obj) source.at(JsonPath.of("parts", 0)).orElseThrow();
String edited = source.apply(List.of(source.remove(parent, "children"), source.append(parts, source.detachedTextOf(children.elements().getFirst()))));
JsonText moved = JsonText.parse(edited);
assertEquals("3", moved.textOf(moved.at(JsonPath.of("parts", 1, "blob", "radius")).orElseThrow()));
assertTrue(edited.contains("\n {\n \"blob\": {\n \"radius\": 3\n }\n }\n ]"));
assertEquals("[16.0, 26.0]", source.textOf(source.at(STEM.member("length")).orElseThrow()));
assertInstanceOf(JsonText.Obj.class, source.at(STEM).orElseThrow());
}
@Test
void readsStringsAndRefusesBrokenText() {
JsonText source = JsonText.parse("{\"role\": \"wo\\\"od\"} // the wood");
assertEquals(Optional.of("wo\"od"), ((JsonText.Literal) source.at(JsonPath.of("role")).orElseThrow()).string());
assertEquals(Optional.of("wo\"od"), ((JsonText.Literal) source.at(JsonPath.ROOT.member("role")).orElseThrow()).string());
assertFalse(JsonText.isValue("{\"role\": }"));
assertFalse(JsonText.isValue("2.8, 4.55"));
assertEquals("\"a\\\"b\"", JsonText.quote("a\"b"));
IllegalArgumentException refused = assertThrows(IllegalArgumentException.class, () -> JsonText.parse("{\n\"a\": tru\n}"));
assertEquals("Not a value: tru on line 2", refused.getMessage());
}
@@ -100,8 +41,18 @@ class JsonTextTest {
void aPathOutsideTheFileFindsNothing() {
JsonText source = JsonText.parse(TREE);
assertTrue(source.at(JsonPath.of("parts", 3)).isEmpty());
assertTrue(source.at(JsonPath.of("variants", "x")).isEmpty());
assertThrows(IllegalArgumentException.class, () -> JsonPath.of("parts", -1));
assertTrue(source.at(JsonPath.ROOT.member("parts").element(3)).isEmpty());
assertTrue(source.at(JsonPath.ROOT.member("variants").member("x")).isEmpty());
assertThrows(IllegalArgumentException.class, () -> JsonPath.ROOT.element(-1));
}
@Test
void aPathKnowsItsStepsAndWhereItSits() {
assertEquals(List.of(new JsonPath.Key("parts"), new JsonPath.Index(0), new JsonPath.Key("stem")), STEM.steps());
assertEquals("parts.0.stem", STEM.toString());
assertTrue(STEM.parent().isElement());
assertFalse(STEM.isElement());
assertTrue(STEM.startsWith(JsonPath.ROOT.member("parts")));
assertThrows(IllegalStateException.class, JsonPath.ROOT::parent);
}
}