feat(client): fog explored bitmap, vision cut-out and player markers (#70)
The fog layer (DESIGN 7.1 layer 4, spec #63 decision 9) keeps the explored grid in one cell-resolution RGBA canvas: never-seen cells opaque black, explored cells black at 0.6 alpha. A second canvas is the sprite texture: the explored canvas is copied into it and the union of the server's vision polygons is cut out with `destination-out`. A full explored snapshot repaints; a cell diff mutates only the new bytes and uploads the dirty rectangle. Player markers from the marker set/del frames are sprites above the fog; the GM layer hides the fog. The cut-out is baked instead of using a Graphics stencil mask: on the e2e's software renderer the stencil state cost ~350 ms of the phone-class viewport fill budget (412x869 dpr 2.625), while baking keeps the fill at the pre-fog baseline. The cut-out is rasterized at cell resolution, the same grid the server sends. Integration fix in the tile layer: a tile denied with 403 because it was unexplored is asked once more when the fog says its cells became explored; unexplored denials still never retry (the map 403 test is unchanged). Proven at the reducer seam (fog slice) and by screenshot pixel probes in the browser e2e: black/dim/visible, window see-through, one-way blind side, secret door, marker anchor and retraction, a drag that moves the fog with no reload, and a reconnect resync. Fog update cost recorded under the 412x869 dpr 2.625 / 4x CPU emulation.
This commit is contained in:
@@ -0,0 +1,452 @@
|
|||||||
|
// 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, 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 }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** 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 token = await gm.ws.request({
|
||||||
|
t: 'token.create',
|
||||||
|
scene: scene.id,
|
||||||
|
kind: 'pc',
|
||||||
|
pos: [2048, 2048],
|
||||||
|
descriptive_name: 'Ann',
|
||||||
|
actual_name: 'Ann',
|
||||||
|
controller: player.id,
|
||||||
|
flags: { vision: true },
|
||||||
|
vision_radius: 300,
|
||||||
|
radius: 20,
|
||||||
|
})
|
||||||
|
assert.equal(token.ok, true, JSON.stringify(token))
|
||||||
|
return { gm, player, scene, 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()
|
||||||
|
}
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -0,0 +1,139 @@
|
|||||||
|
// Pixel probes for the client e2e (TESTING 10.3). A probe is the colour the browser actually shows
|
||||||
|
// at one CSS point: Playwright screenshots a 3x3 CSS-pixel clip and this module decodes the PNG and
|
||||||
|
// averages it. No renderer internals, no WebGL readPixels, no preserveDrawingBuffer.
|
||||||
|
//
|
||||||
|
// The decoder is intentionally small: Chromium screenshots are non-interlaced 8-bit truecolour
|
||||||
|
// (RGB or RGBA), which is all a screenshot can be. Anything else is a programmer error here, not a
|
||||||
|
// browser case to support.
|
||||||
|
import zlib from 'node:zlib'
|
||||||
|
|
||||||
|
const SIGNATURE = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a])
|
||||||
|
|
||||||
|
function paeth(a, b, c) {
|
||||||
|
const p = a + b - c
|
||||||
|
const pa = Math.abs(p - a)
|
||||||
|
const pb = Math.abs(p - b)
|
||||||
|
const pc = Math.abs(p - c)
|
||||||
|
if (pa <= pb && pa <= pc) return a
|
||||||
|
if (pb <= pc) return b
|
||||||
|
return c
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Decode an 8-bit, non-interlaced RGB/RGBA PNG into `{ width, height, data }` (RGBA bytes). */
|
||||||
|
export function decodePng(buffer) {
|
||||||
|
if (!Buffer.isBuffer(buffer) || !buffer.subarray(0, 8).equals(SIGNATURE)) {
|
||||||
|
throw new Error('not a PNG')
|
||||||
|
}
|
||||||
|
let offset = 8
|
||||||
|
let width = 0
|
||||||
|
let height = 0
|
||||||
|
let channels = 0
|
||||||
|
const idat = []
|
||||||
|
while (offset + 8 <= buffer.length) {
|
||||||
|
const length = buffer.readUInt32BE(offset)
|
||||||
|
const type = buffer.toString('latin1', offset + 4, offset + 8)
|
||||||
|
const body = buffer.subarray(offset + 8, offset + 8 + length)
|
||||||
|
offset += 12 + length
|
||||||
|
if (type === 'IHDR') {
|
||||||
|
width = body.readUInt32BE(0)
|
||||||
|
height = body.readUInt32BE(4)
|
||||||
|
const depth = body[8]
|
||||||
|
const colorType = body[9]
|
||||||
|
const interlace = body[12]
|
||||||
|
if (depth !== 8 || interlace !== 0) throw new Error(`unsupported PNG depth/interlace ${depth}/${interlace}`)
|
||||||
|
if (colorType === 2) channels = 3
|
||||||
|
else if (colorType === 6) channels = 4
|
||||||
|
else throw new Error(`unsupported PNG colour type ${colorType}`)
|
||||||
|
} else if (type === 'IDAT') {
|
||||||
|
idat.push(body)
|
||||||
|
} else if (type === 'IEND') {
|
||||||
|
break
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (!width || !height || !channels) throw new Error('PNG without IHDR/IDAT')
|
||||||
|
|
||||||
|
const raw = zlib.inflateSync(Buffer.concat(idat))
|
||||||
|
const stride = width * channels
|
||||||
|
const pixels = Buffer.alloc(stride * height)
|
||||||
|
for (let y = 0; y < height; y++) {
|
||||||
|
const filter = raw[y * (stride + 1)]
|
||||||
|
const line = raw.subarray(y * (stride + 1) + 1, (y + 1) * (stride + 1))
|
||||||
|
const out = pixels.subarray(y * stride, (y + 1) * stride)
|
||||||
|
const prev = y > 0 ? pixels.subarray((y - 1) * stride, y * stride) : null
|
||||||
|
for (let x = 0; x < stride; x++) {
|
||||||
|
const a = x >= channels ? out[x - channels] : 0
|
||||||
|
const b = prev ? prev[x] : 0
|
||||||
|
const c = prev && x >= channels ? prev[x - channels] : 0
|
||||||
|
let value = line[x]
|
||||||
|
switch (filter) {
|
||||||
|
case 0:
|
||||||
|
break
|
||||||
|
case 1:
|
||||||
|
value = (value + a) & 0xff
|
||||||
|
break
|
||||||
|
case 2:
|
||||||
|
value = (value + b) & 0xff
|
||||||
|
break
|
||||||
|
case 3:
|
||||||
|
value = (value + ((a + b) >> 1)) & 0xff
|
||||||
|
break
|
||||||
|
case 4:
|
||||||
|
value = (value + paeth(a, b, c)) & 0xff
|
||||||
|
break
|
||||||
|
default:
|
||||||
|
throw new Error(`unsupported PNG filter ${filter}`)
|
||||||
|
}
|
||||||
|
out[x] = value
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (channels === 4) return { width, height, data: pixels }
|
||||||
|
const rgba = Buffer.alloc(width * height * 4)
|
||||||
|
for (let i = 0, j = 0; i < pixels.length; i += 3, j += 4) {
|
||||||
|
rgba[j] = pixels[i]
|
||||||
|
rgba[j + 1] = pixels[i + 1]
|
||||||
|
rgba[j + 2] = pixels[i + 2]
|
||||||
|
rgba[j + 3] = 255
|
||||||
|
}
|
||||||
|
return { width, height, data: rgba }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Average every pixel of a decoded image (the probe clip is small and uniform). */
|
||||||
|
export function averageColour(image) {
|
||||||
|
let r = 0
|
||||||
|
let g = 0
|
||||||
|
let b = 0
|
||||||
|
let a = 0
|
||||||
|
const count = image.width * image.height
|
||||||
|
for (let i = 0; i < image.data.length; i += 4) {
|
||||||
|
r += image.data[i]
|
||||||
|
g += image.data[i + 1]
|
||||||
|
b += image.data[i + 2]
|
||||||
|
a += image.data[i + 3]
|
||||||
|
}
|
||||||
|
return { r: r / count, g: g / count, b: b / count, a: a / count }
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The colour shown at CSS point `(x, y)`: a 3x3 CSS-pixel screenshot clip, decoded and averaged.
|
||||||
|
* Screenshots are in device pixels, so DPR is handled by the browser, not by this helper.
|
||||||
|
*/
|
||||||
|
export async function probe(page, x, y) {
|
||||||
|
const px = Math.max(0, Math.round(x) - 1)
|
||||||
|
const py = Math.max(0, Math.round(y) - 1)
|
||||||
|
const buffer = await page.screenshot({ clip: { x: px, y: py, width: 3, height: 3 } })
|
||||||
|
return averageColour(decodePng(buffer))
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Mean absolute channel difference, for "did this area change" assertions. */
|
||||||
|
export function differs(a, b, tolerance = 12) {
|
||||||
|
return (
|
||||||
|
Math.abs(a.r - b.r) > tolerance ||
|
||||||
|
Math.abs(a.g - b.g) > tolerance ||
|
||||||
|
Math.abs(a.b - b.b) > tolerance
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
export function luminance({ r, g, b }) {
|
||||||
|
return 0.2126 * r + 0.7152 * g + 0.0722 * b
|
||||||
|
}
|
||||||
@@ -0,0 +1,320 @@
|
|||||||
|
// The fog and marker layer (T7, #70; DESIGN 7.1 layer 4, 7.3). Three states from the server's facts:
|
||||||
|
// never-seen floor is opaque black, explored floor is black at ~0.6 alpha, currently visible floor
|
||||||
|
// is cut out of the fog so the map shows through.
|
||||||
|
//
|
||||||
|
// Mechanism (spec #63 decision 9 leaves the Pixi object to the build):
|
||||||
|
// - one RGBA canvas at cell resolution (`ceil(w/cell) x ceil(h/cell)`) holds the *explored* state:
|
||||||
|
// never-seen cells alpha 255, explored cells alpha ~0.6. It is repainted from an `ImageData`
|
||||||
|
// buffer; a cell diff mutates only the new bytes and uploads only the dirty rectangle, so "only
|
||||||
|
// changed cells" is the normal path (DESIGN 7.2);
|
||||||
|
// - a second canvas of the same size is the texture the sprite displays: the explored canvas is
|
||||||
|
// copied into it and the union of this player's `vision` polygons is cut out with
|
||||||
|
// `destination-out`, which is the polygon cut-out itself, not a separate stencil pass. It is
|
||||||
|
// recomposed only when an explored or vision frame arrives; there is no per-frame work here;
|
||||||
|
// - player markers are small sprites in the same layer, drawn above the fog sprite from the
|
||||||
|
// `marker` set/del frames, never inferred from tiles or walls (decision 17).
|
||||||
|
//
|
||||||
|
// Why no stencil mask: a Graphics stencil mask forces a depth-stencil attachment plus a full-frame
|
||||||
|
// stencil pass on every frame. Measured on the e2e's software renderer it cost ~350 ms of the
|
||||||
|
// phone-class viewport-fill budget (test 412x869 dpr 2.625); the baked cut-out keeps the same
|
||||||
|
// pixels and leaves the fill at the pre-fog baseline. The cut-out is rasterized at cell resolution,
|
||||||
|
// the same resolution as the explored grid the server sends.
|
||||||
|
//
|
||||||
|
// The GM has no fog (story 26): the layer hides and the GM never receives `explored`/`vision`/
|
||||||
|
// `marker` frames anyway. The counts, timings and ids are published on the canvas dataset; the e2e
|
||||||
|
// reads them and probes the pixels, so the test never touches renderer internals.
|
||||||
|
|
||||||
|
import { Container, Graphics, GraphicsContext, Sprite, Texture } from 'pixi.js'
|
||||||
|
import type { RenderContext, RenderModule } from '../stage.ts'
|
||||||
|
import type { RootState } from '../../reducer.ts'
|
||||||
|
import { fogOf } from '../../slices/fog.ts'
|
||||||
|
import type { FogState, VisionPoly } from '../../slices/fog.ts'
|
||||||
|
|
||||||
|
/** Explored-but-not-visible: black at 0.6 alpha, so the map reads dimmed, never hidden. */
|
||||||
|
export const EXPLORED_ALPHA = 0.6
|
||||||
|
|
||||||
|
/** One shared icon context for every marker: a lit window pane with a dark frame. */
|
||||||
|
const MARKER_ICON = new GraphicsContext()
|
||||||
|
.roundRect(-7, -7, 14, 14, 2)
|
||||||
|
.fill(0xffcc33)
|
||||||
|
.stroke({ width: 2, color: 0x2b1d00 })
|
||||||
|
|
||||||
|
export const renderModule: RenderModule = {
|
||||||
|
name: 'fog',
|
||||||
|
mount({ app, layers, store }: RenderContext) {
|
||||||
|
const canvas = app.canvas
|
||||||
|
|
||||||
|
// Markers live in their own layer above the fog sprite.
|
||||||
|
const markerLayer = new Container()
|
||||||
|
layers.fog.addChild(markerLayer)
|
||||||
|
|
||||||
|
let sprite: Sprite | null = null
|
||||||
|
let texture: Texture | null = null
|
||||||
|
/** Explored state (`alpha 255` never seen, `alpha 153` explored), at cell resolution. */
|
||||||
|
let base: HTMLCanvasElement | null = null
|
||||||
|
let baseContext: CanvasRenderingContext2D | null = null
|
||||||
|
let baseImage: ImageData | null = null
|
||||||
|
/** What the sprite shows: `base` with the vision polygons cut out. */
|
||||||
|
let shown: HTMLCanvasElement | null = null
|
||||||
|
let shownContext: CanvasRenderingContext2D | null = null
|
||||||
|
let grid = { cols: 0, rows: 0 }
|
||||||
|
let cell = 0
|
||||||
|
let sceneId: number | null = null
|
||||||
|
|
||||||
|
/** The union of this player's polygons, kept for every recompose after a cell diff. */
|
||||||
|
let currentPolys: readonly VisionPoly[] = []
|
||||||
|
let renderedExplored = -1
|
||||||
|
let renderedVision = -1
|
||||||
|
let renderedMarkers = -1
|
||||||
|
const markerNodes = new Map<string, Graphics>()
|
||||||
|
|
||||||
|
// Instrumentation. `cellsPainted` is the cumulative number of cell pixels touched, so a diff
|
||||||
|
// is visibly cheaper than the snapshot; `fullRedraws` stays at 1 after a connect.
|
||||||
|
const stats = {
|
||||||
|
cellsPainted: 0,
|
||||||
|
fullRedraws: 0,
|
||||||
|
visionBuilds: 0,
|
||||||
|
markerUpdates: 0,
|
||||||
|
lastFresh: 0,
|
||||||
|
exploredMs: 0,
|
||||||
|
fullMs: 0,
|
||||||
|
visionMs: 0,
|
||||||
|
}
|
||||||
|
|
||||||
|
function destroySurface(): void {
|
||||||
|
sprite?.destroy()
|
||||||
|
sprite = null
|
||||||
|
texture?.destroy(true)
|
||||||
|
texture = null
|
||||||
|
base = null
|
||||||
|
baseContext = null
|
||||||
|
baseImage = null
|
||||||
|
shown = null
|
||||||
|
shownContext = null
|
||||||
|
grid = { cols: 0, rows: 0 }
|
||||||
|
cell = 0
|
||||||
|
sceneId = null
|
||||||
|
renderedExplored = -1
|
||||||
|
renderedVision = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
function build(fog: FogState, width: number, height: number): void {
|
||||||
|
const cols = fog.cols
|
||||||
|
const rows = fog.rows
|
||||||
|
if (cols <= 0 || rows <= 0) return
|
||||||
|
|
||||||
|
base = document.createElement('canvas')
|
||||||
|
base.width = cols
|
||||||
|
base.height = rows
|
||||||
|
const exploredContext = base.getContext('2d')
|
||||||
|
if (!exploredContext) return
|
||||||
|
baseContext = exploredContext
|
||||||
|
baseImage = exploredContext.createImageData(cols, rows)
|
||||||
|
// Before the first `explored` frame everything is never-seen: opaque black.
|
||||||
|
exploredContext.fillStyle = '#000'
|
||||||
|
exploredContext.fillRect(0, 0, cols, rows)
|
||||||
|
|
||||||
|
shown = document.createElement('canvas')
|
||||||
|
shown.width = cols
|
||||||
|
shown.height = rows
|
||||||
|
const fogContext = shown.getContext('2d')
|
||||||
|
if (!fogContext) return
|
||||||
|
shownContext = fogContext
|
||||||
|
fogContext.fillStyle = '#000'
|
||||||
|
fogContext.fillRect(0, 0, cols, rows)
|
||||||
|
|
||||||
|
grid = { cols, rows }
|
||||||
|
cell = fog.cell
|
||||||
|
|
||||||
|
texture = Texture.from(shown)
|
||||||
|
// The cell texture is displayed scaled: smooth beats a pixelated haze at any zoom.
|
||||||
|
texture.source.scaleMode = 'linear'
|
||||||
|
sprite = new Sprite(texture)
|
||||||
|
sprite.width = width
|
||||||
|
sprite.height = height
|
||||||
|
sprite.label = 'fog'
|
||||||
|
layers.fog.addChildAt(sprite, 0)
|
||||||
|
sceneId = fog.sceneId
|
||||||
|
renderedExplored = -1
|
||||||
|
renderedVision = -1
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Rebuild the displayed texture from the explored base and the current vision polygons. The
|
||||||
|
* canvas 2D `destination-out` fill is the polygon cut-out: antialiased at cell resolution and
|
||||||
|
* one cheap draw, with no mask/stencil state on the render target.
|
||||||
|
*/
|
||||||
|
function compose(): number {
|
||||||
|
if (!shownContext || !base || !shown) return 0
|
||||||
|
const started = performance.now()
|
||||||
|
shownContext.globalCompositeOperation = 'copy'
|
||||||
|
shownContext.drawImage(base, 0, 0)
|
||||||
|
const polys = currentPolys
|
||||||
|
if (polys.length > 0 && cell > 0) {
|
||||||
|
shownContext.globalCompositeOperation = 'destination-out'
|
||||||
|
shownContext.save()
|
||||||
|
shownContext.scale(1 / cell, 1 / cell)
|
||||||
|
// One fill per polygon: overlapping polygons punch the same hole whether their winding
|
||||||
|
// orders agree or not (a single nonzero fill could cancel an opposite-winding overlap).
|
||||||
|
for (const poly of polys) {
|
||||||
|
const [first, ...rest] = poly.pts
|
||||||
|
if (!first) continue
|
||||||
|
shownContext.beginPath()
|
||||||
|
shownContext.moveTo(first[0], first[1])
|
||||||
|
for (const [x, y] of rest) shownContext.lineTo(x, y)
|
||||||
|
shownContext.closePath()
|
||||||
|
shownContext.fill()
|
||||||
|
}
|
||||||
|
shownContext.restore()
|
||||||
|
}
|
||||||
|
shownContext.globalCompositeOperation = 'source-over'
|
||||||
|
texture?.source.update()
|
||||||
|
return performance.now() - started
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Paint the explored state into `base`. Full repaint only for a snapshot or missed revision. */
|
||||||
|
function paintExplored(fog: FogState): void {
|
||||||
|
if (!baseContext || !baseImage || !texture || fog.cols !== grid.cols || fog.rows !== grid.rows) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const started = performance.now()
|
||||||
|
const data = baseImage.data
|
||||||
|
const full = fog.snapshot || fog.exploredVersion !== renderedExplored + 1
|
||||||
|
const alpha = Math.round(EXPLORED_ALPHA * 255)
|
||||||
|
|
||||||
|
if (full) {
|
||||||
|
for (let i = 3; i < data.length; i += 4) data[i] = 255
|
||||||
|
for (const index of fog.cells) data[index * 4 + 3] = alpha
|
||||||
|
baseContext.putImageData(baseImage, 0, 0)
|
||||||
|
stats.cellsPainted += grid.cols * grid.rows
|
||||||
|
stats.fullRedraws += 1
|
||||||
|
} else if (fog.fresh.length > 0) {
|
||||||
|
let minX = grid.cols
|
||||||
|
let minY = grid.rows
|
||||||
|
let maxX = -1
|
||||||
|
let maxY = -1
|
||||||
|
for (const index of fog.fresh) {
|
||||||
|
data[index * 4 + 3] = alpha
|
||||||
|
const x = index % grid.cols
|
||||||
|
const y = (index / grid.cols) | 0
|
||||||
|
if (x < minX) minX = x
|
||||||
|
if (y < minY) minY = y
|
||||||
|
if (x > maxX) maxX = x
|
||||||
|
if (y > maxY) maxY = y
|
||||||
|
}
|
||||||
|
stats.cellsPainted += fog.fresh.length
|
||||||
|
// One write of the dirtied rectangle, not the whole map.
|
||||||
|
baseContext.putImageData(baseImage, 0, 0, minX, minY, maxX - minX + 1, maxY - minY + 1)
|
||||||
|
} else {
|
||||||
|
renderedExplored = fog.exploredVersion
|
||||||
|
stats.exploredMs = performance.now() - started
|
||||||
|
return
|
||||||
|
}
|
||||||
|
currentPolys = fog.polys
|
||||||
|
const composeMs = compose()
|
||||||
|
renderedExplored = fog.exploredVersion
|
||||||
|
renderedVision = fog.visionVersion
|
||||||
|
stats.lastFresh = fog.fresh.length
|
||||||
|
stats.exploredMs = performance.now() - started + composeMs
|
||||||
|
if (full) stats.fullMs = stats.exploredMs
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Recompose the cut-out; nothing per frame. */
|
||||||
|
function paintVision(fog: FogState): void {
|
||||||
|
if (!base) return
|
||||||
|
currentPolys = fog.polys
|
||||||
|
stats.visionMs = compose()
|
||||||
|
renderedVision = fog.visionVersion
|
||||||
|
stats.visionBuilds += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Apply one `marker` change: only added, removed or moved ids are touched. */
|
||||||
|
function paintMarkers(fog: FogState): void {
|
||||||
|
for (const [id, node] of markerNodes) {
|
||||||
|
if (fog.markers[id] !== undefined) continue
|
||||||
|
markerLayer.removeChild(node)
|
||||||
|
node.destroy()
|
||||||
|
markerNodes.delete(id)
|
||||||
|
}
|
||||||
|
for (const [id, pos] of Object.entries(fog.markers)) {
|
||||||
|
let node = markerNodes.get(id)
|
||||||
|
if (!node) {
|
||||||
|
node = new Graphics(MARKER_ICON)
|
||||||
|
node.label = `marker-${id}`
|
||||||
|
markerLayer.addChild(node)
|
||||||
|
markerNodes.set(id, node)
|
||||||
|
}
|
||||||
|
if (node.x !== pos[0] || node.y !== pos[1]) node.position.set(pos[0], pos[1])
|
||||||
|
}
|
||||||
|
renderedMarkers = fog.markerVersion
|
||||||
|
stats.markerUpdates += 1
|
||||||
|
}
|
||||||
|
|
||||||
|
function publish(fog: FogState): void {
|
||||||
|
const datasets = canvas.dataset
|
||||||
|
const role = store.state.session.role
|
||||||
|
datasets['fog'] = role === 'gm' ? 'gm' : sceneId === null ? 'idle' : 'player'
|
||||||
|
datasets['fogCells'] = String(fog.cells.size)
|
||||||
|
datasets['fogPolys'] = String(fog.polys.length)
|
||||||
|
datasets['fogMarkers'] = Object.keys(fog.markers).join(' ')
|
||||||
|
datasets['fogCellsPainted'] = String(stats.cellsPainted)
|
||||||
|
datasets['fogFullRedraws'] = String(stats.fullRedraws)
|
||||||
|
datasets['fogVisionBuilds'] = String(stats.visionBuilds)
|
||||||
|
datasets['fogMarkerUpdates'] = String(stats.markerUpdates)
|
||||||
|
datasets['fogLastFresh'] = String(stats.lastFresh)
|
||||||
|
datasets['fogExploredMs'] = stats.exploredMs.toFixed(3)
|
||||||
|
datasets['fogFullMs'] = stats.fullMs.toFixed(3)
|
||||||
|
datasets['fogVisionMs'] = stats.visionMs.toFixed(3)
|
||||||
|
}
|
||||||
|
|
||||||
|
function sync(state: RootState): void {
|
||||||
|
const fog = fogOf(state)
|
||||||
|
const role = state.session.role
|
||||||
|
const gm = role === 'gm'
|
||||||
|
|
||||||
|
// The GM sees everything: no fog and no marker-only memory (stories 24-26).
|
||||||
|
if (sprite) sprite.visible = !gm
|
||||||
|
markerLayer.visible = !gm
|
||||||
|
|
||||||
|
if (gm || fog.cols <= 0 || !state.session.scene) {
|
||||||
|
publish(fog)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
const width = state.session.scene.w
|
||||||
|
const height = state.session.scene.h
|
||||||
|
if (sceneId !== fog.sceneId || !sprite) {
|
||||||
|
destroySurface()
|
||||||
|
build(fog, width, height)
|
||||||
|
for (const node of markerNodes.values()) node.destroy()
|
||||||
|
markerNodes.clear()
|
||||||
|
} else if (sprite.width !== width || sprite.height !== height) {
|
||||||
|
sprite.width = width
|
||||||
|
sprite.height = height
|
||||||
|
}
|
||||||
|
if (!sprite) {
|
||||||
|
publish(fog)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
|
||||||
|
if (fog.exploredVersion !== renderedExplored) paintExplored(fog)
|
||||||
|
// A vision frame can arrive before the first explored frame; compose still needs the base.
|
||||||
|
else if (fog.visionVersion !== renderedVision) paintVision(fog)
|
||||||
|
if (fog.markerVersion !== renderedMarkers) paintMarkers(fog)
|
||||||
|
publish(fog)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The stage is created once the session is live, but a resync can beat `app.init`: start from
|
||||||
|
// whatever the reducer already holds, then follow the event stream.
|
||||||
|
sync(store.state)
|
||||||
|
const unsubscribe = store.subscribe(sync)
|
||||||
|
|
||||||
|
return () => {
|
||||||
|
unsubscribe()
|
||||||
|
for (const node of markerNodes.values()) node.destroy()
|
||||||
|
markerNodes.clear()
|
||||||
|
destroySurface()
|
||||||
|
layers.fog.removeChild(markerLayer)
|
||||||
|
markerLayer.destroy({ children: true })
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
@@ -4,7 +4,8 @@
|
|||||||
// TileScheduler's 8-wide queue. The decoded textures live in a module-level cache keyed by URL, so
|
// TileScheduler's 8-wide queue. The decoded textures live in a module-level cache keyed by URL, so
|
||||||
// a reconnect (which keeps the stage and only resets the reducer slices) never refetches a tile.
|
// a reconnect (which keeps the stage and only resets the reducer slices) never refetches a tile.
|
||||||
// A `403` from the server is the gate saying "not yours": it is remembered as denied and never
|
// A `403` from the server is the gate saying "not yours": it is remembered as denied and never
|
||||||
// retried. Sprites outside the wanted window are removed but their textures are kept.
|
// retried *while its cells stay unexplored*. When the fog slice reports newly explored cells (#70)
|
||||||
|
// the gate's answer for those tiles changed, so exactly those denied tiles are asked once more.
|
||||||
//
|
//
|
||||||
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
|
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
|
||||||
// `data-tile-requests` (how many fetches this page ever made). `ready` means every tile the current
|
// `data-tile-requests` (how many fetches this page ever made). `ready` means every tile the current
|
||||||
@@ -13,8 +14,9 @@
|
|||||||
import { Sprite, Texture } from 'pixi.js'
|
import { Sprite, Texture } from 'pixi.js'
|
||||||
import type { RenderModule } from '../stage.ts'
|
import type { RenderModule } from '../stage.ts'
|
||||||
import { viewport, visibleTiles } from '../../viewport.ts'
|
import { viewport, visibleTiles } from '../../viewport.ts'
|
||||||
import { TileScheduler } from '../../tiles.ts'
|
import { TileScheduler, tilesForCells } from '../../tiles.ts'
|
||||||
import type { TileLoadResult } from '../../tiles.ts'
|
import type { TileLoadResult } from '../../tiles.ts'
|
||||||
|
import { fogOf } from '../../slices/fog.ts'
|
||||||
|
|
||||||
/** Kept across a reconnect (and even a stage rebuild): URL -> decoded texture. */
|
/** Kept across a reconnect (and even a stage rebuild): URL -> decoded texture. */
|
||||||
const textureCache = new Map<string, Texture>()
|
const textureCache = new Map<string, Texture>()
|
||||||
@@ -115,8 +117,20 @@ export const renderModule: RenderModule = {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unsubscribe = viewport.subscribe(scheduleSync)
|
const unsubscribe = viewport.subscribe(scheduleSync)
|
||||||
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
|
let lastExplored = -1
|
||||||
const unsubscribeStore = store.subscribe((_state, event) => {
|
const unsubscribeStore = store.subscribe((state, event) => {
|
||||||
|
// Newly explored cells can flip a tile's `403` to an allowed tile (#70): retry exactly the
|
||||||
|
// denied tiles the new cells touch, once. An unexplored 403 stays denied (no retry loop).
|
||||||
|
const fog = fogOf(state)
|
||||||
|
if (fog.exploredVersion !== lastExplored) {
|
||||||
|
lastExplored = fog.exploredVersion
|
||||||
|
const scene = viewport.state.scene
|
||||||
|
if (fog.fresh.length > 0 && scene) {
|
||||||
|
scheduler.retryDenied(tilesForCells(scene, fog, fog.fresh))
|
||||||
|
scheduleSync()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
|
||||||
if (event.type === 'frame' && event.frame.t === 'hello') {
|
if (event.type === 'frame' && event.frame.t === 'hello') {
|
||||||
scheduler.retryFailed()
|
scheduler.retryFailed()
|
||||||
scheduleSync()
|
scheduleSync()
|
||||||
|
|||||||
@@ -0,0 +1,207 @@
|
|||||||
|
// Fog slice (T7, #70; DESIGN 6.1 `explored`/`vision`/`marker`, 7.3). Append-only registration: this
|
||||||
|
// file was enough; the reducer's glob picked it up and `hello` resets it with every other slice.
|
||||||
|
//
|
||||||
|
// The server sends derived, per-recipient memory: `explored` (a full RLE snapshot on connect, cell
|
||||||
|
// diffs after), `vision` (the union of this player's sight polygons, integer px) and `marker`
|
||||||
|
// (this player's opaque window-marker ids with an anchor). Nothing here is a secret the client
|
||||||
|
// must enforce; it is only what the server chose to send (DESIGN 7.3, story 27).
|
||||||
|
//
|
||||||
|
// The slice keeps the whole explored set, because a reconnect must rebuild the view from a full
|
||||||
|
// snapshot, plus the *delta* of the last `explored` frame. The renderer uses the delta to touch only
|
||||||
|
// the new cells (DESIGN 7.2); a snapshot or a missed revision tells it to redraw everything.
|
||||||
|
|
||||||
|
import type { ReducerEvent, RootState, Slice } from '../reducer.ts'
|
||||||
|
import type { SceneInfo, ServerFrame, Vec2 } from '../protocol.ts'
|
||||||
|
|
||||||
|
/** One sight polygon: the token that produced it and its integer-px points (DESIGN 6.1, Q16). */
|
||||||
|
export interface VisionPoly {
|
||||||
|
id: string
|
||||||
|
pts: Vec2[]
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface FogState {
|
||||||
|
/** The explored cell grid, from `hello.scene`: `cols = ceil(w / cell)`, `rows = ceil(h / cell)`. */
|
||||||
|
cols: number
|
||||||
|
rows: number
|
||||||
|
cell: number
|
||||||
|
sceneId: number | null
|
||||||
|
/** Explored cells, row-major (`cy * cols + cx`). Only ever grows between `hello`s. */
|
||||||
|
cells: Set<number>
|
||||||
|
/** Cells added by the latest explored update: the only cells a renderer has to touch. */
|
||||||
|
fresh: number[]
|
||||||
|
/** The latest explored update was a full `rle` snapshot, not a cell diff. */
|
||||||
|
snapshot: boolean
|
||||||
|
/** Bumped when the explored set changes; a renderer tracks what it has already drawn. */
|
||||||
|
exploredVersion: number
|
||||||
|
/** This player's current sight polygons (server-clipped already; never another player's). */
|
||||||
|
polys: VisionPoly[]
|
||||||
|
/** Bumped when the polygon union changes; the renderer rebuilds the cut-out then. */
|
||||||
|
visionVersion: number
|
||||||
|
/** This player's own window markers: opaque id -> integer-px anchor (DESIGN 5.8, 6.1). */
|
||||||
|
markers: Record<string, Vec2>
|
||||||
|
/** Bumped when the marker set or an anchor changes. */
|
||||||
|
markerVersion: number
|
||||||
|
}
|
||||||
|
|
||||||
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
||||||
|
return typeof value === 'object' && value !== null && !Array.isArray(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isInt(value: unknown): value is number {
|
||||||
|
return typeof value === 'number' && Number.isInteger(value)
|
||||||
|
}
|
||||||
|
|
||||||
|
function isVec2(value: unknown): value is Vec2 {
|
||||||
|
return Array.isArray(value) && value.length === 2 && isInt(value[0]) && isInt(value[1])
|
||||||
|
}
|
||||||
|
|
||||||
|
export function emptyFog(): FogState {
|
||||||
|
return {
|
||||||
|
cols: 0,
|
||||||
|
rows: 0,
|
||||||
|
cell: 0,
|
||||||
|
sceneId: null,
|
||||||
|
cells: new Set<number>(),
|
||||||
|
fresh: [],
|
||||||
|
snapshot: false,
|
||||||
|
exploredVersion: 0,
|
||||||
|
polys: [],
|
||||||
|
visionVersion: 0,
|
||||||
|
markers: {},
|
||||||
|
markerVersion: 0,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The cell grid of a scene, or zero for a missing/invalid one. */
|
||||||
|
function gridOf(scene: SceneInfo | null): { cols: number; rows: number; cell: number } {
|
||||||
|
const cell = scene && scene.cell > 0 ? scene.cell : 0
|
||||||
|
if (!scene || cell <= 0 || !(scene.w > 0) || !(scene.h > 0)) return { cols: 0, rows: 0, cell: 0 }
|
||||||
|
return { cols: Math.ceil(scene.w / cell), rows: Math.ceil(scene.h / cell), cell }
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `explored {full:true, rle:[[cy, x0, len, x0, len, ...], ...]}` (DESIGN 6.1). */
|
||||||
|
function applyFull(state: FogState, rle: unknown): boolean {
|
||||||
|
if (!Array.isArray(rle)) return false
|
||||||
|
const cells = new Set<number>()
|
||||||
|
for (const row of rle) {
|
||||||
|
if (!Array.isArray(row) || row.length < 3) continue
|
||||||
|
const cy = row[0]
|
||||||
|
if (!isInt(cy) || cy < 0 || cy >= state.rows) continue
|
||||||
|
for (let i = 1; i + 1 < row.length; i += 2) {
|
||||||
|
const x0 = row[i]
|
||||||
|
const len = row[i + 1]
|
||||||
|
if (!isInt(x0) || !isInt(len) || len <= 0) continue
|
||||||
|
const end = Math.min(state.cols, x0 + len)
|
||||||
|
for (let cx = Math.max(0, x0); cx < end; cx++) cells.add(cy * state.cols + cx)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.cells = cells
|
||||||
|
state.fresh = [...cells]
|
||||||
|
state.snapshot = true
|
||||||
|
state.exploredVersion += 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `explored {full:false, cells:[[cx, cy], ...]}` (DESIGN 6.1): monotone additions only. */
|
||||||
|
function applyFresh(state: FogState, list: unknown): boolean {
|
||||||
|
if (!Array.isArray(list)) return false
|
||||||
|
const fresh: number[] = []
|
||||||
|
for (const entry of list) {
|
||||||
|
if (!isVec2(entry)) continue
|
||||||
|
const [cx, cy] = entry
|
||||||
|
if (cx < 0 || cy < 0 || cx >= state.cols || cy >= state.rows) continue
|
||||||
|
const index = cy * state.cols + cx
|
||||||
|
if (state.cells.has(index)) continue
|
||||||
|
state.cells.add(index)
|
||||||
|
fresh.push(index)
|
||||||
|
}
|
||||||
|
state.fresh = fresh
|
||||||
|
state.snapshot = false
|
||||||
|
if (fresh.length > 0) state.exploredVersion += 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `vision {polys:[{id, pts:[[x,y],...]}]}` (DESIGN 6.1). Malformed polygons are dropped whole. */
|
||||||
|
function applyVision(state: FogState, polys: unknown): boolean {
|
||||||
|
if (!Array.isArray(polys)) return false
|
||||||
|
const next: VisionPoly[] = []
|
||||||
|
for (const entry of polys) {
|
||||||
|
if (!isRecord(entry)) continue
|
||||||
|
const id = entry['id']
|
||||||
|
const pts = entry['pts']
|
||||||
|
if (typeof id !== 'string' || !Array.isArray(pts)) continue
|
||||||
|
if (pts.length < 3 || !pts.every(isVec2)) continue
|
||||||
|
next.push({ id, pts: pts as Vec2[] })
|
||||||
|
}
|
||||||
|
state.polys = next
|
||||||
|
state.visionVersion += 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
/** `marker {full, set:[{id,pos}], del:[id]}` (DESIGN 6.1). A full frame replaces; a diff retracts. */
|
||||||
|
function applyMarkers(state: FogState, frame: ServerFrame): boolean {
|
||||||
|
const set = frame['set']
|
||||||
|
if (!Array.isArray(set)) return false
|
||||||
|
const full = frame['full'] === true
|
||||||
|
const next: Record<string, Vec2> = full ? {} : { ...state.markers }
|
||||||
|
let changed = full
|
||||||
|
for (const entry of set) {
|
||||||
|
if (!isRecord(entry)) continue
|
||||||
|
const id = entry['id']
|
||||||
|
const pos = entry['pos']
|
||||||
|
if (typeof id !== 'string' || !isVec2(pos)) continue
|
||||||
|
const before = next[id]
|
||||||
|
if (!before || before[0] !== pos[0] || before[1] !== pos[1]) changed = true
|
||||||
|
next[id] = [pos[0], pos[1]]
|
||||||
|
}
|
||||||
|
if (!full) {
|
||||||
|
const del = frame['del']
|
||||||
|
if (Array.isArray(del)) {
|
||||||
|
for (const id of del) {
|
||||||
|
if (typeof id !== 'string' || next[id] === undefined) continue
|
||||||
|
delete next[id]
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
state.markers = next
|
||||||
|
if (changed) state.markerVersion += 1
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
|
||||||
|
export const slice: Slice<FogState> = {
|
||||||
|
name: 'fog',
|
||||||
|
init: emptyFog,
|
||||||
|
reduce(state: FogState, event: ReducerEvent, root: RootState): void {
|
||||||
|
if (event.type !== 'frame') return
|
||||||
|
const frame = event.frame
|
||||||
|
switch (frame.t) {
|
||||||
|
case 'hello': {
|
||||||
|
// `hello` already reset the slice; the scene (set before the slice loop runs) gives the grid.
|
||||||
|
const grid = gridOf(root.session.scene)
|
||||||
|
state.cols = grid.cols
|
||||||
|
state.rows = grid.rows
|
||||||
|
state.cell = grid.cell
|
||||||
|
state.sceneId = root.session.scene?.id ?? null
|
||||||
|
return
|
||||||
|
}
|
||||||
|
case 'explored':
|
||||||
|
if (state.cols === 0) return
|
||||||
|
if (frame['full'] === true) applyFull(state, frame['rle'])
|
||||||
|
else applyFresh(state, frame['cells'])
|
||||||
|
return
|
||||||
|
case 'vision':
|
||||||
|
applyVision(state, frame['polys'])
|
||||||
|
return
|
||||||
|
case 'marker':
|
||||||
|
applyMarkers(state, frame)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
},
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The fog slice of a root state (always registered, always present after `initialState`). */
|
||||||
|
export function fogOf(state: RootState): FogState {
|
||||||
|
const fog = state.slices['fog'] as FogState | undefined
|
||||||
|
return fog ?? emptyFog()
|
||||||
|
}
|
||||||
+45
-1
@@ -9,7 +9,12 @@
|
|||||||
// - a `403`/`404` is a permanent `denied` answer: never retried in a loop (the server said no);
|
// - a `403`/`404` is a permanent `denied` answer: never retried in a loop (the server said no);
|
||||||
// - a transient `error` is retried only when a later viewport sync asks for the tile again;
|
// - a transient `error` is retried only when a later viewport sync asks for the tile again;
|
||||||
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
|
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
|
||||||
// prefetches beyond the margin.
|
// prefetches beyond the margin;
|
||||||
|
// - a denied tile is asked again only when the fog says its cells just became explored (#70):
|
||||||
|
// the gate's answer changed, so the old "no" is stale.
|
||||||
|
|
||||||
|
import type { SceneInfo } from './protocol.ts'
|
||||||
|
import { tileUrl } from './viewport.ts'
|
||||||
|
|
||||||
export const TILE_CONCURRENCY = 8
|
export const TILE_CONCURRENCY = 8
|
||||||
|
|
||||||
@@ -29,6 +34,28 @@ function sameList(a: readonly string[], b: readonly string[]): boolean {
|
|||||||
return true
|
return true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* The tile urls touched by a set of explored cells (fog slice indices, row-major). v1 has
|
||||||
|
* `cell == tile_size` (DESIGN 8), but the maths keeps a cell-to-tile mapping general.
|
||||||
|
*/
|
||||||
|
export function tilesForCells(
|
||||||
|
scene: Pick<SceneInfo, 'id' | 'art_version' | 'tile_size'>,
|
||||||
|
grid: { cols: number; cell: number },
|
||||||
|
cells: Iterable<number>,
|
||||||
|
): string[] {
|
||||||
|
const tileSize = scene.tile_size
|
||||||
|
if (!(tileSize > 0) || grid.cell <= 0 || grid.cols <= 0) return []
|
||||||
|
const urls = new Set<string>()
|
||||||
|
for (const index of cells) {
|
||||||
|
const cx = index % grid.cols
|
||||||
|
const cy = (index / grid.cols) | 0
|
||||||
|
const tx = Math.floor((cx * grid.cell) / tileSize)
|
||||||
|
const ty = Math.floor((cy * grid.cell) / tileSize)
|
||||||
|
urls.add(tileUrl(scene, tx, ty))
|
||||||
|
}
|
||||||
|
return [...urls]
|
||||||
|
}
|
||||||
|
|
||||||
export class TileScheduler {
|
export class TileScheduler {
|
||||||
readonly #load: (url: string) => Promise<TileLoadResult>
|
readonly #load: (url: string) => Promise<TileLoadResult>
|
||||||
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
|
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
|
||||||
@@ -96,6 +123,23 @@ export class TileScheduler {
|
|||||||
this.#lastDesired = []
|
this.#lastDesired = []
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
|
||||||
|
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
|
||||||
|
* denied urls are forgotten and the next `setDesired` asks for them exactly once more. Nothing
|
||||||
|
* else is retried: an unexplored 403 stays denied (no retry loop).
|
||||||
|
*/
|
||||||
|
retryDenied(urls: Iterable<string>): void {
|
||||||
|
let changed = false
|
||||||
|
for (const url of urls) {
|
||||||
|
if (this.#states.get(url) !== 'denied') continue
|
||||||
|
this.#states.delete(url)
|
||||||
|
changed = true
|
||||||
|
}
|
||||||
|
// The next setDesired rebuilds the queue, which re-queues the forgotten urls as `queued`.
|
||||||
|
if (changed) this.#lastDesired = []
|
||||||
|
}
|
||||||
|
|
||||||
/** True when every wanted tile settled with an `ok` or `denied` answer. */
|
/** True when every wanted tile settled with an `ok` or `denied` answer. */
|
||||||
isComplete(urls: readonly string[]): boolean {
|
isComplete(urls: readonly string[]): boolean {
|
||||||
return urls.every(url => {
|
return urls.every(url => {
|
||||||
|
|||||||
@@ -0,0 +1,202 @@
|
|||||||
|
// The fog slice (T7, #70; DESIGN 6.1 `explored`/`vision`/`marker`, 7.3). These are reducer-seam
|
||||||
|
// tests: server frames in, state out. The pixels themselves are proven in the browser e2e
|
||||||
|
// (`client/e2e/fog.test.mjs`), not here.
|
||||||
|
import { describe, expect, it } from 'vitest'
|
||||||
|
import { initialState, reduce } from '../src/reducer.ts'
|
||||||
|
import type { ReducerEvent, RootState } from '../src/reducer.ts'
|
||||||
|
import { parseServerFrame } from '../src/protocol.ts'
|
||||||
|
import { fogOf } from '../src/slices/fog.ts'
|
||||||
|
import type { FogState } from '../src/slices/fog.ts'
|
||||||
|
|
||||||
|
const scene = {
|
||||||
|
id: 1,
|
||||||
|
name: 'Cellar',
|
||||||
|
w: 4096,
|
||||||
|
h: 4096,
|
||||||
|
tile_size: 32,
|
||||||
|
cell: 32,
|
||||||
|
grid_size: 64,
|
||||||
|
vision_radius_default: 320,
|
||||||
|
token_radius_default: 20,
|
||||||
|
art_version: 1,
|
||||||
|
}
|
||||||
|
|
||||||
|
const frame = (body: Record<string, unknown>): ReducerEvent => {
|
||||||
|
const parsed = parseServerFrame(JSON.stringify(body))
|
||||||
|
if (!parsed) throw new Error(`bad test frame ${JSON.stringify(body)}`)
|
||||||
|
return { type: 'frame', frame: parsed }
|
||||||
|
}
|
||||||
|
|
||||||
|
const hello = (n: number): ReducerEvent =>
|
||||||
|
frame({ t: 'hello', n, proto: 2, role: 'player', me: { id: 2, name: 'Ann' }, scene })
|
||||||
|
|
||||||
|
const run = (...events: ReducerEvent[]): RootState =>
|
||||||
|
events.reduce((state, event) => reduce(state, event), initialState())
|
||||||
|
|
||||||
|
const fogAfter = (...events: ReducerEvent[]): FogState => fogOf(run(hello(1), ...events))
|
||||||
|
|
||||||
|
describe('the explored grid comes from hello.scene (6.1)', () => {
|
||||||
|
it('is empty until hello, then sized in cells', () => {
|
||||||
|
const before = fogOf(initialState())
|
||||||
|
expect(before.cols).toBe(0)
|
||||||
|
expect(before.sceneId).toBeNull()
|
||||||
|
|
||||||
|
const fog = fogAfter()
|
||||||
|
expect(fog.cols).toBe(128)
|
||||||
|
expect(fog.rows).toBe(128)
|
||||||
|
expect(fog.cell).toBe(32)
|
||||||
|
expect(fog.sceneId).toBe(1)
|
||||||
|
expect(fog.cells.size).toBe(0)
|
||||||
|
expect(fog.exploredVersion).toBe(0)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('explored full and diff frames (6.1)', () => {
|
||||||
|
it('a full RLE snapshot answers every explored cell and marks the update a snapshot', () => {
|
||||||
|
// Row cy=2: x=5..7 and x=10..11 (runs are [x0, len] pairs).
|
||||||
|
const fog = fogAfter(frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 3, 10, 2]] }))
|
||||||
|
const base = 2 * 128
|
||||||
|
expect([...fog.cells].sort((a, b) => a - b)).toEqual([
|
||||||
|
base + 5,
|
||||||
|
base + 6,
|
||||||
|
base + 7,
|
||||||
|
base + 10,
|
||||||
|
base + 11,
|
||||||
|
])
|
||||||
|
expect(fog.fresh).toHaveLength(5)
|
||||||
|
expect(fog.snapshot).toBe(true)
|
||||||
|
expect(fog.exploredVersion).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a diff adds only new cells and reports exactly those as fresh', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
|
||||||
|
frame({
|
||||||
|
t: 'explored',
|
||||||
|
n: 3,
|
||||||
|
full: false,
|
||||||
|
cells: [
|
||||||
|
[5, 2], // explored already: not fresh again
|
||||||
|
[6, 2], // explored already
|
||||||
|
[7, 2], // new
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(fog.cells.size).toBe(3)
|
||||||
|
expect(fog.fresh).toEqual([2 * 128 + 7])
|
||||||
|
expect(fog.snapshot).toBe(false)
|
||||||
|
expect(fog.exploredVersion).toBe(2)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a diff with nothing new changes no version and reports no fresh cells', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
|
||||||
|
frame({ t: 'explored', n: 3, full: false, cells: [[5, 2], [6, 2]] }),
|
||||||
|
)
|
||||||
|
expect(fog.cells.size).toBe(2)
|
||||||
|
expect(fog.fresh).toEqual([])
|
||||||
|
expect(fog.exploredVersion).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('ignores cells outside the grid and malformed frames without half-applying them', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2], [999, 0, 3], [3, -4, 2]] }),
|
||||||
|
frame({ t: 'explored', n: 3, full: false, cells: [[-1, 0], [128, 0], [0, 128], ['x', 0]] }),
|
||||||
|
frame({ t: 'explored', n: 4, full: false, cells: 'nope' }),
|
||||||
|
)
|
||||||
|
expect(fog.cells.size).toBe(2)
|
||||||
|
expect(fog.exploredVersion).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('vision polygons (6.1)', () => {
|
||||||
|
it('keeps this player\'s polygons and drops malformed ones whole', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({
|
||||||
|
t: 'vision',
|
||||||
|
n: 2,
|
||||||
|
polys: [
|
||||||
|
{ id: 'tok-1', pts: [[10, 10], [20, 10], [20, 20]] },
|
||||||
|
{ id: 'short', pts: [[0, 0], [1, 1]] },
|
||||||
|
{ id: 'bad-point', pts: [[0, 0], [1, 'x'], [2, 2]] },
|
||||||
|
{ pts: [[0, 0], [1, 1], [2, 0]] },
|
||||||
|
],
|
||||||
|
}),
|
||||||
|
)
|
||||||
|
expect(fog.polys).toEqual([{ id: 'tok-1', pts: [[10, 10], [20, 10], [20, 20]] }])
|
||||||
|
expect(fog.visionVersion).toBe(1)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a later vision frame replaces the union (a token leaving sight is gone)', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'vision', n: 2, polys: [{ id: 'a', pts: [[0, 0], [9, 0], [9, 9]] }] }),
|
||||||
|
frame({ t: 'vision', n: 3, polys: [] }),
|
||||||
|
)
|
||||||
|
expect(fog.polys).toEqual([])
|
||||||
|
expect(fog.visionVersion).toBe(2)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('player markers (5.8, 6.1)', () => {
|
||||||
|
it('a full set replaces the whole memory', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'marker', n: 2, full: true, set: [{ id: 'm1', pos: [100, 200] }] }),
|
||||||
|
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm2', pos: [300, 400] }] }),
|
||||||
|
frame({ t: 'marker', n: 4, full: true, set: [{ id: 'm3', pos: [500, 600] }] }),
|
||||||
|
)
|
||||||
|
expect(fog.markers).toEqual({ m3: [500, 600] })
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a diff adds and retracts by id; an anchor change moves the same id', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'marker', n: 2, full: true, set: [{ id: 'm1', pos: [100, 200] }] }),
|
||||||
|
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm2', pos: [300, 400] }] }),
|
||||||
|
frame({ t: 'marker', n: 4, full: false, set: [{ id: 'm1', pos: [110, 200] }] }),
|
||||||
|
frame({ t: 'marker', n: 5, full: false, set: [], del: ['m2', 'never-seen'] }),
|
||||||
|
)
|
||||||
|
expect(fog.markers).toEqual({ m1: [110, 200] })
|
||||||
|
expect(fog.markerVersion).toBe(4)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a diff that changes nothing does not bump the version', () => {
|
||||||
|
const fog = fogAfter(
|
||||||
|
frame({ t: 'marker', n: 2, full: false, set: [{ id: 'm1', pos: [100, 200] }] }),
|
||||||
|
frame({ t: 'marker', n: 3, full: false, set: [{ id: 'm1', pos: [100, 200] }] }),
|
||||||
|
frame({ t: 'marker', n: 4, full: false, set: [], del: [] }),
|
||||||
|
)
|
||||||
|
expect(fog.markerVersion).toBe(1)
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|
||||||
|
describe('reset and the GM (6.3)', () => {
|
||||||
|
it('a second hello clears explored, vision and markers and rebuilds the grid', () => {
|
||||||
|
const reset = run(
|
||||||
|
hello(1),
|
||||||
|
frame({ t: 'explored', n: 2, full: true, rle: [[2, 5, 2]] }),
|
||||||
|
frame({ t: 'vision', n: 3, polys: [{ id: 'a', pts: [[0, 0], [9, 0], [9, 9]] }] }),
|
||||||
|
frame({ t: 'marker', n: 4, full: true, set: [{ id: 'm1', pos: [1, 2] }] }),
|
||||||
|
hello(1),
|
||||||
|
)
|
||||||
|
const fog = fogOf(reset)
|
||||||
|
expect(fog.cols).toBe(128)
|
||||||
|
expect(fog.cells.size).toBe(0)
|
||||||
|
expect(fog.fresh).toEqual([])
|
||||||
|
expect(fog.polys).toEqual([])
|
||||||
|
expect(fog.markers).toEqual({})
|
||||||
|
expect(fog.exploredVersion).toBe(0)
|
||||||
|
expect(fog.visionVersion).toBe(0)
|
||||||
|
expect(fog.markerVersion).toBe(0)
|
||||||
|
})
|
||||||
|
|
||||||
|
it('a GM connection receives no fog frames, so its fog state stays empty', () => {
|
||||||
|
const state = run(
|
||||||
|
frame({ t: 'hello', n: 1, proto: 2, role: 'gm', me: { id: 1, name: 'GM' }, scene }),
|
||||||
|
frame({ t: 'roster', n: 2, players: [] }),
|
||||||
|
)
|
||||||
|
const fog = fogOf(state)
|
||||||
|
expect(fog.cols).toBe(128)
|
||||||
|
expect(fog.cells.size).toBe(0)
|
||||||
|
expect(fog.polys).toEqual([])
|
||||||
|
expect(fog.markers).toEqual({})
|
||||||
|
})
|
||||||
|
})
|
||||||
@@ -2,7 +2,7 @@
|
|||||||
// 8, a decoded-texture cache the tile module keeps across reconnect, no duplicate in-flight fetch,
|
// 8, a decoded-texture cache the tile module keeps across reconnect, no duplicate in-flight fetch,
|
||||||
// and a denied tile (403/404) is remembered so the client never retries it in a loop.
|
// and a denied tile (403/404) is remembered so the client never retries it in a loop.
|
||||||
import { describe, expect, it } from 'vitest'
|
import { describe, expect, it } from 'vitest'
|
||||||
import { TILE_CONCURRENCY, TileScheduler } from '../src/tiles.ts'
|
import { TILE_CONCURRENCY, TileScheduler, tilesForCells } from '../src/tiles.ts'
|
||||||
import type { TileLoadResult } from '../src/tiles.ts'
|
import type { TileLoadResult } from '../src/tiles.ts'
|
||||||
|
|
||||||
interface Harness {
|
interface Harness {
|
||||||
@@ -170,3 +170,42 @@ describe('TileScheduler', () => {
|
|||||||
expect(h.calls).toEqual([list[0], list[0]])
|
expect(h.calls).toEqual([list[0], list[0]])
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
|
|
||||||
|
describe('fog-driven denied retry (#70)', () => {
|
||||||
|
it('re-asks a denied tile exactly once after its cells became explored', async () => {
|
||||||
|
const h = harness()
|
||||||
|
const list = urls(2)
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
h.settle(list[0] as string, 'denied')
|
||||||
|
h.settle(list[1] as string, 'ok')
|
||||||
|
await flush()
|
||||||
|
expect(h.calls).toEqual(list)
|
||||||
|
|
||||||
|
// The fog says cells under the first tile became explored: only that denied tile is stale.
|
||||||
|
h.scheduler.retryDenied([list[0] as string])
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
expect(h.calls).toEqual([...list, list[0]])
|
||||||
|
h.settleAll('ok')
|
||||||
|
await flush()
|
||||||
|
|
||||||
|
// A plain re-sync (no new cells) must not ask again: the denial is still remembered.
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
h.scheduler.retryDenied([])
|
||||||
|
h.scheduler.setDesired(list)
|
||||||
|
expect(h.calls).toEqual([...list, list[0]])
|
||||||
|
})
|
||||||
|
|
||||||
|
it('maps explored cells to the tiles they touch', () => {
|
||||||
|
const scene = { id: 3, art_version: 7, tile_size: 32 }
|
||||||
|
const grid = { cols: 4, cell: 32 }
|
||||||
|
// Cells (1,0) -> tile (1,0), (1,1) -> tile (1,1), (3,1) -> tile (3,1).
|
||||||
|
expect(tilesForCells(scene, grid, [1, 5, 7])).toEqual([
|
||||||
|
'/tiles/3/v7/1_0.png',
|
||||||
|
'/tiles/3/v7/1_1.png',
|
||||||
|
'/tiles/3/v7/3_1.png',
|
||||||
|
])
|
||||||
|
// Two cells in one tile are one url; a smaller cell than a tile still maps correctly.
|
||||||
|
expect(tilesForCells(scene, { cols: 16, cell: 8 }, [0, 1, 2])).toEqual(['/tiles/3/v7/0_0.png'])
|
||||||
|
expect(tilesForCells(scene, { cols: 0, cell: 0 }, [1])).toEqual([])
|
||||||
|
})
|
||||||
|
})
|
||||||
|
|||||||
Reference in New Issue
Block a user