Files
bworld/client/mods.ts
T
2026-10-03 13:41:01 -03:00

214 lines
7.2 KiB
TypeScript

// loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts.
// see docs/modding/networking/index.md
import { AIR } from "$/common/constants.ts";
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
import { type Bmod, read_bmod } from "$/common/bmod.ts";
import { display_name } from "$/common/utils.ts";
import { tag_api } from "$/common/tags.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { Client } from "./client.ts";
import { code_url, fetch_verified } from "./handshake.ts";
import { GuiModScreen } from "./gui/gui_mod_screens.ts";
// each loaded mod's credits file, for the credits screen
export const mod_credits: { name: string; version: string; text: string }[] = [];
// set once the game is running, mods can't look at it during setup
let client: Client | undefined;
// what mods draw on inventory screens, see GuiInventoryScreen
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
// each menu type's screen, see ctx.ui.register_menu_screen
export const menu_screens = new Map<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
// mod channels, see ctx.net: who listens on each channel
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
// the server sent a mod message
export function receive_mod_message(channel: string, data: unknown) {
for (const { mod, handler } of net_handlers.get(channel) ?? []) {
try {
handler(data);
} catch (e) {
console.error(`[${mod}] a ${channel} handler threw:`, e);
}
}
}
// the loaded mods' recipes, and their names by id
let recipe_book = new RecipeBook();
const mod_names = new Map<string, string>();
export function set_mods_client(game_client: Client) {
client = game_client;
}
// downloads every mod's .bmod and checks it against the hash the server listed. everything a mod runs comes from
// the checked bytes, never fetched twice
export async function download_mods(listings: ModListing[], base: URL): Promise<Bmod[]> {
return await Promise.all(listings.map(async (listing) => {
try {
const bytes = await fetch_verified(new URL(listing.file, base), listing.sha256, `${listing.name}`);
const bmod = read_bmod(bytes, `${listing.id}.bmod`);
if (bmod.manifest.id !== listing.id) throw new Error(`the server listed it as ${listing.id}`);
return bmod;
} catch (e) {
throw new ModLoadError(listing.id, (e as Error).message);
}
}));
}
// registers the mods' data and runs their client scripts, in the order the server listed them
export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
for (const [i, bmod] of bmods.entries()) {
if (bmod.credits) {
mod_credits.push({ name: listings[i].name, version: listings[i].version, text: bmod.credits });
}
}
const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data })));
recipe_book = recipes;
inventory_overlays.length = 0;
menu_screens.clear();
net_handlers.clear();
mod_names.clear();
for (const listing of listings) mod_names.set(listing.id, listing.name);
for (const [i, bmod] of bmods.entries()) {
if (!bmod.scripts.client) continue;
const module = await import(script_url(bmod.scripts.client));
if (typeof module.setup !== "function") {
throw new ModLoadError(bmod.manifest.id, "the client script doesn't export a setup function");
}
await module.setup(client_context(listings[i]));
}
}
function script_url(code: string) {
return code_url(new TextEncoder().encode(code));
}
function client_context(listing: ModListing): ClientContext {
const mod = listing.id;
const not_yet = (name: string, where: string) =>
new Proxy({}, {
get: (_, prop) => () => {
throw new Error(
`[${mod}] ctx.${name}.${String(prop)} isn't implemented yet (${where}, see docs/modding_plan.md)`,
);
},
});
const need_client = () => {
if (!client) throw new Error(`[${mod}] the world isn't there yet during setup`);
return client;
};
const own = (id: string, what = "channel") => {
if (!id.startsWith(`${mod}:`)) {
throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`);
}
};
const known_item = (id: string) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`[${mod}] unknown item ${id}`);
return item;
};
return {
mod: { id: mod, version: listing.version },
ui: {
register_menu_screen(type, create) {
own(type, "menu type");
if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`);
menu_screens.set(type, { mod, create });
},
open(screen) {
if (typeof screen?.on_render !== "function") throw new Error(`[${mod}] a screen needs an on_render`);
const game = need_client();
game.push_screen(new GuiModScreen(game, mod, screen));
},
close() {
need_client().pop_screen();
},
add_inventory_overlay(overlay) {
inventory_overlays.push({ mod, overlay });
},
},
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
input: not_yet("input", "keybinds") as ClientContext["input"],
options: key_mappings(need_client),
net: {
on(channel, handler) {
own(channel);
const handlers = net_handlers.get(channel) ?? [];
handlers.push({ mod, handler: handler as (data: unknown) => void });
net_handlers.set(channel, handlers);
},
send(channel, data) {
own(channel);
need_client().connection.send({ type: "mod", channel, data });
},
},
player: {
get name() {
return need_client().connection.name;
},
get position() {
const { x, y, z } = need_client().player;
return { x, y, z };
},
is_swimming: () => need_client().player.swimming,
},
world: {
get_block(x, y, z) {
const nid = need_client().level.get_block(x, y, z);
if (nid === AIR) return AIR_ID;
return EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid)?.id;
},
get time() {
return need_client().level.time;
},
},
items: {
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
name: (id) => (known_item(id), display_name(id)),
mod(id) {
known_item(id);
const namespace = id.split(":")[0];
return mod_names.get(namespace) ?? namespace;
},
},
recipes: {
list: (type) =>
structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all),
},
tags: tag_api(),
log: (...args) => console.log(`[${mod}]`, ...args),
};
}
// the client's key settings as they are when read, so changing them reaches mods
function key_mappings(client: () => Client): KeyMappings {
const keys = [
"key_forward",
"key_back",
"key_left",
"key_right",
"key_jump",
"key_sprint",
"key_sneak",
"key_inventory",
"key_drop",
"key_chat",
] as const;
const mappings = {} as KeyMappings;
for (const key of keys) {
Object.defineProperty(mappings, key, { get: () => client().options[key], enumerable: true });
}
return Object.freeze(mappings);
}