Merge main into feat/shipwrecks

Main added the News layer at the same places: both layers are kept in the
layer names, panel order (News stays last of Events), standalone sources,
voice manifest, credits, DATA_SOURCES and the CURRENT-STATE table. News took
share-link token 00 first, so Shipwrecks moves to 01 (ledger, registry,
CURRENT-STATE and the token tests). The catalog now has 40 layers and the
share-link registry 38. Shipwreck strings are added to the new Hebrew
catalog; the other catalogs keep both sides' strings.
This commit is contained in:
Sameh Khamis committed 2026-11-10 14:03:39 -08:00
commit 8ff22f1a12
466 files changed
+57748 -1865

No files matched your search

+2 -1
View File
@@ -1,7 +1,8 @@
import { normalizeDisplayText } from '../../data/displayText.js';
import { QUERY_LIMIT, QUERY_SNAP_DEGREES } from './policy.js';
function textTag(value) {
const t = String(value ?? '').trim();
const t = normalizeDisplayText(value);
return t || null;
}
+23
View File
@@ -182,6 +182,28 @@ export function createPanel({ state: layerState, parts }) {
: null;
}
/** The tracked airliner's photo with its credit, or null. The subject
* refresh resolves it; only the subject it was resolved for shows it. */
function presentPhoto(subject) {
const held = layerState.subjectPhoto;
if (
!held ||
held.layerId !== subject.layerId ||
String(held.id) !== String(subject.id)
)
return null;
const { photo } = held;
return {
src: photo.src,
width: photo.width ?? null,
height: photo.height ?? null,
link: photo.link,
credit: t('Photo © {photographer}', {
photographer: photo.photographer,
}),
};
}
function renderResults() {
if (!layerState.enabled || !layerState.results) return hidePanel();
ensurePanel();
@@ -191,6 +213,7 @@ export function createPanel({ state: layerState, parts }) {
kind: 'results',
subject: `${subject.label} · ${t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) })}`,
subjectNames: presentNames(subject.memberNames),
photo: presentPhoto(subject),
navigation: presentNavigation(),
rows: cohorts.map(presentRow),
note: t(
+117
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createPanel } from './panel.js';
import { createSubject } from './subject.js';
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
const cohort = (id, source, sourceStatus) => ({
@@ -36,3 +37,119 @@ test('a Contacts row names its provider as the Layers panel does, with its feed
);
state.offPanelLocale?.();
});
const PHOTO = Object.freeze({
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/n123ab',
});
/** The published Contacts view for one subject and the refresh's photo. */
function photoView(subject, subjectPhoto) {
const state = {
enabled: true,
results: { subject, cohorts: [] },
subjectPhoto,
cohortPages: new Map(),
panelListeners: new Set(),
panelSignature: '',
navigationIndex: 0,
};
const parts = {
navigation: { canNavigateNext: () => false },
rendering: { hideDirectionOverlay() {} },
};
createPanel({ state, parts }).renderResults();
state.offPanelLocale?.();
return state.panelView;
}
const FLIGHT = Object.freeze({
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
});
test('the Contacts view carries the tracked flight’s photo with its credit', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: PHOTO,
});
assert.deepEqual(view.photo, {
src: PHOTO.src,
width: 280,
height: 186,
link: PHOTO.link,
credit: 'Photo © Jane Doe',
});
});
test('the Contacts view has no photo without one, or with another subject’s', () => {
assert.equal(photoView(FLIGHT, null).photo, null);
assert.equal(
photoView(FLIGHT, { layerId: 'flights', id: 'def456', photo: PHOTO }).photo,
null,
);
assert.equal(
photoView(
{ layerId: 'ais-live-vessels', id: 'abc123', label: 'VESSEL' },
{ layerId: 'flights', id: 'abc123', photo: PHOTO },
).photo,
null,
);
});
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
const tracked = {
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
photo: PHOTO,
};
let current = tracked;
let lookups = 0;
const flights = {
getTrackedSubject: () => {
lookups += 1;
return current;
},
};
const military = {
getTrackedSubject: () => ({ ...tracked, layerId: 'military' }),
};
const { resolveSubjectPhoto } = createSubject({
state: {},
services: { flights, military, vessels: {}, installations: {} },
parts: {
navigation: {
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
},
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }),
PHOTO,
);
assert.equal(lookups, 1);
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'def456' }), null);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military-installations', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military', id: 'abc123' }),
null,
);
assert.equal(resolveSubjectPhoto(null), null);
current = null;
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
current = { ...tracked, photo: null };
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
});
+2
View File
@@ -29,6 +29,8 @@ export function createState({ services }) {
/** Stops following the manager's adoptions (see watchAdoptions). */
unwatchAdoptions: null,
subject: null,
/** The tracked flight's photo with the subject it belongs to, or null. */
subjectPhoto: null,
results: null,
visual: null,
/** Whether layer views replace the panel's initial markup yet. */
+52 -8
View File
@@ -378,19 +378,48 @@ export function createSubject({ state: layerState, services, parts, source }) {
*
* Identity (`subject.id`) is NEVER re-derived — only the rendered string.
* @param {{layerId: string, id: string, label: string}} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it (see trackedSubjectOf).
* @returns {string} The current label, or the cached one when the owning layer
* has no tracked subject (e.g. a cross-layer handoff is in flight).
*/
function resolveSubjectLabel(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId))
return subject?.label;
function resolveSubjectLabel(subject, tracked = trackedSubjectOf(subject)) {
return tracked?.label || subject?.label;
}
/**
* The owning flight layer's tracked-subject descriptor when it describes
* this subject, else null. Built once per refresh and shared by the label
* and the photo.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @returns {?{id: string, label: string, photo?: ?object}}
*/
function trackedSubjectOf(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId)) return null;
const layer =
subject.layerId === 'flights' ? flightsLayer : militaryFlightsLayer;
const tracked = layer.getTrackedSubject?.();
if (tracked?.label && String(tracked.id) === String(subject.id))
return tracked.label;
return subject.label;
return tracked && String(tracked.id) === String(subject.id)
? tracked
: null;
}
/**
* The tracked airliner's Planespotters photo, for the Contacts panel.
*
* Only the flights layer looks photos up, and only for the plane it tracks;
* a vessel, an installation, a military aircraft or an untracked flight has
* none.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it.
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
*/
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
return subject?.layerId === 'flights' && tracked?.photo
? tracked.photo
: null;
}
/** Refresh proximity counts/distances against the subject's current live position. */
@@ -417,8 +446,21 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (presence === SUBJECT_PRESENCE.LIVE) layerState.subjectMissing = false;
else if (presence === SUBJECT_PRESENCE.MISSING)
layerState.subjectMissing = true;
const nextLabel = resolveSubjectLabel(layerState.subject);
const tracked = trackedSubjectOf(layerState.subject);
const nextLabel = resolveSubjectLabel(layerState.subject, tracked);
const labelChanged = nextLabel !== layerState.subject.label;
// The panel reads the photo from here, with the subject it belongs to.
const photo = resolveSubjectPhoto(layerState.subject, tracked);
layerState.subjectPhoto = photo
? {
layerId: layerState.subject.layerId,
id: layerState.subject.id,
photo,
}
: null;
// A photo arriving after selection is render-worthy on its own, as a label.
const photoChanged =
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
layerState.subject = { ...layerState.subject, position, label: nextLabel };
const movementM = layerState.lastEvaluatedPosition
? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position)
@@ -439,7 +481,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// kept the ICAO hex until unrelated movement, a source-revision bump, or
// page rotation happened to repaint it. Gated on an ACTUAL change so the
// common no-op refresh (every 750 ms) still costs no repaint.
if (labelChanged) parts.panel.renderResults();
if (labelChanged || photoChanged) parts.panel.renderResults();
parts.rendering.scheduleDirectionOverlayUpdate(force);
return;
}
@@ -502,6 +544,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
militaryInstallationsLayer.setContextAnchor?.(null);
layerState.autoFocusRetryPending = false;
layerState.subject = null;
layerState.subjectPhoto = null;
layerState.subjectMissing = false;
layerState.results = null;
layerState.navigationHistory = [];
@@ -528,6 +571,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
resolveSubjectPosition,
collectionSubjectPosition,
resolveSubjectLabel,
resolveSubjectPhoto,
refreshSelectedSubject,
subjectFromContext,
markSubjectEvicted,
+37 -4
View File
@@ -1,5 +1,6 @@
import { msg, t } from '../../i18n/index.js';
import { STATUS_POLL_MS } from './policy.js';
import { ACTIVATION_ENTER_ALTITUDE_M, STATUS_POLL_MS } from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
@@ -13,6 +14,14 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: STATUS_POLL_MS,
/**
* Kept so camera moves can repaint the row before the next status poll.
* @param {object} dataManager DataLayerManager instance.
*/
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
},
/**
* Return a sampled array of detectable station objects for HUD overlay rendering.
* @param {Object} [options] - Sampling options (maxCount, seed).
@@ -57,15 +66,39 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Return current layer statistics for the UI status display.
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean }}
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean, status?: string, statusMessage?: string }}
*/
getStats() {
// A city in range without points is loading even before its fetch
// starts: the row repaints on entry, ahead of beginLoading().
const loading =
layerState._loading ||
[...layerState._activeCityIds].some(
(cityId) =>
!layerState._cityRuntime.has(cityId) &&
!layerState._failedCityIds.has(cityId),
);
const stats = {
count: layerState._count,
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
loading,
};
if (layerState._loading) {
// No system in range: the camera is too high or no system is near. A
// failed city also leaves range empty and reports its failure below.
if (
layerState._enabled &&
!loading &&
layerState._activeCityIds.size === 0 &&
layerState._failedCityIds.size === 0
) {
// English: the analyst's empty note and the row's prompt, both shown
// through translateStatusMessage (ui/statusText.js).
const note = layerState._altitudeGateEnabled
? `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered city`;
return { ...stats, status: 'zoom-in', statusMessage: note };
}
if (loading) {
stats.loadingLabel =
layerState._activeCityIds.size > 0
? t('syncing {count} city feeds...', {
+1
View File
@@ -169,6 +169,7 @@ export function createLifecycle({
viewer.scene.primitives.remove(layerState._pointCollection);
layerState._pointCollection = null;
}
layerState._dataManager = null;
layerState._viewer = null;
},
};
+366
View File
@@ -0,0 +1,366 @@
// Bike Share's Layers row. With no system in range it says why instead of
// "never" and keeps no date for data it no longer draws. After the camera
// settles, the last row the panel painted must match what the layer reports
// now. Each case drives the real viewport,
// ingestion, rendering and controls; the manager is a spy that records the
// row text (LayerPanel._buildMetaText) at every refreshLayerStats() call.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { CITY_BY_ID, GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
const BOSTON_ID = 'boston-bluebikes';
const TORONTO_ID = 'toronto-bike-share';
const BUFFALO_ID = 'buffalo-reddy';
const LONDON = { lat: 51.5072, lon: -0.1276 };
const BOSTON = { lat: 42.3601, lon: -71.0589 };
const BOSTON_NUDGED = { lat: 42.37, lon: -71.05 };
const BETWEEN = { lat: 43.25, lon: -79.1 };
const TORONTO_ONLY = { lat: 43.7, lon: -79.6 };
const LOW_M = 10_000;
globalThis.document ??= {
addEventListener() {},
removeEventListener() {},
};
function deferred() {
let resolve;
const promise = new Promise((res) => {
resolve = res;
});
return { promise, resolve };
}
function makeSource() {
const cityOf = (url) => {
for (const [id, city] of CITY_BY_ID) {
if (url === city.stationInformationUrl) return { id, kind: 'info' };
if (url === city.stationStatusUrl) return { id, kind: 'status' };
}
throw new Error(`unexpected GBFS url ${url}`);
};
const source = {
dead: new Set(),
/** `${cityId}:${kind}` → deferred that gates the answer. */
gates: new Map(),
async getStations(url, { signal } = {}) {
const { id, kind } = cityOf(url);
const gate = source.gates.get(`${id}:${kind}`);
if (gate) {
await new Promise((resolve, reject) => {
gate.promise.then(resolve);
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
);
});
} else {
await new Promise((resolve) => setTimeout(resolve, 1));
}
signal?.throwIfAborted();
if (source.dead.has(id)) throw new Error('GBFS HTTP 503');
const city = CITY_BY_ID.get(id);
if (kind === 'info') {
return {
data: {
stations: [
{
station_id: `${id}-1`,
name: `${id} dock`,
lat: city.centerLat,
lon: city.centerLon,
capacity: 10,
},
],
},
};
}
return {
data: {
stations: [
{
station_id: `${id}-1`,
num_bikes_available: 3,
num_docks_available: 7,
is_installed: true,
is_renting: true,
is_returning: true,
},
],
},
};
},
};
return source;
}
/** The row as the panel draws it: state chip, count, meta text. */
const rowText = (raw) => {
const stats = {
count: 0,
lastUpdate: null,
...raw,
loading: raw.loading === true,
};
const meta = LayerPanel.prototype._buildMetaText({
id: 'bikeshare',
source: 'GBFS',
enabled: true,
lifecycleState: 'enabled',
stats,
});
return `${layerFeedState(stats)} | ${stats.count || '—'} | ${meta}`;
};
function makeLiveLayer() {
const source = makeSource();
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
};
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.ingestion = createIngestion(context);
parts.model = createModel(context);
parts.viewport = createViewport(context);
parts.rendering = createRendering(context);
parts.selection = {
_installClickHandler() {},
_clearSelection() {},
_onKeyDown() {},
};
parts.queries = { collectDetectableStations: () => [] };
parts.lifecycle = createLifecycle(context);
const { methods: controls } = createControls(context);
const camera = { ...LONDON, height: LOW_M };
const viewer = {
camera: {
get positionCartographic() {
return Cesium.Cartographic.fromDegrees(
camera.lon,
camera.lat,
camera.height,
);
},
computeViewRectangle: () => undefined,
changed: { addEventListener() {}, removeEventListener() {} },
},
scene: { globe: {}, primitives: { add() {}, remove() {} } },
};
parts.lifecycle.methods.init(viewer);
const painted = [];
controls.attachDataManager({
refreshLayerStats() {
painted.push(rowText(controls.getStats()));
},
});
return {
state,
source,
painted,
lastPainted: () => painted.at(-1),
stats: () => controls.getStats(),
live: () => rowText(controls.getStats()),
moveTo(place, height = LOW_M) {
Object.assign(camera, place, { height });
return parts.viewport.runProximityCheck();
},
async enable() {
parts.lifecycle.methods.enable(viewer);
await settle();
},
};
}
async function settle() {
for (let i = 0; i < 5; i += 1)
await new Promise((resolve) => setTimeout(resolve, 2));
}
test('entering a city paints the loading row, not "never"', async () => {
const layer = makeLiveLayer();
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const before = layer.painted.length;
const entering = layer.moveTo(BOSTON);
assert.ok(layer.painted.length > before, 'entering repainted');
const atEntry = layer.lastPainted();
const liveAfter = layer.live();
info.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('re-entering a city with cached station info paints loading', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
await layer.moveTo(LONDON);
await settle();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
const entering = layer.moveTo(BOSTON);
const atEntry = layer.lastPainted();
await Promise.resolve();
await Promise.resolve();
const liveAfter = layer.live();
status.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('leaving a city mid-load does not leave the row on LOADING', async () => {
const layer = makeLiveLayer();
layer.source.gates.set(`${BOSTON_ID}:info`, deferred());
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.equal(layer.state._loading, true);
await layer.moveTo(LONDON);
await entering;
await settle();
assert.equal(layer.state._loading, false);
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('a camera nudge during the first load still repaints the drawn stations', async () => {
const layer = makeLiveLayer();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.ok(layer.state._cityRuntime.has(BOSTON_ID), 'points are drawn');
await layer.moveTo(BOSTON_NUDGED);
status.resolve();
await entering;
await settle();
assert.equal(layer.state._count, 1, 'one station on the map');
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving a city whose load failed repaints the error away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BOSTON_ID);
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.match(layer.lastPainted(), /GBFS fetch error/i);
await layer.moveTo(LONDON);
await settle();
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving the failed city of two repaints DEGRADED away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BUFFALO_ID);
await layer.enable();
await layer.moveTo(BETWEEN);
await settle();
assert.match(layer.lastPainted(), /^degraded/);
await layer.moveTo(TORONTO_ONLY);
await settle();
assert.doesNotMatch(layer.live(), /^degraded/);
assert.equal(layer.lastPainted(), layer.live());
});
test('above the altitude gate the row says how low to fly', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(LONDON, 2_000_000);
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(stats.statusMessage, 'Fly below 48 km to a covered city');
assert.equal(stats.error, undefined);
});
test('a city with no system says so and counts the ones there are', async () => {
const layer = makeLiveLayer();
await layer.enable();
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(
stats.statusMessage,
`No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`,
);
assert.equal(stats.count, 0);
});
test('a city in range, loading, failed or a disabled layer gets no prompt', async () => {
const layer = makeLiveLayer();
assert.equal(layer.stats().status, undefined, 'disabled');
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const entering = layer.moveTo(BOSTON);
assert.equal(layer.stats().status, undefined, 'loading');
info.resolve();
await entering;
await settle();
assert.equal(layer.stats().status, undefined, 'loaded');
// Left mid-load: range is empty, but the aborted load still owns the row.
const leaving = makeLiveLayer();
leaving.source.gates.set(`${BOSTON_ID}:info`, deferred());
await leaving.enable();
const loading = leaving.moveTo(BOSTON);
await settle();
const left = leaving.moveTo(LONDON);
assert.equal(leaving.state._activeCityIds.size, 0);
assert.equal(leaving.stats().loading, true);
assert.equal(leaving.stats().status, undefined, 'leaving mid-load');
await Promise.all([loading, left]);
const failed = makeLiveLayer();
failed.source.dead.add(BOSTON_ID);
await failed.enable();
await failed.moveTo(BOSTON);
await settle();
assert.equal(failed.stats().status, undefined, 'failed');
assert.equal(failed.stats().error, 'GBFS fetch error');
});
test('leaving every system behind drops the date of the data it drew', async () => {
for (const height of [LOW_M, 2_000_000]) {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.ok(layer.stats().lastUpdate, 'Boston is dated');
await layer.moveTo(LONDON, height);
assert.equal(layer.stats().lastUpdate, null, `at ${height} m`);
}
});
+4
View File
@@ -19,6 +19,10 @@ export function createState({ services }) {
layerState._viewer = null;
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} Manager that repaints the layer's row. */
layerState._dataManager = null;
/** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */
layerState._pointCollection = null;
+25 -3
View File
@@ -116,6 +116,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
parts.rendering.removeCityPoints(cityId);
}
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
function refreshRow() {
layerState._dataManager?.refreshLayerStats?.('bikeshare');
}
/** Deactivate all currently active cities and clear the active set. */
function deactivateAllCities() {
@@ -125,6 +130,8 @@ export function createViewport({ state: layerState, services, parts, source }) {
// A failure belongs to a city in range; none are once everything is off.
layerState._failedCityIds.clear();
layerState._count = 0;
// Nothing is left on the map to date.
layerState._lastUpdate = null;
}
/**
@@ -203,9 +210,11 @@ export function createViewport({ state: layerState, services, parts, source }) {
const generation = ++layerState._proximityGeneration;
const altitude = getCameraAltitude(layerState._viewer);
const wasGateEnabled = layerState._altitudeGateEnabled;
// Altitude gate: disable all cities when camera is too high
if (!shouldActivateAtAltitude(altitude)) {
deactivateAllCities();
if (wasGateEnabled) refreshRow();
return;
}
@@ -220,15 +229,25 @@ export function createViewport({ state: layerState, services, parts, source }) {
}
}
// A failure never outlives its city's range.
let failureCleared = false;
for (const cityId of layerState._failedCityIds) {
if (!nextActive.has(cityId)) layerState._failedCityIds.delete(cityId);
if (!nextActive.has(cityId)) {
layerState._failedCityIds.delete(cityId);
failureCleared = true;
}
}
const changed =
!wasGateEnabled ||
failureCleared ||
nextActive.size !== layerState._activeCityIds.size ||
[...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId));
layerState._activeCityIds = nextActive;
if (layerState._activeCityIds.size === 0) {
if (nextActive.size === 0) {
layerState._count = 0;
return;
layerState._lastUpdate = null;
}
if (changed) refreshRow();
// Only activate cities that don't already have rendered points
const toActivate = [];
@@ -240,6 +259,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
await Promise.all(
toActivate.map((cityId) => activateCity(cityId, generation)),
);
// Superseded loads repaint too: a newer check may have painted the row
// while this one was still loading, or found nothing to load itself.
if (layerState._enabled) refreshRow();
}
/** Schedule a debounced proximity check after camera movement. */
+1 -1
View File
@@ -448,7 +448,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
// Photoreal regime. Sampling is delegated to the shared coarse-cell
// sampler. It remains event-driven, one-shot per cell, and keeps its
// sampler. It remains event-driven, a few probes per cell, and keeps its
// existing acceptance window; CCTV adds no rooftop rejection policy.
if (sampleGround && parts.model.projectionTilesReady()) {
record.groundMeshSampleRequestCount =
+8
View File
@@ -3,6 +3,10 @@ import { fireDetectionKey } from '../../data/firmsLabels.js';
import { filterFires } from '../../data/firmsIntensity.js';
import { msg } from '../../i18n/index.js';
/** A time a Date can print: epoch ms within JavaScript's date range. */
const isSnapshotEnd = (value) =>
Number.isFinite(value) && Math.abs(value) <= 8_640_000_000_000_000;
export function createIngestion({
layerState,
services,
@@ -32,6 +36,7 @@ export function createIngestion({
return;
if (payload.keyRequired) {
layerState._keyRequired = true;
layerState._at = null;
layerState._error = null;
layerState._stale = false;
return;
@@ -39,6 +44,9 @@ export function createIngestion({
layerState._keyRequired = false;
layerState._error = null;
layerState._stale = Boolean(payload?.stale);
// A snapshot of the 24 hours to a set time names it; one of the
// trailing 24 hours to now does not.
layerState._at = isSnapshotEnd(payload?.at) ? payload.at : null;
const previousSelection = layerState._selectedFire;
layerState._selectedFire = null;
layerState._allFires = adaptFirmsRecords(payload?.fires);
+1
View File
@@ -127,6 +127,7 @@ export function createLifecycle({
layerState._rowControlsListener = null;
layerState._cellCount = 0;
layerState._lastUpdate = null;
layerState._at = null;
layerState._keyRequired = false;
layerState._stale = false;
layerState._error = null;
+14 -3
View File
@@ -8,7 +8,7 @@ import {
rampTrackGradient,
sliderPositionForFrp,
} from '../../data/firmsIntensity.js';
import { formatNumber, t } from '../../i18n/index.js';
import { formatNumber, formatUtcDayMonth, t } from '../../i18n/index.js';
import { LOD_LEVELS, REFRESH_INTERVAL_MS } from './policy.js';
/** Slider resolution: whole-percent positions along the log axis. */
@@ -190,8 +190,9 @@ export function createQueries({
* Layer stats for the data panel. Degraded feed states surface through
* `error` (established qa-failstate pattern: a dead feed must never look
* like a healthy empty layer) with a matching human `loadingLabel`:
* 'LIVE · updated Xm ago' fresh, 'STALE · cached Xh' when the proxy
* served past-TTL cache, 'KEY REQUIRED' keyless.
* 'LIVE · updated Xm ago' fresh, '24 h to MM-DD HH:MM UTC' for a
* snapshot that ends at a set time (`at`), 'STALE · cached Xh' when the
* proxy served past-TTL cache, 'KEY REQUIRED' keyless.
*/
getStats() {
const now = Date.now();
@@ -213,6 +214,11 @@ export function createQueries({
loadingLabel = staleText;
} else if (layerState._error) {
loadingLabel = layerState._error;
} else if (Number.isFinite(layerState._at)) {
loadingLabel = t('24 h to {day} {time} UTC', {
day: formatUtcDayMonth(layerState._at),
time: new Date(layerState._at).toISOString().slice(11, 16),
});
} else if (layerState._lastUpdate) {
loadingLabel = t('LIVE · updated {age}', {
age: components.model.formatAgoMinutes(now - layerState._lastUpdate),
@@ -226,6 +232,11 @@ export function createQueries({
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
stale: layerState._stale,
// The end of the 24 hours shown when the snapshot ends at a set time;
// null for the trailing 24 hours to now. Such a snapshot is not live,
// so the row names the provider without the catalog's "LIVE".
at: Number.isFinite(layerState._at) ? layerState._at : null,
...(Number.isFinite(layerState._at) ? { source: 'NASA FIRMS' } : {}),
// The machine-readable half of the keyless state, ahead of the human
// strings below: without it "no key configured" is indistinguishable
// from a broken feed, and the row reads as a fault instead of a step
+2
View File
@@ -77,6 +77,8 @@ export function createFirmsState({ services, config }) {
layerState._lastUpdate = null;
layerState._at = null;
layerState._currentLodId = null;
layerState._currentLodIndex = -1;
+47
View File
@@ -0,0 +1,47 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (context) => {
const now = 1800000000000;
context.mock.method(Date, 'now', () => now);
const previousLocale = getLocale();
const at = Date.UTC(2026, 9, 21, 15);
const layerState = {
_loading: false,
_stale: false,
_keyRequired: false,
_error: null,
_lastUpdate: now - 120000,
_at: at,
_count: 1,
_cellCount: 0,
_fires: [],
};
const model = createModel({ services: { anchors: {} } });
const { methods } = createQueries({
layerState,
components: { model },
config: {},
});
try {
setLocale('en');
assert.equal(methods.getStats().loadingLabel, '24 h to 10-21 15:00 UTC');
assert.equal(methods.getStats().at, at);
assert.equal(methods.getStats().source, 'NASA FIRMS', 'the row drops LIVE');
setLocale('de');
assert.equal(
methods.getStats().loadingLabel,
'24 Std. bis 21.10. 15:00 UTC',
);
layerState._at = null;
setLocale('en');
assert.equal(methods.getStats().loadingLabel, 'LIVE · updated 2m ago');
assert.equal(methods.getStats().at, null);
assert.equal(methods.getStats().source, undefined);
} finally {
setLocale(previousLocale);
}
});
+111 -7
View File
@@ -1,5 +1,6 @@
import { classifyAircraft } from '../../data/aircraftClass.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { parsePlanespottersPhoto } from '../../data/planespottersPhoto.js';
import * as Cesium from 'cesium';
import {
ENRICH_MAX_INFLIGHT,
@@ -8,6 +9,7 @@ import {
ENRICH_AMBIENT_REFILL_TOKENS,
ENRICH_AMBIENT_REFILL_WINDOW_MS,
ENRICH_AMBIENT_PER_SWEEP,
ENRICH_RETRY_COOLDOWN_MS,
} from './policy.js';
export function createEnrichment({
@@ -17,11 +19,62 @@ export function createEnrichment({
layer,
resolveAsset,
}) {
function _enqueueEnrich(key, query, onData, priority = false) {
const { isMilitaryIcao } = services.militaryRegistry;
const { isTr3b } = services.aircraftPresentation;
/**
* Whether `key` is answered, queued, or cooling down after a failure. A
* key past its cool-down is released here so it can be asked again.
* @param {string} key Lookup key.
* @returns {boolean}
*/
function _enrichHeld(key) {
if (flightState._enrichSeen.has(key)) return true;
const retryAfter = flightState._enrichRetryAfter.get(key);
if (retryAfter === undefined) return false;
if (Date.now() < retryAfter) return true;
flightState._enrichRetryAfter.delete(key);
return false;
}
/**
* Whether a source failure is permanent: an unsupported lookup, or an HTTP
* 4xx other than 401/403 (an authorization refusal that may clear), 408
* (timeout) and 429 (rate limited). Anything else, including an error without a
* status, is temporary.
* @param {*} error The rejection, as `LiveSourceError` / `httpError` carry it.
* @returns {boolean}
*/
function _enrichFailureIsFinal(error) {
if (error?.code === 'unsupported') return true;
const status = Number(error?.status);
return (
Number.isInteger(status) &&
status >= 400 &&
status < 500 &&
status !== 401 &&
status !== 403 &&
status !== 408 &&
status !== 429
);
}
/**
* Ask each key at most once per session, except that a lookup whose source
* failed temporarily (rejected or threw) may be asked again after
* ENRICH_RETRY_COOLDOWN_MS; an answer, found or not, and a permanent
* refusal (see _enrichFailureIsFinal) are final.
* @param {string} key Session-unique lookup key.
* @param {object} query The source's enrichment query.
* @param {function(object):void} onData Receives a `found` answer.
* @param {boolean} [priority] Front of the queue.
* @param {function(*):?object} [read] Reads the source's answer first, for
* a lookup whose answer may arrive in more than one shape.
*/
function _enqueueEnrich(key, query, onData, priority = false, read = null) {
if (flightState.lifetime.signal.aborted) return;
if (flightState._enrichSeen.has(key)) return;
if (_enrichHeld(key)) return;
flightState._enrichSeen.add(key);
const job = { query, onData };
const job = { key, query, onData, read };
// Priority (tracked / model-eligible) goes to the FRONT so a deep ambient
// backlog can never delay the plane the user just clicked or zoomed into.
if (priority) flightState._enrichQueue.unshift(job);
@@ -61,9 +114,24 @@ export function createEnrichment({
signal: lifetime.signal,
});
})
.then((data) => {
if (!lifetime.signal.aborted && data && data.found) job.onData(data);
})
.then(
(answer) => {
const data = job.read ? job.read(answer) : answer;
if (!lifetime.signal.aborted && data && data.found)
job.onData(data);
},
(error) => {
// The source failed: release the key after a cool-down. A layer
// teardown is not a failure and schedules nothing, and a
// permanent refusal is as final as an answer.
if (lifetime.signal.aborted || _enrichFailureIsFinal(error)) return;
flightState._enrichSeen.delete(job.key);
flightState._enrichRetryAfter.set(
job.key,
Date.now() + ENRICH_RETRY_COOLDOWN_MS,
);
},
)
.catch(() => {
/* enrichment never surfaces errors */
})
@@ -119,6 +187,14 @@ export function createEnrichment({
(data) => {
const meta = flightState.records.data.get(icao24);
if (!meta) return;
// A late answer for a callsign the plane no longer flies is dropped.
if (
String(meta.callsign || '')
.trim()
.toUpperCase() !== cs
)
return;
meta.routeCallsign = cs;
meta.airline = data.airline || meta.airline;
if (data.origin && data.destination)
meta.route = { origin: data.origin, destination: data.destination };
@@ -129,6 +205,31 @@ export function createEnrichment({
); // route lookups only fire for the TRACKED plane — front of the queue
}
/** The tracked plane's photo from Planespotters, asked once per hex at the
* front of the queue like its route. A miss is final; a temporary failure
* is asked again after the cool-down. A military aircraft or a converted
* TR-3B is never looked up. The answer is read with
* `parsePlanespottersPhoto` whatever shape the source returns (the upstream
* answer, a server's cached shape, or an already-read photo), so only a
* checked photo is ever stored. */
function _requestPhotoEnrichment(icao24) {
if (!/^[0-9a-f]{6}$/i.test(icao24)) return;
const id = icao24.toLowerCase();
if (isMilitaryIcao(id) || isTr3b(id)) return;
_enqueueEnrich(
`p:${id}`,
{ kind: 'photo', id },
(data) => {
const meta = flightState.records.data.get(id);
if (!meta) return; // evicted while the lookup was in flight
const { src, width, height, photographer, link } = data;
meta.photo = { src, width, height, photographer, link };
},
true,
parsePlanespottersPhoto,
);
}
/** QA seam: headless harnesses (scripts/qa-enrich-ambient.mjs) shrink the
* bucket knobs via window.__GEV_ENRICH_AMBIENT_QA = {ceil, refillTokens,
* windowMs} — they cannot wait out a real 5-minute window. Read lazily each
@@ -196,7 +297,9 @@ export function createEnrichment({
);
const cand = [];
for (const [icao24, bb] of flightState._billboards) {
if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session
// Answered, queued, negative this session, or cooling down after a
// failure: never spend a token on it.
if (_enrichHeld(`t:${icao24}`)) continue;
if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only
if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works)
if (!bb.position || !occluder.isPointVisible(bb.position)) continue; // beyond the limb
@@ -233,6 +336,7 @@ export function createEnrichment({
_drainEnrich,
_requestTypeEnrichment,
_requestRouteEnrichment,
_requestPhotoEnrichment,
_ambientBudgetKnobs,
_refillAmbientBudget,
_sweepAmbientEnrichment,
+1
View File
@@ -312,6 +312,7 @@ export function createLifecycle({
flightState._displayFloorState.clear();
flightState._enrichQueue.length = 0;
flightState._enrichSeen.clear();
flightState._enrichRetryAfter.clear();
if (flightState._enrichDripTimer) {
clearTimeout(flightState._enrichDripTimer);
flightState._enrichDripTimer = null;
+110 -24
View File
@@ -1,14 +1,19 @@
import * as Cesium from 'cesium';
import { julianAt } from '../../time/julian.js';
import {
COURSE_HOLD_SPEED_MPS,
lerpAngleDeg,
speedRamp,
courseBetweenCartesians,
floorCoastedPosition,
staleCoastLimitSeconds,
staleCoastSecondsFrom,
staleHoldsForFix,
arcOffsetEnu,
courseSlewCapDps,
limitCourseStep,
corridorPathLatLon,
COAST_MAX_SPEED_MPS,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
@@ -36,6 +41,22 @@ import {
DISPLAY_CORRIDOR_FAIR_SHARE,
} from './policy.js';
/** Half a coarse floor cell (0.001°), less a margin so rounding keeps a
* clamped coordinate inside the cell. */
const HALF_CELL_DEG = 0.00049;
/**
* A coordinate held within half a cell of the cell's centre (the short way
* round for longitude), so a read lands in the given cell.
* @param {number} deg @param {number} centreDeg
* @returns {number}
*/
function clampToCell(deg, centreDeg) {
let d = deg - centreDeg;
d -= 360 * Math.round(d / 360);
return centreDeg + Math.max(-HALF_CELL_DEG, Math.min(HALF_CELL_DEG, d));
}
export function createMotion({
flightState,
services,
@@ -156,7 +177,7 @@ export function createMotion({
const renderTime =
sampledRenderTime ??
Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(flightState._scratchRenderTime),
julianAt(flightState.now(), flightState._scratchRenderTime),
-RENDER_DELAY_SEC,
flightState._scratchRenderTime,
);
@@ -231,30 +252,88 @@ export function createMotion({
);
}
// Newest POSITION is older than renderTime. OpenSky can still be receiving
// fresh contact/kinematic messages for that aircraft; freezing at a hard
// 60 s-after-position boundary produced the visible stop → catch-up → stop
// cadence. Coast through the latest real contact plus a bounded grace
// window, with an absolute cap so a stale cached feed cannot drift forever.
// Newest POSITION is older than renderTime. Coast on the last speed and
// heading for five minutes past it, then stop, dimmed as SIGNAL LOST.
// A contact last heard on or near the ground holds there instead, and a
// coast never goes below the ground.
const { coastSec } = _coastPlan(newest, info, elapsedSec);
_extrapolateFix(
newest,
info,
coastSec,
out,
(info && info.turnRateDps) || 0,
);
return coastSec > 0 ? floorCoastedPosition(out, cachedGroundFloor) : out;
}
/**
* How far a contact coasts past its newest fix at a display time
* `elapsedSec` after it: up to five minutes, or not at all for a contact
* that holds at a report on or near the ground. The hold decision is made once
* per report and kept on it.
* @param {{epochMs?: number, time: Cesium.JulianDate}} newest
* @param {object|undefined} info - The contact's record.
* @param {number} elapsedSec
* @returns {{coastSec: number, holds: boolean}}
*/
function _coastPlan(newest, info, elapsedSec) {
const coastLimitSec = staleCoastLimitSeconds({
// `epochMs` is captured once when the poll is normalized. Avoid allocating
// a Date per aircraft on every 12 Hz fleet tick.
// a Date per aircraft on every fleet tick.
fixEpochMs: Number.isFinite(newest.epochMs)
? newest.epochMs
: Cesium.JulianDate.toDate(newest.time).getTime(),
lastContactEpochMs: info?.lastContactEpochMs,
// Permit one minute of contact grace but cap any cached-feed drift at
// five minutes. Source backoff is exposed separately as a STALE cue.
minimumSec: 60,
// A plane that stops reporting keeps flying for five minutes, whatever
// its contact time, then stops dimmed as SIGNAL LOST. A missed update
// shows STALE throughout.
minimumSec: 300,
maximumSec: 300,
});
return _extrapolateFix(
const holds = staleHoldsForFix(newest, {
onGround: info?.onGround,
cachedGroundFloor,
});
return {
coastSec: staleCoastSecondsFrom({
newest,
elapsedSec,
coastLimitSec,
holds,
}),
holds,
};
}
/**
* Whether a contact has stopped where its coast ended (or held at its last
* report) with no newer report, and since when it has had none.
* @param {string} icao24
* @returns {{reportEpochMs: number, holds: boolean}|null} Null while a
* report is ahead of the display time or the contact is still coasting.
*/
function _signalLost(icao24) {
const newest = flightState._positionHistory.get(icao24)?.at(-1);
if (!newest) return null;
const newestMs = Number.isFinite(newest.epochMs)
? newest.epochMs
: Cesium.JulianDate.toDate(newest.time).getTime();
const elapsedSec =
(flightState.now() - RENDER_DELAY_SEC * 1000 - newestMs) / 1000;
if (!(elapsedSec > 0)) return null;
const { coastSec, holds } = _coastPlan(
newest,
info,
Math.min(elapsedSec, coastLimitSec),
out,
(info && info.turnRateDps) || 0,
flightState.records.data.get(icao24),
elapsedSec,
);
if (!(elapsedSec > coastSec)) return null;
return {
reportEpochMs: Number.isFinite(newest.reportEpochMs)
? newest.reportEpochMs
: newestMs,
holds,
};
}
/**
@@ -269,9 +348,12 @@ export function createMotion({
*/
function _extrapolateFix(fix, info, dt, out, turnRateDps = 0) {
const speed = Number.isFinite(fix.velocity)
? fix.velocity
: (info && info.velocity) || 0;
const speed = Math.min(
Number.isFinite(fix.velocity)
? fix.velocity
: (info && info.velocity) || 0,
COAST_MAX_SPEED_MPS,
);
const heading = Number.isFinite(fix.track)
? fix.track
: (info && info.true_track) || 0;
@@ -332,7 +414,7 @@ export function createMotion({
const history = flightState._positionHistory.get(flightState._trackedIcao);
if (!history || history.length === 0) return true;
const renderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
@@ -864,12 +946,15 @@ export function createMotion({
);
// Boundary hysteresis: a position jittering across a cell edge would flip
// floors at fleet-tick rate (see stickyFloorCell).
const cell = stickyFloorCell(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
state?.cell,
const latDeg = Cesium.Math.toDegrees(carto.latitude);
const lonDeg = Cesium.Math.toDegrees(carto.longitude);
const cell = stickyFloorCell(latDeg, lonDeg, state?.cell);
// A cell holds rendered-surface readings at the points they were taken,
// so the floor is read where the contact is, held inside its sticky cell.
const floor = cachedGroundFloor(
clampToCell(latDeg, cell.lat),
clampToCell(lonDeg, cell.lon),
);
const floor = cachedGroundFloor(cell.lat, cell.lon);
const next = state || {
cell,
in: new Cesium.Cartesian3(),
@@ -1111,6 +1196,7 @@ export function createMotion({
return {
_refloorStaleGroundedContacts,
_deadReckon,
_signalLost,
_extrapolateFix,
_isTrackWarmingUp,
_trackedFocusSizePx,
+8 -6
View File
@@ -12,6 +12,7 @@ function fixture() {
_scratchArc: {},
_scratchOffset: new Cesium.Cartesian3(),
_scratchRenderTime: new Cesium.JulianDate(),
now: Date.now,
};
const motion = createMotion({
flightState,
@@ -138,7 +139,7 @@ test('fleet render time is shared without resampling or mutating the supplied in
assert.ok(Cesium.JulianDate.equals(renderTime, savedTime));
});
test('tracked callers still sample a fresh delayed time without a fleet epoch', (t) => {
test('tracked callers still sample a fresh delayed time without a fleet epoch', () => {
const { flightState, motion } = fixture();
const start = Cesium.JulianDate.fromIso8601('2026-10-24T12:00:00Z');
const history = [
@@ -156,10 +157,11 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
flightState.records.data.set('tracked', { velocity: 100, true_track: 90 });
flightState._positionHistory.set('tracked', history);
let elapsed = 60;
const spy = t.mock.method(Cesium.JulianDate, 'now', (result) => {
assert.equal(result, flightState._scratchRenderTime);
return Cesium.JulianDate.addSeconds(start, elapsed, result);
});
let reads = 0;
flightState.now = () => {
reads += 1;
return Cesium.JulianDate.toDate(start).getTime() + elapsed * 1000;
};
const out = new Cesium.Cartesian3();
close(
motion._deadReckon('tracked', out),
@@ -180,5 +182,5 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch',
new Cesium.Cartesian3(),
),
);
assert.equal(spy.mock.callCount(), 2);
assert.equal(reads, 2);
});
+352 -2
View File
@@ -4,6 +4,7 @@ import { createCivilFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createEnrichment } from './enrichment.js';
import { createTracking } from './tracking.js';
import { LiveSourceError } from '../../sources/live/contract.js';
function services() {
const names = [
@@ -29,6 +30,14 @@ function services() {
};
}
/** The services enrichment reads: which hexes are military or a TR-3B. */
function enrichServices({ military = [], tr3b = [] } = {}) {
return {
militaryRegistry: { isMilitaryIcao: (id) => military.includes(id) },
aircraftPresentation: { isTr3b: (id) => tr3b.includes(id) },
};
}
test('constructing independent flight layers performs no source request and isolates selection', () => {
let requests = 0;
const source = {
@@ -90,7 +99,11 @@ test('aborted enrichment cannot write into a later lifecycle or decrement its ac
},
};
const flightState = createFlightState({ source, services: services() });
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
let writes = 0;
enrichment._enqueueEnrich(
'test',
@@ -118,7 +131,11 @@ test('a synchronous enrichment failure stays bounded and releases its slot', asy
},
},
});
const enrichment = createEnrichment({ flightState, services: {}, parts: {} });
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
assert.doesNotThrow(() =>
enrichment._enqueueEnrich('test', {}, () => assert.fail()),
);
@@ -146,3 +163,336 @@ test('voice context reads a track that rounds to north as 0°, not 360°', () =>
'0°',
);
});
test('the tracked plane’s photo is asked once per hex and lands on its record', async () => {
const queries = [];
let answer = {
found: true,
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg',
width: 420,
height: 280,
photographer: 'Jan Seler',
link: 'https://www.planespotters.net/photo/1745410/x?utm_source=api',
};
const flightState = createFlightState({
services: services(),
source: {
async getEnrichment(query) {
queries.push(query);
if (answer instanceof Error) throw answer;
return answer;
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
flightState.records.data.set('a0f1bb', { callsign: 'AAL1' });
flightState._trackedIcao = 'a0f1bb';
flightState._trackedEntity = {};
enrichment._requestPhotoEnrichment('A0F1BB');
enrichment._requestPhotoEnrichment('a0f1bb');
await new Promise((done) => setImmediate(done));
assert.deepEqual(queries, [{ kind: 'photo', id: 'a0f1bb' }]);
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, {
src: answer.src,
width: 420,
height: 280,
photographer: 'Jan Seler',
link: answer.link,
});
// A failure is not asked again within its cool-down.
answer = new Error('outage');
flightState.records.data.set('abc123', {});
enrichment._requestPhotoEnrichment('abc123');
await new Promise((done) => setTimeout(done, 300));
enrichment._requestPhotoEnrichment('abc123');
await new Promise((done) => setImmediate(done));
assert.equal(queries.length, 2);
assert.equal(flightState.records.data.get('abc123').photo, undefined);
enrichment._requestPhotoEnrichment('not-hex');
assert.equal(queries.length, 2);
flightState.lifetime.abort();
});
test('a military aircraft or a converted TR-3B is never looked up for a photo', async () => {
const queries = [];
const flightState = createFlightState({
services: services(),
source: {
async getEnrichment(query) {
queries.push(query);
return { found: false };
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices({ military: ['ae1234'], tr3b: ['a0f1bb'] }),
parts: {},
});
for (const id of ['ae1234', 'a0f1bb']) {
flightState.records.data.set(id, {});
enrichment._requestPhotoEnrichment(id);
}
enrichment._requestPhotoEnrichment('AE1234');
await new Promise((done) => setImmediate(done));
assert.deepEqual(queries, []);
assert.equal(flightState._enrichSeen.size, 0);
flightState.lifetime.abort();
});
test('a photo answer in the upstream shape or a server’s cached shape lands checked', async () => {
const SRC = 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg';
const LINK = 'https://www.planespotters.net/photo/1745410/x?utm_source=api';
const answers = {
a0f1bb: {
photos: [
{
thumbnail_large: { src: SRC, size: { width: 420, height: 280 } },
link: LINK,
photographer: 'Jan Seler',
},
],
},
abc123: {
found: true,
thumbnail: { src: SRC, width: 420, height: 280 },
photographer: 'Jan Seler',
link: LINK,
},
def456: {
found: true,
thumbnail: { src: 'https://evil.example/a.jpg', width: 1, height: 1 },
photographer: 'Jan Seler',
link: LINK,
},
fed789: { photos: [] },
};
const flightState = createFlightState({
services: services(),
source: { getEnrichment: async ({ id }) => answers[id] },
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: {},
});
const ids = Object.keys(answers);
for (const id of ids) flightState.records.data.set(id, {});
for (const id of ids) {
enrichment._requestPhotoEnrichment(id);
// One dispatch per drip gap.
await new Promise((done) => setTimeout(done, 250));
}
const photo = {
src: SRC,
width: 420,
height: 280,
photographer: 'Jan Seler',
link: LINK,
};
assert.deepEqual(flightState.records.data.get('a0f1bb').photo, photo);
assert.deepEqual(flightState.records.data.get('abc123').photo, photo);
assert.equal(flightState.records.data.get('def456').photo, undefined);
assert.equal(flightState.records.data.get('fed789').photo, undefined);
flightState.lifetime.abort();
});
/** An enrichment queue over `answer(query)` with a hand-driven clock. */
function enrichmentClock(t, answer) {
let now = 1_000_000;
t.mock.method(Date, 'now', () => now);
const queries = [];
const flightState = createFlightState({
services: services(),
source: {
getEnrichment(query) {
queries.push(query.id);
return answer(query);
},
},
});
const enrichment = createEnrichment({
flightState,
services: enrichServices(),
parts: { tracking: { _updateTrackedLabelModel() {} } },
});
const settle = () => new Promise((done) => setImmediate(done));
const advance = (ms) => {
now += ms;
};
return { flightState, enrichment, queries, settle, advance };
}
test('a failed lookup is asked again only after its cool-down', async (t) => {
let fail = true;
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async () => {
if (fail) throw new Error('503');
return { found: true, typeCode: 'A321' };
},
);
flightState.records.data.set('a0f1bb', {});
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb']);
advance(59_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb'], 'not within the cool-down');
fail = false;
advance(1_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb'], 'asked again after it');
assert.equal(flightState.records.data.get('a0f1bb').typeCode, 'A321');
advance(120_000);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2, 'an answer is final');
assert.equal(flightState._enrichActive, 0);
flightState.lifetime.abort();
});
test('a synchronous source failure cools down like a rejected one', async (t) => {
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
() => {
throw new Error('boom');
},
);
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
advance(60_000);
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.deepEqual(queries, ['a0f1bb', 'a0f1bb']);
flightState.lifetime.abort();
});
test('a "not found" answer is never asked again', async (t) => {
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async ({ kind }) => (kind === 'photo' ? { photos: [] } : { found: false }),
);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
advance(1_000); // past the dispatch drip
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2);
advance(3_600_000);
enrichment._requestTypeEnrichment('a0f1bb');
enrichment._requestPhotoEnrichment('a0f1bb');
await settle();
assert.equal(queries.length, 2);
assert.equal(flightState._enrichRetryAfter.size, 0);
flightState.lifetime.abort();
});
test('a lookup cut off by the layer’s teardown schedules no retry', async (t) => {
let release;
const { flightState, enrichment, settle } = enrichmentClock(
t,
(query) =>
new Promise((_resolve, reject) => {
release = () => reject(new DOMException('aborted', 'AbortError'));
}),
);
enrichment._requestTypeEnrichment('a0f1bb');
await settle();
flightState.lifetime.abort();
release();
await settle();
assert.equal(flightState._enrichRetryAfter.size, 0);
assert.equal(flightState._enrichSeen.has('t:a0f1bb'), true);
});
test('a permanent refusal is final; a timeout, rate limit, outage or authorization refusal cools down', async (t) => {
const errors = {
aaaaa1: new LiveSourceError('denied', 'adsbdb HTTP 404', { status: 404 }),
aaaaa2: new LiveSourceError('unsupported', 'Enrichment unavailable'),
aaaaa3: new LiveSourceError('limited', 'adsbdb rate limited', {
status: 429,
}),
aaaaa4: new LiveSourceError('unavailable', 'adsbdb HTTP 503', {
status: 503,
}),
aaaaa5: new LiveSourceError('unavailable', 'adsbdb HTTP 408', {
status: 408,
}),
aaaaa6: new Error('network'),
aaaaa7: new LiveSourceError('denied', 'Unauthorized', { status: 401 }),
aaaaa8: new LiveSourceError('denied', 'Forbidden', { status: 403 }),
};
const { flightState, enrichment, queries, settle, advance } = enrichmentClock(
t,
async ({ id }) => {
throw errors[id];
},
);
const ids = Object.keys(errors);
for (const id of ids) {
enrichment._requestTypeEnrichment(id);
await settle();
advance(1_000); // past the dispatch drip
}
assert.deepEqual(queries, ids);
advance(60_000);
for (const id of ids) {
enrichment._requestTypeEnrichment(id);
await settle();
advance(1_000);
}
assert.deepEqual(
queries.slice(ids.length),
['aaaaa3', 'aaaaa4', 'aaaaa5', 'aaaaa6', 'aaaaa7', 'aaaaa8'],
'a 404 and an unsupported lookup are never asked again',
);
assert.equal(flightState._enrichSeen.has('t:aaaaa1'), true);
assert.equal(flightState._enrichRetryAfter.has('t:aaaaa1'), false);
flightState.lifetime.abort();
});
test('a route answer for a callsign the plane no longer flies is dropped', async (t) => {
const pending = [];
const { flightState, enrichment, settle, advance } = enrichmentClock(
t,
(query) => new Promise((resolve) => pending.push({ query, resolve })),
);
const meta = { callsign: 'UAL9' };
flightState.records.data.set('a0f1bb', meta);
enrichment._requestRouteEnrichment('a0f1bb');
await settle();
meta.callsign = 'UAL10'; // the next poll's callsign
advance(1_000);
enrichment._requestRouteEnrichment('a0f1bb');
await settle();
assert.deepEqual(
pending.map(({ query }) => query.id),
['UAL9', 'UAL10'],
);
const route = (code) => ({
found: true,
airline: `${code} Air`,
origin: { code: `${code}O` },
destination: { code: `${code}D` },
});
pending[0].resolve(route('OLD'));
await settle();
assert.equal(meta.route, undefined, 'the late UAL9 answer is ignored');
assert.equal(meta.airline, undefined);
pending[1].resolve(route('NEW'));
await settle();
assert.deepEqual(meta.route, {
origin: { code: 'NEWO' },
destination: { code: 'NEWD' },
});
assert.equal(meta.routeCallsign, 'UAL10');
flightState.lifetime.abort();
});
+9 -1
View File
@@ -132,7 +132,7 @@ export const TRAIL_COLOR = '#00d4ff';
/** @constant {number} Combined cap on trail vertices (backfill + live accumulation). */
export const TRAIL_MAX_POINTS = 400;
export const TRAIL_MAX_POINTS = 2000;
// ---------------------------------------------------------------------------
// Render-behind smoothing (PRD WS-C C2 — approved product decision):
@@ -254,6 +254,11 @@ export const ENRICH_MAX_INFLIGHT = 4;
export const ENRICH_DISPATCH_GAP_MS = 200;
/** A lookup whose source failed (an outage, a timeout, a restarting server) may
* be asked again after this long; a real "not found" answer never is. */
export const ENRICH_RETRY_COOLDOWN_MS = 60_000;
// ---------------------------------------------------------------------------
// Ambient fleet type enrichment (2026-07-02 field data: OpenSky's live
// category field is 0/"no info" for ~94% of planes, so ambient classification
@@ -466,3 +471,6 @@ export const FLOOR_SEED_GRACE_MS = 90_000;
* reloads synchronously. */
export const IR_RELOAD_BATCH = 40;
/** Alpha of a contact that has missed an update or lost its signal: the stale fade, for the fleet and the tracked aircraft alike. */
export const STALE_ALPHA = 0.45;
+13 -3
View File
@@ -24,7 +24,8 @@ export function createQueries({
layer,
resolveAsset,
}) {
const { tr3bTypeLabel, tr3bAircraftClass } = services.aircraftPresentation;
const { isTr3b, tr3bTypeLabel, tr3bAircraftClass } =
services.aircraftPresentation;
const { formatFlightLevel } = services.labels;
const { isMilitaryIcao } = services.militaryRegistry;
const { applyTrackedCameraFrame } = services.camera;
@@ -208,6 +209,12 @@ export function createQueries({
destination: { ...info.route.destination },
}
: null,
// The airframe's Planespotters photo for the Context panel; a military
// aircraft or a converted TR-3B (it would name the real one) shows none.
photo:
info?.photo && !isTr3b(icao24) && !isMilitaryIcao(icao24)
? { ...info.photo }
: null,
};
}
@@ -875,8 +882,9 @@ export function createQueries({
/**
* Describe the currently tracked aircraft at its dead-reckoned position.
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null}
* Tracked aircraft info, or null when nothing is tracked.
* @returns {{icao24: string, callsign: string|null, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null, photo: {src: string, width: number|null, height: number|null, photographer: string, link: string}|null}|null}
* Tracked aircraft info, or null when nothing is tracked. `photo` is the
* airframe's credited Planespotters photo, or null.
*/
getTrackedInfo() {
if (!flightState._trackedIcao) return null;
@@ -906,6 +914,8 @@ export function createQueries({
_toCleanText(described.registration) ||
described.icao24,
position: Cesium.Cartesian3.clone(described.position),
// The airframe's photo for the Context panel, or null.
photo: described.photo,
};
},
+4
View File
@@ -9,6 +9,10 @@ export const LANDED_MISSING_POLL_LIMIT = 1;
export const MISSING_POLL_LIMIT = 3;
/** The tracked contact is kept this long after its newest fix: five minutes
* coasting, then five stopped as SIGNAL LOST. */
export const TRACKED_RETENTION_MS = 10 * 60_000;
/** Cooldown in milliseconds after a transient source error. */
export const ERROR_BACKOFF_INTERVAL = 20000;
+78 -10
View File
@@ -11,6 +11,7 @@ import {
GROUND_FLOOR_WARM_MAX_ALT_M,
LANDED_MISSING_POLL_LIMIT,
MISSING_POLL_LIMIT,
TRACKED_RETENTION_MS,
} from './recordPolicy.js';
/** Source-independent aircraft metadata and bounded missing-poll retention. */
@@ -23,10 +24,45 @@ export class FlightRecords {
};
this.data = new Map();
this.missingPolls = new Map();
// Contacts whose last poll re-sent a fix no newer than the one before.
this.fixRepeated = new Set();
this.lastSnapshotMs = null;
this.snapshotAdvanced = true;
this.geoidNCache = new Map();
this.geoidReady = false;
}
/**
* Start reading a snapshot taken at `observedAtMs`. A fix re-sent in a
* newer snapshot marks its contact as not updated; the same snapshot read
* again does not.
* @param {number} observedAtMs
*/
beginSnapshot(observedAtMs) {
this.snapshotAdvanced =
!Number.isFinite(observedAtMs) ||
!Number.isFinite(this.lastSnapshotMs) ||
observedAtMs > this.lastSnapshotMs;
if (Number.isFinite(observedAtMs))
this.lastSnapshotMs = Math.max(
this.lastSnapshotMs ?? -Infinity,
observedAtMs,
);
}
/** Note a received fix: the newest fix time, and whether it advanced. */
_noteFix(id, prevMeta, fixEpochMs) {
const prevFixMs = prevMeta?.newestFixMs;
// A fix counts as new only when it moves on by a second: feeds that
// derive fix time from receipt (readsb `now − seen_pos`, 0.1 s) jitter.
if (!Number.isFinite(prevFixMs) || fixEpochMs >= prevFixMs + 1000) {
this.fixRepeated.delete(id);
return fixEpochMs;
}
if (this.snapshotAdvanced) this.fixRepeated.add(id);
return prevFixMs;
}
receive(
observation,
{ viewerLatDeg, viewerLonDeg, trackedId, floorWarmPoints },
@@ -158,6 +194,12 @@ export class FlightRecords {
// (2) otherwise the SAME default policy `alt` already uses, so the two
// never disagree on the genuine "no data yet" case (a never-reported
// aircraft has no prior render height, so it lands here unchanged).
// Neither altitude this poll nor a held render height: the height below
// is the airborne default, invented. The tracked trail keeps no point there.
const renderAltitudeInvented =
pickedAltM == null &&
!onGround &&
!Number.isFinite(prevMeta?.renderAltitudeM);
let renderAltitudeM;
if (pickedAltM != null) {
renderAltitudeM = pickedAltM;
@@ -198,10 +240,22 @@ export class FlightRecords {
!!prevMeta && (prevMeta.onGround === true) !== onGround;
// Store flight metadata for click-to-track labels
const cat = stickyNumber(category, prevMeta?.category, null);
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
// A route (and its airline) belongs to the callsign it was looked up for;
// a new callsign drops it, so an old flight's route never shows under it.
const routeHeld =
Boolean(prevMeta?.routeCallsign) &&
prevMeta.routeCallsign === nextCallsign.toUpperCase();
const fixEpochMs =
Number.isFinite(observation.positionTimeMs) &&
observation.positionTimeMs > 0
? observation.positionTimeMs
: Date.now();
const meta = {
sourceReference: observation.reference,
observedReceiptMs: Date.now(),
callsign: stickyText(callsign, prevMeta?.callsign),
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
callsign: nextCallsign,
altitude: alt,
// geoAltitudeM/renderAltitudeM are ADDITIVE fields alongside the
// untouched aviation `altitude` — never rename/replace it (labels,
@@ -209,6 +263,7 @@ export class FlightRecords {
// still read `altitude`/baro).
geoAltitudeM,
renderAltitudeM,
renderAltitudeInvented,
onGround,
// Round 7: sticky airborne history — the landed fast-cull only
// applies to contacts that actually flew this session.
@@ -256,8 +311,11 @@ export class FlightRecords {
typeCode: prevMeta?.typeCode ?? null,
typeName: prevMeta?.typeName ?? null,
registration: prevMeta?.registration ?? null,
airline: prevMeta?.airline ?? null,
route: prevMeta?.route ?? null,
airline: routeHeld ? (prevMeta.airline ?? null) : null,
route: routeHeld ? (prevMeta.route ?? null) : null,
routeCallsign: routeHeld ? prevMeta.routeCallsign : null,
// Planespotters photo of the tracked airframe (Core asks it directly).
photo: prevMeta?.photo ?? null,
// The RAW poll fix lat/lon (this tick's OpenSky state-vector
// coords, pre-dead-reckon) — kept distinct from the continuously
// dead-reckoned billboard position for any consumer that needs the
@@ -267,15 +325,25 @@ export class FlightRecords {
};
this.data.set(icao24, meta);
const fixEpochMs =
Number.isFinite(observation.positionTimeMs) &&
observation.positionTimeMs > 0
? observation.positionTimeMs
: Date.now();
return { icao24, prevMeta, meta, groundFlipped, fixEpochMs };
}
absence(id, { complete, retainIds, likelyLanded }) {
absence(id, { complete, retainIds, likelyLanded, tracked = false }) {
const misses = (this.missingPolls.get(id) || 0) + 1;
// The tracked contact has missed an update: it is stale from the first
// one, and kept (so the camera keeps its target) until ten minutes after
// its newest fix, whatever the snapshot says. With no fix time known it
// takes the ordinary limits below.
const meta = this.data.get(id);
const fixMs = meta?.newestFixMs ?? meta?.observedReceiptMs;
if (tracked && Number.isFinite(fixMs)) {
if (Date.now() - fixMs < TRACKED_RETENTION_MS) {
this.missingPolls.set(id, misses);
return 'stale';
}
this.missingPolls.delete(id);
return 'remove';
}
// Partial admissions and position-less rows do not prove absence, but
// retention remains bounded; a likely-landed position-less contact
// still takes the landed limit.
@@ -284,7 +352,6 @@ export class FlightRecords {
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
)
return 'retain';
const misses = (this.missingPolls.get(id) || 0) + 1;
const limit = likelyLanded ? LANDED_MISSING_POLL_LIMIT : MISSING_POLL_LIMIT;
if (misses < limit) {
this.missingPolls.set(id, misses);
@@ -297,6 +364,7 @@ export class FlightRecords {
forget(id) {
this.data.delete(id);
this.missingPolls.delete(id);
this.fixRepeated.delete(id);
this.geoidNCache.delete(id);
}
}
+120
View File
@@ -39,6 +39,7 @@ test('civil records keep aviation units separate from render height and survive
assert.equal(first.meta.renderAltitudeM, 1040);
assert.equal(first.fixEpochMs, 1700000000000);
first.meta.typeCode = 'B738';
first.meta.photo = { src: 'https://t.plnspttrs.net/1/2_280.jpg' };
const second = store.receive(
observation({
callsign: '',
@@ -55,6 +56,7 @@ test('civil records keep aviation units separate from render height and survive
assert.equal(second.meta.velocity, 120);
assert.equal(second.meta.true_track, 90);
assert.equal(second.meta.typeCode, 'B738');
assert.equal(second.meta.photo, first.meta.photo, 'the photo survives polls');
assert.equal(Object.hasOwn(second.meta, 'cullPosition'), false);
assert.deepEqual(JSON.parse(JSON.stringify(second.meta)), second.meta);
});
@@ -140,3 +142,121 @@ test('civil emergency status follows the latest poll instead of sticking', () =>
assert.equal(next.meta.squawk, '2000');
assert.equal(next.meta.emergency, null);
});
test('a route belongs to its callsign: a new callsign drops it, a blank one keeps it', () => {
const store = records();
store.geoidReady = true;
const first = store.receive(observation({ callsign: 'UAL9' }), view());
first.meta.route = { origin: { code: 'AUS' }, destination: { code: 'DEN' } };
first.meta.airline = 'United';
first.meta.routeCallsign = 'UAL9';
const same = store.receive(observation({ callsign: 'UAL9 ' }), view());
assert.equal(same.meta.route, first.meta.route);
const blank = store.receive(observation({ callsign: '' }), view());
assert.equal(
blank.meta.route,
first.meta.route,
'a dropped callsign is sticky',
);
assert.equal(blank.meta.airline, 'United');
const next = store.receive(observation({ callsign: 'UAL10' }), view());
assert.equal(next.meta.route, null, 'the old route never shows under UAL10');
assert.equal(next.meta.airline, null);
assert.equal(next.meta.routeCallsign, null);
});
test('a contact with no altitude yet is marked as drawn at an invented height; a held one is not', () => {
const store = records();
const none = store.receive(
observation({ baroAltitudeM: null, ellipsoidAltitudeM: null }),
view(),
);
assert.equal(none.meta.renderAltitudeInvented, true);
const known = store.receive(
observation({ positionTimeMs: 1700000005000 }),
view(),
);
assert.equal(known.meta.renderAltitudeInvented, false);
const held = store.receive(
observation({
baroAltitudeM: null,
ellipsoidAltitudeM: null,
positionTimeMs: 1700000010000,
}),
view(),
);
assert.equal(held.meta.renderAltitudeInvented, false);
const parked = records().receive(
observation({ id: 'abc124', baroAltitudeM: null, onGround: true }),
view(),
);
assert.equal(parked.meta.renderAltitudeInvented, false);
});
test('the tracked contact is stale from its first missed update and kept until ten minutes after its newest fix', () => {
const realNow = Date.now;
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
let clock = fixMs + 5_000;
Date.now = () => clock;
try {
for (const snapshot of [
{ complete: true },
{ complete: true, retainIds: new Set(['abc123']) },
{ complete: false },
]) {
const store = records();
store.receive(observation({ positionTimeMs: fixMs }), view());
const absent = (tracked) =>
store.absence('abc123', { ...snapshot, likelyLanded: false, tracked });
clock = fixMs + 15_000;
assert.equal(absent(true), 'stale');
assert.equal(store.missingPolls.get('abc123'), 1);
// Kept long after the untracked limits, measured from the fix time.
clock = fixMs + 9 * 60_000;
assert.equal(absent(true), 'stale');
clock = fixMs + 10 * 60_000 - 1;
assert.equal(absent(true), 'stale');
clock = fixMs + 10 * 60_000;
assert.equal(absent(true), 'remove');
assert.equal(store.missingPolls.has('abc123'), false);
}
// Untracked contacts keep their own limits.
const store = records();
store.receive(observation({ positionTimeMs: fixMs }), view());
clock = fixMs + 15_000;
const untracked = (snapshot) =>
store.absence('abc123', { ...snapshot, likelyLanded: false });
assert.equal(untracked({ complete: false }), 'retain');
assert.deepEqual(
[1, 2, 3].map(() => untracked({ complete: true })),
['stale', 'stale', 'remove'],
);
} finally {
Date.now = realNow;
}
});
test('a repeated fix time marks the contact as not updated; removal is unchanged', () => {
const store = records();
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
store.beginSnapshot(fixMs + 2_000);
store.receive(observation({ positionTimeMs: fixMs }), view());
assert.equal(store.fixRepeated.has('abc123'), false);
// The next poll re-sends the same position.
store.beginSnapshot(fixMs + 12_000);
store.receive(observation({ positionTimeMs: fixMs }), view());
assert.equal(store.fixRepeated.has('abc123'), true);
assert.equal(store.missingPolls.has('abc123'), false);
// The same snapshot read again is not a missed update.
store.beginSnapshot(fixMs + 12_000);
store.receive(observation({ positionTimeMs: fixMs }), view());
assert.equal(store.fixRepeated.has('abc123'), true);
// A newer fix clears it.
store.beginSnapshot(fixMs + 22_000);
store.receive(observation({ positionTimeMs: fixMs + 10_000 }), view());
assert.equal(store.fixRepeated.has('abc123'), false);
store.beginSnapshot(fixMs + 32_000);
store.receive(observation({ positionTimeMs: fixMs + 10_000 }), view());
store.forget('abc123');
assert.equal(store.fixRepeated.has('abc123'), false);
});
+27 -2
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { julianAt } from '../../time/julian.js';
import { cyberSonarBaseAlpha } from '../../cyberSonar.js';
import { selectModelEligible } from '../../data/modelEligibility.js';
import { civilAircraftModelSpec } from './modelSpec.js';
@@ -38,6 +39,7 @@ import {
COURSE_MAX_DPS,
HIDDEN_CONTACT_DR_TICKS,
hiddenContactDrPhase,
STALE_ALPHA,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
@@ -679,6 +681,19 @@ export function createRendering({
* follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed
* in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode). */
/** Fade the tracked 3D model like the billboard while the plane is stale. */
function _applyTrackedModelFade(model) {
const alpha = parts.tracking._trackedStaleCue?.(flightState._trackedIcao)
?.dimmed
? STALE_ALPHA
: 1;
if (model.color?.alpha === alpha) return;
model.color = (
flightState._irBoost ? Cesium.Color.WHITE : Cesium.Color.CYAN
).withAlpha(alpha);
}
function _updateTrackedModel() {
const active =
flightState._trackedIcao &&
@@ -822,6 +837,7 @@ export function createRendering({
parts.motion._trackedDisplayCourse(),
flightState._trackedModel.modelMatrix,
);
_applyTrackedModelFade(flightState._trackedModel);
if (!flightState._trackedModel.ready) return;
const spec = _modelSpec(
flightState.records.data.get(flightState._trackedIcao)?.klass,
@@ -848,6 +864,13 @@ export function createRendering({
}
function _fleetTick() {
// Every frame, shown or not: the tracked trail records where its icon is
// drawn and moves its body on (the head callback only reads the result),
// and the tracked label's stale cue follows the clock.
if (flightState._viewer) {
parts.tracking._trailTick?.();
parts.tracking._staleCueTick?.();
}
if (
!flightState._viewer ||
!flightState._billboardCollection ||
@@ -871,7 +894,7 @@ export function createRendering({
flightState._lastFleetTickMs = nowMs;
// Every contact in this pass shares the same delayed display instant.
const renderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(flightState._scratchFleetRenderTime),
julianAt(flightState.now(), flightState._scratchFleetRenderTime),
-RENDER_DELAY_SEC,
flightState._scratchFleetRenderTime,
);
@@ -1080,7 +1103,9 @@ export function createRendering({
flightState._cockpitContactMode && !isCockpitNear
? 1
: _fleetBillboardScale(icao24, info?.klass),
baseAlpha: flightState.records.missingPolls.get(icao24) ? 0.45 : 1,
baseAlpha: flightState.records.missingPolls.get(icao24)
? STALE_ALPHA
: 1,
baseColor,
focusFactor: focus.factor,
cameraDistanceM,
+30 -7
View File
@@ -3,6 +3,7 @@ import { cyberSonarBaseAlpha } from '../../cyberSonar.js';
import {
turnRateFromFixHistory,
liftRepeatedGroundFix,
staleHoldsForFix,
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
@@ -22,7 +23,7 @@ export function createFlightSnapshotRenderer({
queries,
}) {
const { refreshMilitaryRegistryIfStale, isMilitaryIcao } = militaryRegistry;
const { warmGroundFloor } = groundFloor;
const { warmGroundFloor, cachedGroundFloor } = groundFloor;
const { sampleMeshFloorCells } = meshFloor;
return function applySnapshot(snapshot, viewer) {
const currentIcaos = new Set();
@@ -39,6 +40,7 @@ export function createFlightSnapshotRenderer({
? Cesium.Math.toDegrees(viewerCarto.longitude)
: null;
const floorWarmPoints = [];
records.beginSnapshot(snapshot.observedAtMs);
// Classification and display policy consume source-independent observations.
refreshMilitaryRegistryIfStale();
@@ -112,6 +114,9 @@ export function createFlightSnapshotRenderer({
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();
@@ -125,7 +130,10 @@ export function createFlightSnapshotRenderer({
// 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());
if (isTracked)
tracking._appendTrailFix(position.clone(), fixEpochMs, {
nullAltitude: meta.renderAltitudeInvented === true,
});
} else {
const modelOwnsGroundVisual = rendering._modelOwnsVisual(icao24);
if (!modelOwnsGroundVisual) {
@@ -133,21 +141,28 @@ export function createFlightSnapshotRenderer({
}
// 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 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;
if (kinematicsChanged) {
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
epochMs: 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);
if (isTracked) tracking._appendTrailFix(synthetic.position.clone());
}
}
}
@@ -230,6 +245,13 @@ export function createFlightSnapshotRenderer({
// (position updates automatically via dead-reckoning CallbackProperty)
if (isTracked && flightState._trackedEntity) {
tracking._updateTrackedLabelModel(icao24);
// Re-ask the tracked plane's lookups each poll. Answered and queued
// keys return at once; a lookup whose source failed runs again once
// its cool-down has passed, and the route uses the callsign this
// snapshot just recorded.
enrichment._requestTypeEnrichment(icao24, true);
enrichment._requestRouteEnrichment(icao24);
enrichment._requestPhotoEnrichment(icao24);
}
}
@@ -245,6 +267,7 @@ export function createFlightSnapshotRenderer({
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
});
if (absence === 'retain') continue;
if (absence === 'stale') {
@@ -300,8 +323,8 @@ export function createFlightSnapshotRenderer({
// floor cells collected in the loop (fire-and-forget, single-flight;
// read synchronously by NEXT poll's clamp — the military-layer pattern).
warmGroundFloor(floorWarmPoints);
// Round 4: sample the RENDERED mesh for those same cells (one-shot per
// cell, budget-capped, viewer-proximate, google-3d regime only). Own
// Round 4: sample the RENDERED mesh for those same cells (a few probes
// per cell, budget-capped, viewer-proximate, google-3d regime only). Own
// billboards/models are excluded so a vertical probe can't land on an
// aircraft instead of the pavement.
sampleMeshFloorCells(flightState._viewer?.scene, floorWarmPoints, {
+153
View File
@@ -0,0 +1,153 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightSnapshotRenderer } from './snapshotRenderer.js';
// A poll that repeats a contact's last position with new speed or course
// must not move it past where the stale rules allow, and never adds a
// report to the tracked trail.
const ICAO = '00a002';
const SEC = 1000;
/** Any property is a no-op function unless given. */
function stub(overrides = {}) {
return new Proxy(overrides, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
}
function harness({ ground = () => null }) {
const appended = [];
const history = [];
const flightState = {
_trackedIcao: ICAO,
_trackedEntity: null,
_positionHistory: new Map([[ICAO, history]]),
_billboards: new Map([[ICAO, { position: new Cesium.Cartesian3() }]]),
_billboardCollection: stub(),
_cullPositions: new Map(),
_displayCourse: new Map(),
_groundSnap: stub(),
_displayFloorState: new Map(),
_models: new Map(),
_viewer: null,
_cockpitContactMode: false,
records: { data: new Map() },
};
let meta = null;
let fixEpochMs = 0;
const records = stub({
receive: () => {
flightState.records.data.set(ICAO, meta);
return { prevMeta: meta, meta, groundFlipped: false, fixEpochMs };
},
absence: () => 'retain',
});
const apply = createFlightSnapshotRenderer({
flightState,
records,
militaryRegistry: stub({ isMilitaryIcao: () => false }),
groundFloor: stub({ cachedGroundFloor: ground }),
meshFloor: stub(),
rendering: stub({
_modelOwnsVisual: () => false,
_fleetBillboardColor: () => Cesium.Color.WHITE,
}),
tracking: stub({
_militaryLayerSuppresses: () => false,
_appendTrailFix: (position, epochMs) =>
appended.push({ position, epochMs }),
}),
motion: stub(),
enrichment: stub(),
queries: stub({ _likelyLanded: () => false }),
});
return {
history,
appended,
poll(nextMeta, epochMs) {
meta = nextMeta;
fixEpochMs = epochMs;
apply({ records: [{ id: ICAO }], complete: true }, null);
},
};
}
const lightAircraft = (velocity, track) => ({
rawLat: 38.1436,
rawLon: -122.5561,
renderAltitudeM: 10,
altitude: 40,
velocity,
true_track: track,
onGround: false,
wasAirborne: true,
klass: 'light',
});
test('a low contact whose position repeats while its speed changes is not moved and adds nothing to the trail', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({ ground: () => -30 });
h.poll(lightAircraft(36.4, 63), t0);
const first = h.history[0].position;
for (const [i, velocity] of [30, 22, 14, 9].entries()) {
t.mock.timers.tick(10 * SEC);
h.poll(lightAircraft(velocity, 63 + i * 20), t0);
}
assert.equal(h.history.length, 1, 'a synthetic fix moved a holding contact');
assert.equal(h.history[0].position, first);
assert.equal(h.appended.length, 1, 'only the real report joins the trail');
});
test('a cruising contact whose position repeats coasts no further than the stale cap, and the synthetic fix is not a report', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
const cruise = (velocity, track) => ({
rawLat: 36,
rawLon: -115,
renderAltitudeM: 9_000,
altitude: 9_000,
velocity,
true_track: track,
onGround: false,
wasAirborne: true,
klass: 'jet',
});
h.poll(cruise(220, 90), t0);
const report = h.history[0].position;
t.mock.timers.tick(300 * SEC);
h.poll(cruise(200, 100), t0);
assert.equal(h.history.length, 2);
const moved = Cesium.Cartesian3.distance(report, h.history[1].position);
assert.ok(
moved <= 220 * 300 + 1,
`the synthetic fix coasted ${moved.toFixed(0)} m`,
);
assert.equal(h.appended.length, 1, 'the synthetic fix joined the trail');
});
test('a report drawn at an invented height says so on its history fix', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
h.poll({ ...lightAircraft(60, 90), renderAltitudeInvented: true }, t0);
h.poll({ ...lightAircraft(60, 90), rawLon: -122.55 }, t0 + 10 * SEC);
assert.equal(h.history[0].inventedHeight, true);
assert.equal(h.history[1].inventedHeight, false);
});
test('with the ground unknown, a low barometric altitude alone does not hold a contact', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
h.poll(lightAircraft(36.4, 63), t0);
t.mock.timers.tick(10 * SEC);
h.poll(lightAircraft(30, 80), t0);
// It coasts under the stale cap instead.
assert.equal(h.history.length, 2);
assert.equal(h.history[0].staleHolds, false);
assert.equal(h.appended.length, 1);
});
+421
View File
@@ -0,0 +1,421 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import {
staleCoastSeconds,
staleHoldsAtLastReport,
} from '../../data/motionModel.js';
import { TRAIL_CONTINUITY_MAX_SPEED_KT } from '../../data/trailContinuity.js';
import { RENDER_DELAY_SEC } from './policy.js';
const SEC = 1000;
// Ellipsoidal ground at a sea-level airfield (geoid about -32 m).
const FIELD_GROUND_M = -30;
/** A motion module over one contact's history, with a fixed clock. */
function motionFixture({ info, fixes, nowMs, ground = () => null }) {
const flightState = {
records: { data: new Map([['00a001', info]]) },
_positionHistory: new Map([['00a001', fixes]]),
_focusEvidenceIds: new Set(),
_scratchArc: {},
_scratchOffset: new Cesium.Cartesian3(),
_scratchRenderTime: new Cesium.JulianDate(),
_scratchCoastCarto: new Cesium.Cartographic(),
now: () => nowMs,
};
const motion = createMotion({
flightState,
services: {
groundFloor: {
cachedGroundFloor: ground,
floorAltitudeM: (alt, g) =>
Number.isFinite(g) ? Math.max(alt, g + 1.5) : alt,
},
camera: {},
focus: {},
},
parts: {},
});
return { flightState, motion };
}
function fix(timeMs, lat, lon, heightM, velocity, track) {
return {
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
epochMs: timeMs,
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
velocity,
track,
};
}
const height = (position) => Cesium.Cartographic.fromCartesian(position).height;
test('a stale contact holds at its last report when it reported on the ground or low', () => {
assert.equal(staleHoldsAtLastReport({ onGround: true }), true);
// A light aircraft on final: -30 m barometric, its render height 1.5 m above the known ground.
assert.equal(
staleHoldsAtLastReport({
onGround: false,
heightM: FIELD_GROUND_M + 1.5,
groundM: FIELD_GROUND_M,
}),
true,
);
// Ground unknown: a low barometric altitude alone does not hold it; it
// coasts under the cap.
assert.equal(
staleHoldsAtLastReport({ onGround: false, heightM: 120 }),
false,
);
// A high airfield: 1,600 m barometric but 60 m above its ground.
assert.equal(
staleHoldsAtLastReport({
onGround: false,
heightM: 1_660,
groundM: 1_600,
}),
true,
);
assert.equal(
staleHoldsAtLastReport({
onGround: false,
heightM: 10_000,
groundM: 20,
}),
false,
);
});
test('a stale contact coasts up to its source limit at any speed, and a holding one not at all', () => {
const coast = (over) =>
staleCoastSeconds({
elapsedSec: 400,
coastLimitSec: 300,
speedMps: 230,
holds: false,
...over,
});
assert.equal(coast(), 300);
assert.equal(coast({ elapsedSec: 200 }), 200);
assert.equal(coast({ coastLimitSec: 60 }), 60);
assert.equal(coast({ speedMps: 1_000 }), 300);
assert.equal(coast({ holds: true }), 0);
assert.equal(coast({ elapsedSec: -5 }), 0);
});
test('a light aircraft on short final goes stale after a low, slow, descending report, the icon holds at that report, not below the ground', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 38.1279, -122.5425, 122, 40, 340),
fix(t0 + 30 * SEC, 38.133, -122.5494, 38, 37, 10),
fix(t0 + 60 * SEC, 38.1436, -122.5561, FIELD_GROUND_M + 1.5, 36.4, 63),
];
const info = {
altitude: -30,
renderAltitudeM: FIELD_GROUND_M + 1.5,
rawLat: 38.1436,
rawLon: -122.5561,
velocity: 36.4,
true_track: 63,
onGround: false,
wasAirborne: true,
lastContactEpochMs: t0 + 60 * SEC,
};
for (const afterSec of [5, 45, 90, 240]) {
const nowMs = t0 + 60 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
const { motion } = motionFixture({
info,
fixes,
nowMs,
ground: () => FIELD_GROUND_M,
});
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
assert.ok(
Cesium.Cartesian3.distance(drawn, fixes[2].position) < 0.01,
`${afterSec} s after the report the icon is at the report`,
);
assert.ok(height(drawn) >= FIELD_GROUND_M);
}
});
function cruiser(lastContactAfterSec) {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 40, -100, 10_000, 230, 90),
fix(t0 + 15 * SEC, 40, -99.96, 10_000, 230, 90),
];
const info = {
altitude: 10_000,
renderAltitudeM: 10_000,
rawLat: 40,
rawLon: -99.96,
velocity: 230,
true_track: 90,
onGround: false,
wasAirborne: true,
lastContactEpochMs: t0 + 15 * SEC + lastContactAfterSec * SEC,
};
const at = (afterSec) => {
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
const { motion } = motionFixture({ info, fixes, nowMs });
return motion._deadReckon('00a001', new Cesium.Cartesian3());
};
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
return { at, d };
}
test('a cruising contact still heard after its last position coasts past 90 s, for up to 5 minutes, then stops', () => {
// Contact kept arriving for four minutes after the last position.
const { at, d } = cruiser(240);
const near = (got, want) => Math.abs(got - want) < want * 0.005 + 50;
assert.ok(near(d(at(90)), 230 * 90));
assert.ok(near(d(at(200)), 230 * 200), 'still moving at 200 s');
assert.ok(near(d(at(300)), 230 * 300));
assert.ok(near(d(at(400)), 230 * 300), 'stopped at 300 s');
assert.ok(Cesium.Cartesian3.distance(at(400), at(600)) < 0.01);
});
test('a cruising contact that stops reporting coasts five minutes, then stops', () => {
const { at, d } = cruiser(0);
assert.ok(Math.abs(d(at(60)) - 230 * 60) < 120);
assert.ok(Math.abs(d(at(300)) - 230 * 300) < 600);
assert.ok(Cesium.Cartesian3.distance(at(301), at(420)) < 0.01);
});
test('a bad reported speed coasts no faster than the 1,500 kt continuity limit', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
// 2,000 m/s (about 3,900 kt): a corrupt velocity, not a real aircraft.
const fixes = [
fix(t0, 40, -100, 10_000, 2_000, 90),
fix(t0 + 15 * SEC, 40, -99.96, 10_000, 2_000, 90),
];
const info = {
altitude: 10_000,
renderAltitudeM: 10_000,
rawLat: 40,
rawLon: -99.96,
velocity: 2_000,
true_track: 90,
onGround: false,
wasAirborne: true,
};
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + 300 * SEC;
const { motion } = motionFixture({ info, fixes, nowMs });
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
const limitMps = (TRAIL_CONTINUITY_MAX_SPEED_KT * 1852) / 3600;
const d = Cesium.Cartesian3.distance(drawn, fixes[1].position);
assert.ok(Math.abs(d - limitMps * 300) < 1_500, `${d.toFixed(0)} m`);
});
test('coasting never takes a contact below the ground', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 39.7, -105.5, 3_400, 80, 270),
fix(t0 + 15 * SEC, 39.7, -105.514, 3_400, 80, 270),
];
const info = {
altitude: 3_400,
renderAltitudeM: 3_400,
rawLat: 39.7,
rawLon: -105.514,
velocity: 80,
true_track: 270,
onGround: false,
wasAirborne: true,
};
// 3,000 m under the report, rising to 3,600 m along the coast west.
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + 60 * SEC;
const { motion } = motionFixture({
info,
fixes,
nowMs,
ground: (lat, lon) => (lon < -105.52 ? 3_600 : 3_000),
});
const drawn = motion._deadReckon('00a001', new Cesium.Cartesian3());
assert.ok(height(drawn) >= 3_600, `height ${height(drawn)}`);
});
// ---------------------------------------------------------------------------
// The trail and head across a stale gap.
function services(trail) {
const names = [
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
];
return {
...Object.fromEntries(names.map((name) => [name, {}])),
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
trails: trail,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: () => null,
floorAltitudeM: (alt) => alt,
},
};
}
function trailHarness({ fixes, nowMs, head }) {
const calls = [];
const trail = {
createTrail: () => ({
setSegments(segments) {
calls.push(segments.map((segment) => segment.slice()));
},
setPositions(positions) {
calls.push([positions.slice()]);
},
setVisible() {},
clear() {},
destroy() {},
}),
};
const svc = services(trail);
const flightState = createFlightState({
services: svc,
source: { label: 'Fixture aircraft' },
});
const added = [];
flightState._viewer = {
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove() {},
},
};
flightState._trackedIcao = '00a001';
let clock = nowMs;
flightState.now = () => clock;
flightState._positionHistory.set('00a001', fixes);
let headPosition = head;
const tracking = createTracking({
flightState,
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_trackedTrailCached: () => headPosition,
_trackedDisplayPosition: () => headPosition,
_trackedModelCenterWorld: () => null,
_trackedModelEnvelopeM: () => null,
},
},
layer: {},
});
const headEntity = () =>
added.find((definition) =>
String(definition.id).startsWith('gev-trail:fl-head-'),
);
return {
tracking,
flightState,
drawn: () => (calls.at(-1) ?? []).flat(),
head: () => headEntity().polyline.positions.getValue(),
setClock: (ms) => {
clock = ms;
},
setHead: (position) => {
headPosition = position;
},
};
}
test('a holding contact draws no head, and the trail ends at the last report, never past the icon', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 38.1678, -122.527, 303, 45, 200),
fix(t0 + 30 * SEC, 38.1279, -122.5425, 122, 40, 340),
fix(t0 + 60 * SEC, 38.133, -122.5494, 38, 37, 10),
fix(t0 + 90 * SEC, 38.1436, -122.5561, 0, 36.4, 63),
];
const last = fixes.at(-1).position;
// The display time is long past the last report; the icon holds there.
const h = trailHarness({
fixes,
nowMs: t0 + 90 * SEC + RENDER_DELAY_SEC * SEC + 120 * SEC,
head: Cesium.Cartesian3.clone(last),
});
h.tracking._startTrail('00a001');
// Every report, including the last, is in the trail: the head no longer
// cuts from the one before it to the icon.
assert.equal(h.drawn().length, 4);
assert.equal(h.drawn().at(-1), h.flightState._trailFixes.at(-1).position);
assert.deepEqual(h.head(), []);
});
test('while the display is between reports, the trail stops at the report behind the icon', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
// Reports every 10 s; the icon is drawn 30 s behind, between the 2nd and 3rd.
const fixes = [0, 1, 2, 3, 4, 5].map((i) =>
fix(t0 + i * 10 * SEC, 40, -100 + i * 0.03, 10_000, 230, 90),
);
const nowMs = t0 + 25 * SEC + RENDER_DELAY_SEC * SEC;
const icon = Cesium.Cartesian3.fromDegrees(-100 + 0.075, 40, 10_000);
const h = trailHarness({ fixes, nowMs, head: icon });
h.tracking._startTrail('00a001');
// Reports at 0, 10 and 20 s are behind the icon (display time 25 s).
assert.equal(h.drawn().length, 3);
const head = h.head();
assert.equal(head.length, 2);
assert.ok(Cesium.Cartesian3.distance(head[0], fixes[2].position) < 0.01);
});
test('the hold-or-coast decision is made once per report: a floor that resolves mid-coast does not snap the icon back', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 39.7, -104.6, 1_900, 70, 270),
fix(t0 + 15 * SEC, 39.7, -104.6123, 1_900, 70, 270),
];
const info = {
altitude: 1_950,
renderAltitudeM: 1_900,
rawLat: 39.7,
rawLon: -104.6123,
velocity: 70,
true_track: 270,
onGround: false,
wasAirborne: true,
lastContactEpochMs: t0 + 15 * SEC + 120 * SEC,
};
// No floor known when the contact goes stale: baro says well clear of the
// ground, so it coasts. Mid-coast the floor resolves 100 m under the report.
let ground = () => null;
const at = (afterSec) => {
const nowMs = t0 + 15 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
const { motion } = motionFixture({
info,
fixes,
nowMs,
ground: (lat, lon) => ground(lat, lon),
});
return motion._deadReckon('00a001', new Cesium.Cartesian3());
};
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
const before = d(at(30));
assert.ok(Math.abs(before - 70 * 30) < 50, `coasted ${before.toFixed(0)} m`);
ground = () => 1_800;
const after = d(at(31));
assert.ok(
after > before,
`the icon went from ${before.toFixed(0)} m to ${after.toFixed(0)} m`,
);
});
+32 -2
View File
@@ -1,6 +1,7 @@
import { FlightRecords } from './records.js';
import { createFlightFeed } from './ingestion.js';
import * as Cesium from 'cesium';
import { worldTimeFor } from '../../time/worldClock.js';
import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js';
export function createFlightState({ source, services }) {
@@ -12,6 +13,8 @@ export function createFlightState({ source, services }) {
...services.groundFloor,
});
flightState._cullPositions = new Map();
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('flights');
/** Per-class model spec. Hangar-fleet classes (CLASS_MODEL_REAL) ship GLBs
* vertex-baked to real-world METERS in the airplane.glb axis convention, so
@@ -192,9 +195,32 @@ export function createFlightState({ source, services }) {
flightState._trailHeadSeq = 0;
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
/** @type {{position: Cesium.Cartesian3|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
* Chronological tracked-aircraft trail (oldest first): reports, and
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
* new segment. */
flightState._trailPositions = [];
flightState._trailFixes = [];
/** @type {number} Body fixes drawn: those at or before the display time. */
flightState._trailBodyCount = 0;
/** @type {Cesium.Cartesian3|null} Where the tracked icon was last recorded into the trail. */
flightState._trailRecordPosition = null;
/** @type {number} Display time (epoch ms) of that recording. */
flightState._trailRecordMs = -Infinity;
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
flightState._trackedStaleCueText = undefined;
/** @type {{key: string, cue: {text: string, dimmed: boolean}}|null} This frame's tracked stale cue (see `_trackedStaleCue`). */
flightState._trackedStaleCueCache = null;
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
@@ -339,6 +365,10 @@ export function createFlightState({ source, services }) {
flightState._enrichSeen = new Set();
/** Lookup key -> epoch ms before which a failed lookup is not asked again. */
flightState._enrichRetryAfter = new Map();
flightState._enrichAmbientBudget = ENRICH_AMBIENT_BUDGET_CEIL;
/** Epoch ms the bucket last accounted a refill window from (0 = unset). */
+14 -1
View File
@@ -190,8 +190,20 @@ export function createTesting({
);
}
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
/** Forget every enrichment lookup and the dispatch clock, so a test that
* moved `Date.now` leaves no future-dated drip or cool-down behind. */
function _resetEnrichmentForTest() {
flightState._enrichQueue.length = 0;
flightState._enrichSeen.clear();
flightState._enrichRetryAfter.clear();
flightState._enrichLastDispatchMs = 0;
if (flightState._enrichDripTimer) {
clearTimeout(flightState._enrichDripTimer);
flightState._enrichDripTimer = null;
}
}
/** Exercise the exact asynchronous fleet loader and return its admitted model. */
async function _ensureFleetModelForTest(icao24) {
await parts.rendering._ensureModel(icao24);
return flightState._models.get(icao24) || null;
@@ -212,5 +224,6 @@ export function createTesting({
_trackedBillboardColorForTest,
_driveFleetModelHandoffForTest,
_ensureFleetModelForTest,
_resetEnrichmentForTest,
};
}
+274 -84
View File
@@ -20,12 +20,31 @@ import {
TRACKED_MODEL_MAX_LOAD_FAILS,
TRACKED_MODEL_RETRY_BACKOFF_MS,
TRAIL_MAX_POINTS,
DR_CORRECTION_MS,
RENDER_DELAY_SEC,
TRAIL_COLOR,
CYAN_TRANSPARENT,
STALE_ALPHA,
} from './policy.js';
import {
drawTrailSegments,
historyFixEpochMs,
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
trailBackfillFixes,
trailBodyCount,
trailBodyCountOutsideModel,
trailBodySegments,
trailHeadStartFix,
trailRecordingBlocked,
TRAIL_RECORD_STEP_M,
TRAIL_RECORD_STEP_MS,
} from '../../data/trailContinuity.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
const STALE_CYAN = Cesium.Color.CYAN.withAlpha(STALE_ALPHA);
export function createTracking({
flightState,
services,
@@ -332,18 +351,81 @@ export function createTracking({
}
/**
* Append one fix to the tracked aircraft's trail accumulation and refresh
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
* Put one report into the tracked aircraft's trail, in time order, and
* refresh the rendered trail. Caller passes an owned (cloned) Cartesian3. A
* report that breaks from its neighbour starts a new segment (see
* trailContinuity).
* @param {Cesium.Cartesian3} position - The report's position.
* @param {number} [epochMs] - The report's time; defaults to the tracked
* aircraft's newest position-history fix, which every caller has just pushed.
* @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report
* had no altitude, so its position is not kept and the line breaks there.
* A report for a time the display has already passed replaces what was
* drawn after it (see `insertTrailFix`).
*/
function _appendTrailFix(position) {
flightState._trailPositions.push(position);
if (flightState._trailPositions.length > TRAIL_MAX_POINTS)
flightState._trailPositions.shift();
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
? epochMs
: historyFixEpochMs(history?.[history.length - 1]);
insertTrailFix(
flightState._trailFixes,
position,
timeMs,
TRAIL_MAX_POINTS,
{
nullAltitude,
displayMs: flightState.now() - RENDER_DELAY_SEC * 1000,
settleMs: DR_CORRECTION_MS,
},
);
_refreshTrailDisplay();
}
/**
* Per-frame trail work, run from the layer's preRender pass whether or not
* the head is visible: record where the tracked icon is drawn (at most once
* a second or every 150 m) and move the body on as the display time passes
* reports. The head callback only reads the result.
*/
function _trailTick() {
if (!flightState._trackedIcao || !flightState._trail) return;
const displayMs = flightState.now() - RENDER_DELAY_SEC * 1000;
let changed = false;
if (
flightState._trailFixes.length &&
!parts.motion._isTrackWarmingUp() &&
!trailRecordingBlocked(flightState._trailFixes, displayMs)
) {
const drawn = parts.motion._trackedDisplayPosition(
flightState._trackedIcao,
);
const last = flightState._trailRecordPosition;
if (
drawn &&
(!last ||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
Cesium.Cartesian3.distance(last, drawn) >= TRAIL_RECORD_STEP_M)
) {
flightState._trailRecordMs = displayMs;
flightState._trailRecordPosition = Cesium.Cartesian3.clone(
drawn,
flightState._trailRecordPosition ?? undefined,
);
changed = recordTrailPoint(
flightState._trailFixes,
Cesium.Cartesian3.clone(drawn),
displayMs,
TRAIL_MAX_POINTS,
);
}
}
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
_refreshTrailDisplay();
}
/**
* Renders the trail with its head clamped to the render-behind display
* position. Raw newest fixes run up to RENDER_DELAY_SEC ahead of the
@@ -353,17 +435,33 @@ export function createTracking({
*/
function _refreshTrailDisplay() {
// The trail BODY is the accumulated fixes EXCLUDING the newest raw one — that newest
// fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at
// now − RENDER_DELAY_SEC), so drawing it would push the trail in front of the plane.
// The cheap per-frame _trailHeadEntity segment bridges the last body point to the
// delayed dead-reckoned head, so the body primitive only rebuilds on a real fix
// (poll cadence), never at motion cadence.
// The trail BODY is the accumulated fixes at or before the delayed display time
// (now − RENDER_DELAY_SEC); newer fixes are AHEAD of the icon, so drawing them
// would push the trail in front of the plane. The cheap per-frame
// _trailHeadEntity segment bridges the last body point to the delayed
// dead-reckoned head, so the body rebuilds only on a real fix or when the
// display time passes one, never at motion cadence.
// A break lifts the pen: each segment is its own line, nothing between them.
if (!flightState._trail) return;
flightState._trail.setPositions(
flightState._trailPositions.length > 1
? flightState._trailPositions.slice(0, -1)
: flightState._trailPositions,
flightState._trailBodyCount = _trailBodyCountNow();
drawTrailSegments(
flightState._trail,
trailBodySegments(flightState._trailFixes, flightState._trailBodyCount),
);
}
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
* less the newest recorded points inside its 3D model. */
function _trailBodyCountNow() {
return trailBodyCountOutsideModel(
flightState._trailFixes,
trailBodyCount(
flightState._trailFixes,
flightState.now() - RENDER_DELAY_SEC * 1000,
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
);
}
@@ -376,21 +474,24 @@ export function createTracking({
function _startTrail(icao24) {
flightState._trailBackfillToken += 1;
flightState._trailPositions = [];
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
const history = flightState._positionHistory.get(icao24) || [];
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
// would draw the trail in front of the plane. They join the trail via _appendTrailFix
// as they age past the delay.
const seedRenderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
// Seed every report. The body only draws those at or before the delayed
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
// motion aid, never a report. A report drawn at an invented height keeps
// no position and breaks the line.
for (const fix of history) {
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
flightState._trailPositions.push(Cesium.Cartesian3.clone(fix.position));
}
if (Number.isFinite(fix.reportEpochMs)) continue;
insertTrailFix(
flightState._trailFixes,
Cesium.Cartesian3.clone(fix.position),
historyFixEpochMs(fix),
TRAIL_MAX_POINTS,
{ nullAltitude: fix.inventedHeight === true },
);
}
if (!flightState._trail && flightState._viewer) {
flightState._trail = createTrail(flightState._viewer, {
@@ -411,14 +512,13 @@ export function createTracking({
show: !flightState._cockpitContactMode,
polyline: {
positions: new Cesium.CallbackProperty(() => {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
// start at the last DISPLAYED body point (index n−2). With a single fix that
// point would be the sole raw fix — which is ~now, AHEAD of the delayed icon —
// so the segment would draw IN FRONT of the plane. Likewise during warm-up the
// icon predates all real history, so there is no valid body point behind it.
// The head starts at the last DISPLAYED body point, the newest fix at or
// before the delayed display time; a fix ahead of the icon would draw the
// segment IN FRONT of the plane. During warm-up the icon predates all real
// history, so there is no valid body point behind it.
if (
!flightState._trackedIcao ||
flightState._trailPositions.length < 2 ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
)
return [];
@@ -426,12 +526,19 @@ export function createTracking({
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
// backward/reversing segment.
const start =
flightState._trailPositions[
flightState._trailPositions.length - 2
];
// The last body point (a report, or where the icon was drawn a
// moment ago) → the icon. The body is moved on by _trailTick, never
// here: a callback must not add or remove entities.
// No head across a break: a body point more than 150 km away, or
// too long ago or too far to be one path, stays detached; none while
// the aircraft holds at its last point.
const last = trailHeadStartFix(
flightState._trailFixes,
head,
flightState.now(),
flightState._trailBodyCount,
);
if (!last) return [];
// On a contact that has not moved this segment runs from inside the
// model out to its own anchor — a line through the fuselage. The END
// never gives, so a moving trail still terminates on the tail; the
@@ -440,7 +547,7 @@ export function createTracking({
// See trailHeadStart. Read `head` in place and clone only on the draw
// path — a suppressed parked contact runs this every frame.
const from = trailHeadStart(
start,
last.position,
head,
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
@@ -519,7 +626,13 @@ export function createTracking({
const time = observedAtMs / 1000;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (!Number.isFinite(time) || time >= oldestFixEpochSec) continue;
parsed.push({ lat, lon, baroAlt });
parsed.push({
lat,
lon,
baroAlt,
onGround: waypoint.onGround === true,
timeMs: observedAtMs,
});
}
if (!parsed.length) return;
@@ -542,27 +655,30 @@ export function createTracking({
)
return;
const older = [];
let lastAltM = null; // carry-forward for no-baro points whose cell isn't warm yet
for (const { lat, lon, baroAlt } of parsed) {
const baroM = Number.isFinite(baroAlt)
? baroAlt + geoidHeight(lat, lon)
: null;
let altM = floorAltitudeM(baroM, cachedGroundFloor(lat, lon));
// No baro + unresolved floor: hold the previous waypoint's altitude
// (continuity — never a dive/spike to a made-up height). Leading points
// with nothing to carry keep the old 10 km airborne default.
if (altM == null) altM = lastAltM != null ? lastAltM : 10000;
lastAltM = altM;
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
}
flightState._trailPositions = older.concat(flightState._trailPositions);
if (flightState._trailPositions.length > TRAIL_MAX_POINTS) {
flightState._trailPositions = flightState._trailPositions.slice(
flightState._trailPositions.length - TRAIL_MAX_POINTS,
);
}
// Every waypoint is kept, each leg its own segment. A ground waypoint is
// at altitude 0, floored at the ground. A waypoint with no altitude is a
// break on both sides: it sits on the ground where the floor is known and
// is skipped otherwise; a skipped point still breaks the line.
const backfill = trailBackfillFixes(
parsed.map(({ lat, lon, baroAlt, onGround, timeMs }) => {
const known = Number.isFinite(baroAlt) ? baroAlt : onGround ? 0 : null;
const altM = floorAltitudeM(
known == null ? null : known + geoidHeight(lat, lon),
cachedGroundFloor(lat, lon),
);
return {
position:
altM == null ? null : Cesium.Cartesian3.fromDegrees(lon, lat, altM),
timeMs,
nullAltitude: known == null,
};
}),
);
flightState._trailFixes = joinTrailBackfill(
backfill,
flightState._trailFixes,
TRAIL_MAX_POINTS,
);
_refreshTrailDisplay();
}
@@ -572,7 +688,9 @@ export function createTracking({
function _clearTrail() {
flightState._trailBackfillToken += 1;
flightState._trailPositions = [];
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
if (flightState._trail) flightState._trail.clear();
if (
flightState._trailHeadEntity &&
@@ -736,14 +854,90 @@ export function createTracking({
flightState._pendingTrackingRestore = null;
}
/**
* The tracked plane's stale cue and whether it is drawn with the stale fade.
* - SIGNAL LOST · <time since its last report>, dimmed: its coast has ended
* (or it holds at its last report after a missed update) and no newer
* report has come.
* - STALE, dimmed: it has missed an update and still coasts, or the whole
* feed is backing off.
* @param {string} icao24
* @returns {{text: string, dimmed: boolean}}
*/
function _trackedStaleCue(icao24) {
const records = flightState.records;
const misses = records.missingPolls.get(icao24) || 0;
const repeated = records.fixRepeated?.has(icao24) === true;
const backoff = flightState.feed._backoff === true;
// Computed once per frame for the label, the icon colour and the model
// fade; a poll between frames changes the key.
const frame = flightState._viewer?.scene?.frameState?.frameNumber;
const key = Number.isFinite(frame)
? `${frame}|${icao24}|${misses}|${repeated}|${backoff}`
: null;
const cached = flightState._trackedStaleCueCache;
if (key !== null && cached?.key === key) return cached.cue;
const cue = _computeTrackedStaleCue(
icao24,
misses > 0 || repeated,
backoff,
);
flightState._trackedStaleCueCache = key === null ? null : { key, cue };
return cue;
}
/** `_trackedStaleCue` without the per-frame cache. A repeated fix counts as missed. */
function _computeTrackedStaleCue(icao24, missed, backoff) {
const lost = parts.motion._signalLost(icao24);
if (lost && (missed || !lost.holds)) {
const sec = Math.max(
0,
Math.floor((flightState.now() - lost.reportEpochMs) / 1000),
);
const time =
sec < 60
? `${formatNumber(sec, { useGrouping: false })} ${unitLabel('s')}`
: `${formatNumber(Math.floor(sec / 60), { useGrouping: false })} ${unitLabel('min')}`;
return { text: t('SIGNAL LOST · {time}', { time }), dimmed: true };
}
// A missed update or a stalled feed: no newer position is coming in.
if (missed || backoff) return { text: t('STALE'), dimmed: true };
return { text: '', dimmed: false };
}
/** The tracked billboard's colour: cyan, faded while stale, clear while the 3D model is the visual. */
function _trackedIconColor() {
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
return CYAN_TRANSPARENT;
return _trackedStaleCue(flightState._trackedIcao).dimmed
? STALE_CYAN
: Cesium.Color.CYAN;
}
/**
* Re-word the tracked label when its stale cue changes (STALE, SIGNAL LOST,
* each new second or minute of it). Run from the layer's per-frame pass.
*/
function _staleCueTick() {
const icao24 = flightState._trackedIcao;
if (!icao24 || !flightState._trackedEntity) return;
const text = _trackedStaleCue(icao24).text;
if (text === flightState._trackedStaleCueText) return;
flightState._trackedStaleCueText = text;
_updateTrackedLabelModel(icao24);
}
/** Multi-line tracked presentation text: "CS · FL · kts" + "Airline · Type" +
* "ORIG → DEST". The route line is gated by
* routePlausible so a wrong-leg adsbdb route is hidden, not displayed.
* While the plane is in its missed-poll grace (coasting on dead reckoning
* with sticky metadata), the first line carries a "· STALE" cue — the fleet's
* 45%-alpha billboard fade doesn't apply to the tracked plane (its entity
* owns the visual), so without this the readout would present last-known
* velocity/altitude as live. */
* The first line carries the stale cue (`_trackedStaleCue`): STALE while
* the plane coasts on dead reckoning after a missed update, SIGNAL LOST
* once the coast has ended, so last-known velocity/altitude are never
* presented as live. */
function _trackedLabelText(icao24) {
const info = flightState.records.data.get(icao24);
@@ -764,10 +958,7 @@ export function createTracking({
const spd = info.velocity
? quantity(Math.round(info.velocity * 1.944), 'kts')
: '';
const stale =
flightState.records.missingPolls.get(icao24) || flightState.feed._backoff
? t('STALE')
: '';
const stale = _trackedStaleCue(icao24).text;
const lines = [[cs, fl, spd, stale].filter(Boolean).join(' · ')];
// Converted contacts report their class as TR-3B and nothing else — the
// operator/type identity is exactly what the Easter egg is replacing.
@@ -966,15 +1157,9 @@ export function createTracking({
CLASS_SCALE_2D[
flightState.records.data.get(flightState._trackedIcao)?.klass
] || 1,
// Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the STANDALONE tracked model is actually up (ready + shown).
color: new Cesium.CallbackProperty(
() =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? CYAN_TRANSPARENT
: Cesium.Color.CYAN,
false,
),
// Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the STANDALONE tracked model is actually up.
color: new Cesium.CallbackProperty(_trackedIconColor, false),
sizeInMeters: false,
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5),
alignedAxis: Cesium.Cartesian3.ZERO,
@@ -1059,6 +1244,7 @@ export function createTracking({
// starts one.
parts.enrichment._requestTypeEnrichment(icao24, true); // tracked plane — front of the enrichment queue
parts.enrichment._requestRouteEnrichment(icao24);
parts.enrichment._requestPhotoEnrichment(icao24);
// Round 2 (owner): grounded contacts get trails too — a landed-but-taxiing
// aircraft's history is retrievable on select. Grounded flights positions
// are already surface-clamped (the surfaceM chain), so seeds/appends drape.
@@ -1255,6 +1441,7 @@ export function createTracking({
_trackedModelRegimeActive,
_syncTracked2dRotation,
_appendTrailFix,
_trailTick,
_refreshTrailDisplay,
_startTrail,
_backfillTrail,
@@ -1265,6 +1452,9 @@ export function createTracking({
_applyPendingTrackingRestore,
_cancelPendingTrackingRestore,
_trackedLabelText,
_trackedStaleCue,
_trackedIconColor,
_staleCueTick,
_updateTrackedLabelModel,
_syncTrackedBillboardImage,
_refreshTr3bContact,
+414
View File
@@ -0,0 +1,414 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { TRAIL_MAX_POINTS } from './policy.js';
import { trailHeadJoins, trailPairBreaks } from '../../data/trailContinuity.js';
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
const NM = 1852;
function services({ trails, floor = () => null } = {}) {
const names = [
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
];
return {
...Object.fromEntries(names.map((name) => [name, {}])),
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
trails,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: floor,
floorAltitudeM: (alt, ground) =>
Number.isFinite(alt)
? alt
: Number.isFinite(ground)
? ground + 1
: null,
},
};
}
/** A fake trail that records every segment list it is given. */
function recordingTrail() {
const calls = [];
return {
calls,
// What draws: a lone point is a segment with no line.
last: () =>
(calls[calls.length - 1] ?? []).filter((segment) => segment.length >= 2),
createTrail: () => ({
setSegments(segments) {
calls.push(segments.map((segment) => segment.slice()));
},
setPositions(positions) {
calls.push([positions.slice()]);
},
setVisible() {},
clear() {
calls.push([]);
},
destroy() {},
}),
};
}
function viewer() {
const added = [];
return {
added,
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove() {},
},
};
}
/**
* A tracked aircraft whose live history holds `liveFixes` ({timeMs, lat, lon}),
* with a track endpoint answering `waypoints`.
*/
function trackedHarness({
liveFixes = [],
waypoints = null,
nowMs,
floor,
head = null,
} = {}) {
const trail = recordingTrail();
const svc = services({ trails: trail, floor });
const flightState = createFlightState({
services: svc,
source: {
label: 'Fixture aircraft',
async getTrack() {
if (!waypoints) throw new Error('404');
return { records: waypoints };
},
},
});
const v = viewer();
flightState._viewer = v;
flightState._trackedIcao = 'abc123';
flightState.now = () => nowMs;
flightState._positionHistory.set(
'abc123',
liveFixes.map((fix) => ({
time: Cesium.JulianDate.fromDate(new Date(fix.timeMs)),
epochMs: fix.timeMs,
position: Cesium.Cartesian3.fromDegrees(fix.lon, fix.lat, 10_000),
})),
);
const tracking = createTracking({
flightState,
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_trackedTrailCached: () => head,
_trackedDisplayPosition: () => head,
_trackedModelCenterWorld: () => null,
_trackedModelEnvelopeM: () => null,
},
},
layer: {},
});
return { trail, tracking, flightState, viewer: v };
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
function waypoint(timeMs, lat, lon, baroAltitudeM = 10_000) {
return { observedAtMs: timeMs, latitude: lat, longitude: lon, baroAltitudeM };
}
/** `count` waypoints one minute apart flying east at ~420 kt from (lat, lon). */
function leg(startMs, lat, lon, count) {
return Array.from({ length: count }, (_, i) =>
waypoint(startMs + i * MINUTE, lat, lon + i * 0.12),
);
}
function headPositions(v) {
const entity = v.added.find((definition) =>
String(definition.id).startsWith('gev-trail:fl-head-'),
);
return entity.polyline.positions.getValue();
}
test('a pair 40 minutes and 300 km apart stays joined', () => {
assert.equal(trailPairBreaks(40 * MINUTE, 300_000), false);
});
test('a pair 1 minute and 200 km apart breaks: faster than 1,500 kt', () => {
assert.equal(trailPairBreaks(MINUTE, 200_000), true);
});
test('a gap longer than 48 minutes breaks, and time that does not advance breaks', () => {
assert.equal(trailPairBreaks(49 * MINUTE, 10_000), true);
assert.equal(trailPairBreaks(48 * MINUTE, 10_000), false);
assert.equal(trailPairBreaks(0, 0), true);
assert.equal(trailPairBreaks(-MINUTE, 100), true);
});
test('a parked aircraft two hours apart within 0.1 nm stays joined', () => {
assert.equal(trailPairBreaks(2 * HOUR, 0.09 * NM), false);
assert.equal(trailPairBreaks(3 * HOUR + MINUTE, 0.09 * NM), true);
assert.equal(trailPairBreaks(2 * HOUR, 0.2 * NM), true);
});
test('the head joins within 150 km under the time and speed test', () => {
assert.equal(trailHeadJoins(30_000, 5_000), true);
assert.equal(trailHeadJoins(30 * MINUTE, 151_000), false);
assert.equal(trailHeadJoins(HOUR, 5_000), false);
});
test('a backfill with gaps of 10 h, 2 h, 1.2 h and 6.5 h draws five segments and no line across a gap', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const legs = [];
let start = t0;
const gaps = [10 * HOUR, 2 * HOUR, 1.2 * HOUR, 6.5 * HOUR];
const anchors = [
[30, 31],
[12, 0],
[14, -15],
[20, -40],
[35, -75],
];
for (let i = 0; i < anchors.length; i++) {
const points = leg(start, anchors[i][0], anchors[i][1], 6);
legs.push(points);
start = points[points.length - 1].observedAtMs + (gaps[i] ?? 0);
}
const waypoints = legs.flat();
const lastLeg = legs[legs.length - 1];
const liveStart = lastLeg[lastLeg.length - 1].observedAtMs + MINUTE;
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: liveStart + i * MINUTE,
lat: 35,
lon: -75 + 0.72 + i * 0.12,
}));
const nowMs = liveStart + 3 * MINUTE;
const { trail, tracking, flightState } = trackedHarness({
liveFixes,
waypoints,
nowMs,
});
tracking._startTrail('abc123');
await settle();
assert.equal(flightState._trailFixes.length, waypoints.length + 3);
const segments = trail.last();
assert.equal(segments.length, 5);
const bodyCount = segments.reduce((sum, segment) => sum + segment.length, 0);
// The body draws every fix at or before the display time: all of them here.
assert.equal(bodyCount, waypoints.length + 3);
for (const [index, segment] of segments.entries()) {
const expected = legs[index].map((point) =>
Cesium.Cartesian3.fromDegrees(point.longitude, point.latitude, 10_000),
);
for (const position of segment.slice(0, expected.length)) {
assert.ok(
expected.some((e) => Cesium.Cartesian3.distance(e, position) < 1),
`segment ${index} holds a point from another leg`,
);
}
}
});
test('a null-altitude waypoint breaks the line, and nothing is drawn at 10 km', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const waypoints = leg(t0, 40, 10, 6);
waypoints[3] = waypoint(waypoints[3].observedAtMs, 40, 10.36, null);
const nowMs = t0 + 8 * MINUTE;
const liveFixes = [
{ timeMs: t0 + 6 * MINUTE, lat: 40, lon: 10.72 },
{ timeMs: t0 + 7 * MINUTE, lat: 40, lon: 10.84 },
];
// Unknown floor: the null point is skipped, and the line still breaks there.
const skipped = trackedHarness({ liveFixes, waypoints, nowMs });
skipped.tracking._startTrail('abc123');
await settle();
assert.equal(
skipped.flightState._trailFixes.length,
waypoints.length - 1 + 2,
);
const segments = skipped.trail.last();
assert.deepEqual(
segments.map((segment) => segment.length),
[3, 4],
);
for (const segment of segments) {
for (const position of segment) {
const height = Cesium.Cartographic.fromCartesian(position).height;
assert.ok(Math.abs(height - 10_000) < 1, 'only real altitudes drawn');
}
}
// Known floor: the point is kept on the ground, alone, joined to nothing.
const grounded = trackedHarness({
liveFixes,
waypoints,
nowMs,
floor: () => 120,
});
grounded.tracking._startTrail('abc123');
await settle();
assert.equal(grounded.flightState._trailFixes.length, waypoints.length + 2);
assert.deepEqual(
grounded.trail.last().map((segment) => segment.length),
[3, 4],
);
const kept = grounded.flightState._trailFixes[3];
assert.ok(
Math.abs(Cesium.Cartographic.fromCartesian(kept.position).height - 121) < 1,
);
});
test('a history tail far from the first live fix does not connect to it', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
// History ends 20 minutes before the first live fix, 1,400 km away.
const waypoints = leg(t0, 50, 0, 5);
const liveStart = t0 + 24 * MINUTE;
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: liveStart + i * MINUTE,
lat: 50,
lon: 20 + i * 0.12,
}));
const { trail, tracking } = trackedHarness({
liveFixes,
waypoints,
nowMs: liveStart + 3 * MINUTE,
});
tracking._startTrail('abc123');
await settle();
assert.deepEqual(
trail.last().map((segment) => segment.length),
[5, 3],
);
});
test('the head is drawn to a nearby aircraft and not to one more than 150 km away', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 50,
lon: 1 + i * 0.12,
}));
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 10_000);
const joined = trackedHarness({
liveFixes,
nowMs: t0 + 3 * MINUTE,
head: near,
});
joined.tracking._startTrail('abc123');
const drawn = headPositions(joined.viewer);
assert.equal(drawn.length, 2);
assert.ok(Cesium.Cartesian3.distance(drawn[1], near) < 1e-6);
const far = Cesium.Cartesian3.fromDegrees(4, 50, 10_000);
const detached = trackedHarness({
liveFixes,
nowMs: t0 + 3 * MINUTE,
head: far,
});
detached.tracking._startTrail('abc123');
assert.deepEqual(headPositions(detached.viewer), []);
// An hour without a fix: the head no longer joins the last body point.
const stale = trackedHarness({ liveFixes, nowMs: t0 + HOUR, head: near });
stale.tracking._startTrail('abc123');
assert.deepEqual(headPositions(stale.viewer), []);
});
test('a live fix after a one-hour feed gap starts a new segment', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 50,
lon: 1 + i * 0.12,
}));
const { trail, tracking, flightState } = trackedHarness({
liveFixes,
nowMs: t0 + 3 * MINUTE,
});
tracking._startTrail('abc123');
assert.deepEqual(
trail.last().map((segment) => segment.length),
[3],
);
const later = t0 + 2 * MINUTE + HOUR;
// The display time moves past the new fixes.
flightState.now = () => later + 3 * MINUTE;
for (const [i, lon] of [3, 3.12, 3.24].entries()) {
tracking._appendTrailFix(
Cesium.Cartesian3.fromDegrees(lon, 50, 10_000),
later + i * MINUTE,
);
}
assert.equal(flightState._trailFixes.length, 6);
assert.deepEqual(
trail.last().map((segment) => segment.length),
[3, 3],
);
});
test('every waypoint of a 24 h history survives, and the trail stays within TRAIL_MAX_POINTS', async () => {
// A full day at one fix per minute.
const day = 24 * 60;
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const full = leg(t0, 10, -100, day);
const liveStart = t0 + day * MINUTE;
const liveFixes = [{ timeMs: liveStart, lat: 10, lon: -100 + day * 0.12 }];
const kept = trackedHarness({
liveFixes,
waypoints: full,
nowMs: liveStart + MINUTE,
});
kept.tracking._startTrail('abc123');
await settle();
assert.ok(TRAIL_MAX_POINTS >= day + 500);
assert.equal(kept.flightState._trailFixes.length, full.length + 1);
assert.deepEqual(
kept.trail.last().map((segment) => segment.length),
[day + 1],
);
const count = TRAIL_MAX_POINTS + 120;
const large = leg(
liveStart - count * MINUTE,
10,
-100 + (day - count) * 0.12,
count,
);
const capped = trackedHarness({
liveFixes,
waypoints: large,
nowMs: liveStart + MINUTE,
});
capped.tracking._startTrail('abc123');
await settle();
const fixes = capped.flightState._trailFixes;
assert.equal(fixes.length, TRAIL_MAX_POINTS);
// The oldest go first: the newest live fix is still the last point.
assert.equal(fixes[fixes.length - 1].timeMs, liveStart);
});
+866
View File
@@ -0,0 +1,866 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// Between reports, a tracked trail is the path the icon was actually drawn
// along: the real display position, recorded as the frames go by. These tests
// drive the real motion and display path frame by frame.
const SEC = 1000;
const ICAO = '00a001';
const T0 = Date.UTC(2026, 10, 9, 21, 0);
function fix(timeMs, lat, lon, heightM, velocity, track) {
return {
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
epochMs: timeMs,
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
velocity,
track,
};
}
function services(trail, ground) {
const names = [
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
];
return {
...Object.fromEntries(names.map((name) => [name, {}])),
aircraftPresentation: {
isTr3b: () => false,
tr3bTypeLabel: (id, label) => label,
},
focus: {
nearFarScalarValueAtDistance: () => 1,
clearFocusTarget() {},
publishFocusTargetFromCachedPosition() {},
},
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
trails: trail,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: ground,
stickyFloorCell: (lat, lon) => ({ lat, lon }),
neighborFloorM: () => null,
floorAltitudeM: (alt, g) =>
Number.isFinite(g) && Number.isFinite(alt)
? Math.max(alt, g + 1.5)
: alt,
},
};
}
/**
* Real motion, real display position and real tracking over one contact.
* `frame()` runs one rendered frame: the layer's preRender work, then the
* head callback, as Cesium does.
*/
function harness({
fixes,
info,
nowMs,
ground = () => null,
envelopeM = null,
}) {
const segmentsCalls = [];
let inHead = false;
const trail = {
createTrail: () => ({
setSegments(segments) {
assert.ok(
!inHead,
'the trail body was rebuilt inside the head callback',
);
segmentsCalls.push(segments.map((segment) => segment.slice()));
},
setPositions(positions) {
assert.ok(
!inHead,
'the trail body was rebuilt inside the head callback',
);
segmentsCalls.push([positions.slice()]);
},
setVisible() {},
clear() {},
destroy() {},
}),
};
const svc = services(trail, ground);
const flightState = createFlightState({
services: svc,
source: { label: 'Fixture aircraft' },
});
flightState.records.data.set(ICAO, info);
let frameNumber = 0;
const added = [];
let entityChanges = 0;
flightState._viewer = {
isDestroyed: () => false,
scene: {
frameState: {
get frameNumber() {
return frameNumber;
},
},
},
entities: {
add(definition) {
entityChanges += 1;
added.push(definition);
return definition;
},
remove() {
entityChanges += 1;
},
},
};
flightState._trackedIcao = ICAO;
let clock = nowMs;
flightState.now = () => clock;
flightState._positionHistory.set(ICAO, fixes);
const parts = {
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
queries: { _contactLabel: (id, info) => info?.callsign || id },
};
parts.motion = createMotion({ flightState, services: svc, parts });
if (envelopeM != null) {
// A 3D model is the visual: its centre is the drawn position.
parts.motion._trackedModelCenterWorld = () =>
parts.motion._trackedDisplayCached();
parts.motion._trackedModelEnvelopeM = () => envelopeM;
}
const tracking = createTracking({
flightState,
services: svc,
parts,
layer: {},
});
parts.tracking = tracking;
const realDateNow = Date.now;
Date.now = () => clock;
const headEntity = () =>
added.find((definition) =>
String(definition.id).startsWith('gev-trail:fl-head-'),
);
const head = () => {
const before = entityChanges;
inHead = true;
try {
return headEntity().polyline.positions.getValue();
} finally {
inHead = false;
assert.equal(
entityChanges,
before,
'the head callback added or removed an entity',
);
}
};
/** Drawn icon positions, one per frame. */
const drawn = [];
const frame = ({ readHead = true } = {}) => {
frameNumber += 1;
tracking._trailTick();
const icon = parts.motion._trackedDisplayPosition(ICAO);
if (icon) drawn.push(Cesium.Cartesian3.clone(icon));
if (readHead) head();
};
const run = (toMs, { frameMs = 100, readHead = true } = {}) => {
while (clock < toMs) {
clock = Math.min(toMs, clock + frameMs);
frame({ readHead });
}
};
return {
flightState,
tracking,
motion: parts.motion,
head,
drawn,
run,
body: () => segmentsCalls.at(-1) ?? [],
bodyPoints: () => (segmentsCalls.at(-1) ?? []).flat(),
restore: () => {
Date.now = realDateNow;
},
};
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
const ab = new Cesium.Cartesian3();
const ap = new Cesium.Cartesian3();
const closest = new Cesium.Cartesian3();
if (path.length === 1) return Cesium.Cartesian3.distance(p, path[0]);
for (let i = 1; i < path.length; i++) {
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
const t =
len2 > 0
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
: 0;
Cesium.Cartesian3.add(
path[i - 1],
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
closest,
);
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
}
return best;
}
/** No vertex turns the line back sharper than 120° over a short step. */
function assertNoSpur(line, label) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 0 && lv > 0) || Math.min(lu, lv) > 500) continue;
const cos = Cesium.Cartesian3.dot(u, v) / (lu * lv);
assert.ok(
cos >= -0.5,
`${label}: spur at vertex ${i} of ${line.length} (turn ${(
(Math.acos(cos) * 180) /
Math.PI
).toFixed(0)}°)`,
);
}
}
const indexOfPoint = (line, p) =>
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
// A departing jet: four northbound climb reports, then a left turn through
// west to south with no report while the icon flies it.
function departure() {
const fixes = [
fix(T0, 37.6329, -122.3661, 213, 85, 8),
fix(T0 + 30 * SEC, 37.6542, -122.3616, 495, 95, 0),
fix(T0 + 60 * SEC, 37.6813, -122.3615, 808, 104, 350),
fix(T0 + 90 * SEC, 37.7066, -122.3755, 1257, 112, 340),
];
const info = {
altitude: 1257,
renderAltitudeM: 1257,
rawLat: 37.7066,
rawLon: -122.3755,
velocity: 112,
true_track: 340,
turnRateDps: -2,
onGround: false,
wasAirborne: true,
lastContactEpochMs: T0 + 200 * SEC,
};
return { fixes, info };
}
test('a report newer than the display time arrives mid-turn: the trail between the two reports stays on the drawn arc', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
// 40 s of turn with no new report: the icon flies the arc.
h.run(start + 40 * SEC);
const arc = h.drawn.slice();
// The next report is where the plane really was 60 s after the last one,
// still ahead of the display time (normal 30 s delay, slow feed). The icon
// now interpolates the straight line between the two reports and is eased
// onto it.
const at60 = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(at60);
const report = fix(
T0 + 150 * SEC,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
220,
);
fixes.push(report);
info.true_track = 220;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// The display passes the new report.
h.run(start + 75 * SEC);
const line = h.bodyPoints();
const from = indexOfPoint(line, fixes[3].position);
const to = indexOfPoint(line, report.position);
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
const between = line.slice(from, to + 1);
// Every vertex between the reports is where the icon was drawn...
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
for (const vertex of between) {
const off = distanceToPath(vertex, drawnPath);
assert.ok(
off < 50,
`trail vertex ${off.toFixed(0)} m off the drawn path`,
);
}
// ...and the arc the icon flew is still there: no straight chord. (The
// arc strays far from the chord, so a chord would fail this.)
const chord = [fixes[3].position, report.position];
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
// The last 10 s of the arc are exempt: the correction pulled the icon back
// over them, and keeping them would fold the line back on itself.
for (const point of arc.slice(0, -100)) {
const off = distanceToPath(point, between);
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
}
assertNoSpur(line, 'trail');
assertNoSpur(h.head(), 'head');
} finally {
h.restore();
}
});
test('a fresh report after a hold resumes with no backward spur', () => {
const fixes = [0, 1, 2, 3].map((i) =>
fix(T0 + i * 15 * SEC, 40, -100 + i * 0.04, 10_000, 230, 90),
);
const info = {
altitude: 10_000,
renderAltitudeM: 10_000,
rawLat: 40,
rawLon: -100 + 0.12,
velocity: 230,
true_track: 90,
turnRateDps: 0,
onGround: false,
wasAirborne: true,
lastContactEpochMs: T0 + 45 * SEC,
};
const start = T0 + 45 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
// The contact coasts five minutes, then holds; recording stops while it
// holds.
h.run(start + 320 * SEC);
const held = h.bodyPoints().length;
h.run(start + 360 * SEC);
assert.equal(h.bodyPoints().length, held, 'the trail grew during a hold');
// A fresh report, a little north of the track, ahead of the display.
const display = start + 360 * SEC - RENDER_DELAY_SEC * SEC;
// Just past where it held: five minutes and ten seconds at 230 m/s.
const aheadDeg = (230 * 310) / (111_320 * Math.cos((40 * Math.PI) / 180));
const fresh = fix(
display + 10 * SEC,
40.01,
-100 + 0.12 + aheadDeg,
10_000,
230,
80,
);
fixes.push(fresh);
info.lastContactEpochMs = fresh.epochMs;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(fresh.position),
fresh.epochMs,
);
h.run(start + 390 * SEC);
assertNoSpur(h.bodyPoints(), 'trail');
assertNoSpur(h.head(), 'head');
assert.ok(indexOfPoint(h.bodyPoints(), fresh.position) >= 0);
} finally {
h.restore();
}
});
test('with the head hidden the body keeps advancing, and untracking clears the recording', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
h.run(start + 5 * SEC);
const before = h.bodyPoints().at(-1);
// Cockpit view: the head is hidden and its callback never runs.
h.run(start + 30 * SEC, { readHead: false });
// The body's end keeps following the icon; straight stretches are thinned.
const end = h.bodyPoints().at(-1);
assert.ok(
Cesium.Cartesian3.distance(end, before) > 1_000,
'the body stopped advancing',
);
assert.ok(Cesium.Cartesian3.distance(end, h.drawn.at(-1)) < 300);
h.tracking._clearTrail();
assert.equal(h.flightState._trailFixes.length, 0);
// A new track of the same plane starts from reports only.
h.tracking._startTrail(ICAO);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
);
} finally {
h.restore();
}
});
test('a live fix with no altitude breaks the line and puts no point at an invented height', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
const invented = Cesium.Cartesian3.fromDegrees(-122.38, 37.71, 10_000);
h.tracking._appendTrailFix(invented, T0 + 95 * SEC, { nullAltitude: true });
const later = Cesium.Cartesian3.fromDegrees(-122.39, 37.715, 1400);
h.tracking._appendTrailFix(later, T0 + 100 * SEC);
h.run(T0 + 100 * SEC + RENDER_DELAY_SEC * SEC + SEC, { frameMs: 500 });
for (const point of h.bodyPoints())
assert.ok(Cesium.Cartographic.fromCartesian(point).height < 5_000);
// The reports on either side of it are not joined.
const segments = h.body();
const holding = (p) =>
segments.findIndex((segment) =>
segment.some((q) => Cesium.Cartesian3.distance(p, q) < 0.01),
);
assert.notEqual(holding(fixes[3].position), holding(later));
} finally {
h.restore();
}
});
test('with a 3D model as the visual, the trail stops outside the model and the head runs from there to the plane', () => {
const { fixes, info } = departure();
info.turnRateDps = 0;
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const envelopeM = 300;
const h = harness({ fixes, info, nowMs: start, envelopeM });
try {
h.tracking._startTrail(ICAO);
h.run(start + 30 * SEC);
const icon = h.drawn.at(-1);
const body = h.bodyPoints();
const head = h.head();
assert.ok(head.length >= 2, 'no head is drawn');
assert.ok(Cesium.Cartesian3.distance(head.at(-1), icon) < 0.01);
// No trail point inside the model, and the head starts where the body ends.
for (const point of body)
assert.ok(Cesium.Cartesian3.distance(point, icon) >= envelopeM - 1);
assert.ok(Cesium.Cartesian3.distance(head[0], body.at(-1)) < 0.01);
// Body and head together follow where the icon was drawn.
const line = body.concat(head);
for (const point of h.drawn) {
const off = distanceToPath(point, line);
assert.ok(off < 35, `drawn icon ${off.toFixed(0)} m off the trail`);
}
} finally {
h.restore();
}
});
test('a report the display already passed replaces the guess drawn after it, with no spike', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
h.run(start + 40 * SEC);
const displayMs = T0 + 130 * SEC;
// A report for 10 s before the display time, 400 m inside the drawn arc.
const guess = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 120 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(guess);
const report = fix(
T0 + 120 * SEC,
Cesium.Math.toDegrees(c.latitude) - 400 / 111_320,
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
250,
);
fixes.push(report);
info.true_track = 250;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
h.run(start + 55 * SEC);
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
// Nothing recorded between the report and the end of the ease.
assert.deepEqual(
recorded
.filter(
(entry) =>
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
)
.map((entry) => entry.timeMs - T0),
[],
);
const line = h.bodyPoints();
assert.ok(indexOfPoint(line, report.position) >= 0);
assertNoSpur(line, 'trail');
} finally {
h.restore();
}
});
test('a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
const { fixes, info } = departure();
fixes[3].inventedHeight = true;
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
const seeded = h.flightState._trailFixes.find(
(entry) => entry.timeMs === fixes[3].epochMs,
);
assert.equal(seeded.position, null);
assert.equal(seeded.nullAltitude, true);
h.run(start + 10 * SEC);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
);
} finally {
h.restore();
}
});
// A turboprop at FL210 flying east out of receiver coverage: its last
// position is at T0 + 30 s, and contact goes on for four more minutes.
function outOfCoverage() {
const fixes = [
fix(T0, 43, -108.1, 6_400, 140, 90),
fix(T0 + 30 * SEC, 43, -108.05, 6_400, 140, 90),
];
const info = {
altitude: 6_400,
renderAltitudeM: 6_400,
rawLat: 43,
rawLon: -108.05,
velocity: 140,
true_track: 90,
callsign: 'TEST7',
turnRateDps: 0,
onGround: false,
wasAirborne: true,
lastContactEpochMs: T0 + 30 * SEC + 240 * SEC,
};
return { fixes, info };
}
/** Display time (ms) `afterSec` past the last report. */
const pastReport = (afterSec) =>
T0 + 30 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
test('a plane that stops reporting keeps moving dimmed as STALE from its first missed update, then stops as SIGNAL LOST', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(30));
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: '',
dimmed: false,
});
assert.equal(h.tracking._trackedIconColor().alpha, 1);
// The first missed update.
h.flightState.records.missingPolls.set(ICAO, 1);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.match(h.tracking._trackedLabelText(ICAO), /STALE/);
// Drawn with the fleet's stale fade.
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
// Still moving well past 90 s.
h.run(pastReport(200));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-11)) > 100,
);
// The coast ends 300 s past the report; the plane stops there.
h.run(pastReport(310));
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
h.run(pastReport(330));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
);
assert.equal(
h.flightState._trailFixes.filter((e) => e.drawn).length,
recorded,
'the trail kept recording a stopped plane',
);
// 330 s of display past the report is 330 s + the display delay of wall time.
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: `SIGNAL LOST · ${minutes} min`,
dimmed: true,
});
assert.match(
h.tracking._trackedLabelText(ICAO),
new RegExp(`SIGNAL LOST · ${minutes} min`),
);
} finally {
h.restore();
}
});
test('a plane held at its last report shows SIGNAL LOST in seconds under a minute', () => {
// Its last report is 100 m above a known ground height: it holds there.
const { fixes, info } = outOfCoverage();
const h = harness({
fixes,
info,
nowMs: pastReport(-5),
ground: () => 6_300,
});
try {
h.tracking._startTrail(ICAO);
h.flightState.records.missingPolls.set(ICAO, 1);
h.run(pastReport(10));
assert.ok(10 + RENDER_DELAY_SEC < 60);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: `SIGNAL LOST · ${10 + RENDER_DELAY_SEC} s`,
dimmed: true,
});
} finally {
h.restore();
}
});
test('a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(200));
// Heard again: the report is for 10 s before the display time, 2 km north
// of where the coast put it.
const at = T0 + 30 * SEC + 190 * SEC;
const guess = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(at)),
);
const c = Cesium.Cartographic.fromCartesian(guess);
const report = fix(
at,
Cesium.Math.toDegrees(c.latitude) + 2_000 / 111_320,
Cesium.Math.toDegrees(c.longitude),
c.height,
140,
90,
);
fixes.push(report);
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
assert.deepEqual(
h.flightState._trailFixes.filter(
(e) => e.drawn && e.timeMs > report.epochMs,
),
[],
);
const from = h.drawn.length;
h.run(pastReport(203));
const after = h.drawn.slice(from - 1);
for (let i = 1; i < after.length; i++)
assert.ok(
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
'the plane jumped instead of easing',
);
// Eased onto the path from the report: 13 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(
Math.abs(off - 140 * 13) < 150,
`${off.toFixed(0)} m from the report`,
);
} finally {
h.restore();
}
});
test('a tracked plane that stops reporting: STALE from the first missed poll, SIGNAL LOST after the five-minute coast, kept at 9 min, removed at 10 min', () => {
const { fixes, info } = outOfCoverage();
const fixMs = fixes.at(-1).epochMs;
// Contact stops with the position: the plane left coverage.
info.lastContactEpochMs = fixMs;
info.newestFixMs = fixMs;
const h = harness({ fixes, info, nowMs: fixMs + 5 * SEC });
try {
h.tracking._startTrail(ICAO);
const records = h.flightState.records;
const polls = new Map();
let removedAtSec = null;
// A poll every 10 s that lists the plane without a position.
for (let afterSec = 10; afterSec <= 660; afterSec += 10) {
h.run(fixMs + afterSec * SEC, { frameMs: 500, readHead: false });
const result = records.absence(ICAO, {
complete: true,
retainIds: new Set([ICAO]),
likelyLanded: false,
tracked: true,
});
if (result === 'remove') {
removedAtSec = afterSec;
break;
}
polls.set(afterSec, {
cue: h.tracking._trackedStaleCue(ICAO),
drawn: Cesium.Cartesian3.clone(h.drawn.at(-1)),
});
}
// Wall time when the display reaches the end of the coast.
const coastEndSec = 300 + RENDER_DELAY_SEC;
for (const [afterSec, { cue }] of polls) {
if (afterSec <= coastEndSec) {
assert.deepEqual(cue, { text: 'STALE', dimmed: true }, `${afterSec} s`);
} else {
assert.deepEqual(
cue,
{
text: `SIGNAL LOST · ${Math.floor(afterSec / 60)} min`,
dimmed: true,
},
`${afterSec} s`,
);
}
}
const moved = (a, b) =>
Cesium.Cartesian3.distance(polls.get(a).drawn, polls.get(b).drawn);
// Moving through the coast, still at its last speed at four minutes.
assert.ok(Math.abs(moved(230, 240) - 140 * 10) < 20);
// Stopped once the coast has ended.
const after = Math.ceil(coastEndSec / 10) * 10;
assert.ok(moved(after, 540) < 0.01);
assert.equal(polls.get(300).cue.text, 'STALE');
assert.deepEqual(polls.get(540).cue, {
text: 'SIGNAL LOST · 9 min',
dimmed: true,
});
assert.equal(removedAtSec, 600);
} finally {
h.restore();
}
});
test('a repeated old fix counts as a missed update for the tracked plane', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(-2));
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: '',
dimmed: false,
});
// The feed re-sends the last position: its fix time did not advance.
h.flightState.records.fixRepeated.add(ICAO);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
}
});
test('a stalled feed dims the tracked plane as STALE', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(-2));
// The whole feed is backing off: no poll counts a miss, and no newer
// position is coming in.
h.flightState.feed._backoff = true;
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
}
});
test('a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
const { fixes, info } = outOfCoverage();
info.lastContactEpochMs = fixes.at(-1).epochMs;
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(360));
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
const kept = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => Cesium.Cartesian3.clone(e.position));
// The thinned straight coast, recorded up to where the plane stopped.
assert.ok(kept.length >= 2);
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
// Heard again, for 20 s before the display time: the plane flew on, a
// little north of its old heading.
const at = T0 + 30 * SEC + 340 * SEC;
const lonDeg =
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
const report = fix(at, 43 + 1_000 / 111_320, lonDeg, 6_400, 140, 90);
fixes.push(report);
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// Nothing was recorded after the stop, so nothing is dropped.
const after = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => e.position);
assert.equal(after.length, kept.length);
kept.forEach((p, i) =>
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
);
const from = h.drawn.length;
h.run(pastReport(365));
const eased = h.drawn.slice(from - 1);
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
for (let i = 1; i < eased.length; i++)
assert.ok(
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
'the plane jumped instead of easing',
);
// On the path from the report: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
assertNoSpur(h.bodyPoints(), 'trail');
assertNoSpur(h.head(), 'head');
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
} finally {
h.restore();
}
});
+3 -1
View File
@@ -69,6 +69,8 @@ export function createGnssIntegrityLayer({
source,
viewAnchor = defaultGnssViewAnchor,
now = () => Date.now(),
// The end of the window shown; retries and receipt times stay on `now`.
worldNow = now,
monotonicNow = () => performance.now(),
windowMs: requestedWindowMs,
} = {}) {
@@ -163,7 +165,7 @@ export function createGnssIntegrityLayer({
/** Age the store without new evidence, so expired cells leave the globe. */
function expire() {
pruneGnssObservations(_observations, now(), { windowMs });
pruneGnssObservations(_observations, worldNow(), { windowMs });
_cells = binGnssCells(_observations);
render();
}
+35
View File
@@ -164,6 +164,41 @@ export function createControls({ state: layerState, services, parts, source }) {
);
},
/**
* A loaded mapped installation by id, as `getNearby` returns it (with its
* drawn `position`), or null while the layer is off or the id is not
* loaded. Read-only: nothing is selected.
* @param {string} id Source-backed installation id.
* @returns {object|null}
*/
getById(id) {
if (!layerState.enabled || id === null || id === undefined) return null;
const record = layerState.recordById.get(String(id));
if (!record || record.kind !== 'installation') return null;
return {
...record,
position: Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
parts.rendering.installationSurfaceHeightM(record),
),
};
},
/**
* The mapped installation a `scene.pick()` result landed on: a named
* marker point (`{ installationId }`) or a site entity, as this layer's
* own click selection reads them. Null for anything else.
* @param {object|null|undefined} picked
* @returns {object|null} As {@link getById}.
*/
findByPick(picked) {
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
return id ? methods.getById(id) : null;
},
/**
* Select and frame a mapped installation from another contextual UI.
* @param {string} id Source-backed installation id.
+1 -1
View File
@@ -29,7 +29,7 @@ export function createControls({ state: layerState, services, parts, source }) {
*/
getAnalystRecords(maxCount = Infinity) {
if (!layerState._enabled) return [];
const now = Date.now();
const now = layerState.now();
const text = (v) => (typeof v === 'string' && v.trim() ? v.trim() : null);
const result = [];
for (const launch of layerState._launches || []) {
+1
View File
@@ -224,6 +224,7 @@ export function createIngestion({
}
layerState._focusAfterActiveLookup = false;
parts.panel.renderMissionPanel();
layerState.coverageChanged();
layerState._entryCameraView = null;
} catch (error) {
if (layerState._enabled && token === layerState._lifecycleToken) {
+1 -1
View File
@@ -105,7 +105,7 @@ export function createLaunchPad({
}
const nowMs = Date.now();
if (nowMs - layerState._lastMissionRingRotationMs >= 1000) {
layerState._missionRingDate.setTime(nowMs);
layerState._missionRingDate.setTime(layerState.orbitNow());
parts.orbitRendering.updateMissionOrbitPrimitiveFrames(
layerState._missionRingDate,
);
+18
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../data/inputOwnership.js';
import { worldClock } from '../../time/worldClock.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -156,6 +157,21 @@ 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.
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);
if (!marks.length) return null;
return { start: marks[0], end: marks.at(-1), marks };
},
});
const methods = {
init(viewer) {
@@ -231,6 +247,7 @@ export function createLifecycle({
}
throw error;
}
layerState.coverageChanged();
},
async _enableBody() {
@@ -297,6 +314,7 @@ export function createLifecycle({
parts.overlays.clearMissionOverlaySources();
await parts.ingestion.restoreSatelliteDependency();
parts.panel.renderMissionPanel();
layerState.coverageChanged();
},
async destroy(viewer) {
+4 -1
View File
@@ -67,6 +67,9 @@ export function createOrbitRendering({
return Boolean(
layerState._enabled &&
layerState._dataSource?.show &&
!layerState.launchHidden(
layerState._missionOverlayRecords.get(launchId)?.launch,
) &&
(!layerState._selectedLaunchId ||
layerState._selectedLaunchId === launchId),
);
@@ -124,7 +127,7 @@ export function createOrbitRendering({
collection.show = missionOrbitPrimitiveVisible(launch.id);
orbitFrameModelMatrix(
satelliteTrack.gmstAtBake,
new Date(),
new Date(layerState.orbitNow()),
collection.modelMatrix,
);
layerState._viewer.scene.primitives.add(collection);
+4 -1
View File
@@ -411,8 +411,11 @@ export function createOverlays({ state: layerState, services, parts, source }) {
false,
);
layerState._selectedMissionOverlayTimeText = null;
const records = [...layerState._missionOverlayRecords.values()].filter(
(record) => !layerState.launchHidden(record.launch),
);
const entries = selectRocketMissionMarkerOverlayCohort(
Array.from(layerState._missionOverlayRecords.values(), (record) => {
records.map((record) => {
const entry = createRocketMissionMarkerOverlayEntry(
record.launch,
record.anchorPosition,
+39 -12
View File
@@ -22,6 +22,25 @@ export function createRendering({
if (current !== next) graphic.show = next;
}
// Away from live, a launch shows from its lift-off on, so scrubbing the
// world time forward brings the launches up in the order they flew. The
// selected mission stays, whenever it flies.
function syncPendingLaunches() {
const pending = new Set();
for (const { launch } of layerState._missionOverlayRecords.values()) {
if (layerState.launchHidden(launch)) pending.add(launch.id);
}
const previous = layerState._pendingLaunchIds;
if (
pending.size === previous.size &&
[...pending].every((id) => previous.has(id))
)
return;
layerState._pendingLaunchIds = pending;
parts.overlays.syncMissionOverlayEntries();
parts.orbitRendering.syncMissionOrbitPrimitiveVisibility();
}
function updateMissionFrame() {
if (
!layerState._enabled ||
@@ -31,6 +50,7 @@ export function createRendering({
parts.overlays.hideReplayVehicleOverlay();
return;
}
syncPendingLaunches();
parts.panel.updateMissionTelemetry();
const time = Cesium.JulianDate.now(layerState._declutterTime);
layerState._declutterOccluder.cameraPosition =
@@ -39,21 +59,28 @@ export function createRendering({
parts.overlays.refreshSelectedMissionOverlayText();
for (const entity of layerState._dataSource.entities.values) {
if (!entity.show) continue;
if (!entity.position) continue;
const id = parts.selection.entityLaunchId(entity);
if (!id) continue;
const pending = layerState._pendingLaunchIds.has(id);
if (entity.polyline)
setGraphicVisibility(entity.polyline, !pending, time);
if (!entity.position) continue;
const position = entity.position.getValue(time);
let horizonVisible = Boolean(
position && layerState._declutterOccluder.isPointVisible(position),
);
let horizonVisible =
!pending &&
Boolean(
position && layerState._declutterOccluder.isPointVisible(position),
);
const launchAnchor = entity.id.startsWith('rocket-launch:');
if (launchAnchor) {
horizonVisible = parts.overlays.missionAnchorVisible(
layerState._viewer.scene.camera.positionWC,
position,
id,
layerState._selectedLaunchId,
);
horizonVisible =
!pending &&
parts.overlays.missionAnchorVisible(
layerState._viewer.scene.camera.positionWC,
position,
id,
layerState._selectedLaunchId,
);
// Keep entity.show reserved for mission-selection isolation. Horizon
// state is applied to the individual graphics below so a rear-side
// anchor remains eligible for reevaluation as the camera moves.
@@ -394,7 +421,7 @@ export function createRendering({
orbitCurrent.latitude,
orbitCurrent.altitude,
);
const liveTime = new Date();
const liveTime = new Date(layerState.orbitNow());
const liveTelemetry = { speedMps: null };
layerState._satelliteTelemetry.set(launch.id, liveTelemetry);
let liveFrameNumber = -1;
@@ -405,7 +432,7 @@ export function createRendering({
layerState._viewer?.scene?.frameState?.frameNumber ?? -1;
if (frameNumber !== -1 && frameNumber === liveFrameNumber) return;
liveFrameNumber = frameNumber;
const nowMs = Date.now();
const nowMs = layerState.orbitNow();
liveTime.setTime(nowMs);
if (satelliteTrack) {
const propagated =
+33
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
@@ -156,6 +157,38 @@ export function createState({ services }) {
state._missionRingDate = new Date(0);
/** The time the launch window ends at, in epoch ms. */
state.now = worldTimeFor('rocket-launches');
/** A launched mission's satellite flies on the satellites layer's time. */
state.orbitNow = worldTimeFor('satellites');
/** The launches loaded changed, and with them the time they cover. */
state.coverageChanged = () => worldClock.coverageChanged();
/**
* Whether a launch has yet to lift off at the world time. While live none
* has, so the layer shows every launch in its window as it always did.
*/
state.launchPending = (launch) => {
if (worldClock.isLive()) return false;
const launchMs = Date.parse(launch?.launchTime);
return Number.isFinite(launchMs) && launchMs > state.now();
};
/** Whether a launch is hidden for lifting off after the world time. */
state.launchHidden = (launch) =>
launch?.id !== state._selectedLaunchId && state.launchPending(launch);
/** The launches hidden at the last frame, by id, to spot a change. */
state._pendingLaunchIds = new Set();
state._missionOrbitPatternRegistered = false;
state._pathDistanceCache = new WeakMap();
+102
View File
@@ -0,0 +1,102 @@
// Away from live, a launch shows from its lift-off on, so scrubbing the world
// time brings the launches up in the order they flew.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { worldClock } from '../../time/worldClock.js';
import { createState } from './state.js';
import { createRendering } from './rendering.js';
import { createSelection } from './selection.js';
const noop = () => {};
const LAUNCH_MS = Date.UTC(2026, 9, 20, 12);
function scene(t) {
t.after(() => worldClock.goLive());
const state = createState({
services: {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
},
});
const launch = {
id: 'ceres-1',
launchTime: new Date(LAUNCH_MS).toISOString(),
};
state._enabled = true;
state._dataSource = new Cesium.CustomDataSource('launches');
state._viewer = {
scene: { camera: { positionWC: new Cesium.Cartesian3(2e7, 0, 0) } },
};
state._missionOverlayRecords.set(launch.id, { launch });
const position = Cesium.Cartesian3.fromDegrees(0, 0);
const anchor = state._dataSource.entities.add({
id: `rocket-launch:${launch.id}`,
position,
point: { pixelSize: 5 },
});
const path = state._dataSource.entities.add({
id: `rocket-transfer:${launch.id}`,
polyline: { positions: [position, Cesium.Cartesian3.fromDegrees(1, 1)] },
});
const syncs = { labels: 0, orbits: 0 };
const parts = {
panel: { updateMissionTelemetry: noop },
overlays: {
hideReplayVehicleOverlay: noop,
updateReplayVehicleOverlay: noop,
refreshSelectedMissionOverlayText: noop,
missionAnchorVisible: () => true,
syncMissionOverlayEntries: () => syncs.labels++,
},
orbitRendering: {
syncMissionOrbitPrimitiveVisibility: () => syncs.orbits++,
},
};
const services = {
geometry: { getKeyholeGeometry: noop },
satellites: {},
};
parts.selection = createSelection({ state, services, parts });
const rendering = createRendering({ state, services, parts });
const shown = () => {
rendering.updateMissionFrame();
const time = Cesium.JulianDate.now();
return {
marker: anchor.point.show.getValue(time),
path: path.polyline.show?.getValue(time) ?? true,
};
};
return { state, launch, syncs, shown };
}
test('live shows every launch in the window, lifted off or not', (t) => {
const { state, launch, shown } = scene(t);
assert.equal(state.launchPending(launch), false);
assert.deepEqual(shown(), { marker: true, path: true });
});
test('away from live a launch shows from its lift-off on', (t) => {
const { state, launch, syncs, shown } = scene(t);
worldClock.seek(LAUNCH_MS - 60_000);
assert.equal(state.launchPending(launch), true);
assert.deepEqual(shown(), { marker: false, path: false });
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'its label and orbit go');
shown();
assert.deepEqual(syncs, { labels: 1, orbits: 1 }, 'once, not each frame');
worldClock.seek(LAUNCH_MS);
assert.equal(state.launchPending(launch), false);
assert.deepEqual(shown(), { marker: true, path: true });
assert.deepEqual(syncs, { labels: 2, orbits: 2 });
});
test('the selected mission stays whenever it flies', (t) => {
const { state, launch, shown } = scene(t);
state._selectedLaunchId = launch.id;
worldClock.seek(LAUNCH_MS - 60_000);
assert.deepEqual(shown(), { marker: true, path: true });
});
+86 -14
View File
@@ -1,13 +1,18 @@
import * as Cesium from 'cesium';
import { julianAt } from '../../time/julian.js';
import {
lerpAngleDeg,
speedRamp,
courseBetweenCartesians,
COURSE_HOLD_SPEED_MPS,
floorCoastedPosition,
staleCoastLimitSeconds,
staleCoastSecondsFrom,
staleHoldsForFix,
arcOffsetEnu,
courseSlewCapDps,
limitCourseStep,
COAST_MAX_SPEED_MPS,
} from '../../data/motionModel.js';
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
@@ -67,7 +72,7 @@ export function createMotion({
// 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(
Cesium.JulianDate.now(),
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
flightState._scratchRenderTime,
);
@@ -140,23 +145,86 @@ export function createMotion({
);
}
// Continue through fresh adsb.lol contacts even when the position epoch has
// not advanced, but keep an absolute stale-feed drift ceiling.
// Coast on the last speed and heading for five minutes past the newest
// fix, then stop, dimmed as SIGNAL LOST. A contact last heard on or near
// the ground holds there instead, and a coast never goes below the ground.
const { coastSec } = _coastPlan(newest, info, elapsedSec);
const cachedGroundFloor = services.groundFloor?.cachedGroundFloor;
_extrapolateFix(
newest,
info,
coastSec,
out,
(info && info.turnRateDps) || 0,
);
return coastSec > 0 ? floorCoastedPosition(out, cachedGroundFloor) : out;
}
/**
* How far a contact coasts past its newest fix at a display time
* `elapsedSec` after it: up to five minutes, or not at all for a contact
* that holds at a report on or near the ground. The hold decision is made once
* per report and kept on it.
* @param {{epochMs?: number, time: Cesium.JulianDate}} newest
* @param {object|undefined} info - The contact's record.
* @param {number} elapsedSec
* @returns {{coastSec: number, holds: boolean}}
*/
function _coastPlan(newest, info, elapsedSec) {
const coastLimitSec = staleCoastLimitSeconds({
// Captured at poll normalization so the fleet tick does not allocate a
// Date for every aircraft twelve times per second.
// `epochMs` is captured once when the poll is normalized. Avoid allocating
// a Date per aircraft on every fleet tick.
fixEpochMs: Number.isFinite(newest.epochMs)
? newest.epochMs
: Cesium.JulianDate.toDate(newest.time).getTime(),
lastContactEpochMs: info?.lastContactEpochMs,
// Five minutes of flight after the last report, as flights.
minimumSec: 300,
maximumSec: 300,
});
return _extrapolateFix(
const holds = staleHoldsForFix(newest, {
onGround: info?.onGround,
cachedGroundFloor: services.groundFloor?.cachedGroundFloor,
});
return {
coastSec: staleCoastSecondsFrom({
newest,
elapsedSec,
coastLimitSec,
holds,
}),
holds,
};
}
/**
* Whether a contact has stopped where its coast ended (or held at its last
* report) with no newer report, and since when it has had none.
* @param {string} icao24
* @returns {{reportEpochMs: number, holds: boolean}|null} Null while a
* report is ahead of the display time or the contact is still coasting.
*/
function _signalLost(icao24) {
const newest = flightState._positionHistory.get(icao24)?.at(-1);
if (!newest) return null;
const newestMs = Number.isFinite(newest.epochMs)
? newest.epochMs
: Cesium.JulianDate.toDate(newest.time).getTime();
const elapsedSec =
(flightState.now() - RENDER_DELAY_SEC * 1000 - newestMs) / 1000;
if (!(elapsedSec > 0)) return null;
const { coastSec, holds } = _coastPlan(
newest,
info,
Math.min(elapsedSec, coastLimitSec),
out,
(info && info.turnRateDps) || 0,
flightState.records.data.get(icao24),
elapsedSec,
);
if (!(elapsedSec > coastSec)) return null;
return {
reportEpochMs: Number.isFinite(newest.reportEpochMs)
? newest.reportEpochMs
: newestMs,
holds,
};
}
/**
@@ -171,9 +239,12 @@ export function createMotion({
*/
function _extrapolateFix(fix, info, dt, out, turnRateDps = 0) {
const speed = Number.isFinite(fix.velocity)
? fix.velocity
: (info && info.speedMps) || 0;
const speed = Math.min(
Number.isFinite(fix.velocity)
? fix.velocity
: (info && info.speedMps) || 0,
COAST_MAX_SPEED_MPS,
);
const heading = Number.isFinite(fix.track)
? fix.track
: (info && info.track) || 0;
@@ -213,7 +284,7 @@ export function createMotion({
const history = flightState._positionHistory.get(flightState._trackedIcao);
if (!history || history.length === 0) return true;
const renderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
@@ -513,6 +584,7 @@ export function createMotion({
}
return {
_deadReckon,
_signalLost,
_extrapolateFix,
_isTrackWarmingUp,
_trackedFocusSizePx,
+4 -1
View File
@@ -172,7 +172,7 @@ export const TRAIL_COLOR = '#FFB800';
/** @constant {number} Combined cap on trail vertices (backfill + live accumulation). */
export const TRAIL_MAX_POINTS = 400;
export const TRAIL_MAX_POINTS = 2000;
// ---------------------------------------------------------------------------
// Render-behind smoothing (mirrors flights.js): the fleet renders at
@@ -271,3 +271,6 @@ export const TRACKED_MODEL_RETRY_BACKOFF_MS = 1500;
* synchronously (single primitive). */
export const IR_RELOAD_BATCH = 40;
/** Alpha of a contact that has missed an update or lost its signal: the stale fade, for the fleet and the tracked aircraft alike. */
export const STALE_ALPHA = 0.45;
+4
View File
@@ -6,4 +6,8 @@ export const LANDED_MISSING_POLL_LIMIT = 1;
export const MISSING_POLL_LIMIT = 3;
/** The tracked contact is kept this long after its newest fix: five minutes
* coasting, then five stopped as SIGNAL LOST. */
export const TRACKED_RETENTION_MS = 10 * 60_000;
export const ERROR_BACKOFF_INTERVAL = 20000;
+61 -3
View File
@@ -6,6 +6,7 @@ import {
GROUND_FLOOR_WARM_MAX_ALT_M,
LANDED_MISSING_POLL_LIMIT,
MISSING_POLL_LIMIT,
TRACKED_RETENTION_MS,
} from './recordPolicy.js';
/** Portable military aircraft metadata and bounded missing-poll retention. */
@@ -14,9 +15,44 @@ export class MilitaryFlightRecords {
this.services = { geoidHeight, cachedGroundFloor, floorAltitudeM };
this.data = new Map();
this.missingPolls = new Map();
// Contacts whose last poll re-sent a fix no newer than the one before.
this.fixRepeated = new Set();
this.lastSnapshotMs = null;
this.snapshotAdvanced = true;
this.geoidNCache = new Map();
this.geoidReady = false;
}
/**
* Start reading a snapshot taken at `observedAtMs`. A fix re-sent in a
* newer snapshot marks its contact as not updated; the same snapshot read
* again does not.
* @param {number} observedAtMs
*/
beginSnapshot(observedAtMs) {
this.snapshotAdvanced =
!Number.isFinite(observedAtMs) ||
!Number.isFinite(this.lastSnapshotMs) ||
observedAtMs > this.lastSnapshotMs;
if (Number.isFinite(observedAtMs))
this.lastSnapshotMs = Math.max(
this.lastSnapshotMs ?? -Infinity,
observedAtMs,
);
}
/** Note a received fix: the newest fix time, and whether it advanced. */
_noteFix(id, prevMeta, fixEpochMs) {
const prevFixMs = prevMeta?.newestFixMs;
// A fix counts as new only when it moves on by a second: feeds that
// derive fix time from receipt (readsb `now − seen_pos`, 0.1 s) jitter.
if (!Number.isFinite(prevFixMs) || fixEpochMs >= prevFixMs + 1000) {
this.fixRepeated.delete(id);
return fixEpochMs;
}
if (this.snapshotAdvanced) this.fixRepeated.add(id);
return prevFixMs;
}
receive(
aircraft,
{ observedAtMs, floorWarmPoints: _floorWarmPoints, modelOwnsVisual },
@@ -88,6 +124,10 @@ export class MilitaryFlightRecords {
// already uses (which also carries the on-ground 0 m / last-known-baro
// case), so the two never disagree on the "no data yet" case.
let renderAltitudeM = pickedAltM != null ? pickedAltM : altitudeM;
// No altitude for an airborne contact: the height is the airborne
// default, invented. The tracked trail keeps no point there.
const renderAltitudeInvented =
pickedAltM == null && !onGround && aircraft.baroAltitudeM == null;
// Field-test fix (RS46 heli-in-hillside, 2026-07-06): a baro-only
// AIRBORNE contact near steep terrain can compute a render height
// BELOW the local surface (no alt_geom; baro+N carries QNH error
@@ -127,9 +167,11 @@ export class MilitaryFlightRecords {
// Sticky merge — adsb.lol intermittently drops flight/t/r/ownOp; hold
// 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 meta = {
sourceReference: aircraft.reference,
observedReceiptMs: Date.now(),
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
callsign: stickyText(callsign, prevMeta?.callsign),
type: stickyType,
// Type outranks category automatically inside classifyAircraft.
@@ -146,6 +188,7 @@ export class MilitaryFlightRecords {
// altitudeFt/baro).
geoAltitudeM,
renderAltitudeM,
renderAltitudeInvented,
// A poll that omits track/speed holds the last values, like the civil
// records; 0 only until one is known. A grounded row without a speed
// reads 0, so a parked plane never coasts at its landing speed.
@@ -184,10 +227,25 @@ export class MilitaryFlightRecords {
prevMeta,
meta,
groundFlipped,
fixEpochMs: aircraft.positionTimeMs ?? observedAtMs,
fixEpochMs,
};
}
absence(id, { complete, retainIds, likelyLanded }) {
absence(id, { complete, retainIds, likelyLanded, tracked = false }) {
const misses = (this.missingPolls.get(id) || 0) + 1;
// The tracked contact has missed an update: it is stale from the first
// one, and kept (so the camera keeps its target) until ten minutes after
// its newest fix, whatever the snapshot says. With no fix time known it
// takes the ordinary limits below.
const meta = this.data.get(id);
const fixMs = meta?.newestFixMs ?? meta?.observedReceiptMs;
if (tracked && Number.isFinite(fixMs)) {
if (Date.now() - fixMs < TRACKED_RETENTION_MS) {
this.missingPolls.set(id, misses);
return 'stale';
}
this.missingPolls.delete(id);
return 'remove';
}
// Partial admissions and position-less rows do not prove absence, but
// retention remains bounded; a likely-landed position-less contact
// still takes the landed limit.
@@ -196,7 +254,6 @@ export class MilitaryFlightRecords {
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
)
return 'retain';
const misses = (this.missingPolls.get(id) || 0) + 1;
const limit = likelyLanded ? LANDED_MISSING_POLL_LIMIT : MISSING_POLL_LIMIT;
if (misses < limit) {
this.missingPolls.set(id, misses);
@@ -208,6 +265,7 @@ export class MilitaryFlightRecords {
forget(id) {
this.data.delete(id);
this.missingPolls.delete(id);
this.fixRepeated.delete(id);
this.geoidNCache.delete(id);
}
}
+95
View File
@@ -174,3 +174,98 @@ test('military records hold the last track and speed when a poll omits them', ()
assert.equal(parked.meta.speedMps, 0);
assert.equal(parked.meta.track, 90);
});
test('an airborne military contact reported with no altitude is marked as drawn at an invented height', () => {
const records = store();
const none = records.receive(
observation({ baroAltitudeM: null, ellipsoidAltitudeM: null }),
context(),
);
assert.equal(none.meta.renderAltitudeInvented, true);
const known = records.receive(
observation({ positionTimeMs: 1700000005000 }),
context(),
);
assert.equal(known.meta.renderAltitudeInvented, false);
const parked = store().receive(
observation({ baroAltitudeM: null, onGround: true }),
context(),
);
assert.equal(parked.meta.renderAltitudeInvented, false);
});
test('the tracked military contact is stale from its first missed update and kept until ten minutes after its newest fix', () => {
const realNow = Date.now;
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
let clock = fixMs + 5_000;
Date.now = () => clock;
try {
for (const snapshot of [
{ complete: true },
{ complete: true, retainIds: new Set(['aaa001']) },
{ complete: false },
]) {
const records = store();
records.receive(
observation({ positionTimeMs: fixMs }),
context({ observedAtMs: fixMs + 1_000 }),
);
const absent = (tracked) =>
records.absence('aaa001', {
...snapshot,
likelyLanded: false,
tracked,
});
clock = fixMs + 15_000;
assert.equal(absent(true), 'stale');
assert.equal(records.missingPolls.get('aaa001'), 1);
clock = fixMs + 9 * 60_000;
assert.equal(absent(true), 'stale');
clock = fixMs + 10 * 60_000 - 1;
assert.equal(absent(true), 'stale');
clock = fixMs + 10 * 60_000;
assert.equal(absent(true), 'remove');
assert.equal(records.missingPolls.has('aaa001'), false);
}
const records = store();
records.receive(
observation({ positionTimeMs: fixMs }),
context({ observedAtMs: fixMs + 1_000 }),
);
clock = fixMs + 15_000;
const untracked = (snapshot) =>
records.absence('aaa001', { ...snapshot, likelyLanded: false });
assert.equal(untracked({ complete: false }), 'retain');
assert.deepEqual(
[1, 2, 3].map(() => untracked({ complete: true })),
['stale', 'stale', 'remove'],
);
} finally {
Date.now = realNow;
}
});
test('a repeated military fix time marks the contact as not updated; removal is unchanged', () => {
const records = store();
const fixMs = Date.UTC(2026, 10, 9, 20, 0);
const poll = (snapshotMs, positionTimeMs) => {
records.beginSnapshot(snapshotMs);
records.receive(
observation({ positionTimeMs }),
context({ observedAtMs: snapshotMs }),
);
};
poll(fixMs + 2_000, fixMs);
assert.equal(records.fixRepeated.has('aaa001'), false);
// adsb.lol re-sends the last position for up to a minute.
poll(fixMs + 12_000, fixMs);
assert.equal(records.fixRepeated.has('aaa001'), true);
assert.equal(records.missingPolls.has('aaa001'), false);
poll(fixMs + 12_000, fixMs);
assert.equal(records.fixRepeated.has('aaa001'), true);
poll(fixMs + 22_000, fixMs + 10_000);
assert.equal(records.fixRepeated.has('aaa001'), false);
poll(fixMs + 32_000, fixMs + 10_000);
records.forget('aaa001');
assert.equal(records.fixRepeated.has('aaa001'), false);
});
+25 -1
View File
@@ -52,6 +52,7 @@ import {
COURSE_SLEW_DT_MAX_SEC,
ROTATION_REFRESH_MS,
COURSE_MAX_DPS,
STALE_ALPHA,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
@@ -640,6 +641,19 @@ export function createRendering({
/** Per-frame driver for the standalone tracked model (see flights.js for the rationale). The
* tracked entity stays a pure billboard, so the follow-camera never stalls/freezes on 3D-toggle. */
/** Fade the tracked 3D model like the billboard while the plane is stale. */
function _applyTrackedModelFade(model) {
const alpha = parts.tracking._trackedStaleCue?.(flightState._trackedIcao)
?.dimmed
? STALE_ALPHA
: 1;
if (model.color?.alpha === alpha) return;
model.color = (
flightState._irBoost ? Cesium.Color.WHITE : TRACKED_ICON_COLOR
).withAlpha(alpha);
}
function _updateTrackedModel() {
const active =
flightState._trackedIcao &&
@@ -787,6 +801,7 @@ export function createRendering({
flightState._trackedModel.modelMatrix,
spec.headingOffsetDeg,
);
_applyTrackedModelFade(flightState._trackedModel);
if (!flightState._trackedModel.ready) return;
flightState._trackedModel.scale = trackedModelScaleForPixelCap({
baseScale: spec.scale,
@@ -814,6 +829,13 @@ export function createRendering({
*/
function _fleetTick() {
// Every frame, shown or not: the tracked trail records where its icon is
// drawn and moves its body on (the head callback only reads the result),
// and the tracked label's stale cue follows the clock.
if (flightState._viewer) {
parts.tracking._trailTick?.();
parts.tracking._staleCueTick?.();
}
if (
!flightState._viewer ||
!flightState._billboardCollection ||
@@ -989,7 +1011,9 @@ export function createRendering({
flightState._cockpitContactMode && !isCockpitNear
? 1
: _militaryBillboardScale(icao24),
baseAlpha: flightState.records.missingPolls.get(icao24) ? 0.45 : 1,
baseAlpha: flightState.records.missingPolls.get(icao24)
? STALE_ALPHA
: 1,
baseColor,
focusFactor: focus.factor,
cameraDistanceM,
+21 -5
View File
@@ -4,6 +4,7 @@ import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
turnRateFromFixHistory,
liftRepeatedGroundFix,
staleHoldsForFix,
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
@@ -29,6 +30,7 @@ export function createMilitarySnapshotRenderer({
return function applySnapshot(snapshot, viewer) {
const currentIcaos = new Set();
const receiptNowMs = snapshot.observedAtMs;
records.beginSnapshot(snapshot.observedAtMs);
// Field-test fix (RS46): coarse floor cells to warm for the below-ground
// clamp — collected during the loop (low airborne contacts only),
// batch-resolved once after it. Never a fetch inside the loop.
@@ -83,6 +85,9 @@ export function createMilitarySnapshotRenderer({
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();
@@ -95,26 +100,36 @@ export function createMilitarySnapshotRenderer({
// (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());
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;
if (kinematicsChanged) {
const holds = staleHoldsForFix(newest, {
onGround: meta.onGround,
cachedGroundFloor,
});
if (kinematicsChanged && !holds) {
const synthetic = synthesizeForwardKinematicsFix(newest, {
epochMs: 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);
if (isTracked) tracking._appendTrailFix(synthetic.position.clone());
}
}
}
@@ -228,8 +243,8 @@ export function createMilitarySnapshotRenderer({
const bbStale = flightState._billboards.get(icao24);
if (bbStale) bbStale.position = liftedPos;
}
// Round 4: sample the RENDERED mesh for those cells (one-shot per cell,
// budget-capped, viewer-proximate, google-3d regime only), excluding
// Round 4: sample the RENDERED mesh for those cells (a few probes per
// cell, budget-capped, viewer-proximate, google-3d regime only), excluding
// this layer's own billboards/models from the probe.
{
const viewerCarto =
@@ -261,6 +276,7 @@ export function createMilitarySnapshotRenderer({
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
});
if (absence === 'retain') continue;
if (absence === 'stale') {
+152
View File
@@ -0,0 +1,152 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMilitarySnapshotRenderer } from './snapshotRenderer.js';
// A poll that repeats a contact's last position with new speed or course
// must not move it past where the stale rules allow, and never adds a
// report to the tracked trail.
const ICAO = '00a005';
const SEC = 1000;
/** Any property is a no-op function unless given. */
function stub(overrides = {}) {
return new Proxy(overrides, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
}
function harness({ ground = () => null }) {
const appended = [];
const history = [];
const flightState = {
_trackedIcao: ICAO,
_trackedEntity: null,
_positionHistory: new Map([[ICAO, history]]),
_billboards: new Map([[ICAO, { position: new Cesium.Cartesian3() }]]),
_billboardCollection: stub(),
_cullPositions: new Map(),
_displayCourse: new Map(),
_groundSnap: stub(),
_displayFloorState: new Map(),
_models: new Map(),
_viewer: null,
_cockpitContactMode: false,
records: { data: new Map() },
};
let meta = null;
let fixEpochMs = 0;
const records = stub({
receive: () => {
flightState.records.data.set(ICAO, meta);
return { prevMeta: meta, meta, groundFlipped: false, fixEpochMs };
},
absence: () => 'retain',
});
const apply = createMilitarySnapshotRenderer({
flightState,
records,
militaryRegistry: stub(),
groundFloor: stub({ cachedGroundFloor: ground }),
meshFloor: stub(),
rendering: stub({
_modelOwnsVisual: () => false,
_fleetBillboardColor: () => Cesium.Color.WHITE,
}),
tracking: stub({
_militaryLayerSuppresses: () => false,
_appendTrailFix: (position, epochMs) =>
appended.push({ position, epochMs }),
}),
motion: stub(),
enrichment: stub(),
queries: stub({ _likelyLanded: () => false }),
});
return {
history,
appended,
poll(nextMeta, epochMs) {
meta = nextMeta;
fixEpochMs = epochMs;
apply({ records: [{ id: ICAO }], complete: true }, null);
},
};
}
const lightAircraft = (velocity, track) => ({
rawLat: 38.1436,
rawLon: -122.5561,
renderAltitudeM: 10,
altitudeFt: 130,
speedMps: velocity,
track,
onGround: false,
wasAirborne: true,
klass: 'light',
});
test('military: a low contact whose position repeats while its speed changes is not moved and adds nothing to the trail', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({ ground: () => -30 });
h.poll(lightAircraft(36.4, 63), t0);
const first = h.history[0].position;
for (const [i, velocity] of [30, 22, 14, 9].entries()) {
t.mock.timers.tick(10 * SEC);
h.poll(lightAircraft(velocity, 63 + i * 20), t0);
}
assert.equal(h.history.length, 1, 'a synthetic fix moved a holding contact');
assert.equal(h.history[0].position, first);
assert.equal(h.appended.length, 1, 'only the real report joins the trail');
});
test('military: a cruising contact whose position repeats coasts no further than the stale cap, and the synthetic fix is not a report', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
const cruise = (velocity, track) => ({
rawLat: 36,
rawLon: -115,
renderAltitudeM: 9_000,
altitudeFt: 29_500,
speedMps: velocity,
track,
onGround: false,
wasAirborne: true,
klass: 'jet',
});
h.poll(cruise(220, 90), t0);
const report = h.history[0].position;
t.mock.timers.tick(300 * SEC);
h.poll(cruise(200, 100), t0);
assert.equal(h.history.length, 2);
const moved = Cesium.Cartesian3.distance(report, h.history[1].position);
assert.ok(
moved <= 220 * 300 + 1,
`the synthetic fix coasted ${moved.toFixed(0)} m`,
);
assert.equal(h.appended.length, 1, 'the synthetic fix joined the trail');
});
test('military: a report drawn at an invented height says so on its history fix', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
h.poll({ ...lightAircraft(60, 90), renderAltitudeInvented: true }, t0);
h.poll({ ...lightAircraft(60, 90), rawLon: -122.55 }, t0 + 10 * SEC);
assert.equal(h.history[0].inventedHeight, true);
assert.equal(h.history[1].inventedHeight, false);
});
test('military: with the ground unknown, a low barometric altitude alone does not hold a contact', (t) => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
t.mock.timers.enable({ apis: ['Date'], now: t0 });
const h = harness({});
h.poll(lightAircraft(36.4, 63), t0);
t.mock.timers.tick(10 * SEC);
h.poll(lightAircraft(30, 80), t0);
assert.equal(h.history.length, 2);
assert.equal(h.history[0].staleHolds, false);
assert.equal(h.appended.length, 1);
});
+199
View File
@@ -0,0 +1,199 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { TRAIL_CONTINUITY_MAX_SPEED_KT } from '../../data/trailContinuity.js';
import { RENDER_DELAY_SEC } from './policy.js';
const SEC = 1000;
function motionFixture({ info, fixes, nowMs, ground = () => null }) {
const flightState = {
records: { data: new Map([['00a003', info]]) },
_positionHistory: new Map([['00a003', fixes]]),
_scratchArc: {},
_scratchOffset: new Cesium.Cartesian3(),
_scratchEnu: new Cesium.Matrix4(),
_scratchRenderTime: new Cesium.JulianDate(),
now: () => nowMs,
};
const motion = createMotion({
flightState,
services: {
groundFloor: { cachedGroundFloor: ground },
camera: {},
focus: {},
},
parts: {},
});
return motion;
}
function fix(timeMs, lat, lon, heightM, velocity, track) {
return {
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
epochMs: timeMs,
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
velocity,
track,
};
}
test('a military contact stale after a low approach holds at its last report', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const ground = 1_590; // An airbase, ellipsoidal.
const fixes = [
fix(t0, 35.03, -106.58, ground + 300, 75, 260),
fix(t0 + 10 * SEC, 35.03, -106.588, ground + 40, 70, 260),
];
const info = {
altitudeFt: 5_350,
renderAltitudeM: ground + 40,
rawLat: 35.03,
rawLon: -106.588,
speedMps: 70,
track: 260,
onGround: false,
};
for (const afterSec of [10, 60, 200]) {
const motion = motionFixture({
info,
fixes,
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC,
ground: () => ground,
});
const drawn = motion._deadReckon('00a003', new Cesium.Cartesian3());
assert.ok(Cesium.Cartesian3.distance(drawn, fixes[1].position) < 0.01);
}
});
test('a cruising military contact still heard after its last position coasts past 90 s, for up to 5 minutes, then stops', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 36, -115, 9_000, 220, 90),
fix(t0 + 10 * SEC, 36, -114.975, 9_000, 220, 90),
];
const info = {
altitudeFt: 29_500,
renderAltitudeM: 9_000,
rawLat: 36,
rawLon: -114.975,
speedMps: 220,
track: 90,
onGround: false,
lastContactEpochMs: t0 + 10 * SEC + 300 * SEC,
};
const at = (afterSec) =>
motionFixture({
info,
fixes,
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC,
})._deadReckon('00a003', new Cesium.Cartesian3());
const d = (p) => Cesium.Cartesian3.distance(p, fixes[1].position);
const near = (got, want) => Math.abs(got - want) < want * 0.005 + 50;
assert.ok(near(d(at(45)), 220 * 45));
assert.ok(near(d(at(250)), 220 * 250), 'still moving at 250 s');
assert.ok(near(d(at(400)), 220 * 300), 'stopped at 300 s');
});
test('a bad military speed coasts no faster than the 1,500 kt continuity limit', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [
fix(t0, 36, -115, 9_000, 2_000, 90),
fix(t0 + 10 * SEC, 36, -114.975, 9_000, 2_000, 90),
];
const info = {
altitudeFt: 29_500,
renderAltitudeM: 9_000,
rawLat: 36,
rawLon: -114.975,
speedMps: 2_000,
track: 90,
onGround: false,
};
const drawn = motionFixture({
info,
fixes,
nowMs: t0 + 10 * SEC + RENDER_DELAY_SEC * SEC + 300 * SEC,
})._deadReckon('00a003', new Cesium.Cartesian3());
const limitMps = (TRAIL_CONTINUITY_MAX_SPEED_KT * 1852) / 3600;
const d = Cesium.Cartesian3.distance(drawn, fixes[1].position);
assert.ok(Math.abs(d - limitMps * 300) < 1_500, `${d.toFixed(0)} m`);
});
test('a holding military contact draws no head and its trail ends at the last report', () => {
const t0 = Date.UTC(2026, 10, 9, 20, 0);
const fixes = [0, 1, 2].map((i) =>
fix(t0 + i * 10 * SEC, 35.03, -106.57 - i * 0.008, 1_700, 70, 260),
);
const svc = {
...Object.fromEntries(
[
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
].map((name) => [name, {}]),
),
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: () => null,
floorAltitudeM: (alt) => alt,
},
};
const calls = [];
svc.trails = {
createTrail: () => ({
setSegments: (segments) => calls.push(segments.flat()),
setPositions: (positions) => calls.push(positions.slice()),
setVisible() {},
clear() {},
destroy() {},
}),
};
const flightState = createFlightState({ services: svc, source: {} });
const added = [];
flightState._viewer = {
isDestroyed: () => false,
entities: {
add: (definition) => (added.push(definition), definition),
remove() {},
},
};
flightState._trackedIcao = '00a003';
flightState.now = () => t0 + 20 * SEC + RENDER_DELAY_SEC * SEC + 120 * SEC;
flightState._positionHistory.set('00a003', fixes);
const last = Cesium.Cartesian3.clone(fixes[2].position);
const tracking = createTracking({
flightState,
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_trackedTrailCached: () => last,
_trackedDisplayPosition: () => last,
_trackedModelCenterWorld: () => null,
_trackedModelEnvelopeM: () => null,
},
},
layer: {},
});
tracking._startTrail('00a003');
assert.equal(calls.at(-1).length, 3);
const head = added.find((d) =>
String(d.id).startsWith('gev-trail:mil-head-'),
);
assert.deepEqual(head.polyline.positions.getValue(), []);
});
+28 -2
View File
@@ -1,6 +1,7 @@
import { MilitaryFlightRecords } from './records.js';
import { createMilitaryFeed } from './ingestion.js';
import * as Cesium from 'cesium';
import { worldTimeFor } from '../../time/worldClock.js';
export function createFlightState({ source, services }) {
const { createGroundSnap } = services.groundSnap;
@@ -11,6 +12,8 @@ export function createFlightState({ source, services }) {
...services.groundFloor,
});
flightState._cullPositions = new Map();
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('military');
/** Per-class model spec for THIS layer (2026-08-16, owner playtest ask:
* military contacts should read as their WEIGHT CLASS, always in this layer's
@@ -175,9 +178,32 @@ export function createFlightState({ source, services }) {
flightState._trailHeadSeq = 0;
/** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */
/** @type {{position: Cesium.Cartesian3|null, timeMs: number, nullAltitude: boolean, breakBefore: boolean, drawn?: boolean}[]}
* Chronological tracked-aircraft trail (oldest first): reports, and
* (`drawn`) where the icon was drawn between them; `breakBefore` starts a
* new segment. */
flightState._trailPositions = [];
flightState._trailFixes = [];
/** @type {number} Body fixes drawn: those at or before the display time. */
flightState._trailBodyCount = 0;
/** @type {Cesium.Cartesian3|null} Where the tracked icon was last recorded into the trail. */
flightState._trailRecordPosition = null;
/** @type {number} Display time (epoch ms) of that recording. */
flightState._trailRecordMs = -Infinity;
/** @type {string|undefined} The stale cue last written into the tracked label (see `_staleCueTick`). */
flightState._trackedStaleCueText = undefined;
/** @type {{key: string, cue: {text: string, dimmed: boolean}}|null} This frame's tracked stale cue (see `_trackedStaleCue`). */
flightState._trackedStaleCueCache = null;
/** @type {number} Monotonic token — invalidates in-flight backfill responses */
+286 -103
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { formatNumber, t } from '../../i18n/index.js';
import { unitLabel } from '../../ui/unitLabels.js';
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js';
import { trackedModelZoomActive } from '../../data/trackedModelRegime.js';
@@ -18,14 +19,33 @@ import {
TRACKED_MODEL_MAX_LOAD_FAILS,
TRACKED_MODEL_RETRY_BACKOFF_MS,
TRAIL_MAX_POINTS,
DR_CORRECTION_MS,
RENDER_DELAY_SEC,
TRAIL_COLOR,
BILLBOARD_SCALE,
GROUND_SCALE,
AMBER_TRANSPARENT,
TRACKED_ICON_COLOR,
STALE_ALPHA,
} from './policy.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
import {
drawTrailSegments,
historyFixEpochMs,
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
trailBackfillFixes,
trailBodyCount,
trailBodyCountOutsideModel,
trailBodySegments,
trailHeadStartFix,
trailRecordingBlocked,
TRAIL_RECORD_STEP_M,
TRAIL_RECORD_STEP_MS,
} from '../../data/trailContinuity.js';
const STALE_TRACKED_COLOR = TRACKED_ICON_COLOR.withAlpha(STALE_ALPHA);
export function createTracking({
flightState,
@@ -205,24 +225,98 @@ export function createTracking({
_setCockpitContactMode(active);
}
/**
* The tracked plane's stale cue and whether it is drawn with the stale fade.
* - SIGNAL LOST · <time since its last report>, dimmed: its coast has ended
* (or it holds at its last report after a missed update) and no newer
* report has come.
* - STALE, dimmed: it has missed an update and still coasts, or the whole
* feed is backing off.
* @param {string} icao24
* @returns {{text: string, dimmed: boolean}}
*/
function _trackedStaleCue(icao24) {
const records = flightState.records;
const misses = records.missingPolls.get(icao24) || 0;
const repeated = records.fixRepeated?.has(icao24) === true;
const backoff = flightState.feed._backoff === true;
// Computed once per frame for the label, the icon colour and the model
// fade; a poll between frames changes the key.
const frame = flightState._viewer?.scene?.frameState?.frameNumber;
const key = Number.isFinite(frame)
? `${frame}|${icao24}|${misses}|${repeated}|${backoff}`
: null;
const cached = flightState._trackedStaleCueCache;
if (key !== null && cached?.key === key) return cached.cue;
const cue = _computeTrackedStaleCue(
icao24,
misses > 0 || repeated,
backoff,
);
flightState._trackedStaleCueCache = key === null ? null : { key, cue };
return cue;
}
/** `_trackedStaleCue` without the per-frame cache. A repeated fix counts as missed. */
function _computeTrackedStaleCue(icao24, missed, backoff) {
const lost = parts.motion._signalLost(icao24);
if (lost && (missed || !lost.holds)) {
const sec = Math.max(
0,
Math.floor((flightState.now() - lost.reportEpochMs) / 1000),
);
const time =
sec < 60
? `${formatNumber(sec, { useGrouping: false })} ${unitLabel('s')}`
: `${formatNumber(Math.floor(sec / 60), { useGrouping: false })} ${unitLabel('min')}`;
return { text: t('SIGNAL LOST · {time}', { time }), dimmed: true };
}
// A missed update or a stalled feed: no newer position is coming in.
if (missed || backoff) return { text: t('STALE'), dimmed: true };
return { text: '', dimmed: false };
}
/** The tracked billboard's colour: amber, faded while stale, clear while the 3D model is the visual. */
function _trackedIconColor() {
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
return AMBER_TRANSPARENT;
return _trackedStaleCue(flightState._trackedIcao).dimmed
? STALE_TRACKED_COLOR
: TRACKED_ICON_COLOR;
}
/**
* Re-word the tracked label when its stale cue changes (STALE, SIGNAL LOST,
* each new second or minute of it). Run from the layer's per-frame pass.
*/
function _staleCueTick() {
const icao24 = flightState._trackedIcao;
if (!icao24 || !flightState._trackedEntity) return;
const text = _trackedStaleCue(icao24).text;
if (text === flightState._trackedStaleCueText) return;
flightState._trackedStaleCueText = text;
_updateTrackedLabelModel(icao24);
}
/**
* Build the multi-line presentation text for the protected tracked host card.
* Lines: callsign, type/registration, operator/altitude.
* While the plane is in its missed-poll grace (coasting on dead reckoning
* with sticky metadata) the first line carries a "· STALE" cue — the fleet's
* 45%-alpha billboard fade doesn't apply to the tracked plane (its entity
* owns the visual), so without this the readout would present last-known
* altitude/speed as live.
* The first line carries the stale cue (`_trackedStaleCue`): STALE while
* the plane coasts on dead reckoning after a missed update, SIGNAL LOST
* once the coast has ended, so last-known altitude/speed are never
* presented as live.
* @param {Object|null} info - Flight metadata from _flightData
* @param {string} icao24 - ICAO hex identifier (fallback display name)
* @returns {string} Newline-separated label text
*/
function _buildTrackedLabel(info, icao24) {
const stale =
flightState.records.missingPolls.get(icao24) || flightState.feed._backoff
? ` · ${t('STALE')}`
: '';
const cue = _trackedStaleCue(icao24).text;
const stale = cue ? ` · ${cue}` : '';
const callsign =
(parts.queries._toCleanText(info?.callsign) ||
parts.queries._toCleanText(info?.registration) ||
@@ -455,33 +549,112 @@ export function createTracking({
}
/**
* Append one fix to the tracked aircraft's trail accumulation and refresh
* the rendered trail. Caller passes an owned (cloned) Cartesian3.
* @param {Cesium.Cartesian3} position - New fix position, appended at the head.
* Put one report into the tracked aircraft's trail, in time order, and
* refresh the rendered trail. Caller passes an owned (cloned) Cartesian3. A
* report that breaks from its neighbour starts a new segment (see
* trailContinuity).
* @param {Cesium.Cartesian3} position - The report's position.
* @param {number} [epochMs] - The report's time; defaults to the tracked
* aircraft's newest position-history fix, which every caller has just pushed.
* @param {{nullAltitude?: boolean}} [options] - `nullAltitude`: the report
* had no altitude, so its position is not kept and the line breaks there.
* A report for a time the display has already passed replaces what was
* drawn after it (see `insertTrailFix`).
*/
function _appendTrailFix(position) {
flightState._trailPositions.push(_trailFloorPosition(position));
if (flightState._trailPositions.length > TRAIL_MAX_POINTS)
flightState._trailPositions.shift();
function _appendTrailFix(position, epochMs, { nullAltitude = false } = {}) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
? epochMs
: historyFixEpochMs(history?.[history.length - 1]);
insertTrailFix(
flightState._trailFixes,
_trailFloorPosition(position),
timeMs,
TRAIL_MAX_POINTS,
{
nullAltitude,
displayMs: flightState.now() - RENDER_DELAY_SEC * 1000,
settleMs: DR_CORRECTION_MS,
},
);
_refreshTrailDisplay();
}
/**
* Renders the trail BODY — the accumulated fixes EXCLUDING the newest raw one. That
* newest fix is at ~now, ~one poll interval AHEAD of the delayed icon (rendered at
* now − RENDER_DELAY_SEC), so drawing it would push the trail in FRONT of the plane.
* The cheap per-frame _trailHeadEntity segment bridges the last body point to the
* delayed dead-reckoned head, so this primitive only rebuilds on a real fix (poll
* cadence), never at motion cadence.
* Per-frame trail work, run from the layer's preRender pass whether or not
* the head is visible: record where the tracked icon is drawn (at most once
* a second or every 150 m, floored like the head) and move the body on as
* the display time passes reports. The head callback only reads the result.
*/
function _trailTick() {
if (!flightState._trackedIcao || !flightState._trail) return;
const displayMs = flightState.now() - RENDER_DELAY_SEC * 1000;
let changed = false;
if (
flightState._trailFixes.length &&
!parts.motion._isTrackWarmingUp() &&
!trailRecordingBlocked(flightState._trailFixes, displayMs)
) {
const drawn = parts.motion._trackedDisplayPosition(
flightState._trackedIcao,
);
const last = flightState._trailRecordPosition;
if (
drawn &&
(!last ||
displayMs - flightState._trailRecordMs >= TRAIL_RECORD_STEP_MS ||
Cesium.Cartesian3.distance(last, drawn) >= TRAIL_RECORD_STEP_M)
) {
flightState._trailRecordMs = displayMs;
flightState._trailRecordPosition = Cesium.Cartesian3.clone(
drawn,
flightState._trailRecordPosition ?? undefined,
);
changed = recordTrailPoint(
flightState._trailFixes,
_trailFloorPosition(Cesium.Cartesian3.clone(drawn)),
displayMs,
TRAIL_MAX_POINTS,
);
}
}
if (changed || _trailBodyCountNow() !== flightState._trailBodyCount)
_refreshTrailDisplay();
}
/**
* Renders the trail BODY — the accumulated fixes at or before the delayed display
* time (now − RENDER_DELAY_SEC). Newer fixes are AHEAD of the icon, so drawing them
* would push the trail in FRONT of the plane. The cheap per-frame _trailHeadEntity
* segment bridges the last body point to the delayed dead-reckoned head, so the
* body rebuilds only on a real fix or when the display time passes one, never at
* motion cadence. A break lifts the pen: each segment is
* its own line, nothing between them.
*/
function _refreshTrailDisplay() {
if (!flightState._trail) return;
flightState._trail.setPositions(
flightState._trailPositions.length > 1
? flightState._trailPositions.slice(0, -1)
: flightState._trailPositions,
flightState._trailBodyCount = _trailBodyCountNow();
drawTrailSegments(
flightState._trail,
trailBodySegments(flightState._trailFixes, flightState._trailBodyCount),
);
}
/** Fixes at or before the time the aircraft is drawn (now − RENDER_DELAY_SEC),
* less the newest recorded points inside its 3D model. */
function _trailBodyCountNow() {
return trailBodyCountOutsideModel(
flightState._trailFixes,
trailBodyCount(
flightState._trailFixes,
flightState.now() - RENDER_DELAY_SEC * 1000,
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
);
}
@@ -494,25 +667,27 @@ export function createTracking({
function _startTrail(icao24) {
flightState._trailBackfillToken += 1;
flightState._trailPositions = [];
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
const history = flightState._positionHistory.get(icao24) || [];
// Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The
// newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them
// would draw the trail in front of the plane. They join via _appendTrailFix as they age.
const seedRenderTime = Cesium.JulianDate.addSeconds(
Cesium.JulianDate.now(),
-RENDER_DELAY_SEC,
flightState._scratchWarmupTime,
);
// Seed every report. The body only draws those at or before the delayed
// display time (now − RENDER_DELAY_SEC); newer ones join it as the display
// passes them. A synthetic forward fix (it carries `reportEpochMs`) is a
// motion aid, never a report. A report drawn at an invented height keeps
// no position and breaks the line.
for (const fix of history) {
if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) {
// Floor grounded-history seeds (round 2): a grounded contact's stored
// fixes carry the pre-datum default height — the trail copy sits on
// the surface instead (pure lift; airborne fixes pass through).
flightState._trailPositions.push(
_trailFloorPosition(Cesium.Cartesian3.clone(fix.position)),
);
}
if (Number.isFinite(fix.reportEpochMs)) continue;
// Floor grounded-history seeds (round 2): a grounded contact's stored
// fixes carry the pre-datum default height — the trail copy sits on
// the surface instead (pure lift; airborne fixes pass through).
insertTrailFix(
flightState._trailFixes,
_trailFloorPosition(Cesium.Cartesian3.clone(fix.position)),
historyFixEpochMs(fix),
TRAIL_MAX_POINTS,
{ nullAltitude: fix.inventedHeight === true },
);
}
if (!flightState._trail && flightState._viewer) {
flightState._trail = createTrail(flightState._viewer, {
@@ -533,14 +708,13 @@ export function createTracking({
show: !flightState._cockpitContactMode,
polyline: {
positions: new Cesium.CallbackProperty(() => {
// Need ≥2 accumulated points: the body draws all-but-newest, so the head must
// start at the last DISPLAYED body point (index n−2). With a single fix that
// point would be the sole raw fix — ~now, AHEAD of the delayed icon — so the
// segment would draw IN FRONT of the plane. Likewise during warm-up the icon
// predates all real history, so there is no valid body point behind it.
// The head starts at the last DISPLAYED body point, the newest fix at or
// before the delayed display time; a fix ahead of the icon would draw the
// segment IN FRONT of the plane. During warm-up the icon predates all real
// history, so there is no valid body point behind it.
if (
!flightState._trackedIcao ||
flightState._trailPositions.length < 2 ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
)
return [];
@@ -548,12 +722,20 @@ export function createTracking({
parts.motion._trackedTrailCached() ||
parts.motion._trackedDisplayPosition(flightState._trackedIcao);
if (!head) return [];
// body[n−2] (last displayed body point) → delayed head: runs FORWARD, never a
// backward/reversing segment.
const start =
flightState._trailPositions[
flightState._trailPositions.length - 2
];
// The last body point (a report, or where the icon was drawn a
// moment ago) → the icon. The body is moved on by _trailTick, never
// here: a callback must not add or remove entities.
// No head across a break: a body point more than 150 km away, or
// too long ago or too far to be one path, stays detached; none while
// the aircraft holds at its last point.
const last = trailHeadStartFix(
flightState._trailFixes,
head,
flightState.now(),
flightState._trailBodyCount,
);
if (!last) return [];
const start = last.position;
// Floor the head too (round 2): a grounded tracked contact's DR
// display height is the pre-datum default — without this the last
// segment dives underground while taxiing.
@@ -594,10 +776,10 @@ export function createTracking({
}
/**
* Fire-and-forget optional source history backfill (PRD F2). Trace points are
* stride-thinned to the remaining vertex budget, then spliced strictly older
* than the oldest seeded fix AHEAD of the locally accumulated fine segment,
* capped at TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/
* Fire-and-forget optional source history backfill (PRD F2). Every trace
* point strictly older than the oldest seeded fix is spliced AHEAD of the
* locally accumulated fine segment, each leg its own segment, capped at
* TRAIL_MAX_POINTS (newest kept). Any failure (404/timeout/
* malformed) silently keeps the local-only trail.
* @param {string} icao24 - ICAO hex identifier being tracked.
* @param {number} token - Backfill token captured at request time.
@@ -643,7 +825,13 @@ export function createTracking({
lon = point.longitude;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (!Number.isFinite(t) || t >= oldestFixEpochSec) continue;
parsed.push({ lat, lon, baroAltitudeM: point.baroAltitudeM });
parsed.push({
lat,
lon,
baroAltitudeM: point.baroAltitudeM,
onGround: point.onGround === true,
timeMs: point.observedAtMs,
});
}
if (!parsed.length) return;
@@ -666,39 +854,34 @@ export function createTracking({
)
return;
let older = [];
let lastAltM = null; // carry-forward for ground points whose cell isn't warm yet
for (const { lat, lon, baroAltitudeM } of parsed) {
const baroM =
baroAltitudeM == null ? null : baroAltitudeM + geoidHeight(lat, lon);
let altM = floorAltitudeM(baroM, cachedGroundFloor(lat, lon));
// Ground/no-alt point with an unresolved floor: hold the previous
// waypoint's altitude (continuity — never a dive to a made-up depth).
// Leading points with nothing to carry keep the old low breadcrumb
// sentinel (an arbitrary placeholder, never a reported altitude).
if (altM == null) altM = lastAltM != null ? lastAltM : 50;
lastAltM = altM;
older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM));
}
// Stride-thin the backfill so it plus the live fine segment fit the cap.
const budget = Math.max(
1,
TRAIL_MAX_POINTS - flightState._trailPositions.length,
// Every trace point is kept, each leg its own segment. A 'ground' point
// is at altitude 0, floored at the ground. A point with no altitude is a
// break on both sides: it sits on the ground where the floor is known and
// is skipped otherwise; a skipped point still breaks the line.
const backfill = trailBackfillFixes(
parsed.map(({ lat, lon, baroAltitudeM, onGround, timeMs }) => {
const known = Number.isFinite(baroAltitudeM)
? baroAltitudeM
: onGround
? 0
: null;
const altM = floorAltitudeM(
known == null ? null : known + geoidHeight(lat, lon),
cachedGroundFloor(lat, lon),
);
return {
position:
altM == null ? null : Cesium.Cartesian3.fromDegrees(lon, lat, altM),
timeMs,
nullAltitude: known == null,
};
}),
);
flightState._trailFixes = joinTrailBackfill(
backfill,
flightState._trailFixes,
TRAIL_MAX_POINTS,
);
if (older.length > budget) {
const stride = Math.ceil(older.length / budget);
const thinned = [];
for (let i = 0; i < older.length; i += stride) thinned.push(older[i]);
older = thinned;
}
flightState._trailPositions = older.concat(flightState._trailPositions);
if (flightState._trailPositions.length > TRAIL_MAX_POINTS) {
flightState._trailPositions = flightState._trailPositions.slice(
flightState._trailPositions.length - TRAIL_MAX_POINTS,
);
}
_refreshTrailDisplay();
}
@@ -708,7 +891,9 @@ export function createTracking({
function _clearTrail() {
flightState._trailBackfillToken += 1;
flightState._trailPositions = [];
flightState._trailFixes = [];
flightState._trailRecordPosition = null;
flightState._trailRecordMs = -Infinity;
if (flightState._trail) flightState._trail.clear();
if (
flightState._trailHeadEntity &&
@@ -925,15 +1110,9 @@ export function createTracking({
(CLASS_SCALE_2D[
flightState.records.data.get(flightState._trackedIcao)?.klass
] || 1),
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
// transparent once the STANDALONE tracked model is actually up (ready + shown).
color: new Cesium.CallbackProperty(
() =>
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
? AMBER_TRANSPARENT
: TRACKED_ICON_COLOR,
false,
),
// Solid amber (faded while stale) when the billboard is the visual (zoomed out, 3D off,
// or model still loading); transparent once the STANDALONE tracked model is actually up.
color: new Cesium.CallbackProperty(_trackedIconColor, false),
sizeInMeters: false,
scaleByDistance: new Cesium.NearFarScalar(1000, 3.0, 8000000, 0.5),
alignedAxis: Cesium.Cartesian3.ZERO,
@@ -1156,6 +1335,9 @@ export function createTracking({
_setCockpitContactMode,
_applyCockpitState,
_buildTrackedLabel,
_trackedStaleCue,
_trackedIconColor,
_staleCueTick,
_updateTrackedLabelModel,
_syncTrackedBillboardImage,
_refreshTr3bContact,
@@ -1167,6 +1349,7 @@ export function createTracking({
_syncTracked2dRotation,
_trailFloorPosition,
_appendTrailFix,
_trailTick,
_refreshTrailDisplay,
_startTrail,
_backfillTrail,
+260
View File
@@ -0,0 +1,260 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { TRAIL_MAX_POINTS } from './policy.js';
const MINUTE = 60_000;
const HOUR = 60 * MINUTE;
function services({ trails, floor = () => null } = {}) {
const names = [
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
];
return {
...Object.fromEntries(names.map((name) => [name, {}])),
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
trails,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: floor,
floorAltitudeM: (alt, ground) =>
Number.isFinite(alt) && Number.isFinite(ground)
? Math.max(alt, ground + 1)
: Number.isFinite(alt)
? alt
: Number.isFinite(ground)
? ground + 1
: null,
},
};
}
/** A fake trail that records what draws: segments of two or more points. */
function recordingTrail() {
const calls = [];
return {
last: () =>
(calls[calls.length - 1] ?? []).filter((segment) => segment.length >= 2),
createTrail: () => ({
setSegments(segments) {
calls.push(segments.map((segment) => segment.slice()));
},
setPositions(positions) {
calls.push([positions.slice()]);
},
setVisible() {},
clear() {
calls.push([]);
},
destroy() {},
}),
};
}
function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
const trail = recordingTrail();
const svc = services({ trails: trail, floor });
const flightState = createFlightState({
services: svc,
source: {
label: 'Fixture military aircraft',
async getTrack() {
if (!trace) throw new Error('404');
return { records: trace };
},
},
});
const added = [];
flightState._viewer = {
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove() {},
},
};
flightState._trackedIcao = 'ae0001';
flightState.now = () => nowMs;
flightState._positionHistory.set(
'ae0001',
liveFixes.map((fix) => ({
time: Cesium.JulianDate.fromDate(new Date(fix.timeMs)),
epochMs: fix.timeMs,
position: Cesium.Cartesian3.fromDegrees(fix.lon, fix.lat, 9_000),
})),
);
const tracking = createTracking({
flightState,
services: svc,
parts: {
motion: {
_isTrackWarmingUp: () => false,
_trackedTrailCached: () => head ?? null,
_trackedDisplayPosition: () => head ?? null,
_trackedModelCenterWorld: () => null,
_trackedModelEnvelopeM: () => null,
},
},
layer: {},
});
const headPositions = () =>
added
.find((definition) =>
String(definition.id).startsWith('gev-trail:mil-head-'),
)
.polyline.positions.getValue();
return { trail, tracking, flightState, headPositions };
}
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
/** readsb-shaped trace points as the military source parses them. */
function point(timeMs, lat, lon, baroAltitudeM = 9_000, onGround = false) {
return {
observedAtMs: timeMs,
latitude: lat,
longitude: lon,
baroAltitudeM,
onGround,
};
}
function leg(startMs, lat, lon, count) {
return Array.from({ length: count }, (_, i) =>
point(startMs + i * MINUTE, lat, lon + i * 0.12),
);
}
test('a multi-leg military trace becomes separate segments with no line across a gap', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const first = leg(t0, 36, -115, 5);
const second = leg(t0 + 5 * MINUTE + 3 * HOUR, 35, -106, 5);
const third = leg(t0 + 10 * MINUTE + 5 * HOUR, 38, -77, 5);
const trace = [...first, ...second, ...third];
const liveStart = t0 + 15 * MINUTE + 5 * HOUR;
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: liveStart + i * MINUTE,
lat: 38,
lon: -77 + 0.6 + i * 0.12,
}));
const { trail, flightState, tracking } = trackedHarness({
liveFixes,
trace,
nowMs: liveStart + 3 * MINUTE,
});
tracking._startTrail('ae0001');
await settle();
assert.equal(flightState._trailFixes.length, trace.length + 3);
assert.deepEqual(
trail.last().map((segment) => segment.length),
[5, 5, 8],
);
});
test('a military trace point with no altitude breaks the line and is never given a made-up height', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const trace = leg(t0, 35, -106, 7);
trace[3] = point(trace[3].observedAtMs, 35, -105.64, null);
const liveFixes = [{ timeMs: t0 + 7 * MINUTE, lat: 35, lon: -105.16 }];
const { trail, flightState, tracking } = trackedHarness({
liveFixes,
trace,
nowMs: t0 + 9 * MINUTE,
});
tracking._startTrail('ae0001');
await settle();
// Skipped (no floor known): 3 + 3 + the live fix drawn.
assert.equal(flightState._trailFixes.length, trace.length - 1 + 1);
assert.deepEqual(
trail.last().map((segment) => segment.length),
[3, 4],
);
for (const fix of flightState._trailFixes) {
const height = Cesium.Cartographic.fromCartesian(fix.position).height;
assert.ok(Math.abs(height - 9_000) < 1, `no invented height: ${height}`);
}
});
test('a military ground point is drawn on the ground and stays joined', async () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
// Taxiing: 'ground' points a few hundred metres apart, one minute apart.
const trace = Array.from({ length: 4 }, (_, i) =>
point(t0 + i * MINUTE, 35, -106.6 + i * 0.004, null, true),
);
const liveFixes = [{ timeMs: t0 + 4 * MINUTE, lat: 35, lon: -106.584 }];
const { trail, flightState, tracking } = trackedHarness({
liveFixes,
trace,
nowMs: t0 + 6 * MINUTE,
floor: () => 1_590,
});
tracking._startTrail('ae0001');
await settle();
assert.deepEqual(
trail.last().map((segment) => segment.length),
[5],
);
const height = Cesium.Cartographic.fromCartesian(
flightState._trailFixes[0].position,
).height;
assert.ok(Math.abs(height - 1_591) < 1);
});
test('the military head is drawn to a nearby aircraft and not to one more than 150 km away', () => {
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const liveFixes = [0, 1, 2].map((i) => ({
timeMs: t0 + i * MINUTE,
lat: 35,
lon: -106 + i * 0.12,
}));
const near = Cesium.Cartesian3.fromDegrees(-105.7, 35, 9_000);
const joined = trackedHarness({
liveFixes,
nowMs: t0 + 3 * MINUTE,
head: near,
});
joined.tracking._startTrail('ae0001');
assert.equal(joined.headPositions().length, 2);
const far = Cesium.Cartesian3.fromDegrees(-103, 35, 9_000);
const detached = trackedHarness({
liveFixes,
nowMs: t0 + 3 * MINUTE,
head: far,
});
detached.tracking._startTrail('ae0001');
assert.deepEqual(detached.headPositions(), []);
});
test('a full 24 h military trace fits within TRAIL_MAX_POINTS without thinning', async () => {
const day = 24 * 60;
const t0 = Date.UTC(2026, 10, 8, 0, 0);
const trace = leg(t0, 20, -150, day);
const liveStart = t0 + day * MINUTE;
const liveFixes = [{ timeMs: liveStart, lat: 20, lon: -150 + day * 0.12 }];
const { flightState, tracking } = trackedHarness({
liveFixes,
trace,
nowMs: liveStart + MINUTE,
});
tracking._startTrail('ae0001');
await settle();
assert.ok(TRAIL_MAX_POINTS >= day + 500);
assert.equal(flightState._trailFixes.length, day + 1);
});
+717
View File
@@ -0,0 +1,717 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createMotion } from './motion.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
// A tracked military contact's trail between reports is the path its icon
// was drawn along, recorded from the real display path frame by frame.
const SEC = 1000;
const ICAO = '00a004';
const T0 = Date.UTC(2026, 10, 9, 21, 0);
function fix(timeMs, lat, lon, heightM, velocity, track) {
return {
time: Cesium.JulianDate.fromDate(new Date(timeMs)),
epochMs: timeMs,
position: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
velocity,
track,
};
}
function services(trail, ground) {
const names = [
'picking',
'sprites',
'aircraftPresentation',
'camera',
'militaryRegistry',
'labels',
'meshFloor',
'focus',
'readout',
'context',
'render',
'recession',
];
return {
...Object.fromEntries(names.map((name) => [name, {}])),
aircraftPresentation: {
isTr3b: () => false,
tr3bTypeLabel: (id, label) => label,
},
focus: {
nearFarScalarValueAtDistance: () => 1,
clearFocusTarget() {},
publishFocusTargetFromCachedPosition() {},
},
groundSnap: { createGroundSnap: () => ({ clear() {} }) },
trails: trail,
geoid: { ensureGeoidReady: async () => {}, geoidHeight: () => 0 },
groundFloor: {
resolveGroundFloorCellsBounded: async () => {},
cachedGroundFloor: ground,
floorAltitudeM: (alt, g) =>
Number.isFinite(g) && Number.isFinite(alt)
? Math.max(alt, g + 1.5)
: alt,
},
};
}
/**
* Real motion, real display position and real tracking over one contact.
* `frame()` runs one rendered frame: the layer's preRender work, then the
* head callback, as Cesium does.
*/
function harness({ fixes, info, nowMs, ground = () => null }) {
const segmentsCalls = [];
let inHead = false;
const trail = {
createTrail: () => ({
setSegments(segments) {
assert.ok(
!inHead,
'the trail body was rebuilt inside the head callback',
);
segmentsCalls.push(segments.map((segment) => segment.slice()));
},
setPositions(positions) {
assert.ok(
!inHead,
'the trail body was rebuilt inside the head callback',
);
segmentsCalls.push([positions.slice()]);
},
setVisible() {},
clear() {},
destroy() {},
}),
};
const svc = services(trail, ground);
const flightState = createFlightState({ services: svc, source: {} });
flightState.records.data.set(ICAO, info);
let frameNumber = 0;
const added = [];
let entityChanges = 0;
flightState._viewer = {
isDestroyed: () => false,
scene: {
frameState: {
get frameNumber() {
return frameNumber;
},
},
},
entities: {
add(definition) {
entityChanges += 1;
added.push(definition);
return definition;
},
remove() {
entityChanges += 1;
},
},
};
flightState._trackedIcao = ICAO;
let clock = nowMs;
flightState.now = () => clock;
flightState._positionHistory.set(ICAO, fixes);
const parts = {
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
queries: {
_toCleanText: (value) => (typeof value === 'string' ? value.trim() : ''),
_formatAltitude: (ft) => `${ft} ft`,
},
};
parts.motion = createMotion({ flightState, services: svc, parts });
const tracking = createTracking({
flightState,
services: svc,
parts,
layer: {},
});
parts.tracking = tracking;
const realDateNow = Date.now;
Date.now = () => clock;
const headEntity = () =>
added.find((definition) =>
String(definition.id).startsWith('gev-trail:mil-head-'),
);
const head = () => {
const before = entityChanges;
inHead = true;
try {
return headEntity().polyline.positions.getValue();
} finally {
inHead = false;
assert.equal(
entityChanges,
before,
'the head callback added or removed an entity',
);
}
};
/** Drawn icon positions, one per frame. */
const drawn = [];
const frame = ({ readHead = true } = {}) => {
frameNumber += 1;
tracking._trailTick();
const icon = parts.motion._trackedDisplayPosition(ICAO);
if (icon) drawn.push(Cesium.Cartesian3.clone(icon));
if (readHead) head();
};
const run = (toMs, { frameMs = 100, readHead = true } = {}) => {
while (clock < toMs) {
clock = Math.min(toMs, clock + frameMs);
frame({ readHead });
}
};
return {
flightState,
tracking,
motion: parts.motion,
head,
drawn,
run,
body: () => segmentsCalls.at(-1) ?? [],
bodyPoints: () => (segmentsCalls.at(-1) ?? []).flat(),
restore: () => {
Date.now = realDateNow;
},
};
}
/** Distance from p to the nearest point of a polyline. */
function distanceToPath(p, path) {
let best = Infinity;
const ab = new Cesium.Cartesian3();
const ap = new Cesium.Cartesian3();
const closest = new Cesium.Cartesian3();
if (path.length === 1) return Cesium.Cartesian3.distance(p, path[0]);
for (let i = 1; i < path.length; i++) {
Cesium.Cartesian3.subtract(path[i], path[i - 1], ab);
Cesium.Cartesian3.subtract(p, path[i - 1], ap);
const len2 = Cesium.Cartesian3.magnitudeSquared(ab);
const t =
len2 > 0
? Math.max(0, Math.min(1, Cesium.Cartesian3.dot(ap, ab) / len2))
: 0;
Cesium.Cartesian3.add(
path[i - 1],
Cesium.Cartesian3.multiplyByScalar(ab, t, closest),
closest,
);
best = Math.min(best, Cesium.Cartesian3.distance(p, closest));
}
return best;
}
/** No vertex turns the line back sharper than 120° over a short step. */
function assertNoSpur(line, label) {
const u = new Cesium.Cartesian3();
const v = new Cesium.Cartesian3();
for (let i = 1; i < line.length - 1; i++) {
Cesium.Cartesian3.subtract(line[i], line[i - 1], u);
Cesium.Cartesian3.subtract(line[i + 1], line[i], v);
const lu = Cesium.Cartesian3.magnitude(u);
const lv = Cesium.Cartesian3.magnitude(v);
if (!(lu > 0 && lv > 0) || Math.min(lu, lv) > 500) continue;
const cos = Cesium.Cartesian3.dot(u, v) / (lu * lv);
assert.ok(
cos >= -0.5,
`${label}: spur at vertex ${i} of ${line.length} (turn ${(
(Math.acos(cos) * 180) /
Math.PI
).toFixed(0)}°)`,
);
}
}
const indexOfPoint = (line, p) =>
line.findIndex((q) => Cesium.Cartesian3.distance(p, q) < 0.01);
// A departing jet: four northbound climb reports, then a left turn through
// west to south with no report while the icon flies it.
function departure() {
const fixes = [
fix(T0, 37.6329, -122.3661, 213, 85, 8),
fix(T0 + 30 * SEC, 37.6542, -122.3616, 495, 95, 0),
fix(T0 + 60 * SEC, 37.6813, -122.3615, 808, 104, 350),
fix(T0 + 90 * SEC, 37.7066, -122.3755, 1257, 112, 340),
];
const info = {
altitudeFt: 4_124,
renderAltitudeM: 1257,
rawLat: 37.7066,
rawLon: -122.3755,
speedMps: 112,
track: 340,
turnRateDps: -2,
onGround: false,
wasAirborne: true,
lastContactEpochMs: T0 + 200 * SEC,
};
return { fixes, info };
}
test('military: a report newer than the display time arrives mid-turn, and the trail between the reports stays on the drawn arc', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
// 40 s of turn with no new report: the icon flies the arc.
h.run(start + 40 * SEC);
const arc = h.drawn.slice();
// The next report is where the plane really was 60 s after the last one,
// still ahead of the display time (normal 30 s delay, slow feed). The icon
// now interpolates the straight line between the two reports and is eased
// onto it.
const at60 = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 150 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(at60);
const report = fix(
T0 + 150 * SEC,
Cesium.Math.toDegrees(c.latitude),
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
220,
);
fixes.push(report);
info.track = 220;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// The display passes the new report.
h.run(start + 75 * SEC);
const line = h.bodyPoints();
const from = indexOfPoint(line, fixes[3].position);
const to = indexOfPoint(line, report.position);
assert.ok(from >= 0 && to > from, 'both reports are on the trail');
const between = line.slice(from, to + 1);
// Every vertex between the reports is where the icon was drawn...
const drawnPath = [fixes[3].position, ...h.drawn, report.position];
for (const vertex of between) {
const off = distanceToPath(vertex, drawnPath);
assert.ok(
off < 50,
`trail vertex ${off.toFixed(0)} m off the drawn path`,
);
}
// ...and the arc the icon flew is still there: no straight chord. (The
// arc strays far from the chord, so a chord would fail this.)
const chord = [fixes[3].position, report.position];
assert.ok(Math.max(...arc.map((p) => distanceToPath(p, chord))) > 300);
// The last 10 s of the arc are exempt: the correction pulled the icon back
// over them, and keeping them would fold the line back on itself.
for (const point of arc.slice(0, -100)) {
const off = distanceToPath(point, between);
assert.ok(off < 50, `drawn arc point ${off.toFixed(0)} m from the trail`);
}
assertNoSpur(line, 'trail');
assertNoSpur(h.head(), 'head');
} finally {
h.restore();
}
});
test('military: a report the display already passed replaces the guess drawn after it, with no spike', () => {
const { fixes, info } = departure();
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
h.run(start + 40 * SEC);
const displayMs = T0 + 130 * SEC;
// A report for 10 s before the display time, 400 m inside the drawn arc.
const guess = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(T0 + 120 * SEC)),
);
const c = Cesium.Cartographic.fromCartesian(guess);
const report = fix(
T0 + 120 * SEC,
Cesium.Math.toDegrees(c.latitude) - 400 / 111_320,
Cesium.Math.toDegrees(c.longitude),
c.height,
112,
250,
);
fixes.push(report);
info.track = 250;
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
h.run(start + 55 * SEC);
const recorded = h.flightState._trailFixes.filter((entry) => entry.drawn);
// Nothing recorded between the report and the end of the ease.
assert.deepEqual(
recorded
.filter(
(entry) =>
entry.timeMs > report.epochMs && entry.timeMs < displayMs + 900,
)
.map((entry) => entry.timeMs - T0),
[],
);
const line = h.bodyPoints();
assert.ok(indexOfPoint(line, report.position) >= 0);
assertNoSpur(line, 'trail');
} finally {
h.restore();
}
});
test('military: a history report at an invented height is seeded with no position, and nothing is recorded next to it', () => {
const { fixes, info } = departure();
fixes[3].inventedHeight = true;
const start = T0 + 90 * SEC + RENDER_DELAY_SEC * SEC;
const h = harness({ fixes, info, nowMs: start });
try {
h.tracking._startTrail(ICAO);
const seeded = h.flightState._trailFixes.find(
(entry) => entry.timeMs === fixes[3].epochMs,
);
assert.equal(seeded.position, null);
assert.equal(seeded.nullAltitude, true);
h.run(start + 10 * SEC);
assert.equal(
h.flightState._trailFixes.filter((entry) => entry.drawn).length,
0,
);
} finally {
h.restore();
}
});
// A turboprop at FL210 flying east out of receiver coverage: its last
// position is at T0 + 30 s, and contact goes on for four more minutes.
function outOfCoverage() {
const fixes = [
fix(T0, 43, -108.1, 6_400, 140, 90),
fix(T0 + 30 * SEC, 43, -108.05, 6_400, 140, 90),
];
const info = {
altitudeFt: 21_000,
renderAltitudeM: 6_400,
rawLat: 43,
rawLon: -108.05,
speedMps: 140,
track: 90,
callsign: 'TEST7',
turnRateDps: 0,
onGround: false,
wasAirborne: true,
lastContactEpochMs: T0 + 30 * SEC + 240 * SEC,
};
return { fixes, info };
}
/** Display time (ms) `afterSec` past the last report. */
const pastReport = (afterSec) =>
T0 + 30 * SEC + RENDER_DELAY_SEC * SEC + afterSec * SEC;
test('military: a plane that stops reporting keeps moving dimmed as STALE from its first missed update, then stops as SIGNAL LOST', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(30));
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: '',
dimmed: false,
});
assert.equal(h.tracking._trackedIconColor().alpha, 1);
// The first missed update.
h.flightState.records.missingPolls.set(ICAO, 1);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.match(
h.tracking._buildTrackedLabel(h.flightState.records.data.get(ICAO), ICAO),
/STALE/,
);
// Drawn with the fleet's stale fade.
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
// Still moving well past 90 s.
h.run(pastReport(200));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-11)) > 100,
);
// The coast ends 300 s past the report; the plane stops there.
h.run(pastReport(310));
const recorded = h.flightState._trailFixes.filter((e) => e.drawn).length;
h.run(pastReport(330));
assert.ok(
Cesium.Cartesian3.distance(h.drawn.at(-1), h.drawn.at(-50)) < 0.01,
);
assert.equal(
h.flightState._trailFixes.filter((e) => e.drawn).length,
recorded,
'the trail kept recording a stopped plane',
);
// 330 s of display past the report is 330 s + the display delay of wall time.
const minutes = Math.floor((330 + RENDER_DELAY_SEC) / 60);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: `SIGNAL LOST · ${minutes} min`,
dimmed: true,
});
assert.match(
h.tracking._buildTrackedLabel(h.flightState.records.data.get(ICAO), ICAO),
new RegExp(`SIGNAL LOST · ${minutes} min`),
);
} finally {
h.restore();
}
});
test('military: a plane held at its last report shows SIGNAL LOST in seconds under a minute', () => {
// Its last report is 100 m above a known ground height: it holds there.
const { fixes, info } = outOfCoverage();
const h = harness({
fixes,
info,
nowMs: pastReport(-5),
ground: () => 6_300,
});
try {
h.tracking._startTrail(ICAO);
h.flightState.records.missingPolls.set(ICAO, 1);
h.run(pastReport(10));
assert.ok(10 + RENDER_DELAY_SEC < 60);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: `SIGNAL LOST · ${10 + RENDER_DELAY_SEC} s`,
dimmed: true,
});
} finally {
h.restore();
}
});
test('military: a report arriving 200 s into a coast: the plane eases onto it and the trail drops what was drawn after it', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(200));
// Heard again: the report is for 10 s before the display time, 2 km north
// of where the coast put it.
const at = T0 + 30 * SEC + 190 * SEC;
const guess = h.motion._deadReckon(
ICAO,
new Cesium.Cartesian3(),
Cesium.JulianDate.fromDate(new Date(at)),
);
const c = Cesium.Cartographic.fromCartesian(guess);
const report = fix(
at,
Cesium.Math.toDegrees(c.latitude) + 2_000 / 111_320,
Cesium.Math.toDegrees(c.longitude),
c.height,
140,
90,
);
fixes.push(report);
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
assert.deepEqual(
h.flightState._trailFixes.filter(
(e) => e.drawn && e.timeMs > report.epochMs,
),
[],
);
const from = h.drawn.length;
h.run(pastReport(203));
const after = h.drawn.slice(from - 1);
for (let i = 1; i < after.length; i++)
assert.ok(
Cesium.Cartesian3.distance(after[i], after[i - 1]) < 400,
'the plane jumped instead of easing',
);
// Eased onto the path from the report: 13 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(after.at(-1), report.position);
assert.ok(
Math.abs(off - 140 * 13) < 150,
`${off.toFixed(0)} m from the report`,
);
} finally {
h.restore();
}
});
test('military: a tracked plane that stops reporting: STALE from the first missed poll, SIGNAL LOST after the five-minute coast, kept at 9 min, removed at 10 min', () => {
const { fixes, info } = outOfCoverage();
const fixMs = fixes.at(-1).epochMs;
// Contact stops with the position: the plane left coverage.
info.lastContactEpochMs = fixMs;
info.newestFixMs = fixMs;
const h = harness({ fixes, info, nowMs: fixMs + 5 * SEC });
try {
h.tracking._startTrail(ICAO);
const records = h.flightState.records;
const polls = new Map();
let removedAtSec = null;
// A poll every 10 s that lists the plane without a position.
for (let afterSec = 10; afterSec <= 660; afterSec += 10) {
h.run(fixMs + afterSec * SEC, { frameMs: 500, readHead: false });
const result = records.absence(ICAO, {
complete: true,
retainIds: new Set([ICAO]),
likelyLanded: false,
tracked: true,
});
if (result === 'remove') {
removedAtSec = afterSec;
break;
}
polls.set(afterSec, {
cue: h.tracking._trackedStaleCue(ICAO),
drawn: Cesium.Cartesian3.clone(h.drawn.at(-1)),
});
}
// Wall time when the display reaches the end of the coast.
const coastEndSec = 300 + RENDER_DELAY_SEC;
for (const [afterSec, { cue }] of polls) {
if (afterSec <= coastEndSec) {
assert.deepEqual(cue, { text: 'STALE', dimmed: true }, `${afterSec} s`);
} else {
assert.deepEqual(
cue,
{
text: `SIGNAL LOST · ${Math.floor(afterSec / 60)} min`,
dimmed: true,
},
`${afterSec} s`,
);
}
}
const moved = (a, b) =>
Cesium.Cartesian3.distance(polls.get(a).drawn, polls.get(b).drawn);
// Moving through the coast, still at its last speed at four minutes.
assert.ok(Math.abs(moved(230, 240) - 140 * 10) < 20);
// Stopped once the coast has ended.
const after = Math.ceil(coastEndSec / 10) * 10;
assert.ok(moved(after, 540) < 0.01);
assert.equal(polls.get(300).cue.text, 'STALE');
assert.deepEqual(polls.get(540).cue, {
text: 'SIGNAL LOST · 9 min',
dimmed: true,
});
assert.equal(removedAtSec, 600);
} finally {
h.restore();
}
});
test('military: a repeated old fix counts as a missed update for the tracked plane', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(-2));
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: '',
dimmed: false,
});
// The feed re-sends the last position: its fix time did not advance.
h.flightState.records.fixRepeated.add(ICAO);
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
}
});
test('military: a stalled feed dims the tracked plane as STALE', () => {
const { fixes, info } = outOfCoverage();
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(-2));
// The whole feed is backing off: no poll counts a miss, and no newer
// position is coming in.
h.flightState.feed._backoff = true;
assert.deepEqual(h.tracking._trackedStaleCue(ICAO), {
text: 'STALE',
dimmed: true,
});
assert.equal(h.tracking._trackedIconColor().alpha, STALE_ALPHA);
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
} finally {
h.restore();
}
});
test('military: a report arriving after the plane has stopped: it eases in with no spur, and the trail keeps everything up to the stop', () => {
const { fixes, info } = outOfCoverage();
info.lastContactEpochMs = fixes.at(-1).epochMs;
const h = harness({ fixes, info, nowMs: pastReport(-5) });
try {
h.tracking._startTrail(ICAO);
h.run(pastReport(360));
const stop = Cesium.Cartesian3.clone(h.drawn.at(-1));
assert.ok(Cesium.Cartesian3.distance(stop, h.drawn.at(-100)) < 0.01);
const kept = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => Cesium.Cartesian3.clone(e.position));
// The thinned straight coast, recorded up to where the plane stopped.
assert.ok(kept.length >= 2);
assert.ok(Cesium.Cartesian3.distance(kept.at(-1), stop) < 300);
// Heard again, for 20 s before the display time: the plane flew on, a
// little north of its old heading.
const at = T0 + 30 * SEC + 340 * SEC;
const lonDeg =
-108.05 + (140 * 340) / (111_320 * Math.cos((43 * Math.PI) / 180));
const report = fix(at, 43 + 1_000 / 111_320, lonDeg, 6_400, 140, 90);
fixes.push(report);
h.tracking._appendTrailFix(
Cesium.Cartesian3.clone(report.position),
report.epochMs,
);
// Nothing was recorded after the stop, so nothing is dropped.
const after = h.flightState._trailFixes
.filter((e) => e.drawn)
.map((e) => e.position);
assert.equal(after.length, kept.length);
kept.forEach((p, i) =>
assert.ok(Cesium.Cartesian3.distance(p, after[i]) < 0.01),
);
const from = h.drawn.length;
h.run(pastReport(365));
const eased = h.drawn.slice(from - 1);
const jump = Cesium.Cartesian3.distance(eased[0], eased.at(-1));
for (let i = 1; i < eased.length; i++)
assert.ok(
Cesium.Cartesian3.distance(eased[i], eased[i - 1]) < jump / 2,
'the plane jumped instead of easing',
);
// On the path from the report: 25 s on from it at 140 m/s.
const off = Cesium.Cartesian3.distance(eased.at(-1), report.position);
assert.ok(Math.abs(off - 140 * 25) < 150, `${off.toFixed(0)} m`);
assertNoSpur(h.bodyPoints(), 'trail');
assertNoSpur(h.head(), 'head');
assert.ok(indexOfPoint(h.bodyPoints(), report.position) >= 0);
} finally {
h.restore();
}
});
+236
View File
@@ -0,0 +1,236 @@
// Event cards on the globe: a picture, the headline in two lines, and "age ·
// sources · sides", with the severity colour down the left edge and the
// event's marker as a badge on the picture. Painted on a canvas and handed to
// the world overlay as a thumbnail entry, so the overlay places them, keeps
// them apart and draws their leader to the marker, as it does CCTV cards.
//
// The picture is the publisher's own (hotlinked, never copied, credited on
// the card); until it loads, or without one, the card shows a tile in the
// severity colour with the category icon.
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import { NEWS_SEVERITY } from './model.js';
import { paintMarker } from './sprites.js';
/** Card size in CSS pixels. */
export const CARD_W = 168;
export const CARD_H = 136;
const PAD = 4;
const PIC_H = 84;
const EDGE = 3;
const SCALE = 2; // canvas pixels per CSS pixel
const TITLE_FONT = '600 11px Inter, "Noto Sans Arabic", system-ui, sans-serif';
const META_FONT = '9px "JetBrains Mono", "Noto Sans Arabic", monospace';
const CREDIT_FONT = '8px Inter, "Noto Sans Arabic", system-ui, sans-serif';
// The map shows about ten cards plus the clicked one; a few more stay ready
// for a pan back. The least recently drawn card goes, and its picture with it.
export const MAX_CARDS = 24;
const pictures = new Map(); // url → {image, state: 'loading'|'ok'|'failed', waiters}
const cards = new Map(); // event id → {canvas, key, view, look, pic}, oldest first
/** Forget a picture no kept card shows any more. */
function releasePicture(url) {
if (!url || [...cards.values()].some((card) => card.view.image === url))
return;
const entry = pictures.get(url);
if (!entry) return;
entry.waiters.clear();
entry.image.onload = entry.image.onerror = null;
pictures.delete(url);
}
function picture(url, onLoad) {
let entry = pictures.get(url);
if (!entry) {
const image = new Image();
// No referrer: the publisher sees a plain image request, as from a link preview.
image.referrerPolicy = 'no-referrer';
image.decoding = 'async';
entry = { image, state: 'loading', waiters: new Set() };
pictures.set(url, entry);
image.onload = () => {
entry.state = 'ok';
for (const done of entry.waiters) done();
entry.waiters.clear();
};
image.onerror = () => {
entry.state = 'failed';
entry.waiters.clear();
};
image.src = url;
}
if (entry.state === 'loading' && onLoad) entry.waiters.add(onLoad);
return entry;
}
function roundRect(ctx, x, y, w, h, r) {
ctx.beginPath();
ctx.moveTo(x + r, y);
ctx.arcTo(x + w, y, x + w, y + h, r);
ctx.arcTo(x + w, y + h, x, y + h, r);
ctx.arcTo(x, y + h, x, y, r);
ctx.arcTo(x, y, x + w, y, r);
ctx.closePath();
}
/** `text` in at most `lines` lines of `width`, the last cut with an ellipsis. */
export function wrapLines(ctx, text, width, lines) {
const words = String(text || '')
.split(/\s+/)
.filter(Boolean);
const out = [];
let line = '';
for (let i = 0; i < words.length; i++) {
const next = line ? `${line} ${words[i]}` : words[i];
if (ctx.measureText(next).width <= width || !line) {
line = next;
continue;
}
out.push(line);
line = words[i];
if (out.length === lines - 1) {
line = words.slice(i).join(' ');
break;
}
}
if (line) out.push(line);
const last = out.length - 1;
if (last >= 0 && ctx.measureText(out[last]).width > width) {
let cut = out[last];
while (cut && ctx.measureText(`${cut}…`).width > width)
cut = cut.slice(0, -1);
out[last] = `${cut.trimEnd()}…`;
}
return out.slice(0, lines);
}
/** Cover-fit an image into a box. */
function drawCover(ctx, image, x, y, w, h) {
const iw = image.naturalWidth || image.width;
const ih = image.naturalHeight || image.height;
if (!iw || !ih) return;
const s = Math.max(w / iw, h / ih);
const sw = w / s;
const sh = h / s;
ctx.drawImage(image, (iw - sw) / 2, (ih - sh) / 2, sw, sh, x, y, w, h);
}
function paint(canvas, view, look, pic) {
const ctx = canvas.getContext('2d');
ctx.setTransform(SCALE, 0, 0, SCALE, 0, 0);
ctx.clearRect(0, 0, CARD_W, CARD_H);
const color = (NEWS_SEVERITY[look.severity] || NEWS_SEVERITY[0]).color;
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
ctx.fillStyle = WORLD_OVERLAY_STYLE.selectedBackground;
ctx.fill();
ctx.strokeStyle = WORLD_OVERLAY_STYLE.border;
ctx.lineWidth = 1;
ctx.stroke();
// Severity down the left edge.
ctx.save();
roundRect(ctx, 0.5, 0.5, CARD_W - 1, CARD_H - 1, WORLD_OVERLAY_STYLE.radius);
ctx.clip();
ctx.fillStyle = color;
ctx.fillRect(0, 0, EDGE, CARD_H);
ctx.restore();
const px = PAD + EDGE;
const pw = CARD_W - px - PAD;
ctx.save();
roundRect(ctx, px, PAD, pw, PIC_H, 3);
ctx.clip();
if (pic?.state === 'ok') {
try {
drawCover(ctx, pic.image, px, PAD, pw, PIC_H);
} catch {
pic.state = 'failed';
}
}
if (pic?.state !== 'ok') {
// No picture: a plain glass tile with the event's marker.
ctx.fillStyle = WORLD_OVERLAY_STYLE.background;
ctx.fillRect(px, PAD, pw, PIC_H);
ctx.fillStyle = 'rgba(255, 255, 255, 0.04)';
ctx.fillRect(px, PAD, pw, PIC_H);
paintMarker(ctx, look, px + pw / 2, PAD + PIC_H / 2, 34);
}
ctx.restore();
// The event's marker as a badge, so the card reads with the map.
if (pic?.state === 'ok') paintMarker(ctx, look, px + 13, PAD + 13, 18);
// The picture's publisher, always named on it.
if (pic?.state === 'ok' && view.credit) {
ctx.font = CREDIT_FONT;
const w = Math.min(pw - 30, ctx.measureText(view.credit).width + 8);
ctx.fillStyle = 'rgba(0, 0, 0, 0.6)';
ctx.fillRect(px + pw - w, PAD + PIC_H - 12, w, 12);
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
ctx.textBaseline = 'middle';
ctx.fillText(
wrapLines(ctx, view.credit, w - 8, 1)[0] || '',
px + pw - w + 4,
PAD + PIC_H - 6,
);
}
ctx.textBaseline = 'alphabetic';
ctx.fillStyle = WORLD_OVERLAY_STYLE.title;
ctx.font = TITLE_FONT;
wrapLines(ctx, view.title, pw, 2).forEach((line, i) =>
ctx.fillText(line, px, PAD + PIC_H + 14 + i * 13),
);
ctx.fillStyle = WORLD_OVERLAY_STYLE.detail;
ctx.font = META_FONT;
ctx.fillText(wrapLines(ctx, view.meta, pw, 1)[0] || '', px, CARD_H - PAD - 2);
}
/**
* The canvas of an event's card, one per event: a change in what it shows
* (the age in its meta line ticks by the minute) repaints the same canvas.
* `onChange` runs when its picture arrives and the canvas has been repainted
* (ask the scene for a frame).
* @returns {HTMLCanvasElement|null} null where there is no canvas
*/
export function eventCard(id, view, look, onChange) {
const key = `${look.severity}|${look.category}|${look.rim}|${view.image || ''}|${view.credit || ''}|${view.title}|${view.meta}`;
let card = cards.get(id);
if (card) {
// Most recently drawn last.
cards.delete(id);
cards.set(id, card);
if (card.key === key) return card.canvas;
} else {
const canvas = globalThis.document?.createElement?.('canvas');
if (
!canvas?.getContext?.('2d') ||
typeof globalThis.Path2D !== 'function' ||
typeof globalThis.Image !== 'function'
)
return null;
canvas.width = CARD_W * SCALE;
canvas.height = CARD_H * SCALE;
card = { canvas, key: null, view: {}, look, pic: null };
cards.set(id, card);
while (cards.size > MAX_CARDS) {
const [oldest, gone] = cards.entries().next().value;
cards.delete(oldest);
releasePicture(gone.view.image);
}
}
const previous = card.view.image;
card.key = key;
card.view = view;
card.look = look;
const shown = card;
card.pic = view.image
? picture(view.image, () => {
if (cards.get(id) !== shown || shown.view.image !== view.image) return;
paint(shown.canvas, shown.view, shown.look, shown.pic);
onChange?.();
})
: null;
if (previous && previous !== view.image) releasePicture(previous);
paint(card.canvas, view, look, card.pic);
return card.canvas;
}
+120
View File
@@ -0,0 +1,120 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MAX_CARDS, eventCard } from './cards.js';
const look = { severity: 3, category: 'strike', rim: 'confirmed', size: 20 };
const view = (extra = {}) => ({
title: 'Strike on Kharkiv',
meta: '10 min · 6 sources · UA, RU',
image: 'https://a.test/p.jpg',
credit: 'A',
...extra,
});
// Node has no canvas: a 2D context that accepts every call, and an Image that
// records what was asked for.
function fakeBrowser(t) {
const saved = {
document: globalThis.document,
Path2D: globalThis.Path2D,
Image: globalThis.Image,
};
const images = [];
const ctx = new Proxy(
{},
{
get: (_target, name) =>
name === 'measureText'
? (text) => ({ width: String(text).length * 5 })
: name === 'createLinearGradient'
? () => ({ addColorStop() {} })
: () => {},
set: () => true,
},
);
let canvases = 0;
globalThis.document = {
createElement: () => {
canvases++;
return { getContext: () => ctx };
},
};
globalThis.Path2D = class {};
globalThis.Image = class {
constructor() {
images.push(this);
}
};
t.after(() => {
for (const [name, value] of Object.entries(saved))
if (value === undefined) delete globalThis[name];
else globalThis[name] = value;
});
return { images, canvases: () => canvases };
}
test('a card keeps one canvas per event while its age ticks', (t) => {
const browser = fakeBrowser(t);
const first = eventCard('ev-a', view(), look);
assert.ok(first);
// The meta line's minute-level age changes: the same canvas, repainted.
const later = eventCard('ev-a', view({ meta: '11 min · 6 sources' }), look);
assert.equal(later, first);
assert.equal(browser.canvases(), 1);
// One picture request for the event, however often it is drawn.
assert.equal(browser.images.length, 1);
// Its picture arriving repaints and asks for a frame once; a card with no
// picture never does.
let frames = 0;
const pictured = eventCard(
'ev-b',
view({ image: 'https://b.test/p.jpg' }),
look,
() => frames++,
);
assert.ok(pictured);
browser.images.at(-1).onload();
assert.equal(frames, 1);
assert.ok(eventCard('ev-c', view({ image: null }), look));
});
test('the card cache is bounded and evicts pictures with their cards', (t) => {
const browser = fakeBrowser(t);
const kept = eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look);
for (let i = 0; i < MAX_CARDS * 3; i++) {
eventCard(`ev-${i}`, view({ image: `https://p.test/${i}.jpg` }), look);
// A card drawn every frame stays: the least recently drawn goes first.
assert.equal(
eventCard('keep', view({ image: 'https://k.test/0.jpg' }), look),
kept,
);
}
const requested = browser.images.length;
// The first event was evicted with its picture: drawing it again paints a
// new canvas and asks for the picture anew.
const again = eventCard(
'ev-0',
view({ image: 'https://p.test/0.jpg' }),
look,
);
assert.ok(again);
assert.equal(browser.images.length, requested + 1);
// Evicted pictures are let go: their load handlers are cleared.
assert.equal(browser.images[1].onload, null);
// The recent ones are still cached.
const recent = MAX_CARDS * 3 - 1;
eventCard(
`ev-${recent}`,
view({ image: `https://p.test/${recent}.jpg` }),
look,
);
assert.equal(browser.images.length, requested + 1);
});
test('without a canvas no card is made and nothing is cached', (t) => {
fakeBrowser(t);
globalThis.document = { createElement: () => ({ getContext: () => null }) };
assert.equal(eventCard('none', view(), look), null);
globalThis.document = undefined;
assert.equal(eventCard('none', view(), look), null);
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+826
View File
@@ -0,0 +1,826 @@
// Pure presentation model for the news layer: severity, category glyphs,
// attestation, marker looks and placement, the feed's filters and paging, and
// the event cards the News panel and the globe show. No Cesium, no DOM.
import { getLocale, msg, t, tn } from '../../i18n/index.js';
export const NEWS_LAYER_ID = 'news';
export const NEWS_OVERLAY_SOURCE_ID = 'news';
export const NEWS_PICK_PREFIX = 'news:';
export const NEWS_FEED_PAGE = 60;
export const NEWS_MAP_LIMIT = 500;
/** News is real time only: nothing older than a day is shown anywhere. */
export const NEWS_WINDOW_MS = 24 * 3_600_000;
/**
* The window a server serves, in ms: its `windowHours` (a whole number of
* hours up to 24; a host may serve fewer), else the full day.
*/
export function newsWindowMs(hours) {
return Number.isInteger(hours) && hours >= 1 && hours <= 24
? hours * 3_600_000
: NEWS_WINDOW_MS;
}
/** The windows the News panel offers, longest first. */
export const NEWS_WINDOW_CHOICES = Object.freeze([24, 12, 6, 3, 1]);
/**
* The windows offered under a server's own window of `maxHours`: that window
* itself, then each shorter choice.
*/
export function newsWindowChoices(maxHours) {
const cap = newsWindowMs(maxHours) / 3_600_000;
return [cap, ...NEWS_WINDOW_CHOICES.filter((hours) => hours < cap)];
}
// A publish time this far ahead of the clock is skew, not a future story
// (as data/regionalNewsWindow.js).
const NEWS_CLOCK_SKEW_MS = 15 * 60_000;
/** At most this many reports are kept in the feed list, newest first. */
export const NEWS_FEED_MAX = 600;
// Above this camera height the layer shows one beacon per hotspot; below it
// (or once a hotspot is chosen) the outlines and individual reports.
export const NEWS_DETAIL_MAX_HEIGHT_M = 2_500_000;
// "In view": reports near the view centre, only once the camera is low enough
// for "here" to mean a region, read again when it settles in a new cell.
// Near is inside the area the server names there (a country, a large
// country's state, a disputed area), else, at sea, within the radius.
export const NEWS_IN_VIEW_MAX_HEIGHT_M = 3_000_000;
export const NEWS_IN_VIEW_RADIUS_KM = 500;
export const NEWS_IN_VIEW_LIMIT = 12;
/** The Local section lists at most this many reports near the view centre. */
export const NEWS_LOCAL_LIMIT = 40;
/**
* The News panel's sections: Conflicts (the hotspots' significant news, on the
* map whenever the layer is on) and Local (everything near the view centre,
* on the map while the section is chosen).
*/
export const NEWS_SECTIONS = Object.freeze(['conflicts', 'local']);
export const NEWS_SETTLE_MS = 800;
export const NEWS_CELL_DEG = 0.5;
/** A feed card's click flies the camera to this height over the event. */
export const NEWS_FOCUS_HEIGHT_M = 150_000;
// Minor news (a broad outlet's prices, sport, health) is left out unless asked for.
export const NEWS_RELEVANT = 'core,related';
const SOURCE_LABEL = msg('Source');
const DISPUTED = msg('Disputed: {name}');
const VIA = msg('via {source}');
const MEDIA_LABELS = { video: msg('Video'), photo: msg('Photos') };
const CLAIMED_BY = msg('Claimed by {who}');
const CLAIMED = msg('Claimed');
const UNCONFIRMED = msg('Not yet confirmed by others');
const REPORTED_BY_SIDE = msg('Reported by {side} sources');
const REPORTED_BY_SIDES = msg('Reported by {sides}');
const SIDE_SOURCES = msg('{side} sources');
const OFFICIAL = msg('Official');
const OFFICIAL_AFFILIATIONS = new Set(['military', 'state']);
const ATTESTATION = {
'both-sides': msg('Reported by both sides'),
independent: msg('Independently reported'),
single: msg('Single source'),
};
const NEUTRAL_SIDES = Object.freeze({
intl: msg('International'),
independent: msg('Independent'),
unknown: msg('Unattributed'),
external: msg('Outside party'),
});
/**
* Short chip names for the curated hotspots; the API's own English name is
* the fallback for any other.
*/
export const NEWS_HOTSPOT_LABELS = Object.freeze({
'ua-ru-war': msg('Ukraine–Russia'),
'israel-gaza-lebanon': msg('Israel–Gaza–Lebanon'),
'iran-hormuz': msg('Iran–Hormuz'),
yemen: msg('Yemen–Red Sea'),
'sudan-war': msg('Sudan'),
sahel: msg('Sahel'),
elsewhere: msg('Elsewhere'),
// Core's own news (no news server): the world is one hotspot.
worldwide: msg('Worldwide'),
});
/** A hotspot's chip label in the interface language. */
export function hotspotLabel(hotspot) {
const key = NEWS_HOTSPOT_LABELS[hotspot?.id];
if (key) return t(key);
return hotspot?.catchAll ? t(NEWS_HOTSPOT_LABELS.elsewhere) : hotspot?.name;
}
/** A country's name in the interface language, from its ISO code. */
export function countryName(code) {
if (!code) return '';
try {
return (
new Intl.DisplayNames([getLocale(), 'en'], { type: 'region' }).of(code) ||
code
);
} catch {
return code;
}
}
const AREA_IN_COUNTRY = msg('{region}, {country}');
/**
* The Local section's area in the interface language: a country by its code,
* a state with its country, a disputed area by its own name only.
*/
export function areaLabel(area) {
if (!area) return '';
if (area.kind === 'disputed' || !area.country) return area.name;
if (area.kind === 'country') return countryName(area.country);
return t(AREA_IN_COUNTRY, {
region: area.name,
country: countryName(area.country),
});
}
/** Label for a disputed area on the map: its name, marked as disputed. */
export const disputedLabel = (area) => t(DISPUTED, { name: area.name });
// A category is told by its icon (a 16-unit SVG path, filled or stroked). On
// the map and in the feed colour is severity (NEWS_SEVERITY), never the type
// of event or a side.
export const NEWS_CATEGORIES = Object.freeze({
strike: {
label: msg('Strike'),
icon: 'M8 0.8 L9.6 5.2 L14.2 3.6 L11.2 7.6 L15.2 10.6 L10.3 10.6 L8 15.2 L5.7 10.6 L0.8 10.6 L4.8 7.6 L1.8 3.6 L6.4 5.2 Z',
solid: true,
},
// A threat on its way (a drone's course, an air-raid alert): nothing has
// hit yet. Not a physical event, so never a picture card.
alert: {
label: msg('Alert'),
icon: 'M1.5 8 H11.5 M8 4.5 L11.5 8 L8 11.5 M14.5 3.5 V12.5',
},
'air-defence': {
label: msg('Air defence'),
icon: 'M8 1.5 L13.5 3.5 V8 C13.5 11.3 10.8 13.4 8 14.6 C5.2 13.4 2.5 11.3 2.5 8 V3.5 Z M8 4.5 V11',
},
ground: {
label: msg('Ground fighting'),
icon: 'M3 13 L12 4 M8.5 3.5 H12.5 V7.5 M13 13 L4 4 M3.5 7.5 V3.5 H7.5',
},
casualties: {
label: msg('Casualties'),
icon: 'M6.2 2 H9.8 V6.2 H14 V9.8 H9.8 V14 H6.2 V9.8 H2 V6.2 H6.2 Z',
solid: true,
},
humanitarian: {
label: msg('Humanitarian'),
icon: 'M8 2.5 L14.5 13.5 H1.5 Z M8 2.5 V13.5',
},
infrastructure: {
label: msg('Infrastructure'),
icon: 'M9.2 1 L3.2 9 H7.6 L6.6 15 L12.8 6.8 H8.4 Z',
solid: true,
},
disaster: {
label: msg('Disaster'),
icon: 'M1.5 6.5 C3.5 4.5 5.5 4.5 7.5 6.5 S11.5 8.5 14.5 6.5 M1.5 10.5 C3.5 8.5 5.5 8.5 7.5 10.5 S11.5 12.5 14.5 10.5',
},
protest: {
label: msg('Protest'),
icon: 'M2.5 6.2 V9.8 H5 L12.5 13.2 V2.8 L5 6.2 Z',
},
political: {
label: msg('Political'),
icon: 'M2 14 H14 M2.5 5.5 H13.5 M8 1.8 L14 4.8 H2 Z M4.2 6.5 V12 M8 6.5 V12 M11.8 6.5 V12',
},
// Business, trade and industry: a national feed's news in Local.
economy: {
label: msg('Economy'),
icon: 'M2 13.5 H14 M2.5 11 L6 7.5 L8.5 9.5 L13.5 4.5 M10.5 4.5 H13.5 V7.5',
},
other: {
label: msg('Other'),
icon: 'M8 4.5 A3.5 3.5 0 1 0 8.01 4.5 Z',
solid: true,
},
});
// Severity 0–3, in colours GEV already uses: its dim and primary text, the
// military layers' amber and the Cockpit's emergency red. They are drawn on
// a dark disc, so from minor up lightness falls as severity rises and the
// ramp still reads under colour blindness and in greyscale.
export const NEWS_SEVERITY = Object.freeze([
{ label: msg('No physical event'), color: '#7c878d' },
{ label: msg('Minor incident'), color: '#e8eaed' },
{ label: msg('Significant'), color: '#ffb800' },
{ label: msg('Major'), color: '#ff4444' },
]);
/** The feed's default floor: significant and major events. */
export const NEWS_DEFAULT_MIN_SEVERITY = 2;
const PHYSICAL = new Set([
'strike',
'air-defence',
'ground',
'casualties',
'infrastructure',
'disaster',
]);
export const categoryStyle = (category) =>
NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
export const categoryLabel = (category) => t(categoryStyle(category).label);
/** Party codes (UA, RU, IL…) are shown as-is; neutral sides are translated. */
export const sideLabel = (side) =>
Object.hasOwn(NEUTRAL_SIDES, side) ? t(NEUTRAL_SIDES[side]) : side;
/**
* A report's severity, 0–3: the server's (the local model's reading, else
* its rules, raised to its event's), or a fallback from the category.
*/
export function reportSeverity(report) {
const own = Number.isInteger(report?.severity) ? report.severity : null;
const event = Number.isInteger(report?.event?.severity)
? report.event.severity
: null;
if (own === null && event === null)
return PHYSICAL.has(report?.category) ? 1 : 0;
return Math.max(own ?? 0, event ?? 0);
}
export const severityStyle = (report) => NEWS_SEVERITY[reportSeverity(report)];
export const severityLabel = (report) => t(severityStyle(report).label);
/** When a report (or its event) was last heard of, in ms; NaN when unknown. */
const lastHeard = (report) =>
Date.parse(report?.event?.lastAt || report?.publishedAt || '');
/**
* Whether a time is inside the window (the last 24 hours unless the server
* serves fewer; the only news shown); one more than 15 minutes ahead of the
* clock is not.
*/
function inWindow(value, now, windowMs = NEWS_WINDOW_MS) {
const at = Date.parse(value || '');
return (
Number.isFinite(at) &&
now - at <= windowMs &&
at - now <= NEWS_CLOCK_SKEW_MS
);
}
/** Whether a report is inside the window (the only news shown). */
export function withinNewsWindow(
report,
now = Date.now(),
windowMs = NEWS_WINDOW_MS,
) {
return inWindow(report?.publishedAt, now, windowMs);
}
/** The event's one-report-per-side list, inside the last 24 hours only. */
const recentSides = (report, now) =>
(report?.event?.sides || []).filter((s) => inWindow(s.publishedAt, now));
/**
* How a report or its event is attested, as a chip: `claimed` (someone's
* claim, named where known), `confirmed` (both sides, or an independent
* source), `side` (one party's own press), `single` (one report), or null.
*/
export function attestation(report) {
const event = report?.event;
const status = event?.status || (report?.claim ? 'claimed' : null);
if (status === 'claimed') {
const who = event?.claimedBy || report?.claim?.by;
return {
kind: 'claimed',
label: who ? t(CLAIMED_BY, { who }) : t(CLAIMED),
};
}
if (status === 'both-sides' || status === 'independent')
return { kind: 'confirmed', label: t(ATTESTATION[status]) };
if (status === 'side' && event.reportedSide)
return {
kind: 'side',
label: t(REPORTED_BY_SIDE, { side: sideLabel(event.reportedSide) }),
};
if (status === 'single')
return { kind: 'single', label: t(ATTESTATION.single) };
return null;
}
/**
* The attestation chip under a report. An official channel's own post is
* already marked Official: "Claimed by" itself would read as doubt about an
* alert. It says only that nobody else has reported it yet, and nothing for
* an alert, which is the channel's own notice.
*/
function ownClaimChip(report) {
const chip = attestation(report);
if (
chip?.kind !== 'claimed' ||
!OFFICIAL_AFFILIATIONS.has(report.affiliation)
)
return chip;
const who = report.event?.claimedBy || report.claim?.by;
if (who && who !== report.sourceName && who !== report.publisher) return chip;
return report.category === 'alert'
? null
: { kind: 'claimed', label: t(UNCONFIRMED) };
}
// The map card is a label, not a reader: long headlines are cut.
export const NEWS_CARD_TITLE_MAX = 90;
/** A headline cut at a word to fit `max` characters. */
export function shortTitle(title, max = NEWS_CARD_TITLE_MAX) {
const text = String(title || '');
if (text.length <= max) return text;
const cut = text.slice(0, max - 1);
const word = cut.lastIndexOf(' ');
return `${word > max * 0.6 ? cut.slice(0, word) : cut}…`;
}
/** The media a post carries ("Video", "Photos"), translated. */
export function mediaLabels(report) {
return (report?.media || [])
.map((m) => (MEDIA_LABELS[m] ? t(MEDIA_LABELS[m]) : ''))
.filter(Boolean);
}
/**
* How long ago, in few words: "now" under a minute, "N min" under an hour,
* "N h" under a day. Older is never shown; it reads
* "24 h".
*/
export function ageWords(at, now = Date.now()) {
const minutes = Math.max(0, Math.floor((now - Date.parse(at)) / 60_000));
if (!Number.isFinite(minutes)) return '';
if (minutes < 1) return t('now', { context: 'age' });
if (minutes < 60) return t('{minutes} min', { minutes });
return t('{hours} h', { hours: Math.min(24, Math.floor(minutes / 60)) });
}
/**
* How a report's marker looks: colour = severity, icon = category, rim =
* attestation (`confirmed` solid, `claimed` dashed, else thin), size =
* sources, opacity = age (fading to 45 % over a day).
*/
export function markerStyle(report, now = Date.now()) {
const kind = attestation(report)?.kind;
const at = lastHeard(report);
const hours = Number.isFinite(at) ? Math.max(0, (now - at) / 3_600_000) : 0;
return {
category: Object.hasOwn(NEWS_CATEGORIES, report?.category)
? report.category
: 'other',
severity: reportSeverity(report),
rim: kind === 'confirmed' || kind === 'claimed' ? kind : 'thin',
size: eventPixelSize(report?.event?.size),
alpha: Math.max(0.45, 1 - (0.55 * Math.min(hours, 24)) / 24),
};
}
function hash(text) {
let h = 2166136261;
for (let i = 0; i < text.length; i++) {
h ^= text.charCodeAt(i);
h = Math.imul(h, 16777619);
}
return h >>> 0;
}
/**
* Trend glyph for a hotspot: ▲/▼ when the last 24 h differ from the 24 h
* before by more than a fifth, nothing when flat or without a prior day.
*/
export function hotspotTrend(last24h, prev24h) {
if (!(prev24h > 0)) return '';
if (last24h > prev24h * 1.2) return '▲';
if (last24h < prev24h * 0.8) return '▼';
return '';
}
/** Beacon size in pixels: grows with the square root of daily activity. */
export const beaconPixelSize = (last24h) =>
Math.round(Math.min(26, 10 + Math.sqrt(Math.max(0, last24h)) * 1.4));
/** Marker size for an event: grows with the number of distinct sources. */
export function eventPixelSize(sources = 1) {
return Math.round(
// No smaller than 24: the category icon is half the disc and unreadable
// below that.
Math.min(36, 24 + 3 * Math.log2(Math.max(1, Number(sources) || 1))),
);
}
// An event several sources report within the last few hours gets a halo.
export const NEWS_PRESSING_SOURCES = 5;
const PRESSING_MS = 3 * 3_600_000;
/** Whether an event is fresh and widely reported, or fresh and major. */
export function isPressing(report, now = Date.now()) {
const event = report?.event;
const fresh = now - lastHeard(report) <= PRESSING_MS;
return Boolean(
fresh &&
((event && event.size >= NEWS_PRESSING_SOURCES) ||
reportSeverity(report) === 3),
);
}
// The big events stand as picture cards over their marker: several
// sources, and major or pressing.
export const NEWS_CARD_LIMIT = 10;
export const NEWS_CARD_MIN_SOURCES = 2;
/** Whether an event gets a card on the map: physical events only, not statements. */
export function isCardEvent(report, now = Date.now()) {
return Boolean(
report?.event?.size >= NEWS_CARD_MIN_SOURCES &&
PHYSICAL.has(report.category) &&
(reportSeverity(report) === 3 || isPressing(report, now)),
);
}
/** The card events among `reports`, most severe, most reported and newest first. */
export function cardEvents(reports, now = Date.now(), limit = NEWS_CARD_LIMIT) {
return reports
.filter((r) => r.pins?.length && isCardEvent(r, now))
.sort(
(a, b) =>
reportSeverity(b) - reportSeverity(a) ||
b.event.size - a.event.size ||
(b.event.lastAt || '').localeCompare(a.event.lastAt || ''),
)
.slice(0, limit);
}
/** The distinct sides an event was reported by in the last day, lead first. */
function eventSides(report, now) {
const sides = recentSides(report, now).map((s) => s.side);
return [...new Set(sides.length ? sides : [report?.side].filter(Boolean))];
}
/**
* "Reported by UA sources · RU sources", or '' when no side is known; an
* unattributed side is left out.
*/
export function sidesLine(report, now = Date.now()) {
const sides = eventSides(report, now).filter((side) => side !== 'unknown');
if (!sides.length) return '';
if (sides.length === 1)
return t(REPORTED_BY_SIDE, { side: sideLabel(sides[0]) });
return t(REPORTED_BY_SIDES, {
sides: sides
.map((side) => t(SIDE_SOURCES, { side: sideLabel(side) }))
.join(' · '),
});
}
/**
* The event's picture, the publisher named, and its clip when it has one. The
* panel shows it for any event; the globe's picture cards are for events of
* two or more sources (isCardEvent).
*/
export function eventPicture(report) {
const image = report?.event?.image;
if (!image) return null;
return {
url: image.url,
credit: image.publisher || '',
...(image.video ? { video: image.video } : {}),
};
}
/** What an event's picture card on the globe shows. */
export function cardView(report, now = Date.now()) {
const event = report.event;
const sides = eventSides(report, now).map(sideLabel);
// A globe card's picture needs two or more sources, as the card does.
const picture =
report?.event?.size >= NEWS_CARD_MIN_SOURCES ? eventPicture(report) : null;
return {
title: report.titleEn || report.title,
meta: [
ageWords(event?.lastAt || report.publishedAt, now),
tn(event?.size || 1, '{count} source', '{count} sources'),
sides.slice(0, 3).join(', ') + (sides.length > 3 ? '…' : ''),
]
.filter(Boolean)
.join(' · '),
image: picture?.url || null,
credit: picture?.credit || '',
};
}
/** "Source: host ↗" line for a report's card; the card opens the article. */
export function sourceLinkLabel(url) {
let host = '';
try {
host = new URL(url).hostname.replace(/^www\./, '');
} catch {
return '';
}
return `${t(SOURCE_LABEL)}: ${host} ↗`;
}
/**
* "via GDELT Project": the service a report was read through, which asks to
* be credited where its reports show; '' when the server names none.
*/
export function attributionLabel(report) {
return report?.attribution ? t(VIA, { source: report.attribution }) : '';
}
/** The places a report is pinned at, joined, or null. */
function placeLine(report) {
return (
(report.pins?.length ? report.pins : [report.geo])
.map((p) => p?.place)
.filter(Boolean)
.join(' · ') || null
);
}
/**
* One event card in the News panel: picture,
* headline, a mono meta line (severity, category, place, sources, age, the
* service it came through), the sides line, then attestation and media chips. Labels and colours are
* resolved here so the panel imports no layer code.
*/
export function feedCardView(report, now = Date.now()) {
const severity = reportSeverity(report);
const style = categoryStyle(report.category);
const size = report.event?.size || 1;
const translated = Boolean(report.titleEn && report.titleEn !== report.title);
return {
id: report.id,
url: report.url,
title: translated ? report.titleEn : report.title,
// The local model's English headline over a post in another language:
// the original stays beside it.
original: translated ? report.title : null,
snippet: report.snippet,
severity,
severityLabel: t(NEWS_SEVERITY[severity].label),
color: NEWS_SEVERITY[severity].color,
icon: style.icon,
solid: Boolean(style.solid),
category: categoryLabel(report.category),
place: placeLine(report),
placedByModel: Boolean(report.geo?.byModel),
mappable: Boolean(report.pins?.length),
sources: tn(size, '{count} source', '{count} sources'),
age: ageWords(report.event?.lastAt || report.publishedAt, now),
publisher: report.publisher,
via: attributionLabel(report),
sides: sidesLine(report, now),
sourceLink: sourceLinkLabel(report.url),
picture: eventPicture(report),
chips: [
// An official channel speaking for itself (a ministry, the armed
// forces, a press service), not an outlet that quotes one.
OFFICIAL_AFFILIATIONS.has(report.affiliation)
? { kind: 'official', label: t(OFFICIAL) }
: null,
ownClaimChip(report),
...mediaLabels(report).map((label) => ({ kind: 'media', label })),
].filter(Boolean),
// The event's first report from each other side, under the lead.
others: recentSides(report, now)
.slice(1)
.map((s) => ({
side: sideLabel(s.side),
publisher: s.publisher,
title: s.title,
url: s.url,
})),
};
}
/**
* Whether a report is placed no closer than a country: it has no spot of its
* own on the map.
*/
export const countryOnly = (report) =>
report.pins?.length > 0 &&
report.pins.every((pin) => pin.precision === 'country');
/**
* Country-only reports as one group per country, in the order met:
* `{key, place, lat, lon, count}`. They are drawn as one badge with a count,
* not as markers piled on the country's centre.
*/
export function countryGroups(reports) {
const groups = new Map();
for (const report of reports) {
if (!countryOnly(report)) continue;
const { lat, lon, place } = report.pins[0];
const key = place || `${lat.toFixed(1)},${lon.toFixed(1)}`;
const group = groups.get(key);
if (group) group.count += 1;
else groups.set(key, { key, place: place || '', lat, lon, count: 1 });
}
return [...groups.values()];
}
/**
* Marker position for a report. Many reports name the same city and would
* stack on one centroid, so each is spread on a small deterministic ring
* (about 1.5 km for a place, 6 km for a region, 28 km for a country) to stay
* individually clickable. The spread is display-only; cards show the place.
*/
export function reportMarkerPosition(report, pin = 0) {
const { lat, lon, precision } = report.pins?.[pin] || report.geo;
const h = hash(pin ? `${report.id}~${pin}` : report.id);
const angle = ((h % 3600) / 3600) * 2 * Math.PI;
const radiusDeg =
(precision === 'country' ? 0.25 : precision === 'region' ? 0.055 : 0.014) *
(0.35 + ((h >>> 12) % 65) / 100);
return {
lat: lat + radiusDeg * Math.sin(angle),
lon: lon + (radiusDeg * Math.cos(angle)) / Math.cos((lat * Math.PI) / 180),
};
}
/**
* Merge a page into the feed, newest first, one row per report id, keeping
* only the window and at most `max` rows (a long session does not grow
* the list). `mode` 'head' refreshes the top and keeps the older cursor;
* 'append' adds an older page and takes its cursor; 'replace' starts over.
* A head page that has older pages behind it and shares no row with the list
* left a gap (more than a page arrived since), so it starts over too.
*/
export function mergeFeedPage(
feed,
page,
mode,
now = Date.now(),
max = NEWS_FEED_MAX,
windowMs = NEWS_WINDOW_MS,
) {
const byId = new Map();
if (mode === 'head' && page.nextBefore && feed.items.length) {
const held = new Set(feed.items.map((item) => item.id));
if (!page.reports.some((item) => held.has(item.id))) mode = 'replace';
}
const items =
mode === 'replace'
? page.reports
: mode === 'append'
? [...feed.items, ...page.reports]
: [...page.reports, ...feed.items];
for (const item of items)
if (!byId.has(item.id) && withinNewsWindow(item, now, windowMs))
byId.set(item.id, item);
return {
items: [...byId.values()]
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
.slice(0, max),
nextBefore:
mode === 'head' && feed.items.length ? feed.nextBefore : page.nextBefore,
};
}
/** Normalised filters; anything unknown falls back to its default. */
export function normalizeFilters(next = {}, hotspots = [], previous = {}) {
const merged = { ...previous, ...next };
const hotspot = hotspots.some((h) => h.id === merged.hotspot)
? merged.hotspot
: 'all';
const category = Object.hasOwn(NEWS_CATEGORIES, merged.category)
? merged.category
: 'all';
const minSeverity =
Number.isInteger(merged.minSeverity) &&
merged.minSeverity >= 0 &&
merged.minSeverity <= 3
? merged.minSeverity
: NEWS_DEFAULT_MIN_SEVERITY;
return {
hotspot,
category,
minSeverity,
section: NEWS_SECTIONS.includes(merged.section)
? merged.section
: 'conflicts',
// A shorter window than the server's; null shows all it serves.
hours: NEWS_WINDOW_CHOICES.includes(merged.hours) ? merged.hours : null,
};
}
/** Whether a report passes the filters the server does not apply. */
export function passesFilters(
report,
filters,
now = Date.now(),
windowMs = NEWS_WINDOW_MS,
) {
return (
withinNewsWindow(report, now, windowMs) &&
reportSeverity(report) >= filters.minSeverity
);
}
/** Whether a report belongs on the map under the current filters. */
export function visibleOnMap(
report,
filters,
now = Date.now(),
windowMs = NEWS_WINDOW_MS,
) {
return (
(filters.hotspot === 'all' ||
(report.hotspotIds || [report.hotspotId]).includes(filters.hotspot)) &&
(filters.category === 'all' || report.category === filters.category) &&
passesFilters(report, filters, now, windowMs)
);
}
/**
* The filters Local applies: every hotspot and every severity, near the view
* centre; the category and the window still hold.
*/
export const localFilters = (filters) => ({
...filters,
hotspot: 'all',
minSeverity: 0,
});
/** API query for the Conflicts feed under the current filters: the window only. */
export function feedQueryFor(filters, extra = {}) {
return {
events: true,
today: true,
relevance: NEWS_RELEVANT,
hotspot: filters.hotspot,
category: filters.category === 'all' ? '' : filters.category,
limit: NEWS_FEED_PAGE,
...extra,
};
}
/** The half-degree cell a point lies in, as a key. */
export function viewCell({ lat, lon }) {
return `${Math.floor(lat / NEWS_CELL_DEG)}:${Math.floor(lon / NEWS_CELL_DEG)}`;
}
/** Great-circle distance in kilometres. */
export function distanceKm(a, b) {
const rad = Math.PI / 180;
const dLat = (b.lat - a.lat) * rad;
const dLon = (b.lon - a.lon) * rad;
const s =
Math.sin(dLat / 2) ** 2 +
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(s)));
}
function inRing(ring, { lat, lon }) {
let inside = false;
for (let i = 0, j = ring.length - 1; i < ring.length; j = i++) {
const [xi, yi] = ring[i];
const [xj, yj] = ring[j];
if (
yi > lat !== yj > lat &&
lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi
)
inside = !inside;
}
return inside;
}
/** Whether a point lies in an outline's polygons (`{outer, holes}`). */
export function inPolygons(polygons, point) {
return polygons.some(
({ outer, holes }) =>
inRing(outer, point) && !holes.some((hole) => inRing(hole, point)),
);
}
/**
* The reports near `centre` that pass the filters, newest first: any pin
* inside `area` (outline polygons), or without one within
* NEWS_IN_VIEW_RADIUS_KM. Newest, not most severe: an area's own news often
* carries no severity, and the area's fighting would otherwise crowd it out.
*/
export function reportsInView(
reports,
centre,
filters,
now = Date.now(),
limit = NEWS_IN_VIEW_LIMIT,
windowMs = NEWS_WINDOW_MS,
area = null,
) {
if (!centre) return [];
const near = area?.length
? (pin) => inPolygons(area, pin)
: (pin) => distanceKm(pin, centre) <= NEWS_IN_VIEW_RADIUS_KM;
return reports
.filter(
(r) =>
passesFilters(r, filters, now, windowMs) &&
(filters.category === 'all' || r.category === filters.category) &&
r.pins?.some(near),
)
.sort((a, b) => b.publishedAt.localeCompare(a.publishedAt))
.slice(0, limit);
}
+765
View File
@@ -0,0 +1,765 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
normalizeFeedPayload,
normalizeHotspotsPayload,
normalizeOutlinePayload,
} from './records.js';
import {
NEWS_IN_VIEW_RADIUS_KM,
ageWords,
areaLabel,
beaconPixelSize,
cardEvents,
cardView,
distanceKm,
eventPixelSize,
feedCardView,
feedQueryFor,
hotspotLabel,
hotspotTrend,
inPolygons,
isPressing,
markerStyle,
mergeFeedPage,
newsWindowChoices,
newsWindowMs,
normalizeFilters,
passesFilters,
reportMarkerPosition,
reportSeverity,
reportsInView,
sidesLine,
sourceLinkLabel,
viewCell,
visibleOnMap,
withinNewsWindow,
} from './model.js';
import { newsFeedQuery } from './source.js';
const NOW = Date.parse('2026-10-28T10:00:00Z');
const report = (id, publishedAt, extra = {}) => ({
id,
title: `Report ${id}`,
url: `https://example.com/${id}`,
publishedAt,
publisher: 'Example',
side: 'UA',
category: 'strike',
hotspotIds: ['ua'],
geo: {
lat: 50,
lon: 36,
place: 'Kharkiv',
precision: 'city',
mappable: true,
},
pins: [
{ lat: 50, lon: 36, place: 'Kharkiv', precision: 'city', mappable: true },
],
...extra,
});
const event = (extra = {}) => ({
status: 'both-sides',
size: 6,
severity: 3,
lastAt: '2026-10-28T09:30:00Z',
sides: [
{
side: 'UA',
title: 'a',
url: 'https://a.test/',
publisher: 'A',
publishedAt: '2026-10-28T09:00:00Z',
},
{
side: 'RU',
title: 'b',
url: 'https://b.test/',
publisher: 'B',
publishedAt: '2026-10-28T09:20:00Z',
},
],
image: { url: 'https://a.test/p.jpg', publisher: 'A' },
...extra,
});
test('payloads are validated record by record; empty and malformed payloads', () => {
const hotspots = normalizeHotspotsPayload({
hotspots: [
{
id: 'ua',
name: 'UA',
bbox: [22, 44, 42, 56],
parties: ['UA', 'RU', '<x>'],
counts: { last24h: 3 },
},
{ id: 'bad', name: 'Bad', bbox: [42, 44, 22, 56] },
{ id: '../x', name: 'Bad id', bbox: [22, 44, 42, 56] },
],
ingest: { lastRunAt: '2026-10-28T10:00:00Z' },
});
assert.deepEqual(
hotspots.hotspots.map((h) => [h.id, h.parties, h.last24h]),
[['ua', ['UA', 'RU'], 3]],
);
assert.equal(hotspots.lastRunAt, '2026-10-28T10:00:00.000Z');
assert.equal(normalizeHotspotsPayload({}), null);
assert.equal(normalizeHotspotsPayload(null), null);
assert.deepEqual(normalizeHotspotsPayload({ hotspots: [] }).hotspots, []);
const feed = normalizeFeedPayload({
reports: [
{
id: 'r_1',
title: ' Strike on Kharkiv ',
url: 'https://x.test/a',
publishedAt: '2026-10-28T09:00:00Z',
geo: { lat: 50, lon: 36, mappable: true },
media: ['video', 'video', 'audio'],
event: { size: 3, image: { url: 'http://x.test/p.jpg' } },
},
{
id: 'r_2',
title: 'Bad link',
url: 'javascript:alert(1)',
publishedAt: '2026-10-28T09:00:00Z',
},
{
id: 'r_3',
title: 'Bad geo',
url: 'https://user:[email protected]/c',
publishedAt: '2026-10-28T09:00:00Z',
},
{
id: 'r_4',
title: 'Off the globe',
url: 'https://x.test/d',
publishedAt: '2026-10-28T09:00:00Z',
geo: { lat: 200, lon: 36 },
},
],
nextBefore: '2026-10-28T08:00:00Z',
});
assert.deepEqual(
feed.reports.map((r) => [r.id, r.title, Boolean(r.geo), r.pins.length]),
[
['r_1', 'Strike on Kharkiv', true, 1],
['r_4', 'Off the globe', false, 0],
],
);
assert.deepEqual(feed.reports[0].media, ['video']);
// A picture must be HTTPS on the publisher's site.
assert.equal(feed.reports[0].event.image, null);
assert.equal(feed.nextBefore, '2026-10-28T08:00:00.000Z');
assert.equal(normalizeFeedPayload({ reports: 'x' }), null);
assert.deepEqual(normalizeFeedPayload({ reports: [] }), {
reports: [],
nextBefore: null,
});
});
test("an event's clip is kept only as an HTTPS file a browser plays itself", () => {
const clip = (video) =>
normalizeFeedPayload({
reports: [
{
id: 'r',
title: 'T',
url: 'https://x.test/r',
publishedAt: '2026-10-28T09:00:00Z',
event: {
size: 1,
image: { url: 'https://cdn.test/p.jpg', publisher: 'P', video },
},
},
],
}).reports[0].event.image.video;
assert.equal(
clip('https://cdn.test/v.mp4?token=a'),
'https://cdn.test/v.mp4?token=a',
);
assert.equal(clip('https://cdn.test/v.webm'), 'https://cdn.test/v.webm');
assert.equal(clip('http://cdn.test/v.mp4'), undefined);
assert.equal(clip('https://cdn.test/v.m3u8'), undefined);
assert.equal(clip(undefined), undefined);
});
test('outlines keep valid rings, borders and named disputed areas', () => {
const ring = [
[30, 45],
[31, 45],
[31, 46],
];
const outline = normalizeOutlinePayload({
polygons: [{ outer: ring, holes: [[[0, 0]]] }, { outer: [[1, 2]] }],
borders: [ring, 'x'],
disputed: [
{
name: 'Crimea',
kind: 'held',
heldBy: 'RU',
claimedBy: 'UA',
rings: [ring],
},
{ name: 'No rings', rings: [] },
{ name: 'Odd kind', kind: 'zzz', heldBy: 'nope', rings: [ring] },
],
});
assert.equal(outline.polygons.length, 1);
assert.deepEqual(outline.polygons[0].holes, []);
assert.equal(outline.borders.length, 1);
assert.deepEqual(
outline.disputed.map((d) => [d.name, d.kind, d.heldBy]),
[
['Crimea', 'held', 'RU'],
['Odd kind', 'held', null],
],
);
assert.deepEqual(normalizeOutlinePayload(null), {
polygons: [],
borders: [],
disputed: [],
area: null,
});
// Indonesia's 208 islands are all kept.
const islands = Array.from({ length: 208 }, () => ({ outer: ring }));
assert.equal(
normalizeOutlinePayload({ polygons: islands }).polygons.length,
208,
);
});
test('a point outline names its area, and Local keeps to it', () => {
const box = [
[35, 48],
[37, 48],
[37, 50.5],
[35, 50.5],
];
const { area, polygons } = normalizeOutlinePayload({
area: { key: 'US-TX', name: 'Texas', kind: 'region', country: 'US' },
polygons: [{ outer: box, holes: [] }],
});
assert.deepEqual(area, {
key: 'US-TX',
name: 'Texas',
kind: 'region',
country: 'US',
});
assert.equal(areaLabel(area), 'Texas, United States');
assert.equal(
areaLabel({ ...area, kind: 'country', country: 'UA' }),
'Ukraine',
);
// A disputed area is named as itself, never as either side's.
assert.equal(
areaLabel({ key: 'disputed:Crimea', name: 'Crimea', kind: 'disputed' }),
'Crimea',
);
assert.equal(normalizeOutlinePayload({ area: { key: 'X' } }).area, null);
const at = (id, lat, lon) =>
report(id, '2026-10-28T09:00:00Z', {
pins: [{ lat, lon, mappable: true }],
});
const reports = [at('inside', 50, 36), at('beyond', 49, 39)];
const filters = normalizeFilters({ minSeverity: 0 });
const centre = { lat: 49, lon: 36 };
const now = Date.parse('2026-10-28T10:00:00Z');
const ids = (area) =>
reportsInView(reports, centre, filters, now, 10, undefined, area).map(
(r) => r.id,
);
// Within 500 km both; inside the area only the one.
assert.deepEqual(ids(null), ['inside', 'beyond']);
assert.deepEqual(ids(polygons), ['inside']);
assert.ok(inPolygons(polygons, { lat: 49, lon: 36 }));
assert.ok(!inPolygons([{ outer: box, holes: [box] }], { lat: 49, lon: 36 }));
});
test('feed pages merge newest first without duplicates', () => {
const a = report('a', '2026-10-28T10:00:00Z');
const b = report('b', '2026-10-28T09:00:00Z');
const c = report('c', '2026-10-28T08:00:00Z');
let feed = mergeFeedPage(
{ items: [] },
{ reports: [a, b], nextBefore: 'B' },
'replace',
NOW,
);
assert.deepEqual(
[feed.items.map((r) => r.id), feed.nextBefore],
[['a', 'b'], 'B'],
);
feed = mergeFeedPage(
feed,
{ reports: [b, c], nextBefore: null },
'append',
NOW,
);
assert.deepEqual(
[feed.items.map((r) => r.id), feed.nextBefore],
[['a', 'b', 'c'], null],
);
const newer = report('n', '2026-10-28T11:00:00Z');
feed = mergeFeedPage(
{ ...feed, nextBefore: 'C' },
{ reports: [newer, a], nextBefore: 'X' },
'head',
NOW + 3_600_000,
);
assert.deepEqual(
[feed.items.map((r) => r.id), feed.nextBefore],
[['n', 'a', 'b', 'c'], 'C'],
);
assert.deepEqual(
mergeFeedPage({ items: [] }, { reports: [], nextBefore: null }, 'replace'),
{ items: [], nextBefore: null },
);
});
test('a head page that does not reach the rows held starts the list over', () => {
const held = report('h', '2026-10-28T06:00:00Z');
const fresh = report('n', '2026-10-28T09:30:00Z');
// More than a page arrived since the last refresh (a suspended tab): the
// reports between this page and the rows held are behind its cursor.
const feed = mergeFeedPage(
{ items: [held], nextBefore: 'OLD' },
{ reports: [fresh], nextBefore: 'NEW' },
'head',
NOW,
);
assert.deepEqual(
[feed.items.map((r) => r.id), feed.nextBefore],
[['n'], 'NEW'],
);
});
test('the feed list keeps only the last 24 hours and at most its cap', () => {
const fresh = report('f', '2026-10-28T09:00:00Z');
const stale = report('s', '2026-10-27T09:00:00Z');
const ahead = report('x', '2026-10-28T11:00:00Z');
// A long session: yesterday's rows already held fall out on the next merge.
const feed = mergeFeedPage(
{ items: [stale], nextBefore: 'S' },
{ reports: [fresh, ahead], nextBefore: 'F' },
'head',
NOW,
);
assert.deepEqual(
feed.items.map((r) => r.id),
['f'],
);
const many = Array.from({ length: 30 }, (_, i) =>
report(`r${i}`, new Date(NOW - (i + 1) * 60_000).toISOString()),
);
const capped = mergeFeedPage(
{ items: [] },
{ reports: many, nextBefore: null },
'replace',
NOW,
10,
);
assert.equal(capped.items.length, 10);
assert.equal(capped.items[0].id, 'r0');
assert.equal(capped.items.at(-1).id, 'r9');
// Everything outside the window: an empty list, not an error.
assert.deepEqual(
mergeFeedPage(
{ items: [] },
{ reports: [stale], nextBefore: null },
'replace',
NOW,
).items,
[],
);
});
test('filters default to significant news and map to a last-24-hours query', () => {
const hotspots = [{ id: 'ua' }, { id: 'me' }];
const filters = normalizeFilters(
{ hotspot: 'ua', category: 'nope', minSeverity: 9 },
hotspots,
);
assert.deepEqual(filters, {
hotspot: 'ua',
category: 'all',
minSeverity: 2,
section: 'conflicts',
hours: null,
});
assert.equal(
normalizeFilters({ section: 'local' }, hotspots).section,
'local',
);
assert.equal(
normalizeFilters({ section: 'nope' }, hotspots).section,
'conflicts',
);
assert.equal(normalizeFilters({ hours: 6 }, hotspots).hours, 6);
assert.equal(normalizeFilters({ hours: 5 }, hotspots).hours, null);
assert.equal(normalizeFilters({ minSeverity: 0 }, hotspots).minSeverity, 0);
assert.equal(normalizeFilters({ hotspot: 'gone' }, hotspots).hotspot, 'all');
assert.equal(
newsFeedQuery(
feedQueryFor(filters, { before: '2026-10-28T08:00:00.000Z' }),
),
'hotspot=ua&before=2026-10-28T08%3A00%3A00.000Z&limit=60&relevance=core%2Crelated&today=1&events=1',
);
// The Conflicts feed reads the same whichever section is chosen.
assert.equal(
newsFeedQuery(feedQueryFor({ ...filters, section: 'local' })),
newsFeedQuery(feedQueryFor(filters)),
);
});
test('only the last 24 hours pass, and the severity floor applies', () => {
const filters = normalizeFilters();
const fresh = report('f', '2026-10-28T09:00:00Z', { severity: 2 });
const minor = report('m', '2026-10-28T09:00:00Z', { severity: 1 });
const old = report('o', '2026-10-27T09:00:00Z', { severity: 3 });
assert.equal(withinNewsWindow(fresh, NOW), true);
assert.equal(withinNewsWindow(old, NOW), false);
assert.equal(withinNewsWindow({ publishedAt: 'x' }, NOW), false);
// Clock skew up to 15 min ahead passes; further ahead is not news yet.
const skew = report('k', '2026-10-28T10:14:00Z');
const future = report('z', '2026-10-28T10:16:00Z');
assert.equal(withinNewsWindow(skew, NOW), true);
assert.equal(withinNewsWindow(future, NOW), false);
assert.deepEqual(
[fresh, minor, old]
.filter((r) => passesFilters(r, filters, NOW))
.map((r) => r.id),
['f'],
);
assert.equal(visibleOnMap(minor, { ...filters, minSeverity: 0 }, NOW), true);
assert.equal(visibleOnMap(fresh, { ...filters, hotspot: 'me' }, NOW), false);
});
test('ageWords says now, minutes or hours', () => {
assert.equal(ageWords('2026-10-28T09:59:30Z', NOW), 'now');
assert.equal(ageWords('2026-10-28T09:55:00Z', NOW), '5 min');
assert.equal(ageWords('2026-10-28T07:10:00Z', NOW), '2 h');
assert.equal(ageWords('2026-10-26T07:10:00Z', NOW), '24 h');
assert.equal(ageWords('not a date', NOW), '');
});
test('markers spread deterministically near their place; source link line', () => {
const r = report('r_spread', '2026-10-28T10:00:00Z');
const p1 = reportMarkerPosition(r);
assert.deepEqual(reportMarkerPosition(r), p1);
assert.ok(Math.abs(p1.lat - 50) < 0.02 && Math.abs(p1.lon - 36) < 0.04);
assert.notDeepEqual(
reportMarkerPosition(report('r_other', r.publishedAt)),
p1,
);
assert.equal(
sourceLinkLabel('https://www.reliefweb.int/report/x'),
'Source: reliefweb.int ↗',
);
assert.equal(sourceLinkLabel('not a url'), '');
});
test('beacons carry a focus, a size by activity and a trend only against a prior day', () => {
const { hotspots } = normalizeHotspotsPayload({
hotspots: [
{
id: 'a',
name: 'A',
bbox: [20, 40, 40, 50],
focus: { lat: 45, lon: 30 },
counts: { last24h: 120, prev24h: 80 },
},
{
id: 'b',
name: 'B',
bbox: [20, 40, 40, 50],
focus: { lat: 80, lon: 30 },
},
],
});
assert.deepEqual(
hotspots.map((h) => h.focus),
[
{ lat: 45, lon: 30 },
{ lat: 45, lon: 30 },
],
);
assert.equal(hotspotTrend(120, 80), '▲');
assert.equal(hotspotTrend(50, 80), '▼');
assert.equal(hotspotTrend(85, 80), '');
assert.equal(hotspotTrend(40, 0), '');
assert.equal(beaconPixelSize(0), 10);
assert.equal(beaconPixelSize(10_000), 26);
assert.equal(
hotspotLabel({ id: 'ua-ru-war', name: 'Russia–Ukraine war' }),
'Ukraine–Russia',
);
assert.equal(hotspotLabel({ id: 'new-one', name: 'New one' }), 'New one');
assert.equal(
hotspotLabel({ id: 'x', name: 'X', catchAll: true }),
'Elsewhere',
);
assert.equal(
hotspotLabel({ id: 'worldwide', name: 'Worldwide', catchAll: true }),
'Worldwide',
);
});
test('marker style: severity fill, attestation rim, size by sources, fading with age', () => {
const r = report('r_style', '2026-10-28T10:00:00Z', {
severity: 2,
event: event({
status: 'claimed',
size: 4,
lastAt: '2026-10-28T10:00:00Z',
}),
});
const fresh = markerStyle(r, NOW);
assert.equal(fresh.severity, 3); // the event's, when higher than the report's
assert.equal(fresh.rim, 'claimed');
assert.equal(fresh.size, eventPixelSize(4));
// The icon is half the disc: no marker is too small to read it.
assert.equal(eventPixelSize(1), 24);
assert.equal(eventPixelSize(1000), 36);
assert.equal(fresh.alpha, 1);
assert.equal(markerStyle(r, NOW + 48 * 3_600_000).alpha, 0.45);
assert.equal(reportSeverity({ category: 'political' }), 0);
assert.equal(reportSeverity({ category: 'strike' }), 1);
});
test('picture cards: physical, two or more sources, major or pressing, at most ten', () => {
const big = report('big', '2026-10-28T09:30:00Z', { event: event() });
const statement = report('st', '2026-10-28T09:30:00Z', {
category: 'political',
event: event(),
});
const lone = report('lone', '2026-10-28T09:30:00Z', {
event: event({ size: 1 }),
});
const stale = report('stale', '2026-10-28T01:00:00Z', {
event: event({ severity: 2, lastAt: '2026-10-28T01:00:00Z' }),
});
assert.equal(isPressing(big, NOW), true);
assert.deepEqual(
cardEvents([statement, lone, stale, big], NOW).map((r) => r.id),
['big'],
);
const many = Array.from({ length: 14 }, (_, i) =>
report(`m${i}`, '2026-10-28T09:30:00Z', { event: event() }),
);
assert.equal(cardEvents(many, NOW).length, 10);
const view = cardView(big, NOW);
assert.equal(view.image, 'https://a.test/p.jpg');
assert.equal(view.credit, 'A');
assert.equal(view.meta, '30 min · 6 sources · UA, RU');
assert.equal(cardView(lone, NOW).image, null);
});
test('feed cards: headline, meta parts, sides and chips', () => {
const r = report('fc', '2026-10-28T09:00:00Z', {
title: 'Удар по Харкову',
titleEn: 'Strike on Kharkiv',
affiliation: 'military',
media: ['video', 'photo'],
geo: { lat: 50, lon: 36, place: 'Kharkiv', mappable: true, byModel: true },
event: event({ lastAt: '2026-10-28T09:50:00Z' }),
});
const view = feedCardView(r, NOW);
assert.equal(view.title, 'Strike on Kharkiv');
assert.equal(view.original, 'Удар по Харкову');
assert.equal(view.placedByModel, true);
assert.equal(view.severityLabel, 'Major');
assert.equal(view.color, '#ff4444');
assert.equal(view.category, 'Strike');
assert.equal(view.place, 'Kharkiv');
assert.equal(view.sources, '6 sources');
assert.equal(view.age, '10 min');
assert.equal(view.sides, 'Reported by UA sources · RU sources');
assert.deepEqual(view.picture, { url: 'https://a.test/p.jpg', credit: 'A' });
assert.deepEqual(
view.chips.map((c) => [c.kind, c.label]),
[
['official', 'Official'],
['confirmed', 'Reported by both sides'],
['media', 'Video'],
['media', 'Photos'],
],
);
assert.deepEqual(
view.others.map((o) => o.side),
['RU'],
);
// A lone report: its own side, no picture, one source.
const single = feedCardView(report('s', '2026-10-28T09:00:00Z'), NOW);
assert.equal(single.sides, 'Reported by UA sources');
assert.equal(single.picture, null);
// A one-source event (a Telegram post) shows its picture and its clip in
// the panel, though the globe's picture cards need two sources.
const post = report('p', '2026-10-28T09:00:00Z', {
event: {
size: 1,
sides: [],
image: {
url: 'https://cdn4.telesco.pe/file/v.jpg',
publisher: 'Channel',
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
},
},
});
assert.deepEqual(feedCardView(post, NOW).picture, {
url: 'https://cdn4.telesco.pe/file/v.jpg',
credit: 'Channel',
video: 'https://cdn4.telesco.pe/file/v.mp4?token=x',
});
assert.equal(single.original, null);
assert.equal(sidesLine({ side: 'unknown' }), '');
});
test('event sides older than a day are left out of the card and its sides line', () => {
const r = report('w', '2026-10-28T09:00:00Z', {
event: event({
sides: [
{
side: 'UA',
title: 'a',
url: 'https://a.test/',
publisher: 'A',
publishedAt: '2026-10-28T08:00:00Z',
},
{
side: 'RU',
title: 'old',
url: 'https://b.test/',
publisher: 'B',
publishedAt: '2026-10-26T08:00:00Z',
},
{
side: 'unknown',
title: 'c',
url: 'https://c.test/',
publisher: 'C',
publishedAt: '2026-10-28T09:10:00Z',
},
// No date: nothing shows it is recent.
{ side: 'IL', title: 'd', url: 'https://d.test/', publisher: 'D' },
],
}),
});
const view = feedCardView(r, NOW);
assert.deepEqual(
view.others.map((o) => [o.side, o.title]),
[['Unattributed', 'c']],
);
// The unattributed side is not named in the sides line.
assert.equal(view.sides, 'Reported by UA sources');
assert.equal(cardView(r, NOW).meta, '30 min · 6 sources · UA, Unattributed');
// All sides outside the window: no others, the report's own side remains.
const stale = report('v', '2026-10-28T09:00:00Z', {
event: event({
sides: [
{
side: 'RU',
title: 'old',
url: 'https://b.test/',
publisher: 'B',
publishedAt: '2026-10-26T08:00:00Z',
},
],
}),
});
assert.deepEqual(feedCardView(stale, NOW).others, []);
assert.equal(feedCardView(stale, NOW).sides, 'Reported by UA sources');
});
test('in view: half-degree cells and reports within 500 km of the centre', () => {
assert.equal(viewCell({ lat: 50.2, lon: 36.7 }), '100:73');
assert.equal(viewCell({ lat: 50.4, lon: 36.9 }), '100:73');
assert.notEqual(viewCell({ lat: 50.6, lon: 36.7 }), '100:73');
assert.ok(
Math.abs(distanceKm({ lat: 0, lon: 0 }, { lat: 0, lon: 1 }) - 111.2) < 0.5,
);
const filters = normalizeFilters({ minSeverity: 0 });
const near = report('near', '2026-10-28T09:00:00Z', { severity: 1 });
const major = report('major', '2026-10-28T08:00:00Z', { severity: 3 });
const far = report('far', '2026-10-28T09:00:00Z', {
pins: [{ lat: 31.5, lon: 34.4, place: 'Gaza', mappable: true }],
});
const old = report('old', '2026-10-27T08:00:00Z');
const centre = { lat: 49, lon: 36 };
assert.ok(distanceKm(centre, far.pins[0]) > NEWS_IN_VIEW_RADIUS_KM);
assert.deepEqual(
reportsInView([near, far, old, major], centre, filters, NOW).map(
(r) => r.id,
),
['near', 'major'],
);
assert.deepEqual(reportsInView([near], null, filters, NOW), []);
assert.deepEqual(reportsInView([], centre, filters, NOW), []);
});
test('a server may serve fewer hours than the day, never more', () => {
assert.equal(newsWindowMs(12), 12 * 3_600_000);
assert.equal(newsWindowMs(24), 24 * 3_600_000);
for (const bad of [0, 25, 12.5, '12', null, undefined])
assert.equal(newsWindowMs(bad), 24 * 3_600_000);
const page = {
reports: [
report('fresh', '2026-10-28T02:00:00Z'),
report('old', '2026-10-27T20:00:00Z'),
],
nextBefore: null,
};
const empty = { items: [], nextBefore: null };
const ids = (windowMs) =>
mergeFeedPage(empty, page, 'replace', NOW, undefined, windowMs).items.map(
(r) => r.id,
);
assert.deepEqual(ids(newsWindowMs(12)), ['fresh']);
assert.deepEqual(ids(newsWindowMs(24)), ['fresh', 'old']);
});
test('the hotspots answer carries the window it was counted over', () => {
const base = {
hotspots: [],
ingest: { lastRunAt: '2026-10-28T09:00:00Z' },
};
assert.equal(
normalizeHotspotsPayload({ ...base, windowHours: 12 }).windowHours,
12,
);
assert.equal(normalizeHotspotsPayload(base).windowHours, null);
assert.equal(
normalizeHotspotsPayload({ ...base, windowHours: 48 }).windowHours,
null,
);
const shorter = normalizeHotspotsPayload({
...base,
windowHours: 3,
maxWindowHours: 12,
});
assert.deepEqual([shorter.windowHours, shorter.maxWindowHours], [3, 12]);
assert.equal(normalizeHotspotsPayload(base).maxWindowHours, null);
});
test('the window choices stop at the window the server serves', () => {
assert.deepEqual(newsWindowChoices(24), [24, 12, 6, 3, 1]);
assert.deepEqual(newsWindowChoices(12), [12, 6, 3, 1]);
assert.deepEqual(newsWindowChoices(8), [8, 6, 3, 1]);
assert.deepEqual(newsWindowChoices(1), [1]);
assert.deepEqual(newsWindowChoices(null), [24, 12, 6, 3, 1]);
});
test('a checked severity keeps saying who set it', () => {
const page = normalizeFeedPayload({
reports: ['label', 'model', 'guess'].map((by, i) => ({
...report(`r${i}`, '2026-10-28T09:00:00Z'),
severity: 2,
severityBy: by,
})),
});
assert.deepEqual(
page.reports.map((r) => r.severityBy),
['label', 'model', 'rules'],
);
});
+366
View File
@@ -0,0 +1,366 @@
// Validate /api/news payloads before they reach the scene or the DOM. Every
// string is bounded, every URL is http(s), every position is finite; a record
// that fails is dropped, a payload that fails is rejected whole. A portable
// export (layers/news/source): no i18n here.
const CATEGORY = /^[a-z][a-z-]{1,31}$/;
const CODE = /^[A-Za-z][A-Za-z0-9-]{0,31}$/;
const ID = /^[a-z0-9][a-z0-9_-]{0,63}$/i;
const EVENT_STATUSES = Object.freeze([
'both-sides',
'independent',
'claimed',
'reported',
'side',
'single',
]);
const text = (value, max) =>
typeof value === 'string' && value.trim()
? value.replace(/\s+/g, ' ').trim().slice(0, max)
: null;
const finite = (value, min, max) =>
Number.isFinite(value) && value >= min && value <= max ? value : null;
const iso = (value) => {
const ms = Date.parse(value);
return Number.isFinite(ms) ? new Date(ms).toISOString() : null;
};
const code = (value) =>
typeof value === 'string' && CODE.test(value) ? value : null;
const severity = (value) =>
Number.isInteger(value) && value >= 0 && value <= 3 ? value : null;
/** An http(s) URL without credentials, as its normalised href, or null. */
export function httpUrl(value) {
try {
const url = new URL(value);
return ['http:', 'https:'].includes(url.protocol) &&
!url.username &&
!url.password
? url.href
: null;
} catch {
return null;
}
}
function normalizeBbox(bbox) {
if (!Array.isArray(bbox) || bbox.length !== 4) return null;
const [west, south, east, north] = bbox;
if (
finite(west, -180, 180) === null ||
finite(east, -180, 180) === null ||
finite(south, -90, 90) === null ||
finite(north, -90, 90) === null ||
west >= east ||
south >= north
)
return null;
return [west, south, east, north];
}
/** Beacon position: the curated focus point, else the bbox centre. */
function normalizeFocus(focus, [west, south, east, north]) {
const lat = finite(focus?.lat, south, north);
const lon = finite(focus?.lon, west, east);
return lat !== null && lon !== null
? { lat, lon }
: { lat: (south + north) / 2, lon: (west + east) / 2 };
}
function normalizeDeveloping(items) {
const out = [];
for (const raw of Array.isArray(items) ? items.slice(0, 16) : []) {
const lat = finite(raw?.focus?.lat, -90, 90);
const lon = finite(raw?.focus?.lon, -180, 180);
const country =
typeof raw?.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
? raw.country
: null;
if (lat === null || lon === null || !country) continue;
// A state where the catch-all flags states ("US-FL"), else the country.
const area =
typeof raw.area === 'string' && /^[A-Z]{2}-[A-Z0-9]{1,3}$/.test(raw.area)
? raw.area
: null;
out.push({
country,
key: area || country,
name: text(raw.name, 80) || country,
events: Math.max(0, Math.floor(Number(raw.events) || 0)),
reports: Math.max(0, Math.floor(Number(raw.reports) || 0)),
focus: { lat, lon },
});
}
return out;
}
const hoursOrNull = (hours) =>
Number.isInteger(hours) && hours >= 1 && hours <= 24 ? hours : null;
/**
* `/api/news/hotspots` → `{hotspots, categories, lastRunAt, windowHours,
* maxWindowHours}`, or null when the payload has no hotspot list.
* `windowHours` is the window the counts cover and `maxWindowHours` the
* longest the server serves this reader; each is null when the server names
* none.
*/
export function normalizeHotspotsPayload(payload) {
if (!Array.isArray(payload?.hotspots)) return null;
const hotspots = [];
for (const raw of payload.hotspots.slice(0, 64)) {
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
const name = text(raw?.name, 80);
const bbox = normalizeBbox(raw?.bbox);
if (!id || !name || !bbox) continue;
const counts = raw.counts || {};
hotspots.push({
id,
name,
kind: text(raw.kind, 16) || 'conflict',
catchAll: raw.catchAll === true,
developing: normalizeDeveloping(raw.developing),
bbox,
parties: Array.isArray(raw.parties)
? raw.parties.filter((p) => code(p))
: [],
last24h: Math.max(0, Math.floor(Number(counts.last24h) || 0)),
mapped24h: Math.max(0, Math.floor(Number(counts.mapped24h) || 0)),
prev24h: Number.isFinite(counts.prev24h)
? Math.max(0, Math.floor(counts.prev24h))
: null,
focus: normalizeFocus(raw.focus, bbox),
latestAt: iso(raw.latestAt),
});
}
return {
hotspots,
categories: Array.isArray(payload.categories)
? payload.categories.filter(
(c) => typeof c === 'string' && CATEGORY.test(c),
)
: [],
lastRunAt: iso(payload.ingest?.lastRunAt),
windowHours: hoursOrNull(payload.windowHours),
maxWindowHours: hoursOrNull(payload.maxWindowHours),
};
}
function normalizeGeo(geo) {
if (!geo || typeof geo !== 'object') return null;
const lat = finite(geo.lat, -90, 90);
const lon = finite(geo.lon, -180, 180);
if (lat === null || lon === null) return null;
return {
lat,
lon,
place: text(geo.place, 80),
precision: text(geo.precision, 16) || 'city',
confidence: finite(geo.confidence, 0, 1) ?? 0,
mappable: geo.mappable === true,
byModel: geo.method === 'llm',
};
}
/**
* The event's picture: an HTTPS URL on the publisher's site, and whose it is;
* with the post's own clip when it has one a browser plays itself (an HTTPS
* MP4 or WebM file), the picture then its poster.
*/
function eventImage(image) {
const url = httpUrl(image?.url);
if (!url?.startsWith('https://')) return null;
const video = httpUrl(image.video);
const playable =
video?.startsWith('https://') &&
/\.(?:mp4|m4v|webm)$/i.test(new URL(video).pathname);
return {
url,
publisher: text(image.publisher, 80) || '',
...(playable ? { video } : {}),
};
}
/** An event summary from `/feed?events=1`: size and one report per side. */
function normalizeEvent(event) {
if (!event || typeof event !== 'object') return null;
const count = (value) => Math.max(1, Math.floor(Number(value) || 1));
const sides = [];
for (const side of Array.isArray(event.sides)
? event.sides.slice(0, 8)
: []) {
const url = httpUrl(side?.url);
const title = text(side?.title, 300);
if (!url || !title) continue;
sides.push({
side: code(side.side) || 'unknown',
title,
url,
publisher: text(side.publisher, 80) || '',
publishedAt: iso(side.publishedAt),
});
}
return {
id: typeof event.id === 'string' && ID.test(event.id) ? event.id : null,
status: EVENT_STATUSES.includes(event.status) ? event.status : null,
claimedBy: text(event.claimedBy, 80),
reportedSide: code(event.reportedSide),
size: count(event.size),
reports: count(event.reports),
severity: severity(event.severity),
firstAt: iso(event.firstAt),
lastAt: iso(event.lastAt),
sides,
image: eventImage(event.image),
};
}
function normalizeReport(raw) {
const id = typeof raw?.id === 'string' && ID.test(raw.id) ? raw.id : null;
const title = text(raw?.title, 300);
const url = httpUrl(raw?.url);
const publishedAt = iso(raw?.publishedAt);
if (!id || !title || !url || !publishedAt) return null;
const source = raw.source || {};
const geo = normalizeGeo(raw.geo);
// Map positions: the report's own place plus any other hotspot its title
// names (a roundup is pinned in each).
const pins = [];
for (const place of [
geo,
...(Array.isArray(raw.locations)
? raw.locations.slice(0, 8).map(normalizeGeo)
: []),
])
if (
place?.mappable &&
!pins.some((p) => p.lat === place.lat && p.lon === place.lon)
)
pins.push(place);
const hotspotId = typeof raw.hotspotId === 'string' ? raw.hotspotId : null;
return {
id,
hotspotId,
hotspotIds: Array.isArray(raw.hotspotIds)
? raw.hotspotIds.filter((h) => typeof h === 'string').slice(0, 8)
: [hotspotId].filter(Boolean),
title,
url,
snippet: text(raw.snippet, 400),
publisher: text(raw.publisher, 80) || text(source.name, 80) || '',
sourceName: text(source.name, 80) || text(raw.publisher, 80) || '',
kind: text(raw.kind, 16) || 'rss',
side: code(raw.side) || 'unknown',
affiliation: text(raw.affiliation, 32),
attribution: text(source.attribution, 120),
category:
typeof raw.category === 'string' && CATEGORY.test(raw.category)
? raw.category
: 'other',
publishedAt,
geo,
pins,
event: normalizeEvent(raw.event),
titleEn: text(raw.titleEn, 200),
relevance: ['core', 'related', 'minor'].includes(raw.relevance)
? raw.relevance
: 'related',
severity: severity(raw.severity),
severityBy: ['model', 'label'].includes(raw.severityBy)
? raw.severityBy
: 'rules',
claim:
raw.claim && typeof raw.claim === 'object'
? { by: text(raw.claim.by, 80) }
: null,
media: Array.isArray(raw.media)
? [...new Set(raw.media.filter((m) => m === 'video' || m === 'photo'))]
: [],
};
}
function normalizeRing(ring) {
if (!Array.isArray(ring) || ring.length < 3) return null;
const points = [];
for (const point of ring.slice(0, 20_000)) {
const lon = finite(point?.[0], -180, 180);
const lat = finite(point?.[1], -90, 90);
if (lon !== null && lat !== null) points.push([lon, lat]);
}
return points.length >= 3 ? points : null;
}
/**
* `/api/news/outline` → `{polygons, borders, disputed, area}`: the dissolved
* extent (`{outer, holes}`), the national borders inside it (rings), its
* disputed areas and, answering a point, the area named there (else null),
* invalid parts dropped.
*/
export function normalizeOutlinePayload(payload) {
const polygons = [];
// Above every country's island count (Indonesia's is 208): an outline cut
// short leaves islands outside the area, read again on each settle there.
for (const raw of Array.isArray(payload?.polygons)
? payload.polygons.slice(0, 300)
: []) {
const outer = normalizeRing(raw?.outer);
if (!outer) continue;
const holes = (Array.isArray(raw.holes) ? raw.holes.slice(0, 200) : [])
.map(normalizeRing)
.filter(Boolean);
polygons.push({ outer, holes });
}
const borders = (
Array.isArray(payload?.borders) ? payload.borders.slice(0, 50) : []
)
.map(normalizeRing)
.filter(Boolean);
const KINDS = ['held', 'self', 'un', 'unclaimed'];
const country = (value) =>
typeof value === 'string' && /^[A-Z]{2}$/.test(value) ? value : null;
const disputed = [];
for (const raw of Array.isArray(payload?.disputed)
? payload.disputed.slice(0, 30)
: []) {
const rings = (Array.isArray(raw?.rings) ? raw.rings.slice(0, 20) : [])
.map(normalizeRing)
.filter(Boolean);
const name = text(raw?.name, 60);
if (!rings.length || !name) continue;
disputed.push({
name,
kind: KINDS.includes(raw.kind) ? raw.kind : 'held',
heldBy: country(raw.heldBy),
claimedBy: country(raw.claimedBy),
rings,
});
}
return { polygons, borders, disputed, area: outlineArea(payload?.area) };
}
const AREA_KINDS = ['country', 'region', 'disputed'];
function outlineArea(raw) {
const key = text(raw?.key, 80);
const name = text(raw?.name, 80);
if (!key || !name) return null;
return {
key,
name,
kind: AREA_KINDS.includes(raw.kind) ? raw.kind : 'country',
country:
typeof raw.country === 'string' && /^[A-Z]{2}$/.test(raw.country)
? raw.country
: null,
};
}
/** `/api/news/feed` → `{reports, nextBefore}`, or null without a report list. */
export function normalizeFeedPayload(payload) {
if (!Array.isArray(payload?.reports)) return null;
const reports = [];
for (const raw of payload.reports.slice(0, 500)) {
const report = normalizeReport(raw);
if (report) reports.push(report);
}
return { reports, nextBefore: iso(payload.nextBefore) };
}
+228
View File
@@ -0,0 +1,228 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { isUnavailableCapability } from '../../sources/capability.js';
import {
normalizeFeedPayload,
normalizeHotspotsPayload,
normalizeOutlinePayload,
} from './records.js';
// A portable export (package.json): no i18n here. Failures stay English data;
// the layer shows them translated.
const msg = (text) => text;
const MAX_BYTES = 4 * 1024 * 1024;
const BASE_PATH = '/api/news';
// The outline geometry version the client draws (disputed areas included).
const OUTLINE_VERSION = '4';
/** The three read routes the news layer calls, for a host's path allowlist. */
export const NEWS_API_PATHS = Object.freeze([
`${BASE_PATH}/hotspots`,
`${BASE_PATH}/feed`,
`${BASE_PATH}/outline`,
]);
const FEED_KEYS = Object.freeze([
'hotspot',
'before',
'since',
'limit',
'category',
'relevance',
'at',
]);
const FLAG_KEYS = Object.freeze(['geo', 'today', 'events']);
const ISO = /^\d{4}-\d\d-\d\dT\d\d:\d\d:\d\d(?:\.\d{1,3})?Z$/;
const LIST = /^[a-z][a-z,-]{0,127}$/;
// A point to two decimals (~1 km), as areaPoint writes it.
const AT = /^-?\d{1,2}(?:\.\d{1,2})?,-?\d{1,3}(?:\.\d{1,2})?$/;
// A coordinate to two decimals, without trailing zeros ("50.4", "-97.74").
const areaPoint = (value) => String(Math.round(value * 100) / 100);
const FEED_VALUE = {
hotspot: (v) => /^[a-z0-9][a-z0-9_-]{0,63}$/i.test(v),
before: (v) => ISO.test(v),
since: (v) => ISO.test(v),
limit: (v) => /^\d{1,3}$/.test(v) && Number(v) >= 1 && Number(v) <= 500,
category: (v) => LIST.test(v),
relevance: (v) => LIST.test(v),
at: (v) => AT.test(v),
};
/**
* Feed query string from a plain object; unknown keys and empty values are
* dropped. `at` is a point (`{lat, lon}`), the Local section's area there.
*/
export function newsFeedQuery(query = {}) {
const params = new URLSearchParams();
for (const key of FEED_KEYS) {
const value =
key === 'at' && query.at
? `${areaPoint(query.at.lat)},${areaPoint(query.at.lon)}`
: query[key];
if (value !== undefined && value !== null && value !== '')
params.set(key, String(value));
}
for (const key of FLAG_KEYS) if (query[key]) params.set(key, '1');
return params.toString();
}
/**
* Whether a request URL is one this client sends: a known route, known keys
* only, each value in its form. A host proxying the routes can admit exactly
* these and refuse the rest.
* @param {URL} url
*/
export function newsQueryAllowed(url) {
const params = [...url.searchParams];
if (new Set(params.map(([key]) => key)).size !== params.length) return false;
if (url.pathname === `${BASE_PATH}/hotspots`)
return (
params.length === 0 ||
(params.length === 1 &&
params[0][0] === 'hours' &&
/^\d{1,2}$/.test(params[0][1]) &&
Number(params[0][1]) >= 1 &&
Number(params[0][1]) <= 24)
);
if (url.pathname === `${BASE_PATH}/outline`) {
const keys = params.map(([key]) => key).sort();
const value = url.searchParams;
return (
params.length === 2 &&
keys[1] === 'v' &&
value.get('v') === OUTLINE_VERSION &&
((keys[0] === 'hotspot' && FEED_VALUE.hotspot(value.get('hotspot'))) ||
(keys[0] === 'country' &&
/^[A-Z]{2}(?:-[A-Z0-9]{1,3})?$/.test(value.get('country'))) ||
(keys[0] === 'at' && AT.test(value.get('at'))))
);
}
if (url.pathname !== `${BASE_PATH}/feed`) return false;
return params.every(([key, value]) =>
FLAG_KEYS.includes(key)
? value === '1'
: Object.hasOwn(FEED_VALUE, key) && FEED_VALUE[key](value),
);
}
/**
* A failed read: a server without the news routes is a permanent miss; one
* that reads a section from a key it lacks (503 `no_key`, `key_rejected` or,
* its allowance for the day spent, `key_quota`, naming the key registry's id)
* says which, and is asked again later.
*/
async function responseError(response) {
let body = null;
try {
body = await readResponseJsonCapped(response, 16 * 1024);
} catch {
await response.body?.cancel?.().catch?.(() => {});
}
if (
response.status === 503 &&
['no_key', 'key_rejected', 'key_quota'].includes(body?.error) &&
typeof body.key === 'string' &&
/^[a-z][a-z0-9-]{0,31}$/.test(body.key)
)
return Object.assign(new Error(msg('News key required')), {
status: 503,
code: body.error,
keyRequired: true,
keyRejected: body.error === 'key_rejected',
keyQuota: body.error === 'key_quota',
keyId: body.key,
unavailable: false,
retryable: true,
});
const unavailable =
response.status === 404 ||
(response.status === 503 && isUnavailableCapability(body));
return Object.assign(
new Error(
unavailable
? msg('News feed not configured on this server')
: msg('News feed unavailable'),
),
{
status: response.status,
code: unavailable ? 'unavailable' : 'http',
unavailable,
retryable: !unavailable,
},
);
}
/** Read hotspots, reports and outlines from the server's /api/news routes. */
export function createNewsSource({
fetchImpl = (...args) => globalThis.fetch(...args),
timeoutMs = 15_000,
} = {}) {
async function get(path, { signal } = {}) {
signal?.throwIfAborted();
const timeout = AbortSignal.timeout(timeoutMs);
const request = signal ? AbortSignal.any([signal, timeout]) : timeout;
try {
const response = await fetchImpl(`${BASE_PATH}${path}`, {
signal: request,
cache: 'no-store',
redirect: 'error',
});
if (!response.ok) throw await responseError(response);
return await readResponseJsonCapped(response, MAX_BYTES, request);
} catch (cause) {
// Out of time the feed reads unavailable, not the browser's own words
// ("signal timed out"); the caller's own abort stays an abort.
if (timeout.aborted && !signal?.aborted)
throw Object.assign(new Error(msg('News feed unavailable')), {
code: 'timeout',
unavailable: false,
retryable: true,
});
throw cause;
}
}
return {
// `hours` asks for counts over a shorter window than the server's own.
async getHotspots({ signal, hours } = {}) {
const payload = normalizeHotspotsPayload(
await get(hours ? `/hotspots?hours=${hours}` : '/hotspots', {
signal,
}),
);
if (!payload) throw new Error(msg('Malformed news hotspots response'));
return payload;
},
async getOutline(hotspotId, { signal } = {}) {
return normalizeOutlinePayload(
await get(
`/outline?hotspot=${encodeURIComponent(hotspotId)}&v=${OUTLINE_VERSION}`,
{ signal },
),
);
},
async getCountryOutline(country, { signal } = {}) {
return normalizeOutlinePayload(
await get(
`/outline?country=${encodeURIComponent(country)}&v=${OUTLINE_VERSION}`,
{ signal },
),
);
},
// The area the Local section reads at a point, with its outline.
async getAreaOutline({ lat, lon }, { signal } = {}) {
return normalizeOutlinePayload(
await get(
`/outline?at=${areaPoint(lat)},${areaPoint(lon)}&v=${OUTLINE_VERSION}`,
{ signal },
),
);
},
async getFeed(query = {}, { signal } = {}) {
const payload = normalizeFeedPayload(
await get(`/feed?${newsFeedQuery(query)}`, { signal }),
);
if (!payload) throw new Error(msg('Malformed news feed response'));
return payload;
},
};
}
+248
View File
@@ -0,0 +1,248 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
NEWS_API_PATHS,
createNewsSource,
newsFeedQuery,
newsQueryAllowed,
} from './source.js';
const json = (body, status = 200) =>
new Response(JSON.stringify(body), {
status,
headers: { 'Content-Type': 'application/json' },
});
function recorder(respond) {
const calls = [];
return {
calls,
fetchImpl: async (url, init) => {
calls.push({ url, init });
return respond(url, init);
},
};
}
test('reads validated hotspots, feed and outlines from the same-origin routes', async () => {
const { calls, fetchImpl } = recorder((url) => {
if (url.startsWith('/api/news/hotspots'))
return json({
hotspots: [{ id: 'ua', name: 'UA', bbox: [22, 44, 42, 56] }],
});
if (url.startsWith('/api/news/feed'))
return json({
reports: [
{
id: 'r1',
title: 'T',
url: 'https://x.test/',
publishedAt: '2026-10-28T09:00:00Z',
},
],
nextBefore: null,
});
return json({ polygons: [], borders: [], disputed: [] });
});
const source = createNewsSource({ fetchImpl });
assert.equal((await source.getHotspots()).hotspots[0].id, 'ua');
assert.equal(
(await source.getFeed({ hotspot: 'all', today: true, limit: 60 }))
.reports[0].id,
'r1',
);
assert.deepEqual((await source.getOutline('ua')).polygons, []);
await source.getCountryOutline('SD');
await source.getHotspots({ hours: 6 });
await source.getAreaOutline({ lat: 30.26666, lon: -97.7 });
await source.getFeed({ hotspot: 'all', at: { lat: 30.26666, lon: -97.7 } });
assert.deepEqual(
calls.map((c) => c.url),
[
'/api/news/hotspots',
'/api/news/feed?hotspot=all&limit=60&today=1',
'/api/news/outline?hotspot=ua&v=4',
'/api/news/outline?country=SD&v=4',
'/api/news/hotspots?hours=6',
'/api/news/outline?at=30.27,-97.7&v=4',
'/api/news/feed?hotspot=all&at=30.27%2C-97.7',
],
);
for (const { url, init } of calls) {
assert.equal(init.redirect, 'error');
assert.equal(init.cache, 'no-store');
assert.ok(init.signal instanceof AbortSignal);
// Every URL the client sends is one a host's allowlist admits.
assert.equal(newsQueryAllowed(new URL(url, 'http://h')), true, url);
}
});
test('malformed, failed and unconfigured reads reject; a server without news is a permanent miss', async () => {
const malformed = createNewsSource({ fetchImpl: async () => json({}) });
await assert.rejects(malformed.getHotspots(), /Malformed news hotspots/);
await assert.rejects(malformed.getFeed(), /Malformed news feed/);
const down = createNewsSource({
fetchImpl: async () => json({ error: 'upstream' }, 502),
});
await assert.rejects(down.getHotspots(), (error) => {
assert.equal(error.message, 'News feed unavailable');
assert.equal(error.retryable, true);
assert.equal(error.unavailable, false);
return true;
});
const unconfigured = createNewsSource({
fetchImpl: async () =>
json(
{ error: 'news_not_configured', unavailable: true, retryable: false },
503,
),
});
await assert.rejects(unconfigured.getHotspots(), (error) => {
assert.equal(error.message, 'News feed not configured on this server');
assert.equal(error.code, 'unavailable');
assert.equal(error.unavailable, true);
assert.equal(error.retryable, false);
return true;
});
const missing = createNewsSource({
fetchImpl: async () => new Response('Not found', { status: 404 }),
});
await assert.rejects(missing.getFeed(), { unavailable: true });
const broken = createNewsSource({
fetchImpl: async () => new Response('{', { status: 200 }),
});
await assert.rejects(broken.getHotspots(), SyntaxError);
});
test('a section read from a key the server lacks names the key and is asked again', async () => {
const answer = (body) =>
createNewsSource({
fetchImpl: async () =>
new Response(JSON.stringify(body), {
status: 503,
headers: { 'Content-Type': 'application/json' },
}),
});
await assert.rejects(
answer({ error: 'no_key', key: 'liveuamap' }).getHotspots(),
(error) => {
assert.equal(error.keyRequired, true);
assert.equal(error.keyRejected, false);
assert.equal(error.keyId, 'liveuamap');
assert.equal(error.unavailable, false);
assert.equal(error.retryable, true);
return true;
},
);
await assert.rejects(
answer({ error: 'key_rejected', key: 'worldnewsapi' }).getFeed({
at: { lat: 51.13, lon: 71.43 },
}),
{ keyRequired: true, keyRejected: true, keyId: 'worldnewsapi' },
);
// The day's allowance spent: still the key's matter, back tomorrow.
await assert.rejects(
answer({ error: 'key_quota', key: 'worldnewsapi' }).getFeed(),
{
keyRequired: true,
keyRejected: false,
keyQuota: true,
keyId: 'worldnewsapi',
unavailable: false,
},
);
// A key name not in the registry's form is an ordinary failure.
await assert.rejects(
answer({ error: 'no_key', key: '<script>' }).getHotspots(),
(error) => error.keyRequired === undefined && error.code === 'http',
);
});
test('reads time out and follow the caller signal', async () => {
// AbortSignal.timeout does not hold the event loop open: the hanging fetch
// does, until its signal aborts, so the run cannot end before it.
const hang = (_url, { signal }) =>
new Promise((_, reject) => {
const alive = setTimeout(() => {}, 60_000);
signal.addEventListener(
'abort',
() => {
clearTimeout(alive);
reject(signal.reason);
},
{ once: true },
);
});
const slow = createNewsSource({ fetchImpl: hang, timeoutMs: 20 });
// Out of time it reads unavailable, in the app's words, as retryable.
await assert.rejects(slow.getHotspots(), {
message: 'News feed unavailable',
code: 'timeout',
retryable: true,
});
// The caller's abort stays its own, even once the time is up too.
const late = (_url, { signal }) =>
new Promise((_, reject) => {
setTimeout(() => reject(signal.reason), 40);
});
const leaving = new AbortController();
const gone = createNewsSource({ fetchImpl: late, timeoutMs: 20 }).getFeed(
{},
{ signal: leaving.signal },
);
leaving.abort(new Error('gone'));
await assert.rejects(gone, /gone/);
const caller = new AbortController();
const pending = createNewsSource({ fetchImpl: hang }).getFeed(
{},
{ signal: caller.signal },
);
caller.abort(new Error('gone'));
await assert.rejects(pending, /gone/);
await assert.rejects(
createNewsSource({ fetchImpl: hang }).getHotspots({
signal: AbortSignal.abort(new Error('already')),
}),
/already/,
);
});
test('the host allowlist admits the client routes and refuses anything else', () => {
const allowed = (path) => newsQueryAllowed(new URL(path, 'http://h'));
assert.deepEqual(NEWS_API_PATHS, [
'/api/news/hotspots',
'/api/news/feed',
'/api/news/outline',
]);
assert.equal(
allowed(
`/api/news/feed?${newsFeedQuery({ hotspot: 'ua-ru-war', before: '2026-10-28T08:00:00.000Z', limit: 500, category: 'strike', relevance: 'core,related', geo: true, today: true, events: true })}`,
),
true,
);
assert.equal(allowed('/api/news/hotspots?hours=6'), true);
for (const path of [
'/api/news/hotspots?hours=0',
'/api/news/hotspots?hours=25',
'/api/news/hotspots?hours=6&hours=3',
'/api/news/hotspots?hours=6&x=1',
'/api/news/hotspots?x=1',
'/api/news/feed?limit=501',
'/api/news/feed?limit=0',
'/api/news/feed?hotspot=all&hotspot=ua',
'/api/news/feed?since=yesterday',
'/api/news/feed?geo=yes',
'/api/news/feed?side=UA',
'/api/news/air-alerts',
'/api/news/outline?hotspot=ua',
'/api/news/outline?hotspot=ua&v=2',
'/api/news/outline?country=ukraine&v=4',
'/api/news/outline?at=30.267,-97.7&v=4',
'/api/news/outline?at=30.27&v=4',
'/api/news/outline?at=30.27,-97.7&country=US&v=4',
'/api/news/feed?at=30.267,-97.7',
])
assert.equal(allowed(path), false, path);
});
+131
View File
@@ -0,0 +1,131 @@
// Marker sprites for news reports: a dark disc with the category's icon and
// a rim in the severity colour, the rim's form telling attestation. Drawn once per look
// on a canvas and handed to Cesium as a data URL, so its texture atlas keeps
// one copy per look however often the layer re-renders.
import { NEWS_CATEGORIES, NEWS_SEVERITY } from './model.js';
const CANVAS = 64;
const BODY = 52; // disc diameter inside the canvas; the rest is rim and ring
const INK = 'rgba(10, 10, 15, 0.92)';
const SELECTED = '#00d4ff';
const COUNT_INK = '#e8eaed';
/** Canvas pixels per marker pixel: the billboard is drawn at this ratio. */
export const SPRITE_SCALE = CANVAS / BODY;
const cache = new Map();
/**
* Paint one marker look centred at (cx, cy) with a disc of `body` pixels: the
* sprites and the event cards' badges draw the same thing.
*/
export function paintMarker(ctx, { category, severity, rim }, cx, cy, body) {
const k = body / BODY; // the strokes below are tuned for the 52 px body
const r = body / 2;
// A dark edge keeps the lightest fills apart from bright ground.
ctx.beginPath();
ctx.arc(cx, cy, r + 1.5 * k, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
ctx.fill();
// GEV's dark glass disc, as its HUD buttons are; severity colours the rim
// and the icon rather than filling the disc.
ctx.beginPath();
ctx.arc(cx, cy, r, 0, 2 * Math.PI);
ctx.fillStyle = INK;
ctx.fill();
const color = (NEWS_SEVERITY[severity] || NEWS_SEVERITY[0]).color;
// Attestation is the rim's form, never its colour.
ctx.beginPath();
ctx.arc(cx, cy, r - 3 * k, 0, 2 * Math.PI);
ctx.setLineDash(rim === 'claimed' ? [7 * k, 5 * k] : []);
ctx.lineWidth = (rim === 'thin' ? 2.5 : 6) * k;
ctx.strokeStyle = color;
ctx.stroke();
ctx.setLineDash([]);
const style = NEWS_CATEGORIES[category] || NEWS_CATEGORIES.other;
const icon = body * 0.5;
ctx.save();
ctx.translate(cx - icon / 2, cy - icon / 2);
ctx.scale(icon / 16, icon / 16);
const path = new Path2D(style.icon);
ctx.lineCap = 'round';
ctx.lineJoin = 'round';
ctx.lineWidth = 1.7;
ctx.strokeStyle = color;
if (style.solid) {
ctx.fillStyle = color;
ctx.fill(path);
} else ctx.stroke(path);
ctx.restore();
}
/**
* Data URL of the sprite for a look, or null where there is no canvas (the
* layer then falls back to a plain point).
* @param {{category: string, severity: number, rim: 'confirmed'|'claimed'|'thin', selected?: boolean}} look
*/
export function markerSprite({ category, severity, rim, selected = false }) {
const key = `${category}|${severity}|${rim}|${selected ? 1 : 0}`;
if (cache.has(key)) return cache.get(key);
const canvas = globalThis.document?.createElement?.('canvas');
const ctx = canvas?.getContext?.('2d');
if (!ctx || typeof globalThis.Path2D !== 'function') return null;
canvas.width = canvas.height = CANVAS;
const c = CANVAS / 2;
paintMarker(ctx, { category, severity, rim }, c, c, BODY);
if (selected) {
ctx.beginPath();
ctx.arc(c, c, CANVAS / 2 - 2, 0, 2 * Math.PI);
ctx.lineWidth = 3.5;
ctx.strokeStyle = SELECTED;
ctx.stroke();
}
const url = canvas.toDataURL('image/png');
cache.set(key, url);
return url;
}
/**
* Data URL of a country badge: the dark disc with a light rim and the number
* of reports it stands for, drawn at the pixels it is shown at so the digits
* stay sharp. Null where there is no canvas.
* @param {number} count Reports the badge stands for.
* @param {number} pixels The disc's diameter in drawn pixels.
*/
export function countSprite(count, pixels) {
const body = Math.max(1, Math.round(pixels));
const text = count > 99 ? '99+' : String(count);
const key = `count|${text}|${body}`;
if (cache.has(key)) return cache.get(key);
const canvas = globalThis.document?.createElement?.('canvas');
const ctx = canvas?.getContext?.('2d');
if (!ctx) return null;
const k = body / BODY;
canvas.width = canvas.height = Math.round(CANVAS * k);
const c = canvas.width / 2;
const r = body / 2;
ctx.beginPath();
ctx.arc(c, c, r + 1.5 * k, 0, 2 * Math.PI);
ctx.fillStyle = 'rgba(0, 0, 0, 0.85)';
ctx.fill();
ctx.beginPath();
ctx.arc(c, c, r, 0, 2 * Math.PI);
ctx.fillStyle = INK;
ctx.fill();
ctx.beginPath();
ctx.arc(c, c, r - 2 * k, 0, 2 * Math.PI);
ctx.lineWidth = 3 * k;
ctx.strokeStyle = COUNT_INK;
ctx.stroke();
ctx.fillStyle = COUNT_INK;
ctx.font = `600 ${Math.round(body * (text.length > 2 ? 0.34 : 0.44))}px ui-monospace, Menlo, monospace`;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, c, c + k);
const url = canvas.toDataURL('image/png');
cache.set(key, url);
return url;
}
+2 -1
View File
@@ -159,7 +159,8 @@ export function buildIncidentCard(row, nowMs, { link = null } = {}) {
// the known cause, behavior and complexity values and the wording around them.
const facts = [];
if (Number.isFinite(row.acres)) {
const acres = Math.round(row.acres);
const acres =
row.acres < 1 ? Math.round(row.acres * 100) / 100 : Math.round(row.acres);
facts.push(
tn(acres, '{acres} ac', '{acres} ac', { acres: formatNumber(acres) }),
);
+31
View File
@@ -302,3 +302,34 @@ test('partial incident details render only the facts that exist', () => {
'Catron County · $85K to date',
]);
});
test('a fire under one acre keeps its WFIGS size instead of reading 0 ac', () => {
const row = {
stableId: 'x',
name: 'Grey',
acres: 0.25,
containedPct: null,
state: 'US-WA',
category: 'WF',
discoveredTime: null,
updatedTime: null,
cause: null,
behavior: null,
personnel: null,
county: null,
costToDate: null,
complexity: null,
};
assert.equal(
buildIncidentCard(row, 1758000000000).details[0],
'0.25 ac · containment unknown · US-WA',
);
assert.equal(
buildIncidentCard({ ...row, acres: 0.01 }, 1758000000000).details[0],
'0.01 ac · containment unknown · US-WA',
);
assert.equal(
buildIncidentCard({ ...row, acres: 1.4 }, 1758000000000).details[0],
'1 ac · containment unknown · US-WA',
);
});
+19 -2
View File
@@ -32,7 +32,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
1,
Math.ceil(layerState._denseIds.length / DENSE_REFRESH_FRAMES),
);
const now = new Date();
const now = new Date(layerState.now());
for (let i = 0; i < perFrame; i++) {
if (layerState._denseCursor >= layerState._denseIds.length)
layerState._denseCursor = 0;
@@ -97,7 +97,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
const entries = parts.orbits.parseTLE(text);
const style = POINT_STYLES.dense;
const now = new Date();
const now = new Date(layerState.now());
let added = 0;
for (let start = 0; start < entries.length; start += DENSE_CREATE_CHUNK) {
@@ -124,6 +124,13 @@ export function createCatalog({ state: layerState, services, parts, source }) {
satrec,
group: 'dense',
launchYear: tleLineLaunchYear(entry.line1),
line1: entry.line1,
line2: entry.line2,
// The dense feed is CelesTrak's Starlink group.
satelliteClass: 'starlink',
ucs: null,
satcat: null,
sensor: null,
});
const point = layerState._pointCollection.add({
position: Cesium.Cartesian3.fromDegrees(
@@ -165,6 +172,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
layerState._count = layerState._points.size;
layerState._catalogRevision++;
layerState.coverageChanged();
layerState._denseStatus = 'ready';
console.log(
`[Data:Satellites] Dense catalog: +${added} ${DENSE_GROUP_PATH} (points only)`,
@@ -203,6 +211,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
if (token !== layerState._denseLoadToken) return;
layerState._params.catalog = 'core';
_removeDenseCatalog();
// Back on core, Starlink is off: hide the core catalog's own Starlink
// points again, and say so in the class choice.
if (layerState._params.classes)
layerState._params.classes = {
...layerState._params.classes,
starlink: false,
};
parts.controls._applyClassVisibility?.();
layerState._denseStatus = 'failed';
layerState._denseError = reason;
parts.controls._notifyRowControls();
@@ -232,6 +248,7 @@ export function createCatalog({ state: layerState, services, parts, source }) {
layerState._denseCursor = 0;
layerState._count = layerState._points.size;
layerState._catalogRevision++;
layerState.coverageChanged();
}
return {
_abortActiveUpdates,
+765
View File
@@ -0,0 +1,765 @@
/**
* @file Satellite classes: which of six KSP-style classes an object in orbit
* belongs to, who owns it and who operates it.
*
* Classes, in legend order:
* - stations: crewed stations and the craft that visit them (ISS, Tiangong,
* Soyuz, Shenzhou, Dragon, Progress, Cygnus…), by name. The CubeSats
* CelesTrak's stations group also carries after their deployment from the
* ISS are classed like any other satellite. Retired stations and the
* shuttles have re-entered, so they have no orbit to show.
* - imaging: Earth observation of every kind (optical, radar, multispectral,
* hyperspectral, weather, Earth science, surveillance).
* - telecom: communications and navigation (GEO comsats, Iridium, OneWeb,
* GPS, GLONASS, Galileo, BeiDou…), Starlink excepted.
* - starlink: the Starlink constellation.
* - probes: other working payloads (space science, technology development and
* demonstration, education, unknown purpose).
* - debris: rocket bodies, fragments, unknown objects and payloads that no
* longer work. Shown and tracked on request, never ridden in the Cockpit.
*
* The evidence, strongest first: CelesTrak SATCAT's object type and
* operational status (current, so it overrules UCS on a satellite that has
* died since), the UCS Satellite Database's purpose (May 2023), name patterns
* for satellites launched after it, and the CelesTrak group the TLE came in.
* Pure: no Cesium, no fetches, so the tables are unit-tested directly.
*
* @module satelliteClasses
*/
import { msg } from '../../i18n/index.js';
/** Class ids in legend order. */
export const SATELLITE_CLASS_IDS = Object.freeze([
'stations',
'imaging',
'telecom',
'starlink',
'probes',
'debris',
]);
/**
* Which classes show when nobody has chosen: everything the layer showed
* before classes existed. Starlink stays off, as the DENSE switch was.
*/
export const DEFAULT_SATELLITE_CLASSES = Object.freeze({
stations: true,
imaging: true,
telecom: true,
starlink: false,
probes: true,
debris: true,
});
/**
* Point colour and the legend and chip text for each class. Colours reuse the
* layer's established palette (src/data/satelliteClass.js); debris recedes.
*/
export const SATELLITE_CLASS_DISPLAY = Object.freeze({
stations: Object.freeze({
color: '#fff6e5',
label: msg('STATIONS'),
blurb: msg('Crewed stations and the craft that visit them'),
}),
imaging: Object.freeze({
color: '#4fd8ff',
label: msg('IMAGING'),
blurb: msg('Earth observation: optical, radar, weather and science'),
}),
telecom: Object.freeze({
color: '#c89bff',
label: msg('TELECOM'),
blurb: msg('Communications and navigation satellites, Starlink excepted'),
}),
starlink: Object.freeze({
color: '#54697f',
label: msg('STARLINK'),
blurb: msg('The Starlink constellation (thousands of extra points)'),
}),
probes: Object.freeze({
color: '#9fb3c4',
label: msg('PROBES'),
blurb: msg('Space science, technology demonstration and other payloads'),
}),
debris: Object.freeze({
color: '#7d7468',
label: msg('DEBRIS'),
blurb: msg('Rocket bodies, fragments and dead satellites'),
}),
});
/** The ISS, a station whatever else says. */
const ISS_NORAD = 25544;
/** SATCAT object types that are never a working payload. */
const DEBRIS_OBJECT_TYPES = new Set(['R/B', 'DEB']);
/**
* SATCAT files a new launch's objects as UNK until it identifies them, so an
* unknown object launched within this many calendar years (2: this year or
* last) is not presumed debris. Years, not dates: the TLE designator, the
* fallback when SATCAT has no launch date, carries only the year.
*/
export const UNIDENTIFIED_GRACE_YEARS = 2;
/** SATCAT operational status: nonoperational, decayed. */
const DEAD_STATUSES = new Set(['-', 'D']);
/** SATCAT operational status left blank or unknown. */
const UNKNOWN_STATUSES = new Set(['', '?']);
/**
* A payload whose SATCAT record gives no status, with no UCS record and no
* recognisable name, that launched this many years ago is presumed dead (old
* weather and science satellites the "visual" group keeps for their
* brightness). Without a SATCAT record (a failed read) nothing is presumed.
*/
export const PRESUMED_DEAD_AFTER_YEARS = 20;
const DEBRIS_NAME = /\bR\/B\b|\bDEB\b|\bAKM\b|ROCKET BODY/i;
const STATION_NAME =
/^(ISS\b|TIANGONG|TIANHE|WENTIAN|MENGTIAN|CSS\b|SHENZHOU|TIANZHOU|SOYUZ|PROGRESS|CREW DRAGON|DRAGON|CYGNUS|STARLINER|HTV\b|AXIOM)/i;
const STARLINK_NAME = /^STARLINK/i;
const IMAGING_NAME =
/^(SENTINEL|LANDSAT|WORLDVIEW|GEOEYE|PLEIADES|SPOT[ -]\d|ICEYE|CAPELLA|UMBRA|FLOCK|SKYSAT|PELICAN|SUPERDOVE|DOVE\b|NOAA[ -]?\d|GOES|METEOSAT|METOP|HIMAWARI|FENGYUN|FY-?\d|GAOFEN|JILIN|SUPERVIEW|KOMPSAT|RADARSAT|RCM-|TERRA\b|AQUA\b|SUOMI NPP|JPSS|CARTOSAT|RESOURCESAT|RISAT|EOS-\d|ALOS|COSMO-SKYMED|CSG-|TERRASAR|TANDEM-X|PAZ\b|SAOCOM|KANOPUS|RESURS|METEOR-M|ELEKTRO-L|ARKTIKA-M|YAOGAN|NUSAT|NEWSAT|BLACKSKY|GLOBAL-\d|GHGSAT|LEMUR|HAIYANG|HY-\d|ZIYUAN|ZY-\d|TIANHUI|SWOT|ICESAT|GRACE|CRYOSAT|SMAP|SMOS|PROBA-V|DEIMOS|THEOS|GOKTURK|EROS|OFEQ|OPTSAT|PRISMA|ENMAP|NISAR|BIOMASS|EARTHCARE|FORMOSAT|CBERS|AMAZONIA|SICH|DMSP|ELECTRO)/i;
const TELECOM_NAME =
/^(ONEWEB|IRIDIUM|GLOBALSTAR|ORBCOMM|INTELSAT|IS-\d|SES[ -]?\d|ASTRA|EUTELSAT|INMARSAT|VIASAT|ECHOSTAR|DIRECTV|SIRIUS|XM-|TDRS|NAVSTAR|GPS\b|GLONASS|GSAT0|GALILEO|BEIDOU|QZS|IRNSS|NVS-|KUIPER|LYNK|BLUEBIRD|O3B|TELESAT|ANIK|NIMIQ|AMAZONAS|HISPASAT|ARABSAT|NILESAT|TURKSAT|YAMAL|EXPRESS-|CHINASAT|ZHONGXING|APSTAR|ASIASAT|THAICOM|MEASAT|JCSAT|SUPERBIRD|OPTUS|SKYNET|WGS|MUOS|AEHF|MILSTAR|QIANFAN|GUOWANG|SPACEMOBILE|GONETS|MERIDIAN|LUCH|RADUGA|SKYTERRA|TERRESTAR|SPACEWAY|HYLAS|ARSAT|AMOS|BADR|KA-SAT|YAHSAT|THURAYA)/i;
const IMAGING_PURPOSE =
/earth observation|earth\/space observation|earth science|meteorolog|surveillance/i;
const TELECOM_PURPOSE = /communications|navigation|positioning/i;
/**
* CelesTrak groups whose members are, by default, of one class. Not
* stations: it also carries CubeSats deployed from the ISS.
*/
const GROUP_CLASS = Object.freeze({
dense: 'starlink',
starlink: 'starlink',
resource: 'imaging',
weather: 'imaging',
planet: 'imaging',
sar: 'imaging',
'gps-ops': 'telecom',
glonass: 'telecom',
'glo-ops': 'telecom',
galileo: 'telecom',
geo: 'telecom',
science: 'probes',
});
/** CelesTrak groups named for an orbit, not a mission: the last resort. */
const ORBIT_GROUPS = new Set(['geo']);
/** The year of a SATCAT launch date (`2024-03-15`), or null. */
function launchYearOf(launchDate) {
const match = /^(\d{4})-/.exec(String(launchDate || ''));
return match ? Number(match[1]) : null;
}
/**
* The class a satellite belongs to.
* @param {{noradId?: number, name?: string, group?: string|null,
* groups?: string[]|null,
* ucs?: {purpose?: string|null}|null,
* satcat?: {objectType?: string, opsStatus?: string,
* launchDate?: string|null}|null,
* launchYear?: number|null, nowYear?: number}} subject `groups` is every
* CelesTrak group the TLE came in (`group` is the one it is shown under):
* the first of them that names a class gives the last-resort class, so a
* satellite in both `visual` and `resource` is still imaging. `launchYear` is
* the TLE designator's; SATCAT's launch date wins where it has one (an
* object deployed from the ISS carries the station's 1998 designator).
* @returns {'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris'}
*/
export function classifySatellite({
noradId,
name = '',
group = null,
ucs = null,
satcat = null,
groups = null,
launchYear = null,
nowYear = new Date().getUTCFullYear(),
} = {}) {
if (noradId === ISS_NORAD) return 'stations';
const label = String(name || '').trim();
const objectType = satcat?.objectType || null;
const status = satcat?.opsStatus ?? null;
const launched = launchYearOf(satcat?.launchDate) ?? launchYear;
const recent =
Number.isFinite(launched) && nowYear - launched < UNIDENTIFIED_GRACE_YEARS;
if (objectType && DEBRIS_OBJECT_TYPES.has(objectType)) return 'debris';
if (objectType === 'UNK' && !recent) return 'debris';
if (!objectType && DEBRIS_NAME.test(label)) return 'debris';
if (status !== null && DEAD_STATUSES.has(status)) return 'debris';
// CelesTrak's stations group also carries the CubeSats deployed from the
// ISS (they share its 1998-067 designator): only a station or a visiting
// craft, by name, is a station.
if (STATION_NAME.test(label)) return 'stations';
if (group === 'dense' || STARLINK_NAME.test(label)) return 'starlink';
// UCS writes "Unknown" for a purpose it does not know: no evidence.
const purpose = /^unknown$/i.test(ucs?.purpose || '')
? ''
: ucs?.purpose || '';
if (IMAGING_PURPOSE.test(purpose)) return 'imaging';
if (TELECOM_PURPOSE.test(purpose)) return 'telecom';
if (purpose) return 'probes';
if (IMAGING_NAME.test(label)) return 'imaging';
if (TELECOM_NAME.test(label)) return 'telecom';
// UCS lists working satellites only: a payload it never knew, whose SATCAT
// record gives no status and whose launch is decades old, is presumed
// dead. Without a SATCAT record (its read failed or has not landed) there
// is no evidence either way, so nothing is presumed.
if (
satcat &&
UNKNOWN_STATUSES.has(status ?? '') &&
Number.isFinite(launched) &&
nowYear - launched >= PRESUMED_DEAD_AFTER_YEARS
)
return 'debris';
// A mission group (weather, resource, science…) says more than an orbit
// group: a weather satellite in geostationary orbit is in both.
const memberships = groups?.length ? groups : [group];
for (const membership of [
...memberships.filter((m) => !ORBIT_GROUPS.has(m)),
...memberships.filter((m) => ORBIT_GROUPS.has(m)),
])
if (GROUP_CLASS[membership]) return GROUP_CLASS[membership];
return 'probes';
}
/** Whether a class may be ridden in the Cockpit's orbital view. */
export function satelliteClassEnterable(satelliteClass) {
return (
SATELLITE_CLASS_IDS.includes(satelliteClass) && satelliteClass !== 'debris'
);
}
/**
* Merge a partial class-visibility request into the current choice.
* Unknown keys and non-boolean values are ignored.
* @param {Record<string, unknown>|null|undefined} request
* @param {Record<string, boolean>} [current]
* @returns {Record<string, boolean>}
*/
export function mergeClassVisibility(
request,
current = DEFAULT_SATELLITE_CLASSES,
) {
const next = {};
for (const id of SATELLITE_CLASS_IDS) {
const value = request?.[id];
next[id] = typeof value === 'boolean' ? value : current[id] === true;
}
return next;
}
// ISO 3166-1 alpha-2 code → short English name, for every owner below.
const COUNTRY_NAMES = Object.freeze({
AE: 'United Arab Emirates',
AM: 'Armenia',
AO: 'Angola',
AR: 'Argentina',
AT: 'Austria',
AU: 'Australia',
AZ: 'Azerbaijan',
BD: 'Bangladesh',
BE: 'Belgium',
BG: 'Bulgaria',
BH: 'Bahrain',
BM: 'Bermuda',
BO: 'Bolivia',
BR: 'Brazil',
BT: 'Bhutan',
BW: 'Botswana',
BY: 'Belarus',
CA: 'Canada',
CH: 'Switzerland',
CL: 'Chile',
CN: 'China',
CO: 'Colombia',
CR: 'Costa Rica',
CZ: 'Czechia',
DE: 'Germany',
DJ: 'Djibouti',
DK: 'Denmark',
DZ: 'Algeria',
EC: 'Ecuador',
EE: 'Estonia',
EG: 'Egypt',
ES: 'Spain',
ET: 'Ethiopia',
FI: 'Finland',
FR: 'France',
GB: 'United Kingdom',
GH: 'Ghana',
GR: 'Greece',
GT: 'Guatemala',
HR: 'Croatia',
HU: 'Hungary',
ID: 'Indonesia',
IE: 'Ireland',
IL: 'Israel',
IN: 'India',
IQ: 'Iraq',
IR: 'Iran',
IT: 'Italy',
JO: 'Jordan',
JP: 'Japan',
KE: 'Kenya',
KP: 'North Korea',
KR: 'South Korea',
KW: 'Kuwait',
KZ: 'Kazakhstan',
LA: 'Laos',
LK: 'Sri Lanka',
LT: 'Lithuania',
LU: 'Luxembourg',
MA: 'Morocco',
MC: 'Monaco',
MD: 'Moldova',
ME: 'Montenegro',
MM: 'Myanmar',
MN: 'Mongolia',
MU: 'Mauritius',
MX: 'Mexico',
MY: 'Malaysia',
NG: 'Nigeria',
NL: 'Netherlands',
NO: 'Norway',
NP: 'Nepal',
NZ: 'New Zealand',
PE: 'Peru',
PH: 'Philippines',
PK: 'Pakistan',
PL: 'Poland',
PT: 'Portugal',
PY: 'Paraguay',
QA: 'Qatar',
RO: 'Romania',
RU: 'Russia',
RW: 'Rwanda',
SA: 'Saudi Arabia',
SB: 'Solomon Islands',
SD: 'Sudan',
SE: 'Sweden',
SG: 'Singapore',
SI: 'Slovenia',
SN: 'Senegal',
TH: 'Thailand',
TM: 'Turkmenistan',
TN: 'Tunisia',
TR: 'Türkiye',
TW: 'Taiwan',
UA: 'Ukraine',
US: 'United States',
UY: 'Uruguay',
VA: 'Vatican City',
VE: 'Venezuela',
VN: 'Vietnam',
ZA: 'South Africa',
ZW: 'Zimbabwe',
});
/**
* Every owner country a satellite can be marked with, sorted: the flags
* `scripts/build-owner-flags.mjs` draws into the owner flag sheet.
*/
export const OWNER_COUNTRY_CODES = Object.freeze(
Object.keys(COUNTRY_NAMES).sort(),
);
// UCS "Country of Operator/Owner" → ISO code. Joint owners ("USA/Japan") and
// organisations are not countries and resolve through ORGANISATIONS or as a
// joint label.
const UCS_COUNTRIES = Object.freeze({
Algeria: 'DZ',
Angola: 'AO',
Argentina: 'AR',
Australia: 'AU',
Austria: 'AT',
Azerbaijan: 'AZ',
Bangladesh: 'BD',
Belarus: 'BY',
Belgium: 'BE',
Bolivia: 'BO',
Brazil: 'BR',
Bulgaria: 'BG',
Canada: 'CA',
Chile: 'CL',
China: 'CN',
Colombia: 'CO',
'Czech Republic': 'CZ',
Denmark: 'DK',
Ecuador: 'EC',
Egypt: 'EG',
Estonia: 'EE',
Ethiopia: 'ET',
Finland: 'FI',
France: 'FR',
Germany: 'DE',
Greece: 'GR',
Hungary: 'HU',
India: 'IN',
Indonesia: 'ID',
Iran: 'IR',
Iraq: 'IQ',
Israel: 'IL',
Italy: 'IT',
Japan: 'JP',
Jordan: 'JO',
Kazakhstan: 'KZ',
Kenya: 'KE',
Kuwait: 'KW',
Laos: 'LA',
Lithuania: 'LT',
Luxembourg: 'LU',
Malaysia: 'MY',
Mexico: 'MX',
Monaco: 'MC',
Morocco: 'MA',
Nepal: 'NP',
Netherlands: 'NL',
'New Zealand': 'NZ',
Nigeria: 'NG',
Norway: 'NO',
Pakistan: 'PK',
Peru: 'PE',
Poland: 'PL',
Russia: 'RU',
'Saudi Arabia': 'SA',
Sinapore: 'SG',
Singapore: 'SG',
Slovenia: 'SI',
'South Africa': 'ZA',
'South Korea': 'KR',
Spain: 'ES',
Sudan: 'SD',
Sweden: 'SE',
Switzerland: 'CH',
Taiwan: 'TW',
Thailand: 'TH',
Tunisia: 'TN',
Turkey: 'TR',
UK: 'GB',
USA: 'US',
Ukraine: 'UA',
'United Arab Emirates': 'AE',
'United Kingdom': 'GB',
Venezuela: 'VE',
Vietnam: 'VN',
});
// CelesTrak SATCAT OWNER code → ISO code (https://celestrak.org/satcat/sources.php).
// CIS (former USSR) is filed under Russia, its continuing state.
const SATCAT_COUNTRIES = Object.freeze({
ALG: 'DZ',
ANG: 'AO',
ARGN: 'AR',
ARM: 'AM',
ASRA: 'AT',
AUS: 'AU',
AZER: 'AZ',
BEL: 'BE',
BELA: 'BY',
BERM: 'BM',
BGD: 'BD',
BHR: 'BH',
BHUT: 'BT',
BOL: 'BO',
BRAZ: 'BR',
BUL: 'BG',
BWA: 'BW',
CA: 'CA',
CHLE: 'CL',
CIS: 'RU',
COL: 'CO',
CRI: 'CR',
CZCH: 'CZ',
DEN: 'DK',
DJI: 'DJ',
ECU: 'EC',
EGYP: 'EG',
EST: 'EE',
ETH: 'ET',
FIN: 'FI',
FR: 'FR',
GER: 'DE',
GHA: 'GH',
GREC: 'GR',
GUAT: 'GT',
HRV: 'HR',
HUN: 'HU',
IND: 'IN',
INDO: 'ID',
IRAN: 'IR',
IRAQ: 'IQ',
IRL: 'IE',
ISRA: 'IL',
ISRO: 'IN',
IT: 'IT',
JPN: 'JP',
KAZ: 'KZ',
KEN: 'KE',
LAOS: 'LA',
LKA: 'LK',
LTU: 'LT',
LUXE: 'LU',
MA: 'MA',
MALA: 'MY',
MCO: 'MC',
MDA: 'MD',
MEX: 'MX',
MMR: 'MM',
MNE: 'ME',
MNG: 'MN',
MUS: 'MU',
NETH: 'NL',
NIG: 'NG',
NKOR: 'KP',
NOR: 'NO',
NPL: 'NP',
NZ: 'NZ',
PAKI: 'PK',
PERU: 'PE',
POL: 'PL',
POR: 'PT',
PRC: 'CN',
PRY: 'PY',
QAT: 'QA',
ROC: 'TW',
ROM: 'RO',
RP: 'PH',
RWA: 'RW',
SAFR: 'ZA',
SAUD: 'SA',
SDN: 'SD',
SEN: 'SN',
SING: 'SG',
SKOR: 'KR',
SLB: 'SB',
SPN: 'ES',
SVN: 'SI',
SWED: 'SE',
SWTZ: 'CH',
THAI: 'TH',
TUN: 'TN',
TURK: 'TR',
UAE: 'AE',
UK: 'GB',
UKR: 'UA',
URY: 'UY',
US: 'US',
VAT: 'VA',
VENZ: 'VE',
VTNM: 'VN',
ZWE: 'ZW',
});
// Organisations, by SATCAT code and by UCS name: no flag, a short label.
const ORGANISATIONS = Object.freeze({
AB: 'Arabsat',
ABS: 'ABS',
AC: 'AsiaSat',
ESA: 'ESA',
ESRO: 'ESRO',
EUME: 'EUMETSAT',
EUTE: 'Eutelsat',
GLOB: 'Globalstar',
IM: 'Inmarsat',
IRID: 'Iridium',
ISS: 'ISS partners',
ITSO: 'Intelsat',
NATO: 'NATO',
NICO: 'New ICO',
O3B: 'O3b',
ORB: 'ORBCOMM',
RASC: 'RascomStar-QAF',
SEAL: 'Sea Launch',
SES: 'SES',
Multinational: 'Multinational',
});
// SATCAT codes for joint ownership, as their parts.
const SATCAT_JOINT = Object.freeze({
CHBZ: ['CN', 'BR'],
CHTU: ['CN', 'TR'],
FGER: ['FR', 'DE'],
FRIT: ['FR', 'IT'],
GRSA: ['GR', 'SA'],
PRES: ['CN', 'ESA'],
SGJP: ['SG', 'JP'],
STCT: ['SG', 'TW'],
TMMC: ['TM', 'MC'],
USBZ: ['US', 'BR'],
});
function country(code) {
return COUNTRY_NAMES[code]
? { countryCode: code, label: COUNTRY_NAMES[code] }
: null;
}
function joint(parts) {
const labels = parts.map(
(part) => COUNTRY_NAMES[part] || ORGANISATIONS[part] || part,
);
return { countryCode: null, label: labels.join(' / ') };
}
/**
* Normalise a UCS owner country ("USA", "China/France", "ESA",
* "Multinational") to `{ countryCode, label }`.
* @param {string|null|undefined} text
* @returns {{countryCode: string|null, label: string}|null}
*/
export function ownerFromUcs(text) {
const value = String(text || '').trim();
if (!value) return null;
if (UCS_COUNTRIES[value]) return country(UCS_COUNTRIES[value]);
if (ORGANISATIONS[value])
return { countryCode: null, label: ORGANISATIONS[value] };
if (value.includes('/'))
return joint(
value
.split('/')
.map((part) => part.trim())
.map((part) => UCS_COUNTRIES[part] || part),
);
return { countryCode: null, label: value };
}
/**
* Normalise a CelesTrak SATCAT OWNER code ("US", "PRC", "CIS", "ITSO") to
* `{ countryCode, label }`; null for TBD, UNK and blanks.
* @param {string|null|undefined} code
* @returns {{countryCode: string|null, label: string}|null}
*/
export function ownerFromSatcat(code) {
const value = String(code || '')
.trim()
.toUpperCase();
if (!value || value === 'TBD' || value === 'UNK') return null;
if (SATCAT_COUNTRIES[value]) return country(SATCAT_COUNTRIES[value]);
if (ORGANISATIONS[value])
return { countryCode: null, label: ORGANISATIONS[value] };
if (SATCAT_JOINT[value]) return joint(SATCAT_JOINT[value]);
return null;
}
/**
* Who owns a satellite: UCS names the operator's country, SATCAT the
* registering owner; UCS wins where both exist. Starlink without either is
* SpaceX's, so United States.
* @returns {{countryCode: string|null, label: string}|null}
*/
export function satelliteOwner({
ucs = null,
satcat = null,
satelliteClass,
} = {}) {
return (
ownerFromUcs(ucs?.operatorCountry) ||
ownerFromSatcat(satcat?.owner) ||
(satelliteClass === 'starlink' ? country('US') : null)
);
}
/** Who operates a satellite: UCS's operator, or SpaceX for Starlink. */
export function satelliteOperator({ ucs = null, satelliteClass } = {}) {
if (ucs?.operator) return ucs.operator;
return satelliteClass === 'starlink' ? 'SpaceX' : null;
}
/**
* The international designator (COSPAR id) from TLE line 1, columns 10–17:
* `98067A` → `1998-067A`. Two-digit years below 57 are 20xx.
* @param {string|null|undefined} line1
* @returns {string|null}
*/
export function cosparIdFromTleLine1(line1) {
const field = String(line1 || '')
.slice(9, 17)
.trim();
const match = /^(\d{2})(\d{3})([A-Z]{1,3})$/.exec(field);
if (!match) return null;
const yy = Number(match[1]);
return `${yy < 57 ? 2000 + yy : 1900 + yy}-${match[2]}${match[3]}`;
}
/**
* The TLE's epoch as epoch milliseconds, from satellite.js's Julian date.
* @param {{jdsatepoch?: number, jdsatepochF?: number}|null|undefined} satrec
* @returns {number|null}
*/
export function tleEpochMs(satrec) {
const jd = Number(satrec?.jdsatepoch) + (Number(satrec?.jdsatepochF) || 0);
return Number.isFinite(jd) && jd > 0
? Math.round((jd - 2440587.5) * 86_400_000)
: null;
}
/** Split one RFC 4180 CSV line (quoted fields may hold commas). */
function csvFields(line) {
const fields = [];
let field = '';
let quoted = false;
for (let i = 0; i < line.length; i++) {
const ch = line[i];
if (quoted) {
if (ch === '"' && line[i + 1] === '"') {
field += '"';
i++;
} else if (ch === '"') quoted = false;
else field += ch;
} else if (ch === '"') quoted = true;
else if (ch === ',') {
fields.push(field);
field = '';
} else field += ch;
}
fields.push(field);
return fields;
}
/**
* Parse CelesTrak SATCAT CSV into records keyed by NORAD number.
* @param {string} text `records.php?…&FORMAT=CSV` body.
* @returns {Map<number, {objectType: string, opsStatus: string,
* owner: string, cosparId: string|null, launchDate: string|null}>}
*/
export function parseSatcatCsv(text) {
const records = new Map();
const lines = String(text || '')
.split(/\r?\n/)
.filter((line) => line.trim());
if (!lines.length) return records;
const header = csvFields(lines[0]).map((name) => name.trim());
const at = (name) => header.indexOf(name);
const col = {
norad: at('NORAD_CAT_ID'),
type: at('OBJECT_TYPE'),
status: at('OPS_STATUS_CODE'),
owner: at('OWNER'),
id: at('OBJECT_ID'),
launch: at('LAUNCH_DATE'),
};
if (col.norad < 0 || col.type < 0) return records;
for (const line of lines.slice(1)) {
const fields = csvFields(line);
const noradId = Number(fields[col.norad]);
if (!Number.isInteger(noradId) || noradId <= 0) continue;
const text = (index) => (index < 0 ? '' : (fields[index] ?? '').trim());
records.set(noradId, {
objectType: text(col.type).toUpperCase(),
opsStatus: text(col.status),
owner: text(col.owner),
cosparId: text(col.id) || null,
launchDate: text(col.launch) || null,
});
}
return records;
}
+473
View File
@@ -0,0 +1,473 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { twoline2satrec } from 'satellite.js';
import {
DEFAULT_SATELLITE_CLASSES,
PRESUMED_DEAD_AFTER_YEARS,
SATELLITE_CLASS_DISPLAY,
SATELLITE_CLASS_IDS,
classifySatellite,
cosparIdFromTleLine1,
mergeClassVisibility,
ownerFromSatcat,
ownerFromUcs,
parseSatcatCsv,
satelliteClassEnterable,
satelliteOperator,
satelliteOwner,
tleEpochMs,
} from './classes.js';
import { CATALOG_GROUPS } from './policy.js';
const NOW = 2026;
const classify = (subject) => classifySatellite({ nowYear: NOW, ...subject });
test('six classes, with stations and imaging on by default and the rest off', () => {
assert.deepEqual(SATELLITE_CLASS_IDS, [
'stations',
'imaging',
'telecom',
'starlink',
'probes',
'debris',
]);
assert.deepEqual(
SATELLITE_CLASS_IDS.filter((id) => DEFAULT_SATELLITE_CLASSES[id]),
['stations', 'imaging', 'telecom', 'probes', 'debris'],
);
for (const id of SATELLITE_CLASS_IDS) {
const display = SATELLITE_CLASS_DISPLAY[id];
assert.match(display.color, /^#[0-9a-f]{6}$/, id);
assert.ok(display.label && display.blurb, id);
}
});
test('SATCAT object type and status file debris first, overruling UCS', () => {
const imaging = { purpose: 'Earth Observation' };
for (const objectType of ['R/B', 'DEB', 'UNK'])
assert.equal(classify({ name: 'X', satcat: { objectType, opsStatus: '' } }), 'debris', objectType);
// A satellite UCS listed in 2023 that SATCAT now calls dead or decayed.
for (const opsStatus of ['-', 'D'])
assert.equal(
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus } }),
'debris',
opsStatus,
);
assert.equal(
classify({ name: 'OLDSAT', ucs: imaging, satcat: { objectType: 'PAY', opsStatus: '+' } }),
'imaging',
);
// SATCAT calls a new launch's objects UNK until it names them: only an
// old unknown object, or one with no launch date, is debris.
assert.equal(
classify({
name: 'OBJECT C',
group: 'resource',
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2025-11-02' },
}),
'imaging',
);
assert.equal(
classify({
name: 'OBJECT C',
group: 'resource',
satcat: { objectType: 'UNK', opsStatus: '', launchDate: '2019-04-01' },
}),
'debris',
);
// Debris riding in the stations group (CelesTrak lists FREGAT DEB there).
assert.equal(classify({ name: 'FREGAT DEB', group: 'stations' }), 'debris');
assert.equal(classify({ name: 'SL-16 R/B', group: 'visual' }), 'debris');
});
test('the ISS is a station whatever else says', () => {
assert.equal(
classify({ noradId: 25544, name: 'ISS (ZARYA)', group: 'visual', satcat: { objectType: 'DEB' } }),
'stations',
);
});
test('stations: crewed stations and visiting vehicles by name', () => {
assert.equal(classify({ name: 'CSS (TIANHE)', group: 'stations' }), 'stations');
assert.equal(classify({ name: 'ISS (NAUKA)', group: 'stations' }), 'stations');
for (const name of ['SHENZHOU-21', 'TIANZHOU-9', 'SOYUZ-MS 28', 'PROGRESS-MS 31', 'CREW DRAGON 11', 'CYGNUS NG-23'])
assert.equal(classify({ name, group: 'visual' }), 'stations', name);
});
test('UCS purpose decides imaging, telecom and probes', () => {
const table = [
['Earth Observation', 'imaging'],
['Earth Science', 'imaging'],
['Meteorological', 'imaging'],
['Surveillance', 'imaging'],
['Earth Observation/Navigation', 'imaging'],
['Earth/Space Observation', 'imaging'],
['Communications', 'telecom'],
['Navigation/Global Positioning', 'telecom'],
['Navigation/Regional Positioning', 'telecom'],
['Technology Development', 'probes'],
['Technology Demonstration', 'probes'],
['Space Science', 'probes'],
['Unknown', 'probes'],
];
for (const [purpose, expected] of table)
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', ucs: { purpose } }), expected, purpose);
});
test('satellites launched after the UCS snapshot are classed by name', () => {
const table = [
['ICEYE-X50', 'imaging'],
['CAPELLA-17', 'imaging'],
['FLOCK 4Y-12', 'imaging'],
['PELICAN-3', 'imaging'],
['SENTINEL-1C', 'imaging'],
['LANDSAT 9', 'imaging'],
['GOES 19', 'imaging'],
['ONEWEB-0712', 'telecom'],
['IRIDIUM 180', 'telecom'],
['GPS BIII-8 (PRN 14)', 'telecom'],
['KUIPER-00042', 'telecom'],
['STARLINK-34012', 'starlink'],
];
for (const [name, expected] of table)
assert.equal(classify({ name, group: 'visual', launchYear: 2025 }), expected, name);
});
test('the group the TLE came in is the last resort', () => {
assert.equal(classify({ name: 'UNNAMED-1', group: 'resource', launchYear: 2024 }), 'imaging');
assert.equal(classify({ name: 'UNNAMED-1', group: 'geo', launchYear: 2024 }), 'telecom');
assert.equal(classify({ name: 'UNNAMED-1', group: 'science', launchYear: 2024 }), 'probes');
assert.equal(classify({ name: 'STARLINK-1', group: 'dense' }), 'starlink');
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 2024 }), 'probes');
});
test('CubeSats deployed from the ISS are not stations', () => {
// They ride in CelesTrak's stations group under the ISS's 1998 designator.
for (const name of ['DUPLEX', 'KNACKSAT-2', 'GXIBA-1', 'LEOPARD', 'HMU-SAT2']) {
assert.equal(
classify({ name, group: 'stations', launchYear: 1998 }),
'probes',
`${name} without SATCAT`,
);
assert.equal(
classify({
name,
group: 'stations',
launchYear: 1998,
satcat: { objectType: 'PAY', opsStatus: '', launchDate: '2025-04-21' },
}),
'probes',
`${name}: SATCAT's 2025 launch, not the designator's 1998`,
);
}
assert.equal(
classify({ name: 'UNNAMED-1', group: 'stations', ucs: { purpose: 'Earth Observation' } }),
'imaging',
);
});
test('an unknown old payload is presumed dead; a recognisable one is not', () => {
const old = NOW - PRESUMED_DEAD_AFTER_YEARS;
assert.equal(
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963 }),
'probes',
'without a SATCAT record (a failed read) nothing is presumed',
);
assert.equal(
classify({ name: 'ATLAS CENTAUR 2', group: 'visual', launchYear: 1963, satcat: { objectType: 'PAY', opsStatus: '' } }),
'debris',
'a blank SATCAT status is no evidence of life',
);
assert.equal(classify({ name: 'UNNAMED-1', group: 'visual', launchYear: old + 1 }), 'probes');
assert.equal(classify({ name: 'NOAA 15', group: 'weather', launchYear: 1998 }), 'imaging');
assert.equal(
classify({ name: 'UNNAMED-1', group: 'visual', launchYear: 1990, satcat: { objectType: 'PAY', opsStatus: '+' } }),
'probes',
'SATCAT says it works',
);
});
test('only debris is refused the Cockpit', () => {
for (const id of SATELLITE_CLASS_IDS)
assert.equal(satelliteClassEnterable(id), id !== 'debris', id);
assert.equal(satelliteClassEnterable('nonsense'), false);
});
test('class visibility merges booleans and ignores everything else', () => {
const next = mergeClassVisibility({ telecom: true, imaging: false, debris: 'yes', bogus: true });
assert.deepEqual(next, { ...DEFAULT_SATELLITE_CLASSES, telecom: true, imaging: false });
assert.deepEqual(mergeClassVisibility(null), { ...DEFAULT_SATELLITE_CLASSES });
assert.equal(Object.hasOwn(next, 'bogus'), false);
});
test('UCS owner countries normalise to ISO codes, organisations and joint owners', () => {
assert.deepEqual(ownerFromUcs('USA'), { countryCode: 'US', label: 'United States' });
assert.deepEqual(ownerFromUcs('United Kingdom'), { countryCode: 'GB', label: 'United Kingdom' });
assert.deepEqual(ownerFromUcs('Sinapore'), { countryCode: 'SG', label: 'Singapore' }, 'UCS typo');
assert.deepEqual(ownerFromUcs('Turkey'), { countryCode: 'TR', label: 'Türkiye' });
assert.deepEqual(ownerFromUcs('ESA'), { countryCode: null, label: 'ESA' });
assert.deepEqual(ownerFromUcs('Multinational'), { countryCode: null, label: 'Multinational' });
assert.deepEqual(ownerFromUcs('China/France'), { countryCode: null, label: 'China / France' });
assert.deepEqual(ownerFromUcs('United Kingdom/ESA'), { countryCode: null, label: 'United Kingdom / ESA' });
assert.equal(ownerFromUcs(''), null);
assert.equal(ownerFromUcs(null), null);
});
test('SATCAT owner codes normalise the same way', () => {
assert.deepEqual(ownerFromSatcat('US'), { countryCode: 'US', label: 'United States' });
assert.deepEqual(ownerFromSatcat('PRC'), { countryCode: 'CN', label: 'China' });
assert.deepEqual(ownerFromSatcat('CIS'), { countryCode: 'RU', label: 'Russia' }, 'former USSR');
assert.deepEqual(ownerFromSatcat('ISRO'), { countryCode: 'IN', label: 'India' });
assert.deepEqual(ownerFromSatcat('itso'), { countryCode: null, label: 'Intelsat' });
assert.deepEqual(ownerFromSatcat('EUME'), { countryCode: null, label: 'EUMETSAT' });
assert.deepEqual(ownerFromSatcat('PRES'), { countryCode: null, label: 'China / ESA' });
assert.deepEqual(ownerFromSatcat('TMMC'), { countryCode: null, label: 'Turkmenistan / Monaco' });
for (const code of ['TBD', 'UNK', '', null, 'ZZZZ']) assert.equal(ownerFromSatcat(code), null, String(code));
});
test('owner prefers UCS, falls back to SATCAT, and Starlink is American', () => {
assert.deepEqual(
satelliteOwner({ ucs: { operatorCountry: 'ESA' }, satcat: { owner: 'FR' } }),
{ countryCode: null, label: 'ESA' },
);
assert.deepEqual(satelliteOwner({ satcat: { owner: 'FR' } }), { countryCode: 'FR', label: 'France' });
assert.deepEqual(satelliteOwner({ satelliteClass: 'starlink' }), { countryCode: 'US', label: 'United States' });
assert.equal(satelliteOwner({}), null);
assert.equal(satelliteOperator({ ucs: { operator: 'Planet Labs, Inc.' } }), 'Planet Labs, Inc.');
assert.equal(satelliteOperator({ satelliteClass: 'starlink' }), 'SpaceX');
assert.equal(satelliteOperator({ satelliteClass: 'imaging' }), null);
});
const ISS_LINE1 = '1 25544U 98067A 24001.50000000 .00016717 00000-0 30370-3 0 9993';
const ISS_LINE2 = '2 25544 51.6416 247.4627 0006703 130.5360 325.0288 15.50377579432323';
test('COSPAR ids come from TLE line 1, across the 1957 century pivot', () => {
assert.equal(cosparIdFromTleLine1(ISS_LINE1), '1998-067A');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '24123BC ')), '2024-123BC');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', '57001A ')), '1957-001A');
assert.equal(cosparIdFromTleLine1(ISS_LINE1.replace('98067A ', ' ')), null);
assert.equal(cosparIdFromTleLine1(null), null);
});
test('the TLE epoch is read as epoch milliseconds', () => {
const satrec = twoline2satrec(ISS_LINE1, ISS_LINE2);
// Day 001.5 of 2024: 1 January 2024, 12:00 UTC.
assert.ok(Math.abs(tleEpochMs(satrec) - Date.UTC(2024, 0, 1, 12)) < 1000);
assert.equal(tleEpochMs(null), null);
assert.equal(tleEpochMs({}), null);
});
test('SATCAT CSV parses, quoted commas included, keyed by NORAD id', () => {
const csv = [
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER,LAUNCH_DATE',
'ISS (ZARYA),1998-067A,25544,PAY,+,ISS,1998-11-20',
'"THOR AGENA, D R/B",1964-002A,733,r/b,,US,1964-01-19',
'BROKEN,,notanumber,PAY,+,US,',
'',
].join('\r\n');
const records = parseSatcatCsv(csv);
assert.deepEqual([...records.keys()], [25544, 733]);
assert.deepEqual(records.get(25544), {
objectType: 'PAY',
opsStatus: '+',
owner: 'ISS',
cosparId: '1998-067A',
launchDate: '1998-11-20',
});
assert.equal(records.get(733).objectType, 'R/B');
assert.equal(parseSatcatCsv('<html>busy</html>').size, 0);
assert.equal(parseSatcatCsv('').size, 0);
});
test('turning Stations off takes the ISS ring and label with its point', async () => {
const { createControls } = await import('./controls.js');
let overlaySyncs = 0;
const ring = { primitive: { show: true } };
const state = {
_enabled: true,
_params: {
catalog: 'core',
showOrbits: true,
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
},
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
_points: new Map([[25544, { show: true }]]),
_orbitPaths: new Map([[25544, ring]]),
_detectionObjects: new Map(),
_trackedNorad: null,
};
const controls = createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: { labels: { _syncIssOverlay: () => (overlaySyncs += 1) } },
source: {},
});
controls._applyClassVisibility();
assert.equal(state._points.get(25544).show, false);
assert.equal(ring.primitive.show, false, 'the ring goes with the class');
assert.ok(overlaySyncs >= 1, 'the label is re-synced');
state._params.classes = { ...DEFAULT_SATELLITE_CLASSES };
controls._applyClassVisibility();
assert.equal(ring.primitive.show, true, 'and comes back with it');
});
test('a failed Starlink load hides the core catalog Starlink points again', async () => {
const { createCatalog } = await import('./catalog.js');
let applied = 0;
const state = {
_params: {
catalog: 'dense',
classes: { ...DEFAULT_SATELLITE_CLASSES, starlink: true },
},
_denseLoadToken: 3,
_denseIds: [],
_catalog: new Map(),
_points: new Map(),
_detectionObjects: new Map(),
_trackedNorad: null,
_activeUpdateControllers: new Set(),
coverageChanged() {},
};
const catalog = createCatalog({
state,
services: {},
parts: {
controls: {
_applyClassVisibility: () => (applied += 1),
_notifyRowControls() {},
},
labels: { _syncIssOverlay() {} },
},
source: {},
});
catalog._denseLoadFailed(state._denseLoadToken, 'feed unreachable');
assert.equal(state._params.catalog, 'core');
assert.equal(state._params.classes.starlink, false, 'the choice says so');
assert.ok(applied >= 1, 'class visibility is applied again');
});
test('every ingested group names the class its unnamed members fall back to', () => {
// A group added to CATALOG_GROUPS without a class would file its members
// under PROBES, the catch-all.
const expected = {
stations: 'probes',
visual: 'probes',
'gps-ops': 'telecom',
glonass: 'telecom',
galileo: 'telecom',
geo: 'telecom',
resource: 'imaging',
weather: 'imaging',
planet: 'imaging',
sar: 'imaging',
science: 'probes',
};
assert.deepEqual(
Object.fromEntries(
CATALOG_GROUPS.map(({ tag }) => [
tag,
classify({ noradId: 99999, name: 'UNNAMED-1', group: tag }),
]),
),
expected,
);
});
test('enabling the layer leaves a hidden Stations class without its ISS ring', async () => {
const { createLifecycle } = await import('./lifecycle.js');
const iss = { primitive: { show: false } };
const other = { primitive: { show: false } };
let issVisible = false;
const state = {
_params: { showPoints: true, showOrbits: true },
_orbitPaths: new Map([
[25544, iss],
[90001, other],
]),
_points: new Map(),
coverageChanged() {},
};
const { methods } = createLifecycle({
state,
services: {
focus: { clearFocusTarget() {} },
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
},
parts: {
controls: {
satelliteVisualsVisible: (enabled, on) => enabled && on !== false,
_issOrbitVisible: () => issVisible,
},
labels: { _syncIssOverlay() {} },
interaction: { _installClickHandler() {} },
tracking: { _applyPendingTrackingRestore() {} },
rendering: {},
},
});
methods.enable(null);
assert.equal(iss.primitive.show, false, 'the ISS ring follows its class');
assert.equal(other.primitive.show, true, 'other rings follow showOrbits');
issVisible = true;
methods.enable(null);
assert.equal(iss.primitive.show, true);
});
test('a mission group outranks an orbit group, and an Unknown UCS purpose is no evidence', () => {
assert.equal(
classify({ name: 'MTG-X1', group: 'geo', groups: ['geo', 'weather'] }),
'imaging',
);
assert.equal(
classify({ name: 'UNNAMED-1', group: 'geo', groups: ['geo'] }),
'telecom',
);
assert.equal(
classify({
name: 'GPS BIII-9',
group: 'visual',
ucs: { purpose: 'Unknown' },
}),
'telecom',
);
assert.equal(
classify({
name: 'UNNAMED-1',
group: 'resource',
ucs: { purpose: 'Unknown' },
}),
'imaging',
);
});
test('a tracked ISS keeps its ring while Stations is hidden', async () => {
const { createControls } = await import('./controls.js');
const ring = { primitive: { show: true } };
const state = {
_enabled: true,
_params: {
catalog: 'core',
showOrbits: true,
classes: { ...DEFAULT_SATELLITE_CLASSES, stations: false },
},
_catalog: new Map([[25544, { satelliteClass: 'stations' }]]),
_points: new Map([[25544, { show: true }]]),
_orbitPaths: new Map([[25544, ring]]),
_detectionObjects: new Map(),
_trackedNorad: null,
};
const controls = createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: { labels: { _syncIssOverlay() {} } },
source: {},
});
controls._syncIssOrbit();
assert.equal(ring.primitive.show, false);
state._trackedNorad = 25544;
controls._syncIssOrbit();
assert.equal(ring.primitive.show, true, 'tracked, it keeps its ring');
state._params.showOrbits = false;
controls._syncIssOrbit();
assert.equal(ring.primitive.show, false, 'orbits off still hides it');
});
+332
View File
@@ -0,0 +1,332 @@
import * as Cesium from 'cesium';
import { satelliteClassText } from '../../data/satelliteClass.js';
import {
classifySatellite,
cosparIdFromTleLine1,
satelliteClassEnterable,
satelliteOperator,
satelliteOwner,
tleEpochMs,
} from './classes.js';
import { ISS_NORAD } from './policy.js';
/** The layer id a satellite subject carries through Cockpit events and state. */
export const SATELLITE_COCKPIT_LAYER_ID = 'satellites';
/**
* While the Cockpit rides a satellite, every other orbit ring (the ISS ring
* included) draws at this fraction of its normal alpha, so the rings stay
* legible without competing with the nadir picture.
*/
export const COCKPIT_ORBIT_DIM_FACTOR = 0.3;
/**
* Write an orbit ring's alpha as a multiple of the alpha it was built with.
* The ring's per-instance attributes exist only once Cesium has updated the
* primitive; until then nothing is written and the next tick retries.
* @param {{primitive: object, instanceId: string, baseColor: Cesium.Color,
* baseDepthFailColor: Cesium.Color, alphaFactor: number}} path
* @param {number} factor 1 restores the built colours exactly.
* @returns {boolean} True when the ring now carries `factor`.
*/
export function applyOrbitPathAlpha(path, factor) {
if (!path?.primitive || !path.baseColor) return false;
if ((path.alphaFactor ?? 1) === factor) return true;
let attributes;
try {
attributes = path.primitive.getGeometryInstanceAttributes?.(
path.instanceId,
);
} catch {
return false;
}
if (!attributes) return false;
const scaled = (color) => color.withAlpha(color.alpha * factor);
attributes.color = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseColor : scaled(path.baseColor),
);
attributes.depthFailColor = Cesium.ColorGeometryInstanceAttribute.toValue(
factor === 1 ? path.baseDepthFailColor : scaled(path.baseDepthFailColor),
);
path.alphaFactor = factor;
return true;
}
/**
* Who and what a catalog entry is: class, COSPAR id, TLE, owner, operator.
* Fixed for the entry's life, so it is worked out once and kept on it.
* @param {number} noradId
* @param {object} sat Catalog entry.
*/
function satelliteIdentity(noradId, sat) {
if (sat.cockpitIdentity) return sat.cockpitIdentity;
const satelliteClass =
sat.satelliteClass ||
classifySatellite({ noradId, name: sat.name, group: sat.group });
const epochMs = tleEpochMs(sat.satrec);
const identity = Object.freeze({
satelliteClass,
cosparId: sat.satcat?.cosparId || cosparIdFromTleLine1(sat.line1),
tle:
sat.line1 && sat.line2 && epochMs !== null
? Object.freeze({ line1: sat.line1, line2: sat.line2, epochMs })
: null,
owner: freezeOwner(
satelliteOwner({ ucs: sat.ucs, satcat: sat.satcat, satelliteClass }),
),
operator: satelliteOperator({ ucs: sat.ucs, satelliteClass }),
// src/layers/satellites/sensors.js entry, or null: the orbital view's sensor swath.
sensor: sat.sensor ?? null,
});
sat.cockpitIdentity = identity;
return identity;
}
function freezeOwner(owner) {
return owner
? Object.freeze({
countryCode: owner.countryCode ?? null,
label: owner.label ?? null,
})
: null;
}
/**
* Normalize the tracked satellite and its per-frame fix into Cockpit subject
* info, in the shape every Cockpit subject kind shares.
* @param {number} noradId NORAD catalog number.
* @param {{name?: string, group?: string}|null} sat Catalog entry.
* @param {{latitude: number, longitude: number, altitude: number,
* speedMps?: number|null, groundTrackDeg?: number|null, atMs?: number}|null}
* fix Per-frame SGP4 sample (orbits.js propagatePosition), at `atMs`.
* @returns {object|null} Subject info, or null without a usable fix.
*/
export function satelliteCockpitInfo(noradId, sat, fix) {
if (!sat || !fix) return null;
const { latitude, longitude, altitude } = fix;
if (![latitude, longitude, altitude].every(Number.isFinite)) return null;
const isIss = noradId === ISS_NORAD;
const identity = satelliteIdentity(noradId, sat);
return {
kind: 'satellite',
layerId: SATELLITE_COCKPIT_LAYER_ID,
id: String(noradId),
noradId,
name: sat.name?.trim() || `SAT-${noradId}`,
// Localized at read time, as the vessel layer's type label is.
classLabel: satelliteClassText(identity.satelliteClass, sat.group, {
isIss,
}),
latitude,
longitude,
altitudeM: altitude,
// SGP4's TEME velocity: the inertial orbital speed, not ground speed.
velocityMps: Number.isFinite(fix.speedMps) ? fix.speedMps : null,
// The time the position is at (epoch ms), the satellites' world-clock
// time; null when the sample does not say.
atMs: Number.isFinite(fix.atMs) ? fix.atMs : null,
// Degrees clockwise from north; null for a geostationary satellite.
groundTrackDeg: Number.isFinite(fix.groundTrackDeg)
? fix.groundTrackDeg
: null,
stale: false,
// src/layers/satellites/classes.js: 'stations'|'imaging'|'telecom'|'starlink'|
// 'probes'|'debris'.
satelliteClass: identity.satelliteClass,
// Whether its class may be ridden in the orbital view (debris may not);
// the Cockpit's entry gate reads it (orbitEntryAllowed).
enterable: satelliteClassEnterable(identity.satelliteClass),
// International designator, e.g. '1998-067A'.
cosparId: identity.cosparId,
tle: identity.tle,
// { countryCode: ISO 3166-1 alpha-2 or null (organisations, joint
// owners), label: English name } or null.
owner: identity.owner,
operator: identity.operator,
sensor: identity.sensor,
};
}
/**
* The tracked satellite as a Cockpit orbital-view subject, and the hold that
* hides its own marks while the Cockpit camera rides it.
*
* While held, the tracked dot is hidden (it would sit on the lens), as are
* the point primitives of docked companions (they share the position within
* 2 km) and the subject's orbit ring: a nadir camera on the ring sees its far
* side, dimmed by the ring's depth-fail appearance, drawn straight across the
* Earth's disk. The detection overlay skips the subject too. The tracked
* card needs nothing here: its overlay source already hides in Cockpit mode.
* Every other orbit ring is dimmed to COCKPIT_ORBIT_DIM_FACTOR of its alpha
* while a subject is set; other satellites' points and labels stay as they
* are. Scene clicks and the layer's Escape are ignored while held, so the
* picture cannot untrack its own subject. Release restores exactly what the
* hold hid or dimmed.
*/
export function createCockpitSubject({ state: layerState, parts }) {
/** The subject is held only while it is the tracked satellite. */
function _cockpitHeld() {
return (
layerState._cockpitSubjectNorad !== null &&
layerState._cockpitSubjectNorad === layerState._trackedNorad
);
}
function _setPointShown(noradId, show) {
const point = layerState._points.get(noradId);
// Released points go back to their class's visibility.
if (point) point.show = show && parts.controls._classVisible(noradId);
}
/**
* Apply or release the hold. Idempotent, and cheap enough for the preRender
* tick, which re-applies it while held so catalog rebuilds, enable and the
* orbit toggle cannot re-show what the hold hides.
* @returns {void}
*/
function _syncCockpitSubjectVisuals() {
const held = _cockpitHeld();
const tracked = layerState._trackedNorad;
const dot = layerState._trackedEntity?.point;
if (held) {
if (dot) dot.show = false;
layerState._cockpitHiddenDot = true;
} else if (layerState._cockpitHiddenDot) {
if (dot) dot.show = true;
layerState._cockpitHiddenDot = false;
}
const hiddenPoints = layerState._cockpitHiddenPoints;
const companions = held ? layerState._dockedCompanions : new Set();
for (const noradId of [...hiddenPoints]) {
if (companions.has(noradId)) continue;
hiddenPoints.delete(noradId);
// The tracked primitive stays hidden: its entity draws the dot.
if (noradId !== tracked) _setPointShown(noradId, true);
}
// Re-applied every sync: a catalog rebuild replaces the point
// primitives, and the new ones arrive shown.
for (const noradId of companions) {
if (noradId === tracked) continue;
hiddenPoints.add(noradId);
_setPointShown(noradId, false);
}
if (held) {
const trackedPoint = layerState._points.get(tracked);
if (trackedPoint) trackedPoint.show = false;
}
const hiddenPath = layerState._cockpitHiddenPath;
if (hiddenPath !== null && (!held || hiddenPath !== tracked)) {
const path = layerState._orbitPaths.get(hiddenPath);
// The ISS's ring also follows its class (and its tracking).
if (path && hiddenPath === ISS_NORAD) parts.controls._syncIssOrbit();
else if (path)
path.primitive.show = parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
layerState._cockpitHiddenPath = null;
}
if (held) {
const path = layerState._orbitPaths.get(tracked);
if (path) {
path.primitive.show = false;
layerState._cockpitHiddenPath = tracked;
}
}
// Every other ring is dimmed for the whole session and restored on
// release; rebuilt rings arrive at full alpha and are dimmed again here.
const subject = layerState._cockpitSubjectNorad;
for (const [noradId, path] of layerState._orbitPaths) {
const dim = subject !== null && noradId !== subject;
applyOrbitPathAlpha(path, dim ? COCKPIT_ORBIT_DIM_FACTOR : 1);
}
}
const methods = {
/**
* The tracked satellite as Cockpit subject info, from the same per-frame
* SGP4 sample the dot and the follow camera use.
* @returns {{kind: 'satellite', layerId: 'satellites', id: string,
* noradId: number, name: string, classLabel: string,
* latitude: number, longitude: number, altitudeM: number,
* velocityMps: number|null, stale: false,
* satelliteClass: 'stations'|'imaging'|'telecom'|'starlink'|'probes'|'debris',
* cosparId: string|null,
* tle: {line1: string, line2: string, epochMs: number}|null,
* owner: {countryCode: string|null, label: string|null}|null,
* operator: string|null}|null} Null while the layer is off or nothing
* is tracked.
*/
getCockpitSubject() {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
const noradId = layerState._trackedNorad;
return satelliteCockpitInfo(
noradId,
layerState._catalog.get(noradId),
parts.tracking._getTrackedFramePosition(),
);
},
/**
* The tracked satellite's Earth-fixed position this frame: the per-frame
* cache the dot and follow camera read, never a separate propagation.
* @param {Cesium.Cartesian3} [result] Receives the position.
* @returns {Cesium.Cartesian3|null} Null while the layer is off, nothing
* is tracked or no sample has propagated.
*/
getCockpitPosition(result) {
if (!layerState._enabled || layerState._trackedNorad === null)
return null;
if (!parts.tracking._getTrackedFramePosition()) return null;
return Cesium.Cartesian3.clone(layerState._trackedFrameCartesian, result);
},
/**
* Mark the satellite whose position the Cockpit camera occupies, or
* release it. The hold applies while that satellite is tracked.
* @param {string|number|null} noradId Subject NORAD id, or null to release.
* @returns {boolean} Always true.
*/
setCockpitSubject(noradId) {
const next =
noradId === null || noradId === undefined
? null
: parts.tracking._normalizeTrackedNorad(noradId);
if (layerState._cockpitSubjectNorad === next) return true;
layerState._cockpitSubjectNorad = next;
_syncCockpitSubjectVisuals();
return true;
},
/**
* Put the follow camera back on the tracked satellite after the Cockpit
* released it, without re-tracking (no new selection or context events).
* @param {string|number} noradId The satellite the Cockpit rode.
* @returns {boolean} True when that satellite is still tracked and the
* follow camera was restored.
*/
refocusTrackedById(noradId) {
const id = parts.tracking._normalizeTrackedNorad(noradId);
const viewer = layerState._viewer;
const entity = layerState._trackedEntity;
if (
id === null ||
id !== layerState._trackedNorad ||
!viewer ||
!entity ||
!viewer.entities?.contains?.(entity)
)
return false;
viewer.camera?.cancelFlight?.();
viewer.trackedEntity = entity;
return true;
},
};
return { _cockpitHeld, _syncCockpitSubjectVisuals, methods };
}
@@ -0,0 +1,604 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createOrbits } from './orbits.js';
import { createLabels } from './labels.js';
import { createTracking } from './tracking.js';
import { createRendering } from './rendering.js';
import { createCatalog } from './catalog.js';
import { createLifecycle } from './lifecycle.js';
import { createInteraction } from './interaction.js';
import { createIngestion } from './ingestion.js';
import {
COCKPIT_ORBIT_DIM_FACTOR,
applyOrbitPathAlpha,
createCockpitSubject,
satelliteCockpitInfo,
} from './cockpitSubject.js';
import { groundTrackBearingDeg } from './orbits.js';
import { indexImagingSensors } from './sensors.js';
import { ISS_NORAD } from './policy.js';
const COMPANION = 25545;
const GPS = 32711;
function tle(name, id, motion = '15.48899044', inclination = ' 51.6326') {
// Owned synthetic element sets; never live requests. The station pair
// share elements, so the companion is docked to the ISS.
return `${name}\n1 ${id}U 98067A 26289.78971908 .00007803 00000+0 15012-3 0 9995\n2 ${id} ${inclination} 58.3278 0006748 271.9059 88.1156 ${motion}590607`;
}
const GROUP_TEXT = {
stations: [
tle('ISS (ZARYA)', ISS_NORAD),
tle('PROGRESS-MS 31', COMPANION),
].join('\n'),
'gps-ops': tle('GPS FIXTURE', GPS, ' 2.00563000', ' 55.0000'),
};
/** Whether the tracked entity draws its dot (an unset show is shown). */
function dotShown(f) {
const show = f.state._trackedEntity.point.show;
return show === undefined ? true : show.getValue();
}
const SATCAT_HEADER =
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER';
const SATCAT_TEXT = {
stations: [
SATCAT_HEADER,
`ISS (ZARYA),1998-067A,${ISS_NORAD},PAY,+,ISS`,
`PROGRESS-MS 31,2026-001A,${COMPANION},PAY,+,CIS`,
].join('\n'),
// No designator: the TLE's is used.
'gps-ops': [SATCAT_HEADER, `GPS FIXTURE,,${GPS},PAY,+,US`].join('\n'),
};
const UCS = new Map([
[
ISS_NORAD,
{
noradId: ISS_NORAD,
operator: 'NASA/Multinational',
operatorCountry: 'Multinational',
purpose: 'Space Science',
},
],
]);
// One sensor entry, matched by NORAD number, for the orbital zoom cap.
const SENSORS = indexImagingSensors({
entries: [
{
id: 'fixture-imager',
label: 'Fixture imager',
match: { norad: [GPS] },
narrowestSwathKm: 50,
swathConfirmed: true,
sources: ['https://example.test/spec'],
},
],
});
async function fixture(t) {
const source = {
async readGroup(group) {
const text = GROUP_TEXT[group] || '';
return { ok: true, status: 200, text, stale: false };
},
async readSatcat(group) {
return { ok: true, status: 200, text: SATCAT_TEXT[group] || '' };
},
readUcs: async () => UCS,
readSensors: async () => SENSORS,
};
const noop = () => {};
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
},
layerState: { isExplicitLayerStateOrigin: () => false },
focus: {
clearFocusTarget: noop,
publishFocusTargetFromCachedPosition: noop,
getFocusTarget: () => null,
focusNowMs: (now) => now,
focusPassIsNeeded: () => false,
},
context: {
clearTrackedSubjectContext: noop,
getContextStore: () => ({ entities: new Map() }),
refreshTrackedSubjectContext: noop,
selectTrackedSubjectContext: noop,
},
readout: { refreshTrackedReadout: noop },
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
};
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
for (const [name, factory] of Object.entries({
controls: createControls,
orbits: createOrbits,
labels: createLabels,
tracking: createTracking,
rendering: createRendering,
catalog: createCatalog,
interaction: createInteraction,
lifecycle: createLifecycle,
ingestion: createIngestion,
cockpit: createCockpitSubject,
})) {
parts[name] = factory(context);
}
const viewer = {
trackedEntity: undefined,
entities: new Cesium.EntityCollection(),
scene: {
canvas: new EventTarget(),
primitives: new Cesium.PrimitiveCollection(),
preRender: new Cesium.Event(),
frameState: { frameNumber: 1 },
},
trackedEntityChanged: new Cesium.Event(),
};
const { log, warn } = console;
console.log = noop;
console.warn = noop;
await parts.lifecycle.methods.init(viewer);
await parts.ingestion.methods.update(viewer);
parts.lifecycle.methods.enable(viewer);
// GPS is TELECOM; these tests need its point on screen whatever the default.
parts.controls.methods.setParams({ classes: { telecom: true } });
Object.assign(console, { log, warn });
t.after(() => {
console.log = noop;
if (state._pointCollection) parts.lifecycle.methods.destroy(viewer);
console.log = log;
viewer.scene.primitives.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
const methods = { ...parts.controls.methods, ...parts.cockpit.methods };
return {
state,
parts,
viewer,
methods,
track(id) {
const log = console.log;
console.log = noop;
try {
return methods.trackById(id);
} finally {
console.log = log;
}
},
nextFrame() {
viewer.scene.frameState.frameNumber += 1;
parts.rendering._preRenderTick();
},
ring: (id) => state._orbitPaths.get(id)?.primitive,
detected: () =>
methods.getDetectableObjects().map((object) => object.sourceId),
};
}
test('no subject while the layer is off or nothing is tracked', async (t) => {
const f = await fixture(t);
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
assert.equal(f.track(ISS_NORAD), true);
f.state._enabled = false;
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.methods.getCockpitPosition(), null);
});
test('the tracked satellite is a subject read from the per-frame sample', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const propagate = f.parts.orbits.propagatePosition;
let propagations = 0;
f.parts.orbits.propagatePosition = (...args) => {
propagations += 1;
return propagate(...args);
};
f.viewer.scene.frameState.frameNumber += 1;
const subject = f.methods.getCockpitSubject();
const position = f.methods.getCockpitPosition();
f.methods.getCockpitSubject();
assert.equal(propagations, 1, 'one SGP4 sample per frame for every reader');
assert.equal(subject.kind, 'satellite');
assert.equal(subject.layerId, 'satellites');
assert.equal(subject.id, String(ISS_NORAD));
assert.equal(subject.noradId, ISS_NORAD);
assert.equal(subject.name, 'ISS (ZARYA)');
assert.equal(subject.classLabel, 'STATIONS · ISS');
assert.equal(subject.stale, false);
assert.ok(subject.altitudeM > 150e3 && subject.altitudeM < 1000e3);
assert.ok(subject.velocityMps > 7000 && subject.velocityMps < 8000);
// The same point the tracked dot and follow camera use, as a copy.
const cached = f.state._trackedFrameCartesian;
assert.ok(Cesium.Cartesian3.equals(position, cached));
assert.notEqual(position, cached);
const target = new Cesium.Cartesian3();
assert.equal(f.methods.getCockpitPosition(target), target);
const geodetic = Cesium.Cartographic.fromCartesian(position);
assert.ok(
Math.abs(Cesium.Math.toDegrees(geodetic.latitude) - subject.latitude) <
1e-6,
);
f.parts.orbits.propagatePosition = propagate;
});
test('the subject says what it is, which TLE it flies, and who owns and runs it', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
const iss = f.methods.getCockpitSubject();
assert.equal(iss.satelliteClass, 'stations');
assert.equal(iss.cosparId, '1998-067A');
assert.match(iss.tle.line1, /^1 25544U/);
assert.match(iss.tle.line2, /^2 25544 /);
// Day 289.789… of 2026.
assert.ok(
Math.abs(
iss.tle.epochMs - (Date.UTC(2026, 0, 1) + 288.78971908 * 86_400_000),
) < 1000,
);
assert.deepEqual(
iss.owner,
{ countryCode: null, label: 'Multinational' },
'UCS before SATCAT',
);
assert.equal(iss.operator, 'NASA/Multinational');
assert.equal(
f.methods.getCockpitSubject().owner,
iss.owner,
'worked out once',
);
f.track(GPS);
const gps = f.methods.getCockpitSubject();
assert.equal(gps.satelliteClass, 'telecom');
assert.equal(
gps.cosparId,
'1998-067A',
'from TLE line 1 when SATCAT has none',
);
assert.deepEqual(gps.owner, { countryCode: 'US', label: 'United States' });
assert.equal(gps.operator, null);
// The sensor pack is matched once, at ingestion.
assert.equal(gps.sensor?.id, 'fixture-imager');
assert.equal(gps.sensor.narrowestSwathKm, 50);
assert.equal(iss.sensor, null, 'no sensor entry, no extra zoom');
// A bare catalog entry still answers every field.
const bare = satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(bare.satelliteClass, 'telecom');
// An imaging satellite CelesTrak lists among the brightest objects names
// its class, not the 'visual' group it came in.
const landsat = satelliteCockpitInfo(
49260,
{ name: 'LANDSAT 9', group: 'visual', satelliteClass: 'imaging' },
{ latitude: 1, longitude: 2, altitude: 3 },
);
assert.equal(landsat.classLabel, 'IMAGING');
assert.equal(bare.tle, null);
assert.equal(bare.owner, null);
assert.equal(bare.operator, null);
assert.equal(bare.cosparId, null);
});
test('a GNSS satellite carries its class and an orbital speed', async (t) => {
const f = await fixture(t);
f.track(GPS);
const subject = f.methods.getCockpitSubject();
assert.equal(subject.classLabel, 'TELECOM · GPS');
assert.ok(subject.altitudeM > 19e6 && subject.altitudeM < 21.5e6);
assert.ok(subject.velocityMps > 3500 && subject.velocityMps < 4200);
assert.equal(
satelliteCockpitInfo(
GPS,
{ name: 'X', group: 'gps-ops' },
{
latitude: 1,
longitude: 2,
altitude: 3,
},
).velocityMps,
null,
);
assert.equal(satelliteCockpitInfo(GPS, null, { latitude: 0 }), null);
});
test('holding the subject hides its dot, ring, docked companions and bracket', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
assert.ok(f.state._dockedCompanions.has(COMPANION));
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.ok(f.detected().includes(ISS_NORAD));
assert.equal(f.methods.setCockpitSubject(String(ISS_NORAD)), true);
assert.equal(dotShown(f), false);
assert.equal(f.ring(ISS_NORAD).show, false);
assert.equal(f.state._points.get(COMPANION).show, false);
assert.equal(f.state._points.get(GPS).show, true);
assert.ok(!f.detected().includes(ISS_NORAD));
// Toggling orbits on again cannot bring the ring back while held.
f.methods.setParams({ showOrbits: true });
assert.equal(f.ring(ISS_NORAD).show, true);
f.nextFrame();
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.setCockpitSubject(null);
assert.equal(dotShown(f), true);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
// The tracked primitive stays hidden: the tracked entity draws the dot.
assert.equal(f.state._points.get(ISS_NORAD).show, false);
assert.ok(f.detected().includes(ISS_NORAD));
});
test('a subject that is not tracked holds nothing', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(ISS_NORAD);
f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.ring(ISS_NORAD).show, true);
});
test('untracking a held subject gives its marks back', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.stopTracking();
assert.equal(f.methods.getCockpitSubject(), null);
assert.equal(f.ring(ISS_NORAD).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._points.get(ISS_NORAD).show, true);
});
test('a catalog refresh while held keeps the subject and its companions hidden', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
const log = console.log;
console.log = () => {};
try {
await f.parts.ingestion.methods.update(f.viewer);
} finally {
console.log = log;
}
f.nextFrame();
assert.equal(f.state._points.get(COMPANION).show, false, 'companion');
assert.equal(f.state._points.get(ISS_NORAD).show, false, 'tracked point');
f.methods.setCockpitSubject(null);
assert.equal(f.state._points.get(COMPANION).show, true, 'given back');
});
test('untracking a held ISS leaves its ring hidden while Stations is off', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
f.methods.setParams({ classes: 'itpd' });
f.nextFrame();
f.methods.stopTracking();
assert.equal(f.ring(ISS_NORAD).show, false);
f.methods.setParams({ classes: 'sitpd' });
assert.equal(f.ring(ISS_NORAD).show, true);
});
test('tracking without a Cockpit subject keeps its marks', async (t) => {
const f = await fixture(t);
f.track(GPS);
for (let i = 0; i < 3; i++) f.nextFrame();
assert.equal(dotShown(f), true);
assert.equal(f.ring(GPS).show, true);
assert.equal(f.state._points.get(COMPANION).show, true);
assert.equal(f.state._cockpitHiddenPoints.size, 0);
assert.equal(f.state._cockpitHiddenPath, null);
});
/**
* Give a ring the per-instance attributes Cesium creates on its first
* update, starting from the colours it was built with. Rings in this
* fixture are never rendered, so the test stands in for that update.
*/
function readyRing(f, id) {
const path = f.state._orbitPaths.get(id);
const attributes = {
color: Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.toValue(
path.baseDepthFailColor,
),
};
path.primitive.getGeometryInstanceAttributes = (instanceId) =>
instanceId === path.instanceId ? attributes : undefined;
return attributes;
}
/** A colour attribute's alpha byte. */
const alphaByte = (value) => value[3];
test('a Cockpit subject dims every other orbit ring and restores it exactly', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.nextFrame();
assert.ok(f.ring(ISS_NORAD), 'the ISS ring is drawn beside the tracked one');
const iss = readyRing(f, ISS_NORAD);
const gps = readyRing(f, GPS);
const builtColor = [...iss.color];
const builtDepthFail = [...iss.depthFailColor];
const gpsBuilt = [...gps.color];
f.methods.setCockpitSubject(GPS);
const dimmed = (byte) => Math.round(byte * COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(Math.abs(alphaByte(iss.color) - dimmed(builtColor[3])) <= 1);
assert.ok(
Math.abs(alphaByte(iss.depthFailColor) - dimmed(builtDepthFail[3])) <= 1,
);
assert.deepEqual([...iss.color].slice(0, 3), builtColor.slice(0, 3));
assert.equal(f.ring(ISS_NORAD).show, true, 'other rings stay visible');
assert.equal(f.ring(GPS).show, false, 'the ridden ring stays hidden');
assert.deepEqual([...gps.color], gpsBuilt, 'the ridden ring is not dimmed');
// Other satellites' points stay as they are.
assert.equal(f.state._points.get(COMPANION).show, true);
// A rebuilt ring arrives at full alpha and is dimmed again on the tick.
f.parts.rendering._hideOrbitPath(ISS_NORAD);
f.parts.rendering._showOrbitPath(ISS_NORAD, Cesium.Color.YELLOW);
const rebuilt = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.ok(alphaByte(rebuilt.color) < builtColor[3]);
f.methods.setCockpitSubject(null);
assert.deepEqual(
[...rebuilt.color],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseColor,
),
],
'released rings get their built colours back exactly',
);
assert.deepEqual(
[...rebuilt.depthFailColor],
[
...Cesium.ColorGeometryInstanceAttribute.toValue(
f.state._orbitPaths.get(ISS_NORAD).baseDepthFailColor,
),
],
);
assert.equal(f.ring(GPS).show, true);
assert.deepEqual([...gps.color], gpsBuilt);
});
test('a ring not yet updated by Cesium is dimmed once it is', async (t) => {
const f = await fixture(t);
f.track(GPS);
f.methods.setCockpitSubject(GPS);
const path = f.state._orbitPaths.get(ISS_NORAD);
assert.equal(path.alphaFactor, 1, 'nothing written before the first update');
const iss = readyRing(f, ISS_NORAD);
f.nextFrame();
assert.equal(path.alphaFactor, COCKPIT_ORBIT_DIM_FACTOR);
assert.ok(alphaByte(iss.color) < 100);
assert.equal(applyOrbitPathAlpha(path, 1), true);
assert.deepEqual(
[...iss.color],
[...Cesium.ColorGeometryInstanceAttribute.toValue(path.baseColor)],
);
});
test('a held subject ignores the layer Escape; refocus restores the follow', async (t) => {
const f = await fixture(t);
f.track(ISS_NORAD);
f.nextFrame();
f.methods.setCockpitSubject(ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, ISS_NORAD, 'the Cockpit owns Escape');
// The Cockpit took the follow camera off the entity; refocus puts it back.
f.viewer.trackedEntity = undefined;
f.methods.setCockpitSubject(null);
assert.equal(f.methods.refocusTrackedById(GPS), false, 'not the tracked one');
assert.equal(f.viewer.trackedEntity, undefined);
assert.equal(f.methods.refocusTrackedById(String(ISS_NORAD)), true);
assert.equal(f.viewer.trackedEntity, f.state._trackedEntity);
assert.equal(f.state._trackedNorad, ISS_NORAD);
f.parts.interaction._onKeyDown({ key: 'Escape' });
assert.equal(f.state._trackedNorad, null, 'released, Escape untracks again');
assert.equal(f.methods.refocusTrackedById(ISS_NORAD), false);
});
test('the ground track bearing comes from the SGP4 velocity, less the Earth turning', () => {
const near = (actual, expected) =>
assert.ok(Math.abs(actual - expected) < 0.2, `${actual} vs ${expected}`);
// An ISS-like orbit (51.6°, 7.66 km/s) crossing the equator northbound at
// 0°E: inertially 38.4° from north, but the ground turns east beneath it,
// so the track runs closer to north.
const inclination = (51.6 * Math.PI) / 180;
const iss = {
position: { x: 6771, y: 0, z: 0 },
velocity: {
x: 0,
y: 7.66 * Math.cos(inclination),
z: 7.66 * Math.sin(inclination),
},
};
near(groundTrackBearingDeg(iss.position, iss.velocity, 0, 0, 0), 35.4);
// The same state given in TEME a quarter sidereal turn on (GMST 90°):
// still over 0°E, so the same ground track.
near(
groundTrackBearingDeg(
{ x: 0, y: 6771, z: 0 },
{ x: -iss.velocity.y, y: 0, z: iss.velocity.z },
Math.PI / 2,
0,
0,
),
35.4,
);
// Geostationary: it turns with the Earth, so there is no ground track.
assert.equal(
groundTrackBearingDeg(
{ x: 42164, y: 0, z: 0 },
{ x: 0, y: 3.0747, z: 0 },
0,
0,
0,
),
null,
);
assert.equal(groundTrackBearingDeg(iss.position, null, 0, 0, 0), null);
// The subject passes the sample's track through.
const sat = { name: 'X', group: 'stations' };
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
assert.equal(
satelliteCockpitInfo(1, sat, { ...fix, groundTrackDeg: 35.4 })
.groundTrackDeg,
35.4,
);
assert.equal(satelliteCockpitInfo(1, sat, fix).groundTrackDeg, null);
});
test('the subject says whether its class may be ridden', () => {
const fix = { latitude: 0, longitude: 0, altitude: 400_000 };
const subject = (satelliteClass) =>
satelliteCockpitInfo(
1,
{ name: 'X', group: 'visual', satelliteClass },
fix,
);
assert.equal(subject('debris').enterable, false);
for (const satelliteClass of [
'stations',
'imaging',
'telecom',
'starlink',
'probes',
])
assert.equal(subject(satelliteClass).enterable, true, satelliteClass);
});
+304 -80
View File
@@ -1,11 +1,14 @@
import {
tallySatelliteClasses,
satelliteClassLabel,
satelliteClassLegend,
} from '../../data/satelliteClass.js';
import { satelliteClassText } from '../../data/satelliteClass.js';
import { decodeSatelliteClassMask } from '../../data/satelliteClassMask.js';
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { ISS_NORAD, POINT_STYLES } from './policy.js';
import {
DEFAULT_SATELLITE_CLASSES,
SATELLITE_CLASS_DISPLAY,
SATELLITE_CLASS_IDS,
mergeClassVisibility,
} from './classes.js';
import { ISS_NORAD, POINT_STYLES, classPointStyle } from './policy.js';
export function createControls({ state: layerState, services, parts, source }) {
const { isExplicitLayerStateOrigin } = services.layerState;
@@ -19,7 +22,84 @@ export function createControls({ state: layerState, services, parts, source }) {
function _pointStyleFor(noradId, group) {
if (noradId === ISS_NORAD) return POINT_STYLES.iss;
return POINT_STYLES[group] || POINT_STYLES.visual;
return classPointStyle(
group,
layerState._catalog.get(noradId)?.satelliteClass,
);
}
/** The class-visibility choice, defaults filled in. */
function _classes() {
return layerState._params.classes || DEFAULT_SATELLITE_CLASSES;
}
/**
* Whether a satellite's class is shown. Starlink follows the catalog mode:
* its points exist only in dense mode. An unclassed entry shows.
* @param {number} noradId NORAD catalog number.
*/
function _classVisible(noradId) {
const satelliteClass = layerState._catalog.get(noradId)?.satelliteClass;
if (!satelliteClass) return true;
if (satelliteClass === 'starlink')
return layerState._params.catalog === 'dense';
return _classes()[satelliteClass] === true;
}
/**
* Show or hide every point by its class. The tracked satellite's point
* stays hidden (its entity draws the dot), as do points a Cockpit hold hid.
* The ISS's ring and label go with its class.
*/
function _applyClassVisibility() {
for (const [noradId, point] of layerState._points) {
if (noradId === layerState._trackedNorad) continue;
if (layerState._cockpitHiddenPoints?.has(noradId)) continue;
point.show = _classVisible(noradId);
}
_syncIssOrbit();
parts.labels?._syncIssOverlay?.();
layerState._detectionObjects.clear();
}
/**
* Whether the ISS's ring shows: orbits on, the layer drawing, and its
* class on or the ISS tracked (a tracked satellite keeps its ring).
*/
function _issOrbitVisible() {
return (
satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
) &&
(_classVisible(ISS_NORAD) || layerState._trackedNorad === ISS_NORAD)
);
}
/** Show or hide the ISS's ring by _issOrbitVisible, if it is built. */
function _syncIssOrbit() {
const issPath = layerState._orbitPaths.get(ISS_NORAD);
if (issPath) issPath.primitive.show = _issOrbitVisible();
}
/**
* The row's info line while the classes rest on old or missing SATCAT
* evidence (`_satcatState`), and an empty one otherwise.
* @returns {{info: string, infoTitle: string}}
*/
function classEvidenceNotice() {
const evidence = layerState._satcatState;
if (evidence !== 'stale' && evidence !== 'unavailable')
return { info: '', infoTitle: '' };
return {
info:
evidence === 'stale'
? t('Classes may lag: SATCAT is a cached copy')
: t('Classes may lag: SATCAT unavailable'),
infoTitle: t(
"CelesTrak SATCAT gives each object's type and status. Without a current copy the classes rest on the UCS database, names and CelesTrak groups, so a satellite that has died since may still show as working.",
),
};
}
/** Tell the manager to re-render this layer's row (chip state / legend counts). */
@@ -46,14 +126,11 @@ export function createControls({ state: layerState, services, parts, source }) {
) {
return layerState._classTallyCache.counts;
}
const entries = [];
// Pass the ISS flag, not just the group: during a stations-feed outage the
// ISS is ingested as `visual`, and the legend must file it exactly where its
// card does (STATION) rather than letting STATION vanish from the legend.
for (const [noradId, sat] of layerState._catalog) {
entries.push({ group: sat.group, isIss: noradId === ISS_NORAD });
const counts = Object.create(null);
for (const sat of layerState._catalog.values()) {
const satelliteClass = sat.satelliteClass || 'probes';
counts[satelliteClass] = (counts[satelliteClass] || 0) + 1;
}
const counts = tallySatelliteClasses(entries);
layerState._classTallyCache = {
revision: layerState._catalogRevision,
counts,
@@ -88,6 +165,47 @@ export function createControls({ state: layerState, services, parts, source }) {
requestedCatalog !== currentCatalog
);
}
/** The STARLINK chip: the dense catalog, with its load state. */
function _starlinkChip() {
const loading = layerState._denseStatus === 'loading';
const failed = layerState._denseStatus === 'failed';
const active =
layerState._params.catalog === 'dense' &&
layerState._denseStatus === 'ready';
let title = t(
'Add the full Starlink broadband shell (thousands of extra points)',
);
if (loading) title = t('Loading the Starlink shell…');
else if (failed)
title = t('Starlink {detail} — click to retry', {
detail: layerState._denseError || t('load failed'),
});
else if (active)
title = t(
'Showing the full Starlink shell — click for the core catalog only',
);
return {
id: 'catalog',
label: loading
? t('STARLINK ···')
: failed
? t('STARLINK ✕')
: t('STARLINK'),
active,
busy: loading,
disabled: loading,
state: loading
? 'loading'
: failed
? 'error'
: active
? 'active'
: 'idle',
title,
params: { catalog: active ? 'core' : 'dense' },
};
}
const methods = {
id: 'satellites',
@@ -129,11 +247,16 @@ export function createControls({ state: layerState, services, parts, source }) {
if (!shouldTake) continue;
if (!point.position) continue;
const isTracked = noradId === layerState._trackedNorad;
// A hidden class is not on screen, so nothing is bracketed on it.
if (!isTracked && !_classVisible(noradId)) continue;
// A docked companion sits at the tracked subject's own position, so its
// mark and label would stack underneath the tracked card. It is listed on
// that card instead. Only members of the tracked cluster are affected —
// unrelated nearby satellites are never suppressed.
if (!isTracked && layerState._dockedCompanions.has(noradId)) continue;
// The Cockpit camera rides a held subject; a bracket on it would sit
// on the lens.
if (isTracked && parts.cockpit?._cockpitHeld()) continue;
const cat = layerState._catalog.get(noradId);
let object = layerState._detectionObjects.get(noradId);
if (!object) {
@@ -141,15 +264,16 @@ export function createControls({ state: layerState, services, parts, source }) {
sourceId: noradId,
id: cat?.name || `SAT-${noradId}`,
type: 'SAT',
// Human class ("NAV · GPS"), not the raw CelesTrak tag ("GPS-OPS").
// The detection canvas composites ABOVE the post-FX chain, so this
// is how class survives NVG/FLIR once the dot colors are collapsed.
klass: satelliteClassLabel(cat?.group, {
isIss: noradId === ISS_NORAD,
}),
};
layerState._detectionObjects.set(noradId, object);
}
// Human class ("TELECOM · GPS"), not the raw CelesTrak tag
// ("GPS-OPS"). The detection canvas composites ABOVE the post-FX
// chain, so this is how class survives NVG/FLIR once the dot colors
// are collapsed. Read each time: SATCAT can reclassify a satellite.
object.klass = satelliteClassText(cat?.satelliteClass, cat?.group, {
isIss: noradId === ISS_NORAD,
});
object.position = point.position;
object.skipLabel = isTracked;
result.push(object);
@@ -190,7 +314,10 @@ export function createControls({ state: layerState, services, parts, source }) {
if (noradId === null) return null;
const sat = layerState._catalog.get(noradId);
const pos = parts.orbits.propagatePosition(sat.satrec, new Date());
const pos = parts.orbits.propagatePosition(
sat.satrec,
new Date(layerState.now()),
);
if (!pos) return null;
return {
@@ -222,6 +349,7 @@ export function createControls({ state: layerState, services, parts, source }) {
for (const [noradId, point] of layerState._points) {
if (result.length >= cap) break;
if (!point.position) continue;
if (!_classVisible(noradId)) continue;
// Dense extras are points-only — keep voice/framing lists to the core catalog.
if (
layerState._denseIds.length > 0 &&
@@ -243,6 +371,72 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* The shown satellites nearest a position, nearest first, from per-point
* state (no SGP4 re-propagation): a bounded pass that keeps only the
* nearest `maxCount`, and reads latitude and longitude for those alone.
* Dense extras are left out, as in `getAllPositions`.
* @param {Cesium.Cartesian3} center Earth-fixed position.
* @param {number} [maxCount=8] Most entries to return.
* @param {{excludeIds?: Array<number|string>,
* excludeClasses?: Array<string>}} [options] Satellites, and classes
* (e.g. 'debris'), to leave out.
* @returns {Array<{ id: number, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, satelliteClass: string|null, distanceM: number }>}
*/
getNearestPositions(
center,
maxCount = 8,
{ excludeIds = [], excludeClasses = [] } = {},
) {
const nearest = [];
const cap = Number.isFinite(maxCount) ? Math.floor(maxCount) : 8;
if (
cap < 1 ||
!center ||
!layerState._points ||
layerState._points.size === 0
)
return nearest;
const excluded = new Set(excludeIds.map(String));
const classes = new Set(excludeClasses);
const dense = layerState._denseIds.length > 0;
for (const [noradId, point] of layerState._points) {
const p = point.position;
if (!p || excluded.has(String(noradId))) continue;
if (!_classVisible(noradId)) continue;
const sat = layerState._catalog.get(noradId);
if (dense && sat?.group === 'dense') continue;
if (classes.size && classes.has(sat?.satelliteClass)) continue;
const dx = p.x - center.x;
const dy = p.y - center.y;
const dz = p.z - center.z;
const distanceSq = dx * dx + dy * dy + dz * dz;
if (nearest.length === cap && distanceSq >= nearest[cap - 1].distanceSq)
continue;
// Insertion into a short sorted list: no copy or sort of the rest.
let at = nearest.length;
while (at > 0 && nearest[at - 1].distanceSq > distanceSq) at -= 1;
nearest.splice(at, 0, { noradId, point, sat, distanceSq });
if (nearest.length > cap) nearest.pop();
}
const result = [];
for (const { noradId, point, sat, distanceSq } of nearest) {
const carto = Cesium.Cartographic.fromCartesian(point.position);
if (!carto) continue;
result.push({
id: noradId,
label: sat ? sat.name.trim() : String(noradId),
position: point.position,
latitude: Cesium.Math.toDegrees(carto.latitude),
longitude: Cesium.Math.toDegrees(carto.longitude),
altitudeM: carto.height,
satelliteClass: sat?.satelliteClass ?? null,
distanceM: Math.sqrt(distanceSq),
});
}
return result;
},
/**
* Track a satellite by NORAD id (camera follow + orbit path + highlight),
* same path as clicking its point.
@@ -380,9 +574,11 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Runtime params (DataLayerManager.setLayerParams path).
* catalog: 'core' (default, ~840 sats) | 'dense' (adds the Starlink shell
* as points-only extras on a relaxed propagation budget).
* @param {{ catalog?: 'core'|'dense', showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
* catalog: 'core' (default, about 1,300 satellites from the CelesTrak
* groups) | 'dense' (adds the Starlink shell as points-only extras on a
* relaxed propagation budget). classes: which of the six classes show
* (src/layers/satellites/classes.js); Starlink's toggle is the dense catalog.
* @param {{ catalog?: 'core'|'dense', classes?: Record<string, boolean>, showPoints?: boolean, showOrbits?: boolean, selectedSatTrackingId?: number|null }} [params]
*/
setParams(params = {}, { origin = 'programmatic' } = {}) {
if (
@@ -391,9 +587,28 @@ export function createControls({ state: layerState, services, parts, source }) {
) {
parts.tracking._cancelPendingTrackingRestore();
}
const catalog = params.catalog;
let catalog = params.catalog;
if (catalog !== undefined && catalog !== 'core' && catalog !== 'dense')
return false;
// A saved or shared choice arrives as class letters (layerState.js).
const requestedClasses =
typeof params.classes === 'string'
? decodeSatelliteClassMask(params.classes)
: params.classes;
if (params.classes !== undefined) {
if (!requestedClasses || typeof requestedClasses !== 'object')
return false;
// Starlink's toggle is the dense catalog: its points load on demand.
if (
typeof requestedClasses.starlink === 'boolean' &&
catalog === undefined
)
catalog = requestedClasses.starlink ? 'dense' : 'core';
layerState._params.classes = mergeClassVisibility(
requestedClasses,
_classes(),
);
}
const catalogChanged = satelliteCatalogModeChanged(
layerState._params.catalog,
catalog,
@@ -411,11 +626,14 @@ export function createControls({ state: layerState, services, parts, source }) {
}
if (params.showOrbits !== undefined) {
layerState._params.showOrbits = params.showOrbits !== false;
for (const path of layerState._orbitPaths.values())
path.primitive.show = satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
for (const [noradId, path] of layerState._orbitPaths)
path.primitive.show =
noradId === ISS_NORAD
? _issOrbitVisible()
: satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
parts.labels._syncIssOverlay();
}
if (catalogChanged && catalog === 'dense') {
@@ -431,6 +649,13 @@ export function createControls({ state: layerState, services, parts, source }) {
}
if (catalogChanged)
console.log(`[Data:Satellites] Catalog mode: ${catalog}`);
if (params.classes !== undefined || catalogChanged) {
layerState._params.classes = {
..._classes(),
starlink: layerState._params.catalog === 'dense',
};
_applyClassVisibility();
}
if (Object.hasOwn(params, 'selectedSatTrackingId')) {
const requested = parts.tracking._normalizeTrackedNorad(
params.selectedSatTrackingId,
@@ -462,25 +687,29 @@ export function createControls({ state: layerState, services, parts, source }) {
catalog: layerState._params.catalog,
showPoints: layerState._params.showPoints,
showOrbits: layerState._params.showOrbits,
classes: { ..._classes() },
selectedSatTrackingId: layerState._trackedNorad,
};
},
/**
* Layer-row sub-controls (DataLayerManager row-controls contract): the DENSE
* catalog chip plus a class legend so the point colors are learnable without
* a new panel.
* Layer-row sub-controls (DataLayerManager row-controls contract): one
* toggle chip per satellite class (src/layers/satellites/classes.js), and a legend
* of the classes on screen so the point colours are learnable.
*
* The chip is stateless — it declares the params to apply and the manager
* Chips are stateless — each declares the params to apply and the manager
* owns the write, so the Space Missions snapshot/restore path (which drives
* the same `catalog` param) stays the single source of truth and the chip
* the same `catalog` param) stays the single source of truth and a chip
* always renders whatever the layer actually has.
*
* The chip reports the dense LOAD state, not the catalog param: the param
* flips synchronously while the Starlink shell takes seconds to arrive and
* frequently 502s, so ACTIVE means "dense points are on screen" and nothing
* less. The legend tally is cached against the catalog revision.
* @returns {{ chips: Array<object>, legend: Array<object> }} Row controls.
* STARLINK is the dense catalog (chip id `catalog`) and reports the dense
* LOAD state, not the param: the param flips synchronously while the shell
* takes seconds to arrive and frequently 502s, so ACTIVE means "Starlink
* points are on screen" and nothing less. The legend tally is cached
* against the catalog revision. While SATCAT is stale or unavailable the
* info line says the classes may lag (see `classEvidenceNotice`).
* @returns {{ chips: Array<object>, legend: Array<object>, info: string,
* infoTitle: string }} Row controls.
*/
getRowControls() {
// A dependency owner (Space Missions) borrows this layer for TLE lookup
@@ -489,48 +718,36 @@ export function createControls({ state: layerState, services, parts, source }) {
// restore. Surrender the row rather than lie about it.
if (!layerState._params.showPoints) return { chips: [], legend: [] };
const loading = layerState._denseStatus === 'loading';
const failed = layerState._denseStatus === 'failed';
const active =
layerState._params.catalog === 'dense' &&
layerState._denseStatus === 'ready';
let title = t(
'Add the full Starlink broadband shell (thousands of extra points)',
const classes = _classes();
const chips = SATELLITE_CLASS_IDS.map((id) =>
id === 'starlink'
? _starlinkChip()
: {
id: `class-${id}`,
label: t(SATELLITE_CLASS_DISPLAY[id].label),
active: classes[id] === true,
state: classes[id] === true ? 'active' : 'idle',
title: t(SATELLITE_CLASS_DISPLAY[id].blurb),
params: { classes: { [id]: classes[id] !== true } },
},
);
if (loading) title = t('Loading the Starlink shell…');
else if (failed)
title = t('Starlink {detail} — click to retry', {
detail: layerState._denseError || t('load failed'),
const counts = _classTally();
const legend = [];
for (const id of SATELLITE_CLASS_IDS) {
const shown =
id === 'starlink'
? layerState._params.catalog === 'dense'
: classes[id] === true;
if (!shown || !(counts[id] > 0)) continue;
legend.push({
klass: id,
label: t(SATELLITE_CLASS_DISPLAY[id].label),
color: SATELLITE_CLASS_DISPLAY[id].color,
blurb: t(SATELLITE_CLASS_DISPLAY[id].blurb),
count: counts[id],
});
else if (active)
title = t(
'Showing the full Starlink shell — click for the core catalog only',
);
return {
chips: [
{
id: 'catalog',
label: loading
? t('DENSE ···')
: failed
? t('DENSE ✕')
: t('DENSE'),
active,
busy: loading,
disabled: loading,
state: loading
? 'loading'
: failed
? 'error'
: active
? 'active'
: 'idle',
title,
params: { catalog: active ? 'core' : 'dense' },
},
],
legend: satelliteClassLegend(_classTally()),
};
}
return { chips, legend, ...classEvidenceNotice() };
},
/**
@@ -559,6 +776,9 @@ export function createControls({ state: layerState, services, parts, source }) {
? 'stale'
: 'nominal',
error: layerState._lastError,
// SATCAT refines the classes; when it is stale or unavailable the
// classes rest on UCS, names and groups alone.
classEvidence: layerState._satcatState,
};
},
};
@@ -567,6 +787,10 @@ export function createControls({ state: layerState, services, parts, source }) {
_pointStyleFor,
_notifyRowControls,
_classTally,
_classVisible,
_applyClassVisibility,
_issOrbitVisible,
_syncIssOrbit,
satelliteVisualsVisible,
satelliteCatalogModeChanged,
methods,
+3
View File
@@ -1,5 +1,6 @@
import { createControls } from './controls.js';
import { createCatalog } from './catalog.js';
import { createCockpitSubject } from './cockpitSubject.js';
import { createLabels } from './labels.js';
import { createOrbits } from './orbits.js';
import { createRendering } from './rendering.js';
@@ -29,9 +30,11 @@ export function createSatellitesLayer({ services, source }) {
parts.interaction = createInteraction(context);
parts.lifecycle = createLifecycle(context);
parts.ingestion = createIngestion(context);
parts.cockpit = createCockpitSubject(context);
return Object.assign(
{},
parts.controls.methods,
parts.cockpit.methods,
parts.lifecycle.methods,
parts.ingestion.methods,
{
+236 -5
View File
@@ -3,6 +3,22 @@ import * as Cesium from 'cesium';
import { msg } from '../../i18n/index.js';
import { noradIdFromSatnum, tleLineLaunchYear } from '../../sources/tle.js';
import { CATALOG_GROUPS, ISS_NORAD, POINT_STYLES } from './policy.js';
import { classifySatellite, parseSatcatCsv } from './classes.js';
import { matchImagingSensor } from './sensors.js';
/**
* How long a catalog rebuild waits for SATCAT before it classifies without
* it, ms. SATCAT can hang for the proxy's whole upstream timeout (20 s); the
* late answer reclassifies in place.
*/
export const SATCAT_WAIT_MS = 3000;
/**
* How long a complete, current SATCAT read is kept before the layer asks
* again, ms. SATCAT changes daily and the proxy caches it a day, so the
* five-minute TLE update does not read all eleven groups each time.
*/
export const SATCAT_KEEP_MS = 6 * 60 * 60 * 1000;
export function createIngestion({
state: layerState,
@@ -10,6 +26,161 @@ export function createIngestion({
parts,
source,
}) {
/**
* The local packs the classes and zoom steps are read from: the UCS pack
* and the imaging-sensor pack. Neither is needed to render: a failed read
* leaves the last pack (or none) and classification falls back to names
* and groups.
*/
async function _readLocalEvidence() {
const ucs = layerState._ucs
? Promise.resolve(layerState._ucs)
: Promise.resolve()
.then(() => source.readUcs?.())
.then((pack) => (pack instanceof Map ? pack : null))
.catch((error) => {
console.warn('[Data:Satellites] UCS pack unavailable:', error);
return null;
});
// The sensor pack only adds zoom steps in the orbital view; without it
// every satellite keeps the base steps.
const sensors = layerState._sensors
? Promise.resolve(layerState._sensors)
: Promise.resolve()
.then(() => source.readSensors?.())
.then((index) => (index?.byNorad instanceof Map ? index : null))
.catch((error) => {
console.warn(
'[Data:Satellites] Imaging sensor pack unavailable:',
error,
);
return null;
});
const [pack, sensorIndex] = await Promise.all([ucs, sensors]);
if (pack) layerState._ucs = pack;
if (sensorIndex) layerState._sensors = sensorIndex;
}
/**
* CelesTrak SATCAT for every core group: type and status, which refine the
* classes. A group whose read failed gives null.
* @returns {Promise<Array<{records: Map, stale: boolean}|null>>}
*/
function _readSatcat(signal) {
if (typeof source.readSatcat !== 'function') return Promise.resolve([]);
// A complete, current read is kept; a stale or failed one is asked again.
if (
layerState._satcatState === 'current' &&
Date.now() - layerState._satcatReadAtMs < SATCAT_KEEP_MS
)
return Promise.resolve([]);
return Promise.all(
CATALOG_GROUPS.map((groupDef) =>
source
.readSatcat(groupDef.path, { signal })
.then((res) =>
res?.ok
? { records: parseSatcatCsv(res.text), stale: Boolean(res.stale) }
: null,
)
.catch((error) => {
if (signal.aborted || error?.name === 'AbortError') throw error;
return null;
}),
),
);
}
/**
* Merge SATCAT reads and say how current they are: 'current', 'stale' (a
* group came from the proxy's last copy) or 'unavailable' (a group failed;
* its earlier records, if any, stay).
*/
function _mergeSatcat(groups) {
let satcatState = 'current';
for (const group of groups) {
if (!group) {
satcatState = 'unavailable';
continue;
}
if (group.stale && satcatState === 'current') satcatState = 'stale';
for (const [noradId, record] of group.records) {
// A group served from the proxy's last copy never overrules a
// current read of the same object, from this merge or an earlier one.
const held = layerState._satcat.get(noradId);
if (group.stale && held && !held.stale) continue;
layerState._satcat.set(
noradId,
group.stale ? { ...record, stale: true } : record,
);
}
}
if (!groups.length) return;
const changed = layerState._satcatState !== satcatState;
layerState._satcatState = satcatState;
layerState._satcatReadAtMs = Date.now();
if (satcatState !== 'current')
console.warn(`[Data:Satellites] SATCAT ${satcatState}: classes may lag`);
// The row's info line says so (getRowControls).
if (changed) parts.controls._notifyRowControls();
}
/**
* Classify the catalog again once SATCAT lands after it was built: only
* entries whose SATCAT record changed are read again; a changed class
* restyles its point and refreshes visibility, the legend and the overlay.
*/
function _reclassifyFromSatcat() {
let changed = false;
for (const [noradId, sat] of layerState._catalog) {
if (sat.group === 'dense') continue;
const satcat = layerState._satcat.get(noradId) || null;
if (satcat === sat.satcat) continue;
sat.satcat = satcat;
// The Cockpit identity (owner, COSPAR id) reads SATCAT too.
sat.cockpitIdentity = undefined;
const next = classifySatellite({
noradId,
name: sat.name,
group: sat.group,
groups: sat.groups,
ucs: sat.ucs,
satcat,
launchYear: sat.launchYear,
});
if (next === sat.satelliteClass) continue;
sat.satelliteClass = next;
changed = true;
const point = layerState._points.get(noradId);
if (point) {
const style = parts.controls._pointStyleFor(noradId, sat.group);
point.pixelSize = style.pixelSize;
point.color = style.color;
point.outlineColor = style.outlineColor;
point.outlineWidth = style.outlineWidth;
}
}
if (!changed) return;
parts.controls._applyClassVisibility();
layerState._catalogRevision++;
parts.controls._notifyRowControls();
}
/** Resolve null after `ms`, or at once when `signal` aborts. */
function _waitOrAbort(ms, signal) {
return new Promise((resolve) => {
const timer = setTimeout(resolve, ms, null);
signal.addEventListener(
'abort',
() => {
clearTimeout(timer);
resolve(null);
},
{ once: true },
);
});
}
const methods = {
async update(viewer, { signal = null } = {}) {
const trackingRefreshEpoch = ++layerState._trackingRefreshEpoch;
@@ -27,6 +198,10 @@ export function createIngestion({
updateSignal.throwIfAborted();
// Load all core groups in parallel; a failed/empty group degrades
// gracefully (parseTLE of an upstream error body yields []).
const localEvidence = _readLocalEvidence();
const satcat = _readSatcat(updateSignal);
// An abort can reject this before the groups settle and it is awaited.
satcat.catch(() => {});
const results = await Promise.all(
CATALOG_GROUPS.map(async (groupDef) => {
try {
@@ -49,7 +224,23 @@ export function createIngestion({
}
}),
);
await localEvidence;
// SATCAT only refines classes: wait a moment for it, then classify
// with what is held and let a late answer reclassify in place.
const satcatInTime = await Promise.race([
satcat.then((groups) => ({ groups })),
_waitOrAbort(SATCAT_WAIT_MS, updateSignal),
]).catch(() => null);
updateSignal.throwIfAborted();
if (satcatInTime) _mergeSatcat(satcatInTime.groups);
else
satcat
.then((groups) => {
if (updateSignal.aborted || !layerState._enabled) return;
_mergeSatcat(groups);
_reclassifyFromSatcat();
})
.catch(() => {});
const failed = results.filter((r) => !r.ok).map((r) => r.path);
if (failed.length > 0) {
@@ -62,7 +253,7 @@ export function createIngestion({
);
// CelesTrak outage guard (H3): if EVERY group failed, bail BEFORE clearing.
// Wiping the collection + catalog here would blank all 838 satellites while
// Wiping the collection + catalog here would blank every satellite while
// the chip still read "just now". Keep the existing (stale) catalog on
// screen and surface the outage instead — do NOT stamp _lastUpdate.
if (results.every((r) => !r.ok)) {
@@ -103,7 +294,7 @@ export function createIngestion({
layerState._denseLoadToken++; // cancel any in-flight dense load against the old catalog
parts.labels._syncIssOverlay();
const now = new Date();
const now = new Date(layerState.now());
// Process all TLE entries in CATALOG_GROUPS order
const allEntries = [];
@@ -112,6 +303,18 @@ export function createIngestion({
allEntries.push({ ...e, group: r.tag, stale: r.stale });
}
// Every group each TLE came in, keyed by its catalog-number column:
// the shown tag is the first, but classification reads them all.
const groupsByNumber = new Map();
for (const entry of allEntries) {
const number = String(entry.line1 || '')
.slice(2, 7)
.trim();
const groups = groupsByNumber.get(number);
if (!groups) groupsByNumber.set(number, [entry.group]);
else if (!groups.includes(entry.group)) groups.push(entry.group);
}
// Deduplicate by NORAD ID — first (most specific) group tag wins
const seen = new Set();
let coreStale = false;
@@ -125,12 +328,38 @@ export function createIngestion({
seen.add(noradId);
// Store in catalog
const launchYear = tleLineLaunchYear(entry.line1);
const ucs = layerState._ucs?.get(noradId) || null;
const satcat = layerState._satcat.get(noradId) || null;
const groups = groupsByNumber.get(
String(entry.line1 || '')
.slice(2, 7)
.trim(),
) || [entry.group];
layerState._catalog.set(noradId, {
name: entry.name,
satrec,
group: entry.group,
groups,
// satellite.js does not keep the designator the year match reads.
launchYear: tleLineLaunchYear(entry.line1),
launchYear,
line1: entry.line1,
line2: entry.line2,
satelliteClass: classifySatellite({
noradId,
name: entry.name,
group: entry.group,
groups,
ucs,
satcat,
launchYear,
}),
ucs,
satcat,
sensor: matchImagingSensor(layerState._sensors, {
noradId,
name: entry.name,
}),
});
coreStale ||= entry.stale;
@@ -156,6 +385,8 @@ export function createIngestion({
scaleByDistance: new Cesium.NearFarScalar(1e6, 1.5, 2e7, 0.6),
id: noradId,
});
// Hidden classes keep their point, so a toggle needs no rebuild.
point.show = parts.controls._classVisible(noradId);
layerState._points.set(noradId, point);
}
@@ -163,8 +394,7 @@ export function createIngestion({
// Show ISS orbital path by default
if (layerState._catalog.has(ISS_NORAD)) {
parts.rendering._showOrbitPath(ISS_NORAD, POINT_STYLES.iss.color);
const issPath = layerState._orbitPaths.get(ISS_NORAD);
if (issPath) issPath.primitive.show = layerState._params.showOrbits;
parts.controls._syncIssOrbit();
parts.labels._syncIssOverlay();
}
@@ -195,6 +425,7 @@ export function createIngestion({
// the rebuild must not block on that.
void parts.tracking._reconcileTrackedSubjectContext();
parts.tracking._applyPendingTrackingRestore();
layerState.coverageChanged();
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Satellite update aborted', 'AbortError');
+199 -5
View File
@@ -1,8 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { parseTleText, tleLineLaunchYear } from '../../sources/tle.js';
import { createIngestion } from './ingestion.js';
import {
SATCAT_KEEP_MS,
SATCAT_WAIT_MS,
createIngestion,
} from './ingestion.js';
import { createOrbits } from './orbits.js';
import { createControls } from './controls.js';
// The ISS set (1 January 2024) with its catalog field swapped per satellite.
const ISS_LINE1 =
@@ -18,7 +23,7 @@ function tleSet(name, field) {
].join('\n');
}
function ingestionFor(catalogText) {
function ingestionFor(catalogText, { source: sourceExtras = {} } = {}) {
const state = {
_trackingRefreshEpoch: 0,
_activeUpdateControllers: new Set(),
@@ -33,6 +38,10 @@ function ingestionFor(catalogText) {
_denseLoadToken: 0,
_catalogRevision: 0,
_params: { catalog: 'core', showOrbits: false },
_satcat: new Map(),
_ucs: null,
now: Date.now,
coverageChanged() {},
};
const parts = {
orbits: {
@@ -40,7 +49,17 @@ function ingestionFor(catalogText) {
propagatePosition: () => ({ longitude: 0, latitude: 0, altitude: 4e5 }),
},
labels: { _syncIssOverlay() {} },
controls: { _pointStyleFor: () => ({}) },
controls: {
_pointStyleFor: () => ({}),
_classVisible: () => true,
_syncIssOrbit() {},
_applyClassVisibility() {
state.visibilityApplied = (state.visibilityApplied || 0) + 1;
},
_notifyRowControls() {
state.rowNotified = (state.rowNotified || 0) + 1;
},
},
rendering: { _showOrbitPath() {} },
tracking: {
async _reconcileTrackedSubjectContext() {},
@@ -49,9 +68,12 @@ function ingestionFor(catalogText) {
catalog: {},
};
const source = {
async readGroup() {
return { ok: true, text: catalogText };
async readGroup(path) {
const text =
typeof catalogText === 'function' ? catalogText(path) : catalogText;
return { ok: true, text };
},
...sourceExtras,
};
const { methods } = createIngestion({ state, services: {}, parts, source });
return { state, update: () => methods.update({ scene: {} }) };
@@ -119,3 +141,175 @@ test('a satellite with a blank designator keeps matching by name', async (t) =>
69728,
);
});
test('a hanging SATCAT read neither holds the catalog nor is lost when it lands', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
t.mock.timers.enable({ apis: ['setTimeout'] });
let answer;
const satcatAnswer = new Promise((resolve) => {
answer = resolve;
});
const { state, update } = ingestionFor(
(path) => (path === 'stations' ? tleSet('OLD STAGE', '40115') : ''),
{ source: { readSatcat: () => satcatAnswer } },
);
state._enabled = true;
const settle = async () => {
for (let turn = 0; turn < 20; turn += 1)
await new Promise((resolve) => setImmediate(resolve));
};
const rebuilt = update();
await settle();
t.mock.timers.tick(SATCAT_WAIT_MS);
await rebuilt;
// Built without SATCAT: neither name nor group says what it is (the
// stations group alone makes no station).
assert.equal(state._catalog.get(40115).satelliteClass, 'probes');
const revision = state._catalogRevision;
// SATCAT lands late: a rocket body.
answer({
ok: true,
stale: true,
text: 'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\nOLD STAGE,2014-048B,40115,R/B,,US',
});
await settle();
assert.equal(state._catalog.get(40115).satelliteClass, 'debris');
assert.equal(state._catalogRevision, revision + 1, 'the legend refreshes');
assert.ok(state.visibilityApplied >= 1 && state.rowNotified >= 1);
assert.equal(state._satcatState, 'stale', 'its staleness is kept');
});
test('a satellite in visual and resource is imaging, whichever group shows it', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
// A name no pattern knows, no UCS record and no SATCAT: only its groups.
const { state, update } = ingestionFor((path) =>
path === 'visual' || path === 'resource'
? tleSet('ZZ TESTSAT', '50001')
: '',
);
await update();
const sat = state._catalog.get(50001);
assert.equal(sat.group, 'visual', 'shown under the first group');
assert.deepEqual(sat.groups, ['visual', 'resource']);
assert.equal(sat.satelliteClass, 'imaging');
});
test('a stale SATCAT copy never overrules a current read of the same object', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const header =
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE,OWNER\n';
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50002'), {
source: {
// visual is current and says it died; resource, a cached copy, still
// says it works.
readSatcat: async (path) =>
path === 'visual'
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,-,US` }
: path === 'resource'
? {
ok: true,
stale: true,
text: `${header}ZZ TESTSAT,2015-001A,50002,PAY,+,US`,
}
: { ok: true, text: header },
},
});
await update();
assert.equal(state._catalog.get(50002).satelliteClass, 'debris');
});
test('a failed SATCAT read is told on the layer row, not only the console', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
source: { readSatcat: async () => ({ ok: false, text: '' }) },
});
await update();
assert.equal(state._satcatState, 'unavailable');
assert.ok(state.rowNotified >= 1, 'the row repaints');
const controls = createControls({
state: {
...state,
_params: { ...state._params, showPoints: true },
_classTallyCache: {},
},
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: {},
source: {},
});
const row = controls.methods.getRowControls();
assert.equal(row.info, 'Classes may lag: SATCAT unavailable');
assert.match(row.infoTitle, /SATCAT/);
const current = createControls({
state: {
...state,
_satcatState: 'current',
_params: { ...state._params, showPoints: true },
_classTallyCache: {},
},
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: {},
source: {},
});
assert.equal(current.methods.getRowControls().info, '');
});
test('a current SATCAT read is kept between updates; a failed one is asked again', async (t) => {
t.mock.method(console, 'log', () => {});
t.mock.method(console, 'warn', () => {});
const header =
'OBJECT_NAME,OBJECT_ID,NORAD_CAT_ID,OBJECT_TYPE,OPS_STATUS_CODE\n';
let reads = 0;
let ok = true;
const { state, update } = ingestionFor(tleSet('ZZ TESTSAT', '50003'), {
source: {
readSatcat: async () => {
reads++;
return ok
? { ok: true, text: `${header}ZZ TESTSAT,2015-001A,50003,PAY,-` }
: { ok: false, text: '' };
},
},
});
await update();
const perUpdate = reads;
assert.ok(perUpdate > 0);
await update();
assert.equal(reads, perUpdate, 'a fresh read is not asked again');
assert.equal(
state._catalog.get(50003).satelliteClass,
'debris',
'the held records still class the rebuilt catalog',
);
state._satcatReadAtMs -= SATCAT_KEEP_MS;
ok = false;
await update();
assert.equal(reads, 2 * perUpdate, 'an old read is asked again');
assert.equal(state._satcatState, 'unavailable');
await update();
assert.equal(reads, 3 * perUpdate, 'a failed read is asked again');
});
test('a failed imaging-sensor pack is warned about, as the UCS pack is', async (t) => {
t.mock.method(console, 'log', () => {});
const warn = t.mock.method(console, 'warn', () => {});
const { state, update } = ingestionFor(tleSet('OLD STAGE', '40115'), {
source: {
readSensors: async () => {
throw new Error('chunk failed');
},
},
});
await update();
assert.ok(
warn.mock.calls.some((call) =>
/sensor pack unavailable/i.test(call.arguments[0]),
),
'the failure is not swallowed',
);
assert.equal(state._catalog.get(40115).sensor, null, 'base zoom steps');
});
+5
View File
@@ -10,6 +10,8 @@ export function createInteraction({
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
function _onKeyDown(e) {
// The Cockpit owns Escape while it rides the tracked satellite.
if (parts.cockpit?._cockpitHeld()) return;
if (layerState._enabled && e.key === 'Escape' && layerState._trackedNorad) {
parts.tracking._cancelPendingTrackingRestore();
parts.tracking._clearTracking(false, { origin: 'user' });
@@ -50,6 +52,9 @@ export function createInteraction({
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (!layerState._enabled) return;
// The Cockpit camera rides the tracked satellite: a click on the
// picture below must not untrack it or switch satellites.
if (parts.cockpit?._cockpitHeld()) return;
const picked = viewer.scene.pick(click.position);
if (picked) {
+3
View File
@@ -83,6 +83,8 @@ export function createLabels({ state: layerState, services, parts, source }) {
function _dockedCompanionNames() {
const names = [];
for (const noradId of layerState._dockedCompanions) {
// A hidden class is not named on the tracked card either.
if (parts.controls?._classVisible?.(noradId) === false) continue;
names.push(
layerState._catalog.get(noradId)?.name?.trim() || `SAT-${noradId}`,
);
@@ -102,6 +104,7 @@ export function createLabels({ state: layerState, services, parts, source }) {
layerState._trackedNorad !== ISS_NORAD &&
!layerState._dockedCompanions.has(ISS_NORAD) &&
layerState._catalog.has(ISS_NORAD) &&
parts.controls?._classVisible?.(ISS_NORAD) !== false &&
_issDisplayCached();
if (!visible) {
layerState._overlayHost.clearSource(ISS_OVERLAY_SOURCE_ID);
+36 -6
View File
@@ -1,5 +1,10 @@
import * as Cesium from 'cesium';
import { ISS_OVERLAY_SOURCE_ID } from './policy.js';
import {
ISS_NORAD,
ISS_OVERLAY_SOURCE_ID,
SATELLITE_COVERAGE_MS,
} from './policy.js';
import { worldClock } from '../../time/worldClock.js';
export function createLifecycle({
state: layerState,
@@ -8,6 +13,20 @@ export function createLifecycle({
source,
}) {
const { clearFocusTarget } = services.focus;
// While on with a catalog, satellites can be shown at any time in reach of
// their element sets. Registered once; off, the layer has no time to show,
// and each step tells the clock once it has settled.
worldClock.register({
id: 'satellites',
coverage: () => {
if (!layerState._enabled || !layerState._catalog.size) return null;
const now = worldClock.wallNow();
return {
start: now - SATELLITE_COVERAGE_MS,
end: now + SATELLITE_COVERAGE_MS,
};
},
});
const { holdContinuousRender, releaseContinuousRender } = services.render;
const { registerPickOwner, unregisterPickOwner } = services.picking;
@@ -32,6 +51,10 @@ export function createLifecycle({
layerState._trackedFrameNumber = -1;
layerState._trackedFrameGeo = null;
layerState._trackedFrameNowForTest = null;
// The new catalog's points and rings carry no hold.
layerState._cockpitHiddenPoints = new Set();
layerState._cockpitHiddenPath = null;
layerState._cockpitHiddenDot = false;
layerState._lastFocusUpdate = 0;
layerState._activeFocusCount = 0;
layerState._enabled = false;
@@ -46,6 +69,7 @@ export function createLifecycle({
layerState._denseStatus = 'idle';
layerState._denseError = null;
layerState._catalogRevision++;
layerState.coverageChanged();
// Point primitives for satellite dots
layerState._pointCollection = new Cesium.PointPrimitiveCollection();
@@ -72,11 +96,14 @@ export function createLifecycle({
layerState._params.showPoints,
);
// Orbit ring primitives + persistent ISS host label — show them
for (const path of layerState._orbitPaths.values())
path.primitive.show = parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
for (const [noradId, path] of layerState._orbitPaths)
path.primitive.show =
noradId === ISS_NORAD
? parts.controls._issOrbitVisible()
: parts.controls.satelliteVisualsVisible(
layerState._enabled,
layerState._params.showOrbits,
);
parts.labels._syncIssOverlay();
// Re-attach input handlers and preRender propagation
parts.interaction._installClickHandler(viewer);
@@ -92,6 +119,7 @@ export function createLifecycle({
);
}
parts.tracking._applyPendingTrackingRestore();
layerState.coverageChanged();
},
disable(viewer) {
@@ -119,6 +147,7 @@ export function createLifecycle({
layerState._preRenderListener();
layerState._preRenderListener = null;
}
layerState.coverageChanged();
},
destroy(viewer) {
@@ -176,6 +205,7 @@ export function createLifecycle({
failedGroups: [],
};
layerState._viewer = null;
layerState.coverageChanged();
},
};
@@ -0,0 +1,70 @@
// src/layers/satellites/nearestPositions.test.mjs — the satellites nearest a
// position: bounded to the nearest few, nearest first, hidden classes,
// dense extras and asked-for exclusions left out.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createControls } from './controls.js';
function controlsWith(satellites, { classes, dense = [] } = {}) {
const state = {
_points: new Map(),
_catalog: new Map(),
_denseIds: dense,
_params: classes ? { classes } : {},
};
for (const sat of satellites) {
state._points.set(sat.id, {
position: Cesium.Cartesian3.fromDegrees(sat.lon, sat.lat, sat.alt),
});
state._catalog.set(sat.id, {
name: `${sat.name} `,
satelliteClass: sat.cls,
group: sat.group,
});
}
return createControls({
state,
services: { layerState: { isExplicitLayerStateOrigin: () => false } },
parts: {},
}).methods;
}
const SATELLITES = [
{ id: 1, name: 'NEAR', lat: 30.5, lon: -97, alt: 500_000, cls: 'imaging' },
{ id: 2, name: 'MID', lat: 33, lon: -97, alt: 500_000, cls: 'stations' },
{ id: 3, name: 'FAR', lat: -40, lon: 80, alt: 500_000, cls: 'imaging' },
{ id: 4, name: 'DEB', lat: 30.1, lon: -97, alt: 500_000, cls: 'debris' },
{ id: 5, name: 'TELECOM', lat: 30.2, lon: -97, alt: 500_000, cls: 'telecom' },
{ id: 6, name: 'SELF', lat: 30, lon: -97, alt: 420_000, cls: 'stations' },
{ id: 7, name: 'EXTRA', lat: 30.3, lon: -97, alt: 500_000, cls: 'imaging', group: 'dense' },
];
const CENTRE = Cesium.Cartesian3.fromDegrees(-97, 30, 420_000);
test('the nearest shown satellites come first, bounded, with their distance', () => {
const methods = controlsWith(SATELLITES, {
classes: { stations: true, imaging: true, debris: true, telecom: false },
dense: [7],
});
const nearest = methods.getNearestPositions(CENTRE, 3, {
excludeIds: [6],
excludeClasses: ['debris'],
});
assert.deepEqual(
nearest.map((entry) => entry.label),
['NEAR', 'MID', 'FAR'],
'no self, debris, hidden telecom or dense extra',
);
for (let i = 1; i < nearest.length; i += 1)
assert.ok(nearest[i].distanceM >= nearest[i - 1].distanceM);
const exact = Cesium.Cartesian3.distance(CENTRE, nearest[0].position);
assert.ok(Math.abs(nearest[0].distanceM - exact) < 1e-6);
assert.ok(Math.abs(nearest[0].latitude - 30.5) < 1e-6);
assert.equal(nearest[0].satelliteClass, 'imaging');
assert.equal(methods.getNearestPositions(CENTRE, 1, { excludeIds: [6] })[0].label, 'DEB');
assert.deepEqual(methods.getNearestPositions(null, 3), []);
assert.deepEqual(methods.getNearestPositions(CENTRE, 0), []);
assert.deepEqual(methods.getNearestPositions(CENTRE, 0.5), []);
assert.equal(methods.getNearestPositions(CENTRE, 2.5).length, 2);
});
+65 -5
View File
@@ -15,6 +15,57 @@ import {
} from '../../sources/tle.js';
import { ORBIT_PATH_STEPS, ISS_NORAD } from './policy.js';
/** The Earth's rotation rate, rad/s (WGS84). */
const EARTH_ROTATION_RAD_S = 7.292115e-5;
/** Below this ground speed a satellite holds still over the ground (GEO), m/s. */
const GROUND_TRACK_MIN_SPEED_MPS = 10;
/**
* The ground track's bearing, degrees clockwise from north, from one SGP4
* state: the inertial velocity turned into the Earth-fixed frame, less the
* Earth's rotation under the satellite, read in the east/north plane at the
* sub-satellite point. Null without a velocity, or for a satellite that holds
* still over the ground (geostationary).
* @param {{x: number, y: number, z: number}} positionKm TEME position, km.
* @param {{x: number, y: number, z: number}|null} velocityKmS TEME velocity, km/s.
* @param {number} gmst Greenwich mean sidereal time, radians.
* @param {number} latitudeDeg Sub-satellite latitude.
* @param {number} longitudeDeg Sub-satellite longitude.
* @returns {number|null}
*/
export function groundTrackBearingDeg(
positionKm,
velocityKmS,
gmst,
latitudeDeg,
longitudeDeg,
) {
if (!positionKm || !velocityKmS || !Number.isFinite(gmst)) return null;
const cosG = Math.cos(gmst);
const sinG = Math.sin(gmst);
// TEME to Earth-fixed is a turn about z by GMST.
const rx = cosG * positionKm.x + sinG * positionKm.y;
const ry = -sinG * positionKm.x + cosG * positionKm.y;
const vx =
(cosG * velocityKmS.x + sinG * velocityKmS.y + EARTH_ROTATION_RAD_S * ry) *
1000;
const vy =
(-sinG * velocityKmS.x + cosG * velocityKmS.y - EARTH_ROTATION_RAD_S * rx) *
1000;
const vz = velocityKmS.z * 1000;
const φ = (latitudeDeg * Math.PI) / 180;
const λ = (longitudeDeg * Math.PI) / 180;
const east = -Math.sin(λ) * vx + Math.cos(λ) * vy;
const north =
-Math.sin(φ) * Math.cos(λ) * vx -
Math.sin(φ) * Math.sin(λ) * vy +
Math.cos(φ) * vz;
if (![east, north].every(Number.isFinite)) return null;
if (Math.hypot(east, north) < GROUND_TRACK_MIN_SPEED_MPS) return null;
return ((Math.atan2(east, north) * 180) / Math.PI + 360) % 360;
}
export function createOrbits({ state: layerState, services, parts, source }) {
/**
* Build the rigid ECEF transform that keeps an orbit path baked at one GMST
@@ -68,11 +119,20 @@ export function createOrbits({ state: layerState, services, parts, source }) {
? Math.hypot(velocity.x, velocity.y, velocity.z) * 1000
: null;
const latitude = degreesLat(geo.latitude);
const longitude = degreesLong(geo.longitude);
return {
longitude: degreesLong(geo.longitude),
latitude: degreesLat(geo.latitude),
longitude,
latitude,
altitude: geo.height * 1000, // km → meters
speedMps: Number.isFinite(speedMps) ? speedMps : null,
groundTrackDeg: groundTrackBearingDeg(
posVel.position,
velocity,
gmst,
latitude,
longitude,
),
};
} catch {
return null;
@@ -137,7 +197,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
lonDeg,
minElevDeg = 10,
requireVisible = false,
fromMs = Date.now(),
fromMs = layerState.now(),
}) {
return getNextSatellitePass(ISS_NORAD, {
latDeg,
@@ -167,7 +227,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
lonDeg,
minElevDeg = 10,
requireVisible = false,
fromMs = Date.now(),
fromMs = layerState.now(),
},
) {
const id = Number(noradId);
@@ -271,7 +331,7 @@ export function createOrbits({ state: layerState, services, parts, source }) {
}
function orbitTrackFromRecord(name, satrec) {
const referenceDate = new Date();
const referenceDate = new Date(layerState.now());
const current = propagatePosition(satrec, referenceDate);
if (!current) return null;
return {
+54 -3
View File
@@ -1,12 +1,16 @@
import * as Cesium from 'cesium';
import { satelliteClassColor } from '../../data/satelliteClass.js';
import { SATELLITE_CLASS_DISPLAY, SATELLITE_CLASS_IDS } from './classes.js';
/**
* Satellite Orbits — Real-time positions via CelesTrak TLE + SGP4 propagation.
*
* Loads six CelesTrak groups (~840 sats): stations, visual, GPS, GLONASS,
* Galileo, and the geosynchronous belt. Optional dense mode (setParams
* catalog:'dense') adds the Starlink shell as points-only extras.
* Loads eleven CelesTrak groups: stations, visual, GPS, GLONASS, Galileo, the
* geosynchronous belt, and the Earth resources, weather, Planet, SAR and
* science groups. Each object is filed under one of six classes
* (src/layers/satellites/classes.js) whose visibility the layer row toggles; dense mode
* (setParams catalog:'dense', the STARLINK toggle) adds the Starlink shell as
* points-only extras.
* Renders positions via PointPrimitiveCollection, orbital paths as polylines.
* Click any satellite to track it with camera follow + orbital path.
*
@@ -28,6 +32,15 @@ export const ORBIT_PATH_STEPS = 180;
// points per orbital path
export const POSITION_UPDATE_MS = 1000;
/** How far either side of now SGP4 on current element sets stays meaningful. */
export const SATELLITE_COVERAGE_MS = 14 * 24 * 3_600_000;
/**
* How far the world time may move from when an orbit ring was drawn before it
* is drawn again: the Earth's turn is followed exactly, but the orbit's plane
* 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;
@@ -49,6 +62,13 @@ export const CATALOG_GROUPS = [
{ tag: 'glonass', path: 'glo-ops' },
{ tag: 'galileo', path: 'galileo' },
{ tag: 'geo', path: 'geo' },
// Earth observation launched after the UCS snapshot, and science probes.
// Each object's class comes from src/layers/satellites/classes.js, not its group.
{ tag: 'resource', path: 'resource' },
{ tag: 'weather', path: 'weather' },
{ tag: 'planet', path: 'planet' },
{ tag: 'sar', path: 'sar' },
{ tag: 'science', path: 'science' },
];
// Dense-catalog mode (setParams({ catalog: 'dense' })): Starlink shell as
@@ -157,6 +177,37 @@ export const POINT_STYLES = {
},
};
const CLASS_COLORS = Object.fromEntries(
SATELLITE_CLASS_IDS.map((id) => [
id,
Cesium.Color.fromCssColorString(SATELLITE_CLASS_DISPLAY[id].color),
]),
);
const _classStyles = new Map();
/**
* A satellite's point style: its group's size and outline, in its class's
* colour (src/layers/satellites/classes.js), so the dots match the class legend and
* toggles. Styles are shared per group and class.
* @param {string|undefined} group Catalog group tag.
* @param {string|undefined} satelliteClass Class id.
*/
export function classPointStyle(group, satelliteClass) {
const base = POINT_STYLES[group] || POINT_STYLES.visual;
const color = CLASS_COLORS[satelliteClass];
if (!color) return base;
const key = `${group}|${satelliteClass}`;
let style = _classStyles.get(key);
if (!style) {
style = Object.freeze({
...base,
color: group === 'dense' ? color.withAlpha(0.9) : color,
});
_classStyles.set(key, style);
}
return style;
}
/**
* Physically DOCKED vehicles are separate real tracks sharing one position: the
* station and everything berthed to it sit within metres of each other. Their
+13 -3
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { satelliteClassLabel } from '../../data/satelliteClass.js';
import { satelliteClassText } from '../../data/satelliteClass.js';
import { ISS_NORAD } from './policy.js';
/**
@@ -38,7 +38,10 @@ export function mapAnalystRecord(raw) {
// must not leak onto a row that has no satellite identity.
satelliteClass:
noradId || group
? satelliteClassLabel(group, { isIss, localize: false })
? satelliteClassText(text(raw?.satelliteClass), group, {
isIss,
localize: false,
})
: null,
group,
};
@@ -79,10 +82,16 @@ export function createRecords({ state, parts }) {
const limit = Number.isFinite(maxCount)
? Math.max(1, Math.floor(maxCount))
: 2000;
const now = new Date();
const now = new Date(state.now());
const result = [];
const emit = (noradId, sat) => {
if (result.length >= limit) return false;
// A class the user hid stays out of answers too; the tracked one stays.
if (
noradId !== state._trackedNorad &&
parts.controls?._classVisible?.(noradId) === false
)
return true;
const pos = analystGeo(noradId, sat, now);
if (!pos) return true;
result.push(
@@ -90,6 +99,7 @@ export function createRecords({ state, parts }) {
noradId,
name: sat?.name,
group: sat?.group,
satelliteClass: sat?.satelliteClass,
lat: pos.lat,
lon: pos.lon,
altitudeM: pos.altitudeM,
+38 -12
View File
@@ -1,6 +1,11 @@
import * as Cesium from 'cesium';
import { gstime } from 'satellite.js';
import { ISS_NORAD, POSITION_UPDATE_MS, RING_ROTATION_MS } from './policy.js';
import {
ISS_NORAD,
ORBIT_REBAKE_MS,
POSITION_UPDATE_MS,
RING_ROTATION_MS,
} from './policy.js';
export function createRendering({
state: layerState,
@@ -42,26 +47,28 @@ export function createRendering({
const sat = layerState._catalog.get(noradId);
if (!sat || !layerState._viewer) return;
const bakeDate = new Date();
const bakeDate = new Date(layerState.now());
const basePositions = parts.orbits.computeOrbitPath(sat.satrec, bakeDate);
if (basePositions.length < 2) return;
const pathColor = color || Cesium.Color.CYAN;
// Kept so the Cockpit's orbit dim (cockpitSubject.js) restores exactly.
const baseColor = pathColor.withAlpha(0.6);
const baseDepthFailColor = pathColor.withAlpha(0.35);
const instanceId = `satellite-orbit:${noradId}`;
const primitive = new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
id: instanceId,
geometry: new Cesium.PolylineGeometry({
positions: basePositions,
width: noradId === ISS_NORAD ? 2.5 : 2.0,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.6),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
pathColor.withAlpha(0.35),
),
color: Cesium.ColorGeometryInstanceAttribute.fromColor(baseColor),
depthFailColor:
Cesium.ColorGeometryInstanceAttribute.fromColor(baseDepthFailColor),
},
}),
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
@@ -75,10 +82,17 @@ export function createRendering({
layerState._orbitPaths.set(noradId, {
primitive,
color: pathColor,
bakeMs: bakeDate.getTime(),
// Same Date object as computeOrbitPath's internal fixedGmst → identical
// GMST value (gstime is pure), so delta starts at exactly 0 and the
// initial identity modelMatrix is correct until the first ring tick.
gmstAtBake: gstime(bakeDate),
instanceId,
baseColor,
baseDepthFailColor,
// The alpha multiple last written to the instance (1: as built).
alphaFactor: 1,
});
}
@@ -113,8 +127,15 @@ export function createRendering({
function _updateOrbitPathRotations(nowDate) {
if (layerState._orbitPaths.size === 0) return;
for (const path of layerState._orbitPaths.values()) {
for (const [noradId, path] of [...layerState._orbitPaths]) {
if (!path.primitive) continue;
// The rotation keeps the ring under the dot for minutes; the plane
// itself precesses, so a world time moved far from the bake re-bakes.
if (Math.abs(nowDate.getTime() - path.bakeMs) > ORBIT_REBAKE_MS) {
_hideOrbitPath(noradId);
_showOrbitPath(noradId, path.color);
continue;
}
parts.orbits.orbitFrameModelMatrix(
path.gmstAtBake,
nowDate,
@@ -138,12 +159,13 @@ export function createRendering({
/**
* Propagate all CORE satellite positions and update point primitives.
* (~840 sats ≈ 1.6 ms/pass — fine at the 1s/200ms cadence.) Dense extras are
* (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.
*/
function _propagateAll() {
const now = new Date();
const now = new Date(layerState.now());
let updated = 0;
for (const [noradId, sat] of layerState._catalog) {
@@ -203,6 +225,10 @@ export function createRendering({
}
}
// While the Cockpit rides the tracked satellite, keep its marks hidden.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
_updatePointFocus(now);
// Hidden standalone orbit primitives do not need GMST matrix writes while
@@ -211,7 +237,7 @@ export function createRendering({
layerState._params.showOrbits &&
now - layerState._lastRingRotation >= RING_ROTATION_MS
) {
_updateOrbitPathRotations(new Date(now));
_updateOrbitPathRotations(new Date(layerState.now()));
layerState._lastRingRotation = now;
}
}
+100
View File
@@ -0,0 +1,100 @@
/**
* @file Imaging sensors: which Earth-observation platform a satellite is, and
* the swath its sensor images. The orbital view draws that swath to scale and
* lets a satellite zoom past 8x only as far as its sensor's narrowest
* standard swath (src/cockpitOrbital.js `orbitalMaxZoom`).
*
* Pure: no Cesium, no fetches; the bundled pack is loaded by
* src/data/imagingSensors.js.
*
* @module imagingSensors
*/
/**
* One sensor-pack entry as the app uses it.
* @typedef {{id: string, label: string, operator: string|null,
* sensor: string, type: string, altitudeKm: number|null,
* modes: Array<{name: string, swathKm: number|null, gsdM: number|null}>,
* narrowestSwathKm: number|null, swathConfirmed: boolean,
* sources: string[], unverified: string[]}} ImagingSensor
*/
/**
* Index the pack for matching: exact NORAD numbers first, then name patterns
* in pack order. A malformed pattern is skipped, not fatal.
* @param {{entries?: Array<object>}} pack Parsed `imaging_sensors.json`.
* @returns {{byNorad: Map<number, ImagingSensor>,
* patterns: Array<{pattern: RegExp, sensor: ImagingSensor}>}}
*/
export function indexImagingSensors(pack) {
const byNorad = new Map();
const patterns = [];
for (const entry of pack?.entries || []) {
if (!entry?.id) continue;
const sensor = Object.freeze({
id: entry.id,
label: entry.label || entry.id,
operator: entry.operator ?? null,
sensor: entry.sensor || '',
type: entry.type || '',
altitudeKm: Number.isFinite(entry.altitudeKm) ? entry.altitudeKm : null,
modes: Object.freeze(
(entry.modes || []).map((mode) => Object.freeze({ ...mode })),
),
narrowestSwathKm: Number.isFinite(entry.narrowestSwathKm)
? entry.narrowestSwathKm
: null,
swathConfirmed: entry.swathConfirmed === true,
sources: Object.freeze([...(entry.sources || [])]),
unverified: Object.freeze([...(entry.unverified || [])]),
});
for (const noradId of entry.match?.norad || []) {
if (Number.isInteger(noradId) && !byNorad.has(noradId))
byNorad.set(noradId, sensor);
}
if (entry.match?.nameRegex) {
try {
patterns.push({ pattern: new RegExp(entry.match.nameRegex), sensor });
} catch {
// A bad pattern only loses its name match; NORAD ids still work.
}
}
}
return { byNorad, patterns };
}
/**
* The sensor entry for a satellite: by NORAD number, else by its CelesTrak
* name (upper-cased, trimmed).
* @param {ReturnType<typeof indexImagingSensors>|null|undefined} index
* @param {{noradId?: number, name?: string}} satellite
* @returns {ImagingSensor|null}
*/
export function matchImagingSensor(index, { noradId, name } = {}) {
if (!index) return null;
const byId = index.byNorad?.get(noradId);
if (byId) return byId;
const text = String(name || '')
.trim()
.toUpperCase();
if (!text) return null;
for (const { pattern, sensor } of index.patterns || [])
if (pattern.test(text)) return sensor;
return null;
}
/**
* The swath the orbital view may zoom to: the narrowest standard swath, only
* when it was confirmed on a cited page. An unconfirmed swath keeps the
* satellite at the base zoom steps.
* @param {ImagingSensor|null|undefined} sensor
* @returns {number|null} Kilometres.
*/
export function zoomableSwathKm(sensor) {
const swathKm = sensor?.narrowestSwathKm;
return sensor?.swathConfirmed === true &&
Number.isFinite(swathKm) &&
swathKm > 0
? swathKm
: null;
}
+154
View File
@@ -0,0 +1,154 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import {
indexImagingSensors,
matchImagingSensor,
zoomableSwathKm,
} from './sensors.js';
import { loadImagingSensors } from '../../data/imagingSensors.js';
const PACK_URL = new URL(
'../../data/local_data/imaging_sensors/imaging_sensors.json',
import.meta.url,
);
const PACK = {
entries: [
{
id: 'worldview-3',
label: 'WorldView-3',
match: { norad: [40115], nameRegex: '^WORLDVIEW-3' },
narrowestSwathKm: 13.1,
swathConfirmed: true,
},
{
id: 'iceye',
label: 'ICEYE',
match: { nameRegex: '^ICEYE-X\\d+' },
narrowestSwathKm: 5,
swathConfirmed: true,
},
{
id: 'broken',
label: 'Broken pattern',
match: { norad: [1], nameRegex: '([' },
narrowestSwathKm: 9,
swathConfirmed: true,
},
{
id: 'blacksky',
label: 'BlackSky',
match: { nameRegex: '^GLOBAL-\\d+$' },
narrowestSwathKm: null,
swathConfirmed: false,
},
],
};
test('a satellite matches its sensor by NORAD number, then by name', () => {
const index = indexImagingSensors(PACK);
assert.equal(
matchImagingSensor(index, { noradId: 40115 })?.id,
'worldview-3',
);
// An id match wins over a name that says otherwise.
assert.equal(
matchImagingSensor(index, { noradId: 40115, name: 'ICEYE-X9' })?.id,
'worldview-3',
);
assert.equal(
matchImagingSensor(index, { noradId: 99999, name: ' iceye-x14 ' })?.id,
'iceye',
);
assert.equal(matchImagingSensor(index, { noradId: 1 })?.id, 'broken');
assert.equal(matchImagingSensor(index, { name: 'STARLINK-1007' }), null);
assert.equal(matchImagingSensor(null, { noradId: 40115 }), null);
});
test('only a confirmed swath opens zoom steps past 8x', () => {
const index = indexImagingSensors(PACK);
assert.equal(
zoomableSwathKm(matchImagingSensor(index, { noradId: 40115 })),
13.1,
);
assert.equal(
zoomableSwathKm(matchImagingSensor(index, { name: 'GLOBAL-21' })),
null,
);
assert.equal(zoomableSwathKm(null), null);
assert.equal(
zoomableSwathKm({ swathConfirmed: true, narrowestSwathKm: 0 }),
null,
'no swath to zoom to',
);
});
test('the bundled pack is well formed and cites its sources', () => {
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
assert.ok(pack.entries.length >= 40);
assert.ok(
readFileSync(PACK_URL).length < 60_000,
'small enough for the layer',
);
const ids = new Set();
for (const entry of pack.entries) {
assert.ok(entry.id && !ids.has(entry.id), `unique id ${entry.id}`);
ids.add(entry.id);
assert.ok(entry.match.norad || entry.match.nameRegex, entry.id);
if (entry.match.nameRegex) new RegExp(entry.match.nameRegex);
assert.ok(entry.sources.length > 0, `${entry.id} cites a source`);
if (entry.swathConfirmed) {
assert.ok(entry.narrowestSwathKm > 0, entry.id);
// The narrowest *standard* swath: sampling modes (Himawari's landmark
// area) and older generations (Dove Classic) may be narrower.
const swaths = entry.modes
.map((mode) => mode.swathKm)
.filter(Number.isFinite);
assert.ok(
swaths.includes(entry.narrowestSwathKm),
`${entry.id}: the narrowest swath is one of its modes`,
);
}
}
});
test('the pack cites no reseller, links its datasheets and names its own fields', () => {
const pack = JSON.parse(readFileSync(PACK_URL, 'utf8'));
// Resellers, Gunter's Space Page, and the Copernicus portal whose terms
// forbid reuse.
const excluded =
/euspaceimaging\.com|apollomapping\.com|landinfo\.com|satimagingcorp\.com|space\.skyrocket\.de|dataspace\.copernicus\.eu/;
const fields = new Set(['altitudeKm', 'narrowestSwathKm', 'swathKm', 'gsdM']);
for (const entry of pack.entries) {
for (const source of entry.sources)
assert.doesNotMatch(source, excluded, `${entry.id}: ${source}`);
// A bare file-host datasheet is cited beside the operator page that
// links it.
if (entry.sources.some((source) => /cdn\.sanity\.io/.test(source)))
assert.ok(
entry.sources.some((source) => /^https:\/\/vantor\.com\//.test(source)),
`${entry.id}: the Vantor page for its datasheet`,
);
// An unverified value is named by the pack's own field.
for (const note of entry.unverified) {
const [field] = /^[A-Za-z_]+/.exec(note) ?? [''];
if (/^[a-z]+(_[a-z]+)+$|^[a-z]+[A-Z]\w*$/.test(field))
assert.ok(fields.has(field), `${entry.id}: unknown field ${field}`);
}
}
});
test('the pack loads once and matches real catalog names', async () => {
const index = await loadImagingSensors();
assert.equal(index, await loadImagingSensors(), 'loaded once');
const cases = [
[{ noradId: 49260, name: 'LANDSAT 9' }, 'landsat-8-9'],
[{ noradId: 40115, name: 'WORLDVIEW-3 (WV-3)' }, 'worldview-3'],
[{ noradId: 1, name: 'FLOCK 4Q-12' }, 'planetscope'],
[{ noradId: 1, name: 'ICEYE-X40' }, 'iceye'],
[{ noradId: 1, name: 'SKYSAT-C19' }, 'skysat'],
];
for (const [satellite, id] of cases)
assert.equal(matchImagingSensor(index, satellite)?.id, id, satellite.name);
});
+48
View File
@@ -6,11 +6,31 @@ const GROUPS = new Set([
'galileo',
'geo',
'starlink',
// Imaging coverage beyond the UCS May 2023 snapshot, and science probes.
'resource',
'weather',
'planet',
'sar',
'science',
]);
/** The UCS pack, loaded on first use (see src/data/ucsSatellites.js). */
async function loadBundledUcs() {
const { loadUcsSatellites } = await import('../../data/ucsSatellites.js');
return loadUcsSatellites();
}
/** The imaging-sensor pack, loaded on first use (see src/data/imagingSensors.js). */
async function loadBundledSensors() {
const { loadImagingSensors } = await import('../../data/imagingSensors.js');
return loadImagingSensors();
}
/** Read catalog text from the existing group endpoint using a supplied transport. */
export function createSatelliteSource({
fetchImpl = (...args) => globalThis.fetch(...args),
loadUcs = loadBundledUcs,
loadSensors = loadBundledSensors,
} = {}) {
return {
async readGroup(group, { signal } = {}) {
@@ -24,5 +44,33 @@ export function createSatelliteSource({
const stale = response.headers?.get?.('x-tle-cache') === 'STALE-ERROR';
return { ok: response.ok, status: response.status, text, stale };
},
/**
* CelesTrak SATCAT records (CSV) for one group: object type, operational
* status and owner, through the proxy's day-long cache.
*/
async readSatcat(group, { signal } = {}) {
if (!GROUPS.has(group)) throw new TypeError('Unknown satellite group');
signal?.throwIfAborted();
const response = await fetchImpl(`/api/celestrak-satcat/${group}`, {
signal,
});
const text = response.ok ? await response.text() : '';
signal?.throwIfAborted();
// The proxy serves its last copy, marked STALE-ERROR, when CelesTrak
// is down.
const stale = response.headers?.get?.('x-satcat-cache') === 'STALE-ERROR';
return { ok: response.ok, status: response.status, text, stale };
},
/** The UCS Satellite Database pack, keyed by NORAD number. */
readUcs() {
return loadUcs();
},
/** The imaging-sensor pack, indexed by NORAD number and name pattern. */
readSensors() {
return loadSensors();
},
};
}
+21
View File
@@ -164,3 +164,24 @@ test('satellite pass prediction methods report no-tle on cold catalog and coerce
{ status: 'no-tle' },
);
});
test('a SATCAT read says when the proxy served its last copy', async () => {
const headers = (cache) => ({
get: (name) => (name === 'x-satcat-cache' ? cache : null),
});
let cache = 'STALE-ERROR';
const source = createSatelliteSource({
fetchImpl: async (url) => {
assert.equal(url, '/api/celestrak-satcat/visual');
return {
ok: true,
status: 200,
headers: headers(cache),
text: async () => 'OBJECT_NAME,NORAD_CAT_ID,OBJECT_TYPE',
};
},
});
assert.equal((await source.readSatcat('visual')).stale, true);
cache = 'HIT';
assert.equal((await source.readSatcat('visual')).stale, false);
});
+23 -15
View File
@@ -24,7 +24,15 @@ const GROUPS = [
'galileo',
'geo',
'starlink',
// Added after Starlink so the fixture ids above keep their numbers.
'resource',
'weather',
'planet',
'sar',
'science',
];
/** The core catalog's groups, one owned satellite each. */
const CORE = GROUPS.filter((group) => group !== 'starlink');
function tle(id, invalid = false) {
// Owned synthetic catalog IDs over one valid element set; never live requests.
@@ -143,10 +151,10 @@ test('stale core records surface through actual HTTP, ingestion and feed state,
const f = await fixture(t);
await f.update();
assert.equal(f.feed(), 'nominal');
assert.equal(f.stats().count, 6);
f.policy.stale = new Set(GROUPS.slice(0, 6));
assert.equal(f.stats().count, CORE.length);
f.policy.stale = new Set(CORE);
await f.update();
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.stats().stale, true);
assert.equal(f.feed(), 'stale');
f.policy.stale = new Set(['visual']);
@@ -163,13 +171,13 @@ test('a stale duplicate cannot taint its earlier fresh winning record', async (t
f.policy.stale.add('visual');
f.policy.ids.visual = 25545;
await f.update();
assert.equal(f.stats().count, 5);
assert.equal(f.stats().count, CORE.length - 1);
assert.equal(f.state._catalog.get(25545).group, 'stations');
assert.equal(f.stats().stale, false);
assert.equal(f.feed(), 'nominal');
f.policy.stale = new Set(['stations']);
await f.update();
assert.equal(f.stats().count, 5);
assert.equal(f.stats().count, CORE.length - 1);
assert.equal(
f.stats().stale,
true,
@@ -182,7 +190,7 @@ test('invalid stale orbital elements are not admitted as provenance', async (t)
f.policy.stale.add('visual');
f.policy.invalid.add('visual');
await f.update();
assert.equal(f.stats().count, 5);
assert.equal(f.stats().count, CORE.length - 1);
assert.equal(f.state._catalog.has(25546), false);
assert.equal(f.stats().stale, false);
});
@@ -194,17 +202,17 @@ test('failed and aborted core refreshes keep provenance of retained records', as
const priorTime = f.stats().lastUpdate;
f.policy.status = 503;
await f.update();
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.stats().stale, true);
assert.equal(f.stats().status, 'unavailable');
assert.equal(f.stats().lastUpdate, priorTime);
f.policy.hold = true;
const controller = new AbortController();
const work = f.update({ signal: controller.signal });
await f.waitHeld(6);
await f.waitHeld(CORE.length);
controller.abort();
await assert.rejects(work, { name: 'AbortError' });
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.stats().stale, true);
assert.equal(f.stats().lastUpdate, priorTime);
assert.equal(f.state._activeUpdateControllers.size, 0);
@@ -216,11 +224,11 @@ test('dense provenance belongs to its admitted records and clears on removal', a
f.policy.stale.add('starlink');
f.state._params.catalog = 'dense';
assert.equal((await f.parts.catalog._loadDenseCatalog()).status, 'ready');
assert.equal(f.stats().count, 7);
assert.equal(f.stats().count, CORE.length + 1);
assert.equal(f.feed(), 'stale');
f.state._params.catalog = 'core';
f.parts.catalog._removeDenseCatalog();
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.feed(), 'nominal');
f.policy.stale = new Set(['stations']);
await f.update();
@@ -261,13 +269,13 @@ test('cancelling dense replacement preserves admitted stale extras until rebuild
await f.waitHeld(1);
controller.abort();
assert.equal((await work).status, 'cancelled');
assert.equal(f.stats().count, 7);
assert.equal(f.stats().count, CORE.length + 1);
assert.equal(f.feed(), 'stale');
f.policy.hold = false;
f.policy.stale.clear();
f.state._params.catalog = 'core';
await f.update();
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.feed(), 'nominal');
});
@@ -277,7 +285,7 @@ test('destroy aborts an in-flight response and initialization starts with new ow
await f.update();
f.policy.hold = true;
const work = f.update();
await f.waitHeld(6);
await f.waitHeld(CORE.length);
const rejected = assert.rejects(work, { name: 'AbortError' });
f.parts.lifecycle.methods.destroy(f.viewer);
assert.equal(f.stats().count, 0);
@@ -288,6 +296,6 @@ test('destroy aborts an in-flight response and initialization starts with new ow
f.policy.hold = false;
f.policy.stale.clear();
await f.update();
assert.equal(f.stats().count, 6);
assert.equal(f.stats().count, CORE.length);
assert.equal(f.feed(), 'nominal');
});
+47 -2
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { DEFAULT_SATELLITE_CLASSES } from './classes.js';
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
@@ -13,7 +15,9 @@ export function createState({ services }) {
state._overlayHost = state.DEFAULT_OVERLAY_HOST;
// Satellite catalog: { noradId → { name, satrec, group } }
// Satellite catalog: { noradId → { name, satrec, group, line1, line2,
// satelliteClass, ucs, satcat } } — class, UCS and SATCAT records from
// src/layers/satellites/classes.js and the sources the update read.
state._catalog = new Map();
@@ -42,6 +46,12 @@ export function createState({ services }) {
// Cache provenance belongs to admitted core and dense records separately.
state._coreStale = false;
// How current the SATCAT records behind the classes are: null before any
// read, then 'current' | 'stale' | 'unavailable' (see ingestion.js).
state._satcatState = null;
// When _satcatState was last set (Date.now()); a current read is kept
// SATCAT_KEEP_MS (src/layers/satellites/ingestion.js).
state._satcatReadAtMs = Number.NEGATIVE_INFINITY;
state._denseStale = false;
state._activeUpdateControllers = new Set();
@@ -92,9 +102,25 @@ export function createState({ services }) {
// Runtime params (DataLayerManager.setLayerParams path)
state._params = { catalog: 'core', showPoints: true, showOrbits: true };
state._params = {
catalog: 'core',
showPoints: true,
showOrbits: true,
// Which satellite classes show (src/layers/satellites/classes.js). Starlink
// follows `catalog`: its points exist only in dense mode.
classes: { ...DEFAULT_SATELLITE_CLASSES },
};
// 'core' | 'dense'
/** SATCAT records (object type, status, owner) by NORAD id, last update. */
state._satcat = new Map();
/** The UCS pack by NORAD id, once loaded; null until then or if it failed. */
state._ucs = null;
/** The imaging-sensor index, once loaded; null until then or if it failed. */
state._sensors = null;
state._denseIds = [];
// norad ids of dense extras, round-robin order
@@ -151,6 +177,25 @@ export function createState({ services }) {
state._trackedFrameNowForTest = null;
// Cockpit orbital-view hold (cockpitSubject.js): the NORAD id the Cockpit
// camera rides, and what the hold hid so release restores exactly that.
state._cockpitSubjectNorad = null;
state._cockpitHiddenPoints = new Set();
state._cockpitHiddenPath = null;
state._cockpitHiddenDot = false;
/** The time satellites are propagated to, in epoch ms. */
state.now = worldTimeFor('satellites');
/** The catalog changed, so the time satellites can be shown at may have. */
state.coverageChanged = () => worldClock.coverageChanged();
// Scratch variables
state._scratchCartesian = new Cesium.Cartesian3();
+7 -1
View File
@@ -26,10 +26,14 @@ export function createTesting({ state: layerState, services, parts, source }) {
// Extra catalog/point rows so a test can exercise a docked cluster (and a
// control satellite that must NOT be treated as part of it).
neighbours = [],
// Optional class of the tracked satellite and class visibility, e.g.
// { telecom: false }.
satelliteClass = undefined,
classes = null,
}) {
layerState._viewer = viewer;
layerState._catalog = new Map([
[noradId, { name, satrec, group: 'stations' }],
[noradId, { name, satrec, group: 'stations', satelliteClass }],
]);
layerState._points = new Map([[noradId, point]]);
for (const neighbour of neighbours) {
@@ -37,6 +41,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
name: neighbour.name,
satrec: neighbour.satrec || satrec,
group: neighbour.group || 'stations',
satelliteClass: neighbour.satelliteClass,
});
layerState._points.set(neighbour.noradId, neighbour.point);
}
@@ -51,6 +56,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
catalog: 'core',
showPoints: false,
showOrbits: false,
...(classes ? { classes } : {}),
};
layerState._enabled = true;
}
+20 -11
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { satelliteClassLabel } from '../../data/satelliteClass.js';
import { satelliteClassText } from '../../data/satelliteClass.js';
import { t } from '../../i18n/index.js';
import { formatQuantity, unitLabel } from '../../ui/unitLabels.js';
import {
@@ -95,7 +95,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedNorad,
layerState._catalog.get(layerState._trackedNorad)?.group,
);
lastPos.show = true;
// Back to its class's visibility: a hidden class stays hidden.
lastPos.show = parts.controls._classVisible(layerState._trackedNorad);
lastPos.pixelSize = style.pixelSize;
lastPos.color = style.color;
lastPos.outlineColor = style.outlineColor;
@@ -118,6 +119,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
layerState._trackedEntity = null;
}
layerState._trackedNorad = null;
parts.controls._syncIssOrbit?.();
// A held Cockpit subject that stops being tracked gets its marks back.
if (layerState._cockpitSubjectNorad !== null)
parts.cockpit?._syncCockpitSubjectVisuals();
parts.labels._syncIssOverlay();
clearTrackedSubjectContext('satellites');
layerState._contextRefreshedAtMs = 0;
@@ -150,13 +155,13 @@ export function createTracking({ state: layerState, services, parts, source }) {
frameNumber !== layerState._trackedFrameNumber ||
layerState._trackedFrameGeo === null
) {
const pos = parts.orbits.propagatePosition(
sat.satrec,
layerState._trackedFrameNowForTest
? new Date(layerState._trackedFrameNowForTest())
: new Date(),
);
const atMs = layerState._trackedFrameNowForTest
? layerState._trackedFrameNowForTest()
: layerState.now();
const pos = parts.orbits.propagatePosition(sat.satrec, new Date(atMs));
if (!pos) return layerState._trackedFrameGeo; // propagation hiccup — keep last good sample
// The time the sample is at: the world clock's, not the wall clock's.
pos.atMs = atMs;
layerState._trackedFrameGeo = pos;
Cesium.Cartesian3.fromDegrees(
pos.longitude,
@@ -241,7 +246,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
name,
operator: '',
noradId: String(noradId),
class: satelliteClassLabel(sat.group, {
class: satelliteClassText(sat.satelliteClass, sat.group, {
isIss: noradId === ISS_NORAD,
localize: false,
}),
@@ -366,7 +371,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
// looking at, and it stays readable under the IR styles that flatten the
// dot colors to a single channel (the card is painted above post-FX).
const details = [
satelliteClassLabel(sat?.group, {
satelliteClassText(sat?.satelliteClass, sat?.group, {
isIss: layerState._trackedNorad === ISS_NORAD,
}),
detail,
@@ -420,6 +425,7 @@ export function createTracking({ state: layerState, services, parts, source }) {
// Show orbital path
parts.rendering._showOrbitPath(noradId, Cesium.Color.YELLOW);
if (noradId === ISS_NORAD) parts.controls._syncIssOrbit?.();
// Tracked entity position propagates per evaluation through the per-frame
// cache (WS-D2) — dot, host readout, and camera share one SGP4 epoch per frame.
@@ -434,7 +440,10 @@ export function createTracking({ state: layerState, services, parts, source }) {
// Comfortable tracking landing: ~726 km back for LEO (user-validated
// "slightly zoomed out" framing — no stutter, label reads cleanly), scaled
// up for MEO/GEO so the camera doesn't land on top of a high-orbit dot.
const initialPos = parts.orbits.propagatePosition(sat.satrec, new Date());
const initialPos = parts.orbits.propagatePosition(
sat.satrec,
new Date(layerState.now()),
);
const viewScale =
initialPos && initialPos.altitude > HIGH_ORBIT_ALTITUDE_M
? TRACK_VIEW_FROM_HIGH_SCALE
+6 -2
View File
@@ -8,6 +8,7 @@ import { createSelection } from './selection.js';
import { createViewerHost } from './viewerHost.js';
import { filtersOf, requiresKeyIdFor, validateProviders } from './registry.js';
import { normalizeFilter, resolveFilter, sameFilter } from './filter.js';
import { worldTimeFor } from '../../time/worldClock.js';
import { decodeParams, encodeParams } from './params.js';
import {
composeUIState,
@@ -41,6 +42,9 @@ const GROUND_RETRY_MS = 1000;
* a time.
* @param {{providers: Array<import('./registry.js').StreetLevelProvider>, services?: object}} options
*/
// "Since N days" counts back from the world time.
const streetLevelTime = worldTimeFor(STREET_LEVEL_LAYER_ID);
export function createStreetLevelLayer({
providers: definitions,
services = {},
@@ -93,7 +97,7 @@ export function createStreetLevelLayer({
return Object.freeze({
services: state.services,
/** Resolved against now, so "since N days" keeps up with the clock. */
getFilter: () => resolveFilter(state.filter),
getFilter: () => resolveFilter(state.filter, streetLevelTime()),
/** The layer and this provider's switch are both on. */
isActive: () => state.enabled && entry.on,
notify,
@@ -365,7 +369,7 @@ export function createStreetLevelLayer({
const filter = normalizeFilter(next, state.filter);
if (sameFilter(filter, state.filter)) return;
state.filter = filter;
const resolved = resolveFilter(filter);
const resolved = resolveFilter(filter, streetLevelTime());
for (const entry of state.providers.values())
entry.instance.setFilter(resolved);
notify();
+219
View File
@@ -0,0 +1,219 @@
// Street Traffic road lines build one set at a time: rebuilds asked for while
// a set is building wait, and only the newest of them runs.
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createRendering } from './rendering.js';
// Cesium tests a material's uniforms against these browser classes.
for (const name of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
])
globalThis[name] ??= class {};
// A line primitive's render state is checked against the context's limits,
// which only a WebGL context sets.
Cesium.ContextLimits._minimumAliasedLineWidth = 1;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
/** A road with flow; `level` picks its bucket (0.1 jam, 0.6 slow, 1 free). */
function road(level = 1) {
return {
flow: { level, closure: false },
segmentDist: [100],
waypoints: Cesium.Cartesian3.fromDegreesArray([
-97.744, 30.267, -97.742, 30.267,
]),
};
}
/**
* Rendering over a scene that records its ground primitives. Each added
* primitive is replaced by a stand-in whose `ready` the test sets, as Cesium
* sets it once the asynchronous geometry is built.
*/
function harness() {
const scene = [];
const added = [];
let linesOn = true;
const state = {
_viewer: {
scene: {
globe: { show: true },
groundPrimitives: {
add(primitive) {
const line = {
ready: false,
roads: primitive.geometryInstances.length,
};
scene.push(line);
added.push(line);
return line;
},
remove(line) {
const index = scene.indexOf(line);
if (index >= 0) scene.splice(index, 1);
},
},
},
},
_liveMode: true,
_showLines: true,
_heatSupported: true,
_heatJamPrim: null,
_heatSlowPrim: null,
_heatFreePrim: null,
_heatRetired: [],
_heatPendingRoads: null,
_heatLineCount: 0,
};
const rendering = createRendering({
state,
services: {},
source: {},
parts: {
style: { heatlineOn: () => linesOn },
animation: { syncRenderDemand() {} },
},
});
return {
state,
rendering,
scene,
added,
setLines(on) {
linesOn = on;
state._showLines = on;
},
/** Finish every build in the scene, then run a frame. */
frame({ built = true } = {}) {
if (built) for (const line of scene) line.ready = true;
rendering.retireHeatLines();
},
};
}
const roads = (count) => Array.from({ length: count }, () => road());
test('rebuilds asked for while lines build do not start more builds', () => {
const { rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
assert.equal(added.length, 1);
// Progressive paints while the first set builds.
for (const count of [2, 3, 4]) rendering.rebuildHeatLines(roads(count));
frame({ built: false });
assert.equal(added.length, 1, 'no build started during a build');
assert.equal(scene.length, 1);
assert.deepEqual(scene[0].roads, 1);
});
test('the newest rebuild asked for during a build is the one that runs', () => {
const { state, rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
for (const count of [2, 3, 4]) rendering.rebuildHeatLines(roads(count));
frame();
// One build for the three requests, of the last one's roads.
assert.deepEqual(
added.map((line) => line.roads),
[1, 4],
);
assert.equal(state._heatLineCount, 4);
assert.equal(state._heatPendingRoads, null);
// The set it replaces stays drawn while it builds, then goes.
assert.deepEqual(
scene.map((line) => line.roads),
[1, 4],
);
frame();
assert.deepEqual(
scene.map((line) => line.roads),
[4],
);
// Nothing is waiting, so later frames start nothing.
frame();
assert.equal(added.length, 2);
});
test('a rebuild with nothing building starts at once', () => {
const { rendering, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
frame();
rendering.rebuildHeatLines(roads(2));
assert.deepEqual(
added.map((line) => line.roads),
[1, 2],
);
});
test('turning lines off during a build removes them at once and drops the waiting rebuild', () => {
const { state, rendering, scene, added, setLines, frame } = harness();
rendering.rebuildHeatLines(roads(1));
frame();
rendering.rebuildHeatLines(roads(2));
rendering.rebuildHeatLines(roads(3));
assert.equal(scene.length, 2, 'the drawn set and the building one');
setLines(false);
rendering.rebuildHeatLines(roads(3));
assert.deepEqual(scene, [], 'not deferred behind the build');
assert.equal(state._heatPendingRoads, null);
assert.equal(state._heatLineCount, 0);
frame();
assert.equal(added.length, 2, 'the waiting rebuild never runs');
assert.deepEqual(scene, []);
});
test('a rebuild right after a build finishes does not keep the lines that build replaced', () => {
const { rendering, scene } = harness();
rendering.rebuildHeatLines(roads(1));
for (const line of scene) line.ready = true;
rendering.rebuildHeatLines(roads(2));
// The second build finishes, and a third is asked for before a frame ran.
for (const line of scene) line.ready = true;
rendering.rebuildHeatLines(roads(3));
assert.deepEqual(
scene.map((line) => line.roads),
[2, 3],
);
});
test('removing the lines drops the waiting rebuild', () => {
const { state, rendering, scene, added, frame } = harness();
rendering.rebuildHeatLines(roads(1));
rendering.rebuildHeatLines(roads(2));
rendering.removeHeatLines();
assert.deepEqual(scene, []);
assert.equal(state._heatPendingRoads, null);
frame();
assert.equal(added.length, 1);
});
test('a stream of rebuilds never leaves more than two sets in the scene, and ends with one', () => {
const { rendering, scene, added, frame } = harness();
let most = 0;
const lines = [road(0.1), road(0.6), road(1)];
// Three primitives per set: one per flow bucket.
for (let paint = 0; paint < 40; paint += 1) {
rendering.rebuildHeatLines(lines);
most = Math.max(most, scene.length);
// A build takes several paints.
if (paint % 5 === 4) frame();
else frame({ built: false });
most = Math.max(most, scene.length);
}
frame();
frame();
assert.equal(most <= 6, true, `${most} primitives at once`);
assert.equal(scene.length, 3, 'only the current set remains');
assert.equal(
scene.every((line) => line.ready),
true,
);
// Without coalescing every paint builds: 40 sets, 120 primitives.
assert.equal(
added.length <= 3 * 10,
true,
`${added.length} primitives built`,
);
});
+39 -13
View File
@@ -59,24 +59,37 @@ export function createRendering({
/** Remove the heat-line / flow-line ground primitives from the scene. */
function removeHeatLines() {
layerState._heatPendingRoads = null;
removePrimitives(takeHeatLines());
removePrimitives(layerState._heatRetired || []);
layerState._heatRetired = [];
parts.animation.syncRenderDemand?.();
}
/** @returns {boolean} Whether a line primitive's geometry is still building. */
function linesBuilding() {
return LINE_KEYS.some((key) => layerState[key] && !layerState[key].ready);
}
/**
* Replaced lines stay drawn until their successors finish building
* (GroundPolylinePrimitive geometry is asynchronous), so a rebuild never
* blinks. Called every held frame.
* blinks. Once they have, the replaced lines go and the newest rebuild
* asked for in the meantime starts. Called every held frame.
*/
function retireHeatLines() {
if (!layerState._heatRetired?.length) return;
if (LINE_KEYS.some((key) => layerState[key] && !layerState[key].ready))
return;
removePrimitives(layerState._heatRetired);
layerState._heatRetired = [];
if (linesBuilding()) return;
if (layerState._heatRetired?.length) {
removePrimitives(layerState._heatRetired);
layerState._heatRetired = [];
}
const pending = layerState._heatPendingRoads;
if (pending) {
layerState._heatPendingRoads = null;
rebuildHeatLines(pending);
}
}
/**
@@ -95,24 +108,37 @@ export function createRendering({
* the globe is hidden (photoreal) and on terrain or tiles otherwise. No-op in
* sim mode, when both looks are off, or without ground-primitive support.
*
* One build runs at a time. A city loads in progressive paints, each asking
* for a rebuild, and every build drapes up to the cap of polylines
* asynchronously. A rebuild asked for while lines are building only replaces
* the one waiting, which retireHeatLines starts when the build finishes, so
* the scene never holds more than the lines drawn and the lines building.
* Turning the lines off is never deferred.
*
* @param {Array} roads - Road objects visible in the current render.
*/
function rebuildHeatLines(roads) {
const wanted =
layerState._viewer && layerState._liveMode && parts.style.heatlineOn();
if (wanted && linesBuilding()) {
layerState._heatPendingRoads = roads;
return;
}
layerState._heatPendingRoads = null;
// No build is left for replaced lines to wait for (it finished, or lines
// are going off), so they go first and never pile up behind this rebuild.
removePrimitives(layerState._heatRetired || []);
layerState._heatRetired = [];
const previous = takeHeatLines();
const finish = () => {
// Nothing new to wait for: the old lines go now.
if (LINE_KEYS.some((key) => layerState[key]))
(layerState._heatRetired ||= []).push(...previous);
// Nothing new to wait for: the old lines go now.
else removePrimitives(previous);
parts.animation.syncRenderDemand?.();
};
if (
!layerState._viewer ||
!layerState._liveMode ||
!parts.style.heatlineOn()
)
return finish();
if (!wanted) return finish();
if (layerState._heatSupported === null) {
layerState._heatSupported = Cesium.GroundPolylinePrimitive.isSupported(
layerState._viewer.scene,
+4
View File
@@ -200,6 +200,10 @@ export function createState({ services, source }) {
layerState._heatRetired = [];
/** @type {Array|null} Roads of the newest rebuild asked for while the lines were building. */
layerState._heatPendingRoads = null;
/** @type {number} Heat-lines in the current render (stats). */
layerState._heatLineCount = 0;
Loaded 100 of 466 files, more files were not shown because too many files have changed in this diff. Show more