diff --git a/MODS.md b/MODS.md index 565df6b..291def3 100644 --- a/MODS.md +++ b/MODS.md @@ -905,11 +905,37 @@ interface ClientContext { net: ClientNet; // see Mod channels player: { readonly name: string; readonly position: { x: number; y: number; z: number } }; world: { get_block(x: number, y: number, z: number): string | undefined }; // read only, what the client sees + // every item any mod registered, in load order: ids(), exists(id), name(id) ("Cooked Rice"), mod(id) (its mod's name) + items: ClientItems; + // every recipe as its json, including mods' own types, in load order + recipes: { list(type?: string): RecipeJson[] }; log(...args: unknown[]): void; } ``` -Only `ctx.player`, `ctx.world` and `ctx.log` work so far, the rest is phase 4. +`ctx.player`, `ctx.world`, `ctx.items`, `ctx.recipes`, `ctx.log` and `ctx.ui.add_inventory_overlay` work so far, the rest +is phase 4. + +### Inventory overlays + +`ctx.ui.add_inventory_overlay` draws on every inventory screen (the player's inventory, chests, furnaces and other +container screens) with [`Graphics`](#3-custom-screens-client-code), over the screen, like Just Enough Items' item list. +`mods/recipe_viewer` is one. + +```ts +ctx.ui.add_inventory_overlay({ + on_render(g, screen) { + // screen is the inventory's box, and what's in the slot under the mouse + const x = screen.x + screen.width + 16; + g.text(screen.hovered_item ? ctx.items.name(screen.hovered_item.id) : "", x, 16); + }, +}); +``` + +Overlays get the mouse before the slots. A click they use (`g.button`, or `g.consume_click()`) doesn't reach the slots, +and `g.block_mouse(x, y, w, h)` keeps the slots from taking the mouse under something drawn over them. While a +`g.text_input` has the keyboard, keybinds like the inventory key don't fire. An overlay that throws is removed, with the +error in the console. Client scripts are for presentation. They can't change the world or inventories; they ask the server over a [mod channel](#mod-channels). Anything they show should be treated as a view of the server's state. Everything in a @@ -1102,7 +1128,7 @@ interface ModScreen { interface Graphics { readonly width: number; readonly height: number; - readonly mouse: { x: number; y: number; down: boolean; pressed: boolean }; + readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean }; rect(x: number, y: number, w: number, h: number, color?: [number, number, number, number]): void; panel(x: number, y: number, w: number, h: number): void; // nine slice background text(text: string, x: number, y: number, options?: { scale?: number; color?: number[] }): void; @@ -1115,10 +1141,16 @@ interface Graphics { slider(id: string, x: number, y: number, w: number, min: number, max: number): number; // server synced slots, same behavior as container screens slots(container: string, layout: { slot: number; x: number; y: number }[], x: number, y: number): void; - key_pressed(key: KeyCode): boolean; + key_pressed(key: KeyCode): boolean; // false while a text input has the keyboard + tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number): void; // over everything + item_tooltip(id: string, x: number, y: number, extra?: (string | { text: string; color?: Color })[]): void; + consume_click(): void; // nothing under it gets the click + block_mouse(x: number, y: number, w: number, h: number): void; // the screen underneath ignores the mouse there } ``` +Everything but `slider` and `slots` works, for [inventory overlays](#inventory-overlays). + Custom screens can also show server containers. The server passes them in when opening: `ctx.ui.open_screen(player, id, props, { containers: { input: container } })`, and the screen draws them with `g.slots("input", layout, x, y)`. Clicks still go to the server and follow the container rules, so a custom screen can't diff --git a/client/client.ts b/client/client.ts index bec063b..7353989 100644 --- a/client/client.ts +++ b/client/client.ts @@ -150,7 +150,8 @@ export class Client { #handle_keybinds(closed_screen: boolean) { const player = this.player; - if (!closed_screen) { + // typing into a screen's text field, keys are letters, not keybinds + if (!closed_screen && !this.screen?.typing) { this.#handle_keys(); } diff --git a/client/gui/gui_screen.ts b/client/gui/gui_screen.ts index 412d414..4ca1028 100644 --- a/client/gui/gui_screen.ts +++ b/client/gui/gui_screen.ts @@ -8,6 +8,8 @@ import { ClientInventories } from "../inventory.ts"; import { canvas, Texture } from "../renderer/mod.ts"; import { draw_item, draw_nine_slice } from "../rendering/render_utils.ts"; import { draw_tooltip, item_tooltip } from "./tooltip.ts"; +import { ModGraphics } from "./mod_graphics.ts"; +import { inventory_overlays } from "../mods.ts"; export class Slot { container: ContainerKey; @@ -34,6 +36,11 @@ export abstract class GuiScreen { abstract on_tick(_delta: number): void; abstract on_render(): void; abstract on_close(): void; + + // something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire + get typing(): boolean { + return false; + } } // a screen of slots. the server owns the contents: clicks are sent to it and guessed locally @@ -46,6 +53,8 @@ export class GuiInventoryScreen extends GuiScreen { hovering: Slot | undefined; inventory_width: number = 500; inventory_height: number = 500; + // what mods draw over it, like a recipe viewer + graphics = new ModGraphics(); constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) { super(); @@ -64,11 +73,13 @@ export class GuiInventoryScreen extends GuiScreen { } } + override get typing() { + return this.graphics.typing; + } + on_tick(_delta: number): void { this.x = canvas.width / 2 - (this.inventory_width / 2); this.y = canvas.height / 2 - (this.inventory_height / 2); - - this.handle_interaction(); } on_render(): void { @@ -100,6 +111,14 @@ export class GuiInventoryScreen extends GuiScreen { } } + // mods' overlays go on top and get the mouse first, then the slots get what they left + this.#render_overlays(); + if (this.graphics.mouse_blocked()) { + this.hovering = undefined; + } else { + this.handle_interaction(); + } + const mouse = InputManager.get_mouse_position(); if (this.inventories.cursor.item) { draw_item(this.inventories.cursor.item, mouse.x, mouse.y); @@ -110,6 +129,29 @@ export class GuiInventoryScreen extends GuiScreen { draw_tooltip(item_tooltip(item), mouse.x, mouse.y); } } + this.graphics.end(); + } + + #render_overlays() { + const g = this.graphics; + g.begin(); + const hovered = this.hovering && this.get_container(this.hovering.container)?.get_item(this.hovering.index); + const view = { + x: this.x, + y: this.y, + width: this.inventory_width, + height: this.inventory_height, + hovered_item: hovered ? { id: hovered.type_id, count: hovered.amount, data: hovered.data } : undefined, + }; + for (const entry of [...inventory_overlays]) { + try { + entry.overlay.on_render(g, view); + } catch (e) { + // a broken overlay is taken off, not left to throw every frame + console.error(`[${entry.mod}] inventory overlay threw, removing it:`, e); + inventory_overlays.splice(inventory_overlays.indexOf(entry), 1); + } + } } on_close(): void { diff --git a/client/gui/mod_graphics.ts b/client/gui/mod_graphics.ts new file mode 100644 index 0000000..c1719b5 --- /dev/null +++ b/client/gui/mod_graphics.ts @@ -0,0 +1,224 @@ +// the immediate mode drawing mods' client scripts get (Graphics in common/mod_api/client.ts), on top of the renderer. +// one per screen, so text inputs keep their text and focus while it's open +import { SLOT_SIZE, TEXTURE_SIZE } from "$/common/constants.ts"; +import { EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; +import { ItemStack } from "$/common/inventory.ts"; +import type { Color, Graphics } from "$/common/mod_api/client.ts"; +import type { KeyCode } from "$/common/mod_api/shared.ts"; +import { point_inside_rec } from "$/common/utils.ts"; +import { AssetManager } from "$/client/assets.ts"; +import { InputManager, type KeyCode as InputKey } from "$/client/input_manager.ts"; +import { + begin_clip, + canvas, + draw_rect, + draw_text, + draw_texture_region, + end_clip, + measure_text, + Texture, +} from "$/client/renderer/mod.ts"; +import { draw_item, draw_nine_slice } from "$/client/rendering/render_utils.ts"; +import { get_sprite_region } from "$/client/sprites.ts"; +import { draw_tooltip, item_tooltip, type TooltipLine } from "./tooltip.ts"; +import { TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts"; + +const WHITE: Color = [1, 1, 1, 1]; +const GREY: Color = [0.66, 0.66, 0.66, 1]; +const INPUT_HEIGHT = 32; + +export class ModGraphics implements Graphics { + // text inputs by id, and which one has the keyboard + #inputs = new Map(); + #focused: string | undefined; + #tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined; + // areas the screen underneath shouldn't take the mouse in, this frame + #blocked: { x: number; y: number; w: number; h: number }[] = []; + #clicks_consumed = false; + + get width() { + return canvas.width; + } + + get height() { + return canvas.height; + } + + get mouse() { + const { x, y } = InputManager.get_mouse_position(); + return { + x, + y, + down: InputManager.is_mouse_down(0), + pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(0), + right_pressed: !this.#clicks_consumed && InputManager.is_mouse_pressed(2), + }; + } + + // a text input has the keyboard, so keybinds like the inventory key shouldn't fire + get typing() { + return this.#focused !== undefined; + } + + // call before a frame's drawing + begin() { + this.#tooltip = undefined; + this.#blocked = []; + this.#clicks_consumed = false; + } + + // call after, draws the tooltip over everything + end() { + if (this.#tooltip) draw_tooltip(this.#tooltip.lines, this.#tooltip.x, this.#tooltip.y); + } + + // whether the screen underneath should ignore the mouse + mouse_blocked() { + const { x, y } = this.mouse; + return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h)); + } + + rect(x: number, y: number, w: number, h: number, color: Color = WHITE) { + draw_rect(x, y, w, h, color); + } + + panel(x: number, y: number, w: number, h: number) { + draw_nine_slice(AssetManager.instance.get("bworld:ui"), 160, 0, 16, 16, 4, 4, 4, 4, x, y, w, h); + } + + text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) { + draw_text(text, x, y, options.scale ?? TEXT_SCALE, options.color ?? WHITE); + } + + measure_text(text: string, scale = TEXT_SCALE) { + return measure_text(text, scale); + } + + texture(id: string, x: number, y: number, w: number, h: number) { + const atlas = AssetManager.instance.get("bworld:textures"); + const region = get_sprite_region(id); + draw_texture_region( + atlas, + region.x * TEXTURE_SIZE, + region.y * TEXTURE_SIZE, + TEXTURE_SIZE, + TEXTURE_SIZE, + x, + y, + w, + h, + ); + } + + item(id: string, x: number, y: number, count = 1) { + if (!EverythingRegistry.get("items", id)) throw new Error(`unknown item ${id}`); + const stack = new ItemStack(id, count); + // the count only shows when it's more than one + if (count === 1) stack.max_amount = 1; + draw_item(stack, x, y); + } + + clip(x: number, y: number, w: number, h: number, draw: () => void) { + begin_clip(x, y, w, h); + try { + draw(); + } finally { + end_clip(); + } + } + + button(label: string, x: number, y: number, w: number, h: number): boolean { + const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, h); + const [sx, sy] = hovered ? [224, 16] : [176, 0]; + draw_nine_slice(AssetManager.instance.get("bworld:ui"), sx, sy, 16, 16, 4, 4, 4, 4, x, y, w, h); + const text_width = measure_text(label, TEXT_SCALE); + draw_text(label, x + (w - text_width) / 2, y + (h - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE); + if (hovered && this.mouse.pressed) { + this.consume_click(); + return true; + } + return false; + } + + text_input(id: string, x: number, y: number, w: number): string { + let input = this.#inputs.get(id); + if (!input) { + input = new TextInput("", 256); + this.#inputs.set(id, input); + } + const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT); + if (this.mouse.pressed) { + if (hovered) { + this.#focused = id; + this.consume_click(); + } else if (this.#focused === id) { + this.#focused = undefined; + } + } + const focused = this.#focused === id; + if (focused) { + // what was typed this frame goes in before enter or escape lets go of the keyboard + input.handle_keys(); + if (InputManager.is_key_pressed("Escape") || InputManager.is_key_pressed("Enter")) { + this.#focused = undefined; + } + } + + draw_rect(x, y, w, INPUT_HEIGHT, focused ? WHITE : GREY); + draw_rect(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, [0, 0, 0, 1]); + this.clip(x + 2, y + 2, w - 4, INPUT_HEIGHT - 4, () => { + draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE); + if (focused && TextInput.caret_visible()) { + draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE); + } + }); + return input.value; + } + + slider(): number { + throw new Error("g.slider isn't implemented yet"); + } + + slots(): void { + throw new Error("g.slots isn't implemented yet"); + } + + key_pressed(key: KeyCode): boolean { + return !this.typing && InputManager.is_key_pressed(key as InputKey); + } + + tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number) { + this.#tooltip = { + lines: lines.map((line) => + typeof line === "string" + ? { text: line, color: WHITE } + : { text: line.text, color: line.color ?? WHITE } + ), + x, + y, + }; + } + + item_tooltip(id: string, x: number, y: number, extra: (string | { text: string; color?: Color })[] = []) { + const lines = [ + ...item_tooltip(new ItemStack(id, 1)), + ...extra.map((line) => + typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY } + ), + ]; + this.#tooltip = { lines, x, y }; + } + + block_mouse(x: number, y: number, w: number, h: number) { + this.#blocked.push({ x, y, w, h }); + } + + consume_click() { + this.#clicks_consumed = true; + InputManager.consume_mouse(0); + InputManager.consume_mouse(2); + } +} + +// how big an item is drawn, for laying out around g.item +export const ITEM_SIZE = SLOT_SIZE; diff --git a/client/mods.ts b/client/mods.ts index 4fdaf2c..65a06e9 100644 --- a/client/mods.ts +++ b/client/mods.ts @@ -1,11 +1,12 @@ // loads the mods the server lists: downloads their .bmod files, registers their data, then runs their client scripts. // see "Delivery to clients" in MODS.md import { AIR } from "$/common/constants.ts"; -import { BlockRegistry, EverythingRegistry } from "$/common/everything_registry.ts"; -import type { ClientContext } from "$/common/mod_api/client.ts"; -import { ModListing, ModLoadError, register_mod_data } from "$/common/mod_loader.ts"; +import { BlockRegistry, EverythingRegistry, type ItemRegistry } from "$/common/everything_registry.ts"; +import type { ClientContext, InventoryOverlay } 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 type { OreJson } from "$/common/mod_data.ts"; +import { display_name } from "$/common/utils.ts"; import { AIR_ID } from "$/common/protocol.ts"; import type { Client } from "./client.ts"; import { code_url, fetch_verified } from "./handshake.ts"; @@ -19,6 +20,13 @@ export const worldgen_mods: { scripts: { mod: string; url: string }[]; ores: Ore // set once the game is running, mods can't look at it during setup let client: Client | undefined; +// what mods draw on inventory screens, see GuiInventoryScreen +export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = []; + +// the loaded mods' recipes, and their names by id +let recipe_book = new RecipeBook(); +const mod_names = new Map(); + export function set_mods_client(game_client: Client) { client = game_client; } @@ -47,6 +55,10 @@ export async function load_client_mods(listings: ModListing[], bmods: Bmod[]) { } const recipes = register_mod_data(bmods.map((bmod) => ({ id: bmod.manifest.id, data: bmod.data }))); + recipe_book = recipes; + inventory_overlays.length = 0; + mod_names.clear(); + for (const listing of listings) mod_names.set(listing.id, listing.name); worldgen_mods.ores = recipes.ores; worldgen_mods.scripts = bmods.flatMap((bmod) => @@ -80,9 +92,24 @@ function client_context(listing: ModListing): ClientContext { return client; }; + const not_yet_fn = (name: string) => () => { + throw new Error(`[${mod}] ctx.ui.${name} isn't implemented yet (Custom screens in MODS.md)`); + }; + const known_item = (id: string) => { + const item = EverythingRegistry.get("items", id); + if (!item) throw new Error(`[${mod}] unknown item ${id}`); + return item; + }; + return { mod: { id: mod, version: listing.version }, - ui: not_yet("ui", "step 7") as ClientContext["ui"], + ui: { + register_screen: not_yet_fn("register_screen"), + open: not_yet_fn("open"), + add_inventory_overlay(overlay) { + inventory_overlays.push({ mod, overlay }); + }, + }, hud: not_yet("hud", "step 7") as ClientContext["hud"], input: not_yet("input", "step 8") as ClientContext["input"], net: not_yet("net", "step 8") as ClientContext["net"], @@ -105,6 +132,20 @@ function client_context(listing: ModListing): ClientContext { return need_client().level.time; }, }, + items: { + ids: () => EverythingRegistry.entries("items").map(([id]) => id), + exists: (id) => EverythingRegistry.get("items", id) !== undefined, + name: (id) => (known_item(id), display_name(id)), + mod(id) { + known_item(id); + const namespace = id.split(":")[0]; + return mod_names.get(namespace) ?? namespace; + }, + }, + recipes: { + list: (type) => + structuredClone(type ? recipe_book.all.filter((recipe) => recipe.type === type) : recipe_book.all), + }, log: (...args) => console.log(`[${mod}]`, ...args), }; } diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 141aefd..b61247f 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -1,5 +1,5 @@ // what client scripts get, see "Client scripts" and "GUIs" in MODS.md -import type { Id, KeyCode, ModInfo, Position } from "./shared.ts"; +import type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts"; export type { Id, ItemStack, KeyCode, ModInfo, Position } from "./shared.ts"; @@ -16,6 +16,20 @@ export interface ClientContext { // ticks since 06:00 of day 1, see ServerWorld.time readonly time: number; }; + // every item any mod registered, in load order + items: { + ids(): Id[]; + exists(id: Id): boolean; + // what players see, like "Cooked Rice" + name(id: Id): string; + // the mod that registered it + mod(id: Id): string; + }; + // every recipe as its json (see Recipes in MODS.md), including mods' own types, in load order. copies + recipes: { + // deno-lint-ignore no-explicit-any + list(type?: Id): any[]; + }; log(...args: unknown[]): void; } @@ -36,7 +50,7 @@ export type Color = [number, number, number, number]; export interface Graphics { readonly width: number; readonly height: number; - readonly mouse: { x: number; y: number; down: boolean; pressed: boolean }; + readonly mouse: { x: number; y: number; down: boolean; pressed: boolean; right_pressed: boolean }; rect(x: number, y: number, w: number, h: number, color?: Color): void; panel(x: number, y: number, w: number, h: number): void; text(text: string, x: number, y: number, options?: { scale?: number; color?: Color }): void; @@ -49,13 +63,38 @@ export interface Graphics { slider(id: string, x: number, y: number, w: number, min: number, max: number): number; // server synced slots, same rules as container screens slots(container: string, layout: { slot: number; x: number; y: number }[], x: number, y: number): void; + // false while a text input has the keyboard key_pressed(key: KeyCode): boolean; + // shown next to the mouse over everything else, the last one this frame wins + tooltip(lines: (string | { text: string; color?: Color })[], x: number, y: number): void; + // the game's tooltip for an item (its name, food, lore), with extra lines under it + item_tooltip(id: Id, x: number, y: number, extra?: (string | { text: string; color?: Color })[]): void; + // the click was used, so nothing under it (like slots) gets it + consume_click(): void; + // the screen underneath ignores the mouse over this area this frame, for something drawn over it + block_mouse(x: number, y: number, w: number, h: number): void; +} + +// drawn on every inventory screen (the player's inventory, chests, furnaces...), over it, like just enough items' +// item list. it gets the screen's box to lay itself out around +export interface InventoryOverlay { + on_render(g: Graphics, screen: InventoryScreenView): void; +} + +export interface InventoryScreenView { + readonly x: number; + readonly y: number; + readonly width: number; + readonly height: number; + // what's in the slot under the mouse + readonly hovered_item: ItemStack | undefined; } export interface ClientUi { register_screen(id: Id, create: (props: Props) => ModScreen): void; // open a screen that doesn't involve the server, like a settings page open(id: Id, props: Props): void; + add_inventory_overlay(overlay: InventoryOverlay): void; } export interface HudRegistry { diff --git a/common/mod_loader.ts b/common/mod_loader.ts index 2d43362..9bc8b2e 100644 --- a/common/mod_loader.ts +++ b/common/mod_loader.ts @@ -44,6 +44,8 @@ export class RecipeBook { smithing: Extract[] = []; // recipes of mods' own types, by type by_type = new Map(); + // every recipe as its json, in load order, for recipe viewers + all: RecipeJson[] = []; ores: OreJson[] = []; } @@ -81,6 +83,7 @@ export function register_mod_data(mods: { id: string; data: ModData }[]): Recipe } for (const recipe of data.recipes) { + recipes.all.push(recipe); if (is_mod_recipe(recipe)) { const list = recipes.by_type.get(recipe.type) ?? []; recipes.by_type.set(recipe.type, list); diff --git a/mods/recipe_viewer/README.md b/mods/recipe_viewer/README.md new file mode 100644 index 0000000..1b207bb --- /dev/null +++ b/mods/recipe_viewer/README.md @@ -0,0 +1,13 @@ +# 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`). + +- 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. + +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. diff --git a/mods/recipe_viewer/manifest.json b/mods/recipe_viewer/manifest.json new file mode 100644 index 0000000..0ef1e7e --- /dev/null +++ b/mods/recipe_viewer/manifest.json @@ -0,0 +1,14 @@ +{ + "format_version": 1, + "id": "recipe_viewer", + "name": "Recipe Viewer", + "description": "Every item next to the inventory, searchable, with the recipes that make and use it. Like Just Enough Items.", + "version": "0.1.0", + "authors": [ + "paula" + ], + "game_version": ">=0.1.0", + "scripts": { + "client": "scripts/client.ts" + } +} diff --git a/mods/recipe_viewer/scripts/client.ts b/mods/recipe_viewer/scripts/client.ts new file mode 100644 index 0000000..79421c6 --- /dev/null +++ b/mods/recipe_viewer/scripts/client.ts @@ -0,0 +1,385 @@ +// 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 } from "bworld/client"; + +// items and slots are drawn this big +const CELL = 54; +const GAP = 16; +const TEXT = 22; +const LINE = 30; +const BUTTON = 32; +const SLOT_COLOR: Color = [0, 0, 0, 0.25]; +const HOVER_COLOR: Color = [1, 1, 1, 0.35]; +const LABEL_COLOR: Color = [0.25, 0.25, 0.25, 1]; +const MOD_COLOR: Color = [0.33, 0.33, 1, 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 = { + furnace: "bworld:furnace", + fuel: "bworld:furnace", + smithing: "bworld:smithing_table", + "farmersdelight:cooking": "farmersdelight:cooking_pot", +}; +const CATEGORY_NAMES: Record = { + 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"; + +export function setup(ctx: ClientContext) { + ctx.ui.add_inventory_overlay(new RecipeViewer(ctx)); +} + +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(); + } + + #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).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 - TEXT) / 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); + 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); + } + 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 - TEXT) / 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 id = letter && letter !== " " && column < width_in ? recipe.key[letter] : undefined; + cell(id ? { ids: [id], 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: [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: [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 + const { grid, extras } = mod_recipe_inputs(recipe); + 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"]) + ); + outputs(recipe).slice(0, 1).forEach((output) => cell(output, x + 5 * CELL, top + CELL / 2)); + if (typeof recipe.cook_time === "number") { + g.text(seconds(recipe.cook_time), x + 5 * CELL, top + CELL * 1.5 + (CELL - TEXT) / 2, { + color: LABEL_COLOR, + }); + } + } + } + return hovered; + } +} + +// a card's height: its label, its rows of items, and a gap +function card_height(recipe: Recipe): 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).grid.length / 3)); + 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): Recipe[][] { + const pages: Recipe[][] = [[]]; + let used = 0; + for (const recipe of recipes) { + const needed = card_height(recipe); + 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: { + const output = recipe.result ?? recipe.output; + if (typeof output === "string") return [{ ids: [output], count: 1 }]; + if (output && typeof output.id === "string") return [stack(output)]; + return []; + } + } +} + +// what a recipe takes +export function inputs(recipe: Recipe): Ingredient[] { + switch (recipe.type) { + case "shaped": + return Object.values(recipe.key as Record).map((id) => ({ ids: [id], count: 1 })); + case "furnace": + return [{ ids: [recipe.input], count: 1 }]; + case "fuel": + return [{ ids: [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); + return [...grid, ...extras]; + } + } +} + +// the items in a mod recipe's fields besides its type and result: each item 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): { grid: Ingredient[]; extras: Ingredient[] } { + const grid: Ingredient[] = []; + const extras: Ingredient[] = []; + const is_id = (value: unknown): value is string => + typeof value === "string" && /^[a-z0-9_]+:[a-z0-9_/]+$/.test(value); + for (const [field, value] of Object.entries(recipe)) { + if (field === "type" || field === "result" || field === "output") continue; + if (is_id(value)) { + extras.push({ ids: [value], count: 1 }); + } else if (Array.isArray(value)) { + for (const entry of value) { + if (is_id(entry)) grid.push({ ids: [entry], count: 1 }); + else if (Array.isArray(entry) && entry.every(is_id)) grid.push({ ids: entry, count: 1 }); + } + } + } + return { grid, extras }; +} + +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); + }); +} diff --git a/tests/handshake_test.ts b/tests/handshake_test.ts index 399c76f..b28c483 100644 --- a/tests/handshake_test.ts +++ b/tests/handshake_test.ts @@ -29,7 +29,7 @@ Deno.test("welcome lists what to download, and nothing happens until ready", asy send(2, { type: "hello", name: "bob", protocol: PROTOCOL_VERSION }); const [welcome] = take(2); assertEquals(welcome.type, "welcome"); - assertEquals(welcome.mods.map((m: { id: string }) => m.id), ["bworld", "farmersdelight"]); + assertEquals(welcome.mods.map((m: { id: string }) => m.id), ["bworld", "farmersdelight", "recipe_viewer"]); assert(welcome.mods.every((m: { sha256: string; file: string }) => m.sha256 && m.file)); assert(!("players" in welcome) && !("changes" in welcome), "welcome shouldn't have world state"); diff --git a/tests/recipe_viewer_test.ts b/tests/recipe_viewer_test.ts new file mode 100644 index 0000000..2c40407 --- /dev/null +++ b/tests/recipe_viewer_test.ts @@ -0,0 +1,42 @@ +// the recipe viewer mod reads every mod's recipes, its own types included +import { assert, assertEquals } from "@std/assert"; +import { category_name, inputs, outputs } from "../mods/recipe_viewer/scripts/client.ts"; +import { test_game } from "./helpers.ts"; + +const ids = (ingredients: { ids: string[] }[]) => ingredients.map((i) => i.ids.join("|")); + +Deno.test("the recipe viewer finds what makes and uses an item, in any recipe type", async () => { + const { game } = await test_game("mods"); + const all = game.recipes.all; + const making = (item: string) => all.filter((r) => outputs(r).some((o) => o.ids.includes(item))); + const using = (item: string) => all.filter((r) => inputs(r).some((i) => i.ids.includes(item))); + + // a shaped recipe, with its count + const [bowl] = making("bworld:bowl"); + assertEquals(bowl.type, "shaped"); + assertEquals(outputs(bowl), [{ ids: ["bworld:bowl"], count: 4 }]); + + // the cooking pot's own type: ingredients, alternatives, and the bowl it's served in + const [rolls] = making("farmersdelight:cabbage_rolls"); + assertEquals(category_name(rolls.type), "Cooking"); + assertEquals(ids(inputs(rolls)), [ + "farmersdelight:cabbage", + "bworld:carrot|bworld:potato|farmersdelight:onion|farmersdelight:tomato", + ]); + const [rice] = making("farmersdelight:cooked_rice"); + assertEquals(ids(inputs(rice)), ["farmersdelight:rice", "bworld:bowl"]); + + // uses: the bowl serves two meals, coal is fuel and in the stove, potatoes are in cabbage rolls + assertEquals(using("bworld:bowl").map((r) => outputs(r)[0].ids[0]).sort(), [ + "farmersdelight:cooked_rice", + "farmersdelight:tomato_sauce", + ]); + assert(using("bworld:coal").some((r) => r.type === "fuel")); + assert(using("bworld:coal").some((r) => r.type === "shaped" && outputs(r)[0].ids[0] === "farmersdelight:stove")); + assert(using("bworld:potato").includes(rolls)); + + // smelting and smithing + assertEquals(ids(making("bworld:iron_ingot").flatMap(inputs)), ["bworld:iron_ore"]); + assertEquals(ids(inputs(making("bworld:stone_pickaxe")[0])), ["bworld:wood_pickaxe", "bworld:stone"]); + assertEquals(category_name("smithing"), "Smithing"); +});