// SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later import { AssetManager } from "./assets.ts"; import { Client } from "./client.ts"; import { InputManager } from "./input_manager.ts"; import { Connection } from "./network.ts"; import { Options } from "./options.ts"; import { connect, HandshakeError, is_trusted, join, remember_trust, ServerAddress } from "./handshake.ts"; import { build_atlas, engine_textures } from "./atlas.ts"; import { set_texture_animations } from "./texture_animations.ts"; import type { TextureJson } from "@/common/texture_animation.ts"; import { ModLoadError } from "@/common/mod_loader.ts"; import { begin_drawing, clear_background, device, end_drawing, init_font, load_texture } from "./renderer/mod.ts"; import { is_stopped } from "./fatal.ts"; import { download_mods, load_client_mods, set_mods_client } from "./mods.ts"; import type { GuiScreen } from "./gui/gui_screen.ts"; import { in_desktop_app, type JoinServer, TitleScreen } from "./gui/title_screen.ts"; import { MainMenuScreen } from "./gui/main_menu.ts"; import { DisconnectedScreen } from "./gui/disconnected_screen.ts"; import { profiler } from "./profiler.ts"; import { platform } from "./platform.ts"; // runs whatever is showing every frame: a menu screen before joining (and after leaving), or the game class ClientLoop { running = false; last_time = 0; client: Client | undefined; screen: GuiScreen | undefined; frame_count = 0; last_fps_time = 0; start() { platform.on_shown(() => { this.last_time = performance.now(); }); this.running = true; const now = performance.now(); this.last_time = now; this.frame_count = 0; this.last_fps_time = this.last_time; platform.request_frame((time) => this.loop(time)); } stop() { this.running = false; } show_screen(screen: GuiScreen) { this.screen?.on_close(); this.client = undefined; platform.confirm_leaving(false); this.screen = screen; InputManager.set_mouse_grabbed(false); } play(connection: Connection) { const client = new Client(connection, (message) => this.show_screen(new DisconnectedScreen(message))); set_mods_client(client); client.chat.add("Connected to the server"); this.screen?.on_close(); this.screen = undefined; this.client = client; platform.confirm_leaving(true); console.log("Game started"); } loop(time: number) { if (!this.running || is_stopped()) { return; } const delta = (time - this.last_time) / 1000; profiler.begin_frame(); profiler.section("begin frame", begin_drawing); clear_background(0.69, 0.8, 1, 1.0); if (this.client) { this.client.run_frame(delta); } else if (this.screen) { this.screen.on_tick(delta); this.screen.on_render(); } profiler.section("submit", end_drawing); profiler.end_frame(); this.frame_count += 1; const now = performance.now(); if (now - this.last_fps_time >= 1000) { const fps = (this.frame_count * 1000) / (now - this.last_fps_time); console.log(`FPS: ${fps.toFixed(2)}`); this.frame_count = 0; this.last_fps_time = now; } InputManager.update(); this.last_time = time; platform.request_frame((time) => this.loop(time)); } } // a server's blocks, items and scripts can't be taken back out once loaded, so a failure after that point // can't go back to the title screen to try again, the page has to start over class FailedAfterLoadingMods extends Error {} // the game only runs against a server, it owns the world and everything in it. see docs/modding/networking/index.md async function join_server(address: ServerAddress, name: string, status: (text: string) => void): Promise { const { socket, welcome } = await connect(address, name); console.log(`Connected to ${address.ws_url}`); let loaded_mods = false; try { if (address.cross_origin && !is_trusted(address, welcome)) { status("Waiting for you to accept the server's mods..."); if (!await platform.confirm_mods(address, welcome)) { throw new HandshakeError(`You didn't join ${address.base.host}`); } remember_trust(address, welcome); } // textures, blocks and items all come from the server's mods, so this happens before anything else status("Downloading the server's mods..."); const mods = await download_mods(welcome.mods, address.base); const textures = await engine_textures(); const texture_json = new Map(); for (const mod of mods) { for (const [id, png] of mod.textures) textures.set(id, png); for (const [id, json] of mod.texture_json ?? []) texture_json.set(id, json); } const atlas = build_atlas(textures, texture_json); loaded_mods = true; const atlas_texture = load_texture(atlas.image); set_texture_animations(atlas_texture.tex, device.queue, atlas.animated); AssetManager.instance.assets["cubi:textures"] = atlas_texture; AssetManager.instance.assets["cubi:textures_info"] = atlas.regions; await load_client_mods(welcome.mods, mods); console.log(`Mods: ${welcome.mods.map((mod) => `${mod.id} ${mod.version}`).join(", ") || "none"}`); status("Joining..."); const joined = await join(socket, new Options().render_distance); return new Connection(socket, welcome, joined); } catch (e) { socket.close(); const message = error_message(e); throw loaded_mods ? new FailedAfterLoadingMods(message) : new HandshakeError(message); } } function error_message(e: unknown) { if (e instanceof HandshakeError) { return e.message; } if (e instanceof ModLoadError) { return `Couldn't load the server's mods: ${e.message}`; } return `Something went wrong joining the server: ${e instanceof Error ? e.message : e}`; } // the title screen (the main menu in the desktop app), and the game once it joins a server. the platform is set, the // window was set up with init_window, and input comes in export async function start_client() { AssetManager.instance.load("cubi:assets_text", "/assets/ASSETS.md"); AssetManager.instance.load("cubi:skin", "/assets/sprites/skin_template.png"); AssetManager.instance.load("cubi:gui", "/assets/sprites/gui.png"); AssetManager.instance.load("cubi:m6x11", "/assets/fonts/m6x11.png"); AssetManager.instance.load("cubi:m6x11_fnt", "/assets/fonts/m6x11.fnt"); await AssetManager.instance.load_all(); init_font(); const loop = new ClientLoop(); const join_game: JoinServer = async (address, name, status) => { let connection: Connection; try { connection = await join_server(address, name, status); } catch (e) { if (e instanceof FailedAfterLoadingMods) { loop.show_screen(new DisconnectedScreen(e.message)); return; } throw e; } loop.play(connection); }; loop.show_screen( in_desktop_app() ? new MainMenuScreen((screen) => loop.show_screen(screen), join_game) : new TitleScreen(join_game), ); loop.start(); }