From c6e49fdb47cf3798c0c2b7c340b566c86c2a8037 Mon Sep 17 00:00:00 2001 From: Meta Vens Date: Thu, 3 Dec 2026 21:56:40 +0100 Subject: [PATCH] teardown(R3): remove bindOwner circular hack and 2-stage ease in camera/heading/Ridge --- src/app/features/scene/cameraState.test.ts | 19 - src/app/features/scene/cameraState.ts | 17 +- src/app/features/scene/ridge/Ridge.test.ts | 362 +------------------ src/app/features/scene/ridge/Ridge.ts | 19 +- src/app/features/scene/ridge/heading.test.ts | 219 ++--------- src/app/features/scene/ridge/heading.ts | 128 +++---- 6 files changed, 103 insertions(+), 661 deletions(-) diff --git a/src/app/features/scene/cameraState.test.ts b/src/app/features/scene/cameraState.test.ts index 6bbb9f02..c09331c1 100644 --- a/src/app/features/scene/cameraState.test.ts +++ b/src/app/features/scene/cameraState.test.ts @@ -1,7 +1,5 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import * as camera from './cameraState'; import { - bindOwner, CAMERA_KEY, DEFAULT_CAMERA, effectiveMode, @@ -74,23 +72,6 @@ describe('the viewer camera', () => { expect(cb).toHaveBeenCalledWith({ ...DEFAULT_CAMERA, mode: 'offset' }, DEFAULT_CAMERA, 1234, false); }); - it('hands a change to the owner before any listener, at its clock, whenever the listeners registered, and keeps no log of it', () => { - const order: string[] = []; - subscribe(() => order.push('early')); - bindOwner((at) => order.push(`owner ${at}`)); - subscribe(() => order.push('late')); - setCamera({ offsetM: 5 }, 42); - holdCamera(43); - setCamera({ mode: 'both' }, 44); // picking a mode ends the hold - setCamera({ offsetM: 5 }, 45); // nothing changed - expect(order).toEqual(['owner 42', 'early', 'late', 'owner 43', 'early', 'late', 'owner 44', 'early', 'late']); - resetCamera(); // a reload of the choice does not unbind the owner: it outlives the scenes - setCamera({ offsetM: 9 }, 50); - expect(order.at(-1)).toBe('owner 50'); - expect(Object.keys(camera)).not.toContain('takeChanges'); - bindOwner(undefined); - }); - it('a hold is session state: the mode in effect is still, the chosen mode is untouched and stored as chosen, and a reload does not hold', () => { setCamera({ mode: 'offset', speedDegPerS: 2 }); const cb = vi.fn(); diff --git a/src/app/features/scene/cameraState.ts b/src/app/features/scene/cameraState.ts index 8d09216b..a85e4188 100644 --- a/src/app/features/scene/cameraState.ts +++ b/src/app/features/scene/cameraState.ts @@ -2,8 +2,10 @@ // chosen mode, speed and offset (persisted, never rewritten by anything but the viewer: the clamp on the offset, `ridge/view.ts` `offsetRange`, and the bound // on the speed, `maxSpeed`, are derived from them at read for the mode and the bake in force) and of the hold: a manual turn (`ridge/heading.ts` `hold`) makes the // mode in effect 'still' until the viewer picks a mode, the one already chosen included. The hold is session state: a rebuild keeps it, a reload does not -// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime), as placeState and skyState are. -import type { RotationMode } from './ridge/heading'; +// (a reload is a Return). `ridge/heading.ts` integrates the view direction over the mode in effect. Main-chunk safe (no ridge code is imported at runtime). + +/** `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'; export const CAMERA_KEY = 'ratatoskr.camera'; @@ -52,15 +54,6 @@ let current: CameraChoice | undefined; type Listener = (next: CameraChoice, prev: CameraChoice, at: number, wasHeld: boolean) => void; let held = false; const listeners = new Set(); -/** - * The one reader that must have taken a change before anyone else hears of it: the heading owner (`ridge/heading.ts`), which starts a new segment of the view's - * motion at the clock `at`. Called synchronously by the change, before every listener, so no order of registration can put a listener ahead of it, and nothing is - * queued. Cleared by nothing: the owner outlives the scenes and the choice. - */ -let owner: ((at: number) => void) | undefined; -export const bindOwner = (cb: ((at: number) => void) | undefined): void => { - owner = cb; -}; const clock = (): number => (typeof performance !== 'undefined' ? performance.now() : Date.now()); function load(): CameraChoice { @@ -98,7 +91,6 @@ export function setCamera(change: Partial, at: number = clock()): // Storage is refused: the choice holds for this page load only. } } - owner?.(at); [...listeners].forEach((cb) => cb(next, prev, at, wasHeld)); } @@ -113,7 +105,6 @@ export function holdCamera(at: number = clock()): void { if (held) return; held = true; const cam = getCamera(); - owner?.(at); [...listeners].forEach((cb) => cb(cam, cam, at, false)); } diff --git a/src/app/features/scene/ridge/Ridge.test.ts b/src/app/features/scene/ridge/Ridge.test.ts index b96a045c..48c0205d 100644 --- a/src/app/features/scene/ridge/Ridge.test.ts +++ b/src/app/features/scene/ridge/Ridge.test.ts @@ -1,5 +1,3 @@ -import { readFileSync } from 'node:fs'; -import { join } from 'node:path'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; import { createRidgeScene, RESIDENCY_MS } from './Ridge'; import { hash2 } from './noise'; @@ -9,19 +7,17 @@ import { sunAt } from './sunAt'; import { makePhysicalSky, paintSky as paintPhysicalSky } from './physicalSky'; import { sunOfBand } from './skyTestkit'; import { startBackgroundScene } from '../index'; -import { parseIndex, parseManifest } from './manifest'; +import { 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, HFOV_MAX_DEG, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view'; +import { cardArc, cardPose, FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed, offsetRange, windowFor } from './view'; import { LATENESS_S, plateCamera, plateSize, SLACK_MIN_DEG, slackFor } from './skyTurn'; import { ringAzimuth, sunColumns, sunInColumn } from './lightCards'; import { norm, residentTiles } from './ring'; -import { anchor, hold, poseAt, resetHeading, settledAt, STAGE_MS } from './heading'; +import { anchor, hold, poseAt, resetHeading } from './heading'; import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; -/** The two stages of the ease of a mode pick (the angle, then the offset, or the other way round). */ -const EASE_MS = 2 * STAGE_MS; /** A card's pose as the heading owner has the view at `t`: what the rig lays the card out from. */ const posed = (m: Parameters[0], card: number, t: number, w: Parameters[5]) => { const p = poseAt(t); @@ -1254,361 +1250,41 @@ describe('the ridge cards in the scene', () => { setCamera({ mode: 'offset', speedDegPerS: 0.6, offsetM: 200 }); const { parent, canvas } = host(); const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!; - const posed = (offset: number) => { + const poseTransform = (offset: number) => { const p = cardPose(ring, 0, poseAt(T0).h, poseAt(T0).phi, offset, w2); return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; }; - expect(frame(rigOf(parent).children[2], 0)).toBe(posed(98.2)); + expect(frame(rigOf(parent).children[2], 0)).toBe(poseTransform(98.2)); expect(getCamera().offsetM).toBe(200); setCamera({ mode: 'both' }); expect(getCamera().offsetM).toBe(200); const keys = live(rigOf(parent).children[2])[0].keyframes; - expect(keys[0].transform).toBe(posed(98.2)); // the view leaves from the offset it showed (the pick does not move it) ... - const p = cardPose(ring, 0, poseAt(T0 + STAGE_MS).h, 0, 200, w2); - expect(keys.find((f: any) => f.offset >= STAGE_MS / (SEGMENT_S * 1000) - 1e-9).transform).toBe(`translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`); // ... and is at 200 when the ease is spent + expect(keys).toHaveLength(31); + expect(keys[0].transform).toBe(poseTransform(200)); s.dispose(); }); - it('eases a mode pick: the view the viewer saw is the first frame, the new regime the frame an EASE_MS later, one animation and no timer of its own', () => { + it('keeps every mode switch and rebuild clamped inside offsetRange and matching poseAt', () => { const ring = fixtureRing(); const w2 = windowFor(ring.view, 400, 800); 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; // 90 degrees round its circle at 12 degrees a second, at the offset 98.2 the mode clamps to - const tf = (ms: number, phi: number, offset: number) => { - const p = cardPose(ring, 0, poseAt(at + ms).h, phi, offset, w2); - return { text: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`, scale: p.scale }; - }; - expect(poseAt(at).phi).toBeCloseTo(90, 6); - const seen = tf(0, poseAt(at).phi, 98.2); + const at = T0 + 7_500; vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode: 'both' }, at); // phi goes to 0 and the clamp releases to 200: both used to land in one frame - const run = live(rigOf(parent).children[2])[0]; - expect(run.keyframes[0].transform).toBe(seen.text); - const spent = EASE_MS / (SEGMENT_S * 1000); - const end = run.keyframes.find((f: any) => f.offset >= spent - 1e-9); - const there = tf(EASE_MS, 0, 200); - expect(end.transform).toBe(there.text); - const eased = run.keyframes.filter((f: any) => f.offset <= spent + 1e-9); - expect(eased.length).toBeGreaterThan(10); // keyed finely while it runs - const scale = (f: any) => parseFloat(/scale\(([^)]*)\)/.exec(f.transform)![1]); - const jump = Math.abs(there.scale - seen.scale); - expect(jump).toBeGreaterThan(0.05); // the pop this pick used to be - eased.slice(1).forEach((f: any, i: number) => expect(Math.abs(scale(f) - scale(eased[i]))).toBeLessThan(jump / 4)); - expect(run.keyframes.at(-1).offset).toBe(1); + setCamera({ mode: 'both' }, at); + expect(poseAt(at)).toMatchObject({ phi: 0, r: 200 }); + const [loBoth, hiBoth] = offsetRange(ring, w2, 'both', poseAt(at).phi); + expect(poseAt(at).r).toBeGreaterThanOrEqual(loBoth); + expect(poseAt(at).r).toBeLessThanOrEqual(hiBoth); + const keys = live(rigOf(parent).children[2])[0].keyframes; + expect(keys).toHaveLength(31); + const p0 = cardPose(ring, 0, poseAt(at).h, poseAt(at).phi, poseAt(at).r, w2); + expect(keys[0].transform).toBe(`translate3d(${p0.shiftPx}px,0,0) scale(${p0.scale})`); 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 best line over the widest field, the continuous error (the line by the trapezoid rule on 1025 samples, the error on the same). */ - const fitPx = (d: number, r: number, phiDeg: number, n = 1025): number => { - const phi = (phiDeg * Math.PI) / 180; - const half = (HFOV_MAX_DEG * Math.PI) / 360; - const b = Array.from({ length: n }, (_, i) => -half + (2 * half * i) / (n - 1)); - const a = b.map((x) => Math.atan2(d * Math.sin(x) - r * Math.sin(phi), d * Math.cos(x) - r * Math.cos(phi))); - const w = (i: number) => (i === 0 || i === n - 1 ? 0.5 : 1); - let sw = 0; - let sa = 0; - let sab = 0; - let sbb = 0; - a.forEach((y, i) => { - sw += w(i); - sa += w(i) * y; - sab += w(i) * y * b[i]; - sbb += w(i) * b[i] * b[i]; - }); - const mean = sa / sw; - const s = sab / sbb; - return (Math.max(...a.map((y, i) => Math.abs(y - (mean + s * b[i])))) * 180) / Math.PI * vienna.view.pxPerDegH; - }; - // The baker holds r_max for the NEAREST solid terrain each card draws in each tile, not its median distance_m (export.py pack); the manifest carries only the median. - // Vienna's nearest solid pixel is 500.4523 m (the baker's report, in every card 0 tile terrain stands at the 500 m near clip to within a metre), so that is the distance that binds, beside the medians. - const NEAREST_TERRAIN_M = 500.4523; - const distances = [NEAREST_TERRAIN_M, ...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))); - /** The same over the six nearest cards and 129 samples (the trapezoid rule is exact to a few thousandths of a pixel there): the nearest cards bind, and a property run asks it thousands of times. */ - const nearest = [...distances].sort((a, b) => a - b).slice(0, 6); - const quickPx = (r: number, phiDeg: number): number => Math.max(...nearest.map((d) => fitPx(d, r, phiDeg, 129))); - 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 = poseAt(at + ms).phi; - return { phi, ms, ...offsetOf(f.transform, poseAt(at + ms).h, 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([95.8, 198.4]); - const circle = Array.from({ length: 24 }, (_, i) => i * 15); - expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeGreaterThan(FIT_PX_MAX - 0.5); - expect(Math.max(...circle.map((phi) => worstPx(rMaxM, phi)))).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - expect(worstPx(rMaxForwardM, 0)).toBeGreaterThan(FIT_PX_MAX - 0.5); - expect(worstPx(rMaxForwardM, 0)).toBeLessThanOrEqual(FIT_PX_MAX + 0.05); - expect(worstPx(200, 90)).toBeGreaterThan(FIT_PX_MAX); // the blend the ease used to pass through - expect(worstPx(rMaxForwardM + 1, 0)).toBeGreaterThan(FIT_PX_MAX); // past the forward bound, and the circle's bound is not the forward one - expect(Math.max(...circle.map((phi) => worstPx(rMaxM + 1, phi)))).toBeGreaterThan(FIT_PX_MAX); - }); - - [ - { 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' ? Math.min(200, vienna.camera.rMaxForwardM) : vienna.camera.rMaxM, 1); // the offset owed: the default 200 or the forward bound, or the bound of the circling mode - if (to === 'both') expect(last.phi % 360).toBe(0); - }); - }); - - /** A transform's two numbers. */ - const parsed = (transform: string): { shift: number; scale: number } => { - const m = /translate3d\((-?[\d.e+-]+)px,0,0\) scale\((-?[\d.e+-]+)\)/.exec(transform)!; - return { shift: Number(m[1]), scale: Number(m[2]) }; - }; - /** What the compositor shows `ms` into an animation: the keyframes' straight lines. */ - const playedAt = (anim: any, ms: number): { shift: number; scale: number } => { - const keys: any[] = anim.keyframes; - const at = (k: number) => (keys[k].offset ?? k / (keys.length - 1)) * anim.options.duration; - let k = 1; - while (k < keys.length - 1 && at(k) < ms) k += 1; - const [a, b] = [parsed(keys[k - 1].transform), parsed(keys[k].transform)]; - const x = Math.min(1, Math.max(0, (ms - at(k - 1)) / (at(k) - at(k - 1)))); - return { shift: a.shift + (b.shift - a.shift) * x, scale: a.scale + (b.scale - a.scale) * x }; - }; - - describe('a pick made while an ease is under way, and a rebuild in the middle of one', () => { - const picks: { name: string; from: 'both' | 'offset'; waitS: number; then: ['still' | 'offset' | 'both', number][] }[] = [ - { name: 'offset-only to both, then to still a moment later', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100]] }, - { name: 'offset-only to both, then back to offset-only', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 100]] }, - { name: 'offset-only to both, to still, and to both again', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 100], ['both', 150]] }, - { name: 'offset-only to both, then offset-only as the angle lands', from: 'offset', waitS: 7.8, then: [['both', 0], ['offset', 295]] }, - { name: 'offset-only to both, then still with the offset on its way out', from: 'offset', waitS: 7.8, then: [['both', 0], ['still', 450]] }, - { name: 'both to offset-only, then to both before the offset is in', from: 'both', waitS: 3, then: [['offset', 0], ['both', 150]] }, - { name: 'both to offset-only, then to still, then to offset-only', from: 'both', waitS: 3, then: [['offset', 0], ['still', 100], ['offset', 120]] }, - ]; - picks.forEach(({ name, from, waitS, then }) => { - it(`${name}: every keyframe the last pick lays out is the pose of an angle and an offset inside the card fit`, () => { - setCamera({ mode: from, speedDegPerS: 12, offsetM: 200 }); - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - let at = T0 + waitS * 1000; - for (const [mode, after] of then) { - at += after; - vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode }, at); - } - const got = pairsOf(rigOf(parent).children[2], at); - 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); - s.dispose(); - }); - }); - - it('a rebuild in the middle of an ease lands where the old scene was: the first frame of the new rig is the frame the old one showed', () => { - pending(); - for (const gap of [100, 250, 400, 550]) { - resetHeading(); - resetCamera(); - vi.mocked(performance.now).mockReturnValue(T0); - anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); - setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }); - const { parent, canvas } = host(); - const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - const at = T0 + 7_800; - vi.mocked(performance.now).mockReturnValue(at); - setCamera({ mode: 'both' }, at); - const old = rigOf(parent).children.map((box: any) => live(box)[0]); - vi.mocked(performance.now).mockReturnValue(at + gap); - window.dispatchEvent(new Event('resize')); - vi.advanceTimersByTime(300); // the debounced rebuild: a new rig at this clock - const now = rigOf(parent).children.map((box: any) => live(box)[0]); - now.forEach((a: any, i: number) => { - expect(a).not.toBe(old[i]); - const was = playedAt(old[i], gap); - const is = parsed(a.keyframes[0].transform); - expect(Math.abs(is.shift - was.shift), `card ${i} ${gap} ms into the ease`).toBeLessThan(2); - expect(Math.abs(is.scale - was.scale), `card ${i} ${gap} ms into the ease`).toBeLessThan(0.01); - }); - s.dispose(); - } - vi.useRealTimers(); - }); - }); - - describe('random sequences of picks, holds, speeds, offsets and rebuilds at random times', () => { - /** A seeded generator (mulberry32): a failing sequence is the seed it prints. */ - const random = (seed: number) => () => { - seed = (seed + 0x6d2b79f5) | 0; - let t = Math.imul(seed ^ (seed >>> 15), 1 | seed); - t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t; - return ((t ^ (t >>> 14)) >>> 0) / 4294967296; - }; - const modes = ['still', 'offset', 'both'] as const; - const inside = ([lo, hi]: [number, number], v: number, slack = 1e-6) => v >= lo - slack && v <= hi + slack; - - /** Every pose a laid-out stretch passes through is one the baker's bound allows, at the offset it has: whenever the camera angle moves, the circle's bound holds at both ends; and the keyframes are the poses the heading owner has. */ - const checkLayout = (parent: any, label: string) => { - const boxes = rigOf(parent).children as any[]; - boxes.forEach((box) => expect(live(box)).toHaveLength(1)); - // The rig lays every card out from the owner's pose at the clock of each keyframe. - boxes.forEach((box) => { - const card = Number(box.id.slice(-1)); - const { keyframes, options, at } = live(box)[0]; - keyframes.forEach((f: any, n: number) => { - const t = at + (f.offset ?? n / (keyframes.length - 1)) * options.duration; - const p = poseAt(t); - const c = cardPose(vienna, card, p.h, p.phi, p.r, w2); - expect(f.transform, `${label}: card ${card} keyframe ${n}`).toBe(`translate3d(${c.shiftPx}px,0,0) scale(${c.scale})`); - }); - }); - // The pose itself, every 2 ms through the ease and every half second after. - const t0: number = live(boxes[0])[0].at; - const home = Math.max(t0, settledAt()); - const times: number[] = []; - for (let t = t0; t <= home + 2; t += 2) times.push(t); - for (let t = home; t <= t0 + SEGMENT_S * 1000; t += 500) times.push(t); - let last = poseAt(times[0]); - times.forEach((t, i) => { - const p = poseAt(t); - expect(inside(offsetRange(vienna, w2, 'both', p.phi), p.r), `${label}: phi ${p.phi}, r ${p.r} at +${t - t0} ms`).toBe(true); - if (i && Math.abs(p.phi - last.phi) > 1e-9) { - const circle = offsetRange(vienna, w2, 'offset'); - expect(inside(circle, p.r, 0.02) && inside(circle, last.r, 0.02), `${label}: the angle moves with r ${last.r} then ${p.r} at +${t - t0} ms`).toBe(true); - } - if (i % 40 === 0 || i === times.length - 1) expect(quickPx(p.r, p.phi), `${label}: fit at phi ${p.phi}, r ${p.r}`).toBeLessThanOrEqual(FIT_PX_MAX + 0.1); - last = p; - }); - }; - - let inEase = 0; - const sequence = (seed: number): number => { - const next = random(seed); - const pick = (xs: readonly T[]): T => xs[Math.floor(next() * xs.length)]; - resetHeading(); - resetCamera(); - const clock = vi.mocked(performance.now); - let now = T0; - clock.mockReturnValue(now); - anchor(vienna.view.place.id, vienna.view.lookAzDeg, T0); - setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 3, 12, -12, 0]), offsetM: pick([200, 98, -60, 0, 999]) }, now); - let { parent, canvas } = host(); - let scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - let rebuilds = 0; - for (let step = 0; step < 36; step += 1) { - const gap = pick([0, 20, 60, 100, 150, 299, 301, 450, 700, 3000, 24_500]); - now += gap; - clock.mockReturnValue(now); - vi.advanceTimersByTime(gap); - const label = `seed ${seed} step ${step}`; - const op = Math.floor(next() * 9); - const before = poseAt(now); - const fine = now <= settledAt(); // the old stretch is keyed every 50 ms here, a second apart after: the straight lines between keyframes are the pose only where they are close - const old = rigOf(parent).children.map((box: any) => live(box)[0]); - if (op <= 2) setCamera({ mode: pick(modes) }, now); - else if (op === 3) hold(next() * 1000 - 300, now); - else if (op === 4) setCamera({ speedDegPerS: pick([0.6, 3, 12, -12, 0, 7.5]) }, now); - else if (op === 5) setCamera({ offsetM: Math.round(next() * 600 - 300) }, now); - else if (op === 6) setCamera({ mode: pick(modes), speedDegPerS: pick([0.6, 12, -12]), offsetM: pick([200, 0, 50]) }, now); - else if (op === 7) { - window.dispatchEvent(new Event('resize')); - vi.advanceTimersByTime(300); - } else { - scene.dispose(); - ({ parent, canvas } = host()); - scene = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(vienna) })!; - } - if (op >= 7) { - rebuilds += 1; - if (fine) inEase += 1; - // A rebuild changes where nothing is: the owner's pose is the same before and after it, and the first frame laid out is the frame that was showing. - const after = poseAt(now); - expect(after.r, label).toBeCloseTo(before.r, 9); - expect(norm(after.phi), label).toBeCloseTo(norm(before.phi), 6); - expect(norm(after.h), label).toBeCloseTo(norm(before.h), 6); - rigOf(parent).children.forEach((box: any, i: number) => { - if (!fine) return; - const was = playedAt(old[i], now - old[i].at); - const is = parsed(live(box)[0].keyframes[0].transform); - // The new stretch is laid out from angles brought into [0, 360): a whole turn of the heading is a whole turn of the shift, the same picture. - const turn = is.scale * w2.plane.scale * vienna.view.pxPerDegH * 360; - const jump = Math.abs(is.shift - was.shift); - expect(Math.abs(jump - turn * Math.round(jump / turn)), `${label}: card ${i} popped at the rebuild`).toBeLessThan(3); - expect(Math.abs(is.scale - was.scale), `${label}: card ${i} popped at the rebuild`).toBeLessThan(0.02); - }); - } - checkLayout(parent, label); - } - scene.dispose(); - return rebuilds; - }; - - it('every pose laid out is inside the bound the baker set, and a rebuild never moves the view', () => { - pending(); - let rebuilds = 0; - for (let seed = 1; seed <= 24; seed += 1) rebuilds += sequence(seed); - expect(rebuilds).toBeGreaterThan(100); - expect(inEase).toBeGreaterThan(10); // and some of them in the middle of eases, not only at rest - vi.useRealTimers(); - }, 120_000); - }); - }); - - describe('under reduced motion there is no ease: the pose owed is the pose issued', () => { + describe('under reduced motion rotation stops and the clamped pose is issued at once', () => { const owed = (ring: typeof manifest, offset: number, phi: number, at = T0) => { const p = cardPose(ring, 0, poseAt(at).h, phi, offset, windowFor(ring.view, 400, 800)); return `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`; diff --git a/src/app/features/scene/ridge/Ridge.ts b/src/app/features/scene/ridge/Ridge.ts index d2081169..765294d1 100644 --- a/src/app/features/scene/ridge/Ridge.ts +++ b/src/app/features/scene/ridge/Ridge.ts @@ -5,7 +5,7 @@ import { cardArc, cardPose, HFOV_MAX_DEG, offsetRange, SEGMENT_S, sweepArc, wind import type { Camera, CardPose, View } from './view'; import type { TileCard } from './manifest'; import { residentTiles } from './ring'; -import { freeze, normalize, poseAt as headingPose, setRange, settledAt, subscribe as onHeading, turnRate } from './heading'; +import { freeze, normalize, poseAt as headingPose, setRange, subscribe as onHeading, turnRate } from './heading'; import type { Pose } from './heading'; import { activeAt, drawTwinkle as paintTwinkle, slotsFor, Star } from './stars'; import { STAR_COUNT } from './nightSkyData'; @@ -165,28 +165,15 @@ const REISSUE_FRAC = 0.8; /** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */ export const RESIDENCY_MS = 500; -/** Keyframe spacing while an ease runs, ms: fine enough that the straight lines between them are the smoothstep to a pixel. */ -const EASE_KEY_MS = 50; -/** The instants of a stretch keyed finely up to `easeMs`, then every second to SEGMENT_S: ms from the stretch's start, ascending, ending at the stretch's length. */ -const easeTimes = (easeMs: number): number[] => { - const times: number[] = []; - for (let ms = 0; ms < easeMs; ms += EASE_KEY_MS) times.push(ms); - times.push(easeMs); - for (let ms = (Math.floor(easeMs / 1000) + 1) * 1000; ms <= SEGMENT_S * 1000; ms += 1000) times.push(ms); - return times; -}; - /** - * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, finely - * keyed while an ease of the heading owner runs, constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. + * The keyframes of a stretch of motion from `t0` (ms), the transform at each instant from `transformAt`: a keyframe a second for SEGMENT_S seconds, + * constant under reduced motion. The cards and the sky are keyed by it alike, so they turn together. */ const stretch = (t0: number, frozen: boolean, transformAt: (t: number) => string): Keyframe[] => { if (frozen) { const at = transformAt(t0); return [{ transform: at }, { transform: at }]; } - const easeMs = Math.min(SEGMENT_S * 1000, Math.max(0, settledAt() - t0)); - if (easeMs > 0) return easeTimes(easeMs).map((ms) => ({ transform: transformAt(t0 + ms), offset: ms / (SEGMENT_S * 1000) })); return Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({ transform: transformAt(t0 + n * 1000) })); }; diff --git a/src/app/features/scene/ridge/heading.test.ts b/src/app/features/scene/ridge/heading.test.ts index 4019bc70..67847e19 100644 --- a/src/app/features/scene/ridge/heading.test.ts +++ b/src/app/features/scene/ridge/heading.test.ts @@ -1,8 +1,8 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'; -import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, settledAt, STAGE_MS, subscribe, turnRate } from './heading'; +import { anchor, freeze, hold, normalize, poseAt, resetHeading, setRange, subscribe, turnRate } from './heading'; import type { RotationMode } from './heading'; import * as camera from '../cameraState'; -import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState'; +import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState'; import { maxSpeed } from './view'; import { norm } from './ring'; import { parseManifest } from './manifest'; @@ -13,12 +13,13 @@ const S = 1000; /** The viewer's choice, at the clock `at` (ms): the one way the mode and the speed reach the view. */ const choose = (mode: RotationMode, speedDegPerS: number, at: number) => setCamera({ mode, speedDegPerS }, at); -/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera exactly on its heading and the view turning with it. */ +/** The bound of a baked place, as `view.ts` `offsetRange` draws it: 100 m round the circle, 200 m forward with the camera on its heading. */ const BACK = 100; const FORWARD = 200; -const range = (mode: RotationMode, phi: number): [number, number] => [-BACK, mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK]; -/** Whether a pose is one the bound allows, whatever mode led there. */ -const fits = (p: { phi: number; r: number }): boolean => p.r >= range('both', p.phi)[0] - 1e-9 && p.r <= range('both', p.phi)[1] + 1e-9; +const range = (mode: RotationMode, phi: number): [number, number] => [ + -BACK, + mode !== 'offset' && Math.abs(norm(phi + 180) - 180) < 1e-6 ? FORWARD : BACK, +]; const store = new Map(); @@ -95,26 +96,14 @@ describe('the heading owner', () => { expect(poseAt(104 * S)).toMatchObject({ h: 120, phi: 30 }); }); - it('puts the camera back on its heading when the view direction is made to turn with it, by the short way round, and the view direction turns meanwhile', () => { + it('puts the camera directly back on its heading when switching to both, and turns the view direction from there', () => { anchor('p', 100, 0); choose('offset', 12, 0); expect(poseAt(7.5 * S).phi).toBeCloseTo(90, 9); choose('both', 12, 7.5 * S); - expect(poseAt(7.5 * S)).toMatchObject({ h: 100 }); // the pick moves nothing in the frame it is made - const gone = [0, 0.25, 0.5, 0.75, 1].map((x) => poseAt(7.5 * S + x * STAGE_MS).phi); - gone.slice(1).forEach((v, i) => expect(v).toBeLessThan(gone[i])); - expect(gone[4]).toBe(0); - expect(poseAt(7.5 * S + 5 * S).phi).toBe(0); - expect(poseAt(7.5 * S + 5 * S).h).toBeCloseTo(100 + 12 * 5, 9); - // 270 degrees on is 90 short of home the other way: the camera goes forward to 360, not back through 270. - choose('offset', 12, 20 * S); - choose('offset', 12, 20 * S + 22.5 * S); - const t = 20 * S + 22.5 * S; - expect(norm(poseAt(t).phi)).toBeCloseTo(270, 9); - choose('both', 12, t); - const mid = poseAt(t + STAGE_MS / 2).phi; - expect(norm(mid)).toBeGreaterThan(270); - expect(norm(poseAt(t + STAGE_MS).phi)).toBeCloseTo(0, 9); + expect(poseAt(7.5 * S)).toMatchObject({ h: 100, phi: 0 }); + expect(poseAt(12.5 * S).phi).toBe(0); + expect(poseAt(12.5 * S).h).toBeCloseTo(100 + 12 * 5, 9); }); it('a speed change takes effect from now, without moving the view', () => { @@ -214,7 +203,7 @@ describe('the heading owner', () => { expect(poseAt(60 * S).h).toBe(20); }); - it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime, and an ease under way goes on as it was', () => { + it('normalizes into [0, 360) without changing the view, so the angles never grow with uptime', () => { anchor('p', 0, 0); choose('both', 6, 0); const day = 24 * 3600 * S; @@ -231,18 +220,6 @@ describe('the heading owner', () => { setCamera({ speedDegPerS: -6 }, day + 100 * S); normalize(day + 101 * S); expect(poseAt(day + 101 * S).phi).toBeGreaterThanOrEqual(0); // a turn the other way is brought into range too - // An ease is the same ease before and after it is renormalized, in the middle. - choose('offset', 12, day + 200 * S); - choose('both', 12, day + 207.5 * S); - const at = day + 207.5 * S; - const before = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); - normalize(at + 0.3 * STAGE_MS); - const after = [0.2, 0.5, 0.9].map((x) => poseAt(at + x * STAGE_MS)); - after.forEach((p, i) => { - expect(norm(p.phi)).toBeCloseTo(norm(before[i].phi), 6); - expect(norm(p.h)).toBeCloseTo(norm(before[i].h), 6); - expect(p.r).toBeCloseTo(before[i].r, 9); - }); }); it('tells subscribers of every change of its course: a choice, a hold, a bound, a manual turn while held, a new place; and of nothing that changes nothing', () => { @@ -267,25 +244,7 @@ describe('the heading owner', () => { expect(cb).toHaveBeenCalledTimes(5); }); - it('is the one owner of the order: the heading is current when a listener of the camera hears of a change, whenever the listener registered', () => { - setCamera({ mode: 'both', speedDegPerS: 1 }, 0); - const early: number[] = []; - const offEarly = onCamera((_n, _p, at) => early.push(poseAt(at).h)); // before the place is anchored: first of the listeners, as a control mounted before the scene start is - anchor('p', 214, 0); - const late: number[] = []; - const offLate = onCamera((_n, _p, at) => late.push(poseAt(at).h)); - anchor('p', 214, 1 * S); // a rebuild for a sky anchors the same place again - setCamera({ speedDegPerS: 4 }, 5 * S); - expect(poseAt(10 * S).h).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('keeps no log of the camera: the owner takes each change as it is made, so a change nobody reads is held nowhere', () => { + it('keeps no log of the camera: each change updates the active segment directly', () => { expect(Object.keys(camera)).not.toContain('takeChanges'); anchor('p', 100, 0); choose('both', 2, 0); @@ -295,156 +254,44 @@ describe('the heading owner', () => { expect(poseAt(9 * S).h).toBeCloseTo(100 + 14 + 2, 9); }); - describe('a change of mode eases the pose in two stages inside the bound, from wherever the pose is', () => { - const sample = (from: number, to: number, step = 1): { h: number; phi: number; r: number }[] => { - const out = []; - for (let t = from; t <= to; t += step) out.push(poseAt(t)); - return out; - }; - /** Every pose inside the bound, and whenever the camera angle moves the offset is inside the circle's bound at both ends of the move. */ - const insideTheBound = (poses: { phi: number; r: number }[]) => { - poses.forEach((p, i) => { - expect(fits(p), `pose ${i}: phi ${p.phi}, r ${p.r}`).toBe(true); - if (i && Math.abs(p.phi - poses[i - 1].phi) > 1e-9) { - expect(Math.abs(p.r)).toBeLessThanOrEqual(BACK + 0.02); // a sample step may straddle the end of a stage: a thousandth of the ease on - expect(Math.abs(poses[i - 1].r)).toBeLessThanOrEqual(BACK + 0.02); - } - }); - }; - - /** The clock at which the camera has gone a quarter round its circle at 12 degrees a second, started when its offset is in: the offset comes in first, and the angle is let go after. */ - const QUARTER = 90 / 12 * S + STAGE_MS; - + describe('clamped offset and mode switches', () => { beforeEach(() => { setCamera({ offsetM: 200 }, 0); anchor('p', 100, 0); setRange(range, 0); }); - it('goes to a mode that stands the camera on its heading in two stages: the angle first, the offset let out after, and the view direction never waits', () => { - choose('offset', 12, 0); - const at = QUARTER; - expect(poseAt(at)).toMatchObject({ phi: 90, r: BACK }); - choose('both', 12, at); - expect(poseAt(at)).toMatchObject({ h: 100, phi: 90, r: BACK }); // what is seen at the pick - expect(settledAt()).toBe(at + 2 * STAGE_MS); - const stage1 = sample(at, at + STAGE_MS); - expect(stage1.every((p) => p.r === BACK)).toBe(true); // the angle alone - expect(stage1.at(-1)!.phi).toBeCloseTo(0, 9); - const stage2 = sample(at + STAGE_MS, at + 2 * STAGE_MS); - expect(stage2.every((p) => p.phi === 0)).toBe(true); // the offset alone - expect(stage2.at(-1)!.r).toBe(FORWARD); - expect(poseAt(at + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); - expect(poseAt(at + 3 * S).h).toBeCloseTo(100 + 36, 9); // turning from the instant of the pick - insideTheBound(sample(at, at + 2 * STAGE_MS)); - }); - - it('goes to a mode that takes the camera off its heading the other way: the offset comes in first with the camera held where it stood, then the camera goes', () => { - choose('both', 12, 0); - const at = 10 * S; - expect(poseAt(at)).toMatchObject({ phi: 0, r: FORWARD }); - choose('offset', 12, at); - const stage1 = sample(at, at + STAGE_MS); - expect(stage1.every((p) => p.phi === 0)).toBe(true); - expect(stage1.at(-1)!.r).toBe(BACK); - expect(poseAt(at + STAGE_MS + 1 * S)).toMatchObject({ r: BACK }); - expect(poseAt(at + STAGE_MS + 1 * S).phi).toBeCloseTo(12, 9); // and goes round from the angle it stood at, at the speed - insideTheBound(sample(at, at + 3 * STAGE_MS)); - }); - - it('a pick that asks nothing of the offset does not wait for it: the angle goes at once', () => { - choose('both', 12, 0); - setCamera({ offsetM: 50 }, 1 * S); - choose('offset', 12, 2 * S); - expect(poseAt(2 * S + 1 * S).phi).toBeCloseTo(12, 9); - }); - - it('a pick made while an ease is under way starts from the pose the view has, and every pose on the way stays inside the bound', () => { - const picks: RotationMode[] = ['still', 'offset', 'both']; - let checked = 0; - for (const first of picks) { - for (const second of picks) { - for (const gap of [10, 100, 250, 310, 450, 590]) { - resetHeading(); - resetCamera(); - setCamera({ mode: 'offset', speedDegPerS: 12, offsetM: 200 }, 0); - anchor('p', 100, 0); - setRange(range, 0); - const at = QUARTER; - setCamera({ mode: first }, at); - const seen = poseAt(at + gap); - setCamera({ mode: second }, at + gap); - expect(poseAt(at + gap), `${first} then ${second} after ${gap} ms`).toEqual(seen); // nothing moves at the pick - insideTheBound(sample(at, at + 4 * STAGE_MS, 3)); - checked += 1; - } - } - } - expect(checked).toBe(54); - }); - - it('a pick to both made from the offset-only mode mid-way, then to offset-only again, never leaves the bound: the case a target-only order got wrong', () => { - choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); // the angle goes first, the offset held at the circle's bound - choose('offset', 12, at + 100); // and the offset-only mode has the offset on the circle's bound already - insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); - // From both with the offset out, pick still then both then offset within a stage each. - resetHeading(); - resetCamera(); - setCamera({ mode: 'both', speedDegPerS: 12, offsetM: 200 }, 0); - anchor('p', 100, 0); - setRange(range, 0); - choose('offset', 12, 5 * S); // the offset comes in first - choose('both', 12, 5 * S + 100); // back out: the camera is still on its heading, so the offset can go straight out - insideTheBound(sample(5 * S, 5 * S + 4 * STAGE_MS, 2)); - expect(poseAt(5 * S + 10 * S)).toMatchObject({ phi: 0, r: FORWARD }); - }); - - it('a slider eases in one stage, inside the bound the mode keeps, and an offset past it is held to it', () => { + it('clamps offset directly per mode without rewriting the stored choice', () => { choose('both', 0.6, 0); + expect(poseAt(0)).toMatchObject({ phi: 0, r: FORWARD }); setCamera({ offsetM: 20 }, 1 * S); - expect(poseAt(1 * S).r).toBe(FORWARD); - expect(poseAt(1 * S + STAGE_MS).r).toBe(20); - expect(settledAt()).toBe(1 * S + STAGE_MS); + expect(poseAt(1 * S).r).toBe(20); setCamera({ offsetM: 999 }, 5 * S); - expect(poseAt(6 * S).r).toBe(FORWARD); + expect(poseAt(5 * S).r).toBe(FORWARD); choose('offset', 0.6, 7 * S); - expect(poseAt(9 * S).r).toBe(BACK); // the viewer's 999 is not rewritten + expect(poseAt(7 * S).r).toBe(BACK); // the viewer's 999 is not rewritten expect(getCamera().offsetM).toBe(999); choose('both', 0.6, 10 * S); - expect(poseAt(12 * S).r).toBe(FORWARD); + expect(poseAt(10 * S)).toMatchObject({ phi: 0, r: FORWARD }); }); - it('a new bound is a new segment from the pose the view has: a rebuild mid-ease lands exactly where the old scene was', () => { + it('clamps to the new bound on setRange without moving h or phi', () => { choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); - for (const gap of [50, 150, 299, 301, 450]) { - const seen = poseAt(at + gap); - setRange(range, at + gap); // what a rebuild at another size, or a rebuilt scene, does - const now = poseAt(at + gap); - expect(now.h).toBeCloseTo(seen.h, 9); - expect(now.phi).toBeCloseTo(seen.phi, 9); - expect(now.r).toBeCloseTo(seen.r, 9); - } - insideTheBound(sample(at, at + 4 * STAGE_MS, 2)); - expect(poseAt(at + 5 * S)).toMatchObject({ phi: 0, r: FORWARD }); + const at = 5 * S; + const seen = poseAt(at); + setRange(() => [-50, 50], at); + expect(poseAt(at)).toMatchObject({ h: seen.h, phi: seen.phi, r: 50 }); }); - it('has no ease under reduced motion: the pose owed is the pose shown at once, and one begun before is cut short', () => { + it('stops rotation under reduced motion while clamping the pose immediately', () => { choose('offset', 12, 0); - const at = QUARTER; - choose('both', 12, at); - expect(settledAt()).toBeGreaterThan(at); - freeze(true, at + 10); - expect(poseAt(at + 10)).toMatchObject({ phi: 0, r: FORWARD }); - expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 10).h); // and nothing turns - setCamera({ mode: 'offset', speedDegPerS: 12 }, at + 20); - expect(poseAt(at + 21)).toMatchObject({ r: BACK }); // the clamp, at once - setCamera({ mode: 'both', speedDegPerS: 12 }, at + 30); - expect(poseAt(at + 31)).toMatchObject({ phi: 0, r: FORWARD }); - expect(settledAt()).toBeLessThanOrEqual(at + 30); + const at = 7.5 * S; + freeze(true, at); + expect(poseAt(at).phi).toBeCloseTo(90, 9); + expect(poseAt(at + 5 * S).phi).toBeCloseTo(90, 9); + setCamera({ mode: 'both', speedDegPerS: 12 }, at + 20); + expect(poseAt(at + 20)).toMatchObject({ phi: 0, r: FORWARD }); + expect(poseAt(at + 5 * S).h).toBe(poseAt(at + 20).h); }); }); }); diff --git a/src/app/features/scene/ridge/heading.ts b/src/app/features/scene/ridge/heading.ts index 880caa59..2542dfae 100644 --- a/src/app/features/scene/ridge/heading.ts +++ b/src/app/features/scene/ridge/heading.ts @@ -2,21 +2,13 @@ // centre (`r`), at any clock. Module-level state, so a sky change that makes a new scene keeps the pose. Angles are unwrapped compass degrees between two // `normalize` calls (the rig makes one before each stretch of motion); `ring.ts` is the one place that reasons about 0 / 360. // -// The state is one SEGMENT: the pose at its start `t0`, the mode and bounded speed in force, and the ease that takes the pose to the one the inputs owe. -// `poseAt(t)` is a pure function of the segment and `t`, ease included. Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced -// motion, a place) starts a new segment from `poseAt(now)`: no log of changes, no second copy of the ease, so whoever reads at any clock, a rebuilt scene -// included, gets the pose the view has. -// -// The camera sits on its circle at angle `h + phi` and distance `r` (signed, forward positive): with `phi` 0 it is pushed forward along its own heading -// (`view.ts` `cardPose`), and 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'). The bound on `r` is the baker's (`view.ts` `offsetRange`, given by the scene as `setRange`): a -// forward offset past `rMaxM` fits only with the camera exactly on its heading. So an ease takes `phi` and `r` one after the other, STAGE_MS each, in the -// order that keeps every pose inside it from wherever it starts: a camera going to stand on its heading turns first and lets the offset out after; one going -// off it brings the offset in first and lets the camera go after. -import { bindOwner, getCamera, holdCamera, isHeld } from '../cameraState'; +// The state is one SEGMENT: the pose at its start `t0` and the mode and bounded speed in force. `poseAt(t)` is a pure function of the segment and `t`. +// Every change of an input (a mode pick, a hold, the speed, the offset, a bound, reduced motion, a place) starts a new segment from `poseAt(now)` with +// `phi` and `r` clamped directly to what the mode and bound allow. +import { getCamera, holdCamera, isHeld, subscribe as subscribeCamera } from '../cameraState'; +import type { RotationMode } 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'; +export type { RotationMode }; /** Where the view faces, where the camera stands on its circle against that, and its offset (m, signed): the pose the rig lays the cards out from. */ export interface Pose { @@ -29,24 +21,13 @@ export interface Pose { type Speed = (mode: RotationMode) => number; type Range = (mode: RotationMode, phiDeg: number) => [number, number]; -export const STAGE_MS = 300; // one stage of an ease, ms -const EPS = 1e-9; // a pose this close to the one owed is there: nothing eases - interface Segment extends Pose { /** The clock (ms) at which `h`, `phi` and `r` hold. */ t0: number; - /** Degrees per second of whatever turns, signed and bounded, and what that is: the view direction ('both'), the camera on its circle ('offset') or nothing. */ + /** Degrees per second of whatever turns, signed and bounded. */ rate: number; + /** What turns: the view direction ('both'), the camera on its circle ('offset'), or nothing. */ turns: 'h' | 'phi' | undefined; - /** The camera's angle turns only from this clock (ms): after the offset has come in. */ - turnsFrom: number; - /** The angle an ease takes `phi` to from `t0` (unwrapped, the nearest way round); undefined: `phi` is what `turns` makes it. */ - phiTo: number | undefined; - /** The offset an ease takes `r` to, from `rAt`. */ - rTo: number; - rAt: number; - /** The clock (ms) at which everything eased is home. */ - endAt: number; } let seg: Segment | undefined; @@ -54,13 +35,9 @@ let frozen = false; let anchored: string | undefined; let speed: Speed | undefined; let range: Range | undefined; +let offCamera: (() => void) | undefined; const listeners = new Set<() => void>(); -/** 0 at `at`, 1 at `at + STAGE_MS` (smoothstep): the one curve of the view's easing. */ -const ease = (at: number, now: number): number => { - const x = Math.min(1, Math.max(0, (now - at) / STAGE_MS)); - return x * x * (3 - 2 * x); -}; const free: [number, number] = [-Infinity, Infinity]; /** What each mode turns: the view direction, the camera on its circle, or nothing. */ const TURNS: Record = { both: 'h', offset: 'phi', still: undefined }; @@ -70,84 +47,65 @@ function pose(s: Segment, t: number): Pose { const sec = (t - s.t0) / 1000; return { h: s.h + (s.turns === 'h' ? s.rate * sec : 0), - phi: - s.phiTo !== undefined - ? s.phi + (s.phiTo - s.phi) * ease(s.t0, t) - : s.phi + (s.turns === 'phi' ? (s.rate * Math.max(0, t - s.turnsFrom)) / 1000 : 0), - r: s.r + (s.rTo - s.r) * ease(s.rAt, t), + phi: s.phi + (s.turns === 'phi' ? s.rate * sec : 0), + r: s.r, }; } -/** - * Start a segment at `now` from `from`, the pose the view has there, under the inputs in force: the viewer's choice, the hold, reduced motion and the bounds. - * What the inputs owe is where the camera must stand (on its heading when the view turns with it and is not held) and the offset the bound allows there; an - * ease is what takes `from` to it, none when `snap` (a place or a bound met for the first time) or while frozen. - */ -function begin(now: number, from: Pose, snap = false): void { +/** Start a segment at `now` from `from`, with `phi` and `r` clamped to the mode and bound in force. */ +function begin(now: number, from: Pose): void { const cam = getCamera(); const held = isHeld(); const kin: RotationMode = frozen || held ? 'still' : cam.mode; const toHeading = cam.mode === 'both' && !held; const limit = speed?.(cam.mode) ?? Infinity; - const phiTo = toHeading ? 360 * Math.round(from.phi / 360) : undefined; - const landed = phiTo ?? from.phi; - const [lo, hi] = rangeOf(cam.mode, landed); // the bound is the chosen mode's, held or frozen or not: a hold does not move the offset - const rTo = Math.min(hi, Math.max(lo, cam.offsetM)); - const easing = !snap && !frozen; - const turnsPhi = easing && phiTo !== undefined && Math.abs(phiTo - from.phi) > EPS; - const movesR = easing && Math.abs(rTo - from.r) > EPS; - // Going to circle with the offset out past the circle's bound: the camera stays on its heading until the offset is in. - const [circleLo, circleHi] = rangeOf('offset', from.phi); - const holdsPhi = movesR && kin === 'offset' && (from.r < circleLo || from.r > circleHi); - const rAt = turnsPhi ? now + STAGE_MS : now; + const phi = toHeading ? 0 : from.phi; + const [lo, hi] = rangeOf(cam.mode, phi); + const r = Math.min(hi, Math.max(lo, cam.offsetM)); seg = { t0: now, h: from.h, - phi: turnsPhi ? from.phi : landed, - r: movesR ? from.r : rTo, + phi, + r, rate: Math.sign(cam.speedDegPerS) * Math.min(Math.abs(cam.speedDegPerS), limit), turns: TURNS[kin], - turnsFrom: holdsPhi ? now + STAGE_MS : now, - phiTo: turnsPhi ? phiTo : undefined, - rTo, - rAt, - endAt: Math.max(turnsPhi ? now + STAGE_MS : now, movesR ? rAt + STAGE_MS : now), }; } const current = (now: number): Segment => { - if (!seg) begin(now, { h: 0, phi: 0, r: 0 }, true); + if (!seg) begin(now, { h: 0, phi: 0, r: 0 }); return seg as Segment; }; + /** The pose at `now` (ms): unwrapped degrees, bounded by the last `normalize` and the stretch since. */ export function poseAt(now: number): Pose { return pose(current(now), now); } + const emit = () => [...listeners].forEach((cb) => cb()); + /** A new segment at `now` from the pose the view has, told to the subscribers. */ -function restart(now: number, over: Partial = {}, snap = false): void { - begin(now, { ...poseAt(now), ...over }, snap); +function restart(now: number, over: Partial = {}): void { + begin(now, { ...poseAt(now), ...over }); emit(); } +function ensureSync(): void { + offCamera ??= subscribeCamera((_next, _prev, at) => restart(Math.max(at, seg?.t0 ?? at))); +} + /** * Degrees per second the view direction turns at under the inputs in force: the viewer's speed bounded by what the place sustains in the mode picked (`anchor`'s - * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). Every change of any of these starts a - * segment and is heard by `subscribe`, so a reader that sizes something to this speed learns when it must size again. + * limit), and nothing while the view does not turn (a mode that turns the camera on its circle, a hold, reduced motion). */ export const turnRate = (): number => (seg?.turns === 'h' ? Math.abs(seg.rate) : 0); -/** The clock (ms) at which what the last change eased is home. */ -export const settledAt = (): number => seg?.endAt ?? 0; - -// The viewer's choice or hold changed: a new segment at that clock, before any listener hears of it. -bindOwner((at) => restart(Math.max(at, seg?.t0 ?? at))); - /** * Bound the speed in each mode to what the baked place sustains (`view.ts` `maxSpeed`), from this moment, before anything awaits the place's tiles, and point - * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading, with no ease; the same place again keeps the pose. + * the view at a place: a place not shown before faces its rest azimuth, the camera on its heading; the same place again keeps the pose. */ export function anchor(key: string, restDeg: number, now: number, limit?: Speed): void { + ensureSync(); if (limit) speed = limit; if (anchored === key) { if (limit) restart(now); @@ -155,14 +113,14 @@ export function anchor(key: string, restDeg: number, now: number, limit?: Speed) } anchored = key; range = undefined; // the bound belongs to the place before - restart(now, { h: restDeg, phi: 0 }, true); + restart(now, { h: restDeg, phi: 0 }); } -/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`); the first one met takes the offset to its bound at once, a new one eases there. */ +/** The offsets the scene's place and viewport allow (`view.ts` `offsetRange`), clamped at once. */ export function setRange(limit: Range, now: number): void { - const first = range === undefined; + ensureSync(); range = limit; - restart(now, {}, first); + restart(now); } /** @@ -170,37 +128,39 @@ export function setRange(limit: Range, now: number): void { * is held in cameraState, which leaves the chosen mode as it is; a rebuild keeps the hold, and picking a mode, the one already chosen included, resumes it. */ export function hold(h: number, now: number): void { + ensureSync(); begin(now, { ...poseAt(now), h }); if (isHeld()) emit(); - else holdCamera(now); // the owner starts the held segment, then the camera's listeners hear it, once + else holdCamera(now); } /** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view takes the pose owed at once and stays there. */ export function freeze(on: boolean, now: number): void { + ensureSync(); if (on === frozen) return; frozen = on; restart(now); } -/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open: the whole turns are all that goes, and the ease and the motion go on. Silent: the caller lays out again. */ +/** Bring `h` and `phi` into [0, 360) at `now`, so the transforms stay small however long the page has been open. Silent: the caller lays out again. */ export function normalize(now: number): void { const s = current(now); const p = pose(s, now); - const dh = 360 * Math.floor(p.h / 360); - const dphi = 360 * Math.floor(p.phi / 360); - s.h -= dh; - s.phi -= dphi; - if (s.phiTo !== undefined) s.phiTo -= dphi; + s.h -= 360 * Math.floor(p.h / 360); + s.phi -= 360 * Math.floor(p.phi / 360); } /** Hear every change of the pose's course: the viewer's choice or hold, a bound, reduced motion, a manual turn, a new place; returns the way to stop. */ export function subscribe(cb: () => void): () => void { + ensureSync(); listeners.add(cb); return () => listeners.delete(cb); } /** For tests: the state of a fresh page. */ export function resetHeading(): void { + offCamera?.(); + offCamera = undefined; seg = undefined; frozen = false; anchored = undefined;