ridge: load baked planes by manifest and compose them over the live sky; failure is the sky-only scene
createRidgeScene takes a decoded Backdrop and adds one rig (far, mid, near) with transform-only drift; index.ts create() loads manifest, frame choice and planes with the scene chunk; BackgroundSceneConfig.place; vite copies public/ridge. Tests also cover resize debounce, listener removal and the window-size fallback. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
parent
1b2689dce9
commit
5a6d712b0d
11 changed files with 571 additions and 30 deletions
|
|
@ -7,8 +7,8 @@ means "keep the CSS ground". Everything below this section describes the opt-in
|
|||
- `ridge/Ridge.ts` `createRidgeScene({ canvas, tier, probe?, onProbe?, sky? })` 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`) and, when it rains, tiled rain streaks slid down on the compositor (`ridge/rain.ts`). There is no skyline: 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 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.
|
||||
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,6 +18,15 @@ 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` `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
|
||||
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`.
|
||||
`vite.config.js` copies `public/ridge` into `dist/public/`.
|
||||
- `harness/scene/bundle.cjs <out> ridge` builds a standalone page (`?tier=`, `?probe=1`).
|
||||
- Not yet measured on a phone: see the PR description.
|
||||
|
||||
|
|
|
|||
|
|
@ -4,6 +4,9 @@ import type { Scene } from './Scene';
|
|||
import { startBackgroundScene } from './index';
|
||||
import { setSkyClock, setSkyState } from './skyState';
|
||||
import { ridgeSkyFor } from './skyForState';
|
||||
import { forgetManifests } from './ridge/manifest';
|
||||
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
|
||||
import { FALLBACK_VIEW } from './ridge/view';
|
||||
|
||||
const { createRidgeScene, createScene } = vi.hoisted(() => ({
|
||||
createRidgeScene: vi.fn(),
|
||||
|
|
@ -254,3 +257,124 @@ describe('startBackgroundScene follows the sky state', () => {
|
|||
expect(onCompileFail).toHaveBeenCalledWith(boom);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the ridge planes', () => {
|
||||
const served = (over: Record<string, unknown> = {}) => {
|
||||
const files: Record<string, unknown> = {
|
||||
'/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 () => ({}) }
|
||||
)
|
||||
);
|
||||
};
|
||||
const images = (reject = false) => {
|
||||
const loaded: string[] = [];
|
||||
vi.stubGlobal(
|
||||
'Image',
|
||||
class {
|
||||
src = '';
|
||||
decoding = '';
|
||||
cloneNode = () => this;
|
||||
decode = async () => {
|
||||
if (reject) throw new Error('bad image');
|
||||
loaded.push(this.src);
|
||||
};
|
||||
}
|
||||
);
|
||||
return loaded;
|
||||
};
|
||||
beforeEach(() => forgetManifests());
|
||||
|
||||
it('hands the scene the planes of the frame the sky was baked for, over the manifest view', async () => {
|
||||
served();
|
||||
const loaded = images();
|
||||
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);
|
||||
// Midnight in Vienna: the night frame, three planes.
|
||||
expect(loaded.sort()).toEqual([
|
||||
'/public/ridge/vienna-abc123abc123/night-far.webp',
|
||||
'/public/ridge/vienna-abc123abc123/night-mid.webp',
|
||||
'/public/ridge/vienna-abc123abc123/night-near.webp',
|
||||
]);
|
||||
scene?.dispose();
|
||||
});
|
||||
|
||||
it('config place picks the index entry; an unknown id falls back to the default', async () => {
|
||||
served();
|
||||
images();
|
||||
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 () => ({}) }))
|
||||
);
|
||||
images();
|
||||
await skyOnly();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the ridge planes failing', () => {
|
||||
it('a rejecting image 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()),
|
||||
}))
|
||||
);
|
||||
vi.stubGlobal(
|
||||
'Image',
|
||||
class {
|
||||
decode = async () => {
|
||||
throw new Error('bad image');
|
||||
};
|
||||
}
|
||||
);
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -3,6 +3,10 @@ import { BackgroundSceneConfig, Capabilities, SceneTier, resolveTier } from './t
|
|||
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 { frameChoice } from './ridge/frameChoice';
|
||||
|
||||
export type { Scene, SceneStats } from './Scene';
|
||||
export type { SceneStyle, SceneTier } from './tier';
|
||||
|
|
@ -14,6 +18,8 @@ export type StartOptions = Omit<SceneOptions, 'tier' | 'patchSource' | 'onCompil
|
|||
onInactive?: () => 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. */
|
||||
onPlanesFail?: (e: Error) => void;
|
||||
};
|
||||
|
||||
/** The observation file the ridge sky reads: the page's own, beside config.json. The browser calls no weather service. */
|
||||
|
|
@ -24,6 +30,7 @@ async function create(
|
|||
options: StartOptions & { tier: SceneTier; debug?: boolean },
|
||||
state: SkyState
|
||||
): Promise<Scene | null> {
|
||||
const { onPlanesFail, ...sceneOptions } = options;
|
||||
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');
|
||||
|
|
@ -39,7 +46,30 @@ async function create(
|
|||
}
|
||||
const { createRidgeScene } = await import('./ridge/Ridge');
|
||||
await loadWeather(weatherUrl());
|
||||
return createRidgeScene({ ...options, sky: ridgeSkyFor(state) });
|
||||
// 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;
|
||||
try {
|
||||
const manifest = await loadManifest(import.meta.env.BASE_URL, config?.place);
|
||||
const manifestSky = ridgeSkyFor(state, undefined, undefined, manifest.view);
|
||||
sky = manifestSky;
|
||||
const choice = frameChoice(
|
||||
manifest.frames,
|
||||
(manifestSky.physical as NonNullable<typeof manifestSky.physical>).sun
|
||||
);
|
||||
const { loadBackdrop } = await import('./ridge/Backdrop');
|
||||
backdrop = await loadBackdrop(manifest, choice);
|
||||
if (!backdrop) throw new Error('ridge planes did not load');
|
||||
} catch (e) {
|
||||
backdrop = null;
|
||||
sky = undefined;
|
||||
onPlanesFail?.(e instanceof Error ? e : new Error(String(e)));
|
||||
}
|
||||
return createRidgeScene({
|
||||
...sceneOptions,
|
||||
sky: sky ?? ridgeSkyFor(state),
|
||||
backdrop: backdrop ?? undefined,
|
||||
});
|
||||
} catch (e) {
|
||||
options.onCompileFail?.(e instanceof Error ? e : new Error(String(e)));
|
||||
return null;
|
||||
|
|
@ -87,7 +117,15 @@ export async function startBackgroundScene(
|
|||
const tier = resolveTier(config, capabilities);
|
||||
if (tier === 'off') return null;
|
||||
const debug = debugOverlaysAllowed(config);
|
||||
const build = (state: SkyState) => create(config, { ...options, tier, debug }, state);
|
||||
// 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);
|
||||
};
|
||||
const build = (state: SkyState) =>
|
||||
create(config, { ...options, onPlanesFail, tier, debug }, state);
|
||||
const state = getSkyState();
|
||||
const key0 = config?.style === 'raymarch' ? null : await skyKey(config, state);
|
||||
const first = await build(state);
|
||||
|
|
|
|||
|
|
@ -5,16 +5,28 @@ import { parseManifest } from './manifest';
|
|||
import { wireManifest } from './manifest.fixture';
|
||||
|
||||
const manifest = parseManifest(wireManifest(), '/d/');
|
||||
const img = (src: string) => ({ src }) as unknown as HTMLImageElement;
|
||||
const img = (src: string) => ({ src } as unknown as HTMLImageElement);
|
||||
|
||||
describe('loadBackdrop', () => {
|
||||
it('loads the planes of the needed frames only, by manifest directory', async () => {
|
||||
const load = vi.fn(async (u: string) => img(u));
|
||||
const one = await loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load);
|
||||
expect(load.mock.calls.map((c) => c[0]).sort()).toEqual(['/d/noon-far.webp', '/d/noon-mid.webp', '/d/noon-near.webp']);
|
||||
const one = await loadBackdrop(
|
||||
manifest,
|
||||
frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }),
|
||||
load
|
||||
);
|
||||
expect(load.mock.calls.map((c) => c[0]).sort()).toEqual([
|
||||
'/d/noon-far.webp',
|
||||
'/d/noon-mid.webp',
|
||||
'/d/noon-near.webp',
|
||||
]);
|
||||
expect(one?.b).toBeNull();
|
||||
load.mockClear();
|
||||
const two = await loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 10, azimuth: 130 }), load);
|
||||
const two = await loadBackdrop(
|
||||
manifest,
|
||||
frameChoice(manifest.frames, { elevation: 10, azimuth: 130 }),
|
||||
load
|
||||
);
|
||||
expect(load).toHaveBeenCalledTimes(6);
|
||||
expect(two?.b?.far.src).toBe('/d/morning-far.webp');
|
||||
expect(two?.a.near.src).toBe('/d/dawn-near.webp');
|
||||
|
|
@ -25,6 +37,8 @@ describe('loadBackdrop', () => {
|
|||
if (u.includes('mid')) throw new Error('decode');
|
||||
return img(u);
|
||||
});
|
||||
await expect(loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load)).resolves.toBeNull();
|
||||
await expect(
|
||||
loadBackdrop(manifest, frameChoice(manifest.frames, { elevation: 60, azimuth: 180 }), load)
|
||||
).resolves.toBeNull();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,11 @@ import type { SkyColours } from './skyColour';
|
|||
import { makeStars } from './stars';
|
||||
import { makePhysicalSky } from './physicalSky';
|
||||
import { startBackgroundScene } from '../index';
|
||||
import { frameChoice } from './frameChoice';
|
||||
import { parseManifest } from './manifest';
|
||||
import { wireManifest } from './manifest.fixture';
|
||||
import type { Backdrop } from './Backdrop';
|
||||
import { windowFor } from './view';
|
||||
|
||||
describe('noise', () => {
|
||||
it('is deterministic and in [0, 1)', () => {
|
||||
|
|
@ -132,6 +137,7 @@ const DAY: SkyColours = {
|
|||
horizon: [240, 215, 190],
|
||||
};
|
||||
const draws: string[] = [];
|
||||
const images: unknown[][] = [];
|
||||
function ctx() {
|
||||
const c: any = {
|
||||
createLinearGradient: () => ({ addColorStop: vi.fn() }),
|
||||
|
|
@ -167,7 +173,10 @@ function ctx() {
|
|||
if (c.arcing) c.arcing = false;
|
||||
else draws.push('fill');
|
||||
},
|
||||
drawImage() {},
|
||||
drawImage(...a: unknown[]) {
|
||||
images.push(a);
|
||||
},
|
||||
globalAlpha: 1,
|
||||
set fillStyle(_v: unknown) {},
|
||||
};
|
||||
return c;
|
||||
|
|
@ -181,6 +190,7 @@ let search: string;
|
|||
beforeEach(() => {
|
||||
rafQueue = [];
|
||||
draws.length = 0;
|
||||
images.length = 0;
|
||||
search = '';
|
||||
motion = { matches: false, addEventListener: vi.fn(), removeEventListener: vi.fn() };
|
||||
doc = Object.assign(new EventTarget(), {
|
||||
|
|
@ -321,7 +331,6 @@ describe('createRidgeScene', () => {
|
|||
});
|
||||
});
|
||||
|
||||
|
||||
describe('the door', () => {
|
||||
it('runs the ridge scene by default and never requests a WebGL context', async () => {
|
||||
const { canvas } = host();
|
||||
|
|
@ -499,3 +508,188 @@ describe('rain in the scene', () => {
|
|||
s.dispose();
|
||||
});
|
||||
});
|
||||
|
||||
describe('the ridge planes in the scene', () => {
|
||||
const manifest = parseManifest(wireManifest(), '/d/');
|
||||
const fakeImg = (src: string) => {
|
||||
const el = fakeEl('img');
|
||||
el.src = src;
|
||||
el.cloneNode = () => fakeImg(src);
|
||||
return el as unknown as HTMLImageElement;
|
||||
};
|
||||
const planes = (k: string) => ({
|
||||
far: fakeImg(`${k}-far`),
|
||||
mid: fakeImg(`${k}-mid`),
|
||||
near: fakeImg(`${k}-near`),
|
||||
});
|
||||
const backdropAt = (elevation: number, azimuth: number): Backdrop => {
|
||||
const choice = frameChoice(manifest.frames, { elevation, azimuth });
|
||||
return { manifest, choice, a: planes(choice.a.key), b: choice.b ? planes(choice.b.key) : null };
|
||||
};
|
||||
const NOON = backdropAt(60, 180);
|
||||
const BLEND = backdropAt(10, 130);
|
||||
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),
|
||||
};
|
||||
const rigOf = (parent: any) =>
|
||||
parent.children.find((c: any) => c.children.some((g: any) => g.anims.length));
|
||||
|
||||
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: NOON })!;
|
||||
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 three groups, far to near, each placed by windowFor and drifting by its depth of driftPx', () => {
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON })!;
|
||||
const rig = rigOf(parent);
|
||||
const win = windowFor(manifest.view, 400, 800);
|
||||
expect(rig.children).toHaveLength(3);
|
||||
rig.children.forEach((g: any, k: number) => {
|
||||
expect(g.style.width).toBe(`${win.plane.w}px`);
|
||||
expect(g.style.height).toBe(`${win.plane.h}px`);
|
||||
expect(g.style.bottom).toBe('0px');
|
||||
expect(g.style.left).toBe(`${(400 - win.plane.w) / 2}px`);
|
||||
expect(g.children.map((i: any) => i.src)).toEqual([`noon-${['far', 'mid', 'near'][k]}`]);
|
||||
const { keyframes, options } = g.anims[0];
|
||||
const reach = win.driftPx * [0.35, 0.7, 1][k];
|
||||
expect(keyframes).toEqual([
|
||||
{ transform: `translate3d(${-reach}px,0,0)` },
|
||||
{ transform: `translate3d(${reach}px,0,0)` },
|
||||
]);
|
||||
expect(options).toMatchObject({
|
||||
duration: 75000,
|
||||
iterations: Infinity,
|
||||
direction: 'alternate',
|
||||
easing: 'ease-in-out',
|
||||
});
|
||||
});
|
||||
s.dispose();
|
||||
});
|
||||
|
||||
it('lays frame b over frame a at the blend weight', () => {
|
||||
const { parent, canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: BLEND })!;
|
||||
const g = rigOf(parent).children[1];
|
||||
expect(g.children.map((i: any) => [i.src, i.style.opacity])).toEqual([
|
||||
['dawn-mid', '1'],
|
||||
['morning-mid', String(BLEND.choice.w)],
|
||||
]);
|
||||
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: NOON })!;
|
||||
expect(rafQueue).toHaveLength(1); // the frame sampler, as without planes
|
||||
s.dispose();
|
||||
const bare = host();
|
||||
const b = createRidgeScene({ canvas: bare.canvas, tier: 'full', sky: DAY })!;
|
||||
expect(rafQueue).toHaveLength(1);
|
||||
b.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: NOON })!;
|
||||
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 the planes into the host canvas at windowFor's placement and leaves no animation", () => {
|
||||
const { parent, canvas } = host();
|
||||
createRidgeScene({ canvas, tier: 'still', sky: DAY, backdrop: BLEND });
|
||||
const win = windowFor(manifest.view, 400, 800);
|
||||
const planesDrawn = images.filter((a) => (a[0] as any).src);
|
||||
expect(planesDrawn).toHaveLength(6);
|
||||
expect(planesDrawn.map((a) => (a[0] as any).src)).toEqual([
|
||||
'dawn-far',
|
||||
'morning-far',
|
||||
'dawn-mid',
|
||||
'morning-mid',
|
||||
'dawn-near',
|
||||
'morning-near',
|
||||
]);
|
||||
const [, x, y, w, h] = planesDrawn[0] as number[];
|
||||
expect([x, y, w, h]).toEqual([
|
||||
(800 - win.plane.w * 2) / 2,
|
||||
1600 - win.plane.h * 2,
|
||||
win.plane.w * 2,
|
||||
win.plane.h * 2,
|
||||
]);
|
||||
expect(parent.children).toEqual([canvas]);
|
||||
});
|
||||
|
||||
it('settles to a still with the planes painted when the frame rate is poor', () => {
|
||||
const { parent, canvas } = host();
|
||||
createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: NOON });
|
||||
runFrames(100, 400);
|
||||
expect(images.filter((a) => (a[0] as any).src)).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).src)).toHaveLength(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('the scene wiring', () => {
|
||||
it('sizes from the window when the canvas has no client size', () => {
|
||||
const { canvas } = host();
|
||||
canvas.clientWidth = 0;
|
||||
canvas.clientHeight = 0;
|
||||
(window as any).innerWidth = 300;
|
||||
(window as any).innerHeight = 500;
|
||||
createRidgeScene({ canvas, tier: 'full', sky: DAY })!.dispose();
|
||||
expect([canvas.width, canvas.height]).toEqual([600, 1000]);
|
||||
});
|
||||
|
||||
it('a burst of resizes rebuilds once, after 250 ms, and not after dispose', async () => {
|
||||
vi.useFakeTimers();
|
||||
(window as any).setTimeout = setTimeout;
|
||||
const { canvas } = host();
|
||||
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY })!;
|
||||
const skies = () => draws.filter((d) => d === 'sky').length;
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
vi.advanceTimersByTime(200);
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
vi.advanceTimersByTime(200);
|
||||
expect(skies()).toBe(1);
|
||||
vi.advanceTimersByTime(60);
|
||||
expect(skies()).toBe(2);
|
||||
s.dispose();
|
||||
window.dispatchEvent(new Event('resize'));
|
||||
vi.advanceTimersByTime(1000);
|
||||
expect(skies()).toBe(2);
|
||||
vi.useRealTimers();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -6,6 +6,8 @@ import { paintSky as paintPhysicalSky } from './physicalSky';
|
|||
import { windowFor } from './view';
|
||||
import { activeAt, drawStars, drawTwinkle as paintTwinkle, makeStars, Star } from './stars';
|
||||
import { drawRainTile, RAIN_TILES } from './rain';
|
||||
import type { Backdrop, Planes } from './Backdrop';
|
||||
import { PLANE_NAMES } from './manifest';
|
||||
|
||||
export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
||||
/** Show the rAF median/p95 readout. Default: the page URL has `?probe=1`, where `debug` allows it. */
|
||||
|
|
@ -16,6 +18,8 @@ export type RidgeOptions = Pick<SceneOptions, 'canvas' | 'tier'> & {
|
|||
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 planes, already decoded; 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 +96,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 planes' rig, over the twinkle canvas and under the rain; absent in 'still' (the planes 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,9 +105,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;
|
||||
|
||||
/** Far, mid and near slide this share of the drift room (`windowFor` driftPx); one leg of the back-and-forth takes DRIFT_LEG_S, so the loop is 150 s. Authored, tunable by eye. */
|
||||
const DRIFT_DEPTH = [0.35, 0.7, 1] as const;
|
||||
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, with no skyline. The host canvas holds the baked sky; it and
|
||||
* ground"), no WebGL. It draws the sky, the stars, the baked ridge planes when given a `backdrop` (none: the sky alone) and the rain. 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 {
|
||||
|
|
@ -133,6 +143,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);
|
||||
|
|
@ -196,6 +208,91 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
|||
return { els, anims };
|
||||
};
|
||||
|
||||
/**
|
||||
* The ridge over the sky: one div holding a group per plane (far, mid, near: DOM order is paint order, stacking is by order alone), each the frame's
|
||||
* image and, when the choice blends two frames, the second over it at the blend weight. A group slides sideways on the compositor by
|
||||
* `driftPx` times its depth; the baker's pixels are never touched.
|
||||
*/
|
||||
const startRig = (bd: Backdrop, w: number, h: number): NonNullable<Built['rig']> => {
|
||||
const win = windowFor(bd.manifest.view, w, h);
|
||||
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)[] = [];
|
||||
PLANE_NAMES.forEach((name, k) => {
|
||||
const group = document.createElement('div');
|
||||
Object.assign(group.style, {
|
||||
position: 'absolute',
|
||||
left: `${(w - win.plane.w) / 2}px`,
|
||||
bottom: `${win.plane.bottom}px`,
|
||||
width: `${win.plane.w}px`,
|
||||
height: `${win.plane.h}px`,
|
||||
willChange: 'transform',
|
||||
});
|
||||
const layer = (planes: Planes, opacity: number) => {
|
||||
const img = planes[name].cloneNode() as HTMLImageElement;
|
||||
Object.assign(img.style, {
|
||||
position: 'absolute',
|
||||
left: '0',
|
||||
top: '0',
|
||||
width: '100%',
|
||||
height: '100%',
|
||||
opacity: String(opacity),
|
||||
});
|
||||
group.appendChild(img);
|
||||
};
|
||||
layer(bd.a, 1);
|
||||
if (bd.b) layer(bd.b, bd.choice.w);
|
||||
el.appendChild(group);
|
||||
const reach = win.driftPx * DRIFT_DEPTH[k];
|
||||
anims.push(
|
||||
group.animate?.(
|
||||
[
|
||||
{ transform: `translate3d(${-reach}px,0,0)` },
|
||||
{ transform: `translate3d(${reach}px,0,0)` },
|
||||
],
|
||||
{
|
||||
duration: DRIFT_LEG_S * 1000,
|
||||
iterations: Infinity,
|
||||
direction: 'alternate',
|
||||
easing: 'ease-in-out',
|
||||
}
|
||||
)
|
||||
);
|
||||
});
|
||||
parent.appendChild(el);
|
||||
return { el, anims };
|
||||
};
|
||||
|
||||
/** Paint the ridge planes into the host canvas, a over b, far to near: the still scene's one image. */
|
||||
const paintPlanes = (bd: Backdrop) => {
|
||||
const ctx = context2d(canvas);
|
||||
if (!ctx) return;
|
||||
const { w, h, scale } = viewSize();
|
||||
const win = windowFor(bd.manifest.view, w, h);
|
||||
const dw = win.plane.w * scale;
|
||||
const dh = win.plane.h * scale;
|
||||
const x = (canvas.width - dw) / 2;
|
||||
const y = canvas.height - dh - win.plane.bottom * scale;
|
||||
PLANE_NAMES.forEach((name) => {
|
||||
ctx.globalAlpha = 1;
|
||||
ctx.drawImage(bd.a[name], x, y, dw, dh);
|
||||
if (bd.b) {
|
||||
ctx.globalAlpha = bd.choice.w;
|
||||
ctx.drawImage(bd.b[name], x, y, dw, dh);
|
||||
}
|
||||
});
|
||||
ctx.globalAlpha = 1;
|
||||
};
|
||||
|
||||
/** 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();
|
||||
|
|
@ -228,6 +325,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();
|
||||
|
|
@ -262,7 +360,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()) {
|
||||
|
|
@ -281,6 +379,7 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
|
|||
teardown();
|
||||
cancelAnimationFrame(raf);
|
||||
raf = 0;
|
||||
if (opts.backdrop) paintPlanes(opts.backdrop);
|
||||
report(true);
|
||||
};
|
||||
|
||||
|
|
|
|||
|
|
@ -45,13 +45,14 @@ describe('frameChoice', () => {
|
|||
it('collapses a blend within 2% of either end to one frame, and w stays in 0..1', () => {
|
||||
expect(keys(at(0.2, 130))).toEqual(['dawn', null]); // w = 0.01
|
||||
expect(keys(at(19.8, 130))).toEqual(['morning', null]); // w = 0.99
|
||||
for (let el = -30; el <= 90; el += 0.37) {
|
||||
for (const az of [0, 100, 179, 181, 270]) {
|
||||
const els = Array.from({ length: 325 }, (_, i) => -30 + i * 0.37);
|
||||
els.forEach((el) =>
|
||||
[0, 100, 179, 181, 270].forEach((az) => {
|
||||
const c = at(el, az);
|
||||
expect(c.w).toBeGreaterThanOrEqual(0);
|
||||
expect(c.w).toBeLessThanOrEqual(1);
|
||||
expect(c.b === null).toBe(c.w === 0);
|
||||
}
|
||||
}
|
||||
})
|
||||
);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,7 +1,7 @@
|
|||
// A hand-written manifest v1 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder.
|
||||
import { FRAME_KEYS } from './manifest';
|
||||
|
||||
const SUN: Record<(typeof FRAME_KEYS)[number], [number, number]> = {
|
||||
const SUN: Record<typeof FRAME_KEYS[number], [number, number]> = {
|
||||
dawn: [100, 0],
|
||||
morning: [130, 20],
|
||||
noon: [180, 60],
|
||||
|
|
@ -14,20 +14,51 @@ export const wireManifest = (over: Record<string, unknown> = {}): Record<string,
|
|||
schema: 1,
|
||||
baker_version: 1,
|
||||
bake_id: 'abc123abc123',
|
||||
place: { id: 'vienna', name: 'Vienna', lat: 48.19, lon: 16.35, altitude_km: 0.183, tz_h: 1, tz_name: 'CET', date: '2026-06-21' },
|
||||
view: { look_az_deg: 214, window_deg: 72, plane_w: 1280, plane_h: 600, px_per_deg_h: 1280 / 72, px_per_deg_v: 17.7, horizon_row: 314.5, sky_row: 0, near_row: 599 },
|
||||
place: {
|
||||
id: 'vienna',
|
||||
name: 'Vienna',
|
||||
lat: 48.19,
|
||||
lon: 16.35,
|
||||
altitude_km: 0.183,
|
||||
tz_h: 1,
|
||||
tz_name: 'CET',
|
||||
date: '2026-06-21',
|
||||
},
|
||||
view: {
|
||||
look_az_deg: 214,
|
||||
window_deg: 72,
|
||||
plane_w: 1280,
|
||||
plane_h: 600,
|
||||
px_per_deg_h: 1280 / 72,
|
||||
px_per_deg_v: 17.7,
|
||||
horizon_row: 314.5,
|
||||
sky_row: 0,
|
||||
near_row: 599,
|
||||
},
|
||||
frames: FRAME_KEYS.map((key) => ({
|
||||
key,
|
||||
sun: { az: SUN[key][0], el: SUN[key][1] },
|
||||
hour_utc: 0,
|
||||
planes: Object.fromEntries(
|
||||
['far', 'mid', 'near'].map((n) => [n, { file: `${key}-${n}.webp`, bytes: 1, w: 1280, h: 600 }])
|
||||
['far', 'mid', 'near'].map((n) => [
|
||||
n,
|
||||
{ file: `${key}-${n}.webp`, bytes: 1, w: 1280, h: 600 },
|
||||
])
|
||||
),
|
||||
bytes: 3,
|
||||
luma: { min: 0.1, max: 0.5 },
|
||||
})),
|
||||
attribution: { credit_line: 'credit', licence: 'licence', dem_source: 'dem', url: 'https://example.test' },
|
||||
attribution: {
|
||||
credit_line: 'credit',
|
||||
licence: 'licence',
|
||||
dem_source: 'dem',
|
||||
url: 'https://example.test',
|
||||
},
|
||||
...over,
|
||||
});
|
||||
|
||||
export const wireIndex = { schema: 1, default: 'vienna', places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' } };
|
||||
export const wireIndex = {
|
||||
schema: 1,
|
||||
default: 'vienna',
|
||||
places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' },
|
||||
};
|
||||
|
|
|
|||
|
|
@ -6,10 +6,26 @@ describe('parseManifest', () => {
|
|||
it('reads a v1 manifest into the View the sky and planes share', () => {
|
||||
const m = parseManifest(wireManifest(), '/public/ridge/v/');
|
||||
expect(m.dir).toBe('/public/ridge/v/');
|
||||
expect(m.view).toMatchObject({ lookAzDeg: 214, windowDeg: 72, planeW: 1280, planeH: 600, horizonRow: 314.5 });
|
||||
expect(m.view).toMatchObject({
|
||||
lookAzDeg: 214,
|
||||
windowDeg: 72,
|
||||
planeW: 1280,
|
||||
planeH: 600,
|
||||
horizonRow: 314.5,
|
||||
});
|
||||
expect(m.view.place).toEqual({ id: 'vienna', lat: 48.19, lon: 16.35, altitudeKm: 0.183 });
|
||||
expect(m.frames.map((f) => f.key)).toEqual(['dawn', 'morning', 'noon', 'golden', 'dusk', 'night']);
|
||||
expect(m.frames[2]).toMatchObject({ sun: { az: 180, el: 60 }, planes: { far: 'noon-far.webp', near: 'noon-near.webp' } });
|
||||
expect(m.frames.map((f) => f.key)).toEqual([
|
||||
'dawn',
|
||||
'morning',
|
||||
'noon',
|
||||
'golden',
|
||||
'dusk',
|
||||
'night',
|
||||
]);
|
||||
expect(m.frames[2]).toMatchObject({
|
||||
sun: { az: 180, el: 60 },
|
||||
planes: { far: 'noon-far.webp', near: 'noon-near.webp' },
|
||||
});
|
||||
expect(m.attribution.creditLine).toBe('credit');
|
||||
});
|
||||
|
||||
|
|
@ -19,14 +35,18 @@ describe('parseManifest', () => {
|
|||
expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/schema/);
|
||||
expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/);
|
||||
expect(() => parseManifest({ ...w, frames: w.frames.slice(1) }, '/')).toThrow(/frames/);
|
||||
expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow(/horizon_row/);
|
||||
expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow(
|
||||
/horizon_row/
|
||||
);
|
||||
expect(() => parseManifest(null, '/')).toThrow();
|
||||
});
|
||||
});
|
||||
|
||||
const serve = (files: Record<string, unknown>) => {
|
||||
const f = vi.fn(async (url: string) =>
|
||||
url in files ? { ok: true, status: 200, json: async () => files[url] } : { ok: false, status: 404, json: async () => ({}) }
|
||||
url in files
|
||||
? { ok: true, status: 200, json: async () => files[url] }
|
||||
: { ok: false, status: 404, json: async () => ({}) }
|
||||
);
|
||||
vi.stubGlobal('fetch', f);
|
||||
return f;
|
||||
|
|
@ -34,7 +54,9 @@ const serve = (files: Record<string, unknown>) => {
|
|||
const files = () => ({
|
||||
'/b/public/ridge/index.json': wireIndex,
|
||||
'/b/public/ridge/vienna-abc123abc123/manifest.json': wireManifest(),
|
||||
'/b/public/ridge/graz-def456def456/manifest.json': wireManifest({ place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' } }),
|
||||
'/b/public/ridge/graz-def456def456/manifest.json': wireManifest({
|
||||
place: { ...(wireManifest() as any).place, id: 'graz', name: 'Graz' },
|
||||
}),
|
||||
});
|
||||
|
||||
describe('loadManifest', () => {
|
||||
|
|
@ -48,7 +70,10 @@ describe('loadManifest', () => {
|
|||
const m = await loadManifest('/b/');
|
||||
expect(m.view.place.id).toBe('vienna');
|
||||
expect(m.dir).toBe('/b/public/ridge/vienna-abc123abc123/');
|
||||
expect(f.mock.calls.map((c) => c[0])).toEqual(['/b/public/ridge/index.json', '/b/public/ridge/vienna-abc123abc123/manifest.json']);
|
||||
expect(f.mock.calls.map((c) => c[0])).toEqual([
|
||||
'/b/public/ridge/index.json',
|
||||
'/b/public/ridge/vienna-abc123abc123/manifest.json',
|
||||
]);
|
||||
});
|
||||
|
||||
it('place picks the index entry; an unknown id falls back to the default', async () => {
|
||||
|
|
|
|||
|
|
@ -24,6 +24,8 @@ export type SceneStyle = 'ridge' | 'raymarch' | 'terrain';
|
|||
export interface BackgroundSceneConfig {
|
||||
tier?: SceneTier;
|
||||
style?: SceneStyle;
|
||||
/** The baked ridge place to show (a key of the ridge index); unknown or absent: the index's default. */
|
||||
place?: string;
|
||||
/** Let the page URL switch on the diagnostic overlays (`?probe=1`, `?tierlabel=1`) in a production build. Default: no. */
|
||||
debugOverlays?: boolean;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -51,6 +51,10 @@ const copyFiles = {
|
|||
src: 'public/dings',
|
||||
dest: 'public/',
|
||||
},
|
||||
{
|
||||
src: 'public/ridge',
|
||||
dest: 'public/',
|
||||
},
|
||||
],
|
||||
};
|
||||
|
||||
|
|
|
|||
Loading…
Reference in a new issue