Single module modding

This commit is contained in:
2026-11-14 12:18:41 -03:00
parent 605008f584
commit 313098892e
134 changed files with 919 additions and 924 deletions
+12 -12
View File
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// blocks a content script registers in code are the mod's data like its files': checked, registered on the server,
// sent to players and generated by worldgen workers. see common/mod_api/content.ts
// blocks a script's content phase registers in code are the mod's data like its files': checked, registered on the
// server, sent to players and generated by worldgen workers. see common/mod_api/content.ts
import { assert, assertEquals, assertRejects, assertStringIncludes, assertThrows } from "@std/assert";
import { EverythingRegistry } from "@/common/everything_registry.ts";
import { ID_MASK } from "@/common/constants.ts";
@@ -19,7 +19,7 @@ import { copy_dir, GROUND_BLOCKS, test_game } from "./helpers.ts";
// a block for every rock and its bricks, and one more where the script can't read files, like the server's worker
const CONTENT = `
import type { ContentContext } from "cubi/content";
export function setup(ctx: ContentContext) {
export function content(ctx: ContentContext) {
for (const rock of ["granite", "basalt"]) {
ctx.blocks.register({ id: \`rocks:\${rock}\`, textures: "cubi:missing", drops: \`rocks:\${rock}\` });
ctx.blocks.register({ id: \`rocks:\${rock}_bricks\`, textures: "cubi:missing" });
@@ -36,7 +36,7 @@ const CONTENT = `
const CODE_BLOCKS = ["rocks:granite", "rocks:granite_bricks", "rocks:basalt", "rocks:basalt_bricks"];
// the base game, and rocks: a block file, the content script above, and a tag and an ore that name its blocks
// the base game, and rocks: a block file, the content phase above, and a tag and an ore that name its blocks
function rocks_mod(extra = "") {
const dir = Deno.makeTempDirSync({ prefix: "bworld_content_" });
copy_dir("mods/bworld", `${dir}/bworld`);
@@ -50,7 +50,7 @@ function rocks_mod(extra = "") {
name: "Rocks",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { content: "scripts/content.ts" },
main: "scripts/content.ts",
});
write("blocks/lamp.json", { format_version: 1, block: { id: "rocks:lamp", textures: "cubi:missing" } });
write("scripts/content.ts", CONTENT.replace("EXTRA", extra));
@@ -62,7 +62,7 @@ function rocks_mod(extra = "") {
return dir;
}
Deno.test("check-mods runs a mod's content script, and its files can name the blocks it registers", async () => {
Deno.test("check-mods runs a mod's content phase, and its files can name the blocks it registers", async () => {
const dir = rocks_mod();
const rocks = (await load_and_check(dir)).find((mod) => mod.id === "rocks")!;
Deno.removeSync(dir, { recursive: true });
@@ -80,7 +80,7 @@ Deno.test("check-mods runs a mod's content script, and its files can name the bl
);
});
Deno.test("the server registers a content script's blocks, and a worldgen worker numbers and generates them alike", async () => {
Deno.test("the server registers a mod's content phase's blocks, and a worldgen worker numbers and generates them alike", async () => {
const dir = rocks_mod();
const { game } = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
@@ -99,7 +99,7 @@ Deno.test("the server registers a content script's blocks, and a worldgen worker
assert(generated.some((value) => (value & ID_MASK) === basalt), "the ore of a block made in code is generated");
});
Deno.test("a packed mod leaves its content script's blocks out, the server registers them without permissions, and players get them as data", async () => {
Deno.test("a packed mod leaves its content phase's blocks out, the server registers them without permissions, and players get them as data", async () => {
const sources = rocks_mod();
const folder = Deno.makeTempDirSync({ prefix: "bworld_content_mods_" });
for (const mod of await load_and_check(sources)) {
@@ -108,7 +108,7 @@ Deno.test("a packed mod leaves its content script's blocks out, the server regis
Deno.removeSync(sources, { recursive: true });
const packed = read_mod(Deno.readFileSync(`${folder}/rocks.cubi`), "rocks.cubi");
assertEquals(packed.data.blocks.map((block) => block.id), ["rocks:lamp"]);
assert(packed.scripts.content);
assert(packed.script);
const rocks = (await load_mods(folder, ["cubi:missing"])).find((mod) => mod.listing.id === "rocks")!;
Deno.removeSync(folder, { recursive: true });
@@ -117,14 +117,14 @@ Deno.test("a packed mod leaves its content script's blocks out, the server regis
assertEquals(rocks.mod.data.blocks.map((block) => block.id), ids);
const copy = read_mod(rocks.client_bytes, rocks.listing.file);
assertEquals(copy.scripts.content, undefined, "players don't run it, they get what it registered");
// players get the script too, but never run its content phase: they get what it registered as data
assertEquals(copy.data.blocks, client_copy(rocks.mod).data.blocks);
EverythingRegistry.clear();
await load_client_mods([rocks.listing], [copy]);
for (const id of ids) assert(EverythingRegistry.get("blocks", id), `${id} is a block on the client`);
});
Deno.test("a content script's mistakes stop its mod loading, naming the script", async () => {
Deno.test("a content phase's mistakes stop its mod loading, naming the script", async () => {
const cases: [string, string][] = [
[
`ctx.blocks.register({ id: "bworld:granite", textures: "cubi:missing" });`,
@@ -155,6 +155,6 @@ Deno.test("a content script's mistakes stop its mod loading, naming the script",
Deno.removeSync(folder, { recursive: true });
assertStringIncludes(
(rejected as Error).message,
`rocks.cubi: scripts/content.js: block bworld:granite isn't in this mod's namespace "rocks"`,
`rocks.cubi: script.js: block bworld:granite isn't in this mod's namespace "rocks"`,
);
});
+2 -2
View File
@@ -6,7 +6,7 @@ import { AIR_ID } from "@/common/protocol.ts";
import { get_state_value, set_state_value } from "@/common/utils.ts";
import type { Face } from "@/common/mod_api/shared.ts";
import type { ClientContext, Instances, ModelRef, Visual, VisualBlock } from "@/common/mod_api/client.ts";
import { setup as setup_client } from "@/mods/create/scripts/client.ts";
import { client as setup_client } from "@/mods/create/scripts/client.ts";
import { stone_floor, test_game } from "../helpers.ts";
// facing and axis states, in the order the importer numbers them
@@ -49,7 +49,7 @@ export async function setup(config: Record<string, unknown> = {}) {
return { ...t, move, place, speed, overstressed, state, use, ticks, crank };
}
// create's client script with only what its visuals need, and a block for one to draw that records what its instances
// create's client phase with only what its visuals need, and a block for one to draw that records what its instances
// do, by model ("own" for the block's own model): how rotating ones turn, and where transformed ones are moved. and the
// items and fluid boxes it draws now, by item and fluid id
export async function visual_for(
+33 -41
View File
@@ -22,22 +22,18 @@ import { game_with_pool } from "./chunk_loading.ts";
const [MAJOR, MINOR] = GAME_VERSION.split(".");
const THIS_MINOR = `~${MAJOR}.${MINOR}.0`;
// a mod in dir with these scripts, as { side: [file, code] }
// a mod in dir whose script is code
function write_mod(
dir: string,
id: string,
scripts: Record<string, [string, string]>,
code: string,
manifest: Record<string, unknown> = { engine_access: true, game_version: THIS_MINOR },
) {
Deno.mkdirSync(`${dir}/${id}/scripts`, { recursive: true });
const paths: Record<string, string> = {};
for (const [side, [file, code]] of Object.entries(scripts)) {
Deno.writeTextFileSync(`${dir}/${id}/scripts/${file}`, code);
paths[side] = `scripts/${file}`;
}
Deno.writeTextFileSync(`${dir}/${id}/scripts/main.ts`, code);
Deno.writeTextFileSync(
`${dir}/${id}/manifest.json`,
JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", scripts: paths, ...manifest }),
JSON.stringify({ format_version: 1, id, name: id, version: "1.0.0", main: "scripts/main.ts", ...manifest }),
);
}
@@ -80,11 +76,11 @@ async function errors_during(fn: () => unknown): Promise<string[]> {
Deno.test("a server mod hooks GameServer to drop twice, like the plan's example", async () => {
const dir = mods_dir((dir) =>
write_mod(dir, "double_drops", {
server: [
"server.ts",
`import { engine, hook } from "cubi/engine";
export function setup() {
write_mod(
dir,
"double_drops",
`import { engine, hook } from "cubi/engine";
export function server() {
hook(engine.server.GameServer.prototype, "pop_item", {
after(game, [x, y, z, stack], entity) {
game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
@@ -92,8 +88,7 @@ Deno.test("a server mod hooks GameServer to drop twice, like the plan's example"
},
});
}`,
],
})
)
);
const { game } = await test_game(dir);
const items = () => game.entities.entities_near(0.5, 100, 0.5, 4).length;
@@ -105,16 +100,15 @@ Deno.test("a server mod hooks GameServer to drop twice, like the plan's example"
Deno.test("a worldgen mod hooks the terrain in engine.common", async () => {
const dir = mods_dir((dir) =>
write_mod(dir, "flat_sea", {
worldgen: [
"worldgen.ts",
`import { engine, hook } from "cubi/engine";
write_mod(
dir,
"flat_sea",
`import { engine, hook } from "cubi/engine";
// no ground anywhere, so it's all sea
export function setup() {
export function worldgen() {
hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 });
}`,
],
})
)
);
const { game } = await test_game(dir, undefined, "engine-access-flat-sea");
assertEquals(game.world.get_block_id(8, 10, 8), "bworld:water");
@@ -126,20 +120,19 @@ Deno.test("a worldgen mod hooks the terrain in engine.common", async () => {
});
Deno.test({
name: "a worldgen mod's hook reaches the worldgen workers too, since each loads the worldgen scripts",
name: "a worldgen mod's hook reaches the worldgen workers too, since each runs the worldgen phase",
sanitizeOps: false,
sanitizeResources: false,
fn: async () => {
const dir = mods_dir((dir) =>
write_mod(dir, "flat_sea", {
worldgen: [
"worldgen.ts",
`import { engine, hook } from "cubi/engine";
export function setup() {
write_mod(
dir,
"flat_sea",
`import { engine, hook } from "cubi/engine";
export function worldgen() {
hook(engine.common.NoiseTerrain.prototype, "density", { replace: () => -1 });
}`,
],
})
)
);
// it's all sea, so no spawn search
const t = await game_with_pool(1, "engine-access-flat-sea-pool", dir, false);
@@ -159,20 +152,19 @@ Deno.test({
Deno.test("a client mod hooks LocalPlayer from its .cubi", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" });
write_mod(dir, "floaty", {
client: [
"client.ts",
`import { engine, hook } from "cubi/engine";
write_mod(
dir,
"floaty",
`import { engine, hook } from "cubi/engine";
// everyone is a block higher than they think
export function setup() {
export function client() {
hook(engine.client.LocalPlayer.prototype, "set_position", {
before(_player, args) {
args[1] += 1;
},
});
}`,
],
});
);
const mod = (await load_and_check(dir))[0];
assertEquals(mod.report.errors, []);
const packed = read_mod(await pack_mod(mod), "floaty.cubi");
@@ -340,18 +332,18 @@ Deno.test("hook needs a loading mod with engine access", async () => {
Deno.test("cubi/engine without engine_access is an error in check-mods and in a .cubi", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_engine_" });
const script = `import { engine } from "cubi/engine";
export function setup() {
export function server() {
console.log(engine.common.physics);
}`;
write_mod(dir, "sneaky", { server: ["server.ts", script] }, {});
write_mod(dir, "sneaky", script, {});
const [mod] = await load_and_check(dir);
assertEquals(mod.report.errors, [
`scripts/server.ts imports cubi/engine, which needs "engine_access": true in manifest.json`,
`scripts/main.ts imports cubi/engine, which needs "engine_access": true in manifest.json`,
]);
// packed anyway, the bundle gives it away
const bytes = await pack_mod(mod);
assertThrows(() => read_mod(bytes, "sneaky.cubi"), Error, "a script uses cubi/engine");
assertThrows(() => read_mod(bytes, "sneaky.cubi"), Error, "its script uses cubi/engine");
Deno.removeSync(dir, { recursive: true });
});
+4 -4
View File
@@ -11,7 +11,7 @@ import { copy_dir, test_game } from "./helpers.ts";
const SCRIPT = `
import type { WorldgenContext } from "cubi/worldgen";
export function setup(gen: WorldgenContext) {
export function worldgen(gen: WorldgenContext) {
// a type for data features: a pillar of a block
gen.register_feature_type<{ block: string; height: number }>("testmod:pillar", (chunk, config, origin) => {
for (let i = 0; i < config.height; i++) chunk.set_block(origin.x, origin.y + i, origin.z, config.block);
@@ -50,7 +50,7 @@ function with_mod(files: Record<string, unknown>, script = SCRIPT) {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { worldgen: "scripts/worldgen.ts" },
main: "scripts/worldgen.ts",
}),
);
write("scripts/worldgen.ts", script);
@@ -135,7 +135,7 @@ Deno.test("a data feature whose type no script registers stops the server", asyn
await assertRejects(
() => test_game(dir),
Error,
"type testmod:nothing isn't built in, and no worldgen script registered it",
"type testmod:nothing isn't built in, and no mod's worldgen phase registered it",
);
} finally {
Deno.removeSync(dir, { recursive: true });
@@ -146,7 +146,7 @@ Deno.test("a feature can't be both code and data", async () => {
const clash = with_mod(
{ "worldgen/features/glass_pillar.json": GLASS_PILLAR },
`import type { WorldgenContext } from "cubi/worldgen";
export function setup(gen: WorldgenContext) {
export function worldgen(gen: WorldgenContext) {
gen.register_feature("testmod:glass_pillar", () => {});
}`,
);
+2 -2
View File
@@ -14,7 +14,7 @@ const JAR = "testmod:jar";
const SERVER_SCRIPT = `
import type { FluidStack, ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
// two tanks kept in its data, reached from every side but the bottom
ctx.components.register_block("testmod:tank", {
fluid_handler(block, _params, face) {
@@ -48,7 +48,7 @@ async function setup() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
});
write("fluids/syrup.json", { format_version: 1, fluid: { id: SYRUP.id, color: "#a0522d" } });
write("fluids/honey.json", { format_version: 1, fluid: { id: HONEY.id, color: "#e0a030" } });
+3 -3
View File
@@ -14,7 +14,7 @@ import { load_and_check } from "@/tools/check_mods.ts";
import { pack_mod } from "@/tools/pack_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
// testfluids: a manifest, the given fluids/ files by file name, and maybe a shared script and an item for it to read
// testfluids: a manifest, the given fluids/ files by file name, and maybe a shared phase and an item for it to read
function fluid_mod(dir: string, fluids: Record<string, unknown>, shared_script?: string) {
const mod = `${dir}/testfluids`;
const write = (path: string, json: unknown) => {
@@ -26,7 +26,7 @@ function fluid_mod(dir: string, fluids: Record<string, unknown>, shared_script?:
id: "testfluids",
name: "Test Fluids",
version: "1.0.0",
...(shared_script && { scripts: { shared: "scripts/shared.ts" } }),
...(shared_script && { main: "scripts/shared.ts" }),
});
for (const [file, fluid] of Object.entries(fluids)) write(`fluids/${file}`, { format_version: 1, fluid });
if (shared_script) {
@@ -66,7 +66,7 @@ Deno.test("a fluid with a bad color fails loading", async () => {
// syrup is named after the tree in its data and has the color its data says, sap has no rules
const RULES = `
import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) {
export function shared(ctx: SharedContext) {
ctx.fluids.register("testfluids:syrup", {
name: (data: any) => data?.tree && ctx.items.name(data.tree) + " Syrup",
color: (data: any) => data?.color,
+5 -8
View File
@@ -31,7 +31,7 @@ import { collision_shape_at, covers_face, is_solid } from "@/common/block_shapes
import { tag_api } from "@/common/tags.ts";
import { get_state_value, set_state_value, shared_items_api } from "@/common/utils.ts";
import type { Face, SharedWorld } from "@/common/mod_api/shared.ts";
import { setup as setup_shared } from "@/mods/bworld/scripts/shared.ts";
import { shared as setup_shared } from "@/mods/bworld/scripts/shared.ts";
// the repo's own mods/, read once: reading and checking every mod's files is most of starting a game in a test. only
// mods/ is kept, since tests change the temporary folders they make between games
@@ -50,8 +50,7 @@ async function read_mod_sources(mods_dir: string): Promise<ServerModSource[]> {
const errors = mods.flatMap((mod) => mod.report.errors.map((e) => `${mod.id}: ${e}`));
if (errors.length) throw new Error(errors.join("\n"));
return load_order(mods).map((mod) => {
const scripts = (mod.manifest?.scripts ?? {}) as Record<string, string>;
const url = (path?: string) => path ? toFileUrl(resolve(mod.dir, path)).href : undefined;
const main = mod.manifest?.main as string | undefined;
return {
listing: {
id: mod.id,
@@ -63,9 +62,7 @@ async function read_mod_sources(mods_dir: string): Promise<ServerModSource[]> {
...(mod.manifest?.engine_access === true ? { engine_access: true } : {}),
},
data: mod_data(mod),
server_url: url(scripts.server),
worldgen_url: url(scripts.worldgen),
shared_url: url(scripts.shared),
url: main ? toFileUrl(resolve(mod.dir, main)).href : undefined,
};
});
}
@@ -284,7 +281,7 @@ export const GROUND_BLOCKS = "#bworld:raw_rocks";
export const ENGINE_TEXTURES = ["cubi:missing", ...Array.from({ length: 9 }, (_, i) => `cubi:break_${i}`)];
// registers a folder of mod sources the way a player gets them: packed, loaded by a server, which adds the blocks
// content scripts register, and the copies it serves loaded on the client
// content phases register, and the copies it serves loaded on the client
export async function load_as_player(sources: string) {
const folder = Deno.makeTempDirSync({ prefix: "bworld_player_mods_" });
try {
@@ -369,7 +366,7 @@ export function server_blocks(game: GameServer, area: Area) {
return blocks_in(area, (x, y, z) => [game.world.get_block_id(x, y, z), game.world.get_block_value(x, y, z) >>> 16]);
}
// a client: its copy of the area, and the bworld shared script's rules running on it the way client/mods.ts does
// a client: its copy of the area, and the bworld shared phase's rules running on it the way client/mods.ts does
export function client_of(game: GameServer, area: Area) {
const copy = new Map<string, [string, number]>();
for (const line of server_blocks(game, area)) {
+4 -4
View File
@@ -22,7 +22,7 @@ async function load(script: string) {
id: "testmod",
name: "Test",
version: "1.0.0",
scripts: { client: "scripts/client.ts" },
main: "scripts/client.ts",
}),
);
Deno.writeTextFileSync(`${dir}/testmod/scripts/client.ts`, script);
@@ -39,7 +39,7 @@ async function load(script: string) {
Deno.test("hud layers draw in order on the same space, and one that throws is removed", async () => {
await load(`
import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) {
export function client(ctx: ClientContext) {
ctx.hud.register("testmod:bar", { on_render(_g, hud) { hud.left_height += 10; } });
ctx.hud.register("testmod:broken", { on_render() { throw new Error("broken"); } });
const above = {
@@ -75,13 +75,13 @@ Deno.test("hud layers draw in order on the same space, and one that throws is re
Deno.test("hud layers are in the mod's namespace, one to an id", async () => {
const layer = `{ on_render() {} }`;
await assertRejects(
() => load(`export function setup(ctx) { ctx.hud.register("bworld:hotbar", ${layer}); }`),
() => load(`export function client(ctx) { ctx.hud.register("bworld:hotbar", ${layer}); }`),
Error,
`must be in the namespace "testmod"`,
);
await assertRejects(
() =>
load(`export function setup(ctx) {
load(`export function client(ctx) {
ctx.hud.register("testmod:bar", ${layer});
ctx.hud.register("testmod:bar", ${layer});
}`),
+3 -3
View File
@@ -12,7 +12,7 @@ import { sell_value } from "@/common/inventory.ts";
import { block_visuals, Visuals } from "@/client/rendering/visuals.ts";
import { AssetManager } from "@/client/assets.ts";
import { fluid_rules, set_fluid_rules } from "@/client/fluid_rules.ts";
import { setup as setup_client } from "@/mods/bworld/scripts/client.ts";
import { client as setup_client } from "@/mods/bworld/scripts/client.ts";
import { JUICE_VALUE, type JuiceableParams, WINE_VALUE } from "@/mods/bworld/scripts/shared.ts";
import type { FermentableRecipe } from "@/mods/bworld/scripts/fermenting.ts";
import { copy_dir, stone_floor, test_game } from "./helpers.ts";
@@ -277,14 +277,14 @@ Deno.test("a broken bworld:fermentable recipe stops the server from starting", a
}
});
// a juicer at 1 100 1 drawn by bworld's client script, and a way to set a field of its client data. its fluids have the
// a juicer at 1 100 1 drawn by bworld's client phase, and a way to set a field of its client data. its fluids have the
// server's rules, the same as a client's
async function drawn_juicer() {
const { game } = await setup();
AssetManager.instance.assets["cubi:textures_info"] = {};
const client_rules = fluid_rules;
set_fluid_rules(game.mods.fluid_rules);
// bworld's client script, with only what it needs for its visuals
// bworld's client phase, with only what it needs for its visuals
const made = new Map<string, (block: VisualBlock, instances: Instances) => Visual>();
setup_client({
ui: { register_menu_screen() {}, add_item_tooltip() {} },
+2 -2
View File
@@ -187,7 +187,7 @@ function loot_mod(dir: string) {
name: "Test Loot",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
});
for (const id of ["gem", "charm"]) {
write(`items/${id}.json`, { format_version: 1, item: { id: `testloot:${id}`, texture: `testloot:${id}` } });
@@ -233,7 +233,7 @@ function loot_mod(dir: string) {
Deno.writeTextFileSync(
`${mod}/scripts/server.ts`,
`import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
ctx.loot.register_condition("testloot:high", (_params, context) => (context.position?.y ?? 0) > 120);
ctx.loot.register_function("testloot:double", (item) => ({ ...item, count: item.count * 2 }));
ctx.loot.modify("testloot:chests/treasure", (items) => { items.push({ id: "testloot:charm", count: 1 }); });
+3 -3
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what machines do to the world through server scripts: read which way water flows, find items lying around and
// what machines do to the world through server phases: read which way water flows, find items lying around and
// change them, push things, break blocks over time, and use items on blocks like a player would
import { assert, assertEquals, assertThrows } from "@std/assert";
import type { ServerContext } from "cubi/server";
@@ -11,7 +11,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts";
// hands the test its context, and has a block that says who right clicked it and an item that gives a stick when used
const SERVER_SCRIPT = `
import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
(globalThis as any).machines_ctx = ctx;
ctx.components.register_block("testmod:button", {
on_interact(block, _params, player) {
@@ -39,7 +39,7 @@ async function setup() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
});
write("blocks/button.json", {
format_version: 1,
+3 -4
View File
@@ -32,14 +32,14 @@ Deno.test("changing a mod's config only changes settings it has, to the same kin
]);
});
Deno.test("a server script reads its mod's config, with the changes a test makes", async () => {
Deno.test("a mod's server phase reads its mod's config, with the changes a test makes", async () => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_config_" });
copy_dir("mods/bworld", `${dir}/bworld`);
create_mod("copper_tools", "Copper Tools", dir);
Deno.writeTextFileSync(
`${dir}/copper_tools/scripts/server.ts`,
`${dir}/copper_tools/scripts/main.ts`,
`import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
ctx.components.register_block("copper_tools:announce", {});
ctx.commands.register("settings", {
description: "Shows the settings",
@@ -94,7 +94,6 @@ Deno.test("a server changes a mod's settings with config/<mod id>.json, and play
write_mod({
manifest: { format_version: 1, id: "tiny", name: "Tiny", version: "1.0.0" },
data,
scripts: {},
textures: new Map(),
}),
);
+6 -6
View File
@@ -146,12 +146,12 @@ Deno.test("the template's worldgen feature places boulders, the same way every t
}
assert(boulders >= 1 && boulders <= 8, `${boulders} of 20 chunks got a boulder, expected about 2`);
// loading the script again (like a client does) gives the same terrain
// loading the script again (like a worldgen worker does) gives the same terrain
const again = await load_worldgen({
mods: ["bworld", "copper_tools"],
scripts: ["bworld", "copper_tools"].map((mod) => ({
mod,
url: new URL(`file://${Deno.realPathSync(dir)}/${mod}/scripts/worldgen.ts`).href,
url: new URL(`file://${Deno.realPathSync(dir)}/${mod}/scripts/main.ts`).href,
})),
ores: worldgen.ores,
generator: "bworld:overworld",
@@ -202,11 +202,11 @@ Deno.test("mod ores generate into the block they replace", async () => {
Deno.test("mod storage and block data are saved with the world", async () => {
const dir = mods_with_template();
// a server script that uses storage and block data
// a mod's server phase that uses storage and block data
Deno.writeTextFileSync(
`${dir}/copper_tools/scripts/server.ts`,
`${dir}/copper_tools/scripts/main.ts`,
`import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
ctx.components.register_block("copper_tools:announce", {
on_create(block) { block.data = { placed_at: ctx.system.current_tick }; },
on_interact(block, _params, player) {
@@ -237,7 +237,7 @@ export function setup(ctx: ServerContext) {
Deno.test("broken mods stop the game from starting", async () => {
const dir = mods_with_template();
// the block uses a component the script no longer registers
Deno.writeTextFileSync(`${dir}/copper_tools/scripts/server.ts`, "export function setup() {}\n");
Deno.writeTextFileSync(`${dir}/copper_tools/scripts/main.ts`, "export function server() {}\n");
let error = "";
try {
await test_game(dir);
+15 -16
View File
@@ -32,7 +32,7 @@ async function packed_mods() {
return { sources, folder, mods };
}
Deno.test("packing a mod keeps its data, scripts, textures and credits, and gives the same bytes every time", async () => {
Deno.test("packing a mod keeps its data, script, 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.cubi`);
@@ -43,13 +43,12 @@ Deno.test("packing a mod keeps its data, scripts, textures and credits, and give
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());
assertEquals(Object.keys(mod.scripts).sort(), ["client", "server", "worldgen"]);
assertStringIncludes(mod.scripts.server!, "setup");
assertStringIncludes(mod.script!, "function server");
assert(mod.credits);
const bworld = read_mod(Deno.readFileSync(`${folder}/bworld.cubi`), "bworld.cubi");
assertEquals(bworld.data.blocks.length, [...Deno.readDirSync("mods/bworld/blocks")].length);
assertEquals(Object.keys(bworld.scripts), ["server", "client", "worldgen", "shared", "content"]);
assert(bworld.script);
Deno.removeSync(sources, { recursive: true });
Deno.removeSync(folder, { recursive: true });
@@ -78,13 +77,13 @@ Deno.test("broken .cubi files are turned away, saying why", () => {
() =>
read_mod(
zip({
"manifest.json": text({ ...manifest, scripts: { server: "scripts/server.js" } }),
"manifest.json": text({ ...manifest, main: "script.js" }),
"data.json": text({}),
}),
"d.cubi",
),
Error,
"scripts.server scripts/server.js isn't in the file",
"main script.js isn't in the file",
);
// a texture bigger than MAX_TEXTURE_SIZE. only its header is read
const big = new Uint8Array(24);
@@ -109,7 +108,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 server scripts", async () => {
Deno.test("the server loads every .cubi in its folder, dependencies first, and players get them without the terrain", 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"]);
@@ -119,9 +118,11 @@ Deno.test("the server loads every .cubi in its folder, dependencies first, and p
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_mod(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.mod.scripts.shared, "players run the shared rules too");
assertEquals(
copy.script,
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: [] };
@@ -131,7 +132,6 @@ Deno.test("the server loads every .cubi in its folder, dependencies first, and p
assert(terrain.every((list) => list!.length > 0));
}
}
assert(mods[1].mod.scripts.server, "the server still has it");
// the same mod twice, and a mod whose dependency isn't there
Deno.copyFileSync(`${folder}/copper_tools.cubi`, `${folder}/copper_tools_again.cubi`);
@@ -173,7 +173,7 @@ Deno.test("the host serves each mod's player copy by its hash, and a game made f
}
assertEquals((await host.handle(new Request("http://localhost/mods/nope.cubi"))).status, 404);
// the game worker loaded both mods, including the template's server script, and saves
// the game worker loaded both mods, including the template's server phase, and saves
await host.shutdown();
const saved = JSON.parse(Deno.readTextFileSync(`${world}/level.json`));
assertEquals(saved.seed, "mod-seed");
@@ -193,7 +193,7 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => {
id: "project",
name: "Project",
version: "1.0.0",
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
}),
);
// only the mod's own import map knows "lib/"
@@ -201,13 +201,13 @@ Deno.test("a mod with its own deno.json is bundled with it", async () => {
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`,
`import { GREETING } from "lib/greeting.ts";\n// deno-lint-ignore no-explicit-any\nexport function server(ctx: any) {\n\tctx.log(GREETING);\n}\n`,
);
const project = (await load_and_check(sources)).find((m) => m.id === "project")!;
assertEquals(project.report.errors, []);
const packed = read_mod(await pack_mod(project), "project.cubi");
assertStringIncludes(packed.scripts.server!, "hello from a deno project");
assertStringIncludes(packed.script!, "hello from a deno project");
Deno.removeSync(sources, { recursive: true });
});
@@ -438,7 +438,6 @@ Deno.test("a mod with only data packs and reads", () => {
fluids: [],
tags: [],
},
scripts: {},
textures: new Map(),
};
assertEquals(read_mod(write_mod(mod), "tiny.cubi").manifest.id, "tiny");
+2 -2
View File
@@ -128,7 +128,7 @@ Deno.test("check-mods finds broken mods", async () => {
new DataView(huge.buffer).setUint32(20, 16);
Deno.writeFileSync(`${mod}/textures/huge.png`, huge);
// a script that doesn't typecheck
Deno.writeTextFileSync(`${mod}/scripts/client.ts`, "export function setup(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
const manifest = JSON.parse(Deno.readTextFileSync(`${mod}/manifest.json`));
manifest.dependencies = [{ id: "missing_mod", version: "1.0.0" }];
@@ -147,7 +147,7 @@ Deno.test("check-mods finds broken mods", async () => {
has(report.errors, `elements[0].faces can't have "up"`);
has(report.errors, `key needs "B", which pattern uses`);
has(report.errors, "textures/huge.png: is");
has(report.errors, "scripts don't typecheck");
has(report.errors, "its script doesn't typecheck");
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 }");
+7 -3
View File
@@ -12,7 +12,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
const at = ({ x, y, z }: { x: number; y: number; z: number }) => x + " " + y + " " + z;
ctx.components.register_block("testmod:watcher", {
@@ -57,7 +57,7 @@ export function setup(ctx: ServerContext) {
const SHARED_SCRIPT = `
import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) {
export function shared(ctx: SharedContext) {
// marks the watcher once anything beside it changes
ctx.components.register_block("testmod:watcher", {
on_neighbor_change(block) { ctx.world.set_state(block.x, block.y, block.z, "seen", 1); },
@@ -93,7 +93,7 @@ function test_mods() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
main: "scripts/main.ts",
});
const block = (name: string, states: unknown[] = []) =>
write(`blocks/${name}.json`, {
@@ -113,6 +113,10 @@ function test_mods() {
block("flipper", [{ name: "on", bits: 1, default: 0 }]);
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
Deno.writeTextFileSync(
`${mod}/scripts/main.ts`,
`export { server } from "./server.ts";\nexport { shared } from "./shared.ts";\n`,
);
return dir;
}
+7 -3
View File
@@ -8,7 +8,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
const log = (key: string, value: unknown = 1) => {
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
(all[key] ??= []).push(value);
@@ -41,7 +41,7 @@ export function setup(ctx: ServerContext) {
// a pillar placed upside down while sneaking, like a block whose placement reads sneaking
const SHARED_SCRIPT = `
import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) {
export function shared(ctx: SharedContext) {
ctx.components.register_block("testmod:pillar", {
state_for_placement(placement) { return { flipped: placement.sneaking ? 1 : 0 }; },
});
@@ -60,7 +60,7 @@ function test_mods() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts", shared: "scripts/shared.ts" },
main: "scripts/main.ts",
});
const block = (id: string, extra: Record<string, unknown>) => ({
format_version: 1,
@@ -82,6 +82,10 @@ function test_mods() {
write("items/bow.json", item("testmod:bow", { "testmod:bow": { ticks: 5 } }));
Deno.writeTextFileSync(`${mod}/scripts/server.ts`, SERVER_SCRIPT);
Deno.writeTextFileSync(`${mod}/scripts/shared.ts`, SHARED_SCRIPT);
Deno.writeTextFileSync(
`${mod}/scripts/main.ts`,
`export { server } from "./server.ts";\nexport { shared } from "./shared.ts";\n`,
);
return dir;
}
+1 -1
View File
@@ -189,7 +189,7 @@ Deno.test("a crab pot's recipes are what each bait catches in fresh and salt wat
});
Deno.test("each juiceable item has a juicing recipe that presses it into its own juice", async () => {
// registered by the base game's shared script, see mods/bworld/scripts/juicing.ts
// registered by the base game's shared phase, see mods/bworld/scripts/juicing.ts
const { game } = await test_game("mods");
const index = new RecipeIndex(client_ctx(game.recipes.all));
+2 -2
View File
@@ -9,7 +9,7 @@ import { copy_dir, stone_floor, test_game } from "./helpers.ts";
const SERVER_SCRIPT = `
import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
const log = (event: unknown[]) => ctx.storage.set("log", [...ctx.storage.get<unknown[]>("log") ?? [], event]);
ctx.components.register_block("testmod:clock", {
on_scheduled_tick(block) { log([block.x, ctx.system.current_tick]); },
@@ -54,7 +54,7 @@ function test_mods() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
});
const block = (name: string, states: unknown[] = []) =>
write(`blocks/${name}.json`, {
+13 -9
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// recipes a shared script registers with ctx.recipes.register: there on the server and every client alike, for their
// recipes the shared phase registers with ctx.recipes.register: there on the server and every client alike, for their
// scripts and the crafting grid, without being sent
import { assert, assertEquals, assertRejects } from "@std/assert";
import { EverythingRegistry } from "@/common/everything_registry.ts";
@@ -16,7 +16,7 @@ import { copy_dir, load_as_player, test_game } from "./helpers.ts";
// types, found by the item put in
const SHARED = `
import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) {
export function shared(ctx: SharedContext) {
for (const id of ctx.items.ids()) {
const sifts = ctx.items.components(id)["testrecipes:siftable"] as { into: string } | undefined;
if (sifts) ctx.recipes.register("testrecipes:sifting", { input: id, result: { id: sifts.into, count: 1 } });
@@ -32,9 +32,9 @@ const SHARED = `
}
`;
// what the server and client scripts see of them while they set up. the server's registers the siftable component
// what the server and client phases see of them while they run. the server's registers the siftable component
const SEEN = (side: string) => `
export function setup(ctx: any) {
export function ${side}(ctx: any) {
ctx.components?.register_item?.("testrecipes:siftable", {});
(globalThis as any).testrecipes_${side} = ctx.recipes.list("testrecipes:sifting");
(globalThis as any).testrecipes_${side}_parsed = {
@@ -59,7 +59,7 @@ function recipe_mod(shared_extra = "", recipes: Record<string, unknown> = {}) {
id: "testrecipes",
name: "Test Recipes",
version: "1.0.0",
scripts: { shared: "scripts/shared.ts", server: "scripts/server.ts", client: "scripts/client.ts" },
main: "scripts/main.ts",
});
const item = (id: string, components?: unknown) =>
write(`items/${id}.json`, {
@@ -72,6 +72,10 @@ function recipe_mod(shared_extra = "", recipes: Record<string, unknown> = {}) {
write("scripts/shared.ts", SHARED.replace("SHARED_EXTRA", shared_extra));
write("scripts/server.ts", SEEN("server"));
write("scripts/client.ts", SEEN("client"));
write(
"scripts/main.ts",
`export { shared } from "./shared.ts"; export { server } from "./server.ts"; export { client } from "./client.ts";`,
);
for (const [name, recipe] of Object.entries(recipes)) write(`recipes/${name}`, { format_version: 1, recipe });
return dir;
}
@@ -95,7 +99,7 @@ async function load_client(dir: string) {
await load_client_mods([listing], [packed]);
}
Deno.test("recipes a shared script registers are on the server and clients, for their scripts and crafting", async () => {
Deno.test("recipes a mod's shared phase registers are on the server and clients, for their scripts and crafting", async () => {
const dir = recipe_mod();
const t = await test_game(dir);
assertEquals(seen.testrecipes_server, SIFTING);
@@ -180,7 +184,7 @@ Deno.test("a mod can only register recipe types in its own namespace", async ()
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a shared script lists the recipes there are so far, from files and the scripts before it", async () => {
Deno.test("a mod's shared phase lists the recipes there are so far, from files and the scripts before it", async () => {
// a washing recipe for every sifting one, whatever made it
const dir = recipe_mod(
`for (const sifting of ctx.recipes.list("testrecipes:sifting")) {
@@ -200,7 +204,7 @@ Deno.test("a shared script lists the recipes there are so far, from files and th
assertEquals(washing as unknown, [{ id: "testrecipes:sand", count: 1 }, { id: "testrecipes:gravel", count: 1 }]);
});
Deno.test("a broken recipe from a shared script stops the mod loading, like a broken file", async () => {
Deno.test("a broken recipe from a mod's shared phase stops the mod loading, like a broken file", async () => {
const dir = recipe_mod(
`ctx.recipes.register("shaped", { pattern: ["#"], key: {}, result: { id: "testrecipes:sand", count: 1 } });`,
);
@@ -208,7 +212,7 @@ Deno.test("a broken recipe from a shared script stops the mod loading, like a br
Deno.removeSync(dir, { recursive: true });
});
Deno.test("recipes can only be registered while shared scripts set up", async () => {
Deno.test("recipes can only be registered while shared phases set up", async () => {
const dir = recipe_mod(
`(globalThis as any).testrecipes_late = () => ctx.recipes.register("testrecipes:sifting", {});`,
);
+2 -2
View File
@@ -10,7 +10,7 @@ import { copy_dir, test_game } from "./helpers.ts";
const SCRIPT = `
import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
(globalThis as any).season_test = { ctx, created: [] };
ctx.components.register_block("testmod:thermometer", {
on_create(block) {
@@ -42,7 +42,7 @@ function season_mods() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
}),
);
Deno.writeTextFileSync(
+2 -2
View File
@@ -8,7 +8,7 @@ import type { WorldSave } from "@/server/game/saves.ts";
// a mod that uses every part of the server api worth testing, and writes down what happened in its storage
const SERVER_SCRIPT = `
import type { BlockRef, ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
export function server(ctx: ServerContext) {
const log = (key: string, value: unknown = 1) => {
const all = ctx.storage.get<Record<string, unknown[]>>("log") ?? {};
(all[key] ??= []).push(value);
@@ -153,7 +153,7 @@ function test_mods() {
name: "Test",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { server: "scripts/server.ts" },
main: "scripts/server.ts",
}),
);
Deno.writeTextFileSync(
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// shared scripts' block rules run on clients too, so what a client shows the moment it places, breaks or right clicks
// shared phases' block rules run on clients too, so what a client shows the moment it places, breaks or right clicks
// a block is what the server ends up with
import { assertEquals } from "@std/assert";
import { AIR_ID } from "@/common/protocol.ts";
+1 -1
View File
@@ -224,6 +224,6 @@ Deno.test("tags survive packing into a .cubi", () => {
tags: [tag],
};
const manifest: ManifestJson = { format_version: 1, id: "x", name: "X", version: "1.0.0" };
const mod = read_mod(write_mod({ manifest, data, scripts: {}, textures: new Map() }), "x.cubi");
const mod = read_mod(write_mod({ manifest, data, textures: new Map() }), "x.cubi");
assertEquals(mod.data.tags, [tag]);
});
+6 -6
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// item tooltips: the game's lines, the ones client scripts add and where they go
// item tooltips: the game's lines, the ones client phases add and where they go
import { assertEquals } from "@std/assert";
import { item_tooltip } from "@/client/gui/tooltip.ts";
import { ItemStack } from "@/common/inventory.ts";
@@ -9,7 +9,7 @@ import { copy_dir, load_as_player } from "./helpers.ts";
const SNACK = "tips:snack";
// mods/bworld, then tips: a snack with food and lore that sells for 4, and a client script adding lines to its tooltip
// mods/bworld, then tips: a snack with food and lore that sells for 4, and a client phase adding lines to its tooltip
async function load(client_script: string) {
const dir = Deno.makeTempDirSync({ prefix: "bworld_tooltips_" });
copy_dir("mods/bworld", `${dir}/bworld`);
@@ -24,7 +24,7 @@ async function load(client_script: string) {
id: "tips",
name: "Tips",
version: "1.0.0",
scripts: { client: "scripts/client.ts" },
main: "scripts/client.ts",
}),
);
write(
@@ -49,10 +49,10 @@ async function load(client_script: string) {
return (id: string) => item_tooltip(new ItemStack(id)).map((line) => line.text);
}
Deno.test("a client script's lines show in item tooltips, and bworld's sell value goes after the food", async () => {
Deno.test("a mod's client phase's lines show in item tooltips, and bworld's sell value goes after the food", async () => {
const tooltip = await load(`
import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) {
export function client(ctx: ClientContext) {
ctx.ui.add_item_tooltip((item, lines) => lines.push({ text: "from tips: " + item.id }));
}
`);
@@ -63,7 +63,7 @@ Deno.test("a client script's lines show in item tooltips, and bworld's sell valu
Deno.test("tooltip lines go where their priority says, and ones with the same priority keep their order", async () => {
const tooltip = await load(`
import { type ClientContext, TOOLTIP_PRIORITY } from "cubi/client";
export function setup(ctx: ClientContext) {
export function client(ctx: ClientContext) {
ctx.ui.add_item_tooltip((item, lines) => {
if (item.id !== "${SNACK}") return;
lines.push({ text: "last", priority: TOOLTIP_PRIORITY.lore + 1 });
+7 -10
View File
@@ -24,7 +24,7 @@ function deep_mod() {
name: "Deep",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
scripts: { worldgen: "scripts/worldgen.ts", server: "scripts/server.ts" },
main: "scripts/main.ts",
});
write("worldgen/biomes/caves.json", {
format_version: 1,
@@ -49,21 +49,18 @@ function deep_mod() {
},
});
write(
"scripts/worldgen.ts",
`import type { WorldgenContext } from "cubi/worldgen";
export function setup(gen: WorldgenContext) {
"scripts/main.ts",
`import type { ServerContext } from "cubi/server";
import type { WorldgenContext } from "cubi/worldgen";
export function worldgen(gen: WorldgenContext) {
gen.register_feature("deep:look", (chunk) => {
if (chunk.x !== 0 || chunk.z !== 0) return;
const ground = chunk.height_at(8, 8);
(globalThis as any).deep_seen = [chunk.biome_at(8, ground, 8), chunk.biome_at(8, ground - 40, 8)];
chunk.set_biome(9, 201, 9, "deep:caves");
});
}`,
);
write(
"scripts/server.ts",
`import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) {
}
export function server(ctx: ServerContext) {
(globalThis as any).deep_ctx = ctx;
}`,
);
+5 -5
View File
@@ -28,7 +28,7 @@ const HALF = {
};
// testmod: a shaft with an axis state and a model of half of one, syrup, a jar drawn with the syrup in it, and maybe a
// client script
// client phase
function write_testmod(dir: string, client_script?: string) {
const mod = `${dir}/testmod`;
for (const folder of ["blocks", "models", "scripts", "fluids", "items"]) {
@@ -40,7 +40,7 @@ function write_testmod(dir: string, client_script?: string) {
id: "testmod",
name: "Test",
version: "1.0.0",
...(client_script && { scripts: { client: "scripts/client.ts" } }),
...(client_script && { main: "scripts/client.ts" }),
});
write("blocks/shaft.json", {
format_version: 1,
@@ -473,7 +473,7 @@ Deno.test({
},
});
Deno.test("client scripts register visuals during setup, for blocks that exist", async () => {
Deno.test("client phases register visuals during setup, for blocks that exist", async () => {
const load = async (script: string) => {
const dir = Deno.makeTempDirSync({ prefix: "bworld_visuals_" });
write_testmod(dir, script);
@@ -486,7 +486,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist",
};
await load(`
import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) {
export function client(ctx: ClientContext) {
ctx.render.register_visual("testmod:shaft", (_block, instances) => {
instances.rotating();
return {};
@@ -500,7 +500,7 @@ Deno.test("client scripts register visuals during setup, for blocks that exist",
() =>
load(`
import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) {
export function client(ctx: ClientContext) {
ctx.render.register_visual("testmod:gear", () => ({}));
}
`),
+1 -1
View File
@@ -20,7 +20,7 @@ Deno.test("a bundle, cloned like a message to a worker and loaded into an empty
EverythingRegistry.clear();
const loaded = await load_bundle(bundle);
assertEquals(loaded.block_ids, game_ids, "blocks are numbered like the game numbers them");
assert(loaded.setup.features.some((f) => f.id === "bworld:trees"), "bworld's worldgen script was loaded");
assert(loaded.setup.features.some((f) => f.id === "bworld:trees"), "bworld's worldgen phase was loaded");
const name = namer(loaded.block_ids);
for (const [x, z] of golden_chunks()) {
+1 -1
View File
@@ -16,7 +16,7 @@ const options = { sanitizeOps: false, sanitizeResources: false };
async function pool_for(seed: string, workers: number) {
const { game } = await test_game("mods", undefined, seed);
// tests load worldgen scripts from files, so the workers need to read them
// tests load worldgen phases from files, so the workers need to read them
const started = start_worldgen_workers(workers, { permissions: "inherit", on_restart: () => {} });
const pool = new WorldgenPool(started.ports as unknown as WorkerPort[], game.worldgen_bundle!);
const chunks = new Map<number, RawChunk>();