Files
bworld/common/schematic.ts
T
2026-11-15 18:41:22 -03:00

65 lines
2.3 KiB
TypeScript

// 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";
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;
}