Improve recipe viewer
This commit is contained in:
@@ -87,20 +87,16 @@ export abstract class GuiMenuScreen extends GuiScreen {
|
||||
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
|
||||
const g = this.graphics;
|
||||
g.begin();
|
||||
// an overlay drawing something in the screen's place, like the recipe viewer's recipes, hides all of it
|
||||
const hidden = this.#overlay_hides_screen();
|
||||
if (!hidden) {
|
||||
g.origin_x = this.x;
|
||||
g.origin_y = this.y;
|
||||
this.render_background(g);
|
||||
this.#render_slots();
|
||||
this.render_labels(g);
|
||||
}
|
||||
g.origin_x = this.x;
|
||||
g.origin_y = this.y;
|
||||
this.render_background(g);
|
||||
this.#render_slots();
|
||||
this.render_labels(g);
|
||||
|
||||
// mods' overlays go on top and get the mouse first, then the slots get what they left
|
||||
g.origin_x = g.origin_y = 0;
|
||||
this.#render_overlays();
|
||||
if (hidden || g.mouse_blocked()) {
|
||||
if (g.mouse_blocked()) {
|
||||
this.hovering = undefined;
|
||||
} else {
|
||||
this.handle_interaction();
|
||||
@@ -155,18 +151,6 @@ export abstract class GuiMenuScreen extends GuiScreen {
|
||||
highlight("slot_highlight_front");
|
||||
}
|
||||
|
||||
#overlay_hides_screen() {
|
||||
for (const entry of [...inventory_overlays]) {
|
||||
try {
|
||||
if (entry.overlay.hides_screen?.()) return true;
|
||||
} catch (e) {
|
||||
console.error(`[${entry.mod}] inventory overlay's hides_screen threw, removing it:`, e);
|
||||
inventory_overlays.splice(inventory_overlays.indexOf(entry), 1);
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
#render_overlays() {
|
||||
const hovered = this.hovering && this.hovering.container.get_item(this.hovering.index);
|
||||
const view = {
|
||||
|
||||
+23
-1
@@ -2,7 +2,7 @@
|
||||
// see docs/modding/networking/index.md
|
||||
import { AIR } from "$/common/constants.ts";
|
||||
import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts";
|
||||
import type { ClientContext, ClientMenu, InventoryOverlay, MenuScreen } from "$/common/mod_api/client.ts";
|
||||
import type { ClientContext, ClientMenu, InventoryOverlay, KeyMappings, MenuScreen } from "$/common/mod_api/client.ts";
|
||||
import { ModListing, ModLoadError, RecipeBook, register_mod_data } from "$/common/mod_loader.ts";
|
||||
import { type Bmod, read_bmod } from "$/common/bmod.ts";
|
||||
import { display_name } from "$/common/utils.ts";
|
||||
@@ -139,6 +139,7 @@ function client_context(listing: ModListing): ClientContext {
|
||||
},
|
||||
hud: not_yet("hud", "HUD elements") as ClientContext["hud"],
|
||||
input: not_yet("input", "keybinds") as ClientContext["input"],
|
||||
options: key_mappings(need_client),
|
||||
net: {
|
||||
on(channel, handler) {
|
||||
own(channel);
|
||||
@@ -189,3 +190,24 @@ function client_context(listing: ModListing): ClientContext {
|
||||
log: (...args) => console.log(`[${mod}]`, ...args),
|
||||
};
|
||||
}
|
||||
|
||||
// the client's key settings as they are when read, so changing them reaches mods
|
||||
function key_mappings(client: () => Client): KeyMappings {
|
||||
const keys = [
|
||||
"key_forward",
|
||||
"key_back",
|
||||
"key_left",
|
||||
"key_right",
|
||||
"key_jump",
|
||||
"key_sprint",
|
||||
"key_sneak",
|
||||
"key_inventory",
|
||||
"key_drop",
|
||||
"key_chat",
|
||||
] as const;
|
||||
const mappings = {} as KeyMappings;
|
||||
for (const key of keys) {
|
||||
Object.defineProperty(mappings, key, { get: () => client().options[key], enumerable: true });
|
||||
}
|
||||
return Object.freeze(mappings);
|
||||
}
|
||||
|
||||
@@ -8,6 +8,9 @@ export interface ClientContext {
|
||||
ui: ClientUi;
|
||||
hud: HudRegistry;
|
||||
input: { bind(id: Id, default_key: KeyCode, on_press: () => void): void };
|
||||
// the player's settings, read only, like minecraft's Options. a screen closes on key_inventory like the inventory,
|
||||
// the way jei's recipes screen checks options.keyInventory
|
||||
options: KeyMappings;
|
||||
net: ClientNet;
|
||||
// is_swimming: lying flat in water in the 0.8 tall box, like minecraft's isSwimming
|
||||
player: { readonly name: string; readonly position: Readonly<Position>; is_swimming(): boolean };
|
||||
@@ -36,6 +39,20 @@ export interface ClientContext {
|
||||
log(...args: unknown[]): void;
|
||||
}
|
||||
|
||||
// the keys the player has bound, like the key mappings in minecraft's Options
|
||||
export interface KeyMappings {
|
||||
readonly key_forward: KeyCode;
|
||||
readonly key_back: KeyCode;
|
||||
readonly key_left: KeyCode;
|
||||
readonly key_right: KeyCode;
|
||||
readonly key_jump: KeyCode;
|
||||
readonly key_sprint: KeyCode;
|
||||
readonly key_sneak: KeyCode;
|
||||
readonly key_inventory: KeyCode;
|
||||
readonly key_drop: KeyCode;
|
||||
readonly key_chat: KeyCode;
|
||||
}
|
||||
|
||||
// a screen with no menu, only on this client, like neoforge's Screen. see docs/modding/gui/index.md
|
||||
export interface Screen {
|
||||
// when it opens, and whenever the window changes size. in gui pixels
|
||||
@@ -115,9 +132,6 @@ export interface Graphics {
|
||||
// list. it gets the screen's box to lay itself out around
|
||||
export interface InventoryOverlay {
|
||||
on_render(g: Graphics, screen: InventoryScreenView): void;
|
||||
// while it's true the screen underneath isn't drawn or clicked, panels outside its box included, for something
|
||||
// drawn in its place like the recipe viewer's recipes. asked every frame, before on_render
|
||||
hides_screen?(): boolean;
|
||||
// the screen closed for any reason, like the player closing their inventory
|
||||
on_close?(): void;
|
||||
}
|
||||
|
||||
@@ -28,7 +28,7 @@ name.
|
||||
> [!TIP]
|
||||
> The mods already in the repository are the best reference. `mods/bworld` is the base game itself, written against the
|
||||
> same API as any other mod. `mods/farmersdelight` adds crops, a stove, a cooking pot and a cutting board, and
|
||||
> `mods/recipe_viewer` is a client-only mod that draws over inventory screens.
|
||||
> `mods/recipe_viewer` is a client-only mod with an inventory overlay and a screen of its own.
|
||||
|
||||
## Checking Your Mod
|
||||
|
||||
|
||||
@@ -86,12 +86,12 @@ Overlays get the mouse before the slots:
|
||||
- While a `g.text_input` has the keyboard, keybinds like the inventory key don't fire. Text inputs edit like chat:
|
||||
selecting with shift or the mouse, ctrl+a, and copy, cut and paste.
|
||||
|
||||
`hides_screen()`, if the overlay has one, is asked every frame before `on_render`. While it returns `true` the screen
|
||||
underneath isn't drawn and its slots don't react to the mouse, including the panels mods add outside its box, like the
|
||||
curios slots. The recipe viewer does this while it shows a recipe in the screen's place.
|
||||
|
||||
`on_close()`, if the overlay has one, runs when the screen closes for any reason, like the player closing their
|
||||
inventory. The recipe viewer goes back to its item list then.
|
||||
inventory.
|
||||
|
||||
To show something bigger than fits around the screen, open a [screen](#plain-screens) over it with `ctx.ui.open`, like
|
||||
the recipe viewer's recipes screen does, the way Just Enough Items opens its recipes GUI. Escape goes back to the screen
|
||||
underneath.
|
||||
|
||||
An overlay that throws is removed, with the error in the console.
|
||||
|
||||
@@ -148,9 +148,14 @@ ctx.items.exists(id);
|
||||
ctx.items.name(id); // "Cooked Rice"
|
||||
ctx.items.mod(id); // the name of the mod that added it
|
||||
ctx.recipes.list(type?); // every recipe as its JSON, including mods' own types
|
||||
ctx.options.key_inventory; // the key the player has bound, like Minecraft's Options key mappings
|
||||
```
|
||||
|
||||
`ctx.player` and `ctx.world` only work once the player is in the world, not during `setup`.
|
||||
`ctx.player`, `ctx.world` and `ctx.options` only work once the player is in the world, not during `setup`.
|
||||
|
||||
The key mappings are `key_forward`, `key_back`, `key_left`, `key_right`, `key_jump`, `key_sprint`, `key_sneak`,
|
||||
`key_inventory`, `key_drop` and `key_chat`. A screen that should close on the inventory key, like the recipe viewer's,
|
||||
checks `g.key_pressed(ctx.options.key_inventory)` and calls `ctx.ui.close()`, the way JEI checks `keyInventory`.
|
||||
|
||||
## Not Built Yet
|
||||
|
||||
|
||||
@@ -1,13 +1,20 @@
|
||||
# Recipe Viewer
|
||||
|
||||
A recipe viewer like Just Enough Items, as a client script. Every inventory screen gets the list of every item on its
|
||||
right, with a search box (`@mod` searches by mod, like `@farmersdelight`).
|
||||
right, with the page on top and a search box under it (`@mod` searches by mod, like `@farmersdelight`).
|
||||
|
||||
- Left click an item, or press R over any item (in the list or in a slot), for the recipes that make it.
|
||||
- Right click, or U, for the recipes that use it.
|
||||
- In the recipes, click items to follow them. Backspace or Back goes back, X closes.
|
||||
- Left click an item, or press R over any item (in the list, a slot or a recipe), for the recipes that make it.
|
||||
- Right click, or U, for the recipes that use it. The uses of a block that makes recipes, like the furnace, are all of
|
||||
the recipes made in it.
|
||||
|
||||
It reads every mod's recipes with `ctx.recipes.list()`. It knows how to draw shaped, furnace, fuel and smithing recipes,
|
||||
and draws other mods' recipe types from their JSON: the items in their lists as ingredients, a single item (like the
|
||||
cooking pot's bowl) under the arrow, and their `result`. `CATALYSTS` in `scripts/client.ts` says which block makes each
|
||||
type.
|
||||
The recipes open in a screen of their own, laid out like JEI's: a tab for each category above it, where the category is
|
||||
made down its left side, the category and the page between their arrows, then the recipes. Clicking items in it follows
|
||||
them, Backspace goes back, and Escape or the inventory key (E) returns to the inventory.
|
||||
|
||||
It reads every mod's recipes with `ctx.recipes.list()`.
|
||||
|
||||
- `scripts/categories.ts` has a category for each recipe type, like JEI's `IRecipeCategory`: its title, size, where it's
|
||||
made (`MOD_CATALYSTS` for mods' types) and where its items go. Types without one are drawn from their JSON: the items
|
||||
in their lists as ingredients, a single item (like the cooking pot's bowl) under the arrow, and their `result`.
|
||||
- `scripts/recipes.ts` reads what any recipe makes and takes.
|
||||
- `scripts/item_list.ts` is the item list, `scripts/recipes_screen.ts` the recipes screen.
|
||||
|
||||
@@ -0,0 +1,151 @@
|
||||
// how each recipe type is shown, like jei's IRecipeCategory: a title, a fixed size every recipe of it is drawn in, the
|
||||
// blocks it's made in (jei's recipe catalysts), and where its items go. types no category knows get one from their
|
||||
// recipes' json, see mod_category
|
||||
import type { ClientContext, TagApi } from "bworld/client";
|
||||
import { type Ingredient, mod_recipe_inputs, outputs, type Recipe, seconds, stack } from "./recipes.ts";
|
||||
|
||||
// in gui pixels, a slot with its border, like minecraft's
|
||||
export const SLOT = 18;
|
||||
// the decorations are 16x16, and jei puts its 22x15 arrow about here
|
||||
const ARROW = 16;
|
||||
|
||||
// what a category draws a recipe with, at positions from the recipe's top left, like jei's IRecipeLayoutBuilder and
|
||||
// IRecipeExtrasBuilder
|
||||
export interface RecipeLayout {
|
||||
// a slot, empty when ingredient is undefined. alternatives take turns
|
||||
slot(ingredient: Ingredient | undefined, x: number, y: number, tooltip?: string[]): void;
|
||||
texture(id: string, x: number, y: number, w: number, h: number): void;
|
||||
text(text: string, x: number, y: number): void;
|
||||
}
|
||||
|
||||
export interface RecipeCategory {
|
||||
readonly type: string;
|
||||
readonly title: string;
|
||||
readonly width: number;
|
||||
readonly height: number;
|
||||
// where these recipes are made, shown left of the recipes and as their tab's icon
|
||||
readonly catalysts: string[];
|
||||
draw(recipe: Recipe, layout: RecipeLayout): void;
|
||||
}
|
||||
|
||||
// where each mod's recipe type is made, for the categories made from json
|
||||
const MOD_CATALYSTS: Record<string, string[]> = {
|
||||
"farmersdelight:cooking": ["farmersdelight:cooking_pot"],
|
||||
"farmersdelight:cutting": ["farmersdelight:cutting_board"],
|
||||
};
|
||||
|
||||
// the base game's, in the order their tabs go, like jei's vanilla plugin
|
||||
function base_categories(tags: TagApi): RecipeCategory[] {
|
||||
return [
|
||||
{
|
||||
// shaped recipes are made in the inventory's grid
|
||||
type: "shaped",
|
||||
title: "Crafting",
|
||||
width: 116,
|
||||
height: 54,
|
||||
catalysts: [],
|
||||
draw(recipe, layout) {
|
||||
const width = Math.max(...recipe.pattern.map((row: string) => row.length));
|
||||
for (let row = 0; row < 3; row++) {
|
||||
for (let column = 0; column < 3; column++) {
|
||||
const letter = recipe.pattern[row]?.[column];
|
||||
const choice = letter && letter !== " " && column < width ? recipe.key[letter] : undefined;
|
||||
const ingredient = choice ? { ids: tags.expand(choice), count: 1 } : undefined;
|
||||
layout.slot(ingredient, column * SLOT, row * SLOT);
|
||||
}
|
||||
}
|
||||
layout.texture("bworld:arrow_full", 61, 19, ARROW, ARROW);
|
||||
layout.slot(stack(recipe.result), 94, 18);
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "furnace",
|
||||
title: "Smelting",
|
||||
width: 82,
|
||||
height: 54,
|
||||
catalysts: ["bworld:furnace"],
|
||||
draw(recipe, layout) {
|
||||
layout.slot({ ids: tags.expand(recipe.input), count: 1 }, 0, 0);
|
||||
layout.texture("bworld:fire_full", 1, 20, ARROW, ARROW);
|
||||
layout.texture("bworld:arrow_full", 24, 18, ARROW, ARROW);
|
||||
layout.slot(stack(recipe.output), 60, 18);
|
||||
layout.text(seconds(recipe.cook_time), 24, 45);
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "fuel",
|
||||
title: "Fuel",
|
||||
width: 98,
|
||||
height: 36,
|
||||
catalysts: ["bworld:furnace"],
|
||||
draw(recipe, layout) {
|
||||
layout.slot({ ids: tags.expand(recipe.item), count: 1 }, 0, 0);
|
||||
layout.texture("bworld:fire_full", 1, 20, ARROW, ARROW);
|
||||
layout.text(`Burns for ${seconds(recipe.burn_time)}`, 24, 5);
|
||||
},
|
||||
},
|
||||
{
|
||||
type: "smithing",
|
||||
title: "Smithing",
|
||||
width: 108,
|
||||
height: 18,
|
||||
catalysts: ["bworld:smithing_table"],
|
||||
draw(recipe, layout) {
|
||||
layout.slot({ ids: [recipe.tool], count: 1 }, 0, 0);
|
||||
layout.slot(stack(recipe.material), SLOT, 0);
|
||||
layout.slot(recipe.addition ? { ids: [recipe.addition], count: 1 } : undefined, SLOT * 2, 0);
|
||||
layout.texture("bworld:arrow_full", 61, 1, ARROW, ARROW);
|
||||
layout.slot({ ids: [recipe.result], count: 1 }, 90, 0);
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// a mod's own type, from its recipes' json: the items in its lists in a grid, a single item (like a bowl to serve in)
|
||||
// under the arrow, then what it makes, one under the other
|
||||
function mod_category(type: string, tags: TagApi): RecipeCategory {
|
||||
return {
|
||||
type,
|
||||
title: category_name(type),
|
||||
width: 116,
|
||||
height: 54,
|
||||
catalysts: MOD_CATALYSTS[type] ?? [],
|
||||
draw(recipe, layout) {
|
||||
const { grid, extras } = mod_recipe_inputs(recipe, tags);
|
||||
grid.slice(0, 9).forEach((ingredient, i) =>
|
||||
layout.slot(ingredient, (i % 3) * SLOT, Math.floor(i / 3) * SLOT)
|
||||
);
|
||||
layout.texture("bworld:arrow_full", 61, 19, ARROW, ARROW);
|
||||
extras.slice(0, 1).forEach((ingredient) => layout.slot(ingredient, 60, 36, ["Served in"]));
|
||||
const made = outputs(recipe).slice(0, 3);
|
||||
made.forEach((output, i) => layout.slot(output, 94, made.length > 1 ? i * SLOT : SLOT));
|
||||
if (typeof recipe.cook_time === "number") layout.text(seconds(recipe.cook_time), 84, 45);
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// every type the recipes have, the base game's first, then mods' by name. catalysts that don't exist, like a mod's
|
||||
// that isn't loaded, are left out
|
||||
export function make_categories(ctx: ClientContext, recipes: Recipe[]): RecipeCategory[] {
|
||||
const base = base_categories(ctx.tags);
|
||||
const known = new Set(base.map((category) => category.type));
|
||||
const mod_types = [...new Set(recipes.map((recipe) => recipe.type as string))].filter((type) => !known.has(type))
|
||||
.sort();
|
||||
return [...base, ...mod_types.map((type) => mod_category(type, ctx.tags))].map((category) => ({
|
||||
...category,
|
||||
catalysts: category.catalysts.filter((id) => ctx.items.exists(id)),
|
||||
}));
|
||||
}
|
||||
|
||||
// "Crafting", or a mod type's name: farmersdelight:cooking is "Cooking"
|
||||
export function category_name(type: string): string {
|
||||
const base: Record<string, string> = {
|
||||
shaped: "Crafting",
|
||||
furnace: "Smelting",
|
||||
fuel: "Fuel",
|
||||
smithing: "Smithing",
|
||||
};
|
||||
if (base[type]) return base[type];
|
||||
const name = type.split(":")[1] ?? type;
|
||||
return name.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
|
||||
}
|
||||
@@ -1,416 +1,24 @@
|
||||
// a recipe viewer like just enough items: every item in a list next to the inventory, searchable, and clicking one (or
|
||||
// R and U over any item) shows the recipes that make it and the ones that use it. it only reads recipes, so it works
|
||||
// with any mod's, and draws the ones it doesn't know as their items in, then what comes out
|
||||
import type { ClientContext, Color, Graphics, InventoryScreenView, TagApi } from "bworld/client";
|
||||
|
||||
// in gui pixels. items and slots are drawn this big
|
||||
const CELL = 18;
|
||||
const GAP = 5;
|
||||
const LINE = 10;
|
||||
const BUTTON = 11;
|
||||
// catppuccin mocha, like the engine's gui: crust, pink, subtext 0 and blue
|
||||
const SLOT_COLOR: Color = [0.07, 0.07, 0.11, 0.6];
|
||||
const HOVER_COLOR: Color = [0.96, 0.76, 0.91, 0.35];
|
||||
const LABEL_COLOR: Color = [0.65, 0.68, 0.78, 1];
|
||||
const MOD_COLOR: Color = [0.54, 0.71, 0.98, 1];
|
||||
// alternatives, like "any vegetable", take turns this often
|
||||
const CYCLE_MS = 1000;
|
||||
|
||||
// where each recipe type is made, like jei's recipe catalysts. shaped recipes are made in the inventory
|
||||
const CATALYSTS: Record<string, string> = {
|
||||
furnace: "bworld:furnace",
|
||||
fuel: "bworld:furnace",
|
||||
smithing: "bworld:smithing_table",
|
||||
"farmersdelight:cooking": "farmersdelight:cooking_pot",
|
||||
"farmersdelight:cutting": "farmersdelight:cutting_board",
|
||||
};
|
||||
const CATEGORY_NAMES: Record<string, string> = {
|
||||
shaped: "Crafting",
|
||||
furnace: "Smelting",
|
||||
fuel: "Fuel",
|
||||
smithing: "Smithing",
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
type Recipe = any;
|
||||
// one place in a recipe: the items any of which fit, and how many
|
||||
type Ingredient = { ids: string[]; count: number };
|
||||
type Mode = "recipes" | "uses";
|
||||
// R and U over any item) opens a screen with the recipes that make it or the ones that use it, like jei's. it only
|
||||
// reads recipes, so it works with any mod's, and draws the ones it has no category for from their json
|
||||
import type { ClientContext } from "bworld/client";
|
||||
import { ItemList, type Mode } from "./item_list.ts";
|
||||
import { RecipeIndex, RecipesScreen } from "./recipes_screen.ts";
|
||||
|
||||
export function setup(ctx: ClientContext) {
|
||||
ctx.ui.add_inventory_overlay(new RecipeViewer(ctx));
|
||||
}
|
||||
const index = new RecipeIndex(ctx);
|
||||
const list = new ItemList(ctx);
|
||||
// like jei's IRecipesGui.show, only when there's something to show
|
||||
const open = (item: string, mode: Mode) => {
|
||||
if (index.find(item, mode).length > 0) ctx.ui.open(new RecipesScreen(ctx, index, list, item, mode));
|
||||
};
|
||||
|
||||
class RecipeViewer {
|
||||
#page = 0;
|
||||
// what the recipe view shows, and where it came from for going back
|
||||
#view: { item: string; mode: Mode; page: number } | undefined;
|
||||
#history: { item: string; mode: Mode; page: number }[] = [];
|
||||
// set on the first frame, once every mod's items and recipes are loaded
|
||||
#items: string[] | undefined;
|
||||
#recipes: Recipe[] = [];
|
||||
|
||||
constructor(private ctx: ClientContext) {}
|
||||
|
||||
on_render(g: Graphics, screen: InventoryScreenView) {
|
||||
this.#items ??= this.ctx.items.ids().filter((id) => id !== "bworld:air");
|
||||
if (this.#recipes.length === 0) this.#recipes = this.ctx.recipes.list();
|
||||
|
||||
// the item under the mouse in the list or the recipe view, then in the inventory's slots
|
||||
let hovered = this.#item_list(g, screen);
|
||||
if (this.#view) hovered = this.#recipe_view(g, screen, this.#view) ?? hovered;
|
||||
hovered ??= screen.hovered_item?.id;
|
||||
|
||||
if (hovered && g.key_pressed("KeyR")) this.#open(hovered, "recipes");
|
||||
if (hovered && g.key_pressed("KeyU")) this.#open(hovered, "uses");
|
||||
if (this.#view && g.key_pressed("Backspace")) this.#back();
|
||||
}
|
||||
|
||||
// the recipes are drawn where the screen was, so its slots, and the panels mods add around it like curios', don't
|
||||
// show beside them
|
||||
hides_screen() {
|
||||
return this.#view !== undefined;
|
||||
}
|
||||
|
||||
// the recipe views go with the inventory, it opens again on the item list
|
||||
on_close() {
|
||||
this.#view = undefined;
|
||||
this.#history = [];
|
||||
}
|
||||
|
||||
#open(item: string, mode: Mode) {
|
||||
if (this.#find(item, mode).length === 0) return;
|
||||
if (this.#view) this.#history.push(this.#view);
|
||||
this.#view = { item, mode, page: 0 };
|
||||
}
|
||||
|
||||
#back() {
|
||||
this.#view = this.#history.pop();
|
||||
}
|
||||
|
||||
#find(item: string, mode: Mode): Recipe[] {
|
||||
return this.#recipes.filter((recipe) =>
|
||||
mode === "recipes"
|
||||
? outputs(recipe).some((output) => output.ids.includes(item))
|
||||
: inputs(recipe, this.ctx.tags).some((input) => input.ids.includes(item))
|
||||
);
|
||||
}
|
||||
|
||||
// every item, in pages in the space right of the screen, with a search box under them. returns the hovered one
|
||||
#item_list(g: Graphics, screen: InventoryScreenView): string | undefined {
|
||||
const left = screen.x + screen.width + GAP;
|
||||
const width = g.width - GAP - left;
|
||||
const columns = Math.floor(width / CELL);
|
||||
const top = GAP + BUTTON + GAP / 2;
|
||||
const rows = Math.floor((g.height - GAP - BUTTON - GAP / 2 - top) / CELL);
|
||||
if (columns < 2 || rows < 1) return undefined;
|
||||
|
||||
const search = g.text_input("search", left, g.height - GAP - BUTTON, columns * CELL).trim().toLowerCase();
|
||||
const items = this.#items!.filter((id) => matches_search(this.ctx, id, search));
|
||||
const per_page = columns * rows;
|
||||
const pages = Math.max(1, Math.ceil(items.length / per_page));
|
||||
this.#page = Math.min(this.#page, pages - 1);
|
||||
|
||||
// the page bar
|
||||
if (g.button("<", left, GAP, BUTTON * 1.5, BUTTON)) this.#page = (this.#page + pages - 1) % pages;
|
||||
if (g.button(">", left + columns * CELL - BUTTON * 1.5, GAP, BUTTON * 1.5, BUTTON)) {
|
||||
this.#page = (this.#page + 1) % pages;
|
||||
}
|
||||
const label = `${this.#page + 1}/${pages}`;
|
||||
g.text(label, left + (columns * CELL - g.measure_text(label)) / 2, GAP + (BUTTON - g.text_height) / 2);
|
||||
|
||||
let hovered: string | undefined;
|
||||
items.slice(this.#page * per_page, (this.#page + 1) * per_page).forEach((id, i) => {
|
||||
const x = left + (i % columns) * CELL;
|
||||
const y = top + Math.floor(i / columns) * CELL;
|
||||
if (this.#item_cell(g, id, x, y, false)) hovered = id;
|
||||
});
|
||||
if (items.length === 0) g.text("Nothing found", left, top, { color: [0.8, 0.8, 0.8, 1] });
|
||||
return hovered;
|
||||
}
|
||||
|
||||
// an item that can be hovered for its tooltip and clicked for its recipes (right click, its uses)
|
||||
#item_cell(g: Graphics, id: string, x: number, y: number, slot: boolean, count = 1, extra: string[] = []): boolean {
|
||||
if (slot) g.rect(x, y, CELL, CELL, SLOT_COLOR);
|
||||
g.item(id, x, y, count);
|
||||
const { mouse } = g;
|
||||
if (mouse.x < x || mouse.y < y || mouse.x >= x + CELL || mouse.y >= y + CELL) return false;
|
||||
g.rect(x, y, CELL, CELL, HOVER_COLOR);
|
||||
g.item_tooltip(id, mouse.x, mouse.y, [
|
||||
...extra,
|
||||
{ text: id, color: LABEL_COLOR },
|
||||
{ text: this.ctx.items.mod(id), color: MOD_COLOR },
|
||||
]);
|
||||
if (mouse.pressed) {
|
||||
g.consume_click();
|
||||
this.#open(id, "recipes");
|
||||
} else if (mouse.right_pressed) {
|
||||
g.consume_click();
|
||||
this.#open(id, "uses");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// the recipes for or with an item, a page at a time, over the screen. returns the hovered item
|
||||
#recipe_view(g: Graphics, screen: InventoryScreenView, view: { item: string; mode: Mode; page: number }) {
|
||||
const { x, y, width, height } = screen;
|
||||
g.block_mouse(x, y, width, height);
|
||||
g.panel(x, y, width, height);
|
||||
|
||||
// header: the item, what's shown, back and close
|
||||
const title = `${this.ctx.items.name(view.item)} - ${view.mode === "recipes" ? "Recipes" : "Uses"}`;
|
||||
g.text(title, x + GAP, y + GAP, { color: LABEL_COLOR });
|
||||
if (g.button("X", x + width - GAP - BUTTON, y + GAP / 2, BUTTON, BUTTON)) {
|
||||
this.#view = undefined;
|
||||
this.#history = [];
|
||||
return undefined;
|
||||
}
|
||||
if (
|
||||
this.#history.length > 0 &&
|
||||
g.button("Back", x + width - GAP * 2 - BUTTON * 4, y + GAP / 2, BUTTON * 3, BUTTON)
|
||||
) {
|
||||
this.#back();
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const recipes = this.#find(view.item, view.mode);
|
||||
const top = y + GAP + BUTTON;
|
||||
const bottom = y + height - GAP - BUTTON;
|
||||
const pages = paginate(recipes, bottom - top, this.ctx.tags);
|
||||
view.page = Math.min(view.page, pages.length - 1);
|
||||
|
||||
let hovered: string | undefined;
|
||||
let card_y = top;
|
||||
for (const recipe of pages[view.page]) {
|
||||
hovered = this.#card(g, recipe, x + GAP, card_y, width - GAP * 2) ?? hovered;
|
||||
card_y += card_height(recipe, this.ctx.tags);
|
||||
}
|
||||
const page_count = pages.length;
|
||||
|
||||
if (page_count > 1) {
|
||||
if (g.button("<", x + GAP, bottom, BUTTON * 1.5, BUTTON)) {
|
||||
view.page = (view.page + page_count - 1) % page_count;
|
||||
}
|
||||
if (g.button(">", x + width - GAP - BUTTON * 1.5, bottom, BUTTON * 1.5, BUTTON)) {
|
||||
view.page = (view.page + 1) % page_count;
|
||||
}
|
||||
const label = `${view.page + 1}/${page_count}`;
|
||||
g.text(label, x + (width - g.measure_text(label)) / 2, bottom + (BUTTON - g.text_height) / 2, {
|
||||
color: LABEL_COLOR,
|
||||
});
|
||||
}
|
||||
return hovered;
|
||||
}
|
||||
|
||||
// one recipe: its category and where it's made, then its items. returns the hovered item
|
||||
#card(g: Graphics, recipe: Recipe, x: number, y: number, width: number): string | undefined {
|
||||
let hovered: string | undefined;
|
||||
const cell = (ingredient: Ingredient | undefined, cx: number, cy: number, extra: string[] = []) => {
|
||||
if (!ingredient || ingredient.ids.length === 0) {
|
||||
g.rect(cx, cy, CELL, CELL, SLOT_COLOR);
|
||||
return;
|
||||
}
|
||||
const id = ingredient.ids[Math.floor(Date.now() / CYCLE_MS) % ingredient.ids.length];
|
||||
const any = ingredient.ids.length > 1 ? [`Any of ${ingredient.ids.length}`] : [];
|
||||
if (this.#item_cell(g, id, cx, cy, true, ingredient.count, [...any, ...extra])) hovered = id;
|
||||
};
|
||||
const texture = (id: string, cx: number, cy: number) => g.texture(id, cx, cy, CELL, CELL);
|
||||
|
||||
g.text(category_name(recipe.type), x, y, { color: LABEL_COLOR });
|
||||
const catalyst = CATALYSTS[recipe.type];
|
||||
if (catalyst && this.ctx.items.exists(catalyst)) {
|
||||
cell({ ids: [catalyst], count: 1 }, x + width - CELL, y, ["Made here"]);
|
||||
} else if (recipe.type === "shaped") {
|
||||
const text = "In the inventory";
|
||||
g.text(text, x + width - g.measure_text(text), y, { color: LABEL_COLOR });
|
||||
}
|
||||
const top = y + LINE;
|
||||
|
||||
switch (recipe.type) {
|
||||
case "shaped": {
|
||||
const width_in = Math.max(...recipe.pattern.map((row: string) => row.length));
|
||||
for (let row = 0; row < 3; row++) {
|
||||
for (let column = 0; column < 3; column++) {
|
||||
const letter = recipe.pattern[row]?.[column];
|
||||
const choice = letter && letter !== " " && column < width_in ? recipe.key[letter] : undefined;
|
||||
cell(
|
||||
choice ? { ids: this.ctx.tags.expand(choice), count: 1 } : undefined,
|
||||
x + column * CELL,
|
||||
top + row * CELL,
|
||||
);
|
||||
}
|
||||
}
|
||||
texture("bworld:arrow_full", x + 3.5 * CELL, top + CELL);
|
||||
cell(stack(recipe.result), x + 5 * CELL, top + CELL);
|
||||
break;
|
||||
}
|
||||
case "furnace":
|
||||
cell({ ids: this.ctx.tags.expand(recipe.input), count: 1 }, x, top);
|
||||
texture("bworld:fire_full", x, top + CELL);
|
||||
texture("bworld:arrow_full", x + 1.5 * CELL, top + CELL / 2);
|
||||
cell(stack(recipe.output), x + 3 * CELL, top + CELL / 2);
|
||||
g.text(seconds(recipe.cook_time), x + 1.5 * CELL, top + CELL * 1.5, { color: LABEL_COLOR });
|
||||
break;
|
||||
case "fuel":
|
||||
cell({ ids: this.ctx.tags.expand(recipe.item), count: 1 }, x, top);
|
||||
texture("bworld:fire_full", x, top + CELL);
|
||||
g.text(`Burns for ${seconds(recipe.burn_time)}`, x + 1.5 * CELL, top + CELL / 2, {
|
||||
color: LABEL_COLOR,
|
||||
});
|
||||
break;
|
||||
case "smithing":
|
||||
cell({ ids: [recipe.tool], count: 1 }, x, top + CELL / 2);
|
||||
cell(stack(recipe.material), x + CELL, top + CELL / 2);
|
||||
cell(recipe.addition ? { ids: [recipe.addition], count: 1 } : undefined, x + 2 * CELL, top + CELL / 2);
|
||||
texture("bworld:arrow_full", x + 3.5 * CELL, top + CELL / 2);
|
||||
cell({ ids: [recipe.result], count: 1 }, x + 5 * CELL, top + CELL / 2);
|
||||
break;
|
||||
default: {
|
||||
// a mod's own type: the items in its lists in a grid, single items (like a bowl to serve in) under
|
||||
// the arrow, then what it makes, one under the other
|
||||
const { grid, extras } = mod_recipe_inputs(recipe, this.ctx.tags);
|
||||
grid.slice(0, 9).forEach((ingredient, i) =>
|
||||
cell(ingredient, x + (i % 3) * CELL, top + Math.floor(i / 3) * CELL)
|
||||
);
|
||||
texture("bworld:arrow_full", x + 3.5 * CELL, top + CELL / 2);
|
||||
extras.slice(0, 1).forEach((ingredient) =>
|
||||
cell(ingredient, x + 3.5 * CELL, top + CELL * 1.5, ["Served in"])
|
||||
);
|
||||
const made = outputs(recipe).slice(0, 3);
|
||||
made.forEach((output, i) =>
|
||||
cell(output, x + 5 * CELL, made.length > 1 ? top + i * CELL : top + CELL / 2)
|
||||
);
|
||||
if (typeof recipe.cook_time === "number") {
|
||||
g.text(seconds(recipe.cook_time), x + 5 * CELL, top + CELL * 1.5 + (CELL - g.text_height) / 2, {
|
||||
color: LABEL_COLOR,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
return hovered;
|
||||
}
|
||||
}
|
||||
|
||||
// a card's height: its label, its rows of items, and a gap
|
||||
function card_height(recipe: Recipe, tags: TagApi): number {
|
||||
let rows = 2;
|
||||
if (recipe.type === "shaped") rows = 3;
|
||||
else if (!(recipe.type in CATEGORY_NAMES)) {
|
||||
rows = Math.max(2, Math.ceil(mod_recipe_inputs(recipe, tags).grid.length / 3), outputs(recipe).length);
|
||||
}
|
||||
return LINE + Math.min(rows, 3) * CELL + GAP;
|
||||
}
|
||||
|
||||
// as many cards on each page as fit, at least one
|
||||
function paginate(recipes: Recipe[], height: number, tags: TagApi): Recipe[][] {
|
||||
const pages: Recipe[][] = [[]];
|
||||
let used = 0;
|
||||
for (const recipe of recipes) {
|
||||
const needed = card_height(recipe, tags);
|
||||
if (used + needed > height && pages.at(-1)!.length > 0) {
|
||||
pages.push([]);
|
||||
used = 0;
|
||||
}
|
||||
pages.at(-1)!.push(recipe);
|
||||
used += needed;
|
||||
}
|
||||
return pages;
|
||||
}
|
||||
|
||||
// what a recipe makes
|
||||
export function outputs(recipe: Recipe): Ingredient[] {
|
||||
switch (recipe.type) {
|
||||
case "shaped":
|
||||
return [stack(recipe.result)];
|
||||
case "furnace":
|
||||
return [stack(recipe.output)];
|
||||
case "fuel":
|
||||
return [];
|
||||
case "smithing":
|
||||
return [{ ids: [recipe.result], count: 1 }];
|
||||
default: {
|
||||
// one item or stack, or a list of them, like what a cutting board cuts something into
|
||||
const output = recipe.result ?? recipe.output;
|
||||
return [output].flat().flatMap((output): Ingredient[] => {
|
||||
if (typeof output === "string") return [{ ids: [output], count: 1 }];
|
||||
if (output && typeof output.id === "string") return [stack(output)];
|
||||
return [];
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// what a recipe takes. shaped keys, furnace 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":
|
||||
return Object.values(recipe.key as Record<string, string | string[]>).map((choice) => ({
|
||||
ids: tags.expand(choice),
|
||||
count: 1,
|
||||
}));
|
||||
case "furnace":
|
||||
return [{ ids: tags.expand(recipe.input), count: 1 }];
|
||||
case "fuel":
|
||||
return [{ ids: tags.expand(recipe.item), count: 1 }];
|
||||
case "smithing":
|
||||
return [{ ids: [recipe.tool], count: 1 }, stack(recipe.material)].concat(
|
||||
recipe.addition ? [{ ids: [recipe.addition], count: 1 }] : [],
|
||||
);
|
||||
default: {
|
||||
const { grid, extras } = mod_recipe_inputs(recipe, tags);
|
||||
return [...grid, ...extras];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the items in a mod recipe's fields besides its type and result: each item or #tag in a list is an ingredient (a list
|
||||
// in a list is one ingredient any of whose items fit), and a field that's one item is an extra, like a container
|
||||
function mod_recipe_inputs(recipe: Recipe, tags: TagApi): { grid: Ingredient[]; extras: Ingredient[] } {
|
||||
const grid: Ingredient[] = [];
|
||||
const extras: Ingredient[] = [];
|
||||
const ingredient = (choice: string | string[]) => ({ ids: tags.expand(choice), count: 1 });
|
||||
for (const [field, value] of Object.entries(recipe)) {
|
||||
if (field === "type" || field === "result" || field === "output") continue;
|
||||
if (is_id(value)) {
|
||||
extras.push(ingredient(value));
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
if (is_id(entry) || (Array.isArray(entry) && entry.every(is_id))) grid.push(ingredient(entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
return { grid, extras };
|
||||
}
|
||||
|
||||
// an item id or #tag
|
||||
function is_id(value: unknown): value is string {
|
||||
return typeof value === "string" && /^#?[a-z0-9_]+:[a-z0-9_/]+$/.test(value);
|
||||
}
|
||||
|
||||
function stack(value: { id: string; count: number }): Ingredient {
|
||||
return { ids: [value.id], count: value.count };
|
||||
}
|
||||
|
||||
// "Crafting", or a mod type's name: farmersdelight:cooking is "Cooking"
|
||||
export function category_name(type: string): string {
|
||||
if (CATEGORY_NAMES[type]) return CATEGORY_NAMES[type];
|
||||
const name = type.split(":")[1] ?? type;
|
||||
return name.split("_").map((word) => word[0].toUpperCase() + word.slice(1)).join(" ");
|
||||
}
|
||||
|
||||
function seconds(ticks: number): string {
|
||||
const s = ticks / 20;
|
||||
return `${Number.isInteger(s) ? s : s.toFixed(1)} s`;
|
||||
}
|
||||
|
||||
// by name or id, or "@mod" for a mod's items, like jei
|
||||
function matches_search(ctx: ClientContext, id: string, search: string): boolean {
|
||||
if (search === "") return true;
|
||||
return search.split(/\s+/).every((word) => {
|
||||
if (word.startsWith("@")) {
|
||||
const mod = word.slice(1);
|
||||
return id.split(":")[0].includes(mod) || ctx.items.mod(id).toLowerCase().includes(mod);
|
||||
}
|
||||
return ctx.items.name(id).toLowerCase().includes(word) || id.includes(word);
|
||||
// the item list on every menu's screen, right of it
|
||||
ctx.ui.add_inventory_overlay({
|
||||
on_render(g, screen) {
|
||||
const hovered = list.render(g, screen.x + screen.width, open) ?? screen.hovered_item?.id;
|
||||
if (hovered && g.key_pressed("KeyR")) open(hovered, "recipes");
|
||||
if (hovered && g.key_pressed("KeyU")) open(hovered, "uses");
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -0,0 +1,98 @@
|
||||
// every item, right of the inventory and of the recipes screen, like jei's ingredient list overlay: the page and its
|
||||
// arrows on top, the items, and the search box under them
|
||||
import type { ClientContext, Color, Graphics } from "bworld/client";
|
||||
import { SLOT } from "./categories.ts";
|
||||
|
||||
const GAP = 5;
|
||||
export const BUTTON = 13;
|
||||
// catppuccin mocha, like the engine's gui: crust, pink, subtext 0 and blue
|
||||
export const SLOT_COLOR: Color = [0.07, 0.07, 0.11, 0.6];
|
||||
const HOVER_COLOR: Color = [0.96, 0.76, 0.91, 0.35];
|
||||
export const LABEL_COLOR: Color = [0.65, 0.68, 0.78, 1];
|
||||
const MOD_COLOR: Color = [0.54, 0.71, 0.98, 1];
|
||||
|
||||
// show the recipes that make an item, or the ones that use it
|
||||
export type Mode = "recipes" | "uses";
|
||||
export type Open = (item: string, mode: Mode) => void;
|
||||
|
||||
// one item that can be hovered for its tooltip and clicked for its recipes (right click, its uses). true when hovered
|
||||
export function item_cell(
|
||||
g: Graphics,
|
||||
ctx: ClientContext,
|
||||
open: Open,
|
||||
id: string,
|
||||
x: number,
|
||||
y: number,
|
||||
options: { slot?: boolean; count?: number; tooltip?: string[] } = {},
|
||||
): boolean {
|
||||
if (options.slot) g.rect(x, y, SLOT, SLOT, SLOT_COLOR);
|
||||
g.item(id, x, y, options.count ?? 1);
|
||||
const { mouse } = g;
|
||||
if (mouse.x < x || mouse.y < y || mouse.x >= x + SLOT || mouse.y >= y + SLOT) return false;
|
||||
g.rect(x, y, SLOT, SLOT, HOVER_COLOR);
|
||||
g.item_tooltip(id, mouse.x, mouse.y, [
|
||||
...(options.tooltip ?? []),
|
||||
{ text: id, color: LABEL_COLOR },
|
||||
{ text: ctx.items.mod(id), color: MOD_COLOR },
|
||||
]);
|
||||
if (mouse.pressed) {
|
||||
g.consume_click();
|
||||
open(id, "recipes");
|
||||
} else if (mouse.right_pressed) {
|
||||
g.consume_click();
|
||||
open(id, "uses");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
export class ItemList {
|
||||
// kept between screens, like jei
|
||||
page = 0;
|
||||
// set on the first frame, once every mod's items are loaded
|
||||
#items: string[] | undefined;
|
||||
|
||||
constructor(private ctx: ClientContext) {}
|
||||
|
||||
// in the space from left to the window's right edge. returns the hovered item
|
||||
render(g: Graphics, left: number, open: Open): string | undefined {
|
||||
this.#items ??= this.ctx.items.ids().filter((id) => id !== "bworld:air");
|
||||
left += GAP;
|
||||
const columns = Math.floor((g.width - GAP - left) / SLOT);
|
||||
const top = GAP + BUTTON + 2;
|
||||
const rows = Math.floor((g.height - GAP - BUTTON - 2 - top) / SLOT);
|
||||
if (columns < 2 || rows < 1) return undefined;
|
||||
const width = columns * SLOT;
|
||||
|
||||
const search = g.text_input("search", left, g.height - GAP - BUTTON, width).trim().toLowerCase();
|
||||
const items = this.#items.filter((id) => matches_search(this.ctx, id, search));
|
||||
const per_page = columns * rows;
|
||||
const pages = Math.max(1, Math.ceil(items.length / per_page));
|
||||
this.page = Math.min(this.page, pages - 1);
|
||||
|
||||
if (g.button("<", left, GAP, BUTTON, BUTTON)) this.page = (this.page + pages - 1) % pages;
|
||||
if (g.button(">", left + width - BUTTON, GAP, BUTTON, BUTTON)) this.page = (this.page + 1) % pages;
|
||||
const label = `${this.page + 1}/${pages}`;
|
||||
g.text(label, left + (width - g.measure_text(label)) / 2, GAP + (BUTTON - g.text_height) / 2);
|
||||
|
||||
let hovered: string | undefined;
|
||||
items.slice(this.page * per_page, (this.page + 1) * per_page).forEach((id, i) => {
|
||||
const x = left + (i % columns) * SLOT;
|
||||
const y = top + Math.floor(i / columns) * SLOT;
|
||||
if (item_cell(g, this.ctx, open, id, x, y)) hovered = id;
|
||||
});
|
||||
if (items.length === 0) g.text("Nothing found", left, top, { color: [0.8, 0.8, 0.8, 1] });
|
||||
return hovered;
|
||||
}
|
||||
}
|
||||
|
||||
// by name or id, or "@mod" for a mod's items, like jei
|
||||
function matches_search(ctx: ClientContext, id: string, search: string): boolean {
|
||||
if (search === "") return true;
|
||||
return search.split(/\s+/).every((word) => {
|
||||
if (word.startsWith("@")) {
|
||||
const mod = word.slice(1);
|
||||
return id.split(":")[0].includes(mod) || ctx.items.mod(id).toLowerCase().includes(mod);
|
||||
}
|
||||
return ctx.items.name(id).toLowerCase().includes(word) || id.includes(word);
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// reading recipes: what each one makes and takes, for any mod's recipe type, so the viewer works with recipes it has
|
||||
// no category for
|
||||
import type { TagApi } from "bworld/client";
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Recipe = any;
|
||||
// one place in a recipe: the items any of which fit, and how many
|
||||
export type Ingredient = { ids: string[]; count: number };
|
||||
|
||||
// what a recipe makes
|
||||
export function outputs(recipe: Recipe): Ingredient[] {
|
||||
switch (recipe.type) {
|
||||
case "shaped":
|
||||
return [stack(recipe.result)];
|
||||
case "furnace":
|
||||
return [stack(recipe.output)];
|
||||
case "fuel":
|
||||
return [];
|
||||
case "smithing":
|
||||
return [{ ids: [recipe.result], count: 1 }];
|
||||
default: {
|
||||
// one item or stack, or a list of them, like what a cutting board cuts something into
|
||||
const output = recipe.result ?? recipe.output;
|
||||
return [output].flat().flatMap((output): Ingredient[] => {
|
||||
if (typeof output === "string") return [{ ids: [output], count: 1 }];
|
||||
if (output && typeof output.id === "string") return [stack(output)];
|
||||
return [];
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// what a recipe takes. shaped keys, furnace 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":
|
||||
return Object.values(recipe.key as Record<string, string | string[]>).map((choice) => ({
|
||||
ids: tags.expand(choice),
|
||||
count: 1,
|
||||
}));
|
||||
case "furnace":
|
||||
return [{ ids: tags.expand(recipe.input), count: 1 }];
|
||||
case "fuel":
|
||||
return [{ ids: tags.expand(recipe.item), count: 1 }];
|
||||
case "smithing":
|
||||
return [{ ids: [recipe.tool], count: 1 }, stack(recipe.material)].concat(
|
||||
recipe.addition ? [{ ids: [recipe.addition], count: 1 }] : [],
|
||||
);
|
||||
default: {
|
||||
const { grid, extras } = mod_recipe_inputs(recipe, tags);
|
||||
return [...grid, ...extras];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// the items in a mod recipe's fields besides its type and result: each item or #tag in a list is an ingredient (a list
|
||||
// in a list is one ingredient any of whose items fit), and a field that's one item is an extra, like a container
|
||||
export function mod_recipe_inputs(recipe: Recipe, tags: TagApi): { grid: Ingredient[]; extras: Ingredient[] } {
|
||||
const grid: Ingredient[] = [];
|
||||
const extras: Ingredient[] = [];
|
||||
const ingredient = (choice: string | string[]) => ({ ids: tags.expand(choice), count: 1 });
|
||||
for (const [field, value] of Object.entries(recipe)) {
|
||||
if (field === "type" || field === "result" || field === "output") continue;
|
||||
if (is_id(value)) {
|
||||
extras.push(ingredient(value));
|
||||
} else if (Array.isArray(value)) {
|
||||
for (const entry of value) {
|
||||
if (is_id(entry) || (Array.isArray(entry) && entry.every(is_id))) grid.push(ingredient(entry));
|
||||
}
|
||||
}
|
||||
}
|
||||
return { grid, extras };
|
||||
}
|
||||
|
||||
// an item id or #tag
|
||||
function is_id(value: unknown): value is string {
|
||||
return typeof value === "string" && /^#?[a-z0-9_]+:[a-z0-9_/]+$/.test(value);
|
||||
}
|
||||
|
||||
export function stack(value: { id: string; count: number }): Ingredient {
|
||||
return { ids: [value.id], count: value.count };
|
||||
}
|
||||
|
||||
export function seconds(ticks: number): string {
|
||||
const s = ticks / 20;
|
||||
return `${Number.isInteger(s) ? s : s.toFixed(1)} s`;
|
||||
}
|
||||
@@ -0,0 +1,211 @@
|
||||
// the recipes that make or use an item, a screen of its own like jei's RecipesGui: a tab for each category above the
|
||||
// panel, where the category is made down its left side, the category and page with their arrows at the top, then as
|
||||
// many recipes as fit, one under the other. the item list stays on the right. escape or the inventory key go back to
|
||||
// the inventory, and backspace to what was shown before
|
||||
import type { ClientContext, Graphics, Screen } from "bworld/client";
|
||||
import { make_categories, type RecipeCategory, type RecipeLayout, SLOT } from "./categories.ts";
|
||||
import { BUTTON, item_cell, ItemList, LABEL_COLOR, type Mode, SLOT_COLOR } from "./item_list.ts";
|
||||
import { type Ingredient, inputs, outputs, type Recipe } from "./recipes.ts";
|
||||
|
||||
// jei's sizes, in gui pixels
|
||||
const WIDTH = 198;
|
||||
const MAX_HEIGHT = 350;
|
||||
const BORDER = 6;
|
||||
const NAV_PADDING = 2;
|
||||
const TAB = 24;
|
||||
const TAB_OVERLAP = 3;
|
||||
const TAB_INSET = 2;
|
||||
const CATALYST_BORDER = 5;
|
||||
// how far the catalysts' panel goes under the recipes'
|
||||
const CATALYST_OVERLAP = 4;
|
||||
const RECIPE_SPACING = 8;
|
||||
// alternatives, like "any vegetable", take turns this often
|
||||
const CYCLE_MS = 1000;
|
||||
const UNSELECTED_TAB: [number, number, number, number] = [0, 0, 0, 0.35];
|
||||
|
||||
// every category and its recipes, read once every mod's are loaded, on the first lookup
|
||||
export class RecipeIndex {
|
||||
#categories: RecipeCategory[] | undefined;
|
||||
#recipes: Recipe[] = [];
|
||||
|
||||
constructor(private ctx: ClientContext) {}
|
||||
|
||||
get categories(): RecipeCategory[] {
|
||||
if (!this.#categories) {
|
||||
this.#recipes = this.ctx.recipes.list();
|
||||
this.#categories = make_categories(this.ctx, this.#recipes);
|
||||
}
|
||||
return this.#categories;
|
||||
}
|
||||
|
||||
// each category with recipes that make the item, or use it. like jei, the uses of where a category is made, like
|
||||
// a furnace, are all of that category's recipes
|
||||
find(item: string, mode: Mode): { category: RecipeCategory; recipes: Recipe[] }[] {
|
||||
return this.categories.flatMap((category) => {
|
||||
const of_type = this.#recipes.filter((recipe) => recipe.type === category.type);
|
||||
const recipes = mode === "recipes"
|
||||
? of_type.filter((recipe) => outputs(recipe).some((output) => output.ids.includes(item)))
|
||||
: category.catalysts.includes(item)
|
||||
? of_type
|
||||
: of_type.filter((recipe) => inputs(recipe, this.ctx.tags).some((input) => input.ids.includes(item)));
|
||||
return recipes.length > 0 ? [{ category, recipes }] : [];
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface View {
|
||||
item: string;
|
||||
mode: Mode;
|
||||
// which of find's categories, and which page of it
|
||||
category: number;
|
||||
page: number;
|
||||
}
|
||||
|
||||
export class RecipesScreen implements Screen {
|
||||
#view: View;
|
||||
#history: View[] = [];
|
||||
|
||||
constructor(
|
||||
private ctx: ClientContext,
|
||||
private index: RecipeIndex,
|
||||
private list: ItemList,
|
||||
item: string,
|
||||
mode: Mode,
|
||||
) {
|
||||
this.#view = { item, mode, category: 0, page: 0 };
|
||||
}
|
||||
|
||||
on_render(g: Graphics) {
|
||||
// over the world, like every screen
|
||||
g.rect(0, 0, g.width, g.height, [0, 0, 0, 0.8]);
|
||||
const results = this.index.find(this.#view.item, this.#view.mode);
|
||||
if (results.length === 0) return;
|
||||
const view = this.#view;
|
||||
view.category = Math.min(view.category, results.length - 1);
|
||||
const { category, recipes } = results[view.category];
|
||||
|
||||
const left = Math.floor((g.width - WIDTH) / 2);
|
||||
const top = TAB - TAB_OVERLAP + BORDER;
|
||||
const height = Math.min(MAX_HEIGHT, g.height - top - BORDER);
|
||||
const header_rows = BORDER + BUTTON * 2 + NAV_PADDING;
|
||||
const recipes_top = top + header_rows + BORDER;
|
||||
|
||||
// the panels: tabs and where it's made go under the recipes' panel's edges
|
||||
const tabs = this.#tabs(g, results, left, top);
|
||||
let hovered: string | undefined;
|
||||
const catalysts = category.catalysts;
|
||||
if (catalysts.length > 0) {
|
||||
const width = CATALYST_BORDER * 2 + SLOT;
|
||||
const x = left - width + CATALYST_OVERLAP;
|
||||
g.panel(x, recipes_top, width, catalysts.length * SLOT + CATALYST_BORDER * 2);
|
||||
g.panel(left, top, WIDTH, height);
|
||||
catalysts.forEach((id, i) => {
|
||||
const y = recipes_top + CATALYST_BORDER + i * SLOT;
|
||||
if (this.#cell(g, id, x + CATALYST_BORDER, y, { slot: true })) hovered = id;
|
||||
});
|
||||
} else {
|
||||
g.panel(left, top, WIDTH, height);
|
||||
}
|
||||
tabs.draw_icons();
|
||||
|
||||
// the category and the page, each between its arrows
|
||||
const row = (y: number, label: string, count: number, current: number, set: (index: number) => void) => {
|
||||
if (g.button("<", left + BORDER, y, BUTTON, BUTTON)) set((current + count - 1) % count);
|
||||
if (g.button(">", left + WIDTH - BORDER - BUTTON, y, BUTTON, BUTTON)) set((current + 1) % count);
|
||||
g.text(label, left + (WIDTH - g.measure_text(label)) / 2, y + (BUTTON - g.text_height) / 2);
|
||||
};
|
||||
row(top + BORDER, category.title, results.length, view.category, (i) => {
|
||||
view.category = i;
|
||||
view.page = 0;
|
||||
});
|
||||
const per_page = Math.max(
|
||||
1,
|
||||
Math.floor((top + height - BORDER - recipes_top + RECIPE_SPACING) / (category.height + RECIPE_SPACING)),
|
||||
);
|
||||
const pages = Math.ceil(recipes.length / per_page);
|
||||
view.page = Math.min(view.page, pages - 1);
|
||||
row(top + BORDER + BUTTON + NAV_PADDING, `${view.page + 1}/${pages}`, pages, view.page, (i) => view.page = i);
|
||||
|
||||
// the page's recipes, in the middle
|
||||
const x = left + Math.floor((WIDTH - category.width) / 2);
|
||||
recipes.slice(view.page * per_page, (view.page + 1) * per_page).forEach((recipe, i) => {
|
||||
const y = recipes_top + i * (category.height + RECIPE_SPACING);
|
||||
hovered = this.#draw_recipe(g, category, recipe, x, y) ?? hovered;
|
||||
});
|
||||
|
||||
hovered = this.list.render(g, left + WIDTH, (item, mode) => this.#open(item, mode)) ?? hovered;
|
||||
if (hovered && g.key_pressed("KeyR")) this.#open(hovered, "recipes");
|
||||
if (hovered && g.key_pressed("KeyU")) this.#open(hovered, "uses");
|
||||
if (g.key_pressed("Backspace")) this.#view = this.#history.pop() ?? this.#view;
|
||||
// back to the inventory, like jei's recipes screen
|
||||
if (g.key_pressed(this.ctx.options.key_inventory)) this.ctx.ui.close();
|
||||
}
|
||||
|
||||
// shows the recipes for or with another item, coming back to this one with backspace. nothing happens when there
|
||||
// aren't any
|
||||
#open(item: string, mode: Mode) {
|
||||
if (this.index.find(item, mode).length === 0) return;
|
||||
this.#history.push(this.#view);
|
||||
this.#view = { item, mode, category: 0, page: 0 };
|
||||
}
|
||||
|
||||
// a tab per category, as many as fit around the selected one, each showing where it's made or what it makes. the
|
||||
// panels are drawn now, under the recipes' panel, and their icons after it
|
||||
#tabs(g: Graphics, results: { category: RecipeCategory; recipes: Recipe[] }[], left: number, top: number) {
|
||||
const view = this.#view;
|
||||
const fit = Math.floor((WIDTH - TAB_INSET * 2) / TAB);
|
||||
const first = Math.max(0, Math.min(view.category - Math.floor(fit / 2), results.length - fit));
|
||||
const shown = results.slice(first, first + fit).map(({ category, recipes }, i) => ({
|
||||
category,
|
||||
// where it's made, or what its first recipe makes
|
||||
icon: category.catalysts[0] ?? outputs(recipes[0])[0]?.ids[0],
|
||||
index: first + i,
|
||||
x: left + TAB_INSET + i * TAB,
|
||||
y: top - TAB + TAB_OVERLAP,
|
||||
}));
|
||||
for (const { index, x, y } of shown) {
|
||||
g.panel(x, y, TAB, TAB);
|
||||
if (index !== view.category) g.rect(x, y, TAB, TAB, UNSELECTED_TAB);
|
||||
}
|
||||
return {
|
||||
draw_icons: () => {
|
||||
const { mouse } = g;
|
||||
for (const { category, icon, index, x, y } of shown) {
|
||||
if (icon) g.item(icon, x + (TAB - SLOT) / 2, y + (TAB - SLOT) / 2 - 1);
|
||||
if (mouse.x < x || mouse.y < y || mouse.x >= x + TAB || mouse.y >= y + TAB - TAB_OVERLAP) continue;
|
||||
g.tooltip([category.title], mouse.x, mouse.y);
|
||||
if (mouse.pressed) {
|
||||
g.consume_click();
|
||||
view.category = index;
|
||||
view.page = 0;
|
||||
}
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// one recipe, its category drawing it with its top left at x, y. returns the hovered item
|
||||
#draw_recipe(g: Graphics, category: RecipeCategory, recipe: Recipe, x: number, y: number): string | undefined {
|
||||
let hovered: string | undefined;
|
||||
const layout: RecipeLayout = {
|
||||
slot: (ingredient: Ingredient | undefined, dx, dy, tooltip = []) => {
|
||||
if (!ingredient || ingredient.ids.length === 0) {
|
||||
g.rect(x + dx, y + dy, SLOT, SLOT, SLOT_COLOR);
|
||||
return;
|
||||
}
|
||||
const id = ingredient.ids[Math.floor(Date.now() / CYCLE_MS) % ingredient.ids.length];
|
||||
const any = ingredient.ids.length > 1 ? [`Any of ${ingredient.ids.length}`] : [];
|
||||
const options = { slot: true, count: ingredient.count, tooltip: [...any, ...tooltip] };
|
||||
if (this.#cell(g, id, x + dx, y + dy, options)) hovered = id;
|
||||
},
|
||||
texture: (id, dx, dy, w, h) => g.texture(id, x + dx, y + dy, w, h),
|
||||
text: (text, dx, dy) => g.text(text, x + dx, y + dy, { color: LABEL_COLOR }),
|
||||
};
|
||||
category.draw(recipe, layout);
|
||||
return hovered;
|
||||
}
|
||||
|
||||
#cell(g: Graphics, id: string, x: number, y: number, options: Parameters<typeof item_cell>[6]) {
|
||||
return item_cell(g, this.ctx, (item, mode) => this.#open(item, mode), id, x, y, options);
|
||||
}
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
// the recipe viewer mod reads every mod's recipes, its own types included
|
||||
import { assert, assertEquals } from "@std/assert";
|
||||
import { category_name, inputs as recipe_inputs, outputs } from "../mods/recipe_viewer/scripts/client.ts";
|
||||
import { category_name } from "../mods/recipe_viewer/scripts/categories.ts";
|
||||
import { inputs as recipe_inputs, outputs } from "../mods/recipe_viewer/scripts/recipes.ts";
|
||||
import { RecipeIndex } from "../mods/recipe_viewer/scripts/recipes_screen.ts";
|
||||
import { tag_api } from "$/common/tags.ts";
|
||||
import { EverythingRegistry } from "$/common/everything_registry.ts";
|
||||
import type { ClientContext } from "bworld/client";
|
||||
import { test_game } from "./helpers.ts";
|
||||
|
||||
const ids = (ingredients: { ids: string[] }[]) => ingredients.map((i) => i.ids.join("|"));
|
||||
@@ -42,3 +46,26 @@ Deno.test("the recipe viewer finds what makes and uses an item, in any recipe ty
|
||||
assertEquals(ids(inputs(making("bworld:stone_pickaxe")[0])), ["bworld:wood_pickaxe", "bworld:stone"]);
|
||||
assertEquals(category_name("smithing"), "Smithing");
|
||||
});
|
||||
|
||||
Deno.test("recipes are found by category in jei's order, and a catalyst's uses are everything made in it", async () => {
|
||||
const { game } = await test_game("mods");
|
||||
const ctx = {
|
||||
recipes: { list: () => game.recipes.all },
|
||||
tags: tag_api(),
|
||||
items: { exists: (id: string) => EverythingRegistry.get("items", id) !== undefined },
|
||||
} as unknown as ClientContext;
|
||||
const index = new RecipeIndex(ctx);
|
||||
|
||||
const titles = index.categories.map((category) => category.title);
|
||||
assertEquals(titles.slice(0, 4), ["Crafting", "Smelting", "Fuel", "Smithing"]);
|
||||
assert(titles.includes("Cooking"));
|
||||
assertEquals(index.categories.find((c) => c.type === "farmersdelight:cooking")?.catalysts, [
|
||||
"farmersdelight:cooking_pot",
|
||||
]);
|
||||
|
||||
const furnace_uses = index.find("bworld:furnace", "uses").map(({ 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(index.find("bworld:air", "recipes"), []);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user