Files
bworld/desktop/sdl.ts
T

347 lines
13 KiB
TypeScript

// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the desktop app's window, with sdl3 through ffi: its native handles for webgpu to draw into, and its events as
// the client's messages (see client/native/messages.ts), keys named like the dom's. sdl's relative mouse mode grabs
// the mouse, which unlike a browser's pointer lock never gets taken away by escape or held back after letting go
import type { SurfaceHandles, WindowMessage } from "../client/native/messages.ts";
const LIBRARY = { linux: "libSDL3.so.0", windows: "SDL3.dll", darwin: "libSDL3.0.dylib" }[Deno.build.os as string];
const SYMBOLS = {
SDL_Init: { parameters: ["u32"], result: "bool" },
SDL_Quit: { parameters: [], result: "void" },
SDL_GetError: { parameters: [], result: "pointer" },
SDL_free: { parameters: ["pointer"], result: "void" },
SDL_GetCurrentVideoDriver: { parameters: [], result: "pointer" },
SDL_CreateWindow: { parameters: ["buffer", "i32", "i32", "u64"], result: "pointer" },
SDL_GetWindowProperties: { parameters: ["pointer"], result: "u32" },
SDL_GetPointerProperty: { parameters: ["u32", "buffer", "pointer"], result: "pointer" },
SDL_GetNumberProperty: { parameters: ["u32", "buffer", "i64"], result: "i64" },
SDL_GetWindowSizeInPixels: { parameters: ["pointer", "buffer", "buffer"], result: "bool" },
SDL_GetWindowSize: { parameters: ["pointer", "buffer", "buffer"], result: "bool" },
SDL_GetWindowFlags: { parameters: ["pointer"], result: "u64" },
SDL_SetWindowFullscreen: { parameters: ["pointer", "bool"], result: "bool" },
SDL_SetWindowRelativeMouseMode: { parameters: ["pointer", "bool"], result: "bool" },
SDL_WarpMouseInWindow: { parameters: ["pointer", "f32", "f32"], result: "void" },
SDL_StartTextInput: { parameters: ["pointer"], result: "bool" },
SDL_GetModState: { parameters: [], result: "u16" },
SDL_PollEvent: { parameters: ["buffer"], result: "bool" },
SDL_GetClipboardText: { parameters: [], result: "pointer" },
SDL_SetClipboardText: { parameters: ["buffer"], result: "bool" },
SDL_ShowSimpleMessageBox: { parameters: ["u32", "buffer", "buffer", "pointer"], result: "bool" },
SDL_ShowMessageBox: { parameters: ["buffer", "buffer"], result: "bool" },
} as const;
const INIT_VIDEO = 0x20;
const WINDOW_FULLSCREEN = 0x1n;
const WINDOW_RESIZABLE = 0x20n;
const MESSAGEBOX_ERROR = 0x10;
const MESSAGEBOX_WARNING = 0x20;
const BUTTON_RETURNKEY_DEFAULT = 0x1;
const BUTTON_ESCAPEKEY_DEFAULT = 0x2;
const EVENT_QUIT = 0x100;
const EVENT_WINDOW_SHOWN = 0x202;
const EVENT_WINDOW_HIDDEN = 0x203;
const EVENT_WINDOW_EXPOSED = 0x204;
const EVENT_WINDOW_PIXEL_SIZE_CHANGED = 0x207;
const EVENT_WINDOW_MINIMIZED = 0x209;
const EVENT_WINDOW_MAXIMIZED = 0x20a;
const EVENT_WINDOW_RESTORED = 0x20b;
const EVENT_WINDOW_FOCUS_GAINED = 0x20e;
const EVENT_WINDOW_FOCUS_LOST = 0x20f;
const EVENT_WINDOW_CLOSE_REQUESTED = 0x210;
const EVENT_WINDOW_OCCLUDED = 0x216;
const EVENT_KEY_DOWN = 0x300;
const EVENT_KEY_UP = 0x301;
const EVENT_TEXT_INPUT = 0x303;
const EVENT_MOUSE_MOTION = 0x400;
const EVENT_MOUSE_BUTTON_DOWN = 0x401;
const EVENT_MOUSE_BUTTON_UP = 0x402;
const EVENT_MOUSE_WHEEL = 0x403;
const KMOD_CTRL = 0x00c0;
const KMOD_ALT = 0x0300;
const KMOD_GUI = 0x0c00;
// a wheel notch, in the dom's pixels
const WHEEL_NOTCH = 100;
// sdl's scancodes (usb's key numbers) as the dom's KeyboardEvent.code
const KEY_CODES: Record<number, string> = {
40: "Enter",
41: "Escape",
42: "Backspace",
43: "Tab",
44: "Space",
45: "Minus",
46: "Equal",
47: "BracketLeft",
48: "BracketRight",
49: "Backslash",
50: "Backslash",
51: "Semicolon",
52: "Quote",
53: "Backquote",
54: "Comma",
55: "Period",
56: "Slash",
57: "CapsLock",
70: "PrintScreen",
71: "ScrollLock",
72: "Pause",
73: "Insert",
74: "Home",
75: "PageUp",
76: "Delete",
77: "End",
78: "PageDown",
79: "ArrowRight",
80: "ArrowLeft",
81: "ArrowDown",
82: "ArrowUp",
83: "NumLock",
84: "NumpadDivide",
85: "NumpadMultiply",
86: "NumpadSubtract",
87: "NumpadAdd",
88: "NumpadEnter",
98: "Numpad0",
99: "NumpadDecimal",
100: "IntlBackslash",
101: "ContextMenu",
224: "ControlLeft",
225: "ShiftLeft",
226: "AltLeft",
227: "MetaLeft",
228: "ControlRight",
229: "ShiftRight",
230: "AltRight",
231: "MetaRight",
};
for (let i = 0; i < 26; i++) KEY_CODES[4 + i] = `Key${String.fromCharCode(65 + i)}`;
for (let i = 0; i < 9; i++) KEY_CODES[30 + i] = `Digit${i + 1}`;
KEY_CODES[39] = "Digit0";
for (let i = 0; i < 12; i++) KEY_CODES[58 + i] = `F${i + 1}`;
for (let i = 0; i < 9; i++) KEY_CODES[89 + i] = `Numpad${i + 1}`;
const encoder = new TextEncoder();
const c_string = (text: string) => encoder.encode(text + "\0");
const read_string = (pointer: Deno.PointerValue) => pointer ? Deno.UnsafePointerView.getCString(pointer) : "";
export class SdlWindow {
#sdl: Deno.DynamicLibrary<typeof SYMBOLS>["symbols"];
#window: Deno.PointerObject;
#event = new Uint8Array(128);
#event_view = new DataView(this.#event.buffer);
#relative = false;
// the grabbed mouse's movement and the cursor's last place since the last message, sent as one
#look = { x: 0, y: 0 };
#cursor: { x: number; y: number } | undefined;
// throws when there's no sdl3 or no window can be made
constructor(title: string, width: number, height: number) {
if (!LIBRARY) throw new Error(`There's no sdl3 for ${Deno.build.os}`);
this.#sdl = Deno.dlopen(LIBRARY, SYMBOLS).symbols;
if (!this.#sdl.SDL_Init(INIT_VIDEO)) throw new Error(`Couldn't start sdl: ${this.#error()}`);
// not high pixel density: frames are drawn at the window's size and the os scales them, like a page's canvas
const window = this.#sdl.SDL_CreateWindow(c_string(title), width, height, WINDOW_RESIZABLE);
if (!window) throw new Error(`Couldn't open a window: ${this.#error()}`);
this.#window = window;
this.#sdl.SDL_StartTextInput(window);
}
#error() {
return read_string(this.#sdl.SDL_GetError());
}
// what webgpu needs to draw into the window
surface_handles(): SurfaceHandles {
const sdl = this.#sdl;
const properties = sdl.SDL_GetWindowProperties(this.#window);
const pointer = (name: string) =>
Deno.UnsafePointer.value(sdl.SDL_GetPointerProperty(properties, c_string(name), null));
const driver = read_string(sdl.SDL_GetCurrentVideoDriver());
switch (driver) {
case "wayland":
return {
system: "wayland",
window: pointer("SDL.window.wayland.surface"),
display: pointer("SDL.window.wayland.display"),
};
case "x11":
return {
system: "x11",
window: BigInt(sdl.SDL_GetNumberProperty(properties, c_string("SDL.window.x11.window"), 0n)),
display: pointer("SDL.window.x11.display"),
};
case "windows":
return {
system: "win32",
window: pointer("SDL.window.win32.hwnd"),
display: pointer("SDL.window.win32.instance"),
};
default:
throw new Error(`Can't draw into ${driver} windows`);
}
}
// in pixels
pixel_size() {
const [width, height] = [new Int32Array(1), new Int32Array(1)];
this.#sdl.SDL_GetWindowSizeInPixels(this.#window, width, height);
return { width: width[0], height: height[0] };
}
// the mouse turns the camera instead of moving a cursor. letting go puts the cursor in the middle
set_grabbed(grab: boolean) {
if (grab === this.#relative) return;
this.#relative = grab;
if (!grab) {
const [width, height] = [new Int32Array(1), new Int32Array(1)];
this.#sdl.SDL_GetWindowSize(this.#window, width, height);
this.#sdl.SDL_WarpMouseInWindow(this.#window, width[0] / 2, height[0] / 2);
this.#cursor = { x: width[0] / 2, y: height[0] / 2 };
}
this.#sdl.SDL_SetWindowRelativeMouseMode(this.#window, grab);
}
toggle_fullscreen() {
const fullscreen = (this.#sdl.SDL_GetWindowFlags(this.#window) & WINDOW_FULLSCREEN) !== 0n;
this.#sdl.SDL_SetWindowFullscreen(this.#window, !fullscreen);
}
read_clipboard(): string {
const text = this.#sdl.SDL_GetClipboardText();
const result = read_string(text);
this.#sdl.SDL_free(text);
return result;
}
write_clipboard(text: string) {
this.#sdl.SDL_SetClipboardText(c_string(text));
}
show_error(title: string, text: string) {
this.#sdl.SDL_ShowSimpleMessageBox(MESSAGEBOX_ERROR, c_string(title), c_string(text), this.#window);
}
// waits for the player to pick yes or no, no if the box can't be shown
ask(title: string, text: string, yes: string, no: string): boolean {
const [title_text, message, yes_text, no_text] = [title, text, yes, no].map(c_string);
const ptr = (buffer: Uint8Array<ArrayBuffer>) =>
BigInt(Deno.UnsafePointer.value(Deno.UnsafePointer.of(buffer)));
// SDL_MessageBoxButtonData: flags, id, text
const buttons = new ArrayBuffer(32);
const button_view = new DataView(buttons);
button_view.setUint32(0, BUTTON_ESCAPEKEY_DEFAULT, true);
button_view.setInt32(4, 0, true);
button_view.setBigUint64(8, ptr(no_text), true);
button_view.setUint32(16, BUTTON_RETURNKEY_DEFAULT, true);
button_view.setInt32(20, 1, true);
button_view.setBigUint64(24, ptr(yes_text), true);
// SDL_MessageBoxData: flags, window, title, message, button count, buttons, colors
const data = new ArrayBuffer(56);
const data_view = new DataView(data);
data_view.setUint32(0, MESSAGEBOX_WARNING, true);
data_view.setBigUint64(8, BigInt(Deno.UnsafePointer.value(this.#window)), true);
data_view.setBigUint64(16, ptr(title_text), true);
data_view.setBigUint64(24, ptr(message), true);
data_view.setInt32(32, 2, true);
data_view.setBigUint64(40, ptr(new Uint8Array(buttons)), true);
const picked = new Int32Array([0]);
const shown = this.#sdl.SDL_ShowMessageBox(new Uint8Array(data), picked);
return shown && picked[0] === 1;
}
// everything that happened since the last call, as the client's messages. on_close is for the window being closed
poll(send: (message: WindowMessage) => void, on_close: () => void) {
const sdl = this.#sdl;
const event = this.#event_view;
const flush = () => {
if (this.#look.x || this.#look.y) send({ type: "look", ...this.#look });
if (this.#cursor) send({ type: "cursor", ...this.#cursor });
this.#look = { x: 0, y: 0 };
this.#cursor = undefined;
};
while (sdl.SDL_PollEvent(this.#event)) {
const type = event.getUint32(0, true);
// motion comes in often, so it's added up and sent before anything else
if (type === EVENT_MOUSE_MOTION) {
if (this.#relative) {
this.#look.x += event.getFloat32(36, true);
this.#look.y += event.getFloat32(40, true);
} else {
this.#cursor = { x: event.getFloat32(28, true), y: event.getFloat32(32, true) };
}
continue;
}
flush();
switch (type) {
case EVENT_QUIT:
case EVENT_WINDOW_CLOSE_REQUESTED:
on_close();
break;
case EVENT_WINDOW_PIXEL_SIZE_CHANGED:
send({ type: "resize", width: event.getInt32(20, true), height: event.getInt32(24, true) });
break;
case EVENT_WINDOW_FOCUS_GAINED:
send({ type: "focus", focused: true });
send({ type: "shown", shown: true });
break;
case EVENT_WINDOW_FOCUS_LOST:
send({ type: "focus", focused: false });
break;
case EVENT_WINDOW_SHOWN:
case EVENT_WINDOW_EXPOSED:
case EVENT_WINDOW_RESTORED:
case EVENT_WINDOW_MAXIMIZED:
send({ type: "shown", shown: true });
break;
case EVENT_WINDOW_HIDDEN:
case EVENT_WINDOW_MINIMIZED:
case EVENT_WINDOW_OCCLUDED:
send({ type: "shown", shown: false });
break;
case EVENT_KEY_DOWN:
case EVENT_KEY_UP: {
const code = KEY_CODES[event.getUint32(24, true)];
if (!code) break;
const keycode = event.getUint32(28, true);
const shortcut = is_shortcut(event.getUint16(32, true));
// a letter with ctrl held is a shortcut, see InputManager.key_down. typing comes as text
const key = shortcut && keycode >= 0x20 && keycode < 0x7f ? String.fromCharCode(keycode) : "";
send({ type: "key", down: type === EVENT_KEY_DOWN, code, key, shortcut });
break;
}
case EVENT_TEXT_INPUT: {
// ctrl+c is a shortcut, not a c
if (is_shortcut(sdl.SDL_GetModState())) break;
const text = Deno.UnsafePointer.create(event.getBigUint64(24, true));
send({ type: "text", text: read_string(text) });
break;
}
case EVENT_MOUSE_BUTTON_DOWN:
case EVENT_MOUSE_BUTTON_UP:
// sdl counts from 1: left, middle, right, back, forward. the dom from 0
send({ type: "button", down: type === EVENT_MOUSE_BUTTON_DOWN, button: event.getUint8(24) - 1 });
break;
case EVENT_MOUSE_WHEEL:
send({ type: "scroll", amount: -event.getFloat32(28, true) * WHEEL_NOTCH });
break;
}
}
flush();
}
close() {
this.#sdl.SDL_Quit();
}
}
// ctrl (cmd on macs) held for a shortcut, not altgr, which some systems have as ctrl+alt
function is_shortcut(mod: number) {
return (mod & KMOD_GUI) !== 0 || ((mod & KMOD_CTRL) !== 0 && (mod & KMOD_ALT) === 0);
}