Files
bworld/common/mod_loader.ts
T
2026-11-22 09:12:15 -03:00

415 lines
16 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// registers mods' data, the same way on the server and on clients
import { BlockRegistry, EverythingRegistry, ItemRegistry } from "./everything_registry.ts";
import {
add_to_block_item,
block_from_json,
BlockJson,
choice_ids,
choice_list,
choice_problems,
ClipJson,
EffectJson,
EntityJson,
EntityModelJson,
FluidJson,
grid_recipe_from_json,
GridRecipe,
is_mod_recipe,
item_from_json,
item_problems,
ItemJson,
ModRecipeJson,
OreJson,
RecipeJson,
SoundJson,
SpawnJson,
stack_problems,
TagJson,
TagRegistry,
validate_recipe,
} from "./mod_data.ts";
import type { FluidStack, RecipeLookup, RecipeReader, RecipeType, SharedContext } from "./mod_api/shared.ts";
import { fluid_exists } from "./fluids.ts";
import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { type BiomeJson, register_biome } from "./worldgen/biomes.ts";
import type {
BiomeSourceJson,
DensityFunctionJson,
DimensionJson,
NoiseJson,
NoiseSettingsJson,
} from "./worldgen/data.ts";
import type { FeatureJson } from "./worldgen/features.ts";
import { register_block_item } from "./utils.ts";
import { find_model, type ModelFileJson, type ModelJson, resolve_models } from "./block_models.ts";
import { loading_mod } from "./hooks.ts";
import type { Schematic } from "./schematic.ts";
// everything a mod's json files hold, merged into one file by the build (build/mods/<id>/<hash>/data.json)
export interface ModData {
blocks: BlockJson[];
// block models as mods write them, parents not merged in yet. see common/block_models.ts
models: ModelFileJson[];
items: ItemJson[];
recipes: RecipeJson[];
ores: OreJson[];
// natural spawns, see SpawnJson
spawns: SpawnJson[];
entities: EntityJson[];
entity_models: EntityModelJson[];
// clips, see ClipJson. missing from mods packed before there were any
animations?: ClipJson[];
// its sounds.json, see docs/modding/resources/sounds.md. the files are in the .cubi's sounds/
sounds?: SoundJson[];
// status effects, see EffectJson
effects: EffectJson[];
// kinds of fluid, see FluidJson
fluids: FluidJson[];
// tag files, see common/tags.ts
tags: TagJson[];
// see common/loot.ts. missing from mods packed before there were loot tables
loot_tables?: LootTableJson[];
// see common/worldgen/biomes.ts. missing from mods packed before biomes were data
biomes?: BiomeJson[];
// the terrain as data, see common/worldgen/data.ts. server only, players' copies leave them out
noises?: NoiseJson[];
density_functions?: DensityFunctionJson[];
noise_settings?: NoiseSettingsJson[];
biome_sources?: BiomeSourceJson[];
// which noise settings the world is generated with, see DimensionJson. server only too
dimensions?: DimensionJson[];
// data features, see common/worldgen/features.ts. server only too
features?: FeatureJson[];
// its schematics/<name>.cbsm files, with their ids, see common/schematic.ts. server only too
schematics?: Schematic[];
// the mod's settings, its config.json's "config", with the server's changes once the server loads it. server only
// too, see docs/modding/misc/config.md
config?: Record<string, unknown>;
}
// a mod as the server lists it to clients, in load order: the .cubi players download, without its terrain or config
export interface ModListing {
id: string;
name: string;
version: string;
// sha-256 in hex of the .cubi, clients check it before using anything in it
sha256: string;
// where it's served from, relative to the server's root. named by its hash, so it never changes
file: string;
size: number;
// it imports cubi/engine, see docs/modding/misc/engine.md. the confirm screen for other sites says so
engine_access?: boolean;
}
export class RecipeBook {
shaped: GridRecipe[] = [];
// 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[]>();
first_used_by = new Map<string, string>();
// the types shared phases registered, and their recipes as parse made them, see SharedContext.recipes.register_type
types = new Map<string, RecipeType<unknown, unknown>>();
parsed = new Map<string, unknown[]>();
// every recipe as its json, in load order, for recipe viewers
all: RecipeJson[] = [];
// each mod's ores, in load order. each mod's are their own pass, see generate_raw_chunk
ores: OreJson[][] = [];
spawns: SpawnJson[] = [];
}
export class ModLoadError extends Error {
// the message without the mod's id
readonly problem: string;
constructor(mod: string, message: string) {
super(`${mod}: ${message}`);
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];
// the checks everything a mod registers from code goes through, the same on every side: only while the phase that
// registers it runs, in the mod's own namespace, and once. running says whether that phase is running. what names the
// kind of thing, like "component"
export function registrar(mod: string, phase: Phase, running: () => boolean) {
const fail = (message: string): never => {
throw new ModLoadError(mod, message);
};
const checks = {
fail,
running(what: string) {
if (!running()) fail(`${what} can only be registered while the ${phase} phase runs`);
},
own(what: string, id: string) {
if (typeof id !== "string" || !id.startsWith(`${mod}:`)) {
fail(`${what} ${id} must be in the namespace "${mod}"`);
}
},
// all three, taken saying whether id is registered already
new_id(what: string, id: string, taken: boolean) {
checks.running(what);
checks.own(what, id);
if (taken) fail(`${what} ${id} is registered twice`);
},
};
return checks;
}
export type Registrar = ReturnType<typeof registrar>;
// 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
export function is_registered(registry: TagRegistry, id: string): boolean {
return (registry === "blocks" && id === "cubi:air") || EverythingRegistry.get(registry, id) !== undefined;
}
// registers every mod's blocks, items, entities, effects, fluids, tags and recipes, in the order given (dependencies
// first). tags load once every mod's content has, since a tag can hold anything, and recipes after them, since they can
// use tags
export function register_mod_data(mods: { id: string; data: ModData }[]): RecipeBook {
const recipes = new RecipeBook();
for (const { id, data } of mods) {
try {
// parents are this mod's or an earlier one's, which are already registered with theirs merged in
const { models, problems } = resolve_models(
data.models,
(model_id) => find_model(model_id, {}) ?? EverythingRegistry.get<ModelJson>("models", model_id),
);
if (problems.length > 0) {
throw new Error(problems.map(({ id, problem }) => `model ${id}: ${problem}`).join("\n"));
}
for (const model of models) {
EverythingRegistry.register<ModelJson>("models", model.id, model);
}
for (const json of data.blocks) {
const { block, has_item } = block_from_json(json);
EverythingRegistry.register<BlockRegistry>("blocks", block.id, block);
if (has_item) {
register_block_item(block);
}
}
for (const json of data.items) {
if (json.texture !== undefined) {
EverythingRegistry.register<ItemRegistry>("items", json.id, item_from_json(json));
continue;
}
const block_item = EverythingRegistry.get<BlockRegistry>("blocks", json.id) &&
EverythingRegistry.get<ItemRegistry>("items", json.id);
if (!block_item) throw new Error(`item ${json.id} has no texture and isn't a block's item`);
add_to_block_item(json, block_item);
}
for (const model of data.entity_models) {
EverythingRegistry.register<EntityModelJson>("entity_models", model.id, model);
}
for (const clip of data.animations ?? []) {
EverythingRegistry.register<ClipJson>("animations", clip.id, clip);
}
for (const json of data.sounds ?? []) {
EverythingRegistry.register<SoundJson>("sounds", json.id, json);
}
for (const json of data.entities) {
EverythingRegistry.register<EntityJson>("entities", json.id, json);
}
for (const json of data.effects) {
EverythingRegistry.register<EffectJson>("effects", json.id, json);
}
for (const json of data.fluids) {
EverythingRegistry.register<FluidJson>("fluids", json.id, json);
}
for (const json of data.loot_tables ?? []) {
EverythingRegistry.register<LootTableJson>("loot_tables", json.id, json);
}
for (const json of data.biomes ?? []) {
register_biome(json);
}
// compiled into a generator once every mod's are in, see common/worldgen/generator.ts
for (const json of data.noises ?? []) EverythingRegistry.register("noises", json.id, json);
for (const json of data.density_functions ?? []) {
EverythingRegistry.register("density_functions", 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);
// compiled with the types worldgen phases register, see common/worldgen_loader.ts
for (const json of data.features ?? []) EverythingRegistry.register("features", json.id, json);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
}
const { tags, problems } = resolve_tags(
mods.flatMap(({ id, data }) =>
data.tags.map((json) => ({ mod: id, file: `tags/${json.registry}/${json.id}`, json }))
),
is_registered,
);
if (problems.length > 0) throw new ModLoadError(problems[0].mod, `${problems[0].file}: ${problems[0].message}`);
Tags.load(tags);
for (const { id, data } of mods) {
try {
for (const recipe of data.recipes) add_recipe(recipes, recipe, id);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
if (data.ores.length > 0) recipes.ores.push(data.ores);
recipes.spawns.push(...data.spawns);
}
return recipes;
}
// 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) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
const list = recipes.by_type.get(recipe.type) ?? [];
recipes.by_type.set(recipe.type, list);
if (!recipes.first_used_by.has(recipe.type)) recipes.first_used_by.set(recipe.type, mod);
list.push(recipe);
const type = recipes.types.get(recipe.type);
if (type) recipes.parsed.get(recipe.type)!.push(parse_recipe(type, recipe, list.length - 1));
return;
}
recipes.shaped.push(grid_recipe_from_json(recipe));
}
// the index'th recipe of its type, turned into what its type's parse makes of it, or throwing naming it
function parse_recipe(type: RecipeType<unknown, unknown>, json: ModRecipeJson, index: number): unknown {
try {
return type.parse(structuredClone(json), recipe_reader);
} catch (e) {
throw new Error(`${json.type} recipe ${index + 1}: ${(e as Error).message}`);
}
}
// items, fluids and tags load before any script sets up, so the ones recipes name can be checked
const recipe_reader: RecipeReader = {
item: (value, name) => checked_item(name, item_problems(value), value as string),
stack(value, name) {
const stack = value as { id: string; count: number } | undefined;
return { id: checked_item(name, stack_problems(stack), stack?.id as string), count: stack!.count };
},
// a tag can be empty, like one of another mod's items that isn't installed, but it has to exist
ingredient(value, name) {
const choice = value as string | string[];
const problems = choice_problems(choice);
if (problems.length > 0) throw new Error(`${name} ${problems[0]}`);
for (const entry of choice_list(choice)) {
if (!entry.startsWith("#")) checked_item(name, [], entry);
else if (!Tags.exists("items", entry)) throw new Error(`${name}: there's no item tag ${entry}`);
}
return choice_ids(choice);
},
fluid_stack(value, name) {
const stack = value as Partial<FluidStack> | undefined;
const id = stack?.fluid?.id;
if (typeof id !== "string") throw new Error(`${name} must be { fluid: { id, data }, amount }`);
if (!fluid_exists(id)) throw new Error(`${name}: there's no fluid ${id}`);
return { fluid: stack!.fluid!, amount: recipe_reader.positive_int(stack!.amount, `${name} amount`) };
},
positive_int(value, name) {
if (!Number.isInteger(value) || (value as number) < 1) {
throw new Error(`${name} must be a whole number, at least 1`);
}
return value as number;
},
};
// the item a field names, once the field has no problems
function checked_item(name: string, problems: string[], id: string): string {
if (problems.length > 0) throw new Error(`${name} ${problems[0]}`);
if (!is_registered("items", id)) throw new Error(`${name}: there's no item ${id}`);
return id;
}
// 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
export function check_recipe_types(recipes: RecipeBook) {
for (const [type, mod] of recipes.first_used_by) {
if (!recipes.types.has(type)) {
throw new ModLoadError(mod, `it has ${type} recipes, but no mod registers that type`);
}
}
}
// find and all, for every side's ctx.recipes
export function recipe_lookup(recipes: () => RecipeBook): RecipeLookup {
return {
find<R>(type: string, input: unknown) {
const rules = recipes().types.get(type);
return recipes().parsed.get(type)?.find((recipe) => rules!.matches(recipe, input)) as R | undefined;
},
all: <R>(type: string) => (recipes().parsed.get(type) ?? []) as R[],
};
}
// 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. list reads the book
// as it is, so a script sees the recipes of the ones before it
export function shared_recipes_api(
mod: string,
recipes: () => RecipeBook,
register: Registrar,
): SharedContext["recipes"] {
const fail = register.fail;
return {
...recipe_lookup(recipes),
register(type, json) {
register.running("recipe");
const recipe = { ...structuredClone(json), type };
const problems = validate_recipe(recipe);
if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`);
try {
add_recipe(recipes(), recipe as RecipeJson, mod);
} catch (e) {
fail((e as Error).message);
}
},
list: (type) => structuredClone(type ? recipes().all.filter((recipe) => recipe.type === type) : recipes().all),
// the recipes of the type there are so far are parsed now, and the ones registered after as they come
register_type(type, rules) {
const book = recipes();
register.new_id("recipe type", type, book.types.has(type));
const type_rules = rules as RecipeType<unknown, unknown>;
try {
book.parsed.set(
type,
(book.by_type.get(type) ?? []).map((json, i) => parse_recipe(type_rules, json, i)),
);
} catch (e) {
fail((e as Error).message);
}
book.types.set(type, type_rules);
},
};
}