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
+187
View File
@@ -0,0 +1,187 @@
// Pan, zoom and pinch (story 15, spec #63 decision 7; ADR-0013). Hand-rolled DOM pointer events,
// as DESIGN 7.2 keeps Pixi federated events off: the camera is a transform on the world container,
// so a pan is two numbers and never a redraw of the map.
//
// The module also owns the grid toggle button and the small `data-*` view contract the browser e2e
// reads: `data-zoom` (the exact clamped number), `data-grid` (on/off) and `data-tiles` (the tile
// module marks `ready` when every wanted tile of the current viewport has settled). Those are UI
// facts, not renderer internals.
import type { RenderModule } from '../stage.ts'
import type { Camera } from '../../viewport.ts'
import { viewport } from '../../viewport.ts'
interface Point {
x: number
y: number
}
function canvasPoint(canvas: HTMLCanvasElement, event: PointerEvent | WheelEvent): Point {
const rect = canvas.getBoundingClientRect()
return { x: event.clientX - rect.left, y: event.clientY - rect.top }
}
function distance(a: Point, b: Point): number {
return Math.hypot(a.x - b.x, a.y - b.y)
}
function midpoint(a: Point, b: Point): Point {
return { x: (a.x + b.x) / 2, y: (a.y + b.y) / 2 }
}
/** Wheel delta in CSS pixels; Firefox reports lines and pages instead. */
function wheelPixels(event: WheelEvent): number {
if (event.deltaMode === 1) return event.deltaY * 16
if (event.deltaMode === 2) return event.deltaY * 400
return event.deltaY
}
export const renderModule: RenderModule = {
name: 'camera',
mount({ app, world, store }) {
const canvas = app.canvas
canvas.style.touchAction = 'none'
canvas.style.cursor = 'grab'
const size = () => ({ width: app.screen.width, height: app.screen.height })
viewport.reset(store.state.session.scene, store.state.session.role, size())
function apply(): void {
const { camera, grid } = viewport.state
world.scale.set(camera.zoom)
world.position.set(camera.x, camera.y)
canvas.dataset['zoom'] = String(camera.zoom)
canvas.dataset['grid'] = grid ? 'on' : 'off'
canvas.dataset['view'] = `${viewport.state.size.width}x${viewport.state.size.height}`
}
const unsubscribeViewport = viewport.subscribe(apply)
apply()
// --- session / resize ----------------------------------------------------------------
function syncSession(): void {
const scene = store.state.session.scene
const role = store.state.session.role
if (scene) viewport.setScene(scene)
viewport.setRole(role)
if (store.state.connection.phase === 'live' || store.state.connection.phase === 'reconnecting') {
viewport.setSize(size())
}
}
const unsubscribeStore = store.subscribe(syncSession)
function onResize(): void {
viewport.setSize(size())
}
window.addEventListener('resize', onResize)
// --- grid toggle (story 18) ----------------------------------------------------------
const button = document.createElement('button')
button.id = 'grid-toggle'
button.type = 'button'
button.textContent = 'Grid'
button.hidden = true
button.style.cssText =
'position:fixed;left:12px;bottom:12px;padding:6px 12px;border-radius:6px;' +
'border:1px solid #777;background:rgb(20 20 20 / 85%);color:#eee;font:12px/1.4 ' +
'ui-monospace,monospace;cursor:pointer;z-index:2;pointer-events:auto'
button.addEventListener('click', () => viewport.toggleGrid())
const panels = document.querySelector('#panels') ?? document.body
panels.append(button)
function syncButton(): void {
const phase = store.state.connection.phase
button.hidden = phase !== 'live' && phase !== 'reconnecting'
button.setAttribute('aria-pressed', viewport.state.grid ? 'true' : 'false')
button.style.opacity = viewport.state.grid ? '1' : '0.55'
}
const unsubscribeButton = viewport.subscribe(syncButton)
const unsubscribeButtonStore = store.subscribe(syncButton)
syncButton()
// --- pointer pan / pinch -------------------------------------------------------------
const pointers = new Map<number, Point>()
let drag: Point | null = null
let pinch: { start: Camera; distance: number; midpoint: Point } | null = null
function beginPinch(): void {
const [a, b] = [...pointers.values()]
if (!a || !b) return
drag = null
pinch = { start: viewport.state.camera, distance: distance(a, b), midpoint: midpoint(a, b) }
}
function onPointerDown(event: PointerEvent): void {
if (event.pointerType === 'mouse' && event.button !== 0) return
pointers.set(event.pointerId, canvasPoint(canvas, event))
try {
canvas.setPointerCapture(event.pointerId)
} catch {
// Synthetic pointers (the e2e's touch pinch) are not active pointers to capture.
}
if (pointers.size === 1) {
drag = canvasPoint(canvas, event)
} else if (pointers.size === 2) {
beginPinch()
}
canvas.style.cursor = 'grabbing'
}
function onPointerMove(event: PointerEvent): void {
if (!pointers.has(event.pointerId)) return
const point = canvasPoint(canvas, event)
pointers.set(event.pointerId, point)
if (pinch && pointers.size >= 2) {
const [a, b] = [...pointers.values()]
if (!a || !b) return
viewport.pinch(
pinch.start,
pinch.distance,
distance(a, b),
pinch.midpoint,
midpoint(a, b),
)
return
}
if (drag) {
viewport.pan(point.x - drag.x, point.y - drag.y)
drag = point
}
}
function onPointerUp(event: PointerEvent): void {
pointers.delete(event.pointerId)
if (pointers.size < 2) pinch = null
const [remaining] = [...pointers.values()]
drag = pointers.size === 1 && remaining ? remaining : null
if (pointers.size === 0) canvas.style.cursor = 'grab'
}
function onWheel(event: WheelEvent): void {
event.preventDefault()
const factor = Math.exp(-wheelPixels(event) * 0.0015)
viewport.zoomAt(factor, canvasPoint(canvas, event))
}
canvas.addEventListener('pointerdown', onPointerDown)
canvas.addEventListener('pointermove', onPointerMove)
canvas.addEventListener('pointerup', onPointerUp)
canvas.addEventListener('pointercancel', onPointerUp)
canvas.addEventListener('wheel', onWheel, { passive: false })
return () => {
unsubscribeViewport()
unsubscribeStore()
unsubscribeButton()
unsubscribeButtonStore()
window.removeEventListener('resize', onResize)
canvas.removeEventListener('pointerdown', onPointerDown)
canvas.removeEventListener('pointermove', onPointerMove)
canvas.removeEventListener('pointerup', onPointerUp)
canvas.removeEventListener('pointercancel', onPointerUp)
canvas.removeEventListener('wheel', onWheel)
button.remove()
world.position.set(0, 0)
world.scale.set(1)
}
},
}
+79
View File
@@ -0,0 +1,79 @@
// The grid layer (story 18, DESIGN 7.1 layer 2): one TilingSprite over a tiny cell texture, not a
// per-frame redraw. The texture is `grid_size` world pixels square with a one-pixel line along its
// top/left edge; tiling it across the scene puts a line on every cell boundary.
//
// The toggle is owned by the camera module (`#grid-toggle`); this module only follows
// `viewport.grid` and writes `data-grid` on the canvas so the e2e can prove the state change.
import { Texture, TilingSprite } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import type { SceneInfo } from '../../protocol.ts'
import { viewport } from '../../viewport.ts'
function gridTexture(cell: number): Texture {
const canvas = document.createElement('canvas')
canvas.width = cell
canvas.height = cell
const context = canvas.getContext('2d')
if (context) {
context.strokeStyle = 'rgba(230, 240, 255, 0.30)'
context.lineWidth = 1
context.beginPath()
context.moveTo(0.5, 0)
context.lineTo(0.5, cell)
context.moveTo(0, 0.5)
context.lineTo(cell, 0.5)
context.stroke()
}
const texture = Texture.from(canvas)
texture.source.label = `grid-${cell}`
return texture
}
export const renderModule: RenderModule = {
name: 'grid',
mount({ app, layers }) {
let sprite: TilingSprite | null = null
let texture: Texture | null = null
let sceneId: number | null = null
function build(scene: SceneInfo): void {
const cell = Math.max(4, Math.round(scene.grid_size || scene.tile_size || 32))
texture = gridTexture(cell)
sprite = new TilingSprite({ texture, width: scene.w, height: scene.h })
sprite.label = 'grid'
layers.grid.addChild(sprite)
sceneId = scene.id
}
function sync(): void {
const { scene, grid } = viewport.state
if (!scene) {
if (sprite) sprite.visible = false
return
}
if (scene.id !== sceneId) {
destroy()
build(scene)
}
if (sprite) sprite.visible = grid
app.canvas.dataset['grid'] = grid ? 'on' : 'off'
}
function destroy(): void {
sprite?.destroy()
sprite = null
texture?.destroy(true)
texture = null
sceneId = null
}
const unsubscribe = viewport.subscribe(sync)
sync()
return () => {
unsubscribe()
destroy()
}
},
}
+136
View File
@@ -0,0 +1,136 @@
// The tile layer (story 13/14/19, DESIGN 7.1 layer 1, spec #63 decision 12).
//
// 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. Sprites outside the wanted window are removed but their textures are kept.
//
// 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
// viewport wants has settled with `ok` or `denied`, which is what the tile-size gate (a) measures.
import { Sprite, Texture } from 'pixi.js'
import type { RenderModule } from '../stage.ts'
import { viewport } from '../../viewport.ts'
import { visibleTiles } from '../../viewport.ts'
import { TileScheduler } from '../../tiles.ts'
import type { TileLoadResult } from '../../tiles.ts'
/** Kept across a reconnect (and even a stage rebuild): URL -> decoded texture. */
const textureCache = new Map<string, Texture>()
/** Fetches made by this page; the cache-survives-reconnect proof reads it. */
let requests = 0
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
})
}
async function fetchTile(url: string): Promise<TileLoadResult> {
requests += 1
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))
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'
}
}
}
export const renderModule: RenderModule = {
name: 'tiles',
mount({ app, layers, store }) {
const canvas = app.canvas
const sprites = new Map<string, Sprite>()
let frame = 0
canvas.dataset['tileRequests'] = String(requests)
const scheduler = new TileScheduler({
load: fetchTile,
onSettled: () => scheduleSync(),
})
function scheduleSync(): void {
if (frame !== 0) return
frame = requestAnimationFrame(() => {
frame = 0
sync()
})
}
function sync(): void {
const { scene, camera, size } = viewport.state
if (!scene) {
canvas.dataset['tiles'] = 'idle'
return
}
const wanted = visibleTiles(scene, camera, size)
const wantedUrls = new Set(wanted.map(tile => tile.url))
for (const [url, sprite] of sprites) {
if (wantedUrls.has(url)) continue
sprite.destroy()
sprites.delete(url)
}
const tileSize = scene.tile_size
for (const tile of wanted) {
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)
}
scheduler.setDesired(wanted.map(tile => tile.url))
canvas.dataset['tileRequests'] = String(requests)
canvas.dataset['visibleTiles'] = String(wanted.length)
const settled = wanted.every(tile => {
const status = scheduler.status(tile.url)
return status === 'ok' || status === 'denied'
})
canvas.dataset['tiles'] = wanted.length === 0 ? 'idle' : settled ? 'ready' : 'loading'
}
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) => {
if (event.type === 'frame' && event.frame.t === 'hello') {
scheduler.retryFailed()
scheduleSync()
}
})
scheduleSync()
return () => {
unsubscribe()
unsubscribeStore()
if (frame !== 0) cancelAnimationFrame(frame)
for (const sprite of sprites.values()) sprite.destroy()
sprites.clear()
}
},
}
+138
View File
@@ -0,0 +1,138 @@
// The tile scheduler (#69, spec #63 decision 12). Pure: the loader is injected, so the concurrency,
// cache and denial rules are unit-tested without a browser or a GPU.
//
// Rules encoded here:
// - at most TILE_CONCURRENCY (8) requests in flight;
// - the wanted list is the viewport plus one tile of margin, in viewport order;
// - a tile is never fetched twice (a decoded texture is cached by the tile module across a
// reconnect; this scheduler remembers settled URLs too);
// - 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;
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
// prefetches beyond the margin.
export const TILE_CONCURRENCY = 8
export type TileLoadResult = 'ok' | 'denied' | 'error'
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
export interface TileSchedulerOptions {
load(url: string): Promise<TileLoadResult>
onSettled?(url: string, result: TileLoadResult): void
onIdle?(): void
concurrency?: number
}
function sameList(a: readonly string[], b: readonly string[]): boolean {
if (a.length !== b.length) return false
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false
return true
}
export class TileScheduler {
readonly #load: (url: string) => Promise<TileLoadResult>
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
readonly #onIdle: (() => void) | undefined
readonly #concurrency: number
#states = new Map<string, TileStatus>()
#queue: string[] = []
#desired = new Set<string>()
#lastDesired: readonly string[] = []
#active = 0
#idle = true
constructor(options: TileSchedulerOptions) {
this.#load = options.load
this.#onSettled = options.onSettled
this.#onIdle = options.onIdle
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
}
status(url: string): TileStatus | undefined {
return this.#states.get(url)
}
get active(): number {
return this.#active
}
/** What the viewport wants now. `urls` is already in viewport order. */
setDesired(urls: readonly string[]): void {
// A settle calls back into the renderer, which syncs again with the same window; skip the
// O(n) rebuild in that common case. It still pumps, which is what opens the next slot.
if (sameList(urls, this.#lastDesired)) {
this.#pump()
return
}
this.#lastDesired = [...urls]
this.#desired = new Set(urls)
// Keep queued entries that are still wanted, in the new viewport order; forget the rest so a
// later viewport that asks for the tile again can queue it fresh.
const order = new Map(urls.map((url, index) => [url, index]))
const dropped = this.#queue.filter(url => !this.#desired.has(url))
for (const url of dropped) this.#states.delete(url)
this.#queue = this.#queue
.filter(url => this.#desired.has(url))
.sort((a, b) => (order.get(a) ?? 0) - (order.get(b) ?? 0))
for (const url of urls) {
const existing = this.#states.get(url)
if (existing === 'error') this.#states.delete(url)
else if (existing !== undefined) continue
this.#states.set(url, 'queued')
this.#queue.push(url)
}
this.#pump()
}
/** A texture already in the cache (e.g. a renderer remount) needs no request. */
markLoaded(url: string): void {
if (!this.#states.has(url)) this.#states.set(url, 'ok')
}
/** Forget transient failures: the next sync (e.g. after a reconnect) may ask again. */
retryFailed(): void {
for (const [url, status] of this.#states) if (status === 'error') this.#states.delete(url)
this.#lastDesired = []
}
/** True when every wanted tile settled with an `ok` or `denied` answer. */
isComplete(urls: readonly string[]): boolean {
return urls.every(url => {
const status = this.#states.get(url)
return status === 'ok' || status === 'denied'
})
}
#pump(): void {
while (this.#active < this.#concurrency && this.#queue.length > 0) {
const url = this.#queue.shift()
if (url === undefined) break
if (!this.#desired.has(url) || this.#states.get(url) !== 'queued') continue
this.#states.set(url, 'loading')
this.#active += 1
this.#idle = false
void this.#load(url).then(
result => this.#settle(url, result),
() => this.#settle(url, 'error'),
)
}
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
this.#idle = true
this.#onIdle?.()
}
}
#settle(url: string, result: TileLoadResult): void {
this.#active -= 1
if (result === 'ok' || result === 'denied') {
this.#states.set(url, result)
} else {
// Transient: remember the failure, but never retry it on the same viewport; only a new
// window or `retryFailed()` (reconnect) asks again. A denied 403 is never retried at all.
this.#states.set(url, 'error')
}
this.#onSettled?.(url, result)
this.#pump()
}
}
+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()