feat(client): map tiles, grid and pan/zoom (#69)

T6 of spec #63. Tiles are requested only for the viewport plus one tile of
margin, in viewport order, at most 8 at a time (TileScheduler); decoded
textures are cached by URL so a reconnect refetches nothing; a 403/404 is
remembered as denied and never retried. The browser image loader is the hot
path, with one status fetch only to classify an error.

Camera: drag to pan, wheel/pinch to zoom around the pointer/midpoint; players
clamp at 0.5 (ADR-0013) and the GM has no player floor; both stop at 4.0.
Grid is one TilingSprite toggled by #grid-toggle. Camera is local UI state,
not a reducer slice, so hello/reconnect does not move the view.

Tests: viewport/tile unit tests (clamps, margin window, 8-wide queue, denial,
cache) and client/e2e/map.test.mjs (mobile viewport fill gate (a), grid,
pinch, cache across reconnect, GM zoom, 403 no-retry) against the real
server through TLS/h2. Tile-size gate (a) documented in client/README.md.
This commit is contained in:
2026-11-21 01:11:12 +01:00
parent 0323fbd2ae
commit 4534ed6426
9 changed files with 1469 additions and 0 deletions
+269
View File
@@ -0,0 +1,269 @@
// Camera, viewport and tile-window maths (#69, DESIGN 7.1/7.2). Pure: no Pixi, no DOM, no socket,
// so it is unit-tested next to the reducer seam. The renderer is the only consumer that turns these
// numbers into a transform and sprites.
//
// Coordinate convention: world pixels are the scene's own (`0..scene.w`, `0..scene.h`). The camera
// is the world container's transform: `screen = world * zoom + (x, y)`. Panning changes x/y;
// zooming around an anchor keeps the world point under that anchor fixed (wheel and pinch).
//
// Zoom bounds are the owner-delegated numbers of spec #63 decision 7: a player stops at 0.5
// (ADR-0013, the cheapest bound on how many tiles a phone can ask for) and both roles stop at 4.0.
// The GM has no low clamp; GM_MIN_ZOOM is only a sanity floor so the transform can never become
// singular (a GM surveying a 16k scene at 0.1 still sees everything they need).
import type { Role, SceneInfo } from './protocol.ts'
export const PLAYER_MIN_ZOOM = 0.5
export const MAX_ZOOM = 4
/** No player-style low clamp for the GM; this only keeps `zoom > 0`. */
export const GM_MIN_ZOOM = 1 / 64
/** The tile window is the viewport plus exactly this many tiles on every side (spec decision 12). */
export const VIEWPORT_MARGIN_TILES = 1
export interface Camera {
/** Screen x of world x = 0, in CSS pixels. */
x: number
/** Screen y of world y = 0, in CSS pixels. */
y: number
zoom: number
}
export interface ViewportSize {
width: number
height: number
}
export interface VisibleTile {
x: number
y: number
url: string
}
export function minZoom(role: Role | null): number {
return role === 'player' ? PLAYER_MIN_ZOOM : GM_MIN_ZOOM
}
export function clampZoom(role: Role | null, zoom: number): number {
if (Number.isNaN(zoom)) return 1
if (zoom === Number.POSITIVE_INFINITY) return MAX_ZOOM
if (zoom === Number.NEGATIVE_INFINITY) return minZoom(role)
return Math.min(MAX_ZOOM, Math.max(minZoom(role), zoom))
}
/** The starting view: the whole scene centred in the viewport at zoom 1. */
export function centredCamera(scene: SceneInfo, size: ViewportSize, zoom = 1): Camera {
return {
x: size.width / 2 - (scene.w / 2) * zoom,
y: size.height / 2 - (scene.h / 2) * zoom,
zoom,
}
}
export function screenToWorld(camera: Camera, screenX: number, screenY: number): [number, number] {
return [(screenX - camera.x) / camera.zoom, (screenY - camera.y) / camera.zoom]
}
export function worldToScreen(camera: Camera, worldX: number, worldY: number): [number, number] {
return [worldX * camera.zoom + camera.x, worldY * camera.zoom + camera.y]
}
export function panCamera(camera: Camera, dx: number, dy: number): Camera {
return { ...camera, x: camera.x + dx, y: camera.y + dy }
}
/**
* Multiply the zoom by `factor` around a screen anchor: the world point under the anchor does not
* move, which is what a wheel over the pointer or a pinch between two fingers must feel like.
*/
export function zoomCamera(
role: Role | null,
camera: Camera,
factor: number,
anchor: { x: number; y: number },
): Camera {
return zoomCameraTo(role, camera, camera.zoom * factor, anchor)
}
export function zoomCameraTo(
role: Role | null,
camera: Camera,
zoom: number,
anchor: { x: number; y: number },
): Camera {
const next = clampZoom(role, zoom)
const [worldX, worldY] = screenToWorld(camera, anchor.x, anchor.y)
return { x: anchor.x - worldX * next, y: anchor.y - worldY * next, zoom: next }
}
/**
* Two-finger pinch: the world point under the starting midpoint stays under the (possibly moved)
* midpoint, scaled by how far apart the fingers are now.
*/
export function pinchCamera(
role: Role | null,
start: Camera,
startDistance: number,
distance: number,
startMidpoint: { x: number; y: number },
midpoint: { x: number; y: number },
): Camera {
const safeStart = startDistance > 0 ? startDistance : 1
const [worldX, worldY] = screenToWorld(start, startMidpoint.x, startMidpoint.y)
const zoom = clampZoom(role, start.zoom * (distance / safeStart))
return { x: midpoint.x - worldX * zoom, y: midpoint.y - worldY * zoom, zoom }
}
/**
* The tiles a viewport needs: every tile intersecting the viewport, plus `VIEWPORT_MARGIN_TILES`
* on each side, clamped to the scene grid and returned in viewport order (row-major, top-left to
* bottom-right). Never a tile beyond that margin, so the client cannot prefetch the map.
*/
export function visibleTiles(
scene: SceneInfo,
camera: Camera,
size: ViewportSize,
marginTiles = VIEWPORT_MARGIN_TILES,
): VisibleTile[] {
const tileSize = scene.tile_size
if (!(tileSize > 0)) return []
const columns = Math.ceil(scene.w / tileSize)
const rows = Math.ceil(scene.h / tileSize)
if (columns <= 0 || rows <= 0) return []
const [worldLeft, worldTop] = screenToWorld(camera, 0, 0)
const [worldRight, worldBottom] = screenToWorld(camera, size.width, size.height)
const margin = marginTiles * tileSize
const x0 = Math.max(0, Math.floor((worldLeft - margin) / tileSize))
const y0 = Math.max(0, Math.floor((worldTop - margin) / tileSize))
const x1 = Math.min(columns - 1, Math.ceil((worldRight + margin) / tileSize) - 1)
const y1 = Math.min(rows - 1, Math.ceil((worldBottom + margin) / tileSize) - 1)
const tiles: VisibleTile[] = []
for (let y = y0; y <= y1; y++) {
for (let x = x0; x <= x1; x++) tiles.push({ x, y, url: tileUrl(scene, x, y) })
}
return tiles
}
/** The canonical tile URL of DESIGN 3.3: digits only, no leading zeros, `v` + art_version. */
export function tileUrl(scene: Pick<SceneInfo, 'id' | 'art_version'>, x: number, y: number): string {
return `/tiles/${scene.id}/v${scene.art_version}/${x}_${y}.png`
}
// ---------------------------------------------------------------------------------------------
// The renderer's viewport model. It lives outside `slices/` on purpose: camera and grid are local
// UI state, not server-derived state, so a `hello` reset must not move the player's view. The
// renderer remounts it when a new stage is created; a reconnect keeps the stage, so it also keeps
// the camera (and the tile cache).
export interface ViewportState {
scene: SceneInfo | null
role: Role | null
size: ViewportSize
camera: Camera
/** Grid defaults to on; players and the GM toggle it with the same button (story 18). */
grid: boolean
}
export type ViewportListener = (state: ViewportState) => void
const EMPTY_SIZE: ViewportSize = { width: 1, height: 1 }
export class ViewportModel {
#state: ViewportState = {
scene: null,
role: null,
size: EMPTY_SIZE,
camera: { x: 0, y: 0, zoom: 1 },
grid: true,
}
#listeners = new Set<ViewportListener>()
get state(): ViewportState {
return this.#state
}
subscribe(listener: ViewportListener): () => void {
this.#listeners.add(listener)
return () => {
this.#listeners.delete(listener)
}
}
/** A fresh stage: start from the scene centre at zoom 1 with the grid on. */
reset(scene: SceneInfo | null, role: Role | null, size: ViewportSize): void {
this.#state = {
scene,
role,
size,
camera: scene ? centredCamera(scene, size) : { x: 0, y: 0, zoom: 1 },
grid: true,
}
this.#emit()
}
setSize(size: ViewportSize): void {
if (size.width === this.#state.size.width && size.height === this.#state.size.height) return
this.#state = { ...this.#state, size }
this.#emit()
}
/** The role decides the clamp; a downgrade to player immediately lifts zoom to 0.5. */
setRole(role: Role | null): void {
if (role === this.#state.role) return
const zoom = clampZoom(role, this.#state.camera.zoom)
this.#state = { ...this.#state, role, camera: { ...this.#state.camera, zoom } }
this.#emit()
}
setScene(scene: SceneInfo | null): void {
if (scene?.id === this.#state.scene?.id) {
if (scene && scene !== this.#state.scene) this.#state = { ...this.#state, scene }
return
}
this.reset(scene, this.#state.role, this.#state.size)
}
pan(dx: number, dy: number): void {
this.#state = { ...this.#state, camera: panCamera(this.#state.camera, dx, dy) }
this.#emit()
}
zoomAt(factor: number, anchor: { x: number; y: number }): void {
const camera = zoomCamera(this.#state.role, this.#state.camera, factor, anchor)
const current = this.#state.camera
if (camera.zoom === current.zoom && camera.x === current.x && camera.y === current.y) return
this.#state = { ...this.#state, camera }
this.#emit()
}
pinch(
start: Camera,
startDistance: number,
distance: number,
startMidpoint: { x: number; y: number },
midpoint: { x: number; y: number },
): void {
const camera = pinchCamera(this.#state.role, start, startDistance, distance, startMidpoint, midpoint)
this.#state = { ...this.#state, camera }
this.#emit()
}
setGrid(visible: boolean): void {
if (visible === this.#state.grid) return
this.#state = { ...this.#state, grid: visible }
this.#emit()
}
toggleGrid(): void {
this.setGrid(!this.#state.grid)
}
#emit(): void {
for (const listener of this.#listeners) listener(this.#state)
}
}
/** The single viewport the render modules share. */
export const viewport = new ViewportModel()