commit d239b7175e5f993f309fd0643169cb20b037733a
parent e3b4cfaed234d8bad4a4f23159258e5a6aca24e6
Author: anon <anon@example.com>
Date: Mon, 19 Oct 2026 19:41:23 +0000
Add mobile browser controls and keyboard-aware chat
Add mobile movement, steering, camera orbit, autorun, actions and options. Keep overlays and native HUD adjustments limited to mobile browsers, and support touch interaction and chat above the phone keyboard.
Bound retained asset chunks to reduce memory use. Document Android validation and the unresolved iOS Safari startup crash.
Diffstat:
12 files changed, 2606 insertions(+), 80 deletions(-)
diff --git a/README.md b/README.md
@@ -28,10 +28,22 @@ required. New visitors start in run mode with character tips disabled.
Click the game or press a key to enable sound.
Two-finger scrolling (or a mouse wheel) rotates the browser camera. Right-button
drag and Ctrl-drag also work; the game canvas suppresses the browser context menu.
-Press Ctrl+Alt+M (Control+Option+M on Mac) for the player display menu. Switch
+Press Ctrl+Alt+M (Control+Option+M on Mac), or tap Opt on mobile, for player settings. Switch
between CSS pixels and Retina pixels while playing; the choice is remembered.
Retina uses the screen's pixel density, making the original interface smaller
and sharper as well as increasing rendering resolution.
+The menu also provides fullscreen and, on mobile, touch controls and a 1P/3P toggle.
+On mobile, Move controls forward/backward and strafing; swipe the world to steer
+and drag with two fingers to orbit. Autorun keeps moving after releasing Move.
+Jump, Attack and Use buttons provide the common keyboard actions; inventory uses
+the game's native INV button.
+Tap the game to left-click, drag to move windows or items, and hold briefly for
+a right-click. Touch controls hide while settings or the chat composer is open.
+Tap Chat to open the phone keyboard; Send enters the message through the game's
+chat input. The composer accepts the game's Windows-1252 character set and
+reports unsupported characters before sending.
+Android Firefox has been tested on a Android phone. iOS Safari still crashes during
+startup and is not yet supported.
Press Enter to chat nearby. `/tell Visitor81 hello` sends a private message;
`/g Global hello` sends to everyone connected. `/whisper` and `/shout` change
the vicinity range. Visitor names contain no spaces so they work in commands.
diff --git a/src/browser/index.html b/src/browser/index.html
@@ -1,41 +1,101 @@
<!doctype html>
<html lang="en">
<meta charset="utf-8">
-<meta name="viewport" content="width=device-width, initial-scale=1">
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-visual">
<title>Anarchy Online 14.9.1</title>
<style>
html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #111; color: #ddd; font: 14px sans-serif; }
- canvas { display: block; width: 100%; height: 100%; }
+ @font-face { font-family: GameVerdana; src: url('/browser-assets/fonts/verdana.ttf'); }
+ #game-surface { position: absolute; left: 0; top: 0; width: 100%; height: 100%; }
+ canvas { display: block; width: 100%; height: 100%; touch-action: none; }
+ button, select, input { font: inherit; }
+ button { min-height: 44px; }
+ #game-toolbar { position: absolute; top: max(24px, env(safe-area-inset-top)); right: max(8px, env(safe-area-inset-right)); display: flex; gap: 8px; }
+ #game-toolbar button, #touch-controls button { border: 1px solid #aaa8; border-radius: 8px; background: #202428d9; color: #fff; }
+ #game-toolbar button, #touch-actions button { padding: 8px 12px; }
+ #touch-controls { position: absolute; inset: 0; pointer-events: none; user-select: none; -webkit-user-select: none; }
+ #game-toolbar[hidden], #touch-controls[hidden], #chat-compose[hidden], #chat-actions[hidden] { display: none; }
+ #game-toolbar, #touch-controls { animation: fade-overlays 4s linear forwards; }
+ #game-surface[data-overlays-active] #game-toolbar, #game-surface[data-overlays-active] #touch-controls { animation: none; opacity: 1; }
+ @keyframes fade-overlays { from { opacity: 1; } to { opacity: 0; } }
+ #chat-actions { display: flex; gap: 8px; }
+ #touch-controls button { pointer-events: auto; touch-action: none; }
+ #move-pad { position: absolute; bottom: max(64px, calc(env(safe-area-inset-bottom) + 48px)); width: 112px; height: 112px; border-radius: 50% !important; opacity: .5; }
+ #move-pad[data-active] { opacity: .8; }
+ #move-pad { left: max(16px, env(safe-area-inset-left)); }
+ #move-thumb { position: absolute; inset: 36px; border-radius: 50%; background: #ffffff30; pointer-events: none; }
+ #touch-actions { position: absolute; bottom: max(24px, env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); display: flex; gap: 6px; }
+ #chat-button, #menu-button, #touch-actions button { opacity: .5; }
+ #chat-button:active, #menu-button:active, #touch-actions button:active { opacity: .8; }
+ #chat-compose { position: absolute; }
+ #chat-text { display: block; box-sizing: border-box; width: 100%; height: 100%; min-width: 0; padding: 0; border: 0; border-radius: 0; outline: none; background: #222; color: #fff; font: 12px GameVerdana, Verdana, sans-serif; }
#loading { position: fixed; inset: 0; display: grid; place-items: center; pointer-events: none; }
#loading[hidden] { display: none; }
dialog { width: min(320px, calc(100vw - 64px)); padding: 24px; border: 1px solid #777; border-radius: 8px; background: #202428; color: #eee; box-shadow: 0 8px 40px #0008; }
dialog::backdrop { background: #0006; }
- dialog h1 { margin: 0 0 20px; font-size: 20px; }
+ dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; }
+ dialog h1 { margin: 0; font-size: 20px; }
dialog select { display: block; width: 100%; margin: 8px 0; padding: 8px; }
dialog p { color: #bbb; line-height: 1.5; }
dialog button { padding: 8px 16px; cursor: pointer; }
+ dialog label { display: block; margin: 12px 0; }
+ #menu-error { color: #ffb0a0; }
+ #menu-error:empty { display: none; }
</style>
+<div id="game-surface">
<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
<div id="loading" role="status">Loading...</div>
+<div id="game-toolbar" hidden>
+ <div id="chat-actions" hidden>
+ <button form="chat-compose">Send</button>
+ <button id="chat-cancel" type="button">Cancel</button>
+ </div>
+ <button id="menu-button">Opt</button>
+ <button id="chat-button" disabled>Chat</button>
+</div>
+<div id="touch-controls" hidden>
+ <button id="move-pad" aria-label="Move: drag forward, backward or sideways"><span id="move-thumb"></span>Move</button>
+ <div id="touch-actions">
+ <button id="autorun-button" aria-pressed="false">Autorun</button>
+ <button data-key="113">Attack</button>
+ <button data-key="101">Use</button>
+ <button data-key="32">Jump</button>
+ </div>
+</div>
+<form id="chat-compose" hidden>
+ <input id="chat-text" aria-label="Chat message" enterkeyhint="send" autocomplete="off" required>
+</form>
+</div>
<dialog id="player-menu" aria-labelledby="menu-title">
- <h1 id="menu-title">Display</h1>
+ <header>
+ <h1 id="menu-title">Options</h1>
+ <form method="dialog"><button>Close</button></form>
+ </header>
+ <button id="fullscreen-button">Enter fullscreen</button>
+ <p id="menu-error" role="status"></p>
<label for="pixel-mode">Resolution</label>
<select id="pixel-mode">
<option value="css">CSS pixels</option>
<option value="retina">Retina pixels</option>
</select>
<output id="render-size"></output>
- <p>Retina makes the scene sharper and the game interface smaller. It may reduce frame rate.</p>
- <form method="dialog"><button>Back to game</button></form>
- <p>Ctrl+Alt+M to open or close. Escape to close.</p>
+ <div id="mobile-options" hidden>
+ <button id="view-button">Toggle 1P / 3P</button>
+ <label><input id="touch-enabled" type="checkbox"> Touch controls</label>
+ <p>Left pad: move. Swipe: steer. Two fingers: orbit. Hold: right click.</p>
+ </div>
</dialog>
<script>
const status = document.querySelector('#loading');
const canvas = document.querySelector('#canvas');
+ const gameSurface = document.querySelector('#game-surface');
const playerMenu = document.querySelector('#player-menu');
const pixelMode = document.querySelector('#pixel-mode');
+ // Distinguish iPadOS's desktop Mac user agent by its touch support.
+ const isMobileBrowser = /Android|iPhone|iPad|iPod/.test(navigator.userAgent) ||
+ (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
pixelMode.value = localStorage.getItem('ao-pixel-mode') === 'retina' ? 'retina' : 'css';
- let runtimeReady = false;
+ let runtimeReady = false, gameReady = false;
let recording = null, reportURL = null;
function log(message) {
console.log(message);
@@ -50,11 +110,17 @@
status.hidden = false;
console.error(message);
},
- onFirstFrame: () => { status.hidden = true; },
+ onFirstFrame: () => {
+ status.hidden = true;
+ gameReady = true;
+ document.querySelector('#chat-button').disabled = !isMobileBrowser || !chatBounds;
+ updateTouchControls();
+ },
onRuntimeInitialized: () => {
console.log('Client running');
runtimeReady = true;
- new ResizeObserver(updateResolution).observe(canvas);
+ Module._browser_hide_cursor(isMobileBrowser);
+ new ResizeObserver(() => { updateResolution(); updateChatViewport(); }).observe(canvas);
updateResolution();
if (!playerMenu.open) canvas.focus();
},
@@ -72,34 +138,36 @@
function updateResolution() {
const [width, height] = renderSize();
document.querySelector('#render-size').textContent = `${width} x ${height} pixels`;
- if (runtimeReady) Module._browser_request_resize(width, height);
+ if (runtimeReady) {
+ Module._browser_request_resize(width, height);
+ const inset = isMobileBrowser ? Math.round(24 * width / canvas.clientWidth) : 0;
+ Module._browser_hud_insets(inset, document.fullscreenElement ? inset : 0);
+ }
}
pixelMode.onchange = () => {
localStorage.setItem('ao-pixel-mode', pixelMode.value);
updateResolution();
+ updateChatViewport();
};
window.addEventListener('resize', updateResolution);
- window.addEventListener('keydown', event => {
- if (event.ctrlKey && event.altKey && event.code === 'KeyM') {
- event.preventDefault();
- event.stopImmediatePropagation();
- if (event.repeat) return;
- if (playerMenu.open) playerMenu.close();
- else {
- // Release held game inputs before the dialog takes keyboard focus.
- window.dispatchEvent(new Event('blur'));
- playerMenu.showModal();
- updateResolution();
- }
- } else if (playerMenu.open) event.stopImmediatePropagation();
- }, true);
- window.addEventListener('keypress', event => {
- if (playerMenu.open) event.stopImmediatePropagation();
- }, true);
- playerMenu.addEventListener('close', () => {
- window.dispatchEvent(new Event('focus'));
- canvas.focus();
- });
+
+ // Move chat above the keyboard while retaining the full game canvas and buffers.
+ function updateChatViewport() {
+ const viewport = window.visualViewport;
+ if (isMobileBrowser && viewport) {
+ gameSurface.style.left = `${viewport.offsetLeft}px`;
+ gameSurface.style.top = `${viewport.offsetTop}px`;
+ }
+ if (runtimeReady) {
+ const height = Math.min(canvas.clientHeight, viewport ? viewport.height : canvas.clientHeight);
+ const scale = renderSize()[1] / canvas.clientHeight;
+ // Zero disables native chat relocation and shortcut hiding on desktop.
+ Module._browser_chat_viewport(isMobileBrowser && !chatForm.hidden ? Math.round(height * scale) : 0);
+ }
+ positionChat();
+ }
+ window.visualViewport?.addEventListener('resize', updateChatViewport);
+ window.visualViewport?.addEventListener('scroll', updateChatViewport);
// HTTP handles decompression; count prepared bytes while compilation streams.
async function instantiateClient(imports, receive) {
@@ -186,13 +254,14 @@ show();
};
async function startGame() {
if (!crossOriginIsolated) { status.textContent = 'Shared memory is unavailable'; return; }
- if (!WebAssembly.Suspending || !canvas.transferControlToOffscreen || !globalThis.DecompressionStream) { status.textContent = 'This browser lacks required WebAssembly or rendering support'; return; }
+ if (!WebAssembly.Suspending) { status.textContent = 'This game requires WebAssembly JSPI, which this browser does not support'; return; }
+ if (!canvas.transferControlToOffscreen) { status.textContent = 'This game requires OffscreenCanvas, which this browser does not support'; return; }
Module.audioContext = new AudioContext();
// Load immediately; browsers unlock audio on the first game interaction.
for (const type of ['pointerdown', 'keydown']) {
- canvas.addEventListener(type, () => {
+ document.addEventListener(type, () => {
if (Module.audioContext.state === 'suspended') Module.audioContext.resume();
- });
+ }, true);
}
status.textContent = 'Loading...';
const response = await fetch('/browser-launch', {method: 'POST'});
@@ -205,6 +274,451 @@ show();
script.onerror = () => { status.textContent = 'Could not load the client'; };
document.body.append(script);
}
+</script>
+<script id="player-controls">
+ const touchEnabled = document.querySelector('#touch-enabled');
+ const touchControls = document.querySelector('#touch-controls');
+ const chatForm = document.querySelector('#chat-compose');
+ const chatText = document.querySelector('#chat-text');
+ const chatActions = document.querySelector('#chat-actions');
+ const movePad = document.querySelector('#move-pad');
+ const autorunButton = document.querySelector('#autorun-button');
+ const heldKeys = new Set();
+ const overlayTouches = new Set();
+ let canvasTouch = null, moveTouch = null;
+ let canvasTouchInput = false;
+ let orbitTouch = null, autoRun = false, moveForward = false;
+ let touchRegions = null;
+ let chatBounds = null;
+ let chatFullscreen = null, chatComposing = false;
+ Module.onChatBounds = bounds => {
+ chatBounds = bounds;
+ document.querySelector('#chat-button').disabled = !isMobileBrowser || !gameReady;
+ positionChat();
+ };
+ Module.onTouchRegions = bounds => { touchRegions = bounds; updateTouchControls(); };
+ const savedTouchMode = localStorage.getItem('ao-touch-controls');
+ touchEnabled.checked = isMobileBrowser && savedTouchMode !== 'false';
+ touchEnabled.disabled = !isMobileBrowser;
+ document.querySelector('#mobile-options').hidden = !isMobileBrowser;
+
+ // Queue virtual keys through SDL, including releases before focus changes.
+ function setKey(key, down) {
+ if (!gameReady || heldKeys.has(key) === down) return;
+ Module._browser_input_key(key, down);
+ if (down) heldKeys.add(key);
+ else heldKeys.delete(key);
+ }
+ function pressKey(key) {
+ setKey(key, true);
+ setKey(key, false);
+ }
+ function mouse(type, x, y, button = 0) {
+ const bounds = canvas.getBoundingClientRect();
+ const [width, height] = renderSize();
+ x = Math.round((x - bounds.left) * width / bounds.width);
+ y = Math.round((y - bounds.top) * height / bounds.height);
+ if (type === 'mousemove') Module._browser_input_motion(x, y);
+ else Module._browser_input_button(button === 2 ? 3 : 1, type === 'mousedown', x, y);
+ }
+ function touchRegion(x, y) {
+ if (!touchRegions) return;
+ const bounds = canvas.getBoundingClientRect();
+ x = (x - bounds.left) * touchRegions.screenWidth / bounds.width;
+ y = (y - bounds.top) * touchRegions.screenHeight / bounds.height;
+ return touchRegions.regions.find(region =>
+ x >= region.left && x < region.right && y >= region.top && y < region.bottom);
+ }
+ function finishCanvasTouch() {
+ if (!canvasTouch) return;
+ clearTimeout(canvasTouch.timer);
+ if (canvasTouch.button !== null)
+ mouse('mouseup', canvasTouch.x, canvasTouch.y, canvasTouch.button);
+ canvasTouch = null;
+ }
+ function finishOrbit() {
+ if (!orbitTouch || orbitTouch.points.size !== 2) return;
+ Module._browser_orbit(0, 0, 0);
+ }
+ function setAutoRun(active) {
+ autoRun = active;
+ autorunButton.textContent = active ? 'Stop' : 'Autorun';
+ autorunButton.ariaPressed = String(active);
+ setKey(119, autoRun || moveForward);
+ }
+ function releaseControls() {
+ finishCanvasTouch();
+ finishOrbit();
+ orbitTouch = null;
+ moveForward = false;
+ for (const key of heldKeys) setKey(key, false);
+ setAutoRun(false);
+ moveTouch = null;
+ delete movePad.dataset.active;
+ document.querySelector('#move-thumb').style.transform = '';
+ overlayTouches.clear();
+ updateTouchControls();
+ }
+ function updateTouchControls() {
+ const ready = isMobileBrowser && gameReady && touchRegions?.regions.some(region => region.world);
+ document.querySelector('#game-toolbar').hidden = !ready;
+ touchControls.hidden = !ready || !touchEnabled.checked || playerMenu.open || !chatForm.hidden;
+ if (overlayTouches.size || playerMenu.open || !chatForm.hidden) gameSurface.dataset.overlaysActive = '';
+ else delete gameSurface.dataset.overlaysActive;
+ }
+ // Reveal before canvas handlers consume the gesture; fade after the last finger lifts.
+ document.addEventListener('pointerdown', event => {
+ if (!isMobileBrowser || event.pointerType === 'mouse') return;
+ overlayTouches.add(event.pointerId);
+ updateTouchControls();
+ }, true);
+ for (const type of ['pointerup', 'pointercancel']) {
+ document.addEventListener(type, event => {
+ overlayTouches.delete(event.pointerId);
+ updateTouchControls();
+ }, true);
+ }
+ touchEnabled.onchange = () => {
+ releaseControls();
+ localStorage.setItem('ao-touch-controls', touchEnabled.checked);
+ updateTouchControls();
+ };
+ touchControls.addEventListener('contextmenu', event => event.preventDefault());
+
+ // Anchor camera gestures above the character and clear of native windows.
+ function cameraAnchor(startX, startY) {
+ const bounds = canvas.getBoundingClientRect();
+ const y = bounds.top + bounds.height / 4;
+ for (const x of [bounds.left + bounds.width / 2, startX])
+ if (touchRegion(x, y)?.world === true) return [x, y];
+ return [startX, startY];
+ }
+
+ // Own canvas touches so SDL and browser compatibility events cannot click twice.
+ for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
+ canvas.addEventListener(type, event => {
+ if (!isMobileBrowser) return;
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ }, {capture: true, passive: false});
+ }
+ for (const type of ['mousedown', 'mouseup', 'mousemove']) {
+ canvas.addEventListener(type, event => {
+ // Touch compatibility events can omit sourceCapabilities; track their pointer source.
+ if (isMobileBrowser && (canvasTouchInput || event.sourceCapabilities?.firesTouchEvents))
+ event.stopImmediatePropagation();
+ }, true);
+ }
+ canvas.addEventListener('pointerdown', event => {
+ if (!isMobileBrowser) return;
+ if (event.pointerType === 'mouse') {
+ if (!canvasTouch && !orbitTouch) canvasTouchInput = false;
+ return;
+ }
+ canvasTouchInput = true;
+ // Cancelling pointerdown can suppress other fingers in Firefox. CSS owns touch gestures.
+ event.stopImmediatePropagation();
+ if (!gameReady || orbitTouch || playerMenu.open) return;
+ const region = touchRegion(event.clientX, event.clientY);
+ const bounds = canvas.getBoundingClientRect();
+ const history = chatBounds?.history;
+ const x = (event.clientX - bounds.left) * chatBounds?.screenWidth / bounds.width;
+ const y = (event.clientY - bounds.top) * chatBounds?.screenHeight / bounds.height;
+ if (!canvasTouch && region?.chat && history &&
+ x >= history.x && x < history.x + history.width && y >= history.y && y < history.y + history.height) {
+ event.preventDefault();
+ canvas.setPointerCapture(event.pointerId);
+ canvasTouch = {id: event.pointerId, chat: true, y: event.clientY, button: null};
+ return;
+ }
+ if (!chatForm.hidden) return;
+ if (canvasTouch) {
+ if (!canvasTouch.camera || touchRegion(event.clientX, event.clientY)?.world !== true) return;
+ const first = {x: canvasTouch.x - canvasTouch.offsetX, y: canvasTouch.y - canvasTouch.offsetY};
+ const points = new Map([[canvasTouch.id, first], [event.pointerId, {x: event.clientX, y: event.clientY}]]);
+ finishCanvasTouch();
+ canvas.setPointerCapture(event.pointerId);
+ orbitTouch = {points};
+ Module._browser_orbit(0, 0, 1);
+ return;
+ }
+ canvas.focus();
+ canvas.setPointerCapture(event.pointerId);
+ canvasTouch = {id: event.pointerId, x: event.clientX, y: event.clientY,
+ startX: event.clientX, startY: event.clientY, offsetX: 0, offsetY: 0, button: null,
+ camera: touchEnabled.checked && touchRegion(event.clientX, event.clientY)?.world === true};
+ mouse('mousemove', event.clientX, event.clientY);
+ canvasTouch.timer = setTimeout(() => {
+ canvasTouch.button = 2;
+ mouse('mousedown', canvasTouch.x, canvasTouch.y, 2);
+ }, 450);
+ }, true);
+ canvas.addEventListener('pointermove', event => {
+ if (event.pointerType === 'mouse' && !canvasTouch && !orbitTouch) canvasTouchInput = false;
+ if (orbitTouch) {
+ const point = orbitTouch.points.get(event.pointerId);
+ if (!point || orbitTouch.points.size !== 2) return;
+ // Half of each finger's movement, at 35% sensitivity, in viewport fractions.
+ const bounds = canvas.getBoundingClientRect();
+ Module._browser_orbit(Math.round((event.clientX - point.x) / bounds.width * 32768 * .35),
+ Math.round((event.clientY - point.y) / bounds.height * 32768 * .35), 1);
+ point.x = event.clientX;
+ point.y = event.clientY;
+ return;
+ }
+ if (!canvasTouch || event.pointerId !== canvasTouch.id) return;
+ if (canvasTouch.chat) {
+ const bounds = canvas.getBoundingClientRect();
+ const pixels = Math.round((event.clientY - canvasTouch.y) * chatBounds.screenHeight / bounds.height);
+ if (pixels) {
+ Module._browser_chat_scroll(pixels);
+ canvasTouch.y += pixels * bounds.height / chatBounds.screenHeight;
+ }
+ return;
+ }
+ if (canvasTouch.button === null && Math.hypot(event.clientX - canvasTouch.startX, event.clientY - canvasTouch.startY) > 8) {
+ clearTimeout(canvasTouch.timer);
+ canvasTouch.button = canvasTouch.camera ? 2 : 0;
+ if (canvasTouch.camera) {
+ const [x, y] = cameraAnchor(canvasTouch.startX, canvasTouch.startY);
+ canvasTouch.offsetX = x - canvasTouch.startX;
+ canvasTouch.offsetY = y - canvasTouch.startY;
+ mouse('mousemove', canvasTouch.startX + canvasTouch.offsetX, canvasTouch.startY + canvasTouch.offsetY);
+ }
+ mouse('mousedown', canvasTouch.startX + canvasTouch.offsetX, canvasTouch.startY + canvasTouch.offsetY, canvasTouch.button);
+ }
+ canvasTouch.x = event.clientX + canvasTouch.offsetX;
+ canvasTouch.y = event.clientY + canvasTouch.offsetY;
+ mouse('mousemove', canvasTouch.x, canvasTouch.y, canvasTouch.button ?? 0);
+ });
+ canvas.addEventListener('pointerup', event => {
+ if (orbitTouch) return;
+ if (!canvasTouch || event.pointerId !== canvasTouch.id) return;
+ if (canvasTouch.chat) { finishCanvasTouch(); return; }
+ canvasTouch.x = event.clientX + canvasTouch.offsetX;
+ canvasTouch.y = event.clientY + canvasTouch.offsetY;
+ mouse('mousemove', canvasTouch.x, canvasTouch.y);
+ if (canvasTouch.button === null) {
+ canvasTouch.button = 0;
+ mouse('mousedown', event.clientX, event.clientY);
+ }
+ finishCanvasTouch();
+ });
+ for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) {
+ canvas.addEventListener(type, event => {
+ if (orbitTouch?.points.has(event.pointerId)) {
+ finishOrbit();
+ orbitTouch.points.delete(event.pointerId);
+ if (!orbitTouch.points.size) orbitTouch = null;
+ }
+ if (event.pointerId === canvasTouch?.id) finishCanvasTouch();
+ });
+ }
+
+ // Track the movement thumb independently of world swipes and UI dragging.
+ movePad.onpointerdown = event => {
+ if (moveTouch !== null) return;
+ movePad.setPointerCapture(event.pointerId);
+ moveTouch = event.pointerId;
+ movePad.dataset.active = '';
+ movePad.onpointermove(event);
+ };
+ movePad.onpointermove = event => {
+ if (event.pointerId !== moveTouch) return;
+ const bounds = movePad.getBoundingClientRect();
+ const x = event.clientX - bounds.left - bounds.width / 2;
+ const y = event.clientY - bounds.top - bounds.height / 2;
+ // The original game uses Z/C for strafing and W/S for forward/backward.
+ setKey(122, x < -16);
+ setKey(99, x > 16);
+ moveForward = y < -16;
+ if (y > 16) setAutoRun(false);
+ setKey(119, autoRun || moveForward);
+ setKey(115, y > 16);
+ const scale = Math.min(1, 36 / Math.hypot(x, y));
+ document.querySelector('#move-thumb').style.transform = `translate(${x * scale}px, ${y * scale}px)`;
+ };
+ const releaseMove = event => {
+ if (event.pointerId !== moveTouch) return;
+ moveTouch = null;
+ moveForward = false;
+ delete movePad.dataset.active;
+ for (const key of [122, 99, 115]) setKey(key, false);
+ setKey(119, autoRun);
+ document.querySelector('#move-thumb').style.transform = '';
+ };
+ for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) movePad.addEventListener(type, releaseMove);
+ autorunButton.onpointerdown = () => {
+ if (!isMobileBrowser || !gameReady || !touchEnabled.checked) return;
+ setAutoRun(!autoRun);
+ };
+ autorunButton.onclick = event => {
+ if (event.detail === 0 && isMobileBrowser && gameReady && touchEnabled.checked) setAutoRun(!autoRun);
+ };
+ for (const button of document.querySelectorAll('[data-key]')) {
+ button.onpointerdown = () => {
+ pressKey(Number(button.dataset.key));
+ };
+ button.onclick = event => {
+ if (event.detail === 0) pressKey(Number(button.dataset.key));
+ };
+ }
+
+ // Use a native field for the phone keyboard, paste, and text composition.
+ function closeChat(cancel) {
+ chatForm.hidden = true;
+ chatActions.hidden = true;
+ chatButton.textContent = 'Chat';
+ chatComposing = false;
+ updateChatViewport();
+ if (cancel) pressKey(27);
+ chatText.value = '';
+ canvas.focus();
+ updateTouchControls();
+ if (chatFullscreen) {
+ chatFullscreen.requestFullscreen().catch(error => {
+ document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
+ }).finally(() => {
+ gameSurface.style.width = gameSurface.style.height = '';
+ updateResolution();
+ updateChatViewport();
+ });
+ chatFullscreen = null;
+ }
+ }
+ const chatButton = document.querySelector('#chat-button');
+ chatButton.onclick = () => {
+ if (!isMobileBrowser) return;
+ releaseControls();
+ if (!chatForm.hidden) {
+ // A fresh focus during the gesture reopens a keyboard dismissed by the IME.
+ chatText.blur();
+ chatText.focus({preventScroll: true});
+ return;
+ }
+ // Release physical keys before their keyup events move into the text field.
+ window.dispatchEvent(new Event('blur'));
+ window.dispatchEvent(new Event('focus'));
+ pressKey(27);
+ pressKey(13);
+ chatForm.hidden = false;
+ chatActions.hidden = false;
+ chatButton.textContent = 'Keyboard';
+ // Firefox Android does not report keyboard occlusion reliably in fullscreen.
+ if (document.fullscreenElement && /Android.*Firefox\//.test(navigator.userAgent)) {
+ chatFullscreen = document.fullscreenElement;
+ gameSurface.style.width = `${canvas.clientWidth}px`;
+ gameSurface.style.height = `${canvas.clientHeight}px`;
+ document.exitFullscreen().then(() => {
+ updateChatViewport();
+ if (!chatForm.hidden) chatText.focus({preventScroll: true});
+ }).catch(error => {
+ document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
+ });
+ }
+ updateTouchControls();
+ updateChatViewport();
+ chatText.focus({preventScroll: true});
+ };
+ // Open the phone keyboard during the touch gesture, without a second compatibility click.
+ chatButton.addEventListener('touchend', event => {
+ if (chatButton.disabled) return;
+ event.preventDefault();
+ chatButton.onclick();
+ }, {passive: false});
+ chatText.oninput = () => chatText.setCustomValidity('');
+ chatText.addEventListener('compositionstart', () => { chatComposing = true; });
+ chatText.addEventListener('compositionend', () => { chatComposing = false; });
+ chatForm.onsubmit = event => {
+ event.preventDefault();
+ if (chatComposing) return;
+ // The guest uses Windows-1252; reject text it cannot display rather than corrupting it.
+ const decoder = new TextDecoder('windows-1252');
+ const alphabet = Array.from({length: 256}, (_,byte) => decoder.decode(new Uint8Array([byte])));
+ const bytes = Array.from(chatText.value, character => alphabet.indexOf(character));
+ if (bytes.some(byte => byte < 32)) {
+ chatText.setCustomValidity('This game cannot display one or more characters in this message.');
+ chatText.reportValidity();
+ return;
+ }
+ for (const byte of bytes) Module._browser_input_character(byte);
+ pressKey(13);
+ closeChat(false);
+ };
+ document.querySelector('#chat-cancel').onclick = () => closeChat(true);
+ function positionChat() {
+ if (!chatBounds) return;
+ const scaleX = canvas.clientWidth / chatBounds.screenWidth;
+ const scaleY = canvas.clientHeight / chatBounds.screenHeight;
+ chatForm.style.left = `${chatBounds.x * scaleX}px`;
+ // Pin immediately, including while native bounds still describe the last frame.
+ const visibleHeight = Math.min(canvas.clientHeight, window.visualViewport?.height ?? canvas.clientHeight);
+ chatForm.style.top = `${chatForm.hidden ? chatBounds.y * scaleY : Math.max(0, visibleHeight - (chatBounds.height + 1) * scaleY)}px`;
+ // Keep the caret reachable when a narrow screen clips the game's chat widget.
+ chatForm.style.width = `${Math.min(chatBounds.width, chatBounds.screenWidth - chatBounds.x) * scaleX}px`;
+ chatForm.style.height = `${chatBounds.height * scaleY}px`;
+ chatForm.style.bottom = 'auto';
+ chatText.style.fontSize = `${12 * scaleY}px`;
+ }
+
+ // Keep the settings reachable by touch and include the overlay in fullscreen.
+ function openMenu() {
+ releaseControls();
+ if (!chatForm.hidden) closeChat(true);
+ window.dispatchEvent(new Event('blur'));
+ playerMenu.showModal();
+ updateTouchControls();
+ updateResolution();
+ }
+ document.querySelector('#menu-button').onclick = openMenu;
+ document.querySelector('#view-button').onclick = () => {
+ if (!isMobileBrowser || !gameReady) return;
+ playerMenu.close();
+ pressKey(1073741889); // SDL F8: toggle first and third person.
+ };
+ playerMenu.addEventListener('close', () => {
+ window.dispatchEvent(new Event('focus'));
+ canvas.focus();
+ updateTouchControls();
+ });
+ const fullscreenButton = document.querySelector('#fullscreen-button');
+ fullscreenButton.hidden = !document.fullscreenEnabled;
+ fullscreenButton.onclick = async () => {
+ document.querySelector('#menu-error').textContent = '';
+ try {
+ if (document.fullscreenElement) await document.exitFullscreen();
+ else await document.documentElement.requestFullscreen();
+ } catch (error) {
+ document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
+ }
+ };
+ document.addEventListener('fullscreenchange', () => {
+ fullscreenButton.textContent = document.fullscreenElement ? 'Exit fullscreen' : 'Enter fullscreen';
+ updateResolution();
+ updateChatViewport();
+ });
+ for (const type of ['keydown', 'keyup', 'keypress']) {
+ window.addEventListener(type, event => {
+ if (type === 'keydown' && event.ctrlKey && event.altKey && event.code === 'KeyM') {
+ event.preventDefault();
+ event.stopImmediatePropagation();
+ if (event.repeat) return;
+ if (playerMenu.open) playerMenu.close();
+ else openMenu();
+ } else if (playerMenu.open || !chatForm.hidden) {
+ event.stopImmediatePropagation();
+ if (type === 'keydown' && event.key === 'Escape' && !chatForm.hidden && !chatComposing && !event.isComposing && event.keyCode !== 229) {
+ event.preventDefault();
+ closeChat(true);
+ }
+ }
+ }, true);
+ }
+ window.addEventListener('blur', releaseControls);
+ window.addEventListener('resize', releaseControls);
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) releaseControls();
+ });
startGame().catch(error => Module.onAbort(error.message));
</script>
</html>
diff --git a/src/game/ccr.dll/lifted-0008.c b/src/game/ccr.dll/lifted-0008.c
@@ -5,6 +5,10 @@
#include <stdlib.h>
#include <string.h>
+#ifdef __EMSCRIPTEN__
+extern int browser_cursor_hidden(void);
+#endif
+
void sub_27016810(void) {
int _fpu_cmp = 0;
uint32_t _cf = 0;
@@ -958,6 +962,10 @@ L_27016F21:
MEM32(esi + 0x8) = eax; /* 0x27016F33: mov dword ptr [esi + 8], eax */
L_27016F36:
SET_LO8(eax, MEM8(esi + 0x10)); /* 0x27016F36: mov al, byte ptr [esi + 0x10] */
+#ifdef __EMSCRIPTEN__
+ /* Hide the software pointer on mobile without changing native input state. */
+ if (browser_cursor_hidden()) SET_LO8(eax, 0);
+#endif
/* test LO8(eax), LO8(eax) */ /* 0x27016F39: test al, al */
_flag_a = (uint32_t)(LO8(eax)) << 24; _flag_b = (uint32_t)(LO8(eax)) << 24;
_cf = 0;
@@ -1461,6 +1469,10 @@ L_27016F21:
MEM32(esi + 0x8) = eax; /* 0x27016F33: mov dword ptr [esi + 8], eax */
L_27016F36:
SET_LO8(eax, MEM8(esi + 0x10)); /* 0x27016F36: mov al, byte ptr [esi + 0x10] */
+#ifdef __EMSCRIPTEN__
+ /* Hide the software pointer on mobile without changing native input state. */
+ if (browser_cursor_hidden()) SET_LO8(eax, 0);
+#endif
/* test LO8(eax), LO8(eax) */ /* 0x27016F39: test al, al */
_flag_a = (uint32_t)(LO8(eax)) << 24; _flag_b = (uint32_t)(LO8(eax)) << 24;
_cf = 0;
diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js
@@ -8,6 +8,27 @@ addToLibrary({
],
_wasmfs_create_fetch_backend_js: async function(backend) {
const files = new Map();
+ const cachedChunks = new Map();
+ let cachedBytes = 0;
+
+ // Active reads retain their bytes until copying into Wasm has finished.
+ function trimChunks() {
+ for (const [bytes, entry] of cachedChunks) {
+ if (cachedBytes <= 64 * 1024 * 1024) break;
+ if (entry.file.readers) continue;
+ delete entry.file.chunks[entry.index];
+ cachedChunks.delete(bytes);
+ cachedBytes -= bytes.byteLength;
+ }
+ }
+ function rememberChunk(file, index, bytes) {
+ const previous = file.chunks[index];
+ if (cachedChunks.delete(previous)) cachedBytes -= previous.byteLength;
+ file.chunks[index] = bytes;
+ cachedChunks.set(bytes, {file, index});
+ cachedBytes += bytes.byteLength;
+ trimChunks();
+ }
// File URLs are valid only after their WasmFS constructor has returned.
const allocatedFiles = new Set(), prefetchedFamilies = new Set(), prefetchQueue = [];
let prefetching = 0, soundGroups = null;
@@ -108,7 +129,8 @@ addToLibrary({
if (response.status === 200) {
file.size = bytes.length;
for (let offset = 0; offset < bytes.length; offset += file.chunkSize)
- file.chunks[offset / file.chunkSize] = bytes.subarray(offset, offset + file.chunkSize);
+ rememberChunk(file, offset / file.chunkSize,
+ bytes.length <= file.chunkSize ? bytes : bytes.slice(offset, offset + file.chunkSize));
return;
}
const range = /^bytes (\d+)-(\d+)\/(\d+)$/.exec(response.headers.get('Content-Range'));
@@ -118,10 +140,11 @@ addToLibrary({
file.size = Number(range[3]);
for (let index = first; index <= last && index * file.chunkSize < file.size; ++index) {
const offset = (index - first) * file.chunkSize;
- file.chunks[index] = bytes.subarray(offset, offset + file.chunkSize);
+ const chunk = bytes.length <= file.chunkSize ? bytes : bytes.slice(offset, offset + file.chunkSize);
+ rememberChunk(file, index, chunk);
// Store complete chunks as ordinary responses; Cache Storage rejects HTTP 206.
if (cache && file.version)
- cache.put(chunkURL(file, index), new Response(file.chunks[index], {
+ cache.put(chunkURL(file, index), new Response(chunk, {
headers: {ETag: file.version}
})).catch(disableCache);
}
@@ -136,7 +159,7 @@ addToLibrary({
if (response && response.headers.get('ETag') === file.version) {
const bytes = new Uint8Array(await response.arrayBuffer());
if (bytes.length === Math.min(file.chunkSize, file.size - index * file.chunkSize)) {
- file.chunks[index] = bytes;
+ rememberChunk(file, index, bytes);
cached[index] = true;
}
}
@@ -171,7 +194,7 @@ addToLibrary({
if (!files.has(handle)) {
const url = fileURL(handle);
const file = {
- url,
+ url, handle, readers: 0,
chunkSize: __wasmfs_fetch_get_chunk_size(handle), chunks: []
};
const pending = Promise.all([cacheReady, fileMetadata(url)]).then(async ([, info]) => {
@@ -222,10 +245,16 @@ addToLibrary({
if (url.endsWith('/ResourceDatabase.dat')) databaseHandle = file;
}
const file = await getFile(handle);
- await ensureChunks(file, 0, Math.ceil(file.size / file.chunkSize) - 1);
const bytes = new Uint8Array(file.size);
- for (let chunk = 0; chunk < file.chunks.length; ++chunk)
- bytes.set(file.chunks[chunk], chunk * file.chunkSize);
+ ++file.readers;
+ try {
+ await ensureChunks(file, 0, Math.ceil(file.size / file.chunkSize) - 1);
+ for (let chunk = 0; chunk < file.chunks.length; ++chunk)
+ bytes.set(file.chunks[chunk], chunk * file.chunkSize);
+ } finally {
+ --file.readers;
+ trimChunks();
+ }
// Index leaves contain a little-endian data offset and big-endian identity.
const view = new DataView(bytes.buffer), records = new Map(), seen = new Set();
@@ -277,7 +306,14 @@ addToLibrary({
wasmFS$backends[backend] = {
allocFile: async (file) => { allocatedFiles.add(file); soundGroups = null; },
- freeFile: async (file) => { allocatedFiles.delete(file); files.delete(file); soundGroups = null; },
+ freeFile: async (file) => {
+ allocatedFiles.delete(file); files.delete(file); soundGroups = null;
+ for (const [bytes, entry] of cachedChunks) {
+ if (entry.file.handle !== file) continue;
+ cachedChunks.delete(bytes);
+ cachedBytes -= bytes.byteLength;
+ }
+ },
write: async () => -{{{ cDefs.EROFS }}},
getSize: async (handle) => {
try {
@@ -296,12 +332,21 @@ addToLibrary({
const first = Math.floor(offset / file.chunkSize);
const last = Math.floor((offset + length - 1) / file.chunkSize);
- await ensureChunks(file, first, last);
- for (let index = first; index <= last; ++index) {
- const start = Math.max(offset, index * file.chunkSize);
- const end = Math.min(offset + length, (index + 1) * file.chunkSize);
- HEAPU8.set(file.chunks[index].subarray(start - index * file.chunkSize,
- end - index * file.chunkSize), buffer + start - offset);
+ ++file.readers;
+ try {
+ await ensureChunks(file, first, last);
+ for (let index = first; index <= last; ++index) {
+ const start = Math.max(offset, index * file.chunkSize);
+ const end = Math.min(offset + length, (index + 1) * file.chunkSize);
+ const bytes = file.chunks[index], entry = cachedChunks.get(bytes);
+ cachedChunks.delete(bytes);
+ cachedChunks.set(bytes, entry);
+ HEAPU8.set(bytes.subarray(start - index * file.chunkSize,
+ end - index * file.chunkSize), buffer + start - offset);
+ }
+ } finally {
+ --file.readers;
+ trimChunks();
}
return length;
} catch (error) {
diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js
@@ -2,6 +2,21 @@ addToLibrary({
$AOPresented: false,
ao_loading_complete__proxy: 'async',
ao_loading_complete: () => { Module.onFirstFrame?.(); },
+ ao_chat_bounds__proxy: 'async',
+ ao_chat_bounds: (x, y, width, height, screenWidth, screenHeight, outputX, outputY, outputWidth, outputHeight) => {
+ Module.onChatBounds?.({x, y, width, height, screenWidth, screenHeight,
+ history: {x: outputX, y: outputY, width: outputWidth, height: outputHeight}});
+ },
+ ao_touch_regions__proxy: 'sync',
+ ao_touch_regions: (bounds, count, screenWidth, screenHeight) => {
+ const regions = Array.from({length: count}, (_, index) => {
+ const offset = (bounds >> 2) + index * 5;
+ return {left: HEAP32[offset], top: HEAP32[offset + 1],
+ right: HEAP32[offset + 2], bottom: HEAP32[offset + 3],
+ world: HEAP32[offset + 4] === 1, chat: HEAP32[offset + 4] === 2};
+ });
+ Module.onTouchRegions?.({regions, screenWidth, screenHeight});
+ },
ao_present_yield__async: 'auto',
ao_present_yield__deps: ['$AOProfile', '$AOPresented', 'ao_loading_complete'],
ao_present_yield: () => {
diff --git a/src/runtime/browser_resolution.c b/src/runtime/browser_resolution.c
@@ -10,6 +10,78 @@
#endif
static _Atomic uint32_t requested_size;
+static _Atomic unsigned chat_viewport_bottom;
+static _Atomic int orbit_x, orbit_y, orbit_active;
+static _Atomic int cursor_hidden;
+static _Atomic uint32_t hud_insets;
+static _Atomic int chat_scroll_pixels;
+static int chat_scroll_remainder;
+static uint32_t chat_width_owner;
+static unsigned chat_max_width;
+static int hud_adjusted;
+static int orbit_running;
+static struct {
+ uint32_t chat, hidden_toolbar;
+ int input_x, input_y, output_x, output_y, output_height;
+ unsigned output_lines;
+} mobile_chat;
+void ao_chat_bounds(int x, int y, int width, int height, int screen_width, int screen_height,
+ int output_x, int output_y, int output_width, int output_height);
+void ao_touch_regions(const int *regions, unsigned count, int screen_width, int screen_height);
+
+static void publish_touch_regions(void)
+{
+ /* Native hit order and rectangles: src/game/ccr.dll/lifted-0005.c:sub_27010890. */
+ uint32_t module = MEM32(0x27048b7c);
+ uint32_t head = module && MEM8(module + 4) ? MEM32(MEM32(module) + 4) : 0;
+ unsigned count = 0;
+ for (uint32_t node = head ? MEM32(head) : 0; node && node != head; node = MEM32(node))
+ if (MEM8(MEM32(node + 8) + 8)) ++count;
+
+ int regions[2 + count * 5];
+ regions[0] = MEM32(0x27048be8);
+ regions[1] = MEM32(0x27048bec);
+ uint32_t action = MEM32(0x2b0ee640);
+ uint32_t world = action ? MEM32(action + 0x10) : 0;
+ uint32_t chat = MEM32(0x2b0ee6a4);
+ uint32_t history = chat ? MEM32(MEM32(chat + 0xc) + 0x18) : 0;
+ unsigned offset = 2;
+ for (uint32_t node = head ? MEM32(head) : 0; node && node != head; node = MEM32(node)) {
+ uint32_t hotspot = MEM32(node + 8);
+ if (!MEM8(hotspot + 8)) continue;
+ for (unsigned i = 0; i < 4; ++i) regions[offset++] = MEM32(hotspot + 0x2c + i * 4);
+ regions[offset++] = hotspot == world ? 1 : hotspot == history ? 2 : 0;
+ }
+
+ /* Publish only layout changes; the synchronous copy keeps the snapshot stable. */
+ static int *previous;
+ static size_t previous_size;
+ if (previous_size == sizeof(regions) && !memcmp(previous, regions, sizeof(regions))) return;
+ previous = realloc(previous, sizeof(regions));
+ if (!previous) abort();
+ previous_size = sizeof(regions);
+ memcpy(previous, regions, sizeof(regions));
+ ao_touch_regions(previous + 2, count, regions[0], regions[1]);
+}
+
+static void publish_chat_bounds(void)
+{
+ uint32_t chat = MEM32(0x2b0ee6a4);
+ if (!chat) return;
+ /* Input window layout: src/game/ccr.dll/lifted-0007.c:sub_270156A0. */
+ uint32_t window = MEM32(MEM32(chat + 8));
+ uint32_t output = MEM32(MEM32(chat + 0xc) + 0x14);
+ int bounds[] = {MEM32(window + 0x2c) + 1, MEM32(window + 0x30) + 1,
+ MEM32(window + 0x34) - 2, MEM32(window + 0x38) - 2,
+ MEM32(0x27048be8), MEM32(0x27048bec),
+ MEM32(output + 0x2c), MEM32(output + 0x30),
+ MEM32(output + 0x34), MEM32(output + 0x38)};
+ static int previous[10];
+ if (!memcmp(previous, bounds, sizeof(bounds))) return;
+ memcpy(previous, bounds, sizeof(bounds));
+ ao_chat_bounds(bounds[0], bounds[1], bounds[2], bounds[3], bounds[4], bounds[5],
+ bounds[6], bounds[7], bounds[8], bounds[9]);
+}
/* The browser main thread only publishes a request; the game owns all objects. */
EMSCRIPTEN_KEEPALIVE void browser_request_resize(unsigned width, unsigned height)
@@ -18,6 +90,43 @@ EMSCRIPTEN_KEEPALIVE void browser_request_resize(unsigned width, unsigned height
atomic_store(&requested_size, width | (height << 16));
}
+EMSCRIPTEN_KEEPALIVE void browser_chat_viewport(unsigned bottom)
+{
+ atomic_store(&chat_viewport_bottom, bottom);
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_hide_cursor(int hidden)
+{
+ atomic_store(&cursor_hidden, hidden);
+}
+
+int browser_cursor_hidden(void)
+{
+ return atomic_load(&cursor_hidden);
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_hud_insets(unsigned right, unsigned top)
+{
+ atomic_store(&hud_insets, right | (top << 16));
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_chat_scroll(int pixels)
+{
+ if (atomic_load(&hud_insets)) atomic_fetch_add(&chat_scroll_pixels, pixels);
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_orbit(int x, int y, int active)
+{
+ if (active) {
+ atomic_fetch_add(&orbit_x, x);
+ atomic_fetch_add(&orbit_y, y);
+ } else {
+ atomic_store(&orbit_x, 0);
+ atomic_store(&orbit_y, 0);
+ }
+ atomic_store(&orbit_active, active);
+}
+
static void call_method(uint32_t address, uint32_t object, unsigned count,
const uint32_t *arguments)
{
@@ -29,6 +138,26 @@ static void call_method(uint32_t address, uint32_t object, unsigned count,
assert(g_esp == stack);
}
+static void orbit_frame(void)
+{
+ int active = atomic_load(&orbit_active);
+ if (!active && !orbit_running) return;
+ int x = atomic_exchange(&orbit_x, 0), y = atomic_exchange(&orbit_y, 0);
+ uint32_t engine = MEM32(0x2d01752c);
+ if (!engine) { orbit_running = 0; return; }
+
+ /* CCR sub_270041F0 uses half a screen fraction for native camera movement. */
+ if (active) {
+ float movement[] = {x / 131072.0f, y / 131072.0f};
+ uint32_t arguments[2];
+ memcpy(arguments, movement, sizeof(arguments));
+ call_method(0x36020440, engine, 2, arguments);
+ } else {
+ call_method(0x36020470, engine, 0, NULL);
+ }
+ orbit_running = active;
+}
+
static void move_point(uint32_t method, uint32_t object, int x, int y)
{
g_esp -= 8;
@@ -38,6 +167,131 @@ static void move_point(uint32_t method, uint32_t object, int x, int y)
g_esp += 8;
}
+static void scroll_mobile_chat(void)
+{
+ int pixels = atomic_exchange(&chat_scroll_pixels, 0);
+ uint32_t chat = MEM32(0x2b0ee6a4);
+ if (!pixels || !chat || !atomic_load(&hud_insets)) return;
+ uint32_t output = MEM32(chat + 0xc);
+ int line_height = MEM32(output + 0x38);
+ chat_scroll_remainder += pixels;
+ int lines = chat_scroll_remainder / line_height;
+ chat_scroll_remainder %= line_height;
+ /* Native history scrolling also updates its scrollbar and follow-newest state. */
+ if (lines) call_method(0x2b005220, output, 1, (uint32_t[]){-lines});
+}
+
+static void resize_chat_background(uint32_t output)
+{
+ /* The history background is a scaled 16x16 sprite: ddr.dll:sub_2B003ED0. */
+ g_esp -= 8;
+ *(float *)ADDR(g_esp) = MEM32(output + 0x48) / 16.0f;
+ *(float *)ADDR(g_esp + 4) = MEM32(output + 0x4c) / 16.0f;
+ call_method(MEM32(0x2b0b5658), MEM32(output + 0x20), 2, (uint32_t[]){g_esp, g_esp + 4});
+ g_esp += 8;
+}
+
+static void update_chat_toolbar(uint32_t output_window, unsigned bottom)
+{
+ /* ToolbarSystem_t: src/game/ddr.dll/lifted-0031.c:sub_2B0775B0. */
+ uint32_t toolbar = MEM32(0x2b0ef034);
+ if (!toolbar) { mobile_chat.hidden_toolbar = 0; return; }
+ int hide = 0;
+ if (bottom) {
+ /* The strip's hotspot covers its full area; its render window is one tile. */
+ uint32_t hotspot = MEM32(toolbar + 0x5c);
+ int x = MEM32(hotspot + 0x2c), y = MEM32(hotspot + 0x30);
+ int width = (int)MEM32(hotspot + 0x34) - x;
+ int height = (int)MEM32(hotspot + 0x38) - y;
+ int chat_x = MEM32(output_window + 0x2c), chat_y = MEM32(output_window + 0x30);
+ int overlap_width = fminf(x + width, chat_x + MEM32(output_window + 0x34)) - fmaxf(x, chat_x);
+ int overlap_height = fminf(y + height, chat_y + MEM32(output_window + 0x38)) - fmaxf(y, chat_y);
+ hide = overlap_width > 0 && overlap_height > 0 &&
+ (int64_t)overlap_width * overlap_height * 5 > (int64_t)width * height;
+ }
+
+ /* Restore only a bar that this chat session hid. */
+ if (hide && !MEM8(toolbar + 4)) {
+ call_method(0x2b0775b0, toolbar, 1, (uint32_t[]){1});
+ mobile_chat.hidden_toolbar = toolbar;
+ } else if (!hide && mobile_chat.hidden_toolbar == toolbar) {
+ call_method(0x2b0775b0, toolbar, 1, (uint32_t[]){0});
+ mobile_chat.hidden_toolbar = 0;
+ }
+}
+
+static void position_mobile_chat(void)
+{
+ uint32_t chat = MEM32(0x2b0ee6a4);
+ if (!chat) {
+ update_chat_toolbar(0, 0);
+ mobile_chat.chat = 0;
+ return;
+ }
+ unsigned bottom = atomic_load(&chat_viewport_bottom);
+ uint32_t input = MEM32(chat + 8), output = MEM32(chat + 0xc);
+ uint32_t input_window = MEM32(input), output_window = MEM32(output + 0x14);
+ if (bottom && mobile_chat.chat != chat) {
+ mobile_chat.chat = chat;
+ mobile_chat.input_x = MEM32(input_window + 0x2c);
+ mobile_chat.input_y = MEM32(input_window + 0x30);
+ mobile_chat.output_x = MEM32(output_window + 0x2c);
+ mobile_chat.output_y = MEM32(output_window + 0x30);
+ mobile_chat.output_height = MEM32(output_window + 0x38);
+ mobile_chat.output_lines = MEM32(output + 0x3c);
+ }
+ if (mobile_chat.chat != chat) return;
+
+ /* Keep chat clear of the left health/nano bars while the editor is open. */
+ int margin = (atomic_load(&hud_insets) & 65535) / 2;
+ if (margin < 20) margin = 20;
+ int input_x = bottom && mobile_chat.input_x < margin ? margin : mobile_chat.input_x;
+ int output_x = bottom && mobile_chat.output_x < margin ? margin : mobile_chat.output_x;
+
+ /* Reserve the input line first, then fit whole history lines above it. */
+ int input_y = bottom ? (int)bottom - (int)MEM32(input_window + 0x38) : mobile_chat.input_y;
+ unsigned lines = mobile_chat.output_lines;
+ if (bottom && input_y < mobile_chat.output_height) {
+ lines = input_y > 0 ? input_y / MEM32(output + 0x38) : 0;
+ if (!lines) lines = 1;
+ }
+ int output_height = lines == mobile_chat.output_lines ? mobile_chat.output_height :
+ lines * MEM32(output + 0x38);
+ int changed = 0;
+ if ((int)MEM32(output_window + 0x38) != output_height) {
+ /* DDR history layout: lifted-0000.c:sub_2B003ED0 and sub_2B004F50. */
+ MEM32(output + 0x3c) = lines;
+ MEM32(output + 0x4c) = output_height;
+ if (MEM8(output + 0x60))
+ MEM32(output + 0x58) = MEM32(output + 0x2c) > lines ? MEM32(output + 0x2c) - lines : 0;
+ MEM32(output + 0x54) = MEM32(output + 0x58) + lines;
+ MEM8(output + 9) = 1;
+
+ /* Shrink the existing tile grids so restoring them needs no allocation. */
+ move_point(0x27018720, output_window, MEM32(output_window + 0x34), output_height);
+ uint32_t scrollbar = MEM32(output + 0x6c);
+ move_point(0x27018720, scrollbar, MEM32(scrollbar + 0x34), output_height);
+ uint32_t detector = MEM32(output + 0x18);
+ move_point(MEM32(MEM32(detector) + 0x18), detector,
+ MEM32(output_window + 0x34), output_height);
+ resize_chat_background(output);
+ changed = 1;
+ }
+ int output_y = bottom ? input_y - (int)MEM32(output_window + 0x38) : mobile_chat.output_y;
+ if ((int)MEM32(input_window + 0x2c) != input_x || (int)MEM32(input_window + 0x30) != input_y) {
+ move_point(0x27015910, input, input_x, input_y);
+ changed = 1;
+ }
+ if ((int)MEM32(output_window + 0x2c) != output_x || (int)MEM32(output_window + 0x30) != output_y) {
+ move_point(0x2b004560, output, output_x, output_y);
+ changed = 1;
+ }
+ update_chat_toolbar(output_window, bottom);
+ /* WidgetModule_t::InvalidateAll redraws UI uncovered by relocated chat. */
+ if (changed && MEM32(0x27048be4)) call_method(0x2701d270, 0, 0, NULL);
+ if (!bottom) mobile_chat.chat = 0;
+}
+
/* Layout from src/game/ddr.dll/lifted-0033.c:sub_2B081C40 (status bar). */
struct status_bar {
uint32_t detector, options, help, inventory, skills, map, chat, menu;
@@ -53,7 +307,8 @@ static void resize_status_bar(unsigned width, unsigned height)
uint32_t address = MEM32(0x2b0ef09c);
if (!address) return;
struct status_bar *bar = (void *)ADDR(address);
- int x = width, y = (int)height - bar->height;
+ int x = (int)width - (int)(atomic_load(&hud_insets) & 65535);
+ int y = (int)height - bar->height;
uint32_t buttons[] = {bar->help, bar->options};
for (unsigned i = 0; i < 2; ++i) {
x -= MEM32(buttons[i] + 0x44);
@@ -97,6 +352,82 @@ static void resize_status_bar(unsigned width, unsigned height)
(uint32_t[]){0, y, width > minimum ? width : minimum, 1, 0x62, 0x62, 0x62, 10000});
}
+static void position_mobile_hud(void)
+{
+ uint32_t insets = atomic_load(&hud_insets);
+ if (!insets && !hud_adjusted) return;
+ unsigned right = insets & 65535, top = insets >> 16;
+ int changed = 0;
+
+ /* Keep chat text clear of rounded left corners, including after typing. */
+ unsigned chat_margin = right / 2;
+ uint32_t chat = MEM32(0x2b0ee6a4);
+ if (chat_margin && chat) {
+ uint32_t input = MEM32(chat + 8), output = MEM32(chat + 0xc);
+ uint32_t input_window = MEM32(input), output_window = MEM32(output + 0x14);
+ if ((int)MEM32(input_window + 0x2c) < (int)chat_margin) {
+ move_point(0x27015910, input, chat_margin, MEM32(input_window + 0x30));
+ changed = 1;
+ }
+ if ((int)MEM32(output_window + 0x2c) < (int)chat_margin) {
+ move_point(0x2b004560, output, chat_margin, MEM32(output_window + 0x30));
+ changed = 1;
+ }
+
+ /* Retain the native maximum and reserve space for the scrollbar and right edge. */
+ if (chat_width_owner != chat) {
+ chat_width_owner = chat;
+ chat_max_width = MEM32(output_window + 0x34);
+ }
+ uint32_t scrollbar = MEM32(output + 0x6c);
+ int available = (int)MEM32(0x27048be8) - (int)MEM32(output_window + 0x2c) -
+ (int)chat_margin - (int)MEM32(scrollbar + 0x34);
+ unsigned width = available > 0 ? available : 1;
+ if (width > chat_max_width) width = chat_max_width;
+ if (MEM32(output_window + 0x34) != width) {
+ MEM32(output + 0x48) = MEM32(output + 0x50) = width;
+ MEM32(output + 0x54) = MEM32(output + 0x58) + MEM32(output + 0x3c);
+ MEM8(output + 9) = 1;
+ move_point(0x27018720, output_window, width, MEM32(output_window + 0x38));
+ uint32_t detector = MEM32(output + 0x18);
+ move_point(MEM32(MEM32(detector) + 0x18), detector,
+ width, MEM32(output_window + 0x38));
+ resize_chat_background(output);
+ move_point(0x2b004560, output, MEM32(output_window + 0x2c), MEM32(output_window + 0x30));
+ changed = 1;
+ }
+ }
+
+ /* Reposition native buttons with their hotspots, retaining the full strip background. */
+ uint32_t address = MEM32(0x2b0ef09c);
+ if (address) {
+ struct status_bar *bar = (void *)ADDR(address);
+ unsigned width = MEM32(0x27048be8), height = MEM32(0x27048bec);
+ int x = (int)width - (int)right - (int)MEM32(bar->help + 0x44);
+ if ((int)MEM32(bar->help + 0x3c) != x ||
+ (int)MEM32(bar->help + 0x40) != (int)height - bar->height) {
+ resize_status_bar(width, height);
+ changed = 1;
+ }
+ }
+
+ /* StatView_t's health/nano sprites: ddr.dll/lifted-0016.c:sub_2B0403D0. */
+ uint32_t stats = MEM32(0x2b0eea5c);
+ if (stats) {
+ for (unsigned i = 0; i < 2; ++i) {
+ uint32_t sprite = MEM32(stats + 0xdc + i * 4);
+ uint32_t hotspot = MEM32(stats + (i ? 0xe4 : 0xe8));
+ int y = top + i * 144;
+ if (*(float *)ADDR(sprite + 0x1c) == y) continue;
+ move_point(0x250ae720, sprite, *(float *)ADDR(sprite + 0x18), y);
+ move_point(MEM32(MEM32(hotspot) + 0x14), hotspot, MEM32(hotspot + 0x2c), y);
+ changed = 1;
+ }
+ }
+ if (changed && MEM32(0x27048be4)) call_method(0x2701d270, 0, 0, NULL);
+ hud_adjusted = !!insets;
+}
+
static void resize_side_panel(unsigned width, unsigned height)
{
uint32_t panel = MEM32(0x2b0ee9b8);
@@ -161,6 +492,10 @@ static void resize_windows(unsigned width, int height_change)
/* Chat output and its input line retain their distance from the bottom edge. */
uint32_t chat = MEM32(0x2b0ee6a4);
if (chat) {
+ if (mobile_chat.chat == chat) {
+ mobile_chat.input_y += height_change;
+ mobile_chat.output_y += height_change;
+ }
uint32_t output = MEM32(chat + 0xc), window = MEM32(output + 0x14);
int y = (int)MEM32(window + 0x30) + height_change;
move_point(0x2b004560, output, MEM32(window + 0x2c), y > 0 ? y : 0);
@@ -171,8 +506,7 @@ static void resize_windows(unsigned width, int height_change)
}
}
-/* Called by Clientr.exe::sub_28002D20 before AFCM starts the next frame. */
-void browser_resize_frame(void)
+static void resize_frame(void)
{
uint32_t size = atomic_load(&requested_size);
if (!size) return;
@@ -188,16 +522,6 @@ void browser_resize_frame(void)
if (!linux_graphics_resize(width, height, MEM32(MEM32(display + 0xd4)))) return;
atomic_compare_exchange_strong(&requested_size, &size, 0);
- /* Preserve the interrupted guest CPU, including x87 values and flags. */
- uint32_t registers[] = {g_eax, g_ecx, g_edx, g_ebx, g_esi, g_edi, g_ebp,
- g_cur_func, g_flag_k, g_flag_a, g_flag_b, g_flag_cf};
- double fpu[8];
- int64_t integers[8];
- memcpy(fpu, g_st, sizeof(fpu));
- memcpy(integers, g_st_i64, sizeof(integers));
- int top = g_fp_top;
- uint16_t control = g_fpu_cw;
-
/* BBR DisplayInfo and Randy_t::ResizeBuffers own the full back/depth buffers. */
MEM32(info) = width;
MEM32(info + 4) = height;
@@ -260,6 +584,37 @@ void browser_resize_frame(void)
resize_windows(width, height_change);
if (MEM32(0x27048be4)) call_method(0x2701d270, 0, 0, NULL);
+ fprintf(stderr, "[browser-resolution] %ux%u\n", width, height);
+}
+
+/* Called by Clientr.exe::sub_28002D20 before AFCM starts the next frame. */
+void browser_resize_frame(void)
+{
+ if (!atomic_load(&requested_size) && !atomic_load(&chat_viewport_bottom) && !mobile_chat.chat &&
+ !atomic_load(&orbit_active) && !orbit_running && !atomic_load(&hud_insets) && !hud_adjusted) {
+ publish_chat_bounds();
+ publish_touch_regions();
+ return;
+ }
+
+ /* Preserve the interrupted guest CPU, including x87 values and flags. */
+ uint32_t registers[] = {g_eax, g_ecx, g_edx, g_ebx, g_esi, g_edi, g_ebp,
+ g_cur_func, g_flag_k, g_flag_a, g_flag_b, g_flag_cf};
+ double fpu[8];
+ int64_t integers[8];
+ memcpy(fpu, g_st, sizeof(fpu));
+ memcpy(integers, g_st_i64, sizeof(integers));
+ int top = g_fp_top;
+ uint16_t control = g_fpu_cw;
+
+ resize_frame();
+ orbit_frame();
+ position_mobile_chat();
+ position_mobile_hud();
+ scroll_mobile_chat();
+ publish_chat_bounds();
+ publish_touch_regions();
+
g_eax = registers[0]; g_ecx = registers[1]; g_edx = registers[2];
g_ebx = registers[3]; g_esi = registers[4]; g_edi = registers[5];
g_ebp = registers[6]; g_cur_func = registers[7]; g_flag_k = registers[8];
@@ -268,5 +623,4 @@ void browser_resize_frame(void)
memcpy(g_st_i64, integers, sizeof(integers));
g_fp_top = top;
g_fpu_cw = control;
- fprintf(stderr, "[browser-resolution] %ux%u\n", width, height);
}
diff --git a/src/runtime/linux_window.c b/src/runtime/linux_window.c
@@ -4,6 +4,9 @@
#include <SDL2/SDL.h>
#include <strings.h>
#include <pthread.h>
+#ifdef __EMSCRIPTEN__
+#include <emscripten.h>
+#endif
/* Guest classes and handles contain no native pointers. SDL owns decoration. */
static struct window_class {
@@ -42,6 +45,7 @@ static uint32_t queued_mouse_buttons;
#ifdef __EMSCRIPTEN__
/* Browsers cannot warp the physical pointer; camera recentering is virtual. */
static int cursor_x, cursor_y, cursor_warped, control_drag;
+static int browser_mouse, browser_mouse_x, browser_mouse_y;
static int wheel_drag;
static uint32_t wheel_deadline;
static float wheel_x, wheel_y;
@@ -766,7 +770,7 @@ static void cursor_position(void)
if (!linux_graphics_window()) { MEM32(g_fs_base + 0x34) = 8; return; }
int x, y;
#ifdef __EMSCRIPTEN__
- if (!cursor_warped) SDL_GetMouseState(&cursor_x, &cursor_y);
+ if (!cursor_warped && !browser_mouse) SDL_GetMouseState(&cursor_x, &cursor_y);
if (cursor_warped) {
int dx = (int)wheel_x, dy = (int)wheel_y;
wheel_x -= dx; wheel_y -= dy;
@@ -956,6 +960,40 @@ static uint32_t virtual_key(SDL_Keycode key, unsigned *scan)
}
#ifdef __EMSCRIPTEN__
+/* SDL's queue carries browser controls to the game worker in input order. */
+EMSCRIPTEN_KEEPALIVE void browser_input_key(int key, int down)
+{
+ SDL_Event event = {.type = down ? SDL_KEYDOWN : SDL_KEYUP};
+ event.key.keysym.sym = key;
+ event.key.state = down ? SDL_PRESSED : SDL_RELEASED;
+ if (SDL_PushEvent(&event) != 1) abort();
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_input_character(unsigned character)
+{
+ SDL_Event event = {.type = SDL_USEREVENT};
+ event.user.code = character;
+ if (SDL_PushEvent(&event) != 1) abort();
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_input_motion(int x, int y)
+{
+ SDL_Event event = {.type = SDL_MOUSEMOTION};
+ event.motion.which = SDL_TOUCH_MOUSEID;
+ event.motion.x = x; event.motion.y = y;
+ if (SDL_PushEvent(&event) != 1) abort();
+}
+
+EMSCRIPTEN_KEEPALIVE void browser_input_button(unsigned button, int down, int x, int y)
+{
+ SDL_Event event = {.type = down ? SDL_MOUSEBUTTONDOWN : SDL_MOUSEBUTTONUP};
+ event.button.which = SDL_TOUCH_MOUSEID;
+ event.button.button = button;
+ event.button.state = down ? SDL_PRESSED : SDL_RELEASED;
+ event.button.x = x; event.button.y = y;
+ if (SDL_PushEvent(&event) != 1) abort();
+}
+
static void end_wheel_drag(void)
{
if (!wheel_drag) return;
@@ -970,6 +1008,13 @@ static void end_wheel_drag(void)
static void process_event(const SDL_Event *event)
{
if (!client.handle) return;
+#ifdef __EMSCRIPTEN__
+ /* HTML input supplies composed text; physical keys use TranslateMessage. */
+ if (event->type == SDL_USEREVENT) {
+ queue_message(client.handle, 0x102, event->user.code, 1, 0, 0);
+ return;
+ }
+#endif
if (event->type == SDL_QUIT) queue_message(client.handle, 0x10, 0, 0, 0, 0);
else if (event->type == SDL_WINDOWEVENT &&
event->window.windowID == SDL_GetWindowID(linux_graphics_window())) {
@@ -1029,7 +1074,7 @@ static void process_event(const SDL_Event *event)
#ifdef __EMSCRIPTEN__
/* Include virtual gestures and keep lost-focus buttons released. */
state = queued_mouse_buttons;
- if (!wheel_drag) {
+ if (!wheel_drag && event->motion.which != SDL_TOUCH_MOUSEID) {
if (cursor_warped && (state & 2)) {
cursor_x += event->motion.xrel;
cursor_y += event->motion.yrel;
@@ -1040,8 +1085,12 @@ static void process_event(const SDL_Event *event)
SDL_Keymod modifiers = SDL_GetModState();
state |= modifiers & KMOD_SHIFT ? 4 : 0;
state |= modifiers & KMOD_CTRL ? 8 : 0;
+ int input = 2;
+#ifdef __EMSCRIPTEN__
+ if (event->motion.which == SDL_TOUCH_MOUSEID) input = 3;
+#endif
queue_message(client.handle, 0x200, state,
- (event->motion.x & 0xffffu) | ((uint32_t)event->motion.y << 16), 2, 0);
+ (event->motion.x & 0xffffu) | ((uint32_t)event->motion.y << 16), input, 0);
} else if (event->type == SDL_MOUSEBUTTONDOWN || event->type == SDL_MOUSEBUTTONUP) {
uint32_t button = event->button.button, message, mask;
#ifdef __EMSCRIPTEN__
@@ -1063,8 +1112,12 @@ static void process_event(const SDL_Event *event)
SDL_Keymod modifiers = SDL_GetModState();
state |= modifiers & KMOD_SHIFT ? 4 : 0;
state |= modifiers & KMOD_CTRL ? 8 : 0;
+ int input = 2;
+#ifdef __EMSCRIPTEN__
+ if (event->button.which == SDL_TOUCH_MOUSEID) input = 3;
+#endif
queue_message(client.handle, message + up, state,
- (event->button.x & 0xffffu) | ((uint32_t)event->button.y << 16), 2, 0);
+ (event->button.x & 0xffffu) | ((uint32_t)event->button.y << 16), input, 0);
} else if (event->type == SDL_MOUSEWHEEL) {
#ifdef __EMSCRIPTEN__
/* SDL converts pixel wheel deltas to steps; restore pixels for the camera. */
@@ -1107,10 +1160,26 @@ static int read_message(uint32_t output, uint32_t window, uint32_t first, uint32
if (entry->keyboard == 1) {
keyboard_state[entry->words[2]] = message & 1 ? 0 : 0x80;
SDL_SetModState(entry->modifiers);
- } else if (entry->keyboard == 2) {
+ } else if (entry->keyboard == 2 || entry->keyboard == 3) {
keyboard_state[1] = entry->words[2] & 1 ? 0x80 : 0;
keyboard_state[2] = entry->words[2] & 2 ? 0x80 : 0;
keyboard_state[4] = entry->words[2] & 16 ? 0x80 : 0;
+#ifdef __EMSCRIPTEN__
+ /* Touch presses must see their own point, before later drag motion. */
+ browser_mouse = entry->keyboard == 3;
+ if (browser_mouse) {
+ int x = (int16_t)entry->words[3], y = (int16_t)(entry->words[3] >> 16);
+ if (message == 0x200 && cursor_warped && (entry->words[2] & 2)) {
+ cursor_x += x - browser_mouse_x;
+ cursor_y += y - browser_mouse_y;
+ } else if (message != 0x205 || !cursor_warped) {
+ /* Releasing a camera drag must not add an absolute-position jump. */
+ cursor_x = x; cursor_y = y;
+ cursor_warped = 0;
+ }
+ browser_mouse_x = x; browser_mouse_y = y;
+ }
+#endif
}
*link = entry->next;
if (message_tail == entry) message_tail = previous;
diff --git a/src/tests/browser_camera.c b/src/tests/browser_camera.c
@@ -8,6 +8,10 @@
static SDL_Window *native_window;
static uint32_t window;
+void browser_input_key(int key, int down);
+void browser_input_character(unsigned character);
+void browser_input_motion(int x, int y);
+void browser_input_button(unsigned button, int down, int x, int y);
struct SDL_Window *linux_graphics_window(void) { return native_window; }
int linux_graphics_display_mode(SDL_DisplayMode *mode) { return SDL_GetCurrentDisplayMode(0, mode); }
recomp_func_t recomp_lookup(uint32_t address)
@@ -129,6 +133,100 @@ static void focus_loss_releases_camera_button(void)
assert(!MEM32(0x50003008));
}
+static void browser_controls_preserve_key_and_text_order(void)
+{
+ uint32_t output = 0x50003000, keys = 0x50003100;
+ uint32_t peek[] = {output, window, 0x100, 0x102, 1};
+ browser_input_key('w', 1);
+ browser_input_key('w', 0);
+ browser_input_character('H');
+ browser_input_character(0xe9);
+ browser_input_key(13, 1);
+ browser_input_key(13, 0);
+
+ assert(call("PeekMessageA", 5, peek));
+ assert(call("GetKeyboardState", 1, &keys));
+
+ assert(MEM32(output + 4) == 0x100 && MEM32(output + 8) == 'W');
+ assert(MEM8(keys + 'W') == 0x80);
+ assert(call("PeekMessageA", 5, peek));
+ assert(MEM32(output + 4) == 0x101 && MEM32(output + 8) == 'W');
+ assert(call("GetKeyboardState", 1, &keys) && !MEM8(keys + 'W'));
+ assert(call("PeekMessageA", 5, peek));
+ assert(MEM32(output + 4) == 0x102 && MEM32(output + 8) == 'H');
+ assert(call("PeekMessageA", 5, peek));
+ assert(MEM32(output + 4) == 0x102 && MEM32(output + 8) == 0xe9);
+ assert(call("PeekMessageA", 5, peek));
+ assert(MEM32(output + 4) == 0x100 && MEM32(output + 8) == 13);
+ assert(call("PeekMessageA", 5, peek));
+ assert(MEM32(output + 4) == 0x101 && MEM32(output + 8) == 13);
+ assert(!call("PeekMessageA", 5, peek));
+}
+
+static void touch_drag_preserves_the_press_position(void)
+{
+ browser_input_motion(100, 20);
+ browser_input_button(SDL_BUTTON_LEFT, 1, 100, 20);
+ browser_input_motion(180, 60);
+ browser_input_button(SDL_BUTTON_LEFT, 0, 180, 60);
+ uint32_t output = 0x50003100;
+
+ assert(mouse_message() == 0x200);
+ assert(mouse_message() == 0x201);
+ assert(call("GetCursorPos", 1, &output));
+
+ assert(MEM32(output) == 100 && MEM32(output + 4) == 20);
+ assert(mouse_message() == 0x200);
+ assert(call("GetCursorPos", 1, &output));
+ assert(MEM32(output) == 180 && MEM32(output + 4) == 60);
+ assert(mouse_message() == 0x202);
+ assert(!MEM32(0x50003008));
+ assert(!mouse_message());
+}
+
+static void touch_camera_accumulates_motion_after_recentering(void)
+{
+ browser_input_motion(320, 240);
+ browser_input_button(SDL_BUTTON_RIGHT, 1, 320, 240);
+ assert(mouse_message() == 0x200);
+ assert(mouse_message() == 0x204);
+ assert(call("SetCursorPos", 2, (uint32_t[]){320, 240}));
+ browser_input_motion(330, 235);
+ assert(mouse_message() == 0x200);
+ assert(call("SetCursorPos", 2, (uint32_t[]){320, 240}));
+
+ browser_input_motion(340, 230);
+ assert(mouse_message() == 0x200);
+ uint32_t output = 0x50003100;
+ assert(call("GetCursorPos", 1, &output));
+
+ assert(MEM32(output) == 330 && MEM32(output + 4) == 235);
+ browser_input_button(SDL_BUTTON_RIGHT, 0, 340, 230);
+ assert(mouse_message() == 0x205);
+ assert(!MEM32(0x50003008));
+ assert(!mouse_message());
+}
+
+static void touch_camera_release_preserves_recentered_position(void)
+{
+ browser_input_motion(320, 80);
+ browser_input_button(SDL_BUTTON_RIGHT, 1, 320, 80);
+ assert(mouse_message() == 0x200);
+ assert(mouse_message() == 0x204);
+ assert(call("SetCursorPos", 2, (uint32_t[]){320, 240}));
+ browser_input_motion(360, 80);
+ assert(mouse_message() == 0x200);
+ assert(call("SetCursorPos", 2, (uint32_t[]){320, 240}));
+
+ browser_input_button(SDL_BUTTON_RIGHT, 0, 360, 80);
+ assert(mouse_message() == 0x205);
+ uint32_t output = 0x50003100;
+ assert(call("GetCursorPos", 1, &output));
+
+ assert(MEM32(output) == 320 && MEM32(output + 4) == 240);
+ assert(!mouse_message());
+}
+
int main(void)
{
assert(guest_map("camera test", 0x50000000, 0x10000));
@@ -151,6 +249,10 @@ int main(void)
control_drag_releases_after_modifier_release();
wheel_rotation_keeps_fractional_motion_and_ends();
focus_loss_releases_camera_button();
- puts("camera: recentering, Ctrl-drag, fractional wheel motion, timeout and focus loss passed");
+ browser_controls_preserve_key_and_text_order();
+ touch_drag_preserves_the_press_position();
+ touch_camera_accumulates_motion_after_recentering();
+ touch_camera_release_preserves_recentered_position();
+ puts("camera: recentering, Ctrl-drag, wheel motion, focus loss and browser key/text/touch input passed");
return 0;
}
diff --git a/src/tests/browser_controls.mjs b/src/tests/browser_controls.mjs
@@ -0,0 +1,894 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import test from 'node:test';
+
+function page({navigator = {userAgent: 'Mozilla/5.0 (Android) Gecko Firefox/149.0'}, saved = null, ready = true} = {}) {
+ const elements = new Map();
+ const keys = [], characters = [], mouse = [], orbits = [], sizes = [], chatViewports = [], cursorHidden = [], hudInsets = [];
+ const scrolls = [];
+ const timers = new Map();
+ const storage = new Map(saved === null ? [] : [['ao-touch-controls', saved]]);
+ const document = new EventTarget();
+ class Element extends EventTarget {
+ hidden = false;
+ open = false;
+ style = {};
+ dataset = {};
+ clientWidth = 844;
+ clientHeight = 390;
+ value = '';
+ validity = '';
+ dispatchEvent(event) {
+ const result = super.dispatchEvent(event);
+ this['on' + event.type]?.(event);
+ return result;
+ }
+ focus() { document.activeElement = this; this.dispatchEvent(new Event('focus')); }
+ blur() { document.activeElement = null; this.dispatchEvent(new Event('blur')); }
+ setPointerCapture() {}
+ getBoundingClientRect() { return {left: 0, top: 0, width: this.clientWidth, height: this.clientHeight}; }
+ showModal() { this.open = true; }
+ close() { this.open = false; this.dispatchEvent(new Event('close')); }
+ setCustomValidity(message) { this.validity = message; }
+ reportValidity() {}
+ }
+ document.querySelector = selector => {
+ if (!elements.has(selector)) elements.set(selector, new Element());
+ return elements.get(selector);
+ };
+ const actions = [32, 113, 101].map(key => {
+ const button = new Element();
+ button.dataset.key = key;
+ return button;
+ });
+ document.querySelectorAll = () => actions;
+ document.querySelector('#chat-compose').hidden = true;
+ document.querySelector('#touch-controls').hidden = true;
+ const canvas = document.querySelector('#canvas');
+
+ const window = new EventTarget();
+ window.visualViewport = new EventTarget();
+ window.visualViewport.height = 390;
+ window.visualViewport.width = 844;
+ window.visualViewport.offsetLeft = 0;
+ window.visualViewport.offsetTop = 0;
+ const context = vm.createContext({
+ document, window, navigator, Event, TextDecoder, Uint8Array,
+ console: {log() {}, error: console.error},
+ localStorage: {getItem: key => storage.get(key) ?? null, setItem: (key, value) => storage.set(key, String(value))},
+ devicePixelRatio: 2, innerHeight: 390, crossOriginIsolated: false,
+ ResizeObserver: class { observe() {} },
+ setTimeout: callback => { const id = Symbol(); timers.set(id, callback); return id; },
+ clearTimeout: id => timers.delete(id)
+ });
+ const html = fs.readFileSync(new URL('../browser/index.html', import.meta.url), 'utf8');
+ for (const script of html.matchAll(/<script(?: id="player-controls")?>([\s\S]*?)<\/script>/g))
+ vm.runInContext(script[1], context);
+ context.Module._browser_input_key = (key, down) => keys.push([key, down]);
+ context.Module._browser_input_character = character => characters.push(character);
+ context.Module._browser_input_motion = (x, y) => mouse.push(['mousemove', x, y, 0]);
+ context.Module._browser_input_button = (button, down, x, y) => mouse.push([down ? 'mousedown' : 'mouseup', x, y, button === 3 ? 2 : 0]);
+ context.Module._browser_orbit = (x, y, active) => orbits.push([x, y, active]);
+ context.Module._browser_hide_cursor = hidden => cursorHidden.push(hidden);
+ context.Module._browser_hud_insets = (right, top) => hudInsets.push([right, top]);
+ context.Module._browser_request_resize = (width, height) => sizes.push([width, height]);
+ context.Module._browser_chat_viewport = bottom => chatViewports.push(bottom);
+ context.Module._browser_chat_scroll = pixels => scrolls.push(pixels);
+ context.Module.onRuntimeInitialized();
+ if (ready) context.Module.onFirstFrame();
+ context.Module.onChatBounds({x: 1, y: 355, width: 760, height: 14, screenWidth: 844, screenHeight: 390});
+ context.Module.onTouchRegions({screenWidth: 844, screenHeight: 390,
+ regions: [{left: 0, top: 0, right: 844, bottom: 390, world: true}]});
+ function fire(selector, type, values = {}) {
+ const event = new Event(type, {cancelable: true});
+ Object.assign(event, {pointerId: 1, pointerType: 'touch', clientX: 100, clientY: 120}, values);
+ if (type.startsWith('pointer')) document.dispatchEvent(event);
+ document.querySelector(selector).dispatchEvent(event);
+ return event;
+ }
+ return {document, window, navigator, canvas, keys, characters, mouse, orbits, sizes, chatViewports, cursorHidden, hudInsets, scrolls, storage, actions, fire,
+ firstFrame: () => context.Module.onFirstFrame(),
+ chatBounds: bounds => context.Module.onChatBounds(bounds),
+ touchRegions: bounds => context.Module.onTouchRegions(bounds),
+ element: selector => document.querySelector(selector),
+ hold: () => { for (const callback of timers.values()) callback(); timers.clear(); }};
+}
+
+test('dragging chat scrolls history without clicks, camera movement or a held right click', () => {
+ const game = page();
+ game.chatBounds({x: 13, y: 201, width: 336, height: 14, screenWidth: 844, screenHeight: 390,
+ history: {x: 12, y: 100, width: 338, height: 100}});
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 12, top: 100, right: 350, bottom: 200, chat: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientY: 150});
+ game.hold();
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+ game.fire('#canvas', 'pointermove', {clientY: 135});
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.scrolls, [30, -15]);
+ assert.deepEqual(game.mouse, []);
+ assert.deepEqual(game.orbits, []);
+});
+
+test('chat history scrolls while composing without taking focus from the keyboard', () => {
+ const game = page();
+ game.chatBounds({x: 21, y: 201, width: 328, height: 14, screenWidth: 844, screenHeight: 390,
+ history: {x: 20, y: 20, width: 330, height: 180}});
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 20, top: 20, right: 350, bottom: 200, chat: true}
+ ]});
+ game.fire('#chat-button', 'click');
+
+ const drag = game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientY: 150});
+ game.fire('#canvas', 'pointercancel');
+
+ assert.deepEqual(game.scrolls, [30]);
+ assert.equal(drag.defaultPrevented, true);
+ assert.equal(game.document.activeElement, game.element('#chat-text'));
+ assert.deepEqual(game.mouse, []);
+});
+
+test('chat scrolling converts CSS movement into Retina rendering pixels', () => {
+ const game = page();
+ game.canvas.clientWidth = 422;
+ game.canvas.clientHeight = 195;
+ game.chatBounds({x: 25, y: 381, width: 674, height: 14, screenWidth: 844, screenHeight: 390,
+ history: {x: 24, y: 100, width: 676, height: 280}});
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 24, top: 100, right: 700, bottom: 380, chat: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientY: 150});
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.scrolls, [60]);
+});
+
+test('a native window covering history keeps its own touch interaction', () => {
+ const game = page();
+ game.chatBounds({x: 13, y: 201, width: 336, height: 14, screenWidth: 844, screenHeight: 390,
+ history: {x: 12, y: 100, width: 338, height: 100}});
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 50, top: 110, right: 200, bottom: 180, world: false},
+ {left: 12, top: 100, right: 350, bottom: 200, chat: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientY: 150});
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.scrolls, []);
+ assert.ok(game.mouse.some(event => event[0] === 'mousedown'));
+});
+
+test('desktop touch cannot activate chat scrolling', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'}});
+ game.chatBounds({x: 13, y: 201, width: 336, height: 14, screenWidth: 844, screenHeight: 390,
+ history: {x: 12, y: 100, width: 338, height: 100}});
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 12, top: 100, right: 350, bottom: 200, chat: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientY: 150});
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.scrolls, []);
+});
+
+test('overlays wait for a rendered game world after loading', () => {
+ const game = page({ready: false});
+ assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#touch-controls').hidden, true);
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: []});
+
+ game.firstFrame();
+ assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#touch-controls').hidden, true);
+ game.touchRegions({screenWidth: 844, screenHeight: 390,
+ regions: [{left: 0, top: 0, right: 844, bottom: 370, world: true}]});
+
+ assert.equal(game.element('#game-toolbar').hidden, false);
+ assert.equal(game.element('#touch-controls').hidden, false);
+});
+
+test('overlays stay revealed until the last touch ends and reset on blur', () => {
+ const game = page();
+ const surface = game.element('#game-surface');
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#move-pad', 'pointerdown', {pointerId: 2});
+ game.fire('#canvas', 'pointerup');
+ assert.equal(surface.dataset.overlaysActive, '');
+ game.fire('#move-pad', 'pointercancel', {pointerId: 2});
+ assert.equal(surface.dataset.overlaysActive, undefined);
+ game.fire('#canvas', 'pointerdown');
+ assert.equal(surface.dataset.overlaysActive, '');
+ game.window.dispatchEvent(new Event('blur'));
+
+ assert.equal(surface.dataset.overlaysActive, undefined);
+});
+
+test('chat actions stay visible without touching and fade after chat closes', () => {
+ const game = page();
+
+ game.fire('#chat-button', 'click');
+ assert.equal(game.element('#game-surface').dataset.overlaysActive, '');
+ game.fire('#chat-cancel', 'click');
+
+ assert.equal(game.element('#game-surface').dataset.overlaysActive, undefined);
+});
+
+test('touch taps move the cursor and send one complete left click', () => {
+ const game = page();
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerup');
+ game.hold();
+
+ assert.deepEqual(game.cursorHidden, [true]);
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 100, 120, 0], ['mousemove', 100, 120, 0],
+ ['mousedown', 100, 120, 0], ['mouseup', 100, 120, 0]
+ ]);
+});
+
+test('touch compatibility mouse events cannot reach SDL during or after orbit', () => {
+ const game = page();
+ const nativeMouseEvents = [];
+ for (const type of ['mousemove', 'mousedown', 'mouseup'])
+ game.canvas.addEventListener(type, event => nativeMouseEvents.push(event.type));
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+
+ game.fire('#canvas', 'mousemove');
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 102});
+ game.fire('#canvas', 'mousemove');
+ game.fire('#canvas', 'pointerup');
+ game.fire('#canvas', 'pointerup', {pointerId: 2});
+ game.fire('#canvas', 'mousemove');
+ game.fire('#canvas', 'mousedown');
+ game.fire('#canvas', 'mouseup');
+
+ assert.deepEqual(nativeMouseEvents, []);
+ game.fire('#canvas', 'pointermove', {pointerType: 'mouse'});
+ game.fire('#canvas', 'mousemove');
+ assert.deepEqual(nativeMouseEvents, ['mousemove']);
+});
+
+test('desktop mouse events pass through after touch input', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'}});
+ let mouseEvents = 0;
+ game.canvas.addEventListener('mousemove', () => ++mouseEvents);
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'mousemove');
+
+ assert.deepEqual(game.cursorHidden, [false]);
+ assert.equal(mouseEvents, 1);
+});
+
+test('a native UI drag keeps the left button when it crosses into the world', () => {
+ const game = page();
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 90, top: 110, right: 120, bottom: 140, world: false},
+ {left: 0, top: 0, right: 844, bottom: 390, world: true}
+ ]});
+ game.fire('#canvas', 'pointerdown');
+
+ game.fire('#canvas', 'pointermove', {clientX: 140});
+ game.fire('#canvas', 'pointercancel');
+ game.hold();
+
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 100, 120, 0], ['mousedown', 100, 120, 0],
+ ['mousemove', 140, 120, 0], ['mouseup', 140, 120, 0]
+ ]);
+});
+
+test('a world swipe rotates without selecting an object on release', () => {
+ const game = page();
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 400, top: 160, right: 500, bottom: 250, world: false},
+ {left: 0, top: 0, right: 844, bottom: 390, world: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown', {clientX: 300, clientY: 200});
+ game.fire('#canvas', 'pointermove', {clientX: 420, clientY: 180});
+ game.fire('#canvas', 'pointerup', {clientX: 420, clientY: 180});
+ game.hold();
+
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 300, 200, 0], ['mousemove', 422, 98, 0], ['mousedown', 422, 98, 2],
+ ['mousemove', 542, 78, 0], ['mousemove', 542, 78, 0],
+ ['mouseup', 542, 78, 2]
+ ]);
+});
+
+test('native UI hit testing scales correctly in Retina mode', () => {
+ const game = page();
+ game.element('#pixel-mode').value = 'retina';
+ game.fire('#pixel-mode', 'change');
+ game.touchRegions({screenWidth: 1688, screenHeight: 780, regions: [
+ {left: 190, top: 230, right: 220, bottom: 260, world: false},
+ {left: 0, top: 0, right: 1688, bottom: 780, world: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientX: 140});
+ game.fire('#canvas', 'pointercancel');
+
+ assert.deepEqual(game.hudInsets, [[24, 0], [48, 0]]);
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 200, 240, 0], ['mousedown', 200, 240, 0],
+ ['mousemove', 280, 240, 0], ['mouseup', 280, 240, 0]
+ ]);
+});
+
+test('mobile fullscreen adds top clearance and restores it on exit', () => {
+ const game = page();
+
+ game.document.fullscreenElement = game.element('#game-surface');
+ game.document.dispatchEvent(new Event('fullscreenchange'));
+ game.element('#pixel-mode').value = 'retina';
+ game.fire('#pixel-mode', 'change');
+ game.document.fullscreenElement = null;
+ game.document.dispatchEvent(new Event('fullscreenchange'));
+
+ assert.deepEqual(game.hudInsets, [[24, 0], [24, 24], [48, 48], [48, 0]]);
+});
+
+test('a world swipe anchors beside a window covering the camera origin', () => {
+ const game = page();
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 350, top: 80, right: 500, bottom: 130, world: false},
+ {left: 0, top: 0, right: 844, bottom: 390, world: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown', {clientX: 300, clientY: 200});
+ game.fire('#canvas', 'pointermove', {clientX: 420, clientY: 180});
+ game.fire('#canvas', 'pointercancel');
+
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 300, 200, 0], ['mousemove', 300, 98, 0], ['mousedown', 300, 98, 2],
+ ['mousemove', 420, 78, 0], ['mouseup', 420, 78, 2]
+ ]);
+});
+
+test('touch coordinates follow the selected Retina resolution', () => {
+ const game = page();
+ game.element('#pixel-mode').value = 'retina';
+ game.fire('#pixel-mode', 'change');
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 200, 240, 0], ['mousemove', 200, 240, 0],
+ ['mousedown', 200, 240, 0], ['mouseup', 200, 240, 0]
+ ]);
+});
+
+test('holding a touch makes a right click and another finger cannot release it', () => {
+ const game = page();
+ game.fire('#canvas', 'pointerdown');
+
+ game.hold();
+ game.fire('#canvas', 'pointercancel', {pointerId: 2});
+ game.fire('#canvas', 'pointerup');
+
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 100, 120, 0], ['mousedown', 100, 120, 2],
+ ['mousemove', 100, 120, 0], ['mouseup', 100, 120, 2]
+ ]);
+});
+
+test('movement and camera work together and opening settings releases both', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+
+ game.fire('#move-pad', 'pointerdown', {clientX: 90, clientY: 10});
+ game.fire('#canvas', 'pointerdown', {pointerId: 2, clientX: 400, clientY: 250});
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 600, clientY: 240});
+ game.fire('#menu-button', 'click');
+
+ assert.deepEqual(game.keys, [[99, true], [119, true], [99, false], [119, false]]);
+ assert.deepEqual(game.mouse, [
+ ['mousemove', 400, 250, 0], ['mousemove', 422, 98, 0], ['mousedown', 422, 98, 2],
+ ['mousemove', 622, 88, 0], ['mouseup', 622, 88, 2]
+ ]);
+ assert.equal(game.element('#touch-controls').hidden, true);
+ assert.equal(game.element('#player-menu').open, true);
+});
+
+test('two world fingers orbit while a third finger keeps moving', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+ game.fire('#move-pad', 'pointerdown', {pointerId: 3, clientX: 56, clientY: 10});
+ game.fire('#canvas', 'pointerdown', {clientX: 400, clientY: 200});
+ game.fire('#canvas', 'pointerdown', {pointerId: 2, clientX: 500, clientY: 200});
+
+ game.fire('#canvas', 'pointermove', {clientX: 420, clientY: 180});
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 520, clientY: 180});
+ game.fire('#canvas', 'pointerup', {pointerId: 2});
+ game.fire('#canvas', 'pointermove', {clientX: 600});
+ game.fire('#canvas', 'pointerup');
+ game.hold();
+
+ assert.deepEqual(game.keys, [[119, true]]);
+ assert.deepEqual(game.mouse, [['mousemove', 400, 200, 0]]);
+ assert.deepEqual(game.orbits, [[0, 0, 1], [272, -588, 1], [272, -588, 1], [0, 0, 0]]);
+ game.fire('#move-pad', 'pointerup', {pointerId: 3});
+ assert.deepEqual(game.keys.at(-1), [119, false]);
+});
+
+test('adding a second world finger releases steering before starting orbit', () => {
+ const game = page();
+ const first = game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientX: 140});
+
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+ game.window.dispatchEvent(new Event('blur'));
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 200});
+
+ assert.equal(first.defaultPrevented, false);
+ assert.deepEqual(game.mouse.filter(event => event[0] !== 'mousemove').map(event => [event[0], event[3]]),
+ [['mousedown', 2], ['mouseup', 2]]);
+ assert.deepEqual(game.keys, []);
+ assert.deepEqual(game.orbits, [[0, 0, 1], [0, 0, 0]]);
+});
+
+test('mobile buttons leave pointer defaults enabled for Firefox multitouch', () => {
+ const game = page();
+ const cancelled = [];
+
+ cancelled.push(game.fire('#move-pad', 'pointerdown').defaultPrevented);
+ game.fire('#move-pad', 'pointerup');
+ cancelled.push(game.fire('#autorun-button', 'pointerdown').defaultPrevented);
+ for (const button of game.actions) {
+ const event = new Event('pointerdown', {cancelable: true});
+ button.dispatchEvent(event);
+ cancelled.push(event.defaultPrevented);
+ }
+
+ assert.deepEqual(cancelled, [false, false, false, false, false]);
+});
+
+test('UI touches cannot join or start a camera orbit', () => {
+ const game = page();
+ game.touchRegions({screenWidth: 844, screenHeight: 390, regions: [
+ {left: 90, top: 110, right: 120, bottom: 140, world: false},
+ {left: 0, top: 0, right: 844, bottom: 390, world: true}
+ ]});
+
+ game.fire('#canvas', 'pointerdown', {clientX: 300});
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+ game.fire('#canvas', 'pointercancel');
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerdown', {pointerId: 2, clientX: 300});
+ game.fire('#canvas', 'pointermove', {clientX: 140});
+ game.fire('#canvas', 'pointercancel');
+
+ assert.deepEqual(game.keys, []);
+ assert.deepEqual(game.orbits, []);
+ assert.deepEqual(game.mouse.filter(event => event[0] !== 'mousemove'),
+ [['mousedown', 100, 120, 0], ['mouseup', 140, 120, 0]]);
+});
+
+test('releasing movement leaves orbit active until a camera finger is cancelled', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+ game.fire('#move-pad', 'pointerdown', {pointerId: 3, clientX: 56, clientY: 10});
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+
+ game.fire('#move-pad', 'pointerup', {pointerId: 3});
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 140});
+ game.fire('#canvas', 'lostpointercapture');
+ game.fire('#canvas', 'pointerup');
+ game.fire('#canvas', 'pointerup', {pointerId: 2});
+
+ assert.deepEqual(game.keys, [[119, true], [119, false]]);
+ assert.deepEqual(game.orbits, [[0, 0, 1], [544, 0, 1], [0, 0, 0]]);
+ assert.deepEqual(game.mouse, [['mousemove', 100, 120, 0]]);
+});
+
+test('autorun keeps moving after releasing the joystick and stops on a second press', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+ game.fire('#move-pad', 'pointerdown', {clientX: 56, clientY: 10});
+
+ game.fire('#autorun-button', 'pointerdown', {pointerId: 2});
+ game.fire('#autorun-button', 'click', {detail: 1});
+ game.fire('#move-pad', 'pointerup');
+
+ assert.deepEqual(game.keys, [[119, true]]);
+ assert.equal(game.element('#autorun-button').textContent, 'Stop');
+ assert.equal(game.element('#autorun-button').ariaPressed, 'true');
+ game.fire('#autorun-button', 'pointerdown');
+ assert.deepEqual(game.keys, [[119, true], [119, false]]);
+ assert.equal(game.element('#autorun-button').textContent, 'Autorun');
+});
+
+test('pulling the joystick backward cancels autorun', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+ game.fire('#autorun-button', 'pointerdown');
+
+ game.fire('#move-pad', 'pointerdown', {pointerId: 2, clientX: 56, clientY: 100});
+ game.fire('#move-pad', 'pointerup', {pointerId: 2});
+
+ assert.deepEqual(game.keys, [[119, true], [119, false], [115, true], [115, false]]);
+ assert.equal(game.element('#autorun-button').ariaPressed, 'false');
+});
+
+test('opening chat or options and losing focus stop autorun', () => {
+ for (const target of ['#chat-button', '#menu-button', null]) {
+ const game = page();
+ game.fire('#autorun-button', 'pointerdown');
+
+ if (target) game.fire(target, 'click');
+ else game.window.dispatchEvent(new Event('blur'));
+
+ assert.deepEqual(game.keys.slice(0, 2), [[119, true], [119, false]]);
+ assert.equal(game.element('#autorun-button').ariaPressed, 'false');
+ }
+});
+
+test('desktop browsers cannot activate orbit or autorun', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)', maxTouchPoints: 5}});
+
+ game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+ game.fire('#canvas', 'pointermove', {clientX: 200});
+ game.fire('#autorun-button', 'pointerdown');
+ game.fire('#autorun-button', 'click', {detail: 0});
+
+ assert.deepEqual(game.keys, []);
+ assert.deepEqual(game.mouse, []);
+ assert.deepEqual(game.orbits, []);
+});
+
+test('blur releases movement and subsequent finger motion cannot restart it', () => {
+ const game = page();
+ game.element('#move-pad').clientWidth = game.element('#move-pad').clientHeight = 112;
+ game.fire('#move-pad', 'pointerdown', {clientX: 56, clientY: 10});
+
+ game.window.dispatchEvent(new Event('blur'));
+ game.fire('#move-pad', 'pointermove', {clientX: 56, clientY: 0});
+
+ assert.deepEqual(game.keys, [[119, true], [119, false]]);
+});
+
+test('native chat sends composed text once and keeps typing out of game controls', () => {
+ const game = page();
+ let gameKeyEvents = 0;
+ game.window.addEventListener('keydown', () => ++gameKeyEvents);
+
+ game.fire('#chat-button', 'click');
+ game.element('#chat-text').value = 'H\u00e9llo!';
+ game.window.dispatchEvent(new Event('keydown'));
+ game.fire('#chat-compose', 'submit');
+
+ assert.deepEqual(game.characters, [72, 233, 108, 108, 111, 33]);
+ assert.deepEqual(game.keys, [[27, true], [27, false], [13, true], [13, false], [13, true], [13, false]]);
+ assert.equal(gameKeyEvents, 0);
+ assert.equal(game.element('#chat-compose').hidden, true);
+ assert.equal(game.document.activeElement, game.canvas);
+});
+
+test('action buttons respond on press without repeating on the resulting click', () => {
+ const game = page();
+
+ for (const button of game.actions) {
+ button.dispatchEvent(new Event('pointerdown', {cancelable: true}));
+ const click = new Event('click');
+ Object.assign(click, {detail: 1});
+ button.dispatchEvent(click);
+ }
+
+ assert.deepEqual(game.keys, [
+ [32, true], [32, false], [113, true], [113, false],
+ [101, true], [101, false]
+ ]);
+});
+
+test('the keyboard moves chat while the game viewport stays unchanged', () => {
+ const game = page();
+ game.window.visualViewport.height = 180;
+
+ game.fire('#chat-button', 'click');
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+ game.chatBounds({x: 1, y: 165, width: 320, height: 14, screenWidth: 844, screenHeight: 390});
+
+ assert.equal(game.document.activeElement, game.element('#chat-text'));
+ assert.equal(game.element('#touch-controls').hidden, true);
+ assert.deepEqual(game.sizes, [[844, 390]]);
+ assert.equal(game.chatViewports.at(-1), 180);
+ assert.equal(game.canvas.clientHeight, 390);
+ assert.equal(game.element('#chat-compose').style.left, '1px');
+ assert.equal(game.element('#chat-compose').style.top, '165px');
+ assert.equal(game.element('#chat-compose').style.width, '320px');
+ assert.equal(game.element('#chat-compose').style.height, '14px');
+});
+
+test('closing chat restores its native position without resizing the game', () => {
+ const game = page();
+ game.fire('#chat-button', 'touchend');
+ game.window.visualViewport.height = 180;
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+
+ game.fire('#chat-cancel', 'click');
+ game.window.visualViewport.height = 390;
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+
+ assert.deepEqual(game.sizes, [[844, 390]]);
+ assert.equal(game.chatViewports.at(-1), 0);
+ assert.equal(game.element('#chat-actions').hidden, true);
+ assert.equal(game.element('#chat-button').hidden, false);
+ assert.equal(game.document.activeElement, game.canvas);
+});
+
+test('chat geometry scales Retina pixels into CSS pixels', () => {
+ const game = page();
+ game.element('#pixel-mode').value = 'retina';
+ game.fire('#pixel-mode', 'change');
+ game.fire('#chat-button', 'click');
+ game.window.visualViewport.height = 180;
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+
+ game.chatBounds({x: 2, y: 740, width: 640, height: 28, screenWidth: 1688, screenHeight: 780});
+
+ assert.equal(game.element('#chat-compose').style.left, '1px');
+ assert.equal(game.element('#chat-compose').style.top, '165.5px');
+ assert.equal(game.element('#chat-compose').style.width, '320px');
+ assert.equal(game.element('#chat-compose').style.height, '14px');
+ assert.equal(game.element('#chat-text').style.fontSize, '6px');
+ assert.equal(game.chatViewports.at(-1), 360);
+});
+
+test('a short landscape viewport keeps the editor above the keyboard with stale native bounds', () => {
+ const game = page();
+ game.fire('#chat-button', 'touchend');
+ game.element('#chat-text').value = 'Draft';
+ game.window.visualViewport.height = 80;
+ game.window.visualViewport.offsetTop = 25;
+
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+ game.chatBounds({x: 11, y: 200, width: 174, height: 14, screenWidth: 844, screenHeight: 390});
+
+ assert.equal(game.element('#chat-compose').style.top, '65px');
+ assert.equal(game.element('#chat-compose').style.height, '14px');
+ assert.equal(game.element('#game-surface').style.top, '25px');
+ assert.equal(game.element('#chat-text').value, 'Draft');
+ assert.equal(game.chatViewports.at(-1), 80);
+ assert.deepEqual(game.sizes, [[844, 390]]);
+});
+
+test('a clipped native field keeps the editor caret within the phone width', () => {
+ const game = page();
+ game.canvas.clientWidth = 390;
+ game.canvas.clientHeight = 844;
+ game.window.visualViewport.width = 390;
+ game.window.visualViewport.height = 844;
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+
+ game.chatBounds({x: 11, y: 826, width: 760, height: 14, screenWidth: 390, screenHeight: 844});
+
+ assert.equal(game.element('#chat-compose').style.left, '11px');
+ assert.equal(game.element('#chat-compose').style.width, '379px');
+});
+
+test('a released movement pad stays disengaged while another touch reveals the controls', () => {
+ const game = page();
+
+ game.fire('#move-pad', 'pointerdown');
+ game.fire('#canvas', 'pointerdown', {pointerId: 2});
+ game.fire('#canvas', 'pointermove', {pointerId: 2, clientX: 140});
+ game.fire('#move-pad', 'pointerup');
+
+ assert.equal('active' in game.element('#move-pad').dataset, false);
+ assert.equal(game.element('#game-surface').dataset.overlaysActive, '');
+
+ game.window.dispatchEvent(new Event('blur'));
+
+ assert.deepEqual(game.mouse.at(-1), ['mouseup', 462, 98, 2]);
+});
+
+test('a chat touch focuses the field during the gesture and suppresses the compatibility click', () => {
+ const game = page();
+
+ const touch = game.fire('#chat-button', 'touchend');
+ if (!touch.defaultPrevented) game.fire('#chat-button', 'click');
+
+ assert.equal(touch.defaultPrevented, true);
+ assert.equal(game.document.activeElement, game.element('#chat-text'));
+ assert.equal(game.element('#chat-compose').hidden, false);
+ assert.deepEqual(game.keys, [[27, true], [27, false], [13, true], [13, false]]);
+});
+
+test('IME composition cannot cancel or implicitly submit the draft', () => {
+ const game = page();
+ game.fire('#chat-button', 'touchend');
+ game.element('#chat-text').value = 'Hello';
+ const escape = new Event('keydown', {cancelable: true});
+ Object.assign(escape, {key: 'Escape', isComposing: true, keyCode: 229});
+
+ game.fire('#chat-text', 'compositionstart');
+ game.window.dispatchEvent(escape);
+ game.fire('#chat-compose', 'submit', {submitter: game.element('[form="chat-compose"]')});
+ game.fire('#chat-text', 'compositionend');
+ const released = new Event('keyup');
+ Object.assign(released, {key: 'Escape', keyCode: 27});
+ game.window.dispatchEvent(released);
+
+ assert.equal(game.element('#chat-compose').hidden, false);
+ assert.equal(game.element('#chat-text').value, 'Hello');
+ assert.deepEqual(game.characters, []);
+ assert.equal(game.document.activeElement, game.element('#chat-text'));
+});
+
+test('the keyboard button refocuses the existing draft without submitting it', () => {
+ const game = page();
+ game.fire('#chat-button', 'touchend');
+ game.element('#chat-text').value = 'Autocompleted draft';
+ const focusEvents = [];
+ for (const type of ['blur', 'focus'])
+ game.element('#chat-text').addEventListener(type, () => focusEvents.push(type));
+
+ game.fire('#chat-button', 'touchend');
+
+ assert.deepEqual(focusEvents, ['blur', 'focus']);
+ assert.equal(game.element('#chat-button').textContent, 'Keyboard');
+ assert.equal(game.element('#chat-compose').hidden, false);
+ assert.equal(game.element('#chat-text').value, 'Autocompleted draft');
+ assert.deepEqual(game.characters, []);
+});
+
+test('Firefox Android chat leaves fullscreen with fixed game dimensions and restores it on cancel', async () => {
+ const game = page();
+ const surface = game.element('#game-surface');
+ const fullscreenChanges = [];
+ game.document.fullscreenElement = surface;
+ game.document.exitFullscreen = async () => {
+ fullscreenChanges.push('exit');
+ game.document.fullscreenElement = null;
+ game.window.visualViewport.height = 330;
+ game.document.dispatchEvent(new Event('fullscreenchange'));
+ };
+ surface.requestFullscreen = async () => {
+ fullscreenChanges.push('enter');
+ game.document.fullscreenElement = surface;
+ game.window.visualViewport.height = 390;
+ game.document.dispatchEvent(new Event('fullscreenchange'));
+ };
+
+ game.fire('#chat-button', 'touchend');
+ await Promise.resolve();
+
+ assert.deepEqual(fullscreenChanges, ['exit']);
+ assert.equal(game.document.activeElement, game.element('#chat-text'));
+ assert.equal(surface.style.width, '844px');
+ assert.equal(surface.style.height, '390px');
+ assert.equal(game.element('#chat-compose').style.top, '315px');
+
+ game.fire('#chat-cancel', 'click');
+ await Promise.resolve();
+ await Promise.resolve();
+
+ assert.deepEqual(fullscreenChanges, ['exit', 'enter']);
+ assert.equal(game.document.fullscreenElement, surface);
+ assert.equal(surface.style.width, '');
+ assert.equal(surface.style.height, '');
+ assert.equal(game.element('#chat-button').textContent, 'Chat');
+ assert.equal(game.sizes.every(size => size[0] === 844 && size[1] === 390), true);
+});
+
+test('unsupported chat characters stay editable and are not sent', () => {
+ const game = page();
+ game.fire('#chat-button', 'click');
+ game.element('#chat-text').value = '\ud83d\ude00';
+
+ game.fire('#chat-compose', 'submit');
+
+ assert.deepEqual(game.characters, []);
+ assert.equal(game.element('#chat-compose').hidden, false);
+ assert.match(game.element('#chat-text').validity, /cannot display/);
+});
+
+test('mobile options toggle the native view and return focus to the game', () => {
+ const game = page();
+ game.fire('#menu-button', 'click');
+
+ game.fire('#view-button', 'click');
+
+ assert.deepEqual(game.keys, [[1073741889, true], [1073741889, false]]);
+ assert.equal(game.element('#player-menu').open, false);
+ assert.equal(game.document.activeElement, game.canvas);
+});
+
+test('desktop resolution settings remain available without enabling mobile overlays', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', maxTouchPoints: 10}, saved: 'true'});
+ assert.equal(game.element('#touch-controls').hidden, true);
+
+ const shortcut = new Event('keydown', {cancelable: true});
+ Object.assign(shortcut, {ctrlKey: true, altKey: true, code: 'KeyM'});
+ game.window.dispatchEvent(shortcut);
+ game.element('#pixel-mode').value = 'retina';
+ game.fire('#pixel-mode', 'change');
+ game.fire('#view-button', 'click');
+ game.element('#player-menu').close();
+
+ assert.equal(game.element('#touch-controls').hidden, true);
+ assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#mobile-options').hidden, true);
+ assert.deepEqual(game.keys, []);
+ assert.equal(game.element('#touch-enabled').checked, false);
+ assert.equal(game.element('#touch-enabled').disabled, true);
+ assert.equal(game.storage.get('ao-touch-controls'), 'true');
+ assert.equal(game.storage.get('ao-pixel-mode'), 'retina');
+ assert.deepEqual(game.sizes.at(-1), [1688, 780]);
+ assert.deepEqual(game.hudInsets, [[0, 0], [0, 0], [0, 0]]);
+ assert.equal(page({saved: 'false'}).element('#touch-controls').hidden, true);
+});
+
+test('desktop touch input and saved preferences cannot activate mobile controls', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)', maxTouchPoints: 10}, saved: 'true'});
+ game.element('#touch-enabled').checked = true;
+
+ game.fire('#touch-enabled', 'change');
+ const touch = game.fire('#canvas', 'touchstart');
+ const pointer = game.fire('#canvas', 'pointerdown');
+ game.fire('#canvas', 'pointermove', {clientX: 200});
+ game.fire('#canvas', 'pointerup');
+ game.fire('#chat-button', 'click');
+
+ assert.equal(game.element('#game-toolbar').hidden, true);
+ assert.equal(game.element('#touch-controls').hidden, true);
+ assert.equal(game.element('#chat-compose').hidden, true);
+ assert.equal(touch.defaultPrevented, false);
+ assert.equal(pointer.defaultPrevented, false);
+ assert.deepEqual(game.keys, []);
+ assert.deepEqual(game.mouse, []);
+});
+
+test('desktop viewport changes cannot request chat relocation or shortcut hiding', () => {
+ const game = page({navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64) Gecko Firefox/149.0'}});
+ game.element('#chat-compose').hidden = false;
+ game.window.visualViewport.height = 80;
+ game.window.visualViewport.offsetTop = 25;
+
+ game.window.visualViewport.dispatchEvent(new Event('resize'));
+ game.window.visualViewport.dispatchEvent(new Event('scroll'));
+ game.document.dispatchEvent(new Event('fullscreenchange'));
+
+ assert.deepEqual(game.chatViewports, [0, 0, 0]);
+ assert.equal(game.element('#game-surface').style.top, undefined);
+});
+
+test('iPhone and iPadOS browsers enable the mobile controls', () => {
+ const phone = page({navigator: {userAgent: 'Mozilla/5.0 (iPhone; CPU iPhone OS 18_0 like Mac OS X)'}});
+ const tablet = page({navigator: {userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)', platform: 'MacIntel', maxTouchPoints: 5}});
+ const desktop = page({navigator: {userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15)', platform: 'MacIntel', maxTouchPoints: 0}});
+
+ phone.fire('#canvas', 'pointerdown');
+ tablet.fire('#canvas', 'pointerdown');
+ desktop.fire('#canvas', 'pointerdown');
+
+ assert.equal(phone.element('#game-toolbar').hidden, false);
+ assert.deepEqual(phone.cursorHidden, [true]);
+ assert.equal(phone.element('#touch-controls').hidden, false);
+ assert.equal(tablet.element('#game-toolbar').hidden, false);
+ assert.deepEqual(tablet.cursorHidden, [true]);
+ assert.equal(tablet.element('#touch-controls').hidden, false);
+ assert.equal(desktop.element('#game-toolbar').hidden, true);
+ assert.deepEqual(desktop.cursorHidden, [false]);
+ assert.equal(desktop.element('#touch-controls').hidden, true);
+});
diff --git a/src/tests/browser_fetch.mjs b/src/tests/browser_fetch.mjs
@@ -3,11 +3,11 @@ import fs from 'node:fs';
import vm from 'node:vm';
// Exercise the WasmFS callbacks with small chunks and observable HTTP requests.
-async function fixture(bytes, wholeFile = false, storage, version = '"one"') {
+async function fixture(bytes, wholeFile = false, storage, version = '"one"', chunkSize = 4) {
const requests = [];
const manifests = [];
const warnings = [];
- const heap = new Uint8Array(64);
+ const heap = new Uint8Array(Math.max(64, bytes?.length || 0));
let library;
const context = vm.createContext({
AOProfile: {begin: () => 0, end: () => {}},
@@ -15,7 +15,7 @@ async function fixture(bytes, wholeFile = false, storage, version = '"one"') {
caches: storage, console: {warn: (...args) => warnings.push(args)},
UTF8ToString: value => value,
__wasmfs_fetch_get_file_url: () => 'http://example.test/browser-assets//asset',
- __wasmfs_fetch_get_chunk_size: () => 4,
+ __wasmfs_fetch_get_chunk_size: () => chunkSize,
wasmFS$backends: {}, AOResourcePrefetch: {}, _browser_prefetch_resource_ready: () => {},
addToLibrary: value => { library = value; },
fetch: async (url, options) => {
@@ -248,4 +248,42 @@ async function cachedSmallFileAfterReload() {
}
await cachedSmallFileAfterReload();
-console.log('PASS: browser asset ranges, concurrent reads, persistent chunks, batch revision checks and storage denial');
+
+async function leastRecentlyUsedChunksAreFetchedAgain() {
+ const bytes = new Uint8Array(65 * 1024 * 1024);
+ bytes[0] = 11;
+ bytes[1048576] = 22;
+ const {backend, requests, heap} = await fixture(bytes, false, undefined, undefined, 1048576);
+ for (let index = 0; index < 64; ++index)
+ assert.equal(await backend.read(1, 0, 1, index * 1048576), 1);
+
+ await backend.read(1, 0, 1, 0);
+ await backend.read(1, 0, 1, 67108864);
+ await backend.read(1, 0, 1, 0);
+ assert.equal(heap[0], 11);
+ await backend.read(1, 0, 1, 1048576);
+
+ assert.equal(heap[0], 22);
+ assert.equal(requests.filter(range => range === 'bytes=0-1048575').length, 1);
+ assert.equal(requests.filter(range => range === 'bytes=1048576-2097151').length, 2);
+}
+
+async function readsLargerThanCacheKeepAllBytesUntilCopied() {
+ const bytes = new Uint8Array(66 * 1024 * 1024);
+ bytes[0] = 11;
+ bytes[69206015] = 33;
+ const {backend, requests, heap} = await fixture(bytes, false, undefined, undefined, 1048576);
+
+ const length = await backend.read(1, 0, bytes.length, 0);
+ assert.equal(heap[0], 11);
+ assert.equal(heap[69206015], 33);
+ await backend.read(1, 0, 1, 0);
+
+ assert.equal(length, 69206016);
+ assert.equal(heap[0], 11);
+ assert.deepEqual(requests, ['bytes=0-1048575', 'bytes=1048576-69206015', 'bytes=0-1048575']);
+}
+
+await leastRecentlyUsedChunksAreFetchedAgain();
+await readsLargerThanCacheKeepAllBytesUntilCopied();
+console.log('PASS: browser asset ranges, concurrent reads, persistent chunks, memory eviction, large reads and storage denial');
diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs
@@ -7,7 +7,9 @@ function fixture(response) {
const loading = {hidden: false, set textContent(value) { progress.push(value); }};
const canvas = {addEventListener() {}};
const context = vm.createContext({
- console, WebAssembly, Response, TransformStream,
+ console, WebAssembly, Response, TransformStream, crossOriginIsolated: true,
+ navigator: {userAgent: 'Mozilla/5.0 (X11; Linux x86_64)'},
+ updateTouchControls() {},
localStorage: {getItem() { return null; }},
window: {addEventListener() {}},
document: {querySelector: selector => selector === '#loading' ? loading : canvas},
@@ -17,8 +19,7 @@ function fixture(response) {
}
});
const html = fs.readFileSync(new URL('../browser/index.html', import.meta.url), 'utf8');
- const script = html.slice(html.indexOf('<script>') + 8, html.lastIndexOf('</script>'))
- .replace(' startGame().catch(error => Module.onAbort(error.message));', '');
+ const script = html.match(/<script>([\s\S]*?)<\/script>/)[1];
vm.runInContext(script, context);
return {context, progress, loading};
}
@@ -54,6 +55,26 @@ async function rejectsFailedClientDownload() {
/Client download: HTTP 404/);
}
+async function reportsMissingJspi() {
+ const test = fixture();
+ test.context.WebAssembly = {};
+
+ await test.context.startGame();
+
+ assert.deepEqual(test.progress, ['This game requires WebAssembly JSPI, which this browser does not support']);
+}
+
+async function reportsMissingOffscreenCanvas() {
+ const test = fixture();
+ test.context.WebAssembly = {Suspending() {}};
+
+ await test.context.startGame();
+
+ assert.deepEqual(test.progress, ['This game requires OffscreenCanvas, which this browser does not support']);
+}
+
await streamsDecodedClientAndTracksProgress();
await rejectsFailedClientDownload();
-console.log('PASS: decoded preparation progress, streaming compilation, first frame and download failure');
+await reportsMissingJspi();
+await reportsMissingOffscreenCanvas();
+console.log('PASS: loading progress, streaming compilation, first frame, download failure and missing browser features');
diff --git a/src/tests/browser_resolution.c b/src/tests/browser_resolution.c
@@ -2,6 +2,10 @@
#include <assert.h>
void browser_request_resize(unsigned width, unsigned height);
+void browser_chat_viewport(unsigned bottom);
+void browser_orbit(int x, int y, int active);
+void browser_hud_insets(unsigned right, unsigned top);
+void browser_chat_scroll(int pixels);
void browser_resize_frame(void);
static unsigned calls, width, height, resize_calls;
static int graphics_ready = 1, request_during_resize;
@@ -11,9 +15,129 @@ static float logo_scale_x, logo_scale_y;
static float backdrop_scale_x, backdrop_scale_y;
static unsigned backdrop_positions;
static int caption_x, caption_y;
+static int chat_bounds[10];
+static unsigned chat_updates;
+static unsigned chat_moves;
+static unsigned chat_resizes;
+static unsigned ui_redraws;
+static unsigned toolbar_changes;
+static int touch_regions[10];
+static unsigned touch_count, touch_updates;
+static int touch_width, touch_height;
+static unsigned orbit_updates, orbit_stops;
+static float orbit_x, orbit_y;
+static int chat_scrolled;
+static unsigned chat_background_width, chat_background_height;
+
+static void resize_chat_detector(void)
+{
+ assert(g_ecx == 0x50004b00);
+ uint32_t size = MEM32(g_esp + 4);
+ MEM32(g_ecx + 0x34) = MEM32(g_ecx + 0x2c) + MEM32(size);
+ MEM32(g_ecx + 0x38) = MEM32(g_ecx + 0x30) + MEM32(size + 4);
+ g_esp += 8;
+}
+
+static void scale_chat_background(void)
+{
+ assert(g_ecx == 0x50004900);
+ chat_background_width = *(float *)ADDR(MEM32(g_esp + 4)) * 16;
+ chat_background_height = *(float *)ADDR(MEM32(g_esp + 8)) * 16;
+ g_esp += 12;
+}
+
+static void scroll_chat(void)
+{
+ assert(g_ecx == 0x50003300);
+ chat_scrolled += (int32_t)MEM32(g_esp + 4);
+ g_esp += 8;
+}
+
+static void move_camera(void)
+{
+ assert(g_ecx == 0x50003f00);
+ orbit_x = *(float *)ADDR(g_esp + 4);
+ orbit_y = *(float *)ADDR(g_esp + 8);
+ ++orbit_updates;
+ g_eax = 999;
+ g_st[0] = -1;
+ g_flag_cf = 0;
+ g_esp += 12;
+}
+
+static void stop_camera(void)
+{
+ assert(g_ecx == 0x50003f00);
+ ++orbit_stops;
+ g_esp += 4;
+}
+
+static void invalidate_ui(void)
+{
+ assert(g_ecx == 0 && MEM32(0x27048be4) == 0x50003800);
+ ++ui_redraws;
+ g_esp += 4;
+}
+
+void ao_touch_regions(const int *regions, unsigned count, int screen_width, int screen_height)
+{
+ assert(count <= 2);
+ memcpy(touch_regions, regions, count * 5 * sizeof(int));
+ touch_count = count;
+ touch_width = screen_width;
+ touch_height = screen_height;
+ ++touch_updates;
+}
+
+static void toggle_toolbar(void)
+{
+ assert(g_ecx == 0x50003600);
+ MEM8(g_ecx + 4) = MEM32(g_esp + 4);
+ ++toolbar_changes;
+ g_esp += 8;
+}
+
+void ao_chat_bounds(int x, int y, int width, int height, int screen_width, int screen_height,
+ int output_x, int output_y, int output_width, int output_height)
+{
+ int bounds[] = {x, y, width, height, screen_width, screen_height,
+ output_x, output_y, output_width, output_height};
+ memcpy(chat_bounds, bounds, sizeof(bounds));
+ ++chat_updates;
+}
+
+static void reposition_chat(void)
+{
+ assert(g_ecx == 0x50003100 || g_ecx == 0x50003300);
+ uint32_t window = g_ecx == 0x50003100 ? MEM32(g_ecx) : MEM32(g_ecx + 0x14);
+ uint32_t point = MEM32(g_esp + 4);
+ MEM32(window + 0x2c) = MEM32(point);
+ MEM32(window + 0x30) = MEM32(point + 4);
+ ++chat_moves;
+ g_eax = 1;
+ g_st[0] = -7;
+ g_flag_cf = 0;
+ g_esp += 8;
+}
+
+static void resize_chat(void)
+{
+ assert(g_ecx == 0x50003400 || g_ecx == 0x50003500);
+ uint32_t size = MEM32(g_esp + 4);
+ MEM32(g_ecx + 0x34) = MEM32(size);
+ MEM32(g_ecx + 0x38) = MEM32(size + 4);
+ ++chat_resizes;
+ g_esp += 8;
+}
static void reposition_backdrop(void)
{
+ if (g_ecx == 0x50004100 || g_ecx == 0x50004200) {
+ *(float *)ADDR(g_ecx + 0x18) = MEM32(MEM32(g_esp + 4));
+ *(float *)ADDR(g_ecx + 0x1c) = MEM32(MEM32(g_esp + 4) + 4);
+ g_esp += 8;
+ return;
+ }
assert(g_ecx == 0x50002100);
assert(backdrop_scale_x > 0 && backdrop_scale_y > 0);
assert(MEM32(MEM32(g_esp + 4)) == 0);
@@ -82,6 +206,10 @@ static void panel_one_argument(void)
caption_x = MEM32(MEM32(g_esp + 4));
caption_y = MEM32(MEM32(g_esp + 4) + 4);
}
+ if (g_ecx == 0x50004300 || g_ecx == 0x50004400) {
+ MEM32(g_ecx + 0x2c) = MEM32(MEM32(g_esp + 4));
+ MEM32(g_ecx + 0x30) = MEM32(MEM32(g_esp + 4) + 4);
+ }
g_esp += 8;
}
static void panel_eight_arguments(void) { g_esp += 36; }
@@ -162,6 +290,7 @@ recomp_func_t recomp_lookup(uint32_t address)
case 0x270181e0: return rebuild_panel;
case 0x250af340: return clear_panel;
case 0x27018620: return panel_one_argument;
+ case 5: return panel_one_argument;
case 0x2b03b110: case 0x27018890: case 0x27026160: case 0x270262c0:
return panel_no_arguments;
case 0x27025ec0: return panel_eight_arguments;
@@ -169,6 +298,15 @@ recomp_func_t recomp_lookup(uint32_t address)
case 0x27018b20: return center_logo;
case 3: return scale_backdrop;
case 0x250ae720: return reposition_backdrop;
+ case 0x27015910: case 0x2b004560: return reposition_chat;
+ case 0x27018720: return resize_chat;
+ case 0x2b005220: return scroll_chat;
+ case 7: return scale_chat_background;
+ case 6: return resize_chat_detector;
+ case 0x2701d270: return invalidate_ui;
+ case 0x2b0775b0: return toggle_toolbar;
+ case 0x36020440: return move_camera;
+ case 0x36020470: return stop_camera;
default: abort();
}
}
@@ -179,6 +317,8 @@ int main(void)
assert(guest_map("sprite globals", 0x27040000, 0x10000));
assert(guest_map("sprite imports", 0x27020000, 0x10000));
assert(guest_map("action globals", 0x2b0e0000, 0x10000));
+ assert(guest_map("chat imports", 0x2b0b0000, 0x10000));
+ MEM32(0x2b0b5658) = 7;
assert(guest_map("message globals", 0x20010000, 0x10000));
assert(guest_map("resize objects", 0x50000000, 0x10000));
MEM32(0x25238568) = 0x50000000;
@@ -298,6 +438,316 @@ int main(void)
assert(caption_x == logo_sizes[i].text_x && caption_y == logo_sizes[i].text_y);
assert(g_esp == 0x5000ff00);
}
- puts("Browser resize request, frame boundary, loading logo, and guest state checks passed");
+ MEM32(0x2b0ee6a4) = 0x50003000;
+ MEM32(0x50003008) = 0x50003100;
+ MEM32(0x5000300c) = 0x50003300;
+ MEM32(0x50003314) = 0x50003400;
+ MEM32(0x50003100) = 0x50003200;
+ MEM32(0x5000322c) = 10;
+ MEM32(0x50003230) = 690;
+ MEM32(0x50003234) = 322;
+ MEM32(0x50003238) = 16;
+ MEM32(0x27048be8) = 1024;
+ MEM32(0x27048bec) = 768;
+
+ browser_resize_frame();
+ browser_resize_frame();
+
+ assert(chat_updates == 1);
+ assert(chat_bounds[0] == 11 && chat_bounds[1] == 691);
+ assert(chat_bounds[2] == 320 && chat_bounds[3] == 14);
+ assert(chat_bounds[4] == 1024 && chat_bounds[5] == 768);
+
+ MEM32(0x50003230) = 390;
+ MEM32(0x27048bec) = 468;
+ browser_resize_frame();
+
+ assert(chat_updates == 2 && chat_bounds[1] == 391 && chat_bounds[5] == 468);
+
+ MEM32(0x50003338) = 15;
+ MEM32(0x50003318) = 0x50004b00;
+ MEM32(0x50004b00) = 0x50004a00;
+ MEM32(0x50004a18) = 6;
+ MEM32(0x50003320) = 0x50004900;
+ MEM32(0x50003348) = 322;
+ MEM32(0x5000333c) = 10;
+ MEM32(0x5000334c) = 150;
+ MEM32(0x5000332c) = 30;
+ MEM32(0x50003358) = 20;
+ MEM8(0x50003360) = 1;
+ MEM32(0x5000336c) = 0x50003500;
+ MEM32(0x5000342c) = 10;
+ MEM32(0x50003430) = 540;
+ MEM32(0x50003438) = 150;
+ MEM32(0x50003434) = 322;
+ MEM32(0x50003534) = 11;
+ MEM32(0x50003538) = 150;
+ MEM32(0x50003230) = 690;
+ MEM32(0x27048bec) = 768;
+ MEM32(0x2b0ef034) = 0x50003600;
+ MEM32(0x50003638) = 0x50003900;
+ MEM32(0x5000392c) = 500;
+ MEM32(0x50003930) = 300;
+ MEM32(0x50003934) = 64;
+ MEM32(0x50003938) = 64;
+ MEM32(0x5000365c) = 0x50003700;
+ MEM32(0x5000372c) = 20;
+ MEM32(0x50003730) = 50;
+ MEM32(0x50003734) = 220;
+ MEM32(0x50003738) = 100;
+ MEM32(0x27048be4) = 0x50003800;
+
+ browser_chat_viewport(200);
+ browser_resize_frame();
+ browser_resize_frame();
+
+ assert(MEM32(0x50003230) == 184 && MEM32(0x50003430) == 34);
+ assert(MEM32(0x5000322c) == 20 && MEM32(0x5000342c) == 20);
+ assert(chat_bounds[0] == 21);
+ assert(chat_bounds[1] == 185 && chat_bounds[5] == 768);
+ assert(chat_moves == 2 && resize_calls == 10);
+ assert(MEM32(0x50003238) == 16 && MEM32(0x50003438) == 150);
+ assert(g_eax == 101 && g_st[0] == 123.5 && g_flag_cf == 112);
+ assert(g_esp == 0x5000ff00);
+ assert(MEM8(0x50003604) == 1 && toolbar_changes == 1);
+ assert(ui_redraws == 1);
+
+ browser_chat_viewport(120);
+ browser_resize_frame();
+
+ assert(MEM32(0x50003230) == 104 && MEM32(0x50003430) == 14);
+ assert(MEM32(0x5000322c) == 20 && MEM32(0x5000342c) == 20);
+ assert(MEM32(0x50003438) == 90 && MEM32(0x50003538) == 90);
+ assert(MEM32(0x5000333c) == 6 && MEM32(0x5000334c) == 90);
+ assert(MEM32(0x50003358) == 24 && MEM8(0x50003309) == 1);
+ assert(chat_resizes == 2);
+ assert(MEM8(0x50003604) == 1 && toolbar_changes == 1);
+ assert(chat_moves == 4 && resize_calls == 10);
+ assert(ui_redraws == 2);
+
+ browser_chat_viewport(0);
+ browser_resize_frame();
+ browser_resize_frame();
+
+ assert(MEM32(0x50003230) == 690 && MEM32(0x50003430) == 540);
+ assert(MEM32(0x5000322c) == 10 && MEM32(0x5000342c) == 10);
+ assert(chat_bounds[0] == 11);
+ assert(chat_bounds[1] == 691 && chat_moves == 6 && resize_calls == 10);
+ assert(MEM32(0x50003438) == 150 && MEM32(0x50003538) == 150);
+ assert(MEM32(0x5000333c) == 10 && MEM32(0x5000334c) == 150);
+ assert(MEM32(0x50003358) == 20 && chat_resizes == 4);
+ assert(MEM8(0x50003604) == 0 && toolbar_changes == 2);
+ assert(ui_redraws == 3);
+
+ MEM32(0x50003730) = 174;
+ MEM32(0x50003738) = 224;
+
+ browser_chat_viewport(200);
+ browser_resize_frame();
+
+ assert(MEM8(0x50003604) == 0 && toolbar_changes == 2);
+
+ MEM32(0x50003730) = 173;
+ MEM32(0x50003738) = 223;
+ browser_resize_frame();
+
+ assert(MEM8(0x50003604) == 1 && toolbar_changes == 3);
+
+ MEM32(0x5000372c) = 400;
+ MEM32(0x50003734) = 600;
+ browser_resize_frame();
+
+ assert(MEM8(0x50003604) == 0 && toolbar_changes == 4);
+
+ MEM32(0x5000372c) = 20;
+ MEM32(0x50003734) = 220;
+ MEM8(0x50003604) = 1;
+
+ browser_resize_frame();
+ browser_chat_viewport(0);
+ browser_resize_frame();
+
+ assert(MEM8(0x50003604) == 1 && toolbar_changes == 4);
+
+ MEM32(0x5000322c) = 40;
+ MEM32(0x5000342c) = 60;
+
+ browser_chat_viewport(200);
+ browser_resize_frame();
+ assert(MEM32(0x5000322c) == 40 && MEM32(0x5000342c) == 60);
+ browser_chat_viewport(0);
+ browser_resize_frame();
+
+ assert(MEM32(0x5000322c) == 40 && MEM32(0x5000342c) == 60);
+
+ MEM32(0x27048b7c) = 0x50004000;
+ MEM32(0x50004000) = 0x50004100;
+ MEM8(0x50004004) = 1;
+ MEM32(0x50004104) = 0x50004200;
+ MEM32(0x50004200) = 0x50004300;
+ MEM32(0x50004300) = 0x50004400;
+ MEM32(0x50004308) = 0x50004600;
+ MEM32(0x50004400) = 0x50004500;
+ MEM32(0x50004408) = 0x50004700;
+ MEM32(0x50004500) = 0x50004200;
+ MEM32(0x50004508) = 0x50004800;
+ MEM8(0x50004608) = MEM8(0x50004708) = 1;
+ MEM32(0x5000462c) = 20;
+ MEM32(0x50004630) = 30;
+ MEM32(0x50004634) = 200;
+ MEM32(0x50004638) = 300;
+ MEM32(0x50004734) = 1024;
+ MEM32(0x50004738) = 768;
+ MEM32(MEM32(0x2b0ee640) + 0x10) = 0x50004700;
+ MEM32(0x50003318) = 0x50004600;
+
+ browser_resize_frame();
+ unsigned published = touch_updates;
+ browser_resize_frame();
+
+ int expected[] = {20, 30, 200, 300, 2, 0, 0, 1024, 768, 1};
+ assert(touch_count == 2 && touch_width == 1024 && touch_height == 768);
+ assert(!memcmp(touch_regions, expected, sizeof(expected)));
+ assert(touch_updates == published);
+ assert(g_eax == 101 && g_st[0] == 123.5 && g_flag_cf == 112);
+
+ MEM8(0x50004608) = 0;
+ MEM32(0x50003318) = 0x50004b00;
+ browser_resize_frame();
+
+ assert(touch_count == 1 && touch_regions[4] == 1);
+ assert(touch_updates == published + 1);
+ assert(guest_map("camera interface", 0x2d010000, 0x10000));
+ MEM32(0x2d01752c) = 0x50003f00;
+ uint32_t stack = g_esp;
+
+ browser_orbit(64, -32, 1);
+ browser_orbit(64, -32, 1);
+ browser_resize_frame();
+
+ assert(orbit_updates == 1 && orbit_stops == 0);
+ assert(orbit_x == 0.0009765625f && orbit_y == -0.00048828125f);
+ assert(g_esp == stack && g_eax == 101 && g_st[0] == 123.5 && g_flag_cf == 112);
+
+ browser_resize_frame();
+ browser_orbit(0, 0, 0);
+ browser_resize_frame();
+ browser_resize_frame();
+
+ assert(orbit_updates == 2 && orbit_x == 0 && orbit_y == 0);
+ assert(orbit_stops == 1);
+ assert(g_esp == stack && g_eax == 101 && g_st[0] == 123.5 && g_flag_cf == 112);
+
+ browser_orbit(100, 100, 1);
+ browser_orbit(0, 0, 0);
+ browser_orbit(0, 0, 1);
+ browser_resize_frame();
+ browser_orbit(0, 0, 0);
+ browser_resize_frame();
+
+ assert(orbit_updates == 3 && orbit_x == 0 && orbit_y == 0);
+ assert(orbit_stops == 2);
+
+ MEM32(0x2b0eea5c) = 0x50004000;
+ MEM32(0x500040dc) = 0x50004100;
+ MEM32(0x500040e0) = 0x50004200;
+ MEM32(0x500040e8) = 0x50004300;
+ MEM32(0x500040e4) = 0x50004400;
+ MEM32(0x50004300) = MEM32(0x50004400) = 0x50004500;
+ MEM32(0x50004514) = 5;
+ *(float *)ADDR(0x5000421c) = 144;
+ MEM32(0x50004430) = 144;
+
+ browser_hud_insets(24, 24);
+ browser_resize_frame();
+
+ assert(*(float *)ADDR(0x5000411c) == 24 && *(float *)ADDR(0x5000421c) == 168);
+ assert(MEM32(0x50004330) == 24 && MEM32(0x50004430) == 168);
+ assert(g_esp == stack && g_eax == 101 && g_st[0] == 123.5 && g_flag_cf == 112);
+
+ browser_hud_insets(24, 0);
+ browser_resize_frame();
+
+ assert(*(float *)ADDR(0x5000411c) == 0 && *(float *)ADDR(0x5000421c) == 144);
+ assert(MEM32(0x50004330) == 0 && MEM32(0x50004430) == 144);
+
+ browser_hud_insets(0, 0);
+ browser_resize_frame();
+ *(float *)ADDR(0x5000411c) = 7;
+ browser_resize_frame();
+
+ assert(*(float *)ADDR(0x5000411c) == 7);
+
+ MEM32(0x5000322c) = MEM32(0x5000342c) = 0;
+ MEM32(0x50003230) = 690;
+ MEM32(0x50003430) = 540;
+
+ browser_hud_insets(24, 0);
+ browser_resize_frame();
+ unsigned moves = chat_moves;
+ browser_resize_frame();
+
+ assert(MEM32(0x5000322c) == 12 && MEM32(0x5000342c) == 12);
+ assert(MEM32(0x50003230) == 690 && MEM32(0x50003430) == 540);
+ assert(chat_moves == moves);
+
+ browser_chat_viewport(200);
+ browser_resize_frame();
+
+ assert(MEM32(0x5000322c) == 20 && MEM32(0x5000342c) == 20);
+ assert(MEM32(0x50003230) == 184 && MEM32(0x50003430) == 34);
+
+ browser_chat_viewport(0);
+ browser_resize_frame();
+ browser_hud_insets(48, 0);
+ browser_resize_frame();
+
+ assert(MEM32(0x5000322c) == 24 && MEM32(0x5000342c) == 24);
+ assert(MEM32(0x50003230) == 690 && MEM32(0x50003430) == 540);
+
+ MEM32(0x5000342c) = 80;
+
+ browser_resize_frame();
+ browser_hud_insets(0, 0);
+ browser_resize_frame();
+
+ assert(MEM32(0x5000342c) == 80);
+
+ MEM32(0x5000322c) = MEM32(0x5000342c) = 0;
+
+ browser_resize_frame();
+
+ assert(MEM32(0x5000322c) == 0 && MEM32(0x5000342c) == 0);
+
+ MEM32(0x27048be8) = 320;
+
+ browser_hud_insets(24, 0);
+ browser_resize_frame();
+
+ assert(MEM32(0x5000342c) == 12 && MEM32(0x50003434) == 285);
+ assert(MEM32(0x50003350) == 285 && MEM32(0x50003348) == 285);
+ assert(chat_bounds[6] == 12 && chat_bounds[8] == 285);
+ assert(chat_background_width == 285 && chat_background_height == 150);
+ assert(MEM32(0x50004b34) - MEM32(0x50004b2c) == 285);
+ assert(MEM32(0x5000342c) + MEM32(0x50003434) + 11 == 308);
+
+ MEM32(0x27048be8) = 844;
+ browser_resize_frame();
+ browser_chat_scroll(8);
+ browser_resize_frame();
+ browser_chat_scroll(22);
+ browser_resize_frame();
+
+ assert(MEM32(0x50003434) == 322 && MEM32(0x50003350) == 322);
+ assert(chat_scrolled == -2);
+
+ browser_chat_scroll(-15);
+ browser_resize_frame();
+ browser_hud_insets(0, 0);
+ browser_chat_scroll(60);
+ browser_resize_frame();
+
+ assert(chat_scrolled == -1);
+ puts("Browser resize, guest state, mobile chat, and camera orbit checks passed");
return 0;
}