Merge origin/main into review/pr-1593

Conflicts: docs/CURRENT-STATE.md layer table, src/ui/layerPanel.js imports,
src/data/dataCredits.test.mjs imports; both sides kept.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
Mazeyar Moeini FeizabadiandClaude Fable 5.2 committed 2026-11-10 21:20:15 +01:00
commit 3342d7a07a
194 files changed
+16487 -764

No files matched your search

+39
View File
@@ -1802,3 +1802,42 @@ test('vessel focus wire skips hidden sprites at rest while a target is tracked',
assert.equal(result.activeCount, 1);
for (const billboard of hidden) assert.equal(billboard.color.alpha, 1);
});
test('detection objects name the vessel card their callout gives way to', () => {
const vessel = (mmsi, name) => ({
name,
mmsi,
type: 'Cargo',
destination: '',
speed: 9.5,
course: 80,
heading: 80,
lastPositionUtc: '',
missedRefreshes: 0,
position: POS,
billboard: null,
});
const keyed = vessel('200', 'GOLDEN BEAR');
const unkeyed = { ...vessel('', 'NO MMSI'), lat: 37.8, lon: -122.4 };
_setVesselStateForTest({
viewer: {},
records: [keyed, unkeyed],
billboardCollection: { show: true, remove() {} },
});
try {
const objects = Object.fromEntries(
aisLiveVesselsLayer
.getDetectableObjects()
.map((object) => [object.id, object]),
);
assert.equal(objects['GOLDEN BEAR'].cardSourceId, 'ais-live-vessels');
assert.equal(objects['GOLDEN BEAR'].cardEntryId, 'vessel:200');
assert.equal(
objects['NO MMSI'].cardEntryId,
'vessel:unkeyed:NO MMSI:37.80000:-122.40000',
'the same identity the vessel card is published under',
);
} finally {
_setVesselStateForTest({ enabled: false });
}
});
+21
View File
@@ -1518,3 +1518,24 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
h.restore();
}
});
test('ALPR display tags collapse controls and cap final text without erasing Unicode', () => {
const record = normalizeAlprNode({
type: 'node',
id: 1,
lat: 30,
lon: -97,
tags: {
'surveillance:type': 'ALPR',
operator: ' Şehir\n\u0000 PD ',
manufacturer: '😀'.repeat(200),
'camera:type': null,
'surveillance:zone': '\t traffic zone ',
},
});
assert.equal(record.operator, 'Şehir PD');
assert.equal(record.manufacturer.length, 180);
assert.equal(record.manufacturer, '😀'.repeat(90));
assert.equal(record.cameraType, null);
assert.equal(record.zone, 'traffic zone');
});
+31 -4
View File
@@ -134,6 +134,13 @@ export const DATA_CREDITS = [
'copied, published, or incorporated into other databases without the ' +
'explicit permission of David J Taylor, Edinburgh',
},
{
key: 'planespotters',
html:
'Aircraft photos: ' +
'<a href="https://www.planespotters.net" target="_blank" rel="noopener">Planespotters.net</a> ' +
'· each photo is © its photographer, credited beside it',
},
{
key: 'aisstream',
html:
@@ -706,20 +713,40 @@ export const OSM_PLACES_CREDIT = {
/**
* Per-feed transit credit, registered the first time that feed's vehicles
* render (see `src/data/transitFeeds.js` for the license of each).
* @param {{ id: string, attribution: string, license: string, licenseUrl: string }} feed
*
* Two optional registry fields serve licences that ask for more than a name:
* `sourceUrl` links the attribution to the publisher (Warsaw asks for a link
* to its API), and `creditDated` adds the UTC date of the data, from the feed
* header or else the fetch time (Warsaw and Poznań ask for the download or
* update date). A dated credit is keyed by its date, so a new day registers a
* new line instead of keeping yesterday's.
* @param {{ id: string, attribution: string, license: string, licenseUrl: string,
* sourceUrl?: string, creditDated?: boolean }} feed
* @param {{ feedTimestamp?: number|null, fetchedAt?: number|null }} [snapshot]
* `feedTimestamp` in epoch seconds, `fetchedAt` in epoch ms.
* @returns {{ key: string, html: string }}
*/
export function transitFeedCredit(feed) {
export function transitFeedCredit(feed, snapshot = null) {
const escape = (text) =>
String(text)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
const source = feed.sourceUrl
? `<a href="${escape(feed.sourceUrl)}" target="_blank" rel="noopener">${escape(feed.attribution)}</a>`
: escape(feed.attribution);
const dataMs = Number.isFinite(snapshot?.feedTimestamp)
? snapshot.feedTimestamp * 1000
: snapshot?.fetchedAt;
const date =
feed.creditDated === true && Number.isFinite(dataMs) && dataMs > 0
? new Date(dataMs).toISOString().slice(0, 10)
: null;
return {
key: `transit-${feed.id}`,
key: date ? `transit-${feed.id}-${date}` : `transit-${feed.id}`,
html:
`Transit (${escape(feed.attribution)}): ` +
`Transit (${source}${date ? `, data of ${date}` : ''}): ` +
`<a href="${escape(feed.licenseUrl)}" target="_blank" rel="noopener">${escape(feed.license)}</a>`,
};
}
+30
View File
@@ -4,7 +4,9 @@ import {
DATA_CREDITS,
LIVEUAMAP_CREDIT,
NYC_DOT_DISCLAIMER,
transitFeedCredit,
} from './dataCredits.js';
import { getTransitFeed } from './transitFeeds.js';
test('every credit carries a unique key and some markup to render', () => {
const keys = DATA_CREDITS.map((entry) => entry.key);
@@ -42,6 +44,13 @@ test('adsbdb is credited and carries its published route-data restriction', () =
assert.match(credit.html, /href="https:\/\/www\.adsbdb\.com"/);
});
test('Planespotters is credited with a plain followable link', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'planespotters');
assert.ok(credit, 'the tracked aircraft photos come from Planespotters');
assert.match(credit.html, /href="https:\/\/www\.planespotters\.net"/);
assert.doesNotMatch(credit.html, /nofollow/);
});
test('the UCS Satellite Database is acknowledged with its version and webpage', () => {
// UCS database manual, section 3: references name the version (the Excel
// file's name) and link www.ucsusa.org/satellite_database.
@@ -214,3 +223,24 @@ test('the PR #1506 camera packs are credited with their sources and terms', () =
/href="https:\/\/www\.river\.go\.jp\//,
);
});
test('Warsaw and Poznań credits carry the data date their licences ask for', () => {
const warsaw = getTransitFeed('ztm-warszawa');
// 2026-11-09T06:00:00Z as a GTFS-RT header timestamp (seconds).
const credit = transitFeedCredit(warsaw, { feedTimestamp: 1_794_204_000 });
assert.match(credit.html, /, data of 2026-11-09\)/);
assert.match(credit.html, /href="http:\/\/api\.um\.warszawa\.pl"/);
assert.equal(credit.key, 'transit-ztm-warszawa-2026-11-09');
// Without a feed timestamp the fetch time is the download date.
const poznan = transitFeedCredit(getTransitFeed('ztm-poznan'), {
feedTimestamp: null,
fetchedAt: Date.UTC(2026, 10, 10, 12),
});
assert.match(poznan.html, /data of 2026-11-10/);
// Undated feeds keep one credit line for the session.
const mbta = transitFeedCredit(getTransitFeed('mbta'), {
feedTimestamp: 1_794_204_000,
});
assert.equal(mbta.key, 'transit-mbta');
assert.doesNotMatch(mbta.html, /data of/);
});
+24 -3
View File
@@ -21,7 +21,10 @@ import {
getKeyholeFadeTuning,
keyholeLabelAlphaFromGeometry,
} from '../celestialRing.js';
import { registerWorldOverlayPaintLane } from '../overlays/worldOverlay.js';
import {
getQueuedOverlayEntryAlpha,
registerWorldOverlayPaintLane,
} from '../overlays/worldOverlay.js';
import {
DETECTION_STYLE,
DETECTION_THEME_MAP,
@@ -107,6 +110,8 @@ const THEME_MAP = DETECTION_THEME_MAP;
const SPARSE_ZONE_FRACTION = 0.5;
/** Solve cadence for membership/collision; accepted identities still reproject every frame. */
const LABEL_SOLVE_INTERVAL_MS = 125;
/** Own-card opacity that fully hides a callout; below it the callout fades in. */
const CARD_ALPHA_HIDING_CALLOUT = 0.5;
/** Alpha bands retain bracket batching while approximating a continuous radial fade. */
const BRACKET_ALPHA_STEPS = 4;
/** Finer bands for Global Context echo brackets, whose fade is animated. */
@@ -576,7 +581,8 @@ export function getDetectionDiagnostics() {
// sprites/strokes. Nothing is copied on the production paint path.
result.calloutRects = _calloutPool
.slice(0, _calloutCount)
.map(({ x, y, w, h, alpha }) => ({ x, y, w, h, alpha }));
.filter((row) => row.paintAlpha > 0.001)
.map(({ x, y, w, h, paintAlpha }) => ({ x, y, w, h, alpha: paintAlpha }));
return result;
}
@@ -1077,6 +1083,9 @@ function _stashCallout(entry, acquireFade, keyhole) {
font: FONT,
microFont: MICRO_FONT,
alpha: 1,
cardSourceId: '',
cardEntryId: '',
paintAlpha: 1,
};
_calloutPool[_calloutCount] = row;
}
@@ -1103,6 +1112,8 @@ function _stashCallout(entry, acquireFade, keyhole) {
row.font = FONT;
row.microFont = MICRO_FONT;
row.alpha = alpha;
row.cardSourceId = candidate.cardSourceId;
row.cardEntryId = candidate.cardEntryId;
_calloutCount++;
}
@@ -1134,7 +1145,15 @@ function _paintCalloutLane(frame) {
ctx.textBaseline = 'alphabetic';
for (let i = 0; i < _calloutCount; i++) {
const row = _calloutPool[i];
paintDetectionCallout(ctx, row, row.alpha);
// The callout would show through its contact's own card: fade it by the
// opacity that card paints with this frame.
const cardAlpha =
row.cardEntryId === ''
? 0
: getQueuedOverlayEntryAlpha(row.cardSourceId, row.cardEntryId);
row.paintAlpha =
row.alpha * Math.max(0, 1 - cardAlpha / CARD_ALPHA_HIDING_CALLOUT);
if (row.paintAlpha > 0.001) paintDetectionCallout(ctx, row, row.paintAlpha);
}
ctx.globalAlpha = 1;
}
@@ -1211,6 +1230,8 @@ function _materializeCandidate(
primary,
micro,
hasMicro: card.hasMicro,
cardSourceId: obj.cardSourceId ? String(obj.cardSourceId) : '',
cardEntryId: obj.cardEntryId ? String(obj.cardEntryId) : '',
};
}
+179
View File
@@ -20,9 +20,16 @@ import {
} from './detection.js';
import {
destroyWorldOverlay,
getOverlayPaintRect,
initWorldOverlay,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { applyVesselOverlayPolicy } from './vesselLabels.js';
import {
getKeyholeFadeTuning,
getKeyholeGeometry,
keyholeLabelAlphaFromGeometry,
} from '../celestialRing.js';
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
import {
clearAwarenessEchoField,
@@ -579,6 +586,178 @@ test('every style paints its OWN plate token through the production callout path
}
});
/** A vessel detection contact that names its ambient card, like the AIS layer does. */
function shipWithCard(mmsi, position) {
return {
position,
sourceId: mmsi,
id: `SHIP-${mmsi}`,
metric: '6 kn',
type: 'SEA',
cardSourceId: 'ais-live-vessels',
cardEntryId: `vessel:${mmsi}`,
};
}
/** The production ambient vessel card (not protected: it goes through the arbiter). */
function ambientVesselCard(mmsi, position) {
return applyVesselOverlayPolicy({
id: `vessel:${mmsi}`,
position,
title: `CARD-${mmsi}`,
details: ['CARGO · 6KT · 80°'],
gapPx: 10,
});
}
test('a callout stays readable when its own card is faded out at the keyhole rim', () => {
// Default keyhole tuning: 7% feather, 1% outside opacity.
assert.deepEqual(getKeyholeFadeTuning(), { fadeRatio: 0.07, outsideOpacity: 0.01 });
const width = 1600;
const height = 900;
const keyhole = getKeyholeGeometry(width, height);
const env = installEnvironment({ width, height, dpr: 1 });
// Just outside the keyhole's left rim: the card sits above or below the
// anchor (outside, 1% alpha), the callout to its right (inside the feather).
const position = new Cesium.Cartesian3(270 / (width / 2) - 1, 1 - 460 / (height / 2), 6_356_752);
const ship = shipWithCard('200', position);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
const [alone] = getDetectionDiagnostics().calloutRects;
assert.ok(alone && alone.alpha >= 0.5, 'without a card the callout is clearly visible');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', position)]);
for (let i = 0; i < 4; i++) settleFrame(env);
const rect = getOverlayPaintRect('ais-live-vessels', 'vessel:200');
assert.ok(rect, 'the host paints the card (at the outside opacity)');
const cardAlpha = keyholeLabelAlphaFromGeometry(rect.x + rect.w / 2, rect.y + rect.h / 2, keyhole);
assert.ok(cardAlpha <= 0.05, `the card is invisible at the rim (keyhole alpha ${cardAlpha})`);
const callouts = getDetectionDiagnostics().calloutRects;
assert.equal(callouts.length, 1, 'the callout keeps painting while its card is faded out');
assert.ok(callouts[0].alpha >= 0.4, 'and stays readable');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a callout stays hidden while its card fades out after leaving the published cohort', () => {
const env = installEnvironment({ width: 1600, height: 900, dpr: 1 });
const at = (x, y) => new Cesium.Cartesian3(x, y, 6_356_752);
const ship = shipWithCard('200', at(0.1, 0.1));
const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text);
const frame = (ms) => {
env.ctx.calls.length = 0;
env.advance(ms);
env.postRender.raise();
};
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]);
for (let i = 0; i < 6; i++) frame(250);
frame(16);
assert.ok(painted('CARD-200') && !painted('SHIP-200'), 'steady state: card only');
// The vessel layer republishes its screen-grid cohort after a camera move:
// this vessel's card is replaced by another one, the vessel stays detectable.
setOverlayEntries('ais-live-vessels', [ambientVesselCard('300', at(-0.5, -0.4))]);
frame(16);
assert.ok(getOverlayPaintRect('ais-live-vessels', 'vessel:200'), 'the dropped card is still fading out');
assert.ok(painted('CARD-200'), 'and its text still paints');
assert.ok(!painted('SHIP-200'), 'no full callout under the fading card');
for (let i = 0; i < 4; i++) frame(250);
assert.ok(!painted('CARD-200'), 'the card has faded out');
assert.ok(painted('SHIP-200'), 'and the callout is back');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a vessel whose ambient card loses the collision keeps its callout', () => {
const env = installEnvironment({ width: 900, height: 600, dpr: 1 });
// Four vessels a few pixels apart: their cards collide (a card goes only
// above or below its anchor), so the arbiter paints only some of them.
const ships = [0, 1, 2, 3].map((i) =>
shipWithCard(String(100 + i), new Cesium.Cartesian3(-0.2 + i * 0.005, i * 0.005, 6_356_752)),
);
const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => ships }], () => {});
setOverlayEntries(
'ais-live-vessels',
ships.map((ship) => ambientVesselCard(ship.sourceId, ship.position)),
);
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
env.ctx.calls.length = 0;
settleFrame(env);
const winners = ships.filter((ship) => getOverlayPaintRect('ais-live-vessels', ship.cardEntryId));
assert.ok(
winners.length >= 1 && winners.length < ships.length,
`the colliding cards leave some unpainted (${winners.length} of ${ships.length} painted)`,
);
for (const ship of ships) {
const carded = winners.includes(ship);
assert.equal(
painted(ship.id),
!carded,
carded ? `${ship.id} draws no callout under its card` : `${ship.id} keeps its callout`,
);
}
assert.equal(
getDetectionDiagnostics().calloutRects.length,
ships.length - winners.length,
'only the callouts that painted are reported',
);
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a callout fades out while its card fades in instead of vanishing at once', () => {
const env = installEnvironment({ width: 1600, height: 900, dpr: 1 });
const ship = shipWithCard('200', new Cesium.Cartesian3(0.1, 0.1, 6_356_752));
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
const [alone] = getDetectionDiagnostics().calloutRects;
assert.ok(alone.alpha >= 0.9, 'the callout starts fully visible');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]);
const alphas = [];
for (let i = 0; i < 30; i++) {
env.advance(16);
env.postRender.raise();
alphas.push(getDetectionDiagnostics().calloutRects[0]?.alpha ?? 0);
}
assert.ok(
alphas.some((alpha) => alpha > 0.1 && alpha < alone.alpha - 0.1),
`the callout passes through partial opacity: ${alphas.map((a) => a.toFixed(2)).join(' ')}`,
);
assert.equal(alphas.at(-1), 0, 'and is gone once the card is fully in');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('space-tier callouts take the heavier plate while air contacts keep the light one', () => {
// Satellites sit over the high-albedo lit Earth disc far more often than
// aircraft do, so the space tier carries the heavier backing. Losing the
+11
View File
@@ -0,0 +1,11 @@
/** One-line text capped at `maxLength` without splitting a surrogate pair. Still untrusted. */
export function normalizeDisplayText(value, maxLength = 180) {
if (value == null || typeof value === 'object') return '';
return String(value)
.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, maxLength)
.replace(/[\uD800-\uDBFF]$/, '')
.trim();
}
+4 -3
View File
@@ -120,9 +120,10 @@ test('fire detection key survives a refetch that renumbers the index', () => {
});
test('two satellites over the same pixel at the same time stay distinct', () => {
// The proxy merges SNPP + NOAA-20 + NOAA-21 without dedup and their orbits
// overlap, so position and time alone are NOT unique. Collapsing them let a
// restored selection land on the other satellite's record.
// The proxy merges NOAA-20 + NOAA-21 without dedup and their orbits overlap,
// so position and time alone are NOT unique. Collapsing them let a restored
// selection land on the other satellite's record. Archived Suomi NPP (`N`)
// rows must stay distinct too.
const base = makeFire({ satellite: 'N20' });
const twin = makeFire({ satellite: 'N21' });
const suomi = makeFire({ satellite: 'N' });
+14 -5
View File
@@ -21,7 +21,10 @@ assert.notEqual(start, -1, 'FIRMS refresh function exists');
const end = config.indexOf('\n }', start);
assert.notEqual(end, -1, 'FIRMS refresh function closes');
const refreshSource = config.slice(start, end + 4);
const SOURCES = ['VIIRS_NOAA20_NRT', 'VIIRS_NOAA21_NRT', 'VIIRS_SNPP_NRT', 'MODIS_NRT'];
// Read the list from production so these tests follow it.
const listed = config.match(/const SOURCES = \[([^\]]*)\];/);
assert.ok(listed, 'FIRMS source list exists');
const SOURCES = [...listed[1].matchAll(/'([A-Z0-9_]+)'/g)].map((m) => m[1]);
const NOW = Date.UTC(2026, 8, 11, 12);
const recent = { acqDate: '2026-09-11', acqTime: '1100' };
@@ -54,7 +57,7 @@ test('FIRMS retains large sources in order and filters expired rows', async () =
assert.equal(result.fires[199_999], large.at(-1));
assert.equal(result.fires.at(-1), last);
assert.deepEqual(result.sources, SOURCES.map((source, index) => ({
source, count: [200_000, 1, 0, 0][index], ok: true,
source, count: [200_000, 1, 0][index], ok: true,
})));
});
@@ -63,7 +66,7 @@ test('FIRMS keeps successful sources when another upstream fails', async () => {
if (source === SOURCES[1]) throw new Error('upstream unavailable');
return [recent];
})('fixture');
assert.equal(result.fires.length, 3);
assert.equal(result.fires.length, SOURCES.length - 1);
assert.deepEqual(result.sources, SOURCES.map((source, index) => ({
source, count: index === 1 ? 0 : 1, ok: index !== 1,
})));
@@ -77,7 +80,7 @@ test('FIRMS reports one failure if consuming a source throws before append', asy
// Fault injection for aggregation; ordinary parsed CSV returns an array.
return { length: 1, [Symbol.iterator]() { throw new Error('aggregation failed'); } };
})('fixture');
assert.equal(result.fires.length, 3);
assert.equal(result.fires.length, SOURCES.length - 1);
assert.deepEqual(result.sources, SOURCES.map((source, index) => ({
source, count: index === 0 ? 0 : 1, ok: index !== 0,
})));
@@ -107,7 +110,7 @@ function wrappedAddressSelectionFailure() {
{ name: 'ConnectTimeoutError', code: 'UND_ERR_CONNECT_TIMEOUT', cause: inner });
return new TypeError('fetch failed', { cause });
}
const URL_WITH_KEY = 'https://firms.modaps.eosdis.nasa.gov/api/area/csv/SECRET/VIIRS_SNPP_NRT/world/2';
const URL_WITH_KEY = 'https://firms.modaps.eosdis.nasa.gov/api/area/csv/SECRET/VIIRS_NOAA20_NRT/world/2';
test('FIRMS failures log the socket cause, never the keyed URL', () => {
const described = describeFetchError(addressSelectionFailure());
@@ -307,3 +310,9 @@ test('every FIRMS upstream request goes through the IPv4 fallback', async () =>
assert.ok(calls[0][2] instanceof AbortSignal);
assert.deepEqual(calls[1], ['read', response, calls[0][2]], 'the body read shares the request deadline');
});
test('FIRMS requests only the satellites NASA still delivers', () => {
// NASA stopped delivering Suomi NPP on 2026-11-02; asking for it only spends
// a MAP_KEY transaction.
assert.ok(!SOURCES.includes('VIIRS_SNPP_NRT'));
});
+2
View File
@@ -40,5 +40,7 @@ export const _driveFleetModelHandoffForTest =
flightsLayer.testing._driveFleetModelHandoffForTest;
export const _ensureFleetModelForTest =
flightsLayer.testing._ensureFleetModelForTest;
export const _resetEnrichmentForTest =
flightsLayer.testing._resetEnrichmentForTest;
export const mapAnalystRecord = flightsLayer.mapAnalystRecord;
export default flightsLayer;
+293 -2
View File
@@ -1,7 +1,7 @@
// src/data/flights.test.mjs
// Focused tests for the pure analyst-record mapper (analyst query engine seam).
// Pure function — no viewer/DOM needed; imported directly.
import { test } from 'node:test';
import { after, afterEach, before, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import flightsLayer, {
@@ -14,21 +14,53 @@ import flightsLayer, {
_setTrackedFlightRefreshStateForTest,
_floorGroundedDisplayPositionForTest,
_clearDisplayFloorStateForTest,
_resetEnrichmentForTest,
mapAnalystRecord,
} from './flights.js';
import { setMilitaryLayerActive } from './militaryRegistry.js';
import {
isMilitaryLayerActive,
registerMilitaryIcaos,
setMilitaryLayerActive,
} from './militaryRegistry.js';
import {
GROUND_FLOOR_LIFT_M,
reportMeshFloorCell,
reportValidatedMeshFloorCell,
setMeshFloorPreferred,
_clearMeshFloorCellsForTest,
} from './groundFloor.js';
import { resolveEllipsoidalGround } from './terrainHeights.js';
import {
_setTrackedOverlayHostForTest,
destroyTrackedReadout,
initTrackedReadout,
} from './trackedReadout.js';
// Unit tests never reach the network. A test that tracks a plane queues its
// enrichment (type, route, photo), so every test ends on an empty queue, and a
// fetch of any absolute URL fails the test it happened in. A test that needs
// answers installs its own fetch and restores this one.
const nodeFetch = globalThis.fetch;
const networkRequests = [];
before(() => {
globalThis.fetch = async (url) => {
const href = String(url?.url ?? url);
if (/^https?:\/\//i.test(href)) networkRequests.push(href);
throw new TypeError(`Failed to parse URL from ${href}`);
};
});
afterEach(() => {
_resetEnrichmentForTest();
assert.deepEqual(
networkRequests.splice(0),
[],
'no test reaches the network',
);
});
after(() => {
globalThis.fetch = nodeFetch;
});
test('share-Follow absence requires an accepted OpenSky snapshot', async () => {
_setFlightTrackingRefreshOutcomeForTest({ status: 'source-unavailable' });
assert.equal(
@@ -402,6 +434,232 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA
}
});
test('a tracked plane whose photo lookup failed asks again on the first poll after the cool-down', async (t) => {
const icao24 = 'b2c3d4';
const realNow = Date.now.bind(Date);
let offsetMs = 0;
t.mock.method(Date, 'now', () => realNow() + offsetMs);
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24,
entity,
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
show: false,
},
billboardCollection: { show: false, remove() {} },
viewer,
meta: {
callsign: 'UAL9',
altitude: 9_000,
renderAltitudeM: 9_050,
velocity: 180,
true_track: 80,
klass: 'airliner',
onGround: false,
wasAirborne: true,
turnRateDps: 0,
rawLat: 30.2,
rawLon: -97.7,
},
});
let callsign = 'UAL9 ';
const photoRequests = [];
const routeRequests = [];
const guardFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
url = String(url);
if (url.startsWith('https://api.planespotters.net/')) {
photoRequests.push(url);
return { ok: false, status: 503, json: async () => ({}) };
}
if (url.startsWith('/api/adsbdb/route/UAL')) routeRequests.push(url);
if (!url.startsWith('/api/flights'))
return { ok: true, status: 200, json: async () => ({ found: false }) };
const nowSec = Math.floor(Date.now() / 1000);
return {
ok: true,
status: 200,
headers: { get: () => null },
json: async () => ({
time: nowSec,
states: [
[
icao24,
callsign,
'United States',
nowSec,
nowSec,
-97.6,
30.3,
10_668,
false,
250,
95,
5,
null,
10_700,
null,
null,
null,
5,
],
],
}),
};
};
// Lookups drip out one per 200 ms. Wait for what must arrive (with a
// generous deadline, so a loaded machine cannot fail it), then a little
// longer so anything that must NOT arrive would have.
const until = async (ready) => {
const deadline = realNow() + 5_000;
while (!ready() && realNow() < deadline)
await new Promise((done) => setTimeout(done, 20));
await new Promise((done) => setTimeout(done, 450));
};
try {
await flightsLayer.update(viewer);
await until(() => photoRequests.length >= 1 && routeRequests.length >= 1);
assert.equal(photoRequests.length, 1, 'the first poll asks for the photo');
assert.deepEqual(routeRequests, ['/api/adsbdb/route/UAL9']);
// Well inside the 60 s cool-down, and well past it below, so real time
// spent between polls cannot move either side across the line.
offsetMs += 30_000;
callsign = 'UAL10 ';
await flightsLayer.update(viewer);
await until(() => routeRequests.length >= 2);
assert.equal(photoRequests.length, 1, 'not within the cool-down');
assert.deepEqual(
routeRequests,
['/api/adsbdb/route/UAL9', '/api/adsbdb/route/UAL10'],
'the route follows the callsign the poll just recorded',
);
offsetMs += 60_000;
await flightsLayer.update(viewer);
await until(() => photoRequests.length >= 2);
assert.deepEqual(
photoRequests,
[
'https://api.planespotters.net/pub/photos/hex/b2c3d4',
'https://api.planespotters.net/pub/photos/hex/b2c3d4',
],
'asked again on the first poll after the cool-down',
);
} finally {
globalThis.fetch = guardFetch;
// The moved clock dated this layer's dispatch and cool-downs into the
// future; reset before the real clock comes back.
_resetEnrichmentForTest();
t.mock.restoreAll();
}
});
test('a known-military aircraft tracked in the flights layer is never looked up and shows no photo', async () => {
const icao24 = 'ae5e01';
// The registry has no way to forget one hex (only a whole-registry reset,
// which would also drop its source), so the test uses a hex no other test
// reads and restores the layer-active flag it changes.
const militaryWasActive = isMilitaryLayerActive();
registerMilitaryIcaos([icao24]);
setMilitaryLayerActive(false);
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24,
entity: { gevLabelModel: { title: 'OLD', details: [] } },
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
show: false,
},
billboardCollection: { show: false, remove() {} },
viewer,
meta: {
callsign: 'RCH123',
altitude: 9_000,
renderAltitudeM: 9_050,
velocity: 180,
true_track: 80,
klass: 'airliner',
onGround: false,
wasAirborne: true,
turnRateDps: 0,
rawLat: 30.2,
rawLon: -97.7,
// Even a photo already on the record is never shown.
photo: {
src: 'https://t.plnspttrs.net/1/ae5e01_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/x',
},
},
});
const photoRequests = [];
const routeRequests = [];
const guardFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
url = String(url);
if (url.startsWith('https://api.planespotters.net/')) {
photoRequests.push(url);
return { ok: false, status: 503, json: async () => ({}) };
}
if (url.startsWith('/api/adsbdb/route/')) routeRequests.push(url);
if (!url.startsWith('/api/flights'))
return { ok: true, status: 200, json: async () => ({ found: false }) };
const nowSec = Math.floor(Date.now() / 1000);
return {
ok: true,
status: 200,
headers: { get: () => null },
json: async () => ({
time: nowSec,
states: [
[
icao24,
'RCH123 ',
'United States',
nowSec,
nowSec,
-97.6,
30.3,
10_668,
false,
250,
95,
5,
null,
10_700,
null,
null,
null,
5,
],
],
}),
};
};
try {
await flightsLayer.update(viewer);
// A photo lookup would go out ahead of the route; wait for the route.
const deadline = Date.now() + 5_000;
while (!routeRequests.length && Date.now() < deadline)
await new Promise((done) => setTimeout(done, 20));
assert.deepEqual(routeRequests, ['/api/adsbdb/route/RCH123']);
assert.deepEqual(photoRequests, [], 'no photo lookup for a military hex');
assert.equal(flightsLayer.getTrackedInfo()?.icao24, icao24);
assert.equal(flightsLayer.getTrackedInfo()?.photo, null);
assert.equal(flightsLayer.getTrackedSubject()?.photo, null);
} finally {
globalThis.fetch = guardFetch;
setMilitaryLayerActive(militaryWasActive);
}
});
test('real civil track path creates no native label and publishes every cached host line', async () => {
const icao24 = 'civ001';
const position = Cesium.Cartesian3.fromDegrees(-97.6699, 30.1945, 10_668);
@@ -1181,6 +1439,39 @@ test('display floor: a grounded contact that drifted onto a higher cell is lifte
assert.ok(Math.abs(Cesium.Math.toDegrees(c.longitude) + 97.6604) < 1e-6);
});
test('display floor: reads the reading nearest the contact, not the cell centre', async () => {
_clearDisplayFloorStateForTest();
_clearMeshFloorCellsForTest();
setMeshFloorPreferred(true);
const realFetch = globalThis.fetch;
globalThis.fetch = async () =>
new Response(JSON.stringify({ results: [{ ellipsoid: 120 }] }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
try {
await resolveEllipsoidalGround([{ lat: 30.317, lon: -97.717 }]);
} finally {
globalThis.fetch = realFetch;
}
// A hangar roof over the cell's centre; the apron where the contact is.
assert.equal(reportValidatedMeshFloorCell(30.317, -97.717, 142), true);
assert.equal(reportValidatedMeshFloorCell(30.3173, -97.7173, 121), true);
const pos = Cesium.Cartesian3.fromDegrees(-97.7173, 30.3173, 100);
const out = _floorGroundedDisplayPositionForTest(
{ onGround: true },
pos,
false,
);
const c = _floorCarto(out);
assert.ok(
Math.abs(c.height - (121 + GROUND_FLOOR_LIFT_M)) < 0.05,
`height ${c.height} should be the apron's 121 + lift`,
);
_clearMeshFloorCellsForTest();
_clearDisplayFloorStateForTest();
});
test('display floor: an AIRBORNE contact over the same cell is never lifted', () => {
_clearDisplayFloorStateForTest();
_clearMeshFloorCellsForTest();
+1 -1
View File
@@ -13,7 +13,7 @@ import { isCalibratedAllocationRuntime } from '../../scripts/run-unit-tests.mjs'
*/
test('converged focus treatment stays within the GC-bracketed allocation budget', (t) => {
if (!isCalibratedAllocationRuntime()) {
return t.skip(`allocation budgets are calibrated for Node 24; running ${process.versions.node}`);
return t.skip(`allocation budgets are calibrated for Node 24 or 26; running ${process.versions.node}`);
}
const result = spawnSync(
process.execPath,
+1
View File
@@ -22,6 +22,7 @@ export const {
reportMeshFloorCell,
meshFloorSampleWithinPrior,
reportValidatedMeshFloorCell,
meshFloorPriorReady,
cachedMeshFloor,
_clearMeshFloorCellsForTest,
cachedGroundFloor,
+17 -1
View File
@@ -2385,11 +2385,27 @@ export class LayerLifecycle {
/**
* Ask presentation to repaint layer rows now, for data that lands outside
* the manager tick (Transit's proximity polls, Directions' route steps).
* @param {string} [layerId] - The layer whose row changed.
*/
refreshLayerStats() {
refreshLayerStats(layerId) {
this._dropRecoveredRefreshError(layerId);
this._publishActivity({ type: 'status' });
}
/**
* Drop a tick failure the layer's stats no longer report (the camera left
* that feed) instead of showing it until the next tick.
*/
_dropRecoveredRefreshError(layerId) {
const entry = layerId ? this.layers.get(layerId) : null;
if (!entry?.managerRefreshError || entry.refreshing) return;
const failure = refreshFailureFromStats(
this._moduleStats(entry),
entry.module.name || layerId,
);
if (!failure) entry.managerRefreshError = null;
}
_publishActivity(change) {
for (const callback of this._activityListeners) {
try {
-10
View File
@@ -15,16 +15,6 @@ export class DataLayerManager extends LayerLifecycle {
this._presentation.refresh();
}
/**
* Repaint the toggle panel now. For layers whose data arrives outside their
* manager tick (camera-driven loads such as Transit's proximity polls), so a
* row shows its count when the data lands instead of at the next interval.
* One DOM pass; skipped while the document is hidden.
*/
refreshLayerStats() {
this._refreshTogglePanel();
}
_buildMetaText(layer) {
return this._presentation.panel._buildMetaText(layer);
}
+25
View File
@@ -2677,6 +2677,31 @@ test('refreshLayerStats reaches presentation through the bare lifecycle', async
assert.deepEqual(changes, ['status']);
});
test('refreshLayerStats(layerId) drops a tick failure the layer no longer reports', async () => {
const { LayerLifecycle } = await import('./lifecycle.js');
const lifecycle = new LayerLifecycle({});
let stats = { count: 0, error: 'Feed unavailable' };
lifecycle.register({
id: 'feed',
name: 'Feed',
getStats: () => stats,
async update() {},
});
const entry = lifecycle.layers.get('feed');
entry.enabled = true;
entry.initialized = true;
entry.managerRefreshError = 'Feed unavailable';
lifecycle.refreshLayerStats('feed');
assert.equal(entry.managerRefreshError, 'Feed unavailable');
stats = { count: 0 };
lifecycle.refreshLayerStats();
assert.equal(entry.managerRefreshError, 'Feed unavailable');
lifecycle.refreshLayerStats('feed');
assert.equal(entry.managerRefreshError, null);
});
test('periodic polls pause hidden, catch up once when due, and dispose visibility listeners', async (t) => {
const listeners = new Set();
const doc = {
+178 -1
View File
@@ -24,7 +24,7 @@ import { sampleMeshFloorCells } from './meshFloorSampler.js';
import { resolveEllipsoidalGround } from './terrainHeights.js';
import {
cachedGroundFloor, cachedMeshFloor, setMeshFloorPreferred,
_clearMeshFloorCellsForTest,
_clearMeshFloorCellsForTest, reportValidatedMeshFloorCell,
} from './groundFloor.js';
/** Distinct site per test — terrainHeights' cache is module-global and warm
@@ -137,3 +137,180 @@ test('sampler: a cell just across the antimeridian is still near the viewer', ()
sampleMeshFloorCells(scene, [{ lat: -16.81, lon: 179.999 }], { viewerLat: -16.81, viewerLon: -179.999 });
assert.equal(calls, 2, 'about 200 m apart, so both cells are probed');
});
test('sampler: the probe goes where the point is, not to the cell centre', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
const asked = [];
const scene = fakeScene((carto) => {
asked.push(Cesium.Math.toDegrees(carto.longitude));
return 122.0;
});
const point = { lat: cell.lat + 0.0003, lon: cell.lon + 0.0004 };
sampleMeshFloorCells(scene, [point], { viewerLat: cell.lat, viewerLon: cell.lon });
assert.equal(asked.length, 1);
assert.ok(Math.abs(asked[0] - point.lon) < 1e-9, `probed at ${asked[0]}, not ${point.lon}`);
});
test('sampler: a viaduct and the street beside it in one cell keep their own heights', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
// A viaduct deck 9 m up along one line of the cell, the street elsewhere.
const deckLat = cell.lat + 0.0003;
let calls = 0;
const scene = fakeScene((carto) => {
calls += 1;
return Math.abs(Cesium.Math.toDegrees(carto.latitude) - deckLat) < 1e-7 ? 129.0 : 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
const onDeck = { lat: deckLat, lon: cell.lon };
const street = { lat: cell.lat - 0.0003, lon: cell.lon };
sampleMeshFloorCells(scene, [onDeck], opts);
sampleMeshFloorCells(scene, [street], opts);
assert.equal(calls, 2);
assert.equal(cachedMeshFloor(onDeck.lat, onDeck.lon + 0.0001), 129.0, 'the train stays on the deck');
assert.equal(cachedMeshFloor(street.lat, street.lon - 0.0001), 121.0, 'the bus stays on the street');
assert.equal(cachedGroundFloor(street.lat, street.lon), 121.0);
sampleMeshFloorCells(scene, [{ lat: deckLat, lon: cell.lon + 0.00001 }], opts);
assert.equal(calls, 2, 'a point next to one already probed is not probed again');
});
test('sampler: a roof over the cell centre does not lift a bus on the street', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
// A roof 22 m up covering the cell's centre; the street 30 m west of it.
const scene = fakeScene((carto) =>
Math.abs(Cesium.Math.toDegrees(carto.longitude) - cell.lon) < 0.0001 ? 142.0 : 121.0);
const bus = { lat: cell.lat, lon: cell.lon - 0.0003 };
sampleMeshFloorCells(scene, [bus], { viewerLat: cell.lat, viewerLon: cell.lon });
assert.equal(cachedGroundFloor(bus.lat, bus.lon), 121.0);
});
test('sampler: a second reading at the same spot keeps the lower one', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
assert.equal(reportValidatedMeshFloorCell(cell.lat, cell.lon, 131.0), true);
assert.equal(reportValidatedMeshFloorCell(cell.lat + 0.00002, cell.lon, 122.0), true);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 122.0);
assert.equal(reportValidatedMeshFloorCell(cell.lat, cell.lon + 0.00002, 140.0), true);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 122.0, 'a higher one never raises it');
});
test('sampler: a cell with a reading is probed a few times at most', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
let calls = 0;
const scene = fakeScene(() => {
calls += 1;
return 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
for (let i = 0; i < 20; i++)
sampleMeshFloorCells(
scene,
[{ lat: cell.lat - 0.0004 + (i % 5) * 0.0002, lon: cell.lon - 0.00045 + Math.floor(i / 5) * 0.0003 }],
opts,
);
assert.equal(calls, 8);
});
test('sampler: a cell with no accepted reading is probed again on every call', async () => {
reset();
const cell = nextSite();
let calls = 0;
const scene = fakeScene(() => {
calls += 1;
return 138.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
for (let i = 0; i < 3; i++) sampleMeshFloorCells(scene, [cell], opts);
assert.equal(calls, 3, 'no DEM prior yet, so nothing is kept and the cell is retried');
await seedDem(cell, 120.0);
sampleMeshFloorCells(scene, [cell], opts);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), 138.0, 'and lands once the prior is warm');
});
test('sampler: a spot whose reading is refused does not use up the cell', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
// A tower 260 m up where the first vehicle waits; the street elsewhere and
// a deck 9 m up along one line of the cell.
const towerLon = cell.lon + 0.0004;
const deckLat = cell.lat + 0.0003;
const scene = fakeScene((carto) => {
if (Math.abs(Cesium.Math.toDegrees(carto.longitude) - towerLon) < 1e-7) return 380.0;
return Math.abs(Cesium.Math.toDegrees(carto.latitude) - deckLat) < 1e-7 ? 129.0 : 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
for (let i = 0; i < 10; i++) sampleMeshFloorCells(scene, [{ lat: cell.lat, lon: towerLon }], opts);
assert.equal(cachedMeshFloor(cell.lat, cell.lon), null, 'the tower is refused every time');
sampleMeshFloorCells(scene, [{ lat: cell.lat - 0.0003, lon: cell.lon }], opts);
sampleMeshFloorCells(scene, [{ lat: deckLat, lon: cell.lon - 0.0003 }], opts);
assert.equal(cachedMeshFloor(deckLat, cell.lon - 0.0003), 129.0, 'the deck is still probed');
});
test('ground floor: a cell keeps at most sixteen readings', async () => {
reset();
const cell = nextSite();
await seedDem(cell, 120.0);
for (let i = 0; i < 40; i++) {
const lat = cell.lat - 0.00045 + (i % 8) * 0.0001;
const lon = cell.lon - 0.00045 + Math.floor(i / 8) * 0.0002;
reportValidatedMeshFloorCell(lat, lon, 121.0 + i);
}
// Readings 0..15 are kept; reading 39 (at the far corner) is not, so that
// spot answers from the nearest kept one.
assert.equal(cachedMeshFloor(cell.lat - 0.00045, cell.lon - 0.00045), 121.0);
assert.equal(cachedMeshFloor(cell.lat + 0.00025, cell.lon + 0.00035), 121.0 + 15);
});
test('sampler: a spot refused while the DEM was cold is probed again once it is warm', async () => {
reset();
const cell = nextSite();
const deckLat = cell.lat + 0.0003;
let calls = 0;
const scene = fakeScene((carto) => {
calls += 1;
return Math.abs(Cesium.Math.toDegrees(carto.latitude) - deckLat) < 1e-7 ? 129.0 : 121.0;
});
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
const onDeck = { lat: deckLat, lon: cell.lon };
sampleMeshFloorCells(scene, [onDeck], opts);
assert.equal(cachedMeshFloor(onDeck.lat, onDeck.lon), null, 'no prior, nothing kept');
await seedDem(cell, 120.0);
sampleMeshFloorCells(scene, [{ lat: cell.lat - 0.0003, lon: cell.lon }], opts);
sampleMeshFloorCells(scene, [onDeck], opts);
assert.equal(calls, 3);
assert.equal(cachedMeshFloor(onDeck.lat, onDeck.lon), 129.0);
});
test('sampler: a spot refused while the DEM prior was evicted is probed again', async () => {
const { createGroundFloor } = await import('../services/groundFloor.js');
const { createMeshFloorSampler } = await import('../services/meshFloorSampler.js');
let prior = 120.0;
const terrain = {
cachedRealEllipsoidalGround: () => prior,
resolveEllipsoidalGround: async () => {},
};
const groundFloor = createGroundFloor({ terrain });
const sampler = createMeshFloorSampler({ groundFloor });
const cell = { lat: 41.5, lon: -97.66 };
const deckLat = cell.lat + 0.0003;
const scene = fakeScene((carto) =>
Math.abs(Cesium.Math.toDegrees(carto.latitude) - deckLat) < 1e-7 ? 129.0 : 121.0);
const opts = { viewerLat: cell.lat, viewerLon: cell.lon };
const onDeck = { lat: deckLat, lon: cell.lon };
sampler.sampleMeshFloorCells(scene, [{ lat: cell.lat - 0.0003, lon: cell.lon }], opts);
prior = null; // the cell's DEM entry is evicted; the street reading stays
sampler.sampleMeshFloorCells(scene, [onDeck], opts);
assert.equal(groundFloor.cachedMeshFloor(onDeck.lat, onDeck.lon), 121.0);
prior = 120.0;
sampler.sampleMeshFloorCells(scene, [onDeck], opts);
assert.equal(groundFloor.cachedMeshFloor(onDeck.lat, onDeck.lon), 129.0);
});
+87 -1
View File
@@ -425,7 +425,7 @@ test('a dependency the user adopts stays on when Contacts turns off', async () =
assert.deepEqual(
released,
AWARENESS_DEPENDENCIES.filter((layerId) => layerId !== 'flights').sort(),
'the adopted layer is the user\'s now; the rest are still released',
"the adopted layer is the user's now; the rest are still released",
);
} finally {
runtime.restore();
@@ -1118,6 +1118,92 @@ test('production military tracked-subject label falls back to registration befor
}
});
test('the tracked airliner’s photo reaches the Contacts panel when it lands after selection', async () => {
const id = 'a1f2c3';
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
const sourceViewer = { camera: { positionCartographic: null }, scene: {} };
const runtime = installAwarenessRuntime();
const restores = [];
const meta = {
callsign: 'AAL100',
altitude: 10_668,
renderAltitudeM: 10_700,
velocity: 250,
true_track: 95,
klass: 'airliner',
onGround: false,
wasAirborne: true,
turnRateDps: 0,
rawLat: 30.21,
rawLon: -97.71,
photo: null,
};
try {
_setTrackedFlightRefreshStateForTest({
icao24: id,
entity: null,
billboard: { position, color: Cesium.Color.WHITE, show: true },
billboardCollection: { show: true, remove() {} },
viewer: sourceViewer,
meta,
});
runtime.viewer.trackedEntity = { gevTrackedId: `flights:${id}` };
replaceMethod(
militaryFlightsLayer,
'getTrackedSubject',
() => null,
restores,
);
replaceMethod(flightsLayer, 'trackById', () => true, restores);
replaceMethod(militaryFlightsLayer, 'trackById', () => true, restores);
militaryAwarenessLayer.setParams({ passive: false });
await nextTurn();
assert.equal(runtime.panel().view?.kind, 'results');
assert.equal(runtime.panel().view.photo, null, 'no photo before it lands');
// An unchanged refresh stays quiet.
const settledPublishes = runtime.panel().publishes;
await militaryAwarenessLayer.update();
assert.equal(runtime.panel().publishes, settledPublishes);
// The photo lands while the plane holds still: render-worthy on its own.
meta.photo = {
src: 'https://t.plnspttrs.net/1/a1f2c3_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/n100aa',
};
await militaryAwarenessLayer.update();
assert.deepEqual(runtime.panel().view.photo, {
src: 'https://t.plnspttrs.net/1/a1f2c3_280.jpg',
width: 280,
height: 186,
link: 'https://www.planespotters.net/photo/1/n100aa',
credit: 'Photo © Jane Doe',
});
// And it repaints once, not on every refresh.
const shownPublishes = runtime.panel().publishes;
await militaryAwarenessLayer.update();
assert.equal(runtime.panel().publishes, shownPublishes);
} finally {
restores.reverse().forEach((restore) => restore());
_setTrackedFlightRefreshStateForTest({
icao24: id,
entity: null,
billboard: { position, show: true },
billboardCollection: { show: false, remove() {} },
viewer: sourceViewer,
meta: {},
tracked: false,
});
runtime.restore();
}
});
test('a cached Context subject re-reads its label when enrichment lands after selection', async () => {
// The subject snapshot is captured once at selection. Selecting a
// callsign-less aircraft BEFORE adsbdb enrichment answers used to freeze the
+181 -8
View File
@@ -198,6 +198,157 @@ export function staleCoastLimitSeconds({
return Math.min(ceiling, Math.max(floor, contactLeadSec + grace));
}
/** @constant {number} Dead reckoning never moves a contact faster than this
* (1,500 kt, the trail's continuity limit), so a corrupt reported speed
* cannot fly a coasting plane hundreds of kilometres. */
export const COAST_MAX_SPEED_MPS = (1_500 * 1852) / 3600;
/** @constant {number} A contact with no fresh report coasts at most this long past it, whatever its source limit; there is no distance cap. */
export const STALE_COAST_MAX_SEC = 300;
/** @constant {number} A report this close to a known ground height holds
* instead of coasting. */
export const STALE_HOLD_MAX_HEIGHT_M = 150;
/**
* Whether a contact whose reports have stopped holds at its last reported
* position instead of coasting: it reported on the ground, or a known ground
* floor puts it within STALE_HOLD_MAX_HEIGHT_M of the ground (landing or
* taking off). A plane that low has no evidence of being anywhere but where
* it was last heard. Where the ground is unknown, barometric altitude is not
* read as height above it; the contact coasts under the stale cap.
* @param {object} report
* @param {boolean} [report.onGround]
* @param {number} [report.heightM] - Render height (ellipsoidal metres).
* @param {number} [report.groundM] - Ellipsoidal ground under the report, if known.
* @returns {boolean}
*/
export function staleHoldsAtLastReport({ onGround, heightM, groundM } = {}) {
if (onGround === true) return true;
return (
Number.isFinite(heightM) &&
Number.isFinite(groundM) &&
heightM - groundM < STALE_HOLD_MAX_HEIGHT_M
);
}
/**
* The hold-or-coast decision for a report, made once and kept on the report,
* so a ground floor that resolves while the contact coasts cannot flip it and
* snap the icon back. Height and position come from the report itself.
* @param {{position: Cesium.Cartesian3, staleHolds?: boolean}} fix - History
* fix; `staleHolds` is stored on it.
* @param {object} args
* @param {boolean} [args.onGround] - The contact's ground flag.
* @param {(latDeg: number, lonDeg: number) => number|null} [args.cachedGroundFloor]
* @returns {boolean}
*/
export function staleHoldsForFix(fix, { onGround, cachedGroundFloor } = {}) {
if (typeof fix.staleHolds === 'boolean') return fix.staleHolds;
const carto = Cesium.Cartographic.fromCartesian(
fix.position,
Cesium.Ellipsoid.WGS84,
_holdCarto,
);
const groundM =
carto && typeof cachedGroundFloor === 'function'
? cachedGroundFloor(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
)
: null;
fix.staleHolds = staleHoldsAtLastReport({
onGround,
heightM: carto?.height,
groundM,
});
return fix.staleHolds;
}
const _holdCarto = new Cesium.Cartographic();
/**
* Seconds a contact coasts past `newest` at a display time `elapsedSec`
* after it, counting any coast a synthetic fix already took since the real
* report it was built from (`reportEpochMs`), so a chain of synthetic fixes
* never coasts further than one report would.
* @param {object} args
* @param {{epochMs: number, reportEpochMs?: number, velocity?: number}} args.newest
* @param {number} args.elapsedSec - Display time past `newest`.
* @param {number} args.coastLimitSec - Source limit past `newest`.
* @param {boolean} args.holds
* @returns {number}
*/
export function staleCoastSecondsFrom({
newest,
elapsedSec,
coastLimitSec,
holds,
}) {
const alreadySec = Number.isFinite(newest?.reportEpochMs)
? Math.max(0, (newest.epochMs - newest.reportEpochMs) / 1000)
: 0;
return Math.max(
0,
staleCoastSeconds({
elapsedSec: elapsedSec + alreadySec,
coastLimitSec: coastLimitSec + alreadySec,
holds,
}) - alreadySec,
);
}
/** @constant {number} A coasted position sits at least this far (m) above the ground. */
export const COAST_FLOOR_LIFT_M = 1.5;
/**
* Lift a coasted position to COAST_FLOOR_LIFT_M above the ground where the
* ground is known; a coast runs level from the report and terrain may rise
* under it.
* @param {Cesium.Cartesian3} position - Mutated in place.
* @param {(latDeg: number, lonDeg: number) => number|null} [cachedGroundFloor]
* @returns {Cesium.Cartesian3}
*/
export function floorCoastedPosition(position, cachedGroundFloor) {
if (typeof cachedGroundFloor !== 'function') return position;
const carto = Cesium.Cartographic.fromCartesian(
position,
Cesium.Ellipsoid.WGS84,
_coastCarto,
);
if (!carto) return position;
const ground = cachedGroundFloor(
Cesium.Math.toDegrees(carto.latitude),
Cesium.Math.toDegrees(carto.longitude),
);
if (!Number.isFinite(ground) || carto.height >= ground + COAST_FLOOR_LIFT_M)
return position;
return Cesium.Cartesian3.fromRadians(
carto.longitude,
carto.latitude,
ground + COAST_FLOOR_LIFT_M,
Cesium.Ellipsoid.WGS84,
position,
);
}
const _coastCarto = new Cesium.Cartographic();
/**
* Seconds to coast past the last report: the elapsed time, bounded by the
* source's coast limit and STALE_COAST_MAX_SEC; none for a contact that
* holds.
* @param {object} args
* @param {number} args.elapsedSec - Display time past the last report.
* @param {number} args.coastLimitSec - From `staleCoastLimitSeconds`.
* @param {boolean} args.holds - From `staleHoldsAtLastReport`.
* @returns {number}
*/
export function staleCoastSeconds({ elapsedSec, coastLimitSec, holds }) {
if (holds || !(elapsedSec > 0)) return 0;
return Math.max(0, Math.min(elapsedSec, coastLimitSec, STALE_COAST_MAX_SEC));
}
/**
* Shortest-arc rate limiter: step `prevDeg` toward `targetDeg` by at most
* `maxDegPerSec * dtSec`. Seeds directly on the target when prev is null.
@@ -446,12 +597,21 @@ const _forwardFixOffset = new Cesium.Cartesian3();
* kinematics. This prevents a late course change from reprojecting the entire
* stale interval and snapping the rendered contact by kilometres.
*
* The same stale rules as the display apply: no fix for a contact that holds
* at its report (`staleHoldsForFix`, decided before calling), a coast of at
* most STALE_COAST_MAX_SEC counted from the real report
* (`reportEpochMs` carries it along a chain), and never below known ground.
* The result is a motion fix only, never a report for the trail.
*
* @param {{time: Cesium.JulianDate, epochMs?: number, position: Cesium.Cartesian3,
* velocity?: number, track?: number}} newest Existing immutable history fix.
* @param {{epochMs: number, velocity: number, track: number, turnRateDps?: number}} next
* velocity?: number, track?: number, staleHolds?: boolean, reportEpochMs?: number}} newest
* Existing immutable history fix.
* @param {{epochMs: number, velocity: number, track: number, turnRateDps?: number,
* cachedGroundFloor?: Function}} next
* New kinematics and the wall/source epoch at which they become authoritative.
* @returns {{time: Cesium.JulianDate, epochMs: number, position: Cesium.Cartesian3,
* velocity: number, track: number}|null} Forward synthetic fix, or null.
* velocity: number, track: number, staleHolds?: boolean, reportEpochMs: number}|null}
* Forward synthetic fix, or null.
*/
export function synthesizeForwardKinematicsFix(newest, next = {}) {
if (!newest?.position || !newest?.time || !Number.isFinite(next.epochMs))
@@ -461,12 +621,18 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) {
: Cesium.JulianDate.toDate(newest.time).getTime();
if (!Number.isFinite(startEpochMs) || next.epochMs <= startEpochMs)
return null;
if (newest.staleHolds === true) return null;
const previousVelocity = Number.isFinite(newest.velocity)
? Math.max(0, newest.velocity)
: 0;
const previousTrack = Number.isFinite(newest.track) ? newest.track : 0;
const dtSec = (next.epochMs - startEpochMs) / 1000;
const dtSec = staleCoastSecondsFrom({
newest: { epochMs: startEpochMs, reportEpochMs: newest.reportEpochMs },
elapsedSec: (next.epochMs - startEpochMs) / 1000,
coastLimitSec: Infinity,
holds: false,
});
arcOffsetEnu(
previousVelocity,
previousTrack,
@@ -485,14 +651,21 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) {
Cesium.Ellipsoid.WGS84,
_forwardFixEnu,
);
const position = Cesium.Matrix4.multiplyByPoint(
enu,
_forwardFixOffset,
new Cesium.Cartesian3(),
const position = floorCoastedPosition(
Cesium.Matrix4.multiplyByPoint(
enu,
_forwardFixOffset,
new Cesium.Cartesian3(),
),
next.cachedGroundFloor,
);
return {
time: Cesium.JulianDate.fromDate(new Date(next.epochMs)),
epochMs: next.epochMs,
reportEpochMs: Number.isFinite(newest.reportEpochMs)
? newest.reportEpochMs
: startEpochMs,
staleHolds: newest.staleHolds,
position,
velocity: Number.isFinite(next.velocity)
? Math.max(0, next.velocity)
+121
View File
@@ -0,0 +1,121 @@
/**
* @module planespottersPhoto
* @description Reads a Planespotters photo answer into the one credited
* thumbnail every surface shows. Planespotters lets the thumbnail be hotlinked
* on the condition that the photographer is credited next to it and the image
* links back to the photo's page, so a photo without a photographer, or whose
* image or page is not on Planespotters' own hosts, is "no photo": nothing
* arbitrary is ever shown or linked.
*
* Accepts the upstream answer (`GET https://api.planespotters.net/pub/photos/hex/{hex}`,
* `{photos: [...]}`), the cached server shape
* (`{found, thumbnail_large?, thumbnail: {src, width, height}, photographer,
* link}`), and an
* already-read photo (`{found, src, width, height, photographer, link}`).
* Pure: no fetch, no DOM.
*/
/** The image host: Planespotters' thumbnail CDN and its subdomains. */
const IMAGE_HOST = 'plnspttrs.net';
/** The only page host a photo may link to. */
const PAGE_HOST = 'www.planespotters.net';
const NO_PHOTO = Object.freeze({ found: false });
const isObject = (value) => Boolean(value) && typeof value === 'object';
/** The parsed `https:` URL, or null for anything else or with userinfo/port. */
function httpsUrl(value) {
if (typeof value !== 'string' || !value) return null;
let url;
try {
url = new URL(value);
} catch {
return null;
}
if (url.protocol !== 'https:' || url.username || url.password || url.port)
return null;
return url;
}
function imageSrc(value) {
const url = httpsUrl(value);
return url &&
(url.hostname === IMAGE_HOST || url.hostname.endsWith(`.${IMAGE_HOST}`))
? url.href
: null;
}
function pageLink(value) {
const url = httpsUrl(value);
return url && url.hostname === PAGE_HOST ? url.href : null;
}
function dimension(value) {
const number = Number(value);
return value != null && Number.isFinite(number) && number > 0
? Math.round(number)
: null;
}
/** One candidate `{src, width, height, photographer, link}`, checked. */
function checked({ src, width, height, photographer, link }) {
const credit = typeof photographer === 'string' ? photographer.trim() : '';
const image = imageSrc(src);
const page = pageLink(link);
if (!credit || !image || !page) return null;
return {
found: true,
src: image,
width: dimension(width),
height: dimension(height),
photographer: credit,
link: page,
};
}
/** The upstream photo's candidates, large thumbnail first. */
function upstreamCandidates(photo) {
if (!photo || typeof photo !== 'object') return [];
return [photo.thumbnail_large, photo.thumbnail]
.filter((thumb) => thumb && typeof thumb === 'object')
.map((thumb) => ({
src: thumb.src,
width: thumb.size?.width,
height: thumb.size?.height,
photographer: photo.photographer,
link: photo.link,
}));
}
/**
* Read a Planespotters answer into the first photo that passes the checks.
* @param {*} payload Upstream, cached-server, or already-read photo.
* @returns {{found: true, src: string, width: ?number, height: ?number,
* photographer: string, link: string} | {found: false}}
*/
export function parsePlanespottersPhoto(payload) {
if (!payload || typeof payload !== 'object') return NO_PHOTO;
let candidates;
if (Array.isArray(payload.photos)) {
candidates = payload.photos.flatMap(upstreamCandidates);
} else if (payload.found !== true) {
return NO_PHOTO;
} else if (isObject(payload.thumbnail) || isObject(payload.thumbnail_large)) {
// Large first, as for the upstream answer; each must pass the checks.
candidates = [payload.thumbnail_large, payload.thumbnail]
.filter(isObject)
.map((thumb) => ({
...thumb,
photographer: payload.photographer,
link: payload.link,
}));
} else {
candidates = [payload];
}
for (const candidate of candidates) {
const photo = checked(candidate);
if (photo) return photo;
}
return NO_PHOTO;
}
+200
View File
@@ -0,0 +1,200 @@
// src/data/planespottersPhoto.test.mjs — the Planespotters photo answer is read
// into one credited thumbnail, and nothing outside Planespotters' own hosts is
// ever shown or linked.
import test from 'node:test';
import assert from 'node:assert/strict';
import { parsePlanespottersPhoto } from './planespottersPhoto.js';
const UPSTREAM = Object.freeze({
photos: [
{
id: '1745410',
thumbnail: {
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_t.jpg',
size: { width: 200, height: 133 },
},
thumbnail_large: {
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_280.jpg',
size: { width: 420, height: 280 },
},
link: 'https://www.planespotters.net/photo/1745410/n160an-american-airlines-airbus-a321-231-wl?utm_source=api',
photographer: 'Jan Seler',
},
],
});
const PHOTO = Object.freeze({
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/n160an-american-airlines-airbus-a321-231-wl?utm_source=api',
});
const photo = (overrides) => ({
photos: [{ ...UPSTREAM.photos[0], ...overrides }],
});
test('the upstream answer maps to the large thumbnail, its size, credit and link', () => {
assert.deepEqual(parsePlanespottersPhoto(UPSTREAM), PHOTO);
});
test('the small thumbnail stands in when the large one is missing', () => {
assert.deepEqual(parsePlanespottersPhoto(photo({ thumbnail_large: null })), {
...PHOTO,
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_t.jpg',
width: 200,
height: 133,
});
});
test('a server’s cached shape reads the same way', () => {
assert.deepEqual(
parsePlanespottersPhoto({
found: true,
thumbnail: { src: PHOTO.src, width: 420, height: 280 },
photographer: 'Jan Seler',
link: PHOTO.link,
}),
PHOTO,
);
assert.deepEqual(parsePlanespottersPhoto({ found: false }), {
found: false,
});
});
test('a server’s cached shape prefers its large thumbnail', () => {
assert.deepEqual(
parsePlanespottersPhoto({
found: true,
thumbnail: {
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_t.jpg',
width: 200,
height: 133,
},
thumbnail_large: { src: PHOTO.src, width: 420, height: 280 },
photographer: 'Jan Seler',
link: PHOTO.link,
}),
PHOTO,
);
});
test('a server’s cached shape falls back to its small thumbnail when the large one fails the checks', () => {
const small = {
src: 'https://t.plnspttrs.net/33043/1745410_822dfe330c_t.jpg',
width: 200,
height: 133,
};
for (const thumbnail_large of [
{ src: 'https://evil.example/a.jpg', width: 420, height: 280 },
null,
]) {
assert.deepEqual(
parsePlanespottersPhoto({
found: true,
thumbnail: small,
thumbnail_large,
photographer: 'Jan Seler',
link: PHOTO.link,
}),
{ ...PHOTO, ...small },
JSON.stringify(thumbnail_large),
);
}
});
test('no photo, junk, and missing fields are "no photo"', () => {
for (const payload of [
{ photos: [] },
{},
null,
undefined,
'nope',
{ photos: 'nope' },
{ photos: [null] },
photo({ photographer: '' }),
photo({ photographer: ' ' }),
photo({ photographer: 42 }),
photo({ link: '' }),
photo({ thumbnail: null, thumbnail_large: null }),
]) {
assert.deepEqual(
parsePlanespottersPhoto(payload),
{ found: false },
JSON.stringify(payload),
);
}
});
test('a src outside https *.plnspttrs.net is dropped', () => {
for (const src of [
'http://t.plnspttrs.net/a.jpg',
'https://plnspttrs.net.evil.example/a.jpg',
'https://evil.example/t.plnspttrs.net/a.jpg',
'https://t.plnspttrs.net.evil.example/a.jpg',
'https://[email protected]/a.jpg',
'https://t.plnspttrs.net:8443/a.jpg',
'javascript:alert(1)',
'//t.plnspttrs.net/a.jpg',
'not a url',
]) {
assert.deepEqual(
parsePlanespottersPhoto(
photo({
thumbnail_large: { src, size: { width: 420, height: 280 } },
thumbnail: { src, size: { width: 200, height: 133 } },
}),
),
{ found: false },
src,
);
}
});
test('a link anywhere but https://www.planespotters.net is dropped', () => {
for (const link of [
'http://www.planespotters.net/photo/1',
'https://planespotters.net/photo/1',
'https://www.planespotters.net.evil.example/photo/1',
'https://evil.example/?u=https://www.planespotters.net/',
'https://user:[email protected]/photo/1',
'https://www.planespotters.net:444/photo/1',
'javascript:alert(1)',
]) {
assert.deepEqual(
parsePlanespottersPhoto(photo({ link })),
{ found: false },
link,
);
}
});
test('the first photo that passes the checks is the one shown', () => {
const second = {
...UPSTREAM.photos[0],
photographer: 'Second Spotter',
};
assert.deepEqual(
parsePlanespottersPhoto({
photos: [
{ ...UPSTREAM.photos[0], link: 'https://evil.example/' },
second,
],
}),
{ ...PHOTO, photographer: 'Second Spotter' },
);
});
test('a missing size is null and the credit is trimmed', () => {
assert.deepEqual(
parsePlanespottersPhoto(
photo({
photographer: ' Jan Seler ',
thumbnail_large: { src: PHOTO.src },
}),
),
{ ...PHOTO, width: null, height: null },
);
});
+10 -1
View File
@@ -46,7 +46,13 @@ function alongTrackKm(position, origin, destination) {
}
const NEAR_ENDPOINT_KM = 130;
/** Least allowed distance off the great circle, and how far past either
* endpoint the plane may be along it. */
const CROSS_TRACK_KM = 200;
/** On a long route the allowed distance off the great circle grows to this
* share of its length: airways and winds take a coast-to-coast flight several
* hundred kilometres off it (JFK–SFO: 623 km). */
const CROSS_TRACK_ROUTE_FRACTION = 0.15;
const LOW_ALT_M = 3700; // ~12 000 ft
const VERT_TREND_MPS = 2; // ~400 fpm
const LOCAL_AIRPORT_KM = 150;
@@ -90,6 +96,9 @@ export function routePlausible({
// existing loose check when the segment cannot be judged reliably.
const segmentKnown =
routeKm > 0.001 && routeKm < Math.PI * EARTH_RADIUS_KM - 0.001;
const corridorKm = segmentKnown
? Math.max(CROSS_TRACK_KM, CROSS_TRACK_ROUTE_FRACTION * routeKm)
: CROSS_TRACK_KM;
geomOk =
Math.abs(
crossTrackKm(
@@ -100,7 +109,7 @@ export function routePlausible({
destination.lat,
destination.lon,
),
) < CROSS_TRACK_KM &&
) < corridorKm &&
(!segmentKnown ||
(segmentAlongKm >= -CROSS_TRACK_KM &&
segmentAlongKm <= routeKm + CROSS_TRACK_KM));
+18
View File
@@ -27,6 +27,24 @@ test('plane in London with an SFO→LAX route: implausible', () => {
}), false);
});
test('a long route allows a wider corridor; a short one does not', () => {
// JFK→SFO over Kansas, 384 km south of the great circle.
assert.equal(routePlausible({
latDeg: 38.21, lonDeg: -99.69, altitudeM: 10370, verticalRateMps: 0,
origin: JFK, destination: SFO,
}), true);
// 516 km off the 543 km SFO→LAX route is still the wrong route.
assert.equal(routePlausible({
latDeg: 37.9, lonDeg: -115.0, altitudeM: 10000, verticalRateMps: 0,
origin: SFO, destination: LAX,
}), false);
// 960 km off, past 15 % of the 4,152 km JFK→SFO route, is still wrong.
assert.equal(routePlausible({
latDeg: 33.0, lonDeg: -99.69, altitudeM: 10000, verticalRateMps: 0,
origin: JFK, destination: SFO,
}), false);
});
test('vertical trend: low climbing plane near SFO — origin must be local', () => {
const nearSfo = { latDeg: 37.7, lonDeg: -122.4, altitudeM: 2500 };
// JFK→SFO passes geometry (near destination), but a CLIMBING plane here just
+4 -1
View File
@@ -140,7 +140,10 @@ test('the actual native tracked label hides the wrong leg and keeps a healthy ro
].map((name) => [name, {}]),
);
services.aircraftPresentation = { isTr3b: () => false };
const parts = { queries: { _contactLabel: (_, info) => info.callsign } };
const parts = {
queries: { _contactLabel: (_, info) => info.callsign },
motion: { _signalLost: () => null },
};
const tracking = createTracking({ flightState, services, parts });
for (const [position, expected] of [
[beyond, false],
+53
View File
@@ -0,0 +1,53 @@
/**
* @file Upstream-request accounting shared by the keyed tile proxies.
*
* A soft cap per UTC period, persisted as `{date, count}` so it survives a
* restart. Nothing here is provider-specific: the caller picks the period by
* the key it passes, and decides what happens over the cap.
*
* Zero dependencies and Cesium-free, so providers and browser helpers can
* import it and node:test can exercise it directly.
*
* @module data/tileBudget
*/
/**
* UTC calendar-day key for budget bucketing.
*
* @param {number} [epochMs=Date.now()] - Timestamp in ms.
* @returns {string} 'YYYY-MM-DD' in UTC.
*/
export function utcDayKey(epochMs = Date.now()) {
return new Date(epochMs).toISOString().slice(0, 10);
}
/**
* Normalize a persisted budget state against the current period key.
* Rolls the counter to zero when the period changes; replaces missing/corrupt
* state. Returns the SAME object when it is already valid for `periodKey`
* (cheap to call on every request).
*
* @param {{date:string, count:number}|null|undefined} state - Persisted state.
* @param {string} periodKey - Current period key, e.g. from `utcDayKey`.
* @returns {{date:string, count:number}} Valid state for `periodKey`.
*/
export function normalizeBudget(state, periodKey) {
const valid =
Boolean(state) &&
state.date === periodKey &&
Number.isFinite(state.count) &&
state.count >= 0;
return valid ? state : { date: periodKey, count: 0 };
}
/**
* Whether the soft cap for the current period has been reached.
*
* @param {{count:number}} state - Normalized budget state.
* @param {number} limit - Budget per period; non-positive/invalid never blocks.
* @returns {boolean} True when `count >= limit`.
*/
export function isOverBudget(state, limit) {
if (!Number.isFinite(limit) || limit <= 0) return false;
return state.count >= limit;
}
+10
View File
@@ -0,0 +1,10 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { isOverBudget, normalizeBudget, utcDayKey } from './tileBudget.js';
import * as tomtom from './tomtomTiles.js';
test('tile budget helpers live in one module and TomTom re-exports them', () => {
assert.equal(tomtom.utcDayKey, utcDayKey);
assert.equal(tomtom.normalizeBudget, normalizeBudget);
assert.equal(tomtom.isOverBudget, isOverBudget);
});
+6 -40
View File
@@ -1,9 +1,10 @@
/**
* @file Pure tile math + budget accounting for the TomTom traffic-flow proxy.
* @file Pure tile math for the TomTom traffic-flow proxy; budget helpers are
* re-exported from `./tileBudget.js`.
*
* Shared by the `/api/tomtom` vite plugin (server-side: coordinate validation,
* daily budget governor) and `src/layers/traffic/flowSource.js` (client-side: which tiles
* cover the current traffic fetch bounds). Zero dependencies, Cesium-free, so
* cover the current traffic fetch bounds). No external dependencies, Cesium-free, so
* both sides can unit-test against it with node:test.
*
* Slippy scheme: standard Web Mercator XYZ, y grows southward
@@ -131,42 +132,7 @@ export function tilesForBounds(bounds, zoom = 12, { maxTiles = 64 } = {}) {
// ─── Daily budget accounting ───────────────────────────────
/**
* UTC calendar-day key for budget bucketing.
*
* @param {number} [epochMs=Date.now()] - Timestamp in ms.
* @returns {string} 'YYYY-MM-DD' in UTC.
* Re-exported from `./tileBudget.js`, which keyed tile proxies share. The
* traffic provider and its tests keep one import for tile math and budget.
*/
export function utcDayKey(epochMs = Date.now()) {
return new Date(epochMs).toISOString().slice(0, 10);
}
/**
* Normalize a persisted budget state against today's UTC day key.
* Rolls the counter to zero on day change; replaces missing/corrupt state.
* Returns the SAME object when it is already valid for `dayKey` (cheap to
* call on every request).
*
* @param {{date:string, count:number}|null|undefined} state - Persisted state.
* @param {string} dayKey - Today's UTC day key (from `utcDayKey`).
* @returns {{date:string, count:number}} Valid state for `dayKey`.
*/
export function normalizeBudget(state, dayKey) {
const valid =
Boolean(state) &&
state.date === dayKey &&
Number.isFinite(state.count) &&
state.count >= 0;
return valid ? state : { date: dayKey, count: 0 };
}
/**
* Whether the daily soft cap has been reached.
*
* @param {{count:number}} state - Normalized budget state.
* @param {number} limit - Daily tile budget; non-positive/invalid never blocks.
* @returns {boolean} True when `count >= limit`.
*/
export function isOverBudget(state, limit) {
if (!Number.isFinite(limit) || limit <= 0) return false;
return state.count >= limit;
}
export { utcDayKey, normalizeBudget, isOverBudget } from './tileBudget.js';
+607
View File
@@ -0,0 +1,607 @@
/**
* @module trailContinuity
* @description Where a tracked aircraft's trail lifts the pen.
*
* A trail is a chronological list of fixes `{position, timeMs, nullAltitude,
* breakBefore, drawn}`: reports, and (`drawn`) points where the tracked icon
* was drawn between them. Between two consecutive fixes that are not one path, a new
* segment starts and nothing is drawn between them: no dashes, no arcs.
* Nothing is dropped except the oldest fixes past the layer's point limit.
*
* Two points are not one path when time does not advance, when the gap is
* longer than 48 minutes (a coverage hole or a separate flight), when the
* implied great-circle speed is over 1,500 kt, or when either point has no
* reported altitude. A parked aircraft is the exception: a pair under three
* hours apart within 0.1 nm stays one path.
*
* Civil and military flight tracking share these rules.
*/
import * as Cesium from 'cesium';
/** @constant {number} A gap longer than this is a coverage hole or a separate flight. */
export const TRAIL_CONTINUITY_MAX_GAP_MS = 48 * 60_000;
/** @constant {number} A pair implying more than this great-circle speed is not one path. */
export const TRAIL_CONTINUITY_MAX_SPEED_KT = 1_500;
/** @constant {number} A parked aircraft may stop reporting this long and stay one path. */
export const TRAIL_STATIONARY_HOLD_MAX_GAP_MS = 3 * 60 * 60_000;
/** @constant {number} How close (nautical miles) two points must be to count as parked. */
export const TRAIL_STATIONARY_HOLD_MAX_DISTANCE_NM = 0.1;
/** @constant {number} The head never joins a body point farther than this from the aircraft. */
export const TRAIL_HEAD_JOIN_MAX_M = 150_000;
const METRES_PER_NM = 1852;
/** @constant {number} Mean Earth radius (m) for great-circle trail distances. */
const EARTH_MEAN_RADIUS_M = 6_371_008.8;
/**
* Whether two consecutive trail points belong to different paths. Time that
* does not advance, a gap over TRAIL_CONTINUITY_MAX_GAP_MS or an implied
* speed over TRAIL_CONTINUITY_MAX_SPEED_KT breaks the line, except for a
* parked aircraft: a pair under three hours apart within 0.1 nm.
* @param {number} deltaMs - Later point's time minus the earlier one's.
* @param {number} distanceM - Great-circle distance between the points.
* @returns {boolean}
*/
export function trailPairBreaks(deltaMs, distanceM) {
if (!(deltaMs > 0) || !Number.isFinite(distanceM)) return true;
const distanceNm = distanceM / METRES_PER_NM;
if (
deltaMs <= TRAIL_STATIONARY_HOLD_MAX_GAP_MS &&
distanceNm <= TRAIL_STATIONARY_HOLD_MAX_DISTANCE_NM
)
return false;
return (
deltaMs > TRAIL_CONTINUITY_MAX_GAP_MS ||
distanceNm / (deltaMs / 3_600_000) > TRAIL_CONTINUITY_MAX_SPEED_KT
);
}
/**
* Whether the head segment may join the last body point to the aircraft:
* within TRAIL_HEAD_JOIN_MAX_M and not broken under `trailPairBreaks`.
* @param {number} deltaMs - Current time minus the body point's time.
* @param {number} distanceM - Distance from the body point to the aircraft.
* @returns {boolean}
*/
export function trailHeadJoins(deltaMs, distanceM) {
return (
distanceM <= TRAIL_HEAD_JOIN_MAX_M && !trailPairBreaks(deltaMs, distanceM)
);
}
/**
* Great-circle distance between two trail positions, in metres.
* @param {Cesium.Cartesian3} a
* @param {Cesium.Cartesian3} b
* @returns {number}
*/
export function trailDistanceM(a, b) {
return Cesium.Cartesian3.angleBetween(a, b) * EARTH_MEAN_RADIUS_M;
}
/**
* Whether the pen lifts between two consecutive fixes.
* @param {object|undefined} prev - Earlier fix, if any.
* @param {object} next - Later fix.
* @returns {boolean}
*/
export function trailFixBreaks(prev, next) {
if (!prev || prev.nullAltitude || next.nullAltitude) return true;
// A recorded point is where the icon was drawn; the speed between it and a
// report it was eased onto is not a flight speed, so only the gap counts.
if (prev.drawn || next.drawn)
return Math.abs(next.timeMs - prev.timeMs) > TRAIL_CONTINUITY_MAX_GAP_MS;
return trailPairBreaks(
next.timeMs - prev.timeMs,
trailDistanceM(prev.position, next.position),
);
}
/**
* Build backfill fixes from chronological waypoints. Every waypoint with a
* position is kept. A waypoint without one (no altitude and no known ground)
* is skipped, and the line still breaks there.
* @param {{position: Cesium.Cartesian3|null, timeMs: number, nullAltitude: boolean}[]} waypoints
* @returns {{fixes: object[], breakAfter: boolean}} The fixes, and whether the
* line breaks after the last one because trailing waypoints were skipped.
*/
export function trailBackfillFixes(waypoints) {
const fixes = [];
let skipped = false;
for (const { position, timeMs, nullAltitude } of waypoints) {
if (!position) {
skipped = true;
continue;
}
const fix = { position, timeMs, nullAltitude: !!nullAltitude };
fix.breakBefore = skipped || trailFixBreaks(fixes[fixes.length - 1], fix);
skipped = false;
fixes.push(fix);
}
return { fixes, breakAfter: skipped };
}
/**
* Put backfill fixes ahead of the live trail. The join follows the same
* rule, so a distant history tail never connects to the first live fix.
* Past `maxPoints` the oldest recorded points go first, then the oldest
* reports.
* @param {{fixes: object[], breakAfter: boolean}} backfill
* @param {object[]} live - Live fixes; the first one's break is recomputed.
* @param {number} maxPoints - Point limit across all segments.
* @returns {object[]} The joined trail.
*/
export function joinTrailBackfill({ fixes, breakAfter }, live, maxPoints) {
if (!fixes.length) return live;
if (live.length)
live[0].breakBefore =
breakAfter || trailFixBreaks(fixes[fixes.length - 1], live[0]);
return keepTrailLimit(fixes.concat(live), maxPoints);
}
/**
* How many fixes the drawn body holds: every fix at or before the display
* time, where the aircraft is drawn. Fixes ahead of it (reports newer than
* the delayed display) are reached by the head segment instead, so the trail
* never runs past the aircraft, and once the display passes the newest
* report the body ends there.
* @param {object[]} fixes
* @param {number} displayMs - Time the aircraft is drawn at.
* @returns {number}
*/
export function trailBodyCount(fixes, displayMs) {
let count = fixes.length;
while (count > 0 && fixes[count - 1].timeMs > displayMs) count -= 1;
return count;
}
/**
* Leave out the newest recorded points that lie inside the aircraft's 3D
* model, so the body never runs through the fuselage; the head then runs
* from the newest point outside the model to the plane. Reports are kept.
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @param {Cesium.Cartesian3|null} modelCenter - The model's centre, or null
* when no model is the visual.
* @param {number|null} envelopeM - The model's radius (m).
* @returns {number}
*/
export function trailBodyCountOutsideModel(
fixes,
count,
modelCenter,
envelopeM,
) {
if (!modelCenter || !(envelopeM > 0)) return count;
while (
count > 0 &&
fixes[count - 1].drawn &&
Cesium.Cartesian3.distance(fixes[count - 1].position, modelCenter) <
envelopeM
)
count -= 1;
return count;
}
/**
* The drawn trail body, split at breaks: the first `count` fixes.
* @param {object[]} fixes
* @param {number} count - From `trailBodyCount`.
* @returns {Cesium.Cartesian3[][]}
*/
export function trailBodySegments(fixes, count) {
const segments = [];
for (let i = 0; i < count; i++) {
const fix = fixes[i];
// A live report with no altitude keeps no position; it only breaks the line.
if (!fix.position) continue;
if (fix.breakBefore || !segments.length) segments.push([]);
segments[segments.length - 1].push(fix.position);
}
return segments;
}
/**
* Draw body segments. A trail without breaks support draws only the newest
* segment, never a line across a break.
* @param {{setSegments?: Function, setPositions: Function}} trail
* @param {Cesium.Cartesian3[][]} segments
*/
export function drawTrailSegments(trail, segments) {
if (typeof trail.setSegments === 'function') trail.setSegments(segments);
else trail.setPositions(segments[segments.length - 1] ?? []);
}
/** @constant {number} A head shorter than this (m) is not drawn: the aircraft is holding at its last report. */
const TRAIL_HEAD_MIN_M = 0.5;
/**
* The body fix the head segment starts from, or null when the head is not
* drawn: no body yet, the aircraft holding at that fix, a body point more
* than 150 km from the aircraft, or one too long ago or too far away to be
* one path.
* @param {object[]} fixes
* @param {Cesium.Cartesian3} head - Displayed aircraft position.
* @param {number} nowMs - Current time.
* @param {number} count - Body fixes, from `trailBodyCount`.
* @returns {object|null}
*/
export function trailHeadStartFix(fixes, head, nowMs, count) {
if (count < 1 || !head) return null;
const last = fixes[count - 1];
if (!last.position) return null;
if (Cesium.Cartesian3.distance(last.position, head) < TRAIL_HEAD_MIN_M)
return null;
return trailHeadJoins(
nowMs - last.timeMs,
trailDistanceM(last.position, head),
)
? last
: null;
}
/**
* Epoch ms of a position-history fix (`{epochMs?, time}`).
* @param {object|undefined} fix
* @returns {number} NaN when unknown.
*/
export function historyFixEpochMs(fix) {
if (Number.isFinite(fix?.epochMs)) return fix.epochMs;
return fix?.time ? Cesium.JulianDate.toDate(fix.time).getTime() : NaN;
}
/** @constant {number} The tracked icon's drawn position is recorded at least this often (ms of display time)... */
export const TRAIL_RECORD_STEP_MS = 1_000;
/** @constant {number} ...or whenever it has moved this far (m), whichever comes first. */
export const TRAIL_RECORD_STEP_M = 150;
/** @constant {number} A recorded point is kept only where dropping it would move the line by more than this (m) across the track or in height. */
export const TRAIL_THIN_TOLERANCE_M = 30;
/** @constant {number} A recorded point is kept where dropping it would leave a straight piece longer than this (m), so a long leg still has vertices. */
export const TRAIL_THIN_MAX_SPAN_M = 10_000;
/** @constant {number} A kept point stands in for at most this many dropped positions; past it the point is kept. */
const TRAIL_THIN_MAX_ABSORBED = 512;
/** @constant {number} A recorded point is dropped where the line turns back sharper than this (degrees)... */
export const TRAIL_SPUR_TURN_DEG = 120;
/** @constant {number} ...over a step shorter than this (m). */
export const TRAIL_SPUR_MAX_STEP_M = 500;
/** @constant {number} A recorded point closer than this (m) to the previous one is not kept: the aircraft is holding. */
const TRAIL_RECORD_MIN_STEP_M = 1;
const _u = new Cesium.Cartesian3();
const _v = new Cesium.Cartesian3();
/** Cosine of the turn at `b` on the way a → b → c, or NaN for a zero step. */
function turnCos(a, b, c) {
Cesium.Cartesian3.subtract(b, a, _u);
Cesium.Cartesian3.subtract(c, b, _v);
const lu = Cesium.Cartesian3.magnitude(_u);
const lv = Cesium.Cartesian3.magnitude(_v);
if (!(lu > 0 && lv > 0)) return NaN;
return Cesium.Cartesian3.dot(_u, _v) / (lu * lv);
}
const SPUR_COS = Math.cos(Cesium.Math.toRadians(TRAIL_SPUR_TURN_DEG));
/** Whether entry `i` and its neighbours are one drawn piece of line. */
function joinedAt(fixes, i) {
const a = fixes[i - 1];
const b = fixes[i];
const c = fixes[i + 1];
return (
a?.position &&
b?.position &&
c?.position &&
!b.breakBefore &&
!c.breakBefore
);
}
/** Whether the line turns back on itself at entry `i` over a short step. */
function spurAt(fixes, i) {
if (!joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const b = fixes[i].position;
const c = fixes[i + 1].position;
if (
Math.min(
Cesium.Cartesian3.distance(a, b),
Cesium.Cartesian3.distance(b, c),
) > TRAIL_SPUR_MAX_STEP_M
)
return false;
return turnCos(a, b, c) < SPUR_COS;
}
/** Remove entry `i` and re-judge the break before the entry that takes its place. */
function removeAt(fixes, i) {
fixes.splice(i, 1);
if (i < fixes.length)
fixes[i].breakBefore = trailFixBreaks(fixes[i - 1], fixes[i]);
}
/**
* Keep the point limit: drop the oldest recorded point first, and the oldest
* report only when no recorded point is left.
* @param {object[]} fixes - The trail, mutated.
* @param {number} maxPoints
* @returns {object[]} `fixes`.
*/
function keepTrailLimit(fixes, maxPoints) {
let excess = fixes.length - maxPoints;
if (excess <= 0) return fixes;
for (let i = 0; i < fixes.length && excess > 0;) {
if (fixes[i].drawn) {
removeAt(fixes, i);
excess -= 1;
} else i += 1;
}
if (excess > 0) fixes.splice(0, excess);
return fixes;
}
const _ab = new Cesium.Cartesian3();
const _ap = new Cesium.Cartesian3();
const _off = new Cesium.Cartesian3();
const _up = new Cesium.Cartesian3();
/** Whether `p` lies within the thinning tolerance of segment a → b, across the track and in height. */
function nearSegment(p, a, b) {
Cesium.Cartesian3.subtract(b, a, _ab);
Cesium.Cartesian3.subtract(p, a, _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.multiplyByScalar(_ab, t, _off);
Cesium.Cartesian3.subtract(_ap, _off, _off);
Cesium.Cartesian3.normalize(p, _up);
const vertical = Cesium.Cartesian3.dot(_off, _up);
const across = Math.sqrt(
Math.max(0, Cesium.Cartesian3.magnitudeSquared(_off) - vertical * vertical),
);
return (
Math.abs(vertical) <= TRAIL_THIN_TOLERANCE_M &&
across <= TRAIL_THIN_TOLERANCE_M
);
}
/**
* Drop recorded point `i` when the line without it stays within the
* tolerance of every position it stood for, and the straight piece left is
* no longer than TRAIL_THIN_MAX_SPAN_M. The positions it stood for go on to
* the next entry. Reports are never dropped.
* @returns {boolean} Whether it was dropped.
*/
function thinAt(fixes, i) {
const entry = fixes[i];
if (!entry?.drawn || entry.sealed || !joinedAt(fixes, i)) return false;
const a = fixes[i - 1].position;
const next = fixes[i + 1];
if (next.sealed) return false;
const b = next.position;
if (Cesium.Cartesian3.distance(a, b) > TRAIL_THIN_MAX_SPAN_M) return false;
const stood = entry.absorbed ?? [];
const nextStood = next.absorbed ?? [];
if (stood.length + nextStood.length + 1 > TRAIL_THIN_MAX_ABSORBED)
return false;
if (!nearSegment(entry.position, a, b)) return false;
for (const p of stood) if (!nearSegment(p.position, a, b)) return false;
for (const p of nextStood) if (!nearSegment(p.position, a, b)) return false;
next.absorbed = stood.concat(
[{ position: entry.position, timeMs: entry.timeMs }],
nextStood,
);
removeAt(fixes, i);
return true;
}
/**
* Thin the recorded points either side of entry `i`, reaching past a
* neighbouring report: the point recorded just before a report is only
* judged once the line goes on beyond it.
*/
function thinAround(fixes, i) {
if (!thinAt(fixes, i + 1) && fixes[i + 1] && !fixes[i + 1].drawn)
thinAt(fixes, i + 2);
if (thinAt(fixes, i - 1)) i -= 1;
else if (fixes[i - 1] && !fixes[i - 1].drawn) thinAt(fixes, i - 2);
}
/**
* Drop recorded points that make a spur next to entry `i`. Reports are never
* dropped; at a report the recorded neighbour is dropped instead.
* @returns {number} The index entry `i` ends up at.
*/
function removeSpursAround(fixes, i) {
for (let guard = 0; guard < 64; guard++) {
let changed = false;
for (const j of [i - 1, i, i + 1]) {
if (!spurAt(fixes, j)) continue;
let drop = -1;
if (fixes[j].drawn) drop = j;
else if (fixes[j + 1]?.drawn) drop = j + 1;
else if (fixes[j - 1]?.drawn) drop = j - 1;
if (drop < 0) continue;
removeAt(fixes, drop);
if (drop < i) i -= 1;
changed = true;
break;
}
if (!changed) break;
}
return i;
}
/** Index a fix at `timeMs` goes in at: after every entry at or before it. */
function insertionIndex(fixes, timeMs) {
let i = fixes.length;
while (i > 0 && fixes[i - 1].timeMs > timeMs) i -= 1;
return i;
}
/**
* Insert an entry at `i`, judge both breaks, remove spurs, thin the recorded
* points either side and keep the limit.
*/
function insertAt(fixes, i, entry, maxPoints) {
fixes.splice(i, 0, entry);
entry.breakBefore = trailFixBreaks(fixes[i - 1], entry);
const after = fixes[i + 1];
if (after) {
after.breakBefore = trailFixBreaks(entry, after);
// Positions the next entry stood for that come before this one are now
// on this entry's side.
if (after.absorbed?.length) {
const mine = after.absorbed.filter((p) => p.timeMs < entry.timeMs);
if (mine.length) {
entry.absorbed = mine;
after.absorbed = after.absorbed.filter((p) => p.timeMs >= entry.timeMs);
}
}
}
i = removeSpursAround(fixes, i);
thinAround(fixes, i);
keepTrailLimit(fixes, maxPoints);
}
/** Index of the newest report before entry `i`, or -1. */
function reportBefore(fixes, i) {
let j = i - 1;
while (j >= 0 && fixes[j].drawn) j -= 1;
return j;
}
/** Index of the oldest report at or after `i`, or `fixes.length`. */
function reportFrom(fixes, i) {
let j = i;
while (j < fixes.length && fixes[j].drawn) j += 1;
return j;
}
/**
* Put a report into the trail in time order. Reports are the record: they
* are kept as anchors among the recorded points.
*
* - A report the display has already passed replaces the guess drawn after
* it: the recorded points timed after it go, and nothing is recorded until
* the icon has eased onto the correction (`displayMs` + `settleMs`), so the
* line reads arc, report, corrected path.
* - Recorded points never join two reports that break under
* `trailPairBreaks` (too long or too fast apart to be one flight): the
* points between them go and the line breaks.
* - A live report with no altitude keeps no position and only breaks the
* line.
* @param {object[]} fixes - The trail, mutated.
* @param {Cesium.Cartesian3} position - Owned position.
* @param {number} timeMs - The report's epoch ms.
* @param {number} maxPoints - Point limit across all segments.
* @param {{nullAltitude?: boolean, displayMs?: number, settleMs?: number}} [options]
* `displayMs`: the time the aircraft is drawn at as the report arrives;
* `settleMs`: how long the icon takes to ease onto a correction.
* @returns {object[]} `fixes`.
*/
export function insertTrailFix(
fixes,
position,
timeMs,
maxPoints,
{ nullAltitude = false, displayMs = NaN, settleMs = 0 } = {},
) {
const entry = {
position: nullAltitude ? null : position,
timeMs,
nullAltitude,
drawn: false,
breakBefore: false,
};
let i = insertionIndex(fixes, timeMs);
// The guess drawn after a report the display already passed.
fixes.splice(i, reportFrom(fixes, i) - i);
if (displayMs > timeMs) entry.settleUntilMs = displayMs + settleMs;
// Recorded points across a pair of reports that are not one flight.
const before = reportBefore(fixes, i);
if (before >= 0 && trailFixBreaks(fixes[before], entry)) {
fixes.splice(before + 1, i - before - 1);
i = before + 1;
}
insertAt(fixes, i, entry, maxPoints);
return fixes;
}
/**
* Record where the tracked aircraft was drawn at a display time. Between
* reports this recorded path is the trail, so the line follows every turn
* the icon made instead of a straight chord between two reports. Points are
* thinned by shape: one stays only where dropping it would move the line by
* more than TRAIL_THIN_TOLERANCE_M across the track or in height, or leave a
* straight piece longer than TRAIL_THIN_MAX_SPAN_M. Nothing is recorded
* while the aircraft holds.
* @param {object[]} fixes - The trail, mutated.
* @param {Cesium.Cartesian3} position - Owned drawn position.
* @param {number} timeMs - Display time it was drawn for.
* @param {number} maxPoints - Point limit across all segments.
* @returns {boolean} Whether the trail changed.
*/
export function recordTrailPoint(fixes, position, timeMs, maxPoints) {
const i = insertionIndex(fixes, timeMs);
const prev = fixes[i - 1];
if (
prev?.position &&
Cesium.Cartesian3.distance(prev.position, position) <
TRAIL_RECORD_MIN_STEP_M
)
return false;
const entry = {
position,
timeMs,
nullAltitude: false,
drawn: true,
breakBefore: false,
};
insertAt(fixes, i, entry, maxPoints);
// Entries before the second report behind this point can never be thinned
// again, so they let go of the positions they stood for.
const passed = reportBefore(fixes, fixes.lastIndexOf(entry));
if (passed >= 0) sealThrough(fixes, reportBefore(fixes, passed));
return true;
}
/** Release the absorbed positions of entry `i` and everything before it. */
function sealThrough(fixes, i) {
for (let j = i; j >= 0 && !fixes[j].sealed; j--) {
fixes[j].sealed = true;
delete fixes[j].absorbed;
}
}
/**
* Whether the icon's drawn position must not be recorded at a display time:
* a report on either side of it has no altitude (the icon is drawn at an
* invented height), the reports on either side are not one flight
* (`trailPairBreaks`), or the icon is still easing onto a report that
* arrived after the display had passed it.
* @param {object[]} fixes
* @param {number} displayMs
* @returns {boolean}
*/
export function trailRecordingBlocked(fixes, displayMs) {
const i = insertionIndex(fixes, displayMs);
const before = fixes[reportBefore(fixes, i)];
const after = fixes[reportFrom(fixes, i)];
if (before?.nullAltitude || after?.nullAltitude) return true;
if (before?.settleUntilMs > displayMs) return true;
return !!(before && after && trailFixBreaks(before, after));
}
+269 -58
View File
@@ -14,6 +14,18 @@
* the whole history renders at one readable alpha (dimmer where it passes
* behind/below geometry).
*
* A trail with breaks draws each segment separately and nothing between
* them. Every segment is cut into chunks of up to CHUNK_POINTS points;
* adjacent chunks share their boundary point, so the line has no seam. A
* chunk that can no longer change (every chunk except the newest one of the
* newest segment) is FROZEN: an entity with constant positions, built once as
* static geometry, so it costs nothing per frame. Only the newest chunk stays
* dynamic. A freshly frozen chunk is also drawn dynamically until its static
* geometry is in the scene, so freezing never shows a blank frame. A chunk is
* identified by its position objects, so a chunk survives every update that
* keeps those points: appends, a backfill prepended ahead of it, or the
* oldest points dropping off the front (which rebuilds only the first chunk).
*
* Trails update at poll cadence (~15-60 s) plus once on history backfill, so
* assigning a fresh positions array per update is cheap. `allowPicking` has
* no entity equivalent; the polyline entity is excluded from clicks by never
@@ -42,6 +54,13 @@ const TRAIL_ALPHA = 0.85;
const TRAIL_OCCLUDED_ALPHA = 0.4;
/** @constant {number} Squared distance (m^2) below which consecutive points are merged. */
const MIN_SEGMENT_DISTANCE_SQ = 0.01;
/** @constant {Cesium.Cartesian3[]} What a spare dynamic polyline draws. */
const NO_POSITIONS = Object.freeze([]);
/** @constant {number} Points per chunk; adjacent chunks share one point. */
export const CHUNK_POINTS = 128;
/** @constant {number} Visible frames a frozen chunk's stand-in waits for its
* static geometry before it is dropped anyway. */
const STAND_IN_MAX_FRAMES = 600;
/**
* Create an always-visible polyline trail bound to a viewer.
@@ -49,93 +68,285 @@ const MIN_SEGMENT_DISTANCE_SQ = 0.01;
* @param {object} options - Trail options.
* @param {string} options.color - CSS color string for the trail hue.
* @param {number} [options.width=2.5] - Polyline width in pixels.
* @returns {{setPositions: function(Cesium.Cartesian3[]): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
* Trail handle: setPositions replaces the geometry, setVisible temporarily
* hides it without discarding history, clear empties it, and destroy removes
* the entity permanently.
* @returns {{setPositions: function(Cesium.Cartesian3[]): void, setSegments: function(Cesium.Cartesian3[][]): void, setVisible: function(boolean): void, clear: function(): void, destroy: function(): void}}
* Trail handle: setPositions replaces the geometry with one line,
* setSegments with one line per segment, setVisible temporarily hides it
* without discarding history, clear empties it, and destroy removes the
* entities permanently.
*/
export function createTrail(viewer, { color, width = 2.5 }) {
const baseColor = Cesium.Color.fromCssColorString(color);
/** @type {Cesium.Cartesian3[]} Current deduped positions (owned copy). */
let current = [];
const material = baseColor.withAlpha(TRAIL_ALPHA);
const depthFailMaterial = baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA);
let destroyed = false;
let visible = true;
/** @type {Cesium.Entity|null} */
let entity = null;
/** @type {{positions: Cesium.Cartesian3[], entity: Cesium.Entity, standIn: boolean, frames: number}[]} */
let frozen = [];
/** Newest chunk of the newest segment: the only part that changes. */
let tail = NO_POSITIONS;
/** What the dynamic polylines draw: the tail, then frozen chunks whose
* static geometry is not in the scene yet. */
let dynamicRuns = [];
/** @type {Cesium.Entity[]} Pooled dynamic polylines; spares draw nothing. */
const dynamicEntities = [];
let removeReadyListener = null;
const scratchSphere = new Cesium.BoundingSphere();
function ensureEntity() {
if (entity || destroyed || !viewer || viewer.isDestroyed()) return;
entity = viewer.entities.add({
const usable = () => !destroyed && viewer && !viewer.isDestroyed();
function polyline(positions) {
return {
positions,
width,
material,
// The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground.
depthFailMaterial,
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
// globe"): NONE draws straight 3D chords between waypoints — over a
// sparse trans-oceanic trace a single segment spans hundreds of km
// and tunnels through the planet. GEODESIC subdivides each segment
// along the curved surface (heights interpolated), so long legs hug
// the globe instead of chording through it.
arcType: Cesium.ArcType.GEODESIC,
};
}
function addEntity(positions) {
return viewer.entities.add({
id: `gev-trail:${++_trailSeq}`,
show: visible,
polyline: {
// CallbackProperty so a positions swap never rebuilds the entity —
// Cesium re-reads on change; `false` marks it non-constant.
positions: new Cesium.CallbackProperty(() => current, false),
width,
material: baseColor.withAlpha(TRAIL_ALPHA),
// The owner-locked rule (round 6): a segment below the photoreal
// mesh renders dimmed — it must never disappear into the ground.
depthFailMaterial: baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA),
// Round 8 (owner: UAL1104's Pacific trail "cutting through the
// globe"): NONE draws straight 3D chords between waypoints — over a
// sparse trans-oceanic trace a single segment spans hundreds of km
// and tunnels through the planet. GEODESIC subdivides each segment
// along the curved surface (heights interpolated), so long legs hug
// the globe instead of chording through it.
arcType: Cesium.ArcType.GEODESIC,
},
polyline: polyline(positions),
});
}
function removeEntity(entity) {
try {
viewer.entities.remove(entity);
} catch {
/* torn down */
}
}
function syncDynamic() {
dynamicRuns = [];
if (tail.length >= 2) dynamicRuns.push(tail);
for (const chunk of frozen)
if (chunk.standIn) dynamicRuns.push(chunk.positions);
while (dynamicEntities.length < Math.max(1, dynamicRuns.length)) {
const index = dynamicEntities.length;
dynamicEntities.push(
addEntity(
// CallbackProperty so a positions swap never rebuilds the entity —
// Cesium re-reads on change; `false` marks it non-constant.
new Cesium.CallbackProperty(
() => dynamicRuns[index] ?? NO_POSITIONS,
false,
),
),
);
}
}
/** Whether a frozen chunk's static geometry is drawn in the scene. */
function staticReady(chunk) {
const display = viewer.dataSourceDisplay;
if (typeof display?.getBoundingSphere !== 'function') return true;
if (!visible) return false;
chunk.frames += 1;
if (chunk.frames > STAND_IN_MAX_FRAMES) return true;
try {
return (
display.getBoundingSphere(chunk.entity, false, scratchSphere) ===
Cesium.BoundingSphereState.DONE
);
} catch {
return false;
}
}
/** Drop stand-ins whose static geometry is in; stop listening when none are left. */
function resolveStandIns() {
if (!usable()) return;
let changed = false;
for (const chunk of frozen) {
if (chunk.standIn && staticReady(chunk)) {
chunk.standIn = false;
changed = true;
}
}
if (changed) syncDynamic();
if (!frozen.some((chunk) => chunk.standIn)) stopListening();
}
function stopListening() {
if (removeReadyListener) removeReadyListener();
removeReadyListener = null;
}
function listenForStandIns() {
if (removeReadyListener) return;
const event = viewer.scene?.postRender;
if (typeof event?.addEventListener !== 'function') {
resolveStandIns();
return;
}
removeReadyListener = event.addEventListener(resolveStandIns);
}
/** Drop consecutive near-duplicates: zero-length segments add nothing. */
function dedupe(cartesians) {
const positions = [];
for (const position of Array.isArray(cartesians) ? cartesians : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (
last &&
Cesium.Cartesian3.distanceSquared(last, position) <
MIN_SEGMENT_DISTANCE_SQ
)
continue;
positions.push(position);
}
return positions;
}
/** Whether `chunk` holds exactly the same position objects as `seg` from `start`. */
function sameRun(chunk, seg, start) {
const positions = chunk.positions;
if (start + positions.length > seg.length) return false;
for (let k = 0; k < positions.length; k++)
if (positions[k] !== seg[start + k]) return false;
return true;
}
/**
* Cut segments into chunks, reusing every frozen chunk whose points are
* still drawn in the same order. New chunks end where a reusable one begins,
* so dropping the oldest point rebuilds only the first chunk.
*/
function reconcile(segments) {
const byStart = new Map();
for (const chunk of frozen) byStart.set(chunk.positions[0], chunk);
const kept = new Set();
const reusable = (seg, j) => {
const chunk = byStart.get(seg[j]);
return chunk && !kept.has(chunk) && sameRun(chunk, seg, j) ? chunk : null;
};
const next = [];
let nextTail = NO_POSITIONS;
segments.forEach((seg, s) => {
const newest = s === segments.length - 1;
let i = 0;
while (i < seg.length - 1) {
const existing = reusable(seg, i);
if (existing) {
kept.add(existing);
next.push(existing);
i += existing.positions.length - 1;
continue;
}
if (newest && seg.length - i <= CHUNK_POINTS) {
nextTail = seg.slice(i);
break;
}
let end = Math.min(seg.length - 1, i + CHUNK_POINTS - 1);
for (let j = i + 1; j < end; j++) {
if (reusable(seg, j)) {
end = j;
break;
}
}
const positions = seg.slice(i, end + 1);
next.push({
positions,
entity: addEntity(positions),
standIn: true,
frames: 0,
});
i = end;
}
});
for (const chunk of frozen)
if (!kept.has(chunk)) removeEntity(chunk.entity);
frozen = next;
tail = nextTail;
syncDynamic();
if (frozen.some((chunk) => chunk.standIn)) listenForStandIns();
else stopListening();
}
function release() {
stopListening();
for (const chunk of frozen) removeEntity(chunk.entity);
frozen = [];
tail = NO_POSITIONS;
dynamicRuns = [];
}
return {
/**
* Replace the trail geometry with a chronological position list
* Replace the trail geometry with one chronological position list
* (oldest first). Fewer than 2 distinct positions clears the trail.
* @param {Cesium.Cartesian3[]} cartesians - Positions, oldest -> newest.
*/
setPositions(cartesians) {
if (destroyed || !viewer || viewer.isDestroyed()) return;
// Drop consecutive near-duplicates: zero-length segments add nothing.
const positions = [];
for (const position of Array.isArray(cartesians) ? cartesians : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (
last &&
Cesium.Cartesian3.distanceSquared(last, position) <
MIN_SEGMENT_DISTANCE_SQ
)
continue;
positions.push(position);
}
current = positions.length >= 2 ? positions : [];
ensureEntity();
this.setSegments([cartesians]);
},
/**
* Replace the trail geometry with chronological segments (oldest first).
* Nothing is drawn between segments. A segment with fewer than 2 distinct
* positions draws nothing. Pass the same position objects on every
* update: a chunk whose points are unchanged is never rebuilt.
* @param {Cesium.Cartesian3[][]} list - Segments, each oldest -> newest.
*/
setSegments(list) {
if (!usable()) return;
reconcile(
(Array.isArray(list) ? list : [])
.map(dedupe)
.filter((positions) => positions.length >= 2),
);
},
/** Temporarily hide/show the trail without discarding accumulated history. */
setVisible(nextVisible) {
visible = nextVisible !== false;
if (entity) entity.show = visible;
for (const entity of dynamicEntities) entity.show = visible;
for (const chunk of frozen) chunk.entity.show = visible;
},
/** Empty the trail without removing the entity (cheap re-arm). */
/** Empty the trail and release its frozen geometry; dynamic polylines stay for re-arm. */
clear() {
current = [];
if (!usable()) return;
release();
},
/** Remove the trail entity permanently (layer disable/teardown). */
/** Remove every trail entity permanently (layer disable/teardown). */
destroy() {
destroyed = true;
current = [];
if (entity && viewer && !viewer.isDestroyed()) {
try {
viewer.entities.remove(entity);
} catch {
/* torn down */
}
if (usable()) {
release();
for (const entity of dynamicEntities) removeEntity(entity);
}
entity = null;
destroyed = true;
frozen = [];
tail = NO_POSITIONS;
dynamicRuns = [];
dynamicEntities.length = 0;
stopListening();
},
/** Test seam: frozen chunks (positions, stand-in state) and the dynamic runs. */
_chunksForTest() {
return {
frozen: frozen.map((chunk) => ({
positions: chunk.positions,
standIn: chunk.standIn,
entity: chunk.entity,
})),
dynamic: dynamicRuns.slice(),
};
},
};
}
+251 -1
View File
@@ -1,7 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createTrail } from './trailRenderer.js';
import { CHUNK_POINTS, createTrail } from './trailRenderer.js';
test('trail visibility can change without discarding its accumulated geometry', () => {
const added = [];
@@ -37,3 +37,253 @@ test('trail visibility can change without discarding its accumulated geometry',
trail.destroy();
assert.deepEqual(removed, [added[0]]);
});
/**
* A fake viewer. `ready` holds the frozen-chunk entities whose static
* geometry is in the scene; `frame()` runs one post-render pass.
*/
function fakeViewer({ scene = true } = {}) {
const added = [];
const removed = [];
const ready = new Set();
let listeners = [];
const viewer = {
added,
removed,
ready,
isDestroyed: () => false,
entities: {
add(definition) {
added.push(definition);
return definition;
},
remove(entity) {
removed.push(entity);
},
},
listenerCount: () => listeners.length,
frame() {
for (const listener of listeners.slice()) listener();
},
};
if (scene) {
viewer.scene = {
postRender: {
addEventListener(listener) {
listeners.push(listener);
return () => {
listeners = listeners.filter((l) => l !== listener);
};
},
},
};
viewer.dataSourceDisplay = {
getBoundingSphere: (entity) =>
ready.has(entity)
? Cesium.BoundingSphereState.DONE
: Cesium.BoundingSphereState.PENDING,
};
}
return viewer;
}
const valueOf = (positions) =>
typeof positions?.getValue === 'function' ? positions.getValue() : positions;
/** Every line the scene can draw now: live entities with two or more points. */
function drawnRuns(viewer) {
return viewer.added
.filter((entity) => !viewer.removed.includes(entity))
.map((entity) => valueOf(entity.polyline.positions))
.filter((positions) => positions.length >= 2);
}
/** Distinct position objects across all drawn lines. */
function drawnPoints(viewer) {
return new Set(drawnRuns(viewer).flat());
}
function line(count, offset = 0) {
return Array.from(
{ length: count },
(_, i) => new Cesium.Cartesian3(6_378_137 + offset, i * 1000, 0),
);
}
test('a trail with breaks draws each segment and nothing between them', () => {
const viewer = fakeViewer({ scene: false });
const trail = createTrail(viewer, { color: '#ffffff' });
const first = line(2, 0);
const lone = line(1, 50_000);
const second = line(3, 100_000);
trail.setSegments([first, lone, second]);
assert.deepEqual(
drawnRuns(viewer).sort((a, b) => a[0].x - b[0].x),
[first, second],
);
for (const entity of viewer.added) {
assert.match(String(entity.id), /^gev-trail:/);
assert.equal(entity.polyline.width, 2.5);
}
// The first segment is gone later: its geometry is released.
trail.setSegments([second]);
assert.deepEqual(drawnRuns(viewer), [second]);
trail.setVisible(false);
assert.ok(
viewer.added
.filter((entity) => !viewer.removed.includes(entity))
.every((entity) => entity.show === false),
);
trail.destroy();
assert.equal(new Set(viewer.removed).size, viewer.added.length);
});
test('chunks share their boundary points and only the newest chunk is dynamic', () => {
const viewer = fakeViewer({ scene: false });
const trail = createTrail(viewer, { color: '#ffffff' });
const points = line(300);
trail.setPositions(points);
const { frozen, dynamic } = trail._chunksForTest();
assert.deepEqual(
frozen.map((chunk) => chunk.positions.length),
[CHUNK_POINTS, CHUNK_POINTS],
);
assert.equal(frozen[0].positions.at(-1), frozen[1].positions[0]);
assert.equal(dynamic.length, 1);
assert.equal(frozen[1].positions.at(-1), dynamic[0][0]);
assert.equal(dynamic[0].at(-1), points.at(-1));
assert.equal(drawnPoints(viewer).size, points.length);
// A frozen chunk is constant geometry, not a per-frame callback.
for (const chunk of frozen)
assert.ok(Array.isArray(chunk.entity.polyline.positions));
});
test('freezing a chunk keeps every point drawn, and the dynamic copy goes only once the static geometry is in', () => {
const viewer = fakeViewer();
const trail = createTrail(viewer, { color: '#ffffff' });
const points = line(CHUNK_POINTS + 20);
for (let n = 2; n <= points.length; n++) {
trail.setPositions(points.slice(0, n));
assert.equal(drawnPoints(viewer).size, n, `points drawn at ${n}`);
}
const { frozen } = trail._chunksForTest();
assert.equal(frozen.length, 1);
// Not in the scene yet: the chunk is still drawn by a dynamic polyline.
viewer.frame();
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
assert.ok(
trail._chunksForTest().dynamic.includes(frozen[0].positions),
'the dynamic copy stays until the static geometry is ready',
);
viewer.ready.add(frozen[0].entity);
viewer.frame();
const after = trail._chunksForTest();
assert.equal(after.frozen[0].standIn, false);
assert.ok(!after.dynamic.includes(frozen[0].positions));
assert.equal(after.dynamic.length, 1);
assert.equal(viewer.listenerCount(), 0, 'no listener once nothing waits');
// The frozen entity is the same object: freezing built it once.
assert.equal(after.frozen[0].entity, frozen[0].entity);
});
test('a hidden trail keeps its dynamic copy until it is shown and the static geometry is in', () => {
const viewer = fakeViewer();
const trail = createTrail(viewer, { color: '#ffffff' });
trail.setVisible(false);
trail.setPositions(line(CHUNK_POINTS + 5));
const [chunk] = trail._chunksForTest().frozen;
viewer.ready.add(chunk.entity);
viewer.frame();
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
trail.setVisible(true);
viewer.frame();
assert.equal(trail._chunksForTest().frozen[0].standIn, false);
});
test('dropping the oldest point rebuilds only the first chunk', () => {
const viewer = fakeViewer({ scene: false });
const trail = createTrail(viewer, { color: '#ffffff' });
const points = line(400);
trail.setPositions(points);
const before = trail._chunksForTest().frozen;
trail.setPositions(points.slice(1));
const after = trail._chunksForTest().frozen;
assert.equal(after.length, before.length);
assert.notEqual(after[0].entity, before[0].entity);
assert.ok(viewer.removed.includes(before[0].entity));
for (let k = 1; k < before.length; k++)
assert.equal(after[k].entity, before[k].entity);
assert.equal(after[0].positions.at(-1), after[1].positions[0]);
assert.equal(drawnPoints(viewer).size, 399);
});
test('a backfill prepended ahead of frozen chunks keeps them and joins at a shared point', () => {
const viewer = fakeViewer({ scene: false });
const trail = createTrail(viewer, { color: '#ffffff' });
const live = line(300, 0);
trail.setPositions(live);
const before = trail._chunksForTest().frozen;
// History older than every live point, joined as one path.
const history = Array.from(
{ length: 200 },
(_, i) => new Cesium.Cartesian3(6_378_137, -(200 - i) * 1000, 0),
);
trail.setPositions(history.concat(live));
const after = trail._chunksForTest().frozen;
for (const chunk of before)
assert.ok(after.some((c) => c.entity === chunk.entity));
for (let k = 0; k + 1 < after.length; k++)
assert.equal(after[k].positions.at(-1), after[k + 1].positions[0]);
assert.equal(drawnPoints(viewer).size, 500);
// A backfill that breaks from the live trail is its own segment.
trail.setSegments([history, live]);
assert.equal(drawnPoints(viewer).size, 500);
const runs = drawnRuns(viewer);
assert.ok(
!runs.some((run) => run.includes(history.at(-1)) && run.includes(live[0])),
'no line across the break',
);
});
test('clearing and re-tracking release every frozen chunk', () => {
const viewer = fakeViewer();
const trail = createTrail(viewer, { color: '#ffffff' });
trail.setPositions(line(600));
const frozen = trail._chunksForTest().frozen.map((chunk) => chunk.entity);
assert.ok(frozen.length >= 4);
assert.equal(viewer.listenerCount(), 1);
trail.clear();
for (const entity of frozen) assert.ok(viewer.removed.includes(entity));
assert.equal(viewer.listenerCount(), 0);
assert.equal(drawnRuns(viewer).length, 0);
// Another aircraft: nothing of the first one survives.
const other = line(200, 900_000);
trail.setPositions(other);
assert.equal(drawnPoints(viewer).size, 200);
trail.destroy();
assert.equal(new Set(viewer.removed).size, viewer.added.length);
assert.equal(viewer.listenerCount(), 0);
});
test('replacing the newest point and removing points inside the trail draws exactly the new trail', () => {
const viewer = fakeViewer({ scene: false });
const trail = createTrail(viewer, { color: '#ffffff' });
const points = line(400);
trail.setPositions(points.slice());
// A recorded point replaces the newest one; a spur point inside a frozen
// chunk and one at a chunk boundary go.
points[points.length - 1] = new Cesium.Cartesian3(6_378_137, 399_500, 10);
points.splice(200, 1);
points.splice(CHUNK_POINTS - 1, 1);
trail.setPositions(points.slice());
assert.deepEqual(drawnPoints(viewer), new Set(points));
// Every drawn line runs through consecutive trail points only.
const next = new Map(points.slice(0, -1).map((p, i) => [p, points[i + 1]]));
for (const run of drawnRuns(viewer))
for (let i = 1; i < run.length; i++) assert.equal(next.get(run[i - 1]), run[i]);
});
+165
View File
@@ -0,0 +1,165 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
recordTrailPoint,
trailBodySegments,
trailPairBreaks,
trailDistanceM,
trailRecordingBlocked,
} from './trailContinuity.js';
// Reports decide where the line may run: recorded points never join two
// reports too far apart to be one flight, a report the display has already
// passed replaces the guess drawn after it, and old entries let go of the
// positions they stood for.
const SEC = 1000;
const LIMIT = 2_000;
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-100, 40, 0),
);
const at = (e, n, u = 10) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
/** No two neighbours in one drawn segment are too far apart to be one flight. */
function assertNoBrokenJoin(fixes) {
const reports = fixes.filter((fix) => !fix.drawn && fix.position);
for (const segment of trailBodySegments(fixes, fixes.length)) {
const inSegment = reports.filter((r) =>
segment.some((p) => Cesium.Cartesian3.distance(p, r.position) < 0.01),
);
for (let i = 1; i < inSegment.length; i++)
assert.equal(
trailPairBreaks(
inSegment[i].timeMs - inSegment[i - 1].timeMs,
trailDistanceM(inSegment[i - 1].position, inSegment[i].position),
),
false,
`one segment joins reports at ${inSegment[i - 1].timeMs / SEC} s and ${
inSegment[i].timeMs / SEC
} s`,
);
}
}
test('two reports 60 s and 51 km apart are not joined, even by recorded points', () => {
const A = Cesium.Cartesian3.fromDegrees(-100, 40, 9_000);
const B = Cesium.Cartesian3.fromDegrees(-99.4, 40, 9_000);
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
insertTrailFix(fixes, B, 60 * SEC, LIMIT); // ahead of the display
for (let t = 1; t < 60; t++) {
// Nothing is recorded across the pair.
assert.equal(trailRecordingBlocked(fixes, t * SEC), true);
}
assert.equal(trailBodySegments(fixes, fixes.length).length, 2);
// Points recorded before the far report was known are dropped.
const late = [];
insertTrailFix(late, A, 0, LIMIT);
for (let t = 1; t < 60; t++)
recordTrailPoint(
late,
Cesium.Cartesian3.lerp(A, B, t / 60, new Cesium.Cartesian3()),
t * SEC,
LIMIT,
);
insertTrailFix(late, B, 60 * SEC, LIMIT);
assert.equal(late.filter((fix) => fix.drawn).length, 0);
assert.equal(trailBodySegments(late, late.length).length, 2);
assertNoBrokenJoin(late);
});
test('a coast, a hold and then a far report: nothing is drawn across', () => {
const A = at(0, 0, 9_000);
const fixes = [];
insertTrailFix(fixes, A, 0, LIMIT);
// The icon coasts east for 90 s at 230 m/s, then holds.
for (let t = 1; t <= 200; t++)
recordTrailPoint(
fixes,
at(230 * Math.min(t, 90), 0, 9_000),
t * SEC,
LIMIT,
);
assert.ok(fixes.filter((fix) => fix.drawn).length > 0);
// The next report is 150 km away two minutes later: over 1,500 kt.
const B = at(0, 150_000, 9_000);
insertTrailFix(fixes, B, 120 * SEC, LIMIT);
assertNoBrokenJoin(fixes);
const segments = trailBodySegments(fixes, fixes.length);
const segmentOf = (p) =>
segments.findIndex((s) =>
s.some((q) => Cesium.Cartesian3.distance(p, q) < 0.01),
);
assert.notEqual(segmentOf(A), segmentOf(B));
// No recorded point between the two reports remains.
assert.equal(
fixes.filter((fix) => fix.drawn && fix.timeMs < 120 * SEC).length,
0,
);
});
for (const off of [200, 400, 600, 1_000]) {
test(`a report the display already passed, ${off} m off a 2 km turn, leaves no spike`, () => {
const R = 2_000;
const w = 100 / R;
const pos = (t, r = R) =>
at(r * Math.sin(w * t), R - r * Math.cos(w * t), 3_000);
const fixes = [];
insertTrailFix(fixes, pos(0), 0, LIMIT);
for (let t = 1; t <= 60; t++)
recordTrailPoint(fixes, pos(t), t * SEC, LIMIT);
const report = pos(50, R - off);
// It arrives with the display at 60 s; the ease takes 900 ms.
insertTrailFix(fixes, report, 50 * SEC, LIMIT, {
displayMs: 60 * SEC,
settleMs: 900,
});
// The guess drawn after the report is gone...
assert.deepEqual(
fixes.filter((fix) => fix.drawn && fix.timeMs > 50 * SEC),
[],
);
// ...nothing is recorded while the icon eases onto the correction...
assert.equal(trailRecordingBlocked(fixes, 60.5 * SEC), true);
assert.equal(trailRecordingBlocked(fixes, 61 * SEC), false);
// ...and the line reads arc, report, corrected path.
for (let t = 61; t <= 70; t++)
recordTrailPoint(fixes, pos(t, R - off), t * SEC, LIMIT);
const line = trailBodySegments(fixes, fixes.length).flat();
const r = line.findIndex(
(p) => Cesium.Cartesian3.distance(p, report) < 0.01,
);
assert.ok(r > 0);
for (const p of line.slice(0, r))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - R) < 31,
'a point before the report is off the arc',
);
for (const p of line.slice(r + 1))
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R, 3_000)) - (R - off)) <
31,
'a point after the report is off the corrected path',
);
});
}
test('entries behind the report before the display let go of the positions they stood for', () => {
const fixes = [];
for (let s = 0; s <= 2 * 3_600; s++) {
const p = at(230 * s, 0, 10_000);
if (s % 15 === 0) insertTrailFix(fixes, p, s * SEC, LIMIT);
else recordTrailPoint(fixes, p, s * SEC, LIMIT);
}
let held = 0;
for (const fix of fixes) held += fix.absorbed?.length ?? 0;
// Only the newest stretch, up to two reports back, keeps what it stood for.
assert.ok(held <= 30, `${held} positions still held`);
});
+180
View File
@@ -0,0 +1,180 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
insertTrailFix,
joinTrailBackfill,
recordTrailPoint,
TRAIL_THIN_MAX_SPAN_M,
TRAIL_THIN_TOLERANCE_M,
} from './trailContinuity.js';
// Recorded points are thinned by shape: a point stays only where the line
// would move without it. Reports always stay.
const SEC = 1000;
const LIMIT = 2_000;
const LAT0 = 40;
const LON0 = -100;
const M_PER_DEG_LAT = 111_320;
const mPerDegLon = (lat) => M_PER_DEG_LAT * Math.cos((lat * Math.PI) / 180);
/** Straight and level east at `speed` m/s, `tSec` after the start. */
const eastbound = (speed, tSec, heightM = 10_000) =>
Cesium.Cartesian3.fromDegrees(
LON0 + (speed * tSec) / mPerDegLon(LAT0),
LAT0,
heightM,
);
/** A standard-rate (3°/s) left turn from north, radius v / ω, `tSec` in. */
function turning(speed, tSec, heightM = 10_000) {
const omega = (3 * Math.PI) / 180;
const radius = speed / omega;
// Centre west of the start; heading north, turning left (towards west).
const angle = omega * tSec;
const east = -radius + radius * Math.cos(angle);
const north = radius * Math.sin(angle);
return Cesium.Cartesian3.fromDegrees(
LON0 + east / mPerDegLon(LAT0),
LAT0 + north / M_PER_DEG_LAT,
heightM,
);
}
/** 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();
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;
}
const drawnCount = (fixes) => fixes.filter((fix) => fix.drawn).length;
test('one hour straight and level with a report every 15 s adds under 60 recorded points', () => {
const speed = 230;
const fixes = [];
for (const t of [0, 15, 30])
insertTrailFix(fixes, eastbound(speed, t), t * SEC, LIMIT);
// Live order: a report arrives 30 s before the display reaches it, and the
// drawn icon is recorded once a second.
for (let t = 1; t <= 3_600; t++) {
const reportAt = t + 30;
if (reportAt % 15 === 0 && reportAt <= 3_600)
insertTrailFix(fixes, eastbound(speed, reportAt), reportAt * SEC, LIMIT);
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
}
assert.ok(
drawnCount(fixes) < 60,
`${drawnCount(fixes)} recorded points kept`,
);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 241);
});
test('with no report at all, a straight leg keeps one point per 10 km and no more', () => {
const speed = 230;
const fixes = [];
insertTrailFix(fixes, eastbound(speed, 0), 0, LIMIT);
for (let t = 1; t <= 3_600; t++)
recordTrailPoint(fixes, eastbound(speed, t), t * SEC, LIMIT);
const legKm = (speed * 3_600) / 1_000;
assert.equal(TRAIL_THIN_MAX_SPAN_M, 10_000);
assert.ok(
drawnCount(fixes) <= Math.ceil(legKm / 10) + 1,
`${drawnCount(fixes)} points over ${legKm} km`,
);
for (let i = 1; i < fixes.length; i++)
assert.ok(
Cesium.Cartesian3.distance(fixes[i - 1].position, fixes[i].position) <=
TRAIL_THIN_MAX_SPAN_M + speed,
);
});
test('a standard-rate 180° turn keeps its curve: every recorded position stays within 30 m of the kept line', () => {
const speed = 230;
const fixes = [];
const recorded = [];
insertTrailFix(fixes, turning(speed, 0), 0, LIMIT);
for (let t = 1; t <= 60; t++) {
const position = turning(speed, t);
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
assert.equal(TRAIL_THIN_TOLERANCE_M, 30);
for (const position of recorded) {
const off = distanceToPath(position, line);
assert.ok(off <= TRAIL_THIN_TOLERANCE_M + 1, `${off.toFixed(1)} m off`);
}
assert.ok(drawnCount(fixes) < recorded.length, 'nothing was thinned');
assert.ok(drawnCount(fixes) >= 6, 'the curve was flattened');
});
test('a climb off the straight line keeps its vertices', () => {
const fixes = [];
insertTrailFix(fixes, eastbound(200, 0, 1_000), 0, LIMIT);
// 30 s level, then a 60 s climb of 20 m/s, then level again.
const height = (t) => 1_000 + 20 * Math.min(60, Math.max(0, t - 30));
const recorded = [];
for (let t = 1; t <= 150; t++) {
const position = eastbound(200, t, height(t));
recorded.push(position);
recordTrailPoint(fixes, position, t * SEC, LIMIT);
}
const line = fixes.map((fix) => fix.position);
for (const position of recorded)
assert.ok(distanceToPath(position, line) <= TRAIL_THIN_TOLERANCE_M + 1);
});
test('at the limit, old recorded points go before any report from the backfill', () => {
const max = 300;
const backfill = [];
for (let i = 0; i < 100; i++)
backfill.push({
position: eastbound(200, i * 60 - 20_000),
timeMs: (i * 60 - 20_000) * SEC,
nullAltitude: false,
});
let fixes = [];
insertTrailFix(fixes, turning(150, 0), 0, max);
// A long series of turns keeps many recorded points.
for (let t = 1; t <= 2_000; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(drawnCount(fixes) > 150);
fixes = joinTrailBackfill(
{
fixes: backfill.map((b) => ({ ...b, breakBefore: false })),
breakAfter: false,
},
fixes,
max,
);
assert.ok(fixes.length <= max);
const reports = fixes.filter((fix) => !fix.drawn);
assert.equal(reports.length, 101, 'a report was dropped');
// More recording at the limit drops recorded points, never reports.
for (let t = 2_001; t <= 2_400; t++)
recordTrailPoint(fixes, turning(150, t), t * SEC, max);
assert.ok(fixes.length <= max);
assert.equal(fixes.filter((fix) => !fix.drawn).length, 101);
// The recorded points that remain are the newest.
const drawnTimes = fixes.filter((fix) => fix.drawn).map((fix) => fix.timeMs);
assert.ok(Math.min(...drawnTimes) > 1_000 * SEC);
});
+798
View File
@@ -389,6 +389,179 @@ function rioRouteLabel(routeId) {
: routeId;
}
/**
* Carris Metropolitana realtime route ids wrap the GTFS route id in an
* operator-area prefix and keep its pattern suffix: `[LA77N]1708_0` is GTFS
* route `1708_0`, whose `short_name` (the number on the bus) is `1708`, per
* the operator's own `/v2/routes` API. Anything else passes through.
* @param {string|null} routeId
* @returns {string|null}
*/
function carrisMetropolitanaRouteLabel(routeId) {
const match = /^\[[A-Z0-9]+\](\d{4})_\d+$/.exec(routeId ?? '');
return match ? match[1] : routeId;
}
/**
* Route ids that wrap the rider-facing line in a fixed prefix, suffix or
* zero-padding. The returned function yields the captured line, or the id
* unchanged when it does not match the operator's pattern.
* @param {RegExp} pattern One capture group: the line a rider would say.
* @returns {(routeId: string|null) => string|null}
*/
function routeIdPattern(pattern) {
return (routeId) => {
const match = pattern.exec(routeId ?? '');
return match ? match[1] : routeId;
};
}
/** Zero-padded numbers (Edmonton `005`, Toulon `0002`, Bordeaux `01`). */
const unpaddedRouteLabel = routeIdPattern(/^0+(\d+\w*)$/);
/** Turin GTT appends `U` (urban) to the line: `10NU` is night line 10N. */
const gttRouteLabel = routeIdPattern(/^(\w+?)U$/);
/** Venice ACTV appends the network: `5.1_UN` is waterbus line 5.1, `53E_ES` bus 53E. */
const actvRouteLabel = routeIdPattern(/^(.+)_[A-Z]{2}$/);
/** BC Transit appends the system: `95-VIC` is Victoria route 95. */
const bcTransitRouteLabel = routeIdPattern(/^(.+)-VIC$/);
/** Carris (Lisbon city) appends a variant: `172_1` is route 172. */
const carrisRouteLabel = routeIdPattern(/^(\w+)_\d+$/);
/** Astuce prefixes the network: `TCAR:93` is Rouen line 93. */
const astuceNetworkLabel = routeIdPattern(/^[A-Z]+:(.+)$/);
/** BAS.MY Johor appends a fixed operator code: `J33CWLMYJB` is route J33. */
const mybasJohorRouteLabel = routeIdPattern(/^(.+?)CWLMYJB$/);
/** LiA prefixes its network: `8-C3` is Le Havre line C3, `8-09` line 9. */
const liaRouteLabel = routeIdPattern(/^8-0*(\w.*)$/);
/**
* Le Havre LiA runs its two tram lines as A and B and the funicular as
* `FUNI`; every other line is a bus.
* @param {string|null} routeId
* @returns {string}
*/
function liaRouteMode(routeId) {
if (!routeId) return 'unknown';
const line = liaRouteLabel(routeId);
if (line === 'FUNI') return 'rail';
return /^[AB]$/.test(line) ? 'tram' : 'bus';
}
/**
* Rouen Astuce lines that are not buses, by route id, from the TCAR
* routes.txt (checked 2026-11-09): line 90 is the Métro (GTFS type 1, a light
* rail that runs mostly on the street) and 99 the Calypso river boat.
*/
const ASTUCE_ROUTES = Object.freeze({
// i18n-ignore: line name, as on the vehicle
'TCAR:90': Object.freeze({ mode: 'tram', label: 'Métro' }),
// i18n-ignore: line name, as on the vehicle
'TCAR:99': Object.freeze({ mode: 'ferry', label: 'Calypso' }),
});
/** @param {string|null} routeId @returns {string} */
function astuceRouteMode(routeId) {
if (!routeId) return 'unknown';
return ASTUCE_ROUTES[routeId]?.mode ?? 'bus';
}
/** `TCAR:93` is Rouen line 93; the Métro and Calypso keep their names. */
function astuceRouteLabel(routeId) {
return ASTUCE_ROUTES[routeId ?? '']?.label ?? astuceNetworkLabel(routeId);
}
/**
* Prague PID route ids are `L` plus a number whose range says what runs it,
* per PID's GTFS routes.txt (data.pid.cz, checked 2026-11-09): 1–99 trams
* (50–59 trolleybuses, 49 the Petřín funicular `LD`), 100–990 buses (the
* 800s are the X replacement lines, `L803` is X3), 991–993 metro A–C,
* 1000s and 1100s the S and R trains (`L1004` is S4, `L1109` R9), the rest
* of 1200–1399 other trains, 1700s town buses, 1800s the P ferries, and from
* 2000 more buses (`L2841` is 841). A label the range cannot give stays the
* route id.
* @param {string|null} routeId
* @returns {{mode: string, label: string|null}}
*/
function pidRoute(routeId) {
const match = /^L(\d+)$/.exec(routeId ?? '');
if (!match) return { mode: 'unknown', label: routeId };
const n = Number(match[1]);
// i18n-ignore: line code, as signed
if (n === 49) return { mode: 'rail', label: 'LD' };
if (n >= 50 && n <= 59) return { mode: 'bus', label: String(n) };
if (n < 100) return { mode: 'tram', label: String(n) };
if (n >= 800 && n < 900) return { mode: 'bus', label: `X${n - 800}` };
if (n < 991) return { mode: 'bus', label: String(n) };
// i18n-ignore: metro line letters, as signed
if (n <= 993) return { mode: 'subway', label: 'ABC'[n - 991] };
if (n >= 1000 && n < 1100) return { mode: 'rail', label: `S${n - 1000}` };
if (n >= 1100 && n < 1200) return { mode: 'rail', label: `R${n - 1100}` };
if (n >= 1200 && n < 1400) return { mode: 'rail', label: routeId };
if (n >= 1800 && n < 1900) return { mode: 'ferry', label: `P${n - 1800}` };
if (n >= 2800 && n < 2900) return { mode: 'bus', label: String(n - 2000) };
return { mode: n >= 1700 ? 'bus' : 'unknown', label: routeId };
}
/** @param {string|null} routeId @returns {string} */
function pidRouteMode(routeId) {
return pidRoute(routeId).mode;
}
/** @param {string|null} routeId @returns {string|null} */
function pidRouteLabel(routeId) {
return pidRoute(routeId).label;
}
/**
* Bordeaux TBM tram and boat lines by route id, from TBM's static GTFS
* routes.txt (checked 2026-11-09): the trams are numbered ids, not letters.
*/
const TBM_TRAM_LINES = Object.freeze({
59: 'A',
60: 'B',
61: 'C',
62: 'D',
163: 'E',
164: 'F',
});
const TBM_BOAT_LINES = new Set(['951', '952', '953']);
/**
* Bordeaux TBM: trams A–F and the BAT³ river shuttles; every other line is a
* bus.
* @param {string|null} routeId
* @returns {string}
*/
function tbmRouteMode(routeId) {
if (!routeId) return 'unknown';
if (Object.hasOwn(TBM_TRAM_LINES, routeId)) return 'tram';
return TBM_BOAT_LINES.has(routeId) ? 'ferry' : 'bus';
}
/** `59` is tram A; zero-padded bus ids lose their padding (`01` is 1). */
function tbmRouteLabel(routeId) {
return Object.hasOwn(TBM_TRAM_LINES, routeId ?? '')
? TBM_TRAM_LINES[routeId]
: unpaddedRouteLabel(routeId);
}
/**
* A registry entry, frozen with its centre and terms, and switched on.
* @param {object} fields
* @returns {Readonly<object>}
*/
function transitFeed(fields) {
return Object.freeze({
defaultEnabled: true,
...fields,
center: Object.freeze({ ...fields.center }),
terms: Object.freeze({ ...fields.terms }),
...(fields.headers
? { headers: Object.freeze({ ...fields.headers }) }
: {}),
});
}
/**
* Registry of feeds. Order is presentation order in the stats/credit text.
* `loadRadiusKm` is the distance from `center` inside which the feed is polled.
@@ -398,7 +571,14 @@ function rioRouteLabel(routeId) {
* url: string, headers?: Record<string, string>,
* license: string, licenseUrl: string, attribution: string,
* defaultMode: string, routeMode?: (routeId: string|null) => string,
* speedUnit?: 'km/h', refreshMs?: number, sourceUrl?: string,
* creditDated?: boolean,
* }>>}
* `speedUnit` marks a feed that publishes km/h where the spec requires m/s;
* the proxy converts it before the snapshot leaves the server. `refreshMs`
* stretches the proxy's cache for an upstream that rate-limits below one
* request per 15 s TTL. `sourceUrl` and `creditDated` add a link and a date
* to the credit for licences that ask for them (`transitFeedCredit`).
*/
export const TRANSIT_FEED_REGISTRY = Object.freeze([
Object.freeze({
@@ -788,6 +968,624 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
defaultMode: 'bus',
routeLabel: rioRouteLabel,
}),
transitFeed({
id: 'zditm-szczecin',
name: 'Szczecin buses and trams',
operator:
'Zarząd Dróg i Transportu Miejskiego w Szczecinie (ZDiTM), Szczecin',
region: 'Szczecin, Poland',
// Every vehicle in a 2026-11-05 snapshot sat between 53.34–53.55 N and
// 14.44–14.77 E, inside 20 km of this point.
center: { lat: 53.44, lon: 14.56 },
loadRadiusKm: 25,
url: 'https://www.zditm.szczecin.pl/storage/gtfs/gtfs-rt-vehicles.pb',
license: 'CC0 1.0',
licenseUrl: 'https://www.zditm.szczecin.pl/en/zditm/for-developers',
attribution:
'Zarząd Dróg i Transportu Miejskiego w Szczecinie (ZDiTM Szczecin)',
terms: {
quote:
'The data are provided free of charge under the CC0 1.0 licence, for use in any context, with no prior notification required.',
note: 'CC0 needs no credit; it is given anyway as a courtesy. ZDiTM gives no guarantee of accuracy or completeness. The developer page says the feed updates every minute; measured on 2026-11-05 the file changed about every 20 seconds, with vehicle timestamps up to 50 seconds old. Speeds are m/s: checked against vehicle movement between two snapshots. The feed carries no route id at all, so every vehicle takes the feed default mode even though the city also runs trams.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'carris-metropolitana-lisboa',
name: 'Carris Metropolitana',
operator: 'Carris Metropolitana (TML), Lisbon Metropolitan Area',
region: 'Lisbon Metropolitan Area, Portugal',
// Every vehicle in a 2026-11-07 snapshot, from Mafra to Setúbal, sat
// between 38.47–39.00 N and 9.47–8.79 W, inside 40 km of this point.
center: { lat: 38.73, lon: -9.13 },
loadRadiusKm: 45,
url: 'https://api.carrismetropolitana.pt/v2/vehicles.pb',
license: 'No separate licence for the realtime feed',
licenseUrl: 'https://github.com/carrismetropolitana/api',
attribution: 'Carris Metropolitana',
terms: {
quote:
'GET /vehicles.pb — Returns vehicle locations in Protobuf format, following the GTFS-RT Vehicle Locations standard.',
note: 'The operator publishes this feed keyless and documented for developers in its public API repository, but states no licence for the realtime endpoint; its static GTFS (github.com/carrismetropolitana/gtfs) is CC BY 4.0. Credited as a courtesy, on the same basis as the Metro Transit and OVapi feeds; switch it off if Carris objects. The quote above is the API README, not a licence. `/vehicles.pb` answers with a 307 to `/v2/vehicles.pb`, so the registry points at the target. Speeds are km/h, not the m/s the spec requires: 2026-11-07 readings of 31–33 matched 6–9 m/s of measured movement, so the proxy converts them. Vehicle reports arrive every 30–50 seconds. Route ids are the GTFS route id inside an area prefix and are read as the line number.',
},
defaultMode: 'bus',
routeLabel: carrisMetropolitanaRouteLabel,
speedUnit: 'km/h',
}),
transitFeed({
id: 'pid-praha',
name: 'Prague PID',
operator: 'Pražská integrovaná doprava (PID), via Golemio',
region: 'Prague and Central Bohemia, Czechia',
// PID reaches across Central Bohemia: on 2026-11-08, 95% of 923 vehicles
// sat within 58 km of Prague, the farthest at 98 km.
center: { lat: 50.08, lon: 14.45 },
loadRadiusKm: 60,
url: 'https://api.golemio.cz/v2/vehiclepositions/gtfsrt/vehicle_positions.pb',
license: 'CC BY',
licenseUrl: 'https://pid.cz/o-systemu/opendata/',
attribution: 'Pražská integrovaná doprava (PID) / Golemio',
terms: {
quote:
'Data, která lze stáhnout přímo zde z webu, jsou stejně jako celý obsah webu opatřena licencí CC-BY',
note: 'The PID open-data page lists this realtime feed and licenses the data it publishes under CC BY, crediting the author and any changes. The same page says data served from other sources follows that source’s licence; the feed is served by Golemio, the city’s data platform, which states none of its own. Keyless since the catalogue moved it off the X-Access-Token endpoint. Speeds are m/s, checked against movement on 2026-11-07. Route ids are `L` plus a number whose range gives the mode and the line (metro `L991` is A, train `L1004` is S4, ferry `L1801` is P1); `pidRoute` holds the table, read from PID’s GTFS routes.txt on 2026-11-09.',
},
defaultMode: 'bus',
routeLabel: pidRouteLabel,
routeMode: pidRouteMode,
}),
transitFeed({
id: 'ztm-warszawa',
name: 'Warsaw buses and trams',
operator: 'Miasto Stołeczne Warszawa, relayed by mkuran.pl',
region: 'Warsaw, Poland',
center: { lat: 52.25, lon: 21.02 },
loadRadiusKm: 30,
url: 'https://mkuran.pl/gtfs/warsaw/vehicles.pb',
license: 'Warsaw Open Data Project Usage Terms',
licenseUrl: 'https://mkuran.pl/gtfs/',
attribution: 'Miasto Stołeczne Warszawa (api.um.warszawa.pl)',
sourceUrl: 'http://api.um.warszawa.pl',
creditDated: true,
terms: {
quote:
'The City Hall requires a credit by providing the name Miasto Stołeczne Warszawa, data download date (use the timestamp from the FeedHeader) and link to http://api.um.warszawa.pl.',
note: 'Positions come from the Warsaw City Hall API, repackaged as GTFS-RT by Mikołaj Kuranowski’s unofficial feed. The credit names the city, links its API (`sourceUrl`) and carries the date of the feed timestamp (`creditDated`), the three things the terms ask for. Vehicle timestamps ran about two minutes old on 2026-11-07, which the delayed playback absorbs.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'tbm-bordeaux',
name: 'Bordeaux TBM',
operator: 'Transports Bordeaux Métropole (TBM), Bordeaux Métropole',
region: 'Bordeaux, France',
center: { lat: 44.85, lon: -0.65 },
loadRadiusKm: 20,
url: 'https://bdx.mecatran.com/utw/ws/gtfsfeed/vehicles/bordeaux?apiKey=opendata-bordeaux-metropole-flux-gtfs-rt',
license: 'Licence Ouverte / Etalab 2.0',
licenseUrl:
'https://transport.data.gouv.fr/datasets/offres-de-services-bus-tram-et-scolaire-au-format-gtfs-netex-gtfs-rt-siri-lite',
attribution: 'Bordeaux Métropole (TBM)',
terms: {
quote: 'licence: fr-lo',
note: 'The quote is the licence field of the national access point’s dataset record (fr-lo is the Licence Ouverte), which asks only for credit. The `apiKey` in the URL is not a credential: it is the same fixed string printed in the open-data listing for everyone. Speeds are m/s. The trams (A–F) and BAT³ boats ride numbered route ids (tram A is `59`), so `tbmRouteMode` and `tbmRouteLabel` map them from TBM’s static GTFS; other numbered lines are buses.',
},
defaultMode: 'bus',
routeLabel: tbmRouteLabel,
routeMode: tbmRouteMode,
}),
transitFeed({
id: 'sendai-city-bus',
name: 'Sendai City Bus',
operator: 'Sendai City Transportation Bureau (仙台市交通局), via ODPT',
region: 'Sendai, Japan',
center: { lat: 38.27, lon: 140.82 },
loadRadiusKm: 22,
url: 'https://api-public.odpt.org/api/v4/gtfs/realtime/odpt_SendaiMunicipal_bus_realtime_information_vehicle',
license: 'CC BY 4.0',
licenseUrl: 'https://creativecommons.org/licenses/by/4.0/',
attribution: '仙台市交通局 (Sendai City Transportation Bureau) / ODPT',
terms: {
quote: 'https://creativecommons.org/licenses/by/4.0/',
note: 'Served by the Open Data Challenge for Public Transportation (ODPT) public API, which needs no key for this feed; the catalogue records CC BY 4.0 as its licence. Vehicle timestamps ran about two minutes old on 2026-11-07. Speeds are m/s.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ztm-poznan',
name: 'Poznań buses and trams',
operator: 'Zarząd Transportu Miejskiego w Poznaniu (ZTM Poznań)',
region: 'Poznań, Poland',
center: { lat: 52.39, lon: 16.92 },
loadRadiusKm: 20,
url: 'https://www.ztm.poznan.pl/pl/dla-deweloperow/getGtfsRtFile/?file=vehicle_positions.pb',
license: 'ZTM Poznań open-data terms',
licenseUrl: 'https://www.ztm.poznan.pl/otwarte-dane/dla-deweloperow/',
attribution: 'Zarząd Transportu Miejskiego w Poznaniu (processed)',
creditDated: true,
terms: {
quote:
'Treści udostępniane są bezwnioskowo i bezpłatnie, na zasadach powszechnego dostępu i stanowią źródło informacji.',
note: 'Reuse is free on three conditions: name the source, give the date of the last update, and say the data were processed. The credit names ZTM, says processed, and carries the date of the feed timestamp (`creditDated`) as the update date. The feed carries no bearing, so heading comes from movement between fixes.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ztm-gdansk',
name: 'Gdańsk buses and trams',
operator: 'Zarząd Transportu Miejskiego w Gdańsku (ZTM Gdańsk)',
region: 'Gdańsk, Poland',
center: { lat: 54.35, lon: 18.6 },
loadRadiusKm: 20,
url: 'https://ckan2.multimediagdansk.pl/gtfs-rt?feed=vehiclePositions',
license: 'CC BY 4.0',
licenseUrl:
'https://dane.gov.pl/pl/dataset/38599,rozklady-jazdy-i-lokalizacja-przystankow-gtfs-rt',
attribution: 'Zarząd Transportu Miejskiego w Gdańsku',
terms: {
note: 'The national catalogue (dane.gov.pl) lists this dataset under CC BY 4.0. No bearing; heading comes from movement. Speeds are m/s.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ets-edmonton',
name: 'Edmonton Transit Service',
operator: 'City of Edmonton (Edmonton Transit Service)',
region: 'Edmonton, AB',
center: { lat: 53.53, lon: -113.52 },
loadRadiusKm: 25,
url: 'https://gtfs.edmonton.ca/TMGTFSRealTimeWebService/Vehicle/VehiclePositions.pb',
license: 'City of Edmonton Open Data Agreement',
licenseUrl:
'https://www.edmonton.ca/transportation/Web-version2.1-OpenDataAgreement.pdf',
attribution:
'Contains information licensed under the Open Data Agreement – City of Edmonton',
terms: {
note: 'The agreement is the same municipal template as Mississauga and Burlington: a licence to use, modify and distribute for any lawful purpose, in any medium. It was read from search excerpts; the PDF itself would not extract here. Route ids are zero-padded. Speeds are m/s.',
},
defaultMode: 'bus',
routeLabel: unpaddedRouteLabel,
}),
transitFeed({
id: 'halifax-transit',
name: 'Halifax Transit',
operator: 'Halifax Regional Municipality (Halifax Transit)',
region: 'Halifax, NS',
center: { lat: 44.7, lon: -63.6 },
loadRadiusKm: 22,
url: 'https://gtfs.halifax.ca/realtime/Vehicle/VehiclePositions.pb',
license: 'Open Government Licence – Halifax',
licenseUrl: 'https://www.halifax.ca/home/open-data/open-data-license',
attribution:
'Contains information licenced under the Open Government Licence – Halifax',
terms: {
quote:
'The information provider grants you a worldwide, royalty-free, perpetual, non-exclusive licence to use the Information, including for commercial purposes, subject to the terms below.',
note: 'Version 1.0, modelled on the Open Government Licence – Canada 2.0. The attribution is the licence’s own standard statement, with a link to the licence where possible. Logos and crests are excluded and no endorsement may be implied, so the credit stays plain text. The page refuses automated requests (403); its text was read in a browser on 2026-11-08. Speeds are m/s.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'bc-transit-victoria',
name: 'Victoria Regional Transit',
operator: 'BC Transit (Victoria Regional Transit System)',
region: 'Victoria, BC',
center: { lat: 48.53, lon: -123.43 },
loadRadiusKm: 28,
url: 'https://bct.tmix.se/gtfs-realtime/vehicleupdates.pb?operatorIds=48',
license: 'BC Transit Open Data Terms of Use',
licenseUrl: 'https://www.bctransit.com/open-data/terms-of-use',
attribution: 'BC Transit',
terms: {
quote:
'BC Transit grants you a limited, revocable and non-exclusive license to use, reproduce, and redistribute the Data in accordance with these Terms.',
note: 'The grant is revocable, like the Ontario municipal templates. Route ids carry a `-VIC` system suffix. Speeds are m/s.',
},
defaultMode: 'bus',
routeLabel: bcTransitRouteLabel,
}),
transitFeed({
id: 'tam-montpellier',
name: 'Montpellier TaM',
operator: 'Montpellier Méditerranée Métropole (TaM)',
region: 'Montpellier, France',
center: { lat: 43.61, lon: 3.87 },
loadRadiusKm: 20,
url: 'https://gtfsproxy.e-tam.fr/COMMON/VehiclePosition.pb',
license: 'ODbL',
licenseUrl:
'https://transport.data.gouv.fr/datasets/offre-de-transport-tam-en-temps-reel-gtfs-rt-urbain-et-suburbain',
attribution: 'Montpellier Méditerranée Métropole (TaM)',
terms: {
quote: 'licence: odc-odbl',
note: 'The quote is the dataset record’s licence field. ODbL asks for credit and share-alike on a derived database; the layer redistributes no database, it draws the positions. Speeds are km/h: readings ran 3.3 times the measured movement on 2026-11-07, so the proxy converts them.',
},
defaultMode: 'bus',
speedUnit: 'km/h',
}),
transitFeed({
id: 'ztp-krakow-bus',
name: 'Kraków buses',
operator: 'Zarząd Transportu Publicznego w Krakowie (ZTP Kraków)',
region: 'Kraków, Poland',
center: { lat: 50.06, lon: 19.94 },
loadRadiusKm: 22,
url: 'https://gtfs.ztp.krakow.pl/VehiclePositions_A.pb',
license: 'No licence stated',
licenseUrl: 'https://gtfs.ztp.krakow.pl/',
attribution: 'Zarząd Transportu Publicznego w Krakowie',
terms: {
note: 'ZTP publishes this feed keyless on its own GTFS server and lists it in the Mobility Database, but states no licence there or on dane.gov.pl. Shipped on the same basis as Metro Transit and OVapi; switch it off if ZTP objects.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ztp-krakow-tram',
name: 'Kraków trams',
operator: 'Zarząd Transportu Publicznego w Krakowie (ZTP Kraków)',
region: 'Kraków, Poland',
center: { lat: 50.06, lon: 19.94 },
loadRadiusKm: 22,
url: 'https://gtfs.ztp.krakow.pl/VehiclePositions_T.pb',
license: 'No licence stated',
licenseUrl: 'https://gtfs.ztp.krakow.pl/',
attribution: 'Zarząd Transportu Publicznego w Krakowie',
terms: { note: 'Same server and basis as the bus feed.' },
defaultMode: 'tram',
}),
transitFeed({
id: 'vilnius-transport',
name: 'Vilnius public transport',
operator: 'SĮ Susisiekimo paslaugos, Vilnius',
region: 'Vilnius, Lithuania',
center: { lat: 54.69, lon: 25.28 },
loadRadiusKm: 20,
url: 'https://www.stops.lt/vilnius/vehicle_positions.pb',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2383',
attribution: 'SĮ Susisiekimo paslaugos (stops.lt)',
terms: {
note: 'Published keyless by the city transport agency on stops.lt; no licence found. Shipped on the same basis as Metro Transit and OVapi. Answered 522 once on 2026-11-07 and normally since.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'tpbi-bucuresti',
name: 'Bucharest public transport',
operator: 'Asociația de Dezvoltare Intercomunitară TPBI, Bucharest–Ilfov',
region: 'Bucharest, Romania',
center: { lat: 44.43, lon: 26.1 },
loadRadiusKm: 25,
url: 'https://gtfs.tpbi.ro/api/gtfs-rt/vehiclePositions',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2104',
attribution: 'TPBI (Transport Public București–Ilfov)',
terms: {
note: 'Keyless public endpoint from the metropolitan transport authority; no licence found. Same basis as Metro Transit and OVapi.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'roma-mobilita',
name: 'Rome public transport',
operator: 'Roma Servizi per la Mobilità',
region: 'Rome, Italy',
center: { lat: 41.89, lon: 12.5 },
loadRadiusKm: 35,
url: 'https://romamobilita.it/wp-content/uploads/shared/rome_rtgtfs_vehicle_positions_feed.pb',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-1776',
attribution: 'Roma Servizi per la Mobilità',
terms: {
note: 'Keyless file on the agency’s own site; the catalogue’s older `/sites/default/files/` path now 404s. No licence found; same basis as Metro Transit and OVapi. Fewer than one vehicle in five carries a bearing, so most headings come from movement.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'gtt-torino',
name: 'Turin GTT',
operator: 'Gruppo Torinese Trasporti (GTT)',
region: 'Turin, Italy',
center: { lat: 45.07, lon: 7.68 },
loadRadiusKm: 20,
url: 'https://percorsieorari.gtt.to.it/das_gtfsrt/vehicle_position.aspx',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2696',
attribution: 'Gruppo Torinese Trasporti (GTT)',
terms: {
note: 'Official keyless endpoint; no licence found. Same basis as Metro Transit and OVapi. Route ids append `U` for urban lines.',
},
defaultMode: 'bus',
routeLabel: gttRouteLabel,
}),
transitFeed({
id: 'actv-venezia-bus',
name: 'Venice ACTV buses',
operator: 'Azienda del Consorzio Trasporti Veneziano (ACTV)',
region: 'Venice, Italy',
center: { lat: 45.4, lon: 12.2 },
loadRadiusKm: 38,
url: 'https://tpl.actv.it/aut/GTFSRT/vehiclePositions',
license: 'ACTV open-data catalogue',
licenseUrl:
'https://actv.avmspa.it/it/content/catalogo-dei-dati-metadati-e-banche-dati-actv',
attribution: 'ACTV S.p.A.',
terms: {
note: 'ACTV lists this feed in its own open-data catalogue; that page would not render for a script, so its licence is not quoted. Same basis as Metro Transit and OVapi. Route ids append a two-letter network code (`_UM`, `_ES`, `_UN`).',
},
defaultMode: 'bus',
routeLabel: actvRouteLabel,
}),
transitFeed({
id: 'actv-venezia-waterbus',
name: 'Venice ACTV waterbuses',
operator: 'Azienda del Consorzio Trasporti Veneziano (ACTV) Navigazione',
region: 'Venice, Italy',
center: { lat: 45.43, lon: 12.33 },
loadRadiusKm: 15,
url: 'https://tpl.actv.it/nav/GTFSRT/vehiclePositions',
license: 'ACTV open-data catalogue',
licenseUrl:
'https://actv.avmspa.it/it/content/catalogo-dei-dati-metadati-e-banche-dati-actv',
attribution: 'ACTV S.p.A.',
terms: { note: 'Same catalogue and basis as the ACTV bus feed.' },
defaultMode: 'ferry',
routeLabel: actvRouteLabel,
}),
transitFeed({
id: 'adelaide-metro',
name: 'Adelaide Metro',
operator: 'Adelaide Metro (Government of South Australia)',
region: 'Adelaide, SA',
center: { lat: -34.93, lon: 138.6 },
loadRadiusKm: 35,
url: 'https://gtfs.adelaidemetro.com.au/v1/realtime/vehicle_positions',
// Any Accept naming a protobuf type gets base64 text labelled JSON; only
// */* returns the binary feed (checked 2026-11-08).
headers: { Accept: '*/*' },
license: 'No licence stated for the realtime feed',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-1772',
attribution: 'Adelaide Metro',
terms: {
note: 'Official keyless endpoint; the state catalogue page refused automated reads, so no licence is quoted. Same basis as Metro Transit and OVapi. Speeds are m/s. The server picks its encoding from Accept, hence the override.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'marta-atlanta',
name: 'MARTA buses',
operator: 'Metropolitan Atlanta Rapid Transit Authority (MARTA)',
region: 'Atlanta, GA',
center: { lat: 33.78, lon: -84.39 },
loadRadiusKm: 35,
url: 'https://gtfs-rt.itsmarta.com/TMGTFSRealTimeWebService/vehicle/vehiclepositions.pb',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-1601',
attribution: 'MARTA',
terms: {
note: 'Official keyless endpoint; no licence found. Same basis as Metro Transit and OVapi. Speeds are m/s.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'rtd-denver',
name: 'Denver RTD',
operator: 'Regional Transportation District (RTD), Denver',
region: 'Denver, CO',
center: { lat: 39.75, lon: -104.99 },
loadRadiusKm: 55,
url: 'https://open-data.rtd-denver.com/files/gtfs-rt/rtd/VehiclePosition.pb',
license: 'RTD GTFS-realtime licence agreement',
licenseUrl:
'https://www.rtd-denver.com/business-center/open-spatial-data/gtfs-realtime-license-agreement',
attribution: 'Regional Transportation District (RTD)',
terms: {
quote:
'RTD hereby grants you non-exclusive, limited and revocable rights to use, reproduce, and redistribute the Data',
note: 'Read 2026-11-09. The agreement is a click-through (“By clicking to download the Data files, you confirm that you have read and agree”) that RTD may change without notice; it permits redistribution, asks for no credit wording, and bars RTD trademarks from being used with the data, so the credit stays plain text. The feed itself is keyless. Speeds are m/s.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ctp-cluj',
name: 'Cluj-Napoca CTP',
operator: 'Compania de Transport Public Cluj-Napoca',
region: 'Cluj-Napoca, Romania',
center: { lat: 46.77, lon: 23.59 },
loadRadiusKm: 15,
url: 'https://cluj-rt-feed.gtfs.ro/vehiclePositions',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2614',
attribution: 'Compania de Transport Public Cluj-Napoca',
terms: {
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'ctp-iasi',
name: 'Iași CTP',
operator: 'Compania de Transport Public Iași',
region: 'Iași, Romania',
center: { lat: 47.16, lon: 27.59 },
loadRadiusKm: 15,
url: 'https://iasi-rt-feed.gtfs.ro/vehiclePositions',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2118',
attribution: 'Compania de Transport Public Iași',
terms: {
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'mpk-rzeszow',
name: 'Rzeszów city transport',
operator: 'Rzeszowski Transport Miejski (MPK Rzeszów)',
region: 'Rzeszów, Poland',
center: { lat: 50.04, lon: 22.0 },
loadRadiusKm: 15,
url: 'https://www.mpkrzeszow.pl/gtfs/rt/gtfsrt.pb',
license: 'MPK Rzeszów open data',
licenseUrl: 'https://www.mpkrzeszow.pl/otwartedane/',
attribution: 'MPK Rzeszów',
terms: {
note: 'Listed on the operator’s open-data page, which names no licence. No bearing; heading comes from movement.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'emt-malaga',
name: 'Málaga EMT',
operator: 'Empresa Malagueña de Transportes (EMT)',
region: 'Málaga, Spain',
center: { lat: 36.72, lon: -4.42 },
loadRadiusKm: 15,
url: 'https://gtfs.emtmalaga.es/GTFSRTapi/api/vehicleposition',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2213',
attribution: 'EMT Málaga',
terms: {
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi. No bearing; heading comes from movement.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'carris-lisboa',
name: 'Carris (Lisbon city)',
operator: 'Carris – Companhia Carris de Ferro de Lisboa',
region: 'Lisbon, Portugal',
center: { lat: 38.74, lon: -9.15 },
loadRadiusKm: 15,
url: 'https://gateway.carris.pt/gateway/gtfs/api/v2.11/GTFS/realtime/vehiclepositions',
license: 'No licence stated',
licenseUrl: 'https://mobilitydatabase.org/feeds/gtfs_rt/mdb-2930',
attribution: 'Carris',
terms: {
note: 'Keyless official gateway; no licence found. Same basis as Metro Transit and OVapi. Carries neither bearing nor speed, and vehicle reports run about a minute old. Route ids append a variant.',
},
defaultMode: 'bus',
routeLabel: carrisRouteLabel,
}),
transitFeed({
id: 'mybas-johor',
name: 'BAS.MY Johor Bahru',
operator: 'BAS.MY, via data.gov.my',
region: 'Johor Bahru, Malaysia',
center: { lat: 1.51, lon: 103.75 },
loadRadiusKm: 35,
url: 'https://api.data.gov.my/gtfs-realtime/vehicle-position/mybas-johor/',
license: 'CC BY 4.0',
licenseUrl: 'https://developer.data.gov.my/realtime-api/gtfs-realtime',
attribution: 'BAS.MY / data.gov.my',
// data.gov.my allows 4 GTFS-Realtime requests a minute and refreshes
// vehicle positions every 30 seconds, so the proxy asks half as often as
// the default 15 s TTL would.
refreshMs: 30_000,
terms: {
quote: 'All GTFS Realtime feeds are licensed under CC BY 4.0.',
note: 'Served keyless by Malaysia’s national open-data API (developer.data.gov.my, read 2026-11-09). Its rate-limit page caps GTFS Realtime at 4 requests a minute and answers 429 above that; the feed updates every 30 seconds, hence `refreshMs`. Without the trailing slash the API redirects. Route ids append an operator code.',
},
defaultMode: 'bus',
routeLabel: mybasJohorRouteLabel,
}),
transitFeed({
id: 'mybas-kota-bharu',
name: 'BAS.MY Kota Bharu',
operator: 'BAS.MY, via data.gov.my',
region: 'Kota Bharu, Malaysia',
// Routes run south into Kelantan: 95% of vehicles within 58 km on 2026-11-08.
center: { lat: 6.06, lon: 102.22 },
loadRadiusKm: 60,
url: 'https://api.data.gov.my/gtfs-realtime/vehicle-position/mybas-kota-bharu/',
license: 'CC BY 4.0',
licenseUrl: 'https://developer.data.gov.my/realtime-api/gtfs-realtime',
attribution: 'BAS.MY / data.gov.my',
refreshMs: 30_000,
terms: {
quote: 'All GTFS Realtime feeds are licensed under CC BY 4.0.',
note: 'Same API, licence and rate limit as Johor Bahru.',
},
defaultMode: 'bus',
}),
transitFeed({
id: 'astuce-rouen',
name: 'Rouen Astuce',
operator: 'Métropole Rouen Normandie (Astuce), réseau TCAR',
region: 'Rouen, France',
center: { lat: 49.44, lon: 1.1 },
loadRadiusKm: 20,
url: 'https://api.mrn.cityway.fr/dataflow/vehicle-tc-tr/download?provider=TCAR&dataFormat=gtfs-rt',
license: 'Licence Ouverte 2.0',
licenseUrl:
'https://transport.data.gouv.fr/datasets/donnees-statiques-et-temps-reel-du-reseau-astuce-metropole-rouen-normandie',
attribution: 'Métropole Rouen Normandie (Astuce)',
terms: {
quote: 'licence: lov2',
note: 'The metropolis publishes its realtime data under the Licence Ouverte (dataset record quoted), and this is its own TCAR vehicle feed from that record (178 vehicles on 2026-11-09). The suburban TAE and TNI networks are separate feeds in the same record and are not read here. Route ids carry the network prefix (`TCAR:`); `TCAR:90` is the Métro (a street-running light rail, drawn as a tram) and `TCAR:99` the Calypso boat.',
},
defaultMode: 'bus',
routeLabel: astuceRouteLabel,
routeMode: astuceRouteMode,
}),
transitFeed({
id: 'mpm-toulon',
name: 'Toulon Mistral',
operator: 'Métropole Toulon Provence Méditerranée (réseau Mistral)',
region: 'Toulon, France',
center: { lat: 43.12, lon: 5.94 },
loadRadiusKm: 18,
url: 'https://feed-rdtpm-toulon.ratpdev.com/VehiclePosition/GTFS-RT',
license: 'Licence Ouverte 2.0',
licenseUrl:
'https://transport.data.gouv.fr/datasets/reseau-de-transport-urbain-de-la-metropole-toulon-provence-mediterranee',
attribution: 'Métropole Toulon Provence Méditerranée (Mistral)',
terms: {
quote: 'licence: lov2',
note: 'Dataset record’s licence field quoted. Speeds are km/h: readings ran 3.5 times the measured movement on 2026-11-07, so the proxy converts them. Route ids are zero-padded.',
},
defaultMode: 'bus',
routeLabel: unpaddedRouteLabel,
speedUnit: 'km/h',
}),
transitFeed({
id: 'lia-le-havre',
name: 'Le Havre LiA',
operator: 'Le Havre Seine Métropole (LiA)',
region: 'Le Havre, France',
center: { lat: 49.49, lon: 0.11 },
loadRadiusKm: 18,
url: 'https://opendata.transports-lia.fr/gtfs-rt/VehiclePosition.pb',
license: 'ODbL',
licenseUrl:
'https://transport.data.gouv.fr/datasets/reseau-de-transport-en-commun-lia-gtfs-siri',
attribution: 'Le Havre Seine Métropole (LiA)',
terms: {
quote: 'licence: odc-odbl',
note: 'The network publishes under ODbL (dataset record quoted), and this is its own GTFS-RT vehicle feed from that record (105 vehicles on 2026-11-09). The layer draws positions and redistributes no database. Route ids carry the network prefix `8-`; lines A and B are the tramway.',
},
defaultMode: 'bus',
routeLabel: liaRouteLabel,
routeMode: liaRouteMode,
}),
transitFeed({
id: 'filbleu-tours',
name: 'Tours Fil Bleu',
operator: 'Syndicat des Mobilités de Touraine (Fil Bleu)',
region: 'Tours, France',
center: { lat: 47.39, lon: 0.69 },
loadRadiusKm: 18,
url: 'https://data.filbleu.fr/ws-tr/gtfs-rt/opendata/vehicle-positions',
license: 'Licence Ouverte 2.0',
licenseUrl:
'https://transport.data.gouv.fr/datasets/fil-bleu-syndicat-des-mobilites-gtfs-gtfs-rt',
attribution: 'Fil Bleu – Syndicat des Mobilités de Touraine',
terms: {
quote: 'licence: lov2',
note: 'Dataset record’s licence field quoted.',
},
defaultMode: 'bus',
}),
]);
/**
+226
View File
@@ -552,3 +552,229 @@ test('Rio feeds are CC BY 4.0 and live', () => {
'Rio has a DATA_SOURCES row',
);
});
test('Szczecin is CC0, live, covers the city and not Berlin', () => {
const feed = getTransitFeed('zditm-szczecin');
assert.equal(feed.defaultEnabled, true);
assert.equal(feed.license, 'CC0 1.0');
assert.equal(
feed.licenseUrl,
'https://www.zditm.szczecin.pl/en/zditm/for-developers',
);
assert.match(feed.terms.quote, /CC0 1\.0 licence/);
assert.match(feed.attribution, /ZDiTM/);
assert.equal(feed.routeLabel, undefined, 'the feed has no route ids');
assert.equal(transitModeFor(feed, null), 'bus');
const ids = (lat, lon) => transitFeedsInRange(lat, lon).map((f) => f.id);
assert.ok(ids(53.4285, 14.5528).includes('zditm-szczecin'), 'city centre');
assert.ok(ids(53.5, 14.7).includes('zditm-szczecin'), 'north-east edge');
assert.ok(!ids(52.52, 13.405).includes('zditm-szczecin'), 'Berlin');
const sources = readFileSync(
new URL('../../DATA_SOURCES.md', import.meta.url),
'utf8',
);
assert.ok(
sources.split('\n').some((l) => l.startsWith('| **ZDiTM Szczecin')),
'Szczecin has a DATA_SOURCES row',
);
});
test('Carris Metropolitana covers Lisbon from Mafra to Setúbal, not Porto', () => {
const feed = getTransitFeed('carris-metropolitana-lisboa');
assert.equal(feed.defaultEnabled, true);
assert.equal(feed.url, 'https://api.carrismetropolitana.pt/v2/vehicles.pb');
assert.equal(feed.speedUnit, 'km/h');
assert.match(feed.terms.note, /no licence for the realtime endpoint/);
const ids = (lat, lon) => transitFeedsInRange(lat, lon).map((f) => f.id);
for (const [place, lat, lon] of [
['Lisbon', 38.7223, -9.1393],
['Mafra', 38.9369, -9.3277],
['Setúbal', 38.5244, -8.8882],
]) {
assert.ok(ids(lat, lon).includes(feed.id), place);
}
assert.ok(!ids(41.1579, -8.6291).includes(feed.id), 'Porto');
const sources = readFileSync(
new URL('../../DATA_SOURCES.md', import.meta.url),
'utf8',
);
assert.ok(
sources.split('\n').some((l) => l.startsWith('| **Carris Metropolitana')),
'Lisbon has a DATA_SOURCES row',
);
});
test('Carris Metropolitana route ids read as the line number on the bus', () => {
const feed = getTransitFeed('carris-metropolitana-lisboa');
assert.equal(transitRouteLabel(feed, '[LA77N]1708_0'), '1708');
assert.equal(transitRouteLabel(feed, '[BNA17]2772_1'), '2772');
assert.equal(transitRouteLabel(feed, 'unexpected'), 'unexpected');
assert.equal(transitRouteLabel(feed, null), null);
});
// The 2026-11 batch: one landmark per feed, inside its own radius.
const NEW_CITY_LANDMARKS = {
'pid-praha': [50.0875, 14.4213],
'ztm-warszawa': [52.2297, 21.0122],
'tbm-bordeaux': [44.8378, -0.5792],
'sendai-city-bus': [38.2602, 140.8824],
'ztm-poznan': [52.4064, 16.9252],
'ztm-gdansk': [54.352, 18.6466],
'ets-edmonton': [53.5461, -113.4938],
'halifax-transit': [44.6488, -63.5752],
'bc-transit-victoria': [48.4284, -123.3656],
'tam-montpellier': [43.6108, 3.8767],
'ztp-krakow-bus': [50.0614, 19.9366],
'ztp-krakow-tram': [50.0614, 19.9366],
'vilnius-transport': [54.6872, 25.2797],
'tpbi-bucuresti': [44.4268, 26.1025],
'roma-mobilita': [41.9028, 12.4964],
'gtt-torino': [45.0703, 7.6869],
'actv-venezia-bus': [45.4408, 12.3155],
'actv-venezia-waterbus': [45.4408, 12.3155],
'adelaide-metro': [-34.9285, 138.6007],
'marta-atlanta': [33.749, -84.388],
'rtd-denver': [39.7392, -104.9903],
'ctp-cluj': [46.7712, 23.6236],
'ctp-iasi': [47.1585, 27.6014],
'mpk-rzeszow': [50.0412, 21.9991],
'emt-malaga': [36.7213, -4.4214],
'carris-lisboa': [38.7223, -9.1393],
'mybas-johor': [1.4927, 103.7414],
'mybas-kota-bharu': [6.1254, 102.2381],
'astuce-rouen': [49.4432, 1.0999],
'mpm-toulon': [43.1242, 5.928],
'lia-le-havre': [49.4944, 0.1079],
'filbleu-tours': [47.3941, 0.6848],
};
test('every city in the 2026-11 batch is live, licensed and covers its own centre', () => {
for (const [id, [lat, lon]] of Object.entries(NEW_CITY_LANDMARKS)) {
const feed = getTransitFeed(id);
assert.ok(feed, `${id} is routable`);
assert.ok(
publicTransitCatalog().some((f) => f.id === id),
`${id} is offered to the browser`,
);
assert.ok(feed.terms?.note, `${id} records the basis it ships on`);
assert.ok(
transitFeedsInRange(lat, lon).some((f) => f.id === id),
`${id} covers its city`,
);
}
// A feed's radius stays local: Warsaw is not polled for Kraków.
assert.ok(
!transitFeedsInRange(50.0614, 19.9366).some((f) => f.id === 'ztm-warszawa'),
);
});
test('feeds with no stated licence say so and name the basis they ship on', () => {
for (const feed of TRANSIT_FEED_REGISTRY.filter((f) =>
/^No licence stated/.test(f.license),
)) {
assert.match(
feed.terms.note,
/Metro Transit and OVapi|Same .*basis/,
`${feed.id} names its basis`,
);
}
});
test('route ids in the 2026-11 batch read as the line on the vehicle', () => {
const label = (id, routeId) => transitRouteLabel(getTransitFeed(id), routeId);
assert.equal(label('pid-praha', 'L135'), '135');
assert.equal(label('ets-edmonton', '009'), '9');
assert.equal(label('mpm-toulon', '0002'), '2');
assert.equal(label('gtt-torino', '10NU'), '10N');
assert.equal(label('actv-venezia-waterbus', '5.1_UN'), '5.1');
assert.equal(label('actv-venezia-bus', '53E_ES'), '53E');
assert.equal(label('bc-transit-victoria', '95-VIC'), '95');
assert.equal(label('carris-lisboa', '172_1'), '172');
assert.equal(label('astuce-rouen', 'TCAR:93'), '93');
assert.equal(label('mybas-johor', 'J33CWLMYJB'), 'J33');
// Unmatched and absent ids pass through untouched.
assert.equal(label('pid-praha', 'S4'), 'S4');
assert.equal(label('gtt-torino', null), null);
});
test('trams, waterbuses and buses are told apart where the ids allow it', () => {
const mode = (id, routeId) => transitModeFor(getTransitFeed(id), routeId);
assert.equal(mode('pid-praha', 'L22'), 'tram');
assert.equal(mode('pid-praha', 'L135'), 'bus');
assert.equal(mode('tbm-bordeaux', '16'), 'bus');
assert.equal(mode('lia-le-havre', '8-B'), 'tram');
assert.equal(mode('lia-le-havre', '8-C3'), 'bus');
assert.equal(mode('ztp-krakow-tram', null), 'tram');
assert.equal(mode('actv-venezia-waterbus', '1_UN'), 'ferry');
});
test('feeds that publish km/h are marked for conversion, and only those', () => {
const kmh = TRANSIT_FEED_REGISTRY.filter((f) => f.speedUnit === 'km/h')
.map((f) => f.id)
.sort();
assert.deepEqual(kmh, [
'carris-metropolitana-lisboa',
'mpm-toulon',
'tam-montpellier',
]);
});
// Route ids as the live feeds and the operators' own GTFS routes.txt carried
// them on 2026-11-09: the ranges and numbered tram ids are not guessable from
// the line names riders see.
test('Prague route-id ranges give metro, trains, ferries and trolleybuses their mode', () => {
const feed = getTransitFeed('pid-praha');
const read = (routeId) => [
transitModeFor(feed, routeId),
transitRouteLabel(feed, routeId),
];
assert.deepEqual(read('L22'), ['tram', '22']);
assert.deepEqual(read('L58'), ['bus', '58'], 'trolleybus');
assert.deepEqual(read('L49'), ['rail', 'LD'], 'Petřín funicular');
assert.deepEqual(read('L135'), ['bus', '135']);
assert.deepEqual(read('L803'), ['bus', 'X3']);
assert.deepEqual(read('L991'), ['subway', 'A']);
assert.deepEqual(read('L993'), ['subway', 'C']);
assert.deepEqual(read('L1004'), ['rail', 'S4']);
assert.deepEqual(read('L1109'), ['rail', 'R9']);
assert.deepEqual(read('L1204'), ['rail', 'L1204'], 'no label to derive');
assert.deepEqual(read('L1801'), ['ferry', 'P1']);
assert.deepEqual(read('L1703'), ['bus', 'L1703']);
assert.deepEqual(read('L2841'), ['bus', '841']);
assert.deepEqual(read('S4'), ['bus', 'S4'], 'unknown ids keep the default');
});
test('Bordeaux trams ride numbered route ids and keep their letters', () => {
const feed = getTransitFeed('tbm-bordeaux');
for (const [routeId, line] of [
['59', 'A'],
['62', 'D'],
['163', 'E'],
]) {
assert.equal(transitModeFor(feed, routeId), 'tram', routeId);
assert.equal(transitRouteLabel(feed, routeId), line);
}
assert.equal(transitModeFor(feed, '952'), 'ferry');
assert.equal(transitModeFor(feed, '01'), 'bus');
assert.equal(transitRouteLabel(feed, '01'), '1');
});
test('Rouen Métro and Calypso are not buses; Le Havre reads its own ids', () => {
const feed = getTransitFeed('astuce-rouen');
assert.equal(transitModeFor(feed, 'TCAR:90'), 'tram');
assert.equal(transitRouteLabel(feed, 'TCAR:90'), 'Métro');
assert.equal(transitModeFor(feed, 'TCAR:99'), 'ferry');
assert.equal(transitModeFor(feed, 'TCAR:93'), 'bus');
assert.equal(transitRouteLabel(feed, 'TAE:F'), 'F');
const lia = getTransitFeed('lia-le-havre');
assert.equal(transitModeFor(lia, '8-FUNI'), 'rail');
assert.equal(transitRouteLabel(lia, '8-C3'), 'C3');
assert.equal(transitRouteLabel(lia, '8-09'), '9');
assert.equal(transitRouteLabel(lia, '8-A'), 'A');
});
test('data.gov.my feeds ask the proxy for no more than its 4 a minute', () => {
for (const id of ['mybas-johor', 'mybas-kota-bharu']) {
assert.ok(getTransitFeed(id).refreshMs >= 30_000, id);
}
});
+22 -3
View File
@@ -257,24 +257,43 @@ export function buildTransitSnapshot(feed, bytes, now = Date.now()) {
truncated: decoded.truncated,
count: decoded.vehicles.length,
vehicles: repairVehicleTimestamps(
decoded.vehicles,
feed.speedUnit === 'km/h'
? decoded.vehicles.map((v) =>
v.speedMps === null ? v : { ...v, speedMps: v.speedMps / 3.6 },
)
: decoded.vehicles,
decoded.timestamp,
Math.floor(now / 1000),
),
};
}
/**
* Fresh window for one feed's cached snapshot: the shared TTL, stretched by a
* registry `refreshMs` for upstreams that rate-limit below one request per
* TTL (data.gov.my allows 4 a minute). Never shorter than the shared TTL.
* @param {{ refreshMs?: number }|null|undefined} feed Registry entry.
* @returns {number}
*/
export function transitFeedTtlMs(feed) {
const refresh = feed?.refreshMs;
return Number.isFinite(refresh) && refresh > TRANSIT_PROXY_TTL_MS
? refresh
: TRANSIT_PROXY_TTL_MS;
}
/**
* Classify a cache entry for the request policy.
* @param {{ at: number }|null|undefined} entry Cached snapshot (`at` = fetch ms).
* @param {number} now
* @param {number} [ttlMs] Fresh window; `transitFeedTtlMs(feed)` for a feed.
* @returns {'none'|'fresh'|'stale'|'expired'}
*/
export function transitCacheState(entry, now) {
export function transitCacheState(entry, now, ttlMs = TRANSIT_PROXY_TTL_MS) {
if (!entry || !Number.isFinite(entry.at)) return 'none';
const age = now - entry.at;
if (age < 0) return 'fresh';
if (age < TRANSIT_PROXY_TTL_MS) return 'fresh';
if (age < ttlMs) return 'fresh';
if (age < TRANSIT_PROXY_STALE_MAX_MS) return 'stale';
return 'expired';
}
+43
View File
@@ -12,6 +12,7 @@ import {
repairVehicleTimestamps,
resolveTransitRoute,
transitCacheState,
transitFeedTtlMs,
transitRedirectDecision,
transitResponseHeaders,
transitUpstreamHeaders,
@@ -294,6 +295,27 @@ test('Rio speeds pass through as the m/s they are published in', () => {
assert.equal(rio.vehicles[0].speedMps, 10);
});
test('Carris Metropolitana km/h speeds leave the proxy as m/s', () => {
// 2026-11-07: readings of 31-33 matched 6-9 m/s of measured movement.
const bytes = encodeFeed({
entities: [
{ id: 'moving', lat: 38.72, lon: -9.14, speed: 36 },
{ id: 'parked', lat: 38.73, lon: -9.15 },
],
});
const feed = getTransitFeed('carris-metropolitana-lisboa');
const lisbon = buildTransitSnapshot(feed, bytes, 1);
const byId = Object.fromEntries(lisbon.vehicles.map((v) => [v.id, v]));
assert.ok(Math.abs(byId.moving.speedMps - 10) < 1e-6);
assert.equal(byId.parked.speedMps, null, 'no speed stays no speed');
const szczecin = buildTransitSnapshot(
getTransitFeed('zditm-szczecin'),
encodeFeed({ entities: [{ id: 'm', lat: 53.43, lon: 14.55, speed: 10 }] }),
1,
);
assert.equal(szczecin.vehicles[0].speedMps, 10, 'm/s feeds are untouched');
});
test('conditional-request validators and gzip ride along with feed identification', () => {
const entur = getTransitFeed('entur-norway');
const plain = transitUpstreamHeaders(entur);
@@ -375,3 +397,24 @@ test('client history validates response bounds, epochs and cancellation through
{ name: 'AbortError' },
);
});
test('Adelaide asks for */* because a protobuf Accept gets base64 text back', () => {
const headers = transitUpstreamHeaders(getTransitFeed('adelaide-metro'));
assert.equal(headers.Accept, '*/*');
// Every other feed keeps the protobuf-first Accept.
assert.match(
transitUpstreamHeaders(getTransitFeed('mbta')).Accept,
/protobuf/,
);
});
test('a feed refreshMs stretches its fresh window, never shortens it', () => {
const johor = getTransitFeed('mybas-johor');
assert.equal(transitFeedTtlMs(johor), 30_000);
assert.equal(transitFeedTtlMs(getTransitFeed('mbta')), TRANSIT_PROXY_TTL_MS);
assert.equal(transitFeedTtlMs({ refreshMs: 1_000 }), TRANSIT_PROXY_TTL_MS);
const now = 1_000_000;
const entry = { at: now - 20_000 };
assert.equal(transitCacheState(entry, now), 'stale');
assert.equal(transitCacheState(entry, now, transitFeedTtlMs(johor)), 'fresh');
});