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
+4 -4
View File
@@ -7,9 +7,9 @@ install anything themselves.
The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your The base game is a mod too: `mods/bworld` is written against the same API as any other mod, so anything it does, your
mod can do, and it's the best place to look for examples. mod can do, and it's the best place to look for examples.
A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from A mod is mostly data: JSON files for blocks, items, recipes and entities, and PNG textures. Behavior comes from one
TypeScript scripts: a server script for game logic, a client script for what players see, and a worldgen script for TypeScript script, whose exports are its phases: `server` for game logic, `client` for what players see, and `worldgen`
terrain features. for terrain features.
```sh ```sh
deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod deno task new-mod copper_tools "Copper Tools" # a new mod in mods/copper_tools, from templates/mod
@@ -35,7 +35,7 @@ deno task build && deno task server # packs the mods and starts a se
- [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement - [Blocks](docs/modding/blocks/index.md): looks, mining, drops and placement
- [Block States](docs/modding/blocks/states.md): state bits, variants and facing - [Block States](docs/modding/blocks/states.md): state bits, variants and facing
- [Block Components](docs/modding/blocks/components.md): giving blocks behavior from a server script - [Block Components](docs/modding/blocks/components.md): giving blocks behavior from the server phase
- [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or - [Tile Data](docs/modding/blocks/tiledata.md): data kept for one block, the part clients see, and blocks that hold or
show items show items
- [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a - [Visuals](docs/modding/blocks/visuals.md): blocks drawn with code, like a shaft that turns or the items and fluid in a
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// what engine access mods get as engine.client, in client scripts. see docs/modding/misc/engine.md // what engine access mods get as engine.client, in client phases. see docs/modding/misc/engine.md
import { Client } from "./client.ts"; import { Client } from "./client.ts";
import { Entity } from "./entity/entity.ts"; import { Entity } from "./entity/entity.ts";
import { LocalPlayer } from "./entity/local_player.ts"; import { LocalPlayer } from "./entity/local_player.ts";
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the fluids' rules from the mods' shared scripts on this client, the same as the server's (see common/fluids.ts), for // the fluids' rules from the mods' shared phases on this client, the same as the server's (see common/fluids.ts), for
// drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods // drawing fluids and naming them in tooltips. its own module so those don't import client/mods.ts, which loads the mods
// and makes it again for each server's // and makes it again for each server's
import { FluidRules } from "@/common/fluids.ts"; import { FluidRules } from "@/common/fluids.ts";
+2 -2
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// screens mods' client scripts make, see docs/modding/gui/index.md: the screens of their menus, and screens with no // screens mods' client phases make, see docs/modding/gui/index.md: the screens of their menus, and screens with no
// menu. a mod's screen that throws is closed, with the error in the console // menu. a mod's screen that throws is closed, with the error in the console
import { TICK_DELTA } from "@/common/constants.ts"; import { TICK_DELTA } from "@/common/constants.ts";
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "@/common/mod_api/client.ts"; import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "@/common/mod_api/client.ts";
@@ -98,7 +98,7 @@ export class GuiModMenuScreen extends GuiMenuScreen {
} }
} }
// a screen with no menu, opened by a client script // a screen with no menu, opened by a mod's client phase
export class GuiModScreen extends GuiScreen { export class GuiModScreen extends GuiScreen {
#mod: string; #mod: string;
#screen: Screen; #screen: Screen;
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer. // the immediate mode drawing mods' client phases get (Graphics in common/mod_api/client.ts), on top of the renderer.
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas // one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
// pixels each // pixels each
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
+1 -1
View File
@@ -31,7 +31,7 @@ const ICON_GAP = 4;
// from the mouse, so the cursor doesn't cover it // from the mouse, so the cursor doesn't cover it
const OFFSET = 16; const OFFSET = 16;
// what client scripts add to every item's tooltip, in load order, see ctx.ui.add_item_tooltip. client/mods.ts fills it, // what client phases add to every item's tooltip, in load order, see ctx.ui.add_item_tooltip. client/mods.ts fills it,
// each wrapped so one throwing is logged under its mod // each wrapped so one throwing is logged under its mod
export const item_tooltips: ((item: ApiItemStack, lines: TooltipLine[]) => void)[] = []; export const item_tooltips: ((item: ApiItemStack, lines: TooltipLine[]) => void)[] = [];
+24 -33
View File
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// loads the mods the server lists: downloads their .cubi files, registers their data, then runs their client scripts. // loads the mods the server lists: downloads their .cubi files, registers their data, then runs their scripts' shared
// see docs/modding/networking/index.md // and client phases. see docs/modding/networking/index.md
import { AIR } from "@/common/constants.ts"; import { AIR } from "@/common/constants.ts";
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import type { import type {
@@ -19,9 +19,11 @@ import {
check_recipe_types, check_recipe_types,
ModListing, ModListing,
ModLoadError, ModLoadError,
type Phase,
recipe_lookup, recipe_lookup,
RecipeBook, RecipeBook,
register_mod_data, register_mod_data,
run_phase,
shared_recipes_api, shared_recipes_api,
} from "@/common/mod_loader.ts"; } from "@/common/mod_loader.ts";
import { type Mod, read_mod } from "@/common/mod.ts"; import { type Mod, read_mod } from "@/common/mod.ts";
@@ -37,7 +39,7 @@ import type { Client } from "./client.ts";
import { code_url, fetch_verified } from "./handshake.ts"; import { code_url, fetch_verified } from "./handshake.ts";
import { GuiModScreen } from "./gui/gui_mod_screens.ts"; import { GuiModScreen } from "./gui/gui_mod_screens.ts";
import { item_tooltips } from "./gui/tooltip.ts"; import { item_tooltips } from "./gui/tooltip.ts";
import { clear_hooks, expose_engine, loading_mod } from "@/common/hooks.ts"; import { clear_hooks, expose_engine } from "@/common/hooks.ts";
import { common_engine } from "@/common/engine_modules.ts"; import { common_engine } from "@/common/engine_modules.ts";
import { client_engine } from "./engine_modules.ts"; import { client_engine } from "./engine_modules.ts";
import { block_visuals } from "./rendering/visuals.ts"; import { block_visuals } from "./rendering/visuals.ts";
@@ -130,11 +132,11 @@ const rules_world: SharedWorld = {
}, },
}; };
// what the mods' shared scripts registered, run to guess ahead of the server, see common/block_rules.ts // what the mods' shared phases registered, run to guess ahead of the server, see common/block_rules.ts
export let block_rules = new BlockRules(run_mod, rules_world.get_block); export let block_rules = new BlockRules(run_mod, rules_world.get_block);
// whether shared scripts are being set up, the only time they can register rules // whether shared phases are being set up, the only time they can register rules
let rules_setup = false; let rules_setup = false;
// whether client scripts are being set up, the only time they can register visuals, since chunk workers are told // whether client phases are being set up, the only time they can register visuals, since chunk workers are told
// which blocks have them when the level starts // which blocks have them when the level starts
let client_setup = false; let client_setup = false;
@@ -186,7 +188,7 @@ export async function download_mods(listings: ModListing[], base: URL): Promise<
})); }));
} }
// registers the mods' data and runs their client scripts, in the order the server listed them // registers the mods' data and runs their scripts' shared and client phases, in the order the server listed them
export async function load_client_mods(listings: ModListing[], mods: Mod[]) { export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
for (const [i, mod] of mods.entries()) { for (const [i, mod] of mods.entries()) {
if (mod.credits) { if (mod.credits) {
@@ -209,39 +211,28 @@ export async function load_client_mods(listings: ModListing[], mods: Mod[]) {
// for engine access mods. the last server's hooks go first // for engine access mods. the last server's hooks go first
clear_hooks(); clear_hooks();
expose_engine({ common: common_engine(), client: client_engine() }); expose_engine({ common: common_engine(), client: client_engine() });
const as_mod = (mod: Mod, fn: () => Promise<void>) =>
loading_mod(mod.manifest.id, mod.manifest.engine_access ?? false, fn);
// every mod's shared rules first, so client scripts can count on any mod's being there // one url for each mod's script, so its phases share one module
const urls = mods.map((mod) => mod.script === undefined ? undefined : script_url(mod.script));
const run = async (phase: Phase, context: (i: number) => unknown) => {
for (const [i, mod] of mods.entries()) {
const url = urls[i];
if (url === undefined) continue;
const as = { id: mod.manifest.id, engine_access: mod.manifest.engine_access };
await run_phase(as, url, phase, () => context(i));
}
};
// every mod's shared rules first, so client phases can count on any mod's being there
block_rules = new BlockRules(run_mod, rules_world.get_block); block_rules = new BlockRules(run_mod, rules_world.get_block);
set_fluid_rules(new FluidRules(run_mod)); set_fluid_rules(new FluidRules(run_mod));
rules_setup = true; rules_setup = true;
for (const [i, mod] of mods.entries()) { await run("shared", (i) => shared_context(listings[i]));
const code = mod.scripts.shared;
if (!code) continue;
await as_mod(mod, async () => {
const module = await import(script_url(code));
if (typeof module.setup !== "function") {
throw new ModLoadError(mod.manifest.id, "the shared script doesn't export a setup function");
}
await module.setup(shared_context(listings[i]));
});
}
rules_setup = false; rules_setup = false;
check_recipe_types(recipe_book); check_recipe_types(recipe_book);
client_setup = true; client_setup = true;
for (const [i, mod] of mods.entries()) { await run("client", (i) => client_context(listings[i]));
const code = mod.scripts.client;
if (!code) continue;
await as_mod(mod, async () => {
const module = await import(script_url(code));
if (typeof module.setup !== "function") {
throw new ModLoadError(mod.manifest.id, "the client script doesn't export a setup function");
}
await module.setup(client_context(listings[i]));
});
}
client_setup = false; client_setup = false;
} }
@@ -249,7 +240,7 @@ function script_url(code: string) {
return code_url(new TextEncoder().encode(code)); return code_url(new TextEncoder().encode(code));
} }
// ctx.blocks, the same in shared and client scripts // ctx.blocks, the same in shared and client phases
function blocks_api(mod: string): SharedContext["blocks"] { function blocks_api(mod: string): SharedContext["blocks"] {
return { return {
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined, exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the block rules shared scripts register (see BlockRules in mod_api/shared.ts), run the same way on the server and on // the block rules shared phases register (see BlockRules in mod_api/shared.ts), run the same way on the server and on
// clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own // clients: what states a placed block gets, and how blocks change with the blocks beside them. each side has its own
// BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with // BlockRules, with its own world: the server's is the real one, a client's is what it shows and guesses ahead with
import type { import type {
+18 -10
View File
@@ -1,33 +1,42 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// runs a mod's content script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the server on // runs the content phase of a mod's script, see common/mod_api/content.ts. check-mods runs it on the mod's folder, the
// its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to the mod's // server on its .cubi in a worker without permissions (server/content_worker.ts), and both add what it registers to
// data before anything else reads it // the mod's data before anything else reads it
import { type BlockJson, validate_block } from "./mod_data.ts"; import { type BlockJson, validate_block } from "./mod_data.ts";
import type { ContentContext } from "./mod_api/content.ts"; import type { ContentContext } from "./mod_api/content.ts";
import { ModLoadError, run_phase } from "./mod_loader.ts";
import { expose_engine } from "./hooks.ts";
import { common_engine } from "./engine_modules.ts";
export interface ContentScript { export interface ContentScript {
mod: string; mod: string;
version: string; version: string;
engine_access?: boolean;
// importable url of the script // importable url of the script
url: string; url: string;
} }
// a .cubi's bundled content script, what server/content_worker.ts is sent // a .cubi's bundled script, what server/content_worker.ts is sent
export interface ContentScriptCode { export interface ContentScriptCode {
mod: string; mod: string;
version: string; version: string;
engine_access?: boolean;
code: string; code: string;
} }
// what a content script registered, in order, and what was wrong. with problems the mod doesn't load // what a content phase registered, in order, and what was wrong. with problems the mod doesn't load
export interface RegisteredContent { export interface RegisteredContent {
blocks: BlockJson[]; blocks: BlockJson[];
problems: string[]; problems: string[];
} }
export async function run_content_script({ mod, version, url }: ContentScript): Promise<RegisteredContent> { export async function run_content_script(
{ mod, version, engine_access, url }: ContentScript,
): Promise<RegisteredContent> {
// the whole script loads here, and one with engine access can import cubi/engine. only engine.common is here
expose_engine({ common: common_engine() });
const blocks: BlockJson[] = []; const blocks: BlockJson[] = [];
let setting_up = true; let setting_up = true;
const ctx: ContentContext = { const ctx: ContentContext = {
@@ -48,12 +57,11 @@ export async function run_content_script({ mod, version, url }: ContentScript):
}, },
}; };
try { try {
const module = await import(url); await run_phase({ id: mod, engine_access }, url, "content", () => ctx);
if (typeof module.setup !== "function") throw new Error("the content script doesn't export a setup function");
await module.setup(ctx);
return { blocks, problems: [] }; return { blocks, problems: [] };
} catch (e) { } catch (e) {
return { blocks, problems: [e instanceof Error ? e.message : String(e)] }; const problem = e instanceof ModLoadError ? e.problem : e instanceof Error ? e.message : String(e);
return { blocks, problems: [problem] };
} finally { } finally {
setting_up = false; setting_up = false;
} }
+1 -1
View File
@@ -170,7 +170,7 @@ export interface BlockRegistry {
place_in?: string[]; place_in?: string[];
// custom components from mods and their params, the server runs them // custom components from mods and their params, the server runs them
components?: Record<string, unknown>; components?: Record<string, unknown>;
// draws the item a server script gives it (ServerWorld.set_block_item) on top of it, like the // draws the item a mod's server phase gives it (ServerWorld.set_block_item) on top of it, like the
// cutting board. surface is the height in pixels it lies on. turned with the variant's y // cutting board. surface is the height in pixels it lies on. turned with the variant's y
item_display?: { surface: number }; item_display?: { surface: number };
// a fluid like water, drawn like luanti's: its top slopes down towards where it flows. see FluidProperties // a fluid like water, drawn like luanti's: its top slopes down towards where it flows. see FluidProperties
+2 -2
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared scripts give them, which name, // fluids with their data (see FluidVariant in mod_api/shared.ts) and the rules shared phases give them, which name,
// color and value a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips // color and value a fluid by its data. each side has its own FluidRules from the same scripts, so the server's tooltips
// and a client's drawing agree // and a client's drawing agree
import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts"; import type { FluidApi, FluidRules as Rules, FluidVariant } from "./mod_api/shared.ts";
@@ -44,7 +44,7 @@ export class FluidRules {
return this.#ask(fluid, "sell_value", "a number of 0 or more", valid) ?? json.base_sell_value; return this.#ask(fluid, "sell_value", "a number of 0 or more", valid) ?? json.base_sell_value;
} }
// ctx.fluids for server and client scripts // ctx.fluids for server and client phases
api(): FluidApi { api(): FluidApi {
return { return {
ids: () => EverythingRegistry.entries("fluids").map(([id]) => id), ids: () => EverythingRegistry.entries("fluids").map(([id]) => id),
+1 -1
View File
@@ -12,7 +12,7 @@ export interface ItemData {
id: string; id: string;
count: number; count: number;
data?: unknown; data?: unknown;
// what server scripts say about it (get_lore), only sent to players, never saved // what server phases say about it (get_lore), only sent to players, never saved
lore?: string; lore?: string;
} }
+1 -1
View File
@@ -4,7 +4,7 @@
// loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table // loot tables, like minecraft's: what something gives when it's broken, killed, fished or opened, as data. a table
// has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions // has pools, each rolled some number of times, each roll picking one of the pool's entries by weight. conditions
// decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own // decide whether a table, pool or entry counts, functions change the items it gives. mods can add their own
// conditions and functions (ctx.loot in server scripts), which are ids in their namespace. // conditions and functions (ctx.loot in server phases), which are ids in their namespace.
// see docs/modding/resources/loot_tables.md // see docs/modding/resources/loot_tables.md
import * as z from "zod"; import * as z from "zod";
import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts"; import { EverythingRegistry, type ItemRegistry } from "./everything_registry.ts";
+19 -35
View File
@@ -59,14 +59,11 @@ const MAX_UNZIPPED_BYTES = 64 * 1024 * 1024;
// written into every entry, so packing the same mod twice gives the same bytes and the same hash // written into every entry, so packing the same mod twice gives the same bytes and the same hash
const FIXED_TIME = new Date(Date.UTC(2020, 0, 1)); const FIXED_TIME = new Date(Date.UTC(2020, 0, 1));
export type ScriptSide = "server" | "client" | "worldgen" | "shared" | "content";
export const SCRIPT_SIDES: ScriptSide[] = ["server", "client", "worldgen", "shared", "content"];
export interface Mod { export interface Mod {
manifest: ManifestJson; manifest: ManifestJson;
data: ModData; data: ModData;
// bundled javascript, one module per side // its script bundled into one javascript module, which every side runs the phases of, see run_phase
scripts: Partial<Record<ScriptSide, string>>; script?: string;
// png bytes by texture id, like copper_tools:copper_block // png bytes by texture id, like copper_tools:copper_block
textures: Map<string, Uint8Array>; textures: Map<string, Uint8Array>;
// the .json of the textures that have one, like animated ones, by texture id // the .json of the textures that have one, like animated ones, by texture id
@@ -82,27 +79,24 @@ export class ModError extends Error {
} }
// the zip's layout: // the zip's layout:
// manifest.json the mod's manifest, with "scripts" 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 and biome, and the mod's config
// scripts/<side>.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
// credits.md // credits.md
export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> { export function write_mod(mod: Mod): Uint8Array<ArrayBuffer> {
const text = (value: string) => new TextEncoder().encode(value); const text = (value: string) => new TextEncoder().encode(value);
const manifest: ManifestJson = { ...mod.manifest, scripts: {} }; const manifest: ManifestJson = { ...mod.manifest };
delete manifest.main;
delete manifest.credits; delete manifest.credits;
const files: Record<string, Uint8Array> = {}; const files: Record<string, Uint8Array> = {};
for (const side of SCRIPT_SIDES) { if (mod.script !== undefined) {
const code = mod.scripts[side]; files["script.js"] = text(mod.script);
if (code !== undefined) { manifest.main = "script.js";
files[`scripts/${side}.js`] = text(code);
manifest.scripts![side] = `scripts/${side}.js`;
}
} }
if (Object.keys(manifest.scripts!).length === 0) delete manifest.scripts;
if (mod.credits !== undefined) { if (mod.credits !== undefined) {
files["credits.md"] = text(mod.credits); files["credits.md"] = text(mod.credits);
manifest.credits = "credits.md"; manifest.credits = "credits.md";
@@ -233,18 +227,13 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
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`);
} }
const scripts: Mod["scripts"] = {}; const script = manifest.main === undefined ? undefined : text(manifest.main);
for (const [side, path] of Object.entries(manifest.scripts ?? {})) { if (manifest.main !== undefined && script === undefined) {
const code = text(path); problems.push(`manifest.json: main ${manifest.main} isn't in the file`);
if (!SCRIPT_SIDES.includes(side as ScriptSide) || code === undefined) {
problems.push(`manifest.json: scripts.${side} ${path} isn't in the file`);
} else {
scripts[side as ScriptSide] = code;
}
} }
// what the cubi/engine shim reads, so it's in the bundle of every script that imports it // what the cubi/engine shim reads, so it's in the bundle of a script that imports it
if (!manifest.engine_access && Object.values(scripts).some((code) => code.includes(ENGINE_GLOBAL))) { if (!manifest.engine_access && script?.includes(ENGINE_GLOBAL)) {
problems.push(`a script uses cubi/engine, which needs "engine_access": true in manifest.json`); problems.push(`its script uses cubi/engine, which needs "engine_access": true in manifest.json`);
} }
const credits = manifest.credits === undefined ? undefined : text(manifest.credits); const credits = manifest.credits === undefined ? undefined : text(manifest.credits);
if (manifest.credits !== undefined && credits === undefined) { if (manifest.credits !== undefined && credits === undefined) {
@@ -293,17 +282,12 @@ export function read_mod(bytes: Uint8Array, file: string): Mod {
} }
if (problems.length > 0) throw new ModError(file, problems); if (problems.length > 0) throw new ModError(file, problems);
return { manifest, data, scripts, textures, texture_json, credits }; return { manifest, data, script, textures, texture_json, credits };
} }
// the same mod without its server and worldgen scripts, the terrain's data and its config, what players get. the // the same mod without the terrain's data and its config, what players get. the server sends them the world. its
// server sends them the world // 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 scripts = { ...mod.scripts };
delete scripts.server;
delete scripts.worldgen;
// players get what it registered in data, see common/mod_api/content.ts
delete scripts.content;
const { const {
noises: _n, noises: _n,
density_functions: _d, density_functions: _d,
@@ -314,7 +298,7 @@ export function client_copy(mod: Mod): Mod {
config: _c, config: _c,
...data ...data
} = mod.data; } = mod.data;
return { ...mod, scripts, data }; return { ...mod, data };
} }
function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] { function checked(list: unknown, name: string, validate: (json: unknown) => string[], problems: string[]): unknown[] {
+4 -4
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// what client scripts get, see docs/modding/gui/index.md // what client phases get, see docs/modding/gui/index.md
import type { import type {
FluidApi, FluidApi,
FluidVariant, FluidVariant,
@@ -66,7 +66,7 @@ export interface ClientContext {
// read only, what this client sees // read only, what this client sees
world: { world: {
get_block(x: number, y: number, z: number): Id | undefined; get_block(x: number, y: number, z: number): Id | undefined;
// a field of the block's client data, what server scripts set with BlockRef.set_client_data, a copy. // a field of the block's client data, what server phases set with BlockRef.set_client_data, a copy.
// undefined when it isn't set or the chunk isn't loaded // undefined when it isn't set or the chunk isn't loaded
get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined; get_client_data<T>(x: number, y: number, z: number, field: string): T | undefined;
// the biome at a block and its season, like the server's. undefined when the chunk isn't loaded // the biome at a block and its season, like the server's. undefined when the chunk isn't loaded
@@ -115,7 +115,7 @@ export interface ClientContext {
table(id: Id): LootTableJson | undefined; table(id: Id): LootTableJson | undefined;
}; };
// every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies. // every recipe as its json (see docs/modding/resources/recipes.md), including mods' own types, in load order. copies.
// find and all read the recipes of types shared scripts registered // find and all read the recipes of types shared phases registered
recipes: { recipes: {
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
list(type?: Id): any[]; list(type?: Id): any[];
@@ -376,7 +376,7 @@ export interface HudRegistry {
// a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's // a layer, drawn every frame in the order they're registered, mods in load order, like RegisterGuiLayersEvent's
// registerAboveAll. only during setup. one that throws is removed, with the error in the console // registerAboveAll. only during setup. one that throws is removed, with the error in the console
register(id: Id, layer: HudLayer): void; register(id: Id, layer: HudLayer): void;
// a server script sent an overlay message (MessageOptions.overlay), for a layer to show // a mod's server phase sent an overlay message (MessageOptions.overlay), for a layer to show
on_overlay_message(fn: (text: string) => void): void; on_overlay_message(fn: (text: string) => void): void;
} }
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// content scripts: blocks made in code, for content that's easier to generate than to write out file by file, like // content phases: blocks made in code, for content that's easier to generate than to write out file by file, like
// every block of every kind of rock. the server runs them while it loads mods, before anything else reads their data, // every block of every kind of rock. the server runs them while it loads mods, before anything else reads their data,
// and what they register becomes part of the mod's data just like its files: checked the same way, sent to players // and what they register becomes part of the mod's data just like its files: checked the same way, sent to players
// with the rest, and generated by worldgen workers. see docs/modding/gettingstarted/modfiles.md // with the rest, and generated by worldgen workers. see docs/modding/gettingstarted/modfiles.md
+2 -2
View File
@@ -13,8 +13,8 @@ import type { client_engine } from "../../client/engine_modules.ts";
export type { HookHandlers } from "../hooks.ts"; export type { HookHandlers } from "../hooks.ts";
// the engine's live classes and objects. common is on every side, server only in server scripts, client only in // the engine's live classes and objects. common is on every side, server only in server phases, client only in
// client scripts // client phases
export interface Engine { export interface Engine {
common: ReturnType<typeof common_engine>; common: ReturnType<typeof common_engine>;
server: ReturnType<typeof server_engine>; server: ReturnType<typeof server_engine>;
+5 -5
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// what server scripts get, see docs/modding/ // what server phases get, see docs/modding/
import type { import type {
EventSignal, EventSignal,
Face, Face,
@@ -118,7 +118,7 @@ export interface BlockComponent<P = any> {
// particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none // particular when it's undefined, like neoforge's Capabilities.FluidHandler.BLOCK. undefined when it has none
// there. see ServerFluidApi.block_handler // there. see ServerFluidApi.block_handler
fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined; fluid_handler?(block: BlockRef, params: P, face: Face | undefined): FluidHandler | undefined;
// placing and neighbor rules are in shared scripts, see BlockRules in cubi/shared // placing and neighbor rules are in shared phases, see BlockRules in cubi/shared
} }
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -638,7 +638,7 @@ export interface TankHandlerOptions {
set(tanks: FluidStack[]): void; set(tanks: FluidStack[]): void;
} }
// ctx.fluids in server scripts: FluidApi, and fluid handlers // ctx.fluids in server phases: FluidApi, and fluid handlers
export interface ServerFluidApi extends FluidApi { export interface ServerFluidApi extends FluidApi {
// the handler of the block at x y z reached from face, from the first of its components with one, like // the handler of the block at x y z reached from face, from the first of its components with one, like
// level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there // level.getCapability(Capabilities.FluidHandler.BLOCK, pos, side). undefined for a block without one there
@@ -660,7 +660,7 @@ export interface ServerFluidApi extends FluidApi {
interact(player: Player, handler: FluidHandler): boolean; interact(player: Player, handler: FluidHandler): boolean;
} }
// find and all read the recipes of types shared scripts registered // find and all read the recipes of types shared phases registered
export interface RecipeApi extends RecipeLookup { export interface RecipeApi extends RecipeLookup {
// every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order // every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -817,7 +817,7 @@ export interface MenuRegistry {
// adds slots to every player's own inventory menu, always there while they play, like the curios slots next to the // adds slots to every player's own inventory menu, always there while they play, like the curios slots next to the
// inventory. build runs when each player joins. only during setup // inventory. build runs when each player joins. only during setup
extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void; extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void;
// like registering a MenuType. the client script gives it a screen with ctx.ui.register_menu_screen // like registering a MenuType. the client phase gives it a screen with ctx.ui.register_menu_screen
register<Args = undefined>( register<Args = undefined>(
id: Id, id: Id,
build: (menu: MenuBuilder, args: Args, player: Player) => void, build: (menu: MenuBuilder, args: Args, player: Player) => void,
+10 -10
View File
@@ -12,7 +12,7 @@ export type Season = "spring" | "summer" | "autumn" | "winter";
export interface ItemStack { export interface ItemStack {
readonly id: Id; readonly id: Id;
count: number; count: number;
// any json value, set by server scripts // any json value, set by server phases
data?: unknown; data?: unknown;
} }
@@ -30,7 +30,7 @@ export interface FluidStack {
amount: number; amount: number;
} }
// ctx.fluids in server and client scripts: every fluid any mod defines, the same on the server and every client // ctx.fluids in server and client phases: every fluid any mod defines, the same on the server and every client
export interface FluidApi { export interface FluidApi {
// every fluid's id, in load order, like ctx.items.ids. each without data, which a fluid like juice has many of // every fluid's id, in load order, like ctx.items.ids. each without data, which a fluid like juice has many of
ids(): Id[]; ids(): Id[];
@@ -44,7 +44,7 @@ export interface FluidApi {
same(a: FluidVariant, b: FluidVariant): boolean; same(a: FluidVariant, b: FluidVariant): boolean;
} }
// what a fluid's data makes it, registered by a shared script, like neoforge's FluidType.getDescription and // what a fluid's data makes it, registered by a mod's shared phase, like neoforge's FluidType.getDescription and
// FluidTintSource.colorAsStack without the amount. data is the variant's, undefined for none, and isn't to be changed. // FluidTintSource.colorAsStack without the amount. data is the variant's, undefined for none, and isn't to be changed.
// returning undefined keeps what the fluid's json says // returning undefined keeps what the fluid's json says
export interface FluidRules { export interface FluidRules {
@@ -127,7 +127,7 @@ export interface EventSignal<T> {
subscribe(handler: (event: T) => void): Unsubscribe; subscribe(handler: (event: T) => void): Unsubscribe;
} }
// shared scripts: block rules that run on the server and on every client, so a client places blocks the way the // shared phases: block rules that run on the server and on every client, so a client places blocks the way the
// server will, like minecraft's Block code that both sides run. see docs/modding/gettingstarted/modfiles.md // server will, like minecraft's Block code that both sides run. see docs/modding/gettingstarted/modfiles.md
export interface SharedContext { export interface SharedContext {
@@ -169,21 +169,21 @@ export interface SharedContext {
readonly recipes: { readonly recipes: {
// adds a recipe of type, like "shaped" or "bworld:cooking", as a file in the mod's recipes/ with that // adds a recipe of type, like "shaped" or "bworld:cooking", as a file in the mod's recipes/ with that
// json would, only during setup. for recipes made from other data, like one for every item with a component. // json would, only during setup. for recipes made from other data, like one for every item with a component.
// shared scripts run on the server and every client alike, so they all have it without it being sent. it's // shared phases run on the server and every client alike, so they all have it without it being sent. it's
// there for server and client scripts, which set up after, and it throws when it's broken like a file would // there for server and client phases, which set up after, and it throws when it's broken like a file would
// stop the mod loading // stop the mod loading
register(type: string, json: Record<string, unknown>): void; register(type: string, json: Record<string, unknown>): void;
// every recipe, or every one of type, as its json, copies, in load order: the mods' recipes/ files, and what the // every recipe, or every one of type, as its json, copies, in load order: the mods' recipes/ files, and what the
// shared scripts that set up before this one registered, which are the dependencies'. like the client's // shared phases that set up before this one registered, which are the dependencies'. like the client's
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
list(type?: string): any[]; list(type?: string): any[];
// a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register, // a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register,
// are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod // are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod
// registers stops its mod loading once every shared script has set up. see RecipeType // registers stops its mod loading once every shared phase has set up. see RecipeType
register_type<R, I>(type: Id, rules: RecipeType<R, I>): void; register_type<R, I>(type: Id, rules: RecipeType<R, I>): void;
} & RecipeLookup; } & RecipeLookup;
readonly components: { readonly components: {
// the rules of a block component, the same id the server script registers the rest of it under // the rules of a block component, the same id the server phase registers the rest of it under
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
register_block<P = any>(id: Id, rules: BlockRules<P>): void; register_block<P = any>(id: Id, rules: BlockRules<P>): void;
}; };
@@ -246,6 +246,6 @@ export interface BlockRules<P = any> {
on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void; on_neighbor_change?(block: SharedBlock, params: P, neighbor: SharedBlock): void;
// a player right clicks it, like minecraft's useWithoutItem: changes only its states and its neighbors', which // a player right clicks it, like minecraft's useWithoutItem: changes only its states and its neighbors', which
// the clicking client shows right away instead of waiting for the server. return true if it did something, then // the clicking client shows right away instead of waiting for the server. return true if it did something, then
// nothing is placed. the server runs the server script's on_interact too // nothing is placed. the server runs the server phase's on_interact too
on_interact?(block: SharedBlock, params: P, interaction: BlockInteraction): boolean | void; on_interact?(block: SharedBlock, params: P, interaction: BlockInteraction): boolean | void;
} }
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// what worldgen scripts get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic // what worldgen phases get, see docs/modding/worldgen/index.md. runs on the server and must be deterministic
import type { Id, Position } from "./shared.ts"; import type { Id, Position } from "./shared.ts";
export type { Id, Position } from "./shared.ts"; export type { Id, Position } from "./shared.ts";
+1 -1
View File
@@ -487,7 +487,7 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
// check-mods doesn't run scripts, the server checks these when it starts // check-mods doesn't run scripts, the server checks these when it starts
for (const custom of refs.custom) { for (const custom of refs.custom) {
check_namespace(file, custom); check_namespace(file, custom);
warnings.push(`${file}: ${custom} isn't built in, a worldgen script must register it`); warnings.push(`${file}: ${custom} isn't built in, a mod's worldgen phase must register it`);
} }
} }
for (const { file, json } of mod.biomes ?? []) { for (const { file, json } of mod.biomes ?? []) {
+2 -7
View File
@@ -82,13 +82,8 @@ const manifest_schema = (folder_name: string) =>
// imports cubi/engine to reach into the engine and hook its methods. needs game_version within one minor version // imports cubi/engine to reach into the engine and hook its methods. needs game_version within one minor version
engine_access: z.boolean().optional(), engine_access: z.boolean().optional(),
dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(), dependencies: z.array(z.object({ id: z.string(), version: z.string() })).optional(),
scripts: z.strictObject({ // the mod's script, whose exports are its phases, see common/mod_loader.ts's PHASES
server: z.string().optional(), main: z.string().optional(),
client: z.string().optional(),
worldgen: z.string().optional(),
shared: z.string().optional(),
content: z.string().optional(),
}).optional(),
credits: z.string().optional(), credits: z.string().optional(),
}).superRefine((manifest, ctx) => { }).superRefine((manifest, ctx) => {
const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined; const problem = manifest.engine_access ? engine_version_problem(manifest.game_version) : undefined;
+37 -6
View File
@@ -44,6 +44,7 @@ import type {
import type { FeatureJson } from "./worldgen/features.ts"; 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";
// 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 {
@@ -81,7 +82,7 @@ export interface ModData {
config?: Record<string, unknown>; config?: Record<string, unknown>;
} }
// a mod as the server lists it to clients, in load order: the .cubi players download, without its server script // a mod as the server lists it to clients, in load order: the .cubi players download, without its terrain or config
export interface ModListing { export interface ModListing {
id: string; id: string;
name: string; name: string;
@@ -100,7 +101,7 @@ export class RecipeBook {
// recipes of mods' own types, by type, and the mod with the first one of each, for the error when nothing registers it // recipes of mods' own types, by type, and the mod with the first one of each, for the error when nothing registers it
by_type = new Map<string, ModRecipeJson[]>(); by_type = new Map<string, ModRecipeJson[]>();
first_used_by = new Map<string, string>(); first_used_by = new Map<string, string>();
// the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type // the types shared phases registered, and their recipes as parse made them, see SharedContext.recipes.register_type
types = new Map<string, RecipeType<unknown, unknown>>(); types = new Map<string, RecipeType<unknown, unknown>>();
parsed = new Map<string, unknown[]>(); parsed = new Map<string, unknown[]>();
// every recipe as its json, in load order, for recipe viewers // every recipe as its json, in load order, for recipe viewers
@@ -111,12 +112,42 @@ export class RecipeBook {
} }
export class ModLoadError extends Error { export class ModLoadError extends Error {
// the message without the mod's id
readonly problem: string;
constructor(mod: string, message: string) { constructor(mod: string, message: string) {
super(`${mod}: ${message}`); super(`${mod}: ${message}`);
this.name = "ModLoadError"; this.name = "ModLoadError";
this.problem = message;
} }
} }
// what a mod's script can export, each called with its context where and when it runs: content on the server while
// it loads mods, shared on the server and every client, then server or client, and worldgen wherever chunks are
// generated. see docs/modding/concepts/sides.md
export const PHASES = ["content", "shared", "server", "client", "worldgen"] as const;
export type Phase = typeof PHASES[number];
// imports a mod's script and calls its export for phase, if it has one, with the context context makes. a realm
// imports the same url once, so every phase there gets the same module and what it keeps at its top level
export async function run_phase(
mod: { id: string; engine_access?: boolean },
url: string,
phase: Phase,
context: () => unknown,
): Promise<void> {
await loading_mod(mod.id, mod.engine_access ?? false, async () => {
const module = await import(url);
if (!PHASES.some((name) => name in module)) {
throw new ModLoadError(mod.id, `its script exports none of ${PHASES.join(", ")}`);
}
const run = module[phase];
if (run === undefined) return;
if (typeof run !== "function") throw new ModLoadError(mod.id, `its script's ${phase} export isn't a function`);
await run(context());
});
}
// whether a block, item, entity or biome is registered, for tags. air isn't a registered block, but tags can hold it // whether a block, item, entity or biome is registered, for tags. air isn't a registered block, but tags can hold it
export function is_registered(registry: TagRegistry, id: string): boolean { export function is_registered(registry: TagRegistry, id: string): boolean {
return (registry === "blocks" && id === "cubi:air") || EverythingRegistry.get(registry, id) !== undefined; return (registry === "blocks" && id === "cubi:air") || EverythingRegistry.get(registry, id) !== undefined;
@@ -183,7 +214,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
} }
for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json); for (const json of data.noise_settings ?? []) EverythingRegistry.register("noise_settings", json.id, json);
for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json); for (const json of data.biome_sources ?? []) EverythingRegistry.register("biome_sources", json.id, json);
// compiled with the types worldgen scripts register, see common/worldgen_loader.ts // compiled with the types worldgen phases register, see common/worldgen_loader.ts
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json); for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
} catch (e) { } catch (e) {
throw new ModLoadError(id, (e as Error).message); throw new ModLoadError(id, (e as Error).message);
@@ -212,7 +243,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
return recipes; return recipes;
} }
// puts mod's recipe in the book, from its recipes/ or its shared script. throws when its registered type's parse throws // puts mod's recipe in the book, from its recipes/ or its shared phase. throws when its registered type's parse throws
export function add_recipe(recipes: RecipeBook, recipe: RecipeJson, mod: string) { export function add_recipe(recipes: RecipeBook, recipe: RecipeJson, mod: string) {
recipes.all.push(recipe); recipes.all.push(recipe);
if (is_mod_recipe(recipe)) { if (is_mod_recipe(recipe)) {
@@ -276,7 +307,7 @@ function checked_item(name: string, problems: string[], id: string): string {
return id; return id;
} }
// once every shared script has set up: a recipe of a type no mod registered, which nothing would read, is an error // once every shared phase has set up: a recipe of a type no mod registered, which nothing would read, is an error
// for the first mod with one, like a misspelled type // for the first mod with one, like a misspelled type
export function check_recipe_types(recipes: RecipeBook) { export function check_recipe_types(recipes: RecipeBook) {
for (const [type, mod] of recipes.first_used_by) { for (const [type, mod] of recipes.first_used_by) {
@@ -297,7 +328,7 @@ export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup {
}; };
} }
// ctx.recipes for shared scripts, the same on the server and every client: a recipe registered there is in the book // ctx.recipes for shared phases, the same on the server and every client: a recipe registered there is in the book
// on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the // on every side without being sent, like one from the mod's recipes/. checked like a data file's. fail throws, as the
// side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it // side's error for the mod. list reads the book as it is, so a script sees the recipes of the ones before it
export function shared_recipes_api( export function shared_recipes_api(
+2 -2
View File
@@ -166,7 +166,7 @@ export type ClientMessage =
| { type: "chat"; text: string } | { type: "chat"; text: string }
// what could come next in a command being typed, answered with suggestions. id matches them up // what could come next in a command being typed, answered with suggestions. id matches them up
| { type: "suggest"; id: number; text: string } | { type: "suggest"; id: number; text: string }
// a mod's client script talking to its server script, see ctx.net // a mod's client phase talking to its server phase, see ctx.net
| { type: "mod"; channel: string; data: unknown }; | { type: "mod"; channel: string; data: unknown };
export type ServerMessage = export type ServerMessage =
@@ -304,7 +304,7 @@ export type ServerMessage =
// the player's own effects that show an icon, when they change. duration is in ticks, -1 for forever, and the // the player's own effects that show an icon, when they change. duration is in ticks, -1 for forever, and the
// client counts it down itself, so it isn't sent every tick // client counts it down itself, so it isn't sent every tick
| { type: "effects"; effects: { id: string; amplifier: number; duration: number }[] } | { type: "effects"; effects: { id: string; amplifier: number; duration: number }[] }
// a mod's server script talking to its client script, see ctx.net // a mod's server phase talking to its client phase, see ctx.net
| { type: "mod"; channel: string; data: unknown }; | { type: "mod"; channel: string; data: unknown };
export const MAX_NAME_LENGTH = 16; export const MAX_NAME_LENGTH = 16;
+1 -1
View File
@@ -181,7 +181,7 @@ export function expand_items(list: readonly string[]): string[] {
return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))]; return [...new Set(list.flatMap((id) => id.startsWith("#") ? Tags.get("items", id) : [id]))];
} }
// ctx.tags for server and client scripts. everything it returns is a copy // ctx.tags for server and client phases. everything it returns is a copy
export function tag_api(): TagApi { export function tag_api(): TagApi {
const registry = (name: string): TagRegistry => { const registry = (name: string): TagRegistry => {
if (!TAG_REGISTRIES.includes(name as TagRegistry)) { if (!TAG_REGISTRIES.includes(name as TagRegistry)) {
+1 -1
View File
@@ -88,7 +88,7 @@ export function display_name(item_id: string): string {
return EverythingRegistry.get<ItemRegistry>("items", item_id)?.name || name_from_id(item_id); return EverythingRegistry.get<ItemRegistry>("items", item_id)?.name || name_from_id(item_id);
} }
// ctx.items for shared scripts, and the part of the client's that's the same. fluids are this side's rules, which // ctx.items for shared phases, and the part of the client's that's the same. fluids are this side's rules, which
// price full fluid containers // price full fluid containers
export function shared_items_api(mod: string, fluids: FluidRules): SharedContext["items"] { export function shared_items_api(mod: string, fluids: FluidRules): SharedContext["items"] {
const known = (id: string) => { const known = (id: string) => {
+7 -7
View File
@@ -3,7 +3,7 @@
// data features: worldgen/features/<path>.json in a mod, a feature's type and config (what) with a list of placement // data features: worldgen/features/<path>.json in a mod, a feature's type and config (what) with a list of placement
// modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into // modifiers (where), see docs/modding/worldgen/index.md. like minecraft's configured and placed features joined into
// one file. the types and modifiers here are built in, worldgen scripts register more // one file. the types and modifiers here are built in, worldgen phases register more
import { EverythingRegistry } from "../everything_registry.ts"; import { EverythingRegistry } from "../everything_registry.ts";
import type { BlockRegistry } from "../everything_registry.ts"; import type { BlockRegistry } from "../everything_registry.ts";
import { CHUNK_SIZE } from "../constants.ts"; import { CHUNK_SIZE } from "../constants.ts";
@@ -42,7 +42,7 @@ export const DEFAULT_STEP: FeatureStep = "top_layer_modification";
export interface FeatureJson { export interface FeatureJson {
id: string; id: string;
// a built in type, like "minecraft:block_column", or one a worldgen script registers // a built in type, like "minecraft:block_column", or one a mod's worldgen phase registers
type: string; type: string;
config?: Record<string, unknown>; config?: Record<string, unknown>;
placement?: PlacementJson[]; placement?: PlacementJson[];
@@ -73,7 +73,7 @@ export function builtin_name(type: string): string | undefined {
export interface FeatureRefs { export interface FeatureRefs {
blocks: Set<string>; blocks: Set<string>;
biomes: Set<string>; biomes: Set<string>;
// types and modifiers that aren't built in, which a worldgen script has to register // types and modifiers that aren't built in, which a mod's worldgen phase has to register
custom: Set<string>; custom: Set<string>;
} }
@@ -141,7 +141,7 @@ const block_predicate_schema: z.ZodType = z.lazy(() =>
], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true") ], "must be matching_blocks, solid, replaceable, would_survive, not, all_of, any_of or true")
); );
// a mod's own modifier is checked by the worldgen script that registers it // a mod's own modifier is checked by the worldgen phase that registers it
const placement_modifier = by_kind<PlacementJson>("type", (type) => { const placement_modifier = by_kind<PlacementJson>("type", (type) => {
const name = builtin_name(type); const name = builtin_name(type);
if (name === undefined) return json_object; if (name === undefined) return json_object;
@@ -156,7 +156,7 @@ const feature_schema: z.ZodType<FeatureJson> = z.object({
biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(), biomes: z.union([biome_id, z.array(biome_id)], "must be a biome's id or a list of them").optional(),
step: z.enum(FEATURE_STEPS).optional(), step: z.enum(FEATURE_STEPS).optional(),
}).superRefine((feature, ctx) => { }).superRefine((feature, ctx) => {
// a built in type's config. a mod's own type is checked by the worldgen script that registers it, like modifiers // a built in type's config. a mod's own type is checked by the worldgen phase that registers it, like modifiers
const name = builtin_name(feature.type); const name = builtin_name(feature.type);
if (name === undefined) return; if (name === undefined) return;
if (!Object.hasOwn(FEATURE_TYPES, name)) { if (!Object.hasOwn(FEATURE_TYPES, name)) {
@@ -205,7 +205,7 @@ export function compile_feature(
const type = types.get(json.type); const type = types.get(json.type);
if (!type) { if (!type) {
throw new Error( throw new Error(
`feature ${json.id}: type ${json.type} isn't built in, and no worldgen script registered it`, `feature ${json.id}: type ${json.type} isn't built in, and no mod's worldgen phase registered it`,
); );
} }
place = (chunk, origin) => type(chunk, config, origin); place = (chunk, origin) => type(chunk, config, origin);
@@ -216,7 +216,7 @@ export function compile_feature(
const custom = modifiers.get(modifier.type); const custom = modifiers.get(modifier.type);
if (!custom) { if (!custom) {
throw new Error( throw new Error(
`feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no worldgen script registered it`, `feature ${json.id}: placement[${i}] ${modifier.type} isn't built in, and no mod's worldgen phase registered it`,
); );
} }
return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions); return (chunk: FeatureChunk, positions: Position[]) => custom(chunk, modifier, positions);
+9 -8
View File
@@ -2,9 +2,9 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// everything generating a chunk reads, as one plain object a worker can be sent: the seed, the generator, and each // everything generating a chunk reads, as one plain object a worker can be sent: the seed, the generator, and each
// mod's data generation needs with its worldgen script's url. loading it registers the data in this realm and loads // mod's data generation needs with its script's url. loading it registers the data in this realm and runs the
// the scripts, which gives the same numeric block ids and the same generator as the game, so chunks come out the same // scripts' worldgen phases, which gives the same numeric block ids and the same generator as the game, so chunks come
// block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture // out the same block for block. tests/worldgen_bundle_test.ts checks it with the golden fixture
import type { ModData } from "./mod_loader.ts"; import type { ModData } from "./mod_loader.ts";
import { register_mod_data } from "./mod_loader.ts"; import { register_mod_data } from "./mod_loader.ts";
import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts"; import { type BlockRegistry, EverythingRegistry } from "./everything_registry.ts";
@@ -35,20 +35,21 @@ export interface WorldgenBundle {
// the dimension's, see WorldShape // the dimension's, see WorldShape
shape: WorldShapeJson; shape: WorldShapeJson;
// in load order // in load order
mods: { id: string; data: WorldgenModData; worldgen_url?: string; engine_access?: boolean }[]; // url is the mod's script, which worldgen workers run the worldgen phase of
mods: { id: string; data: WorldgenModData; url?: string; engine_access?: boolean }[];
} }
export function worldgen_bundle( export function worldgen_bundle(
seed: string, seed: string,
generator: string, generator: string,
shape: WorldShapeJson, shape: WorldShapeJson,
mods: { id: string; data: ModData; worldgen_url?: string; engine_access?: boolean }[], mods: { id: string; data: ModData; url?: string; engine_access?: boolean }[],
): WorldgenBundle { ): WorldgenBundle {
return { return {
seed, seed,
generator, generator,
shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light }, shape: { min_y: shape.min_y, max_y: shape.max_y, sky_light: shape.sky_light },
mods: mods.map(({ id, data, worldgen_url, engine_access }) => ({ mods: mods.map(({ id, data, url, engine_access }) => ({
id, id,
data: { data: {
blocks: data.blocks, blocks: data.blocks,
@@ -62,7 +63,7 @@ export function worldgen_bundle(
biome_sources: data.biome_sources ?? [], biome_sources: data.biome_sources ?? [],
features: data.features ?? [], features: data.features ?? [],
}, },
...(worldgen_url ? { worldgen_url } : {}), ...(url ? { url } : {}),
...(engine_access ? { engine_access } : {}), ...(engine_access ? { engine_access } : {}),
})), })),
}; };
@@ -105,7 +106,7 @@ export async function load_bundle(bundle: WorldgenBundle): Promise<LoadedBundle>
const setup = await load_worldgen({ const setup = await load_worldgen({
mods: bundle.mods.map((mod) => mod.id), mods: bundle.mods.map((mod) => mod.id),
scripts: bundle.mods.flatMap((mod) => scripts: bundle.mods.flatMap((mod) =>
mod.worldgen_url ? [{ mod: mod.id, url: mod.worldgen_url, engine_access: mod.engine_access }] : [] mod.url ? [{ mod: mod.id, url: mod.url, engine_access: mod.engine_access }] : []
), ),
ores: recipes.ores, ores: recipes.ores,
generator: bundle.generator, generator: bundle.generator,
+3 -10
View File
@@ -1,14 +1,13 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// imports mods' worldgen scripts and collects what they and mods' data add to generation: the generator, ores, and // runs mods' worldgen phases and collects what they and mods' data add to generation: the generator, ores, and
// features, code and data, in the order they run. used by the game server // features, code and data, in the order they run. used by the game server
import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_api/worldgen.ts"; import type { FeatureChunk, FeatureStep, WorldgenContext } from "@/common/mod_api/worldgen.ts";
import type { OreJson } from "@/common/mod_data.ts"; import type { OreJson } from "@/common/mod_data.ts";
import type { SetupFeature, WorldgenSetup } from "./generation.ts"; import type { SetupFeature, WorldgenSetup } from "./generation.ts";
import { EverythingRegistry } from "./everything_registry.ts"; import { EverythingRegistry } from "./everything_registry.ts";
import { ModLoadError } from "./mod_loader.ts"; import { ModLoadError, run_phase } from "./mod_loader.ts";
import { loading_mod } from "./hooks.ts";
import { compile_generator } from "./worldgen/generator.ts"; import { compile_generator } from "./worldgen/generator.ts";
import type { WorldShape } from "./world_shape.ts"; import type { WorldShape } from "./world_shape.ts";
import { import {
@@ -97,13 +96,7 @@ export async function load_worldgen(sources: WorldgenSources): Promise<WorldgenS
}, },
}; };
await loading_mod(mod, engine_access ?? false, async () => { await run_phase({ id: mod, engine_access }, url, "worldgen", () => ctx);
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the worldgen script doesn't export a setup function");
}
await module.setup(ctx);
});
} }
// data features last, so they can use the types and modifiers every script registered // data features last, so they can use the types and modifiers every script registered
+12 -12
View File
@@ -1,6 +1,6 @@
# Block Components # Block Components
A block's JSON says what it is. Components say what it _does_. A component is a set of handlers a server script A block's JSON says what it is. Components say what it _does_. A component is a set of handlers the server phase
registers under an id. Any block that lists that id in its `components` gets that behavior, with its own parameters. registers under an id. Any block that lists that id in its `components` gets that behavior, with its own parameters.
This is how every block that does something works, including the base game's chests, furnaces and crops. One component This is how every block that does something works, including the base game's chests, furnaces and crops. One component
@@ -20,7 +20,7 @@ A block can list several. Their handlers run in the listed order.
## Registering a Component ## Registering a Component
In the server script: In the server phase:
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
@@ -30,7 +30,7 @@ interface OxidizesParams {
into: string; into: string;
} }
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
ctx.components.register_block<OxidizesParams>("copper_tools:oxidizes", { ctx.components.register_block<OxidizesParams>("copper_tools:oxidizes", {
on_create(block) { on_create(block) {
block.data = { age: 0 }; block.data = { age: 0 };
@@ -53,9 +53,9 @@ export function setup(ctx: ServerContext) {
Items have components the same way, and so do [status effects](../entities/effects.md#effect-components). Items have components the same way, and so do [status effects](../entities/effects.md#effect-components).
Components can only be registered during `setup`, and only in the mod's own namespace. Once every mod's `setup` has run, Components can only be registered while the server phase runs, and only in the mod's own namespace. Once every mod's
a block or item that lists a component nobody registered stops the server from starting, naming the block and the server phase has run, a block or item that lists a component nobody registered stops the server from starting, naming
component. the block and the component.
## Handlers ## Handlers
@@ -145,14 +145,14 @@ not in memory counts as loaded, and reading it reads it from the save.
## Rules ## Rules
A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're A component's rules decide a block's states from where it's placed, what's around it and being right clicked. They're
registered in the mod's [shared script](../concepts/sides.md#shared-scripts) instead, under the same id, because clients registered in the mod's [shared phase](../concepts/sides.md#shared) instead, under the same id, because clients run them
run them too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later too: that's how a player sees a fence join its neighbors the moment they place it, instead of a moment later when the
when the server answers. A component can have rules, handlers, or both, and a block can list one that only has rules. server answers. A component can have rules, handlers, or both, and a block can list one that only has rules.
```ts ```ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
ctx.components.register_block("copper_tools:pipe", { ctx.components.register_block("copper_tools:pipe", {
state_for_placement(placement, params) {/* ... */}, state_for_placement(placement, params) {/* ... */},
on_neighbor_change(block, params, neighbor) {/* ... */}, on_neighbor_change(block, params, neighbor) {/* ... */},
@@ -167,7 +167,7 @@ export function setup(ctx: SharedContext) {
| `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | | | `on_neighbor_change(block, params, neighbor)` | A block on one of its 6 sides is placed, broken or changes its states. | |
| `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something | | `on_interact(block, params, interaction)` | A player right clicks it. | `true` if it did something |
Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in a shared script has Here `block` is `{ id, x, y, z }`, without tile data, which clients never have. `ctx.world` in the shared phase has
`get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see `get_block`, `get_state`, `set_state`, `is_face_sturdy`, `biome_at` and `season_at` (see
[Seasons](../worldgen/biomes.md#seasons)), and only works inside rules. `ctx.blocks.components(id)` gives any block's [Seasons](../worldgen/biomes.md#seasons)), and only works inside rules. `ctx.blocks.components(id)` gives any block's
components and their params, like on the server, for rules that look at what's around them, like a shaft lining up with components and their params, like on the server, for rules that look at what's around them, like a shaft lining up with
@@ -329,7 +329,7 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
| `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. | | `bworld:crop_top` | see [Crops](crops.md) | The top half of a two block crop, like rice. |
| `bworld:water_source` | none | Refills the watering can. | | `bworld:water_source` | none | Refills the watering can. |
| `bworld:fishable` | `loot_table`? | The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is `loot_table`, `bworld:gameplay/fishing` when not given, built from the fish whose `fluid` is this block. | | `bworld:fishable` | `loot_table`? | The fishing rod's hook floats on it and fish bite there when it lands in it. What's caught is `loot_table`, `bworld:gameplay/fishing` when not given, built from the fish whose `fluid` is this block. |
| `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared script). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. | | `bworld:trapdoor` | none | Opens and closes when right clicked, and is placed like Minecraft's (both are rules, in the shared phase). Needs `facing` (2 bits), `half` and `open` states, see `blocks/oak_trapdoor.json`. |
| `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. | | `bworld:fence` | `connects_to` | Joins the blocks in the tag `connects_to` and sturdy sides of other blocks, except leaves. Needs the `north`, `east`, `south` and `west` states. |
Item components work the same way, see [Items](../items/index.md#item-components). Item components work the same way, see [Items](../items/index.md#item-components).
+4 -4
View File
@@ -4,7 +4,7 @@ Blocks make up the world. Each kind of block is defined once, in a JSON file in
world is made of references to those definitions at different positions. world is made of references to those definitions at different positions.
A block's definition says how it looks, how it's mined and what it drops. What it _does_ comes from A block's definition says how it looks, how it's mined and what it drops. What it _does_ comes from
[components](components.md), which server scripts register. [components](components.md), which server phases register.
## A Basic Block ## A Basic Block
@@ -27,7 +27,7 @@ side, takes 5 seconds to break by hand, breaks faster with a pickaxe, and only d
of tier 1 (stone or copper) or better. of tier 1 (stone or copper) or better.
A mod with many similar blocks, like every block of every kind of rock, can register them in code from a A mod with many similar blocks, like every block of every kind of rock, can register them in code from a
[content script](../concepts/sides.md#content-scripts) instead, with the same object a file holds under `"block"`. [content phase](../concepts/sides.md#content) instead, with the same object a file holds under `"block"`.
## Properties ## Properties
@@ -225,8 +225,8 @@ plains' color.
## Raycasts ## Raycasts
Server scripts find the first block on a line with `ctx.world.raycast`, like Minecraft's `Level.clip`. The fishing rod's The server phase finds the first block on a line with `ctx.world.raycast`, like Minecraft's `Level.clip`. The fishing
hook uses it to see where it lands, and with a player's rod's hook uses it to see where it lands, and with a player's
[`eye_position` and `look_direction`](../entities/players.md#the-player-api) it finds what they're looking at: [`eye_position` and `look_direction`](../entities/players.md#the-player-api) it finds what they're looking at:
```ts ```ts
+1 -1
View File
@@ -21,7 +21,7 @@ the defaults when it's placed or generated.
## Reading and Changing States ## Reading and Changing States
Server scripts use `ctx.world`: The server phase uses `ctx.world`:
```ts ```ts
const age = ctx.world.get_state(x, y, z, "age") ?? 0; const age = ctx.world.get_state(x, y, z, "age") ?? 0;
+2 -2
View File
@@ -78,7 +78,7 @@ ctx.components.register_block("copper_tools:shaft", {
changes often doesn't resend the others, and setting a field to what it already is sends nothing. changes often doesn't resend the others, and setting a field to what it already is sends nothing.
- `undefined` removes a field. All of them go when the block is broken or replaced. - `undefined` removes a field. All of them go when the block is broken or replaced.
- It's saved with the world. `get_client_data` and `set_client_data` copy the value, so change it by setting it again. - It's saved with the world. `get_client_data` and `set_client_data` copy the value, so change it by setting it again.
- Client scripts read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md). A block's - Client phases read it with `ctx.world.get_client_data<T>(x, y, z, field)`, see [GUI](../gui/index.md). A block's
[visual](visuals.md) reads it with `block.get_client_data`, and its `update` is called when a field changes. [visual](visuals.md) reads it with `block.get_client_data`, and its `update` is called when a field changes.
Like NeoForge's `getUpdateTag`, but per field. Keep it to what clients need to draw the block: everything in it is sent Like NeoForge's `getUpdateTag`, but per field. Keep it to what clients need to draw the block: everything in it is sent
@@ -92,7 +92,7 @@ A block with `item_display` draws one item lying on top of it, like the food on
"item_display": { "surface": 1 } "item_display": { "surface": 1 }
``` ```
`surface` is the height in pixels the item lies at, 0 to 16. The server script sets the item: `surface` is the height in pixels the item lies at, 0 to 16. The server phase sets the item:
```ts ```ts
ctx.world.set_block_item(x, y, z, { id: "bworld:cabbage", count: 1 }); ctx.world.set_block_item(x, y, z, { id: "bworld:cabbage", count: 1 });
+4 -4
View File
@@ -1,7 +1,7 @@
# Visuals # Visuals
A visual draws a block with code, for blocks that move or show what's in them: a shaft that turns, a press coming down, A visual draws a block with code, for blocks that move or show what's in them: a shaft that turns, a press coming down,
the items and fluid in a machine. A client script registers one for a block, and every block of that kind in a shown the items and fluid in a machine. The client phase registers one for a block, and every block of that kind in a shown
chunk gets its own. It's bworld's version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create chunk gets its own. It's bworld's version of Minecraft's block entity renderers, shaped like the Flywheel visuals Create
draws its machines with. draws its machines with.
@@ -10,7 +10,7 @@ draws its machines with.
```ts ```ts
import type { ClientContext } from "cubi/client"; import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.render.register_visual("copper_tools:shaft", (block, instances) => { ctx.render.register_visual("copper_tools:shaft", (block, instances) => {
const shaft = instances.rotating(); const shaft = instances.rotating();
const turn = () => shaft.set_rotation("y", block.get_client_data<number>("speed") ?? 0); const turn = () => shaft.set_rotation("y", block.get_client_data<number>("speed") ?? 0);
@@ -20,7 +20,7 @@ export function setup(ctx: ClientContext) {
} }
``` ```
- Visuals can only be registered during `setup`, and a block has at most one. - Visuals can only be registered while the client phase runs, and a block has at most one.
- With `replaces_model: true`, the block's model is left out of the terrain, for a visual that draws all of the block, - With `replaces_model: true`, the block's model is left out of the terrain, for a visual that draws all of the block,
like the shaft above. Without it, the model is drawn as usual and the visual adds to it, like a press's head over its like the shaft above. Without it, the model is drawn as usual and the visual adds to it, like a press's head over its
casing. The model is still what the block's item, its outline and the cracks on it while it's broken are drawn with. casing. The model is still what the block's item, its outline and the cracks on it while it's broken are drawn with.
@@ -145,7 +145,7 @@ ctx.render.register_visual("copper_tools:crank", (block, instances) => {
}); });
``` ```
Only visuals in chunks in view get `on_frame`, so keep anything that has to happen out of view in the server script. Only visuals in chunks in view get `on_frame`, so keep anything that has to happen out of view in the server phase.
## Cost ## Cost
+4 -4
View File
@@ -1,6 +1,6 @@
# Events # Events
Events let a server script react to what happens in the game, and stop some of it from happening. They're the Events let the server phase react to what happens in the game, and stop some of it from happening. They're the
alternative to [components](../blocks/components.md) when the behavior isn't tied to one block or item: logging chat, alternative to [components](../blocks/components.md) when the behavior isn't tied to one block or item: logging chat,
protecting spawn, or reacting to every block broken anywhere. protecting spawn, or reacting to every block broken anywhere.
@@ -15,7 +15,7 @@ Every event is a signal you subscribe to. Events come in two kinds:
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
// nobody breaks blocks within 16 blocks of the world's center // nobody breaks blocks within 16 blocks of the world's center
ctx.events.before.block_break.subscribe((event) => { ctx.events.before.block_break.subscribe((event) => {
const { x, z } = event.block; const { x, z } = event.block;
@@ -52,7 +52,7 @@ showed. These events fire for **every** player's actions, since they all go thro
| `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after | | `player_death` | | ✓ | `player`, `cause`. They've dropped what they carried and respawn right after |
| `player_join` | | ✓ | `player` | | `player_join` | | ✓ | `player` |
| `player_leave` | | ✓ | `player` | | `player_leave` | | ✓ | `player` |
| `server_start` | | ✓ | none. Every mod's `setup` has run | | `server_start` | | ✓ | none. Every mod's server phase has run |
| `tick` | | ✓ | `dt`, in seconds. 20 times a second | | `tick` | | ✓ | `dt`, in seconds. 20 times a second |
| `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` | | `new_day` | | ✓ | `day`. At 06:00, after every block's `on_new_day` |
@@ -66,7 +66,7 @@ only when the entity was hurt, with the amount the before handlers left.
### Order ### Order
Handlers run in the order they subscribed, and mods' `setup` functions run in [load order](registries.md#loading). For Handlers run in the order they subscribed, and mods' server phases run in [load order](registries.md#loading). For
`block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers, `block_interact`, the before event runs first, then the block's own components' `on_interact`, rules before handlers,
unless the player is [sneaking](../entities/players.md#sneaking) with an item in hand. If no component handled the click unless the player is [sneaking](../entities/players.md#sneaking) with an item in hand. If no component handled the click
and the held item has no `on_use`, the held block is placed, which fires `block_place`. Cancelling it undoes what the and the held item has no `on_use`, the held block is placed, which fires `block_place`. Cancelling it undoes what the
+7 -7
View File
@@ -32,18 +32,18 @@ The server and every client load mods the same way, in the same order:
1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend 1. **Order.** Dependencies come before the mods that need them, and otherwise mods load alphabetically. Mods that depend
on each other in a circle are an error. The server sends its order to clients, and they follow it. on each other in a circle are an error. The server sends its order to clients, and they follow it.
2. **Data**, one mod at a time: its block models, blocks (and their items), including the ones its 2. **Data**, one mod at a time: its block models, blocks (and their items), including the ones its
[content script](sides.md#content-scripts) registers, after its `blocks/` files, items, entity models, entities, [content phase](sides.md#content) registers, after its `blocks/` files, items, entity models, entities, effects and
effects and fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and fluids. Then every mod's [tags](../resources/tags.md), merged in load order, then each mod's recipes and ores, which
ores, which can use tags. can use tags.
3. **Scripts.** Server scripts' `setup` runs on the server, and client scripts' on each client. Worldgen scripts' 3. **Scripts.** Every mod's shared phase runs, then its server phase on the server and its client phase on each client.
`setup` runs on the server before it makes chunks. The worldgen phase runs wherever the server makes chunks.
Scripts read the registries but can't add to them. Content comes from data files, and from content scripts, which the Scripts read the registries but can't add to them. Content comes from data files, and from content phases, which the
server runs when it loads mods, before anything else, and whose blocks go to players as data. server runs when it loads mods, before anything else, and whose blocks go to players as data.
> [!IMPORTANT] > [!IMPORTANT]
> The server and the client must end up with exactly the same blocks, items and recipes. They do as long as content is > The server and the client must end up with exactly the same blocks, items and recipes. They do as long as content is
> only data, since both load the same files in the same order. Content scripts only run on the server, and players get > only data, since both load the same files in the same order. Content phases only run on the server, and players get
> what they made as data. > what they made as data.
## Numeric Ids ## Numeric Ids
+11 -9
View File
@@ -9,24 +9,26 @@ Anything a client sends can be forged by a player who edits their client. The en
reach and the held item for every break, place and interact, and container rules (slot filters, output-only slots) on reach and the held item for every break, place and interact, and container rules (slot filters, output-only slots) on
the server. A mod's own logic has to do the same: the server. A mod's own logic has to do the same:
- Decide on the server. Client scripts show things. Server scripts decide what happens. - Decide on the server. The client phase shows things. The server phase decides what happens.
- Check permissions on the server, in the server script, before acting for a player, like `requires` on a - Check permissions on the server, in the server phase, before acting for a player, like `requires` on a
[command](../misc/commands.md). [command](../misc/commands.md).
- Never use a value from a client as an item id, a count or a position without checking it. - Never use a value from a client as an item id, a count or a position without checking it.
Server script code and tile data are never sent to clients, so a mod can keep anti-cheat logic or secrets there. Only Tile data is never sent to clients, only the fields a script sets as [client data](../blocks/tiledata.md#client-data). A
the fields a script sets as [client data](../blocks/tiledata.md#client-data) are. mod's script is: players get all of it, its server phase too, and only run its shared and client phases. So a mod can
keep secrets in the world, in tile data or [`ctx.storage`](../datastorage/index.md), but never in its code. Anti-cheat
works by the server deciding, not by hiding how it decides.
## Server Scripts ## The Server Phase
Server scripts run in the game worker with **no Deno permissions**: they can't read files, open connections or run The server phase runs in the game worker with **no Deno permissions**: they can't read files, open connections or run
programs. Everything they can do goes through the mod API. Installing a server mod still means trusting it with the game programs. Everything they can do goes through the mod API. Installing a server mod still means trusting it with the game
world and everything players send. world and everything players send.
## Client Scripts ## The Client Phase
Client scripts run in the game page with the page's full access. How much that matters depends on where the page came The client phase runs in the game page, like the rest of a mod's script there, with the page's full access. How much
from: that matters depends on where the page came from:
- **The page was served by the game server** (the default). That server already chose every line of JavaScript on the - **The page was served by the game server** (the default). That server already chose every line of JavaScript on the
page, so running its mods doesn't trust it any more than loading the page did. page, so running its mods doesn't trust it any more than loading the page did.
+99 -60
View File
@@ -10,81 +10,122 @@ slot 3". The server checks it (reach, the item being held, container rules), run
happened. happened.
For responsiveness, the client guesses the result of breaking, placing and right clicking blocks and shows it right For responsiveness, the client guesses the result of breaking, placing and right clicking blocks and shows it right
away, with the states the server will give them: it runs the same [shared scripts](#shared-scripts) the server does. away, with the states the server will give them: it runs the same [shared phase](#shared) the server does. When the
When the server disagrees, like when a before event cancels a placement, it sends that player the real block and the server disagrees, like when a before event cancels a placement, it sends that player the real block and the guess is
guess is undone. Like Minecraft, each click is numbered and the server says when it's done with it: until then the undone. Like Minecraft, each click is numbered and the server says when it's done with it: until then the client keeps
client keeps showing its guess, so the server's answer to an earlier click can't flicker a block a newer one changed, showing its guess, so the server's answer to an earlier click can't flicker a block a newer one changed, like a trapdoor
like a trapdoor clicked twice. Blocks with `"interactive": true` tell the client not to guess a placement, since right clicked twice. Blocks with `"interactive": true` tell the client not to guess a placement, since right clicking them
clicking them does something else. does something else.
``` ```
server process browser server process browser
┌───────────────────────────────────────┐ ┌──────────────────────────────────┐ ┌───────────────────────────────────────┐ ┌──────────────────────────────────┐
│ host: http, websocket, files │ │ game client (rendering, input) │ │ host: http, websocket, files │ │ game client (rendering, input) │
│ ┌───────────────────────────────────┐ │ ws │ + mods' client scripts │ │ ┌───────────────────────────────────┐ │ ws │ + mods' shared phases │
│ │ game server worker │◄├──────────┤► │ │ │ game server worker │◄├──────────┤► + mods' client phases │
│ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │ │ │ world, inventories, tile data │ │ protocol │ chunk workers (meshing, light) │
│ │ + mods' server scripts │ │ chunks │ + mods' shared scripts │ │ │ + mods' shared phases │ │ chunks └──────────────────────────────────┘
│ │ + mods' shared scripts │ │ └──────────────────────────────────┘ │ │ + mods' server phases │ │
│ │ + mods' worldgen scripts │ │
│ └───────────────────────────────────┘ │ │ └───────────────────────────────────┘ │
│ worldgen workers │
│ + mods' worldgen phases │
│ content worker, while mods load │
│ + mods' content phases │
└───────────────────────────────────────┘ └───────────────────────────────────────┘
``` ```
## The Five Scripts ## One Script, Five Phases
| Script | Runs on | Sent to players | For | A mod has one script, named by `main` in its manifest. Each of its exports is a **phase**, a function the game calls
| ---------- | -------------------------------- | ---------------------- | ------------------------------------------------------------------- | with that phase's context where and when it runs:
| `server` | the server, in the game worker | **never** | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | yes | presentation: screens, inventory overlays and the HUD | ```ts
| `shared` | the server and every browser | yes | block rules: the states blocks are placed with, joining neighbors | import type { ContentContext } from "cubi/content";
| `worldgen` | the server, when it makes chunks | no | features that decorate terrain, deterministic | import type { SharedContext } from "cubi/shared";
| `content` | the server, while it loads mods | no, only what it makes | blocks made in code, like one for every kind of rock | import type { ServerContext } from "cubi/server";
import type { ClientContext } from "cubi/client";
import type { WorldgenContext } from "cubi/worldgen";
export function content(ctx: ContentContext) {/* blocks made in code */}
export function shared(ctx: SharedContext) {/* block rules, fluid rules, recipe types */}
export function server(ctx: ServerContext) {/* components, events, commands */}
export function client(ctx: ClientContext) {/* screens, the HUD */}
export function worldgen(gen: WorldgenContext) {/* features */}
```
| Phase | Runs on | For |
| ---------- | -------------------------------- | ------------------------------------------------------------------- |
| `content` | the server, while it loads mods | blocks made in code, like one for every kind of rock |
| `shared` | the server and every browser | block rules: the states blocks are placed with, joining neighbors |
| `server` | the server, in the game worker | game logic: block and item components, events, commands, containers |
| `client` | every player's browser | presentation: screens, inventory overlays and the HUD |
| `worldgen` | the server, when it makes chunks | features that decorate terrain, deterministic |
Every export is optional: a mod leaves out the phases it doesn't need. A big mod can keep each phase in its own file and
export them all from its main script, like the base game does:
```ts
// scripts/main.ts
export { content } from "./content.ts";
export { shared } from "./shared.ts";
export { server } from "./server.ts";
export { client } from "./client.ts";
export { worldgen } from "./worldgen.ts";
```
Or it can keep a feature together, with its shared rules and its server handlers in one file, sharing what's at its top
level. A side imports the script once, so every phase that side runs gets the same module.
The script is bundled into one module that goes everywhere: the server, every player, and the server's workers. Each
only runs its own phases, but every one of them loads the whole module, so its top level must work anywhere. Keep what
only one side has, like the browser's `document`, inside that side's phase, and import a library only one side needs
with `await import()` inside its phase. Players can read all of it, the server phase too, so it's no place for secrets,
see [Security](security.md).
Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and Data (blocks, items, models, recipes, entities, textures) isn't a script: it's registered the same way on the server and
on every client, before any script runs. See [Registries](registries.md). Content scripts make more of it. on every client, before any phase runs. See [Registries](registries.md). The content phase makes more of it.
### Server Scripts ### Server
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
// register components and commands, subscribe to events // register components and commands, subscribe to events
} }
``` ```
`setup` runs once when the server starts, after every mod's data is registered. Components and commands can only be It runs once when the server starts, after every mod's data is registered and every mod's shared phase has run.
registered during `setup`. Everything else on `ctx` works for as long as the server runs, from timers, events and Components and commands can only be registered while it runs. Everything else on `ctx` works for as long as the server
component handlers. runs, from timers, events and component handlers.
The game worker has **no Deno permissions**: no files, network or subprocesses. State that should last goes in the The game worker has **no Deno permissions**: no files, network or subprocesses. State that should last goes in the
world, through [tile data](../blocks/tiledata.md), [containers](../inventories/containers.md) and world, through [tile data](../blocks/tiledata.md), [containers](../inventories/containers.md) and
[`ctx.storage`](../datastorage/index.md), which are saved with it. [`ctx.storage`](../datastorage/index.md), which are saved with it.
### Client Scripts ### Client
```ts ```ts
import type { ClientContext } from "cubi/client"; import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({ on_render(g, screen) {/* ... */} }); ctx.ui.add_inventory_overlay({ on_render(g, screen) {/* ... */} });
} }
``` ```
`setup` runs after the client has downloaded the server's mods and before the world appears. Client scripts are for It runs after the client has downloaded the server's mods and before the world appears. The client phase is for
presentation. They can read what the client sees (`ctx.world.get_block`, `ctx.player.position`, items, recipes) but presentation. It can read what the client sees (`ctx.world.get_block`, `ctx.player.position`, items, recipes) but can't
can't change the world or inventories. change the world or inventories.
Client code is visible to players and can be changed by them. Never trust it for anything that matters. See Client code is visible to players and can be changed by them. Never trust it for anything that matters. See
[Security](security.md). [Security](security.md).
### Shared Scripts ### Shared
```ts ```ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
ctx.components.register_block("copper_tools:pipe", { ctx.components.register_block("copper_tools:pipe", {
state_for_placement(placement) {/* ... */}, state_for_placement(placement) {/* ... */},
on_neighbor_change(block, params, neighbor) {/* ... */}, on_neighbor_change(block, params, neighbor) {/* ... */},
@@ -93,32 +134,30 @@ export function setup(ctx: SharedContext) {
} }
``` ```
Shared scripts hold a block component's rules, the code Minecraft runs on both sides: what states a block is placed with The shared phase holds a block component's rules, the code Minecraft runs on both sides: what states a block is placed
(`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it with (`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it
changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server
script registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the phase registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the
same id. They also hold [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data, and same id. It also holds [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data, and
[recipes made in code](../resources/recipes.md#recipes-from-scripts), which every side has without the server sending [recipes made in code](../resources/recipes.md#recipes-from-scripts), which every side has without the server sending
them. them.
On the server they run on the real world. On a client they run on what that client shows, when its player places, breaks On the server it runs on the real world. On a client it runs on what that client shows, when its player places, breaks
or right clicks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and or right clicks a block, so a fence joins its neighbors the moment it's placed. What it changes there is a guess, and
the server's answer replaces it a moment later, so a shared script that gives a different answer on a client only costs the server's answer replaces it a moment later, so a rule that gives a different answer on a client only costs a
a flicker. `ctx.side` says which one it's running on. flicker. `ctx.side` says which one it's running on.
`setup` runs before the server or client script on each side, for every mod first, so their scripts can count on any It runs before the server or client phase on each side, for every mod first, so their phases can count on any mod's
mod's rules being there. Rules can only be registered during `setup`, and `ctx.world` only works in them. rules being there. Rules can only be registered while it runs, and `ctx.world` only works in them.
Shared code is sent to players like client code, so it's for rules anyone may read, never anti-cheat or secrets. ### Content
### Content Scripts
```ts ```ts
import type { ContentContext } from "cubi/content"; import type { ContentContext } from "cubi/content";
const ROCKS = ["granite", "basalt", "slate"]; const ROCKS = ["granite", "basalt", "slate"];
export function setup(ctx: ContentContext) { export function content(ctx: ContentContext) {
for (const rock of ROCKS) { for (const rock of ROCKS) {
ctx.blocks.register({ ctx.blocks.register({
id: `rocks:${rock}`, id: `rocks:${rock}`,
@@ -130,25 +169,27 @@ export function setup(ctx: ContentContext) {
} }
``` ```
Content scripts make data in code, for content that's easier to generate than to write out file by file. The content phase makes data in code, for content that's easier to generate than to write out file by file.
`ctx.blocks.register` takes the same object a `blocks/` file holds under `"block"`. The blocks a content script `ctx.blocks.register` takes the same object a `blocks/` file holds under `"block"`. The blocks it registers become part
registers become part of the mod's data, the same as its files: of the mod's data, the same as its files:
- They're registered right after the mod's `blocks/` files, in the order of the calls. - They're registered right after the mod's `blocks/` files, in the order of the calls.
- They're checked the same way, so a mistake stops the mod loading and names the script. They have to be in the mod's - They're checked the same way, so a mistake stops the mod loading and names the script. They have to be in the mod's
own namespace. own namespace.
- The mod's files can name them: tags, recipes, drops, ores and the rest of worldgen. - The mod's files can name them: tags, recipes, drops, ores and the rest of worldgen.
- Players get them with the rest of the mod's data and never run the script, so the server and its players always agree. - Players get them with the rest of the mod's data and never run the content phase, so the server and its players always
agree.
The server runs content scripts when it loads mods, before anything else reads their data, in a worker with **no Deno The server runs it when it loads mods, before anything else reads their data, in a worker with **no Deno permissions**,
permissions**, like the game's. `check-mods`, the build and tests run them from the mod's folder. Blocks can only be like the game's. `check-mods`, the build and tests run it from the mod's folder. Blocks can only be registered while it
registered during `setup`. Content scripts don't see other mods' content or the server's [config](../misc/config.md), runs. It doesn't see other mods' content or the server's [config](../misc/config.md), and only `engine.common` of
and can't import [`cubi/engine`](../misc/engine.md). [`cubi/engine`](../misc/engine.md) is there.
### Worldgen Scripts ### Worldgen
Worldgen scripts register features that run on every chunk the server generates. They must be deterministic: the same The worldgen phase registers features that run on every chunk the server generates. It runs in each of the server's
seed and chunk always give the same blocks. See [World Generation](../worldgen/index.md). worldgen workers, and features must be deterministic: the same seed and chunk always give the same blocks. See
[World Generation](../worldgen/index.md).
## What Each Side Knows ## What Each Side Knows
@@ -162,9 +203,7 @@ seed and chunk always give the same blocks. See [World Generation](../worldgen/i
| Entities | yes | near the player | | Entities | yes | near the player |
| `ctx.storage` | yes | no | | `ctx.storage` | yes | no |
| [Config](../misc/config.md) | yes | no | | [Config](../misc/config.md) | yes | no |
| Server script code | yes | **never** | | A mod's script | yes | yes, but only runs its shared and client |
| Shared script code | yes | yes, and runs it |
| Content script code | yes | **never**, only the blocks it registers |
When a client needs to see something only the server has, the server has to send it: open a When a client needs to see something only the server has, the server has to send it: open a
[menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows. [menu](../inventories/menus.md), put it in an item's `data`, or set a block state the block's model shows.
+3 -3
View File
@@ -1,6 +1,6 @@
# Saving Data # Saving Data
Server scripts have no file access, so everything a mod keeps goes through the world, and is saved with it. Pick the The server phase has no file access, so everything a mod keeps goes through the world, and is saved with it. Pick the
place by what the data belongs to: place by what the data belongs to:
| Data belongs to | Keep it in | Sent to players | | Data belongs to | Keep it in | Sent to players |
@@ -37,8 +37,8 @@ belongs in that block's tile data, which goes away with the block.
## What Isn't Saved ## What Isn't Saved
- Variables in a script. Everything in memory is gone when the server restarts, so rebuild it in `setup` from what was - Variables in a script. Everything in memory is gone when the server restarts, so rebuild it in the server phase from
saved. what was saved.
- [Timers](../misc/time.md#timers). - [Timers](../misc/time.md#timers).
- Scripted [entities](../entities/index.md#behaviors), like the fishing hook. - Scripted [entities](../entities/index.md#behaviors), like the fishing hook.
- `get_lore` text, which is worked out each time a stack is sent. - `get_lore` text, which is worked out each time a stack is sent.
+4 -4
View File
@@ -4,7 +4,7 @@ Status effects change a player or a mob for a while, like speed or poison. They
effect is defined once, and adding it to someone gives them an instance of it with a duration and a level. effect is defined once, and adding it to someone gives them an instance of it with a duration and a level.
Like blocks and items, an effect is data with components. Its JSON in the mod's `effects/` folder says what it is and Like blocks and items, an effect is data with components. Its JSON in the mod's `effects/` folder says what it is and
which attributes it changes. Components, registered by the server script, say what it does over time. An effect can also which attributes it changes. Components, registered by the server phase, say what it does over time. An effect can also
change things where they happen, through an [event](../concepts/events.md). Even the base game's effects are defined change things where they happen, through an [event](../concepts/events.md). Even the base game's effects are defined
this way, in `mods/bworld/effects`. this way, in `mods/bworld/effects`.
@@ -46,12 +46,12 @@ An effect that does something each tick lists components, with their parameters:
} }
``` ```
The server script registers them during `setup`, in the mod's own namespace: The server phase registers them while it runs, in the mod's own namespace:
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
ctx.components.register_effect<{ every: number }>("copper_tools:rusting", { ctx.components.register_effect<{ every: number }>("copper_tools:rusting", {
should_tick: (ticks, amplifier, params) => ticks % params.every === 0, should_tick: (ticks, amplifier, params) => ticks % params.every === 0,
on_tick(entity, amplifier) { on_tick(entity, amplifier) {
@@ -102,7 +102,7 @@ Like block components, an effect that lists a component nobody registered stops
Some effects change something as it happens, like damage coming in, rather than over time. Those need no component: a Some effects change something as it happens, like damage coming in, rather than over time. Those need no component: a
handler checks whether the entity has the effect. `bworld:resistance` is one, subscribing to `entity_damage` in its handler checks whether the entity has the effect. `bworld:resistance` is one, subscribing to `entity_damage` in its
server script: server phase:
```ts ```ts
ctx.events.before.entity_damage.subscribe((event) => { ctx.events.before.entity_damage.subscribe((event) => {
+4 -4
View File
@@ -1,7 +1,7 @@
# Players # Players
Server scripts see players as `Player` objects: in events, in component handlers, from `ctx.players`, and as the source The server phase sees players as `Player` objects: in events, in component handlers, from `ctx.players`, and as the
of a command. source of a command.
## Finding Players ## Finding Players
@@ -181,7 +181,7 @@ their eyes at 0.6, so they fit through 1-block gaps. Under a low ceiling they st
stand up. stand up.
`player.is_swimming()` says whether a player is swimming, like NeoForge's `isSwimming()`. It works on the server and in `player.is_swimming()` says whether a player is swimming, like NeoForge's `isSwimming()`. It works on the server and in
client scripts, where `ctx.player.is_swimming()` is about the player on this client: the client phase, where `ctx.player.is_swimming()` is about the player on this client:
```ts ```ts
if (player.is_swimming()) player.add_effect("bworld:speed", 20); if (player.is_swimming()) player.add_effect("bworld:speed", 20);
@@ -190,7 +190,7 @@ if (player.is_swimming()) player.add_effect("bworld:speed", 20);
## Sneaking ## Sneaking
`player.is_sneaking()` says whether a player holds the sneak key, like NeoForge's `isShiftKeyDown()`. It's the key, not `player.is_sneaking()` says whether a player holds the sneak key, like NeoForge's `isShiftKeyDown()`. It's the key, not
the pose: a player flying down holds it too. Their client tells the server as soon as it changes. In client scripts, the pose: a player flying down holds it too. Their client tells the server as soon as it changes. In the client phase,
`ctx.player.is_sneaking()` is about the player on this client. `ctx.player.is_sneaking()` is about the player on this client.
Sneaking changes what right clicking a block does, like Minecraft: with an item in hand, the block isn't used at all, Sneaking changes what right clicking a block does, like Minecraft: with an item in hand, the block isn't used at all,
+2 -2
View File
@@ -19,8 +19,8 @@ deno task new-mod copper_tools "Copper Tools"
``` ```
This copies `templates/mod` to `mods/copper_tools` and fills in the id and name. The template has one of everything: a This copies `templates/mod` to `mods/copper_tools` and fills in the id and name. The template has one of everything: a
block with a custom component, an item, a shaped recipe, two textures, and a server, client and worldgen script. Delete block with a custom component, an item, a shaped recipe, two textures, and a script with a server, client and worldgen
what you don't need, along with its entry in `manifest.json`. phase. Delete what you don't need: a phase you don't need is an export you leave out.
The first argument is the mod's id, its [namespace](../concepts/registries.md#identifiers). It has to match the folder The first argument is the mod's id, its [namespace](../concepts/registries.md#identifiers). It has to match the folder
name. name.
+20 -33
View File
@@ -1,7 +1,7 @@
# Mod Files # Mod Files
A mod is a folder with a `manifest.json`, some data files, textures, and up to five scripts. The build packs it into a A mod is a folder with a `manifest.json`, some data files, textures, and a script. The build packs it into a single
single `.cubi` file, which is what servers load. `.cubi` file, which is what servers load.
## Layout ## Layout
@@ -32,11 +32,8 @@ mods/
textures/*.png textures/*.png
textures/*.json # animations, see resources/textures.md textures/*.json # animations, see resources/textures.md
scripts/ scripts/
server.ts # game logic, never sent to players main.ts # the mod's script, its exports are its phases. sent to players, see concepts/sides.md
client.ts # sent to players *.ts # whatever else it imports
shared.ts # block rules, run on the server and sent to players
worldgen.ts # terrain features, never sent to players
content.ts # blocks made in code, run by the server while it loads mods, never sent to players
``` ```
Data folders can have subfolders. Every data file holds one definition, wrapped with the format version: Data folders can have subfolders. Every data file holds one definition, wrapped with the format version:
@@ -63,13 +60,7 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
"authors": ["paula"], "authors": ["paula"],
"game_version": ">=0.1.0", "game_version": ">=0.1.0",
"dependencies": [{ "id": "bworld", "version": "*" }], "dependencies": [{ "id": "bworld", "version": "*" }],
"scripts": { "main": "scripts/main.ts",
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"worldgen": "scripts/worldgen.ts",
"shared": "scripts/shared.ts",
"content": "scripts/content.ts"
},
"credits": "CREDITS.md" "credits": "CREDITS.md"
} }
``` ```
@@ -83,29 +74,29 @@ matter, the `id` inside does, except for [tags](../resources/tags.md), whose id
| `version` | yes | The mod's own version, semver like `1.0.0`. | | `version` | yes | The mod's own version, semver like `1.0.0`. |
| `authors` | no | A list of names. | | `authors` | no | A list of names. |
| `game_version` | no | The bworld versions the mod works with, as a semver range. Only checked for mods with `engine_access`. | | `game_version` | no | The bworld versions the mod works with, as a semver range. Only checked for mods with `engine_access`. |
| `engine_access` | no | `true` lets the scripts import `cubi/engine` and hook the engine. See [Engine Access](../misc/engine.md). | | `engine_access` | no | `true` lets the script import `cubi/engine` and hook the engine. See [Engine Access](../misc/engine.md). |
| `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. | | `dependencies` | no | Other mods, `{ "id", "version" }`. A missing dependency is an error, and dependencies load first. The version range isn't checked yet. |
| `scripts` | no | Paths to the `server`, `client`, `shared`, `worldgen` and `content` scripts. See [Sides](../concepts/sides.md). | | `main` | no | The path of the mod's script, whose exports are its phases. See [Sides](../concepts/sides.md). |
| `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. | | `credits` | no | A markdown file for licenses and thanks, shown on the Credits screen. Raw HTML in it is shown as text. |
List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It List every mod whose ids you use in `dependencies`, including `bworld` for the base game's blocks and items. It
guarantees they're loaded before yours, and `check-mods` warns when one is missing. guarantees they're loaded before yours, and `check-mods` warns when one is missing.
## Scripts ## The Script
Each script is an ES module that exports a `setup` function. The build bundles every script on its own into one module, A mod's script is an ES module whose exports are its phases: `content`, `shared`, `server`, `client` and `worldgen`,
so they can import other files and packages, but code imported by several scripts is copied into each bundle. each a function called with its context where and when it runs. See [Sides](../concepts/sides.md). The build bundles it
with everything it imports into one module, so it can import other files and packages.
> [!WARNING] > [!WARNING]
> Anything the client script imports is sent to every player who joins. Don't import secrets or anti-cheat logic into > The whole script is sent to every player who joins, its server phase too. Don't put secrets in it.
> code the client script shares with the server script.
### Mods as Deno Projects ### Mods as Deno Projects
When a mod's folder has a `deno.json`, its scripts are bundled and typechecked with it, so the mod can have its own When a mod's folder has a `deno.json`, its script is bundled and typechecked with it, so the mod can have its own
imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in imports and npm or JSR packages. Mods without one use the `deno.json` of the folder the build runs in, like the mods in
this repository. That config maps the API types, which scripts import as `cubi/server`, `cubi/client`, `cubi/shared`, this repository. That config maps the API types, which the script imports as `cubi/server`, `cubi/client`,
`cubi/worldgen` and `cubi/content`, and [`cubi/engine`](../misc/engine.md): `cubi/shared`, `cubi/worldgen` and `cubi/content`, and [`cubi/engine`](../misc/engine.md):
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
@@ -123,13 +114,9 @@ deno task build # packs every mod in mods/ into server_mo
``` ```
copper_tools.cubi copper_tools.cubi
manifest.json # with scripts 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 and loot table, and the config
scripts/server.js # each script bundled into one module script.js # the script bundled into one module
scripts/client.js
scripts/worldgen.js
scripts/shared.js
scripts/content.js
textures/<name>.png textures/<name>.png
textures/<name>.json # for animated textures textures/<name>.json # for animated textures
credits.md credits.md
@@ -139,6 +126,6 @@ copper_tools.cubi
- Packing the same mod twice gives the same bytes, so the file only changes when the mod does. - Packing the same mod twice gives the same bytes, so the file only changes when the mod does.
- `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 `scripts/content.js` 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** `scripts/server.js`, `scripts/worldgen.js`, `scripts/content.js` and the config, but - Players get a copy **without** the terrain's data and the config, but with the blocks the content phase registered in
with the blocks the content script registered in its `data.json`. See [Networking](../networking/index.md). its `data.json`. See [Networking](../networking/index.md).
+3 -3
View File
@@ -7,12 +7,12 @@ above them.
## Layers ## Layers
A client script registers layers during `setup`, with ids in its namespace: The client phase registers layers while it runs, with ids in its namespace:
```ts ```ts
import type { ClientContext } from "cubi/client"; import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.hud.register("thirst:water", { ctx.hud.register("thirst:water", {
on_render(g, hud) { on_render(g, hud) {
// a row of drops above the hunger, on the right // a row of drops above the hunger, on the right
@@ -48,7 +48,7 @@ side without raising it, and chat goes above that.
## Overlay Messages ## Overlay Messages
A server script's message with `{ overlay: true }` (see `Player.send_message`) isn't chat: it goes to the client scripts The server phase's message with `{ overlay: true }` (see `Player.send_message`) isn't chat: it goes to the client phases
that listen for it, and the base game shows it above the hotbar for a few seconds: that listen for it, and the base game shows it above the hotbar for a few seconds:
```ts ```ts
+8 -8
View File
@@ -43,8 +43,8 @@ interface Screen {
``` ```
The server can't open one directly. Like a NeoForge payload handler calling `setScreen`, the server sends a The server can't open one directly. Like a NeoForge payload handler calling `setScreen`, the server sends a
[mod channel](../networking/index.md) message, and the client script's handler opens it, as above. A screen that needs [mod channel](../networking/index.md) message, and the client phase's handler opens it, as above. A screen that needs to
to tell the server something sends a message back the same way. `ctx.ui.close()` closes the screen on top. A screen that tell the server something sends a message back the same way. `ctx.ui.close()` closes the screen on top. A screen that
throws is closed, with the error in the console. throws is closed, with the error in the console.
## Inventory Overlays ## Inventory Overlays
@@ -56,7 +56,7 @@ game's fishing minigame. `mods/recipe_viewer` is one.
```ts ```ts
import type { ClientContext } from "cubi/client"; import type { ClientContext } from "cubi/client";
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.ui.add_inventory_overlay({ ctx.ui.add_inventory_overlay({
on_render(g, screen) { on_render(g, screen) {
// screen is the inventory's box, and what's in the slot under the mouse // screen is the inventory's box, and what's in the slot under the mouse
@@ -168,7 +168,7 @@ pushes its own:
```ts ```ts
import { type ClientContext, TOOLTIP_PRIORITY } from "cubi/client"; 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) => { ctx.ui.add_item_tooltip((item, lines) => {
const value = ctx.items.sell_value(item.id, item.data); const value = ctx.items.sell_value(item.id, item.data);
if (value === undefined) return; if (value === undefined) return;
@@ -203,7 +203,7 @@ so a mod's can go between them:
## Reading Game State ## Reading Game State
Client scripts can read what the client knows, to show it: The client phase can read what the client knows, to show it:
```ts ```ts
ctx.player.name; ctx.player.name;
@@ -226,12 +226,12 @@ ctx.blocks.components(id); // the same for a block, like what a crab pot catches
ctx.fluids.ids(); // every fluid, in load order ctx.fluids.ids(); // every fluid, in load order
ctx.fluids.mod(id); // the name of the mod that added it ctx.fluids.mod(id); // the name of the mod that added it
ctx.fluids.name(fluid); // and color, exists and same, see ../resources/fluids.md#using-fluids ctx.fluids.name(fluid); // and color, exists and same, see ../resources/fluids.md#using-fluids
ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server scripts make aren't here ctx.loot.table(id); // a loot table file's JSON, or undefined. tables server phases make aren't here
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings
``` ```
`ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not during `setup`. `ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not while the client phase runs.
To draw blocks that move, like a shaft that turns, register a [visual](../blocks/visuals.md) with To draw blocks that move, like a shaft that turns, register a [visual](../blocks/visuals.md) with
`ctx.render.register_visual`. `ctx.render.register_visual`.
@@ -245,7 +245,7 @@ checks `g.key_pressed(ctx.options.key_inventory)` and calls `ctx.ui.close()`, th
The client and server APIs have types for these, but calling them throws for now: The client and server APIs have types for these, but calling them throws for now:
- **Forms** (`ctx.ui.message_form`, `action_form` and `modal_form` on the server): simple dialogs defined entirely by - **Forms** (`ctx.ui.message_form`, `action_form` and `modal_form` on the server): simple dialogs defined entirely by
the server script, like Bedrock's server forms. They'll be menus whose screens the engine draws. the server phase, like Bedrock's server forms. They'll be menus whose screens the engine draws.
- **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is - **Keybinds** (`ctx.input.bind`). Until then, an inventory overlay can check `g.key_pressed` while an inventory is
open. open.
+1 -1
View File
@@ -1,7 +1,7 @@
# Containers # Containers
A container is a list of item slots that the server owns and saves: a chest's contents, a furnace's input, fuel and A container is a list of item slots that the server owns and saves: a chest's contents, a furnace's input, fuel and
result, a player's inventory. Server scripts make and use them through `ctx.containers`. result, a player's inventory. The server phase makes and uses them through `ctx.containers`.
## Making Containers ## Making Containers
+8 -8
View File
@@ -2,9 +2,9 @@
Menus are how players use [containers](containers.md), like NeoForge's. A GUI has two halves: Menus are how players use [containers](containers.md), like NeoForge's. A GUI has two halves:
- The **menu** lives in the server script. It decides which slots the player can click, what goes in them, the numbers - The **menu** lives in the server phase. It decides which slots the player can click, what goes in them, the numbers
the screen shows, what its buttons do, and when it closes. the screen shows, what its buttons do, and when it closes.
- The **screen** lives in the client script. It only draws the menu and sends the player's clicks. - The **screen** lives in the client phase. It only draws the menu and sends the player's clicks.
Every click goes to the server, which applies it following the menu's rules, so a modified client can only do what the Every click goes to the server, which applies it following the menu's rules, so a modified client can only do what the
menu allows. Chests, furnaces, the smithing table and cooking pot are all menus, and the base game's curios slots are menu allows. Chests, furnaces, the smithing table and cooking pot are all menus, and the base game's curios slots are
@@ -12,13 +12,13 @@ part of [the player's inventory](#the-players-inventory).
## Registering a Menu Type ## Registering a Menu Type
A menu type is registered in the server script with a function that builds each menu when it opens, like NeoForge's A menu type is registered in the server phase with a function that builds each menu when it opens, like NeoForge's
`MenuType` and its server menu constructor. It gets the menu to build, whatever the code opening it passes, and the `MenuType` and its server menu constructor. It gets the menu to build, whatever the code opening it passes, and the
player: player:
```ts ```ts
// server.ts // server.ts
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => { const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => {
const container = ctx.containers.get(block.data.container)!; const container = ctx.containers.get(block.data.container)!;
menu.title = "Smelter"; menu.title = "Smelter";
@@ -158,12 +158,12 @@ interface MenuHandle {
## Screens ## Screens
The client script gives each of the mod's menu types a screen, like NeoForge's `RegisterMenuScreensEvent` and The client phase gives each of the mod's menu types a screen, like NeoForge's `RegisterMenuScreensEvent` and
`AbstractContainerScreen`. The function runs each time one opens, with the client's copy of the menu: `AbstractContainerScreen`. The function runs each time one opens, with the client's copy of the menu:
```ts ```ts
// client.ts // client.ts
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.ui.register_menu_screen("copper_tools:smelter", (menu) => ({ ctx.ui.register_menu_screen("copper_tools:smelter", (menu) => ({
width: 176, width: 176,
height: 166, height: 166,
@@ -215,8 +215,8 @@ console. A screen that throws is closed the same way.
## The Player's Inventory ## The Player's Inventory
The player's own inventory screen is a menu too, menu 0, like Minecraft's `InventoryMenu`: their inventory and crafting The player's own inventory screen is a menu too, menu 0, like Minecraft's `InventoryMenu`: their inventory and crafting
grid, always there while they play. Mods can add slots to it with `ctx.menus.extend_player_menu` during setup. The grid, always there while they play. Mods can add slots to it with `ctx.menus.extend_player_menu` while the server phase
function runs when each player joins: runs. The function runs when each player joins:
```ts ```ts
ctx.menus.extend_player_menu((menu, player) => { ctx.menus.extend_player_menu((menu, player) => {
+1 -1
View File
@@ -63,7 +63,7 @@ Hunger and health work like Minecraft's:
- A full stomach heals: quickly while there's saturation, slowly with at least 18 hunger. - A full stomach heals: quickly while there's saturation, slowly with at least 18 hunger.
- At 0 hunger, players lose health every 4 seconds, down to half a heart. - At 0 hunger, players lose health every 4 seconds, down to half a heart.
Server scripts can feed players directly, and read and change their hunger. See [Players](../entities/players.md). The server phase can feed players directly, and read and change their hunger. See [Players](../entities/players.md).
```ts ```ts
player.feed(4, 0.3); // like eating 4 nutrition with a 0.3 modifier player.feed(4, 0.3); // like eating 4 nutrition with a 0.3 modifier
+5 -5
View File
@@ -12,7 +12,7 @@ Like blocks, each kind of item is defined once. What players hold are **item sta
interface ItemStack { interface ItemStack {
readonly id: string; readonly id: string;
count: number; count: number;
data?: unknown; // any JSON value, set by server scripts data?: unknown; // any JSON value, set by server phases
} }
``` ```
@@ -22,7 +22,7 @@ tool. It's saved, and synced to clients as part of the container the stack is in
Two stacks of one item only merge into one when their `data` is the same, whatever order its keys are in, in an Two stacks of one item only merge into one when their `data` is the same, whatever order its keys are in, in an
inventory or on the ground. No data is the same as `{}`. inventory or on the ground. No data is the same as `{}`.
Stacks handed to server scripts are live: setting `count` or `data` on one changes the real stack, and a stack counted Stacks handed to server phases are live: setting `count` or `data` on one changes the real stack, and a stack counted
down to 0 is gone. down to 0 is gone.
## A Basic Item ## A Basic Item
@@ -97,7 +97,7 @@ they should stay inside the item's own shape, and an item drawn with a `model` c
### Worn Models ### Worn Models
`worn` says how an item looks on a player who wears it, like Bedrock's attachables. A server script says what a player `worn` says how an item looks on a player who wears it, like Bedrock's attachables. The server phase says what a player
wears with [`set_worn`](../entities/players.md#worn-items), and every client draws it on them. There's no third person wears with [`set_worn`](../entities/players.md#worn-items), and every client draws it on them. There's no third person
view, so players see what others wear, and what's on their own right arm in first person. Artifacts' power glove and view, so players see what others wear, and what's on their own right arm in first person. Artifacts' power glove and
feral claws (`mods/artifacts`) and the base game's giant chestplate are examples. feral claws (`mods/artifacts`) and the base game's giant chestplate are examples.
@@ -154,7 +154,7 @@ load the mod.
## Item Components ## Item Components
Like [block components](../blocks/components.md), item components give items behavior. The server script registers them: Like [block components](../blocks/components.md), item components give items behavior. The server phase registers them:
```ts ```ts
ctx.components.register_item<{ max_water: number }>("bworld:watering_can", { ctx.components.register_item<{ max_water: number }>("bworld:watering_can", {
@@ -257,6 +257,6 @@ player.give_item("bworld:carrot", 3); // what doesn't fit drops at their feet
player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this player.exchange_held({ id: "bworld:bucket", count: 1, data }); // one of the held item becomes this
``` ```
Client and shared scripts have `ctx.items.sell_value(id, data)` too, worked out the same way with that side's Client and shared phases have `ctx.items.sell_value(id, data)` too, worked out the same way with that side's
[fluid rules](../resources/fluids.md#rules), so a client can show what a full bottle of juice is worth, like the base [fluid rules](../resources/fluids.md#rules), so a client can show what a full bottle of juice is worth, like the base
game's [tooltip line](../gui/index.md#item-tooltips) does. game's [tooltip line](../gui/index.md#item-tooltips) does.
+2 -2
View File
@@ -38,7 +38,7 @@ The base game's tiers:
| `2` | iron | 7 | everything so far | | `2` | iron | 7 | everything so far |
Tool types don't have to be the base game's. A mod can add a `"sickle"` type and blocks with `"tool": "sickle"`, and a Tool types don't have to be the base game's. A mod can add a `"sickle"` type and blocks with `"tool": "sickle"`, and a
server script can check a held item's type with `ctx.items.tool(id)`, like the base game's `bworld:hoeable` does for server phase can check a held item's type with `ctx.items.tool(id)`, like the base game's `bworld:hoeable` does for
hoes. The base game's watering cans are tools of type `"watering_can"` that no block is mined with: they come in the hoes. The base game's watering cans are tools of type `"watering_can"` that no block is mined with: they come in the
same five tiers with the same durability, and each holds more water than the last (16, 24, 32, 48 and 64), set by its same five tiers with the same durability, and each holds more water than the last (16, 24, 32, 48 and 64), set by its
`bworld:watering_can` component. `bworld:watering_can` component.
@@ -52,5 +52,5 @@ dropping.
The damage a tool has taken is kept in its stack's `data.damage`, and a worn tool shows a bar under it in its slot, The damage a tool has taken is kept in its stack's `data.damage`, and a worn tool shows a bar under it in its slot,
going from green to red as it wears down. Upgrading a tool at the smithing table keeps its data, damage included. going from green to red as it wears down. Upgrading a tool at the smithing table keeps its data, damage included.
A server script wears a tool down with `ctx.items.damage(item, amount)`, which adds to the stack's `data.damage` and The server phase wears a tool down with `ctx.items.damage(item, amount)`, which adds to the stack's `data.damage` and
returns true when that used it up. It does nothing to items that aren't tools. The base game's death drops use it. returns true when that used it up. It does nothing to items that aren't tools. The base game's death drops use it.
+3 -3
View File
@@ -8,12 +8,12 @@ Each argument type reads its part of the text and suggests what could go there.
## Registering a Command ## Registering a Command
In the server script's `setup`: In the server phase:
```ts ```ts
import type { Player, ServerContext } from "cubi/server"; import type { Player, ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
const { literal, argument, types } = ctx.commands; const { literal, argument, types } = ctx.commands;
const heal = (player: Player, amount: number) => player.heal(amount); const heal = (player: Player, amount: number) => player.heal(amount);
@@ -102,7 +102,7 @@ ctx.commands.register("hello", {
Command names are `a-z`, `0-9` and `_`. Two mods registering the same name, or a mod registering one of the engine's, Command names are `a-z`, `0-9` and `_`. Two mods registering the same name, or a mod registering one of the engine's,
stops the server from starting. Every mod command can also be run as `/<mod id>:<name>`, like `/copper_tools:heal`. stops the server from starting. Every mod command can also be run as `/<mod id>:<name>`, like `/copper_tools:heal`.
Commands can only be registered during `setup`. Commands can only be registered while the server phase runs.
## The Engine's Commands ## The Engine's Commands
+7 -7
View File
@@ -2,7 +2,7 @@
A mod's config is its settings: the numbers and switches a server might want different without changing the mod, like A mod's config is its settings: the numbers and switches a server might want different without changing the mod, like
how fast a machine works, how far something reaches, or whether a feature is on. The mod lists them with their defaults how fast a machine works, how far something reaches, or whether a feature is on. The mod lists them with their defaults
in `config.json`, a server changes the ones it wants in a file of its own, and the server script reads the result as in `config.json`, a server changes the ones it wants in a file of its own, and the server phase reads the result as
`ctx.config`. It's like NeoForge's server configs. `ctx.config`. It's like NeoForge's server configs.
## `config.json` ## `config.json`
@@ -26,7 +26,7 @@ can change has to be in this file with its default.
## Reading It ## Reading It
`ctx.config` in the server script holds the settings, with the server's changes made: `ctx.config` in the server phase holds the settings, with the server's changes made:
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
@@ -36,17 +36,17 @@ interface Config {
fan: { push_distance: number; pull_distance: number }; fan: { push_distance: number; pull_distance: number };
} }
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
const config: Config = ctx.config; const config: Config = ctx.config;
ctx.log(`fans push things up to ${config.fan.push_distance} blocks away`); ctx.log(`fans push things up to ${config.fan.push_distance} blocks away`);
} }
``` ```
It's there from `setup` on, and stays the same for as long as the server runs. It's typed `any`, so give it a type of It's there from the server phase on, and stays the same for as long as the server runs. It's typed `any`, so give it a
your own like `Config` above. type of your own like `Config` above.
Only the server script has it. The copy of a mod players download leaves its config out, since a server's settings Only the server phase has it. The copy of a mod players download leaves its config out, since a server's settings aren't
aren't always the defaults. When players need to see one, the server sends it, like any other always the defaults. When players need to see one, the server sends it, like any other
[server data](../concepts/sides.md#what-each-side-knows): in a block's [client data](../blocks/tiledata.md), an item's [server data](../concepts/sides.md#what-each-side-knows): in a block's [client data](../blocks/tiledata.md), an item's
`data`, or over a [channel](../networking/index.md#mod-channels). `data`, or over a [channel](../networking/index.md#mod-channels).
+13 -12
View File
@@ -21,10 +21,10 @@ runs. When players join from another site, the confirm screen marks mods that ch
## Hooking ## Hooking
```ts ```ts
// server.ts: broken blocks drop twice // broken blocks drop twice
import { engine, hook } from "cubi/engine"; import { engine, hook } from "cubi/engine";
export function setup() { export function server() {
hook(engine.server.GameServer.prototype, "pop_item", { hook(engine.server.GameServer.prototype, "pop_item", {
after(game, [x, y, z, stack], entity) { after(game, [x, y, z, stack], entity) {
game.spawn_item(entity.x, entity.y, entity.z, stack.clone()); game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
@@ -48,16 +48,17 @@ made changes too. It returns a function that unhooks it.
outermost, and `after` hooks chain results. outermost, and `after` hooks chain results.
- A hook that throws is logged under its mod (`[my_mod] an after hook on GameServer.pop_item threw: ...`) and skipped. A - A hook that throws is logged under its mod (`[my_mod] an after hook on GameServer.pop_item threw: ...`) and skipped. A
`replace` hook that throws after calling `original` gives what `original` returned, so the method doesn't run twice. `replace` hook that throws after calling `original` gives what `original` returned, so the method doesn't run twice.
- `hook` only works while the mod's script loads or runs `setup`. Unhooking works any time. - `hook` only works while a phase runs. Unhooking works any time. Hook inside a phase, not at the script's top level,
which runs once on each side, in whichever phase imports the script first.
- Unhooking a method's last hook puts the original back, so a method nobody hooks costs nothing. - Unhooking a method's last hook puts the original back, so a method nobody hooks costs nothing.
## What's in `engine` ## What's in `engine`
| Side | Where | Like | | Side | Where | Like |
| -------- | -------------- | ----------------------------------------------------------------------------------------- | | -------- | ------------ | ----------------------------------------------------------------------------------------- |
| `common` | every script | `EverythingRegistry`, `ItemStack`, `Container`, `BlockRules`, `NoiseTerrain`, `physics` | | `common` | every phase | `EverythingRegistry`, `ItemStack`, `Container`, `BlockRules`, `NoiseTerrain`, `physics` |
| `server` | server scripts | `GameServer`, `ServerWorld`, `ServerPlayer`, `Entity`, `Mob`, `ModRuntime`, the mob goals | | `server` | server phase | `GameServer`, `ServerWorld`, `ServerPlayer`, `Entity`, `Mob`, `ModRuntime`, the mob goals |
| `client` | client scripts | `Client`, `LocalPlayer`, `ClientLevel`, `GameRenderer`, `Camera`, `GuiScreen` | | `client` | client phase | `Client`, `LocalPlayer`, `ClientLevel`, `GameRenderer`, `Camera`, `GuiScreen` |
The full lists are in `common/engine_modules.ts`, `server/game/engine_modules.ts` and `client/engine_modules.ts`. The The full lists are in `common/engine_modules.ts`, `server/game/engine_modules.ts` and `client/engine_modules.ts`. The
types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod runs on. `cubi/engine` types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod runs on. `cubi/engine`
@@ -67,13 +68,13 @@ also exports `game_version`, the version of the game that's running.
through: `engine.common.physics.move_body` is how every entity moves, on the server and on clients. through: `engine.common.physics.move_body` is how every entity moves, on the server and on clients.
- `#private` members can't be hooked. They're kept for things with rules that must hold, like a container's slots. - `#private` members can't be hooked. They're kept for things with rules that must hold, like a container's slots.
- Hooks reach one JavaScript realm. Chunk workers run their own copy of the engine, so a client hook doesn't change - Hooks reach one JavaScript realm. Chunk workers run their own copy of the engine, so a client hook doesn't change
meshing. The server generates chunks in worldgen workers, and each loads the worldgen scripts into its own copy, so meshing. The server generates chunks in worldgen workers, and each loads the worldgen phases into its own copy, so
hooks on the terrain (`engine.common.NoiseTerrain`) go in the worldgen script. A server script's hooks there only hooks on the terrain (`engine.common.NoiseTerrain`) go in the worldgen phase. The server phase's hooks there only
reach the few chunks the game generates itself, so the world would come out different in places. reach the few chunks the game generates itself, so the world would come out different in places.
## Performance ## Performance
Hooking is cheap to set up: hook in `setup`, before the game is running. Each call to a hooked method then goes through Hooking is cheap to set up: hook in a phase, before the game is running. Each call to a hooked method then goes through
a wrapper that runs its hooks, which is fine for something that happens now and then, like a block breaking. On a wrapper that runs its hooks, which is fine for something that happens now and then, like a block breaking. On
something called many times a tick, like `physics.move_body` or a method of every entity, the wrapper's cost adds up, something called many times a tick, like `physics.move_body` or a method of every entity, the wrapper's cost adds up,
and the engine can no longer inline the method into its callers. and the engine can no longer inline the method into its callers.
@@ -81,5 +82,5 @@ and the engine can no longer inline the method into its callers.
## Security ## Security
A server mod with engine access controls the game worker completely, but the worker still has no Deno permissions. A A server mod with engine access controls the game worker completely, but the worker still has no Deno permissions. A
client mod with it can change anything in the game page, which every client script can already reach. See client mod with it can change anything in the game page, which every client phase can already reach. See
[Security](../concepts/security.md). [Security](../concepts/security.md).
+1 -1
View File
@@ -16,7 +16,7 @@ ctx.system.current_tick; // ticks since the server started
``` ```
`run_timeout(fn, 0)` runs on the next tick, which is how a [before event](../concepts/events.md) gets something done `run_timeout(fn, 0)` runs on the next tick, which is how a [before event](../concepts/events.md) gets something done
after it. Timers aren't saved: they're gone after a restart, so set them up again in `setup`. after it. Timers aren't saved: they're gone after a restart, so set them up again in the server phase.
For work every tick, subscribe to the `tick` event. For work on a block, use a For work every tick, subscribe to the `tick` event. For work on a block, use a
[component](../blocks/components.md#ticking)'s `on_tick` or `on_second`. [component](../blocks/components.md#ticking)'s `on_tick` or `on_second`.
+11 -11
View File
@@ -15,8 +15,8 @@ client server
│ [another site: confirm screen] │ │ [another site: confirm screen] │
│ download every .cubi, check each one's │ │ download every .cubi, check each one's │
│ sha256, build the texture atlas, load │ │ sha256, build the texture atlas, load │
│ data in the listed order, run client │ │ data in the listed order, run shared │
│ scripts' setup, start chunk workers │ │ and client phases, start chunk workers │
│ │ │ │
│ ready { view_distance } │ │ ready { view_distance } │
├────────────────────────────────────────►│ ├────────────────────────────────────────►│
@@ -30,10 +30,10 @@ client server
- The client loads mods **in the order the server lists them**, so both sides register the same content the same way. - The client loads mods **in the order the server lists them**, so both sides register the same content the same way.
- Every `.cubi` is checked against its SHA-256 before it's opened, and scripts run from the checked bytes, so what runs - Every `.cubi` is checked against its SHA-256 before it's opened, and scripts run from the checked bytes, so what runs
is exactly what the server listed. is exactly what the server listed.
- Players get each mod's `.cubi` **without its server and worldgen scripts**. The server makes that copy when it starts, - Players get each mod's `.cubi` **without its terrain data and config**. Its script is all there, and players run its
named by its hash so it can be cached forever. shared and client phases. The server makes that copy when it starts, named by its hash so it can be cached forever.
- If any download, hash check or client `setup` fails, the client disconnects and says which mod failed. It never joins - If any download, hash check, shared or client phase fails, the client disconnects and says which mod failed. It never
with some mods missing. joins with some mods missing.
- Until `ready`, the connection isn't a player: nobody sees it, and anything else it sends is ignored. A client that - Until `ready`, the connection isn't a player: nobody sees it, and anything else it sends is ignored. A client that
doesn't send `ready` within 60 seconds is turned away. doesn't send `ready` within 60 seconds is turned away.
- Leaving a server reloads the page, so one server's mod code never stays loaded while playing on another. - Leaving a server reloads the page, so one server's mod code never stays loaded while playing on another.
@@ -43,8 +43,8 @@ away before anything is downloaded.
## The World ## The World
The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so worldgen scripts The server sends the world the way Minecraft Java does since 1.20.2. Clients never generate terrain, so they never run
stay on the server. the worldgen phase.
- Chunks are 16×16 and as tall as the dimension, sent whole, compressed, in batches, nearest first. The server paces - Chunks are 16×16 and as tall as the dimension, sent whole, compressed, in batches, nearest first. The server paces
batches by how fast each client says it loads them. batches by how fast each client says it loads them.
@@ -54,12 +54,12 @@ stay on the server.
close. close.
- Entities near a player are sent to them, and their movement follows. - Entities near a player are sent to them, and their movement follows.
For a mod, this means: what a client knows about the world is what's near its player. Tile data, `ctx.storage` and For a mod, this means: what a client knows about the world is what's near its player. Tile data and `ctx.storage` are
server code are never sent at all. See [Sides](../concepts/sides.md#what-each-side-knows). never sent at all. See [Sides](../concepts/sides.md#what-each-side-knows).
## Mod Channels ## Mod Channels
Mod channels let a mod's client and server scripts send each other JSON messages: Mod channels let a mod's client and server phases send each other JSON messages:
```ts ```ts
// server.ts // server.ts
+13 -13
View File
@@ -48,8 +48,8 @@ a tank.
## Rules ## Rules
A fluid's name, color and value can depend on its data. The mod's [shared script](../concepts/sides.md#shared-scripts) A fluid's name, color and value can depend on its data. The mod's [shared phase](../concepts/sides.md#shared) gives one
gives one of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`: of its fluids rules for that, like NeoForge's `FluidType.getDescription` and `FluidTintSource.colorAsStack`:
```ts ```ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
@@ -58,7 +58,7 @@ interface SyrupData {
tree?: string; tree?: string;
} }
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
ctx.fluids.register("copper_tools:syrup", { ctx.fluids.register("copper_tools:syrup", {
name(data) { name(data) {
const { tree } = (data ?? {}) as SyrupData; const { tree } = (data ?? {}) as SyrupData;
@@ -86,15 +86,15 @@ export function setup(ctx: SharedContext) {
`data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something `data` is the variant's, `undefined` when it has none, and mustn't be changed. A rule that throws, or returns something
that isn't a name, a color or a value, is logged and the JSON's is used. A fluid has one set of rules, from its own mod, that isn't a name, a color or a value, is logged and the JSON's is used. A fluid has one set of rules, from its own mod,
and they can only be registered during `setup`. and they can only be registered while the shared phase runs.
The rules are in the shared script because both sides need them: the server for tooltips, and clients to draw the fluid. The rules are in the shared phase because both sides need them: the server for tooltips, and clients to draw the fluid.
Shared scripts have `ctx.items.exists(id)`, `ctx.items.name(id)`, `ctx.items.components(id)` and The shared phase has `ctx.items.exists(id)`, `ctx.items.name(id)`, `ctx.items.components(id)` and
`ctx.items.sell_value(id, data?)` for rules that read an item, like syrup named after its tree. `ctx.items.sell_value(id, data?)` for rules that read an item, like syrup named after its tree.
## Using Fluids ## Using Fluids
Server and client scripts have `ctx.fluids`, which goes through the rules: Server and client phases have `ctx.fluids`, which goes through the rules:
```ts ```ts
const birch = { id: "copper_tools:syrup", data: { tree: "bworld:birch_log" } }; const birch = { id: "copper_tools:syrup", data: { tree: "bworld:birch_log" } };
@@ -106,10 +106,10 @@ ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is diff
``` ```
`ids` gives each fluid once, without data, so a fluid that's many things by its data, like syrup from each tree, is only `ids` gives each fluid once, without data, so a fluid that's many things by its data, like syrup from each tree, is only
there as plain `copper_tools:syrup`. Client scripts also have `ctx.fluids.mod(id)`, the name of the mod that added it, there as plain `copper_tools:syrup`. The client phase also has `ctx.fluids.mod(id)`, the name of the mod that added it,
like `ctx.items.mod`. like `ctx.items.mod`.
Shared scripts have `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a The shared phase has `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a
[recipe type](recipes.md#custom-recipe-types) that's found by a fluid. [recipe type](recipes.md#custom-recipe-types) that's found by a fluid.
## Containers ## Containers
@@ -146,11 +146,11 @@ tooltip says what's in it and how much, like "Birch Log Syrup, 250 mB".
A full one sells for its own `base_sell_value` and what its fluid is worth on top: the fluid's value for 1000 mB times A full one sells for its own `base_sell_value` and what its fluid is worth on top: the fluid's value for 1000 mB times
how much it holds, rounded up to a whole number. A jar of maple syrup worth 40 a bucket sells for 10, and the jar's own how much it holds, rounded up to a whole number. A jar of maple syrup worth 40 a bucket sells for 10, and the jar's own
value when it has one. It can't be sold if neither has a value. Server scripts get this from value when it has one. It can't be sold if neither has a value. The server phase gets this from
`ctx.items.sell_value(id, data)`, which the base game's shipping bin sells by. Client and shared scripts have it too, `ctx.items.sell_value(id, data)`, which the base game's shipping bin sells by. Client and shared phases have it too, and
and the base game shows it in [tooltips](../gui/index.md#item-tooltips). the base game shows it in [tooltips](../gui/index.md#item-tooltips).
A server script fills and empties one through its [fluid handler](#fluid-handlers), and `ctx.items.fluid_capacity(id)` The server phase fills and empties one through its [fluid handler](#fluid-handlers), and `ctx.items.fluid_capacity(id)`
says how much one holds. says how much one holds.
## Fluid Handlers ## Fluid Handlers
+3 -3
View File
@@ -2,7 +2,7 @@
A loot table says what something gives, as data: a block when it's broken, a mob when it dies, a fishing rod when it A loot table says what something gives, as data: a block when it's broken, a mob when it dies, a fishing rod when it
reels something in, a crop when it's picked, and a container a script fills, like a chest in a ruin. They work like reels something in, a crop when it's picked, and a container a script fills, like a chest in a ruin. They work like
Minecraft's, and mods can add their own conditions and functions from a server script. Minecraft's, and mods can add their own conditions and functions from the server phase.
## Files and Ids ## Files and Ids
@@ -174,12 +174,12 @@ Those become the `bworld:season`, `bworld:biome` and `bworld:time` conditions, w
## From a Script ## From a Script
Server scripts roll tables, fill containers, and add conditions, functions and changes of their own: The server phase rolls tables, fills containers, and adds conditions, functions and changes of its own:
```ts ```ts
import type { ServerContext } from "cubi/server"; import type { ServerContext } from "cubi/server";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
// "condition": "my_mod:night" in any table // "condition": "my_mod:night" in any table
ctx.loot.register_condition("my_mod:night", (_params, context) => ctx.world.time % 24000 > 13000); ctx.loot.register_condition("my_mod:night", (_params, context) => ctx.world.time % 24000 > 13000);
+22 -23
View File
@@ -25,7 +25,7 @@ pattern fits anywhere in the grid.
## Smelting: `bworld:smelting` and `bworld:fuel` ## Smelting: `bworld:smelting` and `bworld:fuel`
For the furnace. They're the base game's own types, registered by its shared script like For the furnace. They're the base game's own types, registered by its shared phase like
[any mod's](#custom-recipe-types): [any mod's](#custom-recipe-types):
```json ```json
@@ -53,7 +53,7 @@ long something burns.
## Smithing: `bworld:smithing` ## Smithing: `bworld:smithing`
For the smithing table, which upgrades a tool. It's the base game's own type, registered by its shared script like For the smithing table, which upgrades a tool. It's the base game's own type, registered by its shared phase like
[any mod's](#custom-recipe-types): [any mod's](#custom-recipe-types):
```json ```json
@@ -76,7 +76,7 @@ are an error.
## Stonecutting: `bworld:stonecutting` ## Stonecutting: `bworld:stonecutting`
For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared script: For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared phase:
```json ```json
{ {
@@ -95,9 +95,8 @@ uses up one of the input.
## Juicing: `bworld:juicing` ## Juicing: `bworld:juicing`
For the juicer, which presses an item into a fluid. The base game registers one from its For the juicer, which presses an item into a fluid. The base game registers one from its
[shared script](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the [shared phase](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the juice
juice named after it, so most mods never write one. A file can add one for anything else, or make something other than named after it, so most mods never write one. A file can add one for anything else, or make something other than juice:
juice:
```json ```json
{ {
@@ -118,7 +117,7 @@ makes. The juicer uses the first recipe that takes the item.
## Fermenting: `bworld:fermentable` ## Fermenting: `bworld:fermentable`
A fluid that ferments into another over time, like juice into wine. The base game registers one from its A fluid that ferments into another over time, like juice into wine. The base game registers one from its
[shared script](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file [shared phase](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file
can add one for anything else: can add one for anything else:
```json ```json
@@ -165,7 +164,7 @@ Use a tag rather than listing ids when other mods might have more of the same th
Any `type` with a namespace is a mod's own, like `bworld:smithing` for the smithing table. The engine only stores these Any `type` with a namespace is a mod's own, like `bworld:smithing` for the smithing table. The engine only stores these
recipes. What their fields mean is up to the mod, which registers the type from its recipes. What their fields mean is up to the mod, which registers the type from its
[shared script](../concepts/sides.md#shared-scripts), like NeoForge's `RecipeType` with its serializer: [shared phase](../concepts/sides.md#shared), like NeoForge's `RecipeType` with its serializer:
```ts ```ts
import type { ItemStack, SharedContext } from "cubi/shared"; import type { ItemStack, SharedContext } from "cubi/shared";
@@ -176,7 +175,7 @@ interface SmithingRecipe {
result: string; result: string;
} }
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
ctx.recipes.register_type<SmithingRecipe, { tool: ItemStack; material: ItemStack }>("bworld:smithing", { ctx.recipes.register_type<SmithingRecipe, { tool: ItemStack; material: ItemStack }>("bworld:smithing", {
// the json checked and turned into what matches and the machine use // the json checked and turned into what matches and the machine use
parse: (json, read) => ({ parse: (json, read) => ({
@@ -205,7 +204,7 @@ are checked, throwing with the name it's given, like `"result"` or `"ingredients
| `read.fluid_stack(value, name)` | `{ fluid: { id, data }, amount }` of a fluid that exists, in mB. | | `read.fluid_stack(value, name)` | `{ fluid: { id, data }, amount }` of a fluid that exists, in mB. |
| `read.positive_int(value, name)` | A whole number, at least 1, like a time in ticks. | | `read.positive_int(value, name)` | A whole number, at least 1, like a time in ticks. |
Then server, client and shared scripts look recipes up by what's in the machine, like NeoForge's Then server, client and shared phases look recipes up by what's in the machine, like NeoForge's
`RecipeManager.getRecipeFor`: `RecipeManager.getRecipeFor`:
```ts ```ts
@@ -214,25 +213,25 @@ ctx.recipes.all<SmithingRecipe>("bworld:smithing"); // every one, in load order
``` ```
`find` gives the first recipe, in load order, that `matches` says the input makes. Both give the recipes as `parse` made `find` gives the first recipe, in load order, that `matches` says the input makes. Both give the recipes as `parse` made
them, not copies, so they aren't to be changed. A type can only be registered during `setup`, in the mod's own them, not copies, so they aren't to be changed. A type can only be registered while the shared phase runs, in the mod's
namespace. Other mods can add recipes of your type too, as long as they depend on your mod. own namespace. Other mods can add recipes of your type too, as long as they depend on your mod.
A recipe of a type no mod registers, like a misspelled one, stops the first mod with one from loading once every shared A recipe of a type no mod registers, like a misspelled one, stops the first mod with one from loading once every shared
script has set up, since nothing would ever read it. script has set up, since nothing would ever read it.
`ctx.recipes.list(type?)` gives recipes as their JSON instead, copies in load order. It's how the recipe viewer shows `ctx.recipes.list(type?)` gives recipes as their JSON instead, copies in load order. It's how the recipe viewer shows
every mod's types, and how a shared script makes recipes from another type's, see below. every mod's types, and how the shared phase makes recipes from another type's, see below.
## Recipes From Scripts ## Recipes From Scripts
A recipe that follows from other data, like one for every item with a component, can be made in the mod's A recipe that follows from other data, like one for every item with a component, can be made in the mod's
[shared script](../concepts/sides.md#shared-scripts) instead of written out as files. `ctx.recipes.register(type, json)` [shared phase](../concepts/sides.md#shared) instead of written out as files. `ctx.recipes.register(type, json)` adds one
adds one like a file in `recipes/` with that `type` would, with the rest of its fields from `json`: like a file in `recipes/` with that `type` would, with the rest of its fields from `json`:
```ts ```ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
// a sieve recipe for every item that says what it sifts into // a sieve recipe for every item that says what it sifts into
for (const id of ctx.items.ids()) { for (const id of ctx.items.ids()) {
const sifts = ctx.items.components(id)["copper_tools:siftable"] as { into: string } | undefined; const sifts = ctx.items.components(id)["copper_tools:siftable"] as { into: string } | undefined;
@@ -241,15 +240,15 @@ export function setup(ctx: SharedContext) {
} }
``` ```
Shared scripts run on the server and on every player's client, from the same data, so every side makes the same recipes The shared phase runs on the server and on every player's client, from the same data, so every side makes the same
and nothing is sent: the crafting grid, `ctx.recipes.list` in server and client scripts, and recipe viewers see them recipes and nothing is sent: the crafting grid, `ctx.recipes.list` in server and client phases, and recipe viewers see
like any other. That's also why it's only in shared scripts. Recipes can only be registered during `setup`, before any them like any other. That's also why it's only in the shared phase. Recipes can only be registered while it runs, before
server or client script sets up, and one is checked like a file would be: a broken one, or a second smelting recipe for any server or client phase sets up, and one is checked like a file would be: a broken one, or a second smelting recipe
the same input, throws, which stops the mod loading. for the same input, throws, which stops the mod loading.
`ctx.recipes.list(type?)` reads the recipes there are so far, copies in load order, like the client's: every mod's `ctx.recipes.list(type?)` reads the recipes there are so far, copies in load order, like the client's: every mod's
`recipes/` files, and what the shared scripts that set up before this one registered. Dependencies set up first, so a `recipes/` files, and what the shared phases that set up before this one registered. Dependencies set up first, so a mod
mod can make recipes of its own from another mod's, like a machine of its own for every one of the base game's juicing can make recipes of its own from another mod's, like a machine of its own for every one of the base game's juicing
recipes: recipes:
```ts ```ts
+2 -2
View File
@@ -89,7 +89,7 @@ A tag nobody defines is a check-mods error there.
## Using Tags in Scripts ## Using Tags in Scripts
Server and client scripts both have `ctx.tags`. Tags can be written with or without their `#`: Server and client phases both have `ctx.tags`. Tags can be written with or without their `#`:
```ts ```ts
ctx.tags.has("items", "bworld:planks", item.id); // whether it's in the tag ctx.tags.has("items", "bworld:planks", item.id); // whether it's in the tag
@@ -102,7 +102,7 @@ ctx.tags.expand(["#bworld:planks", "bworld:stick"]); // every item a recipe's ch
`has` and `get` treat a tag nobody defines as empty. `has` and `get` treat a tag nobody defines as empty.
Mods' own [recipe types](recipes.md#custom-recipe-types) should take tags like the base game's do. `expand` turns a Mods' own [recipe types](recipes.md#custom-recipe-types) should take tags like the base game's do. `expand` turns a
choice into the items it stands for, so the mod's server script can check and match them: choice into the items it stands for, so the mod's server phase can check and match them:
```ts ```ts
const ingredient = ctx.tags.expand(json.ingredient); // "#bworld:planks" -> ["bworld:oak_planks", "bworld:spruce_planks", ...] const ingredient = ctx.tags.expand(json.ingredient); // "#bworld:planks" -> ["bworld:oak_planks", "bworld:spruce_planks", ...]
+9 -9
View File
@@ -93,19 +93,19 @@ summer in `desert`.
Scripts read the season where something is: Scripts read the season where something is:
| Where | Biome | Season | | Where | Biome | Season |
| ----------------------------------------------- | ----------------------------- | ------------------------------ | | ---------------------------------------------- | ----------------------------- | ------------------------------ |
| a block in a server component, like `on_tick` | `block.biome` | `block.season` | | a block in a server component, like `on_tick` | `block.biome` | `block.season` |
| an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` | | an entity from `ctx.world.spawn_entity` | `entity.biome` | `entity.season` |
| a player, on the server | `player.biome` | `player.season` | | a player, on the server | `player.biome` | `player.season` |
| any block, in server, shared and client scripts | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` | | any block, in server, shared and client phases | `ctx.world.biome_at(x, y, z)` | `ctx.world.season_at(x, y, z)` |
| the player on this client | `ctx.player.biome` | `ctx.player.season` | | the player on this client | `ctx.player.biome` | `ctx.player.season` |
| a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | | | a feature's chunk, see [Features](index.md) | `chunk.biome_at(x, y, z)` | |
`biome_at` is NeoForge's `level.getBiome(pos)`. Entities and players go by the block their feet are in, like `biome_at` is NeoForge's `level.getBiome(pos)`. Entities and players go by the block their feet are in, like
`level.getBiome(entity.blockPosition())`. Above and below the world it's the biome at its top or bottom. On the server `level.getBiome(entity.blockPosition())`. Above and below the world it's the biome at its top or bottom. On the server
every block has a biome: in a chunk that isn't loaded it's what generation makes there, which takes a while the first every block has a biome: in a chunk that isn't loaded it's what generation makes there, which takes a while the first
time. In shared rules and client scripts it's what that client has loaded, and `undefined` where it has nothing. time. In shared rules and client phases it's what that client has loaded, and `undefined` where it has nothing.
```ts ```ts
ctx.components.register_block("my_mod:crop", { ctx.components.register_block("my_mod:crop", {
+6 -6
View File
@@ -1,7 +1,7 @@
# World Generation # World Generation
The server generates chunks from the world's seed, and players get the finished chunks. Mods add to what it generates The server generates chunks from the world's seed, and players get the finished chunks. Mods add to what it generates
with ores (data) and features (a worldgen script). with ores (data) and features (the worldgen phase).
## Determinism ## Determinism
@@ -13,7 +13,7 @@ isn't the same, trees are cut off at chunk borders.
- **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's - **Never use `Math.random`, `Date`, `performance.now` or anything else that changes between runs.** Use the chunk's
`rng` and noise helpers, which are seeded from the world's seed. `rng` and noise helpers, which are seeded from the world's seed.
- Don't keep state between chunks. Chunks generate in any order, and in several worldgen workers at once, each with its - Don't keep state between chunks. Chunks generate in any order, and in several worldgen workers at once, each with its
own copy of the worldgen scripts (and the game generates a few itself). own copy of the worldgen phases (and the game generates a few itself).
- Adding or removing a mod's features only changes chunks that haven't been generated yet, with seams where they meet - Adding or removing a mod's features only changes chunks that haven't been generated yet, with seams where they meet
saved ones. saved ones.
@@ -76,12 +76,12 @@ order they were registered. The base game's trees are in `vegetal_decoration`, s
### Code Features ### Code Features
The worldgen script registers them: The worldgen phase registers them:
```ts ```ts
import type { WorldgenContext } from "cubi/worldgen"; import type { WorldgenContext } from "cubi/worldgen";
export function setup(gen: WorldgenContext) { export function worldgen(gen: WorldgenContext) {
gen.register_feature("copper_tools:boulders", (chunk) => { gen.register_feature("copper_tools:boulders", (chunk) => {
if (chunk.rng.next() > 0.1) return; if (chunk.rng.next() > 0.1) return;
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16); const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
@@ -125,7 +125,7 @@ cell agrees on where its tree is.
`set_block` can write up to one chunk away, so a tree near the border can grow into the next chunk. Writes into another `set_block` can write up to one chunk away, so a tree near the border can grow into the next chunk. Writes into another
chunk only fill air, so the result doesn't depend on which chunk generates first. chunk only fill air, so the result doesn't depend on which chunk generates first.
Generated blocks don't run `on_create`, and worldgen scripts can't use the server or client API. Generated blocks don't run `on_create`, and worldgen phases can't use the server or client API.
### Data Features ### Data Features
@@ -185,7 +185,7 @@ Built in names work with or without `minecraft:`.
### Types and Modifiers in Code ### Types and Modifiers in Code
A worldgen script can add types and placement modifiers for data features to use, by id: The worldgen phase can add types and placement modifiers for data features to use, by id:
```ts ```ts
gen.register_feature_type<{ block: string; height: number }>("copper_tools:pillar", (chunk, config, origin) => { gen.register_feature_type<{ block: string; height: number }>("copper_tools:pillar", (chunk, config, origin) => {
+49 -44
View File
@@ -24,11 +24,11 @@ A mod is built from up to three layers. Most mods only need the first one or two
## Status ## Status
**Built:** the mod loader and `.cubi` files (packing, loading from `server_mods/`, sending players a copy without the **Built:** the mod loader and `.cubi` files (packing, loading from `server_mods/`, sending players a copy without the
server and worldgen scripts), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the terrain's data and the config), delivery to clients (hashed downloads, the confirm screen for other sites, credits), the
data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models, data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models,
ores), server scripts (components, events, commands, timers, storage, recipes, containers, displayed items), menus like ores), the server phase (components, events, commands, timers, storage, recipes, containers, displayed items), menus
NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the like NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the
player's inventory as menu 0, which mods can add slots to), client scripts (item and recipe lookups, plain screens, player's inventory as menu 0, which mods can add slots to), the client phase (item and recipe lookups, plain screens,
inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior
and screens as a mod, world time, and worn items (an item's `worn` model, `player.set_worn`, synced to every client and and screens as a mod, world time, and worn items (an item's `worn` model, `player.set_worn`, synced to every client and
drawn on other players and on the first person arm). See [Menus](modding/inventories/menus.md), drawn on other players and on the first person arm). See [Menus](modding/inventories/menus.md),
@@ -41,12 +41,17 @@ The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.t
**In the API types but throwing:** forms, keybinds, `g.slider`, `register_terrain`. **In the API types but throwing:** forms, keybinds, `g.slider`, `register_terrain`.
**Content scripts** are built, the first part of common scripts: `scripts.content` with `ctx.blocks.register`, see **One script per mod** is built: the manifest's `main` names it, and its exports are its phases (`content`, `shared`,
[Content Scripts](#content-scripts-as-built). The code is in `common/content_scripts.ts`, `common/mod_api/content.ts`, `server`, `client`, `worldgen`), like NeoForge's one jar with setup events by phase and by dist. It's bundled into one
`server/content_worker.ts`, `server/load_mods.ts` and `tools/check_mods.ts`. module that goes everywhere, players included, and each side runs only its own phases through `run_phase` in
`common/mod_loader.ts`. See [Sides](modding/concepts/sides.md).
**Not built at all:** the rest of common scripts (items and models from code, reading other mods' content), the registry **The content phase** is built, the first part of the common phase: `content` with `ctx.blocks.register`, see
freeze and hash, overrides. [The Content Phase](#the-content-phase-as-built). The code is in `common/content_scripts.ts`,
`common/mod_api/content.ts`, `server/content_worker.ts`, `server/load_mods.ts` and `tools/check_mods.ts`.
**Not built at all:** the rest of the common phase (items and models from code, reading other mods' content), the
registry freeze and hash, overrides.
**Engine access** is built (phase 3): `cubi/engine`, `hook`, `engine_access` and its checks, and `physics` as the first **Engine access** is built (phase 3): `cubi/engine`, `hook`, `engine_access` and its checks, and `physics` as the first
plain object mods can hook. See [Engine Access](modding/misc/engine.md). The code is in `common/hooks.ts`, plain object mods can hook. See [Engine Access](modding/misc/engine.md). The code is in `common/hooks.ts`,
@@ -66,37 +71,37 @@ plain object mods can hook. See [Engine Access](modding/misc/engine.md). The cod
## Planned API ## Planned API
### Common Scripts ### The Common Phase
A fourth script, `scripts.common`, run on the server and on every client while content loads, right after the mod's own A phase, `common`, run on the server and on every client while content loads, right after the mod's own JSON is
JSON is registered. Data would then be shorthand for code: loading `blocks/copper_block.json` would do exactly what registered. Data would then be shorthand for code: loading `blocks/copper_block.json` would do exactly what
`ctx.blocks.register(...)` with the same object does, so content that's easier to generate (every color of wool) or `ctx.blocks.register(...)` with the same object does, so content that's easier to generate (every color of wool) or
depends on other mods can be written as code. depends on other mods can be written as code.
#### Content Scripts, as Built #### The Content Phase, as Built
The first part is built differently from the rest of this section: `scripts.content` with only `ctx.blocks.register`, The first part is built differently from the rest of this section: `content` with only `ctx.blocks.register`, run
run **once, on the server**, while it loads mods, instead of on both sides. What it registers is added to the mod's data **once, on the server**, while it loads mods, instead of on both sides. What it registers is added to the mod's data as
as if it were files, so everything downstream needs no change: if it were files, so everything downstream needs no change:
- `check-mods` runs it from the mod's folder before checking references, so tags, recipes and worldgen files can name - `check-mods` runs it from the mod's folder before checking references, so tags, recipes and worldgen files can name
its blocks. Packing leaves its blocks out of `data.json`. its blocks. Packing leaves its blocks out of `data.json`.
- The server runs it on each `.cubi` before its reference check, in a worker without permissions, since the host that - The server runs it on each `.cubi` before its reference check, in a worker without permissions, since the host that
loads mods has file access. loads mods has file access.
- Players get the blocks in the copy of `data.json` they download and never run the script, like Luanti's clients get - Players get the blocks in the copy of `data.json` they download and never run the phase, like Luanti's clients get
node definitions from the server. The server and its players can't disagree, so this part needs no freeze or hash. node definitions from the server. The server and its players can't disagree, so this part needs no freeze or hash.
- Worldgen workers get the blocks in the worldgen bundle, which is built from the mods' data, and number them the same - Worldgen workers get the blocks in the worldgen bundle, which is built from the mods' data, and number them the same
way, like Luanti's mapgen threads get a copy of the finished registrations instead of running mods' code again. way, like Luanti's mapgen threads get a copy of the finished registrations instead of running mods' code again.
Since it runs per mod, before any registry exists, it can't read other mods' content or the server's config yet. Reading Since it runs per mod, before any registry exists, it can't read other mods' content or the server's config yet. Reading
other mods' content would mean running content scripts in load order with a view of what came before. other mods' content would mean running content phases in load order with a view of what came before.
```ts ```ts
import type { CommonContext } from "bworld/common"; import type { CommonContext } from "bworld/common";
const COLORS = ["white", "red", "green", "blue", "black"]; const COLORS = ["white", "red", "green", "blue", "black"];
export function setup(ctx: CommonContext) { export function common(ctx: CommonContext) {
for (const color of COLORS) { for (const color of COLORS) {
ctx.blocks.register({ ctx.blocks.register({
id: `wool:${color}_wool`, id: `wool:${color}_wool`,
@@ -140,10 +145,10 @@ interface RecipeRegistry {
``` ```
- Definitions are checked exactly like JSON files, and a problem is a load error naming the mod. - Definitions are checked exactly like JSON files, and a problem is a load error naming the mod.
- Common scripts only run during loading and can't reach the world or players. They get the same `ctx` on both sides, so - The common phase only runs during loading and can't reach the world or players. They get the same `ctx` on both sides,
they can't accidentally register different things. so they can't accidentally register different things.
- `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking - `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking
its recipes in `setup`. `shaped` becomes short for `bworld:shaped`. Shared scripts can now register types with its recipes itself. `shaped` becomes short for `bworld:shaped`. The shared phase can now register types with
`ctx.recipes.register_type`, and every one of the base game's and create's are. `ctx.recipes.register_type`, and every one of the base game's and create's are.
### The Freeze and the Registry Hash ### The Freeze and the Registry Hash
@@ -151,7 +156,7 @@ interface RecipeRegistry {
After content loads, the registries close: numeric ids, block items and recipe indexes are made then, and registering After content loads, the registries close: numeric ids, block items and recipe indexes are made then, and registering
later throws. Then each side hashes its registries (every id and its definition), and the client sends the hash with later throws. Then each side hashes its registries (every id and its definition), and the client sends the hash with
`ready`. A mismatch turns the player away naming the first thing that differs, instead of letting them play with `ready`. A mismatch turns the player away naming the first thing that differs, instead of letting them play with
mismatched blocks. This matters once common scripts exist, since code can register different things on each side. mismatched blocks. This matters once the common phase exists, since code can register different things on each side.
### Overrides ### Overrides
@@ -192,10 +197,10 @@ asks for it in its manifest:
``` ```
```ts ```ts
// server.ts: broken blocks drop twice // broken blocks drop twice
import { engine, hook } from "cubi/engine"; import { engine, hook } from "cubi/engine";
export function setup() { export function server() {
hook(engine.server.GameServer.prototype, "pop_item", { hook(engine.server.GameServer.prototype, "pop_item", {
after(game, [x, y, z, stack], entity) { after(game, [x, y, z, stack], entity) {
game.spawn_item(entity.x, entity.y, entity.z, stack.clone()); game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
@@ -218,13 +223,13 @@ function hook<T, K extends keyof T>(target: T, method: K, handlers: {
}): () => void; // unhook }): () => void; // unhook
``` ```
- `engine` holds the live modules on each side: `engine.common` everywhere, `engine.server` in server scripts, - `engine` holds the live modules on each side: `engine.common` everywhere, `engine.server` in the server phase,
`engine.client` in client scripts. The engine puts them on the global object at startup, and `cubi/engine` in a mod's `engine.client` in the client phase. The engine puts them on the global object at startup, and `cubi/engine` in a
bundle is a shim that reads them, so a hook on a prototype changes every instance already made. mod's bundle is a shim that reads them, so a hook on a prototype changes every instance already made.
- Types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod will run on. - Types are the engine's own source, so `check-mods` typechecks against exactly the engine the mod will run on.
- Several mods can hook one method: `before` hooks run in priority order, `replace` hooks nest, `after` hooks chain - Several mods can hook one method: `before` hooks run in priority order, `replace` hooks nest, `after` hooks chain
results. A hook that throws is logged under its mod and skipped. results. A hook that throws is logged under its mod and skipped.
- `hook` only works while a mod's script loads or runs `setup`, which is how it knows the mod. Each side clears every - `hook` only works while a mod's script loads or runs a phase, which is how it knows the mod. Each side clears every
hook before it loads mods, so tests and a client joining another server start clean. hook before it loads mods, so tests and a client joining another server start clean.
- The wrapper is rebuilt when hooks change, with only the steps they use, and the last unhook puts the original back. - The wrapper is rebuilt when hooks change, with only the steps they use, and the last unhook puts the original back.
- Module exports can't be reassigned, so functions mods may want to change move onto plain objects the engine calls - Module exports can't be reassigned, so functions mods may want to change move onto plain objects the engine calls
@@ -345,23 +350,23 @@ How the server sends the world, like Minecraft Java since 1.20.2. The code is in
`WORLDGEN_WORKERS` on the dedicated server, 0 for none. Each tick the game asks them for what the nearest chunks each `WORLDGEN_WORKERS` on the dedicated server, 0 for none. Each tick the game asks them for what the nearest chunks each
player is waiting for are built from, nearest first, and only sends a chunk once they've made it; entities and players player is waiting for are built from, nearest first, and only sends a chunk once they've made it; entities and players
in a chunk they haven't made yet wait for it, like Minecraft's in chunks that aren't loaded. Each worker gets the in a chunk they haven't made yet wait for it, like Minecraft's in chunks that aren't loaded. Each worker gets the
worldgen bundle (`common/worldgen_bundle.ts`: the mods' data generation reads and their worldgen scripts), so it makes worldgen bundle (`common/worldgen_bundle.ts`: the mods' data generation reads and their scripts, whose worldgen phase
the same chunks as the game. The host starts them, since the game has no permissions to (see it runs), so it makes the same chunks as the game. The host starts them, since the game has no permissions to (see
`server/worldgen_workers.ts`), and they talk to the game through ports. Whatever needs a chunk right away, like a mod `server/worldgen_workers.ts`), and they talk to the game through ports. Whatever needs a chunk right away, like a
script reading a block somewhere far, still generates it on the game thread: `/tps` shows how many chunks that was in mod's server phase reading a block somewhere far, still generates it on the game thread: `/tps` shows how many chunks
the last minute. `tools/chunk_loading_bench.ts` measures a player arriving somewhere new. that was in the last minute. `tools/chunk_loading_bench.ts` measures a player arriving somewhere new.
## Phases ## Phases
Each phase ends with every test passing and the game playable. Each phase ends with every test passing and the game playable.
**Phase 1: loading and common scripts.** Partly done: content scripts register blocks, see **Phase 1: loading and the common phase.** Partly done: the content phase registers blocks, see
[Content Scripts](#content-scripts-as-built). `scripts.common` bundled like the client script and run on both sides [The Content Phase](#the-content-phase-as-built). `common` run on both sides between each mod's data and the next mod.
between each mod's data and the next mod. `CommonContext`, with the JSON loader going through the same functions. The `CommonContext`, with the JSON loader going through the same functions. The freeze and the registry hash. Recipe types
freeze and the registry hash. Recipe types as ids with `register_type`. Check: a test mod registers content from code, as ids with `register_type`. Check: a test mod registers content from code, and the server and a client end up with
and the server and a client end up with equal registries and hashes. equal registries and hashes.
**Phase 2: overrides.** `override` and `extend` in common scripts, `overrides/*.json`, `recipes.remove`, and the **Phase 2: overrides.** `override` and `extend` in the common phase, `overrides/*.json`, `recipes.remove`, and the
`check-mods` rules. Check: a test mod adds a component to `bworld:grass_block`, changes `bworld:glass`'s toughness and `check-mods` rules. Check: a test mod adds a component to `bworld:grass_block`, changes `bworld:glass`'s toughness and
replaces the chest recipe, on both sides and in the hash. replaces the chest recipe, on both sides and in the hash.
@@ -377,9 +382,9 @@ and dropped, containers clicked, players moving between chunks, entities.
rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking. rules become something `mods/bworld` sets, with the engine asking it on both sides so clients still predict breaking.
Check: all tests pass unchanged, and old saves still load. Check: all tests pass unchanged, and old saves still load.
**Phase 6: world generation.** Done, as data instead of a worldgen script with `register_terrain`: noises, density **Phase 6: world generation.** Done, as data instead of `register_terrain` in the worldgen phase: noises, density
functions, noise settings and biome sources in `mods/bworld/worldgen/` (see [Terrain](modding/worldgen/terrain.md)), functions, noise settings and biome sources in `mods/bworld/worldgen/` (see [Terrain](modding/worldgen/terrain.md)),
features that are code or data (bworld's trees and cacti are code, in its worldgen script), and generation in worldgen features that are code or data (bworld's trees and cacti are code, in its worldgen phase), and generation in worldgen
workers (see [Chunk Streaming](#chunk-streaming)). The golden fixture checked every step made the same world block for workers (see [Chunk Streaming](#chunk-streaming)). The golden fixture checked every step made the same world block for
block, and the server refuses to start without the `bworld:overworld` generator. block, and the server refuses to start without the `bworld:overworld` generator.
@@ -404,8 +409,8 @@ saved before any of this plays exactly the same.
every biome border. A `minecraft:multi_noise` source could exist next to the rules, for mods and imported datapacks every biome border. A `minecraft:multi_noise` source could exist next to the rules, for mods and imported datapacks
that want it. that want it.
- **Should `register_terrain` stay?** It's still in the worldgen API, and only throws. Data covers bworld's terrain, but - **Should `register_terrain` stay?** It's still in the worldgen API, and only throws. Data covers bworld's terrain, but
a mod might want a generator that isn't density functions at all, like a flat or skyblock world. Keeping it means the a mod might want a generator that isn't density functions at all, like a flat or skyblock world. Keeping it costs
worldgen bundle also carries a terrain script, which workers can load the same way as features. Otherwise it goes. little, since workers already run each mod's worldgen phase, where it would be registered. Otherwise it goes.
- **Importing Minecraft's terrain.** Datapacks' noise settings assume a world from -64 to 320 and Minecraft's noises. - **Importing Minecraft's terrain.** Datapacks' noise settings assume a world from -64 to 320 and Minecraft's noises.
The formats are close enough that an importer could translate them, but the result wouldn't look like Minecraft's. Not The formats are close enough that an importer could translate them, but the result wouldn't look like Minecraft's. Not
a goal for now. a goal for now.
+1 -7
View File
@@ -9,11 +9,5 @@
], ],
"game_version": ">=0.1.0", "game_version": ">=0.1.0",
"credits": "CREDITS.md", "credits": "CREDITS.md",
"scripts": { "main": "scripts/main.ts"
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"shared": "scripts/shared.ts",
"worldgen": "scripts/worldgen.ts",
"content": "scripts/content.ts"
}
} }
+1 -1
View File
@@ -29,7 +29,7 @@ const HEIGHT = 166;
// what an item sells for, after its food line in its tooltip // what an item sells for, after its food line in its tooltip
const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1]; const VALUE_COLOR: Color = [0.95, 0.8, 0.3, 1];
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
ctx.ui.register_menu_screen("bworld:storage", chest_screen); ctx.ui.register_menu_screen("bworld:storage", chest_screen);
ctx.ui.register_menu_screen("bworld:furnace", furnace_screen); ctx.ui.register_menu_screen("bworld:furnace", furnace_screen);
ctx.ui.register_menu_screen("bworld:crabpot", (menu) => container_screen(menu, HEIGHT)); ctx.ui.register_menu_screen("bworld:crabpot", (menu) => container_screen(menu, HEIGHT));
+1 -1
View File
@@ -41,7 +41,7 @@ const FORMS: { form: string; id: (rock: string) => string }[] = [
const STONE_MINING = { toughness: 3, tool: "pickaxe", requires_tool: true } as const; const STONE_MINING = { toughness: 3, tool: "pickaxe", requires_tool: true } as const;
export function setup(ctx: ContentContext) { export function content(ctx: ContentContext) {
const texture = (form: string, rock: string) => `bworld:rock_${form}_${rock}`; const texture = (form: string, rock: string) => `bworld:rock_${form}_${rock}`;
for (const rock of ROCKS) { for (const rock of ROCKS) {
for (const { form, id } of FORMS) { for (const { form, id } of FORMS) {
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the kitchen's recipe types, registered by the shared script: what the cooking pot cooks, found by the items in its // the kitchen's recipe types, registered by the shared phase: what the cooking pot cooks, found by the items in its
// ingredient slots, and what the cutting board cuts, found by the item on it. see cooking.ts // ingredient slots, and what the cutting board cuts, found by the item on it. see cooking.ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// fermentable recipes: a fluid that ferments into another over a number of ticks, like juice into wine in the keg. the // fermentable recipes: a fluid that ferments into another over a number of ticks, like juice into wine in the keg. the
// shared script registers one for every juice, and mods can add more like any recipe, as files or from their shared // shared phase registers one for every juice, and mods can add more like any recipe, as files or from their shared
// scripts. they're found by the fluid that ferments // scripts. they're found by the fluid that ferments
import type { FluidStack, FluidVariant, SharedContext } from "cubi/shared"; import type { FluidStack, FluidVariant, SharedContext } from "cubi/shared";
import type { JuiceableParams } from "./shared.ts"; import type { JuiceableParams } from "./shared.ts";
+3 -3
View File
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// juicing recipes: what the juicer presses an item into. the shared script registers one for every item with // juicing recipes: what the juicer presses an item into. the shared phase registers one for every item with
// bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared scripts. // bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared phases.
// whatever makes juice finds them by the item, like the juicer. with create installed, each is also a create:compacting // whatever makes juice finds them by the item, like the juicer. with create installed, each is also a create:compacting
// recipe, so its press can make juice in a basin // recipe, so its press can make juice in a basin
import type { FluidStack, SharedContext } from "cubi/shared"; import type { FluidStack, SharedContext } from "cubi/shared";
@@ -44,7 +44,7 @@ export function register_juicing(ctx: SharedContext) {
// a create:compacting recipe for every juicing recipe there is so far, so create's press squashes the item into its // a create:compacting recipe for every juicing recipe there is so far, so create's press squashes the item into its
// juice in a basin under it. create's recipes take a list of item choices and give a list of results, a fluid's as // juice in a basin under it. create's recipes take a list of item choices and give a list of results, a fluid's as
// { fluid, amount }. juicing recipes other mods' shared scripts register later aren't seen here // { fluid, amount }. juicing recipes other mods' shared phases register later aren't seen here
function register_compacting(ctx: SharedContext) { function register_compacting(ctx: SharedContext) {
for (const juicing of ctx.recipes.list(JUICING)) { for (const juicing of ctx.recipes.list(JUICING)) {
ctx.recipes.register("create:compacting", { ctx.recipes.register("create:compacting", {
+9
View File
@@ -0,0 +1,9 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the base game's script. each phase is in its own file, see docs/modding/concepts/sides.md
export { content } from "./content.ts";
export { shared } from "./shared.ts";
export { server } from "./server.ts";
export { client } from "./client.ts";
export { worldgen } from "./worldgen.ts";
+1 -1
View File
@@ -15,7 +15,7 @@ import { JUICING, type JuicingRecipe } from "./juicing.ts";
import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts"; import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts";
import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts"; import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts";
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
register_hoeable(ctx); register_hoeable(ctx);
register_strippable(ctx); register_strippable(ctx);
const storage_menu = register_storage(ctx); const storage_menu = register_storage(ctx);
+1 -1
View File
@@ -14,7 +14,7 @@ import { register_smithing } from "./smithing.ts";
import { register_stonecutting } from "./stonecutting.ts"; import { register_stonecutting } from "./stonecutting.ts";
import { register_verdigris_rules } from "./verdigris/shared.ts"; import { register_verdigris_rules } from "./verdigris/shared.ts";
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
register_fence(ctx); register_fence(ctx);
register_trapdoor(ctx); register_trapdoor(ctx);
register_door(ctx); register_door(ctx);
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// smelting and fuel recipes: the furnace cooks one item into another, burning fuel to do it. both are found by an item // smelting and fuel recipes: the furnace cooks one item into another, burning fuel to do it. both are found by an item
// id, and registered by the shared script like smithing.ts // id, and registered by the shared phase like smithing.ts
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
export const SMELTING = "bworld:smelting"; export const SMELTING = "bworld:smelting";
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// smithing recipes: the smithing table upgrades a tool with some of a material and maybe some of one more item. the // smithing recipes: the smithing table upgrades a tool with some of a material and maybe some of one more item. the
// type is registered by the shared script, so the server's menu and anything on a client find them the same way // type is registered by the shared phase, so the server's menu and anything on a client find them the same way
import type { ItemStack, RecipeReader, SharedContext } from "cubi/shared"; import type { ItemStack, RecipeReader, SharedContext } from "cubi/shared";
export const SMITHING = "bworld:smithing"; export const SMITHING = "bworld:smithing";
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the type is // stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the type is
// registered by the shared script, so the server's menu and the client's screen both list them from ctx.recipes.all, in // registered by the shared phase, so the server's menu and the client's screen both list them from ctx.recipes.all, in
// the same order, so a button's number means the same recipe to both // the same order, so a button's number means the same recipe to both
import type { SharedContext } from "cubi/shared"; import type { SharedContext } from "cubi/shared";
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the power blocks give each other, see docs/modding/blocks/verdigris.md. every signal is a block state, so this only // the power blocks give each other, see docs/modding/blocks/verdigris.md. every signal is a block state, so this only
// reads states, through a small world instead of ctx so it runs the same in shared scripts, server scripts and tests // reads states, through a small world instead of ctx so it runs the same in shared phases, server phases and tests
import type { Face, Id } from "cubi/shared"; import type { Face, Id } from "cubi/shared";
import { FACES, type FacingParam, front_of, named_sides, OPPOSITE, type SideName, step } from "./sides.ts"; import { FACES, type FacingParam, front_of, named_sides, OPPOSITE, type SideName, step } from "./sides.ts";
+1 -1
View File
@@ -6,7 +6,7 @@
import type { FeatureChunk, WorldgenContext } from "cubi/worldgen"; import type { FeatureChunk, WorldgenContext } from "cubi/worldgen";
import { register_trees } from "./trees.ts"; import { register_trees } from "./trees.ts";
export function setup(gen: WorldgenContext) { export function worldgen(gen: WorldgenContext) {
// trees grow in vegetal_decoration, before the cactus looks for air in the last step // trees grow in vegetal_decoration, before the cactus looks for air in the last step
register_trees(gen); register_trees(gen);
gen.register_feature("bworld:cactus", cactus); gen.register_feature("bworld:cactus", cactus);
+1 -5
View File
@@ -16,9 +16,5 @@
} }
], ],
"credits": "CREDITS.md", "credits": "CREDITS.md",
"scripts": { "main": "scripts/main.ts"
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"shared": "scripts/shared.ts"
}
} }
+1 -1
View File
@@ -49,7 +49,7 @@ const half_shaft = (facing: Face) => HALF_SHAFT_TURNS[OPPOSITE[facing]];
// how a model made along y is turned to an axis, the way the kinetic blocks' variants turn theirs // how a model made along y is turned to an axis, the way the kinetic blocks' variants turn theirs
const AXIS_TURNS: Record<Axis, { x?: number; y?: number }> = { x: { x: 90, y: 90 }, y: {}, z: { x: 90, y: 180 } }; const AXIS_TURNS: Record<Axis, { x?: number; y?: number }> = { x: { x: 90, y: 90 }, y: {}, z: { x: 90, y: 180 } };
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
const shape_of = (block: VisualBlock): KineticShape => { const shape_of = (block: VisualBlock): KineticShape => {
const params = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams; const params = ctx.blocks.components(block.id)["create:kinetic"] as KineticParams;
return kinetic_shape(params, (name) => block.states[name]); return kinetic_shape(params, (name) => block.states[name]);
+7
View File
@@ -0,0 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's script. each phase is in its own file, see docs/modding/concepts/sides.md
export { shared } from "./shared.ts";
export { server } from "./server.ts";
export { client } from "./client.ts";
+1 -1
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and // create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and
// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared script // stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared phase
// registers each type, so a broken recipe stops the mod loading instead of a machine later. no ctx, tests give what it // registers each type, so a broken recipe stops the mod loading instead of a machine later. no ctx, tests give what it
// needs // needs
import type { FluidStack, Id, RecipeType } from "cubi/shared"; import type { FluidStack, Id, RecipeType } from "cubi/shared";
+1 -1
View File
@@ -79,7 +79,7 @@ interface PressData extends KineticData {
scan?: number; scan?: number;
} }
export function setup(ctx: ServerContext) { export function server(ctx: ServerContext) {
const config: Config = ctx.config; const config: Config = ctx.config;
const world = kinetic_world(ctx, config); const world = kinetic_world(ctx, config);
+1 -1
View File
@@ -20,7 +20,7 @@ import {
OPPOSITE, OPPOSITE,
} from "./kinetics/connections.ts"; } from "./kinetics/connections.ts";
export function setup(ctx: SharedContext) { export function shared(ctx: SharedContext) {
const lookup = { expand: ctx.tags.expand, item_exists: ctx.items.exists, fluid_exists: ctx.fluids.exists }; const lookup = { expand: ctx.tags.expand, item_exists: ctx.items.exists, fluid_exists: ctx.fluids.exists };
ctx.recipes.register_type(PRESSING.id, processing_type(PRESSING, lookup)); ctx.recipes.register_type(PRESSING.id, processing_type(PRESSING, lookup));
ctx.recipes.register_type(COMPACTING.id, processing_type(COMPACTING, lookup)); ctx.recipes.register_type(COMPACTING.id, processing_type(COMPACTING, lookup));
+1 -3
View File
@@ -8,7 +8,5 @@
"paula" "paula"
], ],
"game_version": ">=0.1.0", "game_version": ">=0.1.0",
"scripts": { "main": "scripts/client.ts"
"client": "scripts/client.ts"
}
} }
+1 -1
View File
@@ -8,7 +8,7 @@ import type { ClientContext } from "cubi/client";
import { type Entry, ItemList, type Mode } from "./item_list.ts"; import { type Entry, ItemList, type Mode } from "./item_list.ts";
import { RecipeIndex, RecipesScreen } from "./recipes_screen.ts"; import { RecipeIndex, RecipesScreen } from "./recipes_screen.ts";
export function setup(ctx: ClientContext) { export function client(ctx: ClientContext) {
const index = new RecipeIndex(ctx); const index = new RecipeIndex(ctx);
const list = new ItemList(ctx); const list = new ItemList(ctx);
// like jei's IRecipesGui.show, only when there's something to show // like jei's IRecipesGui.show, only when there's something to show
+5 -4
View File
@@ -3,15 +3,16 @@
/// <reference lib="deno.worker" /> /// <reference lib="deno.worker" />
// runs the mods' content scripts for server/load_mods.ts, without permissions like the game's worker, since the host // runs the content phase of the mods' scripts for server/load_mods.ts, without permissions like the game's worker,
// that loads mods can read and write files. gets each one's script and answers with what each registered, in order // since the host that loads mods can read and write files. gets each one's script and answers with what each
// registered, in order
import { type ContentScriptCode, run_content_script } from "@/common/content_scripts.ts"; import { type ContentScriptCode, run_content_script } from "@/common/content_scripts.ts";
import { data_url } from "@/common/mod.ts"; import { data_url } from "@/common/mod.ts";
self.onmessage = async (event: MessageEvent<ContentScriptCode[]>) => { self.onmessage = async (event: MessageEvent<ContentScriptCode[]>) => {
const results = []; const results = [];
for (const { mod, version, code } of event.data) { for (const { code, ...script } of event.data) {
results.push(await run_content_script({ mod, version, url: data_url(code) })); results.push(await run_content_script({ ...script, url: data_url(code) }));
} }
self.postMessage(results); self.postMessage(results);
}; };
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// what engine access mods get as engine.server, in server scripts. see docs/modding/misc/engine.md // what engine access mods get as engine.server, in server phases. see docs/modding/misc/engine.md
import { GameServer } from "./game_server.ts"; import { GameServer } from "./game_server.ts";
import { ServerWorld } from "./world.ts"; import { ServerWorld } from "./world.ts";
import { ServerPlayer } from "./player.ts"; import { ServerPlayer } from "./player.ts";
+1 -1
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the fluid handlers the engine makes for server scripts, see ServerFluidApi in mod_api/server.ts: fluid containers', // the fluid handlers the engine makes for server phases, see ServerFluidApi in mod_api/server.ts: fluid containers',
// tanks scripts keep, and pouring from one handler into another // tanks scripts keep, and pouring from one handler into another
import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts"; import { EverythingRegistry, type ItemRegistry } from "@/common/everything_registry.ts";
import { contained_fluid } from "@/common/inventory.ts"; import { contained_fluid } from "@/common/inventory.ts";
+2 -2
View File
@@ -587,7 +587,7 @@ export class GameServer {
this.#send(player, overlay ? { type: "chat", text, overlay } : { type: "chat", text }); this.#send(player, overlay ? { type: "chat", text, overlay } : { type: "chat", text });
} }
// a mod's server script to its client script, see ctx.net // a mod's server phase to its client phase, see ctx.net
send_mod_message(player: ServerPlayer, channel: string, data: unknown) { send_mod_message(player: ServerPlayer, channel: string, data: unknown) {
this.#send(player, { type: "mod", channel, data }); this.#send(player, { type: "mod", channel, data });
} }
@@ -1372,7 +1372,7 @@ export class GameServer {
return; return;
} }
// the shared rules first, the ones the client guessed, then the server script's. sneaking with an item skips the // the shared rules first, the ones the client guessed, then the server phase's. sneaking with an item skips the
// block, like minecraft's secondary use, so a block can be placed against a chest // block, like minecraft's secondary use, so a block can be placed against a chest
const sneaking = player.sneaking; const sneaking = player.sneaking;
let handled = false; let handled = false;
+2 -8
View File
@@ -19,14 +19,8 @@ export type HostToGame =
// level.json, and where the saved chunks are. the game reads them with read_chunk when it needs them // level.json, and where the saved chunks are. the game reads them with read_chunk when it needs them
save: { level?: string; chunks: [number, number][] }; save: { level?: string; chunks: [number, number][] };
default_seed: string; default_seed: string;
// in load order, with the scripts' code since the worker can't read files // in load order, with their script's code since the worker can't read files
mods: { mods: { listing: ModListing; data: ModData; code?: string }[];
listing: ModListing;
data: ModData;
server_code?: string;
worldgen_code?: string;
shared_code?: string;
}[];
// the game's ends of channels to the worldgen workers the host started, see worldgen_pool.ts. none means // the game's ends of channels to the worldgen workers the host started, see worldgen_pool.ts. none means
// generating on the game's thread // generating on the game's thread
worldgen_ports: MessagePort[]; worldgen_ports: MessagePort[];
+10 -19
View File
@@ -1,8 +1,8 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// starts a game server with its mods: registers their data, then imports worldgen and server scripts. // starts a game server with its mods: registers their data, then runs the worldgen, shared and server phases of their
// 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 { 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";
@@ -22,10 +22,8 @@ import { server_engine } from "./engine_modules.ts";
export interface ServerModSource { export interface ServerModSource {
listing: ModListing; listing: ModListing;
data: ModData; data: ModData;
// importable urls of the scripts: data: urls in the worker, file urls in tests // importable url of its script: a data: url in the worker, a file url in tests
server_url?: string; url?: string;
worldgen_url?: string;
shared_url?: string;
} }
export async function start_game( export async function start_game(
@@ -47,9 +45,7 @@ export async function start_game(
const generator = dimension.generator; const generator = dimension.generator;
const shape = dimension_shape(dimension); const shape = dimension_shape(dimension);
const worldgen_scripts = mods.flatMap((mod) => const worldgen_scripts = mods.flatMap((mod) =>
mod.worldgen_url mod.url ? [{ mod: mod.listing.id, url: mod.url, engine_access: mod.listing.engine_access }] : []
? [{ mod: mod.listing.id, url: mod.worldgen_url, engine_access: mod.listing.engine_access }]
: []
); );
const worldgen = await load_worldgen({ const worldgen = await load_worldgen({
mods: mods.map((mod) => mod.listing.id), mods: mods.map((mod) => mod.listing.id),
@@ -72,15 +68,10 @@ export async function start_game(
runtime, runtime,
}); });
// every mod's shared rules first, so server scripts can count on any mod's being there const scripts = mods.flatMap((mod) => mod.url ? [{ ...script_of(mod), url: mod.url }] : []);
await runtime.load_shared_scripts( // every mod's shared rules first, so server phases can count on any mod's being there
game, await runtime.load_shared_scripts(game, scripts);
mods.flatMap((mod) => mod.shared_url ? [{ ...script_of(mod), url: mod.shared_url }] : []), await runtime.load_scripts(game, scripts);
);
await runtime.load_scripts(
game,
mods.flatMap((mod) => mod.server_url ? [{ ...script_of(mod), url: mod.server_url }] : []),
);
runtime.finish_setup(); runtime.finish_setup();
game.find_ticking_tiles(); game.find_ticking_tiles();
// what a worldgen worker needs to generate the same chunks, see worldgen_pool.ts // what a worldgen worker needs to generate the same chunks, see worldgen_pool.ts
@@ -91,7 +82,7 @@ export async function start_game(
mods.map((mod) => ({ mods.map((mod) => ({
id: mod.listing.id, id: mod.listing.id,
data: mod.data, data: mod.data,
worldgen_url: mod.worldgen_url, url: mod.url,
engine_access: mod.listing.engine_access, engine_access: mod.listing.engine_access,
})), })),
); );
+38 -43
View File
@@ -1,7 +1,7 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// runs mods' server scripts: builds each one's ServerContext and keeps what they register. // runs mods' server phases: builds each one's ServerContext and keeps what they register.
// see docs/modding/. parts not built yet throw when used, saying so // see docs/modding/. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "@/common/everything_registry.ts"; import { BlockRegistry, EverythingRegistry, fluid_height, ItemRegistry } from "@/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack, max_stack } from "@/common/inventory.ts"; import { Container as EngineContainer, ItemStack as EngineItemStack, max_stack } from "@/common/inventory.ts";
@@ -23,7 +23,6 @@ import { fluid_exists, FluidRules, same_fluid } from "@/common/fluids.ts";
import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts"; import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts";
import type { SharedContext } from "@/common/mod_api/shared.ts"; import type { SharedContext } from "@/common/mod_api/shared.ts";
import { tag_api } from "@/common/tags.ts"; import { tag_api } from "@/common/tags.ts";
import { loading_mod } from "@/common/hooks.ts";
import type { import type {
BlockComponent, BlockComponent,
BlockRef, BlockRef,
@@ -52,7 +51,14 @@ import type {
ServerContext, ServerContext,
SlotOptions, SlotOptions,
} from "@/common/mod_api/server.ts"; } from "@/common/mod_api/server.ts";
import { check_recipe_types, ModLoadError, recipe_lookup, shared_recipes_api } from "@/common/mod_loader.ts"; import {
check_recipe_types,
ModLoadError,
type Phase,
recipe_lookup,
run_phase,
shared_recipes_api,
} from "@/common/mod_loader.ts";
import { import {
argument, argument,
block as block_argument, block as block_argument,
@@ -114,7 +120,6 @@ export class Signal<T> {
// the mod whose code is running right now, for apis shared between mods that need to know who called // the mod whose code is running right now, for apis shared between mods that need to know who called
let running_mod = ""; let running_mod = "";
// a mod's script, imported from url. engine_access lets it import cubi/engine
// a component a block lists, with its params from the block's json // a component a block lists, with its params from the block's json
export interface BlockComponentOf { export interface BlockComponentOf {
mod: string; mod: string;
@@ -123,6 +128,7 @@ export interface BlockComponentOf {
params: unknown; params: unknown;
} }
// a mod's script, imported from url. engine_access lets it import cubi/engine
interface ScriptSource { interface ScriptSource {
mod: string; mod: string;
version: string; version: string;
@@ -159,13 +165,13 @@ interface Timer {
export class ModRuntime { export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>(); block_components = new Map<string, { mod: string; component: BlockComponent }>();
// what shared scripts registered, see common/block_rules.ts, running on the game's world // what shared phases registered, see common/block_rules.ts, running on the game's world
rules = new BlockRules( rules = new BlockRules(
run_guarded, run_guarded,
(x, y, z) => this.game.world.get_block_id(x, y, z), (x, y, z) => this.game.world.get_block_id(x, y, z),
(x, y, z, from) => this.#neighbor_changed(x, y, z, from), (x, y, z, from) => this.#neighbor_changed(x, y, z, from),
); );
// the fluids' rules from shared scripts, see common/fluids.ts // the fluids' rules from shared phases, see common/fluids.ts
fluid_rules = new FluidRules(run_guarded); fluid_rules = new FluidRules(run_guarded);
item_components = new Map<string, { mod: string; component: ItemComponent }>(); item_components = new Map<string, { mod: string; component: ItemComponent }>();
effect_components = new Map<string, { mod: string; component: EffectComponent }>(); effect_components = new Map<string, { mod: string; component: EffectComponent }>();
@@ -264,30 +270,45 @@ export class ModRuntime {
} }
game!: GameServer; game!: GameServer;
// imports each server script and calls its setup, in load order // runs each script's shared phase in load order: the block rules clients run too. their world is the server's
// shared scripts, the block rules clients run too. their world is the server's
async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) { async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) {
this.game = game; this.game = game;
this.#shared_setup = true; this.#shared_setup = true;
try { try {
for (const { mod, version, url, engine_access, config } of scripts) { await this.#run_phase(scripts, "shared", (script) => this.#shared_context(script));
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config));
}
check_recipe_types(game.recipes); check_recipe_types(game.recipes);
} finally { } finally {
this.#shared_setup = false; this.#shared_setup = false;
} }
} }
// while shared scripts set up, the only time they can register recipes, as on clients // while shared phases run, the only time they can register recipes, as on clients
#shared_setup = false; #shared_setup = false;
async #load_shared_script(mod: string, version: string, url: string, config: Record<string, unknown>) { // runs each script's server phase in load order
const module = await import(url); async load_scripts(game: GameServer, scripts: ScriptSource[]) {
if (typeof module.setup !== "function") { this.game = game;
throw new ModLoadError(mod, "the shared script doesn't export a setup function"); await this.#run_phase(scripts, "server", ({ mod, version, config }) => this.#context(mod, version, config));
}
async #run_phase(scripts: ScriptSource[], phase: Phase, context: (script: ScriptSource) => unknown) {
for (const script of scripts) {
running_mod = script.mod;
try {
await run_phase(
{ id: script.mod, engine_access: script.engine_access },
script.url,
phase,
() => context(script),
);
} finally {
running_mod = "";
}
} }
}
#shared_context({ mod, version, config }: ScriptSource): SharedContext {
const { world, blocks } = this.#context(mod, version, config); const { world, blocks } = this.#context(mod, version, config);
const ctx: SharedContext = { return {
mod: { id: mod, version }, mod: { id: mod, version },
side: "server", side: "server",
tags: tag_api(), tags: tag_api(),
@@ -322,32 +343,6 @@ export class ModRuntime {
}, },
}, },
}; };
running_mod = mod;
try {
await module.setup(ctx);
} finally {
running_mod = "";
}
}
async load_scripts(game: GameServer, scripts: ScriptSource[]) {
this.game = game;
for (const { mod, version, url, engine_access, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url, config));
}
}
async #load_script(mod: string, version: string, url: string, config: Record<string, unknown>) {
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the server script doesn't export a setup function");
}
running_mod = mod;
try {
await module.setup(this.#context(mod, version, config));
} finally {
running_mod = "";
}
} }
// every effect mods define, from their json. they're made before scripts run, since the world loads first and // every effect mods define, from their json. they're made before scripts run, since the world loads first and
+1 -3
View File
@@ -120,9 +120,7 @@ async function init(message: Extract<HostToGame, { type: "init" }>) {
listing: mod.listing, listing: mod.listing,
data: mod.data, data: mod.data,
// the worker has no file access, so the host sends the code and it's imported from memory // the worker has no file access, so the host sends the code and it's imported from memory
server_url: mod.server_code ? data_url(mod.server_code) : undefined, url: mod.code ? data_url(mod.code) : undefined,
worldgen_url: mod.worldgen_code ? data_url(mod.worldgen_code) : undefined,
shared_url: mod.shared_code ? data_url(mod.shared_code) : undefined,
})), })),
); );
} catch (e) { } catch (e) {
+1 -1
View File
@@ -19,7 +19,7 @@ self.onmessage = (event: MessageEvent<{ port: MessagePort }>) => {
port.onmessage = async (event: MessageEvent<PoolToWorker>) => { port.onmessage = async (event: MessageEvent<PoolToWorker>) => {
const message = event.data; const message = event.data;
if (message.type === "init") { if (message.type === "init") {
// worldgen scripts with engine access hook engine.common here, in this worker's own copy of the engine // worldgen phases with engine access hook engine.common here, in this worker's own copy of the engine
expose_engine({ common: common_engine() }); expose_engine({ common: common_engine() });
loaded = load_bundle(message.bundle); loaded = load_bundle(message.bundle);
try { try {
+1 -3
View File
@@ -151,9 +151,7 @@ export async function start_host(options: HostOptions): Promise<Host> {
mods: mods.map(({ listing, mod }) => ({ mods: mods.map(({ listing, mod }) => ({
listing, listing,
data: mod.data, data: mod.data,
server_code: mod.scripts.server, code: mod.script,
worldgen_code: mod.scripts.worldgen,
shared_code: mod.scripts.shared,
})), })),
worldgen_ports: worldgen.ports, worldgen_ports: worldgen.ports,
} satisfies HostToGame, } satisfies HostToGame,
+9 -8
View File
@@ -2,7 +2,7 @@
// SPDX-License-Identifier: AGPL-3.0-or-later // SPDX-License-Identifier: AGPL-3.0-or-later
// the server's mods: every .cubi in server_mods/, checked, with the server's changes to their config, sorted so // the server's mods: every .cubi in server_mods/, checked, with the server's changes to their config, sorted so
// dependencies load first, and with the copy players download (the same mod without its server script) ready to serve // dependencies load first, and with the copy players download (the same mod without its server phase) ready to serve
import { join } from "@std/path"; import { join } from "@std/path";
import { client_copy, type Mod, MOD_EXTENSION, read_mod, write_mod } from "@/common/mod.ts"; import { client_copy, type Mod, MOD_EXTENSION, read_mod, write_mod } from "@/common/mod.ts";
import { check_references, load_order, type LoadedMod } from "@/common/mod_check.ts"; import { check_references, load_order, type LoadedMod } from "@/common/mod_check.ts";
@@ -104,16 +104,17 @@ export async function load_mods(
})); }));
} }
// runs the mods' content scripts in a worker without permissions and adds the blocks they register to their data, // runs the content phase of the mods' scripts in a worker without permissions and adds the blocks they register to
// after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players download, // their data, after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players
// and in the worldgen bundle // download, and in the worldgen bundle
async function add_registered_content(mods: { file: string; mod: Mod }[], problems: string[]) { async function add_registered_content(mods: { file: string; mod: Mod }[], problems: string[]) {
const with_scripts = mods.filter(({ mod }) => mod.scripts.content !== undefined); const with_scripts = mods.filter(({ mod }) => mod.script !== undefined);
if (with_scripts.length === 0) return; if (with_scripts.length === 0) return;
const scripts: ContentScriptCode[] = with_scripts.map(({ mod }) => ({ const scripts: ContentScriptCode[] = with_scripts.map(({ mod }) => ({
mod: mod.manifest.id, mod: mod.manifest.id,
version: mod.manifest.version, version: mod.manifest.version,
code: mod.scripts.content!, engine_access: mod.manifest.engine_access,
code: mod.script!,
})); }));
const worker = new Worker(new URL("./content_worker.ts", import.meta.url), { const worker = new Worker(new URL("./content_worker.ts", import.meta.url), {
type: "module", type: "module",
@@ -125,7 +126,7 @@ async function add_registered_content(mods: { file: string; mod: Mod }[], proble
worker.onmessage = (event) => resolve(event.data); worker.onmessage = (event) => resolve(event.data);
worker.onerror = (event) => { worker.onerror = (event) => {
event.preventDefault(); event.preventDefault();
reject(new Error(`content scripts: ${event.message}`)); reject(new Error(`content phases: ${event.message}`));
}; };
worker.postMessage(scripts); worker.postMessage(scripts);
}); });
@@ -134,7 +135,7 @@ async function add_registered_content(mods: { file: string; mod: Mod }[], proble
} }
with_scripts.forEach(({ file, mod }, i) => { with_scripts.forEach(({ file, mod }, i) => {
mod.data.blocks.push(...results[i].blocks); mod.data.blocks.push(...results[i].blocks);
problems.push(...results[i].problems.map((problem) => `${file}: ${mod.manifest.scripts!.content}: ${problem}`)); problems.push(...results[i].problems.map((problem) => `${file}: ${mod.manifest.main}: ${problem}`));
}); });
} }
+1 -1
View File
@@ -27,7 +27,7 @@ export interface WorldgenWorkers {
export function start_worldgen_workers( export function start_worldgen_workers(
count: number, count: number,
options: { options: {
// "none" like the game, for the host. tests load worldgen scripts from files, which needs "inherit" // "none" like the game, for the host. tests load worldgen phases from files, which needs "inherit"
permissions: "none" | "inherit"; permissions: "none" | "inherit";
// a worker crashed and was started again: the game's end of its new channel // a worker crashed and was started again: the game's end of its new channel
on_restart(index: number, port: MessagePort): void; on_restart(index: number, port: MessagePort): void;
+11 -13
View File
@@ -4,20 +4,18 @@ A bworld mod. `MODS.md` at the root of the bworld repo links to the modding docs
## Files ## Files
| Path | What it's for | | Path | What it's for |
| --------------------- | ------------------------------------------------------------------------------------ | | -------------------- | ----------------------------------------------------------------------------------------------------------- |
| `manifest.json` | The mod's id, name, version, dependencies and scripts. | | `manifest.json` | The mod's id, name, version, dependencies and script. |
| `blocks/*.json` | One block per file. Blocks get an item form with the same id unless `"item": false`. | | `blocks/*.json` | One block per file. Blocks get an item form with the same id unless `"item": false`. |
| `items/*.json` | Items that aren't a block's item form. | | `items/*.json` | Items that aren't a block's item form. |
| `recipes/*.json` | `shaped` crafting, `furnace` smelting and `fuel`. | | `recipes/*.json` | `shaped` crafting, `furnace` smelting and `fuel`. |
| `textures/*.png` | 16×16 textures, named `example_mod:<file name>`. | | `textures/*.png` | 16×16 textures, named `example_mod:<file name>`. |
| `worldgen/ores.json` | Ores to generate (optional, not included here). | | `worldgen/ores.json` | Ores to generate (optional, not included here). |
| `scripts/server.ts` | Game logic: block components, commands, events. Never sent to players. | | `scripts/main.ts` | Its exports are phases: `server` for game logic, `client` for screens and the HUD, `worldgen` for features. |
| `scripts/client.ts` | Sent to players: menu screens, screens, HUD, keybinds. | | `CREDITS.md` | Licenses and thanks, shown on the About page. |
| `scripts/worldgen.ts` | Terrain features. Runs on the server and every client and must be deterministic. |
| `CREDITS.md` | Licenses and thanks, shown on the About page. |
Delete what you don't use, including its entry in `manifest.json`. Delete what you don't use. A phase you don't need is an export you leave out.
## Checking it ## Checking it
+1 -5
View File
@@ -9,10 +9,6 @@
"dependencies": [ "dependencies": [
{ "id": "bworld", "version": ">=0.1.0" } { "id": "bworld", "version": ">=0.1.0" }
], ],
"scripts": { "main": "scripts/main.ts",
"server": "scripts/server.ts",
"client": "scripts/client.ts",
"worldgen": "scripts/worldgen.ts"
},
"credits": "CREDITS.md" "credits": "CREDITS.md"
} }
-14
View File
@@ -1,14 +0,0 @@
import type { ClientContext } from "cubi/client";
// called on every player's client after the mod is downloaded, before the world shows up.
// everything here is visible to players, so keep secrets and game rules in server.ts
export function setup(ctx: ClientContext) {
ctx.log("loaded");
// a HUD element, drawn every frame
// ctx.hud.register("example_mod:hint", {
// on_render(g) {
// g.text("example mod is here", 8, 8);
// },
// });
}
+65
View File
@@ -0,0 +1,65 @@
import type { ClientContext } from "cubi/client";
import type { ServerContext } from "cubi/server";
import type { WorldgenContext } from "cubi/worldgen";
// the mod's script. each export is a phase, called where and when it runs. this file goes to the server and to every
// player, and each runs only its own phases, so keep the top level free of anything only one side has
// called once when the server starts. players never run it, so game rules belong here
export function server(ctx: ServerContext) {
// used by blocks/example_block.json, which passes { message } as params
ctx.components.register_block<{ message: string }>("example_mod:announce", {
// block data is saved with the world. on_tick and on_second only run for blocks that have some
on_create(block) {
block.data = { age: 0 };
},
// on_tick runs 20 times a second, on_second once, while a player is nearby
on_second(block) {
block.data.age += 1;
},
on_interact(block, params, player) {
player.send_message(`${params.message} It's been here for ${block.data?.age ?? 0} seconds.`);
// handled, so right clicking it doesn't place a block
return true;
},
});
// /example_mod:hello, or /hello when no other mod uses that name
ctx.commands.register("hello", {
description: "Say hello",
usage: "/hello",
run(_args, player) {
player.send_message(`Hello ${player.name}!`);
},
});
ctx.events.after.player_join.subscribe(({ player }) => {
ctx.log(`${player.name} joined`);
});
}
// called on every player's client after the mod is downloaded, before the world shows up
export function client(ctx: ClientContext) {
ctx.log("loaded");
// a HUD element, drawn every frame
// ctx.hud.register("example_mod:hint", {
// on_render(g) {
// g.text("example mod is here", 8, 8);
// },
// });
}
// runs wherever the server generates chunks, which must always give the same world. only use chunk.rng and the noise
// helpers, never Math.random or the time
export function worldgen(gen: WorldgenContext) {
// a boulder on one chunk in ten
gen.register_feature("example_mod:boulders", (chunk) => {
if (chunk.rng.next() > 0.1) {
return;
}
const x = chunk.x * 16 + Math.floor(chunk.rng.next() * 16);
const z = chunk.z * 16 + Math.floor(chunk.rng.next() * 16);
chunk.set_block(x, chunk.height_at(x, z) + 1, z, "bworld:stone");
});
}

Some files were not shown because too many files have changed in this diff Show More