Change whole gui system

This commit is contained in:
2026-10-01 16:22:02 -03:00
parent 013a4fbb97
commit deba36260e
48 changed files with 1925 additions and 1302 deletions
+30 -11
View File
@@ -11,7 +11,7 @@ import { MultiPlayerGameMode } from "./game_mode.ts";
import { ClientPacketListener } from "./packet_listener.ts";
import { GameRenderer } from "./rendering/game_renderer.ts";
import { ChatComponent } from "./gui/chat_component.ts";
import { GuiInventoryScreen, GuiScreen } from "./gui/gui_screen.ts";
import { GuiMenuScreen, GuiScreen } from "./gui/gui_screen.ts";
import { GuiPlayerInventory } from "./gui/gui_player_inventory.ts";
import { GuiChat } from "./gui/gui_chat.ts";
import { InputManager } from "./input_manager.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 { PLAYER_MENU } from "$/common/protocol.ts";
import { EverythingRegistry } from "$/common/everything_registry.ts";
import type { EntityJson } from "$/common/mod_data.ts";
@@ -97,8 +98,26 @@ export class Client {
this.screens.push(screen);
}
// the player closed the one on top
pop_screen() {
this.screens.pop()?.on_close();
const screen = this.screens.pop();
screen?.on_close();
screen?.on_removed();
}
// the player closed this one, wherever it is
close_screen(screen: GuiScreen) {
if (!this.screens.includes(screen)) return;
this.screens = this.screens.filter((s) => s !== screen);
screen.on_close();
screen.on_removed();
}
// takes these off without closing them, like when the server opens a menu or closes it
remove_screens(which: (screen: GuiScreen) => boolean) {
const removed = this.screens.filter(which);
this.screens = this.screens.filter((s) => !which(s));
for (const screen of removed) screen.on_removed();
}
// leaving on purpose, from the pause screen
@@ -194,7 +213,7 @@ export class Client {
if (InputManager.is_key_pressed(options.key_inventory)) {
if (!this.screen) {
this.push_screen(new GuiPlayerInventory(player.inventories, (m) => this.connection.send(m)));
} else if (this.screen instanceof GuiInventoryScreen) {
} else if (this.screen instanceof GuiMenuScreen) {
this.pop_screen();
}
}
@@ -212,7 +231,7 @@ export class Client {
const lost_mouse = InputManager.take_lost_pointer_lock();
if (InputManager.is_key_pressed("Escape")) {
if (this.screen) {
this.pop_screen();
if (this.screen.close_on_escape()) this.pop_screen();
} else {
this.push_screen(new PauseScreen(this));
}
@@ -233,15 +252,15 @@ export class Client {
const inventories = this.player.inventories;
const screen = this.screen;
if (!screen) {
this.game_mode.drop_item(inventories.inventory, "inventory", inventories.hotbar_selected, all);
// the hotbar slot of menu 0, they're the same numbers
const slot = inventories.hotbar_selected;
this.game_mode.drop_item(inventories.inventory, slot, PLAYER_MENU, slot, all);
return;
}
const slot = screen instanceof GuiInventoryScreen ? screen.hovering : undefined;
const container = slot && screen instanceof GuiInventoryScreen
? screen.get_container(slot.container)
: undefined;
if (slot && container && !slot.output && !inventories.cursor.item) {
this.game_mode.drop_item(container, slot.container, slot.index, all);
const slot = screen instanceof GuiMenuScreen ? screen.hovering : undefined;
if (screen instanceof GuiMenuScreen && slot && !slot.output && !inventories.cursor.item) {
const index = screen.menu.slots.indexOf(slot);
this.game_mode.drop_item(slot.container, slot.index, screen.menu.id, index, all);
}
}
+4 -3
View File
@@ -3,7 +3,7 @@ import { AIR, FACE_OFFSETS, TICK_DELTA } from "$/common/constants.ts";
import type { Client } from "./client.ts";
import type { BlockHitResult } from "./level/client_level.ts";
import type { Container } from "$/common/inventory.ts";
import { AIR_ID, type ContainerKey } from "$/common/protocol.ts";
import { AIR_ID } from "$/common/protocol.ts";
import { box_overlaps_block, can_place, placement_target } from "$/common/utils.ts";
import type { EntityJson } from "$/common/mod_data.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
@@ -86,12 +86,13 @@ export class MultiPlayerGameMode {
}
// q on a slot: throws one, or the whole stack. the server spawns the item, this only takes it out right away
drop_item(container: Container, key: ContainerKey, index: number, all: boolean) {
// q on a menu's slot, whose item is in container at index on this client
drop_item(container: Container, index: number, menu: number, slot: number, all: boolean) {
const item = container.get_item(index);
if (!item) {
return;
}
this.client.connection.send({ type: "drop_item", container: key, index, all });
this.client.connection.send({ type: "drop_item", menu, slot, all });
item.amount = all ? 0 : item.amount - 1;
container.set_item(index, item.amount > 0 ? item : undefined);
}
-111
View File
@@ -1,111 +0,0 @@
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
import { canvas, draw_rect, draw_texture_region, Texture } from "$/client/renderer/mod.ts";
import { AssetManager } from "../assets.ts";
import { SLOT_SIZE } from "$/common/constants.ts";
import { ClientMessage, ScreenLayout } from "$/common/protocol.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { get_sprite_region } from "$/client/sprites.ts";
import { ClientInventories } from "../inventory.ts";
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
const MARGIN = 7 * GUI_SCALE;
const GAP = 4 * GUI_SCALE;
// where the screen's own slots start, below the player's
const AREA_Y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
// a screen opened by the server (chest, furnace, ...), drawn from the layout it sent
export class GuiContainer extends GuiInventoryScreen {
layout: ScreenLayout;
properties: Record<string, number>;
constructor(
inventories: ClientInventories,
send: (message: ClientMessage) => void,
layout: ScreenLayout,
properties: Record<string, number>,
) {
super(inventories, send);
this.layout = layout;
this.properties = properties;
this.inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
this.inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * (4 + layout.rows);
add_player_hotbar(this, MARGIN, MARGIN);
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
for (const slot of layout.slots) {
this.slots.push(
new Slot(
"screen",
slot.index,
MARGIN + slot.x * SLOT_SIZE,
AREA_Y + slot.y * SLOT_SIZE,
slot.output,
slot.icon,
),
);
}
}
override on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
this.draw_bars();
super.on_render();
}
draw_bars() {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
for (const bar of this.layout.bars) {
const x = this.x + MARGIN + bar.x * SLOT_SIZE;
const y = this.y + AREA_Y + bar.y * SLOT_SIZE;
const max = this.properties[bar.max] ?? 0;
const pct = max > 0 ? Math.max(0, Math.min(1, (this.properties[bar.value] ?? 0) / max)) : 0;
const empty = get_sprite_region(bar.empty_texture);
draw_texture_region(
atlas,
empty.x,
empty.y,
empty.width,
empty.height,
x,
y,
SLOT_SIZE,
SLOT_SIZE,
);
const full = get_sprite_region(bar.full_texture);
if (bar.direction === "right") {
draw_texture_region(
atlas,
full.x,
full.y,
full.width * pct,
full.height,
x,
y,
SLOT_SIZE * pct,
SLOT_SIZE,
);
} else {
// fills from the bottom up
draw_texture_region(
atlas,
full.x,
full.y + full.height * (1 - pct),
full.width,
full.height * pct,
x,
y + SLOT_SIZE * (1 - pct),
SLOT_SIZE,
SLOT_SIZE * pct,
);
}
}
}
}
+153
View File
@@ -0,0 +1,153 @@
// screens mods' client scripts make, see docs/modding/gui/index.md: the screens of their menus, and screens with no
// menu. a mod's screen that throws is closed, with the error in the console
import { TICK_DELTA } from "$/common/constants.ts";
import type { ClientMenu as ModClientMenu, MenuScreen, Screen } from "$/common/mod_api/client.ts";
import { canvas } from "../renderer/mod.ts";
import type { Client } from "../client.ts";
import type { ClientMenu } from "../menu.ts";
import { GuiMenuScreen, GuiScreen } from "./gui_screen.ts";
import { ModGraphics } from "./mod_graphics.ts";
import { GUI_SCALE } from "./gui_sprites.ts";
// runs on_tick 20 times a second from the frames' deltas, like the game's own ticks
class Ticker {
#pending = 0;
run(delta: number, tick: () => void) {
this.#pending += delta;
for (let i = 0; this.#pending >= TICK_DELTA && i < 10; i++) {
this.#pending -= TICK_DELTA;
tick();
}
this.#pending = Math.min(this.#pending, TICK_DELTA);
}
}
// a menu the server opened, drawn by the screen its mod registered for the menu type
export class GuiModMenuScreen extends GuiMenuScreen {
#client: Client;
#mod: string;
#screen: MenuScreen;
#ticker = new Ticker();
constructor(client: Client, mod: string, menu: ClientMenu, create: (menu: ModClientMenu) => MenuScreen) {
const send = client.connection.send.bind(client.connection);
// this, once super has run
const self: { screen?: GuiModMenuScreen } = {};
const api: ModClientMenu = {
type: menu.type,
title: menu.title,
open_data: menu.open_data,
get data() {
return menu.data;
},
click_button: (id) => {
if (!Number.isInteger(id)) throw new Error(`a menu button is a whole number, not ${id}`);
if (self.screen && client.screens.includes(self.screen)) {
send({ type: "menu_button", menu: menu.id, button: id });
}
},
close: () => {
if (self.screen) client.close_screen(self.screen);
},
};
const screen = create(api);
if (!(screen.width > 0 && screen.height > 0)) throw new Error(`the screen for ${menu.type} has no size`);
super(client.player.inventories, send, menu, screen.width, screen.height);
this.#client = client;
this.#mod = mod;
this.#screen = screen;
self.screen = this;
}
#guarded(what: string, fn: () => void) {
try {
fn();
} catch (e) {
console.error(`[${this.#mod}] the ${this.menu.type} screen's ${what} threw, closing it:`, e);
this.#client.close_screen(this);
}
}
override on_tick(delta: number): void {
super.on_tick(delta);
const tick = this.#screen.on_tick;
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
}
render_background(g: ModGraphics): void {
const render = this.#screen.on_render_background;
if (render) this.#guarded("on_render_background", () => render.call(this.#screen, g));
}
render_labels(g: ModGraphics): void {
const render = this.#screen.on_render_labels;
if (render) this.#guarded("on_render_labels", () => render.call(this.#screen, g));
}
}
// a screen with no menu, opened by a client script
export class GuiModScreen extends GuiScreen {
#mod: string;
#screen: Screen;
#client: Client;
#ticker = new Ticker();
graphics = new ModGraphics();
// the window size on_init last saw, it runs again when it changes
#size = "";
constructor(client: Client, mod: string, screen: Screen) {
super();
this.#client = client;
this.#mod = mod;
this.#screen = screen;
}
#guarded(what: string, fn: () => void) {
try {
fn();
} catch (e) {
console.error(`[${this.#mod}] a screen's ${what} threw, closing it:`, e);
this.#client.close_screen(this);
}
}
override get typing() {
return this.graphics.typing;
}
override close_on_escape(): boolean {
let close = true;
const should = this.#screen.should_close_on_escape;
if (should) this.#guarded("should_close_on_escape", () => close = should.call(this.#screen) !== false);
return close;
}
on_tick(delta: number): void {
const size = `${canvas.width}x${canvas.height}`;
if (size !== this.#size) {
this.#size = size;
const init = this.#screen.on_init;
const [w, h] = [canvas.width / GUI_SCALE, canvas.height / GUI_SCALE];
if (init) this.#guarded("on_init", () => init.call(this.#screen, w, h));
}
const tick = this.#screen.on_tick;
if (tick) this.#ticker.run(delta, () => this.#guarded("on_tick", () => tick.call(this.#screen)));
}
on_render(): void {
this.graphics.begin();
this.#guarded("on_render", () => this.#screen.on_render(this.graphics));
this.graphics.end();
}
on_close(): void {
const close = this.#screen.on_close;
if (close) this.#guarded("on_close", () => close.call(this.#screen));
}
override on_removed(): void {
const removed = this.#screen.on_removed;
if (removed) this.#guarded("on_removed", () => removed.call(this.#screen));
}
}
+15 -37
View File
@@ -1,46 +1,24 @@
import { add_player_hotbar, add_player_inventory, GuiInventoryScreen, Slot } from "./gui_screen.ts";
import { canvas, draw_rect } from "$/client/renderer/mod.ts";
import { SLOT_SIZE } from "../../common/constants.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { GuiMenuScreen } from "./gui_screen.ts";
import { ClientInventories } from "../inventory.ts";
import { ClientMessage, CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
import { ClientMessage } from "$/common/protocol.ts";
import { player_menu } from "../menu.ts";
import type { ModGraphics } from "./mod_graphics.ts";
// around the slots, and between the hotbar, the rest of the inventory and what's below, like minecraft's
const MARGIN = 7 * GUI_SCALE;
const GAP = 4 * GUI_SCALE;
// the recipes live on the server, which fills in the result slot
export class GuiPlayerInventory extends GuiInventoryScreen {
override inventory_width = MARGIN * 2 + SLOT_SIZE * 9;
override inventory_height = MARGIN * 2 + GAP * 2 + SLOT_SIZE * 7;
const WIDTH = 176;
const HEIGHT = 166;
// menu 0's screen: the crafting grid over the inventory. 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);
add_player_hotbar(this, MARGIN, MARGIN);
add_player_inventory(this, MARGIN, MARGIN + GAP + SLOT_SIZE);
const crafting_x = MARGIN;
const crafting_y = MARGIN + GAP * 2 + SLOT_SIZE * 4;
for (let i = 0; i < 3; i += 1) {
for (let j = 0; j < 3; j += 1) {
this.slots.push(
new Slot("crafting", j * 3 + i, crafting_x + i * SLOT_SIZE, crafting_y + j * SLOT_SIZE),
);
}
}
this.slots.push(
new Slot("crafting", CRAFTING_RESULT_SLOT, crafting_x + 5 * SLOT_SIZE, crafting_y + 1 * SLOT_SIZE, true),
);
super(inventories, send, player_menu(inventories), WIDTH, HEIGHT);
}
override on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
render_background(g: ModGraphics): void {
g.panel(0, 0, WIDTH, HEIGHT);
}
draw_gui_sprite("panel", this.x, this.y, this.inventory_width, this.inventory_height);
super.on_render();
render_labels(g: ModGraphics): void {
g.text(this.menu.title, 26, 6);
g.text("Inventory", 8, 73);
}
}
+122 -116
View File
@@ -1,84 +1,72 @@
import { SLOT_SIZE } from "$/common/constants.ts";
import { draw_gui_sprite, GUI_SCALE } from "./gui_sprites.ts";
import { click_slot, Container } from "$/common/inventory.ts";
import { ClientMessage, ContainerKey, CRAFTING_RESULT_SLOT } from "$/common/protocol.ts";
import { click_slot } from "$/common/inventory.ts";
import { ClientMessage, CRAFTING_RESULT_SLOT, PLAYER_MENU } from "$/common/protocol.ts";
import { point_inside_rec } from "../../common/utils.ts";
import { InputManager } from "../input_manager.ts";
import { ClientInventories } from "../inventory.ts";
import { canvas, draw_texture_region, Texture } from "../renderer/mod.ts";
import { canvas, draw_rect, draw_texture_region, Texture } from "../renderer/mod.ts";
import { AssetManager } from "../assets.ts";
import { get_sprite_region } from "../sprites.ts";
import { draw_item } 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";
import type { ClientMenu, ClientSlot } from "../menu.ts";
// how far past the slot's edge its highlight goes
const HIGHLIGHT_OVERHANG = 3 * GUI_SCALE;
export class Slot {
container: ContainerKey;
index: number;
// relative to screen top left
x: number;
y: number;
// can only be taken from, like the crafting or furnace result
output: boolean;
// a texture drawn while it's empty, like minecraft's armor slots
icon: string | undefined;
constructor(container: ContainerKey, index: number, x: number, y: number, output = false, icon?: string) {
this.container = container;
this.index = index;
this.x = x;
this.y = y;
this.output = output;
this.icon = icon;
}
}
export abstract class GuiScreen {
x: number = 0;
y: number = 0;
abstract on_tick(_delta: number): void;
abstract on_render(): void;
// the player closed it
abstract on_close(): void;
// it's gone for any reason, after on_close when the player closed it
on_removed(): void {}
// something in it has the keyboard, like a text field, so keybinds (inventory, drop) don't fire
get typing(): boolean {
return false;
}
close_on_escape(): boolean {
return true;
}
}
// a screen of slots. the server owns the contents: clicks are sent to it and guessed locally
// so they feel instant, then whatever the server syncs back wins
export class GuiInventoryScreen extends GuiScreen {
// a menu's screen, like minecraft's AbstractContainerScreen: in the middle of the window, it draws the menu's slots,
// the item on the cursor and tooltips, and sends clicks. the server owns what's in the slots: clicks are guessed
// locally so they feel instant, then whatever the server syncs back wins. subclasses draw the rest
export abstract class GuiMenuScreen extends GuiScreen {
inventories: ClientInventories;
send: (message: ClientMessage) => void;
menu: ClientMenu;
// in gui pixels
width: number;
height: number;
slots: Slot[] = [];
hovering: Slot | undefined;
inventory_width: number = 500;
inventory_height: number = 500;
// what mods draw over it, like a recipe viewer
hovering: ClientSlot | undefined;
// what the screen and mods draw with, in gui pixels
graphics = new ModGraphics();
constructor(inventories: ClientInventories, send: (message: ClientMessage) => void) {
constructor(
inventories: ClientInventories,
send: (message: ClientMessage) => void,
menu: ClientMenu,
width: number,
height: number,
) {
super();
this.inventories = inventories;
this.send = send;
}
get_container(key: ContainerKey): Container | undefined {
switch (key) {
case "inventory":
return this.inventories.inventory;
case "crafting":
return this.inventories.crafting;
case "screen":
return this.inventories.screen;
}
this.menu = menu;
this.width = width;
this.height = height;
}
override get typing() {
@@ -86,40 +74,29 @@ export class GuiInventoryScreen extends GuiScreen {
}
on_tick(_delta: number): void {
this.x = canvas.width / 2 - (this.inventory_width / 2);
this.y = canvas.height / 2 - (this.inventory_height / 2);
this.x = Math.floor((canvas.width - this.width * GUI_SCALE) / 2);
this.y = Math.floor((canvas.height - this.height * GUI_SCALE) / 2);
}
on_render(): void {
for (const slot of this.slots) {
draw_gui_sprite("slot", this.x + slot.x, this.y + slot.y);
}
// under the slots, from the screen's top left
abstract render_background(g: ModGraphics): void;
// over the slots
abstract render_labels(g: ModGraphics): void;
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
if (this.hovering) {
const x = this.x + this.hovering.x - HIGHLIGHT_OVERHANG;
draw_gui_sprite(sprite, x, this.y + this.hovering.y - HIGHLIGHT_OVERHANG);
}
};
highlight("slot_highlight_back");
for (const slot of this.slots) {
const item = this.get_container(slot.container)?.get_item(slot.index);
if (item) {
draw_item(item, this.x + slot.x, this.y + slot.y);
} else if (slot.icon) {
// where an item's sprite would be
const icon = get_sprite_region(slot.icon);
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const [x, y, size] = [this.x + slot.x + 3, this.y + slot.y + 3, SLOT_SIZE - 6];
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
}
}
highlight("slot_highlight_front");
on_render(): void {
draw_rect(0, 0, canvas.width, canvas.height, [0, 0, 0, 0.8]);
const g = this.graphics;
g.begin();
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 (this.graphics.mouse_blocked()) {
if (g.mouse_blocked()) {
this.hovering = undefined;
} else {
this.handle_interaction();
@@ -130,28 +107,62 @@ export class GuiInventoryScreen extends GuiScreen {
draw_item(this.inventories.cursor.item, mouse.x, mouse.y);
} else if (this.hovering) {
// what's in the slot under the mouse, while not carrying anything
const item = this.get_container(this.hovering.container)?.get_item(this.hovering.index);
const item = this.hovering.container.get_item(this.hovering.index);
if (item) {
draw_tooltip(item_tooltip(item), mouse.x, mouse.y);
}
}
this.graphics.end();
g.end();
}
#slot_x(slot: ClientSlot) {
return this.x + slot.x * GUI_SCALE;
}
#slot_y(slot: ClientSlot) {
return this.y + slot.y * GUI_SCALE;
}
#render_slots() {
for (const slot of this.menu.slots) {
draw_gui_sprite("slot", this.#slot_x(slot), this.#slot_y(slot));
}
// like minecraft's, the highlight is a bit bigger than the slot, part of it under the item and part over
const highlight = (sprite: "slot_highlight_back" | "slot_highlight_front") => {
if (this.hovering) {
const x = this.#slot_x(this.hovering) - HIGHLIGHT_OVERHANG;
draw_gui_sprite(sprite, x, this.#slot_y(this.hovering) - HIGHLIGHT_OVERHANG);
}
};
highlight("slot_highlight_back");
for (const slot of this.menu.slots) {
const item = slot.container.get_item(slot.index);
if (item) {
draw_item(item, this.#slot_x(slot), this.#slot_y(slot));
} else if (slot.icon) {
// where an item's sprite would be
const icon = get_sprite_region(slot.icon);
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const [x, y, size] = [this.#slot_x(slot) + 3, this.#slot_y(slot) + 3, SLOT_SIZE - 6];
draw_texture_region(atlas, icon.x, icon.y, icon.width, icon.height, x, y, size, size);
}
}
highlight("slot_highlight_front");
}
#render_overlays() {
const g = this.graphics;
g.begin();
const hovered = this.hovering && this.get_container(this.hovering.container)?.get_item(this.hovering.index);
const hovered = this.hovering && this.hovering.container.get_item(this.hovering.index);
const view = {
x: this.x,
y: this.y,
width: this.inventory_width,
height: this.inventory_height,
x: this.x / GUI_SCALE,
y: this.y / GUI_SCALE,
width: this.width,
height: this.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);
entry.overlay.on_render(this.graphics, 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);
@@ -160,19 +171,32 @@ export class GuiInventoryScreen extends GuiScreen {
}
}
override on_removed(): void {
for (const entry of [...inventory_overlays]) {
try {
entry.overlay.on_close?.();
} catch (e) {
console.error(`[${entry.mod}] inventory overlay's on_close threw, removing it:`, e);
inventory_overlays.splice(inventory_overlays.indexOf(entry), 1);
}
}
}
on_close(): void {
this.send({ type: "close_screen" });
this.send({ type: "close_menu", menu: this.menu.id });
// the server puts these back in the inventory, show it right away
const { inventory, crafting, cursor } = this.inventories;
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
const item = crafting.get_item(i);
if (item) {
inventory.add_item(item);
crafting.set_item(i, undefined);
if (this.menu.id === PLAYER_MENU) {
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
const item = crafting.get_item(i);
if (item) {
inventory.add_item(item);
crafting.set_item(i, undefined);
}
}
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
}
crafting.set_item(CRAFTING_RESULT_SLOT, undefined);
if (cursor.item) {
inventory.add_item(cursor.item);
cursor.item = undefined;
@@ -183,9 +207,9 @@ export class GuiInventoryScreen extends GuiScreen {
this.hovering = undefined;
const mouse = InputManager.get_mouse_position();
for (const slot of this.slots) {
const hovering = point_inside_rec(mouse.x, mouse.y, this.x + slot.x, this.y + slot.y, SLOT_SIZE, SLOT_SIZE);
if (!hovering) {
for (const [index, slot] of this.menu.slots.entries()) {
const [x, y] = [this.#slot_x(slot), this.#slot_y(slot)];
if (!point_inside_rec(mouse.x, mouse.y, x, y, SLOT_SIZE, SLOT_SIZE)) {
continue;
}
this.hovering = slot;
@@ -193,40 +217,22 @@ export class GuiInventoryScreen extends GuiScreen {
for (const button of [0, 2]) {
if (InputManager.is_mouse_pressed(button)) {
InputManager.consume_mouse(button);
this.click(slot, button);
this.click(index, button);
return;
}
}
}
}
click(slot: Slot, button: number) {
click(index: number, button: number) {
const slot = this.menu.slots[index];
const shift = InputManager.is_key_down("ShiftLeft") || InputManager.is_key_down("ShiftRight");
this.send({ type: "click", container: slot.container, index: slot.index, button, shift });
this.send({ type: "click", menu: this.menu.id, slot: index, button, shift });
// output slots depend on server side things like recipes, and where a shift click goes on slot filters only the
// server has, just wait for the server
const container = this.get_container(slot.container);
if (container && !slot.output && !shift) {
click_slot(container, slot.index, this.inventories.cursor, button);
if (!slot.output && !shift) {
click_slot(slot.container, slot.index, this.inventories.cursor, button);
}
}
}
// generic methods that is often needed
export function add_player_inventory(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
for (let i = 0; i < 3; ++i) {
for (let l = 0; l < 9; ++l) {
handler.slots.push(
new Slot("inventory", l + i * 9 + 9, offset_x + l * SLOT_SIZE, offset_y + i * SLOT_SIZE),
);
}
}
}
export function add_player_hotbar(handler: GuiInventoryScreen, offset_x: number, offset_y: number) {
for (let i = 0; i < 9; ++i) {
handler.slots.push(new Slot("inventory", i, offset_x + i * SLOT_SIZE, offset_y));
}
}
+64 -43
View File
@@ -1,6 +1,6 @@
// 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 } from "$/common/constants.ts";
// one per screen, so text inputs keep their text and focus while it's open. mods work in gui pixels, GUI_SCALE canvas
// pixels each
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";
@@ -30,28 +30,39 @@ const GREY: Color = [0.66, 0.66, 0.66, 1];
const INPUT_HEIGHT = 32;
const FIELD_BORDER = GUI_ATLAS.text_field.border[0] * GUI_SCALE;
// gui pixels to the canvas's, see GUI_SCALE
const S = GUI_SCALE;
export class ModGraphics implements Graphics {
// where gui pixel 0, 0 is on the canvas: a menu screen's top left, or the window's
origin_x = 0;
origin_y = 0;
// text inputs by id, and which one has the keyboard
#inputs = new Map<string, TextInput>();
#focused: string | undefined;
#tooltip: { lines: TooltipLine[]; x: number; y: number } | undefined;
// areas the screen underneath shouldn't take the mouse in, this frame
// areas the screen underneath shouldn't take the mouse in this frame, on the canvas
#blocked: { x: number; y: number; w: number; h: number }[] = [];
#clicks_consumed = false;
// the whole window, in gui pixels
get width() {
return canvas.width;
return canvas.width / S;
}
get height() {
return canvas.height;
return canvas.height / S;
}
get text_height() {
return TEXT_HEIGHT * TEXT_SCALE / S;
}
get mouse() {
const { x, y } = InputManager.get_mouse_position();
return {
x,
y,
x: (x - this.origin_x) / S,
y: (y - this.origin_y) / S,
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),
@@ -77,39 +88,49 @@ export class ModGraphics implements Graphics {
// whether the screen underneath should ignore the mouse
mouse_blocked() {
const { x, y } = this.mouse;
const { x, y } = InputManager.get_mouse_position();
return this.#clicks_consumed || this.#blocked.some((r) => point_inside_rec(x, y, r.x, r.y, r.w, r.h));
}
// a gui position on the canvas
#x(x: number) {
return this.origin_x + x * S;
}
#y(y: number) {
return this.origin_y + y * S;
}
rect(x: number, y: number, w: number, h: number, color: Color = WHITE) {
draw_rect(x, y, w, h, color);
draw_rect(this.#x(x), this.#y(y), w * S, h * S, color);
}
panel(x: number, y: number, w: number, h: number) {
draw_gui_sprite("panel", x, y, w, h);
draw_gui_sprite("panel", this.#x(x), this.#y(y), w * S, h * S);
}
text(text: string, x: number, y: number, options: { scale?: number; color?: Color } = {}) {
draw_text(text, x, y, options.scale ?? TEXT_SCALE, options.color ?? WHITE);
draw_text(text, this.#x(x), this.#y(y), TEXT_SCALE * (options.scale ?? 1), options.color ?? WHITE);
}
measure_text(text: string, scale = TEXT_SCALE) {
return measure_text(text, scale);
measure_text(text: string, scale = 1) {
return measure_text(text, TEXT_SCALE * scale) / S;
}
texture(id: string, x: number, y: number, w: number, h: number) {
texture(id: string, x: number, y: number, w: number, h: number, part = [0, 0, 1, 1]) {
const atlas = AssetManager.instance.get<Texture>("bworld:textures");
const region = get_sprite_region(id);
const [u, v, pw, ph] = part;
draw_texture_region(
atlas,
region.x,
region.y,
region.width,
region.height,
x,
y,
w,
h,
region.x + region.width * u,
region.y + region.height * v,
region.width * pw,
region.height * ph,
this.#x(x),
this.#y(y),
w * S,
h * S,
);
}
@@ -118,10 +139,14 @@ export class ModGraphics implements Graphics {
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);
draw_item(stack, this.#x(x), this.#y(y));
}
clip(x: number, y: number, w: number, h: number, draw: () => void) {
this.#clip_canvas(this.#x(x), this.#y(y), w * S, h * S, draw);
}
#clip_canvas(x: number, y: number, w: number, h: number, draw: () => void) {
begin_clip(x, y, w, h);
try {
draw();
@@ -132,9 +157,10 @@ export class ModGraphics implements Graphics {
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);
draw_gui_sprite(hovered ? "button_highlighted" : "button", x, y, w, h);
const [cx, cy, cw, ch] = [this.#x(x), this.#y(y), w * S, h * S];
draw_gui_sprite(hovered ? "button_highlighted" : "button", cx, cy, cw, ch);
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);
draw_text(label, cx + (cw - text_width) / 2, cy + (ch - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE, WHITE);
if (hovered && this.mouse.pressed) {
this.consume_click();
return true;
@@ -142,15 +168,17 @@ export class ModGraphics implements Graphics {
return false;
}
// INPUT_HEIGHT canvas pixels tall
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);
const [cx, cy, cw] = [this.#x(x), this.#y(y), w * S];
const hovered = point_inside_rec(this.mouse.x, this.mouse.y, x, y, w, INPUT_HEIGHT / S);
if (this.#focused === id || (hovered && this.mouse.pressed)) {
input.handle_mouse({ x, y, width: w, height: INPUT_HEIGHT }, x + 6);
input.handle_mouse({ x: cx, y: cy, width: cw, height: INPUT_HEIGHT }, cx + 6);
}
if (this.mouse.pressed) {
if (hovered) {
@@ -169,15 +197,15 @@ export class ModGraphics implements Graphics {
}
}
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", x, y, w, INPUT_HEIGHT);
draw_gui_sprite(focused ? "text_field_highlighted" : "text_field", cx, cy, cw, INPUT_HEIGHT);
// inside the field's border, so long text doesn't go over it
this.clip(x + FIELD_BORDER, y + 2, w - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
this.#clip_canvas(cx + FIELD_BORDER, cy + 2, cw - FIELD_BORDER * 2, INPUT_HEIGHT - 4, () => {
if (focused) {
input.draw_selection(x + 6, y + 6, INPUT_HEIGHT - 12);
input.draw_selection(cx + 6, cy + 6, INPUT_HEIGHT - 12);
}
draw_text(input.value, x + 6, y + 4, TEXT_SCALE, WHITE);
draw_text(input.value, cx + 6, cy + 4, TEXT_SCALE, WHITE);
if (focused && TextInput.caret_visible()) {
draw_rect(input.caret_x(x + 6), y + 6, 2, INPUT_HEIGHT - 12, WHITE);
draw_rect(input.caret_x(cx + 6), cy + 6, 2, INPUT_HEIGHT - 12, WHITE);
}
});
return input.value;
@@ -187,10 +215,6 @@ export class ModGraphics implements Graphics {
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);
}
@@ -202,8 +226,8 @@ export class ModGraphics implements Graphics {
? { text: line, color: WHITE }
: { text: line.text, color: line.color ?? WHITE }
),
x,
y,
x: this.#x(x),
y: this.#y(y),
};
}
@@ -214,11 +238,11 @@ export class ModGraphics implements Graphics {
typeof line === "string" ? { text: line, color: GREY } : { text: line.text, color: line.color ?? GREY }
),
];
this.#tooltip = { lines, x, y };
this.#tooltip = { lines, x: this.#x(x), y: this.#y(y) };
}
block_mouse(x: number, y: number, w: number, h: number) {
this.#blocked.push({ x, y, w, h });
this.#blocked.push({ x: this.#x(x), y: this.#y(y), w: w * S, h: h * S });
}
consume_click() {
@@ -227,6 +251,3 @@ export class ModGraphics implements Graphics {
InputManager.consume_mouse(2);
}
}
// how big an item is drawn, for laying out around g.item
export const ITEM_SIZE = SLOT_SIZE;
-2
View File
@@ -4,8 +4,6 @@ import { Container, Cursor } from "$/common/inventory.ts";
export class ClientInventories {
inventory = new Container(9 * 4);
crafting = new Container(10);
// the open server screen's container
screen: Container | undefined;
cursor: Cursor = { item: undefined };
hotbar_selected = 0;
}
+86
View File
@@ -0,0 +1,86 @@
// 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 type { ClientInventories } from "./inventory.ts";
export interface ClientSlot {
// where its item is on this client
container: Container;
index: number;
// gui pixels from the screen's top left to its frame
x: number;
y: number;
// can only be taken from, like the crafting or furnace result
output: boolean;
// a texture drawn while it's empty, like minecraft's armor slots
icon: string | undefined;
}
export class ClientMenu {
readonly id: number;
readonly type: string;
readonly title: string;
readonly open_data: unknown;
data: Record<string, number>;
slots: ClientSlot[];
constructor(
id: number,
type: string,
title: string,
open_data: unknown,
slots: ClientSlot[],
data: Record<string, number> = {},
) {
this.id = id;
this.type = type;
this.title = title;
this.open_data = open_data;
this.slots = slots;
this.data = data;
}
// one the server opened: its slots' items come in menu_content, into a container of its own
static opened(id: number, type: string, title: string, open_data: unknown, slots: MenuSlotInfo[]) {
const items = new Container(slots.length);
return new ClientMenu(
id,
type,
title,
open_data,
slots.map((slot, index) => ({
container: items,
index,
x: slot.x,
y: slot.y,
output: slot.output === true,
icon: slot.icon,
})),
);
}
}
// 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
export function player_menu(inventories: ClientInventories): ClientMenu {
const slot = (container: Container, index: number, x: number, y: number, output = false): ClientSlot => ({
container,
index,
x,
y,
output,
icon: undefined,
});
const slots: ClientSlot[] = [];
for (let i = 0; i < 36; i++) {
const row = Math.floor(i / 9);
slots.push(slot(inventories.inventory, i, 7 + (i % 9) * 18, i < 9 ? 141 : 83 + (row - 1) * 18));
}
for (let i = 0; i < CRAFTING_RESULT_SLOT; i++) {
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");
return new ClientMenu(PLAYER_MENU, "", "Crafting", null, slots);
}
+22 -9
View File
@@ -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, InventoryOverlay } from "$/common/mod_api/client.ts";
import type { ClientContext, ClientMenu, InventoryOverlay, 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";
@@ -10,6 +10,7 @@ import { tag_api } from "$/common/tags.ts";
import { AIR_ID } from "$/common/protocol.ts";
import type { Client } from "./client.ts";
import { code_url, fetch_verified } from "./handshake.ts";
import { GuiModScreen } from "./gui/gui_mod_screens.ts";
// each loaded mod's credits file, for the credits screen
export const mod_credits: { name: string; version: string; text: string }[] = [];
@@ -20,6 +21,9 @@ let client: Client | undefined;
// what mods draw on inventory screens, see GuiInventoryScreen
export const inventory_overlays: { mod: string; overlay: InventoryOverlay }[] = [];
// each menu type's screen, see ctx.ui.register_menu_screen
export const menu_screens = new Map<string, { mod: string; create: (menu: ClientMenu) => MenuScreen }>();
// mod channels, see ctx.net: who listens on each channel
const net_handlers = new Map<string, { mod: string; handler: (data: unknown) => void }[]>();
@@ -68,6 +72,7 @@ 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;
menu_screens.clear();
net_handlers.clear();
mod_names.clear();
for (const listing of listings) mod_names.set(listing.id, listing.name);
@@ -101,12 +106,9 @@ 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, see docs/modding_plan.md)`);
};
const own = (channel: string) => {
if (!channel.startsWith(`${mod}:`)) {
throw new Error(`[${mod}] channel ${channel} must be in the namespace "${mod}"`);
const own = (id: string, what = "channel") => {
if (!id.startsWith(`${mod}:`)) {
throw new Error(`[${mod}] ${what} ${id} must be in the namespace "${mod}"`);
}
};
const known_item = (id: string) => {
@@ -118,8 +120,19 @@ function client_context(listing: ModListing): ClientContext {
return {
mod: { id: mod, version: listing.version },
ui: {
register_screen: not_yet_fn("register_screen"),
open: not_yet_fn("open"),
register_menu_screen(type, create) {
own(type, "menu type");
if (menu_screens.has(type)) throw new Error(`[${mod}] ${type} already has a screen`);
menu_screens.set(type, { mod, create });
},
open(screen) {
if (typeof screen?.on_render !== "function") throw new Error(`[${mod}] a screen needs an on_render`);
const game = need_client();
game.push_screen(new GuiModScreen(game, mod, screen));
},
close() {
need_client().pop_screen();
},
add_inventory_overlay(overlay) {
inventory_overlays.push({ mod, overlay });
},
+48 -26
View File
@@ -1,13 +1,14 @@
import type { ServerMessage } from "$/common/protocol.ts";
import { Container, ItemStack } from "$/common/inventory.ts";
import { ItemStack } from "$/common/inventory.ts";
import type { Client } from "./client.ts";
import { GuiContainer } from "./gui/gui_container.ts";
import { GuiModMenuScreen } from "./gui/gui_mod_screens.ts";
import { ClientMenu } from "./menu.ts";
import { GuiChat } from "./gui/gui_chat.ts";
import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import { Player } from "./entity/player.ts";
import { receive_mod_message } from "./mods.ts";
import { menu_screens, receive_mod_message } from "./mods.ts";
// minecraft's ChunkBatchSizeCalculator: how long loading a chunk takes here, so the server sends as many a tick as
// fit in CHUNK_BUDGET_MS
@@ -197,32 +198,24 @@ export class ClientPacketListener {
client.screen.receive_suggestions(message);
}
break;
case "container": {
let container = message.container === "screen" ? inventories.screen : inventories[message.container];
if (message.container === "screen" && container?.size !== message.items.length) {
container = inventories.screen = new Container(message.items.length);
}
container?.load(message.items);
case "container":
inventories[message.container]?.load(message.items);
break;
}
case "cursor":
inventories.cursor.item = message.item ? ItemStack.from_data(message.item) : undefined;
break;
case "open_screen": {
// replace anything open locally without telling the server, it just opened this one
client.screens.length = 0;
const size = Math.max(0, ...message.layout.slots.map((slot) => slot.index + 1));
inventories.screen = new Container(size);
client.push_screen(
new GuiContainer(inventories, (m) => client.connection.send(m), message.layout, message.properties),
);
case "open_menu":
this.#open_menu(message);
break;
case "menu_content": {
const menu = this.#menu(message.id);
// every slot's item is in the menu's own container, at the slot's index
menu?.slots[0]?.container.load(message.items);
break;
}
case "screen_properties": {
const screen = client.screen;
if (screen instanceof GuiContainer) {
screen.properties = message.properties;
}
case "menu_data": {
const menu = this.#menu(message.id);
if (menu) menu.data = message.data;
break;
}
case "teleport": {
@@ -243,11 +236,40 @@ export class ClientPacketListener {
case "mod":
receive_mod_message(message.channel, message.data);
break;
case "close_screen":
case "close_menu":
// closed by the server (the block broke), it already put everything back
client.screens = client.screens.filter((s) => !(s instanceof GuiContainer));
inventories.screen = undefined;
client.remove_screens((s) => s instanceof GuiModMenuScreen && s.menu.id === message.id);
break;
}
}
// the open menu with this id, if it's still open here
#menu(id: number): ClientMenu | undefined {
const screen = this.client.screens.find((s) => s instanceof GuiModMenuScreen && s.menu.id === id);
return (screen as GuiModMenuScreen | undefined)?.menu;
}
#open_menu(message: Extract<ServerMessage, { type: "open_menu" }>) {
const client = this.client;
const close = () => client.connection.send({ type: "close_menu", menu: message.id });
const registered = menu_screens.get(message.menu_type);
if (!registered) {
console.error(`No screen for the menu type ${message.menu_type}, closing it`);
close();
return;
}
const menu = ClientMenu.opened(message.id, message.menu_type, message.title, message.open_data, message.slots);
menu.data = message.data;
let screen: GuiModMenuScreen;
try {
screen = new GuiModMenuScreen(client, registered.mod, menu, registered.create);
} catch (e) {
console.error(`[${registered.mod}] the ${message.menu_type} screen threw, closing it:`, e);
close();
return;
}
// replace anything open locally without telling the server, it just opened this one
client.remove_screens(() => true);
client.push_screen(screen);
}
}