From 25937f2c31b528495babbb8d5dc58c6569136162 Mon Sep 17 00:00:00 2001 From: Paula Date: Sun, 22 Nov 2026 18:34:18 -0300 Subject: [PATCH] Drop deno desktop --- client/browser_input.ts | 44 +-------- client/native/main.ts | 2 +- client/native/messages.ts | 2 +- deno.json | 9 +- desktop/app.ts | 4 +- desktop/center_mouse.ts | 117 ------------------------ desktop/linux_launcher.ts | 68 -------------- desktop/main.ts | 168 ++++++++++++++++++++++++++++------- desktop/native.ts | 151 ------------------------------- desktop/shortcuts.ts | 52 ----------- desktop/shortcuts_windows.ts | 81 ----------------- desktop/shortcuts_x11.ts | 124 -------------------------- docs/modding_plan.md | 8 +- server/host.ts | 2 +- tools/desktop_all.ts | 116 ------------------------ 15 files changed, 147 insertions(+), 801 deletions(-) delete mode 100644 desktop/center_mouse.ts delete mode 100644 desktop/linux_launcher.ts delete mode 100644 desktop/native.ts delete mode 100644 desktop/shortcuts.ts delete mode 100644 desktop/shortcuts_windows.ts delete mode 100644 desktop/shortcuts_x11.ts delete mode 100644 tools/desktop_all.ts diff --git a/client/browser_input.ts b/client/browser_input.ts index 77e8fff..e0a7b62 100644 --- a/client/browser_input.ts +++ b/client/browser_input.ts @@ -24,17 +24,6 @@ let pointer_lock_waiting = false; let skip_look_event = false; // the browser let go of the mouse while the game wanted it, like escape or switching windows let lost_pointer_lock = false; -// the canvas had the pointer lock at the last pointerlockchange -let was_locked = false; -// the desktop app moving the cursor after the mouse was let go, see center_desktop_mouse. grabbing it again waits -// for that, or the move would come while it's locked and turn the camera -let centering = Promise.resolve(); -let awaiting_centering = false; -// the locked mouse doesn't turn the camera until then, the move can still reach chromium after the app answered, -// or the mouse was locked again before chromium said it let go -let ignore_look_until = 0; -// what the game last asked for, it can change while grabbing waits -let want_grab = false; export function listen_to_page(page_canvas: HTMLCanvasElement) { canvas = page_canvas; @@ -84,7 +73,6 @@ export function listen_to_page(page_canvas: HTMLCanvasElement) { skip_look_event = false; return; } - if (performance.now() < ignore_look_until) return; InputManager.look(e.movementX, e.movementY); } else { const rect = canvas.getBoundingClientRect(); @@ -93,15 +81,7 @@ export function listen_to_page(page_canvas: HTMLCanvasElement) { }); document.addEventListener("pointerlockchange", () => { - const locked = document.pointerLockElement === canvas; - if (was_locked && !locked) { - ignore_look_until = Infinity; - centering = center_desktop_mouse().then(() => { - ignore_look_until = performance.now() + CENTERING_SETTLE_MS; - }); - } - was_locked = locked; - skip_look_event = locked; + skip_look_event = document.pointerLockElement === canvas; self.setTimeout(() => { const grab = document.pointerLockElement === canvas; if (!grab) { @@ -140,7 +120,6 @@ function is_shortcut(e: KeyboardEvent) { export async function set_mouse_grabbed(grab: boolean) { pointer_lock_flag = grab; - want_grab = grab; // a retry to grab it again mustn't happen once it shouldn't be grabbed if (!grab && mouse_ungrab_timeout !== -1) { self.clearTimeout(mouse_ungrab_timeout); @@ -151,15 +130,6 @@ export async function set_mouse_grabbed(grab: boolean) { if (grab ? locked : !locked && !pointer_lock_waiting) { return; } - if (grab) { - // called every frame, once is enough - if (awaiting_centering) return; - awaiting_centering = true; - await centering; - awaiting_centering = false; - // a gui opened again meanwhile - if (!want_grab || document.pointerLockElement === canvas) return; - } const t = performance.now(); if (grab) { InputManager.mouse_x = -1; @@ -204,15 +174,3 @@ export function toggle_fullscreen() { document.exitFullscreen(); } } - -const CENTERING_TIMEOUT_MS = 250; -const CENTERING_SETTLE_MS = 100; - -// the desktop app (the page has ?singleplayer there, see desktop/main.ts) moves the cursor to the middle of the -// window when the mouse is let go to open a gui, like minecraft. chromium would put it back where it was grabbed. -// resolves once the cursor was moved, or after CENTERING_TIMEOUT_MS if the app is slow, so grabbing isn't held up -function center_desktop_mouse(): Promise { - if (!new URL(location.href).searchParams.has("singleplayer")) return Promise.resolve(); - const moved = fetch("/desktop/center_mouse", { method: "POST" }).then(() => {}, () => {}); - return Promise.race([moved, new Promise((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]); -} diff --git a/client/native/main.ts b/client/native/main.ts index c0bf0e0..4bf3853 100644 --- a/client/native/main.ts +++ b/client/native/main.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// the desktop app's client: a deno worker drawing into the app's window with webgpu, see desktop/native.ts. the +// the desktop app's client: a deno worker drawing into the app's window with webgpu, see desktop/main.ts. the // window sends what the player does (messages.ts), and does what needs the os, like grabbing the mouse. the browser's // client starts at ../main.ts import { type Platform, set_platform } from "../platform.ts"; diff --git a/client/native/messages.ts b/client/native/messages.ts index 1710402..525663c 100644 --- a/client/native/messages.ts +++ b/client/native/messages.ts @@ -1,7 +1,7 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -// what the desktop app's window (desktop/native.ts, on deno's main thread) and the client running in a worker (see +// what the desktop app's window (desktop/main.ts, on deno's main thread) and the client running in a worker (see // main.ts here) tell each other. the window has the os's events and the client draws into it // the window's surface, for deno's UnsafeWindowSurface. handles are pointers' addresses, pointers can't be posted diff --git a/deno.json b/deno.json index 0e05308..ad4e4d8 100644 --- a/deno.json +++ b/deno.json @@ -9,9 +9,7 @@ "pack-mod": "deno run --allow-read --allow-write --allow-run --allow-env tools/pack_mod.ts", "test": "deno test --allow-read --allow-write --allow-run --allow-net tests/", "bench": "deno bench --allow-read --allow-write --allow-run tests/", - "desktop": "deno run -A build.ts --once && deno desktop --allow-read --allow-write --allow-net --allow-ffi --allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG --include build --include server_mods --include server/game/worker.ts --include server/game/worldgen_worker.ts --include server/content_worker.ts --include desktop/config.json desktop/main.ts && deno run --allow-read --allow-write desktop/linux_launcher.ts dist/cubi", - "desktop-all": "deno run -A tools/desktop_all.ts", - "native": "deno run --unstable-webgpu --allow-read --allow-write --allow-net --allow-ffi --allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME desktop/native.ts" + "desktop": "deno run --unstable-webgpu --allow-read --allow-write --allow-net --allow-ffi --allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME desktop/main.ts" }, "compilerOptions": { "lib": ["dom", "dom.asynciterable", "dom.iterable", "deno.ns", "deno.unstable", "deno.webgpu"] @@ -45,10 +43,5 @@ "gl-matrix": "npm:gl-matrix@^3.4.4", "marked": "npm:marked@^17.0.3", "zod": "jsr:@zod/zod@^4.6.7" - }, - "desktop": { - "app": { "name": "cubi", "identifier": "com.bworld.game" }, - "backend": "cef", - "output": { "macos": "./dist/cubi.app", "windows": "./dist/cubi", "linux": "./dist/cubi" } } } diff --git a/desktop/app.ts b/desktop/app.ts index 0a6ff68..1a18381 100644 --- a/desktop/app.ts +++ b/desktop/app.ts @@ -3,7 +3,7 @@ // what the desktop app serves its client from: the client's files (updated from the site, see client_updates.ts), // and singleplayer, whose worlds are played on a game server of the app's own with the mods each world picked from -// its data folder (see saves.ts). the client is shown by main.ts in chromium, or by native.ts in a window of its own +// its data folder (see saves.ts). main.ts shows the client in the app's window import { fromFileUrl, join } from "@std/path"; import { serve_static } from "../server/host.ts"; import { PROTOCOL_VERSION } from "../common/protocol.ts"; @@ -11,7 +11,7 @@ import { current_client, update_client } from "./client_updates.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 +// where the project was built from, with what deno task build made in build/ and server_mods/ (the .cubi files) const ROOT = fromFileUrl(new URL("../", import.meta.url)); const BUILD_DIR = join(ROOT, "build"); diff --git a/desktop/center_mouse.ts b/desktop/center_mouse.ts deleted file mode 100644 index d3db707..0000000 --- a/desktop/center_mouse.ts +++ /dev/null @@ -1,117 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// when the game lets go of the mouse to open a gui, chromium puts the cursor back where it was grabbed. like minecraft -// it goes to the middle of the window instead, moved there by the os: libX11 on linux, user32 on windows. the page -// asks for it, see desktop/main.ts and client/input_manager.ts. nothing happens without the library or on macs - -const X11 = { - XOpenDisplay: { parameters: ["pointer"], result: "pointer" }, - XSetErrorHandler: { parameters: ["function"], result: "pointer" }, - XGetInputFocus: { parameters: ["pointer", "buffer", "buffer"], result: "i32" }, - XGetGeometry: { - parameters: ["pointer", "u64", "buffer", "buffer", "buffer", "buffer", "buffer", "buffer", "buffer"], - result: "i32", - }, - XWarpPointer: { parameters: ["pointer", "u64", "u64", "i32", "i32", "u32", "u32", "i32", "i32"], result: "i32" }, - XSync: { parameters: ["pointer", "i32"], result: "i32" }, -} as const; - -const USER32 = { - GetForegroundWindow: { parameters: [], result: "pointer" }, - GetWindowThreadProcessId: { parameters: ["pointer", "buffer"], result: "u32" }, - GetClientRect: { parameters: ["pointer", "buffer"], result: "i32" }, - ClientToScreen: { parameters: ["pointer", "buffer"], result: "i32" }, - SetCursorPos: { parameters: ["i32", "i32"], result: "i32" }, -} as const; - -// moves the cursor to the middle of the app's window, if it's the one in front. set up on the first call -export function center_mouse() { - center ??= setup(); - center(); -} - -let center: (() => void) | undefined; - -function setup(): () => void { - switch (Deno.build.os) { - case "linux": - return setup_x11(); - case "windows": - return setup_windows(); - default: - return () => {}; - } -} - -function setup_x11(): () => void { - let lib: Deno.DynamicLibrary; - try { - lib = Deno.dlopen("libX11.so.6", X11); - } catch (e) { - console.error(`Not centering the mouse, no libX11: ${(e as Error).message}`); - return () => {}; - } - const x = lib.symbols; - const display = x.XOpenDisplay(null); - if (!display) { - console.error("Not centering the mouse, no X display"); - return () => {}; - } - // xlib's own handler exits the process, like when the window went away - const on_error = new Deno.UnsafeCallback({ parameters: ["pointer", "pointer"], result: "i32" }, () => 0); - x.XSetErrorHandler(on_error.pointer); - - const focus = new BigUint64Array(1); - const revert_to = new Int32Array(1); - const root = new BigUint64Array(1); - const [left, top] = [new Int32Array(1), new Int32Array(1)]; - const [width, height, border, depth] = [ - new Uint32Array(1), - new Uint32Array(1), - new Uint32Array(1), - new Uint32Array(1), - ]; - return () => { - // the window with focus, chromium's own inside the app's frame, which has it while the game is asking - x.XGetInputFocus(display, focus, revert_to); - const window = focus[0]; - // None and PointerRoot - if (window <= 1n) return; - if (!x.XGetGeometry(display, window, root, left, top, width, height, border, depth)) return; - // from no particular window, to the middle of the app's - x.XWarpPointer(display, 0n, window, 0, 0, 0, 0, width[0] >> 1, height[0] >> 1); - // done before the page hears back, it grabs the mouse again only after that - x.XSync(display, 0); - }; -} - -function setup_windows(): () => void { - let lib: Deno.DynamicLibrary; - try { - lib = Deno.dlopen("user32.dll", USER32); - } catch (e) { - console.error(`Not centering the mouse, no user32: ${(e as Error).message}`); - return () => {}; - } - const user32 = lib.symbols; - - const owner = new Uint32Array(1); - // RECT: left, top, right, bottom - const rect = new Int32Array(4); - // POINT: x, y - const point = new Int32Array(2); - return () => { - // chromium's windows are this process's own, like in shortcuts_windows.ts - const window = user32.GetForegroundWindow(); - if (!window) return; - owner[0] = 0; - user32.GetWindowThreadProcessId(window, owner); - if (owner[0] !== Deno.pid) return; - if (!user32.GetClientRect(window, rect)) return; - point[0] = (rect[0] + rect[2]) >> 1; - point[1] = (rect[1] + rect[3]) >> 1; - if (!user32.ClientToScreen(window, point)) return; - user32.SetCursorPos(point[0], point[1]); - }; -} diff --git a/desktop/linux_launcher.ts b/desktop/linux_launcher.ts deleted file mode 100644 index f8d0436..0000000 --- a/desktop/linux_launcher.ts +++ /dev/null @@ -1,68 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// deno run --allow-read --allow-write desktop/linux_launcher.ts dist/bworld -// deno desktop has no setting for chromium's command line, but its linux launcher passes its arguments on to chromium. -// so this moves the launcher to bworld-bin and puts a script in its place that starts it with the switches webgpu -// needs on some linux setups. run it on the app folder after deno desktop builds it; running it again does nothing - -const SWITCHES = [ - "--enable-features=UseOzonePlatform,Vulkan,VulkanFromANGLE", - // "--enable-unsafe-webgpu", - "--use-angle=vulkan", - "--ozone-platform=wayland", - "--enable-wayland-ime", - "--wayland-text-input-version=3", -]; - -if (import.meta.main) { - // on its own it's run after building for the os it's on, which only needs wrapping on linux - if (Deno.build.os !== "linux") { - Deno.exit(0); - } - const dir = Deno.args[0]; - if (!dir) { - console.error("usage: linux_launcher.ts , like dist/cubi"); - Deno.exit(1); - } - wrap_linux_launcher(dir); -} - -// wraps the launcher of a linux build in dir. it works from any os, see tools/desktop_all.ts, but the script is only -// made executable on unix: zipping it from windows has to set that itself -export function wrap_linux_launcher(dir: string) { - const name = dir.replace(/[\/\\]+$/, "").split(/[\/\\]/).pop()!; - const launcher = `${dir}/${name}`; - const binary = `${launcher}-bin`; - - // already wrapped: the launcher is a script now - if (!is_elf(launcher)) { - console.log(`${launcher} is already wrapped`); - return; - } - - Deno.renameSync(launcher, binary); - Deno.writeTextFileSync( - launcher, - `#!/bin/sh -# starts ${name} with the chromium switches webgpu needs on some linux setups, see desktop/linux_launcher.ts. -# CUBI_CHROMIUM_FLAGS replaces them, set it to "" to start without any -here="$(dirname "$(readlink -f "$0")")" -# the binary finds its runtime by its own name, which is ${name}.so and not ${name}-bin.so -export LAUFEY_RUNTIME_PATH="$here/${name}.so" -exec "$here/${name}-bin" \${CUBI_CHROMIUM_FLAGS-${SWITCHES.join(" ")}} "$@" -`, - ); - if (Deno.build.os !== "windows") { - Deno.chmodSync(launcher, 0o755); - } - console.log(`Wrapped ${launcher}: ${SWITCHES.join(" ")}`); -} - -export function is_elf(path: string) { - const head = new Uint8Array(4); - const file = Deno.openSync(path); - file.readSync(head); - file.close(); - return head[0] === 0x7f && head[1] === 0x45 && head[2] === 0x4c && head[3] === 0x46; -} diff --git a/desktop/main.ts b/desktop/main.ts index e6446f9..89c78ad 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -1,47 +1,151 @@ // SPDX-FileCopyrightText: 2026 Paula Wisnievski // SPDX-License-Identifier: AGPL-3.0-or-later -/// - -// 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. 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 { guard_shortcuts } from "./shortcuts.ts"; -import { center_mouse } from "./center_mouse.ts"; +// the desktop app: an sdl window (sdl.ts) that the client draws into with deno's own webgpu, so it plays without a +// browser. the client runs in a worker (client/native/main.ts) loaded from the client's files like a page, and this +// thread passes it the window's events and does what it asks, like grabbing the mouse or playing sounds (openal.ts). +// the client's files and singleplayer are served on a local address, see app.ts +import { join, toFileUrl } from "@std/path"; import { desktop_app } from "./app.ts"; +import { SdlWindow } from "./sdl.ts"; +import { OpenAl } from "./openal.ts"; +import type { ClientMessage, WindowMessage } from "../client/native/messages.ts"; + +// how often the window's events are looked at, in milliseconds +const POLL_MS = 2; +// how often sounds are checked for having ended, in polls +const AUDIO_POLLS = 10; + +const game_window = new SdlWindow("bworld", 1280, 720); + +// the game plays without sound when there's no openal +let audio: OpenAl | undefined; +try { + audio = new OpenAl(); +} catch (e) { + console.error(`No sound: ${(e as Error).message}`); +} const app = desktop_app((message) => { console.error(message); - alert(`The singleplayer world stopped: ${message}`); + game_window.show_error("bworld", `The singleplayer world stopped: ${message}`); Deno.exit(1); }); -const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 }); -guard_shortcuts(win); +const server = Deno.serve( + { hostname: "127.0.0.1", port: 0, onListen() {} }, + (req) => app.handle(req, new URL(req.url)), +); +const start_page = app.start_page(`http://127.0.0.1:${server.addr.port}`); -// 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(); - await app.singleplayer.stop(); - Deno.exit(0); -}); - -if (Deno.env.get("DEBUG")) { - win.openDevtools(); +// what the client remembers, see Platform.storage +const STORAGE_FILE = join(app.data_dir, "client_storage.json"); +let storage: Record = {}; +try { + storage = JSON.parse(Deno.readTextFileSync(STORAGE_FILE)); +} catch { + // nothing saved yet } -// deno desktop binds this to a private local address and opens the window on it, the port given here is ignored -Deno.serve(async (req) => { - const url = new URL(req.url); - if (url.pathname === "/") { - return Response.redirect(app.start_page(url.origin), 302); +let client: Worker | undefined; +let closing = false; + +// a fresh client, like loading the page again. the old one is gone with everything it loaded +async function start_client(page: URL) { + client?.terminate(); + game_window.set_grabbed(false); + audio?.reset(); + const client_dir = await app.client_dir; + const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), { + type: "module", + deno: { + // the servers it plays on, and its own files. ffi is for drawing into the window, it gives it up after + permissions: { net: true, read: [client_dir], ffi: true, write: false, run: false, env: false, sys: false }, + }, + }); + worker.onmessage = (event: MessageEvent) => handle(event.data); + worker.onerror = (event) => { + console.error(`The client stopped: ${event.message}`); + }; + client = worker; + send({ + type: "start", + page: page.href, + surface: game_window.surface_handles(), + ...game_window.pixel_size(), + storage, + audio: audio !== undefined, + }); +} + +function send(message: WindowMessage) { + client?.postMessage(message); +} + +function handle(message: ClientMessage) { + // what it asks while the app closes, like sounds, would come after openal and the window are gone + if (closing) return; + switch (message.type) { + case "grab": + game_window.set_grabbed(message.grab); + break; + case "fullscreen": + game_window.toggle_fullscreen(); + break; + case "restart": { + const page = new URL(message.page); + // only its own pages + start_client(page.origin === start_page.origin ? page : start_page); + break; + } + // the client can't run at all, like without webgpu + case "fatal": + game_window.set_grabbed(false); + game_window.show_error("bworld", message.message); + close(); + break; + case "ask": + game_window.set_grabbed(false); + send({ + type: "answer", + id: message.id, + yes: game_window.ask(message.title, message.text, message.yes, message.no), + }); + break; + case "read_clipboard": + send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() }); + break; + case "write_clipboard": + game_window.write_clipboard(message.text); + break; + case "audio": + audio?.run(message.commands); + break; + case "store": + storage[message.key] = message.value; + Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t")); + break; } - // the page let go of the mouse, see center_mouse.ts - if (url.pathname === "/desktop/center_mouse" && req.method === "POST") { - center_mouse(); - return new Response(null, { status: 204 }); +} + +// the world gets saved before the app closes. the client isn't terminated first, exiting while a terminated worker is +// still letting go of its webgpu surface can crash deno, exiting stops it as well +async function close() { + if (closing) return; + closing = true; + clearInterval(polling); + await app.singleplayer.stop(); + audio?.close(); + game_window.close(); + Deno.exit(0); +} + +let polls = 0; +const polling = setInterval(() => { + game_window.poll(send, close); + if (audio && ++polls % AUDIO_POLLS === 0) { + const ended = audio.ended(); + if (ended.length) send({ type: "audio_ended", sources: ended }); } - return await app.handle(req, url); -}); +}, POLL_MS); +start_client(start_page); diff --git a/desktop/native.ts b/desktop/native.ts deleted file mode 100644 index 34c4de9..0000000 --- a/desktop/native.ts +++ /dev/null @@ -1,151 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// the desktop app without a browser: an sdl window (sdl.ts) that the client draws into with deno's own webgpu. the -// client runs in a worker (client/native/main.ts) loaded from the client's files like a page, and this thread passes -// it the window's events and does what it asks, like grabbing the mouse. the client's files and singleplayer are -// served on a local address like main.ts's chromium window has them, see app.ts -import { join, toFileUrl } from "@std/path"; -import { desktop_app } from "./app.ts"; -import { SdlWindow } from "./sdl.ts"; -import { OpenAl } from "./openal.ts"; -import type { ClientMessage, WindowMessage } from "../client/native/messages.ts"; - -// how often the window's events are looked at, in milliseconds -const POLL_MS = 2; -// how often sounds are checked for having ended, in polls -const AUDIO_POLLS = 10; - -const game_window = new SdlWindow("bworld", 1280, 720); - -// the game plays without sound when there's no openal -let audio: OpenAl | undefined; -try { - audio = new OpenAl(); -} catch (e) { - console.error(`No sound: ${(e as Error).message}`); -} - -const app = desktop_app((message) => { - console.error(message); - game_window.show_error("bworld", `The singleplayer world stopped: ${message}`); - Deno.exit(1); -}); - -const server = Deno.serve( - { hostname: "127.0.0.1", port: 0, onListen() {} }, - (req) => app.handle(req, new URL(req.url)), -); -const start_page = app.start_page(`http://127.0.0.1:${server.addr.port}`); - -// what the client remembers, see Platform.storage -const STORAGE_FILE = join(app.data_dir, "client_storage.json"); -let storage: Record = {}; -try { - storage = JSON.parse(Deno.readTextFileSync(STORAGE_FILE)); -} catch { - // nothing saved yet -} - -let client: Worker | undefined; -let closing = false; - -// a fresh client, like loading the page again. the old one is gone with everything it loaded -async function start_client(page: URL) { - client?.terminate(); - game_window.set_grabbed(false); - audio?.reset(); - const client_dir = await app.client_dir; - const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), { - type: "module", - deno: { - // the servers it plays on, and its own files. ffi is for drawing into the window, it gives it up after - permissions: { net: true, read: [client_dir], ffi: true, write: false, run: false, env: false, sys: false }, - }, - }); - worker.onmessage = (event: MessageEvent) => handle(event.data); - worker.onerror = (event) => { - console.error(`The client stopped: ${event.message}`); - }; - client = worker; - send({ - type: "start", - page: page.href, - surface: game_window.surface_handles(), - ...game_window.pixel_size(), - storage, - audio: audio !== undefined, - }); -} - -function send(message: WindowMessage) { - client?.postMessage(message); -} - -function handle(message: ClientMessage) { - // what it asks while the app closes, like sounds, would come after openal and the window are gone - if (closing) return; - switch (message.type) { - case "grab": - game_window.set_grabbed(message.grab); - break; - case "fullscreen": - game_window.toggle_fullscreen(); - break; - case "restart": { - const page = new URL(message.page); - // only its own pages - start_client(page.origin === start_page.origin ? page : start_page); - break; - } - // the client can't run at all, like without webgpu - case "fatal": - game_window.set_grabbed(false); - game_window.show_error("bworld", message.message); - close(); - break; - case "ask": - game_window.set_grabbed(false); - send({ - type: "answer", - id: message.id, - yes: game_window.ask(message.title, message.text, message.yes, message.no), - }); - break; - case "read_clipboard": - send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() }); - break; - case "write_clipboard": - game_window.write_clipboard(message.text); - break; - case "audio": - audio?.run(message.commands); - break; - case "store": - storage[message.key] = message.value; - Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t")); - break; - } -} - -// the world gets saved before the app closes. the client isn't terminated first, exiting while a terminated worker is -// still letting go of its webgpu surface can crash deno, exiting stops it as well -async function close() { - if (closing) return; - closing = true; - clearInterval(polling); - await app.singleplayer.stop(); - audio?.close(); - game_window.close(); - Deno.exit(0); -} - -let polls = 0; -const polling = setInterval(() => { - game_window.poll(send, close); - if (audio && ++polls % AUDIO_POLLS === 0) { - const ended = audio.ended(); - if (ended.length) send({ type: "audio_ended", sources: ended }); - } -}, POLL_MS); -start_client(start_page); diff --git a/desktop/shortcuts.ts b/desktop/shortcuts.ts deleted file mode 100644 index 0dcbbec..0000000 --- a/desktop/shortcuts.ts +++ /dev/null @@ -1,52 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// chromium's reserved shortcuts, like ctrl+w closing the window, happen before the page can stop them. sprinting is -// ctrl and walking is w, so the app takes those keys from the os before chromium sees them and hands them to the page. -// how depends on the os, see shortcuts_x11.ts and shortcuts_windows.ts. macs close with cmd+w, which isn't a game key -import { guard_shortcuts_x11 } from "./shortcuts_x11.ts"; -import { guard_shortcuts_windows } from "./shortcuts_windows.ts"; - -// the keys taken with ctrl and with ctrl+shift: their X11 key symbols, windows virtual keys, and how they reach the page -export const KEYS: { keysym: number; vk: number; code: string; key: string; shifted_key: string }[] = [ - // close the window, ctrl+shift+w too - { keysym: 0x77, vk: 0x57, code: "KeyW", key: "w", shifted_key: "W" }, - // new tab, reopen a closed one - { keysym: 0x74, vk: 0x54, code: "KeyT", key: "t", shifted_key: "T" }, - // new window - { keysym: 0x6e, vk: 0x4e, code: "KeyN", key: "n", shifted_key: "N" }, - // ctrl+shift+q quits on linux - { keysym: 0x71, vk: 0x51, code: "KeyQ", key: "q", shifted_key: "Q" }, - // switching tabs - { keysym: 0xff09, vk: 0x09, code: "Tab", key: "Tab", shifted_key: "Tab" }, - { keysym: 0xff55, vk: 0x21, code: "PageUp", key: "PageUp", shifted_key: "PageUp" }, - { keysym: 0xff56, vk: 0x22, code: "PageDown", key: "PageDown", shifted_key: "PageDown" }, - // ctrl+f4 closes the tab on windows - { keysym: 0xffc1, vk: 0x73, code: "F4", key: "F4", shifted_key: "F4" }, -]; - -export type Key = typeof KEYS[number]; - -export function guard_shortcuts(win: Deno.BrowserWindow) { - switch (Deno.build.os) { - case "linux": - guard_shortcuts_x11(win); - break; - case "windows": - guard_shortcuts_windows(win); - break; - } -} - -// to the page as if chromium had sent it, see client/input_manager.ts -export function send_key(win: Deno.BrowserWindow, type: "keydown" | "keyup", key: Key, ctrl: boolean, shift: boolean) { - const init = { - code: key.code, - key: shift ? key.shifted_key : key.key, - ctrlKey: ctrl, - shiftKey: shift, - bubbles: true, - cancelable: true, - }; - win.executeJs(`dispatchEvent(new KeyboardEvent(${JSON.stringify(type)}, ${JSON.stringify(init)}))`).catch(() => {}); -} diff --git a/desktop/shortcuts_windows.ts b/desktop/shortcuts_windows.ts deleted file mode 100644 index 53dcbe7..0000000 --- a/desktop/shortcuts_windows.ts +++ /dev/null @@ -1,81 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// on windows the app takes chromium's reserved shortcuts (see shortcuts.ts) as hotkeys, through user32. a hotkey takes -// the key press before any window gets it, its release still reaches chromium. hotkeys are for the whole system, so -// they're only registered while the app's window is in front. holding the key repeats the hotkey -import { KEYS, send_key } from "./shortcuts.ts"; - -const MOD_CONTROL = 0x2; -const MOD_SHIFT = 0x4; -const WM_HOTKEY = 0x0312; -const PM_REMOVE = 0x1; -// MSG on 64 bit windows: hwnd, then the message, wParam (the hotkey's id) and lParam (its modifiers and virtual key) -const MSG_SIZE = 48; -const MSG_MESSAGE = 8; -const MSG_LPARAM = 24; -// how often it looks for hotkeys and which window is in front, in milliseconds -const POLL_MS = 4; - -const USER32 = { - RegisterHotKey: { parameters: ["pointer", "i32", "u32", "u32"], result: "i32" }, - UnregisterHotKey: { parameters: ["pointer", "i32"], result: "i32" }, - PeekMessageW: { parameters: ["buffer", "pointer", "u32", "u32", "u32"], result: "i32" }, - GetForegroundWindow: { parameters: [], result: "pointer" }, - GetWindowThreadProcessId: { parameters: ["pointer", "buffer"], result: "u32" }, -} as const; - -export function guard_shortcuts_windows(win: Deno.BrowserWindow) { - let lib: Deno.DynamicLibrary; - try { - lib = Deno.dlopen("user32.dll", USER32); - } catch (e) { - console.error(`Not guarding shortcuts, no user32: ${(e as Error).message}`); - return; - } - const user32 = lib.symbols; - - // every key with ctrl and with ctrl+shift, by their ids. without a window, WM_HOTKEY goes to this thread's queue - const hotkeys = KEYS.flatMap((key) => - [MOD_CONTROL, MOD_CONTROL | MOD_SHIFT].map((modifiers) => ({ key, modifiers })) - ); - let registered = false; - const register = () => { - if (registered) return; - // one already taken by another app just isn't guarded - hotkeys.forEach(({ key, modifiers }, id) => user32.RegisterHotKey(null, id + 1, modifiers, key.vk)); - registered = true; - }; - const unregister = () => { - if (!registered) return; - hotkeys.forEach((_, id) => user32.UnregisterHotKey(null, id + 1)); - registered = false; - }; - win.addEventListener("close", unregister); - - // the cef backend never sends focus or blur on windows, so it checks whether the window in front is the app's. - // chromium's windows are this process's own - const owner = new Uint32Array(1); - const in_front = () => { - const window = user32.GetForegroundWindow(); - if (!window) return false; - owner[0] = 0; - user32.GetWindowThreadProcessId(window, owner); - return owner[0] === Deno.pid; - }; - - const msg = new Uint8Array(MSG_SIZE); - const view = new DataView(msg.buffer); - setInterval(() => { - if (in_front()) register(); - else unregister(); - while (user32.PeekMessageW(msg, null, WM_HOTKEY, WM_HOTKEY, PM_REMOVE)) { - if (view.getUint32(MSG_MESSAGE, true) !== WM_HOTKEY) continue; - const lparam = view.getUint32(MSG_LPARAM, true); - const modifiers = lparam & 0xffff; - const vk = lparam >>> 16; - const key = KEYS.find((k) => k.vk === vk); - if (key) send_key(win, "keydown", key, (modifiers & MOD_CONTROL) !== 0, (modifiers & MOD_SHIFT) !== 0); - } - }, POLL_MS); -} diff --git a/desktop/shortcuts_x11.ts b/desktop/shortcuts_x11.ts deleted file mode 100644 index ae7e0d1..0000000 --- a/desktop/shortcuts_x11.ts +++ /dev/null @@ -1,124 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// on linux the app takes chromium's reserved shortcuts (see shortcuts.ts) from the x server itself, with a passive grab -// on its window through libX11. deno desktop's chromium always runs on x11, see linux_launcher.ts. a grabbed key goes -// to the grabbing client until it's let go, so the grab is dropped right away and the key's release and everything -// after it reaches chromium as usual. holding it repeats the press, which is grabbed again each time -import { type Key, KEYS, send_key } from "./shortcuts.ts"; - -const SHIFT_MASK = 1 << 0; -const LOCK_MASK = 1 << 1; -const CONTROL_MASK = 1 << 2; -// num lock on most setups. a grab only matches the exact modifiers, so every lock combination gets one -const MOD2_MASK = 1 << 4; -const KEY_PRESS = 2; -const KEY_RELEASE = 3; -const GRAB_MODE_ASYNC = 1; -const CURRENT_TIME = 0n; -// XEvent is a union of 24 longs -const EVENT_SIZE = 24 * 8; -// XKeyEvent's fields on 64 bit systems -const EVENT_STATE = 80; -const EVENT_KEYCODE = 84; -// how often it looks for grabbed keys, in milliseconds -const POLL_MS = 4; - -const X11 = { - XOpenDisplay: { parameters: ["pointer"], result: "pointer" }, - XSetErrorHandler: { parameters: ["function"], result: "pointer" }, - XKeysymToKeycode: { parameters: ["pointer", "u64"], result: "u8" }, - XGetInputFocus: { parameters: ["pointer", "buffer", "buffer"], result: "i32" }, - XQueryTree: { parameters: ["pointer", "u64", "buffer", "buffer", "buffer", "buffer"], result: "i32" }, - XFree: { parameters: ["pointer"], result: "i32" }, - XGrabKey: { parameters: ["pointer", "i32", "u32", "u64", "i32", "i32", "i32"], result: "i32" }, - XUngrabKeyboard: { parameters: ["pointer", "u64"], result: "i32" }, - XPending: { parameters: ["pointer"], result: "i32" }, - XNextEvent: { parameters: ["pointer", "buffer"], result: "i32" }, - XFlush: { parameters: ["pointer"], result: "i32" }, - XSync: { parameters: ["pointer", "i32"], result: "i32" }, -} as const; - -// grabs the shortcuts on the window once it has focus, which is when x11 can tell which window is the app's. nothing -// happens without libX11 -export function guard_shortcuts_x11(win: Deno.BrowserWindow) { - let lib: Deno.DynamicLibrary; - try { - lib = Deno.dlopen("libX11.so.6", X11); - } catch (e) { - console.error(`Not guarding shortcuts, no libX11: ${(e as Error).message}`); - return; - } - const x = lib.symbols; - const display = x.XOpenDisplay(null); - if (!display) { - console.error("Not guarding shortcuts, no X display"); - return; - } - // xlib's own handler exits the process, like when another app already grabbed one of the keys - const on_error = new Deno.UnsafeCallback({ parameters: ["pointer", "pointer"], result: "i32" }, () => 0); - x.XSetErrorHandler(on_error.pointer); - - const by_keycode = new Map(); - for (const key of KEYS) { - const keycode = x.XKeysymToKeycode(display, BigInt(key.keysym)); - if (keycode) by_keycode.set(keycode, key); - } - - let grabbed = false; - win.addEventListener("focus", () => { - if (grabbed) return; - const window = top_level(x, display); - if (!window) return; - for (const keycode of by_keycode.keys()) { - for (const shift of [0, SHIFT_MASK]) { - for (const locks of [0, LOCK_MASK, MOD2_MASK, LOCK_MASK | MOD2_MASK]) { - const modifiers = CONTROL_MASK | shift | locks; - x.XGrabKey(display, keycode, modifiers, window, 0, GRAB_MODE_ASYNC, GRAB_MODE_ASYNC); - } - } - } - x.XSync(display, 0); - grabbed = true; - }); - - const event = new Uint8Array(EVENT_SIZE); - const view = new DataView(event.buffer); - setInterval(() => { - while (x.XPending(display) > 0) { - x.XNextEvent(display, event); - const type = view.getInt32(0, true); - if (type !== KEY_PRESS && type !== KEY_RELEASE) continue; - if (type === KEY_PRESS) { - x.XUngrabKeyboard(display, CURRENT_TIME); - x.XFlush(display); - } - const key = by_keycode.get(view.getUint32(EVENT_KEYCODE, true)); - const state = view.getUint32(EVENT_STATE, true); - if (key) { - const ctrl = (state & CONTROL_MASK) !== 0; - send_key(win, type === KEY_PRESS ? "keydown" : "keyup", key, ctrl, (state & SHIFT_MASK) !== 0); - } - } - }, POLL_MS); -} - -// the window that has focus, up to the one right under the root, which is the app's own window and not one of -// chromium's inside it -function top_level(x: Deno.DynamicLibrary["symbols"], display: Deno.PointerObject): bigint | undefined { - const focus = new BigUint64Array(1); - x.XGetInputFocus(display, focus, new Int32Array(1)); - let window = focus[0]; - // None and PointerRoot - if (window <= 1n) return undefined; - const root = new BigUint64Array(1); - const parent = new BigUint64Array(1); - const children = new BigUint64Array(1); - const count = new Uint32Array(1); - while (true) { - if (!x.XQueryTree(display, window, root, parent, children, count)) return undefined; - if (children[0]) x.XFree(Deno.UnsafePointer.create(children[0])); - if (parent[0] === root[0]) return window; - window = parent[0]; - } -} diff --git a/docs/modding_plan.md b/docs/modding_plan.md index 3478a21..53c0db2 100644 --- a/docs/modding_plan.md +++ b/docs/modding_plan.md @@ -431,7 +431,7 @@ saved before any of this plays exactly the same. - **Importing Minecraft's terrain.** Datapacks' noise settings assume a world from -64 to 320 and Minecraft's noises. The formats are close enough that an importer could translate them, but the result wouldn't look like Minecraft's. Not a goal for now. -- **Generation's loose ends.** The packaged desktop build hasn't been tried with the worldgen worker, which the desktop - task includes. In a world without land, the spawn search looks 32 chunks out on the game thread, which the server now - does at startup. Saved chunks are read on the game thread, which waits for the host (see `read_chunk` in - `server/game/worker.ts`): much faster than generating them, but Minecraft reads them ahead instead. +- **Generation's loose ends.** The desktop app isn't packaged yet, and a package will need the worldgen worker in it. In + a world without land, the spawn search looks 32 chunks out on the game thread, which the server now does at startup. + Saved chunks are read on the game thread, which waits for the host (see `read_chunk` in `server/game/worker.ts`): much + faster than generating them, but Minecraft reads them ahead instead. diff --git a/server/host.ts b/server/host.ts index d8e82de..9e450df 100644 --- a/server/host.ts +++ b/server/host.ts @@ -17,7 +17,7 @@ const MAX_MESSAGE_SIZE = 4096; export const ENGINE_TEXTURES_INDEX = "assets/textures/index.json"; const SHUTDOWN_TIMEOUT_MS = 5000; const DOWNLOAD_TIMEOUT_MS = 10_000; -// the desktop app's zips that deno task desktop-all makes, for the title screen's download button +// the desktop app's zips in dist/, for the title screen's download button export const DESKTOP_DOWNLOADS = ["windows.zip", "linux.zip"]; export interface HostOptions { diff --git a/tools/desktop_all.ts b/tools/desktop_all.ts deleted file mode 100644 index 22b7da0..0000000 --- a/tools/desktop_all.ts +++ /dev/null @@ -1,116 +0,0 @@ -// SPDX-FileCopyrightText: 2026 Paula Wisnievski -// SPDX-License-Identifier: AGPL-3.0-or-later - -// deno task desktop-all -// builds the desktop app for windows and linux, from whichever of them it runs on, and zips each into -// dist/windows.zip and dist/linux.zip for the title screen's download button. each zip has the app's bworld/ folder -import { walk } from "@std/fs"; -import { relative } from "@std/path"; -import { Zip, ZipDeflate } from "fflate"; -import { is_elf, wrap_linux_launcher } from "../desktop/linux_launcher.ts"; - -const APP_NAME = "bworld"; -const TARGETS = [ - { name: "windows", target: "x86_64-pc-windows-msvc" }, - { name: "linux", target: "x86_64-unknown-linux-gnu" }, -]; -// same as deno task desktop -const DESKTOP_ARGS = [ - "--allow-read", - "--allow-write", - "--allow-net", - "--allow-ffi", - "--allow-env=CUBI_SERVER,CUBI_CLIENT_UPDATES,HOME,USERPROFILE,APPDATA,XDG_DATA_HOME,DEBUG", - "--include", - "build", - "--include", - "server_mods", - "--include", - "server/game/worker.ts", - "--include", - "server/content_worker.ts", - "--include", - "desktop/config.json", - "desktop/main.ts", -]; - -async function run(args: string[]) { - const { success } = await new Deno.Command(Deno.execPath(), { args, stdout: "inherit", stderr: "inherit" }) - .output(); - if (!success) { - throw new Error(`deno ${args.join(" ")} failed`); - } -} - -function remove(path: string) { - try { - Deno.removeSync(path, { recursive: true }); - } catch (e) { - if (!(e instanceof Deno.errors.NotFound)) throw e; - } -} - -// zip is built on any os, so linux's executables are found by what they start with: elf binaries and scripts -function is_executable(path: string) { - if (is_elf(path)) return true; - const head = new Uint8Array(2); - const file = Deno.openSync(path); - file.readSync(head); - file.close(); - return head[0] === 0x23 && head[1] === 0x21; // #! -} - -// zips folder into out with the folder itself at its root. unix_modes keeps linux's executables executable -async function zip_folder(folder: string, out: string, unix_modes: boolean) { - const parent = `${folder}/..`; - const output = await Deno.open(out, { write: true, create: true, truncate: true }); - // the zip's chunks are written one after another, in order - let writes = Promise.resolve(); - const done = Promise.withResolvers(); - const zip = new Zip((error, chunk, final) => { - if (error) { - done.reject(error); - return; - } - writes = writes.then(() => write_all(output, chunk)); - if (final) done.resolve(); - }); - - for await (const entry of walk(folder, { includeDirs: false })) { - const file = new ZipDeflate(relative(parent, entry.path).replaceAll("\\", "/"), { level: 6 }); - if (unix_modes) { - file.os = 3; - file.attrs = (is_executable(entry.path) ? 0o100755 : 0o100644) << 16; - } - zip.add(file); - file.push(await Deno.readFile(entry.path), true); - } - zip.end(); - try { - await done.promise; - await writes; - } finally { - output.close(); - } -} - -async function write_all(file: Deno.FsFile, data: Uint8Array) { - for (let written = 0; written < data.length;) { - written += await file.write(data.subarray(written)); - } -} - -await run(["run", "-A", "build.ts", "--once"]); -for (const { name, target } of TARGETS) { - const dir = `dist/${name}`; - const app = `${dir}/${APP_NAME}`; - remove(dir); - console.log(`Building ${name} (${target})`); - await run(["desktop", "--target", target, "--output", app, ...DESKTOP_ARGS]); - if (name === "linux") { - wrap_linux_launcher(app); - } - const zip = `dist/${name}.zip`; - await zip_folder(app, zip, name === "linux"); - console.log(`Zipped ${zip}`); -}