export interface AnimationClock { elapsed: number; anchoredAt: number; speed: number; running: boolean; } function normalizeSpeed(speed: number) { return Math.min(3, Math.max(0.25, speed)); } export function createAnimationClock(now = 0, speed = 1): AnimationClock { return { elapsed: 0, anchoredAt: now, speed: normalizeSpeed(speed), running: true, }; } export function readAnimationClock(clock: AnimationClock, now: number) { if (!clock.running) return clock.elapsed; return clock.elapsed + Math.max(0, now - clock.anchoredAt) * clock.speed; } export function setAnimationClockSpeed( clock: AnimationClock, speed: number, now: number, ): AnimationClock { return { ...clock, elapsed: readAnimationClock(clock, now), anchoredAt: now, speed: normalizeSpeed(speed), }; } export function pauseAnimationClock(clock: AnimationClock, now: number): AnimationClock { if (!clock.running) return clock; return { ...clock, elapsed: readAnimationClock(clock, now), anchoredAt: now, running: false, }; } export function resumeAnimationClock(clock: AnimationClock, now: number): AnimationClock { if (clock.running) return clock; return { ...clock, anchoredAt: now, running: true, }; } export function resetAnimationClock(clock: AnimationClock, now: number): AnimationClock { return { ...clock, elapsed: 0, anchoredAt: now, running: true, }; }