Register recipe api

This commit is contained in:
2026-10-28 23:56:29 -03:00
parent 5d64b801a3
commit 43521b3675
9 changed files with 235 additions and 42 deletions
+4 -2
View File
@@ -6,7 +6,7 @@
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 { ModListing, ModLoadError, RecipeBook, register_mod_data, shared_recipes_api } from "$/common/mod_loader.ts";
import { type Bmod, read_bmod } from "$/common/bmod.ts";
import { get_state_value, set_state_value, shared_items_api } from "$/common/utils.ts";
import { BlockRules } from "$/common/block_rules.ts";
@@ -237,6 +237,9 @@ function shared_context(listing: ModListing): SharedContext {
fluid_rules.register(mod, id, rules);
},
},
recipes: shared_recipes_api(() => recipe_book, () => rules_setup, (message) => {
throw new Error(`[${mod}] ${message}`);
}),
world: rules_world,
components: {
register_block(id, rules) {
@@ -346,7 +349,6 @@ function client_context(listing: ModListing): ClientContext {
},
items: {
...shared_items_api(mod),
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
mod(id) {
known_item(id);
return mod_name(id);
+10
View File
@@ -111,6 +111,8 @@ export interface SharedContext {
// every item any mod registered, like the client's ctx.items, for rules that read one, like a juice named after the
// fruit it's from
readonly items: {
// every item, in load order, like the server's ctx.items.ids
ids(): Id[];
exists(id: Id): boolean;
// what players see, like "Cooked Rice"
name(id: Id): string;
@@ -123,6 +125,14 @@ export interface SharedContext {
// the rules of one of the mod's fluids, which the server and every client name and color it by
register(id: Id, rules: FluidRules): void;
};
readonly recipes: {
// adds a recipe of type, like "shaped" or "farmersdelight:cooking", as a file in the mod's recipes/ with that
// json would, only during setup. for recipes made from other data, like one for every item with a component.
// shared scripts run on the server and every client alike, so they all have it without it being sent. it's
// there for server and client scripts, which set up after, and it throws when it's broken like a file would
// stop the mod loading
register(type: string, json: Record<string, unknown>): void;
};
readonly components: {
// the rules of a block component, the same id the server script registers the rest of it under
// deno-lint-ignore no-explicit-any
+66 -36
View File
@@ -23,7 +23,9 @@ import {
SpawnJson,
TagJson,
TagRegistry,
validate_recipe,
} from "./mod_data.ts";
import type { SharedContext } from "./mod_api/shared.ts";
import { resolve_tags, Tags } from "./tags.ts";
import type { LootTableJson } from "./loot.ts";
import { type BiomeJson, register_biome } from "./worldgen/biomes.ts";
@@ -184,42 +186,10 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
Tags.load(tags);
for (const { id, data } of mods) {
const fail = (message: string): never => {
throw new ModLoadError(id, message);
};
for (const recipe of data.recipes) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
const list = recipes.by_type.get(recipe.type) ?? [];
recipes.by_type.set(recipe.type, list);
list.push(recipe);
continue;
}
switch (recipe.type) {
case "shaped":
recipes.shaped.push(grid_recipe_from_json(recipe));
break;
case "furnace":
for (const input of choice_ids(recipe.input)) {
if (recipes.furnace.has(input)) fail(`two furnace recipes for ${input}`);
recipes.furnace.set(input, { output: recipe.output, cook_time: recipe.cook_time });
}
break;
case "fuel":
for (const item of choice_ids(recipe.item)) recipes.fuel.set(item, recipe.burn_time);
break;
case "smithing":
if (
recipes.smithing.some((other) =>
other.tool === recipe.tool && other.material.id === recipe.material.id &&
other.addition === recipe.addition
)
) {
fail(`two smithing recipes for ${recipe.tool} with ${recipe.material.id}`);
}
recipes.smithing.push(recipe);
break;
}
try {
for (const recipe of data.recipes) add_recipe(recipes, recipe);
} 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);
@@ -227,3 +197,63 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
return recipes;
}
// puts a recipe in the book, from a mod's recipes/ or a shared script. throws when it's for the same furnace input or
// smithing as one already there
export function add_recipe(recipes: RecipeBook, recipe: RecipeJson) {
recipes.all.push(recipe);
if (is_mod_recipe(recipe)) {
const list = recipes.by_type.get(recipe.type) ?? [];
recipes.by_type.set(recipe.type, list);
list.push(recipe);
return;
}
switch (recipe.type) {
case "shaped":
recipes.shaped.push(grid_recipe_from_json(recipe));
break;
case "furnace":
for (const input of choice_ids(recipe.input)) {
if (recipes.furnace.has(input)) throw new Error(`two furnace recipes for ${input}`);
recipes.furnace.set(input, { output: recipe.output, cook_time: recipe.cook_time });
}
break;
case "fuel":
for (const item of choice_ids(recipe.item)) recipes.fuel.set(item, recipe.burn_time);
break;
case "smithing":
if (
recipes.smithing.some((other) =>
other.tool === recipe.tool && other.material.id === recipe.material.id &&
other.addition === recipe.addition
)
) {
throw new Error(`two smithing recipes for ${recipe.tool} with ${recipe.material.id}`);
}
recipes.smithing.push(recipe);
break;
}
}
// 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
export function shared_recipes_api(
recipes: () => RecipeBook,
setting_up: () => boolean,
fail: (message: string) => never,
): SharedContext["recipes"] {
return {
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);
} catch (e) {
fail((e as Error).message);
}
},
};
}
+1
View File
@@ -95,6 +95,7 @@ export function shared_items_api(mod: string): SharedContext["items"] {
return item;
};
return {
ids: () => EverythingRegistry.entries("items").map(([id]) => id),
exists: (id) => EverythingRegistry.get("items", id) !== undefined,
name: (id) => (known(id), display_name(id)),
components: (id) => structuredClone(known(id).components ?? {}),
+3 -1
View File
@@ -96,7 +96,9 @@ Shared scripts hold a block component's rules, the code Minecraft runs on both s
(`state_for_placement`), how it changes with the blocks beside it (`on_neighbor_change`) and what right clicking it
changes (`on_interact`, like a trapdoor opening). See [Block Components](../blocks/components.md#rules). The server
script registers the rest of the same component, like its `on_break` or an `on_interact` that opens a screen, under the
same id. They also hold [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data.
same id. They also hold [fluids' rules](../resources/fluids.md#rules), which name and color a fluid by its data, and
[recipes made in code](../resources/recipes.md#recipes-from-scripts), which every side has without the server sending
them.
On the server they run on the real world. On a client they run on what that client shows, when its player places, breaks
or right clicks a block, so a fence joins its neighbors the moment it's placed. What they change there is a guess, and
+27
View File
@@ -140,6 +140,33 @@ mod.
`list` returns copies, in load order. Client scripts can read every recipe with `ctx.recipes.list(type?)`, which is how
the recipe viewer shows mods' own types.
## Recipes From Scripts
A recipe that follows from other data, like one for every item with a component, can be made in the mod's
[shared script](../concepts/sides.md#shared-scripts) instead of written out as files. `ctx.recipes.register(type, json)`
adds one like a file in `recipes/` with that `type` would, with the rest of its fields from `json`:
```ts
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
// a sieve recipe for every item that says what it sifts into
for (const id of ctx.items.ids()) {
const sifts = ctx.items.components(id)["copper_tools:siftable"] as { into: string } | undefined;
if (sifts) ctx.recipes.register("copper_tools:sifting", { input: id, result: { id: sifts.into, count: 1 } });
}
}
```
Shared scripts run on the server and on every player's client, from the same data, so every side makes the same recipes
and nothing is sent: the crafting grid, `ctx.recipes.list` in server and client scripts, and recipe viewers see them
like any other. That's also why it's only in shared scripts. Recipes can only be registered during `setup`, before any
server or client script sets up, and one is checked like a file would be: a broken one, or a second furnace recipe for
the same input, throws, which stops the mod loading.
Make them from what's the same on every side, like items and their components, not from the server's
[config](../misc/config.md), which clients don't have.
## Looking Up Recipes
Server scripts can ask about the base game's types:
+13 -3
View File
@@ -53,7 +53,7 @@ import type {
ServerContext,
SlotOptions,
} from "$/common/mod_api/server.ts";
import { ModLoadError } from "$/common/mod_loader.ts";
import { ModLoadError, shared_recipes_api } from "$/common/mod_loader.ts";
import {
argument,
block as block_argument,
@@ -269,10 +269,17 @@ export class ModRuntime {
// 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, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config));
this.#shared_setup = true;
try {
for (const { mod, version, url, engine_access, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config));
}
} finally {
this.#shared_setup = false;
}
}
// while shared scripts set up, the only time they can register recipes, as on clients
#shared_setup = false;
async #load_shared_script(mod: string, version: string, url: string, config: Record<string, unknown>) {
const module = await import(url);
@@ -292,6 +299,9 @@ export class ModRuntime {
this.fluid_rules.register(mod, id, rules);
},
},
recipes: shared_recipes_api(() => this.game.recipes, () => this.#shared_setup, (message) => {
throw new ModLoadError(mod, message);
}),
world: {
get_block: world.get_block,
get_state: world.get_state,
+1
View File
@@ -262,6 +262,7 @@ export function client_of(game: GameServer, area: Area) {
items: shared_items_api("bworld"),
// only its blocks are looked at here
fluids: { register() {} },
recipes: { register() {} },
world,
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
});
+110
View File
@@ -0,0 +1,110 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// recipes a shared script registers with ctx.recipes.register: there on the server and every client alike, for their
// scripts and the crafting grid, without being sent
import { assert, assertEquals, assertRejects } from "@std/assert";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { ModListing } from "$/common/mod_loader.ts";
import { read_bmod } from "$/common/bmod.ts";
import { load_client_mods } from "$/client/mods.ts";
import { load_and_check } from "$/tools/check_mods.ts";
import { pack_mod } from "$/tools/pack_mod.ts";
import { copy_dir, test_game } from "./helpers.ts";
// sifts into what its component says, and a shaped recipe made in code
const SHARED = `
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
for (const id of ctx.items.ids()) {
const sifts = ctx.items.components(id)["testrecipes:siftable"] as { into: string } | undefined;
if (sifts) ctx.recipes.register("testrecipes:sifting", { input: id, result: { id: sifts.into, count: 1 } });
}
ctx.recipes.register("shaped", { pattern: ["#"], key: { "#": "testrecipes:gravel" }, result: { id: "testrecipes:flint", count: 2 } });
SHARED_EXTRA
}
`;
// what the server and client scripts see of them while they set up. the server's registers the siftable component
const SEEN = (side: string) => `
export function setup(ctx: any) {
ctx.components?.register_item?.("testrecipes:siftable", {});
(globalThis as any).testrecipes_${side} = ctx.recipes.list("testrecipes:sifting");
(globalThis as any).testrecipes_late?.();
}
`;
// the base game, and testrecipes: gravel that sifts into flint, sand that doesn't sift, and the scripts above
function recipe_mod(shared_extra = "") {
const dir = Deno.makeTempDirSync({ prefix: "bworld_script_recipes_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, json: unknown) => {
Deno.mkdirSync(`${dir}/testrecipes/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
Deno.writeTextFileSync(`${dir}/testrecipes/${path}`, typeof json === "string" ? json : JSON.stringify(json));
};
write("manifest.json", {
format_version: 1,
id: "testrecipes",
name: "Test Recipes",
version: "1.0.0",
scripts: { shared: "scripts/shared.ts", server: "scripts/server.ts", client: "scripts/client.ts" },
});
const item = (id: string, components?: unknown) =>
write(`items/${id}.json`, {
format_version: 1,
item: { id: `testrecipes:${id}`, texture: "engine:missing", ...(components ? { components } : {}) },
});
item("gravel", { "testrecipes:siftable": { into: "testrecipes:flint" } });
item("sand");
item("flint");
write("scripts/shared.ts", SHARED.replace("SHARED_EXTRA", shared_extra));
write("scripts/server.ts", SEEN("server"));
write("scripts/client.ts", SEEN("client"));
return dir;
}
const SIFTING = [{
type: "testrecipes:sifting",
input: "testrecipes:gravel",
result: { id: "testrecipes:flint", count: 1 },
}];
Deno.test("recipes a shared script registers are on the server and clients, for their scripts and crafting", async () => {
const dir = recipe_mod();
const t = await test_game(dir);
const seen = globalThis as unknown as Record<string, unknown>;
assertEquals(seen.testrecipes_server, SIFTING);
assertEquals(t.game.recipes.by_type.get("testrecipes:sifting") as unknown, SIFTING);
assert(
t.game.recipes.shaped.some((recipe) => recipe.result.id === "testrecipes:flint" && recipe.result.count === 2),
);
const mod = load_and_check(dir).find((m) => m.id === "testrecipes")!;
assertEquals(mod.report.errors, []);
const bmod = read_bmod(await pack_mod(mod), "testrecipes.bmod");
Deno.removeSync(dir, { recursive: true });
const listing: ModListing = { id: "testrecipes", name: "Test", version: "1.0.0", sha256: "", file: "", size: 0 };
EverythingRegistry.clear();
await load_client_mods([listing], [bmod]);
assertEquals(seen.testrecipes_client, SIFTING);
});
Deno.test("a broken recipe from a shared script stops the mod loading, like a broken file", async () => {
const dir = recipe_mod(
`ctx.recipes.register("shaped", { pattern: ["#"], key: {}, result: { id: "testrecipes:sand", count: 1 } });`,
);
await assertRejects(() => test_game(dir), Error, "testrecipes: recipe of type shaped");
Deno.removeSync(dir, { recursive: true });
});
Deno.test("recipes can only be registered while shared scripts set up", async () => {
const dir = recipe_mod(
`(globalThis as any).testrecipes_late = () => ctx.recipes.register("testrecipes:sifting", {});`,
);
try {
await assertRejects(() => test_game(dir), Error, "recipes can only be registered during setup");
} finally {
delete (globalThis as Record<string, unknown>).testrecipes_late;
Deno.removeSync(dir, { recursive: true });
}
});