diff --git a/src/app/features/scene/README.md b/src/app/features/scene/README.md index c2af8e57..73844795 100644 --- a/src/app/features/scene/README.md +++ b/src/app/features/scene/README.md @@ -21,11 +21,13 @@ means "keep the CSS ground". Everything below this section describes the opt-in - 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` `create()` loads manifest and planes with the scene chunk, so `createRidgeScene({ backdrop })` stays - synchronous. The rig is one div of three plane groups (far, mid, near; DOM order is paint order; no z-index, no fixed position, nothing + 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. A failure anywhere (404, bad manifest, an image that - will not decode) is the sky-only scene on `FALLBACK_VIEW`, reported once through `onPlanesFail`; it is never `onCompileFail`. + 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/`. - `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 79bcb0b5..4da1b3b7 100644 --- a/src/app/features/scene/index.test.ts +++ b/src/app/features/scene/index.test.ts @@ -7,6 +7,7 @@ import { ridgeSkyFor } from './skyForState'; import { forgetManifests } from './ridge/manifest'; import { wireIndex, wireManifest } from './ridge/manifest.fixture'; import { FALLBACK_VIEW } from './ridge/view'; +import { frameChoice } from './ridge/frameChoice'; const { createRidgeScene, createScene } = vi.hoisted(() => ({ createRidgeScene: vi.fn(), @@ -189,7 +190,7 @@ describe('startBackgroundScene follows the sky state', () => { }); // A second sky change `ticks` microtasks after the first. True when it landed mid-build: the build for the first - // change finished, was found stale and dropped (never shown), and only the newest sky was announced. + // change finished loading, was found stale and was never made (so it never showed or spoke), and only the newest sky was announced. const changeAfter = async (ticks: number) => { createRidgeScene.mockReset(); setSkyState('auto'); @@ -216,7 +217,7 @@ describe('startBackgroundScene follows the sky state', () => { }); scene?.dispose(); expect(live.dispose, at).toHaveBeenCalledOnce(); - return built === 3 && onActive.mock.calls.length === 1; + return built === 2 && onActive.mock.calls.length === 1; }; it('a sky change at any point of a build leaves only the newer build live; the stale one is disposed', async () => { @@ -230,7 +231,7 @@ describe('startBackgroundScene follows the sky state', () => { // This can fail after a correct refactor that changes the await count in create/skyKey and moves every offset // off the build. Then widen the range of offsets until some land again; do not weaken the assertion. expect(landed.length, 'at least one offset must land mid-build').toBeGreaterThan(0); - }); + }, 30000); it('leaves the ray-march scene alone: it has one fixed dusk', async () => { const inner = fakeScene() as unknown as Scene; @@ -378,3 +379,203 @@ describe('the ridge planes failing', () => { scene?.dispose(); }); }); + +describe('the ridge planes 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), + })) + ); + /** Image stub whose decode waits on `gate` (when given) and then resolves or rejects as `outcome` says now. */ + const decoder = () => { + const ctl = { + pending: [] as Array<() => void>, + hold: false, + fail: false, + urls: [] as string[], + }; + vi.stubGlobal( + 'Image', + class { + src = ''; + decoding = ''; + cloneNode = () => this; + decode = () => { + const fails = ctl.fail; // the outcome belongs to the request, whenever it settles + return new Promise((resolve, reject) => { + const settle = () => { + ctl.urls.push(this.src); + if (fails) reject(new Error('bad image')); + else resolve(); + }; + 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(); + }, + }; + }; + beforeEach(() => forgetManifests()); + + it('says nothing about planes when they load', async () => { + serve(); + decoder(); + 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('chooses frames by the sun over the manifest place, not the fallback place', async () => { + const w = wireManifest() as any; + // A day where it is night by the clock, in the south, has the noon sun high and to the north; at Vienna it is low in the south: a different frame. + serve({ ...w, place: { ...w.place, lat: -33, lon: -163.65, tz_h: -11 } }); + decoder(); + setSkyState('day'); + createRidgeScene.mockReturnValue(fakeScene()); + (await startBackgroundScene(config, caps, { canvas }))?.dispose(); + const opts = createRidgeScene.mock.calls[0][0]; + const { manifest } = opts.backdrop; + const own = frameChoice(manifest.frames, opts.sky.physical.sun); + const fallbackSun = ridgeSkyFor('day').physical!.sun; + const theirs = frameChoice(manifest.frames, fallbackSun); + expect(own.a.key).not.toBe(theirs.a.key); + expect(opts.backdrop.choice.a.key).toBe(own.a.key); + expect(opts.backdrop.choice.b?.key ?? null).toBe(own.b?.key ?? null); + }); + + it('a failed load is the sky alone on the fallback view, never the manifest place', async () => { + serve(); + const { ctl } = decoder(); + 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 = decoder(); + 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 = decoder(); + 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 = decoder(); + 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, 6); + 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 rebuild that makes no scene says nothing about planes and leaves the host inactive', async () => { + serve(); + const d = decoder(); + 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 = decoder(); + 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 3d3c0a38..f4464612 100644 --- a/src/app/features/scene/index.ts +++ b/src/app/features/scene/index.ts @@ -18,37 +18,63 @@ export type StartOptions = Omit void; /** A rebuild made a scene again: the host lets it show. */ onActive?: () => void; - /** The baked ridge planes did not load (no manifest, a missing image): the scene is the sky alone, once per start. The host may fill the ground. */ + /** 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. */ 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; }; /** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */ const weatherUrl = (): string => `${import.meta.env.BASE_URL.replace(/\/$/, '')}/weather.json`; -async function create( +/** A scene made ready: every await is done, so `make` is synchronous and a rebuild can keep the old scene until the instant it swaps. */ +interface Prepared { + make: () => Scene | null; + /** Why this scene is the sky alone, when the baked planes did not load; null when it has planes or none are asked for. */ + planesFail: Error | null; +} + +async function prepare( config: BackgroundSceneConfig | undefined, options: StartOptions & { tier: SceneTier; debug?: boolean }, state: SkyState -): Promise { - const { onPlanesFail, ...sceneOptions } = options; +): Promise { + // Whatever throws in making the scene is a compile failure, as whatever throws in loading it. + const guarded = (make: () => Scene | null): Prepared => ({ + planesFail: null, + make: () => { + try { + return make(); + } catch (e) { + options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); + return null; + } + }, + }); try { // Loaded here, with the scenes, so the main chunk does not carry the terrain sky or the baked tables. const { loadWeather, ridgeSkyFor, terrainSkyFor } = await import('./skyForState'); - if (config?.style === 'raymarch') return (await import('./Scene')).createScene(options); + if (config?.style === 'raymarch') { + const { createScene } = await import('./Scene'); + return guarded(() => createScene(options)); + } if (config?.style === 'terrain') { const { createTerrainScene } = await import('./terrain/Terrain'); - const sky = terrainSkyFor(state); - const scene = createTerrainScene({ ...options, ...sky }); - // No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground. - if (scene) return scene; const { createTerrainSkyScene } = await import('./terrain/TerrainSky2D'); - return createTerrainSkyScene({ ...options, ...sky }); + const sky = terrainSkyFor(state); + // No WebGL2 (or no usable GL): the terrain's sky alone on the same canvas, not bare ground. + return guarded( + () => + createTerrainScene({ ...options, ...sky }) ?? + createTerrainSkyScene({ ...options, ...sky }) + ); } const { createRidgeScene } = await import('./ridge/Ridge'); await loadWeather(weatherUrl()); // The planes load with the scene chunk and the weather: createRidgeScene stays synchronous. Any failure is the sky alone. let backdrop: Backdrop | null = null; let sky: SkyColours | undefined; + let planesFail: Error | null = null; try { const manifest = await loadManifest(import.meta.env.BASE_URL, config?.place); const manifestSky = ridgeSkyFor(state, undefined, undefined, manifest.view); @@ -63,16 +89,19 @@ async function create( } catch (e) { backdrop = null; sky = undefined; - onPlanesFail?.(e instanceof Error ? e : new Error(String(e))); + planesFail = e instanceof Error ? e : new Error(String(e)); } - return createRidgeScene({ - ...sceneOptions, - sky: sky ?? ridgeSkyFor(state), - backdrop: backdrop ?? undefined, - }); + const made = guarded(() => + createRidgeScene({ + ...options, + sky: sky ?? ridgeSkyFor(state), + backdrop: backdrop ?? undefined, + }) + ); + return { ...made, planesFail }; } catch (e) { options.onCompileFail?.(e instanceof Error ? e : new Error(String(e))); - return null; + return { make: () => null, planesFail: null }; } } @@ -117,19 +146,20 @@ export async function startBackgroundScene( const tier = resolveTier(config, capabilities); if (tier === 'off') return null; const debug = debugOverlaysAllowed(config); - // A failed load repeats on every rebuild; the host hears of it once. - let planesReported = false; - const onPlanesFail = (e: Error) => { - if (planesReported) return; - planesReported = true; - options.onPlanesFail?.(e); + // What the host was last told of the planes: only the live scene speaks, and only when its state changes. + let planesFailed = false; + const announce = (planesFail: Error | null) => { + if (planesFail && !planesFailed) options.onPlanesFail?.(planesFail); + if (!planesFail && planesFailed) options.onPlanesOk?.(); + planesFailed = planesFail !== null; }; - const build = (state: SkyState) => - create(config, { ...options, onPlanesFail, tier, debug }, state); + const prepared = (state: SkyState) => prepare(config, { ...options, tier, debug }, state); const state = getSkyState(); const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state); - const first = await build(state); + const firstReady = await prepared(state); + const first = firstReady.make(); if (!first || config?.style === 'raymarch') return first; + announce(firstReady.planesFail); let inner: Scene | null = first; let built = key0; @@ -146,14 +176,14 @@ export async function startBackgroundScene( generation += 1; const mine = generation; built = key; + // The old scene stays up while the next one loads; a build that is stale or after dispose is never made, so it never speaks. + const ready = await prepared(next); + if (disposed || mine !== generation) return; inner?.dispose(); inner = null; - const scene = await build(next); - if (disposed || mine !== generation) { - scene?.dispose(); - return; - } + const scene = ready.make(); inner = scene; + if (scene) announce(ready.planesFail); if (!scene) options.onInactive?.(); else { options.onActive?.();