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:
@@ -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()
|
||||
|
||||
+140
-21
@@ -1,31 +1,57 @@
|
||||
// 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.
|
||||
// The tile scheduler (#69, spec #63 decision 12; #86 tile-loading). Pure: the loader is injected, so
|
||||
// the concurrency, cache and retry 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;
|
||||
// - at most TILE_CONCURRENCY requests in flight (measured knee: a browser decodes and uploads
|
||||
// faster than one 8-wide queue can keep the server busy on a 16k map, see the issue);
|
||||
// - the wanted list is the viewport plus one tile of margin, ordered by the caller (the renderer
|
||||
// asks nearest the viewport centre first);
|
||||
// - 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;
|
||||
// - a `403` is a permanent `denied` answer: never retried in a loop (the server said no). It is
|
||||
// asked once more only when the fog says its cells just became explored (#70);
|
||||
// - a `404`/`5xx`/network failure is transient: up to TILE_MAX_ATTEMPTS loads with exponential
|
||||
// backoff, then a stored `error` that waits for a new window or a reconnect (`retryFailed`) —
|
||||
// this fixes the black void a missing tile used to leave until a page reload;
|
||||
// - queued tiles that leave the viewport before they start are dropped, so a fast pan never
|
||||
// prefetches beyond the margin;
|
||||
// - a denied tile is asked again only when the fog says its cells just became explored (#70):
|
||||
// the gate's answer changed, so the old "no" is stale.
|
||||
// prefetches beyond the margin.
|
||||
|
||||
import type { SceneInfo } from './protocol.ts'
|
||||
import { tileUrl } from './viewport.ts'
|
||||
|
||||
export const TILE_CONCURRENCY = 8
|
||||
/**
|
||||
* Torrent of small tiles is bounded here, not by the server: the gate + nginx sustain ~2.5k
|
||||
* requests/s, so a narrow client queue is the bottleneck on a survey view. Measured knee on a
|
||||
* Full HD scene at GM fit / player 0.5 (min-of-3, headless SwiftShader): 8 -> 32 cuts the fill
|
||||
* 11-29%; 64 is inside the noise and doubles browser decode pressure, so 32 is the cap.
|
||||
*/
|
||||
export const TILE_CONCURRENCY = 32
|
||||
/** Total loads per URL (first try included) before a transient failure is stored as `error`. */
|
||||
export const TILE_MAX_ATTEMPTS = 3
|
||||
/** First retry delay; each following retry doubles it (250 ms, 500 ms). */
|
||||
export const TILE_RETRY_BASE_MS = 250
|
||||
|
||||
export type TileLoadResult = 'ok' | 'denied' | 'error'
|
||||
export type TileStatus = 'queued' | 'loading' | 'ok' | 'denied' | 'error'
|
||||
|
||||
export type RetryScheduler = (run: () => void, ms: number) => () => void
|
||||
|
||||
const setTimeoutRetry: RetryScheduler = (run, ms) => {
|
||||
const timer = setTimeout(run, ms)
|
||||
return () => clearTimeout(timer)
|
||||
}
|
||||
|
||||
export interface TileSchedulerOptions {
|
||||
load(url: string): Promise<TileLoadResult>
|
||||
onSettled?(url: string, result: TileLoadResult): void
|
||||
onIdle?(): void
|
||||
concurrency?: number
|
||||
/** Bounded transient-failure retries (default TILE_MAX_ATTEMPTS, 3). */
|
||||
maxAttempts?: number
|
||||
/** First backoff in ms; doubles per attempt (default TILE_RETRY_BASE_MS). */
|
||||
retryBaseMs?: number
|
||||
/** Injectable timer, so tests drive backoff without wall-clock waits. */
|
||||
scheduleRetry?: RetryScheduler
|
||||
}
|
||||
|
||||
function sameList(a: readonly string[], b: readonly string[]): boolean {
|
||||
@@ -56,12 +82,32 @@ export function tilesForCells(
|
||||
return [...urls]
|
||||
}
|
||||
|
||||
/**
|
||||
* True when a new scene invalidates every cached tile URL: a different scene, or the same scene
|
||||
* after a re-import (`art_version`). A first scene (no previous) has nothing to invalidate, and a
|
||||
* reconnect to the same version must keep the decoded cache.
|
||||
*/
|
||||
export function tilesInvalidated(
|
||||
previous: Pick<SceneInfo, 'id' | 'art_version'> | null,
|
||||
next: Pick<SceneInfo, 'id' | 'art_version'> | null,
|
||||
): boolean {
|
||||
if (previous === null || next === null) return false
|
||||
return previous.id !== next.id || previous.art_version !== next.art_version
|
||||
}
|
||||
|
||||
export class TileScheduler {
|
||||
readonly #load: (url: string) => Promise<TileLoadResult>
|
||||
readonly #onSettled: ((url: string, result: TileLoadResult) => void) | undefined
|
||||
readonly #onIdle: (() => void) | undefined
|
||||
readonly #concurrency: number
|
||||
readonly #maxAttempts: number
|
||||
readonly #retryBaseMs: number
|
||||
readonly #scheduleRetry: RetryScheduler
|
||||
#states = new Map<string, TileStatus>()
|
||||
#attempts = new Map<string, number>()
|
||||
#timers = new Map<string, () => void>()
|
||||
/** Bumped by `retryFailed`/`reset`: a load that settles after it gets a fresh budget. */
|
||||
#epoch = 0
|
||||
#queue: string[] = []
|
||||
#desired = new Set<string>()
|
||||
#lastDesired: readonly string[] = []
|
||||
@@ -73,6 +119,9 @@ export class TileScheduler {
|
||||
this.#onSettled = options.onSettled
|
||||
this.#onIdle = options.onIdle
|
||||
this.#concurrency = Math.max(1, options.concurrency ?? TILE_CONCURRENCY)
|
||||
this.#maxAttempts = Math.max(1, options.maxAttempts ?? TILE_MAX_ATTEMPTS)
|
||||
this.#retryBaseMs = Math.max(0, options.retryBaseMs ?? TILE_RETRY_BASE_MS)
|
||||
this.#scheduleRetry = options.scheduleRetry ?? setTimeoutRetry
|
||||
}
|
||||
|
||||
status(url: string): TileStatus | undefined {
|
||||
@@ -83,7 +132,7 @@ export class TileScheduler {
|
||||
return this.#active
|
||||
}
|
||||
|
||||
/** What the viewport wants now. `urls` is already in viewport order. */
|
||||
/** What the viewport wants now. `urls` is already in the caller's order (centre-out). */
|
||||
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.
|
||||
@@ -104,8 +153,13 @@ export class TileScheduler {
|
||||
.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
|
||||
if (existing === 'error') {
|
||||
// A bounded retry that already used its attempts stays failed until `retryFailed()`; a
|
||||
// fresh window must not hammer a tile the server keeps 404ing.
|
||||
if ((this.#attempts.get(url) ?? 0) >= this.#maxAttempts) continue
|
||||
this.#cancelRetry(url)
|
||||
this.#states.delete(url)
|
||||
} else if (existing !== undefined) continue
|
||||
this.#states.set(url, 'queued')
|
||||
this.#queue.push(url)
|
||||
}
|
||||
@@ -117,12 +171,43 @@ export class TileScheduler {
|
||||
if (!this.#states.has(url)) this.#states.set(url, 'ok')
|
||||
}
|
||||
|
||||
/** Forget transient failures: the next sync (e.g. after a reconnect) may ask again. */
|
||||
/**
|
||||
* Forget transient failures: the next sync (e.g. after a reconnect) may ask again. The attempt
|
||||
* budget is reset too, so a reconnect gets the full bounded-retry allowance.
|
||||
*/
|
||||
retryFailed(): void {
|
||||
for (const [url, status] of this.#states) if (status === 'error') this.#states.delete(url)
|
||||
for (const cancel of this.#timers.values()) cancel()
|
||||
this.#timers.clear()
|
||||
this.#epoch += 1
|
||||
for (const [url, status] of this.#states) {
|
||||
if (status !== 'error') continue
|
||||
this.#states.delete(url)
|
||||
this.#attempts.delete(url)
|
||||
}
|
||||
this.#lastDesired = []
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop every cached decision and pending retry (a new `art_version`: the URLs all changed).
|
||||
* Loads already in flight settle harmlessly and their results are ignored by the caller.
|
||||
*/
|
||||
reset(): void {
|
||||
for (const cancel of this.#timers.values()) cancel()
|
||||
this.#timers.clear()
|
||||
this.#epoch += 1
|
||||
this.#states.clear()
|
||||
this.#attempts.clear()
|
||||
this.#queue = []
|
||||
this.#desired.clear()
|
||||
this.#lastDesired = []
|
||||
}
|
||||
|
||||
/** Cancel pending retry timers on teardown; no callback runs after this. */
|
||||
dispose(): void {
|
||||
for (const cancel of this.#timers.values()) cancel()
|
||||
this.#timers.clear()
|
||||
}
|
||||
|
||||
/**
|
||||
* A `403` is permanent *for the explored set the server had then*. When the fog slice reports
|
||||
* newly explored cells (#70), the tiles those cells touch may have become allowed, so those
|
||||
@@ -168,9 +253,10 @@ export class TileScheduler {
|
||||
this.#states.set(url, 'loading')
|
||||
this.#active += 1
|
||||
this.#idle = false
|
||||
const epoch = this.#epoch
|
||||
void this.#load(url).then(
|
||||
result => this.#settle(url, result),
|
||||
() => this.#settle(url, 'error'),
|
||||
result => this.#settle(url, result, epoch),
|
||||
() => this.#settle(url, 'error', epoch),
|
||||
)
|
||||
}
|
||||
if (this.#active === 0 && this.#queue.length === 0 && !this.#idle) {
|
||||
@@ -179,16 +265,49 @@ export class TileScheduler {
|
||||
}
|
||||
}
|
||||
|
||||
#settle(url: string, result: TileLoadResult): void {
|
||||
#settle(url: string, result: TileLoadResult, epoch: number): void {
|
||||
this.#active -= 1
|
||||
if (result === 'ok' || result === 'denied') {
|
||||
this.#states.set(url, result)
|
||||
this.#attempts.delete(url)
|
||||
this.#cancelRetry(url)
|
||||
} 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')
|
||||
// Transient: retry with exponential backoff up to `maxAttempts`, then store the failure and
|
||||
// wait for a new window or `retryFailed()` (reconnect). A 403 is a separate `denied` answer.
|
||||
// A reconnect (`retryFailed`) during the load resets the budget: a failure that lands after
|
||||
// it is a fresh first attempt, not the tail of the old one. A tile that left the window
|
||||
// while loading does not spend the budget: a later window can still try it.
|
||||
if (!this.#desired.has(url)) {
|
||||
this.#states.set(url, 'error')
|
||||
} else {
|
||||
const attempt = epoch === this.#epoch ? (this.#attempts.get(url) ?? 0) + 1 : 1
|
||||
this.#attempts.set(url, attempt)
|
||||
this.#states.set(url, 'error')
|
||||
if (attempt < this.#maxAttempts) this.#scheduleRetryFor(url, attempt)
|
||||
}
|
||||
}
|
||||
this.#onSettled?.(url, result)
|
||||
this.#pump()
|
||||
}
|
||||
|
||||
#scheduleRetryFor(url: string, attempt: number): void {
|
||||
this.#cancelRetry(url)
|
||||
const delay = this.#retryBaseMs * 2 ** (attempt - 1)
|
||||
const cancel = this.#scheduleRetry(() => {
|
||||
this.#timers.delete(url)
|
||||
// The window may have moved on, or the tile may have been answered meanwhile.
|
||||
if (this.#states.get(url) !== 'error' || !this.#desired.has(url)) return
|
||||
this.#states.set(url, 'queued')
|
||||
this.#queue.push(url)
|
||||
this.#pump()
|
||||
}, delay)
|
||||
this.#timers.set(url, cancel)
|
||||
}
|
||||
|
||||
#cancelRetry(url: string): void {
|
||||
const cancel = this.#timers.get(url)
|
||||
if (cancel === undefined) return
|
||||
cancel()
|
||||
this.#timers.delete(url)
|
||||
}
|
||||
}
|
||||
|
||||
+27
-1
@@ -151,6 +151,28 @@ export function visibleTiles(
|
||||
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<SceneInfo, 'tile_size'>,
|
||||
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<SceneInfo, 'id' | 'art_version'>, x: number, y: number): string {
|
||||
return `/tiles/${scene.id}/v${scene.art_version}/${x}_${y}.png`
|
||||
@@ -224,7 +246,11 @@ export class ViewportModel {
|
||||
|
||||
setScene(scene: SceneInfo | null): void {
|
||||
if (scene?.id === this.#state.scene?.id) {
|
||||
if (scene && scene !== this.#state.scene) this.#state = { ...this.#state, scene }
|
||||
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)
|
||||
|
||||
Reference in New Issue
Block a user