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:
@@ -0,0 +1,172 @@
|
||||
// The tile scheduler (#69, spec #63 decision 12): viewport-order requests, a bounded concurrency of
|
||||
// 8, a decoded-texture cache the tile module keeps across reconnect, no duplicate in-flight fetch,
|
||||
// and a denied tile (403/404) is remembered so the client never retries it in a loop.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { TILE_CONCURRENCY, TileScheduler } from '../src/tiles.ts'
|
||||
import type { TileLoadResult } from '../src/tiles.ts'
|
||||
|
||||
interface Harness {
|
||||
scheduler: TileScheduler
|
||||
calls: string[]
|
||||
maxActive: number
|
||||
settle(url: string, result: TileLoadResult): void
|
||||
settleAll(result: TileLoadResult): void
|
||||
idle: number
|
||||
}
|
||||
|
||||
function harness(concurrency = TILE_CONCURRENCY): Harness {
|
||||
const calls: string[] = []
|
||||
const pending = new Map<string, (result: TileLoadResult) => void>()
|
||||
let active = 0
|
||||
let maxActive = 0
|
||||
const state = { idle: 0 }
|
||||
const scheduler = new TileScheduler({
|
||||
concurrency,
|
||||
load: url => {
|
||||
calls.push(url)
|
||||
active += 1
|
||||
maxActive = Math.max(maxActive, active)
|
||||
return new Promise<TileLoadResult>(resolve => {
|
||||
pending.set(url, result => {
|
||||
active -= 1
|
||||
pending.delete(url)
|
||||
resolve(result)
|
||||
})
|
||||
})
|
||||
},
|
||||
onIdle: () => {
|
||||
state.idle += 1
|
||||
},
|
||||
})
|
||||
return {
|
||||
scheduler,
|
||||
calls,
|
||||
get maxActive() {
|
||||
return maxActive
|
||||
},
|
||||
settle(url, result) {
|
||||
const resolve = pending.get(url)
|
||||
if (!resolve) throw new Error(`no pending load for ${url}`)
|
||||
resolve(result)
|
||||
},
|
||||
settleAll(result) {
|
||||
for (const url of [...pending.keys()]) {
|
||||
pending.get(url)?.(result)
|
||||
pending.delete(url)
|
||||
}
|
||||
},
|
||||
get idle() {
|
||||
return state.idle
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
function urls(count: number): string[] {
|
||||
return Array.from({ length: count }, (_, index) => `/tiles/1/v1/${index}_0.png`)
|
||||
}
|
||||
|
||||
/** Let every queued promise callback and the next pump round run. */
|
||||
async function flush(): Promise<void> {
|
||||
for (let i = 0; i < 20; i++) await Promise.resolve()
|
||||
}
|
||||
|
||||
describe('TileScheduler', () => {
|
||||
it('starts at most 8 loads at once, in the order asked', async () => {
|
||||
expect(TILE_CONCURRENCY).toBe(8)
|
||||
const h = harness()
|
||||
const list = urls(20)
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual(list.slice(0, 8))
|
||||
expect(h.maxActive).toBe(8)
|
||||
h.settle(list[0] as string, 'ok')
|
||||
await flush()
|
||||
expect(h.calls[8]).toBe(list[8])
|
||||
expect(h.maxActive).toBe(8)
|
||||
// Each settle opens a slot for the next queued tile; drain every round.
|
||||
for (let round = 0; round < 4 && h.calls.length < 20; round++) {
|
||||
h.settleAll('ok')
|
||||
await flush()
|
||||
}
|
||||
expect(h.calls.length).toBe(20)
|
||||
expect(h.maxActive).toBe(8)
|
||||
})
|
||||
|
||||
it('never asks twice for the same tile', () => {
|
||||
const h = harness()
|
||||
const list = urls(4)
|
||||
h.scheduler.setDesired(list)
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual(list)
|
||||
})
|
||||
|
||||
it('remembers a denied tile and never retries it', async () => {
|
||||
const h = harness()
|
||||
const list = urls(1)
|
||||
h.scheduler.setDesired(list)
|
||||
h.settle(list[0] as string, 'denied')
|
||||
await flush()
|
||||
expect(h.scheduler.status(list[0] as string)).toBe('denied')
|
||||
h.scheduler.setDesired(list)
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual(list)
|
||||
})
|
||||
|
||||
it('reports idle once when every wanted tile is settled', async () => {
|
||||
const h = harness()
|
||||
const list = urls(3)
|
||||
h.scheduler.setDesired(list)
|
||||
h.settleAll('ok')
|
||||
await flush()
|
||||
expect(h.scheduler.isComplete(list)).toBe(true)
|
||||
expect(h.idle).toBe(1)
|
||||
})
|
||||
|
||||
it('drops queued work that left the viewport (no prefetch beyond the margin)', async () => {
|
||||
const h = harness()
|
||||
const list = urls(20)
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls.length).toBe(8)
|
||||
h.scheduler.setDesired([list[0] as string])
|
||||
h.settleAll('ok')
|
||||
await flush()
|
||||
// Only the first 8 were ever started; the 12 queued tiles were cancelled.
|
||||
expect(h.calls.length).toBe(8)
|
||||
expect(h.scheduler.status(list[19] as string)).toBeUndefined()
|
||||
})
|
||||
|
||||
it('does not retry a failed tile on the same window, only on a new one', async () => {
|
||||
const h = harness()
|
||||
const list = urls(2)
|
||||
h.scheduler.setDesired([list[0] as string])
|
||||
h.settle(list[0] as string, 'error')
|
||||
await flush()
|
||||
expect(h.scheduler.isComplete([list[0] as string])).toBe(false)
|
||||
expect(h.calls).toEqual([list[0]])
|
||||
// Same window: the rAF sync after the failure must not hammer the server.
|
||||
h.scheduler.setDesired([list[0] as string])
|
||||
expect(h.calls).toEqual([list[0]])
|
||||
// A new window that still wants the tile asks once more.
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual([list[0], list[0], list[1]])
|
||||
})
|
||||
|
||||
it('markLoaded satisfies a tile from the texture cache without a request', () => {
|
||||
const h = harness()
|
||||
const list = urls(1)
|
||||
h.scheduler.markLoaded(list[0] as string)
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual([])
|
||||
expect(h.scheduler.isComplete(list)).toBe(true)
|
||||
})
|
||||
|
||||
it('retryFailed makes a transient failure askable again after a reconnect', async () => {
|
||||
const h = harness()
|
||||
const list = urls(1)
|
||||
h.scheduler.setDesired(list)
|
||||
h.settle(list[0] as string, 'error')
|
||||
await flush()
|
||||
h.scheduler.retryFailed()
|
||||
h.scheduler.setDesired(list)
|
||||
expect(h.calls).toEqual([list[0], list[0]])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,188 @@
|
||||
// Camera and viewport maths (#69, DESIGN 7.1/7.2, ADR-0013). Pure: no Pixi, no DOM, so this is
|
||||
// the same cheap seam as the reducer. The numbers here are the contract: players clamp at 0.5 and
|
||||
// the GM has no low clamp; both stop at 4.0; a viewport asks for its tiles plus exactly one tile of
|
||||
// margin, clamped to the scene.
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import type { SceneInfo } from '../src/protocol.ts'
|
||||
import {
|
||||
GM_MIN_ZOOM,
|
||||
MAX_ZOOM,
|
||||
PLAYER_MIN_ZOOM,
|
||||
VIEWPORT_MARGIN_TILES,
|
||||
ViewportModel,
|
||||
clampZoom,
|
||||
centredCamera,
|
||||
pinchCamera,
|
||||
screenToWorld,
|
||||
tileUrl,
|
||||
visibleTiles,
|
||||
worldToScreen,
|
||||
zoomCamera,
|
||||
} from '../src/viewport.ts'
|
||||
|
||||
const scene: SceneInfo = {
|
||||
id: 1,
|
||||
name: 'Scene',
|
||||
w: 4096,
|
||||
h: 4096,
|
||||
tile_size: 32,
|
||||
cell: 32,
|
||||
grid_size: 32,
|
||||
vision_radius_default: 320,
|
||||
token_radius_default: 20,
|
||||
art_version: 1,
|
||||
}
|
||||
|
||||
const size = { width: 320, height: 320 }
|
||||
|
||||
describe('zoom clamps (ADR-0013, spec #63 decision 7)', () => {
|
||||
it('a player stops exactly at 0.5 and 4.0', () => {
|
||||
expect(PLAYER_MIN_ZOOM).toBe(0.5)
|
||||
expect(MAX_ZOOM).toBe(4)
|
||||
expect(clampZoom('player', 0.4)).toBe(0.5)
|
||||
expect(clampZoom('player', 0.5)).toBe(0.5)
|
||||
expect(clampZoom('player', 1)).toBe(1)
|
||||
expect(clampZoom('player', 4)).toBe(4)
|
||||
expect(clampZoom('player', 4.1)).toBe(4)
|
||||
})
|
||||
|
||||
it('the GM has no player low clamp, but the same 4.0 ceiling', () => {
|
||||
expect(GM_MIN_ZOOM).toBeLessThan(0.5)
|
||||
expect(clampZoom('gm', 0.25)).toBe(0.25)
|
||||
expect(clampZoom('gm', 0.1)).toBe(0.1)
|
||||
expect(clampZoom('gm', GM_MIN_ZOOM)).toBe(GM_MIN_ZOOM)
|
||||
expect(clampZoom('gm', 0.0001)).toBe(GM_MIN_ZOOM)
|
||||
expect(clampZoom('gm', 4.1)).toBe(4)
|
||||
})
|
||||
|
||||
it('an unknown or non-finite zoom falls back to 1', () => {
|
||||
expect(clampZoom(null, Number.NaN)).toBe(1)
|
||||
expect(clampZoom('player', Number.POSITIVE_INFINITY)).toBe(4)
|
||||
})
|
||||
})
|
||||
|
||||
describe('camera', () => {
|
||||
it('centres on the scene at zoom 1', () => {
|
||||
const camera = centredCamera(scene, size)
|
||||
expect(camera.zoom).toBe(1)
|
||||
expect(camera.x + (scene.w / 2) * camera.zoom).toBe(size.width / 2)
|
||||
expect(camera.y + (scene.h / 2) * camera.zoom).toBe(size.height / 2)
|
||||
})
|
||||
|
||||
it('screenToWorld and worldToScreen are inverses', () => {
|
||||
const camera = { x: -100, y: -200, zoom: 2 }
|
||||
const world = screenToWorld(camera, 40, 80)
|
||||
expect(world).toEqual([70, 140])
|
||||
const screen = worldToScreen(camera, world[0], world[1])
|
||||
expect(screen[0]).toBeCloseTo(40, 10)
|
||||
expect(screen[1]).toBeCloseTo(80, 10)
|
||||
})
|
||||
|
||||
it('zoomCamera keeps the world point under the anchor fixed and clamps', () => {
|
||||
const camera = { x: -1000, y: -800, zoom: 1 }
|
||||
const anchor = { x: 120, y: 200 }
|
||||
const before = screenToWorld(camera, anchor.x, anchor.y)
|
||||
const zoomed = zoomCamera('player', camera, 0.1, anchor)
|
||||
expect(zoomed.zoom).toBe(0.5)
|
||||
const after = screenToWorld(zoomed, anchor.x, anchor.y)
|
||||
expect(after[0]).toBeCloseTo(before[0], 10)
|
||||
expect(after[1]).toBeCloseTo(before[1], 10)
|
||||
expect(zoomCamera('player', camera, 100, anchor).zoom).toBe(4)
|
||||
})
|
||||
|
||||
it('pinch zooms around the starting midpoint and follows it as it moves', () => {
|
||||
const start = { x: -1000, y: -800, zoom: 1 }
|
||||
const startMid = { x: 100, y: 100 }
|
||||
const world = screenToWorld(start, startMid.x, startMid.y)
|
||||
const movedMid = { x: 140, y: 120 }
|
||||
const pinched = pinchCamera('player', start, 100, 200, startMid, movedMid)
|
||||
expect(pinched.zoom).toBe(2)
|
||||
const atMoved = screenToWorld(pinched, movedMid.x, movedMid.y)
|
||||
expect(atMoved[0]).toBeCloseTo(world[0], 10)
|
||||
expect(atMoved[1]).toBeCloseTo(world[1], 10)
|
||||
expect(pinchCamera('player', start, 100, 1, startMid, startMid).zoom).toBe(0.5)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ViewportModel (the render layer\'s UI state)', () => {
|
||||
it('pans, toggles the grid and re-clamps when the role becomes a player', () => {
|
||||
const model = new ViewportModel()
|
||||
model.reset(scene, 'gm', size)
|
||||
model.pan(10, -20)
|
||||
expect(model.state.camera.x).toBe(centredCamera(scene, size).x + 10)
|
||||
expect(model.state.camera.y).toBe(centredCamera(scene, size).y - 20)
|
||||
expect(model.state.grid).toBe(true)
|
||||
model.toggleGrid()
|
||||
expect(model.state.grid).toBe(false)
|
||||
// A GM zoomed to 0.25; the same view cannot stay below the player floor.
|
||||
model.zoomAt(0.25, { x: 0, y: 0 })
|
||||
expect(model.state.camera.zoom).toBe(0.25)
|
||||
model.setRole('player')
|
||||
expect(model.state.camera.zoom).toBe(0.5)
|
||||
})
|
||||
|
||||
it('keeps the camera across a same-scene resync and resets for a new scene', () => {
|
||||
const model = new ViewportModel()
|
||||
model.reset(scene, 'player', size)
|
||||
model.pan(-40, 0)
|
||||
const panned = model.state.camera
|
||||
model.setScene({ ...scene })
|
||||
expect(model.state.camera).toBe(panned)
|
||||
model.setScene({ ...scene, id: 2 })
|
||||
expect(model.state.camera).toEqual(centredCamera({ ...scene, id: 2 }, size))
|
||||
})
|
||||
})
|
||||
|
||||
describe('visible tiles', () => {
|
||||
it('returns the viewport plus one tile of margin, row-major, inside the scene', () => {
|
||||
const camera = centredCamera(scene, size)
|
||||
const tiles = visibleTiles(scene, camera, size)
|
||||
// 320 px at zoom 1 is 10 tiles; one margin on each side is 12 x 12.
|
||||
expect(tiles.length).toBe(12 * 12)
|
||||
expect(tiles[0]).toMatchObject({ x: 58, y: 58 })
|
||||
expect(tiles[tiles.length - 1]).toMatchObject({ x: 69, y: 69 })
|
||||
expect(tiles[0]?.url).toBe('/tiles/1/v1/58_58.png')
|
||||
expect(tiles.every(tile => tile.x >= 0 && tile.x < 128 && tile.y >= 0 && tile.y < 128)).toBe(true)
|
||||
// row-major: every tile of a row comes before the next row.
|
||||
const ys = tiles.map(tile => tile.y)
|
||||
expect(ys).toEqual([...ys].sort((a, b) => a - b))
|
||||
})
|
||||
|
||||
it('clamps the margin at the scene edges', () => {
|
||||
const camera = { x: 0, y: 0, zoom: 1 }
|
||||
const tiles = visibleTiles(scene, camera, size)
|
||||
expect(tiles[0]).toMatchObject({ x: 0, y: 0 })
|
||||
// 320 px + one tile margin to the right/down => 0..10 inclusive.
|
||||
expect(Math.max(...tiles.map(tile => tile.x))).toBe(10)
|
||||
expect(Math.max(...tiles.map(tile => tile.y))).toBe(10)
|
||||
})
|
||||
|
||||
it('scales with zoom (out asks for more, in for fewer)', () => {
|
||||
const out = visibleTiles(scene, centredCamera(scene, size, 0.5), size)
|
||||
const inn = visibleTiles(scene, centredCamera(scene, size, 4), size)
|
||||
expect(out.length).toBeGreaterThan(inn.length)
|
||||
// At 0.5 a 320 px viewport is 640 world px: 20 tiles + 2 margin = 22 per axis.
|
||||
expect(out.length).toBe(22 * 22)
|
||||
})
|
||||
|
||||
it('never prefetches beyond the margin', () => {
|
||||
const camera = centredCamera(scene, size)
|
||||
const tiles = visibleTiles(scene, camera, size)
|
||||
const maxX = Math.max(...tiles.map(tile => tile.x))
|
||||
const minX = Math.min(...tiles.map(tile => tile.x))
|
||||
const viewport = visibleTiles(scene, camera, { width: 320, height: 320 })
|
||||
// Calling twice is deterministic; the margin is exactly one tile (VIEWPORT_MARGIN_TILES).
|
||||
expect(VIEWPORT_MARGIN_TILES).toBe(1)
|
||||
expect(maxX - minX).toBe(11)
|
||||
expect(viewport.length).toBe(tiles.length)
|
||||
})
|
||||
|
||||
it('returns nothing when the camera looks outside the map', () => {
|
||||
expect(visibleTiles(scene, { x: 100000, y: 100000, zoom: 1 }, size)).toEqual([])
|
||||
})
|
||||
|
||||
it('builds the canonical tile URL', () => {
|
||||
expect(tileUrl(scene, 0, 0)).toBe('/tiles/1/v1/0_0.png')
|
||||
expect(tileUrl(scene, 127, 3)).toBe('/tiles/1/v1/127_3.png')
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user