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
+207
View File
@@ -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()
}