From 0564275f580c9207ec234e4393ad11c7775f93df Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 15 Nov 2026 19:54:08 -0300 Subject: [PATCH] Loading schematics --- STRUCTURES.md | 3 ++- common/mod.ts | 8 ++++-- common/mod_check.ts | 14 ++++++++++ common/mod_loader.ts | 3 +++ common/schematic.ts | 5 ++++ docs/modding/gettingstarted/modfiles.md | 7 ++--- docs/modding/misc/schematics.md | 10 ++++--- mods/bworld/schematics/air.cbsm | Bin 0 -> 87 bytes mods/bworld/schematics/dirt.cbsm | Bin 0 -> 87 bytes server/game/load_mods.ts | 14 +++++++++- server/load_mods.ts | 1 + tests/mod_test.ts | 34 +++++++++++++++++++----- tests/mod_tools_test.ts | 16 +++++++++++ tests/schematic_test.ts | 26 +++++++++++++++++- tools/check_mods.ts | 18 +++++++++++++ 15 files changed, 142 insertions(+), 17 deletions(-) create mode 100644 mods/bworld/schematics/air.cbsm create mode 100644 mods/bworld/schematics/dirt.cbsm diff --git a/STRUCTURES.md b/STRUCTURES.md index c29541e..b609891 100644 --- a/STRUCTURES.md +++ b/STRUCTURES.md @@ -80,7 +80,8 @@ 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 +Mods' `schematics/.cbsm` files are registered as `:` 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. diff --git a/common/mod.ts b/common/mod.ts index 3c28c78..be03856 100644 --- a/common/mod.ts +++ b/common/mod.ts @@ -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/.png the texture : // textures/.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; diff --git a/common/mod_check.ts b/common/mod_check.ts index 6c95749..2cd67ad 100644 --- a/common/mod_check.ts +++ b/common/mod_check.ts @@ -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/.cbsm, decoded and with their ids + schematics: { file: string; json: Schematic }[]; // config.json's settings, see docs/modding/misc/config.md config?: Record; 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//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/.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; diff --git a/common/schematic.ts b/common/schematic.ts index edcf723..ac68900 100644 --- a/common/schematic.ts +++ b/common/schematic.ts @@ -84,3 +84,8 @@ const schematic_schema = z.object({ 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: : +export function validate_schematic(json: unknown): Problems { + return find_problems(schematic_schema.extend({ id }), json); +} diff --git a/docs/modding/gettingstarted/modfiles.md b/docs/modding/gettingstarted/modfiles.md index 334ae73..96b1b99 100644 --- a/docs/modding/gettingstarted/modfiles.md +++ b/docs/modding/gettingstarted/modfiles.md @@ -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/.png textures/.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). diff --git a/docs/modding/misc/schematics.md b/docs/modding/misc/schematics.md index 23731fd..466dfa0 100644 --- a/docs/modding/misc/schematics.md +++ b/docs/modding/misc/schematics.md @@ -4,8 +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. -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, registering and placing are built. Blocks making what their data points to when they're placed +(`import_data`) is planned in `STRUCTURES.md`. ## Exporting @@ -35,7 +35,11 @@ Positions are from the box's lowest corner. ## Placing -A schematic is registered by id in the server phase, then placed by that id: +A mod's `schematics/.cbsm` files are its schematics `:`, 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); diff --git a/mods/bworld/schematics/air.cbsm b/mods/bworld/schematics/air.cbsm new file mode 100644 index 0000000000000000000000000000000000000000..aab54293fdd615f531ddda03de2cb78fe7405653 GIT binary patch literal 87 zcmWN_OAbIV6a~3a;!G!{UtfQZk;8acxg-@=8)NZM0ixK=-GOZo$L pIv4}3TI3a;!G!{UtfQZk;8acxg-@=8)NZM0ixK=-GOZo$L pIv4}3TI 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); diff --git a/server/load_mods.ts b/server/load_mods.ts index 58417c7..83cdff2 100644 --- a/server/load_mods.ts +++ b/server/load_mods.ts @@ -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(), diff --git a/tests/mod_test.ts b/tests/mod_test.ts index 59ba276..4e5d19c 100644 --- a/tests/mod_test.ts +++ b/tests/mod_test.ts @@ -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)); diff --git a/tests/mod_tools_test.ts b/tests/mod_tools_test.ts index b0f511a..2eb617b 100644 --- a/tests/mod_tools_test.ts +++ b/tests/mod_tools_test.ts @@ -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`); diff --git a/tests/schematic_test.ts b/tests/schematic_test.ts index 74a7b8a..47da0e6 100644 --- a/tests/schematic_test.ts +++ b/tests/schematic_test.ts @@ -3,7 +3,7 @@ // 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 { 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"; @@ -127,6 +127,12 @@ export function server(ctx: ServerContext) { } 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).placing = ctx.schematics; } `; @@ -147,6 +153,16 @@ async function place_setup() { }), ); 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); @@ -228,3 +244,11 @@ Deno.test("a schematic is checked when it's registered, and a placement before a ); assertEquals(t.game.world.get_block_id(0, 100, 0), "cubi:air"); }); + +Deno.test("a mod's schematics/.cbsm files are registered as : 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"); +}); diff --git a/tools/check_mods.ts b/tools/check_mods.ts index 387d75e..1e56e44 100644 --- a/tools/check_mods.ts +++ b/tools/check_mods.ts @@ -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/.cbsm is the schematic : + 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, "{ ... }"); }