ridge runtime: the speed is bounded from the anchor, the owner settles before the rig reads it, a mode pick eases the view, and a scene start has a deadline

anchor takes the place's speed bound, so the view never turns past it while the first tiles load, and the rig no longer installs it. The owner keeps one
listener (same function, same place in cameraState's order) so a re-anchor cannot move it behind the old rig's. A change of mode eases phi (shownPhiAt) and
the offset the clamp releases or takes over EASE_MS, keyed finely in the same WAAPI animation. prepare waits PREPARE_DEADLINE_MS for the first arc, then draws
with the tiles held (the rig asks for the rest) or, with none, is the sky alone.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
Meta Vens 2026-11-23 02:09:27 +01:00
commit fa2e216039
6 changed files with 278 additions and 42 deletions

View file

@ -1,15 +1,16 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { atSolarTime } from './ridge/skyTestkit';
import type { Scene } from './Scene';
import { startBackgroundScene } from './index';
import { PREPARE_DEADLINE_MS, startBackgroundScene } from './index';
import { getResolvedSkyState, getSkyPlace, pickSkyChoice, setSkyChoice, setSkyClock, setSkyPlace, subscribe } from './skyState';
import { skyBand } from './ridge/skyMoment';
import type { SkyChoice } from './ridge/skyMoment';
import { ridgeSkyFor } from './skyForState';
import { forgetManifests } from './ridge/manifest';
import { wireIndex, wireManifest } from './ridge/manifest.fixture';
import { FALLBACK_VIEW, HFOV_MAX_DEG } from './ridge/view';
import { hold, resetHeading } from './ridge/heading';
import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
import { headingAt, hold, resetHeading } from './ridge/heading';
import { resetCamera, setCamera } from './cameraState';
import { sunAt } from './ridge/sunAt';
import { ridgeWeather } from './ridge/weather';
import { parseWeatherFile, WEATHER_ATTRIBUTION, weatherFromFile } from './ridge/weatherFeed';
@ -421,6 +422,92 @@ describe('the ridge planes', () => {
expect((second.fromDeg + second.toDeg) / 2).toBeCloseTo(100, 0);
});
it('bounds the speed from the anchor: while the first tiles load the view turns no faster than the place sustains, whatever speed is stored', async () => {
served({ '/public/ridge/vienna-abc123abc123/manifest.json': wireManifest({ camera: { r_max_m: 98.2, r_max_forward_m: 205.4 } }, 3, 32) }); // a ring whose gate holds fewer than all its tiles
resetHeading();
resetCamera();
setCamera({ mode: 'both', speedDegPerS: 12 }, 0);
const clock = vi.spyOn(performance, 'now').mockReturnValue(1_000);
const d = loader();
let seen = NaN;
createRidgeScene.mockImplementation(() => {
seen = headingAt(performance.now());
return fakeScene();
});
d.ctl.hold = true;
const started = startBackgroundScene(config, caps, { canvas });
await flush();
clock.mockReturnValue(6_000); // the tiles took five seconds
await d.release();
(await started)?.dispose();
const slow = maxSpeed(d.ctl.made[0].manifest, 'both');
expect(slow).toBeLessThan(12);
expect(seen).toBeCloseTo(214 + 5 * slow, 6); // not 214 + 60
clock.mockRestore();
resetCamera();
});
describe('a scene start with a deadline', () => {
/** A backdrop whose first arc never settles, holding `tiles` tiles. */
const silent = (tiles: number) => {
const made: any[] = [];
createBackdrop.mockImplementation((manifest: unknown) => {
const bd = {
manifest,
dispose: vi.fn(),
litTiles: () => Array.from({ length: tiles }, (_, tile) => ({ tile, card: 0, canvas: {} })),
ensure: vi.fn(() => new Promise<void>(() => undefined)),
};
made.push(bd);
return bd;
});
return made;
};
const real = () => new Promise<void>((r) => setImmediate(r));
afterEach(() => {
vi.useRealTimers();
});
it('draws with the tiles it has when the server is slow, and the rest fill in: the backdrop is the scene, not a finished load', async () => {
served();
resetHeading();
const made = silent(2);
createRidgeScene.mockReturnValue(fakeScene());
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
const started = startBackgroundScene(config, caps, { canvas });
for (let i = 0; i < 20; i += 1) await real();
expect(made).toHaveLength(1);
expect(createRidgeScene).not.toHaveBeenCalled(); // the first arc is still out
await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS - 1);
for (let i = 0; i < 5; i += 1) await real();
expect(createRidgeScene).not.toHaveBeenCalled();
await vi.advanceTimersByTimeAsync(1);
const scene = await started;
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[0][0].backdrop).toBe(made[0]); // the scene holds it, and goes on asking it for the arcs ahead
expect(made[0].dispose).not.toHaveBeenCalled();
scene?.dispose();
});
it('is the sky alone, told once, when the deadline passes with no tile held, and lets go of the backdrop and its requests', async () => {
served();
resetHeading();
const made = silent(0);
createRidgeScene.mockReturnValue(fakeScene());
const onPlanesFail = vi.fn();
vi.useFakeTimers({ toFake: ['setTimeout', 'clearTimeout'] });
const started = startBackgroundScene(config, caps, { canvas, onPlanesFail });
for (let i = 0; i < 20; i += 1) await real();
await vi.advanceTimersByTimeAsync(PREPARE_DEADLINE_MS);
const scene = await started;
expect(createRidgeScene).toHaveBeenCalledOnce();
expect(createRidgeScene.mock.calls[0][0].backdrop).toBeUndefined();
expect(made[0].dispose).toHaveBeenCalledOnce();
expect(onPlanesFail).toHaveBeenCalledOnce();
scene?.dispose();
});
});
it('a build that goes stale disposes the backdrop it made, and a scene that fails to be made does too', async () => {
served();
const d = loader();

View file

@ -6,7 +6,7 @@ import type { SkyChoice } from './ridge/skyMoment';
import { drawnView, ensureSkyPlace, resetSkyPlanes } from './skyPlace';
import type { SkyColours } from './ridge/skyColour';
import type { Backdrop } from './ridge/Backdrop';
import { FALLBACK_VIEW, HFOV_MAX_DEG } from './ridge/view';
import { FALLBACK_VIEW, HFOV_MAX_DEG, maxSpeed } from './ridge/view';
export type { Scene, SceneStats } from './Scene';
export type { SceneStyle, SceneTier } from './tier';
@ -36,6 +36,9 @@ interface Prepared {
planesFail: Error | null;
}
/** How long a scene start waits for the first tiles, ms: past it the scene draws with the tiles it has and the rest arrive into it; with none, it is the sky alone. */
export const PREPARE_DEADLINE_MS = 6_000;
async function prepare(
config: BackgroundSceneConfig | undefined,
options: StartOptions & { tier: SceneTier; debug?: boolean },
@ -80,11 +83,23 @@ async function prepare(
manifest,
manifestSky.physical as NonNullable<typeof manifestSky.physical>
);
// A place not shown before faces its rest azimuth; a rebuild for a sky keeps the heading the view has turned to.
// A place not shown before faces its rest azimuth; a rebuild for a sky keeps the heading the view has turned to. The speed is bounded from here on, not
// from the scene's first frame: the view does not turn further than the place sustains while the tiles load.
const now = performance.now();
heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now);
heading.anchor(manifest.view.place.id, manifest.view.lookAzDeg, now, (mode) => maxSpeed(manifest, mode));
const h = heading.headingAt(now);
await backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 });
// The first arc, against a deadline: a slow or silent server must not hold the scene back. What is held by then is drawn and the rest fills in.
let timer: ReturnType<typeof setTimeout> | undefined;
try {
await Promise.race([
backdrop.ensure({ fromDeg: h - HFOV_MAX_DEG / 2, toDeg: h + HFOV_MAX_DEG / 2 }),
new Promise<void>((late) => {
timer = setTimeout(late, PREPARE_DEADLINE_MS);
}),
]);
} finally {
clearTimeout(timer);
}
if (backdrop.litTiles().length === 0) throw new Error('ridge cards did not load');
lit = manifestSky;
} catch (e) {

View file

@ -12,9 +12,9 @@ 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, maxSpeed, offsetRange, windowFor } from './view';
import { cardArc, cardPose, FALLBACK_VIEW, maxSpeed, offsetRange, SEGMENT_S, windowFor } from './view';
import { residentTiles } from './ring';
import { anchor, headingAt, hold, phiAt, resetHeading } from './heading';
import { anchor, EASE_MS, headingAt, hold, phiAt, resetHeading } from './heading';
import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState';
describe('noise', () => {
@ -989,6 +989,7 @@ describe('the ridge cards in the scene', () => {
expect(slow).toBeGreaterThan(0.6);
expect(slow).toBeLessThan(12);
setCamera({ mode: 'both', speedDegPerS: 50 }); // a stored or future-slider value
anchor(view.place.id, view.lookAzDeg, T0, (m) => maxSpeed(ring, m)); // what index.ts prepare does with the manifest, before the scene is made
const { canvas } = host();
const s = createRidgeScene({ canvas, tier: 'full', sky: DAY, backdrop: ringBackdrop(ring) })!;
expect(getCamera().speedDegPerS).toBe(50);
@ -1018,7 +1019,41 @@ describe('the ridge cards in the scene', () => {
expect(getCamera().offsetM).toBe(200);
setCamera({ mode: 'both' });
expect(getCamera().offsetM).toBe(200);
expect(frame(rigOf(parent).children[2], 0)).toBe(posed(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, headingAt(T0 + EASE_MS), phiAt(T0 + EASE_MS), 200, w2);
expect(keys.find((f: any) => f.offset >= EASE_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
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', () => {
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, headingAt(at + ms), phi, offset, w2);
return { text: `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`, scale: p.scale };
};
expect(phiAt(at)).toBeCloseTo(90, 6);
const seen = tf(0, phiAt(at), 98.2);
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);
s.dispose();
});

View file

@ -3,11 +3,11 @@ import { overlayRequested } from '../debugOverlays';
import { FrameSampler, FrameStats } from './probe';
import { skyColours, SkyColours, Srgb } from './skyColour';
import { paintSky as paintPhysicalSky } from './physicalSky';
import { cardArc, cardPose, maxSpeed, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view';
import { cardArc, cardPose, offsetRange, SEGMENT_S, sweepArc, windowFor } from './view';
import type { CardPose, View } from './view';
import type { TileCard } from './manifest';
import { residentTiles } from './ring';
import { freeze, headingAt, normalize, phiAt, setSpeedLimit, subscribe as onHeading } from './heading';
import { easeEndsAt, easeLeft, EASE_MS, freeze, headingAt, normalize, phiAt, shownPhiAt, 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';
@ -133,6 +133,17 @@ const REISSUE_FRAC = 0.8;
/** How often the arc of tiles ahead is asked for and the mounted tiles are brought up to date. */
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 ridge scene: same contract as `createScene` ({ login, dispose }, null for "keep the CSS
* ground"). It draws the sky, the stars, the lit ridge cards when given a `backdrop` (none: the sky alone) and the rain. The scene itself
@ -293,11 +304,14 @@ 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 speed the baked resident count sustains is derived at every read in the heading owner; the viewer's stored speed is not touched.
setSpeedLimit((mode) => maxSpeed(bd.manifest, mode), clock());
// 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.
let offset = offsetNow(bd, win);
let offsetFrom = offset;
let offsetEase = -Infinity;
const offsetShown = (t: number): number => offset + (offsetFrom - offset) * easeLeft(offsetEase, t);
const poseAt = (card: number, t: number): CardPose =>
cardPose(bd.manifest, card, headingAt(t), phiAt(t), offset, win);
cardPose(bd.manifest, card, headingAt(t), shownPhiAt(t), offsetShown(t), win);
const transform = (p: CardPose) => `translate3d(${p.shiftPx}px,0,0) scale(${p.scale})`;
let issuedAt = 0;
let live = true;
@ -307,16 +321,26 @@ export function createRidgeScene(opts: RidgeOptions): Scene | null {
if (!live) return;
const t0 = clock();
normalize(t0); // the angles of this stretch start within a turn of zero, so the transforms stay small however long the page has been open
offset = offsetNow(bd, win);
const next = offsetNow(bd, win);
if (next !== offset) {
offsetFrom = offsetShown(t0);
offset = next;
offsetEase = t0;
}
issuedAt = t0;
const frozen = reducedMotion?.matches === true;
// 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 times = easeMs > 0 && !frozen ? easeTimes(easeMs) : null;
for (let i = 0; i < k; i += 1) {
const frames = frozen
const frames: Keyframe[] = frozen
? [{ transform: transform(poseAt(i, t0)) }, { transform: transform(poseAt(i, t0)) }]
: Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({
transform: transform(poseAt(i, t0 + n * 1000)),
}));
boxes[i].style.transform = frames[0].transform;
: times
? times.map((ms) => ({ transform: transform(poseAt(i, t0 + ms)), offset: ms / (SEGMENT_S * 1000) }))
: Array.from({ length: SEGMENT_S + 1 }, (_, n) => ({
transform: transform(poseAt(i, t0 + n * 1000)),
}));
boxes[i].style.transform = frames[0].transform as string;
anims[i]?.cancel();
anims[i] = boxes[i].animate?.(frames, {
duration: SEGMENT_S * 1000,

View file

@ -1,6 +1,6 @@
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import { anchor, freeze, headingAt, hold, normalize, phiAt, resetHeading, setSpeedLimit, subscribe } from './heading';
import { effectiveMode, getCamera, isHeld, resetCamera, setCamera } from '../cameraState';
import { anchor, EASE_MS, easeEndsAt, freeze, headingAt, hold, normalize, phiAt, resetHeading, setSpeedLimit, shownPhiAt, subscribe } from './heading';
import { effectiveMode, getCamera, isHeld, resetCamera, setCamera, subscribe as onCamera } from '../cameraState';
import { maxSpeed } from './view';
import { parseManifest } from './manifest';
import { wireManifest } from './manifest.fixture';
@ -199,4 +199,50 @@ describe('the heading owner', () => {
anchor('q', 0, 5);
expect(cb).toHaveBeenCalledTimes(2);
});
it('bounds the speed from the anchor, before anything has been told the place is loaded: a stored speed above the bound does not run over the load', () => {
const ring = parseManifest(wireManifest({}, 3, 32), '/d/');
const slow = maxSpeed(ring, 'both');
setCamera({ mode: 'both', speedDegPerS: 12 }, 0);
anchor('p', 214, 0, (m) => maxSpeed(ring, m)); // what a scene start does, then awaits the first tiles
expect(headingAt(5 * S)).toBeCloseTo(214 + 5 * slow, 9);
expect(slow).toBeLessThan(12);
anchor('p', 214, 5 * S, (m) => maxSpeed(ring, m)); // a rebuild keeps the heading and the bound
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', () => {
setCamera({ mode: 'both', speedDegPerS: 1 }, 0);
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();
});
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', () => {
anchor('p', 100, 0);
choose('offset', 12, 0);
expect(phiAt(7.5 * S)).toBeCloseTo(90, 9);
choose('both', 12, 7.5 * S);
const at = 7.5 * S;
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));
shown.slice(1).forEach((v, i) => expect(v).toBeLessThan(shown[i]));
expect(shown[4]).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);
const t = at + 10 * S + 22.5 * S;
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.
choose('both', 6, t + 10 * S);
expect(shownPhiAt(t + 10 * S + 1)).toBeCloseTo(0, 6);
});
});

View file

@ -10,7 +10,8 @@
//
// 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.
// 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';
@ -24,17 +25,28 @@ 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. */
frozen: boolean;
}
const initial = (): State => ({ h0: 0, phi0: 0, t0: 0, anchor: undefined, frozen: false });
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. */
export const easeLeft = (at: number, now: number): number => {
const x = Math.min(1, Math.max(0, (now - at) / EASE_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. */
let speedLimit: ((mode: RotationMode) => number) | undefined;
type SpeedLimit = (mode: RotationMode) => number;
let speedLimit: SpeedLimit | undefined;
/** The mode in effect under a choice and a hold. */
const turning = (cam: CameraChoice, held: boolean, frozen: boolean): RotationMode => (frozen || held ? 'still' : cam.mode);
/** The speed the choice turns at, bounded for its mode at read: the stored value is the viewer's and is not rewritten. */
@ -50,8 +62,13 @@ const phiUnder = (now: number, cam: CameraChoice, held = isHeld()): number =>
/** 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`. */
/** 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);
const emit = () => [...listeners].forEach((cb) => cb());
@ -66,23 +83,41 @@ function settle(
state = { ...state, ...over, h0: h, phi0: phi, t0: now };
}
/** Listen to the viewer's choice from now on (again, if a test cleared the listeners): a change of mode or speed lands on the anchor at the moment it is made. */
/** 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));
const gap = shown - state.phi0;
const delta = gap - 360 * Math.round(gap / 360);
state = { ...state, ease: Math.abs(delta) < 1e-9 ? undefined : { delta, at } };
}
/**
* 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?.();
unbind = onCamera((next, prev, at, wasHeld) => {
// Taken to the moment of the change under the choice and hold in force until it; picking 'both' puts the camera on its heading.
settle(at, prev, {}, headingUnder(at, prev, wasHeld), next.mode === 'both' && !isHeld() ? 0 : phiUnder(at, prev, wasHeld));
});
unbind = onCamera(onChange);
}
/** 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());
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.
* 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.
*/
export function anchor(key: string, restDeg: number, now: number): void {
export function anchor(key: string, restDeg: number, now: number, limit?: SpeedLimit): void {
bind();
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 }, restDeg, 0);
settle(now, getCamera(), { anchor: key, ease: undefined }, restDeg, 0);
emit();
}
@ -98,12 +133,6 @@ export function hold(h: number, now: number): void {
else holdCamera(now); // the camera's listeners tell everyone, once
}
/** 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: ((mode: RotationMode) => number) | undefined, now: number): void {
settle(now, getCamera());
speedLimit = limit;
}
/** Nothing turns while `on` (reduced motion), whatever the viewer chose; the view stays where it is. */
export function freeze(on: boolean, now: number): void {
if (on === state.frozen) return;