23 KiB
Modding: Design Notes and Plan
The mod docs in docs/modding/ describe what works today. This file is for people working on the engine:
the design behind the mod API, what's planned, and the questions still open.
bworld's modding takes from three places:
- Minetest: the game is mods. The engine is small, and everything that makes bworld bworld (its blocks, items,
crafting, screens, commands and terrain) lives in
mods/bworld, written against the same API as any other mod. - Minecraft Bedrock add-ons: easy to start. Most content is JSON, blocks and items get behavior from named components, scripts use before/after events and server-driven forms, and players get everything from the server.
- Minecraft Java with NeoForge: no ceiling. Most mods get by with registries and events on a bus, with priorities and cancelling. A mod that needs more can reach into the engine itself and hook its methods, like NeoForge's mixins and access transformers.
A mod is built from up to three layers. Most mods only need the first one or two:
| Layer | Like | What a mod writes | Stability |
|---|---|---|---|
| Data | Bedrock behavior packs | JSON in blocks/, items/, models/, recipes/, ... |
Versioned by format_version |
| Game API | Minetest's Lua API, Bedrock's Script API | TypeScript against bworld/server, bworld/client, bworld/worldgen |
Only breaks with the game's major version |
| Engine access | NeoForge's mixins | import { engine, hook } from "bworld/engine" |
None, tied to one game version |
Status
Built: the mod loader and .bmod 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
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
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,
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
drawn on other players and on the first person arm). See Menus,
Screens and Worn Models.
The code is in common/mod_loader.ts, common/mod_data.ts, common/mod_check.ts, common/bmod.ts,
server/game/mod_runtime.ts, server/game/menu.ts, server/load_bmods.ts, client/mods.ts, client/menu.ts,
common/worldgen_loader.ts, and for worn items client/rendering/worn_renderer.ts, player_model.ts and
model_math.ts.
In the API types but throwing: forms, HUD elements, keybinds, g.slider, register_terrain.
Not built at all: common scripts, the registry freeze and hash, overrides.
Engine access is built (phase 3): bworld/engine, hook, engine_access and its checks, and physics as the
first plain object mods can hook. See Engine Access. The code is in common/hooks.ts,
common/mod_api/engine.ts and the engine_modules.ts of each side.
Known gaps:
- Manifest
dependenciesversion ranges aren't checked, andgame_versiononly is for engine access mods. - Mods can't throw a
CommandErrorthe server recognizes: it's checked withinstanceof, and the class isn't in the API, so a mod's bundled copy is a different class. Export it frombworld/server, or recognize it byname. - Tools only lose durability when their owner dies. Nothing else uses it.
- The GUI scale is always 3: screens work in GUI pixels like NeoForge's, but there's no option to change it yet.
- Worn models haven't been looked at in the game yet, only tested: Artifacts' power glove and feral claws and the giant chestplate on other players, wide and slim, and on the first person arm with its equip and swing.
- Blockbench's
mirrorisn't supported in entity models, so the giant chestplate's left sleeve has the right one's texture unflipped.
Planned API
Common Scripts
A fourth script, scripts.common, run on the server and on every client while content loads, right after the mod's own
JSON is 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
depends on other mods can be written as code.
import type { CommonContext } from "bworld/common";
const COLORS = ["white", "red", "green", "blue", "black"];
export function setup(ctx: CommonContext) {
for (const color of COLORS) {
ctx.blocks.register({
id: `wool:${color}_wool`,
textures: `wool:${color}_wool`,
mining: { toughness: 1 },
drops: `wool:${color}_wool`,
});
}
// every leaf block any mod registered drops sticks sometimes
for (const id of ctx.blocks.ids().filter((id) => id.endsWith("_leaves"))) {
ctx.blocks.extend(id, { components: { "wool:stick_drop": { chance: 0.05 } } });
}
}
interface CommonContext {
mod: { id: string; version: string };
blocks: ContentRegistry<BlockJson>;
items: ContentRegistry<ItemJson>;
models: ContentRegistry<ModelJson>;
recipes: RecipeRegistry;
log(...args: unknown[]): void;
}
// T is the same shape as the JSON file's content, checked the same way
interface ContentRegistry<T> {
register(definition: T): void;
get(id: string): Readonly<T> | undefined; // what's registered so far, by any mod
ids(): string[];
override(id: string, fields: Partial<T>): void; // like "set" in an override file
extend(id: string, change: { components?: Record<string, unknown>; remove_components?: string[] }): void;
}
interface RecipeRegistry {
register(recipe: RecipeJson): void;
remove(match: (recipe: RecipeJson) => boolean): number;
list(type: string): readonly RecipeJson[];
register_type(id: string, type: { validate(recipe: unknown): string[] }): void;
}
- 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
ctxon both sides, so they can't accidentally register different things. register_typewould letcheck-modsand the loader validate mods' own recipe types, instead of each mod checking its recipes insetup.shaped,furnace,fuelandsmithingbecome short forbworld:shapedand so on.
The Freeze and the Registry Hash
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
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.
Overrides
A mod changes content other mods registered, like Minetest's override_item. overrides/grass_weeds.json:
{
"format_version": 1,
"override": {
"block": "bworld:grass",
"set": { "mining": { "toughness": 1, "tool": "shovel" } },
"add_components": { "farming_plus:weeds": { "chance": 0.01 } }
}
}
| Field | Meaning |
|---|---|
block or item |
The id to change. |
set |
Fields to replace, named as in the block or item JSON. Each listed field is replaced whole. |
add_components |
Components to add. One it already has gets these params instead. |
remove_components |
Component ids to take away. |
remove_recipes |
Removes recipes whose fields equal the ones given (result matches the result's id), like { "type": "shaped", "result": "bworld:chest" }. |
- A mod can only change content of mods it lists in
dependencies, so it always loads after them.check-modsmakes this an error. - Changes apply in load order, so the later mod wins.
check-modswarns when two mods change the same field. - Ids never change and blocks and items can't be removed. To make something unobtainable, remove its recipes and drops.
- Overrides are content: applied on every side, and part of the registry hash.
Engine Access
For what the Game API doesn't cover yet: a new kind of rendering, different player physics, a new entity type. A mod asks for it in its manifest:
{ "engine_access": true, "game_version": "~0.4.0" }
// server.ts: broken blocks drop twice
import { engine, hook } from "bworld/engine";
export function setup() {
hook(engine.server.GameServer.prototype, "pop_item", {
after(game, [x, y, z, stack], entity) {
game.spawn_item(entity.x, entity.y, entity.z, stack.clone());
return entity;
},
});
}
function hook<T, K extends keyof T>(target: T, method: K, handlers: {
// runs first. change args in place, or return { result } to skip the method and everything after
before?(self: T, args: Parameters<T[K]>): { result: ReturnType<T[K]> } | void;
// wraps the method, calling original (or not)
replace?(self: T, args: Parameters<T[K]>, original: T[K]): ReturnType<T[K]>;
// runs last, and returns the result the caller gets. undefined keeps the result it was given
after?(self: T, args: Parameters<T[K]>, result: ReturnType<T[K]>): ReturnType<T[K]> | void;
// lower runs earlier, the default is 1000. ties go in load order
priority?: number;
}): () => void; // unhook
engineholds the live modules on each side:engine.commoneverywhere,engine.serverin server scripts,engine.clientin client scripts. The engine puts them on the global object at startup, andbworld/enginein a 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-modstypechecks against exactly the engine the mod will run on. - Several mods can hook one method:
beforehooks run in priority order,replacehooks nest,afterhooks chain results. A hook that throws is logged under its mod and skipped. hookonly works while a mod's script loads or runssetup, 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.- 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
through (like
engine.common.physics.move_body).#privatemembers can't be hooked, so 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 meshing.
- It isn't a stable API. A mod with
engine_accessmust setgame_versionwithin one minor version, and loading it on another is a load error. Withoutengine_access, importingbworld/engineis an error. - A server mod with engine access controls the game worker completely, but the worker still has no Deno permissions. The confirm screen for other sites lists which mods use it.
- Prefer the Game API. Many mods hooking the same thing is a sign it should become part of the Game API.
Forms
NeoForge has nothing like Bedrock's server forms, but they're the quickest way to ask a player something, so they stay,
built on menus: each kind of form is a menu whose screen the engine provides, so they
need no client code. The types are in common/mod_api/server.ts (message_form, action_form, modal_form).
const result = await ctx.ui.action_form(player, {
title: "Teleporter",
body: "Where to?",
buttons: [{ text: "Spawn", icon: "bworld:compass" }, { text: "Home" }],
});
if (!result.canceled && result.selection === 0) player.teleport(0, 100, 0);
- The form's definition is the menu's open data. A button press is a menu button with the button's index, and a modal form sends its values with its submit button.
- The promise resolves with
canceled: truewhen the menu closes any other way: the player closes it, disconnects, or another menu replaces it. - The engine checks every response against the form's definition (types, ranges, option counts, text length) before mod code sees it.
More Worn Items
Worn items are drawn by render_worn, which puts an item's worn model on a player's parts. The same can show more:
- Mobs' equipment.
EntityData.equipmentis already synced but never drawn.render_worncan draw it on mod entities whose bones are named like a humanoid's, and held items in theirright_arm, like Minecraft'sItemInHandLayer. - Other players' held items, in their right hand the same way.
- Hiding curio slots, like Curios' render toggles, sent by the client and kept by the curios script.
- A third person view. Players would see what they wear themselves with nothing else to change, the local player has
worntoo. - Glint and glowing overlays, as
glintand a full brightoverlay_textureinworn, once the renderer has a glint pass.
HUD, Keybinds and Mod Channels
ctx.hud.register(id, { on_render(g) })draws every frame after the world, under open screens.ctx.input.bind(id, default_key, on_press)with ids likecopper_tools:open_smelter, so a controls menu can rebind them. They only fire while no screen is open.ctx.neton both sides:on(channel, handler),send, andbroadcaston the server. Channel ids are in the mod's namespace, and a mod only sends on its own. Messages are at most 16 KB of JSON, each player can send at most 60 mod messages a second, and the server drops anything over that. On the wire it's{ type: "mod", channel, data }. Everything a client sends is untrusted.
The Engine and the Base Game
Like a Minetest game, bworld is the engine plus one mod, mods/bworld, written against the same API as any other mod.
If the base game can't be written as a mod, the API is missing something, and other mods would hit the same wall.
The engine keeps what every game built on it needs: rendering, meshing, lighting and the sky; physics, player
movement and input; networking, saving, the game server and its loop; registries, the mod loader and the Game API;
containers, slot click rules, screens and the GUI toolkit; entities; chat; world time; /tps; bworld:air; and the
engine assets in assets/.
mods/bworld has everything else:
| What | Where it is now | Status |
|---|---|---|
| Blocks, items, models, entities, recipes, textures, credits | mods/bworld |
Done |
| Hoeing, chest, furnace, smithing table, farming, watering can, fishing | mods/bworld/scripts/server.ts |
Done |
Recipe types shaped, furnace, fuel, smithing |
engine (common/mod_loader.ts, server/game/crafting.ts) |
Phase 5 |
| The player's inventory screen and crafting grid | engine (client/gui/gui_player_inventory.ts, server/game/crafting.ts) |
Phase 5 |
| The hotbar and crosshair | engine (client/gui/hud.ts) |
Phase 5 |
/give, /time and /summon |
engine (server/game/game_server.ts) |
Phase 5 |
Mining: tool speed, requires_tool, drops |
engine (client/game_mode.ts, server/game/game_server.ts) |
Phase 5 |
| Day and night lengths, sky colors | engine (common/time.ts, client/rendering/game_renderer.ts) |
Phase 5 |
| Where new players spawn | engine (server/game/world.ts) |
Phase 5 |
| Terrain, biomes and ores | mods/bworld/worldgen/ (data) |
Done |
| Trees | mods/bworld/scripts/trees.ts (a code feature) |
Done |
Rules That Keep Existing Worlds Working
- Ids don't change. Saves store blocks and items by string id, including inventories and chest contents.
- Terrain is identical, block for block. A save only stores what players changed on top of generated terrain. If the generator's output changes at all, every existing world silently changes with it.
- Old saves are upgraded when loading. The save format can change, as long as older saves load into the new shape.
tests/fixtures/keeps a save from each version. - The protocol can change, with
PROTOCOL_VERSION. Clients on another version are turned away before anything else happens.
Chunk Streaming
How the server sends the world, like Minecraft Java since 1.20.2. The code is in common/chunk_streaming.ts,
server/game/player_chunks.ts and client/level/client_level.ts.
- Whole chunks. A
level_chunkis a binary websocket message with every block of a 16×256×16 chunk and its columns' biomes, deflated. Blocks are in 16 sections of 16×16×16, each a paletted container like Minecraft's: one value when the section is all one block, a palette and 1, 2, 4 or 8 bits per block up to 256 kinds, and whole values past that. Light isn't sent. - Numeric ids. Chunks use the server's numeric block ids, and
join.blockslists the string id for each, like Minecraft's registry sync. Clients translate them as a chunk loads. - The view. Players send their view distance with
readyandview_distance. The server uses up to 16 chunks, and sends a round area around the player plus the ring past it, which clients need to mesh and light the edge (Minecraft'sChunkTrackingView). Moving into another chunk sendsset_center_chunk, andforget_level_chunkfor each chunk that left the view. - Batches. Chunks go out nearest first, between
chunk_batch_startandchunk_batch_finished { size }. The client answerschunk_batch_received { chunks_per_tick }: as many chunks as fit in 7 ms a tick. Until the first answer there's one batch of 9 in flight, after it up to 10. The server stops building chunks for a tick after 20 ms. - Changes.
set_blockonly goes to players that have the chunk.
Phases
Each phase ends with every test passing and the game playable.
Phase 1: loading and common scripts. scripts.common bundled like the client script and run on both sides between
each mod's data and the next mod. CommonContext, with the JSON loader going through the same functions. The freeze and
the registry hash. Recipe types as ids with register_type. Check: a test mod registers content from code, and the
server and a client end up with equal registries and hashes.
Phase 2: overrides. override and extend in common scripts, overrides/*.json, recipes.remove, and the
check-mods rules. Check: a test mod adds a component to bworld:grass, changes bworld:glass's toughness and
replaces the chest recipe, on both sides and in the hash.
Phase 3: engine access. The global engine modules and the bworld/engine shim, hook, engine_access in the
manifest and its checks, and making the engine hookable where mods will want it. Check: test mods hook a server, a
client and a worldgen method, hooks on one method run in priority order, and a throwing hook is logged without breaking
the game.
Phase 4: the rest of the Game API. Keybinds, forms built on menus, and HUD elements. More events: items picked up and dropped, containers clicked, players moving between chunks, entities.
Phase 5: gameplay out of the engine. Everything marked phase 5 in the table above moves into mods/bworld. Mining
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.
Phase 6: world generation. Moved to data instead of a worldgen script, see GENERATION.md. The
golden fixture, the ore table, and the terrain, biomes, surface and water as data are done: the server refuses to start
without the bworld:overworld generator, and the fixture matches exactly. Trees are a code feature in bworld's worldgen
script.
Done when searching client/, common/ and server/ for "bworld: finds only bworld:air, removing
mods/bworld gives an engine that starts and says it needs a terrain generator, the base game uses no engine access,
and a world saved before any of this plays exactly the same.
Open Questions
- Client-only mods. Should players install their own client mods (minimaps, UI tweaks) that work on any server, like NeoForge's mods that only load on the client? They'd need a separate kind of mod that can't add content or change the registry hash, and servers might want to forbid them.
- Client-side prediction for mods. Block components only run on the server, so interacting with a mod block always waits a round trip. Components could get optional handlers that clients run to predict.
- Engine access versions. Tying engine access mods to one minor version is simple but strict.
- Game API versions. Only breaking with the game's major version needs deprecation warnings and a changelog.
- Entities. Mods can define simple animals, but there's no API for entity types with their own behavior, animations, or natural spawning.
- Hot reload. Restarting the server and rejoining is the answer for now.