feat(time): the app clock on the engine

src/time/clock.js is the app's own time in ms since the epoch: by default
Date.now exactly (read at each call), with freeze/offset/rate/reset for QA
and tests, and one frame time latched per engine frame (beginFrame). The
contract gains engine.clock { now, frameTime, ticked }, in the fake engine
(a controllable wall clock, fake.advanceTime, fake.appClock), the contract
suite (one frame time for every listener of a frame, latched before
preUpdate, never decreasing), Cesium and Navara.

Cesium latches on the viewer clock's onTick, which CesiumWidget runs right
before scene.render, so scene listeners the app added before the engine
existed read the same frame time; the subscription appears on first use
and destroy removes it. The viewer clock itself is untouched: in the app
it never animates (shouldAnimate false, multiplier 1, its time frozen at
boot), and its time still drives Cesium's lighting as before. Navara
latches in the engine's handler of the view's preUpdate, and the look
reads the engine clock's frame time for the sun, so the app clock is the
one time source on Navara too.

src/time is a portable root in check-import-directions: no engine
packages, no browser globals.
This commit is contained in:
German Khokhlov committed 2026-10-16 15:01:36 +04:00
1 parent 27e28373d0
commit f1a2df5cfe
20 files changed
+771 -13

No files matched your search

+113
View File
@@ -0,0 +1,113 @@
// The app's own time: milliseconds since the Unix epoch, read by layers and
// both globe engines instead of Cesium's JulianDate or viewer.clock. By
// default it is the wall clock (Date.now) exactly; QA and tests can freeze,
// offset or speed it up. The globe engine latches one frame time per engine
// frame (beginFrame), so every reader in a frame sees the same value.
// No engine, DOM or Node imports: this runs in the browser and in Node tests.
const isFiniteNumber = (value) =>
typeof value === 'number' && Number.isFinite(value);
function finite(value, label) {
if (!isFiniteNumber(value))
throw new TypeError(`${label} must be a finite number: ${value}`);
return value;
}
/**
* @typedef {object} AppClock
* @property {() => number} now The current app time (ms since the epoch).
* @property {() => number} frameTime The time latched for the current engine
* frame; the current time before the first frame.
* @property {() => number} beginFrame Latches and returns the frame time; the
* globe engine calls it once at the start of each of its frames.
* @property {(ms?: number) => void} freeze Holds the time at `ms` (default:
* the current time). QA and tests only.
* @property {() => void} resume Runs on from the frozen time.
* @property {(ms: number) => void} offset Sets the time to the wall clock
* plus `ms`, running on from it at the current rate (it ends a freeze).
* QA and tests only.
* @property {(rate: number) => void} rate App milliseconds per wall
* millisecond (>= 0), without a jump. QA and tests only.
* @property {() => void} reset Back to the wall clock.
* @property {() => { frozen: boolean, offsetMs: number, rate: number }} state
* The controls in force (offsetMs: the current time minus the wall clock).
*/
/**
* @param {{ now?: () => number }} [options] `now`: the wall clock (Date.now).
* @returns {AppClock}
*/
export function createAppClock({ now: source = () => Date.now() } = {}) {
if (typeof source !== 'function')
throw new TypeError('createAppClock needs a now() function');
// Rate 1: wall + offsetMs, exact. Any other rate: anchorValue plus the wall
// time since anchorSource, scaled.
let offsetMs = 0;
let rateValue = 1;
let anchorValue = 0;
let anchorSource = 0;
let frozen = null;
let latched = null;
const running = () =>
rateValue === 1
? source() + offsetMs
: anchorValue + (source() - anchorSource) * rateValue;
const now = () => (frozen === null ? running() : frozen);
// Make the running clock read `value` from this moment on.
const runFrom = (value) => {
if (rateValue === 1) offsetMs = value - source();
else {
anchorValue = value;
anchorSource = source();
}
};
return {
now,
frameTime: () => (latched === null ? now() : latched),
beginFrame() {
latched = now();
return latched;
},
freeze(ms) {
frozen = ms === undefined ? now() : finite(ms, 'Frozen time');
},
resume() {
if (frozen === null) return;
const value = frozen;
frozen = null;
runFrom(value);
},
offset(ms) {
const value = source() + finite(ms, 'Clock offset');
frozen = null;
runFrom(value);
},
rate(rate) {
if (!(isFiniteNumber(rate) && rate >= 0))
throw new TypeError(`Clock rate must be a finite number >= 0: ${rate}`);
if (frozen !== null) {
rateValue = rate;
return;
}
const value = running();
rateValue = rate;
runFrom(value);
},
reset() {
offsetMs = 0;
rateValue = 1;
frozen = null;
},
state: () => ({
frozen: frozen !== null,
offsetMs: now() - source(),
rate: rateValue,
}),
};
}
/** The page's app clock: the one both globe engines and the layers read. */
export const appClock = createAppClock();
+145
View File
@@ -0,0 +1,145 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { appClock, createAppClock } from './clock.js';
// A wall clock the test moves by hand.
function manualSource(start = Date.UTC(2026, 9, 16, 12)) {
let value = start;
return {
now: () => value,
advance(ms) {
value += ms;
},
};
}
test('by default the app clock is the wall clock, exactly', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
assert.equal(clock.now(), wall.now());
wall.advance(1234.5);
assert.equal(clock.now(), wall.now());
});
test('the page clock reads Date.now', () => {
const before = Date.now();
const value = appClock.now();
assert.ok(value >= before && value <= Date.now());
});
test('frameTime is the time latched by beginFrame, one value per frame', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
// Before the first frame it is the current time.
assert.equal(clock.frameTime(), wall.now());
const latched = clock.beginFrame();
assert.equal(latched, wall.now());
wall.advance(7);
assert.equal(clock.frameTime(), latched);
assert.equal(clock.now(), latched + 7);
assert.equal(clock.beginFrame(), latched + 7);
assert.equal(clock.frameTime(), latched + 7);
});
test('freeze holds the time, resume continues from it', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
const frozenAt = Date.UTC(2020, 0, 1);
clock.freeze(frozenAt);
wall.advance(5000);
assert.equal(clock.now(), frozenAt);
assert.equal(clock.beginFrame(), frozenAt);
clock.resume();
assert.equal(clock.now(), frozenAt);
wall.advance(250);
assert.equal(clock.now(), frozenAt + 250);
});
test('freeze without a time holds the current time', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
const at = wall.now();
clock.freeze();
wall.advance(100);
assert.equal(clock.now(), at);
});
test('offset shifts the clock from the wall clock', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
clock.offset(-30_000);
assert.equal(clock.now(), wall.now() - 30_000);
wall.advance(10);
assert.equal(clock.now(), wall.now() - 30_000);
clock.offset(0);
assert.equal(clock.now(), wall.now());
});
test('rate runs the clock faster or slower without a jump', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
const start = clock.now();
clock.rate(4);
assert.equal(clock.now(), start);
wall.advance(1000);
assert.equal(clock.now(), start + 4000);
clock.rate(0);
wall.advance(1000);
assert.equal(clock.now(), start + 4000);
clock.rate(1);
wall.advance(500);
assert.equal(clock.now(), start + 4500);
});
test('a rate set while frozen applies from resume', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
clock.freeze(1000);
clock.rate(2);
wall.advance(400);
assert.equal(clock.now(), 1000);
clock.resume();
wall.advance(400);
assert.equal(clock.now(), 1800);
});
test('reset returns to the wall clock and reports the state', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
assert.deepEqual(clock.state(), { frozen: false, offsetMs: 0, rate: 1 });
clock.rate(3);
clock.freeze();
assert.equal(clock.state().frozen, true);
assert.equal(clock.state().rate, 3);
clock.reset();
assert.deepEqual(clock.state(), { frozen: false, offsetMs: 0, rate: 1 });
assert.equal(clock.now(), wall.now());
});
test('non-finite controls are refused', () => {
const clock = createAppClock({ now: () => 0 });
for (const call of [
() => clock.freeze(Number.NaN),
() => clock.offset(Number.POSITIVE_INFINITY),
() => clock.rate('2'),
() => clock.rate(-1),
])
assert.throws(call, TypeError);
assert.throws(() => createAppClock({ now: 5 }), TypeError);
});
test('offset ends a freeze and runs on from the wall clock plus the offset', () => {
const wall = manualSource();
const clock = createAppClock({ now: wall.now });
clock.freeze(5);
clock.offset(1000);
assert.equal(clock.now(), wall.now() + 1000);
wall.advance(20);
assert.equal(clock.now(), wall.now() + 1000);
});
test('the default wall clock is read through Date.now at each call', (t) => {
const clock = createAppClock();
t.mock.method(Date, 'now', () => 1_800_000_000_000);
assert.equal(clock.now(), 1_800_000_000_000);
});