From 8f999c837ea3a739ddf1c236ebf6ccb6787213b0 Mon Sep 17 00:00:00 2001 From: dingo Date: Wed, 9 Sep 2026 06:48:04 -0400 Subject: [PATCH] Decouple gameplay input from rendering and wait for world synchronization --- client/src/main.ts | 17 +++++++++++----- client/src/world-view.ts | 5 +---- docs/ARCHITECTURE.md | 5 +++++ docs/VERIFICATION.md | 17 ++++++++++++++++ tests/game.spec.ts | 42 ++++++++++++++++++++++++++++++++++------ 5 files changed, 71 insertions(+), 15 deletions(-) diff --git a/client/src/main.ts b/client/src/main.ts index 891fc80..77089d2 100644 --- a/client/src/main.ts +++ b/client/src/main.ts @@ -91,16 +91,17 @@ function action(op: string) { lastProgress = undefined; lastProgressAt = Date.now(); } function connect() { - requestedClose = false; sequence = 0; + requestedClose = false; sequence = 0; snapshot = undefined; const ending = $('ending'); ending.close(); ws = new WebSocket(`${location.protocol === 'https:' ? 'wss:' : 'ws:'}//${location.host}${worldPrefix}/ws`); - ws.onopen = () => { $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); }; + ws.onopen = () => { $('connection-status').textContent = 'Synchronizing world'; }; ws.onmessage = event => { const value = JSON.parse(event.data) as Snapshot; if (value.type !== 'snapshot' || value.version !== 1) { ws?.close(); notice('Client and server versions do not match.'); return; } if(pendingAction?.op==='gather' && snapshot && value.self.gatherAttempt!==snapshot.self.gatherAttempt){pendingAction=undefined;walkTo=undefined;gatherSent=0;} if(gatherSent && value.self.ack>=gatherSent)gatherSent=0; snapshot = value; view.update(value); updateHUD(value); + $('connection-status').textContent = 'Connected'; $('connection-dot').parentElement!.classList.remove('offline'); const state = value.self.entity.state; if (state === 'dead') showEnding('A life, remembered.', 'This character is permanently dead. Their belongings remain in this world.', false); else if (state === 'eligible') showEnding('A passage forward.', 'The Harbinger has fallen. Your character and belongings can continue to a new world.', true); @@ -194,10 +195,16 @@ async function boot() { else if(key==='inventory')$('inventory-toggle').click(); else if(key==='heal'||key==='return'||key==='jump')send(key); }); - view.start(dt => { + view.start(); + // Send bounded intents on elapsed wall time, independently of GPU frame rate. + // A delayed timer performs one update; it never replays a backlog of inputs. + let lastInputAt = performance.now(); + window.setInterval(() => { + const now = performance.now(), dt = (now - lastInputAt) / 1000; + lastInputAt = now; inputElapsed += dt; if (!snapshot || ws?.readyState !== WebSocket.OPEN || $('ending').open) return; - if(hasOpenMenu()||isEditing(document.activeElement)){ + if(document.hidden||hasOpenMenu()||isEditing(document.activeElement)){ input.clear();walkTo=undefined;pendingAction=undefined;view.moving=false; if(inputElapsed>=0.05){send('move');inputElapsed=0;}return; } @@ -242,7 +249,7 @@ async function boot() { } view.moving = !!(x || z); if (inputElapsed >= 0.05) { send('move', '', x, z); inputElapsed = 0; } - }); + }, 50); const [loadedConfig, chunks] = await Promise.all([api('/api/config'), api('/api/preview'), view.load()]); config = loadedConfig; $('zoom').value = String(view.distance); diff --git a/client/src/world-view.ts b/client/src/world-view.ts index 021319f..1bf96a1 100644 --- a/client/src/world-view.ts +++ b/client/src/world-view.ts @@ -29,7 +29,6 @@ export class WorldView { private matrix = new T.Matrix4(); private dummy = new T.Object3D(); private ray = new T.Raycaster(); - private onFrame: (dt: number) => void = () => {}; constructor(readonly canvas: HTMLCanvasElement) { this.renderer = new T.WebGLRenderer({ canvas, antialias: true, powerPreference: 'high-performance' }); this.renderer.setPixelRatio(Math.min(devicePixelRatio, 1.5)); @@ -210,11 +209,9 @@ export class WorldView { } return { point: this.ray.intersectObjects([...this.chunks.values()].map(c => c.mesh), false)[0]?.point }; } - start(onFrame: (dt: number) => void) { - this.onFrame = onFrame; + start() { this.renderer.setAnimationLoop(() => { const dt = Math.min(this.clock.getDelta(), 0.05); - this.onFrame(dt); // Presentation interpolation follows server positions; it never changes authoritative movement. this.position.lerp(this.aim, 1 - Math.exp(-14 * dt)); this.focus.lerp(this.position, 1 - Math.exp(-8 * dt)); diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index af5d53a..67f7419 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -46,6 +46,11 @@ One Go process owns one world, with a serial simulation protected by one lock. Clients submit bounded intents. The server determines speed, terrain height, range, cooldown, inventory changes, damage, death, play-time, and passage eligibility. Movement is interpolated on the client; full prediction/reconciliation is deferred. +Client movement and action intents run on a bounded 50ms timer, independent of +render frames. Elapsed time controls retries without replaying missed timer ticks; +hidden tabs and open menus clear movement/actions. Rendering alone clamps its +interpolation step. An open WebSocket shows "Synchronizing world" until a valid +world snapshot has been processed; reconnect clears the previous input snapshot. No rigid-body physics is claimed: this is heightfield movement in open terrain. Milestone 3 adds authoritative vertical jump velocity and gravity over that diff --git a/docs/VERIFICATION.md b/docs/VERIFICATION.md index bf0e952..f8881cd 100644 --- a/docs/VERIFICATION.md +++ b/docs/VERIFICATION.md @@ -1,5 +1,22 @@ # Verification performed +## September 9 client regression checks + +The initial timeout-only CI correction did not address render-dependent input or +the premature "Connected" status. The existing boss test now holds animation-frame +callbacks after targeting: it reproduced unchanged boss HP before the input-timer +fix and passes afterward against the real authoritative server. The existing +desktop reconnect test holds incoming server snapshots, checks the synchronizing +state, then releases them and requires the original character and all nine chunks. +Neither test substitutes client-calculated gameplay results. + +Required TypeScript/build and Go checks pass locally. CI on its Linux software +renderer remains the deployment verification gate; local passing tests do not +establish its result. Routine new Playwright coverage remains deferred; these +changes extend the existing failing regressions. + +## Original verification baseline + Local checks on Windows, 2026-09-05. Node 24.13.0, Go 1.27.1, Blender 4.3.2, Helm 3.18.6, and headless Microsoft Edge driven by Playwright. diff --git a/tests/game.spec.ts b/tests/game.spec.ts index 89d08d5..4cc1cc1 100644 --- a/tests/game.spec.ts +++ b/tests/game.spec.ts @@ -5,20 +5,24 @@ async function enter(page, name = 'Wayfarer') { await expect(page.locator('#connection-status')).toHaveText('World online'); await page.getByLabel('Character name').fill(name); await page.getByRole('button', { name: 'Enter world' }).click(); - await expect(page.locator('#connection-status')).toHaveText('Connected'); await expect(page.locator('#game-controls')).toBeVisible(); + await expectWorldReady(page); +} + +async function expectWorldReady(page, characterId?: string) { // Software-rendered CI can take longer than the default 5s to process the // initial snapshot. test.slow() extends the test, not this assertion's budget. // Keep the nine-chunk requirement and include both sides in failure output. - await expect.poll(() => page.evaluate(() => { + await expect.poll(() => page.evaluate(expectedId => { const game = (window as any).__aeternalis; return { connection: document.getElementById('connection-status')?.textContent, subscribedChunks: game?.snapshot?.chunkKeys.length ?? 0, renderedChunks: game?.diagnostics().chunks ?? 0, + characterMatches: expectedId ? game?.snapshot?.self.entity.id === expectedId : !!game?.snapshot?.self.entity.id, }; - }), { timeout: 20000, message: 'Initial server subscription and rendered terrain must contain all nine chunks' }) - .toEqual({ connection: 'Connected', subscribedChunks: 9, renderedChunks: 9 }); + }, characterId), { timeout: 20000, message: 'World readiness requires the expected character and all nine subscribed/rendered chunks' }) + .toEqual({ connection: 'Connected', subscribedChunks: 9, renderedChunks: 9, characterMatches: true }); } test('desktop renders models, moves authoritatively, gathers, and reconnects', async ({ page }) => { @@ -56,9 +60,21 @@ test('desktop renders models, moves authoritatively, gathers, and reconnects', a expect(pixels).toBeGreaterThan(8); const diagnostics = await page.evaluate(() => (window as any).__aeternalis.diagnostics()); expect(diagnostics.models).toBe(6); expect(diagnostics.frames).toBeGreaterThan(10); expect(diagnostics.triangles).toBeGreaterThan(1000); + // Keep the real server connection, but hold incoming snapshots until we have + // checked that an open socket alone does not claim the world is synchronized. + let releaseSnapshots: (() => void) | undefined; + await page.routeWebSocket('**/ws', socket => { + const server = socket.connectToServer(); + let held = true; + const buffered: (string | Buffer)[] = []; + server.onMessage(message => { if (held) buffered.push(message); else socket.send(message); }); + releaseSnapshots = () => { held = false; for (const message of buffered) socket.send(message); buffered.length = 0; }; + }); await page.reload(); - await expect(page.locator('#connection-status')).toHaveText('Connected'); - await expect.poll(() => page.evaluate(() => (window as any).__aeternalis?.snapshot?.self.entity.id)).toBe(id); + await expect(page.locator('#connection-status')).toHaveText('Synchronizing world', { timeout: 20000 }); + expect(await page.evaluate(() => (window as any).__aeternalis?.snapshot)).toBeUndefined(); + releaseSnapshots!(); + await expectWorldReady(page, id); expect(errors).toEqual([]); }); @@ -96,14 +112,28 @@ test('boss event is visible and accepts server-authoritative combat', async ({ p // timeout ever gets to fire and report cleanly. slow() triples this test's budget. test.slow(); await page.setViewportSize({ width: 1440, height: 900 }); + // Hold rendering after the target click. Input and server combat must keep + // progressing even when requestAnimationFrame is stalled on a slow GPU. + await page.addInitScript(() => { + const raf = window.requestAnimationFrame.bind(window); + window.requestAnimationFrame = callback => raf(time => { + const deliver = () => { + if ((window as any).__holdGameFrames) setTimeout(deliver, 50); + else callback(time); + }; + deliver(); + }); + }); await enter(page, 'Boss witness'); await page.getByRole('button', { name: 'Display settings' }).click(); await page.getByRole('button', { name: 'Awaken Harbinger' }).click(); await expect(page.locator('#phase-label')).toHaveText('THE UNRAVELING'); await page.getByRole('button', { name: 'Close display settings' }).click(); const hp = await page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp); + await page.locator('#target-boss').evaluate(button => button.addEventListener('click', () => { (window as any).__holdGameFrames = true; }, { once: true })); await page.getByRole('button', { name: 'Target Harbinger', exact: true }).click(); await expect.poll(() => page.evaluate(() => (window as any).__aeternalis.snapshot.world.bossHp), { timeout: 20000 }).toBeLessThan(hp); + await page.evaluate(() => { (window as any).__holdGameFrames = false; }); await expect(page.locator('#boss-bar')).toBeVisible(); await page.screenshot({ path: 'test-results/boss.png' }); });