Placing schematics

This commit is contained in:
2026-11-15 19:01:40 -03:00
parent 59bfed58bf
commit 6bb2c87373
10 changed files with 464 additions and 50 deletions
+8 -1
View File
@@ -73,10 +73,17 @@ Blocks without the hooks just copy data unchanged, which is fine for plain field
### Placing schematics
Built without `import_data`, see `docs/modding/misc/schematics.md`:
```typescript
ctx.schematics.place(id, { position, dimension, position_pivot, rotation, mirror });
ctx.schematics.register(id, schematic);
ctx.schematics.place(id, { position, position_pivot, rotation, mirror });
```
`register` takes a `Schematic` object for now, loading them from mods' schematics directories isn't built. 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.
### Rotation and mirroring
- `rotation` is `0`, `90`, `180` or `270` degrees clockwise seen from above, the same as the `"y"` of a block variant
+21
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,
@@ -577,6 +579,25 @@ export interface SchematicApi {
// 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 {
+22
View File
@@ -4,6 +4,8 @@
// 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";
@@ -62,3 +64,23 @@ export function decode_schematic(bytes: Uint8Array): Schematic {
}
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);
}
+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 -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 |
+40 -1
View File
@@ -4,7 +4,8 @@ A schematic is a box of the world saved to a file: its blocks with their states
placed again somewhere else. Schematic files end in `.cbsm` and are [MessagePack](https://msgpack.org), see
`common/schematic.ts` for their format.
Only exporting is built so far. Placing schematics, and mods shipping their own, are planned in `STRUCTURES.md`.
Exporting, registering and placing are built. Mods shipping their own as files, and blocks making what their data points
to when they're placed (`import_data`), are planned in `STRUCTURES.md`.
## Exporting
@@ -32,6 +33,44 @@ What goes in:
Positions are from the box's lowest corner.
## Placing
A schematic is registered by id in the server phase, then placed 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
+73 -32
View File
@@ -47,10 +47,10 @@ 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, Position, 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 } from "./schematics.ts";
import { capture_schematic, placed_schematic, type RegisteredSchematic } from "./schematics.ts";
import {
argument,
choice,
@@ -88,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";
@@ -183,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;
@@ -693,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
@@ -734,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>();
@@ -924,6 +929,42 @@ export class GameServer {
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
+17 -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";
@@ -769,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 = {}) => {
@@ -1061,6 +1061,15 @@ export class ModRuntime {
},
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) => {
+135 -3
View File
@@ -1,15 +1,24 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// exporting a box of the world as a schematic, see common/schematic.ts and ctx.schematics
// 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, SchematicBlock, SchematicEntity, SchematicPaletteEntry } from "@/common/schematic.ts";
import { block_states } from "@/common/utils.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;
@@ -93,3 +102,126 @@ function without_passenger_uuids(saved: SavedEntity): Record<string, unknown> {
),
};
}
// 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;
}
+133 -4
View File
@@ -1,13 +1,15 @@
// 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
import { assert, assertEquals } from "@std/assert";
// 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, 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 { set_state_value } from "@/common/utils.ts";
import { stone_floor, test_game } from "./helpers.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;
@@ -99,3 +101,130 @@ Deno.test("a box with too many blocks isn't exported", async () => {
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);
}
(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);
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");
});