commit 679ef6cb15af0c45a8786f5324787d7552295863
parent ce17241701142b5c0231fa541385d11e3905b05a
Author: anon <anon@example.com>
Date: Sat, 17 Oct 2026 01:40:39 +0000
Add an isolated WASM playfield sweep with movement and frame captures
Diffstat:
8 files changed, 558 insertions(+), 27 deletions(-)
diff --git a/docs/playfield-validation.md b/docs/playfield-validation.md
@@ -1,5 +1,46 @@
# Playfield coverage
+## Browser sweep
+
+The WASM sweep has its own run directory and results. Native passes do not
+count toward browser coverage. Build the WASM dependencies and unpack runtime
+assets using the [developer guide](../DEVELOPERS.md), then run:
+
+```sh
+python3 tools/client/build_browser_sweep.py
+python3 tools/client/sweep_browser.py
+```
+
+Open `http://127.0.0.1:8082/wasm/sweep.html` in a browser with the required
+WASM/OffscreenCanvas support and press **Start WASM sweep**. Leave that tab open.
+The controller reserves ports 7520, 7521, 8082 and 8083 and owns an isolated
+character, server and settings directory. It needs the desktop's usual
+`DISPLAY`/`XAUTHORITY` environment for its display-awake inhibitor.
+
+The test build adds a small presentation/capture adapter to the production WASM
+objects. It reports actual game presentations once a second and reads back the
+rendered framebuffer only when an arrival test finishes. It does not publish
+over the committed client. The run keeps its own module and build digest.
+
+Every scene waits for `CharacterReady`, then holds left-arrow for 0.6 seconds
+and `W` for one second, after a one-second settling delay. Inputs pass through
+the browser's canvas keyboard events. The controller records the server's
+position and rotation before and after input. At least ten seconds and 30
+presentations after readiness are required before capturing a PNG. A browser
+worker error, 180-second timeout or unintended zone crossing is recorded as a
+failure and retried with a fresh iframe/client. After the transition pass, each
+scene is tested with a fresh client. Screenshots still require visual review;
+these are arrival smoke tests, not exhaustive exploration of each playfield.
+
+Results are appended to `local/playfield-sweep/wasm-sweep-*/results.jsonl`,
+alongside per-scene logs and screenshots. Stop with Ctrl-C and close the test
+tab. Resume by passing that run directory to `sweep_browser.py`, reopening its
+page and pressing Start. Completed rows are retained. Resumption uses the
+run's saved module and starts a fresh client at the first unfinished playfield;
+it does not preserve the previous browser's cache or memory-growth history.
+
+## Native sweep
+
The native sweep uses an isolated character and server, exercises the real
teleport/reconnect protocol, and then repeats each scene with a fresh client.
It retains logs, screenshots, frame counts, loading times and resident memory.
diff --git a/tools/client/build_browser_sweep.py b/tools/client/build_browser_sweep.py
@@ -0,0 +1,43 @@
+"""Link the current WASM objects with a test-only presentation/capture adapter."""
+import os
+import hashlib
+import json
+import pathlib
+import shlex
+import subprocess
+
+root = pathlib.Path(__file__).resolve().parents[2]
+output = root / 'local/playfield-sweep/browser-build'
+output.mkdir(parents=True, exist_ok=True)
+compiler = root / 'toolchains/emsdk/upstream/emscripten/emcc'
+subprocess.run(['make', '-f', 'Makefile.wasm', '-j4', 'objects'], cwd=root / 'src', check=True)
+subprocess.run([str(compiler), '-O2', '-pthread', '-Isrc/runtime', '-c',
+ 'tools/client/sweep_browser_capture.c', '-o', str(output / 'capture.o')], cwd=root, check=True)
+
+# Reuse the production link flags; the adapter adds no production runtime switches.
+plan = subprocess.check_output(['make', '-f', 'Makefile.wasm', '-n', '-W',
+ 'Makefile.wasm', 'build/wasm/web/game.js'], cwd=root / 'src', text=True)
+commands = [shlex.split(line) for line in plan.splitlines()
+ if line.startswith('../toolchains/emsdk/upstream/emscripten/emcc ')
+ and line.endswith('-o build/wasm/web/game.js')]
+assert len(commands) == 1
+command = commands[0]
+command[-1] = str(output / 'sweep-game.js')
+command += [str(output / 'capture.o'), '-Wl,--wrap=gl_target_present']
+subprocess.run(command, cwd=root / 'src', env={**os.environ, 'BINARYEN_CORES': '8'}, check=True)
+
+# Tie each sweep to the linked module and the source inputs, not a later checkout.
+inputs = subprocess.check_output(['git', 'ls-files', 'src'], cwd=root, text=True).splitlines()
+inputs.append('tools/client/sweep_browser_capture.c')
+digest = hashlib.sha256()
+for name in inputs:
+ digest.update(name.encode() + b'\0')
+ digest.update((root / name).read_bytes())
+with (output / 'sweep-game.wasm').open('rb') as module:
+ module_hash = hashlib.file_digest(module, 'sha256').hexdigest()
+metadata = {
+ 'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip(),
+ 'source_sha256': digest.hexdigest(), 'module_sha256': module_hash,
+ 'compiler': subprocess.check_output([str(compiler), '--version'], text=True).splitlines()[0],
+}
+(output / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n')
diff --git a/tools/client/playfield_catalog.py b/tools/client/playfield_catalog.py
@@ -0,0 +1,35 @@
+"""Release-backed playfield catalog shared by the native and browser sweeps."""
+import json
+import re
+
+import tools.data.ao_database
+
+
+def read(root, assets):
+ # Reconcile the server catalog with actual release definitions, including exclusions.
+ database = tools.data.ao_database.Database(assets)
+ catalog = []
+ for line in (root / 'server/playfields.go').read_text().splitlines():
+ match = re.match(r'\s+(\d+):\s+\{name: ("(?:[^"\\]|\\.)*")(.*)', line)
+ if not match:
+ continue
+ identity = int(match[1])
+ row = {'id': identity, 'name': json.loads(match[2])}
+ if (1000001, identity) not in database.records:
+ row['skip'] = 'no playfield definition in 14.9.1'
+ elif 'unavailable: true' in match[3]:
+ row['skip'] = 'dependency-only entry in server catalog'
+ catalog.append(row)
+ known = {row['id'] for row in catalog}
+ for kind, identity in database.records:
+ if kind == 1000001 and identity not in known:
+ row = {'id': identity, 'name': database.read(kind, identity)[8:40].split(b'\0')[0].decode('ascii').strip()}
+ if identity in [101, 105]:
+ row['skip'] = 'door-link dependency or developer graphics test area'
+ elif identity == 1673:
+ row['skip'] = 'empty definition: zero zones, zero districts, no outdoor ground'
+ else:
+ row['skip'] = 'not in server catalog; investigate arrival'
+ catalog.append(row)
+ database.close()
+ return catalog
diff --git a/tools/client/sweep_browser.html b/tools/client/sweep_browser.html
@@ -0,0 +1,79 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<title>AO WASM playfield sweep</title>
+<style>
+body { background: #111; color: #ddd; font: 16px sans-serif; }
+iframe { width: 1040px; height: 790px; border: 0; }
+pre { white-space: pre-wrap; }
+</style>
+<button id="start">Start WASM sweep</button>
+<pre id="status">Ready</pre>
+<iframe id="game" title="AO WASM client"></iframe>
+<pre id="result"></pre>
+<script>
+const status = document.querySelector('#status');
+const frame = document.querySelector('#game');
+let instance = 0, frames = 0, frameTime = 0, input = null, error = '', log = '';
+let inputRequested = false, captureRequested = false, screenshot = null;
+window.addEventListener('message', event => {
+ if (event.origin !== location.origin || event.source !== frame.contentWindow) return;
+ const message = event.data;
+ if (message.instance !== instance) return;
+ if (message.kind === 'frame') { frames = message.frames; frameTime = message.time; }
+ if (message.kind === 'log') log += message.text + '\n';
+ if (message.kind === 'error') error = message.text;
+ if (message.kind === 'input') input = message.events;
+ if (message.kind === 'capture') screenshot = message.png;
+});
+async function request(path, body) {
+ const response = await fetch('http://127.0.0.1:8083' + path, {
+ method: 'POST', headers: {'Content-Type': 'application/json'}, body: JSON.stringify(body)
+ });
+ if (!response.ok) throw new Error(await response.text());
+ return response.json();
+}
+document.querySelector('#start').onclick = async event => {
+ event.target.disabled = true;
+ window.sweepAudio = new AudioContext();
+ await window.sweepAudio.resume();
+ try {
+ while (true) {
+ const command = await request('/tick', {instance, frames, frame_time: frameTime,
+ input, error, user_agent: navigator.userAgent});
+ status.textContent = JSON.stringify(command);
+ if (command.action === 'done') break;
+ if (command.action === 'unload' && instance !== 0) {
+ frame.src = 'about:blank';
+ instance = 0;
+ }
+ if (command.action === 'launch') {
+ instance = command.instance;
+ frames = 0; frameTime = 0; input = null; error = ''; log = '';
+ inputRequested = captureRequested = false; screenshot = null;
+ frame.src = 'sweep-client.html?instance=' + instance;
+ }
+ if (command.action === 'input' && !inputRequested) {
+ inputRequested = true;
+ frame.contentWindow.sweepInput();
+ }
+ if (command.action === 'capture' && !captureRequested) {
+ captureRequested = true;
+ frame.contentWindow.Module._sweep_capture();
+ }
+ if (command.action === 'finish' || (command.action === 'capture' && screenshot)) {
+ const result = await request('/finish', {instance, log, screenshot, input});
+ document.querySelector('#result').textContent = JSON.stringify(result, null, 2);
+ input = null; inputRequested = captureRequested = false; screenshot = null; log = '';
+ }
+ await new Promise(resolve => setTimeout(resolve, 250));
+ }
+ frame.src = 'about:blank';
+ await window.sweepAudio.close();
+ } catch (failure) {
+ status.textContent = 'Sweep controller failed: ' + failure.stack;
+ throw failure;
+ }
+};
+</script>
+</html>
diff --git a/tools/client/sweep_browser.py b/tools/client/sweep_browser.py
@@ -0,0 +1,258 @@
+"""Run an isolated WASM sweep; open the printed URL and press Start WASM sweep."""
+import base64
+import hashlib
+import html
+import http.server
+import json
+import pathlib
+import re
+import shutil
+import socket
+import subprocess
+import sys
+import time
+import urllib.parse
+import urllib.request
+
+root = pathlib.Path(__file__).resolve().parents[2]
+sys.path.insert(0, str(root))
+import tools.client.playfield_catalog
+
+work = root / 'local/playfield-sweep'
+assert len(sys.argv) <= 2, 'usage: sweep_browser.py [previous-run-directory]'
+resuming = len(sys.argv) == 2
+output = pathlib.Path(sys.argv[1]).resolve() if resuming else work / ('wasm-sweep-' + time.strftime('%Y%m%d-%H%M%S'))
+build = work / 'browser-build'
+assert (build / 'sweep-game.wasm').exists(), 'Build objects and run build_browser_sweep.py first'
+for port in [7520, 7521, 8082, 8083]:
+ with socket.socket() as connection:
+ assert connection.connect_ex(('127.0.0.1', port)) != 0, port
+subprocess.run(['go', 'build', '-o', str(work / 'server'), './server'], cwd=root, check=True)
+
+# Isolate the character and writable settings; keep immutable game assets shared.
+fixture = output / 'server'
+if not resuming:
+ (fixture / 'data').mkdir(parents=True)
+ (fixture / 'client').mkdir()
+ assets = fixture / 'anarchy-assets-14.9.1'
+ assets.mkdir()
+ for source in (root / 'anarchy-assets-14.9.1').iterdir():
+ if source.name in ['cd_image', 'fonts']:
+ (assets / source.name).symlink_to(source)
+ elif source.is_dir():
+ shutil.copytree(source, assets / source.name)
+ else:
+ shutil.copy2(source, assets / source.name)
+ for name in ['terrain.bin', 'zone_links.yaml', 'npc_spawns.yaml', 'maps']:
+ (fixture / 'data' / name).symlink_to(root / 'data' / name)
+ (fixture / 'runtime').symlink_to(root / 'runtime')
+ (fixture / '.runtime-bundle').write_text(hashlib.sha256((root / 'runtime/manifest.json').read_bytes()).hexdigest() + '\n')
+ (fixture / 'data/users.yaml').write_text('- id: 73\n name: WASM Sweep\n playfield: 705\n position: [960, 16.5, 510]\n rotation: [0, 0, 0, 1]\n appearance: 789\n monster_data: 0\n level: 1\n')
+ for name in ['sweep-game.js', 'sweep-game.wasm']:
+ shutil.copyfile(build / name, fixture / 'client' / name)
+ shutil.copyfile(build / 'build.json', output / 'client-build.json')
+for source, target in [('sweep_browser.html', 'sweep.html'), ('sweep_browser_client.html', 'sweep-client.html')]:
+ shutil.copyfile(root / 'tools/client' / source, fixture / 'client' / target)
+
+catalog = tools.client.playfield_catalog.read(root, fixture / 'anarchy-assets-14.9.1')
+priority = [120, 127, 1931, 4107, 152, 124, 641, 706, 4704, 705, 695]
+zones = sorted([row for row in catalog if 'skip' not in row], key=lambda row: (priority.index(row['id']) if row['id'] in priority else len(priority), row['id']))
+with (fixture / 'client/sweep-game.wasm').open('rb') as module:
+ module_hash = hashlib.file_digest(module, 'sha256').hexdigest()
+assert json.loads((output / 'client-build.json').read_text())['module_sha256'] == module_hash
+metadata = {
+ 'source_commit': subprocess.check_output(['git', 'rev-parse', 'HEAD'], cwd=root, text=True).strip(),
+ 'working_diff': subprocess.check_output(['git', 'diff', 'HEAD'], cwd=root, text=True),
+ 'module_sha256': module_hash, 'started': time.time(), 'client': 'WASM/WebGL browser',
+ 'coverage': 'CharacterReady, ten seconds and 30 presented frames, turn/walk, server pose and screenshot; screenshots require visual review',
+ 'resume_behavior': 'fresh browser client at the first unfinished playfield',
+}
+completed = {}
+if resuming:
+ assert json.loads((output / 'catalog.json').read_text()) == catalog
+ assert json.loads((output / 'build.json').read_text())['module_sha256'] == module_hash
+ if (output / 'results.jsonl').exists():
+ for line in (output / 'results.jsonl').read_text().splitlines():
+ row = json.loads(line)
+ completed[row['phase'], row['id']] = row
+ (output / ('resume-' + time.strftime('%Y%m%d-%H%M%S') + '.json')).write_text(json.dumps(metadata, indent=2) + '\n')
+else:
+ (output / 'build.json').write_text(json.dumps(metadata, indent=2) + '\n')
+ (output / 'catalog.json').write_text(json.dumps(catalog, indent=2) + '\n')
+queue = [(phase, zone) for phase in ['transition', 'cold'] for zone in zones if (phase, zone['id']) not in completed]
+for zone in reversed(zones):
+ previous = completed.get(('transition', zone['id']))
+ if previous and previous['status'] != 'ready-and-rendering' and ('cold-repro', zone['id']) not in completed:
+ queue.insert(0, ('cold-repro', zone))
+active = None
+instance = 0
+need_launch = True
+disconnect_started = None
+
+
+def request(path, fields=None):
+ data = urllib.parse.urlencode(fields).encode() if fields is not None else None
+ return urllib.request.urlopen('http://127.0.0.1:8082' + path, data, timeout=10).read()
+
+
+def character_pose():
+ page = request('/users/73').decode()
+ data = html.unescape(re.search(r'<textarea[^>]*>(.*?)</textarea>', page, re.S)[1])
+ return {field: json.loads(re.search(r'^' + field + r': (\[.*\])$', data, re.M)[1])
+ for field in ['position', 'rotation']}
+
+
+def tick(message):
+ global active, instance, need_launch, disconnect_started
+ player = json.loads(request('/map-players'))['players'][0]
+ if active is None:
+ if not queue:
+ return {'action': 'done'}
+ phase, zone = queue[0]
+ need_launch = need_launch or phase != 'transition'
+ if need_launch and player['connected']:
+ if disconnect_started is None:
+ disconnect_started = time.time()
+ assert time.time() - disconnect_started < 10, 'server did not observe browser disconnect'
+ return {'action': 'unload'}
+ disconnect_started = None
+ queue.pop(0)
+ log_start = (output / 'server.log').stat().st_size
+ request('/teleport/73', {'playfield': zone['id']})
+ request('/time', {'hour': 13, 'minute': 30})
+ active = dict(zone, phase=phase, started=time.time(), status='loading',
+ server_log_start=log_start, cold_start=need_launch, user_agent=message['user_agent'])
+ if need_launch:
+ instance += 1
+ need_launch = False
+ active['instance'] = instance
+ return {'action': 'launch', 'instance': instance, 'id': zone['id'], 'phase': phase}
+ active['instance'] = instance
+ player = json.loads(request('/map-players'))['players'][0]
+
+ # Main-page heartbeats remain responsive even if the game worker faults or blocks.
+ assert message['instance'] == instance
+ elapsed = time.time() - active['started']
+ if message['error']:
+ active.update(status='client-error', error=message['error'])
+ elif elapsed >= 180:
+ active['status'] = 'timeout'
+ elif 'ready_time' in active and player['playfield'] != active['id']:
+ active.update(status='zoned-during-movement', destination=player['playfield'])
+ if active['status'] not in ['loading', 'ready', 'capturing']:
+ return {'action': 'finish', 'id': active['id'], 'status': active['status']}
+
+ if 'ready_time' not in active and player['connected'] and player['playfield'] == active['id']:
+ with (output / 'server.log').open('rb') as log:
+ log.seek(active['server_log_start'])
+ received = log.read()
+ if re.search(rb'World C2S: dfdf000a[0-9a-f]{24}570c20390000c3500000004901', received):
+ active.update(status='ready', ready_time=time.time(), ready_seconds=elapsed,
+ input_before=character_pose(), character_ready=True)
+ if 'ready_time' in active:
+ if message['frame_time'] / 1000 >= active['ready_time']:
+ if 'first_frame' not in active:
+ active['first_frame'] = {'frames': message['frames'], 'time': message['frame_time'] / 1000}
+ active['last_frame'] = {'frames': message['frames'], 'time': message['frame_time'] / 1000}
+ if message['input'] is None:
+ return {'action': 'input', 'id': active['id'], 'phase': active['phase']}
+ if 'first_frame' in active:
+ duration = active['last_frame']['time'] - active['first_frame']['time']
+ frames = active['last_frame']['frames'] - active['first_frame']['frames']
+ if duration >= 10 and frames >= 30:
+ if active['status'] != 'capturing':
+ active.update(status='capturing', capture_started=time.time(), frames=frames, fps=frames / duration)
+ if time.time() - active['capture_started'] > 10:
+ active['status'] = 'capture-timeout'
+ return {'action': 'finish', 'id': active['id'], 'status': active['status']}
+ return {'action': 'capture', 'id': active['id'], 'phase': active['phase']}
+ return {'action': 'wait', 'id': active['id'], 'phase': active['phase'], 'elapsed': round(elapsed, 1)}
+
+
+def finish(message):
+ global active, need_launch
+ assert active is not None and message['instance'] == instance
+ name = f'{active["phase"]}-{active["id"]}'
+ if message['screenshot'] is not None:
+ pixels = base64.b64decode(message['screenshot'], validate=True)
+ assert pixels.startswith(b'\x89PNG\r\n\x1a\n')
+ (output / (name + '.png')).write_bytes(pixels)
+ active['screenshot'] = name + '.png'
+ assert active['status'] == 'capturing'
+ active['status'] = 'ready-and-rendering'
+ active.update(elapsed_seconds=time.time() - active['started'], log=name + '.log')
+ (output / active['log']).write_text(message['log'])
+ if 'input_before' in active:
+ active['input_after'] = character_pose()
+ active['input_events'] = message['input']
+ active['movement_observed'] = sum((active['input_before']['position'][axis]
+ - active['input_after']['position'][axis]) ** 2 for axis in [0, 2]) > .01
+ active['rotation_observed'] = abs(sum(a * b for a, b in zip(
+ active['input_before']['rotation'], active['input_after']['rotation']))) < .999
+ with (output / 'results.jsonl').open('a') as results:
+ results.write(json.dumps(active) + '\n')
+ print(json.dumps(active), flush=True)
+ if active['status'] != 'ready-and-rendering':
+ need_launch = True
+ if active['phase'] == 'transition' and ('cold-repro', active['id']) not in completed:
+ queue.insert(0, ('cold-repro', {'id': active['id'], 'name': active['name']}))
+ result = active
+ active = None
+ return result
+
+
+class Controller(http.server.BaseHTTPRequestHandler):
+ def log_message(self, format, *args):
+ pass
+
+ def do_OPTIONS(self):
+ self.respond({})
+
+ def do_POST(self):
+ if self.headers.get('Origin') != 'http://127.0.0.1:8082':
+ self.send_error(403)
+ return
+ size = int(self.headers['Content-Length'])
+ assert 0 < size < 16 * 1024 * 1024
+ message = json.loads(self.rfile.read(size))
+ if self.path == '/tick':
+ self.respond(tick(message))
+ elif self.path == '/finish':
+ self.respond(finish(message))
+ else:
+ self.send_error(404)
+
+ def respond(self, result):
+ body = json.dumps(result).encode()
+ self.send_response(200)
+ self.send_header('Access-Control-Allow-Origin', 'http://127.0.0.1:8082')
+ self.send_header('Access-Control-Allow-Methods', 'POST, OPTIONS')
+ self.send_header('Access-Control-Allow-Headers', 'Content-Type')
+ self.send_header('Content-Type', 'application/json')
+ self.send_header('Content-Length', str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+
+with (output / 'server.log').open('a') as server_log:
+ inhibitor = subprocess.Popen(['gnome-session-inhibit', '--reason', 'AO WASM playfield coverage', '--inhibit-only'], stdout=server_log, stderr=server_log)
+ server = subprocess.Popen([str(work / 'server'), '-login-port', '7520', '-world-port', '7521', '-http-port', '8082'], cwd=fixture, stdout=server_log, stderr=server_log)
+ try:
+ subprocess.run(['xset', 'dpms', 'force', 'on'], check=True)
+ for attempt in range(60):
+ assert server.poll() is None
+ with socket.socket() as connection:
+ if connection.connect_ex(('127.0.0.1', 8082)) == 0:
+ break
+ time.sleep(1)
+ print(output, '\nOpen http://127.0.0.1:8082/wasm/sweep.html', flush=True)
+ with http.server.HTTPServer(('127.0.0.1', 8083), Controller) as controller:
+ controller.timeout = 1
+ while True:
+ assert server.poll() is None
+ controller.handle_request()
+ finally:
+ server.terminate()
+ server.wait(timeout=10)
+ inhibitor.terminate()
+ inhibitor.wait(timeout=10)
diff --git a/tools/client/sweep_browser_capture.c b/tools/client/sweep_browser_capture.c
@@ -0,0 +1,44 @@
+#include "gl_renderer.h"
+#include <assert.h>
+#include <stdatomic.h>
+#include <stdlib.h>
+#include <GLES3/gl3.h>
+#include <emscripten.h>
+
+static atomic_int capture_requested;
+
+EMSCRIPTEN_KEEPALIVE void sweep_capture(void)
+{
+ atomic_store(&capture_requested, 1);
+}
+
+void __real_gl_target_present(struct gl_target *, const int32_t *, int, int);
+
+void __wrap_gl_target_present(struct gl_target *target, const int32_t rectangle[4], int width, int height)
+{
+ static unsigned frames;
+ static double reported;
+ __real_gl_target_present(target, rectangle, width, height);
+
+ /* Report actual game presentations, independently of the browser UI timer. */
+ ++frames;
+ double now = emscripten_get_now();
+ if (now - reported >= 1000) {
+ double timestamp = EM_ASM_DOUBLE({ return Date.now(); });
+ MAIN_THREAD_ASYNC_EM_ASM({ Module.sweepFrame($0, $1); }, frames, timestamp);
+ reported = now;
+ }
+
+ /* Read back only at the end of an arrival test, on the GL context's worker. */
+ if (atomic_exchange(&capture_requested, 0)) {
+ unsigned char *pixels = malloc((size_t)width * height * 4);
+ assert(pixels);
+ glBindFramebuffer(GL_READ_FRAMEBUFFER, 0);
+ glReadPixels(0, 0, width, height, GL_RGBA, GL_UNSIGNED_BYTE, pixels);
+ assert(glGetError() == GL_NO_ERROR);
+ MAIN_THREAD_EM_ASM({
+ Module.sweepCapture(HEAPU8.slice($0, $0 + $1 * $2 * 4), $1, $2);
+ }, pixels, width, height);
+ free(pixels);
+ }
+}
diff --git a/tools/client/sweep_browser_client.html b/tools/client/sweep_browser_client.html
@@ -0,0 +1,56 @@
+<!doctype html>
+<html lang="en">
+<meta charset="utf-8">
+<title>AO sweep client</title>
+<style>body { margin: 0; background: #111; } canvas { display: block; }</style>
+<canvas id="canvas" width="1024" height="768" tabindex="0"></canvas>
+<script>
+const canvas = document.querySelector('#canvas');
+const instance = Number(new URLSearchParams(location.search).get('instance'));
+function report(message) { parent.postMessage({...message, instance}, location.origin); }
+window.addEventListener('error', event => report({kind: 'error', text: event.message}));
+window.addEventListener('unhandledrejection', event => report({kind: 'error', text: String(event.reason)}));
+var Module = {
+ canvas, audioContext: parent.sweepAudio,
+ print: text => report({kind: 'log', text}),
+ printErr: text => report({kind: 'log', text}),
+ onAbort: text => report({kind: 'error', text: String(text)}),
+ onRuntimeInitialized: () => canvas.focus(),
+ sweepFrame: (frames, time) => report({kind: 'frame', frames, time}),
+ sweepCapture: (pixels, width, height) => {
+ const capture = document.createElement('canvas');
+ capture.width = width; capture.height = height;
+ const image = new ImageData(width, height);
+ for (let row = 0; row < height; ++row)
+ image.data.set(pixels.subarray(row * width * 4, (row + 1) * width * 4), (height - row - 1) * width * 4);
+ capture.getContext('2d').putImageData(image, 0, 0);
+ report({kind: 'capture', png: capture.toDataURL('image/png').split(',')[1]});
+ }
+};
+async function sweepInput() {
+ // Match the native sweep: settle, turn left for 600 ms, then walk for one second.
+ canvas.focus();
+ const started = performance.now(), events = [];
+ for (const [delay, type, key, code, keyCode] of [
+ [1000, 'keydown', 'ArrowLeft', 'ArrowLeft', 37],
+ [600, 'keyup', 'ArrowLeft', 'ArrowLeft', 37],
+ [200, 'keydown', 'w', 'KeyW', 87],
+ [1000, 'keyup', 'w', 'KeyW', 87]
+ ]) {
+ await new Promise(resolve => setTimeout(resolve, delay));
+ canvas.dispatchEvent(new KeyboardEvent(type, {key, code, keyCode, which: keyCode, bubbles: true}));
+ events.push({time: (performance.now() - started) / 1000, type, key});
+ }
+ report({kind: 'input', events});
+}
+(async () => {
+ const response = await fetch('/browser-launch', {method: 'POST'});
+ if (!response.ok) throw new Error(await response.text());
+ Module.arguments = (await response.text()).trim().split(' ').slice(1);
+ const script = document.createElement('script');
+ script.src = 'sweep-game.js';
+ script.onerror = () => report({kind: 'error', text: 'Client script failed to load'});
+ document.body.append(script);
+})();
+</script>
+</html>
diff --git a/tools/client/sweep_playfields.py b/tools/client/sweep_playfields.py
@@ -17,7 +17,7 @@ import PIL.Image
root = pathlib.Path(__file__).resolve().parents[2]
sys.path.insert(0, str(root))
-import tools.data.ao_database
+import tools.client.playfield_catalog
work = root / 'local/playfield-sweep'
work.mkdir(parents=True, exist_ok=True)
@@ -58,32 +58,7 @@ for port in [7520, 7521, 8082]:
with socket.socket() as connection:
assert connection.connect_ex(('127.0.0.1', port)) != 0, port
-# Reconcile the server catalog with actual release definitions, including exclusions.
-database = tools.data.ao_database.Database(assets)
-catalog = []
-for line in (root / 'server/playfields.go').read_text().splitlines():
- match = re.match(r'\s+(\d+):\s+\{name: ("(?:[^"\\]|\\.)*")(.*)', line)
- if not match:
- continue
- identity = int(match[1])
- row = {'id': identity, 'name': json.loads(match[2])}
- if (1000001, identity) not in database.records:
- row['skip'] = 'no playfield definition in 14.9.1'
- elif 'unavailable: true' in match[3]:
- row['skip'] = 'dependency-only entry in server catalog'
- catalog.append(row)
-known = {row['id'] for row in catalog}
-for kind, identity in database.records:
- if kind == 1000001 and identity not in known:
- row = {'id': identity, 'name': database.read(kind, identity)[8:40].split(b'\0')[0].decode('ascii').strip()}
- if identity in [101, 105]:
- row['skip'] = 'door-link dependency or developer graphics test area'
- elif identity == 1673:
- row['skip'] = 'empty definition: zero zones, zero districts, no outdoor ground'
- else:
- row['skip'] = 'not in server catalog; investigate arrival'
- catalog.append(row)
-database.close()
+catalog = tools.client.playfield_catalog.read(root, assets)
if resuming:
assert json.loads((output / 'catalog.json').read_text()) == catalog, 'catalog changed; start a new sweep'
else: