Files
bworld/client/client.ts
T
2026-11-06 22:49:43 -03:00

407 lines
14 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
import { ClientLevel } from "./level/client_level.ts";
import type { BlockHitResult } from "./level/client_level.ts";
import { LocalPlayer } from "./entity/local_player.ts";
import { RemotePlayer } from "./entity/remote_player.ts";
import { ItemEntity } from "./entity/item_entity.ts";
import { RemoteEntity } from "./entity/remote_entity.ts";
import type { Entity } from "./entity/entity.ts";
import { Camera } from "./camera.ts";
import { Options } from "./options.ts";
import { MultiPlayerGameMode } from "./game_mode.ts";
import { ClientPacketListener } from "./packet_listener.ts";
import { profiler } from "./profiler.ts";
import { GameRenderer } from "./rendering/game_renderer.ts";
import { ChatComponent } from "./gui/chat_component.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";
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 { type BlockRegistry, EverythingRegistry } from "@/common/everything_registry.ts";
import type { EntityJson } from "@/common/mod_data.ts";
import { tick_texture_animations } from "./texture_animations.ts";
import type { RenderBenchmark } from "./benchmark/benchmark.ts";
// holding the use button uses the held item on blocks again this often, like minecraft's 4 ticks
const USE_REPEAT_MS = 200;
// after a long stall (a hidden tab, a debugger) the game skips ahead instead of running every missed tick at once
const MAX_TICKS_PER_FRAME = 10;
// the game client, like minecraft's Minecraft class: owns the level, the player, the screens and the renderer.
// the game runs in fixed ticks (TICKS_PER_SECOND), input and drawing happen every frame
export class Client {
connection: Connection;
options = new Options();
level: ClientLevel;
player: LocalPlayer;
camera = new Camera();
game_mode: MultiPlayerGameMode;
packet_listener: ClientPacketListener;
game_renderer = new GameRenderer();
chat = new ChatComponent();
// open screens, the last one is on top and gets the input
screens: GuiScreen[] = [];
// what the player is looking at, updated every frame
hit_result: BlockHitResult | undefined;
// the entity or other player being looked at, closer than any block. hit_result is undefined then
entity_hit: Entity | undefined;
debugging = false;
// started from the f3 performance window
benchmark: RenderBenchmark | undefined;
// seconds of game time not ticked yet
#pending_time = 0;
// whether the attack button is held on a block, breaking it advances every tick
#attacking = false;
// when holding the use button on a block uses it again, see USE_REPEAT_MS
#next_use = 0;
// a use was sent and the use button hasn't been let go of since, see #handle_block_interaction
#use_held = false;
#stopped = false;
// the render distance the server was last told, it sends chunks for it
#sent_view_distance: number;
// called once when the connection drops, with why
#on_disconnect: (message: string) => void;
constructor(connection: Connection, on_disconnect: (message: string) => void) {
this.connection = connection;
this.#on_disconnect = on_disconnect;
this.level = new ClientLevel(connection.server_blocks, connection.shape, this.options.render_distance);
this.level.time = connection.time;
this.#sent_view_distance = this.options.render_distance;
const spawn = connection.spawn;
this.player = new LocalPlayer(this, connection.id, connection.name);
this.player.set_position(spawn.x, spawn.y, spawn.z);
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));
}
for (const info of connection.initial_entities) {
this.level.add_entity(
info.kind === "item" ? new ItemEntity(this.level, info) : new RemoteEntity(this.level, info),
);
}
this.game_mode = new MultiPlayerGameMode(this);
this.packet_listener = new ClientPacketListener(this);
}
get screen(): GuiScreen | undefined {
return this.screens.at(-1);
}
push_screen(screen: GuiScreen) {
this.screens.push(screen);
}
// the player closed the one on top
pop_screen() {
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
disconnect() {
this.#stopped = true;
this.connection.close();
back_to_title();
}
#stop() {
this.#stopped = true;
this.level.dispose();
InputManager.set_mouse_grabbed(false);
}
// one frame: input, as many ticks as are due, then drawing between the last tick and the next. while the benchmark
// runs, it ticks and draws its own level instead and the world waits, so what's around the player doesn't change
// its numbers
run_frame(delta: number) {
if (this.#stopped) {
return;
}
if (this.benchmark) {
this.benchmark.frame();
} else {
const screen = this.screen;
this.screen?.on_tick(delta);
// a screen that closed itself just now, like chat on enter, had this frame's keys
this.#handle_keybinds(screen !== undefined && this.screen === undefined);
}
this.#pending_time += delta;
let ticks = 0;
const stopped = profiler.section("ticks", () => {
while (this.#pending_time >= TICK_DELTA && ticks < MAX_TICKS_PER_FRAME) {
if (this.benchmark) this.benchmark.tick();
else this.tick();
if (this.#stopped) {
return true;
}
this.#pending_time -= TICK_DELTA;
ticks += 1;
}
return false;
});
if (stopped) {
return;
}
if (ticks === MAX_TICKS_PER_FRAME) {
this.#pending_time = Math.min(this.#pending_time, TICK_DELTA);
}
if (this.benchmark) this.benchmark.render(this.#pending_time / TICK_DELTA);
else this.game_renderer.render(this, this.#pending_time / TICK_DELTA);
}
// one step of the game: what the server sent (chunks included), breaking, then every entity
tick() {
this.packet_listener.handle_packets();
if (this.connection.closed) {
this.#stop();
this.#on_disconnect("Lost connection to the server");
return;
}
if (this.#attacking && this.hit_result) {
this.game_mode.continue_destroy_block(this.hit_result);
}
const view_distance = Math.round(this.options.render_distance);
if (view_distance !== this.#sent_view_distance) {
this.#sent_view_distance = view_distance;
this.level.view_distance = view_distance;
this.connection.send({ type: "view_distance", distance: view_distance });
}
this.level.tick();
tick_texture_animations();
}
// closed_screen: a screen closed this frame and took its keys, so they don't also open the inventory or pick a
// hotbar slot. typing "/give pickaxe" and enter in the same slow frame would otherwise open the inventory
#handle_keybinds(closed_screen: boolean) {
const player = this.player;
// typing into a screen's text field, keys are letters, not keybinds
if (!closed_screen && !this.screen?.typing) {
this.#handle_keys();
}
if (InputManager.is_mouse_grabbed()) {
const mouse = InputManager.get_look_delta();
player.turn(mouse.x, mouse.y);
}
InputManager.set_mouse_grabbed(!this.screen);
this.#pick();
this.#handle_block_interaction();
if (!this.screen && !closed_screen) {
this.#handle_hotbar();
}
}
#handle_keys() {
const options = this.options;
const player = this.player;
if (InputManager.is_key_pressed(options.key_inventory)) {
if (!this.screen) {
this.push_screen(new GuiPlayerInventory(player, (m) => this.connection.send(m)));
} else if (this.screen instanceof GuiMenuScreen) {
this.pop_screen();
}
}
if (InputManager.is_key_pressed(options.key_drop)) {
this.#handle_drop();
}
if (InputManager.is_key_pressed(options.key_chat) && !this.screen) {
this.push_screen(new GuiChat(this));
}
// straight into a command, like minecraft
if (InputManager.is_key_pressed("Slash") && !this.screen) {
this.push_screen(new GuiChat(this, "/"));
}
// browsers eat the escape that lets go of the mouse, so losing the mouse pauses too
const lost_mouse = InputManager.take_lost_pointer_lock();
if (InputManager.is_key_pressed("Escape")) {
if (this.screen) {
if (this.screen.close_on_escape()) this.pop_screen();
} else {
this.push_screen(new PauseScreen(this));
}
} else if (lost_mouse && !this.screen) {
this.push_screen(new PauseScreen(this));
}
if (InputManager.is_key_pressed(options.key_debug)) {
this.debugging = !this.debugging;
}
if (InputManager.is_key_pressed(options.key_fullscreen)) {
InputManager.toggle_fullscreen();
}
}
// the held item while playing, the slot under the mouse in an inventory (only with nothing on the cursor)
#handle_drop() {
const all = InputManager.is_key_down("ControlLeft") || InputManager.is_key_down("ControlRight");
const inventories = this.player.inventories;
const screen = this.screen;
if (!screen) {
// 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 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);
}
}
// what's under the crosshair: an entity, or the first block in front of it
#pick() {
const player = this.player;
const eye_y = player.y + player.eye_height;
const picked = this.level.pick_entity(
player.x,
eye_y,
player.z,
player.yaw,
player.pitch,
player.entity_interaction_range,
(entity) =>
entity instanceof RemotePlayer ||
(entity instanceof RemoteEntity && !entity.dead && is_hittable(entity)),
);
// a block in front of the entity hides it
this.hit_result = this.level.pick(
player.x,
eye_y,
player.z,
player.yaw,
player.pitch,
picked?.distance ?? player.block_interaction_range,
this.game_mode.held_item()?.targets_fluids,
);
this.entity_hit = picked && !this.hit_result ? picked.entity : undefined;
}
// clicks happen right away, holding to break advances in tick()
#handle_block_interaction() {
const hit = this.hit_result;
const attacking = !this.screen && InputManager.is_mouse_down(0);
this.#attacking = attacking;
if (!attacking || !hit) {
this.game_mode.stop_destroy_block();
}
// letting go stops using an item over time, like shooting a bow, even with a screen open by then. the server
// may not have said it's using one yet, so it's sent after every use
if (this.#use_held && !InputManager.is_mouse_down(2)) {
this.#use_held = false;
this.connection.send({ type: "release_use" });
}
if (this.screen) {
return;
}
// a click uses right away, holding it on blocks keeps using every USE_REPEAT_MS. not while it's using an item
const now = performance.now();
const use_pressed = InputManager.is_mouse_pressed(2) && !this.player.using_item;
const using = use_pressed ||
(hit && InputManager.is_mouse_down(2) && now >= this.#next_use && !this.player.using_item);
if (using) {
this.#next_use = now + USE_REPEAT_MS;
this.#use_held = true;
}
// the held item swings on every click and use, and keeps swinging while breaking, like minecraft
if (InputManager.is_mouse_pressed(0) || using || (attacking && hit)) {
this.game_renderer.hand.swing();
}
if (this.entity_hit && InputManager.is_mouse_pressed(0)) {
this.game_mode.attack(this.entity_hit);
}
if (hit) {
if (InputManager.is_mouse_pressed(0)) {
this.game_mode.start_destroy_block(hit);
}
if (!attacking && using) {
this.game_mode.use_item_on(hit);
}
} else if (use_pressed) {
this.game_mode.use_item();
} else if (!this.entity_hit && InputManager.is_mouse_pressed(0)) {
this.game_mode.swing();
}
}
#handle_hotbar() {
const inventories = this.player.inventories;
const previous = inventories.hotbar_selected;
const scroll = InputManager.get_wheel_delta();
// at a block that takes the mouse wheel, like a pulse repeater's delay, it goes to the block instead
const hit = this.hit_result;
if (scroll !== 0 && hit && EverythingRegistry.get_by_id<BlockRegistry>("blocks", hit.block)?.scrollable) {
const { x, y, z, face } = hit;
this.connection.send({ type: "scroll_block", x, y, z, face, hit: hit.hit, amount: scroll < 0 ? 1 : -1 });
} else if (scroll > 0) {
inventories.hotbar_selected = Math.min(8, inventories.hotbar_selected + 1);
} else if (scroll < 0) {
inventories.hotbar_selected = Math.max(0, inventories.hotbar_selected - 1);
}
const pressed = this.options.key_hotbar.findIndex((key) => InputManager.is_key_pressed(key));
if (pressed !== -1) {
inventories.hotbar_selected = pressed;
}
if (inventories.hotbar_selected !== previous) {
this.connection.send({ type: "select_slot", slot: inventories.hotbar_selected });
// the server starts the attack cooldown over too
this.player.last_attack = performance.now();
}
}
}
// mobs can be hit, scripted entities like the fishing hook can't. kinds the client doesn't know are left to the server
function is_hittable(entity: RemoteEntity) {
return EverythingRegistry.get<EntityJson>("entities", entity.type)?.behavior !== "scripted";
}