// T7 (#70): the three-state fog, the vision cut-out and the player markers, against the real server // behind the TLS/HTTP2 test nginx (TESTING 10.3). The gate is a pixel probe: what the browser shows // at a world point, read from a screenshot (client/e2e/pixels.mjs), never from renderer internals. // // The scene is the seeded 4096 px map, cell 32 (128x128 cells), tile 32. Fixture tiles are one solid // colour per tile, so a probe has an independent expected colour (the same formula the fixture // writer uses, re-written here on purpose). The player's token sits near the middle; three walls // shape the sight: a window (sight passes), a one-way wall (the blind side is below it) and a closed // secret door (an opaque wall to a player). import test from 'node:test' import assert from 'node:assert/strict' import { createPlayer, namePlayer } from '../../tools/lib.mjs' import { openAs } from '../../tools/withserver.mjs' import { writeTileGrid } from '../../tools/tilefixture.mjs' import { launchBrowser, signIn, waitForText, waitForVisible, withStack, sleep, } from './stack.mjs' import { differs, luminance, probe } from './pixels.mjs' const SCENE = { w: 4096, h: 4096, tile: 32, cell: 32 } /** The fixture writer's colour formula (tools/tilefixture.mjs), re-written for the oracle. */ function tileColour(worldX, worldY) { const x = Math.floor(worldX / SCENE.tile) const y = Math.floor(worldY / SCENE.tile) return { r: (x * 37 + y * 11) & 0xff, g: (x * 17 + y * 53) & 0xff, b: (x * 97 + y * 5) & 0xff } } /** Cell centres (cell = 32): the middle of a cell keeps clear of grid lines and cell edges. */ const cellCentre = (cx, cy) => [cx * SCENE.cell + 16, cy * SCENE.cell + 16] /** World points probed in the fog test (each one is a cell centre; see the test's geometry notes). */ const POINTS = { visible: cellCentre(68, 64), // inside the token's sight, no wall on the ray throughWindow: cellCentre(72, 64), // beyond the window: a window lets sight pass blindBehindOneWay: cellCentre(64, 58), // above the one-way wall, on its blind side behindSecretDoor: cellCentre(55, 64), // left of the closed secret door unexplored: cellCentre(51, 54), // beyond the sight radius, explored by nobody gmMap: cellCentre(60, 64), // left of centre: the GM's panels cover the right of the viewport afterMove: cellCentre(68, 73), // inside the new sight after the token moves } async function gmWorld(origin, gmKey) { const gm = await openAs(origin, gmKey) const hello = await gm.ws.waitText('hello') const walls = await gm.ws.waitText('walls') return { ...gm, hello, scene: hello.scene ?? walls.scene } } /** * Create the player's sighted token through the GM token panel (#78): the fog test's world is * authored the way a GM authors it, with no raw `flags`/`vision_radius` on a wire `token.create`. * Returns the new token id. */ async function createSightedToken(origin, gmKey, player, { pos, name, radius, visionRadius }) { const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 900, height: 900 }, }) const page = await context.newPage() await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, gmKey) await waitForVisible(page, '#gm-panels') await waitForText(page, '#gm-roster-list', new RegExp(name)) // The create form and the token list start folded (M4 UX). await page.click('#gm-token-create-section > summary') await page.click('#gm-token-list-section > summary') await page .locator(`#token-controller option[value="${player.id}"]`) .waitFor({ state: 'attached', timeout: 20000 }) await page.fill('#token-kind', 'pc') await page.fill('#token-name', name) await page.fill('#token-actual', name) await page.fill('#token-x', String(pos[0])) await page.fill('#token-y', String(pos[1])) await page.fill('#token-radius', String(radius)) await page.check('#token-vision') await page.fill('#token-vision-radius', String(visionRadius)) await page.selectOption('#token-controller', String(player.id)) await page.click('#token-create-submit') const row = page.locator('#gm-token-list li', { hasText: name }).first() await row.waitFor({ state: 'visible', timeout: 20000 }) const id = await row.getAttribute('data-token') assert.ok(id, 'the panel-created token has no id') await context.close() return id } finally { await browser.close() } } /** One player, one sighted token and the three walls; returns the wall ids. */ async function fogWorld(origin, gmKey, stateDir) { const gm = await gmWorld(origin, gmKey) const scene = gm.scene writeTileGrid(stateDir, { scene: scene.id, artVersion: scene.art_version, size: scene.tile_size, x0: 40, x1: 87, y0: 40, y1: 87, }) const player = await createPlayer(gm.ws) await namePlayer(origin, player.key, 'Ann') // The walls exist before the token, so the first vision fan already has the blind zones and // explored memory never covers them (explored only grows, 6.1 / 5.8). // Window: sight passes; the preset turns the player marker on. const window = await gm.ws.request({ t: 'wall.add', scene: scene.id, preset: 'window', a: [2250, 1950], b: [2250, 2150], }) assert.equal(window.ok, true, JSON.stringify(window)) // One-way: `sight_dir:"left"` names the blind side; a->b runs +x, so +y (below) is blind. const oneWay = await gm.ws.request({ t: 'wall.add', scene: scene.id, a: [1800, 1950], b: [2300, 1950], blocks_sight: true, blocks_movement: true, sight_dir: 'left', }) assert.equal(oneWay.ok, true, JSON.stringify(oneWay)) // A closed secret door: a solid, sight-blocking wall to a player (5.8). const secret = await gm.ws.request({ t: 'wall.add', scene: scene.id, a: [1850, 1980], b: [1850, 2140], blocks_sight: true, blocks_movement: true, door: true, secret: true, }) assert.equal(secret.ok, true, JSON.stringify(secret)) const tokenId = await createSightedToken(origin, gmKey, player, { pos: [2048, 2048], name: 'Ann', radius: 20, visionRadius: 300, }) // The GM's own frame confirms the panel round-trip before the pixel probes rely on the sight. await gm.ws.waitFor( frame => frame.t === 'token' && frame.id === tokenId && frame.flags?.vision === true && frame.vision_radius === 300, 20000, ) return { gm, player, scene, tokenId, windowId: window.id, playerId: player.id } } /** Canvas rect plus the world container's transform (#69): `screen = world * zoom + camera.xy`. */ async function viewOf(page) { return page.evaluate(() => { const canvas = document.querySelector('#stage canvas') if (!canvas) throw new Error('no canvas') const rect = canvas.getBoundingClientRect() const [x, y] = (canvas.dataset.camera ?? '').split(',').map(Number) return { left: rect.left, top: rect.top, x, y, zoom: Number(canvas.dataset.zoom ?? '1') } }) } async function screenOf(page, [wx, wy]) { const view = await viewOf(page) return { x: view.left + wx * view.zoom + view.x, y: view.top + wy * view.zoom + view.y, } } async function probeWorld(page, world) { const point = await screenOf(page, world) return probe(page, point.x, point.y) } async function fogState(page) { return page.evaluate(() => { const canvas = document.querySelector('#stage canvas') if (!canvas) return null const data = canvas.dataset return { mode: data.fog ?? '', cells: Number(data.fogCells ?? '-1'), polys: Number(data.fogPolys ?? '-1'), markers: (data.fogMarkers ?? '').split(' ').filter(Boolean), cellsPainted: Number(data.fogCellsPainted ?? '-1'), fullRedraws: Number(data.fogFullRedraws ?? '-1'), visionBuilds: Number(data.fogVisionBuilds ?? '-1'), lastFresh: Number(data.fogLastFresh ?? '-1'), exploredMs: Number(data.fogExploredMs ?? '-1'), fullMs: Number(data.fogFullMs ?? '-1'), visionMs: Number(data.fogVisionMs ?? '-1'), } }) } async function waitFog(page, predicate, timeout = 30000) { const deadline = Date.now() + timeout let last = null while (Date.now() < deadline) { last = await fogState(page) if (last !== null && predicate(last)) return last await sleep(50) } throw new Error(`fog never reached the expected state: ${JSON.stringify(last)}`) } async function waitTilesReady(page, timeout = 30000) { await page.waitForFunction( () => document.querySelector('#stage canvas')?.dataset.tiles === 'ready', null, { timeout }, ) } /** Drag the token with real mouse steps (the #72 path), so the server recomputes vision. */ async function drag(page, from, to, steps = 10) { const start = await screenOf(page, from) await page.mouse.move(start.x, start.y) await page.mouse.down() for (let step = 1; step <= steps; step += 1) { const point = await screenOf(page, [ from[0] + ((to[0] - from[0]) * step) / steps, from[1] + ((to[1] - from[1]) * step) / steps, ]) await page.mouse.move(point.x, point.y) await sleep(60) } await page.mouse.up() } function near(actual, expected, tolerance = 10) { return ( Math.abs(actual.r - expected.r) <= tolerance && Math.abs(actual.g - expected.g) <= tolerance && Math.abs(actual.b - expected.b) <= tolerance ) } test('fog: unexplored black, explored dim, visible map colour; markers; a move; a resync', { timeout: 240000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const { gm, player, scene, windowId } = await fogWorld(origin, gmKey, stateDir) const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 900, height: 900 }, }) const page = await context.newPage() const errors = [] page.on('pageerror', error => errors.push(error.message)) page.on('console', message => { // Unfogged tiles are refused with 403 by design (story 20/27); the browser logs each one. if ( message.type() === 'error' && !message.text().includes('WebSocket connection') && !message.text().includes('403') && // The deliberate offline window aborts in-flight tile requests (status fetch or retry). !message.text().includes('net::ERR_') ) { errors.push(message.text()) } }) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, player.key) await waitForVisible(page, '#stage canvas') await waitTilesReady(page) const initial = await waitFog(page, state => state.mode === 'player' && state.polys > 0 && state.markers.length === 1) assert.ok(initial.cells > 100, `the sight explored cells: ${initial.cells}`) assert.equal(initial.fullRedraws, 1, 'the connect snapshot is the only full explored repaint') // Story 20/21/22: three states at cell-resolution probes. const unexplored = await probeWorld(page, POINTS.unexplored) assert.ok(luminance(unexplored) < 8, `unexplored floor is near-black: ${JSON.stringify(unexplored)}`) assert.ok(luminance(unexplored) < 8, 'never-seen floor leaks no map colour') const visible = await probeWorld(page, POINTS.visible) assert.ok(near(visible, tileColour(...POINTS.visible)), `visible floor shows the map: ${JSON.stringify(visible)}`) // Story 22 + §5.8: a window does not block sight; the floor beyond it is visible. const windowView = await probeWorld(page, POINTS.throughWindow) assert.ok( near(windowView, tileColour(...POINTS.throughWindow)), `a window lets sight through: ${JSON.stringify(windowView)}`, ) // Story 20/23 + §5.8: the one-way wall's blind side is dark, unlike the window's far side. const blind = await probeWorld(page, POINTS.blindBehindOneWay) assert.ok(luminance(blind) < 8, `the one-way blind side is unexplored: ${JSON.stringify(blind)}`) // §5.8: a closed secret door blocks sight like a solid wall. const secretView = await probeWorld(page, POINTS.behindSecretDoor) assert.ok(luminance(secretView) < 8, `the secret door blocks sight: ${JSON.stringify(secretView)}`) // Story 24: the window marker sits at the wall's drawn anchor, above the fog. const anchor = [2250, 2048] const markerPoint = await screenOf(page, anchor) const markerPixel = await probe(page, markerPoint.x, markerPoint.y) assert.ok( near(markerPixel, { r: 255, g: 204, b: 51 }, 24), `the seen window shows a marker at its anchor: ${JSON.stringify(markerPixel)}`, ) // Story 25: the GM turns the marker off; the marker is retracted (its own `del` frame). const update = await gm.ws.request({ t: 'wall.update', scene: scene.id, id: windowId, player_marker: false }) assert.equal(update.ok, true, JSON.stringify(update)) await waitFog(page, state => state.markers.length === 0) const afterMarker = await probe(page, markerPoint.x, markerPoint.y) assert.ok(differs(afterMarker, markerPixel, 30), 'the marker pixel is gone after `del`') assert.ok( luminance(afterMarker) > 60, `the seen floor shows through where the marker was, not fog: ${JSON.stringify(afterMarker)}`, ) // Story 23: a real drag moves the token; the server's new `vision` cuts the fog with no reload. await page.evaluate(() => { window.__fogKept = 'alive' }) const beforeMove = await fogState(page) await drag(page, [2048, 2048], [2048, 2400]) const moved = await waitFog( page, state => state.cells > beforeMove.cells && state.visionBuilds > beforeMove.visionBuilds, ) assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the fog followed the move without a reload') assert.equal(moved.fullRedraws, beforeMove.fullRedraws, 'the move painted cells, not the whole map') assert.ok(moved.cellsPainted > beforeMove.cellsPainted, 'the new cells were painted') assert.ok( moved.cellsPainted - beforeMove.cellsPainted <= moved.cells - beforeMove.cells + 1, `only the new cells were painted (${moved.cellsPainted - beforeMove.cellsPainted} painted for ${moved.cells - beforeMove.cells} cells)`, ) const nowDim = await probeWorld(page, POINTS.visible) const expectedDim = tileColour(...POINTS.visible) assert.ok( near(nowDim, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 12), `explored floor is dim (~0.6 alpha): ${JSON.stringify(nowDim)} for tile ${JSON.stringify(expectedDim)}`, ) assert.ok( luminance(nowDim) < luminance(tileColour(...POINTS.visible)) * 0.6, 'explored floor is visibly darker than visible floor', ) const newView = await probeWorld(page, POINTS.afterMove) assert.ok( near(newView, tileColour(...POINTS.afterMove)), `the new sight is clear: ${JSON.stringify(newView)}`, ) const stillBlind = await probeWorld(page, POINTS.blindBehindOneWay) assert.ok(luminance(stillBlind) < 8, 'the blind side never becomes visible') assert.deepEqual((await fogState(page)).markers, [], 'the retracted marker stays retracted') // Story 11: a reconnect resyncs explored, vision and markers; the view is the same, no reload. const beforeReconnect = await fogState(page) await context.setOffline(true) await page.locator('#badge[data-state="offline"]').waitFor({ state: 'visible', timeout: 20000 }) await context.setOffline(false) await page.locator('#badge[data-state="connected"]').waitFor({ state: 'visible', timeout: 30000 }) await waitFog(page, state => state.cells === beforeReconnect.cells && state.polys > 0) assert.equal(await page.evaluate(() => window.__fogKept), 'alive', 'the resync did not reload the page') assert.deepEqual((await fogState(page)).markers, [], 'a full marker snapshot does not resurrect a retracted marker') const dimAgain = await probeWorld(page, POINTS.visible) assert.ok(near(dimAgain, { r: expectedDim.r * 0.4, g: expectedDim.g * 0.4, b: expectedDim.b * 0.4 }, 14), `explored memory survives the resync: ${JSON.stringify(dimAgain)}`) const visibleAgain = await probeWorld(page, POINTS.afterMove) assert.ok(near(visibleAgain, tileColour(...POINTS.afterMove)), 'the current sight survives the resync') assert.deepEqual(errors, []) await context.close() } finally { await browser.close() gm.ws.close() } }) }) test('GM map is unfogged (story 26)', { timeout: 120000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const { gm } = await fogWorld(origin, gmKey, stateDir) const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 900, height: 900 }, }) const page = await context.newPage() await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, gmKey) await waitForVisible(page, '#stage canvas') await waitTilesReady(page) const state = await waitFog(page, fog => fog.mode === 'gm') assert.equal(state.cells, 0) assert.deepEqual(state.markers, [], 'the GM never receives a player marker') // The point the player is blind to (behind the one-way wall) is plain map for the GM. const gmView = await probeWorld(page, POINTS.gmMap) assert.ok( near(gmView, tileColour(...POINTS.gmMap)), `the GM map is unfogged: ${JSON.stringify(gmView)} for tile ${JSON.stringify(tileColour(...POINTS.gmMap))}`, ) await context.close() } finally { await browser.close() gm.ws.close() } }) }) test('fog cost on the phone-class emulation: full snapshot, a cell diff and a vision rebuild', { timeout: 180000 }, async () => { await withStack(async ({ origin, gmKey, stateDir }) => { const { gm, player, scene } = await fogWorld(origin, gmKey, stateDir) // The 50-token target (spec #63, M4): 49 more tokens packed inside the sight, no walls near // them, so the player's renderer draws 50 tokens with the fog on. for (let i = 0; i < 49; i += 1) { const ack = await gm.ws.request({ t: 'token.create', scene: scene.id, kind: 'npc', pos: [2048 + ((i % 7) - 3) * 28, 2048 + (Math.floor(i / 7) - 3) * 28], descriptive_name: `T${i}`, actual_name: `T${i}`, }) assert.equal(ack.ok, true, JSON.stringify(ack)) } const browser = await launchBrowser() try { const context = await browser.newContext({ ignoreHTTPSErrors: true, viewport: { width: 412, height: 869 }, deviceScaleFactor: 2.625, isMobile: true, hasTouch: true, }) const page = await context.newPage() const cdp = await context.newCDPSession(page) const errors = [] page.on('pageerror', error => errors.push(error.message)) await page.goto(`${origin}/`) await waitForVisible(page, '#signin') await signIn(page, player.key) await waitForVisible(page, '#stage canvas') await waitTilesReady(page) await waitFog(page, state => state.mode === 'player' && state.polys > 0) // Checked after the page-load fill, as in the tile-size gate: throttling multiplies every // image callback, so the fill itself is measured at real CPU. await cdp.send('Emulation.setCPUThrottlingRate', { rate: 4 }) const snapshot = await fogState(page) assert.ok(snapshot.fullMs > 0 && snapshot.fullMs < 250, `the connect snapshot repaints 128x128 cells under throttling: ${snapshot.fullMs} ms`) const before = snapshot await drag(page, [2048, 2048], [2048, 2250], 8) const after = await waitFog(page, state => state.cells > before.cells && state.visionBuilds > before.visionBuilds) assert.ok(after.lastFresh > 0, 'the move added explored cells') assert.ok(after.exploredMs < 50, `a cell diff is cheap under 4x CPU: ${after.exploredMs} ms for ${after.lastFresh} cells`) assert.ok(after.visionMs < 50, `a vision cut-out rebuild is cheap under 4x CPU: ${after.visionMs} ms`) // Frame cadence with 50 tokens and the fog active; recorded, not a hard gate (the phone run // is the human ticket), so a pathological regression still fails. const frames = await page.evaluate(async () => { const samples = [] await new Promise(resolve => { let last = performance.now() let count = 0 const step = () => { const now = performance.now() samples.push(now - last) last = now count += 1 if (count < 90) requestAnimationFrame(step) else resolve() } requestAnimationFrame(step) }) samples.sort((a, b) => a - b) return { samples: samples.length, median: samples[Math.floor(samples.length / 2)], p95: samples[Math.floor(samples.length * 0.95)], } }) // Recorded, not a gate (spec #63: no timing gate in the client suite; the phone run is the // human ticket). The fog's own update costs above are the assertion. assert.deepEqual(errors, []) console.log( `fog cost (#70, 412x869 dpr2.625, 4x CPU, 4096px map = 16384 cells, 50 tokens): ` + `snapshot=${snapshot.fullMs.toFixed(3)}ms cells=${snapshot.cells} ` + `diff=${after.exploredMs.toFixed(3)}ms fresh=${after.lastFresh} ` + `vision=${after.visionMs.toFixed(3)}ms polys=${after.polys} ` + `frames median=${frames.median.toFixed(1)}ms p95=${frames.p95.toFixed(1)}ms ` + `(16384px map = 262144 cells: full repaint scales ~16x, a diff does not)`, ) await context.close() } finally { await browser.close() gm.ws.close() } }) })