Merge branch 'main' into upstream/route-outage-unavailable

This commit is contained in:
German Khokhlov committed 2026-11-11 21:16:50 +04:00
commit a29611ca17
422 files changed
+53860 -1931

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;
}
+1 -1
View File
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
return (
items.find(
(item) =>
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
) || subject
);
}
+25 -1
View File
@@ -117,7 +117,7 @@ export function createPanel({ state: layerState, parts }) {
.slice(page, page + AWARENESS_PAGE_SIZE)
.map((item, index) => {
const label = formatAwarenessLabel(item);
const targetId = item.icao24 || item.mmsi || item.id;
const targetId = item.icao24 || item.id || item.mmsi;
const distance = presentAwarenessDistance(item.distanceM);
if (!targetId)
return {
@@ -182,6 +182,29 @@ 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,
// A photo whose answer names no photographer shows no credit line.
credit: photo.photographer
? t('Photo © {photographer}', { photographer: photo.photographer })
: '',
};
}
function renderResults() {
if (!layerState.enabled || !layerState.results) return hidePanel();
ensurePanel();
@@ -191,6 +214,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(
+128
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,130 @@ 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 shows an uncredited photo with no credit line', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: { ...PHOTO, photographer: '' },
});
assert.equal(view.photo.src, PHOTO.src);
assert.equal(view.photo.link, PHOTO.link);
assert.equal(view.photo.credit, '');
});
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. */
+54 -10
View File
@@ -85,7 +85,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
.filter(
(item) =>
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
);
const coverage = installationsState.stats?.coverage;
const installationRadius =
@@ -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;
}
@@ -477,7 +519,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
return {
layerId: record.layerId,
id: record.properties?.mmsi || record.id,
id: record.properties?.vesselId || record.id,
label: record.label || record.id,
memberNames: record.properties?.memberNames || [],
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
@@ -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,
+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;
+23 -11
View File
@@ -535,14 +535,26 @@ export function createModel({
return `${isolate(latPart)} ${isolate(lonPart)}`;
}
/**
* Millisecond delta → `{ unit: '<1h' | 'h' | 'd', count }`, or null for
* invalid input. Both age formatters read it, so they pick the same unit.
*/
function ageParts(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return null;
const hours = deltaMs / 3600000;
if (hours < 1) return { unit: '<1h', count: 0 };
const wholeHours = Math.round(hours);
if (wholeHours < 48) return { unit: 'h', count: wholeHours };
return { unit: 'd', count: Math.round(hours / 24) };
}
/** Millisecond delta → "<1h" / "Xh" / "Xd", or '' for invalid input. */
function formatAge(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return '<1h';
if (hours < 48) return `${Math.round(hours)}h`;
return `${Math.round(hours / 24)}d`;
const age = ageParts(deltaMs);
if (!age) return '';
return age.unit === '<1h' ? '<1h' : `${age.count}${age.unit}`;
}
/** Millisecond delta → "<1m ago" / "Xm ago" / "Xh ago" (fresh-feed readout). */
@@ -573,12 +585,12 @@ export function createModel({
/** formatAge for a card: "<1h", "24h", "3d" in the UI language ("24 ч"). */
function formatAgeLabel(deltaMs) {
if (!Number.isFinite(deltaMs) || deltaMs < 0) return '';
const hours = deltaMs / 3600000;
if (hours < 1) return t('<1h', { context: 'age' });
if (hours < 48)
return t('{count}h', { context: 'age', count: Math.round(hours) });
return t('{count}d', { context: 'age', count: Math.round(hours / 24) });
const age = ageParts(deltaMs);
if (!age) return '';
if (age.unit === '<1h') return t('<1h', { context: 'age' });
return age.unit === 'h'
? t('{count}h', { context: 'age', count: age.count })
: t('{count}d', { context: 'age', count: age.count });
}
/** Normalized 0..1 confidence → low/nominal/high display bucket. */
+45
View File
@@ -0,0 +1,45 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { getLocale, setLocale } from '../../i18n/index.js';
import { createModel } from './model.js';
const HOUR_MS = 3600000;
test('a fire age that rounds to 48 hours reads in days, as 48 hours does', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
assert.equal(formatAge(47.4 * HOUR_MS), '47h');
assert.equal(formatAge(47.5 * HOUR_MS), '2d');
assert.equal(formatAge(47.6 * HOUR_MS), '2d');
assert.equal(formatAge(48 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.4 * HOUR_MS), '47h');
assert.equal(formatAgeLabel(47.5 * HOUR_MS), '2d');
assert.equal(formatAgeLabel(47.6 * HOUR_MS), formatAgeLabel(48 * HOUR_MS));
assert.equal(formatAgeLabel(48 * HOUR_MS), '2d');
} finally {
setLocale(previousLocale);
}
});
test('both fire age formatters agree on invalid, sub-hour and multi-day ages', () => {
const previousLocale = getLocale();
const { formatAge, formatAgeLabel } = createModel({
services: { anchors: {} },
});
try {
setLocale('en');
for (const format of [formatAge, formatAgeLabel]) {
assert.equal(format(-1), '');
assert.equal(format(Number.NaN), '');
assert.equal(format(0.5 * HOUR_MS), '<1h');
assert.equal(format(1 * HOUR_MS), '1h');
assert.equal(format(72 * HOUR_MS), '3d');
}
} finally {
setLocale(previousLocale);
}
});
+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);
}
});
+41
View File
@@ -0,0 +1,41 @@
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
export function createClockFollow({ flightState, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses, floors and the tracked
* trail belong to the time the clock left.
*/
function resetMotion() {
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState._displayFloorState.clear();
flightState._drReconcileValid = false;
flightState._cachedDRFrame = -1;
flightState._cachedDRPosition = null;
parts.tracking._clearTrail();
flightState._lastCamPoseSig = '';
}
/** Drop every contact: the time has none to show, or the clock went live. */
function clear() {
if (flightState._trackedIcao)
parts.tracking._clearTracking(false, { evicted: true });
resetMotion();
for (const [icao24, billboard] of flightState._billboards) {
flightState._billboardCollection?.remove(billboard);
parts.rendering._releaseModel(icao24);
}
flightState._billboards.clear();
flightState._cullPositions.clear();
flightState._detectionObjects.clear();
flightState.feed._count = 0;
flightState.feed._lastUpdate = null;
}
return { resetMotion, clear };
}
+230
View File
@@ -0,0 +1,230 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FlightRecords } from './records.js';
import { createIngestion } from './ingestion.js';
import { createClockFollow } from './clockFollow.js';
import { displayDelayMs, followsClock, RENDER_DELAY_SEC } from './policy.js';
// Flights follow the world clock only while their source declares a timeline
// (src/time/snapshotTimeline.js); these cover the layer's side of it.
const T = 1_800_000_000_000;
const following = { timeline: { active: () => true } };
const live = { timeline: { active: () => false } };
function records(now = () => T) {
return new FlightRecords({
geoidHeight: () => 0,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
now,
});
}
const view = () => ({
viewerLatDeg: null,
viewerLonDeg: null,
trackedId: null,
floorWarmPoints: [],
});
const observation = (fields = {}) => ({
id: 'abc123',
reference: 'abc123',
longitude: -77,
latitude: 39,
callsign: 'TEST1',
baroAltitudeM: 1000,
onGround: false,
speedMps: 120,
courseDeg: 90,
positionTimeMs: T - 5_000,
...fields,
});
test('contacts are drawn behind the live edge, and at the time following the clock', () => {
assert.equal(displayDelayMs({ timeline: null }), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs({}), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs(live), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs(following), 0);
assert.equal(followsClock({}), false);
assert.equal(followsClock(following), true);
});
test('civil records judge absence and receipt at the layer clock', () => {
let now = T;
const store = records(() => now);
const { meta } = store.receive(observation({ positionTimeMs: null }), view());
assert.equal(meta.observedReceiptMs, T);
assert.equal(meta.newestFixMs, T, 'an undated fix is the clock time');
assert.equal(
store.absence('abc123', { complete: true, tracked: true }),
'stale',
);
assert.equal(
store.absence('abc123', {
complete: true,
tracked: true,
nowMs: T + 11 * 60_000,
}),
'remove',
'a given time judges retention',
);
store.receive(observation(), view());
now = T + 11 * 60_000;
assert.equal(
store.absence('abc123', { complete: true, tracked: true }),
'remove',
'the clock judges retention when no time is given',
);
});
test('a records reset forgets where airframes were and keeps what they are', () => {
const store = records();
const first = store.receive(observation(), view());
first.meta.typeCode = 'B738';
first.meta.registration = 'N123';
first.meta.photo = { src: 'photo.jpg' };
store.absence('abc123', { complete: true });
store.beginSnapshot(T);
store.reset();
assert.equal(store.data.size, 0);
assert.equal(store.missingPolls.size, 0);
assert.equal(store.lastSnapshotMs, null);
const again = store.receive(
observation({ positionTimeMs: T - 600_000, callsign: 'OTHER' }),
view(),
);
assert.equal(again.prevMeta, undefined, 'no motion carries across');
assert.equal(again.groundFlipped, false);
assert.equal(again.meta.typeCode, 'B738');
assert.equal(again.meta.registration, 'N123');
assert.equal(again.meta.photo.src, 'photo.jpg');
assert.equal(again.meta.newestFixMs, T - 600_000, 'an earlier fix applies');
store.forget('abc123');
assert.equal(store.airframes.size, 0);
});
function ingestion(source, { follows = false } = {}) {
const feed = {
_source: source,
_activeUpdateControllers: new Set(),
_trackingRefreshEpoch: 0,
_lastSource: 'Fixture',
_retryAt: 0,
};
const applied = [];
const state = { follows };
const { methods } = createIngestion({
feed,
getQuery: () => ({ latitude: 39 }),
applySnapshot: (snapshot, _viewer, options) => {
applied.push({ snapshot, options });
return { count: 1, ids: new Set() };
},
setSourceLabel: () => {},
applyPendingTrackingRestore: () => {},
followsClock: () => state.follows,
});
return { feed, applied, state, methods };
}
test('civil polls carry no time; a snapshot at a time carries it and replaces', async () => {
const queries = [];
const probe = ingestion({
async getSnapshot(query) {
queries.push(query);
return { records: [], observedAtMs: T - 60_000, freshness: 'current' };
},
});
await probe.methods.update(null);
assert.deepEqual(queries[0], { latitude: 39 });
assert.equal(probe.applied[0].options, undefined);
assert.equal(await probe.methods.loadAt(T - 60_000, { replace: true }), true);
assert.deepEqual(queries[1], { latitude: 39, atMs: T - 60_000 });
assert.deepEqual(probe.applied[1].options, { replace: true });
assert.equal(probe.feed._lastUpdate, T - 60_000);
});
test('following the clock, civil polls stop and a poll already out is dropped', async () => {
let release;
const probe = ingestion({
getSnapshot: () =>
new Promise((resolve) => {
release = resolve;
}),
});
const out = probe.methods.update(null);
probe.state.follows = true;
release({ records: [], observedAtMs: T, freshness: 'current' });
await out;
assert.equal(probe.applied.length, 0);
await probe.methods.update(null);
assert.equal(probe.applied.length, 0, 'no poll while following');
});
test('a failed snapshot at a time reports it without holding the live backoff', async () => {
const probe = ingestion({
async getSnapshot() {
throw Object.assign(new Error('nope'), { retryAfterMs: 60_000 });
},
});
assert.equal(await probe.methods.loadAt(T), false);
assert.equal(probe.feed._retryAt, 0);
assert.equal(probe.feed._lastError, 'Live data unavailable');
});
test('a jump forgets how contacts moved; clearing drops every contact', () => {
const calls = [];
const flightState = {
records: records(),
_positionHistory: new Map([['abc123', []]]),
_displayCourse: new Map([['abc123', 90]]),
_groundSnap: { clear: () => calls.push('ground') },
_displayFloorState: new Map([['abc123', {}]]),
_drReconcileValid: true,
_cachedDRFrame: 7,
_billboards: new Map([['abc123', { id: 'abc123' }]]),
_billboardCollection: { remove: () => calls.push('remove') },
_cullPositions: new Map([['abc123', null]]),
_detectionObjects: new Map([['abc123', {}]]),
_trackedIcao: 'abc123',
feed: { _count: 1, _lastUpdate: T },
};
const parts = {
tracking: {
_clearTrail: () => calls.push('trail'),
_clearTracking: (_skip, { evicted }) => {
calls.push(`untrack:${evicted}`);
flightState._trackedIcao = null;
},
},
rendering: { _releaseModel: (id) => calls.push(`model:${id}`) },
};
const follow = createClockFollow({ flightState, parts });
flightState.records.receive(observation(), view());
follow.resetMotion();
assert.equal(flightState.records.data.size, 0);
assert.equal(flightState._positionHistory.size, 0);
assert.equal(flightState._displayCourse.size, 0);
assert.equal(flightState._displayFloorState.size, 0);
assert.equal(flightState._drReconcileValid, false);
assert.equal(flightState._billboards.size, 1, 'contacts stay until replaced');
follow.clear();
assert.equal(flightState._billboards.size, 0);
assert.equal(flightState._detectionObjects.size, 0);
assert.equal(flightState.feed._count, 0);
assert.equal(flightState.feed._lastUpdate, null);
assert.ok(calls.includes('untrack:true'));
assert.ok(calls.includes('model:abc123'));
});
test('a snapshot at a time the source drops for a newer one sets no error', async () => {
const probe = ingestion({
async getSnapshot() {
throw new DOMException('Superseded', 'AbortError');
},
});
await assert.rejects(probe.methods.loadAt(T), { name: 'AbortError' });
assert.equal(probe.feed._lastError, undefined);
assert.equal(probe.feed._backoff, undefined);
assert.equal(probe.feed._retryAt, 0);
});
+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,
+22 -1
View File
@@ -10,6 +10,9 @@ import { createLifecycle } from './lifecycle.js';
import { createEvidence } from './evidence.js';
import { createTesting } from './testing.js';
import { createQueries } from './queries.js';
import { createClockFollow } from './clockFollow.js';
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
import { worldClock } from '../../time/worldClock.js';
/** Compose one civil-flight layer with application-owned scene services. */
export function createCivilFlightLayer({
source,
@@ -29,6 +32,7 @@ export function createCivilFlightLayer({
parts.evidence = createEvidence(context);
parts.testing = createTesting(context);
parts.queries = createQueries(context);
parts.clockFollow = createClockFollow(context);
const applySnapshot = createFlightSnapshotRenderer({
flightState,
records: flightState.records,
@@ -45,7 +49,11 @@ export function createCivilFlightLayer({
feed: flightState.feed,
getQuery: (viewer) =>
parts.controller._flightQuery(viewer || flightState._viewer),
applySnapshot,
applySnapshot: (snapshot, viewer, options) => {
if (options?.replace) parts.clockFollow.resetMotion();
return applySnapshot(snapshot, viewer, options);
},
followsClock: () => flightState.timeline.active(),
setSourceLabel: (source) => {
layer.source = source;
},
@@ -53,6 +61,19 @@ export function createCivilFlightLayer({
parts.tracking._applyPendingTrackingRestore(),
});
// Contacts follow the world clock while the source declares a timeline.
flightState.timeline = createSnapshotTimeline({
id: 'flights',
clock: worldClock,
source: () => flightState.feed._source,
load: (atMs, { signal, replace }) =>
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
clear: () => parts.clockFollow.clear(),
resumeLive: () => {
layer.update(flightState._viewer).catch(() => {});
},
});
Object.assign(
layer,
parts.queries.methods,
+101 -67
View File
@@ -11,85 +11,119 @@ export function createIngestion({
applySnapshot,
setSourceLabel,
applyPendingTrackingRestore,
followsClock = () => false,
}) {
const methods = {
async update(viewer, { signal = null } = {}) {
const nowMs = Date.now();
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
// Following the world clock, the layer shows the snapshots loadAt
// applies; polling the live feed would put the live edge among them.
if (followsClock()) return;
await acquire(viewer, { signal });
},
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every contact when `replace`. Resolves
* whether it was applied.
* @param {number} atMs
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
* @returns {Promise<boolean>}
*/
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
// Whatever polls or loads for another time no longer applies.
if (replace)
for (const controller of feed._activeUpdateControllers)
controller.abort();
return acquire(viewer, { signal, atMs, replace });
},
};
async function acquire(viewer, { signal = null, atMs, replace = false }) {
const nowMs = Date.now();
const timed = atMs !== undefined;
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'source-unavailable',
ids: new Set(),
source: feed._lastSource,
coverage: feed._lastCoverage,
};
if (!timed && feed._retryAt && nowMs < feed._retryAt) {
feed._backoff = true;
return;
}
const resourceController = new AbortController();
feed._activeUpdateControllers.add(resourceController);
const updateSignal = signal
? AbortSignal.any([signal, resourceController.signal])
: resourceController.signal;
try {
updateSignal.throwIfAborted();
const query = timed ? { ...getQuery(viewer), atMs } : getQuery(viewer);
const snapshot = await feed._source.getSnapshot(query, {
signal: updateSignal,
});
updateSignal.throwIfAborted();
// The clock left the live edge while this poll was out.
if (!timed && followsClock()) return;
feed._lastStatus = snapshot.status ?? 200;
const sourceEpochMs = snapshot.observedAtMs;
const sourceAgeMs = snapshot.ageMs;
const sourceStale = snapshot.stale || snapshot.freshness === 'unknown';
feed._backoff = sourceStale;
feed._retryAt = 0;
// i18n-ignore: English data; the panel shows it through FEED_ERROR_PATTERNS (ui/statusText.js)
feed._lastError = sourceStale
? sourceAgeMs == null
? msg('Source snapshot time unavailable')
: `Source snapshot ${Math.max(2, Math.round(sourceAgeMs / 60_000))} min old`
: null;
feed._lastSource = snapshot.source;
feed._lastCoverage = snapshot.coverage;
setSourceLabel(feed._lastSource);
const accepted = timed
? applySnapshot(snapshot, viewer, { replace })
: applySnapshot(snapshot, viewer);
feed._count = accepted.count;
// Freshness belongs to the source snapshot, not the moment this browser
// received a cached 200 response.
feed._lastUpdate = sourceEpochMs;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'source-unavailable',
ids: new Set(),
status: 'accepted',
ids: accepted.ids,
source: feed._lastSource,
coverage: feed._lastCoverage,
};
if (feed._retryAt && nowMs < feed._retryAt) {
feed._backoff = true;
return;
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
return true;
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Flights update aborted', 'AbortError');
}
const resourceController = new AbortController();
feed._activeUpdateControllers.add(resourceController);
const updateSignal = signal
? AbortSignal.any([signal, resourceController.signal])
: resourceController.signal;
try {
updateSignal.throwIfAborted();
const snapshot = await feed._source.getSnapshot(getQuery(viewer), {
signal: updateSignal,
});
updateSignal.throwIfAborted();
feed._lastStatus = snapshot.status ?? 200;
const sourceEpochMs = snapshot.observedAtMs;
const sourceAgeMs = snapshot.ageMs;
const sourceStale = snapshot.stale || snapshot.freshness === 'unknown';
feed._backoff = sourceStale;
feed._retryAt = 0;
// i18n-ignore: English data; the panel shows it through FEED_ERROR_PATTERNS (ui/statusText.js)
feed._lastError = sourceStale
? sourceAgeMs == null
? msg('Source snapshot time unavailable')
: `Source snapshot ${Math.max(2, Math.round(sourceAgeMs / 60_000))} min old`
: null;
feed._lastSource = snapshot.source;
feed._lastCoverage = snapshot.coverage;
setSourceLabel(feed._lastSource);
const accepted = applySnapshot(snapshot, viewer);
feed._count = accepted.count;
// Freshness belongs to the source snapshot, not the moment this browser
// received a cached 200 response.
feed._lastUpdate = sourceEpochMs;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'accepted',
ids: accepted.ids,
source: feed._lastSource,
coverage: feed._lastCoverage,
};
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Flights update aborted', 'AbortError');
}
console.warn('[Data:Flights] Fetch error:', e);
feed._backoff = true;
console.warn('[Data:Flights] Fetch error:', e);
feed._backoff = true;
// A snapshot at a time is asked again by the clock's follower.
if (!timed)
feed._retryAt =
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
feed._lastStatus = e?.status ?? null;
if (e?.source) {
feed._lastSource = e.source;
setSourceLabel(feed._lastSource);
}
feed._lastError =
e?.name === 'LiveSourceError'
? e.message
: msg('Live data unavailable');
} finally {
feed._activeUpdateControllers.delete(resourceController);
feed._lastStatus = e?.status ?? null;
if (e?.source) {
feed._lastSource = e.source;
setSourceLabel(feed._lastSource);
}
},
};
feed._lastError =
e?.name === 'LiveSourceError'
? e.message
: msg('Live data unavailable');
return false;
} finally {
feed._activeUpdateControllers.delete(resourceController);
}
}
return { methods };
}
+4
View File
@@ -190,6 +190,7 @@ export function createLifecycle({
);
}
restoreSpriteOrderOnEnable('flights', viewer);
flightState.timeline?.start();
},
/**
@@ -198,6 +199,7 @@ export function createLifecycle({
* @param {Cesium.Viewer} viewer
*/
disable(viewer) {
flightState.timeline?.stop();
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._billboardCollection)
@@ -240,6 +242,7 @@ export function createLifecycle({
* @param {Cesium.Viewer} viewer
*/
destroy(viewer) {
flightState.timeline?.stop();
flightState.lifetime.abort();
flightState._enrichActive = 0;
flightState._enrichLastDispatchMs = 0;
@@ -312,6 +315,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;
+119 -26
View File
@@ -5,11 +5,15 @@ import {
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 {
@@ -18,7 +22,6 @@ import {
} from '../../data/modelVisualAnchor.js';
import {
FOCUS_EVIDENCE_DEV,
RENDER_DELAY_SEC,
TRACKED_MODEL_MAX_PX,
TRACKED_MODEL_MIN_PX,
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
@@ -35,8 +38,26 @@ import {
DISPLAY_CORRIDOR_LOOKAHEAD_SEC,
DISPLAY_CORRIDOR_CELL_BUDGET,
DISPLAY_CORRIDOR_FAIR_SHARE,
displayDelayMs,
followsClock,
} 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,
@@ -158,7 +179,7 @@ export function createMotion({
sampledRenderTime ??
Cesium.JulianDate.addSeconds(
julianAt(flightState.now(), flightState._scratchRenderTime),
-RENDER_DELAY_SEC,
-displayDelayMs(flightState) / 1000,
flightState._scratchRenderTime,
);
@@ -232,30 +253,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() - displayDelayMs(flightState) - 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,
};
}
/**
@@ -270,9 +349,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;
@@ -334,7 +416,7 @@ export function createMotion({
if (!history || history.length === 0) return true;
const renderTime = Cesium.JulianDate.addSeconds(
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
-displayDelayMs(flightState) / 1000,
flightState._scratchWarmupTime,
);
return Cesium.JulianDate.lessThan(renderTime, history[0].time);
@@ -418,9 +500,15 @@ export function createMotion({
}
const nowMs = Date.now();
// How far the contact may move between frames goes by the world's time,
// which plays faster than the wall clock when following it at a rate.
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
const info = flightState.records.data.get(icao24);
if (sameTrack) {
const dtSec = Math.max(0.001, (nowMs - flightState._drPrevMs) / 1000);
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
const speed = (info && info.velocity) || 0;
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
const plausible = speed * dtSec * 4 + 25;
@@ -468,6 +556,7 @@ export function createMotion({
Cesium.Cartesian3.clone(raw, flightState._drPrevRaw);
Cesium.Cartesian3.clone(display, flightState._drPrevDisplay);
flightState._drPrevMs = nowMs;
flightState._drPrevWorldMs = worldMs;
flightState._drReconcileValid = true;
flightState._cachedDRPosition = display;
const focusSizePx = _trackedFocusSizePx(
@@ -865,12 +954,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(),
@@ -1112,6 +1204,7 @@ export function createMotion({
return {
_refloorStaleGroundedContacts,
_deadReckon,
_signalLost,
_extrapolateFix,
_isTrackWarmingUp,
_trackedFocusSizePx,
+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();
});
+18 -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):
@@ -147,6 +147,15 @@ export const TRAIL_MAX_POINTS = 400;
export const RENDER_DELAY_SEC = 30;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (state) => state.timeline?.active() === true;
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
* following the clock, whose snapshots are loaded ahead of the time. */
export const displayDelayMs = (state) =>
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
/** @constant {number} Polls an aircraft may miss before removal (transient OpenSky dropouts). */
// --- Landed-plane fast cull (owner field report 2026-07-02: "phantom" planes
@@ -254,6 +263,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 +480,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;
+16 -3
View File
@@ -14,6 +14,7 @@ import {
LANDED_SPEED_MAX_MPS,
FOCUS_EVIDENCE_DEV,
FLEET_DR_INTERVAL_MS,
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
@@ -24,7 +25,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 +210,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 +883,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 +915,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,
};
},
@@ -976,6 +987,8 @@ export function createQueries({
retryInSec,
source: flightState.feed._lastSource,
coverage: flightState.feed._lastCoverage,
// Following the world clock, the snapshot's age is told from its time.
...(followsClock(flightState) && { atMs: flightState.now() }),
};
},
};
+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;
+125 -17
View File
@@ -11,22 +11,67 @@ 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. */
export class FlightRecords {
constructor({ geoidHeight, cachedGroundFloor, floorAltitudeM }) {
constructor({
geoidHeight,
cachedGroundFloor,
floorAltitudeM,
now = () => Date.now(),
}) {
this.services = {
geoidHeight,
cachedGroundFloor,
floorAltitudeM,
};
/** The time records are judged at: the layer's clock. */
this.now = now;
this.data = new Map();
// Facts about an airframe, not a moment, kept across a reset.
this.airframes = 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 },
@@ -54,6 +99,9 @@ export class FlightRecords {
// regressing to the ICAO hex / a 0° (north) heading. Bounded by the
// MISSING_POLL_LIMIT eviction below, which deletes the whole entry.
const prevMeta = this.data.get(icao24);
// The airframe's facts: this record's, or those kept across a reset.
const airframe = prevMeta ?? this.airframes.get(icao24);
this.airframes.delete(icao24);
// Grounded planes with no baro reading sit at 0 m, not the 10 km
// airborne default (a parked plane must never float).
// NOTE (height-datum fix): `alt` stays the AVIATION field — the sticky
@@ -158,6 +206,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 +252,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(airframe?.routeCallsign) &&
airframe.routeCallsign === nextCallsign.toUpperCase();
const fixEpochMs =
Number.isFinite(observation.positionTimeMs) &&
observation.positionTimeMs > 0
? observation.positionTimeMs
: this.now();
const meta = {
sourceReference: observation.reference,
observedReceiptMs: Date.now(),
callsign: stickyText(callsign, prevMeta?.callsign),
observedReceiptMs: this.now(),
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 +275,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.
@@ -218,7 +285,7 @@ export class FlightRecords {
category: cat,
// An adsbdb-enriched type code outranks the coarse OpenSky category.
klass: classifyAircraft({
typeCode: prevMeta?.typeCode ?? null,
typeCode: airframe?.typeCode ?? null,
category: cat,
}),
turnRateDps: prevMeta?.turnRateDps || 0,
@@ -253,11 +320,14 @@ export class FlightRecords {
null,
),
// adsbdb enrichment — written by the enrichment callbacks, carried across polls:
typeCode: prevMeta?.typeCode ?? null,
typeName: prevMeta?.typeName ?? null,
registration: prevMeta?.registration ?? null,
airline: prevMeta?.airline ?? null,
route: prevMeta?.route ?? null,
typeCode: airframe?.typeCode ?? null,
typeName: airframe?.typeName ?? null,
registration: airframe?.registration ?? null,
airline: routeHeld ? (airframe.airline ?? null) : null,
route: routeHeld ? (airframe.route ?? null) : null,
routeCallsign: routeHeld ? airframe.routeCallsign : null,
// Planespotters photo of the tracked airframe (Core asks it directly).
photo: airframe?.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,24 +337,36 @@ 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, nowMs = this.now() },
) {
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 (nowMs - 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.
if (
(!complete || (retainIds?.has(id) && !likelyLanded)) &&
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
nowMs - (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);
@@ -294,9 +376,35 @@ export class FlightRecords {
return 'remove';
}
/**
* Forget every observation, as when the world clock jumps to another time:
* what an airframe is (its type, registration, route and photo) is kept for
* when it is seen again; where it was and when is not.
*/
reset() {
for (const [id, meta] of this.data) {
this.airframes.set(id, {
typeCode: meta.typeCode,
typeName: meta.typeName,
registration: meta.registration,
airline: meta.airline,
route: meta.route,
routeCallsign: meta.routeCallsign,
photo: meta.photo,
});
}
this.data.clear();
this.missingPolls.clear();
this.fixRepeated.clear();
this.lastSnapshotMs = null;
this.snapshotAdvanced = true;
}
forget(id) {
this.data.delete(id);
this.airframes.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 -3
View File
@@ -33,12 +33,13 @@ import {
TRACKED_MODEL_MIN_PX,
TRACKED_MODEL_MAX_PX,
FLEET_DR_INTERVAL_MS,
RENDER_DELAY_SEC,
COURSE_SLEW_DT_MAX_SEC,
ROTATION_REFRESH_MS,
COURSE_MAX_DPS,
HIDDEN_CONTACT_DR_TICKS,
hiddenContactDrPhase,
STALE_ALPHA,
displayDelayMs,
} from './policy.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js';
@@ -680,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 &&
@@ -823,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,
@@ -849,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 ||
@@ -873,7 +895,7 @@ export function createRendering({
// Every contact in this pass shares the same delayed display instant.
const renderTime = Cesium.JulianDate.addSeconds(
julianAt(flightState.now(), flightState._scratchFleetRenderTime),
-RENDER_DELAY_SEC,
-displayDelayMs(flightState) / 1000,
flightState._scratchFleetRenderTime,
);
@@ -1081,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,
+56 -14
View File
@@ -3,10 +3,12 @@ import { cyberSonarBaseAlpha } from '../../cyberSonar.js';
import {
turnRateFromFixHistory,
liftRepeatedGroundFix,
staleHoldsForFix,
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { followsClock } from './policy.js';
/** Apply reconciled aircraft records to Cesium resources and follow state. */
export function createFlightSnapshotRenderer({
@@ -22,9 +24,13 @@ export function createFlightSnapshotRenderer({
queries,
}) {
const { refreshMilitaryRegistryIfStale, isMilitaryIcao } = militaryRegistry;
const { warmGroundFloor } = groundFloor;
const { warmGroundFloor, cachedGroundFloor } = groundFloor;
const { sampleMeshFloorCells } = meshFloor;
return function applySnapshot(snapshot, viewer) {
/**
* `replace`: the snapshot is the world at another time (the world clock
* jumped), so it stands in for every contact: one it lacks is gone at once.
*/
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
const currentIcaos = new Set();
const acceptedSnapshotIcaos = new Set();
// Field-test round 3 (2026-07-06, Austin fleet-underground): viewer
@@ -39,6 +45,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 +119,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 +135,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 +146,31 @@ 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(),
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.velocity,
track: meta.true_track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
if (isTracked) tracking._appendTrailFix(synthetic.position.clone());
}
}
}
@@ -230,6 +253,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);
}
}
@@ -241,11 +271,15 @@ export function createFlightSnapshotRenderer({
// feed gap, and the full grace left phantom planes parked at airports.
for (const [icao24, bb] of flightState._billboards) {
if (currentIcaos.has(icao24)) continue;
const absence = records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
});
const absence = replace
? 'remove'
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
if (absence === 'retain') continue;
if (absence === 'stale') {
if (icao24 === flightState._trackedIcao && flightState._trackedEntity) {
@@ -279,6 +313,14 @@ export function createFlightSnapshotRenderer({
flightState._displayFloorState.delete(icao24);
}
// The tracked contact at the new time: its trail starts there.
if (
replace &&
flightState._trackedIcao &&
currentIcaos.has(flightState._trackedIcao)
)
tracking._startTrail(flightState._trackedIcao);
// Fresh courses arrived — force a rotation pass on the next fleet tick
flightState._lastCamPoseSig = '';
@@ -300,8 +342,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`,
);
});
+36 -2
View File
@@ -11,10 +11,14 @@ export function createFlightState({ source, services }) {
flightState.records = new FlightRecords({
...services.geoid,
...services.groundFloor,
now: () => flightState.now(),
});
flightState._cullPositions = new Map();
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('flights');
/** Follows the world clock while the source declares a timeline (set by the
* layer); see followsClock and displayDelayMs in policy.js. */
flightState.timeline = null;
/** 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
@@ -195,9 +199,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 */
@@ -342,6 +369,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). */
@@ -358,6 +389,9 @@ export function createFlightState({ source, services }) {
flightState._drPrevMs = 0;
/** World time of that frame: the wall clock live, the cursor following the clock. */
flightState._drPrevWorldMs = 0;
flightState._drReconcileValid = false;
/** @type {string|null} icao the reconciliation state currently belongs to */
+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,
};
}
+284 -92
View File
@@ -1,5 +1,4 @@
import * as Cesium from 'cesium';
import { julianAt } from '../../time/julian.js';
import { formatNumber, t } from '../../i18n/index.js';
import { unitLabel } from '../../ui/unitLabels.js';
import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js';
@@ -21,12 +20,32 @@ import {
TRACKED_MODEL_MAX_LOAD_FAILS,
TRACKED_MODEL_RETRY_BACKOFF_MS,
TRAIL_MAX_POINTS,
RENDER_DELAY_SEC,
DR_CORRECTION_MS,
TRAIL_COLOR,
CYAN_TRANSPARENT,
STALE_ALPHA,
displayDelayMs,
followsClock,
} 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,
@@ -333,18 +352,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() - displayDelayMs(flightState),
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() - displayDelayMs(flightState);
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
@@ -354,17 +436,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() - displayDelayMs(flightState),
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
);
}
@@ -377,21 +475,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(
julianAt(flightState.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, {
@@ -412,14 +513,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 [];
@@ -427,12 +527,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
@@ -441,7 +548,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(),
@@ -481,15 +588,16 @@ export function createTracking({
async function _backfillTrail(icao24, token, oldestFixEpochSec) {
let path = null;
// Following the world clock, the track ends at the world's time.
const atMs = followsClock(flightState) ? flightState.now() : undefined;
try {
const signal = AbortSignal.any([
flightState.lifetime.signal,
AbortSignal.timeout(8000),
]);
const track = await flightState.feed._source.getTrack?.(
flightState.records.data.get(icao24)?.sourceReference ?? icao24,
{
signal: AbortSignal.any([
flightState.lifetime.signal,
AbortSignal.timeout(8000),
]),
},
atMs === undefined ? { signal } : { signal, atMs },
);
path = track?.records ?? null;
} catch {
@@ -519,8 +627,15 @@ export function createTracking({
} = waypoint;
const time = observedAtMs / 1000;
if (!Number.isFinite(lat) || !Number.isFinite(lon)) continue;
if (atMs !== undefined && !(observedAtMs <= atMs)) 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;
@@ -543,27 +658,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();
}
@@ -573,7 +691,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 &&
@@ -737,14 +857,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);
@@ -765,10 +961,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.
@@ -967,15 +1160,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,
@@ -1060,6 +1247,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.
@@ -1256,6 +1444,7 @@ export function createTracking({
_trackedModelRegimeActive,
_syncTracked2dRotation,
_appendTrailFix,
_trailTick,
_refreshTrailDisplay,
_startTrail,
_backfillTrail,
@@ -1266,6 +1455,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();
}
});
+40
View File
@@ -0,0 +1,40 @@
/**
* What the layer drops when the world clock moves it to another time (its
* source declares a timeline; see src/time/snapshotTimeline.js).
*/
export function createClockFollow({ flightState, parts }) {
/**
* Forget how every contact moved, before the snapshot at another time takes
* the place of every contact: their fixes, courses and the tracked trail
* belong to the time the clock left.
*/
function resetMotion() {
flightState.records.reset();
flightState._positionHistory.clear();
flightState._displayCourse.clear();
flightState._groundSnap.clear();
flightState._drReconcileValid = false;
flightState._cachedDRFrame = -1;
flightState._cachedDRPosition = null;
parts.tracking._clearTrail();
flightState._lastCamPoseSig = '';
}
/** Drop every contact: the time has none to show, or the clock went live. */
function clear() {
if (flightState._trackedIcao)
parts.tracking._clearTracking(false, { evicted: true });
resetMotion();
for (const [icao24, billboard] of flightState._billboards) {
flightState._billboardCollection?.remove(billboard);
parts.rendering._releaseModel(icao24);
}
flightState._billboards.clear();
flightState._cullPositions.clear();
flightState._detectionObjects.clear();
flightState.feed._count = 0;
flightState.feed._lastUpdate = null;
}
return { resetMotion, clear };
}
+88
View File
@@ -0,0 +1,88 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { MilitaryFlightRecords } from './records.js';
import { createIngestion, createMilitaryFeed } from './ingestion.js';
import { displayDelayMs, RENDER_DELAY_SEC } from './policy.js';
// Military aircraft follow the world clock only while their source declares
// a timeline (src/time/snapshotTimeline.js); these cover the layer's side.
const T = 1_800_000_000_000;
test('military contacts are drawn behind the live edge, and at the time following the clock', () => {
assert.equal(displayDelayMs({ timeline: null }), RENDER_DELAY_SEC * 1000);
assert.equal(displayDelayMs({ timeline: { active: () => false } }), 15_000);
assert.equal(displayDelayMs({ timeline: { active: () => true } }), 0);
});
test('military records judge absence at the layer clock and reset at a jump', () => {
let now = T;
const store = new MilitaryFlightRecords({
geoidHeight: () => 0,
cachedGroundFloor: () => null,
floorAltitudeM: (altitude) => altitude,
now: () => now,
});
const { meta } = store.receive(
{
id: 'ae0001',
reference: 'ae0001',
latitude: 39,
longitude: -77,
baroAltitudeM: 3000,
onGround: false,
positionTimeMs: T - 1_000,
},
{ observedAtMs: T, floorWarmPoints: [] },
);
assert.equal(meta.observedReceiptMs, T);
assert.equal(
store.absence('ae0001', { complete: true, tracked: true }),
'stale',
);
now = T + 11 * 60_000;
assert.equal(
store.absence('ae0001', { complete: true, tracked: true }),
'remove',
);
store.receive(
{ id: 'ae0001', latitude: 39, longitude: -77, positionTimeMs: T },
{ observedAtMs: T, floorWarmPoints: [] },
);
store.absence('ae0001', { complete: true });
store.reset();
assert.equal(store.data.size, 0);
assert.equal(store.missingPolls.size, 0);
assert.equal(store.lastSnapshotMs, null);
});
test('military polls carry no time; a snapshot at a time carries it, and polls stop following', async () => {
const queries = [];
const applied = [];
let follows = false;
const feed = createMilitaryFeed({
async getSnapshot(query) {
queries.push(query);
return { records: [], observedAtMs: T, freshness: 'current' };
},
});
const { methods } = createIngestion({
feed,
applySnapshot: (_snapshot, _viewer, options) => {
applied.push(options);
return { count: 0, ids: new Set() };
},
setSourceLabel: () => {},
applyPendingTrackingRestore: () => {},
followsClock: () => follows,
});
await methods.update(null);
assert.deepEqual(queries, [{}]);
assert.deepEqual(applied, [undefined]);
follows = true;
await methods.update(null);
assert.equal(queries.length, 1, 'no poll while following');
assert.equal(await methods.loadAt(T, { replace: true }), true);
assert.deepEqual(queries[1], { atMs: T });
assert.deepEqual(applied[1], { replace: true });
});
+22 -1
View File
@@ -8,6 +8,9 @@ import { createIngestion } from './ingestion.js';
import { createLifecycle } from './lifecycle.js';
import { createTesting } from './testing.js';
import { createQueries } from './queries.js';
import { createClockFollow } from './clockFollow.js';
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
import { worldClock } from '../../time/worldClock.js';
/** Compose one military-flight layer with application-owned scene services. */
export function createMilitaryFlightLayer({
source,
@@ -25,6 +28,7 @@ export function createMilitaryFlightLayer({
parts.lifecycle = createLifecycle(context);
parts.testing = createTesting(context);
parts.queries = createQueries(context);
parts.clockFollow = createClockFollow(context);
const applySnapshot = createMilitarySnapshotRenderer({
flightState,
records: flightState.records,
@@ -38,7 +42,11 @@ export function createMilitaryFlightLayer({
});
parts.ingestion = createIngestion({
feed: flightState.feed,
applySnapshot,
applySnapshot: (snapshot, viewer, options) => {
if (options?.replace) parts.clockFollow.resetMotion();
return applySnapshot(snapshot, viewer, options);
},
followsClock: () => flightState.timeline.active(),
setSourceLabel: (source) => {
layer.source = source;
},
@@ -46,6 +54,19 @@ export function createMilitaryFlightLayer({
parts.tracking._applyPendingTrackingRestore(),
});
// Contacts follow the world clock while the source declares a timeline.
flightState.timeline = createSnapshotTimeline({
id: 'military',
clock: worldClock,
source: () => flightState.feed._source,
load: (atMs, { signal, replace }) =>
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
clear: () => parts.clockFollow.clear(),
resumeLive: () => {
layer.update(flightState._viewer).catch(() => {});
},
});
Object.assign(
layer,
parts.queries.methods,
+97 -65
View File
@@ -10,78 +10,110 @@ export function createIngestion({
applySnapshot,
setSourceLabel,
applyPendingTrackingRestore,
followsClock = () => false,
}) {
const methods = {
async update(viewer, { signal = null } = {}) {
const nowMs = Date.now();
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'source-unavailable',
ids: new Set(),
source: feed._lastSource,
};
if (feed._retryAt && nowMs < feed._retryAt) {
feed._backoff = true;
return;
}
// Following the world clock, the layer shows the snapshots loadAt
// applies; polling the live feed would put the live edge among them.
if (followsClock()) return;
await acquire(viewer, { signal });
},
const resourceController = new AbortController();
feed._activeUpdateControllers.add(resourceController);
const updateSignal = signal
? AbortSignal.any([signal, resourceController.signal])
: resourceController.signal;
try {
updateSignal.throwIfAborted();
const snapshot = await feed._source.getSnapshot(
{},
{ signal: updateSignal },
);
updateSignal.throwIfAborted();
feed._lastStatus = snapshot.status ?? 200;
feed._lastSource = snapshot.source;
setSourceLabel(feed._lastSource);
feed._backoff = snapshot.stale || snapshot.freshness === 'unknown';
feed._retryAt = 0;
feed._lastError =
snapshot.reason ||
(snapshot.freshness === 'unknown'
? msg('Source snapshot time unavailable')
: null);
const accepted = applySnapshot(snapshot, viewer);
feed._count = accepted.count;
feed._lastUpdate = snapshot.observedAtMs;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'accepted',
ids: accepted.ids,
source: feed._lastSource,
};
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Military update aborted', 'AbortError');
}
console.warn('[Data:Military] Fetch error:', e);
feed._backoff = true;
feed._retryAt =
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
feed._lastStatus = e?.status ?? null;
if (e?.source) {
feed._lastSource = e.source;
setSourceLabel(feed._lastSource);
}
feed._lastError =
e?.name === 'LiveSourceError'
? e.message
: msg('Live data unavailable');
} finally {
feed._activeUpdateControllers.delete(resourceController);
}
/**
* Apply the source's snapshot at world time `atMs` (its timeline says it
* can answer one), in place of every contact when `replace`. Resolves
* whether it was applied.
* @param {number} atMs
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
* @returns {Promise<boolean>}
*/
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
// Whatever polls or loads for another time no longer applies.
if (replace)
for (const controller of feed._activeUpdateControllers)
controller.abort();
return acquire(viewer, { signal, atMs, replace });
},
};
async function acquire(viewer, { signal = null, atMs, replace = false }) {
const nowMs = Date.now();
const timed = atMs !== undefined;
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'source-unavailable',
ids: new Set(),
source: feed._lastSource,
};
if (!timed && feed._retryAt && nowMs < feed._retryAt) {
feed._backoff = true;
return;
}
const resourceController = new AbortController();
feed._activeUpdateControllers.add(resourceController);
const updateSignal = signal
? AbortSignal.any([signal, resourceController.signal])
: resourceController.signal;
try {
updateSignal.throwIfAborted();
const snapshot = await feed._source.getSnapshot(timed ? { atMs } : {}, {
signal: updateSignal,
});
updateSignal.throwIfAborted();
// The clock left the live edge while this poll was out.
if (!timed && followsClock()) return;
feed._lastStatus = snapshot.status ?? 200;
feed._lastSource = snapshot.source;
setSourceLabel(feed._lastSource);
feed._backoff = snapshot.stale || snapshot.freshness === 'unknown';
feed._retryAt = 0;
feed._lastError =
snapshot.reason ||
(snapshot.freshness === 'unknown'
? msg('Source snapshot time unavailable')
: null);
const accepted = timed
? applySnapshot(snapshot, viewer, { replace })
: applySnapshot(snapshot, viewer);
feed._count = accepted.count;
feed._lastUpdate = snapshot.observedAtMs;
feed._lastTrackingRefreshOutcome = {
epoch: trackingRefreshEpoch,
status: 'accepted',
ids: accepted.ids,
source: feed._lastSource,
};
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
applyPendingTrackingRestore();
return true;
} catch (e) {
if (updateSignal.aborted || e?.name === 'AbortError') {
throw new DOMException('Military update aborted', 'AbortError');
}
console.warn('[Data:Military] Fetch error:', e);
feed._backoff = true;
// A snapshot at a time is asked again by the clock's follower.
if (!timed)
feed._retryAt =
Date.now() + (e?.retryAfterMs ?? ERROR_BACKOFF_INTERVAL);
feed._lastStatus = e?.status ?? null;
if (e?.source) {
feed._lastSource = e.source;
setSourceLabel(feed._lastSource);
}
feed._lastError =
e?.name === 'LiveSourceError'
? e.message
: msg('Live data unavailable');
return false;
} finally {
feed._activeUpdateControllers.delete(resourceController);
}
}
return { methods };
}
+3
View File
@@ -167,6 +167,7 @@ export function createLifecycle({
);
}
restoreSpriteOrder(viewer);
flightState.timeline?.start();
},
/**
@@ -175,6 +176,7 @@ export function createLifecycle({
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
*/
disable(viewer) {
flightState.timeline?.stop();
parts.controller._abortActiveUpdates();
parts.tracking._cancelPendingTrackingRestore();
if (flightState._billboardCollection)
@@ -219,6 +221,7 @@ export function createLifecycle({
* @param {Cesium.Viewer} viewer - The Cesium viewer instance
*/
destroy(viewer) {
flightState.timeline?.stop();
flightState.lifetime.abort();
parts.controller._abortActiveUpdates();
releaseContinuousRender('military'); // direct-destroy path (perf wave 2 fix)
+95 -16
View File
@@ -5,10 +5,14 @@ import {
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 {
@@ -16,7 +20,8 @@ import {
modelAnchorWorld,
} from '../../data/modelVisualAnchor.js';
import {
RENDER_DELAY_SEC,
displayDelayMs,
followsClock,
TRACKED_MODEL_MAX_PX,
TRACKED_MODEL_MIN_PX,
BILLBOARD_SCALE,
@@ -69,7 +74,7 @@ export function createMotion({
// two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale).
const renderTime = Cesium.JulianDate.addSeconds(
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
-displayDelayMs(flightState) / 1000,
flightState._scratchRenderTime,
);
@@ -141,23 +146,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() - displayDelayMs(flightState) - 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,
};
}
/**
@@ -172,9 +240,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;
@@ -215,7 +286,7 @@ export function createMotion({
if (!history || history.length === 0) return true;
const renderTime = Cesium.JulianDate.addSeconds(
julianAt(flightState.now()),
-RENDER_DELAY_SEC,
-displayDelayMs(flightState) / 1000,
flightState._scratchWarmupTime,
);
return Cesium.JulianDate.lessThan(renderTime, history[0].time);
@@ -300,9 +371,15 @@ export function createMotion({
}
const nowMs = Date.now();
// How far the contact may move between frames goes by the world's time,
// which plays faster than the wall clock when following it at a rate.
const worldMs = followsClock(flightState) ? flightState.now() : nowMs;
const info = flightState.records.data.get(icao24);
if (sameTrack) {
const dtSec = Math.max(0.001, (nowMs - flightState._drPrevMs) / 1000);
const dtSec = Math.max(
0.001,
(worldMs - flightState._drPrevWorldMs) / 1000,
);
const speed = (info && info.speedMps) || 0;
// Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base.
const plausible = speed * dtSec * 4 + 25;
@@ -333,6 +410,7 @@ export function createMotion({
Cesium.Cartesian3.clone(raw, flightState._drPrevRaw);
Cesium.Cartesian3.clone(display, flightState._drPrevDisplay);
flightState._drPrevMs = nowMs;
flightState._drPrevWorldMs = worldMs;
flightState._drReconcileValid = true;
flightState._cachedDRPosition = display;
const focusSizePx = _trackedFocusSizePx(
@@ -514,6 +592,7 @@ export function createMotion({
}
return {
_deadReckon,
_signalLost,
_extrapolateFix,
_isTrackWarmingUp,
_trackedFocusSizePx,
+13 -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
@@ -186,6 +186,15 @@ export const TRAIL_MAX_POINTS = 400;
export const RENDER_DELAY_SEC = 15;
/** Whether the layer shows the world clock's time instead of the live feed:
* its source declares a timeline and the clock is away from live. */
export const followsClock = (state) => state.timeline?.active() === true;
/** How far behind the time contacts are drawn: RENDER_DELAY_SEC live, none
* following the clock, whose snapshots are loaded ahead of the time. */
export const displayDelayMs = (state) =>
followsClock(state) ? 0 : RENDER_DELAY_SEC * 1000;
/** @constant {number} Polls an aircraft may miss before removal (transient adsb.lol dropouts). */
// --- Landed-plane fast cull (mirror of flights.js; owner field report
@@ -271,3 +280,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;
+7 -1
View File
@@ -9,7 +9,11 @@ import {
contactMatchWins,
CONTACT_MATCH_TIER,
} from '../../data/contactMatch.js';
import { LANDED_ALT_MAX_FT, LANDED_SPEED_MAX_MPS } from './policy.js';
import {
LANDED_ALT_MAX_FT,
LANDED_SPEED_MAX_MPS,
followsClock,
} from './policy.js';
import { emergencyBroadcastPhrase } from '../../data/aircraftEmergency.js';
export function createQueries({
@@ -834,6 +838,8 @@ export function createQueries({
retryInSec,
source: flightState.feed._lastSource,
fallback: false,
// Following the world clock, the snapshot's age is told from its time.
...(followsClock(flightState) && { atMs: flightState.now() }),
};
},
};
+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;
+82 -6
View File
@@ -6,17 +6,60 @@ 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. */
export class MilitaryFlightRecords {
constructor({ geoidHeight, cachedGroundFloor, floorAltitudeM }) {
constructor({
geoidHeight,
cachedGroundFloor,
floorAltitudeM,
now = () => Date.now(),
}) {
this.services = { geoidHeight, cachedGroundFloor, floorAltitudeM };
/** The time records are judged at: the layer's clock. */
this.now = now;
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 +131,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 +174,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(),
observedReceiptMs: this.now(),
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
callsign: stickyText(callsign, prevMeta?.callsign),
type: stickyType,
// Type outranks category automatically inside classifyAircraft.
@@ -146,6 +195,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,19 +234,36 @@ export class MilitaryFlightRecords {
prevMeta,
meta,
groundFlipped,
fixEpochMs: aircraft.positionTimeMs ?? observedAtMs,
fixEpochMs,
};
}
absence(id, { complete, retainIds, likelyLanded }) {
absence(
id,
{ complete, retainIds, likelyLanded, tracked = false, nowMs = this.now() },
) {
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 (nowMs - 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.
if (
(!complete || (retainIds?.has(id) && !likelyLanded)) &&
Date.now() - (this.data.get(id)?.observedReceiptMs ?? 0) < 300000
nowMs - (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);
@@ -205,9 +272,18 @@ export class MilitaryFlightRecords {
this.missingPolls.delete(id);
return 'remove';
}
/** Forget every observation, as when the world clock jumps to another time. */
reset() {
this.data.clear();
this.missingPolls.clear();
this.fixRepeated.clear();
this.lastSnapshotMs = null;
this.snapshotAdvanced = true;
}
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,
+52 -13
View File
@@ -4,11 +4,17 @@ import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
import {
turnRateFromFixHistory,
liftRepeatedGroundFix,
staleHoldsForFix,
synthesizeForwardKinematicsFix,
} from '../../data/motionModel.js';
import { aircraftIcon } from '../../data/aircraftIcons.js';
import { POSITION_HISTORY_LIMIT } from './recordPolicy.js';
import { BILLBOARD_SCALE, GROUND_SCALE, TRACKED_ICON_COLOR } from './policy.js';
import {
BILLBOARD_SCALE,
GROUND_SCALE,
TRACKED_ICON_COLOR,
followsClock,
} from './policy.js';
/** Apply military record changes to Cesium resources and existing follow operations. */
export function createMilitarySnapshotRenderer({
@@ -26,9 +32,14 @@ export function createMilitarySnapshotRenderer({
groundFloor;
const { sampleMeshFloorCells } = meshFloor;
const { registerMilitaryIcaos } = militaryRegistry;
return function applySnapshot(snapshot, viewer) {
/**
* `replace`: the snapshot is the world at another time (the world clock
* jumped), so it stands in for every contact: one it lacks is gone at once.
*/
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
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 +94,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 +109,39 @@ 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(),
// Following the clock, the snapshot's time is the moment it moves on from.
epochMs: followsClock(flightState)
? snapshot.observedAtMs
: Date.now(),
velocity: meta.speedMps,
track: meta.track,
turnRateDps: meta.turnRateDps,
cachedGroundFloor,
});
if (synthetic) {
history.push(synthetic);
if (history.length > POSITION_HISTORY_LIMIT) history.shift();
meta.turnRateDps = turnRateFromFixHistory(history);
if (isTracked) tracking._appendTrailFix(synthetic.position.clone());
}
}
}
@@ -228,8 +255,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 =
@@ -257,11 +284,15 @@ export function createMilitarySnapshotRenderer({
// feed gap, and the full grace left phantom planes parked at airports.
for (const [icao24, bb] of flightState._billboards) {
if (currentIcaos.has(icao24)) continue;
const absence = records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
});
const absence = replace
? 'remove'
: records.absence(icao24, {
complete: snapshot.complete,
retainIds: snapshot.retainIds,
likelyLanded: queries._likelyLanded(icao24),
tracked: icao24 === flightState._trackedIcao,
nowMs: flightState.now?.(),
});
if (absence === 'retain') continue;
if (absence === 'stale') {
if (icao24 === flightState._trackedIcao && flightState._trackedEntity) {
@@ -294,6 +325,14 @@ export function createMilitarySnapshotRenderer({
flightState._groundSnap.forget(icao24);
}
// The tracked contact at the new time: its trail starts there.
if (
replace &&
flightState._trackedIcao &&
currentIcaos.has(flightState._trackedIcao)
)
tracking._startTrail(flightState._trackedIcao);
// Fresh courses arrived — force a rotation pass on the next fleet tick
flightState._lastCamPoseSig = '';
+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(), []);
});
+32 -2
View File
@@ -10,10 +10,14 @@ export function createFlightState({ source, services }) {
flightState.records = new MilitaryFlightRecords({
...services.geoid,
...services.groundFloor,
now: () => flightState.now(),
});
flightState._cullPositions = new Map();
/** The time contacts are drawn behind by the render delay, in epoch ms. */
flightState.now = worldTimeFor('military');
/** Follows the world clock while the source declares a timeline (set by the
* layer); see followsClock and displayDelayMs in policy.js. */
flightState.timeline = null;
/** 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
@@ -178,9 +182,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 */
@@ -298,6 +325,9 @@ export function createFlightState({ source, services }) {
flightState._drPrevMs = 0;
/** World time of that frame: the wall clock live, the cursor following the clock. */
flightState._drPrevWorldMs = 0;
flightState._drReconcileValid = false;
/** @type {string|null} icao the reconciliation state currently belongs to */
+296 -111
View File
@@ -1,6 +1,6 @@
import * as Cesium from 'cesium';
import { julianAt } from '../../time/julian.js';
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';
@@ -19,14 +19,34 @@ import {
TRACKED_MODEL_MAX_LOAD_FAILS,
TRACKED_MODEL_RETRY_BACKOFF_MS,
TRAIL_MAX_POINTS,
RENDER_DELAY_SEC,
DR_CORRECTION_MS,
displayDelayMs,
followsClock,
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,
@@ -206,24 +226,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) ||
@@ -456,33 +550,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() - displayDelayMs(flightState),
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() - displayDelayMs(flightState);
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() - displayDelayMs(flightState),
),
parts.motion._trackedModelCenterWorld(),
parts.motion._trackedModelEnvelopeM(),
);
}
@@ -495,25 +668,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(
julianAt(flightState.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, {
@@ -534,14 +709,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 [];
@@ -549,12 +723,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.
@@ -595,10 +777,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.
@@ -608,15 +790,16 @@ export function createTracking({
async function _backfillTrail(icao24, token, oldestFixEpochSec) {
let trace = null;
// Following the world clock, the track ends at the world's time.
const atMs = followsClock(flightState) ? flightState.now() : undefined;
try {
const signal = AbortSignal.any([
flightState.lifetime.signal,
AbortSignal.timeout(8000),
]);
const track = await flightState.feed._source.getTrack?.(
flightState.records.data.get(icao24)?.sourceReference ?? icao24,
{
signal: AbortSignal.any([
flightState.lifetime.signal,
AbortSignal.timeout(8000),
]),
},
atMs === undefined ? { signal } : { signal, atMs },
);
trace = track?.records ?? null;
} catch {
@@ -644,7 +827,14 @@ 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 });
if (atMs !== undefined && !(point.observedAtMs <= atMs)) continue;
parsed.push({
lat,
lon,
baroAltitudeM: point.baroAltitudeM,
onGround: point.onGround === true,
timeMs: point.observedAtMs,
});
}
if (!parsed.length) return;
@@ -667,39 +857,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();
}
@@ -709,7 +894,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 &&
@@ -926,15 +1113,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,
@@ -1157,6 +1338,9 @@ export function createTracking({
_setCockpitContactMode,
_applyCockpitState,
_buildTrackedLabel,
_trackedStaleCue,
_trackedIconColor,
_staleCueTick,
_updateTrackedLabelModel,
_syncTrackedBillboardImage,
_refreshTr3bContact,
@@ -1168,6 +1352,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;
}
+123
View File
@@ -0,0 +1,123 @@
import { formatDate, formatNumber, msg, t } from '../../i18n/index.js';
import { EMODNET_PAGE_URL } from './records.js';
export const ERA_LABELS = Object.freeze({
'before-1900': msg('Before 1900'),
'1900-1945': msg('1900–1945'),
'after-1945': msg('After 1945'),
undated: msg('Date unknown'),
});
export const ERA_COLORS = Object.freeze({
'before-1900': '#c79a5b',
'1900-1945': '#ff6b5e',
'after-1945': '#4fc3f7',
undated: '#9aa7b4',
});
function formatDay(date) {
const match = /^(-?\d{4})-(\d{2})-(\d{2})$/.exec(date || '');
if (!match) return '';
return formatDate(
Date.UTC(Number(match[1]), Number(match[2]) - 1, Number(match[3])),
{ day: 'numeric', month: 'short', year: 'numeric', timeZone: 'UTC' },
);
}
function meters(value) {
return formatNumber(value, {
maximumFractionDigits: value < 10 ? 1 : 0,
});
}
/** How well the position is known, as one card line (or null). */
export function positionLine(record) {
if (record.positionNote) return t('Position: centre of the protected area');
const accuracy = record.positionAccuracy;
if (!Number.isFinite(accuracy)) return null;
// 1852 m is EMODnet's "within a nautical mile" for old, reported positions.
if (accuracy >= 1000)
return t('Position approximate (within about {km} km)', {
km: formatNumber(accuracy / 1000, { maximumFractionDigits: 1 }),
});
return t('Position surveyed (within about {m} m)', { m: meters(accuracy) });
}
/**
* The link a click on the card opens: the Wikipedia (or Wikidata) page, the
* wreck's own page when EMODnet lists one, else EMODnet's portal.
* @param {object} record
* @returns {string}
*/
export function cardLink(record) {
return record?.url || EMODNET_PAGE_URL;
}
/**
* Title and detail lines for one wreck card: deaths first, then when and
* where, then the ship facts. Victims appear as a count only; free text that
* refers to a person by a title or role is dropped by a keyword filter (see
* records.js), which a bare name can still pass.
* @param {object} record A normalized shipwreck record.
* @returns {{title: string, details: string[], link: string}}
*/
export function describeShipwreck(record) {
const titleParts = [t('Shipwreck')];
if (record.name) titleParts.push(record.name);
const details = [];
// Deaths first, right under the title: the fact readers look for.
const toll = [];
if (Number.isFinite(record.casualties))
toll.push(
t('Fatalities: {count}', { count: formatNumber(record.casualties) }),
);
if (record.survivors)
toll.push(
t('Survivors: {count}', { count: formatNumber(record.survivors) }),
);
if (toll.length) details.push(toll.join(' · '));
const when =
formatDay(record.date) ||
(Number.isInteger(record.year) ? String(record.year) : '') ||
record.dating ||
'';
const where = [when, record.country].filter(Boolean);
if (where.length) details.push(where.join(' · '));
if (record.vesselType)
details.push(t('Vessel: {value}', { value: record.vesselType }));
if (record.cause)
details.push(t('What happened: {value}', { value: record.cause }));
if (Number.isFinite(record.depth))
details.push(
record.depthQuality
? t('Depth: {m} m ({quality})', {
m: meters(record.depth),
quality: record.depthQuality,
})
: t('Depth: {m} m', { m: meters(record.depth) }),
);
const position = positionLine(record);
if (position) details.push(position);
if (record.notes) details.push(t('Notes: {value}', { value: record.notes }));
if (record.cargo)
details.push(t('Cargo or finds: {value}', { value: record.cargo }));
if (record.protected) details.push(t('Protected wreck'));
const sources =
record.source === 'wikidata'
? record.alsoIn === 'emodnet'
? 'Wikidata · EMODnet'
: 'Wikidata'
: record.originator
? `EMODnet (${record.originator})`
: 'EMODnet';
details.push(t('Source: {value}', { value: sources }));
const link = cardLink(record);
details.push(
link === EMODNET_PAGE_URL
? t('Click the card to open EMODnet ↗')
: link.includes('.wikipedia.org/')
? t('Click the card to open the article ↗')
: t('Click the card to open the source ↗'),
);
return { title: titleParts.join(' · '), details, link };
}
+63
View File
@@ -0,0 +1,63 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { describeShipwreck, positionLine } from './cards.js';
import { EMODNET_PAGE_URL } from './records.js';
test('a Wikidata card shows the ship facts and links its article', () => {
const card = describeShipwreck({
source: 'wikidata',
alsoIn: 'emodnet',
name: 'HMS Havant',
vesselType: 'destroyer',
date: '1940-06-01',
year: 1940,
cause: 'Was sunk on 06/01/1940 by the German air force',
casualties: 8,
survivors: 120,
depth: 14.72,
depthQuality: 'Least depth known',
positionAccuracy: 3.1,
notes: '1939 G and H-class destroyer',
country: 'France',
url: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)',
});
assert.equal(card.title, 'Shipwreck · HMS Havant');
assert.equal(card.link, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
const text = card.details.join('\n');
assert.equal(card.details[0], 'Fatalities: 8 · Survivors: 120');
assert.match(card.details[1], /1940 · France$/);
assert.match(text, /Vessel: destroyer/);
assert.match(text, /What happened: Was sunk/);
assert.match(text, /Depth: 15 m \(Least depth known\)/);
assert.match(text, /Position surveyed \(within about 3\.1 m\)/);
assert.match(text, /Source: Wikidata · EMODnet/);
assert.match(text, /open the article/);
});
test('an EMODnet card without a page links the portal', () => {
const card = describeShipwreck({
source: 'emodnet',
name: null,
year: null,
dating: 'C1st AD',
originator: 'The Oxford Roman Economy Project',
protected: true,
url: null,
});
assert.equal(card.title, 'Shipwreck');
assert.equal(card.link, EMODNET_PAGE_URL);
const text = card.details.join('\n');
assert.equal(card.details[0], 'C1st AD');
assert.match(text, /Protected wreck/);
assert.match(text, /EMODnet \(The Oxford Roman Economy Project\)/);
assert.match(text, /open EMODnet/);
});
test('position lines read the accuracy', () => {
assert.equal(positionLine({}), null);
assert.match(positionLine({ positionAccuracy: 1852 }), /about 1\.9 km/);
assert.match(
positionLine({ positionNote: 'x' }),
/centre of the protected area/,
);
});
+21
View File
@@ -0,0 +1,21 @@
/** Era chips, oldest first; a wreck with no known year sits in its own chip. */
export const SHIPWRECK_ERAS = Object.freeze([
'before-1900',
'1900-1945',
'after-1945',
'undated',
]);
/**
* The era a wreck belongs to. Ancient wrecks dated only by period
* ("Roman Imperial", "C1st AD") count as before 1900.
* @param {{year?: number|null, ancient?: boolean}} record
* @returns {string}
*/
export function eraOf(record) {
const year = Number.isInteger(record?.year) ? record.year : null;
if (year === null) return record?.ancient ? 'before-1900' : 'undated';
if (year < 1900) return 'before-1900';
if (year <= 1945) return '1900-1945';
return 'after-1945';
}
+13
View File
@@ -0,0 +1,13 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { eraOf } from './eras.js';
test('each wreck falls in one era', () => {
assert.equal(eraOf({ year: 1588 }), 'before-1900');
assert.equal(eraOf({ year: null, ancient: true }), 'before-1900');
assert.equal(eraOf({ year: 1900 }), '1900-1945');
assert.equal(eraOf({ year: 1945 }), '1900-1945');
assert.equal(eraOf({ year: 1946 }), 'after-1945');
assert.equal(eraOf({ year: null }), 'undated');
assert.equal(eraOf(null), 'undated');
});
+528
View File
@@ -0,0 +1,528 @@
import * as Cesium from 'cesium';
import { formatNumber, msg, t, tn } from '../../i18n/index.js';
import {
registerSpriteCollection,
restoreSpriteOrder,
unregisterSpriteCollection,
} from '../../data/spriteOrder.js';
import { createHorizonCull } from '../streetLevel/view.js';
import { ERA_COLORS, ERA_LABELS, describeShipwreck } from './cards.js';
import { SHIPWRECK_ERAS, eraOf } from './eras.js';
import {
inPeriod,
normalizePeriod,
periodRange,
yearExtent,
} from './period.js';
export * from './records.js';
export * from './cards.js';
export * from './eras.js';
export * from './period.js';
export { createShipwrecksSource } from './source.js';
export const SHIPWRECKS_LAYER_ID = 'shipwrecks';
export const SHIPWRECKS_OVERLAY_SOURCE_ID = 'shipwrecks';
const PICK_PREFIX = 'shipwreck:';
const CARD_HOST_OPTIONS = Object.freeze({
cohortLimit: 1,
collisionCapacity: 1,
moving: false,
});
const MAX_CARD_LINES = 14;
/** Wrecks not refreshed for this long leave the map (the proxy's own limit). */
const MAX_SHOWN_AGE_MS = 7 * 24 * 60 * 60 * 1000;
/**
* When the shown wrecks leave the map if the page cannot refresh, on this
* page's clock: the age the proxy reports (its own clock) is subtracted from
* the limit, so the two clocks are never compared, and the newest source
* decides. A wreck both sources list is one merged record, so the snapshot
* goes as a whole, not per source. With no age reported, the snapshot counts
* as fresh when it arrives.
*/
export function snapshotDeadline(snapshot, at) {
const limit = snapshot.maxAgeMs ?? MAX_SHOWN_AGE_MS;
const ages = ['emodnet', 'wikidata']
.filter((name) => snapshot.sources?.[name] !== false)
.map((name) => snapshot.ages?.[name] ?? 0);
const newest = ages.length ? Math.min(...ages) : 0;
return at + limit - newest;
}
/**
* Marker size in pixels: grows with the death toll, from 16 px (no deaths known) to 36 px (about a thousand or more).
*/
export function markerPixelSize(casualties) {
const n = Number.isFinite(casualties) && casualties > 0 ? casualties : 0;
return Math.round(16 + Math.min(20, Math.log2(1 + n) * 2));
}
/**
* A round marker in the era's colour with a sinking hull and mast in the
* middle, as an SVG data URL. It is rasterized at 144 px, four times the
* largest marker, so big markers stay sharp on high-density screens.
* @param {string} color CSS colour.
* @returns {string}
*/
export function wreckMarkerImage(color) {
const svg =
`<svg xmlns="http://www.w3.org/2000/svg" width="144" height="144" viewBox="0 0 36 36">` +
`<circle cx="18" cy="18" r="16" fill="${color}" stroke="#ffffff" stroke-width="2"/>` +
`<path d="M8 21h20l-3.5 5h-13z" fill="#0b1420"/>` +
`<path d="M17 8v12M17 9l6 7h-6" fill="none" stroke="#0b1420" stroke-width="2.2" stroke-linejoin="round"/>` +
`</svg>`;
return `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
}
/**
* Shipwrecks: EMODnet's European heritage wrecks and Wikidata's notable
* wrecks worldwide, one marker each, with a card and era chips.
*/
export function createShipwrecksLayer({
source,
overlayHost = null,
screenSpaceEventHandlerFactory = null,
picking = null,
pointer = null,
openExternal = null,
now = () => Date.now(),
// One collection for every wreck marker (thousands of them): far cheaper to
// draw and rebuild than an entity each. Tests pass a fake.
createMarkers = (scene) =>
new Cesium.BillboardCollection({
scene,
blendOption: Cesium.BlendOption.TRANSLUCENT,
}),
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Shipwrecks require a snapshot source');
let _viewer = null;
let _enabled = false;
let _markers = null;
let _request = null;
let _records = new Map();
let _pins = [];
let _snapshot = null;
let _deadline = null;
let _lastError = null;
let _clickHandler = null;
let _rowListener = null;
let _selectedId = null;
let _selectedCardId = null;
let _selectedLink = null;
let _period = { from: null, to: null };
let _extent = null;
let _range = null;
const _images = Object.fromEntries(
SHIPWRECK_ERAS.map((era) => [era, wreckMarkerImage(ERA_COLORS[era])]),
);
const render = () => _viewer?.scene?.requestRender?.();
const notifyRow = () => _rowListener?.();
const canSelect = () =>
overlayHost && screenSpaceEventHandlerFactory && picking;
// Markers skip the depth test so terrain does not swallow them; the
// horizon cull hides the far side of the planet instead.
const _horizon = createHorizonCull({
getViewer: () => _viewer,
items: () => _pins,
onChange: render,
});
/** Shown: its year is inside the period (undated ones only for all years). */
function visible(record) {
return Boolean(record) && inPeriod(record, _range);
}
function applyPin(pin) {
const show = pin.inFront && visible(pin.record);
if (pin.billboard.show !== show) pin.billboard.show = show;
}
/** Re-apply the period to every marker and the open card. */
function applyFilter() {
for (const pin of _pins) applyPin(pin);
if (_selectedId && !visible(_records.get(_selectedId))) clearSelection();
notifyRow();
render();
}
function rebuild(records) {
_records = new Map(records.map((record) => [record.id, record]));
_extent = yearExtent(records);
_range = periodRange(_period, _extent);
_pins = [];
if (!_markers) return;
_markers.removeAll();
// Within one collection later markers draw on top: add by rising death
// toll so a bigger toll covers smaller neighbours.
const ordered = [...records].sort(
(a, b) => (a.casualties || 0) - (b.casualties || 0),
);
for (const record of ordered) {
const position = Cesium.Cartesian3.fromDegrees(record.lon, record.lat);
const size = markerPixelSize(record.casualties);
const billboard = _markers.add({
id: `${PICK_PREFIX}${record.id}`,
position,
image: _images[eraOf(record)],
width: size,
height: size,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
});
const pin = {
billboard,
record,
position,
inFront: true,
get show() {
return this.inFront;
},
set show(value) {
this.inFront = value;
applyPin(this);
},
};
applyPin(pin);
_pins.push(pin);
}
_horizon.update();
if (_selectedId && !_records.has(_selectedId)) clearSelection();
else if (_selectedId) publishCard();
render();
}
// ---- selection card ----------------------------------------------------
function publishCard() {
if (!canSelect()) return;
const record = _selectedId ? _records.get(_selectedId) : null;
if (!visible(record)) {
clearSelection();
return;
}
const { title, details, link } = describeShipwreck(record);
_selectedLink = link && openExternal ? link : null;
const card = {
id: `shipwreck-card:${record.id}`,
selected: true,
interactive: Boolean(_selectedLink),
title,
details: details.slice(0, MAX_CARD_LINES),
accent: ERA_COLORS[eraOf(record)],
priority: Number.MAX_SAFE_INTEGER,
gapPx: 15,
verticalOnly: true,
placement: 'above',
stateless: true,
horizonCull: true,
position: Cesium.Cartesian3.fromDegrees(record.lon, record.lat),
};
if (card.interactive) {
const target = _selectedLink;
card.accessibilityLabel = t('Open the source for {title}', { title });
card.activate = () => {
openExternal(target);
return true;
};
}
_selectedCardId = card.id;
overlayHost.setEntries(
SHIPWRECKS_OVERLAY_SOURCE_ID,
[card],
CARD_HOST_OPTIONS,
);
overlayHost.setVisible?.(SHIPWRECKS_OVERLAY_SOURCE_ID, true);
}
function clearSelection() {
_selectedId = null;
_selectedCardId = null;
_selectedLink = null;
overlayHost?.setEntries(
SHIPWRECKS_OVERLAY_SOURCE_ID,
[],
CARD_HOST_OPTIONS,
);
}
function pickedRecordId(picked) {
const pickId = picking.resolvePickId(picked);
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
return null;
const id = pickId.slice(PICK_PREFIX.length);
return _records.has(id) ? id : null;
}
function installClickHandler() {
if (!canSelect() || _clickHandler || !_viewer) return;
picking.registerPickOwner?.(
SHIPWRECKS_LAYER_ID,
(pickedId) =>
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickHandler = screenSpaceEventHandlerFactory(_viewer);
_clickHandler.setInputAction((click) => {
if (pointer && !pointer.isPointerFree()) return;
const cardHit = overlayHost.hitTest?.(
click.position?.x,
click.position?.y,
{ sourceId: SHIPWRECKS_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink) openExternal(_selectedLink);
return;
}
const picked = _viewer.scene.pick(click.position);
const id = picked ? pickedRecordId(picked) : null;
if (id) {
_selectedId = id;
publishCard();
render();
return;
}
if (picked) {
const pickId = picking.resolvePickId(picked);
if (pickId && picking.isOwnedByOtherLayer(SHIPWRECKS_LAYER_ID, pickId))
return;
}
if (_selectedId) {
clearSelection();
render();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
function removeClickHandler() {
_clickHandler?.destroy();
_clickHandler = null;
picking?.unregisterPickOwner?.(SHIPWRECKS_LAYER_ID);
}
/** Wrecks shown per era, in one pass over the records. */
function eraCounts() {
const counts = Object.fromEntries(SHIPWRECK_ERAS.map((era) => [era, 0]));
for (const record of _records.values())
if (inPeriod(record, _range)) counts[eraOf(record)]++;
return counts;
}
/** The years that have a dated wreck, plus `extra` ones, newest first. */
function yearsInData(extra = []) {
const years = new Set(extra);
for (const record of _records.values())
if (Number.isInteger(record.year)) years.add(record.year);
return [...years].sort((a, b) => b - a);
}
/** The start and end year pickers, side by side. */
function periodControls() {
if (!_extent || _extent.min === _extent.max) return {};
const range = periodRange(_period, _extent);
const valueText = range.all
? t('All years')
: range.from === range.to
? String(range.from)
: `${range.from}–${range.to}`;
// Only years with a wreck: a picker of every year since the oldest
// dated wreck would run to well over a thousand entries.
// The chosen ends stay listed even when no wreck sank that year.
const options = yearsInData([range.from, range.to]).map((year) => ({
value: year,
label: String(year),
}));
return {
range: {
id: 'period',
label: t('Period'),
valueText,
from: {
label: t('From'),
ariaLabel: t('First year of the shipwreck period'),
value: range.from,
},
to: {
label: t('To'),
ariaLabel: t('Last year of the shipwreck period'),
value: range.to,
},
options,
params: (end, value) => ({ [end]: Number(value) }),
},
};
}
const layer = {
id: SHIPWRECKS_LAYER_ID,
name: 'Shipwrecks',
icon: '⚓',
source: 'EMODnet · Wikidata',
// The proxy refreshes once a day; this only notices a new snapshot.
updateInterval: 6 * 60 * 60 * 1000,
init(viewer) {
if (_viewer) throw new Error('Shipwrecks layer is already initialized');
_viewer = viewer;
_markers = createMarkers(viewer.scene);
_markers.show = false;
viewer.scene.primitives.add(_markers);
registerSpriteCollection(SHIPWRECKS_LAYER_ID, _markers);
},
enable() {
_enabled = true;
if (_markers) _markers.show = true;
restoreSpriteOrder(_viewer);
installClickHandler();
if (_pins.length) _horizon.update();
},
disable() {
_enabled = false;
_request?.abort();
_request = null;
if (_markers) _markers.show = false;
removeClickHandler();
clearSelection();
_horizon.stop();
render();
},
async update() {
if (!_enabled || !_markers) return false;
_request?.abort();
const request = new AbortController();
_request = request;
try {
const snapshot = await source.getSnapshot({ signal: request.signal });
if (request.signal.aborted || _request !== request || !_enabled)
return false;
// The page checks every 6 h; the proxy refreshes once a day. Only a
// new snapshot rebuilds the markers.
const unchanged =
typeof snapshot.version === 'string' &&
snapshot.version === _snapshot?.version &&
_pins.length > 0;
_snapshot = snapshot;
_deadline = snapshotDeadline(snapshot, now());
_lastError =
snapshot.sources.emodnet && snapshot.sources.wikidata
? null
: snapshot.sources.emodnet
? msg('Wikidata unavailable; showing EMODnet only')
: msg('EMODnet unavailable; showing Wikidata only');
if (!unchanged) rebuild(snapshot.records);
notifyRow();
return true;
} catch (error) {
if (request.signal.aborted || _request !== request || !_enabled)
return false;
console.warn('[Data:Shipwrecks] Fetch error:', error);
_lastError = error?.message || msg('Shipwrecks unavailable');
// What is on the map was not refreshed: say so, and drop it once
// even its newest source is older than the proxy would serve.
if (_snapshot) {
if (now() >= _deadline) {
_snapshot = null;
_deadline = null;
rebuild([]);
} else _snapshot = { ..._snapshot, stale: true };
}
notifyRow();
return false;
} finally {
if (_request === request) _request = null;
}
},
destroy(viewer = _viewer) {
layer.disable();
if (_markers) {
unregisterSpriteCollection(SHIPWRECKS_LAYER_ID, _markers);
const primitives = viewer?.scene?.primitives;
if (primitives && !primitives.isDestroyed?.())
primitives.remove(_markers);
_markers = null;
}
_records = new Map();
_pins = [];
_snapshot = null;
_deadline = null;
_viewer = null;
_rowListener = null;
},
/** The period filter: `from` and `to` are years (null = oldest / latest in the data). */
getParams() {
return { ..._period };
},
setParams(params = {}) {
const next = normalizePeriod(params, _period);
if (next.from === _period.from && next.to === _period.to) return true;
_period = next;
_range = periodRange(_period, _extent);
applyFilter();
return true;
},
setRowControlsListener(listener) {
_rowListener = listener;
},
getRowControls() {
const counts = eraCounts();
return {
chips: [],
...periodControls(),
// The colours are a legend: when the ship sank.
legend: SHIPWRECK_ERAS.map((era) => ({
label: t(ERA_LABELS[era]),
count: counts[era],
color: ERA_COLORS[era],
blurb: tn(counts[era], '{count} wreck', '{count} wrecks', {
count: formatNumber(counts[era]),
}),
})),
info: t('EMODnet (European waters) · Wikidata (worldwide)'),
infoTitle: t(
'European heritage wrecks come from EMODnet Human Activities; notable wrecks worldwide come from Wikidata. Colour shows when the ship sank; marker size grows with deaths. Click a marker for its card.',
),
};
},
getStats() {
let shown = 0;
for (const record of _records.values()) if (visible(record)) shown++;
return {
count: shown,
lastUpdate: _snapshot?.fetchedAt ?? null,
stale: _snapshot?.stale === true,
error: _lastError,
};
},
/** Loaded records as plain JSON-safe objects, for tools and QA. */
getAnalystRecords(maxCount = 2000) {
if (!_enabled) return [];
const out = [];
for (const record of _records.values()) {
if (out.length >= maxCount) break;
if (!visible(record)) continue;
out.push({
id: record.id,
source: record.source,
name: record.name,
vesselType: record.vesselType,
year: record.year,
era: eraOf(record),
lat: record.lat,
lon: record.lon,
depth: record.depth,
casualties: record.casualties,
});
}
return out;
},
};
return layer;
}
+383
View File
@@ -0,0 +1,383 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import * as picking from '../../data/pickRegistry.js';
import {
createShipwrecksLayer,
markerPixelSize,
snapshotDeadline,
} from './index.js';
const wreck = (id, extra = {}) => ({
id,
source: 'wikidata',
name: id,
lat: 50,
lon: -1,
year: 1912,
date: null,
casualties: null,
...extra,
});
const snapshot = (records, version = 'v1') => ({
records,
fetchedAt: 1,
stale: false,
version,
sources: { emodnet: true, wikidata: true },
});
function deferred() {
let resolve;
const promise = new Promise((done) => {
resolve = done;
});
return { promise, resolve };
}
/** A fake billboard collection that records what the layer adds. */
function fakeMarkers() {
const collection = {
show: true,
billboards: [],
rebuilds: 0,
add(options) {
const billboard = { show: true, ...options };
collection.billboards.push(billboard);
return billboard;
},
removeAll() {
collection.rebuilds++;
collection.billboards = [];
},
};
return collection;
}
function harness({ snapshots, now = () => 1 } = {}) {
const markers = fakeMarkers();
const primitives = [];
const cards = [];
const handlers = [];
const opened = [];
let pickResult = null;
const viewer = {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(-1, 50, 2e6) },
scene: {
canvas: {},
requestRender() {},
pick: () => pickResult,
preRender: { addEventListener: () => () => {} },
primitives: {
add: (primitive) => primitives.push(primitive),
remove: (primitive) =>
primitives.splice(primitives.indexOf(primitive), 1),
raiseToTop() {},
contains: (primitive) => primitives.includes(primitive),
},
},
};
const queue = [...(snapshots || [])];
const requests = [];
const layer = createShipwrecksLayer({
source: {
getSnapshot({ signal }) {
requests.push(signal);
const next = queue.shift();
if (next instanceof Error) return Promise.reject(next);
return next instanceof Promise ? next : Promise.resolve(next);
},
},
createMarkers: () => markers,
overlayHost: {
setEntries: (_source, entries) => cards.push(entries),
setVisible() {},
hitTest: () => null,
},
screenSpaceEventHandlerFactory: () => {
const handler = {
setInputAction(callback) {
handler.click = callback;
},
destroy() {
handler.destroyed = true;
},
};
handlers.push(handler);
return handler;
},
picking,
pointer: { isPointerFree: () => true },
openExternal: (url) => opened.push(url),
now: () => now(),
});
layer.init(viewer);
return {
layer,
markers,
primitives,
cards,
handlers,
requests,
opened,
pick(id) {
pickResult = id ? { id: `shipwreck:${id}` } : null;
},
lastCard: () => cards.at(-1),
};
}
test('markers live in one collection, shown only while the layer is on', async () => {
const h = harness({ snapshots: [snapshot([wreck('a'), wreck('b')])] });
assert.deepEqual(h.primitives, [h.markers]);
assert.equal(h.markers.show, false);
h.layer.enable();
assert.equal(h.markers.show, true);
assert.equal(await h.layer.update(), true);
assert.equal(h.markers.billboards.length, 2);
assert.equal(h.layer.getStats().count, 2);
h.layer.disable();
assert.equal(h.markers.show, false);
assert.equal(h.handlers[0].destroyed, true);
h.layer.destroy();
assert.deepEqual(h.primitives, [], 'the collection leaves the scene');
});
test('markers sit on the wreck: no eye offset, bigger toll drawn last', async () => {
const h = harness({
snapshots: [
snapshot([
wreck('big', { casualties: 1500 }),
wreck('none'),
wreck('small', { casualties: 3 }),
]),
],
});
h.layer.enable();
await h.layer.update();
const ids = h.markers.billboards.map((billboard) => billboard.id);
assert.deepEqual(ids, ['shipwreck:none', 'shipwreck:small', 'shipwreck:big']);
for (const billboard of h.markers.billboards)
assert.equal(billboard.eyeOffset, undefined);
assert.equal(h.markers.billboards[2].width, markerPixelSize(1500));
});
test('an unchanged snapshot does not rebuild the markers', async () => {
const records = [wreck('a')];
const h = harness({
snapshots: [
snapshot(records, 'v1'),
snapshot(records, 'v1'),
snapshot([wreck('a'), wreck('b')], 'v2'),
],
});
h.layer.enable();
await h.layer.update();
await h.layer.update();
assert.equal(h.markers.rebuilds, 1);
await h.layer.update();
assert.equal(h.markers.rebuilds, 2);
assert.equal(h.markers.billboards.length, 2);
});
test('a response that arrives after the layer is turned off is ignored', async () => {
const late = deferred();
const h = harness({ snapshots: [late.promise] });
h.layer.enable();
const pending = h.layer.update();
h.layer.disable();
assert.equal(h.requests[0].aborted, true);
late.resolve(snapshot([wreck('a')]));
assert.equal(await pending, false);
assert.equal(h.markers.billboards.length, 0);
});
test('a click opens the card; a period that excludes the wreck closes it', async () => {
const h = harness({
snapshots: [
snapshot([wreck('old', { year: 1850 }), wreck('new', { year: 1990 })]),
],
});
h.layer.enable();
await h.layer.update();
h.pick('old');
h.handlers[0].click({ position: { x: 1, y: 1 } });
const [card] = h.lastCard();
assert.equal(card.id, 'shipwreck-card:old');
h.layer.setParams({ from: 1900, to: 1990 });
assert.deepEqual(h.lastCard(), [], 'the hidden wreck loses its card');
const shown = h.markers.billboards.filter((billboard) => billboard.show);
assert.deepEqual(
shown.map((billboard) => billboard.id),
['shipwreck:new'],
);
assert.equal(h.layer.getStats().count, 1);
});
test('the year pickers list only years with a wreck, and each era is counted', async () => {
const h = harness({
snapshots: [
snapshot([
wreck('a', { year: 300 }),
wreck('b', { year: 1912 }),
wreck('c', { year: 1912 }),
wreck('d', { year: 1990 }),
wreck('e', { year: null }),
]),
],
});
h.layer.enable();
await h.layer.update();
let controls = h.layer.getRowControls();
assert.deepEqual(
controls.range.options.map((option) => option.value),
[1990, 1912, 300],
);
assert.deepEqual(
controls.legend.map((era) => era.count),
[1, 2, 1, 1],
);
h.layer.setParams({ from: 1900, to: 1950 });
controls = h.layer.getRowControls();
assert.deepEqual(
controls.range.options.map((option) => option.value),
[1990, 1950, 1912, 1900, 300],
'the chosen ends are listed too',
);
assert.deepEqual(
controls.legend.map((era) => era.count),
[0, 2, 0, 0],
);
});
test('a source without a version rebuilds on every new snapshot', async () => {
const bare = (records) => {
const value = snapshot(records);
delete value.version;
return value;
};
const h = harness({
snapshots: [
bare([wreck('a')]),
bare([wreck('a'), wreck('b')]),
{ ...snapshot([wreck('a')]), version: null },
{ ...snapshot([wreck('a'), wreck('b'), wreck('c')]), version: null },
],
});
h.layer.enable();
for (const expected of [1, 2, 1, 3]) {
await h.layer.update();
assert.equal(h.markers.billboards.length, expected);
}
});
test('a failed refresh marks the shown wrecks stale, and clears them after seven days', async () => {
const DAY = 24 * 60 * 60 * 1000;
let clock = 1;
const h = harness({
now: () => clock,
snapshots: [
snapshot([wreck('a')]),
new Error('Shipwrecks unavailable (HTTP 502)'),
new Error('Shipwrecks unavailable (HTTP 502)'),
],
});
h.layer.enable();
await h.layer.update();
assert.equal(h.layer.getStats().stale, false);
clock = 1 + 2 * DAY;
assert.equal(await h.layer.update(), false);
assert.equal(h.layer.getStats().stale, true);
assert.equal(h.layer.getStats().count, 1, 'still shown, as stale');
clock = 1 + 8 * DAY;
await h.layer.update();
assert.equal(h.layer.getStats().count, 0, 'expired wrecks leave the map');
assert.equal(h.markers.billboards.length, 0);
});
test('expiry runs on the page clock and keeps every wreck until the newest source is too old', async () => {
const DAY = 24 * 60 * 60 * 1000;
const down = () => new Error('Shipwrecks unavailable (HTTP 502)');
// The page clock is far from the proxy's fetchedAt: only reported ages count.
let clock = 5e12;
const h = harness({
now: () => clock,
snapshots: [
{
...snapshot([
wreck('fresh', { source: 'emodnet' }),
wreck('merged', { source: 'wikidata', alsoIn: 'emodnet' }),
]),
fetchedAt: 1,
ages: { emodnet: 0, wikidata: 6.5 * DAY },
maxAgeMs: 7 * DAY,
},
down(),
down(),
],
});
h.layer.enable();
await h.layer.update();
clock += 1 * DAY;
await h.layer.update();
assert.equal(
h.layer.getStats().count,
2,
'nothing leaves while EMODnet is in date',
);
assert.equal(h.layer.getStats().stale, true);
clock += 6.5 * DAY;
await h.layer.update();
assert.equal(
h.layer.getStats().count,
0,
'all leave once the newest is too old',
);
});
test('a snapshot with no timestamp or ages still expires seven days after it arrived', async () => {
const DAY = 24 * 60 * 60 * 1000;
let clock = 100;
const h = harness({
now: () => clock,
snapshots: [
{ ...snapshot([wreck('a')]), fetchedAt: null },
new Error('down'),
],
});
h.layer.enable();
await h.layer.update();
clock += 8 * DAY;
await h.layer.update();
assert.equal(h.layer.getStats().count, 0);
});
test('the page deadline subtracts the newest available source age from the limit', () => {
const DAY = 24 * 60 * 60 * 1000;
const both = { emodnet: true, wikidata: true };
assert.equal(
snapshotDeadline(
{
sources: both,
ages: { emodnet: 2 * DAY, wikidata: 6.5 * DAY },
maxAgeMs: 5 * DAY,
},
100,
),
100 + 3 * DAY,
);
assert.equal(
snapshotDeadline(
{
sources: { emodnet: false, wikidata: true },
ages: { emodnet: null, wikidata: 4 * DAY },
maxAgeMs: 5 * DAY,
},
0,
),
1 * DAY,
'an unavailable source does not count',
);
assert.equal(snapshotDeadline({ sources: both }, 0), 7 * DAY, 'defaults');
});
+75
View File
@@ -0,0 +1,75 @@
/**
* The sinking year, or null when it is unknown (ancient wrecks dated only by
* period, "C1st AD", have none).
*/
export function recordYear(record) {
return Number.isInteger(record?.year) ? record.year : null;
}
/** First and last year present in the records (null when none is dated). */
export function yearExtent(records) {
let min = Infinity;
let max = -Infinity;
for (const record of records) {
const year = recordYear(record);
if (year === null) continue;
if (year < min) min = year;
if (year > max) max = year;
}
return Number.isFinite(min) ? { min, max } : null;
}
function yearParam(value) {
if (value === null) return null;
const year =
typeof value === 'string' && /^-?\d+$/.test(value) ? Number(value) : value;
return Number.isInteger(year) && Math.abs(year) < 10000 ? year : undefined;
}
/**
* Merge a (partial) period request into the current one. `from: null` means
* the first year in the data and `to: null` the latest; an invalid year keeps
* the current one, and a start after the end is stored as the reverse.
* @param {{from?: number|string|null, to?: number|string|null}} params
* @param {{from: number|null, to: number|null}} current
* @returns {{from: number|null, to: number|null}}
*/
export function normalizePeriod(
params = {},
current = { from: null, to: null },
) {
const next = { ...current };
for (const end of ['from', 'to']) {
if (!(end in params)) continue;
const year = yearParam(params[end]);
if (year !== undefined) next[end] = year;
}
// Stored in the order it is shown, so a later edit to one end (the picker
// sends only that end) changes the end the reader picked, not the other.
if (Number.isInteger(next.from) && Number.isInteger(next.to))
if (next.from > next.to) [next.from, next.to] = [next.to, next.from];
return next;
}
/**
* The inclusive year range a period covers over the data's extent. Years are
* clamped to the data, and a start after the end is read as the reverse.
* @returns {{from: number, to: number, all: boolean}|null}
*/
export function periodRange(period, extent) {
if (!extent) return null;
const clamp = (year, fallback) =>
Math.min(extent.max, Math.max(extent.min, year ?? fallback));
const start = clamp(period.from, extent.min);
const end = clamp(period.to, extent.max);
const from = Math.min(start, end);
const to = Math.max(start, end);
return { from, to, all: from === extent.min && to === extent.max };
}
/** Whether a record falls in the range; undated records only when all years show. */
export function inPeriod(record, range) {
if (!range || range.all) return true;
const year = recordYear(record);
return year !== null && year >= range.from && year <= range.to;
}
+58
View File
@@ -0,0 +1,58 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
inPeriod,
normalizePeriod,
periodRange,
recordYear,
yearExtent,
} from './period.js';
const RECORDS = [
{ year: 1588 },
{ year: 1912 },
{ year: 2012 },
{ year: null, ancient: true },
];
test('years come from the record; the extent ignores undated wrecks', () => {
assert.equal(recordYear(RECORDS[1]), 1912);
assert.equal(recordYear(RECORDS[3]), null);
assert.deepEqual(yearExtent(RECORDS), { min: 1588, max: 2012 });
assert.equal(yearExtent([{ year: null }]), null);
});
test('all years show every wreck; a narrower period hides undated ones', () => {
const extent = yearExtent(RECORDS);
const all = periodRange({ from: null, to: null }, extent);
assert.deepEqual(all, { from: 1588, to: 2012, all: true });
assert.ok(RECORDS.every((record) => inPeriod(record, all)));
const wars = periodRange(normalizePeriod({ from: '1914', to: 1945 }), extent);
assert.deepEqual(
RECORDS.map((record) => inPeriod(record, wars)),
[false, false, false, false],
);
const reversed = periodRange({ from: 1950, to: 1900 }, extent);
assert.deepEqual(reversed, { from: 1900, to: 1950, all: false });
assert.equal(inPeriod(RECORDS[1], reversed), true);
});
test('a reversed period is stored as shown, so editing one end keeps the other', () => {
const reversed = normalizePeriod({ from: 1950, to: 1900 });
assert.deepEqual(reversed, { from: 1900, to: 1950 });
// The picker shows 1900–1950; the reader changes "From" to 1920.
assert.deepEqual(normalizePeriod({ from: 1920 }, reversed), {
from: 1920,
to: 1950,
});
// Moving "From" past "To" reads as the reverse, never an empty range.
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: 1900, to: 1950 }), {
from: 1950,
to: 1960,
});
// One open end stays open.
assert.deepEqual(normalizePeriod({ from: 1960 }, { from: null, to: null }), {
from: 1960,
to: null,
});
});
+455
View File
@@ -0,0 +1,455 @@
// Shared by the server proxy (server/providers/shipwrecks.js) and the browser
// layer, so it must not load the i18n catalogs: values stay data.
/** EMODnet Human Activities "Cultural Heritage – Ship wrecks" (CC BY 4.0). */
export const EMODNET_WFS_URL =
'https://ows.emodnet-humanactivities.eu/wfs?service=WFS&request=GetFeature' +
'&version=2.0.0&typeNames=emodnet:heritageshipwrecks' +
'&outputFormat=application/json&srsName=EPSG:4326';
/** Landing page shown when an EMODnet wreck has no web page of its own. */
export const EMODNET_PAGE_URL =
'https://emodnet.ec.europa.eu/en/human-activities';
export const SHIPWRECK_SOURCES = Object.freeze(['emodnet', 'wikidata']);
/**
* Wikidata (CC0): shipwreck items that have at least one Wikipedia article,
* so the worldwide set stays to notable wrecks and skips bulk register
* imports, plus sinking events ("sinking of the RMS Titanic"), which are where
* Wikidata keeps the death toll. Dates, the end of service (P576) included,
* come with their precision so a month-precise date is not shown as the 1st.
* Only ship and event facts are read: no items about people.
*/
export const WIKIDATA_QUERY = `SELECT ?item ?itemLabel ?itemDescription ?coord ?sunk ?sunkPrecision ?end ?endPrecision ?deaths ?survivors ?typeLabel ?enwiki ?event WHERE {
{
?item wdt:P31/wdt:P279* wd:Q852190 ; wdt:P625 ?coord ; wikibase:sitelinks ?links .
FILTER(?links > 0)
OPTIONAL { ?item p:P793 ?wreck . ?wreck ps:P793 wd:Q906512 ; pqv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
OPTIONAL { ?item p:P576 [ a wikibase:BestRank ; psv:P576 [ wikibase:timeValue ?end ; wikibase:timePrecision ?endPrecision ] ] }
OPTIONAL { ?item wdt:P31 ?type . FILTER(?type != wd:Q852190) }
} UNION {
?item wdt:P31/wdt:P279* wd:Q906512 ; wdt:P625 ?coord .
BIND("event" AS ?event)
OPTIONAL { ?item p:P585/psv:P585 [ wikibase:timeValue ?sunk ; wikibase:timePrecision ?sunkPrecision ] }
OPTIONAL { ?item wdt:P1561 ?survivors }
}
OPTIONAL { ?item wdt:P1120 ?deaths }
OPTIONAL { ?enwiki schema:about ?item ; schema:isPartOf <https://en.wikipedia.org/> }
SERVICE wikibase:label { bd:serviceParam wikibase:language "en,mul,fr,de,es,it,pt,ru,uk,ja,zh,ar". }
}`;
const MAX_TEXT = 160;
const MAX_NOTE = 260;
/** Same name within this distance: one wreck seen by both sources. */
const SAME_WRECK_KM = 3;
// Free text sometimes names people (owners, masters, divers who reported a
// wreck). The layer is about ships, so text that refers to a person by a title
// or role is dropped whole. This is a keyword filter: a bare name with none of
// these words still passes.
const PERSON_TEXT =
/\b(mr|mrs|ms|dr|capt|captain|master|skipper|owner|owned|crew|body|bodies|drowned|reported by|according to)\b/i;
/** EMODnet writes "n/a" or nothing where a value is unknown. */
function clean(value, max = MAX_TEXT) {
if (typeof value !== 'string') return null;
const text = value
.replace(/[\u0000-\u001f<>]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text || /^(n\/a|null|unknown|none|-)$/i.test(text)) return null;
return text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text;
}
/** Free text with none of the person keywords in it, or null. */
function impersonalText(value, max) {
const text = clean(value, max);
return text && !PERSON_TEXT.test(text) ? text : null;
}
function positiveNumber(value, max) {
const n = typeof value === 'number' ? value : Number(value);
return Number.isFinite(n) && n > 0 && n <= max ? n : null;
}
function count(value) {
const text = String(value ?? '').replace(/\.0+$/, '');
if (!/^\d{1,6}$/.test(text)) return null;
return Number(text);
}
/** A sinking year from "1917", "1917-1918" or "c. 1917"; null otherwise. */
export function parseYear(value, maxYear = new Date().getUTCFullYear()) {
const match = /(?:^|\D)(\d{3,4})(?:\D|$)/.exec(String(value ?? ''));
if (!match) return null;
const year = Number(match[1]);
return year >= 100 && year <= maxYear ? year : null;
}
function validPoint(lat, lon) {
return (
Number.isFinite(lat) &&
Number.isFinite(lon) &&
Math.abs(lat) <= 90 &&
Math.abs(lon) <= 180 &&
!(lat === 0 && lon === 0)
);
}
function httpUrl(value) {
const text = clean(value, 400);
if (!text) return null;
try {
const url = new URL(text);
return url.protocol === 'https:' || url.protocol === 'http:'
? url.href
: null;
} catch {
return null;
}
}
/** Whether a provenance or link value points at wrecksite.eu, in any form. */
function fromWrecksite(value) {
return typeof value === 'string' && /wrecksite/i.test(value);
}
/**
* Normalize EMODnet's shipwreck GeoJSON. Records the portal took from
* wrecksite.eu, named in the provenance or linked as the record's page, are
* skipped: that site's data is not openly licensed.
* @param {object} payload WFS GeoJSON FeatureCollection.
* @returns {object[]} Shipwreck records.
*/
export function normalizeEmodnetFeatures(payload) {
const features = payload?.features;
if (!Array.isArray(features)) return [];
const out = [];
const ids = new Set();
for (const feature of features) {
const p = feature?.properties || {};
const coords = feature?.geometry?.coordinates;
if (feature?.geometry?.type !== 'Point' || !Array.isArray(coords)) continue;
const lon = Number(coords[0]);
const lat = Number(coords[1]);
if (!validPoint(lat, lon)) continue;
// Checked on the raw values: the shown origin is cut to 80 characters,
// and a long provenance list can name wrecksite.eu after the cut.
if (fromWrecksite(p.source_inf) || fromWrecksite(p.website1)) continue;
const origin = clean(p.source_inf, 80);
const key = clean(String(feature.id ?? p.source_id ?? ''), 80);
if (!key) continue;
const id = `emodnet:${key}`;
if (ids.has(id)) continue;
ids.add(id);
const year = parseYear(p.sink_yr);
const dating = clean(p.dating, 60);
const period = clean(p.period, 60);
const vesselType =
clean(p.obj_type, 60) ||
(() => {
// ship_char is sometimes a short type ("Trawler"), sometimes a long
// history that can name people; only the short form is a type.
const text = clean(p.ship_char, 40);
return text && !/\d/.test(text) && !PERSON_TEXT.test(text)
? text
: null;
})();
out.push({
id,
source: 'emodnet',
lat,
lon,
name: clean(p.name, 100),
vesselType,
year,
date: null,
dating: year ? null : dating,
ancient: !year && Boolean(period || dating),
cause: impersonalText(p.sink_context, MAX_NOTE),
notes: period && dating ? `${period} (${dating})` : period,
cargo: impersonalText(p.artefacts, 120),
protected: /protected/i.test(p.statutory || ''),
depth: positiveNumber(p.least_depth, 11000),
depthQuality: clean(p.depth_prec, 80),
positionAccuracy: positiveNumber(p.loc_prec, 100000),
positionNote: /centroid/i.test(p.point_info || '')
? 'Centre of the protected area'
: null,
casualties: null,
survivors: null,
country: clean(p.country, 60),
originator: origin,
url: httpUrl(p.website1),
});
}
return out;
}
function wikiUrl(value) {
const url = httpUrl(value);
return url && /^https:\/\/[a-z]{2,3}\.wikipedia\.org\/wiki\//.test(url)
? url
: null;
}
/**
* A Wikidata time as a day ("1912-04-15") when it is day-precise, else as a
* year only: a month- or year-precise value reads back as the 1st. A year
* before AD 100 ("-0299", 300 BC) has no place on the year picker, so it is
* kept as ancient with its year as text, like EMODnet's period-dated wrecks.
* @returns {{date: string|null, year: number|null, dating: string|null}}
*/
function wikidataTime(value, precision) {
const none = { date: null, year: null, dating: null };
const match = /^([+-]?)(\d{4,})-(\d{2})-(\d{2})T/.exec(value || '');
if (!match) return none;
// A value without a precision is only trusted to the year.
const p = precision == null ? 9 : Number(precision);
// 11 = day; 10 = month; 9 = year; below 9 is a decade or coarser.
if (!Number.isFinite(p) || p < 9) return none;
const signed = Number(`${match[1] === '-' ? '-' : ''}${match[2]}`);
if (signed < 100) {
// The query service writes XSD 1.1 years: 0000 is 1 BC, -0299 is 300 BC.
const dating = signed <= 0 ? `${1 - signed} BC` : `AD ${signed}`;
return { date: null, year: null, dating };
}
const year = parseYear(String(signed));
if (year === null) return none;
if (p >= 11)
return { date: `${match[2]}-${match[3]}-${match[4]}`, year, dating: null };
return { date: null, year, dating: null };
}
/** Whether a record (or a parsed time) says when the ship sank. */
function hasWhen(when) {
return Boolean(when.date || Number.isInteger(when.year) || when.dating);
}
/** Copy when a ship sank from one record (or parsed time) to another. */
function takeWhen(target, from) {
target.date = from.date ?? null;
target.year = from.year ?? null;
target.dating = from.dating ?? null;
target.ancient = Boolean(from.dating) || Boolean(from.ancient);
}
/** "sinking of the RMS Titanic" → "Sinking of the RMS Titanic". */
function sentenceCase(text) {
return text ? text.charAt(0).toUpperCase() + text.slice(1) : text;
}
/**
* Normalize Wikidata SPARQL results to shipwreck records (one per item).
* Sinking events are folded into the ship they sank when both are listed.
* @param {object} payload SPARQL JSON results.
* @returns {object[]}
*/
export function normalizeWikidataResults(payload) {
const bindings = payload?.results?.bindings;
if (!Array.isArray(bindings)) return [];
const byItem = new Map();
for (const binding of bindings) {
const value = (key) => binding?.[key]?.value;
const qid = /\/entity\/(Q\d{1,12})$/.exec(value('item') || '')?.[1];
if (!qid) continue;
const sunk = wikidataTime(value('sunk'), value('sunkPrecision'));
const ended = wikidataTime(value('end'), value('endPrecision'));
const known = byItem.get(qid);
if (known) {
// Extra rows only add what the first one lacked.
known.vesselType ||= clean(value('typeLabel'), 60);
if (!hasWhen(known)) takeWhen(known, hasWhen(sunk) ? sunk : ended);
known.casualties ??= count(value('deaths'));
known.survivors ??= count(value('survivors'));
continue;
}
const point = /^Point\(([-\d.eE]+) ([-\d.eE]+)\)$/.exec(
value('coord') || '',
);
const lon = point ? Number(point[1]) : NaN;
const lat = point ? Number(point[2]) : NaN;
if (!validPoint(lat, lon)) continue;
const name = clean(value('itemLabel'), 100);
const event = value('event') === 'event';
const when = hasWhen(sunk) ? sunk : ended;
byItem.set(qid, {
id: `wikidata:${qid}`,
source: 'wikidata',
event,
lat,
lon,
// An unlabelled item reads back as its own Q-id; that is no name.
name: name && name !== qid ? (event ? sentenceCase(name) : name) : null,
vesselType: event ? null : clean(value('typeLabel'), 60),
year: when.year,
date: when.date,
dating: when.dating,
ancient: Boolean(when.dating),
cause: null,
notes: impersonalText(value('itemDescription'), MAX_TEXT),
cargo: null,
protected: false,
depth: null,
depthQuality: null,
positionAccuracy: null,
positionNote: null,
casualties: count(value('deaths')),
survivors: count(value('survivors')),
country: null,
originator: null,
url:
// English Wikipedia, else the Wikidata item, which links the
// article in every language that has one.
wikiUrl(value('enwiki')) || `https://www.wikidata.org/wiki/${qid}`,
});
}
return foldSinkingEvents([...byItem.values()]);
}
/** An event this far from a listed ship whose name it contains is that ship's sinking. */
const SAME_SINKING_KM = 50;
/**
* "Sinking of the RMS Titanic" near the RMS Titanic wreck is one marker: the
* ship keeps its article and takes the event's date, deaths and survivors.
*/
function foldSinkingEvents(records) {
// Wikidata sometimes has both the ship and its wreck as items at one spot
// ("Titanic", "wreck of the RMS Titanic"): keep the ship, one marker.
const isWreckItem = (record) => (/^wreck\b/i.test(record.name || '') ? 1 : 0);
const ships = [];
const candidates = records
.filter((record) => !record.event)
.sort((a, b) => isWreckItem(a) - isWreckItem(b));
for (const record of candidates) {
const key = nameKey(record.name);
const twin =
key &&
ships.find(
(ship) =>
nameKey(ship.name) === key &&
distanceKm(ship, record) <= SAME_WRECK_KM,
);
if (!twin) {
ships.push(record);
continue;
}
twin.vesselType ||= record.vesselType;
if (!hasWhen(twin)) takeWhen(twin, record);
twin.casualties ??= record.casualties;
twin.survivors ??= record.survivors;
}
const out = [...ships];
for (const event of records.filter((record) => record.event)) {
const eventKey = ` ${nameKey(event.name)} `;
const ship = ships.find((candidate) => {
const key = nameKey(candidate.name);
return (
key.length >= 3 &&
eventKey.includes(` ${key} `) &&
distanceKm(candidate, event) <= SAME_SINKING_KM
);
});
if (!ship) {
out.push(event);
continue;
}
if (!hasWhen(ship)) {
takeWhen(ship, event);
} else if (!ship.date && event.date && event.year === ship.year) {
ship.date = event.date;
}
ship.casualties ??= event.casualties;
ship.survivors ??= event.survivors;
}
for (const record of out) delete record.event;
return out;
}
function nameKey(name) {
return String(name || '')
.normalize('NFD')
.replace(/[̀-ͯ]/g, '')
.toLowerCase()
.replace(/\([^)]*\)/g, ' ')
.replace(/\b(wreck|sinking|loss|disaster|of)\b/g, ' ')
.replace(
/\b(hms|hmt|hmhs|hmas|sms|ss|ms|mv|rms|uss|hm|s\/s|m\/v|the)\b/g,
' ',
)
.replace(/[^a-z0-9]+/g, ' ')
.trim();
}
function distanceKm(a, b) {
const rad = Math.PI / 180;
const dLat = (b.lat - a.lat) * rad;
const dLon = (b.lon - a.lon) * rad;
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(a.lat * rad) * Math.cos(b.lat * rad) * Math.sin(dLon / 2) ** 2;
return 12742 * Math.asin(Math.min(1, Math.sqrt(h)));
}
/**
* One list from both sources. A wreck in both (same name, a few km apart)
* keeps the Wikidata record, which links an article, and takes EMODnet's
* survey facts (depth, sinking text, year) that Wikidata lacks.
*/
export function mergeShipwreckRecords(emodnet = [], wikidata = []) {
const byName = new Map();
for (const record of wikidata) {
const key = nameKey(record.name);
if (!key) continue;
if (!byName.has(key)) byName.set(key, []);
byName.get(key).push(record);
}
const kept = [];
for (const record of emodnet) {
const twin = (byName.get(nameKey(record.name)) || []).find(
(candidate) => distanceKm(candidate, record) <= SAME_WRECK_KM,
);
if (!twin) {
kept.push(record);
continue;
}
if (!hasWhen(twin)) takeWhen(twin, record);
twin.vesselType ||= record.vesselType;
twin.cause ||= record.cause;
twin.depth ??= record.depth;
twin.depthQuality ||= record.depthQuality;
twin.positionAccuracy ??= record.positionAccuracy;
twin.country ||= record.country;
twin.protected ||= record.protected;
twin.alsoIn = 'emodnet';
}
return [...wikidata, ...kept];
}
/**
* Validate the proxy's snapshot in the browser.
* @returns {object[]|null} Records, or null when the payload is malformed.
*/
export function normalizeShipwreckSnapshot(payload) {
if (!Array.isArray(payload?.records)) return null;
const rows = [];
const ids = new Set();
for (const record of payload.records) {
if (
!record ||
typeof record.id !== 'string' ||
ids.has(record.id) ||
!SHIPWRECK_SOURCES.includes(record.source) ||
!validPoint(record.lat, record.lon)
)
continue;
ids.add(record.id);
rows.push({
...record,
year: Number.isInteger(record.year) ? record.year : null,
url: httpUrl(record.url),
});
}
return rows;
}
+314
View File
@@ -0,0 +1,314 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
mergeShipwreckRecords,
normalizeEmodnetFeatures,
normalizeShipwreckSnapshot,
normalizeWikidataResults,
parseYear,
WIKIDATA_QUERY,
} from './records.js';
function feature(id, properties, coordinates = [-4.35, 54.13]) {
return {
type: 'Feature',
id,
geometry: { type: 'Point', coordinates },
properties,
};
}
test('EMODnet wrecks keep ship facts and drop text that names people', () => {
const [wreck, roman] = normalizeEmodnetFeatures({
features: [
feature('w.1', {
name: 'MAINA-NUI',
sink_yr: '1987',
sink_context: 'Sank on 07/02/1987',
obj_type: 'Pusher or tug',
least_depth: 12.5,
depth_prec: 'Least depth known',
loc_prec: 50,
country: 'France',
source_inf: 'SHOM',
statutory: 'n/a',
website1: 'n/a',
}),
feature('w.2', {
name: 'Lerici',
sink_yr: '',
dating: 'C1st-2nd AD',
period: 'Roman Imperial',
artefacts: 'Marble, Columns',
obj_type: 'n/a',
ship_char: 'Owned by J. Smith, master was A. Jones',
sink_context: 'Wrecked here, reported by Mr Smith',
}),
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
feature('w.4', { name: 'Null island' }, [0, 0]),
],
});
const ids = normalizeEmodnetFeatures({
features: [
feature('w.3', { name: 'Copied', source_inf: 'www.wrecksite.eu' }),
feature('w.5', {
source_inf: `${'SHOM; '.repeat(20)}wrecksite.eu`,
}),
feature('w.6', { website1: 'https://www.wrecksite.eu/wreck.aspx?1' }),
feature('w.7', { website1: 'wrecksite.eu/wreck/1' }),
feature('w.8', { name: 'Kept', source_inf: 'SHOM' }),
],
}).map((record) => record.id);
assert.deepEqual(ids, ['emodnet:w.8'], 'wrecksite.eu rows are all skipped');
assert.equal(wreck.id, 'emodnet:w.1');
assert.equal(wreck.year, 1987);
assert.equal(wreck.vesselType, 'Pusher or tug');
assert.equal(wreck.cause, 'Sank on 07/02/1987');
assert.equal(wreck.depth, 12.5);
assert.equal(wreck.positionAccuracy, 50);
assert.equal(wreck.url, null);
assert.equal(roman.year, null);
assert.equal(roman.ancient, true);
assert.equal(roman.dating, 'C1st-2nd AD');
assert.equal(roman.notes, 'Roman Imperial (C1st-2nd AD)');
assert.equal(roman.cargo, 'Marble, Columns');
assert.equal(roman.vesselType, null, 'a history naming people is no type');
assert.equal(roman.cause, null, 'text naming a person is dropped');
});
test('Wikidata rows fold into one record per item', () => {
const item = 'http://www.wikidata.org/entity/Q1471525';
const records = normalizeWikidataResults({
results: {
bindings: [
{
item: { value: item },
itemLabel: { value: 'HMS Havant' },
itemDescription: { value: '1939 G and H-class destroyer' },
coord: { value: 'Point(2.26 51.13)' },
sunk: { value: '1940-06-01T00:00:00Z' },
sunkPrecision: { value: '11' },
enwiki: { value: 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)' },
},
{
item: { value: item },
typeLabel: { value: 'destroyer' },
deaths: { value: '8' },
coord: { value: 'Point(2.26 51.13)' },
},
{
item: { value: 'http://www.wikidata.org/entity/Q9' },
itemLabel: { value: 'Q9' },
coord: { value: 'Point(10 10)' },
},
],
},
});
assert.equal(records.length, 2);
const [havant, unnamed] = records;
assert.equal(havant.date, '1940-06-01');
assert.equal(havant.year, 1940);
assert.equal(havant.vesselType, 'destroyer');
assert.equal(havant.casualties, 8);
assert.equal(havant.url, 'https://en.wikipedia.org/wiki/HMS_Havant_(H32)');
assert.equal(unnamed.name, null);
assert.equal(unnamed.url, 'https://www.wikidata.org/wiki/Q9');
});
test('a wreck in both sources keeps Wikidata and takes EMODnet survey facts', () => {
const wikidata = [
{
id: 'wikidata:Q1',
source: 'wikidata',
name: 'HMS Havant',
lat: 51.13,
lon: 2.26,
year: null,
depth: null,
},
];
const emodnet = [
{
id: 'emodnet:a',
source: 'emodnet',
name: 'Havant (HMS)',
lat: 51.131,
lon: 2.262,
year: 1940,
depth: 14.7,
},
{
id: 'emodnet:b',
source: 'emodnet',
name: 'HMS Havant',
lat: 45,
lon: -10,
year: 1950,
},
];
const merged = mergeShipwreckRecords(emodnet, wikidata);
assert.deepEqual(
merged.map((record) => record.id),
['wikidata:Q1', 'emodnet:b'],
);
assert.equal(merged[0].year, 1940);
assert.equal(merged[0].depth, 14.7);
assert.equal(merged[0].alsoIn, 'emodnet');
});
test('years and snapshots are validated', () => {
assert.equal(parseYear('1917-1918'), 1917);
assert.equal(parseYear('c. 1588'), 1588);
assert.equal(parseYear(''), null);
assert.equal(parseYear('3000'), null);
assert.equal(normalizeShipwreckSnapshot({}), null);
const rows = normalizeShipwreckSnapshot({
records: [
{ id: 'a', source: 'emodnet', lat: 1, lon: 2, url: 'javascript:x' },
{ id: 'a', source: 'emodnet', lat: 1, lon: 2 },
{ id: 'b', source: 'other', lat: 1, lon: 2 },
{ id: 'c', source: 'wikidata', lat: 91, lon: 2 },
],
});
assert.equal(rows.length, 1);
assert.equal(rows[0].url, null);
});
test('a sinking event folds into its ship; month-precise dates keep the year only', () => {
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
const records = normalizeWikidataResults({
results: {
bindings: [
{
item: entity('Q25173'),
itemLabel: { value: 'Titanic' },
coord: { value: 'Point(-49.9469 41.7325)' },
},
{
item: entity('Q3018259'),
itemLabel: { value: 'wreck of the RMS Titanic' },
coord: { value: 'Point(-49.9469 41.7325)' },
},
{
item: entity('Q2577588'),
itemLabel: { value: 'sinking of the RMS Titanic' },
coord: { value: 'Point(-49.9458 41.7319)' },
event: { value: 'event' },
sunk: { value: '1912-04-01T00:00:00Z' },
sunkPrecision: { value: '10' },
deaths: { value: '1501' },
survivors: { value: '712' },
},
{
item: entity('Q1245004'),
itemLabel: { value: 'Costa Concordia disaster' },
coord: { value: 'Point(10.92 42.37)' },
event: { value: 'event' },
sunk: { value: '2012-01-13T00:00:00Z' },
sunkPrecision: { value: '11' },
deaths: { value: '32' },
},
],
},
});
assert.deepEqual(
records.map((record) => record.id),
['wikidata:Q25173', 'wikidata:Q1245004'],
);
const [titanic, concordia] = records;
assert.equal(titanic.date, null);
assert.equal(titanic.year, 1912);
assert.equal(titanic.casualties, 1501);
assert.equal(titanic.survivors, 712);
assert.equal(concordia.name, 'Costa Concordia disaster');
assert.equal(concordia.date, '2012-01-13');
assert.equal('event' in concordia, false);
});
test('a date before AD 100 is kept as ancient text, never read as an AD year', () => {
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
const [bc, earlyAd, roman] = normalizeWikidataResults({
results: {
bindings: [
{
item: entity('Q1'),
itemLabel: { value: 'Antikythera wreck' },
coord: { value: 'Point(23.3 35.9)' },
sunk: { value: '-0299-01-01T00:00:00Z' },
sunkPrecision: { value: '11' },
},
{
item: entity('Q2'),
itemLabel: { value: 'Early wreck' },
coord: { value: 'Point(12 40)' },
sunk: { value: '0050-01-01T00:00:00Z' },
sunkPrecision: { value: '9' },
},
{
item: entity('Q3'),
itemLabel: { value: 'Roman wreck' },
coord: { value: 'Point(13 41)' },
sunk: { value: '0300-01-01T00:00:00Z' },
sunkPrecision: { value: '9' },
},
],
},
});
assert.equal(bc.year, null, '300 BC is not the year 300');
assert.equal(bc.date, null, 'no day for a BC date');
assert.equal(bc.dating, '300 BC');
assert.equal(bc.ancient, true);
assert.equal(earlyAd.year, null);
assert.equal(earlyAd.dating, 'AD 50');
assert.equal(earlyAd.ancient, true);
assert.equal(roman.year, 300);
assert.equal(roman.dating, null);
});
test('an end-of-service date keeps its precision: a year-only one is no day', () => {
const entity = (q) => ({ value: `http://www.wikidata.org/entity/${q}` });
const [yearOnly, dayPrecise, unknown] = normalizeWikidataResults({
results: {
bindings: [
{
item: entity('Q11'),
itemLabel: { value: 'Year only' },
coord: { value: 'Point(1 50)' },
end: { value: '1917-01-01T00:00:00Z' },
endPrecision: { value: '9' },
},
{
item: entity('Q12'),
itemLabel: { value: 'Day precise' },
coord: { value: 'Point(2 50)' },
end: { value: '1917-03-04T00:00:00Z' },
endPrecision: { value: '11' },
},
{
item: entity('Q13'),
itemLabel: { value: 'No precision' },
coord: { value: 'Point(3 50)' },
end: { value: '1917-01-01T00:00:00Z' },
},
],
},
});
assert.equal(yearOnly.date, null, 'not shown as 1 Jan 1917');
assert.equal(yearOnly.year, 1917);
assert.equal(dayPrecise.date, '1917-03-04');
assert.equal(unknown.date, null, 'an unknown precision is a year only');
assert.equal(unknown.year, 1917);
});
test('the query reads the end of service with its precision', () => {
assert.match(
WIKIDATA_QUERY,
/psv:P576 \[ wikibase:timeValue \?end ; wikibase:timePrecision \?endPrecision \]/,
);
assert.doesNotMatch(WIKIDATA_QUERY, /wdt:P576/);
});
test('labels and links do not default to one other language', () => {
assert.doesNotMatch(WIKIDATA_QUERY, /ptwiki|pt\.wikipedia/);
assert.match(WIKIDATA_QUERY, /wikibase:language "en,mul,/);
});
+45
View File
@@ -0,0 +1,45 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
import { normalizeShipwreckSnapshot } from './records.js';
const age = (value) => (Number.isFinite(value) && value >= 0 ? value : null);
/** Same-origin source for the proxy's EMODnet + Wikidata shipwreck snapshot. */
export function createShipwrecksSource({
fetchImpl = (...args) => globalThis.fetch(...args),
} = {}) {
return {
async getSnapshot({ signal } = {}) {
signal?.throwIfAborted();
const response = await fetchImpl('/api/shipwrecks', { signal });
if (!response.ok)
throw new Error(`Shipwrecks unavailable (HTTP ${response.status})`);
const payload = await readResponseJsonCapped(
response,
16 * 1024 * 1024,
signal,
);
signal?.throwIfAborted();
const records = normalizeShipwreckSnapshot(payload);
if (!records) throw new Error('Malformed shipwrecks response');
return {
records,
fetchedAt: Number.isFinite(payload.fetchedAt)
? payload.fetchedAt
: null,
stale: payload.stale === true,
// Changes whenever either source's data does; null from an older proxy.
version: typeof payload.version === 'string' ? payload.version : null,
// Each source's age on the proxy's clock (null when unknown).
ages: {
emodnet: age(payload.ages?.emodnet),
wikidata: age(payload.ages?.wikidata),
},
maxAgeMs: age(payload.maxAgeMs),
sources: {
emodnet: payload.sources?.emodnet !== false,
wikidata: payload.sources?.wikidata !== false,
},
};
},
};
}
+27
View File
@@ -0,0 +1,27 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createShipwrecksSource } from './source.js';
const respond = (payload) =>
createShipwrecksSource({ fetchImpl: async () => Response.json(payload) });
test('the snapshot keeps valid source ages and drops malformed ones', async () => {
const record = { id: 'a', source: 'emodnet', lat: 50, lon: -1 };
const good = await respond({
records: [record],
version: 'v',
ages: { emodnet: 0, wikidata: 3600 },
maxAgeMs: 604800000,
}).getSnapshot();
assert.deepEqual(good.ages, { emodnet: 0, wikidata: 3600 });
assert.equal(good.maxAgeMs, 604800000);
assert.equal(good.version, 'v');
const bad = await respond({
records: [record],
ages: { emodnet: -5, wikidata: 'x' },
maxAgeMs: Number.NaN,
}).getSnapshot();
assert.deepEqual(bad.ages, { emodnet: null, wikidata: null });
assert.equal(bad.maxAgeMs, null);
assert.equal(bad.version, null);
});
+195 -18
View File
@@ -15,13 +15,14 @@ import {
keyAlternatives,
summarizeCoverage,
} from './uiState.js';
import { groundUnderCamera, viewCentre } from './view.js';
import { groundUnderCamera, metresBetween, viewCentre } from './view.js';
import { createGroundClick, groundClickHeightOk } from './groundClick.js';
import { msg, t, translateKnown } from '../../i18n/index.js';
import {
AIM_AT_GROUND_MESSAGE,
keyStatusLabel,
NEAREST_RADIUS_M,
NEAREST_RADIUS_MAX_M,
POSITION_PICK_ID,
STREET_LEVEL_LAYER_ID,
} from './policy.js';
@@ -33,6 +34,11 @@ const KEY_STATUS_TIMEOUT_MS = 10_000;
/** Re-measures of a ground not loaded yet (Google 3D), a second apart. */
const GROUND_RETRY_LIMIT = 5;
const GROUND_RETRY_MS = 1000;
/**
* An armed point stays the OPEN button's target while the view centre is
* this close to it (m); a user who moved on opens what the view shows now.
*/
const ARMED_REACH_M = 1000;
/**
* The Street Level layer over imagery providers (contract in registry.js).
@@ -170,6 +176,12 @@ export function createStreetLevelLayer({
const owner = state.providers.get(state.street.providerId);
if (state.street.open && owner && !providerAvailable(owner))
layer.closeViewer();
// An armed lookup for a source whose map left dies too.
const armedFor = state.street.armed?.providerIds?.map((id) =>
state.providers.get(id),
);
if (armedFor?.some((entry) => entry && !providerAvailable(entry)))
state.street.armed = null;
for (const entry of state.providers.values()) {
if (!entry.def.requiresMapStack) continue;
if (state.enabled && entry.on && providerAvailable(entry))
@@ -254,8 +266,11 @@ export function createStreetLevelLayer({
if (providerAvailable(entry)) parts.credits.show(state.viewer, entry.def);
}
/** Sources whose open photo a replacing request keeps up while it switches them off. */
const heldViewers = new Map();
function deactivate(entry) {
parts.viewerHost.unmount(entry.def.id);
if (!heldViewers.has(entry.def.id)) parts.viewerHost.unmount(entry.def.id);
entry.instance.deactivate();
parts.credits.hide(state.viewer, entry.def);
}
@@ -268,6 +283,13 @@ export function createStreetLevelLayer({
nearestLookup = null;
}
/** Close the image and deselect its sequence on the map. */
function closeViewer() {
abortNearest();
parts.viewerHost.close();
parts.clearSequences();
}
/** Ground under the screen centre; null for sky, undefined when it cannot aim. */
function screenCentreGround() {
const canvas = state.viewer?.scene?.canvas;
@@ -288,8 +310,14 @@ export function createStreetLevelLayer({
}
/** `frame: false` keeps the camera where it is (the user picked the spot). */
function openImage(providerId, imageId, { frame = true } = {}) {
function openImage(
providerId,
imageId,
{ frame = true, signal = null } = {},
) {
if (signal?.aborted) return Promise.resolve(false);
abortNearest();
state.street.armed = null;
const entry = state.providers.get(providerId);
if (entry && !providerAvailable(entry)) {
state.street.loading = false;
@@ -297,7 +325,7 @@ export function createStreetLevelLayer({
notify();
return Promise.resolve(false);
}
return parts.viewerHost.open(providerId, imageId, { frame });
return parts.viewerHost.open(providerId, imageId, { frame, signal });
}
function unavailableReason(entry) {
@@ -343,6 +371,9 @@ export function createStreetLevelLayer({
function switchProvider(entry, on) {
if (entry.on === on) return;
entry.on = on;
// A lookup armed for this source dies with it.
if (!on && state.street.armed?.providerIds?.includes(entry.def.id))
state.street.armed = null;
if (!state.enabled) return;
if (on) activate(entry);
else deactivate(entry);
@@ -479,6 +510,33 @@ export function createStreetLevelLayer({
},
/** Registered providers, in chip order. */
providerIds: defs.map((def) => def.id),
/** The map stack a provider needs (`requiresMapStack`), or null for any. */
requiredMapStack(providerId) {
const def = defs.find((entry) => entry.id === providerId);
return def?.requiresMapStack || null;
},
/**
* A provider's name and key state on any map (the panel lists a provider
* only on the map it needs). `configured` is null until its status call
* answers; `keyRequired` covers a missing or refused key.
*/
providerStatus(providerId) {
const entry = state.providers.get(providerId);
if (!entry) return null;
const stats = entry.instance.coverageStats();
return {
id: entry.def.id,
name: entry.def.name,
on: entry.on,
configured: entry.status ? entry.status.configured === true : null,
keyRequired: stats.keyRequired === true || stats.keyRejected === true,
keyRejected: stats.keyRejected === true,
groundClick: entry.def.groundClick === true,
billed: entry.def.billedPerImage === true,
available: providerAvailable(entry),
error: stats.error || null,
};
},
getSourceAvailability() {
const available = defs.length > 0;
return {
@@ -636,19 +694,66 @@ export function createStreetLevelLayer({
* Open the nearest image of the active providers (or `providerIds`) near
* a point, else the view centre, or with `aim: 'screen-centre'` the ground
* under the screen centre (sky: nothing). Providers without
* `nearestImage` are skipped.
* `nearestImage` are skipped. Options:
* - `radiusM` widens the search where a provider can (a geocoded landmark
* is rarely within 50 m of a street);
* - `signal` retires the lookup: nothing opens after it fires;
* - `armed: false` (the assistant's own request) ignores a link's armed
* point and keeps it until a photo opens;
* - `replace: true` keeps an open photo (and EXPAND) up while it looks and
* closes it if nothing opens;
* - `proceed()` is asked before a found photo loads or an empty lookup
* reports; false retires the request and leaves the panel as it was.
* Why nothing opened is in `street.nearestOutcome`: 'empty', 'sky' or
* null (an error).
*/
async openNearest(
point,
{ providerIds = null, frame = true, aim = 'view' } = {},
{
providerIds = null,
frame = true,
aim = 'view',
radiusM = null,
signal: callerSignal = null,
armed: useArmed = true,
replace = false,
proceed = null,
} = {},
) {
if (callerSignal?.aborted) return false;
state.street.nearestOutcome = null;
// An OPEN press after a link armed a lookup opens what the link asked;
// any other lookup is a new request and drops the armed one.
const armed = useArmed ? state.street.armed : null;
if (useArmed) state.street.armed = null;
const closeReplaced = () => {
if (replace && state.street.open) closeViewer();
};
if (!point && aim === 'screen-centre' && armed) {
// OPEN promises the view centre: the link's spot only while the view
// still shows it, or when the view cannot be picked.
const centre = armed.point ? screenCentreGround() : null;
if (!armed.point) radiusM ??= armed.radiusM;
else if (
centre === undefined ||
(centre && metresBetween(centre, armed.point) <= ARMED_REACH_M)
) {
point = armed.point;
radiusM ??= armed.radiusM;
}
}
const radius = Number.isFinite(radiusM)
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
: NEAREST_RADIUS_M;
let view = point;
if (!view && aim === 'screen-centre') {
view = screenCentreGround();
if (view === null) {
abortNearest();
closeReplaced();
state.street.loading = false;
state.street.error = AIM_AT_GROUND_MESSAGE;
state.street.nearestOutcome = 'sky';
notify();
return false;
}
@@ -660,6 +765,19 @@ export function createStreetLevelLayer({
const lookup = new AbortController();
nearestLookup = lookup;
const { signal } = lookup;
const onCallerAbort = () => lookup.abort();
callerSignal?.addEventListener('abort', onCallerAbort, { once: true });
const retired = () => {
callerSignal?.removeEventListener('abort', onCallerAbort);
// A newer lookup owns the panel, its spinner and its error.
if (nearestLookup !== lookup) return false;
nearestLookup = null;
if (state.street.loading) {
state.street.loading = false;
notify();
}
return false;
};
state.street.loading = true;
state.street.error = null;
notify();
@@ -674,49 +792,108 @@ export function createStreetLevelLayer({
try {
imageId = await entry.instance.nearestImage(
{ lat: view.lat, lon: view.lon },
{ signal },
radius === NEAREST_RADIUS_M
? { signal }
: { signal, radiusM: radius },
);
} catch (error) {
if (callerSignal?.aborted) return retired();
// Overtaken: whatever replaced it owns the panel, errors included.
if (signal.aborted) return false;
if (signal.aborted) return retired();
// One provider failing (no key, offline) must not hide the others.
lastError = error;
continue;
}
if (signal.aborted) return false;
if (callerSignal?.aborted) return retired();
if (signal.aborted) return retired();
if (!state.enabled) break;
// Switched off, or its map left, while it looked: try the next.
if (!imageId || !entry.on || !providerAvailable(entry)) continue;
if (proceed && proceed() !== true) return retired();
nearestLookup = null;
return openImage(entry.def.id, imageId, { frame });
callerSignal?.removeEventListener('abort', onCallerAbort);
// A sequence playing in the replaced photo would step past this one.
if (replace && state.street.open) parts.viewerHost.stopPlayback();
// The caller's signal still counts while the viewer mounts and loads.
return openImage(entry.def.id, imageId, {
frame,
signal: callerSignal,
});
}
if (nearestLookup === lookup) nearestLookup = null;
callerSignal?.removeEventListener('abort', onCallerAbort);
// Replaced while it looked: the panel is the newer lookup's.
if (nearestLookup !== lookup) return false;
// Given up by its caller: the panel stays as it was.
if (proceed && proceed() !== true) return retired();
nearestLookup = null;
closeReplaced();
// Switched off while it looked: nothing to open, nothing to report.
const stillOn = entries.some(
(entry) => entry.on && providerAvailable(entry),
);
// A provider's own refusal is English data that the panel translates;
// the core's refusal is built here, for the panel only, in the language.
if (state.enabled && stillOn && !lastError)
state.street.nearestOutcome = 'empty';
if (state.enabled && stillOn)
state.street.error =
lastError?.message ||
(point
? t('No street-level imagery within {radius} m of that point', {
radius: NEAREST_RADIUS_M,
radius,
})
: t(
'No street-level imagery within {radius} m of the view centre',
{ radius: NEAREST_RADIUS_M },
{
radius,
},
));
state.street.loading = false;
notify();
return false;
},
/** Close the image and deselect its sequence on the map. */
closeViewer() {
abortNearest();
parts.viewerHost.close();
parts.clearSequences();
closeViewer,
/**
* Keep the open photo up while a request that replaces it switches its
* source off, so EXPAND stays; only that source's own switch-off is held,
* a source switched by hand meanwhile still stops a load. Release frees
* the old viewer.
*/
holdViewer() {
const id = state.street.open ? state.street.providerId : null;
if (!id) return () => {};
heldViewers.set(id, (heldViewers.get(id) || 0) + 1);
let held = true;
return () => {
if (!held) return;
held = false;
const left = heldViewers.get(id) - 1;
if (left > 0) return void heldViewers.set(id, left);
heldViewers.delete(id);
if (state.providers.get(id)?.on !== false) return;
// Its photo still up (the request gave up) closes with its source;
// otherwise the request replaced or closed it, and the panel keeps
// what that request left (an error, an armed OPEN).
if (state.street.open && state.street.providerId === id)
parts.viewerHost.unmount(id);
else parts.viewerHost.release(id);
};
},
/**
* Arm a nearest lookup for the next OPEN press without running it (a link
* to a source that bills every load). Any other lookup, open or close, the
* source switched off or its map leaving clears it.
*/
armNearest(point, { providerIds = null, radiusM = null } = {}) {
state.street.armed = {
point:
Number.isFinite(point?.lat) && Number.isFinite(point?.lon)
? { lat: point.lat, lon: point.lon }
: null,
providerIds: Array.isArray(providerIds) ? [...providerIds] : null,
radiusM: Number.isFinite(radiusM) ? radiusM : null,
};
notify();
},
setViewerRenderMode: (mode) => parts.viewerHost.setRenderMode(mode),
resizeViewer: () => parts.viewerHost.resize(),
+950 -2
View File
@@ -1,5 +1,6 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { getEventListeners } from 'node:events';
import * as Cesium from 'cesium';
import { createStreetLevelLayer } from './index.js';
import { MAPILLARY_CREDIT_HTML } from './providers/mapillary/policy.js';
@@ -12,6 +13,9 @@ import {
fakeStreetLevelProvider as fakeProvider,
} from '../../testSupport/streetLevelFakes.mjs';
import { setLocale } from '../../i18n/index.js';
// Loaded up front: it brings Vue, which reads `document` once when it loads,
// and several tests here stand a bare fake document in for the page.
import { createGevActionRunner } from '../../voice/gevActions.js';
/**
* A layer over `source` and `photoViewer`, initialised on a stand-in viewer
@@ -362,7 +366,11 @@ function fakeViewer() {
}
/** A layer over `providers`, initialised and enabled on a stand-in viewer. */
async function enabledLayer(t, providers = [fakeProvider()]) {
async function enabledLayer(
t,
providers = [fakeProvider()],
{ services, setup } = {},
) {
const saved = globalThis.document;
// A pose moves the position marker, whose glyph is drawn on a canvas.
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
@@ -370,7 +378,11 @@ async function enabledLayer(t, providers = [fakeProvider()]) {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const layer = createStreetLevelLayer({ providers });
setup?.(viewer);
const layer = createStreetLevelLayer({
providers,
...(services ? { services } : {}),
});
layer.init(viewer);
layer.enable(viewer);
t.after(() => {
@@ -944,6 +956,54 @@ test('the button’s “centre of the view” is the ground under the middle of
assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
});
test('OPEN after a link armed opens at its point only while the view centre is still near it', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ point, radiusM: options?.radiusM ?? null });
return null;
},
});
const saved = globalThis.document;
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
globalThis.document = Object.assign(new EventTarget(), {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
const layer = create({ providers: [provider], services: { scenePick } });
layer.init(viewer);
layer.enable(viewer);
t.after(() => {
layer.destroy();
globalThis.document = saved;
});
// About 120 m from the view centre: the link's spot is still in view.
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre' });
assert.deepEqual(lookups.at(-1), {
point: { lat: 38.5808, lon: -121.494 },
radiusM: 250,
});
// The user flew to Paris after the link armed in Sacramento: OPEN looks
// under the view centre, and the link's radius goes with its point.
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre' });
const press = lookups.at(-1);
assert.ok(Math.abs(press.point.lat - 38.5799) < 1e-9, 'the view centre');
assert.ok(Math.abs(press.point.lon - -121.4937) < 1e-9);
assert.equal(press.radiusM, null, 'the default radius');
assert.equal(layer.getUIState().street.armed, null, 'dropped');
});
test('the button aimed at the sky opens nothing, and says to aim at a street', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
@@ -1118,6 +1178,732 @@ test('switching source by params clears a failed lookup’s error; reapplying th
assert.equal(second.getUIState().street.error, kept);
});
test('openNearest searches wider on request, never past the cap, and says how far it looked', async (t) => {
const { layer, fake } = await withStreetView(t, { nearest: () => null });
layer.setProviderEnabled('google', true);
await settle();
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, radiusM: 250 },
);
assert.equal(fake.lookups.at(-1).radius, 250);
assert.equal(
layer.getUIState().street.error,
'No street-level imagery within 250 m of that point',
);
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, radiusM: 5000 },
);
assert.equal(fake.lookups.at(-1).radius, 250, 'capped');
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false },
);
assert.equal(fake.lookups.at(-1).radius, 50, 'a click keeps the default');
});
test('a caller’s signal retires a nearest lookup: nothing opens after it fires', async (t) => {
let answer = null;
const { layer, fake } = await withStreetView(t, {
nearest: () => 'pano-a',
});
const lib = fake.library;
const service = lib.StreetViewService.prototype.getPanorama;
lib.StreetViewService.prototype.getPanorama = function (request) {
return new Promise((resolve, reject) => {
answer = () => service.call(this, request).then(resolve, reject);
});
};
layer.setProviderEnabled('google', true);
await settle();
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: controller.signal },
);
await settle();
controller.abort();
answer?.();
assert.equal(await pending, false);
const street = layer.getUIState().street;
assert.equal(street.open, false, 'the retired lookup opened nothing');
assert.equal(street.loading, false, 'no stuck spinner');
assert.equal(street.error, null, 'and reports no missing imagery');
const refused = await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: controller.signal },
);
assert.equal(refused, false, 'an already-aborted signal asks nothing');
});
test('providerStatus reports name, key state and billing on any map', async (t) => {
const { layer } = await withStreetView(t, { mapStack: 'osm' });
const google = layer.providerStatus('google');
assert.equal(google.name, 'Google Street View');
assert.equal(google.billed, true, 'every Street View load is billed');
assert.equal(google.available, false, 'not on this map');
assert.equal(google.keyRequired, false);
assert.equal(layer.providerStatus('mapillary').billed, false);
assert.equal(layer.providerStatus('nope'), null);
assert.equal(layer.requiredMapStack('google'), 'photoreal');
assert.equal(layer.requiredMapStack('mapillary'), null);
});
test('an armed lookup asks nothing until the OPEN press, then opens at its point and radius once', async (t) => {
const { layer, fake, mapillaryLookups } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
const before = fake.lookups.length;
layer.armNearest(
{ lat: 38.57986, lon: -121.49372 },
{ providerIds: ['google'], radiusM: 250 },
);
await settle();
await new Promise((resolve) => setTimeout(resolve, 20));
// The click gate: arming is free. No provider was asked, nothing opened.
assert.equal(
fake.lookups.length,
before,
'no Google lookup before the press',
);
assert.deepEqual(mapillaryLookups, [], 'no Mapillary lookup either');
assert.equal(layer.getUIState().street.open, false);
assert.equal(layer.getUIState().street.loading, false);
assert.deepEqual(layer.getUIState().street.armed, {
point: { lat: 38.57986, lon: -121.49372 },
providerIds: ['google'],
radiusM: 250,
});
// The OPEN button: no point, aimed at the screen centre.
const opened = await layer.openNearest(undefined, {
providerIds: ['google'],
frame: false,
aim: 'screen-centre',
});
assert.equal(opened, true);
assert.equal(
fake.lookups.length,
before + 1,
'exactly one lookup for the press',
);
const request = fake.lookups.at(-1);
assert.deepEqual(
request.location,
{ lat: 38.57986, lng: -121.49372 },
'the armed point, not the screen centre',
);
assert.equal(request.radius, 250);
assert.equal(layer.getUIState().street.armed, null, 'used once');
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
layer.closeViewer();
assert.equal(layer.getUIState().street.armed, null, 'closing clears it');
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false },
);
assert.deepEqual(
fake.lookups.at(-1).location,
{ lat: 38.58, lng: -121.49 },
'an explicit point wins',
);
assert.equal(layer.getUIState().street.armed, null);
// Only the OPEN press consumes the armed point: "street view here" after a
// pan is a new request at the view centre, and it drops the armed one.
layer.closeViewer();
layer.armNearest(
{ lat: 10, lon: 20 },
{ providerIds: ['google'], radiusM: 250 },
);
await layer.openNearest(null, { providerIds: ['google'], frame: false });
const centre = fake.lookups.at(-1);
assert.notDeepEqual(
centre.location,
{ lat: 10, lng: 20 },
'the view centre, not the armed point',
);
assert.equal(centre.radius, 50, 'and the default radius');
assert.equal(layer.getUIState().street.armed, null, 'dropped');
// Opening any image, or switching the layer off, clears it too.
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
await layer.openImage('google', 'pano-a');
assert.equal(layer.getUIState().street.armed, null, 'cleared by an open');
layer.armNearest({ lat: 10, lon: 20 }, { providerIds: ['google'] });
layer.disable();
assert.equal(layer.getUIState().street.armed, null, 'cleared by disable');
});
test('a caller’s signal: an aborted one asks nothing, and a provider that ignores the abort still opens nothing', async (t) => {
const { layer, fake } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
const before = fake.lookups.length;
const done = new AbortController();
done.abort();
assert.equal(
await layer.openNearest(
{ lat: 38.58, lon: -121.49 },
{ providerIds: ['google'], frame: false, signal: done.signal },
),
false,
);
assert.equal(
fake.lookups.length,
before,
'an already-aborted signal asks nothing',
);
});
test('a provider that ignores the abort and answers late still opens nothing', async (t) => {
let seen = null;
let release = null;
const slow = fakeProvider({
nearestImage: async (_point, { signal } = {}) => {
seen = signal;
await new Promise((resolve) => {
release = resolve;
});
return 'late-image';
},
});
const { layer: ignoring } = await enabledLayer(t, [slow]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
ignoring.attachViewerHost(fakeHost());
const controller = new AbortController();
const pending = ignoring.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
await settle();
controller.abort();
assert.equal(seen?.aborted, true, 'the provider sees the abort');
release();
assert.equal(await pending, false);
const street = ignoring.getUIState().street;
assert.equal(street.open, false, 'the late answer opened nothing');
assert.equal(street.loading, false, 'no stuck spinner');
assert.equal(street.error, null);
});
test('providerStatus reports a keyless source on any map', async (t) => {
const keyless = await withStreetView(t, {
mapStack: 'osm',
mapillaryKeyless: true,
});
await settle();
const mapillary = keyless.layer.providerStatus('mapillary');
assert.equal(mapillary.configured, false);
assert.equal(mapillary.keyRequired, true);
assert.equal(mapillary.keyRejected, false);
});
test('providerStatus reports the key state as unknown until the status call answers', async (t) => {
// A freshly loaded sl= link meets its source in this state: unknown is not
// "needs its key", or the link would fail on a cold load.
const pending = fakeProvider();
pending.requiresKeyId = 'mapillary';
const create = pending.create;
pending.create = (context) => ({
...create(context),
status: () => new Promise(() => {}),
});
const { layer } = await enabledLayer(t, [pending]);
const status = layer.providerStatus(pending.id);
assert.equal(status.configured, null);
assert.equal(status.keyRequired, false);
});
test('providerStatus reports a refused key on any map', async (t) => {
const refused = await withStreetView(t, { mapStack: 'osm' });
refused.loader.refuseKey();
await settle();
const google = refused.layer.providerStatus('google');
assert.equal(
google.keyRequired,
true,
'a refused key gates like a missing one',
);
assert.equal(google.keyRejected, true);
assert.equal(google.available, false, 'still not on this map');
});
test('an armed lookup dies with its source: switched off, or its map gone', async (t) => {
const { layer, stack } = await withStreetView(t);
layer.setProviderEnabled('google', true);
await settle();
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
layer.setProviderEnabled('google', false);
assert.equal(
layer.getUIState().street.armed,
null,
'switching the source off clears it',
);
layer.setProviderEnabled('google', true);
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
// Lighting Mapillary instead (one source at a time) turns Google off too.
layer.setProviderEnabled('mapillary', true);
assert.equal(
layer.getUIState().street.armed,
null,
'another source lit clears it',
);
layer.setProviderEnabled('google', true);
layer.armNearest(
{ lat: 1, lon: 2 },
{ providerIds: ['google'], radiusM: 250 },
);
// A map-stack notify that keeps Google 3D (a silent re-settle) keeps it.
stack.switchTo('photoreal');
assert.notEqual(
layer.getUIState().street.armed,
null,
'a notify on the same map keeps it',
);
stack.switchTo('osm');
assert.equal(
layer.getUIState().street.armed,
null,
'leaving Google 3D clears it',
);
// Arming notifies, so a panel can show the state.
let notified = 0;
const unsubscribe = layer.subscribe(() => notified++);
stack.switchTo('photoreal');
await settle();
const before = notified;
layer.armNearest({ lat: 1, lon: 2 }, { providerIds: ['google'] });
await settle();
assert.ok(notified > before, 'subscribers hear about the armed lookup');
unsubscribe();
});
test('a lookup armed with no point opens under the middle of the screen on the press', async (t) => {
const { createStreetLevelLayer: create } = await import('./index.js');
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ ...point, radiusM: options?.radiusM ?? null });
return null;
},
});
const saved = globalThis.document;
const drawing = new Proxy({}, { get: () => () => ({ addColorStop() {} }) });
globalThis.document = Object.assign(new EventTarget(), {
createElement: () => ({ getContext: () => drawing }),
});
const viewer = fakeViewer();
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) => (at.x === 500 && at.y === 300 ? centre : undefined),
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
// Registered before the layer exists, so a throwing create() still
// restores the document; destroy() runs first, while the stub is in place.
let layer = null;
t.after(() => {
layer?.destroy();
globalThis.document = saved;
});
layer = create({ providers: [provider], services: { scenePick } });
layer.init(viewer);
layer.enable(viewer);
layer.armNearest(null, { providerIds: [provider.id], radiusM: 250 });
assert.equal(
layer.getUIState().street.armed.point,
null,
'no point stored, not 0,0',
);
await layer.openNearest(undefined, { aim: 'screen-centre' });
assert.equal(lookups.length, 1);
assert.ok(
Math.abs(lookups[0].lat - 38.5799) < 1e-9,
'the screen centre, not Null Island',
);
assert.ok(Math.abs(lookups[0].lon - -121.4937) < 1e-9);
assert.equal(lookups[0].radiusM, 250, 'with the armed radius');
});
test('the action over the real layer: a billed link arms without a lookup, and one press makes exactly one at the point', async (t) => {
const { layer, fake, viewer } = await withStreetView(t);
// The runner wires pointer tracking to the clock and camera.
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'photoreal' },
setMapStack: async () => ({ ok: true, activeStack: 'photoreal' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
const before = fake.lookups.length;
const armed = await runner('show_street_level', {
latitude: 38.57986,
longitude: -121.49372,
provider: 'google',
fly: false,
autoOpen: false,
});
assert.equal(armed.ok, true, armed.error);
assert.equal(armed.armed, true);
assert.equal(armed.providerName, 'Google Street View');
await settle();
assert.equal(fake.lookups.length, before, 'arming made no Google request');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['google'],
);
assert.equal(layer.getUIState().street.open, false);
// The OPEN button.
assert.equal(
await layer.openNearest(undefined, {
providerIds: ['google'],
frame: false,
aim: 'screen-centre',
}),
true,
);
assert.equal(fake.lookups.length, before + 1, 'one request for the press');
assert.deepEqual(fake.lookups.at(-1).location, {
lat: 38.57986,
lng: -121.49372,
});
assert.equal(fake.lookups.at(-1).radius, 250);
assert.equal(layer.getUIState().street.imageId, 'pano-a');
// The same call without the gate opens at once, with one request.
layer.closeViewer();
const opened = await runner('show_street_level', {
latitude: 38.57986,
longitude: -121.49372,
provider: 'google',
fly: false,
});
assert.equal(opened.ok, true, opened.error);
assert.equal(opened.imageId, 'pano-a');
assert.equal(fake.lookups.length, before + 2);
});
test('openNearest keeps honouring the caller after the lookup: an abort while the viewer loads opens nothing', async (t) => {
let releaseMount = null;
const provider = fakeProvider({ nearestImage: async () => 'img-1' });
const create = provider.create;
provider.create = (context) => {
const instance = create(context);
const mount = instance.viewer.mount;
instance.viewer.mount = async (...args) => {
await new Promise((resolve) => {
releaseMount = resolve;
});
return mount(...args);
};
return instance;
};
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
for (let i = 0; i < 20 && !releaseMount; i++) await settle();
assert.ok(releaseMount, 'the lookup answered and the viewer is mounting');
controller.abort();
releaseMount();
assert.equal(await pending, false);
assert.deepEqual(provider.calls.open, [], 'the photo was never opened');
assert.equal(layer.getUIState().street.open, false);
assert.equal(layer.getUIState().street.loading, false);
});
for (const rejectsOnAbort of [true, false]) {
test(`cancelling a lookup over an open photo clears its spinner (provider rejects: ${rejectsOnAbort})`, async (t) => {
const answer = deferred();
const provider = fakeProvider({
nearestImage: (_point, { signal }) => {
if (rejectsOnAbort)
signal.addEventListener('abort', () => answer.reject(signal.reason), {
once: true,
});
return answer.promise;
},
});
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
assert.equal(
await layer.openImage('mapillary', 'existing', { frame: false }),
true,
);
const controller = new AbortController();
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: controller.signal },
);
assert.equal(layer.getUIState().street.loading, true);
controller.abort();
if (!rejectsOnAbort) answer.resolve('late-image');
assert.equal(await pending, false);
const street = layer.getUIState().street;
assert.equal(
street.loading,
false,
'the cancelled lookup owns and clears the spinner',
);
assert.equal(street.open, true, 'the existing photo remains open');
assert.equal(street.error, null);
assert.deepEqual(
provider.calls.open,
['existing'],
'no replacement photo opens',
);
});
}
for (const rejectsOnAbort of [true, false]) {
test(`retired lookups release the caller listener (provider rejects: ${rejectsOnAbort})`, async (t) => {
let answer;
const provider = fakeProvider({
nearestImage: (_point, { signal }) => {
answer = deferred();
if (rejectsOnAbort)
signal.addEventListener('abort', () => answer.reject(signal.reason), {
once: true,
});
return answer.promise;
},
});
const { layer } = await enabledLayer(t, [provider]);
const lifetime = new AbortController();
for (let i = 0; i < 3; i++) {
const pending = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: lifetime.signal },
);
assert.equal(getEventListeners(lifetime.signal, 'abort').length, 1);
layer.closeViewer();
if (!rejectsOnAbort) answer.resolve('late-image');
assert.equal(await pending, false);
assert.equal(
getEventListeners(lifetime.signal, 'abort').length,
0,
'closing the lookup releases its listener on the application lifetime',
);
}
assert.equal(lifetime.signal.aborted, false);
});
}
test('an aborted older lookup leaves its replacement’s spinner alone', async (t) => {
const answers = [];
const provider = fakeProvider({
nearestImage: (_point, { signal } = {}) =>
new Promise((resolve, reject) => {
answers.push(resolve);
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
);
}),
});
const { layer } = await enabledLayer(t, [provider]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
const older = new AbortController();
const first = layer.openNearest(
{ lat: 1, lon: 2 },
{ frame: false, signal: older.signal },
);
await settle();
// A newer request replaces it, and its caller withdraws the old one too.
const second = layer.openNearest({ lat: 3, lon: 4 }, { frame: false });
older.abort();
assert.equal(await first, false);
assert.equal(
layer.getUIState().street.loading,
true,
'the newer lookup is still loading',
);
answers.at(-1)(null);
assert.equal(await second, false);
assert.equal(layer.getUIState().street.loading, false);
assert.match(
layer.getUIState().street.error,
/No street-level imagery/,
'the newer lookup reports its own result',
);
});
test('show_street_level opens a KartaView photo, and a plain link opens it at once since it is not billed', async (t) => {
const mapillary = fakeProvider();
let nearest = 'kv-1';
const kartaview = fakeProvider({
id: 'kartaview',
pickPrefix: 'kv:',
nearestImage: async () => nearest,
});
kartaview.name = 'KartaView';
kartaview.label = 'KARTAVIEW';
kartaview.defaultOn = false;
// As the real provider: 360° / flat and SINCE (the setFilter log stays in
// the fake's closure).
kartaview.filters = Object.freeze(['pano', 'since']);
const { layer, viewer } = await enabledLayer(t, [mapillary, kartaview]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'osm' },
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
// The way a plain sl=kartaview link calls it: autoOpen false.
const result = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
autoOpen: false,
});
assert.equal(result.ok, true, result.error);
assert.equal(result.armed, undefined, 'not armed: KartaView bills nothing');
assert.equal(result.provider, 'kartaview');
assert.equal(result.providerName, 'KartaView');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['kartaview'],
);
assert.deepEqual(kartaview.calls.open, ['kv-1']);
assert.equal(layer.providerStatus('kartaview').billed, false);
assert.equal(layer.requiredMapStack('kartaview'), null);
// With 360° only on, an empty search names the filter, not just "no imagery".
layer.closeViewer?.();
layer.setParams({ pano: 'pano' });
nearest = null;
const empty = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
});
assert.deepEqual([empty.ok, empty.stage], [false, 'imagery']);
assert.equal(empty.filter?.pano, 'pano');
assert.match(empty.error, /with the 360° filter on$/);
layer.setParams({ pano: 'all' });
const plain = await runner('show_street_level', {
latitude: 52.52,
longitude: 13.405,
provider: 'kartaview',
fly: false,
});
assert.equal(plain.ok, false);
assert.equal(plain.filter, undefined, 'no filter, no hint');
assert.doesNotMatch(plain.error, /filter/);
});
test('show_street_level switches from KartaView to Panoramax and opens its photo at once, unbilled', async (t) => {
const mapillary = fakeProvider();
const kartaview = fakeProvider({ id: 'kartaview', pickPrefix: 'kv:' });
kartaview.name = 'KartaView';
kartaview.defaultOn = false;
const panoramax = fakeProvider({
id: 'panoramax',
pickPrefix: 'px:',
nearestImage: async () => 'px-1',
});
panoramax.name = 'Panoramax';
panoramax.label = 'PANORAMAX';
panoramax.defaultOn = false;
const { layer, viewer } = await enabledLayer(t, [
mapillary,
kartaview,
panoramax,
]);
const { fakeHost } =
await import('../../testSupport/googleStreetViewFakes.mjs');
layer.attachViewerHost(fakeHost());
viewer.clock ??= { onTick: { addEventListener: () => () => {} } };
viewer.camera.moveEnd ??= { addEventListener() {} };
layer.setParams({ mapillary: false, kartaview: true, panoramax: false });
const dataManager = {
layers: new Map([['street-level', { module: layer }]]),
isEnabled: () => true,
getLayerParams: () => layer.getParams(),
setLayerParams: (_id, params) => {
layer.setParams(params);
return true;
},
getAll: () => [{ id: 'street-level', name: 'Street Level', enabled: true }],
};
const styleManager = {
mapStackController: { getActiveId: () => 'osm' },
setMapStack: async () => ({ ok: false, error: 'no map switch expected' }),
};
const runner = createGevActionRunner({ viewer, styleManager, dataManager });
// The way a plain sl=panoramax link calls it: autoOpen false.
const result = await runner('show_street_level', {
latitude: 48.8874,
longitude: 2.3495,
provider: 'panoramax',
fly: false,
autoOpen: false,
});
assert.equal(result.ok, true, result.error);
assert.equal(result.armed, undefined, 'not armed: Panoramax bills nothing');
assert.equal(result.providerName, 'Panoramax');
assert.deepEqual(
layer
.getUIState()
.providers.filter((p) => p.on)
.map((p) => p.id),
['panoramax'],
'KartaView switched off',
);
assert.deepEqual(panoramax.calls.open, ['px-1']);
assert.deepEqual(kartaview.calls.open, [], 'nothing asked of KartaView');
assert.equal(layer.providerStatus('panoramax').billed, false);
assert.equal(layer.requiredMapStack('panoramax'), null);
});
test('the panel says why a lit Street View draws nothing off Google 3D', async (t) => {
const { presentStreetLevelPanel } =
await import('../../ui/streetLevelPresentation.js');
@@ -1128,6 +1914,88 @@ test('the panel says why a lit Street View draws nothing off Google 3D', async (
assert.match(view.meta, /Google Street View needs the Google 3D map/);
});
test('OPEN aimed at the sky after a link armed opens nothing: never the far link point', async (t) => {
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point) => {
lookups.push(point);
return null;
},
});
const { layer } = await enabledLayer(t, [provider], {
services: { scenePick },
setup: (viewer) => {
// Every pick misses the ground: the screen centre is sky.
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: () => undefined,
});
viewer.globe = { pick: () => undefined };
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
},
});
layer.armNearest({ lat: 48.8584, lon: 2.2945 }, { radiusM: 250 });
assert.equal(
await layer.openNearest(undefined, { aim: 'screen-centre' }),
false,
);
assert.deepEqual(lookups, [], 'no paid Paris lookup from another city’s sky');
const street = layer.getUIState().street;
assert.equal(street.nearestOutcome, 'sky');
assert.match(street.error, /Aim the middle of the view/);
});
test('a request of its own (armed: false) neither uses nor drops the link’s armed point', async (t) => {
const scenePick = await import('../../data/scenePick.js');
const lookups = [];
const provider = fakeProvider({
nearestImage: async (point, options) => {
lookups.push({ point, radiusM: options?.radiusM ?? null });
return null;
},
});
const centre = Cesium.Cartesian3.fromDegrees(-121.4937, 38.5799, 0);
const { layer } = await enabledLayer(t, [provider], {
services: { scenePick },
setup: (viewer) => {
Object.assign(viewer.scene, {
pickPositionSupported: true,
pickPosition: (at) =>
at.x === 500 && at.y === 300 ? centre : undefined,
});
viewer.scene.canvas.clientWidth = 1000;
viewer.scene.canvas.clientHeight = 600;
},
});
// About 120 m away: an OPEN press would take the link's spot.
layer.armNearest({ lat: 38.5808, lon: -121.494 }, { radiusM: 250 });
await layer.openNearest(undefined, { aim: 'screen-centre', armed: false });
const asked = lookups.at(-1);
assert.ok(Math.abs(asked.point.lat - 38.5799) < 1e-9, 'the screen centre');
assert.equal(asked.radiusM, null, 'its own radius');
assert.equal(layer.getUIState().street.nearestOutcome, 'empty');
assert.deepEqual(
layer.getUIState().street.armed?.point,
{ lat: 38.5808, lon: -121.494 },
'still armed for the OPEN press',
);
});
test('a failing source is not reported as missing imagery', async (t) => {
const provider = fakeProvider({
nearestImage: async () => {
throw new Error('Mapillary graph HTTP 500');
},
});
const { layer } = await enabledLayer(t, [provider]);
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), false);
const street = layer.getUIState().street;
assert.equal(street.nearestOutcome, null);
assert.equal(street.error, 'Mapillary graph HTTP 500');
});
/** Mapillary (keyless unless `mapillary` says otherwise) plus KartaView. */
function keylessLayer(t, mapillary = { hasToken: () => false }) {
const layer = createStreetLevelLayer({
@@ -1183,3 +2051,83 @@ test('filter-only updates keep the lit source, even a chosen keyless Mapillary',
);
}
});
test('a replacing lookup keeps the viewer open while it looks, so EXPAND stays with the new photo', async (t) => {
const answers = ['img-1', 'img-2'];
const provider = posingProvider({
nearestImage: async () => answers.shift(),
});
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
assert.equal(await layer.openNearest({ lat: 1, lon: 2 }), true);
const seen = [];
const unsubscribe = layer.subscribe(() =>
seen.push(layer.getUIState().street.open),
);
t.after(unsubscribe);
assert.equal(
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
true,
);
assert.ok(seen.length > 0);
assert.ok(!seen.includes(false), 'never published closed on the way');
assert.deepEqual(provider.calls.open, ['img-1', 'img-2']);
});
test('a replacing lookup that finds nothing closes the old photo and keeps its own message', async (t) => {
const answers = ['img-1', null];
const provider = posingProvider({
nearestImage: async () => answers.shift(),
});
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
await layer.openNearest({ lat: 1, lon: 2 });
assert.equal(
await layer.openNearest({ lat: 3, lon: 4 }, { replace: true }),
false,
);
const street = layer.getUIState().street;
assert.equal(street.open, false, 'no photo of another place');
assert.equal(street.nearestOutcome, 'empty');
assert.match(street.error, /No street-level imagery within 50 m/);
});
test('a found photo the viewer cannot load keeps its error on the open viewer', async (t) => {
const provider = posingProvider({ nearestImage: async () => 'img-1' });
const create = provider.create;
provider.create = (context) => {
const instance = create(context);
instance.viewer.open = async () => {
throw new Error('Image could not be opened');
};
return instance;
};
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
assert.equal(
await layer.openNearest({ lat: 1, lon: 2 }, { replace: true }),
false,
);
const street = layer.getUIState().street;
assert.equal(street.open, true);
assert.equal(street.error, 'Image could not be opened');
});
test('proceed() is asked after the lookup: false loads nothing and clears the spinner', async (t) => {
const provider = posingProvider({ nearestImage: async () => 'img-1' });
const { layer } = await enabledLayer(t, [provider]);
layer.attachViewerHost({});
let asked = 0;
const opened = await layer.openNearest(
{ lat: 1, lon: 2 },
{ proceed: () => (asked++, false) },
);
assert.equal(opened, false);
assert.equal(asked, 1);
assert.deepEqual(provider.calls.open, [], 'the viewer never loads it');
assert.equal(layer.getUIState().street.loading, false);
assert.equal(
await layer.openNearest({ lat: 1, lon: 2 }, { proceed: () => true }),
true,
);
});
+8
View File
@@ -40,6 +40,14 @@ export const FILTER_DEFAULT = Object.freeze({ pano: 'all', sinceDays: 0 });
/** Nearest-image search radius in metres. */
export const NEAREST_RADIUS_M = 50;
/**
* Widest nearest-image radius a caller may ask for, in metres. A geocoded
* landmark sits at its centroid, often further than 50 m from the nearest
* street; providers that can search wider (Google) honour it, the rest keep
* their own cap.
*/
export const NEAREST_RADIUS_MAX_M = 250;
/** The Google 3D map stack: Street View may be shown only on it. */
export const GOOGLE_3D_MAP_STACK_ID = 'photoreal';
@@ -12,6 +12,7 @@ import {
GROUND_CLICK_HINT,
KEY_REJECTED_MESSAGE,
NEAREST_RADIUS_M,
NEAREST_RADIUS_MAX_M,
NEAREST_TIMEOUT_MS,
NO_ANSWER_MESSAGE,
PICK_PREFIX,
@@ -67,6 +68,7 @@ export function createGoogleProvider({
requiresMapStack: GOOGLE_3D_MAP_STACK_ID,
// Every panorama is billed to the Maps key.
defaultOn: false,
billedPerImage: true,
// All 360°, and no coverage for a date filter to thin.
filters: [],
marker: Object.freeze({ kind: 'view-cone', color: COLORS.coverage }),
@@ -136,8 +138,12 @@ export function createGoogleProvider({
* Nearest Google-collected outdoor panorama, or null. The imagery
* filters do not apply (see `filters`).
*/
async nearestImage({ lat, lon }, { signal } = {}) {
async nearestImage({ lat, lon }, { signal, radiusM } = {}) {
if (loader.authFailed()) throw new Error(KEY_REJECTED_MESSAGE);
// Wider than the shared default only on request, never past the cap.
const radius = Number.isFinite(radiusM)
? Math.min(NEAREST_RADIUS_MAX_M, Math.max(1, radiusM))
: NEAREST_RADIUS_M;
signal?.throwIfAborted();
// Set once the caller has its answer (aborted, timed out, refused):
// a lookup still waiting on Google's script then asks nothing.
@@ -150,7 +156,7 @@ export function createGoogleProvider({
try {
const { data } = await service.getPanorama({
location: { lat, lng: lon },
radius: NEAREST_RADIUS_M,
radius,
// Both: Google's own imagery, outdoors (sources intersect).
sources: [GOOGLE, OUTDOOR],
preference: lib.StreetViewPreference.NEAREST,
@@ -1,7 +1,7 @@
import { COLORS as SHARED_COLORS, PROVIDER_COLORS } from '../../policy.js';
import { msg } from '../../../../i18n/index.js';
export { NEAREST_RADIUS_M } from '../../policy.js';
export { NEAREST_RADIUS_M, NEAREST_RADIUS_MAX_M } from '../../policy.js';
export const GOOGLE_PROVIDER_ID = 'google';
export const GOOGLE_NAME = msg('Google Street View');
@@ -291,3 +291,13 @@ test('the panorama a lookup found is dated without a second lookup', async () =>
'no getPanorama({pano}) for a panorama the lookup already described',
);
});
test('a wider lookup radius is honoured up to the cap', async () => {
const { instance, fake } = setup();
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 250 });
assert.equal(fake.lookups.at(-1).radius, 250);
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: 9999 });
assert.equal(fake.lookups.at(-1).radius, 250);
await instance.nearestImage({ lat: 38.58, lon: -121.49 }, { radiusM: NaN });
assert.equal(fake.lookups.at(-1).radius, 50);
});
@@ -5,6 +5,8 @@ import {
} from '../../lineCoverage.js';
import { createSequenceCones, thinImages } from '../../sequenceCones.js';
import { coverageZoomForHeight } from '../../tileMath.js';
import { passesImageryFilter } from '../../filter.js';
import { metresBetween } from '../../view.js';
import { decodeCoverageTile } from './decode.js';
import { createMapillaryViewer } from './viewer.js';
import {
@@ -195,6 +197,35 @@ export function createMapillaryProvider({ source, photoViewer = null }) {
error: state.sequence.error,
}),
/**
* The nearest image that passes the imagery filter, or null: what
* show_street_level and sl= links open (clicks open a line, then a
* cone). The core aborts `signal` once a newer request overtakes it.
*/
async nearestImage({ lat, lon }, { signal } = {}) {
const images = await source.nearestImages({ lat, lon }, { signal });
// The API returns the images in the radius in no particular order.
const metres = (record) => {
const [lon2, lat2] = (record.computed_geometry || record.geometry)
?.coordinates || [NaN, NaN];
const d = metresBetween({ lon, lat }, { lon: lon2, lat: lat2 });
return Number.isFinite(d) ? d : Infinity;
};
const filter = context.getFilter();
const hit = [...images]
.sort((a, b) => metres(a) - metres(b))
.find((record) =>
passesImageryFilter(
{
isPano: record.is_pano === true,
capturedAt: Number(record.captured_at) || 0,
},
filter,
),
);
return hit ? String(hit.id) : null;
},
viewer:
photoViewer ||
createMapillaryViewer({ source, render: context.services?.render }),
@@ -16,6 +16,7 @@ export const MAPILLARY_SOURCE_METHODS = Object.freeze([
'getStatus',
'getTile',
'getSequenceImages',
'nearestImages',
]);
/** Stable id prefixes for picked primitives; every one starts with `mly:`. */
@@ -72,3 +73,18 @@ export function mapillaryImageUrl(imageId) {
/** Fields requested for a sequence's images. */
export const SEQUENCE_IMAGE_FIELDS =
'id,captured_at,compass_angle,geometry,is_pano';
/**
* Images asked for in a nearest-image search: the API cuts at the limit
* before any order, so this is its most; the distance sort and the imagery
* filter choose among the photos this one request returns.
*/
export const NEAREST_LIMIT = 100;
/**
* A nearest-image search not answered in full (body included) by then is
* given up: a link or posted view, and every view queued behind it, waits.
*/
export const NEAREST_TIMEOUT_MS = 12_000;
/** Fields a nearest-image search needs: where each is, and the filter's. */
export const NEAREST_IMAGE_FIELDS =
'id,captured_at,geometry,computed_geometry,is_pano';
@@ -170,3 +170,41 @@ test('a status the server never answers falls back to the bundled token once the
assert.deepEqual(await status, { configured: false });
assert.equal(instance.coverageStats().keyRequired, true);
});
/** A graph image record at a point. */
const imageAt = (id, lon, lat, extra = {}) => ({
id,
is_pano: false,
captured_at: 10,
geometry: { type: 'Point', coordinates: [lon, lat] },
...extra,
});
test('nearestImage opens the closest image that passes the filter, not the first the API returned', async () => {
const requests = [];
const answer = [
imageAt('far', 2.0004, 1), // ~45 m east
imageAt('near-pano', 2.00002, 1, { is_pano: true }), // ~2 m, a panorama
imageAt('near', 2.00005, 1), // ~5 m east
imageAt('mid', 2, 1.0002), // ~22 m north
];
const source = fakeMapillarySource({
nearestImages: async (query, options) => {
requests.push({ query, options });
return answer;
},
});
const { signal } = new AbortController();
const flat = createMapillaryProvider({ source }).create(
fakeContext({ pano: 'flat', sinceMs: null }),
);
assert.equal(await flat.nearestImage({ lat: 1, lon: 2 }, { signal }), 'near');
assert.equal(requests[0].options.signal, signal, 'the core can abort it');
assert.deepEqual(requests[0].query, { lat: 1, lon: 2 });
const any = createMapillaryProvider({ source }).create(fakeContext());
assert.equal(await any.nearestImage({ lat: 1, lon: 2 }), 'near-pano');
const tooOld = createMapillaryProvider({ source }).create(
fakeContext({ pano: 'all', sinceMs: 100 }),
);
assert.equal(await tooOld.nearestImage({ lat: 1, lon: 2 }), null);
});
@@ -0,0 +1,56 @@
import '../../../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import { registerHooks } from 'node:module';
import { createStreetLevelLayer } from '../../index.js';
import { fakeStreetLevelProvider, fakeCesiumViewer } from '../../../../testSupport/streetLevelFakes.mjs';
import { createMapillaryViewer } from './viewer.js';
import { showStreetLevel } from '../../../../voice/gevActions.js';
// Library boundary fixture: moveTo changes the image without stopping PLAY,
// matching installed MapillaryJS Viewer.moveTo / Navigator.moveTo$.
const fakeLibrary = `export class Viewer {
constructor() { globalThis.__replacePlayViewer = this; this.playing = false; this.id = null; this.stops = 0; }
on() {} remove() {} resize() {} setRenderMode() {}
getComponent() { return { play: () => {this.playing = true;}, stop: () => {this.playing = false; this.stops++;} }; }
async moveTo(id) { this.id = id; return { id, sequenceId: 'fixture-sequence', cameraType: 'perspective' }; }
async getPosition() { return { lng: 2, lat: 48 }; }
async getPointOfView() { return { bearing: 0 }; }
}
export class GraphDataProvider {}
export const RenderMode = { Fill: 1, Letterbox: 0 };`;
const hooks = registerHooks({
resolve(specifier, context, next) {
if (specifier === 'mapillary-js') return { url: 'data:text/javascript,' + encodeURIComponent(fakeLibrary), shortCircuit: true };
if (specifier.endsWith('mapillary.css')) return { url: 'data:text/javascript,export default {}', shortCircuit: true };
return next(specifier, context);
},
});
globalThis.fetch = async () => { throw new Error('Unexpected network use in offline test'); };
test('a photo the action asks for stops sequence PLAY', async t => {
const provider = fakeStreetLevelProvider({ nearestImage: async () => 'B' });
const create = provider.create;
provider.create = context => ({ ...create(context), viewer: createMapillaryViewer({ source: { token: '' } }) });
const viewer = fakeCesiumViewer(); viewer.canvas = viewer.scene.canvas;
const layer = createStreetLevelLayer({ providers: [provider] });
layer.init(viewer); layer.enable(viewer);
layer.attachViewerHost(document.body.appendChild(document.createElement('div')));
t.after(() => { layer.destroy(); hooks.deregister(); delete globalThis.__replacePlayViewer; document.body.replaceChildren(); });
await Promise.resolve();
await layer.openImage('mapillary', 'A', { frame: false });
const libraryViewer = globalThis.__replacePlayViewer;
libraryViewer.getComponent('sequence').play();
assert.equal(libraryViewer.playing, true);
const manager = {
layers: new Map([['street-level', { module: layer }]]), isEnabled: () => true,
getLayerParams: () => layer.getParams(), setLayerParams: (_id, params) => layer.setParams(params),
};
const result = await showStreetLevel({ provider: 'mapillary', latitude: 48, longitude: 2 }, {
viewer, dataManager: manager, styleManager: { _navigationGeneration: 1 },
runGevAction: async () => ({ ok: true, latitude: 48, longitude: 2, label: 'fixture destination' }),
});
assert.equal(result.ok, true);
assert.equal(libraryViewer.id, 'B');
assert.equal(layer.getUIState().street.open, true);
assert.equal(libraryViewer.playing, false, 'requested image must stay selected rather than continue sequence PLAY');
});
@@ -1,9 +1,17 @@
import { msg } from '../../../../i18n/marker.js';
import { NEAREST_RADIUS_M } from '../../policy.js';
import {
MAPILLARY_GRAPH_HOST,
NEAREST_IMAGE_FIELDS,
NEAREST_LIMIT,
NEAREST_TIMEOUT_MS,
SEQUENCE_IMAGE_FIELDS,
SEQUENCE_IMAGES_LIMIT,
} from './policy.js';
/** English data: the Street Level panel translates it. */
const NO_ANSWER = msg('Mapillary did not answer in time — try again');
/** HTTP error flagged `keyRequired`, `keyRejected` or `retryAfterSec` (429). */
export class MapillarySourceError extends Error {
constructor(message, { status = 0, payload = null, retryAfterSec } = {}) {
@@ -66,7 +74,47 @@ export function createMapillarySource({
...endpoints,
};
async function graph(path, params = {}, { signal } = {}) {
async function graph(path, params = {}, { signal, timeoutMs = 0 } = {}) {
if (!timeoutMs) return graphOnce(path, params, { signal });
// The whole answer, body included, within `timeoutMs`; the caller's
// abort still wins.
if (signal?.aborted) throw signal.reason;
const controller = new AbortController();
const onAbort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', onAbort, { once: true });
const timer = setTimeout(
() =>
controller.abort(
new MapillarySourceError(NO_ANSWER, {
status: 504,
}),
),
timeoutMs,
);
try {
// A body that never ends is given up too, whatever the fetch does.
const gaveUp = new Promise((_, reject) =>
controller.signal.addEventListener(
'abort',
() => reject(controller.signal.reason),
{ once: true },
),
);
return await Promise.race([
graphOnce(path, params, { signal: controller.signal }),
gaveUp,
]);
} catch (error) {
if (signal?.aborted) throw signal.reason;
if (controller.signal.aborted) throw controller.signal.reason;
throw error;
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', onAbort);
}
}
async function graphOnce(path, params, { signal }) {
if (graphBase) {
const search = new URLSearchParams(params);
const response = await fetchImpl(`${graphBase}${path}?${search}`, {
@@ -147,5 +195,21 @@ export function createMapillarySource({
);
return Array.isArray(payload?.data) ? payload.data : [];
},
/** Images within `NEAREST_RADIUS_M` of a point, in no particular order. */
async nearestImages({ lat, lon }, { signal } = {}) {
const payload = await graph(
'images',
{
lat: String(lat),
lng: String(lon),
radius: String(NEAREST_RADIUS_M),
limit: String(NEAREST_LIMIT),
fields: NEAREST_IMAGE_FIELDS,
},
{ signal, timeoutMs: NEAREST_TIMEOUT_MS },
);
return Array.isArray(payload?.data) ? payload.data : [];
},
};
}
@@ -126,6 +126,25 @@ test('a rejected key and a rate limit are told apart from other tile errors', as
);
});
test('nearestImages asks the graph API around a point, within 50 m, for at most 100 images', async () => {
const { calls, fetchImpl } = fakeFetch(() =>
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
);
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const images = await source.nearestImages({ lat: 38.5, lon: -121.5 });
assert.equal(images.length, 1);
const url = new URL(calls[0].url);
assert.equal(url.pathname, '/images');
assert.equal(url.searchParams.get('lat'), '38.5');
assert.equal(url.searchParams.get('lng'), '-121.5');
assert.equal(url.searchParams.get('radius'), '50');
// The API cuts at the limit before any order: a small one would sort and
// filter a handful of arbitrary photos (a 360° filter could find none).
assert.equal(url.searchParams.get('limit'), '100', "the API's most");
assert.match(url.searchParams.get('fields'), /computed_geometry/);
assert.match(url.searchParams.get('fields'), /is_pano/);
});
test('with a Graph endpoint, sequence lookups go there without a token', async () => {
const { calls, fetchImpl } = fakeFetch(() =>
jsonResponse({ data: [{ id: '1', geometry: { coordinates: [1, 2] } }] }),
@@ -157,3 +176,63 @@ test('Graph endpoint errors keep their status', async () => {
(error) => error.status === 503 && error.keyRequired === true,
);
});
test('a nearest-image search that never answers is given up, body included', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const { NEAREST_TIMEOUT_MS } = await import('./policy.js');
// Headers arrive; the body never ends, and the fetch ignores its signal.
const { fetchImpl } = fakeFetch(() => ({
ok: true,
status: 200,
json: () => new Promise(() => {}),
}));
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const pending = source.nearestImages({ lat: 1, lon: 2 });
const outcome = pending.then(
() => 'answered',
(error) => error,
);
await Promise.resolve();
t.mock.timers.tick(NEAREST_TIMEOUT_MS);
const error = await outcome;
assert.ok(error instanceof MapillarySourceError, String(error));
assert.equal(error.status, 504);
assert.equal(error.keyRequired, false, 'not a key problem');
// English data, shown in the interface language like the other sources'.
const { setLocale } = await import('../../../../i18n/index.js');
const { translateStreetLevelError } =
await import('../../../../ui/streetLevelPresentation.js');
assert.equal(
translateStreetLevelError(error.message),
'Mapillary did not answer in time — try again',
);
for (const [locale, expected] of [
['de', /nicht rechtzeitig/],
['ja', /時間内に応答/],
]) {
setLocale(locale);
try {
assert.match(translateStreetLevelError(error.message), expected, locale);
} finally {
setLocale('en');
}
}
});
test('the caller’s abort still ends a nearest-image search before its deadline', async () => {
const { fetchImpl } = fakeFetch(
(_url, init) =>
new Promise((_, reject) =>
init.signal.addEventListener('abort', () => reject(init.signal.reason)),
),
);
const source = createMapillarySource({ token: 'MLY|1|abc', fetchImpl });
const controller = new AbortController();
const pending = source.nearestImages(
{ lat: 1, lon: 2 },
{ signal: controller.signal },
);
const reason = new Error('the turn moved on');
controller.abort(reason);
await assert.rejects(pending, (error) => error === reason);
});
@@ -174,6 +174,15 @@ export function createMapillaryViewer({ source, render } = {}) {
current = null;
}
/** A playing sequence keeps stepping through (and downloading) images. */
function stopPlayback() {
try {
viewer?.getComponent('sequence')?.stop();
} catch {
/* sequence component not available */
}
}
return {
async mount(host) {
if (!host) throw new Error('Street Level viewer has no host element');
@@ -195,15 +204,12 @@ export function createMapillaryViewer({ source, render } = {}) {
close() {
pendingOpen = null;
current = null;
// A playing sequence would keep stepping through (and downloading)
// images in the hidden viewer.
try {
viewer?.getComponent('sequence')?.stop();
} catch {
/* sequence component not available */
}
// Hidden, the viewer must not keep playing.
stopPlayback();
},
stopPlayback,
unmount() {
pendingOpen = null;
// A build still waiting for the library gives up when it arrives.
+2 -1
View File
@@ -20,6 +20,7 @@ export function filtersOf(provider) {
* @property {boolean} [groundClick] No coverage: a ground click at street zoom opens its nearest image.
* @property {string} [requiresMapStack] Usable only on this map stack.
* @property {boolean} [defaultOn] Default true; the first that defaults on is lit.
* @property {boolean} [billedPerImage] Every image load costs the key's owner: a link never opens one without a click.
* @property {() => boolean} [keyReady] False when its key is missing now; the
* first keyless provider is lit instead of a default that cannot draw.
* @property {{kind: 'view-cone', color: string}} [marker] Default: GEV's pin.
@@ -50,7 +51,7 @@ export function filtersOf(provider) {
* @property {(sequenceId: string) => Promise<void>} [selectSequence]
* @property {() => void} [clearSequence]
* @property {() => {selectedId: string|null, images: number, loading: boolean, error?: string|null}} [sequenceStats]
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError).
* @property {(point: {lat: number, lon: number}, options?: {signal?: AbortSignal, radiusM?: number}) => Promise<string|null>} [nearestImage] For ground clicks and `openNearest`; an aborted lookup gives up (it may reject with an AbortError). `radiusM` asks for a wider search than NEAREST_RADIUS_M; a provider that cannot search wider ignores it.
* @property {ViewerAdapter} viewer
*
* @typedef {object} ViewerAdapter
+4
View File
@@ -19,6 +19,8 @@ export function freshStreet() {
capturedAt: null,
/** 'day', or 'month' for providers that date images by month (Google). */
capturedAtPrecision: 'day',
/** Why the last nearest lookup opened nothing: 'empty', 'sky' or null. */
nearestOutcome: null,
/** A place name for the caption (Google's address), or null. */
title: null,
/** Whether the open viewer has FIT/FILL render modes. */
@@ -29,6 +31,8 @@ export function freshStreet() {
externalUrl: null,
loading: false,
error: null,
// A lookup a link prepared but left to a click: {point, providerIds, radiusM}.
armed: null,
};
}
+55 -5
View File
@@ -73,6 +73,19 @@ export function createViewerHost({ state, parts }) {
active.unsubscribe();
active.adapter.unmount();
active = null;
// The photo being replaced belonged to that source: none of its details
// (id, place, author, link) describe the one loading now.
const { open, loading, error, providerId, providerName, providerLabel } =
state.street;
Object.assign(state.street, freshStreet(), {
open,
loading,
error,
providerId,
providerName,
providerLabel,
});
parts.marker.clear();
}
const adapter = entry.instance.viewer;
const promise = (async () => {
@@ -99,12 +112,17 @@ export function createViewerHost({ state, parts }) {
}
/**
* Open an image: true once its first pose is in, false if it failed or was
* overtaken. `frame: false` leaves the camera where it is.
* Open an image: true once its first pose is in, false if it failed, was
* overtaken, or `signal` fired first. An abort while the viewer mounts or
* loads closes the photo: nothing opens for a request that was withdrawn.
*/
async function open(providerId, imageId, { frame = true } = {}) {
async function open(
providerId,
imageId,
{ frame = true, signal = null } = {},
) {
const entry = state.providers.get(providerId);
if (!entry || !imageId) return false;
if (!entry || !imageId || signal?.aborted) return false;
if (!state.street.host) {
// A nearest-image lookup may have set it; nothing is loading now.
state.street.loading = false;
@@ -115,6 +133,10 @@ export function createViewerHost({ state, parts }) {
}
const seq = ++openSeq;
const current = () => seq === openSeq;
const onAbort = () => {
if (current()) close();
};
signal?.addEventListener('abort', onAbort, { once: true });
// Claimed now, honoured after loading only if nothing newer took the camera.
const ticket = frame ? parts.framing.begin() : null;
Object.assign(state.street, {
@@ -138,6 +160,7 @@ export function createViewerHost({ state, parts }) {
if (current())
state.street.error = error?.message || msg('Image could not be opened');
} finally {
signal?.removeEventListener('abort', onAbort);
if (current()) state.street.loading = false;
notify();
}
@@ -165,6 +188,11 @@ export function createViewerHost({ state, parts }) {
active?.adapter.resize();
}
/** Stop a sequence playing in the open photo (adapters that play). */
function stopPlayback() {
active?.adapter.stopPlayback?.();
}
function setRenderMode(mode) {
state.street.renderMode = mode === 'fill' ? 'fill' : 'letterbox';
active?.adapter.setRenderMode?.(state.street.renderMode);
@@ -187,5 +215,27 @@ export function createViewerHost({ state, parts }) {
active = null;
}
return { attach, open, close, resize, setRenderMode, unmount };
/**
* Destroy `providerId`'s viewer and leave the panel's state alone: what a
* request leaves behind once it replaced or closed that source's photo.
*/
function release(providerId) {
if (active?.id !== providerId && mounting?.id !== providerId) return;
const pending = mounting;
mounting = null;
active?.unsubscribe();
(active?.adapter ?? pending?.adapter)?.unmount();
active = null;
}
return {
attach,
open,
close,
resize,
setRenderMode,
stopPlayback,
unmount,
release,
};
}
@@ -557,6 +557,51 @@ test('an adapter that can frame but says this image has no frame offers no FIT /
assert.equal(state.street.renderModes, true, 'a flat image can be framed');
});
test('a caller that withdraws while the viewer is still mounting gets no photo', async () => {
const gate = deferred();
const adapter = fakeAdapter({ gate });
const { state, host } = harness(adapter);
const controller = new AbortController();
const pending = host.open('mapillary', 'a', { signal: controller.signal });
assert.equal(state.street.open, true, 'opening');
controller.abort(); // the library is still loading
gate.resolve();
assert.equal(await pending, false);
assert.deepEqual(adapter.calls.open, [], 'the image was never opened');
assert.equal(state.street.open, false, 'the photo is closed');
assert.equal(state.street.loading, false, 'no stuck spinner');
assert.equal(state.street.imageId, null);
});
test('a caller that withdraws while the photo is loading gets it closed', async () => {
const openGate = deferred();
const adapter = fakeAdapter({ openGate });
const { state, host } = harness(adapter);
const controller = new AbortController();
const pending = host.open('mapillary', 'a', { signal: controller.signal });
await settle();
assert.deepEqual(adapter.calls.open, ['a'], 'loading');
controller.abort();
openGate.resolve();
assert.equal(await pending, false);
assert.equal(state.street.open, false, 'the withdrawn photo is closed');
assert.equal(state.street.imageId, null);
// An already-withdrawn request asks nothing at all.
const done = new AbortController();
done.abort();
assert.equal(
await host.open('mapillary', 'b', { signal: done.signal }),
false,
);
assert.deepEqual(adapter.calls.open, ['a']);
// A signal that never fires changes nothing.
assert.equal(
await host.open('mapillary', 'c', { signal: new AbortController().signal }),
true,
);
assert.equal(state.street.imageId, 'c');
});
test('a pose’s licence reaches the caption state, and a closed viewer forgets it', async () => {
const { state, host, google } = twoProviders();
await host.open('google', 'g-1');
+3
View File
@@ -299,6 +299,9 @@ export function createControls({ state: layerState, services, parts, source }) {
position: pos,
id: `VEH-${String(layerState._dots[i].id).padStart(4, '0')}`,
type: 'VEH',
// The dots are depth-tested, so the overlay hides a contact's
// bracket and callout wherever the scene hides its dot.
depthTested: true,
};
// Live mode: the detection bracket carries the congestion signal —
// its canvas sits ABOVE the post-FX chain, so tier colors survive
+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;
+15 -1
View File
@@ -124,7 +124,14 @@ export function createHeight({ state, services, parts }) {
const cells = new Map();
const collect = (point, answer) => {
if (!onGround) return;
if (!cells.has(answer.cell))
// A cell keeps the last point offered in it: the path is walked
// oldest first, so that is where the vehicle is now or about to be,
// and the mesh sampler reads the surface there.
const held = cells.get(answer.cell);
if (held) {
held.lat = point.lat;
held.lon = point.lon;
} else
cells.set(answer.cell, {
lat: point.lat,
lon: point.lon,
@@ -136,6 +143,13 @@ export function createHeight({ state, services, parts }) {
const newest = entry.fixes.at(-1);
const answer = requestHeight(newest.lat, newest.lon, entry);
entry.heightCell = answer.cell;
// The selected vehicle's path also offers its history, newest segment
// first; the vehicle's own cell is read where its newest fix is.
const own = cells.get(answer.cell);
if (own) {
own.lat = newest.lat;
own.lon = newest.lon;
}
if (answer.height !== null) {
entry.heightM = answer.height;
entry.heightResolved = true;
+108
View File
@@ -2938,6 +2938,114 @@ test('mesh refinement reaches all 100 retained DEM cells within five poll budget
assert.equal(probed.size, 100);
});
test('mesh refinement probes the latest point the path offers in a cell', async (t) => {
const { createHeight } = await import('./height.js');
// Three points along one cell's stretch of path, oldest first.
const path = [
{ lat: 42.3611, lon: -71.0751 },
{ lat: 42.3612, lon: -71.0753 },
{ lat: 42.3614, lon: -71.0754 },
];
const entry = { key: 'train', to: path[0], fixes: [path.at(-1)] };
const probed = [];
const state = {
_enabled: true,
_selectedKey: null,
_visible: new Set([entry]),
_vehicles: new Map([[entry.key, entry]]),
_floorCursor: 0,
_heightDirty: new Set(),
_viewer: { camera: { positionCartographic: { height: 100 } } },
};
const height = createHeight({
state,
services: {
render: { governorRequestRender() {} },
ground: {
coarseFloorCoord: (lat, lon) => ({
lat: Number(lat.toFixed(3)),
lon: Number(lon.toFixed(3)),
}),
cachedGroundFloor: () => 10,
GROUND_FLOOR_LIFT_M: 1.5,
},
mesh: {
sampleMeshFloorCells(scene, points) {
probed.push(...points.map((p) => [p.lat, p.lon]));
},
},
},
parts: {
trails: {
prepareEntry(e, collect) {
if (collect)
for (const point of path)
collect(point, height.requestHeight(point.lat, point.lon));
},
},
rendering: { requestVisibility() {} },
},
});
t.after(() => height.clear());
height.anchorFloors();
assert.deepEqual(probed, [[42.3614, -71.0754]]);
});
test('the selected vehicle is probed at its newest fix in its own cell', async (t) => {
const { createHeight } = await import('./height.js');
// The selected path offers its active corridor first, then its history
// newest segment first, so the last offer in the cell is an older point.
const newest = { lat: 42.3614, lon: -71.0754 };
const offers = [
newest,
{ lat: 42.3612, lon: -71.0753 },
{ lat: 42.3611, lon: -71.0751 },
];
const entry = { key: 'train', to: offers[0], fixes: [newest] };
const probed = [];
const state = {
_enabled: true,
_selectedKey: entry.key,
_visible: new Set([entry]),
_vehicles: new Map([[entry.key, entry]]),
_floorCursor: 0,
_heightDirty: new Set(),
_viewer: { camera: { positionCartographic: { height: 100 } } },
};
const height = createHeight({
state,
services: {
render: { governorRequestRender() {} },
ground: {
coarseFloorCoord: (lat, lon) => ({
lat: Number(lat.toFixed(3)),
lon: Number(lon.toFixed(3)),
}),
cachedGroundFloor: () => 10,
GROUND_FLOOR_LIFT_M: 1.5,
},
mesh: {
sampleMeshFloorCells(scene, points) {
probed.push(...points.map((p) => [p.lat, p.lon]));
},
},
},
parts: {
trails: {
prepareEntry(e, collect) {
if (collect)
for (const point of offers)
collect(point, height.requestHeight(point.lat, point.lon));
},
},
rendering: { requestVisibility() {} },
},
});
t.after(() => height.clear());
height.anchorFloors();
assert.deepEqual(probed, [[42.3614, -71.0754]]);
});
test('selection churn releases past geometry on every retained vehicle', async (t) => {
const app = harness(t, { floorAt: () => 10 });
const { mergeHistory, seek } = await import('../../data/contactPlayback.js');
Loaded 100 of 422 files, more files were not shown because too many files have changed in this diff. Show more