Files
bworld/server/game/mod_runtime.ts
T
2026-10-07 20:56:24 -03:00

1275 lines
43 KiB
TypeScript

// runs mods' server scripts: builds each one's ServerContext and keeps what they register.
// see docs/modding/. parts not built yet throw when used, saying so
import { BlockRegistry, EverythingRegistry, ItemRegistry, liquid_height } from "$/common/everything_registry.ts";
import { Container as EngineContainer, ItemStack as EngineItemStack } from "$/common/inventory.ts";
import { get_state_value, is_waterlogged, liquid_block, set_state_value } from "$/common/utils.ts";
import { collision_shape_at, covers_face, raycast_blocks, type Shape } from "$/common/block_shapes.ts";
import { AIR, ID_MASK } from "$/common/constants.ts";
import { BlockRules } from "$/common/block_rules.ts";
import type { SharedContext } from "$/common/mod_api/shared.ts";
import { tag_api } from "$/common/tags.ts";
import { loading_mod } from "$/common/hooks.ts";
import type {
BlockComponent,
BlockRef,
Command,
CommandRegistry,
CommandSource,
Container,
EffectComponent,
EntityRef,
EventSignal,
ItemComponent,
ItemStack,
LivingRef,
MenuBuilder,
MenuHandle,
MenuType,
Player,
PlayerMenuBuilder,
ServerAfterEvents,
ServerBeforeEvents,
ServerContext,
SlotOptions,
} from "$/common/mod_api/server.ts";
import { ModLoadError } from "$/common/mod_loader.ts";
import {
argument,
block as block_argument,
boolean,
choice,
CommandDispatcher,
CommandError,
CommandNode,
greedy_string,
integer,
item,
literal,
number,
word,
} from "$/common/commands.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { GameServer } from "./game_server.ts";
import type { ServerPlayer } from "./player.ts";
import { Menu, type MenuSlot } from "./menu.ts";
import { damage_source, type Entity } from "./entity/entity.ts";
import type { LivingEntity } from "./entity/living_entity.ts";
import type { EffectJson } from "$/common/mod_data.ts";
import { create_entity } from "./entity/entity_types.ts";
import { attribute_type, type AttributeType, MODIFIER_OPERATIONS } from "./entity/attributes.ts";
import { effect_type, EffectInstance, type EffectType } from "./entity/effects.ts";
// a list of handlers that can't break each other: one throwing is logged under its mod and the rest still run
export class Signal<T> {
#handlers: { mod: string; handler: (event: T) => void }[] = [];
for_mod(mod: string): EventSignal<T> {
return {
subscribe: (handler) => {
const entry = { mod, handler };
this.#handlers.push(entry);
return () => {
this.#handlers = this.#handlers.filter((h) => h !== entry);
};
},
};
}
emit(event: T) {
for (const { mod, handler } of [...this.#handlers]) {
run_guarded(mod, "an event handler", () => handler(event));
}
}
get empty() {
return this.#handlers.length === 0;
}
}
// the mod whose code is running right now, for apis shared between mods that need to know who called
let running_mod = "";
// a mod's script, imported from url. engine_access lets it import bworld/engine
interface ScriptSource {
mod: string;
version: string;
url: string;
engine_access: boolean;
}
export function run_guarded<T>(mod: string, what: string, fn: () => T): T | undefined {
const previous = running_mod;
running_mod = mod;
try {
return fn();
} catch (e) {
console.error(`[${mod}] ${what} threw:`, e);
return undefined;
} finally {
running_mod = previous;
}
}
type Before = {
[K in keyof ServerBeforeEvents]: ServerBeforeEvents[K] extends EventSignal<infer T> ? Signal<T> : never;
};
type After = { [K in keyof ServerAfterEvents]: ServerAfterEvents[K] extends EventSignal<infer T> ? Signal<T> : never };
interface Timer {
mod: string;
fn: () => void;
at: number;
every?: number;
}
export class ModRuntime {
block_components = new Map<string, { mod: string; component: BlockComponent }>();
// what shared scripts registered, see common/block_rules.ts
rules = new BlockRules(run_guarded);
item_components = new Map<string, { mod: string; component: ItemComponent }>();
effect_components = new Map<string, { mod: string; component: EffectComponent }>();
// every command, the engine's and mods', see common/commands.ts
commands = new CommandDispatcher<ServerCommandSource>();
// who registered each command name: "engine" or a mod's id
command_owners = new Map<string, string>();
before: Before = {
block_break: new Signal(),
block_place: new Signal(),
block_interact: new Signal(),
chat_send: new Signal(),
player_damage: new Signal(),
};
after: After = {
block_break: new Signal(),
block_place: new Signal(),
block_interact: new Signal(),
chat_send: new Signal(),
player_join: new Signal(),
player_leave: new Signal(),
player_damage: new Signal(),
player_death: new Signal(),
server_start: new Signal(),
tick: new Signal(),
new_day: new Signal(),
};
// per mod key value storage, saved with the world
storage: Record<string, Record<string, unknown>> = {};
#timers = new Map<number, Timer>();
// containers mods listen to with on_change, compared slot by slot every tick
#watched: { mod: string; container: EngineContainer; last: string[]; fn: (slot: number) => void }[] = [];
#next_timer = 1;
#setting_up = true;
#players = new WeakMap<ServerPlayer, Player>();
// mod channels, see ctx.net: who listens on each channel
#net_handlers = new Map<string, { mod: string; handler: (player: Player, data: unknown) => void }[]>();
// mod messages each player sent this second, to drop floods
#net_counts = new WeakMap<ServerPlayer, { second: number; count: number }>();
// a player's client sent a mod message. clients are untrusted: too big or too many are dropped
receive(player: ServerPlayer, channel: string, data: unknown) {
if (!this.#count_message(player)) return;
if ((JSON.stringify(data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) return;
for (const { mod, handler } of this.#net_handlers.get(channel) ?? []) {
run_guarded(mod, `a ${channel} handler`, () => handler(this.player(player), data));
}
}
// a client pressed a button of its open menu. buttons count as mod messages, clients are untrusted
menu_button(player: ServerPlayer, menu: Menu, button: number) {
if (!this.#count_message(player)) return;
for (const fn of [...menu.on_button]) fn(button);
}
// false once a player has sent too many this second
#count_message(player: ServerPlayer): boolean {
const second = Math.floor(Date.now() / 1000);
let counts = this.#net_counts.get(player);
if (!counts || counts.second !== second) {
counts = { second, count: 0 };
this.#net_counts.set(player, counts);
}
return ++counts.count <= MAX_MOD_MESSAGES_PER_SECOND;
}
// the other way, for apis that take a player
#server_players = new WeakMap<Player, ServerPlayer>();
// menu types by id, every mod's
#menu_types = new Set<string>();
// what each mod adds to the player's own menu, in load order
#player_menu_builders: { mod: string; build: (menu: PlayerMenuBuilder, player: Player) => void }[] = [];
// a player joined: the mods' slots go after menu 0's own. one that throws is logged and the rest still run
extend_player_menu(player: ServerPlayer) {
const api = this.player(player);
for (const { mod, build } of this.#player_menu_builders) {
const menu = player.inventory_menu;
const added: MenuSlot[] = [];
const ok = run_guarded(mod, "an extend_player_menu", () => {
build({
add_slot: (container, slot, options) => {
added.push(menu_slot(this.game, mod, player, container, slot, options));
return menu.slots.length + added.length - 1;
},
}, api);
return true;
});
// all of a mod's slots or none, so a half built set can't shift the next mod's
if (ok) menu.slots.push(...added);
}
}
game!: GameServer;
// imports each server script and calls its setup, in load order
// shared scripts, the block rules clients run too. their world is the server's
async load_shared_scripts(game: GameServer, scripts: ScriptSource[]) {
this.game = game;
for (const { mod, version, url, engine_access } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url));
}
}
async #load_shared_script(mod: string, version: string, url: string) {
const module = await import(url);
if (typeof module.setup !== "function") {
throw new ModLoadError(mod, "the shared script doesn't export a setup function");
}
const { world } = this.#context(mod, version);
const ctx: SharedContext = {
mod: { id: mod, version },
side: "server",
tags: tag_api(),
world: {
get_block: world.get_block,
get_state: world.get_state,
set_state: world.set_state,
is_face_sturdy: world.is_face_sturdy,
},
components: {
register_block: (id, rules) => {
if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup");
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `component ${id} must be in the namespace "${mod}"`);
}
this.rules.register(mod, id, rules);
},
},
};
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 } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_script(mod, version, url));
}
}
async #load_script(mod: string, version: string, url: string) {
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));
} finally {
running_mod = "";
}
}
// every effect mods define, from their json. they're made before scripts run, since the world loads first and
// its mobs can have effects, so their components are looked up as they tick
effect_types(): EffectType[] {
return EverythingRegistry.entries<EffectJson>("effects").map(([id, json]) => {
const modifiers = (json.modifiers ?? []).map(({ attribute, amount, operation }) => {
const type = attribute_type(attribute);
if (!type) {
throw new ModLoadError(
id.split(":")[0],
`effect ${id} changes ${attribute}, which isn't an attribute`,
);
}
return { attribute: type, amount, operation };
});
const components = Object.entries(json.components ?? {});
const on_tick = (entity: LivingEntity, ticks: number | undefined, amplifier: number) => {
let keep = true;
for (const [component_id, params] of components) {
const { mod, component } = this.effect_components.get(component_id)!;
const due = ticks === undefined || !component.should_tick ||
run_guarded(
mod,
`${component_id} should_tick`,
() => component.should_tick!(ticks, amplifier, params),
);
if (!due || !component.on_tick) continue;
const result = run_guarded(
mod,
`${component_id} on_tick`,
() => component.on_tick!(living_ref(entity), amplifier, params),
);
if (result === false) keep = false;
}
return keep;
};
return {
id,
category: json.category ?? "neutral",
instant: json.instant === true,
modifiers,
on_tick: components.length > 0 ? on_tick : undefined,
};
});
}
// after every setup ran: registration closes and every component blocks, items and effects use must exist
finish_setup() {
this.#setting_up = false;
for (const [id, effect] of EverythingRegistry.entries<EffectJson>("effects")) {
for (const component of Object.keys(effect.components ?? {})) {
if (!this.effect_components.has(component)) {
throw new ModLoadError(
id.split(":")[0],
`effect ${id} uses component ${component}, which nothing registered`,
);
}
}
}
for (const [id, block] of EverythingRegistry.entries<{ components?: Record<string, unknown> }>("blocks")) {
for (const component of Object.keys(block.components ?? {})) {
if (!this.block_components.has(component) && !this.rules.has(component)) {
throw new ModLoadError(
id.split(":")[0],
`block ${id} uses component ${component}, which nothing registered`,
);
}
}
}
for (const [id, item] of EverythingRegistry.entries<ItemRegistry>("items")) {
const components = Object.entries(item.components ?? {});
if (components.length === 0) continue;
for (const [component_id] of components) {
if (!this.item_components.has(component_id)) {
throw new ModLoadError(
id.split(":")[0],
`item ${id} uses component ${component_id}, which nothing registered`,
);
}
}
const lore = components.filter(([component_id]) =>
this.item_components.get(component_id)!.component.get_lore
);
if (lore.length > 0) {
item.get_lore = (stack) =>
lore.map(([component_id, params]) => {
const { mod, component } = this.item_components.get(component_id)!;
return run_guarded(mod, `${component_id} get_lore`, () =>
component.get_lore!(item_api(stack), params));
}).filter((line) =>
typeof line === "string"
).join("\n");
}
// items are created all over the engine, hook their creation once here
const previous = item.on_create;
item.on_create = (stack) => {
previous?.(stack);
for (const [component_id, params] of components) {
const { mod, component } = this.item_components.get(component_id)!;
if (component.on_create) {
run_guarded(
mod,
`${component_id} on_create`,
() => component.on_create!(item_api(stack), params),
);
}
}
};
}
}
// adds a command, and for mods the same command as /mod:name so it can always be told apart
register_command(owner: string, node: CommandNode<ServerCommandSource>) {
if (!/^[a-z0-9_]+$/.test(node.name)) {
throw new Error(`command name "${node.name}" must be a-z, 0-9 and _`);
}
const existing = this.command_owners.get(node.name);
if (existing) {
throw new Error(
existing === "engine"
? `/${node.name} belongs to the engine`
: `/${node.name} is also registered by ${existing}`,
);
}
this.commands.register(node);
this.command_owners.set(node.name, owner);
if (owner !== "engine") {
const alias = new CommandNode<ServerCommandSource>(`${owner}:${node.name}`);
alias.children.push(...node.children);
alias.command = node.command;
alias.requirement = node.requirement;
alias.description = node.description;
this.commands.root.then(alias);
this.command_owners.set(alias.name, owner);
}
}
// components on a block, with their params from its json
components_of(block_id: string): { mod: string; id: string; component: BlockComponent; params: unknown }[] {
const block = EverythingRegistry.get<{ components?: Record<string, unknown> }>("blocks", block_id);
// components that only have shared rules have nothing here
return Object.entries(block?.components ?? {}).flatMap(([id, params]) => {
const registered = this.block_components.get(id);
return registered ? [{ ...registered, id, params }] : [];
});
}
// components on an item, with their params from its json
item_components_of(item_id: string): { mod: string; id: string; component: ItemComponent; params: unknown }[] {
const item = EverythingRegistry.get<ItemRegistry>("items", item_id);
return Object.entries(item?.components ?? {}).map(([id, params]) => ({
...this.item_components.get(id)!,
id,
params,
}));
}
watch_container(mod: string, container: EngineContainer, fn: (slot: number) => void) {
const entry = { mod, container, fn, last: snapshot(container) };
this.#watched.push(entry);
return () => {
this.#watched = this.#watched.filter((w) => w !== entry);
};
}
// items change in many places (clicks, drops, crafting, scripts), so compare instead of hooking every one
check_watched_containers() {
for (const watch of [...this.#watched]) {
const now = snapshot(watch.container);
const changed = now.flatMap((slot, i) => slot !== watch.last[i] ? [i] : []);
watch.last = now;
for (const slot of changed) {
run_guarded(watch.mod, "a container on_change", () => watch.fn(slot));
}
}
}
tick() {
const now = this.game.current_tick;
for (const [handle, timer] of [...this.#timers]) {
if (timer.at > now) continue;
if (timer.every) {
timer.at = now + timer.every;
} else {
this.#timers.delete(handle);
}
run_guarded(timer.mod, "a timer", timer.fn);
}
if (!this.after.tick.empty) {
this.after.tick.emit({ dt: 1 / 20 });
}
}
player(player: ServerPlayer): Player {
let api = this.#players.get(player);
if (!api) {
api = player_api(this.game, player);
this.#players.set(player, api);
this.#server_players.set(api, player);
}
return api;
}
block_ref(x: number, y: number, z: number, id: string): BlockRef {
const game = this.game;
return {
id,
x,
y,
z,
get data() {
return game.world.get_tile(x, y, z)?.mod_data;
},
set data(value) {
game.get_or_create_tile(x, y, z).mod_data = value;
game.world.dirty = true;
},
};
}
#context(mod: string, version: string): ServerContext {
const setup_only = (what: string) => {
if (!this.#setting_up) {
throw new Error(`[${mod}] ${what} can only be registered during setup`);
}
};
const own = (id: string, what: string) => {
if (!id.startsWith(`${mod}:`)) {
throw new ModLoadError(mod, `${what} ${id} must be in the namespace "${mod}"`);
}
};
const game = () => this.game;
const ctx: ServerContext = {
mod: { id: mod, version },
components: {
register_block: (id, component) => {
setup_only("components");
own(id, "component");
if (this.block_components.has(id)) {
throw new ModLoadError(mod, `component ${id} is registered twice`);
}
this.block_components.set(id, { mod, component: component as BlockComponent });
},
register_item: (id, component) => {
setup_only("components");
own(id, "component");
if (this.item_components.has(id)) {
throw new ModLoadError(mod, `component ${id} is registered twice`);
}
this.item_components.set(id, { mod, component: component as ItemComponent });
},
register_effect: (id, component) => {
setup_only("components");
own(id, "component");
if (this.effect_components.has(id)) {
throw new ModLoadError(mod, `component ${id} is registered twice`);
}
this.effect_components.set(id, { mod, component: component as EffectComponent });
},
},
commands: {
register: (name_or_node: string | CommandNode<CommandSource>, command?: Command) => {
setup_only("commands");
const node = typeof name_or_node === "string"
? simple_command(name_or_node, command!)
: name_or_node as unknown as CommandNode<ServerCommandSource>;
try {
this.register_command(mod, node as CommandNode<ServerCommandSource>);
} catch (e) {
throw new ModLoadError(mod, (e as Error).message);
}
},
literal: (name) => literal<CommandSource>(name),
argument: (name, type) => argument(name, type),
types: {
integer,
number,
boolean,
word,
greedy_string,
choice,
item: () => item(),
block: () => block_argument(),
player: () => ({
parse: (text: string) => {
const found = game().players().find((p) => p.name === text);
if (!found) throw new CommandError(`${text} isn't online`);
return this.player(found);
},
suggest: (partial: string) =>
game().players().filter((p) => p.name.startsWith(partial)).map((p) => ({ text: p.name })),
}),
},
} as CommandRegistry,
events: {
before: map_signals(this.before, mod),
after: map_signals(this.after, mod),
},
system: {
run_timeout: (fn, ticks) => this.#add_timer(mod, fn, ticks),
run_interval: (fn, ticks) => this.#add_timer(mod, fn, ticks, Math.max(1, ticks)),
clear_run: (handle) => void this.#timers.delete(handle),
get current_tick() {
return game().current_tick;
},
},
world: {
get_block: (x, y, z) => game().world.get_block_id(x, y, z),
set_block: (x, y, z, id) => {
if (id !== AIR_ID && !EverythingRegistry.get("blocks", id)) throw new Error(`unknown block ${id}`);
game().set_block(x, y, z, id);
return true;
},
break_block: (x, y, z) => {
if (game().world.get_block_id(x, y, z) === AIR_ID) return false;
game().destroy_block(x, y, z);
return true;
},
get_state: (x, y, z, name) => {
const id = game().world.get_block_id(x, y, z);
if (id === AIR_ID) return undefined;
const info = state_owner(id, name);
return get_state_value(game().world.get_block_value(x, y, z), info, name);
},
set_state: (x, y, z, name, value) => {
const id = game().world.get_block_id(x, y, z);
if (id === AIR_ID) return false;
const info = state_owner(id, name);
const bits = info.states!.find((s) => s.name === name)!.bits;
if (!Number.isInteger(value) || value < 0 || value >= 2 ** bits) {
throw new Error(`${id} state "${name}" has ${bits} bits, ${value} doesn't fit`);
}
const new_value = set_state_value(game().world.get_block_value(x, y, z), info, name, value)!;
game().set_block_state(x, y, z, new_value >>> 16);
return true;
},
is_face_sturdy: (x, y, z, face) => covers_face(game().world.collision_shape(x, y, z), face),
get_block_data: (x, y, z) => game().world.get_tile(x, y, z)?.mod_data as never,
set_block_item: (x, y, z, item) => {
if (game().world.get_block_id(x, y, z) === AIR_ID) return;
if (!item || item.count <= 0) {
const tile = game().world.get_tile(x, y, z);
if (tile?.item) game().world.set_tile_item(tile, undefined);
return;
}
game().world.set_tile_item(game().get_or_create_tile(x, y, z), new_stack(item).to_data());
},
get_block_item: (x, y, z) => {
const item = game().world.get_tile(x, y, z)?.item;
return item && structuredClone(item);
},
drop_item: (x, y, z, item) => void game().pop_item(x, y, z, new_stack(item)),
spawn_entity: (id, x, y, z) => {
const entity = EverythingRegistry.get("entities", id)
? create_entity(game().entities, id)
: undefined;
if (!entity) throw new Error(`unknown entity ${id}`);
entity.set_position(x, y, z);
game().entities.add_entity(entity);
return entity_ref(entity);
},
raycast: (from, to, options) => {
const liquids = options?.liquids ?? "none";
if (!["none", "source_only", "any"].includes(liquids)) {
throw new Error(`liquids must be "none", "source_only" or "any", not ${liquids}`);
}
const origin = [from.x, from.y, from.z];
const length = Math.hypot(to.x - from.x, to.y - from.y, to.z - from.z);
if (!Number.isFinite(length)) throw new Error("raycast needs two points with finite x, y and z");
if (length === 0) return undefined;
const direction = [(to.x - from.x) / length, (to.y - from.y) / length, (to.z - from.z) / length];
const world = game().world;
const hit = raycast_blocks(
origin,
direction,
length,
(x, y, z) => raycast_shape(world, x, y, z, liquids),
);
if (!hit) return undefined;
// what was hit in a waterlogged block with liquids on is its liquid, see raycast_shape
const value = world.get_block_value(hit.x, hit.y, hit.z);
const block = world.get_block_info(hit.x, hit.y, hit.z);
const liquid = liquids === "none" ? undefined : liquid_block(value, block);
return {
id: liquid?.id ?? world.get_block_id(hit.x, hit.y, hit.z),
x: hit.x,
y: hit.y,
z: hit.z,
face: hit.face,
position: {
x: from.x + direction[0] * hit.distance,
y: from.y + direction[1] * hit.distance,
z: from.z + direction[2] * hit.distance,
},
};
},
is_loaded: () => true,
get seed() {
return game().world.seed;
},
get time() {
return game().world.time;
},
get day() {
return game().world.day;
},
set_time: (time) => {
if (!Number.isInteger(time) || time < 0) {
throw new Error(`time must be a whole number of ticks, not ${time}`);
}
game().set_time(time);
},
},
players: {
all: () => game().players().map((p) => this.player(p)),
get: (id) => {
const p = game().players().find((p) => p.id === id);
return p && this.player(p);
},
by_name: (name) => {
const p = game().players().find((p) => p.name === name);
return p && this.player(p);
},
},
items: {
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
max_stack: (id) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`unknown item ${id}`);
return item.max_stack ?? (item.tool ? 1 : 64);
},
tool: (id) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`unknown item ${id}`);
return item.tool?.type;
},
sell_value: (id) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`unknown item ${id}`);
return item.base_sell_value;
},
components: (id) => {
const item = EverythingRegistry.get<ItemRegistry>("items", id);
if (!item) throw new Error(`unknown item ${id}`);
return structuredClone(item.components ?? {});
},
},
blocks: {
exists: (id) => EverythingRegistry.get("blocks", id) !== undefined,
components: (id) => {
const block = EverythingRegistry.get<BlockRegistry>("blocks", id);
if (!block) throw new Error(`unknown block ${id}`);
return structuredClone(block.components ?? {});
},
},
recipes: {
furnace_result: (input) => {
const recipe = game().recipes.furnace.get(input);
return recipe && { output: { ...recipe.output }, cook_time: recipe.cook_time };
},
fuel_value: (item) => game().recipes.fuel.get(item) ?? 0,
is_fuel: (item) => game().recipes.fuel.has(item),
is_smeltable: (item) => game().recipes.furnace.has(item),
smithing: (tool, material, addition) => {
const recipe = game().recipes.smithing.find((r) =>
r.tool === tool && r.material.id === material && r.addition === addition
);
return recipe && { result: recipe.result, material_count: recipe.material.count };
},
list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []),
},
tags: tag_api(),
containers: {
create: (size) => {
if (!Number.isInteger(size) || size < 1 || size > MAX_CONTAINER_SIZE) {
throw new Error(`a container has 1 to ${MAX_CONTAINER_SIZE} slots, not ${size}`);
}
const { id, container } = game().create_container(size);
return container_api(game(), id, container);
},
get: (id) => {
const container = game().containers.get(id);
return container && container_api(game(), id, container);
},
delete: (id) => game().delete_container(id),
},
menus: {
extend_player_menu: (build) => {
setup_only("extend_player_menu");
this.#player_menu_builders.push({ mod, build });
},
register: <Args>(id: string, build: (menu: MenuBuilder, args: Args, player: Player) => void) => {
own(id, "menu type");
if (this.#menu_types.has(id)) throw new Error(`[${mod}] menu type ${id} is already registered`);
this.#menu_types.add(id);
const type: MenuType<Args> = {
id,
open: (player, args) => this.#open_menu(mod, id, player, (menu) => build(menu, args, player)),
};
return type;
},
},
ui: {
message_form: not_yet(mod, "ui.message_form", "see docs/modding_plan.md"),
action_form: not_yet(mod, "ui.action_form", "see docs/modding_plan.md"),
modal_form: not_yet(mod, "ui.modal_form", "see docs/modding_plan.md"),
},
net: {
on: (channel, handler) => {
own(channel, "channel");
const handlers = this.#net_handlers.get(channel) ?? [];
handlers.push({ mod, handler: handler as (player: Player, data: unknown) => void });
this.#net_handlers.set(channel, handlers);
},
send: (player, channel, data) => {
own(channel, "channel");
const server_player = this.#server_players.get(player);
if (!server_player || !game().players().includes(server_player)) {
throw new Error(`${player.name} isn't online`);
}
game().send_mod_message(server_player, channel, data);
},
broadcast: (channel, data) => {
own(channel, "channel");
for (const player of game().players()) game().send_mod_message(player, channel, data);
},
},
storage: {
get: (key) => structuredClone(this.storage[mod]?.[key]) as never,
set: (key, value) => {
(this.storage[mod] ??= {})[key] = structuredClone(value);
game().world.dirty = true;
},
delete: (key) => {
delete this.storage[mod]?.[key];
game().world.dirty = true;
},
},
log: (...args) => console.log(`[${mod}]`, ...args),
};
return ctx;
}
// builds a menu with the mod's function and opens it. a build that throws opens nothing
#open_menu(mod: string, type: string, player: Player, build: (menu: MenuBuilder) => void): MenuHandle {
const game = this.game;
const server_player = this.#server_players.get(player);
if (!server_player || !game.players().includes(server_player)) {
throw new Error(`${player.name} isn't online`);
}
const menu = new Menu(game.next_menu_id(server_player), type);
const guarded = <T>(what: string, fn: () => T) => run_guarded(mod, what, fn);
build({
get title() {
return menu.title;
},
set title(value) {
menu.title = String(value);
},
get open_data() {
return menu.open_data;
},
set open_data(value) {
menu.open_data = structuredClone(value) ?? null;
},
add_slot(container, slot, options) {
menu.slots.push(menu_slot(game, mod, server_player, container, slot, options));
return menu.slots.length - 1;
},
add_player_inventory(x, y) {
const first = menu.slots.length;
for (let i = 0; i < server_player.inventory.size; i++) {
// the rest of the inventory in rows from x and y, the hotbar under it like minecraft's
const row = i < 9 ? 0 : Math.floor(i / 9) - 1;
menu.slots.push({
container: server_player.inventory,
index: i,
x: x + (i % 9) * 18,
y: i < 9 ? y + 58 : y + row * 18,
inventory: i,
});
}
return first;
},
add_data(name, get) {
menu.data.set(String(name), () => guarded(`menu data ${name}`, get) ?? 0);
},
still_valid(check) {
menu.still_valid.push(() => guarded("a still_valid", () => check(player)) !== false);
},
still_valid_near(block) {
const { id, x, y, z } = block;
menu.still_valid.push(() => {
const [dx, dy, dz] = [
server_player.x - x - 0.5,
server_player.y - y - 0.5,
server_player.z - z - 0.5,
];
return dx * dx + dy * dy + dz * dz <= MENU_REACH * MENU_REACH &&
game.world.get_block_id(x, y, z) === id;
});
},
on_button(fn) {
menu.on_button.push((button) => guarded("an on_button", () => fn(player, button)));
},
quick_move(fn) {
menu.quick_move_order = (index) => {
const order = guarded("a quick_move", () => fn(player, index));
return Array.isArray(order) ? order.filter((i) => Number.isInteger(i)) : [];
};
},
on_tick(fn) {
menu.on_tick.push(() => guarded("a menu on_tick", fn));
},
on_close(fn) {
menu.on_close.push(() => guarded("a menu on_close", fn));
},
});
if ((JSON.stringify(menu.open_data) ?? "").length > MAX_MOD_MESSAGE_LENGTH) {
throw new Error(`the open_data of ${type} is over 16 KB`);
}
let open = true;
menu.on_close.unshift(() => open = false);
game.open_menu(server_player, menu);
return {
player,
get open() {
return open;
},
close() {
if (server_player.menu === menu) game.close_menu(server_player);
},
on_close(fn) {
if (!open) {
guarded("a menu on_close", fn);
return;
}
menu.on_close.push(() => guarded("a menu on_close", fn));
},
};
}
#add_timer(mod: string, fn: () => void, ticks: number, every?: number) {
const handle = this.#next_timer++;
this.#timers.set(handle, { mod, fn, at: this.game.current_tick + Math.max(0, ticks), every });
return handle;
}
}
// each event's signal, as seen by one mod so errors say which mod threw
// a block that has this state, or an error saying it doesn't
function state_owner(id: string, name: string): BlockRegistry {
const info = EverythingRegistry.get<BlockRegistry>("blocks", id)!;
if (!info.states?.some((s) => s.name === name)) {
throw new Error(`${id} has no state "${name}"`);
}
return info;
}
function snapshot(container: EngineContainer): string[] {
return container.to_data().map((item) => JSON.stringify(item));
}
function map_signals<T extends { [name: string]: { for_mod(mod: string): unknown } }>(
signals: T,
mod: string,
): { [K in keyof T]: ReturnType<T[K]["for_mod"]> } {
return Object.fromEntries(Object.entries(signals).map(([name, signal]) => [name, signal.for_mod(mod)])) as {
[K in keyof T]: ReturnType<T[K]["for_mod"]>;
};
}
function not_yet(mod: string, name: string, why: string) {
return () => {
throw new Error(`[${mod}] ctx.${name} isn't implemented yet: ${why}`);
};
}
const MAX_CONTAINER_SIZE = 256;
// how far a player can be from a block whose menu they have open, like minecraft's stillValid
const MENU_REACH = 8;
// what a client may send on mod channels, see docs/modding/networking/index.md
const MAX_MOD_MESSAGE_LENGTH = 16 * 1024;
const MAX_MOD_MESSAGES_PER_SECOND = 60;
// who ran a command, as the engine sees it: what mods see plus the engine's player
export interface ServerCommandSource extends CommandSource {
server_player: ServerPlayer;
}
// register(name, { run }): the words after the name go to run, split on spaces
function simple_command(name: string, command: Command): CommandNode<ServerCommandSource> {
const run = (args: string[], source: ServerCommandSource) => command.run(args, source.player);
return literal<ServerCommandSource>(name)
.describe(command.description)
.executes((context) => run([], context.source))
.then(
argument<string, ServerCommandSource>("args", greedy_string()).executes((context) =>
run(context.get<string>("args").split(/\s+/).filter((word) => word.length > 0), context.source)
),
);
}
// the engine's item stacks as mods see them: { id, count, data }
export function item_api(stack: EngineItemStack): ItemStack {
return {
get id() {
return stack.type_id;
},
get count() {
return stack.amount;
},
set count(value) {
stack.amount = value;
},
get data() {
return stack.data;
},
set data(value) {
stack.data = value;
},
};
}
function new_stack(item: ItemStack): EngineItemStack {
if (!EverythingRegistry.get("items", item.id)) throw new Error(`unknown item ${item.id}`);
const stack = new EngineItemStack(item.id, item.count);
if (item.data !== undefined) stack.data = structuredClone(item.data);
return stack;
}
// a menu's slot from what a mod's add_slot got
function menu_slot(
game: GameServer,
mod: string,
player: ServerPlayer,
container: Container,
slot: number,
options: SlotOptions,
): MenuSlot {
const engine = engine_containers.get(container);
if (!engine) throw new Error("add_slot needs a container from ctx.containers or player.inventory");
if (!Number.isInteger(slot) || slot < 0 || slot >= engine.size) {
throw new Error(`slot ${slot} isn't in the container, it has ${engine.size}`);
}
if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) {
throw new Error(`slot ${slot} needs an x and y`);
}
const { filter, on_take } = options;
const guarded = <T>(what: string, fn: () => T) => run_guarded(mod, what, fn);
const added: MenuSlot = { container: engine, index: slot, x: options.x, y: options.y };
if (filter === "smeltable") {
added.filter = (item) => game.recipes.furnace.has(item.type_id);
} else if (filter === "fuel") {
added.filter = (item) => game.recipes.fuel.has(item.type_id);
} else if (typeof filter === "function") {
added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true;
}
if (options.output_only) added.output = true;
if (on_take) added.on_take = (item) => guarded("an on_take", () => on_take(item_api(item))) === true;
if (options.icon) added.icon = String(options.icon);
if (engine === player.inventory) added.inventory = slot;
return added;
}
// the engine container behind each one mods get, for menus' slots
const engine_containers = new WeakMap<Container, EngineContainer>();
// an engine container as mods see it
function container_api(game: GameServer, id: string, container: EngineContainer): Container {
const api: Container = {
id,
size: container.size,
get: (slot) => {
const stack = container.get_item(slot);
return stack && item_api(stack);
},
set: (slot, item) => {
if (!Number.isInteger(slot) || slot < 0 || slot >= container.size) {
throw new Error(`slot ${slot} isn't in the container, it has ${container.size}`);
}
container.set_item(slot, item ? new_stack(item) : undefined);
},
add: (item) => {
const stack = new_stack(item);
const left = container.add_item(stack);
return left > 0 ? { id: item.id, count: left, data: stack.data } : undefined;
},
on_change: (fn) => game.mods.watch_container(running_mod || "unknown", container, fn),
};
engine_containers.set(api, container);
return api;
}
// what ServerWorld.raycast hits in a block: what entities bump into, and liquids up to their surface when it's
// looking for them
function raycast_shape(
world: GameServer["world"],
x: number,
y: number,
z: number,
liquids: "none" | "source_only" | "any",
): Shape | undefined {
const value = world.get_block_value(x, y, z);
const nid = value & ID_MASK;
if (nid === AIR) return undefined;
const block = EverythingRegistry.get_by_id<BlockRegistry>("blocks", nid);
if (!block) return undefined;
if (block.liquid) {
const level = get_state_value(value, block, "level") ?? 0;
if (liquids === "none" || (liquids === "source_only" && level !== 0)) return undefined;
return [[0, 0, 0, 1, liquid_height(level, block.liquid.range), 1]];
}
// the source in a waterlogged block covers the block, like minecraft's fluid clip
if (liquids !== "none" && is_waterlogged(value, block)) return [[0, 0, 0, 1, 1, 1]];
const shape = collision_shape_at(block, value);
return shape.length > 0 ? shape : undefined;
}
function player_api(game: GameServer, player: ServerPlayer): Player {
const inventory = container_api(game, `player:${player.id}`, player.inventory);
return {
get id() {
return player.id;
},
get name() {
return player.name;
},
get position() {
return { x: player.x, y: player.y, z: player.z };
},
get eye_position() {
return { x: player.x, y: player.y + player.eye_height, z: player.z };
},
// the same way the client aims, see ClientLevel.pick
get look_direction() {
const cos_pitch = Math.cos(player.pitch);
return {
x: -Math.sin(player.yaw) * cos_pitch,
y: Math.sin(player.pitch),
z: -Math.cos(player.yaw) * cos_pitch,
};
},
inventory,
get selected_slot() {
return player.selected_slot;
},
get held_item() {
const stack = player.held_item;
return stack && item_api(stack);
},
give_item(id, count = 1, data) {
if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`);
game.give(player, id, count, data);
},
send_message(text) {
game.send_chat(player, String(text));
},
set_worn(key, items) {
if (typeof key !== "string" || key.length === 0) throw new Error('set_worn needs a key, like "mymod:hats"');
if (!Array.isArray(items)) throw new Error("set_worn needs a list of items, [] for none");
if (items.length === 0) player.worn.delete(key);
else player.worn.set(key, items.map(new_stack));
},
teleport(x, y, z) {
game.teleport(player, x, y, z);
},
get health() {
return player.health;
},
get max_health() {
return player.max_health;
},
get food() {
return player.vitals.food;
},
get saturation() {
return player.vitals.saturation;
},
damage(amount, cause = "script") {
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`);
game.damage_player(player, amount, String(cause));
},
heal(amount) {
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`heal must be a number`);
game.heal_player(player, amount);
},
feed(nutrition, saturation_modifier) {
if (![nutrition, saturation_modifier].every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0)) {
throw new Error("feed takes two numbers of 0 or more");
}
player.vitals.eat(nutrition, saturation_modifier);
},
add_exhaustion(amount) {
if (typeof amount !== "number" || !Number.isFinite(amount) || amount < 0) {
throw new Error("exhaustion must be a number of 0 or more");
}
player.vitals.add_exhaustion(amount);
},
attribute: (id) => player.attribute(known_attribute(id)),
add_modifier(attribute, modifier) {
const type = known_attribute(attribute);
const { id, amount, operation } = modifier;
if (typeof id !== "string" || typeof amount !== "number" || !Number.isFinite(amount)) {
throw new Error("a modifier needs a string id and a number amount");
}
if (!MODIFIER_OPERATIONS.includes(operation)) throw new Error(`unknown modifier operation ${operation}`);
player.attributes.get(type)?.add_modifier({ id, amount, operation });
},
remove_modifier: (attribute, id) =>
player.attributes.get(known_attribute(attribute))?.remove_modifier(id) ?? false,
add_effect(id, duration, options = {}) {
const type = known_effect(id);
if (!Number.isInteger(duration) || (duration < 1 && duration !== -1)) {
throw new Error("an effect's duration is a whole number of ticks, or -1 for forever");
}
const amplifier = options.amplifier ?? 0;
if (!Number.isInteger(amplifier) || amplifier < 0) {
throw new Error("amplifier must be a whole number of 0 or more");
}
player.add_effect(new EffectInstance(type, duration, { ...options, amplifier }));
},
effect(id) {
const effect = player.get_effect(known_effect(id).id);
return effect && { amplifier: effect.amplifier, duration: effect.duration };
},
remove_effect: (id) => player.remove_effect(known_effect(id).id),
is_swimming: () => player.swimming,
};
}
function known_effect(id: string): EffectType {
const type = effect_type(id);
if (!type) throw new Error(`unknown effect ${id}`);
return type;
}
function known_attribute(id: string): AttributeType {
const type = attribute_type(id);
if (!type) throw new Error(`unknown attribute ${id}`);
return type;
}
function living_ref(entity: LivingEntity): LivingRef {
return {
id: entity.id,
get health() {
return entity.health;
},
get max_health() {
return entity.max_health;
},
damage(amount, cause = "script") {
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`damage must be a number`);
entity.hurt(amount, damage_source(String(cause)));
},
heal(amount) {
if (typeof amount !== "number" || !Number.isFinite(amount)) throw new Error(`heal must be a number`);
entity.heal(amount);
},
};
}
function entity_ref(entity: Entity): EntityRef {
return {
id: entity.id,
type: entity.type,
get position() {
return { x: entity.x, y: entity.y, z: entity.z };
},
get removed() {
return entity.removed;
},
teleport(x, y, z) {
if (!entity.removed) entity.set_position(x, y, z);
},
remove() {
entity.remove();
},
};
}