Files
bworld/client/native/main.ts
T

202 lines
6.2 KiB
TypeScript

// 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/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";
import { InputManager } from "../input_manager.ts";
import { init_window, resize_canvas } from "../renderer/mod.ts";
import { show_fatal_error } from "../fatal.ts";
import { start_client } from "../client_loop.ts";
import { TextCreditsScreen } from "./credits_screen.ts";
import { install_web_audio, sources_ended } from "./web_audio.ts";
import { sounds } from "../sounds.ts";
import { WebAudioOutput } from "../audio_output.ts";
import type { ClientMessage, WindowMessage } from "./messages.ts";
const post = (message: ClientMessage) => self.postMessage(message);
// what the game asked for, the window does it
let grabbed = false;
let focused = true;
// the window let go of the mouse while the game had it, see Platform.take_lost_mouse
let lost_mouse = false;
// frames are each a task of their own, so input, the network and the workers' messages get handled in between.
// waiting for the display's refresh happens while drawing, the window's surface holds back frames the display can't
// show yet. a timer, not a MessageChannel like the browser's: deno handles a channel's messages before timers,
// fetches and the gpu's callbacks, so frames one after another through one would hold those back
let shown = true;
let next_frame: ((time: number) => void) | undefined;
let frame_waiting = false;
const shown_listeners: (() => void)[] = [];
function run_frame() {
frame_waiting = false;
const frame = next_frame;
next_frame = undefined;
frame?.(performance.now());
}
function request_frame(frame: (time: number) => void) {
next_frame = frame;
// a hidden window gets no frames, drawing to it could wait until it's shown again
if (shown) wait_for_frame();
}
function wait_for_frame() {
if (frame_waiting) return;
frame_waiting = true;
setTimeout(run_frame, 0);
}
function set_shown(now_shown: boolean) {
if (shown === now_shown) return;
shown = now_shown;
if (!shown) return;
for (const listener of shown_listeners) listener();
if (next_frame) wait_for_frame();
}
// what was asked of the window, by id, waiting for its answer
let next_id = 0;
const asking = new Map<number, (answer: string) => void>();
function ask(question: (id: number) => ClientMessage): Promise<string> {
const id = next_id++;
post(question(id));
return new Promise((resolve) => asking.set(id, resolve));
}
function native_platform(page: URL, stored: Record<string, string>, credits: string | undefined): Platform {
const storage = new Map(Object.entries(stored));
return {
page,
restart(url) {
post({ type: "restart", page: url.href });
},
request_frame,
on_shown(listener) {
shown_listeners.push(listener);
},
// kept by the window, which saves it with the app's data
storage: {
getItem: (key) => storage.get(key) ?? null,
setItem(key, value) {
storage.set(key, value);
post({ type: "store", key, value });
},
},
// the window saves the world when it closes
confirm_leaving() {},
show_fatal_error(message) {
post({ type: "fatal", message });
},
credits_screen: (on_back) => new TextCreditsScreen(on_back, credits),
read_clipboard: () => ask((id) => ({ type: "read_clipboard", id })),
write_clipboard(text) {
post({ type: "write_clipboard", text });
return Promise.resolve();
},
set_mouse_grabbed(grab) {
if (grab === grabbed) return;
grabbed = grab;
// it's no longer where it was, see InputManager.move_cursor
if (grab) {
InputManager.mouse_x = -1;
InputManager.mouse_y = -1;
}
post({ type: "grab", grab });
},
is_mouse_grabbed: () => grabbed && focused,
take_lost_mouse() {
const lost = lost_mouse;
lost_mouse = false;
return lost;
},
toggle_fullscreen() {
post({ type: "fullscreen" });
},
};
}
async function start(message: Extract<WindowMessage, { type: "start" }>) {
set_platform(native_platform(new URL(message.page), message.storage, message.credits));
const { surface: handles, width, height } = message;
const surface = new Deno.UnsafeWindowSurface({
system: handles.system,
windowHandle: Deno.UnsafePointer.create(handles.window),
displayHandle: Deno.UnsafePointer.create(handles.display),
width,
height,
});
// pointers to the window were all that needed ffi. mods run in here too, they don't get it
await Deno.permissions.revoke({ name: "ffi" });
try {
await init_window(surface);
} catch (e) {
show_fatal_error(e instanceof Error ? e.message : String(e));
throw e;
}
resize_canvas(width, height);
if (message.audio) {
install_web_audio((commands) => post({ type: "audio", commands }));
sounds.set_output(new WebAudioOutput(false));
}
await start_client();
}
self.onmessage = (event: MessageEvent<WindowMessage>) => {
const message = event.data;
switch (message.type) {
case "start":
start(message);
break;
case "resize":
resize_canvas(message.width, message.height);
break;
case "key":
if (message.down) InputManager.key_down(message.code, message.key, message.shortcut);
else InputManager.key_up(message.code);
break;
case "text":
InputManager.type_text(message.text);
break;
case "button":
if (message.down) InputManager.mouse_down(message.button);
else InputManager.mouse_up(message.button);
break;
case "cursor":
InputManager.move_cursor(message.x, message.y);
break;
case "look":
if (grabbed) InputManager.look(message.x, message.y);
break;
case "scroll":
InputManager.scroll(message.amount);
break;
case "focus":
focused = message.focused;
if (focused) break;
InputManager.release_all();
// the window let go of it, the game asks again once it wants it
if (grabbed) {
lost_mouse = true;
grabbed = false;
post({ type: "grab", grab: false });
}
break;
case "shown":
set_shown(message.shown);
break;
case "clipboard":
asking.get(message.id)?.(message.text);
asking.delete(message.id);
break;
case "audio_ended":
sources_ended(message.sources);
break;
}
};