diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts index 3a102f35..51f6cb87 100644 --- a/src/app/features/scene/cameraState.ts +++ b/src/app/features/scene/cameraState.ts @@ -52,6 +52,27 @@ let current: CameraChoice | undefined; type Listener = (next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean) => void; let held = false; const listeners = new Set(); + +/** A change of what turns the view (the mode, the speed or the hold), whole: the heading is integrated over the choices in force, so it takes them in the order they were made. */ +export interface CameraChange { + next: CameraChoice; + prev: CameraChoice; + at: number; + wasHeld: boolean; + /** Whether the view is held after the change. */ + held: boolean; +} +/** The changes `ridge/heading.ts` has not taken yet: kept only once it has asked (a page with no ridge scene keeps none). */ +let changes: CameraChange[] | undefined; +const NONE: readonly CameraChange[] = []; +/** Hand over the changes of what turns the view since the last call, oldest first: the one reader is the heading owner, which computes the heading from them whenever it is read, so who listens and in what order is no business of its. */ +export function takeChanges(): readonly CameraChange[] { + changes ??= []; + return changes.length ? changes.splice(0) : NONE; +} +const record = (c: CameraChange): void => { + if (c.next.mode !== c.prev.mode || c.next.speedDegPerS !== c.prev.speedDegPerS || c.held !== c.wasHeld) changes?.push(c); +}; const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); function load(): CameraChoice { @@ -89,6 +110,7 @@ export function setCamera(change: Partial, at: number = clock()): // Storage is refused: the choice holds for this page load only. } } + record({ next, prev, at, wasHeld, held }); [...listeners].forEach((cb) => cb(next, prev, at, wasHeld)); } @@ -103,6 +125,7 @@ export function holdCamera(at: number = clock()): void { if (held) return; held = true; const cam = getCamera(); + record({ next: cam, prev: cam, at, wasHeld: false, held: true }); [...listeners].forEach((cb) => cb(cam, cam, at, false)); } @@ -115,5 +138,6 @@ export function subscribe(cb: Listener): () => void { export function resetCamera(): void { current = undefined; held = false; + changes = undefined; listeners.clear(); } diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index dc33f5a6..a0207a5f 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -1,3 +1,5 @@ +import { readFileSync } from 'node:fs'; +import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createRidgeScene } from './Ridge'; import { valueNoise, hash2 } from './noise'; @@ -8,13 +10,13 @@ import { sunAt } from './sunAt'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { sunOfBand } from './skyTestkit'; import { startBackgroundScene } from '../index'; -import { parseManifest } from './manifest'; +import { parseIndex, parseManifest } from './manifest'; import { ELSEWHERE_VIEW, wireManifest } from './manifest.fixture'; import type { Arc, Backdrop, LitTile } from './Backdrop'; import type { Mock } from 'vitest'; -import { cardArc, cardPose, FALLBACK_VIEW, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; +import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; import { residentTiles } from './ring'; -import { anchor, EASE_MS, headingAt, hold, phiAt, resetHeading } from './heading'; +import { anchor, EASE_MS, headingAt, hold, phiAt, resetHeading, shownPhiAt } from './heading'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; describe('noise', () => { @@ -1059,6 +1061,141 @@ describe('the ridge cards in the scene', () => { s.dispose(); }); + describe('the ease of a mode pick stays inside the fit of the card slide', () => { + // The baked Vienna: its distances and its two bounds, as shipped. + const root = join(process.cwd(), 'public', 'ridge'); + const dir = parseIndex(JSON.parse(readFileSync(join(root, 'index.json'), 'utf8'))).places.vienna; + const vienna = parseManifest(JSON.parse(readFileSync(join(root, dir, 'manifest.json'), 'utf8')), `${dir}/`); + const FIT_PX_MAX = 24; // scripts/ridge-bake/export.py + /** The baker's `fit_px` (export.py): the worst error, in card px, of a card at distance `d` metres seen from offset `r` at camera angle `phiDeg`, against its least-squares line over the widest field. */ + const fitPx = (d: number, r: number, phiDeg: number): number => { + const n = 33; + const b = Array.from({ length: n }, (_, i) => ((-HFOV_MAX_DEG / 2 + (HFOV_MAX_DEG * i) / (n - 1)) * Math.PI) / 180); + const phi = (phiDeg * Math.PI) / 180; + const a = b.map((x) => Math.atan2(d * Math.sin(x) - r * Math.sin(phi), d * Math.cos(x) - r * Math.cos(phi))); + const mean = (v: number[]) => v.reduce((x, y) => x + y, 0) / v.length; + const bc = b.map((x) => x - mean(b)); + const s = a.reduce((acc, y, i) => acc + y * bc[i], 0) / bc.reduce((acc, y) => acc + y * y, 0); + const am = mean(a); + return (Math.max(...a.map((y, i) => Math.abs(y - (am + s * bc[i])))) * 180) / Math.PI * vienna.view.pxPerDegH; + }; + const distances = vienna.tiles.flatMap((row) => row.flatMap((e) => (e ? [e.distanceM] : []))); + /** The worst of every card of the bake at the camera angle `phiDeg` and offset `r`. */ + const worstPx = (r: number, phiDeg: number): number => Math.max(...distances.map((d) => fitPx(d, r, phiDeg))); + const w2 = windowFor(vienna.view, 400, 800); + /** The offset a keyframe's pose was made from: the one `cardPose` gives the transform at this heading and camera angle (a scan, then a finer one), with how far it is off. */ + const offsetOf = (transform: string, heading: number, phi: number): { r: number; miss: number } => { + const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; + const want = { shiftPx: Number(m[1]), scale: Number(m[2]) }; + const miss = (r: number) => { + const p = cardPose(vienna, 0, heading, phi, r, w2); + return Math.hypot(p.shiftPx - want.shiftPx, (p.scale - want.scale) * 400); + }; + let best = { r: 0, miss: Infinity }; + for (const step of [0.5, 0.02, 0.001]) { + const from = best.miss === Infinity ? -300 : best.r - 20 * step; + const to = best.miss === Infinity ? 300 : best.r + 20 * step; + for (let r = from; r <= to; r += step) { + const e = miss(r); + if (e < best.miss) best = { r, miss: e }; + } + } + return best; + }; + /** Every (camera angle, offset) a stretch of keyframes poses card 0 from, recovered from the transforms, from the pick on. */ + const pairsOf = (box: any, at: number): { phi: number; r: number; ms: number; miss: number }[] => { + const keys = live(box)[0].keyframes; + return keys.map((f: any, n: number) => { + const ms = (f.offset ?? n / (keys.length - 1)) * SEGMENT_S * 1000; + const phi = shownPhiAt(at + ms); + return { phi, ms, ...offsetOf(f.transform, headingAt(at + ms), phi) }; + }); + }; + const pick = (from: { mode: 'both' | 'offset'; speed: number; waitS: number }, to: 'both' | 'offset') => { + setCamera({ mode: from.mode, speedDegPerS: from.speed, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; + const at = T0 + from.waitS * 1000; + vi.mocked(performance.now).mockReturnValue(at); + setCamera({ mode: to }, at); + const got = pairsOf(rigOf(parent).children[2], at); + s.dispose(); + return got; + }; + + it('measures the fit as the baker does: Vienna sits at the bound at its two offsets, and above it past them', () => { + const { rMaxM, rMaxForwardM } = vienna.camera; + expect([rMaxM, rMaxForwardM]).toEqual([98.2, 205.4]); + expect(Math.max(...[0, 15, 30, 45, 90, 135, 180, 270].map((phi) => worstPx(rMaxM, phi)))).toBeGreaterThan(FIT_PX_MAX - 0.5); + expect(Math.max(...[0, 15, 30, 45, 90, 135, 180, 270].map((phi) => worstPx(rMaxM, phi)))).toBeLessThanOrEqual(FIT_PX_MAX); + expect(worstPx(rMaxForwardM, 0)).toBeGreaterThan(FIT_PX_MAX - 0.5); + expect(worstPx(rMaxForwardM, 0)).toBeLessThanOrEqual(FIT_PX_MAX); + expect(worstPx(200, 90)).toBeGreaterThan(FIT_PX_MAX); // the blend the ease used to pass through + }); + + [ + { name: 'offset-only to both from the camera a quarter round', from: { mode: 'offset', speed: 12, waitS: 7.5 }, to: 'both' }, + { name: 'offset-only to both with the camera half way round', from: { mode: 'offset', speed: 12, waitS: 15 }, to: 'both' }, + { name: 'offset-only to both with the camera just off its heading', from: { mode: 'offset', speed: 12, waitS: 1.25 }, to: 'both' }, + { name: 'both to offset-only at the default speed', from: { mode: 'both', speed: 0.6, waitS: 3 }, to: 'offset' }, + { name: 'both to offset-only at the fastest turn', from: { mode: 'both', speed: 12, waitS: 3 }, to: 'offset' }, + ].forEach(({ name, from, to }) => { + it(`${name}: every keyframe is the pose of an angle and an offset inside the card fit, at Vienna's bounds`, () => { + const got = pick(from as any, to as any); + expect(got.length).toBeGreaterThan(12); + got.forEach((g) => expect(g.miss, `a pose of the camera at ${g.phi.toFixed(1)} degrees, ${g.r.toFixed(1)} m`).toBeLessThan(0.05)); + const worst = Math.max(...got.map((g) => worstPx(g.r, g.phi))); + expect(worst).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); + // The angle and the offset take a stage each: never both between their ends at once. + const moving = (v: number[], i: number) => i > 0 && Math.abs(v[i] - v[i - 1]) > 1e-3; + const phis = got.map((g) => g.phi); + const rs = got.map((g) => g.r); + got.forEach((_, i) => expect(moving(phis, i) && moving(rs, i), `keyframe ${i}`).toBe(false)); + const last = got.at(-1)!; + expect(last.r).toBeCloseTo(to === 'both' ? 200 : vienna.camera.rMaxM, 1); // the offset owed: the default 200, or the bound of the circling mode + if (to === 'both') expect(last.phi).toBe(0); + }); + }); + }); + + describe('under reduced motion there is no ease: the pose owed is the pose issued', () => { + const owed = (ring: typeof manifest, offset: number, phi: number, at = T0) => { + const p = cardPose(ring, 0, headingAt(at), phi, offset, windowFor(ring.view, 400, 800)); + return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; + }; + + it('lands on the offset the mode allows at the pick, each way, and the next pick starts from there', () => { + const ring = fixtureRing(); + motion.matches = true; + setCamera({ mode: 'both', speedDegPerS: 0.6, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const box = () => rigOf(parent).children[2]; + expect(frame(box(), 0)).toBe(owed(ring, 200, 0)); + setCamera({ mode: 'offset' }); + expect(frame(box(), 0)).toBe(owed(ring, 98.2, 0)); // the clamp, at once: not the 200 m it showed + setCamera({ mode: 'both' }); + expect(frame(box(), 0)).toBe(owed(ring, 200, 0)); // and back, not the 98.2 it was left at + s.dispose(); + }); + + it('lands on the camera angle the mode owes when the setting arrives with the camera turned away from its heading', () => { + const ring = fixtureRing(); + setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); + const { parent, canvas } = host(); + const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; + const at = T0 + 7_500; // a quarter round + vi.mocked(performance.now).mockReturnValue(at); + motion.matches = true; + motion.addEventListener.mock.calls.filter((c: any) => c[0] === 'change').forEach((c: any) => c[1]()); + expect(phiAt(at)).toBeCloseTo(90, 6); + setCamera({ mode: 'both' }, at); + expect(phiAt(at + 10_000)).toBe(0); + expect(frame(rigOf(parent).children[2], 0)).toBe(owed(ring, 200, 0, at)); + s.dispose(); + }); + }); + it('keeps the angles, the transforms and the tile positions bounded after days of uptime: the rig normalizes before each stretch', () => { const now = vi.mocked(performance.now); const { parent, canvas } = host(); diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index d26186d5..fd1cbae4 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -7,7 +7,7 @@ import { cardArc, cardPose, offsetRange, SEGMENT_S, sweepArc, windowFor } from ' import type { CardPose, View } from './view'; import type { TileCard } from './manifest'; import { residentTiles } from './ring'; -import { easeEndsAt, easeLeft, EASE_MS, freeze, headingAt, normalize, phiAt, shownPhiAt, subscribe as onHeading } from './heading'; +import { easeEndsAt, easeLeft, freeze, headingAt, normalize, offsetFreeAt, phiAt, shownPhiAt, STAGE_MS, subscribe as onHeading } from './heading'; import { effectiveMode, getCamera, subscribe as onCamera } from '../cameraState'; import { activeAt, drawTwinkle as paintTwinkle, Star } from './stars'; import { nightBodies, paintNightBodies } from './nightBodies'; @@ -304,12 +304,15 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { } const anims: (Animation | undefined)[] = new Array(k).fill(undefined); freeze(reducedMotion?.matches === true, clock()); // reduced motion turns nothing, whatever the viewer chose - // The offset the cards are posed at is eased, as the camera's angle is (`heading.ts` `shownPhiAt`): when the clamp moves it (a mode that keeps the camera on - // its heading lets a forward offset go further), the view goes from the offset it showed to the new one over EASE_MS instead of jumping. + // The offset the cards are posed at is eased, as the camera's angle is (`heading.ts` `shownPhiAt`) but not with it: when the clamp moves it (a mode that keeps the + // camera on its heading lets a forward offset go further), it goes from the offset it showed to the new one in a stage of its own, STAGE_MS from `offsetAt`, the + // moment the angle lets it. Every pose between is a pose of the camera at an angle and an offset the mode's bound holds, never a blend of two. Reduced motion has + // no ease: the offset asked for is the one shown. let offset = offsetNow(bd, win); let offsetFrom = offset; - let offsetEase = -Infinity; - const offsetShown = (t: number): number => offset + (offsetFrom - offset) * easeLeft(offsetEase, t); + let offsetAt = -Infinity; + const calm = (): boolean => reducedMotion?.matches === true; + const offsetShown = (t: number): number => (calm() ? offset : offset + (offsetFrom - offset) * easeLeft(offsetAt, t)); const poseAt = (card: number, t: number): CardPose => cardPose(bd.manifest, card, headingAt(t), shownPhiAt(t), offsetShown(t), win); const transform = (p: CardPose) => `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; @@ -325,12 +328,12 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null { if (next !== offset) { offsetFrom = offsetShown(t0); offset = next; - offsetEase = t0; + offsetAt = Math.max(t0, offsetFreeAt()); } issuedAt = t0; - const frozen = reducedMotion?.matches === true; + const frozen = calm(); // A stretch with an ease in it is keyed finely while the ease runs (its keyframes at explicit offsets of the stretch), a second apart after. - const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, easeEndsAt(), offsetEase + EASE_MS) - t0); + const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, easeEndsAt(), offsetAt + STAGE_MS) - t0); const times = easeMs > 0 && !frozen ? easeTimes(easeMs) : null; for (let i = 0; i < k; i += 1) { const frames: Keyframe[] = frozen diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts index 98a3a23b..15173041 100644 --- a/src/app/features/scene/ridge/heading.test.ts +++ b/src/app/features/scene/ridge/heading.test.ts @@ -1,5 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { anchor, EASE_MS, easeEndsAt, freeze, headingAt, hold, normalize, phiAt, resetHeading, setSpeedLimit, shownPhiAt, subscribe } from './heading'; +import { anchor, EASE_MS, easeEndsAt, freeze, headingAt, hold, normalize, offsetFreeAt, phiAt, resetHeading, setSpeedLimit, shownPhiAt, STAGE_MS, subscribe } from './heading'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState'; import { maxSpeed } from './view'; import { parseManifest } from './manifest'; @@ -211,18 +211,35 @@ describe('the heading owner', () => { expect(headingAt(10 * S)).toBeCloseTo(214 + 10 * slow, 9); }); - it('settles before a listener that was added after it reads it, however often the place is anchored again', () => { + it('answers the same to a listener of the camera whenever it registered: the heading is computed at read from the clock and the changes, not from state a listener may reach before it is settled', () => { setCamera({ mode: 'both', speedDegPerS: 1 }, 0); + const early: number[] = []; + const offEarly = onCamera((_n, _p, at) => early.push(headingAt(at))); // subscribed before the place is anchored: the first of the listeners, as a control mounted before the scene start is anchor('p', 214, 0); - let read = NaN; - const off = onCamera((_next, _prev, at) => (read = headingAt(at))); // the old rig: subscribed after the owner - anchor('p', 214, 1 * S); // a rebuild for a sky re-binds the owner: it must keep its place in the order - setCamera({ mode: 'still' }, 2 * S); - expect(read).toBeCloseTo(214 + 2, 9); // the heading at the change, not the one the last settle left - off(); + const late: number[] = []; + const offLate = onCamera((_n, _p, at) => late.push(headingAt(at))); + anchor('p', 214, 1 * S); // a rebuild for a sky anchors the same place again + setCamera({ speedDegPerS: 4 }, 5 * S); + expect(headingAt(10 * S)).toBeCloseTo(214 + 5 + 20, 9); + setCamera({ mode: 'still' }, 11 * S); + expect(early).toEqual(late); + expect(early[0]).toBeCloseTo(214 + 5, 9); // the heading at the change, with the speed it had until it + expect(early[1]).toBeCloseTo(214 + 5 + 24, 9); + offEarly(); + offLate(); }); - it('eases a pick of the turning mode: the angle shown starts where the viewer saw it and ends where the camera goes, the kinematics never wait for it', () => { + it('takes the changes made between two reads in order, each at its own moment', () => { + anchor('p', 100, 0); + choose('both', 2, 0); + choose('both', 4, 3 * S); // 6 degrees by then + choose('offset', 4, 5 * S); // 14 degrees: the view stops, the camera starts + choose('both', 1, 7 * S); // the camera went 8 degrees round, and is put back on its heading + expect(headingAt(9 * S)).toBeCloseTo(100 + 14 + 2, 9); + expect(phiAt(9 * S)).toBe(0); + }); + + it('eases a pick to a forward mode in two stages: the angle first, the offset let out after it, and the kinematics never wait for either', () => { anchor('p', 100, 0); choose('offset', 12, 0); expect(phiAt(7.5 * S)).toBeCloseTo(90, 9); @@ -231,9 +248,11 @@ describe('the heading owner', () => { expect(phiAt(at)).toBe(0); // where it is going expect(shownPhiAt(at)).toBeCloseTo(90, 9); // what is seen at the instant of the pick expect(easeEndsAt()).toBe(at + EASE_MS); - const shown = [0, 0.25, 0.5, 0.75, 1].map((x) => shownPhiAt(at + x * EASE_MS)); + expect(offsetFreeAt()).toBe(at + STAGE_MS); // the offset waits for the angle + const shown = [0, 0.25, 0.5, 0.75, 1].map((x) => shownPhiAt(at + x * STAGE_MS)); shown.slice(1).forEach((v, i) => expect(v).toBeLessThan(shown[i])); - expect(shown[4]).toBe(0); + expect(shown[4]).toBe(0); // the angle is home when the offset starts + expect(shownPhiAt(at + EASE_MS)).toBe(0); expect(shownPhiAt(at + 10 * S)).toBe(0); // The way round is the short one: 270 degrees on is a pick that eases 90 forward. choose('offset', 12, at + 10 * S); @@ -241,8 +260,40 @@ describe('the heading owner', () => { expect(phiAt(t) % 360).toBeCloseTo(270, 9); choose('both', 12, t); expect(shownPhiAt(t)).toBeCloseTo(phiAt(t) + (-90), 9); - // A pick that changes nothing the viewer sees eases nothing; a hold in the mode the camera circles in keeps its angle. + // A speed that changes nothing the viewer sees eases nothing. choose('both', 6, t + 10 * S); expect(shownPhiAt(t + 10 * S + 1)).toBeCloseTo(0, 6); }); + + it('eases a pick to the offset-only mode in two stages the other way: the offset comes in first with the camera held where it stood, then the angle is let go', () => { + anchor('p', 100, 0); + choose('both', 12, 0); + choose('offset', 12, 10 * S); + const at = 10 * S; + expect(offsetFreeAt()).toBe(at); // the offset goes at once + expect(phiAt(at + 3 * S)).toBeCloseTo(36, 9); // the camera is going round ... + [0, 0.5, 1].forEach((x) => expect(shownPhiAt(at + x * STAGE_MS)).toBe(0)); // ... and is seen where it stood while the offset comes in + const after = [0, 0.25, 0.5, 0.75, 1].map((x) => shownPhiAt(at + STAGE_MS + x * STAGE_MS)); + after.slice(1).forEach((v, i) => expect(v).toBeGreaterThan(after[i])); + expect(shownPhiAt(at + EASE_MS)).toBeCloseTo(phiAt(at + EASE_MS), 9); // and has caught up when the ease is spent + expect(shownPhiAt(at + 10 * S)).toBeCloseTo(phiAt(at + 10 * S), 9); + }); + + it('has no ease under reduced motion: the angle owed is the angle shown at once, and one begun before is cut short', () => { + anchor('p', 100, 0); + choose('offset', 12, 0); + freeze(true, 0); + hold(100, 1); // frozen: nothing turned + freeze(false, 2); + choose('offset', 12, 3); + const t = 10 * S; + choose('both', 12, t); + expect(shownPhiAt(t + 1)).not.toBeCloseTo(phiAt(t + 1), 3); // an ease is under way (the camera had turned) + freeze(true, t + 2); + expect(shownPhiAt(t + 3)).toBe(phiAt(t + 3)); + setCamera({ mode: 'offset', speedDegPerS: 12 }, t + 4); + setCamera({ mode: 'both', speedDegPerS: 12 }, t + 5); + expect(shownPhiAt(t + 6)).toBe(0); + expect(easeEndsAt()).toBe(0); + }); }); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts index 7c1d88a9..d92d1f43 100644 --- a/src/app/features/scene/ridge/heading.ts +++ b/src/app/features/scene/ridge/heading.ts @@ -5,15 +5,20 @@ // // The rotation mode, its speed and the hold are not held here: they are the viewer's choice and the session's hold, `cameraState.ts`, the one owner. This // module keeps only where the view and the camera were at the clock `t0` and integrates them under the mode in effect since (the chosen mode, 'still' while -// held), with the speed bounded to what the baked place sustains in that mode (`setSpeedLimit`, derived at every read, never stored), so it listens to -// cameraState and takes the anchor to the moment of each change. A rebuild keeps the hold; a reload (a Return) does not. +// held), with the speed bounded to what the baked place sustains in that mode (`setSpeedLimit`, derived at every read, never stored). It does not listen: +// every read takes the changes the viewer made since the last one from `cameraState` (`takeChanges`) and folds them in, each at its own moment, before it answers, +// so the heading is a function of the clock and of those changes whoever else listens to the camera and in whatever order. A rebuild keeps the hold; a reload +// (a Return) does not. // // 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). `phi` is 0 whenever the view direction turns -// with the camera ('both'): picking that mode returns the camera to its heading, eased over EASE_MS: `phiAt` is where the camera is going, `shownPhiAt` -// the angle the viewer sees while it gets there (the one the rig poses the cards from), so a pick moves the view and never jumps it. -import { getCamera, holdCamera, isHeld, subscribe as onCamera } from '../cameraState'; -import type { CameraChoice } from '../cameraState'; +// with the camera ('both'): picking that mode returns the camera to its heading. A change of mode eases the view over two stages of STAGE_MS, the camera's +// angle and its offset one after the other, never together (the fit of a card's linear slide holds along the angle at a fixed offset, and along the offset at +// the angle the mode keeps; blended, they leave it): `phiAt` is where the camera is going, `shownPhiAt` the angle the viewer sees while it gets there (the one +// the rig poses the cards from), and `offsetFreeAt` the moment the offset may start. A pick that stands the camera on its heading turns it first and lets +// the offset out after; a pick that takes it off the heading brings the offset in first and lets the camera go after. +import { getCamera, holdCamera, isHeld, takeChanges } from '../cameraState'; +import type { CameraChange, CameraChoice } from '../cameraState'; /** `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'; @@ -25,24 +30,27 @@ interface State { 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; - /** The camera's angle the viewer still sees beyond where it is going: `delta` degrees at `at` (ms), gone by `at + EASE_MS`. A change of mode sets it; the kinematics never read it. */ - ease: { delta: number; at: number } | undefined; - /** Nothing turns, whatever the viewer chose (the OS asks for reduced motion): an override of the environment, not a second copy of the choice. */ + /** + * The ease a change of mode began at `at` (ms): the angle the viewer saw then, `from` (unwrapped, within half a turn of where the camera was going), and + * whether the angle goes in the first stage (the camera is going to stand on its heading) or the second. The kinematics never read it. + */ + ease: { from: number; at: number; phiFirst: boolean } | undefined; + /** Nothing turns, whatever the viewer chose (the OS asks for reduced motion): an override of the environment, not a second copy of the choice. There is no ease then: the pose asked for is shown at once. */ frozen: boolean; } const initial = (): State => ({ h0: 0, phi0: 0, t0: 0, anchor: undefined, ease: undefined, frozen: false }); -/** How long a change of mode takes to carry the view to its new pose, ms. */ -export const EASE_MS = 600; -/** What is left of an ease that began at `at` (ms), from 1 down to 0 at `at + EASE_MS` (smoothstep): the one curve of the view's easing, the rig's offset included. */ +/** How long one stage of the ease takes, ms, and the whole of it: the angle and the offset a stage each. */ +export const STAGE_MS = 300; +export const EASE_MS = 2 * STAGE_MS; +/** What is left of a stage that began at `at` (ms), from 1 down to 0 at `at + STAGE_MS` (smoothstep): the one curve of the view's easing, the rig's offset included. */ export const easeLeft = (at: number, now: number): number => { - const x = Math.min(1, Math.max(0, (now - at) / EASE_MS)); + const x = Math.min(1, Math.max(0, (now - at) / STAGE_MS)); return 1 - x * x * (3 - 2 * x); }; let state = initial(); const listeners = new Set<() => void>(); -let unbind: (() => void) | undefined; /** The largest speed a mode may turn at here: the baked place's bound (`view.ts` `maxSpeed`), set by the scene that knows the place; none until then. */ type SpeedLimit = (mode: RotationMode) => number; @@ -55,69 +63,88 @@ const speedOf = (cam: CameraChoice): number => { return Math.sign(cam.speedDegPerS) * Math.min(Math.abs(cam.speedDegPerS), limit); }; const advanced = (now: number, cam: CameraChoice): number => (speedOf(cam) * (now - state.t0)) / 1000; -const headingUnder = (now: number, cam: CameraChoice, held = isHeld()): number => +const headingUnder = (now: number, cam: CameraChoice, held: boolean): number => state.h0 + (turning(cam, held, state.frozen) === 'both' ? advanced(now, cam) : 0); -const phiUnder = (now: number, cam: CameraChoice, held = isHeld()): number => +const phiUnder = (now: number, cam: CameraChoice, held: boolean): number => state.phi0 + (turning(cam, held, state.frozen) === 'offset' ? advanced(now, cam) : 0); - -/** The view direction at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */ -export const headingAt = (now: number): number => headingUnder(now, getCamera()); -/** The camera's angle on its circle against the heading at `now`, degrees, as `headingAt`: where it is going, which the offset's clamp follows. */ -export const phiAt = (now: number): number => phiUnder(now, getCamera()); -const easeTerm = (now: number): number => (state.ease ? state.ease.delta * easeLeft(state.ease.at, now) : 0); -/** The angle the viewer sees at `now`: `phiAt` plus what is left of the ease a change of mode began. The rig poses the cards from it. */ -export const shownPhiAt = (now: number): number => phiAt(now) + easeTerm(now); -/** The clock (ms) at which the last ease is spent; 0 when none was begun. */ -export const easeEndsAt = (): number => (state.ease ? state.ease.at + EASE_MS : 0); +/** The angle shown at `now` under a choice: from the angle the viewer saw at the pick to where the camera is going by then, in the stage the ease gives the angle. */ +const shownUnder = (now: number, cam: CameraChoice, held: boolean): number => { + const phi = phiUnder(now, cam, held); + const e = state.ease; + if (!e) return phi; + const left = easeLeft(e.phiFirst ? e.at : e.at + STAGE_MS, now); + return e.from + (phi - e.from) * (1 - left); +}; const emit = () => [...listeners].forEach((cb) => cb()); /** Take `h`, `phi` and the clock to `now` under the choice `cam` in force until now: the one way a value is replaced, so no change makes the view jump. */ -function settle( - now: number, - cam: CameraChoice, - over: Partial = {}, - h = headingUnder(now, cam), - phi = phiUnder(now, cam) -): void { +function settle(now: number, cam: CameraChoice, held: boolean, over: Partial = {}, h = headingUnder(now, cam, held), phi = phiUnder(now, cam, held)): void { state = { ...state, ...over, h0: h, phi0: phi, t0: now }; } -/** A change of the viewer's choice lands on the anchor at the moment it is made. */ -function onChange(next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean): void { - // Taken to the moment of the change under the choice and hold in force until it; picking 'both' puts the camera on its heading, and the angle the viewer - // saw until then is eased out (by the shortest way round) instead of dropped. - const shown = phiUnder(at, prev, wasHeld) + easeTerm(at); - settle(at, prev, {}, headingUnder(at, prev, wasHeld), next.mode === 'both' && !isHeld() ? 0 : phiUnder(at, prev, wasHeld)); +/** + * A change of the viewer's choice lands on the anchor at the moment it is made, under the choice and hold in force until it. Picking 'both' puts the camera on + * its heading; a change of mode or of the hold begins an ease from the angle the viewer saw (by the shortest way round), none under reduced motion. + */ +function apply({ next, prev, at, wasHeld, held }: CameraChange): void { + const shown = shownUnder(at, prev, wasHeld); + const onHeading = next.mode === 'both' && !held; + settle(at, prev, wasHeld, {}, headingUnder(at, prev, wasHeld), onHeading ? 0 : phiUnder(at, prev, wasHeld)); + if (next.mode === prev.mode && held === wasHeld) return; // a speed: the angle and the ease, if one is under way, go on const gap = shown - state.phi0; - const delta = gap - 360 * Math.round(gap / 360); - state = { ...state, ease: Math.abs(delta) < 1e-9 ? undefined : { delta, at } }; + const from = state.phi0 + gap - 360 * Math.round(gap / 360); + state = { ...state, ease: state.frozen ? undefined : { from, at, phiFirst: onHeading } }; } -/** - * Listen to the viewer's choice (again, if a test cleared the listeners). The listener is one function, so listening again keeps its place in the order - * cameraState calls them: the owner settles before any listener that was added after it reads it. - */ -function bind(): void { - unbind = onCamera(onChange); +/** Fold in what the viewer changed since the last read, each at its own moment: every read answers from the choices in force, whatever listened to them first. */ +function catchUp(): void { + takeChanges().forEach(apply); +} + +/** The view direction at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */ +export function headingAt(now: number): number { + catchUp(); + return headingUnder(now, getCamera(), isHeld()); +} +/** The camera's angle on its circle against the heading at `now`, degrees, as `headingAt`: where it is going, which the offset's clamp follows. */ +export function phiAt(now: number): number { + catchUp(); + return phiUnder(now, getCamera(), isHeld()); +} +/** The angle the viewer sees at `now`: `phiAt` while the ease a change of mode began is not under way, between the angle seen at the pick and it while it is. The rig poses the cards from it. */ +export function shownPhiAt(now: number): number { + catchUp(); + return shownUnder(now, getCamera(), isHeld()); +} +/** The clock (ms) at which the last ease is spent; 0 when none was begun. */ +export function easeEndsAt(): number { + catchUp(); + return state.ease ? state.ease.at + EASE_MS : 0; +} +/** The clock (ms) from which the offset may move for the last change of mode: its stage, after the angle's when the camera is going to stand on its heading, at once otherwise; 0 when none was begun. */ +export function offsetFreeAt(): number { + catchUp(); + return state.ease ? state.ease.at + (state.ease.phiFirst ? STAGE_MS : 0) : 0; } /** Bound the speed in each mode to what the baked place sustains (`view.ts` `maxSpeed`); the anchor is taken to now first, so nothing jumps. */ export function setSpeedLimit(limit: SpeedLimit | undefined, now: number): void { - settle(now, getCamera()); + catchUp(); + settle(now, getCamera(), isHeld()); speedLimit = limit; } /** * 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). Also starts listening to the viewer's choice and, given - * `limit` (what the baked place sustains, `view.ts` `maxSpeed`), bounds the speed from this moment, before anything awaits the place's tiles. + * with the camera on its heading. The same place again changes nothing (a rebuild for a sky keeps the heading). Given `limit` (what the baked place sustains, + * `view.ts` `maxSpeed`), it bounds the speed from this moment, before anything awaits the place's tiles. */ export function anchor(key: string, restDeg: number, now: number, limit?: SpeedLimit): void { - bind(); + catchUp(); if (limit) setSpeedLimit(limit, now); // before the view is let to turn: the bound is known from the first read if (state.anchor === key) return; - settle(now, getCamera(), { anchor: key, ease: undefined }, restDeg, 0); + settle(now, getCamera(), isHeld(), { anchor: key, ease: undefined }, restDeg, 0); emit(); } @@ -127,17 +154,19 @@ export function anchor(key: string, restDeg: number, now: number, limit?: SpeedL * already chosen included, resumes it. */ export function hold(h: number, now: number): void { + catchUp(); const wasHeld = isHeld(); - settle(now, getCamera(), {}, h); + settle(now, getCamera(), wasHeld, {}, h); if (wasHeld) emit(); else holdCamera(now); // the camera's listeners tell everyone, once } -/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view stays where it is. */ +/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view stays where it is, and what was easing is shown where it is going. */ export function freeze(on: boolean, now: number): void { + catchUp(); if (on === state.frozen) return; - settle(now, getCamera()); - state = { ...state, frozen: on }; + settle(now, getCamera(), isHeld()); + state = { ...state, frozen: on, ease: on ? undefined : state.ease }; } /** @@ -145,9 +174,13 @@ export function freeze(on: boolean, now: number): void { * are laid out from them, so their positions and the transforms stay small however long the page has been open. Silent: the caller lays out again. */ export function normalize(now: number): void { + catchUp(); const cam = getCamera(); + const held = isHeld(); const wrap = (x: number): number => x - 360 * Math.floor(x / 360); - settle(now, cam, {}, wrap(headingUnder(now, cam)), wrap(phiUnder(now, cam))); + const phi = phiUnder(now, cam, held); + const turns = wrap(phi) - phi; + settle(now, cam, held, { ease: state.ease && { ...state.ease, from: state.ease.from + turns } }, wrap(headingUnder(now, cam, held)), phi + turns); } /** Hear every change of the kinematics that the viewer's choice does not announce (a manual turn while still, a new place); returns the way to stop. */ @@ -158,8 +191,6 @@ export function subscribe(cb: () => void): () => void { /** For tests: the state of a fresh page. */ export function resetHeading(): void { - unbind?.(); - unbind = undefined; speedLimit = undefined; state = initial(); listeners.clear();