aorecomp

Anarchy Online classic in the browser

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


commit 974f598f23eed9aa782da7539ef7f4cc5642df1d
parent 02a5afd8f7c3e78161e84421b78c61abf2d5819d
Author: anon <anon@example.com>
Date:   Sun, 18 Oct 2026 04:58:00 +0000

Show streaming client load progress without the Tools overlay

Diffstat:
Msrc/browser/index.html | 126+++++++++++++++++++++++++++++++++----------------------------------------------
Msrc/runtime/browser_host.js | 9++++++++-
Msrc/runtime/browser_profile.js | 8++------
Asrc/tests/browser_loading.mjs | 59+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Msrc/tests/browser_profile.mjs | 8+++++++-
5 files changed, 128 insertions(+), 82 deletions(-)

diff --git a/src/browser/index.html b/src/browser/index.html @@ -4,65 +4,60 @@ <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Anarchy Online 14.9.1</title> <style> - body { margin: 0; background: #111; color: #ddd; font: 16px sans-serif; } - header { padding: 12px; } - button { padding: 8px 16px; } - html, body { width: 100%; height: 100%; overflow: hidden; } + 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%; } - #tools { position: fixed; z-index: 1; top: 4px; left: 16px; background: #222e; max-width: 90%; max-height: 90%; overflow: auto; } - #tools > summary { padding: 8px; cursor: pointer; } - pre { padding: 12px; white-space: pre-wrap; } + #loading { position: fixed; inset: 0; display: grid; place-items: center; pointer-events: none; } + #loading[hidden] { display: none; } </style> <canvas id="canvas" width="1024" height="768" tabindex="0"></canvas> -<details id="tools" open><summary>Tools</summary> -<header><span id="status">Loading client</span></header> -<div id="profile-status" style="padding:0 12px"></div> -<details style="padding:12px"> -<summary>Frame capture</summary> -<p>Records every game frame. This slows rendering; use it to inspect glitches, not measure FPS.</p> -<label>Frames <input id="capture-count" type="number" min="1" max="120" value="60" required></label> -<button id="capture" disabled>Record frames</button> -<span id="capture-status"></span> -<a id="capture-download" hidden download="ao-frames.html">Download frame report</a> -<div id="capture-viewer" hidden> -<label>Captured frame <input id="capture-frame" type="range" min="0" value="0"></label> -<span id="capture-label"></span><br> -<img id="capture-image" alt="Captured game frame" style="max-width:100%"> -</div> -</details> -<pre id="log"></pre> -</details> +<div id="loading" role="status">Loading...</div> <script> - const status = document.querySelector('#status'); - const log = document.querySelector('#log'); + const status = document.querySelector('#loading'); const canvas = document.querySelector('#canvas'); + let recording = null, reportURL = null; + function log(message) { + console.log(message); + if (recording) recording.log += message + '\n'; + } var Module = { canvas, - print: message => { log.textContent += message + '\n'; }, - printErr: message => { log.textContent += message + '\n'; }, - onAbort: message => { status.textContent = 'Stopped: ' + message; document.querySelector('#tools').open = true; }, + print: log, + printErr: log, + onAbort: message => { + status.textContent = 'Stopped: ' + message; + status.hidden = false; + console.error(message); + }, + onFirstFrame: () => { status.hidden = true; }, onRuntimeInitialized: () => { - status.textContent = 'Client running'; - document.querySelector('#capture').disabled = false; - document.querySelector('#tools').open = false; + console.log('Client running'); new ResizeObserver(() => Module._browser_request_resize(canvas.clientWidth, canvas.clientHeight)).observe(canvas); canvas.focus(); + }, + instantiateWasm: (imports, receive) => { + instantiateClient(imports, receive).catch(error => Module.onAbort(error.message)); + return {}; } }; - const captureButton = document.querySelector('#capture'); - const captureStatus = document.querySelector('#capture-status'); - const captureDownload = document.querySelector('#capture-download'); - let recording = null, reportURL = null; - let capturedFrames = []; - const frameSlider = document.querySelector('#capture-frame'); - function showCapturedFrame() { - const index = Number(frameSlider.value), frame = capturedFrames[index]; - document.querySelector('#capture-image').src = frame.png; - document.querySelector('#capture-label').textContent = `${index + 1} / ${capturedFrames.length}`; + + // Count compressed bytes and preserve streaming compilation while decoding. + async function instantiateClient(imports, receive) { + const response = await fetch('/wasm/game.wasm.gz'); + if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`); + let loaded = 0; + const progress = new TransformStream({transform(chunk, controller) { + loaded += chunk.byteLength; + status.textContent = `Loading... ${(loaded / 1000000).toFixed(1)} MB`; + controller.enqueue(chunk); + }}); + const decoded = response.body.pipeThrough(progress).pipeThrough(new DecompressionStream('gzip')); + const result = await WebAssembly.instantiateStreaming(new Response(decoded, { + headers: {'Content-Type': 'application/wasm'} + }), imports); + receive(result.instance, result.module); } - frameSlider.oninput = showCapturedFrame; - // Keep input times beside the frame sequence so turns can be replayed and inspected. + // Console capture keeps every frame and input time for inspecting motion glitches. for (const type of ['keydown', 'keyup', 'mousedown', 'mouseup', 'mousemove']) { canvas.addEventListener(type, event => { if (recording) recording.inputs.push({time: performance.timeOrigin + performance.now(), type, @@ -73,16 +68,6 @@ Module._browser_capture_frames(0); const report = recording; recording = null; - captureButton.textContent = 'Record frames'; - captureStatus.textContent = `Saved ${report.frames.length} frames.`; - if (!report.frames.length) return; - report.log = log.textContent; - capturedFrames = report.frames; - frameSlider.max = capturedFrames.length - 1; - frameSlider.value = 0; - showCapturedFrame(); - document.querySelector('#capture-viewer').hidden = false; - // A standalone HTML report retains every PNG and works without the game server. const data = JSON.stringify(report).replaceAll('<', '\\u003c'); const viewer = `<!doctype html><meta charset="utf-8"><title>AO frame capture</title> <style>body{background:#111;color:#ddd;font:16px sans-serif}img{max-width:100%}pre{white-space:pre-wrap}</style> @@ -114,23 +99,17 @@ document.querySelector('#details').textContent = JSON.stringify(metadata, null, show(); <\/script>`; reportURL = URL.createObjectURL(new Blob([viewer], {type: 'text/html'})); - captureDownload.href = reportURL; - captureDownload.hidden = false; + console.log(`Captured ${report.frames.length} frames. Open this report:`, reportURL); } - captureButton.onclick = () => { - if (recording) { finishCapture(); return; } - const count = document.querySelector('#capture-count'); - if (!count.reportValidity()) return; + Module.captureFrames = count => { + if (!Number.isInteger(count) || count < 1 || count > 120) + throw new RangeError('Capture requires 1-120 frames'); + if (recording) throw new Error('A frame capture is already running'); if (reportURL) URL.revokeObjectURL(reportURL); - captureDownload.hidden = true; - capturedFrames = []; - document.querySelector('#capture-viewer').hidden = true; - document.querySelector('#capture-image').removeAttribute('src'); - recording = {requested: Number(count.value), started: new Date().toISOString(), - userAgent: navigator.userAgent, inputs: [], frames: []}; - captureButton.textContent = 'Stop recording'; - captureStatus.textContent = 'Waiting for game frames'; - Module._browser_capture_frames(recording.requested); + recording = {requested: count, started: new Date().toISOString(), + userAgent: navigator.userAgent, inputs: [], frames: [], log: ''}; + console.log(`Recording ${count} frames; this slows rendering`); + Module._browser_capture_frames(count); canvas.focus(); }; Module.captureFrame = (pixels, width, height, time) => { @@ -142,12 +121,11 @@ show(); frame.width = width; frame.height = height; frame.getContext('2d').putImageData(image, 0, 0); recording.frames.push({time, png: frame.toDataURL('image/png')}); - captureStatus.textContent = `Recorded ${recording.frames.length} / ${recording.requested}`; if (recording.frames.length === recording.requested) finishCapture(); }; async function startGame() { if (!crossOriginIsolated) { status.textContent = 'Shared memory is unavailable'; return; } - if (!WebAssembly.Suspending || !canvas.transferControlToOffscreen) { status.textContent = 'This browser lacks required WebAssembly or rendering support'; return; } + if (!WebAssembly.Suspending || !canvas.transferControlToOffscreen || !globalThis.DecompressionStream) { status.textContent = 'This browser lacks required WebAssembly or rendering support'; return; } Module.audioContext = new AudioContext(); // Load immediately; browsers unlock audio on the first game interaction. for (const type of ['pointerdown', 'keydown']) { @@ -155,7 +133,7 @@ show(); if (Module.audioContext.state === 'suspended') Module.audioContext.resume(); }); } - status.textContent = 'Loading client'; + status.textContent = 'Loading...'; const response = await fetch('/browser-launch', {method: 'POST'}); if (!response.ok) { status.textContent = await response.text(); return; } Module.arguments = (await response.text()).trim().split(' ').slice(1); @@ -167,6 +145,6 @@ show(); script.onerror = () => { status.textContent = 'Could not load the client'; }; document.body.append(script); } - startGame(); + startGame().catch(error => Module.onAbort(error.message)); </script> </html> diff --git a/src/runtime/browser_host.js b/src/runtime/browser_host.js @@ -1,7 +1,14 @@ addToLibrary({ + $AOPresented: false, + ao_loading_complete__proxy: 'async', + ao_loading_complete: () => { Module.onFirstFrame?.(); }, ao_present_yield__async: 'auto', - ao_present_yield__deps: ['$AOProfile'], + ao_present_yield__deps: ['$AOProfile', '$AOPresented', 'ao_loading_complete'], ao_present_yield: () => { + if (!AOPresented) { + AOPresented = true; + _ao_loading_complete(); + } AOProfile.frame(); const start = AOProfile.begin('raf wait'); return new Promise(resolve => requestAnimationFrame(timestamp => { diff --git a/src/runtime/browser_profile.js b/src/runtime/browser_profile.js @@ -96,14 +96,10 @@ addToLibrary({ worker.postMessage({init: {session, detailed, memory: wasmMemory.buffer, currentFunction, phase, thread, started: performance.timeOrigin + performance.now(), visibility: document.visibilityState, client: {userAgent: navigator.userAgent, width: Module.canvas.width, height: Module.canvas.height}}}); - worker.onmessage = event => { - const status = document.getElementById('profile-status'); - if (status) status.textContent = event.data; - }; + worker.onmessage = event => console.log(event.data); worker.onerror = () => { channel.close(); - const status = document.getElementById('profile-status'); - if (status) status.textContent = 'Profiler stopped; gameplay continues'; + console.warn('Profiler stopped; gameplay continues'); }; document.addEventListener('visibilitychange', () => { worker.postMessage({visibility: document.visibilityState}); diff --git a/src/tests/browser_loading.mjs b/src/tests/browser_loading.mjs @@ -0,0 +1,59 @@ +import assert from 'node:assert/strict'; +import fs from 'node:fs'; +import vm from 'node:vm'; +import zlib from 'node:zlib'; + +function fixture(response) { + const progress = []; + const loading = {hidden: false, set textContent(value) { progress.push(value); }}; + const canvas = {addEventListener() {}}; + const context = vm.createContext({ + console, WebAssembly, Response, TransformStream, DecompressionStream, + document: {querySelector: selector => selector === '#loading' ? loading : canvas}, + fetch: async url => { + assert.equal(url, '/wasm/game.wasm.gz'); + return 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));', ''); + vm.runInContext(script, context); + return {context, progress, loading}; +} + +async function streamsCompressedClientAndTracksProgress() { + // A valid module with one 64 KiB custom section, kept uncompressed for the test. + const wasm = new Uint8Array(65549); + wasm.set([0, 97, 115, 109, 1, 0, 0, 0, 0, 129, 128, 4, 0]); + const compressed = zlib.gzipSync(wasm, {level: 0}); + const stream = new ReadableStream({start(controller) { + controller.enqueue(compressed.subarray(0, 32768)); + controller.enqueue(compressed.subarray(32768)); + controller.close(); + }}); + const test = fixture(new Response(stream)); + let instance, module; + + await test.context.instantiateClient({}, (loadedInstance, loadedModule) => { + instance = loadedInstance; + module = loadedModule; + }); + test.context.Module.onFirstFrame(); + + assert.ok(instance instanceof WebAssembly.Instance); + assert.ok(module instanceof WebAssembly.Module); + assert.deepEqual(test.progress, ['Loading... 0.0 MB', 'Loading... 0.1 MB']); + assert.equal(test.loading.hidden, true); +} + +async function rejectsFailedClientDownload() { + const test = fixture(new Response('missing', {status: 404})); + + await assert.rejects(test.context.instantiateClient({}, () => assert.fail('instantiated missing client')), + /Client download: HTTP 404/); +} + +await streamsCompressedClientAndTracksProgress(); +await rejectsFailedClientDownload(); +console.log('PASS: compressed loading progress, streaming compilation, first frame and download failure'); diff --git a/src/tests/browser_profile.mjs b/src/tests/browser_profile.mjs @@ -184,7 +184,7 @@ console.log('PASS: busy and short-lived audio workers deliver aggregates without async function frameCallbackTimestampPreservesPacing() { for (const detailed of [false, true]) { - let library, callback, now = 0, callbacks = 0; + let library, callback, now = 0, callbacks = 0, firstFrames = 0; const sent = []; const heap = new Uint32Array(new SharedArrayBuffer(16)); heap[1] = 2; @@ -193,6 +193,7 @@ async function frameCallbackTimestampPreservesPacing() { _browser_profile_configuration: () => `${detailed ? 1 : 0}:test:4:7`, _pthread_self: () => 7, UTF8ToString: value => value, setInterval: () => {}, requestAnimationFrame: handler => { callback = handler; ++callbacks; }, + AOPresented: false, _ao_loading_complete: () => { ++firstFrames; }, BroadcastChannel: class { postMessage(value) { sent.push(value); } }, addToLibrary: value => { library = value; } }); @@ -210,6 +211,7 @@ async function frameCallbackTimestampPreservesPacing() { context.AOProfile.flush(); assert.equal(callbacks, 1); + assert.equal(firstFrames, 1); assert.equal(resumed, true); assert.equal(heap[1], 2); assert.equal(sent.length, 1); @@ -220,6 +222,10 @@ async function frameCallbackTimestampPreservesPacing() { assert.equal(sent[0].events[0].dur, 180000); assert.equal(sent[0].events[0].args.frame_time_us, 1020000); } + const next = library.ao_present_yield(); + callback(200); + await next; + assert.equal(firstFrames, 1); } }