Merge main (d49d3d10) into the renderer branch

This commit is contained in:
Sameh Khamis committed 2026-11-14 17:21:53 -08:00
commit 489c316556
134 files changed
+4980 -229

No files matched your search

+2 -1
View File
@@ -32,7 +32,8 @@ export function createCards({
if (!layerState._viewer) return;
const { query } = components.rendering.scenePorts();
const project = (position) => query?.project(position) ?? null;
const now = Date.now();
// Ages count back from the time shown: the window's end, or now when live.
const now = components.model.ageReferenceMs();
const entries = [];
/** @type {Array<{x: number, y: number}>} Screen positions of accepted labels. */
const accepted = [];
+19 -4
View File
@@ -310,7 +310,7 @@ export function createModel({
* (on top) and never distance-faded by the overlay.
* Exported for unit tests.
* @param {Object} fire - Detection record.
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -351,9 +351,10 @@ export function createModel({
* Card model for an ambient fire detection, e.g. title "▲ 47 MW", detail
* "high · 14h · N20". Ages are computed against each detection's acquisition
* time — with the live feed everything reads under 24 h (and a stale cache
* reads truthfully old). Exported for unit tests.
* reads truthfully old); `nowMs` is the time ages count back from, the end
* of the window shown (see {@link ageReferenceMs}). Exported for unit tests.
* @param {{fire: Object, position: {x: number, y: number, z: number}}} candidate - Label candidate.
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -385,7 +386,7 @@ export function createModel({
* "max 210 MW · new 3h". Accent comes from the candidate (renderHeat sets
* it with {@link cellCardAccent}). Exported for unit tests.
* @param {{cell: Object, position: {x: number, y: number, z: number}, accent: string}} candidate
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -516,6 +517,19 @@ export function createModel({
return { unit: 'd', count: Math.round(hours / 24) };
}
/**
* The time a card's ages count back from: the end of the 24 hours shown
* when the snapshot ends at a set time, now while it runs to now. A window
* that ended months ago then reads its fires as hours old, as they were.
* @param {number} [nowMs] - Current epoch milliseconds.
* @returns {number}
*/
function ageReferenceMs(nowMs = Date.now()) {
const at = layerState?._at;
return Number.isFinite(at) ? at : nowMs;
}
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
function formatAge(deltaMs) {
@@ -590,6 +604,7 @@ export function createModel({
cellCardAccent,
formatLatLon,
formatFrp,
ageReferenceMs,
formatAge,
formatAgeLabel,
formatAgoMinutes,
+3 -1
View File
@@ -183,7 +183,9 @@ export function createSelection({
confidence: components.model.confidenceBucket(fire.confidence),
age:
fire.acqMs > 0
? components.model.formatAge(Date.now() - fire.acqMs)
? components.model.formatAge(
components.model.ageReferenceMs() - fire.acqMs,
)
: 'unknown',
sensor: fire.sensor || 'unknown',
},
+58
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
import { createCards } from './cards.js';
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
const now = 1800000000000;
@@ -42,3 +43,60 @@ test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (conte
setLocale(previousLocale);
}
});
test('fire cards count ages from the end of the window shown, and from now when live', (context) => {
const now = Date.UTC(2026, 10, 14, 12);
context.mock.method(Date, 'now', () => now);
// A window that ended months before now: its newest fire three hours earlier.
const at = Date.UTC(2026, 7, 1, 12);
const layerState = { _at: at };
const model = createModel({ layerState, services: { anchors: {} } });
const cell = {
count: 4,
maxFrp: 210,
newestAcqMs: at - 3 * 3_600_000,
latCell: 1,
lonCell: 2,
};
const previousLocale = getLocale();
try {
setLocale('en');
assert.equal(model.ageReferenceMs(), at);
const card = model.buildCellCard({ cell, position: {} }, model.ageReferenceMs());
assert.equal(card.details[0], 'max 210 MW · new 3h', 'not months old');
// The cards the scene shows use the same time.
const entries = [];
layerState._viewer = { canvas: { clientWidth: 800, clientHeight: 600 } };
layerState._fireByCardId = new Map();
layerState._selectedFire = null;
layerState._labelCandidates = [{ cell, position: {} }];
layerState._labelLodDistance = 0;
const { rebuildAmbientLabels } = createCards({
layerState,
services: {},
components: {
model,
rendering: {
scenePorts: () => ({
query: { project: () => ({ x: 400, y: 300 }), isOccluded: () => false },
}),
},
},
config: { overlayHost: { setEntries: (source, shown) => entries.push(...shown) } },
});
rebuildAmbientLabels();
assert.equal(entries.length, 1);
assert.equal(entries[0].details[0], 'max 210 MW · new 3h');
// Live, they count from now.
layerState._at = null;
cell.newestAcqMs = now - 5 * 3_600_000;
assert.equal(model.ageReferenceMs(), now);
entries.length = 0;
rebuildAmbientLabels();
assert.equal(entries[0].details[0], 'max 210 MW · new 5h');
} finally {
setLocale(previousLocale);
}
});
+7 -1
View File
@@ -1,14 +1,20 @@
import { forgetPlacedAircraft } from './placed.js';
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
export function createClockFollow({ flightState, parts }) {
export function createClockFollow({ flightState, services, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses, floors and the tracked
* trail belong to the time the clock left.
*/
function resetMotion() {
forgetPlacedAircraft(
services?.placement,
flightState._positionHistory.keys(),
);
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
+19
View File
@@ -223,6 +223,25 @@ test('a jump forgets how contacts moved; clearing drops every contact', () => {
assert.ok(calls.includes('model:abc123'));
});
test('leaving the live edge forgets every contact a host placement was told of', () => {
const forgotten = [];
const flightState = {
records: records(),
_positionHistory: new Map([
['abc123', []],
['def456', []],
]),
_displayCourse: new Map(),
_groundSnap: { clear() {} },
_displayFloorState: new Map(),
};
const parts = { tracking: { _clearTrail() {} } };
const services = { placement: { forget: (id) => forgotten.push(id) } };
createClockFollow({ flightState, services, parts }).resetMotion();
assert.deepEqual(forgotten, ['abc123', 'def456']);
assert.equal(flightState._positionHistory.size, 0);
});
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
const probe = ingestion({
async getSnapshot() {
+13
View File
@@ -1,5 +1,6 @@
import { courseSlewCapDps } from '../../data/motionModel.js';
import { createAircraftIcons } from '../../data/aircraftIconLayer.js';
import { placeAircraftAt } from './placed.js';
import { motionCourse } from '../../render/motion/iconMotion.js';
import { distanceSquared, norm180 } from '../../geo/vector.js';
import {
@@ -31,6 +32,18 @@ export function createIcons({ flightState, services, parts }) {
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
// A host-supplied placement, if any, draws a live contact where it places it.
placeAt: services.placement
? (icao24, wallMs, info, history, out) =>
placeAircraftAt(
services.placement,
icao24,
wallMs,
info,
history,
out,
)
: null,
holdsPlan: (icao24) =>
flightState._focusEvidenceIds.has(icao24) ||
flightState._floorPinned.has(icao24),
+88 -2
View File
@@ -4,6 +4,7 @@ import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createIcons } from './icons.js';
import { createContactIcons } from '../../data/aircraftIconLayer.js';
import { layerPlacement } from '../../data/placementProvider.js';
function services(focus = {}) {
return {
@@ -17,8 +18,11 @@ function services(focus = {}) {
};
}
function setup({ focus, motion = {}, rendering = {} } = {}) {
const svc = services(focus);
function setup({ focus, motion = {}, rendering = {}, placement = null } = {}) {
const svc = {
...services(focus),
...(placement ? { placement: layerPlacement(placement, 'aircraft') } : {}),
};
const flightState = createFlightState({ services: svc });
flightState._icons = createContactIcons();
const parts = {
@@ -214,3 +218,85 @@ test('a hidden contact shown again is where dead reckoning puts it now', (t) =>
'not where it was hidden',
);
});
test('a live contact a placement places is drawn along where it places it', (t) => {
const t0 = Date.UTC(2026, 10, 9, 12);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const asked = [];
let places = true;
const regimes = [];
const { flightState, icons, set } = setup({
placement: {
layer: () => ({
place(id, wallMs) {
asked.push(wallMs);
if (!places) return null;
// A degree of longitude every 10 s, at its own height and course.
return {
lat: 30,
lon: (wallMs - t0) / 10_000,
altitudeM: 2000,
courseDeg: 90 + (wallMs - t0) / 1000,
speedMps: 200,
};
},
}),
},
motion: {
_motionRegime: () => {
regimes.push(1);
return {
kind: 'fix',
fix: { position: at(5), time: null },
speed: 0,
heading: 10,
};
},
_fixEpochMs: () => t0,
},
});
hold(set, 'p', at(0), 0, true);
flightState._positionHistory.set('p', [{ position: at(0) }]);
flightState.records.data.set('p', { renderAltitudeM: 1000 });
const now = icons._displayMs();
const leadMs = Date.now() - now;
icons._planIcon('p');
// Asked for the wall times the segment's ends stand for.
assert.deepEqual(asked, [now + leadMs, now + 1000 + leadMs]);
assert.equal(regimes.length, 0, 'its own motion is not planned');
const item = set.item('p');
assert.equal(item.motion.kind, 'lerp');
assert.ok(
Cesium.Cartesian3.distance(
item.motion.from,
Cesium.Cartesian3.fromDegrees((now + leadMs - t0) / 10_000, 30, 2000),
) < 1e-6,
);
assert.ok(
Cesium.Cartesian3.distance(
item.motion.to,
Cesium.Cartesian3.fromDegrees(
(now + 1000 + leadMs - t0) / 10_000,
30,
2000,
),
) < 1e-6,
);
assert.equal(item.motion.t0, now);
assert.equal(item.motion.t1, now + 1000);
assert.ok(Math.abs(item.motion.courseSlopeDeg - 1) < 1e-9);
assert.equal(set.expires('p'), now + 1000);
// No answer: the layer's own motion plans it.
places = false;
icons._planIcon('p');
assert.equal(regimes.length, 1);
assert.equal(set.item('p').motion.kind, 'hold');
// Following the world clock, the placement is not asked.
places = true;
asked.length = 0;
flightState.timeline = { active: () => true };
icons._planIcon('p');
assert.deepEqual(asked, []);
});
+1
View File
@@ -37,6 +37,7 @@ export function createCivilFlightLayer({
parts.clockFollow = createClockFollow(context);
const applySnapshot = createFlightSnapshotRenderer({
flightState,
placement: services.placement ?? null,
records: flightState.records,
militaryRegistry: services.militaryRegistry,
groundFloor: services.groundFloor,
+9
View File
@@ -1,5 +1,6 @@
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from './placed.js';
export function createLifecycle({
flightState,
@@ -56,6 +57,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects = new Map();
flightState.records.data = new Map();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory = new Map();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
@@ -247,6 +252,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects.clear();
flightState.records.data.clear();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
+14
View File
@@ -42,6 +42,7 @@ import {
corridorPathLatLon,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from './placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -231,6 +232,19 @@ export function createMotion({
}
const out = result || vec();
// A host-supplied placement decides where a live contact is drawn; with
// none, or no answer for this contact, the layer's own motion below does.
if (
placeLiveAircraft(
flightState,
services.placement,
icao24,
info,
history,
out,
)
)
return out;
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
+191 -2
View File
@@ -3,8 +3,11 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { arcOffsetEnu } from '../../data/motionModel.js';
import { createMotion as createMilitaryMotion } from '../military/motion.js';
import { layerPlacement } from '../../data/placementProvider.js';
import { observeLiveAircraft } from './placed.js';
function fixture() {
function fixture(placement = null) {
const flightState = {
records: { data: new Map() },
_positionHistory: new Map(),
@@ -16,7 +19,7 @@ function fixture() {
};
const motion = createMotion({
flightState,
services: { groundFloor: {}, camera: {}, focus: {} },
services: { groundFloor: {}, camera: {}, focus: {}, placement },
parts: {},
});
return { flightState, motion };
@@ -182,3 +185,189 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
),
);
});
/** Two fixes a minute apart, read across the minute from a clock at `start`. */
function placedScenario(create, placement, record) {
const flightState = {
records: { data: new Map() },
_positionHistory: new Map(),
_focusEvidenceIds: new Set(),
_scratchArc: {},
_scratchOffset: new Cesium.Cartesian3(),
_scratchRenderTime: new Cesium.JulianDate(),
now: () => 0,
};
const motion = create({
flightState,
services: { groundFloor: {}, camera: {}, focus: {}, placement },
parts: {},
});
const start = Date.parse('2026-10-24T12:00:00Z');
const at = (seconds) =>
Cesium.JulianDate.fromDate(new Date(start + seconds * 1000));
flightState.records.data.set('abc123', record);
flightState._positionHistory.set('abc123', [
{
time: at(0),
position: Cesium.Cartesian3.fromDegrees(-97, 30, 1000),
track: 90,
velocity: 100,
},
{
time: at(60),
position: Cesium.Cartesian3.fromDegrees(-96.99, 30, 1000),
track: 90,
velocity: 100,
},
]);
const drawn = [];
for (let seconds = 0; seconds <= 150; seconds += 7.5) {
flightState.now = () => start + seconds * 1000;
const position = motion._deadReckon('abc123', new Cesium.Cartesian3());
drawn.push({
position,
course: flightState._drCourseDeg,
speed: flightState._drSpeedMps,
hold: flightState._drCourseHold,
});
}
return { flightState, motion, drawn, start };
}
const declining = (asked) =>
layerPlacement(
{
layer: () => ({
place: (id, wallMs) => {
asked.push([id, wallMs]);
return null;
},
}),
},
'aircraft',
);
// Each kind's record carries only its own kinematics fields.
for (const [name, create, record] of [
[
'civil',
createMotion,
{ velocity: 100, true_track: 90, renderAltitudeM: 1234 },
],
[
'military',
createMilitaryMotion,
{ speedMps: 100, track: 90, renderAltitudeM: 1234 },
],
]) {
test(`${name} aircraft move as before without a placement or with one that places nothing`, () => {
const own = placedScenario(create, null, record).drawn;
const asked = [];
const declined = placedScenario(create, declining(asked), record).drawn;
assert.equal(asked.length, own.length);
assert.equal(declined.length, own.length);
for (let i = 0; i < own.length; i++) {
assert.ok(
Cesium.Cartesian3.equals(declined[i].position, own[i].position),
);
assert.equal(declined[i].course, own[i].course);
assert.equal(declined[i].speed, own[i].speed);
assert.equal(declined[i].hold, own[i].hold);
}
});
test(`${name} aircraft are drawn where a placement places them, live only`, () => {
const asked = [];
const placement = layerPlacement(
{
layer: () => ({
place(id, wallMs) {
asked.push(wallMs);
return wallMs % 2 === 0
? {
lat: 30.5,
lon: -96.5,
altitudeM: 2000,
courseDeg: 45,
speedMps: 0.5,
extrapolating: true,
}
: { lat: 30.6, lon: -96.4 };
},
}),
},
'aircraft',
);
const { flightState, motion, start } = placedScenario(
create,
placement,
record,
);
flightState.now = () => start + 2000;
const out = motion._deadReckon('abc123', new Cesium.Cartesian3());
close(out, Cesium.Cartesian3.fromDegrees(-96.5, 30.5, 2000));
assert.equal(flightState._drCourseDeg, 45);
assert.equal(flightState._drSpeedMps, 0.5);
assert.equal(flightState._drCourseHold, true);
// No height, course or speed placed: the record's drawn height and kinematics.
flightState.now = () => start + 2001;
close(
motion._deadReckon('abc123', new Cesium.Cartesian3()),
Cesium.Cartesian3.fromDegrees(-96.4, 30.6, 1234),
);
assert.equal(flightState._drCourseDeg, 90);
assert.equal(flightState._drSpeedMps, 100);
// Following the world clock the layer's own motion places it, unasked.
const before = asked.length;
flightState.timeline = { active: () => true };
const own = motion._deadReckon('abc123', new Cesium.Cartesian3());
assert.equal(asked.length, before);
assert.ok(Cesium.Cartesian3.distance(own, out) > 1000);
});
}
test('an aircraft fix is told to the placement live, with its drawn height', () => {
const told = [];
const placement = layerPlacement(
{
layer: () => ({
place: () => null,
observe: (id, fix) => told.push([id, fix]),
}),
},
'aircraft',
);
const state = { timeline: { active: () => false } };
const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false };
observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270);
observeLiveAircraft(
state,
placement,
'abc123',
6000,
{ ...meta, renderAltitudeInvented: true, onGround: true },
null,
undefined,
);
observeLiveAircraft(state, null, 'abc123', 7000, meta, 80, 270);
state.timeline.active = () => true;
observeLiveAircraft(state, placement, 'abc123', 8000, meta, 80, 270);
assert.equal(told.length, 2);
assert.deepEqual(told[0], [
'abc123',
{
timeMs: 5000,
lat: 1,
lon: 2,
altitudeM: 300,
speedMps: 80,
courseDeg: 270,
headingDeg: NaN,
onGround: false,
},
]);
assert.ok(Number.isNaN(told[1][1].altitudeM));
assert.ok(Number.isNaN(told[1][1].speedMps));
assert.ok(Number.isNaN(told[1][1].courseDeg));
assert.equal(told[1][1].onGround, true);
});
+127
View File
@@ -0,0 +1,127 @@
import { fromDegreesInto, toCartographicRadians } from '../../geo/ellipsoid.js';
import { COURSE_HOLD_SPEED_MPS } from '../../data/motionModel.js';
import { followsClock } from './policy.js';
/**
* Where the host-supplied placement (`services.placement`,
* ../../data/placementProvider.js) draws an aircraft at `wallMs`, written
* into `out`, with the course and speed it is drawn with; null when it has
* no answer for this aircraft. A placement without a height keeps the
* aircraft's newest drawn height, and one without a course or speed the
* record's own.
* @param {object} placement
* @param {string} icao24
* @param {number} wallMs
* @param {object|undefined} info The aircraft's record.
* @param {{position: {x: number, y: number, z: number}}[]} history Its fixes, newest last.
* @param {{x: number, y: number, z: number}} out
* @returns {{courseDeg: number, speedMps: number, extrapolating: boolean}|null}
*/
export function placeAircraftAt(placement, icao24, wallMs, info, history, out) {
const placed = placement.place(icao24, wallMs);
if (!placed) return null;
let heightM = placed.altitudeM;
if (!Number.isFinite(heightM)) heightM = info?.renderAltitudeM;
if (!Number.isFinite(heightM))
heightM =
toCartographicRadians(history[history.length - 1].position)?.height ?? 0;
const speedMps = Number.isFinite(placed.speedMps)
? placed.speedMps
: // Civil records carry velocity and true_track, military speedMps and track.
Number.isFinite(info?.velocity)
? info.velocity
: info?.speedMps || 0;
const courseDeg = Number.isFinite(placed.courseDeg)
? placed.courseDeg
: Number.isFinite(info?.true_track)
? info.true_track
: info?.track || 0;
fromDegreesInto(placed.lon, placed.lat, heightM, out);
return { courseDeg, speedMps, extrapolating: placed.extrapolating };
}
/**
* Where the host-supplied placement draws a live aircraft now, written into
* `out` with the course scratches `_deadReckon` sets on `flightState`; false
* when there is no placement, the layer follows the world clock, or it has
* no answer for this aircraft, and the layer's own motion places it.
* @param {object} flightState The civil or military flight state.
* @param {object|null|undefined} placement
* @param {string} icao24
* @param {object|undefined} info The aircraft's record.
* @param {{position: {x: number, y: number, z: number}}[]} history Its fixes, newest last.
* @param {{x: number, y: number, z: number}} out
* @returns {boolean}
*/
export function placeLiveAircraft(
flightState,
placement,
icao24,
info,
history,
out,
) {
if (!placement || followsClock(flightState)) return false;
const placed = placeAircraftAt(
placement,
icao24,
flightState.now(),
info,
history,
out,
);
if (!placed) return false;
flightState._drCourseDeg = placed.courseDeg;
flightState._drSpeedMps = placed.speedMps;
flightState._drCourseHold = placed.speedMps < COURSE_HOLD_SPEED_MPS;
flightState._drExtrapolating = placed.extrapolating;
return true;
}
/**
* Tell the host-supplied placement, if any, that the aircraft `ids` left the
* layer (removed, the layer off, or the world clock moved it to another time).
* @param {object|null|undefined} placement
* @param {Iterable<string>} ids
*/
export function forgetPlacedAircraft(placement, ids) {
if (!placement) return;
for (const id of ids) placement.forget(id);
}
/**
* Tell the host-supplied placement an aircraft's fix as the layer took it
* (nothing while the layer follows the world clock): its own time, its
* position, the height the layer draws it at (NaN when that height is
* invented), and its reported speed, course and ground state.
* @param {object} flightState
* @param {object|null|undefined} placement
* @param {string} icao24
* @param {number} fixEpochMs
* @param {{rawLat: number, rawLon: number, renderAltitudeM: number,
* renderAltitudeInvented?: boolean, onGround?: boolean}} meta
* @param {number|null|undefined} speedMps
* @param {number|null|undefined} courseDeg
*/
export function observeLiveAircraft(
flightState,
placement,
icao24,
fixEpochMs,
meta,
speedMps,
courseDeg,
) {
if (!placement || followsClock(flightState)) return;
placement.observe(icao24, {
timeMs: fixEpochMs,
lat: meta.rawLat,
lon: meta.rawLon,
altitudeM:
meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM,
speedMps: Number.isFinite(speedMps) ? speedMps : NaN,
courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN,
headingDeg: NaN,
onGround: meta.onGround === true,
});
}
+13
View File
@@ -8,6 +8,7 @@ import {
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
import { observeLiveAircraft } from './placed.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
@@ -35,6 +36,7 @@ function noteDelivery(flightState, snapshot) {
/** Apply reconciled aircraft records to the layer's drawing and follow state. */
export function createFlightSnapshotRenderer({
flightState,
placement = null,
records,
militaryRegistry,
groundFloor,
@@ -112,6 +114,17 @@ export function createFlightSnapshotRenderer({
}
const isTracked = icao24 === flightState._trackedIcao;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
placement,
icao24,
fixEpochMs,
meta,
meta.velocity,
meta.true_track,
);
// Append to position history stamped with the FEED's fix epoch
// (time_position), not client receipt time — OpenSky positions arrive
// 5-15s stale and receipt-time stamping is what caused the
+7 -1
View File
@@ -1,14 +1,20 @@
import { forgetPlacedAircraft } from '../flights/placed.js';
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
export function createClockFollow({ flightState, parts }) {
export function createClockFollow({ flightState, services, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses and the tracked trail
* belong to the time the clock left.
*/
function resetMotion() {
forgetPlacedAircraft(
services?.placement,
flightState._positionHistory.keys(),
);
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
+13
View File
@@ -1,4 +1,5 @@
import { createAircraftIcons } from '../../data/aircraftIconLayer.js';
import { placeAircraftAt } from '../flights/placed.js';
import {
COCKPIT_CONTACT_SIZE_PX,
COURSE_MAX_DPS,
@@ -18,5 +19,17 @@ export function createIcons({ flightState, services, parts }) {
staleAlpha: STALE_ALPHA,
courseMaxDps: COURSE_MAX_DPS,
cockpitContactSizePx: COCKPIT_CONTACT_SIZE_PX,
// A host-supplied placement, if any, draws a live contact where it places it.
placeAt: services.placement
? (icao24, wallMs, info, history, out) =>
placeAircraftAt(
services.placement,
icao24,
wallMs,
info,
history,
out,
)
: null,
});
}
+1
View File
@@ -33,6 +33,7 @@ export function createMilitaryFlightLayer({
parts.clockFollow = createClockFollow(context);
const applySnapshot = createMilitarySnapshotRenderer({
flightState,
placement: services.placement ?? null,
records: flightState.records,
groundFloor: services.groundFloor,
militaryRegistry: services.militaryRegistry,
+9
View File
@@ -1,5 +1,6 @@
import { findCamera, findFrame } from '../../render/rendererOf.js';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from '../flights/placed.js';
export function createLifecycle({
flightState,
@@ -52,6 +53,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects = new Map();
flightState.records.data = new Map();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory = new Map();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
@@ -224,6 +229,10 @@ export function createLifecycle({
flightState._iconFocusActive = 0;
flightState._detectionObjects.clear();
flightState.records.data.clear();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
+14
View File
@@ -35,6 +35,7 @@ import {
limitCourseStep,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from '../flights/placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -133,6 +134,19 @@ export function createMotion({
}
const out = result || vec();
// A host-supplied placement decides where a live contact is drawn; with
// none, or no answer for this contact, the layer's own motion below does.
if (
placeLiveAircraft(
flightState,
services.placement,
icao24,
info,
history,
out,
)
)
return out;
// Render behind real time, as late as the feed is (displayDelayMs), so we
// interpolate between two KNOWN fixes whenever possible.
const renderTime =
+13
View File
@@ -8,6 +8,7 @@ import {
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { newestReport, pushReport } from '../../data/aircraftMotionRegime.js';
import { observeLiveAircraft } from '../flights/placed.js';
/**
* Note how late each report in a live snapshot is, and aim the display delay
@@ -35,6 +36,7 @@ function noteDelivery(flightState, snapshot) {
/** Apply military record changes to the layer's drawing and existing follow operations. */
export function createMilitarySnapshotRenderer({
flightState,
placement = null,
records,
groundFloor,
militaryRegistry,
@@ -86,6 +88,17 @@ export function createMilitarySnapshotRenderer({
if (groundFlipped) flightState._groundSnap.forget(icao24);
const isTracked = icao24 === flightState._trackedIcao;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
placement,
icao24,
fixEpochMs,
meta,
meta.speedMps,
meta.track,
);
// Append to position history stamped with the FEED's fix epoch.
// adsb.lol's seen_pos is the AGE in seconds of the last position
// report, so the fix epoch is receipt time minus that age. Only
+29
View File
@@ -19,6 +19,7 @@ import { RAIL_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
import { publicRailCatalog } from '../../data/railFeeds.js';
import { pointAtS } from '../../data/railPaths.js';
import { fleetModelFakes } from '../../testSupport/fleetModelFakes.mjs';
import { PLACED_WAKE_MS } from '../transit/movement.js';
const M_PER_DEG = 111_320;
const LAT = 42.36;
@@ -511,3 +512,31 @@ test('turning the layer off ends the hold', async (t) => {
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
test('a train a placement holds still stops animating, and moves on when the placement does', async (t) => {
let spot = { lat: LAT, lon: LON0 + 3000 / KX };
const app = await onTheLine(t, {
placement: {
layer: () => ({
place: (id) => (id === T1 ? { ...spot, speedMps: 0 } : null),
}),
},
});
app.run(1_000);
const entry = app.entry(T1);
assert.equal(entry.placed, true);
assert.equal(app.state()._moving.has(entry), false, 'parked: not animating');
assert.notEqual(entry.wakeTimer, null, 'a wake asks the placement again');
assert.ok(app.state()._moving.has(app.entry(T2)), 'its own motion runs on');
spot = { lat: LAT, lon: spot.lon + 10 / KX };
t.mock.timers.tick(PLACED_WAKE_MS);
assert.ok(app.state()._moving.has(entry), 'moving again');
for (let i = 0; i < 3; i += 1) {
spot = { lat: LAT, lon: spot.lon + 1 / KX };
app.run(250);
assert.ok(app.state()._moving.has(entry), 'while it moves');
}
app.run(250);
assert.equal(app.state()._moving.has(entry), false, 'stopped again');
});
+3
View File
@@ -82,6 +82,7 @@ export function createIngestion({ state, services, parts, source }) {
state._moving.delete(entry);
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
entry.placement?.forget(key);
state._trains.delete(key);
state._revision += 1;
// A copy it hid may now be the one to draw.
@@ -274,6 +275,8 @@ export function createIngestion({ state, services, parts, source }) {
const entry = {
key,
feedId: feed.id,
// A host-supplied placement, if any, draws it while live.
placement: services.placement ?? null,
marker: null,
category: record.category,
railMode: record.mode,
+1
View File
@@ -22,6 +22,7 @@ export function createLifecycle({ state, services, parts, timetable }) {
for (const entry of state._trains.values()) {
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
entry.placement?.forget(entry.key);
}
state._trains.clear();
state._moving.clear();
+30 -10
View File
@@ -11,7 +11,12 @@ import {
} from '../../geo/ellipsoid.js';
import { horizonFrom } from '../../geo/horizon.js';
import { distanceSquared } from '../../geo/vector.js';
import { applyDisplayCourse, updatePlayback } from '../transit/movement.js';
import {
PLACED_WAKE_MS,
applyDisplayCourse,
playbackMoving,
updatePlayback,
} from '../transit/movement.js';
import { HEIGHT_SAMPLE_MAX_ALTITUDE_M } from '../transit/policy.js';
import {
COLD_CELL_FLUSH_MS,
@@ -721,8 +726,11 @@ export function createRendering({ state, services, parts }) {
*/
function place(entry) {
const sample = entry.sample;
// Placed by a host-supplied placement, it is drawn where that puts it.
const onPath =
entry.path && placeOnPath(entry.path, sample, entry.segment, pathPoint);
!entry.placed &&
entry.path &&
placeOnPath(entry.path, sample, entry.segment, pathPoint);
const lat = onPath
? pathPoint.lat
: Number.isFinite(sample?.lat)
@@ -796,16 +804,26 @@ export function createRendering({ state, services, parts }) {
if (!entry.marker) return;
place(entry);
const sample = entry.sample;
const moving =
playing(entry) &&
sample?.phase === 'playing' &&
sample.segmentSpeedMps > 0;
const moving = playing(entry) && playbackMoving(entry);
if (moving) {
state._moving.add(entry);
return;
}
state._moving.delete(entry);
if (playing(entry) && Number.isFinite(sample?.nextWakeMonoMs)) {
if (!playing(entry)) return;
// A train a host-supplied placement holds still is asked again every
// PLACED_WAKE_MS: it moves on once the placement does.
const monoNow = performance.now();
const placedWake = entry.placed === true;
const boundary = sample?.nextWakeMonoMs;
const wakeMonoMs = placedWake
? Math.min(
Number.isFinite(boundary) ? boundary : Infinity,
monoNow + PLACED_WAKE_MS,
)
: boundary;
if (Number.isFinite(wakeMonoMs)) {
const atBoundary = !placedWake || boundary <= wakeMonoMs;
entry.wakeTimer = setTimeout(
() => {
entry.wakeTimer = null;
@@ -813,9 +831,10 @@ export function createRendering({ state, services, parts }) {
updatePlayback(entry, Date.now(), performance.now());
schedulePlayback(entry);
syncRenderHold();
governorRequestRender('rail-motion-boundary');
if (atBoundary || state._moving.has(entry))
governorRequestRender('rail-motion-boundary');
},
Math.max(1, sample.nextWakeMonoMs - performance.now()),
Math.max(1, wakeMonoMs - monoNow),
);
}
}
@@ -1021,7 +1040,8 @@ export function createRendering({ state, services, parts }) {
place(entry);
if (
entry.sample.phase !== 'playing' ||
entry.sample.segmentSpeedMps === 0
entry.sample.segmentSpeedMps === 0 ||
(entry.placed === true && entry.placedMoving !== true)
)
schedulePlayback(entry);
}
+15 -1
View File
@@ -16,6 +16,7 @@ import {
import {
transitModeFor,
transitModeResolved,
transitModelRouteType,
} from '../../data/transitFeeds.js';
import {
attachFloorToPlace,
@@ -85,6 +86,7 @@ export function createIngestion({ state, services, parts, source }) {
state._heightDirty.delete(entry);
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
entry.placement?.forget(key);
state._vehicles.delete(key);
state._detectRevision += 1;
}
@@ -222,12 +224,19 @@ export function createIngestion({ state, services, parts, source }) {
for (const record of records) {
if (isStaleVehicleFix(record, now, fetchedAt)) continue;
const key = transitVehicleKey(feed.id, record.id);
const mode = transitModeFor(feed, record.routeId, record.id);
const mode = transitModeFor(
feed,
record.routeId,
record.id,
record.routeType,
);
const modeInferred = !transitModeResolved(
feed,
record.routeId,
record.id,
record.routeType,
);
const routeType = transitModelRouteType(mode, record.routeType);
// A stamp ahead of the fetch is a clock fault; the fetch time bounds it.
const stamped = vehicleReportTimeMs(record, fetchedAt);
const reportAt =
@@ -267,6 +276,7 @@ export function createIngestion({ state, services, parts, source }) {
continue;
}
if (entry.mode !== mode) parts.rendering.paintMode(entry, mode);
entry.routeType = routeType;
entry.modeInferred = modeInferred;
updatePlayback(entry, now, monoNow);
parts.rendering.schedulePlayback(entry);
@@ -318,8 +328,12 @@ export function createIngestion({ state, services, parts, source }) {
entry = {
key,
feedId: feed.id,
// A host-supplied placement, if any, draws it while live.
placement: services.placement ?? null,
marker: null,
mode,
// The GTFS route type its model is chosen by, when it has one.
routeType,
modeInferred,
heightM: prior === null ? 0 : prior,
heightCell: height.cell,
+2
View File
@@ -98,6 +98,7 @@ export function createLifecycle({ state, services, parts }) {
entry.detectContact = null;
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
entry.placement?.forget(entry.key);
}
state._vehicles.clear();
parts.height.clear();
@@ -179,6 +180,7 @@ export function createLifecycle({ state, services, parts }) {
entry.detectContact = null;
parts.rendering.cancelWake(entry);
destroyTrack(entry.track);
entry.placement?.forget(entry.key);
}
state._vehicles.clear();
parts.rendering.stopModels();
+109
View File
@@ -13,6 +13,8 @@ import {
} from './policy.js';
import { FLOOR_WARM_PER_POLL } from './policy.js';
import { fleetModelFakes } from '../../testSupport/fleetModelFakes.mjs';
import { layerPlacement } from '../../data/placementProvider.js';
import { PLACED_WAKE_MS } from './movement.js';
import {
FUTURE_STAMP_TOLERANCE_MS,
ORDER_REJECTS_BEFORE_RESET,
@@ -229,6 +231,8 @@ function harness(
// Fleet-model services (testSupport/fleetModelFakes.mjs), with a camera
// looking straight down for them; without them vehicles stay icons.
fleet = null,
// A host-supplied placement (../../data/placementProvider.js), or none.
placement = null,
} = {},
) {
const viewRect = { ...view };
@@ -346,6 +350,7 @@ function harness(
source,
services: {
...(fleet ? { fleet } : {}),
...(placement ? { placement: layerPlacement(placement, 'transit') } : {}),
ground,
mesh: {
sampleMeshFloorCells(scene, points, options) {
@@ -1329,6 +1334,110 @@ test('a parked fleet that keeps reporting the same position stops asking for fra
'only the vehicle that actually moved is animating',
);
});
test('a vehicle a placement holds still stops asking for frames, and moves on when the placement does', async (t) => {
// The placement parks bus-1 at a terminal until `spot` moves.
let spot = { lat: 42.3605, lon: -71.0605 };
let asked = 0;
const app = harness(t, {
placement: {
layer: () => ({
place: () => {
asked += 1;
return { ...spot, courseDeg: 0, speedMps: 0 };
},
}),
},
});
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, reported())],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const entry = app.vehicles()[0];
assert.equal(entry.placed, true);
for (let i = 0; i < 3; i += 1) {
app.advance(16);
app.frame();
}
assert.equal(app.state()._moving.has(entry), false, 'parked: not animating');
assert.equal(app.holds().includes('transit'), false, 'and the loop idles');
assert.notEqual(entry.wakeTimer, null, 'a wake asks the placement again');
assert.ok(Math.abs(lat(entry) - 42.3605) < 1e-6, 'drawn where placed');
// Asked again while it stays put: still idle, the wake re-armed.
const before = asked;
app.advance(PLACED_WAKE_MS);
assert.ok(asked > before, 'the wake asked the placement');
assert.equal(app.state()._moving.has(entry), false);
assert.equal(app.holds().includes('transit'), false);
// The placement moves it: the next wake picks that up and the loop runs.
spot = { lat: 42.361, lon: -71.0605 };
app.advance(PLACED_WAKE_MS);
assert.equal(app.state()._moving.has(entry), true, 'moving again');
assert.ok(app.holds().includes('transit'), 'and holds the loop');
assert.ok(Math.abs(lat(entry) - 42.361) < 1e-6);
for (let i = 0; i < 3; i += 1) {
spot = { lat: spot.lat + 1e-5, lon: spot.lon };
app.advance(16);
app.frame();
assert.equal(app.state()._moving.has(entry), true, 'while it moves');
}
// It stops again: the next frame that sees it unchanged lets go.
app.advance(16);
app.frame();
assert.equal(app.state()._moving.has(entry), false, 'stopped again');
assert.equal(app.holds().includes('transit'), false);
});
test('a vehicle a placement draws is shown from a high camera, as one it does not', async (t) => {
// Far above the ground no floor is asked for, so the fixes carry no height
// and the vehicle stands on the ellipsoid, placed or not.
const app = harness(t, {
at: { lat: 52.09, lon: 5.12 },
altitude: 1_500_000,
view: { west: -78.084, south: 20, east: 88.084, north: 84 },
placement: {
layer: () => ({
place: (id) =>
id.endsWith('nl-1')
? { lat: 52.091, lon: 5.12, courseDeg: 0, speedMps: 0 }
: null,
}),
},
});
const now = Date.now();
app.serve('ovapi-nl', () => ({
status: 200,
body: snapshot(
'ovapi-nl',
'OVapi',
[
vehicle('nl-1', 52.09, 5.12, now / 1000),
vehicle('nl-2', 51.92, 4.48, now / 1000),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.advance(250);
app.frame();
const placed = app.vehicles().find((entry) => entry.placed === true);
assert.ok(placed, 'one vehicle is placed');
const shown = app.vehicles().filter((entry) => entry.marker?.show !== false);
assert.equal(shown.length, 2, 'both vehicles are drawn');
assert.ok(Math.abs(lat(placed) - 52.091) < 1e-6, 'where placed');
});
test('the last vehicle leaving mid-segment takes the render hold with it', async (t) => {
const app = harness(t);
const fetchedAt = Date.now();
+59
View File
@@ -11,9 +11,14 @@ import {
} from '../../data/contactPlayback.js';
const MODE_MAX_SPEED_MPS = Object.freeze({
bus: 36, // ~130 km/h — a coach on a motorway
trolleybus: 28, // ~100 km/h — wired to the street
tram: 28, // ~100 km/h — interurban light rail
cable_tram: 12, // ~43 km/h — the cable runs at a walking-pace multiple
subway: 42, // ~150 km/h
monorail: 42, // ~150 km/h
rail: 111, // ~400 km/h — high-speed services exist on some feeds
funicular: 16, // ~58 km/h — the fastest lines
aerial_lift: 15, // ~54 km/h — the fastest gondolas and trams
ferry: 25, // ~90 km/h — fast catamarans
unknown: 56, // ~200 km/h
});
@@ -181,13 +186,57 @@ export function recordFix(entry, fix, observation = {}) {
);
entry.currentEpoch = latest.epoch;
if (context) entry.track.epochs.set(latest.epoch, context);
entry.placement?.observe(entry.key, {
timeMs: fix.t,
lat: fix.lat,
lon: fix.lon,
altitudeM: NaN,
speedMps: NaN,
courseDeg: Number.isFinite(fix.bearingDeg) ? fix.bearingDeg : NaN,
headingDeg: NaN,
feedId: entry.feedId,
});
}
return result;
}
/**
* How often a vehicle a host-supplied placement holds still is asked again
* whether it moves, so it resumes without the frame loop running for it.
*/
export const PLACED_WAKE_MS = 1000;
/**
* Advance a vehicle's playback to now. With a host-supplied placement
* (`entry.placement`, ../../data/placementProvider.js) that places it, it is
* drawn there, its course and speed the placement's (`entry.placed`); the
* playback's own phase, motion and segment stand. `entry.placedMoving` says
* whether the placed position changed since the placement was last asked at
* an earlier time (true for its first answer, so one more frame can tell).
*/
export function updatePlayback(entry, wallNowMs, monoNowMs) {
entry.clocks.wallNowMs = wallNowMs;
entry.clocks.monoNowMs = monoNowMs;
advance(entry.track, entry.clocks, entry.sample);
const placed = entry.placement?.place(entry.key, wallNowMs) ?? null;
const wasPlaced = entry.placed === true;
entry.placed = placed !== null;
if (!placed) entry.placedMoving = false;
else if (!wasPlaced) entry.placedMoving = true;
else if (wallNowMs !== entry.placedAtWallMs)
entry.placedMoving =
placed.lat !== entry.placedLat || placed.lon !== entry.placedLon;
if (placed) {
entry.placedLat = placed.lat;
entry.placedLon = placed.lon;
entry.placedAtWallMs = wallNowMs;
const sample = entry.sample;
sample.lat = placed.lat;
sample.lon = placed.lon;
if (Number.isFinite(placed.courseDeg))
sample.segmentCourseDeg = placed.courseDeg;
if (Number.isFinite(placed.speedMps))
sample.segmentSpeedMps = placed.speedMps;
}
entry.resets = entry.track.resets;
const segment = entry.segment;
readFix(
@@ -212,6 +261,16 @@ export function syncPlayback(entry, wallNowMs, monoNowMs = performance.now()) {
}
updatePlayback(entry, wallNowMs, monoNowMs);
}
/**
* Whether a vehicle's drawn position changes on its own: a vehicle a
* host-supplied placement draws moves while that placement's position
* changes; any other while its playback glides along a segment.
*/
export function playbackMoving(entry) {
if (entry.placed === true) return entry.placedMoving === true;
const sample = entry.sample;
return sample?.phase === 'playing' && sample.segmentSpeedMps > 0;
}
export function playbackPosition(entry) {
if (!entry?.track) return null;
return {
+99
View File
@@ -10,6 +10,7 @@ import {
} from './movement.js';
import { buildTransitSelectionCopy } from './policy.js';
import { sampleAt } from '../../data/contactPlayback.js';
import { layerPlacement } from '../../data/placementProvider.js';
const entry = () => {
const e = { mode: 'bus', modeInferred: false, courseDeg: null };
initializePlayback(e);
@@ -163,3 +164,101 @@ test('course fallback prefers held course, then finite reported bearing, then un
assert.equal(e.courseDeg, expected);
}
});
const placedEntry = (placement) => {
const e = {
key: 'feed:7',
feedId: 'feed',
mode: 'bus',
modeInferred: false,
courseDeg: null,
placement,
};
initializePlayback(e);
return e;
};
const drive = (e) => {
recordFix(e, { ...fix(0), bearingDeg: 10 });
recordFix(e, { ...fix(15000, 42.001), bearingDeg: 20 });
recordFix(e, fix(30000, 42.002));
const samples = [];
for (let wall = 0; wall <= 120000; wall += 2500) {
updatePlayback(e, wall, wall);
samples.push({ ...e.sample });
}
return samples;
};
test('without a placement, or one that places nothing, playback is the layer own', () => {
const own = drive(placedEntry(null));
const declined = [];
const placement = layerPlacement(
{
layer: () => ({
observe: (id, f) => declined.push([id, f.timeMs]),
place: () => null,
}),
},
'transit',
);
const e = placedEntry(placement);
assert.deepEqual(drive(e), own);
assert.equal(e.placed, false);
assert.deepEqual(declined, [
['feed:7', 0],
['feed:7', 15000],
['feed:7', 30000],
]);
});
test('a placement draws the vehicle where it places it, keeping the playback state', () => {
const own = drive(placedEntry(null));
const e = placedEntry(
layerPlacement(
{
layer: () => ({
place: (id, wallMs) =>
wallMs >= 60000
? { lat: 1, lon: 2, courseDeg: 45, speedMps: 7 }
: { lat: 3, lon: 4 },
}),
},
'transit',
),
);
const placed = drive(e);
assert.equal(e.placed, true);
for (let i = 0; i < own.length; i++) {
const late = i * 2500 >= 60000;
assert.equal(placed[i].lat, late ? 1 : 3);
assert.equal(placed[i].lon, late ? 2 : 4);
assert.equal(placed[i].phase, own[i].phase);
assert.equal(placed[i].motion, own[i].motion);
if (late) {
assert.equal(placed[i].segmentCourseDeg, 45);
assert.equal(placed[i].segmentSpeedMps, 7);
} else {
// No course or speed placed: the playback's own stand.
assert.deepEqual(
[placed[i].segmentCourseDeg, placed[i].segmentSpeedMps],
[own[i].segmentCourseDeg, own[i].segmentSpeedMps],
);
}
}
});
test('a refused fix is never told to the placement', () => {
const told = [];
const e = placedEntry(
layerPlacement(
{
layer: () => ({
observe: (id, f) => told.push(f.lat),
place: () => null,
}),
},
'transit',
),
);
recordFix(e, fix(0));
recordFix(e, fix(15000, 42.001));
assert.equal(recordFix(e, fix(30000, 43)).accepted, false);
assert.deepEqual(told, [42, 42.001]);
});
+15
View File
@@ -188,9 +188,14 @@ export const SELECTED_CARD_REFRESH_MS = 250;
/** Mode palette: distinct at a glance, none reused by flights (white/cyan), military (amber), or vessels. */
export const TRANSIT_MODE_COLORS = Object.freeze({
bus: '#5EF08A',
trolleybus: '#B6F04A',
tram: '#FFC24A',
cable_tram: '#FF8F4A',
subway: '#FF4538',
monorail: '#FF6FB8',
rail: '#D9A6FF',
funicular: '#E8C98A',
aerial_lift: '#7FA8FF',
ferry: '#5FD6FF',
unknown: '#D8DDE5',
});
@@ -525,9 +530,14 @@ const UNDERGROUND_MODES = new Set(['subway']);
/** The mode in plain words, for a card a person reads rather than scans. */
const TRANSIT_MODE_WORD = Object.freeze({
bus: msg('Bus'),
trolleybus: msg('Trolleybus'),
tram: msg('Tram'),
cable_tram: msg('Cable car'),
subway: msg('Subway'),
monorail: msg('Monorail'),
rail: msg('Train'),
funicular: msg('Funicular'),
aerial_lift: msg('Gondola'),
ferry: msg('Ferry'),
unknown: msg('Transit vehicle'),
});
@@ -535,9 +545,14 @@ const TRANSIT_MODE_WORD = Object.freeze({
/** Short, fixed-width mode word for the detection card's class field. */
const TRANSIT_MODE_ABBR = Object.freeze({
bus: 'BUS',
trolleybus: 'TROLLEY',
tram: 'TRAM',
cable_tram: 'CABLE',
subway: 'METRO',
monorail: 'MONO',
rail: 'RAIL',
funicular: 'FUNI',
aerial_lift: 'GONDOLA',
ferry: 'FERRY',
unknown: 'TRANSIT',
});
+29 -7
View File
@@ -12,8 +12,10 @@ import { fromDegreesInto } from '../../geo/ellipsoid.js';
import { frustumPlanes } from '../../geo/frustum.js';
import { perspectiveCourseRotation } from '../../data/screenRotation.js';
import {
PLACED_WAKE_MS,
updatePlayback,
applyDisplayCourse,
playbackMoving,
syncPlayback,
} from './movement.js';
import {
@@ -535,7 +537,7 @@ export function createRendering({ state, services, parts }) {
migrateMarker(entry, false);
return;
}
const positional = sample.phase === 'playing' && sample.segmentSpeedMps > 0;
const positional = playbackMoving(entry);
const turning =
Number.isFinite(sample.segmentCourseDeg) &&
Number.isFinite(entry.courseDeg) &&
@@ -548,7 +550,19 @@ export function createRendering({ state, services, parts }) {
} else {
state._moving.delete(entry);
migrateMarker(entry, false);
if (Number.isFinite(sample.nextWakeMonoMs)) {
// A vehicle a host-supplied placement holds still is asked again every
// PLACED_WAKE_MS: it moves on once the placement does.
const monoNow = performance.now();
const placedWake = entry.placed === true;
const boundary = sample.nextWakeMonoMs;
const wakeMonoMs = placedWake
? Math.min(
Number.isFinite(boundary) ? boundary : Infinity,
monoNow + PLACED_WAKE_MS,
)
: boundary;
if (Number.isFinite(wakeMonoMs)) {
const atBoundary = !placedWake || boundary <= wakeMonoMs;
entry.wakeTimer = setTimeout(
() => {
entry.wakeTimer = null;
@@ -558,9 +572,10 @@ export function createRendering({ state, services, parts }) {
schedulePlayback(entry);
flushMarkers();
syncRenderHold();
governorRequestRender('transit-motion-boundary');
if (atBoundary || state._moving.has(entry))
governorRequestRender('transit-motion-boundary');
},
Math.max(1, sample.nextWakeMonoMs - performance.now()),
Math.max(1, wakeMonoMs - monoNow),
);
}
}
@@ -836,7 +851,8 @@ export function createRendering({ state, services, parts }) {
if (
!entry.surfaceReady ||
entry.sample.phase !== 'playing' ||
entry.sample.segmentSpeedMps === 0
entry.sample.segmentSpeedMps === 0 ||
(entry.placed === true && entry.placedMoving !== true)
)
schedulePlayback(entry);
if (!state._moving.has(entry)) settleSelectedCard(entry);
@@ -939,9 +955,15 @@ export function createRendering({ state, services, parts }) {
groundLiftM,
};
}
if (item.mode !== entry.mode) {
if (item.mode !== entry.mode || item.routeType !== entry.routeType) {
item.mode = entry.mode;
item.spec = transitModelSpec(set, { mode: entry.mode });
item.routeType = entry.routeType;
// The route type picks the finer model (a coach, a high-speed set);
// the mode is the fallback for a type the model table lacks.
item.spec = transitModelSpec(set, {
routeType: entry.routeType,
mode: entry.mode,
});
item.tint =
TRANSIT_MODE_COLORS[entry.mode] || TRANSIT_MODE_COLORS.unknown;
}
+15 -10
View File
@@ -1,5 +1,5 @@
import { getRegisteredTransitFeed } from '../../data/transitFeeds.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import {
readFix,
correctHeight,
@@ -8,16 +8,9 @@ import {
} from '../../data/contactPlayback.js';
import { createContactTrailRenderer } from '../../data/contactTrailRenderer.js';
import { fixDistanceM } from './movement.js';
import { TRANSIT_MODE_COLORS } from './policy.js';
import { transitStyleProfile } from '../../data/transitPresetStyle.js';
const MODE_COLOR = {
bus: '#5EF08A',
tram: '#FFC24A',
subway: '#FF4538',
rail: '#D9A6FF',
ferry: '#5FD6FF',
unknown: '#D8DDE5',
};
// Final Cesium batching uses 3,152 bytes per two-lane edge.
// The 1,278-instance body plus 64 bytes/instance reserve stays below 2 MiB.
export const TRAIL_VERTEX_LIMIT = 640;
@@ -41,7 +34,7 @@ export function createTrails({ state, services, parts, source }) {
renderer?.setStyle(
transitStyleProfile(state._stylePreset) === 'mono'
? '#FFFFFF'
: MODE_COLOR[selected?.mode] || MODE_COLOR.unknown,
: TRANSIT_MODE_COLORS[selected?.mode] || TRANSIT_MODE_COLORS.unknown,
);
}
function releaseSelectionGeometry(entry) {
@@ -200,6 +193,18 @@ export function createTrails({ state, services, parts, source }) {
nearGround = parts.height.nearGround(),
) {
pruneMarkerPaths(entry, sample);
// Placed by a host-supplied placement, it is drawn at the placed point,
// at the height its own playback has reached; far above the ground, where
// no floor is asked for, on the ellipsoid as an unplaced vehicle is.
if (entry.placed === true) {
const heightM = Number.isFinite(sample.heightM)
? sample.heightM
: nearGround
? NaN
: 0;
if (!Number.isFinite(heightM)) return null;
return fromDegreesInto(sample.lon, sample.lat, heightM, out);
}
if (!nearGround) {
const a = entry.fromCart,
b = entry.toCart,
+55 -20
View File
@@ -1,8 +1,10 @@
import {
AID_TO_NAVIGATION_STYLE,
accentForVesselType,
displayVesselType,
normalizeVesselType,
} from '../../data/vesselLabels.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
import { formatNumber, t } from '../../i18n/index.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
@@ -16,14 +18,21 @@ export function createCards({
function updateSelectedVesselHud(record) {
// Pinned vessels missing from recent refreshes get a stale marker
const stale = (record.missedRefreshes || 0) > 0;
// An aid to navigation is a fixed mark: it has no speed or heading to show.
const aid = isAidToNavigation(record);
services.readouts?.presentSelectedVessel({
text: [
t('AIS: {name}', { name: trimHudValue(record.name, 32) }),
t('{type} SPD: {speed} HDG: {heading}', {
type: trimHudValue(record.type || t('VESSEL'), 24),
speed: formatSpeed(record.speed),
heading: formatHeading(record.heading ?? record.course),
}),
aid
? aidKind(
trimHudValue(record.type || t('AID TO NAVIGATION'), 24),
record,
)
: t('{type} SPD: {speed} HDG: {heading}', {
type: trimHudValue(record.type || t('VESSEL'), 24),
speed: formatSpeed(record.speed),
heading: formatHeading(record.heading ?? record.course),
}),
`MMSI: ${record.mmsi || '--'} ${formatPositionTime(record)}${stale ? ` · ${t('STALE')}` : ''}`,
].join('\n'),
});
@@ -43,27 +52,29 @@ export function createCards({
/**
* Card model for an ambient (decluttered-in) vessel — name title plus one
* compact type/speed/heading detail line, anchored at the record's current
* rendered position (height-datum caveat: no datum work here). Pure —
* exported for unit tests.
* rendered position (height-datum caveat: no datum work here). An aid to
* navigation's line is its kind alone. Pure — exported for unit tests.
* @param {Object} record - Vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildVesselCard(record) {
const parts = [];
const aid = isAidToNavigation(record);
const type = vesselTypeShort(record);
if (type) parts.push(type);
if (record.speed !== null && record.speed !== undefined)
if (record.virtual === true) parts.push(t('VIRTUAL'));
if (!aid && record.speed !== null && record.speed !== undefined)
parts.push(formatSpeed(record.speed));
const direction = record.heading ?? record.course;
if (Number.isFinite(direction))
if (!aid && Number.isFinite(direction))
parts.push(`${roundHeadingDegrees(direction)}°`);
return {
id: vesselOverlayEntryId(record),
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 10,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 26),
details: parts.length ? [parts.join(' · ')] : [],
selected: false,
@@ -74,22 +85,26 @@ export function createCards({
/**
* Card model for the click-selected vessel — the full-detail card, drawn last
* (on top) and never distance-faded by the overlay. Pinned-but-vanished
* vessels carry a STALE marker (mirrors the HUD readout). Pure — exported
* for unit tests.
* vessels carry a STALE marker (mirrors the HUD readout). An aid to
* navigation shows its kind with no speed or heading. Pure — exported for
* unit tests.
* @param {Object} record - Selected vessel record.
* @returns {Object} vesselLabels entry.
*/
function buildSelectedVesselCard(record) {
const aid = isAidToNavigation(record);
const direction = record.heading ?? record.course;
const details = [
[
vesselTypeShort(record) || t('VESSEL'),
formatSpeed(record.speed),
Number.isFinite(direction)
? `${roundHeadingDegrees(direction)}°`
: '--°',
].join(' · '),
aid
? aidKind(vesselTypeShort(record) || t('AID TO NAVIGATION'), record)
: [
vesselTypeShort(record) || t('VESSEL'),
formatSpeed(record.speed),
Number.isFinite(direction)
? `${roundHeadingDegrees(direction)}°`
: '--°',
].join(' · '),
];
const destination = String(record.destination || '').trim();
if (destination) details.push(`→ ${trimHudValue(destination, 24)}`);
@@ -102,7 +117,7 @@ export function createCards({
actionable: Boolean(record?.id),
position: components.rendering.iconPosition(record),
gapPx: 12,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 32),
details,
selected: true,
@@ -110,6 +125,20 @@ export function createCards({
};
}
/** An aid's kind, marked virtual when nothing physical stands there. */
function aidKind(kind, record) {
return record.virtual === true ? `${kind} · ${t('VIRTUAL')}` : kind;
}
/** A card's accent: an aid's disc colour, else its ship type's. */
function vesselAccent(record, aid) {
return aid
? AID_TO_NAVIGATION_STYLE.accent
: accentForVesselType(record.type);
}
/** Stable overlay identity for keyed and source-retained unkeyed rows. */
function vesselOverlayEntryId(record) {
@@ -125,9 +154,15 @@ export function createCards({
* Uppercased AIS type for the card (empty string when unknown). Free feed
* text is bounded to the card width; a translated type token is a short
* catalog word and shows whole, never cut mid-word ("AUXILIAR DE PUERTO").
* An aid's kind is the whole line, so it keeps the room speed and heading
* would take ("CARDINAL MARK N", not "CARDINAL MARK ").
*/
function vesselTypeShort(record) {
if (isAidToNavigation(record)) {
const kind = String(record.type || '').trim();
return kind ? trimHudValue(kind.toUpperCase(), 26) : '';
}
const feedType = normalizeVesselType(record.type);
const shown = displayVesselType(record.type);
return shown === feedType
+1
View File
@@ -31,6 +31,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
parts.queries = createQueries(context);
parts.snapshots = createVesselSnapshotRenderer({
state: vesselState.state,
placement: services?.placement ?? null,
records: vesselState.state.records,
rendering: parts.rendering,
tracking: parts.tracking,
+1
View File
@@ -218,6 +218,7 @@ export function createIngestion({
speed: record.speedMps == null ? null : record.speedMps / 0.514444,
course: record.courseDeg,
heading: record.headingDeg,
virtual: record.virtual === true,
last_position_epoch:
record.observedAtMs == null ? null : record.observedAtMs / 1000,
last_position_UTC:
+4
View File
@@ -115,6 +115,8 @@ export function createLifecycle({
state.feed.firstConnectTimer = null;
state.feed.abort = null;
state.icons = null;
if (services.placement)
for (const id of state.records.byId.keys()) services.placement.forget(id);
state.records.all = [];
state.records.byId = new Map();
state.records.unkeyed = [];
@@ -207,6 +209,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels');
components.rendering.cancelTrailingVisibilityPass();
components.rendering.cancelPlacementFrame();
unregisterPickOwner('ais-live-vessels');
components.rendering.setVisible(false);
vesselState._vesselOverlayHost.clearSource(VESSEL_OVERLAY_SOURCE_ID);
@@ -228,6 +231,7 @@ export function createLifecycle({
invalidateAisSession();
releaseContinuousRender('ais-vessels'); // direct-destroy path (perf wave 2 fix)
components.rendering.cancelTrailingVisibilityPass();
components.rendering.cancelPlacementFrame();
if (state.feed.abort) state.feed.abort.abort();
unregisterPickOwner('ais-live-vessels');
components.selection.clearVesselInspection();
+45
View File
@@ -556,3 +556,48 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
['235000001', '235000001'],
);
});
test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
const aid = {
...observation('993672001'),
mmsi: '993672001',
type: 'Port Hand Mark',
speedMps: 0,
};
const ship = { ...observation('366999002'), type: 'Cargo' };
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid, ship]);
},
});
await layer.update();
const svgOf = (id) => {
assert.ok(icons.has(id), id);
return atob(icons.item(id).image.split(',')[1]);
};
assert.match(svgOf('993672001'), /<circle/);
// The source's virtual flag reaches the layer's record.
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
assert.equal(recordOf('993672001').virtual, false);
assert.equal(recordOf('366999002').virtual, false);
assert.doesNotMatch(svgOf('993672001'), /<path/);
assert.match(svgOf('366999002'), /<path/);
});
test('a virtual aid to navigation keeps its disc and its virtual flag', async () => {
const aid = {
...observation('993672009'),
mmsi: '993672009',
type: 'Isolated danger',
virtual: true,
};
const { layer, icons } = setup({
async getSnapshot() {
return snapshot([aid]);
},
});
await layer.update();
assert.ok(icons.has('993672009'));
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
});
+107
View File
@@ -0,0 +1,107 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { VesselRecords } from './records.js';
import { createVesselSnapshotRenderer } from './snapshotRenderer.js';
import { layerPlacement } from '../../data/placementProvider.js';
const row = (id, fields = {}) => ({
id,
mmsi: id,
lat: 51.93,
lon: 4.05,
speed: 10,
course: 90,
heading: 92,
last_position_epoch: 1_000,
...fields,
});
function harness({ placement = null, following = false } = {}) {
const visuals = [];
const state = { selectedRecord: null, trailId: null };
const records = new VesselRecords({ now: () => 5_000_000 });
const rendering = {
ensureCollections() {},
makeOccluder: () => null,
renderRowLimit: () => Infinity,
prepareRecordVisual(record) {
visuals.push(record.id);
return { billboard: null };
},
addRecordPrimitives() {},
removeRecordPrimitives() {},
shipIcon: () => 'icon',
shipScale: () => 1,
syncRecordIcon() {},
updateVisibility() {},
};
const renderer = createVesselSnapshotRenderer({
state,
placement,
records,
rendering,
tracking: {},
selection: {},
cards: {},
followsClock: () => following,
});
return {
visuals,
reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
};
}
function recording() {
const told = [];
const forgotten = [];
const placement = layerPlacement(
{
layer: () => ({
observe: (id, fix) => told.push([id, fix]),
place: () => null,
forget: (id) => forgotten.push(id),
}),
},
'vessels',
);
return { told, forgotten, placement };
}
test('vessels reconcile as before with no placement', () => {
const own = harness();
own.reconcile([row('a'), row('b')]);
own.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
const { placement } = recording();
const placed = harness({ placement });
placed.reconcile([row('a'), row('b')]);
placed.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
assert.deepEqual(placed.visuals, own.visuals);
});
test('each live vessel fix is told to the placement, in m/s, and a vessel that leaves is forgotten', () => {
const { told, forgotten, placement } = recording();
const probe = harness({ placement });
probe.reconcile([row('a'), row('b', { speed: null, course: null })]);
probe.reconcile([row('a', { lat: 52, last_position_epoch: 1_060 })]);
assert.deepEqual(
told.map(([id, fix]) => [id, fix.timeMs, fix.lat]),
[
['a', 1_000_000, 51.93],
['b', 1_000_000, 51.93],
['a', 1_060_000, 52],
],
);
assert.ok(Math.abs(told[0][1].speedMps - 10 * (1852 / 3600)) < 1e-12);
assert.equal(told[0][1].courseDeg, 90);
assert.equal(told[0][1].headingDeg, 92);
assert.ok(Number.isNaN(told[1][1].speedMps));
assert.ok(Number.isNaN(told[1][1].courseDeg));
assert.deepEqual(forgotten, ['b']);
});
test('following the world clock, or rows at another time, tell the placement nothing', () => {
const { told, placement } = recording();
harness({ placement, following: true }).reconcile([row('a')]);
harness({ placement }).reconcile([row('a')], { replace: true });
assert.deepEqual(told, []);
});
+3
View File
@@ -31,6 +31,8 @@ export function normalizeVessel(row) {
speed: finiteNumber(row.speed),
course: finiteNumber(row.course),
heading: finiteNumber(row.heading),
// A virtual aid to navigation: a mark with nothing physical there.
virtual: row.virtual === true,
lastPositionUtc: String(row.last_position_UTC || ''),
lastPositionEpoch: finiteNumber(row.last_position_epoch),
missedRefreshes: 0,
@@ -159,6 +161,7 @@ export class VesselRecords {
record.speed = next.speed;
record.course = next.course;
record.heading = next.heading;
record.virtual = next.virtual;
record.lastPositionUtc = next.lastPositionUtc;
record.lastPositionEpoch = next.lastPositionEpoch;
record.missedRefreshes = 0;
+56 -1
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { VISIBILITY_UPDATE_MS } from './policy.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { layerPlacement } from '../../data/placementProvider.js';
// Vessels move only when a poll lands, so the layer must let the scene idle:
// it asks for frames for forced passes and one trailing frame after the camera
@@ -10,7 +11,7 @@ import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const noop = () => {};
function setup({ focusPassIsNeeded = () => false } = {}) {
function setup({ focusPassIsNeeded = () => false, placement = null } = {}) {
let clock = 10_000;
const requests = [];
const holds = new Set();
@@ -47,6 +48,7 @@ function setup({ focusPassIsNeeded = () => false } = {}) {
releaseContinuousRender: (id) => holds.delete(id),
governorRequestRender: (reason) => requests.push(reason),
},
...(placement ? { placement: layerPlacement(placement, 'vessels') } : {}),
},
});
const camera = {
@@ -184,3 +186,56 @@ test('a focus pass reads the camera pose even with a trailing frame waiting', ()
frame();
assert.ok(reads > 0, 'the focus pass needs the eye');
});
test('a placement that places nothing asks for no frames; one that places a drawn vessel moves it in place', (t) => {
let mono = 0;
t.mock.method(performance, 'now', () => mono);
const originalDocument = globalThis.document;
globalThis.document = { getElementById: () => null };
t.after(() => {
if (originalDocument === undefined) delete globalThis.document;
else globalThis.document = originalDocument;
});
let spot = null;
const { layer, camera, requests, timers, advance } = setup({
placement: { layer: () => ({ place: () => spot }) },
});
const record = { mmsi: '111', lat: 51.93, lon: 4.05 };
const viewer = { camera, scene: {} };
bindFakeCesiumScene(viewer);
layer.testing._setVesselStateForTest({ viewer, records: [record] });
const visual = layer.testing._prepareVesselVisualForTest(record);
// Drawn: on the camera's side of the horizon.
visual.visible = true;
const position = visual.position;
const before = { ...position };
// Nothing placed: no frame is asked for, and the vessel stays put.
for (let i = 0; i < 8; i += 1) {
mono += 250;
layer.testing._runPlacementPassForTest();
advance(250);
}
assert.equal(timers.size, 0);
assert.deepEqual(requests, []);
assert.deepEqual({ ...visual.position }, before);
// Placed: moved in place, no new positions, and a frame asked for.
spot = { lat: 51.94, lon: 4.05 };
mono += 250;
layer.testing._runPlacementPassForTest();
assert.equal(visual.position, position, 'written in place');
assert.notDeepEqual({ ...visual.position }, before);
assert.equal(timers.size, 1);
advance(1_000);
assert.deepEqual(requests, ['ais-vessels-placement']);
// Turning the layer off drops the pending frame.
mono += 250;
layer.testing._runPlacementPassForTest();
assert.equal(timers.size, 1);
layer.destroy();
assert.equal(timers.size, 0);
advance(1_000);
assert.deepEqual(requests, ['ais-vessels-placement']);
});
+140 -20
View File
@@ -1,12 +1,13 @@
import { t } from '../../i18n/index.js';
import {
AID_TO_NAVIGATION_STYLE,
vesselTypeCss,
vesselOverlayCohortLimit,
VESSEL_OVERLAY_SOURCE_ID,
applyVesselOverlayPolicy,
VESSEL_CARD_FADE_DISTANCE_M,
} from '../../data/vesselLabels.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { fromDegrees, fromDegreesInto } from '../../geo/ellipsoid.js';
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
import { distance, distanceSquared } from '../../geo/vector.js';
import {
@@ -35,9 +36,12 @@ import {
vesselModelSpec,
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
/** A frame is asked for this often while a placement moves live vessels. */
const PLACEMENT_FRAME_MS = 1000;
/** The ship artwork's own raster size (px). */
const SHIP_ICON_PX = 32;
@@ -79,26 +83,43 @@ export function createRendering({
};
visualRecords.set(record, visual);
}
visual.position = anchorPosition(record);
const { lat, lon } = drawnAt(record);
visual.position = anchorAt(lat, lon);
// A ship model's origin is its waterline: the sea surface, unlifted.
visual.waterline = anchorPosition(record, 0);
visual.waterline = anchorAt(lat, lon, 0);
if (services.placement) {
visual.drawnLat = lat;
visual.drawnLon = lon;
}
return visual;
}
/**
* Where a record's icon is anchored: VESSEL_LIFT_M above the sea surface
* (the geoid, once its grid has loaded). Following the world clock, a
* vessel is drawn where it was at the time.
* Where a record is drawn now: following the world clock, where it was at
* the time; live, where a host-supplied placement draws it, if one does.
* @param {Object} record - Vessel record with a finite lat/lon.
* @returns {{lat: number, lon: number}} A fresh pair (the placement's
* answer is reused by its next call).
*/
function drawnAt(record) {
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: (services.placement?.place(record.id, vesselState._aisRuntime.now()) ??
record);
return { lat, lon };
}
/**
* Where an icon at `lat`/`lon` is anchored: VESSEL_LIFT_M above the sea
* surface (the geoid, once its grid has loaded).
* @param {number} lat
* @param {number} lon
* @param {number} [liftM] Height above the sea surface (the icon's lift by
* default; 0 for a ship model's waterline).
* @returns {{x: number, y: number, z: number}} ECEF metres: icon items,
* focus and the layer's queries take it as it is.
*/
function anchorPosition(record, liftM = VESSEL_LIFT_M) {
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: record;
function anchorAt(lat, lon, liftM = VESSEL_LIFT_M) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
liftM,
@@ -106,6 +127,35 @@ export function createRendering({
return fromDegrees(lon, lat, heightM);
}
/**
* Where a record's icon is anchored (see drawnAt and anchorAt).
* @param {Object} record - Vessel record with a finite lat/lon.
* @param {number} [liftM] Height above the sea surface.
* @returns {{x: number, y: number, z: number}} ECEF metres.
*/
function anchorPosition(record, liftM = VESSEL_LIFT_M) {
const { lat, lon } = drawnAt(record);
return anchorAt(lat, lon, liftM);
}
/**
* Move a prepared vessel visual to `lat`/`lon` (a host-supplied placement
* moved it), writing into its own positions rather than allocating new
* ones: the placement pass runs for every drawn vessel several times a
* second. Its icon is drawn there again.
*/
function moveRecordVisual(record, visual, lat, lon) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
fromDegreesInto(lon, lat, heightM, visual.position);
fromDegreesInto(lon, lat, heightM - VESSEL_LIFT_M, visual.waterline);
visual.drawnLat = lat;
visual.drawnLon = lon;
syncRecordIcon(record);
}
// Reused projection buffers for the card pass, grown to the candidates.
let worldXyz = new Float64Array(0);
let screenXy = new Float32Array(0);
@@ -281,12 +331,14 @@ export function createRendering({
/**
* Best available real-world direction of travel for a vessel, degrees
* clockwise from north (true heading preferred, course-over-ground fallback).
* The renderer turns this into its screen rotation each frame.
* The renderer turns this into its screen rotation each frame. An aid to
* navigation is fixed, so it has none.
* @param {Object} record - Vessel record.
* @returns {number} Course in degrees (0 when unknown).
*/
function vesselCourseDeg(record) {
if (isAidToNavigation(record)) return 0;
const direction = record.heading ?? record.course;
return Number.isFinite(direction) ? direction : 0;
}
@@ -294,6 +346,7 @@ export function createRendering({
/**
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
* The shape points north (up) so the row's course maps directly to heading.
* An aid to navigation, which has no heading, is a ringed disc instead.
* One icon is generated per color+variant and shares one atlas slot.
* @param {Object} record - Vessel record (drives per-type tint).
* @param {boolean} selected - True for the white/brighter selected variant.
@@ -301,16 +354,25 @@ export function createRendering({
*/
function shipIcon(record, selected) {
const cssColor = selected ? '#ffffff' : vesselTypeCss(record.type);
const key = `${cssColor}:${selected ? 'selected' : 'normal'}`;
const aid = isAidToNavigation(record);
const cssColor = selected
? '#ffffff'
: aid
? AID_TO_NAVIGATION_STYLE.css
: vesselTypeCss(record.type);
const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`;
if (vesselState.shipIconCache.has(key))
return vesselState.shipIconCache.get(key);
const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)';
const strokeWidth = selected ? 1.1 : 0.7;
const shape = aid
? `<circle r="8" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth * 2}"/>
<circle r="3" fill="${stroke}"/>`
: `<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>`;
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
<g transform="translate(16,16)">
<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>
${shape}
</g>
</svg>`;
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
@@ -344,8 +406,13 @@ export function createRendering({
});
}
/** The model item for `record`, its spec rebuilt only when its type or size changes. */
/**
* The model item for `record`, its spec rebuilt only when its type or size
* changes; null for a virtual aid to navigation, which keeps its disc: no
* buoy stands there (vesselModelSpec).
*/
function modelItem(record, set) {
if (record.virtual === true) return null;
let item = modelItems.get(record.id);
if (!item || item.record !== record)
item = {
@@ -354,13 +421,14 @@ export function createRendering({
tint: null,
modelOwnsVisual: false,
};
const specKey = `${record.type}|${record.length}|${record.beam}|${record.name}`;
const specKey = `${record.type}|${record.mmsi}|${record.length}|${record.beam}|${record.name}`;
if (item.specKey !== specKey) {
item.specKey = specKey;
item.spec = vesselModelSpec(set, record);
}
item.position = getVisual(record).waterline;
item.headingDeg = vesselCourseDeg(record);
// An aid to navigation is a fixed mark: it does not turn to a heading.
item.headingDeg = item.spec?.fixed ? 0 : vesselCourseDeg(record);
item.show = record.id !== state.cockpitSubjectId;
return item;
}
@@ -381,7 +449,8 @@ export function createRendering({
const waterline = getVisual(record).waterline;
if (!waterline) continue;
if (distanceSquared(eye, waterline) > limitSq) continue;
into.set(record.id, modelItem(record, set));
const item = modelItem(record, set);
if (item) into.set(record.id, item);
}
}
@@ -412,8 +481,10 @@ export function createRendering({
gatherModelItems(set, next);
} else {
for (const [id, item] of modelItems)
if (state.records.byId.get(id) === item.record)
next.set(id, modelItem(item.record, set));
if (state.records.byId.get(id) === item.record) {
const kept = modelItem(item.record, set);
if (kept) next.set(id, kept);
}
}
for (const [id, item] of modelItems)
if (next.get(id) !== item) handBackVisual(item.record);
@@ -453,6 +524,7 @@ export function createRendering({
state.preRenderRemover =
findFrame(viewer)?.on('preRender', () => {
if (followsClock(vesselState)) followClockPositions();
else if (services.placement && state.feed.enabled) followPlacements();
updateVisibility();
if (state.feed.enabled) updateModels();
}) ?? null;
@@ -475,6 +547,52 @@ export function createRendering({
}
}
// Live with a host-supplied placement, vessels move on between refreshes:
// drawn where it places them at most every FOLLOW_POSITION_MS, with a frame
// asked for every PLACEMENT_FRAME_MS while it places any drawn vessel, so
// they move while the scene idles.
let placedAtWallMs = -Infinity;
let placing = false;
let placementFrameTimer = null;
function followPlacements() {
const wallMs = performance.now();
if (wallMs - placedAtWallMs >= FOLLOW_POSITION_MS) {
placedAtWallMs = wallMs;
placing = false;
const nowMs = vesselState._aisRuntime.now();
// Drawn vessels only, as a sprite or a model: a hidden one is placed
// again when it is drawn.
for (const record of state.records.all) {
const visual = visualRecords.get(record);
if (!visual?.position) continue;
const drawn =
(visual.visible && !isCockpitSubject(record)) ||
visual.modelOwnsVisual;
if (!drawn) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) placing = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveRecordVisual(record, visual, lat, lon);
}
}
if (placing && placementFrameTimer === null)
placementFrameTimer = vesselState._aisRuntime.setTimeout(() => {
placementFrameTimer = null;
if (state.feed.enabled && !followsClock(vesselState))
governorRequestRender('ais-vessels-placement');
}, PLACEMENT_FRAME_MS);
}
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
placedAtWallMs = -Infinity;
placing = false;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
}
function scheduleTrailingVisibilityPass(now) {
if (state.trailingVisibilityTimer) return;
const waitMs = Math.max(
@@ -837,6 +955,8 @@ export function createRendering({
installRuntime,
updateVisibility,
cancelTrailingVisibilityPass,
cancelPlacementFrame,
followPlacements,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
+36 -1
View File
@@ -1,7 +1,32 @@
/** Connect portable vessel reconciliation to scene and selection operations. */
const KNOT_MPS = 1852 / 3600;
const finiteOrNaN = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : NaN;
/**
* A vessel record's fix as a host-supplied placement takes it: its own time
* (when it was received, if the row gives none), position, speed in m/s
* (rows give knots), course and heading.
*/
function placementFix(record) {
const epoch = record.lastPositionEpoch;
return {
timeMs: Number.isFinite(epoch) ? epoch * 1000 : record.receivedAtMs,
lat: record.lat,
lon: record.lon,
altitudeM: NaN,
speedMps: Number.isFinite(record.speed) ? record.speed * KNOT_MPS : NaN,
courseDeg: finiteOrNaN(record.course),
headingDeg: finiteOrNaN(record.heading),
};
}
/**
* Connect portable vessel reconciliation to scene and selection operations.
* `placement`, a host-supplied placement, is told each live fix.
*/
export function createVesselSnapshotRenderer({
state,
placement = null,
records,
rendering,
tracking,
@@ -18,6 +43,13 @@ export function createVesselSnapshotRenderer({
rendering.ensureCollections(viewer);
const occluder = rendering.makeOccluder();
const follow = followsClock();
// Live fixes only: following the clock, the layer places every vessel.
const observe =
placement && !follow && !replace
? (record) => {
if (record.id) placement.observe(record.id, placementFix(record));
}
: () => {};
records.reconcile(
rows,
{
@@ -29,10 +61,12 @@ export function createVesselSnapshotRenderer({
},
{
add(record) {
observe(record);
rendering.prepareRecordVisual(record);
rendering.addRecordPrimitives(record, occluder);
},
updated(record) {
observe(record);
const selected = record === state.selectedRecord;
rendering.prepareRecordVisual(record);
rendering.syncRecordIcon(record);
@@ -48,6 +82,7 @@ export function createVesselSnapshotRenderer({
rendering.removeRecordPrimitives(record);
},
removed(id) {
placement?.forget(id);
if (state.trailId === id) tracking.clearSelectedVesselTrail();
},
staleSelected(record) {
+21
View File
@@ -164,6 +164,18 @@ export function createTesting({
components.rendering.updateVisibility(force);
}
/** Draw a record's visual where it stands now. Test-only seam. */
function _prepareVesselVisualForTest(record) {
return components.rendering.prepareRecordVisual(record);
}
/** Run one live placement pass (a host-supplied placement). Test-only seam. */
function _runPlacementPassForTest() {
components.rendering.followPlacements();
}
/** True while a trailing visibility frame is scheduled. Test-only seam. */
function _hasTrailingVisibilityPassForTest() {
@@ -183,6 +195,12 @@ export function createTesting({
vesselCount: state.records.byId.size,
};
}
/** The layer's record for a vessel id, or null. Test-only seam. */
function _vesselRecordForTest(id) {
return state.records.byId.get(id) ?? null;
}
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
@@ -195,7 +213,10 @@ export function createTesting({
_setAisRuntimeForTest,
_getVesselFeedStateForTest,
_getVesselStateForTest,
_vesselRecordForTest,
_runVisibilityPassForTest,
_prepareVesselVisualForTest,
_runPlacementPassForTest,
_hasTrailingVisibilityPassForTest,
};
}
+5
View File
@@ -66,6 +66,11 @@ export function createTracking({
continue;
visual.position = components.rendering.anchorPosition(record);
components.rendering.syncRecordIcon(record);
// A placed vessel is drawn again at its placement on the next pass.
if (services.placement) {
visual.drawnLat = NaN;
visual.drawnLon = NaN;
}
}
// The rows moved with no poll behind them: draw the frame that shows it.
governorRequestRender('ais-vessels-refloor');
+46
View File
@@ -4,6 +4,52 @@ export const RADAR_MAX_GAP_MS = 30 * 60_000;
export const REGIONAL_INFRARED_MAX_GAP_MS = 30 * 60_000;
export const GLOBAL_INFRARED_MAX_GAP_MS = 3 * 60 * 60_000;
export const LIGHTNING_MAX_GAP_MS = 30 * 60_000;
/** How many of a feed's latest frames say how far apart its frames come. */
const SPACING_FRAMES = 12;
/** A frame holds this many of its feed's frame spacings before it lapses. */
const SPACING_SLACK = 1.5;
/**
* How far apart a feed's frames come: the median spacing of its latest
* frames, in ms, or null with fewer than two. Takes UTC times or epoch ms.
* @param {Array<string|number>} times
* @returns {number|null}
*/
export function frameSpacingMs(times) {
const at = [
...new Set(
(times ?? [])
.map((time) => (typeof time === 'number' ? time : Date.parse(time)))
.filter(Number.isFinite),
),
]
.sort((a, b) => a - b)
.slice(-(SPACING_FRAMES + 1));
if (at.length < 2) return null;
const gaps = at
.slice(1)
.map((time, i) => time - at[i])
.sort((a, b) => a - b);
const middle = gaps.length >> 1;
return gaps.length % 2 ? gaps[middle] : (gaps[middle - 1] + gaps[middle]) / 2;
}
/**
* A product's least time, `leastMs`, held to its feed's own frame spacing:
* never less than one and a half spacings, so a feed whose frames come an
* hour apart covers the whole hour between them, while one with frames
* minutes apart keeps `leastMs`.
* @param {number} leastMs
* @param {Array<string|number>} times
* @returns {number}
*/
export function atLeastFrameSpacing(leastMs, times) {
const spacing = frameSpacingMs(times);
return spacing === null
? leastMs
: Math.max(leastMs, spacing * SPACING_SLACK);
}
/** The longest play waits on a frame before it goes on without it. */
export const PLAY_WAIT_MS = 8_000;
// Playing on its own, the world does not wait on the frame it is at: that
+64
View File
@@ -7,6 +7,8 @@ import {
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
PLAY_WAIT_MS,
frameSpacingMs,
atLeastFrameSpacing,
} from './clock.js';
import { createWorldClock } from '../../time/worldClock.js';
@@ -94,6 +96,68 @@ test('union excludes suspended products; nearest selection never uses future or
assert.equal(LIGHTNING_MAX_GAP_MS, 30 * 60_000);
});
test('a feed’s frame spacing is the median of its latest frames', () => {
assert.equal(frameSpacingMs([]), null);
assert.equal(frameSpacingMs([time(0)]), null);
assert.equal(frameSpacingMs([0, 10, 20, 30].map(time)), 10 * 60_000);
// Out of order, repeated, unparseable, and one late frame among many.
assert.equal(
frameSpacingMs([
time(60),
time(0),
'never',
time(0),
time(10),
time(20),
time(30),
]),
10 * 60_000,
);
assert.equal(frameSpacingMs([0, 60, 120].map(time)), 60 * 60_000);
assert.equal(frameSpacingMs([0, 10, 70, 130]), 60);
// Only the latest frames count: an hourly start gives way to ten minutes.
const times = [
...[-600, -540, -480, -420, -360, -300, -240, -180, -120, -60],
...[0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120],
].map(time);
assert.equal(frameSpacingMs(times), 10 * 60_000);
});
test('a product’s gap is at least one and a half of its feed’s frame spacings', (t) => {
const tenMinutes = [0, 10, 20, 30].map(time);
const hourly = [0, 60, 120].map(time);
assert.equal(
atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, tenMinutes),
REGIONAL_INFRARED_MAX_GAP_MS,
'frames minutes apart keep the product’s own gap',
);
assert.equal(
atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, hourly),
90 * 60_000,
);
assert.equal(
atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, [time(0)]),
REGIONAL_INFRARED_MAX_GAP_MS,
);
assert.equal(
atLeastFrameSpacing(GLOBAL_INFRARED_MAX_GAP_MS, hourly),
GLOBAL_INFRARED_MAX_GAP_MS,
);
// Selected against it, an hourly feed has a frame all through each hour.
const { clock } = harness(t);
const clouds = product(
'clouds',
[0, 60, 120],
atLeastFrameSpacing(REGIONAL_INFRARED_MAX_GAP_MS, hourly),
);
clock.register(clouds);
assert.equal(clock.selectFor('clouds', time(45)), time(0));
assert.equal(clock.selectFor('clouds', time(119)), time(60));
assert.equal(clock.selectFor('clouds', time(210)), time(120));
assert.equal(clock.selectFor('clouds', time(211)), null);
});
test('history applies per-product selections, including null; latest restores unequal newest times', async (t) => {
const { clock } = harness(t);
const radar = product('radar', [0, 10, 20]);
+26 -6
View File
@@ -8,6 +8,7 @@ import {
REGIONAL_INFRARED_MAX_GAP_MS,
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
atLeastFrameSpacing,
} from './clock.js';
import { formatUtcDayMonth, t, msg } from '../../i18n/index.js';
import { formatScaleLabel } from '../../ui/unitLabels.js';
@@ -102,7 +103,10 @@ export function createWeatherLayer({
let unregisterClock = null;
let frameRequest = null;
let noFrame = false;
const maxGap = () =>
// A product's own gap, and the delay after which its latest frame reads
// late. A feed whose frames come further apart holds each frame, and waits
// for the next, as long as its frames are apart (see atLeastFrameSpacing).
const productGap = () =>
radar
? RADAR_MAX_GAP_MS
: lightning
@@ -110,6 +114,23 @@ export function createWeatherLayer({
: product === 'clouds'
? GLOBAL_INFRARED_MAX_GAP_MS
: REGIONAL_INFRARED_MAX_GAP_MS;
const productDelay = () =>
(product === 'clouds' ? 240 : lightning ? 45 : 20) * 60_000;
// Read for every frame a selection weighs, so worked out once per product
// and frame list.
let spaced = null;
const spacedTimes = () => {
const times = manifest?.times ?? [];
if (spaced?.times !== times || spaced?.product !== product)
spaced = {
times,
product,
gap: atLeastFrameSpacing(productGap(), times),
delay: atLeastFrameSpacing(productDelay(), times),
};
return spaced;
};
const maxGap = () => spacedTimes().gap;
const isLatest = () =>
clock ? clock.getState().mode === 'latest' : followLatest;
const getHost = () => imageryHost?.() ?? globeImageryHost(viewer);
@@ -130,8 +151,7 @@ export function createWeatherLayer({
};
const observationDelayed = () =>
manifest?.latest &&
worldNow() - Date.parse(manifest.latest) >
(product === 'clouds' ? 240 : lightning ? 45 : 20) * 60_000;
worldNow() - Date.parse(manifest.latest) > spacedTimes().delay;
const stop = () => {
if (clock) return;
playing = false;
@@ -560,11 +580,11 @@ export function createWeatherLayer({
shared.products.find((entry) => entry.id === id)?.selected === null
? maxGap() / 60_000 < 60
? t('No frame within {gap} min of {time}', {
gap: maxGap() / 60_000,
gap: Math.round(maxGap() / 60_000),
time: utc(shared.target),
})
: t('No frame within {gap} h of {time}', {
gap: maxGap() / 3600_000,
gap: Math.round(maxGap() / 360_000) / 10,
time: utc(shared.target),
})
: null;
@@ -699,7 +719,7 @@ export function createWeatherLayer({
? t('Global · 60°S–60°N')
: t('North America')),
shownTime: time,
maxGapMinutes: maxGap() / 60_000,
maxGapMinutes: Math.round(maxGap() / 60_000),
detail,
status:
missing ||
+63
View File
@@ -1986,6 +1986,69 @@ test('satellite global selection uses the three-hour gap and preserves the share
assert.equal(params.target, undefined);
});
test('satellite clouds from an hourly feed draw all through each hour and read late only past it', async (t) => {
const clock = createWeatherClock();
const now = Date.now();
const hour = 3_600_000;
const top = Math.floor(now / hour) * hour;
// Frames an hour apart, the latest forty minutes old.
const hourly = [3, 2, 1].map((back) =>
new Date(top - back * hour + 20 * 60_000).toISOString(),
);
const latest = hourly.at(-1);
const h = layerHarness({
clock,
id: 'weather-satellite',
feed: {
getSnapshot: async ({ product }) => ({
...snapshot,
product,
times: hourly,
latest,
}),
},
});
t.after(() => {
h.layer.destroy();
clock.destroy();
});
t.mock.method(Date, 'now', () => Date.parse(latest) + 40 * 60_000);
const update = h.layer.update();
await flush();
h.stages.at(-1).finish();
await update;
assert.equal(h.layer.getParams().product, 'clouds-regional');
assert.equal(h.layer.getRowControls().summary.maxGapMinutes, 90);
assert.equal(
h.layer.getStats().stale,
false,
'forty minutes is within the hour',
);
// Forty-five minutes past a frame, between it and the next, it still shows.
const between = clock.setTarget(
new Date(Date.parse(hourly[0]) + 45 * 60_000).toISOString(),
);
await flush();
h.stages.at(-1).finish();
await between;
assert.equal(h.layer.getDiagnostics().hidden, false);
assert.equal(h.stages.at(-1).time, hourly[0]);
// Live again (a past time judges delay from the timeline's time), past
// one and a half hours it reads late.
const live = clock.latest();
await flush();
h.stages.at(-1).finish();
await live;
t.mock.method(Date, 'now', () => Date.parse(latest) + 100 * 60_000);
assert.equal(
h.layer.getStats().stale,
true,
'past one and a half hours, late',
);
});
test('switching to history cancels a still-loading latest refresh and a later target cancels the first history load', async (t) => {
const clock = createWeatherClock();
const h = layerHarness({ clock });