commit ce2fe0a9ec6894e86cf8e1879ca8927660767f11
parent d49b764358686e10d27f112ead52a4df9fa98fa2
Author: anon <anon@example.com>
Date: Tue, 10 Nov 2026 23:15:02 +0000
Combine asset and game binary download progress
Diffstat:
3 files changed, 91 insertions(+), 37 deletions(-)
diff --git a/client/browser/index.html b/client/browser/index.html
@@ -69,8 +69,8 @@
</style>
<div id="game-surface">
<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
-<div id="loading" role="status">Downloading Anarchy Online client...</div>
-<div id="download-progress" role="progressbar" aria-label="Client download" aria-valuemin="0" aria-valuemax="100" aria-valuenow="0" hidden><div id="download-fill"></div></div>
+<div id="loading" role="status">Downloading Anarchy Online...</div>
+<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>
<button id="reconnect" hidden>Reconnect</button>
<div id="game-toolbar" hidden>
<div id="chat-actions" hidden>
@@ -298,20 +298,28 @@
resumeAudio();
}
- // The published sizes distinguish the compressed transfer from decoded progress.
+ // One byte-weighted download covers the uncached assets and compressed game binary.
+ let startupAssetBytes = 0, loadedStartupAssetBytes = 0;
+ function updateDownloadProgress(clientFraction) {
+ const clientBytes = Number('__WASM_DOWNLOAD_MB__') * 1000000;
+ const total = startupAssetBytes + clientBytes;
+ const loaded = loadedStartupAssetBytes + clientBytes * clientFraction;
+ const percent = Math.min(100, loaded / total * 100);
+ status.textContent = `Downloading Anarchy Online...\n${(loaded / 1000000).toFixed(2)} / ${(total / 1000000).toFixed(2)} MB`;
+ downloadProgress.hidden = false;
+ downloadFill.style.width = `${percent}%`;
+ downloadProgress.setAttribute('aria-valuenow', Math.round(percent));
+ }
+
+ // Fetch exposes decoded WASM bytes; scale them to the published compressed size.
async function instantiateClient(imports, receive) {
const response = await fetch('wasm/game.wasm');
if (!response.ok) throw new Error(`Client download: HTTP ${response.status}`);
- const totalMB = Number('__WASM_DOWNLOAD_MB__');
- status.textContent = `Downloading Anarchy Online client...\n0.00 / ${totalMB.toFixed(2)} MB`;
- downloadProgress.hidden = false;
+ updateDownloadProgress(0);
let loaded = 0;
const progress = new TransformStream({transform(chunk, controller) {
loaded += chunk.byteLength;
- const percent = Math.min(100, loaded / Number('__WASM_DECODED_BYTES__') * 100);
- status.textContent = `Downloading Anarchy Online client...\n${(totalMB * percent / 100).toFixed(2)} / ${totalMB.toFixed(2)} MB`;
- downloadFill.style.width = `${percent}%`;
- downloadProgress.setAttribute('aria-valuenow', Math.round(percent));
+ updateDownloadProgress(Math.min(1, loaded / Number('__WASM_DECODED_BYTES__')));
controller.enqueue(chunk);
}, flush() {
downloadProgress.hidden = true;
@@ -326,6 +334,7 @@
// Receive the fixed startup ranges in one stream before the game starts reading assets.
async function preloadStartupAssets() {
+ startupAssetBytes = loadedStartupAssetBytes = 0;
if (!globalThis.caches) return;
let cache;
try {
@@ -353,11 +362,10 @@
return;
}
if (cached.every(Boolean)) {
- status.textContent = 'Downloading Anarchy Online client...';
+ status.textContent = 'Downloading Anarchy Online...';
return;
}
- status.textContent = 'Downloading game assets...';
const response = await fetch('browser-startup', {cache: 'no-store'});
if (!response.ok) throw new Error(`Game assets: HTTP ${response.status}`);
const reader = response.body.getReader();
@@ -372,7 +380,8 @@
// Keep only one assembled chunk in memory, with the same key and ETag as range fetches.
let chunk = new Uint8Array(chunkSize), offset = 0, completed = 0;
- downloadProgress.hidden = false;
+ startupAssetBytes = total;
+ updateDownloadProgress(0);
for (;;) {
const {value, done} = await reader.read();
if (done) break;
@@ -389,24 +398,22 @@
await cache.put(url.href, new Response(chunk, {headers: {'ETag': version}}));
} catch (error) {
console.warn('Startup asset cache write failed:', error);
+ startupAssetBytes = loadedStartupAssetBytes;
+ updateDownloadProgress(0);
return;
}
completed++;
offset = 0;
chunk = new Uint8Array(chunkSize);
- const percent = completed / indices.length * 100;
- status.textContent = `Downloading game assets...\n${completed} / ${indices.length} MiB`;
- downloadFill.style.width = `${percent}%`;
- downloadProgress.setAttribute('aria-valuenow', Math.round(percent));
+ loadedStartupAssetBytes = completed * chunkSize;
+ updateDownloadProgress(0);
}
}
if (completed !== indices.length || offset) throw new Error('Incomplete startup asset download');
console.info('Startup asset chunks cached:', indices);
} finally {
await reader.cancel();
- downloadProgress.hidden = true;
}
- status.textContent = 'Downloading Anarchy Online client...';
}
// Console capture keeps every frame and input time for inspecting motion glitches.
@@ -514,7 +521,7 @@ show();
for (const type of ['pointerdown', 'keydown']) {
document.addEventListener(type, resumeAudio, true);
}
- status.textContent = 'Downloading Anarchy Online client...';
+ status.textContent = 'Downloading Anarchy Online...';
const response = await fetch('browser-launch' + (creating ? '?create=1' : ''), {method: 'POST'});
if (!response.ok) { status.textContent = await response.text(); return; }
Module.arguments = (await response.text()).trim().split(' ').slice(1);
diff --git a/client/tests/browser_loading.mjs b/client/tests/browser_loading.mjs
@@ -5,8 +5,10 @@ import vm from 'node:vm';
function fixture(response) {
const progress = [];
const loading = {hidden: false, set textContent(value) { progress.push(value); }};
- const percentages = [], widths = [];
- const downloadProgress = {hidden: true, setAttribute(name, value) {
+ const percentages = [], widths = [], visibility = [];
+ let progressHidden = true;
+ const downloadProgress = {get hidden() { return progressHidden; },
+ set hidden(value) { progressHidden = value; visibility.push(value); }, setAttribute(name, value) {
assert.equal(name, 'aria-valuenow');
assert.equal(this.hidden, false);
percentages.push(value);
@@ -33,19 +35,22 @@ function fixture(response) {
.replace('__WASM_DOWNLOAD_MB__', '11.57').replace('__WASM_DECODED_BYTES__', '65549');
vm.runInContext(script, context);
context.Module.loadAccount = () => {};
- return {context, progress, loading, downloadProgress, percentages, widths};
+ return {context, progress, loading, downloadProgress, percentages, widths, visibility};
}
-async function streamsDecodedClientAndTracksProgress() {
+function clientDownloadResponse() {
// Fetch exposes the decoded body after HTTP handles Content-Encoding.
const wasm = new Uint8Array(65549);
wasm.set([0, 97, 115, 109, 1, 0, 0, 0, 0, 129, 128, 4, 0]);
- const stream = new ReadableStream({start(controller) {
+ return new Response(new ReadableStream({start(controller) {
controller.enqueue(wasm.subarray(0, 32768));
controller.enqueue(wasm.subarray(32768));
controller.close();
- }});
- const test = fixture(new Response(stream));
+ }}));
+}
+
+async function streamsDecodedClientAndTracksProgress() {
+ const test = fixture(clientDownloadResponse());
let instance, module;
await test.context.instantiateClient({}, (loadedInstance, loadedModule) => {
@@ -57,14 +62,14 @@ async function streamsDecodedClientAndTracksProgress() {
assert.ok(instance instanceof WebAssembly.Instance);
assert.ok(module instanceof WebAssembly.Module);
assert.deepEqual(test.progress, [
- 'Downloading Anarchy Online client...\n0.00 / 11.57 MB',
- 'Downloading Anarchy Online client...\n5.78 / 11.57 MB',
- 'Downloading Anarchy Online client...\n11.57 / 11.57 MB',
+ 'Downloading Anarchy Online...\n0.00 / 11.57 MB',
+ 'Downloading Anarchy Online...\n5.78 / 11.57 MB',
+ 'Downloading Anarchy Online...\n11.57 / 11.57 MB',
'Starting Anarchy Online...'
]);
- assert.deepEqual(test.percentages, [50, 100]);
- assert.equal(Math.round(parseFloat(test.widths[0])), 50);
- assert.equal(test.widths[1], '100%');
+ assert.deepEqual(test.percentages, [0, 50, 100]);
+ assert.equal(Math.round(parseFloat(test.widths[1])), 50);
+ assert.equal(test.widths[2], '100%');
assert.equal(test.downloadProgress.hidden, true);
assert.equal(test.loading.hidden, true);
}
@@ -239,8 +244,8 @@ async function cachesStreamedStartupChunks() {
assert.equal(response.headers.get('ETag'), '"database-revision"');
assert.deepEqual(new Uint8Array(await response.arrayBuffer()), test.bytes.subarray(i * 1048576, (i + 1) * 1048576));
}
- assert.deepEqual(test.percentages, [33, 67, 100]);
- assert.equal(test.downloadProgress.hidden, true);
+ assert.deepEqual(test.percentages, [0, 7, 14, 21]);
+ assert.equal(test.downloadProgress.hidden, false);
assert.deepEqual(test.warnings, []);
assert.deepEqual(test.requests, ['HEAD', 'GET']);
}
@@ -290,6 +295,8 @@ async function rejectsIncompleteStartupStream() {
await assert.rejects(test.context.preloadStartupAssets(), /Incomplete startup asset download/);
assert.equal(test.written.size, 1, 'partial chunks must never enter the cache');
+ test.context.console.error = () => {};
+ test.context.Module.onAbort('Incomplete startup asset download');
assert.equal(test.downloadProgress.hidden, true);
test.context.fetch = fetch;
test.requests.length = 0;
@@ -324,9 +331,34 @@ async function cancelsStartupStreamWhenCacheFills() {
assert.equal(cancelled, true);
assert.equal(test.warnings.length, 1);
- assert.equal(test.downloadProgress.hidden, true);
+ assert.equal(test.downloadProgress.hidden, false);
+ test.context.fetch = async () => clientDownloadResponse();
+ await test.context.instantiateClient({}, () => {});
+ assert.equal(test.percentages.at(-1), 100);
+}
+
+async function combinesAssetAndClientProgress(warm) {
+ const test = startupFixture();
+ if (warm) {
+ await test.context.preloadStartupAssets();
+ test.percentages.length = test.progress.length = test.visibility.length = 0;
+ }
+
+ await test.context.preloadStartupAssets();
+ test.context.fetch = async () => clientDownloadResponse();
+ await test.context.instantiateClient({}, () => {});
+
+ assert.deepEqual(test.percentages, warm ? [0, 50, 100] : [0, 7, 14, 21, 21, 61, 100]);
+ assert.equal(test.visibility.at(-1), true);
+ assert.ok(test.visibility.slice(0, -1).every(hidden => !hidden), 'bar must stay visible between downloads');
+ const downloads = test.progress.filter(message => message.includes(' MB'));
+ assert.ok(downloads.every(message => message.startsWith('Downloading Anarchy Online...')));
+ assert.equal(downloads.at(-1), warm ? 'Downloading Anarchy Online...\n11.57 / 11.57 MB' :
+ 'Downloading Anarchy Online...\n14.72 / 14.72 MB');
}
+await combinesAssetAndClientProgress(false);
+await combinesAssetAndClientProgress(true);
await cachesStreamedStartupChunks();
await skipsCachedStartupStream();
await reloadsStartupStreamAfterCacheEviction();
diff --git a/tests/e2e/startup.test.mjs b/tests/e2e/startup.test.mjs
@@ -35,6 +35,15 @@ for (const latency of [0, 120]) {
}
});
const page = await context.newPage();
+ await page.addInitScript(() => {
+ window.startupDownloadProgress = [];
+ document.addEventListener('DOMContentLoaded', () => {
+ const bar = document.querySelector('#download-progress');
+ new MutationObserver(() => window.startupDownloadProgress.push({
+ percent: Number(bar.getAttribute('aria-valuenow')), hidden: bar.hidden
+ })).observe(bar, {attributes: true, attributeFilter: ['aria-valuenow', 'hidden']});
+ });
+ });
const game = await GameTest.attach(page);
fixture.games.push(game);
const results = [];
@@ -80,7 +89,13 @@ for (const latency of [0, 120]) {
});
assert.deepEqual(requestedChunks.filter(index => bundles[0].chunks.includes(index)), [],
'preloaded database chunks must not be downloaded again');
- results.push({cache, ready, playable, preload, requestedChunks, requests});
+ const downloadProgress = await page.evaluate(() => window.startupDownloadProgress);
+ assert.ok(downloadProgress.length > 1);
+ assert.deepEqual(downloadProgress.at(-1), {percent: 100, hidden: true});
+ assert.ok(downloadProgress.every((sample, i) => (!sample.hidden || sample.percent === 100) &&
+ (i === 0 || sample.percent >= downloadProgress[i - 1].percent)),
+ 'download bar must advance continuously through assets and game binary');
+ results.push({cache, ready, playable, preload, requestedChunks, requests, downloadProgress});
await game.save(fixture.output + '/' + cache);
}