Compare commits

...
5 Commits
Author SHA1 Message Date
paula a10748b5eb Add fake hud client on juicer test 2026-11-15 20:00:50 -03:00
paula 0564275f58 Loading schematics 2026-11-15 19:54:08 -03:00
paula 6bb2c87373 Placing schematics 2026-11-15 19:01:40 -03:00
paula 59bfed58bf Export schematics 2026-11-15 18:41:22 -03:00
paula 2fa109026c Structures plan 2026-11-15 16:49:13 -03:00
33 changed files with 1196 additions and 933 deletions
+1
View File
@@ -80,6 +80,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Config](docs/modding/misc/config.md): settings a server can change, like how fast a machine works
- [Commands](docs/modding/misc/commands.md)
- [Time](docs/modding/misc/time.md): ticks, timers, days and nights
- [Schematics](docs/modding/misc/schematics.md): saving a box of the world, blocks, data and entities, to a file
- [Engine Access](docs/modding/misc/engine.md): reaching into the engine and hooking its methods, for what the API
doesn't cover yet
+96 -858
View File
@@ -1,891 +1,129 @@
# Structures and Features
# Structures
A plan for generating structures (villages, ruins, towers) and data-driven features (fossils, boulders, springs) in
bworld, in bworld's data style, while reading Minecraft Java's datapack formats closely enough that datapacks and mods
like [Trek](ports/trek) can be imported with a tool instead of rewritten.
## Schematics
Nothing here is built yet. Numbers about Trek come from reading every file in `ports/trek`.
Schematics are pre-defined block patterns to be placed somewhere in the world
## Where We Are
### Schematic format
What world generation has today (see [World Generation](docs/modding/worldgen/index.md)):
Schematics are json data, encoded and decoded with MessagePack (@std/msgpack), they are saved in .cbsm files
- **The server generates every chunk** (`server/game/world.ts`, `common/generation.ts`). Players only get finished
chunks, so generation code and data never have to reach clients.
- **Three passes per chunk:** terrain (data, see [terrain.md](docs/modding/worldgen/terrain.md)), then ores
(`worldgen/ores.json`), then features, code or data, by step. The base game's trees are a code feature in
`vegetal_decoration`.
- **Chunks generate alone.** A feature may write up to one chunk away. Those writes are "spills" that only fill air in
the neighbor, so the result doesn't depend on which chunk generates first.
- **Determinism matters at chunk borders.** Every chunk generated is saved whole, like Minecraft, so a change to
generation only shows in chunks never generated before. A chunk generated next to a saved one still takes the saved
one's spills from generation, so features cross the border the same way only when generation hasn't changed.
- **Heights and biomes for any column**, without generating its chunk: `NoiseTerrain.column` and `estimate_biome`. The
biome is exact away from coasts and cliffs. The height is the height before 3D noise, so it isn't the real surface.
- **Blocks:** numeric states (up to 16 bits), `variants`, `parts`, shapes, tile data, containers, components and shared
rules. Tags exist for blocks, items and entities. Biomes are a registry of data (`worldgen/biomes/` in a mod), but
which one a column gets is data too, a biome source's rules (see [biomes.md](docs/modding/worldgen/biomes.md)).
- **Loot:** a block's `drops` is one item id. There are no loot tables.
On the schematic the objects have `i`, `s` and `p` keys, these correspond to `index`, `state` and `position`, they are
shorten to save on bytes on msgpack
What's missing for structures:
The data on blocks[number].data is from BlockComponent.export_data. A block's client data, like the item a cutting board
holds, goes in blocks[number].client_data. `id` is left out of exported schematics, it's set when one is registered
- anything planned before blocks exist, or that spans more than three chunks;
- a block template format, and turning blocks when a piece is turned;
- terrain shaped around what's placed on it;
- a way to read Minecraft's content: NBT, `minecraft:` ids, string block states.
## Features and Structures
The same split as Minecraft's. A **feature** is a small thing placed while a chunk is decorated, like a boulder, a
spring or a fossil. It's decided from that chunk alone and forgotten once it's written. A **structure** is planned
before any block exists: a grid picks where structures start, the start is assembled into pieces with bounding boxes,
and every chunk a piece overlaps writes its own part of it. Structures can be large, made of many pieces, kept apart
from each other, and found again (`/locate`).
The order a chunk generates in becomes:
```
1. structure starts which structures overlap this chunk, assembled into pieces (cached, never saved)
2. terrain the overworld, shaped around pieces that adapt the terrain
3. ores as now
4. structures each overlapping piece writes the blocks inside this chunk, by step
5. features data features and script features, by step
```
Steps order structures and features the way Minecraft's decoration steps do, so a village is placed before trees and
flowers decorate around it: `raw_generation`, `lakes`, `local_modifications`, `underground_structures`,
`surface_structures`, `strongholds`, `underground_ores`, `underground_decoration`, `fluid_springs`,
`vegetal_decoration`, `top_layer_modification`. Script features from `register_feature` keep running last, as now.
## Principles
1. **bworld's data style.** Every JSON file has `format_version`, a wrapper key and an `id`, lives in a plural folder,
and is checked by `check-mods`. Inside the wrapper, fields keep **Minecraft's names and meanings**, so the Minecraft
Wiki's documentation applies, and importing a datapack is mostly renaming ids.
2. **Templates stay `.nbt`.** Minecraft's structure template format, unchanged. Templates can be built in Minecraft with
structure blocks and saved, read by existing NBT tools, and imported without converting them.
3. **One mapping from Minecraft to bworld, written once.** The base game ships what each `minecraft:` block, item, biome
and entity is in bworld. A template can keep vanilla ids in its palette and the mapping is applied when it loads, so
every imported pack gets better when a block is added to bworld.
4. **Deterministic, nothing saved.** Starts and pieces are recomputed from the seed whenever they're needed, like
everything else generation makes. No structure data goes into saves.
5. **Server only.** Templates, pools, structures, features and loot tables are server data, left out of the copy of a
`.cubi` players download, like worldgen scripts are now. The only thing clients need is the blocks.
6. **No goal of matching Minecraft's positions.** bworld's seeds and random numbers aren't Java's, and its terrain is
its own, so structures land in different places than in Minecraft with the same seed. What has to match is how pieces
fit together and what each field means.
## Data Formats
### Mod Folders
New folders, next to the ones a mod has now (see [Mod Files](docs/modding/gettingstarted/modfiles.md)):
```
copper_tools/
structures/<path>.nbt # templates, Minecraft's structure format
worldgen/structures/<path>.json # what a structure is: its start pool, size, biomes, terrain adaptation
worldgen/structure_sets/<path>.json # where structures start
worldgen/template_pools/<path>.json # pieces to choose from
worldgen/processor_lists/<path>.json # changes made to template blocks as they're placed
worldgen/features/<path>.json # data features: what, where, which biomes
loot_tables/<path>.json # what chests from templates are filled with
tags/biomes/<namespace>/<path>.json # biome tags, like tags/blocks
remaps/<namespace>.json # what another game's ids are here, in the base game: remaps/minecraft.json
```
Ids are the mod's namespace and the path, like `trek:village/plains/town_centers`. Paths can have folders, as in
Minecraft. Templates take their id from their path (`structures/ruins/ruin_1.nbt` is `copper_tools:ruins/ruin_1`). JSON
files also state it in `id`, and `check-mods` checks that it matches the path.
`check-mods` checks every reference: pools, templates, processor lists, structures, sets, loot tables, tags, blocks and
biomes. Missing references are errors, except the ones in an import's report (see [The Importer](#the-importer)).
### Named State Values
Blocks' states get optional value names, in Minecraft's order:
```json
"states": [
{ "name": "facing", "bits": 2, "default": 0, "values": ["north", "east", "south", "west"] },
{ "name": "half", "bits": 1, "default": 0, "values": ["bottom", "top"] },
{ "name": "shape", "bits": 3, "default": 0, "values": ["straight", "inner_left", "inner_right", "outer_left", "outer_right"] }
]
```
- `bits` can be left out when `values` is given: it's the fewest bits that fit them.
- Variant and part conditions can use names: `"facing=east,half=top"`, the same as `"facing=1,half=1"`.
- Existing blocks keep working unchanged. The base game's blocks get names that match Minecraft's (trapdoors and fences
already use Minecraft's state names and orders).
- Named values are what the remap and turning below are built on.
### Turning Blocks
Jigsaw turns pieces by 90, 180 or 270 degrees, so every block's states have to turn with the piece, like Minecraft's
`BlockState.rotate`. With named values, turning works out from the names:
| State | Turned clockwise by 90° |
| ------------------------------------------------------ | ------------------------------------------------------------- |
| values are directions (`north`, `east`, `south`, ...) | each value turns: `north` → `east`, `up` stays `up` |
| values are `x`, `y`, `z` (`axis`) | `x` ↔ `z` |
| the state's name is a direction (`north`, `east`, ...) | values move between states: `north=1` becomes `east=1` |
| `rotation` with 16 values (signs, banners, heads) | +4 |
| anything else (`half`, `open`, `shape` of stairs) | unchanged, like Minecraft (a stair's shape is relative to it) |
Odd cases, like rails' `shape` (`north_south` ↔ `east_west`, `ascending_east` → `ascending_south`), name their turns
explicitly:
```json
{
"name": "shape",
"values": ["north_south", "east_west", "ascending_east", "..."],
"turns": { "north_south": "east_west", "...": "..." }
}
```
Mirroring (Minecraft's `Mirror`) uses the same rules plus `left` ↔ `right` in values. Jigsaw never mirrors, so it can
wait.
Unit tests turn a few of each kind four times and check they're back where they started, and that turning a fence
connected north and east gives one connected east and south.
### Remaps
What another game's ids are in bworld. The base game ships `mods/bworld/remaps/minecraft.json`; any mod can add one for
its own blocks, like Trek's, or for another mod's namespace, like `remaps/waystones.json`.
Example:
```json
{
"format_version": 1,
"remap": {
"namespace": "minecraft",
"blocks": {
"grass_block": "bworld:grass",
"farmland": "bworld:hoed_dirt",
"snow_block": "bworld:snow_block",
"spruce_stairs": "bworld:spruce_stairs",
"chest": { "id": "bworld:chest", "states": { "facing": "facing" } },
"oak_wall_sign": {
"id": "bworld:oak_sign",
"states": { "facing": "facing" },
"set": { "on_wall": "true" }
},
"short_grass": "bworld:short_grass",
"grass": "bworld:short_grass",
"structure_void": null
},
"items": { "wheat_seeds": "bworld:wheat_seeds" },
"biomes": {
"plains": "bworld:plains",
"sunflower_plains": "bworld:plains",
"old_growth_pine_taiga": "bworld:taiga"
},
"entities": { "chicken": "bworld:chicken" },
"block_tags": { "features_cannot_replace": "#bworld:features_cannot_replace" }
}
}
```
- A string maps to that id, carrying over every state whose name and value names match. That's most blocks once their
states are named like Minecraft's.
- `{ id, states, set }` renames states and sets fixed ones. Properties bworld doesn't model (`waterlogged`, `powered`)
are dropped.
- `null` means known, and nothing there. Ids not in the map at all are reported as unmapped and, while generating,
treated as nothing: the template keeps whatever the world had in that spot.
- Old and new names both go in, since templates from different Minecraft versions use both. Trek's templates were saved
by 1.19 to 1.21 (DataVersion 3105 to 3953), so `grass` and `short_grass` both appear.
- Remaps apply when data loads: to template palettes, and to ids in processor lists, pools, loot tables and tags that
still use a `minecraft:` id. The engine only ever deals with bworld ids.
### Templates
`.nbt` files exactly as Minecraft saves them (gzipped, big endian):
```
{ DataVersion, size: [x, y, z], palette: [{ Name, Properties }], blocks: [{ pos, state, nbt? }], entities: [{ pos, blockPos, nbt }] }
```
`palettes` (several palettes, one picked at random) is read too. Meanings that matter:
- **A position missing from `blocks` keeps what the world has there** (Minecraft's structure void). Air in `blocks`
clears what was there, except in `legacy_single_pool_element` pieces, which skip air.
- **`nbt` is a block entity:**
- `minecraft:chest` and `minecraft:barrel` with `LootTable` become tile data that fills the container the first time
it's opened.
- `minecraft:jigsaw` holds `name`, `target`, `pool`, `joint` and `final_state`, used by assembly.
- Anything else (signs, spawners, banners) is ignored until bworld has a use for it.
- **`entities`** are spawned the first time their chunk is generated, mapped through the remap. Unmapped ones are
skipped.
An NBT reader (`common/nbt.ts`) is about 60 lines. Templates are parsed once and kept as the remapped palette and
compact arrays: positions and palette indexes as typed arrays, block entities in a map. They're packed into `.cubi`
files as they are, like textures, and only the server copy keeps them.
### Processor Lists
```json
{
"format_version": 1,
"processor_list": {
"id": "trek:stone/mossify_20",
"processors": [{
"processor_type": "minecraft:rule",
"rules": [{
"location_predicate": { "predicate_type": "minecraft:always_true" },
"input_predicate": {
"predicate_type": "minecraft:random_block_match",
"block": "minecraft:stone_bricks",
"probability": 0.2
},
"output_state": { "Name": "minecraft:mossy_stone_bricks" }
}]
}]
}
}
```
One of the two rules in Trek's `stone/mossify_20`, as imported: its `minecraft:` ids stay as they are and the remap
turns them into `bworld:stone_bricks` and `bworld:mossy_stone_bricks` when it loads.
What Trek uses, which is the first set to support:
- **`rule`**, with input and location predicates `always_true`, `block_match`, `blockstate_match`, `random_block_match`,
`random_blockstate_match` and `tag_match`, and position predicates `linear_pos` and `axis_aligned_linear_pos`. The
output is `output_state` (`{ Name, Properties }`, remapped like palettes).
- **`protected_blocks`**: never replace blocks in a tag.
Random predicates are seeded from the block's world position and the world's seed, so a block always comes out the same
whichever chunk places it. `minecraft:empty` is a list with no processors. Processor types are open: worldgen scripts
can register more with `register_processor`.
### Template Pools
```json
{
"format_version": 1,
"template_pool": {
"id": "trek:village/plains/town_centers",
"fallback": "minecraft:empty",
"elements": [
"schematic": {
"id": "bworld:my_schematic",
"size": [2, 2, 1],
"palette": [
{ "id": "bworld:stone" },
{ "id": "bworld:dirt" },
{
"weight": 49,
"element": {
"element_type": "minecraft:single_pool_element",
"location": "trek:village/plains/town_centers/plains_market_1",
"processors": "minecraft:empty",
"projection": "rigid"
}
"id": "bworld:furnace",
"s": { "facing": 1 }
}
],
"blocks": [
{
"i": 0,
"p": [0, 0, 0]
},
{
"i": 1,
"p": [1, 0, 0]
},
{
"i": 2,
"p": [1, 1, 0],
"data": { "progress": 0, "container": [{ "id": "bworld:coal", "count": 5 }, null, null] }
}
],
"entities": [
{
"p": [0.5, 1.0, 0.5],
"id": "bworld:chicken",
"data": {}
}
]
}
}
```
Element types: `single_pool_element`, `legacy_single_pool_element` (skips the template's air), `list_pool_element`
(several elements in the same spot), `feature_pool_element` (a data feature at the jigsaw's position) and
`empty_pool_element`. `projection` is `rigid` (placed as built) or `terrain_matching` (each column follows the ground,
for paths). Element types keep their `minecraft:` names: they're types, not content, so remaps don't apply to them.
Schematics will come from the schematics directory inside mods or through ctx.schematics.register() function
### Structures
## Block data serialization
```json
{
"format_version": 1,
"structure": {
"id": "trek:overworld/very_common/rocks",
"type": "minecraft:jigsaw",
"biomes": "#trek:combination/plains_forest_desert_no_snow_jungle",
"start_pool": "trek:overworld/very_common/rocks",
"size": 1,
"start_height": { "absolute": 0 },
"project_start_to_heightmap": "WORLD_SURFACE_WG",
"max_distance_from_center": 64,
"terrain_adaptation": "none",
"step": "surface_structures"
}
}
BlockComponent will have new methods:
```typescript
// the block's data as it's kept outside the world, with its containers' items written in
export_data?(block: BlockRef, params: P): unknown;
// the other way, for a block placed from a structure: creates its containers from those items
import_data?(block: BlockRef, params: P, data: unknown): void;
```
- `type` is `minecraft:jigsaw` for now. Other types, like Undergarden's `bigger_jigsaw` (jigsaw with a higher `size`
limit), map onto it with different limits. Mods can register types written in code from a worldgen script with
`register_structure_type`, for structures made in code instead of from templates.
- `size` is how many connections deep assembly goes. Minecraft allows up to 20.
- `project_start_to_heightmap` is `WORLD_SURFACE_WG` (the surface, or the water's surface) or `OCEAN_FLOOR_WG` (the
ground under water).
- `terrain_adaptation` is `none`, `beard_thin`, `beard_box`, `bury` or `encapsulate`. See
[Terrain Adaptation](#terrain-adaptation).
- `spawn_overrides` replaces which mobs spawn inside the structure. It can wait until natural spawning reads it.
Blocks without the hooks just copy data unchanged, which is fine for plain fields.
### Structure Sets
### Placing schematics
```json
{
"format_version": 1,
"structure_set": {
"id": "trek:overworld/medium",
"structures": [{ "structure": "trek:overworld/medium/oasis", "weight": 1 }],
"placement": {
"type": "minecraft:random_spread",
"spacing": 30,
"separation": 12,
"spread_type": "linear",
"salt": 98700002,
"frequency": 1,
"exclusion_zone": { "chunk_count": 6, "other_set": "trek:village" }
}
}
}
Built without `import_data`, see `docs/modding/misc/schematics.md`:
```typescript
ctx.schematics.register(id, schematic);
ctx.schematics.place(id, { position, position_pivot, rotation, mirror });
```
**`random_spread`:** the world is split into cells of `spacing` × `spacing` chunks. Each cell has at most one start, in
a chunk picked inside its first `spacing - separation` chunks on each axis. `linear` picks evenly, `triangular` leans
towards the middle. The random generator is seeded from the world's seed, the set's id, `salt` and the cell, so sets
don't move each other, and any chunk can find the starts near it without generating anything. Then:
Mods' `schematics/<name>.cbsm` files are registered as `<mod id>:<name>` before scripts run. They're decoded when the
mod is checked and packed into its `data.json` like its other server only data, so players don't get them. There's no
`dimension` yet, like export. Blocks with data in the schematic get it as it is and skip `on_create`, the rest get their
`on_create`, then every placed block tells its neighbors.
1. `frequency` skips some starts.
2. One of `structures` is picked by weight. A structure whose biome check fails is removed and another is picked, as in
Minecraft.
3. The start is skipped if a start of `exclusion_zone.other_set` is within `chunk_count` chunks.
### Rotation and mirroring
**`concentric_rings`** (strongholds) comes later. Trek only uses it to change vanilla's strongholds.
- `rotation` is `0`, `90`, `180` or `270` degrees clockwise seen from above, the same as the `"y"` of a block variant
- `mirror` is `"x"` or `"z"`, the axis that gets flipped, or left out for none
- the mirror is applied first, then the rotation, both around `position_pivot`
### Data Features
Positions, relative to the pivot:
Minecraft splits a feature into a configured feature (what) and a placed feature (where), and adds features to biomes in
the biome's own file (NeoForge adds biome modifiers so mods can add to biomes they don't own). bworld's biomes aren't
data, so a feature says where it goes itself, in one file:
- mirror `"x"`: `x` becomes `-x`
- mirror `"z"`: `z` becomes `-z`
- each 90 degrees: `[x, z]` becomes `[-z, x]`
```json
{
"format_version": 1,
"feature": {
"id": "trek:monster_room/upper/default",
"type": "minecraft:fossil",
"config": {
"max_empty_corners_allowed": 4,
"fossil_structures": ["trek:monster_room/default"],
"overlay_structures": ["trek:monster_room/empty"],
"fossil_processors": "trek:monster_room/upper/default",
"overlay_processors": "minecraft:empty"
},
"placement": [
{ "type": "minecraft:count", "count": 10 },
{ "type": "minecraft:rarity_filter", "chance": 800 },
{ "type": "minecraft:in_square" },
{
"type": "minecraft:height_range",
"height": {
"type": "minecraft:very_biased_to_bottom",
"min_inclusive": { "absolute": 24 },
"max_inclusive": { "below_top": 0 },
"inner": 10
}
}
],
"biomes": "#bworld:is_overworld",
"step": "underground_structures"
}
}
The only state that changes is one named `facing`, the standard one. Its values are always `0` north, `1` east, `2`
south, `3` west, then `4` up and `5` down for a 3 bit one (see `FACINGS` in `common/block_rules.ts` and the importer's
`ORDERS`):
- mirror `"x"` swaps east and west (`1` and `3`)
- mirror `"z"` swaps north and south (`0` and `2`)
- each 90 degrees adds 1 to a value under 4, wrapping around (`(facing + 1) % 4`)
- up and down never change
Every other state (`axis`, door hinges, stair shapes) is copied as it is, so those blocks can come out wrong in a turned
or mirrored schematic. A hook for them can come later if it's needed.
Entities get their position turned the same way as blocks, and their yaw with it (yaw 0 looks north, east is `-π/2`):
- mirror `"x"`: `yaw` becomes `-yaw`
- mirror `"z"`: `yaw` becomes `π - yaw`
- each 90 degrees: `yaw` becomes `yaw - π/2`
### Saving schematics
Built, see `docs/modding/misc/schematics.md`:
```typescript
// writes a .cbsm file to the system's temporary directory and resolves to its path
ctx.schematics.export(from, to);
```
That's Trek's `monster_room/upper/default`, its configured and placed feature joined, with `biomes` and `step` added.
- Height providers (in `height_range` and structures' `start_height`): `constant` (and a bare `{ "absolute": y }`),
`uniform`, `trapezoid`, `biased_to_bottom` and `very_biased_to_bottom`. Heights are `absolute`, `above_bottom` or
`below_top`.
- `type` and `config` are Minecraft's configured feature. `placement` is Minecraft's placed feature modifiers: `count`,
`rarity_filter`, `in_square`, `height_range`, `heightmap`, `biome`, `surface_relative_threshold_filter`,
`block_predicate_filter`.
- First feature types, from what Trek uses: `fossil` (a template, which covers Trek's monster rooms), `simple_block`,
`block_column`, `disk` and `spring_feature`, and `ore` and `random_patch` for the base game. Its trees stay code. The
format, `simple_block`, `block_column`, the first placement modifiers and `register_feature_type` are built already,
see [Data Features](docs/modding/worldgen/index.md#data-features).
- Worldgen scripts register more types with `register_feature_type(id, (chunk, config, origin) => ...)`, so a data
feature can use a type a mod wrote in code. `register_feature` stays for features that are only code.
- **Features that reach into other chunks are evaluated from each chunk they touch.** Where a feature starts is decided
from its own chunk's random numbers and heights, which neighbors can recompute. A template feature like a fossil then
writes its part in each chunk like a structure piece does. That lifts the "spills only fill air" limit for everything
placed from templates. Placement that needs to read a neighbor's blocks (not just heights) stays limited to its own
chunk.
### Biome Tags
`tags/biomes/<namespace>/<path>.json`, like block tags, with `"biomes"` as a tag registry in `ctx.tags`. The base game
ships tags for its biomes under Minecraft's names (`#bworld:is_forest`, `#bworld:is_ocean`,
`#bworld:has_structure/...`), and `remaps/minecraft.json` maps `#minecraft:is_forest` to them, so imported structures
that use vanilla's biome tags work. A biome id or tag in a structure that maps to nothing is reported, and that
structure never generates.
### Loot Tables
A subset of Minecraft's format: `pools` with `rolls` (a number or `{ min, max }`), entries of type `item`, `tag`,
`loot_table` and `empty` with `weight`, and the functions `set_count` and `set_damage`, enough for chest loot. Item ids
are remapped. Missing items are skipped and reported.
A chest placed from a template keeps `{ loot_table, loot_seed }` in its tile data. `bworld:storage` fills the container
the first time it's opened, then forgets the table, like Minecraft. The roll is seeded by `loot_seed`, so the same chest
always gets the same loot. The server API gets `ctx.loot.roll(id, seed)` for mods that want loot elsewhere.
## Engine
### Finding Starts
`common/structures/starts.ts`: for a chunk, every start whose structure could reach it. A structure's reach is
`max_distance_from_center` plus its largest template, capped at 128 blocks like Minecraft's jigsaw, so each set checks
the cells within 8 chunks. That's cheap: it's random numbers, plus biome and height lookups at the few candidate starts.
### Heights and Biomes Outside the Chunk
Assembly needs the surface at columns in chunks that don't exist yet: at the start, and for every `terrain_matching`
piece. Add `surface_at(x, z)` to the overworld, the exact surface the terrain pass would make, found by sampling the
column's 3D density downward from its rough height. Same for `ocean_floor_at`. Biomes come from `estimate_biome`, made
exact where it isn't. These need to be fast and must never disagree with the terrain pass. A test compares them against
generated chunks for many columns.
### Assembly
`common/structures/jigsaw.ts`, following Minecraft's `JigsawPlacement`. This is the part to compare most carefully
against Minecraft's source (decompiled through a NeoForge workspace; `ports/neoforge` only has patches):
1. Pick the start element from `start_pool` by weight, and a random rotation. Put it at the start chunk's corner, at
`start_height`, plus the surface at the middle of its box when `project_start_to_heightmap` is set.
2. Keep a queue of placed pieces with their depth, highest `placement_priority` first. For each piece, its jigsaw blocks
are shuffled, then sorted by `selection_priority`.
3. For a jigsaw block pointing out of its piece: the candidates are its pool's elements in weighted random order (or
only the `fallback` pool's at the last depth), each in its 4 rotations, in random order. An element connects when it
has a jigsaw that faces back towards this one, whose `name` is this one's `target`, and, for jigsaws facing up or
down with `aligned` joints, whose top points the same way.
4. The candidate's box must fit: inside the box `max_distance_from_center` around the start, and not overlapping placed
pieces. A jigsaw pointing into its own piece (like a house's door into its room) only has to fit inside that piece's
free space. `terrain_matching` candidates get the ground height at the jigsaw.
5. The first candidate that fits is placed and queued with depth + 1, if that's within `size`. An `empty` element ends
that jigsaw.
6. Jigsaw blocks become their `final_state` when placed.
Everything random comes from one generator seeded by the world's seed and the start's chunk, so a start assembles the
same in any chunk that asks. The result is a list of pieces: element, position, rotation, box. Starts are kept in an LRU
cache in the world, since every chunk a start reaches asks for it.
`use_expansion_hack` (Minecraft widening rigid villages' boxes for old templates) is read and ignored until something
looks wrong without it.
### Placing a Piece
`common/structures/place.ts`, for each piece box that overlaps the chunk:
1. Go through the template's blocks inside the chunk, turned by the piece's rotation (position and states, see
[Turning Blocks](#turning-blocks)).
2. Run the piece's processors. Air from `legacy_single_pool_element` pieces and unmapped blocks are skipped, and
`protected_blocks` blocks in the world are kept.
3. `terrain_matching` pieces move each column to the ground there.
4. Write it, overwriting whatever the terrain pass put there (unlike spills).
5. Block entities that matter become tile data. Entities are queued to spawn (see [Entities](#entities)).
Only the chunk's own blocks are written, so the result doesn't depend on which chunk generates first. That's the same
promise spills keep now, in a different way.
### Terrain Adaptation
Minecraft's `beard` options change the terrain's density near pieces. bworld's terrain is heights plus 3D density too,
so it's the same idea. The terrain pass gets the boxes of every piece in or near the chunk:
- **`beard_thin`:** under each rigid piece, fill solid down to the ground, fading out over about 8 blocks around the
box. Above its floor, inside its box, clear what the terrain put there.
- **`beard_box`:** the same, without fading at the edges.
- **`bury` and `encapsulate`:** fill around the piece instead. Trek doesn't use them, so they can come later.
- **Trees:** the base game's trees feature doesn't grow trees whose trunk is inside a piece's box (grown out a few
blocks), using `chunk.structures`, so villages don't get trees through their roofs. Trees still grow around them.
Like Minecraft, `terrain_matching` pieces (paths) don't adapt the terrain: they follow it.
### Entities
Generation only makes blocks now. Template entities and anything else generation spawns need "this chunk was generated
for the first time": the world keeps a set of chunks whose generation spawns already happened, saved with the world.
When a chunk is built and isn't in it, its structure entities are spawned and it's added. Mods' natural spawning can use
the same hook later.
### Determinism and Saves
- Starts and pieces are recomputed whenever needed and never saved: a chunk with a piece in it is saved with its blocks
like any other, and pieces reaching into chunks not generated yet need the same start.
- Adding or removing a mod with structures changes only chunks not generated yet, the same as features do now. Saved
chunks stay as they were, so there can be seams.
- Tests generate the same chunks in different orders and compare every block. A golden test records a few chunks with
structures in them, so changes to generation show up.
### Performance
Starts are cached. Templates are parsed once into typed arrays. A chunk only looks at pieces whose boxes overlap it.
Assembling a large village is the expensive part: a few milliseconds is fine, since it happens once per start and the
server only builds chunks for a limited time each tick. Profile with Trek's villages before optimizing.
### Script API
- **Worldgen:** `register_feature_type`, `register_processor` and `register_structure_type`, and `chunk.structures`: the
pieces overlapping the chunk, so a script feature can avoid them or decorate them.
- **Server:** `ctx.world.structures_at(x, y, z)` (which structures a position is in, for advancements and spawning) and
`ctx.world.find_structure(id, x, z, radius)`.
- **Commands:** `/locate structure <id>` and `/place structure <id>`, `/place template <id>` and `/place feature <id>`,
like Minecraft's `/place`. They're the fastest way to look at what an import made.
## The Importer
`deno task import-datapack ports/trek mods/trek` turns a datapack (or a mod's `data/` folder) into a bworld mod:
1. **Copy and wrap.** `<ns>/structure/**/*.nbt` goes to `structures/`. Each `worldgen/*` JSON gets bworld's wrapper, an
`id` from its path, and plural folders. Configured and placed features are joined into one data feature per placed
feature.
2. **Rename ids.** Ids in the pack's own namespace stay. `minecraft:` content ids (blocks, items, biomes, tags) are left
for the remaps to resolve when loading, so the import stays close to the original and updates easily. Types
(`minecraft:jigsaw`, `minecraft:rule`) are untouched.
3. **Heights.** Minecraft's world goes from -64 to 320 with the sea at 63. bworld's goes from 0 to 256 with the sea at
64. Heights relative to the surface (almost everything) need nothing. Absolute heights are moved: y 63 and up gets
+1, and -64 to 63 is squeezed into 1 to 64.
4. **Skip what can't work here.** Anything under a `minecraft/` folder that changes vanilla's own structures
(strongholds, mansions, end cities) and Nether and End content is left out, and listed.
5. **Report.** `IMPORT_REPORT.md` in the new mod:
- blocks, items, biomes and entities that don't map yet, with how many templates use each;
- references to content the pack doesn't include;
- structures that can't generate (no biome maps, or the start pool is missing).
Run it again after adding blocks: the report shrinks while the mod stays the same.
6. **Credits.** The pack's license and authors go into the mod's `CREDITS.md`. Trek is MIT.
The importer is the only code that knows datapacks' folder layout. The engine only reads bworld mods.
## Trek
Trek has 133 structures in 17 sets, 398 template pools, 45 processor lists, 777 templates (126 more change vanilla's
structures) and 32 configured features.
- **45 structures are always one piece:** their start templates have no jigsaw blocks. 42 are in the overworld, among
them `rocks`, `plains`, `ruins`, the ice spikes, `oasis`, `graveyard`, `stonehedge` and `pyramide_of_anubis`. These
need everything except assembly.
- **88 are assembled from pieces,** including every village. 699 templates contain jigsaw blocks (2,920 of them).
- **Terrain adaptation:** 75 structures use `beard_thin`, 5 use `beard_box` and 53 use `none`.
- **References outside the pack:** 20 templates and about 50 processor lists and fallback pools are vanilla's
(`minecraft:street_plains`, `minecraft:zombie_plains`, `minecraft:village/plains/terminators`), and 8 templates are
from the Waystones mod. Jigsaw blocks inside templates also name vanilla pools that aren't included, like
`minecraft:village/plains/villagers` and `minecraft:village/common/cats`. The mushroom village refers to
`minecraft:village/mushroom/houses`, which Trek doesn't define. Following Minecraft, a missing pool or processor list
is empty, so those spots stay plain. The base game can add bworld versions of the vanilla street processors later.
- **Not for bworld:** the 3 Nether structures, the End ones, and the `minecraft/` changes to vanilla's structures.
## Phases
Each phase ends with every test passing and something to look at in a world.
**Phase 1: blocks for templates.**
- Named state values, `values` in conditions, and turning states.
- `common/nbt.ts` and template loading.
- `remaps/` and `mods/bworld/remaps/minecraft.json` for the blocks bworld has.
- The importer's first version, which writes the report.
Check: `deno task import-datapack ports/trek mods/trek` makes a mod that passes `check-mods`. Every template loads, and
the report lists every unmapped block.
**Phase 2: single-piece structures.**
- Structures, structure sets (`random_spread`, frequency, exclusion zones), pools with single elements, processor lists,
and placing pieces per chunk.
- `surface_at` and `ocean_floor_at`.
- Biome tags and remapped biomes.
- `/place` and `/locate`.
Check: Trek's rocks, ruins and ice spikes generate in a world. The same chunks come out identical in any generation
order. `/locate structure trek:overworld/very_common/rocks` finds one.
**Phase 3: terrain adaptation and trees.** `beard_thin` and `beard_box`, and no trees inside pieces.
Check: `stonehedge` and `destroyed_house` sit on filled ground on slopes, with nothing growing through them.
**Phase 4: jigsaw.**
- Assembly, every pool element type, `terrain_matching`, fallbacks and priorities.
- The start cache.
Check: Trek's plains village generates with streets following the ground and no overlapping houses. Assembling the same
start twice gives the same pieces.
**Phase 5: what's inside.**
- Loot tables and chest tile data.
- Spawning template entities once per chunk.
- `structures_at`.
Check: a village chest has loot the first time it's opened and not the second.
**Phase 6: data features.**
- `worldgen/features/`: `fossil`, `simple_block`, `block_column`, `disk`, `spring_feature`.
- `register_feature_type`, and template features written per chunk.
Check: Trek's monster rooms generate underground.
**Phase 7: the rest, as it's needed.** `concentric_rings`, `bury` and `encapsulate`, `spawn_overrides`, mirroring,
structure types from scripts, and the base game's ores as data features. Meanwhile blocks keep being added, and each one
lets more of Trek's templates generate whole.
## Open Questions
- **Starts across mod updates.** Changing a pool's weights moves every structure assembled from it in existing worlds.
That's the same as features now, but structures are bigger. Should a world keep the starts it has seen (like Minecraft
saves them), so updating a mod only changes chunks that were never generated?
- **The `minecraft` namespace.** Packs that change vanilla content (`minecraft:village/plains/...`) could become changes
to the base game's own villages, once the base game has some. Until then they're skipped.
- **Mapping close enough.** Is a block that looks similar (`polished_andesite` → `andesite` → `stone`) better than
leaving the spot empty? Remaps can do either. Start with exact matches only, so the report stays honest.
- **Waterlogging.** Templates mark many blocks `waterlogged` (stairs and slabs under water). bworld has no waterlogging,
so underwater structures will have air pockets in them until it does.
## Blocks Trek Uses
<!-- generated from ports/trek: every template's palette, counting blocks that are placed -->
Counted over the 743 trek templates bworld could generate (overworld, villages, monster rooms; not Nether or End): 748
distinct blocks, 58 already in bworld.
### Already in bworld
`dirt`, `chest`, `spruce_trapdoor`, `grass_block` → `bworld:grass`, `spruce_fence`, `cobblestone`, `spruce_planks`,
`stone_bricks`, `water`, `oak_planks`, `oak_trapdoor`, `stone`, `dark_oak_fence`, `oak_log`, `oak_leaves`,
`dark_oak_planks`, `spruce_log`, `coal_ore`, `oak_fence`, `farmland` → `bworld:hoed_dirt`, `spruce_leaves`,
`birch_leaves`, `iron_ore`, `dark_oak_trapdoor`, `smooth_stone`, `dark_oak_log`, `furnace`, `jungle_fence`, `sand`,
`wheat`, `acacia_leaves`, `smithing_table`, `birch_planks`, `snow_block` → `bworld:snow`, `acacia_fence`,
`acacia_planks`, `cracked_stone_bricks`, `jungle_planks`, `cherry_fence`, `jungle_leaves`, `mossy_stone_bricks`,
`acacia_trapdoor`, `carrots`, `potatoes`, `acacia_log`, `cherry_log`, `jungle_trapdoor`, `cherry_trapdoor`,
`cherry_leaves`, `birch_log`, `birch_trapdoor`, `jungle_log`, `glass`, `dark_oak_leaves`, `cherry_planks`, `copper_ore`,
`birch_fence`, `gold_ore`
### Missing, used in 20 or more templates
Templates is how many templates use the block, placed is how many times it's placed across all of them. States are the
vanilla properties the templates use (`waterlogged` left out, bworld has no waterlogging).
| # | Block | Templates | Placed | States used |
| --: | -------------------------- | --------: | -----: | ---------------------------------------------- |
| 1 | `lantern` | 302 | 1610 | `hanging` |
| 2 | `spruce_slab` | 192 | 10415 | `type` |
| 3 | `spruce_stairs` | 189 | 11049 | `facing`, `half`, `shape` |
| 4 | `coarse_dirt` | 186 | 48024 | |
| 5 | `dirt_path` | 134 | 5495 | |
| 6 | `spruce_door` | 115 | 446 | `facing`, `half`, `hinge`, `open`, `powered` |
| 7 | `dark_oak_stairs` | 109 | 4487 | `facing`, `half`, `shape` |
| 8 | `cobblestone_wall` | 108 | 1620 | `east`, `north`, `south`, `up`, `west` |
| 9 | `dark_oak_slab` | 103 | 4302 | `type` |
| 10 | `spruce_fence_gate` | 103 | 1250 | `facing`, `in_wall`, `open`, `powered` |
| 11 | `ladder` | 97 | 1108 | `facing` |
| 12 | `stone_brick_stairs` | 93 | 2924 | `facing`, `half`, `shape` |
| 13 | `andesite` | 91 | 305242 | |
| 14 | `barrel` | 91 | 1249 | `facing`, `open` |
| 15 | `campfire` | 90 | 558 | `facing`, `lit`, `signal_fire` |
| 16 | `cobblestone_stairs` | 88 | 1609 | `facing`, `half`, `shape` |
| 17 | `oak_slab` | 88 | 2791 | `type` |
| 18 | `rooted_dirt` | 84 | 3547 | |
| 19 | `glass_pane` | 82 | 724 | `east`, `north`, `south`, `west` |
| 20 | `grass` | 80 | 8109 | |
| 21 | `oak_stairs` | 77 | 2840 | `facing`, `half`, `shape` |
| 22 | `chain` | 75 | 506 | `axis` |
| 23 | `stone_brick_slab` | 75 | 1556 | `type` |
| 24 | `stripped_spruce_log` | 71 | 5580 | `axis` |
| 25 | `cobblestone_slab` | 61 | 789 | `type` |
| 26 | `hay_block` | 58 | 992 | `axis` |
| 27 | `crafting_table` | 56 | 204 | |
| 28 | `soul_lantern` | 56 | 138 | `hanging` |
| 29 | `light_gray_wool` | 55 | 246768 | |
| 30 | `stone_brick_wall` | 53 | 682 | `east`, `north`, `south`, `up`, `west` |
| 31 | `dandelion` | 53 | 342 | |
| 32 | `player_head` | 51 | 418 | `rotation` |
| 33 | `tall_grass` | 51 | 3518 | `half` |
| 34 | `light_gray_concrete` | 51 | 260268 | |
| 35 | `vine` | 49 | 3759 | `east`, `north`, `south`, `up`, `west` |
| 36 | `iron_bars` | 49 | 1318 | `east`, `north`, `south`, `west` |
| 37 | `podzol` | 48 | 1362 | `snowy` |
| 38 | `oak_door` | 47 | 166 | `facing`, `half`, `hinge`, `open`, `powered` |
| 39 | `bookshelf` | 46 | 706 | |
| 40 | `white_wool` | 45 | 1711 | |
| 41 | `lime_terracotta` | 45 | 6981 | |
| 42 | `composter` | 44 | 174 | `level` |
| 43 | `rail` | 43 | 270 | `shape` |
| 44 | `stone_button` | 43 | 641 | `face`, `facing`, `powered` |
| 45 | `stone_slab` | 41 | 710 | `type` |
| 46 | `bell` | 41 | 50 | `attachment`, `facing`, `powered` |
| 47 | `grindstone` | 40 | 63 | `face`, `facing` |
| 48 | `mycelium` | 39 | 6911 | `snowy` |
| 49 | `water_cauldron` | 38 | 69 | `level` |
| 50 | `poppy` | 38 | 190 | |
| 51 | `dark_oak_fence_gate` | 37 | 457 | `facing`, `in_wall`, `open`, `powered` |
| 52 | `white_wall_banner` | 37 | 143 | `facing` |
| 53 | `mossy_cobblestone_slab` | 37 | 560 | `type` |
| 54 | `stripped_oak_log` | 37 | 1747 | `axis` |
| 55 | `smoker` | 36 | 60 | `facing`, `lit` |
| 56 | `blast_furnace` | 36 | 54 | `facing`, `lit` |
| 57 | `smooth_sandstone` | 36 | 2689 | |
| 58 | `spruce_pressure_plate` | 36 | 75 | `powered` |
| 59 | `stone_stairs` | 35 | 366 | `facing`, `half`, `shape` |
| 60 | `oak_wall_sign` | 35 | 353 | `facing` |
| 61 | `red_bed` | 35 | 170 | `facing`, `occupied`, `part` |
| 62 | `moss_block` | 35 | 8669 | |
| 63 | `candle` | 35 | 84 | `candles`, `lit` |
| 64 | `snow` | 34 | 2508 | `layers` |
| 65 | `spruce_wall_sign` | 34 | 532 | `facing` |
| 66 | `stripped_dark_oak_log` | 33 | 861 | `axis` |
| 67 | `diorite` | 33 | 4578 | |
| 68 | `calcite` | 32 | 2964 | |
| 69 | `birch_slab` | 32 | 630 | `type` |
| 70 | `jungle_stairs` | 32 | 426 | `facing`, `half`, `shape` |
| 71 | `smooth_sandstone_stairs` | 32 | 560 | `facing`, `half`, `shape` |
| 72 | `cut_sandstone` | 32 | 1722 | |
| 73 | `mossy_cobblestone` | 32 | 3850 | |
| 74 | `melon` | 32 | 686 | |
| 75 | `scaffolding` | 31 | 214 | `bottom`, `distance` |
| 76 | `birch_wood` | 31 | 356 | `axis` |
| 77 | `acacia_wood` | 30 | 1033 | `axis` |
| 78 | `polished_diorite` | 30 | 653 | |
| 79 | `flowering_azalea_leaves` | 30 | 531 | `distance`, `persistent` |
| 80 | `light_blue_bed` | 30 | 96 | `facing`, `occupied`, `part` |
| 81 | `wall_torch` | 29 | 221 | `facing` |
| 82 | `flower_pot` | 29 | 113 | |
| 83 | `terracotta` | 29 | 707 | |
| 84 | `red_mushroom_block` | 29 | 679 | `down`, `east`, `north`, `south`, `up`, `west` |
| 85 | `acacia_stairs` | 29 | 896 | `facing`, `half`, `shape` |
| 86 | `stripped_spruce_wood` | 28 | 3415 | `axis` |
| 87 | `potted_blue_orchid` | 28 | 43 | |
| 88 | `polished_andesite` | 27 | 1021 | |
| 89 | `mud_brick_wall` | 27 | 898 | `east`, `north`, `south`, `up`, `west` |
| 90 | `sandstone` | 27 | 10819 | |
| 91 | `end_rod` | 27 | 142 | `facing` |
| 92 | `green_bed` | 27 | 76 | `facing`, `occupied`, `part` |
| 93 | `decorated_pot` | 27 | 49 | `cracked`, `facing` |
| 94 | `cobweb` | 26 | 346 | |
| 95 | `spruce_wood` | 26 | 2521 | `axis` |
| 96 | `rose_bush` | 26 | 304 | `half` |
| 97 | `jungle_slab` | 26 | 778 | `type` |
| 98 | `deepslate_brick_stairs` | 26 | 1319 | `facing`, `half`, `shape` |
| 99 | `green_wool` | 25 | 3524 | |
| 100 | `cartography_table` | 25 | 29 | |
| 101 | `chiseled_stone_bricks` | 25 | 274 | |
| 102 | `loom` | 25 | 245 | `facing` |
| 103 | `white_carpet` | 24 | 112 | |
| 104 | `oak_fence_gate` | 24 | 466 | `facing`, `in_wall`, `open`, `powered` |
| 105 | `smooth_sandstone_slab` | 24 | 364 | `type` |
| 106 | `azalea_leaves` | 24 | 2186 | `distance`, `persistent` |
| 107 | `potted_fern` | 24 | 51 | |
| 108 | `deepslate_bricks` | 24 | 1356 | |
| 109 | `acacia_slab` | 24 | 1741 | `type` |
| 110 | `cauldron` | 23 | 47 | |
| 111 | `lectern` | 23 | 96 | `facing`, `has_book`, `powered` |
| 112 | `cornflower` | 23 | 46 | |
| 113 | `bamboo` | 23 | 608 | `age`, `leaves`, `stage` |
| 114 | `deepslate_brick_slab` | 23 | 1455 | `type` |
| 115 | `red_carpet` | 22 | 278 | |
| 116 | `blue_bed` | 22 | 66 | `facing`, `occupied`, `part` |
| 117 | `black_wall_banner` | 22 | 55 | `facing` |
| 118 | `crimson_roots` | 22 | 177 | |
| 119 | `andesite_stairs` | 21 | 169 | `facing`, `half`, `shape` |
| 120 | `mossy_stone_brick_stairs` | 21 | 119 | `facing`, `half`, `shape` |
| 121 | `smooth_quartz_stairs` | 21 | 372 | `facing`, `half`, `shape` |
| 122 | `green_concrete` | 21 | 3324 | |
| 123 | `fletching_table` | 21 | 41 | |
| 124 | `sea_pickle` | 21 | 84 | `pickles` |
| 125 | `potted_oak_sapling` | 21 | 32 | |
| 126 | `fern` | 21 | 139 | |
| 127 | `diorite_slab` | 21 | 318 | `type` |
| 128 | `jungle_door` | 21 | 70 | `facing`, `half`, `hinge`, `open`, `powered` |
| 129 | `dead_brain_coral_block` | 21 | 797 | |
| 130 | `hopper` | 20 | 53 | `enabled`, `facing` |
| 131 | `dark_oak_wood` | 20 | 1805 | `axis` |
| 132 | `potted_spruce_sapling` | 20 | 29 | |
| 133 | `brewing_stand` | 20 | 38 | `has_bottle_0`, `has_bottle_1`, `has_bottle_2` |
| 134 | `green_concrete_powder` | 20 | 530 | |
| 135 | `polished_diorite_slab` | 20 | 293 | `type` |
| 136 | `glow_lichen` | 20 | 346 | `down`, `east`, `north`, `south`, `up`, `west` |
| 137 | `spruce_wall_hanging_sign` | 20 | 58 | `facing` |
### Missing, used in 5 to 19 templates
- **19:** `dark_oak_wall_sign`, `andesite_wall`, `moss_carpet`, `granite`, `oak_wood`, `potted_dead_bush`,
`mossy_stone_brick_slab`, `cut_sandstone_slab`, `brown_mushroom`, `smooth_quartz_slab`
- **18:** `anvil`, `potted_dark_oak_sapling`, `oxeye_daisy`, `mossy_cobblestone_stairs`, `green_terracotta`,
`green_glazed_terracotta`
- **17:** `smooth_quartz`, `lever`, `sandstone_wall`, `sandstone_slab`, `stonecutter`, `tripwire_hook`, `pumpkin`,
`dried_kelp_block`, `mushroom_stem`, `green_stained_glass`, `pink_bed`
- **16:** `damaged_anvil`, `tuff`, `cyan_terracotta`, `red_wall_banner`, `cave_vines_plant`, `cave_vines`, `clay`,
`crimson_fungus`, `acacia_door`, `oak_pressure_plate`, `wet_sponge`
- **15:** `bricks`, `gravel`, `mossy_cobblestone_wall`, `brick_stairs`, `mossy_stone_brick_wall`, `glowstone`,
`potted_dandelion`, `note_block`, `obsidian`, `red_stained_glass_pane`, `orange_terracotta`, `deepslate_tile_slab`,
`potted_flowering_azalea_bush`
- **14:** `spruce_button`, `heavy_weighted_pressure_plate`, `jungle_wood`, `potted_red_tulip`, `azalea`, `white_bed`,
`potted_bamboo`, `weeping_vines`
- **13:** `andesite_slab`, `potted_lily_of_the_valley`, `potted_cactus`, `sandstone_stairs`, `blue_orchid`,
`flowering_azalea`, `amethyst_cluster`, `azure_bluet`, `large_fern`, `white_concrete`, `white_terracotta`,
`potted_azalea_bush`, `deepslate_tile_stairs`, `lime_stained_glass`, `dead_bubble_coral_block`, `cherry_door`
- **12:** `gray_carpet`, `diorite_wall`, `bone_block`, `tripwire`, `stone_pressure_plate`, `brown_carpet`,
`polished_andesite_stairs`, `crimson_slab`, `mangrove_trapdoor`, `weeping_vines_plant`, `red_candle`, `sponge`
- **11:** `stripped_dark_oak_wood`, `torch`, `orange_bed`, `quartz_stairs`, `quartz_slab`, `yellow_wool`,
`birch_stairs`, `gold_block`, `black_bed`, `carved_pumpkin`, `brown_wall_banner`, `potted_oxeye_daisy`,
`potted_pink_tulip`, `potted_cornflower`, `beetroots`, `dead_horn_coral_fan`, `orange_stained_glass_pane`,
`polished_andesite_slab`, `potted_poppy`, `smooth_stone_slab`, `mangrove_stairs`, `mud_bricks`, `jungle_fence_gate`,
`yellow_wall_banner`, `light_blue_terracotta`, `white_concrete_powder`, `yellow_terracotta`, `crimson_fence`,
`spruce_hanging_sign`, `potted_cherry_sapling`
- **10:** `peony`, `packed_ice`, `gray_wool`, `blue_ice`, `chiseled_sandstone`, `seagrass`, `white_candle`,
`large_amethyst_bud`, `dark_oak_door`, `spawner`, `crying_obsidian`, `red_sandstone`, `stripped_crimson_hyphae`,
`chiseled_bookshelf`, `lava_cauldron`, `bamboo_sapling`, `bamboo_fence`, `bamboo_trapdoor`
- **9:** `green_carpet`, `brick_slab`, `brick_wall`, `lilac`, `coal_block`, `polished_diorite_stairs`, `diorite_stairs`,
`potted_white_tulip`, `sweet_berry_bush`, `magma_block`, `redstone_wire`, `white_stained_glass_pane`,
`light_gray_carpet`, `allium`, `red_wool`, `netherrack`, `beehive`, `deepslate_brick_wall`, `yellow_carpet`,
`stripped_birch_wood`, `mud_brick_stairs`, `crimson_hyphae`, `crimson_trapdoor`, `bamboo_pressure_plate`
- **8:** `dark_oak_button`, `iron_trapdoor`, `blue_wool`, `deepslate`, `dead_bush`, `potted_acacia_sapling`,
`dark_oak_pressure_plate`, `lightning_rod`, `enchanting_table`, `light_gray_stained_glass_pane`, `ice`, `packed_mud`,
`mangrove_wood`, `deepslate_tiles`, `stripped_oak_wood`, `raw_iron_block`, `brown_mushroom_block`, `shroomlight`,
`acacia_fence_gate`, `birch_wall_sign`, `red_stained_glass`, `short_grass`, `cherry_stairs`
- **7:** `oak_button`, `skeleton_skull`, `hanging_roots`, `polished_deepslate_wall`, `cyan_wool`, `soul_campfire`,
`black_wool`, `quartz_block`, `stripped_jungle_log`, `mud_brick_slab`, `brown_bed`, `potted_crimson_fungus`,
`lily_of_the_valley`, `medium_amethyst_bud`, `jukebox`, `black_carpet`, `lily_pad`, `nether_brick_fence`,
`red_terracotta`, `potted_mangrove_propagule`, `mangrove_log`, `blue_terracotta`, `red_mushroom`, `potted_allium`,
`lava`, `dripstone_block`, `crimson_planks`, `jungle_wall_hanging_sign`
- **6:** `brown_terracotta`, `dead_brain_coral_fan`, `polished_deepslate`, `sugar_cane`, `potted_birch_sapling`,
`granite_stairs`, `polished_granite`, `attached_pumpkin_stem`, `stripped_birch_log`, `cobbled_deepslate`,
`purple_stained_glass`, `gray_bed`, `purple_carpet`, `tnt`, `nether_wart_block`, `potted_brown_mushroom`,
`yellow_bed`, `oak_wall_hanging_sign`, `jungle_pressure_plate`, `cherry_hanging_sign`
- **5:** `green_wall_banner`, `white_tulip`, `iron_block`, `polished_deepslate_stairs`, `cobbled_deepslate_slab`,
`tall_seagrass`, `cake`, `pumpkin_stem`, `attached_melon_stem`, `emerald_block`, `red_tulip`, `purple_wool`,
`nether_brick_slab`, `nether_brick_stairs`, `black_terracotta`, `gray_stained_glass_pane`, `blackstone_wall`,
`jungle_wall_sign`, `infested_chiseled_stone_bricks`, `piston`, `stripped_acacia_log`, `potted_azure_bluet`,
`lapis_ore`, `light_gray_terracotta`, `raw_gold_block`, `target`, `granite_wall`, `crimson_nylium`,
`twisting_vines_plant`, `twisting_vines`, `stripped_cherry_log`, `cherry_wall_hanging_sign`, `bamboo_stairs`,
`acacia_hanging_sign`, `acacia_wall_hanging_sign`, `acacia_pressure_plate`
The other 287 are in fewer than 5 templates each; the importer's unmapped report lists them.
### Missing, by family
Many missing blocks are one shape in many materials, so adding the shape once (a model, its states and its rules) and
then the materials is most of the work.
| Family | Missing blocks | In templates (sum) | Examples |
| ------------------------- | -------------: | -----------------: | ----------------------------------------------------------------------------------------------------------- |
| slabs | 45 | 971 | `spruce_slab`, `dark_oak_slab`, `oak_slab`, `stone_brick_slab`, ... |
| stairs | 47 | 964 | `spruce_stairs`, `dark_oak_stairs`, `stone_brick_stairs`, `cobblestone_stairs`, ... |
| flower pots | 33 | 353 | `potted_blue_orchid`, `potted_fern`, `potted_oak_sapling`, `potted_spruce_sapling`, ... |
| walls | 19 | 315 | `cobblestone_wall`, `stone_brick_wall`, `mud_brick_wall`, `andesite_wall`, ... |
| stripped logs and wood | 19 | 244 | `stripped_spruce_log`, `stripped_oak_log`, `stripped_dark_oak_log`, `stripped_spruce_wood`, ... |
| doors | 10 | 232 | `spruce_door`, `oak_door`, `jungle_door`, `acacia_door`, ... |
| terracotta | 27 | 209 | `lime_terracotta`, `green_terracotta`, `green_glazed_terracotta`, `cyan_terracotta`, ... |
| wool | 16 | 195 | `light_gray_wool`, `white_wool`, `green_wool`, `yellow_wool`, ... |
| beds | 15 | 194 | `red_bed`, `light_blue_bed`, `green_bed`, `blue_bed`, ... |
| fence gates | 8 | 190 | `spruce_fence_gate`, `dark_oak_fence_gate`, `oak_fence_gate`, `jungle_fence_gate`, ... |
| signs | 20 | 180 | `oak_wall_sign`, `spruce_wall_sign`, `spruce_wall_hanging_sign`, `dark_oak_wall_sign`, ... |
| wood (bark on every side) | 8 | 151 | `birch_wood`, `acacia_wood`, `spruce_wood`, `dark_oak_wood`, ... |
| carpets | 17 | 150 | `white_carpet`, `red_carpet`, `moss_carpet`, `gray_carpet`, ... |
| glass panes | 12 | 141 | `glass_pane`, `red_stained_glass_pane`, `orange_stained_glass_pane`, `white_stained_glass_pane`, ... |
| banners | 17 | 122 | `white_wall_banner`, `black_wall_banner`, `red_wall_banner`, `brown_wall_banner`, ... |
| pressure plates | 12 | 111 | `spruce_pressure_plate`, `oak_pressure_plate`, `heavy_weighted_pressure_plate`, `stone_pressure_plate`, ... |
| concrete | 12 | 100 | `light_gray_concrete`, `green_concrete`, `white_concrete`, `red_concrete`, ... |
| buttons | 9 | 81 | `stone_button`, `spruce_button`, `dark_oak_button`, `oak_button`, ... |
| stained glass | 9 | 57 | `green_stained_glass`, `lime_stained_glass`, `red_stained_glass`, `purple_stained_glass`, ... |
| trapdoors | 5 | 41 | `mangrove_trapdoor`, `bamboo_trapdoor`, `crimson_trapdoor`, `iron_trapdoor`, ... |
| candles | 9 | 34 | `red_candle`, `white_candle`, `light_gray_candle`, `pink_candle`, ... |
| fences | 5 | 31 | `crimson_fence`, `bamboo_fence`, `nether_brick_fence`, `mangrove_fence`, ... |
It has no dimension argument yet, since a server only has one world. `/exportschematic x1 y1 z1 x2 y2 z2` calls it and
tells the player the path in chat. The game worker can't write files, so the host writes it (`write_schematic` in
`server/game/host_protocol.ts`).
+6 -2
View File
@@ -50,6 +50,7 @@ import {
import { type FeatureJson, validate_feature } from "./worldgen/features.ts";
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts";
import { type Schematic, validate_schematic } from "./schematic.ts";
export const MOD_EXTENSION = ".cubi";
@@ -81,7 +82,7 @@ export class ModError extends Error {
// the zip's layout:
// manifest.json the mod's manifest, with "main" and "credits" pointing into the zip
// data.json every block, model, item, recipe, ore, entity, entity model, effect, fluid, tag, loot
// table and biome, and the mod's config
// table, biome and schematic, and the mod's config
// script.js
// textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one
@@ -214,6 +215,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
) as BiomeSourceJson[],
dimensions: checked(raw_data.dimensions, "dimensions", validate_dimension, problems) as DimensionJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[],
schematics: checked(raw_data.schematics, "schematics", validate_schematic, problems) as Schematic[],
config: raw_data.config,
};
if (raw_data.config !== undefined && !is_object(raw_data.config)) {
@@ -236,6 +238,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
...data.biome_sources!,
...data.dimensions!,
...data.features!,
...data.schematics!,
];
for (const { id } of [...registered, ...data.loot_tables!, ...data.biomes!, ...worldgen]) {
if (typeof id === "string" && id.split(":")[0] !== mod) problems.push(`${id} isn't in this mod's namespace`);
@@ -299,7 +302,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
return { manifest, data, script, textures, texture_json, credits };
}
// the same mod without the terrain's data and its config, what players get. the server sends them the world. its
// the same mod without the terrain's data, its schematics and its config, what players get. the server sends them the world. its
// script goes with it whole, and players only run its shared and client phases
export function client_copy(mod: Mod): Mod {
const {
@@ -309,6 +312,7 @@ export function client_copy(mod: Mod): Mod {
biome_sources: _b,
dimensions: _dim,
features: _f,
schematics: _sc,
config: _c,
...data
} = mod.data;
+35
View File
@@ -18,8 +18,10 @@ import type {
} from "./shared.ts";
import type { ArgumentType, CommandNode } from "../commands.ts";
import type { LootTableJson } from "../loot.ts";
import type { Schematic } from "../schematic.ts";
export type { ArgumentType, CommandContext, CommandNode, Suggestion } from "../commands.ts";
export type { Schematic, SchematicBlock, SchematicEntity, SchematicPaletteEntry } from "../schematic.ts";
export type {
EventSignal,
@@ -49,6 +51,7 @@ export interface ServerContext {
world: ServerWorld;
players: PlayerList;
containers: ContainerApi;
schematics: SchematicApi;
items: ItemApi;
blocks: BlockApi;
// every fluid, named and colored by its rules, and fluid handlers, see docs/modding/resources/fluids.md
@@ -118,6 +121,11 @@ export interface BlockComponent<P = any> {
// particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none
// there. see ServerFluidApi.block_handler
fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined;
// its tile data the way it's kept outside the world, in a schematic, like neoforge's
// BlockEntity.saveWithoutMetadata: what lives elsewhere written in, like its container's items in place of the
// container's id. any json value. the first of its components that returns something other than undefined gives
// it, and a block without any keeps its data as it is
export_data?(block: BlockRef, params: P): unknown;
// placing and neighbor rules are in shared phases, see BlockRules in cubi/shared
}
@@ -565,6 +573,33 @@ export interface ContainerApi {
delete(id: string): void;
}
// see docs/modding/misc/schematics.md
export interface SchematicApi {
// the blocks between two corners, both of them in it, with their tile data (see BlockComponent.export_data) and
// the entities whose feet are in that box, written to a .cbsm file the host keeps in a temporary directory, like
// create's schematic and quill. resolves to where the file is. throws for a box of more than 1048576 blocks (2^20)
export(from: Position, to: Position): Promise<string>;
// adds a schematic for place, by an id in this mod's namespace, while the server phase runs. it's checked here:
// every block, state and entity in it has to be registered
register(id: Id, schematic: Schematic): void;
// puts a registered schematic in the world, all of it at once, replacing what was there, air too. replaced blocks
// get their on_break. blocks it has data for get that data as it is, the rest their on_create, then everything
// placed tells the blocks beside it. its entities come with new uuids. throws for an id nothing registered, or a
// placement that isn't one, before changing anything
place(id: Id, placement: SchematicPlacement): void;
}
export interface SchematicPlacement {
// where the schematic's lowest corner goes, before it's turned
position: Position;
// the block it turns and mirrors around, from its lowest corner. 0 0 0 by default
position_pivot?: Position;
// clockwise seen from above. turns positions, a state named facing and entities' yaw, see STRUCTURES.md
rotation?: 0 | 90 | 180 | 270;
// the axis that gets flipped, before it's turned
mirror?: "x" | "z";
}
export interface ItemApi {
exists(id: Id): boolean;
// every item, in load order
+14
View File
@@ -42,6 +42,7 @@ import {
import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
import { cell_height_problem } from "./world_shape.ts";
import type { ModData } from "./mod_loader.ts";
import type { Schematic } from "./schematic.ts";
export interface ModReport {
id: string;
@@ -74,6 +75,8 @@ export interface LoadedMod {
biome_sources: { file: string; json: BiomeSourceJson }[];
dimensions: { file: string; json: DimensionJson }[];
features: { file: string; json: FeatureJson }[];
// schematics/<name>.cbsm, decoded and with their ids
schematics: { file: string; json: Schematic }[];
// config.json's settings, see docs/modding/misc/config.md
config?: Record<string, unknown>;
textures: string[];
@@ -105,6 +108,7 @@ export function mod_data(mod: LoadedMod): ModData {
biome_sources: mod.biome_sources.map((b) => b.json),
dimensions: mod.dimensions.map((d) => d.json),
features: mod.features.map((f) => f.json),
schematics: mod.schematics.map((s) => s.json),
config: mod.config,
};
}
@@ -503,6 +507,16 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
}
if (json.texture !== undefined) uses(file, json.texture, "texture");
}
// cubi: entities, like dropped items, are the engine's
for (const { file, json } of mod.schematics) {
for (const { id } of json.palette) uses(file, id, "block");
for (const { id } of json.entities) {
check_namespace(file, id);
if (!id.startsWith("cubi:") && !entity_owners.has(id)) {
errors.push(`${file}: entity ${id} doesn't exist`);
}
}
}
for (const { file, json } of mod.spawns) {
check_namespace(file, json.entity);
const entity = entity_jsons.get(json.entity);
+3
View File
@@ -45,6 +45,7 @@ import type { FeatureJson } from "./worldgen/features.ts";
import { register_block_item } from "./utils.ts";
import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts";
import { loading_mod } from "./hooks.ts";
import type { Schematic } from "./schematic.ts";
// everything a mod's json files hold, merged into one file by the build (build/mods/<id>/<hash>/data.json)
export interface ModData {
@@ -77,6 +78,8 @@ export interface ModData {
dimensions?: DimensionJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
// its schematics/<name>.cbsm files, with their ids, see common/schematic.ts. server only too
schematics?: Schematic[];
// the mod's settings, its config.json's "config", with the server's changes once the server loads it. server only
// too, see docs/modding/misc/config.md
config?: Record<string, unknown>;
+91
View File
@@ -0,0 +1,91 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// schematics: blocks and entities from a box of the world, kept to be placed again somewhere else. a .cbsm file is
// one encoded with msgpack. the short keys (i, s, p) are there to keep files small, see STRUCTURES.md
import { decode, encode } from "@std/msgpack";
import * as z from "zod";
import { find_problems, id, json_object, type Problems, vec3 } from "./schema.ts";
export const SCHEMATIC_EXTENSION = ".cbsm";
export interface SchematicFile {
format_version: 1;
schematic: Schematic;
}
export interface Schematic {
// set once it's registered. an exported one doesn't have one yet
id?: string;
// blocks along x, y and z
size: [number, number, number];
palette: SchematicPaletteEntry[];
// every position in the box, air too, so placing it clears what was there
blocks: SchematicBlock[];
entities: SchematicEntity[];
}
export interface SchematicPaletteEntry {
id: string;
// its states by name, left out for a block without any
s?: Record<string, number>;
}
export interface SchematicBlock {
// its entry in the palette
i: number;
// from the box's lowest corner
p: [number, number, number];
// its tile data, the way its components' export_data give it
data?: unknown;
// the part of its tile data clients see, like the item a cutting board holds
client_data?: Record<string, unknown>;
}
export interface SchematicEntity {
// where its feet are, from the box's lowest corner
p: [number, number, number];
id: string;
// everything else the entity saves, without its uuid, so each one placed gets a new one
data: Record<string, unknown>;
}
export function encode_schematic(schematic: Schematic): Uint8Array<ArrayBuffer> {
const file: SchematicFile = { format_version: 1, schematic };
// msgpack can't encode undefined, which tile data and entities can have in them. as json they're left out
return encode(JSON.parse(JSON.stringify(file))) as Uint8Array<ArrayBuffer>;
}
// throws for anything that isn't a schematic file of a format this knows
export function decode_schematic(bytes: Uint8Array): Schematic {
const file = decode(bytes) as Partial<SchematicFile> | null;
if (file?.format_version !== 1 || typeof file.schematic !== "object" || file.schematic === null) {
throw new Error("isn't a schematic, or is one of a format this game doesn't know");
}
return file.schematic;
}
const int = z.int();
const block_position = z.tuple([int.min(0), int.min(0), int.min(0)], "must be [x, y, z], whole numbers from 0");
const schematic_schema = z.object({
id: z.string().optional(),
size: z.tuple([int.min(1), int.min(1), int.min(1)], "must be [x, y, z], whole numbers from 1"),
palette: z.array(z.object({ id, s: z.record(z.string(), int.min(0)).optional() })),
blocks: z.array(z.object({
i: int.min(0),
p: block_position,
data: z.unknown().optional(),
client_data: json_object.optional(),
})),
entities: z.array(z.object({ p: vec3, id, data: json_object })),
});
// what's wrong with the shape of a schematic, without looking at whether its blocks and entities exist
export function schematic_problems(json: unknown): Problems {
return find_problems(schematic_schema, json);
}
// the same for one in a mod's data.json, which has its id: <mod id>:<file name>
export function validate_schematic(json: unknown): Problems {
return find_problems(schematic_schema.extend({ id }), json);
}
+14
View File
@@ -189,6 +189,20 @@ export function default_block_value(nid: number, block_info: BlockRegistry | und
return value;
}
// a block's value with the states named set over its defaults, like { facing: 1 }. throws for a state it doesn't have
// or a value that doesn't fit in it
export function value_with_states(nid: number, block_info: BlockRegistry, states: Record<string, number>): number {
let value = default_block_value(nid, block_info);
for (const [name, state] of Object.entries(states)) {
const bits = block_info.states?.find((s) => s.name === name)?.bits;
if (bits === undefined || !Number.isInteger(state) || state < 0 || state >= 2 ** bits) {
throw new Error(`${block_info.id} has no state ${name} that fits ${state}`);
}
value = set_state_value(value, block_info, name, state)!;
}
return value;
}
export function block_value(nid: number, state: number): number {
return ((state << STATE_SHIFT) | nid) >>> 0;
}
+1
View File
@@ -25,6 +25,7 @@
},
"imports": {
"@/": "./",
"@std/msgpack": "jsr:@std/msgpack@^1.0.3",
"cubi/server": "./common/mod_api/server.ts",
"cubi/client": "./common/mod_api/client.ts",
"cubi/worldgen": "./common/mod_api/worldgen.ts",
Generated
+15 -3
View File
@@ -5,6 +5,7 @@
"jsr:@paulaboks/codecounter@*": "0.0.3",
"jsr:@paulaboks/rng@^0.0.3": "0.0.3",
"jsr:@std/assert@1": "1.0.14",
"jsr:@std/bytes@^1.0.5": "1.0.6",
"jsr:@std/cli@^1.0.27": "1.0.27",
"jsr:@std/encoding@1.0.5": "1.0.5",
"jsr:@std/encoding@^1.0.10": "1.0.10",
@@ -14,14 +15,15 @@
"jsr:@std/html@^1.0.5": "1.0.5",
"jsr:@std/http@*": "1.0.24",
"jsr:@std/http@^1.0.23": "1.0.24",
"jsr:@std/internal@^1.0.10": "1.0.12",
"jsr:@std/internal@^1.0.12": "1.0.12",
"jsr:@std/internal@^1.0.10": "1.0.14",
"jsr:@std/internal@^1.0.12": "1.0.14",
"jsr:@std/internal@^1.0.14": "1.0.14",
"jsr:@std/media-types@^1.1.0": "1.1.0",
"jsr:@std/msgpack@^1.0.3": "1.0.3",
"jsr:@std/net@^1.0.6": "1.0.6",
"jsr:@std/path@1": "1.1.6",
"jsr:@std/path@^1.1.2": "1.1.6",
"jsr:@std/path@^1.1.4": "1.1.4",
"jsr:@std/path@^1.1.4": "1.1.6",
"jsr:@std/streams@^1.0.17": "1.1.2",
"jsr:@zod/zod@^4.6.7": "4.6.7",
"npm:fflate@~0.8.2": "0.8.3",
@@ -50,6 +52,9 @@
"jsr:@std/internal@^1.0.10"
]
},
"@std/bytes@1.0.6": {
"integrity": "f6ac6adbd8ccd99314045f5703e23af0a68d7f7e58364b47d2c7f408aeb5820a"
},
"@std/cli@1.0.27": {
"integrity": "eba97edd0891871a7410e835dd94b3c260c709cca5983df2689c25a71fbe04de"
},
@@ -95,6 +100,12 @@
"@std/media-types@1.1.0": {
"integrity": "c9d093f0c05c3512932b330e3cc1fe1d627b301db33a4c2c2185c02471d6eaa4"
},
"@std/msgpack@1.0.3": {
"integrity": "b384239867dfd08aba9069d433e415a8229c6f966716d6b7fd3972a6fe605848",
"dependencies": [
"jsr:@std/bytes"
]
},
"@std/net@1.0.6": {
"integrity": "110735f93e95bb9feb95790a8b1d1bf69ec0dc74f3f97a00a76ea5efea25500c"
},
@@ -140,6 +151,7 @@
"jsr:@std/assert@1",
"jsr:@std/fs@^1.0.23",
"jsr:@std/http@^1.0.23",
"jsr:@std/msgpack@^1.0.3",
"jsr:@std/path@1",
"jsr:@zod/zod@^4.6.7",
"npm:fflate@~0.8.2",
+2 -1
View File
@@ -61,7 +61,7 @@ the block and the component.
| Handler | Called when | Returns |
| --------------------------------------------- | --------------------------------------------------------------------------------------------------------- | -------------------------------- |
| `on_create(block, params)` | The block is placed or set, by a player or a script. | |
| `on_create(block, params)` | The block is placed or set, by a player, a script, or a schematic without data for it. | |
| `on_break(block, params, player?)` | The block is broken or replaced. `player` when a player broke it. | |
| `on_click(block, params, player)` | A player starts hitting it. | |
| `on_interact(block, params, player)` | A player right clicks it. | `true` if it did something |
@@ -74,6 +74,7 @@ the block and the component.
| `on_scheduled_tick(block, params)` | A tick it asked for comes. See [Scheduled Ticks](#scheduled-ticks). | |
| `on_entity_stand(block, params, entity)` | An entity standing on it moves, every tick it does. See [Entities on It](#entities-on-it). | |
| `fluid_handler(block, params, face?)` | Something reaches for its tanks from `face`. See [Fluid Handlers](../resources/fluids.md#fluid-handlers). | a `FluidHandler`, or `undefined` |
| `export_data(block, params)` | It goes into a schematic. See [Schematics](../misc/schematics.md#block-data). | its data for the schematic |
`block` is `{ id, x, y, z, biome, season, data, get_client_data, set_client_data, set_ticking }`, where `data` is the
block's [tile data](tiledata.md) and the client data functions its [part clients see](tiledata.md#client-data), `biome`
+3
View File
@@ -56,6 +56,9 @@ ctx.components.register_block("copper_tools:crate", {
The base game's `bworld:storage` does exactly this, see `mods/bworld/scripts/server.ts`.
The container's id means nothing outside the world, so a block like this should also have an `export_data` that writes
its items in, for when it's saved into a [schematic](../misc/schematics.md#block-data).
## Client Data
Client data is the part of a block's data its clients see too, like how fast a shaft turns. It's kept by field, each any
+4 -3
View File
@@ -29,6 +29,7 @@ mods/
worldgen/noise_settings/**/*.json
worldgen/biome_source/**/*.json
worldgen/spawns.json # monsters that spawn on their own, see entities/index.md
schematics/*.cbsm # schematics, never sent to players. see misc/schematics.md
textures/*.png
textures/*.json # animations, see resources/textures.md
scripts/
@@ -115,7 +116,7 @@ deno task build # packs every mod in mods/ into server_mo
```
copper_tools.cubi
manifest.json # with main and credits pointing into the zip
data.json # every block, model, item, entity, recipe, ore, tag and loot table, and the config
data.json # every block, model, item, entity, recipe, ore, tag, loot table and schematic, and the config
script.js # the script bundled into one module
textures/<name>.png
textures/<name>.json # for animated textures
@@ -127,5 +128,5 @@ copper_tools.cubi
- `deno task build` leaves other `.cubi` files in `server_mods/` alone, so mods from elsewhere can sit next to the ones
it builds.
- `data.json` doesn't hold the blocks the content phase registers. The server runs it when it loads the `.cubi`.
- Players get a copy **without** the terrain's data and the config, but with the blocks the content phase registered in
its `data.json`. See [Networking](../networking/index.md).
- Players get a copy **without** the terrain's data, the schematics and the config, but with the blocks the content
phase registered in its `data.json`. See [Networking](../networking/index.md).
+101
View File
@@ -0,0 +1,101 @@
# Schematics
A schematic is a box of the world saved to a file: its blocks with their states and data, and the entities in it, to be
placed again somewhere else. Schematic files end in `.cbsm` and are [MessagePack](https://msgpack.org), see
`common/schematic.ts` for their format.
Exporting, registering and placing are built. Blocks making what their data points to when they're placed
(`import_data`) is planned in `STRUCTURES.md`.
## Exporting
`/exportschematic x1 y1 z1 x2 y2 z2` saves the blocks between two corners, both of them included, in any order. The
server writes the file to its system's temporary directory and tells the player where it is, so it's for whoever runs
the server to pick up.
Scripts do the same in the server phase:
```ts
const path = await ctx.schematics.export({ x: 0, y: 64, z: 0 }, { x: 15, y: 80, z: 15 });
ctx.log(`saved to ${path}`);
```
A schematic holds up to 1048576 blocks (2^20), a box of 128 by 64 by 128. A bigger box throws right away.
What goes in:
- Every block in the box, air too, so placing it clears what was there. Blocks with the same states share one entry in
the palette.
- Each block's [tile data](../blocks/tiledata.md), see [Block Data](#block-data), and its
[client data](../blocks/tiledata.md#client-data), like the item a cutting board holds.
- Entities whose feet are in the box, with what they ride and what rides them, without their uuids, so each copy placed
gets new ones. Players aren't entities, so they're never in one.
Positions are from the box's lowest corner.
## Placing
A mod's `schematics/<name>.cbsm` files are its schematics `<mod id>:<name>`, so an exported file can be dropped in as it
is. `check-mods` checks that every block and entity in them exists. They're registered before any script runs, so a
server phase can place them right away. Players never download them.
A script can also register one it made itself, by id in the server phase, then place it by that id:
```ts
ctx.schematics.register("copper_tools:hut", schematic);
ctx.schematics.place("copper_tools:hut", {
position: { x: 100, y: 64, z: 40 },
rotation: 90,
});
```
`register` checks it right away, so a schematic with a block, state or entity that isn't registered stops the mod from
loading, instead of failing when it's placed. It takes a `Schematic` (exported from `cubi/server`), the same shape as a
file's.
`place` puts the whole schematic in at once, replacing what was there, air too:
- `position` is where its lowest corner goes.
- `rotation` is `0`, `90`, `180` or `270` degrees clockwise seen from above. `mirror` is `"x"` or `"z"`, the axis that
gets flipped. The mirror is applied first, then the rotation, both around `position_pivot`, a block from the
schematic's lowest corner, `0 0 0` by default. Each placement can come out different, so a mod can turn the same room
to face each way.
- Only a state named `facing` turns with it (`0` north, `1` east, `2` south, `3` west, `4` up and `5` down stay). Other
states, like a stair's shape, stay as they are. Entities' positions and yaw turn too.
- Replaced blocks get their `on_break`, like with `ctx.world.set_block`, so a chest it replaces drops what it holds.
- Blocks the schematic has data or client data for get it as it is. Other blocks get their `on_create`. Then every block
placed tells the blocks beside it, so a fence at its edge joins what's outside. Blocks hear of it once all of them are
in, so a door's two halves are both there by then.
- Entities come with new uuids each time.
- Parts above or below the world are left out. Ungenerated chunks it reaches are generated first.
It throws for an id nothing registered, or a placement that isn't one, before anything changes.
Until `import_data` is built, a block's exported data goes back in as it is, so a chest placed from a schematic has its
items' list in its data and no container.
## Block Data
Tile data goes into a schematic as it is, which is right for plain fields like a furnace's progress. Data that only
means something in this world, like the id of a [container](../inventories/containers.md), needs an `export_data`
handler that writes what it points to in:
```ts
ctx.components.register_block("copper_tools:crate", {
export_data(block) {
const container = ctx.containers.get(block.data.container);
if (!container) return block.data;
const items = [];
for (let slot = 0; slot < container.size; slot++) items.push(container.get(slot) ?? null);
return { ...block.data, container: items };
},
});
```
It returns any JSON value, and leaves the block's own data alone. Like NeoForge's `BlockEntity.saveWithoutMetadata`,
it's what the block is outside the world. The first of a block's components whose `export_data` returns something other
than `undefined` decides, and a block without any keeps its data as it is.
The base game's chests, furnaces, crabpots, worm bins and cooking pots do this, with `export_container_data` in
`mods/bworld/scripts/block_containers.ts`.
Binary file not shown.
Binary file not shown.
+18
View File
@@ -0,0 +1,18 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import type { BlockRef, ServerContext } from "cubi/server";
// export_data for a block that keeps its items in a container whose id is its data's "container", like a chest: its
// data with the items in place of the id, one for each slot and null for an empty one, so a schematic has them. its
// data as it is when it has no container yet
export function export_container_data(ctx: ServerContext, block: BlockRef): unknown {
const container = block.data?.container && ctx.containers.get(block.data.container);
if (!container) return block.data;
const items = [];
for (let slot = 0; slot < container.size; slot++) {
const item = container.get(slot);
items.push(item ? { id: item.id, count: item.count, data: item.data } : null);
}
return { ...block.data, container: items };
}
+2
View File
@@ -8,6 +8,7 @@
import type { BlockRef, Container, ItemStack, ServerContext } from "cubi/server";
import { COOKING, type CookingRecipe, CUTTING, type CuttingRecipe, INGREDIENT_SLOTS } from "./cooking_recipes.ts";
import { export_container_data } from "./block_containers.ts";
// stove
@@ -168,6 +169,7 @@ export function register_cooking_pot(ctx: ServerContext) {
};
ctx.components.register_block("bworld:cooking_pot", {
export_data: (block) => export_container_data(ctx, block),
on_create(block) {
pot_data(block);
},
+6
View File
@@ -14,6 +14,7 @@ import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES } from "./shared.
import { JUICING, type JuicingRecipe } from "./juicing.ts";
import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts";
import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts";
import { export_container_data } from "./block_containers.ts";
export function server(ctx: ServerContext) {
register_hoeable(ctx);
@@ -143,6 +144,7 @@ function register_storage(ctx: ServerContext) {
});
ctx.components.register_block<{ rows: number }>("bworld:storage", {
export_data: (block) => export_container_data(ctx, block),
on_create(block, params) {
block_container(ctx, block, params.rows * 9);
},
@@ -175,6 +177,7 @@ function register_shipping_bin(ctx: ServerContext, storage_menu: ReturnType<type
const coins = [...COINS].sort((a, b) => coin_value(b) - coin_value(a));
ctx.components.register_block<{ rows: number }>("bworld:shipping_bin", {
export_data: (block) => export_container_data(ctx, block),
on_create(block, params) {
block_container(ctx, block, params.rows * 9);
},
@@ -252,6 +255,7 @@ function register_furnace(ctx: ServerContext) {
};
ctx.components.register_block("bworld:furnace", {
export_data: (block) => export_container_data(ctx, block),
on_create(block) {
furnace_data(block);
},
@@ -344,6 +348,7 @@ function register_crabpot(ctx: ServerContext) {
});
ctx.components.register_block<CrabpotParams>("bworld:crabpot", {
export_data: (block) => export_container_data(ctx, block),
on_interact(block, _params, player) {
menu_type.open(player, block);
return true;
@@ -416,6 +421,7 @@ function register_worm_bin(ctx: ServerContext) {
});
ctx.components.register_block("bworld:worm_bin", {
export_data: (block) => export_container_data(ctx, block),
// its container is its tile data, so its mornings come anywhere in the world, like a crop's
on_create(block) {
block_container(ctx, block, WORM_BIN_SIZE);
+122 -31
View File
@@ -47,13 +47,16 @@ import { collision_shape_at, type Shape } from "@/common/block_shapes.ts";
import { physics } from "@/common/physics.ts";
import { EXHAUSTION } from "./vitals.ts";
import { entity_ref, ModRuntime, new_stack, run_guarded, type ServerCommandSource } from "./mod_runtime.ts";
import type { LootContext, UseTarget } from "@/common/mod_api/server.ts";
import type { LootContext, Position, SchematicPlacement, UseTarget } from "@/common/mod_api/server.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import { encode_schematic } from "@/common/schematic.ts";
import { capture_schematic, placed_schematic, type RegisteredSchematic } from "./schematics.ts";
import {
argument,
choice,
type CommandContext,
CommandError,
type CommandFunction,
type CommandNode,
fluid,
integer,
@@ -85,8 +88,8 @@ import { Mob } from "./entity/mob.ts";
import { LivingEntity } from "./entity/living_entity.ts";
import { EntityManager } from "./entity/entity_manager.ts";
import { NaturalSpawner } from "./natural_spawner.ts";
import { create_entity, entity_type_ids } from "./entity/entity_types.ts";
import { damage_source, type DamageSource, type SavedEntity } from "./entity/entity.ts";
import { create_entity, entity_type_ids, load_entity } from "./entity/entity_types.ts";
import { damage_source, type DamageSource, type Entity, type SavedEntity } from "./entity/entity.ts";
import { effect_type, effect_type_ids, EffectInstance } from "./entity/effects.ts";
import { ATTRIBUTES } from "./entity/attributes.ts";
@@ -132,6 +135,8 @@ export interface GameHost {
close(conn: number): void;
// fetches a url, failing with a message for players when it can't or it's more than max_bytes
download(url: string, max_bytes: number): Promise<Uint8Array>;
// keeps an exported schematic in a new file, for whoever runs the server, resolving to where it is
write_schematic(bytes: Uint8Array<ArrayBuffer>): Promise<string>;
}
// level.json, everything saved but the blocks, which are in region files (see saves.ts)
@@ -178,6 +183,8 @@ export class GameServer {
#mods: GameMods;
// ctx.containers, saved with the world
containers = new Map<string, Container>();
// by id, what ctx.schematics.register added for place
readonly schematics = new Map<string, RegisteredSchematic>();
// everything in the world that isn't a block or a player
entities: EntityManager;
mods: ModRuntime;
@@ -688,34 +695,8 @@ export class GameServer {
// replaces a block: the old one's on_break, then the new one's on_create, then the blocks beside it hear of it
set_block(x: number, y: number, z: number, id: string, player?: ServerPlayer, state?: number) {
this.mods.rules.change(() => {
const old_id = this.world.get_block_id(x, y, z);
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
if (old_id !== AIR_ID) {
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
if (components.length > 0) {
const block = this.mods.block_ref(x, y, z, old_id);
const player_api = player && this.mods.player(player);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(
mod,
`${component_id} on_break`,
() => component.on_break!(block, params, player_api),
);
}
}
}
this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state);
if (id !== AIR_ID) {
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
}
}
}
this.#replace_block(x, y, z, id, state, player);
this.#create_block(x, y, z, id);
this.mods.rules.notify_neighbors(x, y, z);
// a block standing on this one that can't stand on what it is now breaks, like a crop on farmland that was
@@ -729,6 +710,35 @@ export class GameServer {
});
}
// the old block's on_break, then the new one without a tile. nothing else hears of it yet
#replace_block(x: number, y: number, z: number, id: string, state?: number, player?: ServerPlayer) {
const old_id = this.world.get_block_id(x, y, z);
if (this.#break_stages.size > 0) this.set_break_progress(x, y, z, undefined);
if (old_id !== AIR_ID) {
const components = this.mods.components_of(old_id).filter(({ component }) => component.on_break);
if (components.length > 0) {
const block = this.mods.block_ref(x, y, z, old_id);
const player_api = player && this.mods.player(player);
for (const { mod, id: component_id, component, params } of components) {
run_guarded(mod, `${component_id} on_break`, () => component.on_break!(block, params, player_api));
}
}
}
this.world.remove_tile(x, y, z);
this.world.set_block(x, y, z, id, state);
}
// its components' on_create
#create_block(x: number, y: number, z: number, id: string) {
if (id === AIR_ID) return;
const block = this.mods.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of this.mods.components_of(id)) {
if (component.on_create) {
run_guarded(mod, `${component_id} on_create`, () => component.on_create!(block, params));
}
}
}
// the cracks machines are making on blocks, as the stage clients draw, by position. see set_break_progress
#break_stages = new Map<string, number>();
@@ -911,6 +921,50 @@ export class GameServer {
}
}
// schematics
// the box between two corners as a schematic in a file the host writes, see ctx.schematics.export. throws right
// away for a box that's too big
export_schematic(from: Position, to: Position): Promise<string> {
return this.#host.write_schematic(encode_schematic(capture_schematic(this, from, to)));
}
// see ctx.schematics.place. the blocks all change before any of them hears of it, so a door's halves or a torch's
// wall are both there by then
place_schematic(id: string, placement: SchematicPlacement) {
const registered = this.schematics.get(id);
if (!registered) throw new Error(`there's no schematic ${id}`);
const { blocks, entities } = placed_schematic(registered, placement);
const placed = blocks.filter(({ y }) => this.world.shape.contains(y));
this.mods.rules.change(() => {
for (const { x, y, z, id, state } of placed) this.#replace_block(x, y, z, id, state);
for (const { x, y, z, id, block } of placed) {
if (id === AIR_ID) continue;
// TODO: import_data, so blocks can make what their data points to, like a chest's container
if (block.data !== undefined) this.set_tile_data(x, y, z, structuredClone(block.data));
for (const [field, value] of Object.entries(block.client_data ?? {})) {
this.set_tile_client_data(x, y, z, field, structuredClone(value));
}
if (block.data === undefined && block.client_data === undefined) this.#create_block(x, y, z, id);
}
});
// each on its own, a big schematic tells more blocks than one change can
for (const { x, y, z } of placed) this.mods.rules.notify_neighbors(x, y, z);
const seat = (vehicle: Entity) => {
for (const passenger of vehicle.passengers) {
vehicle.position_passenger(passenger);
seat(passenger);
}
};
for (const saved of entities) {
const entity = load_entity(this.entities, saved);
if (!entity) continue;
seat(entity);
this.entities.add_entity(entity);
}
}
// menus
// the id a new menu for this player gets, 1 to 100 and around, like minecraft's containerCounter
@@ -1772,6 +1826,22 @@ export class GameServer {
),
);
// TODO: only let operators do this, it writes files on the server's disk
// whole number arguments one after another, the last one running it
const coordinates = (
names: string[],
run: CommandFunction<ServerCommandSource>,
): CommandNode<ServerCommandSource> => {
const [name, ...rest] = names;
const node = argument<number, ServerCommandSource>(name, integer());
return rest.length ? node.then(coordinates(rest, run)) : node.executes(run);
};
register(
literal<ServerCommandSource>("exportschematic")
.describe("Saves the blocks between two corners as a schematic file on the server")
.then(coordinates(["x1", "y1", "z1", "x2", "y2", "z2"], (context) => this.#export_schematic(context))),
);
register(
literal<ServerCommandSource>("locatebiome").describe("Finds the nearest biome of a kind").then(
argument<string, ServerCommandSource>("biome", word())
@@ -1906,6 +1976,27 @@ export class GameServer {
this.#broadcast({ type: "player_skin", id: player.id, skin, slim: slim || undefined });
}
// /exportschematic. the host writes the file, so the player hears back where it is a little later
#export_schematic(context: CommandContext<ServerCommandSource>) {
const player = context.source.server_player;
const [from, to] = ["1", "2"].map((corner) => ({
x: context.get<number>(`x${corner}`),
y: context.get<number>(`y${corner}`),
z: context.get<number>(`z${corner}`),
}));
let writing: Promise<string>;
try {
writing = this.export_schematic(from, to);
} catch (e) {
throw new CommandError(`Couldn't export it: ${(e as Error).message}`);
}
const online = () => this.#players.get(player.conn) === player;
writing.then(
(path) => online() && this.send_chat(player, `Saved the schematic to ${path}`),
(e) => online() && this.send_chat(player, `Couldn't save the schematic: ${(e as Error).message}`),
);
}
// the host downloads it, which takes a while, so the player hears back later
#download_skin(player: ServerPlayer, url: string, slim: boolean) {
if (player.downloading_skin) {
+6 -2
View File
@@ -33,7 +33,9 @@ export type HostToGame =
// save now and say when it's done, for shutting down
| { type: "shutdown" }
// answers download, with the bytes or why it failed
| { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string };
| { type: "downloaded"; id: number; bytes?: Uint8Array; error?: string }
// answers write_schematic, with where the file is or why it couldn't be written
| { type: "wrote_schematic"; id: number; path?: string; error?: string };
export type GameToHost =
| { type: "ready"; seed: string }
@@ -46,4 +48,6 @@ export type GameToHost =
// the game waits on buffer for a saved chunk, see READ_WAITING
| { type: "read_chunk"; x: number; z: number; buffer: SharedArrayBuffer }
// the worker can't use the network, so the host fetches urls for it, like skins
| { type: "download"; id: number; url: string; max_bytes: number };
| { type: "download"; id: number; url: string; max_bytes: number }
// an exported schematic, which the host writes to a new file in a temporary directory, see ctx.schematics.export
| { type: "write_schematic"; id: number; bytes: Uint8Array<ArrayBuffer> };
+13 -1
View File
@@ -3,7 +3,7 @@
// starts a game server with its mods: registers their data, then runs the worldgen, shared and server phases of their
// scripts. the worker loads built mods, tests can load mods straight from their source folders
import { register_mod_data } from "@/common/mod_loader.ts";
import { ModLoadError, register_mod_data } from "@/common/mod_loader.ts";
import type { ModData, ModListing } from "@/common/mod_loader.ts";
import { load_worldgen } from "@/common/worldgen_loader.ts";
import { dimension_shape, type DimensionJson } from "@/common/worldgen/data.ts";
@@ -12,6 +12,7 @@ import { worldgen_bundle } from "@/common/worldgen_bundle.ts";
import { GameHost, GameServer } from "./game_server.ts";
import type { WorldSource } from "./saves.ts";
import { ModRuntime } from "./mod_runtime.ts";
import { prepare_schematic } from "./schematics.ts";
import { register_entity_type } from "./entity/entity_types.ts";
import { mod_entity_factory } from "./entity/mod_entity.ts";
import { set_effect_types } from "./entity/effects.ts";
@@ -68,6 +69,17 @@ export async function start_game(
runtime,
});
// before scripts, so their server phases can place them
for (const mod of mods) {
for (const schematic of mod.data.schematics ?? []) {
try {
game.schematics.set(schematic.id!, prepare_schematic(game, schematic));
} catch (e) {
throw new ModLoadError(mod.listing.id, `schematic ${schematic.id}: ${(e as Error).message}`);
}
}
}
const scripts = mods.flatMap((mod) => mod.url ? [{ ...script_of(mod), url: mod.url }] : []);
// every mod's shared rules first, so server phases can count on any mod's being there
await runtime.load_shared_scripts(game, scripts);
+38 -8
View File
@@ -12,8 +12,10 @@ import {
is_waterlogged,
set_state_value,
shared_items_api,
value_with_states,
} from "@/common/utils.ts";
import { LootTables } from "./loot.ts";
import { prepare_schematic } from "./schematics.ts";
import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "@/common/block_shapes.ts";
import { AIR, CHUNK_SIZE, faces, ID_MASK } from "@/common/constants.ts";
import { physics } from "@/common/physics.ts";
@@ -530,6 +532,24 @@ export class ModRuntime {
return undefined;
}
// the tile data of the block at x y z for a schematic: what the first of its components with export_data that
// returns something gives, or else a copy of its data
export_block_data(x: number, y: number, z: number, id: string): unknown {
const components = this.components_with(id, "export_data");
if (components.length > 0) {
const block = this.block_ref(x, y, z, id);
for (const { mod, id: component_id, component, params } of components) {
const data = run_guarded(
mod,
`${component_id} export_data`,
() => component.export_data!(block, params),
);
if (data !== undefined) return structuredClone(data);
}
}
return structuredClone(this.game.world.get_tile(x, y, z)?.mod_data);
}
// the block at x y z was told the one at from changed, and its rules have had their say: its components'
// on_neighbor_change
#neighbor_changed(x: number, y: number, z: number, from: Position) {
@@ -751,15 +771,13 @@ export class ModRuntime {
set_block: (x, y, z, id, states) => {
const info = id === AIR_ID ? undefined : EverythingRegistry.get<BlockRegistry>("blocks", id);
if (id !== AIR_ID && !info) throw new Error(`unknown block ${id}`);
let value = info && game().world.default_values[game().world.block_ids[id]];
for (const [name, state] of Object.entries(states ?? {})) {
const bits = info?.states?.find((s) => s.name === name)?.bits;
if (bits === undefined || !Number.isInteger(state) || state < 0 || state >= 2 ** bits) {
throw new Error(`${id} has no state ${name} that fits ${state}`);
}
value = set_state_value(value!, info!, name, state)!;
const state = info && states
? value_with_states(game().world.block_ids[id], info, states) >>> 16
: undefined;
if (id === AIR_ID && states && Object.keys(states).length > 0) {
throw new Error(`${id} has no state ${Object.keys(states)[0]}`);
}
game().set_block(x, y, z, id, undefined, states && value !== undefined ? value >>> 16 : undefined);
game().set_block(x, y, z, id, undefined, state);
return true;
},
break_block: (x, y, z, options = {}) => {
@@ -1041,6 +1059,18 @@ export class ModRuntime {
},
delete: (id) => game().delete_container(id),
},
schematics: {
export: (from, to) => game().export_schematic(from, to),
register: (id, schematic) => {
register.new_id("schematic", id, game().schematics.has(id));
try {
game().schematics.set(id, prepare_schematic(game(), schematic));
} catch (e) {
register.fail(`schematic ${id}: ${(e as Error).message}`);
}
},
place: (id, placement) => game().place_schematic(id, placement),
},
menus: {
extend_player_menu: (build) => {
register.running("player menu slot");
+227
View File
@@ -0,0 +1,227 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// exporting a box of the world as a schematic, and where a registered one's blocks and entities go when it's placed.
// see common/schematic.ts and ctx.schematics
import type { GameServer } from "./game_server.ts";
import type { SavedEntity } from "./entity/entity.ts";
import { has_entity_type } from "./entity/entity_types.ts";
import type { Position } from "@/common/mod_api/shared.ts";
import type { SchematicPlacement } from "@/common/mod_api/server.ts";
import { AIR, ID_MASK } from "@/common/constants.ts";
import { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import { AIR_ID } from "@/common/protocol.ts";
import {
type Schematic,
schematic_problems,
type SchematicBlock,
type SchematicEntity,
type SchematicPaletteEntry,
} from "@/common/schematic.ts";
import { block_states, get_state_value, set_state_value, value_with_states, wrap_angle } from "@/common/utils.ts";
// the most blocks one schematic can hold, 2^20, so an export can't hold up the game for long
export const MAX_SCHEMATIC_VOLUME = 1 << 20;
// the blocks between two corners, both of them in it, with their tile data, and the entities whose feet are in the
// box. positions in it are from the box's lowest corner. throws for a box that's too big
export function capture_schematic(game: GameServer, from: Position, to: Position): Schematic {
for (const corner of [from, to]) {
if (![corner?.x, corner?.y, corner?.z].every(Number.isFinite)) {
throw new Error("a schematic's corners need a number for each of x, y and z");
}
}
const [x0, x1] = [Math.floor(Math.min(from.x, to.x)), Math.floor(Math.max(from.x, to.x))];
const [y0, y1] = [Math.floor(Math.min(from.y, to.y)), Math.floor(Math.max(from.y, to.y))];
const [z0, z1] = [Math.floor(Math.min(from.z, to.z)), Math.floor(Math.max(from.z, to.z))];
const size: [number, number, number] = [x1 - x0 + 1, y1 - y0 + 1, z1 - z0 + 1];
const volume = size[0] * size[1] * size[2];
if (volume > MAX_SCHEMATIC_VOLUME) {
throw new Error(`a schematic holds up to ${MAX_SCHEMATIC_VOLUME} blocks, and that box has ${volume}`);
}
const world = game.world;
const palette: SchematicPaletteEntry[] = [];
// palette entries by block value, the id with its state bits
const entries = new Map<number, number>();
const blocks: SchematicBlock[] = [];
for (let y = y0; y <= y1; y++) {
for (let z = z0; z <= z1; z++) {
for (let x = x0; x <= x1; x++) {
const value = world.get_block_value(x, y, z);
let i = entries.get(value);
if (i === undefined) {
i = palette.length;
entries.set(value, i);
palette.push(palette_entry(value));
}
const block: SchematicBlock = { i, p: [x - x0, y - y0, z - z0] };
const tile = world.get_tile(x, y, z);
if (tile) {
const data = game.mods.export_block_data(x, y, z, tile.id);
if (data !== undefined) block.data = data;
if (tile.client_data) block.client_data = structuredClone(tile.client_data);
}
blocks.push(block);
}
}
}
// ones riding something are in what they ride's passengers, like in a save
const entities: SchematicEntity[] = [];
for (const entity of game.entities.all()) {
if (entity.vehicle || !entity.persistent) continue;
if (entity.x < x0 || entity.x >= x1 + 1 || entity.y < y0 || entity.y >= y1 + 1) continue;
if (entity.z < z0 || entity.z >= z1 + 1) continue;
const { id, uuid: _uuid, pos: _pos, ...data } = entity.save();
entities.push({
p: [entity.x - x0, entity.y - y0, entity.z - z0],
id,
data: without_passenger_uuids(data as SavedEntity),
});
}
return { size, palette, blocks, entities };
}
function palette_entry(value: number): SchematicPaletteEntry {
const nid = value & ID_MASK;
const block = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
if (!block) return { id: AIR_ID };
const states = block_states(value, block);
return Object.keys(states).length ? { id: block.id, s: states } : { id: block.id };
}
// each placed copy gets new ones
function without_passenger_uuids(saved: SavedEntity): Record<string, unknown> {
if (!saved.passengers) return saved;
return {
...saved,
passengers: saved.passengers.map(({ uuid: _uuid, ...passenger }) =>
without_passenger_uuids(passenger as SavedEntity)
),
};
}
// a schematic ctx.schematics.register checked, with its palette as this world's block values
export interface RegisteredSchematic {
schematic: Schematic;
palette: { id: string; value: number }[];
}
// a copy of the schematic, checked once so placing it can't fail halfway. throws saying what's wrong with it
export function prepare_schematic(game: GameServer, json: Schematic): RegisteredSchematic {
const problems = schematic_problems(json);
if (problems.length > 0) throw new Error(problems.slice(0, 5).join(", "));
const schematic = structuredClone(json);
const volume = schematic.size[0] * schematic.size[1] * schematic.size[2];
if (volume > MAX_SCHEMATIC_VOLUME) {
throw new Error(`a schematic holds up to ${MAX_SCHEMATIC_VOLUME} blocks, and this one is ${volume}`);
}
const palette = schematic.palette.map(({ id, s }) => {
if (id === AIR_ID) return { id, value: AIR };
const info = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!info) throw new Error(`it has ${id}, which isn't a block`);
return { id, value: value_with_states(game.world.block_ids[id], info, s ?? {}) };
});
for (const { i, p } of schematic.blocks) {
if (i >= palette.length) {
throw new Error(`the block at ${p.join(" ")} is palette entry ${i}, there are ${palette.length}`);
}
if (p.some((v, axis) => v >= schematic.size[axis])) {
throw new Error(`the block at ${p.join(" ")} is outside its size`);
}
}
for (const { id } of schematic.entities) {
if (!has_entity_type(id)) throw new Error(`it has ${id}, which isn't an entity`);
}
return { schematic, palette };
}
// a block a placement puts in the world, with its state bits turned
export interface PlacedBlock {
x: number;
y: number;
z: number;
id: string;
state: number;
block: SchematicBlock;
}
// how a placement turns the schematic: mirrored first, then turned clockwise this many quarters
interface Turn {
quarters: number;
mirror?: "x" | "z";
}
// where a schematic's blocks and its entities go for a placement, see SchematicPlacement and STRUCTURES.md. the
// entities as saved entities, ready to load. throws for a placement that isn't one
export function placed_schematic(
{ schematic, palette }: RegisteredSchematic,
placement: SchematicPlacement,
): { blocks: PlacedBlock[]; entities: SavedEntity[] } {
const [ox, oy, oz] = whole_position(placement?.position, "position");
const [px, , pz] = placement.position_pivot === undefined
? [0, 0, 0]
: whole_position(placement.position_pivot, "position_pivot");
const { rotation = 0, mirror } = placement;
if (![0, 90, 180, 270].includes(rotation)) throw new Error(`rotation is 0, 90, 180 or 270, not ${rotation}`);
if (mirror !== undefined && mirror !== "x" && mirror !== "z") {
throw new Error(`mirror is "x", "z" or left out, not ${mirror}`);
}
const turn: Turn = { quarters: rotation / 90, mirror };
const states = palette.map(({ value }) => turned_value(value, turn) >>> 16);
const blocks = schematic.blocks.map((block) => {
const [x, y, z] = block.p;
const [tx, tz] = turned_xz(x - px, z - pz, turn);
return { x: ox + px + tx, y: oy + y, z: oz + pz + tz, id: palette[block.i].id, state: states[block.i], block };
});
// they turn around the middle of the pivot's block, like the blocks do
const entities = schematic.entities.map(({ p: [x, y, z], id, data }) => {
const [tx, tz] = turned_xz(x - px - 0.5, z - pz - 0.5, turn);
const saved = turned_entity({ ...structuredClone(data), id } as SavedEntity, turn);
saved.pos = [ox + px + 0.5 + tx, oy + y, oz + pz + 0.5 + tz];
return saved;
});
return { blocks, entities };
}
function whole_position(position: Position | undefined, name: string): [number, number, number] {
const xyz = [position?.x, position?.y, position?.z];
if (!xyz.every(Number.isFinite)) throw new Error(`${name} needs a number for each of x, y and z`);
return xyz.map((v) => Math.floor(v!)) as [number, number, number];
}
function turned_xz(x: number, z: number, turn: Turn): [number, number] {
if (turn.mirror === "x") x = -x;
if (turn.mirror === "z") z = -z;
for (let i = 0; i < turn.quarters; i++) [x, z] = [-z, x];
return [x, z];
}
// only a state named facing turns: 0 north, 1 east, 2 south, 3 west. up and down (4 and 5) stay
function turned_value(value: number, turn: Turn): number {
const nid = value & ID_MASK;
const info = nid === AIR ? undefined : EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
const bits = info?.states?.find((s) => s.name === "facing")?.bits;
if (!info || bits === undefined) return value;
let facing = get_state_value(value, info, "facing")!;
if (facing >= 4) return value;
if (turn.mirror === "x" && facing % 2 === 1) facing = 4 - facing;
if (turn.mirror === "z" && facing % 2 === 0) facing = 2 - facing;
facing = (facing + turn.quarters) % 4;
return facing < 2 ** bits ? set_state_value(value, info, "facing", facing)! : value;
}
// with its yaw and its passengers' turned. yaw 0 looks north, -π/2 east
function turned_entity(saved: SavedEntity, turn: Turn): SavedEntity {
if (Array.isArray(saved.rotation) && Number.isFinite(saved.rotation[0])) {
let yaw = saved.rotation[0];
if (turn.mirror === "x") yaw = -yaw;
if (turn.mirror === "z") yaw = Math.PI - yaw;
saved.rotation = [wrap_angle(yaw - turn.quarters * Math.PI / 2), saved.rotation[1]];
}
if (Array.isArray(saved.passengers)) saved.passengers = saved.passengers.map((p) => turned_entity(p, turn));
return saved;
}
+32 -17
View File
@@ -19,22 +19,43 @@ const CHUNK_READ_TIMEOUT_MS = 30_000;
let game: GameServer | undefined;
let starting: Promise<void> | undefined;
// downloads waiting for the host, by id
const downloads = new Map<number, { resolve: (bytes: Uint8Array) => void; reject: (error: Error) => void }>();
let next_download = 1;
// what the game asked the host for and waits on, downloads and schematic files, by id
const requests = new Map<number, { resolve: (value: never) => void; reject: (error: Error) => void }>();
let next_request = 1;
// where the host puts saved chunks, grown when one doesn't fit
let chunk_buffer = new SharedArrayBuffer(READ_HEADER + 256 * 1024);
function post(message: GameToHost) {
// the chunks are moved to the host, not copied
// the chunks and other bytes are moved to the host, not copied
const transfer = message.type === "save"
? message.save.chunks.map((chunk) => chunk.data.buffer)
: message.type === "send" && typeof message.data !== "string"
? [message.data.buffer]
: message.type === "write_schematic"
? [message.bytes.buffer]
: [];
self.postMessage(message, transfer);
}
function request<T>(message: (id: number) => GameToHost): Promise<T> {
return new Promise((resolve, reject) => {
const id = next_request++;
requests.set(id, { resolve: resolve as (value: never) => void, reject });
post(message(id));
});
}
// the host's answer to a request, with what was asked for, or undefined and why not
function answer(id: number, value: unknown, error: string) {
const pending = requests.get(id);
requests.delete(id);
if (value !== undefined) {
pending?.resolve(value as never);
} else {
pending?.reject(new Error(error));
}
}
// a saved chunk from the host. the game waits for it, like minecraft's server waits for a chunk it needs right away,
// which takes much less than generating it
function read_chunk(x: number, z: number): Uint8Array | undefined {
@@ -69,13 +90,11 @@ self.onmessage = async (event: MessageEvent<HostToGame>) => {
return;
}
if (message.type === "downloaded") {
const pending = downloads.get(message.id);
downloads.delete(message.id);
if (message.bytes) {
pending?.resolve(message.bytes);
} else {
pending?.reject(new Error(message.error ?? "Couldn't download it"));
}
answer(message.id, message.bytes, message.error ?? "Couldn't download it");
return;
}
if (message.type === "wrote_schematic") {
answer(message.id, message.path, message.error ?? "Couldn't write it");
return;
}
@@ -107,12 +126,8 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
{
send: (conn, data) => post({ type: "send", conn, data }),
close: (conn) => post({ type: "close", conn }),
download: (url, max_bytes) =>
new Promise((resolve, reject) => {
const id = next_download++;
downloads.set(id, { resolve, reject });
post({ type: "download", id, url, max_bytes });
}),
download: (url, max_bytes) => request((id) => ({ type: "download", id, url, max_bytes })),
write_schematic: (bytes) => request((id) => ({ type: "write_schematic", id, bytes })),
},
{ level: message.save.level, chunks: { list: message.save.chunks, read: read_chunk } },
message.default_seed,
+20
View File
@@ -10,6 +10,7 @@ import { load_mods } from "./load_mods.ts";
import { list_chunks, read_chunk, write_chunks } from "./regions.ts";
import { default_worldgen_workers, start_worldgen_workers } from "./worldgen_workers.ts";
import type { SavedChunk } from "./game/saves.ts";
import { SCHEMATIC_EXTENSION } from "@/common/schematic.ts";
const MAX_MESSAGE_SIZE = 4096;
// in build/, see build.ts
@@ -141,6 +142,17 @@ export async function start_host(options: HostOptions): Promise<Host> {
post({ type: "downloaded", id: message.id, error: e instanceof Error ? e.message : String(e) }),
);
break;
case "write_schematic":
write_schematic(message.bytes).then(
(path) => post({ type: "wrote_schematic", id: message.id, path }),
(e) =>
post({
type: "wrote_schematic",
id: message.id,
error: e instanceof Error ? e.message : String(e),
}),
);
break;
}
};
game.onerror = (event) => {
@@ -242,6 +254,14 @@ export async function start_host(options: HostOptions): Promise<Host> {
};
}
// an exported schematic in a new file in the system's temporary directory, for whoever runs the server to pick up.
// returns where it is
async function write_schematic(bytes: Uint8Array): Promise<string> {
const path = await Deno.makeTempFile({ prefix: "schematic_", suffix: SCHEMATIC_EXTENSION });
await Deno.writeFile(path, bytes);
return path;
}
// for the game worker, which has no network access. errors are told to players, so they say what went wrong simply
async function download(url: string, max_bytes: number): Promise<Uint8Array> {
let parsed: URL;
+1
View File
@@ -233,6 +233,7 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
biome_sources: entries(mod.data.biome_sources ?? []),
dimensions: entries(mod.data.dimensions ?? []),
features: entries(mod.data.features ?? []),
schematics: entries(mod.data.schematics ?? []),
config: mod.data.config,
textures: [...mod.textures.keys()],
texture_files: new Map(),
+8 -1
View File
@@ -109,6 +109,8 @@ export async function test_game(
const closed = new Set<number>();
// what host.download gives back, by url. other urls fail
const downloads = new Map<string, Uint8Array>();
// what host.write_schematic was given, by the path it answered with
const schematics = new Map<string, Uint8Array>();
const host = {
// chunks come out decoded, as { type: "level_chunk", x, z, blocks, biomes }
send: (conn: number, data: string | Uint8Array) => {
@@ -124,6 +126,11 @@ export async function test_game(
const bytes = downloads.get(url);
return bytes ? Promise.resolve(bytes) : Promise.reject(new Error("Couldn't download it"));
},
write_schematic(bytes: Uint8Array) {
const path = `memory/schematic_${schematics.size + 1}.cbsm`;
schematics.set(path, bytes);
return Promise.resolve(path);
},
};
const chunks = new MemoryChunks();
if (save) chunks.add(save.chunks);
@@ -157,7 +164,7 @@ export async function test_game(
send(conn, { type: "ready" });
return take(conn).find((m) => m.type === "join");
};
return { game, take, send, join, closed, downloads };
return { game, take, send, join, closed, downloads, schematics };
}
// the block id and state bits at x, y, z in the chunks among messages, read the way a client does with the table
+1
View File
@@ -289,6 +289,7 @@ async function drawn_juicer() {
setup_client({
ui: { register_menu_screen() {}, add_item_tooltip() {} },
render: { register_visual: (id: string, create: never) => made.set(id, create) },
hud: { register() {}, on_overlay_message() {} },
} as unknown as ClientContext);
const juicer = EverythingRegistry.get_id("blocks", "bworld:juicer")!;
block_visuals.clear();
+28 -6
View File
@@ -18,12 +18,23 @@ import { decode_level_chunk, type LevelChunk } from "@/common/chunk_streaming.ts
import { decode_chunk, encode_chunk } from "@/server/game/saves.ts";
import { list_chunks, read_chunk, write_chunks } from "@/server/regions.ts";
import { section_index } from "@/common/section.ts";
import { encode_schematic, type Schematic } from "@/common/schematic.ts";
// mods/bworld and one made from the template, packed into a folder of .cubi files
// a schematic the template mod gets
const POST: Schematic = {
size: [1, 2, 1],
palette: [{ id: "bworld:stone" }],
blocks: [{ i: 0, p: [0, 0, 0] }, { i: 0, p: [0, 1, 0] }],
entities: [],
};
// mods/bworld and one made from the template, with a schematic, packed into a folder of .cubi files
async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources);
Deno.mkdirSync(`${sources}/copper_tools/schematics`);
Deno.writeFileSync(`${sources}/copper_tools/schematics/post.cbsm`, encode_schematic(POST));
const mods = await load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
@@ -32,7 +43,7 @@ async function packed_mods() {
return { sources, folder, mods };
}
Deno.test("packing a mod keeps its data, script, textures and credits, and gives the same bytes every time", async () => {
Deno.test("packing a mod keeps its data, script, textures, schematics and credits, and gives the same bytes every time", async () => {
const { sources, folder, mods } = await packed_mods();
const template = mods.find((mod) => mod.id === "copper_tools")!;
const bytes = Deno.readFileSync(`${folder}/copper_tools.cubi`);
@@ -43,6 +54,8 @@ Deno.test("packing a mod keeps its data, script, textures and credits, and gives
assertEquals(mod.data.blocks.map((b) => b.id), template.blocks.map((b) => b.json.id));
assertEquals(mod.data.recipes, template.recipes.map((r) => r.json));
assertEquals([...mod.textures.keys()].sort(), [...template.textures].sort());
// named by their files
assertEquals(mod.data.schematics, [{ ...POST, id: "copper_tools:post" }]);
assertStringIncludes(mod.script!, "function server");
assert(mod.credits);
@@ -108,7 +121,7 @@ Deno.test("broken .cubi files are turned away, saying why", () => {
);
});
Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without the terrain", async () => {
Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without the terrain or schematics", async () => {
const { sources, folder } = await packed_mods();
const mods = await load_mods(folder, ENGINE_TEXTURES);
assertEquals(mods.map((mod) => mod.listing.id), ["bworld", "copper_tools"]);
@@ -123,10 +136,19 @@ Deno.test("the server loads every .cubi in its folder, dependencies first, and p
mod.mod.script,
"players get the whole script, and only run its shared and client phases",
);
// the terrain's data stays on the server too, the rest is the same
const { noises, density_functions, noise_settings, biome_sources, dimensions, ...data } = mod.mod.data;
const none = { noises: [], density_functions: [], noise_settings: [], biome_sources: [], dimensions: [] };
// the terrain's data and schematics stay on the server too, the rest is the same
const { noises, density_functions, noise_settings, biome_sources, dimensions, schematics: _, ...data } =
mod.mod.data;
const none = {
noises: [],
density_functions: [],
noise_settings: [],
biome_sources: [],
dimensions: [],
schematics: [],
};
assertEquals(copy.data, { ...data, ...none });
if (mod.listing.id === "copper_tools") assertEquals(mod.mod.data.schematics?.length, 1);
if (mod.listing.id === "bworld") {
const terrain = [noises, density_functions, noise_settings, biome_sources, dimensions];
assert(terrain.every((list) => list!.length > 0));
+16
View File
@@ -6,6 +6,7 @@ import { check_mods } from "@/tools/check_mods.ts";
import { MAX_TEXTURE_SIZE } from "@/common/constants.ts";
import { create_mod } from "@/tools/new_mod.ts";
import { item_from_json, item_to_json } from "@/common/mod_data.ts";
import { encode_schematic } from "@/common/schematic.ts";
function temp_mods_dir() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" });
@@ -127,6 +128,18 @@ Deno.test("check-mods finds broken mods", async () => {
new DataView(huge.buffer).setUint32(16, MAX_TEXTURE_SIZE + 1);
new DataView(huge.buffer).setUint32(20, 16);
Deno.writeFileSync(`${mod}/textures/huge.png`, huge);
// a schematic with a block and an entity that don't exist, and a file that isn't a schematic
Deno.mkdirSync(`${mod}/schematics`);
Deno.writeFileSync(
`${mod}/schematics/ghost_hut.cbsm`,
encode_schematic({
size: [1, 1, 1],
palette: [{ id: "broken:no_such_block" }],
blocks: [{ i: 0, p: [0, 0, 0] }],
entities: [{ p: [0.5, 0, 0.5], id: "broken:no_such_entity", data: {} }],
}),
);
Deno.writeTextFileSync(`${mod}/schematics/notes.cbsm`, "not a schematic");
// a script that doesn't typecheck
Deno.writeTextFileSync(`${mod}/scripts/main.ts`, "export function client(ctx: number) { ctx.nope(); }\n");
// a dependency that isn't installed, and no longer depending on bworld
@@ -151,6 +164,9 @@ Deno.test("check-mods finds broken mods", async () => {
has(report.errors, `depends on "missing_mod", which isn't installed`);
has(report.errors, "entity model broken:no_such_worn doesn't exist");
has(report.errors, "worn must be { model, texture }");
has(report.errors, "schematics/ghost_hut.cbsm: block broken:no_such_block doesn't exist");
has(report.errors, "schematics/ghost_hut.cbsm: entity broken:no_such_entity doesn't exist");
has(report.errors, "schematics/notes.cbsm: ");
has(report.warnings, "worn model broken:stiff has no bone named like a player part");
has(report.warnings, "texture broken:nope doesn't exist");
has(report.warnings, `uses bworld:stone but doesn't list "bworld" in dependencies`);
+254
View File
@@ -0,0 +1,254 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// exporting a box of the world as a schematic file, with /exportschematic, and placing registered schematics
import { assert, assertAlmostEquals, assertEquals, assertStringIncludes, assertThrows } from "@std/assert";
import { decode_schematic, encode_schematic, type Schematic } from "@/common/schematic.ts";
import { create_entity } from "@/server/game/entity/entity_types.ts";
import { new_stack } from "@/server/game/mod_runtime.ts";
import { get_state_value, set_state_value } from "@/common/utils.ts";
import type { SchematicApi } from "@/common/mod_api/server.ts";
import type { GameServer } from "@/server/game/game_server.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
// deno-lint-ignore no-explicit-any
type Msg = any;
async function setup() {
const t = await test_game("mods");
t.join(1, "alice");
stone_floor(t.game);
t.send(1, { type: "move", x: 0.5, y: 100, z: 0.5, yaw: 0, pitch: 0 });
t.take(1);
// runs the command and waits for the host to write the file. the schematic, or undefined and what the player was
// told
const export_schematic = async (args: string) => {
t.send(1, { type: "chat", text: `/exportschematic ${args}` });
await new Promise((resolve) => setTimeout(resolve, 0));
const chat = t.take(1).filter((m: Msg) => m.type === "chat").map((m: Msg) => m.text as string);
const path = chat.map((text) => text.match(/^Saved the schematic to (.+)$/)?.[1]).find((path) => path);
const bytes = path ? t.schematics.get(path) : undefined;
return { schematic: bytes && decode_schematic(bytes), chat };
};
return { ...t, export_schematic };
}
// the palette entry of the block at p, from the box's lowest corner
function block_at(schematic: Schematic, p: [number, number, number]) {
const block = schematic.blocks.find((block) => block.p.every((v, i) => v === p[i]));
assert(block, `nothing at ${p}`);
return { ...schematic.palette[block.i], data: block.data };
}
Deno.test("a schematic has every block in the box with its states, air too, from the lowest corner", async () => {
const t = await setup();
t.game.set_block(2, 100, 1, "bworld:oak_planks");
t.game.set_block(1, 101, 1, "bworld:furnace");
const furnace_value = t.game.world.get_block_value(1, 101, 1);
const facing_west = set_state_value(furnace_value, t.game.world.get_block_info(1, 101, 1)!, "facing", 3)!;
t.game.set_block_state(1, 101, 1, facing_west >>> 16);
// the corners in any order
const { schematic } = await t.export_schematic("2 101 1 1 100 2");
assert(schematic);
assertEquals(schematic.size, [2, 2, 2]);
assertEquals(schematic.blocks.length, 8);
assertEquals(block_at(schematic, [1, 0, 0]).id, "bworld:oak_planks");
const furnace = block_at(schematic, [0, 1, 0]);
assertEquals(furnace.id, "bworld:furnace");
assertEquals(furnace.s?.facing, 3);
assertEquals(block_at(schematic, [0, 0, 1]).id, "cubi:air");
// blocks with the same states share their entry
assertEquals(new Set(schematic.palette.map((entry) => JSON.stringify(entry))).size, schematic.palette.length);
});
Deno.test("a chest's items are written into its data in place of its container's id", async () => {
const t = await setup();
t.game.set_block(1, 100, 1, "bworld:chest");
const id = (t.game.world.get_tile(1, 100, 1)?.mod_data as { container: string }).container;
t.game.containers.get(id)!.set_item(2, new_stack({ id: "bworld:coal", count: 5 }));
const { schematic } = await t.export_schematic("1 100 1 1 100 1");
const items = (block_at(schematic!, [0, 0, 0]).data as { container: unknown[] }).container;
assertEquals(items[2], { id: "bworld:coal", count: 5 });
assertEquals(items[0], null);
// exporting doesn't change the chest
assertEquals(t.game.containers.get(id)!.get_item(2)?.amount, 5);
});
Deno.test("a schematic has the entities whose feet are in the box, without their uuids", async () => {
const t = await setup();
const spawn = (x: number, z: number) => {
const chicken = create_entity(t.game.entities, "bworld:chicken")!;
chicken.set_position(x, 100, z);
t.game.entities.add_entity(chicken);
};
spawn(1.5, 1.25);
spawn(5.5, 1.5);
const { schematic } = await t.export_schematic("1 100 1 2 101 2");
assertEquals(schematic!.entities.length, 1);
const [chicken] = schematic!.entities;
assertEquals(chicken.id, "bworld:chicken");
assertEquals(chicken.p, [0.5, 0, 0.25]);
assertEquals(chicken.data.uuid, undefined);
});
Deno.test("a box with too many blocks isn't exported", async () => {
const t = await setup();
const { schematic, chat } = await t.export_schematic("0 0 0 1000 200 1000");
assertEquals(schematic, undefined);
assert(chat.some((text) => text.startsWith("Couldn't export it")), chat.join("\n"));
assertEquals(t.schematics.size, 0);
});
// a mod that registers a schematic, and leaves its ctx.schematics where the tests can call it
const PLACE_SCRIPT = `
import type { ServerContext } from "cubi/server";
export function server(ctx: ServerContext) {
ctx.schematics.register("testmod:hut", {
size: [2, 2, 1],
palette: [
{ id: "bworld:oak_planks" },
{ id: "bworld:furnace", s: { facing: 1 } },
{ id: "bworld:chest" },
{ id: "cubi:air" },
],
blocks: [
{ i: 0, p: [0, 0, 0] },
{ i: 2, p: [1, 0, 0] },
{ i: 1, p: [0, 1, 0], data: { progress: 7 } },
{ i: 3, p: [1, 1, 0] },
],
entities: [{ p: [1.5, 1, 0.5], id: "bworld:chicken", data: { rotation: [-Math.PI / 2, 0] } }],
});
try {
ctx.schematics.register("testmod:broken", { size: [1, 1, 1], palette: [{ id: "testmod:nothing" }], blocks: [{ i: 0, p: [0, 0, 0] }], entities: [] });
} catch (e) {
ctx.storage.set("broken", (e as Error).message);
}
// the file's is registered before scripts run
try {
ctx.schematics.register("testmod:post", { size: [1, 1, 1], palette: [], blocks: [], entities: [] });
} catch (e) {
ctx.storage.set("post", (e as Error).message);
}
(globalThis as Record<string, unknown>).placing = ctx.schematics;
}
`;
async function place_setup() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_schematics_" });
copy_dir("mods/bworld", `${dir}/bworld`);
Deno.mkdirSync(`${dir}/testmod/scripts`, { recursive: true });
Deno.writeTextFileSync(
`${dir}/testmod/manifest.json`,
JSON.stringify({
format_version: 1,
id: "testmod",
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
main: "scripts/main.ts",
}),
);
Deno.writeTextFileSync(`${dir}/testmod/scripts/main.ts`, PLACE_SCRIPT);
Deno.mkdirSync(`${dir}/testmod/schematics`);
Deno.writeFileSync(
`${dir}/testmod/schematics/post.cbsm`,
encode_schematic({
size: [1, 2, 1],
palette: [{ id: "bworld:oak_log" }],
blocks: [{ i: 0, p: [0, 0, 0] }, { i: 0, p: [0, 1, 0] }],
entities: [],
}),
);
const t = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
stone_floor(t.game);
const schematics = (globalThis as Record<string, unknown>).placing as SchematicApi;
const chickens = () => t.game.entities.all().filter((entity) => entity.type === "bworld:chicken");
return { ...t, schematics, chickens };
}
function facing(t: { game: GameServer }, x: number, y: number, z: number) {
return get_state_value(t.game.world.get_block_value(x, y, z), t.game.world.get_block_info(x, y, z)!, "facing");
}
Deno.test("placing a schematic puts its blocks, their data and its entities where it says", async () => {
const t = await place_setup();
t.game.set_block(11, 101, 20, "bworld:stone");
t.schematics.place("testmod:hut", { position: { x: 10, y: 100, z: 20 } });
assertEquals(t.game.world.get_block_id(10, 100, 20), "bworld:oak_planks");
assertEquals(t.game.world.get_block_id(10, 101, 20), "bworld:furnace");
assertEquals(facing(t, 10, 101, 20), 1);
// air replaces what was there
assertEquals(t.game.world.get_block_id(11, 101, 20), "cubi:air");
// a block with data gets it as it is, one without gets its on_create
assertEquals(t.game.world.get_tile(10, 101, 20)?.mod_data, { progress: 7 });
const chest = t.game.world.get_tile(11, 100, 20)?.mod_data as { container: string };
assert(t.game.containers.has(chest.container));
const [chicken] = t.chickens();
assertEquals([chicken.x, chicken.y, chicken.z], [11.5, 101, 20.5]);
assertEquals(chicken.yaw, -Math.PI / 2);
// placed twice, it's a different chicken
t.schematics.place("testmod:hut", { position: { x: 10, y: 100, z: 30 } });
assertEquals(new Set(t.chickens().map((chicken) => chicken.id)).size, 2);
});
Deno.test("a placed schematic turns clockwise around its pivot, with its facing states and entities", async () => {
const t = await place_setup();
t.schematics.place("testmod:hut", { position: { x: 10, y: 100, z: 20 }, rotation: 90 });
// east of the pivot turns to south of it
assertEquals(t.game.world.get_block_id(10, 100, 20), "bworld:oak_planks");
assertEquals(t.game.world.get_block_id(10, 100, 21), "bworld:chest");
// facing east turns to south
assertEquals(facing(t, 10, 101, 20), 2);
const [chicken] = t.chickens();
assertEquals([chicken.x, chicken.z], [10.5, 21.5]);
assertAlmostEquals(Math.abs(chicken.yaw), Math.PI);
});
Deno.test("a mirrored schematic flips across its pivot before it turns", async () => {
const t = await place_setup();
t.schematics.place("testmod:hut", {
position: { x: 10, y: 100, z: 20 },
position_pivot: { x: 1, y: 0, z: 0 },
mirror: "x",
});
assertEquals(t.game.world.get_block_id(12, 100, 20), "bworld:oak_planks");
assertEquals(t.game.world.get_block_id(11, 100, 20), "bworld:chest");
// east flips to west
assertEquals(facing(t, 12, 101, 20), 3);
const [chicken] = t.chickens();
assertEquals([chicken.x, chicken.z], [11.5, 20.5]);
assertEquals(chicken.yaw, Math.PI / 2);
});
Deno.test("a schematic is checked when it's registered, and a placement before anything changes", async () => {
const t = await place_setup();
assertStringIncludes(String(t.game.mods.storage.testmod?.broken), "testmod:nothing");
assertThrows(
() => t.schematics.place("testmod:broken", { position: { x: 0, y: 100, z: 0 } }),
Error,
"no schematic",
);
assertThrows(
() => t.schematics.place("testmod:hut", { position: { x: 0, y: 100, z: 0 }, rotation: 45 as 90 }),
Error,
"rotation",
);
assertEquals(t.game.world.get_block_id(0, 100, 0), "cubi:air");
});
Deno.test("a mod's schematics/<name>.cbsm files are registered as <mod id>:<name> before its scripts run", async () => {
const t = await place_setup();
assertStringIncludes(String(t.game.mods.storage.testmod?.post), "registered twice");
t.schematics.place("testmod:post", { position: { x: 3, y: 100, z: 4 } });
assertEquals(t.game.world.get_block_id(3, 100, 4), "bworld:oak_log");
assertEquals(t.game.world.get_block_id(3, 101, 4), "bworld:oak_log");
});
+18
View File
@@ -28,6 +28,7 @@ import { check_references, load_order, type LoadedMod, type ModReport } from "@/
import { data_url, png_size, texture_size_problem } from "@/common/mod.ts";
import { type TextureJson, validate_texture_json } from "@/common/texture_animation.ts";
import { type LootTableJson, validate_loot_table } from "@/common/loot.ts";
import { decode_schematic, type Schematic, SCHEMATIC_EXTENSION, validate_schematic } from "@/common/schematic.ts";
import { validate_biome } from "@/common/worldgen/biomes.ts";
import {
validate_biome_source,
@@ -141,6 +142,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
biome_sources: [],
dimensions: [],
features: [],
schematics: [],
textures: [],
texture_files: new Map(),
texture_json: new Map(),
@@ -272,6 +274,22 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
});
}
// schematics/<name>.cbsm is the schematic <mod id>:<name>
for (const file of walk(`${dir}/schematics`, SCHEMATIC_EXTENSION)) {
const path = `schematics/${file}`;
let schematic: Schematic;
try {
schematic = decode_schematic(Deno.readFileSync(`${dir}/${path}`));
} catch (e) {
error(`${path}: ${(e as Error).message}`);
continue;
}
const json = { ...schematic, id: `${id}:${file.slice(0, -SCHEMATIC_EXTENSION.length)}` };
const problems = validate_schematic(json);
for (const problem of problems) error(`${path}: ${problem}`);
if (problems.length === 0) mod.schematics.push({ file: path, json });
}
if (exists(`${dir}/config.json`)) {
mod.config = read_data("config.json", "config", json_object, "{ ... }");
}