From 3ec25c1471926402b3db2433dc846aa930a5ca42 Mon Sep 17 00:00:00 2001 From: Paula Date: Wed, 7 Oct 2026 13:59:23 -0300 Subject: [PATCH] Improve input --- client/input_manager.ts | 44 +++++++++++++++- desktop/center_mouse.ts | 114 ++++++++++++++++++++++++++++++++++++++++ desktop/main.ts | 6 +++ 3 files changed, 163 insertions(+), 1 deletion(-) create mode 100644 desktop/center_mouse.ts diff --git a/client/input_manager.ts b/client/input_manager.ts index fc664fd..7a66a02 100644 --- a/client/input_manager.ts +++ b/client/input_manager.ts @@ -121,6 +121,17 @@ export class InputManager { static pointer_lock_waiting = false; // the browser let go of the mouse while the game wanted it, like escape or switching windows static #lost_pointer_lock = false; + // the canvas had the pointer lock at the last pointerlockchange + static #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 + static #centering = Promise.resolve(); + static #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 + static #ignore_look_until = 0; + // what the game last asked for, it can change while grabbing waits + static #want_grab = false; static initialize(canvas: HTMLCanvasElement) { self.addEventListener("keydown", (e) => { @@ -187,6 +198,7 @@ export class InputManager { this.#skip_look_event = false; return; } + if (performance.now() < this.#ignore_look_until) return; this.look_delta_x += e.movementX; this.look_delta_y += e.movementY; } else { @@ -206,7 +218,15 @@ export class InputManager { }); document.addEventListener("pointerlockchange", () => { - this.#skip_look_event = document.pointerLockElement === canvas; + const locked = document.pointerLockElement === canvas; + if (this.#was_locked && !locked) { + this.#ignore_look_until = Infinity; + this.#centering = center_desktop_mouse().then(() => { + this.#ignore_look_until = performance.now() + CENTERING_SETTLE_MS; + }); + } + this.#was_locked = locked; + this.#skip_look_event = locked; self.setTimeout(() => { const grab = document.pointerLockElement === canvas; if (!grab) { @@ -316,6 +336,7 @@ export class InputManager { static async set_mouse_grabbed(grab: boolean) { this.pointer_lock_flag = grab; + this.#want_grab = grab; // a retry to grab it again mustn't happen once it shouldn't be grabbed if (!grab && this.mouse_ungrab_timeout !== -1) { self.clearTimeout(this.mouse_ungrab_timeout); @@ -326,6 +347,15 @@ export class InputManager { if (grab ? locked : !locked && !this.pointer_lock_waiting) { return; } + if (grab) { + // called every frame, once is enough + if (this.#awaiting_centering) return; + this.#awaiting_centering = true; + await this.#centering; + this.#awaiting_centering = false; + // a gui opened again meanwhile + if (!this.#want_grab || document.pointerLockElement === canvas) return; + } const t = performance.now(); this.mouse_grab_timer = t; if (grab) { @@ -372,3 +402,15 @@ export class InputManager { } } } + +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/desktop/center_mouse.ts b/desktop/center_mouse.ts new file mode 100644 index 0000000..cda31ce --- /dev/null +++ b/desktop/center_mouse.ts @@ -0,0 +1,114 @@ +// 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/main.ts b/desktop/main.ts index bb2223a..526f3cc 100644 --- a/desktop/main.ts +++ b/desktop/main.ts @@ -8,6 +8,7 @@ import { type Host, serve_static, start_host } 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"; // where the project was built from: build/ and server_mods/ (the .bmod files) are bundled into the app with --include const ROOT = fromFileUrl(new URL("../", import.meta.url)); @@ -92,6 +93,11 @@ Deno.serve(async (req) => { start.searchParams.set("singleplayer", ""); return Response.redirect(start, 302); } + // 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 singleplayer server's socket and its .bmod downloads if (url.pathname === "/ws" || url.pathname.startsWith("/mods/")) { try {