diff --git a/client/gui/main_menu.ts b/client/gui/main_menu.ts new file mode 100644 index 0000000..07474a6 --- /dev/null +++ b/client/gui/main_menu.ts @@ -0,0 +1,300 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the desktop app's title screen, a main menu like luanti's. singleplayer lists the worlds in the app's data folder, +// to play one, make one or pick its mods. the app does the files and runs the world's server, see desktop/main.ts +import type { ModEntry, WorldEntry } from "@/desktop/saves.ts"; +import { InputManager } from "@/client/input_manager.ts"; +import { canvas, draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts"; +import { server_address } from "@/client/handshake.ts"; +import { GuiScreen } from "./gui_screen.ts"; +import { CreditsScreen } from "./credits_screen.ts"; +import type { JoinServer } from "./title_screen.ts"; +import { Button, EditBox, ListBox, TEXT_HEIGHT, TEXT_SCALE, TextInput } from "./widgets.ts"; + +const WIDTH = 440; +const ROW_HEIGHT = 48; +const GAP = 20; +const LIST_WIDTH = 640; +const HALF_WIDTH = (LIST_WIDTH - GAP) / 2; +const TOP = 100; +// the name players have in singleplayer worlds, which what they carry is saved under +const SINGLEPLAYER_NAME = "singleplayer"; + +type Show = (screen: GuiScreen) => void; + +export class MainMenuScreen extends GuiScreen { + #buttons: Button[]; + + constructor(show: Show, join: JoinServer) { + super(); + const back = () => show(new MainMenuScreen(show, join)); + // there's nothing behind these yet + const multiplayer = new Button("Multiplayer", WIDTH, ROW_HEIGHT, () => {}); + const mods = new Button("Mods", WIDTH, ROW_HEIGHT, () => {}); + multiplayer.active = mods.active = false; + this.#buttons = [ + new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => show(new WorldListScreen(show, join))), + multiplayer, + mods, + new Button("Credits", WIDTH, ROW_HEIGHT, () => show(new CreditsScreen(back))), + ]; + } + + on_tick(_delta: number): void { + let y = (canvas.height - this.#buttons.length * (ROW_HEIGHT + GAP)) / 2 + 40; + for (const button of this.#buttons) { + button.x = (canvas.width - WIDTH) / 2; + button.y = y; + y += ROW_HEIGHT + GAP; + button.handle_input(); + } + } + + on_render(): void { + draw_centered("Cubi", this.#buttons[0].y - 140, 8); + for (const button of this.#buttons) button.render(); + } + + on_close(): void {} +} + +// the worlds in the app's saves folder +class WorldListScreen extends GuiScreen { + #show: Show; + #join: JoinServer; + #worlds: WorldEntry[] = []; + #mods: ModEntry[] = []; + #list = new ListBox(LIST_WIDTH, 0, (row, double) => { + this.#list.selected = row; + if (double) this.#play(); + }); + #play_button = new Button("Play", HALF_WIDTH, ROW_HEIGHT, () => this.#play()); + #new_button = new Button("New world", HALF_WIDTH, ROW_HEIGHT, () => this.#edit()); + #mods_button = new Button("Mods", HALF_WIDTH, ROW_HEIGHT, () => this.#edit(this.#selected)); + #back_button = new Button("Back", HALF_WIDTH, ROW_HEIGHT, () => this.#back()); + #status = new Status(); + #busy = true; + + // select is the world selected at first, like one that was just made + constructor(show: Show, join: JoinServer, select?: string) { + super(); + this.#show = show; + this.#join = join; + this.#status.set("Loading worlds..."); + desktop("singleplayer").then((response) => response.json()).then( + ({ worlds, mods }: { worlds: WorldEntry[]; mods: ModEntry[] }) => { + this.#worlds = worlds; + this.#mods = mods; + this.#list.rows = worlds.map((world) => ({ text: world.name })); + this.#list.selected = Math.max(0, worlds.findIndex((world) => world.name === select)); + this.#status.set(worlds.length === 0 ? "There are no worlds yet, make one with New world" : ""); + this.#busy = false; + }, + (e) => this.#status.fail(e), + ); + } + + get #selected(): WorldEntry | undefined { + return this.#worlds[this.#list.selected]; + } + + on_tick(_delta: number): void { + const buttons = [this.#play_button, this.#new_button, this.#mods_button, this.#back_button]; + const x = (canvas.width - LIST_WIDTH) / 2; + this.#list.x = x; + this.#list.y = TOP; + this.#list.height = canvas.height - TOP - 2 * (ROW_HEIGHT + GAP) - 120; + for (const [i, button] of buttons.entries()) { + button.x = x + (i % 2) * (HALF_WIDTH + GAP); + button.y = TOP + this.#list.height + GAP + Math.floor(i / 2) * (ROW_HEIGHT + GAP); + } + this.#play_button.active = this.#mods_button.active = !this.#busy && this.#selected !== undefined; + this.#new_button.active = !this.#busy; + + if (InputManager.is_key_pressed("Escape")) return this.#back(); + if (InputManager.is_key_pressed("Enter")) this.#play(); + if (!this.#busy) this.#list.handle_input(); + for (const button of buttons) button.handle_input(); + } + + on_render(): void { + draw_centered("Singleplayer", TOP / 2, 4); + this.#list.render(); + for (const button of [this.#play_button, this.#new_button, this.#mods_button, this.#back_button]) { + button.render(); + } + this.#status.render(this.#back_button.y + ROW_HEIGHT + GAP); + } + + on_close(): void {} + + #back() { + if (!this.#busy || this.#status.error) this.#show(new MainMenuScreen(this.#show, this.#join)); + } + + // a new world, or the mods of one there is + #edit(world?: WorldEntry) { + this.#show(new WorldModsScreen(this.#show, this.#join, this.#mods, world)); + } + + async #play() { + const world = this.#selected; + if (!world || this.#busy) return; + this.#busy = true; + this.#status.set(`Starting ${world.name}...`); + try { + await desktop("play", { world: world.name }); + await this.#join(server_address(location.host), SINGLEPLAYER_NAME, (text) => this.#status.set(text)); + } catch (e) { + this.#status.fail(e); + this.#busy = false; + } + } +} + +// a new world's name and mods, or the mods of one there is. turning a mod on turns on the mods it needs, and turning +// one off turns off the mods that need it +class WorldModsScreen extends GuiScreen { + #show: Show; + #join: JoinServer; + #mods: ModEntry[]; + #world: WorldEntry | undefined; + #enabled: Set; + #name = new EditBox(LIST_WIDTH, ROW_HEIGHT, new TextInput("", 32), "World name"); + #list = new ListBox(LIST_WIDTH, 0, (row) => this.#toggle(this.#mods[row].id)); + #save_button: Button; + #cancel_button: Button; + #status = new Status(); + #busy = false; + + constructor(show: Show, join: JoinServer, mods: ModEntry[], world?: WorldEntry) { + super(); + this.#show = show; + this.#join = join; + this.#mods = mods; + this.#world = world; + // a new world starts with every mod. a world's mods that aren't in the folder anymore are dropped when it's saved + this.#enabled = new Set(mods.map(({ id }) => id).filter((id) => !world || world.mods.includes(id))); + this.#name.focused = !world; + this.#save_button = new Button(world ? "Save" : "Create", HALF_WIDTH, ROW_HEIGHT, () => this.#save()); + this.#cancel_button = new Button("Cancel", HALF_WIDTH, ROW_HEIGHT, () => this.#back(world?.name)); + this.#update_rows(); + if (mods.length === 0) this.#status.set("There are no mods in the mods folder"); + } + + on_tick(_delta: number): void { + const x = (canvas.width - LIST_WIDTH) / 2; + let y = TOP; + if (!this.#world) { + this.#name.x = x; + this.#name.y = y; + y += ROW_HEIGHT + GAP; + } + this.#list.x = x; + this.#list.y = y; + this.#list.height = canvas.height - y - ROW_HEIGHT - GAP - 120; + this.#save_button.x = x; + this.#cancel_button.x = x + HALF_WIDTH + GAP; + this.#save_button.y = this.#cancel_button.y = y + this.#list.height + GAP; + this.#save_button.active = this.#name.active = !this.#busy; + + if (InputManager.is_key_pressed("Escape")) return this.#back(this.#world?.name); + if (InputManager.is_key_pressed("Enter")) this.#save(); + this.#name.handle_input(); + this.#list.handle_input(); + this.#save_button.handle_input(); + this.#cancel_button.handle_input(); + } + + on_render(): void { + draw_centered(this.#world ? `${this.#world.name}'s mods` : "New world", TOP / 2, 4); + if (!this.#world) this.#name.render(); + this.#list.render(); + this.#save_button.render(); + this.#cancel_button.render(); + this.#status.render(this.#save_button.y + ROW_HEIGHT + GAP); + } + + on_close(): void {} + + #toggle(id: string) { + const by_id = new Map(this.#mods.map((mod) => [mod.id, mod])); + const on = (id: string) => { + this.#enabled.add(id); + for (const dependency of by_id.get(id)?.dependencies ?? []) { + if (by_id.has(dependency) && !this.#enabled.has(dependency)) on(dependency); + } + }; + const off = (id: string) => { + this.#enabled.delete(id); + for (const mod of this.#mods) { + if (mod.dependencies.includes(id) && this.#enabled.has(mod.id)) off(mod.id); + } + }; + (this.#enabled.has(id) ? off : on)(id); + this.#update_rows(); + } + + #update_rows() { + this.#list.rows = this.#mods.map((mod) => ({ + text: `${mod.name} ${mod.version}`, + checked: this.#enabled.has(mod.id), + })); + } + + async #save() { + if (this.#busy) return; + this.#busy = true; + const world = this.#world?.name ?? this.#name.value.trim(); + try { + await desktop(this.#world ? "world_mods" : "create_world", { world, mods: [...this.#enabled] }); + this.#back(world); + } catch (e) { + this.#status.fail(e); + this.#busy = false; + } + } + + #back(select?: string) { + this.#show(new WorldListScreen(this.#show, this.#join, select)); + } +} + +// what's happening, or what went wrong, under a screen's buttons. a line each for messages that have several, like +// a world's mods' problems +class Status { + text = ""; + error = false; + + set(text: string) { + this.text = text; + this.error = false; + } + + fail(e: unknown) { + this.text = e instanceof Error ? e.message : String(e); + this.error = true; + } + + render(y: number) { + for (const line of this.text.split("\n").filter((line) => line !== "")) { + const width = measure_text(line, TEXT_SCALE); + const x = (canvas.width - width) / 2; + draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]); + draw_text(line, x, y, TEXT_SCALE, this.error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]); + y += TEXT_HEIGHT * TEXT_SCALE + 8; + } + } +} + +function draw_centered(text: string, y: number, scale: number) { + draw_text(text, (canvas.width - measure_text(text, scale)) / 2, y - (TEXT_HEIGHT * scale) / 2, scale); +} + +// asks the desktop app, see desktop/main.ts. throws with what the app said went wrong +async function desktop(path: string, body: unknown = {}): Promise { + const response = await fetch(`/desktop/${path}`, { method: "POST", body: JSON.stringify(body) }); + if (!response.ok) throw new Error(await response.text()); + return response; +} diff --git a/client/gui/title_screen.ts b/client/gui/title_screen.ts index 98ac038..385b340 100644 --- a/client/gui/title_screen.ts +++ b/client/gui/title_screen.ts @@ -23,8 +23,8 @@ const TITLE_SCALE = 8; // for the player when it fails export type JoinServer = (address: ServerAddress, name: string, status: (text: string) => void) => Promise; -// the first thing players see, like minecraft's title and multiplayer screens rolled into one: a name, a server, -// and a button to join it. in the desktop app there's also singleplayer, which joins the app's own server +// the first thing players see in the browser, like minecraft's title and multiplayer screens rolled into one: a +// name, a server, and a button to join it. the desktop app has a main menu instead, see main_menu.ts export class TitleScreen extends GuiScreen { #join_server: JoinServer; @@ -36,15 +36,9 @@ export class TitleScreen extends GuiScreen { ); server = new EditBox(WIDTH, ROW_HEIGHT, new TextInput(initial_server(), 256, (char) => char !== " "), "host:port"); join_button = new Button("Join server", WIDTH, ROW_HEIGHT, () => this.#join()); - // the page was served by a game server of its own to play on alone, see desktop/main.ts - singleplayer_button = has_singleplayer() - ? new Button("Singleplayer", WIDTH, ROW_HEIGHT, () => this.#join_singleplayer()) - : undefined; credits_button = new Button("Credits", WIDTH, ROW_HEIGHT, () => this.#open_credits()); - // in the browser, the desktop app for this computer's os - download_button = has_singleplayer() - ? undefined - : new Button(`Download for ${download_os().name}`, WIDTH, ROW_HEIGHT, download_desktop_app); + // the desktop app for this computer's os + download_button = new Button(`Download for ${download_os().name}`, WIDTH, ROW_HEIGHT, download_desktop_app); // open over the title screen, it gets the input while it's there #credits: CreditsScreen | undefined; @@ -86,10 +80,9 @@ export class TitleScreen extends GuiScreen { if (InputManager.is_key_pressed("Enter")) { this.#join(); } - this.singleplayer_button?.handle_input(); this.join_button.handle_input(); this.credits_button.handle_input(); - this.download_button?.handle_input(); + this.download_button.handle_input(); } on_render(): void { @@ -105,16 +98,15 @@ export class TitleScreen extends GuiScreen { this.#label("Name", this.name); this.#label("Server", this.server); this.name.render(); - this.singleplayer_button?.render(); this.server.render(); this.join_button.render(); this.credits_button.render(); - this.download_button?.render(); + this.download_button.render(); if (this.status) { const width = measure_text(this.status, TEXT_SCALE); const x = (canvas.width - width) / 2; - const y = (this.download_button ?? this.credits_button).y + ROW_HEIGHT + GAP; + const y = this.download_button.y + ROW_HEIGHT + GAP; draw_rect(x - 8, y - 4, width + 16, TEXT_HEIGHT * TEXT_SCALE + 8, [0, 0, 0, 0.5]); draw_text(this.status, x, y, TEXT_SCALE, this.status_is_error ? [1, 0.45, 0.45, 1] : [1, 1, 1, 1]); } @@ -136,28 +128,17 @@ export class TitleScreen extends GuiScreen { #layout() { const x = (canvas.width - WIDTH) / 2; - const singleplayer_height = this.singleplayer_button ? ROW_HEIGHT + GAP : 0; - const download_height = this.download_button ? ROW_HEIGHT + GAP : 0; - const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + singleplayer_height + 2 * ROW_HEIGHT + GAP + - download_height; + const total = 2 * (LABEL_GAP + ROW_HEIGHT + GAP) + 3 * ROW_HEIGHT + 2 * GAP; let y = (canvas.height - total) / 2 + 40; for (const field of [this.name, this.server]) { field.x = x; field.y = y + LABEL_GAP; y += LABEL_GAP + ROW_HEIGHT + GAP; - if (field === this.name && this.singleplayer_button) { - this.singleplayer_button.x = x; - this.singleplayer_button.y = y; - y += singleplayer_height; - } } - this.join_button.x = x; - this.join_button.y = y; - this.credits_button.x = x; - this.credits_button.y = y + ROW_HEIGHT + GAP; - if (this.download_button) { - this.download_button.x = x; - this.download_button.y = this.credits_button.y + ROW_HEIGHT + GAP; + for (const button of [this.join_button, this.credits_button, this.download_button]) { + button.x = x; + button.y = y; + y += ROW_HEIGHT + GAP; } } @@ -181,18 +162,10 @@ export class TitleScreen extends GuiScreen { await this.#connect(address); } - // the server that served this page - async #join_singleplayer() { - if (this.#joining) { - return; - } - await this.#connect(server_address(location.host), "Starting singleplayer..."); - } - - async #connect(address: ServerAddress, status = `Connecting to ${address.base.host}...`) { + async #connect(address: ServerAddress) { remember(LAST_NAME_KEY, this.name.value); this.#set_joining(true); - this.status = status; + this.status = `Connecting to ${address.base.host}...`; this.status_is_error = false; try { await this.#join_server(address, this.name.value, (text) => this.status = text); @@ -205,9 +178,6 @@ export class TitleScreen extends GuiScreen { #set_joining(joining: boolean) { this.#joining = joining; this.name.active = this.server.active = this.join_button.active = !joining; - if (this.singleplayer_button) { - this.singleplayer_button.active = !joining; - } } #show_error(message: string) { @@ -243,7 +213,8 @@ function remember(key: string, value: string) { } } -function has_singleplayer() { +// the page is the desktop app's, see desktop/main.ts +export function in_desktop_app() { return new URL(location.href).searchParams.has("singleplayer"); } @@ -263,12 +234,12 @@ function download_desktop_app() { } // a server's mods can't be unloaded, so going back to the title screen starts the page over. without ?server= -// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, its saved -// fields don't last between launches and the page's own address isn't a server to join +// or ?name=, so the fields show what was used last. the desktop app keeps its ?singleplayer and ?server=, for its +// main menu export function back_to_title() { const page = new URL(location.href); const next = new URL(location.pathname, location.href); - if (has_singleplayer()) { + if (in_desktop_app()) { next.searchParams.set("server", page.searchParams.get("server") ?? ""); next.searchParams.set("singleplayer", ""); } diff --git a/client/gui/widgets.ts b/client/gui/widgets.ts index 989a218..00b4880 100644 --- a/client/gui/widgets.ts +++ b/client/gui/widgets.ts @@ -3,7 +3,7 @@ import { point_inside_rec } from "@/common/utils.ts"; import { InputManager, type KeyCode } from "@/client/input_manager.ts"; -import { draw_rect, draw_text, measure_text } from "@/client/renderer/mod.ts"; +import { draw_rect, draw_rect_stroke, draw_text, measure_text } from "@/client/renderer/mod.ts"; import { draw_gui_sprite } from "./gui_sprites.ts"; export const TEXT_SCALE = 2; @@ -345,3 +345,78 @@ export class EditBox { return this.x + 10; } } + +const LIST_ROW_HEIGHT = 40; +const CHECK_SIZE = 20; + +// rows of text that scroll with the mouse wheel, like minecraft's selection lists. a row can have a box ticked or not +// in front, for lists of things to turn on and off +export class ListBox { + x = 0; + y = 0; + width: number; + height: number; + rows: { text: string; checked?: boolean }[] = []; + selected = -1; + // clicking a row, double is whether it was the second click of a double click + on_click: (row: number, double: boolean) => void; + #scroll = 0; + #hovered = -1; + #last_click = { row: -1, time: -Infinity }; + + constructor(width: number, height: number, on_click: (row: number, double: boolean) => void) { + this.width = width; + this.height = height; + this.on_click = on_click; + } + + get #visible() { + return Math.max(1, Math.floor(this.height / LIST_ROW_HEIGHT)); + } + + handle_input() { + const mouse = InputManager.get_mouse_position(); + const inside = point_inside_rec(mouse.x, mouse.y, this.x, this.y, this.width, this.height); + const max_scroll = Math.max(0, this.rows.length - this.#visible); + if (inside) this.#scroll += Math.sign(InputManager.get_wheel_delta()); + this.#scroll = Math.max(0, Math.min(max_scroll, this.#scroll)); + + const row = this.#scroll + Math.floor((mouse.y - this.y) / LIST_ROW_HEIGHT); + this.#hovered = inside && row < this.rows.length ? row : -1; + if (this.#hovered >= 0 && InputManager.is_mouse_pressed(0)) { + InputManager.consume_mouse(0); + const now = performance.now(); + const double = this.#last_click.row === row && now - this.#last_click.time < DOUBLE_CLICK_MS; + this.#last_click = double ? { row: -1, time: -Infinity } : { row, time: now }; + this.on_click(row, double); + } + } + + render() { + draw_rect(this.x, this.y, this.width, this.height, [0, 0, 0, 0.5]); + const shown = this.rows.slice(this.#scroll, this.#scroll + this.#visible); + for (const [i, row] of shown.entries()) { + const index = this.#scroll + i; + const y = this.y + i * LIST_ROW_HEIGHT; + if (index === this.selected) { + draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, SELECTION_COLOR); + } else if (index === this.#hovered) { + draw_rect(this.x, y, this.width, LIST_ROW_HEIGHT, [1, 1, 1, 0.1]); + } + let text_x = this.x + 12; + if (row.checked !== undefined) { + const box_y = y + (LIST_ROW_HEIGHT - CHECK_SIZE) / 2; + draw_rect_stroke(text_x, box_y, CHECK_SIZE, CHECK_SIZE, [1, 1, 1, 1], 2); + if (row.checked) draw_rect(text_x + 5, box_y + 5, CHECK_SIZE - 10, CHECK_SIZE - 10); + text_x += CHECK_SIZE + 12; + } + draw_text(row.text, text_x, y + (LIST_ROW_HEIGHT - TEXT_HEIGHT * TEXT_SCALE) / 2, TEXT_SCALE); + } + // how far down it's scrolled, when it doesn't all fit + if (this.rows.length > this.#visible) { + const bar = this.height * this.#visible / this.rows.length; + const bar_y = this.y + (this.height - bar) * this.#scroll / (this.rows.length - this.#visible); + draw_rect(this.x + this.width - 6, bar_y, 6, bar, [1, 1, 1, 0.5]); + } + } +} diff --git a/client/main.ts b/client/main.ts index d98d788..cc4b7be 100644 --- a/client/main.ts +++ b/client/main.ts @@ -27,7 +27,8 @@ import { import { is_stopped, show_fatal_error } from "./fatal.ts"; import { download_mods, load_client_mods, set_mods_client } from "./mods.ts"; import type { GuiScreen } from "./gui/gui_screen.ts"; -import { TitleScreen } from "./gui/title_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"; @@ -247,19 +248,20 @@ await AssetManager.instance.load_all(); init_font(); const loop = new ClientLoop(); -loop.show_screen( - new TitleScreen(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; +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; } - loop.play(connection); - }), + 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(); diff --git a/common/mod.ts b/common/mod.ts index 6668ab6..3c28c78 100644 --- a/common/mod.ts +++ b/common/mod.ts @@ -116,6 +116,20 @@ export function write_mod(mod: Mod): Uint8Array { return zipSync(sorted, { mtime: FIXED_TIME, level: 9 }) as Uint8Array; } +// only a .cubi's manifest, checked, without unzipping the rest. for listing mods, read_mod checks the whole thing +export function read_manifest(bytes: Uint8Array, file: string): ManifestJson { + let manifest: ManifestJson; + try { + const files = unzipSync(bytes, { filter: (entry) => entry.name === "manifest.json" }); + manifest = JSON.parse(new TextDecoder().decode(files["manifest.json"])); + } catch (e) { + throw new ModError(file, [`isn't a readable .cubi: ${(e as Error).message}`]); + } + const problems = validate_manifest(manifest, manifest?.id); + if (problems.length > 0) throw new ModError(file, problems.map((problem) => `manifest.json: ${problem}`)); + return manifest; +} + // opens and checks a .cubi. file is only for error messages. throws ModError listing what's wrong export function read_mod(bytes: Uint8Array, file: string): Mod { let files: Record; diff --git a/desktop/main.ts b/desktop/main.ts index f220ae3..74efb67 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -4,18 +4,23 @@ /// // the desktop app: the web client in a bundled chromium (deno desktop's cef backend), so people whose browser has no -// webgpu (firefox) can still play. it joins servers like the browser does, and runs its own game server for -// singleplayer, like minecraft java. build it with deno task desktop, see the desktop/ docs for how deno desktop works +// webgpu (firefox) can still play. its title screen is a main menu like luanti's: singleplayer worlds are played on +// a game server of its own, with the mods each world picked from its data folder, see saves.ts. build it with deno +// task desktop, see the desktop/ docs for how deno desktop works import { fromFileUrl, join } from "@std/path"; -import { type Host, serve_static, start_host } from "../server/host.ts"; +import { serve_static } from "../server/host.ts"; import { PROTOCOL_VERSION } from "../common/protocol.ts"; import { current_client, update_client } from "./client_updates.ts"; import { guard_shortcuts } from "./shortcuts.ts"; import { center_mouse } from "./center_mouse.ts"; +import { data_dir, install_mods } from "./saves.ts"; +import { singleplayer_server } from "./singleplayer.ts"; // where the project was built from: build/ and server_mods/ (the .cubi files) are bundled into the app with --include const ROOT = fromFileUrl(new URL("../", import.meta.url)); const BUILD_DIR = join(ROOT, "build"); +const DATA_DIR = data_dir(); +install_mods(join(ROOT, "server_mods"), DATA_DIR); // the server the address field starts with. "" leaves it empty for the player to fill in const config: { server?: string; client_updates?: string } = JSON.parse( @@ -31,7 +36,7 @@ const UPDATE_WAIT_MS = 3000; const client_options = { source: updates_from, bundled_dir: BUILD_DIR, - cache_dir: join(data_dir(), "client"), + cache_dir: join(DATA_DIR, "client"), protocol: PROTOCOL_VERSION, }; const client_dir: Promise = updates_from === "off" || updates_from === "" @@ -45,40 +50,21 @@ client_dir.then((dir) => console.log(`Playing the client in ${dir}`)); const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 }); guard_shortcuts(win); -// the singleplayer game server, started the first time singleplayer connects so players who only join other servers -// don't get a world made for them. it plays the .cubi files the app was built with -let host: Promise | undefined; - -function singleplayer_host(): Promise { - host ??= (async () => { - const worlds = join(data_dir(), "worlds"); - Deno.mkdirSync(worlds, { recursive: true }); - return await start_host({ - build_dir: BUILD_DIR, - server_mods_dir: join(ROOT, "server_mods"), - config_dir: join(data_dir(), "config"), - world_dir: join(worlds, "world"), - on_fatal(message) { - console.error(message); - alert(`The singleplayer world stopped: ${message}`); - Deno.exit(1); - }, - }); - })(); - return host; -} +const singleplayer = singleplayer_server({ + build_dir: BUILD_DIR, + data_dir: DATA_DIR, + on_fatal(message) { + console.error(message); + alert(`The singleplayer world stopped: ${message}`); + Deno.exit(1); + }, +}); // the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the // last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway win.addEventListener("close", async (event) => { event.preventDefault(); - if (host) { - try { - await (await host).shutdown(); - } catch (e) { - console.error((e as Error).message); - } - } + await singleplayer.stop(); Deno.exit(0); }); @@ -91,7 +77,7 @@ Deno.serve(async (req) => { const url = new URL(req.url); if (url.pathname === "/") { // ?server= fills in the address field, without it the field would start with this app's own address. - // ?singleplayer shows the singleplayer button, which joins this app's own server + // ?singleplayer shows the main menu instead of the browser's title screen const start = new URL("/client/", url); start.searchParams.set("server", default_server); start.searchParams.set("singleplayer", ""); @@ -102,29 +88,7 @@ Deno.serve(async (req) => { center_mouse(); return new Response(null, { status: 204 }); } - // the singleplayer server's socket and its .cubi downloads - if (url.pathname === "/ws" || url.pathname.startsWith("/mods/")) { - try { - return (await singleplayer_host()).handle(req); - } catch (e) { - // its mods have problems, the title screen shows why the connection failed - console.error((e as Error).message); - host = undefined; - return new Response((e as Error).message, { status: 500 }); - } - } + const response = await singleplayer.handle(req, url); + if (response) return response; return serve_static(await client_dir, req, url); }); - -// where the app keeps its worlds, the usual place for app data on each os -function data_dir() { - const home = Deno.env.get("HOME") ?? Deno.env.get("USERPROFILE") ?? "."; - switch (Deno.build.os) { - case "windows": - return join(Deno.env.get("APPDATA") ?? join(home, "AppData", "Roaming"), "bworld"); - case "darwin": - return join(home, "Library", "Application Support", "bworld"); - default: - return join(Deno.env.get("XDG_DATA_HOME") ?? join(home, ".local", "share"), "bworld"); - } -} diff --git a/desktop/saves.ts b/desktop/saves.ts new file mode 100644 index 0000000..91fa689 --- /dev/null +++ b/desktop/saves.ts @@ -0,0 +1,185 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the desktop app's data folder, like luanti's: every .cubi in mods/, and the singleplayer worlds in saves/. a world +// is a folder the game server saves into, with a world.json of its own saying which mods it's played with +import { join } from "@std/path"; +import { z } from "zod"; +import { read_manifest } from "../common/mod.ts"; +import { data_file, FORMAT_VERSION } from "../common/mod_data.ts"; +import { mod_files } from "../server/load_mods.ts"; + +// what the mod lists show +export interface ModEntry { + id: string; + name: string; + version: string; + description?: string; + // the ids of the mods it needs + dependencies: string[]; + // in mods/ + file: string; +} + +export interface WorldEntry { + // its folder's name + name: string; + // the ids of its mods + mods: string[]; +} + +const WORLD_FILE = "world.json"; +const world_file = data_file("mods", z.array(z.string())); +// what works as a folder name on every os +const WORLD_NAME = /^[A-Za-z0-9_\- ]{1,32}$/; + +// the usual place for app data on each os +export function data_dir() { + const home = Deno.env.get("HOME") ?? Deno.env.get("USERPROFILE") ?? "."; + switch (Deno.build.os) { + case "windows": + return join(Deno.env.get("APPDATA") ?? join(home, "AppData", "Roaming"), "cubi"); + case "darwin": + return join(home, "Library", "Application Support", "cubi"); + default: + return join(Deno.env.get("XDG_DATA_HOME") ?? join(home, ".local", "share"), "cubi"); + } +} + +export function mods_dir(data: string) { + return join(data, "mods"); +} + +function saves_dir(data: string) { + return join(data, "saves"); +} + +// puts the .cubi files the app was built with, like the base game, in mods/. they replace the ones with the same file +// name, so they're updated along with the app +export function install_mods(from: string, data: string) { + Deno.mkdirSync(mods_dir(data), { recursive: true }); + for (const file of mod_files(from)) { + const bytes = Deno.readFileSync(join(from, file)); + const to = join(mods_dir(data), file); + if (!same_bytes(bytes, read_if_there(to))) Deno.writeFileSync(to, bytes); + } +} + +// the mods in mods/ that can be read, by name. ones that can't are left out and logged +export function list_mods(data: string): ModEntry[] { + const mods = new Map(); + for (const file of mod_files(mods_dir(data))) { + try { + const manifest = read_manifest(Deno.readFileSync(join(mods_dir(data), file)), file); + const other = mods.get(manifest.id); + if (other) { + console.warn(`${file} is left out, ${other.file} is the mod "${manifest.id}" too`); + continue; + } + mods.set(manifest.id, { + id: manifest.id, + name: manifest.name, + version: manifest.version, + description: manifest.description, + dependencies: (manifest.dependencies ?? []).map(({ id }) => id), + file, + }); + } catch (e) { + console.warn((e as Error).message); + } + } + return [...mods.values()].sort((a, b) => a.name.localeCompare(b.name)); +} + +// the folders in saves/ with a world.json, by name +export function list_worlds(data: string): WorldEntry[] { + const worlds: WorldEntry[] = []; + for (const entry of read_dir(saves_dir(data))) { + if (!entry.isDirectory) continue; + try { + worlds.push({ name: entry.name, mods: read_world_mods(data, entry.name) }); + } catch (e) { + if (!(e instanceof Deno.errors.NotFound)) console.warn(`${entry.name}: ${(e as Error).message}`); + } + } + return worlds.sort((a, b) => a.name.localeCompare(b.name)); +} + +// a new world, which the game server makes once it's played. errors are told to the player +export function create_world(data: string, name: unknown, mods: unknown) { + if (typeof name !== "string" || !WORLD_NAME.test(name.trim())) { + throw new Error("A world's name has to be 1 to 32 letters, numbers, spaces, - and _"); + } + const trimmed = name.trim(); + // any folder, and case insensitive like windows' and macos' folders + const taken = [...read_dir(saves_dir(data))].some((entry) => entry.name.toLowerCase() === trimmed.toLowerCase()); + if (taken) throw new Error(`There's already a world called ${trimmed}`); + const json = world_json(data, mods); + const dir = join(saves_dir(data), trimmed); + Deno.mkdirSync(dir, { recursive: true }); + Deno.writeTextFileSync(join(dir, WORLD_FILE), json); +} + +export function set_world_mods(data: string, name: unknown, mods: unknown) { + Deno.writeTextFileSync(join(world_dir(data, name), WORLD_FILE), world_json(data, mods)); +} + +// a world.json, for mods the page sent +function world_json(data: string, mods: unknown) { + const known = new Set(list_mods(data).map(({ id }) => id)); + if (!Array.isArray(mods) || mods.some((id) => !known.has(id))) { + throw new Error("Those aren't all mods in the mods folder"); + } + const json: z.infer = { format_version: FORMAT_VERSION, mods: [...new Set(mods)] }; + return JSON.stringify(json, null, "\t") + "\n"; +} + +// what the game server needs to play a world: its folder, and the files in mods/ of its mods +export function world_to_play(data: string, name: unknown): { dir: string; mod_files: string[] } { + const dir = world_dir(data, name); + const mods = new Map(list_mods(data).map((mod) => [mod.id, mod])); + const mod_files = read_world_mods(data, name as string).map((id) => { + const mod = mods.get(id); + if (!mod) throw new Error(`This world plays with the mod "${id}", which isn't in the mods folder`); + return mod.file; + }); + return { dir, mod_files }; +} + +// the folder of a world there is, from a name the page sent +function world_dir(data: string, name: unknown) { + if (typeof name !== "string" || !list_worlds(data).some((world) => world.name === name)) { + throw new Error(`There's no world called ${name}`); + } + return join(saves_dir(data), name); +} + +function read_world_mods(data: string, name: string): string[] { + const json = JSON.parse(Deno.readTextFileSync(join(saves_dir(data), name, WORLD_FILE))); + const parsed = world_file.safeParse(json); + if (!parsed.success) throw new Error(`${WORLD_FILE} must be { "format_version": 1, "mods": [...] }`); + return parsed.data.mods as string[]; +} + +// nothing when it isn't there yet +function read_dir(dir: string): Deno.DirEntry[] { + try { + return [...Deno.readDirSync(dir)]; + } catch (e) { + if (e instanceof Deno.errors.NotFound) return []; + throw e; + } +} + +function read_if_there(file: string): Uint8Array | undefined { + try { + return Deno.readFileSync(file); + } catch (e) { + if (e instanceof Deno.errors.NotFound) return undefined; + throw e; + } +} + +function same_bytes(a: Uint8Array, b: Uint8Array | undefined) { + return b !== undefined && a.length === b.length && a.every((byte, i) => byte === b[i]); +} diff --git a/desktop/singleplayer.ts b/desktop/singleplayer.ts new file mode 100644 index 0000000..64b4443 --- /dev/null +++ b/desktop/singleplayer.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +// the desktop app's singleplayer: what the main menu asks it (see client/gui/main_menu.ts), and the game server of +// the world being played, with the mods the world picked from the data folder. see saves.ts +import { join } from "@std/path"; +import { type Host, start_host } from "../server/host.ts"; +import { create_world, list_mods, list_worlds, mods_dir, set_world_mods, world_to_play } from "./saves.ts"; + +export interface SingleplayerOptions { + // what deno task build made: the client and the engine's assets + build_dir: string; + // the app's data folder, see saves.ts + data_dir: string; + // the world being played can't go on + on_fatal(message: string): void; + // how many workers generate chunks, see HostOptions + worldgen_workers?: number; +} + +export function singleplayer_server(options: SingleplayerOptions) { + const data = options.data_dir; + // playing another world, or the same one again after changing its mods, stops it first + let host: Promise | undefined; + + async function play(world: unknown) { + await stop(); + const { dir, mod_files } = world_to_play(data, world); + host = start_host({ + build_dir: options.build_dir, + server_mods_dir: mods_dir(data), + mod_files, + config_dir: join(data, "config"), + world_dir: dir, + worldgen_workers: options.worldgen_workers, + on_fatal: options.on_fatal, + }); + try { + await host; + } catch (e) { + host = undefined; + throw e; + } + } + + // saves the world being played + async function stop() { + const playing = host; + host = undefined; + try { + await (await playing)?.shutdown(); + } catch (e) { + console.error((e as Error).message); + } + } + + // errors are told to the player + async function menu_request(req: Request, url: URL): Promise { + if (url.pathname === "/desktop/singleplayer") { + return Response.json({ worlds: list_worlds(data), mods: list_mods(data) }); + } + let body: Record; + try { + body = await req.json(); + } catch { + return new Response("Expected json", { status: 400 }); + } + try { + switch (url.pathname) { + case "/desktop/create_world": + create_world(data, body.world, body.mods); + break; + case "/desktop/world_mods": + set_world_mods(data, body.world, body.mods); + break; + case "/desktop/play": + await play(body.world); + break; + default: + return new Response("Not found", { status: 404 }); + } + } catch (e) { + console.error((e as Error).message); + return new Response((e as Error).message, { status: 400 }); + } + return new Response(null, { status: 204 }); + } + + return { + // undefined for requests that aren't singleplayer's + async handle(req: Request, url: URL): Promise { + if (url.pathname.startsWith("/desktop/") && req.method === "POST") { + return await menu_request(req, url); + } + // the world's socket and its .cubi downloads + if (url.pathname === "/ws" || url.pathname.startsWith("/mods/")) { + const playing = await host?.catch(() => undefined); + return playing ? playing.handle(req) : new Response("No world is being played", { status: 503 }); + } + return undefined; + }, + stop, + }; +} diff --git a/server/host.ts b/server/host.ts index b757f82..24c6a54 100644 --- a/server/host.ts +++ b/server/host.ts @@ -24,6 +24,8 @@ export interface HostOptions { build_dir: string; // the .cubi files to load server_mods_dir: string; + // which of server_mods_dir's files to load, by file name. every one when left out + mod_files?: string[]; // .json files that change mods' settings, see docs/modding/misc/config.md. without it every mod uses its // own config.json config_dir?: string; @@ -47,7 +49,12 @@ export interface Host { // throws when the mods have problems, saying what they are export async function start_host(options: HostOptions): Promise { - const mods = await load_mods(options.server_mods_dir, engine_texture_ids(options.build_dir), options.config_dir); + const mods = await load_mods( + options.server_mods_dir, + engine_texture_ids(options.build_dir), + options.config_dir, + options.mod_files, + ); console.log(`Mods: ${mods.map((mod) => `${mod.listing.id} ${mod.listing.version}`).join(", ") || "none"}`); // what players download, by path const downloads = new Map(mods.map((mod) => [`/${mod.listing.file}`, mod.client_bytes])); diff --git a/server/load_mods.ts b/server/load_mods.ts index c72cc94..58417c7 100644 --- a/server/load_mods.ts +++ b/server/load_mods.ts @@ -27,19 +27,18 @@ export class ModsError extends Error { } // engine_textures are the cubi: texture ids, for checking the textures mods use. config_dir has the server's -// .json files that change mods' config. a mod with problems stops the whole server from starting, the game -// never runs with some mods missing +// .json files that change mods' config. only, when given, is which of dir's files to load, like a +// singleplayer world's mods. a mod with problems stops the whole server from starting, the game never runs with some +// mods missing export async function load_mods( dir: string, engine_textures: Iterable, config_dir?: string, + only?: string[], ): Promise { let files: string[]; try { - files = [...Deno.readDirSync(dir)] - .filter((entry) => entry.isFile && entry.name.endsWith(MOD_EXTENSION)) - .map((entry) => entry.name) - .sort(); + files = only ?? mod_files(dir); } catch (e) { if (e instanceof Deno.errors.NotFound) return []; throw e; @@ -104,6 +103,14 @@ export async function load_mods( })); } +// the .cubi files in a folder, by name +export function mod_files(dir: string): string[] { + return [...Deno.readDirSync(dir)] + .filter((entry) => entry.isFile && entry.name.endsWith(MOD_EXTENSION)) + .map((entry) => entry.name) + .sort(); +} + // runs the content phase of the mods' scripts in a worker without permissions and adds the blocks they register to // their data, after their files' ones. from then on they're the mod's data like the rest: checked, in the copy players // download, and in the worldgen bundle diff --git a/tests/desktop_saves_test.ts b/tests/desktop_saves_test.ts new file mode 100644 index 0000000..86e0b70 --- /dev/null +++ b/tests/desktop_saves_test.ts @@ -0,0 +1,104 @@ +// SPDX-FileCopyrightText: 2026 Paula Wisnievski +// SPDX-License-Identifier: AGPL-3.0-or-later + +import { assertEquals, assertThrows } from "@std/assert"; +import { join } from "@std/path"; +import { write_mod } from "@/common/mod.ts"; +import type { ModData } from "@/common/mod_loader.ts"; +import { load_mods } from "@/server/load_mods.ts"; +import { + create_world, + install_mods, + list_mods, + list_worlds, + mods_dir, + set_world_mods, + world_to_play, +} from "@/desktop/saves.ts"; + +const EMPTY: ModData = { + blocks: [], + models: [], + items: [], + recipes: [], + ores: [], + spawns: [], + entities: [], + entity_models: [], + effects: [], + fluids: [], + tags: [], +}; + +function cubi(id: string, version = "1.0.0", dependencies: string[] = []) { + return write_mod({ + manifest: { + format_version: 1, + id, + name: id, + version, + dependencies: dependencies.map((id) => ({ id, version: "1.0.0" })), + }, + data: EMPTY, + textures: new Map(), + }); +} + +// a data folder with the app's mods installed in it +function data_folder() { + const data = Deno.makeTempDirSync({ prefix: "cubi_data_" }); + const app = join(data, "app_mods"); + Deno.mkdirSync(app); + Deno.writeFileSync(join(app, "base.cubi"), cubi("base")); + Deno.writeFileSync(join(app, "extra.cubi"), cubi("extra", "1.0.0", ["base"])); + install_mods(app, data); + return { data, app }; +} + +Deno.test("the app's mods are put in the mods folder, and updated with it", () => { + const { data, app } = data_folder(); + assertEquals(list_mods(data).map(({ id, version, dependencies }) => ({ id, version, dependencies })), [ + { id: "base", version: "1.0.0", dependencies: [] }, + { id: "extra", version: "1.0.0", dependencies: ["base"] }, + ]); + + Deno.writeFileSync(join(app, "base.cubi"), cubi("base", "2.0.0")); + install_mods(app, data); + assertEquals(list_mods(data).find(({ id }) => id === "base")?.version, "2.0.0"); + + // a broken file is left out, not in the way of the rest + Deno.writeTextFileSync(join(mods_dir(data), "broken.cubi"), "not a zip"); + assertEquals(list_mods(data).map(({ id }) => id), ["base", "extra"]); + Deno.removeSync(data, { recursive: true }); +}); + +Deno.test("worlds are made with a name and mods, which can be changed", () => { + const { data } = data_folder(); + assertEquals(list_worlds(data), []); + + create_world(data, " My World ", ["base"]); + assertEquals(list_worlds(data), [{ name: "My World", mods: ["base"] }]); + assertEquals(world_to_play(data, "My World").mod_files, ["base.cubi"]); + + set_world_mods(data, "My World", ["base", "extra"]); + assertEquals(world_to_play(data, "My World").mod_files, ["base.cubi", "extra.cubi"]); + + assertThrows(() => create_world(data, "my world", []), Error, "already a world"); + assertThrows(() => create_world(data, "../escape", []), Error, "letters, numbers"); + assertThrows(() => create_world(data, "", []), Error, "letters, numbers"); + assertThrows(() => create_world(data, "Other", ["missing"]), Error, "mods folder"); + assertThrows(() => set_world_mods(data, "../My World", []), Error, "no world"); + assertEquals(list_worlds(data).map(({ name }) => name), ["My World"], "nothing made by the ones that failed"); + + // a mod that was taken out of the folder + Deno.removeSync(join(mods_dir(data), "extra.cubi")); + assertThrows(() => world_to_play(data, "My World"), Error, `"extra"`); + Deno.removeSync(data, { recursive: true }); +}); + +Deno.test("a server can load only some of a folder's mods", async () => { + const { data } = data_folder(); + const mods = await load_mods(mods_dir(data), [], undefined, ["base.cubi"]); + assertEquals(mods.map(({ listing }) => listing.id), ["base"]); + Deno.removeSync(data, { recursive: true }); +});