From 3dc7d2adee0c3b767bb3362392ef1827526238da Mon Sep 17 00:00:00 2001 From: Paula Date: Thu, 1 Oct 2026 16:35:41 -0300 Subject: [PATCH] Change curios to always show on inventory --- client/client.ts | 3 ++ client/gui/gui_player_inventory.ts | 18 ++++++- client/gui/gui_screen.ts | 1 + client/inventory.ts | 4 ++ client/menu.ts | 11 ++-- client/network.ts | 5 +- common/mod_api/client.ts | 2 + common/mod_api/server.ts | 10 ++++ common/protocol.ts | 15 ++++-- docs/modding/gui/index.md | 1 + docs/modding/inventories/menus.md | 28 +++++++++- docs/modding_plan.md | 6 +-- mods/curios/README.md | 3 +- mods/curios/manifest.json | 3 +- mods/curios/scripts/client.ts | 40 -------------- mods/curios/scripts/server.ts | 40 ++++++-------- mods/curios/scripts/slots.ts | 2 +- server/game/game_server.ts | 7 +++ server/game/menu.ts | 24 ++++++--- server/game/mod_runtime.ts | 85 ++++++++++++++++++++++-------- tests/artifacts_test.ts | 22 ++++---- tests/base_game_test.ts | 4 +- tests/curios_test.ts | 57 +++++++++----------- tests/server_scripts_test.ts | 12 +++++ 24 files changed, 244 insertions(+), 159 deletions(-) delete mode 100644 mods/curios/scripts/client.ts diff --git a/client/client.ts b/client/client.ts index 67f8a5c..d1e3169 100644 --- a/client/client.ts +++ b/client/client.ts @@ -19,6 +19,7 @@ import { Connection } from "./network.ts"; import { PauseScreen } from "./gui/pause_screen.ts"; import { back_to_title } from "./gui/title_screen.ts"; import { TICK_DELTA } from "$/common/constants.ts"; +import { Container } from "$/common/inventory.ts"; import { PLAYER_MENU } from "$/common/protocol.ts"; import { EverythingRegistry } from "$/common/everything_registry.ts"; import type { EntityJson } from "$/common/mod_data.ts"; @@ -76,6 +77,8 @@ export class Client { this.player.yaw = spawn.yaw; this.player.pitch = spawn.pitch; this.player.inventories.hotbar_selected = connection.selected_slot; + this.player.inventories.extra_slots = connection.player_menu; + this.player.inventories.extra = new Container(connection.player_menu.length); this.level.add_entity(this.player); for (const info of connection.initial_players) { this.level.add_entity(new RemotePlayer(this.level, info)); diff --git a/client/gui/gui_player_inventory.ts b/client/gui/gui_player_inventory.ts index 60ae51e..f6f4078 100644 --- a/client/gui/gui_player_inventory.ts +++ b/client/gui/gui_player_inventory.ts @@ -1,13 +1,17 @@ import { GuiMenuScreen } from "./gui_screen.ts"; import { ClientInventories } from "../inventory.ts"; -import { ClientMessage } from "$/common/protocol.ts"; +import { ClientMessage, PLAYER_MENU_EXTRA } from "$/common/protocol.ts"; import { player_menu } from "../menu.ts"; import type { ModGraphics } from "./mod_graphics.ts"; const WIDTH = 176; const HEIGHT = 166; +const SLOT = 18; +// around the slots, like minecraft's +const MARGIN = 7; -// menu 0's screen: the crafting grid over the inventory. the recipes live on the server, which fills in the result +// menu 0's screen: the crafting grid over the inventory, and any slots mods added. the recipes live on the server, +// which fills in the result export class GuiPlayerInventory extends GuiMenuScreen { constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) { super(inventories, send, player_menu(inventories), WIDTH, HEIGHT); @@ -15,6 +19,16 @@ export class GuiPlayerInventory extends GuiMenuScreen { render_background(g: ModGraphics): void { g.panel(0, 0, WIDTH, HEIGHT); + // the slots mods added outside the panel get one of their own, around them with the same margin + const outside = this.menu.slots.slice(PLAYER_MENU_EXTRA) + .filter((s) => s.x + SLOT < 0 || s.x > WIDTH || s.y + SLOT < 0 || s.y > HEIGHT); + if (outside.length > 0) { + const left = Math.min(...outside.map((s) => s.x)) - MARGIN; + const top = Math.min(...outside.map((s) => s.y)) - MARGIN; + const right = Math.max(...outside.map((s) => s.x)) + SLOT + MARGIN; + const bottom = Math.max(...outside.map((s) => s.y)) + SLOT + MARGIN; + g.panel(left, top, right - left, bottom - top); + } } render_labels(g: ModGraphics): void { diff --git a/client/gui/gui_screen.ts b/client/gui/gui_screen.ts index f114742..77deac5 100644 --- a/client/gui/gui_screen.ts +++ b/client/gui/gui_screen.ts @@ -154,6 +154,7 @@ export abstract class GuiMenuScreen extends GuiScreen { #render_overlays() { const hovered = this.hovering && this.hovering.container.get_item(this.hovering.index); const view = { + menu_type: this.menu.id === PLAYER_MENU ? undefined : this.menu.type, x: this.x / GUI_SCALE, y: this.y / GUI_SCALE, width: this.width, diff --git a/client/inventory.ts b/client/inventory.ts index 65a8a12..4b1c442 100644 --- a/client/inventory.ts +++ b/client/inventory.ts @@ -1,9 +1,13 @@ import { Container, Cursor } from "$/common/inventory.ts"; +import type { MenuSlotInfo } from "$/common/protocol.ts"; // the local copies of the containers the server syncs to this player export class ClientInventories { inventory = new Container(9 * 4); crafting = new Container(10); + // the slots mods added to menu 0 and what's in them, see join's player_menu + extra_slots: MenuSlotInfo[] = []; + extra = new Container(0); cursor: Cursor = { item: undefined }; hotbar_selected = 0; } diff --git a/client/menu.ts b/client/menu.ts index 9bcb3c3..73e9a7c 100644 --- a/client/menu.ts +++ b/client/menu.ts @@ -1,7 +1,7 @@ // the client's copy of a menu, like neoforge's client menu: built from what the server sent when it opened, kept up // to date with what it syncs. clicks go to the server, which decides what they do import { Container } from "$/common/inventory.ts"; -import { CRAFTING_RESULT_SLOT, type MenuSlotInfo, PLAYER_MENU, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts"; +import { CRAFTING_RESULT_SLOT, type MenuSlotInfo, PLAYER_MENU, PLAYER_MENU_EXTRA } from "$/common/protocol.ts"; import type { ClientInventories } from "./inventory.ts"; export interface ClientSlot { @@ -61,8 +61,8 @@ export class ClientMenu { } } -// menu 0, the player's inventory and crafting grid, laid out for the inventory screen. its slots are the player's -// own containers, which the server syncs whether or not a menu is open +// menu 0, the player's inventory and crafting grid, laid out for the inventory screen, then the slots mods added. its +// slots are the player's own containers, which the server syncs whether or not a menu is open export function player_menu(inventories: ClientInventories): ClientMenu { const slot = (container: Container, index: number, x: number, y: number, output = false): ClientSlot => ({ container, @@ -81,6 +81,9 @@ export function player_menu(inventories: ClientInventories): ClientMenu { slots.push(slot(inventories.crafting, i, 25 + (i % 3) * 18, 16 + Math.floor(i / 3) * 18)); } slots.push(slot(inventories.crafting, CRAFTING_RESULT_SLOT, 115, 34, true)); - if (slots.length !== PLAYER_MENU_CRAFTING + CRAFTING_RESULT_SLOT + 1) throw new Error("menu 0 has the wrong slots"); + if (slots.length !== PLAYER_MENU_EXTRA) throw new Error("menu 0 has the wrong slots"); + for (const [i, info] of inventories.extra_slots.entries()) { + slots.push({ ...slot(inventories.extra, i, info.x, info.y, info.output === true), icon: info.icon }); + } return new ClientMenu(PLAYER_MENU, "", "Crafting", null, slots); } diff --git a/client/network.ts b/client/network.ts index 23bc94c..e9ee6c6 100644 --- a/client/network.ts +++ b/client/network.ts @@ -1,4 +1,4 @@ -import { ClientMessage, EntityInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts"; +import { ClientMessage, EntityInfo, MenuSlotInfo, PlayerInfo, ServerMessage } from "$/common/protocol.ts"; import type { ModListing } from "$/common/mod_loader.ts"; import type { Join, ServerSocket, Welcome } from "./handshake.ts"; @@ -11,6 +11,8 @@ export class Connection { server_blocks: string[]; spawn: { x: number; y: number; z: number; yaw: number; pitch: number }; selected_slot: number; + // the slots mods added to menu 0 + player_menu: MenuSlotInfo[]; time: number; // who was already there when we joined, they become entities in the level initial_players: PlayerInfo[]; @@ -24,6 +26,7 @@ export class Connection { this.server_blocks = join.blocks; this.spawn = join.spawn; this.selected_slot = join.selected_slot; + this.player_menu = join.player_menu; this.time = join.time; this.initial_players = join.players; this.initial_entities = join.entities; diff --git a/common/mod_api/client.ts b/common/mod_api/client.ts index 0c4a35f..364500a 100644 --- a/common/mod_api/client.ts +++ b/common/mod_api/client.ts @@ -119,6 +119,8 @@ export interface InventoryOverlay { } export interface InventoryScreenView { + // the open menu's type, like "bworld:furnace". undefined on the player's own inventory + readonly menu_type: Id | undefined; readonly x: number; readonly y: number; readonly width: number; diff --git a/common/mod_api/server.ts b/common/mod_api/server.ts index 3418790..a52d6b4 100644 --- a/common/mod_api/server.ts +++ b/common/mod_api/server.ts @@ -388,7 +388,17 @@ export interface MenuType { open(player: Player, args: Args): MenuHandle; } +// the player's own inventory menu, see MenuRegistry.extend_player_menu +export interface PlayerMenuBuilder { + // x and y are from the inventory screen's top left, and can be outside it, like left of it with a negative x. the + // engine draws a panel behind slots outside its own. returns the menu slot index, from 46 on + add_slot(container: Container, slot: number, options: SlotOptions): number; +} + export interface MenuRegistry { + // adds slots to every player's own inventory menu, always there while they play, like curios' slots next to the + // inventory. build runs when each player joins. only during setup + extend_player_menu(build: (menu: PlayerMenuBuilder, player: Player) => void): void; // like registering a MenuType. the client script gives it a screen with ctx.ui.register_menu_screen register( id: Id, diff --git a/common/protocol.ts b/common/protocol.ts index 2b2b7c5..6fb096f 100644 --- a/common/protocol.ts +++ b/common/protocol.ts @@ -7,7 +7,7 @@ export const AIR_ID = "bworld:air"; // bump when a client and server of different versions can't play together. // the server rejects a different version before the client downloads anything -export const PROTOCOL_VERSION = 14; +export const PROTOCOL_VERSION = 15; export interface PlayerInfo { id: string; @@ -52,16 +52,19 @@ export type EntityEvent = "hurt" | "death" | "swing"; // x, y, z, block id, and its state bits when they aren't 0 export type BlockChange = [number, number, number, string, number?]; -// the player's own containers, synced to them whether or not a menu is open -export type ContainerKey = "inventory" | "crafting"; +// the player's own containers, synced to them whether or not a menu is open. "extra" is what's in the slots mods added +// to menu 0, like curios', in their order +export type ContainerKey = "inventory" | "crafting" | "extra"; export const CRAFTING_RESULT_SLOT = 9; // menus, like neoforge's: the server's menu decides what every click does, clients draw it and send clicks by menu -// slot index. menu 0 is the player's own inventory and crafting grid, always there and never opened or sent, like -// minecraft's InventoryMenu: slots 0-35 are the inventory (the hotbar is 0-8), 36-45 the crafting grid +// slot index. menu 0 is the player's own inventory and crafting grid, always there and never opened, like minecraft's +// InventoryMenu: slots 0-35 are the inventory (the hotbar is 0-8), 36-45 the crafting grid, then the slots mods added, +// which join's player_menu lists export const PLAYER_MENU = 0; export const PLAYER_MENU_CRAFTING = 36; +export const PLAYER_MENU_EXTRA = 46; // one slot of an opened menu as the client draws it. x and y in gui pixels from the screen's top left, output slots // can only be taken from, icon is a texture drawn while it's empty @@ -134,6 +137,8 @@ export type ServerMessage = blocks: string[]; spawn: { x: number; y: number; z: number; yaw: number; pitch: number }; selected_slot: number; + // the slots mods added to menu 0, from PLAYER_MENU_EXTRA on, see ctx.menus.extend_player_menu + player_menu: MenuSlotInfo[]; // world time in ticks, see common/time.ts time: number; } diff --git a/docs/modding/gui/index.md b/docs/modding/gui/index.md index 250df18..59b1e4d 100644 --- a/docs/modding/gui/index.md +++ b/docs/modding/gui/index.md @@ -70,6 +70,7 @@ GUI pixels from the window's top left: ```ts interface InventoryScreenView { + readonly menu_type: string | undefined; // the open menu's type, undefined on the player's own inventory readonly x: number; readonly y: number; readonly width: number; diff --git a/docs/modding/inventories/menus.md b/docs/modding/inventories/menus.md index 3890b16..eb3d192 100644 --- a/docs/modding/inventories/menus.md +++ b/docs/modding/inventories/menus.md @@ -7,7 +7,8 @@ Menus are how players use [containers](containers.md), like NeoForge's. A GUI ha - The **screen** lives in the client script. It only draws the menu and sends the player's clicks. Every click goes to the server, which applies it following the menu's rules, so a modified client can only do what the -menu allows. Chests, furnaces, the smithing table, Farmer's Delight's cooking pot and Curios are all menus. +menu allows. Chests, furnaces, the smithing table and Farmer's Delight's cooking pot are all menus, and Curios adds its +slots to [the player's inventory](#the-players-inventory). ## Registering a Menu Type @@ -179,11 +180,34 @@ interface ClientMenu { When the server opens a menu type the client has no screen for, the client closes it again, with an error in its console. A screen that throws is closed the same way. +## The Player's Inventory + +The player's own inventory screen is a menu too, menu 0, like Minecraft's `InventoryMenu`: their inventory and crafting +grid, always there while they play. Mods can add slots to it with `ctx.menus.extend_player_menu` during setup. The +function runs when each player joins: + +```ts +ctx.menus.extend_player_menu((menu, player) => { + const pouch = pouch_of(player); // a container from ctx.containers, kept for each player + for (let slot = 0; slot < 4; slot++) { + menu.add_slot(pouch, slot, { x: -25, y: 7 + slot * 18 }); + } +}); +``` + +`add_slot` takes the same options as a menu's. `x` and `y` are from the inventory screen's top left, and can be outside +it: a negative `x` is left of it. The engine draws a panel behind the slots outside its own, so they need no client +code. Curios puts its slots in 2 columns this way. + +Shift clicking in the inventory puts a stack into the first of these slots whose `filter` takes it, before moving it +between the hotbar and the rest of the inventory. Shift clicking one of them moves its stack back into the inventory. + ## Messages How menus go over the network, for anyone working on the engine. Menus have ids from 1 to 100, counting up and around for each player like Minecraft's. Menu 0 is the player's own inventory (slots 0 to 35, the hotbar first) and crafting -grid (36 to 45), always there and never sent. +grid (36 to 45), always there and never opened. The slots mods added to it come after, from 46: `join` lists their +positions, and the `container` message with `"extra"` syncs what's in them, like the inventory's. | Message | Way | What | | -------------------- | ------ | ------------------------------------------------------------------------------- | diff --git a/docs/modding_plan.md b/docs/modding_plan.md index db3d78b..681ccbe 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -28,9 +28,9 @@ server and worldgen scripts), delivery to clients (hashed downloads, the confirm data layer (blocks, block models with variants, items, recipes including mods' own types, entities and entity models, ores), server scripts (components, events, commands, timers, storage, recipes, containers, displayed items), menus like NeoForge's (menu types, slots, data, buttons and `still_valid` on the server, menu screens on the client, and the -player's inventory as menu 0), client scripts (item and recipe lookups, plain screens, inventory overlays, `Graphics` in -GUI pixels), mod channels, worldgen features and ores, the base game's block behavior and screens as a mod, and world -time. See [Menus](modding/inventories/menus.md) and [Screens](modding/gui/index.md). +player's inventory as menu 0, which mods can add slots to), client scripts (item and recipe lookups, plain screens, +inventory overlays, `Graphics` in GUI pixels), mod channels, worldgen features and ores, the base game's block behavior +and screens as a mod, and world time. See [Menus](modding/inventories/menus.md) and [Screens](modding/gui/index.md). The code is in `common/mod_loader.ts`, `common/mod_data.ts`, `common/mod_check.ts`, `common/bmod.ts`, `server/game/mod_runtime.ts`, `server/game/menu.ts`, `server/load_bmods.ts`, `client/mods.ts`, `client/menu.ts` and diff --git a/mods/curios/README.md b/mods/curios/README.md index 10e0623..6f61ed1 100644 --- a/mods/curios/README.md +++ b/mods/curios/README.md @@ -1,7 +1,8 @@ # Curios A port of [Curios](https://github.com/TheIllusiveC4/Curios): accessory slots, like rings, necklaces and belts, for any -mod's items. Players open them with the Curios button next to their inventory, or G while an inventory is open. +mod's items. They're in 2 columns left of the player's inventory, there whenever it's open. Shift clicking a curio in +the inventory puts it in the first slot it fits. Like the original, Curios adds no items and no slots of its own. A slot type only shows up once some mod puts an item in its tag. diff --git a/mods/curios/manifest.json b/mods/curios/manifest.json index 4a4c4c3..8c5a0a6 100644 --- a/mods/curios/manifest.json +++ b/mods/curios/manifest.json @@ -11,7 +11,6 @@ "game_version": ">=0.1.0", "credits": "CREDITS.md", "scripts": { - "server": "scripts/server.ts", - "client": "scripts/client.ts" + "server": "scripts/server.ts" } } diff --git a/mods/curios/scripts/client.ts b/mods/curios/scripts/client.ts deleted file mode 100644 index 00c29b6..0000000 --- a/mods/curios/scripts/client.ts +++ /dev/null @@ -1,40 +0,0 @@ -// the curios button next to every inventory screen, or G like curios' keybind, asks the server to open the curios -// menu, and its screen -import type { ClientContext } from "bworld/client"; -import { active_slots } from "./slots.ts"; - -// in gui pixels -const GAP = 5; -const BUTTON_WIDTH = 40; -const BUTTON_HEIGHT = 11; -const WIDTH = 176; - -export function setup(ctx: ClientContext) { - // no item goes in any slot, so there's nothing to show - if (active_slots(ctx.tags).length === 0) return; - - ctx.ui.add_inventory_overlay({ - on_render(g, screen) { - const clicked = g.button("Curios", screen.x - BUTTON_WIDTH - GAP, screen.y, BUTTON_WIDTH, BUTTON_HEIGHT); - if (clicked || g.key_pressed("KeyG")) { - ctx.net.send("curios:open", {}); - } - }, - }); - - ctx.ui.register_menu_screen("curios:curios", (menu) => { - const { rows } = menu.open_data as { rows: number }; - const height = 114 + rows * 18; - return { - width: WIDTH, - height, - on_render_background(g) { - g.panel(0, 0, WIDTH, height); - }, - on_render_labels(g) { - g.text(menu.title, 8, 6); - g.text("Inventory", 8, height - 93); - }, - }; - }); -} diff --git a/mods/curios/scripts/server.ts b/mods/curios/scripts/server.ts index f925071..5c704f8 100644 --- a/mods/curios/scripts/server.ts +++ b/mods/curios/scripts/server.ts @@ -1,9 +1,12 @@ -// curios: accessory slots, shown with the player's inventory from the curios button. each player's curios are a +// curios: accessory slots, in 2 columns left of the player's inventory. each player's curios are a // container of their own, and fall out when they die like the rest of what they carry. items with the // curios:attribute_modifiers component change the wearer's attributes, like curios' attribute modifiers import type { AttributeModifier, Container, Player, ServerContext } from "bworld/server"; import { active_slots, fits, SLOTS } from "./slots.ts"; +// where the left column of slots goes, from the inventory screen's left edge. the panel around them ends just left of it +const COLUMNS_X = -45; + // curios:attribute_modifiers' params, a list of these interface WornModifier { attribute: string; @@ -24,7 +27,7 @@ export function setup(ctx: ServerContext) { const applied = new Map(); const stop_watching = new Map void>(); - // by player name, like the players themselves are saved. undefined until they first open curios + // by player name, like the players themselves are saved. undefined until they first join with curios function saved_curios(player: Player): Container | undefined { const id = ctx.storage.get>("containers")?.[player.name]; return id ? ctx.containers.get(id) : undefined; @@ -72,28 +75,8 @@ export function setup(ctx: ServerContext) { applied.delete(player.id); }); - // like curios' CuriosContainer: the slot types in rows of 9, each row centered, over the inventory. the screen is - // in scripts/client.ts - const rows = Math.ceil(active.length / 9); - const menu_type = ctx.menus.register("curios:curios", (menu, _args, player) => { - const curios = curios_of(player); - menu.title = "Curios"; - menu.open_data = { rows }; - for (const [i, slot] of active.entries()) { - const row = Math.floor(i / 9); - const in_row = Math.min(9, active.length - row * 9); - menu.add_slot(curios, SLOTS.indexOf(slot), { - x: 7 + ((9 - in_row) / 2 + (i % 9)) * 18, - y: 17 + row * 18, - filter: (item) => fits(ctx.tags, slot, item.id), - icon: `curios:empty_${slot}_slot`, - }); - } - menu.add_player_inventory(7, 31 + rows * 18); - }); - - // the curios button, curios' client asks for its menu like the java mod's packet does - ctx.net.on("curios:open", (player) => { + // the slot types in 2 columns left of the inventory, always there while it's open. the engine draws their panel + ctx.menus.extend_player_menu((menu, player) => { if (active.length === 0) return; const curios = curios_of(player); // what's in slot types no item goes in anymore, since the mod that added them was removed, goes back to them @@ -104,7 +87,14 @@ export function setup(ctx: ServerContext) { curios.set(index, undefined); } } - menu_type.open(player, undefined); + for (const [i, slot] of active.entries()) { + menu.add_slot(curios, SLOTS.indexOf(slot), { + x: COLUMNS_X + (i % 2) * 18, + y: 7 + Math.floor(i / 2) * 18, + filter: (item) => fits(ctx.tags, slot, item.id), + icon: `curios:empty_${slot}_slot`, + }); + } }); ctx.events.after.player_death.subscribe(({ player }) => { diff --git a/mods/curios/scripts/slots.ts b/mods/curios/scripts/slots.ts index b8aa0a9..d1d2edd 100644 --- a/mods/curios/scripts/slots.ts +++ b/mods/curios/scripts/slots.ts @@ -1,4 +1,4 @@ -// curios' slot types, both scripts share them +// curios' slot types import type { TagApi } from "bworld/server"; // in curios' order. every player has one of each, at its index here in their curios container, so slots keep their diff --git a/server/game/game_server.ts b/server/game/game_server.ts index 4ce7f02..2b859a9 100644 --- a/server/game/game_server.ts +++ b/server/game/game_server.ts @@ -714,6 +714,7 @@ export class GameServer { Object.assign(player, this.world.spawn_point()); } + this.mods.extend_player_menu(player); this.#send(player, { type: "join", id: player.id, @@ -723,6 +724,7 @@ export class GameServer { blocks: this.world.block_table(), spawn: { x: player.x, y: player.y, z: player.z, yaw: player.yaw, pitch: player.pitch }, selected_slot: player.selected_slot, + player_menu: player.inventory_menu.extra.map(({ x, y, icon }) => ({ x, y, ...(icon ? { icon } : {}) })), time: this.world.time, }); this.#players.set(conn, player); @@ -1525,6 +1527,11 @@ export class GameServer { sync("crafting", crafting, () => ({ type: "container", container: "crafting", items: crafting })); const cursor = player.cursor.item?.to_synced_data() ?? null; sync("cursor", cursor, () => ({ type: "cursor", item: cursor })); + const extra = player.inventory_menu.extra; + if (extra.length > 0) { + const items = extra.map((slot) => slot.container.get_item(slot.index)?.to_synced_data() ?? null); + sync("extra", items, () => ({ type: "container", container: "extra", items })); + } const { food, saturation } = player.vitals; const health = player.health; diff --git a/server/game/menu.ts b/server/game/menu.ts index b266430..002b762 100644 --- a/server/game/menu.ts +++ b/server/game/menu.ts @@ -11,7 +11,13 @@ import { room_for, take_output, } from "$/common/inventory.ts"; -import { CRAFTING_RESULT_SLOT, type MenuSlotInfo, PLAYER_MENU, PLAYER_MENU_CRAFTING } from "$/common/protocol.ts"; +import { + CRAFTING_RESULT_SLOT, + type MenuSlotInfo, + PLAYER_MENU, + PLAYER_MENU_CRAFTING, + PLAYER_MENU_EXTRA, +} from "$/common/protocol.ts"; import type { GridRecipe } from "$/common/mod_data.ts"; import { consume_recipe_items, update_crafting_result } from "./crafting.ts"; @@ -155,8 +161,8 @@ export class Menu { } } -// menu 0, the player's own inventory and crafting grid, like minecraft's InventoryMenu. clients know its layout, so -// it's never sent +// menu 0, the player's own inventory and crafting grid, like minecraft's InventoryMenu, then the slots mods add with +// ctx.menus.extend_player_menu. clients know its layout, only the mods' slots are sent, with join export class PlayerMenu extends Menu { #crafting: Container; #recipes: () => GridRecipe[]; @@ -198,8 +204,13 @@ export class PlayerMenu extends Menu { } } - // the inventory moves between the hotbar and the rest, never into the grid. the grid and its result go to the - // inventory, the rest first + // the slots mods added + get extra(): MenuSlot[] { + return this.slots.slice(PLAYER_MENU_EXTRA); + } + + // the inventory goes into the slots mods added that take it, then between the hotbar and the rest, never into the + // grid. the grid, its result and the mods' slots go to the inventory, the rest first override quick_move_targets(index: number): number[] { const main = Array.from({ length: PLAYER_MENU_CRAFTING - 9 }, (_, i) => i + 9); const hotbar = Array.from({ length: 9 }, (_, i) => i); @@ -208,6 +219,7 @@ export class PlayerMenu extends Menu { ? [...main, ...hotbar].reverse() : [...main, ...hotbar]; } - return index < 9 ? main : hotbar; + const extra = this.extra.map((_, i) => PLAYER_MENU_EXTRA + i); + return [...extra, ...(index < 9 ? main : hotbar)]; } } diff --git a/server/game/mod_runtime.ts b/server/game/mod_runtime.ts index 0fdb154..ebfbe97 100644 --- a/server/game/mod_runtime.ts +++ b/server/game/mod_runtime.ts @@ -19,9 +19,11 @@ import type { MenuHandle, MenuType, Player, + PlayerMenuBuilder, ServerAfterEvents, ServerBeforeEvents, ServerContext, + SlotOptions, } from "$/common/mod_api/server.ts"; import { ModLoadError } from "$/common/mod_loader.ts"; import { @@ -174,6 +176,28 @@ export class ModRuntime { #server_players = new WeakMap(); // menu types by id, every mod's #menu_types = new Set(); + // what each mod adds to the player's own menu, in load order + #player_menu_builders: { mod: string; build: (menu: PlayerMenuBuilder, player: Player) => void }[] = []; + + // a player joined: the mods' slots go after menu 0's own. one that throws is logged and the rest still run + extend_player_menu(player: ServerPlayer) { + const api = this.player(player); + for (const { mod, build } of this.#player_menu_builders) { + const menu = player.inventory_menu; + const added: MenuSlot[] = []; + const ok = run_guarded(mod, "an extend_player_menu", () => { + build({ + add_slot: (container, slot, options) => { + added.push(menu_slot(this.game, mod, player, container, slot, options)); + return menu.slots.length + added.length - 1; + }, + }, api); + return true; + }); + // all of a mod's slots or none, so a half built set can't shift the next mod's + if (ok) menu.slots.push(...added); + } + } game!: GameServer; // imports each server script and calls its setup, in load order @@ -570,6 +594,10 @@ export class ModRuntime { delete: (id) => game().delete_container(id), }, menus: { + extend_player_menu: (build) => { + setup_only("extend_player_menu"); + this.#player_menu_builders.push({ mod, build }); + }, register: (id: string, build: (menu: MenuBuilder, args: Args, player: Player) => void) => { own(id, "menu type"); if (this.#menu_types.has(id)) throw new Error(`[${mod}] menu type ${id} is already registered`); @@ -646,28 +674,7 @@ export class ModRuntime { menu.open_data = structuredClone(value) ?? null; }, add_slot(container, slot, options) { - const engine = engine_containers.get(container); - if (!engine) throw new Error("add_slot needs a container from ctx.containers or player.inventory"); - if (!Number.isInteger(slot) || slot < 0 || slot >= engine.size) { - throw new Error(`slot ${slot} isn't in the container, it has ${engine.size}`); - } - if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) { - throw new Error(`slot ${slot} needs an x and y`); - } - const { filter, on_take } = options; - const added: MenuSlot = { container: engine, index: slot, x: options.x, y: options.y }; - if (filter === "smeltable") { - added.filter = (item) => game.recipes.furnace.has(item.type_id); - } else if (filter === "fuel") { - added.filter = (item) => game.recipes.fuel.has(item.type_id); - } else if (typeof filter === "function") { - added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true; - } - if (options.output_only) added.output = true; - if (on_take) added.on_take = (item) => guarded("an on_take", () => on_take(item_api(item))) === true; - if (options.icon) added.icon = String(options.icon); - if (engine === server_player.inventory) added.inventory = slot; - menu.slots.push(added); + menu.slots.push(menu_slot(game, mod, server_player, container, slot, options)); return menu.slots.length - 1; }, add_player_inventory(x, y) { @@ -834,6 +841,40 @@ function new_stack(item: ItemStack): EngineItemStack { return stack; } +// a menu's slot from what a mod's add_slot got +function menu_slot( + game: GameServer, + mod: string, + player: ServerPlayer, + container: Container, + slot: number, + options: SlotOptions, +): MenuSlot { + const engine = engine_containers.get(container); + if (!engine) throw new Error("add_slot needs a container from ctx.containers or player.inventory"); + if (!Number.isInteger(slot) || slot < 0 || slot >= engine.size) { + throw new Error(`slot ${slot} isn't in the container, it has ${engine.size}`); + } + if (![options?.x, options?.y].every((n) => typeof n === "number" && Number.isFinite(n))) { + throw new Error(`slot ${slot} needs an x and y`); + } + const { filter, on_take } = options; + const guarded = (what: string, fn: () => T) => run_guarded(mod, what, fn); + const added: MenuSlot = { container: engine, index: slot, x: options.x, y: options.y }; + if (filter === "smeltable") { + added.filter = (item) => game.recipes.furnace.has(item.type_id); + } else if (filter === "fuel") { + added.filter = (item) => game.recipes.fuel.has(item.type_id); + } else if (typeof filter === "function") { + added.filter = (item) => guarded("a slot filter", () => filter(item_api(item))) === true; + } + if (options.output_only) added.output = true; + if (on_take) added.on_take = (item) => guarded("an on_take", () => on_take(item_api(item))) === true; + if (options.icon) added.icon = String(options.icon); + if (engine === player.inventory) added.inventory = slot; + return added; +} + // the engine container behind each one mods get, for menus' slots const engine_containers = new WeakMap(); diff --git a/tests/artifacts_test.ts b/tests/artifacts_test.ts index 98d910a..01802ed 100644 --- a/tests/artifacts_test.ts +++ b/tests/artifacts_test.ts @@ -1,7 +1,8 @@ // artifacts: items worn in curios slots that change the wearer's attributes, see mods/artifacts import { assertEquals } from "@std/assert"; import { ATTRIBUTES } from "$/server/game/entity/attributes.ts"; -import { menu_items, opened_menu, test_game } from "./helpers.ts"; +import { PLAYER_MENU_EXTRA } from "$/common/protocol.ts"; +import { test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; @@ -17,18 +18,14 @@ async function setup() { Deno.test("the power glove and feral claws go in the hands slot, and only work while worn", async () => { const t = await setup(); - t.send(1, { type: "mod", channel: "curios:open", data: {} }); - const menu = opened_menu(t.take(1)); - // the hands slot, then the inventory's - assertEquals(menu.slots.map((s: Msg) => s.icon).filter(Boolean), ["curios:empty_hands_slot"]); - - t.send(1, { type: "click", menu: menu.id, slot: 1, button: 0, shift: true }); + // the hands slot is the only curios one, after the player's own menu's + t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); t.game.tick(); assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1 + 4); // swapped for the claws by hand: the glove's damage goes, the claws' speed comes - t.send(1, { type: "click", menu: menu.id, slot: 2, button: 0 }); - t.send(1, { type: "click", menu: menu.id, slot: 0, button: 0 }); + t.send(1, { type: "click", menu: 0, slot: 1, button: 0 }); + t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_EXTRA, button: 0 }); t.game.tick(); assertEquals(t.alice.attribute(ATTRIBUTES.attack_damage), 1); assertEquals(t.alice.attribute(ATTRIBUTES.attack_speed), 4 * 1.3); @@ -36,10 +33,9 @@ Deno.test("the power glove and feral claws go in the hands slot, and only work w Deno.test("worn artifacts work again after rejoining, and say what they do", async () => { const t = await setup(); - t.send(1, { type: "mod", channel: "curios:open", data: {} }); - const { id } = opened_menu(t.take(1)); - t.send(1, { type: "click", menu: id, slot: 1, button: 0, shift: true }); - assertEquals(menu_items(t.take(1))[0].lore, "When worn:\n+4 Attack Damage"); + t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); + const worn = t.take(1).findLast((m: Msg) => m.type === "container" && m.container === "extra").items; + assertEquals(worn[0].lore, "When worn:\n+4 Attack Damage"); t.game.on_disconnect(1); t.join(1, "alice"); diff --git a/tests/base_game_test.ts b/tests/base_game_test.ts index 3e6222d..4dd4ce4 100644 --- a/tests/base_game_test.ts +++ b/tests/base_game_test.ts @@ -199,6 +199,8 @@ Deno.test("a smithing table upgrades a wooden pickaxe with 5 stone, using up exa const pickaxe = slot_of(messages, "bworld:wood_pickaxe"); const stone = slot_of(messages, "bworld:stone"); + // mods' own, like the player's curios + const containers = t.game.containers.size; t.send(1, { type: "use_block", x: 1, y: 100, z: 0, face: "top" }); const opened = opened_menu(t.take(1)); assertEquals(opened.slots.slice(0, 4).map((s: Msg) => s.output ?? false), [false, false, false, true]); @@ -225,7 +227,7 @@ Deno.test("a smithing table upgrades a wooden pickaxe with 5 stone, using up exa inventory.sort((a: Msg, b: Msg) => a.id.localeCompare(b.id)), [{ id: "bworld:stone", count: 2 }, { id: "bworld:stone_pickaxe", count: 1 }], ); - assertEquals(t.game.containers.size, 0); + assertEquals(t.game.containers.size, containers, "its slots are gone"); }); Deno.test("a smithing result can't be taken once its inputs are gone, even before it updates", async () => { diff --git a/tests/curios_test.ts b/tests/curios_test.ts index 89b313e..d381a49 100644 --- a/tests/curios_test.ts +++ b/tests/curios_test.ts @@ -1,6 +1,7 @@ -// curios: accessory slots for items in the curios tags, opened over mod channels, see mods/curios -import { assert, assertEquals } from "@std/assert"; -import { copy_dir, menu_items, opened_menu, test_game } from "./helpers.ts"; +// curios: accessory slots for items in the curios tags, next to the player's inventory, see mods/curios +import { assertEquals } from "@std/assert"; +import { PLAYER_MENU_EXTRA } from "$/common/protocol.ts"; +import { copy_dir, test_game } from "./helpers.ts"; // deno-lint-ignore no-explicit-any type Msg = any; @@ -32,45 +33,39 @@ async function setup() { return t; } -Deno.test("the curios screen shows the slot types some item goes in, with their icons", async () => { +// what's in the curios slots, the ones curios added to the player's own menu, as last synced +const curios_items = (messages: Msg[]) => last_container(messages, "extra"); + +Deno.test("the slot types some item goes in are in 2 columns left of the inventory, with their icons", async () => { const t = await setup(); - t.send(1, { type: "mod", channel: "curios:open", data: {} }); - const menu = opened_menu(t.take(1)); - assertEquals(menu.menu_type, "curios:curios"); - // in the middle of the row, then the player's inventory - assertEquals(menu.slots.slice(0, 2), [ - { x: 70, y: 17, icon: "curios:empty_curio_slot" }, - { x: 88, y: 17, icon: "curios:empty_ring_slot" }, + t.game.on_disconnect(1); + const join = t.join(1, "alice"); + assertEquals(join.player_menu, [ + { x: -45, y: 7, icon: "curios:empty_curio_slot" }, + { x: -27, y: 7, icon: "curios:empty_ring_slot" }, ]); - assertEquals(menu.slots.length, 2 + 36); }); Deno.test("items only go in the slots they fit, and fall out when the player dies", async () => { const t = await setup(); - t.send(1, { type: "mod", channel: "curios:open", data: {} }); - const { id } = opened_menu(t.take(1)); - // coal fits nowhere, the ring only in the ring slot, and #curios:curio items in any slot, the curio slot first. - // the inventory's slots come after the 2 curios ones - for (const index of [2, 0, 1]) t.send(1, { type: "click", menu: id, slot: 2 + index, button: 0, shift: true }); + // coal fits nowhere so it moves to the rest of the inventory, the ring only goes in the ring slot, and + // #curios:curio items in any slot, the curio slot first + for (const slot of [2, 0, 1]) t.send(1, { type: "click", menu: 0, slot, button: 0, shift: true }); const messages = t.take(1); - assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, { id: "bworld:coal", count: 1 }]); - const curios = menu_items(messages); - assertEquals(curios[0], { id: "jewelry:amulet", count: 1 }); - assertEquals(curios[1], { id: "jewelry:ring", count: 1 }); + assertEquals(last_container(messages, "inventory").slice(0, 3), [null, null, null]); + assertEquals(last_container(messages, "inventory")[9], { id: "bworld:coal", count: 1 }); + assertEquals(curios_items(messages), [{ id: "jewelry:amulet", count: 1 }, { id: "jewelry:ring", count: 1 }]); + + // and they come back out with a shift click, into the inventory + t.send(1, { type: "click", menu: 0, slot: PLAYER_MENU_EXTRA + 1, button: 0, shift: true }); + assertEquals(curios_items(t.take(1))[1], null); + t.send(1, { type: "click", menu: 0, slot: 0, button: 0, shift: true }); const player = t.game.players()[0]; t.game.damage_player(player, 100, "fall"); const dropped = t.game.item_entities().map((e) => e.item.type_id).sort(); assertEquals(dropped, ["bworld:coal", "jewelry:amulet", "jewelry:ring"]); - t.send(1, { type: "mod", channel: "curios:open", data: {} }); - assertEquals(menu_items(t.take(1)).filter(Boolean), []); -}); - -Deno.test("mod messages that are too big or too many are dropped", async () => { - const t = await setup(); - t.send(1, { type: "mod", channel: "curios:open", data: "x".repeat(20_000) }); - assertEquals(t.take(1).filter((m) => m.type === "open_menu"), []); - for (let i = 0; i < 100; i++) t.send(1, { type: "mod", channel: "curios:open", data: {} }); - assert(t.take(1).filter((m) => m.type === "open_menu").length < 100); + t.game.tick(); + assertEquals(curios_items(t.take(1)), [null, null]); }); diff --git a/tests/server_scripts_test.ts b/tests/server_scripts_test.ts index f7d32ad..61c3edf 100644 --- a/tests/server_scripts_test.ts +++ b/tests/server_scripts_test.ts @@ -57,6 +57,8 @@ export function setup(ctx: ServerContext) { on_use(item, params: { power: number }, player) { log("use", [item.id, params.power, player.name]); }, }); + ctx.net.on("testmod:ping", () => log("ping")); + ctx.system.run_timeout(() => log("timeout", ctx.system.current_tick), 5); const interval = ctx.system.run_interval(() => { log("interval", ctx.system.current_tick); @@ -391,3 +393,13 @@ Deno.test("menus: filters, data, buttons, closing, saving, and dropping what's i assertEquals(loaded.game.containers.size, 0); Deno.removeSync(dir, { recursive: true }); }); + +Deno.test("mod messages that are too big or too many are dropped", async () => { + const { send, log, dir } = await setup(); + send(1, { type: "mod", channel: "testmod:ping", data: "x".repeat(20_000) }); + assertEquals(log().ping, undefined); + for (let i = 0; i < 100; i++) send(1, { type: "mod", channel: "testmod:ping", data: {} }); + // 60 a second, counting the big one, and this could be split over two seconds + assert(log().ping.length > 0 && log().ping.length < 100); + Deno.removeSync(dir, { recursive: true }); +});