Every recipe type registered from shared scripts

This commit is contained in:
2026-11-03 15:34:41 -03:00
committed by paula
parent 65113862f7
commit b329a61d96
25 changed files with 334 additions and 371 deletions
+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));
}
+7 -11
View File
@@ -6,13 +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) {
@@ -502,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);
@@ -872,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 };
@@ -897,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
@@ -909,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;
@@ -951,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({
+4
View File
@@ -6,10 +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) {
@@ -22,6 +24,8 @@ export function setup(ctx: SharedContext) {
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
+7 -10
View File
@@ -23,20 +23,14 @@ export interface FuelRecipe {
}
export function register_smelting(ctx: SharedContext) {
// deno-lint-ignore no-explicit-any
const ticks = (json: any, field: string): number => {
if (!Number.isInteger(json[field]) || json[field] < 1) throw new Error(`${field} must be at least 1 tick`);
return json[field];
};
// 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"),
output: read.stack(json, "output"),
cook_time: ticks(json, "cook_time"),
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}`);
@@ -52,7 +46,10 @@ export function register_smelting(ctx: SharedContext) {
const burning = new Map<string, FuelRecipe>();
ctx.recipes.register_type<FuelRecipe, string>(FUEL, {
parse(json, read) {
const recipe = { items: read.ingredient(json, "item"), burn_time: ticks(json, "burn_time") };
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);
+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);