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:
2026-11-21 10:44:32 +01:00
parent d225e956ca
commit 2d9548c941
8 changed files with 1423 additions and 6 deletions
+320
View File
@@ -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 })
}
},
}
+18 -4
View File
@@ -4,7 +4,8 @@
// 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 `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
// `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 type { RenderModule } from '../stage.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 { fogOf } from '../../slices/fog.ts'
/** Kept across a reconnect (and even a stage rebuild): URL -> decoded texture. */
const textureCache = new Map<string, Texture>()
@@ -115,8 +117,20 @@ export const renderModule: RenderModule = {
}
const unsubscribe = viewport.subscribe(scheduleSync)
// A reconnect is the moment to give transient failures another chance; a 403 stays denied.
const unsubscribeStore = store.subscribe((_state, event) => {
let lastExplored = -1
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') {
scheduler.retryFailed()
scheduleSync()