Files
bworld/tests/bmod_test.ts
T
2026-11-03 17:17:37 -03:00

440 lines
18 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// .bmod files: packing mods, reading them back, and the server loading a folder of them
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { zipSync } from "fflate";
import { ATLAS_BORDER, atlas_layout, extrude_borders } from "$/client/atlas.ts";
import { MAX_TEXTURE_SIZE } from "$/common/constants.ts";
import { type Bmod, read_bmod, write_bmod } from "$/common/bmod.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { pack_mod } from "$/tools/pack_mod.ts";
import { create_mod } from "$/tools/new_mod.ts";
import { load_bmods } from "$/server/load_bmods.ts";
import { start_host } from "$/server/host.ts";
import { copy_dir } from "./helpers.ts";
import { PROTOCOL_VERSION } from "$/common/protocol.ts";
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";
const ENGINE_TEXTURES = ["cubi:missing", ...Array.from({ length: 9 }, (_, i) => `cubi:break_${i}`)];
// mods/bworld and one made from the template, packed into a folder of .bmod files
async function packed_mods() {
const sources = Deno.makeTempDirSync({ prefix: "bworld_bmod_src_" });
copy_dir("mods/bworld", `${sources}/bworld`);
create_mod("copper_tools", "Copper Tools", sources);
const mods = load_and_check(sources);
for (const mod of mods) assertEquals(mod.report.errors, [], mod.id);
const folder = Deno.makeTempDirSync({ prefix: "bworld_bmod_" });
for (const mod of mods) Deno.writeFileSync(`${folder}/${mod.id}.bmod`, await pack_mod(mod));
return { sources, folder, mods };
}
Deno.test("packing a mod keeps its data, scripts, textures 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.bmod`);
assertEquals(await pack_mod(template), bytes);
const bmod = read_bmod(bytes, "copper_tools.bmod");
assertEquals(bmod.manifest.id, "copper_tools");
assertEquals(bmod.data.blocks.map((b) => b.id), template.blocks.map((b) => b.json.id));
assertEquals(bmod.data.recipes, template.recipes.map((r) => r.json));
assertEquals([...bmod.textures.keys()].sort(), [...template.textures].sort());
assertEquals(Object.keys(bmod.scripts).sort(), ["client", "server", "worldgen"]);
assertStringIncludes(bmod.scripts.server!, "setup");
assert(bmod.credits);
const bworld = read_bmod(Deno.readFileSync(`${folder}/bworld.bmod`), "bworld.bmod");
assertEquals(bworld.data.blocks.length, [...Deno.readDirSync("mods/bworld/blocks")].length);
assertEquals(Object.keys(bworld.scripts), ["server", "client", "worldgen", "shared"]);
Deno.removeSync(sources, { recursive: true });
Deno.removeSync(folder, { recursive: true });
});
Deno.test("broken .bmod files are turned away, saying why", () => {
const text = (value: unknown) => new TextEncoder().encode(JSON.stringify(value));
const manifest = { format_version: 1, id: "broken", name: "Broken", version: "1.0.0" };
const zip = (files: Record<string, Uint8Array>) => zipSync(files);
assertThrows(() => read_bmod(new TextEncoder().encode("not a zip"), "a.bmod"), Error, "isn't a readable .bmod");
assertThrows(() => read_bmod(zip({ "data.json": text({}) }), "b.bmod"), Error, "manifest.json is missing");
assertThrows(
() =>
read_bmod(
zip({
"manifest.json": text(manifest),
"data.json": text({ blocks: [{ id: "other:thing", textures: "broken:x" }, { id: "broken:y" }] }),
}),
"c.bmod",
),
Error,
"other:thing isn't in this mod's namespace",
);
assertThrows(
() =>
read_bmod(
zip({
"manifest.json": text({ ...manifest, scripts: { server: "scripts/server.js" } }),
"data.json": text({}),
}),
"d.bmod",
),
Error,
"scripts.server scripts/server.js isn't in the file",
);
// a texture bigger than MAX_TEXTURE_SIZE. only its header is read
const big = new Uint8Array(24);
big.set([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]);
new DataView(big.buffer).setUint32(16, MAX_TEXTURE_SIZE * 2);
new DataView(big.buffer).setUint32(20, 16);
assertThrows(
() =>
read_bmod(
zip({ "manifest.json": text(manifest), "data.json": text({}), "textures/big.png": big }),
"e.bmod",
),
Error,
`textures can be at most ${MAX_TEXTURE_SIZE}×${MAX_TEXTURE_SIZE}`,
);
// too much once unzipped, without unzipping it all
const huge = new Uint8Array(65 * 1024 * 1024);
assertThrows(
() => read_bmod(zip({ "manifest.json": text(manifest), "data.json": text({}), "big.bin": huge }), "f.bmod"),
Error,
"unzips to more than",
);
});
Deno.test("the server loads every .bmod in its folder, dependencies first, and players get them without server scripts", async () => {
const { sources, folder } = await packed_mods();
const mods = await load_bmods(folder, ENGINE_TEXTURES);
assertEquals(mods.map((mod) => mod.listing.id), ["bworld", "copper_tools"]);
for (const mod of mods) {
assertEquals(mod.listing.file, `mods/${mod.listing.sha256}.bmod`);
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", mod.client_bytes));
assertEquals([...digest].map((b) => b.toString(16).padStart(2, "0")).join(""), mod.listing.sha256);
const copy = read_bmod(mod.client_bytes, mod.listing.file);
assertEquals(copy.scripts.server, undefined, "server scripts never go to players");
assertEquals(copy.scripts.worldgen, undefined, "players get the world from the server, not its generator");
assertEquals(copy.scripts.shared, mod.bmod.scripts.shared, "players run the shared rules too");
// the terrain's data stays on the server too, the rest is the same
const { noises, density_functions, noise_settings, biome_sources, ...data } = mod.bmod.data;
assertEquals(copy.data, { ...data, noises: [], density_functions: [], noise_settings: [], biome_sources: [] });
if (mod.listing.id === "bworld") {
assert([noises, density_functions, noise_settings, biome_sources].every((list) => list!.length > 0));
}
}
assert(mods[1].bmod.scripts.server, "the server still has it");
// the same mod twice, and a mod whose dependency isn't there
Deno.copyFileSync(`${folder}/copper_tools.bmod`, `${folder}/copper_tools_again.bmod`);
await assertRejects(() => load_bmods(folder, ENGINE_TEXTURES), Error, 'are both the mod "copper_tools"');
Deno.removeSync(`${folder}/copper_tools_again.bmod`);
Deno.removeSync(`${folder}/bworld.bmod`);
await assertRejects(() => load_bmods(folder, ENGINE_TEXTURES), Error, `depends on "bworld"`);
Deno.removeSync(sources, { recursive: true });
Deno.removeSync(folder, { recursive: true });
});
Deno.test("the host serves each mod's player copy by its hash, and a game made from .bmod files plays", async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const world = `${build}/world`;
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: world,
seed: "bmod-seed",
on_fatal: (message) => {
throw new Error(message);
},
});
const listings = (await load_bmods(folder, ENGINE_TEXTURES)).map((mod) => mod.listing);
for (const listing of listings) {
const response = await host.handle(new Request(`http://localhost/${listing.file}`));
assertEquals(response.status, 200);
assertEquals(response.headers.get("access-control-allow-origin"), "*");
const bmod = read_bmod(new Uint8Array(await response.arrayBuffer()), listing.file);
assertEquals(bmod.manifest.id, listing.id);
}
assertEquals((await host.handle(new Request("http://localhost/mods/nope.bmod"))).status, 404);
// the game worker loaded both mods, including the template's server script, and saves
await host.shutdown();
const saved = JSON.parse(Deno.readTextFileSync(`${world}/level.json`));
assertEquals(saved.seed, "bmod-seed");
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
});
Deno.test("a mod with its own deno.json is bundled with it", async () => {
const sources = Deno.makeTempDirSync({ prefix: "bworld_bmod_project_" });
copy_dir("mods/bworld", `${sources}/bworld`);
const mod = `${sources}/project`;
Deno.mkdirSync(`${mod}/scripts/lib`, { recursive: true });
Deno.writeTextFileSync(
`${mod}/manifest.json`,
JSON.stringify({
format_version: 1,
id: "project",
name: "Project",
version: "1.0.0",
scripts: { server: "scripts/server.ts" },
}),
);
// only the mod's own import map knows "lib/"
Deno.writeTextFileSync(`${mod}/deno.json`, JSON.stringify({ imports: { "lib/": "./scripts/lib/" } }));
Deno.writeTextFileSync(`${mod}/scripts/lib/greeting.ts`, `export const GREETING = "hello from a deno project";\n`);
Deno.writeTextFileSync(
`${mod}/scripts/server.ts`,
`import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function setup(ctx: any) {\n\tctx.log(GREETING);\n}\n`,
);
const project = load_and_check(sources).find((m) => m.id === "project")!;
assertEquals(project.report.errors, []);
const bmod = read_bmod(await pack_mod(project), "project.bmod");
assertStringIncludes(bmod.scripts.server!, "hello from a deno project");
Deno.removeSync(sources, { recursive: true });
});
const sizes = (entries: [string, number, number][]) =>
new Map(entries.map(([id, width, height]) => [id, { width, height }]));
Deno.test("the atlas lays out same sized textures by id, with the missing texture among them", () => {
const layout = atlas_layout(sizes([["b:two", 16, 16], ["a:one", 16, 16], ["cubi:break_0", 16, 16]]));
assertEquals(layout.size, 64);
// each inside a pixel of border
assertEquals(layout.regions, {
"a:one": { x: 1, y: 1, width: 16, height: 16 },
"b:two": { x: 19, y: 1, width: 16, height: 16 },
"cubi:break_0": { x: 37, y: 1, width: 16, height: 16 },
"cubi:missing": { x: 1, y: 19, width: 16, height: 16 },
});
const many = atlas_layout(sizes(Array.from({ length: 100 }, (_, i) => [`m:t${i}`, 16, 16])));
assertEquals(many.size, 256);
});
Deno.test("the atlas fits textures of any size, tallest first, without overlapping", () => {
const layout = atlas_layout(
sizes([["a:block", 16, 16], ["a:zombie", 64, 64], ["a:boat", 128, 32], ["a:x", 8, 24]]),
);
assertEquals(layout.size, 256);
assertEquals(layout.regions["a:zombie"], { x: 1, y: 1, width: 64, height: 64 });
assertEquals(layout.regions["a:boat"], { x: 67, y: 1, width: 128, height: 32 });
assertEquals(layout.regions["a:x"], { x: 197, y: 1, width: 8, height: 24 });
const big = atlas_layout(
sizes(Array.from({ length: 40 }, (_, i) => [`m:t${i}`, 16 + (i % 5) * 12, 8 + (i % 7) * 9])),
);
const regions = Object.values(big.regions);
// with their borders
const b = ATLAS_BORDER;
for (const [i, a] of regions.entries()) {
assert(a.x >= b && a.y >= b && a.x + a.width + b <= big.size && a.y + a.height + b <= big.size);
for (const c of regions.slice(i + 1)) {
const apart = a.x + a.width + 2 * b <= c.x || c.x + c.width + 2 * b <= a.x ||
a.y + a.height + 2 * b <= c.y || c.y + c.height + 2 * b <= a.y;
assert(apart, `${JSON.stringify(a)} overlaps ${JSON.stringify(c)}`);
}
}
});
Deno.test("each texture's border in the atlas repeats its edge, so lookups at the edge never reach the next one", () => {
// a 2×2 texture at 1 1 in a 4×4 atlas, pixels numbered 1 to 4 in the red channel
const pixels = new Uint8ClampedArray(4 * 4 * 4);
const red = (x: number, y: number) => pixels[(y * 4 + x) * 4];
[[1, 1, 1], [2, 1, 2], [1, 2, 3], [2, 2, 4]].forEach(([x, y, n]) => pixels[(y * 4 + x) * 4] = n);
extrude_borders(pixels, 4, { "a:t": { x: 1, y: 1, width: 2, height: 2 } });
const rows = [0, 1, 2, 3].map((y) => [0, 1, 2, 3].map((x) => red(x, y)));
assertEquals(rows, [
[1, 1, 2, 2],
[1, 1, 2, 2],
[3, 3, 4, 4],
[3, 3, 4, 4],
]);
});
Deno.test({
name: "a player joining a real host gets chunks the worldgen workers made, and /tps says they're in use",
// the host's server and its workers outlive the sanitizers until they're shut down
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "workers-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
const socket = new WebSocket(`ws://localhost:${server.addr.port}/ws`);
socket.binaryType = "arraybuffer";
let chunks = 0;
const said: string[] = [];
const done = new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks++;
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks >= 49) socket.send(JSON.stringify({ type: "chat", text: "/tps" }));
}
if (message.type === "chat") said.push(message.text);
if (said.some((text) => text.startsWith("Worldgen:"))) {
clearTimeout(timer);
resolve();
}
};
});
socket.onopen = () =>
socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
await done;
socket.close();
assert(chunks >= 49, `${chunks} chunks`);
assertStringIncludes(said.find((text) => text.startsWith("Worldgen:"))!, "Worldgen: 2 workers");
} finally {
await server.shutdown();
await host.shutdown();
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// joins a host as alice with view distance 4, until she has every chunk in view
async function join_host(port: number): Promise<LevelChunk[]> {
const socket = new WebSocket(`ws://localhost:${port}/ws`);
socket.binaryType = "arraybuffer";
const chunks: LevelChunk[] = [];
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => reject(new Error(`only ${chunks.length} chunks came`)), 60_000);
socket.onmessage = (event) => {
if (typeof event.data !== "string") {
chunks.push(decode_level_chunk(new Uint8Array(event.data)));
return;
}
const message = JSON.parse(event.data);
if (message.type === "welcome") socket.send(JSON.stringify({ type: "ready", view_distance: 4 }));
if (message.type === "chunk_batch_finished") {
socket.send(JSON.stringify({ type: "chunk_batch_received", chunks_per_tick: 64 }));
if (chunks.length >= 49) {
clearTimeout(timer);
resolve();
}
}
};
socket.onopen = () => socket.send(JSON.stringify({ type: "hello", name: "alice", protocol: PROTOCOL_VERSION }));
});
const closed = new Promise((resolve) => socket.onclose = resolve);
socket.close();
await closed;
return chunks;
}
Deno.test({
name: "a real host saves every chunk it generates, and players get them from the save after it starts again",
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const { sources, folder } = await packed_mods();
const build = Deno.makeTempDirSync({ prefix: "bworld_build_" });
Deno.mkdirSync(`${build}/assets/textures`, { recursive: true });
Deno.writeTextFileSync(
`${build}/assets/textures/index.json`,
JSON.stringify(ENGINE_TEXTURES.slice(1).map((id) => id.split(":")[1])),
);
const run = async () => {
const host = await start_host({
build_dir: build,
server_mods_dir: folder,
world_dir: `${build}/world`,
seed: "saving-seed",
worldgen_workers: 2,
on_fatal: (message) => {
throw new Error(message);
},
});
const server = Deno.serve({ port: 0, onListen: () => {} }, host.handle);
try {
return await join_host(server.addr.port);
} finally {
await server.shutdown();
await host.shutdown();
}
};
try {
const first = await run();
const region = `${build}/world/region`;
const saved = await list_chunks(region);
for (const chunk of first) assert(saved.some(([x, z]) => x === chunk.x && z === chunk.z));
// a block at the top of every saved chunk, which generation never puts there
await write_chunks(
region,
await Promise.all(saved.map(async ([x, z]) => {
const chunk = decode_chunk((await read_chunk(region, x, z))!);
chunk.blocks[255 * 256] = chunk.palette.push(["bworld:stone", 0]) - 1;
return { x, z, data: encode_chunk(chunk as Required<typeof chunk>) };
})),
);
const second = await run();
assert(second.length >= 49);
for (const chunk of second) assert(chunk.blocks[255 * 256] !== 0, `${chunk.x},${chunk.z} is from the save`);
} finally {
for (const dir of [sources, folder, build]) Deno.removeSync(dir, { recursive: true });
}
},
});
// write_bmod without anything optional still makes a file read_bmod takes
Deno.test("a mod with only data packs and reads", () => {
const bmod: Bmod = {
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data: {
blocks: [],
models: [],
items: [],
recipes: [],
ores: [],
spawns: [],
entities: [],
entity_models: [],
effects: [],
fluids: [],
tags: [],
},
scripts: {},
textures: new Map(),
};
assertEquals(read_bmod(write_bmod(bmod), "tiny.bmod").manifest.id, "tiny");
});