import { MAP_LOOKS, mapTileDrawing, paintTile } from '~/diorama/mapTiles' /** Pixels per side of a village picture: twice the map's biggest field, so it stays crisp. */ const TILE_PX = 160 /** Image URLs by look id, filled in as the pictures are painted; kept for the whole session. */ const urls = shallowReactive>({}) let started = false // The first layout of every look first, so each kind shows its own picture soon; the // other layouts after, standing in with the first until they come. const ORDER = [...MAP_LOOKS.filter((l) => l.variant === 0), ...MAP_LOOKS.filter((l) => l.variant === 1)].map((l) => l.id) /** * The map's village pictures: each look painted once from its demo village's scene, in a * worker so the map's first paint never waits; without one, a look per idle moment. */ export function useMapTiles() { if (!started && import.meta.client) { started = true performance.mark('map-tiles:start') if (typeof Worker !== 'undefined' && typeof OffscreenCanvas !== 'undefined') inWorker() else onMainThread(ORDER) } return urls } function done(id: string, url: string) { urls[id] = url if (Object.keys(urls).length === ORDER.length) performance.mark('map-tiles:done') } function inWorker() { const worker = new Worker(new URL('../workers/mapTiles.worker.ts', import.meta.url), { type: 'module' }) worker.onmessage = (e: MessageEvent<{ id: string; blob: Blob }>) => { done(e.data.id, URL.createObjectURL(e.data.blob)) if (Object.keys(urls).length === ORDER.length) worker.terminate() } worker.onerror = () => { worker.terminate() onMainThread(ORDER.filter((id) => !urls[id])) } worker.postMessage({ ids: ORDER, size: TILE_PX }) } function onMainThread(ids: string[]) { const next = () => { const id = ids.shift() if (!id) return const canvas = document.createElement('canvas') canvas.width = TILE_PX canvas.height = TILE_PX paintTile(canvas.getContext('2d')!, mapTileDrawing(MAP_LOOKS.find((l) => l.id === id)!), TILE_PX) done(id, canvas.toDataURL('image/png')) later(next) } later(next) } const later = (fn: () => void) => (typeof requestIdleCallback === 'function' ? requestIdleCallback(fn, { timeout: 500 }) : setTimeout(fn, 16))