Merge upstream main into feat/iss-3d-model

Translation files: kept both sides' new keys.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Itallo BrandãoandClaude Opus 5.5 committed 2026-11-15 22:41:59 -03:00
commit 349b3a04ec
407 files changed
+23411 -2582

No files matched your search

+31
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { worldClock } from '../../time/worldClock.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -7,6 +8,7 @@ import {
createEarthquakeOverlayEntry,
selectEarthquakeOverlayCohort,
mapAnalystRecord,
earthquakeCoverage,
} from './model.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
@@ -27,6 +29,21 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
let _lastUpdate = null;
let _lastError = null;
let _enabled = false;
// The quakes last drawn, as the timeline reads them
// ({ mag, time, place, usgsId }).
let _events = [];
let _uncover = null;
// The marks last told to the clock, so a refresh with the same strong
// quakes does not tell it again.
let _marksKey = null;
const coverage = () => (_enabled ? earthquakeCoverage(_events) : null);
const coverageChanged = () => {
const covered = coverage();
const key = covered ? JSON.stringify(covered.marks) : null;
if (key === _marksKey) return;
_marksKey = key;
worldClock.coverageChanged();
};
const layer = {
id: 'earthquakes',
@@ -41,6 +58,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_dataSource = new Cesium.CustomDataSource('earthquakes');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
// While on, the strong quakes are marks on the world clock's timeline.
// Registered once; off, the layer has no time to show.
_marksKey = null;
_uncover = worldClock.register({ id: 'earthquakes', coverage });
_count = 0;
_lastUpdate = null;
_lastError = null;
@@ -55,6 +76,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
// layer has no per-frame animator to keep the render loop alive for.
if (_dataSource) _dataSource.show = true;
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
coverageChanged();
},
disable(viewer) {
@@ -64,6 +86,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
if (_dataSource) _dataSource.show = false;
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
coverageChanged();
},
async update(viewer) {
@@ -77,6 +100,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
return false;
const nextEntities = [];
const nextEvents = [];
let count = 0;
const overlayEntries = [];
@@ -91,6 +115,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
time,
} of rows) {
count++;
nextEvents.push({ mag, time, place, usgsId });
const baseRadius = Math.pow(2, mag) * 1000;
const color = depthColor(depthKm || 0);
const isSignificant = mag >= 5.0;
@@ -137,6 +162,8 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_dataSource.entities.removeAll();
for (const entity of nextEntities) _dataSource.entities.add(entity);
_events = nextEvents;
coverageChanged();
if (_enabled) {
overlayHost.setEntries(
EARTHQUAKE_OVERLAY_SOURCE_ID,
@@ -176,6 +203,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
viewer.dataSources.remove(_dataSource, true);
_dataSource = null;
}
_events = [];
_uncover?.();
_uncover = null;
_marksKey = null;
_count = 0;
_lastUpdate = null;
_lastError = null;
+59 -1
View File
@@ -3,6 +3,64 @@ export const EARTHQUAKE_OVERLAY_SOURCE_ID = 'earthquakes';
export const EARTHQUAKE_OVERLAY_COHORT_LIMIT = 96;
export const EARTHQUAKE_OVERLAY_COLLISION_CAPACITY = 48;
/**
* The smallest magnitude the timeline marks. Most quakes are small shakes;
* M6 and up come about once every two days worldwide, so each is an event
* worth stepping to. The map still draws every quake.
*/
export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
`M${Number(magnitude).toFixed(1)}`;
/**
* A strong quake's timeline label: its magnitude and, where the feed names
* one, its place, cut short (`M6.4 · 113 km SSE of Lata, Solomon Islands`).
* @param {{mag: number, place?: string | null}} event
* @returns {string}
*/
export function earthquakeMarkLabel({ mag, place }) {
const title = earthquakeMagnitudeTitle(mag);
const where =
typeof place === 'string' ? place.replace(/\s+/g, ' ').trim() : '';
if (!where) return title;
const short =
where.length > MARK_PLACE_LENGTH
? `${where.slice(0, MARK_PLACE_LENGTH - 1).trimEnd()}…`
: where;
return `${title} · ${short}`;
}
/**
* The time a world clock's timeline can show for `events` (`{mag, time,
* place?, usgsId?}`, time in ms): the span of the quakes of
* EARTHQUAKE_MARK_MAGNITUDE and up, each one a mark labelled with its
* magnitude and place, or null with none, so the layer never stretches the
* timeline past what its feed covers.
* @returns {{start: number, end: number, marks: Array<{time: number, label: string, id?: string, kind: string}>} | null}
*/
export function earthquakeCoverage(events) {
const marks = events
.filter(
({ mag, time }) =>
mag >= EARTHQUAKE_MARK_MAGNITUDE && Number.isFinite(time),
)
.map((event) => ({
time: event.time,
label: earthquakeMarkLabel(event),
...(event.usgsId ? { id: String(event.usgsId) } : {}),
kind: 'earthquake',
}))
.sort((a, b) => a.time - b.time);
return marks.length
? { start: marks[0].time, end: marks.at(-1).time, marks }
: null;
}
/**
* Color by depth:
* - Shallow (<70km): Red
@@ -37,7 +95,7 @@ export function createEarthquakeOverlayEntry({
id: String(id),
position,
variant: 'label',
title: `M${mag.toFixed(1)}`,
title: earthquakeMagnitudeTitle(mag),
accent,
priority: Math.round(mag * 1000),
collisionGroup: 'ambient-label',
+70
View File
@@ -2,6 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createEarthquakesLayer } from './index.js';
import { createUsgsEarthquakeSource } from './source.js';
import { EARTHQUAKE_MARK_MAGNITUDE, earthquakeMarkLabel } from './model.js';
import { worldClock } from '../../time/worldClock.js';
function harness(source) {
const sources = [];
const events = [];
@@ -88,3 +90,71 @@ test('USGS body completion honors cancellation even with an uncooperative transp
name: 'AbortError',
});
});
test('the timeline marks only strong quakes, while the layer is on', async () => {
assert.equal(EARTHQUAKE_MARK_MAGNITUDE, 6);
const rows = [
{ ...row, stableId: 'small', mag: 4.5, time: 1_000 },
{ ...row, stableId: 'strong', usgsId: 'us-strong', mag: 6, time: 5_000 },
{
...row,
stableId: 'great',
usgsId: 'us-great',
mag: 7.2,
place: ' 113 km SSE of Lata, Solomon Islands region of the Pacific ',
time: 3_000,
},
{ ...row, stableId: 'untimed', mag: 6.5, time: null },
];
let snapshot = rows;
const h = harness({ getSnapshot: async () => snapshot });
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
let changes = 0;
const unsubscribe = worldClock.subscribe(() => changes++);
await h.layer.update(h.viewer);
// Every quake is drawn; only M6 and up are marks, spanning their own time.
assert.equal(h.sources[0].entities.values.length, 4);
// Each labelled with its magnitude and, cut short, its place.
assert.deepEqual(worldClock.coverage(), {
start: 3_000,
end: 5_000,
marks: [3_000, 5_000],
markDetails: [
{
time: 3_000,
label: 'M7.2 · 113 km SSE of Lata, Solomon Islands reg…',
id: 'us-great',
kind: 'earthquake',
},
{
time: 5_000,
label: 'M6.0 · Fixture',
id: 'us-strong',
kind: 'earthquake',
},
],
});
const told = changes;
await h.layer.update(h.viewer);
assert.equal(changes, told, 'the same strong quakes are not told again');
snapshot = rows.slice(0, 1);
await h.layer.update(h.viewer);
assert.equal(worldClock.coverage(), null, 'small shakes alone cover no time');
snapshot = rows;
await h.layer.update(h.viewer);
h.layer.disable(h.viewer);
assert.equal(worldClock.coverage(), null, 'off, no time to show');
h.layer.enable(h.viewer);
assert.deepEqual(worldClock.coverage().marks, [3_000, 5_000]);
h.layer.destroy();
assert.equal(worldClock.coverage(), null);
unsubscribe();
});
test('a strong quake with no place is labelled with its magnitude alone', () => {
assert.equal(earthquakeMarkLabel({ mag: 6.44, place: null }), 'M6.4');
assert.equal(earthquakeMarkLabel({ mag: 6, place: ' ' }), 'M6.0');
assert.equal(
earthquakeMarkLabel({ mag: 8.1, place: 'Off the coast' }),
'M8.1 · Off the coast',
);
});
+2 -1
View File
@@ -31,7 +31,8 @@ export function createCards({
function rebuildAmbientLabels() {
if (!layerState._viewer) return;
const scene = layerState._viewer.scene;
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
@@ -343,7 +343,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.
*/
@@ -384,9 +384,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: Cesium.Cartesian3}} candidate - Label candidate.
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -418,7 +419,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: Cesium.Cartesian3, accent: string}} candidate
* @param {number} nowMs - Current epoch milliseconds.
* @param {number} nowMs - Epoch milliseconds ages count back from.
* @returns {Object} firmsLabels entry.
*/
@@ -549,6 +550,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) {
@@ -624,6 +638,7 @@ export function createModel({
cellCardAccent,
formatLatLon,
formatFrp,
ageReferenceMs,
formatAge,
formatAgeLabel,
formatAgoMinutes,
+3 -1
View File
@@ -202,7 +202,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',
},
+53
View File
@@ -1,8 +1,10 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
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 +44,54 @@ 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 = [];
context.mock.method(Cesium.SceneTransforms, 'worldToWindowCoordinates', () => ({ x: 400, y: 300 }));
layerState._viewer = { scene: { 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: { fireHorizonOccluder: () => null } },
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
@@ -217,6 +217,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() {
+1
View File
@@ -35,6 +35,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 * as Cesium from 'cesium';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from './placed.js';
export function createLifecycle({
flightState,
@@ -72,6 +73,10 @@ export function createLifecycle({
flightState._cullPositions.clear();
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();
@@ -291,6 +296,10 @@ export function createLifecycle({
flightState._cullPositions.clear();
flightState._detectionObjects.clear();
flightState.records.data.clear();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
+23 -10
View File
@@ -1,5 +1,9 @@
import { aircraftModelSpec, fleetModelSet } from '../../data/fleetModels.js';
import { MODEL_COLOR_BLEND_AMOUNT } from './policy.js';
import {
aircraftCallsignRule,
aircraftModelByCallsign,
aircraftModelSpec,
fleetModelSet,
} from '../../data/fleetModels.js';
/**
* What an aircraft draws with before the fleet model set has loaded: no
@@ -17,7 +21,6 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
bellyM: 0,
elevationM: 0,
tinted: false,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
visualCenterNative: Object.freeze([0, 0, 0]),
trailAnchorNative: Object.freeze([0, 0, 0]),
key: 'unloaded',
@@ -25,12 +28,14 @@ export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
/**
* The fleet model, life-size scale and measured geometry an aircraft draws
* with, chosen by its ICAO type and emitter category (`fleetModels.js`).
* with, chosen by its ICAO type and emitter category, and by its callsign
* for the types that pick by callsign (`fleetModels.js`).
* Shared by the Flights, Military Flights and Local ADS-B layers so all three
* draw the same model for the same aircraft. `bellyM` is the model's scaled
* clearance: how far a grounded aircraft's origin stands above the ground.
* @param {{typeCode?: string|null, type?: string|null,
* category?: string|number|null}|null|undefined} aircraft
* category?: string|number|null,
* callsign?: string|null}|null|undefined} aircraft
* @param {object|null} [set] The loaded fleet model set.
* @returns {object} The spec, or {@link UNLOADED_AIRCRAFT_MODEL_SPEC} before
* the set has loaded.
@@ -40,17 +45,17 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
// Layers ask on every tick; each type and category is resolved once per set.
let cache = specCaches.get(set);
if (!cache) specCaches.set(set, (cache = new Map()));
const key = aircraftModelSpecCacheKey(aircraft);
const key = aircraftModelSpecCacheKey(aircraft, set);
let layerSpec = cache.get(key);
if (!layerSpec) {
const spec = aircraftModelSpec(set, {
typeCode: aircraft?.typeCode ?? aircraft?.type ?? null,
category: aircraft?.category ?? null,
callsign: aircraft?.callsign ?? null,
});
layerSpec = Object.freeze({
...spec,
bellyM: spec.clearanceM,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
});
cache.set(key, layerSpec);
}
@@ -61,10 +66,18 @@ export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
const specCaches = new WeakMap();
/**
* Cache key of an aircraft's model spec: what selects its model.
* Cache key of an aircraft's model spec: what selects its model. For a type
* that picks its model by callsign (an airport vehicle) the key adds the
* rule its callsign matches, or `type` for none, so such a type caches at
* most one entry per rule and one for its own model.
* @param {object|null|undefined} aircraft
* @param {object|null} [set] The loaded fleet model set.
* @returns {string}
*/
export function aircraftModelSpecCacheKey(aircraft) {
return `${aircraft?.typeCode ?? aircraft?.type ?? ''}|${aircraft?.category ?? ''}`;
export function aircraftModelSpecCacheKey(aircraft, set = fleetModelSet()) {
const type = aircraft?.typeCode ?? aircraft?.type ?? '';
const key = `${type}|${aircraft?.category ?? ''}`;
if (!set || !aircraftModelByCallsign(set.types, type)) return key;
const rule = aircraftCallsignRule(set.types, type, aircraft?.callsign);
return `${key}|${rule >= 0 ? `r${rule}` : 'type'}`;
}
+39 -5
View File
@@ -1,4 +1,9 @@
import * as Cesium from 'cesium';
import {
historyBracketIndex,
historyUnseenAt,
liftGroundedHistory,
} from '../../data/timelineHistory.js';
import { julianAt } from '../../time/julian.js';
import {
COURSE_HOLD_SPEED_MPS,
@@ -16,6 +21,7 @@ import {
COAST_MAX_SPEED_MPS,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from './placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -119,6 +125,7 @@ export function createMotion({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
flightState._cullPositions.delete(icao24); // above the ellipsoid now (or floors say otherwise next poll)
const position = Cesium.Cartesian3.fromDegrees(
@@ -126,10 +133,12 @@ export function createMotion({
info.rawLat,
lifted,
);
const history = flightState._positionHistory.get(icao24);
const newest = history?.[history.length - 1];
if (newest)
newest.position = Cesium.Cartesian3.clone(position, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
position,
drawnM,
lifted,
);
const bb = flightState._billboards.get(icao24);
if (bb) bb.position = position;
}
@@ -152,6 +161,7 @@ export function createMotion({
function _deadReckon(icao24, result, sampledRenderTime) {
const info = flightState.records.data.get(icao24);
flightState._drUnseen = false;
if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) {
const position = flightState._billboards.get(icao24)?.position;
flightState._drCourseDeg = info?.true_track || 0;
@@ -173,6 +183,19 @@ export function createMotion({
}
const out = result || new Cesium.Cartesian3();
// 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 one poll interval behind real time so we interpolate between
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
const renderTime =
@@ -184,7 +207,15 @@ export function createMotion({
);
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
for (let i = history.length - 1; i >= 1; i--) {
// The pair around the render time (and the one before it, for a fix at
// exactly that time), found by halving: a contact following the clock
// keeps a long history.
for (
let i = historyBracketIndex(history, renderTime),
stop = Math.max(1, i - 1);
i >= stop;
i--
) {
const a = history[i - 1];
const b = history[i];
if (
@@ -240,6 +271,9 @@ export function createMotion({
// the oldest fix froze the icon; extrapolating the NEWEST fix to wall-clock now made
// the icon jump back ~one poll interval the instant interpolation took over.)
const oldest = history[0];
// Following the clock, a time well before its first fix is before it
// was there: the fleet pass hides it.
flightState._drUnseen = historyUnseenAt(history, renderTime);
const lookbackSec = Cesium.JulianDate.secondsDifference(
oldest.time,
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 };
@@ -184,3 +187,189 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
);
assert.equal(reads, 2);
});
/** 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);
});
+112
View File
@@ -0,0 +1,112 @@
import * as Cesium from 'cesium';
import { COURSE_HOLD_SPEED_MPS } from '../../data/motionModel.js';
import { followsClock } from './policy.js';
/** Scratch for a placed contact's held height. */
const _placedCarto = new Cesium.Cartographic();
/**
* Where the host-supplied placement (`services.placement`,
* ../../data/placementProvider.js) 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. A
* placement without a height keeps the aircraft's newest drawn height.
* @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: Cesium.Cartesian3}[]} history Its fixes, newest last.
* @param {Cesium.Cartesian3} out
* @returns {boolean}
*/
export function placeLiveAircraft(
flightState,
placement,
icao24,
info,
history,
out,
) {
if (!placement || followsClock(flightState)) return false;
const placed = placement.place(icao24, flightState.now());
if (!placed) return false;
let heightM = placed.altitudeM;
if (!Number.isFinite(heightM)) heightM = info?.renderAltitudeM;
if (!Number.isFinite(heightM))
heightM = Cesium.Cartographic.fromCartesian(
history[history.length - 1].position,
Cesium.Ellipsoid.WGS84,
_placedCarto,
).height;
const speed = 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;
flightState._drCourseDeg = Number.isFinite(placed.courseDeg)
? placed.courseDeg
: Number.isFinite(info?.true_track)
? info.true_track
: info?.track || 0;
flightState._drSpeedMps = speed;
flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS;
flightState._drExtrapolating = placed.extrapolating;
Cesium.Cartesian3.fromDegrees(
placed.lon,
placed.lat,
heightM,
Cesium.Ellipsoid.WGS84,
out,
);
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,
});
}
-4
View File
@@ -85,10 +85,6 @@ export const MODEL_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite Cesium heading 0
// Owner launch-polish direction: models should read as clean light silhouettes,
// with only a weak diffuse contribution from the models' own colours.
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
export const CYAN_TRANSPARENT = Cesium.Color.CYAN.withAlpha(0);
+77 -4
View File
@@ -1,10 +1,16 @@
import { stickyNumber, stickyText } from '../../data/aircraftMeta.js';
import { courseFromFixes } from '../../data/courseFromFixes.js';
import {
geoidSurfaceLastResortM,
pickRenderAltitudeM,
} from '../../data/renderAltitude.js';
import { classifyAircraft } from '../../data/aircraftClass.js';
import { aircraftEmergency } from '../../data/aircraftEmergency.js';
import {
aircraftCallsignRule,
aircraftModelSpec,
fleetModelSet,
} from '../../data/fleetModels.js';
import {
approxDistanceKm,
GROUND_FLOOR_CLAMP_RADIUS_KM,
@@ -21,6 +27,7 @@ export class FlightRecords {
cachedGroundFloor,
floorAltitudeM,
now = () => Date.now(),
fleetModels = fleetModelSet,
}) {
this.services = {
geoidHeight,
@@ -29,6 +36,8 @@ export class FlightRecords {
};
/** The time records are judged at: the layer's clock. */
this.now = now;
/** The loaded fleet model set, or null before it loads. */
this.fleetModels = fleetModels;
this.data = new Map();
// Facts about an airframe, not a moment, kept across a reset.
this.airframes = new Map();
@@ -92,7 +101,6 @@ export class FlightRecords {
verticalRateMps: vertical_rate,
} = observation;
const onGround = on_ground === true;
this.missingPolls.delete(icao24);
// Sticky merge: OpenSky intermittently drops callsign/velocity/track for
// aircraft it still positions — hold last-known-good instead of
@@ -102,6 +110,27 @@ export class FlightRecords {
// The airframe's facts: this record's, or those kept across a reset.
const airframe = prevMeta ?? this.airframes.get(icao24);
this.airframes.delete(icao24);
// A ground vehicle or ground station (a feed's ZVEH or GRND: a model
// built standing, catalog category `other`) takes the feed's own type,
// which no airframe lookup knows; every other aircraft keeps waiting for
// its looked-up type. With no altitude at all it stands on the ground,
// where it is, instead of at the airborne default.
const groundModel = (typeCode) =>
drawnAsGroundModel(
this.fleetModels(),
typeCode,
category,
stickyText(callsign, prevMeta?.callsign),
);
const feedType = observation.typeCode || null;
const typeCode =
airframe?.typeCode ??
(feedType && groundModel(feedType) ? feedType : null);
const onGround =
on_ground === true ||
(!Number.isFinite(baro_alt) &&
!Number.isFinite(geo_alt) &&
groundModel(typeCode));
// Grounded planes with no baro reading sit at 0 m, not the 10 km
// airborne default (a parked plane must never float).
// NOTE (height-datum fix): `alt` stays the AVIATION field — the sticky
@@ -263,6 +292,12 @@ export class FlightRecords {
observation.positionTimeMs > 0
? observation.positionTimeMs
: this.now();
const course = courseFromFixes(prevMeta?.courseAnchor, {
lat,
lon,
ms: fixEpochMs,
speedMps: velocity,
});
const meta = {
sourceReference: observation.reference,
observedReceiptMs: this.now(),
@@ -281,7 +316,14 @@ export class FlightRecords {
// applies to contacts that actually flew this session.
wasAirborne: prevMeta?.wasAirborne === true || !onGround,
velocity: stickyNumber(velocity, prevMeta?.velocity, 0),
true_track: stickyNumber(true_track, prevMeta?.true_track, 0),
// With no reported track or true heading, a moving contact faces the
// way its fixes went (src/data/courseFromFixes.js); else the last one.
true_track: stickyNumber(
true_track,
course.courseDeg ?? prevMeta?.true_track,
0,
),
courseAnchor: course.anchor,
category: cat,
// An adsbdb-enriched type code outranks the coarse OpenSky category.
klass: classifyAircraft({
@@ -319,8 +361,9 @@ export class FlightRecords {
prevMeta?.lastContactEpochMs,
null,
),
// adsbdb enrichment — written by the enrichment callbacks, carried across polls:
typeCode: airframe?.typeCode ?? null,
// adsbdb enrichment — written by the enrichment callbacks, carried
// across polls; a ground vehicle's or station's from the feed:
typeCode,
typeName: airframe?.typeName ?? null,
registration: airframe?.registration ?? null,
airline: routeHeld ? (airframe.airline ?? null) : null,
@@ -408,3 +451,33 @@ export class FlightRecords {
this.geoidNCache.delete(id);
}
}
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
const groundModelCaches = new WeakMap();
/**
* Whether an aircraft of this type, emitter category and callsign is drawn
* with a model built standing on the ground (catalog category `other`: an
* airport vehicle, a ground station's mast). False before the set loads.
* Answered once per type, category and callsign rule matched.
* @param {object|null} set The loaded fleet model set.
* @param {string|null} typeCode
* @param {string|number|null} category
* @param {string|null} callsign
* @returns {boolean}
*/
function drawnAsGroundModel(set, typeCode, category, callsign) {
if (!set || !typeCode) return false;
let cache = groundModelCaches.get(set);
if (!cache) groundModelCaches.set(set, (cache = new Map()));
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
const key = `${typeCode}|${category ?? ''}|${rule}`;
let ground = cache.get(key);
if (ground === undefined) {
ground =
aircraftModelSpec(set, { typeCode, category, callsign }).category ===
'other';
cache.set(key, ground);
}
return ground;
}
+106 -1
View File
@@ -1,13 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { FlightRecords } from './records.js';
function records() {
const FLEET = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../../../public/models/fleet',
);
const fleetSet = {
catalog: JSON.parse(
fs.readFileSync(path.join(FLEET, 'catalog.json'), 'utf8'),
),
types: JSON.parse(fs.readFileSync(path.join(FLEET, 'types.json'), 'utf8')),
};
function records(fleetModels = () => null) {
return new FlightRecords({
geoidHeight: () => 40,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
approxDistanceKm: () => 0,
fleetModels,
});
}
const view = () => ({
@@ -260,3 +275,93 @@ test('a repeated fix time marks the contact as not updated; removal is unchanged
store.forget('abc123');
assert.equal(store.fixRepeated.has('abc123'), false);
});
test('a ground vehicle or station with no altitude stands on the ground; an aircraft does not', () => {
const store = records(() => fleetSet);
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
const vehicle = store.receive(
observation({
id: 'v1',
typeCode: 'ZVEH',
callsign: 'FIRE 2',
...noAltitude,
}),
view(),
).meta;
assert.equal(vehicle.onGround, true);
assert.equal(vehicle.typeCode, 'ZVEH');
assert.equal(vehicle.altitude, 0);
const mast = store.receive(
observation({ id: 'm1', typeCode: 'GRND', callsign: 'RX5', ...noAltitude }),
view(),
).meta;
assert.equal(mast.onGround, true);
assert.equal(mast.typeCode, 'GRND');
// An airliner with no altitude keeps the airborne default, and its feed
// type still waits for the airframe lookup.
const plane = store.receive(
observation({ id: 'p1', typeCode: 'A320', ...noAltitude }),
view(),
).meta;
assert.equal(plane.onGround, false);
assert.equal(plane.altitude, 10000);
assert.equal(plane.typeCode, null);
// A vehicle reporting an altitude is placed by it.
const reported = store.receive(
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }),
view(),
).meta;
assert.equal(reported.onGround, false);
// Before the model set loads nothing is grounded by its model.
const unloaded = records().receive(
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
view(),
).meta;
assert.equal(unloaded.onGround, false);
});
test('a contact reported with no course faces the way its newer fixes went', () => {
const store = records();
const T = 1700000000000;
const taxi = (latitude, seconds, fields = {}) =>
store.receive(
observation({
latitude,
longitude: -97.6588,
courseDeg: null,
onGround: true,
speedMps: 8,
positionTimeMs: T + seconds * 1000,
...fields,
}),
view(),
);
const course = () => store.data.get('abc123').true_track;
taxi(30.1908, 0);
assert.equal(course(), 0, 'nothing known yet');
// Fixes a second apart, 8 m each: they add up until 30 m are covered.
taxi(30.19073, 1);
taxi(30.19066, 2);
assert.equal(course(), 0, 'under 30 m: still nothing');
taxi(30.19059, 3);
taxi(30.19052, 4);
assert.ok(Math.abs(course() - 180) < 0.1, 'southbound');
// An older fix from another feed, behind it: never turns it around.
taxi(30.1912, 2);
assert.ok(Math.abs(course() - 180) < 0.1, 'an older fix gives no course');
taxi(30.1901, 8);
assert.ok(Math.abs(course() - 180) < 0.1);
// Standing (reported under 2 m/s) with 40 m of position noise: kept.
taxi(30.18974, 12, { speedMps: 0.5, longitude: -97.6584 });
assert.ok(
Math.abs(course() - 180) < 0.1,
'a standing contact keeps its course',
);
// A reported course always wins.
taxi(30.189, 16, { courseDeg: 175 });
assert.equal(course(), 175);
// A reset forgets where it was: it starts again from north.
store.reset();
taxi(30.188, 20);
assert.equal(course(), 0);
});
+16 -14
View File
@@ -45,7 +45,10 @@ import {
STALE_ALPHA,
displayDelayMs,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from '../../data/aircraftModelLighting.js';
export function createRendering({
flightState,
@@ -192,11 +195,12 @@ export function createRendering({
* @returns {void}
*/
/** Model tint, mirroring the billboard color rules. */
/** Model colour: the mesh's own (white), tinted cyan while tracked and red
* while broadcasting an emergency. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return Cesium.Color.CYAN;
return _fleetBillboardColor(icao24);
return _isEmergency(icao24) ? EMERGENCY_TINT : Cesium.Color.WHITE;
}
/** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude
@@ -526,10 +530,7 @@ export function createRendering({
minimumPixelSize: MODEL_MIN_PX,
scale: spec.scale,
color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24),
colorBlendMode: Cesium.ColorBlendMode.MIX,
// Launch presentation keeps the code-side tint dominant for every approved
// model; IR boost removes the remaining diffuse hint with flat UNLIT white.
colorBlendAmount: flightState._irBoost ? 1.0 : spec.blendAmount,
...aircraftModelBlend(flightState._irBoost),
customShader: flightState._irBoost
? flightState._IR_UNLIT_SHADER
: undefined,
@@ -748,10 +749,7 @@ export function createRendering({
minimumPixelSize: TRACKED_MODEL_MIN_PX,
scale: trackedSpec.scale,
color: flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN,
colorBlendMode: Cesium.ColorBlendMode.MIX,
// The tracked aircraft uses the same dominant light tint as the fleet;
// IR boost removes the remaining diffuse hint with flat UNLIT white.
colorBlendAmount: flightState._irBoost ? 1.0 : trackedSpec.blendAmount,
...aircraftModelBlend(flightState._irBoost),
customShader: flightState._irBoost
? flightState._IR_UNLIT_SHADER
: undefined,
@@ -1034,6 +1032,7 @@ export function createRendering({
flightState._scratchFleetPos,
renderTime,
);
const unseen = flightState._drUnseen;
// The dead-reckoned point drifts away from the fix whose cell supplied the
// height, so a grounded contact's sprite ends up under the mesh it taxied
// (or coasted) over. Re-floor at the DISPLAYED coordinate — read-only, and
@@ -1059,9 +1058,12 @@ export function createRendering({
// sub-ellipsoid point near the limb "beyond the horizon" and the fleet
// pass would hide a plane that is really just low over high-N terrain
// waiting for its floor to warm (ATL grounded contacts at geoid −31 m).
const beyondHorizon = !occluder.isPointVisible(
flightState._cullPositions.get(icao24) || bb.position,
);
// A contact not there yet at the time drawn is hidden as one beyond it.
const beyondHorizon =
unseen ||
!occluder.isPointVisible(
flightState._cullPositions.get(icao24) || bb.position,
);
// A billboard flipping INTO view (horizon reveal while the camera idles)
// gets its rotation refreshed THIS tick even without a pose change —
// otherwise it reappears wearing its stale (often creation-north) nose for
+115 -67
View File
@@ -9,10 +9,16 @@ import {
import { aircraftIcon } from '../../data/aircraftIcons.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
import { observeLiveAircraft } from './placed.js';
import {
historyAfterTrail,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
/** Apply reconciled aircraft records to Cesium resources and follow state. */
export function createFlightSnapshotRenderer({
flightState,
placement = null,
records,
militaryRegistry,
groundFloor,
@@ -65,6 +71,7 @@ export function createFlightSnapshotRenderer({
flightState._billboards.delete(icao24);
rendering._releaseModel(icao24); // military-suppression: drop any 3D model too
records.forget(icao24);
placement?.forget(icao24);
flightState._cullPositions.delete(icao24);
flightState._positionHistory.delete(icao24);
flightState._displayCourse.delete(icao24);
@@ -98,79 +105,116 @@ export function createFlightSnapshotRenderer({
);
const isTracked = icao24 === flightState._trackedIcao;
// 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
// back/forward oscillation. Only append when the fix actually
// advances, so stale repeats don't create zero-dt segments.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.velocity,
track: meta.true_track,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
// so the visible trail keeps growing while tracked. Ground traffic
// appends nothing — a touchdown freezes the existing trail.
// Round 2 (owner): ground traffic appends too — taxi history stays
// live after touchdown (grounded flights positions are already
// surface-clamped via the surfaceM chain, so the ground leg drapes).
// Following the clock, a record may carry its own track around the
// time: the contact is placed on it, so the clock can move within it,
// back as well as on, without another snapshot.
const timelineHistory = followsClock(flightState)
? mergeAircraftTimelineFixes(
flightState._positionHistory.get(icao24),
observation,
meta,
meta.velocity,
snapshot.observedAtMs ?? fixEpochMs,
)
: null;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
placement,
icao24,
fixEpochMs,
meta,
meta.velocity,
meta.true_track,
);
if (timelineHistory) {
if (isTracked)
tracking._appendTrailFix(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(entry.position.clone(), entry.epochMs, {
nullAltitude: entry.inventedHeight,
});
flightState._positionHistory.set(icao24, timelineHistory);
meta.turnRateDps = 0;
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
// 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
// back/forward oscillation. Only append when the fix actually
// advances, so stale repeats don't create zero-dt segments.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
// Apply fresh kinematics only from a forward synthetic fix. Mutating
// the historical fix reprojects the entire stale interval and snaps
// the rendered aircraft when course or speed changes late. The stale
// rules apply: none for a contact that holds at its report, a coast
// capped from the real report, never below the ground. It is a motion
// aid, not a report, so it never joins the trail.
const kinematicsChanged =
newest.velocity !== meta.velocity || newest.track !== meta.true_track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
// Trail accumulation is separate from the 5-fix DR history (PRD F1)
// so the visible trail keeps growing while tracked. Ground traffic
// appends nothing — a touchdown freezes the existing trail.
// Round 2 (owner): ground traffic appends too — taxi history stays
// live after touchdown (grounded flights positions are already
// surface-clamped via the surfaceM chain, so the ground leg drapes).
if (isTracked)
tracking._appendTrailFix(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
}
// Apply fresh kinematics only from a forward synthetic fix. Mutating
// the historical fix reprojects the entire stale interval and snaps
// the rendered aircraft when course or speed changes late. The stale
// rules apply: none for a contact that holds at its report, a coast
// capped from the real report, never below the ground. It is a motion
// aid, not a report, so it never joins the trail.
const kinematicsChanged =
newest.velocity !== meta.velocity ||
newest.track !== meta.true_track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
}
}
}
}
@@ -214,6 +258,7 @@ export function createFlightSnapshotRenderer({
// the raw fix drew it ahead until the next fleet tick snapped it back;
// skipping the floor started a taxiing contact low and then raised it.
const delayed = motion._deadReckon(icao24, new Cesium.Cartesian3());
const unseenAtStart = flightState._drUnseen;
const displayed =
(delayed &&
motion._floorGroundedDisplayPosition(
@@ -242,7 +287,9 @@ export function createFlightSnapshotRenderer({
// close (_groundDepthDistance).
disableDepthTestDistance: rendering._groundDepthDistance(),
id: icao24,
show: !isTracked, // hidden if currently tracked (entity replaces it)
// Hidden if currently tracked (entity replaces it), or not there yet
// at the time drawn (see historyUnseenAt).
show: !isTracked && !unseenAtStart,
});
flightState._billboards.set(icao24, bb);
rendering._applyFleetBillboardPresentation(icao24, bb);
@@ -311,6 +358,7 @@ export function createFlightSnapshotRenderer({
flightState._billboards.delete(icao24);
rendering._releaseModel(icao24); // aged-out aircraft: drop its 3D model (no orphan / cap leak)
records.forget(icao24);
placement?.forget(icao24);
flightState._cullPositions.delete(icao24);
flightState._positionHistory.delete(icao24);
flightState._displayCourse.delete(icao24);
+5
View File
@@ -321,6 +321,11 @@ export function createFlightState({ source, services }) {
flightState._drExtrapolating = false;
/** Set by `_deadReckon`: following the clock, the time drawn is well
* before the contact's first fix, so the fleet pass does not draw it. */
flightState._drUnseen = false;
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
flightState._cachedDRCourse = null;
+1
View File
@@ -1289,6 +1289,7 @@ export function createTracking({
flightState._billboards.delete(icao24);
parts.rendering._releaseModel(icao24); // military-suppression: drop any 3D model too
flightState.records.data.delete(icao24);
services.placement?.forget(icao24);
flightState._cullPositions.delete(icao24);
flightState._positionHistory.delete(icao24);
flightState._displayCourse.delete(icao24);
+10 -15
View File
@@ -3,10 +3,10 @@ import { formatNumber, msg, t } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
GNSS_LEVEL_COLORS,
GNSS_MIN_AIRCRAFT,
GNSS_WINDOW_MS,
accumulateGnssObservations,
binGnssCells,
gnssCellRing,
gnssProvenance,
pruneGnssObservations,
} from './records.js';
@@ -62,7 +62,7 @@ export function defaultGnssViewAnchor(viewer) {
/**
* Own one GNSS navigation-integrity display: rolling integrity observations
* around the views the user visits, binned into cells coloured by the
* around the views the user visits, binned into H3 hexagons coloured by the
* gpsjam low-accuracy score. Share links retain token 3.
*/
export function createGnssIntegrityLayer({
@@ -185,13 +185,12 @@ export function createGnssIntegrityLayer({
(cell) =>
new Cesium.GeometryInstance({
id: `${layer.id}:${cell.id}`,
geometry: new Cesium.RectangleGeometry({
rectangle: Cesium.Rectangle.fromDegrees(
cell.west,
cell.south,
cell.east,
cell.north,
geometry: new Cesium.PolygonGeometry({
// H3 edges are great-circle arcs, as Cesium's geodesic edges.
polygonHierarchy: new Cesium.PolygonHierarchy(
Cesium.Cartesian3.fromDegreesArray(gnssCellRing(cell)),
),
arcType: Cesium.ArcType.GEODESIC,
vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT,
}),
attributes: {
@@ -209,7 +208,7 @@ export function createGnssIntegrityLayer({
}),
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
// Retain the compact rectangle descriptors for inspection, not Entity visualizers.
// Retain the compact polygon descriptors for inspection, not Entity visualizers.
releaseGeometryInstances: false,
}),
);
@@ -396,7 +395,7 @@ export function createGnssIntegrityLayer({
}`
: ''),
infoTitle: t(
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank cells are outside sampled coverage or have insufficient observations.',
'Updates automatically after pan or zoom and once a minute. The public feed covers a 250-nautical-mile circle around the view centre; zooming out does not make it a worldwide snapshot. Blank areas had no aircraft reporting navigation accuracy in the window.',
),
legend: ['high', 'medium', 'low'].map((level, index) => ({
label: t(LEVEL_LABELS[level]),
@@ -405,11 +404,7 @@ export function createGnssIntegrityLayer({
...(index === 0
? {
blurb: t(
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Cells need {aircraft} aircraft over {minutes} minutes. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
{
aircraft: formatNumber(GNSS_MIN_AIRCRAFT),
minutes: formatNumber(provenance.window.minutes),
},
'Low-accuracy score = 100 × max(0, bad − 1) / total: one aircraft is discounted, so this is not the raw share. Navigation-integrity anomalies are not a detection of jamming or spoofing.',
),
}
: {}),
+21 -13
View File
@@ -75,8 +75,8 @@ function harness(
const MIN = 60_000;
const threeHealthy = () => [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
];
const flush = () => new Promise((resolve) => setImmediate(resolve));
@@ -216,21 +216,25 @@ test('an enabled refresh bins the snapshot into coloured ground cells', async ()
assert.equal(sources[0].show, true);
assert.equal(await layer.update(), true);
const entities = sources[0].get(0).geometryInstances;
assert.equal(entities.length, 1, 'the one-aircraft cell is withheld');
assert.equal(entities[0].id, 'gnss-integrity:280:420');
assert.ok(entities[0].geometry instanceof Cesium.RectangleGeometry);
assert.equal(entities.length, 2, 'a one-aircraft cell is shown too');
assert.deepEqual(
entities.map(({ id }) => id),
['gnss-integrity:841e631ffffffff', 'gnss-integrity:841f6b3ffffffff'],
);
for (const { geometry } of entities)
assert.ok(geometry instanceof Cesium.PolygonGeometry);
assert.equal(sources[0].get(0).allowPicking, false);
const stats = layer.getStats();
assert.equal(stats.count, 1);
assert.equal(stats.count, 2);
assert.equal(stats.error, null);
assert.equal(stats.fallback, false);
const { legend } = layer.getRowControls();
assert.deepEqual(
legend.map(({ count }) => count),
[1, 0, 0],
[1, 0, 1],
);
assert.match(legend[0].blurb, /not a detection/);
assert.match(legend[0].blurb, /need 3 aircraft/);
assert.doesNotMatch(legend[0].blurb, /need \d+ aircraft/);
});
test('the visible layer leads with low navigation accuracy and exposes its provenance', async () => {
@@ -262,10 +266,10 @@ test('the visible layer leads with low navigation accuracy and exposes its prove
assert.deepEqual(layer.provenance.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(layer.provenance.aggregation.grid, 'h3');
assert.equal(layer.provenance.aggregation.h3Resolution, 4);
assert.equal(layer.provenance.interpretation.validated, false);
assert.equal(layer.getStats().provenance, layer.provenance);
});
@@ -277,8 +281,8 @@ test('a failed refresh keeps the last cells and reports the error', async () =>
return {
rows: [
row('a1', 1.1, false),
row('a2', 1.2, false),
row('a3', 1.3, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
stale: true,
};
@@ -305,7 +309,11 @@ test('observations expire with the window, and disable aborts the request in fli
layer.enable();
let result = layer.update();
pending.resolve({
rows: [row('a1', 1.1, false), row('a2', 1.2, false), row('a3', 1.3, false)],
rows: [
row('a1', 1.1, false),
row('a2', 1.12, false),
row('a3', 1.14, false),
],
});
assert.equal(await result, true);
assert.equal(layer.getStats().count, 1);
+48 -34
View File
@@ -1,5 +1,5 @@
/**
* Low navigation accuracy reported by ADS-B aircraft, binned into cells.
* Low navigation accuracy reported by ADS-B aircraft, binned into H3 cells.
*
* Aircraft broadcasting DO-260 version 1/2 ADS-B report how much they trust
* their own position: NIC (integrity containment radius) and NACp (position
@@ -16,9 +16,12 @@
* from the US 14 CFR 91.227(c) ADS-B Out performance minima, which are not
* a published interference classifier) or the readsb/tar1090 `gpsOkBefore`
* flag. gpsjam.org does not publish its per-aircraft threshold.
* - Cell aggregation: gpsjam.org's published formula and 2% / 10% bands.
* - Cell aggregation: gpsjam.org's published formula, 2% / 10% bands and
* hex grid (H3 resolution 4). Every cell with an aircraft is shown, as on
* gpsjam.org; the one-aircraft discount is the only small-sample guard.
* - Window: a GEV-defined rolling 30 minutes over the views the user visits.
*/
import { cellToBoundary, cellToLatLng, latLngToCell } from 'h3-js';
/** Position source can switch to MLAT after GPS loss; quality must remain aircraft-reported. */
const QUALIFYING_TYPES = new Set(['adsb_icao', 'mlat']);
@@ -30,10 +33,8 @@ export const GNSS_NIC_THRESHOLD = 7;
export const GNSS_NACP_THRESHOLD = 8;
/** Positions older than this are not current evidence of the local sky. */
const MAX_POSITION_AGE_S = 60;
/** Cell edge in degrees: roughly 55 km north-south, similar in area to an H3 res-4 cell. */
export const GNSS_CELL_DEG = 0.5;
/** Hide sparse one- and two-aircraft cells; the aggregation separately discounts one bad report. */
export const GNSS_MIN_AIRCRAFT = 3;
/** H3 resolution of the cells, gpsjam.org's grid: hexagons of about 1,770 km² (22.6 km edge). */
export const GNSS_H3_RESOLUTION = 4;
/** Rolling window over which aircraft seen in a cell are counted. */
export const GNSS_WINDOW_MS = 30 * 60_000;
/** gpsjam.org band edges, in percent of aircraft (after discounting one). */
@@ -68,14 +69,14 @@ export function gnssProvenance({ windowMs = GNSS_WINDOW_MS } = {}) {
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: Object.freeze([GNSS_MEDIUM_PERCENT, GNSS_HIGH_PERCENT]),
grid: 'h3',
h3Resolution: GNSS_H3_RESOLUTION,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
}),
window: Object.freeze({
minutes: windowMs / 60_000,
scope: 'visited-view',
cellDeg: GNSS_CELL_DEG,
minAircraft: GNSS_MIN_AIRCRAFT,
definedBy: 'GEV',
}),
state: Object.freeze({
@@ -161,11 +162,30 @@ export function normalizeGnssAircraft(payload) {
return rows;
}
/** Stable key of the cell containing a position. */
export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
const row = Math.floor((Math.min(lat, 89.999999) + 90) / cellDeg);
const col = Math.floor((Math.min(lon, 179.999999) + 180) / cellDeg);
return `${row}:${col}`;
/** Stable key of the cell containing a position: its H3 index. */
export function gnssCellKey(lat, lon, resolution = GNSS_H3_RESOLUTION) {
return latLngToCell(lat, lon, resolution);
}
/**
* The ring to draw for a cell, as flat `[lon, lat, lon, lat, ...]` degrees.
* Longitudes are unwrapped to within 180° of the cell centre, so a cell
* across the antimeridian stays one narrow polygon (some longitudes then lie
* just outside ±180°) instead of spanning the globe. A cell around a pole
* keeps its full turn of longitudes; drawn on the globe it is still small.
*
* @param {{lat: number, lon: number, boundary: {lat: number, lon: number}[]}} cell
* @returns {number[]}
*/
export function gnssCellRing(cell) {
const ring = [];
for (const { lat, lon } of cell.boundary) {
let unwrapped = lon;
while (unwrapped - cell.lon > 180) unwrapped -= 360;
while (unwrapped - cell.lon < -180) unwrapped += 360;
ring.push(unwrapped, lat);
}
return ring;
}
/**
@@ -183,7 +203,7 @@ export function gnssCellKey(lat, lon, cellDeg = GNSS_CELL_DEG) {
* @param {Map<string, {cell: string, seenAt: number, degradedAt: number|null}>} store
* @param {ReturnType<typeof normalizeGnssAircraft>} rows
* @param {number} nowMs
* @param {{windowMs?: number, cellDeg?: number, observedAt?: number}} [options]
* @param {{windowMs?: number, resolution?: number, observedAt?: number}} [options]
* `observedAt` is the snapshot's observation time (defaults to `nowMs`;
* a future time is clamped to `nowMs`, a non-finite one adds nothing).
* @returns {Map} The same store, pruned to the window.
@@ -194,7 +214,7 @@ export function accumulateGnssObservations(
nowMs,
{
windowMs = GNSS_WINDOW_MS,
cellDeg = GNSS_CELL_DEG,
resolution = GNSS_H3_RESOLUTION,
observedAt = nowMs,
} = {},
) {
@@ -202,7 +222,7 @@ export function accumulateGnssObservations(
if (Number.isFinite(at) && nowMs - at <= windowMs) {
for (const row of rows || []) {
if (!Number.isFinite(row?.lat) || !Number.isFinite(row?.lon)) continue;
const cell = gnssCellKey(row.lat, row.lon, cellDeg);
const cell = gnssCellKey(row.lat, row.lon, resolution);
const key = `${row.hex}|${cell}`;
const previous = store.get(key);
const previousDegradedAt = previous?.degradedAt ?? null;
@@ -264,16 +284,16 @@ export function gnssIntegrityLevel(total, degraded) {
}
/**
* Aggregate the observation store into displayable cells. Expects a store
* already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`.
* Aggregate the observation store into displayable cells, one per H3 cell
* with at least one aircraft (gpsjam.org has no minimum count). Expects a
* store already pruned to the window by `accumulateGnssObservations` or
* `pruneGnssObservations`. `lat`/`lon` is the cell centre and `boundary` its
* vertices in order (six for a hexagon, five for a pentagon), with
* longitudes in -180..180; `gnssCellRing` gives the ring to draw.
*
* @returns {{id: string, south: number, west: number, north: number, east: number, lat: number, lon: number, aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
* @returns {{id: string, lat: number, lon: number, boundary: {lat: number, lon: number}[], aircraft: number, degraded: number, percentDegraded: number, level: 'low'|'medium'|'high', state: string, interpretation: string|null}[]}
*/
export function binGnssCells(
store,
{ cellDeg = GNSS_CELL_DEG, minAircraft = GNSS_MIN_AIRCRAFT } = {},
) {
export function binGnssCells(store) {
const tallies = new Map();
for (const { cell, degradedAt } of store.values()) {
const tally = tallies.get(cell) || { aircraft: 0, degraded: 0 };
@@ -283,22 +303,16 @@ export function binGnssCells(
}
const cells = [];
for (const [id, { aircraft, degraded }] of tallies) {
if (aircraft < minAircraft) continue;
const [row, col] = id.split(':').map(Number);
const south = row * cellDeg - 90;
const west = col * cellDeg - 180;
const [lat, lon] = cellToLatLng(id);
const { percent, level, state, interpretation } = gnssIntegrityLevel(
aircraft,
degraded,
);
cells.push({
id,
south,
west,
north: south + cellDeg,
east: west + cellDeg,
lat: south + cellDeg / 2,
lon: west + cellDeg / 2,
lat,
lon,
boundary: cellToBoundary(id).map(([lat, lon]) => ({ lat, lon })),
aircraft,
degraded,
percentDegraded: Math.round(percent * 10) / 10,
+145 -23
View File
@@ -1,12 +1,17 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getResolution, isPentagon, isValidCell } from 'h3-js';
import {
accumulateGnssObservations,
binGnssCells,
GNSS_CLASSIFIER,
GNSS_H3_RESOLUTION,
GNSS_HIGH_PERCENT,
GNSS_MEDIUM_PERCENT,
GNSS_PROVENANCE,
GNSS_WINDOW_MS,
gnssCellKey,
gnssCellRing,
gnssIntegrityLevel,
gnssProvenance,
normalizeGnssAircraft,
@@ -117,13 +122,87 @@ test('low NIC, low NACp or a readsb GPS-loss flag each mark an aircraft degraded
);
});
test('cell keys are stable half-degree bins, clamped at the poles and antimeridian', () => {
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.4, 19.6));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.6, 19.9));
assert.equal(gnssCellKey(90, 180), gnssCellKey(89.9, 179.9));
assert.equal(gnssCellKey(-90, -180), '0:0');
// Just south-west of the origin falls in the last cell before 0°, not cell 0.
assert.equal(gnssCellKey(-0.1, -0.1), '179:359');
test('cell keys are the H3 resolution-4 cells gpsjam.org uses', () => {
assert.equal(GNSS_H3_RESOLUTION, 4);
// Kraków: a known lat/lon lands in its known res-4 hexagon.
assert.equal(gnssCellKey(50.1, 19.9), '841e2e7ffffffff');
assert.equal(getResolution(gnssCellKey(50.1, 19.9)), 4);
// Nearby points share the hexagon; a point ~50 km north does not.
assert.equal(gnssCellKey(50.1, 19.9), gnssCellKey(50.12, 19.95));
assert.notEqual(gnssCellKey(50.1, 19.9), gnssCellKey(50.55, 19.9));
// The poles and both sides of the antimeridian still key valid cells.
for (const [lat, lon] of [
[90, 180],
[-90, -180],
[0, 179.99],
[0, -179.99],
]) {
const key = gnssCellKey(lat, lon);
assert.ok(isValidCell(key), `${lat},${lon} → ${key}`);
assert.equal(getResolution(key), 4);
}
});
const cellAt = (lat, lon) => {
const store = new Map();
accumulateGnssObservations(
store,
[{ hex: 'c1', lat, lon, degraded: false }],
0,
);
return binGnssCells(store)[0];
};
test('a cell carries its H3 centre and hexagon boundary', () => {
const cell = cellAt(50.1, 19.9);
assert.equal(cell.id, '841e2e7ffffffff');
assert.ok(Math.abs(cell.lat - 50.17184) < 1e-4);
assert.ok(Math.abs(cell.lon - 20.12566) < 1e-4);
assert.equal(cell.boundary.length, 6);
for (const { lat, lon } of cell.boundary) {
// Res-4 hexagons are about 45 km across.
assert.ok(Math.abs(lat - cell.lat) < 0.4, `lat ${lat}`);
assert.ok(Math.abs(lon - cell.lon) < 0.6, `lon ${lon}`);
}
for (const key of ['south', 'west', 'north', 'east'])
assert.equal(key in cell, false, `no rectangle field ${key}`);
assert.deepEqual(
gnssCellRing(cell),
cell.boundary.flatMap(({ lat, lon }) => [lon, lat]),
);
});
test('a cell across the antimeridian is drawn as one narrow polygon', () => {
for (const lon of [179.99, -179.99]) {
const cell = cellAt(0, lon);
const lons = cell.boundary.map((vertex) => vertex.lon);
assert.ok(
Math.max(...lons) - Math.min(...lons) > 300,
'the raw boundary straddles ±180°',
);
const drawn = gnssCellRing(cell).filter((_, index) => index % 2 === 0);
const width = Math.max(...drawn) - Math.min(...drawn);
assert.ok(width < 1, `drawn width ${width}° stays narrow`);
for (const value of drawn) assert.ok(Math.abs(value - cell.lon) < 1);
}
});
test('pentagon and polar cells give closed rings', () => {
// 8408001ffffffff is one of the twelve res-4 pentagons.
const pentagon = cellAt(64.7, 10.5);
assert.ok(isPentagon(pentagon.id));
assert.equal(pentagon.boundary.length, 5);
assert.equal(gnssCellRing(pentagon).length, 10);
for (const lat of [89.99, -89.99]) {
const polar = cellAt(lat, 10);
assert.ok(polar.boundary.length >= 6);
for (const vertex of polar.boundary)
assert.ok(Math.abs(vertex.lat) > 89 && Math.abs(vertex.lat) <= 90);
// Unwrapped longitudes stay within half a turn of the centre.
gnssCellRing(polar)
.filter((_, index) => index % 2 === 0)
.forEach((value) => assert.ok(Math.abs(value - polar.lon) <= 180));
}
});
test('integrity level follows the gpsjam.org published cell formula and bands', () => {
@@ -156,8 +235,8 @@ test('the primary state is a navigation-integrity anomaly; interference is only
store,
[
{ hex: 'h1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'h2', lat: 10.2, lon: 10.2, degraded: true },
{ hex: 'h3', lat: 10.3, lon: 10.3, degraded: false },
{ hex: 'h2', lat: 10.11, lon: 10.11, degraded: true },
{ hex: 'h3', lat: 10.12, lon: 10.12, degraded: false },
],
0,
);
@@ -182,14 +261,14 @@ test('provenance separates the GEV classifier from the gpsjam aggregation and th
id: 'gpsjam-cell-bands',
formula: '100 * max(0, bad - 1) / total',
bands: [2, 10],
grid: 'h3',
h3Resolution: 4,
source: 'https://gpsjam.org/faq',
definedBy: 'gpsjam.org',
});
assert.deepEqual(GNSS_PROVENANCE.window, {
minutes: 30,
scope: 'visited-view',
cellDeg: 0.5,
minAircraft: 3,
definedBy: 'GEV',
});
assert.equal(GNSS_PROVENANCE.state.id, 'navigation-integrity-anomaly');
@@ -225,14 +304,13 @@ test('observations count each aircraft once per cell and expire after the window
assert.equal(cell.aircraft, 3);
assert.equal(cell.degraded, 1);
assert.equal(cell.level, 'low');
assert.deepEqual(
[cell.south, cell.west, cell.north, cell.east],
[50, 20, 50.5, 20.5],
);
assert.equal(cell.id, gnssCellKey(50.2, 20.1));
accumulateGnssObservations(store, [], 1200, { windowMs: 1000 });
assert.equal(store.size, 1);
assert.deepEqual(binGnssCells(store), []);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1, 'only a1, seen inside the window, remains');
assert.equal(cell.degraded, 0);
});
const MIN = 60_000;
@@ -396,22 +474,66 @@ test('rows without finite coordinates never key a cell', () => {
assert.equal(store.size, 0);
});
test('cells below the minimum aircraft count are withheld', () => {
test('every cell with an aircraft is shown, as on gpsjam.org; only the bad − 1 discount guards small samples', () => {
const store = new Map();
accumulateGnssObservations(
store,
[
{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true },
{ hex: 'b2', lat: 10.2, lon: 10.2, degraded: true },
],
[{ hex: 'b1', lat: 10.1, lon: 10.1, degraded: true }],
0,
);
assert.deepEqual(binGnssCells(store), []);
const [cell] = binGnssCells(store, { minAircraft: 2 });
let [cell] = binGnssCells(store);
assert.equal(cell.aircraft, 1);
assert.equal(cell.level, 'low', 'one bad aircraft is discounted');
assert.equal(cell.percentDegraded, 0);
accumulateGnssObservations(
store,
[{ hex: 'b2', lat: 10.12, lon: 10.12, degraded: true }],
0,
);
[cell] = binGnssCells(store);
assert.equal(cell.aircraft, 2);
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 50);
});
test('the gpsjam bands are unchanged by the hex grid', () => {
assert.equal(GNSS_MEDIUM_PERCENT, 2);
assert.equal(GNSS_HIGH_PERCENT, 10);
// [total, bad] → level, at and either side of both band edges.
for (const [total, bad, level] of [
[100, 0, 'low'],
[100, 1, 'low'],
[100, 2, 'low'],
[100, 3, 'medium'],
[50, 2, 'medium'],
[100, 11, 'medium'],
[100, 12, 'high'],
[10, 2, 'medium'],
[10, 3, 'high'],
])
assert.equal(
gnssIntegrityLevel(total, bad).level,
level,
`${bad}/${total}`,
);
// Binned cells band the same way: 3 bad of 10 in one hexagon is high.
const store = new Map();
accumulateGnssObservations(
store,
Array.from({ length: 10 }, (_, index) => ({
hex: `h${index}`,
lat: 50.1,
lon: 19.9,
degraded: index < 3,
})),
0,
);
const [cell] = binGnssCells(store);
assert.equal(cell.id, '841e2e7ffffffff');
assert.equal(cell.level, 'high');
assert.equal(cell.percentDegraded, 20);
});
test('MLAT GPS-loss evidence uses the last good GNSS location and ignores MLAT NIC', () => {
const [row] = normalizeGnssAircraft({
ac: [
+21 -6
View File
@@ -149,6 +149,9 @@ function restoreCameraView(viewer, view, landedView) {
camera.setView(view);
}
/** The longest name a timeline mark carries, as in the mission index. */
const MARK_LABEL_LENGTH = 27;
export function createLifecycle({
state: layerState,
services,
@@ -158,18 +161,30 @@ export function createLifecycle({
const { holdContinuousRender, releaseContinuousRender } = services.render;
let hover = null;
// While on, the launches loaded span the time from the first to the last,
// each one a mark. Registered once; off, the layer has no time to show, and
// each step tells the clock once it has settled.
// each one a mark labelled with its mission's name (the launch's where it
// has none), cut short and in capitals as the mission index shows names.
// Registered once; off, the layer has no time to show, and each step tells
// the clock once it has settled.
worldClock.register({
id: 'rocket-launches',
coverage: () => {
if (!layerState._enabled) return null;
const marks = layerState._launches
.map((launch) => Date.parse(launch.launchTime))
.filter(Number.isFinite)
.sort((a, b) => a - b);
.map((launch) => ({
time: Date.parse(launch.launchTime),
label: parts.overlays
.shortMissionLabel(
launch.missionName || launch.name,
MARK_LABEL_LENGTH,
)
.toUpperCase(),
...(launch.id != null ? { id: String(launch.id) } : {}),
kind: 'launch',
}))
.filter(({ time }) => Number.isFinite(time))
.sort((a, b) => a.time - b.time);
if (!marks.length) return null;
return { start: marks[0], end: marks.at(-1), marks };
return { start: marks[0].time, end: marks.at(-1).time, marks };
},
});
-1
View File
@@ -700,7 +700,6 @@ export function createLocalAdsbLayer({
if (viewer.scene?.primitives) {
models = createLocalAdsbModels({
viewer,
color,
resolveAsset,
groundSnap: services.groundSnap?.createGroundSnap?.() || null,
...(loadModel ? { loadModel } : {}),
+4 -7
View File
@@ -503,7 +503,7 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o
assert.equal(queries.length, 2, 'each key is asked for once');
});
test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t) => {
test('the DISPLAY 3D toggle gives local aircraft their fleet models in their mesh colours', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const loads = [];
@@ -548,13 +548,10 @@ test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t
assert.equal(model.scale, spec.scale, 'drawn life size');
assert.equal(model.id, 'local-adsb:a0b702');
assert.ok(
Cesium.Color.equals(
model.color,
Cesium.Color.fromCssColorString('#ff4fd8'),
),
Cesium.Color.equals(model.color, Cesium.Color.WHITE),
'the mesh draws its own colours',
);
assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.MIX);
assert.equal(model.colorBlendAmount, 0.94);
assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.HIGHLIGHT);
assert.equal(model.show, true);
const heli = sources[0].entities.getById('local-adsb:a0b702');
assert.equal(
+9 -8
View File
@@ -16,12 +16,16 @@ import {
MODEL_PROX_ADD_M,
MODEL_PROX_KEEP_M,
} from '../flights/policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from '../../data/aircraftModelLighting.js';
const specOf = (marker) =>
aircraftLayerModelSpec({
typeCode: marker?.typeCode,
category: marker?.category,
callsign: marker?.record?.callsign,
});
/**
@@ -30,15 +34,14 @@ const specOf = (marker) =>
* Mirrors the public Flights fleet: models only below the altitude ceiling,
* the same proximity/all caps and add/keep radii, the same visible-first
* eligibility (`selectModelEligible`), the same fleet model per type, life
* size (`aircraftLayerModelSpec`) and the same tint path (a MIX colour blend, here
* magenta, as Flights tints military amber). Each model owns its matrix. A
* size (`aircraftLayerModelSpec`) and the same colours: the mesh's own
* (`aircraftModelBlend`). Each model owns its matrix. A
* billboard stays the visual until its model is loaded AND placed; a grounded
* aircraft's model rides the one-shot ground snap plus the class belly
* offset, and without a resolved ground it stays a billboard. Every fleet
* model loads once, up front, when the layer starts (`loadFleetModelSet`).
* @param {object} options
* @param {object} options.viewer Cesium viewer.
* @param {Cesium.Color} options.color Model tint.
* @param {(url: string) => string} options.resolveAsset
* @param {object|null} [options.groundSnap] `createGroundSnap()` instance.
* @param {(options: object) => Promise<object>} [options.loadModel]
@@ -46,7 +49,6 @@ const specOf = (marker) =>
*/
export function createLocalAdsbModels({
viewer,
color,
resolveAsset,
groundSnap = null,
loadModel = (options) => Cesium.Model.fromGltfAsync(options),
@@ -103,9 +105,8 @@ export function createLocalAdsbModels({
environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
minimumPixelSize: MODEL_MIN_PX,
scale: spec.scale,
color,
colorBlendMode: Cesium.ColorBlendMode.MIX,
colorBlendAmount: spec.blendAmount,
color: Cesium.Color.WHITE,
...aircraftModelBlend(false),
id,
},
{ resolveAsset, load: loadModel },
+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();
+1
View File
@@ -31,6 +31,7 @@ export function createMilitaryFlightLayer({
parts.clockFollow = createClockFollow(context);
const applySnapshot = createMilitarySnapshotRenderer({
flightState,
placement: services.placement ?? null,
records: flightState.records,
groundFloor: services.groundFloor,
meshFloor: services.meshFloor,
+9
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { loadFleetModelSet } from '../../data/fleetModels.js';
import { forgetPlacedAircraft } from '../flights/placed.js';
export function createLifecycle({
flightState,
@@ -66,6 +67,10 @@ export function createLifecycle({
flightState._cullPositions.clear();
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();
@@ -264,6 +269,10 @@ export function createLifecycle({
flightState._cullPositions.clear();
flightState._detectionObjects.clear();
flightState.records.data.clear();
forgetPlacedAircraft(
services.placement,
flightState._positionHistory.keys(),
);
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
+31 -1
View File
@@ -1,4 +1,8 @@
import * as Cesium from 'cesium';
import {
historyBracketIndex,
historyUnseenAt,
} from '../../data/timelineHistory.js';
import { julianAt } from '../../time/julian.js';
import {
lerpAngleDeg,
@@ -15,6 +19,7 @@ import {
COAST_MAX_SPEED_MPS,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import { placeLiveAircraft } from '../flights/placed.js';
import {
modelVisualAnchor,
modelAnchorWorld,
@@ -60,6 +65,7 @@ export function createMotion({
*/
function _deadReckon(icao24, result) {
flightState._drUnseen = false;
const history = flightState._positionHistory.get(icao24);
const info = flightState.records.data.get(icao24);
if (!history || history.length === 0) {
@@ -70,6 +76,19 @@ export function createMotion({
}
const out = result || new Cesium.Cartesian3();
// 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 one poll interval behind real time so we interpolate between
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
const renderTime = Cesium.JulianDate.addSeconds(
@@ -79,7 +98,15 @@ export function createMotion({
);
// Bracketing pair: interpolate — no extrapolation error, no snap-back.
for (let i = history.length - 1; i >= 1; i--) {
// The pair around the render time (and the one before it, for a fix at
// exactly that time), found by halving: a contact following the clock
// keeps a long history.
for (
let i = historyBracketIndex(history, renderTime),
stop = Math.max(1, i - 1);
i >= stop;
i--
) {
const a = history[i - 1];
const b = history[i];
if (
@@ -133,6 +160,9 @@ export function createMotion({
// the bracketing interpolation above with NO freeze and NO backward snap. (Holding
// the oldest fix froze the icon until enough history accrued, then jumped.)
const oldest = history[0];
// Following the clock, a time well before its first fix is before it
// was there: the fleet pass hides it.
flightState._drUnseen = historyUnseenAt(history, renderTime);
const lookbackSec = Cesium.JulianDate.secondsDifference(
oldest.time,
renderTime,
-4
View File
@@ -107,10 +107,6 @@ export const MODEL_ALL_KEEP_M = 450000;
export const MODEL_HEADING_OFFSET_DEG = 180;
// every fleet model is nose -X: opposite Cesium heading 0
// Preserve the layer's amber identity while reducing the models' own colours
// to a weak diffuse hint, matching civilian launch presentation.
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
+15 -1
View File
@@ -1,5 +1,6 @@
import { pickRenderAltitudeM } from '../../data/renderAltitude.js';
import { stickyText, stickyNumber } from '../../data/aircraftMeta.js';
import { courseFromFixes } from '../../data/courseFromFixes.js';
import { classifyAircraft } from '../../data/aircraftClass.js';
import { aircraftEmergency } from '../../data/aircraftEmergency.js';
import {
@@ -175,6 +176,12 @@ export class MilitaryFlightRecords {
// last-known-good (bounded by the layer's eviction, which deletes the entry).
const stickyType = stickyText(type, prevMeta?.type);
const fixEpochMs = aircraft.positionTimeMs ?? observedAtMs;
const course = courseFromFixes(prevMeta?.courseAnchor, {
lat,
lon,
ms: fixEpochMs,
speedMps: aircraft.speedMps,
});
const meta = {
sourceReference: aircraft.reference,
observedReceiptMs: this.now(),
@@ -206,7 +213,14 @@ export class MilitaryFlightRecords {
onGround ? 0 : prevMeta?.speedMps,
0,
),
track: stickyNumber(aircraft.courseDeg, prevMeta?.track, 0),
// With no reported track or true heading, a moving contact faces the
// way its fixes went (src/data/courseFromFixes.js); else the last one.
track: stickyNumber(
aircraft.courseDeg,
course.courseDeg ?? prevMeta?.track,
0,
),
courseAnchor: course.anchor,
// Analyst seam (additive): sticky like the other kinematics.
verticalRateMps: stickyNumber(
verticalRateMps,
+23
View File
@@ -269,3 +269,26 @@ test('a repeated military fix time marks the contact as not updated; removal is
records.forget('aaa001');
assert.equal(records.fixRepeated.has('aaa001'), false);
});
test('a military contact reported with no course faces the way its newer fixes went', () => {
const records = store();
const T = 1700000000000;
const taxi = (latitude, seconds) =>
records.receive(
observation({
latitude,
onGround: true,
baroAltitudeM: null,
courseDeg: null,
speedMps: 8,
positionTimeMs: T + seconds * 1000,
}),
context({ observedAtMs: T + seconds * 1000 + 500 }),
);
assert.equal(taxi(39, 0).meta.track, 0);
assert.ok(Math.abs(taxi(38.9995, 5).meta.track - 180) < 0.1);
assert.ok(
Math.abs(taxi(39.002, 3).meta.track - 180) < 0.1,
'an older fix gives no course',
);
});
+19 -14
View File
@@ -34,7 +34,6 @@ import {
MODEL_PROX_KEEP_M,
IR_RELOAD_BATCH,
MODEL_MIN_PX,
MODEL_COLOR_BLEND_AMOUNT,
TRACKED_MODEL_MIN_PX,
TRACKED_MODEL_MAX_PX,
FLEET_DR_INTERVAL_MS,
@@ -43,7 +42,10 @@ import {
COURSE_MAX_DPS,
STALE_ALPHA,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from '../../data/aircraftModelLighting.js';
export function createRendering({
flightState,
@@ -81,7 +83,6 @@ export function createRendering({
const base = aircraftLayerModelSpec(meta);
spec = Object.freeze({
...base,
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
});
// Not cached before the model set loads: the answer changes once it has.
@@ -152,11 +153,15 @@ export function createRendering({
const _iconKind = (icao24, klass) =>
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
/** Model tint, mirroring the billboard color rules (amber instead of cyan/white). */
/** Model colour: the mesh's own (white), tinted amber while tracked and red
* while broadcasting an emergency. */
function _modelColor(icao24) {
if (icao24 === flightState._trackedIcao) return TRACKED_ICON_COLOR;
return _fleetBillboardColor(icao24);
const info = flightState.records.data.get(icao24);
return isEmergency(info?.emergency)
? EMERGENCY_ICON_COLOR
: Cesium.Color.WHITE;
}
/** Fleet (untracked) tint: red while the latest poll broadcast an emergency,
@@ -443,9 +448,7 @@ export function createRendering({
minimumPixelSize: MODEL_MIN_PX,
scale: spec.scale,
color: flightState._irBoost ? Cesium.Color.WHITE : _modelColor(icao24),
colorBlendMode: Cesium.ColorBlendMode.MIX,
// near self-illuminated tint so planes read uniform near AND far; IR boost → flat UNLIT white (hot)
colorBlendAmount: flightState._irBoost ? 1.0 : MODEL_COLOR_BLEND_AMOUNT,
...aircraftModelBlend(flightState._irBoost),
customShader: flightState._irBoost
? flightState._IR_UNLIT_SHADER
: undefined,
@@ -662,9 +665,7 @@ export function createRendering({
minimumPixelSize: TRACKED_MODEL_MIN_PX,
scale: trackedSpec.scale,
color: flightState._irBoost ? Cesium.Color.WHITE : TRACKED_ICON_COLOR,
colorBlendMode: Cesium.ColorBlendMode.MIX,
// near self-illuminated tint so planes read uniform near AND far; IR boost → flat UNLIT white (hot)
colorBlendAmount: flightState._irBoost ? 1.0 : MODEL_COLOR_BLEND_AMOUNT,
...aircraftModelBlend(flightState._irBoost),
customShader: flightState._irBoost
? flightState._IR_UNLIT_SHADER
: undefined,
@@ -916,6 +917,7 @@ export function createRendering({
if (icao24 === flightState._trackedIcao) continue; // tracked entity owns its own motion
const dr = parts.motion._deadReckon(icao24, flightState._scratchFleetPos);
const unseen = flightState._drUnseen;
// Gate the write — assigning Billboard.position dirties the whole
// collection's vertex buffer, so skip sub-meter moves.
if (dr && Cesium.Cartesian3.distanceSquared(dr, bb.position) > 1.0) {
@@ -925,9 +927,12 @@ export function createRendering({
// Round 6: occlusion-test a LIFTED point for contacts at/below the
// ellipsoid (mirror of flights.js — sub-ellipsoid points near the limb
// read "beyond the horizon" and would hide low contacts awaiting floors).
const beyondHorizon = !occluder.isPointVisible(
flightState.records.data.get(icao24)?.cullPosition || bb.position,
);
// A contact not there yet at the time drawn is hidden as one beyond it.
const beyondHorizon =
unseen ||
!occluder.isPointVisible(
flightState.records.data.get(icao24)?.cullPosition || bb.position,
);
// A billboard flipping INTO view (horizon reveal while the camera idles)
// gets its rotation refreshed THIS tick even without a pose change —
// otherwise it reappears wearing its stale (often creation-north) nose for
+117 -67
View File
@@ -8,6 +8,11 @@ import {
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import {
historyAfterTrail,
liftGroundedHistory,
mergeAircraftTimelineFixes,
} from '../../data/timelineHistory.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import {
BILLBOARD_SCALE,
@@ -15,10 +20,12 @@ import {
TRACKED_ICON_COLOR,
followsClock,
} from './policy.js';
import { observeLiveAircraft } from '../flights/placed.js';
/** Apply military record changes to Cesium resources and existing follow operations. */
export function createMilitarySnapshotRenderer({
flightState,
placement = null,
records,
groundFloor,
meshFloor,
@@ -73,75 +80,111 @@ export function createMilitarySnapshotRenderer({
);
const isTracked = icao24 === flightState._trackedIcao;
// 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
// append when the fix actually advances, so stale repeats don't
// create zero-dt segments.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.speedMps,
track: meta.track,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
// Trail accumulation is separate from the 5-fix DR history (PRD F2)
// so the visible trail keeps growing while tracked. Round 2
// (owner): ground traffic appends too — taxi history stays live
// after touchdown; _appendTrailFix floors grounded positions at
// the surface so the ground leg drapes instead of diving.
// Following the clock, a record may carry its own track around the
// time: the contact is placed on it, so the clock can move within it,
// back as well as on, without another snapshot.
const timelineHistory = followsClock(flightState)
? mergeAircraftTimelineFixes(
flightState._positionHistory.get(icao24),
aircraft,
meta,
meta.speedMps,
snapshot.observedAtMs ?? fixEpochMs,
)
: null;
// A host-supplied placement, if any, is told every fix as taken.
observeLiveAircraft(
flightState,
placement,
icao24,
fixEpochMs,
meta,
meta.speedMps,
meta.track,
);
if (timelineHistory) {
if (isTracked)
tracking._appendTrailFix(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
for (const entry of historyAfterTrail(
timelineHistory,
flightState._trailFixes,
snapshot.observedAtMs ?? fixEpochMs,
))
tracking._appendTrailFix(entry.position.clone(), entry.epochMs, {
nullAltitude: entry.inventedHeight,
});
flightState._positionHistory.set(icao24, timelineHistory);
meta.turnRateDps = 0;
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
// 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
// append when the fix actually advances, so stale repeats don't
// create zero-dt segments.
const fixTime = Cesium.JulianDate.fromDate(new Date(fixEpochMs));
if (!flightState._positionHistory.has(icao24)) {
flightState._positionHistory.set(icao24, []);
}
// A forward synthetic fix follows the stale rules (none while the
// contact holds at its report, a coast capped from the real report,
// never below the ground) and is a motion aid, never a trail report.
const kinematicsChanged =
newest.velocity !== meta.speedMps || newest.track !== meta.track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
const history = flightState._positionHistory.get(icao24);
const newest = history[history.length - 1];
if (!newest || Cesium.JulianDate.greaterThan(fixTime, newest.time)) {
// Per-fix kinematics: the fix's own velocity/track ride along so the
// extrapolation paths use the values that BELONG to the fix they
// extend, not whatever the latest poll reported.
history.push({
time: fixTime,
epochMs: fixEpochMs,
position: position.clone(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
// Drawn at an invented height: a trail seeded from history keeps no
// position for it.
inventedHeight: meta.renderAltitudeInvented === true,
});
if (history.length > POSITION_HISTORY_LIMIT) {
history.shift();
}
// Turn rate from the fix-track history — computed once per new fix
// (≤5 samples), consumed by the extrapolation paths at tick rate.
meta.turnRateDps = turnRateFromFixHistory(history);
// Trail accumulation is separate from the 5-fix DR history (PRD F2)
// so the visible trail keeps growing while tracked. Round 2
// (owner): ground traffic appends too — taxi history stays live
// after touchdown; _appendTrailFix floors grounded positions at
// the surface so the ground leg drapes instead of diving.
if (isTracked)
tracking._appendTrailFix(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
liftRepeatedGroundFix(newest, position, meta.onGround);
}
// A forward synthetic fix follows the stale rules (none while the
// contact holds at its report, a coast capped from the real report,
// never below the ground) and is a motion aid, never a trail report.
const kinematicsChanged =
newest.velocity !== meta.speedMps || newest.track !== meta.track;
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
}
}
}
}
@@ -182,6 +225,7 @@ export function createMilitarySnapshotRenderer({
// it ahead until the next fleet tick snapped it back.
const displayed =
motion._deadReckon(icao24, new Cesium.Cartesian3()) || position;
const unseenAtStart = flightState._drUnseen;
const bb = flightState._billboardCollection.add({
position: displayed,
image: aircraftIcon(rendering._iconKind(icao24, meta.klass)),
@@ -204,7 +248,9 @@ export function createMilitarySnapshotRenderer({
// close (_groundDepthDistance).
disableDepthTestDistance: rendering._groundDepthDistance(),
id: icao24,
show: !isTracked, // hidden if currently tracked (entity replaces it)
// Hidden if currently tracked (entity replaces it), or not there yet
// at the time drawn (see historyUnseenAt).
show: !isTracked && !unseenAtStart,
});
flightState._billboards.set(icao24, bb);
rendering._applyFleetBillboardPresentation(icao24, bb);
@@ -246,6 +292,7 @@ export function createMilitarySnapshotRenderer({
info.renderAltitudeM >= floor - 1
)
continue;
const drawnM = info.renderAltitudeM;
info.renderAltitudeM = lifted;
flightState._cullPositions.delete(icao24);
const liftedPos = Cesium.Cartesian3.fromDegrees(
@@ -253,10 +300,12 @@ export function createMilitarySnapshotRenderer({
info.rawLat,
lifted,
);
const hist = flightState._positionHistory.get(icao24);
const newest = hist?.[hist.length - 1];
if (newest)
newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position);
liftGroundedHistory(
flightState._positionHistory.get(icao24),
liftedPos,
drawnM,
lifted,
);
const bbStale = flightState._billboards.get(icao24);
if (bbStale) bbStale.position = liftedPos;
}
@@ -324,6 +373,7 @@ export function createMilitarySnapshotRenderer({
flightState._billboards.delete(icao24);
rendering._releaseModel(icao24); // aged-out aircraft: drop its 3D model (no orphan / cap leak)
records.forget(icao24);
placement?.forget(icao24);
flightState._cullPositions.delete(icao24);
flightState._positionHistory.delete(icao24);
flightState._displayCourse.delete(icao24);
+5
View File
@@ -282,6 +282,11 @@ export function createFlightState({ source, services }) {
flightState._drCourseHold = false;
/** Set by `_deadReckon`: following the clock, the time drawn is well
* before the contact's first fix, so the fleet pass does not draw it. */
flightState._drUnseen = false;
/** Frame-cached course for the tracked aircraft (sibling of _cachedDRPosition). */
flightState._cachedDRCourse = null;
+340
View File
@@ -0,0 +1,340 @@
import { pointAtS } from '../../data/railPaths.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
import { displayMotion } from '../transit/movement.js';
/** Each line's read-only copy for a snapshot's `path.line` (lineOf). */
const lines = new WeakMap();
/**
* A line as a snapshot hands it out: a frozen copy of the layer's path, its
* number arrays frozen arrays, built once per line. `pointAtS` and
* `projectOnPath` read it as they read the path, and nothing written to it
* reaches the layer.
*/
function lineOf(path) {
let line = lines.get(path);
if (!line) {
const copy = {};
for (const [name, value] of Object.entries(path))
copy[name] = ArrayBuffer.isView(value)
? Object.freeze(Array.from(value))
: value;
line = Object.freeze(copy);
lines.set(path, line);
}
return line;
}
const NO_STOPS = Object.freeze([]);
/** Each stops list's frozen copy for a snapshot's `stops` (stopsOf). */
const stopLists = new WeakMap();
/** Whether `copy` still holds each of `list`'s stops, field by field. */
function sameStops(copy, list) {
if (copy.length !== list.length) return false;
for (let i = 0; i < list.length; i++) {
const stop = list[i];
const kept = copy[i];
if (
!stop ||
typeof stop !== 'object' ||
!kept ||
typeof kept !== 'object'
) {
if (!Object.is(stop, kept)) return false;
continue;
}
const names = Object.keys(stop);
if (names.length !== Object.keys(kept).length) return false;
for (const name of names)
if (!Object.is(stop[name], kept[name])) return false;
}
return true;
}
/**
* A trip's stops as a snapshot hands them out: a frozen array of frozen
* copies, kept per list the stops provider returns while that list still
* holds the same stops, so a provider that updates its list in place is
* copied again.
*/
function stopsOf(list) {
if (!Array.isArray(list)) return NO_STOPS;
let stops = stopLists.get(list);
if (!stops || !sameStops(stops, list)) {
stops = Object.freeze(
list.map((stop) =>
stop && typeof stop === 'object' ? Object.freeze({ ...stop }) : stop,
),
);
stopLists.set(list, stops);
}
return stops;
}
/**
* `previous` when it holds each of `next`'s values, else a frozen copy of
* `next`: a part of a snapshot that did not change is the one read before.
* `next` is a draft, filled again on every read.
*/
function reuse(previous, next) {
if (!previous) return Object.freeze({ ...next });
for (const name in next)
if (!Object.is(previous[name], next[name]))
return Object.freeze({ ...next });
return previous;
}
/**
* Read access to one train, and a hold on it for a first-person view.
*
* `getSelectedTrain()` and `getCockpitSubject()` describe the selected train
* and the held one as a frozen snapshot, read again on each call: where it is
* along its line, how fast it moves and how that is known, and its stops. A
* call while nothing in it changed returns the snapshot it returned before,
* and a part that did not change (its feed, its line, its stops) is the same
* object in the next one, so a view can read it on every frame. `path.line`
* is a frozen copy of the train's line for `pointAtS` and `projectOnPath`.
* `setCockpitSubject(key)` holds a train: its marker, 3D model, card and
* selected line are hidden, it stays selected (so its stops stay fresh and its feed stays
* polled at any distance) and clicks and Escape no longer change the
* selection. A held train keeps moving, hidden, and keeps the selection when
* its category is turned off, and is the copy of its train drawn though
* another feed's copy would outrank it (dedupe.js). Released, it is a train
* like any other: one in a category turned off is deselected and stops, and
* a better copy takes over at the next poll. The hold ends with
* `setCockpitSubject(null)`, and on its own when the train is removed or the
* layer is turned off. A train removed while held leaves its feed polled
* until the next `setCockpitSubject` call, so a view that waits for it holds
* it again if the feed lists it again.
* `focusTrain(key)` selects a train and hands it the camera, as a click does.
* A snapshot's `selectedAtMs` is when the user last selected the selected
* train (a click, or `focusTrain`), even again, for a view's entry to tell a
* re-selection. It is null for any other train, after a deselection, and for
* a train selected only by a hold: a hold is not a user's selection.
*
* @param {object} context The layer's state, parts, services and timetable.
* @returns {{methods: object}}
*/
export function createRailCockpitSubject({
state,
parts,
services,
timetable,
}) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
const scratch = {};
/** Each train's last snapshot, returned again while nothing in it changed. */
const views = new WeakMap();
/** The drafts trainView fills on every read (reuse). */
const draft = {
view: {},
feed: {},
position: {},
path: {},
motion: {},
provenance: {},
};
/** The catalog's public entry for a feed, else the registry's. */
function feedOf(feedId, previous) {
const listed = state._catalog?.find((feed) => feed.id === feedId);
const feed = listed ?? getRegisteredRailFeed(feedId);
if (!feed) return null;
const next = draft.feed;
next.id = feed.id;
next.name = feed.name ?? null;
next.operator = feed.operator ?? null;
next.region = feed.region ?? null;
next.positions = listed?.positions ?? feed.positions ?? 'gps';
next.tripUpdates =
typeof listed?.tripUpdates === 'boolean'
? listed.tripUpdates
: typeof feed.tripUpdatesUrl === 'string';
next.attribution = feed.attribution ?? null;
next.license = feed.license ?? null;
next.licenseUrl = feed.licenseUrl ?? null;
return reuse(previous, next);
}
/** The route's short (else long) name in the feed's timetable, or null. */
function routeNameOf(entry) {
const routeId = entry.record?.routeId;
if (!routeId) return null;
const schedule = timetable?.scheduleFor?.(entry.feedId);
const route = schedule?.routes?.[routeId];
const name = route?.short || route?.long;
return typeof name === 'string' && name ? name : null;
}
/**
* Which way the train runs along its shape: as its binding learnt it from
* successive reports, else from its drawn course against the line's
* bearing there; 0 while neither tells.
*/
function directionOf(entry) {
const binding = entry.path;
if (binding.direction === 1 || binding.direction === -1)
return binding.direction;
const course = finiteOrNull(entry.courseDeg);
const point = pointAtS(binding.path, binding.drawS, scratch);
if (course === null || !Number.isFinite(point?.bearingDeg)) return 0;
const turn = Math.abs(((course - point.bearingDeg + 540) % 360) - 180);
return turn > 90 ? -1 : 1;
}
/** The train as a frozen snapshot (see the module comment), or null. */
function trainView(entry) {
if (!entry?.record) return null;
const previous = views.get(entry);
const record = entry.record;
const sample = entry.sample ?? null;
const drawn = entry.drawnHeight ?? null;
const binding = entry.path ?? null;
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const trip = state._selectedKey === entry.key ? state._trip : null;
const status = state._feedStatus.get(entry.feedId);
const position = draft.position;
position.latitude =
finiteOrNull(drawn?.lat) ?? finiteOrNull(sample?.lat) ?? record.lat;
position.longitude =
finiteOrNull(drawn?.lon) ?? finiteOrNull(sample?.lon) ?? record.lon;
position.railHeightM = Number.isFinite(drawn?.h) ? drawn.h - liftM : null;
position.heightQuality = Number.isFinite(drawn?.q) ? drawn.q : 0;
position.atMs = finiteOrNull(drawn?.at);
let path = null;
if (binding && binding.path) {
path = draft.path;
path.shapeIndex = binding.shapeIndex;
path.s = binding.drawS;
path.direction = directionOf(entry);
path.lengthM = binding.path.length;
path.via = binding.via;
path.builtAt = state._pathPacks.get(entry.feedId)?.pack?.builtAt ?? null;
path.line = lineOf(binding.path);
}
const motion = draft.motion;
motion.reportedSpeedMps = reported;
motion.derivedSpeedMps = derived;
motion.speedSource =
reported !== null ? 'reported' : derived !== null ? 'derived' : null;
motion.courseDeg = finiteOrNull(entry.courseDeg);
motion.phase = sample?.phase ?? null;
motion.word = displayMotion(entry, Date.now()).word;
motion.reportAgeMs = finiteOrNull(sample?.latestReportAgeMs);
motion.shownBehindMs = finiteOrNull(sample?.actualDelayMs);
motion.feedStale = status?.stale === true;
const provenance = draft.provenance;
provenance.positionSource = record.positionSource ?? 'gps';
provenance.timestampSource = record.timestampSource ?? null;
const view = draft.view;
view.key = entry.key;
view.feedId = entry.feedId;
view.selectedAtMs =
state._selectedKey === entry.key ? state._selectedAtMs : null;
view.id = String(record.id ?? '');
view.tripId = record.tripId || null;
view.routeId = record.routeId || null;
view.routeName = routeNameOf(entry);
view.label = record.label || null;
view.trainNumber = record.trainNumber || null;
view.headsign = trip?.headsign || null;
view.category = entry.category ?? null;
view.mode = entry.railMode ?? null;
view.feed = feedOf(entry.feedId, previous?.feed);
view.position = reuse(previous?.position, position);
view.path = path && reuse(previous?.path, path);
view.motion = reuse(previous?.motion, motion);
view.provenance = reuse(previous?.provenance, provenance);
view.stops = stopsOf(trip?.stops);
view.match = trip?.match ?? null;
const snapshot = reuse(previous, view);
views.set(entry, snapshot);
return snapshot;
}
/** A train's marker and playback again, after a hold on it began or ended. */
function replay(entry) {
parts.rendering.paint(entry);
parts.rendering.schedulePlayback(entry);
parts.rendering.syncRenderHold();
}
const methods = {
/** The selected train (see createRailCockpitSubject), or null. */
getSelectedTrain() {
return trainView(state._trains.get(state._selectedKey));
},
/** The held train, or null when none is held. */
getCockpitSubject() {
return trainView(state._trains.get(state._cockpitSubjectKey));
},
/**
* Hold the train `key` for a first-person view, or release the hold with
* null. A train it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a key the layer does not list. A listed
* train is held even when its category is off or another feed's copy
* is drawn: the held copy is then the one drawn. Releasing returns true.
*/
setCockpitSubject(key) {
const previous = state._trains.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
if (previous) {
// Its category turned off meanwhile: deselected, as the toggle
// does to any other train (controls.js).
if (
previous.key === state._selectedKey &&
state._categories[previous.category] === false
)
parts.selection.clearSelection();
replay(previous);
}
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
}
const entry = state._trains.get(key);
if (!entry) return false;
if (state._selectedKey !== key) {
parts.selection.selectTrain(key);
// A hold is not a selection the user made (selectedAtMs).
state._selectedAtMs = null;
}
state._cockpitSubjectKey = key;
state._cockpitLostFeedId = null;
// Another feed's copy drew it: the held copy is drawn now (dedupe.js).
if (entry.duplicate === true) parts.ingestion.duplicates?.refresh();
if (previous && previous !== entry) replay(previous);
replay(entry);
parts.selection.refreshSelectedCard(true);
parts.routes.applyHold?.();
return true;
},
/**
* Select the train `key` and hand it the camera, as a click on it does.
* @param {string} key
* @returns {boolean} False for a train the layer does not show: gone, in
* a category turned off, or a copy another feed draws (dedupe.js).
*/
focusTrain(key) {
const entry = state._trains.get(key);
if (!entry || !parts.rendering.categoryShown(entry)) return false;
parts.selection.selectAndFocusTrain(key);
return true;
},
};
return { methods, trainView };
}
+533
View File
@@ -0,0 +1,533 @@
// The Rail layer's read API for a first-person view: the selected or held
// train as a snapshot (where it is along its line and which way it runs, its
// speed and how that is known, its feed's credit, its stops), and a hold that
// hides its marker and card, keeps it selected and ends when it goes.
import test from 'node:test';
import assert from 'node:assert/strict';
import {
RAIL_POLL_MS,
STOP_REFRESH_MS,
railTrainFollowable,
railTrainKey,
} from './policy.js';
import {
BOSTON,
railLayerHarness as harness,
railTrain as train,
} from '../../testSupport/railLayerHarness.mjs';
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;
const KX = M_PER_DEG * Math.cos((LAT * Math.PI) / 180);
const LON0 = -71.08;
/** A flat [lat, lon, ...] line due east from LON0, one vertex per 100 m. */
function eastLine(lengthM) {
const out = [];
for (let d = 0; d <= lengthM; d += 100) out.push(LAT, LON0 + d / KX);
return out;
}
const PACK = Object.freeze({
version: 1,
feedId: 'mbta-rail',
builtAt: '2026-09-09T00:00:00.000Z',
shapes: [eastLine(6000)],
dist: [[]],
shapeSources: ['operator'],
trips: { 'trip-T1': 0, 'trip-T2': 0 },
routes: { R1: [0] },
});
/** Two trains on the line, T1 running east and T2 west, a step a poll. */
async function onTheLine(t, options = {}) {
const app = harness(t, {
paths: { 'mbta-rail': PACK },
at: BOSTON,
...options,
});
let step = 0;
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + (1000 + step * 150) / KX, { speedMps: 15 }),
train('T2', LAT, LON0 + (5000 - step * 150) / KX),
]);
await app.enable();
for (let i = 0; i < 4; i += 1) {
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
}
return app;
}
const T1 = railTrainKey('mbta-rail', 'T1');
const T2 = railTrainKey('mbta-rail', 'T2');
test('the selected train reads as a snapshot of its place, motion and sources', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.getSelectedTrain(), null, 'nothing selected');
app.parts().selection.selectTrain(T1);
const view = app.layer.getSelectedTrain();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, T1);
assert.equal(view.feedId, 'mbta-rail');
assert.equal(view.id, 'T1');
assert.equal(view.tripId, 'trip-T1');
assert.equal(view.routeId, 'R1');
assert.equal(view.category, 'regional');
assert.equal(view.mode, 'rail');
const listed = publicRailCatalog().find((feed) => feed.id === 'mbta-rail');
assert.equal(view.feed.attribution, listed.attribution);
assert.equal(view.feed.license, listed.license);
assert.equal(view.feed.licenseUrl, listed.licenseUrl);
assert.equal(view.feed.positions, 'gps');
assert.equal(view.path.shapeIndex, 0);
assert.equal(view.path.builtAt, PACK.builtAt);
assert.equal(view.path.via, 'trip');
assert.ok(Math.abs(view.path.lengthM - 6000) < 1);
assert.ok(view.path.s > 1000 && view.path.s < 2000, `s ${view.path.s}`);
assert.equal(view.path.direction, 1, 'runs along the shape');
assert.equal(typeof view.path.line.length, 'number');
assert.equal(view.motion.reportedSpeedMps, 15);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.equal(view.provenance.timestampSource, 'vehicle');
const drawn = app.entry(T1).drawnHeight;
assert.equal(view.position.railHeightM, drawn.h - 1.5);
assert.ok(Number.isFinite(view.position.latitude));
assert.ok(Array.isArray(view.stops));
app.parts().selection.selectTrain(T2);
const west = app.layer.getSelectedTrain();
assert.equal(west.path.direction, -1, 'runs against the shape');
assert.equal(west.motion.reportedSpeedMps, null);
assert.equal(
west.motion.speedSource,
west.motion.derivedSpeedMps === null ? null : 'derived',
);
});
/** A trip's stops as a stops provider lists them. */
const stopList = (...names) =>
names.map((name, i) => ({
stopId: name,
name,
lat: LAT,
lon: LON0 + (i * 2000) / KX,
state: 'upcoming',
}));
test('a snapshot read again while nothing changed is the one read before', async (t) => {
let list = stopList('Alpha', 'Bravo', 'Charlie');
const app = await onTheLine(t, {
stops: { stopsFor: () => ({ stops: list, headsign: 'Charlie' }) },
});
app.parts().selection.selectTrain(T1);
const first = app.layer.getSelectedTrain();
assert.equal(app.layer.getSelectedTrain(), first, 'the same snapshot');
// Its stops are frozen copies of the provider's.
assert.equal(first.stops.length, 3);
assert.ok(Object.isFrozen(first.stops));
assert.ok(Object.isFrozen(first.stops[0]));
assert.notEqual(first.stops[0], list[0]);
assert.equal(first.stops[0].name, 'Alpha');
// It moves on: a new snapshot at its new place, what did not change kept.
app.run(RAIL_POLL_MS);
await app.poll();
app.run(RAIL_POLL_MS);
const moved = app.layer.getSelectedTrain();
assert.notEqual(moved, first, 'a new snapshot');
assert.ok(Object.isFrozen(moved) && Object.isFrozen(moved.path));
assert.ok(moved.path.s > first.path.s, 'at its new place');
assert.equal(moved.stops, first.stops, 'the same stops');
assert.equal(moved.feed, first.feed);
assert.equal(moved.provenance, first.provenance);
assert.equal(moved.path.line, first.path.line);
assert.equal(app.layer.getSelectedTrain(), moved);
// The provider lists other stops: new ones.
list = stopList('Delta', 'Echo');
app.run(STOP_REFRESH_MS);
const later = app.layer.getSelectedTrain();
assert.notEqual(later.stops, first.stops);
assert.deepEqual(
later.stops.map((stop) => stop.name),
['Delta', 'Echo'],
);
// A provider that updates its list in place: the stops are copied again.
list[0].state = 'passed';
app.run(STOP_REFRESH_MS);
const updated = app.layer.getSelectedTrain();
assert.notEqual(updated.stops, later.stops);
assert.equal(updated.stops[0].state, 'passed');
assert.equal(app.layer.getSelectedTrain().stops, updated.stops);
});
test('a snapshot’s line is a frozen copy: writing to it leaves the layer’s line', async (t) => {
const app = await onTheLine(t);
app.parts().selection.selectTrain(T1);
const { line, s } = app.layer.getSelectedTrain().path;
const own = app.entry(T1).path.path;
assert.notEqual(line, own, 'not the layer’s own');
assert.ok(Object.isFrozen(line));
for (const name of ['lat', 'lon', 'x', 'y', 's', 'box'])
assert.ok(Object.isFrozen(line[name]), name);
const lat = own.lat[1];
assert.throws(() => {
line.lat[1] = 0;
}, TypeError);
assert.equal(own.lat[1], lat, 'the layer’s line is as it was');
assert.deepEqual(pointAtS(line, s), pointAtS(own, s), 'it reads the same');
// Copied once per line: T2 runs on the same one.
app.parts().selection.selectTrain(T2);
assert.equal(app.layer.getSelectedTrain().path.line, line);
});
test('a held train hides its marker and card and keeps the selection', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.setCockpitSubject('rail:mbta-rail:nope'), false);
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._selectedKey, T1, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, T1);
app.run(1000);
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.entry(T2).marker.show, true);
// From inside the train its selected line would run under the eye.
assert.equal(app.state()._route.primitive.show, false, 'no line');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// Escape is the view's while it holds the train.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, T1);
// It still moves.
const before = app.layer.getCockpitSubject().path.s;
app.run(RAIL_POLL_MS);
await app.poll();
app.run(RAIL_POLL_MS);
assert.ok(app.layer.getCockpitSubject().path.s > before, 'still moving');
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
app.run(1000);
assert.equal(app.entry(T1).marker.show, true);
assert.equal(app.state()._route.primitive.show, true, 'the line is back');
assert.equal(
(app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? []).length,
1,
'the card is back',
);
});
test('a held train draws no 3D model either; let go, its model draws again', async (t) => {
const models = await fleetModelFakes(t);
const app = await onTheLine(t, { fleet: models.fleet, altitude: 1_000 });
// A model's load answers off the frame; the next frames place it.
const frames = async () => {
app.run(500);
await app.settle();
app.run(500);
};
await frames();
assert.equal(models.drawn(T1).length, 1, 'near the camera: its model');
assert.equal(app.entry(T1).modelOwnsVisual, true);
assert.equal(app.entry(T1).marker.show, false, 'its icon hands over');
assert.equal(app.layer.setCockpitSubject(T1), true);
app.run(250);
// The view's eye is inside the train.
assert.equal(models.drawn(T1).length, 0, 'no model');
assert.equal(app.entry(T1).modelOwnsVisual, false);
assert.equal(app.entry(T1).marker.show, false, 'and no icon');
assert.equal(models.drawn(T2).length, 1, 'another train keeps its model');
await frames();
assert.equal(models.drawn(T1).length, 0, 'not on a later frame either');
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.layer.setCockpitSubject(null), true);
await frames();
assert.equal(models.drawn(T1).length, 1, 'let go: its model again');
assert.equal(app.entry(T1).modelOwnsVisual, true);
assert.equal(app.entry(T1).marker.show, false);
});
const MADRID = { lat: 40.4168, lon: -3.7038 };
test('a held train stays the copy drawn when another feed’s copy outranks it, and keeps moving', async (t) => {
const app = harness(t, { at: MADRID });
// One Alvia in two feeds: a station-event copy, held, and a poll later a
// GPS copy that would outrank it.
let step = 0;
let gpsCopy = false;
const lat = (offset) => MADRID.lat + offset + step * 0.003;
app.feeds.set('renfe-cercanias', () => [
train('A1', lat(0), MADRID.lon, {
label: 'ALVIA 4073',
positionSource: 'event',
}),
]);
app.feeds.set('renfe-larga-distancia', () =>
gpsCopy ? [train('B1', lat(0.01), MADRID.lon, { label: '4073' })] : [],
);
await app.enable();
const a = railTrainKey('renfe-cercanias', 'A1');
const b = railTrainKey('renfe-larga-distancia', 'B1');
for (let i = 0; i < 12 && !railTrainFollowable(app.entry(a)); i += 1) {
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.ok(railTrainFollowable(app.entry(a)), 'the train is moving');
assert.equal(app.layer.setCockpitSubject(a), true);
gpsCopy = true;
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
// The view knows the train by its key, and the copies stand apart: the
// held copy stays drawn and selected, the other is the one hidden.
assert.equal(app.layer.getCockpitSubject()?.key, a);
assert.equal(app.state()._selectedKey, a);
assert.equal(app.entry(a).duplicate, false);
assert.equal(app.entry(b).duplicate, true);
assert.equal(app.entry(a).marker.show, false);
assert.equal(app.entry(b).marker.show, false, 'no other marker on it');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// It moves between polls, frame by frame.
assert.ok(app.state()._moving.has(app.entry(a)), 'still playing');
const before = app.layer.getCockpitSubject().position.latitude;
app.run(2000);
assert.ok(
app.layer.getCockpitSubject().position.latitude > before,
'still moving',
);
// Let go: the better copy takes over at the next poll, with the selection.
app.layer.setCockpitSubject(null);
step += 1;
app.run(RAIL_POLL_MS);
await app.poll();
assert.equal(app.entry(a).duplicate, true);
assert.equal(app.entry(b).duplicate, false);
assert.equal(app.state()._selectedKey, b);
assert.equal(app.entry(b).marker.show, true);
assert.equal(
(app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? []).length,
1,
'its card',
);
// The copy hidden is not focused: the selection stays on the one drawn.
assert.equal(app.layer.focusTrain(a), false);
assert.equal(app.state()._selectedKey, b);
// A hold of the copy hidden draws it at once, in place of the other.
assert.equal(app.layer.setCockpitSubject(a), true);
assert.equal(app.state()._selectedKey, a);
assert.equal(app.entry(a).duplicate, false);
assert.equal(app.entry(b).duplicate, true);
assert.equal(app.entry(b).marker.show, false);
assert.ok(app.state()._moving.has(app.entry(a)), 'playing');
});
test('a held train keeps the selection and moves, hidden, when its category is turned off', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.run(1000);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing');
app.layer.setParams({ regional: false });
assert.equal(app.state()._selectedKey, T1, 'still selected');
assert.equal(app.layer.getCockpitSubject()?.key, T1);
assert.equal(app.entry(T1).marker.show, false);
assert.equal(app.entry(T2).marker.show, false, 'its category is hidden');
assert.equal(app.state()._route.primitive.show, false, 'no line');
assert.deepEqual(
app.overlayEntries.get(RAIL_SELECTED_OVERLAY_SOURCE_ID) ?? [],
[],
'no card',
);
// It moves between polls, frame by frame.
assert.ok(app.state()._moving.has(app.entry(T1)), 'still playing');
const before = app.layer.getCockpitSubject().path.s;
app.run(2000);
assert.ok(app.layer.getCockpitSubject().path.s > before, 'still moving');
assert.equal(app.entry(T1).marker.show, false, 'and still hidden');
// Let go: a train of a hidden category, deselected and stopped as the
// toggle would have left it.
app.layer.setCockpitSubject(null);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._moving.has(app.entry(T1)), false);
assert.equal(app.entry(T1).marker.show, false);
const parked = app.entry(T1).path.drawS;
app.run(2000);
assert.equal(app.entry(T1).path.drawS, parked, 'stopped');
// Held again, hidden, it plays at once; let go, it stops again.
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing at once');
app.layer.setCockpitSubject(null);
assert.equal(app.state()._moving.has(app.entry(T1)), false);
// Shown again, it is drawn and moves as any other.
app.layer.setParams({ regional: true });
assert.equal(app.entry(T1).marker.show, true);
assert.ok(app.state()._moving.has(app.entry(T1)), 'playing again');
});
test('a ride let go with restore does not focus a train its category hides', async (t) => {
const app = await onTheLine(t);
// The documented provider: hold on entry; on exit, release, then focus
// the train again when asked to restore.
assert.equal(app.layer.setCockpitSubject(T1), true);
app.layer.setParams({ regional: false });
app.layer.setCockpitSubject(null);
assert.equal(app.layer.focusTrain(T1), false, 'not drawn');
assert.equal(app.state()._selectedKey, null, 'not selected');
assert.equal(app.parts().follow.stats(), null, 'not followed');
assert.equal(app.viewer.trackedEntity, undefined);
assert.equal(app.focusRequests.length, 0, 'not flown to');
assert.equal(app.entry(T1).marker.show, false);
// Shown again, it focuses as before.
app.layer.setParams({ regional: true });
assert.equal(app.layer.focusTrain(T1), true);
assert.equal(app.state()._selectedKey, T1);
assert.ok(app.parts().follow.isFollowing(T1), 'the camera is handed to it');
});
test('a held train that goes takes the hold with it; focusTrain selects', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.feeds.set('mbta-rail', () => [train('T2', LAT, LON0 + 4000 / KX)]);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.focusTrain(T1), false);
assert.equal(app.layer.focusTrain(T2), true);
assert.equal(app.state()._selectedKey, T2);
});
test('a held train its feed drops leaves the feed polled until the view lets go', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
// From the cab the camera looks along the ground, here past the feed's range.
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._heldFeedId, 'mbta-rail', 'held for the train');
const others = () => [train('T2', LAT, LON0 + 4000 / KX)];
app.feeds.set('mbta-rail', others);
for (let i = 0; i < 3; i += 1) {
app.run(RAIL_POLL_MS);
await app.poll();
}
await app.recheck();
assert.equal(app.entry(T1), undefined, 'the train is gone');
assert.equal(app.layer.getCockpitSubject(), null);
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'its feed is polled');
await app.moveCamera({ lat: 40.72, lon: -74.0 });
assert.ok(app.state()._activeFeeds.has('mbta-rail'), 'whatever the camera');
// Listed again: the view holds it again.
app.feeds.set('mbta-rail', () => [
train('T1', LAT, LON0 + 2500 / KX, { speedMps: 15 }),
...others(),
]);
app.run(RAIL_POLL_MS);
await app.poll();
assert.equal(app.layer.setCockpitSubject(T1), true);
assert.equal(app.state()._cockpitLostFeedId, null);
assert.equal(app.state()._selectedKey, T1);
// Let go, and the feed is the viewport's again: out of range, released.
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.setCockpitSubject(null);
await app.moveCamera({ lat: 40.71, lon: -74.0 });
assert.equal(app.state()._activeFeeds.has('mbta-rail'), false);
assert.equal(app.state()._trains.size, 0);
});
test('selectedAtMs is the user’s selection time, never a hold’s or another train’s', async (t) => {
const app = await onTheLine(t);
assert.equal(app.layer.focusTrain(T1), true);
const first = app.layer.getSelectedTrain().selectedAtMs;
assert.ok(Number.isFinite(first), 'a click or focusTrain stamps it');
// Selected again: a later stamp.
app.run(1000);
app.layer.focusTrain(T1);
assert.ok(app.layer.getSelectedTrain().selectedAtMs > first);
// A hold of another train is not the user's selection.
app.layer.setCockpitSubject(T2);
assert.equal(app.layer.getCockpitSubject().key, T2);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
app.layer.setCockpitSubject(null);
// Nor after a deselection (Escape), then a hold.
app.layer.focusTrain(T1);
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._selectedAtMs, null, 'deselection clears it');
app.layer.setCockpitSubject(T2);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
// Releasing twice is harmless: the selection stays.
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.state()._selectedKey, T2);
assert.equal(app.layer.getCockpitSubject(), null);
});
test('turning the layer off ends the hold', async (t) => {
const app = await onTheLine(t);
app.layer.setCockpitSubject(T1);
app.parts().ingestion.removeTrain(T1);
assert.equal(app.state()._cockpitLostFeedId, 'mbta-rail');
app.layer.disable(app.viewer);
assert.equal(app.state()._cockpitSubjectKey, null);
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');
});
+7 -1
View File
@@ -91,7 +91,13 @@ export function createControls({ state, parts, timetable }) {
return true;
state._categories = next;
const selected = state._trains.get(state._selectedKey);
if (selected && next[selected.category] === false)
// A held train keeps the selection until its view lets it go
// (cockpitSubject.js).
if (
selected &&
next[selected.category] === false &&
selected.key !== state._cockpitSubjectKey
)
parts.selection.clearSelection();
parts.rendering.applyCategoryVisibility();
state._revision += 1;
+14 -5
View File
@@ -25,9 +25,13 @@ import { greatCircleKm } from '../../geoDistance.js';
* 2. the line: a copy bound to its operator's shape (a built pack), then
* one without.
* The copy drawn stays drawn until another scores strictly higher, so equal
* copies never trade places. A losing copy keeps its playback and is only
* hidden; when a feed leaves the viewport its copies' partners come back.
* The comparison runs once per poll, never per frame.
* copies never trade places. A copy a first-person view holds
* (cockpitSubject.js) stays drawn whatever the scores until the view lets
* go: the view knows the train by that copy's key and rides it where that
* copy's feed puts it, tens of kilometres from another feed's copy at
* times. A losing copy keeps its playback and is only hidden; when a feed
* leaves the viewport its copies' partners come back. The comparison runs
* once per poll, never per frame.
*/
/**
@@ -288,10 +292,12 @@ function better(a, b) {
* scores strictly higher.
* @param {object[][]} groups From matchCopies.
* @param {Map<string, string>} [previous] copy key → key drawn last time.
* @param {string|null} [held] A copy drawn whatever the scores: the train a
* first-person view holds.
* @returns {{winners: Map<string, string>, hidden: Set<string>}}
* `winners`: every grouped copy's key → the key drawn for its train.
*/
export function chooseCopies(groups, previous = new Map()) {
export function chooseCopies(groups, previous = new Map(), held = null) {
const winners = new Map();
const hidden = new Set();
for (const group of groups) {
@@ -305,6 +311,7 @@ export function chooseCopies(groups, previous = new Map()) {
scored.reduce((a, b) => (better(b.score, a.score) ? b : a));
for (const candidate of scored)
if (better(candidate.score, best.score)) best = candidate;
best = scored.find(({ copy }) => copy.key === held) ?? best;
for (const { copy } of scored) {
winners.set(copy.key, best.copy.key);
if (copy.key !== best.copy.key) hidden.add(copy.key);
@@ -318,7 +325,8 @@ export function chooseCopies(groups, previous = new Map()) {
* loaded feed carries, marks the copies not drawn (`entry.duplicate`), and
* moves a selection that sat on a copy now hidden to the copy drawn, so the
* card follows the same physical train (its feed line names the new
* source).
* source). A held copy is never the one hidden, so the hold and the
* selection stay on it.
* @param {{state: object, parts: object,
* defer?: (fn: Function) => unknown}} context
*/
@@ -355,6 +363,7 @@ export function createDuplicateFilter({
const { winners, hidden } = chooseCopies(
matchCopies(entries.map(copyOf)),
previous,
state._cockpitSubjectKey ?? null,
);
previous = winners;
for (const entry of entries) {
+26
View File
@@ -252,6 +252,32 @@ test('the filter hides the weaker copy and the selection follows its train', ()
assert.deepEqual(filter.stats(), { groups: 0, hidden: 0 });
});
test('a copy a first-person view holds stays drawn, with the selection', () => {
const pair = [
copy('a', 'f1', { number: '160', position: 'event' }),
copy('b', 'f2', { number: '160', position: 'gps' }),
];
assert.equal(chooseCopies([pair]).winners.get('a'), 'b');
const held = chooseCopies([pair], new Map(), 'a');
assert.equal(held.winners.get('b'), 'a', 'drawn whatever the scores');
assert.deepEqual([...held.hidden], ['b']);
// Let go, the better copy takes over.
assert.equal(chooseCopies([pair], held.winners).winners.get('a'), 'b');
const layer = fakeLayer({ selected: 'feed-a:v160' });
layer.state._cockpitSubjectKey = 'feed-a:v160';
const filter = createDuplicateFilter({ ...layer, defer: (fn) => fn() });
filter.refresh();
const [unbound, operator] = layer.trains;
assert.equal(unbound.duplicate, false, 'the held copy');
assert.equal(operator.duplicate, true);
assert.deepEqual(layer.calls.selected, [], 'the selection stays on it');
layer.state._cockpitSubjectKey = null;
filter.refresh();
assert.equal(unbound.duplicate, true);
assert.deepEqual(layer.calls.selected, [operator.key]);
});
test('a short number after a local product names a line, not a train (S1, RB 1, U6)', () => {
for (const label of ['S1', 'RB 1', 'U6', 'S 12', 'RE5'])
assert.equal(recordTrainNumber({ label }), null, label);
+15
View File
@@ -7,6 +7,7 @@ import { createIngestion } from './ingestion.js';
import { createViewport } from './viewport.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createRailCockpitSubject } from './cockpitSubject.js';
import { createRouteDisplay } from './routeDisplay.js';
import { createRailSchedules } from './schedules.js';
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
@@ -78,12 +79,24 @@ function createState({ services }) {
_stopAnchors: new Map(),
_categories: { ...DEFAULT_RAIL_CATEGORY_VISIBILITY },
_selectedKey: null,
/** When the user last selected a train, even the selected one (ms). */
_selectedAtMs: null,
_selectedCardAt: 0,
_selectedCardText: null,
/** The camera's follow of the selected train (follow.js), or null. */
_follow: null,
/** A feed polled only for the selected train (viewport.js), or null. */
_heldFeedId: null,
/**
* The train a first-person view holds (cockpitSubject.js), or null: its
* marker, 3D model and card are hidden and the selection stays on it.
*/
_cockpitSubjectKey: null,
/**
* The feed of a held train the feed dropped (ingestion.js), polled until
* the view takes a train again or lets go (cockpitSubject.js), or null.
*/
_cockpitLostFeedId: null,
_revision: 0,
_controlsListener: null,
_dataManager: null,
@@ -175,11 +188,13 @@ export function createRailLayer({
parts.ingestion = createIngestion(context);
parts.viewport = createViewport(context);
parts.lifecycle = createLifecycle(context);
parts.cockpit = createRailCockpitSubject(context);
return Object.assign(
{ updateInterval: RAIL_POLL_MS },
parts.lifecycle.methods,
parts.controls.methods,
parts.cockpit.methods,
{
/** Test seams: this instance's own state and parts. */
_railStateForTest: () => state,
+10
View File
@@ -69,12 +69,20 @@ export function createIngestion({ state, services, parts, source }) {
function removeTrain(key) {
const entry = state._trains.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js); its
// feed stays polled until the view lets go, so the train is found again
// if the feed lists it again.
if (state._cockpitSubjectKey === key) {
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = entry.feedId;
}
if (state._selectedKey === key) parts.selection.clearSelection();
if (entry.marker) state._markers?.remove(entry.marker);
entry.marker = null;
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.
@@ -267,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,
+3
View File
@@ -35,6 +35,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();
@@ -126,6 +127,8 @@ export function createLifecycle({ state, services, parts, timetable }) {
parts.ingestion.abortAllInFlight();
state._activeFeeds.clear();
state._heldFeedId = null;
state._cockpitSubjectKey = null;
state._cockpitLostFeedId = null;
state._feedStatus.clear();
dropAllTrains();
parts.rendering.stopModels();
+29
View File
@@ -47,11 +47,31 @@ export function pathWindowM(dtMs) {
return window > PATH_WINDOW_MAX_M ? NaN : window;
}
/** Arc moved between two reports before it says which way a train runs (m). */
const DIRECTION_MIN_M = 1;
/** +1 or -1 for an arc step longer than DIRECTION_MIN_M, else `known`. */
function directionOf(step, known) {
return Number.isFinite(step) && Math.abs(step) > DIRECTION_MIN_M
? Math.sign(step)
: known;
}
function createBinding(shapeIndex, path, via, s, fix) {
return {
shapeIndex,
path,
via,
/**
* Which way the drawn train runs along the shape: +1 along it, -1
* against it, 0 until two reports or a playback segment tell. Kept until
* a rebind. Once playback has placed the train, only playback changes
* it: the newest reports run ahead of the drawn train, so a reversal
* they show turns it when playback reaches it.
*/
direction: 0,
/** The direction the last placed playback segment ran, 0 before one. */
drawDirection: 0,
/** Arc and time of the newest report. */
fixS: s,
fixT: fix.t,
@@ -139,6 +159,8 @@ export function followFix(binding, fix) {
pathWindowM(fix.t - binding.fixT),
);
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
if (!binding.drawDirection)
binding.direction = directionOf(hit.s - binding.fixS, binding.direction);
binding.fixS = hit.s;
binding.fixT = fix.t;
binding.fixLat = fix.lat;
@@ -230,6 +252,13 @@ export function placeOnPath(binding, sample, segment, out) {
cache.sFrom = sFrom;
cache.sTo = sTo;
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
if (cache.ok) {
binding.drawDirection = directionOf(
sTo - sFrom,
binding.drawDirection || binding.direction || 0,
);
binding.direction = binding.drawDirection;
}
}
if (!cache.ok) return false;
const f = Number.isFinite(sample.fraction)
+61
View File
@@ -201,3 +201,64 @@ test('a segment whose reports do not fit the line keeps the straight line', () =
assert.equal(placeOnPath(binding, stale.sample, stale.segment, out), false);
assert.equal(placeOnPath(null, stale.sample, stale.segment, out), false);
});
test('a binding learns which way its train runs, and keeps it through a stop', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const along = bindTrainPath(p, ids, fix(0, 500, 0));
assert.equal(along.direction, 0, 'one report tells no direction');
assert.ok(followFix(along, fix(10_000, 700, 0)));
assert.equal(along.direction, 1);
// Standing still (under a metre) keeps what it learnt.
assert.ok(followFix(along, fix(20_000, 700.4, 0)));
assert.equal(along.direction, 1);
const against = bindTrainPath(p, ids, fix(0, 1500, 0));
assert.ok(followFix(against, fix(10_000, 1200, 0)));
assert.equal(against.direction, -1);
// A playback segment between two reports tells it too.
const played = bindTrainPath(p, ids, fix(0, 300, 0));
const segment = {
from: { seq: 1, ...fix(0, 300, 0) },
to: { seq: 2, ...fix(10_000, 100, 0) },
};
assert.ok(
placeOnPath(played, { fromSeq: 1, toSeq: 2, fraction: 0.5 }, segment, {}),
);
assert.equal(played.direction, -1);
// A rebind starts again.
const rebound = rebindTrainPath(
p,
{ routeId: 'main' },
along,
fix(30_000, 2000, -300),
);
assert.equal(rebound?.direction ?? 0, 0);
});
test('a report that runs back turns the drawn train only when playback does', () => {
const p = pack();
const ids = { tripId: 'full', routeId: 'main' };
const binding = bindTrainPath(p, ids, fix(0, 300, 0));
const forward = {
from: { seq: 1, ...fix(0, 300, 0) },
to: { seq: 2, ...fix(10_000, 500, 0) },
};
const sample = (fraction) => ({ fromSeq: 1, toSeq: 2, fraction });
assert.ok(placeOnPath(binding, sample(0.2), forward, {}));
assert.equal(binding.direction, 1);
// The newest report lies behind the last one (a reversal, or GPS jitter)
// while playback still draws the forward segment.
assert.ok(followFix(binding, fix(10_000, 500, 0)));
assert.ok(followFix(binding, fix(20_000, 450, 0)));
assert.ok(placeOnPath(binding, sample(0.6), forward, {}));
assert.equal(binding.direction, 1, 'the drawn train still runs forward');
// Playback reaches the reversed segment: now it turns.
const back = {
from: { seq: 2, ...fix(10_000, 500, 0) },
to: { seq: 3, ...fix(20_000, 450, 0) },
};
assert.ok(
placeOnPath(binding, { fromSeq: 2, toSeq: 3, fraction: 0.5 }, back, {}),
);
assert.equal(binding.direction, -1);
});
+51 -13
View File
@@ -1,5 +1,10 @@
import * as Cesium from 'cesium';
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,
@@ -523,9 +528,25 @@ export function createRendering({ state, services, parts }) {
);
}
/** Whether a train's icon is drawn: shown, and not drawn by its model. */
/**
* Whether a train's icon is drawn: shown, not drawn by its model, and no
* first-person view rides it (cockpitSubject.js). A held train keeps its
* playback; only its icon and model hide.
*/
function markerShown(entry) {
return categoryShown(entry) && !entry.modelOwnsVisual;
return (
categoryShown(entry) &&
!entry.modelOwnsVisual &&
entry.key !== state._cockpitSubjectKey
);
}
/**
* Whether the train's playback runs: it is drawn, or a first-person view
* rides it, which keeps it moving, hidden, in a category turned off.
*/
function playing(entry) {
return categoryShown(entry) || entry.key === state._cockpitSubjectKey;
}
/**
@@ -535,8 +556,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)
@@ -613,16 +637,26 @@ export function createRendering({ state, services, parts }) {
if (!entry.marker) return;
place(entry);
const sample = entry.sample;
const moving =
categoryShown(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 (categoryShown(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;
@@ -630,9 +664,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),
);
}
}
@@ -744,7 +779,9 @@ export function createRendering({ state, services, parts }) {
}
item.position = entry.marker.position;
item.headingDeg = Number.isFinite(entry.courseDeg) ? entry.courseDeg : 0;
item.show = categoryShown(entry);
// A train a first-person view rides draws no model: the camera is inside
// it (cockpitSubject.js).
item.show = categoryShown(entry) && entry.key !== state._cockpitSubjectKey;
return item;
}
@@ -833,7 +870,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);
}
+20
View File
@@ -427,10 +427,29 @@ export function createRouteDisplay({
updateSplit();
}
/**
* Show the selected line unless a first-person view rides its train
* (cockpitSubject.js): from inside the train it would run up the middle of
* the view and under the eye.
*/
function applyHold() {
const route = state._route;
if (!route?.primitive) return;
const shown = !(
state._cockpitSubjectKey !== null &&
state._cockpitSubjectKey === state._selectedKey
);
if (route.primitive.show !== shown) {
route.primitive.show = shown;
governorRequestRender('rail-route');
}
}
/** Move the travelled/ahead split to where the train is drawn now. */
function updateSplit() {
const route = state._route;
if (!route?.primitive) return;
applyHold();
const binding = route.binding;
const s = binding ? binding.drawS : NaN;
if (route.direction === 0 && Number.isFinite(s)) {
@@ -777,6 +796,7 @@ export function createRouteDisplay({
applyNetwork,
onCamera,
syncRoute,
applyHold,
refreshStops,
cullStops,
onSelectionChanged,
+17
View File
@@ -35,6 +35,16 @@ export function createSelection({ state, services, parts }) {
function refreshSelectedCard(force) {
const entry = state._trains.get(state._selectedKey);
if (!entry) return;
// A train a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.setEntries(
RAIL_SELECTED_OVERLAY_SOURCE_ID,
[],
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -103,6 +113,8 @@ export function createSelection({ state, services, parts }) {
*/
function selectAndFocusTrain(key) {
if (!state._trains.has(key)) return;
// A selection by the user, even of the selected train (cockpitSubject.js).
state._selectedAtMs = Date.now();
const following = parts.follow.isFollowing(key);
// Another train's follow lets go first, so this is never taken for a
// move between two copies of one train.
@@ -120,6 +132,7 @@ export function createSelection({ state, services, parts }) {
const hadSelection = state._selectedKey !== null;
parts.follow.release({ untrack });
state._selectedKey = null;
state._selectedAtMs = null;
state._selectedCardText = null;
if (hadSelection) {
parts.rendering.paintAll();
@@ -136,6 +149,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the train, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -146,6 +161,8 @@ export function createSelection({ state, services, parts }) {
);
state._clickHandler.setInputAction((click) => {
if (!state._enabled || !isPointerFree()) return;
// A held train keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const picked = viewer.scene.pick(click.position);
const id = typeof picked?.id === 'string' ? picked.id : null;
if (id && state._trains.has(id)) selectAndFocusTrain(id);
+6
View File
@@ -148,6 +148,12 @@ export function createViewport({ state, services, parts, source }) {
))
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
// A first-person view whose train its feed dropped keeps the feed polled
// until it lets go (cockpitSubject.js): from the cab the camera looks
// along the ground, often at a point beyond the feed's range.
const lost = state._cockpitLostFeedId;
if (lost && !desired.has(lost) && state._activeFeeds.has(lost))
desired.set(lost, state._activeFeeds.get(lost));
// The selected train's feed stays polled however far out or away the
// camera goes, so the train and its line stay on the map; while nothing
// else would keep the feed, it carries the selected train alone and its
+44 -32
View File
@@ -1,11 +1,14 @@
import * as Cesium from 'cesium';
import { twoline2satrec } from 'satellite.js';
import { gstime, twoline2satrec } from 'satellite.js';
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
import {
DENSE_REFRESH_FRAMES,
DENSE_GROUP_PATH,
DENSE_SAMPLES_PER_FRAME_MAX,
POINT_STYLES,
DENSE_CREATE_CHUNK,
ORBIT_SAMPLE_HORIZON_MS,
} from './policy.js';
export function createCatalog({ state: layerState, services, parts, source }) {
@@ -18,37 +21,42 @@ export function createCatalog({ state: layerState, services, parts, source }) {
}
/**
* Re-propagate a small per-frame slice of the dense extras (round-robin).
* Budget: the full dense set completes one pass every ~DENSE_REFRESH_FRAMES
* frames (~5s at 60fps ≈ 1/5 of the core cadence), so per-frame cost stays
* ~35 propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the
* work per frame avoids the once-per-second spike a tick-sized chunk
* (~2K props ≈ 4ms) would cause.
* Sample a small per-frame slice of the dense extras (round-robin); every
* point is then reckoned from its sample each frame (rendering.js
* _reckonPoints). At normal speed the full dense set is sampled once every
* ~DENSE_REFRESH_FRAMES frames (~5s at 60fps), so per-frame cost stays ~35
* propagations (~0.1 ms) even with 10K+ Starlink sats — spreading the work
* per frame avoids the once-per-second spike a tick-sized chunk (~2K props
* ≈ 4ms) would cause. While time plays fast, or after a seek, the slice
* grows so each sample stays within ORBIT_SAMPLE_HORIZON_MS of the world
* time, up to DENSE_SAMPLES_PER_FRAME_MAX a frame.
* @param {number} worldStepMs How far the world time moved since the last
* frame (NaN on the first).
*/
function _propagateDenseChunk() {
if (layerState._denseIds.length === 0) return;
const perFrame = Math.max(
1,
Math.ceil(layerState._denseIds.length / DENSE_REFRESH_FRAMES),
function _propagateDenseChunk(worldStepMs) {
const count = layerState._denseIds.length;
if (count === 0) return;
const share = Math.max(
1 / DENSE_REFRESH_FRAMES,
Number.isFinite(worldStepMs)
? Math.abs(worldStepMs) / ORBIT_SAMPLE_HORIZON_MS
: 1,
);
const now = new Date(layerState.now());
const perFrame = Math.min(
count,
DENSE_SAMPLES_PER_FRAME_MAX,
Math.max(1, Math.ceil(count * share)),
);
const nowMs = layerState.now();
for (let i = 0; i < perFrame; i++) {
if (layerState._denseCursor >= layerState._denseIds.length)
layerState._denseCursor = 0;
if (layerState._denseCursor >= count) layerState._denseCursor = 0;
const noradId = layerState._denseIds[layerState._denseCursor++];
if (noradId === layerState._trackedNorad) continue; // per-frame tracked path owns it
const sat = layerState._catalog.get(noradId);
const point = layerState._points.get(noradId);
if (!sat || !point) continue;
const pos = parts.orbits.propagatePosition(sat.satrec, now);
if (pos) {
point.position = Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
}
if (!sat) continue;
const sample = sampleOrbit(sat.satrec, nowMs, sat.orbitSample);
if (sample) sat.orbitSample = sample;
}
}
@@ -97,7 +105,8 @@ export function createCatalog({ state: layerState, services, parts, source }) {
const entries = parts.orbits.parseTLE(text);
const style = POINT_STYLES.dense;
const now = new Date(layerState.now());
const nowMs = layerState.now();
const gmst = gstime(new Date(nowMs));
let added = 0;
for (let start = 0; start < entries.length; start += DENSE_CREATE_CHUNK) {
@@ -116,8 +125,9 @@ export function createCatalog({ state: layerState, services, parts, source }) {
if (!satrec || satrec.error !== 0) continue;
const noradId = noradIdFromSatnum(satrec.satnum);
if (layerState._catalog.has(noradId)) continue; // core catalog keeps priority
const pos = parts.orbits.propagatePosition(satrec, now);
if (!pos) continue;
// Its first sample places it now and moves it from then on.
const orbitSample = sampleOrbit(satrec, nowMs);
if (!orbitSample) continue;
layerState._catalog.set(noradId, {
name: entry.name,
@@ -131,12 +141,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
ucs: null,
satcat: null,
sensor: null,
orbitSample,
});
const point = layerState._pointCollection.add({
position: Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
position: reckonEarthFixed(
orbitSample,
nowMs,
gmst,
new Cesium.Cartesian3(),
),
pixelSize: style.pixelSize,
color: style.color,
+80
View File
@@ -0,0 +1,80 @@
import { propagate } from 'satellite.js';
/** The Earth's gravitational parameter, km³/s², as SGP4's WGS72 constants. */
const MU_KM3_S2 = 398600.8;
/** Floats in one orbit sample: its time, then position, velocity,
* acceleration and jerk. */
export const ORBIT_SAMPLE_LENGTH = 13;
/**
* One SGP4 state of a satellite for dead reckoning: its inertial (TEME)
* position and velocity at `atMs`, with the two-body acceleration and its
* rate of change (jerk) there.
* Layout: [atMs, rx, ry, rz (km), vx, vy, vz (km/s), ax, ay, az (km/s²),
* jx, jy, jz (km/s³)].
* @param {object} satrec
* @param {number} atMs Epoch milliseconds.
* @param {Float64Array} [out]
* @returns {Float64Array|null} Null when SGP4 has no state for that time.
*/
export function sampleOrbit(
satrec,
atMs,
out = new Float64Array(ORBIT_SAMPLE_LENGTH),
) {
let state;
try {
state = propagate(satrec, new Date(atMs));
} catch {
return null;
}
const p = state?.position;
const v = state?.velocity;
if (!p || typeof p === 'boolean' || !v || typeof v === 'boolean') return null;
const r = Math.hypot(p.x, p.y, p.z);
if (!(r > 0) || !Number.isFinite(v.x + v.y + v.z)) return null;
const k = -MU_KM3_S2 / (r * r * r);
// d/dt of -μ r/|r|³: -μ (v/|r|³ - 3 (r·v) r/|r|⁵).
const radial = (3 * (p.x * v.x + p.y * v.y + p.z * v.z)) / (r * r);
out[0] = atMs;
out[1] = p.x;
out[2] = p.y;
out[3] = p.z;
out[4] = v.x;
out[5] = v.y;
out[6] = v.z;
out[7] = k * p.x;
out[8] = k * p.y;
out[9] = k * p.z;
out[10] = k * (v.x - radial * p.x);
out[11] = k * (v.y - radial * p.y);
out[12] = k * (v.z - radial * p.z);
return out;
}
/**
* Where a satellite is at `atMs`, reckoned from its sample along the inertial
* path (position, velocity, gravity and its change) and turned into the
* Earth-fixed frame by the Greenwich sidereal angle at that time. Over half a
* minute of world time the reckoned point stays within metres of SGP4.
* @param {Float64Array} sample From sampleOrbit.
* @param {number} atMs Epoch milliseconds.
* @param {number} gmst Greenwich mean sidereal angle at `atMs`, radians.
* @param {{x: number, y: number, z: number}} out Receives Earth-fixed metres.
* @returns {{x: number, y: number, z: number}} `out`.
*/
export function reckonEarthFixed(sample, atMs, gmst, out) {
const dt = (atMs - sample[0]) / 1000;
const half = 0.5 * dt * dt;
const sixth = (half * dt) / 3;
const x = sample[1] + sample[4] * dt + sample[7] * half + sample[10] * sixth;
const y = sample[2] + sample[5] * dt + sample[8] * half + sample[11] * sixth;
const z = sample[3] + sample[6] * dt + sample[9] * half + sample[12] * sixth;
const cos = Math.cos(gmst);
const sin = Math.sin(gmst);
out.x = (x * cos + y * sin) * 1000;
out.y = (-x * sin + y * cos) * 1000;
out.z = z * 1000;
return out;
}
+86
View File
@@ -0,0 +1,86 @@
// src/layers/satellites/motion.test.mjs — a satellite's point reckoned from
// one SGP4 sample stays on SGP4's track between samples.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { gstime, twoline2satrec } from 'satellite.js';
import { createOrbits } from './orbits.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
const ISS = twoline2satrec(
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
);
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
/** Where the layer has always drawn a satellite: SGP4, through geodetic. */
function drawnBySgp4(atMs) {
const pos = orbits.propagatePosition(ISS, new Date(atMs));
return Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
}
function reckoned(sample, atMs) {
return reckonEarthFixed(
sample,
atMs,
gstime(new Date(atMs)),
new Cesium.Cartesian3(),
);
}
test('at its own time the reckoned point is where SGP4 draws it', () => {
const sample = sampleOrbit(ISS, AT_MS);
const gap = Cesium.Cartesian3.distance(
reckoned(sample, AT_MS),
drawnBySgp4(AT_MS),
);
assert.ok(gap < 1, `${gap} m`);
});
test('between samples the point keeps to the SGP4 track', () => {
const sample = sampleOrbit(ISS, AT_MS);
for (const [seconds, withinM] of [
[0.016, 1],
[1, 2],
[10, 2],
[30, 10],
[60, 50],
]) {
const atMs = AT_MS + seconds * 1000;
const gap = Cesium.Cartesian3.distance(
reckoned(sample, atMs),
drawnBySgp4(atMs),
);
assert.ok(gap < withinM, `${seconds} s: ${gap} m`);
}
});
test('the point moves every frame, at orbital speed', () => {
const sample = sampleOrbit(ISS, AT_MS);
const a = reckoned(sample, AT_MS + 500);
const b = reckoned(sample, AT_MS + 516);
const speed = Cesium.Cartesian3.distance(a, b) / 0.016;
// ISS ground-relative speed: about 7.2–7.7 km/s.
assert.ok(speed > 7000 && speed < 8000, `${speed} m/s`);
});
test('reckoning backwards in time works as forwards', () => {
const sample = sampleOrbit(ISS, AT_MS);
const atMs = AT_MS - 30_000;
const gap = Cesium.Cartesian3.distance(
reckoned(sample, atMs),
drawnBySgp4(atMs),
);
assert.ok(gap < 10, `${gap} m`);
});
test('an element set SGP4 cannot propagate has no sample', () => {
const decayed = { ...ISS, error: 0 };
decayed.ecco = 2; // not an orbit
assert.equal(sampleOrbit(decayed, AT_MS), null);
});
+17 -1
View File
@@ -120,7 +120,16 @@ export const ISS_OVERLAY_SOURCE_OPTIONS = Object.freeze({
export const ORBIT_PATH_STEPS = 180;
// points per orbital path
/** How often every core satellite takes a fresh SGP4 sample (wall ms). */
export const POSITION_UPDATE_MS = 1000;
/**
* Between SGP4 samples every point is reckoned each frame from its last one
* (motion.js). A sample this far from the world time is taken again, so a
* point is never more than about 10 m off SGP4 however fast time plays.
*/
export const ORBIT_SAMPLE_HORIZON_MS = 30_000;
/** Beyond this from its sample a point is left where it is until sampled again. */
export const ORBIT_RECKON_LIMIT_MS = 120_000;
/** How far either side of now SGP4 on current element sets stays meaningful. */
export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
@@ -130,7 +139,6 @@ export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
* drifts a few degrees a day.
*/
export const ORBIT_REBAKE_MS = 30 * 60_000;
// re-propagate every 1s (SGP4 is smooth at this rate)
export const RING_ROTATION_MS = 1000;
// re-align baked orbit rings to current GMST every 1s
@@ -169,6 +177,14 @@ export const DENSE_GROUP_PATH = 'starlink';
export const DENSE_REFRESH_FRAMES = 300;
// full dense pass spread over ~300 frames (~5s @ 60fps)
/**
* The most dense extras sampled in one frame while time plays fast (~4 ms).
* Past about 10 minutes of world time a second the full dense set no longer
* fits within ORBIT_RECKON_LIMIT_MS, and its points move only as they are
* sampled.
*/
export const DENSE_SAMPLES_PER_FRAME_MAX = 2000;
export const DENSE_CREATE_CHUNK = 1500;
// satrec builds per macro-task while loading
+157
View File
@@ -0,0 +1,157 @@
// src/layers/satellites/reckon.test.mjs — every frame each shown point moves
// to where its satellite is at the world time; samples are taken again when
// time has moved far from them, and dense extras are sampled faster the
// faster time plays.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { twoline2satrec } from 'satellite.js';
import { createCatalog } from './catalog.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
import { sampleOrbit } from './motion.js';
import {
DENSE_REFRESH_FRAMES,
DENSE_SAMPLES_PER_FRAME_MAX,
ORBIT_RECKON_LIMIT_MS,
ORBIT_SAMPLE_HORIZON_MS,
} from './policy.js';
const ISS = twoline2satrec(
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927',
'2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.72125391563537',
);
const AT_MS = Date.UTC(2008, 8, 20, 12, 30, 0);
const orbits = createOrbits({ state: {}, services: {}, parts: {} });
/** A point primitive that counts position writes. */
function point(show = true) {
let position = new Cesium.Cartesian3();
return {
show,
writes: 0,
get position() {
return position;
},
set position(value) {
this.writes++;
position = Cesium.Cartesian3.clone(value);
},
};
}
function scene(entries, { tracked = null } = {}) {
const state = {
_points: new Map(),
_catalog: new Map(),
_trackedNorad: tracked,
_denseIds: [],
_denseCursor: 0,
};
for (const [id, entry] of Object.entries(entries)) {
state._points.set(id, entry.point);
state._catalog.set(id, { satrec: ISS, group: 'core', ...entry.sat });
}
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
return { state, rendering };
}
function sgp4At(atMs) {
const pos = orbits.propagatePosition(ISS, new Date(atMs));
return Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
}
test('a shown point moves to its satellite at the world time; hidden and tracked ones do not', () => {
const shown = point();
const hidden = point(false);
const tracked = point();
const { rendering } = scene(
{
shown: { point: shown },
hidden: { point: hidden },
tracked: { point: tracked },
},
{ tracked: 'tracked' },
);
rendering._reckonPoints(AT_MS);
assert.ok(Cesium.Cartesian3.distance(shown.position, sgp4At(AT_MS)) < 1);
assert.equal(hidden.writes, 0);
assert.equal(tracked.writes, 0);
// The same time again (the clock paused): nothing is written.
rendering._reckonPoints(AT_MS);
assert.equal(shown.writes, 1);
// Shown while paused, a hidden point moves at once.
hidden.show = true;
rendering._reckonPoints(AT_MS);
assert.equal(hidden.writes, 1);
});
test('between samples the point keeps to the track; far from its sample, a core satellite is sampled again', () => {
const p = point();
const { state, rendering } = scene({ iss: { point: p } });
rendering._reckonPoints(AT_MS);
const sample = state._catalog.get('iss').orbitSample;
assert.equal(sample[0], AT_MS);
// Within the horizon the same sample moves it on.
const soon = AT_MS + ORBIT_SAMPLE_HORIZON_MS / 2;
rendering._reckonPoints(soon);
assert.equal(state._catalog.get('iss').orbitSample[0], AT_MS);
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(soon)) < 5);
// A seek an hour back samples it again there.
const back = AT_MS - 3_600_000;
rendering._reckonPoints(back);
assert.equal(state._catalog.get('iss').orbitSample[0], back);
assert.ok(Cesium.Cartesian3.distance(p.position, sgp4At(back)) < 1);
});
test('a dense extra is left for its round-robin, and stays put once too far from its sample', () => {
const p = point();
const { rendering } = scene({
starlink: {
point: p,
sat: { group: 'dense', orbitSample: sampleOrbit(ISS, AT_MS) },
},
});
rendering._reckonPoints(AT_MS + ORBIT_SAMPLE_HORIZON_MS * 2);
assert.equal(p.writes, 1, 'reckoned from its own sample');
rendering._reckonPoints(AT_MS + ORBIT_RECKON_LIMIT_MS + 1);
assert.equal(p.writes, 1, 'too far: left where it is');
});
test('the dense slice grows with how fast the world time moves, up to its cap', () => {
const sampled = (count, worldStepMs) => {
const state = {
_denseIds: [],
_denseCursor: 0,
_catalog: new Map(),
_trackedNorad: null,
now: () => AT_MS,
};
for (let i = 0; i < count; i++) {
state._denseIds.push(String(i));
state._catalog.set(String(i), { satrec: ISS, group: 'dense' });
}
createCatalog({
state,
services: {},
parts: {},
source: {},
})._propagateDenseChunk(worldStepMs);
return [...state._catalog.values()].filter((sat) => sat.orbitSample).length;
};
// Real time: the set over DENSE_REFRESH_FRAMES frames.
assert.equal(sampled(3000, 16), Math.ceil(3000 / DENSE_REFRESH_FRAMES));
// A tenth of the horizon a frame: a tenth of the set.
assert.equal(sampled(3000, ORBIT_SAMPLE_HORIZON_MS / 10), 300);
// A seek, or the first frame: as many as the cap allows.
assert.equal(sampled(3000, Number.NaN), DENSE_SAMPLES_PER_FRAME_MAX);
assert.equal(sampled(1000, -ORBIT_SAMPLE_HORIZON_MS * 5), 1000);
});
+67 -22
View File
@@ -1,12 +1,18 @@
import * as Cesium from 'cesium';
import { gstime } from 'satellite.js';
import { reckonEarthFixed, sampleOrbit } from './motion.js';
import {
ISS_NORAD,
ORBIT_REBAKE_MS,
ORBIT_RECKON_LIMIT_MS,
ORBIT_SAMPLE_HORIZON_MS,
POSITION_UPDATE_MS,
RING_ROTATION_MS,
} from './policy.js';
/** Scratch for a point's reckoned position. */
const _reckoned = new Cesium.Cartesian3();
export function createRendering({
state: layerState,
services,
@@ -158,40 +164,73 @@ export function createRendering({
}
/**
* Propagate all CORE satellite positions and update point primitives.
* (About 1,300 core satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms,
* fine at the 1s/200ms cadence.) Dense extras are
* excluded: they refresh on the round-robin budget in _propagateDenseChunk.
* Take a fresh SGP4 sample of every CORE satellite (motion.js); the points
* move from these each frame in _reckonPoints. (About 1,300 core
* satellites: ~840 measured at ≈ 1.6 ms/pass, so ≈ 2.5 ms, fine at the
* 1s/200ms cadence.) Dense extras are excluded: they are sampled on the
* round-robin budget in _propagateDenseChunk.
* @returns {number} How many satellites were sampled.
*/
function _propagateAll() {
const now = new Date(layerState.now());
const nowMs = layerState.now();
let updated = 0;
for (const [noradId, sat] of layerState._catalog) {
for (const sat of layerState._catalog.values()) {
if (sat.group === 'dense') continue;
const pos = parts.orbits.propagatePosition(sat.satrec, now);
if (!pos) continue;
const cartesian = Cesium.Cartesian3.fromDegrees(
pos.longitude,
pos.latitude,
pos.altitude,
);
const point = layerState._points.get(noradId);
if (point) {
point.position = cartesian;
updated++;
}
if (_sample(sat, nowMs)) updated++;
}
return updated;
}
/**
* Sample one satellite's orbit at `atMs` into its reused sample.
* @returns {boolean} Whether SGP4 had a state for that time.
*/
function _sample(sat, atMs) {
const sample = sampleOrbit(sat.satrec, atMs, sat.orbitSample);
if (!sample) return false;
sat.orbitSample = sample;
return true;
}
/**
* Move every shown point to where its satellite is at the world time,
* reckoned from its last sample, so points glide every frame between
* samples instead of stepping once a second. A core sample more than
* ORBIT_SAMPLE_HORIZON_MS from the world time (time playing fast, or a
* seek) is taken again first; dense extras are resampled by their own
* round-robin. A hidden point is moved when it is shown again, and the
* tracked satellite is placed by its per-frame path.
* @param {number} nowMs World time, epoch ms.
*/
function _reckonPoints(nowMs) {
const gmst = gstime(new Date(nowMs));
for (const [noradId, point] of layerState._points) {
if (!point.show || noradId === layerState._trackedNorad) continue;
const sat = layerState._catalog.get(noradId);
if (!sat || sat.reckonedAtMs === nowMs) continue;
let sample = sat.orbitSample;
if (
sat.group !== 'dense' &&
(!sample || Math.abs(nowMs - sample[0]) > ORBIT_SAMPLE_HORIZON_MS)
)
sample = _sample(sat, nowMs) ? sat.orbitSample : null;
if (!sample || Math.abs(nowMs - sample[0]) > ORBIT_RECKON_LIMIT_MS)
continue;
point.position = reckonEarthFixed(sample, nowMs, gmst, _reckoned); // setter clones
sat.reckonedAtMs = nowMs;
}
}
/**
* Shared scene.preRender tick (single definition for init + enable):
* - core fleet propagation at 200ms-tracked / 1s-idle cadence,
* - dense extras on a per-frame round-robin budget,
* - core fleet SGP4 samples at 200ms-tracked / 1s-idle cadence,
* - dense extras sampled on a per-frame round-robin budget,
* - every point reckoned from its sample each frame (motion.js),
* - tracked satellite's point primitive per frame (WS-D2),
* - orbit ring GMST re-alignment every ~1s (WS-D1).
*/
@@ -218,7 +257,12 @@ export function createRendering({
layerState._lastPropagation = now;
}
if (layerState._params.showPoints) parts.catalog._propagateDenseChunk();
if (layerState._params.showPoints) {
const worldMs = layerState.now();
parts.catalog._propagateDenseChunk(worldMs - layerState._lastReckonMs);
layerState._lastReckonMs = worldMs;
_reckonPoints(worldMs);
}
// Keep the tracked dot on the per-frame epoch shared with label + camera —
// runs after _propagateAll so the per-frame sample wins over the 200ms one.
@@ -348,6 +392,7 @@ export function createRendering({
_updateOrbitPathRotations,
_hideOrbitPath,
_propagateAll,
_reckonPoints,
_preRenderTick,
_updatePointFocus,
applySatellitePointFocusDeemphasis,
+4
View File
@@ -64,6 +64,10 @@ export function createState({ services }) {
state._lastPropagation = 0;
// The world time of the last frame that reckoned the points (motion.js),
// NaN before the first.
state._lastReckonMs = NaN;
state._lastRingRotation = 0;
state._lastFocusUpdate = 0;
+1 -1
View File
@@ -440,7 +440,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
// Tracked entity position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
// Falls back to the point primitive's 1s-throttled position if SGP4 fails.
// Falls back to the point primitive's reckoned position if SGP4 fails.
const positionProperty = new Cesium.CallbackProperty(() => {
const pos = _getTrackedFramePosition();
return pos ? layerState._trackedFrameCartesian : point.position;
+242
View File
@@ -0,0 +1,242 @@
import * as Cesium from 'cesium';
import {
getRegisteredTransitFeed,
transitRouteLabel,
} from '../../data/transitFeeds.js';
import { displayMotion } from './movement.js';
/**
* `previous` when it holds each of `next`'s values, else a frozen copy of
* `next`: a part of a snapshot that did not change is the one read before.
* `next` is a draft, filled again on every read.
*/
function reuse(previous, next) {
if (!previous) return Object.freeze({ ...next });
for (const name in next)
if (!Object.is(previous[name], next[name]))
return Object.freeze({ ...next });
return previous;
}
/**
* Read access to one vehicle, and a hold on it for a first-person view.
*
* `getSelectedVehicle()` and `getCockpitSubject()` describe the selected
* vehicle and the held one as a frozen snapshot, read again on each call:
* where it is drawn, how fast it moves and how that is known. A call while
* nothing in it changed returns the snapshot it returned before, and a part
* that did not change (its feed, its stop) is the same object in the next
* one, so a view can read it on every frame. Transit has no route shapes or
* stops, so a snapshot names only the vehicle's last reported stop.
* `setCockpitSubject(key)` holds a vehicle: its sprite, 3D model, card,
* trail and detection box are hidden, it keeps moving when it is out of the camera's
* view, its feed stays polled, and clicks and Escape no longer change the
* selection. The hold ends with `setCockpitSubject(null)`, and on
* its own when the vehicle is removed or the layer is turned off.
* `focusVehicle(key)` selects a vehicle, as a click does. A snapshot's
* `selectedAtMs` is when the user last selected the selected vehicle (a
* click, or `focusVehicle`), even again. It is null for any other vehicle,
* after a deselection, and for a vehicle selected only by a hold: a hold is
* not a user's selection.
*
* @param {object} context The layer's state, parts and services.
* @returns {{methods: object}}
*/
export function createTransitCockpitSubject({ state, parts, services }) {
const liftM = Number.isFinite(services.ground?.GROUND_FLOOR_LIFT_M)
? services.ground.GROUND_FLOOR_LIFT_M
: 0;
const finiteOrNull = (value) =>
typeof value === 'number' && Number.isFinite(value) ? value : null;
/** Each vehicle's last snapshot, returned again while nothing changed. */
const views = new WeakMap();
/** The drafts vehicleView fills on every read (reuse). */
const draft = {
view: {},
feed: {},
position: {},
motion: {},
stop: {},
provenance: {},
};
/** The feed in use, else the registry's entry for it. */
function feedEntry(feedId) {
return state._activeFeeds.get(feedId) || getRegisteredTransitFeed(feedId);
}
function feedOf(feed, previous) {
if (!feed) return null;
const next = draft.feed;
next.id = feed.id;
next.name = feed.name ?? null;
next.operator = feed.operator ?? null;
next.region = feed.region ?? null;
next.attribution = feed.attribution ?? null;
next.license = feed.license ?? null;
next.licenseUrl = feed.licenseUrl ?? null;
return reuse(previous, next);
}
const scratchCartographic = new Cesium.Cartographic();
/**
* The floor under the vehicle where playback draws it, without the shared
* lift: the drawn marker's height while the frame pass places it (in view,
* or held), which near the ground follows the terrain between reports;
* else its segment's two reports' floors at the playback fraction. Null
* while either floor is unknown, as on cold terrain, so a view waits for
* the surface. Not `entry.heightM`, the floor at the newest report, which
* playback has not reached yet.
*/
function drawnFloorOf(entry) {
const segment = entry.segment;
if (!segment || entry.heightPending) return null;
const placed =
entry.surfaceReady === true &&
entry.hasRendered &&
entry.marker?.position &&
(state._visible.has(entry) || entry.key === state._cockpitSubjectKey);
if (placed) {
const drawn = Cesium.Cartographic.fromCartesian(
entry.marker.position,
undefined,
scratchCartographic,
);
if (drawn) return drawn.height - liftM;
}
const from = segment.from?.h;
const to = segment.to?.h;
if (!Number.isFinite(from) || !Number.isFinite(to)) return null;
const f = Number.isFinite(segment.fraction)
? Math.max(0, Math.min(1, segment.fraction))
: 1;
return from + (to - from) * f - liftM;
}
/** The vehicle as a frozen snapshot (see the module comment), or null. */
function vehicleView(entry) {
if (!entry?.record) return null;
const previous = views.get(entry);
const record = entry.record;
const sample = entry.sample ?? null;
const feed = feedEntry(entry.feedId);
const reported = finiteOrNull(record.speedMps);
const derived = finiteOrNull(sample?.segmentSpeedMps);
const status = state._feedStatus.get(entry.feedId);
const position = draft.position;
position.latitude = finiteOrNull(sample?.lat) ?? record.lat;
position.longitude = finiteOrNull(sample?.lon) ?? record.lon;
position.groundHeightM = drawnFloorOf(entry);
position.atMs = finiteOrNull(sample?.displayT);
const motion = draft.motion;
motion.reportedSpeedMps = reported;
motion.derivedSpeedMps = derived;
motion.speedSource =
reported !== null ? 'reported' : derived !== null ? 'derived' : null;
motion.courseDeg = finiteOrNull(entry.courseDeg);
motion.reportedBearingDeg = finiteOrNull(record.bearing);
motion.segmentCourseDeg = finiteOrNull(sample?.segmentCourseDeg);
motion.phase = sample?.phase ?? null;
motion.word = displayMotion(entry, Date.now()).word;
motion.reportAgeMs = finiteOrNull(sample?.latestReportAgeMs);
motion.shownBehindMs = finiteOrNull(sample?.actualDelayMs);
motion.feedStale = status?.stale === true;
const stop = draft.stop;
stop.stopId = record.stopId || null;
stop.status = record.status || null;
const provenance = draft.provenance;
provenance.positionSource = 'gps';
provenance.timestampSource = record.timestampSource ?? null;
const view = draft.view;
view.key = entry.key;
view.feedId = entry.feedId;
view.selectedAtMs =
state._selectedKey === entry.key ? state._selectedAtMs : null;
view.id = String(record.id ?? '');
view.routeId = record.routeId || null;
view.routeLabel =
(feed && record.routeId
? transitRouteLabel(feed, record.routeId)
: null) || null;
view.tripId = record.tripId || null;
view.directionId = record.directionId ?? null;
view.label = record.label || null;
view.mode = entry.mode ?? null;
view.modeInferred = entry.modeInferred === true;
view.feed = feedOf(feed, previous?.feed);
view.position = reuse(previous?.position, position);
view.motion = reuse(previous?.motion, motion);
view.stop = reuse(previous?.stop, stop);
view.provenance = reuse(previous?.provenance, provenance);
const snapshot = reuse(previous, view);
views.set(entry, snapshot);
return snapshot;
}
/** Show or hide a vehicle's sprite and trail for the hold. */
function repaint(entry) {
if (!entry?.marker) return;
if (entry.key === state._cockpitSubjectKey) entry.marker.show = false;
else parts.rendering.placeSample(entry);
parts.rendering.schedulePlayback(entry);
parts.trails.update();
state._detectRevision += 1;
}
const methods = {
/** The selected vehicle (see createTransitCockpitSubject), or null. */
getSelectedVehicle() {
return vehicleView(state._vehicles.get(state._selectedKey));
},
/** The held vehicle, or null when none is held. */
getCockpitSubject() {
return vehicleView(state._vehicles.get(state._cockpitSubjectKey));
},
/**
* Hold the vehicle `key` for a first-person view, or release the hold
* with null. A vehicle it holds is selected, if it was not already.
* @param {string|null} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
setCockpitSubject(key) {
const previous = state._vehicles.get(state._cockpitSubjectKey);
if (key === null || key === undefined) {
state._cockpitSubjectKey = null;
// The hold kept it in play out of view: it leaves until the next
// visibility sweep finds it in view again.
if (previous) {
state._visible.delete(previous);
parts.rendering.requestVisibility();
}
repaint(previous);
parts.selection.refreshSelectedCard(true);
return true;
}
const entry = state._vehicles.get(key);
if (!entry?.marker) return false;
if (state._selectedKey !== key) parts.selection.selectVehicle(key);
state._cockpitSubjectKey = key;
state._visible.add(entry);
if (previous && previous !== entry) repaint(previous);
repaint(entry);
parts.selection.refreshSelectedCard(true);
return true;
},
/**
* Select the vehicle `key`, as a click on it does.
* @param {string} key
* @returns {boolean} False for a vehicle the layer does not show.
*/
focusVehicle(key) {
if (!state._vehicles.get(key)?.marker) return false;
parts.selection.selectVehicle(key, { byUser: true });
return true;
},
};
return { methods, vehicleView };
}
+3
View File
@@ -10,6 +10,7 @@ import { createQueries } from './queries.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { createTesting } from './testing.js';
import { createTransitCockpitSubject } from './cockpitSubject.js';
import { TRANSIT_POLL_MS } from './policy.js';
/**
@@ -54,12 +55,14 @@ export function createTransitLayer({
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
parts.testing = createTesting(context);
parts.cockpit = createTransitCockpitSubject(context);
return Object.assign(
{ updateInterval: TRANSIT_POLL_MS },
parts.lifecycle.methods,
parts.queries.methods,
parts.controls.methods,
parts.cockpit.methods,
parts.testing,
);
}
+17 -1
View File
@@ -16,6 +16,7 @@ import {
import {
transitModeFor,
transitModeResolved,
transitModelRouteType,
} from '../../data/transitFeeds.js';
import {
attachFloorToPlace,
@@ -71,6 +72,8 @@ export function createIngestion({ state, services, parts, source }) {
function removeVehicle(key) {
const entry = state._vehicles.get(key);
if (!entry) return;
// A first-person view on it loses its subject (cockpitSubject.js).
if (state._cockpitSubjectKey === key) state._cockpitSubjectKey = null;
if (state._selectedKey === key) parts.selection.clearSelection();
if (entry.marker) entry.markerCollection?.remove(entry.marker);
entry.marker = null;
@@ -83,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;
}
@@ -220,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 =
@@ -265,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);
@@ -316,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,
+3
View File
@@ -147,10 +147,12 @@ 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();
state._selectedKey = null;
state._cockpitSubjectKey = null;
state._lastUpdate = null;
state._error = null;
state._limitWarned = false;
@@ -241,6 +243,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();
+371
View File
@@ -7,9 +7,13 @@ import {
FEED_STALE_AFTER_MS,
MISSED_POLLS_TO_DROP,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_ID,
VEHICLE_MAX_FIX_AGE_MS,
} 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,
@@ -65,6 +69,25 @@ function snapshot(
};
}
/** A camera's place and frame looking straight down from `altitude` over `at`. */
function lookingDown(at, altitude) {
const positionWC = Cesium.Cartesian3.fromDegrees(at.lon, at.lat, altitude);
const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
positionWC,
new Cesium.Cartesian3(),
);
return {
positionWC,
directionWC: Cesium.Cartesian3.negate(up, new Cesium.Cartesian3()),
upWC: Cesium.Cartesian3.UNIT_Z,
frustum: {
computeCullingVolume: () => ({
computeVisibility: () => Cesium.Intersect.INSIDE,
}),
},
};
}
/** A vehicle record as the proxy emits it, with its timestamp source resolved. */
function vehicle(id, lat, lon, atSeconds, extra = {}) {
return {
@@ -159,6 +182,11 @@ function harness(
east: at.lon + 0.1,
north: at.lat + 0.1,
},
// 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 };
@@ -219,6 +247,7 @@ function harness(
viewRect.north,
);
},
...(fleet ? lookingDown(at, altitude) : {}),
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
@@ -265,6 +294,8 @@ function harness(
const layer = createTransitLayer({
source,
services: {
...(fleet ? { fleet } : {}),
...(placement ? { placement: layerPlacement(placement, 'transit') } : {}),
ground,
mesh: {
sampleMeshFloorCells(scene, points, options) {
@@ -727,6 +758,27 @@ test('disable aborts in-flight work and a response that lands late is ignored',
assert.equal(app.vehicles().length, 1);
});
test('a held vehicle with no floor yet tells its view no height', async (t) => {
// Not the ellipsoid: a first-person view waits for the surface instead.
const app = harness(t, { floorAt: () => undefined });
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[vehicle('bus-1', 42.36, -71.06, Date.now() / 1000)],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
const entry = app.vehicles()[0];
assert.equal(entry.heightPending, true, 'it has nothing to stand on');
assert.ok(app.layer.setCockpitSubject(entry.key) !== false);
assert.equal(app.layer.getCockpitSubject().position.groundHeightM, null);
});
test('a vehicle waits for its floor rather than standing on the ellipsoid', async (t) => {
// The shared ground-floor system answers from the rendered mesh cell or the
// real DEM cell; until one of them is warm there is no honest height to draw
@@ -1109,6 +1161,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();
@@ -1774,11 +1930,19 @@ test('a segment climbs from the ground it left to the ground it reaches', async
assert.ok(Math.abs(entry.heightM - 101.5) < 1, 'the destination is uphill');
const height = () =>
Cesium.Cartographic.fromCartesian(entry.marker.position).height;
// A first-person view reads the floor where the vehicle is drawn, not the
// newest report's floor uphill.
app.layer.setCockpitSubject(entry.key);
const floor = () => app.layer.getCockpitSubject().position.groundHeightM;
app.run(400);
assert.ok(
height() < 30,
`still on the ground it is drawn on, got ${height().toFixed(1)} m`,
);
assert.ok(
Math.abs(floor() + 1.5 - height()) < 1,
`its snapshot stands where it is drawn, got ${floor().toFixed(1)} m`,
);
// Halfway along the segment it is halfway up; at the end, on the high ground.
const firstFixAt = start - AGE_MS;
@@ -1792,6 +1956,7 @@ test('a segment climbs from the ground it left to the ground it reaches', async
Math.abs(height() - 101.5) < 1.5,
`and arrives on the high ground, got ${height().toFixed(1)} m`,
);
assert.ok(Math.abs(floor() - 100) < 1.5, 'and so does its snapshot');
});
test('a lone impossible fix leaves the displayed vehicle and health untouched', async (t) => {
const app = harness(t, { floorAt: () => 5 });
@@ -4142,3 +4307,209 @@ test('the prompt names the altitude the gate opens at, not 3,000 km', async (t)
'Fly below 2,850 km to a covered region',
);
});
/** A bus running north a step a poll, polled `polls` times; its key. */
async function busRunningNorth(app, polls = 4, extra = {}) {
let step = 0;
app.serve('mbta', () => ({
status: 200,
body: snapshot(
'mbta',
'MBTA',
[
vehicle('bus-1', 42.36 + step * 0.001, -71.06, reported(), {
stopId: 'place-1',
status: 'IN_TRANSIT_TO',
...extra,
}),
],
{ fetchedAt: Date.now() },
),
}));
app.layer.enable(app.viewer);
await app.layer.update();
app.settle();
for (let i = 0; i < polls; i += 1) {
step += 1;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
}
return 'mbta:bus-1';
}
test('the selected vehicle reads as a snapshot of its place, motion and source', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app, 4, { speedMps: 9 });
assert.equal(app.layer.getSelectedVehicle(), null);
app.layer._transitPartsForTest().selection.selectVehicle(key);
const view = app.layer.getSelectedVehicle();
assert.ok(Object.isFrozen(view));
assert.equal(view.key, key);
assert.equal(view.feedId, 'mbta');
assert.equal(view.id, 'bus-1');
assert.equal(view.routeId, '1');
assert.equal(typeof view.mode, 'string');
assert.ok(view.feed.attribution, 'the feed names its credit');
assert.equal(view.motion.reportedSpeedMps, 9);
assert.equal(view.motion.speedSource, 'reported');
assert.equal(view.provenance.positionSource, 'gps');
assert.deepEqual(view.stop, { stopId: 'place-1', status: 'IN_TRANSIT_TO' });
const entry = app.vehicles()[0];
// Where it is drawn, without the shared lift (read back from the marker).
assert.ok(
Math.abs(view.position.groundHeightM - (entry.heightM - 1.5)) < 1e-3,
);
assert.ok(Number.isFinite(view.position.latitude));
});
test('a vehicle read again while nothing changed is the snapshot read before', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
app.layer._transitPartsForTest().selection.selectVehicle(key);
const first = app.layer.getSelectedVehicle();
assert.equal(app.layer.getSelectedVehicle(), first, 'the same snapshot');
// It moves on: a new snapshot at its new place, what did not change kept.
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
const moved = app.layer.getSelectedVehicle();
assert.notEqual(moved, first, 'a new snapshot');
assert.ok(Object.isFrozen(moved) && Object.isFrozen(moved.position));
assert.ok(moved.position.latitude > first.position.latitude, 'moved');
assert.equal(moved.feed, first.feed);
assert.equal(moved.stop, first.stop);
assert.equal(moved.provenance, first.provenance);
assert.equal(app.layer.getSelectedVehicle(), moved);
});
test('a held vehicle draws no 3D model either; let go, its model draws again', async (t) => {
const models = await fleetModelFakes(t);
const app = harness(t, { fleet: models.fleet, altitude: 1_000 });
const key = await busRunningNorth(app);
const [entry] = app.vehicles();
assert.notEqual(entry.mode, 'unknown', 'a mode its model is chosen by');
// The throttled sweep runs; a model's load answers off the frame and the
// next frames place it.
const frames = async () => {
app.advance(250);
app.settle();
for (let i = 0; i < 8; i += 1) await Promise.resolve();
app.settle();
};
await frames();
assert.equal(models.drawn(key).length, 1, 'near the camera: its model');
assert.equal(entry.modelOwnsVisual, true);
assert.equal(entry.marker.show, false, 'its icon hands over');
assert.equal(app.layer.setCockpitSubject(key), true);
app.frame();
// The view's eye is inside the vehicle.
assert.equal(models.drawn(key).length, 0, 'no model');
assert.equal(entry.modelOwnsVisual, false);
assert.equal(entry.marker.show, false, 'and no icon');
await frames();
assert.equal(models.drawn(key).length, 0, 'not on a later frame either');
assert.equal(entry.marker.show, false);
assert.equal(app.layer.setCockpitSubject(null), true);
await frames();
assert.equal(models.drawn(key).length, 1, 'let go: its model again');
assert.equal(entry.modelOwnsVisual, true);
assert.equal(entry.marker.show, false);
});
test('selectedAtMs is the user’s selection time; a hold and a deselection leave none', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
// A vehicle only a hold selected reports none.
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
app.layer.setCockpitSubject(null);
assert.equal(app.layer.setCockpitSubject(null), true, 'twice is harmless');
assert.equal(app.state()._selectedKey, key);
// The user's selection stamps it, again on a re-selection.
assert.equal(app.layer.focusVehicle(key), true);
const first = app.layer.getSelectedVehicle().selectedAtMs;
assert.ok(Number.isFinite(first));
app.run(1000);
app.layer.focusVehicle(key);
assert.ok(app.layer.getSelectedVehicle().selectedAtMs > first);
// Deselected, then held: none.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, null);
assert.equal(app.state()._selectedAtMs, null);
app.layer.setCockpitSubject(key);
assert.equal(app.layer.getCockpitSubject().selectedAtMs, null);
});
test('a held vehicle hides, keeps moving out of view, and lets go when it goes', async (t) => {
const app = harness(t);
const key = await busRunningNorth(app);
assert.equal(app.layer.setCockpitSubject('mbta:nope'), false);
assert.equal(app.layer.setCockpitSubject(key), true);
assert.equal(app.state()._selectedKey, key, 'holding selects it');
assert.equal(app.layer.getCockpitSubject().key, key);
assert.equal(
app.overlaySources.has(TRANSIT_SELECTED_OVERLAY_SOURCE_ID),
false,
'no card',
);
const [entry] = app.vehicles();
app.frame();
assert.equal(entry.marker.show, false);
// The camera's view leaves it, as a view from inside it does: it plays on.
app.lookAt({ west: 10, south: 10, east: 11, north: 11 });
app.settle();
assert.equal(
app.layer._transitPartsForTest().rendering.vehicleInView(entry),
true,
);
const before = app.layer.getCockpitSubject().position.latitude;
app.run(TRANSIT_POLL_MS);
await app.layer.update();
app.settle();
app.run(TRANSIT_POLL_MS);
assert.ok(
app.layer.getCockpitSubject().position.latitude > before,
'still moving',
);
// Escape and clicks are the view's while it holds the vehicle.
globalThis.document.dispatchEvent(
Object.assign(new Event('keydown'), { key: 'Escape' }),
);
assert.equal(app.state()._selectedKey, key);
assert.equal(app.layer.setCockpitSubject(null), true);
assert.equal(app.layer.getCockpitSubject(), null);
// Let go, it is out of play until a sweep finds it in view.
assert.equal(app.state()._visible.has(entry), false, 'out of play');
app.lookAt({
west: -71.2,
south: 42.2,
east: -70.9,
north: 42.5,
});
app.advance(250);
app.settle();
assert.equal(entry.marker.show, true, 'shown again');
assert.equal(app.layer.focusVehicle('mbta:nope'), false);
assert.equal(app.layer.focusVehicle(key), true);
app.layer.setCockpitSubject(key);
app.silence('mbta');
app.serve('mbta', () => ({
status: 200,
body: snapshot('mbta', 'MBTA', [], { fetchedAt: Date.now() }),
}));
for (let i = 0; i < MISSED_POLLS_TO_DROP + 1; i += 1) {
app.run(TRANSIT_POLL_MS);
await app.layer.update();
}
assert.equal(app.vehicles().length, 0, 'the vehicle is gone');
assert.equal(app.state()._cockpitSubjectKey, null);
assert.equal(app.layer.getCockpitSubject(), null);
});
+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
@@ -189,9 +189,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',
});
@@ -526,9 +531,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'),
});
@@ -536,9 +546,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',
});
+49 -13
View File
@@ -4,8 +4,10 @@ import {
perspectiveProjectedRotation,
} from '../../data/iconOrientation.js';
import {
PLACED_WAKE_MS,
updatePlayback,
applyDisplayCourse,
playbackMoving,
syncPlayback,
} from './movement.js';
import {
@@ -106,8 +108,12 @@ export function createRendering({ state, services, parts }) {
);
entry.surfaceReady = !!known;
entry.heightPending = !known;
// A vehicle a first-person view rides keeps moving, unseen.
entry.marker.show =
!!known && vehicleInView(entry) && !entry.modelOwnsVisual;
!!known &&
vehicleInView(entry) &&
!entry.modelOwnsVisual &&
entry.key !== state._cockpitSubjectKey;
if (known) {
entry.marker.position = state._scratchCartesian;
entry.hasRendered = true;
@@ -161,7 +167,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) &&
@@ -174,7 +180,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;
@@ -183,9 +201,10 @@ export function createRendering({ state, services, parts }) {
placeSample(entry);
schedulePlayback(entry);
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),
);
}
}
@@ -198,7 +217,7 @@ export function createRendering({ state, services, parts }) {
* @returns {boolean}
*/
function vehicleInView(entry) {
return state._visible.has(entry);
return state._visible.has(entry) || entry.key === state._cockpitSubjectKey;
}
/** Cesium colour for a preset tuple, cached per profile+mode. */
@@ -437,7 +456,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);
@@ -489,7 +509,7 @@ export function createRendering({ state, services, parts }) {
});
}
/** Hand an entry's visual back to its icon. */
/** Hand an entry's visual back to its icon, unless a view rides it. */
function handBack(entry) {
if (!entry.modelOwnsVisual) return;
entry.modelOwnsVisual = false;
@@ -497,7 +517,8 @@ export function createRendering({ state, services, parts }) {
entry.marker.show =
vehicleInView(entry) &&
!entry.heightPending &&
entry.surfaceReady !== false;
entry.surfaceReady !== false &&
entry.key !== state._cockpitSubjectKey;
}
function updateModels() {
@@ -526,15 +547,26 @@ 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 =
MODE_CESIUM_COLORS[entry.mode] || MODE_CESIUM_COLORS.unknown;
}
item.position = entry.marker.position;
item.headingDeg = Number.isFinite(entry.courseDeg) ? entry.courseDeg : 0;
item.show = !entry.heightPending && entry.surfaceReady !== false;
// A vehicle a first-person view rides draws no model: the camera is
// inside it (cockpitSubject.js).
item.show =
!entry.heightPending &&
entry.surfaceReady !== false &&
entry.key !== state._cockpitSubjectKey;
next.set(entry.key, item);
}
for (const [key, item] of modelItems)
@@ -641,7 +673,10 @@ export function createRendering({ state, services, parts }) {
} else if (frustum)
inFrustum =
frustum.computeVisibility(sphere) !== Cesium.Intersect.OUTSIDE;
const visible = (frustum || bounds) && horizon && inFrustum;
// A held vehicle (cockpitSubject.js) is the camera's own: it stays in
// play wherever the view looks.
const held = entry.key === state._cockpitSubjectKey;
const visible = held || ((frustum || bounds) && horizon && inFrustum);
const visibility = (entry.visibility ||= {});
visibility.bounds = bounds;
visibility.boundsApplied = !frustum;
@@ -666,6 +701,7 @@ export function createRendering({ state, services, parts }) {
}
}
entry.marker.show =
!held &&
visible &&
!entry.heightPending &&
entry.surfaceReady !== false &&
+21 -3
View File
@@ -48,6 +48,12 @@ export function createSelection({ state, services, parts }) {
? state._vehicles.get(state._selectedKey)
: null;
if (!entry) return;
// A vehicle a first-person view rides shows no card.
if (entry.key === state._cockpitSubjectKey) {
state._selectedCardText = null;
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
return;
}
const now = Date.now();
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
return;
@@ -93,6 +99,7 @@ export function createSelection({ state, services, parts }) {
: null;
parts.trails.clear();
state._selectedKey = null;
state._selectedAtMs = null;
state._selectedCardText = null;
state._detectRevision += 1;
// Cleared first: the styling path reads the selection from state.
@@ -100,11 +107,18 @@ export function createSelection({ state, services, parts }) {
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
}
function selectVehicle(key) {
/**
* Select a vehicle. `byUser` marks a selection the user made (a click, or
* focusVehicle), even of the selected vehicle again: its time is the
* snapshot's `selectedAtMs` (cockpitSubject.js). A first-person view's hold
* selects without it.
*/
function selectVehicle(key, { byUser = false } = {}) {
clearSelection();
const entry = state._vehicles.get(key);
if (!entry?.marker) return;
state._selectedKey = key;
if (byUser) state._selectedAtMs = Date.now();
state._detectRevision += 1;
parts.rendering.paintSelected(entry, true);
parts.trails.select(entry);
@@ -113,6 +127,8 @@ export function createSelection({ state, services, parts }) {
}
function onKeyDown(event) {
// While a first-person view rides the vehicle, Escape is the view's.
if (state._cockpitSubjectKey) return;
if (event.key === 'Escape' && state._selectedKey) clearSelection();
}
@@ -125,6 +141,8 @@ export function createSelection({ state, services, parts }) {
// Ambient selection never competes for a pointer a tool has claimed:
// placing a draw vertex on top of a bus must not also select the bus.
if (!isPointerFree()) return;
// A held vehicle keeps the selection until its view lets it go.
if (state._cockpitSubjectKey) return;
const scene = viewer.scene;
// Pick buffers precede post-processing. Map a sensor pixel back through
// the active shader's barrel distortion and quantization before picking.
@@ -181,11 +199,11 @@ export function createSelection({ state, services, parts }) {
typeof primitiveId === 'string' &&
state._vehicles.has(primitiveId)
) {
selectVehicle(primitiveId);
selectVehicle(primitiveId, { byUser: true });
return;
}
if (typeof picked.id === 'string' && state._vehicles.has(picked.id)) {
selectVehicle(picked.id);
selectVehicle(picked.id, { byUser: true });
return;
}
}
+9
View File
@@ -95,6 +95,15 @@ export function createState({ services }) {
/** @type {string|null} */
state._selectedKey = null;
/** When the user last selected a vehicle, even the selected one (ms). */
state._selectedAtMs = null;
/**
* The vehicle a first-person view holds (cockpitSubject.js), or null: its
* sprite, 3D model, card, trail and detection box are hidden, and it keeps
* moving out of the camera's view.
* @type {string|null}
*/
state._cockpitSubjectKey = null;
state._selectedCardAt = 0;
/** The card text last published, so an unchanged card is not re-sent. */
state._selectedCardText = null;
+24 -10
View File
@@ -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) {
@@ -205,6 +198,24 @@ 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 Cesium.Cartesian3.fromDegrees(
sample.lon,
sample.lat,
heightM,
undefined,
out,
);
}
if (!nearGround) {
const a = entry.fromCart,
b = entry.toCart,
@@ -235,8 +246,11 @@ export function createTrails({ state, services, parts, source }) {
}
function update() {
if (!selected || !renderer) return;
// A first-person view on the vehicle rides where its trail would start.
renderer.setVisible(
state._enabled && state._vehicles.get(selected.key) === selected,
state._enabled &&
state._vehicles.get(selected.key) === selected &&
selected.key !== state._cockpitSubjectKey,
);
renderer.setDisplaySample(selected.sample, selected.marker?.position);
}
+4
View File
@@ -101,6 +101,10 @@ export function createViewport({ state, services, parts }) {
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
}
}
// A vehicle a first-person view rides keeps its feed polled.
const held = state._vehicles.get(state._cockpitSubjectKey);
if (held && state._activeFeeds.has(held.feedId))
desired.set(held.feedId, state._activeFeeds.get(held.feedId));
for (const feedId of [...state._activeFeeds.keys()]) {
if (!desired.has(feedId)) {
state._inFlight.get(feedId)?.controller.abort();
+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,20 +52,22 @@ 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),
@@ -65,7 +76,7 @@ export function createCards({
components.rendering.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
gapPx: 10,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 26),
details: parts.length ? [parts.join(' · ')] : [],
selected: false,
@@ -76,22 +87,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)}`);
@@ -106,7 +121,7 @@ export function createCards({
components.rendering.getVisual(record).billboard?.position ||
components.rendering.getVisual(record).position,
gapPx: 12,
accent: accentForVesselType(record.type),
accent: vesselAccent(record, aid),
title: trimHudValue(displayVesselName(record), 32),
details,
selected: true,
@@ -114,6 +129,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) {
@@ -129,9 +158,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
+4 -1
View File
@@ -101,7 +101,10 @@ test('the subject says whether its track is the heading or the course', () => {
test('a vessel without identity or position is not a subject', () => {
assert.equal(vesselCockpitInfo(null), null);
assert.equal(vesselCockpitInfo({ lat: 1, lon: 1 }), null);
assert.equal(vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }), null);
assert.equal(
vesselCockpitInfo({ id: '1', mmsi: '1', lat: 'x', lon: 1 }),
null,
);
});
test('a vessel missing from recent refreshes reads as stale', () => {
+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,
+5 -2
View File
@@ -39,8 +39,9 @@ export function createIngestion({
* @returns {Promise<boolean>}
*/
async function loadAt(atMs, { signal = null, replace = false } = {}) {
// Whatever polls or loads for another time no longer applies.
if (replace && feed.loading) {
// Whatever polls or loads for another time no longer applies: the
// timeline asks for one time at a time.
if (feed.loading) {
feed.abort?.abort();
feed.loading = false;
feed.abort = null;
@@ -209,6 +210,7 @@ export function createIngestion({
reference: record.reference,
lat: record.latitude,
lon: record.longitude,
fixes: record.fixes,
name: record.name,
imo: record.imo,
type: record.type,
@@ -218,6 +220,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.billboardCollection = 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 = [];
@@ -211,6 +213,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);
@@ -232,6 +235,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();
+72 -23
View File
@@ -1,14 +1,39 @@
/**
* Where a vessel is at world time `tMs` while the layer follows the world
* clock: between the fix it moved from and the fix it moved to, along the
* great circle; at the earlier fix before it, at the newer fix after it. A
* vessel is never projected past its newest fix.
* clock: on its own fixes around the time when its record carries them
* (`fixes`, see src/time/timelineFixes.js), else between the fix it moved
* from and the fix it moved to; along the great circle between two fixes, at
* the first before them and at the last after them. A vessel is never
* projected past its newest fix.
* @param {{lat: number, lon: number, motion?: {fromLat: number, fromLon: number,
* fromMs: number, toLat: number, toLon: number, toMs: number}|null}} record
* @param {number} tMs
* @returns {{lat: number, lon: number}}
*/
export function vesselPositionAt(record, tMs) {
const fixes = record?.fixes;
if (fixes?.length >= 2 && Number.isFinite(tMs)) {
const first = fixes[0];
const last = fixes[fixes.length - 1];
if (tMs <= first.atMs) return { lat: first.lat, lon: first.lon };
if (tMs >= last.atMs) return { lat: last.lat, lon: last.lon };
let low = 1;
let high = fixes.length - 1;
while (low < high) {
const mid = (low + high) >> 1;
if (fixes[mid].atMs < tMs) low = mid + 1;
else high = mid;
}
const a = fixes[low - 1];
const b = fixes[low];
return greatCircleAt(
a.lat,
a.lon,
b.lat,
b.lon,
b.atMs > a.atMs ? (tMs - a.atMs) / (b.atMs - a.atMs) : 1,
);
}
const motion = record?.motion;
if (
!motion ||
@@ -30,33 +55,57 @@ export function vesselPositionAt(record, tMs) {
const RAD = Math.PI / 180;
/** The point `fraction` of the way from one position to another. */
/** The point `fraction` of the way from one position to another. It runs
* for every drawn vessel as the clock plays, so it builds no arrays. */
function greatCircleAt(lat1, lon1, lat2, lon2, fraction) {
const p1 = unit(lat1, lon1);
const p2 = unit(lat2, lon2);
const dot = Math.min(
1,
Math.max(-1, p1[0] * p2[0] + p1[1] * p2[1] + p1[2] * p2[2]),
);
const phi1 = lat1 * RAD;
const lambda1 = lon1 * RAD;
const phi2 = lat2 * RAD;
const lambda2 = lon2 * RAD;
const cos1 = Math.cos(phi1);
const cos2 = Math.cos(phi2);
const x1 = cos1 * Math.cos(lambda1);
const y1 = cos1 * Math.sin(lambda1);
const z1 = Math.sin(phi1);
const x2 = cos2 * Math.cos(lambda2);
const y2 = cos2 * Math.sin(lambda2);
const z2 = Math.sin(phi2);
const dot = Math.min(1, Math.max(-1, x1 * x2 + y1 * y2 + z1 * z2));
const angle = Math.acos(dot);
if (angle < 1e-12) return { lat: lat2, lon: lon2 };
const a = Math.sin((1 - fraction) * angle) / Math.sin(angle);
const b = Math.sin(fraction * angle) / Math.sin(angle);
const x = a * p1[0] + b * p2[0];
const y = a * p1[1] + b * p2[1];
const z = a * p1[2] + b * p2[2];
const sinAngle = Math.sin(angle);
const a = Math.sin((1 - fraction) * angle) / sinAngle;
const b = Math.sin(fraction * angle) / sinAngle;
const x = a * x1 + b * x2;
const y = a * y1 + b * y2;
const z = a * z1 + b * z2;
return {
lat: Math.atan2(z, Math.hypot(x, y)) / RAD,
lon: Math.atan2(y, x) / RAD,
};
}
function unit(lat, lon) {
const phi = lat * RAD;
const lambda = lon * RAD;
return [
Math.cos(phi) * Math.cos(lambda),
Math.cos(phi) * Math.sin(lambda),
Math.sin(phi),
];
// Whether each fixes array moves, read once per array: records keep theirs
// until a snapshot brings new ones.
const moving = new WeakMap();
/**
* Whether a vessel's fixes (`record.fixes`) put it in more than one place,
* so following the clock moves it; a moored vessel's do not.
* @param {Array<{lat: number, lon: number}>|null|undefined} fixes
* @returns {boolean}
*/
export function fixesMove(fixes) {
if (!fixes?.length) return false;
let moves = moving.get(fixes);
if (moves === undefined) {
const [first] = fixes;
moves = fixes.some(
(fix) =>
Math.abs(fix.lat - first.lat) > 1e-6 ||
Math.abs(fix.lon - first.lon) > 1e-6,
);
moving.set(fixes, moves);
}
return moves;
}
+33 -1
View File
@@ -1,6 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { vesselPositionAt } from './motion.js';
import { fixesMove, vesselPositionAt } from './motion.js';
const record = {
lat: 1,
@@ -29,3 +29,35 @@ test('a vessel with no move is at its record', () => {
assert.equal(vesselPositionAt(still, 2_000), still);
assert.equal(vesselPositionAt({ ...still, motion: null }, 2_000).lat, 4);
});
test('a vessel with fixes around the time is placed on them, held at either end', () => {
const tracked = {
lat: 9,
lon: 9,
motion: record.motion,
fixes: [
{ atMs: 1_000, lat: 0, lon: 0, altitudeM: null },
{ atMs: 2_000, lat: 1, lon: 0, altitudeM: null },
{ atMs: 4_000, lat: 1, lon: 2, altitudeM: null },
],
};
assert.deepEqual(vesselPositionAt(tracked, 0), { lat: 0, lon: 0 });
assert.deepEqual(vesselPositionAt(tracked, 9_000), { lat: 1, lon: 2 });
const back = vesselPositionAt(tracked, 1_500);
assert.ok(Math.abs(back.lat - 0.5) < 1e-3 && Math.abs(back.lon) < 1e-6);
const on = vesselPositionAt(tracked, 3_000);
assert.ok(Math.abs(on.lat - 1) < 1e-3 && Math.abs(on.lon - 1) < 1e-3);
});
test('fixes that stay in one place do not move a vessel', () => {
const still = [
{ atMs: 0, lat: 1, lon: 2 },
{ atMs: 60_000, lat: 1, lon: 2 },
];
assert.equal(fixesMove(still), false);
assert.equal(
fixesMove([...still, { atMs: 90_000, lat: 1.001, lon: 2 }]),
true,
);
assert.equal(fixesMove(null), false);
});
+47
View File
@@ -515,3 +515,50 @@ 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, primitives } = setup({
async getSnapshot() {
return snapshot([aid, ship]);
},
});
await layer.update();
const svgOf = (id) => {
const primitive = [...primitives].find((p) => p.id?.id === id);
assert.ok(primitive, id);
return atob(primitive.image.split(',')[1]);
};
assert.match(svgOf('993672001'), /<circle/);
// The source's virtual flag reaches the layer's record.
const recordOf = (id) => [...primitives].find((p) => p.id?.id === id).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, primitives } = setup({
async getSnapshot() {
return snapshot([aid]);
},
});
await layer.update();
const primitive = [...primitives].find((p) => p.id?.id === '993672009');
assert.ok(primitive);
assert.equal(primitive.id.virtual, true);
assert.match(atob(primitive.image.split(',')[1]), /<circle/);
});
+106
View File
@@ -0,0 +1,106 @@
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,
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, []);
});
+29 -2
View File
@@ -1,3 +1,7 @@
import {
mergeTimelineRuns,
readTimelineFixes,
} from '../../time/timelineFixes.js';
import {
PARTIAL_RETENTION_MS,
SELECTED_PIN_REFRESHES,
@@ -31,8 +35,13 @@ 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),
// Its own track around the time, from a snapshot at a time (see
// src/time/timelineFixes.js); null when the row carries none.
fixes: readTimelineFixes(row.fixes),
missedRefreshes: 0,
};
}
@@ -49,6 +58,9 @@ function stampFix(record, receivedAtMs, feedLatestEpoch) {
record.fixFeedEpoch = feedLatestEpoch;
}
/** A fix's time, as the fixes are merged (one function for every vessel). */
const fixTime = (fix) => fix.atMs;
function positiveNumber(value) {
const number = finiteNumber(value);
return number !== null && number > 0 ? number : null;
@@ -144,8 +156,22 @@ export class VesselRecords {
record.fixReceivedAtMs = next.fixReceivedAtMs;
record.fixFeedEpoch = next.fixFeedEpoch;
}
if (replace) record.motion = null;
else if (follow) record.motion = motionBetween(record, next);
if (replace) {
record.motion = null;
record.fixes = next.fixes;
} else if (follow) {
record.motion = motionBetween(record, next);
// Without fixes now, it is placed by its record, not by fixes
// that end before it.
record.fixes = next.fixes
? mergeTimelineRuns(
record.fixes ?? [],
next.fixes,
fixTime,
(next.lastPositionEpoch ?? 0) * 1000,
)
: null;
} else record.fixes = null;
record.reference = next.reference;
record.mmsi = next.mmsi;
record.receivedAtMs = next.receivedAtMs;
@@ -160,6 +186,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;
+12
View File
@@ -181,3 +181,15 @@ test('an AIS row with no id is keyed by its MMSI; one with neither is unkeyed',
assert.equal(probe.store.byId.size, 0);
assert.equal(probe.store.unkeyed.length, 2);
});
const fixes = (...pairs) =>
pairs.map(([atMs, lat]) => ({ atMs, lat, lon: 4.05, altitudeM: null }));
test('following the clock, a vessel whose next record carries no fixes is placed by the record', () => {
const probe = setup();
probe.reconcile([row('111', { fixes: fixes([0, 1], [60_000, 2]) })], {
replace: true,
});
probe.reconcile([row('111', { lat: 3 })], { follow: true });
assert.equal(probe.store.byId.get('111').fixes, null);
});
+515 -5
View File
@@ -2,14 +2,16 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { createVesselLayer } from './index.js';
import { VISIBILITY_UPDATE_MS } from './policy.js';
import { layerPlacement } from '../../data/placementProvider.js';
import * as Cesium from 'cesium';
// 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
// stops, and never schedules a frame from a pass the camera did not cause.
// The layer must let the scene idle: it asks for frames for forced passes,
// for vessels that move, and one trailing frame after the camera stops, and
// never schedules a frame from a pass nothing caused.
const noop = () => {};
function setup() {
function setup({ placement = null } = {}) {
let clock = 10_000;
const requests = [];
const holds = new Set();
@@ -46,6 +48,7 @@ function setup() {
releaseContinuousRender: (id) => holds.delete(id),
governorRequestRender: (reason) => requests.push(reason),
},
...(placement ? { placement: layerPlacement(placement, 'vessels') } : {}),
},
});
const camera = {
@@ -73,7 +76,16 @@ function setup() {
}
};
const frame = () => layer.testing._runVisibilityPassForTest();
return { layer, camera, requests, holds, timers, advance, frame };
return {
layer,
camera,
requests,
holds,
timers,
advance,
frame,
now: () => clock,
};
}
test('a parked camera schedules no frames after the cadence pass', () => {
@@ -112,6 +124,26 @@ test('a camera that stops inside the cadence gets exactly one trailing frame', (
assert.equal(timers.size, 0);
});
test('following the clock, a time moved inside the cadence gets one trailing frame', () => {
const { layer, requests, timers, advance, frame } = setup();
layer.testing._followClockForTest(1_000_000);
frame();
advance(100);
// A seek while paused: the camera is still, the time drawn is not.
layer.testing._followClockForTest(940_000);
frame();
assert.equal(timers.size, 1);
advance(VISIBILITY_UPDATE_MS);
assert.deepEqual(requests, ['ais-vessels-visibility']);
frame();
for (let i = 0; i < 20; i += 1) {
advance(100);
frame();
}
assert.deepEqual(requests, ['ais-vessels-visibility']);
assert.equal(timers.size, 0);
});
test('a forced pass requests its own frame', () => {
const { layer, requests } = setup();
layer.testing._runVisibilityPassForTest(true);
@@ -136,3 +168,481 @@ test('destroy cancels a pending trailing frame', (t) => {
advance(VISIBILITY_UPDATE_MS);
assert.deepEqual(requests, []);
});
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,
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {} },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
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(record.billboard.position, position);
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']);
});
test('a vessel moving visibly asks for its next frame as soon as it moves half a pixel; a slow one once a second', (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 = { lat: 51.93, lon: 4.05 };
const { layer, camera, timers, advance, now } = setup({
placement: { layer: () => ({ place: () => spot }) },
});
// 20 km above the vessel, in a 1,000 px tall view about 57° tall.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [record],
});
layer.testing._prepareVesselVisualForTest(record);
// How long after a pass the next frame is asked for, once the vessel moved
// `dLat` in the 16 ms since the pass before.
const waitAfterStep = (dLat) => {
layer.testing._runPlacementPassForTest();
advance(1_000); // whatever frame that asked for comes and goes
assert.equal(timers.size, 0);
mono += 16;
spot = { lat: spot.lat + dLat, lon: spot.lon };
layer.testing._runPlacementPassForTest();
assert.equal(timers.size, 1);
const [timer] = [...timers.values()];
return timer.at - now();
};
// About 11 m in a frame, 20 km away: over half a pixel, so the next frame
// is asked for within the frame.
assert.ok(waitAfterStep(0.0001) <= 16);
// About 1 cm in a frame: half a pixel takes seconds, so once a second.
assert.equal(waitAfterStep(0.0000001), 1000);
// A 2D view 40 km across in 1,000 px: 11 m is over a quarter pixel, so the
// next frame comes within two frames.
camera.frustum = { left: -20_000, right: 20_000 };
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientWidth: 1000 } },
records: [record],
});
layer.testing._prepareVesselVisualForTest(record);
assert.ok(waitAfterStep(0.0001) <= 32);
});
test('following the clock moves drawn vessels in place each world time, prepares missing ones and leaves hidden ones be', (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;
});
const { layer, camera, timers, advance } = setup();
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const motion = {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 60_000,
};
const vessel = (mmsi, show) => ({
mmsi,
lat: 51.94,
lon: 4.05,
motion: { ...motion },
billboard: { show, position: null },
});
const drawn = vessel('111', true);
const hidden = vessel('222', false);
const owned = vessel('333', false);
const missing = vessel('444', true);
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [drawn, hidden, owned, missing],
});
const visuals = [drawn, hidden, owned].map((record) =>
layer.testing._prepareVesselVisualForTest(record),
);
visuals[2].modelOwnsVisual = true;
const before = visuals.map((visual) => ({ ...visual.position }));
const positions = visuals.map((visual) => visual.position);
// The first pass moves hidden vessels too.
layer.testing._runClockPassForTest(10_000);
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.equal(visuals[0].position, positions[0], 'written in place');
assert.notDeepEqual({ ...visuals[0].position }, before[0]);
assert.notDeepEqual({ ...visuals[2].position }, before[2], 'model moves');
const hiddenAt = { ...visuals[1].position };
assert.ok(missing.billboard.position, 'a missing visual is prepared');
assert.equal(timers.size, 1, 'moving vessels ask for a frame');
// Hidden vessels move a share each pass, each within HIDDEN_FOLLOW_MS.
mono += 250;
layer.testing._runClockPassForTest(40_000);
assert.notDeepEqual({ ...visuals[1].position }, hiddenAt);
// The same world time again moves nothing and asks for no frame.
advance(1_000);
assert.equal(timers.size, 0);
const still = { ...visuals[0].position };
mono += 16;
layer.testing._runClockPassForTest(40_000);
assert.deepEqual({ ...visuals[0].position }, still);
assert.equal(timers.size, 0);
// Scrubbed back, a vessel moves back.
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.notDeepEqual({ ...visuals[0].position }, still);
// Each vessel moves once per world time: new fixes at the same world time
// are drawn when the snapshot that brings them prepares the visual.
const backAt = { ...visuals[0].position };
drawn.motion = { ...motion, toLat: 52 };
mono += 16;
layer.testing._runClockPassForTest(20_000);
assert.deepEqual({ ...visuals[0].position }, backAt);
// Past the newest fix, vessels hold still and ask for nothing.
mono += 16;
layer.testing._runClockPassForTest(70_000);
advance(1_000);
mono += 16;
layer.testing._runClockPassForTest(80_000);
assert.equal(timers.size, 0);
});
test('following the clock, drawn vessels move again once the fastest would have moved half a pixel, a second has gone by or the camera changed height', (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;
});
const { layer, camera } = setup();
// 20 km above, in a 1,000 px tall view about 57° tall: half a pixel is
// about 11 m. The vessel makes about 1.9 m a second of world time.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const at = () => ({ ...visual.position });
const pass = (atMs, wallMs = 16) => {
mono += wallMs;
layer.testing._runClockPassForTest(atMs);
};
// Two passes a world second apart measure how fast it moves on screen.
pass(10_000);
pass(11_000);
let drawn = at();
// A few metres more stay under half a pixel: it is left where it is.
pass(12_000);
pass(14_000);
assert.deepEqual(at(), drawn);
// About 13 m on from where it was drawn: it moves.
pass(18_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
// Under half a pixel, but a second later: it moves.
pass(19_000, 1_000);
assert.notDeepEqual(at(), drawn);
drawn = at();
pass(20_000);
assert.deepEqual(at(), drawn);
// Under half a pixel, but the camera came down by half: it moves.
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 10_000);
pass(21_000);
assert.notDeepEqual(at(), drawn);
// Scrubbed well back, it moves back at once.
drawn = at();
pass(1_000);
assert.notDeepEqual(at(), drawn);
});
test('a vessel is drawn lifted above the sea surface, its waterline on it, as Cesium places them', () => {
const { layer, camera } = setup();
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {} },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const heightOf = (position) =>
Cesium.Ellipsoid.WGS84.cartesianToCartographic(position).height;
const close = (actual, expected) =>
assert.ok(
Cesium.Cartesian3.distance(actual, expected) < 1e-6,
`${actual} is not ${expected}`,
);
close(visual.surfacePosition, Cesium.Cartesian3.fromDegrees(4.05, 51.93, 0));
close(
visual.position,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.position)),
);
close(
visual.waterline,
Cesium.Cartesian3.fromDegrees(4.05, 51.93, heightOf(visual.waterline)),
);
assert.ok(heightOf(visual.position) > heightOf(visual.waterline));
});
test('following the clock, a pass moves hidden vessels in proportion to the wall time since the last, so all move within HIDDEN_FOLLOW_MS', (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;
});
const { layer, camera } = setup();
const records = Array.from({ length: 100 }, (_, i) => ({
mmsi: String(i),
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: false, position: null },
}));
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records,
});
const visuals = records.map((record) =>
layer.testing._prepareVesselVisualForTest(record),
);
layer.testing._runClockPassForTest(10_000);
const moved = (atMs) => visuals.filter((v) => v.followedAtMs === atMs).length;
assert.equal(moved(10_000), 100, 'the first pass moves them all');
mono += 25;
layer.testing._runClockPassForTest(20_000);
assert.equal(moved(20_000), 10, 'a tenth of HIDDEN_FOLLOW_MS, a tenth');
for (let i = 0; i < 9; i += 1) {
mono += 25;
layer.testing._runClockPassForTest(20_000);
}
assert.equal(moved(20_000), 100, 'all within HIDDEN_FOLLOW_MS');
});
test('following the clock, the step gate measures each vessel from when it was drawn, and reopens for a pan, a zoom or a pause', (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;
});
const { layer, camera } = setup();
const above = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.positionWC = above;
camera.frustum = { fovy: 1 };
const record = {
mmsi: '111',
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 51.94,
toLon: 4.05,
toMs: 600_000,
},
billboard: { show: true, position: null },
};
layer.testing._setVesselStateForTest({
viewer: { camera, scene: {}, canvas: { clientHeight: 1000 } },
records: [record],
});
const visual = layer.testing._prepareVesselVisualForTest(record);
const at = () => ({ ...visual.position });
const pass = (atMs) => {
mono += 16;
layer.testing._runClockPassForTest(atMs);
};
// About 0.08 px a world second: measured over a second.
pass(10_000);
pass(11_000);
pass(13_000);
// A snapshot draws it afresh just before the next pass: the pass after
// it measures the move over that short time, not since 11 s.
layer.testing._followClockForTest(17_900);
layer.testing._prepareVesselVisualForTest(record);
pass(18_000);
let drawn = at();
pass(19_000);
assert.deepEqual(at(), drawn, 'the speed it measured is still its own');
pass(24_500);
assert.notDeepEqual(at(), drawn, 'and it moves once half a pixel is up');
// Panned sideways by more than a tenth of the camera's height: it moves.
drawn = at();
pass(25_000);
assert.deepEqual(at(), drawn);
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.1, 51.93, 20_000);
pass(25_500);
assert.notDeepEqual(at(), drawn);
// Zoomed in by narrowing the view: it moves.
drawn = at();
pass(26_000);
assert.deepEqual(at(), drawn);
camera.frustum = { fovy: 0.5 };
pass(26_500);
assert.notDeepEqual(at(), drawn);
// Paused just after a pass that left it short: the next frame at the same
// time draws it where it is.
drawn = at();
pass(27_000);
assert.deepEqual(at(), drawn);
pass(27_000);
assert.notDeepEqual(at(), drawn);
const where = at();
pass(27_000);
assert.deepEqual(at(), where, 'then holds');
});
test('following the clock, a vessel the visibility pass shows before the clock passes moved it is drawn at the time', (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;
});
const { layer, camera } = setup();
camera.positionWC = Cesium.Cartesian3.fromDegrees(4.05, 51.93, 20_000);
camera.frustum = { fovy: 1 };
const vessel = (mmsi) => ({
mmsi,
lat: 51.93,
lon: 4.05,
motion: {
fromLat: 51.93,
fromLon: 4.05,
fromMs: 0,
toLat: 52.93,
toLon: 4.05,
toMs: 3_600_000,
},
billboard: { show: false, position: null },
});
const records = Array.from({ length: 40 }, (_, i) => vessel(String(i)));
const last = records.at(-1);
layer.testing._setVesselStateForTest({
// No scene: the labels are not placed.
viewer: { camera, scene: null, canvas: { clientHeight: 1000 } },
records,
});
layer.testing._followClockForTest(0);
const visual = layer.testing._prepareVesselVisualForTest(last);
for (const record of records.slice(0, -1))
layer.testing._prepareVesselVisualForTest(record);
layer.testing._runClockPassForTest(10_000);
// Paused, a seek far on: the next frame moves only a share of the hidden
// vessels, not the last.
mono += 16;
layer.testing._runClockPassForTest(11_000);
mono += 16;
layer.testing._runClockPassForTest(1_800_000);
assert.notEqual(visual.followedAtMs, 1_800_000);
layer.testing._runVisibilityPassForTest(true);
assert.equal(last.billboard.show, true);
const { latitude } = Cesium.Ellipsoid.WGS84.cartesianToCartographic(
visual.surfacePosition,
);
assert.ok(Math.abs(Cesium.Math.toDegrees(latitude) - 52.43) < 1e-6);
});
+532 -69
View File
@@ -1,6 +1,7 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import {
AID_TO_NAVIGATION_STYLE,
vesselTypeCss,
vesselOverlayCohortLimit,
VESSEL_OVERLAY_SOURCE_ID,
@@ -21,20 +22,51 @@ import {
CARD_MIN_SEP_PX,
followsClock,
} from './policy.js';
import { vesselPositionAt } from './motion.js';
import { fixesMove, vesselPositionAt } from './motion.js';
import { TIMELINE_UNSEEN_MS } from '../../time/timelineFixes.js';
import {
fleetModelSet,
loadFleetModelSet,
vesselModelSpec,
} from '../../data/fleetModels.js';
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
import { isAidToNavigation } from '../../data/vesselTypes.js';
import { createWindowProjector } from '../../data/windowProjection.js';
/** How often vessels move on as the world clock plays (wall ms). */
const FOLLOW_POSITION_MS = 250;
// Label grid cells are keyed by column * LABEL_CELL_ROW + row, unique while
// rows stay within half of it either side; a cell further off screen is keyed
// by its text.
const LABEL_CELL_ROW = 1 << 20;
/** A moving vessel's next frame is asked for once it would move this far on
* screen (pixels), so it glides when it moves visibly and the scene idles
* when it does not. */
const VESSEL_STEP_PX = 0.5;
/** A frame is asked for at least this often while any drawn vessel moves. */
const PLACEMENT_FRAME_MS = 1000;
/** How often each vessel not drawn moves on as the world clock plays (wall
* ms), so one that comes into view is judged where it is. */
const HIDDEN_FOLLOW_MS = 250;
/** How often the vessels near enough for a model are gathered again (wall ms). */
const MODEL_CANDIDATES_MS = 500;
/** How far the camera may move or change height, as a share of its height,
* before vessels following the world clock move again however little they
* moved. */
const CAMERA_STEP = 0.1;
/** The least height that share is taken of (metres), so a camera just above
* the sea, or below the ellipsoid, still lets vessels rest between steps. */
const CAMERA_STEP_FLOOR_M = 100;
const DEG_TO_RAD = Math.PI / 180;
/** Scratch for the camera's position. */
const _cameraCartographic = new Cesium.Cartographic();
/** Scratch for where a moved vessel was drawn. */
const _movedFrom = new Cesium.Cartesian3();
export function createRendering({
vesselState,
services,
@@ -44,6 +76,7 @@ export function createRendering({
}) {
const { state } = vesselState;
let visualRecords = new WeakMap();
const labelScreenScratch = new Cesium.Cartesian2();
// The fallback preserves helper calls with externally supplied render records.
function getVisual(record) {
@@ -56,27 +89,62 @@ export function createRendering({
visual = { billboard: record.billboard || null };
visualRecords.set(record, visual);
}
// Following the world clock, a vessel is drawn where it was at the time.
// Following the world clock, a vessel is drawn where it was at the time;
// live, where a host-supplied placement draws it, if one does.
const { lat, lon } = followsClock(vesselState)
? vesselPositionAt(record, vesselState.worldNow())
: record;
: (services.placement?.place(record.id, vesselState._aisRuntime.now()) ??
record);
visual.position = new Cesium.Cartesian3();
visual.waterline = new Cesium.Cartesian3();
visual.surfacePosition = new Cesium.Cartesian3();
writeVesselPositions(visual, lat, lon);
// The world time it is drawn at, while it follows the clock.
visual.drawnAtMs = followsClock(vesselState)
? vesselState.worldNow()
: Number.NaN;
return visual;
}
/**
* Write where a vessel visual is drawn at `lat`/`lon` into its own
* positions: lifted VESSEL_LIFT_M above the sea surface, its waterline on
* it, and the surface point under it. The placement pass runs for every
* drawn vessel as it moves, so the surface point and its normal are worked
* out once (as Cesium.Cartesian3.fromDegrees does) and the other two are
* along the normal from it.
*/
function writeVesselPositions(visual, lat, lon) {
const heightM = components.queries.vesselDatumHeightM(
components.tracking.currentGeoidN(lat, lon),
VESSEL_LIFT_M,
);
visual.position = Cesium.Cartesian3.fromDegrees(lon, lat, heightM);
// A ship model's origin is its waterline: the sea surface, unlifted.
visual.waterline = Cesium.Cartesian3.fromDegrees(
lon,
lat,
heightM - VESSEL_LIFT_M,
);
visual.surfacePosition = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
visual.normal = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(
visual.position,
new Cesium.Cartesian3(),
);
return visual;
const phi = lat * DEG_TO_RAD;
const lambda = lon * DEG_TO_RAD;
const cosPhi = Math.cos(phi);
const nx = cosPhi * Math.cos(lambda);
const ny = cosPhi * Math.sin(lambda);
const nz = Math.sin(phi);
const radiiSquared = Cesium.Ellipsoid.WGS84.radiiSquared;
const kx = radiiSquared.x * nx;
const ky = radiiSquared.y * ny;
const kz = radiiSquared.z * nz;
const gamma = Math.sqrt(nx * kx + ny * ky + nz * kz);
const surface = visual.surfacePosition;
surface.x = kx / gamma;
surface.y = ky / gamma;
surface.z = kz / gamma;
const position = visual.position;
position.x = surface.x + nx * heightM;
position.y = surface.y + ny * heightM;
position.z = surface.z + nz * heightM;
const waterlineM = heightM - VESSEL_LIFT_M;
const waterline = visual.waterline;
waterline.x = surface.x + nx * waterlineM;
waterline.y = surface.y + ny * waterlineM;
waterline.z = surface.z + nz * waterlineM;
visual.drawnLat = lat;
visual.drawnLon = lon;
}
function resetRecordVisuals() {
@@ -137,7 +205,7 @@ export function createRendering({
function addRecordPrimitives(record, occluder) {
const visible =
state.feed.enabled &&
isVisible(getVisual(record).surfacePosition, occluder);
isVisible(getVisual(record).surfacePosition, occluder, record);
getVisual(record).billboard = state.billboardCollection.add({
position: getVisual(record).position,
show: visible,
@@ -182,12 +250,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).
* Screen rotation is computed from this by the shared projected-rotation
* pass in updateVisibility — never directly from the compass value.
* pass in updateVisibility — never directly from the compass value. 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;
}
@@ -195,6 +265,7 @@ export function createRendering({
/**
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
* The shape points north (up) so billboard rotation 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 reused across all billboards.
* @param {Object} record - Vessel record (drives per-type tint).
* @param {boolean} selected - True for the white/brighter selected variant.
@@ -202,16 +273,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);
@@ -254,25 +334,31 @@ export function createRendering({
function billboardShown(record, occluder) {
const visual = getVisual(record);
return (
isVisible(visual.surfacePosition, occluder) &&
isVisible(visual.surfacePosition, occluder, record) &&
record.id !== state.cockpitSubjectId &&
!visual.modelOwnsVisual
);
}
/** 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 = { record, pickId: record, 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);
item.show = record.id !== state.cockpitSubjectId;
// 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 && seenYet(record);
return item;
}
@@ -294,7 +380,8 @@ export function createRendering({
limitSq
)
continue;
into.set(record.id, modelItem(record, set));
const item = modelItem(record, set);
if (item) into.set(record.id, item);
}
}
@@ -330,8 +417,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, occluder);
@@ -356,38 +445,346 @@ export function createRendering({
modelCandidatesAtMs = -Infinity;
}
// Vessels move only when a poll lands, so the layer does not hold the
// continuous render loop. Its passes run in preRender, which idle mode fires
// only for rendered frames: a forced pass (new data, selection) requests its
// frame, a frame that moved the camera but fell inside the 800 ms cadence
// leaves a trailing frame so the view the camera stopped on is always
// evaluated, and the continuous hold is kept only while focus emphasis is
// animating. The trailing frame is keyed to camera motion alone: the pass's
// own label publication requests a frame, and scheduling on that would loop.
// The layer does not hold the continuous render loop. Its passes run in
// preRender, which idle mode fires only for rendered frames: moving vessels
// ask for the frame that next moves them visibly (askMotionFrame; while the
// world clock plays, the scene draws every frame anyway), a forced pass
// (new data, selection) requests its frame, a frame that moved the camera
// but fell inside the 800 ms cadence leaves a trailing frame so the view
// the camera stopped on is always evaluated, and the continuous hold is
// kept only while focus emphasis is animating. The trailing frame is keyed
// to camera motion alone: the pass's own label publication requests a
// frame, and scheduling on that would loop.
function installRuntime(viewer) {
if (state.preRenderRemover || !viewer) return;
state.preRenderRemover = viewer.scene.preRender.addEventListener(() => {
if (followsClock(vesselState)) followClockPositions();
if (state.feed.enabled) {
if (followsClock(vesselState)) followClockPositions();
else if (services.placement) followPlacements();
}
updateVisibility();
if (state.feed.enabled) updateModels();
});
}
// As the world clock plays, vessels between two fixes move on along them.
let followedAtWallMs = -Infinity;
let followedAtMs = null;
// Drawn ones move each world time once the fastest would have moved
// VESSEL_STEP_PX on screen, at least once a second, and at once when the
// camera moves or zooms (underClockStep). Hidden ones (which may come into
// view) move a share of them each pass, so each moves at least every
// HIDDEN_FOLLOW_MS without one frame moving them all. The scene renders as
// fast as the display while the clock plays, and moving thousands of
// vessels a fraction of a pixel each frame would take most of every frame.
let hiddenFollowedAtWallMs = null;
let hiddenCursor = 0;
let clockPassAtMs = null;
// Whether the last pass left drawn vessels short of its world time.
let drawnBehind = false;
function followClockPositions() {
const wallMs = performance.now();
if (wallMs - followedAtWallMs < FOLLOW_POSITION_MS) return;
followedAtWallMs = wallMs;
const atMs = vesselState.worldNow();
if (atMs === followedAtMs) return;
followedAtMs = atMs;
const wallMs = performance.now();
const all = state.records.all;
// Each vessel moves once per world time; drawn ones a pass left short
// move to it on the next, so a paused clock shows them where they are.
const sameTime = atMs === clockPassAtMs;
const moveDrawn = sameTime ? drawnBehind : !underClockStep(atMs, wallMs);
clockPassAtMs = atMs;
if (moveDrawn) drawnBehind = false;
else if (!sameTime) {
drawnBehind = true;
askFrameIn(PLACEMENT_FRAME_MS);
}
const motion = moveDrawn ? startMotionPass() : null;
if (moveDrawn)
for (const record of all) followRecord(record, atMs, true, motion);
// As much of the list as the wall time since the last pass is of
// HIDDEN_FOLLOW_MS, going round it.
const sinceMs =
hiddenFollowedAtWallMs === null
? HIDDEN_FOLLOW_MS
: wallMs - hiddenFollowedAtWallMs;
const share = Math.min(
all.length,
Math.ceil((all.length * Math.max(0, sinceMs)) / HIDDEN_FOLLOW_MS),
);
if (share > 0) hiddenFollowedAtWallMs = wallMs;
for (let k = 0; k < share; k += 1) {
if (hiddenCursor >= all.length) hiddenCursor = 0;
followRecord(all[hiddenCursor], atMs, false, motionPass);
hiddenCursor += 1;
}
if (!moveDrawn) return;
askMotionFrame(motion);
noteClockStep(atMs, motion);
}
/**
* Draw a vessel where it is at world time `atMs` if the clock passes have
* not yet; true when it moved.
*/
function catchUpVisual(record, atMs) {
const visual = visualRecords.get(record);
if (!visual?.position || visual.followedAtMs === atMs) return false;
if (!record.motion && !fixesMove(record.fixes)) return false;
visual.followedAtMs = atMs;
visual.drawnAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
if (lat === visual.drawnLat && lon === visual.drawnLon) return false;
writeVesselPositions(visual, lat, lon);
if (visual.billboard) visual.billboard.position = visual.position;
return true;
}
/**
* Move a vessel to where it is at world time `atMs`, if it is drawn
* (`drawn`) or hidden (not `drawn`) as asked; one with no visual yet is
* prepared either way. A hidden vessel's move notes nothing in `motion`.
*/
function followRecord(record, atMs, drawn, motion) {
if (!record.motion && !fixesMove(record.fixes)) return;
let visual = visualRecords.get(record);
if (!visual?.position) {
visual = prepareRecordVisual(record);
visual.followedAtMs = atMs;
} else {
const shown = Boolean(visual.billboard?.show || visual.modelOwnsVisual);
if (shown !== drawn || visual.followedAtMs === atMs) return;
visual.followedAtMs = atMs;
const { lat, lon } = vesselPositionAt(record, atMs);
const elapsedMs = Math.abs(atMs - visual.drawnAtMs);
visual.drawnAtMs = atMs;
// At either end of its fixes a vessel holds still.
if (lat === visual.drawnLat && lon === visual.drawnLon) return;
moveDrawnVisual(visual, lat, lon, motion, elapsedMs);
}
if (visual.billboard) visual.billboard.position = visual.position;
}
// The clock pass that last moved drawn vessels: its world time and wall
// time, how fast the fastest drawn vessel moved on screen (pixels per world
// ms), and the camera then: where it was, its height and its view's size.
const clockStep = {
atMs: null,
wallMs: 0,
pxPerMs: Infinity,
heightM: 0,
eye: new Cesium.Cartesian3(),
fovy: Number.NaN,
width: Number.NaN,
};
/** Measure, after a pass that moved drawn vessels, how fast the fastest
* moved on screen: each over the world time since it was last drawn. */
function noteClockStep(atMs, motion) {
const camera = motion.camera;
if (!motion.moving || motion.unmeasured || !camera?.positionWC) {
clockStep.atMs = null;
return;
}
const pxPerMs = movedPixels({
camera,
angle: motion.angleRate,
metres: motion.metresRate,
});
clockStep.pxPerMs = pxPerMs > 0 ? pxPerMs : Infinity;
clockStep.atMs = atMs;
clockStep.wallMs = motion.wallMs;
clockStep.heightM = cameraHeightM();
Cesium.Cartesian3.clone(camera.positionWC, clockStep.eye);
clockStep.fovy = camera.frustum?.fovy;
clockStep.width = viewWidth(camera.frustum);
}
/** Forget how fast vessels moved, so the next clock pass moves the drawn
* ones however little they moved (they were drawn somewhere else). */
function forgetClockStep() {
clockStep.atMs = null;
clockPassAtMs = null;
}
const viewWidth = (frustum) =>
frustum ? frustum.right - frustum.left : Number.NaN;
const sameNumber = (a, b) => a === b || (Number.isNaN(a) && Number.isNaN(b));
/**
* Whether the fastest drawn vessel would have moved less than
* VESSEL_STEP_PX on screen since the clock pass that last moved them, at
* the speed it moved then: drawn vessels are left where they are. They
* move anyway once PLACEMENT_FRAME_MS has gone by, or once the camera has
* moved or changed height by more than CAMERA_STEP of its height, or its
* view has changed size (a pixel then covers another distance).
*/
function underClockStep(atMs, wallMs) {
if (clockStep.atMs === null || !(clockStep.pxPerMs < Infinity))
return false;
if (wallMs - clockStep.wallMs >= PLACEMENT_FRAME_MS) return false;
const camera = state.viewer?.camera;
if (!camera?.positionWC) return false;
const limitM =
CAMERA_STEP * Math.max(clockStep.heightM, CAMERA_STEP_FLOOR_M);
if (!(Math.abs(cameraHeightM() - clockStep.heightM) <= limitM))
return false;
if (
!(Cesium.Cartesian3.distance(camera.positionWC, clockStep.eye) <= limitM)
)
return false;
if (
!sameNumber(camera.frustum?.fovy, clockStep.fovy) ||
!sameNumber(viewWidth(camera.frustum), clockStep.width)
)
return false;
return Math.abs(atMs - clockStep.atMs) * clockStep.pxPerMs < VESSEL_STEP_PX;
}
/** The camera's height above the ellipsoid (metres), NaN without one. */
function cameraHeightM() {
const eye = state.viewer?.camera?.positionWC;
if (!eye) return Number.NaN;
return (
Cesium.Ellipsoid.WGS84.cartesianToCartographic(eye, _cameraCartographic)
?.height ?? Number.NaN
);
}
// Live with a host-supplied placement, vessels move on between refreshes:
// drawn where it places them every frame, with the next frame asked for
// as soon as a drawn vessel would move visibly, so they move while the
// scene idles.
function followPlacements() {
const nowMs = vesselState._aisRuntime.now();
const motion = startMotionPass();
// 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) {
if (!record.motion) continue;
const visual = prepareRecordVisual(record);
const visual = visualRecords.get(record);
if (!visual?.position) continue;
if (!visual.billboard?.show && !visual.modelOwnsVisual) continue;
const placed = services.placement.place(record.id, nowMs);
if (placed) motion.moving = true;
const { lat, lon } = placed ?? record;
if (lat === visual.drawnLat && lon === visual.drawnLon) continue;
moveDrawnVisual(visual, lat, lon, motion);
if (visual.billboard) visual.billboard.position = visual.position;
}
askMotionFrame(motion);
}
// One pass of moving vessels: whether any drawn vessel is moving, how far
// the fastest moved (as an angle seen from the camera, radians, and in
// metres), the pass's wall time and the wall time since the pass before.
let motionPassWallMs = null;
const motionPass = {
camera: null,
wallMs: 0,
sinceMs: 0,
moving: false,
angle: 0,
metres: 0,
angleRate: 0,
metresRate: 0,
unmeasured: false,
};
function startMotionPass() {
const wallMs = performance.now();
motionPass.camera = state.viewer?.camera ?? null;
motionPass.wallMs = wallMs;
motionPass.sinceMs =
motionPassWallMs === null ? 0 : wallMs - motionPassWallMs;
motionPass.moving = false;
motionPass.angle = 0;
motionPass.metres = 0;
motionPass.angleRate = 0;
motionPass.metresRate = 0;
motionPass.unmeasured = false;
motionPassWallMs = wallMs;
return motionPass;
}
/** Move a drawn visual, noting how far it moved as seen from the camera,
* and, given the world time since it was last drawn (`elapsedMs`), how
* fast. */
function moveDrawnVisual(visual, lat, lon, motion, elapsedMs) {
const from = Cesium.Cartesian3.clone(visual.position, _movedFrom);
writeVesselPositions(visual, lat, lon);
if (!visual.billboard?.show && !visual.modelOwnsVisual) return;
motion.moving = true;
const metres = Cesium.Cartesian3.distance(from, visual.position);
motion.metres = Math.max(motion.metres, metres);
const timed = elapsedMs > 0;
if (elapsedMs !== undefined && !timed) motion.unmeasured = true;
if (timed)
motion.metresRate = Math.max(motion.metresRate, metres / elapsedMs);
const eye = motion.camera?.positionWC;
if (!eye) return;
const distance = Cesium.Cartesian3.distance(eye, from);
if (!(distance > 0)) return;
motion.angle = Math.max(motion.angle, metres / distance);
if (timed)
motion.angleRate = Math.max(
motion.angleRate,
metres / distance / elapsedMs,
);
}
/** How far the fastest drawn vessel moved on screen in a pass (pixels):
* through the perspective view's angle, or across the 2D view's width. */
function movedPixels(motion) {
const canvas = state.viewer?.canvas;
const frustum = motion.camera?.frustum;
if (!canvas || !frustum) return 0;
if (frustum.fovy > 0 && canvas.clientHeight > 0)
return (
(motion.angle * canvas.clientHeight) / (2 * Math.tan(frustum.fovy / 2))
);
const width = frustum.right - frustum.left;
if (!(frustum.fovy > 0) && width > 0 && canvas.clientWidth > 0)
return (motion.metres * canvas.clientWidth) / width;
return 0;
}
// The timer for the next vessel frame while one is asked for, and when it
// is due (the AIS runtime's clock).
let placementFrameTimer = null;
let placementFrameDueMs = 0;
/**
* While a drawn vessel moves, ask for the next frame when the fastest one
* will have moved VESSEL_STEP_PX on screen at the speed this pass saw, and
* at most PLACEMENT_FRAME_MS away.
*/
function askMotionFrame(motion) {
if (!motion.moving) return;
let waitMs = PLACEMENT_FRAME_MS;
const movedPx = movedPixels(motion);
if (movedPx > 0 && motion.sinceMs > 0)
waitMs = Math.min(waitMs, (VESSEL_STEP_PX * motion.sinceMs) / movedPx);
askFrameIn(waitMs);
}
/** Ask for a vessel frame `waitMs` from now; one already asked for no
* later stands. */
function askFrameIn(waitMs) {
const runtime = vesselState._aisRuntime;
const dueMs = runtime.now() + waitMs;
if (placementFrameTimer !== null) {
if (placementFrameDueMs <= dueMs) return;
runtime.clearTimeout(placementFrameTimer);
}
placementFrameDueMs = dueMs;
placementFrameTimer = runtime.setTimeout(() => {
placementFrameTimer = null;
if (state.feed.enabled) governorRequestRender('ais-vessels-placement');
}, waitMs);
}
/** Stop asking for placement frames (the layer turned off or went away). */
function cancelPlacementFrame() {
motionPassWallMs = null;
forgetClockStep();
drawnBehind = false;
hiddenFollowedAtWallMs = null;
if (placementFrameTimer === null) return;
vesselState._aisRuntime.clearTimeout(placementFrameTimer);
placementFrameTimer = null;
}
function scheduleTrailingVisibilityPass(now) {
@@ -418,14 +815,23 @@ export function createRendering({
const focusPass =
focusPassIsNeeded(focusTarget, state.activeFocusCount) &&
(force || now - state.lastFocusUpdate >= FOCUS_UPDATE_MS);
// Following the clock, the time drawn decides which vessels are there
// yet: a time that moved since the last pass (a seek while paused) gets
// its pass too.
const worldMs = followsClock(vesselState) ? vesselState.worldNow() : null;
if (
!regularPass &&
state.viewer?.camera &&
cameraPoseSignature(state.viewer.camera) !== vesselState._lastCamPoseSig
((state.viewer?.camera &&
cameraPoseSignature(state.viewer.camera) !==
vesselState._lastCamPoseSig) ||
worldMs !== state.visibilityWorldMs)
)
scheduleTrailingVisibilityPass(now);
if (!regularPass && !focusPass) return;
if (regularPass) state.lastVisibilityUpdate = now;
if (regularPass) {
state.lastVisibilityUpdate = now;
state.visibilityWorldMs = worldMs;
}
if (focusPass) state.lastFocusUpdate = now;
if (!state.records.all.length) {
// No records — flush any lingering card entries (vanished-feed case).
@@ -455,9 +861,21 @@ export function createRendering({
if (doRotations) vesselState._lastCamPoseSig = poseSig;
const occluder = makeOccluder();
const labelCandidates = [];
// The time the clock pass drew (a playing clock's time moves on within
// the frame), so only vessels it did not reach are moved.
const catchUpAtMs = worldMs === null ? null : (clockPassAtMs ?? worldMs);
for (const record of state.records.all) {
const visual = getVisual(record);
const visible = isVisible(visual.surfacePosition, occluder);
let visible = isVisible(visual.surfacePosition, occluder, record);
// One in view that the clock passes have not moved to the time yet
// (a seek while paused shows it before its turn) is moved there and
// judged again: no later pass would move it while the clock rests.
if (
visible &&
catchUpAtMs !== null &&
catchUpVisual(record, catchUpAtMs)
)
visible = isVisible(visual.surfacePosition, occluder, record);
if (visual.billboard) {
// The bridge camera sits on this sprite; showing it would fill the view.
// The same rule as billboardShown, its horizon test already made.
@@ -465,7 +883,8 @@ export function createRendering({
visible &&
record.id !== state.cockpitSubjectId &&
!visual.modelOwnsVisual;
if (visible && doRotations && scene) {
// An aid's disc is never turned (vesselCourseDeg).
if (visible && doRotations && scene && !isAidToNavigation(record)) {
const rot = screenProjectedRotation(
scene,
visual.position,
@@ -580,11 +999,23 @@ export function createRendering({
);
}
function isVisible(surfacePosition, occluder) {
function isVisible(surfacePosition, occluder, record) {
if (record && !seenYet(record)) return false;
if (!surfacePosition || !occluder) return true;
return occluder.isPointVisible(surfacePosition);
}
/** Whether a vessel is there at the time drawn: following the clock, not
* more than TIMELINE_UNSEEN_MS before its first fix. */
function seenYet(record) {
const first = record.fixes?.[0];
return (
!first ||
!followsClock(vesselState) ||
vesselState.worldNow() >= first.atMs - TIMELINE_UNSEEN_MS
);
}
/**
* Source selector for the shared world-overlay pipeline: the
* grid declutter picks which vessels get cards — one winner per screen-space
@@ -614,25 +1045,30 @@ export function createRendering({
return;
}
// Every vessel in view is projected, so the camera is read once and each
// is a few multiplications (see windowProjection.js) into one screen
// point; a cell gets a candidate only for the vessel that leads it.
const project = createWindowProjector(scene);
const cells = new Map();
for (const record of records) {
const visual = getVisual(record);
if (record === selected) continue;
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
visual.position,
);
const screen = project(getVisual(record).position, labelScreenScratch);
if (!screen) continue;
const key = `${Math.floor(screen.x / LABEL_GRID_PX)}:${Math.floor(screen.y / LABEL_GRID_PX)}`;
const candidate = {
record,
score: labelPriority(record, selected),
x: screen.x,
y: screen.y,
};
const column = Math.floor(screen.x / LABEL_GRID_PX);
const row = Math.floor(screen.y / LABEL_GRID_PX);
const key =
Math.abs(row) < LABEL_CELL_ROW / 2 && Math.abs(column) < LABEL_CELL_ROW
? column * LABEL_CELL_ROW + row
: `${column}:${row}`;
const score = labelPriority(record, selected);
const existing = cells.get(key);
if (!existing || candidate.score > existing.score) {
cells.set(key, candidate);
if (!existing) {
cells.set(key, { record, score, x: screen.x, y: screen.y });
} else if (score > existing.score) {
existing.record = record;
existing.score = score;
existing.x = screen.x;
existing.y = screen.y;
}
}
@@ -724,7 +1160,30 @@ export function createRendering({
return score;
}
// Whether a vessel's name is worth a card, kept per vessel until what it
// is judged from changes: the label pass asks for every vessel in view.
const usefulNames = new WeakMap();
function hasUsefulName(record) {
const known = usefulNames.get(record);
if (
known &&
known.name === record.name &&
known.mmsi === record.mmsi &&
known.id === record.id
)
return known.useful;
const useful = nameIsUseful(record);
usefulNames.set(record, {
name: record.name,
mmsi: record.mmsi,
id: record.id,
useful,
});
return useful;
}
function nameIsUseful(record) {
const text = String(record.name || '').trim();
return Boolean(
text &&
@@ -750,6 +1209,7 @@ export function createRendering({
}
return {
getVisual,
forgetClockStep,
prepareRecordVisual,
resetRecordVisuals,
renderRowLimit,
@@ -763,6 +1223,9 @@ export function createRendering({
installRuntime,
updateVisibility,
cancelTrailingVisibilityPass,
cancelPlacementFrame,
followPlacements,
followClockPositions,
applyVesselFocusDeemphasis,
makeOccluder,
isVisible,
+35 -1
View File
@@ -1,6 +1,30 @@
/** 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,
@@ -17,6 +41,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,
{
@@ -28,6 +59,7 @@ export function createVesselSnapshotRenderer({
},
{
add(record) {
observe(record);
rendering.prepareRecordVisual(record);
rendering.addRecordPrimitives(record, occluder);
},
@@ -35,6 +67,7 @@ export function createVesselSnapshotRenderer({
return rendering.shipIcon(record, record === state.selectedRecord);
},
updated(record, prevIcon) {
observe(record);
const selected = record === state.selectedRecord;
const visual = rendering.prepareRecordVisual(record);
if (visual.billboard) {
@@ -56,6 +89,7 @@ export function createVesselSnapshotRenderer({
rendering.removeRecordPrimitives(record);
},
removed(id) {
placement?.forget(id);
if (state.trailId === id) tracking.clearSelectedVesselTrail();
},
staleSelected(record) {
+2
View File
@@ -81,6 +81,8 @@ export function createVesselState({ source, services }) {
/** Pending timer that renders one frame after a cadence-skipped pass. */
trailingVisibilityTimer: null,
lastVisibilityUpdate: 0,
/** Following the clock, the world time the last visibility pass drew. */
visibilityWorldMs: null,
lastFocusUpdate: 0,
/** Sprites whose animated emphasis remains outside the 1.0 deadband. */
activeFocusCount: 0,
+30
View File
@@ -162,6 +162,32 @@ 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();
}
/** Run one world-clock pass at world time `atMs`. Test-only seam. */
function _runClockPassForTest(atMs) {
vesselState.worldNow = () => atMs;
components.rendering.followClockPositions();
}
/** Follow the world clock, standing at world time `atMs`. Test-only seam. */
function _followClockForTest(atMs) {
vesselState.timeline = { active: () => true };
vesselState.worldNow = () => atMs;
}
/** True while a trailing visibility frame is scheduled. Test-only seam. */
function _hasTrailingVisibilityPassForTest() {
@@ -184,6 +210,7 @@ export function createTesting({
return {
_bindVesselInteractionForTest,
_setVesselStateForTest,
_followClockForTest,
_setVesselOverlayHostForTest,
_updateVesselCardsForTest,
_reconcileVesselsForTest,
@@ -194,6 +221,9 @@ export function createTesting({
_getVesselFeedStateForTest,
_getVesselStateForTest,
_runVisibilityPassForTest,
_prepareVesselVisualForTest,
_runPlacementPassForTest,
_runClockPassForTest,
_hasTrailingVisibilityPassForTest,
};
}
+6
View File
@@ -73,7 +73,13 @@ export function createTracking({
heightM,
);
if (visual.billboard) visual.billboard.position = visual.position;
// A moving vessel is drawn again where it is on the next pass.
visual.drawnLat = NaN;
visual.drawnLon = NaN;
visual.followedAtMs = undefined;
visual.drawnAtMs = Number.NaN;
}
components.rendering.forgetClockStep();
}
/**
+91 -155
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
@@ -13,34 +59,36 @@ export const PLAY_WAIT_MS = 8_000;
// costs play nothing.
let clocks = 0;
// How many weather clocks follow each world clock.
const followers = new WeakMap();
/**
* Transient observed time. Products must honor the signal before installing a
* frame. Its time is the world clock's: latest while the world is live,
* history at the world's time otherwise. Replay steps the observed frames and
* moves the world clock as it goes, as the world clock's driver.
* history at the world's time otherwise. It never moves the world clock
* itself; the world's own controls (its timeline) move time, and while the
* world plays it stops at each next frame until that frame loads.
*
* `shared` (the default) is a clock several layers share, such as the
* catalog's: the last shared clock destroyed leaves the world live. A clock
* one layer keeps for itself (`shared: false`) leaves the world's time where
* it is.
*/
export function createWeatherClock({
now = Date.now,
setTimeout = globalThis.setTimeout,
clearTimeout = globalThis.clearTimeout,
world = createWorldClock({ now }),
shared = true,
} = {}) {
const registry = new Map();
const listeners = new Set();
let mode = 'latest';
let target = null;
let playing = false;
// The world time last applied; while this clock moves the world, the
// transition its move started.
// The world time last applied.
let seen = 'latest';
let moving = false;
let moved = null;
const releases = new Map();
// Attached at the end, once the API exists.
let driver = null;
let generation = 0;
let timer = null;
let pending = null;
// This clock's name on the world, for its holds and its gate.
const holdId = `weather:${++clocks}`;
@@ -101,10 +149,9 @@ export function createWeatherClock({
const getState = () => ({
mode,
target,
playing,
// Frames come on one after another: this clock replays them, or the world
// plays on through them, so the next is worth loading ahead.
advancing: playing || worldPlaysOn(),
// Frames come on one after another as the world plays on through them,
// so the next is worth loading ahead.
advancing: worldPlaysOn(),
timeline: getTimeline(),
products: [...registry.values()].map(({ product }) => ({
id: product.id,
@@ -116,60 +163,12 @@ export function createWeatherClock({
const notify = () => {
if (!destroyed) for (const listener of listeners) listener(getState());
};
const cancelTimer = () => {
if (timer !== null) clearTimeout(timer);
timer = null;
};
const canPlay = () => getTimeline().length >= 2;
const stopPlaying = () => {
if (!playing) return;
playing = false;
driver?.driven(false);
};
// Move the world clock; the change comes back through followWorld. Returns
// the transition the move started, if it started one.
const move = (fn) => {
const outer = [moving, moved];
moving = true;
moved = null;
try {
fn();
return moved;
} finally {
[moving, moved] = outer;
}
};
const selections = () =>
[...registry.values()].map(({ product }) => selectedFor(product)).join();
let applied = null;
function schedule() {
cancelTimer();
if (!playing || destroyed || pending) return;
if (!canPlay()) {
stopPlaying();
notify();
return;
}
const owner = generation;
timer = setTimeout(() => {
timer = null;
if (destroyed || !playing || owner !== generation) return;
const timeline = getTimeline();
if (timeline.length < 2) {
api.pause();
return;
}
const next = timeline.find(
(time) => Date.parse(time) > Date.parse(target),
);
void api.setTarget(next ?? timeline[0]);
}, 2000);
}
function transition() {
if (destroyed) return Promise.resolve(false);
cancelTimer();
const owner = ++generation;
if (!canPlay()) stopPlaying();
// A scrub drops what loads and moves on; play goes on as this loads.
applied = selections();
deferred = false;
@@ -189,15 +188,12 @@ export function createWeatherClock({
if (destroyed || owner !== generation) return false;
stopWaiting();
pending = null;
if (!canPlay()) stopPlaying();
notify();
schedule();
// Play held at the next frame for this one goes on to it.
if (deferred) void transition();
return true;
});
pending = result;
if (moving) moved ??= result;
notify();
return result;
}
@@ -208,11 +204,13 @@ export function createWeatherClock({
throw new Error(`Duplicate weather product: ${product.id}`);
const entry = { product, controller: null };
registry.set(product.id, entry);
// The product moves with the world clock, and its frames are time the
// world clock's timeline can show while it is on, suspended or not, so
// the way back to live stays on screen. Both calls notify the world's
// listeners, which may destroy this clock: the release is in place
// first, and anything acquired after a destroy is let go at once.
// The product moves with the world clock, and the span of its frames is
// time the world clock's timeline can show while it is on, suspended or
// not, so the way back to live stays on screen. The frames are not
// marks: they come every few minutes, and the timeline marks only
// events. Both calls notify the world's listeners, which may destroy
// this clock: the release is in place first, and anything acquired
// after a destroy is let go at once.
let unhold = null;
let uncover = null;
const release = () => {
@@ -226,9 +224,12 @@ export function createWeatherClock({
uncover = world.register({
id: product.id,
coverage: () => {
const marks = timesFor(product).map((time) => Date.parse(time));
return marks.length
? { start: marks[0], end: marks.at(-1), marks }
const times = timesFor(product);
return times.length
? {
start: Date.parse(times[0]),
end: Date.parse(times.at(-1)),
}
: null;
},
});
@@ -248,81 +249,17 @@ export function createWeatherClock({
},
getTimeline,
selectFor,
setTarget(time) {
if (destroyed) return Promise.resolve(false);
if (!Number.isFinite(Date.parse(time)))
throw new TypeError('Weather target must be a UTC time');
const normalized = new Date(time).toISOString();
if (mode === 'history' && target === normalized)
return pending ?? Promise.resolve(true);
return (
move(() => world.seek(Date.parse(normalized))) ??
pending ??
Promise.resolve(true)
);
},
step(direction) {
if (destroyed || ![-1, 1].includes(direction))
return Promise.resolve(false);
api.pause();
const timeline = getTimeline();
if (!timeline.length) return Promise.resolve(false);
const at = Date.parse(target ?? timeline.at(-1));
const next =
direction < 0
? (timeline.findLast((time) => Date.parse(time) < at) ?? timeline[0])
: (timeline.find((time) => Date.parse(time) > at) ?? timeline.at(-1));
return api.setTarget(next);
},
latest() {
if (destroyed) return Promise.resolve(false);
stopPlaying();
if (mode === 'latest') return transition();
return move(() => world.goLive()) ?? pending ?? Promise.resolve(true);
},
play() {
if (destroyed || playing || !canPlay())
return pending ?? Promise.resolve(false);
playing = true;
if (mode === 'latest') {
const timeline = getTimeline();
const start =
timeline.findLast((time) => Date.parse(time) <= now()) ?? timeline[0];
// Playing and at the first frame in one move of the world.
return (
move(() => driver.driven(true, Date.parse(start))) ??
pending ??
Promise.resolve(true)
);
}
driver.driven(true);
notify();
schedule();
return pending ?? Promise.resolve(true);
},
pause() {
cancelTimer();
if (!playing) {
// The world may be playing on its own; a pause or step here holds it.
if (world.isPlaying()) world.pause();
return;
}
stopPlaying();
notify();
},
togglePlay() {
return playing ? api.pause() : api.play();
},
/**
* The world clock this clock follows. Time moves there, through the same
* seek, play and live the world's timeline uses, never through this clock.
*/
world,
refresh() {
if (destroyed) return Promise.resolve(false);
// New frames, or products added or dropped, and with them the next.
world.coverageChanged();
gated = undefined;
gateNext(world.getState());
if (!canPlay()) {
stopPlaying();
cancelTimer();
}
if (mode === 'history') return transition();
notify();
return Promise.resolve(true);
@@ -334,15 +271,18 @@ export function createWeatherClock({
},
destroy() {
if (destroyed) return;
stopPlaying();
destroyed = true;
++generation;
stopWaiting();
world.gate(holdId, null);
cancelTimer();
unfollowWorld();
// The last weather clock leaves the world live, as a new one expects.
if (driver.detach() === 0) world.goLive();
// The last shared weather clock leaves the world live, as a new one
// expects.
if (shared) {
const left = followers.get(world) - 1;
followers.set(world, left);
if (left === 0) world.goLive();
}
for (const release of releases.values()) release();
releases.clear();
for (const entry of registry.values()) entry.controller?.abort();
@@ -351,9 +291,8 @@ export function createWeatherClock({
pending = null;
},
};
// Follow the world clock. A move of this clock's own always applies; one
// from elsewhere (a host's seek, continuous play) applies only when it
// changes the mode or a product's frame.
// Follow the world clock. A move (a seek, play going on) applies only when
// it changes the mode or a product's frame.
function followWorld(state) {
if (destroyed) return;
gateNext(state);
@@ -374,7 +313,7 @@ export function createWeatherClock({
const modeChanged = nextMode !== mode;
mode = nextMode;
target = nextTarget;
if (!moving && !modeChanged && selections() === applied) {
if (!modeChanged && selections() === applied) {
// Back at the frame that loads, play need not hold for it.
if (deferred) {
deferred = false;
@@ -387,7 +326,7 @@ export function createWeatherClock({
}
// Playing on into the next frame while the one before it loads, the
// world holds here until that one shows.
if (!moving && !modeChanged && pending && playsOn) {
if (!modeChanged && pending && playsOn) {
deferred = true;
startWaiting();
notify();
@@ -410,10 +349,7 @@ export function createWeatherClock({
world.gate(holdId, next);
}
const unfollowWorld = world.subscribe(followWorld);
driver = world.attachDriver({
play: () => (canPlay() ? void api.play() : false),
pause: () => api.pause(),
});
if (shared) followers.set(world, (followers.get(world) ?? 0) + 1);
followWorld(world.getState());
return api;
}
+137 -199
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,13 +96,78 @@ test('union excludes suspended products; nearest selection never uses future or
assert.equal(LIGHTNING_MAX_GAP_MS, 30 * 60_000);
});
test('history applies per-product selections, including null; latest restores unequal newest times', async (t) => {
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);
});
const at = (minutes) => Date.parse(time(minutes));
test('history applies per-product selections, including null; live restores unequal newest times', async (t) => {
const { clock, world } = harness(t);
const radar = product('radar', [0, 10, 20]);
const satellite = product('satellite', [5, 15]);
const lightning = product('lightning', [15]);
for (const p of [radar, satellite, lightning]) clock.register(p);
await clock.setTarget(time(10));
world.seek(at(10));
await flush();
assert.deepEqual(
[radar.shown, satellite.shown, lightning.shown],
[time(10), time(5), null],
@@ -109,18 +176,19 @@ test('history applies per-product selections, including null; latest restores un
clock.getState().products.map(({ selected }) => selected),
[time(10), time(5), null],
);
await clock.latest();
world.goLive();
await flush();
assert.deepEqual(
[radar.shown, satellite.shown, lightning.shown],
[time(20), time(15), time(15)],
);
assert.equal(clock.getState().mode, 'latest');
assert.equal(clock.getState().target, null);
assert.equal(clock.getState().playing, false);
assert.equal(clock.getState().advancing, false);
});
test('superseded completions cannot commit, notify or schedule a new playback advance', async (t) => {
const { clock, timers } = harness(t);
test('superseded completions cannot commit or notify', async (t) => {
const { clock, world, timers } = harness(t);
const p = product('radar', [0, 10, 20]);
const loads = [];
p.apply = (selected, { signal }) =>
@@ -137,113 +205,44 @@ test('superseded completions cannot commit, notify or schedule a new playback ad
clock.register(p);
let notifications = 0;
clock.subscribe(() => notifications++);
const old = clock.setTarget(time(0));
world.seek(at(0));
await flush();
const current = clock.setTarget(time(10));
world.seek(at(10));
await flush();
assert.equal(loads[0].signal.aborted, true);
loads[1].finish();
assert.equal(await current, true);
await flush();
const count = notifications;
loads[0].finish();
assert.equal(await old, false);
await flush();
assert.equal(notifications, count);
assert.equal(p.shown, time(10));
assert.equal(clock.getState().target, time(10));
assert.equal(timers.size, 0);
});
test('steps use strict union neighbours from arbitrary targets and clamp at endpoints', async (t) => {
const { clock } = harness(t);
clock.register(product('radar', [0, 10, 20]));
clock.register(product('satellite', [5, 15]));
await clock.step(-1);
assert.equal(clock.getState().target, time(15));
await clock.setTarget(time(12));
await clock.step(-1);
assert.equal(clock.getState().target, time(10));
await clock.setTarget(time(12));
await clock.step(1);
assert.equal(clock.getState().target, time(15));
await clock.setTarget(time(0));
await clock.step(-1);
assert.equal(clock.getState().target, time(0));
await clock.setTarget(time(20));
await clock.step(1);
assert.equal(clock.getState().target, time(20));
});
test('playback waits for every product to settle, including rejection, then waits 2000 ms and wraps', async (t) => {
const { clock, tick, timers } = harness(t);
const a = product('radar', [0, 10]);
const b = product('satellite', [5]);
const loads = [];
b.apply = () =>
new Promise((resolve, reject) => loads.push({ resolve, reject }));
clock.register(a);
clock.register(b);
const start = clock.play();
await flush();
assert.equal(clock.getState().target, time(10));
tick(10_000);
assert.equal(timers.size, 0);
assert.equal(a.calls.length, 1);
loads[0].reject(new Error('unavailable'));
await start;
assert.equal(timers.size, 1);
tick(1999);
assert.equal(clock.getState().target, time(10));
tick(1);
await flush();
assert.equal(clock.getState().target, time(0));
assert.equal(timers.size, 0);
tick(10_000);
assert.equal(clock.getState().target, time(0));
loads[1].resolve(true);
await flush();
tick(2000);
await flush();
assert.equal(clock.getState().target, time(5));
clock.pause();
loads[2].resolve(false);
await flush();
assert.equal(timers.size, 0, 'pausing during a load prevents rescheduling');
});
test('pause cancels a pending advance; playback stops with one time or all products suspended', async (t) => {
const { clock, tick, timers } = harness(t);
const p = product('radar', [0, 10]);
clock.register(p);
await clock.play();
await clock.play();
assert.equal(timers.size, 1);
clock.pause();
tick(2000);
assert.equal(clock.getState().target, time(10));
assert.equal(timers.size, 0);
await clock.togglePlay();
p.times = [time(0)];
await clock.refresh();
assert.equal(clock.getState().playing, false);
await clock.play();
assert.equal(clock.getState().playing, false);
p.times = [time(0), time(10)];
await clock.refresh();
await clock.play();
p.suspended = true;
await clock.refresh();
assert.equal(clock.getState().playing, false);
assert.deepEqual(clock.getTimeline(), []);
assert.equal(timers.size, 0);
test('the clock has no time controls of its own; the world clock moves time', (t) => {
const { clock, world } = harness(t);
for (const name of [
'setTarget',
'step',
'latest',
'play',
'pause',
'togglePlay',
])
assert.equal(clock[name], undefined, name);
assert.equal(clock.world, world);
});
test('refresh does not apply in latest; history retains its target as expired frames disappear', async (t) => {
const { clock } = harness(t);
const { clock, world } = harness(t);
const p = product('radar', [0, 10]);
clock.register(p);
await clock.refresh();
assert.equal(p.calls.length, 0);
await clock.setTarget(time(10));
world.seek(at(10));
await flush();
p.times = [time(0), time(20)];
await clock.refresh();
assert.equal(p.shown, time(0));
@@ -254,15 +253,16 @@ test('refresh does not apply in latest; history retains its target as expired fr
});
test('registration joins history; unregister and destroy abort work and release subscriptions/timers', async (t) => {
const { clock, timers, tick } = harness(t);
const { clock, world, timers } = harness(t);
const p = product('radar', [0, 10]);
const unregister = clock.register(p);
await clock.setTarget(time(0));
world.seek(at(0));
await flush();
const b = product('satellite', [0, 5]);
clock.register(b);
await flush();
assert.equal(b.shown, time(0));
await clock.play();
world.seek(at(5));
unregister();
unregister();
await flush();
@@ -273,31 +273,27 @@ test('registration joins history; unregister and destroy abort work and release
);
let notifications = 0;
const off = clock.subscribe(() => notifications++);
clock.pause();
off();
const before = notifications;
await clock.play();
assert.equal(notifications, before);
world.seek(at(0));
await flush();
assert.equal(notifications, 0);
world.seek(at(5));
clock.destroy();
clock.destroy();
tick(2000);
await flush();
assert.equal(timers.size, 0);
assert.equal(b.calls.at(-1).signal.aborted, true);
assert.equal(clock.getState().playing, false);
assert.deepEqual(clock.getTimeline(), []);
assert.equal(await clock.setTarget(time(5)), false);
});
test('the weather time is the world time, both ways', async (t) => {
test('the weather time is the world time', async (t) => {
const { clock, world } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
assert.equal(world.follows('radar'), true);
await clock.setTarget(time(10));
assert.equal(world.isLive(), false);
assert.equal(world.now(), Date.parse(time(10)));
world.seek(Date.parse(time(3)));
world.seek(at(3));
await flush();
assert.equal(clock.getState().mode, 'history');
assert.equal(clock.getState().target, time(3));
assert.equal(radar.shown, time(0));
world.goLive();
@@ -306,30 +302,22 @@ test('the weather time is the world time, both ways', async (t) => {
assert.equal(radar.shown, time(20));
});
test('world play and pause drive the weather replay', async (t) => {
test('world play runs the world on its own at its rate; weather does not drive it', async (t) => {
const { clock, world, tick } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
world.seek(Date.parse(time(0)));
world.seek(at(0));
await flush();
world.play();
assert.equal(clock.getState().playing, true);
assert.equal(world.isPlaying(), true);
tick(2000);
world.play({ rate: 60 });
assert.equal(world.getState().stepping, false);
assert.equal(clock.getState().advancing, true);
tick(5_000);
assert.equal(world.now(), at(5), 'five minutes on at a minute a second');
tick(10_000);
await flush();
assert.equal(radar.shown, time(10));
assert.equal(world.now(), Date.parse(time(10)));
assert.equal(world.now(), at(10), 'held at the next frame');
world.pause();
assert.equal(clock.getState().playing, false);
clock.play();
assert.equal(world.isPlaying(), true);
clock.pause();
assert.equal(world.isPlaying(), false);
clock.play();
world.goLive();
await flush();
assert.equal(clock.getState().playing, false);
assert.equal(clock.getState().mode, 'latest');
assert.equal(clock.getState().advancing, false);
});
test('a moving world re-applies frames only when a product changes frame', async (t) => {
@@ -352,15 +340,6 @@ test('a moving world re-applies frames only when a product changes frame', async
assert.equal(radar.shown, time(10));
});
test('a world without frames to step plays on its own', async (t) => {
const { clock, world, tick } = harness(t);
world.seek(Date.parse(time(0)));
world.play();
assert.equal(clock.getState().playing, false);
tick(1000);
assert.equal(world.now(), Date.parse(time(0)) + 1000);
});
function worldAt(at) {
return createWorldClock({
now: () => at,
@@ -370,74 +349,25 @@ function worldAt(at) {
});
}
test('weather clocks sharing a world hand play over, and the last leaves it live', async () => {
test('weather clocks sharing a world: the last one destroyed leaves it live', () => {
const world = worldAt(Date.parse(time(20)));
const a = createWeatherClock({ world, now: () => Date.parse(time(20)) });
const b = createWeatherClock({ world, now: () => Date.parse(time(20)) });
const radarA = product('radar', [0, 10, 20]);
const radarB = product('radar', [0, 10, 20]);
a.register(radarA);
b.register(radarB);
await a.play();
assert.equal(world.isPlaying(), true);
world.pause();
assert.equal(a.getState().playing, false);
assert.equal(world.isPlaying(), false);
await a.play();
world.goLive();
assert.equal(a.getState().playing, false);
b.destroy();
assert.equal(world.follows('radar'), true);
a.register(product('radar', [0, 10, 20]));
b.register(product('radar', [0, 10, 20]));
world.seek(Date.parse(time(0)));
world.play();
assert.equal(a.getState().playing, true);
b.destroy();
assert.equal(world.follows('radar'), true);
assert.equal(world.isLive(), false);
assert.equal(world.isPlaying(), true);
a.destroy();
assert.equal(world.follows('radar'), false);
assert.equal(world.isLive(), true);
assert.equal(world.isPlaying(), false);
});
test('pausing from inside the first playing notice stops the world too', async (t) => {
const { clock, world } = harness(t);
clock.register(product('radar', [0, 10, 20]));
const off = clock.subscribe((state) => {
if (state.playing) {
off();
clock.pause();
}
});
await clock.play();
assert.equal(clock.getState().playing, false);
assert.equal(world.isPlaying(), false);
});
test('a step holds a world that was playing on its own', async (t) => {
const { clock, world } = harness(t);
world.seek(Date.parse(time(0)));
world.play();
clock.register(product('radar', [0, 10, 20]));
await clock.step(1);
assert.equal(world.isPlaying(), false);
assert.equal(world.now(), Date.parse(time(10)));
});
test('a target superseded from a listener resolves false', async (t) => {
const { clock } = harness(t);
const radar = product('radar', [0, 10, 20]);
clock.register(radar);
await flush();
let redirected = false;
clock.subscribe((state) => {
if (state.target === time(0) && !redirected) {
redirected = true;
void clock.setTarget(time(10));
}
});
assert.equal(await clock.setTarget(time(0)), false);
assert.equal(radar.shown, time(10));
});
test('each product’s frames are world clock coverage, and support the timeline while shown', (t) => {
test('each product’s frames span world clock coverage, with no marks, and support the timeline while shown', (t) => {
const { clock, world } = harness(t);
assert.equal(world.coverage(), null);
assert.equal(world.getState().supported, false);
@@ -447,11 +377,17 @@ test('each product’s frames are world clock coverage, and support the timeline
assert.deepEqual(world.coverage(), {
start: Date.parse(time(0)),
end: Date.parse(time(10)),
marks: [0, 5, 10].map((m) => Date.parse(time(m))),
marks: [],
markDetails: [],
});
assert.equal(world.getState().supported, true);
unregister();
assert.deepEqual(world.coverage().marks, [Date.parse(time(5))]);
assert.deepEqual(world.coverage(), {
start: Date.parse(time(5)),
end: Date.parse(time(5)),
marks: [],
markDetails: [],
});
clock.destroy();
assert.equal(world.coverage(), null);
assert.equal(world.getState().supported, false);
@@ -464,10 +400,12 @@ test('a suspended product keeps its coverage, so the way back to live stays', (t
radar.suspended = true;
void clock.refresh();
assert.equal(world.getState().supported, true);
assert.deepEqual(
world.coverage().marks,
[0, 10].map((m) => Date.parse(time(m))),
);
assert.deepEqual(world.coverage(), {
start: Date.parse(time(0)),
end: Date.parse(time(10)),
marks: [],
markDetails: [],
});
});
test('new frames reach the world clock through refresh', (t) => {
+9
View File
@@ -39,6 +39,15 @@ function text(value, max) {
: undefined;
}
/**
* A source name a weather feed supplies itself (`sourceName` on the feed),
* held to the same rule as a manifest's `display.source`; undefined when it
* is not a fit name.
*/
export function weatherSourceName(value) {
return text(value, TEXT_LIMITS.source);
}
/**
* Whether a label the legend formats as a number reads back exactly as given:
* within the safe integer range and with no digits lost to rounding, so
+169 -166
View File
@@ -2,13 +2,16 @@ import * as Cesium from 'cesium';
import { createWeatherRendering } from './rendering.js';
import { weatherFrameSource } from './source.js';
import { imageryHostStatus } from './imageryHost.js';
import { weatherDisplay, insideExtent } from './display.js';
import { weatherDisplay, weatherSourceName, insideExtent } from './display.js';
import {
RADAR_MAX_GAP_MS,
REGIONAL_INFRARED_MAX_GAP_MS,
GLOBAL_INFRARED_MAX_GAP_MS,
LIGHTNING_MAX_GAP_MS,
atLeastFrameSpacing,
createWeatherClock,
} from './clock.js';
import { worldClock } from '../../time/worldClock.js';
import { formatUtcDayMonth, t, msg } from '../../i18n/index.js';
import { formatScaleLabel } from '../../ui/unitLabels.js';
@@ -52,12 +55,68 @@ const utc = (value) =>
? `${formatUtcDayMonth(value)} ${value.slice(11, 16)} UTC`
: t('Unavailable');
/**
* Move `world`, the world clock, as its timeline does: `play` toggles play at
* the world clock's rate (the speed the timeline chose), from the start of the
* covered time when live or at its end, unless `canPlay` is false or there
* is no covered time (no timeline to play); `latest` goes live. `step` (-1 or 1) goes to the previous or next of `frames`, the
* weather frames; the timeline does not mark them, so this is the row's own
* way to step through them.
*/
function moveWorldTime(world, frames, { play, latest, step }, canPlay) {
if (!world) return;
if (play === true) {
const state = world.getState();
if (state.playing) world.pause();
else {
// With no time to show there is no timeline, and nothing to play.
const covered = canPlay && state.supported ? world.coverage() : null;
if (covered) {
// The covered time reaches to now, as the timeline's track does.
const end = Math.max(covered.end, world.wallNow());
if (state.live || state.timeMs >= end)
world.seek(Math.min(covered.start, state.timeMs));
world.play({ continuous: true });
}
}
}
if (latest === true) world.goLive();
if (step === -1 || step === 1) {
const at = world.getState().timeMs;
const times = frames
.map((time) => Date.parse(time))
.filter(Number.isFinite)
.sort((a, b) => a - b);
const to =
step < 0
? times.findLast((frame) => frame < at)
: times.find((frame) => frame > at);
if (to === undefined) return;
world.pause();
world.seek(to);
}
}
// What a layer that has not built its own clock yet reads: live, no frames.
const IDLE_CLOCK = Object.freeze({
mode: 'latest',
target: null,
advancing: false,
timeline: [],
products: [],
});
/** A per-application observation layer, using the existing layer lifecycle and
* row controls. Its time is the world clock's, so a link made away from live
* opens its imagery at that time; one made live opens the latest. */
* opens its imagery at that time; one made live opens the latest. Its frames
* follow `clock`, a weather clock several layers share; without one the layer
* builds its own on the page's world clock when first enabled and keeps it
* for its lifetime; that clock never sends the world live. The feed may also
* name its source with `sourceName(kind)`, `kind` being 'radar', 'lightning'
* or 'satellite'; NOAA nowCOAST is named otherwise. */
export function createWeatherLayer({
feed,
clock,
clock: sharedClock,
id = 'weather-radar',
cesium = Cesium,
createRendering = createWeatherRendering,
@@ -67,10 +126,28 @@ export function createWeatherLayer({
} = {}) {
if (typeof feed?.getSnapshot !== 'function')
throw new TypeError('Weather requires a snapshot source');
// Without a shared clock the layer builds its own when first enabled, so a
// layer never turned on leaves the world clock alone.
let ownClock = null;
let clock = sharedClock ?? null;
// A feed may also supply decoded frames; see weatherFrameSource.
const radar = id === 'weather-radar';
const lightning = id === 'weather-lightning';
const satellite = !radar && !lightning;
// A feed may name the source behind each product ('radar', 'lightning' or
// 'satellite'); its row then says so before a manifest names it. A name
// that fails, like a manifest's, leaves the built-in one.
let sourceName = null;
try {
sourceName =
weatherSourceName(
feed.sourceName?.(
radar ? 'radar' : lightning ? 'lightning' : 'satellite',
),
) ?? null;
} catch (cause) {
console.warn('[weather] source name unavailable:', cause);
}
let product = radar ? 'radar' : lightning ? 'lightning' : 'clouds-regional';
let opacity = 'strong';
let infrared = 100;
@@ -79,12 +156,10 @@ export function createWeatherLayer({
manifest = null,
request = null,
listener = null;
let destroyed = false;
let enabled = false,
loading = false,
playing = false,
followLatest = true;
loading = false;
let generation = 0,
timer = null,
error = null,
removeCamera = null;
let motion = null;
@@ -96,7 +171,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
@@ -104,33 +182,48 @@ export function createWeatherLayer({
: product === 'clouds'
? GLOBAL_INFRARED_MAX_GAP_MS
: REGIONAL_INFRARED_MAX_GAP_MS;
const isLatest = () =>
clock ? clock.getState().mode === 'latest' : followLatest;
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 clockState = () => clock?.getState() ?? IDLE_CLOCK;
const isLatest = () => clockState().mode === 'latest';
const getHost = () =>
imageryHost?.() ?? { collection: viewer?.imageryLayers, kind: 'globe' };
const notify = () => listener?.();
const shownTime = () => (noFrame ? null : rendering?.getDiagnostics().time);
const unsubscribeClock = clock?.subscribe(() => {
const onClock = () => {
if (!clock.getState().advancing || suspended())
rendering?.cancelPrefetch?.();
notify();
});
};
let unsubscribeClock = clock?.subscribe(onClock) ?? null;
const ensureClock = () => {
if (clock) return;
ownClock = createWeatherClock({ world: worldClock, shared: false });
clock = ownClock;
unsubscribeClock = clock.subscribe(onClock);
};
const observationDelayed = () =>
manifest?.latest &&
Date.now() - Date.parse(manifest.latest) >
(product === 'clouds' ? 240 : lightning ? 45 : 20) * 60_000;
const stop = () => {
if (clock) return;
playing = false;
rendering?.cancelPrefetch?.();
clearTimeout(timer);
timer = null;
};
Date.now() - Date.parse(manifest.latest) > spacedTimes().delay;
const suspended = () => hostHidden || documentRef?.hidden || motion?.matches;
const onVisibility = () => {
if (suspended()) rendering?.cancelPrefetch?.();
if (clock) void clock.refresh();
else if (suspended()) stop();
void clock?.refresh();
notify();
};
@@ -145,46 +238,15 @@ export function createWeatherLayer({
if (!changed || !rendering) return;
++generation;
rendering.rehome?.();
clearTimeout(timer);
timer = null;
loading = Boolean(request && !request.signal.aborted);
if (clock && enabled) {
if (resume) {
void clock.refresh();
if (!hostHidden && manifest && isLatest()) void show(manifest.latest);
}
notify();
return;
}
if (resume && enabled && !hostHidden && manifest) {
const time =
followLatest || !manifest.times.includes(shownTime())
? manifest.latest
: shownTime();
if (
time !== shownTime() ||
(satellite && rendering.getDiagnostics().infrared !== infrared)
)
void show(time);
else schedule();
if (enabled && resume) {
void clock.refresh();
if (!hostHidden && manifest && isLatest()) void show(manifest.latest);
}
notify();
}
const onMapStackChanged = () => checkHost();
function schedule() {
if (clock) return;
clearTimeout(timer);
timer = null;
if (!enabled || !playing || suspended()) return;
timer = setTimeout(() => {
timer = null;
const times = manifest?.times || [];
const next = (times.indexOf(shownTime()) + 1) % times.length;
if (times[next]) void show(times[next]);
else stop();
}, 2000);
}
async function applyClockTime(time, { signal }) {
if (!enabled || signal.aborted) return false;
if (time !== null) return show(time, signal);
@@ -198,7 +260,7 @@ export function createWeatherLayer({
return true;
}
function registerClock() {
if (!clock || unregisterClock || !rendering || !enabled) return;
if (unregisterClock || !rendering || !enabled || !clock) return;
unregisterClock = clock.register({
id,
get maxGapMs() {
@@ -211,15 +273,11 @@ export function createWeatherLayer({
});
}
async function warmNext(time) {
if (
!enabled ||
suspended() ||
!(clock ? clock.getState().advancing : playing)
)
return;
if (!enabled || suspended() || !clockState().advancing) return;
// The world plays on past the newest frame, never round to the first.
const times = manifest?.times ?? [];
const next = times[(times.indexOf(time) + 1) % times.length];
if (!next || next === time) return;
const next = times[times.indexOf(time) + 1];
if (!next) return;
try {
await rendering.prefetch?.(manifest, next, { infrared });
} catch {
@@ -254,13 +312,10 @@ export function createWeatherLayer({
error = ok
? null
: msg('Frame unavailable; previous observation retained');
if (!ok) stop();
return ok;
} catch {
if (owner === generation && !controller.signal.aborted) {
if (owner === generation && !controller.signal.aborted)
error = msg('Weather imagery unavailable');
stop();
}
return false;
} finally {
signal?.removeEventListener('abort', abort);
@@ -268,8 +323,7 @@ export function createWeatherLayer({
if (owner === generation) {
loading = Boolean(request && !request.signal.aborted);
notify();
if (clock && isLatest()) void clock.refresh();
schedule();
if (isLatest()) void clock?.refresh();
}
}
}
@@ -281,7 +335,7 @@ export function createWeatherLayer({
? 'Lightning density'
: 'Satellite clouds',
icon: radar ? '◉' : lightning ? 'ϟ' : '☁',
source: 'NOAA nowCOAST · OBSERVED',
source: sourceName ?? 'NOAA nowCOAST · OBSERVED',
updateInterval: lightning ? 600_000 : 120_000,
init(nextViewer) {
viewer = nextViewer;
@@ -316,7 +370,10 @@ export function createWeatherLayer({
notify();
},
enable() {
// Destroyed, the layer stays off: no clock is built for it again.
if (destroyed) return;
enabled = true;
ensureClock();
if (!removeCamera) {
removeCamera = viewer.camera.moveEnd?.addEventListener(() => {
checkHost();
@@ -337,26 +394,20 @@ export function createWeatherLayer({
noFrame = false;
request?.abort();
request = null;
stop();
rendering?.cancelPrefetch?.();
rendering?.clear();
manifest = null;
loading = false;
error = null;
followLatest = true;
},
async update(_viewer, { signal } = {}) {
if (!enabled) return false;
checkHost(false);
clearTimeout(timer);
timer = null;
request?.abort();
const controller = new AbortController();
if (signal?.aborted) controller.abort(signal.reason);
request = controller;
const abort = () => {
controller.abort(signal.reason);
stop();
};
const abort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
loading = true;
notify();
@@ -372,36 +423,15 @@ export function createWeatherLayer({
error = msg(
'Weather source unavailable; previous observation retained',
);
stop();
return true;
}
manifest = snapshot;
error = null;
// The shown frame may stay; its credit follows the refreshed manifest.
rendering?.updateSnapshot?.(snapshot);
if (clock) {
await clock.refresh();
if (
isLatest() &&
request === controller &&
!controller.signal.aborted
)
await show(snapshot.latest, controller.signal);
return (
enabled &&
!signal?.aborted &&
(!controller.signal.aborted || request !== controller)
);
}
const time =
followLatest || !snapshot.times.includes(shownTime())
? snapshot.latest
: shownTime();
if (
shownTime() !== time ||
(satellite && rendering.getDiagnostics().infrared !== infrared)
)
await show(time, controller.signal);
await clock.refresh();
if (isLatest() && request === controller && !controller.signal.aborted)
await show(snapshot.latest, controller.signal);
return (
enabled &&
!signal?.aborted &&
@@ -411,7 +441,6 @@ export function createWeatherLayer({
if (controller.signal.aborted || request !== controller)
return enabled && !signal?.aborted && request !== controller;
error = cause?.message || msg('Weather unavailable');
stop();
return true;
} finally {
signal?.removeEventListener('abort', abort);
@@ -419,7 +448,6 @@ export function createWeatherLayer({
request = null;
loading = Boolean(rendering?.getDiagnostics().loading);
notify();
schedule();
}
}
},
@@ -454,19 +482,16 @@ export function createWeatherLayer({
noFrame = false;
request?.abort();
request = null;
stop();
rendering?.cancelPrefetch?.();
manifest = null;
error = null;
loading = false;
followLatest = true;
rendering?.clear();
if (clock) void clock.refresh();
void clock?.refresh();
if (enabled) void layer.update(viewer);
}
if (infraredChanged && enabled && manifest) {
clearTimeout(timer);
timer = null;
if (clock && !isLatest()) void clock.refresh();
if (!isLatest()) void clock.refresh();
else void show(shownTime() || manifest.latest);
}
if (
@@ -492,38 +517,19 @@ export function createWeatherLayer({
}),
);
}
if (clock && enabled) {
if (params.play === true) void clock.togglePlay();
if (params.latest === true) void clock.latest();
if ([-1, 1].includes(params.step)) void clock.step(params.step);
}
if (
!clock &&
params.play === true &&
enabled &&
manifest?.times?.length > 1 &&
!suspended()
) {
playing = !playing;
followLatest = false;
if (playing) schedule();
else stop();
}
if (!clock && params.latest === true && manifest) {
stop();
followLatest = true;
void show(manifest.latest);
}
if (!clock && [-1, 1].includes(params.step) && manifest && !loading) {
stop();
followLatest = false;
const at = manifest.times.indexOf(shownTime());
const next = Math.max(
0,
Math.min(manifest.times.length - 1, at + params.step),
// Time is the world's: these move the world clock as its timeline
// does, and every layer that follows it moves along. A step goes
// through every shown observation's frames, and this row's own even
// while it is suspended.
// Play does nothing while every observation it would show is suspended
// (reduced motion, a hidden page, no imagery host), as the row says.
if (enabled)
moveWorldTime(
clock.world,
[...clock.getTimeline(), ...(manifest?.times ?? [])],
params,
clock.getState().products.some(({ suspended }) => !suspended),
);
void show(manifest.times[next]);
}
notify();
},
getParams() {
@@ -534,21 +540,21 @@ export function createWeatherLayer({
: { product, opacity };
},
getRowControls() {
const shared = clock?.getState();
const shared = clockState();
const followLatest = isLatest();
// Source-described text is data: shown as is, never translated.
const display = weatherDisplay(manifest);
const missing =
noFrame &&
shared?.mode === 'history' &&
shared.mode === 'history' &&
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;
@@ -666,9 +672,7 @@ export function createWeatherLayer({
const stops =
display.legend ?? (radar ? STOPS : lightning ? LIGHTNING_STOPS : []);
const infoMotion = motion?.matches
? clock
? t('Reduced motion · history playback unavailable')
: t('Reduced motion · manual history available')
? t('Reduced motion · history playback unavailable')
: '';
const controls = {
readout: true,
@@ -688,7 +692,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 ||
@@ -850,35 +854,34 @@ export function createWeatherLayer({
loading,
error: error || rendering?.getDiagnostics().error || null,
stale: Boolean(manifest?.stale || observationDelayed()),
...(source === undefined
...(source === undefined && sourceName === null
? { source: 'NOAA nowCOAST' }
: // Source text is data: the panel shows it untranslated.
{ source, sourceVerbatim: true }),
{ source: source ?? sourceName, sourceVerbatim: true }),
observedAt: shownTime(),
};
},
getDiagnostics() {
const shared = clock?.getState();
const shared = clockState();
return {
...rendering?.getDiagnostics(),
playing: shared ? shared.playing : playing && !hostHidden,
playing: shared.advancing,
followLatest: isLatest(),
...(shared
? {
clock: {
mode: shared.mode,
target: shared.target,
playing: shared.playing,
},
}
: {}),
clock: {
mode: shared.mode,
target: shared.target,
playing: shared.advancing,
},
historyFrames: manifest?.times?.length || 0,
timerActive: timer !== null,
};
},
destroy() {
destroyed = true;
layer.disable();
unsubscribeClock?.();
unsubscribeClock = null;
ownClock?.destroy();
if (ownClock) clock = ownClock = null;
removeCamera?.();
removeCamera = null;
motion?.removeEventListener?.('change', onVisibility);
+40 -5
View File
@@ -13,8 +13,13 @@ import {
acquireInfraredMosaic,
processInfraredImage,
} from './infraredImage.js';
// Bounded display detail for the hourly, approximately 3 km global product.
// Bounded display detail for the hourly, approximately 3 km global product
// when it is drawn from one 2048 × 1024 mosaic.
const GLOBAL_TILE_MAXIMUM_LEVEL = 3;
// Detail of the tiled products when the feed does not name its own.
const TILE_MAXIMUM_LEVEL = 6;
// The deepest level a feed may name: about 150 m a pixel.
const SUPPLIED_MAXIMUM_LEVEL_LIMIT = 12;
// Six decoded 2048×1024 canvases (8 MiB each) bound the cache below 50 MiB.
const MAX_MOSAICS = 6;
const MAX_PREFETCH_TILES = 8;
@@ -45,10 +50,33 @@ function createGlobeRendering({
let prefetchJob = null;
let prefetchedKey = null;
/** The deepest level the feed's own tiles of `product` go to, or null. */
function suppliedLevel(product) {
if (!frameSource?.getTile) return null;
let level = null;
try {
level = frameSource.maximumLevel?.(product) ?? null;
} catch {
return null;
}
return Number.isInteger(level) &&
level >= 0 &&
level <= SUPPLIED_MAXIMUM_LEVEL_LIMIT
? level
: null;
}
/** Global clouds come from one mosaic unless the feed tiles them itself. */
function fromMosaic(product) {
return product === 'clouds' && suppliedLevel(product) === null;
}
function profile(product) {
return {
tileSize: 256,
maximumLevel: product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : 6,
maximumLevel:
suppliedLevel(product) ??
(product === 'clouds' ? GLOBAL_TILE_MAXIMUM_LEVEL : TILE_MAXIMUM_LEVEL),
};
}
@@ -252,7 +280,7 @@ function createGlobeRendering({
!snapshot.times.includes(time)
)
return false;
const global = snapshot.product === 'clouds';
const global = fromMosaic(snapshot.product);
const tiles = global ? [] : prefetchTiles(snapshot);
const supplied = !global && Boolean(frameSource?.getTile);
const urls = global || supplied ? [] : tileUrls(snapshot, time, tiles);
@@ -315,7 +343,7 @@ function createGlobeRendering({
lastError = null;
const { west, south, east, north } = snapshot.bounds;
const rectangle = cesium.Rectangle.fromDegrees(west, south, east, north);
const global = snapshot.product === 'clouds';
const global = fromMosaic(snapshot.product);
const frame = {
snapshot,
creditSnapshot,
@@ -484,7 +512,14 @@ function createGlobeRendering({
.then((image) => {
// Cesium decodes tiles as ImageBitmaps already flipped, since WebGL
// ignores UNPACK_FLIP_Y for them; a canvas upload flips again.
if (!frame.closed && snapshot.product === 'clouds-regional')
// Infrared tiles get the display transfer the mosaic already
// carries.
if (
!frame.closed &&
!global &&
(snapshot.product === 'clouds-regional' ||
snapshot.product === 'clouds')
)
image = processInfraredImage(image, infrared, createCanvas, {
flipY:
typeof ImageBitmap !== 'undefined' &&
+11 -1
View File
@@ -121,6 +121,10 @@ export function weatherTileUrl(product, time, { size } = {}) {
* degrees) a detail window of it. `getFrameTile` returns one `size`-pixel tile
* of the geographic tiling scheme, or null for a transparent tile. Rows run
* top-down (north first), as an image does. Both honour `signal`.
* `frameMaximumLevel` names the deepest level of that scheme the feed's tiles
* of a product hold detail at (0–12), or null for the layer's own: with it,
* global clouds are drawn from the feed's tiles to that level instead of from
* one 2048 × 1024 image.
* @typedef {object} WeatherFrameFeed
* @property {(request: { product: string, time: string,
* size: { width: number, height: number },
@@ -129,19 +133,25 @@ export function weatherTileUrl(product, time, { size } = {}) {
* @property {(request: { product: string, time: string, z: number, x: number,
* y: number, size: number, signal: AbortSignal })
* => Promise<WeatherPixels | null>} [getFrameTile]
* @property {(product: string) => number | null} [frameMaximumLevel]
*/
/**
* The frame source a feed provides, or null when it has neither method. A
* missing method is left undefined, so that path keeps the routes.
* @param {WeatherFrameFeed | undefined} feed
* @returns {{ getImage?: Function, getTile?: Function } | null}
* @returns {{ getImage?: Function, getTile?: Function,
* maximumLevel?: Function } | null}
*/
export function weatherFrameSource(feed) {
const image = typeof feed?.getFrameImage === 'function';
const tile = typeof feed?.getFrameTile === 'function';
if (!image && !tile) return null;
const level = typeof feed?.frameMaximumLevel === 'function';
return {
maximumLevel: level
? (product) => feed.frameMaximumLevel(product)
: undefined,
getImage: image
? ({ product, time, size, bbox = null, signal }) =>
feed.getFrameImage({ product, time, size, bbox, signal })
+7
View File
@@ -257,6 +257,13 @@ test('a frame source forwards exactly the documented requests to its feed', asyn
assert.equal(imagesOnly.getTile, undefined, 'tiles keep the tile route');
const tilesOnly = weatherFrameSource({ getFrameTile: feed.getFrameTile });
assert.equal(tilesOnly.getImage, undefined, 'images keep the image route');
assert.equal(tilesOnly.maximumLevel, undefined);
const leveled = weatherFrameSource({
getFrameTile: feed.getFrameTile,
frameMaximumLevel: (product) => (product === 'clouds' ? 6 : null),
});
assert.equal(leveled.maximumLevel('clouds'), 6);
assert.equal(leveled.maximumLevel('radar'), null);
});
test('supplied pixels report their drawn size, draw at the origin and close once', (t) => {
+503 -102
View File
@@ -1,8 +1,9 @@
import test from 'node:test';
import test, { afterEach } from 'node:test';
import assert from 'node:assert/strict';
import { createWeatherRendering, READY_WAKE_MS } from './rendering.js';
import { createWeatherLayer } from './index.js';
import { createWeatherClock } from './clock.js';
import { worldClock } from '../../time/worldClock.js';
import * as Cesium from 'cesium';
import { Color, ImageryLayerCollection, GeographicTilingScheme } from 'cesium';
import { NO_IMAGERY_HOST } from './imageryHost.js';
@@ -35,6 +36,16 @@ const deferred = () => {
const flush = async () => {
for (let i = 0; i < 30; i++) await Promise.resolve();
};
// Time moves on the world clock the weather clock follows, as the timeline
// moves it.
const seekTo = (clock, time) => {
clock.world.seek(Date.parse(time));
return flush();
};
const goLive = (clock) => {
clock.world.goLive();
return flush();
};
function event() {
const listeners = new Set();
return {
@@ -472,12 +483,22 @@ test('failed and timed-out stages retain the previous observation; a healthy rep
h.rendering.clear();
});
// A layer built without a clock keeps its own on the page's world clock:
// each test leaves that clock live, with no layer of its own on it.
const harnessed = new Set();
afterEach(() => {
for (const layer of harnessed) layer.destroy();
harnessed.clear();
worldClock.goLive();
worldClock.setRate(1);
});
function layerHarness({
clock,
reducedMotion = false,
feed,
id,
eventTarget = target(),
enable = true,
} = {}) {
const stages = [];
const motion = target({ matches: reducedMotion });
@@ -551,7 +572,8 @@ function layerHarness({
createRendering: () => rendering,
});
layer.init(viewer);
layer.enable();
if (enable) layer.enable();
harnessed.add(layer);
return {
layer,
rendering,
@@ -565,72 +587,189 @@ function layerHarness({
};
}
test('history has one owned timer, stops while hidden, and releases all work on disable/destroy', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('without a clock the layer keeps one of its own on the world clock and lets it go on destroy', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
assert.equal(worldClock.follows('weather-radar'), true);
// The frames span the timeline's time; they are not marks on it.
assert.deepEqual(worldClock.coverage(), {
start: Date.parse(times[0]),
end: Date.parse(times.at(-1)),
marks: [],
markDetails: [],
});
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().timerActive, true);
t.mock.timers.tick(2000);
assert.equal(h.stages.length, 2);
assert.equal(
h.layer.getDiagnostics().timerActive,
false,
'next timer waits for stage settlement',
);
h.stages[1].finish();
await flush();
assert.equal(h.layer.getDiagnostics().timerActive, true);
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getState().stepping, false);
assert.equal(h.layer.getDiagnostics().playing, true);
h.documentRef.hidden = true;
h.documentRef.emit('visibilitychange');
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
t.mock.timers.tick(20_000);
assert.equal(h.stages.length, 2);
await flush();
assert.equal(worldClock.isPlaying(), true, 'hiding suspends the layer only');
h.documentRef.hidden = false;
h.documentRef.emit('visibilitychange');
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
h.layer.disable();
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getDiagnostics().historyFrames, 0);
t.mock.timers.tick(20_000);
assert.equal(h.stages.length, 2);
h.layer.destroy();
assert.equal(worldClock.follows('weather-radar'), false);
assert.equal(h.documentRef.size, 0);
assert.equal(h.motion.size, 0);
assert.equal(h.moveEnd.size, 0);
assert.ok(h.clears() >= 1);
});
test('reduced motion blocks autoplay but permits manual history and stops newly suspended playback', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('a layer without a clock leaves the world clock alone until enabled, and never sends it live', async (t) => {
const past = Date.parse(times[0]) - 3_600_000;
worldClock.seek(past);
const subscribe = t.mock.method(worldClock, 'subscribe');
const gate = t.mock.method(worldClock, 'gate');
const h = layerHarness({ enable: false });
h.layer.getRowControls();
h.layer.getDiagnostics();
h.layer.setParams({ play: true, step: -1 });
assert.equal(subscribe.mock.callCount(), 0, 'off, no clock is built');
assert.equal(gate.mock.callCount(), 0);
assert.equal(worldClock.isPlaying(), false);
h.layer.destroy();
harnessed.delete(h.layer);
assert.equal(worldClock.now(), past, 'never on, the world is where it was');
assert.equal(worldClock.isLive(), false);
const on = layerHarness({ enable: false });
on.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'built on first enable');
const update = on.layer.update();
await flush();
on.stages.at(-1)?.finish();
await update;
on.layer.disable();
on.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'built once');
on.layer.destroy();
harnessed.delete(on.layer);
assert.equal(
worldClock.isLive(),
false,
'its own clock does not send it live',
);
assert.equal(worldClock.now(), past);
});
test('destroyed, a layer without a clock stays off: enabling it builds no clock', (t) => {
const subscribe = t.mock.method(worldClock, 'subscribe');
const h = layerHarness();
assert.equal(subscribe.mock.callCount(), 1, 'its clock, built on enable');
h.layer.destroy();
harnessed.delete(h.layer);
h.layer.enable();
assert.equal(subscribe.mock.callCount(), 1, 'no clock built after destroy');
assert.equal(worldClock.follows('weather-radar'), false);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
});
test('with no frames yet there is no timeline, and a row plays nothing', () => {
worldClock.setRate(604_800);
const h = layerHarness({
feed: { getSnapshot: () => new Promise(() => {}) },
});
void h.layer.update();
assert.equal(worldClock.coverage(), null);
h.layer.setParams({ play: true });
assert.equal(worldClock.isLive(), true);
assert.equal(worldClock.isPlaying(), false);
});
test('a row plays at the speed the world clock keeps, from the start at the end of the covered time', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
// A speed chosen on the timeline, while live.
worldClock.setRate(3_600);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getRate(), 3_600, 'played at the speed chosen');
assert.ok(
worldClock.now() - Date.parse(times[0]) < 3_600_000,
'live, play starts at the start of the covered time',
);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), false);
// Paused at the end of the covered time (it reaches to now), play starts
// again from the start, as the timeline's does.
worldClock.seek(worldClock.wallNow() + 1_000);
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.ok(worldClock.now() - Date.parse(times[0]) < 3_600_000);
assert.equal(worldClock.getRate(), 3_600);
worldClock.pause();
});
test('reduced motion offers no play; steps still move the world clock from frame to frame', async () => {
const h = layerHarness({ reducedMotion: true });
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(
h.layer.getRowControls().chips.some((chip) => chip.id === 'play'),
false,
);
h.layer.setParams({ step: -1 });
assert.equal(h.stages[1].time, times[1]);
h.stages[1].finish();
await flush();
h.motion.matches = false;
h.motion.emit('change');
// Play, which the row does not offer, does nothing while it is suspended.
h.layer.setParams({ play: true });
assert.equal(h.layer.getDiagnostics().playing, true);
h.motion.matches = true;
h.motion.emit('change');
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
h.layer.destroy();
assert.equal(worldClock.isPlaying(), false);
assert.equal(worldClock.isLive(), true);
// A step back from live goes to the newest frame, and the next one back
// to the frame before it.
h.layer.setParams({ step: -1 });
await flush();
assert.equal(worldClock.now(), Date.parse(times[2]));
h.layer.setParams({ step: -1 });
await flush();
assert.equal(worldClock.now(), Date.parse(times[1]));
assert.equal(h.stages.at(-1).time, times[1]);
});
test('a row steps forward and plays from a past time through the world clock', async () => {
const h = layerHarness();
const update = h.layer.update();
await flush();
h.stages[0].finish();
await update;
worldClock.seek(Date.parse(times[0]));
await flush();
h.layer.setParams({ step: 1 });
assert.equal(worldClock.now(), Date.parse(times[1]));
assert.equal(worldClock.isPlaying(), false);
await flush();
assert.equal(h.stages.at(-1).time, times[1]);
h.layer.setParams({ step: 1 });
assert.equal(worldClock.now(), Date.parse(times[2]));
h.layer.setParams({ step: 1 });
assert.equal(
worldClock.now(),
Date.parse(times[2]),
'no frame after the newest',
);
worldClock.seek(Date.parse(times[1]));
await flush();
h.layer.setParams({ play: true });
assert.equal(worldClock.isPlaying(), true);
assert.equal(worldClock.getState().stepping, false);
assert.ok(
worldClock.now() - Date.parse(times[1]) < 1_000,
'away from live, play goes on from the time shown',
);
h.layer.setParams({ step: 1 });
assert.equal(worldClock.isPlaying(), false, 'a step holds play');
assert.equal(worldClock.now(), Date.parse(times[2]));
});
test('disable invalidates an abort-insensitive source result and an already staged frame', async (t) => {
@@ -659,7 +798,6 @@ test('disable invalidates an abort-insensitive source result and an already stag
await next;
await flush();
assert.equal(h.layer.getStats().count, 0);
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getStats().loading, false);
h.layer.destroy();
});
@@ -719,7 +857,6 @@ test('update cancellation reaches imagery after source acquisition has completed
assert.equal(h.stages[0].signal.aborted, true);
assert.equal(h.layer.getStats().count, 0);
assert.equal(h.layer.getStats().loading, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
h.layer.destroy();
});
@@ -827,21 +964,22 @@ test('coverage navigation requires the shared shell handoff and detaches cleanly
h.layer.destroy();
});
test('manifest refresh during a manual history stage does not strand loading controls', async () => {
test('manifest refresh during a history stage restages the same time and does not strand loading controls', async () => {
const h = layerHarness();
const first = h.layer.update();
await flush();
h.stages[0].finish();
await first;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(times[1]));
await flush();
assert.equal(h.layer.getStats().loading, true);
await h.layer.update();
assert.equal(
h.stages.length,
2,
'metadata refresh preserves the staged manual selection',
);
h.stages[1].finish();
const refreshed = h.layer.update();
await flush();
assert.equal(h.stages.length, 3);
assert.equal(h.stages[1].signal.aborted, true);
assert.equal(h.stages[2].time, times[1], 'the refresh keeps the time');
h.stages[2].finish();
await refreshed;
await flush();
assert.equal(h.layer.getStats().loading, false);
assert.equal(h.layer.getStats().observedAt, times[1]);
@@ -871,7 +1009,8 @@ test('historical observations do not relabel a fresh lightning feed as stale', a
await flush();
h.stages[0].finish();
await first;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(old));
await flush();
h.stages[1].finish();
await flush();
assert.equal(h.layer.getStats().stale, false);
@@ -1246,8 +1385,7 @@ test('404 fails a frame without retry', async () => {
h.rendering.clear();
});
test('no host pauses history, refreshes metadata, and restores retained time and playback', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
test('no host holds the shown history frame, refreshes metadata, and restores the retained time', async () => {
let refreshes = 0;
const h = layerHarness({
feed: {
@@ -1263,28 +1401,23 @@ test('no host pauses history, refreshes metadata, and restores retained time and
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ play: true });
t.mock.timers.tick(2000);
worldClock.seek(Date.parse(times[0]));
await flush();
assert.equal(h.stages.length, 2);
h.stages[1].finish();
await flush();
host = { collection: null, kind: 'none' };
h.eventTarget.emit('gev:map-stack-changed');
await flush();
assert.equal(h.layer.getDiagnostics().playing, false);
assert.equal(h.layer.getDiagnostics().timerActive, false);
assert.equal(h.layer.getRowControls().summary.status, NO_IMAGERY_HOST);
assert.equal(h.layer.getRowControls().info, NO_IMAGERY_HOST);
await h.layer.update();
assert.equal(refreshes, 2);
t.mock.timers.tick(10_000);
assert.equal(h.stages.length, 2);
assert.equal(h.layer.getDiagnostics().time, times[2]);
assert.equal(h.stages.length, 2, 'nothing stages without a host');
host = { collection: {}, kind: 'globe' };
h.eventTarget.emit('gev:map-stack-changed');
assert.equal(h.layer.getDiagnostics().playing, true);
assert.equal(h.layer.getDiagnostics().timerActive, true);
t.mock.timers.tick(2000);
assert.equal(h.stages.length, 3);
assert.equal(h.stages[2].time, times[0]);
await flush();
assert.equal(h.stages.at(-1).time, times[0], 'the retained time restages');
h.layer.destroy();
assert.equal(h.eventTarget.size, 0);
});
@@ -1421,25 +1554,21 @@ for (const [id, product] of [
const [shell] = h.shells();
assert.equal(shell.show, true);
layer.setParams({ play: true });
t.mock.timers.tick(2000);
worldClock.seek(Date.parse(times[0]));
await flush();
assert.equal(
layer.getDiagnostics().time,
times[0],
'history advances at street level',
'history moves at street level',
);
camera.positionCartographic.height = 59_999;
camera.moveEnd.emit();
assert.equal(shell.show, true, 'no height gate');
assert.equal(layer.getDiagnostics().playing, true);
assert.equal(layer.getDiagnostics().timerActive, true);
host = { collection: null, kind: 'none' };
events.emit('gev:map-stack-changed');
assert.equal(shell.show, false);
assert.equal(layer.getRowControls().summary.status, NO_IMAGERY_HOST);
assert.equal(layer.getDiagnostics().timerActive, false);
host = { collection: h.viewer.imageryLayers, kind: 'globe' };
events.emit('gev:map-stack-changed');
assert.equal(shell.destroyed, true);
@@ -1638,10 +1767,12 @@ test('satellite mode chips restage history without changing time or latest-follo
await flush();
h.stages[0].finish();
await update;
h.layer.setParams({ step: -1 });
worldClock.seek(Date.parse(times[1]));
await flush();
h.stages[1].finish();
await flush();
h.layer.setParams({ infrared: 'full' });
await flush();
assert.equal(h.stages[2].time, times[1]);
assert.equal(h.stages[2].infrared, 0);
assert.equal(h.layer.getParams().infrared, 0);
@@ -1765,7 +1896,7 @@ test('a delayed installation failure retains the replacement and does not throw
h.rendering.clear();
});
test('one row steps every registered observation; missing frames hide and latest restores each product', async (t) => {
test('a row steps the world clock through every registered observation; missing frames hide and latest goes live', async (t) => {
const clock = createWeatherClock();
const radar = layerHarness({ clock });
const satellite = layerHarness({
@@ -1798,6 +1929,14 @@ test('one row steps every registered observation; missing frames hide and latest
.chips.filter(({ id }) =>
['previous', 'play', 'next', 'latest'].includes(id),
);
// A step back from live goes to the newest frame, and the next one back
// to the frame before it.
radar.layer.setParams({ step: -1 });
await flush();
assert.equal(clock.getState().target, times[2]);
assert.equal(clock.world.isPlaying(), false);
for (const h of [radar, satellite]) h.stages.at(-1)?.finish();
await flush();
radar.layer.setParams({ step: -1 });
await flush();
assert.equal(clock.getState().target, times[1]);
@@ -1849,6 +1988,33 @@ test('one row steps every registered observation; missing frames hide and latest
assert.equal(clock.getState().products.length, 1);
});
test('a row’s play and latest move the world clock as its timeline does', async (t) => {
const clock = createWeatherClock();
const { world } = clock;
const h = layerHarness({ clock });
t.after(() => {
h.layer.destroy();
clock.destroy();
});
const update = h.layer.update();
await flush();
h.stages.at(-1).finish();
await update;
h.layer.setParams({ play: true });
assert.equal(world.isPlaying(), true);
assert.equal(world.getState().stepping, false, 'the world plays on its own');
assert.ok(
world.now() - Date.parse(times[0]) < 1_000,
'from the start when live',
);
h.layer.setParams({ play: true });
assert.equal(world.isPlaying(), false);
h.layer.setParams({ latest: true });
assert.equal(world.isLive(), true);
await flush();
assert.equal(clock.getState().mode, 'latest');
});
test('history manifest expiry hides imagery without jumping to latest; host resume keeps the target', async (t) => {
const clock = createWeatherClock();
let value = snapshot;
@@ -1861,7 +2027,7 @@ test('history manifest expiry hides imagery without jumping to latest; host resu
await flush();
h.stages.at(-1).finish();
await update;
const history = clock.setTarget(times[0]);
const history = seekTo(clock, times[0]);
await flush();
h.stages.at(-1).finish();
await history;
@@ -1930,7 +2096,7 @@ test('satellite global selection uses the three-hour gap and preserves the share
await flush();
h.stages.at(-1).finish();
await update;
await clock.setTarget(times[0]);
await seekTo(clock, times[0]);
assert.equal(
h.layer.getDiagnostics().hidden,
true,
@@ -1949,6 +2115,64 @@ 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 = seekTo(
clock,
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]);
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 });
@@ -1959,11 +2183,11 @@ test('switching to history cancels a still-loading latest refresh and a later ta
const update = h.layer.update();
await flush();
const latest = h.stages.at(-1);
const oldHistory = clock.setTarget(times[0]);
const oldHistory = seekTo(clock, times[0]);
await flush();
assert.equal(latest.signal.aborted, true);
const oldStage = h.stages.at(-1);
const current = clock.setTarget(times[1]);
const current = seekTo(clock, times[1]);
await flush();
assert.equal(oldStage.signal.aborted, true);
h.stages.at(-1).finish();
@@ -2273,8 +2497,9 @@ test('failed prefetch leaves the current frame and errors unchanged and releases
assert.deepEqual(h.rendering.getDiagnostics(), before);
});
test('layer warms the next advertised observation only after a successful playing frame, wrapping at the end', async (t) => {
test('as the world plays, the layer warms the next advertised observation after each frame that shows', async (t) => {
const clock = createWeatherClock();
const { world } = clock;
const h = layerHarness({ clock });
const warmed = [];
let cancels = 0;
@@ -2292,45 +2517,45 @@ test('layer warms the next advertised observation only after a successful playin
await flush();
h.stages.at(-1).finish();
await updated;
assert.equal(warmed.length, 0);
const play = clock.play();
await seekTo(clock, times[0]);
h.stages.at(-1).finish();
await flush();
assert.equal(warmed.length, 0, 'paused, nothing is warmed');
world.play({ rate: 1e-9, continuous: true });
assert.equal(clock.getState().advancing, true);
await seekTo(clock, times[1]);
assert.equal(warmed.length, 0, 'still staging');
h.stages.at(-1).finish();
await play;
await flush();
assert.deepEqual(
warmed.map(({ time }) => time),
[times[0]],
[times[2]],
);
assert.deepEqual(warmed[0].options, { infrared: 100 });
const next = clock.setTarget(times[0]);
await flush();
h.stages.at(-1).finish();
await next;
assert.deepEqual(
warmed.map(({ time }) => time),
[times[0], times[1]],
);
const failed = clock.setTarget(times[1]);
await flush();
await seekTo(clock, times[0]);
h.stages.at(-1).finish(false);
await failed;
assert.equal(warmed.length, 2);
const priorCancels = cancels;
clock.pause();
assert.ok(cancels > priorCancels);
const paused = clock.setTarget(times[2]);
await flush();
assert.equal(warmed.length, 1, 'a failed frame warms nothing');
await seekTo(clock, times[2]);
h.stages.at(-1).finish();
await paused;
assert.equal(warmed.length, 2);
await clock.play();
await flush();
assert.equal(warmed.length, 1, 'the world plays on past the newest frame');
const priorCancels = cancels;
world.pause();
await flush();
assert.ok(cancels > priorCancels);
await seekTo(clock, times[1]);
h.stages.at(-1).finish();
await flush();
assert.equal(warmed.length, 1);
world.play({ rate: 1e-9, continuous: true });
h.documentRef.hidden = true;
h.documentRef.emit('visibilitychange');
await flush();
h.stages.at(-1).finish();
h.stages.at(-1)?.finish();
await flush();
assert.equal(warmed.length, 2, 'hidden products do not prefetch');
assert.equal(warmed.length, 1, 'hidden products do not prefetch');
world.goLive();
});
for (const product of ['radar', 'clouds-regional', 'lightning']) {
@@ -2469,6 +2694,99 @@ test('a frame source supplies regional tiles in place of the tile route, through
h.rendering.clear();
});
test('a frame source that names its tile detail draws global clouds from its tiles to that level', async () => {
let now = 0;
const requests = [];
const h = renderingHarness({
now: () => now,
fetchImpl: () => assert.fail('supplied clouds are not fetched'),
frameSource: {
getImage: () => assert.fail('no mosaic when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return suppliedTile();
},
maximumLevel: (product) => (product === 'clouds' ? 6 : 8),
},
});
h.viewer.scene.globe.tilesLoaded = false;
const loaded = h.rendering.setFrame(globalSnapshot, times[0]);
assert.equal(h.providers.length, 1);
const [provider] = h.providers;
assert.equal(provider.options, undefined, 'no URL template provider');
assert.equal(provider.maximumLevel, 6);
await provider.requestImage(5, 3, 4, {});
assert.deepEqual(
[requests[0].product, requests[0].z, requests[0].x, requests[0].y],
['clouds', 4, 5, 3],
);
now = 500;
h.settle();
assert.equal(await loaded, true);
h.rendering.clear();
// Radar takes the level the feed names for it.
const radar = renderingHarness({
frameSource: {
getTile: async () => suppliedTile(),
maximumLevel: () => 8,
},
});
radar.rendering.setFrame(snapshot, times[0]);
assert.equal(radar.providers[0].maximumLevel, 8);
radar.rendering.clear();
});
test("a frame source naming no usable level keeps the layer's own detail", async () => {
for (const maximumLevel of [
() => null,
() => 13,
() => 2.5,
() => 'deep',
() => {
throw new Error('no level');
},
]) {
const h = renderingHarness({
frameSource: { getTile: async () => suppliedTile(), maximumLevel },
});
h.rendering.setFrame(snapshot, times[0]);
assert.equal(h.providers[0].maximumLevel, 6);
h.rendering.clear();
// Global clouds stay on the one image, cut to level 3.
let mosaics = 0;
const clouds = renderingHarness({
frameSource: {
getImage: async () => {
mosaics++;
return { width: 2048, height: 1024, close() {} };
},
getTile: () => assert.fail('clouds are not tiled without a level'),
maximumLevel,
},
});
await showMosaic(clouds, times[0]);
assert.equal(mosaics, 1);
assert.equal(clouds.providers[0].maximumLevel, 3);
clouds.rendering.clear();
}
// A level without tiles leaves global clouds on the mosaic.
let images = 0;
const h = renderingHarness({
frameSource: {
getImage: async () => {
images++;
return suppliedTile();
},
maximumLevel: () => 6,
},
});
h.rendering.setFrame(globalSnapshot, times[0]);
await flush();
assert.equal(images, 1);
h.rendering.clear();
});
test('a failed supplied tile fails the staged frame through errorEvent', async () => {
const h = renderingHarness({
frameSource: {
@@ -2523,6 +2841,52 @@ test('supplied regional infrared tiles are canvases, so they get the transfer wi
}
});
test('global clouds tiles get the infrared transfer, and prefetch asks for tiles, not the image', async () => {
const hadBitmap = Object.hasOwn(globalThis, 'ImageBitmap');
const previous = globalThis.ImageBitmap;
globalThis.ImageBitmap = class ImageBitmap {
width = 256;
height = 256;
close() {}
};
try {
const requests = [];
const h = renderingHarness({
frameSource: {
getImage: () => assert.fail('no image when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return new globalThis.ImageBitmap();
},
maximumLevel: () => 6,
},
});
void h.rendering.setFrame(globalSnapshot, times[0]);
const tile = await h.providers[0].requestImage(5, 3, 4, {});
assert.equal(tile.drawnWith, null, 'drawn upright, not flipped');
assert.ok(tile.pixels, 'the infrared transfer ran');
h.rendering.clear();
requests.length = 0;
const warm = renderingHarness({
frameSource: {
getImage: () => assert.fail('no image when the feed tiles clouds'),
getTile: async (request) => {
requests.push(request);
return new globalThis.ImageBitmap();
},
maximumLevel: () => 6,
},
});
assert.equal(await warm.rendering.prefetch(globalSnapshot, times[1]), true);
assert.ok(requests.length > 0, 'prefetch asked for tiles');
assert.ok(requests.every((request) => request.product === 'clouds'));
warm.rendering.clear();
} finally {
if (hadBitmap) globalThis.ImageBitmap = previous;
else delete globalThis.ImageBitmap;
}
});
test('tiled prefetch asks the frame source for the same level 0/1 tiles and releases them', async (t) => {
const requests = [];
const supplied = [];
@@ -2637,3 +3001,40 @@ test('the layer hands rendering a frame source only when its feed is one', () =>
assert.equal(typeof seen[1].getTile, 'function');
assert.equal(seen[1].getImage, undefined);
});
test('a feed names the source behind each product, before any manifest does', (t) => {
t.mock.method(console, 'warn', () => {});
const quiet = {
documentRef: target({ hidden: false }),
eventTarget: target(),
matchMedia: () => target({ matches: false }),
};
const asked = [];
const feed = {
getSnapshot: async () => snapshot,
sourceName(kind) {
asked.push(kind);
if (kind === 'satellite') throw new Error('no name');
return kind === 'radar' ? ' NOAA MRMS ' : 'NOAA\u200b GLM';
},
};
const radar = createWeatherLayer({ ...quiet, feed, id: 'weather-radar' });
assert.equal(radar.source, 'NOAA MRMS');
const stats = radar.getStats();
assert.equal(stats.source, 'NOAA MRMS');
assert.equal(stats.sourceVerbatim, true);
// A name a manifest could not carry, or a failing call, leaves nowCOAST, as
// does a feed with no names.
for (const id of ['weather-lightning', 'weather-satellite']) {
const layer = createWeatherLayer({ ...quiet, feed, id });
assert.equal(layer.source, 'NOAA nowCOAST · OBSERVED', id);
assert.equal(layer.getStats().source, 'NOAA nowCOAST', id);
assert.equal(layer.getStats().sourceVerbatim, undefined, id);
}
assert.deepEqual(asked, ['radar', 'lightning', 'satellite']);
const unnamed = createWeatherLayer({
...quiet,
feed: { getSnapshot: async () => snapshot },
});
assert.equal(unnamed.source, 'NOAA nowCOAST · OBSERVED');
});
Loaded 100 of 407 files, more files were not shown because too many files have changed in this diff. Show more