diff --git a/src/app/features/scene/cameraState.test.ts b/src/app/features/scene/cameraState.test.ts new file mode 100644 index 00000000..6634cef7 --- /dev/null +++ b/src/app/features/scene/cameraState.test.ts @@ -0,0 +1,80 @@ +import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; +import { + CAMERA_KEY, + DEFAULT_CAMERA, + getCamera, + parseCamera, + resetCamera, + setCamera, + subscribe, +} from './cameraState'; + +const store = new Map(); +const reduced = { matches: false }; + +beforeEach(() => { + store.clear(); + reduced.matches = false; + resetCamera(); + vi.stubGlobal('localStorage', { + getItem: (k: string) => store.get(k) ?? null, + setItem: (k: string, v: string) => void store.set(k, v), + }); + vi.stubGlobal('window', { matchMedia: () => reduced }); +}); +afterEach(() => vi.unstubAllGlobals()); + +describe('the viewer camera', () => { + it('starts at the defaults: both, a turn in ten minutes, 200 m forward', () => { + expect(getCamera()).toEqual({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + expect(DEFAULT_CAMERA).toEqual(getCamera()); + }); + + it('starts still under reduced motion, and a stored choice outranks that', () => { + reduced.matches = true; + expect(getCamera().mode).toBe('still'); + resetCamera(); + store.set(CAMERA_KEY, JSON.stringify({ mode: 'offset', speedDegPerS: 1, offsetM: -30 })); + expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 1, offsetM: -30 }); + }); + + it('keeps each change per viewer, and tells listeners only of a change', () => { + const cb = vi.fn(); + subscribe(cb); + setCamera({ offsetM: 50 }); + expect(JSON.parse(store.get(CAMERA_KEY) as string)).toEqual({ ...DEFAULT_CAMERA, offsetM: 50 }); + setCamera({ offsetM: 50 }); + setCamera({ mode: 'both' }); + expect(cb).toHaveBeenCalledTimes(1); + setCamera({ mode: 'offset', speedDegPerS: 2 }); + expect(cb).toHaveBeenCalledTimes(2); + expect(getCamera()).toEqual({ mode: 'offset', speedDegPerS: 2, offsetM: 50 }); + }); + + it('ignores a stored value that is not a choice, and a change that is not one', () => { + store.set(CAMERA_KEY, '{"mode":"spin","speedDegPerS":1,"offsetM":0}'); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + store.set(CAMERA_KEY, 'not json'); + resetCamera(); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + setCamera({ speedDegPerS: Number.NaN }); + setCamera({ mode: 'spin' as never }); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + expect(parseCamera({ mode: 'still', speedDegPerS: Infinity, offsetM: 0 })).toBeUndefined(); + }); + + it('holds the choice for the page load when storage refuses', () => { + vi.stubGlobal('localStorage', { + getItem: () => { + throw new Error('blocked'); + }, + setItem: () => { + throw new Error('blocked'); + }, + }); + resetCamera(); + expect(getCamera()).toEqual(DEFAULT_CAMERA); + setCamera({ offsetM: -10 }); + expect(getCamera().offsetM).toBe(-10); + }); +}); diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts new file mode 100644 index 00000000..74a62dec --- /dev/null +++ b/src/app/features/scene/cameraState.ts @@ -0,0 +1,91 @@ +// How the viewer wants the ridge camera to move: the rotation mode, the speed and the parallax offset, per viewer in localStorage. Intent only: the +// kinematics are `ridge/heading.ts`, the one clamp on the offset is `ridge/view.ts` `offsetRange`, and a scene applies this to both. Main-chunk safe +// (no ridge code is imported at runtime), as placeState and skyState are. +import type { RotationMode } from './ridge/heading'; + +export const CAMERA_KEY = 'ratatoskr.camera'; + +export interface CameraChoice { + mode: RotationMode; + /** Degrees per second the view (or the camera on its circle) turns at. */ + speedDegPerS: number; + /** The camera's offset from the bake centre in metres, forward positive; a scene clamps it to the place's range. */ + offsetM: number; +} + +/** + * What a first visit sees (question ridge-view-defaults, provisional): a turn in ten minutes with the camera 200 m forward, view direction and camera + * together (ruling ridge-scene-view-fullscreen). A visit that asks for reduced motion starts with nothing turning. + */ +export const DEFAULT_CAMERA: CameraChoice = { mode: 'both', speedDegPerS: 0.6, offsetM: 200 }; + +const MODES: readonly RotationMode[] = ['still', 'offset', 'both']; + +/** A stored value as a choice, or undefined when it is not one (an unknown mode, a speed or offset that is not a finite number). */ +export function parseCamera(raw: unknown): CameraChoice | undefined { + if (typeof raw !== 'object' || raw === null) return undefined; + const c = raw as Record; + if ( + !MODES.includes(c.mode as RotationMode) || + typeof c.speedDegPerS !== 'number' || + !Number.isFinite(c.speedDegPerS) || + typeof c.offsetM !== 'number' || + !Number.isFinite(c.offsetM) + ) { + return undefined; + } + return { mode: c.mode as RotationMode, speedDegPerS: c.speedDegPerS, offsetM: c.offsetM }; +} + +const reducedMotion = (): boolean => { + try { + return window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches === true; + } catch { + return false; + } +}; + +let current: CameraChoice | undefined; +const listeners = new Set<(c: CameraChoice) => void>(); + +function load(): CameraChoice { + try { + const stored = localStorage.getItem(CAMERA_KEY); + const parsed = stored === null ? undefined : parseCamera(JSON.parse(stored)); + if (parsed) return parsed; + } catch { + // Storage is unreadable (private mode, bad JSON): the defaults hold for this page load. + } + return reducedMotion() ? { ...DEFAULT_CAMERA, mode: 'still' } : { ...DEFAULT_CAMERA }; +} + +export const getCamera = (): CameraChoice => { + current ??= load(); + return current; +}; + +/** Change any of the three; listeners hear it only when something moved. */ +export function setCamera(change: Partial): void { + const next = parseCamera({ ...getCamera(), ...change }); + if (!next) return; + const prev = getCamera(); + if (next.mode === prev.mode && next.speedDegPerS === prev.speedDegPerS && next.offsetM === prev.offsetM) return; + current = next; + try { + localStorage.setItem(CAMERA_KEY, JSON.stringify(next)); + } catch { + // Storage is refused: the choice holds for this page load only. + } + [...listeners].forEach((cb) => cb(next)); +} + +export function subscribe(cb: (c: CameraChoice) => void): () => void { + listeners.add(cb); + return () => listeners.delete(cb); +} + +/** For tests: forget what was read, so the next read starts from storage again. */ +export function resetCamera(): void { + current = undefined; + listeners.clear(); +} diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts new file mode 100644 index 00000000..b30b04c1 --- /dev/null +++ b/src/app/features/scene/ridge/heading.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest'; +import { anchor, getMode, headingAt, hold, phiAt, resetHeading, setMode, setRate, subscribe } from './heading'; + +const S = 1000; + +beforeEach(resetHeading); + +describe('the heading owner', () => { + it('starts still, facing nothing in particular until a place anchors it', () => { + expect(getMode()).toBe('still'); + expect(headingAt(5 * S)).toBe(0); + expect(phiAt(5 * S)).toBe(0); + }); + + it('anchors a place at its rest azimuth once, and a later anchor of the same place changes nothing', () => { + anchor('vienna', 214, 0); + expect(headingAt(0)).toBe(214); + setMode('both', 0); + setRate(0.6, 0); + expect(headingAt(10 * S)).toBeCloseTo(220, 9); + anchor('vienna', 214, 10 * S); // a rebuild for a new sky: the view keeps the direction it has turned to + expect(headingAt(10 * S)).toBeCloseTo(220, 9); + anchor('fuji', 100, 10 * S); // another place faces its own rest azimuth, with the camera on its heading + expect(headingAt(10 * S)).toBe(100); + expect(phiAt(10 * S)).toBe(0); + }); + + it('is unwrapped over several revolutions: nothing wraps or clamps it', () => { + anchor('p', 0, 0); + setMode('both', 0); + setRate(6, 0); + expect(headingAt(60 * S)).toBeCloseTo(360, 9); + expect(headingAt(210 * S)).toBeCloseTo(1260, 9); + setRate(-6, 210 * S); + expect(headingAt(330 * S)).toBeCloseTo(540, 9); + expect(headingAt(500 * S)).toBeLessThan(0); + }); + + it('turns the view direction in both mode, the camera on its circle alone in offset mode, and nothing when still', () => { + anchor('p', 100, 0); + setRate(2, 0); + setMode('both', 0); + expect([headingAt(10 * S), phiAt(10 * S)]).toEqual([120, 0]); + setMode('offset', 10 * S); // nothing jumps at the change + expect([headingAt(10 * S), phiAt(10 * S)]).toEqual([120, 0]); + expect([headingAt(20 * S), phiAt(20 * S)]).toEqual([120, 20]); + setMode('still', 20 * S); + expect([headingAt(99 * S), phiAt(99 * S)]).toEqual([120, 20]); + setMode('both', 99 * S); // the camera keeps the angle it stopped at + expect([headingAt(104 * S), phiAt(104 * S)]).toEqual([130, 20]); + }); + + it('a rate change takes effect from now, without moving the view', () => { + anchor('p', 0, 0); + setMode('both', 0); + setRate(1, 0); + setRate(3, 10 * S); + expect(headingAt(10 * S)).toBe(10); + expect(headingAt(20 * S)).toBe(40); + }); + + it('a manual turn sets the view direction in every mode, and stops the rotation where the viewer left it', () => { + for (const mode of ['still', 'offset', 'both'] as const) { + resetHeading(); + anchor('p', 0, 0); + setRate(1, 0); + setMode(mode, 0); + hold(300, 10 * S); + expect(headingAt(10 * S)).toBe(300); + expect(getMode()).toBe('still'); + expect(headingAt(500 * S)).toBe(300); + expect(phiAt(500 * S)).toBe(phiAt(10 * S)); + setMode('both', 500 * S); // a rotation mode chosen again resumes it + expect(headingAt(510 * S)).toBe(310); + } + }); + + it('keeps the heading when the scene is rebuilt: the module outlives it', () => { + anchor('p', 50, 0); + setMode('both', 0); + setRate(1, 0); + // A rebuild is another scene reading the same module state: nothing here is per scene. + expect(headingAt(30 * S)).toBe(80); + anchor('p', 50, 30 * S); + expect(headingAt(30 * S)).toBe(80); + }); + + it('tells subscribers of every change and no change that changes nothing', () => { + const cb = vi.fn(); + const off = subscribe(cb); + anchor('p', 0, 0); + expect(cb).toHaveBeenCalledTimes(1); + anchor('p', 0, 1); + setMode('still', 1); + setRate(0, 1); + expect(cb).toHaveBeenCalledTimes(1); + setMode('both', 1); + setRate(1, 1); + hold(5, 2); + expect(cb).toHaveBeenCalledTimes(4); + off(); + setRate(2, 3); + expect(cb).toHaveBeenCalledTimes(4); + }); +}); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts new file mode 100644 index 00000000..8d7135f2 --- /dev/null +++ b/src/app/features/scene/ridge/heading.ts @@ -0,0 +1,77 @@ +// The heading owner: which way the view faces (`h`) and where the camera stands on its circle against that (`phi`), as kinematics over a clock. +// Pure state and subscribe, module-level so it outlives scene rebuilds: a sky change makes a new scene and the view keeps its direction. Angles are +// unwrapped compass degrees, never wrapped by a consumer (`ring.ts` is the one place that reasons about 0 / 360). Nothing but this module advances +// `h` or `phi`; the viewer's intent (mode, speed, offset) is `cameraState.ts`, and a scene applies it here. +// +// The camera sits on its circle at angle `theta = h + phi`: with `phi` 0 it is pushed forward along its own heading (`view.ts` `cardPose`); rotating +// the offset alone moves `phi` and leaves the view direction where it is (ruling ridge-scene-view-submenus). + +/** `still`: nothing turns. `offset`: the camera circles the centre, the view direction stays. `both`: the view direction turns and the camera with it. */ +export type RotationMode = 'still' | 'offset' | 'both'; + +interface State { + mode: RotationMode; + /** Degrees per second, signed. */ + rate: number; + h0: number; + phi0: number; + /** The clock (ms) at which `h0` and `phi0` held. */ + t0: number; + /** What the heading was last anchored to: a baked place (its bake id), so a place change restarts at its rest azimuth and a sky change does not. */ + anchor: string | undefined; +} + +const initial = (): State => ({ mode: 'still', rate: 0, h0: 0, phi0: 0, t0: 0, anchor: undefined }); +let state = initial(); +const listeners = new Set<() => void>(); + +const advanced = (now: number): number => (state.rate * (now - state.t0)) / 1000; + +/** The view direction at `now` (ms), unwrapped degrees. */ +export const headingAt = (now: number): number => state.h0 + (state.mode === 'both' ? advanced(now) : 0); +/** The camera's angle on its circle against the heading at `now`, unwrapped degrees. */ +export const phiAt = (now: number): number => state.phi0 + (state.mode === 'offset' ? advanced(now) : 0); +export const getMode = (): RotationMode => state.mode; +export const getRate = (): number => state.rate; + +const emit = () => [...listeners].forEach((cb) => cb()); + +/** Take `h`, `phi` and the clock to `now` and change what advances them: the one way a value is replaced, so no change makes the view jump. */ +function rebase(now: number, over: Partial = {}, h = headingAt(now), phi = phiAt(now)): void { + state = { ...state, ...over, h0: h, phi0: phi, t0: now }; + emit(); +} + +/** + * Point the view at a place: the first time it is shown, or when it is not the place the heading was last anchored to, the view faces its rest azimuth + * with the camera on its heading. The same place again changes nothing (a rebuild for a sky keeps the heading). + */ +export function anchor(key: string, restDeg: number, now: number): void { + if (state.anchor === key) return; + rebase(now, { anchor: key }, restDeg, 0); +} + +/** A manual turn: the view direction becomes `h` now, in every mode, and the rotation stops where the viewer left it (ruling ridge-view-turn-handback); a mode chosen again resumes it. */ +export function hold(h: number, now: number): void { + rebase(now, { mode: 'still' }, h); +} + +export function setMode(mode: RotationMode, now: number): void { + if (mode !== state.mode) rebase(now, { mode }); +} + +export function setRate(rate: number, now: number): void { + if (rate !== state.rate) rebase(now, { rate }); +} + +/** Hear every change of the kinematics (a manual turn, a mode, a rate, a new place); returns the way to stop. */ +export function subscribe(cb: () => void): () => void { + listeners.add(cb); + return () => listeners.delete(cb); +} + +/** For tests: the state of a fresh page. */ +export function resetHeading(): void { + state = initial(); + listeners.clear(); +} diff --git a/src/app/features/scene/ridge/manifest.fixture.ts b/src/app/features/scene/ridge/manifest.fixture.ts index f56fe407..5fcbf618 100644 --- a/src/app/features/scene/ridge/manifest.fixture.ts +++ b/src/app/features/scene/ridge/manifest.fixture.ts @@ -1,16 +1,21 @@ -// A hand-written manifest v2 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. +// A hand-written manifest schema 3 and index v1 (wire form, as export.py writes them): the runtime's tests need no real bake and no decoder. The ring is +// four tiles of 90 degrees, so a tile is a quarter of the compass and wrap-around at north is easy to meet. import type { View } from './view'; -/** Card scales of the fixture, nearest first, as the baker derives them for a camera 200 m forward (distances 1.2 km, 12 km, 40 km). */ -const SCALES = [1.2, 1.0167, 1.005] as const; +/** A card's distance in each of the fixture's four tiles, metres, nearest card first; null where the tile holds no such card (the third card is absent over the south). */ +export const DISTANCES: (number | null)[][] = [ + [1000, 1200, 1400, 1100], + [10000, 12000, 14000, 11000], + [40000, 41000, null, 39000], +]; -/** A v2 manifest of `k` cards (1 to 6), nearest first, each a band of the 600-row plane. */ +/** A schema 3 manifest of `k` cards (1 to 3, nearest first), each a band of the 600-row plane, over four tiles of 1600 columns. */ export const wireManifest = ( over: Record = {}, k = 3 ): Record => ({ - schema: 2, - baker_version: 2, + schema: 3, + baker_version: 4, bake_id: 'abc123abc123', place: { id: 'vienna', @@ -23,33 +28,40 @@ export const wireManifest = ( }, view: { look_az_deg: 214, - window_deg: 72, - plane_w: 1280, plane_h: 600, - px_per_deg_h: 1280 / 72, - px_per_deg_v: 177.8, + px_per_deg_h: 6400 / 360, + px_per_deg_v: 171.7, exaggeration: 10, - horizon_row: 314.5, + horizon_row: 357, sky_row: 24, near_row: 396, + ring_w: 6400, + tile_w: 1600, + tiles: 4, + apron: 2, }, curvature: { r_earth_m: 6371000, k_ref: 0.13 }, encoding: { log_d_min: 4.6, log_d_max: 11.5, normal: 'rt8' }, - camera: { r_m: 200, heading_max_deg: 23 }, + camera: { r_max_m: 100 }, cards: Array.from({ length: k }, (_, i) => ({ - top: 100 * i, - h: 600 - 100 * i, - near_m: i ? 1000 * i : null, - far_m: i < k - 1 ? 1000 * (i + 1) : null, - median_m: 1000 * (i + 1), - distance_m: 1000 * (i + 1), - scale: SCALES[i] ?? 1.001, - colour: { file: `card-${i}-colour.webp`, bytes: 1 }, - geometry: { file: `card-${i}-geometry.webp`, bytes: 1 }, + near_m: i ? 1000 * 10 ** (i - 1) * 4 : null, + far_m: i < k - 1 ? 4000 * 10 ** i : null, })), - w: 1280, - h: 600, - bytes: 2 * k, + tiles: Array.from({ length: 4 }, (_, t) => + Array.from({ length: k }, (_, i) => { + const d = DISTANCES[i][t]; + return d === null + ? null + : { + top: 100 * i, + h: 600 - 100 * i, + distance_m: d, + colour: { file: `card-${i}-t${String(t).padStart(2, '0')}-colour.webp`, bytes: 1 }, + geometry: { file: `card-${i}-t${String(t).padStart(2, '0')}-geometry.webp`, bytes: 1 }, + }; + }) + ), + bytes: 0, attribution: { credit_line: 'credit', licence: 'licence', @@ -65,14 +77,16 @@ export const wireIndex = { places: { vienna: 'vienna-abc123abc123', graz: 'graz-def456def456' }, }; -/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, window, horizon row), so a test can tell the two apart. */ +/** A View that differs from FALLBACK_VIEW in every field the sky reads (place, altitude, look azimuth, horizon row), so a test can tell the two apart. */ export const ELSEWHERE_VIEW: View = { place: { id: 'elsewhere', lat: -33.9, lon: 151.2, altitudeKm: 1.5, tz: 'Australia/Sydney' }, lookAzDeg: 20, - windowDeg: 90, - planeW: 1600, + ringW: 3600, + tileW: 900, + tiles: 4, + apron: 2, planeH: 700, - pxPerDegH: 1600 / 90, + pxPerDegH: 10, pxPerDegV: 100, horizonRow: 250, }; diff --git a/src/app/features/scene/ridge/manifest.test.ts b/src/app/features/scene/ridge/manifest.test.ts index 736c6252..cbbd9a2c 100644 --- a/src/app/features/scene/ridge/manifest.test.ts +++ b/src/app/features/scene/ridge/manifest.test.ts @@ -3,17 +3,19 @@ import { forgetManifests, loadManifest, parseManifest } from './manifest'; import { wireIndex, wireManifest } from './manifest.fixture'; describe('parseManifest', () => { - it('reads a v2 manifest into the View the sky and cards share, and K cards nearest first', () => { + it('reads a schema 3 manifest into the View the sky and cards share, the offset bound, and the cards by tile', () => { const m = parseManifest(wireManifest(), '/public/ridge/v/'); expect(m.dir).toBe('/public/ridge/v/'); expect(m.view).toMatchObject({ lookAzDeg: 214, - windowDeg: 72, - planeW: 1280, + ringW: 6400, + tileW: 1600, + tiles: 4, + apron: 2, planeH: 600, - pxPerDegH: 1280 / 72, - pxPerDegV: 177.8, // not px_per_deg_h: a real bake's two differ 10x - horizonRow: 314.5, + pxPerDegH: 6400 / 360, + pxPerDegV: 171.7, // not px_per_deg_h: a real bake's two differ 10x + horizonRow: 357, }); expect(m.view.place).toEqual({ id: 'vienna', @@ -23,47 +25,59 @@ describe('parseManifest', () => { tz: 'Europe/Vienna', }); expect(m.encoding).toEqual({ logDMin: 4.6, logDMax: 11.5 }); - expect(m.camera).toEqual({ headingMaxDeg: 23 }); - expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); - expect(m.cards[1]).toEqual({ + expect(m.camera).toEqual({ rMaxM: 100 }); + expect(m.cards).toEqual([ + { nearM: null, farM: 4000 }, + { nearM: 4000, farM: 40000 }, + { nearM: 40000, farM: null }, + ]); + expect(m.tiles).toHaveLength(4); + expect(m.tiles[1][1]).toEqual({ top: 100, h: 500, - scale: 1.0167, - colour: 'card-1-colour.webp', - geometry: 'card-1-geometry.webp', + distanceM: 12000, + colour: 'card-1-t01-colour.webp', + geometry: 'card-1-t01-geometry.webp', }); + expect(m.tiles[2][2]).toBeNull(); // the third card holds nothing over the south expect(m.attribution.creditLine).toBe('credit'); }); - it.each([1, 2, 3, 4, 5, 6])('parses a bake of %i cards', (k) => { - expect(parseManifest(wireManifest({}, k), '/').cards).toHaveLength(k); + it.each([1, 2, 3])('parses a bake of %i cards', (k) => { + const m = parseManifest(wireManifest({}, k), '/'); + expect(m.cards).toHaveLength(k); + m.tiles.forEach((row) => expect(row).toHaveLength(k)); }); - it('keeps only what the runtime reads: no distances, no camera offset', () => { - const m = parseManifest(wireManifest(), '/') as unknown as Record; - expect(JSON.stringify(m)).not.toMatch(/median|near_m|far_m|distance|rM|r_m/); - }); - - it('refuses schema 1, no cards, seven cards, a card past the plane, a scale that is not above 0, a missing camera', () => { + it('refuses schema 2 naming the stale deploy, and any other schema', () => { const w = wireManifest() as any; + expect(() => parseManifest({ ...w, schema: 2 }, '/')).toThrow(/stale ridge bake/); expect(() => parseManifest({ ...w, schema: 1 }, '/')).toThrow(/schema/); - expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/); - expect(() => parseManifest(wireManifest({}, 7), '/')).toThrow(/cards/); - const card = w.cards[0]; - const withCard = (c: unknown) => ({ ...w, cards: [c] }); - expect(() => parseManifest(withCard({ ...card, top: 300, h: 301 }), '/')).toThrow(/rows/); - expect(() => parseManifest(withCard({ ...card, top: -1 }), '/')).toThrow(/rows/); - expect(() => parseManifest(withCard({ ...card, scale: 0 }), '/')).toThrow(/scale/); - expect(() => parseManifest(withCard({ ...card, scale: -1 }), '/')).toThrow(/scale/); - expect(() => parseManifest(withCard({ ...card, scale: Infinity }), '/')).toThrow(/scale/); - expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/); - expect(() => parseManifest({ ...w, camera: { heading_max_deg: 0 } }, '/')).toThrow(/heading/); }); - it('rejects a missing field, a plane wider than 4096, a normal that is not rt8 and a backwards encoding', () => { + it('refuses no cards, seven cards, a ring that is not tiles x tile_w, a tile row of the wrong length, a card in no tile, a band past the plane', () => { + const w = wireManifest() as any; + expect(() => parseManifest({ ...w, cards: [] }, '/')).toThrow(/cards/); + expect(() => parseManifest({ ...w, cards: Array(7).fill({ near_m: null, far_m: null }) }, '/')).toThrow(/cards/); + expect(() => parseManifest({ ...w, view: { ...w.view, ring_w: 6401 } }, '/')).toThrow(/ring_w/); + expect(() => parseManifest({ ...w, tiles: w.tiles.slice(1) }, '/')).toThrow(/tiles/); + expect(() => parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => r.slice(1)) }, '/')).toThrow(/entries/); + expect(() => + parseManifest({ ...w, tiles: w.tiles.map((r: unknown[]) => [r[0], r[1], null]) }, '/') + ).toThrow(/null in every tile/); + const withTile = (e: unknown) => ({ ...w, tiles: [[e, w.tiles[0][1], w.tiles[0][2]], ...w.tiles.slice(1)] }); + const t = w.tiles[0][0]; + expect(() => parseManifest(withTile({ ...t, top: 300, h: 301 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withTile({ ...t, top: -1 }), '/')).toThrow(/rows/); + expect(() => parseManifest(withTile({ ...t, distance_m: 0 }), '/')).toThrow(/distance/); + expect(() => parseManifest(withTile({ ...t, distance_m: Infinity }), '/')).toThrow(/distance/); + expect(() => parseManifest({ ...w, camera: undefined }, '/')).toThrow(/camera/); + expect(() => parseManifest({ ...w, camera: { r_max_m: 0 } }, '/')).toThrow(/r_max_m/); + }); + + it('rejects a missing field, a normal that is not rt8 and a backwards encoding', () => { const w = wireManifest() as any; expect(() => parseManifest({ ...w, bake_id: undefined }, '/')).toThrow(/bake_id/); - expect(() => parseManifest({ ...w, view: { ...w.view, plane_w: 4097 } }, '/')).toThrow(/4096/); expect(() => parseManifest({ ...w, view: { ...w.view, horizon_row: 'x' } }, '/')).toThrow( /horizon_row/ ); @@ -95,8 +109,8 @@ describe('parseManifest', () => { }; for (const bad of [ { ...w, schema: 'SECRET-VALUE-42' }, - { ...w, camera: { heading_max_deg: 'SECRET-VALUE-42' } }, - { ...w, cards: [{ ...w.cards[0], scale: 'SECRET-VALUE-42' }] }, + { ...w, camera: { r_max_m: 'SECRET-VALUE-42' } }, + { ...w, tiles: [[{ ...w.tiles[0][0], distance_m: 'SECRET-VALUE-42' }, ...w.tiles[0].slice(1)], ...w.tiles.slice(1)] }, ]) { const msg = refusal(bad); expect(msg).not.toBe(''); diff --git a/src/app/features/scene/ridge/manifest.ts b/src/app/features/scene/ridge/manifest.ts index 283d2807..9700e621 100644 --- a/src/app/features/scene/ridge/manifest.ts +++ b/src/app/features/scene/ridge/manifest.ts @@ -1,23 +1,29 @@ // The ridge backdrop's one JSON boundary: a static asset between the offline Python baker (scripts/ridge-bake/export.py, whose SCHEMA is the // contract) and the page; no daemon state. Main-chunk safe: types, a parser and fetch only. Wire names are snake_case; the parsed manifest is -// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 2: K G-buffer cards, nearest first. +// camelCase and its `view` is the View (`view.ts`) the sky and the cards share. Schema 3: the whole 360 degree ring, K G-buffer cards cut into +// azimuth tiles, each tile two files. import type { View } from './view'; -export const PLANE_W_MAX = 4096; /** As export.py MAX_CARDS: the decode budget holds this many. */ export const MAX_CARDS = 6; -/** One G-buffer card: its rows of the plane, how large it sits against the bake, and its two files (names inside the manifest's directory). */ -export interface CardEntry { - /** First row of the card in the plane, and its height in rows. */ +/** One card's tile: its rows of the plane, the card's distance there, and its two files (names inside the manifest's directory). */ +export interface TileCard { + /** First row of the card's band in the plane, and its height in rows. */ top: number; h: number; - /** The card's pan rate per unit of heading and its static size, as the baker derived them from the camera and the card's distance (ruling ridge-camera-on-circle). */ - scale: number; + /** exp(median ln d) of the card's solid pixels in the tile's interior, metres. */ + distanceM: number; colour: string; geometry: string; } +/** A card as the bake lists it: the median seam depths over the ring, null at the ends. */ +export interface CardEntry { + nearM: number | null; + farM: number | null; +} + export interface RidgeManifest { bakeId: string; /** Absolute-or-rooted URL of the bake's directory, with a trailing slash. */ @@ -25,12 +31,14 @@ export interface RidgeManifest { /** Display name of the place. */ name: string; view: View; - /** How the geometry card's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */ + /** How the geometry file's blue channel maps to ln metres: `logD = logDMin + b x (logDMax - logDMin)`, b in 0..1. The red and green channels are the 'rt8' normal. */ encoding: { logDMin: number; logDMax: number }; - /** The widest heading either side of the look azimuth the baked cards allow, degrees. */ - camera: { headingMaxDeg: number }; + /** The largest camera offset from the bake centre the cards' linear slide fits, metres (ruling ridge-offset-range-fit). */ + camera: { rMaxM: number }; /** Nearest first. */ cards: CardEntry[]; + /** `tiles[t][i]` is card i in tile t, or null where the card holds nothing there. */ + tiles: (TileCard | null)[][]; attribution: { creditLine: string; licence: string; demSource: string; url: string }; } @@ -51,6 +59,7 @@ const num = (x: unknown, path: string): number => typeof x === 'number' && Number.isFinite(x) ? x : fail(path, 'not a number'); const str = (x: unknown, path: string): string => typeof x === 'string' ? x : fail(path, 'not a string'); +const numOrNull = (x: unknown, path: string): number | null => (x === null ? null : num(x, path)); /** An IANA zone name Intl knows (the one place besides skyMoment.ts that touches Intl.DateTimeFormat). */ const zone = (x: unknown, path: string): string => { @@ -73,39 +82,64 @@ export function parseIndex(raw: unknown): RidgeIndex { return { default: str(r.default, 'index.default'), places: out }; } -/** `dir` is the URL of the directory the manifest was read from; the cards are read relative to it. */ +/** `dir` is the URL of the directory the manifest was read from; the tile files are read relative to it. */ export function parseManifest(raw: unknown, dir: string): RidgeManifest { const r = rec(raw, 'manifest'); - if (r.schema !== 2) fail('schema', 'must be 2'); + if (r.schema !== 3) { + fail( + 'schema', + `must be 3: this build reads ring bakes only, so the deploy holds a stale ridge bake (rebake the place, or redeploy a matching build)` + ); + } const p = rec(r.place, 'place'); const v = rec(r.view, 'view'); - const planeW = num(v.plane_w, 'view.plane_w'); - if (planeW > PLANE_W_MAX) fail('view.plane_w', `above ${PLANE_W_MAX}`); + const ringW = num(v.ring_w, 'view.ring_w'); + const tileW = num(v.tile_w, 'view.tile_w'); + const tiles = num(v.tiles, 'view.tiles'); + if (!Number.isInteger(tiles) || tiles < 1) fail('view.tiles', 'not a count'); + if (ringW !== tiles * tileW) fail('view.ring_w', 'is not tiles x tile_w'); const planeH = num(v.plane_h, 'view.plane_h'); if (!Array.isArray(r.cards) || r.cards.length < 1) fail('cards', 'none'); - if ((r.cards as unknown[]).length > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`); + const k = (r.cards as unknown[]).length; + if (k > MAX_CARDS) fail('cards', `more than ${MAX_CARDS}`); const cards = (r.cards as unknown[]).map((x, i): CardEntry => { const c = rec(x, `cards[${i}]`); - const top = num(c.top, `cards[${i}].top`); - const h = num(c.h, `cards[${i}].h`); - if (top < 0 || h < 1 || top + h > planeH) fail(`cards[${i}]`, 'outside the plane rows'); - const scale = num(c.scale, `cards[${i}].scale`); - if (!(scale > 0)) fail(`cards[${i}].scale`, 'not above 0'); return { - top, - h, - scale, - colour: str(rec(c.colour, `cards[${i}].colour`).file, `cards[${i}].colour.file`), - geometry: str(rec(c.geometry, `cards[${i}].geometry`).file, `cards[${i}].geometry.file`), + nearM: numOrNull(c.near_m, `cards[${i}].near_m`), + farM: numOrNull(c.far_m, `cards[${i}].far_m`), }; }); + if (!Array.isArray(r.tiles) || r.tiles.length !== tiles) fail('tiles', `not ${tiles} tiles`); + const grid = (r.tiles as unknown[]).map((row, t) => { + if (!Array.isArray(row) || row.length !== k) fail(`tiles[${t}]`, `not ${k} entries`); + return (row as unknown[]).map((x, i): TileCard | null => { + if (x === null) return null; + const path = `tiles[${t}][${i}]`; + const e = rec(x, path); + const top = num(e.top, `${path}.top`); + const h = num(e.h, `${path}.h`); + if (top < 0 || h < 1 || top + h > planeH) fail(path, 'outside the plane rows'); + const distanceM = num(e.distance_m, `${path}.distance_m`); + if (!(distanceM > 0)) fail(`${path}.distance_m`, 'not above 0'); + return { + top, + h, + distanceM, + colour: str(rec(e.colour, `${path}.colour`).file, `${path}.colour.file`), + geometry: str(rec(e.geometry, `${path}.geometry`).file, `${path}.geometry.file`), + }; + }); + }); + for (let i = 0; i < k; i += 1) { + if (grid.every((row) => row[i] === null)) fail(`cards[${i}]`, 'is null in every tile'); + } const e = rec(r.encoding, 'encoding'); if (e.normal !== 'rt8') fail('encoding.normal', "must be 'rt8'"); const logDMin = num(e.log_d_min, 'encoding.log_d_min'); const logDMax = num(e.log_d_max, 'encoding.log_d_max'); if (!(logDMax > logDMin)) fail('encoding', 'log_d_max not above log_d_min'); - const headingMaxDeg = num(rec(r.camera, 'camera').heading_max_deg, 'camera.heading_max_deg'); - if (!(headingMaxDeg > 0)) fail('camera.heading_max_deg', 'not above 0'); + const rMaxM = num(rec(r.camera, 'camera').r_max_m, 'camera.r_max_m'); + if (!(rMaxM > 0)) fail('camera.r_max_m', 'not above 0'); const a = rec(r.attribution, 'attribution'); const id = str(p.id, 'place.id'); return { @@ -121,16 +155,19 @@ export function parseManifest(raw: unknown, dir: string): RidgeManifest { tz: zone(p.tz, 'place.tz'), }, lookAzDeg: num(v.look_az_deg, 'view.look_az_deg'), - windowDeg: num(v.window_deg, 'view.window_deg'), - planeW, + ringW, + tileW, + tiles, + apron: num(v.apron, 'view.apron'), planeH, pxPerDegH: num(v.px_per_deg_h, 'view.px_per_deg_h'), pxPerDegV: num(v.px_per_deg_v, 'view.px_per_deg_v'), horizonRow: num(v.horizon_row, 'view.horizon_row'), }, encoding: { logDMin, logDMax }, - camera: { headingMaxDeg }, + camera: { rMaxM }, cards, + tiles: grid, attribution: { creditLine: str(a.credit_line, 'attribution.credit_line'), licence: str(a.licence, 'attribution.licence'), @@ -160,7 +197,7 @@ export function loadManifest(baseUrl: string, placeId?: string): Promise { const index = parseIndex( - // The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and planes are content-addressed. + // The index is the one mutable pointer (a rebake deletes the old directory it named); the manifest and tiles are content-addressed. await getJson(`${root}index.json`, { cache: 'no-cache' }) ); const id = placeId !== undefined && placeId in index.places ? placeId : index.default; diff --git a/src/app/features/scene/ridge/ring.test.ts b/src/app/features/scene/ridge/ring.test.ts new file mode 100644 index 00000000..bfe049fa --- /dev/null +++ b/src/app/features/scene/ridge/ring.test.ts @@ -0,0 +1,93 @@ +import { describe, expect, it } from 'vitest'; +import { distanceAt, norm, residentTiles, runTiles, tileAzimuth } from './ring'; +import { parseManifest } from './manifest'; +import { wireManifest } from './manifest.fixture'; + +const ring32 = { tiles: 32 }; + +describe('norm', () => { + it('brings any angle into [0, 360)', () => { + expect(norm(0)).toBe(0); + expect(norm(360)).toBe(0); + expect(norm(-10)).toBe(350); + expect(norm(725)).toBe(5); + }); +}); + +describe('residentTiles', () => { + it('names the tiles an arc overlaps across north, with turns 0 and 1 and monotone unwrapped azimuths', () => { + // Centre 355, half 40: [315, 395] overlaps tiles 28..31 of the first turn and 0..3 of the next. + const refs = residentTiles(ring32, 355, 40); + expect(refs.map((r) => r.tile)).toEqual([28, 29, 30, 31, 0, 1, 2, 3]); + expect(refs.map((r) => r.turn)).toEqual([0, 0, 0, 0, 1, 1, 1, 1]); + const az = refs.map((r) => tileAzimuth(ring32, r)); + az.slice(1).forEach((a, i) => expect(a).toBeGreaterThan(az[i])); + expect(az[0]).toBe(315); + expect(az[4]).toBe(360); + }); + + it('picks the same tiles for a heading and the heading a revolution on, in another turn', () => { + const a = residentTiles(ring32, 40, 30); + const b = residentTiles(ring32, 400, 30); + expect(b.map((r) => r.tile)).toEqual(a.map((r) => r.tile)); + expect(b.every((r, i) => r.turn === a[i].turn + 1)).toBe(true); + // And a heading turned backwards across north. + const c = residentTiles(ring32, -20, 30); + expect(c.map((r) => r.tile)).toEqual([27, 28, 29, 30, 31, 0]); + expect(c.map((r) => r.turn)).toEqual([-1, -1, -1, -1, -1, 0]); + }); + + it('names a tile once at most, even for an arc of a whole ring or more', () => { + const all = residentTiles(ring32, 100, 400); + expect(all).toHaveLength(32); + expect(new Set(all.map((r) => r.tile)).size).toBe(32); + }); + + it('is one tile for an arc inside a tile, and includes a tile an arc only touches at its edge', () => { + expect(residentTiles(ring32, 5, 1).map((r) => r.tile)).toEqual([0]); + expect(residentTiles(ring32, 11.25, 0).map((r) => r.tile)).toEqual([1]); + }); +}); + +describe('distanceAt', () => { + const m = parseManifest(wireManifest(), '/d/'); // four tiles of 90 degrees, centres at 45, 135, 225, 315 + it('is the tile distance at a tile centre and interpolates linearly between centres', () => { + expect(distanceAt(m, 0, 45)).toBeCloseTo(1000, 9); + expect(distanceAt(m, 0, 135)).toBeCloseTo(1200, 9); + expect(distanceAt(m, 0, 90)).toBeCloseTo(1100, 9); + }); + + it('interpolates across the wrap at north and takes any unwrapped heading the same as its wrapped one', () => { + // between tile 3 (315 degrees, 1100 m) and tile 0 (45, 1000 m): north is halfway. + expect(distanceAt(m, 0, 0)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, 360)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, -360)).toBeCloseTo(1050, 9); + expect(distanceAt(m, 0, 400)).toBeCloseTo(distanceAt(m, 0, 40), 9); + expect(distanceAt(m, 0, -20)).toBeCloseTo(distanceAt(m, 0, 340), 9); + }); + + it('skips a tile where the card is absent: the line runs on to the next tile that holds it', () => { + // card 2 is absent in tile 2 (centre 225): between tile 1 (41000 m at 135) and tile 3 (39000 m at 315), 225 is halfway. + expect(distanceAt(m, 2, 225)).toBeCloseTo(40000, 9); + expect(distanceAt(m, 2, 135)).toBeCloseTo(41000, 9); + expect(distanceAt(m, 2, 180)).toBeCloseTo(40500, 9); + expect(distanceAt(m, 2, 270)).toBeCloseTo(39500, 9); + }); + + it('is the one distance all round for a card that is in one tile only', () => { + const one = wireManifest({}, 3) as { tiles: (unknown | null)[][] }; + const only = { ...one, tiles: one.tiles.map((row, t) => [row[0], row[1], t === 1 ? row[2] : null]) }; + const mo = parseManifest(only, '/d/'); + [0, 77, 135, 200, 359].forEach((az) => expect(distanceAt(mo, 2, az)).toBeCloseTo(41000, 9)); + }); +}); + +describe('runTiles', () => { + it('is export.py run_tiles: the arc at the smallest slide rate plus the offset swing, a straddled tile and two tiles of margin each side', () => { + // Vienna's numbers: r_max 98.2, nearest card 603 m. s_min = 603 / 701.2; arc = 65.45 / s_min + 2 (98.2 / 603) 57.3. + const sMin = 603 / (603 + 98.2); + const arc = 65.4545 / sMin + 2 * (98.2 / 603) * 57.3; + expect(runTiles(ring32, 72 / 1.1, 98.2, 603)).toBe(Math.ceil(arc / 11.25) + 1 + 4); + expect(runTiles(ring32, 72 / 1.1, 100000, 603)).toBe(32); + }); +}); diff --git a/src/app/features/scene/ridge/ring.ts b/src/app/features/scene/ridge/ring.ts new file mode 100644 index 00000000..e698eb4e --- /dev/null +++ b/src/app/features/scene/ridge/ring.ts @@ -0,0 +1,75 @@ +// The ring: the one place that reasons about wrap-around at 0 / 360 degrees (a heading is unwrapped and never wrapped by a consumer), and the +// one place a card's distance at an azimuth is read from its tiles. Pure: no DOM, no state. +import type { RidgeManifest } from './manifest'; +import type { View } from './view'; + +/** A compass angle brought into [0, 360). */ +export const norm = (deg: number): number => ((deg % 360) + 360) % 360; + +/** A tile of the ring and the revolution it is met in: its unwrapped azimuth is `turn x 360 + tile x (360 / tiles)`. */ +export interface TileRef { + tile: number; + turn: number; +} + +/** + * The tiles that overlap `[centre - half, centre + half]`, unwrapped compass degrees, in increasing unwrapped azimuth. Each tile is named at most once + * (an arc of a whole ring or more is every tile, from the one the arc starts in). + */ +export function residentTiles( + view: Pick, + centreDeg: number, + halfArcDeg: number +): TileRef[] { + const w = 360 / view.tiles; + const first = Math.floor((centreDeg - halfArcDeg) / w); + const last = Math.min(Math.floor((centreDeg + halfArcDeg) / w), first + view.tiles - 1); + const out: TileRef[] = []; + for (let u = first; u <= last; u += 1) { + out.push({ tile: ((u % view.tiles) + view.tiles) % view.tiles, turn: Math.floor(u / view.tiles) }); + } + return out; +} + +/** The unwrapped azimuth of the left edge of a tile met in `turn`. */ +export const tileAzimuth = (view: Pick, ref: TileRef): number => + ref.turn * 360 + (ref.tile * 360) / view.tiles; + +/** + * The distance of card `card` at compass angle `azDeg`, metres: the circular linear interpolation of the tiles' `distanceM` between tile centres, a tile + * where the card is absent skipped (the line runs on to the next tile that holds it; a card in one tile only has that distance all round). + */ +export function distanceAt(manifest: RidgeManifest, card: number, azDeg: number): number { + const n = manifest.view.tiles; + const at = (t: number) => manifest.tiles[t][card]?.distanceM; + const u = norm(azDeg) / (360 / n) - 0.5; // tile-centre coordinates: tile t's centre is at t + const lo = Math.floor(u); + const frac = u - lo; + const held = (from: number, step: number): number => { + for (let k = 0; k < n; k += 1) { + const t = (((from + step * k) % n) + n) % n; + if (at(t) !== undefined) return k; + } + throw new Error(`ridge: card ${card} is in no tile`); + }; + // The nearest tiles that hold the card at or before the point (back) and after it (ahead), by how many tile steps away they are. + const back = held(lo, -1); + const ahead = held(lo + 1, 1); + const tBack = (((lo - back) % n) + n) % n; + const tAhead = (((lo + 1 + ahead) % n) + n) % n; + const dBack = at(tBack) as number; + const dAhead = at(tAhead) as number; + const span = back + 1 + ahead; // tile steps between the two holders + const along = back + frac; // steps from the back holder to the point + return dBack + (dAhead - dBack) * (along / span); +} + +/** + * N: the tiles the loader may hold at once for a bake (export.py `run_tiles`): the widest viewport arc at the smallest slide rate plus the offset's own + * swing, one straddled tile and two tiles of margin each side. `rminM` is the nearest card's nearest distance. + */ +export function runTiles(view: Pick, hfovMaxDeg: number, rMaxM: number, rminM: number): number { + const sMin = rminM / (rminM + rMaxM); + const arc = hfovMaxDeg / sMin + 2 * (rMaxM / rminM) * 57.3; + return Math.min(view.tiles, Math.ceil(arc / (360 / view.tiles)) + 1 + 4); +} diff --git a/src/app/features/scene/ridge/view.test.ts b/src/app/features/scene/ridge/view.test.ts index 2900523e..6eddebe6 100644 --- a/src/app/features/scene/ridge/view.test.ts +++ b/src/app/features/scene/ridge/view.test.ts @@ -1,6 +1,14 @@ import { describe, expect, it } from 'vitest'; -import { sunOnScreen } from './skyDome'; -import { cardMotion, DRIFT_FRAC, FALLBACK_VIEW, HORIZON_AT, windowFor } from './view'; +import { + cardArc, + cardPose, + FALLBACK_VIEW, + HFOV_MAX_DEG, + HORIZON_AT, + offsetRange, + RIDGE_BAND_FRAC, + windowFor, +} from './view'; import { parseManifest } from './manifest'; import { wireManifest } from './manifest.fixture'; import type { View } from './view'; @@ -11,28 +19,41 @@ const VIEWPORTS: [number, number][] = [ [3440, 1440], ]; +const manifest = parseManifest(wireManifest(), '/d/'); // distances: card 0 1000-1400 m, card 1 10-14 km, card 2 39-41 km +const withView = (over: Record) => + parseManifest(wireManifest({ view: { ...(wireManifest().view as object), ...over } }), '/d/'); +const DEG = Math.PI / 180; + describe('windowFor', () => { + it('gives a 16:9 viewport the scale and the 65.45 degrees it had when a window was baked, and a phone the band scale', () => { + const v = FALLBACK_VIEW; + const wide = windowFor(v, 1920, 1080); + expect(wide.plane.scale).toBeCloseTo((1920 * 1.1) / 1280, 9); + expect(wide.camera.hfovDeg).toBeCloseTo(72 / 1.1, 9); + expect(HFOV_MAX_DEG).toBeCloseTo(65.4545, 4); + const phone = windowFor(v, 390, 844); + expect(phone.plane.scale).toBeCloseTo((RIDGE_BAND_FRAC * 844) / v.planeH, 9); + expect(phone.camera.hfovDeg).toBeCloseTo(390 / (phone.plane.scale * v.pxPerDegH), 9); + }); + it.each(VIEWPORTS)( - "%i x %i: the planes cover the viewport, the camera sees only baked sky, the horizon is the plane's", + "%i x %i: the camera never sees more than the widest field, the horizon is the plane's, the plane reaches the bottom", (w, h) => { const v = FALLBACK_VIEW; const win = windowFor(v, w, h); - expect(win.driftPx).toBeGreaterThanOrEqual(0); - expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6); + expect(win.camera.hfovDeg).toBeLessThanOrEqual(HFOV_MAX_DEG + 1e-9); expect(win.plane.h).toBeLessThanOrEqual(h * 4); // sanity: scale is not runaway - // Angle seen never exceeds the baked window minus the drift margin on both sides. - expect(win.camera.hfovDeg).toBeLessThanOrEqual(v.windowDeg / (1 + 2 * DRIFT_FRAC) + 1e-9); - // The plane's horizon row lands at the camera's horizon fraction of the viewport. const horizonY = h - win.plane.bottom - win.plane.h + win.plane.scale * v.horizonRow; expect(Math.abs(horizonY - win.camera.horizonAt * h)).toBeLessThan(0.5); expect(win.camera.azimuthDeg).toBe(v.lookAzDeg); expect(win.camera.vfovDeg / win.camera.hfovDeg).toBeCloseTo(h / w, 9); // one scale on both axes + expect(win.plane.bottom).toBeLessThanOrEqual(0); } ); - it('puts the horizon at one fraction of the height, whatever the viewport, the view or the sky state', () => { - const wide: View = { ...FALLBACK_VIEW, lookAzDeg: 10, windowDeg: 144, planeW: 2560, horizonRow: 200 }; - for (const v of [FALLBACK_VIEW, wide]) + it('puts the horizon at one fraction of the height, whatever the viewport or the view', () => { + const other: View = { ...FALLBACK_VIEW, lookAzDeg: 10, horizonRow: 200, pxPerDegH: 10 }; + for (const v of [FALLBACK_VIEW, other]) for (const [w, h] of [...VIEWPORTS, [1024, 768], [375, 812], [1100, 619]] as [number, number][]) expect(windowFor(v, w, h).camera.horizonAt).toBe(HORIZON_AT); expect(HORIZON_AT).toBeGreaterThan(0.5); @@ -46,110 +67,105 @@ describe('windowFor', () => { expect(sky).toBeLessThan(34); }); - it.each([ - [1024, 768], - [1920, 1080], - [375, 812], - [1100, 619], - ])('%i x %i: the plane covers the viewport bottom and sides, drift included, with baked ground to spare below the horizon', (w, h) => { - const win = windowFor(FALLBACK_VIEW, w, h); - expect(win.plane.bottom).toBeLessThanOrEqual(0); // the foot of the plane is at or below the viewport's bottom edge - expect(win.plane.w - 2 * win.driftPx).toBeCloseTo(w, 6); - expect(win.driftPx).toBeGreaterThanOrEqual(0); - // The baked ground below the horizon row that the viewport crops to: more than the viewport needs. - const needed = (1 - HORIZON_AT) * h; - const baked = win.plane.scale * (FALLBACK_VIEW.planeH - FALLBACK_VIEW.horizonRow); - expect(baked).toBeGreaterThanOrEqual(needed); + it('points the camera at the rest azimuth, and a north-crossing one is not wrapped', () => { + expect(windowFor({ ...FALLBACK_VIEW, lookAzDeg: 355 }, 1920, 1080).camera.azimuthDeg).toBe(355); + }); +}); + +describe('cardPose', () => { + const win = windowFor(manifest.view, 1920, 1080); + const rest = manifest.view.lookAzDeg; + const k = win.plane.scale * manifest.view.pxPerDegH; + + it('at phi 0 is the tangent R / (R - r) the camera pushed forward gives, a card pans with the heading, and the offset 0 leaves it at scale 1', () => { + // Heading 135 is tile 1's centre: card 1 stands 12 km away there. + const p = cardPose(manifest, 1, 135, 0, 200, win); + expect(p.scale).toBeCloseTo(12000 / (12000 - 200), 2); + expect(Math.abs(p.scale - 12000 / (12000 - 200))).toBeLessThan(0.002); + const flat = cardPose(manifest, 1, 135, 0, 0, win); + expect(flat.scale).toBeCloseTo(1, 9); + // The column the view faces lands on the centre: at scale s the container shifts by -s (h - rest) k. + expect(flat.shiftPx).toBeCloseTo(-(135 - rest) * k, 6); }); - it('is shaped by the View alone: another window and plane give another camera (azimuth and field of view; the horizon stays put)', () => { - const wide: View = { - ...FALLBACK_VIEW, - lookAzDeg: 10, - windowDeg: 144, - planeW: 2560, - horizonRow: 200, - }; - const a = windowFor(FALLBACK_VIEW, 1920, 1080).camera; - const b = windowFor(wide, 1920, 1080).camera; - expect(b.azimuthDeg).toBe(10); - expect(windowFor(FALLBACK_VIEW, 1920, 1080).camera.hfovDeg).not.toBeCloseTo(windowFor(wide, 1920, 1080).camera.hfovDeg, 2); - expect(b.horizonAt).toBe(a.horizonAt); + it('is mirrored behind the centre: a backward offset shrinks the card and a larger one shrinks it more', () => { + const fwd = cardPose(manifest, 0, 45, 0, 100, win).scale; + const back = cardPose(manifest, 0, 45, 0, -100, win).scale; + expect(fwd).toBeGreaterThan(1); + expect(back).toBeLessThan(1); + expect(cardPose(manifest, 0, 45, 0, -200, win).scale).toBeLessThan(back); }); - it('registration: a sun 10 degrees right of the look azimuth sits where the plane puts that azimuth', () => { + it('at phi 90 shifts the card sideways by r / R x 57.3 degrees and leaves its size alone', () => { + const at = (phi: number) => cardPose(manifest, 1, 135, phi, 200, win); + const p = at(90); + // The sideways part of a pose: where the line meets the heading's own column, a0 = shift / k + s (h - rest). + const a0 = (q: { scale: number; shiftPx: number }) => q.shiftPx / k + q.scale * (135 - rest); + expect(a0(at(0))).toBeCloseTo(0, 6); + // r / R x 57.3 degrees at the heading's own column; the line fitted over the arc takes the mean of cos over it, about 0.93 of that. + const centre = (200 / 12000) * (180 / Math.PI); + expect(Math.abs(a0(p)) / centre).toBeGreaterThan(0.9); + expect(Math.abs(a0(p)) / centre).toBeLessThanOrEqual(1); + expect(p.scale).toBeCloseTo(1, 2); + }); + + it('is the same at a heading and a revolution on: nothing about it wraps', () => { + const a = cardPose(manifest, 0, 100, 10, 80, win); + const b = cardPose(manifest, 0, 100 + 360, 10, 80, win); + expect(b.scale).toBeCloseTo(a.scale, 9); + // The unwrapped heading moves the container a revolution, which is what keeps the tiles at their unwrapped azimuth. + expect(b.shiftPx - a.shiftPx).toBeCloseTo(-a.scale * 360 * k, 4); + }); + + it('is exact where the sheet is: a card seen from its own circle lands on the line it fits', () => { + // The fitted line passes through the exact angle at the middle of the arc within a card pixel at a small offset. + const R = 12000; + const r = 150; + const p = cardPose(manifest, 1, 135, 0, r, win); + const exact = Math.atan2(R * Math.sin(10 * DEG), R * Math.cos(10 * DEG) - r) / DEG; + const line = (p.shiftPx / k + p.scale * (135 - rest)) + p.scale * 10; + expect(Math.abs(exact - line) * k).toBeLessThan(0.5); + }); +}); + +describe('cardArc', () => { + const win = windowFor(manifest.view, 1920, 1080); + it('is the viewport arc at the rest heading with no offset, and follows the heading and the scale', () => { + const rest = manifest.view.lookAzDeg; + const half = win.camera.hfovDeg / 2; + const flat = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest, 0, 0, win)); + expect(flat.fromDeg).toBeCloseTo(rest - half, 6); + expect(flat.toDeg).toBeCloseTo(rest + half, 6); + const turned = cardArc(manifest.view, win, 1920, cardPose(manifest, 1, rest + 400, 0, 0, win)); + expect(turned.fromDeg).toBeCloseTo(rest + 400 - half, 6); + // A card that is larger on screen shows less of itself. + const near = cardPose(manifest, 0, 45, 0, 100, win); + const arc = cardArc(manifest.view, win, 1920, near); + expect(arc.toDeg - arc.fromDeg).toBeCloseTo((2 * half) / near.scale, 6); + }); +}); + +describe('offsetRange', () => { + it('never exceeds the bake, and is symmetric while the nearest card keeps its foot under the viewport bottom', () => { for (const [w, h] of VIEWPORTS) { - const v = FALLBACK_VIEW; - const win = windowFor(v, w, h); - const sun = { elevation: 12, azimuth: v.lookAzDeg + 10, time: new Date(0) }; - const at = sunOnScreen(sun, win.camera)!; - const planeX = w / 2 + 10 * v.pxPerDegH * win.plane.scale; // plane centred on lookAz - expect(Math.abs(at.x * w - planeX)).toBeLessThan(0.5); - // and its height above the ridge's horizon is 12 degrees of plane pixels - const planeY = win.camera.horizonAt * h - 12 * v.pxPerDegH * win.plane.scale; - expect(Math.abs(at.y * h - planeY)).toBeLessThan(0.5); + const [lo, hi] = offsetRange(manifest, windowFor(manifest.view, w, h)); + expect(hi).toBe(manifest.camera.rMaxM); + expect(lo).toBe(-manifest.camera.rMaxM); } }); - it('the sun is seen across north: azimuths wrap', () => { - const v: View = { ...FALLBACK_VIEW, lookAzDeg: 355 }; - const win = windowFor(v, 1920, 1080); - const at = sunOnScreen({ elevation: 10, azimuth: 5, time: new Date(0) }, win.camera)!; - expect(Math.abs(at.x * 1920 - (960 + 10 * v.pxPerDegH * win.plane.scale))).toBeLessThan(0.5); - }); - - it('the sun does not turn the camera: the same camera for any sun', () => { - expect(windowFor(FALLBACK_VIEW, 1280, 720).camera.azimuthDeg).toBe(FALLBACK_VIEW.lookAzDeg); - }); -}); - -describe('cardMotion', () => { - const manifest = parseManifest(wireManifest(), '/d/'); // scales 1.2, 1.0167, 1.005; heading range 23 deg; 1280 px plane, 17.78 px per degree - const motion = (w: number, h: number) => cardMotion(manifest, windowFor(manifest.view, w, h)); - - it('turns the whole baked range on a phone and is capped by coverage on a wide screen', () => { - expect(motion(390, 844).headingDeg).toBe(23); - expect(motion(1920, 1080).headingDeg).toBeCloseTo(3.4, 1); - expect(motion(768, 1024).headingDeg).toBeLessThan(23); - expect(motion(768, 1024).headingDeg).toBeGreaterThan(motion(1920, 1080).headingDeg); - }); - - it.each([ - [390, 844], - [768, 1024], - [1920, 1080], - [3440, 1440], - ])( - '%i x %i: every card still covers the viewport at the end of the drift, and the cap is exact for the card that gives out first', - (w, h) => { - const win = windowFor(manifest.view, w, h); - const { headingDeg } = cardMotion(manifest, win); - const half = w / 2 / win.plane.scale; - const slack = manifest.cards.map( - (c) => manifest.view.planeW / 2 - half / c.scale - headingDeg * manifest.view.pxPerDegH - ); - slack.forEach((s) => expect(s).toBeGreaterThanOrEqual(-1e-6)); - if (headingDeg < manifest.camera.headingMaxDeg) expect(Math.min(...slack)).toBeCloseTo(0, 6); - } - ); - - it('pans card i by scale_i x heading and keeps the scales the manifest gave', () => { - const win = windowFor(manifest.view, 390, 844); - const m = cardMotion(manifest, win); - expect(m.cards.map((c) => c.scale)).toEqual([1.2, 1.0167, 1.005]); - m.cards.forEach((c) => - expect(c.reachPx).toBeCloseTo(c.scale * 23 * manifest.view.pxPerDegH * win.plane.scale, 6) - ); - // The nearer a card, the faster it pans. - expect(m.cards[0].reachPx).toBeGreaterThan(m.cards[1].reachPx); - expect(m.cards[1].reachPx).toBeGreaterThan(m.cards[2].reachPx); - }); - - it('a wider baker range moves a phone further, a narrower one less', () => { - const win = windowFor(manifest.view, 390, 844); - const at = (deg: number) => cardMotion({ ...manifest, camera: { headingMaxDeg: deg } }, win); - expect(at(10).headingDeg).toBe(10); - expect(at(40).headingDeg).toBeLessThan(40); // the phone's coverage gives out first - expect(at(10).cards[0].reachPx).toBeLessThan(at(20).cards[0].reachPx); + it('gives up part of its backward half where the nearest card shrunk by R / (R + r) would lift its foot above the viewport bottom, and all of it past that', () => { + // 1920 x 1080: keep = (1 - HORIZON_AT) 1080 / (scale (planeH - horizonRow)). Put the horizon row so that keep is 0.95, and the nearest card is 1000 m away. + const scale = windowFor(manifest.view, 1920, 1080).plane.scale; + const near = withView({ horizon_row: 600 - (0.15 * 1080) / 0.95 / scale }); + const win = windowFor(near.view, 1920, 1080); + const [lo, hi] = offsetRange(near, win); + expect(hi).toBe(100); + expect(lo).toBeCloseTo(-1000 * (1 / 0.95 - 1), 6); + // At that offset the card's foot is exactly at the viewport bottom. + const s = 1000 / (1000 - lo); + expect(s * win.plane.scale * (near.view.planeH - near.view.horizonRow)).toBeCloseTo(0.15 * 1080, 6); + const none = withView({ horizon_row: 599 }); + expect(offsetRange(none, windowFor(none.view, 1920, 1080))).toEqual([-0, 100]); }); }); diff --git a/src/app/features/scene/ridge/view.ts b/src/app/features/scene/ridge/view.ts index 10ae7e76..0aa4bc2f 100644 --- a/src/app/features/scene/ridge/view.ts +++ b/src/app/features/scene/ridge/view.ts @@ -1,7 +1,10 @@ // The one View: where the sky's camera stands and looks, and where the ridge cards sit against it. A baked place's manifest -// (`view` and `place`, manifest v2) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the -// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. Nothing else -// chooses a field of view, a horizon row or an azimuth. +// (`view` and `place`, manifest schema 3) is a View; a sky with no planes uses FALLBACK_VIEW. `windowFor` is the single owner of the +// registration between sky and ridge: one View and a viewport in, the sky Camera and the plane's placement out. `offsetRange` is the one +// clamp on the camera's offset and `cardPose` the one place a card's scale and shift are derived (ruling ridge-camera-on-circle). Nothing +// else chooses a field of view, a horizon row, an azimuth, a scale or a shift. +import { distanceAt } from './ring'; +import type { RidgeManifest } from './manifest'; /** Where the observer stands. `id` names the baked place (it keys a rebuild); `altitudeKm` is the ground height, eye height excluded. */ export interface Place { @@ -13,13 +16,17 @@ export interface Place { tz: string; } -/** The manifest's `view`: the baked window of the sky the planes cover. Angles are degrees, planes are in plane pixels. */ +/** + * The manifest's `view`: the ring the planes cover, all 360 degrees, absolute compass (column 0 = north), cut into `tiles` azimuth tiles of `tileW` columns + * (`apron` real neighbour columns each side in a tile's files). Angles are degrees, planes are in plane pixels. + */ export interface ManifestView { - /** Compass azimuth at the centre of the planes, degrees clockwise from north. */ + /** The rest azimuth: the compass azimuth the view faces before anything turns it, degrees clockwise from north. */ lookAzDeg: number; - /** Horizontal angle the planes span. */ - windowDeg: number; - planeW: number; + ringW: number; + tileW: number; + tiles: number; + apron: number; planeH: number; pxPerDegH: number; /** Plane pixels per degree of elevation (the baker draws the vertical exaggerated: it is not `pxPerDegH`). */ @@ -45,21 +52,24 @@ export interface Camera { horizonAt: number; } -/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna bake. */ +/** The sky of a scene with no planes (a failed load): Vienna facing south-west, with the numbers of the Vienna ring bake. */ export const FALLBACK_VIEW: View = { place: { id: 'vienna', lat: 48.1929826, lon: 16.3534237, altitudeKm: 0.183, tz: 'Europe/Vienna' }, lookAzDeg: 214, - windowDeg: 72, - planeW: 1280, + ringW: 6400, + tileW: 200, + tiles: 32, + apron: 2, planeH: 600, - pxPerDegH: 1280 / 72, - pxPerDegV: 177.8, - horizonRow: 314.5, + pxPerDegH: 6400 / 360, + pxPerDegV: 171.73831979090915, + horizonRow: 357.01990847502145, }; -/** The share of the viewport height the plane's height is at least scaled to, and the slack each side of the viewport kept for drift. Authored, tunable by eye. */ +/** The share of the viewport height the plane's height is at least scaled to. Authored, tunable by eye. */ export const RIDGE_BAND_FRAC = 0.6; -export const DRIFT_FRAC = 0.05; +/** The widest field of view a viewport may show: a 16:9 viewport with 1.1 widths of plane (72 / 1.1 degrees), as export.py HFOV_MAX_DEG. */ +export const HFOV_MAX_DEG = 72 / 1.1; /** * Where the horizon sits down the viewport, as a fraction of its height: one constant for every sky state and every viewport (ruling * ridge-frame-more-sky-fixed-pitch: the camera pitch never changes between day and night). The plane extends below the viewport bottom and @@ -69,16 +79,14 @@ export const HORIZON_AT = 0.85; export interface Window { camera: Camera; - /** The planes in viewport pixels: scaled size, centred on `lookAzDeg`, placed so the horizon row lands at `HORIZON_AT` of the height. `bottom` is the distance of the plane's foot above the viewport's bottom edge: negative, the plane runs on below it. */ - plane: { scale: number; w: number; h: number; bottom: number }; - /** How far the plane may slide sideways from centre and still cover the viewport. */ - driftPx: number; + /** The planes in viewport pixels: the scale of a plane pixel, the plane's height, and `bottom`, the distance of its foot above the viewport's bottom edge (negative: the plane runs on below it). The horizon row lands at `HORIZON_AT`. */ + plane: { scale: number; h: number; bottom: number }; } export function windowFor(view: View, viewportW: number, viewportH: number): Window { const scale = Math.max( (RIDGE_BAND_FRAC * viewportH) / view.planeH, - (viewportW * (1 + 2 * DRIFT_FRAC)) / view.planeW + viewportW / (HFOV_MAX_DEG * view.pxPerDegH) ); const hfovDeg = viewportW / (scale * view.pxPerDegH); return { @@ -90,45 +98,90 @@ export function windowFor(view: View, viewportW: number, viewportH: number): Win }, plane: { scale, - w: scale * view.planeW, h: scale * view.planeH, bottom: (1 - HORIZON_AT) * viewportH - scale * (view.planeH - view.horizonRow), }, - driftPx: (scale * view.planeW - viewportW) / 2, }; } -/** What `cardMotion` reads of a manifest: the cards' scales, the baker's heading range and the View. */ -interface CardRig { - view: View; - camera: { headingMaxDeg: number }; - cards: readonly { scale: number }[]; -} - -export interface CardMotion { - /** The heading either side of the look azimuth the drift turns through, degrees. */ - headingDeg: number; - /** Per card, in manifest order (nearest first): the static scale the baker derived and how far it pans, in viewport px, at the end of the drift. */ - cards: { scale: number; reachPx: number }[]; -} - /** - * Where each card goes on a viewport: the single owner of pan reach and heading range (ruling ridge-camera-on-circle). The heading is the baker's - * `headingMaxDeg` unless a card could no longer cover the viewport at it, so it is capped by the card that would uncover first: card i is `scale` times - * wider on screen, and shown at heading delta d it needs `half viewport / scale + d x pxPerDegH` of its half width. Card i pans `scale` x heading x - * `pxPerDegH` plane pixels, at the plane's scale. One scale per card on both axes; nothing is reprojected inside a card (ruling ridge-cards-per-card-slide). + * The offsets the camera may take on its circle, metres, forward positive: the one clamp (ruling ridge-offset-range-fit). Forward is the bake's + * `rMaxM`, the largest offset every card's linear slide fits. Backward is the same, until the nearest card, shrunk by R / (R + r) about the horizon, + * would lift its foot above the viewport bottom and show the sky under it: the baker's nearest-card-off-the-bottom refusal as a clamp. */ -export function cardMotion(m: CardRig, win: Window): CardMotion { - const half = (win.plane.w - 2 * win.driftPx) / (2 * win.plane.scale); // half the viewport, in plane px - const cap = Math.min( - ...m.cards.map((c) => (m.view.planeW / 2 - half / c.scale) / m.view.pxPerDegH) - ); - const headingDeg = Math.max(0, Math.min(m.camera.headingMaxDeg, cap)); +export function offsetRange(manifest: RidgeManifest, win: Window): [number, number] { + const { rMaxM } = manifest.camera; + const { planeH, horizonRow } = manifest.view; + const below = win.plane.scale * (planeH - horizonRow); + const keep = 1 + win.plane.bottom / below; // the smallest scale at which the foot stays under the viewport bottom + const nearest = Math.min(...manifest.tiles.map((row) => row[0]?.distanceM ?? Infinity)); + const back = keep >= 1 ? 0 : Math.min(rMaxM, nearest * (1 / keep - 1)); + return [-back, rMaxM]; +} + +/** What a card does on screen: its scale about the horizon and how far it is shifted sideways, viewport px, at a heading and camera angle. */ +export interface CardPose { + scale: number; + shiftPx: number; +} + +const RAD = Math.PI / 180; +const FIT_SAMPLES = 9; + +/** + * Where a card goes on a viewport: the camera stands on its circle of radius `offsetM` (signed, forward positive) at angle `phiDeg` against the heading + * `headingDeg`; a card at distance R (`ring.ts` `distanceAt` at the heading) seen from there is at angle `atan2(R sin b - r sin phi, R cos b - r cos phi)` + * from the heading for a point `b` degrees off it. A card is one flat sheet (ruling ridge-cards-per-card-slide), so that curve is fitted by the line + * `a + s b` over the viewport's arc, and the card is scaled by `s` about the horizon and shifted so the column at azimuth `az` lands at `a + s (az - heading)`. + * `shiftPx` is the translate of a container whose tiles sit at `(az - rest) x px per degree`, rest being the View's rest azimuth. + */ +export function cardPose( + manifest: RidgeManifest, + card: number, + headingDeg: number, + phiDeg: number, + offsetM: number, + win: Window +): CardPose { + const R = distanceAt(manifest, card, headingDeg); + const half = win.camera.hfovDeg / 2; + const phi = phiDeg * RAD; + let sb = 0; + let sa = 0; + let sbb = 0; + let sba = 0; + for (let i = 0; i < FIT_SAMPLES; i += 1) { + const b = (-half + (2 * half * i) / (FIT_SAMPLES - 1)) * RAD; + const a = Math.atan2(R * Math.sin(b) - offsetM * Math.sin(phi), R * Math.cos(b) - offsetM * Math.cos(phi)) / RAD; + const bd = b / RAD; + sb += bd; + sa += a; + sbb += bd * bd; + sba += bd * a; + } + const n = FIT_SAMPLES; + const s = (n * sba - sb * sa) / (n * sbb - sb * sb); + const a0 = (sa - s * sb) / n; + const { view } = manifest; return { - headingDeg, - cards: m.cards.map((c) => ({ - scale: c.scale, - reachPx: c.scale * headingDeg * m.view.pxPerDegH * win.plane.scale, - })), + scale: s, + shiftPx: win.plane.scale * view.pxPerDegH * (a0 - s * (headingDeg - view.lookAzDeg)), + }; +} + +/** + * The compass azimuths, unwrapped, of the card columns a pose puts on a viewport `viewportW` px wide: a column at `az` lands at `shiftPx + scale x (az - rest) + * x px per degree` from the centre. This is the arc the loader must hold for that card. + */ +export function cardArc( + view: View, + win: Window, + viewportW: number, + pose: CardPose +): { fromDeg: number; toDeg: number } { + const per = pose.scale * win.plane.scale * view.pxPerDegH; + return { + fromDeg: view.lookAzDeg + (-viewportW / 2 - pose.shiftPx) / per, + toDeg: view.lookAzDeg + (viewportW / 2 - pose.shiftPx) / per, }; }