From 917344705ff90e071f29a6d52982f91a31bf4a8b Mon Sep 17 00:00:00 2001 From: "nori-sessions[bot]" <264258699+nori-sessions[bot]@users.noreply.github.com> Date: Thu, 5 Nov 2026 00:48:21 +0000 Subject: [PATCH] Stop the service worker re-flooding GitHub Pages on every reload The production worker precached all 24,918 files in public/, most of them per-sprite atlas packer inputs the game never requests, in one atomic cache.addAll. GitHub Pages answered the burst with 503s, one failure discarded the install, and every reload started the whole download again. Precache only the bundle, shell and the public files the game requests (sprite manifest, atlas pages, UI icons), download them a few at a time, stop at the first failure and resume a retried install from what the build's cache already holds. Co-authored-by: Nori --- docs/deploy/README.md | 4 ++ smoke/docs.md | 1 + smoke/returning-visitor.spec.ts | 112 ++++++++++++++++++++++++++++++++ src/pwa/docs.md | 18 +++-- src/pwa/service-worker.js | 40 +++++++++--- src/pwa/service-worker.test.ts | 96 ++++++++++++++++++++------- tools/art/README.md | 4 +- tools/pwa/precache-urls.test.ts | 53 +++++++++++++++ tools/pwa/precache-urls.ts | 36 ++++++++++ tools/sprites/docs.md | 2 +- vite.config.ts | 21 ++---- 11 files changed, 332 insertions(+), 55 deletions(-) create mode 100644 smoke/returning-visitor.spec.ts create mode 100644 tools/pwa/precache-urls.test.ts create mode 100644 tools/pwa/precache-urls.ts diff --git a/docs/deploy/README.md b/docs/deploy/README.md index b4b8468cd..380da43ee 100644 --- a/docs/deploy/README.md +++ b/docs/deploy/README.md @@ -14,4 +14,8 @@ The game is served at https://opencoaster.noriagentic.com/ over HTTPS. `public/C - Production builds use a relative Vite base (`./`) by default, so `dist/` works at the domain root and under a subpath such as `/opencoaster/`. Set `OC_BASE` (e.g. `OC_BASE=/opencoaster/ pnpm build`) to pin an absolute base instead. - `pnpm smoke:subpath` builds `dist/`, serves it under `/opencoaster/` with no cross-origin isolation headers (`tools/serve-subpath.mjs`), and runs the smoke suite against it. GitHub Pages sends no COOP/COEP headers, so this matches production. +## Service worker precache + +The production service worker precaches only what the game requests at runtime, a few files at a time, and resumes a failed install instead of restarting it ([src/pwa](../../src/pwa/docs.md)). `dist/` still contains the per-sprite atlas inputs copied from `public/sprites/`; precaching them all once caused GitHub Pages to answer with 503s and every reload to re-flood the site, so keep the precache list small. + Dev and preview builds keep the root base and the COOP/COEP headers the Vite dev server sends. diff --git a/smoke/docs.md b/smoke/docs.md index fb9706707..cd4ebb9a3 100644 --- a/smoke/docs.md +++ b/smoke/docs.md @@ -22,6 +22,7 @@ Path: @/smoke - The visual check captures the starter park before and after enabling gridlines. - [mobile-fps.spec.ts](mobile-fps.spec.ts) emulates a Pixel 8 (4× CPU throttle, device scale factor 2.6) with 2,000 and 5,000 guests and prints median FPS, p95 frame time and render scale. Budgets (55 and 30 FPS median) are soft: a miss adds a `soft-budget-miss` annotation and a warning, not a failure, because SwiftShader timing varies by host. - [no-4xx.spec.ts](no-4xx.spec.ts) loads the game, opens every toolbar window and fails on any 4xx network response; under `pnpm smoke:subpath` it runs against the production build served at `/opencoaster/`. +- [returning-visitor.spec.ts](returning-visitor.spec.ts) runs only under `pnpm smoke:subpath`. It seeds an earlier build's worker cache, an IndexedDB save, and settings, then checks the production worker installs without downloading the whole of `public/`, reloads stay controlled and fetch nothing but the navigation, the old cache is removed, and the save still appears under Load game ([src/pwa](../src/pwa/docs.md)). - Playwright screenshots are stored in `.local/playwright-results/` (dev) and `.local/playwright-results-subpath/` (subpath). - Specs navigate with `page.goto('./')` so the same spec runs at the origin root and under the subpath. diff --git a/smoke/returning-visitor.spec.ts b/smoke/returning-visitor.spec.ts new file mode 100644 index 000000000..d9257a899 --- /dev/null +++ b/smoke/returning-visitor.spec.ts @@ -0,0 +1,112 @@ +import { expect, test } from '@playwright/test'; + +const SAVE = { id: 'returning-park', name: 'Returning park', bytes: [7, 1, 2, 3] }; + +// The production worker installs once, then repeat visits load from it. The dev server's worker +// only precaches the shell, so this runs against the production build (pnpm smoke:subpath). +test('a returning visitor reloads from the installed worker and keeps their saved parks', async ({ + page, + context, + baseURL, +}) => { + test.skip(new URL(baseURL ?? '/').pathname === '/', 'production build only'); + test.setTimeout(90_000); + const base = new URL(baseURL ?? '/'); + + // A visitor from an earlier build: a saved park, settings and that build's worker cache. + await page.goto(base.origin); + await page.evaluate( + async ({ save, scope }) => { + localStorage.setItem('opencoaster.settings.v1', '{"returning":true}'); + const old = await caches.open('opencoaster-static-old'); + await old.put(new URL(scope, location.href).href, new Response('old shell')); + await new Promise((resolve, reject) => { + const open = indexedDB.open('opencoaster-saves', 1); + open.onupgradeneeded = () => open.result.createObjectStore('slots', { keyPath: 'id' }); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const tx = open.result.transaction('slots', 'readwrite'); + tx.objectStore('slots').put({ + id: save.id, + name: save.name, + savedAt: Date.now(), + scenarioId: 'sandbox', + tick: 0, + cash: 0, + loan: 0, + bytes: new Uint8Array(save.bytes), + }); + tx.oncomplete = () => resolve(); + tx.onerror = () => reject(tx.error); + }; + }); + }, + { save: SAVE, scope: base.pathname }, + ); + + const workerDownloads: string[] = []; + const pageNetworkLoads: string[] = []; + const failures: string[] = []; + context.on('request', (request) => { + if (request.serviceWorker()) workerDownloads.push(request.url()); + }); + context.on('response', (response) => { + if (response.status() >= 400) failures.push(`${response.status()} ${response.url()}`); + const request = response.request(); + if ( + !request.serviceWorker() && + request.resourceType() !== 'document' && + !response.fromServiceWorker() + ) + pageNetworkLoads.push(response.url()); + }); + + await page.goto(base.href); + await expect + .poll(() => page.evaluate(() => Boolean(navigator.serviceWorker.controller)), { + timeout: 60_000, + }) + .toBe(true); + // The precache holds the bundle, shell, atlas and icons, not the per-sprite packer inputs. + expect(workerDownloads).toContain(`${base.href}sprites/manifest.json`); + expect(workerDownloads.length).toBeLessThan(1000); + + await page.waitForLoadState('networkidle'); + for (let reload = 0; reload < 3; reload++) { + workerDownloads.length = 0; + pageNetworkLoads.length = 0; + await page.reload(); + await expect(page.getByRole('button', { name: 'Load game' })).toBeVisible(); + await page.waitForLoadState('networkidle'); + expect(await page.evaluate(() => Boolean(navigator.serviceWorker.controller))).toBe(true); + expect(workerDownloads.filter((url) => url !== base.href)).toEqual([]); + expect(pageNetworkLoads.filter((url) => !url.endsWith('/service-worker.js'))).toEqual([]); + } + + const storage = await page.evaluate(async (id) => { + const save = await new Promise<{ name: string; bytes: Uint8Array } | undefined>( + (resolve, reject) => { + const open = indexedDB.open('opencoaster-saves'); + open.onerror = () => reject(open.error); + open.onsuccess = () => { + const get = open.result.transaction('slots').objectStore('slots').get(id); + get.onerror = () => reject(get.error); + get.onsuccess = () => resolve(get.result as { name: string; bytes: Uint8Array }); + }; + }, + ); + return { + save: save && { name: save.name, bytes: [...save.bytes] }, + settings: localStorage.getItem('opencoaster.settings.v1'), + caches: (await caches.keys()).filter((key) => key.startsWith('opencoaster-static-')).length, + }; + }, SAVE.id); + expect(storage).toEqual({ + save: { name: SAVE.name, bytes: SAVE.bytes }, + settings: '{"returning":true}', + caches: 1, + }); + await page.getByRole('button', { name: 'Load game' }).click(); + await expect(page.getByText(SAVE.name)).toBeVisible(); + expect(failures.filter((failure) => !failure.endsWith(`${base.origin}/`))).toEqual([]); +}); diff --git a/src/pwa/docs.md b/src/pwa/docs.md index 6d1692c18..e228789a2 100644 --- a/src/pwa/docs.md +++ b/src/pwa/docs.md @@ -5,29 +5,33 @@ Path: @/src/pwa ### Overview - Registers the browser service worker that supplies the offline app shell. -- The worker precaches the app shell and built assets, then caches same-origin GET responses as they are used. +- In production the worker precaches the built bundle, the page shell, and the public files the game requests at runtime, then caches other same-origin GET responses as they are used. - PWA metadata and icons live in the public web root and are linked from [index.html](../../index.html). - Every URL is relative to the deploy base, so the app works at the origin root (dev) and under a subpath such as GitHub Pages' `/opencoaster/`. ### How it fits into the larger codebase -- [src/main.ts](../main.ts) registers the worker during app startup; browser support or registration failure does not prevent the game from starting. -- [vite.config.ts](../../vite.config.ts) serves a development worker and emits a production worker. Production builds default to a relative base (`./`, overridable with `OC_BASE`), and the worker's precache list is relative to the worker script, so the worker's scope is the deploy base. -- [register.ts](register.ts) and the sprite fetches in [webgl2-renderer.ts](../render/webgl2-renderer.ts) prefix `import.meta.env.BASE_URL`; the deploy workflow is described in [docs/deploy](../../docs/deploy/README.md). +- [src/app/bootstrap/index.ts](../app/bootstrap/index.ts) calls `registerPwa` during app startup; browser support or registration failure does not prevent the game from starting. +- [vite.config.ts](../../vite.config.ts) serves a development worker (precaching only `/`) and emits a production worker. Production builds default to a relative base (`./`, overridable with `OC_BASE`), and the worker's precache list is relative to the worker script, so the worker's scope is the deploy base. +- The production precache list comes from [tools/pwa/precache-urls.ts](../../tools/pwa/precache-urls.ts): bundle files, `index.html`, `./`, and the files under `public/`, except `CNAME` and any `sprites/` file other than the sprite manifest, atlas pages, and UI icons. The rest of `public/sprites/` is per-sprite packer input from [tools/art](../../tools/art/README.md) that the game never requests. +- [register.ts](register.ts), the atlas loader in [sprite-pages.ts](../render/sprite-pages.ts), and the UI icon URLs in [icons.ts](../ui/icons.ts) prefix `import.meta.env.BASE_URL`; the deploy workflow is described in [docs/deploy](../../docs/deploy/README.md). - The worker caches JavaScript modules, worker chunks, and other same-origin requests used by the client. This allows the simulation worker to start when the app is reopened offline after its assets have been cached. -- The web app remains responsible for simulation state and save persistence; service-worker caches hold application resources rather than park saves. +- The web app remains responsible for simulation state and save persistence; the worker never touches IndexedDB or `localStorage`, so park saves and settings survive worker updates. ### Core Implementation - [register.ts](register.ts) calls `navigator.serviceWorker.register` when the API exists and reports registration errors through the browser console. -- [service-worker.js](service-worker.js) installs a cache named for the build (`opencoaster-static-`, filled in by [vite.config.ts](../../vite.config.ts)) from the build-generated URL list, removes older OpenCoaster static caches on activation, and claims controlled clients. -- Page navigations go to the network first (`cache: 'no-cache'`, so the browser HTTP cache cannot supply an old shell naming old assets) and update the cache; offline they fall back to the cached page or the shell at the worker's scope. Every other same-origin GET is served from the cache first, otherwise fetched and stored. Install precaches with `cache: 'reload'` for the same reason. +- [service-worker.js](service-worker.js) installs into a cache named for the build (`opencoaster-static-`, filled in by [vite.config.ts](../../vite.config.ts)), removes older OpenCoaster static caches on activation, and claims controlled clients. +- Install downloads the precache list with a small fixed number of downloads in flight, storing each response with `cache.put`. URLs already present in this build's cache are skipped, so an install retried after a failure only downloads what is missing. The first failed or non-OK download empties the queue so no new downloads start, and install rejects once in-flight downloads settle; the worker activates only once the whole list is cached. +- Page navigations go to the network first (`cache: 'no-cache'`, so the browser HTTP cache cannot supply an old shell naming old assets) and update the cache; offline they fall back to the cached page or the shell at the worker's scope. Every other same-origin GET is served from the cache first, otherwise fetched and stored. Install downloads use `cache: 'reload'` for the same reason. - [manifest.webmanifest](../../public/manifest.webmanifest) describes standalone launch, orientation, theme colors, and scalable/raster app icons. ### Things to Know - Offline startup requires one successful online load so the worker can install and cache the shell and requested assets. +- The precache list must stay small. Precaching all of `public/` (tens of thousands of per-sprite packer files) in one atomic `cache.addAll` made GitHub Pages answer with 503s; one failed response discarded the whole install, so the page was never controlled and every reload restarted the full download, re-flooding the origin. The filtered list, bounded concurrency, stop-on-first-failure, and resumable install exist to prevent that loop. A new runtime-requested file outside the allowed `sprites/` paths must be added to [precache-urls.ts](../../tools/pwa/precache-urls.ts), or it is only cached on first use. - Each build has its own cache, and activation removes the caches of earlier builds. A page that is already open keeps running the build it loaded until it is reloaded; the next navigation gets the new build. A browser still running the previous cache-first worker serves its old shell once more before the new worker takes over. +- [returning-visitor.spec.ts](../../smoke/returning-visitor.spec.ts) covers install and repeat visits against the production build (`pnpm smoke:subpath` only): an earlier build's cache is removed, reloads stay controlled, and seeded saves and settings remain intact. - The PWA layer does not cache or migrate game saves; save slots remain in the save subsystem's IndexedDB or its in-memory fallback. Created and maintained by Nori. diff --git a/src/pwa/service-worker.js b/src/pwa/service-worker.js index c565365ba..0be7d1692 100644 --- a/src/pwa/service-worker.js +++ b/src/pwa/service-worker.js @@ -1,15 +1,39 @@ const CACHE_NAME = 'opencoaster-static-' + self.__CACHE_VERSION__; const PRECACHE_URLS = self.__PRECACHE_URLS__; +const PRECACHE_CONCURRENCY = 6; + +/** + * Downloads the precache list a few files at a time into this build's cache, skipping files a + * failed earlier attempt already stored, so a retried install fetches only what is missing. + * The first failed download stops the queue, so a throttled server is not sent the rest. + */ +async function precache() { + const cache = await caches.open(CACHE_NAME); + const pending = []; + for (const url of PRECACHE_URLS) { + const request = new Request(url, { cache: 'reload' }); + if (!(await cache.match(request))) pending.push(request); + } + const store = async (request) => { + const response = await fetch(request); + if (!response.ok) throw new Error(`Precache of ${request.url} failed: ${response.status}`); + await cache.put(request, response); + }; + const download = async () => { + for (let request = pending.shift(); request; request = pending.shift()) { + await store(request).catch((error) => { + pending.length = 0; + throw error; + }); + } + }; + const results = await Promise.allSettled(Array.from({ length: PRECACHE_CONCURRENCY }, download)); + const failure = results.find((result) => result.status === 'rejected'); + if (failure) throw failure.reason; +} self.addEventListener('install', (event) => { - event.waitUntil( - caches - .open(CACHE_NAME) - .then((cache) => - cache.addAll(PRECACHE_URLS.map((url) => new Request(url, { cache: 'reload' }))), - ) - .then(() => self.skipWaiting()), - ); + event.waitUntil(precache().then(() => self.skipWaiting())); }); self.addEventListener('activate', (event) => { diff --git a/src/pwa/service-worker.test.ts b/src/pwa/service-worker.test.ts index 5418f7415..4ac18251d 100644 --- a/src/pwa/service-worker.test.ts +++ b/src/pwa/service-worker.test.ts @@ -7,8 +7,18 @@ const SCOPE = `${ORIGIN}/opencoaster/`; type Listener = (event: Record) => void; +class FakeRequest { + method = 'GET'; + mode = 'cors'; + constructor( + public url: string, + public init: { cache?: string } = {}, + ) {} +} + interface FakeResponse { ok: boolean; + status?: number; type: string; body: string; clone(): FakeResponse; @@ -23,25 +33,24 @@ function startWorker(options: { version: string; network: Map; stores?: Map>; + precache?: string[]; + latencyMs?: number; }) { const listeners = new Map(); const stores = options.stores ?? new Map>(); const fetched: Array<{ url: string; cache?: string }> = []; let online = true; + let inFlight = 0; + let peakInFlight = 0; const caches = { open: async (name: string) => { if (!stores.has(name)) stores.set(name, new Map()); const store = stores.get(name)!; return { - addAll: async (requests: Array<{ url: string }>) => { - for (const request of requests) { - const body = options.network.get(request.url); - if (body === undefined) throw new Error(`no network for ${request.url}`); - store.set(request.url, response(body)); - } - }, - put: async (request: { url: string }, value: FakeResponse) => - void store.set(request.url, value), + put: async (request: { url: string } | string, value: FakeResponse) => + void store.set(typeof request === 'string' ? request : request.url, value), + match: async (request: { url: string } | string) => + store.get(typeof request === 'string' ? request : request.url), }; }, keys: async () => [...stores.keys()], @@ -59,21 +68,26 @@ function startWorker(options: { skipWaiting: async () => undefined, clients: { claim: async () => undefined }, __CACHE_VERSION__: options.version, - __PRECACHE_URLS__: [`${SCOPE}index.html`, `${SCOPE}assets/index-aaa.js`], + __PRECACHE_URLS__: options.precache ?? [`${SCOPE}index.html`, `${SCOPE}assets/index-aaa.js`], }; - class FakeRequest { - constructor( - public url: string, - public init: { cache?: string } = {}, - ) {} - } - const fetchImpl = async (target: string | { url: string }, init?: { cache?: string }) => { + const fetchImpl = async ( + target: string | FakeRequest, + init?: { cache?: string }, + ): Promise => { const input = typeof target === 'string' ? target : target.url; - fetched.push({ url: input, cache: init?.cache }); - if (!online) throw new Error('offline'); - const body = options.network.get(input); - if (body === undefined) throw new Error(`no network for ${input}`); - return response(body); + const cacheMode = init?.cache ?? (typeof target === 'string' ? undefined : target.init.cache); + fetched.push({ url: input, cache: cacheMode }); + inFlight++; + peakInFlight = Math.max(peakInFlight, inFlight); + try { + await new Promise((resolve) => setTimeout(resolve, options.latencyMs ?? 0)); + if (!online) throw new Error('offline'); + const body = options.network.get(input); + if (body === undefined) return { ...response('Too Many Requests'), ok: false, status: 503 }; + return response(body); + } finally { + inFlight--; + } }; new Function('self', 'caches', 'fetch', 'Request', SOURCE)(self, caches, fetchImpl, FakeRequest); @@ -89,6 +103,7 @@ function startWorker(options: { return { stores, fetched, + peakInFlight: () => peakInFlight, setOnline: (value: boolean) => (online = value), install: () => dispatch('install'), activate: () => dispatch('activate'), @@ -97,7 +112,7 @@ function startWorker(options: { request: { url, method: 'GET', mode: 'navigate' }, }) as Promise, load: (url: string) => - dispatch('fetch', { request: { url, method: 'GET', mode: 'cors' } }) as Promise, + dispatch('fetch', { request: new FakeRequest(url) }) as Promise, }; } @@ -168,4 +183,39 @@ describe('service worker', () => { expect([...worker.stores.keys()].sort()).toEqual(['opencoaster-static-current', 'unrelated']); }); + + it('resumes a failed precache without downloading what it already stored', async () => { + const precache = Array.from({ length: 20 }, (_, i) => `${SCOPE}sprites/atlas/page-${i}.png`); + const network = new Map(precache.map((url) => [url, 'png'])); + network.delete(precache[2]!); + const first = startWorker({ version: 'v', network, precache }); + + await expect(first.install()).rejects.toThrow(); + expect(first.fetched.length).toBeLessThan(precache.length); + const stored = new Set([...first.stores.values()].flatMap((store) => [...store.keys()])); + network.set(precache[2]!, 'png'); + const retry = startWorker({ version: 'v', network, precache, stores: first.stores }); + await retry.install(); + + const refetched = retry.fetched.map((entry) => entry.url); + expect(stored.size).toBeGreaterThan(0); + expect(refetched).toContain(precache[2]); + expect(refetched.filter((url) => stored.has(url))).toEqual([]); + expect(refetched.length + stored.size).toBe(precache.length); + retry.setOnline(false); + for (const url of precache) expect((await retry.load(url)).body).toBe('png'); + }); + + it('downloads each precache file once past the HTTP cache, a few at a time', async () => { + const precache = Array.from({ length: 200 }, (_, i) => `${SCOPE}sprites/atlas/page-${i}.png`); + const network = new Map(precache.map((url) => [url, 'png'])); + const worker = startWorker({ version: 'v', network, precache, latencyMs: 1 }); + + await worker.install(); + + expect(worker.fetched.map((entry) => entry.url).sort()).toEqual([...precache].sort()); + expect(worker.fetched.every((entry) => entry.cache === 'reload')).toBe(true); + expect(worker.peakInFlight()).toBeGreaterThan(1); + expect(worker.peakInFlight()).toBeLessThanOrEqual(8); + }); }); diff --git a/tools/art/README.md b/tools/art/README.md index 418127b83..8b4a58b4d 100644 --- a/tools/art/README.md +++ b/tools/art/README.md @@ -4,9 +4,9 @@ The art pipeline keeps OpenCoaster independent of original game files and copied ## Preparation -[prepare.ts](prepare.ts) clears and recreates `public/sprites/`, then crops, trims transparent padding, defringes transparent-edge RGB, resizes with nearest-neighbour sampling, and quantizes images to a deterministic 64-colour palette. Per-sprite JSON records frame rectangles, bottom-centre anchors, and tile footprints. [pack.ts](pack.ts) validates that metadata, trims the transparent borders of `native` sprites, assigns every sprite to a category from its key prefix ([categories.ts](categories.ts)), and packs each category's frames with MaxRects ([maxrects.ts](maxrects.ts)) into transparent PNG pages of at most 2048x2048 pixels under `public/sprites/atlas/-.png`. Every frame reserves a two-pixel transparent gutter, and the manifest frame coordinates point to the sprite content inside that gutter. Beside each colour page it writes a height page (`-.depth.png`) with the identical layout: a frame's baked height map from [tools/sprites](../sprites/docs.md) when its source has a `.depth.png`, otherwise an upright card through the frame's trimmed anchor (each opaque row stands `(anchor row - row) / 16` levels high). Heights use the encoding in [src/render/height-encoding.ts](../../src/render/height-encoding.ts) and drive per-pixel occlusion in both renderers ([src/render/docs.md](../../src/render/docs.md), "Occlusion model"); source `.depth.png` files are never packed as sprites themselves. `manifest.json` lists the pages (`file`, `depthFile`, size, category), the categories (`lazy` flag and page indices) and, for each sprite, its category and its frames as `{ page, x, y, width, height }`. Packing is deterministic and fails when a sprite plus its gutter exceeds the page size. The standalone 16px and 24px UI icon PNGs are generated under `public/sprites/ui-icons/` and excluded from the atlas; the DOM loads each native-size image directly. +[prepare.ts](prepare.ts) clears and recreates `public/sprites/`, then crops, trims transparent padding, defringes transparent-edge RGB, resizes with nearest-neighbour sampling, and quantizes images to a deterministic 64-colour palette. Per-sprite JSON records frame rectangles, bottom-centre anchors, and tile footprints. [pack.ts](pack.ts) validates that metadata, trims the transparent borders of `native` sprites, assigns every sprite to a category from its key prefix ([categories.ts](categories.ts)), and packs each category's frames with MaxRects ([maxrects.ts](maxrects.ts)) into transparent PNG pages of at most 2048x2048 pixels under `public/sprites/atlas/-.png`. Every frame reserves a two-pixel transparent gutter, and the manifest frame coordinates point to the sprite content inside that gutter. Beside each colour page it writes a height page (`-.depth.png`) with the identical layout: a frame's baked height map from [tools/sprites](../sprites/docs.md) when its source has a `.depth.png`, otherwise an upright card through the frame's trimmed anchor (each opaque row stands `(anchor row - row) / 16` levels high). Heights use the encoding in [src/render/height-encoding.ts](../../src/render/height-encoding.ts) and drive per-pixel occlusion in both renderers ([src/render/docs.md](../../src/render/docs.md), "Occlusion model"); source `.depth.png` files are never packed as sprites themselves. `manifest.json` lists the pages (`file`, `depthFile`, size, category), the categories (`lazy` flag and page indices) and, for each sprite, its category and its frames as `{ page, x, y, width, height }`. Packing is deterministic and fails when a sprite plus its gutter exceeds the page size. The standalone 16px and 24px UI icon PNGs are generated under `public/sprites/ui-icons/`; the DOM loads each native-size image directly. The packer only skips the `ui/` and `atlas/` directories, so the icons are also packed (as `ui-icons/...` keys) into the eager `world` atlas pages. -Categories group pages that load together: eager ones (`world`, `people`) load at start, lazy ones (flat rides, stalls, each coaster family, vehicles) load when first needed. To add a category, append a rule to `ATLAS_CATEGORIES` in [categories.ts](categories.ts); no packer or renderer change is needed. The service worker precaches everything in `public/`, so every page is available offline. +Categories group pages that load together: eager ones (`world`, `people`) load at start, lazy ones (flat rides, stalls, each coaster family, vehicles) load when first needed. To add a category, append a rule to `ATLAS_CATEGORIES` in [categories.ts](categories.ts); no packer or renderer change is needed. The production service worker precaches the manifest, every atlas page, and the UI icons, so every page is available offline; the per-sprite PNG/JSON inputs that remain in `public/sprites/` are not precached ([src/pwa](../../src/pwa/docs.md)). The terrain sheet supplies distinct source cells for the 16 combinations of the map's 4-bit corner slope mask, plus directional cliff faces, for grass, sand, dirt, and rock. Preparation crops and cleans each authored cell; it does not rotate or reflection-cycle a smaller set of slope drawings. After preparation, [tools/sprites](../sprites/docs.md) overwrites the rock surface key with a generated textured tile and adds four generated directional rock cliff-face keys. The renderer projects tile corners for continuous terrain tops, draws directional cliff faces at map boundaries, and draws exposed interior faces on rock tiles. The map encodes one-level corner differences and has no separate steep-slope encoding. diff --git a/tools/pwa/precache-urls.test.ts b/tools/pwa/precache-urls.test.ts new file mode 100644 index 000000000..477a675bf --- /dev/null +++ b/tools/pwa/precache-urls.test.ts @@ -0,0 +1,53 @@ +import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { dirname, join } from 'node:path'; +import { afterEach, describe, expect, it } from 'vitest'; +import { precacheUrls } from './precache-urls'; + +let root = ''; + +function publicDir(files: string[]): string { + root = mkdtempSync(join(tmpdir(), 'oc-public-')); + for (const file of files) { + mkdirSync(dirname(join(root, file)), { recursive: true }); + writeFileSync(join(root, file), ''); + } + return root; +} + +afterEach(() => rmSync(root, { recursive: true, force: true })); + +describe('service worker precache list', () => { + it('holds the built bundle, the shell and the public files the game requests', () => { + const dir = publicDir([ + 'CNAME', + 'manifest.webmanifest', + 'icons/icon.svg', + 'scenario-previews/forest.png', + 'sprites/manifest.json', + 'sprites/atlas/world-0.png', + 'sprites/atlas/world-0.depth.png', + 'sprites/ui-icons/16/pause.png', + 'sprites/rides/coaster/steel/track/flat/view-0/cell-0.png', + 'sprites/rides/coaster/steel/track/flat/view-0/cell-0.json', + 'sprites/scenery/bench/view-0.depth.png', + 'sprites/people/staff-costumes.png', + ]); + + expect(precacheUrls(['assets/index-abc.js', 'assets/index-abc.css'], dir).sort()).toEqual( + [ + './', + 'assets/index-abc.css', + 'assets/index-abc.js', + 'icons/icon.svg', + 'index.html', + 'manifest.webmanifest', + 'scenario-previews/forest.png', + 'sprites/atlas/world-0.depth.png', + 'sprites/atlas/world-0.png', + 'sprites/manifest.json', + 'sprites/ui-icons/16/pause.png', + ].sort(), + ); + }); +}); diff --git a/tools/pwa/precache-urls.ts b/tools/pwa/precache-urls.ts new file mode 100644 index 000000000..72c04511c --- /dev/null +++ b/tools/pwa/precache-urls.ts @@ -0,0 +1,36 @@ +import { readdirSync, statSync } from 'node:fs'; +import { resolve } from 'node:path'; + +function publicFiles(directory: string, prefix = ''): string[] { + return readdirSync(directory).flatMap((name) => { + const absolutePath = resolve(directory, name); + const relativePath = `${prefix}${name}`; + return statSync(absolutePath).isDirectory() + ? publicFiles(absolutePath, `${relativePath}/`) + : [relativePath]; + }); +} + +/** + * Public files the game requests at runtime. Everything else under `sprites/` is atlas packer + * input that only `public/` holds (see tools/art/README.md); `CNAME` is for GitHub Pages. + */ +function requestedAtRuntime(file: string): boolean { + if (file === 'CNAME') return false; + if (!file.startsWith('sprites/')) return true; + return ( + file === 'sprites/manifest.json' || + file.startsWith('sprites/atlas/') || + file.startsWith('sprites/ui-icons/') + ); +} + +/** The service worker's precache list, relative to the worker script so it works at any base. */ +export function precacheUrls(bundleFiles: string[], publicDirectory: string): string[] { + return [ + ...bundleFiles, + 'index.html', + './', + ...publicFiles(publicDirectory).filter(requestedAtRuntime), + ]; +} diff --git a/tools/sprites/docs.md b/tools/sprites/docs.md index 482e11869..df1db18be 100644 --- a/tools/sprites/docs.md +++ b/tools/sprites/docs.md @@ -8,7 +8,7 @@ Path: @/tools/sprites - Produces PNG and JSON sprite definitions, plus a `.depth.png` height map for every mesh-rendered sprite, for [tools/art](../art/README.md), which prepares and packs them into the runtime atlas and manifest. Generated rock keys replace the prepared rock surface and add directional cliff faces. - `pnpm art:prepare` calls `renderSprites`, which writes every sprite from `buildSprites()` into `public/sprites/`. `pnpm sprites:render` only writes contact sheets under `docs/art/` for visual review. - [ui-icon-art.ts](ui-icon-art.ts) holds the whole-pixel drawings (outline plus ramp shades on a 24×24 grid, recentred) for the toolbar and tab icons that must read at a glance, such as land, water, clear scenery, footpaths, rides, coasters and the rotate arrows. `renderUiIconSprite` consults it before the other two paths; 16px versions are nearest-neighbour reductions. -- `renderUiIcons` in [ui-icons.ts](ui-icons.ts) writes registered UI icons at native 16px and 24px sizes under `public/sprites/ui-icons/`. Most ride and object icons use the deterministic `renderMesh` rasterizer; the hand-authored icon set uses pixel shapes directly so its silhouette and shading remain legible at the UI's native size. Both paths share the icon registry and generated asset locations. UI icons are generated after world sprites during `art:prepare` and are intentionally excluded from the world atlas. +- `renderUiIcons` in [ui-icons.ts](ui-icons.ts) writes registered UI icons at native 16px and 24px sizes under `public/sprites/ui-icons/`. Most ride and object icons use the deterministic `renderMesh` rasterizer; the hand-authored icon set uses pixel shapes directly so its silhouette and shading remain legible at the UI's native size. Both paths share the icon registry and generated asset locations. UI icons are generated after world sprites during `art:prepare`; the DOM loads them directly, and the packer also packs them into the eager `world` atlas because it only skips the `ui/` and `atlas/` directories ([tools/art](../art/README.md)). ### How it fits into the larger codebase diff --git a/vite.config.ts b/vite.config.ts index 4031614d1..14e38ea73 100644 --- a/vite.config.ts +++ b/vite.config.ts @@ -1,6 +1,7 @@ -import { readdirSync, readFileSync, statSync } from 'node:fs'; +import { readFileSync } from 'node:fs'; import { resolve } from 'node:path'; import { defineConfig, type Plugin } from 'vitest/config'; +import { precacheUrls } from './tools/pwa/precache-urls'; // COOP/COEP make the page cross-origin isolated, which unlocks SharedArrayBuffer and // high-resolution timers. The current transport (transferable snapshots) does not require @@ -13,16 +14,6 @@ const isolationHeaders = { const workerSource = readFileSync(resolve('src/pwa/service-worker.js'), 'utf8'); -function publicFiles(directory: string, prefix = ''): string[] { - return readdirSync(directory).flatMap((name) => { - const absolutePath = resolve(directory, name); - const relativePath = `${prefix}${name}`; - return statSync(absolutePath).isDirectory() - ? publicFiles(absolutePath, `${relativePath}/`) - : [relativePath]; - }); -} - /** Fills in the worker's precache list and the cache name that ties its caches to one build. */ function buildWorker(urls: string[], version: string): string { return workerSource @@ -41,9 +32,10 @@ function pwaPlugin(): Plugin { }); }, generateBundle(_options, bundle) { - // Relative to the worker script, so the precache works at any deploy base (e.g. /opencoaster/). - const urls = Object.keys(bundle).filter((fileName) => fileName !== 'service-worker.js'); - urls.push('index.html', './', ...publicFiles(resolve('public'))); + const urls = precacheUrls( + Object.keys(bundle).filter((fileName) => fileName !== 'service-worker.js'), + resolve('public'), + ); this.emitFile({ type: 'asset', fileName: 'service-worker.js', @@ -95,6 +87,7 @@ export default defineConfig(({ command }) => ({ 'bench/**/*.test.ts', 'tools/art/**/*.test.ts', 'tools/sprites/**/*.test.ts', + 'tools/pwa/**/*.test.ts', ], }, }));