aorecomp

Anarchy Online classic in the browser

git clone https://aorecomp.ubeagle.com/code/aorecomp.git


server/assets/client/index.html (67645B)


      1 <!doctype html>
      2 <html lang="en">
      3 <meta charset="utf-8">
      4 <base href="__AO_BASE_URL__">
      5 <link rel="icon" href="favicon.ico">
      6 <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover, interactive-widget=resizes-visual">
      7 <title>Anarchy Online 14.9.1</title>
      8 <style>
      9   html, body { margin: 0; width: 100%; height: 100%; overflow: hidden; background: #111; color: #ddd; font: 14px sans-serif; }
     10   @font-face { font-family: GameVerdana; src: url('browser-assets/fonts/verdana.ttf'); }
     11   #game-surface { position: absolute; left: 0; top: 0; width: 100%; height: 100%; }
     12   canvas { display: block; width: 100%; height: 100%; touch-action: none; outline: none; }
     13   #game-surface[data-creation] canvas { position: absolute; left: 50%; top: 50%; transform: translate(-50%, -50%); }
     14   button, select, input { font: inherit; }
     15   button { min-height: 44px; }
     16   #game-toolbar { position: absolute; top: max(24px, env(safe-area-inset-top)); right: max(8px, env(safe-area-inset-right)); display: flex; gap: 8px; }
     17   #game-toolbar button, #touch-controls button { border: 1px solid #aaa8; border-radius: 8px; background: #202428d9; color: #fff; }
     18   #game-toolbar button, #touch-actions button { padding: 8px 12px; }
     19   #touch-controls { position: absolute; inset: 0; pointer-events: none; user-select: none; -webkit-user-select: none; }
     20   #game-toolbar[hidden], #touch-controls[hidden], #chat-compose[hidden], #chat-actions[hidden] { display: none; }
     21   #game-toolbar, #touch-controls { animation: fade-overlays 4s linear forwards; }
     22   #game-surface[data-overlays-active] #game-toolbar, #game-surface[data-overlays-active] #touch-controls { animation: none; opacity: 1; }
     23   #game-toolbar[data-desktop] { top: 0; animation: none; opacity: 1; pointer-events: none; }
     24   #game-toolbar[data-desktop] #menu-button { min-height: 24px; padding: 2px 6px; border-radius: 3px; font-size: 12px; opacity: 0; pointer-events: none; }
     25   #game-toolbar[data-desktop][data-menu-visible] #menu-button, #game-toolbar[data-desktop] #menu-button:focus-visible { opacity: 1; pointer-events: auto; }
     26   @keyframes fade-overlays { from { opacity: 1; } to { opacity: 0; } }
     27   #chat-actions { display: flex; gap: 8px; }
     28   #touch-controls button { pointer-events: auto; touch-action: none; }
     29   #move-pad { position: absolute; bottom: max(64px, calc(env(safe-area-inset-bottom) + 48px)); width: 112px; height: 112px; border-radius: 50% !important; opacity: .5; }
     30   #move-pad[data-active] { opacity: .8; }
     31   #move-pad { left: max(16px, env(safe-area-inset-left)); }
     32   #move-thumb { position: absolute; inset: 36px; border-radius: 50%; background: #ffffff30; pointer-events: none; }
     33   #touch-actions { position: absolute; bottom: max(24px, env(safe-area-inset-bottom)); left: 50%; transform: translateX(-50%); display: flex; gap: 6px; }
     34   #chat-button, #menu-button, #touch-actions button { opacity: .5; }
     35   #chat-button:active, #menu-button:active, #touch-actions button:active { opacity: .8; }
     36   #chat-compose { position: absolute; }
     37   #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; }
     38   #loading, #javascript-required { position: fixed; inset: 0; display: grid; place-items: center; padding: 24px; text-align: center; white-space: pre-line; pointer-events: none; }
     39   #download-progress { position: fixed; top: calc(50% + 36px); left: 50%; transform: translateX(-50%); width: min(320px, 80vw); height: 6px; overflow: hidden; border-radius: 3px; background: #333; pointer-events: none; }
     40   #download-fill { width: 0; height: 100%; background: #9ab9cc; }
     41   #loading[hidden], #download-progress[hidden] { display: none; }
     42   #reconnect { position: fixed; top: calc(50% + 24px); left: 50%; transform: translateX(-50%); padding: 8px 16px; }
     43   /* SDL sets the game cursor inline, even as its final frames finish. */
     44   #game-surface:has(#reconnect:not([hidden])) canvas { cursor: default !important; }
     45   dialog { width: min(320px, calc(100vw - 64px)); max-height: calc(100dvh - 64px); overflow: auto; padding: 24px; border: 1px solid #777; border-radius: 8px; background: #202428; color: #eee; box-shadow: 0 8px 40px #0008; }
     46   dialog::backdrop { background: #0006; }
     47   dialog header { display: flex; align-items: center; justify-content: space-between; gap: 12px; margin-bottom: 16px; }
     48   dialog h1 { margin: 0; font-size: 20px; }
     49   dialog select { display: block; width: 100%; margin: 8px 0; padding: 8px; }
     50   dialog p { color: #bbb; line-height: 1.5; }
     51   dialog button { padding: 8px 16px; cursor: pointer; }
     52   dialog label { display: block; margin: 12px 0; }
     53   #menu-error { color: #ffb0a0; }
     54   #menu-error:empty { display: none; }
     55   #account-panel { margin-top: 20px; border-top: 1px solid #777; }
     56   #account-panel fieldset, #creation-credentials fieldset { border: 0; padding: 0; margin: 0; min-width: 0; }
     57   #account-choices button { display: block; width: 100%; margin: 8px 0; }
     58   #account-choices button[hidden] { display: none; }
     59   #account-form input, #creation-credentials input { box-sizing: border-box; display: block; width: 100%; margin-top: 6px; padding: 8px; }
     60   #creation-credentials { width: min(300px, calc(100vw - 48px)); padding: 12px; }
     61   #creation-credentials h1 { font-size: 18px; }
     62   #creation-credentials label { margin: 8px 0; }
     63   #creation-credentials input { font-size: 16px; margin-top: 3px; padding: 6px; }
     64   #creation-credentials button { min-height: 36px; padding: 6px 14px; }
     65   #creation-actions { display: flex; justify-content: flex-end; margin-top: 10px; }
     66   #creation-error { margin: 8px 0 0; }
     67   #account-form label[hidden] { display: none; }
     68   #account-error, #creation-error { color: #ffb0a0; }
     69   #account-error.success { color: #b9d8b0; }
     70   #account-error:empty, #creation-error:empty { display: none; }
     71 </style>
     72 <noscript><style>#loading { display: none; }</style></noscript>
     73 <div id="game-surface">
     74 <canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
     75 <div id="loading" role="status">Starting Anarchy Online...</div>
     76 <noscript><div id="javascript-required" role="alert">Anarchy Online requires JavaScript. Enable JavaScript in your browser and reload this page.</div></noscript>
     77 <div id="download-progress" role="progressbar" aria-label="Game download" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden><div id="download-fill"></div></div>
     78 <button id="reconnect" hidden>Reconnect</button>
     79 <div id="game-toolbar" hidden>
     80   <div id="chat-actions" hidden>
     81     <button form="chat-compose">Send</button>
     82     <button id="chat-cancel" type="button">Cancel</button>
     83   </div>
     84   <button id="menu-button" aria-label="Options" title="Options (Ctrl+Alt+M)">Opt</button>
     85   <button id="chat-button" disabled>Chat</button>
     86 </div>
     87 <div id="touch-controls" hidden>
     88   <button id="move-pad" aria-label="Move: drag forward, backward or sideways"><span id="move-thumb"></span>Move</button>
     89   <div id="touch-actions">
     90     <button id="autorun-button" aria-pressed="false">Autorun</button>
     91     <button data-key="113">Attack</button>
     92     <button data-key="101">Use</button>
     93     <button data-key="32">Jump</button>
     94   </div>
     95 </div>
     96 <form id="chat-compose" hidden>
     97   <input id="chat-text" aria-label="Chat message" enterkeyhint="send" autocomplete="off" required>
     98 </form>
     99 </div>
    100 <dialog id="player-menu" aria-labelledby="menu-title">
    101   <header>
    102     <h1 id="menu-title">Options</h1>
    103     <form method="dialog"><button>Close</button></form>
    104   </header>
    105   <button id="fullscreen-button">Enter fullscreen</button>
    106   <p id="menu-error" role="status"></p>
    107   <label for="pixel-mode">Resolution</label>
    108   <select id="pixel-mode">
    109     <option value="css">CSS pixels</option>
    110     <option value="retina">Retina pixels</option>
    111   </select>
    112   <output id="render-size"></output>
    113   <p id="desktop-controls">Camera: F8 toggles first/third person. Wheel or - / = (+) zooms.
    114     Shift + arrows (or Shift + wheel) rotates the camera. Shift + 5 resets it;
    115     Shift + 7 saves the preferred angle. Shift + 0 toggles autorun; W stops it.
    116     Numpad controls also work.</p>
    117   <div id="mobile-options" hidden>
    118     <button id="view-button">Toggle 1P / 3P</button>
    119     <label><input id="touch-enabled" type="checkbox"> Touch controls</label>
    120     <p>Left pad: move. Swipe: steer. Two fingers: orbit and pinch to zoom.</p>
    121     <p>Items: tap for menu, double-tap to use/equip, hold to move.
    122       Tap outside the menu to close it. Elsewhere, hold to right-click.</p>
    123   </div>
    124   <section id="account-panel" hidden>
    125     <p id="account-current"></p>
    126     <fieldset id="account-choices">
    127       <button id="create-button" type="button">Create character from scratch</button>
    128       <button id="claim-button" type="button" hidden>Save this character</button>
    129       <button id="password-button" type="button" hidden>Change password</button>
    130       <button id="login-button" type="button">Log in to an existing character</button>
    131     </fieldset>
    132     <form id="account-form" hidden>
    133       <h2 id="account-title"></h2>
    134       <p id="account-description"></p>
    135       <fieldset id="account-fields">
    136         <label>Player name <input id="account-name" name="name" autocomplete="username" maxlength="254" required></label>
    137         <label><span id="account-password-label">Password</span> <input id="account-password" name="password" type="password" autocomplete="current-password" maxlength="1024"></label>
    138         <button id="account-back" type="button">Back</button>
    139         <button id="account-submit" type="submit"></button>
    140       </fieldset>
    141     </form>
    142     <p id="account-error" role="status"></p>
    143   </section>
    144 </dialog>
    145 <dialog id="creation-credentials" aria-labelledby="creation-title">
    146   <h1 id="creation-title">Name your character</h1>
    147   <form id="creation-form">
    148     <fieldset id="creation-fields">
    149       <label>Name <input id="creation-player-name" name="username" autocomplete="username" autocapitalize="none" spellcheck="false" maxlength="12" required></label>
    150       <label>Password <input id="creation-password" name="password" type="password" autocomplete="new-password" minlength="5" maxlength="1024" required></label>
    151       <label>Confirm password <input id="creation-password-confirm" type="password" autocomplete="new-password" minlength="5" maxlength="1024" required></label>
    152       <div id="creation-actions">
    153         <button id="creation-submit" type="submit">OK</button>
    154       </div>
    155     </fieldset>
    156     <p id="creation-error" role="status"></p>
    157   </form>
    158 </dialog>
    159 <script>
    160   const status = document.querySelector('#loading');
    161   const downloadProgress = document.querySelector('#download-progress');
    162   const downloadFill = document.querySelector('#download-fill');
    163   const canvas = document.querySelector('#canvas');
    164   const gameSurface = document.querySelector('#game-surface');
    165   const playerMenu = document.querySelector('#player-menu');
    166   const pixelMode = document.querySelector('#pixel-mode');
    167   // Distinguish iPadOS's desktop Mac user agent by its touch support.
    168   const isMobileBrowser = /Android|iPhone|iPad|iPod/.test(navigator.userAgent) ||
    169     (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1);
    170   pixelMode.value = localStorage.getItem('ao-pixel-mode') === 'retina' ? 'retina' : 'css';
    171   let runtimeReady = false, gameReady = false, restarting = false;
    172   let creatorActive = false, creatorSeen = false;
    173   let sessionReplaced = false;
    174   let accountRequest = false, accountClosed = null;
    175   let recording = null, reportURL = null;
    176   function log(message) {
    177     console.log(message);
    178     if (recording) recording.log += message + '\n';
    179   }
    180   var Module = {
    181     canvas,
    182     print: log,
    183     printErr: log,
    184     onAbort: message => {
    185       downloadProgress.hidden = true;
    186       status.textContent = 'Stopped: ' + message;
    187       status.hidden = false;
    188       console.error(message);
    189     },
    190     onGameClosed: replaced => {
    191       if (accountRequest) { accountClosed = replaced; return; }
    192       if (replaced) {
    193         sessionReplaced = replaced;
    194         document.querySelector('#reconnect').hidden = false;
    195         if (playerMenu.open) playerMenu.close();
    196       }
    197       if (restarting && !replaced) return;
    198       restarting = true;
    199       gameReady = false;
    200       if (sessionReplaced === 'moderated') status.textContent = 'An administrator ended this session.';
    201       else status.textContent = sessionReplaced ? 'This character connected elsewhere.' : 'Starting a new session...';
    202       status.hidden = false;
    203       updateTouchControls();
    204       if (!document.hidden && !sessionReplaced) setTimeout(() => {
    205         if (!sessionReplaced) location.reload();
    206       }, 100);
    207     },
    208     onGraphicsStatus: lost => {
    209       if (restarting) return;
    210       status.textContent = lost ? 'Restoring graphics...' : 'Loading...';
    211       status.hidden = !lost && gameReady;
    212     },
    213     onFirstFrame: () => {
    214       if (restarting) return;
    215       status.hidden = true;
    216       gameReady = true;
    217       document.querySelector('#chat-button').disabled = !isMobileBrowser || !chatBounds;
    218       updateTouchControls();
    219     },
    220     onRuntimeInitialized: () => {
    221       console.log('Client running');
    222       runtimeReady = true;
    223       Module._browser_hide_cursor(isMobileBrowser);
    224       new ResizeObserver(() => { updateResolution(); updateChatViewport(); }).observe(canvas);
    225       updateResolution();
    226       if (!playerMenu.open) canvas.focus();
    227     },
    228     instantiateWasm: (imports, receive) => {
    229       instantiateClient(imports, receive).catch(error => Module.onAbort(error.message));
    230       return {};
    231     }
    232   };
    233   document.querySelector('#reconnect').onclick = () => location.reload();
    234 
    235   // Keep CSS layout fixed while the render worker changes its backing pixels.
    236   function renderSize() {
    237     if (creatorActive) return [1024, 768];
    238     const scale = pixelMode.value === 'retina' ? devicePixelRatio : 1;
    239     return [Math.round(canvas.clientWidth * scale), Math.round(canvas.clientHeight * scale)];
    240   }
    241   function updateResolution() {
    242     if (creatorActive) {
    243       const width = Math.min(gameSurface.clientWidth, gameSurface.clientHeight * 4 / 3);
    244       canvas.style.width = `${width}px`;
    245       canvas.style.height = `${width * 3 / 4}px`;
    246     }
    247     if (!canvas.clientWidth || !canvas.clientHeight) return;
    248     const [width, height] = renderSize();
    249     document.querySelector('#render-size').textContent = `${width} x ${height} pixels`;
    250     if (runtimeReady) {
    251       Module._browser_request_resize(width, height);
    252       const inset = isMobileBrowser ? Math.round(24 * width / canvas.clientWidth) : 0;
    253       Module._browser_hud_insets(inset, document.fullscreenElement ? inset : 0);
    254     }
    255   }
    256   function setCreatorActive(active) {
    257     if (creatorActive === active) return;
    258     creatorActive = active;
    259     if (active) gameSurface.dataset.creation = '';
    260     else {
    261       delete gameSurface.dataset.creation;
    262       canvas.style.width = canvas.style.height = '';
    263     }
    264     updateResolution();
    265   }
    266   pixelMode.onchange = () => {
    267     localStorage.setItem('ao-pixel-mode', pixelMode.value);
    268     updateResolution();
    269     updateChatViewport();
    270   };
    271   window.addEventListener('resize', updateResolution);
    272 
    273   // Move chat above the keyboard while retaining the full game canvas and buffers.
    274   function updateChatViewport() {
    275     if (!canvas.clientWidth || !canvas.clientHeight) return;
    276     const viewport = window.visualViewport;
    277     if (isMobileBrowser && viewport) {
    278       gameSurface.style.left = `${viewport.offsetLeft}px`;
    279       gameSurface.style.top = `${viewport.offsetTop}px`;
    280     }
    281     if (runtimeReady) {
    282       const height = Math.min(canvas.clientHeight, viewport ? viewport.height : canvas.clientHeight);
    283       const scale = renderSize()[1] / canvas.clientHeight;
    284       // Zero disables native chat relocation and shortcut hiding on desktop.
    285       Module._browser_chat_viewport(isMobileBrowser && !chatForm.hidden ? Math.round(height * scale) : 0);
    286     }
    287     positionChat();
    288   }
    289 
    290   // Restore the existing session after a background tab or suspended page returns.
    291   function resumeAudio() {
    292     if (document.hidden) return;
    293     if (Module.audioContext?.state === 'suspended' || Module.audioContext?.state === 'interrupted')
    294       Module.audioContext.resume().catch(error => console.warn('Audio resume deferred until next interaction', error));
    295   }
    296   function resumeGame() {
    297     if (document.hidden) return;
    298     if (restarting) {
    299       if (!sessionReplaced) location.reload();
    300       return;
    301     }
    302     if (!runtimeReady) return;
    303     updateResolution();
    304     updateChatViewport();
    305     resumeAudio();
    306   }
    307 
    308   // One byte-weighted download covers the uncached assets and compressed game binary.
    309   const clientBinaryBytes = Number('11.63') * 1000000;
    310   let clientDownloadBytes = clientBinaryBytes, clientCache = null, cachedClientResponse = null;
    311   let startupAssetBytes = 0, loadedStartupAssetBytes = 0;
    312   function updateDownloadProgress(clientFraction) {
    313     const total = startupAssetBytes + clientDownloadBytes;
    314     if (total === 0) {
    315       downloadProgress.hidden = true;
    316       status.textContent = 'Starting Anarchy Online...';
    317       return;
    318     }
    319     const loaded = loadedStartupAssetBytes + clientDownloadBytes * clientFraction;
    320     const percent = Math.min(100, loaded / total * 100);
    321     status.textContent = `Downloading Anarchy Online...\n${(loaded / 1000000).toFixed(2)} / ${(total / 1000000).toFixed(2)} MB`;
    322     downloadProgress.hidden = false;
    323     downloadFill.style.width = `${percent}%`;
    324     downloadProgress.setAttribute('aria-valuenow', Math.round(percent));
    325   }
    326 
    327   // Decide the binary's download budget before displaying any asset progress.
    328   async function prepareClientDownload() {
    329     clientDownloadBytes = clientBinaryBytes;
    330     clientCache = cachedClientResponse = null;
    331     if (!globalThis.caches) return;
    332     try {
    333       clientCache = await caches.open('ao-asset-chunks-v1');
    334       cachedClientResponse = await clientCache.match(new URL('wasm/game.wasm', document.baseURI).href);
    335     } catch (error) {
    336       console.warn('Client cache unavailable:', error);
    337       clientCache = null;
    338       return;
    339     }
    340     if (!cachedClientResponse) return;
    341     const response = await fetch('wasm/game.wasm', {method: 'HEAD', cache: 'no-store',
    342       headers: {'If-None-Match': cachedClientResponse.headers.get('ETag')}});
    343     if (response.status === 304) {
    344       clientDownloadBytes = 0;
    345     } else {
    346       if (!response.ok) throw new Error(`Client version: HTTP ${response.status}`);
    347       cachedClientResponse = null;
    348     }
    349   }
    350 
    351   // Fetch exposes decoded WASM bytes; scale them to the published compressed size.
    352   async function instantiateClient(imports, receive) {
    353     const response = cachedClientResponse || await fetch('wasm/game.wasm', {cache: 'no-store'});
    354     if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`);
    355     const cacheWrite = !cachedClientResponse && clientCache ?
    356       clientCache.put(new URL('wasm/game.wasm', document.baseURI).href, response.clone())
    357         .catch(error => console.warn('Client cache write failed:', error)) : Promise.resolve();
    358     let binary = response;
    359     if (cachedClientResponse) {
    360       downloadProgress.hidden = true;
    361       status.textContent = 'Starting Anarchy Online...';
    362     } else {
    363       updateDownloadProgress(0);
    364       let loaded = 0;
    365       const progress = new TransformStream({transform(chunk, controller) {
    366         loaded += chunk.byteLength;
    367         updateDownloadProgress(Math.min(1, loaded / Number('97109368')));
    368         controller.enqueue(chunk);
    369       }, flush() {
    370         downloadProgress.hidden = true;
    371         status.textContent = 'Starting Anarchy Online...';
    372       }});
    373       binary = new Response(response.body.pipeThrough(progress), {headers: {'Content-Type': 'application/wasm'}});
    374     }
    375     const result = await WebAssembly.instantiateStreaming(binary, imports);
    376     await cacheWrite;
    377     receive(result.instance, result.module);
    378   }
    379 
    380   // Receive the fixed startup ranges in one stream before the game starts reading assets.
    381   async function preloadStartupAssets() {
    382     startupAssetBytes = loadedStartupAssetBytes = 0;
    383     if (!globalThis.caches) return;
    384     let cache;
    385     try {
    386       cache = await caches.open('ao-asset-chunks-v1');
    387     } catch (error) {
    388       console.warn('Startup asset cache unavailable:', error);
    389       return;
    390     }
    391     // Check cached chunk headers without reading the 185 MiB of cached bodies.
    392     status.textContent = 'Checking game assets...';
    393     const chunkSize = 1048576;
    394     const url = new URL('browser-assets/cd_image/data/db/ResourceDatabase.dat', document.baseURI);
    395     const manifest = await fetch('browser-startup', {method: 'HEAD', cache: 'no-store'});
    396     if (!manifest.ok) throw new Error(`Game assets: HTTP ${manifest.status}`);
    397     Module.startupAssets = {url: url.href, version: manifest.headers.get('X-AO-Asset-Version'),
    398       indices: manifest.headers.get('X-AO-Chunks').split(',').map(Number)};
    399     let cached;
    400     try {
    401       cached = await Promise.all(manifest.headers.get('X-AO-Chunks').split(',').map(async index => {
    402         const chunkURL = new URL(url);
    403         chunkURL.searchParams.set('ao-chunk', `${chunkSize}:${index}`);
    404         const response = await cache.match(chunkURL.href);
    405         return response?.headers.get('ETag') === manifest.headers.get('X-AO-Asset-Version');
    406       }));
    407     } catch (error) {
    408       console.warn('Startup asset cache read failed:', error);
    409       return;
    410     }
    411     if (cached.every(Boolean)) {
    412       status.textContent = 'Starting Anarchy Online...';
    413       return;
    414     }
    415 
    416     const response = await fetch('browser-startup', {cache: 'no-store'});
    417     if (!response.ok) throw new Error(`Game assets: HTTP ${response.status}`);
    418     const reader = response.body.getReader();
    419     try {
    420       const indices = (response.headers.get('X-AO-Chunks') || '').split(',').map(Number);
    421       const version = response.headers.get('X-AO-Asset-Version');
    422       const total = Number(response.headers.get('Content-Length'));
    423       if (!response.headers.get('X-AO-Chunks') || !version || total !== indices.length * chunkSize ||
    424           indices.some((index, i) => !Number.isSafeInteger(index) || index < 0 ||
    425             (i > 0 && index <= indices[i - 1])))
    426         throw new Error('Invalid startup asset manifest');
    427 
    428       // Keep only one assembled chunk in memory, with the same key and ETag as range fetches.
    429       let chunk = new Uint8Array(chunkSize), offset = 0, completed = 0;
    430       startupAssetBytes = total;
    431       updateDownloadProgress(0);
    432       for (;;) {
    433         const {value, done} = await reader.read();
    434         if (done) break;
    435         let cursor = 0;
    436         while (cursor < value.byteLength) {
    437           if (completed === indices.length) throw new Error('Unexpected extra startup asset data');
    438           const count = Math.min(chunkSize - offset, value.byteLength - cursor);
    439           chunk.set(value.subarray(cursor, cursor + count), offset);
    440           offset += count;
    441           cursor += count;
    442           if (offset !== chunkSize) continue;
    443           url.searchParams.set('ao-chunk', `${chunkSize}:${indices[completed]}`);
    444           try {
    445             await cache.put(url.href, new Response(chunk, {headers: {'ETag': version}}));
    446           } catch (error) {
    447             console.warn('Startup asset cache write failed:', error);
    448             startupAssetBytes = loadedStartupAssetBytes;
    449             updateDownloadProgress(0);
    450             return;
    451           }
    452           completed++;
    453           offset = 0;
    454           chunk = new Uint8Array(chunkSize);
    455           loadedStartupAssetBytes = completed * chunkSize;
    456           updateDownloadProgress(0);
    457         }
    458       }
    459       if (completed !== indices.length || offset) throw new Error('Incomplete startup asset download');
    460       console.info('Startup asset chunks cached:', indices);
    461     } finally {
    462       await reader.cancel();
    463     }
    464   }
    465 
    466   // Console capture keeps every frame and input time for inspecting motion glitches.
    467   for (const type of ['keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove']) {
    468     canvas.addEventListener(type, event => {
    469       if (recording) recording.inputs.push({time: performance.timeOrigin + performance.now(), type,
    470         key: event.key, button: event.button, x: event.clientX, y: event.clientY});
    471     });
    472   }
    473   function finishCapture() {
    474     Module._browser_capture_frames(0);
    475     const report = recording;
    476     recording = null;
    477     const data = JSON.stringify(report).replaceAll('<', '\\u003c');
    478     const viewer = `<!doctype html><meta charset="utf-8"><title>AO frame capture</title>
    479 <style>body{background:#111;color:#ddd;font:16px sans-serif}img{max-width:100%}pre{white-space:pre-wrap}</style>
    480 <button id="previous">Previous</button> <button id="next">Next</button>
    481 <input id="frame" aria-label="Frame" type="range" min="0" max="${report.frames.length - 1}" value="0">
    482 <span id="label"></span><br><img id="image"><details><summary>Capture details</summary><pre id="details"></pre></details>
    483 <script type="application/json" id="data">${data}<\/script>
    484 <script>
    485 const report=JSON.parse(document.querySelector('#data').textContent);
    486 const slider=document.querySelector('#frame');
    487 function show() {
    488   const index = Number(slider.value), frame = report.frames[index];
    489   document.querySelector('#image').src = frame.png;
    490   document.querySelector('#label').textContent = (index+1)+' / '+report.frames.length+
    491     ' at '+(frame.time-report.frames[0].time).toFixed(1)+' ms';
    492 }
    493 slider.oninput=show;
    494 document.querySelector('#previous').onclick=()=>{slider.stepDown();show();};
    495 document.querySelector('#next').onclick=()=>{slider.stepUp();show();};
    496 document.onkeydown = event => {
    497   if (event.key === 'ArrowLeft') slider.stepDown();
    498   else if (event.key === 'ArrowRight') slider.stepUp();
    499   else return;
    500   event.preventDefault();
    501   show();
    502 };
    503 const {frames, ...metadata} = report;
    504 document.querySelector('#details').textContent = JSON.stringify(metadata, null, 2);
    505 show();
    506 <\/script>`;
    507     reportURL = URL.createObjectURL(new Blob([viewer], {type: 'text/html'}));
    508     console.log(`Captured ${report.frames.length} frames. Open this report:`, reportURL);
    509   }
    510   Module.captureFrames = count => {
    511     if (!Number.isInteger(count) || count < 1 || count > 120)
    512       throw new RangeError('Capture requires 1-120 frames');
    513     if (recording) throw new Error('A frame capture is already running');
    514     if (reportURL) URL.revokeObjectURL(reportURL);
    515     recording = {requested: count, started: new Date().toISOString(),
    516       userAgent: navigator.userAgent, inputs: [], frames: [], log: ''};
    517     console.log(`Recording ${count} frames; this slows rendering`);
    518     Module._browser_capture_frames(count);
    519     canvas.focus();
    520   };
    521   Module.captureFrame = (pixels, width, height, time) => {
    522     if (!recording) return;
    523     const image = new ImageData(width, height);
    524     for (let row = 0; row < height; ++row)
    525       image.data.set(pixels.subarray(row * width * 4, (row + 1) * width * 4), (height - row - 1) * width * 4);
    526     const frame = document.createElement('canvas');
    527     frame.width = width; frame.height = height;
    528     frame.getContext('2d').putImageData(image, 0, 0);
    529     recording.frames.push({time, png: frame.toDataURL('image/png')});
    530     if (recording.frames.length === recording.requested) finishCapture();
    531   };
    532   async function startGame() {
    533     if (!crossOriginIsolated) { status.textContent = 'Shared memory is unavailable'; return; }
    534     // Consume the one-time launch intent before any asynchronous loading begins.
    535     const launchURL = new URL(location.href);
    536     const creating = launchURL.searchParams.get('create') === '1';
    537     setCreatorActive(creating);
    538     launchURL.searchParams.delete('create');
    539     history.replaceState(null, '', launchURL);
    540     // Some browsers expose OffscreenCanvas without supporting WebGL in workers.
    541     let workerGraphics = false;
    542     if (canvas.transferControlToOffscreen) {
    543       const probeURL = URL.createObjectURL(new Blob([
    544         "postMessage(!!new OffscreenCanvas(1, 1).getContext('webgl2', {alpha: false, antialias: false}));"
    545       ], {type: 'text/javascript'}));
    546       const probe = new Worker(probeURL);
    547       try {
    548         workerGraphics = await new Promise((resolve, reject) => {
    549           probe.onmessage = event => resolve(event.data);
    550           probe.onerror = event => reject(new Error(event.message));
    551         });
    552       } finally {
    553         probe.terminate();
    554         URL.revokeObjectURL(probeURL);
    555       }
    556     }
    557     if (!workerGraphics) {
    558       // Context attributes are fixed by the first call; match Emscripten's framebuffer forwarding.
    559       if (!canvas.getContext('webgl2', {alpha: false, antialias: false, preserveDrawingBuffer: true})) {
    560         status.textContent = 'This browser could not initialize WebGL 2. Check graphics settings or try another browser.';
    561         return;
    562       }
    563       // Keep this canvas on the page when Emscripten starts the game worker.
    564       canvas.transferControlToOffscreen = undefined;
    565     }
    566     Module.audioContext = new AudioContext();
    567     // Touch activation arrives on release; retry after a premature pointerdown resume.
    568     for (const type of ['pointerdown', 'pointerup', 'touchend', 'keydown']) {
    569       document.addEventListener(type, resumeAudio, true);
    570     }
    571     status.textContent = 'Starting Anarchy Online...';
    572     const response = await fetch('browser-launch' + (creating ? '?create=1' : ''), {method: 'POST'});
    573     if (!response.ok) { status.textContent = await response.text(); return; }
    574     Module.arguments = (await response.text()).trim().split(' ').slice(1);
    575     Module.worldPort = Number(response.headers.get('X-AO-World-Port')) || Number(Module.arguments.at(-3));
    576     // The render worker owns the backing canvas after startup.
    577     [canvas.width, canvas.height] = renderSize();
    578     await prepareClientDownload();
    579     await preloadStartupAssets();
    580     // Keep the script available when later pthreads start during a server outage.
    581     const clientScript = await fetch('wasm/game.js');
    582     if (!clientScript.ok) throw new Error(`Client script: HTTP ${clientScript.status}`);
    583     const script = document.createElement('script');
    584     script.src = URL.createObjectURL(await clientScript.blob());
    585     script.onerror = () => { status.textContent = 'Could not load the client'; };
    586     document.body.append(script);
    587   }
    588 </script>
    589 <script id="player-controls">
    590   const touchEnabled = document.querySelector('#touch-enabled');
    591   const touchControls = document.querySelector('#touch-controls');
    592   const chatForm = document.querySelector('#chat-compose');
    593   const chatText = document.querySelector('#chat-text');
    594   const chatActions = document.querySelector('#chat-actions');
    595   const creationDialog = document.querySelector('#creation-credentials');
    596   const creationFields = document.querySelector('#creation-fields');
    597   const creationError = document.querySelector('#creation-error');
    598   let creationSubmitted = false;
    599   Module.onCreationState = state => {
    600     creatorSeen ||= state.active;
    601     if (creatorSeen) {
    602       if (creatorActive && !state.active) Module.loadAccount();
    603       setCreatorActive(state.active);
    604     }
    605     if (creationSubmitted && (!state.name || !state.active) && creationDialog.open) {
    606       creationDialog.close();
    607       canvas.focus();
    608     }
    609     if (state.name && !creationSubmitted && !creationDialog.open) {
    610       releaseControls();
    611       creationDialog.showModal();
    612       // Firefox Android needs to leave fullscreen before opening its keyboard.
    613       if (document.fullscreenElement && /Android.*Firefox\//.test(navigator.userAgent)) {
    614         document.exitFullscreen().then(() => document.querySelector('#creation-player-name').focus()).catch(error => {
    615           creationError.textContent = 'Fullscreen is unavailable: ' + error.message;
    616         });
    617       }
    618     }
    619   };
    620   creationDialog.addEventListener('cancel', event => event.preventDefault());
    621   document.querySelector('#creation-form').onsubmit = async event => {
    622     event.preventDefault();
    623     if (creationFields.disabled || creationSubmitted) return;
    624     if (Array.from(document.querySelector('#creation-password').value).length < 5) {
    625       creationError.textContent = 'Use a password of at least 5 characters.';
    626       document.querySelector('#creation-password').focus();
    627       return;
    628     }
    629     if (document.querySelector('#creation-password').value !== document.querySelector('#creation-password-confirm').value) {
    630       creationError.textContent = 'Passwords do not match.';
    631       document.querySelector('#creation-password-confirm').focus();
    632       return;
    633     }
    634     creationFields.disabled = true;
    635     creationError.textContent = '';
    636     const values = new URLSearchParams({name: document.querySelector('#creation-player-name').value,
    637       password: document.querySelector('#creation-password').value});
    638     try {
    639       const response = await fetch('browser-create', {method: 'POST', body: values});
    640       if (response.ok) {
    641         creationSubmitted = true;
    642         document.querySelector('#creation-password').value = '';
    643         document.querySelector('#creation-password-confirm').value = '';
    644         Module.finishCreation(response.headers.get('X-AO-Creation-Name'));
    645         return;
    646       }
    647       creationError.textContent = await response.text();
    648     } catch (error) {
    649       creationError.textContent = 'Could not contact the server. Please try again.';
    650     }
    651     creationFields.disabled = false;
    652   };
    653   const movePad = document.querySelector('#move-pad');
    654   const autorunButton = document.querySelector('#autorun-button');
    655   const gameToolbar = document.querySelector('#game-toolbar');
    656   const menuButton = document.querySelector('#menu-button');
    657   let menuPointer = null;
    658   if (!isMobileBrowser) gameToolbar.dataset.desktop = '';
    659   document.querySelector('#chat-button').hidden = !isMobileBrowser;
    660   const heldKeys = new Set();
    661   const overlayTouches = new Set();
    662   let canvasTouch = null, moveTouch = null;
    663   let itemMenu = null;
    664   let touchFrame = 0;
    665   let canvasTouchInput = false;
    666   let orbitTouch = null, autoRun = false, moveForward = false;
    667   let touchRegions = null;
    668   let chatBounds = null;
    669   let chatFullscreen = null, chatComposing = false;
    670   Module.onChatBounds = bounds => {
    671     chatBounds = bounds;
    672     document.querySelector('#chat-button').disabled = !isMobileBrowser || !gameReady;
    673     positionChat();
    674   };
    675   Module.onTouchRegions = bounds => {
    676     touchRegions = bounds;
    677     if (itemMenu && bounds.itemMenu) {
    678       itemMenu.ready = true;
    679     } else if (itemMenu?.ready) cancelItemMenu();
    680     updateTouchControls();
    681   };
    682   Module.onTouchFrame = request => {
    683     if (!itemMenu || itemMenu.request !== request) return;
    684     mouse('mousedown', itemMenu.x, itemMenu.y, 2);
    685     itemMenu.pressed = true;
    686     if (itemMenu.use) {
    687       mouse('mouseup', itemMenu.x, itemMenu.y, 2);
    688       itemMenu = null;
    689     }
    690   };
    691   const savedTouchMode = localStorage.getItem('ao-touch-controls');
    692   touchEnabled.checked = isMobileBrowser && savedTouchMode !== 'false';
    693   touchEnabled.disabled = !isMobileBrowser;
    694   document.querySelector('#mobile-options').hidden = !isMobileBrowser;
    695   document.querySelector('#desktop-controls').hidden = isMobileBrowser;
    696   if (isMobileBrowser) menuButton.title = 'Options';
    697 
    698   // Queue virtual keys through SDL, including releases before focus changes.
    699   function setKey(key, down) {
    700     if (!gameReady || heldKeys.has(key) === down) return;
    701     Module._browser_input_key(key, down, false, 0);
    702     if (down) heldKeys.add(key);
    703     else heldKeys.delete(key);
    704   }
    705   function pressKey(key) {
    706     setKey(key, true);
    707     setKey(key, false);
    708   }
    709   function mouse(type, x, y, button = 0) {
    710     const bounds = canvas.getBoundingClientRect();
    711     const [width, height] = renderSize();
    712     x = Math.round((x - bounds.left) * width / bounds.width);
    713     y = Math.round((y - bounds.top) * height / bounds.height);
    714     if (type === 'mousemove') Module._browser_input_motion(x, y);
    715     else Module._browser_input_button(button === 2 ? 3 : 1, type === 'mousedown', x, y);
    716   }
    717   function touchRegion(x, y) {
    718     if (!touchRegions) return;
    719     const bounds = canvas.getBoundingClientRect();
    720     x = (x - bounds.left) * touchRegions.screenWidth / bounds.width;
    721     y = (y - bounds.top) * touchRegions.screenHeight / bounds.height;
    722     const regions = touchRegions.regions.filter(region =>
    723       x >= region.left && x < region.right && y >= region.top && y < region.bottom);
    724     // Window detectors set input modes without taking the hit from their item icons.
    725     if (regions[0]?.detector)
    726       return {...regions[0], item: regions.find(region => !region.detector)?.item === true};
    727     return regions[0];
    728   }
    729   // Route camera motion separately from native UI scrolling; neither needs a click.
    730   canvas.addEventListener('wheel', event => {
    731     if (!gameReady) return;
    732     event.preventDefault();
    733     event.stopImmediatePropagation();
    734     const bounds = canvas.getBoundingClientRect();
    735     const [width, height] = renderSize();
    736     let scale;
    737     if (event.deltaMode === 0) scale = 0.01;
    738     else if (event.deltaMode === 1) scale = 1 / 3;
    739     else scale = 80;
    740     if (touchRegion(event.clientX, event.clientY)?.world === true) {
    741       if (event.shiftKey)
    742         Module._browser_camera_wheel(Math.round(event.deltaX * scale * 100 / bounds.width * 65536),
    743                                      Math.round(event.deltaY * scale * 100 / bounds.height * 65536));
    744       else Module._browser_zoom(Math.round(event.deltaY * scale * 0.15 * 65536));
    745     } else {
    746       Module._browser_input_wheel(Math.round((event.clientX - bounds.left) * width / bounds.width),
    747                                   Math.round((event.clientY - bounds.top) * height / bounds.height),
    748                                   -event.deltaY * scale);
    749     }
    750   }, {capture: true, passive: false});
    751   function finishCanvasTouch() {
    752     if (!canvasTouch) return;
    753     clearTimeout(canvasTouch.timer);
    754     if (canvasTouch.button !== null)
    755       mouse('mouseup', canvasTouch.x, canvasTouch.y, canvasTouch.button);
    756     canvasTouch = null;
    757   }
    758   function cancelItemMenu() {
    759     if (!itemMenu) return;
    760     clearTimeout(itemMenu.timer);
    761     // Release away from all native hotspots, including while the hold menu is pending.
    762     if (itemMenu.pressed) {
    763       mouse('mousemove', -1, -1);
    764       mouse('mouseup', -1, -1, 2);
    765     }
    766     itemMenu = null;
    767   }
    768   function finishOrbit() {
    769     if (!orbitTouch || orbitTouch.points.size !== 2) return;
    770     Module._browser_orbit(0, 0, 0);
    771   }
    772   function setAutoRun(active) {
    773     autoRun = active;
    774     autorunButton.textContent = active ? 'Stop' : 'Autorun';
    775     autorunButton.ariaPressed = String(active);
    776     setKey(119, autoRun || moveForward);
    777   }
    778   function releaseControls() {
    779     if (canvasTouch?.menu) canvasTouch.button = null;
    780     cancelItemMenu();
    781     finishCanvasTouch();
    782     if (gameReady) Module._browser_orbit(0, 0, 0);
    783     orbitTouch = null;
    784     moveForward = false;
    785     for (const key of heldKeys) setKey(key, false);
    786     setAutoRun(false);
    787     moveTouch = null;
    788     delete movePad.dataset.active;
    789     document.querySelector('#move-thumb').style.transform = '';
    790     overlayTouches.clear();
    791     updateTouchControls();
    792   }
    793   function updateTouchControls() {
    794     const ready = gameReady && touchRegions?.regions.some(region => region.world);
    795     gameToolbar.hidden = !ready;
    796     touchControls.hidden = !isMobileBrowser || !ready || !touchEnabled.checked || playerMenu.open || !chatForm.hidden;
    797     if (!isMobileBrowser && touchRegions) {
    798       // Anchor to the current screen edge; native resize retains older hit rectangles.
    799       let left = touchRegions.screenWidth;
    800       for (const region of touchRegions.regions) {
    801         if (!region.world && !region.chat && region.top <= 0 && region.bottom > 0 &&
    802             region.left > 0 && region.right === touchRegions.screenWidth)
    803           left = Math.min(left, region.left);
    804       }
    805       gameToolbar.style.right = `${(touchRegions.screenWidth - left) * canvas.clientWidth / touchRegions.screenWidth + 6}px`;
    806       updateMenuVisibility();
    807     }
    808     if (overlayTouches.size || playerMenu.open || !chatForm.hidden) gameSurface.dataset.overlaysActive = '';
    809     else delete gameSurface.dataset.overlaysActive;
    810   }
    811   function updateMenuVisibility() {
    812     if (isMobileBrowser) return;
    813     const bounds = menuButton.getBoundingClientRect();
    814     const distance = menuPointer ? Math.hypot(Math.max(bounds.left - menuPointer[0], 0, menuPointer[0] - bounds.right),
    815       Math.max(bounds.top - menuPointer[1], 0, menuPointer[1] - bounds.bottom)) : Infinity;
    816     if (playerMenu.open || distance <= 150) gameToolbar.dataset.menuVisible = '';
    817     else delete gameToolbar.dataset.menuVisible;
    818   }
    819   document.addEventListener('pointermove', event => {
    820     if (event.pointerType !== 'mouse') return;
    821     menuPointer = [event.clientX, event.clientY];
    822     updateMenuVisibility();
    823   }, true);
    824   document.addEventListener('pointerleave', () => { menuPointer = null; updateMenuVisibility(); });
    825   window.addEventListener('blur', () => { menuPointer = null; updateMenuVisibility(); });
    826   // Reveal before canvas handlers consume the gesture; fade after the last finger lifts.
    827   document.addEventListener('pointerdown', event => {
    828     if (!isMobileBrowser || event.pointerType === 'mouse') return;
    829     overlayTouches.add(event.pointerId);
    830     updateTouchControls();
    831   }, true);
    832   for (const type of ['pointerup', 'pointercancel']) {
    833     document.addEventListener(type, event => {
    834       overlayTouches.delete(event.pointerId);
    835       updateTouchControls();
    836     }, true);
    837   }
    838   touchEnabled.onchange = () => {
    839     releaseControls();
    840     localStorage.setItem('ao-touch-controls', touchEnabled.checked);
    841     updateTouchControls();
    842   };
    843   touchControls.addEventListener('contextmenu', event => event.preventDefault());
    844 
    845   // Anchor camera gestures above the character and clear of native windows.
    846   function cameraAnchor(startX, startY) {
    847     const bounds = canvas.getBoundingClientRect();
    848     const y = bounds.top + bounds.height / 4;
    849     for (const x of [bounds.left + bounds.width / 2, startX])
    850       if (touchRegion(x, y)?.world === true) return [x, y];
    851     return [startX, startY];
    852   }
    853 
    854   // Own canvas touches so SDL and browser compatibility events cannot click twice.
    855   for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
    856     canvas.addEventListener(type, event => {
    857       if (!isMobileBrowser) return;
    858       event.preventDefault();
    859       event.stopImmediatePropagation();
    860     }, {capture: true, passive: false});
    861   }
    862   for (const type of ['mousedown', 'mouseup', 'mousemove']) {
    863     canvas.addEventListener(type, event => {
    864       // Touch compatibility events can omit sourceCapabilities; track their pointer source.
    865       if (isMobileBrowser && (canvasTouchInput || event.sourceCapabilities?.firesTouchEvents))
    866         event.stopImmediatePropagation();
    867     }, true);
    868   }
    869   canvas.addEventListener('pointerdown', event => {
    870     if (!isMobileBrowser) return;
    871     if (event.pointerType === 'mouse') {
    872       if (!canvasTouch && !orbitTouch) canvasTouchInput = false;
    873       return;
    874     }
    875     canvasTouchInput = true;
    876     // Cancelling pointerdown can suppress other fingers in Firefox. CSS owns touch gestures.
    877     event.stopImmediatePropagation();
    878     if (!gameReady || orbitTouch || playerMenu.open) return;
    879     const doubleTap = !canvasTouch && itemMenu?.timer &&
    880       Math.hypot(event.clientX - itemMenu.x, event.clientY - itemMenu.y) <= 20;
    881     if (doubleTap) cancelItemMenu();
    882     if (itemMenu && !itemMenu.ready) { cancelItemMenu(); return; }
    883     const region = touchRegion(event.clientX, event.clientY);
    884     const bounds = canvas.getBoundingClientRect();
    885     const history = chatBounds?.history;
    886     const x = (event.clientX - bounds.left) * chatBounds?.screenWidth / bounds.width;
    887     const y = (event.clientY - bounds.top) * chatBounds?.screenHeight / bounds.height;
    888     if (!canvasTouch && region?.chat && history &&
    889         x >= history.x && x < history.x + history.width && y >= history.y && y < history.y + history.height) {
    890       event.preventDefault();
    891       canvas.setPointerCapture(event.pointerId);
    892       canvasTouch = {id: event.pointerId, chat: true, y: event.clientY, button: null};
    893       return;
    894     }
    895     if (!chatForm.hidden) return;
    896     if (canvasTouch) {
    897       if (!canvasTouch.camera || touchRegion(event.clientX, event.clientY)?.world !== true) return;
    898       const first = {x: canvasTouch.x - canvasTouch.offsetX, y: canvasTouch.y - canvasTouch.offsetY};
    899       const points = new Map([[canvasTouch.id, first], [event.pointerId, {x: event.clientX, y: event.clientY}]]);
    900       finishCanvasTouch();
    901       canvas.setPointerCapture(event.pointerId);
    902       orbitTouch = {points, distance: Math.hypot(first.x - event.clientX, first.y - event.clientY)};
    903       Module._browser_orbit(0, 0, 1);
    904       return;
    905     }
    906     canvas.focus();
    907     canvas.setPointerCapture(event.pointerId);
    908     canvasTouch = {id: event.pointerId, x: event.clientX, y: event.clientY,
    909       startX: event.clientX, startY: event.clientY, offsetX: 0, offsetY: 0, button: null,
    910       item: region?.item === true, menu: !!itemMenu, doubleTap: !!doubleTap,
    911       camera: touchEnabled.checked && touchRegion(event.clientX, event.clientY)?.world === true};
    912     mouse('mousemove', event.clientX, event.clientY);
    913     if (itemMenu) { canvasTouch.button = 2; return; }
    914     canvasTouch.timer = setTimeout(() => {
    915       if (canvasTouch.item) {
    916         // Native inventory pickup completes on a click, even while the finger stays down.
    917         mouse('mousedown', canvasTouch.startX, canvasTouch.startY);
    918         mouse('mouseup', canvasTouch.startX, canvasTouch.startY);
    919         canvasTouch.picked = true;
    920       } else {
    921         canvasTouch.button = 2;
    922         mouse('mousedown', canvasTouch.x, canvasTouch.y, 2);
    923       }
    924     }, 450);
    925   }, true);
    926   canvas.addEventListener('pointermove', event => {
    927     if (event.pointerType === 'mouse' && !canvasTouch && !orbitTouch) canvasTouchInput = false;
    928     if (orbitTouch) {
    929       const point = orbitTouch.points.get(event.pointerId);
    930       if (!point || orbitTouch.points.size !== 2) return;
    931       // Half of each finger's movement, at 35% sensitivity, in viewport fractions.
    932       const bounds = canvas.getBoundingClientRect();
    933       Module._browser_orbit(Math.round((event.clientX - point.x) / bounds.width * 32768 * .35),
    934         Math.round((event.clientY - point.y) / bounds.height * 32768 * .35), 1);
    935       point.x = event.clientX;
    936       point.y = event.clientY;
    937 
    938       // Finger separation controls zoom while their midpoint controls orbit.
    939       const [first, second] = orbitTouch.points.values();
    940       const distance = Math.hypot(first.x - second.x, first.y - second.y);
    941       if (orbitTouch.distance > 0 && distance > 0) {
    942         const zoom = Math.round(Math.log(orbitTouch.distance / distance) * 65536);
    943         if (zoom) Module._browser_zoom(zoom);
    944       }
    945       orbitTouch.distance = distance;
    946       return;
    947     }
    948     if (!canvasTouch || event.pointerId !== canvasTouch.id) return;
    949     if (canvasTouch.chat) {
    950       const bounds = canvas.getBoundingClientRect();
    951       const pixels = Math.round((event.clientY - canvasTouch.y) * chatBounds.screenHeight / bounds.height);
    952       if (pixels) {
    953         Module._browser_chat_scroll(pixels);
    954         canvasTouch.y += pixels * bounds.height / chatBounds.screenHeight;
    955       }
    956       return;
    957     }
    958     if (canvasTouch.button === null && !canvasTouch.picked &&
    959         Math.hypot(event.clientX - canvasTouch.startX, event.clientY - canvasTouch.startY) > 8) {
    960       clearTimeout(canvasTouch.timer);
    961       // Moving before the hold threshold cancels an item gesture instead of picking it up.
    962       if (canvasTouch.item) { canvasTouch.cancel = true; return; }
    963       canvasTouch.button = canvasTouch.camera ? 2 : 0;
    964       if (canvasTouch.camera) {
    965         const [x, y] = cameraAnchor(canvasTouch.startX, canvasTouch.startY);
    966         canvasTouch.offsetX = x - canvasTouch.startX;
    967         canvasTouch.offsetY = y - canvasTouch.startY;
    968         mouse('mousemove', canvasTouch.startX + canvasTouch.offsetX, canvasTouch.startY + canvasTouch.offsetY);
    969       }
    970       mouse('mousedown', canvasTouch.startX + canvasTouch.offsetX, canvasTouch.startY + canvasTouch.offsetY, canvasTouch.button);
    971     }
    972     canvasTouch.x = event.clientX + canvasTouch.offsetX;
    973     canvasTouch.y = event.clientY + canvasTouch.offsetY;
    974     mouse('mousemove', canvasTouch.x, canvasTouch.y, canvasTouch.button ?? 0);
    975   });
    976   canvas.addEventListener('pointerup', event => {
    977     if (orbitTouch) return;
    978     if (!canvasTouch || event.pointerId !== canvasTouch.id) return;
    979     if (canvasTouch.chat) { finishCanvasTouch(); return; }
    980     if (canvasTouch.cancel) { finishCanvasTouch(); return; }
    981     canvasTouch.x = event.clientX + canvasTouch.offsetX;
    982     canvasTouch.y = event.clientY + canvasTouch.offsetY;
    983     mouse('mousemove', canvasTouch.x, canvasTouch.y);
    984     if (canvasTouch.picked) {
    985       if (Math.hypot(event.clientX - canvasTouch.startX, event.clientY - canvasTouch.startY) > 8) {
    986         canvasTouch.button = 0;
    987         mouse('mousedown', event.clientX, event.clientY);
    988       }
    989     } else if (canvasTouch.button === null) {
    990       if (canvasTouch.item) {
    991         itemMenu = {ready: false, request: ++touchFrame, x: event.clientX, y: event.clientY,
    992           use: canvasTouch.doubleTap};
    993         if (itemMenu.use) Module._browser_touch_frame(itemMenu.request);
    994         else {
    995           // Give a second tap time to choose the native default action before opening the menu.
    996           itemMenu.timer = setTimeout(() => {
    997             itemMenu.timer = null;
    998             Module._browser_touch_frame(itemMenu.request);
    999           }, 300);
   1000         }
   1001       } else {
   1002         canvasTouch.button = 0;
   1003         mouse('mousedown', event.clientX, event.clientY);
   1004       }
   1005     }
   1006     if (canvasTouch.menu) itemMenu = null;
   1007     finishCanvasTouch();
   1008   });
   1009   for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) {
   1010     canvas.addEventListener(type, event => {
   1011       if (orbitTouch?.points.has(event.pointerId)) {
   1012         finishOrbit();
   1013         orbitTouch.points.delete(event.pointerId);
   1014         if (!orbitTouch.points.size) orbitTouch = null;
   1015       }
   1016       if (event.pointerId === canvasTouch?.id) {
   1017         if (canvasTouch.menu) { canvasTouch.button = null; cancelItemMenu(); }
   1018         finishCanvasTouch();
   1019       }
   1020     });
   1021   }
   1022 
   1023   // Track the movement thumb independently of world swipes and UI dragging.
   1024   movePad.onpointerdown = event => {
   1025     if (moveTouch !== null) return;
   1026     movePad.setPointerCapture(event.pointerId);
   1027     moveTouch = event.pointerId;
   1028     movePad.dataset.active = '';
   1029     movePad.onpointermove(event);
   1030   };
   1031   movePad.onpointermove = event => {
   1032     if (event.pointerId !== moveTouch) return;
   1033     const bounds = movePad.getBoundingClientRect();
   1034     const x = event.clientX - bounds.left - bounds.width / 2;
   1035     const y = event.clientY - bounds.top - bounds.height / 2;
   1036     // The original game uses Z/C for strafing and W/S for forward/backward.
   1037     setKey(122, x < -16);
   1038     setKey(99, x > 16);
   1039     moveForward = y < -16;
   1040     if (y > 16) setAutoRun(false);
   1041     setKey(119, autoRun || moveForward);
   1042     setKey(115, y > 16);
   1043     const scale = Math.min(1, 36 / Math.hypot(x, y));
   1044     document.querySelector('#move-thumb').style.transform = `translate(${x * scale}px, ${y * scale}px)`;
   1045   };
   1046   const releaseMove = event => {
   1047     if (event.pointerId !== moveTouch) return;
   1048     moveTouch = null;
   1049     moveForward = false;
   1050     delete movePad.dataset.active;
   1051     for (const key of [122, 99, 115]) setKey(key, false);
   1052     setKey(119, autoRun);
   1053     document.querySelector('#move-thumb').style.transform = '';
   1054   };
   1055   for (const type of ['pointerup', 'pointercancel', 'lostpointercapture']) movePad.addEventListener(type, releaseMove);
   1056   autorunButton.onpointerdown = () => {
   1057     if (!isMobileBrowser || !gameReady || !touchEnabled.checked) return;
   1058     setAutoRun(!autoRun);
   1059   };
   1060   autorunButton.onclick = event => {
   1061     if (event.detail === 0 && isMobileBrowser && gameReady && touchEnabled.checked) setAutoRun(!autoRun);
   1062   };
   1063   for (const button of document.querySelectorAll('[data-key]')) {
   1064     button.onpointerdown = () => {
   1065       pressKey(Number(button.dataset.key));
   1066     };
   1067     button.onclick = event => {
   1068       if (event.detail === 0) pressKey(Number(button.dataset.key));
   1069     };
   1070   }
   1071 
   1072   // Use a native field for the phone keyboard, paste, and text composition.
   1073   function closeChat(cancel) {
   1074     chatForm.hidden = true;
   1075     chatActions.hidden = true;
   1076     chatButton.textContent = 'Chat';
   1077     chatComposing = false;
   1078     updateChatViewport();
   1079     if (cancel) pressKey(27);
   1080     chatText.value = '';
   1081     canvas.focus();
   1082     updateTouchControls();
   1083     if (chatFullscreen) {
   1084       chatFullscreen.requestFullscreen().catch(error => {
   1085         document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
   1086       }).finally(() => {
   1087         gameSurface.style.width = gameSurface.style.height = '';
   1088         updateResolution();
   1089         updateChatViewport();
   1090       });
   1091       chatFullscreen = null;
   1092     }
   1093   }
   1094   const chatButton = document.querySelector('#chat-button');
   1095   chatButton.onclick = () => {
   1096     if (!isMobileBrowser) return;
   1097     releaseControls();
   1098     if (!chatForm.hidden) {
   1099       // A fresh focus during the gesture reopens a keyboard dismissed by the IME.
   1100       chatText.blur();
   1101       chatText.focus({preventScroll: true});
   1102       return;
   1103     }
   1104     // Release physical keys before their keyup events move into the text field.
   1105     window.dispatchEvent(new Event('blur'));
   1106     window.dispatchEvent(new Event('focus'));
   1107     pressKey(27);
   1108     pressKey(13);
   1109     chatForm.hidden = false;
   1110     chatActions.hidden = false;
   1111     chatButton.textContent = 'Keyboard';
   1112     // Firefox Android does not report keyboard occlusion reliably in fullscreen.
   1113     if (document.fullscreenElement && /Android.*Firefox\//.test(navigator.userAgent)) {
   1114       chatFullscreen = document.fullscreenElement;
   1115       gameSurface.style.width = `${canvas.clientWidth}px`;
   1116       gameSurface.style.height = `${canvas.clientHeight}px`;
   1117       document.exitFullscreen().then(() => {
   1118         updateChatViewport();
   1119         if (!chatForm.hidden) chatText.focus({preventScroll: true});
   1120       }).catch(error => {
   1121         document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
   1122       });
   1123     }
   1124     updateTouchControls();
   1125     updateChatViewport();
   1126     chatText.focus({preventScroll: true});
   1127   };
   1128   // Open the phone keyboard during the touch gesture, without a second compatibility click.
   1129   chatButton.addEventListener('touchend', event => {
   1130     if (chatButton.disabled) return;
   1131     event.preventDefault();
   1132     chatButton.onclick();
   1133   }, {passive: false});
   1134   chatText.oninput = () => chatText.setCustomValidity('');
   1135   chatText.addEventListener('compositionstart', () => { chatComposing = true; });
   1136   chatText.addEventListener('compositionend', () => { chatComposing = false; });
   1137   // Browser text enters the guest through its Windows-1252 character messages.
   1138   const chatDecoder = new TextDecoder('windows-1252');
   1139   const chatAlphabet = Array.from({length: 256}, (_, byte) => chatDecoder.decode(new Uint8Array([byte])));
   1140   canvas.addEventListener('paste', event => {
   1141     if (!gameReady || document.activeElement !== canvas) return;
   1142     event.preventDefault();
   1143     // Bound queued guest input to the server's chat message limit.
   1144     const text = event.clipboardData.getData('text/plain').slice(0, 4096).replace(/[\r\n\t]+/g, ' ');
   1145     for (const character of text) {
   1146       const byte = chatAlphabet.indexOf(character);
   1147       if (byte >= 32) Module._browser_paste_character(byte);
   1148     }
   1149   });
   1150   chatForm.onsubmit = event => {
   1151     event.preventDefault();
   1152     if (chatComposing) return;
   1153     const bytes = Array.from(chatText.value, character => chatAlphabet.indexOf(character));
   1154     if (bytes.some(byte => byte < 32)) {
   1155       chatText.setCustomValidity('This game cannot display one or more characters in this message.');
   1156       chatText.reportValidity();
   1157       return;
   1158     }
   1159     for (const byte of bytes) Module._browser_input_character(byte);
   1160     pressKey(13);
   1161     closeChat(false);
   1162   };
   1163   document.querySelector('#chat-cancel').onclick = () => closeChat(true);
   1164   function positionChat() {
   1165     if (!chatBounds) return;
   1166     const scaleX = canvas.clientWidth / chatBounds.screenWidth;
   1167     const scaleY = canvas.clientHeight / chatBounds.screenHeight;
   1168     chatForm.style.left = `${chatBounds.x * scaleX}px`;
   1169     // Pin immediately, including while native bounds still describe the last frame.
   1170     const visibleHeight = Math.min(canvas.clientHeight, window.visualViewport?.height ?? canvas.clientHeight);
   1171     chatForm.style.top = `${chatForm.hidden ? chatBounds.y * scaleY : Math.max(0, visibleHeight - (chatBounds.height + 1) * scaleY)}px`;
   1172     // Keep the caret reachable when a narrow screen clips the game's chat widget.
   1173     chatForm.style.width = `${Math.min(chatBounds.width, chatBounds.screenWidth - chatBounds.x) * scaleX}px`;
   1174     chatForm.style.height = `${chatBounds.height * scaleY}px`;
   1175     chatForm.style.bottom = 'auto';
   1176     chatText.style.fontSize = `${12 * scaleY}px`;
   1177   }
   1178 
   1179   // Keep the settings reachable by touch and include the overlay in fullscreen.
   1180   function openMenu() {
   1181     releaseControls();
   1182     if (!chatForm.hidden) closeChat(true);
   1183     window.dispatchEvent(new Event('blur'));
   1184     playerMenu.showModal();
   1185     updateTouchControls();
   1186     updateResolution();
   1187     Module.onOptionsOpen?.();
   1188   }
   1189   document.querySelector('#menu-button').onclick = openMenu;
   1190   document.querySelector('#view-button').onclick = () => {
   1191     if (!isMobileBrowser || !gameReady) return;
   1192     playerMenu.close();
   1193     pressKey(1073741889); // SDL F8: toggle first and third person.
   1194   };
   1195   playerMenu.addEventListener('close', () => {
   1196     window.dispatchEvent(new Event('focus'));
   1197     canvas.focus();
   1198     updateTouchControls();
   1199   });
   1200   const fullscreenButton = document.querySelector('#fullscreen-button');
   1201   fullscreenButton.hidden = !document.fullscreenEnabled;
   1202   fullscreenButton.onclick = async () => {
   1203     document.querySelector('#menu-error').textContent = '';
   1204     try {
   1205       if (document.fullscreenElement) await document.exitFullscreen();
   1206       else await document.documentElement.requestFullscreen();
   1207     } catch (error) {
   1208       document.querySelector('#menu-error').textContent = 'Fullscreen is unavailable: ' + error.message;
   1209     }
   1210   };
   1211   document.addEventListener('fullscreenchange', () => {
   1212     fullscreenButton.textContent = document.fullscreenElement ? 'Exit fullscreen' : 'Enter fullscreen';
   1213     updateResolution();
   1214     updateChatViewport();
   1215   });
   1216   // Preserve physical SDL keypad keys when NumLock changes browser key codes.
   1217   const keypadKeys = {
   1218     Numpad0: 1073741922, Numpad1: 1073741913, Numpad2: 1073741914,
   1219     Numpad3: 1073741915, Numpad4: 1073741916, Numpad5: 1073741917,
   1220     Numpad6: 1073741918, Numpad7: 1073741919, Numpad8: 1073741920,
   1221     Numpad9: 1073741921, NumpadMultiply: 1073741909, NumpadAdd: 1073741911,
   1222     NumpadSubtract: 1073741910, NumpadDecimal: 1073741923,
   1223     NumpadDivide: 1073741908, NumpadEnter: 1073741912,
   1224   };
   1225   for (const type of ['keydown', 'keyup', 'keypress']) {
   1226     window.addEventListener(type, event => {
   1227       if (creationDialog.open) {
   1228         event.stopImmediatePropagation();
   1229       } else if (type === 'keydown' && event.ctrlKey && event.altKey && event.code === 'KeyM') {
   1230         event.preventDefault();
   1231         event.stopImmediatePropagation();
   1232         if (event.repeat) return;
   1233         if (playerMenu.open) playerMenu.close();
   1234         else openMenu();
   1235       } else if (playerMenu.open || !chatForm.hidden) {
   1236         event.stopImmediatePropagation();
   1237         if (type === 'keydown' && event.key === 'Escape' && !chatForm.hidden && !chatComposing && !event.isComposing && event.keyCode !== 229) {
   1238           event.preventDefault();
   1239           closeChat(true);
   1240         }
   1241       } else if (gameReady && document.activeElement === canvas && !event.altKey &&
   1242                  (((event.ctrlKey || event.metaKey) && event.code === 'KeyV') ||
   1243                   (event.shiftKey && event.code === 'Insert'))) {
   1244         // Keep the browser's paste event and keep the shortcut out of SDL.
   1245         event.stopImmediatePropagation();
   1246       } else if (gameReady && document.activeElement === canvas && (event.key === 'Tab' || event.key === 'F1')) {
   1247         // Let SDL handle targeting without moving browser focus or opening Help.
   1248         event.preventDefault();
   1249       } else if (gameReady && document.activeElement === canvas && type === 'keypress' &&
   1250                  (event.key === '/' || event.key === "'")) {
   1251         // Cancel Firefox Quick Find before the event is proxied to SDL's worker.
   1252         event.preventDefault();
   1253       } else if (gameReady && keypadKeys[event.code]) {
   1254         event.preventDefault();
   1255         event.stopImmediatePropagation();
   1256         if (type === 'keypress') return;
   1257         const key = keypadKeys[event.code], down = type === 'keydown';
   1258         const modifiers = (event.shiftKey ? 0x0003 : 0) | (event.ctrlKey ? 0x00c0 : 0) |
   1259           (event.altKey ? 0x0300 : 0) | (event.metaKey ? 0x0c00 : 0) |
   1260           (event.getModifierState('NumLock') ? 0x1000 : 0) |
   1261           (event.getModifierState('CapsLock') ? 0x2000 : 0);
   1262         Module._browser_input_key(key, down, event.repeat, modifiers);
   1263         if (down) heldKeys.add(key);
   1264         else heldKeys.delete(key);
   1265       }
   1266     }, true);
   1267   }
   1268   window.addEventListener('blur', releaseControls);
   1269   window.addEventListener('pagehide', releaseControls);
   1270   document.addEventListener('freeze', releaseControls);
   1271   window.addEventListener('focus', resumeAudio);
   1272   window.addEventListener('pageshow', resumeGame);
   1273   document.addEventListener('resume', resumeGame);
   1274   window.addEventListener('resize', releaseControls);
   1275   document.addEventListener('visibilitychange', () => {
   1276     if (document.hidden) releaseControls();
   1277     else resumeGame();
   1278   });
   1279   window.visualViewport?.addEventListener('resize', updateChatViewport);
   1280   window.visualViewport?.addEventListener('scroll', updateChatViewport);
   1281 </script>
   1282 <script id="account-controls">
   1283   const accountForm = document.querySelector('#account-form');
   1284   const accountError = document.querySelector('#account-error');
   1285   const accountChoices = document.querySelector('#account-choices');
   1286   const accountFields = document.querySelector('#account-fields');
   1287   const claimButton = document.querySelector('#claim-button');
   1288   const passwordButton = document.querySelector('#password-button');
   1289   let accountAction = '', currentName = '';
   1290 
   1291   // Restart in the original creator; cancellation returns to the current character.
   1292   document.querySelector('#create-button').onclick = () => {
   1293     location.assign('?create=1');
   1294   };
   1295 
   1296   // Keep account flows separate and clear abandoned credentials on Back.
   1297   for (const [action, title, description] of [
   1298     ['claim', 'Save this character', 'Keep this character, including its equipment and progress, with a name and password.'],
   1299     ['login', 'Log in', 'Switch to an existing character using its name and password.'],
   1300     ['password', 'Change password', '']
   1301   ]) {
   1302     document.querySelector('#' + action + '-button').onclick = () => {
   1303       accountAction = action;
   1304       if (action === 'claim') document.querySelector('#account-name').value = currentName.replace(/^Visitor/, '');
   1305       accountError.textContent = '';
   1306       accountError.classList.remove('success');
   1307       const changingPassword = action === 'password';
   1308       document.querySelector('#account-name').disabled = changingPassword;
   1309       document.querySelector('#account-name').parentElement.hidden = changingPassword;
   1310       document.querySelector('#account-password-label').textContent = changingPassword ? 'New password' : 'Password';
   1311       document.querySelector('#account-description').hidden = changingPassword;
   1312       accountChoices.hidden = true;
   1313       accountForm.hidden = false;
   1314       document.querySelector('#account-title').textContent = title;
   1315       document.querySelector('#account-description').textContent = description;
   1316       document.querySelector('#account-submit').textContent = title;
   1317       document.querySelector('#account-password').required = action !== 'login';
   1318       document.querySelector('#account-password').minLength = action === 'login' ? 0 : 5;
   1319       document.querySelector('#account-password').autocomplete = action === 'login' ? 'current-password' : 'new-password';
   1320       document.querySelector(changingPassword ? '#account-password' : '#account-name').focus();
   1321     };
   1322   }
   1323   document.querySelector('#account-back').onclick = () => {
   1324     accountForm.hidden = true;
   1325     accountChoices.hidden = false;
   1326     accountError.textContent = '';
   1327     document.querySelector('#account-name').value = document.querySelector('#account-password').value = '';
   1328     document.querySelector('#' + accountAction + '-button').focus();
   1329     accountAction = '';
   1330   };
   1331   Module.onOptionsOpen = () => {
   1332     if (accountRequest) return;
   1333     document.querySelector('#account-panel').hidden = false;
   1334     accountForm.hidden = true;
   1335     accountChoices.hidden = false;
   1336     accountAction = '';
   1337     document.querySelector('#account-name').value = document.querySelector('#account-password').value = '';
   1338     if (currentName) accountError.textContent = '';
   1339     else Module.loadAccount();
   1340     accountError.classList.remove('success');
   1341   };
   1342 
   1343   // Fetch identity when first opening the account menu or completing native creation.
   1344   Module.loadAccount = async () => {
   1345     try {
   1346       const response = await fetch('browser-account');
   1347       if (!response.ok) { accountError.textContent = await response.text(); return; }
   1348       const player = await response.json();
   1349       currentName = player.name;
   1350       document.querySelector('#account-current').textContent = `Playing as ${player.name}.` +
   1351         (player.visitor ? ' Save this character to enable name-and-password login.' : '');
   1352       claimButton.hidden = !player.visitor;
   1353       passwordButton.hidden = !player.adopted;
   1354     } catch (error) {
   1355       accountError.textContent = 'Could not load player details. Reload to retry.';
   1356     }
   1357   };
   1358   accountForm.onsubmit = async event => {
   1359     event.preventDefault();
   1360     if (accountRequest || !accountAction) return;
   1361     if (accountAction !== 'login' && Array.from(document.querySelector('#account-password').value).length < 5) {
   1362       accountError.textContent = 'Use a password of at least 5 characters.';
   1363       document.querySelector('#account-password').focus();
   1364       return;
   1365     }
   1366     accountRequest = true;
   1367     accountFields.disabled = true;
   1368     accountError.textContent = '';
   1369     const values = new URLSearchParams({name: document.querySelector('#account-name').value,
   1370       password: document.querySelector('#account-password').value});
   1371     try {
   1372       const response = await fetch('browser-account/' + accountAction, {method: 'POST', body: values});
   1373       if (response.ok) {
   1374         if (accountAction !== 'password') { location.reload(); return; }
   1375         accountForm.hidden = true;
   1376         accountChoices.hidden = false;
   1377         accountAction = '';
   1378         document.querySelector('#account-password').value = '';
   1379         passwordButton.focus();
   1380         accountError.classList.add('success');
   1381         accountError.textContent = 'Password changed.';
   1382       } else {
   1383         accountError.textContent = await response.text();
   1384       }
   1385     } catch (error) {
   1386       accountError.textContent = 'Could not contact the server. Please try again.';
   1387     }
   1388     accountRequest = false;
   1389     accountFields.disabled = false;
   1390     if (accountClosed !== null) {
   1391       const replaced = accountClosed;
   1392       accountClosed = null;
   1393       Module.onGameClosed(replaced);
   1394     }
   1395   };
   1396   startGame().catch(error => Module.onAbort(error.message));
   1397 </script>
   1398 </html>