Compare commits

..
3 Commits
Author SHA1 Message Date
paula 12702520dd Stricter rules 2026-11-01 21:10:13 -03:00
paulaandClaude Opus 5.5 a7e81b9944 Every recipe type registered from shared scripts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 21:00:44 -03:00
paula 65113862f7 Recipe types from shared scripts and stuff 2026-11-01 20:41:23 -03:00
51 changed files with 553 additions and 484 deletions
+6
View File
@@ -3,6 +3,12 @@
A voxel game in TypeScript on Deno. The base game is itself a mod (`mods/bworld`), written against the same modding API
as any other mod.
**Never under any circumstance commit anything on your own**
**Never under any circumstance generate any textures or audio files**
Always ask before making even the simplest models, unless it's coming from ports/
## Layout
- `server/`: the game server, world, saves and server-side game logic
+5 -1
View File
@@ -7,6 +7,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 {
check_recipe_types,
ModListing,
ModLoadError,
recipe_lookup,
@@ -17,7 +18,7 @@ import {
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";
import { FluidRules } from "$/common/fluids.ts";
import { fluid_exists, FluidRules, same_fluid } from "$/common/fluids.ts";
import { fluid_rules, set_fluid_rules } from "./fluid_rules.ts";
import { covers_face, EMPTY_SHAPE, FULL_SHAPE, is_solid } from "$/common/block_shapes.ts";
import type { SharedContext, SharedWorld } from "$/common/mod_api/shared.ts";
@@ -192,6 +193,7 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) {
});
}
rules_setup = false;
check_recipe_types(recipe_book);
client_setup = true;
for (const [i, bmod] of bmods.entries()) {
@@ -239,6 +241,8 @@ function shared_context(listing: ModListing): SharedContext {
blocks: blocks_api(mod),
items: shared_items_api(mod),
fluids: {
exists: fluid_exists,
same: same_fluid,
register(id, rules) {
if (!rules_setup) throw new Error(`[${mod}] rules can only be registered during setup`);
fluid_rules.register(mod, id, rules);
+5 -1
View File
@@ -48,7 +48,7 @@ export class FluidRules {
api(): FluidApi {
return {
ids: () => EverythingRegistry.entries("fluids").map(([id]) => id),
exists: (id) => EverythingRegistry.get("fluids", id) !== undefined,
exists: fluid_exists,
name: (fluid) => this.name(fluid),
color: (fluid) => this.color(fluid),
same: same_fluid,
@@ -68,6 +68,10 @@ export class FluidRules {
}
}
export function fluid_exists(id: string): boolean {
return EverythingRegistry.get("fluids", id) !== undefined;
}
// whether they're one fluid, see FluidApi.same
export function same_fluid(a: FluidVariant, b: FluidVariant): boolean {
return a.id === b.id && same_data(a.data, b.data);
+1 -7
View File
@@ -644,10 +644,6 @@ export interface ServerFluidApi extends FluidApi {
// find and all read the recipes of types shared scripts registered
export interface RecipeApi extends RecipeLookup {
furnace_result(input: Id): { output: ItemStack; cook_time: number } | undefined;
fuel_value(item: Id): number; // burn time in ticks, 0 if it isn't fuel
is_fuel(item: Id): boolean;
is_smeltable(item: Id): boolean;
// every recipe of a mod's own type, like "bworld:cooking", as its json. copies, in load order
// deno-lint-ignore no-explicit-any
list(type: Id): any[];
@@ -726,14 +722,12 @@ export type FormResult<T> = ({ canceled: true } & Partial<T>) | ({ canceled: fal
// menus, like neoforge's: the server side of a gui, see docs/modding/inventories/menus.md
export type SlotFilter = "smeltable" | "fuel" | ((item: ItemStack) => boolean);
export interface SlotOptions {
// gui pixels from the screen's top left to the slot's 18 pixel frame
x: number;
y: number;
// what can be put in, checked on the server
filter?: SlotFilter;
filter?: (item: ItemStack) => boolean;
// can only be taken from, all at once, like the furnace result
output_only?: boolean;
// runs when a player takes from an output_only slot, before they get it. false stops them taking it
+14 -6
View File
@@ -67,11 +67,17 @@ export interface RecipeType<R, I> {
matches(recipe: R, input: I): boolean;
}
// reads a field of a recipe's json for RecipeType.parse, checked like the engine's own recipes' fields. throws naming
// the field when it isn't one, or its item isn't registered
// reads a value from a recipe's json for RecipeType.parse, checked like the engine's own recipes' fields. name is where
// it is, like "result" or "ingredients[0]", for the error thrown when it isn't one, or what it names isn't registered
export interface RecipeReader {
item(json: Record<string, unknown>, field: string): Id;
stack(json: Record<string, unknown>, field: string): { id: Id; count: number };
item(value: unknown, name: string): Id;
stack(value: unknown, name: string): { id: Id; count: number };
// an item, a #tag or a list of them, any of which fits, as every item that does, like the engine's shaped keys
ingredient(value: unknown, name: string): Id[];
// { fluid, amount } in mB
fluid_stack(value: unknown, name: string): FluidStack;
// a whole number, at least 1, like a time in ticks
positive_int(value: unknown, name: string): number;
}
// the recipes of registered types, as their parse made them, in load order. not to be changed
@@ -154,7 +160,8 @@ export interface SharedContext {
// what one sells for, from its "base_sell_value", or undefined if it can't be sold
sell_value(id: Id): number | undefined;
};
readonly fluids: {
// every fluid any mod defines, like the server's and clients' ctx.fluids, without what rules decide
readonly fluids: Pick<FluidApi, "exists" | "same"> & {
// 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;
};
@@ -170,7 +177,8 @@ export interface SharedContext {
// deno-lint-ignore no-explicit-any
list(type?: string): any[];
// a recipe type of the mod's own, in its namespace, only during setup: its recipes, from files and register,
// are parsed by it then, and find and all read them from there on every side. see RecipeType
// are parsed by it then, and find and all read them from there on every side. a recipe of a type no mod
// registers stops its mod loading once every shared script has set up. see RecipeType
register_type<R, I>(type: Id, rules: RecipeType<R, I>): void;
} & RecipeLookup;
readonly components: {
+4 -13
View File
@@ -348,20 +348,11 @@ export function check_references(mods: LoadedMod[], engine_textures: Iterable<st
if (slim_texture !== undefined) uses(file, slim_texture, "texture");
}
}
// mods' own types are checked by their parse when the mod loads
for (const { file, json } of mod.recipes) {
switch (json.type) {
case "shaped":
for (const id of Object.values(json.key).flatMap(choice_list)) uses(file, id, "item");
uses(file, json.result.id, "item");
break;
case "furnace":
for (const id of choice_list(json.input)) uses(file, id, "item");
uses(file, json.output.id, "item");
break;
case "fuel":
for (const id of choice_list(json.item)) uses(file, id, "item");
break;
}
if (json.type !== "shaped") continue;
for (const id of Object.values(json.key).flatMap(choice_list)) uses(file, id, "item");
uses(file, json.result.id, "item");
}
for (const { file, json } of mod.ores) {
uses(file, json.id, "block");
+8 -20
View File
@@ -593,42 +593,26 @@ const shaped_recipe = z.object({
}
});
// cook_time and burn_time are in ticks
const furnace_recipe = z.object({
type: z.literal("furnace"),
input: item_choice,
output: stack,
cook_time: z.int().min(1),
});
const fuel_recipe = z.object({ type: z.literal("fuel"), item: item_choice, burn_time: z.int().min(1) });
export interface ModRecipeJson {
type: `${string}:${string}`;
[field: string]: unknown;
}
export type RecipeJson =
| z.infer<typeof shaped_recipe>
| z.infer<typeof furnace_recipe>
| z.infer<typeof fuel_recipe>
| ModRecipeJson;
export type RecipeJson = z.infer<typeof shaped_recipe> | ModRecipeJson;
const engine_recipes = new Map<string, z.ZodType>([
["shaped", shaped_recipe],
["furnace", furnace_recipe],
["fuel", fuel_recipe],
]);
// a mod's own types, like "bworld:cooking" for its cooking pot, are only stored by the engine. the mod parses them,
// with ctx.recipes.register_type, or reads them with ctx.recipes.list and checks them
// with ctx.recipes.register_type
const recipe_schema = by_kind(
"type",
(type) => engine_recipes.get(type) ?? (ID_PATTERN.test(type) ? json_object : undefined),
'must be "shaped", "furnace", "fuel" or a mod\'s own type like "bworld:cooking"',
'must be "shaped" or a mod\'s own type like "bworld:cooking"',
);
// a recipe type a mod made up, as opposed to the engine's shaped, furnace and fuel
// a recipe type a mod made up, as opposed to the engine's shaped
export function is_mod_recipe(recipe: RecipeJson): recipe is ModRecipeJson {
return recipe.type.includes(":");
}
@@ -643,6 +627,10 @@ export function stack_problems(json: unknown): Problems {
return find_problems(stack, json);
}
export function choice_problems(json: unknown): Problems {
return find_problems(item_choice, json);
}
// the crafting grid's format, see server/game/crafting.ts
export interface GridRecipe {
width: number;
+54 -31
View File
@@ -8,6 +8,8 @@ import {
block_from_json,
BlockJson,
choice_ids,
choice_list,
choice_problems,
EffectJson,
EntityJson,
EntityModelJson,
@@ -27,7 +29,8 @@ import {
TagRegistry,
validate_recipe,
} from "./mod_data.ts";
import type { RecipeLookup, RecipeReader, RecipeType, SharedContext } from "./mod_api/shared.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";
@@ -86,10 +89,9 @@ export interface ModListing {
export class RecipeBook {
shaped: GridRecipe[] = [];
furnace = new Map<string, { output: { id: string; count: number }; cook_time: number }>();
fuel = new Map<string, number>();
// recipes of mods' own types, by type
// 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 scripts 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[]>();
@@ -191,7 +193,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe
for (const { id, data } of mods) {
try {
for (const recipe of data.recipes) add_recipe(recipes, recipe);
for (const recipe of data.recipes) add_recipe(recipes, recipe, id);
} catch (e) {
throw new ModLoadError(id, (e as Error).message);
}
@@ -202,32 +204,19 @@ 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 as
// one already there, or its registered type's parse throws
export function add_recipe(recipes: RecipeBook, recipe: RecipeJson) {
// 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;
}
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;
}
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
@@ -239,22 +228,56 @@ function parse_recipe(type: RecipeType<unknown, unknown>, json: ModRecipeJson, i
}
}
// items are registered before any script sets up, so the ones recipes name can be checked
// items, fluids and tags load before any script sets up, so the ones recipes name can be checked
const recipe_reader: RecipeReader = {
item: (json, field) => checked_item(field, item_problems(json[field]), json[field] as string),
stack(json, field) {
const stack = json[field] as { id: string; count: number } | undefined;
return { id: checked_item(field, stack_problems(stack), stack?.id as string), count: stack!.count };
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(field: string, problems: string[], id: string): string {
if (problems.length > 0) throw new Error(`${field} ${problems[0]}`);
if (!is_registered("items", id)) throw new Error(`${field}: there's no item ${id}`);
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 {
@@ -283,7 +306,7 @@ export function shared_recipes_api(
const problems = validate_recipe(recipe);
if (problems.length > 0) fail(`recipe of type ${type}: ${problems.join(", ")}`);
try {
add_recipe(recipes(), recipe as RecipeJson);
add_recipe(recipes(), recipe as RecipeJson, mod);
} catch (e) {
fail((e as Error).message);
}
+1 -1
View File
@@ -320,7 +320,7 @@ catch up. If it's further behind than that, it skips the rest and logs a warning
| ----------------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
| `bworld:storage` | `rows` | A chest: `rows` × 9 slots, dropped when it's broken. |
| `bworld:shipping_bin` | `rows` | Like `bworld:storage`, and every morning at 06:00 sells what's in it that has a sell value for coins. |
| `bworld:furnace` | none | Smelts with `furnace` and `fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:furnace` | none | Smelts with `bworld:smelting` and `bworld:fuel` [recipes](../resources/recipes.md). Needs `lit` and `facing` states, see `blocks/furnace.json`. |
| `bworld:smithing_table` | none | Upgrades tools with `bworld:smithing` recipes. |
| `bworld:stonecutter` | none | Cuts one item into another with `bworld:stonecutting` recipes, picked from a list. |
| `bworld:hoeable` | `tool`, `into` | Right clicking with a tool of type `tool` turns it into `into`, like a hoe on grass. |
+3 -3
View File
@@ -22,8 +22,8 @@ export function setup(ctx: ServerContext) {
const smelter = ctx.menus.register<BlockRef>("copper_tools:smelter", (menu, block, player) => {
const container = ctx.containers.get(block.data.container)!;
menu.title = "Smelter";
menu.add_slot(container, 0, { x: 55, y: 16, filter: "smeltable" });
menu.add_slot(container, 1, { x: 55, y: 52, filter: "fuel" });
menu.add_slot(container, 0, { x: 55, y: 16, filter: (item) => !!ctx.recipes.find("bworld:smelting", item.id) });
menu.add_slot(container, 1, { x: 55, y: 52, filter: (item) => !!ctx.recipes.find("bworld:fuel", item.id) });
menu.add_slot(container, 2, { x: 115, y: 34, output_only: true });
menu.add_player_inventory(7, 84);
menu.add_data("progress", () => block.data.progress);
@@ -57,7 +57,7 @@ returns the slot's **menu slot index**: slots are numbered in the order they're
| Option | Meaning |
| ------------- | ----------------------------------------------------------------------------------------------------------------- |
| `x`, `y` | Where its 18 pixel frame goes, in GUI pixels from the screen's top left. |
| `filter` | What can be put in: `"smeltable"` (has a furnace recipe), `"fuel"`, or a function `(item) => boolean`. |
| `filter` | What can be put in: a function `(item) => boolean`, like one that looks for a [recipe](../resources/recipes.md). |
| `output_only` | Can only be taken from, all at once, like the furnace result. |
| `on_take` | For `output_only` slots: runs when a player takes from it, before they get the item. Return `false` to stop them. |
| `icon` | A texture drawn in the slot while it's empty, like Minecraft's armor slots. |
+3
View File
@@ -109,6 +109,9 @@ ctx.fluids.same(birch, { id: "copper_tools:syrup" }); // false, the data is diff
there as plain `copper_tools:syrup`. Client scripts also have `ctx.fluids.mod(id)`, the name of the mod that added it,
like `ctx.items.mod`.
Shared scripts have `ctx.fluids.exists` and `ctx.fluids.same` too, which don't depend on rules, like a
[recipe type](recipes.md#custom-recipe-types) that's found by a fluid.
## Containers
An item with `fluid_container` holds one fluid, full or empty, like a bucket or a bottle:
+40 -55
View File
@@ -1,7 +1,8 @@
# Recipes
Recipes are data in a mod's `recipes/` folder, one per file. The engine has three types, for the crafting grid and the
furnace. Everything else, the base game's smithing table included, has a type of its own that a mod defines.
Recipes are data in a mod's `recipes/` folder, one per file. The engine has one type, `shaped`, for the crafting grid in
the player's inventory. Everything else, the base game's furnace and smithing table included, has a type of its own that
a mod defines.
## Crafting: `shaped`
@@ -22,13 +23,16 @@ For the crafting grid in the player's inventory screen:
`pattern` is 1 to 3 rows of 1 to 3 characters, where a space is an empty slot. `key` maps each letter to an item. The
pattern fits anywhere in the grid.
## Smelting: `furnace` and `fuel`
## Smelting: `bworld:smelting` and `bworld:fuel`
For the furnace. They're the base game's own types, registered by its shared script like
[any mod's](#custom-recipe-types):
```json
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:iron_ore",
"output": { "id": "bworld:iron_ingot", "count": 1 },
"cook_time": 200
@@ -39,12 +43,13 @@ pattern fits anywhere in the grid.
```json
{
"format_version": 1,
"recipe": { "type": "fuel", "item": "bworld:coal", "burn_time": 1000 }
"recipe": { "type": "bworld:fuel", "item": "bworld:coal", "burn_time": 1000 }
}
```
`cook_time` and `burn_time` are in ticks, 20 to a second. Two furnace recipes for the same input are an error. For fuel,
a later recipe for the same item replaces an earlier one.
`cook_time` and `burn_time` are in ticks, 20 to a second. Two smelting recipes for the same input are an error. For
fuel, a later recipe for the same item replaces an earlier one, so a mod that depends on the base game can change how
long something burns.
## Smithing: `bworld:smithing`
@@ -69,8 +74,7 @@ recipes with the same tool, material and addition are an error.
## Stonecutting: `bworld:stonecutting`
For the stonecutter, which cuts one item into another. It's the base game's own type, so `mods/bworld` checks these
recipes when the server starts rather than the engine:
For the stonecutter, which cuts one item into another. It's the base game's own type, registered by its shared script:
```json
{
@@ -91,7 +95,7 @@ uses up one of the input.
For the juicer, which presses an item into a fluid. The base game registers one from its
[shared script](#recipes-from-scripts) for every item with [`bworld:juiceable`](../items/food.md#juice), making the
juice named after it, so most mods never write one. A file can add one for anything else, or make something other than
juice. It's checked when the server starts, like stonecutting:
juice:
```json
{
@@ -113,7 +117,7 @@ makes. The juicer uses the first recipe that takes the item.
A fluid that ferments into another over time, like juice into wine. The base game registers one from its
[shared script](#recipes-from-scripts) for every [juice](../items/food.md#juice), into wine from the same item. A file
can add one for anything else. It's checked when the server starts, like juicing:
can add one for anything else:
```json
{
@@ -137,8 +141,9 @@ furnace smelts.
## Choices
Anywhere a recipe takes an item (`key` values, `input`, `item`), an item [tag](tags.md) means anything in it fits, and
so does a list of ids and tags:
Anywhere a recipe takes a choice of items (`shaped` keys, and the fields a type reads with
[`read.ingredient`](#custom-recipe-types), like smelting's `input` and fuel's `item`), an item [tag](tags.md) means
anything in it fits, and so does a list of ids and tags:
```json
"key": { "P": "#bworld:planks" }
@@ -173,9 +178,9 @@ export function setup(ctx: SharedContext) {
ctx.recipes.register_type<SmithingRecipe, { tool: ItemStack; material: ItemStack }>("bworld:smithing", {
// the json checked and turned into what matches and the machine use
parse: (json, read) => ({
tool: read.item(json, "tool"),
material: read.stack(json, "material"),
result: read.item(json, "result"),
tool: read.item(json.tool, "tool"),
material: read.stack(json.material, "material"),
result: read.item(json.result, "result"),
}),
// whether what's in the machine makes the recipe
matches: (recipe, input) =>
@@ -187,9 +192,16 @@ export function setup(ctx: SharedContext) {
`parse` runs once for every recipe of the type, from files and from [scripts](#recipes-from-scripts), in load order, on
the server and every client. Throwing stops the mod loading with an error naming the recipe, so a broken one is caught
when the server starts rather than when someone uses the machine. `read.item(json, field)` and `read.stack(json, field)`
check a field the way the engine's own types are checked, an item id or `{ id, count }` of an item that exists, and
throw naming the field.
when the server starts rather than when someone uses the machine. `read` checks a value the way the engine's own types
are checked, throwing with the name it's given, like `"result"` or `"ingredients[0]"`:
| Reader | Reads |
| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `read.item(value, name)` | An item id, of an item that exists. |
| `read.stack(value, name)` | `{ id, count }` of an item that exists. |
| `read.ingredient(value, name)` | A [choice](#choices): an item, a `#tag` or a list of them, as every item that fits. Its tags have to exist, but can be empty. |
| `read.fluid_stack(value, name)` | `{ fluid: { id, data }, amount }` of a fluid that exists, in mB. |
| `read.positive_int(value, name)` | A whole number, at least 1, like a time in ticks. |
Then server, client and shared scripts look recipes up by what's in the machine, like NeoForge's
`RecipeManager.getRecipeFor`:
@@ -203,36 +215,11 @@ ctx.recipes.all<SmithingRecipe>("bworld:smithing"); // every one, in load order
them, not copies, so they aren't to be changed. A type can only be registered during `setup`, in the mod's own
namespace. Other mods can add recipes of your type too, as long as they depend on your mod.
Types that aren't registered, like `bworld:cooking` for now, are read as JSON instead:
A recipe of a type no mod registers, like a misspelled one, stops the first mod with one from loading once every shared
script has set up, since nothing would ever read it.
```json
{
"format_version": 1,
"recipe": {
"type": "bworld:cooking",
"ingredients": ["bworld:cabbage", ["bworld:carrot", "bworld:potato", "bworld:onion"]],
"result": { "id": "bworld:cabbage_rolls", "count": 1 },
"cook_time": 100
}
}
```
The mod's server script reads them in `setup` and checks their fields itself:
```ts
const recipes = ctx.recipes.list("bworld:cooking").map((json, i) => {
if (!Array.isArray(json.ingredients) || json.ingredients.length > 6) {
throw new Error(`cooking recipe ${i + 1}: ingredients must be 1 to 6 items`);
}
// ...check the rest, and turn it into whatever the machine needs. expand turns #tags into their items
return { ingredients: json.ingredients.map((choice) => ctx.tags.expand(choice)) };
});
```
Throwing in `setup` stops the server from starting with the error, like a broken recipe of a registered type does.
`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.
`ctx.recipes.list(type?)` gives recipes as their JSON instead, copies in load order. It's how the recipe viewer shows
every mod's types, and how a shared script makes recipes from another type's, see below.
## Recipes From Scripts
@@ -255,7 +242,7 @@ export function setup(ctx: SharedContext) {
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
server or client script sets up, and one is checked like a file would be: a broken one, or a second smelting recipe for
the same input, throws, which stops the mod loading.
`ctx.recipes.list(type?)` reads the recipes there are so far, copies in load order, like the client's: every mod's
@@ -274,12 +261,10 @@ Make them from what's the same on every side, like items and their components, n
## Looking Up Recipes
Mods' registered types are looked up with [`find` and `all`](#custom-recipe-types). Server scripts can also ask about
the furnace's:
Every registered type, the base game's included, is looked up with [`find` and `all`](#custom-recipe-types). The base
game's smelting and fuel recipes are found by an item id:
```ts
ctx.recipes.furnace_result("bworld:iron_ore"); // { output, cook_time }, or undefined
ctx.recipes.is_smeltable("bworld:iron_ore");
ctx.recipes.is_fuel("bworld:coal");
ctx.recipes.fuel_value("bworld:coal"); // burn time in ticks, 0 when it isn't fuel
ctx.recipes.find("bworld:smelting", "bworld:iron_ore"); // { input, output, cook_time }, or undefined
ctx.recipes.find("bworld:fuel", "bworld:coal"); // { items, burn_time }, or undefined
```
+1 -1
View File
@@ -80,7 +80,7 @@ back. Depend on the mod whose tag you change, so your file loads after its. chec
## Using Tags in Data
- **Recipes**: anywhere a recipe takes an item (shaped `key` values, furnace `input`, fuel `item`) it can take an item
- **Recipes**: anywhere a recipe takes an item (shaped `key` values, smelting `input`, fuel `item`) it can take an item
tag, on its own or in a list: `"key": { "P": "#bworld:planks" }`. See [Choices](recipes.md#choices).
- **Blocks**: `place_on` and `place_in` take block tags, like `"place_on": ["#bworld:logs"]` for a fungus that grows on
any log. See [Placement](../blocks/index.md#placement).
+3 -3
View File
@@ -120,8 +120,8 @@ interface RecipeRegistry {
- Common scripts only run during loading and can't reach the world or players. They get the same `ctx` on both sides, so
they can't accidentally register different things.
- `register_type` would let `check-mods` and the loader validate mods' own recipe types, instead of each mod checking
its recipes in `setup`. `shaped`, `furnace` and `fuel` become short for `bworld:shaped` and so on. Shared scripts can
now register types with `ctx.recipes.register_type`, and `bworld:smithing` is one.
its recipes in `setup`. `shaped` becomes short for `bworld:shaped`. Shared scripts can now register types with
`ctx.recipes.register_type`, and every one of the base game's and create's are.
### The Freeze and the Registry Hash
@@ -277,7 +277,7 @@ engine assets in `assets/`.
| ---------------------------------------------------------------------- | ------------------------------------------------------------------------ | ------- |
| Blocks, items, models, entities, recipes, textures, credits | `mods/bworld` | Done |
| Hoeing, chest, furnace, smithing table, farming, watering can, fishing | `mods/bworld/scripts/server.ts` | Done |
| Recipe types `shaped`, `furnace`, `fuel` | engine (`common/mod_loader.ts`, `server/game/crafting.ts`) | Phase 5 |
| Recipe type `shaped` | engine (`common/mod_loader.ts`, `server/game/crafting.ts`) | Phase 5 |
| The player's inventory screen and crafting grid | engine (`client/gui/gui_player_inventory.ts`, `server/game/crafting.ts`) | Phase 5 |
| The hotbar and crosshair | engine (`client/gui/hud.ts`) | Phase 5 |
| `/give`, `/time` and `/summon` | engine (`server/game/game_server.ts`) | Phase 5 |
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "fuel",
"type": "bworld:fuel",
"item": "bworld:coal",
"burn_time": 1000
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "fuel",
"type": "bworld:fuel",
"item": "#bworld:logs",
"burn_time": 100
}
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:coal_ore",
"output": {
"id": "bworld:coal",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:cod",
"output": {
"id": "bworld:cooked_cod",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:copper_ore",
"output": {
"id": "bworld:copper_ingot",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:sand",
"output": {
"id": "bworld:glass",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:gold_ore",
"output": {
"id": "bworld:gold_ingot",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:iron_ore",
"output": {
"id": "bworld:iron_ingot",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "#bworld:logs",
"output": {
"id": "bworld:coal",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:salmon",
"output": {
"id": "bworld:cooked_salmon",
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:stone",
"output": {
"id": "bworld:smooth_stone",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:cobblestone",
"output": {
"id": "bworld:stone",
+1 -1
View File
@@ -1,7 +1,7 @@
{
"format_version": 1,
"recipe": {
"type": "furnace",
"type": "bworld:smelting",
"input": "bworld:tin_ore",
"output": {
"id": "bworld:tin_ingot",
+2 -2
View File
@@ -19,7 +19,7 @@ import type {
} from "bworld/client";
import { MINIGAMES } from "./minigames/mod.ts";
import { JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts";
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
import { STONECUTTING, stonecutting_options, type StonecuttingRecipe } from "./stonecutting.ts";
const WIDTH = 176;
// like minecraft's 176x166 container screens
@@ -185,7 +185,7 @@ const SCROLLER_OFF_COLOR: Color = [0.78, 0.78, 0.78, 1];
const SELECTED_COLOR: Color = [1, 1, 1, 0.45];
function stonecutter_screen(ctx: ClientContext, menu: ClientMenu): MenuScreen {
const recipes = stonecutting_recipes(ctx);
const recipes = ctx.recipes.all<StonecuttingRecipe>(STONECUTTING);
// the first row shown, and whether the scroller is being dragged
let row = 0;
let dragging = false;
+5 -119
View File
@@ -7,6 +7,7 @@
// CuttingBoardBlockEntity, holds a stack of anything and cuts it one at a time with the right tool
import type { BlockRef, Container, ItemStack, ServerContext } from "bworld/server";
import { COOKING, type CookingRecipe, CUTTING, type CuttingRecipe, INGREDIENT_SLOTS } from "./cooking_recipes.ts";
// stove
@@ -56,30 +57,16 @@ export function register_stove(ctx: ServerContext) {
// cooking pot
// slots 0-5 are the ingredients, 6 the meal waiting to be served, 7 containers for it, 8 the served meal
const INGREDIENT_SLOTS = 6;
const MEAL_SLOT = 6;
const CONTAINER_SLOT = 7;
const OUTPUT_SLOT = 8;
const POT_SIZE = 9;
// ticks, for recipes that don't say
const DEFAULT_COOK_TIME = 200;
// what's under the pot that heats it, and the state that has to be 1 for it to, like minecraft's heat_sources tag
const HEAT_SOURCES: Record<string, string | undefined> = {
"bworld:furnace": "lit",
"bworld:stove": "lit",
};
// a bworld:cooking recipe: the ingredients in any slots. in the json each is an item id or #tag, or a list of
// those any of which will do. here each is every item that will do
interface CookingRecipe {
ingredients: string[][];
result: { id: string; count: number };
// what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked
container?: string;
cook_time: number;
}
interface PotData {
container: string;
// ticks, counting up to cook_time_total
@@ -89,81 +76,18 @@ interface PotData {
meal_container: string;
}
// an ingredient: an item, or a #tag of items any of which will do
function item_or_tag(ctx: ServerContext, where: string, id: unknown) {
if (typeof id === "string" && id.startsWith("#")) {
if (!ctx.tags.exists("items", id)) throw new Error(`${where}: there's no item tag ${id}`);
} else if (typeof id !== "string" || !ctx.items.exists(id)) {
throw new Error(`${where}: there's no item ${id}`);
}
}
// checked when the server starts, so a broken recipe is a load error naming it
function load_recipes(ctx: ServerContext): CookingRecipe[] {
return ctx.recipes.list("bworld:cooking").map((json, i) => {
const where = `bworld:cooking recipe ${i + 1} (${json.result?.id ?? "no result"})`;
const item = (id: unknown) => {
if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`);
return id;
};
const ingredients = json.ingredients;
if (!Array.isArray(ingredients) || ingredients.length < 1 || ingredients.length > INGREDIENT_SLOTS) {
throw new Error(`${where}: ingredients must be 1 to ${INGREDIENT_SLOTS} items`);
}
for (const ingredient of ingredients) {
if (Array.isArray(ingredient)) {
if (ingredient.length === 0) throw new Error(`${where}: an ingredient's list of items is empty`);
ingredient.forEach((id) => item_or_tag(ctx, where, id));
} else {
item_or_tag(ctx, where, ingredient);
}
}
item(json.result?.id);
if (!Number.isInteger(json.result.count) || json.result.count < 1) {
throw new Error(`${where}: result.count must be a positive whole number`);
}
if (json.container !== undefined) item(json.container);
const cook_time = json.cook_time ?? DEFAULT_COOK_TIME;
if (!Number.isInteger(cook_time) || cook_time < 1) {
throw new Error(`${where}: cook_time must be positive ticks`);
}
return {
ingredients: ingredients.map((ingredient: string | string[]) => ctx.tags.expand(ingredient)),
result: json.result,
container: json.container,
cook_time,
};
});
}
// the recipe whose ingredients are exactly what's in the ingredient slots, one item from each, in any order
function find_recipe(recipes: CookingRecipe[], container: Container): CookingRecipe | undefined {
function find_recipe(ctx: ServerContext, container: Container): CookingRecipe | undefined {
const items: string[] = [];
for (let slot = 0; slot < INGREDIENT_SLOTS; slot++) {
const item = container.get(slot);
if (item) items.push(item.id);
}
if (items.length === 0) return undefined;
return recipes.find((recipe) => recipe.ingredients.length === items.length && matches(recipe.ingredients, items));
}
// pairs every ingredient with a different item, trying each way round, like a shapeless recipe
function matches(ingredients: string[][], items: string[], used = new Set<number>()): boolean {
if (ingredients.length === 0) return true;
const [first, ...rest] = ingredients;
const fits = (id: string) => first.includes(id);
for (let i = 0; i < items.length; i++) {
if (used.has(i) || !fits(items[i])) continue;
used.add(i);
if (matches(rest, items, used)) return true;
used.delete(i);
}
return false;
return ctx.recipes.find<CookingRecipe>(COOKING, items);
}
export function register_cooking_pot(ctx: ServerContext) {
const recipes = load_recipes(ctx);
const pot_data = (block: BlockRef): PotData => {
const existing = block.data?.container && ctx.containers.get(block.data.container);
const container = existing || ctx.containers.create(POT_SIZE);
@@ -277,7 +201,7 @@ export function register_cooking_pot(ctx: ServerContext) {
const data = pot_data(block);
const container = ctx.containers.get(data.container)!;
const heated = is_heated(block);
const recipe = heated ? find_recipe(recipes, container) : undefined;
const recipe = heated ? find_recipe(ctx, container) : undefined;
if (recipe && can_cook(container, recipe)) {
data.cook_time_total = recipe.cook_time;
@@ -297,47 +221,9 @@ export function register_cooking_pot(ctx: ServerContext) {
// cutting board
// a bworld:cutting recipe, like the java mod's: one ingredient (an item, or a list any of which will do), the
// tool type that cuts it, and everything one of it is cut into
interface CuttingRecipe {
ingredient: string[];
tool: string;
result: { id: string; count: number }[];
}
// checked when the server starts, like the cooking pot's
function load_cutting_recipes(ctx: ServerContext): CuttingRecipe[] {
return ctx.recipes.list("bworld:cutting").map((json, i) => {
const where = `bworld:cutting recipe ${i + 1} (${json.ingredients?.[0] ?? "no ingredient"})`;
const item = (id: unknown) => {
if (typeof id !== "string" || !ctx.items.exists(id)) throw new Error(`${where}: there's no item ${id}`);
return id;
};
if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) {
throw new Error(`${where}: ingredients must be one item, or one list of items any of which will do`);
}
const choice = [json.ingredients[0]].flat();
if (choice.length === 0) throw new Error(`${where}: the ingredient's list of items is empty`);
choice.forEach((id) => item_or_tag(ctx, where, id));
const ingredient = ctx.tags.expand(choice);
if (typeof json.tool !== "string") throw new Error(`${where}: tool must be a tool type, like "knife"`);
if (!Array.isArray(json.result) || json.result.length === 0) {
throw new Error(`${where}: result must be a list of { id, count }`);
}
for (const result of json.result) {
item(result?.id);
if (!Number.isInteger(result.count) || result.count < 1) {
throw new Error(`${where}: every result's count must be a positive whole number`);
}
}
return { ingredient, tool: json.tool, result: json.result };
});
}
// like the java mod's CuttingBoardBlock and CuttingBoardBlockEntity. what's on the board is the item it shows
// (set_block_item), so the client draws it, like its CuttingBoardRenderer
export function register_cutting_board(ctx: ServerContext) {
const recipes = load_cutting_recipes(ctx);
const on_board = (block: BlockRef) => ctx.world.get_block_item(block.x, block.y, block.z);
const set_on_board = (block: BlockRef, item: ItemStack | undefined) =>
ctx.world.set_block_item(block.x, block.y, block.z, item);
@@ -369,7 +255,7 @@ export function register_cutting_board(ctx: ServerContext) {
}
// anything else is a tool for cutting one of what's on it, like processStoredItemUsingTool
const recipe = item && recipes.find((recipe) => recipe.ingredient.includes(item.id));
const recipe = item && ctx.recipes.find<CuttingRecipe>(CUTTING, item.id);
if (item && recipe && ctx.items.tool(held.id) === recipe.tool) {
for (const result of recipe.result) ctx.world.drop_item(block.x, block.y, block.z, { ...result });
set_on_board(block, item.count > 1 ? { ...item, count: item.count - 1 } : undefined);
+85
View File
@@ -0,0 +1,85 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the kitchen's recipe types, registered by the shared script: what the cooking pot cooks, found by the items in its
// ingredient slots, and what the cutting board cuts, found by the item on it. see cooking.ts
import type { SharedContext } from "bworld/shared";
export const COOKING = "bworld:cooking";
export const CUTTING = "bworld:cutting";
// how many ingredients the pot holds
export const INGREDIENT_SLOTS = 6;
// ticks, for recipes that don't say
const DEFAULT_COOK_TIME = 200;
// a bworld:cooking recipe: the ingredients in any slots. in the json each is an item id or #tag, or a list of
// those any of which will do. here each is every item that will do
export interface CookingRecipe {
ingredients: string[][];
result: { id: string; count: number };
// what the meal is served in, like a bowl. without it the meal comes out as soon as it's cooked
container?: string;
cook_time: number;
}
// a bworld:cutting recipe, like the java mod's: one ingredient (an item, or a list any of which will do), the
// tool type that cuts it, and everything one of it is cut into
export interface CuttingRecipe {
ingredient: string[];
tool: string;
result: { id: string; count: number }[];
}
export function register_cooking_recipes(ctx: SharedContext) {
// found by the ids of what's in the ingredient slots
ctx.recipes.register_type<CookingRecipe, string[]>(COOKING, {
parse(json, read) {
const ingredients = json.ingredients;
if (!Array.isArray(ingredients) || ingredients.length < 1 || ingredients.length > INGREDIENT_SLOTS) {
throw new Error(`ingredients must be 1 to ${INGREDIENT_SLOTS} items`);
}
const recipe: CookingRecipe = {
ingredients: ingredients.map((choice, i) => read.ingredient(choice, `ingredients[${i}]`)),
result: read.stack(json.result, "result"),
cook_time: json.cook_time === undefined
? DEFAULT_COOK_TIME
: read.positive_int(json.cook_time, "cook_time"),
};
if (json.container !== undefined) recipe.container = read.item(json.container, "container");
return recipe;
},
matches: (recipe, items) => recipe.ingredients.length === items.length && pairs_up(recipe.ingredients, items),
});
ctx.recipes.register_type<CuttingRecipe, string>(CUTTING, {
parse(json, read) {
if (!Array.isArray(json.ingredients) || json.ingredients.length !== 1) {
throw new Error("ingredients must be one item, or one list of items any of which will do");
}
if (typeof json.tool !== "string") throw new Error(`tool must be a tool type, like "knife"`);
if (!Array.isArray(json.result) || json.result.length === 0) {
throw new Error("result must be a list of { id, count }");
}
return {
ingredient: read.ingredient(json.ingredients[0], "ingredients[0]"),
tool: json.tool,
result: json.result.map((result: unknown, i: number) => read.stack(result, `result[${i}]`)),
};
},
matches: (recipe, id) => recipe.ingredient.includes(id),
});
}
// pairs every ingredient with a different item, trying each way round, like a shapeless recipe
function pairs_up(ingredients: string[][], items: string[], used = new Set<number>()): boolean {
if (ingredients.length === 0) return true;
const [first, ...rest] = ingredients;
for (let i = 0; i < items.length; i++) {
if (used.has(i) || !first.includes(items[i])) continue;
used.add(i);
if (pairs_up(rest, items, used)) return true;
used.delete(i);
}
return false;
}
+10 -21
View File
@@ -3,9 +3,8 @@
// fermentable recipes: a fluid that ferments into another over a number of ticks, like juice into wine in the keg. the
// shared script registers one for every juice, and mods can add more like any recipe, as files or from their shared
// scripts
import type { FluidStack, SharedContext } from "bworld/shared";
import { fluid_stack, type RecipeReader } from "./juicing.ts";
// scripts. they're found by the fluid that ferments
import type { FluidStack, FluidVariant, SharedContext } from "bworld/shared";
import type { JuiceableParams } from "./shared.ts";
export const FERMENTABLE = "bworld:fermentable";
@@ -22,6 +21,14 @@ export interface FermentableRecipe {
// a recipe for every juice, the one each juiceable item makes, fermenting it into wine from the same fruit
export function register_fermenting(ctx: SharedContext) {
ctx.recipes.register_type<FermentableRecipe, FluidVariant>(FERMENTABLE, {
parse: (json, read) => ({
input: read.fluid_stack(json.input, "input"),
output: read.fluid_stack(json.output, "output"),
ticks: read.positive_int(json.ticks, "ticks"),
}),
matches: (recipe, fluid) => ctx.fluids.same(recipe.input.fluid, fluid),
});
for (const id of ctx.items.ids()) {
if (!(ctx.items.components(id)["bworld:juiceable"] as JuiceableParams | undefined)) continue;
ctx.recipes.register(FERMENTABLE, {
@@ -31,21 +38,3 @@ export function register_fermenting(ctx: SharedContext) {
});
}
}
// every fermentable recipe, in load order. a broken one throws, which stops the server from starting
export function fermentable_recipes(ctx: RecipeReader): FermentableRecipe[] {
return ctx.recipes.list(FERMENTABLE).map((json, i) => {
const where = `${FERMENTABLE} recipe ${i + 1}`;
const input = fluid_stack(ctx, json.input);
const output = fluid_stack(ctx, json.output);
if (!input || !output) {
throw new Error(
`${where}: input and output must each be a { fluid, amount } of a fluid that exists, in mB`,
);
}
if (!Number.isInteger(json.ticks) || json.ticks < 1) {
throw new Error(`${where}: ticks must be a whole number of ticks, at least 1`);
}
return { input, output, ticks: json.ticks };
});
}
+15 -48
View File
@@ -3,9 +3,9 @@
// juicing recipes: what the juicer presses an item into. the shared script registers one for every item with
// bworld:juiceable, its own juice, and mods can add more like any recipe, as files or from their shared scripts.
// whatever makes juice reads them, like the juicer. with create installed, each is also a create:compacting recipe,
// so its press can make juice in a basin
import type { FluidStack, SharedContext, TagApi } from "bworld/shared";
// whatever makes juice finds them by the item, like the juicer. with create installed, each is also a create:compacting
// recipe, so its press can make juice in a basin
import type { FluidStack, SharedContext } from "bworld/shared";
import type { JuiceableParams } from "./shared.ts";
export const JUICING = "bworld:juicing";
@@ -19,6 +19,18 @@ export interface JuicingRecipe {
// a recipe for every juiceable item, pressing one into the juice named after it, as much as its component says
export function register_juicing(ctx: SharedContext) {
ctx.recipes.register_type<JuicingRecipe, string>(JUICING, {
parse(json, read) {
if (!Array.isArray(json.fluid_results) || json.fluid_results.length !== 1) {
throw new Error("fluid_results must be one { fluid, amount }");
}
return {
input: read.ingredient(json.input, "input"),
juice: read.fluid_stack(json.fluid_results[0], "fluid_results[0]"),
};
},
matches: (recipe, id) => recipe.input.includes(id),
});
for (const id of ctx.items.ids()) {
const params = ctx.items.components(id)["bworld:juiceable"] as JuiceableParams | undefined;
if (!params) continue;
@@ -41,48 +53,3 @@ function register_compacting(ctx: SharedContext) {
});
}
}
// what reading them needs, which server scripts have
export interface RecipeReader {
// deno-lint-ignore no-explicit-any
recipes: { list(type: string): any[] };
tags: TagApi;
items: { exists(id: string): boolean };
fluids: { exists(id: string): boolean };
}
// every juicing recipe, in load order. a broken one throws, which stops the server from starting
export function juicing_recipes(ctx: RecipeReader): JuicingRecipe[] {
return ctx.recipes.list(JUICING).map((json, i) => {
const where = `${JUICING} recipe ${i + 1}`;
const choice: unknown = json.input;
const entries = typeof choice === "string" ? [choice] : Array.isArray(choice) ? choice : [];
const exists = (entry: unknown) =>
typeof entry === "string" &&
(entry.startsWith("#") ? ctx.tags.exists("items", entry.slice(1)) : ctx.items.exists(entry));
if (entries.length === 0 || !entries.every(exists)) {
throw new Error(`${where}: input must be an item, a #tag or a list of them, and they must exist`);
}
const results: unknown = json.fluid_results;
const juice = Array.isArray(results) && results.length === 1 ? fluid_stack(ctx, results[0]) : undefined;
if (!juice) {
throw new Error(`${where}: fluid_results must be one { fluid, amount } of a fluid that exists, in mB`);
}
return { input: ctx.tags.expand(choice as string | string[]), juice };
});
}
// a recipe's { fluid, amount } of a fluid that exists and a whole number of mB, undefined when it isn't one
export function fluid_stack(ctx: RecipeReader, json: unknown): FluidStack | undefined {
const stack = json as Partial<FluidStack> | undefined;
const id = stack?.fluid?.id;
if (typeof id !== "string" || !ctx.fluids.exists(id) || !Number.isInteger(stack!.amount) || stack!.amount! < 1) {
return undefined;
}
return { fluid: stack!.fluid!, amount: stack!.amount! };
}
// the first recipe that presses id, undefined when none does
export function juicing_for(recipes: JuicingRecipe[], id: string): JuicingRecipe | undefined {
return recipes.find((recipe) => recipe.input.includes(id));
}
+14 -16
View File
@@ -6,12 +6,13 @@ import type { BlockRef, Container, FluidHandler, FluidStack, Player, Season, Ser
import { register_curios } from "./curios.ts";
import { register_effects } from "./effects.ts";
import { register_fishing } from "./fishing.ts";
import { stonecutting_options, stonecutting_recipes } from "./stonecutting.ts";
import { STONECUTTING, stonecutting_options, type StonecuttingRecipe } from "./stonecutting.ts";
import { SMITHING, type SmithingRecipe } from "./smithing.ts";
import { FUEL, type FuelRecipe, SMELTING, type SmeltingRecipe } from "./smelting.ts";
import { register_verdigris } from "./verdigris/server.ts";
import { type JuiceableParams, JUICER_CAPACITY, JUICER_PRESSES } from "./shared.ts";
import { juicing_for, juicing_recipes } from "./juicing.ts";
import { fermentable_recipes } from "./fermenting.ts";
import { JUICING, type JuicingRecipe } from "./juicing.ts";
import { FERMENTABLE, type FermentableRecipe } from "./fermenting.ts";
import { register_cooking_pot, register_cutting_board, register_stove } from "./cooking.ts";
export function setup(ctx: ServerContext) {
@@ -219,7 +220,7 @@ function register_furnace(ctx: ServerContext) {
const container = ctx.containers.get(furnace_data(block).container)!;
menu.title = "Furnace";
menu.add_slot(container, 0, { x: 55, y: 16 });
menu.add_slot(container, 1, { x: 55, y: 52, filter: "fuel" });
menu.add_slot(container, 1, { x: 55, y: 52, filter: (item) => ctx.recipes.find(FUEL, item.id) !== undefined });
menu.add_slot(container, 2, { x: 115, y: 34, output_only: true });
menu.add_player_inventory(7, INVENTORY_Y);
for (const field of ["progress", "progress_max", "fuel", "fuel_max"] as const) {
@@ -250,7 +251,7 @@ function register_furnace(ctx: ServerContext) {
const data = furnace_data(block);
const container = ctx.containers.get(data.container)!;
const input = container.get(0);
const recipe = input && ctx.recipes.furnace_result(input.id);
const recipe = input && ctx.recipes.find<SmeltingRecipe>(SMELTING, input.id);
if (data.fuel > 0) {
data.fuel -= 1;
@@ -261,8 +262,9 @@ function register_furnace(ctx: ServerContext) {
} else {
// refuel
const fuel = container.get(1);
if (data.fuel === 0 && fuel && ctx.recipes.is_fuel(fuel.id)) {
data.fuel = ctx.recipes.fuel_value(fuel.id);
const burns = fuel && ctx.recipes.find<FuelRecipe>(FUEL, fuel.id);
if (data.fuel === 0 && fuel && burns) {
data.fuel = burns.burn_time;
data.fuel_max = data.fuel;
fuel.count -= 1;
}
@@ -277,7 +279,7 @@ function register_furnace(ctx: ServerContext) {
if (result) {
result.count += recipe.output.count;
} else {
container.set(2, recipe.output);
container.set(2, { ...recipe.output });
}
input.count -= 1;
}
@@ -500,7 +502,7 @@ const STONECUTTER_INPUT = 0;
const STONECUTTER_RESULT = 1;
function register_stonecutter(ctx: ServerContext) {
const recipes = stonecutting_recipes(ctx);
const recipes = ctx.recipes.all<StonecuttingRecipe>(STONECUTTING);
const menu_type = ctx.menus.register<BlockRef>("bworld:stonecutter", (menu, block, player) => {
const container = ctx.containers.create(2);
@@ -870,8 +872,6 @@ interface JuicerData {
function register_juicer(ctx: ServerContext) {
// what juice is made from and how it looks, read by the juicing recipes and the juice's rules in shared.ts
ctx.components.register_item<JuiceableParams>("bworld:juiceable", {});
// checked now, so a broken recipe stops the server rather than the juicer later
const recipes = juicing_recipes(ctx);
const show = (block: BlockRef, container: Container) => {
const item = container.get(0);
const data = item?.data !== undefined && { data: item.data };
@@ -895,7 +895,7 @@ function register_juicer(ctx: ServerContext) {
const held = player.held_item;
const container = block_container(ctx, block, 1);
const data = block.data as JuicerData;
if (held && juicing_for(recipes, held.id)) {
if (held && ctx.recipes.find(JUICING, held.id)) {
held.count = container.add(held)?.count ?? 0;
show(block, container);
// true even when none fit, so the fruit isn't eaten instead
@@ -907,7 +907,7 @@ function register_juicer(ctx: ServerContext) {
if (held || !player.is_sneaking()) return false;
const item = container.get(0);
const recipe = item && juicing_for(recipes, item.id);
const recipe = item && ctx.recipes.find<JuicingRecipe>(JUICING, item.id);
if (!item || !recipe) return false;
const juice = tank(block);
if (juice.fill(recipe.juice, "simulate") < recipe.juice.amount) return false;
@@ -949,11 +949,9 @@ interface KegData {
type KegTank = "input" | "output";
function register_keg(ctx: ServerContext) {
// checked now, so a broken recipe stops the server rather than the keg later
const recipes = fermentable_recipes(ctx);
const recipe_for = (block: BlockRef) => {
const fluid = (block.data as KegData | undefined)?.input?.fluid;
return fluid && recipes.find((recipe) => ctx.fluids.same(recipe.input.fluid, fluid));
return fluid && ctx.recipes.find<FermentableRecipe>(FERMENTABLE, fluid);
};
const tank = (block: BlockRef, which: KegTank) =>
ctx.fluids.tank_handler({
+6
View File
@@ -6,9 +6,12 @@
// or a door open the moment they click it. and the rules of juice and wine, which name and color them by the item
// they're from, and the recipes that make them. and the base game's recipe types
import type { SharedBlock, SharedContext } from "bworld/shared";
import { register_cooking_recipes } from "./cooking_recipes.ts";
import { register_fermenting } from "./fermenting.ts";
import { register_juicing } from "./juicing.ts";
import { register_smelting } from "./smelting.ts";
import { register_smithing } from "./smithing.ts";
import { register_stonecutting } from "./stonecutting.ts";
import { register_verdigris_rules } from "./verdigris/shared.ts";
export function setup(ctx: SharedContext) {
@@ -20,6 +23,9 @@ export function setup(ctx: SharedContext) {
register_juicing(ctx);
register_fermenting(ctx);
register_smithing(ctx);
register_smelting(ctx);
register_stonecutting(ctx);
register_cooking_recipes(ctx);
}
// the sides a fence connects on, and the face of the block there it connects to
+62
View File
@@ -0,0 +1,62 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// smelting and fuel recipes: the furnace cooks one item into another, burning fuel to do it. both are found by an item
// id, and registered by the shared script like smithing.ts
import type { SharedContext } from "bworld/shared";
export const SMELTING = "bworld:smelting";
export const FUEL = "bworld:fuel";
export interface SmeltingRecipe {
// the items it smelts
input: string[];
output: { id: string; count: number };
// ticks
cook_time: number;
}
export interface FuelRecipe {
items: string[];
// ticks
burn_time: number;
}
export function register_smelting(ctx: SharedContext) {
// two recipes for one item would leave one that can never be made
const smelted = new Set<string>();
ctx.recipes.register_type<SmeltingRecipe, string>(SMELTING, {
parse(json, read) {
const recipe = {
input: read.ingredient(json.input, "input"),
output: read.stack(json.output, "output"),
cook_time: read.positive_int(json.cook_time, "cook_time"),
};
for (const id of recipe.input) {
if (smelted.has(id)) throw new Error(`there's already one for ${id}`);
smelted.add(id);
}
return recipe;
},
matches: (recipe, id) => recipe.input.includes(id),
});
// a later recipe for an item takes it out of the earlier one's items, so a mod can change how long something
// burns and find gives its recipe
const burning = new Map<string, FuelRecipe>();
ctx.recipes.register_type<FuelRecipe, string>(FUEL, {
parse(json, read) {
const recipe = {
items: read.ingredient(json.item, "item"),
burn_time: read.positive_int(json.burn_time, "burn_time"),
};
for (const id of recipe.items) {
const earlier = burning.get(id);
if (earlier) earlier.items = earlier.items.filter((other) => other !== id);
burning.set(id, recipe);
}
return recipe;
},
matches: (recipe, id) => recipe.items.includes(id),
});
}
+4 -4
View File
@@ -27,11 +27,11 @@ export function register_smithing(ctx: SharedContext) {
ctx.recipes.register_type<SmithingRecipe, SmithingInput>(SMITHING, {
parse(json, read) {
const recipe: SmithingRecipe = {
tool: read.item(json, "tool"),
material: read.stack(json, "material"),
result: read.item(json, "result"),
tool: read.item(json.tool, "tool"),
material: read.stack(json.material, "material"),
result: read.item(json.result, "result"),
};
if (json.addition !== undefined) recipe.addition = read.item(json, "addition");
if (json.addition !== undefined) recipe.addition = read.item(json.addition, "addition");
const inputs = `${recipe.tool} ${recipe.material.id} ${recipe.addition}`;
if (seen.has(inputs)) throw new Error(`there's already one for ${recipe.tool} with ${recipe.material.id}`);
seen.add(inputs);
+15 -31
View File
@@ -1,10 +1,10 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the
// server's menu and the client's screen both list them from here, in the same order, so a button's number means the
// same recipe to both
import type { TagApi } from "bworld/shared";
// stonecutting recipes: the stonecutter cuts one item into another, picked from every recipe that takes it. the type is
// registered by the shared script, so the server's menu and the client's screen both list them from ctx.recipes.all, in
// the same order, so a button's number means the same recipe to both
import type { SharedContext } from "bworld/shared";
export const STONECUTTING = "bworld:stonecutting";
@@ -14,36 +14,20 @@ export interface StonecuttingRecipe {
output: { id: string; count: number };
}
// what reading them needs, which server and client scripts both have
interface RecipeReader {
// deno-lint-ignore no-explicit-any
recipes: { list(type: string): any[] };
tags: TagApi;
items: { exists(id: string): boolean };
}
// every stonecutting recipe, in load order. a broken one throws, which stops the server from starting
export function stonecutting_recipes(ctx: RecipeReader): StonecuttingRecipe[] {
return ctx.recipes.list(STONECUTTING).map((json, i) => {
const where = `${STONECUTTING} recipe ${i + 1}`;
// a tag can be empty, like one of another mod's items that isn't installed
const choice: unknown = json.input;
const entries = typeof choice === "string" ? [choice] : Array.isArray(choice) ? choice : [];
const exists = (entry: unknown) =>
typeof entry === "string" &&
(entry.startsWith("#") ? ctx.tags.exists("items", entry.slice(1)) : ctx.items.exists(entry));
if (entries.length === 0 || !entries.every(exists)) {
throw new Error(`${where}: input must be an item, a #tag or a list of them, and they must exist`);
}
const { id, count } = json.output ?? {};
if (typeof id !== "string" || !ctx.items.exists(id) || !Number.isInteger(count) || count < 1) {
throw new Error(`${where}: output must be { id, count } of an item that exists`);
}
return { input: ctx.tags.expand(choice as string | string[]), output: { id, count } };
export function register_stonecutting(ctx: SharedContext) {
ctx.recipes.register_type<StonecuttingRecipe, string>(STONECUTTING, {
parse: (json, read) => ({
input: read.ingredient(json.input, "input"),
output: read.stack(json.output, "output"),
}),
matches: (recipe, id) => recipe.input.includes(id),
});
}
// what an item can be cut into, in the order the stonecutter shows them
export function stonecutting_options(recipes: StonecuttingRecipe[], id: string | undefined): StonecuttingRecipe[] {
export function stonecutting_options(
recipes: readonly StonecuttingRecipe[],
id: string | undefined,
): StonecuttingRecipe[] {
return id === undefined ? [] : recipes.filter((recipe) => recipe.input.includes(id));
}
+15 -16
View File
@@ -2,9 +2,10 @@
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's processing recipes, the shape its machines' recipe types share, like ProcessingRecipe: item choices in, and
// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. read and checked when the server starts, so a broken one stops it there instead of
// in a machine. no ctx, tests give what it needs
import type { FluidStack, Id } from "bworld/shared";
// stacks out, each with a chance, and for the types that can, fluids out as { fluid, amount }. the shared script
// registers each type, so a broken recipe stops the mod loading instead of a machine later. no ctx, tests give what it
// needs
import type { FluidStack, Id, RecipeType } from "bworld/shared";
// how many ingredients, item results and fluid results a type takes at most, like getMaxInputCount,
// getMaxOutputCount and getMaxFluidOutputCount
@@ -42,14 +43,17 @@ export interface RecipeLookup {
fluid_exists(id: Id): boolean;
}
// every recipe of type, from their json, or an error saying what's wrong with each broken one
export function processing_recipes(jsons: unknown[], type: ProcessingType, lookup: RecipeLookup): ProcessingRecipe[] {
const parsed = jsons.map((json) => parse_processing(json, type, lookup));
const problems = parsed.flatMap((recipe, i) =>
"problems" in recipe ? [`${type.id} recipe ${JSON.stringify(jsons[i])}: ${recipe.problems.join("; ")}`] : []
);
if (problems.length > 0) throw new Error(problems.join("\n"));
return parsed as ProcessingRecipe[];
// the recipe type for ctx.recipes.register_type, saying everything wrong with a broken recipe. it's found by the item
// it takes first, like a machine's getRecipe
export function processing_type(type: ProcessingType, lookup: RecipeLookup): RecipeType<ProcessingRecipe, Id> {
return {
parse(json) {
const parsed = parse_processing(json, type, lookup);
if ("problems" in parsed) throw new Error(parsed.problems.join("; "));
return parsed;
},
matches: (recipe, item) => recipe.ingredients[0]?.includes(item) ?? false,
};
}
// one recipe, or what's wrong with it, like ProcessingRecipe.validate
@@ -120,11 +124,6 @@ export function parse_processing(
return problems.length > 0 ? { problems } : { ingredients, results, fluid_results };
}
// the first recipe that takes the item, like a machine's getRecipe
export function processing_for(recipes: ProcessingRecipe[], item: Id): ProcessingRecipe | undefined {
return recipes.find((recipe) => recipe.ingredients[0]?.includes(item));
}
// what one go of a recipe makes: each result, with each of its count kept by its chance, like rollResults
export function roll_results(recipe: ProcessingRecipe, random = Math.random): { id: Id; count: number }[] {
return recipe.results.flatMap(({ id, count, chance }) => {
+7 -20
View File
@@ -19,14 +19,7 @@ import {
} from "./kinetics/connections.ts";
import { flow_score, motor_step } from "./kinetics/generators.ts";
import { handle_added, handle_removed, type KineticWorld, update_generated } from "./kinetics/spreading.ts";
import {
COMPACTING,
PRESSING,
processing_for,
processing_recipes,
type ProcessingRecipe,
roll_results,
} from "./recipes/processing.ts";
import { COMPACTING, PRESSING, type ProcessingRecipe, roll_results } from "./recipes/processing.ts";
import { CYCLE, cycle_rate, PRESS_AT, type PressShown, SCAN_TICKS } from "./processing/press.ts";
import {
apply_basin_recipe,
@@ -90,16 +83,9 @@ export function setup(ctx: ServerContext) {
const config: Config = ctx.config;
const world = kinetic_world(ctx, config);
// checked now, so a broken recipe stops the server rather than a press later
const lookup = {
expand: (choice: Id | Id[]) => ctx.tags.expand(choice),
item_exists: (id: Id) => ctx.items.exists(id),
fluid_exists: (id: Id) => ctx.fluids.exists(id),
};
const pressing = processing_recipes(ctx.recipes.list(PRESSING.id), PRESSING, lookup);
// the ones that take more ingredients first, so a recipe isn't beaten by one that takes part of what it does, like
// BasinOperatingBlockEntity.getMatchingRecipes
const compacting = processing_recipes(ctx.recipes.list(COMPACTING.id), COMPACTING, lookup)
const compacting = [...ctx.recipes.all<ProcessingRecipe>(COMPACTING.id)]
.sort((a, b) => b.ingredients.length - a.ingredients.length);
ctx.components.register_block<KineticParams>("create:kinetic", {
@@ -209,7 +195,7 @@ export function setup(ctx: ServerContext) {
on_second: update_flow,
});
register_press(ctx, pressing, compacting);
register_press(ctx, compacting);
register_basin(ctx);
}
@@ -280,7 +266,8 @@ function set_basin(block: BlockRef, contents: Partial<BasinContents>) {
// lone item turns into what it's pressed into, and from a stack one at a time is, landing beside the rest. with a
// basin two blocks under it, it presses into that instead, making a compacting recipe in it each time, like
// MechanicalPressBlockEntity as a BasinOperatingBlockEntity. it only ticks while it turns
function register_press(ctx: ServerContext, recipes: ProcessingRecipe[], compacting: ProcessingRecipe[]) {
function register_press(ctx: ServerContext, compacting: ProcessingRecipe[]) {
const pressing_for = (item: Id) => ctx.recipes.find<ProcessingRecipe>(PRESSING.id, item);
// the basin two blocks under it, with a block between for the head to come down through, like
// BasinOperatingBlockEntity.getBasin
const basin_under = (block: BlockRef) => {
@@ -308,11 +295,11 @@ function register_press(ctx: ServerContext, recipes: ProcessingRecipe[], compact
{ x: block.x + inset, y: block.y - 1 + inset, z: block.z + inset },
{ x: block.x + 1 - inset, y: block.y - inset, z: block.z + 1 - inset },
"bworld:item",
).filter((item) => item.on_ground && processing_for(recipes, item.get_item()!.id));
).filter((item) => item.on_ground && pressing_for(item.get_item()!.id));
const press = (item: EntityRef) => {
const stack = item.get_item()!;
const results = roll_results(processing_for(recipes, stack.id)!);
const results = roll_results(pressing_for(stack.id)!);
const { x, y, z } = item.position;
if (stack.count === 1) {
const [first, ...rest] = results;
+5
View File
@@ -5,6 +5,7 @@
// placed against, and chain drives join into lines
import type { BlockPlacement, Face, Id, SharedContext } from "bworld/shared";
import { chain_update, type ChainState } from "./kinetics/chains.ts";
import { COMPACTING, PRESSING, processing_type } from "./recipes/processing.ts";
import {
AXES,
type Axis,
@@ -20,6 +21,10 @@ import {
} from "./kinetics/connections.ts";
export function setup(ctx: SharedContext) {
const lookup = { expand: ctx.tags.expand, item_exists: ctx.items.exists, fluid_exists: ctx.fluids.exists };
ctx.recipes.register_type(PRESSING.id, processing_type(PRESSING, lookup));
ctx.recipes.register_type(COMPACTING.id, processing_type(COMPACTING, lookup));
// what turns at x y z, undefined when nothing does
const kinetic_at = (x: number, y: number, z: number): KineticShape | undefined => {
const id = ctx.world.get_block(x, y, z);
+2 -4
View File
@@ -66,7 +66,7 @@ function base_categories(tags: TagApi): RecipeCategory[] {
},
},
{
type: "furnace",
type: "bworld:smelting",
title: "Smelting",
width: 82,
height: 54,
@@ -80,7 +80,7 @@ function base_categories(tags: TagApi): RecipeCategory[] {
},
},
{
type: "fuel",
type: "bworld:fuel",
title: "Fuel",
width: 98,
height: 36,
@@ -323,8 +323,6 @@ export function make_categories(ctx: ClientContext, recipes: Recipe[]): RecipeCa
export function category_name(type: string): string {
const base: Record<string, string> = {
shaped: "Crafting",
furnace: "Smelting",
fuel: "Fuel",
[FISHING]: "Fishing",
[CRABPOT]: "Crab Pot",
[JUICING]: "Juicing",
+5 -5
View File
@@ -17,9 +17,9 @@ export function outputs(recipe: Recipe): Ingredient[] {
switch (recipe.type) {
case "shaped":
return [stack(recipe.result)];
case "furnace":
case "bworld:smelting":
return [stack(recipe.output)];
case "fuel":
case "bworld:fuel":
return [];
case "bworld:smithing":
return [{ ids: [recipe.result], count: 1 }];
@@ -46,7 +46,7 @@ export function fluid_inputs(recipe: Recipe): FluidAmount[] {
return recipe.fluid_ingredients ?? [];
}
// what a recipe takes. shaped keys, furnace inputs and fuels can be an item or #tag, or a list any of which fits
// what a recipe takes. shaped keys, smelting inputs and fuels can be an item or #tag, or a list any of which fits
export function inputs(recipe: Recipe, tags: TagApi): Ingredient[] {
switch (recipe.type) {
case "shaped":
@@ -54,9 +54,9 @@ export function inputs(recipe: Recipe, tags: TagApi): Ingredient[] {
ids: tags.expand(choice),
count: 1,
}));
case "furnace":
case "bworld:smelting":
return [{ ids: tags.expand(recipe.input), count: 1 }];
case "fuel":
case "bworld:fuel":
return [{ ids: tags.expand(recipe.item), count: 1 }];
case "bworld:smithing":
return [{ ids: [recipe.tool], count: 1 }, stack(recipe.material)].concat(
+8 -17
View File
@@ -24,7 +24,7 @@ import { AIR, CHUNK_SIZE, faces, ID_MASK } from "$/common/constants.ts";
import { physics } from "$/common/physics.ts";
import { clock } from "$/common/time.ts";
import { BlockRules } from "$/common/block_rules.ts";
import { FluidRules } from "$/common/fluids.ts";
import { fluid_exists, FluidRules, same_fluid } from "$/common/fluids.ts";
import { interact, item_handler, tank_handler, transfer, use_container } from "./fluid_handlers.ts";
import type { SharedContext } from "$/common/mod_api/shared.ts";
import { tag_api } from "$/common/tags.ts";
@@ -57,7 +57,7 @@ import type {
ServerContext,
SlotOptions,
} from "$/common/mod_api/server.ts";
import { ModLoadError, recipe_lookup, shared_recipes_api } from "$/common/mod_loader.ts";
import { check_recipe_types, ModLoadError, recipe_lookup, shared_recipes_api } from "$/common/mod_loader.ts";
import {
argument,
block as block_argument,
@@ -257,7 +257,7 @@ export class ModRuntime {
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));
added.push(menu_slot(mod, player, container, slot, options));
return menu.slots.length + added.length - 1;
},
}, api);
@@ -278,6 +278,7 @@ export class ModRuntime {
for (const { mod, version, url, engine_access, config } of scripts) {
await loading_mod(mod, engine_access, () => this.#load_shared_script(mod, version, url, config));
}
check_recipe_types(game.recipes);
} finally {
this.#shared_setup = false;
}
@@ -298,6 +299,8 @@ export class ModRuntime {
blocks,
items: shared_items_api(mod),
fluids: {
exists: fluid_exists,
same: same_fluid,
register: (id, rules) => {
if (!this.#setting_up) throw new ModLoadError(mod, "rules can only be registered during setup");
this.fluid_rules.register(mod, id, rules);
@@ -1007,13 +1010,6 @@ export class ModRuntime {
interact,
},
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),
...recipe_lookup(() => game().recipes),
list: (type) => structuredClone(game().recipes.by_type.get(type) ?? []),
},
@@ -1149,7 +1145,7 @@ export class ModRuntime {
menu.open_data = structuredClone(value) ?? null;
},
add_slot(container, slot, options) {
menu.slots.push(menu_slot(game, mod, server_player, container, slot, options));
menu.slots.push(menu_slot(mod, server_player, container, slot, options));
return menu.slots.length - 1;
},
add_fluid_slot(handler, tank, options) {
@@ -1327,7 +1323,6 @@ export function new_stack(item: ItemStack): EngineItemStack {
// a menu's slot from what a mod's add_slot got
function menu_slot(
game: GameServer,
mod: string,
player: ServerPlayer,
container: Container,
@@ -1345,11 +1340,7 @@ function menu_slot(
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") {
if (typeof filter === "function") {
added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true;
}
if (options.output_only) added.output = true;
+9 -5
View File
@@ -1,16 +1,19 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// create's recipe types: read and checked when the server starts, and shown by the recipe viewer
// create's recipe types: read and checked when the mod loads, and shown by the recipe viewer
import { assert, assertEquals, assertThrows } from "@std/assert";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import { tag_api } from "$/common/tags.ts";
import type { ClientContext } from "$/common/mod_api/client.ts";
import type { RecipeReader } from "$/common/mod_api/shared.ts";
import { recipe_lookup } from "$/common/mod_loader.ts";
import {
COMPACTING,
parse_processing,
PRESSING,
processing_recipes,
processing_type,
type ProcessingRecipe,
} from "$/mods/create/scripts/recipes/processing.ts";
import { inputs, outputs } from "$/mods/recipe_viewer/scripts/recipes.ts";
import { RecipeIndex } from "$/mods/recipe_viewer/scripts/recipes_screen.ts";
@@ -24,7 +27,7 @@ const lookup = () => ({
Deno.test("create's pressing recipes are read with every item each ingredient stands for", async () => {
const { game } = await test_game("mods");
const recipes = processing_recipes(game.recipes.by_type.get(PRESSING.id) ?? [], PRESSING, lookup());
const recipes = recipe_lookup(() => game.recipes).all<ProcessingRecipe>(PRESSING.id);
const sheet = recipes.find((recipe) => recipe.results[0].id === "create:iron_sheet");
assert(sheet, "iron is pressed into sheets");
assert(sheet.ingredients[0].includes("bworld:iron_ingot"));
@@ -50,9 +53,10 @@ Deno.test("a pressing recipe that a press couldn't make says what's wrong with i
assertEquals(problems({ ingredients: ["bworld:iron_ingot"], results: [sheet], processing_time: 100 }).length, 1);
assertEquals(problems({ results: [sheet] }).length, 1);
// the server doesn't start with one, and says which
// the mod doesn't load with one, and says what's wrong
const type = processing_type(PRESSING, lookup());
assertThrows(
() => processing_recipes([{ ingredients: ["bworld:no_such_ingot"], results: [sheet] }], PRESSING, lookup()),
() => type.parse({ ingredients: ["bworld:no_such_ingot"], results: [sheet] }, {} as RecipeReader),
Error,
"bworld:no_such_ingot",
);
+1 -1
View File
@@ -261,7 +261,7 @@ export function client_of(game: GameServer, area: Area) {
},
items: shared_items_api("bworld"),
// only its blocks are looked at here
fluids: { register() {} },
fluids: { exists: () => false, same: () => false, register() {} },
recipes: { register() {}, list: () => [], register_type() {}, find: () => undefined, all: () => [] },
world,
components: { register_block: (id, block_rules) => rules.register("bworld", id, block_rules) },
+3 -2
View File
@@ -10,6 +10,7 @@ import { block_variant } from "$/common/block_models.ts";
import { load_worldgen } from "$/common/worldgen_loader.ts";
import { create_mod } from "$/tools/new_mod.ts";
import { PLAYER_MENU_CRAFTING, PROTOCOL_VERSION } from "$/common/protocol.ts";
import { recipe_lookup } from "$/common/mod_loader.ts";
import { container_items, copy_dir, test_game } from "./helpers.ts";
// mods/bworld plus a mod made from the template, in a temp folder
@@ -31,8 +32,8 @@ Deno.test("the base game loads from mods/bworld", async () => {
assert(EverythingRegistry.get<ItemRegistry>("items", "bworld:stone"));
assert(EverythingRegistry.get<ItemRegistry>("items", "bworld:coal"));
assert(game.recipes.shaped.some((recipe) => recipe.result.id === "bworld:oak_planks"));
assert(game.recipes.furnace.has("bworld:iron_ore"));
assert(game.recipes.fuel.has("bworld:coal"));
assert(recipe_lookup(() => game.recipes).find("bworld:smelting", "bworld:iron_ore"));
assert(recipe_lookup(() => game.recipes).find("bworld:fuel", "bworld:coal"));
assertEquals(EverythingRegistry.get<BlockRegistry>("blocks", "bworld:water")?.replaceable, true);
// still has its code until it's a component
assert(EverythingRegistry.get<ItemRegistry>("items", "bworld:copper_watering_can")?.on_create);
+14 -4
View File
@@ -78,12 +78,16 @@ Deno.test("the recipe viewer finds what makes and uses an item, in any recipe ty
const served_in_bowls = using("bworld:bowl").map((r) => outputs(r)[0].ids[0]);
assert(served_in_bowls.includes("bworld:cooked_rice"));
assert(served_in_bowls.includes("bworld:tomato_sauce"));
assert(using("bworld:coal").some((r) => r.type === "fuel"));
assert(using("bworld:coal").some((r) => r.type === "bworld:fuel"));
assert(using("bworld:coal").some((r) => r.type === "shaped" && outputs(r)[0].ids[0] === "bworld:stove"));
assert(using("bworld:potato").includes(rolls));
// smelting and smithing
assert(using("bworld:iron_ore").some((r) => r.type === "furnace" && outputs(r)[0].ids[0] === "bworld:iron_ingot"));
assert(
using("bworld:iron_ore").some((r) =>
r.type === "bworld:smelting" && outputs(r)[0].ids[0] === "bworld:iron_ingot"
),
);
assertEquals(ids(inputs(making("bworld:stone_pickaxe")[0])), ["bworld:wood_pickaxe", "bworld:stone"]);
assertEquals(category_name("bworld:smithing"), "Smithing");
});
@@ -104,8 +108,14 @@ Deno.test("recipes are found by category in jei's order, and a catalyst's uses a
{ category, recipes },
) => [category.type, recipes]);
const all = game.recipes.all;
assertEquals(furnace_uses.find(([type]) => type === "furnace")?.[1], all.filter((r) => r.type === "furnace"));
assertEquals(furnace_uses.find(([type]) => type === "fuel")?.[1], all.filter((r) => r.type === "fuel"));
assertEquals(
furnace_uses.find(([type]) => type === "bworld:smelting")?.[1],
all.filter((r) => r.type === "bworld:smelting"),
);
assertEquals(
furnace_uses.find(([type]) => type === "bworld:fuel")?.[1],
all.filter((r) => r.type === "bworld:fuel"),
);
assertEquals(index.find(item("bworld:air"), "recipes"), []);
});
+45 -11
View File
@@ -8,11 +8,13 @@ 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_order } from "$/common/mod_check.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
// sifts into what its component says, and a shaped recipe made in code. then sifting and washing as testrecipes' own
// types, found by the item put in
const SHARED = `
import type { SharedContext } from "bworld/shared";
export function setup(ctx: SharedContext) {
@@ -21,6 +23,12 @@ const SHARED = `
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 } });
for (const type of ["testrecipes:sifting", "testrecipes:washing"]) {
ctx.recipes.register_type(type, {
parse: (json, read) => ({ input: read.item(json.input, "input"), result: read.stack(json.result, "result") }),
matches: (recipe, input) => recipe.input === input,
});
}
SHARED_EXTRA
}
`;
@@ -101,14 +109,9 @@ Deno.test("recipes a shared script registers are on the server and clients, for
assertEquals(seen.testrecipes_client, SIFTING);
});
// sifting as a type of testrecipes' own, matched by the item put in, and a recipe registered after it
const SIFTING_TYPE = `
ctx.recipes.register_type("testrecipes:sifting", {
parse: (json, read) => ({ input: read.item(json, "input"), result: read.stack(json, "result") }),
matches: (recipe, input) => recipe.input === input,
});
ctx.recipes.register("testrecipes:sifting", { input: "testrecipes:sand", result: { id: "testrecipes:gravel", count: 1 } });
`;
// a sifting recipe registered after the type
const SAND_AFTER =
`ctx.recipes.register("testrecipes:sifting", { input: "testrecipes:sand", result: { id: "testrecipes:gravel", count: 1 } });`;
const SAND_FILE = {
"sand.json": {
@@ -119,7 +122,7 @@ const SAND_FILE = {
};
Deno.test("a recipe type parses its recipes, and find gives the first one an input makes, on every side", async () => {
const dir = recipe_mod(SIFTING_TYPE, SAND_FILE);
const dir = recipe_mod(SAND_AFTER, SAND_FILE);
await test_game(dir);
await load_client(dir);
for (const side of ["server", "client"]) {
@@ -135,7 +138,7 @@ Deno.test("a recipe type parses its recipes, and find gives the first one an inp
});
Deno.test("a recipe its type can't parse stops the mod loading, naming it", async () => {
const dir = recipe_mod(SIFTING_TYPE, {
const dir = recipe_mod("", {
"sand.json": {
type: "testrecipes:sifting",
input: "testrecipes:nothing",
@@ -150,6 +153,22 @@ Deno.test("a recipe its type can't parse stops the mod loading, naming it", asyn
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a recipe of a type no mod registers stops its mod loading, like a misspelled one", async () => {
const dir = recipe_mod("", {
"sand.json": {
type: "testrecipes:sieving",
input: "testrecipes:sand",
result: { id: "testrecipes:flint", count: 1 },
},
});
await assertRejects(
() => test_game(dir),
Error,
"testrecipes: it has testrecipes:sieving recipes, but no mod registers that type",
);
Deno.removeSync(dir, { recursive: true });
});
Deno.test("a mod can only register recipe types in its own namespace", async () => {
const dir = recipe_mod(
`ctx.recipes.register_type("bworld:sifting", { parse: (json) => json, matches: () => true });`,
@@ -201,3 +220,18 @@ Deno.test("recipes can only be registered while shared scripts set up", async ()
Deno.removeSync(dir, { recursive: true });
}
});
Deno.test("every mod's recipe types are registered on a client too, so it loads them", async () => {
const mods = load_order(load_and_check("mods"));
const bmods = await Promise.all(mods.map(async (mod) => read_bmod(await pack_mod(mod), `${mod.id}.bmod`)));
const listings = mods.map((mod): ModListing => ({
id: mod.id,
name: mod.id,
version: "1.0.0",
sha256: "",
file: "",
size: 0,
}));
EverythingRegistry.clear();
await load_client_mods(listings, bmods);
});
+50
View File
@@ -0,0 +1,50 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the base game's bworld:smelting and bworld:fuel recipes, as another mod adding to them sees them
import { assertEquals, assertRejects } from "@std/assert";
import { recipe_lookup } from "$/common/mod_loader.ts";
import { copy_dir, test_game } from "./helpers.ts";
// the base game, and a mod after it with these recipes
function kiln_mod(recipes: Record<string, unknown>) {
const dir = Deno.makeTempDirSync({ prefix: "bworld_smelting_" });
copy_dir("mods/bworld", `${dir}/bworld`);
const write = (path: string, json: unknown) => {
Deno.mkdirSync(`${dir}/kiln/${path.split("/").slice(0, -1).join("/")}`, { recursive: true });
Deno.writeTextFileSync(`${dir}/kiln/${path}`, JSON.stringify(json));
};
write("manifest.json", {
format_version: 1,
id: "kiln",
name: "Kiln",
version: "1.0.0",
dependencies: [{ id: "bworld", version: "*" }],
});
for (const [name, recipe] of Object.entries(recipes)) write(`recipes/${name}.json`, { format_version: 1, recipe });
return dir;
}
Deno.test("a later fuel recipe for an item changes how long it burns, and leaves the rest of the earlier one", async () => {
const dir = kiln_mod({ coal: { type: "bworld:fuel", item: ["bworld:coal", "bworld:oak_log"], burn_time: 50 } });
const { game } = await test_game(dir);
Deno.removeSync(dir, { recursive: true });
const recipes = recipe_lookup(() => game.recipes);
const burn_time = (id: string) => recipes.find<{ burn_time: number }>("bworld:fuel", id)?.burn_time;
assertEquals(burn_time("bworld:coal"), 50);
assertEquals(burn_time("bworld:oak_log"), 50);
assertEquals(burn_time("bworld:spruce_log"), 100);
});
Deno.test("two smelting recipes for one item stop the mod loading", async () => {
const dir = kiln_mod({
iron: {
type: "bworld:smelting",
input: "bworld:iron_ore",
output: { id: "bworld:stone", count: 1 },
cook_time: 10,
},
});
await assertRejects(() => test_game(dir), Error, "there's already one for bworld:iron_ore");
Deno.removeSync(dir, { recursive: true });
});
+6 -1
View File
@@ -183,7 +183,12 @@ Deno.test("check-mods finds broken tags and tags nobody defines", async () => {
write("tags/fluids/maple/sap.json", { format_version: 1, tag: { values: [] } });
write("recipes/uses_missing_tag.json", {
format_version: 1,
recipe: { type: "fuel", item: "#maple:nothing_here", burn_time: 100 },
recipe: {
type: "shaped",
pattern: ["#"],
key: { "#": "#maple:nothing_here" },
result: { id: "maple:maple_planks", count: 1 },
},
});
// another mod's namespace, without depending on it
write("tags/items/kitchen/knives.json", { format_version: 1, tag: { values: ["maple:maple_planks"] } });
+4 -2
View File
@@ -8,6 +8,7 @@ import { CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
import { generate_raw_chunk } from "$/common/generation.ts";
import { get_biome } from "$/common/worldgen/biomes.ts";
import { update_crafting_result } from "$/server/game/crafting.ts";
import { recipe_lookup } from "$/common/mod_loader.ts";
import { copy_dir, test_game } from "./helpers.ts";
Deno.test("recipes that take planks take any kind, even mixed, but nothing else", async () => {
@@ -30,9 +31,10 @@ Deno.test("recipes that take planks take any kind, even mixed, but nothing else"
assertEquals(grid.get_item(CRAFTING_RESULT_SLOT)?.type_id, "bworld:dark_oak_planks");
// every log burns and smelts
const recipes = recipe_lookup(() => game.recipes);
for (const log of ["bworld:oak_log", "bworld:spruce_log", "bworld:cherry_log"]) {
assert(game.recipes.fuel.has(log), log);
assert(game.recipes.furnace.has(log), log);
assert(recipes.find("bworld:fuel", log), log);
assert(recipes.find("bworld:smelting", log), log);
}
});