diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index 5413bc27..1c6c5ad6 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -1,14 +1,14 @@ # Background scene -**Default: the ridge scene** (`ridge/`), no WebGL. `startBackgroundScene` runs it unless the client +**Default: the ridge scene** (`ridge/`): no per-frame WebGL (the baked cards are lit once per scene build, in a WebGL2 context that is released after). `startBackgroundScene` runs it unless the client config says `backgroundScene.style: 'raymarch'`; the tier flag still defaults to `off`, and null still means "keep the CSS ground". Everything below this section describes the opt-in ray-march scene. -- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky? })` returns `{ login, dispose }` or +- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky?, backdrop? })` returns `{ login, dispose }` or null (tier `off`, no 2D context). It paints the sky (`ridge/physicalSky.ts`, from the `SkyColours` the host passes) on the host canvas at the viewport's size in canvas pixels, then the stars baked into it, a twinkle overlay canvas for the swinging ones - (`ridge/stars.ts`), the baked ridge planes (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). - With no planes (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms. + (`ridge/stars.ts`), the lit ridge cards (below) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). + With no cards (the load failed) the scene shows sky, stars and weather only. No script runs per frame except the twinkle, at most every 50 ms. The host canvas and its parent must be positioned and the canvas should fill the parent. A resize rebuilds it; so does a sky change (`index.ts`). - Paused when the tab is hidden; under `prefers-reduced-motion` the rain is paused and the stars stay at base brightness. @@ -18,17 +18,23 @@ means "keep the CSS ground". Everything below this section describes the opt-in and shows `n / median / p95` in a corner readout. - `ridge/skyColour.ts` `skyColours()` is the fallback three-stop palette (top, mid, horizon) a scene gets with no `sky` option; the host passes `ridgeSkyFor` (skyForState.ts) instead. -- Ridge planes: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry, - unknown or absent: the index default), then the place's `manifest.json` (v1, written by `scripts/ridge-bake/export.py`; it is the one JSON - the backdrop reads). `ridge/frameChoice.ts` picks the two baked frames the sky's sun lies between and a blend weight; `ridge/Backdrop.ts` - decodes only those. `index.ts` `prepare()` loads manifest and planes with the scene chunk, so `createRidgeScene({ backdrop })` stays - synchronous, and a rebuild keeps the old scene up until the new one's planes have loaded, then swaps. The rig is one div of three plane groups (far, mid, near; DOM order is paint order; no z-index, no fixed position, nothing - outside the scene's parent), each drifting on `Element.animate` (transform only, 150 s loop, paused when the tab is hidden, motion is - reduced or the scene is still); a still draws the planes into the host canvas. Two frames are a true crossfade (`frameChoice.ts` - `crossfade`: a at 1 - w plus b at w, summed in an isolated group, `plus-lighter` in the rig and `lighter` in an offscreen for the still), because - the planes are haze as alpha and b laid over a would double the haze. A failure anywhere (404, bad manifest, an image that - will not decode) is the sky-only scene on `FALLBACK_VIEW`, told to the host by the live scene alone, through `onPlanesFail` when the live scene has no planes and `onPlanesOk` when a later one has them (never from a stale or disposed build); it is never `onCompileFail`. - `vite.config.js` copies `public/ridge` into `dist/public/`. +- Ridge cards: `ridge/manifest.ts` `loadManifest` reads `${BASE_URL}public/ridge/index.json` (config `backgroundScene.place` picks the entry, + unknown or absent: the index default), then the place's `manifest.json` (schema 2, written by `scripts/ridge-bake/export.py`; it is the one JSON + the backdrop reads): K G-buffer cards, nearest first, each a colour WebP (albedo, straight alpha) and a geometry WebP (the normal as 'rt8', the + log-distance, and the wall code R = G = 255 for the extruded face under a ridge). `index.ts` `prepare()` loads the manifest and, with the scene chunk, + `ridge/Backdrop.ts` `loadBackdrop`: every card's two files fetched and decoded straight (no premultiply, no colour management), then + `ridge/lightCards.ts` lights each card once in WebGL2 for the sky of this build (sun and ambient from the atmosphere, aerial perspective from the + geometry's distance, ink on occluding edges and creases, the sky's own display so terrain and sky share an exposure) into a 2D canvas, and releases + the context. A sky change is a rebuild, so it lights again; nothing is lit per frame, and the host canvas is only ever asked for 2d. + `createRidgeScene({ backdrop })` stays synchronous, and a rebuild keeps the old scene up until the new one's cards are lit, then swaps. The rig + is one div of K card elements (farthest first; DOM order is paint order; no z-index, no fixed position, nothing outside the scene's parent), + each placed at its rows of the plane and moved by `view.ts` `cardMotion`: the camera turns through the baker's heading range (capped so every card still covers + the viewport) and card i pans `scale_i` x heading and is drawn `scale_i` times its bake, about the horizon centre, as a camera pushed forward on a circle + round the bake centre sees it (ruling ridge-camera-on-circle); the scales come from the manifest. It drifts on `Element.animate` (transform only, 150 s loop, + paused when the tab is hidden, motion is reduced or the scene is still); a still draws the same cards at heading 0 into the host canvas. A failure + anywhere (404, a manifest that is not schema 2, a card that will not decode, no WebGL2, a lighting pass that throws) is the sky-only scene on `FALLBACK_VIEW`, + told to the host by the live scene alone, through `onPlanesFail` when the live scene has no cards and `onPlanesOk` when a later one has them (never from a stale + or disposed build); it is never `onCompileFail`. `vite.config.js` copies `public/ridge` into `dist/public/`. - `harness/scene/bundle.cjs ridge` builds a standalone page (`?tier=`, `?probe=1`). - Not yet measured on a phone: see the PR description. diff --git a/src/app/features/scene/index.test.ts b/src/app/features/scene/index.test.ts index 9584bee9..d9557e24 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -11,11 +11,14 @@ import { sunAt } from './ridge/sunAt'; import { ridgeWeather } from './ridge/weather'; import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed'; -const { createRidgeScene, createScene } = vi.hoisted(() => ({ +const { createRidgeScene, createScene, loadBackdrop } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), createScene: vi.fn(), + loadBackdrop: vi.fn(), })); vi.mock('./ridge/Ridge', () => ({ createRidgeScene })); +// Decoding and lighting are the cards' own tests' (Backdrop.test.ts, lightCards.test.ts); here the door sees a loader it can hold, fail and count. +vi.mock('./ridge/Backdrop', () => ({ loadBackdrop })); vi.mock('./Scene', () => ({ createScene })); // The physical sky is baked per call (tens of ms: atmosphere LUTs) and the clock here is fixed, so a state always // draws the same sky. Baking once per state keeps the 21-offset sweep under the default timeout when the machine is @@ -48,6 +51,35 @@ const microtasks = (n: number) => (p) => p.then(() => undefined), Promise.resolve() ); +/** A loader for `loadBackdrop` that waits on `ctl.hold` (queueing its settle in `ctl.pending`), then resolves a backdrop or, with `ctl.fail` as it stood when asked, null. `ctl.calls` is the sky each call was lit for. */ +const loader = () => { + const ctl = { + pending: [] as Array<() => void>, + hold: false, + fail: false, + calls: [] as any[], + }; + loadBackdrop.mockImplementation( + (manifest: unknown, physical: unknown) => + new Promise((resolve) => { + const fails = ctl.fail; // the outcome belongs to the request, whenever it settles + const settle = () => { + ctl.calls.push(physical); + resolve(fails ? null : { manifest, cards: [] }); + }; + if (ctl.hold) ctl.pending.push(settle); + else settle(); + }) + ); + return { + ctl, + release: async () => { + ctl.hold = false; + ctl.pending.splice(0).forEach((s) => s()); + await flush(); + }, + }; +}; const fakeScene = () => ({ login: vi.fn(), dispose: vi.fn() }); const hex = (c: readonly number[]) => `#${c.map((v) => v.toString(16).padStart(2, '0')).join('')}`; @@ -58,6 +90,7 @@ beforeEach(() => { setSkyState('auto'); createRidgeScene.mockReset(); createScene.mockReset(); + loadBackdrop.mockReset(); }); afterEach(() => { setSkyClock(); @@ -70,7 +103,9 @@ describe('startBackgroundScene follows the sky state', () => { createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); expect(createRidgeScene).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor('night', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -89,7 +124,9 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('night'); createRidgeScene.mockReturnValue(fakeScene()); const scene = await startBackgroundScene(config, caps, { canvas }); - expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe(hex(ridgeSkyFor('night', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[0][0].sky.top)).toBe( + hex(ridgeSkyFor('night', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -101,7 +138,9 @@ describe('startBackgroundScene follows the sky state', () => { setSkyState('day'); await flush(); expect(first.dispose).toHaveBeenCalledOnce(); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('day', FALLBACK_VIEW).top) + ); scene?.dispose(); expect(second.dispose).toHaveBeenCalledOnce(); }); @@ -114,7 +153,9 @@ describe('startBackgroundScene follows the sky state', () => { const scene = await started; await flush(); expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('day', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('day', FALLBACK_VIEW).top) + ); expect(a.dispose).toHaveBeenCalledOnce(); scene?.dispose(); expect(b.dispose).toHaveBeenCalledOnce(); @@ -217,7 +258,9 @@ describe('startBackgroundScene follows the sky state', () => { await flush(); // The initial build and one rebuild, for dusk; day's rebuild stood down before building anything. expect(createRidgeScene).toHaveBeenCalledTimes(2); - expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe(hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top)); + expect(hex(createRidgeScene.mock.calls[1][0].sky.top)).toBe( + hex(ridgeSkyFor('dusk', FALLBACK_VIEW).top) + ); scene?.dispose(); }); @@ -290,3 +333,390 @@ describe('startBackgroundScene follows the sky state', () => { expect(onCompileFail).toHaveBeenCalledWith(boom); }); }); + +describe('the ridge planes', () => { + const served = (over: Record = {}) => { + const files: Record = { + '/public/ridge/index.json': wireIndex, + '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(), + '/public/ridge/graz-def456def456/manifest.json': wireManifest({ + place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' }, + }), + ...over, + }; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url in files + ? { ok: true, status: 200, json: async () => files[url] } + : { ok: false, status: 404, json: async () => ({}) } + ) + ); + }; + beforeEach(() => forgetManifests()); + + it('hands the scene the lit cards of its manifest, lit once for the sky it was given, over the manifest view', async () => { + served(); + const { ctl } = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.backdrop.manifest.view.place.id).toBe('vienna'); + expect(opts.sky.physical.view).toBe(opts.backdrop.manifest.view); + expect(ctl.calls).toHaveLength(1); + expect(ctl.calls[0]).toBe(opts.sky.physical); // the sky the cards were lit for is the sky the scene paints + expect(ctl.calls[0].state).toBe('night'); // midnight by the clock + scene?.dispose(); + }); + + it('config place picks the index entry; an unknown id falls back to the default', async () => { + served(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + (await startBackgroundScene({ ...config, place: 'graz' }, caps, { canvas }))?.dispose(); + expect(createRidgeScene.mock.calls[0][0].backdrop.manifest.view.place.id).toBe('graz'); + forgetManifests(); + (await startBackgroundScene({ ...config, place: 'nowhere' }, caps, { canvas }))?.dispose(); + expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); + }); + + const skyOnly = async (onPlanesFail = vi.fn(), onCompileFail = vi.fn()) => { + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(scene).not.toBeNull(); + expect(opts.backdrop).toBeUndefined(); + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }; + + it('a 404 manifest gives the sky-only scene with the fallback view, one onPlanesFail and no onCompileFail', async () => { + served({ '/public/ridge/index.json': undefined }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => ({ ok: false, status: 404, json: async () => ({}) })) + ); + loader(); + await skyOnly(); + }); +}); + +describe('the ridge cards failing', () => { + it('a card that will not load gives the same sky-only scene, and a rebuild does not report again', async () => { + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => (url.endsWith('index.json') ? wireIndex : wireManifest()), + })) + ); + loader().ctl.fail = true; + forgetManifests(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onCompileFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); + setSkyState('day'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); +}); + +describe('the ridge cards and the live scene', () => { + const serve = (manifest: Record = wireManifest()) => + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => (url.endsWith('index.json') ? wireIndex : manifest), + })) + ); + beforeEach(() => forgetManifests()); + + it('says nothing about cards when they load', async () => { + serve(); + loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onPlanesOk = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); + setSkyState('day'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls.every((c) => c[0].backdrop)).toBe(true); + expect(onPlanesFail).not.toHaveBeenCalled(); + expect(onPlanesOk).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('lights the cards again for the new sky on a sky-change rebuild, never otherwise', async () => { + serve(); + const { ctl } = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + expect(ctl.calls.map((s) => s.state)).toEqual(['night']); + setSkyState('night'); // the sky already drawn: no rebuild, no lighting + await flush(); + expect(ctl.calls).toHaveLength(1); + setSkyState('day'); + await flush(); + expect(ctl.calls.map((s) => s.state)).toEqual(['night', 'day']); + expect(createRidgeScene.mock.calls[1][0].sky.physical).toBe(ctl.calls[1]); + expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('vienna'); + scene?.dispose(); + }); + + it('a lighting pass that throws (no WebGL2) is the sky alone, one onPlanesFail and never onCompileFail', async () => { + serve(); + loadBackdrop.mockRejectedValue(new Error('ridge: no WebGL2')); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onCompileFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onCompileFail }); + expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined(); + expect(createRidgeScene.mock.calls[0][0].sky.physical.view).toBe(FALLBACK_VIEW); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onPlanesFail.mock.calls[0][0].message).toMatch(/WebGL2/); + expect(onCompileFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it("keys a rebuild by the manifest's place: the same sky state over a rebaked place rebuilds", async () => { + serve(); + loader(); + const [a, b] = [fakeScene(), fakeScene()]; + createRidgeScene.mockReturnValueOnce(a).mockReturnValueOnce(b); + const w = wireManifest() as any; + const scene = await startBackgroundScene(config, caps, { canvas }); + // 'auto' at midnight and 'night' are one sky: no rebuild, while the place is the one drawn. + setSkyState('night'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + forgetManifests(); + serve({ ...w, place: { ...w.place, id: 'graz' } }); + setSkyState('auto'); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(createRidgeScene.mock.calls[1][0].backdrop.manifest.view.place.id).toBe('graz'); + scene?.dispose(); + }); + + it("reads the weather against the manifest place's sun, not the fallback place's", async () => { + const w = wireManifest() as any; + const place = { ...w.place, id: 'weather-place', lat: -33, lon: -163.65, tz_h: -11 }; + const now = new Date('2026-11-11T10:50:00Z'); + const wx = { + fetched_at: '2026-11-11T10:45:00Z', + observed_at: '2026-11-11T10:40:00Z', + station: 11035, + precip_mm_10min: 0, + humidity_pct: 60, + sunshine_s_10min: null, + glow_wm2: 100, + attribution: WEATHER_ATTRIBUTION, + }; + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => ({ + ok: true, + status: 200, + json: async () => + url.endsWith('weather.json') + ? wx + : url.endsWith('index.json') + ? wireIndex + : { ...w, place }, + })) + ); + loader(); + setSkyClock(() => now); + createRidgeScene.mockReturnValue(fakeScene()); + (await startBackgroundScene(config, caps, { canvas }))?.dispose(); + const file = parseWeatherFile(wx)!; + const at = (p: { lat: number; lon: number }) => + weatherFromFile( + file, + sunAt({ id: 'x', altitudeKm: 0, ...p }, new Date(Date.parse(wx.observed_at) - 5 * 60_000)) + .elevation + ); + expect(at(FALLBACK_VIEW.place)).not.toBe(at(place)); + expect(ridgeWeather()).toBe(at(place)); + }); + + it('a failed load is the sky alone on the fallback view, never the manifest place', async () => { + serve(); + const { ctl } = loader(); + ctl.fail = true; + createRidgeScene.mockReturnValue(fakeScene()); + const scene = await startBackgroundScene(config, caps, { canvas }); + const opts = createRidgeScene.mock.calls[0][0]; + expect(opts.backdrop).toBeUndefined(); + expect(opts.sky.physical.view).toBe(FALLBACK_VIEW); + scene?.dispose(); + }); + + it('a rebuild keeps the old scene until the new planes have loaded, then swaps', async () => { + serve(); + const d = loader(); + const first = fakeScene(); + const second = fakeScene(); + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(second); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyState('day'); + await flush(); + expect(d.ctl.pending.length).toBeGreaterThan(0); + expect(first.dispose).not.toHaveBeenCalled(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + scene?.login(); + expect(first.login).toHaveBeenCalledOnce(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(second.dispose).not.toHaveBeenCalled(); + expect(onActive).toHaveBeenCalledOnce(); + expect(second.login).toHaveBeenCalledOnce(); // replayed onto the swapped-in scene + scene?.dispose(); + expect(second.dispose).toHaveBeenCalledOnce(); + }); + + it('a build that fails after the scene is disposed makes nothing and says nothing', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); + d.ctl.hold = true; + d.ctl.fail = true; + setSkyState('day'); + await flush(); + scene?.dispose(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(onPlanesFail).not.toHaveBeenCalled(); + }); + + it('a superseded build that fails does not speak for the live scene, which has planes', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail }); + d.ctl.hold = true; + d.ctl.fail = true; + setSkyState('day'); // stale: its decodes will reject + await flush(); + d.ctl.fail = false; + setSkyState('dusk'); // the live one: its decodes will succeed + await flush(); + const stale = d.ctl.pending.splice(0, 1); + d.ctl.pending.length = 0; + d.ctl.hold = false; + stale.forEach((s) => s()); // the first six are day's, settled in order + await flush(); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('a superseded build that finishes after the newer one touches nothing of the live scene', async () => { + serve(); + const d = loader(); + const [first, second, third] = [fakeScene(), fakeScene(), fakeScene()]; + createRidgeScene + .mockReturnValueOnce(first) + .mockReturnValueOnce(second) + .mockReturnValueOnce(third); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyState('day'); // stale: its decodes are held until after the newer build is live + await flush(); + const dayDecodes = d.ctl.pending.splice(0); + setSkyState('dusk'); + await flush(); + const duskDecodes = d.ctl.pending.splice(0); + expect(dayDecodes.length).toBeGreaterThan(0); + expect(duskDecodes.length).toBeGreaterThan(0); + duskDecodes.forEach((s) => s()); + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(onActive).toHaveBeenCalledOnce(); + dayDecodes.forEach((s) => s()); // the stale build finishes last + await flush(); + expect(createRidgeScene).toHaveBeenCalledTimes(2); + expect(second.dispose).not.toHaveBeenCalled(); // the live scene is not disposed by a build that lost + expect(onActive).toHaveBeenCalledOnce(); + scene?.login(); + expect(second.login).toHaveBeenCalledOnce(); + scene?.dispose(); + expect(second.dispose).toHaveBeenCalledOnce(); + expect(third.dispose).not.toHaveBeenCalled(); + }); + + it('a build that finishes after dispose makes nothing, shows nothing and disposes nothing twice', async () => { + serve(); + const d = loader(); + const first = fakeScene(); + createRidgeScene.mockReturnValueOnce(first).mockReturnValueOnce(fakeScene()); + const onActive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onActive }); + d.ctl.hold = true; + setSkyState('day'); + await flush(); + scene?.dispose(); + await d.release(); + expect(createRidgeScene).toHaveBeenCalledOnce(); + expect(first.dispose).toHaveBeenCalledOnce(); + expect(onActive).not.toHaveBeenCalled(); + }); + + it('a rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => { + serve(); + const d = loader(); + createRidgeScene.mockReturnValueOnce(fakeScene()).mockReturnValueOnce(null); + const onPlanesFail = vi.fn(); + const onInactive = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onInactive }); + d.ctl.fail = true; + setSkyState('day'); + await flush(); + expect(onInactive).toHaveBeenCalledOnce(); + expect(onPlanesFail).not.toHaveBeenCalled(); + scene?.dispose(); + }); + + it('tells the host when the live scene loses its planes and when it gets them back', async () => { + serve(); + const d = loader(); + d.ctl.fail = true; + createRidgeScene.mockReturnValue(fakeScene()); + const onPlanesFail = vi.fn(); + const onPlanesOk = vi.fn(); + const scene = await startBackgroundScene(config, caps, { canvas, onPlanesFail, onPlanesOk }); + expect(onPlanesFail).toHaveBeenCalledOnce(); + setSkyState('day'); // still failing: the host is not told twice + await flush(); + expect(onPlanesFail).toHaveBeenCalledOnce(); + expect(onPlanesOk).not.toHaveBeenCalled(); + d.ctl.fail = false; + setSkyState('dusk'); + await flush(); + expect(onPlanesOk).toHaveBeenCalledOnce(); + expect(createRidgeScene.mock.calls[2][0].backdrop).toBeDefined(); + d.ctl.fail = true; + setSkyState('night'); + await flush(); + expect(onPlanesFail).toHaveBeenCalledTimes(2); + scene?.dispose(); + }); +}); diff --git a/src/app/features/scene/index.ts b/src/app/features/scene/index.ts index d4286d69..794a9597 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -4,6 +4,7 @@ import { debugOverlaysAllowed } from './debugOverlays'; import { getSkyState, subscribe } from './skyState'; import type { SkyState } from './skyState'; import type { SkyColours } from './ridge/skyColour'; +import type { Backdrop } from './ridge/Backdrop'; import { loadManifest } from './ridge/manifest'; import type { RidgeManifest } from './ridge/manifest'; import { FALLBACK_VIEW } from './ridge/view'; @@ -18,7 +19,7 @@ export type StartOptions = Omit void; /** A rebuild made a scene again: the host lets it show. */ onActive?: () => void; - /** The live scene is the sky alone because the baked ridge planes did not load (no manifest, a missing image). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */ + /** The live scene is the sky alone because the baked ridge cards did not load (no manifest, a missing or undecodable card, no WebGL2 to light them). The host may fill the ground. Told when the live scene changes to that state, never for a build that did not win. */ onPlanesFail?: (e: Error) => void; /** The live scene has its planes after `onPlanesFail` said it had none: the host lets go of the ground it filled. */ onPlanesOk?: () => void; @@ -75,14 +76,32 @@ async function prepare( const { createRidgeScene } = await import('./ridge/Ridge'); const { manifest, fail } = await manifestOf(config); await loadWeather(weatherUrl(), (manifest?.view ?? FALLBACK_VIEW).place); - // Every failure is the sky alone: a manifest that did not load or parse (schema 1 included) names itself in `fail`. + // The cards load with the scene chunk and the weather, and are lit here for this sky (once per build: a sky change comes through a rebuild, never per + // frame), so createRidgeScene stays synchronous. Any failure, a missing WebGL2 included, is the sky alone. + let backdrop: Backdrop | null = null; let sky: SkyColours | undefined; - const planesFail: Error | null = fail; - if (manifest) sky = ridgeSkyFor(state, manifest.view); + let planesFail: Error | null = fail; + if (manifest) { + try { + const manifestSky = ridgeSkyFor(state, manifest.view); + sky = manifestSky; + const { loadBackdrop } = await import('./ridge/Backdrop'); + backdrop = await loadBackdrop( + manifest, + manifestSky.physical as NonNullable + ); + if (!backdrop) throw new Error('ridge cards did not load'); + } catch (e) { + backdrop = null; + sky = undefined; + planesFail = e instanceof Error ? e : new Error(String(e)); + } + } const made = guarded(() => createRidgeScene({ ...options, sky: sky ?? ridgeSkyFor(state, FALLBACK_VIEW), + backdrop: backdrop ?? undefined, }) ); return { ...made, planesFail }; diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index 52e830db..646fab95 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -6,8 +6,10 @@ import type { SkyColours } from './skyColour'; import { makeStars } from './stars'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { startBackgroundScene } from '../index'; +import { parseManifest } from './manifest'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; -import { FALLBACK_VIEW, windowFor } from './view'; +import type { Backdrop } from './Backdrop'; +import { cardMotion, FALLBACK_VIEW, windowFor } from './view'; describe('noise', () => { it('is deterministic and in [0, 1)', () => { @@ -144,7 +146,16 @@ function ctx() { draws.push('sky'); }, save() {}, - restore() {}, + restore() { + c.t = undefined; + c.k = undefined; + }, + translate(x: number, y: number) { + c.t = [x, y]; + }, + scale(k: number) { + c.k = k; + }, rect() {}, clip() {}, createImageData: (w: number, h: number) => ({ @@ -175,7 +186,9 @@ function ctx() { else draws.push('fill'); }, drawImage(...a: unknown[]) { - images.push(Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation })); + images.push( + Object.assign(a, { alpha: c.globalAlpha, op: c.globalCompositeOperation, t: c.t, k: c.k }) + ); }, globalAlpha: 1, globalCompositeOperation: 'source-over', @@ -522,6 +535,175 @@ describe('rain in the scene', () => { }); }); +describe('the ridge cards in the scene', () => { + const manifest = parseManifest(wireManifest(), '/d/'); // three cards, scales 1.2, 1.0167, 1.005, nearest first + const litCards = (): Backdrop => ({ + manifest, + cards: manifest.cards.map((c, k) => { + const canvas = fakeEl('canvas'); + canvas.id = `card-${k}`; + return { canvas: canvas as unknown as HTMLCanvasElement, top: c.top, h: c.h, scale: c.scale }; + }), + }); + const night: SkyColours = { + ...DAY, + top: [10, 14, 40], + mid: [30, 34, 80], + horizon: [60, 50, 90], + physical: makePhysicalSky('night', new Date('2026-06-21T22:40:00Z'), 1, FALLBACK_VIEW), + }; + const rigOf = (parent: any) => + parent.children.find((c: any) => c.children.some((g: any) => g.anims.length)); + const win = windowFor(manifest.view, 400, 800); + const motion400 = cardMotion(manifest, win); + + it('stacks the rig after the twinkle canvas and before the rain, with no z-index and no fixed position', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!; + const kinds = parent.children.map((c: any) => c.tag); + expect(kinds).toEqual(['canvas', 'canvas', 'div', 'div', 'div']); + expect(parent.children[2].children).toHaveLength(3); + parent.children.forEach((c: any) => { + expect(c.style.zIndex).toBeUndefined(); + expect(c.style.position).not.toBe('fixed'); + }); + s.dispose(); + expect(parent.children).toEqual([canvas]); + }); + + it('is one element per card, farthest first, each at its rows of the plane and its origin on the horizon centre', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const rig = rigOf(parent); + expect(rig.children.map((c: any) => c.id)).toEqual(['card-2', 'card-1', 'card-0']); + const planeTop = 800 - win.plane.bottom - win.plane.h; + rig.children.forEach((el: any, j: number) => { + const card = manifest.cards[2 - j]; + expect(el.style.left).toBe(`${(400 - win.plane.w) / 2}px`); + expect(el.style.width).toBe(`${win.plane.w}px`); + expect(el.style.top).toBe(`${planeTop + card.top * win.plane.scale}px`); + expect(el.style.height).toBe(`${card.h * win.plane.scale}px`); + expect(el.style.transformOrigin).toBe( + `${win.plane.w / 2}px ${(manifest.view.horizonRow - card.top) * win.plane.scale}px` + ); + }); + s.dispose(); + }); + + it('pans card i by scale_i x heading and scales it by scale_i, to and fro on the compositor', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + rigOf(parent).children.forEach((el: any, j: number) => { + const k = 2 - j; + const { scale, reachPx } = motion400.cards[k]; + const { keyframes, options } = el.anims[0]; + expect(scale).toBe(manifest.cards[k].scale); + expect(keyframes).toEqual([ + { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` }, + { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` }, + ]); + expect(options).toMatchObject({ + duration: 75000, + iterations: Infinity, + direction: 'alternate', + easing: 'ease-in-out', + }); + }); + // The nearer the card, the further it travels. + const reach = (j: number) => motion400.cards[2 - j].reachPx; + expect(reach(2)).toBeGreaterThan(reach(1)); + expect(reach(1)).toBeGreaterThan(reach(0)); + s.dispose(); + }); + + it('adds no rAF or timer callback of its own: the drift is Element.animate, the stars alone loop', () => { + const { canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + expect(rafQueue).toHaveLength(1); // the frame sampler, as without cards + s.dispose(); + }); + + it('pauses the drift under reduced motion, in a hidden tab, and plays it again', () => { + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() })!; + const anims = rigOf(parent).children.map((g: any) => g.anims[0]); + anims.forEach((a: any) => expect(a.play).toHaveBeenCalled()); + anims.forEach((a: any) => a.pause.mockClear()); + motion.matches = true; + motion.addEventListener.mock.calls + .filter((c: any[]) => c[0] === 'change') + .forEach((c: any[]) => c[1]()); + anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled()); + motion.matches = false; + anims.forEach((a: any) => a.pause.mockClear()); + doc.visibilityState = 'hidden'; + doc.dispatchEvent(new Event('visibilitychange')); + anims.forEach((a: any) => expect(a.pause).toHaveBeenCalled()); + s.dispose(); + anims.forEach((a: any) => expect(a.cancel).toHaveBeenCalled()); + }); + + it("a still draws every card, farthest first, scaled by its own scale about the rig's origin, at heading 0", () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: litCards() }); + const drawn = images.filter((a) => (a[0] as any).id) as any[]; + expect(drawn.map((a) => a[0].id)).toEqual(['card-2', 'card-1', 'card-0']); + const dpr = 2; + const s = win.plane.scale * dpr; + const x0 = (800 - win.plane.w * dpr) / 2; + const planeTop = 1600 - win.plane.h * dpr; + const origin = [x0 + (win.plane.w * dpr) / 2, planeTop + manifest.view.horizonRow * s]; + drawn.forEach((a, j) => { + const card = manifest.cards[2 - j]; + expect(a.k).toBe(card.scale); + expect(a.t).toEqual(origin); + expect([a[1], a[2], a[3], a[4]]).toEqual([ + x0 - origin[0], + planeTop + card.top * s - origin[1], + win.plane.w * dpr, + card.h * s, + ]); + expect([a.alpha, a.op]).toEqual([1, 'source-over']); + }); + expect(parent.children).toEqual([canvas]); + }); + + it('settles to a still with the cards painted when the frame rate is poor', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: litCards() }); + runFrames(100, 400); + expect(images.filter((a) => (a[0] as any).id)).toHaveLength(3); + expect(parent.children).toEqual([canvas]); + }); + + it('with no backdrop it is the sky alone', () => { + const { parent, canvas } = host(); + createRidgeScene({ canvas, tier: 'full', sky: DAY }); + expect(parent.children).toEqual([canvas]); + expect(images.filter((a) => (a[0] as any).id)).toHaveLength(0); + }); + + it('asks the host canvas, and every canvas it makes, only for 2d: the cards arrive lit', () => { + const { canvas } = host(); + const kinds: string[] = []; + const ask = (el: any) => { + const real = el.getContext; + el.getContext = vi.fn((k: string) => (kinds.push(k), real(k))); + }; + ask(canvas); + const make = doc.createElement; + doc.createElement = (t: string) => { + const el = make(t); + ask(el); + return el; + }; + const s = createRidgeScene({ canvas, tier: 'full', sky: night, backdrop: litCards() })!; + expect(kinds.length).toBeGreaterThan(0); + expect(kinds.every((k) => k === '2d')).toBe(true); + s.dispose(); + }); +}); + describe('the scene wiring', () => { it('sizes from the window when the canvas has no client size', () => { const { canvas } = host(); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index 519ff0a5..5cbc0cfd 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -3,9 +3,10 @@ import { overlayRequested } from '../debugOverlays'; import { FrameSampler, FrameStats } from './probe'; import { skyColours, SkyColours, Srgb } from './skyColour'; import { paintSky as paintPhysicalSky } from './physicalSky'; -import { windowFor } from './view'; +import { cardMotion, windowFor } from './view'; import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars'; import { drawRainTile, RAIN_TILES } from './rain'; +import type { Backdrop } from './Backdrop'; export type RidgeOptions = Pick & { /** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */ @@ -16,6 +17,8 @@ export type RidgeOptions = Pick & { onProbe?: (s: FrameStats & { still: boolean }) => void; /** The sky's colours; default `skyColours()`, the one function to replace with Void's sun.js. */ sky?: SkyColours; + /** The baked ridge cards, already lit for `sky` (`Backdrop.ts`); none is the sky-only scene (`view.ts` FALLBACK_VIEW). */ + backdrop?: Backdrop; }; const css = (c: Srgb): string => `rgb(${c[0]},${c[1]},${c[2]})`; @@ -92,6 +95,8 @@ const clock = (): number => (typeof performance !== 'undefined' ? performance.no interface Built { /** The twinkling stars' own canvas, over the sky; absent in a day sky and in 'still'. */ twinkle?: HTMLCanvasElement; + /** The ridge cards' rig, over the twinkle canvas and under the rain; absent in 'still' (the cards are drawn into the host canvas). */ + rig?: { el: HTMLElement; anims: (Animation | undefined)[] }; /** The rain's tiles and their falling, present only when the weather rains (`rain.ts`). */ rain?: { els: HTMLElement[]; anims: (Animation | undefined)[] }; } @@ -99,12 +104,13 @@ interface Built { /** The twinkle overlay redraws at most this often: the swings are 2 to 7 s, no need for 60 fps. */ const TWINKLE_FRAME_MS = 50; -/** One leg of the back-and-forth drift takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ +/** One leg of the back-and-forth drift, a turn of the heading from one end of its range to the other, takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */ const DRIFT_LEG_S = 75; /** * The ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS - * ground"), no WebGL. It draws the sky, the stars and the rain. The host canvas holds the baked sky; it and + * ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself + * requests no WebGL: the cards arrive lit (`lightCards.ts`, once per scene build) and only 2D contexts are asked of the host canvas. The host canvas holds the baked sky; it and * its parent must be positioned, and the canvas should fill the parent. */ export function createRidgeScene(opts: RidgeOptions): Scene | null { @@ -136,6 +142,8 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { const teardown = () => { built?.twinkle?.remove(); + built?.rig?.anims.forEach((a) => a?.cancel()); + built?.rig?.el.remove(); built?.rain?.anims.forEach((a) => a?.cancel()); built?.rain?.els.forEach((e) => e.remove()); cancelAnimationFrame(twRaf); @@ -199,6 +207,84 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { return { els, anims }; }; + /** + * The ridge over the sky: one element per lit card, farthest first (DOM order is paint order, stacking is by order alone), placed at the card's rows + * of the plane and scaled about the horizon's centre by the baker's `scale` (`view.ts` `cardMotion` owns every offset and scale). The camera + * turns through its heading range and back on the compositor: card i pans `scale` x heading, so a nearer card leads the far range. + */ + const startRig = (bd: Backdrop, w: number, h: number): NonNullable => { + const { view } = bd.manifest; + const win = windowFor(view, w, h); + const motion = cardMotion(bd.manifest, win); + const el = document.createElement('div'); + el.setAttribute('aria-hidden', 'true'); + Object.assign(el.style, { + position: 'absolute', + left: '0', + top: '0', + width: '100%', + height: '100%', + overflow: 'hidden', + pointerEvents: 'none', + }); + const anims: (Animation | undefined)[] = []; + const planeTop = h - win.plane.bottom - win.plane.h; + for (let k = bd.cards.length - 1; k >= 0; k -= 1) { + const card = bd.cards[k]; + const { scale, reachPx } = motion.cards[k]; + const node = card.canvas; + Object.assign(node.style, { + position: 'absolute', + left: `${(w - win.plane.w) / 2}px`, + top: `${planeTop + card.top * win.plane.scale}px`, + width: `${win.plane.w}px`, + height: `${card.h * win.plane.scale}px`, + transformOrigin: `${win.plane.w / 2}px ${(view.horizonRow - card.top) * win.plane.scale}px`, + willChange: 'transform', + }); + el.appendChild(node); + anims.push( + node.animate?.( + [ + { transform: `translate3d(${-reachPx}px,0,0) scale(${scale})` }, + { transform: `translate3d(${reachPx}px,0,0) scale(${scale})` }, + ], + { + duration: DRIFT_LEG_S * 1000, + iterations: Infinity, + direction: 'alternate', + easing: 'ease-in-out', + } + ) + ); + } + parent.appendChild(el); + return { el, anims }; + }; + + /** Paint the lit cards into the host canvas, farthest first, each at its scale about the same origin as the rig, at heading 0: the still scene's one image. */ + const paintCards = (bd: Backdrop) => { + const ctx = context2d(canvas); + if (!ctx) return; + const { view } = bd.manifest; + const { w, h, scale } = viewSize(); + const win = windowFor(view, w, h); + const s = win.plane.scale * scale; + const dw = win.plane.w * scale; + const x0 = (canvas.width - dw) / 2; + const planeTop = canvas.height - (win.plane.h + win.plane.bottom) * scale; + const ox = x0 + dw / 2; + const oy = planeTop + view.horizonRow * s; + for (let k = bd.cards.length - 1; k >= 0; k -= 1) { + const card = bd.cards[k]; + ctx.save(); + ctx.translate(ox, oy); + ctx.scale(card.scale, card.scale); + ctx.drawImage(card.canvas, x0 - ox, planeTop + card.top * s - oy, dw, card.h * s); + ctx.restore(); + } + }; + /** Paint the sky, the stars and the rain. Returns false when a 2D context is missing or there is no area yet. */ const build = (): boolean => { teardown(); @@ -231,6 +317,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } field = stars; built = { twinkle }; + if (opts.backdrop && !still) built.rig = startRig(opts.backdrop, w, h); if (tier !== 'still' && sky.physical && sky.physical.weather.rain > 0) built.rain = startRain(sky.physical.weather.rain, sky.horizon, w, h, scale); syncPlayState(); @@ -265,7 +352,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { }; function syncPlayState() { - const anims = [...(built?.rain?.anims ?? [])]; + const anims = [...(built?.rig?.anims ?? []), ...(built?.rain?.anims ?? [])]; anims.forEach((a) => (moving() ? a?.play() : a?.pause())); if (!built?.twinkle) return; if (moving()) { @@ -284,6 +371,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { teardown(); cancelAnimationFrame(raf); raf = 0; + if (opts.backdrop) paintCards(opts.backdrop); report(true); }; diff --git a/src/app/features/scene/ridge/ridgeAssets.test.ts b/src/app/features/scene/ridge/ridgeAssets.test.ts new file mode 100644 index 00000000..aaec06ee --- /dev/null +++ b/src/app/features/scene/ridge/ridgeAssets.test.ts @@ -0,0 +1,242 @@ +// The committed baked set under public/ridge: what the baker wrote is what ships, within the budget the baker itself refuses on +// (export.py MAX_CARDS, TOTAL_BYTES_MAX, DECODE_BYTES_MAX). Reads with node fs. The gate reads each card file's own bytes, not the manifest's +// claims about them: the WebP container is walked and its stated dimensions (VP8X canvas, VP8 / VP8L frame header) must equal the card's +// width and band height, which the decode budget is computed from; and the bake id is re-derived from the card bytes as the baker derives it, +// so any corruption of a card, same length or not, fails. No pixel decoder is in the tree; the baker's own check decodes pixels. +import { createHash } from 'node:crypto'; +import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs'; +import { join, sep } from 'node:path'; +import { describe, expect, it } from 'vitest'; +import { MAX_CARDS, parseIndex, parseManifest } from './manifest'; + +/** The same constants as scripts/ridge-bake/export.py: every card file of a place, and the cards decoded (2 textures x w x band rows x 4 bytes each). */ +export const TOTAL_BYTES_MAX = 1_500_000; +export const DECODE_BYTES_MAX = 20_000_000; + +interface WireFile { + file: string; + bytes: number; +} +interface WireCard { + top: number; + h: number; + scale: number; + colour: WireFile; + geometry: WireFile; +} +export interface WireManifest { + bake_id: string; + w: number; + cards: WireCard[]; + camera?: { heading_max_deg?: number }; +} + +const files = (c: WireCard): WireFile[] => [c.colour, c.geometry]; + +/** Why a manifest breaks the size gate, or undefined: too many cards, too many bytes, or too many decoded bytes. */ +export function sizeGate(m: WireManifest): string | undefined { + if (m.cards.length > MAX_CARDS) return `${m.cards.length} cards, above ${MAX_CARDS}`; + const bytes = m.cards.flatMap(files).reduce((a, f) => a + f.bytes, 0); + if (bytes > TOTAL_BYTES_MAX) return `the cards are ${bytes} bytes, above ${TOTAL_BYTES_MAX}`; + const decoded = m.cards.reduce((a, c) => a + 2 * m.w * c.h * 4, 0); + return decoded > DECODE_BYTES_MAX + ? `the cards decode to ${decoded} bytes, above ${DECODE_BYTES_MAX}` + : undefined; +} + +/** Why `b` is not the WebP of `w` x `h` pixels, or undefined: the RIFF container is walked, so a cut or padded file and a changed frame header fail. */ +export function webpFault(b: Uint8Array, w: number, h: number): string | undefined { + const u32 = (o: number) => (b[o] | (b[o + 1] << 8) | (b[o + 2] << 16) | (b[o + 3] << 24)) >>> 0; + const u24 = (o: number) => b[o] | (b[o + 1] << 8) | (b[o + 2] << 16); + const tag = (o: number) => String.fromCharCode(b[o], b[o + 1], b[o + 2], b[o + 3]); + if (b.length < 20 || tag(0) !== 'RIFF' || tag(8) !== 'WEBP') return 'not a RIFF WEBP'; + if (u32(4) + 8 !== b.length) return `RIFF size ${u32(4)} does not fit a ${b.length} byte file`; + const dims: string[] = []; + let seen = 0; + let o = 12; + while (o < b.length) { + if (o + 8 > b.length) return 'a chunk header runs past the file'; + const id = tag(o); + const len = u32(o + 4); + const body = o + 8; + if (body + len > b.length) return `chunk ${id} runs past the file`; + if (id === 'VP8X') dims.push(`${u24(body + 4) + 1}x${u24(body + 7) + 1}`); + if (id === 'VP8 ') { + if (b[body + 3] !== 0x9d || b[body + 4] !== 0x01 || b[body + 5] !== 0x2a) + return 'VP8 start code missing'; + dims.push( + `${(b[body + 6] | (b[body + 7] << 8)) & 0x3fff}x${ + (b[body + 8] | (b[body + 9] << 8)) & 0x3fff + }` + ); + seen += 1; + } + if (id === 'VP8L') { + if (b[body] !== 0x2f) return 'VP8L signature missing'; + const bits = u32(body + 1); + dims.push(`${(bits & 0x3fff) + 1}x${((bits >>> 14) & 0x3fff) + 1}`); + seen += 1; + } + o = body + len + (len & 1); + } + if (o !== b.length) return 'the chunks do not tile the file'; + if (seen !== 1) return `${seen} bitstream chunks`; + const bad = dims.find((d) => d !== `${w}x${h}`); + return bad ? `states ${bad}, the manifest ${w}x${h}` : undefined; +} + +/** The baker's bake id (export.py `bake_id`): first 12 hex of sha256 over the card files in index order, colour then geometry. */ +export function bakeIdOf( + cardBytes: (card: number, kind: 'colour' | 'geometry') => Uint8Array, + n: number +): string { + const h = createHash('sha256'); + for (let i = 0; i < n; i += 1) { + h.update(cardBytes(i, 'colour')); + h.update(cardBytes(i, 'geometry')); + } + return h.digest('hex').slice(0, 12); +} + +const ROOT = join(process.cwd(), 'public', 'ridge'); +const readJson = (p: string): unknown => JSON.parse(readFileSync(p, 'utf8')); +const index = parseIndex(readJson(join(ROOT, 'index.json'))); +const dirs = Object.entries(index.places); + +describe('the committed ridge assets', () => { + it('ship at least one place, and the index default is one of them', () => { + expect(dirs.length).toBeGreaterThan(0); + expect(index.places[index.default]).toBeDefined(); + }); + + dirs.forEach(([id, dir]) => { + describe(`${id} (${dir})`, () => { + const raw = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest & { schema: number }; + const read = (f: WireFile) => readFileSync(join(ROOT, dir, f.file)); + + it('is schema 2, parses, and its directory ends in its bake id', () => { + expect(raw.schema).toBe(2); + expect(() => parseManifest(raw, `${dir}/`)).not.toThrow(); + expect(dir.endsWith(`-${raw.bake_id}`)).toBe(true); + }); + + it('has every card file, at the length the manifest states', () => { + raw.cards.flatMap(files).forEach((f) => { + expect(statSync(join(ROOT, dir, f.file)).size, f.file).toBe(f.bytes); + }); + }); + + it('decodes every card file as the WebP of the width and band height the manifest states', () => { + raw.cards.forEach((c) => + files(c).forEach((f) => { + expect(webpFault(read(f), raw.w, c.h), f.file).toBeUndefined(); + }) + ); + }); + + it('holds the bytes its bake id was made from', () => { + const bytes = (i: number, kind: 'colour' | 'geometry') => read(raw.cards[i][kind]); + expect(bakeIdOf(bytes, raw.cards.length)).toBe(raw.bake_id); + }); + + it('keeps the place inside the card, byte and decode budget', () => { + expect(sizeGate(raw)).toBeUndefined(); + }); + + it('carries its camera and a scale for every card', () => { + expect(Number.isFinite(raw.camera?.heading_max_deg)).toBe(true); + raw.cards.forEach((c) => expect(Number.isFinite(c.scale) && c.scale > 0).toBe(true)); + }); + }); + }); + + it('shows Vienna from a camera pushed forward: no card is smaller than its bake', () => { + const vienna = index.places.vienna; + expect(vienna).toBeDefined(); + const m = readJson(join(ROOT, vienna, 'manifest.json')) as WireManifest; + m.cards.forEach((c) => expect(c.scale).toBeGreaterThanOrEqual(1)); + }); + + it('holds no file a manifest does not name', () => { + const named = new Set(['index.json']); + dirs.forEach(([, dir]) => { + named.add(`${dir}/manifest.json`); + (readJson(join(ROOT, dir, 'manifest.json')) as WireManifest).cards + .flatMap(files) + .forEach((f) => named.add(`${dir}/${f.file}`)); + }); + const onDisk = readdirSync(ROOT, { recursive: true, withFileTypes: true }) + .filter((e) => e.isFile()) + .map((e) => + join(e.parentPath, e.name) + .slice(ROOT.length + 1) + .split(sep) + .join('/') + ); + expect(onDisk.filter((f) => !named.has(f))).toEqual([]); + expect([...named].filter((f) => !existsSync(join(ROOT, f)))).toEqual([]); + }); +}); + +describe('the card gates refuse a card that is not what the manifest says', () => { + const dir = Object.values(index.places)[0]; + const manifest = readJson(join(ROOT, dir, 'manifest.json')) as WireManifest; + const real = readFileSync(join(ROOT, dir, manifest.cards[1].geometry.file)); + const { h } = manifest.cards[1]; + const w = manifest.w; + const id = (b: Uint8Array) => bakeIdOf(() => b, 1); + + it('accepts the real card at its size', () => { + expect(webpFault(real, w, h)).toBeUndefined(); + }); + it("refuses a manifest that lies about the card's size, and a file cut short or padded", () => { + expect(webpFault(real, w, h + 1)).toMatch(/states/); + expect(webpFault(real.subarray(0, real.length - 1), w, h)).toBeDefined(); + expect(webpFault(Buffer.concat([real, Buffer.from([0])]), w, h)).toBeDefined(); + }); + it('refuses bytes that are not a WebP', () => { + expect(webpFault(Buffer.from('not a webp, but long enough to try'), w, h)).toMatch(/RIFF/); + }); + it('re-derives a different bake id from a card with the same length and 8 bytes overwritten', () => { + const bad = Buffer.from(real); + bad.fill(0xab, 100, 108); + expect(bad.length).toBe(real.length); + expect(id(bad)).not.toBe(id(real)); + }); + it('derives the id from colour then geometry, in card order', () => { + const a = Buffer.from('a-colour'); + const b = Buffer.from('b-geometry'); + const order = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? a : b); + const swapped = (c: number, k: 'colour' | 'geometry') => (c === 0 && k === 'colour' ? b : a); + const want = createHash('sha256').update(a).update(b).update(b).update(b); + expect(bakeIdOf(order, 2)).toBe(want.digest('hex').slice(0, 12)); + expect(bakeIdOf(swapped, 2)).not.toBe(bakeIdOf(order, 2)); + }); +}); + +describe('sizeGate', () => { + const card = (bytes: number, h: number): WireCard => ({ + top: 0, + h, + scale: 1, + colour: { file: 'c.webp', bytes }, + geometry: { file: 'g.webp', bytes }, + }); + const set = (n: number, bytes: number, h: number): WireManifest => ({ + bake_id: 'x', + w: 1280, + cards: Array.from({ length: n }, () => card(bytes, h)), + }); + + it('passes a place at the byte budget and fails one a byte over', () => { + expect(sizeGate(set(3, 250_000, 100))).toBeUndefined(); + expect(sizeGate(set(3, 250_001, 100))).toMatch(/1500006 bytes/); + }); + + it('fails a seventh card, and cards that decode past the budget', () => { + expect(sizeGate(set(6, 1, 150))).toBeUndefined(); + expect(sizeGate(set(7, 1, 150))).toMatch(/7 cards/); + expect(sizeGate(set(2, 1, 600))).toBeUndefined(); + expect(sizeGate(set(4, 1, 600))).toMatch(/decode/); + }); +}); diff --git a/src/app/features/scene/tier.ts b/src/app/features/scene/tier.ts index a7e9ad4a..0f1c96be 100644 --- a/src/app/features/scene/tier.ts +++ b/src/app/features/scene/tier.ts @@ -16,7 +16,7 @@ export interface Capabilities { } /** - * 'ridge': baked parallax ridges, no WebGL (default). 'raymarch': the sphere-traced world with its tree and + * 'ridge': baked ridge cards lit once per sky in WebGL2, no per-frame WebGL (default). 'raymarch': the sphere-traced world with its tree and * clouds. */ export type SceneStyle = 'ridge' | 'raymarch';