fix(client): tile loading: centre-out, one request per tile, 404 recovery (#86)

The GM survey view asked row-major, at most 8 at a time, rebuilt the whole
wanted window on every settle, and paid two requests for every failed tile
(image error, then a fetch to learn the status). A 404/5xx was stored as
permanent `denied`, so a tile imported after page load stayed black until a
page reload, and `viewport.setScene` swallowed a same-id art_version change
so the old textures were never dropped.

- TILE_CONCURRENCY 8 -> 32, the measured knee on a Full HD scene (min-of-3
  headless: GM fit + player 0.5, tile 32/64; 64 is inside the noise).
- orderTilesCentreOut: nearest the viewport centre first.
- Settle path is incremental (one settle = one tile sprite/flag update);
  the window is rebuilt only on camera/scene changes.
- fetch + createImageBitmap: status from the same response, decode off the
  main thread, so a failure costs one request.
- 403 stays permanent (retried only on fog.fresh); 404/5xx/network retry
  with 250/500 ms backoff up to 3 loads, and `hello`/reconnect or a
  scene/art_version change resets the budget. A failure that lands after a
  reconnect is a fresh first attempt; a failure that leaves the window does
  not spend the budget.
- setScene emits for a same-id scene; a new art_version drops the texture
  cache and reschedules. Tiles are `Cache-Control: private, max-age=1y,
  immutable` (still gated), so a reload reuses them; DESIGN 3.3/11.1 and
  client/README updated.

Tests: vitest for ordering, incremental invariants, retry budget/backoff,
reconnect epoch and art_version invalidation; e2e for a GM survey fill (one
request per succeeded tile) and a 404 tile recovering after the file appears
and a real reconnect. Before -> after (min-of-3, saturated host, Full HD):
GM fit 32px 910->843 ms, player 0.5 32px 972->862 ms, GM fit 64px
320->249 ms, player 0.5 64px 332->368 ms (noise).

Part of #63. Blocks #77.
This commit is contained in:
2026-11-21 22:28:18 +01:00
parent 54dbd68587
commit 52ab50d765
11 changed files with 676 additions and 134 deletions
+111 -54
View File
@@ -1,11 +1,19 @@
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12).
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12; #86 tile loading).
//
// Only the viewport plus one tile of margin is requested, nearest the viewport centre first,
// through the TileScheduler's 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 new `art_version` changes every URL, so its textures are dropped and refetched.
//
// Only the viewport plus one tile of margin is requested, in viewport order, through the
// 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 *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.
// A `404`/`5xx`/network failure is transient: the scheduler retries it a bounded number of times
// with backoff, and a reconnect retries every stored failure once more.
//
// The settle path is incremental: a tile that arrives only creates its sprite (or nothing, if the
// window moved on) and updates the readiness flag. Rebuilding the whole wanted list on every
// settle was O(window) per tile — tens of thousands squared while a GM survey view fills.
//
// The e2e contract on the canvas: `data-tiles` (`loading`/`ready`/`idle`) and
// `data-tile-requests` (how many fetches this page ever made) and `data-tile-distinct` (how many
@@ -17,8 +25,9 @@
import { Sprite, Texture } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import { viewport, visibleTiles } from '../../viewport.ts'
import { TileScheduler, tilesForCells } from '../../tiles.ts'
import { viewport, visibleTiles, orderTilesCentreOut } from '../../viewport.ts'
import type { VisibleTile } from '../../viewport.ts'
import { TileScheduler, tilesForCells, tilesInvalidated } from '../../tiles.ts'
import type { TileLoadResult } from '../../tiles.ts'
import { fogOf } from '../../slices/fog.ts'
@@ -30,44 +39,46 @@ let requests = 0
* `requests` may exceed this; a duplicate *tile* would not. */
const requestedUrls = new Set<string>()
function loadImage(src: string): Promise<HTMLImageElement> {
return new Promise((resolve, reject) => {
const image = new Image()
image.onload = () => resolve(image)
image.onerror = () => reject(new Error(`tile image failed: ${src}`))
image.src = src
})
}
/**
* One request per tile. `fetch` is used instead of an `<img>` because an image error carries no
* status: asking again with `fetch` to tell 403 from 404 doubled the cost of *every* failure. The
* response is decoded off the main thread by `createImageBitmap`, so the JS path never holds the
* image bytes.
*/
async function fetchTile(url: string): Promise<TileLoadResult> {
requests += 1
requestedUrls.add(url)
let response: Response
try {
// The browser's own image loader fetches and decodes off the JS path; one `onload` per tile is
// the cheapest way to get 480 phone-viewport tiles onto the GPU. The response body is not
// needed here, so no `fetch`, no blob and no `createImageBitmap` in the hot path.
const image = await loadImage(url)
textureCache.set(url, Texture.from(image))
response = await fetch(url, { credentials: 'same-origin' })
} catch {
return 'error'
}
if (response.status === 403) return 'denied'
if (!response.ok) return 'error'
try {
const bitmap = await createImageBitmap(await response.blob())
textureCache.set(url, Texture.from(bitmap))
return 'ok'
} catch {
// An <img> error has no status. Ask the gate once: 403/404 is a permanent "not yours" and is
// never retried; everything else is transient and may be retried after a reconnect.
try {
requests += 1
const response = await fetch(url, { credentials: 'same-origin' })
if (response.status === 403 || response.status === 404) return 'denied'
return 'error'
} catch {
return 'error'
}
return 'error'
}
}
function clearTextureCache(): void {
for (const texture of textureCache.values()) texture.destroy(true)
textureCache.clear()
}
export const renderModule: RenderModule = {
name: 'tiles',
mount({ app, layers, store }) {
const canvas = app.canvas
const sprites = new Map<string, Sprite>()
/** The current window: url -> tile, so a settle can place its sprite without a rebuild. */
let wanted = new Map<string, VisibleTile>()
/** Wanted urls that have not settled yet this pass; `ready` is `pending.size === 0`. */
let pending = new Set<string>()
let frame = 0
canvas.dataset['tileRequests'] = String(requests)
@@ -75,7 +86,7 @@ export const renderModule: RenderModule = {
const scheduler = new TileScheduler({
load: fetchTile,
onSettled: () => scheduleSync(),
onSettled: settle,
})
function scheduleSync(): void {
@@ -86,48 +97,76 @@ export const renderModule: RenderModule = {
})
}
function setTilesFlag(): void {
canvas.dataset['tiles'] = wanted.size === 0 ? 'idle' : pending.size > 0 ? 'loading' : 'ready'
canvas.dataset['tileRequests'] = String(requests)
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
canvas.dataset['visibleTiles'] = String(wanted.size)
}
function addSprite(tile: VisibleTile, texture: Texture, tileSize: number): void {
const sprite = new Sprite(texture)
sprite.position.set(tile.x * tileSize, tile.y * tileSize)
sprite.width = tileSize
sprite.height = tileSize
layers.tiles.addChild(sprite)
sprites.set(tile.url, sprite)
}
/** A tile settled: touch only that tile. Runs once per request, not once per window. */
function settle(url: string, result: TileLoadResult): void {
if (result === 'ok') {
const tile = wanted.get(url)
const texture = textureCache.get(url)
const scene = viewport.state.scene
if (tile && texture && scene && !sprites.has(url)) addSprite(tile, texture, scene.tile_size)
}
pending.delete(url)
setTilesFlag()
}
/** The viewport changed (pan/zoom/resize/reconnect): rebuild the window and diff it. */
function sync(): void {
const { scene, camera, size } = viewport.state
if (!scene) {
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
wanted = new Map()
pending = new Set()
canvas.dataset['tiles'] = 'idle'
return
}
const wanted = visibleTiles(scene, camera, size)
const wantedUrls = new Set(wanted.map(tile => tile.url))
const visible = orderTilesCentreOut(visibleTiles(scene, camera, size), scene, camera, size)
const next = new Map(visible.map(tile => [tile.url, tile]))
for (const [url, sprite] of sprites) {
if (wantedUrls.has(url)) continue
if (next.has(url)) continue
// Left the window (possibly before its bytes arrived): drop it, and let the scheduler
// cancel it if it was only queued.
sprite.destroy()
sprites.delete(url)
}
const tileSize = scene.tile_size
for (const tile of wanted) {
for (const tile of visible) {
const texture = textureCache.get(tile.url)
if (texture) scheduler.markLoaded(tile.url)
if (sprites.has(tile.url) || !texture) continue
const sprite = new Sprite(texture)
sprite.position.set(tile.x * tileSize, tile.y * tileSize)
sprite.width = tileSize
sprite.height = tileSize
layers.tiles.addChild(sprite)
sprites.set(tile.url, sprite)
if (!texture) continue
scheduler.markLoaded(tile.url)
if (!sprites.has(tile.url)) addSprite(tile, texture, scene.tile_size)
}
scheduler.setDesired(wanted.map(tile => tile.url))
canvas.dataset['tileRequests'] = String(requests)
canvas.dataset['tileDistinct'] = String(requestedUrls.size)
canvas.dataset['visibleTiles'] = String(wanted.length)
// `ready` means this pass is done, not that every tile painted: a transient `error` is
// retried only on a new window or a reconnect (README), so it must not hold the flag at
// `loading` for the rest of the session (a host hiccup would hang every e2e readiness wait).
canvas.dataset['tiles'] =
wanted.length === 0 ? 'idle' : scheduler.isPending(wanted.map(tile => tile.url)) ? 'loading' : 'ready'
wanted = next
scheduler.setDesired(visible.map(tile => tile.url))
pending = new Set()
for (const tile of visible) {
const status = scheduler.status(tile.url)
if (status === undefined || status === 'queued' || status === 'loading') pending.add(tile.url)
}
setTilesFlag()
}
const unsubscribe = viewport.subscribe(scheduleSync)
let lastExplored = -1
let lastScene: { id: number; art_version: number } | null = null
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).
@@ -140,6 +179,23 @@ export const renderModule: RenderModule = {
scheduleSync()
}
}
// New art is new URLs (`v<art_version>`), so every cached texture and scheduling decision is
// stale. Drop them and refetch the window. A same-version hello (reconnect) keeps the cache.
const scene = state.session.scene
if (scene) {
if (tilesInvalidated(lastScene, scene)) {
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
clearTextureCache()
scheduler.reset()
}
lastScene = { id: scene.id, art_version: scene.art_version }
}
// (No branch for `scene === null`: a reconnect's `connecting` reset clears the session, and
// keeping the last known scene lets a re-import that happened during the reconnect still drop
// the old textures when the new `hello` lands.)
// 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()
@@ -151,6 +207,7 @@ export const renderModule: RenderModule = {
return () => {
unsubscribe()
unsubscribeStore()
scheduler.dispose()
if (frame !== 0) cancelAnimationFrame(frame)
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()