commit 7cc52bab0c496895fa8761a55bf85c6e1ab71fe3
parent 80db2585ffb03dba19bb04391adb5e0f663eda83
Author: anon <anon@example.com>
Date: Sat, 17 Oct 2026 19:17:37 +0000
Prefetch queued resource bytes on the browser file worker
Diffstat:
8 files changed, 310 insertions(+), 21 deletions(-)
diff --git a/src/Makefile.wasm b/src/Makefile.wasm
@@ -13,6 +13,10 @@ OBJECTS := $(patsubst %.c,build/wasm/objects/%.o,$(GAME_SOURCES) $(DATA_SOURCES)
.PHONY: all objects
all: build/wasm/web/game.js build/wasm/web/game.wasm build/wasm/web/index.html
+build/wasm/web/resource-dispatch-test.html: tests/browser_resource_queue.c runtime/browser_host.c
+ @mkdir -p $(@D)
+ $(CC) $(CPPFLAGS) $(CFLAGS) $^ -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=2 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -o $@
+
build/wasm/web/game.js build/wasm/web/game.wasm &: $(OBJECTS) runtime/browser_network.js runtime/browser_host.js runtime/browser_fetch.js runtime/browser_audio.js ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a Makefile.wasm
@mkdir -p $(@D)
$(CC) $(CFLAGS) $(PORT_FLAGS) $(OBJECTS) ../local/wasm/deps/lib/libsndfile.a ../local/wasm/deps/lib/libmp3lame.a -sUSE_MPG123=1 -sWASMFS -sPROXY_TO_PTHREAD -sPTHREAD_POOL_SIZE=8 -sALLOW_BLOCKING_ON_MAIN_THREAD=0 -sMIN_WEBGL_VERSION=2 -sMAX_WEBGL_VERSION=2 -sOFFSCREENCANVAS_SUPPORT -sJSPI -sALLOW_MEMORY_GROWTH -sINITIAL_MEMORY=268435456 -sSTACK_SIZE=8388608 --js-library runtime/browser_network.js --js-library runtime/browser_host.js --js-library runtime/browser_fetch.js --js-library runtime/browser_audio.js --emit-symbol-map -o build/wasm/web/game.js
diff --git a/src/game/ppr.dll/lifted-0005.c b/src/game/ppr.dll/lifted-0005.c
@@ -11834,6 +11834,12 @@ void sub_400110E0(void) {
uint32_t _itail_tgt = 0;
RECOMP_REGS_LOCALS
RECOMP_ENTER(0x400110E0u);
+#ifdef __EMSCRIPTEN__
+ /* Start byte loading when the identity enters the resource worker queue. */
+ extern void browser_prefetch_resource(uint32_t kind, uint32_t identity);
+ uint32_t resource = MEM32(esp + 8);
+ browser_prefetch_resource(MEM32(resource), MEM32(resource + 4));
+#endif
L_400110E0:
PUSH32(esp, ebp); /* 0x400110E0: push ebp */
diff --git a/src/runtime/browser_fetch.js b/src/runtime/browser_fetch.js
@@ -1,6 +1,10 @@
addToLibrary({
+ $AOResourcePrefetch: {},
+ browser_prefetch_resource_js__deps: ['$AOResourcePrefetch'],
+ browser_prefetch_resource_js: (kind, identity) => AOResourcePrefetch.request(kind, identity),
_wasmfs_create_fetch_backend_js__deps: [
- '$wasmFS$backends', '_wasmfs_fetch_get_file_url', '_wasmfs_fetch_get_chunk_size'
+ '$wasmFS$backends', '_wasmfs_fetch_get_file_url', '_wasmfs_fetch_get_chunk_size',
+ '$AOResourcePrefetch', 'browser_prefetch_resource_ready'
],
_wasmfs_create_fetch_backend_js: async function(backend) {
const files = new Map();
@@ -177,6 +181,90 @@ addToLibrary({
return files.get(handle);
}
+ async function ensureChunks(file, first, last) {
+ // Foreground reads and speculation join the same in-flight requests.
+ const pending = [];
+ for (let index = first; index <= last; ++index) {
+ if (!file.chunks[index]) {
+ const start = index;
+ while (index < last && !file.chunks[index + 1]) ++index;
+ const end = index;
+ const request = loadChunks(file, start, end);
+ for (let chunk = start; chunk <= end; ++chunk) file.chunks[chunk] = request;
+ request.catch(() => {
+ for (let chunk = start; chunk <= end; ++chunk) delete file.chunks[chunk];
+ });
+ pending.push(request);
+ } else if (file.chunks[index] instanceof Promise) {
+ pending.push(file.chunks[index]);
+ }
+ }
+ await Promise.all(pending);
+ }
+
+ let resourceIndex, databaseHandle, resourceReads = 0;
+ const resources = [];
+ async function readResourceIndex() {
+ let handle;
+ for (const file of allocatedFiles) {
+ const url = fileURL(file);
+ if (url.endsWith('/ResourceDatabase.idx')) handle = file;
+ if (url.endsWith('/ResourceDatabase.dat')) databaseHandle = file;
+ }
+ const file = await getFile(handle);
+ await ensureChunks(file, 0, Math.ceil(file.size / file.chunkSize) - 1);
+ const bytes = new Uint8Array(file.size);
+ for (let chunk = 0; chunk < file.chunks.length; ++chunk)
+ bytes.set(file.chunks[chunk], chunk * file.chunkSize);
+
+ // Index leaves contain a little-endian data offset and big-endian identity.
+ const view = new DataView(bytes.buffer), records = new Map(), seen = new Set();
+ for (let block = view.getUint32(72, true); block; block = view.getUint32(block, true)) {
+ if (seen.has(block)) throw new Error('Resource index block cycle');
+ seen.add(block);
+ for (let entry = 0; entry < view.getUint16(block + 8, true); ++entry) {
+ const offset = block + 18 + entry * 12;
+ records.set(`${view.getUint32(offset + 4)}:${view.getUint32(offset + 8)}`,
+ view.getUint32(offset, true));
+ }
+ }
+ return records;
+ }
+
+ async function prefetchResource(offset) {
+ if (!allocatedFiles.has(databaseHandle)) return;
+ const file = await getFile(databaseHandle);
+ const chunk = Math.floor(offset / file.chunkSize);
+ if (offset < file.size) await ensureChunks(file, chunk, chunk);
+ }
+
+ function pumpResources() {
+ while (resourceReads < 4 && resources.length) {
+ ++resourceReads;
+ // Failed speculation leaves the normal read path free to retry.
+ prefetchResource(resources.shift()).catch(() => {}).finally(() => {
+ --resourceReads;
+ pumpResources();
+ });
+ }
+ }
+
+ AOResourcePrefetch.request = (kind, identity) => {
+ if (!resourceIndex) resourceIndex = readResourceIndex().catch(error => {
+ console.warn('Resource prefetch unavailable; continuing with demand reads', error);
+ return null;
+ });
+ resourceIndex.then(records => {
+ if (!records) return;
+ const offset = records.get(`${kind}:${identity}`);
+ if (offset !== undefined) {
+ resources.push(offset);
+ pumpResources();
+ }
+ });
+ };
+ _browser_prefetch_resource_ready();
+
wasmFS$backends[backend] = {
allocFile: async (file) => { allocatedFiles.add(file); soundGroups = null; },
freeFile: async (file) => { allocatedFiles.delete(file); files.delete(file); soundGroups = null; },
@@ -198,24 +286,7 @@ addToLibrary({
const first = Math.floor(offset / file.chunkSize);
const last = Math.floor((offset + length - 1) / file.chunkSize);
- // Request only missing runs; cached neighbors are never downloaded again.
- const pending = [];
- for (let index = first; index <= last; ++index) {
- if (!file.chunks[index]) {
- const start = index;
- while (index < last && !file.chunks[index + 1]) ++index;
- const end = index;
- const request = loadChunks(file, start, end);
- for (let chunk = start; chunk <= end; ++chunk) file.chunks[chunk] = request;
- request.catch(() => {
- for (let chunk = start; chunk <= end; ++chunk) delete file.chunks[chunk];
- });
- pending.push(request);
- } else if (file.chunks[index] instanceof Promise) {
- pending.push(file.chunks[index]);
- }
- }
- await Promise.all(pending);
+ await ensureChunks(file, first, last);
for (let index = first; index <= last; ++index) {
const start = Math.max(offset, index * file.chunkSize);
const end = Math.min(offset + length, (index + 1) * file.chunkSize);
diff --git a/src/runtime/browser_host.c b/src/runtime/browser_host.c
@@ -5,10 +5,42 @@
#include <unistd.h>
#include <fcntl.h>
#include <assert.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <emscripten/proxying.h>
char *ao_asset_manifest(const char *base);
char *ao_asset_base_url(void);
+static em_proxying_queue *resource_queue;
+static pthread_t resource_thread;
+void browser_prefetch_resource_js(uint32_t kind, uint32_t identity);
+
+void browser_prefetch_resource_ready(void)
+{
+ resource_queue = em_proxying_queue_create();
+ assert(resource_queue);
+ resource_thread = pthread_self();
+}
+
+static void prefetch_resource(void *argument)
+{
+ uint32_t *identity = argument;
+ browser_prefetch_resource_js(identity[0], identity[1]);
+ free(identity);
+}
+
+void browser_prefetch_resource(uint32_t kind, uint32_t identity)
+{
+ /* Only bytes are prefetched; guest object construction keeps its ordering. */
+ uint32_t *request = malloc(2 * sizeof(uint32_t));
+ assert(request);
+ request[0] = kind;
+ request[1] = identity;
+ if (!emscripten_proxy_async(resource_queue, resource_thread, prefetch_resource, request))
+ free(request);
+}
+
void browser_initialize(void)
{
/* FetchFS performs range requests on its own worker while game threads wait. */
diff --git a/src/tests/browser_fetch.mjs b/src/tests/browser_fetch.mjs
@@ -15,7 +15,7 @@ async function fixture(bytes, wholeFile = false, storage, version = '"one"') {
UTF8ToString: value => value,
__wasmfs_fetch_get_file_url: () => 'http://example.test/browser-assets//asset',
__wasmfs_fetch_get_chunk_size: () => 4,
- wasmFS$backends: {},
+ wasmFS$backends: {}, AOResourcePrefetch: {}, _browser_prefetch_resource_ready: () => {},
addToLibrary: value => { library = value; },
fetch: async (url, options) => {
if (url === 'http://example.test/browser-manifest') {
diff --git a/src/tests/browser_prefetch.mjs b/src/tests/browser_prefetch.mjs
@@ -13,7 +13,8 @@ const context = vm.createContext({Map, Set, URL, Response, Uint8Array, console,
return 'http://example.test/browser-assets//cd_image/sound/sfx/foots/' + names.get(handle);
},
__wasmfs_fetch_get_chunk_size: () => 1048576,
- wasmFS$backends:{}, addToLibrary:value => { library = value; },
+ wasmFS$backends:{}, AOResourcePrefetch:{}, _browser_prefetch_resource_ready:() => {},
+ addToLibrary:value => { library = value; },
setTimeout:callback => timers.push(callback),
fetch:url => url === 'http://example.test/browser-manifest'
? Promise.resolve(Response.json(Object.fromEntries([...names.values()].map(name =>
diff --git a/src/tests/browser_resource_prefetch.mjs b/src/tests/browser_resource_prefetch.mjs
@@ -0,0 +1,110 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+
+const index = new Uint8Array(256), view = new DataView(index.buffer);
+view.setUint32(72, 128, true);
+view.setUint16(136, 7, true);
+for (const [entry, identity, offset] of [[0,17,64],[1,18,128],[2,19,192],
+ [3,20,256],[4,21,320],[5,22,384],[6,23,448]]) {
+ view.setUint32(146 + entry * 12, offset, true);
+ view.setUint32(150 + entry * 12, 1010004);
+ view.setUint32(154 + entry * 12, identity);
+}
+const database = Uint8Array.from({length:512}, (_, i) => i % 251);
+const requests = [], pending = new Map(), warnings = [];
+let library, ready = 0;
+const context = vm.createContext({Map, Set, URL, Response, Uint8Array, DataView,
+ HEAPU8:new Uint8Array(64), AOResourcePrefetch:{}, wasmFS$backends:{},
+ console:{warn:(...args) => warnings.push(args)},
+ _browser_prefetch_resource_ready:() => ++ready,
+ UTF8ToString:value => value,
+ __wasmfs_fetch_get_file_url:handle => 'http://example.test/browser-assets//cd_image/data/db/ResourceDatabase.' + (handle === 1 ? 'idx' : 'dat'),
+ __wasmfs_fetch_get_chunk_size:() => 64,
+ addToLibrary:value => { library = value; },
+ setTimeout,
+ fetch:async (url, options) => {
+ if (url.endsWith('/browser-manifest')) return Response.json({
+ 'cd_image/data/db/ResourceDatabase.idx':{size:256,version:'"one"'},
+ 'cd_image/data/db/ResourceDatabase.dat':{size:512,version:'"one"'},
+ });
+ const bytes = url.endsWith('.idx') ? index : database;
+ const [start, end] = options.headers.Range.slice(6).split('-').map(Number);
+ if (bytes === database) {
+ requests.push(start);
+ if (start) {
+ const status = await new Promise(resolve => pending.set(start, resolve));
+ pending.delete(start);
+ if (status !== 206) return new Response(null, {status});
+ }
+ }
+ return new Response(bytes.slice(start, end + 1), {status:206,
+ headers:{'Content-Range':`bytes ${start}-${end}/${bytes.length}`,ETag:'"one"'}});
+ },
+});
+let source = fs.readFileSync(new URL('../runtime/browser_fetch.js', import.meta.url), 'utf8');
+for (const [name, value] of Object.entries({EROFS:69,ENOENT:44,EBADF:8}))
+ source = source.replaceAll('{{{ cDefs.' + name + ' }}}', String(value));
+vm.runInContext(source, context);
+await library._wasmfs_create_fetch_backend_js(1);
+const backend = context.wasmFS$backends[1];
+await backend.allocFile(1);
+await backend.allocFile(2);
+const settle = () => new Promise(setImmediate);
+
+for (const identity of [17,18,19,20,21,22,23,18,999])
+ assert.equal(library.browser_prefetch_resource_js(1010004, identity), undefined);
+await settle();
+assert.deepEqual(requests, [0,64,128,192,256]);
+assert.equal(pending.size, 4);
+
+// A foreground reader joins speculation without issuing a second HTTP request.
+const foreground = backend.read(2, 0, 1, 130);
+await settle();
+assert.deepEqual(requests, [0,64,128,192,256]);
+pending.get(128)(206);
+assert.equal(await foreground, 1);
+assert.equal(context.HEAPU8[0], 130);
+await settle();
+assert.deepEqual(requests, [0,64,128,192,256,320]);
+
+// A failed speculative request can be retried by the normal read path.
+pending.get(192)(503);
+await settle();
+const retry = backend.read(2, 1, 1, 192);
+await settle();
+assert.equal(requests.filter(offset => offset === 192).length, 2);
+pending.get(192)(206);
+assert.equal(await retry, 1);
+assert.equal(context.HEAPU8[1], 192);
+
+// Removing the file drops remaining queued work; active requests may finish.
+await backend.freeFile(2);
+for (const resolve of pending.values()) resolve(206);
+await settle();
+
+assert.equal(ready, 1);
+assert.equal(pending.size, 0);
+assert.equal(requests.includes(448), false);
+assert.equal(requests.filter(offset => offset === 128).length, 1);
+assert.deepEqual(warnings, []);
+console.log('PASS: resource index hints, bounded byte prefetch, joined demand reads, failure retry and freed-file skip');
+
+view.setUint32(128, 128, true);
+await library._wasmfs_create_fetch_backend_js(2);
+const invalidIndex = context.wasmFS$backends[2];
+await invalidIndex.allocFile(1);
+await invalidIndex.allocFile(2);
+requests.length = 0;
+
+library.browser_prefetch_resource_js(1010004, 17);
+await settle();
+assert.deepEqual(requests, []);
+const ordinaryRead = await invalidIndex.read(2, 0, 1, 0);
+
+assert.equal(ordinaryRead, 1);
+assert.equal(context.HEAPU8[0], 0);
+assert.deepEqual(requests, [0]);
+assert.equal(warnings.length, 1);
+assert.equal(warnings[0][1].message, 'Resource index block cycle');
+console.log('PASS: invalid speculative index falls back to ordinary demand reads');
diff --git a/src/tests/browser_resource_queue.c b/src/tests/browser_resource_queue.c
@@ -0,0 +1,65 @@
+#include <assert.h>
+#include <emscripten.h>
+#include <pthread.h>
+#include <stdint.h>
+#include <stdio.h>
+
+void browser_prefetch_resource_ready(void);
+void browser_prefetch_resource(uint32_t kind, uint32_t identity);
+
+static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
+static pthread_cond_t condition = PTHREAD_COND_INITIALIZER;
+static int ready, entered, released, received;
+static uint32_t kinds[3], identities[3];
+
+void browser_prefetch_resource_js(uint32_t kind, uint32_t identity)
+{
+ assert(!pthread_mutex_lock(&mutex));
+ entered = 1;
+ assert(!pthread_cond_broadcast(&condition));
+ while (!released) assert(!pthread_cond_wait(&condition, &mutex));
+ assert(received < 3);
+ kinds[received] = kind;
+ identities[received++] = identity;
+ assert(!pthread_cond_broadcast(&condition));
+ assert(!pthread_mutex_unlock(&mutex));
+}
+
+static void *receiver(void *unused)
+{
+ browser_prefetch_resource_ready();
+ assert(!pthread_mutex_lock(&mutex));
+ ready = 1;
+ assert(!pthread_cond_broadcast(&condition));
+ assert(!pthread_mutex_unlock(&mutex));
+ emscripten_exit_with_live_runtime();
+}
+
+int main(void)
+{
+ pthread_t thread;
+ assert(!pthread_create(&thread, NULL, receiver, NULL));
+ assert(!pthread_mutex_lock(&mutex));
+ while (!ready) assert(!pthread_cond_wait(&condition, &mutex));
+ assert(!pthread_mutex_unlock(&mutex));
+
+ browser_prefetch_resource(1010004, 17);
+ assert(!pthread_mutex_lock(&mutex));
+ while (!entered) assert(!pthread_cond_wait(&condition, &mutex));
+ assert(!pthread_mutex_unlock(&mutex));
+
+ /* The receiver remains blocked until both submissions have returned. */
+ browser_prefetch_resource(1010001, 42);
+ browser_prefetch_resource(1010026, 99);
+ assert(!pthread_mutex_lock(&mutex));
+ assert(!received);
+ released = 1;
+ assert(!pthread_cond_broadcast(&condition));
+ while (received != 3) assert(!pthread_cond_wait(&condition, &mutex));
+
+ assert(kinds[0] == 1010004 && identities[0] == 17);
+ assert(kinds[1] == 1010001 && identities[1] == 42);
+ assert(kinds[2] == 1010026 && identities[2] == 99);
+ assert(!pthread_mutex_unlock(&mutex));
+ puts("PASS: resource hints enqueue while the receiver is blocked; captured identities arrive in order");
+}