// 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, EffectJson, EntityJson, EntityModelJson, FluidJson, grid_recipe_from_json, GridRecipe, is_mod_recipe, item_from_json, item_problems, ItemJson, ModRecipeJson, OreJson, RecipeJson, 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, 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"; // everything a mod's json files hold, merged into one file by the build (build/mods///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[]; // 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[]; // data features, see common/worldgen/features.ts. server only too features?: FeatureJson[]; // 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; } // a mod as the server lists it to clients, in load order: the .bmod players download, without its server script export interface ModListing { id: string; name: string; version: string; // sha-256 in hex of the .bmod, 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(); first_used_by = new Map(); // the types shared scripts registered, and their recipes as parse made them, see SharedContext.recipes.register_type types = new Map>(); parsed = new Map(); // 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 { constructor(mod: string, message: string) { super(`${mod}: ${message}`); this.name = "ModLoadError"; } } // 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("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("models", model.id, model); } for (const json of data.blocks) { const { block, has_item } = block_from_json(json); EverythingRegistry.register("blocks", block.id, block); if (has_item) { register_block_item(block); } } for (const json of data.items) { if (json.texture !== undefined) { EverythingRegistry.register("items", json.id, item_from_json(json)); continue; } const block_item = EverythingRegistry.get("blocks", json.id) && EverythingRegistry.get("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("entity_models", model.id, model); } for (const json of data.entities) { EverythingRegistry.register("entities", json.id, json); } for (const json of data.effects) { EverythingRegistry.register("effects", json.id, json); } for (const json of data.fluids) { EverythingRegistry.register("fluids", json.id, json); } for (const json of data.loot_tables ?? []) { EverythingRegistry.register("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 scripts 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 script. 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, 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 | 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 script 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(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: (type: string) => (recipes().parsed.get(type) ?? []) as R[], }; } // ctx.recipes for shared scripts, 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 // 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( mod: string, recipes: () => RecipeBook, setting_up: () => boolean, fail: (message: string) => never, ): SharedContext["recipes"] { return { ...recipe_lookup(recipes), register(type, json) { if (!setting_up()) fail("recipes can only be registered during setup"); 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) { if (!setting_up()) fail("recipe types can only be registered during setup"); if (!type.startsWith(`${mod}:`)) fail(`recipe type ${type} must be in the namespace "${mod}"`); const book = recipes(); if (book.types.has(type)) fail(`recipe type ${type} is already registered`); const type_rules = rules as RecipeType; 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); }, }; }