// 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 } } /** The world point at the centre of the viewport: the default position for a new token (#82). */ export function viewportCentre(camera: Camera, size: ViewportSize): [number, number] { return screenToWorld(camera, size.width / 2, size.height / 2) } /** * 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 } /** * Order tiles nearest the viewport centre first (the tile layer's request order). At a GM survey * zoom a 16k scene is tens of thousands of tiles, and the fill should grow out of what the eye is * on, not from the top-left corner. Ties keep the incoming (row-major) order, so it is stable. */ export function orderTilesCentreOut( tiles: readonly VisibleTile[], scene: Pick, camera: Camera, size: ViewportSize, ): VisibleTile[] { const tileSize = scene.tile_size if (!(tileSize > 0)) return [...tiles] const [cx, cy] = screenToWorld(camera, size.width / 2, size.height / 2) const distance = (tile: VisibleTile): number => { const dx = (tile.x + 0.5) * tileSize - cx const dy = (tile.y + 0.5) * tileSize - cy return dx * dx + dy * dy } return [...tiles].sort((a, b) => distance(a) - distance(b)) } /** The canonical tile URL of DESIGN 3.3: digits only, no leading zeros, `v` + art_version. */ export function tileUrl(scene: Pick, 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() 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 === this.#state.scene) return // Same scene, new object (a reconnect `hello`, or a re-import with a new art_version). Keep // the camera, but notify: the tile layer must rebuild its window and drop stale textures. this.#state = { ...this.#state, scene } this.#emit() 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()