Loading schematics

This commit is contained in:
2026-11-15 19:54:08 -03:00
parent 6bb2c87373
commit 0564275f58
15 changed files with 142 additions and 17 deletions
+2 -1
View File
@@ -80,7 +80,8 @@ ctx.schematics.register(id, schematic);
ctx.schematics.place(id, { position, position_pivot, rotation, mirror }); 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/<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 `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. `on_create`, then every placed block tells its neighbors.
+6 -2
View File
@@ -50,6 +50,7 @@ import {
import { type FeatureJson, validate_feature } from "./worldgen/features.ts"; import { type FeatureJson, validate_feature } from "./worldgen/features.ts";
import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts"; import { texture_animation, type TextureJson, validate_texture_json } from "./texture_animation.ts";
import { ENGINE_GLOBAL } from "./hooks.ts"; import { ENGINE_GLOBAL } from "./hooks.ts";
import { type Schematic, validate_schematic } from "./schematic.ts";
export const MOD_EXTENSION = ".cubi"; export const MOD_EXTENSION = ".cubi";
@@ -81,7 +82,7 @@ export class ModError extends Error {
// the zip's layout: // the zip's layout:
// manifest.json the mod's manifest, with "main" and "credits" pointing into the zip // 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 // 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 // script.js
// textures/<name>.png the texture <mod id>:<name> // textures/<name>.png the texture <mod id>:<name>
// textures/<name>.json its animation, if it has one // textures/<name>.json its animation, if it has one
@@ -214,6 +215,7 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
) as BiomeSourceJson[], ) as BiomeSourceJson[],
dimensions: checked(raw_data.dimensions, "dimensions", validate_dimension, problems) as DimensionJson[], dimensions: checked(raw_data.dimensions, "dimensions", validate_dimension, problems) as DimensionJson[],
features: checked(raw_data.features, "features", validate_feature, problems) as FeatureJson[], 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, config: raw_data.config,
}; };
if (raw_data.config !== undefined && !is_object(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.biome_sources!,
...data.dimensions!, ...data.dimensions!,
...data.features!, ...data.features!,
...data.schematics!,
]; ];
for (const { id } of [...registered, ...data.loot_tables!, ...data.biomes!, ...worldgen]) { 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`); 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 }; 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 // script goes with it whole, and players only run its shared and client phases
export function client_copy(mod: Mod): Mod { export function client_copy(mod: Mod): Mod {
const { const {
@@ -309,6 +312,7 @@ export function client_copy(mod: Mod): Mod {
biome_sources: _b, biome_sources: _b,
dimensions: _dim, dimensions: _dim,
features: _f, features: _f,
schematics: _sc,
config: _c, config: _c,
...data ...data
} = mod.data; } = mod.data;
+14
View File
@@ -42,6 +42,7 @@ import {
import { feature_refs, type FeatureJson } from "./worldgen/features.ts"; import { feature_refs, type FeatureJson } from "./worldgen/features.ts";
import { cell_height_problem } from "./world_shape.ts"; import { cell_height_problem } from "./world_shape.ts";
import type { ModData } from "./mod_loader.ts"; import type { ModData } from "./mod_loader.ts";
import type { Schematic } from "./schematic.ts";
export interface ModReport { export interface ModReport {
id: string; id: string;
@@ -74,6 +75,8 @@ export interface LoadedMod {
biome_sources: { file: string; json: BiomeSourceJson }[]; biome_sources: { file: string; json: BiomeSourceJson }[];
dimensions: { file: string; json: DimensionJson }[]; dimensions: { file: string; json: DimensionJson }[];
features: { file: string; json: FeatureJson }[]; 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.json's settings, see docs/modding/misc/config.md
config?: Record<string, unknown>; config?: Record<string, unknown>;
textures: string[]; textures: string[];
@@ -105,6 +108,7 @@ export function mod_data(mod: LoadedMod): ModData {
biome_sources: mod.biome_sources.map((b) => b.json), biome_sources: mod.biome_sources.map((b) => b.json),
dimensions: mod.dimensions.map((d) => d.json), dimensions: mod.dimensions.map((d) => d.json),
features: mod.features.map((f) => f.json), features: mod.features.map((f) => f.json),
schematics: mod.schematics.map((s) => s.json),
config: mod.config, 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"); 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) { for (const { file, json } of mod.spawns) {
check_namespace(file, json.entity); check_namespace(file, json.entity);
const entity = entity_jsons.get(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 { register_block_item } from "./utils.ts";
import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts"; import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts";
import { loading_mod } from "./hooks.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) // everything a mod's json files hold, merged into one file by the build (build/mods/<id>/<hash>/data.json)
export interface ModData { export interface ModData {
@@ -77,6 +78,8 @@ export interface ModData {
dimensions?: DimensionJson[]; dimensions?: DimensionJson[];
// data features, see common/worldgen/features.ts. server only too // data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[]; 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 // 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 // too, see docs/modding/misc/config.md
config?: Record<string, unknown>; config?: Record<string, unknown>;
+5
View File
@@ -84,3 +84,8 @@ const schematic_schema = z.object({
export function schematic_problems(json: unknown): Problems { export function schematic_problems(json: unknown): Problems {
return find_problems(schematic_schema, json); 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);
}
+4 -3
View File
@@ -29,6 +29,7 @@ mods/
worldgen/noise_settings/**/*.json worldgen/noise_settings/**/*.json
worldgen/biome_source/**/*.json worldgen/biome_source/**/*.json
worldgen/spawns.json # monsters that spawn on their own, see entities/index.md 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/*.png
textures/*.json # animations, see resources/textures.md textures/*.json # animations, see resources/textures.md
scripts/ scripts/
@@ -115,7 +116,7 @@ deno task build # packs every mod in mods/ into server_mo
``` ```
copper_tools.cubi copper_tools.cubi
manifest.json # with main and credits pointing into the zip 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 script.js # the script bundled into one module
textures/<name>.png textures/<name>.png
textures/<name>.json # for animated textures 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 - `deno task build` leaves other `.cubi` files in `server_mods/` alone, so mods from elsewhere can sit next to the ones
it builds. it builds.
- `data.json` doesn't hold the blocks the content phase registers. The server runs it when it loads the `.cubi`. - `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 - Players get a copy **without** the terrain's data, the schematics and the config, but with the blocks the content
its `data.json`. See [Networking](../networking/index.md). phase registered in its `data.json`. See [Networking](../networking/index.md).
+7 -3
View File
@@ -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 placed again somewhere else. Schematic files end in `.cbsm` and are [MessagePack](https://msgpack.org), see
`common/schematic.ts` for their format. `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 Exporting, registering and placing are built. Blocks making what their data points to when they're placed
to when they're placed (`import_data`), are planned in `STRUCTURES.md`. (`import_data`) is planned in `STRUCTURES.md`.
## Exporting ## Exporting
@@ -35,7 +35,11 @@ Positions are from the box's lowest corner.
## Placing ## Placing
A schematic is registered by id in the server phase, then placed by that id: 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 ```ts
ctx.schematics.register("copper_tools:hut", schematic); ctx.schematics.register("copper_tools:hut", schematic);
Binary file not shown.
Binary file not shown.
+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 // 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 // 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 type { ModData, ModListing } from "@/common/mod_loader.ts";
import { load_worldgen } from "@/common/worldgen_loader.ts"; import { load_worldgen } from "@/common/worldgen_loader.ts";
import { dimension_shape, type DimensionJson } from "@/common/worldgen/data.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 { GameHost, GameServer } from "./game_server.ts";
import type { WorldSource } from "./saves.ts"; import type { WorldSource } from "./saves.ts";
import { ModRuntime } from "./mod_runtime.ts"; import { ModRuntime } from "./mod_runtime.ts";
import { prepare_schematic } from "./schematics.ts";
import { register_entity_type } from "./entity/entity_types.ts"; import { register_entity_type } from "./entity/entity_types.ts";
import { mod_entity_factory } from "./entity/mod_entity.ts"; import { mod_entity_factory } from "./entity/mod_entity.ts";
import { set_effect_types } from "./entity/effects.ts"; import { set_effect_types } from "./entity/effects.ts";
@@ -68,6 +69,17 @@ export async function start_game(
runtime, 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 }] : []); 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 // every mod's shared rules first, so server phases can count on any mod's being there
await runtime.load_shared_scripts(game, scripts); await runtime.load_shared_scripts(game, scripts);
+1
View File
@@ -233,6 +233,7 @@ function as_loaded_mod(file: string, mod: Mod): LoadedMod {
biome_sources: entries(mod.data.biome_sources ?? []), biome_sources: entries(mod.data.biome_sources ?? []),
dimensions: entries(mod.data.dimensions ?? []), dimensions: entries(mod.data.dimensions ?? []),
features: entries(mod.data.features ?? []), features: entries(mod.data.features ?? []),
schematics: entries(mod.data.schematics ?? []),
config: mod.data.config, config: mod.data.config,
textures: [...mod.textures.keys()], textures: [...mod.textures.keys()],
texture_files: new Map(), texture_files: new Map(),
+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 { decode_chunk, encode_chunk } from "@/server/game/saves.ts";
import { list_chunks, read_chunk, write_chunks } from "@/server/regions.ts"; import { list_chunks, read_chunk, write_chunks } from "@/server/regions.ts";
import { section_index } from "@/common/section.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() { async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" }); const sources = Deno.makeTempDirSync({ prefix: "bworld_mod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`); copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources); 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); const mods = await load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id); for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
@@ -32,7 +43,7 @@ async function packed_mods() {
return { sources, folder, 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 { sources, folder, mods } = await packed_mods();
const template = mods.find((mod) => mod.id === "copper_tools")!; const template = mods.find((mod) => mod.id === "copper_tools")!;
const bytes = Deno.readFileSync(`${folder}/copper_tools.cubi`); 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.blocks.map((b) => b.id), template.blocks.map((b) => b.json.id));
assertEquals(mod.data.recipes, template.recipes.map((r) => r.json)); assertEquals(mod.data.recipes, template.recipes.map((r) => r.json));
assertEquals([...mod.textures.keys()].sort(), [...template.textures].sort()); 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"); assertStringIncludes(mod.script!, "function server");
assert(mod.credits); 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 { sources, folder } = await packed_mods();
const mods = await load_mods(folder, ENGINE_TEXTURES); const mods = await load_mods(folder, ENGINE_TEXTURES);
assertEquals(mods.map((mod) => mod.listing.id), ["bworld", "copper_tools"]); 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, mod.mod.script,
"players get the whole script, and only run its shared and client phases", "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 // 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, ...data } = mod.mod.data; const { noises, density_functions, noise_settings, biome_sources, dimensions, schematics: _, ...data } =
const none = { noises: [], density_functions: [], noise_settings: [], biome_sources: [], dimensions: [] }; mod.mod.data;
const none = {
noises: [],
density_functions: [],
noise_settings: [],
biome_sources: [],
dimensions: [],
schematics: [],
};
assertEquals(copy.data, { ...data, ...none }); assertEquals(copy.data, { ...data, ...none });
if (mod.listing.id === "copper_tools") assertEquals(mod.mod.data.schematics?.length, 1);
if (mod.listing.id === "bworld") { if (mod.listing.id === "bworld") {
const terrain = [noises, density_functions, noise_settings, biome_sources, dimensions]; const terrain = [noises, density_functions, noise_settings, biome_sources, dimensions];
assert(terrain.every((list) => list!.length > 0)); 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 { MAX_TEXTURE_SIZE } from "@/common/constants.ts";
import { create_mod } from "@/tools/new_mod.ts"; import { create_mod } from "@/tools/new_mod.ts";
import { item_from_json, item_to_json } from "@/common/mod_data.ts"; import { item_from_json, item_to_json } from "@/common/mod_data.ts";
import { encode_schematic } from "@/common/schematic.ts";
function temp_mods_dir() { function temp_mods_dir() {
const dir = Deno.makeTempDirSync({ prefix: "bworld_mods_" }); 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(16, MAX_TEXTURE_SIZE + 1);
new DataView(huge.buffer).setUint32(20, 16); new DataView(huge.buffer).setUint32(20, 16);
Deno.writeFileSync(`${mod}/textures/huge.png`, huge); 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 // a script that doesn't typecheck
Deno.writeTextFileSync(`${mod}/scripts/main.ts`, "export function client(ctx: number) { ctx.nope(); }\n"); 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 // 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, `depends on "missing_mod", which isn't installed`);
has(report.errors, "entity model broken:no_such_worn doesn't exist"); has(report.errors, "entity model broken:no_such_worn doesn't exist");
has(report.errors, "worn must be { model, texture }"); 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, "worn model broken:stiff has no bone named like a player part");
has(report.warnings, "texture broken:nope doesn't exist"); has(report.warnings, "texture broken:nope doesn't exist");
has(report.warnings, `uses bworld:stone but doesn't list "bworld" in dependencies`); has(report.warnings, `uses bworld:stone but doesn't list "bworld" in dependencies`);
+25 -1
View File
@@ -3,7 +3,7 @@
// exporting a box of the world as a schematic file, with /exportschematic, and placing registered schematics // 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 { 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 { create_entity } from "@/server/game/entity/entity_types.ts";
import { new_stack } from "@/server/game/mod_runtime.ts"; import { new_stack } from "@/server/game/mod_runtime.ts";
import { get_state_value, set_state_value } from "@/common/utils.ts"; import { get_state_value, set_state_value } from "@/common/utils.ts";
@@ -127,6 +127,12 @@ export function server(ctx: ServerContext) {
} catch (e) { } catch (e) {
ctx.storage.set("broken", (e as Error).message); 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; (globalThis as Record<string, unknown>).placing = ctx.schematics;
} }
`; `;
@@ -147,6 +153,16 @@ async function place_setup() {
}), }),
); );
Deno.writeTextFileSync(`${dir}/testmod/scripts/main.ts`, PLACE_SCRIPT); 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); const t = await test_game(dir);
Deno.removeSync(dir, { recursive: true }); Deno.removeSync(dir, { recursive: true });
stone_floor(t.game); 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"); 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 { data_url, png_size, texture_size_problem } from "@/common/mod.ts";
import { type TextureJson, validate_texture_json } from "@/common/texture_animation.ts"; import { type TextureJson, validate_texture_json } from "@/common/texture_animation.ts";
import { type LootTableJson, validate_loot_table } from "@/common/loot.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 } from "@/common/worldgen/biomes.ts";
import { import {
validate_biome_source, validate_biome_source,
@@ -141,6 +142,7 @@ function load_mod(mods_dir: string, id: string): LoadedMod {
biome_sources: [], biome_sources: [],
dimensions: [], dimensions: [],
features: [], features: [],
schematics: [],
textures: [], textures: [],
texture_files: new Map(), texture_files: new Map(),
texture_json: 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`)) { if (exists(`${dir}/config.json`)) {
mod.config = read_data("config.json", "config", json_object, "{ ... }"); mod.config = read_data("config.json", "config", json_object, "{ ... }");
} }