420 lines
12 KiB
TypeScript
420 lines
12 KiB
TypeScript
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
|
|
// SPDX-License-Identifier: AGPL-3.0-or-later
|
|
|
|
import { canvas } from "./renderer/core.ts";
|
|
|
|
export type KeyCode =
|
|
// letters
|
|
| "KeyA"
|
|
| "KeyB"
|
|
| "KeyC"
|
|
| "KeyD"
|
|
| "KeyE"
|
|
| "KeyF"
|
|
| "KeyG"
|
|
| "KeyH"
|
|
| "KeyI"
|
|
| "KeyJ"
|
|
| "KeyK"
|
|
| "KeyL"
|
|
| "KeyM"
|
|
| "KeyN"
|
|
| "KeyO"
|
|
| "KeyP"
|
|
| "KeyQ"
|
|
| "KeyR"
|
|
| "KeyS"
|
|
| "KeyT"
|
|
| "KeyU"
|
|
| "KeyV"
|
|
| "KeyW"
|
|
| "KeyX"
|
|
| "KeyY"
|
|
| "KeyZ"
|
|
// top numbers
|
|
| "Digit0"
|
|
| "Digit1"
|
|
| "Digit2"
|
|
| "Digit3"
|
|
| "Digit4"
|
|
| "Digit5"
|
|
| "Digit6"
|
|
| "Digit7"
|
|
| "Digit8"
|
|
| "Digit9"
|
|
// arrows
|
|
| "ArrowUp"
|
|
| "ArrowDown"
|
|
| "ArrowLeft"
|
|
| "ArrowRight"
|
|
// controls
|
|
| "Space"
|
|
| "Escape"
|
|
| "Enter"
|
|
| "Tab"
|
|
| "ShiftLeft"
|
|
| "ShiftRight"
|
|
| "ControlLeft"
|
|
| "ControlRight"
|
|
| "MetaLeft"
|
|
| "MetaRight"
|
|
| "AltLeft"
|
|
| "AltRight"
|
|
| "Home"
|
|
| "End"
|
|
| "Backspace"
|
|
| "Slash"
|
|
| "Delete"
|
|
// f
|
|
| "F1"
|
|
| "F2"
|
|
| "F3"
|
|
| "F4"
|
|
| "F5"
|
|
| "F6"
|
|
| "F7"
|
|
| "F8"
|
|
| "F9"
|
|
| "F10"
|
|
| "F11"
|
|
| "F12";
|
|
|
|
// the keys the game keeps in fullscreen, see "fullscreenchange". not every key: with all of them locked, chromium
|
|
// can keep alt+tab and the windows key from the os too
|
|
const FULLSCREEN_LOCKED_KEYS = ["Escape", "KeyW"];
|
|
|
|
// chromium's keyboard lock api, typescript's dom types don't have it yet
|
|
interface KeyboardLock {
|
|
lock(codes?: string[]): Promise<void>;
|
|
unlock(): void;
|
|
}
|
|
|
|
export class InputManager {
|
|
static keys_down = new Set<string>();
|
|
static keys_pressed = new Set<string>();
|
|
static keys_released = new Set<string>();
|
|
|
|
static mouse_buttons_down = new Set<number>();
|
|
static mouse_buttons_pressed = new Set<number>();
|
|
static mouse_buttons_released = new Set<number>();
|
|
static mouse_buttons_consumed = new Set<number>();
|
|
|
|
static mouse_x = 0;
|
|
static mouse_y = 0;
|
|
// the cursor's movement over the page, while it isn't locked, like for dragging windows
|
|
static mouse_delta_x = 0;
|
|
static mouse_delta_y = 0;
|
|
// the mouse's movement while it's locked to the game, which turns the camera. kept apart so the cursor moving
|
|
// around a screen can never turn it
|
|
static look_delta_x = 0;
|
|
static look_delta_y = 0;
|
|
// chrome sometimes sends a huge movement with the first mouse event after the lock starts
|
|
static #skip_look_event = false;
|
|
static wheel_delta = 0;
|
|
|
|
// in the order they were typed. a list, since the same letter can be typed twice in one frame
|
|
static typed_characters: string[] = [];
|
|
// letters pressed with ctrl (cmd on macs) held, like "a" for select all
|
|
static shortcuts: string[] = [];
|
|
|
|
static pointer_lock_flag = false;
|
|
static mouse_grab_timer = 0;
|
|
static mouse_ungrab_timer = 0;
|
|
static mouse_ungrab_timeout = -1;
|
|
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) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (!this.keys_down.has(e.code)) {
|
|
this.keys_pressed.add(e.code);
|
|
}
|
|
this.keys_down.add(e.code);
|
|
if (e.key.length === 1) {
|
|
if (this.#is_shortcut(e)) {
|
|
this.shortcuts.push(e.key.toLowerCase());
|
|
} else {
|
|
this.typed_characters.push(e.key);
|
|
}
|
|
}
|
|
});
|
|
|
|
// keys let go while the window isn't focused never send keyup, so they'd stay held
|
|
self.addEventListener("blur", () => {
|
|
this.keys_down.clear();
|
|
this.mouse_buttons_down.clear();
|
|
});
|
|
|
|
self.addEventListener("keyup", (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
this.keys_down.delete(e.code);
|
|
this.keys_released.add(e.code);
|
|
});
|
|
|
|
self.addEventListener("mousedown", (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
if (!document.hasFocus() && document.pointerLockElement !== canvas) {
|
|
this.set_mouse_grabbed(true);
|
|
return;
|
|
}
|
|
if (!this.mouse_buttons_down.has(e.button)) {
|
|
this.mouse_buttons_pressed.add(e.button);
|
|
}
|
|
this.mouse_buttons_down.add(e.button);
|
|
});
|
|
|
|
self.addEventListener("mouseup", (e) => {
|
|
e.preventDefault();
|
|
this.mouse_buttons_down.delete(e.button);
|
|
this.mouse_buttons_released.add(e.button);
|
|
});
|
|
|
|
// ctrl+scroll (and pinching a trackpad, which browsers send as that) would zoom the page. only a listener that
|
|
// isn't passive can stop it, and on the window they're passive unless told otherwise
|
|
self.addEventListener("wheel", (e) => {
|
|
if (e.ctrlKey) {
|
|
e.preventDefault();
|
|
}
|
|
this.wheel_delta += e.deltaY;
|
|
}, { passive: false });
|
|
|
|
document.addEventListener("mousemove", (e) => {
|
|
e.preventDefault();
|
|
if (document.pointerLockElement === canvas) {
|
|
if (this.#skip_look_event) {
|
|
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 {
|
|
const rect = canvas.getBoundingClientRect();
|
|
const new_x = e.clientX - rect.left;
|
|
const new_y = e.clientY - rect.top;
|
|
|
|
// not from where it was before the mouse was grabbed, that's -1
|
|
if (this.mouse_x >= 0 && this.mouse_y >= 0) {
|
|
this.mouse_delta_x += new_x - this.mouse_x;
|
|
this.mouse_delta_y += new_y - this.mouse_y;
|
|
}
|
|
|
|
this.mouse_x = new_x;
|
|
this.mouse_y = new_y;
|
|
}
|
|
});
|
|
|
|
document.addEventListener("pointerlockchange", () => {
|
|
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) {
|
|
if (this.pointer_lock_flag) {
|
|
this.mouse_ungrab_timer = performance.now();
|
|
this.#lost_pointer_lock = true;
|
|
}
|
|
}
|
|
this.pointer_lock_flag = grab;
|
|
}, 60);
|
|
this.pointer_lock_waiting = false;
|
|
});
|
|
|
|
// in fullscreen, chromium's keyboard lock gives the game escape (holding it still leaves fullscreen) and ctrl+w,
|
|
// instead of the browser leaving fullscreen or closing the tab. other browsers don't have it and work as before
|
|
document.addEventListener("fullscreenchange", () => {
|
|
const keyboard = (navigator as Navigator & { keyboard?: KeyboardLock }).keyboard;
|
|
if (!keyboard?.lock) return;
|
|
if (document.fullscreenElement) {
|
|
keyboard.lock(FULLSCREEN_LOCKED_KEYS).catch(() => {});
|
|
} else {
|
|
keyboard.unlock();
|
|
}
|
|
});
|
|
|
|
document.addEventListener("pointerlockerror", () => {
|
|
this.pointer_lock_waiting = false;
|
|
});
|
|
}
|
|
|
|
static is_key_down(code: KeyCode): boolean {
|
|
return this.keys_down.has(code);
|
|
}
|
|
|
|
static is_key_pressed(code: KeyCode): boolean {
|
|
return this.keys_pressed.has(code);
|
|
}
|
|
|
|
static is_key_released(code: KeyCode): boolean {
|
|
return this.keys_released.has(code);
|
|
}
|
|
|
|
static is_mouse_down(button: number): boolean {
|
|
return this.mouse_buttons_down.has(button);
|
|
}
|
|
|
|
static is_mouse_pressed(button: number): boolean {
|
|
return this.mouse_buttons_pressed.has(button) &&
|
|
!this.mouse_buttons_consumed.has(button);
|
|
}
|
|
|
|
static is_mouse_released(button: number): boolean {
|
|
return this.mouse_buttons_released.has(button);
|
|
}
|
|
|
|
static get_mouse_position() {
|
|
return { x: this.mouse_x, y: this.mouse_y };
|
|
}
|
|
|
|
static get_mouse_delta() {
|
|
return { x: this.mouse_delta_x, y: this.mouse_delta_y };
|
|
}
|
|
|
|
// how far the locked mouse moved this frame, for turning the camera
|
|
static get_look_delta() {
|
|
return { x: this.look_delta_x, y: this.look_delta_y };
|
|
}
|
|
|
|
static get_wheel_delta(): number {
|
|
return this.wheel_delta;
|
|
}
|
|
|
|
static consume_mouse(button: number) {
|
|
this.mouse_buttons_consumed.add(button);
|
|
}
|
|
|
|
// ctrl (cmd on macs) held for a shortcut. altgr types characters like @ and comes as ctrl+alt on windows, so it
|
|
// isn't one. getModifierState("AltGraph") isn't used, some linux layouts report it along with plain ctrl
|
|
static #is_shortcut(e: KeyboardEvent) {
|
|
return e.metaKey || (e.ctrlKey && !e.altKey);
|
|
}
|
|
|
|
static is_shortcut_pressed(letter: string): boolean {
|
|
return this.shortcuts.includes(letter);
|
|
}
|
|
|
|
static get_typed_characters(): string[] {
|
|
const chars = this.typed_characters;
|
|
this.typed_characters = [];
|
|
return chars;
|
|
}
|
|
|
|
static update() {
|
|
this.keys_pressed.clear();
|
|
this.keys_released.clear();
|
|
this.mouse_buttons_pressed.clear();
|
|
this.mouse_buttons_released.clear();
|
|
this.mouse_delta_x = 0;
|
|
this.mouse_delta_y = 0;
|
|
this.look_delta_x = 0;
|
|
this.look_delta_y = 0;
|
|
this.wheel_delta = 0;
|
|
this.typed_characters = [];
|
|
this.shortcuts = [];
|
|
this.mouse_buttons_consumed.clear();
|
|
}
|
|
|
|
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);
|
|
this.mouse_ungrab_timeout = -1;
|
|
}
|
|
// already how it should be, the game calls this every frame
|
|
const locked = document.pointerLockElement === canvas;
|
|
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) {
|
|
this.mouse_x = -1;
|
|
this.mouse_y = -1;
|
|
this.pointer_lock_waiting = true;
|
|
try {
|
|
await canvas.requestPointerLock();
|
|
} catch (_) { /* */ }
|
|
if (this.mouse_ungrab_timeout !== -1) {
|
|
self.clearTimeout(this.mouse_ungrab_timeout);
|
|
}
|
|
this.mouse_ungrab_timeout = -1;
|
|
if (t - this.mouse_ungrab_timer < 3000) {
|
|
this.mouse_ungrab_timeout = self.setTimeout(async () => {
|
|
try {
|
|
await canvas.requestPointerLock();
|
|
} catch (_) { /* */ }
|
|
}, 3100 - (t - this.mouse_ungrab_timer));
|
|
}
|
|
} else {
|
|
if (!this.pointer_lock_waiting) {
|
|
document.exitPointerLock();
|
|
}
|
|
}
|
|
}
|
|
|
|
// whether the mouse was taken away since the last call, browsers eat the escape that does it
|
|
static take_lost_pointer_lock() {
|
|
const lost = this.#lost_pointer_lock;
|
|
this.#lost_pointer_lock = false;
|
|
return lost;
|
|
}
|
|
|
|
static is_mouse_grabbed() {
|
|
return document.hasFocus() && document.pointerLockElement === canvas;
|
|
}
|
|
|
|
static toggle_fullscreen() {
|
|
if (!document.fullscreenElement) {
|
|
canvas.requestFullscreen();
|
|
} else {
|
|
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<void> {
|
|
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<void>((resolve) => self.setTimeout(resolve, CENTERING_TIMEOUT_MS))]);
|
|
}
|