mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge origin/main into the renderer-contract branch: the procedural fleet models drawn through the renderer's model sets
Aircraft, military, local ADS-B, vessel, transit and rail models come from the fleet model set, loaded up front and drawn life size through the draw port's models sets; no layer touches the viewer or Cesium outside src/render/cesium/. The models capability gains glTF bytes (gltf), a per-axis stretch (axisScale), a colour for tinted parts (maskColor) and a cut below the origin (clip: 'belowOrigin'), with conformance checks. Main's rail layer and Data Library are ported to the ports; the CCTV footprint probe keeps the globe-terrain clamp through the query port.
This commit is contained in:
commit
e3865f462f
533 files changed
+55738
-2518
No files matched your search
@@ -182,7 +182,22 @@ export function createPanel({ state: layerState, parts }) {
|
||||
: null;
|
||||
}
|
||||
|
||||
/** The tracked airliner's photo with its credit, or null. The subject
|
||||
/** The credit line: the photographer, and an open photo's licence. A
|
||||
* photo whose answer names no photographer shows no photographer. */
|
||||
function photoCredit(photo) {
|
||||
if (photo.licence)
|
||||
return photo.photographer
|
||||
? t('Photo: {photographer} · {licence}', {
|
||||
photographer: photo.photographer,
|
||||
licence: photo.licence,
|
||||
})
|
||||
: t('Photo · {licence}', { licence: photo.licence });
|
||||
return photo.photographer
|
||||
? t('Photo © {photographer}', { photographer: photo.photographer })
|
||||
: '';
|
||||
}
|
||||
|
||||
/** The subject's photo with its credit, or null. The subject
|
||||
* refresh resolves it; only the subject it was resolved for shows it. */
|
||||
function presentPhoto(subject) {
|
||||
const held = layerState.subjectPhoto;
|
||||
@@ -198,10 +213,7 @@ export function createPanel({ state: layerState, parts }) {
|
||||
width: photo.width ?? null,
|
||||
height: photo.height ?? null,
|
||||
link: photo.link,
|
||||
// A photo whose answer names no photographer shows no credit line.
|
||||
credit: photo.photographer
|
||||
? t('Photo © {photographer}', { photographer: photo.photographer })
|
||||
: '',
|
||||
credit: photoCredit(photo),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -113,7 +113,52 @@ test('the Contacts view has no photo without one, or with another subject’s',
|
||||
);
|
||||
});
|
||||
|
||||
test('only the tracked flight has a photo: not a vessel, an installation, a military aircraft or another flight', () => {
|
||||
test('the selected vessel shows its own photo, by its id', () => {
|
||||
const asked = [];
|
||||
const { resolveSubjectPhoto, subjectFromContext } = createSubject({
|
||||
state: {},
|
||||
services: {
|
||||
flights: {},
|
||||
military: {},
|
||||
vessels: {
|
||||
getVesselPhoto: (id) => {
|
||||
asked.push(id);
|
||||
return id === 'uuid-1' ? PHOTO : null;
|
||||
},
|
||||
},
|
||||
installations: {},
|
||||
},
|
||||
parts: { navigation: { isFlightLayer: () => false } },
|
||||
});
|
||||
assert.deepEqual(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-1' }),
|
||||
PHOTO,
|
||||
);
|
||||
assert.equal(
|
||||
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-2' }),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(asked, ['uuid-1', 'uuid-2']);
|
||||
const vessel = (label, mmsi) =>
|
||||
subjectFromContext({
|
||||
layerId: 'ais-live-vessels',
|
||||
id: 'ais-uuid-1',
|
||||
label,
|
||||
latitude: 38.3,
|
||||
longitude: -123.05,
|
||||
properties: { vesselId: 'uuid-1', mmsi },
|
||||
});
|
||||
assert.equal(
|
||||
vessel('USCGC SOCKEYE', '366999709').label,
|
||||
'USCGC SOCKEYE · MMSI 366999709',
|
||||
);
|
||||
assert.equal(vessel('USCGC SOCKEYE', '366999709').id, 'uuid-1');
|
||||
// A vessel named by its MMSI, or without one, is not given it twice.
|
||||
assert.equal(vessel('MMSI 366999709', '366999709').label, 'MMSI 366999709');
|
||||
assert.equal(vessel('USCGC SOCKEYE', null).label, 'USCGC SOCKEYE');
|
||||
});
|
||||
|
||||
test('only the tracked flight has a flight photo: not an installation, a military aircraft or another flight', () => {
|
||||
const tracked = {
|
||||
layerId: 'flights',
|
||||
id: 'abc123',
|
||||
|
||||
@@ -406,17 +406,20 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The tracked airliner's Planespotters photo, for the Contacts panel.
|
||||
* The subject's photo, for the Contacts panel: the tracked airliner's
|
||||
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
|
||||
*
|
||||
* Only the flights layer looks photos up, and only for the plane it tracks;
|
||||
* a vessel, an installation, a military aircraft or an untracked flight has
|
||||
* none.
|
||||
* The flights layer looks photos up only for the plane it tracks, the
|
||||
* vessel layer only for the vessel selected; an installation, a military
|
||||
* aircraft or an untracked flight has none.
|
||||
* @param {{layerId: string, id: string}|null} subject Current subject.
|
||||
* @param {?object} [tracked] The subject's tracked descriptor, when the
|
||||
* caller already has it.
|
||||
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string}}
|
||||
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string, licence?: string}}
|
||||
*/
|
||||
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
|
||||
if (subject?.layerId === 'ais-live-vessels')
|
||||
return aisLiveVesselsLayer.getVesselPhoto?.(subject.id) ?? null;
|
||||
return subject?.layerId === 'flights' && tracked?.photo
|
||||
? tracked.photo
|
||||
: null;
|
||||
@@ -514,10 +517,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
|
||||
const latitude = Number(record.latitude);
|
||||
const longitude = Number(record.longitude);
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
// A vessel reads as its name and MMSI; a vessel named by its MMSI alone
|
||||
// already carries it.
|
||||
const label = String(record.label || record.id);
|
||||
const mmsi = String(record.properties?.mmsi || '');
|
||||
return {
|
||||
layerId: record.layerId,
|
||||
id: record.properties?.vesselId || record.id,
|
||||
label: record.label || record.id,
|
||||
// i18n-ignore: MMSI is a radio identity code, as on the vessel card
|
||||
label: mmsi && !label.includes(mmsi) ? `${label} · MMSI ${mmsi}` : label,
|
||||
memberNames: record.properties?.memberNames || [],
|
||||
position: fromDegrees(longitude, latitude, 0),
|
||||
};
|
||||
|
||||
+54
-11
@@ -260,6 +260,21 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
return Math.max(PROBE_MIN_RANGE_M, hitDistance - PROBE_CLEARANCE_M);
|
||||
}
|
||||
|
||||
/**
|
||||
* Distance along a pitched-down view axis to flat ground at the mount's own
|
||||
* ground height, or null for an axis at or above the horizon.
|
||||
* @param {number} mountHeightM Mount height above its ground.
|
||||
* @param {number} pitchDeg Axis pitch (negative looks down).
|
||||
* @returns {number|null}
|
||||
*/
|
||||
|
||||
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
|
||||
const height = Number(mountHeightM);
|
||||
const pitch = Number(pitchDeg);
|
||||
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
|
||||
return height / Math.sin((Math.min(89, -pitch) * Math.PI) / 180);
|
||||
}
|
||||
|
||||
/**
|
||||
* Unit ECEF direction of the frustum view axis (heading/pitch) at a position.
|
||||
* Used by the plane orientation and the activation obstruction probe — both
|
||||
@@ -509,12 +524,16 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
* range, clamp the plane's effective range just short of the first hit so the
|
||||
* "big and dramatic" true end cap never clips into downtown buildings.
|
||||
*
|
||||
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
|
||||
* never per-frame (the zero-raycast invariant applies to steady state). The
|
||||
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
|
||||
* probe entirely. Probe failure/miss keeps the unclamped range.
|
||||
* On a globe map it also casts along the same axis against the globe's
|
||||
* terrain (flat ground at the mount's ground when terrain is missed or met
|
||||
* beyond the range) and clamps at the nearer end. These are the ONLY
|
||||
* raycasts in the whole CCTV subsystem — once per activation, never
|
||||
* per-frame (the zero-raycast invariant applies to steady state). The
|
||||
* per-camera range slider overrides the clamp: a user-set rangeScale skips
|
||||
* the probe entirely. A miss on the photoreal stack or a probe failure
|
||||
* keeps the unclamped range.
|
||||
*
|
||||
* The cast is made now, against the scene as it is, and answers a
|
||||
* The casts are made now, against the scene as it is, and answer a
|
||||
* microtask later: the clamp then lands by rewriting the geometry from the
|
||||
* ground it was last written at, before the next frame draws. A newer
|
||||
* activation, or the camera's deactivation, drops an answer still to come.
|
||||
@@ -537,17 +556,40 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
|
||||
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
|
||||
const { dir } = frustumFrameEcef(camera, mountPos);
|
||||
// The cast sees through everything the layer draws.
|
||||
return Promise.resolve(parts.rendering.obstructionHit(mountPos, dir))
|
||||
.then((hit) => {
|
||||
if (!hit || record.probeToken !== token) return;
|
||||
// The casts see through everything the layer draws. The surface cast
|
||||
// meets what is drawn on the globe (the photoreal tiles); on a globe
|
||||
// map the axis also ends on the globe's terrain, the nearer of that and
|
||||
// any surface hit. A hit at or beyond the range counts as none. Terrain
|
||||
// still loading at a coarse level can be missed or met beyond the
|
||||
// range; then flat ground at the mount's own ground stands in for it.
|
||||
const inRange = (d) => Number.isFinite(d) && d > 0 && d < camera.rangeM;
|
||||
return Promise.all([
|
||||
parts.rendering.obstructionHit(mountPos, dir),
|
||||
parts.rendering.terrainHit?.(mountPos, dir) ?? null,
|
||||
])
|
||||
.then(([hit, terrain]) => {
|
||||
if (record.probeToken !== token) return;
|
||||
if (record.camera.id !== layerState._activeCameraId) return;
|
||||
// A layer torn down or re-initialised since (another viewer, or
|
||||
// a new record for the same camera) is not the one it asked for.
|
||||
if (layerState._viewer !== viewer) return;
|
||||
if (layerState._recordById?.get(record.camera.id) !== record) return;
|
||||
const dist = distance(mountPos, hit);
|
||||
const clamp = activationProbeClampRange(camera.rangeM, dist);
|
||||
const hitDist = hit ? distance(mountPos, hit) : NaN;
|
||||
const distances = inRange(hitDist) ? [hitDist] : [];
|
||||
if (terrain) {
|
||||
const terrainDist = terrain.hit
|
||||
? distance(mountPos, terrain.hit)
|
||||
: NaN;
|
||||
const ground = inRange(terrainDist)
|
||||
? terrainDist
|
||||
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
|
||||
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
|
||||
}
|
||||
if (!distances.length) return;
|
||||
const clamp = activationProbeClampRange(
|
||||
camera.rangeM,
|
||||
Math.min(...distances),
|
||||
);
|
||||
if (!Number.isFinite(clamp)) return;
|
||||
record.probeClampRangeM = clamp;
|
||||
if (Number.isFinite(record.groundAltM))
|
||||
@@ -685,6 +727,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
hasShippedFootprint,
|
||||
footprintPose,
|
||||
activationProbeClampRange,
|
||||
flatGroundAxisDistance,
|
||||
frustumFrameEcef,
|
||||
applyFrustumGeometry,
|
||||
updateRecordGeometry,
|
||||
|
||||
@@ -75,6 +75,7 @@ export function createCctvLayer({ services, source }) {
|
||||
deriveCalBadge: parts.calibration.deriveCalBadge,
|
||||
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
|
||||
activationProbeClampRange: parts.geometry.activationProbeClampRange,
|
||||
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
|
||||
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
|
||||
_createCctvProjectionPlaneForTest:
|
||||
parts.testing._createCctvProjectionPlaneForTest,
|
||||
|
||||
@@ -788,6 +788,22 @@ export function createRendering({
|
||||
return query.rayCast({ origin, direction }, { against: 'surface' });
|
||||
}
|
||||
|
||||
/**
|
||||
* On a globe map, where the activation probe's axis meets the globe's
|
||||
* terrain: `{hit}`, `hit` null on a miss. Null when the globe is not shown
|
||||
* (the photoreal stack), where only the surface cast counts.
|
||||
* @returns {Promise<{hit: object|null}|null>}
|
||||
*/
|
||||
async function terrainHit(origin, direction) {
|
||||
const viewer = layerState._viewer;
|
||||
if (findGlobe(viewer)?.isGlobeVisible?.() !== true) return null;
|
||||
const query = findQuery(viewer);
|
||||
if (!query) return null;
|
||||
return {
|
||||
hit: await query.rayCast({ origin, direction }, { against: 'terrain' }),
|
||||
};
|
||||
}
|
||||
|
||||
/** Whether there is a query port to cast the activation probe through. */
|
||||
function canPickFromRay() {
|
||||
return typeof findQuery(layerState._viewer)?.rayCast === 'function';
|
||||
@@ -928,6 +944,7 @@ export function createRendering({
|
||||
buildCoverageEntities,
|
||||
placeCoverageLines,
|
||||
obstructionHit,
|
||||
terrainHit,
|
||||
canPickFromRay,
|
||||
removeCoverageEntities,
|
||||
extractPickedCameraId,
|
||||
|
||||
@@ -21,7 +21,13 @@ export function createDirectionsSource({
|
||||
signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
const payload = await response.json();
|
||||
// Proxy error pages may not be JSON.
|
||||
let payload = null;
|
||||
try {
|
||||
payload = await response.json();
|
||||
} catch (error) {
|
||||
if (response.ok) throw error;
|
||||
}
|
||||
signal?.throwIfAborted();
|
||||
// Failures keep their English message and carry the HTTP status and the
|
||||
// server's refusal text, so the layer can show them in the language.
|
||||
@@ -39,7 +45,8 @@ export function createDirectionsSource({
|
||||
{ status: 429, refusal },
|
||||
);
|
||||
}
|
||||
if (!response.ok && !payload?.error)
|
||||
// A 5xx body may mislabel an outage as a route refusal.
|
||||
if (response.status >= 500 || (!response.ok && !payload?.error))
|
||||
throw Object.assign(
|
||||
new Error(`Routing unavailable (HTTP ${response.status})`),
|
||||
{ status: response.status },
|
||||
|
||||
@@ -41,3 +41,15 @@ test('route failures are surfaced without fallback requests', async () => {
|
||||
assert.equal(calls, 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a routing outage stays an outage when its body carries an error', async () => {
|
||||
const source = createDirectionsSource({ fetchImpl: async () =>
|
||||
Response.json({ ok: false, error: 'routing service unavailable' }, { status: 502 }) });
|
||||
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
|
||||
});
|
||||
|
||||
test('a routing outage page that is not JSON still reads as an outage', async () => {
|
||||
const source = createDirectionsSource({ fetchImpl: async () =>
|
||||
new Response('<html>Bad Gateway</html>', { status: 502, headers: { 'content-type': 'text/html' } }) });
|
||||
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
|
||||
});
|
||||
@@ -32,10 +32,7 @@ test('a FIRMS snapshot that ends at a set time names it instead of LIVE', (conte
|
||||
assert.equal(methods.getStats().at, at);
|
||||
assert.equal(methods.getStats().source, 'NASA FIRMS', 'the row drops LIVE');
|
||||
setLocale('de');
|
||||
assert.equal(
|
||||
methods.getStats().loadingLabel,
|
||||
'24 Std. bis 21.10. 15:00 UTC',
|
||||
);
|
||||
assert.equal(methods.getStats().loadingLabel, '24 h bis 21.10. 15:00 UTC');
|
||||
layerState._at = null;
|
||||
setLocale('en');
|
||||
assert.equal(methods.getStats().loadingLabel, 'LIVE · updated 2m ago');
|
||||
|
||||
@@ -167,10 +167,10 @@ export function createEnrichment({
|
||||
if (klass !== meta.klass) {
|
||||
meta.klass = klass;
|
||||
parts.icons._applyIconPresentation(icao24);
|
||||
// Hangar fleet: the class's GLB/scale may have changed — resync the
|
||||
// live model, any in-flight load, and the tracked standalone model.
|
||||
parts.rendering._syncModelToClass(icao24);
|
||||
}
|
||||
// The type picks the fleet model and its length — resync the live
|
||||
// model, any in-flight load, and the tracked standalone model.
|
||||
parts.rendering._syncModelToClass(icao24);
|
||||
}
|
||||
if (icao24 === flightState._trackedIcao && flightState._trackedEntity)
|
||||
parts.tracking._updateTrackedLabelModel(icao24);
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { PLANE_MODEL_URL } from './policy.js';
|
||||
import { loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
|
||||
export function createLifecycle({
|
||||
flightState,
|
||||
@@ -44,10 +44,12 @@ export function createLifecycle({
|
||||
flightState._focusEvidenceIds.clear();
|
||||
flightState._viewer = viewer;
|
||||
parts.icons._createIcons(viewer);
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
preloadUrl: resolveAsset(PLANE_MODEL_URL),
|
||||
// The models' draw sets. Every fleet model loads once, up front, for
|
||||
// every layer that draws them (fleetModels.js), so no model is fetched
|
||||
// while the session runs; until the set has loaded aircraft stay icons.
|
||||
parts.rendering._createModelSets(viewer);
|
||||
loadFleetModelSet({ resolveAsset }).catch(() => {
|
||||
/* aircraft stay icons */
|
||||
});
|
||||
flightState._grounded.clear();
|
||||
flightState._floorPinned.clear();
|
||||
|
||||
@@ -1,52 +1,70 @@
|
||||
import {
|
||||
CLASS_MODEL_REAL,
|
||||
CLASS_MODEL_URL,
|
||||
CLASS_SCALE_3D,
|
||||
} from '../../data/aircraftClass.js';
|
||||
import {
|
||||
trailAnchorForModel,
|
||||
visualCenterForModel,
|
||||
} from '../../data/modelVisualAnchor.js';
|
||||
import {
|
||||
MODEL_BELLY_OFFSET_NATIVE,
|
||||
MODEL_COLOR_BLEND_AMOUNT,
|
||||
MODEL_NATIVE_RADIUS_M,
|
||||
MODEL_SCALE,
|
||||
PLANE_MODEL_URL,
|
||||
} from './policy.js';
|
||||
import { aircraftModelSpec, fleetModelSet } from '../../data/fleetModels.js';
|
||||
import { MODEL_COLOR_BLEND_AMOUNT } from './policy.js';
|
||||
|
||||
/**
|
||||
* The glTF asset, scale and measured geometry a civil aircraft class renders
|
||||
* with. Real per-class GLBs are baked to real-world meters (scale 1, measured
|
||||
* belly and radius); classes without one share airplane.glb at the class's
|
||||
* 3D scale. Shared by the Flights layer and the Local ADS-B layer so both draw
|
||||
* the same model for the same class.
|
||||
* @param {string} klass Aircraft class from `classifyAircraft`.
|
||||
* @returns {{url:string, scale:number, nativeRadiusM:number, bellyM:number,
|
||||
* blendAmount:number, visualCenterNative:object, trailAnchorNative:object}}
|
||||
* What an aircraft draws with before the fleet model set has loaded: no
|
||||
* model (its billboard stays the visual), with neutral geometry for any
|
||||
* reader that asks.
|
||||
*/
|
||||
export function civilAircraftModelSpec(klass) {
|
||||
const real = CLASS_MODEL_REAL[klass];
|
||||
if (real) {
|
||||
return {
|
||||
url: real.url,
|
||||
scale: 1,
|
||||
nativeRadiusM: real.radiusM,
|
||||
bellyM: real.bellyM,
|
||||
export const UNLOADED_AIRCRAFT_MODEL_SPEC = Object.freeze({
|
||||
model: null,
|
||||
url: null,
|
||||
scale: 1,
|
||||
scaleXYZ: Object.freeze([1, 1, 1]),
|
||||
length: 0,
|
||||
nativeRadiusM: 20,
|
||||
clearanceM: 0,
|
||||
bellyM: 0,
|
||||
elevationM: 0,
|
||||
tinted: false,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: Object.freeze([0, 0, 0]),
|
||||
trailAnchorNative: Object.freeze([0, 0, 0]),
|
||||
key: 'unloaded',
|
||||
});
|
||||
|
||||
/**
|
||||
* The fleet model, life-size scale and measured geometry an aircraft draws
|
||||
* with, chosen by its ICAO type and emitter category (`fleetModels.js`).
|
||||
* Shared by the Flights, Military Flights and Local ADS-B layers so all three
|
||||
* draw the same model for the same aircraft. `bellyM` is the model's scaled
|
||||
* clearance: how far a grounded aircraft's origin stands above the ground.
|
||||
* @param {{typeCode?: string|null, type?: string|null,
|
||||
* category?: string|number|null}|null|undefined} aircraft
|
||||
* @param {object|null} [set] The loaded fleet model set.
|
||||
* @returns {object} The spec, or {@link UNLOADED_AIRCRAFT_MODEL_SPEC} before
|
||||
* the set has loaded.
|
||||
*/
|
||||
export function aircraftLayerModelSpec(aircraft, set = fleetModelSet()) {
|
||||
if (!set) return UNLOADED_AIRCRAFT_MODEL_SPEC;
|
||||
// Layers ask on every tick; each type and category is resolved once per set.
|
||||
let cache = specCaches.get(set);
|
||||
if (!cache) specCaches.set(set, (cache = new Map()));
|
||||
const key = aircraftModelSpecCacheKey(aircraft);
|
||||
let layerSpec = cache.get(key);
|
||||
if (!layerSpec) {
|
||||
const spec = aircraftModelSpec(set, {
|
||||
typeCode: aircraft?.typeCode ?? aircraft?.type ?? null,
|
||||
category: aircraft?.category ?? null,
|
||||
});
|
||||
layerSpec = Object.freeze({
|
||||
...spec,
|
||||
bellyM: spec.clearanceM,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: visualCenterForModel(real.url),
|
||||
trailAnchorNative: trailAnchorForModel(real.url),
|
||||
};
|
||||
});
|
||||
cache.set(key, layerSpec);
|
||||
}
|
||||
const scale = MODEL_SCALE * (CLASS_SCALE_3D[klass] || 1);
|
||||
const url = CLASS_MODEL_URL[klass] || PLANE_MODEL_URL;
|
||||
return {
|
||||
url,
|
||||
scale,
|
||||
nativeRadiusM: MODEL_NATIVE_RADIUS_M,
|
||||
bellyM: MODEL_BELLY_OFFSET_NATIVE * scale,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: visualCenterForModel(url),
|
||||
trailAnchorNative: trailAnchorForModel(url),
|
||||
};
|
||||
return layerSpec;
|
||||
}
|
||||
|
||||
/** @type {WeakMap<object, Map<string, object>>} set -> cache key -> spec */
|
||||
const specCaches = new WeakMap();
|
||||
|
||||
/**
|
||||
* Cache key of an aircraft's model spec: what selects its model.
|
||||
* @param {object|null|undefined} aircraft
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aircraftModelSpecCacheKey(aircraft) {
|
||||
return `${aircraft?.typeCode ?? aircraft?.type ?? ''}|${aircraft?.category ?? ''}`;
|
||||
}
|
||||
@@ -373,7 +373,7 @@ export function createMotion({
|
||||
const viewportHeightPx = _viewportHeightPx();
|
||||
if (parts.rendering._modelOwnsVisual(icao24)) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
flightState.records.data.get(icao24),
|
||||
);
|
||||
const scale = trackedModelScaleForPixelCap({
|
||||
baseScale: spec.scale,
|
||||
@@ -549,7 +549,7 @@ export function createMotion({
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
return modelVisualAnchor(
|
||||
flightState._trackedModel.matrix,
|
||||
@@ -594,7 +594,7 @@ export function createMotion({
|
||||
)
|
||||
return 0;
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
return (
|
||||
spec.nativeRadiusM *
|
||||
@@ -608,7 +608,7 @@ export function createMotion({
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
// Through the model's OWN render chain (modelVisualAnchor's hand-rolled
|
||||
// half-correction put this offset on the lateral axis — see
|
||||
|
||||
@@ -44,8 +44,6 @@ export const GROUND_SCALE = 0.8;
|
||||
// the slots go to either the nearest planes ('proximity') or every in-view plane ('all'), each
|
||||
// backed by a hard cap so a draw-call explosion can't tank the frame (no instancing yet).
|
||||
|
||||
export const PLANE_MODEL_URL = '/models/airplane.glb';
|
||||
|
||||
export const MODEL_ALT_CEIL_M = 800000;
|
||||
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
|
||||
|
||||
@@ -60,10 +58,6 @@ export const TRACKED_MODEL_MIN_PX = 40;
|
||||
export const TRACKED_MODEL_MAX_PX = 200;
|
||||
// owner-selected close-range tracked-target feel
|
||||
|
||||
export const MODEL_NATIVE_RADIUS_M = 34.41;
|
||||
|
||||
export const MODEL_SCALE = 1;
|
||||
// airplane.glb is transform-applied and baked to real-world meters
|
||||
// Per-mode caps. Each model is its own draw call (no instancing yet), so these bound the frame cost.
|
||||
|
||||
export const MODEL_MAX = 150;
|
||||
@@ -95,21 +89,12 @@ export const MODEL_ALL_KEEP_M = 450000;
|
||||
// all: KEEP modeled planes out to 450 km
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// airplane.glb nose is opposite the renderer's heading 0
|
||||
// every fleet model is nose -X: opposite the renderer's heading 0
|
||||
// Owner launch-polish direction: models should read as clean light silhouettes,
|
||||
// with only a weak diffuse contribution from the existing approved textures.
|
||||
// with only a weak diffuse contribution from the models' own colours.
|
||||
|
||||
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
|
||||
|
||||
// Grounded-model belly offset: airplane.glb's centred origin sits 6.719 m ABOVE its
|
||||
// lowest vertex (glTF Y-up scene AABB with node transforms applied — same reader as
|
||||
// modelScale.test.mjs, measured after its 24× transform bake). × class multiplier ≈ 5.0–9.7 m
|
||||
// of lift, so a ground-snapped model rests its lowest geometry (gear/belly) ON the sampled
|
||||
// tile skin instead of sinking to the fuselage-centerline origin. Locked against the GLB
|
||||
// by modelScale.test.mjs.
|
||||
|
||||
export const MODEL_BELLY_OFFSET_NATIVE = 6.719;
|
||||
|
||||
/** The tracked contact's tint, and its billboard once a model takes over. */
|
||||
export const TRACKED_CYAN = rgba('#00FFFF');
|
||||
export const CYAN_TRANSPARENT = rgba('#00FFFF', 0);
|
||||
@@ -210,6 +195,24 @@ export const LANDED_SPEED_MAX_MPS = 23;
|
||||
|
||||
export const FLEET_DR_INTERVAL_MS = 80;
|
||||
|
||||
/**
|
||||
* The icon-to-model rules the aircraft layers follow, as the Vessels, Transit
|
||||
* and Rail layers take them (`createFleetModelLayer`): the same altitude
|
||||
* ceiling, minimum pixel size, proximity/all caps, add/keep radii and
|
||||
* eligibility cadence, so every layer turns icons into models at one distance.
|
||||
*/
|
||||
export const FLEET_MODEL_POLICY = Object.freeze({
|
||||
altitudeCeilingM: MODEL_ALT_CEIL_M,
|
||||
minimumPixelSize: MODEL_MIN_PX,
|
||||
cap: MODEL_MAX,
|
||||
capAll: MODEL_MAX_ALL,
|
||||
addM: MODEL_PROX_ADD_M,
|
||||
addAllM: MODEL_ALL_ADD_M,
|
||||
keepM: MODEL_PROX_KEEP_M,
|
||||
keepAllM: MODEL_ALL_KEEP_M,
|
||||
intervalMs: FLEET_DR_INTERVAL_MS,
|
||||
});
|
||||
|
||||
/** Max course slew (deg/s) — well above real turns (≤4°/s), hides fix-boundary
|
||||
* steps. Scaled down toward COURSE_MIN_DPS at low speed (courseSlewCapDps). */
|
||||
|
||||
|
||||
@@ -474,9 +474,7 @@ export function createQueries({
|
||||
// and rises only as the coarse ground-floor cell warms. Zero extra sampling and
|
||||
// no `_modelDisplayPosition` call from postRender. Icon-owned contacts keep
|
||||
// the drawn icon position — icon and bracket are co-located there.
|
||||
const spec = modelOwnsVisual
|
||||
? parts.rendering._modelSpec(info?.klass)
|
||||
: null;
|
||||
const spec = modelOwnsVisual ? parts.rendering._modelSpec(info) : null;
|
||||
const pos = isTracked
|
||||
? parts.motion._trackedVisualCached() ||
|
||||
icons.position(icao24, t, object._iconPos)
|
||||
|
||||
@@ -1,4 +1,7 @@
|
||||
import { civilAircraftModelSpec } from './modelSpec.js';
|
||||
import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
} from './modelSpec.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { isEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
@@ -59,11 +62,14 @@ export function createRendering({
|
||||
);
|
||||
}
|
||||
|
||||
function _modelSpec(klass) {
|
||||
const cached = flightState._specCache.get(klass);
|
||||
/** The fleet model an aircraft draws with, by its type and emitter category. */
|
||||
function _modelSpec(meta) {
|
||||
const key = aircraftModelSpecCacheKey(meta);
|
||||
const cached = flightState._specCache.get(key);
|
||||
if (cached) return cached;
|
||||
const spec = civilAircraftModelSpec(klass);
|
||||
flightState._specCache.set(klass, spec);
|
||||
const spec = aircraftLayerModelSpec(meta);
|
||||
// Not cached before the model set loads: the answer changes once it has.
|
||||
if (spec.model) flightState._specCache.set(key, spec);
|
||||
return spec;
|
||||
}
|
||||
|
||||
|
||||
@@ -175,9 +175,14 @@ export function createFlightSnapshotRenderer({
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
// Poll-path class change (category updates): same model resync rule
|
||||
// as the enrichment path — the class's GLB/scale may have changed.
|
||||
if (prevMeta?.klass !== meta.klass) rendering._syncModelToClass(icao24);
|
||||
// Poll-path type or category change: same model resync rule as the
|
||||
// enrichment path — the fleet model or its scale may have changed.
|
||||
if (
|
||||
prevMeta?.klass !== meta.klass ||
|
||||
prevMeta?.category !== meta.category ||
|
||||
prevMeta?.typeCode !== meta.typeCode
|
||||
)
|
||||
rendering._syncModelToClass(icao24);
|
||||
} else {
|
||||
// Hidden while tracked: the tracked entity replaces it.
|
||||
icons._addIcon(icao24);
|
||||
|
||||
@@ -18,17 +18,13 @@ export function createFlightState({ source, services }) {
|
||||
* layer); see followsClock and displayDelayMs in policy.js. */
|
||||
flightState.timeline = null;
|
||||
|
||||
/** Per-class model spec. Hangar-fleet classes (CLASS_MODEL_REAL) ship GLBs
|
||||
* vertex-baked to real-world METERS in the airplane.glb axis convention, so
|
||||
* they render at scale 1 with their own measured belly lift and bounding
|
||||
* radius. Every other class keeps the shared-airplane.glb formula
|
||||
* (MODEL_SCALE × CLASS_SCALE_3D). nativeRadiusM is PER SCALE UNIT — pixel-cap
|
||||
* math multiplies it by `scale`, so world radius = nativeRadiusM × scale in
|
||||
* both branches. The code-side MIX tint dominates every existing asset so
|
||||
* class silhouettes stay light without modifying third-party GLBs/textures. */
|
||||
/* Specs are static per class, and the detection weld now asks for one per
|
||||
* MODELED contact per frame (up to the fleet cap) on top of the 12 Hz fleet
|
||||
* pass — so this is memoized, as militaryFlights.js already does. */
|
||||
/** Model spec per aircraft type and emitter category (aircraftLayerModelSpec in
|
||||
* flights/modelSpec.js): the procedural fleet model that draws the type, life size,
|
||||
* with its measured clearance, bounding radius and trail anchor. nativeRadiusM is PER
|
||||
* SCALE UNIT — pixel-cap math multiplies it by `scale`. The code-side MIX tint dominates
|
||||
* every model so silhouettes stay light (and this layer's own colour). Memoized: the
|
||||
* detection weld asks for one per MODELED contact per frame on top of the 12 Hz fleet
|
||||
* pass. */
|
||||
|
||||
flightState._specCache = new Map();
|
||||
|
||||
|
||||
@@ -65,10 +65,10 @@ export function createTesting({
|
||||
*/
|
||||
|
||||
/** Turn a test's model fields into the contact's model record, in place. */
|
||||
function _modelRecordForTest(fields, klass) {
|
||||
const spec = parts.rendering._modelSpec(klass);
|
||||
function _modelRecordForTest(fields, meta) {
|
||||
const spec = parts.rendering._modelSpec(meta);
|
||||
const base = createModelRecord({
|
||||
specKey: parts.rendering._specKeyFor(klass),
|
||||
specKey: parts.rendering._specKeyFor(meta),
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
});
|
||||
@@ -110,7 +110,7 @@ export function createTesting({
|
||||
_seedIconForTest(icao24, icon, tracked);
|
||||
flightState._models.clear();
|
||||
for (const [key, model] of models)
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta?.klass));
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta));
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map([[icao24, meta]]);
|
||||
flightState._positionHistory = new Map([[icao24, history]]);
|
||||
|
||||
@@ -280,6 +280,9 @@ export function createLocalAdsbLayer({
|
||||
);
|
||||
marker.evidence = evidence;
|
||||
marker.klass = klass;
|
||||
// What picks its fleet model: the adsbdb type, else the emitter category.
|
||||
marker.typeCode = enrichment.get(marker.record.icao)?.typeCode || null;
|
||||
marker.category = marker.record.category || null;
|
||||
if (!marker.carrier) return;
|
||||
marker.iconKind = klass;
|
||||
const scale = billboardScale(marker);
|
||||
|
||||
@@ -39,6 +39,15 @@ const iconOf = (draw, id) => layerSet(draw, ':markers')?.items.get(id);
|
||||
const ringOf = (draw, id) => layerSet(draw, ':rings')?.items.get(id);
|
||||
/** Degrees of latitude where an aircraft's icon now is. */
|
||||
const latitudeOf = (draw, id) => toLonLatH(iconOf(draw, id).pos).lat;
|
||||
import { loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
|
||||
import { fetchPublicFile } from '../../testSupport/fleetGlb.mjs';
|
||||
|
||||
// The layer draws models only once the fleet model set has loaded; load it from disk.
|
||||
const realInfo = console.info;
|
||||
console.info = () => {};
|
||||
await loadFleetModelSet({ fetchImpl: fetchPublicFile });
|
||||
console.info = realInfo;
|
||||
|
||||
function fakeReceiver(initial = {}) {
|
||||
const state = {
|
||||
@@ -572,8 +581,14 @@ test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t
|
||||
const models = layerSet(draw, ':models');
|
||||
const model = () => models.items.get('local-adsb:a0b702');
|
||||
assert.ok(model(), 'admitted');
|
||||
assert.equal(model().url, '/models/bell206.glb', 'the Flights helicopter');
|
||||
assert.equal(model().scale, 1);
|
||||
const spec = aircraftLayerModelSpec({ category: 'A7' });
|
||||
assert.equal(
|
||||
model().url,
|
||||
'/models/fleet/helicopters/generic_heli.glb',
|
||||
'the Flights rotorcraft model',
|
||||
);
|
||||
assert.ok(model().gltf instanceof Uint8Array, 'built from the loaded set');
|
||||
assert.equal(model().scale, spec.scale, 'drawn life size');
|
||||
assert.deepEqual(model().tint, MAGENTA);
|
||||
assert.deepEqual(model().colorBlend, { mode: 'mix', amount: 0.94 });
|
||||
assert.equal(model().environmentMap, false);
|
||||
@@ -1196,7 +1211,7 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
|
||||
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
|
||||
});
|
||||
|
||||
test('a grounded aircraft changing class keeps its drawn model on its own belly offset until the new one is ready', () => {
|
||||
test('a grounded aircraft changing type keeps its drawn model on its own belly offset until the new one is ready', () => {
|
||||
const { draw, viewer, camera } = modelViewer();
|
||||
const models = createLocalAdsbModels({
|
||||
viewer,
|
||||
@@ -1210,31 +1225,33 @@ test('a grounded aircraft changing class keeps its drawn model on its own belly
|
||||
const marker = {
|
||||
position: fromDegrees(0, 0, 0),
|
||||
courseDeg: 0,
|
||||
klass: 'light',
|
||||
typeCode: 'C172',
|
||||
onGround: true,
|
||||
};
|
||||
const markers = new Map([['a', marker]]);
|
||||
const display = { models3d: true, models3dMode: 'proximity' };
|
||||
const light = 100 + aircraftLayerModelSpec({ typeCode: 'C172' }).bellyM;
|
||||
const widebody = 100 + aircraftLayerModelSpec({ typeCode: 'B789' }).bellyM;
|
||||
const height = () =>
|
||||
toLonLatH(draw.sets.get('test:models').items.get('a').pos).height;
|
||||
models.frame(markers, display, 100_000);
|
||||
draw.ready('test:models', 'a');
|
||||
models.frame(markers, display, 100_001);
|
||||
assert.ok(Math.abs(height() - 101.36) < 0.01, 'light: its belly offset');
|
||||
marker.klass = 'widebody';
|
||||
assert.ok(Math.abs(height() - light) < 0.01, 'light: its belly offset');
|
||||
marker.typeCode = 'B789';
|
||||
models.frame(markers, display, 200_000);
|
||||
assert.equal(
|
||||
draw.sets.get('test:models').items.get('a').url,
|
||||
'/models/b789.glb',
|
||||
'/models/fleet/aircraft/b789.glb',
|
||||
);
|
||||
assert.ok(Math.abs(height() - 101.36) < 0.01, 'the light model still draws');
|
||||
assert.ok(Math.abs(height() - light) < 0.01, 'the light model still draws');
|
||||
draw.ready('test:models', 'a');
|
||||
models.frame(markers, display, 200_001);
|
||||
assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own');
|
||||
assert.ok(Math.abs(height() - widebody) < 0.01, 'the widebody, on its own');
|
||||
models.destroy();
|
||||
});
|
||||
|
||||
test('a class change takes its belly offset with the new model, however soon it is ready; a scale-only change at once', () => {
|
||||
test('a type change takes its belly offset with the new model, however soon it is ready; a scale-only change at once', () => {
|
||||
const { draw, viewer, camera } = modelViewer();
|
||||
const models = createLocalAdsbModels({
|
||||
viewer,
|
||||
@@ -1248,29 +1265,37 @@ test('a class change takes its belly offset with the new model, however soon it
|
||||
const marker = {
|
||||
position: fromDegrees(0, 0, 0),
|
||||
courseDeg: 0,
|
||||
klass: 'narrowbody',
|
||||
typeCode: 'A320',
|
||||
onGround: true,
|
||||
};
|
||||
const markers = new Map([['a', marker]]);
|
||||
const display = { models3d: true, models3dMode: 'proximity' };
|
||||
const bellyOf = (typeCode) =>
|
||||
100 + aircraftLayerModelSpec({ typeCode }).bellyM;
|
||||
const item = () => draw.sets.get('test:models').items.get('a');
|
||||
const height = () => toLonLatH(item().pos).height;
|
||||
models.frame(markers, display, 100_000);
|
||||
draw.ready('test:models', 'a');
|
||||
models.frame(markers, display, 100_001);
|
||||
assert.ok(Math.abs(height() - 106.719) < 0.01, 'narrowbody');
|
||||
// The same asset at another scale: no load, no ready.
|
||||
marker.klass = 'glider';
|
||||
assert.ok(Math.abs(height() - bellyOf('A320')) < 0.01, 'A320');
|
||||
// The same model at another length: no load, no ready.
|
||||
marker.typeCode = 'A321';
|
||||
models.frame(markers, display, 100_002);
|
||||
assert.equal(item().url, '/models/airplane.glb');
|
||||
assert.equal(item().scale, 0.75);
|
||||
assert.ok(Math.abs(height() - 105.03925) < 0.01, 'at once');
|
||||
// Another asset, ready before the next eligibility pass.
|
||||
marker.klass = 'widebody';
|
||||
assert.equal(item().url, '/models/fleet/aircraft/a320.glb');
|
||||
assert.equal(
|
||||
item().scale,
|
||||
aircraftLayerModelSpec({ typeCode: 'A321' }).scale,
|
||||
);
|
||||
assert.ok(Math.abs(height() - bellyOf('A321')) < 0.01, 'at once');
|
||||
// Another model, ready before the next eligibility pass.
|
||||
marker.typeCode = 'B789';
|
||||
models.frame(markers, display, 100_003);
|
||||
assert.ok(Math.abs(height() - 105.03925) < 0.01, 'the old model draws');
|
||||
assert.ok(Math.abs(height() - bellyOf('A321')) < 0.01, 'the old model draws');
|
||||
draw.ready('test:models', 'a');
|
||||
models.frame(markers, display, 100_004);
|
||||
assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own');
|
||||
assert.ok(
|
||||
Math.abs(height() - bellyOf('B789')) < 0.01,
|
||||
'the widebody, on its own',
|
||||
);
|
||||
models.destroy();
|
||||
});
|
||||
@@ -8,7 +8,8 @@ import {
|
||||
sub,
|
||||
} from '../../geo/vector.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { civilAircraftModelSpec } from '../flights/modelSpec.js';
|
||||
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
|
||||
import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
import {
|
||||
FLEET_DR_INTERVAL_MS,
|
||||
MODEL_ALL_ADD_M,
|
||||
@@ -36,19 +37,28 @@ function inView(pose, point) {
|
||||
);
|
||||
}
|
||||
|
||||
/** The fleet model an aircraft draws with: its adsbdb type, else its emitter category. */
|
||||
const specOf = (marker) =>
|
||||
aircraftLayerModelSpec({
|
||||
typeCode: marker?.typeCode,
|
||||
category: marker?.category,
|
||||
});
|
||||
|
||||
/**
|
||||
* 3D models for Local ADS-B aircraft under the DISPLAY rail's 3D toggle,
|
||||
* drawn as one `models` set of the renderer's draw port.
|
||||
*
|
||||
* Mirrors the public Flights fleet: models only below the altitude ceiling,
|
||||
* the same proximity/all caps and add/keep radii, the same visible-first
|
||||
* eligibility (`selectModelEligible`), the same per-class asset and scale
|
||||
* (`civilAircraftModelSpec`) and the same tint path (a MIX colour blend, here
|
||||
* magenta, as Flights tints military amber). A billboard stays the visual
|
||||
* until its model is ready (the set's `ready`) AND placed; a grounded
|
||||
* aircraft's model rides the one-shot ground snap plus the class belly
|
||||
* offset, and without a resolved ground it stays a billboard. Models move
|
||||
* and turn in place each frame; only a class change loads another asset.
|
||||
* eligibility (`selectModelEligible`), the same fleet model per type, life
|
||||
* size (`aircraftLayerModelSpec`) and the same tint path (a MIX colour blend,
|
||||
* here magenta, as Flights tints military amber). A billboard stays the
|
||||
* visual until its model is ready (the set's `ready`) AND placed; a grounded
|
||||
* aircraft's model rides the one-shot ground snap plus the model's clearance,
|
||||
* and without a resolved ground it stays a billboard. Models move and turn in
|
||||
* place each frame; only a type change loads another model. Every fleet
|
||||
* model loads once, up front, when the layer starts (`loadFleetModelSet`),
|
||||
* and models are drawn from those bytes.
|
||||
* @param {object} options
|
||||
* @param {object} options.viewer The viewer the layer draws on; the ground
|
||||
* snap samples through it.
|
||||
@@ -74,6 +84,9 @@ export function createLocalAdsbModels({
|
||||
}) {
|
||||
if (typeof draw?.models !== 'function' || !camera) return null;
|
||||
const tint = cssColor(color) ?? color;
|
||||
void loadFleetModelSet({ resolveAsset }).catch(() => {
|
||||
/* aircraft stay billboards */
|
||||
});
|
||||
const set = draw.models({ id: setId, show: false });
|
||||
/** What ground samples see through, by set id (with every set not drawn as ground). */
|
||||
const groundSets = [setId, ...seeThrough];
|
||||
@@ -118,13 +131,16 @@ export function createLocalAdsbModels({
|
||||
}
|
||||
|
||||
/**
|
||||
* Admit a model for `id`. One admitted keeps its slot through a class
|
||||
* change: the frame pass asks for the new asset, loaded in place.
|
||||
* Admit a model for `id`. One admitted keeps its slot through a type
|
||||
* change: the frame pass asks for the new model, loaded in place. Until
|
||||
* the fleet model set has loaded the aircraft stays a billboard.
|
||||
*/
|
||||
function admit(id, marker, cap) {
|
||||
if (models.has(id) || models.size >= cap) return;
|
||||
const spec = specOf(marker);
|
||||
if (!spec.url) return;
|
||||
models.set(id, {
|
||||
bellyM: civilAircraftModelSpec(marker.klass).bellyM,
|
||||
bellyM: spec.bellyM,
|
||||
nextBellyM: null,
|
||||
sentUrl: null,
|
||||
drawnUrl: null,
|
||||
@@ -199,7 +215,7 @@ export function createLocalAdsbModels({
|
||||
* every admitted model and hand each marker's visual to its model only
|
||||
* once the model is ready and placed.
|
||||
* @param {Map<string, object>} markers Layer markers (position, courseDeg,
|
||||
* klass, onGround); `modelOwnsVisual` is written back.
|
||||
* typeCode, category, onGround); `modelOwnsVisual` is written back.
|
||||
* @param {object} preferences `{ models3d, models3dMode }`.
|
||||
* @param {number} nowMs
|
||||
*/
|
||||
@@ -222,8 +238,10 @@ export function createLocalAdsbModels({
|
||||
const record = models.get(id);
|
||||
marker.modelOwnsVisual = false;
|
||||
if (!record || !marker.position) continue;
|
||||
const spec = civilAircraftModelSpec(marker.klass);
|
||||
const spec = specOf(marker);
|
||||
if (!spec.url) continue;
|
||||
const url = resolveAsset(spec.url);
|
||||
const gltf = fleetModelSet()?.bytes?.get(spec.model);
|
||||
noteAsset(record, url, spec.bellyM);
|
||||
const position = placement(id, marker);
|
||||
const shown =
|
||||
@@ -233,6 +251,8 @@ export function createLocalAdsbModels({
|
||||
// Unplaced, it waits hidden where it last was (or at the marker).
|
||||
pos: position ?? marker.position,
|
||||
url,
|
||||
// Built from the bytes loaded up front: never fetched mid-session.
|
||||
...(gltf ? { gltf } : {}),
|
||||
orientation: {
|
||||
heading:
|
||||
((marker.courseDeg || 0) + MODEL_HEADING_OFFSET_DEG) *
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import { JET_MODEL_URL } from './policy.js';
|
||||
import { loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
|
||||
export function createLifecycle({
|
||||
flightState,
|
||||
@@ -42,10 +42,12 @@ export function createLifecycle({
|
||||
clearFocusTarget('militaryFlights');
|
||||
flightState._viewer = viewer;
|
||||
parts.icons._createIcons(viewer);
|
||||
// The models' draw sets; a hidden item keeps the tracked asset loaded so
|
||||
// the tracked plane's model draws as soon as it is wanted.
|
||||
parts.rendering._createModelSets(viewer, {
|
||||
preloadUrl: resolveAsset(JET_MODEL_URL),
|
||||
// The models' draw sets. Every fleet model loads once, up front, for
|
||||
// every layer that draws them (fleetModels.js), so no model is fetched
|
||||
// while the session runs; until the set has loaded aircraft stay icons.
|
||||
parts.rendering._createModelSets(viewer);
|
||||
loadFleetModelSet({ resolveAsset }).catch(() => {
|
||||
/* aircraft stay icons */
|
||||
});
|
||||
flightState._iconFocusActive = 0;
|
||||
flightState._detectionObjects = new Map();
|
||||
|
||||
@@ -273,7 +273,7 @@ export function createMotion({
|
||||
const viewportHeightPx = _viewportHeightPx();
|
||||
if (parts.rendering._modelOwnsVisual(icao24)) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
flightState.records.data.get(icao24),
|
||||
);
|
||||
const scale = trackedModelScaleForPixelCap({
|
||||
baseScale: spec.scale,
|
||||
@@ -424,7 +424,7 @@ export function createMotion({
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
return modelVisualAnchor(
|
||||
flightState._trackedModel.matrix,
|
||||
@@ -467,7 +467,7 @@ export function createMotion({
|
||||
)
|
||||
return 0;
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
return (
|
||||
spec.nativeRadiusM *
|
||||
@@ -484,7 +484,7 @@ export function createMotion({
|
||||
parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
) {
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(flightState._trackedIcao)?.klass,
|
||||
flightState.records.data.get(flightState._trackedIcao),
|
||||
);
|
||||
// Through the model's OWN render chain (modelVisualAnchor's hand-rolled
|
||||
// half-correction put this offset on the lateral axis — see
|
||||
|
||||
@@ -58,20 +58,18 @@ export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
|
||||
export const GROUND_SCALE = 0.8;
|
||||
|
||||
// --- 3D model rendering (mirrors flights.js) -----------------------------------------
|
||||
// When enabled, military aircraft render as 3D glTF jet models once the camera is below
|
||||
// When enabled, military aircraft render as 3D glTF models once the camera is below
|
||||
// MODEL_ALT_CEIL_M (zoomed in); higher up they stay flat billboards. Eligibility is
|
||||
// FRUSTUM-based (on-screen), and the slots go to either the nearest planes ('proximity')
|
||||
// or every in-view plane ('all'), each backed by a hard cap so a draw-call explosion
|
||||
// can't tank the frame (no instancing yet). Distinct asset + amber tint set this layer
|
||||
// apart from the commercial flights layer.
|
||||
|
||||
export const JET_MODEL_URL = '/models/jet.glb';
|
||||
// can't tank the frame (no instancing yet). Each aircraft draws the fleet model of its
|
||||
// type, as the flights layer does; the amber tint sets this layer apart.
|
||||
|
||||
export const MODEL_ALT_CEIL_M = 800000;
|
||||
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
|
||||
|
||||
export const MODEL_MIN_PX = 24;
|
||||
// floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js, whose models now share this layer's ~30 m world size)
|
||||
// floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js)
|
||||
|
||||
export const TRACKED_MODEL_MIN_PX = 40;
|
||||
// keep the glTF silhouette comparable to the selected 2D glyph at handoff
|
||||
@@ -79,17 +77,6 @@ export const TRACKED_MODEL_MIN_PX = 40;
|
||||
export const TRACKED_MODEL_MAX_PX = 200;
|
||||
// owner-selected close-range tracked-target feel
|
||||
|
||||
export const MODEL_NATIVE_RADIUS_M = 29.83;
|
||||
|
||||
// jet.glb is transform-applied at real-world scale — native bounding radius
|
||||
// 29.83 m at scale 1. ×1 → ~22–43 m aircraft across CLASS_SCALE_3D, matching
|
||||
// flights.js world sizes. At the old copied ×24, models rendered
|
||||
// 600–1000 m across (invisible at the ~6 km follow range where minimumPixelSize
|
||||
// dominates, but zoom under ~1 km put the camera INSIDE the plane). Locked by
|
||||
// modelScale.test.mjs.
|
||||
|
||||
export const MODEL_SCALE = 1;
|
||||
|
||||
// Per-mode caps + radii — mirror of flights.js. Modes differ by RADIUS (not just cap) so Proximity
|
||||
// and All aren't identical when few planes are in range; on-screen planes win the cap (see flights.js).
|
||||
|
||||
@@ -119,33 +106,12 @@ export const MODEL_ALL_KEEP_M = 450000;
|
||||
// all: KEEP modeled planes out to 450 km
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// every aircraft GLB is exported nose -X in the shared transform-applied convention
|
||||
// Preserve the layer's amber identity while reducing approved texture/livery
|
||||
// contribution to a weak diffuse hint, matching civilian launch presentation.
|
||||
// every fleet model is nose -X: opposite Cesium heading 0
|
||||
// Preserve the layer's amber identity while reducing the models' own colours
|
||||
// to a weak diffuse hint, matching civilian launch presentation.
|
||||
|
||||
export const MODEL_COLOR_BLEND_AMOUNT = 0.94;
|
||||
|
||||
// airplane.glb (the shared 747) constants for this layer's heavy classes. The
|
||||
// asset has its former 24× runtime calibration baked into transform-applied
|
||||
// meter-scale geometry; these values mirror flights.js and are regression-pinned.
|
||||
|
||||
export const PLANE_MODEL_URL = '/models/airplane.glb';
|
||||
|
||||
export const PLANE_MODEL_SCALE = 1;
|
||||
|
||||
export const PLANE_NATIVE_RADIUS_M = 34.41;
|
||||
|
||||
export const PLANE_BELLY_OFFSET_NATIVE = 6.719;
|
||||
|
||||
// Grounded-model belly offset: jet.glb's centred origin sits 5.631 native units (= meters — this
|
||||
// asset is real-world scale) ABOVE its lowest vertex (glTF Y-up scene AABB with node
|
||||
// transforms applied — same reader as modelScale.test.mjs, measured 2026-07-03).
|
||||
// × MODEL_SCALE(1) × class multiplier ≈ 4.4–8.6 m of lift, so a ground-snapped model
|
||||
// rests its lowest geometry (gear/belly) ON the sampled tile skin instead of sinking to
|
||||
// the fuselage-centerline origin. Locked against the GLB by modelScale.test.mjs.
|
||||
|
||||
export const MODEL_BELLY_OFFSET_NATIVE = 5.631;
|
||||
|
||||
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
|
||||
|
||||
export const AMBER_TRANSPARENT = rgba('#FFB800', 0);
|
||||
|
||||
@@ -474,9 +474,7 @@ export function createQueries({
|
||||
// contacts read the translation the fleet tick already wrote into their
|
||||
// modelMatrix; icon-owned contacts keep the drawn icon position, where icon and
|
||||
// bracket are co-located anyway.
|
||||
const spec = modelOwnsVisual
|
||||
? parts.rendering._modelSpec(info?.klass)
|
||||
: null;
|
||||
const spec = modelOwnsVisual ? parts.rendering._modelSpec(info) : null;
|
||||
const pos = isTracked
|
||||
? parts.motion._trackedVisualCached() ||
|
||||
icons.position(icao24, t, object._iconPos)
|
||||
|
||||
@@ -181,6 +181,8 @@ export class MilitaryFlightRecords {
|
||||
newestFixMs: this._noteFix(icao24, prevMeta, fixEpochMs),
|
||||
callsign: stickyText(callsign, prevMeta?.callsign),
|
||||
type: stickyType,
|
||||
// The emitter category, kept for the fleet model a type-less row draws.
|
||||
category: aircraft?.category ?? prevMeta?.category ?? null,
|
||||
// Type outranks category automatically inside classifyAircraft.
|
||||
klass: classifyAircraft({
|
||||
typeCode: stickyType,
|
||||
|
||||
@@ -1,22 +1,10 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
CLASS_MODEL_REAL,
|
||||
CLASS_SCALE_3D,
|
||||
CLASS_SCALE_2D,
|
||||
} from '../../data/aircraftClass.js';
|
||||
import {
|
||||
visualCenterForModel,
|
||||
trailAnchorForModel,
|
||||
} from '../../data/modelVisualAnchor.js';
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
} from '../flights/modelSpec.js';
|
||||
import { isEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
PLANE_MODEL_SCALE,
|
||||
PLANE_MODEL_URL,
|
||||
PLANE_NATIVE_RADIUS_M,
|
||||
PLANE_BELLY_OFFSET_NATIVE,
|
||||
MODEL_SCALE,
|
||||
JET_MODEL_URL,
|
||||
MODEL_NATIVE_RADIUS_M,
|
||||
MODEL_BELLY_OFFSET_NATIVE,
|
||||
MODEL_HEADING_OFFSET_DEG,
|
||||
BILLBOARD_SCALE,
|
||||
GROUND_SCALE,
|
||||
@@ -37,51 +25,20 @@ export function createRendering({
|
||||
}) {
|
||||
const { tr3bIconKind } = services.aircraftPresentation;
|
||||
|
||||
function _modelSpec(klass) {
|
||||
let spec = flightState._specCache.get(klass);
|
||||
/** The fleet model an aircraft draws with, by its type and emitter category
|
||||
* (shared with the flights layer), in this layer's own tint. */
|
||||
function _modelSpec(meta) {
|
||||
const key = aircraftModelSpecCacheKey(meta);
|
||||
let spec = flightState._specCache.get(key);
|
||||
if (spec) return spec;
|
||||
const real = CLASS_MODEL_REAL[klass];
|
||||
if (real) {
|
||||
spec = {
|
||||
url: real.url,
|
||||
scale: 1,
|
||||
nativeRadiusM: real.radiusM,
|
||||
bellyM: real.bellyM,
|
||||
headingOffsetDeg: 180,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: visualCenterForModel(real.url),
|
||||
trailAnchorNative: trailAnchorForModel(real.url),
|
||||
};
|
||||
} else if (
|
||||
klass === 'airliner' ||
|
||||
klass === 'quadjet' ||
|
||||
klass === 'glider'
|
||||
) {
|
||||
const scale = PLANE_MODEL_SCALE * (CLASS_SCALE_3D[klass] || 1);
|
||||
spec = {
|
||||
url: PLANE_MODEL_URL,
|
||||
scale,
|
||||
nativeRadiusM: PLANE_NATIVE_RADIUS_M,
|
||||
bellyM: PLANE_BELLY_OFFSET_NATIVE * scale,
|
||||
headingOffsetDeg: 180,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: visualCenterForModel(PLANE_MODEL_URL),
|
||||
trailAnchorNative: trailAnchorForModel(PLANE_MODEL_URL),
|
||||
};
|
||||
} else {
|
||||
const scale = MODEL_SCALE * (CLASS_SCALE_3D[klass] || 1);
|
||||
spec = {
|
||||
url: JET_MODEL_URL,
|
||||
scale,
|
||||
nativeRadiusM: MODEL_NATIVE_RADIUS_M,
|
||||
bellyM: MODEL_BELLY_OFFSET_NATIVE * scale,
|
||||
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
visualCenterNative: visualCenterForModel(JET_MODEL_URL),
|
||||
trailAnchorNative: trailAnchorForModel(JET_MODEL_URL),
|
||||
};
|
||||
}
|
||||
flightState._specCache.set(klass, spec);
|
||||
const base = aircraftLayerModelSpec(meta);
|
||||
spec = Object.freeze({
|
||||
...base,
|
||||
blendAmount: MODEL_COLOR_BLEND_AMOUNT,
|
||||
headingOffsetDeg: MODEL_HEADING_OFFSET_DEG,
|
||||
});
|
||||
// Not cached before the model set loads: the answer changes once it has.
|
||||
if (spec.model) flightState._specCache.set(key, spec);
|
||||
return spec;
|
||||
}
|
||||
|
||||
|
||||
@@ -145,10 +145,15 @@ export function createMilitarySnapshotRenderer({
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
// Per-class GLBs: a class change can mean a different asset OR scale —
|
||||
// resync the live model, any in-flight load, and the tracked
|
||||
// standalone (mirror of flights.js).
|
||||
if (prevMeta?.klass !== meta.klass) rendering._syncModelToClass(icao24);
|
||||
// Per-type fleet models: a type or category change can mean a
|
||||
// different model OR scale — resync the live model, any in-flight
|
||||
// load, and the tracked standalone (mirror of flights.js).
|
||||
if (
|
||||
prevMeta?.klass !== meta.klass ||
|
||||
prevMeta?.type !== meta.type ||
|
||||
prevMeta?.category !== meta.category
|
||||
)
|
||||
rendering._syncModelToClass(icao24);
|
||||
} else {
|
||||
// Hidden while tracked: the tracked entity replaces it.
|
||||
icons._addIcon(icao24);
|
||||
|
||||
@@ -17,15 +17,13 @@ export function createFlightState({ source, services }) {
|
||||
* layer); see followsClock and displayDelayMs in policy.js. */
|
||||
flightState.timeline = null;
|
||||
|
||||
/** Per-class model spec for THIS layer (2026-08-16, owner playtest ask:
|
||||
* military contacts should read as their WEIGHT CLASS, always in this layer's
|
||||
* amber). Real Hangar GLBs serve the classes they cover (meters, nose −X →
|
||||
* 180° offset); airliner/quadjet/glider get the shared 747 silhouette
|
||||
* (airplane.glb — C-5M/RC-135-style heavies stop rendering as bizjets);
|
||||
* fastjet and unknown keep jet.glb with the same 180° offset. The MIX tint stays
|
||||
* dominant everywhere — military is amber, tracked is TRACKED_ICON_COLOR,
|
||||
* and the tint must dominate any livery (owner: "stays yellow"). Specs are
|
||||
* static per class — memoized (the fleet pass asks at 12 Hz per model). */
|
||||
/** Model spec per aircraft type and emitter category (aircraftLayerModelSpec in
|
||||
* flights/modelSpec.js): the procedural fleet model that draws the type, life size,
|
||||
* with its measured clearance, bounding radius and trail anchor. nativeRadiusM is PER
|
||||
* SCALE UNIT — pixel-cap math multiplies it by `scale`. The code-side MIX tint dominates
|
||||
* every model so silhouettes stay light (and in this layer's own colour). Memoized: the
|
||||
* detection weld asks for one per MODELED contact per frame on top of the 12 Hz fleet
|
||||
* pass. */
|
||||
|
||||
flightState._specCache = new Map();
|
||||
|
||||
|
||||
@@ -37,10 +37,10 @@ export function createTesting({
|
||||
*/
|
||||
|
||||
/** Turn a test's model fields into the contact's model record, in place. */
|
||||
function _modelRecordForTest(fields, klass) {
|
||||
const spec = parts.rendering._modelSpec(klass);
|
||||
function _modelRecordForTest(fields, meta) {
|
||||
const spec = parts.rendering._modelSpec(meta);
|
||||
const base = createModelRecord({
|
||||
specKey: parts.rendering._specKeyFor(klass),
|
||||
specKey: parts.rendering._specKeyFor(meta),
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
});
|
||||
@@ -80,7 +80,7 @@ export function createTesting({
|
||||
_seedIconForTest(icao24, icon, tracked);
|
||||
flightState._models.clear();
|
||||
for (const [key, model] of models)
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta?.klass));
|
||||
flightState._models.set(key, _modelRecordForTest(model, meta));
|
||||
flightState._detectionObjects = new Map();
|
||||
flightState.records.data = new Map([[icao24, meta]]);
|
||||
flightState._positionHistory = new Map([[icao24, history]]);
|
||||
|
||||
@@ -56,6 +56,7 @@ import {
|
||||
countryGroups,
|
||||
countryOnly,
|
||||
disputedLabel,
|
||||
eventPicture,
|
||||
feedCardView,
|
||||
feedQueryFor,
|
||||
hotspotLabel,
|
||||
@@ -71,6 +72,7 @@ import {
|
||||
normalizeFilters,
|
||||
passesFilters,
|
||||
reportMarkerPosition,
|
||||
reportSeverity,
|
||||
reportsInView,
|
||||
severityStyle,
|
||||
shortTitle,
|
||||
@@ -186,6 +188,14 @@ const emptyInView = () => ({
|
||||
* chosen: outlines (disputed areas dotted) and the geocoded reports as
|
||||
* markers, the big events as picture cards. The News panel renders the feed
|
||||
* this layer publishes through getRowControls().feed.
|
||||
*
|
||||
* `pictureCards(cards, { selectedId })`, when given, draws the picture cards
|
||||
* instead of the layer: it is called on every render with one card per
|
||||
* pictured event on the map, at every height (zoomed out too, where the
|
||||
* hotspots stand as beacons), in rank order (`{ id, title, lat, lon,
|
||||
* publishedAt, severity, color, image, video, credit }`), and the selected
|
||||
* report's id or null, whose own card the layer still draws at its marker; it
|
||||
* is called with no cards when the layer is turned off.
|
||||
*/
|
||||
export function createNewsLayer({
|
||||
source,
|
||||
@@ -197,6 +207,7 @@ export function createNewsLayer({
|
||||
openUrl = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
|
||||
getViewCentre = viewCentre,
|
||||
registerCredit = registerDynamicCredit,
|
||||
pictureCards: drawPictureCards = null,
|
||||
} = {}) {
|
||||
if (
|
||||
typeof source?.getHotspots !== 'function' ||
|
||||
@@ -204,6 +215,8 @@ export function createNewsLayer({
|
||||
)
|
||||
throw new TypeError('News requires a news source');
|
||||
if (!overlayHost) throw new TypeError('News requires an overlay host');
|
||||
if (drawPictureCards !== null && typeof drawPictureCards !== 'function')
|
||||
throw new TypeError('News picture cards must be a function');
|
||||
|
||||
let viewer = null,
|
||||
// The layer's draw sets (`sets.icons` and the rest), made on init.
|
||||
@@ -742,6 +755,53 @@ export function createNewsLayer({
|
||||
}
|
||||
}
|
||||
|
||||
// What a host's picture cards are chosen from when the hotspots stand as
|
||||
// beacons: every report the close-up view would mark, and the selection.
|
||||
function cardable() {
|
||||
const current = selected();
|
||||
const all = localMode() ? localReports(NEWS_MAP_LIMIT) : mapReports;
|
||||
return current && !all.some((r) => r.id === current.id)
|
||||
? [...all, current]
|
||||
: all;
|
||||
}
|
||||
|
||||
// With a `pictureCards` function the host draws the picture cards: one per
|
||||
// event on the map with a picture (its most severe, then newest report),
|
||||
// most severe then newest first, at its marker. The host chooses which
|
||||
// stand; a click on one calls setParams({ reportId, focus: true }).
|
||||
function hostCards(drawn) {
|
||||
const events = new Set();
|
||||
return drawn
|
||||
.filter((r) => r.pins.length && onMap(r) && eventPicture(r))
|
||||
.sort(
|
||||
(a, b) =>
|
||||
reportSeverity(b) - reportSeverity(a) ||
|
||||
(b.event?.lastAt || b.publishedAt || '').localeCompare(
|
||||
a.event?.lastAt || a.publishedAt || '',
|
||||
),
|
||||
)
|
||||
.filter((report) => {
|
||||
const event = report.event?.id || report.id;
|
||||
if (events.has(event)) return false;
|
||||
events.add(event);
|
||||
return true;
|
||||
})
|
||||
.map((report) => {
|
||||
const picture = eventPicture(report);
|
||||
return {
|
||||
id: report.id,
|
||||
title: report.titleEn || report.title,
|
||||
...reportMarkerPosition(report, 0),
|
||||
publishedAt: report.event?.lastAt || report.publishedAt || null,
|
||||
severity: reportSeverity(report),
|
||||
color: severityStyle(report).color,
|
||||
image: picture.url,
|
||||
video: picture.video || null,
|
||||
credit: picture.credit,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
// The selected report's card: what, where, how attested, the link to the
|
||||
// original article ("Source: host ↗"), which a click on it opens, and the
|
||||
// service it came through.
|
||||
@@ -822,7 +882,13 @@ export function createNewsLayer({
|
||||
for (const kind of ['halos', 'points', 'icons', 'boxes'])
|
||||
sets[kind].set(list[kind]);
|
||||
updatePulse();
|
||||
pictureCards(drawn, current, labels);
|
||||
if (drawPictureCards)
|
||||
// At every height: zoomed out, a hotspot's reports give way to its
|
||||
// beacon, but their pictures still stand (the host keeps them apart).
|
||||
drawPictureCards(enabled ? hostCards(detail ? drawn : cardable()) : [], {
|
||||
selectedId: enabled ? selectedId : null,
|
||||
});
|
||||
else pictureCards(drawn, current, labels);
|
||||
selectedCard(current, labels);
|
||||
if (enabled)
|
||||
overlayHost.setEntries(NEWS_OVERLAY_SOURCE_ID, labels, { moving: false });
|
||||
@@ -1524,6 +1590,7 @@ export function createNewsLayer({
|
||||
}
|
||||
overlayHost.clearSource(NEWS_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(NEWS_OVERLAY_SOURCE_ID, false);
|
||||
drawPictureCards?.([], { selectedId: null });
|
||||
requestRender();
|
||||
notify();
|
||||
},
|
||||
|
||||
@@ -49,6 +49,7 @@ function fixture(
|
||||
credits = [],
|
||||
now = () => NOW,
|
||||
quality,
|
||||
pictureCards,
|
||||
} = {},
|
||||
) {
|
||||
const calls = { feed: [], hotspots: 0, outline: 0 };
|
||||
@@ -147,6 +148,7 @@ function fixture(
|
||||
credits.push(credit.key);
|
||||
return true;
|
||||
},
|
||||
...(pictureCards ? { pictureCards } : {}),
|
||||
});
|
||||
// The context store announces selections on `window`, which Node lacks.
|
||||
const originalWindow = globalThis.window;
|
||||
@@ -267,6 +269,113 @@ test('the severity floor changes what is shown, not what is read', async (t) =>
|
||||
);
|
||||
});
|
||||
|
||||
test('a host that draws the picture cards is handed one card per pictured event on the map, most severe first', async (t) => {
|
||||
const picture = (url, extra = {}) => ({
|
||||
size: 1,
|
||||
lastAt: '2026-10-28T09:00:00.000Z',
|
||||
sides: [],
|
||||
image: { url, publisher: 'Example', ...extra },
|
||||
});
|
||||
const reports = [
|
||||
report('single', {
|
||||
severity: 1,
|
||||
event: picture('https://example.com/single.jpg', {
|
||||
video: 'https://example.com/single.mp4',
|
||||
}),
|
||||
}),
|
||||
report('major', {
|
||||
severity: 3,
|
||||
event: {
|
||||
...picture('https://example.com/major.jpg'),
|
||||
id: 'event-major',
|
||||
size: 3,
|
||||
},
|
||||
}),
|
||||
// Another report of the same event: its picture stands once.
|
||||
report('repeat', {
|
||||
severity: 2,
|
||||
event: {
|
||||
...picture('https://example.com/major.jpg'),
|
||||
id: 'event-major',
|
||||
size: 3,
|
||||
},
|
||||
}),
|
||||
report('bare', { severity: 2 }),
|
||||
];
|
||||
const handed = [];
|
||||
const { layer, entries } = fixture(t, {
|
||||
height: 500_000,
|
||||
source: { getFeed: async () => ({ reports, nextBefore: null }) },
|
||||
pictureCards: (cards, state) => handed.push({ cards, ...state }),
|
||||
});
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
layer.setParams({ filters: { minSeverity: 0 } });
|
||||
const { cards, selectedId } = handed.at(-1);
|
||||
assert.equal(selectedId, null);
|
||||
// A single source is enough; a report without a picture has none.
|
||||
assert.deepEqual(
|
||||
cards.map((card) => card.id),
|
||||
['major', 'single'],
|
||||
);
|
||||
assert.equal(cards[1].image, 'https://example.com/single.jpg');
|
||||
assert.equal(cards[1].video, 'https://example.com/single.mp4');
|
||||
assert.equal(cards[0].video, null);
|
||||
assert.equal(cards[0].credit, 'Example');
|
||||
assert.ok(
|
||||
Math.abs(cards[0].lat - 50) < 0.5 && Math.abs(cards[0].lon - 36) < 0.5,
|
||||
);
|
||||
// The layer paints none of its own.
|
||||
assert.ok(
|
||||
entries.flat().every((entry) => !entry.id.startsWith('event-card:')),
|
||||
);
|
||||
// The selected report is named, pictured or not.
|
||||
layer.setParams({ reportId: 'bare' });
|
||||
assert.equal(handed.at(-1).selectedId, 'bare');
|
||||
layer.disable();
|
||||
assert.deepEqual(handed.at(-1), { cards: [], selectedId: null });
|
||||
});
|
||||
|
||||
test("a host's picture cards stay at every height, beacons or markers", async (t) => {
|
||||
const reports = [
|
||||
report('major', {
|
||||
severity: 3,
|
||||
event: {
|
||||
size: 1,
|
||||
lastAt: '2026-10-28T09:00:00.000Z',
|
||||
sides: [],
|
||||
image: { url: 'https://example.com/major.jpg', publisher: 'Example' },
|
||||
},
|
||||
}),
|
||||
];
|
||||
const handed = [];
|
||||
const { layer } = fixture(t, {
|
||||
// The whole globe: the hotspot stands as one beacon, its reports unmarked.
|
||||
height: 20_000_000,
|
||||
source: { getFeed: async () => ({ reports, nextBefore: null }) },
|
||||
pictureCards: (cards) => handed.push(cards),
|
||||
});
|
||||
layer.enable();
|
||||
await layer.update();
|
||||
layer.setParams({ filters: { minSeverity: 0 } });
|
||||
assert.deepEqual(
|
||||
handed.at(-1).map((card) => card.id),
|
||||
['major'],
|
||||
);
|
||||
});
|
||||
|
||||
test('picture cards must be drawn by a function', () => {
|
||||
assert.throws(
|
||||
() =>
|
||||
createNewsLayer({
|
||||
source: { getHotspots() {}, getFeed() {} },
|
||||
overlayHost: {},
|
||||
pictureCards: 'yes',
|
||||
}),
|
||||
TypeError,
|
||||
);
|
||||
});
|
||||
|
||||
test('Local reads every report once, lists those near the view and takes the map over', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
let centre = { lat: 49, lon: 36 };
|
||||
|
||||
Vendored
+202
@@ -0,0 +1,202 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { RAIL_CATEGORIES } from '../../data/railFeeds.js';
|
||||
import { aggregateTransitFeedHealth } from '../transit/policy.js';
|
||||
import {
|
||||
ACTIVATION_ALTITUDE_M,
|
||||
FEED_STALE_AFTER_MS,
|
||||
RAIL_CATEGORY_COLORS,
|
||||
RAIL_CATEGORY_LABELS,
|
||||
normalizeRailCategories,
|
||||
} from './policy.js';
|
||||
|
||||
/**
|
||||
* Category toggles, the layer row and the stats the panel reads.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createControls({ state, parts, timetable }) {
|
||||
function notify() {
|
||||
state._controlsListener?.();
|
||||
}
|
||||
|
||||
/** Regions with at least one pollable feed, for the empty-coverage note. */
|
||||
function regionCount() {
|
||||
return new Set(parts.viewport.pollableFeeds().map((feed) => feed.region))
|
||||
.size;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trains per category for the legend, shown or not; a train two feeds
|
||||
* carry is one train (the copy dedupe.js hides is not counted).
|
||||
*/
|
||||
function categoryCounts() {
|
||||
const counts = new Map();
|
||||
for (const entry of state._trains.values())
|
||||
if (entry.duplicate !== true)
|
||||
counts.set(entry.category, (counts.get(entry.category) || 0) + 1);
|
||||
return counts;
|
||||
}
|
||||
|
||||
/**
|
||||
* Trains drawn per feed: those still held (a train missing from one poll
|
||||
* stays until MISSED_POLLS_TO_DROP) in a shown category, and not hidden as
|
||||
* another feed's copy. The feed status's own count is what the last poll
|
||||
* listed, which the loading and health rules need but the map does not
|
||||
* show, so the coverage line counts drawn trains, as the layer total does.
|
||||
*/
|
||||
function drawnCounts() {
|
||||
const counts = new Map();
|
||||
for (const entry of state._trains.values())
|
||||
if (parts.rendering.categoryShown(entry))
|
||||
counts.set(entry.feedId, (counts.get(entry.feedId) || 0) + 1);
|
||||
return counts;
|
||||
}
|
||||
|
||||
/** The coverage line: each active feed and its train count, aged when quiet. */
|
||||
function coverageLine(active, now) {
|
||||
const drawn = drawnCounts();
|
||||
return active
|
||||
.map((feed) => {
|
||||
const status = parts.ingestion.feedStatus(feed.id);
|
||||
const quiet =
|
||||
status.stale === true ||
|
||||
(Number.isFinite(status.upstreamAt) &&
|
||||
now - status.upstreamAt > FEED_STALE_AFTER_MS);
|
||||
const aged =
|
||||
quiet && Number.isFinite(status.upstreamAt)
|
||||
? ` (${Math.round((now - status.upstreamAt) / 1000)}s old)`
|
||||
: '';
|
||||
return `${feed.name} ${drawn.get(feed.id) || 0}${aged}`;
|
||||
})
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
const methods = {
|
||||
/** Wired by the application so polls can repaint the panel row. */
|
||||
attachDataManager(manager) {
|
||||
state._dataManager = manager;
|
||||
},
|
||||
setRowControlsListener(listener) {
|
||||
state._controlsListener =
|
||||
typeof listener === 'function' ? listener : null;
|
||||
},
|
||||
/** The category toggles, for share links and restoration. */
|
||||
getParams() {
|
||||
return { ...state._categories };
|
||||
},
|
||||
/** Show or hide categories; unknown keys and non-booleans change nothing. */
|
||||
setParams(params = {}) {
|
||||
const next = normalizeRailCategories(params, state._categories);
|
||||
if (RAIL_CATEGORIES.every((key) => next[key] === state._categories[key]))
|
||||
return true;
|
||||
state._categories = next;
|
||||
const selected = state._trains.get(state._selectedKey);
|
||||
if (selected && next[selected.category] === false)
|
||||
parts.selection.clearSelection();
|
||||
parts.rendering.applyCategoryVisibility();
|
||||
state._revision += 1;
|
||||
notify();
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
return true;
|
||||
},
|
||||
/** One chip per category, with the colour and live count as the legend. */
|
||||
getRowControls() {
|
||||
const counts = categoryCounts();
|
||||
const chips = RAIL_CATEGORIES.map((category) => {
|
||||
const on = state._categories[category] !== false;
|
||||
const label = t(RAIL_CATEGORY_LABELS[category]);
|
||||
return {
|
||||
id: `rail-${category}`,
|
||||
label: label.toUpperCase(),
|
||||
title: on
|
||||
? t('Hide {category}', { category: label })
|
||||
: t('Show {category}', { category: label }),
|
||||
active: on,
|
||||
busy: false,
|
||||
disabled: false,
|
||||
state: on ? 'active' : 'idle',
|
||||
params: { [category]: !on },
|
||||
};
|
||||
});
|
||||
const legend = RAIL_CATEGORIES.filter((category) =>
|
||||
counts.has(category),
|
||||
).map((category) => ({
|
||||
label: t(RAIL_CATEGORY_LABELS[category]),
|
||||
color: RAIL_CATEGORY_COLORS[category],
|
||||
count: counts.get(category),
|
||||
}));
|
||||
return { chips, legend };
|
||||
},
|
||||
/** Route-line, stop, schedule and camera-follow state, for QA probes. */
|
||||
getRouteDisplayStats() {
|
||||
return {
|
||||
...parts.routes.stats(),
|
||||
timetable: timetable.stats(),
|
||||
follow: parts.follow.stats(),
|
||||
heldFeed: state._heldFeedId,
|
||||
};
|
||||
},
|
||||
getStats() {
|
||||
const active = [...state._activeFeeds.values()];
|
||||
const statuses = active.map((feed) =>
|
||||
parts.ingestion.feedStatus(feed.id),
|
||||
);
|
||||
const now = Date.now();
|
||||
const health = aggregateTransitFeedHealth(statuses, now);
|
||||
let count = 0;
|
||||
for (const entry of state._trains.values())
|
||||
if (parts.rendering.categoryShown(entry)) count += 1;
|
||||
// New trains the layer's cap left out of the last polls
|
||||
// (MAX_TRAINS_TOTAL): the map shows part of what the feeds list.
|
||||
const capped = statuses.reduce(
|
||||
(sum, status) => sum + (status.capped || 0),
|
||||
0,
|
||||
);
|
||||
if (state._enabled && active.length === 0) {
|
||||
// English: the row's prompt and the analyst's empty note, both shown
|
||||
// through translateStatusMessage (ui/statusText.js), as Transit's.
|
||||
const note = state._altitudeGateOpen
|
||||
? `No feed here yet · ${regionCount()} regions available`
|
||||
: `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`;
|
||||
return {
|
||||
count: 0,
|
||||
lastUpdate: state._lastUpdate,
|
||||
error: null,
|
||||
source: 'GTFS-RT',
|
||||
status: 'zoom-in',
|
||||
statusMessage: note,
|
||||
coverage: note,
|
||||
};
|
||||
}
|
||||
return {
|
||||
count,
|
||||
lastUpdate: state._lastUpdate,
|
||||
error: count === 0 ? health.error : null,
|
||||
...(count === 0 && Number.isFinite(health.retryInSec)
|
||||
? { retryInSec: health.retryInSec }
|
||||
: {}),
|
||||
degraded: count > 0 && health.degraded,
|
||||
loading: health.loading && count === 0,
|
||||
loadingLabel:
|
||||
// i18n-ignore: English data, translated on display (ui/statusText.js)
|
||||
health.loading && count === 0
|
||||
? `Loading ${active.map((feed) => feed.name).join(', ')}`
|
||||
: undefined,
|
||||
stale: health.stale,
|
||||
// The panel reads this as "PARTIAL · N of M records accepted".
|
||||
...(capped > 0 && count > 0
|
||||
? {
|
||||
partial: true,
|
||||
acceptedRowCount: count,
|
||||
rawRowCount: count + capped,
|
||||
}
|
||||
: {}),
|
||||
source: 'GTFS-RT',
|
||||
coverage: coverageLine(active, now),
|
||||
feeds: active.map((feed) => feed.id),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return { methods, notify };
|
||||
}
|
||||
@@ -0,0 +1,394 @@
|
||||
import { greatCircleKm } from '../../geoDistance.js';
|
||||
|
||||
/**
|
||||
* @module rail/dedupe
|
||||
* @description One physical train drawn once when several loaded feeds carry
|
||||
* it (an operator's own feed and a national feed that lists its trains too,
|
||||
* a cross-border train reported on both sides).
|
||||
*
|
||||
* Matching, between copies from different feeds:
|
||||
* - both carry a train number: the same normalised number (its last digit
|
||||
* group without leading zeros: `RJX 160`, `160`), up to NUMBER_RADIUS_KM
|
||||
* apart. Numbers that differ are different trains. A name's number is a
|
||||
* train's when it has three digits or more, or follows a long-distance
|
||||
* product (`EC 7`, `NJ 40`); a trip id that is an operator prefix and a
|
||||
* number (`AM:530`) and a bare-number headsign (where a feed with no
|
||||
* trip names writes the train number) are read too.
|
||||
* - a shorter number after anything else names a line (`S1`, `RB 1`,
|
||||
* `U6`), which many trains run: copies on different lines are different
|
||||
* trains, and copies on one line within MATCH_RADIUS_KM are one train
|
||||
* only in the same category, the nearest pairs first.
|
||||
* A train has at most one copy per feed; the strongest matches join first.
|
||||
*
|
||||
* Choosing the copy drawn:
|
||||
* 1. position source: live GPS, then station reports;
|
||||
* 2. the line: a copy bound to its operator's shape (a built pack), then
|
||||
* one without.
|
||||
* The copy drawn stays drawn until another scores strictly higher, so equal
|
||||
* copies never trade places. A losing copy keeps its playback and is only
|
||||
* hidden; when a feed leaves the viewport its copies' partners come back.
|
||||
* The comparison runs once per poll, never per frame.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Copies farther apart than this are different trains (km): two copies of
|
||||
* one train at one moment differ only by where each feed reports it.
|
||||
*/
|
||||
export const MATCH_RADIUS_KM = 15;
|
||||
/**
|
||||
* Copies with the same number match up to this far apart (km): two feeds
|
||||
* report one train at different moments, and one polled every few minutes
|
||||
* can be tens of kilometres behind at speed.
|
||||
*/
|
||||
export const NUMBER_RADIUS_KM = 100;
|
||||
/**
|
||||
* Grid cell for finding nearby copies (degrees). A row (27.8 km) spans
|
||||
* MATCH_RADIUS_KM; a column narrows away from the equator (13.9 km at
|
||||
* 60°N), so as many columns either side are searched as reach it
|
||||
* (columnSpan).
|
||||
*/
|
||||
const CELL_DEG = 0.25;
|
||||
|
||||
const POSITION_RANK = Object.freeze({
|
||||
gps: 2,
|
||||
event: 1,
|
||||
});
|
||||
/**
|
||||
* Products whose trains carry short numbers of their own (`EC 7`, `NJ 40`).
|
||||
* Not `IC`: in Switzerland `IC 1` and `IC 5` are lines run by many trains a
|
||||
* day, and IC train numbers elsewhere have three or more digits anyway.
|
||||
*/
|
||||
const LONG_DISTANCE_PRODUCTS = new Set([
|
||||
'EC',
|
||||
'ECE',
|
||||
'EN',
|
||||
'ICE',
|
||||
'NJ',
|
||||
'RJ',
|
||||
'RJX',
|
||||
'TGV',
|
||||
]);
|
||||
|
||||
/**
|
||||
* A train number comparable across feeds: the last group of digits, without
|
||||
* leading zeros (`RJX 160` → `160`, `09725` → `9725`), or null.
|
||||
* @param {string|null|undefined} label
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function trainNumber(label) {
|
||||
const digits = /(\d{1,6})\D*$/.exec(String(label ?? ''))?.[1];
|
||||
const number = digits?.replace(/^0+/, '') ?? '';
|
||||
return number || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* What a name's number says: a train's own number (three digits or more,
|
||||
* or after a long-distance product: `RJX 160`, `EC 7`), or a line's
|
||||
* (`S1`, `RB 1`, `U6`: each run by many trains), with its product.
|
||||
* @param {string|null|undefined} label
|
||||
* @returns {{number: string|null, line: {product: string,
|
||||
* number: string}|null}}
|
||||
*/
|
||||
export function labelNumbers(label) {
|
||||
const match = /([A-Za-z]*)\s*(\d{1,6})\D*$/.exec(String(label ?? ''));
|
||||
const number = match?.[2].replace(/^0+/, '') ?? '';
|
||||
if (!number) return { number: null, line: null };
|
||||
const product = match[1].toUpperCase();
|
||||
return number.length >= 3 || LONG_DISTANCE_PRODUCTS.has(product)
|
||||
? { number, line: null }
|
||||
: { number: null, line: { product, number } };
|
||||
}
|
||||
|
||||
/**
|
||||
* A record's train number and line: the number from its name, unless that
|
||||
* is only the vehicle's own id (a feed that labels each train with its car
|
||||
* number) or names a line; else from a trip id that is an operator
|
||||
* prefix and a number (`AM:530`); else from a headsign that is a bare
|
||||
* number (where a feed with no trip names writes the train number). The line is the name's,
|
||||
* when it names one.
|
||||
* @param {{id?: string|null, label?: string|null, tripId?: string|null,
|
||||
* headsign?: string|null}} record
|
||||
* @returns {{number: string|null, line: {product: string,
|
||||
* number: string}|null}}
|
||||
*/
|
||||
export function recordNumbers(record) {
|
||||
const label = String(record?.label ?? '').trim();
|
||||
const named =
|
||||
label && label !== String(record?.id ?? '')
|
||||
? labelNumbers(label)
|
||||
: { number: null, line: null };
|
||||
if (named.number) return named;
|
||||
const trip = /^[A-Za-z]{1,6}:(\d{1,6})$/.exec(
|
||||
String(record?.tripId ?? '').trim(),
|
||||
);
|
||||
const headsign = String(record?.headsign ?? '').trim();
|
||||
const number = trip
|
||||
? trainNumber(trip[1])
|
||||
: /^\d{3,6}$/.test(headsign)
|
||||
? trainNumber(headsign)
|
||||
: null;
|
||||
return number ? { number, line: null } : named;
|
||||
}
|
||||
|
||||
/**
|
||||
* A record's train number (recordNumbers), or null.
|
||||
* @param {object} record
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function recordTrainNumber(record) {
|
||||
return recordNumbers(record).number;
|
||||
}
|
||||
|
||||
/** Whether two lines can be one: one number, and one product where both name it. */
|
||||
function sameLine(a, b) {
|
||||
return (
|
||||
a.number === b.number &&
|
||||
(!a.product || !b.product || a.product === b.product)
|
||||
);
|
||||
}
|
||||
|
||||
/** A number match outranks any line match. */
|
||||
const NUMBER_MATCH = 2;
|
||||
|
||||
/**
|
||||
* How strongly two copies are the same physical train: 0 when they are not,
|
||||
* NUMBER_MATCH for the same number, else, for one line in one category,
|
||||
* between 0.5 and 1, higher the nearer they are. See the module notes.
|
||||
* @param {object} a A copy (`copyOf` in createDuplicateFilter).
|
||||
* @param {object} b
|
||||
* @returns {number}
|
||||
*/
|
||||
export function matchStrength(a, b) {
|
||||
if (a.feedId === b.feedId) return 0;
|
||||
const km = greatCircleKm(a, b);
|
||||
if (a.number && b.number)
|
||||
return km <= NUMBER_RADIUS_KM && a.number === b.number ? NUMBER_MATCH : 0;
|
||||
if (km > MATCH_RADIUS_KM) return 0;
|
||||
if (a.line && b.line && !sameLine(a.line, b.line)) return 0;
|
||||
// Many trains run one line: in one category, the nearest copies pair
|
||||
// first.
|
||||
return a.line && b.line && a.category != null && a.category === b.category
|
||||
? 1 - km / (2 * MATCH_RADIUS_KM)
|
||||
: 0;
|
||||
}
|
||||
|
||||
/** Whether two copies are the same physical train. */
|
||||
export function sameTrain(a, b) {
|
||||
return matchStrength(a, b) > 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Grid columns either side of a copy's that reach MATCH_RADIUS_KM east and
|
||||
* west of it, measured on the poleward edge of its row's neighbours.
|
||||
* @param {number} lat
|
||||
* @returns {number}
|
||||
*/
|
||||
function columnSpan(lat) {
|
||||
const poleward = Math.min(89, Math.abs(lat) + CELL_DEG);
|
||||
const cellKm = CELL_DEG * 111.32 * Math.cos((poleward * Math.PI) / 180);
|
||||
return Math.max(1, Math.ceil(MATCH_RADIUS_KM / cellKm));
|
||||
}
|
||||
|
||||
/**
|
||||
* Groups of two or more copies that are one train, at most one copy per
|
||||
* feed: two trains of one feed are two trains, even where a third feed's
|
||||
* copy resembles both (coupled TGVs). The strongest matches are joined
|
||||
* first. Numbered copies are compared wherever they are, the others only
|
||||
* within MATCH_RADIUS_KM's reach on the grid.
|
||||
* @param {object[]} copies
|
||||
* @returns {object[][]}
|
||||
*/
|
||||
export function matchCopies(copies) {
|
||||
const cells = new Map();
|
||||
const cellOf = (lat, lon) =>
|
||||
`${Math.floor(lat / CELL_DEG)}|${Math.floor(lon / CELL_DEG)}`;
|
||||
copies.forEach((copy, i) => {
|
||||
if (!Number.isFinite(copy.lat) || !Number.isFinite(copy.lon)) return;
|
||||
const key = cellOf(copy.lat, copy.lon);
|
||||
if (!cells.has(key)) cells.set(key, []);
|
||||
cells.get(key).push(i);
|
||||
});
|
||||
const pairs = [];
|
||||
// Numbered copies pair through their number, wherever they are.
|
||||
const byNumber = new Map();
|
||||
copies.forEach((copy, i) => {
|
||||
if (!copy.number) return;
|
||||
if (!byNumber.has(copy.number)) byNumber.set(copy.number, []);
|
||||
byNumber.get(copy.number).push(i);
|
||||
});
|
||||
for (const list of byNumber.values())
|
||||
for (let x = 0; x < list.length; x++)
|
||||
for (let y = x + 1; y < list.length; y++) {
|
||||
const strength = matchStrength(copies[list[x]], copies[list[y]]);
|
||||
if (strength > 0) pairs.push([strength, list[x], list[y]]);
|
||||
}
|
||||
// The others through the grid: only copies near each other.
|
||||
copies.forEach((copy, i) => {
|
||||
if (!Number.isFinite(copy.lat) || !Number.isFinite(copy.lon)) return;
|
||||
const row = Math.floor(copy.lat / CELL_DEG);
|
||||
const col = Math.floor(copy.lon / CELL_DEG);
|
||||
const span = columnSpan(copy.lat);
|
||||
for (let dr = -1; dr <= 1; dr++)
|
||||
for (let dc = -span; dc <= span; dc++)
|
||||
for (const j of cells.get(`${row + dr}|${col + dc}`) ?? []) {
|
||||
if (j <= i || (copy.number && copies[j].number)) continue;
|
||||
const strength = matchStrength(copy, copies[j]);
|
||||
if (strength > 0) pairs.push([strength, i, j]);
|
||||
}
|
||||
});
|
||||
pairs.sort((a, b) => b[0] - a[0]);
|
||||
const parent = copies.map((_, i) => i);
|
||||
const feeds = copies.map((copy) => new Set([copy.feedId]));
|
||||
const members = copies.map((_, i) => [i]);
|
||||
const find = (i) => {
|
||||
while (parent[i] !== i) i = parent[i] = parent[parent[i]];
|
||||
return i;
|
||||
};
|
||||
for (const [, i, j] of pairs) {
|
||||
const a = find(i);
|
||||
const b = find(j);
|
||||
if (a === b || [...feeds[b]].some((feed) => feeds[a].has(feed))) continue;
|
||||
// Every copy must match every other: a copy resembling two trains (an
|
||||
// unnumbered train at a busy hub) never joins them into one.
|
||||
const all = members[a].every((x) =>
|
||||
members[b].every(
|
||||
(y) => (x === i && y === j) || matchStrength(copies[x], copies[y]) > 0,
|
||||
),
|
||||
);
|
||||
if (!all) continue;
|
||||
parent[b] = a;
|
||||
for (const feed of feeds[b]) feeds[a].add(feed);
|
||||
members[a].push(...members[b]);
|
||||
}
|
||||
const groups = new Map();
|
||||
copies.forEach((copy, i) => {
|
||||
const root = find(i);
|
||||
if (!groups.has(root)) groups.set(root, []);
|
||||
groups.get(root).push(copy);
|
||||
});
|
||||
return [...groups.values()].filter((group) => group.length > 1);
|
||||
}
|
||||
|
||||
/**
|
||||
* A copy's score: `[position, line]`, compared in that order.
|
||||
* @param {object} copy
|
||||
* @returns {number[]}
|
||||
*/
|
||||
export function scoreCopy(copy) {
|
||||
return [POSITION_RANK[copy.position] ?? 0, copy.onShape === true ? 1 : 0];
|
||||
}
|
||||
|
||||
function better(a, b) {
|
||||
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return a[i] > b[i];
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* The copy each group draws, keeping last time's choice unless another copy
|
||||
* scores strictly higher.
|
||||
* @param {object[][]} groups From matchCopies.
|
||||
* @param {Map<string, string>} [previous] copy key → key drawn last time.
|
||||
* @returns {{winners: Map<string, string>, hidden: Set<string>}}
|
||||
* `winners`: every grouped copy's key → the key drawn for its train.
|
||||
*/
|
||||
export function chooseCopies(groups, previous = new Map()) {
|
||||
const winners = new Map();
|
||||
const hidden = new Set();
|
||||
for (const group of groups) {
|
||||
const scored = group.map((copy) => ({ copy, score: scoreCopy(copy) }));
|
||||
const keys = new Set(group.map((copy) => copy.key));
|
||||
const incumbentKey = group
|
||||
.map((copy) => previous.get(copy.key))
|
||||
.find((key) => key && keys.has(key));
|
||||
let best =
|
||||
scored.find(({ copy }) => copy.key === incumbentKey) ??
|
||||
scored.reduce((a, b) => (better(b.score, a.score) ? b : a));
|
||||
for (const candidate of scored)
|
||||
if (better(candidate.score, best.score)) best = candidate;
|
||||
for (const { copy } of scored) {
|
||||
winners.set(copy.key, best.copy.key);
|
||||
if (copy.key !== best.copy.key) hidden.add(copy.key);
|
||||
}
|
||||
}
|
||||
return { winners, hidden };
|
||||
}
|
||||
|
||||
/**
|
||||
* The layer's duplicate filter: after each poll it matches the trains every
|
||||
* loaded feed carries, marks the copies not drawn (`entry.duplicate`), and
|
||||
* moves a selection that sat on a copy now hidden to the copy drawn, so the
|
||||
* card follows the same physical train (its feed line names the new
|
||||
* source).
|
||||
* @param {{state: object, parts: object,
|
||||
* defer?: (fn: Function) => unknown}} context
|
||||
*/
|
||||
export function createDuplicateFilter({
|
||||
state,
|
||||
parts,
|
||||
defer = (fn) => setTimeout(fn, 0),
|
||||
}) {
|
||||
let previous = new Map();
|
||||
let pending = false;
|
||||
let lastStats = { groups: 0, hidden: 0 };
|
||||
|
||||
/** The comparable view of one drawn train. */
|
||||
function copyOf(entry) {
|
||||
const record = entry.record ?? {};
|
||||
const { number, line } = recordNumbers(record);
|
||||
return {
|
||||
key: entry.key,
|
||||
feedId: entry.feedId,
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
number,
|
||||
line,
|
||||
category: entry.category ?? record.category ?? null,
|
||||
position: record.positionSource ?? 'gps',
|
||||
onShape: Number.isInteger(entry.path?.shapeIndex),
|
||||
};
|
||||
}
|
||||
|
||||
/** Recompute which copies are drawn. Cheap enough for once per poll. */
|
||||
function refresh() {
|
||||
pending = false;
|
||||
const entries = [...state._trains.values()];
|
||||
const { winners, hidden } = chooseCopies(
|
||||
matchCopies(entries.map(copyOf)),
|
||||
previous,
|
||||
);
|
||||
previous = winners;
|
||||
for (const entry of entries) {
|
||||
const duplicate = hidden.has(entry.key);
|
||||
if (entry.duplicate === duplicate) continue;
|
||||
entry.duplicate = duplicate;
|
||||
parts.rendering.paint(entry);
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
}
|
||||
// A selection stays on its train: it moves to the copy now drawn.
|
||||
const selected = state._selectedKey;
|
||||
if (selected && hidden.has(selected)) {
|
||||
const drawn = winners.get(selected);
|
||||
if (drawn && state._trains.has(drawn)) parts.selection.selectTrain(drawn);
|
||||
}
|
||||
lastStats = {
|
||||
groups: new Set(winners.values()).size,
|
||||
hidden: hidden.size,
|
||||
};
|
||||
return lastStats;
|
||||
}
|
||||
|
||||
/** Coalesce the refreshes of several feeds' polls into one. */
|
||||
function scheduleRefresh() {
|
||||
if (pending) return;
|
||||
pending = true;
|
||||
defer(() => {
|
||||
if (pending) refresh();
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
refresh,
|
||||
scheduleRefresh,
|
||||
stats: () => ({ ...lastStats }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
// One physical train in several loaded live feeds is drawn once: copies are
|
||||
// matched by train number, or by line and category when near each other,
|
||||
// and the copy with the better position source and line is drawn.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
NUMBER_RADIUS_KM,
|
||||
chooseCopies,
|
||||
createDuplicateFilter,
|
||||
labelNumbers,
|
||||
matchCopies,
|
||||
recordNumbers,
|
||||
recordTrainNumber,
|
||||
sameTrain,
|
||||
scoreCopy,
|
||||
trainNumber,
|
||||
} from './dedupe.js';
|
||||
import * as dedupe from './dedupe.js';
|
||||
|
||||
const ROSENHEIM = { lat: 47.85, lon: 12.119 };
|
||||
const SALZBURG = { lat: 47.813, lon: 13.046 };
|
||||
const LINZ = { lat: 48.29, lon: 14.291 };
|
||||
|
||||
/** A fake copy of a live train. */
|
||||
function copy(key, feedId, extra = {}) {
|
||||
return {
|
||||
key,
|
||||
feedId,
|
||||
lat: ROSENHEIM.lat,
|
||||
lon: ROSENHEIM.lon,
|
||||
number: null,
|
||||
line: null,
|
||||
category: null,
|
||||
position: 'gps',
|
||||
onShape: false,
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
test('train numbers compare across feeds', () => {
|
||||
assert.equal(trainNumber('RJX 160'), '160');
|
||||
assert.equal(trainNumber('160'), '160');
|
||||
assert.equal(trainNumber('09725'), '9725');
|
||||
assert.equal(trainNumber('TGV 10465'), '10465');
|
||||
for (const none of [null, '', 'S', '0', 'RJX'])
|
||||
assert.equal(trainNumber(none), null, String(none));
|
||||
});
|
||||
|
||||
test('the same number is one train; another number is not', () => {
|
||||
const a = copy('a', 'feed-a', { number: '160' });
|
||||
assert.equal(sameTrain(a, copy('b', 'feed-b', { number: '160' })), true);
|
||||
assert.equal(sameTrain(a, copy('b', 'feed-b', { number: '161' })), false);
|
||||
// Never within one feed, never far apart.
|
||||
assert.equal(sameTrain(a, copy('b', 'feed-a', { number: '160' })), false);
|
||||
assert.equal(
|
||||
sameTrain(a, copy('b', 'feed-b', { number: '160', ...LINZ })),
|
||||
false,
|
||||
);
|
||||
// Two feeds report one train at different moments: 70 km on
|
||||
// (Rosenheim–Salzburg) it is still the same numbered train.
|
||||
assert.ok(NUMBER_RADIUS_KM > 70);
|
||||
assert.equal(
|
||||
sameTrain(a, copy('b', 'feed-b', { number: '160', ...SALZBURG })),
|
||||
true,
|
||||
);
|
||||
assert.equal(
|
||||
matchCopies([a, copy('b', 'feed-b', { number: '160', ...SALZBURG })])
|
||||
.length,
|
||||
1,
|
||||
);
|
||||
});
|
||||
|
||||
test('the filter matches nothing from timetables: no stops, dates or homes', () => {
|
||||
// Copies are live trains only; nothing in the filter reads a schedule.
|
||||
for (const gone of [
|
||||
'scheduleRunStops',
|
||||
'scheduleHomeCountry',
|
||||
'copyCountry',
|
||||
'shareTimedStops',
|
||||
'serviceDateKey',
|
||||
])
|
||||
assert.equal(dedupe[gone], undefined, gone);
|
||||
// Unnumbered copies off any line are never joined, however close.
|
||||
assert.equal(sameTrain(copy('a', 'feed-a'), copy('b', 'feed-b')), false);
|
||||
});
|
||||
|
||||
test('a bare-number headsign is the number when there is no name', () => {
|
||||
assert.equal(
|
||||
recordTrainNumber({ label: null, headsign: '839162' }),
|
||||
'839162',
|
||||
);
|
||||
assert.equal(
|
||||
recordTrainNumber({ label: 'RJX 160', headsign: '9999' }),
|
||||
'160',
|
||||
);
|
||||
assert.equal(recordTrainNumber({ label: null, headsign: 'Paris-Est' }), null);
|
||||
assert.equal(recordTrainNumber({ label: null, headsign: 'S 12' }), null);
|
||||
});
|
||||
|
||||
test('a live vehicle labelled with its own car number takes the number from its trip', () => {
|
||||
// A live feed's vehicle 8306 runs train 530.
|
||||
const live = { id: '8306', label: '8306', tripId: 'AM:530' };
|
||||
assert.equal(recordTrainNumber(live), '530');
|
||||
// A label that is not the vehicle id is the train's name.
|
||||
assert.equal(
|
||||
recordTrainNumber({ id: 'v1', label: '531', tripId: 'AM:530' }),
|
||||
'531',
|
||||
);
|
||||
// Long trip ids are not train numbers.
|
||||
assert.equal(
|
||||
recordTrainNumber({ id: '7', label: '7', tripId: '0519321010VRFV' }),
|
||||
null,
|
||||
);
|
||||
// The GPS copy matches a station-report copy of train 530, and wins over
|
||||
// it even on the operator's line.
|
||||
const groups = matchCopies([
|
||||
copy('gps', 'gps-feed', { number: recordTrainNumber(live) }),
|
||||
copy('event', 'event-feed', {
|
||||
number: '530',
|
||||
position: 'event',
|
||||
shape: 'operator',
|
||||
}),
|
||||
]);
|
||||
assert.equal(groups.length, 1);
|
||||
assert.equal(chooseCopies(groups).winners.get('event'), 'gps');
|
||||
});
|
||||
|
||||
test('a group never holds two trains of one feed (coupled trains)', () => {
|
||||
// Two coupled TGVs side by side in one feed; the other feed names one of
|
||||
// them. Each pairs with its own number only.
|
||||
const groups = matchCopies([
|
||||
copy('fr-6194', 'feed-fr', { number: '6194' }),
|
||||
copy('fr-6906', 'feed-fr', { number: '6906' }),
|
||||
copy('ch-6194', 'feed-ch', { number: '6194' }),
|
||||
copy('ch-6906', 'feed-ch', { number: '6906' }),
|
||||
]);
|
||||
assert.deepEqual(
|
||||
groups.map((group) => group.map((c) => c.key).sort()).sort(),
|
||||
[
|
||||
['ch-6194', 'fr-6194'],
|
||||
['ch-6906', 'fr-6906'],
|
||||
],
|
||||
);
|
||||
// On one line, one feed's two copies still never share a group.
|
||||
const s1 = { ...recordNumbers({ label: 'S1' }), category: 'local' };
|
||||
const unnamed = matchCopies([
|
||||
copy('a1', 'feed-a', s1),
|
||||
copy('a2', 'feed-a', { ...s1, lat: ROSENHEIM.lat + 0.01 }),
|
||||
copy('b1', 'feed-b', s1),
|
||||
]);
|
||||
assert.equal(unnamed.length, 1);
|
||||
assert.equal(new Set(unnamed[0].map((c) => c.feedId)).size, 2);
|
||||
});
|
||||
|
||||
test('a copy resembling two different trains never joins them', () => {
|
||||
// An unnumbered S1 lies near two numbered trains on its line; the two
|
||||
// carry different numbers, so the three are never one train.
|
||||
const s1 = { line: { product: 'S', number: '1' }, category: 'local' };
|
||||
const groups = matchCopies([
|
||||
copy('n1', 'feed-a', { number: '1211', ...s1 }),
|
||||
copy('n2', 'feed-s', { number: '22739', ...s1 }),
|
||||
copy('s1', 'feed-c', s1),
|
||||
]);
|
||||
assert.ok(
|
||||
groups.every((group) => group.length < 3),
|
||||
'never all three',
|
||||
);
|
||||
});
|
||||
|
||||
test('the score: position source, then the line', () => {
|
||||
const base = copy('a', 'x');
|
||||
assert.deepEqual(scoreCopy(base), [2, 0]);
|
||||
assert.deepEqual(scoreCopy({ ...base, position: 'event' }), [1, 0]);
|
||||
assert.deepEqual(scoreCopy({ ...base, onShape: true }), [2, 1]);
|
||||
// A source the layer does not know scores nothing.
|
||||
assert.deepEqual(scoreCopy({ ...base, position: 'psychic' }), [0, 0]);
|
||||
});
|
||||
|
||||
test('equal copies never trade places: the one drawn stays drawn', () => {
|
||||
const twins = [
|
||||
copy('a', 'f1', { number: '160', position: 'event' }),
|
||||
copy('b', 'f2', { number: '160', position: 'event' }),
|
||||
];
|
||||
const first = chooseCopies([twins]);
|
||||
const drawn = first.winners.get('a');
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const again = chooseCopies([[...twins].reverse()], first.winners);
|
||||
assert.equal(again.winners.get('a'), drawn);
|
||||
}
|
||||
// A GPS copy takes over from a station-report one at once.
|
||||
const live = chooseCopies(
|
||||
[[twins[0], { ...twins[1], position: 'gps' }]],
|
||||
new Map([
|
||||
['a', 'a'],
|
||||
['b', 'a'],
|
||||
]),
|
||||
);
|
||||
assert.equal(live.winners.get('a'), 'b');
|
||||
});
|
||||
|
||||
/**
|
||||
* A layer's state with one live train per feed, both train RJX 160, and
|
||||
* spies for what the filter calls.
|
||||
*/
|
||||
function fakeLayer({ selected = null } = {}) {
|
||||
const entry = (feedId, onShape) => ({
|
||||
key: `${feedId}:v160`,
|
||||
feedId,
|
||||
record: {
|
||||
id: 'v160',
|
||||
tripId: 't1',
|
||||
label: 'RJX 160',
|
||||
...ROSENHEIM,
|
||||
positionSource: 'gps',
|
||||
},
|
||||
path: onShape ? { shapeIndex: 0 } : null,
|
||||
});
|
||||
const trains = [entry('feed-a', false), entry('feed-b', true)];
|
||||
const state = {
|
||||
_trains: new Map(trains.map((t) => [t.key, t])),
|
||||
_selectedKey: selected,
|
||||
};
|
||||
const calls = { paint: [], selected: [] };
|
||||
const parts = {
|
||||
rendering: {
|
||||
paint: (e) => calls.paint.push([e.key, e.duplicate]),
|
||||
schedulePlayback: () => {},
|
||||
},
|
||||
selection: {
|
||||
selectTrain: (key) => {
|
||||
calls.selected.push(key);
|
||||
state._selectedKey = key;
|
||||
},
|
||||
},
|
||||
};
|
||||
return { state, parts, calls, trains };
|
||||
}
|
||||
|
||||
test('the filter hides the weaker copy and the selection follows its train', () => {
|
||||
const layer = fakeLayer({ selected: 'feed-a:v160' });
|
||||
const filter = createDuplicateFilter({ ...layer, defer: (fn) => fn() });
|
||||
assert.deepEqual(filter.refresh(), { groups: 1, hidden: 1 });
|
||||
const [unbound, operator] = layer.trains;
|
||||
assert.equal(unbound.duplicate, true, 'not on the operator’s line');
|
||||
assert.equal(operator.duplicate, false);
|
||||
assert.deepEqual(layer.calls.selected, [operator.key]);
|
||||
// When the copy on the operator's line goes (its feed left the view), the
|
||||
// other is drawn.
|
||||
layer.state._trains.delete(operator.key);
|
||||
filter.scheduleRefresh();
|
||||
assert.equal(unbound.duplicate, false);
|
||||
assert.deepEqual(filter.stats(), { groups: 0, hidden: 0 });
|
||||
});
|
||||
|
||||
test('a short number after a local product names a line, not a train (S1, RB 1, U6)', () => {
|
||||
for (const label of ['S1', 'RB 1', 'U6', 'S 12', 'RE5'])
|
||||
assert.equal(recordTrainNumber({ label }), null, label);
|
||||
assert.deepEqual(labelNumbers('RB 1').line, { product: 'RB', number: '1' });
|
||||
// Three digits, or a long-distance product's own short number, are a
|
||||
// train's.
|
||||
assert.equal(recordTrainNumber({ label: 'EC 7' }), '7');
|
||||
assert.equal(recordTrainNumber({ label: 'NJ 40' }), '40');
|
||||
assert.equal(recordTrainNumber({ label: 'S 1264' }), '1264');
|
||||
// A line name gives way to a trip id that is the train's number.
|
||||
assert.equal(recordTrainNumber({ label: '5', tripId: 'AM:5' }), '5');
|
||||
|
||||
// An S1 and an RB 1 25 km apart are never joined as one train numbered 1.
|
||||
const s1 = copy('s1', 'feed-a', {
|
||||
...recordNumbers({ label: 'S1' }),
|
||||
lat: 48.14,
|
||||
lon: 11.56,
|
||||
category: 'local',
|
||||
});
|
||||
const rb1 = copy('rb1', 'feed-b', {
|
||||
...recordNumbers({ label: 'RB 1' }),
|
||||
lat: 48.14 + 25 / 111.32,
|
||||
lon: 11.56,
|
||||
category: 'regional',
|
||||
});
|
||||
assert.equal(sameTrain(s1, rb1), false);
|
||||
assert.deepEqual(matchCopies([s1, rb1]), []);
|
||||
// Nearer, still two lines.
|
||||
assert.equal(sameTrain(s1, { ...rb1, lat: 48.15, category: 'local' }), false);
|
||||
});
|
||||
|
||||
test('copies on one line are one train in one category, the nearest first', () => {
|
||||
const at = (key, feedId, km, extra = {}) =>
|
||||
copy(key, feedId, {
|
||||
...recordNumbers({ label: extra.label ?? 'S1' }),
|
||||
lat: 48.14 + km / 111.32,
|
||||
lon: 11.56,
|
||||
category: 'local',
|
||||
...extra,
|
||||
});
|
||||
const gps = at('gps', 'feed-a', 0);
|
||||
// The other feed reports two S1 trains near it; the nearer is the same.
|
||||
const near = at('near', 'feed-b', 1, { position: 'event' });
|
||||
const next = at('next', 'feed-b', 6, { label: 'S 1', position: 'event' });
|
||||
assert.equal(sameTrain(gps, near), true);
|
||||
assert.deepEqual(
|
||||
matchCopies([next, gps, near]).map((group) =>
|
||||
group.map((c) => c.key).sort(),
|
||||
),
|
||||
[['gps', 'near']],
|
||||
);
|
||||
// Another category, or beyond the match radius: not one train.
|
||||
assert.equal(sameTrain(gps, { ...near, category: 'regional' }), false);
|
||||
assert.equal(sameTrain(gps, at('far', 'feed-b', 20)), false);
|
||||
});
|
||||
|
||||
test('copies on one line 14 km apart east-west at 60°N are compared', () => {
|
||||
// A 0.25° grid column is 13.9 km wide there: the copies sit two columns
|
||||
// apart.
|
||||
const line = { ...recordNumbers({ label: 'R1' }), category: 'regional' };
|
||||
const west = copy('west', 'feed-a', { lat: 60, lon: 10.24, ...line });
|
||||
const east = copy('east', 'feed-b', { lat: 60, lon: 10.5, ...line });
|
||||
assert.equal(sameTrain(west, east), true);
|
||||
assert.equal(matchCopies([west, east]).length, 1);
|
||||
});
|
||||
|
||||
test('the filter reads lines and categories from the trains it compares', () => {
|
||||
const entry = (feedId, label, category, lat) => ({
|
||||
key: `${feedId}:${label}`,
|
||||
feedId,
|
||||
category,
|
||||
record: {
|
||||
id: `v-${feedId}`,
|
||||
label,
|
||||
lat,
|
||||
lon: 11.56,
|
||||
positionSource: 'gps',
|
||||
},
|
||||
});
|
||||
const trains = [
|
||||
entry('munich-live', 'S1', 'local', 48.14),
|
||||
entry('other-live', 'S 1', 'local', 48.15),
|
||||
entry('third-live', 'RB 1', 'regional', 48.16),
|
||||
];
|
||||
const state = {
|
||||
_trains: new Map(trains.map((t) => [t.key, t])),
|
||||
_pathPacks: new Map(),
|
||||
_selectedKey: null,
|
||||
};
|
||||
const parts = {
|
||||
rendering: { paint() {}, schedulePlayback() {} },
|
||||
selection: { selectTrain() {} },
|
||||
};
|
||||
const filter = createDuplicateFilter({
|
||||
state,
|
||||
parts,
|
||||
defer: (fn) => fn(),
|
||||
});
|
||||
assert.deepEqual(filter.refresh(), { groups: 1, hidden: 1 });
|
||||
assert.equal(trains[2].duplicate, false, 'the RB 1 is its own train');
|
||||
});
|
||||
|
||||
test('a Swiss IC line name is not a train number', () => {
|
||||
assert.deepEqual(labelNumbers('IC 1'), {
|
||||
number: null,
|
||||
line: { product: 'IC', number: '1' },
|
||||
});
|
||||
assert.deepEqual(labelNumbers('IC 2010'), { number: '2010', line: null });
|
||||
assert.deepEqual(labelNumbers('EC 7'), { number: '7', line: null });
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
import { FOLLOW_MIN_RANGE_M } from '../../data/trackedCamera.js';
|
||||
import { copyInto, lerpInto } from '../../geo/vector.js';
|
||||
import {
|
||||
FOLLOW_HANDOVER_MS,
|
||||
railFollowOffset,
|
||||
railTrainFollowable,
|
||||
} from './policy.js';
|
||||
|
||||
/** The selected train's kind in the shared world-focus framing. */
|
||||
export const RAIL_FOCUS_KIND = 'train';
|
||||
|
||||
/**
|
||||
* The selected train's camera.
|
||||
*
|
||||
* A moving train is followed as a tracked aircraft is: the layer hands the
|
||||
* camera port a follow target that stands on the train's marker, framed by
|
||||
* the shared world-focus framing for a train and never closer than the
|
||||
* aircraft's readable minimum, so the camera rides with the train and the
|
||||
* user still orbits and zooms around it. Any other train gets one fly-to
|
||||
* through the shared world-focus request, as a vessel does. Inside the
|
||||
* Cockpit that request is refused with its toast.
|
||||
*
|
||||
* The follow lets go when the train is deselected (an empty click, Escape, its
|
||||
* category hidden, the train leaving its feed, the layer turned off), when
|
||||
* another train is selected (which takes the camera in its turn), and when
|
||||
* another owner takes the camera: anything else the camera follows (an
|
||||
* aircraft or satellite tracked by another layer) clears the selection as
|
||||
* well, while a navigation that only stops the follow (a search, a fly-to)
|
||||
* leaves the train selected. Letting go leaves the camera where it is.
|
||||
*
|
||||
* When the selection moves to another feed's copy of the same train
|
||||
* (dedupe.js), the follow target stays and glides to the new copy.
|
||||
*
|
||||
* Services (all optional; without them a selection has no camera):
|
||||
* services.camera = {
|
||||
* framing: {rangeM, pitchDeg}, // WORLD_FOCUS_FRAMING.train
|
||||
* requestWorldFocus(detail) → boolean, // src/worldFocus.js
|
||||
* isCockpitActive() → boolean,
|
||||
* }
|
||||
*
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createFollow({ state, services, parts }) {
|
||||
const camera = services.camera ?? null;
|
||||
let removeFollowListener = null;
|
||||
|
||||
function markerPosition(entry) {
|
||||
const p = entry?.marker?.position;
|
||||
return p &&
|
||||
Number.isFinite(p.x) &&
|
||||
Number.isFinite(p.y) &&
|
||||
Number.isFinite(p.z) &&
|
||||
p.x * p.x + p.y * p.y + p.z * p.z > 0
|
||||
? p
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the follow target stands: on the selected train's marker, or
|
||||
* gliding to it after a handover. A new object each call, never the
|
||||
* marker's own vector.
|
||||
*/
|
||||
function followedPosition(follow) {
|
||||
const live = markerPosition(state._trains.get(state._selectedKey));
|
||||
if (live) copyInto(live, follow.last);
|
||||
const blend = follow.blend;
|
||||
if (blend) {
|
||||
const t = (performance.now() - blend.startMs) / FOLLOW_HANDOVER_MS;
|
||||
if (t < 1) {
|
||||
const eased = t <= 0 ? 0 : t * t * (3 - 2 * t);
|
||||
lerpInto(blend.from, follow.last, eased, follow.shown);
|
||||
return { ...follow.shown };
|
||||
}
|
||||
follow.blend = null;
|
||||
}
|
||||
copyInto(follow.last, follow.shown);
|
||||
return { ...follow.shown };
|
||||
}
|
||||
|
||||
/** Whether the camera follows this train now. */
|
||||
function isFollowing(key) {
|
||||
const follow = state._follow;
|
||||
return Boolean(
|
||||
follow &&
|
||||
follow.key === key &&
|
||||
findCamera(state._viewer)?.followed === follow.target,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Let go of the train. The camera stays where the follow left it.
|
||||
* @param {{untrack?: boolean}} [options] `untrack: false` when another
|
||||
* owner already took the camera: what it follows is left alone.
|
||||
*/
|
||||
function release({ untrack = true } = {}) {
|
||||
const follow = state._follow;
|
||||
if (!follow) return;
|
||||
// Cleared first: the follow change below is this layer's own.
|
||||
state._follow = null;
|
||||
const viewer = state._viewer;
|
||||
if (!untrack || !viewer || viewer.isDestroyed?.()) return;
|
||||
const port = findCamera(viewer);
|
||||
if (port?.followed === follow.target) port.follow(null);
|
||||
}
|
||||
|
||||
function startFollow(entry, position, port) {
|
||||
const offset = railFollowOffset(camera.framing, port.pose()?.heading);
|
||||
const follow = {
|
||||
key: entry.key,
|
||||
target: null,
|
||||
last: { x: position.x, y: position.y, z: position.z },
|
||||
shown: { x: position.x, y: position.y, z: position.z },
|
||||
blend: null,
|
||||
};
|
||||
follow.target = {
|
||||
key: `rail:${entry.key}`,
|
||||
position: () => followedPosition(follow),
|
||||
frame: 'enu',
|
||||
viewFrom: { x: offset.x, y: offset.y, z: offset.z },
|
||||
// Framed exactly once, as a tracked aircraft is, and never closer.
|
||||
minRange: FOLLOW_MIN_RANGE_M,
|
||||
selectionOrigin: 'user',
|
||||
};
|
||||
state._follow = follow;
|
||||
// A flight in progress would keep the camera from taking the frame.
|
||||
port.cancelFlight();
|
||||
port.follow(follow.target);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Give the camera to a train the user selected: follow it when it moves,
|
||||
* else fly to it once. A train already followed keeps its follow.
|
||||
* @param {object} entry
|
||||
* @returns {boolean} Whether the camera was taken or kept.
|
||||
*/
|
||||
function focus(entry) {
|
||||
if (!camera || !entry) return false;
|
||||
if (isFollowing(entry.key)) return true;
|
||||
release();
|
||||
const viewer = state._viewer;
|
||||
const position = markerPosition(entry);
|
||||
if (!viewer || !position) return false;
|
||||
const port = findCamera(viewer);
|
||||
if (
|
||||
port &&
|
||||
camera.framing &&
|
||||
!camera.isCockpitActive?.() &&
|
||||
railTrainFollowable(entry)
|
||||
)
|
||||
return startFollow(entry, position, port);
|
||||
const label = String(entry.record?.label || entry.record?.id || '').trim();
|
||||
return (
|
||||
camera.requestWorldFocus?.({
|
||||
kind: RAIL_FOCUS_KIND,
|
||||
id: entry.key,
|
||||
label: label || entry.key,
|
||||
position: { x: position.x, y: position.y, z: position.z },
|
||||
}) === true
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The selection moved to another feed's copy of the followed train: the
|
||||
* follow target stays, and glides from where it stands to the new copy.
|
||||
* @param {object} entry The copy now selected.
|
||||
*/
|
||||
function handover(entry) {
|
||||
const follow = state._follow;
|
||||
if (!follow || !entry || follow.key === entry.key) return;
|
||||
follow.key = entry.key;
|
||||
follow.blend = {
|
||||
from: { ...follow.shown },
|
||||
startMs: performance.now(),
|
||||
};
|
||||
}
|
||||
|
||||
function onFollowChanged() {
|
||||
const follow = state._follow;
|
||||
const followed = findCamera(state._viewer)?.followed ?? null;
|
||||
if (!follow || followed === follow.target) return;
|
||||
// An aircraft or satellite another layer tracks takes the scene, as it
|
||||
// does from a selected vessel. A navigation that only stops the follow
|
||||
// keeps the train selected.
|
||||
if (followed) parts.selection.clearSelection({ untrack: false });
|
||||
else release({ untrack: false });
|
||||
}
|
||||
|
||||
/** Watch for other camera owners while the layer is on. */
|
||||
function install(viewer) {
|
||||
if (removeFollowListener) return;
|
||||
removeFollowListener =
|
||||
findCamera(viewer)?.on('followChanged', onFollowChanged) ?? null;
|
||||
}
|
||||
|
||||
function uninstall() {
|
||||
removeFollowListener?.();
|
||||
removeFollowListener = null;
|
||||
}
|
||||
|
||||
/** For QA probes: which train the camera follows, if any. */
|
||||
function stats() {
|
||||
const follow = state._follow;
|
||||
return follow
|
||||
? { key: follow.key, tracked: isFollowing(follow.key) }
|
||||
: null;
|
||||
}
|
||||
|
||||
return {
|
||||
focus,
|
||||
release,
|
||||
handover,
|
||||
isFollowing,
|
||||
install,
|
||||
uninstall,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,452 @@
|
||||
// The selected train's camera and its visibility from far out: a moving train
|
||||
// is followed through the camera port (as an aircraft is), any other
|
||||
// train is flown to once, and the selected train's feed stays polled at any
|
||||
// distance while the rest of the network hides as before.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FOLLOW_MIN_RANGE_M } from '../../data/trackedCamera.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import {
|
||||
ACTIVATION_EXIT_ALTITUDE_M,
|
||||
FOLLOW_HANDOVER_MS,
|
||||
RAIL_POLL_MS,
|
||||
railFollowOffset,
|
||||
railTrainFollowable,
|
||||
railTrainKey,
|
||||
} from './policy.js';
|
||||
import { WORLD_FOCUS_FRAMING } from '../../worldFocus.js';
|
||||
import { createTrack, insertFix } from '../../data/contactPlayback.js';
|
||||
import {
|
||||
BOSTON,
|
||||
RAIL_HARNESS_T0 as T0,
|
||||
railLayerHarness as harness,
|
||||
railTrain as train,
|
||||
} from '../../testSupport/railLayerHarness.mjs';
|
||||
|
||||
const MADRID = { lat: 40.4168, lon: -3.7038 };
|
||||
const ORBITAL_M = 20_000_000;
|
||||
|
||||
/**
|
||||
* Feed a train reports that move it, poll after poll, until its playback is
|
||||
* gliding along them.
|
||||
*/
|
||||
async function bringToMotion(app, feedId, id, start) {
|
||||
let step = 0;
|
||||
app.feeds.set(feedId, () => [
|
||||
train(id, start.lat + step * 0.003, start.lon),
|
||||
train(`${id}-parked`, start.lat - 0.05, start.lon - 0.05),
|
||||
]);
|
||||
await app.enable();
|
||||
const key = railTrainKey(feedId, id);
|
||||
for (let i = 0; i < 12 && !railTrainFollowable(app.entry(key)); i += 1) {
|
||||
step += 1;
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.ok(railTrainFollowable(app.entry(key)), 'the train is moving');
|
||||
return key;
|
||||
}
|
||||
|
||||
test('the follow offset is the shared train framing seen along the heading', () => {
|
||||
const framing = WORLD_FOCUS_FRAMING.train;
|
||||
const north = railFollowOffset(framing, 0);
|
||||
// Behind (south of) the train and above it, looking north and down.
|
||||
assert.ok(Math.abs(north.x) < 1e-9);
|
||||
assert.ok(north.y < 0 && north.z > 0);
|
||||
const range = Math.hypot(north.x, north.y, north.z);
|
||||
assert.ok(Math.abs(range - framing.rangeM) < 1e-6);
|
||||
const pitch = (Math.atan2(north.z, -north.y) * 180) / Math.PI;
|
||||
assert.ok(Math.abs(pitch + framing.pitchDeg) < 1e-9);
|
||||
// Facing east: the camera stands west of the train.
|
||||
const east = railFollowOffset(framing, Math.PI / 2);
|
||||
assert.ok(east.x < 0 && Math.abs(east.y) < 1e-6);
|
||||
});
|
||||
|
||||
/** A playback track of reports 15 s apart at these [lat, lon] places. */
|
||||
function trackOf(points) {
|
||||
const track = createTrack();
|
||||
points.forEach(([lat, lon], i) =>
|
||||
insertFix(track, { t: T0 + i * 15_000, lat, lon }, { replayed: true }),
|
||||
);
|
||||
return track;
|
||||
}
|
||||
|
||||
test('a train is followed while it moves, and not once it is parked or unheard', () => {
|
||||
const entry = (fields, points = [[BOSTON.lat, BOSTON.lon]]) => ({
|
||||
sample: { phase: 'playing', latestReportAgeMs: 20_000, ...fields },
|
||||
track: trackOf(points),
|
||||
});
|
||||
const moved = [
|
||||
[BOSTON.lat, BOSTON.lon],
|
||||
[BOSTON.lat + 0.003, BOSTON.lon],
|
||||
];
|
||||
const parked = [
|
||||
[BOSTON.lat, BOSTON.lon],
|
||||
[BOSTON.lat + 0.00005, BOSTON.lon],
|
||||
];
|
||||
// Gliding between two reports.
|
||||
assert.equal(railTrainFollowable(entry({ segmentSpeedMps: 25 })), true);
|
||||
// Dwelling at a stop with its departure already reported.
|
||||
assert.equal(
|
||||
railTrainFollowable(
|
||||
entry({
|
||||
segmentSpeedMps: 0,
|
||||
motion: 'stopped',
|
||||
displayT: 1_000,
|
||||
nextMotionT: 31_000,
|
||||
}),
|
||||
),
|
||||
true,
|
||||
);
|
||||
// Between reports: the playback waits at the latest one (or is still
|
||||
// buffering) after the last two moved it; this is a moving train.
|
||||
for (const phase of ['held', 'buffering'])
|
||||
assert.equal(
|
||||
railTrainFollowable(
|
||||
entry({ phase, segmentSpeedMps: 0, motion: 'unknown' }, moved),
|
||||
),
|
||||
true,
|
||||
phase,
|
||||
);
|
||||
// Parked: the last reports are one place (GPS jitter aside), and nothing
|
||||
// says it will move.
|
||||
assert.equal(
|
||||
railTrainFollowable(
|
||||
entry(
|
||||
{
|
||||
segmentSpeedMps: 0,
|
||||
motion: 'stopped',
|
||||
displayT: 1_000,
|
||||
nextMotionT: Infinity,
|
||||
},
|
||||
parked,
|
||||
),
|
||||
),
|
||||
false,
|
||||
);
|
||||
// A single report, a train not heard from lately, or no playback at all.
|
||||
assert.equal(
|
||||
railTrainFollowable(
|
||||
entry({ phase: 'held', segmentSpeedMps: 0, motion: 'unknown' }),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
railTrainFollowable(
|
||||
entry({ segmentSpeedMps: 25, latestReportAgeMs: 120_000 }, moved),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.equal(railTrainFollowable({}), false);
|
||||
assert.equal(railTrainFollowable(null), false);
|
||||
});
|
||||
|
||||
test('selecting a moving train hands the camera a follow target that rides on its marker', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.moveCameraQuietly({ heading: Math.PI / 4 });
|
||||
const cancelled = app.camera.flightsCancelled;
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
|
||||
const target = app.camera.followed;
|
||||
assert.ok(target, 'the camera follows a target');
|
||||
assert.equal(app.focusRequests.length, 0, 'no one-shot fly-to');
|
||||
assert.equal(app.camera.flightsCancelled, cancelled + 1);
|
||||
// Framed as the aircraft are (exactly once, never closer than their
|
||||
// minimum), from the train's own framing seen along the camera's heading.
|
||||
assert.equal(app.follows.length, 1);
|
||||
assert.equal(target.frame, 'enu');
|
||||
assert.equal(target.minRange, FOLLOW_MIN_RANGE_M);
|
||||
const expected = railFollowOffset(WORLD_FOCUS_FRAMING.train, Math.PI / 4);
|
||||
assert.ok(Math.abs(target.viewFrom.x - expected.x) < 1e-6);
|
||||
assert.ok(Math.abs(target.viewFrom.z - expected.z) < 1e-6);
|
||||
|
||||
// The target stands where the marker is drawn, frame after frame.
|
||||
const marker = app.entry(key).marker;
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
app.run(1_000);
|
||||
const shown = app.trackedPosition();
|
||||
assert.ok(distance(shown, marker.position) < 1e-6, 'on the marker');
|
||||
assert.notEqual(shown, marker.position, 'a copy');
|
||||
}
|
||||
assert.ok(app.layer.getRouteDisplayStats().follow.tracked);
|
||||
|
||||
// Picking the followed train again keeps the follow as it is.
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.equal(app.camera.followed, target);
|
||||
assert.equal(app.follows.length, 1);
|
||||
});
|
||||
|
||||
test('a click on a train selects it; a click on the map lets it go', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const icons = app.drawn('icons');
|
||||
assert.ok(icons.items.has(key), 'the train is drawn as an icon');
|
||||
app.click({ set: icons.spec.id, id: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
assert.ok(app.camera.followed);
|
||||
// Its 3D model names it by its pick meta.
|
||||
app.click(null);
|
||||
assert.equal(app.state()._selectedKey, null);
|
||||
assert.equal(app.camera.followed, null);
|
||||
app.click({ set: 'fleet-models', id: 'm1', meta: key, surface: false });
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
});
|
||||
|
||||
test('a parked train, or one known from a single report, is flown to once', async (t) => {
|
||||
const app = harness(t);
|
||||
await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const parked = railTrainKey('mbta-rail', 'T1-parked');
|
||||
assert.equal(railTrainFollowable(app.entry(parked)), false);
|
||||
app.parts().selection.selectAndFocusTrain(parked);
|
||||
assert.equal(app.camera.followed, null);
|
||||
assert.equal(app.follows.length, 0);
|
||||
assert.equal(app.focusRequests.length, 1);
|
||||
const request = app.focusRequests[0];
|
||||
assert.equal(request.kind, 'train');
|
||||
assert.equal(request.id, parked);
|
||||
assert.ok(
|
||||
distance(request.position, app.entry(parked).marker.position) < 1e-6,
|
||||
);
|
||||
// A copy, never the marker's own vector.
|
||||
assert.notEqual(request.position, app.entry(parked).marker.position);
|
||||
|
||||
// A second click flies again, as for a vessel.
|
||||
app.parts().selection.selectAndFocusTrain(parked);
|
||||
assert.equal(app.focusRequests.length, 2);
|
||||
|
||||
// A train with one report has no motion to follow.
|
||||
app.feeds.set('mbta-rail', () => [
|
||||
train('T1', BOSTON.lat, BOSTON.lon),
|
||||
train('T1-parked', BOSTON.lat - 0.05, BOSTON.lon - 0.05),
|
||||
train('NEW', BOSTON.lat + 0.02, BOSTON.lon + 0.02),
|
||||
]);
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
const fresh = railTrainKey('mbta-rail', 'NEW');
|
||||
app.parts().selection.selectAndFocusTrain(fresh);
|
||||
assert.equal(app.camera.followed, null);
|
||||
assert.equal(app.focusRequests.at(-1).id, fresh);
|
||||
});
|
||||
|
||||
test('inside the Cockpit a moving train is not followed: the shared request refuses', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.setCockpit(true);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.equal(app.camera.followed, null);
|
||||
assert.equal(app.focusRequests.length, 1, 'the request carries the refusal');
|
||||
assert.equal(app.state()._selectedKey, key, 'the train is still selected');
|
||||
});
|
||||
|
||||
test('deselecting or Escape lets go of the camera where it is', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.ok(app.camera.followed);
|
||||
app.parts().selection.clearSelection();
|
||||
assert.equal(app.camera.followed, null);
|
||||
assert.equal(app.state()._follow, null);
|
||||
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.ok(app.camera.followed);
|
||||
globalThis.document.dispatchEvent(
|
||||
Object.assign(new Event('keydown'), { key: 'Escape' }),
|
||||
);
|
||||
assert.equal(app.state()._selectedKey, null);
|
||||
assert.equal(app.camera.followed, null);
|
||||
});
|
||||
|
||||
test('orbiting and zooming around the train keep the follow, as for an aircraft', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
const target = app.camera.followed;
|
||||
// Camera input while following moves the camera around the target;
|
||||
// nothing here changes what is followed, so the follow stays.
|
||||
await app.moveCamera({ altitude: 60_000 });
|
||||
app.run(2_000);
|
||||
await app.moveCamera({ altitude: 8_000 });
|
||||
assert.equal(app.camera.followed, target);
|
||||
assert.ok(app.parts().follow.isFollowing(key));
|
||||
});
|
||||
|
||||
test('another camera owner ends the follow: a tracked aircraft takes the selection too', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
|
||||
// An aircraft layer follows its contact.
|
||||
const aircraft = {
|
||||
key: 'flights:abc123',
|
||||
position: () => fromDegrees(-71, 42.3, 3000),
|
||||
frame: 'enu',
|
||||
viewFrom: { x: 0, y: -1000, z: 500 },
|
||||
};
|
||||
app.camera.follow(aircraft);
|
||||
assert.equal(app.camera.followed, aircraft, 'its follow is untouched');
|
||||
assert.equal(app.state()._selectedKey, null);
|
||||
assert.equal(app.state()._follow, null);
|
||||
});
|
||||
|
||||
test('a navigation that releases the follow camera keeps the train selected', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
// What the shell's release does before a search or a fly-to.
|
||||
app.camera.follow(null);
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
assert.equal(app.state()._follow, null);
|
||||
// Picking the train again takes the camera back.
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.ok(app.parts().follow.isFollowing(key));
|
||||
});
|
||||
|
||||
test('selecting another train hands the camera over with a fresh frame', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
assert.ok(app.camera.followed);
|
||||
const parked = railTrainKey('mbta-rail', 'T1-parked');
|
||||
app.parts().selection.selectAndFocusTrain(parked);
|
||||
assert.equal(app.camera.followed, null, 'the follow let go');
|
||||
assert.equal(app.focusRequests.at(-1).id, parked, 'and the new train flew');
|
||||
});
|
||||
|
||||
test('from orbit the selected train and its feed stay; the other trains go as before', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const parked = railTrainKey('mbta-rail', 'T1-parked');
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
|
||||
await app.moveCamera({ altitude: ORBITAL_M });
|
||||
assert.ok(ORBITAL_M > ACTIVATION_EXIT_ALTITUDE_M);
|
||||
const state = app.state();
|
||||
assert.equal(state._heldFeedId, 'mbta-rail');
|
||||
assert.ok(state._activeFeeds.has('mbta-rail'), 'its feed is still polled');
|
||||
assert.ok(app.entry(key)?.marker?.show, 'the selected train is drawn');
|
||||
assert.equal(app.entry(parked), undefined, 'the others have gone');
|
||||
assert.ok(app.camera.followed, 'and the follow holds');
|
||||
|
||||
// The feed keeps updating, for this train alone.
|
||||
const before = app.requested.length;
|
||||
const position = { ...app.entry(key).marker.position };
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.ok(app.requested.length > before);
|
||||
assert.equal(app.entry(parked), undefined);
|
||||
assert.ok(
|
||||
distance(position, app.entry(key).marker.position) > 1,
|
||||
'it still moves',
|
||||
);
|
||||
assert.equal(app.layer.getRouteDisplayStats().heldFeed, 'mbta-rail');
|
||||
|
||||
// Deselecting returns the feed to the viewport's rules: from orbit, gone.
|
||||
app.parts().selection.clearSelection();
|
||||
await app.recheck();
|
||||
assert.equal(state._heldFeedId, null);
|
||||
assert.equal(state._activeFeeds.has('mbta-rail'), false);
|
||||
assert.equal(state._trains.size, 0);
|
||||
});
|
||||
|
||||
test('a held feed the view wants again brings its other trains back at once', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
const parked = railTrainKey('mbta-rail', 'T1-parked');
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
await app.moveCamera({ altitude: ORBITAL_M });
|
||||
assert.equal(app.entry(parked), undefined);
|
||||
const before = app.requested.length;
|
||||
await app.moveCamera({ altitude: 30_000 });
|
||||
assert.equal(app.state()._heldFeedId, null);
|
||||
assert.ok(app.requested.length > before, 'polled at once');
|
||||
assert.ok(app.entry(parked), 'the others are back');
|
||||
assert.ok(app.entry(key), 'and the selection is kept');
|
||||
assert.equal(app.state()._selectedKey, key);
|
||||
});
|
||||
|
||||
test('far side of the globe: the selected train is hidden behind the Earth', async (t) => {
|
||||
const app = harness(t);
|
||||
const key = await bringToMotion(app, 'mbta-rail', 'T1', BOSTON);
|
||||
app.parts().selection.selectAndFocusTrain(key);
|
||||
app.camera.follow(null); // the camera is free to go round
|
||||
await app.moveCamera({ altitude: ORBITAL_M });
|
||||
const marker = app.entry(key).marker;
|
||||
const drawn = () => app.drawn('icons').items.get(key)?.show;
|
||||
app.moveCameraQuietly({
|
||||
position: fromDegrees(BOSTON.lon, BOSTON.lat, ORBITAL_M),
|
||||
});
|
||||
app.run(250);
|
||||
assert.equal(marker.show, true, 'seen from above');
|
||||
assert.equal(drawn(), true);
|
||||
app.moveCameraQuietly({
|
||||
position: fromDegrees(BOSTON.lon + 180, -BOSTON.lat, ORBITAL_M),
|
||||
});
|
||||
app.run(250);
|
||||
assert.equal(marker.show, false, 'hidden from the antipode');
|
||||
assert.equal(drawn(), false);
|
||||
});
|
||||
|
||||
test('the follow glides to the copy another feed now draws, without letting go', async (t) => {
|
||||
const app = harness(t, { at: MADRID });
|
||||
// One Alvia in two feeds: a station-event copy and, a poll later, a GPS
|
||||
// copy that outranks it, so the duplicate filter moves the selection.
|
||||
let step = 0;
|
||||
let gpsCopy = false;
|
||||
const near = (offset) => ({
|
||||
lat: MADRID.lat + offset + step * 0.003,
|
||||
lon: MADRID.lon,
|
||||
});
|
||||
app.feeds.set('renfe-cercanias', () => [
|
||||
train('A1', near(0).lat, near(0).lon, {
|
||||
label: 'ALVIA 4073',
|
||||
positionSource: 'event',
|
||||
}),
|
||||
]);
|
||||
app.feeds.set('renfe-larga-distancia', () =>
|
||||
gpsCopy
|
||||
? [
|
||||
train('B1', near(0.01).lat, near(0.01).lon, {
|
||||
label: '4073',
|
||||
positionSource: 'gps',
|
||||
}),
|
||||
]
|
||||
: [],
|
||||
);
|
||||
await app.enable();
|
||||
const a = railTrainKey('renfe-cercanias', 'A1');
|
||||
const b = railTrainKey('renfe-larga-distancia', 'B1');
|
||||
for (let i = 0; i < 12 && !railTrainFollowable(app.entry(a)); i += 1) {
|
||||
step += 1;
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.ok(railTrainFollowable(app.entry(a)));
|
||||
app.parts().selection.selectAndFocusTrain(a);
|
||||
const target = app.camera.followed;
|
||||
assert.ok(target);
|
||||
const onA = app.trackedPosition();
|
||||
|
||||
gpsCopy = true;
|
||||
step += 1;
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
assert.equal(app.state()._selectedKey, b, 'the selection moved');
|
||||
assert.equal(app.camera.followed, target, 'the same follow');
|
||||
assert.equal(app.follows.length, 1, 'no new frame: no jump');
|
||||
assert.equal(app.focusRequests.length, 0);
|
||||
assert.ok(app.parts().follow.isFollowing(b));
|
||||
// It starts where it stood, then glides onto the new copy.
|
||||
const start = app.trackedPosition();
|
||||
assert.ok(distance(start, onA) < 50, 'no jump at the handover');
|
||||
app.run(FOLLOW_HANDOVER_MS + 250);
|
||||
const settled = app.trackedPosition();
|
||||
assert.ok(
|
||||
distance(settled, app.entry(b).marker.position) < 1e-6,
|
||||
'on the new copy',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,482 @@
|
||||
/**
|
||||
* Where trains and the selected trip's stops stand while their floor cell is
|
||||
* cold: a train on the floor it last stood on (or a neighbouring cell's), a
|
||||
* stop on the ellipsoid only until its cell is warm, and the cell is warmed
|
||||
* off the frame path. Seen on Google's photorealistic tiles, where a train
|
||||
* running onto unsampled cells dropped about 150 m under its line near
|
||||
* Chicago, then jumped back once a cell warmed.
|
||||
*/
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import {
|
||||
BOSTON,
|
||||
railLayerHarness as harness,
|
||||
railTrain as train,
|
||||
} from '../../testSupport/railLayerHarness.mjs';
|
||||
import {
|
||||
COLD_CELL_FLUSH_MS,
|
||||
COLD_CELL_RETRY_MS,
|
||||
COLD_CELLS_PER_FLUSH,
|
||||
FLOOR_CELLS_BURST,
|
||||
FLOOR_CELLS_PER_MINUTE,
|
||||
FLOOR_WARM_MAX_DIST_KM,
|
||||
STOP_REFRESH_MS,
|
||||
TRACK_MAX_GRADE,
|
||||
TRACK_PRIOR_BELOW_M,
|
||||
TRACK_SAMPLE_MAX_AGE_MS,
|
||||
TRACK_SAMPLE_MAX_CAMERA_M,
|
||||
TRACK_SAMPLE_REFRESH_MS,
|
||||
TRACK_SAMPLE_RETRY_MS,
|
||||
railTrainKey,
|
||||
} from './policy.js';
|
||||
import { RAIL_STOP_OVERLAY_SOURCE_ID } from './stopLabels.js';
|
||||
|
||||
const CHICAGO = { lat: 41.8789, lon: -87.6359 };
|
||||
const WEST = { lat: 41.8789, lon: -87.7 };
|
||||
/** A camera low enough over Chicago for the mesh to be sampled. */
|
||||
const LOW_M = 2_000;
|
||||
const cellKey = ({ lat, lon }) =>
|
||||
`${Math.round(lat * 1000)},${Math.round(lon * 1000)}`;
|
||||
|
||||
/** A floor service: warm cells by 0.001° key, and the warm requests made. */
|
||||
function floorService({ neighbour = null } = {}) {
|
||||
const warm = new Map();
|
||||
const requested = [];
|
||||
const near = { m: neighbour, coarseCalls: 0 };
|
||||
return {
|
||||
warm,
|
||||
requested,
|
||||
near,
|
||||
ground: {
|
||||
GROUND_FLOOR_LIFT_M: 1.5,
|
||||
cachedGroundFloor: (lat, lon) => warm.get(cellKey({ lat, lon })) ?? null,
|
||||
warmGroundFloor(cells) {
|
||||
requested.push(...cells.map(cellKey));
|
||||
},
|
||||
coarseFloorCoord(lat, lon) {
|
||||
near.coarseCalls += 1;
|
||||
return {
|
||||
lat: Math.round(lat * 1000) / 1000,
|
||||
lon: Math.round(lon * 1000) / 1000,
|
||||
};
|
||||
},
|
||||
neighborFloorM: () => near.m,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Photorealistic tiles in place of the globe: their streaming state the test
|
||||
* sets, and the mesh height every probe reads (recorded).
|
||||
*/
|
||||
const photoreal = (app, options) => app.photoreal(options);
|
||||
|
||||
test('a train on a cold cell keeps its last floor, and the cell is warmed', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(CHICAGO), 150);
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { heightFor } = app.parts().rendering;
|
||||
const train = {};
|
||||
assert.equal(heightFor(CHICAGO.lat, CHICAGO.lon, train), 151.5);
|
||||
// West of the city, not sampled yet: still on the Chicago floor.
|
||||
assert.equal(heightFor(WEST.lat, WEST.lon, train), 151.5);
|
||||
assert.deepEqual(floors.requested, []);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.deepEqual(floors.requested, [cellKey(WEST)]);
|
||||
// Every frame reads it again; it is asked for once until the retry time.
|
||||
heightFor(WEST.lat, WEST.lon, train);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(floors.requested.length, 1);
|
||||
t.mock.timers.tick(COLD_CELL_RETRY_MS);
|
||||
heightFor(WEST.lat, WEST.lon, train);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(floors.requested.length, 2);
|
||||
// Once warm, its own floor.
|
||||
floors.warm.set(cellKey(WEST), 160);
|
||||
assert.equal(heightFor(WEST.lat, WEST.lon, train), 161.5);
|
||||
// A point with no floor of its own to keep is on the ellipsoid.
|
||||
assert.equal(heightFor(41.9, -87.8), 0);
|
||||
});
|
||||
|
||||
test('a warm neighbouring cell comes before the last floor', async (t) => {
|
||||
const floors = floorService({ neighbour: 170 });
|
||||
floors.warm.set(cellKey(CHICAGO), 150);
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { heightFor } = app.parts().rendering;
|
||||
const train = {};
|
||||
heightFor(CHICAGO.lat, CHICAGO.lon, train);
|
||||
assert.equal(heightFor(WEST.lat, WEST.lon, train), 171.5);
|
||||
});
|
||||
|
||||
test('a train gliding across a cold cell asks for its coarse cell once', async (t) => {
|
||||
const floors = floorService({ neighbour: 170 });
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { heightFor } = app.parts().rendering;
|
||||
const train = {};
|
||||
floors.near.coarseCalls = 0;
|
||||
// Frames inside one 0.001° cell (centred on WEST), then the next cell.
|
||||
for (let i = 0; i < 20; i += 1)
|
||||
assert.equal(heightFor(WEST.lat, WEST.lon + i * 0.00002, train), 171.5);
|
||||
assert.equal(floors.near.coarseCalls, 1);
|
||||
heightFor(WEST.lat, WEST.lon + 0.001, train);
|
||||
assert.equal(floors.near.coarseCalls, 2);
|
||||
});
|
||||
|
||||
test('from far above, cold cells are not warmed', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: 500_000,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
app.parts().rendering.heightFor(WEST.lat, WEST.lon, {});
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.deepEqual(floors.requested, []);
|
||||
});
|
||||
|
||||
test('a high floor next to the line is a bump, not a jump (grade limit)', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(CHICAGO), 150);
|
||||
// The next cell's floor was read on a roof 30 m above the rails.
|
||||
const NEXT = { lat: CHICAGO.lat, lon: CHICAGO.lon + 0.0013 };
|
||||
floors.warm.set(cellKey(NEXT), 180);
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k1' };
|
||||
assert.equal(displayHeightFor(train, CHICAGO.lat, CHICAGO.lon), 151.5);
|
||||
const drawn = train.drawnHeight;
|
||||
const movedM = 0.0013 * 111_320 * Math.cos((CHICAGO.lat * Math.PI) / 180);
|
||||
const next = displayHeightFor(train, NEXT.lat, NEXT.lon);
|
||||
assert.ok(next > 151.5, 'climbs toward the higher floor');
|
||||
assert.ok(
|
||||
next <= 151.5 + TRACK_MAX_GRADE * movedM + 0.01,
|
||||
`no faster than the grade limit (${next})`,
|
||||
);
|
||||
// The drawn height is kept in place, not rebuilt every frame.
|
||||
assert.equal(train.drawnHeight, drawn);
|
||||
assert.equal(drawn.h, next);
|
||||
});
|
||||
|
||||
test('a real floor replacing the ellipsoid fallback is taken at once', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k2' };
|
||||
assert.equal(displayHeightFor(train, WEST.lat, WEST.lon), 0);
|
||||
floors.warm.set(cellKey(WEST), 160);
|
||||
assert.equal(displayHeightFor(train, WEST.lat, WEST.lon), 161.5);
|
||||
});
|
||||
|
||||
test('a neighbouring floor replacing the ellipsoid is taken at once', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k2n' };
|
||||
assert.equal(displayHeightFor(train, WEST.lat, WEST.lon), 0);
|
||||
// Its own cell is still cold, a neighbour's is warm: no 5% ramp up from
|
||||
// the ellipsoid, 150 m under the mesh.
|
||||
floors.near.m = 170;
|
||||
const step = { lat: WEST.lat, lon: WEST.lon + 0.0002 };
|
||||
assert.equal(displayHeightFor(train, step.lat, step.lon), 171.5);
|
||||
// Between two fallbacks, the grade limit still holds.
|
||||
floors.near.m = 190;
|
||||
const after = displayHeightFor(train, step.lat, step.lon + 0.0002);
|
||||
assert.ok(after > 171.5 && after < 180, `ramps (${after})`);
|
||||
});
|
||||
|
||||
test('on photorealistic tiles the mesh is sampled on the line itself', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(WEST), 150);
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: LOW_M,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { mesh } = photoreal(app);
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k3' };
|
||||
// The exact point on the track, not the floor cell's centre.
|
||||
const ON_TRACK = { lat: WEST.lat + 0.00031, lon: WEST.lon - 0.00027 };
|
||||
assert.equal(displayHeightFor(train, ON_TRACK.lat, ON_TRACK.lon), 151.5);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 1);
|
||||
assert.ok(Math.abs(mesh.probes[0].lat - ON_TRACK.lat) < 1e-9);
|
||||
assert.ok(Math.abs(mesh.probes[0].lon - ON_TRACK.lon) < 1e-9);
|
||||
// The sample is the target now; the drawn height settles toward it.
|
||||
t.mock.timers.tick(20_000);
|
||||
assert.equal(displayHeightFor(train, ON_TRACK.lat, ON_TRACK.lon), 159.5);
|
||||
// Not asked again for the same bucket until the refresh time.
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 1);
|
||||
});
|
||||
|
||||
test('a sample far from the floor under it is a coarse tile and is dropped', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(WEST), 150);
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: LOW_M,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { mesh } = photoreal(app, { height: 400 });
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k4' };
|
||||
displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS + TRACK_SAMPLE_RETRY_MS);
|
||||
assert.equal(mesh.probes.length, 1);
|
||||
assert.equal(displayHeightFor(train, WEST.lat, WEST.lon), 151.5);
|
||||
// A valley floor read under a viaduct, well below the floor: dropped too.
|
||||
// (The next track bucket along, in the same floor cell.)
|
||||
const viaduct = { key: 'k4v' };
|
||||
const NEAR = { lat: WEST.lat, lon: WEST.lon - 0.0004 };
|
||||
mesh.height = 150 - TRACK_PRIOR_BELOW_M - 5;
|
||||
displayHeightFor(viaduct, NEAR.lat, NEAR.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.ok(mesh.probes.some((probe) => Math.abs(probe.lon - NEAR.lon) < 1e-9));
|
||||
t.mock.timers.tick(60_000);
|
||||
assert.equal(displayHeightFor(viaduct, NEAR.lat, NEAR.lon), 151.5);
|
||||
});
|
||||
|
||||
test('from far above, the line is not sampled', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(WEST), 150);
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: 500_000,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { mesh } = photoreal(app, { height: 151 });
|
||||
app.parts().rendering.displayHeightFor({ key: 'k5' }, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 0);
|
||||
});
|
||||
|
||||
test('the line is sampled only from a low camera, once the tiles are loaded', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(WEST), 150);
|
||||
// 20 km up the tiles near the camera are coarse, loaded or not.
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: 20_000,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { tileset, mesh } = photoreal(app);
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k6' };
|
||||
displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 0, 'not from 20 km');
|
||||
// Low enough, but the tiles are still streaming.
|
||||
await app.moveCamera({ altitude: 150 + TRACK_SAMPLE_MAX_CAMERA_M - 100 });
|
||||
tileset.tilesLoaded = false;
|
||||
t.mock.timers.tick(TRACK_SAMPLE_RETRY_MS);
|
||||
displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 0, 'not while streaming');
|
||||
tileset.tilesLoaded = true;
|
||||
t.mock.timers.tick(TRACK_SAMPLE_RETRY_MS);
|
||||
displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.equal(mesh.probes.length, 1);
|
||||
});
|
||||
|
||||
test('a sample read from lower down replaces one from higher up; an old one goes', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(WEST), 150);
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: 4_000,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { mesh } = photoreal(app, { height: 140 });
|
||||
const { displayHeightFor } = app.parts().rendering;
|
||||
const train = { key: 'k7' };
|
||||
/** Read the bucket again, and let the drawn height settle on its target. */
|
||||
const settled = () => {
|
||||
displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
t.mock.timers.tick(60_000);
|
||||
return displayHeightFor(train, WEST.lat, WEST.lon);
|
||||
};
|
||||
// From 4 km, a coarse tile 10 m low: inside the bounds, so kept for now.
|
||||
assert.equal(settled(), 141.5);
|
||||
// From 1 km the tiles are finer: the new reading replaces it.
|
||||
await app.moveCamera({ altitude: 1_000 });
|
||||
mesh.height = 158;
|
||||
t.mock.timers.tick(TRACK_SAMPLE_REFRESH_MS);
|
||||
assert.equal(settled(), 159.5);
|
||||
// Back up at 4.5 km, the coarse reading does not win over it...
|
||||
await app.moveCamera({ altitude: 4_500 });
|
||||
mesh.height = 140;
|
||||
const reads = mesh.probes.length;
|
||||
t.mock.timers.tick(TRACK_SAMPLE_REFRESH_MS);
|
||||
assert.equal(settled(), 159.5);
|
||||
assert.equal(mesh.probes.length, reads + 1, 'it was read again');
|
||||
// ...until the one from lower down is old.
|
||||
t.mock.timers.tick(TRACK_SAMPLE_MAX_AGE_MS);
|
||||
assert.equal(settled(), 141.5);
|
||||
});
|
||||
|
||||
test('disabling the layer drops the cells and samples still queued', async (t) => {
|
||||
const floors = floorService();
|
||||
floors.warm.set(cellKey(CHICAGO), 150);
|
||||
const app = harness(t, {
|
||||
at: CHICAGO,
|
||||
altitude: LOW_M,
|
||||
ground: floors.ground,
|
||||
});
|
||||
await app.enable();
|
||||
const { mesh } = photoreal(app);
|
||||
const { heightFor, displayHeightFor } = app.parts().rendering;
|
||||
heightFor(WEST.lat, WEST.lon, {});
|
||||
displayHeightFor({ key: 'k8' }, CHICAGO.lat, CHICAGO.lon);
|
||||
app.layer.disable(app.viewer);
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS * 3);
|
||||
assert.deepEqual(floors.requested, []);
|
||||
assert.equal(mesh.probes.length, 0);
|
||||
// Enabled again, the cell is asked for at once, not after a retry time.
|
||||
await app.enable();
|
||||
heightFor(WEST.lat, WEST.lon, {});
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.deepEqual(floors.requested, [cellKey(WEST)]);
|
||||
});
|
||||
|
||||
test('trains far from the camera do not warm floor cells', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
const { heightFor } = app.parts().rendering;
|
||||
// Well past FLOOR_WARM_MAX_DIST_KM from the camera over Chicago.
|
||||
const FAR = {
|
||||
lat: CHICAGO.lat,
|
||||
lon: CHICAGO.lon + (FLOOR_WARM_MAX_DIST_KM + 20) / 83,
|
||||
};
|
||||
heightFor(FAR.lat, FAR.lon, {});
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
assert.deepEqual(floors.requested, []);
|
||||
});
|
||||
|
||||
/**
|
||||
* Cold cells for hundreds of trains near the camera, `rounds` flushes of
|
||||
* them; the cells the floor service was asked for.
|
||||
*/
|
||||
function crowd(t, app, floors, rounds) {
|
||||
const { heightFor } = app.parts().rendering;
|
||||
let asked = 0;
|
||||
for (let round = 0; round < rounds; round += 1) {
|
||||
for (let i = 0; i < 100; i += 1) {
|
||||
const n = round * 100 + i;
|
||||
heightFor(
|
||||
CHICAGO.lat + (n % 60) * 0.002,
|
||||
CHICAGO.lon + Math.floor(n / 60) * 0.002,
|
||||
{},
|
||||
);
|
||||
}
|
||||
const before = floors.requested.length;
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
const flushed = floors.requested.length - before;
|
||||
assert.ok(flushed <= COLD_CELLS_PER_FLUSH, `one flush ${flushed}`);
|
||||
asked += flushed;
|
||||
}
|
||||
return asked;
|
||||
}
|
||||
|
||||
test('floor warming stays within the shared terrain budget', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
// The budget starts with its burst and refills at FLOOR_CELLS_PER_MINUTE:
|
||||
// 40 flushes (40 s) may spend at most the burst plus 40 s of refill.
|
||||
const asked = crowd(t, app, floors, 40);
|
||||
const secondsElapsed = (40 * COLD_CELL_FLUSH_MS) / 1000;
|
||||
assert.ok(
|
||||
asked <=
|
||||
FLOOR_CELLS_BURST + (FLOOR_CELLS_PER_MINUTE * secondsElapsed) / 60 + 1,
|
||||
`in ${secondsElapsed} s ${asked}`,
|
||||
);
|
||||
assert.ok(asked > 0);
|
||||
});
|
||||
|
||||
test('a minute after an idle spell spends no more than a minute of budget plus the burst', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, { at: CHICAGO, ground: floors.ground });
|
||||
await app.enable();
|
||||
// Idle long enough for any bucket to fill to the brim.
|
||||
t.mock.timers.tick(10 * 60_000);
|
||||
const asked = crowd(t, app, floors, 60);
|
||||
assert.ok(
|
||||
asked <= FLOOR_CELLS_PER_MINUTE + FLOOR_CELLS_BURST,
|
||||
`in a minute ${asked}`,
|
||||
);
|
||||
// About 24 of the 90 terrain requests a minute, not 38.
|
||||
assert.ok(Math.ceil(asked / 64) <= 24, `${Math.ceil(asked / 64)} requests`);
|
||||
// And the refill is spent: the crowd is not starved.
|
||||
assert.ok(asked >= FLOOR_CELLS_PER_MINUTE, `in a minute ${asked}`);
|
||||
});
|
||||
|
||||
/** A trip through Boston, its terminus 120 km away (Portland, Maine). */
|
||||
const STOPS = [
|
||||
{ stopId: 'A', name: 'South Station', lat: 42.3523, lon: -71.0552 },
|
||||
{ stopId: 'B', name: 'North Station', lat: 42.3656, lon: -71.0613 },
|
||||
{ stopId: 'C', name: 'Woburn', lat: 42.5168, lon: -71.1442 },
|
||||
{ stopId: 'D', name: 'Portland', lat: 43.6532, lon: -70.3122 },
|
||||
].map((stop, i) => ({
|
||||
...stop,
|
||||
state: i === 0 ? 'passed' : i === 1 ? 'next' : 'upcoming',
|
||||
relative: i === 0 ? 'T+3' : `T−${i * 10}`,
|
||||
expectedArrival: '14:32',
|
||||
}));
|
||||
|
||||
const heightOf = (position) => toLonLatH(position).height;
|
||||
|
||||
test('stops placed before their cells were warm move up onto the floor', async (t) => {
|
||||
const floors = floorService();
|
||||
const app = harness(t, {
|
||||
at: BOSTON,
|
||||
altitude: LOW_M,
|
||||
ground: floors.ground,
|
||||
stops: { stopsFor: () => ({ stops: STOPS }) },
|
||||
});
|
||||
app.feeds.set('mbta-rail', () => [train('T1', BOSTON.lat, BOSTON.lon)]);
|
||||
await app.enable();
|
||||
const key = railTrainKey('mbta-rail', 'T1');
|
||||
app.parts().selection.selectTrain(key);
|
||||
const dots = app.drawn('points', ':stops');
|
||||
const dotHeights = () =>
|
||||
[...dots.items.values()].map((dot) => heightOf(dot.pos));
|
||||
const labelHeights = () =>
|
||||
app.overlayEntries
|
||||
.get(RAIL_STOP_OVERLAY_SOURCE_ID)
|
||||
.map((entry) => heightOf(entry.position));
|
||||
assert.equal(dots.items.size, STOPS.length);
|
||||
// Every stop's cell is cold: on the ellipsoid for now.
|
||||
for (const h of [...dotHeights(), ...labelHeights()])
|
||||
assert.ok(Math.abs(h) < 0.01, `on the ellipsoid (${h})`);
|
||||
// Their cells are warmed, the terminus too though it is 120 km off.
|
||||
t.mock.timers.tick(COLD_CELL_FLUSH_MS);
|
||||
for (const stop of STOPS)
|
||||
assert.ok(floors.requested.includes(cellKey(stop)), stop.name);
|
||||
// Once warm, the next refresh stands them on the floor.
|
||||
for (const stop of STOPS) floors.warm.set(cellKey(stop), 20);
|
||||
t.mock.timers.tick(STOP_REFRESH_MS);
|
||||
assert.equal(dots.items.size, STOPS.length);
|
||||
for (const h of [...dotHeights(), ...labelHeights()])
|
||||
assert.ok(Math.abs(h - 21.5) < 0.01, `on the floor (${h})`);
|
||||
// Placed on a real floor, a stop is not read again.
|
||||
floors.warm.clear();
|
||||
t.mock.timers.tick(STOP_REFRESH_MS * 3);
|
||||
for (const h of dotHeights()) assert.ok(Math.abs(h - 21.5) < 0.01);
|
||||
});
|
||||
@@ -0,0 +1,203 @@
|
||||
import { createHistoryBudget } from '../../data/contactPlayback.js';
|
||||
import { createRailSource } from './source.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createSelection } from './selection.js';
|
||||
import { createFollow } from './follow.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createViewport } from './viewport.js';
|
||||
import { createControls } from './controls.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createRouteDisplay } from './routeDisplay.js';
|
||||
import { createRailSchedules } from './schedules.js';
|
||||
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
|
||||
import { DEFAULT_RAIL_CATEGORY_VISIBILITY, RAIL_POLL_MS } from './policy.js';
|
||||
|
||||
/** One Rail layer's mutable scene state; nothing is module-global. */
|
||||
function createState({ services }) {
|
||||
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
|
||||
services.overlays;
|
||||
return {
|
||||
_overlayHost: Object.freeze({
|
||||
setEntries: setOverlayEntries,
|
||||
setVisible: setOverlaySourceVisible,
|
||||
clearSource: clearOverlaySource,
|
||||
}),
|
||||
_historyBudget: createHistoryBudget(),
|
||||
/** The viewer the layer draws on, or null. */
|
||||
_viewer: null,
|
||||
/** The train icons' draw set, or null. */
|
||||
_icons: null,
|
||||
_enabled: false,
|
||||
_generation: 0,
|
||||
_cameraChangedAttached: false,
|
||||
/** Removes the camera port listener; null when not listening. */
|
||||
_cameraChangedOff: null,
|
||||
/** Removes the one-shot look after the camera listener's first tick. */
|
||||
_cameraFirstTickOff: null,
|
||||
_cameraDebounceTimer: null,
|
||||
_altitudeGateOpen: false,
|
||||
_preRenderRemove: null,
|
||||
_renderHeld: false,
|
||||
/** Unsubscribes the train-selection click. */
|
||||
_clickSubscription: null,
|
||||
/** Trains mid-glide; the frame pass walks only these. @type {Set<object>} */
|
||||
_moving: new Set(),
|
||||
/** feedId → registry entry currently polled. */
|
||||
_activeFeeds: new Map(),
|
||||
_feedStatus: new Map(),
|
||||
_inFlight: new Map(),
|
||||
/** train key → runtime entry. */
|
||||
_trains: new Map(),
|
||||
/**
|
||||
* feedId → path pack slot `{status, pack, retryAt, failures}`. Kept
|
||||
* across disable/enable, and released with the feed's network and
|
||||
* schedule pack once the feed is out of use FEED_RELEASE_AFTER_MS
|
||||
* (routeDisplay.js releaseIdleFeeds).
|
||||
*/
|
||||
_pathPacks: new Map(),
|
||||
/**
|
||||
* The server's feed catalog (GET /api/rail/feeds), which lists a feed
|
||||
* that reads its routes from a schedule pack only once that pack is
|
||||
* built; null until it loads. Until then only the bundled feeds that
|
||||
* need no pack are used, and a catalog that fails is asked for again
|
||||
* (viewport.js).
|
||||
*/
|
||||
_catalog: null,
|
||||
/** The catalog request in flight: `{controller}`. */
|
||||
_catalogRequest: null,
|
||||
/** Failed catalog requests in a row, and the timer of the next try. */
|
||||
_catalogFailures: 0,
|
||||
_catalogRetryTimer: null,
|
||||
/** feedId → faint route network built from that feed's path pack. */
|
||||
_networks: new Map(),
|
||||
/** Network opacity from camera altitude, 0..1. */
|
||||
_networkFade: 0,
|
||||
/** The selected train's line, split where the train is. */
|
||||
_route: null,
|
||||
/** The selected trip's stops and headsign from the stops provider. */
|
||||
_trip: null,
|
||||
_stopsSignature: '',
|
||||
_stopLabelsSignature: '',
|
||||
/**
|
||||
* Stop → `{lat, lon, h, q, position}` for the selected trip, kept per
|
||||
* selection; one on a fallback height (q 0-1) is read again each refresh.
|
||||
*/
|
||||
_stopAnchors: new Map(),
|
||||
_categories: { ...DEFAULT_RAIL_CATEGORY_VISIBILITY },
|
||||
_selectedKey: null,
|
||||
_selectedCardAt: 0,
|
||||
_selectedCardText: null,
|
||||
/** The camera's follow of the selected train (follow.js), or null. */
|
||||
_follow: null,
|
||||
/** A feed polled only for the selected train (viewport.js), or null. */
|
||||
_heldFeedId: null,
|
||||
_revision: 0,
|
||||
_controlsListener: null,
|
||||
_dataManager: null,
|
||||
_lastUpdate: null,
|
||||
_error: null,
|
||||
/** Whether the train cap (MAX_TRAINS_TOTAL) was reported once. */
|
||||
_capWarned: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Construct one Rail layer with its own scene state and supplied services.
|
||||
*
|
||||
* Trains come from the `/api/rail` proxy (src/sources/railService.js), already
|
||||
* filtered to trains and tagged with a category. Every train drawn is where
|
||||
* its operator last reported it (GPS or station reports); none is placed or
|
||||
* moved from a timetable. Motion between reports is the Transit layer's
|
||||
* delayed playback, so a train glides at 1x behind real time along its line
|
||||
* instead of jumping between reports.
|
||||
*
|
||||
* Each layer owns a schedule tier (schedules.js): feeds' optional schedule
|
||||
* packs and trip updates, read through the same source for the selected
|
||||
* train's stops, headsign and delays. It is the default stops provider:
|
||||
*
|
||||
* stops.stopsFor({feedId, tripId, routeId, record}, nowMs)
|
||||
* → {stops: RailTripStop[], headsign?: string} | null
|
||||
* stops.onSelect?(train | null)
|
||||
*
|
||||
* `stopsFor` is called about once a second while a train is selected,
|
||||
* synchronously; it returns null while it has nothing (yet) and loads what it
|
||||
* needs on its own. RailTripStop is described in stopLabels.js. Pass
|
||||
* `stops: null` to draw the selected line without stops.
|
||||
*
|
||||
* A selected train takes the camera through the optional `services.camera`
|
||||
* (follow.js): a moving train is followed, any other flown to once.
|
||||
*
|
||||
* @param {{services: object, source?: object,
|
||||
* stops?: {stopsFor: Function, onSelect?: Function}|null}} options
|
||||
* @returns {object} The data-layer module the manager registers.
|
||||
*/
|
||||
export function createRailLayer({
|
||||
services,
|
||||
source = createRailSource(),
|
||||
stops,
|
||||
}) {
|
||||
if (
|
||||
!services?.overlays ||
|
||||
!services?.render ||
|
||||
!services?.sprites ||
|
||||
!services?.ground
|
||||
) {
|
||||
throw new TypeError(
|
||||
'A rail layer needs overlay, render, sprite and ground services',
|
||||
);
|
||||
}
|
||||
if (typeof source?.requestSnapshot !== 'function')
|
||||
throw new TypeError('A rail source needs a snapshot operation');
|
||||
if (
|
||||
stops !== undefined &&
|
||||
stops !== null &&
|
||||
typeof stops?.stopsFor !== 'function'
|
||||
)
|
||||
throw new TypeError('A rail stops provider needs a stopsFor operation');
|
||||
const state = createState({ services });
|
||||
const parts = {};
|
||||
const timetable = createRailSchedules({
|
||||
source,
|
||||
// The server's catalog says which feeds it can read trip updates for.
|
||||
hasTripUpdates: (feedId) => {
|
||||
const listed = state._catalog?.find((feed) => feed.id === feedId);
|
||||
if (listed) return listed.tripUpdates === true;
|
||||
return typeof getRegisteredRailFeed(feedId)?.tripUpdatesUrl === 'string';
|
||||
},
|
||||
pathPackFor: (feedId) => state._pathPacks.get(feedId)?.pack || null,
|
||||
});
|
||||
const context = {
|
||||
state,
|
||||
services,
|
||||
parts,
|
||||
source,
|
||||
timetable,
|
||||
stops: stops === undefined ? timetable : stops,
|
||||
};
|
||||
parts.rendering = createRendering(context);
|
||||
parts.routes = createRouteDisplay(context);
|
||||
parts.selection = createSelection(context);
|
||||
parts.follow = createFollow(context);
|
||||
parts.controls = createControls(context);
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.viewport = createViewport(context);
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
|
||||
return Object.assign(
|
||||
{ updateInterval: RAIL_POLL_MS },
|
||||
parts.lifecycle.methods,
|
||||
parts.controls.methods,
|
||||
{
|
||||
/** Test seams: this instance's own state and parts. */
|
||||
_railStateForTest: () => state,
|
||||
_railPartsForTest: () => parts,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
export {
|
||||
RAIL_CATEGORY_COLORS,
|
||||
RAIL_POLL_MS,
|
||||
buildRailSelectionCopy,
|
||||
railTrainKey,
|
||||
} from './policy.js';
|
||||
@@ -0,0 +1,527 @@
|
||||
import {
|
||||
FIX_FLAGS,
|
||||
createLagReservoir,
|
||||
destroyTrack,
|
||||
readFix,
|
||||
} from '../../data/contactPlayback.js';
|
||||
import { createRailPathPack } from '../../data/railPaths.js';
|
||||
import {
|
||||
initializePlayback,
|
||||
recordFix,
|
||||
syncPlayback,
|
||||
updatePlayback,
|
||||
} from '../transit/movement.js';
|
||||
import {
|
||||
FEED_EVICT_AFTER_MS,
|
||||
FEED_STALE_AFTER_MS,
|
||||
FUTURE_STAMP_TOLERANCE_MS,
|
||||
MAX_TRAINS_TOTAL,
|
||||
MISSED_POLLS_TO_DROP,
|
||||
isLiveRailPositionSource,
|
||||
isStaleTrainFix,
|
||||
playbackModeFor,
|
||||
railTrainKey,
|
||||
trainReportTimeMs,
|
||||
} from './policy.js';
|
||||
import { bindTrainPath, followFix, rebindTrainPath } from './pathBinding.js';
|
||||
import { scheduleRetryDelayMs } from './schedules.js';
|
||||
import { createDuplicateFilter } from './dedupe.js';
|
||||
|
||||
/**
|
||||
* Fetching rail feeds through the proxy and turning snapshots into trains.
|
||||
* The aging rules are the Transit layer's: a train is drawn from its own
|
||||
* report time, a feed is judged by when its operator last answered, and both
|
||||
* a quiet train and a quiet feed end in removal rather than a frozen marker.
|
||||
*
|
||||
* Only live positions are drawn (isLiveRailPositionSource). A feed whose
|
||||
* positions fail is shown as unavailable: its trains are never placed from
|
||||
* its timetable, and those already drawn age out as any quiet train does.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createIngestion({ state, services, parts, source }) {
|
||||
const { governorRequestRender } = services.render;
|
||||
const { registerDynamicCredit, railFeedCredit } = services.credits;
|
||||
// One physical train in several loaded feeds is drawn once (dedupe.js).
|
||||
const duplicates = createDuplicateFilter({ state, parts });
|
||||
|
||||
function feedStatus(feedId) {
|
||||
let status = state._feedStatus.get(feedId);
|
||||
if (!status) {
|
||||
status = {
|
||||
count: 0,
|
||||
lastUpdate: null,
|
||||
upstreamAt: null,
|
||||
error: null,
|
||||
retryInSec: null,
|
||||
stale: false,
|
||||
pollSeq: 0,
|
||||
loading: false,
|
||||
lag: null,
|
||||
/** New trains its last poll listed that MAX_TRAINS_TOTAL left out. */
|
||||
capped: 0,
|
||||
};
|
||||
state._feedStatus.set(feedId, status);
|
||||
}
|
||||
return status;
|
||||
}
|
||||
|
||||
function removeTrain(key) {
|
||||
const entry = state._trains.get(key);
|
||||
if (!entry) return;
|
||||
if (state._selectedKey === key) parts.selection.clearSelection();
|
||||
parts.rendering.removeMarker(entry);
|
||||
entry.marker = null;
|
||||
state._moving.delete(entry);
|
||||
parts.rendering.cancelWake(entry);
|
||||
destroyTrack(entry.track);
|
||||
state._trains.delete(key);
|
||||
state._revision += 1;
|
||||
// A copy it hid may now be the one to draw.
|
||||
duplicates.scheduleRefresh();
|
||||
}
|
||||
|
||||
/**
|
||||
* Remove a feed's trains, except `keepKey` when given (the selected train,
|
||||
* whose feed is held for it alone: viewport.js).
|
||||
* @param {string} feedId
|
||||
* @param {string|null} [keepKey]
|
||||
*/
|
||||
function removeFeedTrains(feedId, keepKey = null) {
|
||||
for (const [key, entry] of state._trains) {
|
||||
if (entry.feedId === feedId && key !== keepKey) removeTrain(key);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop trains whose report aged out and feeds whose operator went quiet.
|
||||
* @param {number} nowMs
|
||||
* @returns {number} Trains removed.
|
||||
*/
|
||||
function sweepAgedTrains(nowMs) {
|
||||
let removed = 0;
|
||||
const deadFeeds = new Set();
|
||||
for (const [feedId, status] of state._feedStatus) {
|
||||
if (
|
||||
Number.isFinite(status.upstreamAt) &&
|
||||
nowMs - status.upstreamAt > FEED_EVICT_AFTER_MS
|
||||
)
|
||||
deadFeeds.add(feedId);
|
||||
}
|
||||
for (const [key, entry] of state._trains) {
|
||||
if (
|
||||
deadFeeds.has(entry.feedId) ||
|
||||
isStaleTrainFix(entry.record, nowMs, entry.fetchedAt)
|
||||
) {
|
||||
removeTrain(key);
|
||||
removed += 1;
|
||||
}
|
||||
}
|
||||
for (const feedId of deadFeeds) {
|
||||
const status = state._feedStatus.get(feedId);
|
||||
if (status) {
|
||||
status.count = 0;
|
||||
status.stale = true;
|
||||
}
|
||||
}
|
||||
if (removed > 0) {
|
||||
parts.rendering.syncRenderHold();
|
||||
governorRequestRender('rail-evict');
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
}
|
||||
return removed;
|
||||
}
|
||||
|
||||
/**
|
||||
* Fetch a feed's path pack once. A 404 means the feed has no paths and its
|
||||
* trains keep straight-line motion; any other failure (a 503 from a pack
|
||||
* the server cannot read now, say) is retried on the schedule packs'
|
||||
* stepped delay, 30 s doubling to ten minutes (scheduleRetryDelayMs).
|
||||
* @param {object} feed Registry entry.
|
||||
*/
|
||||
function ensurePaths(feed) {
|
||||
const known = state._pathPacks.get(feed.id);
|
||||
if (known && !(known.status === 'none' && Date.now() >= known.retryAt))
|
||||
return;
|
||||
if (typeof source.requestPaths !== 'function') {
|
||||
state._pathPacks.set(feed.id, {
|
||||
status: 'none',
|
||||
pack: null,
|
||||
retryAt: Infinity,
|
||||
});
|
||||
return;
|
||||
}
|
||||
const slot = {
|
||||
status: 'loading',
|
||||
pack: null,
|
||||
retryAt: Infinity,
|
||||
/** Failed loads in a row. */
|
||||
failures: known?.failures ?? 0,
|
||||
};
|
||||
state._pathPacks.set(feed.id, slot);
|
||||
void (async () => {
|
||||
try {
|
||||
const response = await source.requestPaths(feed.id);
|
||||
if (!response.ok) {
|
||||
const error = new Error(`rail paths HTTP ${response.status}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
const raw = await response.json();
|
||||
const pack = createRailPathPack(raw);
|
||||
if (pack.feedId !== feed.id)
|
||||
throw new Error('rail path pack is for another feed');
|
||||
if (state._pathPacks.get(feed.id) !== slot) return;
|
||||
slot.pack = pack;
|
||||
slot.status = 'ready';
|
||||
bindFeedTrains(feed.id);
|
||||
// The faint network is drawn from the same pack, built once here.
|
||||
parts.routes.buildNetwork(feed.id, raw);
|
||||
} catch (error) {
|
||||
slot.status = 'none';
|
||||
slot.failures += 1;
|
||||
slot.retryAt =
|
||||
error?.status === 404
|
||||
? Infinity
|
||||
: Date.now() + scheduleRetryDelayMs(slot.failures);
|
||||
if (error?.status !== 404)
|
||||
console.warn(
|
||||
`[Data:Rail] ${feed.id} paths unavailable:`,
|
||||
error?.message || error,
|
||||
);
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/**
|
||||
* Keep a train on its railway line: bind it when its trip or route changes,
|
||||
* follow each new report, and move it to another of its route's shapes (or
|
||||
* back to straight lines) when a report lands off the bound one.
|
||||
*/
|
||||
function followPath(entry, record, fix) {
|
||||
const pack = state._pathPacks.get(entry.feedId)?.pack;
|
||||
if (!pack) return;
|
||||
const ids = { tripId: record.tripId || '', routeId: record.routeId || '' };
|
||||
const key = `${ids.tripId}\n${ids.routeId}`;
|
||||
if (entry.pathKey !== key) {
|
||||
entry.pathKey = key;
|
||||
entry.path = bindTrainPath(pack, ids, fix);
|
||||
return;
|
||||
}
|
||||
if (!entry.path || followFix(entry.path, fix)) return;
|
||||
entry.path = rebindTrainPath(pack, ids, entry.path, fix);
|
||||
}
|
||||
|
||||
/** Bind the trains a feed already shows once its pack arrives. */
|
||||
function bindFeedTrains(feedId) {
|
||||
const newest = {};
|
||||
for (const entry of state._trains.values()) {
|
||||
if (entry.feedId !== feedId || entry.pathKey !== undefined) continue;
|
||||
if (!entry.track?.count) continue;
|
||||
readFix(entry.track, entry.track.count - 1, newest);
|
||||
followPath(entry, entry.record, newest);
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
}
|
||||
governorRequestRender('rail-paths');
|
||||
}
|
||||
|
||||
/** A playback fix for one record, with the time it was really reported. */
|
||||
function fixFor(record, fetchedAt) {
|
||||
const stamped = trainReportTimeMs(record, fetchedAt);
|
||||
const reportAt =
|
||||
stamped > fetchedAt + FUTURE_STAMP_TOLERANCE_MS ? fetchedAt : stamped;
|
||||
return {
|
||||
t: reportAt,
|
||||
lat: record.lat,
|
||||
lon: record.lon,
|
||||
bearingDeg: Number.isFinite(record.bearing) ? record.bearing : NaN,
|
||||
flags:
|
||||
stamped !== reportAt
|
||||
? FIX_FLAGS.RECEIPT_TIME
|
||||
: record.timestampSource === 'vehicle'
|
||||
? FIX_FLAGS.VEHICLE_TIME
|
||||
: record.timestampSource === 'header'
|
||||
? FIX_FLAGS.FEED_TIME
|
||||
: FIX_FLAGS.RECEIPT_TIME,
|
||||
};
|
||||
}
|
||||
|
||||
/** Record a new report for a train already drawn. */
|
||||
function advanceTrain(entry, record, fix, observation) {
|
||||
const heard = recordFix(entry, fix, observation);
|
||||
if (!heard.accepted) return heard;
|
||||
followPath(entry, record, fix);
|
||||
if (entry.category !== record.category || entry.railMode !== record.mode) {
|
||||
entry.category = record.category;
|
||||
entry.railMode = record.mode;
|
||||
entry.mode = playbackModeFor(record.mode);
|
||||
parts.rendering.paint(entry);
|
||||
}
|
||||
updatePlayback(entry, observation.wallNowMs, observation.monoNowMs);
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
return heard;
|
||||
}
|
||||
|
||||
/** Create and draw a train the layer has not seen before. */
|
||||
function addTrain(key, feed, record, fix, observation, status) {
|
||||
const entry = {
|
||||
key,
|
||||
feedId: feed.id,
|
||||
marker: null,
|
||||
category: record.category,
|
||||
railMode: record.mode,
|
||||
mode: playbackModeFor(record.mode),
|
||||
// A route the classifier named is a fact about the train, so its
|
||||
// speed ceiling applies; the movement module reads this flag.
|
||||
modeInferred: false,
|
||||
courseDeg: Number.isFinite(record.bearing) ? record.bearing : null,
|
||||
courseAt: observation.wallNowMs,
|
||||
courseEvalAt: observation.monoNowMs,
|
||||
record,
|
||||
fetchedAt: observation.fetchedAt,
|
||||
pollSeq: status.pollSeq,
|
||||
/** Binding to a railway line (pathBinding.js), null for straight lines. */
|
||||
path: null,
|
||||
/** Trip and route the binding was made for; undefined until tried. */
|
||||
pathKey: undefined,
|
||||
};
|
||||
initializePlayback(entry, state._historyBudget, status.lag);
|
||||
const first = recordFix(entry, fix, observation);
|
||||
if (!first.accepted) {
|
||||
destroyTrack(entry.track);
|
||||
return null;
|
||||
}
|
||||
followPath(entry, record, fix);
|
||||
syncPlayback(entry, observation.wallNowMs, observation.monoNowMs);
|
||||
entry.marker = parts.rendering.addMarker(entry);
|
||||
state._trains.set(key, entry);
|
||||
parts.rendering.schedulePlayback(entry);
|
||||
return entry;
|
||||
}
|
||||
|
||||
function applySnapshot(feed, snapshot, { stale, contactedAt = null }) {
|
||||
const now = Date.now();
|
||||
const fetchedAt = Math.min(
|
||||
Number.isFinite(snapshot?.fetchedAt) ? snapshot.fetchedAt : now,
|
||||
now,
|
||||
);
|
||||
const contacted = Math.min(
|
||||
Number.isFinite(contactedAt) ? contactedAt : fetchedAt,
|
||||
now,
|
||||
);
|
||||
const status = feedStatus(feed.id);
|
||||
status.upstreamAt = Math.max(contacted, fetchedAt);
|
||||
const upstreamAgeMs = now - status.upstreamAt;
|
||||
status.loading = false;
|
||||
status.error = null;
|
||||
status.retryInSec = null;
|
||||
status.stale = stale === true || upstreamAgeMs > FEED_STALE_AFTER_MS;
|
||||
if (upstreamAgeMs > FEED_EVICT_AFTER_MS) {
|
||||
removeFeedTrains(feed.id);
|
||||
status.count = 0;
|
||||
parts.rendering.syncRenderHold();
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
return;
|
||||
}
|
||||
status.pollSeq += 1;
|
||||
if (!status.lag) status.lag = createLagReservoir();
|
||||
const replayed = status.snapshotAt === fetchedAt || stale === true;
|
||||
status.snapshotAt = fetchedAt;
|
||||
const monoNow = performance.now();
|
||||
// A feed held only for the selected train (viewport.js) carries it alone,
|
||||
// or a train its operator now lists on the same trip.
|
||||
const only =
|
||||
state._heldFeedId === feed.id
|
||||
? state._trains.get(state._selectedKey)
|
||||
: null;
|
||||
let seen = 0;
|
||||
// The cap counts the trains drawn: a copy another feed draws better
|
||||
// (dedupe.js) is hidden and does not count.
|
||||
let held = 0;
|
||||
for (const entry of state._trains.values())
|
||||
if (entry.duplicate !== true) held += 1;
|
||||
let capped = 0;
|
||||
for (const record of snapshot.trains || []) {
|
||||
// Only a reported position is drawn, never one from a timetable.
|
||||
if (!isLiveRailPositionSource(record?.positionSource)) continue;
|
||||
if (isStaleTrainFix(record, now, fetchedAt)) continue;
|
||||
const key = railTrainKey(feed.id, record.id);
|
||||
if (
|
||||
only &&
|
||||
key !== only.key &&
|
||||
!(only.record?.tripId && record.tripId === only.record.tripId)
|
||||
)
|
||||
continue;
|
||||
const fix = fixFor(record, fetchedAt);
|
||||
const observation = {
|
||||
receivedAt: now,
|
||||
monoNowMs: monoNow,
|
||||
wallNowMs: now,
|
||||
fetchedAt,
|
||||
replayed,
|
||||
modeInferred: false,
|
||||
context: {
|
||||
trip: record.tripId || '',
|
||||
route: record.routeId || '',
|
||||
mode: playbackModeFor(record.mode),
|
||||
},
|
||||
};
|
||||
let entry = state._trains.get(key);
|
||||
if (entry) {
|
||||
const heard = advanceTrain(entry, record, fix, observation);
|
||||
entry.pollSeq = status.pollSeq;
|
||||
seen += 1;
|
||||
if (!heard.accepted) continue;
|
||||
} else {
|
||||
if (held >= MAX_TRAINS_TOTAL) {
|
||||
capped += 1;
|
||||
continue;
|
||||
}
|
||||
entry = addTrain(key, feed, record, fix, observation, status);
|
||||
if (!entry) continue;
|
||||
held += 1;
|
||||
seen += 1;
|
||||
}
|
||||
entry.record = record;
|
||||
entry.fetchedAt = fetchedAt;
|
||||
}
|
||||
// Said in the layer's stats as a partial snapshot (controls.js).
|
||||
status.capped = capped;
|
||||
if (capped > 0 && !state._capWarned) {
|
||||
state._capWarned = true;
|
||||
console.warn(
|
||||
`[Data:Rail] train cap ${MAX_TRAINS_TOTAL} reached; ${capped} trains of ${feed.id} are not drawn`,
|
||||
);
|
||||
}
|
||||
for (const [key, entry] of state._trains) {
|
||||
if (
|
||||
entry.feedId === feed.id &&
|
||||
status.pollSeq - entry.pollSeq >= MISSED_POLLS_TO_DROP
|
||||
)
|
||||
removeTrain(key);
|
||||
}
|
||||
sweepAgedTrains(now);
|
||||
duplicates.scheduleRefresh();
|
||||
status.count = seen;
|
||||
status.lastUpdate = fetchedAt;
|
||||
state._lastUpdate = Math.max(state._lastUpdate || 0, fetchedAt);
|
||||
state._error = null;
|
||||
if (state._viewer)
|
||||
registerDynamicCredit(state._viewer, railFeedCredit(feed));
|
||||
if (state._trains.get(state._selectedKey)?.feedId === feed.id)
|
||||
parts.selection.refreshSelectedCard(true);
|
||||
parts.rendering.warmFloors(feed.id);
|
||||
state._revision += 1;
|
||||
parts.rendering.syncRenderHold();
|
||||
governorRequestRender('rail-poll');
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
parts.controls.notify();
|
||||
}
|
||||
|
||||
/**
|
||||
* A feed whose live positions failed (or that its server has none for):
|
||||
* its row says it is unavailable. Nothing takes the place of its trains;
|
||||
* those already drawn go as their reports age (sweepAgedTrains).
|
||||
* @param {object} feed
|
||||
* @param {object} status
|
||||
* @param {{retryInSec?: number}|null} [error]
|
||||
*/
|
||||
function markUnavailable(feed, status, error = null) {
|
||||
// i18n-ignore: English data, translated on display (ui/statusText.js)
|
||||
status.error = `${feed.name} feed unavailable`;
|
||||
status.retryInSec = Number.isFinite(error?.retryInSec)
|
||||
? error.retryInSec
|
||||
: null;
|
||||
status.loading = false;
|
||||
state._error = status.error;
|
||||
sweepAgedTrains(Date.now());
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll one feed. A request already in flight is reused rather than aborted,
|
||||
* so enable() and the manager's first update() share one request.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {number} generation Enable generation the poll belongs to.
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
function pollFeed(feed, generation) {
|
||||
if (!state._enabled || generation !== state._generation)
|
||||
return Promise.resolve();
|
||||
ensurePaths(feed);
|
||||
const status = feedStatus(feed.id);
|
||||
const existing = state._inFlight.get(feed.id);
|
||||
if (existing) return existing.promise;
|
||||
const controller = new AbortController();
|
||||
status.loading = status.count === 0;
|
||||
const promise = (async () => {
|
||||
try {
|
||||
const response = await source.requestSnapshot(feed.id, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) {
|
||||
const detail = await response.json().catch(() => null);
|
||||
const error = new Error(`rail proxy HTTP ${response.status}`);
|
||||
error.status = response.status;
|
||||
if (Number.isFinite(detail?.retryInSec))
|
||||
error.retryInSec = detail.retryInSec;
|
||||
throw error;
|
||||
}
|
||||
const snapshot = await response.json();
|
||||
if (
|
||||
!state._enabled ||
|
||||
generation !== state._generation ||
|
||||
!state._activeFeeds.has(feed.id)
|
||||
)
|
||||
return;
|
||||
// An answer whose positions are not live (anything but GPS or
|
||||
// station reports) has no live data for this feed: none of its
|
||||
// trains are drawn, and the feed shows unavailable.
|
||||
if (!isLiveRailPositionSource(snapshot?.positions)) {
|
||||
console.warn(
|
||||
`[Data:Rail] ${feed.id} has no live positions on this server`,
|
||||
);
|
||||
markUnavailable(feed, status);
|
||||
return;
|
||||
}
|
||||
const contact = Number.parseInt(
|
||||
response.headers.get('x-rail-contact') || '',
|
||||
10,
|
||||
);
|
||||
applySnapshot(feed, snapshot, {
|
||||
stale: response.headers.get('x-gev-cache') === 'STALE-ERROR',
|
||||
contactedAt: Number.isFinite(contact) ? contact : null,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') return;
|
||||
if (generation !== state._generation) return;
|
||||
console.warn(
|
||||
`[Data:Rail] ${feed.id} poll failed:`,
|
||||
error?.message || error,
|
||||
);
|
||||
markUnavailable(feed, status, error);
|
||||
} finally {
|
||||
if (state._inFlight.get(feed.id)?.controller === controller)
|
||||
state._inFlight.delete(feed.id);
|
||||
}
|
||||
})();
|
||||
state._inFlight.set(feed.id, { controller, promise });
|
||||
return promise;
|
||||
}
|
||||
|
||||
function abortAllInFlight() {
|
||||
for (const { controller } of state._inFlight.values()) controller.abort();
|
||||
state._inFlight.clear();
|
||||
}
|
||||
|
||||
return {
|
||||
feedStatus,
|
||||
removeTrain,
|
||||
removeFeedTrains,
|
||||
sweepAgedTrains,
|
||||
applySnapshot,
|
||||
pollFeed,
|
||||
abortAllInFlight,
|
||||
duplicates,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,101 @@
|
||||
// What the layer row and stats count: trains drawn, a train two feeds carry
|
||||
// once, and a partial snapshot when the train cap leaves trains out.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createTrack } from '../../data/contactPlayback.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { MAX_TRAINS_TOTAL, railTrainKey } from './policy.js';
|
||||
import {
|
||||
BOSTON,
|
||||
railLayerHarness as harness,
|
||||
railTrain as train,
|
||||
} from '../../testSupport/railLayerHarness.mjs';
|
||||
|
||||
const near = (i) => ({
|
||||
lat: BOSTON.lat + 0.001 * i,
|
||||
lon: BOSTON.lon + 0.001 * i,
|
||||
});
|
||||
|
||||
test('a train another feed draws is not counted twice', async (t) => {
|
||||
const app = harness(t, { at: BOSTON });
|
||||
app.feeds.set('mbta-rail', () =>
|
||||
[1, 2, 3].map((i) => train(`T${i}`, near(i).lat, near(i).lon)),
|
||||
);
|
||||
await app.enable();
|
||||
assert.equal(app.layer.getStats().count, 3);
|
||||
// The duplicate filter hides T3 as another feed's copy of a train.
|
||||
app.entry(railTrainKey('mbta-rail', 'T3')).duplicate = true;
|
||||
const stats = app.layer.getStats();
|
||||
assert.equal(stats.count, 2);
|
||||
assert.match(stats.coverage, /MBTA 2\b/);
|
||||
const legend = app.layer.getRowControls().legend;
|
||||
assert.deepEqual(
|
||||
legend.map((item) => item.count),
|
||||
[2],
|
||||
);
|
||||
});
|
||||
|
||||
/** Trains of another feed held by the layer, outside the view. */
|
||||
function fill(app, count, { duplicate }) {
|
||||
for (let i = 0; i < count; i += 1) {
|
||||
const key = railTrainKey('elsewhere', `F${i}`);
|
||||
app.state()._trains.set(key, {
|
||||
key,
|
||||
feedId: 'elsewhere',
|
||||
category: 'regional',
|
||||
duplicate,
|
||||
marker: null,
|
||||
track: createTrack(),
|
||||
fetchedAt: Date.now(),
|
||||
record: {
|
||||
id: `F${i}`,
|
||||
lat: -40 + (i % 80),
|
||||
lon: 100 + Math.floor(i / 80),
|
||||
timestamp: Math.floor(Date.now() / 1000),
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
test('copies hidden as duplicates do not count toward the train cap', async (t) => {
|
||||
const app = harness(t, { at: BOSTON });
|
||||
let trains = [];
|
||||
app.feeds.set('mbta-rail', () => trains);
|
||||
await app.enable();
|
||||
fill(app, MAX_TRAINS_TOTAL - 1, { duplicate: true });
|
||||
trains = [1, 2, 3].map((i) => train(`T${i}`, near(i).lat, near(i).lon));
|
||||
await app.poll();
|
||||
for (const i of [1, 2, 3])
|
||||
assert.ok(app.entry(railTrainKey('mbta-rail', `T${i}`)), `T${i}`);
|
||||
assert.equal(app.state()._feedStatus.get('mbta-rail').capped, 0);
|
||||
assert.notEqual(app.layer.getStats().partial, true);
|
||||
});
|
||||
|
||||
test('trains the cap leaves out make the snapshot partial', async (t) => {
|
||||
const app = harness(t, { at: BOSTON });
|
||||
let trains = [];
|
||||
app.feeds.set('mbta-rail', () => trains);
|
||||
await app.enable();
|
||||
const warn = t.mock.method(console, 'warn', () => {});
|
||||
fill(app, MAX_TRAINS_TOTAL - 2, { duplicate: false });
|
||||
trains = [1, 2, 3, 4, 5].map((i) => train(`T${i}`, near(i).lat, near(i).lon));
|
||||
await app.poll();
|
||||
const kept = [1, 2, 3, 4, 5].filter((i) =>
|
||||
app.entry(railTrainKey('mbta-rail', `T${i}`)),
|
||||
);
|
||||
assert.equal(kept.length, 2);
|
||||
assert.equal(app.state()._feedStatus.get('mbta-rail').capped, 3);
|
||||
const stats = app.layer.getStats();
|
||||
assert.equal(stats.partial, true);
|
||||
assert.equal(stats.rawRowCount - stats.acceptedRowCount, 3);
|
||||
// The panel row reads it as PARTIAL (a feed in range that the harness
|
||||
// does not answer would read as degraded first).
|
||||
assert.equal(layerFeedState({ ...stats, degraded: false }), 'partial');
|
||||
assert.equal(warn.mock.callCount(), 1);
|
||||
// Room again: the next poll draws them all, and the note goes.
|
||||
for (const [key, entry] of app.state()._trains)
|
||||
if (entry.feedId === 'elsewhere') app.state()._trains.delete(key);
|
||||
await app.poll();
|
||||
assert.equal(app.state()._feedStatus.get('mbta-rail').capped, 0);
|
||||
assert.notEqual(app.layer.getStats().partial, true);
|
||||
});
|
||||
@@ -0,0 +1,137 @@
|
||||
import { destroyTrack } from '../../data/contactPlayback.js';
|
||||
import { RAIL_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
|
||||
import { RAIL_STOP_OVERLAY_SOURCE_ID } from './stopLabels.js';
|
||||
import {
|
||||
RAIL_ENABLED_FEEDS,
|
||||
railFeedNeedsSchedulePack,
|
||||
} from '../../data/railFeeds.js';
|
||||
|
||||
/**
|
||||
* Init / enable / disable / update / destroy for one Rail layer instance.
|
||||
* Everything acquired here is released here: the icon set, the pick owner,
|
||||
* listeners (the camera's at this layer's own threshold), and the render
|
||||
* hold.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createLifecycle({ state, services, parts, timetable }) {
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
|
||||
function dropAllTrains() {
|
||||
for (const entry of state._trains.values()) {
|
||||
parts.rendering.cancelWake(entry);
|
||||
destroyTrack(entry.track);
|
||||
}
|
||||
state._trains.clear();
|
||||
state._moving.clear();
|
||||
parts.rendering.clearMarkers();
|
||||
}
|
||||
|
||||
const methods = {
|
||||
id: 'rail',
|
||||
name: 'Rail',
|
||||
icon: '🚆',
|
||||
source: 'GTFS-RT',
|
||||
|
||||
/** Create the train icon set. Called once at bootstrap. */
|
||||
init(viewer) {
|
||||
state._viewer = viewer;
|
||||
parts.rendering.createMarkers(viewer);
|
||||
state._enabled = false;
|
||||
state._overlayHost.setVisible(RAIL_SELECTED_OVERLAY_SOURCE_ID, false);
|
||||
state._overlayHost.setVisible(RAIL_STOP_OVERLAY_SOURCE_ID, false);
|
||||
// A feed that needs its schedule pack runs only once the server's
|
||||
// catalog lists it (its pack is built); the catalog's own count is
|
||||
// logged when it arrives (viewport.js).
|
||||
const packless = RAIL_ENABLED_FEEDS.filter(
|
||||
(feed) => !railFeedNeedsSchedulePack(feed),
|
||||
).length;
|
||||
console.log(
|
||||
`[Data:Rail] Initialized: ${RAIL_ENABLED_FEEDS.length} train feeds registered, ${packless} need no schedule pack`,
|
||||
);
|
||||
},
|
||||
|
||||
/** Show trains, watch the camera, and poll every feed in range. */
|
||||
enable(viewer) {
|
||||
state._enabled = true;
|
||||
state._generation += 1;
|
||||
state._error = null;
|
||||
parts.rendering.showMarkers(true);
|
||||
state._overlayHost.setVisible(RAIL_SELECTED_OVERLAY_SOURCE_ID, true);
|
||||
state._overlayHost.setVisible(RAIL_STOP_OVERLAY_SOURCE_ID, true);
|
||||
parts.selection.installClickHandler(viewer);
|
||||
registerPickOwner('rail', (pickedId) => state._trains.has(pickedId));
|
||||
if (!state._cameraChangedAttached) {
|
||||
parts.viewport.watchCamera(viewer);
|
||||
// Attached only with a camera to listen to, so a later enable retries.
|
||||
state._cameraChangedAttached = state._cameraChangedOff !== null;
|
||||
}
|
||||
parts.rendering.startFrames(viewer);
|
||||
state._networkFade = -1;
|
||||
parts.rendering.startModels();
|
||||
parts.viewport.loadCatalog();
|
||||
parts.viewport.runProximityCheck();
|
||||
},
|
||||
|
||||
/** Hide everything, stop polling, drop all trains. */
|
||||
disable(viewer) {
|
||||
state._enabled = false;
|
||||
state._generation += 1;
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = null;
|
||||
parts.selection.clearSelection();
|
||||
state._overlayHost.setVisible(RAIL_SELECTED_OVERLAY_SOURCE_ID, false);
|
||||
state._overlayHost.setVisible(RAIL_STOP_OVERLAY_SOURCE_ID, false);
|
||||
parts.selection.removeClickHandler();
|
||||
unregisterPickOwner('rail');
|
||||
// Unconditional: whatever watching started, none of it outlives this.
|
||||
parts.viewport.unwatchCamera();
|
||||
state._cameraChangedAttached = false;
|
||||
parts.rendering.stopFrames();
|
||||
parts.viewport.cancelCatalog();
|
||||
timetable.stop();
|
||||
parts.ingestion.abortAllInFlight();
|
||||
state._activeFeeds.clear();
|
||||
state._heldFeedId = null;
|
||||
state._feedStatus.clear();
|
||||
dropAllTrains();
|
||||
parts.rendering.stopModels();
|
||||
// Floor cells and track samples queued for trains now gone.
|
||||
parts.rendering.reset();
|
||||
parts.routes.hideAll();
|
||||
parts.rendering.showMarkers(false);
|
||||
state._altitudeGateOpen = false;
|
||||
if (state._renderHeld) {
|
||||
releaseContinuousRender('rail');
|
||||
state._renderHeld = false;
|
||||
}
|
||||
},
|
||||
|
||||
/** Manager tick (every RAIL_POLL_MS): sweep, then re-poll active feeds. */
|
||||
async update() {
|
||||
if (!state._enabled) return;
|
||||
parts.ingestion.sweepAgedTrains(Date.now());
|
||||
parts.routes.releaseIdleFeeds(Date.now());
|
||||
const generation = state._generation;
|
||||
await Promise.all(
|
||||
[...state._activeFeeds.values()].map((feed) =>
|
||||
parts.ingestion.pollFeed(feed, generation),
|
||||
),
|
||||
);
|
||||
},
|
||||
|
||||
/** Tear down the icon set and release every shared registration. */
|
||||
destroy(viewer) {
|
||||
this.disable(viewer);
|
||||
parts.rendering.stopModels(true);
|
||||
parts.routes.destroy();
|
||||
parts.rendering.destroyMarkers();
|
||||
state._overlayHost.clearSource(RAIL_SELECTED_OVERLAY_SOURCE_ID);
|
||||
state._dataManager = null;
|
||||
state._viewer = null;
|
||||
},
|
||||
};
|
||||
|
||||
return { methods };
|
||||
}
|
||||
@@ -0,0 +1,386 @@
|
||||
// Only live trains are drawn. A live feed whose positions fail is shown as
|
||||
// unavailable: no train is placed or moved from its timetable, nothing is
|
||||
// asked for to place one, and the trains it drew go as their reports age.
|
||||
// A schedule pack is read only for a selected live train's stops. Feeds
|
||||
// that read their routes from a schedule pack wait for the server's
|
||||
// catalog, which is asked for again with a backoff when it fails.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
CATALOG_RETRY_FIRST_MS,
|
||||
CATALOG_RETRY_MAX_MS,
|
||||
FEED_EVICT_AFTER_MS,
|
||||
RAIL_POLL_MS,
|
||||
railCatalogRetryDelayMs,
|
||||
railTrainKey,
|
||||
} from './policy.js';
|
||||
import * as policy from './policy.js';
|
||||
import {
|
||||
getRegisteredRailFeed,
|
||||
publicRailCatalog,
|
||||
railFeedNeedsSchedulePack,
|
||||
} from '../../data/railFeeds.js';
|
||||
import {
|
||||
RAIL_HARNESS_T0 as T0,
|
||||
railLayerHarness as harness,
|
||||
railTrain as train,
|
||||
} from '../../testSupport/railLayerHarness.mjs';
|
||||
|
||||
const FEED = 'septa-regional-rail';
|
||||
const PHILADELPHIA = { lat: 40.0, lon: -75.25 };
|
||||
const MADRID = { lat: 40.42, lon: -3.7 };
|
||||
/** The server's catalog, narrowed to SEPTA so no other feed is polled. */
|
||||
const CATALOG = publicRailCatalog().filter((feed) => feed.id === FEED);
|
||||
const LAT = 40.0;
|
||||
const STEP_M = 0.1 * 111_320 * Math.cos((LAT * Math.PI) / 180);
|
||||
const DAY = new Date(T0).toISOString().slice(0, 10);
|
||||
/** Seconds after midnight (UTC) at the tests' start. */
|
||||
const T0_SEC = (T0 - Date.parse(`${DAY}T00:00:00Z`)) / 1000;
|
||||
|
||||
/**
|
||||
* A SEPTA schedule pack of one Paoli/Thorndale run, T1, west to east across
|
||||
* three stops an hour long, that left its first stop ten minutes before the
|
||||
* tests start. It is served, and must never place a train.
|
||||
*/
|
||||
const SEPTA_PACK = Object.freeze({
|
||||
version: 1,
|
||||
feedId: FEED,
|
||||
timezone: 'UTC',
|
||||
window: { from: DAY, to: DAY },
|
||||
routes: { PAO: { type: 2 } },
|
||||
stops: [
|
||||
{ id: 'A', name: 'Paoli', lat: LAT, lon: -75.45 },
|
||||
{ id: 'B', name: 'Bryn Mawr', lat: LAT, lon: -75.35 },
|
||||
{ id: 'C', name: '30th Street', lat: LAT, lon: -75.25 },
|
||||
],
|
||||
patterns: [
|
||||
{
|
||||
shape: 0,
|
||||
stops: [0, 1, 2],
|
||||
seq: [1, 2, 3],
|
||||
dist: [0, STEP_M, 2 * STEP_M],
|
||||
},
|
||||
],
|
||||
profiles: [[0, 0, 1800, 1860, 3600, 3600]],
|
||||
services: { WK: [DAY] },
|
||||
trips: {
|
||||
T1: {
|
||||
pattern: 0,
|
||||
profile: 0,
|
||||
startSec: T0_SEC - 600,
|
||||
route: 'PAO',
|
||||
service: 'WK',
|
||||
headsign: '30th Street',
|
||||
name: '9512',
|
||||
},
|
||||
},
|
||||
});
|
||||
const LIVE_V1 = railTrainKey(FEED, 'V1');
|
||||
|
||||
/** SEPTA's live answer, switched by the test; its schedule pack is served. */
|
||||
function septa(app, answer = { status: 502 }) {
|
||||
const live = { answer };
|
||||
app.schedules.set(FEED, SEPTA_PACK);
|
||||
app.feeds.set(FEED, () =>
|
||||
typeof live.answer === 'function' ? live.answer() : live.answer,
|
||||
);
|
||||
return live;
|
||||
}
|
||||
|
||||
const feedStatus = (app) => app.state()._feedStatus.get(FEED);
|
||||
const feedKeys = (app) =>
|
||||
[...app.state()._trains.keys()].filter((key) =>
|
||||
key.startsWith(`rail:${FEED}:`),
|
||||
);
|
||||
const asked = (app) => app.requested.filter((id) => id === FEED).length;
|
||||
|
||||
/** Live V1 on trip T1, near where the timetable has the train. */
|
||||
function liveV1() {
|
||||
const minutes = (Date.now() - T0) / 60_000;
|
||||
return [
|
||||
train('V1', LAT, -75.4 + minutes * 0.002, {
|
||||
tripId: 'T1',
|
||||
routeId: 'PAO',
|
||||
category: 'local',
|
||||
label: '9512',
|
||||
}),
|
||||
];
|
||||
}
|
||||
|
||||
test('the layer has no timetable fallback to switch to', () => {
|
||||
for (const gone of [
|
||||
'LIVE_FAILURES_TO_TIMETABLE',
|
||||
'LIVE_PROBE_MIN_MS',
|
||||
'LIVE_PROBE_MAX_MS',
|
||||
'railLiveFailureKind',
|
||||
'railLiveProbeDelayMs',
|
||||
])
|
||||
assert.equal(policy[gone], undefined, gone);
|
||||
});
|
||||
|
||||
test('a live feed whose operator fails shows unavailable, and no timetable is asked for', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const app = harness(t, { at: PHILADELPHIA, catalog: CATALOG });
|
||||
septa(app);
|
||||
await app.enable();
|
||||
for (let i = 0; i < 4; i += 1) {
|
||||
const status = feedStatus(app);
|
||||
assert.match(status.error, /unavailable/, `poll ${i + 1}`);
|
||||
assert.equal(status.loading, false);
|
||||
assert.deepEqual(feedKeys(app), [], 'no train placed from the timetable');
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.deepEqual(app.requestedSchedules, [], 'no schedule pack asked for');
|
||||
// Live positions are asked for again every poll, as for any feed.
|
||||
assert.equal(asked(app), 5);
|
||||
assert.match(app.layer.getStats().error, /unavailable/);
|
||||
});
|
||||
|
||||
test('trains a failing feed drew are never moved on by its timetable; they age out', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const app = harness(t, {
|
||||
at: PHILADELPHIA,
|
||||
catalog: CATALOG,
|
||||
scheduleStops: true,
|
||||
});
|
||||
const live = septa(app, liveV1);
|
||||
await app.enable();
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
assert.deepEqual(feedKeys(app), [LIVE_V1]);
|
||||
// A selected live train reads its stops from the schedule pack.
|
||||
app.parts().selection.selectTrain(LIVE_V1);
|
||||
await app.settle();
|
||||
assert.deepEqual(app.requestedSchedules, [FEED]);
|
||||
const lastReport = app.entry(LIVE_V1).record;
|
||||
|
||||
// The operator fails: the train keeps its last report, and only that.
|
||||
live.answer = { status: 502 };
|
||||
const failedAt = Date.now();
|
||||
while (Date.now() - failedAt <= FEED_EVICT_AFTER_MS) {
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
for (const key of feedKeys(app))
|
||||
assert.equal(key, LIVE_V1, 'no timetable run is drawn');
|
||||
if (app.entry(LIVE_V1))
|
||||
assert.equal(app.entry(LIVE_V1).record, lastReport, 'never moved on');
|
||||
}
|
||||
assert.deepEqual(feedKeys(app), [], 'gone as its report aged');
|
||||
assert.equal(app.state()._selectedKey, null);
|
||||
assert.match(feedStatus(app).error, /unavailable/);
|
||||
assert.deepEqual(app.requestedSchedules, [FEED], 'asked for once, for stops');
|
||||
});
|
||||
|
||||
test('a server that answers with timetable positions has no live data: nothing drawn', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
// SEPTA's trains route answers 200 with no live positions
|
||||
// (`positions: 'schedule'`, no trains).
|
||||
const app = harness(t, { at: PHILADELPHIA, catalog: CATALOG });
|
||||
septa(app, { positions: 'schedule' });
|
||||
await app.enable();
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.deepEqual(feedKeys(app), []);
|
||||
assert.match(feedStatus(app).error, /unavailable/);
|
||||
assert.deepEqual(app.requestedSchedules, []);
|
||||
// It is not taken for a timetable feed: live is asked for every poll.
|
||||
assert.equal(asked(app), 4);
|
||||
});
|
||||
|
||||
test('a train record placed from a timetable is never drawn, whatever the feed says', async (t) => {
|
||||
const app = harness(t, { at: PHILADELPHIA, catalog: CATALOG });
|
||||
septa(app, () => [
|
||||
train('V1', LAT, -75.4, { positionSource: 'schedule' }),
|
||||
train('V2', LAT, -75.3, { positionSource: 'gps' }),
|
||||
train('V3', LAT, -75.35, { positionSource: 'event' }),
|
||||
train('V4', LAT, -75.32, { positionSource: undefined }),
|
||||
]);
|
||||
await app.enable();
|
||||
assert.deepEqual(feedKeys(app).sort(), [
|
||||
railTrainKey(FEED, 'V2'),
|
||||
railTrainKey(FEED, 'V3'),
|
||||
railTrainKey(FEED, 'V4'),
|
||||
]);
|
||||
assert.equal(feedStatus(app).error, null);
|
||||
});
|
||||
|
||||
test('a catalog feed without live positions is never polled', async (t) => {
|
||||
// A catalog entry whose positions are not live is left alone.
|
||||
const app = harness(t, {
|
||||
at: PHILADELPHIA,
|
||||
catalog: CATALOG.map((feed) => ({ ...feed, positions: 'schedule' })),
|
||||
});
|
||||
septa(app, liveV1);
|
||||
await app.enable();
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
assert.ok(!app.state()._activeFeeds.has(FEED));
|
||||
assert.equal(asked(app), 1, 'only the first poll, before the catalog');
|
||||
assert.deepEqual(feedKeys(app), []);
|
||||
assert.deepEqual(app.requestedSchedules, []);
|
||||
});
|
||||
|
||||
test('a feed the catalog leaves out is never polled once it loads', async (t) => {
|
||||
// Here the catalog lists SEPTA's regional rail alone, so the other
|
||||
// bundled feed in range (the trolleys) is dropped as soon as it answers.
|
||||
const app = harness(t, { at: PHILADELPHIA, catalog: CATALOG });
|
||||
septa(app, liveV1);
|
||||
await app.enable();
|
||||
assert.deepEqual([...app.state()._activeFeeds.keys()], [FEED]);
|
||||
const before = app.requested.filter((id) => id !== FEED).length;
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.equal(app.requested.filter((id) => id !== FEED).length, before);
|
||||
assert.deepEqual(
|
||||
[...app.state()._feedStatus.keys()],
|
||||
[FEED],
|
||||
'no status, so no error, for a feed the catalog left out',
|
||||
);
|
||||
});
|
||||
|
||||
/** A catalog the test answers (or fails) when it chooses. */
|
||||
function pendingCatalog() {
|
||||
const pending = {};
|
||||
pending.promise = new Promise((resolve, reject) => {
|
||||
pending.resolve = resolve;
|
||||
pending.reject = reject;
|
||||
});
|
||||
return pending;
|
||||
}
|
||||
|
||||
const LONG_DISTANCE = 'renfe-larga-distancia';
|
||||
const CERCANIAS = 'renfe-cercanias';
|
||||
|
||||
/** Madrid's two live feeds, both answering with no trains. */
|
||||
function liveFeedsAnswer(app) {
|
||||
app.feeds.set(LONG_DISTANCE, () => []);
|
||||
app.feeds.set(CERCANIAS, () => []);
|
||||
}
|
||||
|
||||
const needsPack = (id) => railFeedNeedsSchedulePack(getRegisteredRailFeed(id));
|
||||
|
||||
test('Renfe long distance reads its routes from a pack: it is held back until the catalog lists it', () => {
|
||||
assert.equal(needsPack(LONG_DISTANCE), true);
|
||||
assert.equal(needsPack(CERCANIAS), false);
|
||||
});
|
||||
|
||||
test('a pack-routed live feed waits for the catalog, then runs once its pack is built', async (t) => {
|
||||
// A fresh install builds no packs: until the catalog says which are
|
||||
// built, no such feed's pack is asked for (it would answer 404).
|
||||
const catalog = pendingCatalog();
|
||||
const app = harness(t, { at: MADRID, catalog: catalog.promise, paths: {} });
|
||||
liveFeedsAnswer(app);
|
||||
await app.enable();
|
||||
const asks = () => [...app.requestedSchedules, ...app.requestedPaths];
|
||||
assert.ok(app.requestedPaths.includes(CERCANIAS), 'Cercanías starts at once');
|
||||
assert.deepEqual(asks().filter(needsPack), []);
|
||||
assert.ok(!app.state()._activeFeeds.has(LONG_DISTANCE));
|
||||
assert.ok(!app.requested.includes(LONG_DISTANCE));
|
||||
|
||||
catalog.resolve(
|
||||
publicRailCatalog({ schedulePackBuilt: (id) => id === LONG_DISTANCE }),
|
||||
);
|
||||
await app.settle();
|
||||
assert.ok(app.state()._activeFeeds.has(LONG_DISTANCE));
|
||||
assert.ok(app.requested.includes(LONG_DISTANCE), 'its live positions');
|
||||
assert.ok(app.requestedPaths.includes(LONG_DISTANCE), 'and its line');
|
||||
// Its schedule pack is not needed to place anything.
|
||||
assert.deepEqual(app.requestedSchedules, []);
|
||||
});
|
||||
|
||||
test('a pack-routed live feed whose pack is not built is never polled', async (t) => {
|
||||
const app = harness(t, {
|
||||
at: MADRID,
|
||||
catalog: publicRailCatalog({ schedulePackBuilt: () => false }),
|
||||
paths: {},
|
||||
});
|
||||
liveFeedsAnswer(app);
|
||||
await app.enable();
|
||||
for (let i = 0; i < 2; i += 1) {
|
||||
app.run(RAIL_POLL_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.deepEqual([...app.state()._activeFeeds.keys()], [CERCANIAS]);
|
||||
assert.ok(!app.requested.includes(LONG_DISTANCE));
|
||||
assert.deepEqual(
|
||||
[...app.requestedSchedules, ...app.requestedPaths].filter(needsPack),
|
||||
[],
|
||||
);
|
||||
});
|
||||
|
||||
test('a catalog that fails keeps pack-routed feeds held back and is asked for again', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
// Two failures, then a catalog with Renfe long distance's pack built.
|
||||
const answers = [
|
||||
() => Promise.reject(new Error('Rail feeds HTTP 500')),
|
||||
() => Promise.reject(new Error('Rail feeds HTTP 502')),
|
||||
() =>
|
||||
publicRailCatalog({ schedulePackBuilt: (id) => id === LONG_DISTANCE }),
|
||||
];
|
||||
const app = harness(t, {
|
||||
at: MADRID,
|
||||
catalog: () => answers.shift()(),
|
||||
paths: {},
|
||||
});
|
||||
liveFeedsAnswer(app);
|
||||
await app.enable();
|
||||
const asks = () => [...app.requestedSchedules, ...app.requestedPaths];
|
||||
assert.equal(app.catalogRequests.length, 1);
|
||||
assert.ok(app.state()._activeFeeds.has(CERCANIAS), 'live feeds still run');
|
||||
assert.deepEqual(asks().filter(needsPack), [], 'no pack asked for');
|
||||
assert.ok(!app.state()._activeFeeds.has(LONG_DISTANCE));
|
||||
|
||||
// Asked for again after 30 s, then after a further minute.
|
||||
t.mock.timers.tick(CATALOG_RETRY_FIRST_MS - 1);
|
||||
await app.settle();
|
||||
assert.equal(app.catalogRequests.length, 1);
|
||||
t.mock.timers.tick(1);
|
||||
await app.settle();
|
||||
assert.equal(app.catalogRequests.length, 2);
|
||||
assert.deepEqual(asks().filter(needsPack), []);
|
||||
t.mock.timers.tick(2 * CATALOG_RETRY_FIRST_MS);
|
||||
await app.settle();
|
||||
assert.equal(app.catalogRequests.length, 3);
|
||||
assert.ok(app.state()._activeFeeds.has(LONG_DISTANCE));
|
||||
assert.ok(app.requestedPaths.includes(LONG_DISTANCE));
|
||||
|
||||
// A catalog that loaded is not asked for again.
|
||||
t.mock.timers.tick(CATALOG_RETRY_MAX_MS);
|
||||
await app.settle();
|
||||
assert.equal(app.catalogRequests.length, 3);
|
||||
});
|
||||
|
||||
test('the catalog retry backs off to ten minutes and stops with the layer', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
assert.equal(railCatalogRetryDelayMs(1), CATALOG_RETRY_FIRST_MS);
|
||||
assert.equal(railCatalogRetryDelayMs(2), 2 * CATALOG_RETRY_FIRST_MS);
|
||||
assert.equal(railCatalogRetryDelayMs(30), CATALOG_RETRY_MAX_MS);
|
||||
const app = harness(t, {
|
||||
at: MADRID,
|
||||
catalog: () => Promise.reject(new Error('Rail feeds HTTP 500')),
|
||||
paths: {},
|
||||
});
|
||||
liveFeedsAnswer(app);
|
||||
await app.enable();
|
||||
app.layer.disable(app.viewer);
|
||||
t.mock.timers.tick(CATALOG_RETRY_MAX_MS);
|
||||
await app.settle();
|
||||
assert.equal(app.catalogRequests.length, 1, 'no retry while off');
|
||||
});
|
||||
|
||||
test('a source without a catalog polls only the feeds that need no pack', async (t) => {
|
||||
const app = harness(t, { at: MADRID, catalog: false, paths: {} });
|
||||
liveFeedsAnswer(app);
|
||||
await app.enable();
|
||||
const active = [...app.state()._activeFeeds.keys()];
|
||||
assert.deepEqual(active, [CERCANIAS]);
|
||||
assert.deepEqual(
|
||||
[...app.requestedSchedules, ...app.requestedPaths].filter(needsPack),
|
||||
[],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,243 @@
|
||||
import { pointAtS, projectOnPath } from '../../data/railPaths.js';
|
||||
|
||||
/**
|
||||
* Binding a train to its railway line and moving it along that line.
|
||||
*
|
||||
* A train is bound to one shape of its feed's path pack: the shape its trip
|
||||
* names, else the route's shape its report lies on. Every later report is
|
||||
* projected onto that shape near the arc the train was last seen at, so a
|
||||
* report can never snap to the far side of a loop or to a parallel branch.
|
||||
* A report that lands well off the line means the binding was wrong (a
|
||||
* diversion, a short-turn shape, a mismatched trip): the train is moved to
|
||||
* another of its route's shapes if one fits, else it is unbound and drawn
|
||||
* with straight-line motion again.
|
||||
*
|
||||
* Between two reports the marker moves by arc length: both reports are
|
||||
* projected onto the shape once per playback segment, and each frame only
|
||||
* interpolates the arc and looks up the point.
|
||||
*
|
||||
* Pure: no Cesium, no DOM.
|
||||
*/
|
||||
|
||||
/** A report farther than this from the bound line unbinds the train (m). */
|
||||
export const PATH_OFF_TRACK_M = 150;
|
||||
/** Fastest train the search window allows for (m/s, about 250 km/h). */
|
||||
const PATH_MAX_SPEED_MPS = 70;
|
||||
/** Window slack for report jitter and clock error (m). */
|
||||
const PATH_WINDOW_SLACK_M = 300;
|
||||
/** Widest hinted search; beyond it the whole shape is searched (m). */
|
||||
const PATH_WINDOW_MAX_M = 50_000;
|
||||
/**
|
||||
* Among route shapes that fit a report about equally well, the longest wins:
|
||||
* overlapping shapes are usually a full run and its short turns, and a short
|
||||
* turn would unbind a train that runs past its end.
|
||||
*/
|
||||
const PATH_TIE_M = 10;
|
||||
|
||||
/**
|
||||
* Half-width of the arc window a train can have moved in `dtMs`, or NaN when
|
||||
* the gap is unknown or too long for a window to be meaningful.
|
||||
* @param {number} dtMs
|
||||
* @returns {number}
|
||||
*/
|
||||
export function pathWindowM(dtMs) {
|
||||
if (!Number.isFinite(dtMs)) return NaN;
|
||||
const window =
|
||||
PATH_WINDOW_SLACK_M + (PATH_MAX_SPEED_MPS * Math.abs(dtMs)) / 1000;
|
||||
return window > PATH_WINDOW_MAX_M ? NaN : window;
|
||||
}
|
||||
|
||||
function createBinding(shapeIndex, path, via, s, fix) {
|
||||
return {
|
||||
shapeIndex,
|
||||
path,
|
||||
via,
|
||||
/** Arc and time of the newest report. */
|
||||
fixS: s,
|
||||
fixT: fix.t,
|
||||
fixLat: fix.lat,
|
||||
fixLon: fix.lon,
|
||||
/** Arc and time last drawn. */
|
||||
drawS: s,
|
||||
drawT: fix.t,
|
||||
/** Projections of the current playback segment's two reports. */
|
||||
segment: {
|
||||
fromSeq: -1,
|
||||
toSeq: -1,
|
||||
fromLat: NaN,
|
||||
fromLon: NaN,
|
||||
toLat: NaN,
|
||||
toLon: NaN,
|
||||
sFrom: NaN,
|
||||
sTo: NaN,
|
||||
ok: false,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The route shape a report fits best, preferring the longest near-tie. */
|
||||
function bestRouteShape(pack, routeId, fix, accept) {
|
||||
const candidates = [];
|
||||
for (const index of pack.shapesForRoute(routeId)) {
|
||||
const path = pack.pathAt(index);
|
||||
const hit = projectOnPath(path, fix.lat, fix.lon);
|
||||
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) continue;
|
||||
if (!accept(index, path)) continue;
|
||||
candidates.push({ index, path, s: hit.s, offsetM: hit.offsetM });
|
||||
}
|
||||
if (!candidates.length) return null;
|
||||
const nearest = Math.min(...candidates.map((c) => c.offsetM));
|
||||
let best = null;
|
||||
for (const candidate of candidates) {
|
||||
if (candidate.offsetM > nearest + PATH_TIE_M) continue;
|
||||
if (!best || candidate.path.length > best.path.length) best = candidate;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind a train to a shape from its feed's pack.
|
||||
*
|
||||
* The trip's own shape when the trip is in the pack and the report lies on it;
|
||||
* otherwise the route shape the report lies nearest (within PATH_OFF_TRACK_M),
|
||||
* which for a single-shape route is that shape.
|
||||
*
|
||||
* @param {object} pack From createRailPathPack.
|
||||
* @param {{tripId?: string, routeId?: string}} ids
|
||||
* @param {{t: number, lat: number, lon: number}} fix The newest report.
|
||||
* @returns {object|null} A binding, or null to keep straight-line motion.
|
||||
*/
|
||||
export function bindTrainPath(pack, { tripId, routeId } = {}, fix) {
|
||||
if (!pack || !fix || !Number.isFinite(fix.lat) || !Number.isFinite(fix.lon))
|
||||
return null;
|
||||
const trip = pack.shapeForTrip(tripId);
|
||||
if (trip !== null) {
|
||||
const path = pack.pathAt(trip);
|
||||
const hit = projectOnPath(path, fix.lat, fix.lon);
|
||||
if (hit && hit.offsetM <= PATH_OFF_TRACK_M)
|
||||
return createBinding(trip, path, 'trip', hit.s, fix);
|
||||
}
|
||||
const best = bestRouteShape(pack, routeId, fix, (index) => index !== trip);
|
||||
return best
|
||||
? createBinding(best.index, best.path, 'route', best.s, fix)
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Follow a new report on the bound shape.
|
||||
* @param {object} binding
|
||||
* @param {{t: number, lat: number, lon: number}} fix
|
||||
* @returns {boolean} False when the report lies off the line: the binding is wrong.
|
||||
*/
|
||||
export function followFix(binding, fix) {
|
||||
if (!binding || !fix) return false;
|
||||
const hit = projectOnPath(
|
||||
binding.path,
|
||||
fix.lat,
|
||||
fix.lon,
|
||||
binding.fixS,
|
||||
pathWindowM(fix.t - binding.fixT),
|
||||
);
|
||||
if (!hit || hit.offsetM > PATH_OFF_TRACK_M) return false;
|
||||
binding.fixS = hit.s;
|
||||
binding.fixT = fix.t;
|
||||
binding.fixLat = fix.lat;
|
||||
binding.fixLon = fix.lon;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* After a report fell off the bound shape: another shape of the route that
|
||||
* holds both the previous report and this one, or null for straight lines.
|
||||
* @param {object} pack
|
||||
* @param {{routeId?: string}} ids
|
||||
* @param {object} binding The binding that no longer fits.
|
||||
* @param {{t: number, lat: number, lon: number}} fix
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function rebindTrainPath(pack, { routeId } = {}, binding, fix) {
|
||||
if (!pack || !binding || !fix) return null;
|
||||
const best = bestRouteShape(pack, routeId, fix, (index, path) => {
|
||||
if (index === binding.shapeIndex) return false;
|
||||
const previous = projectOnPath(path, binding.fixLat, binding.fixLon);
|
||||
return !!previous && previous.offsetM <= PATH_OFF_TRACK_M;
|
||||
});
|
||||
return best
|
||||
? createBinding(best.index, best.path, 'route', best.s, fix)
|
||||
: null;
|
||||
}
|
||||
|
||||
/** Project one playback report, near the last drawn arc when that is useful. */
|
||||
function projectReport(binding, fix, hintS, hintT) {
|
||||
const path = binding.path;
|
||||
const window = pathWindowM(fix.t - hintT);
|
||||
let hit = Number.isFinite(hintS)
|
||||
? projectOnPath(path, fix.lat, fix.lon, hintS, window)
|
||||
: null;
|
||||
if (!hit || hit.offsetM > PATH_OFF_TRACK_M)
|
||||
hit = projectOnPath(path, fix.lat, fix.lon);
|
||||
return hit && hit.offsetM <= PATH_OFF_TRACK_M ? hit.s : NaN;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where a bound train is drawn this frame.
|
||||
*
|
||||
* The playback segment's two reports are projected once per segment (the
|
||||
* from-report reuses the previous segment's to-report when they are the same
|
||||
* report); every frame interpolates the arc by the playback fraction and
|
||||
* looks up that point.
|
||||
*
|
||||
* @param {object} binding
|
||||
* @param {{fromSeq: number, toSeq: number, fraction: number}} sample Playback sample.
|
||||
* @param {{from: {seq:number, t:number, lat:number, lon:number},
|
||||
* to: {seq:number, t:number, lat:number, lon:number}}} segment The sample's two reports.
|
||||
* @param {{lat?: number, lon?: number, bearingDeg?: number}} out
|
||||
* @returns {boolean} False when the train should stay on its straight-line point.
|
||||
*/
|
||||
export function placeOnPath(binding, sample, segment, out) {
|
||||
if (!binding || !sample || !segment || !(sample.fromSeq >= 0)) return false;
|
||||
const { from, to } = segment;
|
||||
if (from.seq !== sample.fromSeq || to.seq !== sample.toSeq) return false;
|
||||
const cache = binding.segment;
|
||||
if (
|
||||
cache.fromSeq !== sample.fromSeq ||
|
||||
cache.toSeq !== sample.toSeq ||
|
||||
cache.fromLat !== from.lat ||
|
||||
cache.fromLon !== from.lon ||
|
||||
cache.toLat !== to.lat ||
|
||||
cache.toLon !== to.lon
|
||||
) {
|
||||
const chained =
|
||||
cache.ok &&
|
||||
cache.toSeq === sample.fromSeq &&
|
||||
cache.toLat === from.lat &&
|
||||
cache.toLon === from.lon;
|
||||
const sFrom = chained
|
||||
? cache.sTo
|
||||
: projectReport(binding, from, binding.drawS, binding.drawT);
|
||||
const sTo =
|
||||
sample.toSeq === sample.fromSeq
|
||||
? sFrom
|
||||
: Number.isFinite(sFrom)
|
||||
? projectReport(binding, to, sFrom, from.t)
|
||||
: NaN;
|
||||
cache.fromSeq = sample.fromSeq;
|
||||
cache.toSeq = sample.toSeq;
|
||||
cache.fromLat = from.lat;
|
||||
cache.fromLon = from.lon;
|
||||
cache.toLat = to.lat;
|
||||
cache.toLon = to.lon;
|
||||
cache.sFrom = sFrom;
|
||||
cache.sTo = sTo;
|
||||
cache.ok = Number.isFinite(sFrom) && Number.isFinite(sTo);
|
||||
}
|
||||
if (!cache.ok) return false;
|
||||
const f = Number.isFinite(sample.fraction)
|
||||
? Math.max(0, Math.min(1, sample.fraction))
|
||||
: 1;
|
||||
const s = cache.sFrom + (cache.sTo - cache.sFrom) * f;
|
||||
if (!pointAtS(binding.path, s, out)) return false;
|
||||
binding.drawS = s;
|
||||
binding.drawT = from.t + (to.t - from.t) * f;
|
||||
return true;
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRailPathPack } from '../../data/railPaths.js';
|
||||
import {
|
||||
PATH_OFF_TRACK_M,
|
||||
bindTrainPath,
|
||||
followFix,
|
||||
pathWindowM,
|
||||
placeOnPath,
|
||||
rebindTrainPath,
|
||||
} from './pathBinding.js';
|
||||
|
||||
const D = 1 / 111_320;
|
||||
|
||||
/**
|
||||
* Three shapes on the equator:
|
||||
* 0: an L, 2 km east then 2 km north (the full run);
|
||||
* 1: the first 1 km of the same line (a short turn);
|
||||
* 2: 2 km east then 2 km south (a branch at the same junction).
|
||||
*/
|
||||
function pack() {
|
||||
return createRailPathPack({
|
||||
version: 1,
|
||||
feedId: 'test-feed',
|
||||
shapes: [
|
||||
[0, 0, 0, 2000 * D, 2000 * D, 2000 * D],
|
||||
[0, 0, 0, 1000 * D],
|
||||
[0, 0, 0, 2000 * D, -2000 * D, 2000 * D],
|
||||
],
|
||||
dist: [
|
||||
[0, 2000, 4000],
|
||||
[0, 1000],
|
||||
[0, 2000, 4000],
|
||||
],
|
||||
trips: { full: 0, branch: 2 },
|
||||
routes: { main: [0, 1, 2], short: [1] },
|
||||
});
|
||||
}
|
||||
|
||||
const fix = (t, eastM, northM) => ({ t, lat: northM * D, lon: eastM * D });
|
||||
|
||||
test('a trip binds to its own shape, else to the best route shape', () => {
|
||||
const p = pack();
|
||||
const byTrip = bindTrainPath(
|
||||
p,
|
||||
{ tripId: 'branch', routeId: 'main' },
|
||||
fix(0, 500, 10),
|
||||
);
|
||||
assert.equal(byTrip.shapeIndex, 2);
|
||||
assert.equal(byTrip.via, 'trip');
|
||||
assert.ok(Math.abs(byTrip.fixS - 500) < 0.5);
|
||||
const single = bindTrainPath(
|
||||
p,
|
||||
{ tripId: 'unknown', routeId: 'short' },
|
||||
fix(0, 500, 0),
|
||||
);
|
||||
assert.equal(single.shapeIndex, 1);
|
||||
assert.equal(single.via, 'route');
|
||||
// Near the shared start every main shape fits; the longest wins the tie.
|
||||
const shared = bindTrainPath(p, { routeId: 'main' }, fix(0, 500, 0));
|
||||
assert.ok([0, 2].includes(shared.shapeIndex), String(shared.shapeIndex));
|
||||
// Up the north leg only the full run fits.
|
||||
const north = bindTrainPath(p, { routeId: 'main' }, fix(0, 2010, 1500));
|
||||
assert.equal(north.shapeIndex, 0);
|
||||
assert.ok(Math.abs(north.fixS - 3500) < 1);
|
||||
});
|
||||
|
||||
test('a trip whose report is off its shape falls back to the route', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(
|
||||
p,
|
||||
{ tripId: 'branch', routeId: 'main' },
|
||||
fix(0, 2000, 1000),
|
||||
);
|
||||
assert.equal(binding.shapeIndex, 0);
|
||||
});
|
||||
|
||||
test('nothing binds when no shape lies within the off-track distance', () => {
|
||||
const p = pack();
|
||||
assert.equal(
|
||||
bindTrainPath(p, { routeId: 'main' }, fix(0, 1000, PATH_OFF_TRACK_M + 50)),
|
||||
null,
|
||||
);
|
||||
assert.equal(bindTrainPath(p, { routeId: 'none' }, fix(0, 0, 0)), null);
|
||||
assert.equal(bindTrainPath(null, { routeId: 'main' }, fix(0, 0, 0)), null);
|
||||
assert.equal(
|
||||
bindTrainPath(p, { routeId: 'main' }, { t: 0, lat: Number.NaN, lon: 0 }),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('reports are followed along the line and an off-line report unbinds', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(p, { tripId: 'full' }, fix(0, 100, 0));
|
||||
assert.ok(followFix(binding, fix(30_000, 1200, 5)));
|
||||
assert.ok(Math.abs(binding.fixS - 1200) < 0.5);
|
||||
assert.equal(followFix(binding, fix(60_000, 1500, 400)), false);
|
||||
assert.ok(
|
||||
Math.abs(binding.fixS - 1200) < 0.5,
|
||||
'a rejected report changes nothing',
|
||||
);
|
||||
});
|
||||
|
||||
test('an off-line report moves the train to a route shape that holds both reports', () => {
|
||||
const p = pack();
|
||||
// Bound to the short turn, the train runs past its end and on up the L.
|
||||
const short = bindTrainPath(p, { routeId: 'short' }, fix(0, 800, 0));
|
||||
assert.ok(followFix(short, fix(20_000, 950, 0)));
|
||||
const next = fix(60_000, 2000, 300);
|
||||
assert.equal(followFix(short, next), false);
|
||||
const moved = rebindTrainPath(p, { routeId: 'main' }, short, next);
|
||||
assert.equal(moved.shapeIndex, 0);
|
||||
assert.ok(Math.abs(moved.fixS - 2300) < 1);
|
||||
assert.equal(rebindTrainPath(p, { routeId: 'short' }, short, next), null);
|
||||
});
|
||||
|
||||
test('the search window grows with the gap and gives up when it is too long', () => {
|
||||
assert.equal(pathWindowM(0), 300);
|
||||
assert.equal(pathWindowM(-10_000), 1000);
|
||||
assert.ok(Number.isNaN(pathWindowM(Number.NaN)));
|
||||
assert.ok(Number.isNaN(pathWindowM(3_600_000)));
|
||||
});
|
||||
|
||||
function playback(fromSeq, toSeq, from, to, fraction) {
|
||||
return {
|
||||
sample: { fromSeq, toSeq, fraction },
|
||||
segment: {
|
||||
from: { seq: fromSeq, ...from },
|
||||
to: { seq: toSeq, ...to },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('between two reports a bound train moves along the line, not the chord', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(p, { tripId: 'full' }, fix(0, 1500, 0));
|
||||
// A corner cut: 1.5 km east, then 500 m up the north leg.
|
||||
const a = fix(0, 1500, 0);
|
||||
const b = fix(60_000, 2000, 500);
|
||||
const out = {};
|
||||
const mid = playback(4, 5, a, b, 0.5);
|
||||
assert.ok(placeOnPath(binding, mid.sample, mid.segment, out));
|
||||
// Halfway along the 1 km of track is the corner itself.
|
||||
assert.ok(Math.abs(out.lat) < 1e-9, String(out.lat));
|
||||
assert.ok(Math.abs(out.lon - 2000 * D) < 1e-6, String(out.lon));
|
||||
assert.ok(Math.abs(binding.drawS - 2000) < 1);
|
||||
const later = playback(4, 5, a, b, 0.75);
|
||||
assert.ok(placeOnPath(binding, later.sample, later.segment, out));
|
||||
assert.ok(Math.abs(out.lat - 250 * D) < 1e-6);
|
||||
assert.ok(
|
||||
Math.abs(out.bearingDeg) < 1e-6 || Math.abs(out.bearingDeg - 360) < 1e-6,
|
||||
);
|
||||
});
|
||||
|
||||
test('the two projections are computed once per segment and chained', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(p, { tripId: 'full' }, fix(0, 100, 0));
|
||||
const out = {};
|
||||
const first = playback(1, 2, fix(0, 100, 0), fix(30_000, 600, 0), 0.2);
|
||||
assert.ok(placeOnPath(binding, first.sample, first.segment, out));
|
||||
const cache = binding.segment;
|
||||
assert.equal(cache.fromSeq, 1);
|
||||
assert.ok(Math.abs(cache.sTo - 600) < 0.5);
|
||||
// Same segment, later frame: cached arcs, only the fraction moves.
|
||||
cache.sFrom = 100.25; // a sentinel a recompute would overwrite
|
||||
const frame = playback(1, 2, fix(0, 100, 0), fix(30_000, 600, 0), 0.4);
|
||||
assert.ok(placeOnPath(binding, frame.sample, frame.segment, out));
|
||||
assert.equal(cache.sFrom, 100.25);
|
||||
// Next segment starts at the old to-report: its arc is reused.
|
||||
cache.sTo = 600.5;
|
||||
const next = playback(2, 3, fix(30_000, 600, 0), fix(60_000, 1100, 0), 0);
|
||||
assert.ok(placeOnPath(binding, next.sample, next.segment, out));
|
||||
assert.equal(cache.sFrom, 600.5);
|
||||
assert.ok(Math.abs(cache.sTo - 1100) < 0.5);
|
||||
});
|
||||
|
||||
test('a parked train sits on the line at its report', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(p, { tripId: 'full' }, fix(0, 700, 20));
|
||||
const out = {};
|
||||
const parked = playback(3, 3, fix(0, 700, 20), fix(0, 700, 20), 1);
|
||||
assert.ok(placeOnPath(binding, parked.sample, parked.segment, out));
|
||||
assert.equal(out.lat, 0, 'pulled onto the track');
|
||||
assert.ok(Math.abs(out.lon - 700 * D) < 1e-6);
|
||||
});
|
||||
|
||||
test('a segment whose reports do not fit the line keeps the straight line', () => {
|
||||
const p = pack();
|
||||
const binding = bindTrainPath(p, { tripId: 'full' }, fix(0, 100, 0));
|
||||
const out = {};
|
||||
const off = playback(1, 2, fix(0, 100, 0), fix(30_000, 800, 600), 0.5);
|
||||
assert.equal(placeOnPath(binding, off.sample, off.segment, out), false);
|
||||
assert.equal(binding.segment.ok, false);
|
||||
// No playback position yet, or stale report samples: nothing to place.
|
||||
assert.equal(
|
||||
placeOnPath(binding, { fromSeq: -1, toSeq: -1 }, off.segment, out),
|
||||
false,
|
||||
);
|
||||
const stale = playback(1, 2, fix(0, 100, 0), fix(30_000, 600, 0), 0.5);
|
||||
stale.segment.to.seq = 9;
|
||||
assert.equal(placeOnPath(binding, stale.sample, stale.segment, out), false);
|
||||
assert.equal(placeOnPath(null, stale.sample, stale.segment, out), false);
|
||||
});
|
||||
@@ -0,0 +1,577 @@
|
||||
/**
|
||||
* @module layers/rail/policy
|
||||
* @description Constants and pure decisions for the Rail layer. No Cesium
|
||||
* scene state, no network: everything here is exercised by node:test.
|
||||
*
|
||||
* Motion between reports is the Transit layer's delayed playback
|
||||
* (src/layers/transit/movement.js over src/data/contactPlayback.js), so the
|
||||
* report-age rules here are Transit's too.
|
||||
*/
|
||||
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import {
|
||||
RAIL_CATEGORIES,
|
||||
RAIL_POSITION_SOURCES,
|
||||
} from '../../data/railFeeds.js';
|
||||
import { displayMotion } from '../transit/movement.js';
|
||||
import { FIX_FLAGS, readFix } from '../../data/contactPlayback.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import {
|
||||
stopClock,
|
||||
stopLateMinutes,
|
||||
stopName,
|
||||
stopRoleIndices,
|
||||
} from './stopLabels.js';
|
||||
|
||||
export const RAIL_SELECTED_OVERLAY_SOURCE_ID = 'rail-selected';
|
||||
export const RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS = Object.freeze({
|
||||
cohortLimit: 1,
|
||||
collisionCapacity: 0,
|
||||
moving: true,
|
||||
});
|
||||
|
||||
/** Poll interval (ms), matching the proxy's 15 s cache window. */
|
||||
export const RAIL_POLL_MS = 15_000;
|
||||
/**
|
||||
* Feeds activate below this camera altitude, with hysteresis. Rail networks
|
||||
* are regional, so the gate is Transit's: low enough that a whole-continent
|
||||
* view does not poll every operator at once.
|
||||
*/
|
||||
export const ACTIVATION_ALTITUDE_M = 3_000_000;
|
||||
export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 150_000;
|
||||
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 150_000;
|
||||
export const CAMERA_DEBOUNCE_MS = 340;
|
||||
export const CAMERA_PERCENTAGE_CHANGED = 0.05;
|
||||
/** A feed already active stays active this far past its coverage edge. */
|
||||
export const RANGE_SLACK_KM = 40;
|
||||
export const MAX_TRAINS_TOTAL = 5_000;
|
||||
/** A train a feed stops listing for this many polls in a row is removed. */
|
||||
export const MISSED_POLLS_TO_DROP = 2;
|
||||
/** A report older than this is not drawn (a frozen feed empties, it does not lie). */
|
||||
export const TRAIN_MAX_FIX_AGE_MS = 10 * 60_000;
|
||||
/** A feed whose operator has not answered for this long reads as stale. */
|
||||
export const FEED_STALE_AFTER_MS = 90_000;
|
||||
/** ...and for this long, its trains are removed. */
|
||||
export const FEED_EVICT_AFTER_MS = 5 * 60_000;
|
||||
/** A stamp this far ahead of the fetch is a clock fault, bounded by the fetch. */
|
||||
export const FUTURE_STAMP_TOLERANCE_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Where a drawn train's position may come from: the operator's GPS, or the
|
||||
* station or timing point its signalling last reported. No train is placed
|
||||
* or moved from a timetable; between reports it only glides along its line
|
||||
* behind real time, as Transit's vehicles do. Every source the registry
|
||||
* knows (RAIL_POSITION_SOURCES) is a live one.
|
||||
*/
|
||||
export const RAIL_LIVE_POSITION_SOURCES = RAIL_POSITION_SOURCES;
|
||||
|
||||
/**
|
||||
* Whether a feed (a registry or catalog entry) or a train record reports
|
||||
* live positions. Without a stated source, GPS is meant.
|
||||
* @param {string|null|undefined} source `feed.positions` or
|
||||
* `record.positionSource`.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isLiveRailPositionSource(source) {
|
||||
return RAIL_LIVE_POSITION_SOURCES.includes(source ?? 'gps');
|
||||
}
|
||||
/**
|
||||
* A feed catalog that fails is asked for again after CATALOG_RETRY_FIRST_MS,
|
||||
* then twice as long after each failure in a row, up to CATALOG_RETRY_MAX_MS.
|
||||
*/
|
||||
export const CATALOG_RETRY_FIRST_MS = 30_000;
|
||||
export const CATALOG_RETRY_MAX_MS = 10 * 60_000;
|
||||
|
||||
/**
|
||||
* How long the catalog waits after its nth failure in a row (ms).
|
||||
* @param {number} failures 1 after the first.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function railCatalogRetryDelayMs(failures) {
|
||||
return Math.min(
|
||||
CATALOG_RETRY_MAX_MS,
|
||||
CATALOG_RETRY_FIRST_MS * 2 ** Math.max(0, failures - 1),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Floor cells a moving train reaches cold are warmed in batches: at most
|
||||
* COLD_CELLS_PER_FLUSH per flush, COLD_CELL_FLUSH_MS after the first one is
|
||||
* queued, and a cell asked for is not asked again for COLD_CELL_RETRY_MS. A
|
||||
* long-distance train crosses a 0.001° cell (about 111 m) every few seconds.
|
||||
*/
|
||||
export const COLD_CELLS_PER_FLUSH = 64;
|
||||
export const COLD_CELL_FLUSH_MS = 1_000;
|
||||
/**
|
||||
* Floor warming shares `/api/terrain/heights` with every other layer: 90
|
||||
* requests a minute per client, 64 points each. Rail's budget refills at
|
||||
* FLOOR_CELLS_PER_MINUTE cells a minute and holds at most FLOOR_CELLS_BURST,
|
||||
* so no minute spends more than the two together (1,520 cells, about 24
|
||||
* requests). It is spent only on trains within FLOOR_WARM_MAX_DIST_KM of the
|
||||
* camera and on the selected trip's stops, the selected train first, then
|
||||
* the nearest, so hundreds of trains in view (Paris, the Ruhr) cannot use up
|
||||
* the limit and leave every layer without floors.
|
||||
*/
|
||||
export const FLOOR_CELLS_PER_MINUTE = 1_200;
|
||||
export const FLOOR_CELLS_BURST = COLD_CELLS_PER_FLUSH * 5;
|
||||
export const FLOOR_WARM_MAX_DIST_KM = 30;
|
||||
export const COLD_CELL_RETRY_MS = 5_000;
|
||||
/**
|
||||
* Track heights on photorealistic tiles: the rendered mesh is sampled at
|
||||
* points on the train's own line (where the draped line is the track bed
|
||||
* or the deck), in buckets of 1/TRACK_SAMPLE_GRID degree (about 55 m),
|
||||
* at most TRACK_SAMPLES_PER_FLUSH per flush, for trains within
|
||||
* TRACK_SAMPLE_MAX_DIST_KM of a camera at most TRACK_SAMPLE_MAX_CAMERA_M
|
||||
* above the floor there, and only while the tileset reports its tiles
|
||||
* loaded: a higher camera, or tiles still streaming, reads coarse tiles,
|
||||
* whose height under a viaduct is the valley's (the failure
|
||||
* src/services/meshFloorSampler.js records). A sample is kept only within
|
||||
* TRACK_PRIOR_BELOW_M / TRACK_PRIOR_ABOVE_M of the floor under it, and is
|
||||
* read again after TRACK_SAMPLE_REFRESH_MS: the new reading replaces it
|
||||
* when the camera is no higher than it was, or once the old one is
|
||||
* TRACK_SAMPLE_MAX_AGE_MS old.
|
||||
*/
|
||||
export const TRACK_SAMPLE_GRID = 2000;
|
||||
export const TRACK_SAMPLES_PER_FLUSH = 8;
|
||||
export const TRACK_SAMPLE_RETRY_MS = 4_000;
|
||||
export const TRACK_SAMPLE_MAX_CAMERA_M = 5_000;
|
||||
export const TRACK_SAMPLE_MAX_DIST_KM = 8;
|
||||
export const TRACK_PRIOR_BELOW_M = 25;
|
||||
export const TRACK_PRIOR_ABOVE_M = 80;
|
||||
export const TRACK_SAMPLE_REFRESH_MS = 30_000;
|
||||
export const TRACK_SAMPLE_MAX_AGE_MS = 5 * 60_000;
|
||||
/**
|
||||
* A train's drawn height follows its target height no faster than a
|
||||
* railway climbs: TRACK_MAX_GRADE of the distance it moved (lines rarely
|
||||
* exceed 4%), plus TRACK_SETTLE_MPS while it stands, so a roof or overpass
|
||||
* sampled under it is a bump, not a jump. It snaps to a better source (a
|
||||
* real floor replacing a fallback, or any floor replacing the ellipsoid)
|
||||
* and after a jump of more than TRACK_SNAP_M.
|
||||
*/
|
||||
export const TRACK_MAX_GRADE = 0.05;
|
||||
export const TRACK_SETTLE_MPS = 0.5;
|
||||
export const TRACK_SNAP_M = 2_000;
|
||||
export const MARKER_PIXEL_SIZE = 18;
|
||||
export const SELECTED_PIXEL_SIZE = 28;
|
||||
export const SELECTED_CARD_REFRESH_MS = 250;
|
||||
/** While a train is selected, every other train is drawn at this opacity. */
|
||||
export const UNSELECTED_TRAIN_ALPHA = 0.35;
|
||||
/**
|
||||
* The faint route network is drawn in full below the first altitude, fades
|
||||
* out above it and is not drawn at all above the second (m). Above that the
|
||||
* lines are clutter at the scale of a whole region, and cost frames.
|
||||
*/
|
||||
export const NETWORK_FULL_BELOW_M = 150_000;
|
||||
export const NETWORK_HIDDEN_ABOVE_M = 200_000;
|
||||
/** The network's opacity, and its share of that while a train is selected. */
|
||||
export const NETWORK_ALPHA = 0.4;
|
||||
export const NETWORK_SELECTED_DIM = 0.4;
|
||||
export const NETWORK_WIDTH_PX = 2;
|
||||
/**
|
||||
* A feed out of use this long gives back its network, path pack and parsed
|
||||
* schedule pack; it loads them again when next used (ms).
|
||||
*/
|
||||
export const FEED_RELEASE_AFTER_MS = 10 * 60_000;
|
||||
/** The selected train's line: the part ahead, and the part travelled. */
|
||||
export const ROUTE_AHEAD_WIDTH_PX = 5;
|
||||
export const ROUTE_TRAVELLED_ALPHA = 0.3;
|
||||
/** How often the selected line's travelled/ahead split follows the train. */
|
||||
export const ROUTE_SPLIT_INTERVAL_MS = 250;
|
||||
/** How often the selected train's stops, labels and card are refreshed. */
|
||||
export const STOP_REFRESH_MS = 1_000;
|
||||
/**
|
||||
* How long the follow camera glides to another feed's copy of the selected
|
||||
* train when the selection moves to it (ms), so it neither jumps nor lets go.
|
||||
*/
|
||||
export const FOLLOW_HANDOVER_MS = 1_200;
|
||||
|
||||
/**
|
||||
* Category palette. Warm to cool with distance served, and none of the colours
|
||||
* the Transit modes, flights (white/cyan), military (amber) or vessels use, so
|
||||
* a train never reads as a bus drawn by the other layer.
|
||||
*/
|
||||
export const RAIL_CATEGORY_COLORS = Object.freeze({
|
||||
transit: '#FF7A59',
|
||||
local: '#F2D04B',
|
||||
regional: '#7BE495',
|
||||
national: '#5AB8FF',
|
||||
international: '#C58BFF',
|
||||
});
|
||||
|
||||
/** Panel and card words for each category. */
|
||||
export const RAIL_CATEGORY_LABELS = Object.freeze({
|
||||
transit: msg('Urban rail'),
|
||||
local: msg('Local rail'),
|
||||
regional: msg('Regional rail'),
|
||||
national: msg('National rail'),
|
||||
international: msg('International rail'),
|
||||
});
|
||||
|
||||
/** Card words for what runs on the track, shared with the Transit layer's. */
|
||||
const RAIL_MODE_WORDS = Object.freeze({
|
||||
rail: msg('Train'),
|
||||
metro: msg('Subway'),
|
||||
tram: msg('Tram'),
|
||||
});
|
||||
|
||||
/** Default visibility: every category on. */
|
||||
export const DEFAULT_RAIL_CATEGORY_VISIBILITY = Object.freeze(
|
||||
Object.fromEntries(RAIL_CATEGORIES.map((category) => [category, true])),
|
||||
);
|
||||
|
||||
/**
|
||||
* Normalise requested category toggles against the current ones. Unknown keys
|
||||
* are ignored and non-boolean values keep the current setting, so a malformed
|
||||
* share link can hide nothing it did not name.
|
||||
* @param {Record<string, unknown>} params
|
||||
* @param {Record<string, boolean>} [current]
|
||||
* @returns {Record<string, boolean>}
|
||||
*/
|
||||
export function normalizeRailCategories(
|
||||
params,
|
||||
current = DEFAULT_RAIL_CATEGORY_VISIBILITY,
|
||||
) {
|
||||
const next = {};
|
||||
for (const category of RAIL_CATEGORIES) {
|
||||
next[category] =
|
||||
typeof params?.[category] === 'boolean'
|
||||
? params[category]
|
||||
: current[category] !== false;
|
||||
}
|
||||
return next;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stable key for a train across polls. Prefixed so it can never equal a
|
||||
* Transit vehicle key for the same physical train in a shared pick registry.
|
||||
* @param {string} feedId
|
||||
* @param {string} trainId
|
||||
* @returns {string}
|
||||
*/
|
||||
export function railTrainKey(feedId, trainId) {
|
||||
return `rail:${feedId}:${trainId}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* When a report was made, in ms: the train's own stamp, else the fetch time.
|
||||
* @param {object} record
|
||||
* @param {number|null} [fetchedAtMs]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function trainReportTimeMs(record, fetchedAtMs = null) {
|
||||
const seconds = Number(record?.timestamp);
|
||||
if (Number.isFinite(seconds) && seconds > 0) return seconds * 1000;
|
||||
if (Number.isFinite(fetchedAtMs)) return fetchedAtMs;
|
||||
return Date.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Age of a report in ms (never negative). An unstamped record is aged from
|
||||
* the snapshot's fetch time, never from now.
|
||||
* @param {object} record
|
||||
* @param {number} nowMs
|
||||
* @param {number|null} [fetchedAtMs]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function trainFixAgeMs(record, nowMs, fetchedAtMs = null) {
|
||||
const seconds = Number(record?.timestamp);
|
||||
if (Number.isFinite(seconds) && seconds > 0)
|
||||
return Math.max(0, nowMs - seconds * 1000);
|
||||
if (Number.isFinite(fetchedAtMs)) return Math.max(0, nowMs - fetchedAtMs);
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Whether a report is too old to draw. */
|
||||
export function isStaleTrainFix(record, nowMs, fetchedAtMs = null) {
|
||||
return trainFixAgeMs(record, nowMs, fetchedAtMs) > TRAIN_MAX_FIX_AGE_MS;
|
||||
}
|
||||
|
||||
/** The movement module's speed ceilings are keyed by Transit mode names. */
|
||||
export function playbackModeFor(railMode) {
|
||||
return railMode === 'metro'
|
||||
? 'subway'
|
||||
: railMode === 'tram'
|
||||
? 'tram'
|
||||
: 'rail';
|
||||
}
|
||||
|
||||
/** Two reports closer than this are one place: a parked train's jitter (m). */
|
||||
export const FOLLOW_MIN_MOVE_M = 15;
|
||||
|
||||
const lastFix = {};
|
||||
const priorFix = {};
|
||||
|
||||
/** How far apart a track's last two reports are (m), 0 with fewer. */
|
||||
function lastReportsApartM(track) {
|
||||
if (!track || track.count < 2) return 0;
|
||||
const to = readFix(track, track.count - 1, lastFix);
|
||||
const from = readFix(track, track.count - 2, priorFix);
|
||||
if (from.epoch !== to.epoch || to.flags & FIX_FLAGS.BREAK) return 0;
|
||||
const kx = 111_320 * Math.cos((((from.lat + to.lat) / 2) * Math.PI) / 180);
|
||||
const dLon = ((((to.lon - from.lon + 180) % 360) + 360) % 360) - 180;
|
||||
return Math.hypot(dLon * kx, (to.lat - from.lat) * 111_320);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the camera follows a train once it is selected, as it follows a
|
||||
* tracked aircraft: its reports are recent, and it is moving on its playback
|
||||
* now, waits at a stop with its next move already reported, or is between
|
||||
* reports (playback waiting for the next one) after its last two reports
|
||||
* moved it. Any other train (parked, known from a single report, or not
|
||||
* heard from lately) gets one fly-to.
|
||||
* @param {{sample?: object, track?: object}|null} entry Runtime entry with
|
||||
* playback state.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function railTrainFollowable(entry) {
|
||||
const sample = entry?.sample;
|
||||
if (!sample || displayMotion(entry, 0).word === 'NO FIX') return false;
|
||||
if (sample.phase === 'playing' && sample.segmentSpeedMps > 0) return true;
|
||||
if (
|
||||
sample.phase === 'playing' &&
|
||||
sample.motion === 'stopped' &&
|
||||
Number.isFinite(sample.nextMotionT) &&
|
||||
sample.nextMotionT > sample.displayT
|
||||
)
|
||||
return true;
|
||||
return lastReportsApartM(entry.track) >= FOLLOW_MIN_MOVE_M;
|
||||
}
|
||||
|
||||
/**
|
||||
* The follow camera's offset from the train in east-north-up metres: the
|
||||
* shared world-focus framing for a train (its range and pitch) seen along the
|
||||
* camera's current heading, so taking the train does not swing the view round.
|
||||
* @param {{rangeM: number, pitchDeg: number}} framing
|
||||
* @param {number} headingRad
|
||||
* @returns {{x: number, y: number, z: number}}
|
||||
*/
|
||||
export function railFollowOffset(framing, headingRad) {
|
||||
const heading = Number.isFinite(headingRad) ? headingRad : 0;
|
||||
const pitch = (framing.pitchDeg * Math.PI) / 180;
|
||||
const across = framing.rangeM * Math.cos(pitch);
|
||||
return {
|
||||
x: -Math.sin(heading) * across,
|
||||
y: -Math.cos(heading) * across,
|
||||
z: -Math.sin(pitch) * framing.rangeM,
|
||||
};
|
||||
}
|
||||
|
||||
// Tools and the server may import this module, so no catalogue here: the
|
||||
// layer passes the UI's t().
|
||||
function englishText(text, values) {
|
||||
return String(text).replace(/\{(\w+)\}/g, (match, key) =>
|
||||
values && key in values ? String(values[key]) : match,
|
||||
);
|
||||
}
|
||||
|
||||
/** Card words for where a train's position comes from. */
|
||||
const RAIL_POSITION_SOURCE_WORDS = Object.freeze({
|
||||
gps: msg('Live GPS'),
|
||||
event: msg('Estimated from station reports'),
|
||||
});
|
||||
|
||||
/** The card never grows past this many detail lines. */
|
||||
export const RAIL_CARD_MAX_LINES = 6;
|
||||
|
||||
/**
|
||||
* The card's title: the route when the feed names one, else the trip's
|
||||
* headsign, else the vehicle's own label, else its id.
|
||||
* @param {object} record
|
||||
* @param {string|null} headsign
|
||||
* @param {(text: string, values?: object) => string} t
|
||||
* @returns {string}
|
||||
*/
|
||||
function railCardTitle(record, headsign, t) {
|
||||
const to = headsign ? t('To {headsign}', { headsign }) : '';
|
||||
if (record.routeId) {
|
||||
const route = t('Route {route}', { route: record.routeId });
|
||||
return `🚆 ${to ? `${route} · ${to}` : route}`;
|
||||
}
|
||||
if (to) return `🚆 ${to}`;
|
||||
const label =
|
||||
typeof record.label === 'string' && record.label.trim()
|
||||
? record.label.trim()
|
||||
: '';
|
||||
if (label && label !== record.id) return `🚆 ${label}`;
|
||||
return `🚆 ${t('Vehicle {vehicle}', { vehicle: label || record.id })}`;
|
||||
}
|
||||
|
||||
/** "Next Yonkers 14:32 T−4 (+3 min late)" / "Prev Riverdale 14:24 T+3". */
|
||||
function stopLine(stop, which, t) {
|
||||
const values = {
|
||||
stop: stopName(stop),
|
||||
time: stopClock(stop),
|
||||
relative: stop.relative || '',
|
||||
};
|
||||
const line = (
|
||||
which === 'next'
|
||||
? t('Next {stop} {time} {relative}', values)
|
||||
: t('Prev {stop} {time} {relative}', values)
|
||||
)
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim();
|
||||
const late = which === 'next' ? stopLateMinutes(stop) : 0;
|
||||
return late > 0
|
||||
? `${line} ${t('(+{minutes} min late)', { minutes: late })}`
|
||||
: line;
|
||||
}
|
||||
|
||||
/**
|
||||
* Card copy for the selected train. The status words, report-age wording and
|
||||
* "shown behind" note are the Transit card's, so they read the same.
|
||||
*
|
||||
* With the trip's stops (see stopLabels.js for the stop shape) the card names
|
||||
* the next and previous stops; the card stays within RAIL_CARD_MAX_LINES by
|
||||
* dropping its least useful lines first.
|
||||
*
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {object} record Train record from the snapshot.
|
||||
* @param {number} nowMs
|
||||
* @param {number|null} [fetchedAtMs]
|
||||
* @param {object|null} [entry] Runtime entry with playback state.
|
||||
* @param {(text: string, values?: object) => string} [t]
|
||||
* @param {{stops?: object[]|null, headsign?: string|null}|null} [trip] The
|
||||
* trip's stops and headsign from the feed's schedule pack, when known.
|
||||
* @returns {{title: string, details: string[]}}
|
||||
*/
|
||||
export function buildRailSelectionCopy(
|
||||
feed,
|
||||
record,
|
||||
nowMs,
|
||||
fetchedAtMs = null,
|
||||
entry = null,
|
||||
t = englishText,
|
||||
trip = null,
|
||||
) {
|
||||
const headsign =
|
||||
(typeof trip?.headsign === 'string' && trip.headsign.trim()) ||
|
||||
(typeof record.headsign === 'string' && record.headsign.trim()) ||
|
||||
null;
|
||||
const title = railCardTitle(record, headsign, t);
|
||||
const category = t(RAIL_CATEGORY_LABELS[record.category] || 'Train');
|
||||
const mode = t(RAIL_MODE_WORDS[record.mode] || RAIL_MODE_WORDS.rail);
|
||||
/** Lines with a rank: when the card is too long, the highest ranks go. */
|
||||
const lines = [];
|
||||
const add = (rank, text) => lines.push({ rank, text });
|
||||
add(0, `${category} · ${mode} · ${feed.name} · ${feed.region}`);
|
||||
|
||||
const shown = entry ? displayMotion(entry, nowMs) : null;
|
||||
const motion =
|
||||
shown?.word === 'STOPPED'
|
||||
? t('Stopped', { context: 'vehicle motion' })
|
||||
: shown?.word === 'NO FIX'
|
||||
? t('No recent fix')
|
||||
: shown?.word === 'WAITING'
|
||||
? t('Waiting for update')
|
||||
: shown
|
||||
? t('Moving')
|
||||
: '';
|
||||
const sourceWord = RAIL_POSITION_SOURCE_WORDS[record.positionSource];
|
||||
const source = sourceWord ? t(sourceWord) : '';
|
||||
if (motion || source)
|
||||
add(1, motion && source ? `${motion} · ${source}` : motion || source);
|
||||
|
||||
const stops = Array.isArray(trip?.stops) ? trip.stops : [];
|
||||
const roles = stopRoleIndices(stops);
|
||||
if (roles.next >= 0) add(2, stopLine(stops[roles.next], 'next', t));
|
||||
if (roles.previous >= 0)
|
||||
add(3, stopLine(stops[roles.previous], 'previous', t));
|
||||
const haveStops = roles.next >= 0 || roles.previous >= 0;
|
||||
|
||||
const ageS = Math.round(
|
||||
(Number.isFinite(entry?.sample?.latestReportAgeMs)
|
||||
? entry.sample.latestReportAgeMs
|
||||
: trainFixAgeMs(record, nowMs, fetchedAtMs)) / 1000,
|
||||
);
|
||||
const reported =
|
||||
ageS < 90
|
||||
? t('Reported {seconds} s ago', { seconds: ageS })
|
||||
: t('Reported {minutes} min ago', { minutes: Math.floor(ageS / 60) });
|
||||
const ownTime =
|
||||
Number.isFinite(record.timestamp) &&
|
||||
record.timestamp > 0 &&
|
||||
(!record.timestampSource || record.timestampSource === 'vehicle');
|
||||
const lagS = Number.isFinite(entry?.sample?.actualDelayMs)
|
||||
? Math.max(0, Math.round(entry.sample.actualDelayMs / 1000))
|
||||
: null;
|
||||
add(
|
||||
4,
|
||||
(ownTime ? reported : t('{reported} (feed time)', { reported })) +
|
||||
(lagS === null
|
||||
? ''
|
||||
: ` · ${t('shown {seconds} s behind', { seconds: lagS })}`),
|
||||
);
|
||||
|
||||
const reportedMotion = [];
|
||||
if (Number.isFinite(record.speedMps))
|
||||
reportedMotion.push(
|
||||
t('reported {speed} km/h', { speed: Math.round(record.speedMps * 3.6) }),
|
||||
);
|
||||
if (Number.isFinite(record.bearing))
|
||||
reportedMotion.push(
|
||||
t('reported hdg {heading}°', {
|
||||
heading: roundHeadingDegrees(record.bearing),
|
||||
}),
|
||||
);
|
||||
if (reportedMotion.length) add(7, reportedMotion.join(' · '));
|
||||
// The feed's own stop id says less than the schedule pack's stop names.
|
||||
if (!haveStops) {
|
||||
if (record.status === 'STOPPED_AT' && record.stopId)
|
||||
add(8, t('Last report: stopped at stop {stop}', { stop: record.stopId }));
|
||||
else if (record.status === 'INCOMING_AT' && record.stopId)
|
||||
add(
|
||||
8,
|
||||
t('Last report: arriving at stop {stop}', { stop: record.stopId }),
|
||||
);
|
||||
else if (record.status === 'IN_TRANSIT_TO' && record.stopId)
|
||||
add(8, t('Last report: next stop {stop}', { stop: record.stopId }));
|
||||
}
|
||||
if (record.mode === 'metro')
|
||||
add(5, t('Shown at street level · depth not in the feed'));
|
||||
add(
|
||||
6,
|
||||
`${t('Vehicle {vehicle}', { vehicle: record.id })}${record.label && record.label !== record.id ? ` · ${record.label}` : ''}`,
|
||||
);
|
||||
|
||||
// Past the limit, the highest ranks go; the rest keep their order.
|
||||
const kept = lines
|
||||
.map((line, order) => ({ ...line, order }))
|
||||
.sort((a, b) => a.rank - b.rank || a.order - b.order)
|
||||
.slice(0, RAIL_CARD_MAX_LINES)
|
||||
.sort((a, b) => a.order - b.order);
|
||||
return { title, details: kept.map((line) => line.text) };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared-host card for the selected train.
|
||||
* @param {string} key
|
||||
* @param {object|(() => object|null)} position Cartesian, or a getter the host
|
||||
* calls on every paint so the card follows the marker.
|
||||
* @param {{title: string, details: string[]}} copy
|
||||
* @param {string} category
|
||||
* @returns {object|null}
|
||||
*/
|
||||
export function createRailSelectedOverlayEntry(key, position, copy, category) {
|
||||
if (!key || !position) return null;
|
||||
return {
|
||||
id: String(key),
|
||||
position,
|
||||
variant: 'selected',
|
||||
selected: true,
|
||||
protected: true,
|
||||
paintLane: 'selected',
|
||||
collisionGroup: 'ambient-card',
|
||||
priority: Number.MAX_SAFE_INTEGER,
|
||||
title: copy.title,
|
||||
details: copy.details,
|
||||
accent: RAIL_CATEGORY_COLORS[category] || RAIL_CATEGORY_COLORS.local,
|
||||
interactive: false,
|
||||
anchorRadiusPx: 9,
|
||||
minAnchorGapPx: 11,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
edgeFade: 'keyhole',
|
||||
horizonCull: true,
|
||||
terrainOcclusion: false,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,521 @@
|
||||
// Pure Rail layer decisions: category toggles from share links, train keys,
|
||||
// report aging, the playback mode a train borrows from Transit, and the
|
||||
// selected-train card. The copy builder stays free of i18n (tools import
|
||||
// policy.js); the browser hands it t(), so a fake t() shows which words go
|
||||
// through translation.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
DEFAULT_RAIL_CATEGORY_VISIBILITY,
|
||||
RAIL_CARD_MAX_LINES,
|
||||
RAIL_CATEGORY_COLORS,
|
||||
TRAIN_MAX_FIX_AGE_MS,
|
||||
RAIL_LIVE_POSITION_SOURCES,
|
||||
buildRailSelectionCopy,
|
||||
createRailSelectedOverlayEntry,
|
||||
isLiveRailPositionSource,
|
||||
isStaleTrainFix,
|
||||
normalizeRailCategories,
|
||||
playbackModeFor,
|
||||
railTrainKey,
|
||||
trainFixAgeMs,
|
||||
trainReportTimeMs,
|
||||
} from './policy.js';
|
||||
import { RAIL_CATEGORIES } from '../../data/railFeeds.js';
|
||||
|
||||
const NOW = 1_794_000_000_000;
|
||||
const feed = { name: 'MBTA', region: 'Boston, MA' };
|
||||
|
||||
/** A t() that marks every string it translates and fills placeholders. */
|
||||
function fakeT() {
|
||||
const calls = [];
|
||||
const t = (text, values) => {
|
||||
calls.push({ text, values });
|
||||
const filled = String(text).replace(/\{(\w+)\}/g, (match, key) =>
|
||||
values && key in values ? String(values[key]) : match,
|
||||
);
|
||||
return `T(${filled})`;
|
||||
};
|
||||
return { t, calls };
|
||||
}
|
||||
|
||||
const stampedTrain = Object.freeze({
|
||||
id: '1712',
|
||||
label: 'Train 1712',
|
||||
routeId: 'CR-Worcester',
|
||||
category: 'local',
|
||||
mode: 'rail',
|
||||
lat: 42.35,
|
||||
lon: -71.2,
|
||||
bearing: 90,
|
||||
speedMps: 20,
|
||||
timestamp: (NOW - 30_000) / 1000,
|
||||
timestampSource: 'vehicle',
|
||||
status: 'IN_TRANSIT_TO',
|
||||
stopId: 'place-sstat',
|
||||
});
|
||||
|
||||
const unstampedMetro = Object.freeze({
|
||||
id: '77',
|
||||
label: '77',
|
||||
routeId: null,
|
||||
category: 'transit',
|
||||
mode: 'metro',
|
||||
lat: 42.36,
|
||||
lon: -71.06,
|
||||
});
|
||||
|
||||
test('every category is on by default', () => {
|
||||
assert.deepEqual(Object.keys(DEFAULT_RAIL_CATEGORY_VISIBILITY), [
|
||||
...RAIL_CATEGORIES,
|
||||
]);
|
||||
assert.ok(
|
||||
Object.values(DEFAULT_RAIL_CATEGORY_VISIBILITY).every((on) => on === true),
|
||||
);
|
||||
assert.deepEqual(
|
||||
normalizeRailCategories({}),
|
||||
DEFAULT_RAIL_CATEGORY_VISIBILITY,
|
||||
);
|
||||
assert.deepEqual(
|
||||
normalizeRailCategories(null),
|
||||
DEFAULT_RAIL_CATEGORY_VISIBILITY,
|
||||
);
|
||||
});
|
||||
|
||||
test('category toggles apply booleans and ignore anything else', () => {
|
||||
const current = {
|
||||
transit: true,
|
||||
local: false,
|
||||
regional: true,
|
||||
national: true,
|
||||
international: true,
|
||||
};
|
||||
assert.deepEqual(
|
||||
normalizeRailCategories(
|
||||
{
|
||||
transit: false,
|
||||
local: 'true',
|
||||
regional: 0,
|
||||
national: null,
|
||||
international: true,
|
||||
bus: false,
|
||||
},
|
||||
current,
|
||||
),
|
||||
{
|
||||
transit: false,
|
||||
local: false,
|
||||
regional: true,
|
||||
national: true,
|
||||
international: true,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
test('a share link can switch a hidden category back on', () => {
|
||||
const allOff = Object.fromEntries(RAIL_CATEGORIES.map((key) => [key, false]));
|
||||
assert.deepEqual(normalizeRailCategories({ regional: true }, allOff), {
|
||||
...allOff,
|
||||
regional: true,
|
||||
});
|
||||
});
|
||||
|
||||
test('train keys are namespaced so they never collide with Transit keys', () => {
|
||||
assert.equal(railTrainKey('mbta-rail', '1712'), 'rail:mbta-rail:1712');
|
||||
assert.notEqual(
|
||||
railTrainKey('mbta-rail', '1712'),
|
||||
railTrainKey('mbta-rail', '1713'),
|
||||
);
|
||||
assert.notEqual(
|
||||
railTrainKey('mta-lirr', '7'),
|
||||
railTrainKey('mta-metro-north', '7'),
|
||||
);
|
||||
});
|
||||
|
||||
test('a stamped report is aged from its own time', () => {
|
||||
assert.equal(trainFixAgeMs(stampedTrain, NOW), 30_000);
|
||||
// The fetch time does not override the train's own stamp.
|
||||
assert.equal(trainFixAgeMs(stampedTrain, NOW, NOW - 1_000), 30_000);
|
||||
assert.equal(trainReportTimeMs(stampedTrain, NOW - 1_000), NOW - 30_000);
|
||||
});
|
||||
|
||||
test('a stamp ahead of now ages to zero, never below', () => {
|
||||
assert.equal(trainFixAgeMs({ timestamp: (NOW + 5_000) / 1000 }, NOW), 0);
|
||||
});
|
||||
|
||||
test('an unstamped report is aged from the snapshot fetch time', () => {
|
||||
assert.equal(trainFixAgeMs(unstampedMetro, NOW, NOW - 45_000), 45_000);
|
||||
assert.equal(trainReportTimeMs(unstampedMetro, NOW - 45_000), NOW - 45_000);
|
||||
// Zero and negative stamps count as no stamp.
|
||||
assert.equal(trainFixAgeMs({ timestamp: 0 }, NOW, NOW - 2_000), 2_000);
|
||||
assert.equal(trainFixAgeMs({ timestamp: -1 }, NOW, NOW - 2_000), 2_000);
|
||||
// With neither a stamp nor a fetch time there is nothing to age from.
|
||||
assert.equal(trainFixAgeMs(unstampedMetro, NOW), 0);
|
||||
});
|
||||
|
||||
test('a report is stale only past the ten-minute limit', () => {
|
||||
assert.equal(TRAIN_MAX_FIX_AGE_MS, 10 * 60_000);
|
||||
const at = (ageMs) => ({ timestamp: (NOW - ageMs) / 1000 });
|
||||
assert.equal(isStaleTrainFix(at(TRAIN_MAX_FIX_AGE_MS), NOW), false);
|
||||
assert.equal(isStaleTrainFix(at(TRAIN_MAX_FIX_AGE_MS + 1_000), NOW), true);
|
||||
});
|
||||
|
||||
test('an unstamped report from an old snapshot is stale, not live', () => {
|
||||
const oldFetch = NOW - TRAIN_MAX_FIX_AGE_MS - 1;
|
||||
assert.equal(isStaleTrainFix(unstampedMetro, NOW, oldFetch), true);
|
||||
assert.equal(isStaleTrainFix(unstampedMetro, NOW, NOW - 60_000), false);
|
||||
});
|
||||
|
||||
test('rail modes map onto the Transit playback modes', () => {
|
||||
assert.equal(playbackModeFor('metro'), 'subway');
|
||||
assert.equal(playbackModeFor('tram'), 'tram');
|
||||
assert.equal(playbackModeFor('rail'), 'rail');
|
||||
assert.equal(playbackModeFor('monorail'), 'rail');
|
||||
assert.equal(playbackModeFor(undefined), 'rail');
|
||||
});
|
||||
|
||||
test('the card for a train with its own timestamp', () => {
|
||||
const { t, calls } = fakeT();
|
||||
const copy = buildRailSelectionCopy(feed, stampedTrain, NOW, NOW, null, t);
|
||||
assert.equal(copy.title, '🚆 T(Route CR-Worcester)');
|
||||
assert.deepEqual(copy.details, [
|
||||
'T(Local rail) · T(Train) · MBTA · Boston, MA',
|
||||
'T(Reported 30 s ago)',
|
||||
'T(reported 72 km/h) · T(reported hdg 90°)',
|
||||
'T(Last report: next stop place-sstat)',
|
||||
'T(Vehicle 1712) · Train 1712',
|
||||
]);
|
||||
// Operator names and regions are data, never sent through t().
|
||||
assert.ok(calls.every(({ text }) => !text.includes('MBTA')));
|
||||
});
|
||||
|
||||
test('the card for an unstamped metro train says the time is the feed’s', () => {
|
||||
const { t } = fakeT();
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
unstampedMetro,
|
||||
NOW,
|
||||
NOW - 120_000,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
assert.equal(copy.title, '🚆 T(Vehicle 77)');
|
||||
assert.deepEqual(copy.details, [
|
||||
'T(Urban rail) · T(Subway) · MBTA · Boston, MA',
|
||||
'T(T(Reported 2 min ago) (feed time))',
|
||||
'T(Shown at street level · depth not in the feed)',
|
||||
'T(Vehicle 77)',
|
||||
]);
|
||||
});
|
||||
|
||||
test('a header-stamped report is feed time even with a timestamp', () => {
|
||||
const { t } = fakeT();
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...stampedTrain, timestampSource: 'header' },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
assert.equal(copy.details[1], 'T(T(Reported 30 s ago) (feed time))');
|
||||
});
|
||||
|
||||
test('only metro trains carry the street-level note', () => {
|
||||
const { t } = fakeT();
|
||||
const note = 'T(Shown at street level · depth not in the feed)';
|
||||
for (const mode of ['rail', 'tram']) {
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...unstampedMetro, mode },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
assert.equal(copy.details.includes(note), false, mode);
|
||||
}
|
||||
const metro = buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...stampedTrain, mode: 'metro', category: 'transit' },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
assert.equal(metro.details.includes(note), true);
|
||||
});
|
||||
|
||||
test('playback state adds the motion word and the display delay', () => {
|
||||
const { t, calls } = fakeT();
|
||||
const entry = {
|
||||
sample: {
|
||||
latestReportAgeMs: 5_000,
|
||||
actualDelayMs: 42_400,
|
||||
phase: 'playing',
|
||||
motion: 'stopped',
|
||||
},
|
||||
};
|
||||
const copy = buildRailSelectionCopy(feed, stampedTrain, NOW, NOW, entry, t);
|
||||
assert.equal(copy.details[1], 'T(Stopped)');
|
||||
assert.deepEqual(calls.find(({ text }) => text === 'Stopped').values, {
|
||||
context: 'vehicle motion',
|
||||
});
|
||||
assert.equal(copy.details[2], 'T(Reported 5 s ago) · T(shown 42 s behind)');
|
||||
|
||||
const moving = buildRailSelectionCopy(
|
||||
feed,
|
||||
stampedTrain,
|
||||
NOW,
|
||||
NOW,
|
||||
{ sample: { ...entry.sample, motion: 'moving' } },
|
||||
t,
|
||||
);
|
||||
assert.equal(moving.details[1], 'T(Moving)');
|
||||
});
|
||||
|
||||
test('without a t() the card reads in plain English', () => {
|
||||
const copy = buildRailSelectionCopy(feed, stampedTrain, NOW, NOW);
|
||||
assert.equal(copy.title, '🚆 Route CR-Worcester');
|
||||
assert.equal(copy.details[0], 'Local rail · Train · MBTA · Boston, MA');
|
||||
assert.equal(copy.details[1], 'Reported 30 s ago');
|
||||
});
|
||||
|
||||
test('the selected card is accented in the category colour', () => {
|
||||
const copy = { title: 'Route 550', details: ['Local rail'] };
|
||||
const position = () => ({ x: 1, y: 2, z: 3 });
|
||||
for (const category of RAIL_CATEGORIES) {
|
||||
const card = createRailSelectedOverlayEntry(
|
||||
'rail:capmetro-rail:101',
|
||||
position,
|
||||
copy,
|
||||
category,
|
||||
);
|
||||
assert.equal(card.accent, RAIL_CATEGORY_COLORS[category], category);
|
||||
}
|
||||
const card = createRailSelectedOverlayEntry(
|
||||
'rail:capmetro-rail:101',
|
||||
position,
|
||||
copy,
|
||||
'bus',
|
||||
);
|
||||
assert.equal(card.accent, RAIL_CATEGORY_COLORS.local);
|
||||
assert.equal(card.id, 'rail:capmetro-rail:101');
|
||||
assert.equal(card.position, position);
|
||||
assert.equal(card.title, 'Route 550');
|
||||
assert.deepEqual(card.details, ['Local rail']);
|
||||
assert.equal(card.selected, true);
|
||||
});
|
||||
|
||||
test('no card without a key or a position', () => {
|
||||
const copy = { title: '', details: [] };
|
||||
assert.equal(
|
||||
createRailSelectedOverlayEntry('', () => null, copy),
|
||||
null,
|
||||
);
|
||||
assert.equal(createRailSelectedOverlayEntry('rail:a:1', null, copy), null);
|
||||
});
|
||||
|
||||
/** Two stops as the schedule pack's tripStops() lists them. */
|
||||
const tripStopsNearYonkers = Object.freeze([
|
||||
Object.freeze({
|
||||
stopId: 'riv',
|
||||
name: 'Riverdale',
|
||||
lat: 40.9,
|
||||
lon: -73.91,
|
||||
state: 'passed',
|
||||
expectedArrival: '14:23',
|
||||
expectedDeparture: '14:24',
|
||||
arrivalDelaySec: 180,
|
||||
departureDelaySec: 180,
|
||||
relative: 'T+3',
|
||||
}),
|
||||
Object.freeze({
|
||||
stopId: 'yon',
|
||||
name: 'Yonkers',
|
||||
lat: 40.93,
|
||||
lon: -73.9,
|
||||
state: 'next',
|
||||
atStop: false,
|
||||
expectedArrival: '14:32',
|
||||
expectedDeparture: '14:33',
|
||||
arrivalDelaySec: 200,
|
||||
departureDelaySec: 200,
|
||||
relative: 'T−4',
|
||||
}),
|
||||
]);
|
||||
|
||||
test('with the trip’s stops the card names the next and previous stops', () => {
|
||||
const { t } = fakeT();
|
||||
const copy = buildRailSelectionCopy(feed, stampedTrain, NOW, NOW, null, t, {
|
||||
stops: tripStopsNearYonkers,
|
||||
headsign: 'Poughkeepsie',
|
||||
});
|
||||
assert.equal(copy.title, '🚆 T(Route CR-Worcester) · T(To Poughkeepsie)');
|
||||
assert.deepEqual(copy.details, [
|
||||
'T(Local rail) · T(Train) · MBTA · Boston, MA',
|
||||
'T(Next Yonkers 14:32 T−4) T((+3 min late))',
|
||||
'T(Prev Riverdale 14:24 T+3)',
|
||||
'T(Reported 30 s ago)',
|
||||
'T(reported 72 km/h) · T(reported hdg 90°)',
|
||||
'T(Vehicle 1712) · Train 1712',
|
||||
]);
|
||||
// The feed's bare stop id is not repeated beside the stop names.
|
||||
assert.ok(copy.details.every((line) => !line.includes('place-sstat')));
|
||||
});
|
||||
|
||||
test('an on-time next stop has no lateness, and English reads plainly', () => {
|
||||
const onTime = tripStopsNearYonkers.map((stop) => ({
|
||||
...stop,
|
||||
arrivalDelaySec: 20,
|
||||
}));
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
stampedTrain,
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
undefined,
|
||||
{
|
||||
stops: onTime,
|
||||
},
|
||||
);
|
||||
assert.equal(copy.details[1], 'Next Yonkers 14:32 T−4');
|
||||
assert.equal(copy.details[2], 'Prev Riverdale 14:24 T+3');
|
||||
});
|
||||
|
||||
test('the card never grows past six lines', () => {
|
||||
const { t } = fakeT();
|
||||
const entry = {
|
||||
sample: {
|
||||
latestReportAgeMs: 5_000,
|
||||
actualDelayMs: 30_000,
|
||||
phase: 'playing',
|
||||
motion: 'moving',
|
||||
},
|
||||
};
|
||||
const busy = { ...stampedTrain, mode: 'metro', positionSource: 'gps' };
|
||||
const copy = buildRailSelectionCopy(feed, busy, NOW, NOW, entry, t, {
|
||||
stops: tripStopsNearYonkers,
|
||||
});
|
||||
assert.equal(copy.details.length, RAIL_CARD_MAX_LINES);
|
||||
assert.equal(RAIL_CARD_MAX_LINES, 6);
|
||||
// What stays: who, motion, next, previous, report age and the depth note;
|
||||
// the reported speed and the vehicle line give way first.
|
||||
assert.deepEqual(copy.details, [
|
||||
'T(Local rail) · T(Subway) · MBTA · Boston, MA',
|
||||
'T(Moving) · T(Live GPS)',
|
||||
'T(Next Yonkers 14:32 T−4) T((+3 min late))',
|
||||
'T(Prev Riverdale 14:24 T+3)',
|
||||
'T(Reported 5 s ago) · T(shown 30 s behind)',
|
||||
'T(Shown at street level · depth not in the feed)',
|
||||
]);
|
||||
// Without stops a full card also stays within the limit.
|
||||
const noStops = buildRailSelectionCopy(feed, busy, NOW, NOW, entry, t);
|
||||
assert.ok(noStops.details.length <= RAIL_CARD_MAX_LINES);
|
||||
});
|
||||
|
||||
test('the card says where the position comes from', () => {
|
||||
const { t } = fakeT();
|
||||
const words = {
|
||||
gps: 'T(Live GPS)',
|
||||
event: 'T(Estimated from station reports)',
|
||||
};
|
||||
for (const [positionSource, word] of Object.entries(words)) {
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...stampedTrain, positionSource },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
// No playback state: the source stands on its own line.
|
||||
assert.equal(copy.details[1], word, positionSource);
|
||||
}
|
||||
// A source the layer does not draw, a timetable's included, is never
|
||||
// named as one.
|
||||
for (const positionSource of ['psychic', 'schedule']) {
|
||||
const unknown = buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...stampedTrain, positionSource },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
);
|
||||
assert.equal(unknown.details[1], 'T(Reported 30 s ago)', positionSource);
|
||||
}
|
||||
});
|
||||
|
||||
test('only live positions are drawn: GPS and station reports', () => {
|
||||
assert.deepEqual([...RAIL_LIVE_POSITION_SOURCES], ['gps', 'event']);
|
||||
for (const source of ['gps', 'event', undefined, null])
|
||||
assert.equal(isLiveRailPositionSource(source), true, String(source));
|
||||
for (const source of ['schedule', 'psychic', ''])
|
||||
assert.equal(isLiveRailPositionSource(source), false, source);
|
||||
});
|
||||
|
||||
test('without a route the title prefers the headsign, then the label', () => {
|
||||
const { t } = fakeT();
|
||||
const lirr = { ...stampedTrain, routeId: null, id: '7259', label: '7259' };
|
||||
assert.equal(
|
||||
buildRailSelectionCopy(feed, lirr, NOW, NOW, null, t).title,
|
||||
'🚆 T(Vehicle 7259)',
|
||||
);
|
||||
assert.equal(
|
||||
buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...lirr, label: 'Train 2715' },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
).title,
|
||||
'🚆 Train 2715',
|
||||
);
|
||||
assert.equal(
|
||||
buildRailSelectionCopy(
|
||||
feed,
|
||||
{ ...lirr, headsign: 'Ronkonkoma' },
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
t,
|
||||
).title,
|
||||
'🚆 T(To Ronkonkoma)',
|
||||
);
|
||||
assert.equal(
|
||||
buildRailSelectionCopy(feed, lirr, NOW, NOW, null, t, {
|
||||
headsign: 'Babylon',
|
||||
stops: [],
|
||||
}).title,
|
||||
'🚆 T(To Babylon)',
|
||||
);
|
||||
assert.equal(
|
||||
buildRailSelectionCopy(feed, { ...lirr, label: null }, NOW, NOW, null, t)
|
||||
.title,
|
||||
'🚆 T(Vehicle 7259)',
|
||||
);
|
||||
});
|
||||
|
||||
test('the card names a platform stop by its station', () => {
|
||||
const stops = tripStopsNearYonkers.map((stop) => ({
|
||||
...stop,
|
||||
name: `${stop.name} Platform 2`,
|
||||
parentName: `${stop.name} Station`,
|
||||
}));
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
stampedTrain,
|
||||
NOW,
|
||||
NOW,
|
||||
null,
|
||||
undefined,
|
||||
{
|
||||
stops,
|
||||
},
|
||||
);
|
||||
assert.equal(copy.details[1], 'Next Yonkers Station 14:32 T−4 (+3 min late)');
|
||||
assert.equal(copy.details[2], 'Prev Riverdale Station 14:24 T+3');
|
||||
});
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,738 @@
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { classifyTrain, getRegisteredRailFeed } from '../../data/railFeeds.js';
|
||||
import {
|
||||
FEED_RELEASE_AFTER_MS,
|
||||
NETWORK_ALPHA,
|
||||
NETWORK_FULL_BELOW_M,
|
||||
NETWORK_HIDDEN_ABOVE_M,
|
||||
NETWORK_SELECTED_DIM,
|
||||
NETWORK_WIDTH_PX,
|
||||
RAIL_CATEGORY_COLORS,
|
||||
ROUTE_AHEAD_WIDTH_PX,
|
||||
ROUTE_SPLIT_INTERVAL_MS,
|
||||
ROUTE_TRAVELLED_ALPHA,
|
||||
STOP_REFRESH_MS,
|
||||
} from './policy.js';
|
||||
import {
|
||||
networkAltitudeFade,
|
||||
railNetworkLineSteps,
|
||||
splitFraction,
|
||||
} from './routeLines.js';
|
||||
import {
|
||||
RAIL_STOP_OVERLAY_SOURCE_ID,
|
||||
RAIL_STOP_OVERLAY_SOURCE_OPTIONS,
|
||||
createStopOverlayEntries,
|
||||
selectStopLabels,
|
||||
} from './stopLabels.js';
|
||||
|
||||
/** Longest slice of network building per task, so a frame is never held (ms). */
|
||||
const NETWORK_SLICE_MS = 6;
|
||||
/** The fade is applied in steps, so a slow zoom does not rewrite it per event. */
|
||||
const FADE_STEP = 0.05;
|
||||
/** Arc a route-bound train must cover before its direction is trusted (m). */
|
||||
const DIRECTION_EVIDENCE_M = 60;
|
||||
const STOP_DOT_PX = 5;
|
||||
const STOP_LABELLED_DOT_PX = 8;
|
||||
const STOP_DOT_OUTLINE = Object.freeze(cssColor('rgba(10, 14, 20, 0.9)'));
|
||||
/** Two drawn vertices closer than this are one (m), as the line drops repeats. */
|
||||
const REPEAT_M = 1e-3;
|
||||
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
|
||||
/** A category's colour (0..1 channels) at `alpha`. */
|
||||
function categoryColor(category, alpha) {
|
||||
const rgba =
|
||||
cssColor(RAIL_CATEGORY_COLORS[category] || RAIL_CATEGORY_COLORS.local) ||
|
||||
cssColor(RAIL_CATEGORY_COLORS.local);
|
||||
return [rgba[0], rgba[1], rgba[2], alpha];
|
||||
}
|
||||
|
||||
/**
|
||||
* Route lines for one Rail layer: the faint network of every active feed
|
||||
* (built once per path pack), the selected train's line split where the train
|
||||
* is, and the selected trip's stops as dots and labels.
|
||||
*
|
||||
* Every line is draped on the surface through the draw port: each feed's
|
||||
* network a set per category, the selected line one set whose segments are
|
||||
* coloured travelled or ahead, and the stops a set of dots.
|
||||
*
|
||||
* Nothing here runs per frame but the far-side test of the stops. The
|
||||
* network's opacity follows the camera on camera events; the split and the
|
||||
* stops follow the train on a timer that only runs while a train is
|
||||
* selected.
|
||||
*
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createRouteDisplay({
|
||||
state,
|
||||
services,
|
||||
parts,
|
||||
stops,
|
||||
timetable,
|
||||
}) {
|
||||
const { governorRequestRender } = services.render;
|
||||
const instance = (instances += 1);
|
||||
/** feedId → when the feed was last seen in use (ms). */
|
||||
const feedSeenAt = new Map();
|
||||
/** Releases idle feeds while the layer is off. */
|
||||
let releaseTimer = null;
|
||||
/** The selected line's set and the stop dots' set, made on first use. */
|
||||
let routeSet = null;
|
||||
let stopSet = null;
|
||||
/** The stop dots drawn now, as pushed to their set. */
|
||||
let stopItems = [];
|
||||
let timer = null;
|
||||
let ticks = 0;
|
||||
|
||||
/** The draw port, or null while the layer has no viewer. */
|
||||
function draw() {
|
||||
const viewer = state._viewer;
|
||||
return viewer && !viewer.isDestroyed?.() ? drawOf(viewer) : null;
|
||||
}
|
||||
|
||||
/** ECEF positions on the ellipsoid for a flat `[lat, lon, ...]` run, repeats dropped. */
|
||||
function positionsOf(coords) {
|
||||
const out = [];
|
||||
for (let i = 0; i + 1 < coords.length; i += 2) {
|
||||
const point = fromDegrees(coords[i + 1], coords[i], 0);
|
||||
if (out.length && distance(out[out.length - 1], point) < REPEAT_M)
|
||||
continue;
|
||||
out.push(point);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/** A set of draped lines, never picked. */
|
||||
function lineSet(id) {
|
||||
return draw()?.lines({ id, pickable: false, show: false }) ?? null;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Network
|
||||
|
||||
/**
|
||||
* Start building a feed's network from its decoded pack, in slices between
|
||||
* frames. Called once per pack by ingestion.
|
||||
* @param {string} feedId
|
||||
* @param {object} raw The pack's JSON body.
|
||||
*/
|
||||
function buildNetwork(feedId, raw) {
|
||||
const previous = state._networks.get(feedId);
|
||||
if (previous) dropNetwork(feedId);
|
||||
const feed = getRegisteredRailFeed(feedId);
|
||||
const categoryOf = (routeId) =>
|
||||
feed ? classifyTrain(feed, routeId)?.category || null : null;
|
||||
const network = {
|
||||
feedId,
|
||||
status: 'building',
|
||||
steps: railNetworkLineSteps(raw, categoryOf),
|
||||
timer: null,
|
||||
layers: new Map(),
|
||||
stats: null,
|
||||
};
|
||||
state._networks.set(feedId, network);
|
||||
const slice = () => {
|
||||
network.timer = null;
|
||||
if (state._networks.get(feedId) !== network) return;
|
||||
const started = performance.now();
|
||||
for (;;) {
|
||||
const next = network.steps.next();
|
||||
if (next.done) {
|
||||
network.steps = null;
|
||||
finishNetwork(network, next.value);
|
||||
return;
|
||||
}
|
||||
if (performance.now() - started > NETWORK_SLICE_MS) break;
|
||||
}
|
||||
network.timer = setTimeout(slice, 0);
|
||||
};
|
||||
network.timer = setTimeout(slice, 0);
|
||||
}
|
||||
|
||||
function finishNetwork(network, result) {
|
||||
network.status = 'ready';
|
||||
network.stats = {
|
||||
shapes: result.shapesIn,
|
||||
pointsIn: result.pointsIn,
|
||||
lines: result.lines.length,
|
||||
points: result.pointsOut,
|
||||
};
|
||||
if (!draw()) return;
|
||||
const byCategory = new Map();
|
||||
for (const line of result.lines) {
|
||||
if (!byCategory.has(line.category)) byCategory.set(line.category, []);
|
||||
byCategory.get(line.category).push(positionsOf(line.coords));
|
||||
}
|
||||
for (const [category, runs] of byCategory) {
|
||||
const style = { kind: 'solid', color: categoryColor(category, 0) };
|
||||
const items = [];
|
||||
for (const positions of runs) {
|
||||
if (positions.length < 2) continue;
|
||||
items.push({
|
||||
id: String(items.length),
|
||||
positions,
|
||||
widthPx: NETWORK_WIDTH_PX,
|
||||
mode: 'draped',
|
||||
style,
|
||||
pickable: false,
|
||||
});
|
||||
}
|
||||
if (!items.length) continue;
|
||||
const set = lineSet(
|
||||
`rail:${instance}:network:${network.feedId}:${category}`,
|
||||
);
|
||||
if (!set) continue;
|
||||
set.set(items);
|
||||
network.layers.set(category, { set, items, category, alpha: -1 });
|
||||
}
|
||||
applyNetwork();
|
||||
}
|
||||
|
||||
function dropNetwork(feedId) {
|
||||
const network = state._networks.get(feedId);
|
||||
if (!network) return;
|
||||
clearTimeout(network.timer);
|
||||
network.timer = null;
|
||||
network.steps = null;
|
||||
for (const layer of network.layers.values()) layer.set.dispose();
|
||||
network.layers.clear();
|
||||
state._networks.delete(feedId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show each feed's network while the feed is active, the category is on and
|
||||
* the camera is low enough, at an opacity set by altitude and selection.
|
||||
*/
|
||||
function applyNetwork() {
|
||||
const fade = state._networkFade;
|
||||
const selected = state._selectedKey !== null;
|
||||
let changed = false;
|
||||
for (const network of state._networks.values()) {
|
||||
// A feed held only for the selected train shows that train's line alone.
|
||||
const active =
|
||||
state._enabled &&
|
||||
state._activeFeeds.has(network.feedId) &&
|
||||
network.feedId !== state._heldFeedId;
|
||||
for (const [category, layer] of network.layers) {
|
||||
const alpha =
|
||||
active && state._categories[category] !== false
|
||||
? NETWORK_ALPHA * fade * (selected ? NETWORK_SELECTED_DIM : 1)
|
||||
: 0;
|
||||
const show = alpha > 0.001;
|
||||
if (layer.set.show !== show) {
|
||||
layer.set.show = show;
|
||||
changed = true;
|
||||
}
|
||||
if (show && Math.abs(layer.alpha - alpha) > 0.001) {
|
||||
const style = {
|
||||
kind: 'solid',
|
||||
color: categoryColor(layer.category, alpha),
|
||||
};
|
||||
for (const item of layer.items) item.style = style;
|
||||
layer.set.upsert(layer.items);
|
||||
layer.alpha = alpha;
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
if (changed) governorRequestRender('rail-network');
|
||||
}
|
||||
|
||||
/** Camera moved: recompute the altitude fade, applying it only on a step. */
|
||||
function onCamera() {
|
||||
const altitude = parts.viewport.cameraAltitude();
|
||||
const raw = networkAltitudeFade(
|
||||
altitude,
|
||||
NETWORK_FULL_BELOW_M,
|
||||
NETWORK_HIDDEN_ABOVE_M,
|
||||
);
|
||||
const fade = Math.round(raw / FADE_STEP) * FADE_STEP;
|
||||
if (fade === state._networkFade) return;
|
||||
state._networkFade = fade;
|
||||
applyNetwork();
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selected route
|
||||
|
||||
/**
|
||||
* The shape the selected train runs on: its binding, else its route's
|
||||
* longest.
|
||||
*/
|
||||
function routeShapeFor(entry) {
|
||||
const pack = state._pathPacks.get(entry.feedId)?.pack;
|
||||
if (entry.path?.path)
|
||||
return {
|
||||
shapeIndex: entry.path.shapeIndex,
|
||||
path: entry.path.path,
|
||||
binding: entry.path,
|
||||
};
|
||||
const routeId = entry.record?.routeId;
|
||||
if (!pack || !routeId) return null;
|
||||
let best = null;
|
||||
for (const index of pack.shapesForRoute(routeId)) {
|
||||
const path = pack.pathAt(index);
|
||||
if (path && (!best || path.length > best.path.length))
|
||||
best = { shapeIndex: index, path, binding: null };
|
||||
}
|
||||
return best;
|
||||
}
|
||||
|
||||
function dropRoute() {
|
||||
if (!state._route) return;
|
||||
routeSet?.clear();
|
||||
state._route = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw (or keep) the selected train's line. Rebuilt only when the train
|
||||
* moves to another shape; the split recolours its segments.
|
||||
*/
|
||||
function syncRoute() {
|
||||
const entry = state._trains.get(state._selectedKey);
|
||||
const shape = entry && state._enabled ? routeShapeFor(entry) : null;
|
||||
const port = shape ? draw() : null;
|
||||
if (!shape || !port) {
|
||||
if (state._route) {
|
||||
dropRoute();
|
||||
governorRequestRender('rail-route');
|
||||
}
|
||||
return;
|
||||
}
|
||||
const id = `${entry.key}\n${entry.feedId}\n${shape.shapeIndex}`;
|
||||
if (state._route?.id !== id) {
|
||||
dropRoute();
|
||||
const { path } = shape;
|
||||
const positions = [];
|
||||
// Arc length (m) of each drawn vertex, so each segment knows the arc
|
||||
// it spans, and the cumulative drawn length per path vertex, which
|
||||
// the split's fraction is measured on.
|
||||
const drawnS = [];
|
||||
const chordAt = new Float64Array(path.n);
|
||||
for (let i = 0; i < path.n; i++) {
|
||||
const point = fromDegrees(path.lon[i], path.lat[i], 0);
|
||||
const last = positions[positions.length - 1];
|
||||
const step = last ? distance(last, point) : 0;
|
||||
const repeat = last && step < REPEAT_M;
|
||||
if (i > 0) chordAt[i] = chordAt[i - 1] + (repeat ? 0 : step);
|
||||
if (!repeat) {
|
||||
positions.push(point);
|
||||
drawnS.push(path.s[i]);
|
||||
}
|
||||
}
|
||||
if (positions.length < 2) return;
|
||||
routeSet ||= lineSet(`rail:${instance}:route`);
|
||||
if (!routeSet) return;
|
||||
routeSet.show = true;
|
||||
const ahead = categoryColor(entry.category, 1);
|
||||
const travelled = categoryColor(entry.category, ROUTE_TRAVELLED_ALPHA);
|
||||
const midS = new Float64Array(positions.length - 1);
|
||||
for (let j = 0; j < midS.length; j++)
|
||||
midS[j] = (drawnS[j] + drawnS[j + 1]) / 2;
|
||||
const item = {
|
||||
id: 'route',
|
||||
positions,
|
||||
widthPx: ROUTE_AHEAD_WIDTH_PX,
|
||||
mode: 'draped',
|
||||
style: { kind: 'solid', color: ahead },
|
||||
segmentColors: new Array(midS.length).fill(ahead),
|
||||
pickable: false,
|
||||
};
|
||||
routeSet.set([item]);
|
||||
state._route = {
|
||||
id,
|
||||
item,
|
||||
ahead,
|
||||
travelled,
|
||||
midS,
|
||||
path,
|
||||
chordAt,
|
||||
binding: shape.binding,
|
||||
// A trip's own shape runs the way the trip does; a route's shape may
|
||||
// be drawn either way, so its direction is learnt from the train.
|
||||
direction: shape.binding?.via === 'trip' ? 1 : 0,
|
||||
firstS: shape.binding ? shape.binding.drawS : NaN,
|
||||
fraction: NaN,
|
||||
/** Segments drawn travelled, and which way: `${direction}:${count}`. */
|
||||
split: '1:0',
|
||||
ground: port.clampState?.() !== 'overlay',
|
||||
};
|
||||
governorRequestRender('rail-route');
|
||||
} else if (state._route.binding !== shape.binding) {
|
||||
// Rebound to the same shape (a new trip on it): follow the new binding.
|
||||
state._route.binding = shape.binding;
|
||||
state._route.firstS = shape.binding ? shape.binding.drawS : NaN;
|
||||
if (shape.binding?.via !== 'trip') state._route.direction = 0;
|
||||
}
|
||||
updateSplit();
|
||||
}
|
||||
|
||||
/**
|
||||
* Colour the segments behind the train travelled and the rest ahead: a
|
||||
* segment is behind it when the middle of its arc is.
|
||||
*/
|
||||
function updateSplit() {
|
||||
const route = state._route;
|
||||
if (!route) return;
|
||||
const binding = route.binding;
|
||||
const s = binding ? binding.drawS : NaN;
|
||||
if (route.direction === 0 && Number.isFinite(s)) {
|
||||
const moved = s - route.firstS;
|
||||
if (Math.abs(moved) >= DIRECTION_EVIDENCE_M)
|
||||
route.direction = Math.sign(moved);
|
||||
}
|
||||
const fraction =
|
||||
route.direction !== 0 && Number.isFinite(s)
|
||||
? splitFraction(route.path, route.chordAt, s)
|
||||
: NaN;
|
||||
// No position on the line yet: draw it all as ahead.
|
||||
route.fraction = Number.isFinite(fraction) ? fraction : NaN;
|
||||
const mids = route.midS;
|
||||
let behind = 0;
|
||||
if (Number.isFinite(fraction))
|
||||
for (let j = 0; j < mids.length; j++)
|
||||
if (route.direction > 0 ? mids[j] < s : mids[j] > s) behind += 1;
|
||||
const direction = Number.isFinite(fraction) ? route.direction : 1;
|
||||
const split = `${direction}:${behind}`;
|
||||
if (split === route.split) return;
|
||||
route.split = split;
|
||||
const colors = route.item.segmentColors;
|
||||
for (let j = 0; j < mids.length; j++) {
|
||||
const travelled =
|
||||
Number.isFinite(fraction) &&
|
||||
(route.direction > 0 ? mids[j] < s : mids[j] > s);
|
||||
colors[j] = travelled ? route.travelled : route.ahead;
|
||||
}
|
||||
routeSet?.upsert([route.item]);
|
||||
governorRequestRender('rail-route-split');
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stops
|
||||
|
||||
function stopDots() {
|
||||
stopSet ||=
|
||||
draw()?.points({
|
||||
id: `rail:${instance}:stops`,
|
||||
blend: 'translucent',
|
||||
pickable: false,
|
||||
}) ?? null;
|
||||
return stopSet;
|
||||
}
|
||||
|
||||
function clearStops() {
|
||||
stopItems = [];
|
||||
stopSet?.clear();
|
||||
state._trip = null;
|
||||
state._stopsSignature = '';
|
||||
state._stopLabelsSignature = '';
|
||||
state._stopAnchors.clear();
|
||||
state._overlayHost.setEntries(
|
||||
RAIL_STOP_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
RAIL_STOP_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
function anchorFor(stop) {
|
||||
const key = `${stop.stopId ?? ''}\n${stop.lat}\n${stop.lon}`;
|
||||
let anchor = state._stopAnchors.get(key);
|
||||
if (!anchor) {
|
||||
const { h, q } = parts.rendering.stopHeight(stop.lat, stop.lon);
|
||||
anchor = {
|
||||
lat: stop.lat,
|
||||
lon: stop.lon,
|
||||
h,
|
||||
q,
|
||||
position: fromDegrees(stop.lon, stop.lat, h),
|
||||
};
|
||||
state._stopAnchors.set(key, anchor);
|
||||
}
|
||||
return anchor.position;
|
||||
}
|
||||
|
||||
/**
|
||||
* Stops placed before their floor cell was warm stand on a fallback (the
|
||||
* ellipsoid at worst, which is drawn over the terrain far off its station
|
||||
* from a low camera): each refresh reads those again, and once one stands
|
||||
* better its dot and label are drawn again there.
|
||||
*/
|
||||
function settleAnchors() {
|
||||
let moved = false;
|
||||
for (const anchor of state._stopAnchors.values()) {
|
||||
if (anchor.q >= 2) continue;
|
||||
const { h, q } = parts.rendering.stopHeight(anchor.lat, anchor.lon);
|
||||
if (q < anchor.q || (q === anchor.q && Math.abs(h - anchor.h) < 1))
|
||||
continue;
|
||||
anchor.h = h;
|
||||
anchor.q = q;
|
||||
anchor.position = fromDegrees(anchor.lon, anchor.lat, h);
|
||||
moved = true;
|
||||
}
|
||||
if (moved) {
|
||||
state._stopsSignature = '';
|
||||
state._stopLabelsSignature = '';
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide the stop dots on the far side of the Earth. They are drawn over the
|
||||
* terrain, and the selected trip is drawn at any distance (viewport.js), so
|
||||
* the rendering pass hands over its horizon test every frame.
|
||||
* @param {(position: object) => boolean} facesCamera
|
||||
*/
|
||||
function cullStops(facesCamera) {
|
||||
if (!stopSet || !stopItems.length) return;
|
||||
let changed = null;
|
||||
for (const item of stopItems) {
|
||||
const shown = facesCamera(item.pos);
|
||||
if (item.show === shown) continue;
|
||||
item.show = shown;
|
||||
(changed ||= []).push(item);
|
||||
}
|
||||
if (changed) stopSet.upsert(changed);
|
||||
}
|
||||
|
||||
/** Ask the provider for the selected trip's stops and redraw what changed. */
|
||||
function refreshStops() {
|
||||
const entry = state._trains.get(state._selectedKey);
|
||||
if (!entry || !state._enabled || typeof stops?.stopsFor !== 'function') {
|
||||
if (state._trip || state._stopsSignature) clearStops();
|
||||
return;
|
||||
}
|
||||
let trip = null;
|
||||
try {
|
||||
trip = stops.stopsFor(
|
||||
{
|
||||
feedId: entry.feedId,
|
||||
tripId: entry.record?.tripId || null,
|
||||
routeId: entry.record?.routeId || null,
|
||||
record: entry.record,
|
||||
},
|
||||
Date.now(),
|
||||
);
|
||||
} catch (error) {
|
||||
console.warn('[Data:Rail] stops unavailable:', error?.message || error);
|
||||
}
|
||||
const list = Array.isArray(trip?.stops) ? trip.stops : [];
|
||||
state._trip = list.length || trip?.headsign ? trip : null;
|
||||
settleAnchors();
|
||||
const { labels, dots } = selectStopLabels(list);
|
||||
const color = categoryColor(entry.category, 1);
|
||||
const passedColor = categoryColor(entry.category, 0.45);
|
||||
|
||||
const signature = `${entry.key}|${labels.map((l) => l.index).join(',')}|${dots
|
||||
.map((d) => `${d.index}${d.passed ? 'p' : ''}`)
|
||||
.join(',')}`;
|
||||
if (signature !== state._stopsSignature) {
|
||||
state._stopsSignature = signature;
|
||||
const points = stopDots();
|
||||
if (points) {
|
||||
const items = [];
|
||||
const add = (stop, passed, size) =>
|
||||
items.push({
|
||||
id: String(items.length),
|
||||
pos: anchorFor(stop),
|
||||
pixelSize: size,
|
||||
color: passed ? passedColor : color,
|
||||
outlineColor: STOP_DOT_OUTLINE,
|
||||
outlineWidth: 1.5,
|
||||
disableDepthTest: Infinity,
|
||||
show: true,
|
||||
});
|
||||
for (const dot of dots) add(dot.stop, dot.passed, STOP_DOT_PX);
|
||||
for (const label of labels)
|
||||
add(label.stop, label.stop.state === 'passed', STOP_LABELLED_DOT_PX);
|
||||
stopItems = items;
|
||||
points.set(items);
|
||||
}
|
||||
governorRequestRender('rail-stops');
|
||||
}
|
||||
|
||||
const entries = createStopOverlayEntries(entry.key, labels, anchorFor);
|
||||
const text = JSON.stringify(
|
||||
entries.map((item) => [item.id, item.title, item.details, item.accent]),
|
||||
);
|
||||
if (text !== state._stopLabelsSignature) {
|
||||
state._stopLabelsSignature = text;
|
||||
state._overlayHost.setEntries(
|
||||
RAIL_STOP_OVERLAY_SOURCE_ID,
|
||||
entries,
|
||||
RAIL_STOP_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Selection ticker
|
||||
|
||||
function tick() {
|
||||
if (globalThis.document?.visibilityState === 'hidden') return;
|
||||
if (!state._enabled || !state._selectedKey) {
|
||||
stopTicker();
|
||||
return;
|
||||
}
|
||||
ticks += 1;
|
||||
syncRoute();
|
||||
if ((ticks * ROUTE_SPLIT_INTERVAL_MS) % STOP_REFRESH_MS === 0) {
|
||||
refreshStops();
|
||||
parts.selection.refreshSelectedCard(false);
|
||||
}
|
||||
}
|
||||
|
||||
function startTicker() {
|
||||
if (timer) return;
|
||||
ticks = 0;
|
||||
timer = setInterval(tick, ROUTE_SPLIT_INTERVAL_MS);
|
||||
}
|
||||
|
||||
function stopTicker() {
|
||||
clearInterval(timer);
|
||||
timer = null;
|
||||
}
|
||||
|
||||
/** A train was selected, or the selection was cleared. */
|
||||
function onSelectionChanged() {
|
||||
state._stopAnchors.clear();
|
||||
state._stopsSignature = '';
|
||||
state._stopLabelsSignature = '';
|
||||
const entry = state._enabled ? state._trains.get(state._selectedKey) : null;
|
||||
// The provider loads the feed's timetable and polls its delays while a
|
||||
// train on it is selected.
|
||||
stops?.onSelect?.(
|
||||
entry
|
||||
? {
|
||||
feedId: entry.feedId,
|
||||
tripId: entry.record?.tripId || null,
|
||||
routeId: entry.record?.routeId || null,
|
||||
record: entry.record,
|
||||
}
|
||||
: null,
|
||||
);
|
||||
if (state._selectedKey && state._enabled) {
|
||||
syncRoute();
|
||||
refreshStops();
|
||||
startTicker();
|
||||
} else {
|
||||
stopTicker();
|
||||
dropRoute();
|
||||
clearStops();
|
||||
}
|
||||
applyNetwork();
|
||||
governorRequestRender('rail-route');
|
||||
}
|
||||
|
||||
/**
|
||||
* Give back what a feed out of use for FEED_RELEASE_AFTER_MS holds: its
|
||||
* faint network, its path pack and its parsed timetable. A feed in use
|
||||
* (polled, or held for the selected train) keeps everything; a pack still
|
||||
* loading is left to finish. Called on each poll tick, and once more while
|
||||
* the layer is off.
|
||||
* @param {number} nowMs
|
||||
*/
|
||||
function releaseIdleFeeds(nowMs) {
|
||||
for (const feedId of state._activeFeeds.keys())
|
||||
feedSeenAt.set(feedId, nowMs);
|
||||
const held = new Set([
|
||||
...state._networks.keys(),
|
||||
...state._pathPacks.keys(),
|
||||
...feedSeenAt.keys(),
|
||||
]);
|
||||
for (const feedId of held) {
|
||||
if (state._activeFeeds.has(feedId)) continue;
|
||||
const seen = feedSeenAt.get(feedId);
|
||||
if (seen === undefined) {
|
||||
feedSeenAt.set(feedId, nowMs);
|
||||
continue;
|
||||
}
|
||||
if (nowMs - seen < FEED_RELEASE_AFTER_MS) continue;
|
||||
if (state._pathPacks.get(feedId)?.status === 'loading') continue;
|
||||
dropNetwork(feedId);
|
||||
state._pathPacks.delete(feedId);
|
||||
timetable?.forget?.(feedId);
|
||||
feedSeenAt.delete(feedId);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Layer disabled: hide everything. Built networks stay for a quick return,
|
||||
* and are released once they have been out of use FEED_RELEASE_AFTER_MS.
|
||||
*/
|
||||
function hideAll() {
|
||||
stops?.onSelect?.(null);
|
||||
stopTicker();
|
||||
dropRoute();
|
||||
clearStops();
|
||||
applyNetwork();
|
||||
releaseIdleFeeds(Date.now());
|
||||
clearTimeout(releaseTimer);
|
||||
releaseTimer = setTimeout(() => {
|
||||
releaseTimer = null;
|
||||
releaseIdleFeeds(Date.now());
|
||||
}, FEED_RELEASE_AFTER_MS);
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
hideAll();
|
||||
clearTimeout(releaseTimer);
|
||||
releaseTimer = null;
|
||||
feedSeenAt.clear();
|
||||
for (const feedId of [...state._networks.keys()]) dropNetwork(feedId);
|
||||
routeSet?.dispose();
|
||||
routeSet = null;
|
||||
stopSet?.dispose();
|
||||
stopSet = null;
|
||||
stopItems = [];
|
||||
state._overlayHost.clearSource(RAIL_STOP_OVERLAY_SOURCE_ID);
|
||||
}
|
||||
|
||||
/** Counts for QA and the testing surface. */
|
||||
function stats() {
|
||||
const feeds = {};
|
||||
for (const [feedId, network] of state._networks) {
|
||||
feeds[feedId] = {
|
||||
status: network.status,
|
||||
primitives: network.layers.size,
|
||||
shown: [...network.layers.values()].filter((l) => l.set.show).length,
|
||||
...(network.stats || {}),
|
||||
};
|
||||
}
|
||||
return {
|
||||
fade: state._networkFade,
|
||||
feeds,
|
||||
route: state._route
|
||||
? {
|
||||
id: state._route.id,
|
||||
vertices: state._route.path.n,
|
||||
fraction: state._route.fraction,
|
||||
direction: state._route.direction,
|
||||
ground: state._route.ground,
|
||||
}
|
||||
: null,
|
||||
stops: {
|
||||
points: stopItems.length,
|
||||
trip: state._trip ? state._trip.stops?.length || 0 : 0,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
buildNetwork,
|
||||
dropNetwork,
|
||||
applyNetwork,
|
||||
onCamera,
|
||||
syncRoute,
|
||||
refreshStops,
|
||||
cullStops,
|
||||
onSelectionChanged,
|
||||
hideAll,
|
||||
releaseIdleFeeds,
|
||||
destroy,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,335 @@
|
||||
/**
|
||||
* @module layers/rail/routeLines
|
||||
* @description Pure geometry for the Rail layer's route lines: the faint
|
||||
* network a feed's path pack draws when zoomed in, and the split of a
|
||||
* selected train's line into the part travelled and the part ahead.
|
||||
*
|
||||
* A pack lists every distinct GTFS shape, and most of them overlap: a
|
||||
* commuter network's short turns, express patterns and branches share the
|
||||
* trunk. Drawing each shape would stack hundreds of translucent lines on the
|
||||
* same track, so the network is a union: shapes are walked longest first, and
|
||||
* only the stretches no earlier shape already covered are kept. Each kept
|
||||
* stretch is then thinned to the vertices its curve needs.
|
||||
*
|
||||
* Pure: no Cesium, no DOM.
|
||||
*/
|
||||
|
||||
/** Metres per degree of latitude (and of longitude at the equator). */
|
||||
const M_PER_DEG = 111_320;
|
||||
/** Coverage grid cell (m). A track within about one cell is already drawn. */
|
||||
export const NETWORK_CELL_M = 40;
|
||||
/** Sample spacing when walking a shape for coverage (m). */
|
||||
const NETWORK_STEP_M = 40;
|
||||
/** Uncovered stretches shorter than this are jitter beside a drawn track (m). */
|
||||
export const NETWORK_MIN_RUN_M = 200;
|
||||
/** Douglas-Peucker tolerance for the drawn stretches (m). */
|
||||
export const NETWORK_SIMPLIFY_M = 10;
|
||||
/** Grid key offset, so negative cell indices stay distinct. */
|
||||
const KEY_OFFSET = 2 ** 21;
|
||||
|
||||
/** Longitude difference wrapped into (-180, 180]. */
|
||||
function wrapLon(delta) {
|
||||
return ((((delta + 180) % 360) + 360) % 360) - 180;
|
||||
}
|
||||
|
||||
/** Arc length of a flat `[lat, lon, ...]` shape in a local frame (m). */
|
||||
function shapeLength(coords, kx) {
|
||||
let length = 0;
|
||||
for (let i = 2; i + 1 < coords.length; i += 2)
|
||||
length += Math.hypot(
|
||||
wrapLon(coords[i + 1] - coords[i - 1]) * kx,
|
||||
(coords[i] - coords[i - 2]) * M_PER_DEG,
|
||||
);
|
||||
return length;
|
||||
}
|
||||
|
||||
/**
|
||||
* Douglas-Peucker on a run of local-frame points, returning kept indices.
|
||||
* Iterative, so a long run cannot overflow the stack.
|
||||
*/
|
||||
function simplifyIndices(xs, ys, tolerance) {
|
||||
const n = xs.length;
|
||||
if (n <= 2) return Array.from({ length: n }, (_, i) => i);
|
||||
const keep = new Uint8Array(n);
|
||||
keep[0] = 1;
|
||||
keep[n - 1] = 1;
|
||||
const tol2 = tolerance * tolerance;
|
||||
const stack = [0, n - 1];
|
||||
while (stack.length) {
|
||||
const last = stack.pop();
|
||||
const first = stack.pop();
|
||||
const ax = xs[first];
|
||||
const ay = ys[first];
|
||||
const dx = xs[last] - ax;
|
||||
const dy = ys[last] - ay;
|
||||
const len2 = dx * dx + dy * dy;
|
||||
let worst = -1;
|
||||
let worstD2 = tol2;
|
||||
for (let i = first + 1; i < last; i++) {
|
||||
let t = len2 > 0 ? ((xs[i] - ax) * dx + (ys[i] - ay) * dy) / len2 : 0;
|
||||
t = t < 0 ? 0 : t > 1 ? 1 : t;
|
||||
const ex = ax + dx * t - xs[i];
|
||||
const ey = ay + dy * t - ys[i];
|
||||
const d2 = ex * ex + ey * ey;
|
||||
if (d2 > worstD2) {
|
||||
worstD2 = d2;
|
||||
worst = i;
|
||||
}
|
||||
}
|
||||
if (worst < 0) continue;
|
||||
keep[worst] = 1;
|
||||
stack.push(first, worst, worst, last);
|
||||
}
|
||||
const out = [];
|
||||
for (let i = 0; i < n; i++) if (keep[i]) out.push(i);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The category each shape is drawn in: that of the first route listing it
|
||||
* whose category is known. Shapes no classified route lists are not drawn
|
||||
* (a pack can carry shapes of routes the layer filters out).
|
||||
* @param {Record<string, number[]>} routes routeId → shape indices.
|
||||
* @param {number} shapeCount
|
||||
* @param {(routeId: string) => string|null} categoryOf
|
||||
* @returns {(string|null)[]}
|
||||
*/
|
||||
export function shapeCategories(routes, shapeCount, categoryOf) {
|
||||
const out = new Array(shapeCount).fill(null);
|
||||
for (const [routeId, list] of Object.entries(routes || {})) {
|
||||
if (!Array.isArray(list)) continue;
|
||||
let category;
|
||||
for (const index of list) {
|
||||
if (!Number.isInteger(index) || index < 0 || index >= shapeCount)
|
||||
continue;
|
||||
if (out[index] !== null) continue;
|
||||
if (category === undefined) category = categoryOf(routeId) || null;
|
||||
if (category) out[index] = category;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The union of a pack's shapes as drawable stretches, each tagged with the
|
||||
* category of the route it came from.
|
||||
*
|
||||
* @param {{shapes: ArrayLike<number>[], routes?: Record<string, number[]>}} raw
|
||||
* A decoded path pack (the JSON body, not the indexed wrapper).
|
||||
* @param {(routeId: string) => string|null} categoryOf Route → category, or
|
||||
* null for a route the layer does not draw.
|
||||
* @param {{cellM?: number, minRunM?: number, simplifyM?: number}} [options]
|
||||
* @returns {{lines: {category: string, coords: Float64Array}[],
|
||||
* shapesIn: number, pointsIn: number, pointsOut: number}}
|
||||
*/
|
||||
export function buildRailNetworkLines(raw, categoryOf, options = {}) {
|
||||
const steps = railNetworkLineSteps(raw, categoryOf, options);
|
||||
for (;;) {
|
||||
const next = steps.next();
|
||||
if (next.done) return next.value;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The same union as buildRailNetworkLines(), one shape per step, so a large
|
||||
* pack can be built in slices between frames instead of in one long task.
|
||||
* @param {object} raw
|
||||
* @param {(routeId: string) => string|null} categoryOf
|
||||
* @param {object} [options]
|
||||
* @returns {Generator<void, ReturnType<typeof buildRailNetworkLines>>}
|
||||
*/
|
||||
export function* railNetworkLineSteps(raw, categoryOf, options = {}) {
|
||||
const cellM = options.cellM ?? NETWORK_CELL_M;
|
||||
const minRunM = options.minRunM ?? NETWORK_MIN_RUN_M;
|
||||
const simplifyM = options.simplifyM ?? NETWORK_SIMPLIFY_M;
|
||||
const shapes = Array.isArray(raw?.shapes) ? raw.shapes : [];
|
||||
const categories = shapeCategories(raw?.routes, shapes.length, categoryOf);
|
||||
let minLat = Infinity;
|
||||
let maxLat = -Infinity;
|
||||
let pointsIn = 0;
|
||||
const order = [];
|
||||
for (let index = 0; index < shapes.length; index++) {
|
||||
const coords = shapes[index];
|
||||
if (!categories[index] || !(coords?.length >= 4)) continue;
|
||||
for (let i = 0; i + 1 < coords.length; i += 2) {
|
||||
if (coords[i] < minLat) minLat = coords[i];
|
||||
if (coords[i] > maxLat) maxLat = coords[i];
|
||||
}
|
||||
pointsIn += coords.length / 2;
|
||||
order.push(index);
|
||||
}
|
||||
if (!order.length) return { lines: [], shapesIn: 0, pointsIn, pointsOut: 0 };
|
||||
const lat0 = (minLat + maxLat) / 2;
|
||||
const lon0 = shapes[order[0]][1];
|
||||
const kx = M_PER_DEG * Math.cos((lat0 * Math.PI) / 180);
|
||||
const lengths = new Map(
|
||||
order.map((index) => [index, shapeLength(shapes[index], kx)]),
|
||||
);
|
||||
order.sort((a, b) => lengths.get(b) - lengths.get(a));
|
||||
|
||||
const covered = new Set();
|
||||
const lines = [];
|
||||
let pointsOut = 0;
|
||||
// Reused per shape: the densified walk in the local frame.
|
||||
let xs = [];
|
||||
let ys = [];
|
||||
let cells = [];
|
||||
const rowWidth = KEY_OFFSET * 2;
|
||||
const cellKey = (x, y) =>
|
||||
(Math.floor(x / cellM) + KEY_OFFSET) * rowWidth +
|
||||
(Math.floor(y / cellM) + KEY_OFFSET);
|
||||
// Own cell first: on an already drawn track that is almost always the hit,
|
||||
// so a covered sample costs one lookup and only new track pays for nine.
|
||||
const around = [
|
||||
-rowWidth,
|
||||
rowWidth,
|
||||
-1,
|
||||
1,
|
||||
-rowWidth - 1,
|
||||
-rowWidth + 1,
|
||||
rowWidth - 1,
|
||||
rowWidth + 1,
|
||||
];
|
||||
const isCovered = (key) => {
|
||||
if (covered.has(key)) return true;
|
||||
for (let i = 0; i < around.length; i++)
|
||||
if (covered.has(key + around[i])) return true;
|
||||
return false;
|
||||
};
|
||||
|
||||
function emit(category, from, to) {
|
||||
const runXs = xs.slice(from, to + 1);
|
||||
const runYs = ys.slice(from, to + 1);
|
||||
let length = 0;
|
||||
for (let i = 1; i < runXs.length; i++)
|
||||
length += Math.hypot(runXs[i] - runXs[i - 1], runYs[i] - runYs[i - 1]);
|
||||
if (length < minRunM) return;
|
||||
const kept = simplifyIndices(runXs, runYs, simplifyM);
|
||||
const coords = new Float64Array(kept.length * 2);
|
||||
for (let k = 0; k < kept.length; k++) {
|
||||
const i = kept[k];
|
||||
coords[2 * k] = runYs[i] / M_PER_DEG + lat0;
|
||||
let lon = runXs[i] / kx + lon0;
|
||||
if (lon > 180) lon -= 360;
|
||||
else if (lon < -180) lon += 360;
|
||||
coords[2 * k + 1] = lon;
|
||||
}
|
||||
pointsOut += kept.length;
|
||||
lines.push({ category, coords });
|
||||
}
|
||||
|
||||
for (const index of order) {
|
||||
const coords = shapes[index];
|
||||
xs = [];
|
||||
ys = [];
|
||||
for (let i = 0; i + 1 < coords.length; i += 2) {
|
||||
const x = wrapLon(coords[i + 1] - lon0) * kx;
|
||||
const y = (coords[i] - lat0) * M_PER_DEG;
|
||||
if (xs.length) {
|
||||
const px = xs[xs.length - 1];
|
||||
const py = ys[ys.length - 1];
|
||||
const steps = Math.ceil(Math.hypot(x - px, y - py) / NETWORK_STEP_M);
|
||||
for (let k = 1; k < steps; k++) {
|
||||
xs.push(px + ((x - px) * k) / steps);
|
||||
ys.push(py + ((y - py) * k) / steps);
|
||||
}
|
||||
}
|
||||
xs.push(x);
|
||||
ys.push(y);
|
||||
}
|
||||
cells = new Array(xs.length);
|
||||
let runStart = -1;
|
||||
for (let i = 0; i < xs.length; i++) {
|
||||
cells[i] = cellKey(xs[i], ys[i]);
|
||||
const free = !isCovered(cells[i]);
|
||||
if (free && runStart < 0) runStart = Math.max(0, i - 1);
|
||||
else if (!free && runStart >= 0) {
|
||||
emit(categories[index], runStart, i);
|
||||
runStart = -1;
|
||||
}
|
||||
}
|
||||
if (runStart >= 0) emit(categories[index], runStart, xs.length - 1);
|
||||
// Marked after the walk, not during it: consecutive samples of one shape
|
||||
// sit in neighbouring cells, so marking as it goes would cover the shape
|
||||
// against itself.
|
||||
for (const key of cells) covered.add(key);
|
||||
yield;
|
||||
}
|
||||
return { lines, shapesIn: order.length, pointsIn, pointsOut };
|
||||
}
|
||||
|
||||
/**
|
||||
* The fraction of a polyline, by cumulative chord length, at which arc `s`
|
||||
* of a rail path falls. The renderer draws the path's own vertices, so the
|
||||
* fraction is measured on those vertices: segment `i` of the path holds the
|
||||
* arc range `[path.s[i], path.s[i+1]]` and the same chord in the drawn line.
|
||||
*
|
||||
* @param {{n: number, s: ArrayLike<number>}} path From createRailPath.
|
||||
* @param {ArrayLike<number>} chordAt Cumulative drawn length per vertex
|
||||
* (same length as the path), e.g. from cumulativeChords().
|
||||
* @param {number} s Arc length (m) on the path.
|
||||
* @returns {number} 0..1, or NaN when either input is unusable.
|
||||
*/
|
||||
export function splitFraction(path, chordAt, s) {
|
||||
if (!path || !chordAt || chordAt.length !== path.n || !Number.isFinite(s))
|
||||
return NaN;
|
||||
const total = chordAt[path.n - 1];
|
||||
if (!(total > 0)) return NaN;
|
||||
const arc = path.s;
|
||||
if (s <= arc[0]) return 0;
|
||||
if (s >= arc[path.n - 1]) return 1;
|
||||
let lo = 0;
|
||||
let hi = path.n - 2;
|
||||
while (lo < hi) {
|
||||
const mid = (lo + hi + 1) >> 1;
|
||||
if (arc[mid] <= s) lo = mid;
|
||||
else hi = mid - 1;
|
||||
}
|
||||
const span = arc[lo + 1] - arc[lo];
|
||||
const t = span > 0 ? (s - arc[lo]) / span : 0;
|
||||
const chord = chordAt[lo] + (chordAt[lo + 1] - chordAt[lo]) * t;
|
||||
return Math.max(0, Math.min(1, chord / total));
|
||||
}
|
||||
|
||||
/**
|
||||
* Cumulative length per vertex of a path, measured on the path's own local
|
||||
* frame (x, y). This is what splitFraction() needs when the drawn line's
|
||||
* texture coordinate runs by length, as a ground polyline's does.
|
||||
* @param {{n: number, x: ArrayLike<number>, y: ArrayLike<number>}} path
|
||||
* @returns {Float64Array}
|
||||
*/
|
||||
export function cumulativeChords(path) {
|
||||
const out = new Float64Array(path?.n || 0);
|
||||
for (let i = 1; i < out.length; i++)
|
||||
out[i] =
|
||||
out[i - 1] +
|
||||
Math.hypot(path.x[i] - path.x[i - 1], path.y[i] - path.y[i - 1]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Vertex-index positions: what splitFraction() needs when the drawn line's
|
||||
* texture coordinate runs by vertex index, as a plain PolylineGeometry's does.
|
||||
* @param {{n: number}} path
|
||||
* @returns {Float64Array}
|
||||
*/
|
||||
export function vertexIndexChords(path) {
|
||||
const out = new Float64Array(path?.n || 0);
|
||||
for (let i = 0; i < out.length; i++) out[i] = i;
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* The faint network's opacity at a camera altitude: full below `fullBelowM`,
|
||||
* none above `hiddenAboveM`, linear between.
|
||||
* @param {number} altitudeM
|
||||
* @param {number} fullBelowM
|
||||
* @param {number} hiddenAboveM
|
||||
* @returns {number} 0..1
|
||||
*/
|
||||
export function networkAltitudeFade(altitudeM, fullBelowM, hiddenAboveM) {
|
||||
if (!Number.isFinite(altitudeM)) return 0;
|
||||
if (altitudeM <= fullBelowM) return 1;
|
||||
if (altitudeM >= hiddenAboveM) return 0;
|
||||
return (hiddenAboveM - altitudeM) / (hiddenAboveM - fullBelowM);
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
// The Rail layer's route-line geometry: the network union a path pack draws
|
||||
// as faint lines, and where a selected train's line splits into the part
|
||||
// travelled and the part ahead; and, on a whole layer, how the selected
|
||||
// train's line is drawn and released.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { FEED_RELEASE_AFTER_MS, railTrainKey } from './policy.js';
|
||||
import { SCHEDULE_RETRY_FIRST_MS } from './schedules.js';
|
||||
import {
|
||||
BOSTON,
|
||||
railLayerHarness as harness,
|
||||
railTrain as train,
|
||||
} from '../../testSupport/railLayerHarness.mjs';
|
||||
import {
|
||||
NETWORK_MIN_RUN_M,
|
||||
buildRailNetworkLines,
|
||||
cumulativeChords,
|
||||
networkAltitudeFade,
|
||||
railNetworkLineSteps,
|
||||
shapeCategories,
|
||||
splitFraction,
|
||||
vertexIndexChords,
|
||||
} from './routeLines.js';
|
||||
import {
|
||||
createRailPath,
|
||||
pointAtS,
|
||||
projectOnPath,
|
||||
} from '../../data/railPaths.js';
|
||||
|
||||
const M_PER_DEG = 111_320;
|
||||
const LAT = 42.36;
|
||||
const KX = M_PER_DEG * Math.cos((LAT * Math.PI) / 180);
|
||||
|
||||
/** A flat [lat, lon, ...] line due east from `lon0`, one vertex per `stepM`. */
|
||||
function eastLine(lon0, lengthM, stepM = 100, lat = LAT) {
|
||||
const out = [];
|
||||
for (let d = 0; d <= lengthM + 1e-6; d += stepM) out.push(lat, lon0 + d / KX);
|
||||
return out;
|
||||
}
|
||||
|
||||
/** Total length of a flat line (m), measured like the module does. */
|
||||
function lengthOf(coords) {
|
||||
let length = 0;
|
||||
for (let i = 2; i < coords.length; i += 2)
|
||||
length += Math.hypot(
|
||||
(coords[i + 1] - coords[i - 1]) * KX,
|
||||
(coords[i] - coords[i - 2]) * M_PER_DEG,
|
||||
);
|
||||
return length;
|
||||
}
|
||||
|
||||
const everyRoute = () => 'regional';
|
||||
|
||||
test('shape categories come from the first classified route listing them', () => {
|
||||
const categories = shapeCategories(
|
||||
{ bus: [0], 'CR-A': [1, 2], 'CR-B': [2, 3], bad: [99, -1, 'x'] },
|
||||
4,
|
||||
(route) =>
|
||||
route === 'bus' ? null : route === 'CR-A' ? 'local' : 'national',
|
||||
);
|
||||
assert.deepEqual(categories, [null, 'local', 'local', 'national']);
|
||||
});
|
||||
|
||||
test('overlapping shapes are drawn once: a short turn adds nothing', () => {
|
||||
const full = eastLine(-71.2, 20_000);
|
||||
const shortTurn = eastLine(-71.2, 8_000, 250); // other vertex spacing too
|
||||
const result = buildRailNetworkLines(
|
||||
{ shapes: [shortTurn, full], routes: { r: [0, 1] } },
|
||||
everyRoute,
|
||||
);
|
||||
assert.equal(result.shapesIn, 2);
|
||||
assert.equal(result.lines.length, 1);
|
||||
assert.equal(result.lines[0].category, 'regional');
|
||||
// The longest shape is walked first, so the one line spans all of it.
|
||||
assert.ok(Math.abs(lengthOf(result.lines[0].coords) - 20_000) < 60);
|
||||
// A straight track keeps only its ends.
|
||||
assert.equal(result.lines[0].coords.length, 4);
|
||||
assert.ok(result.pointsOut < result.pointsIn);
|
||||
});
|
||||
|
||||
test('a branch adds only the stretch the trunk does not already cover', () => {
|
||||
const trunk = eastLine(-71.2, 20_000);
|
||||
// Shares the trunk's first 10 km, then turns north for 5 km.
|
||||
const branch = eastLine(-71.2, 10_000);
|
||||
const turnLon = branch[branch.length - 1];
|
||||
for (let d = 100; d <= 5_000; d += 100)
|
||||
branch.push(LAT + d / M_PER_DEG, turnLon);
|
||||
const result = buildRailNetworkLines(
|
||||
{ shapes: [trunk, branch], routes: { a: [0], b: [1] } },
|
||||
(route) => (route === 'a' ? 'local' : 'regional'),
|
||||
);
|
||||
assert.equal(result.lines.length, 2);
|
||||
const [first, second] = result.lines;
|
||||
assert.equal(first.category, 'local');
|
||||
assert.equal(second.category, 'regional');
|
||||
const branchLength = lengthOf(second.coords);
|
||||
// The new stretch is the 5 km spur, joined to the trunk by a sample or so.
|
||||
assert.ok(branchLength > 4_900 && branchLength < 5_200, String(branchLength));
|
||||
});
|
||||
|
||||
test('a parallel track beside a drawn one is jitter, not a new line', () => {
|
||||
const a = eastLine(-71.2, 10_000);
|
||||
const b = eastLine(-71.2, 9_000, 100, LAT + 15 / M_PER_DEG); // 15 m north
|
||||
const result = buildRailNetworkLines(
|
||||
{ shapes: [a, b], routes: { r: [0, 1] } },
|
||||
everyRoute,
|
||||
);
|
||||
assert.equal(result.lines.length, 1);
|
||||
});
|
||||
|
||||
test('uncovered stretches shorter than the minimum run are dropped', () => {
|
||||
const trunk = eastLine(-71.2, 10_000);
|
||||
// Leaves the trunk for a stub shorter than the minimum, then ends.
|
||||
const stub = eastLine(-71.2, 5_000);
|
||||
const endLon = stub[stub.length - 1];
|
||||
const stubM = NETWORK_MIN_RUN_M / 2;
|
||||
for (let d = 20; d <= stubM; d += 20) stub.push(LAT - d / M_PER_DEG, endLon);
|
||||
const result = buildRailNetworkLines(
|
||||
{ shapes: [trunk, stub], routes: { r: [0, 1] } },
|
||||
everyRoute,
|
||||
);
|
||||
assert.equal(result.lines.length, 1);
|
||||
});
|
||||
|
||||
test('shapes of routes the layer does not draw are left out', () => {
|
||||
const result = buildRailNetworkLines(
|
||||
{ shapes: [eastLine(-71.2, 5_000)], routes: { bus: [0] } },
|
||||
() => null,
|
||||
);
|
||||
assert.deepEqual(result.lines, []);
|
||||
assert.equal(result.shapesIn, 0);
|
||||
assert.deepEqual(buildRailNetworkLines(null, everyRoute).lines, []);
|
||||
});
|
||||
|
||||
test('the step builder yields once per shape and ends with the same union', () => {
|
||||
const raw = {
|
||||
shapes: [
|
||||
eastLine(-71.2, 20_000),
|
||||
eastLine(-71.2, 8_000),
|
||||
eastLine(-71.3, 3_000),
|
||||
],
|
||||
routes: { r: [0, 1, 2] },
|
||||
};
|
||||
const steps = railNetworkLineSteps(raw, everyRoute);
|
||||
let yields = 0;
|
||||
let next = steps.next();
|
||||
while (!next.done) {
|
||||
yields += 1;
|
||||
next = steps.next();
|
||||
}
|
||||
assert.equal(yields, 3);
|
||||
assert.deepEqual(
|
||||
next.value.lines.map((line) => Array.from(line.coords)),
|
||||
buildRailNetworkLines(raw, everyRoute).lines.map((line) =>
|
||||
Array.from(line.coords),
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
test('the split falls where the train is on its line, by drawn length', () => {
|
||||
// An L-shaped line: 3 km east, then 1 km north, with uneven vertices.
|
||||
const coords = eastLine(-71.2, 3_000, 500);
|
||||
const cornerLon = coords[coords.length - 1];
|
||||
for (let d = 100; d <= 1_000; d += 100)
|
||||
coords.push(LAT + d / M_PER_DEG, cornerLon);
|
||||
const path = createRailPath(coords);
|
||||
const chords = cumulativeChords(path);
|
||||
assert.equal(chords.length, path.n);
|
||||
assert.ok(Math.abs(chords[path.n - 1] - path.length) < 1e-6);
|
||||
|
||||
// A train reported 1.5 km along, a little off the track.
|
||||
const hit = projectOnPath(path, LAT + 8 / M_PER_DEG, -71.2 + 1_500 / KX);
|
||||
assert.ok(Math.abs(hit.s - 1_500) < 1);
|
||||
const fraction = splitFraction(path, chords, hit.s);
|
||||
assert.ok(Math.abs(fraction - 1_500 / 4_000) < 1e-3);
|
||||
|
||||
// The drawn point at the split is the train's point on the line.
|
||||
const at = pointAtS(path, fraction * path.length);
|
||||
assert.ok(Math.abs(at.lon - (-71.2 + 1_500 / KX)) < 1e-6);
|
||||
|
||||
// Ends and out-of-range arcs clamp; bad input is NaN, not a guess.
|
||||
assert.equal(splitFraction(path, chords, -50), 0);
|
||||
assert.equal(splitFraction(path, chords, path.length + 50), 1);
|
||||
assert.ok(Number.isNaN(splitFraction(path, chords, NaN)));
|
||||
assert.ok(Number.isNaN(splitFraction(path, new Float64Array(2), 10)));
|
||||
assert.ok(Number.isNaN(splitFraction(null, chords, 10)));
|
||||
});
|
||||
|
||||
test('by vertex index, the split follows a line drawn per vertex', () => {
|
||||
// Vertices at 0, 500, 2500 m: by index the middle vertex is halfway.
|
||||
const coords = [LAT, -71.2, LAT, -71.2 + 500 / KX, LAT, -71.2 + 2_500 / KX];
|
||||
const path = createRailPath(coords);
|
||||
const byIndex = vertexIndexChords(path);
|
||||
assert.deepEqual(Array.from(byIndex), [0, 1, 2]);
|
||||
assert.ok(Math.abs(splitFraction(path, byIndex, 500) - 0.5) < 1e-9);
|
||||
// 1500 m is halfway along the second segment: index 1.5 of 2.
|
||||
assert.ok(Math.abs(splitFraction(path, byIndex, 1_500) - 0.75) < 1e-9);
|
||||
// By length the same arc is 0.6 of the line.
|
||||
assert.ok(
|
||||
Math.abs(splitFraction(path, cumulativeChords(path), 1_500) - 0.6) < 1e-6,
|
||||
);
|
||||
});
|
||||
|
||||
test('the network fades out between its two altitudes', () => {
|
||||
assert.equal(networkAltitudeFade(15_000, 150_000, 200_000), 1);
|
||||
assert.equal(networkAltitudeFade(150_000, 150_000, 200_000), 1);
|
||||
assert.equal(networkAltitudeFade(175_000, 150_000, 200_000), 0.5);
|
||||
assert.equal(networkAltitudeFade(200_000, 150_000, 200_000), 0);
|
||||
assert.equal(networkAltitudeFade(3_000_000, 150_000, 200_000), 0);
|
||||
assert.equal(networkAltitudeFade(Infinity, 150_000, 200_000), 0);
|
||||
assert.equal(networkAltitudeFade(NaN, 150_000, 200_000), 0);
|
||||
});
|
||||
|
||||
test('the selected train’s line is its trip’s shape, else its route’s longest', async (t) => {
|
||||
const pack = {
|
||||
version: 1,
|
||||
feedId: 'mbta-rail',
|
||||
shapes: [eastLine(-71.08, 3000), eastLine(-71.08, 3000, 3000, LAT + 0.01)],
|
||||
dist: [[], []],
|
||||
shapeSources: ['operator', 'operator'],
|
||||
trips: { 'trip-T1': 0 },
|
||||
routes: { R1: [0], R2: [1] },
|
||||
};
|
||||
const app = harness(t, { paths: { 'mbta-rail': pack } });
|
||||
app.feeds.set('mbta-rail', () => [
|
||||
train('T1', LAT, -71.07, { routeId: 'R1' }),
|
||||
train('T2', LAT + 0.01, -71.07, { routeId: 'R2' }),
|
||||
]);
|
||||
await app.enable();
|
||||
for (const [id, shapeIndex, vertices] of [
|
||||
['T1', 0, 31],
|
||||
['T2', 1, 2],
|
||||
]) {
|
||||
const key = railTrainKey('mbta-rail', id);
|
||||
app.parts().selection.selectTrain(key);
|
||||
const { route } = app.layer.getRouteDisplayStats();
|
||||
assert.equal(
|
||||
route?.id,
|
||||
`${key}
|
||||
mbta-rail
|
||||
${shapeIndex}`,
|
||||
id,
|
||||
);
|
||||
assert.equal(route.vertices, vertices, id);
|
||||
}
|
||||
});
|
||||
|
||||
/** A one-shape Boston pack for mbta-rail. */
|
||||
const BOSTON_PACK = Object.freeze({
|
||||
version: 1,
|
||||
feedId: 'mbta-rail',
|
||||
shapes: [eastLine(-71.08, 3000)],
|
||||
dist: [[]],
|
||||
trips: {},
|
||||
routes: { R1: [0] },
|
||||
});
|
||||
const OCEAN = { lat: 30, lon: -40 };
|
||||
const mbtaPaths = (app) =>
|
||||
app.requestedPaths.filter((id) => id === 'mbta-rail').length;
|
||||
|
||||
test('a path pack the server cannot read now is asked for again on a stepped delay', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const paths = { 'mbta-rail': 503 };
|
||||
const app = harness(t, { paths });
|
||||
app.feeds.set('mbta-rail', () => []);
|
||||
await app.enable();
|
||||
assert.equal(mbtaPaths(app), 1);
|
||||
await app.poll();
|
||||
assert.equal(mbtaPaths(app), 1, 'not on every poll');
|
||||
t.mock.timers.tick(SCHEDULE_RETRY_FIRST_MS);
|
||||
await app.poll();
|
||||
assert.equal(mbtaPaths(app), 2, 'again after 30 s');
|
||||
// The second failure waits twice as long.
|
||||
t.mock.timers.tick(SCHEDULE_RETRY_FIRST_MS);
|
||||
await app.poll();
|
||||
assert.equal(mbtaPaths(app), 2);
|
||||
paths['mbta-rail'] = BOSTON_PACK;
|
||||
t.mock.timers.tick(SCHEDULE_RETRY_FIRST_MS);
|
||||
await app.poll();
|
||||
assert.equal(mbtaPaths(app), 3);
|
||||
assert.equal(app.state()._pathPacks.get('mbta-rail').status, 'ready');
|
||||
});
|
||||
|
||||
test('a feed out of use for ten minutes gives back its network and packs', async (t) => {
|
||||
const app = harness(t, { paths: { 'mbta-rail': BOSTON_PACK } });
|
||||
app.feeds.set('mbta-rail', () => []);
|
||||
await app.enable();
|
||||
t.mock.timers.tick(0);
|
||||
assert.ok(app.state()._networks.has('mbta-rail'));
|
||||
assert.equal(app.state()._pathPacks.get('mbta-rail').status, 'ready');
|
||||
// Away from Boston: kept for a quick return...
|
||||
await app.moveCamera(OCEAN);
|
||||
assert.ok(!app.state()._activeFeeds.has('mbta-rail'));
|
||||
t.mock.timers.tick(FEED_RELEASE_AFTER_MS - 60_000);
|
||||
await app.poll();
|
||||
assert.ok(app.state()._networks.has('mbta-rail'));
|
||||
assert.ok(app.state()._pathPacks.has('mbta-rail'));
|
||||
// ...and released after ten minutes out of use.
|
||||
t.mock.timers.tick(60_000);
|
||||
await app.poll();
|
||||
assert.ok(!app.state()._networks.has('mbta-rail'));
|
||||
assert.ok(!app.state()._pathPacks.has('mbta-rail'));
|
||||
// Back in Boston, the pack loads again.
|
||||
await app.moveCamera(BOSTON);
|
||||
assert.equal(mbtaPaths(app), 2);
|
||||
});
|
||||
|
||||
test('a feed in use keeps its network however long it runs', async (t) => {
|
||||
const app = harness(t, { paths: { 'mbta-rail': BOSTON_PACK } });
|
||||
app.feeds.set('mbta-rail', () => []);
|
||||
await app.enable();
|
||||
t.mock.timers.tick(0);
|
||||
for (let i = 0; i < 3; i += 1) {
|
||||
t.mock.timers.tick(FEED_RELEASE_AFTER_MS);
|
||||
await app.poll();
|
||||
}
|
||||
assert.ok(app.state()._networks.has('mbta-rail'));
|
||||
assert.equal(mbtaPaths(app), 1);
|
||||
});
|
||||
|
||||
test('with the layer off, its feeds are released after ten minutes', async (t) => {
|
||||
const app = harness(t, { paths: { 'mbta-rail': BOSTON_PACK } });
|
||||
app.feeds.set('mbta-rail', () => []);
|
||||
await app.enable();
|
||||
t.mock.timers.tick(0);
|
||||
app.layer.disable(app.viewer);
|
||||
assert.ok(app.state()._networks.has('mbta-rail'), 'kept for a quick return');
|
||||
t.mock.timers.tick(FEED_RELEASE_AFTER_MS);
|
||||
assert.ok(!app.state()._networks.has('mbta-rail'));
|
||||
assert.ok(!app.state()._pathPacks.has('mbta-rail'));
|
||||
});
|
||||
@@ -0,0 +1,526 @@
|
||||
/**
|
||||
* @module layers/rail/schedules
|
||||
* @description The Rail layer's schedule tier: each feed's optional schedule
|
||||
* pack (src/data/railSchedule.js) and live trip-update delays, read for the
|
||||
* selected live train's stops, headsign and delays (the stops provider,
|
||||
* `stopsFor`). It never places or moves a train: every train drawn is where
|
||||
* its operator last reported it.
|
||||
*
|
||||
* A schedule pack is fetched the first time a train on that feed is
|
||||
* selected, and kept until the feed has been out of use for a while
|
||||
* (`forget`). Trip updates are polled every RAIL_UPDATES_POLL_MS while a
|
||||
* train on the feed is selected. A feed that publishes none (Irish Rail, SJ
|
||||
* Nord) may state each train's delay in its report (`delaySec`): that delay
|
||||
* then moves the train's timetable, for its stops and for finding its run.
|
||||
*
|
||||
* No Cesium, no DOM. Network access goes through the injected source and
|
||||
* timers through injected functions, so node:test drives it.
|
||||
*/
|
||||
|
||||
import {
|
||||
activeTrips,
|
||||
createSchedule,
|
||||
liveDelaySec,
|
||||
scheduledPosition,
|
||||
tripStops,
|
||||
} from '../../data/railSchedule.js';
|
||||
import { pointAtS } from '../../data/railPaths.js';
|
||||
|
||||
/** Trip updates are re-read this often while needed (ms). */
|
||||
export const RAIL_UPDATES_POLL_MS = 30_000;
|
||||
/** Delays older than this are not applied: a stopped poll must not lie (ms). */
|
||||
export const RAIL_UPDATES_MAX_AGE_MS = 2 * RAIL_UPDATES_POLL_MS + 15_000;
|
||||
/**
|
||||
* A schedule pack that failed (other than a 404) is tried again after
|
||||
* SCHEDULE_RETRY_FIRST_MS, then twice as long after each failure in a row,
|
||||
* up to SCHEDULE_RETRY_MS (ms): one bad answer from the server does not
|
||||
* leave a selected train without its stops for ten minutes.
|
||||
*/
|
||||
export const SCHEDULE_RETRY_FIRST_MS = 30_000;
|
||||
export const SCHEDULE_RETRY_MS = 10 * 60_000;
|
||||
/**
|
||||
* A live train without a known trip id may be matched to a run from this
|
||||
* long before its departure (waiting at the origin)...
|
||||
*/
|
||||
export const MATCH_BEFORE_MS = 5 * 60_000;
|
||||
/** ...to this long after its arrival, at the terminus. */
|
||||
export const MATCH_AFTER_MS = 2 * 60_000;
|
||||
/** A live train without a known trip id matches a run this close (m). */
|
||||
export const MATCH_NEAREST_MAX_M = 3_000;
|
||||
/** How long a nearest-run match is kept before it is looked for again (ms). */
|
||||
export const MATCH_KEEP_MS = 60_000;
|
||||
|
||||
/**
|
||||
* How long a schedule pack waits after its nth failure in a row (ms).
|
||||
* @param {number} failures 1 after the first.
|
||||
* @returns {number}
|
||||
*/
|
||||
export function scheduleRetryDelayMs(failures) {
|
||||
return Math.min(
|
||||
SCHEDULE_RETRY_MS,
|
||||
SCHEDULE_RETRY_FIRST_MS * 2 ** Math.max(0, failures - 1),
|
||||
);
|
||||
}
|
||||
|
||||
const M_PER_DEG = 111_320;
|
||||
|
||||
/** Ground distance in metres, equirectangular: fine at a few kilometres. */
|
||||
function distanceM(lat1, lon1, lat2, lon2) {
|
||||
const kx = M_PER_DEG * Math.cos((((lat1 + lat2) / 2) * Math.PI) / 180);
|
||||
const dLon = ((((lon2 - lon1 + 180) % 360) + 360) % 360) - 180;
|
||||
return Math.hypot(dLon * kx, (lat2 - lat1) * M_PER_DEG);
|
||||
}
|
||||
|
||||
/**
|
||||
* GTFS-RT trip records (the `/api/rail/updates` body) as the `delays` map
|
||||
* railSchedule reads, keyed by trip id.
|
||||
* @param {{trips?: object[]}|null} body
|
||||
* @returns {Record<string, object>}
|
||||
*/
|
||||
export function delaysFromUpdates(body) {
|
||||
const delays = {};
|
||||
for (const trip of Array.isArray(body?.trips) ? body.trips : []) {
|
||||
if (typeof trip?.tripId !== 'string' || !trip.tripId) continue;
|
||||
delays[trip.tripId] = {
|
||||
delaySec: Number.isFinite(trip.delaySec) ? trip.delaySec : null,
|
||||
startDate: trip.startDate ?? null,
|
||||
relationship: trip.relationship ?? null,
|
||||
stops: Array.isArray(trip.stops) ? trip.stops : [],
|
||||
};
|
||||
}
|
||||
return delays;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a timetable's shape indices point into this path pack: the two
|
||||
* come from one build. A path pack rebuilt on its own (or a schedule left
|
||||
* from an older build) has other shapes at those indices, so its runs are
|
||||
* compared between their stops instead of along some other line. Packs that
|
||||
* predate the stamps are taken as a pair.
|
||||
* @param {{pathsBuiltAt?: string|null}} schedule
|
||||
* @param {{builtAt?: string|null}|null} pack
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function pathsMatch(schedule, pack) {
|
||||
if (!pack) return false;
|
||||
if (!schedule?.pathsBuiltAt || !pack.builtAt) return true;
|
||||
return schedule.pathsBuiltAt === pack.builtAt;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where the timetable has one run now: on its shape when the path pack has
|
||||
* it, else between its stops. Only compared with a live train's report, to
|
||||
* find the run it is on (stopsFor); never drawn.
|
||||
* @param {object} schedule From createSchedule.
|
||||
* @param {object|string} run A run from activeTrips, or a trip id.
|
||||
* @param {number} nowMs
|
||||
* @param {object|null} delays
|
||||
* @param {object|null} pack A path pack (createRailPathPack), when loaded.
|
||||
* @returns {object|null} scheduledPosition's result plus `lat`, `lon`,
|
||||
* `bearingDeg` (NaN when unknown) and `onShape`.
|
||||
*/
|
||||
export function scheduledRunPoint(schedule, run, nowMs, delays, pack) {
|
||||
const position = scheduledPosition(schedule, run, nowMs, delays);
|
||||
if (!position) return null;
|
||||
const path =
|
||||
position.shape !== null && pathsMatch(schedule, pack)
|
||||
? pack.pathAt(position.shape)
|
||||
: null;
|
||||
const point = path ? pointAtS(path, position.s) : null;
|
||||
if (point && Number.isFinite(point.lat) && Number.isFinite(point.lon))
|
||||
return { ...position, ...point, onShape: true };
|
||||
if (Number.isFinite(position.lat) && Number.isFinite(position.lon))
|
||||
return { ...position, bearingDeg: NaN, onShape: false };
|
||||
// A shaped pattern whose path pack is not here (yet): between the stops.
|
||||
const trip = schedule.trips.get(position.tripId);
|
||||
if (!trip) return null;
|
||||
const stopAt = (k) => (k >= 0 ? schedule.stops[trip.pattern.stops[k]] : null);
|
||||
const a = stopAt(
|
||||
position.prevStop >= 0 ? position.prevStop : position.nextStop,
|
||||
);
|
||||
const b =
|
||||
position.dwell || position.nextStop < 0 ? a : stopAt(position.nextStop);
|
||||
if (!a || !b) return null;
|
||||
const f = position.dwell ? 0 : position.fraction;
|
||||
return {
|
||||
...position,
|
||||
lat: a.lat + (b.lat - a.lat) * f,
|
||||
lon: a.lon + (b.lon - a.lon) * f,
|
||||
bearingDeg: NaN,
|
||||
onShape: false,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The schedule tier for one layer instance.
|
||||
* @param {{source: object,
|
||||
* hasTripUpdates: (feedId: string) => boolean,
|
||||
* pathPackFor?: (feedId: string) => object|null,
|
||||
* now?: () => number,
|
||||
* setInterval?: Function, clearInterval?: Function,
|
||||
* onChange?: (feedId: string) => void}} options
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createRailSchedules({
|
||||
source,
|
||||
hasTripUpdates,
|
||||
pathPackFor = () => null,
|
||||
now = () => Date.now(),
|
||||
setInterval: startInterval = (fn, ms) => globalThis.setInterval(fn, ms),
|
||||
clearInterval: stopInterval = (id) => globalThis.clearInterval(id),
|
||||
onChange = () => {},
|
||||
}) {
|
||||
/**
|
||||
* feedId → `{status: 'loading'|'ready'|'none', schedule, retryAt, promise,
|
||||
* failures}`; `failures` counts failed loads in a row.
|
||||
*/
|
||||
const schedules = new Map();
|
||||
/** feedId → `{delays, at, timer, reasons: Set, controller}`. */
|
||||
const updates = new Map();
|
||||
/** `${feedId}\n${trainId}` → `{tripKey, run, via, at}` for live trains. */
|
||||
const matches = new Map();
|
||||
let selectedFeed = null;
|
||||
|
||||
/**
|
||||
* The feed's schedule, loading it on first ask.
|
||||
* @param {string} feedId
|
||||
* @returns {Promise<object|null>} The schedule, or null when it has none.
|
||||
*/
|
||||
function loadSchedule(feedId) {
|
||||
const known = schedules.get(feedId);
|
||||
if (known?.status === 'ready') return Promise.resolve(known.schedule);
|
||||
if (known?.status === 'loading') return known.promise;
|
||||
if (known?.status === 'none' && now() < known.retryAt)
|
||||
return Promise.resolve(null);
|
||||
if (typeof source?.requestSchedule !== 'function') {
|
||||
schedules.set(feedId, {
|
||||
status: 'none',
|
||||
schedule: null,
|
||||
retryAt: Infinity,
|
||||
});
|
||||
return Promise.resolve(null);
|
||||
}
|
||||
const slot = {
|
||||
status: 'loading',
|
||||
schedule: null,
|
||||
retryAt: Infinity,
|
||||
failures: known?.failures ?? 0,
|
||||
};
|
||||
slot.promise = (async () => {
|
||||
try {
|
||||
const response = await source.requestSchedule(feedId);
|
||||
if (!response.ok) {
|
||||
const error = new Error(`rail schedule HTTP ${response.status}`);
|
||||
error.status = response.status;
|
||||
throw error;
|
||||
}
|
||||
const raw = await response.json();
|
||||
let schedule;
|
||||
try {
|
||||
schedule = createSchedule(raw);
|
||||
if (schedule.feedId !== feedId)
|
||||
throw new TypeError('rail schedule pack is for another feed');
|
||||
} catch (error) {
|
||||
error.permanent = true;
|
||||
throw error;
|
||||
}
|
||||
slot.schedule = schedule;
|
||||
slot.status = 'ready';
|
||||
slot.failures = 0;
|
||||
onChange(feedId);
|
||||
return schedule;
|
||||
} catch (error) {
|
||||
slot.status = 'none';
|
||||
slot.failures += 1;
|
||||
// A 404 is "no timetable for this feed", not a fault to retry; a
|
||||
// malformed pack will not mend itself before the next build either.
|
||||
slot.retryAt =
|
||||
error?.status === 404 || error?.permanent === true
|
||||
? Infinity
|
||||
: now() + scheduleRetryDelayMs(slot.failures);
|
||||
if (error?.status !== 404)
|
||||
console.warn(
|
||||
`[Data:Rail] ${feedId} timetable unavailable:`,
|
||||
error?.message || error,
|
||||
);
|
||||
return null;
|
||||
} finally {
|
||||
slot.promise = null;
|
||||
}
|
||||
})();
|
||||
schedules.set(feedId, slot);
|
||||
return slot.promise;
|
||||
}
|
||||
|
||||
/** The feed's schedule if loaded; starts the load otherwise. */
|
||||
function scheduleFor(feedId) {
|
||||
const known = schedules.get(feedId);
|
||||
if (known?.status === 'ready') return known.schedule;
|
||||
void loadSchedule(feedId);
|
||||
return null;
|
||||
}
|
||||
|
||||
function updatesSlot(feedId) {
|
||||
let slot = updates.get(feedId);
|
||||
if (!slot) {
|
||||
slot = {
|
||||
delays: null,
|
||||
at: -Infinity,
|
||||
timer: null,
|
||||
reasons: new Set(),
|
||||
controller: null,
|
||||
};
|
||||
updates.set(feedId, slot);
|
||||
}
|
||||
return slot;
|
||||
}
|
||||
|
||||
async function fetchUpdates(feedId) {
|
||||
const slot = updatesSlot(feedId);
|
||||
if (slot.controller || typeof source?.requestUpdates !== 'function') return;
|
||||
const controller = new AbortController();
|
||||
slot.controller = controller;
|
||||
try {
|
||||
const response = await source.requestUpdates(feedId, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
if (!response.ok) throw new Error(`rail updates HTTP ${response.status}`);
|
||||
const body = await response.json();
|
||||
if (slot.controller !== controller) return;
|
||||
// Delays are as old as the server's read of the operator (`fetchedAt`),
|
||||
// not this answer: a cached copy, or the last good one replayed while
|
||||
// the operator fails, stops applying RAIL_UPDATES_MAX_AGE_MS after it,
|
||||
// as positions do (ingestion.js applySnapshot).
|
||||
const at = now();
|
||||
slot.delays = delaysFromUpdates(body);
|
||||
slot.at = Math.min(
|
||||
Number.isFinite(body?.fetchedAt) ? body.fetchedAt : at,
|
||||
at,
|
||||
);
|
||||
onChange(feedId);
|
||||
} catch (error) {
|
||||
if (error?.name !== 'AbortError')
|
||||
console.warn(
|
||||
`[Data:Rail] ${feedId} trip updates unavailable:`,
|
||||
error?.message || error,
|
||||
);
|
||||
} finally {
|
||||
if (slot.controller === controller) slot.controller = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Poll a feed's trip updates while `reason` needs them. Reasons are
|
||||
* counted, so every reader shares one poll.
|
||||
* @param {string} feedId
|
||||
* @param {string} reason
|
||||
*/
|
||||
function watchUpdates(feedId, reason) {
|
||||
if (!hasTripUpdates(feedId)) return;
|
||||
const slot = updatesSlot(feedId);
|
||||
slot.reasons.add(reason);
|
||||
if (slot.timer !== null) return;
|
||||
void fetchUpdates(feedId);
|
||||
slot.timer = startInterval(
|
||||
() => void fetchUpdates(feedId),
|
||||
RAIL_UPDATES_POLL_MS,
|
||||
);
|
||||
}
|
||||
|
||||
function unwatchUpdates(feedId, reason) {
|
||||
const slot = updates.get(feedId);
|
||||
if (!slot) return;
|
||||
slot.reasons.delete(reason);
|
||||
if (slot.reasons.size || slot.timer === null) return;
|
||||
stopInterval(slot.timer);
|
||||
slot.timer = null;
|
||||
slot.controller?.abort();
|
||||
slot.controller = null;
|
||||
}
|
||||
|
||||
/** Current delays for a feed, or null when none are fresh. */
|
||||
function delaysFor(feedId) {
|
||||
const slot = updates.get(feedId);
|
||||
return slot?.delays && now() - slot.at <= RAIL_UPDATES_MAX_AGE_MS
|
||||
? slot.delays
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The run a live train is on. Its trip id when the timetable has it (live
|
||||
* GTFS trip ids are normally the static ones); otherwise, as a fallback,
|
||||
* the running run of its route nearest the train's report, kept for a
|
||||
* minute so the stop list does not hop between neighbouring runs. A train
|
||||
* its own report says is `liveDelayMs` late is compared with where the
|
||||
* timetable had each run that long ago.
|
||||
*/
|
||||
function matchRun(schedule, train, nowMs, delays, liveDelayMs = 0) {
|
||||
const tripId = train.tripId || null;
|
||||
if (tripId && schedule.runsByTrip.has(tripId))
|
||||
return { trip: tripId, via: 'trip' };
|
||||
const record = train.record || {};
|
||||
if (!Number.isFinite(record.lat) || !Number.isFinite(record.lon))
|
||||
return null;
|
||||
const key = `${train.feedId}\n${record.id ?? ''}`;
|
||||
const tripKey = `${tripId ?? ''}\n${train.routeId ?? ''}`;
|
||||
const kept = matches.get(key);
|
||||
if (kept && kept.tripKey === tripKey && nowMs - kept.at < MATCH_KEEP_MS)
|
||||
return kept.run ? { trip: kept.run, via: 'nearest' } : null;
|
||||
const pack = pathPackFor(train.feedId);
|
||||
// A uniform delay is a time shift: the run as timetabled that long ago.
|
||||
const matchMs = nowMs - liveDelayMs;
|
||||
let best = null;
|
||||
let bestM = MATCH_NEAREST_MAX_M;
|
||||
for (const run of activeTrips(schedule, matchMs, {
|
||||
delays,
|
||||
beforeMs: MATCH_BEFORE_MS,
|
||||
afterMs: MATCH_AFTER_MS,
|
||||
})) {
|
||||
if (train.routeId && run.routeId !== train.routeId) continue;
|
||||
const point = scheduledRunPoint(schedule, run, matchMs, delays, pack);
|
||||
if (!point) continue;
|
||||
const m = distanceM(record.lat, record.lon, point.lat, point.lon);
|
||||
if (m < bestM) {
|
||||
bestM = m;
|
||||
best = run;
|
||||
}
|
||||
}
|
||||
matches.set(key, { tripKey, run: best, at: nowMs });
|
||||
return best ? { trip: best, via: 'nearest' } : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stops provider (see createRailLayer): the selected train's stops and
|
||||
* headsign, or null until the feed's timetable has loaded (or when it has
|
||||
* none, or the train matches no run).
|
||||
* @param {{feedId: string, tripId: string|null, routeId: string|null,
|
||||
* record: object}} train
|
||||
* @param {number} nowMs
|
||||
* @returns {{stops: object[], headsign: string|null,
|
||||
* match: 'trip'|'nearest'}|null}
|
||||
*/
|
||||
function stopsFor(train, nowMs) {
|
||||
if (!train?.feedId) return null;
|
||||
const schedule = scheduleFor(train.feedId);
|
||||
if (!schedule) return null;
|
||||
// A feed without trip updates: the delay the train's report states.
|
||||
const liveDelay = hasTripUpdates(train.feedId)
|
||||
? null
|
||||
: liveDelaySec(train.record);
|
||||
const updates = liveDelay === null ? delaysFor(train.feedId) : null;
|
||||
const match = matchRun(
|
||||
schedule,
|
||||
train,
|
||||
nowMs,
|
||||
updates,
|
||||
(liveDelay ?? 0) * 1000,
|
||||
);
|
||||
if (!match) return null;
|
||||
const tripId =
|
||||
typeof match.trip === 'string' ? match.trip : match.trip.tripId;
|
||||
const delays =
|
||||
liveDelay === null
|
||||
? updates
|
||||
: {
|
||||
[tripId]: {
|
||||
delaySec: liveDelay,
|
||||
startDate:
|
||||
typeof match.trip === 'string' ? null : match.trip.serviceDate,
|
||||
},
|
||||
};
|
||||
const stops = tripStops(schedule, match.trip, nowMs, delays);
|
||||
if (!stops.length) return null;
|
||||
const trip = schedule.trips.get(tripId);
|
||||
return {
|
||||
stops,
|
||||
headsign: trip?.headsign || null,
|
||||
match: match.via,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* A train was selected (or the selection cleared): poll its delays once
|
||||
* its feed's timetable is loaded. Delays are shown only at the
|
||||
* timetable's stops, so a feed without one is not polled.
|
||||
*/
|
||||
function onSelect(train) {
|
||||
const feedId = train?.feedId || null;
|
||||
if (feedId === selectedFeed) return;
|
||||
if (selectedFeed) unwatchUpdates(selectedFeed, 'selection');
|
||||
selectedFeed = feedId;
|
||||
if (!feedId) return;
|
||||
void loadSchedule(feedId).then((schedule) => {
|
||||
if (schedule && selectedFeed === feedId)
|
||||
watchUpdates(feedId, 'selection');
|
||||
});
|
||||
}
|
||||
|
||||
/** Stop every poll; loaded schedules stay for the next enable. */
|
||||
function stop() {
|
||||
onSelect(null);
|
||||
for (const [feedId, slot] of updates)
|
||||
for (const reason of [...slot.reasons]) unwatchUpdates(feedId, reason);
|
||||
matches.clear();
|
||||
}
|
||||
|
||||
/**
|
||||
* Release what is held for a feed no longer in use: its parsed schedule,
|
||||
* its last trip updates and its live-train matches. A load or a poll
|
||||
* still under way is left to finish; the feed loads again when next used.
|
||||
* @param {string} feedId
|
||||
*/
|
||||
function forget(feedId) {
|
||||
if (schedules.get(feedId)?.status !== 'loading') schedules.delete(feedId);
|
||||
const slot = updates.get(feedId);
|
||||
if (slot && slot.reasons.size === 0 && slot.timer === null) {
|
||||
slot.controller?.abort();
|
||||
updates.delete(feedId);
|
||||
}
|
||||
const prefix = `${feedId}
|
||||
`;
|
||||
for (const key of [...matches.keys()])
|
||||
if (key.startsWith(prefix)) matches.delete(key);
|
||||
}
|
||||
|
||||
/** Counts for QA probes and tests. */
|
||||
function stats() {
|
||||
return {
|
||||
schedules: Object.fromEntries(
|
||||
[...schedules].map(([feedId, slot]) => [
|
||||
feedId,
|
||||
slot.status === 'ready'
|
||||
? {
|
||||
status: 'ready',
|
||||
trips: slot.schedule.trips.size,
|
||||
runs: slot.schedule.instances.length,
|
||||
}
|
||||
: { status: slot.status },
|
||||
]),
|
||||
),
|
||||
updates: Object.fromEntries(
|
||||
[...updates].map(([feedId, slot]) => [
|
||||
feedId,
|
||||
{
|
||||
polling: slot.timer !== null,
|
||||
reasons: [...slot.reasons],
|
||||
trips: slot.delays ? Object.keys(slot.delays).length : 0,
|
||||
ageMs: Number.isFinite(slot.at) ? now() - slot.at : null,
|
||||
},
|
||||
]),
|
||||
),
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
stopsFor,
|
||||
onSelect,
|
||||
loadSchedule,
|
||||
scheduleFor,
|
||||
watchUpdates,
|
||||
unwatchUpdates,
|
||||
delaysFor,
|
||||
stop,
|
||||
forget,
|
||||
stats,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,642 @@
|
||||
// The Rail layer's schedule tier, the stops provider of live trains: null
|
||||
// before the pack loads, trip-id matching with a nearest-run fallback, delay
|
||||
// polling only while a train is selected on a feed with a timetable. It
|
||||
// places no train itself. Built from a small synthetic schedule pack and path
|
||||
// pack.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
MATCH_NEAREST_MAX_M,
|
||||
RAIL_UPDATES_MAX_AGE_MS,
|
||||
RAIL_UPDATES_POLL_MS,
|
||||
SCHEDULE_RETRY_FIRST_MS,
|
||||
SCHEDULE_RETRY_MS,
|
||||
createRailSchedules,
|
||||
delaysFromUpdates,
|
||||
pathsMatch,
|
||||
scheduledRunPoint,
|
||||
scheduleRetryDelayMs,
|
||||
} from './schedules.js';
|
||||
import * as schedules from './schedules.js';
|
||||
import { createSchedule } from '../../data/railSchedule.js';
|
||||
import { createRailPathPack } from '../../data/railPaths.js';
|
||||
|
||||
const FEED = 'test-rail';
|
||||
const LAT = 50;
|
||||
const STEP_M = 0.1 * 111_320 * Math.cos((LAT * Math.PI) / 180);
|
||||
const at = (hhmm) => Date.parse(`2026-11-06T${hhmm}:00Z`);
|
||||
|
||||
/** Three stops due east 0.1° apart; T1 runs 10:00 → 10:20, dwelling at B. */
|
||||
const rawSchedule = Object.freeze({
|
||||
version: 1,
|
||||
feedId: FEED,
|
||||
timezone: 'UTC',
|
||||
window: { from: '2026-11-05', to: '2026-11-08' },
|
||||
routes: { R1: { type: 2 }, BUS: { type: 3 } },
|
||||
stops: [
|
||||
{ id: 'A', name: 'Alpha', lat: LAT, lon: 0 },
|
||||
{ id: 'B', name: 'Bravo', lat: LAT, lon: 0.1 },
|
||||
{ id: 'C', name: 'Charlie', lat: LAT, lon: 0.2 },
|
||||
],
|
||||
patterns: [
|
||||
{
|
||||
shape: 0,
|
||||
stops: [0, 1, 2],
|
||||
seq: [1, 2, 3],
|
||||
dist: [0, STEP_M, 2 * STEP_M],
|
||||
},
|
||||
{
|
||||
shape: 1,
|
||||
stops: [2, 1, 0],
|
||||
seq: [1, 2, 3],
|
||||
dist: [0, STEP_M, 2 * STEP_M],
|
||||
},
|
||||
],
|
||||
profiles: [[0, 0, 600, 660, 1260, 1260]],
|
||||
services: { WK: ['2026-11-06'] },
|
||||
trips: {
|
||||
T1: {
|
||||
pattern: 0,
|
||||
profile: 0,
|
||||
startSec: 10 * 3600,
|
||||
route: 'R1',
|
||||
service: 'WK',
|
||||
headsign: 'Charlie',
|
||||
name: 'Train 1',
|
||||
},
|
||||
T2: {
|
||||
pattern: 1,
|
||||
profile: 0,
|
||||
startSec: 10 * 3600,
|
||||
route: 'R1',
|
||||
service: 'WK',
|
||||
headsign: 'Alpha',
|
||||
name: 'Train 2',
|
||||
},
|
||||
B9: {
|
||||
pattern: 0,
|
||||
profile: 0,
|
||||
startSec: 10 * 3600,
|
||||
route: 'BUS',
|
||||
service: 'WK',
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
const rawPaths = Object.freeze({
|
||||
version: 1,
|
||||
feedId: FEED,
|
||||
shapes: [
|
||||
[LAT, 0, LAT, 0.1, LAT, 0.2],
|
||||
[LAT, 0.2, LAT, 0.1, LAT, 0],
|
||||
],
|
||||
dist: [
|
||||
[0, STEP_M, 2 * STEP_M],
|
||||
[0, STEP_M, 2 * STEP_M],
|
||||
],
|
||||
trips: { T1: 0, T2: 1 },
|
||||
routes: { R1: [0, 1] },
|
||||
});
|
||||
|
||||
const reply = (body, status = 200) => ({
|
||||
ok: status >= 200 && status < 300,
|
||||
status,
|
||||
async json() {
|
||||
return body;
|
||||
},
|
||||
});
|
||||
|
||||
const flush = async () => {
|
||||
for (let i = 0; i < 4; i++) await new Promise((r) => setImmediate(r));
|
||||
};
|
||||
|
||||
/** A provider over a fake source, fake clock and fake interval timers. */
|
||||
function harness({
|
||||
schedule = () => reply(rawSchedule),
|
||||
updates = () => reply({ trips: [] }),
|
||||
tripUpdates = true,
|
||||
clock = at('10:05'),
|
||||
} = {}) {
|
||||
const calls = { schedule: 0, updates: 0 };
|
||||
const timers = new Map();
|
||||
let nextTimer = 1;
|
||||
const h = {
|
||||
calls,
|
||||
timers,
|
||||
now: clock,
|
||||
provider: null,
|
||||
};
|
||||
h.provider = createRailSchedules({
|
||||
source: {
|
||||
async requestSchedule(feedId) {
|
||||
calls.schedule += 1;
|
||||
assert.equal(feedId, FEED);
|
||||
return schedule();
|
||||
},
|
||||
async requestUpdates(feedId) {
|
||||
calls.updates += 1;
|
||||
assert.equal(feedId, FEED);
|
||||
return updates();
|
||||
},
|
||||
},
|
||||
hasTripUpdates: () => tripUpdates,
|
||||
pathPackFor: () => createRailPathPack(rawPaths),
|
||||
now: () => h.now,
|
||||
setInterval: (fn, ms) => {
|
||||
const id = nextTimer++;
|
||||
timers.set(id, { fn, ms });
|
||||
return id;
|
||||
},
|
||||
clearInterval: (id) => timers.delete(id),
|
||||
});
|
||||
return h;
|
||||
}
|
||||
|
||||
const liveTrain = (record) => ({
|
||||
feedId: FEED,
|
||||
tripId: record.tripId ?? null,
|
||||
routeId: record.routeId ?? null,
|
||||
record,
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Where a run is, compared with a live train's report to find its run
|
||||
|
||||
test('the tier places no trains: it has no train records to offer', () => {
|
||||
assert.equal(schedules.scheduledTrainRecords, undefined);
|
||||
const provider = createRailSchedules({
|
||||
source: {},
|
||||
hasTripUpdates: () => false,
|
||||
});
|
||||
assert.deepEqual(Object.keys(provider).sort(), [
|
||||
'delaysFor',
|
||||
'forget',
|
||||
'loadSchedule',
|
||||
'onSelect',
|
||||
'scheduleFor',
|
||||
'stats',
|
||||
'stop',
|
||||
'stopsFor',
|
||||
'unwatchUpdates',
|
||||
'watchUpdates',
|
||||
]);
|
||||
});
|
||||
|
||||
test('without the path pack a run’s point lies between its stops', () => {
|
||||
const schedule = createSchedule(rawSchedule);
|
||||
const point = scheduledRunPoint(schedule, 'T1', at('10:05'), null, null);
|
||||
assert.equal(point.onShape, false);
|
||||
assert.ok(Math.abs(point.lon - 0.05) < 1e-9);
|
||||
assert.ok(Number.isNaN(point.bearingDeg));
|
||||
const onShape = scheduledRunPoint(
|
||||
schedule,
|
||||
'T1',
|
||||
at('10:05'),
|
||||
null,
|
||||
createRailPathPack(rawPaths),
|
||||
);
|
||||
assert.equal(onShape.onShape, true);
|
||||
assert.ok(Math.abs(onShape.bearingDeg - 90) < 1e-6);
|
||||
});
|
||||
|
||||
test('a schedule from another build than its path pack stays between stops', () => {
|
||||
const built = '2026-11-10T08:00:00.000Z';
|
||||
const schedule = createSchedule({ ...rawSchedule, pathsBuiltAt: built });
|
||||
const same = createRailPathPack({ ...rawPaths, builtAt: built });
|
||||
const rebuilt = createRailPathPack({
|
||||
...rawPaths,
|
||||
builtAt: '2026-11-10T09:00:00.000Z',
|
||||
});
|
||||
assert.equal(schedule.pathsBuiltAt, built);
|
||||
assert.equal(same.builtAt, built);
|
||||
assert.equal(pathsMatch(schedule, same), true);
|
||||
assert.equal(pathsMatch(schedule, rebuilt), false);
|
||||
assert.equal(pathsMatch(schedule, null), false);
|
||||
// Packs from before the stamps are taken as a pair.
|
||||
assert.equal(pathsMatch(createSchedule(rawSchedule), rebuilt), true);
|
||||
const onShape = scheduledRunPoint(schedule, 'T1', at('10:05'), null, same);
|
||||
assert.equal(onShape.onShape, true);
|
||||
const between = scheduledRunPoint(schedule, 'T1', at('10:05'), null, rebuilt);
|
||||
assert.equal(between.onShape, false);
|
||||
assert.ok(Math.abs(between.lon - 0.05) < 1e-9);
|
||||
});
|
||||
|
||||
test('trip updates become the delays map the timetable reads', () => {
|
||||
const delays = delaysFromUpdates({
|
||||
trips: [
|
||||
{
|
||||
tripId: 'T1',
|
||||
routeId: 'R1',
|
||||
startDate: '20261106',
|
||||
relationship: 'SCHEDULED',
|
||||
delaySec: null,
|
||||
stops: [{ stopId: 'B', arrival: { time: null, delay: 240 } }],
|
||||
},
|
||||
{ tripId: '', delaySec: 60 },
|
||||
null,
|
||||
],
|
||||
});
|
||||
assert.deepEqual(Object.keys(delays), ['T1']);
|
||||
assert.equal(delays.T1.delaySec, null);
|
||||
assert.equal(delays.T1.stops[0].arrival.delay, 240);
|
||||
assert.deepEqual(delaysFromUpdates(null), {});
|
||||
});
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Stops provider
|
||||
|
||||
test('the provider answers null until the timetable has loaded', async () => {
|
||||
const h = harness();
|
||||
const train = liveTrain({
|
||||
id: 'v1',
|
||||
tripId: 'T1',
|
||||
routeId: 'R1',
|
||||
lat: LAT,
|
||||
lon: 0.05,
|
||||
});
|
||||
assert.equal(h.provider.stopsFor(train, h.now), null);
|
||||
assert.equal(h.calls.schedule, 1);
|
||||
// Asking again while it loads does not fetch twice.
|
||||
assert.equal(h.provider.stopsFor(train, h.now), null);
|
||||
assert.equal(h.calls.schedule, 1);
|
||||
await flush();
|
||||
const trip = h.provider.stopsFor(train, h.now);
|
||||
assert.equal(trip.match, 'trip');
|
||||
assert.equal(trip.headsign, 'Charlie');
|
||||
assert.deepEqual(
|
||||
trip.stops.map((stop) => [stop.name, stop.state, stop.expectedArrival]),
|
||||
[
|
||||
['Alpha', 'passed', '10:00'],
|
||||
['Bravo', 'next', '10:10'],
|
||||
['Charlie', 'upcoming', '10:21'],
|
||||
],
|
||||
);
|
||||
assert.equal(trip.stops[1].relative, 'T−5');
|
||||
assert.equal(h.calls.schedule, 1);
|
||||
assert.equal(h.provider.stopsFor(null, h.now), null);
|
||||
});
|
||||
|
||||
test('a live trip id the timetable lacks falls back to the nearest run', async () => {
|
||||
const h = harness();
|
||||
await h.provider.loadSchedule(FEED);
|
||||
const near = h.provider.stopsFor(
|
||||
liveTrain({
|
||||
id: 'v7',
|
||||
tripId: 'live-123',
|
||||
routeId: 'R1',
|
||||
lat: LAT,
|
||||
lon: 0.149,
|
||||
}),
|
||||
h.now,
|
||||
);
|
||||
// At 10:05 T2 is at 0.15 (westbound) and T1 at 0.05: T2 is nearest.
|
||||
assert.equal(near.match, 'nearest');
|
||||
assert.equal(near.headsign, 'Alpha');
|
||||
// A train with no route searches every run.
|
||||
const noRoute = h.provider.stopsFor(
|
||||
liveTrain({ id: 'v8', tripId: null, lat: LAT, lon: 0.051 }),
|
||||
h.now,
|
||||
);
|
||||
assert.equal(noRoute.headsign, 'Charlie');
|
||||
// Too far from any run: no stops rather than a wrong train's.
|
||||
const farLon = 0.05 + (2 * MATCH_NEAREST_MAX_M) / (STEP_M * 10);
|
||||
assert.equal(
|
||||
h.provider.stopsFor(
|
||||
liveTrain({
|
||||
id: 'v9',
|
||||
tripId: 'x',
|
||||
routeId: 'R1',
|
||||
lat: LAT + 0.1,
|
||||
lon: farLon,
|
||||
}),
|
||||
h.now,
|
||||
),
|
||||
null,
|
||||
);
|
||||
// Another route's train does not take a run of R1.
|
||||
assert.equal(
|
||||
h.provider.stopsFor(
|
||||
liveTrain({ id: 'v10', tripId: 'x', routeId: 'R9', lat: LAT, lon: 0.05 }),
|
||||
h.now,
|
||||
),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('delays are polled every 30 s only while a train on the feed is selected', async () => {
|
||||
const h = harness({
|
||||
updates: () =>
|
||||
reply({
|
||||
trips: [
|
||||
{
|
||||
tripId: 'T1',
|
||||
delaySec: 240,
|
||||
stops: [{ stopId: 'B', arrival: { delay: 240 }, departure: null }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const train = liveTrain({
|
||||
id: 'v1',
|
||||
tripId: 'T1',
|
||||
routeId: 'R1',
|
||||
lat: LAT,
|
||||
lon: 0.05,
|
||||
});
|
||||
assert.equal(h.calls.updates, 0);
|
||||
h.provider.onSelect(train);
|
||||
await flush();
|
||||
assert.equal(h.calls.updates, 1);
|
||||
assert.equal(h.timers.size, 1);
|
||||
assert.equal([...h.timers.values()][0].ms, RAIL_UPDATES_POLL_MS);
|
||||
assert.equal(RAIL_UPDATES_POLL_MS, 30_000);
|
||||
const trip = h.provider.stopsFor(train, h.now);
|
||||
const bravo = trip.stops[1];
|
||||
assert.equal(bravo.arrivalDelaySec, 240);
|
||||
assert.equal(bravo.expectedArrival, '10:14');
|
||||
|
||||
// The interval re-reads; reselecting on the same feed adds no second poll.
|
||||
[...h.timers.values()][0].fn();
|
||||
await flush();
|
||||
assert.equal(h.calls.updates, 2);
|
||||
h.provider.onSelect({ ...train, record: { ...train.record, id: 'v2' } });
|
||||
assert.equal(h.timers.size, 1);
|
||||
|
||||
// Delays too old to trust are not applied.
|
||||
h.now += RAIL_UPDATES_MAX_AGE_MS + 1;
|
||||
assert.equal(h.provider.delaysFor(FEED), null);
|
||||
assert.equal(h.provider.stopsFor(train, h.now).stops[1].arrivalDelaySec, 0);
|
||||
|
||||
// Clearing the selection stops the poll.
|
||||
h.provider.onSelect(null);
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
test('delays are as old as the server’s read, even when it replays them', async () => {
|
||||
let readAt = null;
|
||||
const h = harness({
|
||||
updates: () =>
|
||||
reply({
|
||||
fetchedAt: readAt ?? h.now,
|
||||
trips: [
|
||||
{
|
||||
tripId: 'T1',
|
||||
delaySec: 240,
|
||||
stops: [{ stopId: 'B', arrival: { delay: 240 }, departure: null }],
|
||||
},
|
||||
],
|
||||
}),
|
||||
});
|
||||
const train = liveTrain({
|
||||
id: 'v1',
|
||||
tripId: 'T1',
|
||||
routeId: 'R1',
|
||||
lat: LAT,
|
||||
lon: 0.05,
|
||||
});
|
||||
h.provider.onSelect(train);
|
||||
await flush();
|
||||
assert.equal(h.provider.stopsFor(train, h.now).stops[1].arrivalDelaySec, 240);
|
||||
|
||||
// The operator fails: each poll is answered with the server's last copy,
|
||||
// still stamped with the time it was read.
|
||||
readAt = h.now;
|
||||
const poll = [...h.timers.values()][0].fn;
|
||||
for (let i = 0; i < 3; i++) {
|
||||
h.now += RAIL_UPDATES_POLL_MS;
|
||||
poll();
|
||||
await flush();
|
||||
}
|
||||
assert.equal(h.calls.updates, 4);
|
||||
assert.ok(3 * RAIL_UPDATES_POLL_MS > RAIL_UPDATES_MAX_AGE_MS);
|
||||
assert.equal(h.provider.delaysFor(FEED), null);
|
||||
assert.equal(h.provider.stopsFor(train, h.now).stops[1].arrivalDelaySec, 0);
|
||||
|
||||
// A fresh read applies again; a server clock ahead counts as now.
|
||||
readAt = h.now + 5_000;
|
||||
poll();
|
||||
await flush();
|
||||
assert.equal(h.provider.stopsFor(train, h.now).stops[1].arrivalDelaySec, 240);
|
||||
h.now += RAIL_UPDATES_MAX_AGE_MS;
|
||||
assert.notEqual(h.provider.delaysFor(FEED), null);
|
||||
});
|
||||
|
||||
test('a selected train’s delays are not polled when its feed has no timetable', async () => {
|
||||
const h = harness({
|
||||
schedule: () => reply({ error: 'No rail schedule' }, 404),
|
||||
});
|
||||
h.provider.onSelect(liveTrain({ id: 'v1', tripId: 'T1' }));
|
||||
await flush();
|
||||
assert.equal(h.calls.schedule, 1);
|
||||
assert.equal(h.calls.updates, 0);
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.equal(h.provider.stats().updates[FEED], undefined);
|
||||
|
||||
// With the pack, the same selection polls; cleared before the pack
|
||||
// arrives, it starts no poll.
|
||||
const ready = harness();
|
||||
ready.provider.onSelect(liveTrain({ id: 'v1', tripId: 'T1' }));
|
||||
ready.provider.onSelect(null);
|
||||
await flush();
|
||||
assert.equal(ready.calls.updates, 0);
|
||||
assert.equal(ready.timers.size, 0);
|
||||
ready.provider.onSelect(liveTrain({ id: 'v1', tripId: 'T1' }));
|
||||
await flush();
|
||||
assert.equal(ready.calls.updates, 1);
|
||||
assert.equal(ready.timers.size, 1);
|
||||
});
|
||||
|
||||
test('every reader of a feed’s delays shares one poll', async () => {
|
||||
const h = harness();
|
||||
h.provider.watchUpdates(FEED, 'probe');
|
||||
h.provider.onSelect(liveTrain({ id: 'v1', tripId: 'T1' }));
|
||||
await flush();
|
||||
assert.deepEqual(h.provider.stats().updates[FEED].reasons, [
|
||||
'probe',
|
||||
'selection',
|
||||
]);
|
||||
assert.equal(h.timers.size, 1);
|
||||
h.provider.onSelect(null);
|
||||
assert.equal(h.timers.size, 1);
|
||||
h.provider.unwatchUpdates(FEED, 'probe');
|
||||
assert.equal(h.timers.size, 0);
|
||||
h.provider.watchUpdates(FEED, 'probe');
|
||||
h.provider.stop();
|
||||
assert.equal(h.timers.size, 0);
|
||||
});
|
||||
|
||||
test('a feed without trip updates is never polled for them', async () => {
|
||||
const h = harness({ tripUpdates: false });
|
||||
h.provider.onSelect(liveTrain({ id: 'v1', tripId: 'T1' }));
|
||||
h.provider.watchUpdates(FEED, 'probe');
|
||||
await flush();
|
||||
assert.equal(h.calls.updates, 0);
|
||||
assert.equal(h.timers.size, 0);
|
||||
assert.equal(h.provider.delaysFor(FEED), null);
|
||||
});
|
||||
|
||||
test('without trip updates, the delay a train reports moves its stops', async () => {
|
||||
// Irish Rail and SJ Nord publish no trip updates, but each report says
|
||||
// how late the train is: 9 minutes here.
|
||||
const h = harness({ tripUpdates: false, clock: at('10:12') });
|
||||
await h.provider.loadSchedule(FEED);
|
||||
const late = (record) =>
|
||||
h.provider.stopsFor(liveTrain({ routeId: 'R1', ...record }), h.now);
|
||||
const byTrip = late({
|
||||
id: 'v1',
|
||||
tripId: 'T1',
|
||||
lat: LAT,
|
||||
lon: 0.06,
|
||||
delaySec: 540,
|
||||
});
|
||||
assert.equal(byTrip.match, 'trip');
|
||||
// On time it would have left Bravo at 10:11; 9 minutes late it is still
|
||||
// to reach it.
|
||||
assert.deepEqual(
|
||||
byTrip.stops.map((stop) => [stop.name, stop.state, stop.expectedArrival]),
|
||||
[
|
||||
['Alpha', 'passed', '10:09'],
|
||||
['Bravo', 'next', '10:19'],
|
||||
['Charlie', 'upcoming', '10:30'],
|
||||
],
|
||||
);
|
||||
assert.equal(byTrip.stops[1].arrivalDelaySec, 540);
|
||||
// Without a usable trip id the run is found where its timetable was 9
|
||||
// minutes ago: T1 at 10:03, not T2, which is nearer the report at 10:12.
|
||||
const byPlace = late({
|
||||
id: 'v2',
|
||||
tripId: 'SJN:DatedServiceJourney:1',
|
||||
lat: LAT,
|
||||
lon: 0.03,
|
||||
delaySec: 540,
|
||||
});
|
||||
assert.equal(byPlace.match, 'nearest');
|
||||
assert.equal(byPlace.headsign, 'Charlie');
|
||||
assert.equal(byPlace.stops[1].expectedArrival, '10:19');
|
||||
// A train 25 minutes late is still on its run after the timetable ends.
|
||||
h.now = at('10:40');
|
||||
const after = late({
|
||||
id: 'v3',
|
||||
tripId: 'T1',
|
||||
lat: LAT,
|
||||
lon: 0.18,
|
||||
delaySec: 1500,
|
||||
});
|
||||
assert.equal(after.stops[2].state, 'next');
|
||||
assert.equal(after.stops[2].expectedArrival, '10:46');
|
||||
});
|
||||
|
||||
test('a feed with trip updates takes its delays from them, not the report', async () => {
|
||||
const h = harness({ clock: at('10:12') });
|
||||
await h.provider.loadSchedule(FEED);
|
||||
const trip = h.provider.stopsFor(
|
||||
liveTrain({
|
||||
id: 'v1',
|
||||
tripId: 'T1',
|
||||
routeId: 'R1',
|
||||
lat: LAT,
|
||||
lon: 0.15,
|
||||
delaySec: 540,
|
||||
}),
|
||||
h.now,
|
||||
);
|
||||
assert.deepEqual(
|
||||
trip.stops.map((stop) => stop.state),
|
||||
['passed', 'passed', 'next'],
|
||||
);
|
||||
assert.equal(trip.stops[2].expectedArrival, '10:21');
|
||||
});
|
||||
|
||||
test('no timetable (404) is final; a failed load is retried later', async () => {
|
||||
const missing = harness({
|
||||
schedule: () => reply({ error: 'No rail schedule' }, 404),
|
||||
});
|
||||
const train = liveTrain({ id: 'v1', tripId: 'T1' });
|
||||
assert.equal(missing.provider.stopsFor(train, missing.now), null);
|
||||
await flush();
|
||||
missing.now += SCHEDULE_RETRY_MS * 10;
|
||||
assert.equal(missing.provider.stopsFor(train, missing.now), null);
|
||||
await flush();
|
||||
assert.equal(missing.calls.schedule, 1);
|
||||
assert.equal(await missing.provider.loadSchedule(FEED), null);
|
||||
|
||||
let fail = true;
|
||||
const flaky = harness({
|
||||
schedule: () => (fail ? reply({}, 503) : reply(rawSchedule)),
|
||||
});
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
fail = false;
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
assert.equal(flaky.calls.schedule, 1);
|
||||
flaky.now += SCHEDULE_RETRY_MS;
|
||||
assert.ok(await flaky.provider.loadSchedule(FEED));
|
||||
assert.equal(flaky.calls.schedule, 2);
|
||||
// A malformed pack is not fetched again.
|
||||
const broken = harness({ schedule: () => reply({ version: 99 }) });
|
||||
assert.equal(await broken.provider.loadSchedule(FEED), null);
|
||||
broken.now += SCHEDULE_RETRY_MS * 10;
|
||||
assert.equal(await broken.provider.loadSchedule(FEED), null);
|
||||
assert.equal(broken.calls.schedule, 1);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('a failing pack is tried again after 30 s, then twice as long each time, up to ten minutes', async () => {
|
||||
assert.deepEqual(
|
||||
[1, 2, 3, 4, 5, 6, 7].map(scheduleRetryDelayMs),
|
||||
[30_000, 60_000, 120_000, 240_000, 480_000, 600_000, 600_000],
|
||||
);
|
||||
let fail = true;
|
||||
const flaky = harness({
|
||||
schedule: () => (fail ? reply({}, 502) : reply(rawSchedule)),
|
||||
});
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
// One transient 5xx: back within a minute, not ten.
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
flaky.now += SCHEDULE_RETRY_FIRST_MS - 1;
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
assert.equal(flaky.calls.schedule, 1, 'not before 30 s');
|
||||
flaky.now += 1;
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
assert.equal(flaky.calls.schedule, 2);
|
||||
// Failing again, it waits twice as long.
|
||||
flaky.now += 2 * SCHEDULE_RETRY_FIRST_MS - 1;
|
||||
assert.equal(await flaky.provider.loadSchedule(FEED), null);
|
||||
assert.equal(flaky.calls.schedule, 2, 'not before 60 s');
|
||||
fail = false;
|
||||
flaky.now += 1;
|
||||
assert.ok(await flaky.provider.loadSchedule(FEED));
|
||||
assert.equal(flaky.calls.schedule, 3);
|
||||
// Loaded, it is never fetched again.
|
||||
flaky.now += SCHEDULE_RETRY_MS * 10;
|
||||
assert.ok(await flaky.provider.loadSchedule(FEED));
|
||||
assert.equal(flaky.calls.schedule, 3);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('a forgotten feed gives back its timetable and loads it again when used', async () => {
|
||||
const h = harness();
|
||||
await h.provider.loadSchedule(FEED);
|
||||
assert.equal(h.provider.stats().schedules[FEED].status, 'ready');
|
||||
assert.equal(h.calls.schedule, 1);
|
||||
h.provider.forget(FEED);
|
||||
assert.equal(h.provider.stats().schedules[FEED], undefined);
|
||||
await h.provider.loadSchedule(FEED);
|
||||
assert.equal(h.calls.schedule, 2);
|
||||
// Trip updates still polled for a reason are not dropped.
|
||||
h.provider.watchUpdates(FEED, 'probe');
|
||||
await flush();
|
||||
h.provider.forget(FEED);
|
||||
assert.ok(h.provider.stats().updates[FEED].polling);
|
||||
h.provider.unwatchUpdates(FEED, 'probe');
|
||||
h.provider.forget(FEED);
|
||||
assert.equal(h.provider.stats().updates[FEED], undefined);
|
||||
});
|
||||
@@ -0,0 +1,183 @@
|
||||
import {
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_ID,
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
SELECTED_CARD_REFRESH_MS,
|
||||
buildRailSelectionCopy,
|
||||
createRailSelectedOverlayEntry,
|
||||
} from './policy.js';
|
||||
import { getRegisteredRailFeed } from '../../data/railFeeds.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
|
||||
/**
|
||||
* Click-to-select one train, a card that follows it, and the camera handed
|
||||
* to it (follow.js). Escape or a click on anything else deselects it.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createSelection({ state, services, parts }) {
|
||||
const { governorRequestRender } = services.render;
|
||||
|
||||
/**
|
||||
* The card's anchor: the marker's current position, read on every paint,
|
||||
* whether the train is drawn as its marker or as its 3D model.
|
||||
*/
|
||||
function anchorFor(entry) {
|
||||
return () => {
|
||||
const drawn =
|
||||
entry.marker?.show !== false || entry.modelOwnsVisual === true;
|
||||
const p = drawn ? entry.marker?.position : null;
|
||||
return p && Number.isFinite(p.x) && Number.isFinite(p.y) ? p : null;
|
||||
};
|
||||
}
|
||||
|
||||
function refreshSelectedCard(force) {
|
||||
const entry = state._trains.get(state._selectedKey);
|
||||
if (!entry) return;
|
||||
const now = Date.now();
|
||||
if (!force && now - state._selectedCardAt < SELECTED_CARD_REFRESH_MS)
|
||||
return;
|
||||
state._selectedCardAt = now;
|
||||
const feed = getRegisteredRailFeed(entry.feedId);
|
||||
if (!feed) return;
|
||||
const copy = buildRailSelectionCopy(
|
||||
feed,
|
||||
entry.record,
|
||||
now,
|
||||
entry.fetchedAt,
|
||||
entry,
|
||||
t,
|
||||
state._trip,
|
||||
);
|
||||
const text = JSON.stringify(copy);
|
||||
if (!force && text === state._selectedCardText) return;
|
||||
state._selectedCardText = text;
|
||||
const card = createRailSelectedOverlayEntry(
|
||||
entry.key,
|
||||
anchorFor(entry),
|
||||
copy,
|
||||
entry.category,
|
||||
);
|
||||
state._overlayHost.setEntries(
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_ID,
|
||||
card ? [card] : [],
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Select a train without touching the camera. Called by a click (through
|
||||
* selectAndFocusTrain) and by the duplicate filter, which moves the
|
||||
* selection to another feed's copy of the same train; a follow on the old
|
||||
* copy then glides to the new one.
|
||||
* @param {string} key
|
||||
*/
|
||||
function selectTrain(key) {
|
||||
if (!state._trains.has(key)) return;
|
||||
const hadSelection = state._selectedKey !== null;
|
||||
const previous = state._trains.get(state._selectedKey);
|
||||
state._selectedKey = key;
|
||||
const entry = state._trains.get(key);
|
||||
if (previous && previous !== entry) parts.follow.handover(entry);
|
||||
// The first selection dims every other train; a change of selection only
|
||||
// swaps the two trains involved.
|
||||
if (!hadSelection) parts.rendering.paintAll();
|
||||
else {
|
||||
if (previous) parts.rendering.paint(previous);
|
||||
parts.rendering.paint(entry);
|
||||
}
|
||||
// Line and stops first, so the card is built with this trip's stops.
|
||||
parts.routes.onSelectionChanged();
|
||||
refreshSelectedCard(true);
|
||||
// Its feed is polled for it at any distance from now on.
|
||||
parts.viewport.requestProximityCheck();
|
||||
governorRequestRender('rail-select');
|
||||
}
|
||||
|
||||
/**
|
||||
* Select the train the user picked and give it the camera (follow.js): a
|
||||
* moving train is followed, any other flown to once. Picking the train
|
||||
* already followed keeps the follow as it is.
|
||||
* @param {string} key
|
||||
*/
|
||||
function selectAndFocusTrain(key) {
|
||||
if (!state._trains.has(key)) return;
|
||||
const following = parts.follow.isFollowing(key);
|
||||
// Another train's follow lets go first, so this is never taken for a
|
||||
// move between two copies of one train.
|
||||
if (!following) parts.follow.release();
|
||||
selectTrain(key);
|
||||
if (!following) parts.follow.focus(state._trains.get(key));
|
||||
}
|
||||
|
||||
/**
|
||||
* Deselect, letting go of the camera where it is.
|
||||
* @param {{untrack?: boolean}} [options] `untrack: false` when another
|
||||
* camera owner took over and what the camera follows must stay.
|
||||
*/
|
||||
function clearSelection({ untrack = true } = {}) {
|
||||
const hadSelection = state._selectedKey !== null;
|
||||
parts.follow.release({ untrack });
|
||||
state._selectedKey = null;
|
||||
state._selectedCardText = null;
|
||||
if (hadSelection) {
|
||||
parts.rendering.paintAll();
|
||||
parts.routes.onSelectionChanged();
|
||||
// A feed held for the train goes back to the viewport's rules.
|
||||
parts.viewport.requestProximityCheck();
|
||||
}
|
||||
state._overlayHost.setEntries(
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_ID,
|
||||
[],
|
||||
RAIL_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
);
|
||||
governorRequestRender('rail-deselect');
|
||||
}
|
||||
|
||||
function onKeyDown(event) {
|
||||
if (event.key === 'Escape' && state._selectedKey) clearSelection();
|
||||
}
|
||||
|
||||
/**
|
||||
* The train a click's hit names: one of this layer's icons, or a train's
|
||||
* 3D model (its pick meta is the train's key); null for anything else.
|
||||
*/
|
||||
function trainKeyOf(hit) {
|
||||
if (!hit) return null;
|
||||
if (hit.set && hit.set === state._icons?.id)
|
||||
return state._trains.has(hit.id) ? hit.id : null;
|
||||
const meta = hit.meta;
|
||||
return typeof meta === 'string' && state._trains.has(meta) ? meta : null;
|
||||
}
|
||||
|
||||
function installClickHandler(viewer) {
|
||||
if (state._clickSubscription) return;
|
||||
// The dispatcher maps a sensor-style click back into the pick buffer
|
||||
// and skips it while a tool holds the pointer.
|
||||
state._clickSubscription = inputFor(viewer).onClick((event) => {
|
||||
if (!state._enabled) return;
|
||||
const key = trainKeyOf(event.drawHit);
|
||||
if (key) selectAndFocusTrain(key);
|
||||
else if (state._selectedKey) clearSelection();
|
||||
});
|
||||
globalThis.document?.addEventListener?.('keydown', onKeyDown);
|
||||
parts.follow.install(viewer);
|
||||
}
|
||||
|
||||
function removeClickHandler() {
|
||||
state._clickSubscription?.();
|
||||
state._clickSubscription = null;
|
||||
globalThis.document?.removeEventListener?.('keydown', onKeyDown);
|
||||
parts.follow.uninstall();
|
||||
}
|
||||
|
||||
return {
|
||||
refreshSelectedCard,
|
||||
selectTrain,
|
||||
selectAndFocusTrain,
|
||||
clearSelection,
|
||||
onKeyDown,
|
||||
installClickHandler,
|
||||
removeClickHandler,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
/** Request rail snapshots, path packs, timetables and trip updates through caller-owned transport. */
|
||||
export function createRailSource({
|
||||
fetchImpl = (...args) => fetch(...args),
|
||||
} = {}) {
|
||||
/**
|
||||
* GET one per-feed JSON resource and hand back a response-like object whose
|
||||
* body read still honours the caller's abort.
|
||||
* @param {string} route `trains`, `paths`, `schedule` or `updates`.
|
||||
* @param {string} feedId
|
||||
* @param {{signal?: AbortSignal}} [options]
|
||||
*/
|
||||
function requestFeedJson(route, feedId, { signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
if (typeof feedId !== 'string' || !feedId || feedId.length > 160)
|
||||
throw new TypeError('A rail feed identifier is required');
|
||||
return Promise.resolve(
|
||||
fetchImpl(`/api/rail/${route}/${encodeURIComponent(feedId)}`, {
|
||||
signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
}),
|
||||
).then((response) => {
|
||||
signal?.throwIfAborted();
|
||||
return {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
headers: response.headers,
|
||||
async json() {
|
||||
const body = await response.json();
|
||||
signal?.throwIfAborted();
|
||||
return body;
|
||||
},
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
/** Read the public catalog of enabled feeds. */
|
||||
async getFeeds({ signal } = {}) {
|
||||
signal?.throwIfAborted();
|
||||
const response = await fetchImpl('/api/rail/feeds', {
|
||||
signal,
|
||||
headers: { Accept: 'application/json' },
|
||||
});
|
||||
if (!response.ok) throw new Error('Rail feeds HTTP ' + response.status);
|
||||
const body = await response.json();
|
||||
signal?.throwIfAborted();
|
||||
if (!Array.isArray(body?.feeds))
|
||||
throw new Error('Malformed rail feed catalog');
|
||||
return body.feeds;
|
||||
},
|
||||
/** The feed's current train-only snapshot. */
|
||||
requestSnapshot(feedId, options) {
|
||||
return requestFeedJson('trains', feedId, options);
|
||||
},
|
||||
/** The feed's path pack (route shapes); 404 when none is published. */
|
||||
requestPaths(feedId, options) {
|
||||
return requestFeedJson('paths', feedId, options);
|
||||
},
|
||||
/** The feed's timetable pack; 404 when none is published. */
|
||||
requestSchedule(feedId, options) {
|
||||
return requestFeedJson('schedule', feedId, options);
|
||||
},
|
||||
/** The feed's live trip updates (delays); 404 for a feed without them. */
|
||||
requestUpdates(feedId, options) {
|
||||
return requestFeedJson('updates', feedId, options);
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
// The Rail source names a registered feed id and nothing else: the catalog
|
||||
// route, the per-feed train route with the id encoded as one path segment,
|
||||
// and the caller's abort signal at every await.
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { createRailSource } from './source.js';
|
||||
|
||||
const json = (body, status = 200) =>
|
||||
new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
const isAbort = (error) => error?.name === 'AbortError';
|
||||
|
||||
test('the feed catalog is read from the public catalog route', async () => {
|
||||
const requested = [];
|
||||
const feeds = [
|
||||
{
|
||||
id: 'mbta-rail',
|
||||
name: 'MBTA',
|
||||
center: { lat: 42.36, lon: -71.06 },
|
||||
loadRadiusKm: 110,
|
||||
},
|
||||
];
|
||||
const source = createRailSource({
|
||||
fetchImpl: async (url, init) => {
|
||||
requested.push({ url, accept: init.headers.Accept });
|
||||
return json({ feeds });
|
||||
},
|
||||
});
|
||||
assert.deepEqual(await source.getFeeds(), feeds);
|
||||
assert.deepEqual(requested, [
|
||||
{ url: '/api/rail/feeds', accept: 'application/json' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('feed catalog failures are reported', async () => {
|
||||
const failing = createRailSource({ fetchImpl: async () => json({}, 503) });
|
||||
await assert.rejects(failing.getFeeds(), /Rail feeds HTTP 503/);
|
||||
const malformed = createRailSource({
|
||||
fetchImpl: async () => json({ feeds: {} }),
|
||||
});
|
||||
await assert.rejects(malformed.getFeeds(), /Malformed rail feed catalog/);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
await assert.rejects(
|
||||
createRailSource({
|
||||
fetchImpl: async () => json({ feeds: [] }),
|
||||
}).getFeeds({ signal: aborted.signal }),
|
||||
isAbort,
|
||||
);
|
||||
});
|
||||
|
||||
test('a snapshot is requested from the train route for that feed', async () => {
|
||||
const requested = [];
|
||||
const snapshot = { feedId: 'mta-lirr', count: 0, dropped: 3, trains: [] };
|
||||
const controller = new AbortController();
|
||||
const source = createRailSource({
|
||||
fetchImpl: async (url, init) => {
|
||||
requested.push({
|
||||
url,
|
||||
signal: init.signal,
|
||||
accept: init.headers.Accept,
|
||||
});
|
||||
return new Response(JSON.stringify(snapshot), {
|
||||
status: 200,
|
||||
headers: { 'X-GEV-Cache': 'HIT', 'X-Rail-Contact': '1794000000000' },
|
||||
});
|
||||
},
|
||||
});
|
||||
const response = await source.requestSnapshot('mta-lirr', {
|
||||
signal: controller.signal,
|
||||
});
|
||||
assert.deepEqual(requested, [
|
||||
{
|
||||
url: '/api/rail/trains/mta-lirr',
|
||||
signal: controller.signal,
|
||||
accept: 'application/json',
|
||||
},
|
||||
]);
|
||||
assert.equal(response.ok, true);
|
||||
assert.equal(response.status, 200);
|
||||
assert.equal(response.headers.get('x-gev-cache'), 'HIT');
|
||||
assert.equal(response.headers.get('x-rail-contact'), '1794000000000');
|
||||
assert.deepEqual(await response.json(), snapshot);
|
||||
});
|
||||
|
||||
test('path packs are requested from the paths route with the same wrapper', async () => {
|
||||
const requested = [];
|
||||
const pack = { version: 1, feedId: 'grt-ion', shapes: [] };
|
||||
const source = createRailSource({
|
||||
fetchImpl: async (url) => {
|
||||
requested.push(url);
|
||||
return new Response(JSON.stringify(pack), { status: 200 });
|
||||
},
|
||||
});
|
||||
const response = await source.requestPaths('grt-ion');
|
||||
assert.deepEqual(requested, ['/api/rail/paths/grt-ion']);
|
||||
assert.equal(response.ok, true);
|
||||
assert.deepEqual(await response.json(), pack);
|
||||
assert.throws(() => source.requestPaths(''), TypeError);
|
||||
});
|
||||
|
||||
test('the feed id is encoded as a single path segment', async () => {
|
||||
const requested = [];
|
||||
const source = createRailSource({
|
||||
fetchImpl: async (url) => {
|
||||
requested.push(url);
|
||||
return json({}, 404);
|
||||
},
|
||||
});
|
||||
const response = await source.requestSnapshot('../feeds?x=1 #');
|
||||
assert.equal(response.ok, false);
|
||||
assert.equal(response.status, 404);
|
||||
assert.deepEqual(requested, ['/api/rail/trains/..%2Ffeeds%3Fx%3D1%20%23']);
|
||||
});
|
||||
|
||||
test('a missing, non-string or oversized feed id is refused', () => {
|
||||
let calls = 0;
|
||||
const source = createRailSource({
|
||||
fetchImpl: async () => {
|
||||
calls += 1;
|
||||
return json({});
|
||||
},
|
||||
});
|
||||
for (const id of ['', undefined, null, 42, {}, 'a'.repeat(161)]) {
|
||||
assert.throws(
|
||||
() => source.requestSnapshot(id),
|
||||
{ name: 'TypeError', message: 'A rail feed identifier is required' },
|
||||
String(id).slice(0, 12),
|
||||
);
|
||||
}
|
||||
assert.doesNotThrow(() => source.requestSnapshot('a'.repeat(160)));
|
||||
assert.equal(calls, 1);
|
||||
});
|
||||
|
||||
test('an already aborted request never reaches the network', () => {
|
||||
let calls = 0;
|
||||
const source = createRailSource({
|
||||
fetchImpl: async () => {
|
||||
calls += 1;
|
||||
return json({});
|
||||
},
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
assert.throws(
|
||||
() => source.requestSnapshot('mbta-rail', { signal: controller.signal }),
|
||||
isAbort,
|
||||
);
|
||||
assert.equal(calls, 0);
|
||||
});
|
||||
|
||||
test('an abort while the response is in flight rejects the snapshot', async () => {
|
||||
const controller = new AbortController();
|
||||
const source = createRailSource({
|
||||
fetchImpl: async () => {
|
||||
controller.abort();
|
||||
return json({ trains: [] });
|
||||
},
|
||||
});
|
||||
await assert.rejects(
|
||||
source.requestSnapshot('mbta-rail', { signal: controller.signal }),
|
||||
isAbort,
|
||||
);
|
||||
});
|
||||
|
||||
test('an abort while the body is read rejects the parsed snapshot', async () => {
|
||||
const controller = new AbortController();
|
||||
const source = createRailSource({
|
||||
fetchImpl: async () => json({ trains: [] }),
|
||||
});
|
||||
const response = await source.requestSnapshot('mbta-rail', {
|
||||
signal: controller.signal,
|
||||
});
|
||||
controller.abort();
|
||||
await assert.rejects(response.json(), isAbort);
|
||||
});
|
||||
|
||||
test('timetables and trip updates use the same per-feed wrapper', async () => {
|
||||
const requested = [];
|
||||
const source = createRailSource({
|
||||
fetchImpl: async (url, init) => {
|
||||
requested.push([url, init.headers.Accept]);
|
||||
return url.includes('/schedule/')
|
||||
? json({ error: 'No rail schedule' }, 404)
|
||||
: json({ trips: [{ tripId: 't1', delaySec: 120 }] });
|
||||
},
|
||||
});
|
||||
const schedule = await source.requestSchedule('mbta-rail');
|
||||
assert.equal(schedule.ok, false);
|
||||
assert.equal(schedule.status, 404);
|
||||
const updates = await source.requestUpdates('mbta-rail');
|
||||
assert.equal(updates.ok, true);
|
||||
assert.deepEqual(await updates.json(), {
|
||||
trips: [{ tripId: 't1', delaySec: 120 }],
|
||||
});
|
||||
assert.deepEqual(requested, [
|
||||
['/api/rail/schedule/mbta-rail', 'application/json'],
|
||||
['/api/rail/updates/mbta-rail', 'application/json'],
|
||||
]);
|
||||
assert.throws(() => source.requestSchedule(''), TypeError);
|
||||
assert.throws(() => source.requestUpdates(42), TypeError);
|
||||
});
|
||||
@@ -0,0 +1,275 @@
|
||||
/**
|
||||
* @module layers/rail/stopLabels
|
||||
* @description Which stops of a selected train's trip the map labels, the
|
||||
* colour of each label's time chip, and the shared-overlay entries for them.
|
||||
*
|
||||
* Stops come from an injected provider (see createRailLayer in index.js),
|
||||
* normally the stop list railSchedule.tripStops() returns. The fields read
|
||||
* here are:
|
||||
*
|
||||
* {
|
||||
* stopId: string,
|
||||
* name: string,
|
||||
* parentName?: string|null, // the station a platform stop belongs to
|
||||
* lat: number, lon: number,
|
||||
* state: 'passed' | 'next' | 'upcoming',
|
||||
* atStop?: boolean, // the train dwells at its next stop
|
||||
* relative: string, // 'T−4' (due in 4 min), 'T+3' (3 min ago)
|
||||
* expectedArrival?: string, // 24 h, station local time: '14:32'
|
||||
* expectedDeparture?: string,
|
||||
* arrivalDelaySec?: number, // expected minus timetable
|
||||
* departureDelaySec?: number,
|
||||
* skipped?: boolean, // cancelled at this stop
|
||||
* passThrough?: boolean, // the train runs through without stopping
|
||||
* }
|
||||
*
|
||||
* The clock and the delay shown are those of the event `relative` counts to:
|
||||
* the departure from a stop passed or dwelt at, else the arrival.
|
||||
*
|
||||
* The map labels at most four stops: the stop just passed, the next stop, the
|
||||
* stop after it and the terminus. Every other stop is a dot without a label.
|
||||
*
|
||||
* Pure: no Cesium, no DOM. The caller supplies anchors.
|
||||
*/
|
||||
|
||||
/** Overlay source for the selected train's stop labels. */
|
||||
export const RAIL_STOP_OVERLAY_SOURCE_ID = 'rail-stops';
|
||||
export const RAIL_STOP_OVERLAY_SOURCE_OPTIONS = Object.freeze({
|
||||
cohortLimit: 4,
|
||||
collisionCapacity: 4,
|
||||
maxVisible: 4,
|
||||
moving: false,
|
||||
});
|
||||
|
||||
/** A stop this late or later shows an amber time chip (ms). */
|
||||
export const STOP_LATE_MS = 3 * 60_000;
|
||||
/** ...and this late or later, a red one (ms). */
|
||||
export const STOP_VERY_LATE_MS = 10 * 60_000;
|
||||
|
||||
/** Time-chip colours: on time, late, very late. */
|
||||
export const STOP_CHIP_COLORS = Object.freeze({
|
||||
onTime: '#C9D1D9',
|
||||
late: '#FFB020',
|
||||
veryLate: '#FF4D4F',
|
||||
});
|
||||
|
||||
/** Label roles, most important first for the overlay host. */
|
||||
const ROLE_PRIORITY = Object.freeze({
|
||||
next: 4,
|
||||
previous: 3,
|
||||
afterNext: 2,
|
||||
terminus: 1,
|
||||
});
|
||||
|
||||
/** Above any ambient label another layer publishes. */
|
||||
const STOP_LABEL_BASE_PRIORITY = 1e12;
|
||||
|
||||
/**
|
||||
* The name a stop is shown by: its station's, when the timetable lists the
|
||||
* platform as a child of one ("Town Hall Station", not "Town Hall Station
|
||||
* Platform 3"), else its own.
|
||||
* @param {object} stop
|
||||
* @returns {string}
|
||||
*/
|
||||
export function stopName(stop) {
|
||||
const station =
|
||||
typeof stop?.parentName === 'string' ? stop.parentName.trim() : '';
|
||||
if (station) return station;
|
||||
return typeof stop?.name === 'string' ? stop.name.trim() : '';
|
||||
}
|
||||
|
||||
/** Whether a value is a drawable stop: named and placed. */
|
||||
function placedStop(stop) {
|
||||
return (
|
||||
!!stop &&
|
||||
stopName(stop) !== '' &&
|
||||
Number.isFinite(stop.lat) &&
|
||||
Number.isFinite(stop.lon) &&
|
||||
Math.abs(stop.lat) <= 90
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether the train calls at a stop: worth a label, a card line, a role. */
|
||||
function callingStop(stop) {
|
||||
return placedStop(stop) && stop.skipped !== true && stop.passThrough !== true;
|
||||
}
|
||||
|
||||
/** Whether the stop's shown event is its departure rather than its arrival. */
|
||||
function showsDeparture(stop) {
|
||||
return stop?.state === 'passed' || stop?.atStop === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* The 24 h station-local clock of the stop's shown event.
|
||||
* @param {object} stop
|
||||
* @returns {string}
|
||||
*/
|
||||
export function stopClock(stop) {
|
||||
const departure = showsDeparture(stop);
|
||||
const first = departure ? stop?.expectedDeparture : stop?.expectedArrival;
|
||||
const other = departure ? stop?.expectedArrival : stop?.expectedDeparture;
|
||||
if (typeof first === 'string' && first) return first;
|
||||
return typeof other === 'string' ? other : '';
|
||||
}
|
||||
|
||||
/**
|
||||
* How late the stop's shown event is expected, in ms (never negative: an
|
||||
* early train is on time for the chip), or NaN when the delay is unknown.
|
||||
* @param {object} stop
|
||||
* @returns {number}
|
||||
*/
|
||||
export function stopDelayMs(stop) {
|
||||
const departure = showsDeparture(stop);
|
||||
const first = departure ? stop?.departureDelaySec : stop?.arrivalDelaySec;
|
||||
const other = departure ? stop?.arrivalDelaySec : stop?.departureDelaySec;
|
||||
// Only a number is a delay: null or a string is "unknown", not zero.
|
||||
const seconds = Number.isFinite(first) ? first : other;
|
||||
return Number.isFinite(seconds) ? Math.max(0, seconds * 1000) : NaN;
|
||||
}
|
||||
|
||||
/**
|
||||
* The time-chip colour for a delay.
|
||||
* @param {number} delayMs
|
||||
* @returns {string}
|
||||
*/
|
||||
export function stopChipColor(delayMs) {
|
||||
if (Number.isFinite(delayMs) && delayMs >= STOP_VERY_LATE_MS)
|
||||
return STOP_CHIP_COLORS.veryLate;
|
||||
if (Number.isFinite(delayMs) && delayMs >= STOP_LATE_MS)
|
||||
return STOP_CHIP_COLORS.late;
|
||||
return STOP_CHIP_COLORS.onTime;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whole minutes late, for the card's "(+n min late)", or 0 when on time or
|
||||
* unknown.
|
||||
* @param {object} stop
|
||||
* @returns {number}
|
||||
*/
|
||||
export function stopLateMinutes(stop) {
|
||||
const delay = stopDelayMs(stop);
|
||||
return Number.isFinite(delay) ? Math.round(delay / 60_000) : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The stop just passed and the next stop of a trip, among the stops the train
|
||||
* calls at. The next stop is the one the timetable marks `next`, else the
|
||||
* first not yet passed; the previous is the last passed stop before it.
|
||||
* @param {object[]} stops In trip order.
|
||||
* @returns {{previous: number, next: number}} Indices, -1 when absent.
|
||||
*/
|
||||
export function stopRoleIndices(stops) {
|
||||
const list = Array.isArray(stops) ? stops : [];
|
||||
let next = list.findIndex(
|
||||
(stop) => callingStop(stop) && stop.state === 'next',
|
||||
);
|
||||
if (next < 0)
|
||||
next = list.findIndex(
|
||||
(stop) => callingStop(stop) && stop.state !== 'passed',
|
||||
);
|
||||
let previous = -1;
|
||||
const before = next < 0 ? list.length : next;
|
||||
for (let i = before - 1; i >= 0; i--) {
|
||||
if (callingStop(list[i]) && list[i].state === 'passed') {
|
||||
previous = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
return { previous, next };
|
||||
}
|
||||
|
||||
/**
|
||||
* Choose what to draw for a trip: at most four labelled stops (previous,
|
||||
* next, after-next, terminus) among those the train calls at, and a dot for
|
||||
* every other placed stop (skipped and run-through stops too: the line passes
|
||||
* them).
|
||||
* @param {object[]} stops In trip order.
|
||||
* @returns {{labels: {stop: object, index: number, role: string,
|
||||
* priority: number}[], dots: {stop: object, index: number, passed: boolean}[]}}
|
||||
*/
|
||||
export function selectStopLabels(stops) {
|
||||
const list = Array.isArray(stops) ? stops : [];
|
||||
const { previous, next } = stopRoleIndices(list);
|
||||
const chosen = new Map();
|
||||
const take = (index, role) => {
|
||||
if (index < 0 || index >= list.length || chosen.has(index)) return;
|
||||
if (!callingStop(list[index])) return;
|
||||
chosen.set(index, role);
|
||||
};
|
||||
take(next, 'next');
|
||||
take(previous, 'previous');
|
||||
if (next >= 0) {
|
||||
let after = next + 1;
|
||||
while (after < list.length && !callingStop(list[after])) after++;
|
||||
take(after, 'afterNext');
|
||||
}
|
||||
let last = list.length - 1;
|
||||
while (last >= 0 && !callingStop(list[last])) last--;
|
||||
// The terminus is worth a label while the train still has it ahead.
|
||||
if (last >= 0 && list[last].state !== 'passed') take(last, 'terminus');
|
||||
const labels = [...chosen]
|
||||
.map(([index, role]) => ({
|
||||
stop: list[index],
|
||||
index,
|
||||
role,
|
||||
priority: ROLE_PRIORITY[role],
|
||||
}))
|
||||
.sort((a, b) => a.index - b.index);
|
||||
const dots = [];
|
||||
for (let i = 0; i < list.length; i++) {
|
||||
if (chosen.has(i) || !placedStop(list[i])) continue;
|
||||
dots.push({ stop: list[i], index: i, passed: list[i].state === 'passed' });
|
||||
}
|
||||
return { labels, dots };
|
||||
}
|
||||
|
||||
/**
|
||||
* The text a stop label carries: the name, then the clock and the relative
|
||||
* time, as `Yonkers · 14:32 T−4` once the host joins title and detail.
|
||||
* @param {object} stop
|
||||
* @returns {{title: string, detail: string}}
|
||||
*/
|
||||
export function stopLabelText(stop) {
|
||||
const time = [stopClock(stop), stop?.relative]
|
||||
.filter((part) => typeof part === 'string' && part !== '')
|
||||
.join(' ');
|
||||
return { title: stopName(stop), detail: time };
|
||||
}
|
||||
|
||||
/**
|
||||
* Shared-host entries for the chosen labels. Their time chip (the accent the
|
||||
* host paints beside the text and along the leader) is coloured by delay.
|
||||
* @param {string} trainKey The selected train, so ids change with it.
|
||||
* @param {ReturnType<typeof selectStopLabels>['labels']} labels
|
||||
* @param {(stop: object) => object|null} anchorFor Cartesian for a stop.
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function createStopOverlayEntries(trainKey, labels, anchorFor) {
|
||||
const entries = [];
|
||||
for (const label of labels || []) {
|
||||
const position = anchorFor(label.stop);
|
||||
if (!position) continue;
|
||||
const { title, detail } = stopLabelText(label.stop);
|
||||
entries.push({
|
||||
id: `${trainKey}:${label.index}:${label.stop.stopId ?? label.stop.name}`,
|
||||
variant: 'track',
|
||||
title,
|
||||
details: detail ? [detail] : [],
|
||||
accent: stopChipColor(stopDelayMs(label.stop)),
|
||||
priority: STOP_LABEL_BASE_PRIORITY + label.priority,
|
||||
collisionGroup: 'ambient-label',
|
||||
// The selected train's card is in the card domain; labels fit around it.
|
||||
yieldToCollisionGroup: 'ambient-card',
|
||||
paintLane: 'ambient-track',
|
||||
position,
|
||||
gapPx: 10,
|
||||
verticalOnly: true,
|
||||
placement: 'above',
|
||||
horizonCull: true,
|
||||
edgeFade: 'keyhole',
|
||||
interactive: false,
|
||||
metadata: { role: label.role },
|
||||
});
|
||||
}
|
||||
return entries;
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
// Which of a selected train's stops the map labels, how the label's time
|
||||
// chip is coloured by delay, and the overlay entries the layer publishes.
|
||||
// Stops have the shape railSchedule.tripStops() returns.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
STOP_CHIP_COLORS,
|
||||
STOP_LATE_MS,
|
||||
STOP_VERY_LATE_MS,
|
||||
createStopOverlayEntries,
|
||||
selectStopLabels,
|
||||
stopChipColor,
|
||||
stopClock,
|
||||
stopDelayMs,
|
||||
stopLabelText,
|
||||
stopLateMinutes,
|
||||
stopName,
|
||||
stopRoleIndices,
|
||||
} from './stopLabels.js';
|
||||
|
||||
/** A stop as tripStops() lists it; times and delays are illustrative. */
|
||||
function stop(index, name, state, extra = {}) {
|
||||
return {
|
||||
index,
|
||||
stopId: `s${index}`,
|
||||
name,
|
||||
lat: 40.9 + index * 0.01,
|
||||
lon: -73.9,
|
||||
state,
|
||||
atStop: false,
|
||||
expectedArrival: `14:${String(20 + index * 4).padStart(2, '0')}`,
|
||||
expectedDeparture: `14:${String(21 + index * 4).padStart(2, '0')}`,
|
||||
arrivalDelaySec: 0,
|
||||
departureDelaySec: 0,
|
||||
skipped: false,
|
||||
passThrough: false,
|
||||
relative: state === 'passed' ? 'T+3' : 'T−4',
|
||||
...extra,
|
||||
};
|
||||
}
|
||||
|
||||
const trip = [
|
||||
stop(0, 'Grand Central', 'passed'),
|
||||
stop(1, 'Harlem–125 St', 'passed'),
|
||||
stop(2, 'Riverdale', 'passed'),
|
||||
stop(3, 'Yonkers', 'next'),
|
||||
stop(4, 'Glenwood', 'upcoming'),
|
||||
stop(5, 'Hastings', 'upcoming'),
|
||||
stop(6, 'Poughkeepsie', 'upcoming'),
|
||||
];
|
||||
|
||||
test('the map labels previous, next, after-next and terminus only', () => {
|
||||
const { labels, dots } = selectStopLabels(trip);
|
||||
assert.deepEqual(
|
||||
labels.map((label) => [label.stop.name, label.role]),
|
||||
[
|
||||
['Riverdale', 'previous'],
|
||||
['Yonkers', 'next'],
|
||||
['Glenwood', 'afterNext'],
|
||||
['Poughkeepsie', 'terminus'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
dots.map((dot) => [dot.stop.name, dot.passed]),
|
||||
[
|
||||
['Grand Central', true],
|
||||
['Harlem–125 St', true],
|
||||
['Hastings', false],
|
||||
],
|
||||
);
|
||||
// The next stop outranks the rest when labels compete for room.
|
||||
const top = labels.reduce((a, b) => (b.priority > a.priority ? b : a));
|
||||
assert.equal(top.role, 'next');
|
||||
});
|
||||
|
||||
test('never more than four labels, and none repeated near the end', () => {
|
||||
const nearEnd = [
|
||||
stop(0, 'A', 'passed'),
|
||||
stop(1, 'B', 'passed'),
|
||||
stop(2, 'C', 'next'),
|
||||
stop(3, 'D', 'upcoming'),
|
||||
];
|
||||
const { labels, dots } = selectStopLabels(nearEnd);
|
||||
// After-next is the terminus: one label, not two.
|
||||
assert.deepEqual(
|
||||
labels.map((label) => label.role),
|
||||
['previous', 'next', 'afterNext'],
|
||||
);
|
||||
assert.deepEqual(
|
||||
dots.map((dot) => dot.stop.name),
|
||||
['A'],
|
||||
);
|
||||
for (let n = 0; n <= 12; n++) {
|
||||
const list = Array.from({ length: n }, (_, i) =>
|
||||
stop(
|
||||
i,
|
||||
`S${i}`,
|
||||
i < n / 2 ? 'passed' : i === Math.ceil(n / 2) ? 'next' : 'upcoming',
|
||||
),
|
||||
);
|
||||
const chosen = selectStopLabels(list);
|
||||
assert.ok(chosen.labels.length <= 4, String(n));
|
||||
assert.equal(chosen.labels.length + chosen.dots.length, n);
|
||||
}
|
||||
});
|
||||
|
||||
test('a finished trip labels only the stop it last called at', () => {
|
||||
const done = trip.map((s) => ({ ...s, state: 'passed' }));
|
||||
const { labels } = selectStopLabels(done);
|
||||
assert.deepEqual(
|
||||
labels.map((label) => [label.stop.name, label.role]),
|
||||
[['Poughkeepsie', 'previous']],
|
||||
);
|
||||
});
|
||||
|
||||
test('skipped and run-through stops get a dot, never a label or a role', () => {
|
||||
const list = [
|
||||
stop(0, 'A', 'passed'),
|
||||
stop(1, 'B', 'passed', { passThrough: true }),
|
||||
stop(2, 'C', 'next', { skipped: true }),
|
||||
stop(3, 'D', 'upcoming'),
|
||||
stop(4, 'E', 'upcoming'),
|
||||
stop(5, 'F', 'upcoming', { skipped: true }),
|
||||
];
|
||||
assert.deepEqual(stopRoleIndices(list), { previous: 0, next: 3 });
|
||||
const { labels, dots } = selectStopLabels(list);
|
||||
assert.deepEqual(
|
||||
labels.map((label) => [label.stop.name, label.role]),
|
||||
[
|
||||
['A', 'previous'],
|
||||
['D', 'next'],
|
||||
['E', 'afterNext'],
|
||||
],
|
||||
);
|
||||
assert.deepEqual(
|
||||
dots.map((dot) => dot.stop.name),
|
||||
['B', 'C', 'F'],
|
||||
);
|
||||
});
|
||||
|
||||
test('unplaced or unnamed stops are neither labelled nor dotted', () => {
|
||||
const list = [
|
||||
stop(0, 'A', 'passed'),
|
||||
{ ...stop(1, 'B', 'next'), lat: NaN },
|
||||
stop(2, '', 'upcoming'),
|
||||
stop(3, 'D', 'upcoming'),
|
||||
];
|
||||
const { labels, dots } = selectStopLabels(list);
|
||||
assert.deepEqual(
|
||||
labels.map((label) => label.stop.name),
|
||||
['A', 'D'],
|
||||
);
|
||||
assert.deepEqual(dots, []);
|
||||
assert.deepEqual(selectStopLabels(null), { labels: [], dots: [] });
|
||||
assert.deepEqual(stopRoleIndices(undefined), { previous: -1, next: -1 });
|
||||
});
|
||||
|
||||
test('the time chip is neutral on time, amber from 3 min, red from 10 min', () => {
|
||||
assert.equal(STOP_LATE_MS, 180_000);
|
||||
assert.equal(STOP_VERY_LATE_MS, 600_000);
|
||||
assert.equal(stopChipColor(0), STOP_CHIP_COLORS.onTime);
|
||||
assert.equal(stopChipColor(STOP_LATE_MS - 1), STOP_CHIP_COLORS.onTime);
|
||||
assert.equal(stopChipColor(STOP_LATE_MS), STOP_CHIP_COLORS.late);
|
||||
assert.equal(stopChipColor(STOP_VERY_LATE_MS - 1), STOP_CHIP_COLORS.late);
|
||||
assert.equal(stopChipColor(STOP_VERY_LATE_MS), STOP_CHIP_COLORS.veryLate);
|
||||
assert.equal(stopChipColor(3 * 3_600_000), STOP_CHIP_COLORS.veryLate);
|
||||
assert.equal(stopChipColor(NaN), STOP_CHIP_COLORS.onTime);
|
||||
const colors = new Set(Object.values(STOP_CHIP_COLORS));
|
||||
assert.equal(colors.size, 3);
|
||||
});
|
||||
|
||||
test('the delay and clock are those of the event the chip counts to', () => {
|
||||
const late = stop(3, 'Yonkers', 'next', {
|
||||
arrivalDelaySec: 240,
|
||||
departureDelaySec: 660,
|
||||
});
|
||||
// Arriving: the arrival's clock and delay.
|
||||
assert.equal(stopClock(late), '14:32');
|
||||
assert.equal(stopDelayMs(late), 240_000);
|
||||
assert.equal(stopChipColor(stopDelayMs(late)), STOP_CHIP_COLORS.late);
|
||||
assert.equal(stopLateMinutes(late), 4);
|
||||
// Standing at the stop, or past it: the departure's.
|
||||
const dwelling = { ...late, atStop: true };
|
||||
assert.equal(stopClock(dwelling), '14:33');
|
||||
assert.equal(stopDelayMs(dwelling), 660_000);
|
||||
assert.equal(stopChipColor(stopDelayMs(dwelling)), STOP_CHIP_COLORS.veryLate);
|
||||
assert.equal(stopClock({ ...late, state: 'passed' }), '14:33');
|
||||
// An early train is on time; a missing delay or clock falls back.
|
||||
assert.equal(stopDelayMs({ ...late, arrivalDelaySec: -120 }), 0);
|
||||
assert.equal(stopLateMinutes({ ...late, arrivalDelaySec: -120 }), 0);
|
||||
assert.equal(stopDelayMs({ ...late, arrivalDelaySec: undefined }), 660_000);
|
||||
assert.ok(
|
||||
Number.isNaN(
|
||||
stopDelayMs({ name: 'X', arrivalDelaySec: null, departureDelaySec: 'x' }),
|
||||
),
|
||||
);
|
||||
assert.equal(stopClock({ ...late, expectedArrival: '' }), '14:33');
|
||||
assert.equal(stopClock({ name: 'X' }), '');
|
||||
});
|
||||
|
||||
test('a label reads name, then clock and relative time', () => {
|
||||
assert.deepEqual(stopLabelText(stop(3, 'Yonkers', 'next')), {
|
||||
title: 'Yonkers',
|
||||
detail: '14:32 T−4',
|
||||
});
|
||||
assert.deepEqual(stopLabelText(stop(2, 'Riverdale', 'passed')), {
|
||||
title: 'Riverdale',
|
||||
detail: '14:29 T+3',
|
||||
});
|
||||
assert.deepEqual(stopLabelText({ name: ' Glenwood ', relative: '' }), {
|
||||
title: 'Glenwood',
|
||||
detail: '',
|
||||
});
|
||||
});
|
||||
|
||||
test('overlay entries collide as labels and yield to the selected card', () => {
|
||||
const late = trip.map((s) =>
|
||||
s.name === 'Yonkers' ? { ...s, arrivalDelaySec: 720 } : s,
|
||||
);
|
||||
const { labels } = selectStopLabels(late);
|
||||
const anchors = [];
|
||||
const entries = createStopOverlayEntries(
|
||||
'rail:mta-metro-north:123',
|
||||
labels,
|
||||
(s) => {
|
||||
anchors.push(s.name);
|
||||
return s.name === 'Glenwood' ? null : { x: 1, y: 2, z: 3 };
|
||||
},
|
||||
);
|
||||
// A stop without an anchor is left out, not drawn at the origin.
|
||||
assert.deepEqual(
|
||||
entries.map((entry) => entry.title),
|
||||
['Riverdale', 'Yonkers', 'Poughkeepsie'],
|
||||
);
|
||||
assert.equal(anchors.length, 4);
|
||||
const yonkers = entries[1];
|
||||
assert.equal(yonkers.variant, 'track');
|
||||
assert.deepEqual(yonkers.details, ['14:32 T−4']);
|
||||
assert.equal(yonkers.accent, STOP_CHIP_COLORS.veryLate);
|
||||
assert.equal(yonkers.collisionGroup, 'ambient-label');
|
||||
assert.equal(yonkers.yieldToCollisionGroup, 'ambient-card');
|
||||
assert.equal(yonkers.protected, undefined);
|
||||
assert.equal(entries[0].accent, STOP_CHIP_COLORS.onTime);
|
||||
assert.ok(yonkers.priority > entries[0].priority);
|
||||
assert.ok(entries[0].priority > entries[2].priority);
|
||||
assert.equal(new Set(entries.map((entry) => entry.id)).size, entries.length);
|
||||
assert.ok(
|
||||
entries.every((entry) => entry.id.startsWith('rail:mta-metro-north:123:')),
|
||||
);
|
||||
});
|
||||
|
||||
test('a platform stop is shown by its station’s name', () => {
|
||||
const platform = stop(3, 'Wynyard Station Platform 4', 'next', {
|
||||
parentName: 'Wynyard Station',
|
||||
});
|
||||
assert.equal(stopName(platform), 'Wynyard Station');
|
||||
assert.equal(stopLabelText(platform).title, 'Wynyard Station');
|
||||
assert.equal(
|
||||
stopName({ ...platform, parentName: null }),
|
||||
'Wynyard Station Platform 4',
|
||||
);
|
||||
assert.equal(
|
||||
stopName({ ...platform, parentName: ' ' }),
|
||||
'Wynyard Station Platform 4',
|
||||
);
|
||||
// A stop known only by its station is still drawable.
|
||||
const { labels } = selectStopLabels([
|
||||
stop(0, 'A', 'passed'),
|
||||
{ ...stop(1, '', 'next'), parentName: 'Central' },
|
||||
]);
|
||||
assert.deepEqual(
|
||||
labels.map((label) => stopName(label.stop)),
|
||||
['A', 'Central'],
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,268 @@
|
||||
import { rectangleCenter } from '../../geo/rectangle.js';
|
||||
import { toDegrees, toRadians } from '../../geo/vector.js';
|
||||
import { findCamera, findFrame } from '../../render/rendererOf.js';
|
||||
import {
|
||||
ACTIVATION_ENTER_ALTITUDE_M,
|
||||
ACTIVATION_EXIT_ALTITUDE_M,
|
||||
CAMERA_DEBOUNCE_MS,
|
||||
CAMERA_PERCENTAGE_CHANGED,
|
||||
RANGE_SLACK_KM,
|
||||
isLiveRailPositionSource,
|
||||
railCatalogRetryDelayMs,
|
||||
} from './policy.js';
|
||||
import {
|
||||
RAIL_ENABLED_FEEDS,
|
||||
railFeedNeedsSchedulePack,
|
||||
railFeedsInRange,
|
||||
} from '../../data/railFeeds.js';
|
||||
|
||||
/**
|
||||
* Camera-driven feed activation: only the feeds whose coverage circle contains
|
||||
* the look-at point are polled, and only below the altitude gate; the selected
|
||||
* train's feed is polled for it wherever the camera is.
|
||||
* @param {object} context
|
||||
* @returns {object}
|
||||
*/
|
||||
export function createViewport({ state, services, parts, source }) {
|
||||
const { governorRequestRender } = services.render;
|
||||
|
||||
function cameraAltitude() {
|
||||
const height = findCamera(state._viewer)?.pose().height;
|
||||
return Number.isFinite(height) ? height : Infinity;
|
||||
}
|
||||
|
||||
/** Where the camera looks: its view rectangle's middle, else under the eye. */
|
||||
function cameraCenter() {
|
||||
const camera = findCamera(state._viewer);
|
||||
const rect = camera?.viewRectangle();
|
||||
if (rect) {
|
||||
const center = rectangleCenter({
|
||||
west: toRadians(rect.west),
|
||||
south: toRadians(rect.south),
|
||||
east: toRadians(rect.east),
|
||||
north: toRadians(rect.north),
|
||||
});
|
||||
return { lat: toDegrees(center.lat), lon: toDegrees(center.lon) };
|
||||
}
|
||||
const pose = camera?.pose();
|
||||
if (pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon))
|
||||
return { lat: pose.lat, lon: pose.lon };
|
||||
return null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bundled feeds used until the catalog has loaded: those that need no
|
||||
* schedule pack. A live feed that reads its routes from one is used only
|
||||
* once the catalog lists it, which it does only once its pack is built.
|
||||
*/
|
||||
const PACKLESS_FEEDS = RAIL_ENABLED_FEEDS.filter(
|
||||
(feed) =>
|
||||
isLiveRailPositionSource(feed.positions) &&
|
||||
!railFeedNeedsSchedulePack(feed),
|
||||
);
|
||||
|
||||
/** The server's catalog once it has loaded, else the packless feeds. */
|
||||
function pollableFeeds() {
|
||||
return state._catalog || PACKLESS_FEEDS;
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the server's feed catalog once per layer instance. It leaves out
|
||||
* the feeds whose packs are not built, which are then never polled; until
|
||||
* it answers (or with a source that has no catalog), only the feeds that
|
||||
* need no pack are used. A feed it lists without live positions is never
|
||||
* polled: no train is placed from a timetable. A catalog that fails is
|
||||
* asked for again after railCatalogRetryDelayMs while the layer is on.
|
||||
*/
|
||||
function loadCatalog() {
|
||||
if (state._catalog || state._catalogRequest) return;
|
||||
if (typeof source.getFeeds !== 'function') return;
|
||||
clearTimeout(state._catalogRetryTimer);
|
||||
state._catalogRetryTimer = null;
|
||||
const controller = new AbortController();
|
||||
const request = { controller };
|
||||
state._catalogRequest = request;
|
||||
(async () => {
|
||||
try {
|
||||
const feeds = await source.getFeeds({ signal: controller.signal });
|
||||
if (state._catalogRequest !== request) return;
|
||||
const usable = feeds.filter(
|
||||
(feed) =>
|
||||
typeof feed?.id === 'string' &&
|
||||
Number.isFinite(feed?.center?.lat) &&
|
||||
Number.isFinite(feed?.center?.lon) &&
|
||||
Number.isFinite(feed?.loadRadiusKm) &&
|
||||
isLiveRailPositionSource(feed?.positions),
|
||||
);
|
||||
state._catalog = Object.freeze(usable);
|
||||
state._catalogFailures = 0;
|
||||
state._catalogRequest = null;
|
||||
logCatalog(usable);
|
||||
runProximityCheck();
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError' || state._catalogRequest !== request)
|
||||
return;
|
||||
state._catalogRequest = null;
|
||||
state._catalogFailures += 1;
|
||||
const delay = railCatalogRetryDelayMs(state._catalogFailures);
|
||||
console.warn(
|
||||
`[Data:Rail] feed catalog unavailable, trying again in ${Math.round(delay / 1000)}s:`,
|
||||
error?.message || error,
|
||||
);
|
||||
if (!state._enabled) return;
|
||||
state._catalogRetryTimer = setTimeout(() => {
|
||||
state._catalogRetryTimer = null;
|
||||
if (state._enabled) loadCatalog();
|
||||
}, delay);
|
||||
} finally {
|
||||
if (state._catalogRequest === request) state._catalogRequest = null;
|
||||
}
|
||||
})();
|
||||
}
|
||||
|
||||
/** Say once how many live feeds the catalog lists. */
|
||||
function logCatalog(feeds) {
|
||||
console.log(`[Data:Rail] Catalog lists ${feeds.length} live train feeds`);
|
||||
}
|
||||
|
||||
function cancelCatalog() {
|
||||
state._catalogRequest?.controller.abort();
|
||||
state._catalogRequest = null;
|
||||
clearTimeout(state._catalogRetryTimer);
|
||||
state._catalogRetryTimer = null;
|
||||
}
|
||||
|
||||
function runProximityCheck() {
|
||||
if (globalThis.document?.visibilityState === 'hidden') return;
|
||||
if (!state._enabled || !state._viewer) return;
|
||||
// The feeds in use until now are marked seen before any is let go.
|
||||
parts.routes.releaseIdleFeeds(Date.now());
|
||||
const altitude = cameraAltitude();
|
||||
state._altitudeGateOpen = state._altitudeGateOpen
|
||||
? altitude <= ACTIVATION_EXIT_ALTITUDE_M
|
||||
: altitude <= ACTIVATION_ENTER_ALTITUDE_M;
|
||||
const center = state._altitudeGateOpen ? cameraCenter() : null;
|
||||
const desired = new Map();
|
||||
if (center) {
|
||||
const feeds = pollableFeeds();
|
||||
for (const feed of railFeedsInRange(center.lat, center.lon, 0, feeds))
|
||||
desired.set(feed.id, feed);
|
||||
for (const feed of railFeedsInRange(
|
||||
center.lat,
|
||||
center.lon,
|
||||
RANGE_SLACK_KM,
|
||||
feeds,
|
||||
))
|
||||
if (state._activeFeeds.has(feed.id)) desired.set(feed.id, feed);
|
||||
}
|
||||
// The selected train's feed stays polled however far out or away the
|
||||
// camera goes, so the train and its line stay on the map; while nothing
|
||||
// else would keep the feed, it carries the selected train alone and its
|
||||
// other trains go as they would with the feed.
|
||||
const selected = state._trains.get(state._selectedKey);
|
||||
const held =
|
||||
selected &&
|
||||
!desired.has(selected.feedId) &&
|
||||
state._activeFeeds.has(selected.feedId)
|
||||
? selected.feedId
|
||||
: null;
|
||||
if (held) desired.set(held, state._activeFeeds.get(held));
|
||||
const released = state._heldFeedId !== held ? state._heldFeedId : null;
|
||||
state._heldFeedId = held;
|
||||
for (const feedId of [...state._activeFeeds.keys()]) {
|
||||
if (desired.has(feedId)) continue;
|
||||
state._inFlight.get(feedId)?.controller.abort();
|
||||
state._inFlight.delete(feedId);
|
||||
state._activeFeeds.delete(feedId);
|
||||
state._feedStatus.delete(feedId);
|
||||
parts.ingestion.removeFeedTrains(feedId);
|
||||
}
|
||||
if (held) parts.ingestion.removeFeedTrains(held, state._selectedKey);
|
||||
// A feed the selection held that the view wants again brings its other
|
||||
// trains back now, not at the next poll.
|
||||
if (released && desired.has(released))
|
||||
void parts.ingestion.pollFeed(desired.get(released), state._generation);
|
||||
for (const [feedId, feed] of desired) {
|
||||
if (state._activeFeeds.has(feedId)) continue;
|
||||
state._activeFeeds.set(feedId, feed);
|
||||
void parts.ingestion.pollFeed(feed, state._generation);
|
||||
}
|
||||
parts.ingestion.sweepAgedTrains(Date.now());
|
||||
parts.routes.onCamera();
|
||||
parts.routes.applyNetwork();
|
||||
parts.rendering.syncRenderHold();
|
||||
state._dataManager?.refreshLayerStats?.();
|
||||
governorRequestRender('rail-proximity');
|
||||
}
|
||||
|
||||
function onCameraChanged() {
|
||||
// The network's altitude fade follows the zoom without the debounce; it
|
||||
// only writes when the fade crosses a step.
|
||||
parts.routes.onCamera();
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = setTimeout(() => {
|
||||
state._cameraDebounceTimer = null;
|
||||
runProximityCheck();
|
||||
}, CAMERA_DEBOUNCE_MS);
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for the camera moving, at this layer's own threshold.
|
||||
*
|
||||
* The camera port measures `changed` per listener, so this layer's finer
|
||||
* trigger (it needs to notice it has entered a feed's coverage) is its own
|
||||
* and leaves every other listener's untouched.
|
||||
* @param {object} viewer
|
||||
*/
|
||||
function watchCamera(viewer) {
|
||||
unwatchCamera();
|
||||
state._cameraChangedOff =
|
||||
findCamera(viewer)?.on('changed', onCameraChanged, {
|
||||
threshold: CAMERA_PERCENTAGE_CHANGED,
|
||||
}) ?? null;
|
||||
// A new listener measures from the view at the next tick, so a move made
|
||||
// before that tick never reaches it: look again once that tick is past.
|
||||
if (!state._cameraChangedOff) return;
|
||||
let ticks = 0;
|
||||
state._cameraFirstTickOff =
|
||||
findFrame(viewer)?.on('preUpdate', () => {
|
||||
if (++ticks < 2) return;
|
||||
state._cameraFirstTickOff?.();
|
||||
state._cameraFirstTickOff = null;
|
||||
onCameraChanged();
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
/** Stop listening for the camera moving. */
|
||||
function unwatchCamera() {
|
||||
state._cameraChangedOff?.();
|
||||
state._cameraChangedOff = null;
|
||||
state._cameraFirstTickOff?.();
|
||||
state._cameraFirstTickOff = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-run the check off the caller's stack: a selection changed, so the
|
||||
* feed it holds may change too.
|
||||
*/
|
||||
function requestProximityCheck() {
|
||||
if (!state._enabled) return;
|
||||
clearTimeout(state._cameraDebounceTimer);
|
||||
state._cameraDebounceTimer = setTimeout(() => {
|
||||
state._cameraDebounceTimer = null;
|
||||
runProximityCheck();
|
||||
}, 0);
|
||||
}
|
||||
|
||||
return {
|
||||
runProximityCheck,
|
||||
onCameraChanged,
|
||||
requestProximityCheck,
|
||||
watchCamera,
|
||||
unwatchCamera,
|
||||
cameraAltitude,
|
||||
loadCatalog,
|
||||
cancelCatalog,
|
||||
pollableFeeds,
|
||||
};
|
||||
}
|
||||
@@ -140,6 +140,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
state._cameraChangedAttached = state._cameraChangedOff !== null;
|
||||
}
|
||||
parts.rendering.startFrames(viewer);
|
||||
parts.rendering.startModels();
|
||||
parts.viewport.runProximityCheck();
|
||||
},
|
||||
|
||||
@@ -179,6 +180,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
destroyTrack(entry.track);
|
||||
}
|
||||
state._vehicles.clear();
|
||||
parts.rendering.stopModels();
|
||||
parts.height.clear();
|
||||
parts.rendering.clearMarkers();
|
||||
state._altitudeGateOpen = false;
|
||||
@@ -216,6 +218,7 @@ export function createLifecycle({ state, services, parts }) {
|
||||
*/
|
||||
destroy(viewer) {
|
||||
this.disable(viewer);
|
||||
parts.rendering.stopModels(true);
|
||||
parts.rendering.destroyMarkers(viewer);
|
||||
state._overlayHost.clearSource(TRANSIT_SELECTED_OVERLAY_SOURCE_ID);
|
||||
parts.height.clear();
|
||||
|
||||
@@ -129,7 +129,9 @@ export function createQueries({ state, parts }) {
|
||||
const visible = [];
|
||||
for (const entry of state._visible) {
|
||||
const marker = entry.marker;
|
||||
if (!marker?.position || marker.show === false) continue;
|
||||
// A vehicle drawn as its 3D model is present though its marker is hidden.
|
||||
if (!marker?.position) continue;
|
||||
if (marker.show === false && entry.modelOwnsVisual !== true) continue;
|
||||
visible.push(entry);
|
||||
}
|
||||
let chosen = visible;
|
||||
|
||||
@@ -36,6 +36,12 @@ import {
|
||||
TRANSIT_MODE_COLORS,
|
||||
vehicleNearView,
|
||||
} from './policy.js';
|
||||
import {
|
||||
fleetModelSet,
|
||||
loadFleetModelSet,
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
@@ -145,14 +151,18 @@ export function createRendering({ state, services, parts }) {
|
||||
|
||||
/** The ids of both sets (for the frame probe and floor sampling). */
|
||||
function setIds() {
|
||||
return [state._stillIcons?.id, state._movingIcons?.id].filter(Boolean);
|
||||
return [state._stillIcons?.id, state._movingIcons?.id, modelSetId()].filter(
|
||||
Boolean,
|
||||
);
|
||||
}
|
||||
|
||||
/** Whether `setId` is one of this layer's sets. */
|
||||
function ownsSet(setId) {
|
||||
return (
|
||||
typeof setId === 'string' &&
|
||||
(setId === state._stillIcons?.id || setId === state._movingIcons?.id)
|
||||
(setId === state._stillIcons?.id ||
|
||||
setId === state._movingIcons?.id ||
|
||||
setId === modelSetId())
|
||||
);
|
||||
}
|
||||
|
||||
@@ -160,6 +170,8 @@ export function createRendering({ state, services, parts }) {
|
||||
function setNameOf(setId) {
|
||||
if (setId && setId === state._movingIcons?.id) return 'moving';
|
||||
if (setId && setId === state._stillIcons?.id) return 'still';
|
||||
// A vehicle drawn as its model is picked as the vehicle.
|
||||
if (setId && setId === modelSetId()) return 'model';
|
||||
return null;
|
||||
}
|
||||
|
||||
@@ -473,7 +485,7 @@ export function createRendering({ state, services, parts }) {
|
||||
);
|
||||
entry.surfaceReady = !!known;
|
||||
entry.heightPending = !known;
|
||||
setShown(entry, !!known && vehicleInView(entry));
|
||||
setShown(entry, !!known && vehicleInView(entry) && !entry.modelOwnsVisual);
|
||||
if (known) {
|
||||
const p = entry.marker.position;
|
||||
const s = state._scratchCartesian;
|
||||
@@ -790,6 +802,7 @@ export function createRendering({ state, services, parts }) {
|
||||
const now = state.now();
|
||||
if (state._vehicles.size === 0) {
|
||||
state._moving.clear();
|
||||
updateModels();
|
||||
syncRenderHold();
|
||||
return;
|
||||
}
|
||||
@@ -848,9 +861,118 @@ export function createRendering({ state, services, parts }) {
|
||||
}
|
||||
flushMarkers();
|
||||
if (state._heightDirty.size) governorRequestRender('transit-height-batch');
|
||||
updateModels();
|
||||
syncRenderHold();
|
||||
}
|
||||
|
||||
// Under the DISPLAY rail's 3D toggle, vehicles in view near the camera are
|
||||
// drawn as the project's procedural fleet models, chosen by mode, painted
|
||||
// in their mode colour where the model marks it, on the aircraft layers'
|
||||
// icon-to-model rules (services.fleet). The fleet set loads once, up front,
|
||||
// when the layer starts.
|
||||
let fleetModels = null;
|
||||
/** Items drawn last frame, and the map the next frame's are gathered into. */
|
||||
let modelItems = new Map();
|
||||
let spareItems = new Map();
|
||||
/** The lift icons are drawn with above the floor; a model stands on the floor. */
|
||||
const groundLiftM = services.ground?.GROUND_FLOOR_LIFT_M || 0;
|
||||
|
||||
/** Load the fleet set and create the layer's models (on enable). */
|
||||
function startModels() {
|
||||
const fleet = services.fleet;
|
||||
if (!fleet?.policy || !state._viewer) return;
|
||||
loadFleetModelSet({ resolveAsset: fleet.resolveAsset }).catch(() => {
|
||||
/* models stay off; vehicles keep their icons */
|
||||
});
|
||||
fleetModels ||= createFleetModelLayer({
|
||||
viewer: state._viewer,
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
});
|
||||
}
|
||||
|
||||
/** Hand an entry's visual back to its icon. */
|
||||
function handBack(entry) {
|
||||
if (!entry.modelOwnsVisual) return;
|
||||
entry.modelOwnsVisual = false;
|
||||
if (entry.marker)
|
||||
setShown(
|
||||
entry,
|
||||
vehicleInView(entry) &&
|
||||
!entry.heightPending &&
|
||||
entry.surfaceReady !== false,
|
||||
);
|
||||
}
|
||||
|
||||
function updateModels() {
|
||||
if (!fleetModels) return;
|
||||
if (!fleetModels.active() || state._vehicles.size === 0) {
|
||||
if (modelItems.size) {
|
||||
for (const item of modelItems.values()) handBack(item.entry);
|
||||
modelItems.clear();
|
||||
fleetModels.frame(modelItems, performance.now());
|
||||
}
|
||||
return;
|
||||
}
|
||||
const set = fleetModelSet();
|
||||
const next = spareItems;
|
||||
next.clear();
|
||||
for (const entry of state._visible) {
|
||||
// A vehicle of no known mode keeps its icon: no model says what it is.
|
||||
if (!entry.marker || !entry.hasRendered || entry.mode === 'unknown')
|
||||
continue;
|
||||
let item = modelItems.get(entry.key);
|
||||
if (!item || item.entry !== entry) {
|
||||
item = {
|
||||
entry,
|
||||
pickId: entry.key,
|
||||
modelOwnsVisual: false,
|
||||
groundLiftM,
|
||||
};
|
||||
}
|
||||
if (item.mode !== entry.mode) {
|
||||
item.mode = entry.mode;
|
||||
item.spec = transitModelSpec(set, { mode: entry.mode });
|
||||
item.tint =
|
||||
TRANSIT_MODE_COLORS[entry.mode] || TRANSIT_MODE_COLORS.unknown;
|
||||
}
|
||||
item.position = entry.marker.position;
|
||||
item.headingDeg = Number.isFinite(entry.courseDeg) ? entry.courseDeg : 0;
|
||||
item.show = !entry.heightPending && entry.surfaceReady !== false;
|
||||
next.set(entry.key, item);
|
||||
}
|
||||
for (const [key, item] of modelItems)
|
||||
if (next.get(key) !== item) handBack(item.entry);
|
||||
spareItems = modelItems;
|
||||
modelItems = next;
|
||||
fleetModels.frame(modelItems, performance.now());
|
||||
for (const item of modelItems.values()) {
|
||||
const entry = item.entry;
|
||||
if (item.modelOwnsVisual) {
|
||||
entry.modelOwnsVisual = true;
|
||||
setShown(entry, false);
|
||||
} else handBack(entry);
|
||||
}
|
||||
if (fleetModels.settling) governorRequestRender('transit-models');
|
||||
}
|
||||
|
||||
/** The fleet models' set id, or null before the layer draws models. */
|
||||
function modelSetId() {
|
||||
return fleetModels?.setId ?? null;
|
||||
}
|
||||
|
||||
/** Drop every model (layer disabled); `destroy` also lets their set go. */
|
||||
function stopModels(destroy = false) {
|
||||
for (const item of modelItems.values()) item.entry.modelOwnsVisual = false;
|
||||
modelItems.clear();
|
||||
spareItems.clear();
|
||||
if (destroy) {
|
||||
fleetModels?.destroy();
|
||||
fleetModels = null;
|
||||
} else fleetModels?.clear();
|
||||
}
|
||||
|
||||
const candidatePosition = { x: 0, y: 0, z: 0 };
|
||||
/** Visibility work runs off the frame path, coalesced at four sweeps/second. */
|
||||
function requestVisibility() {
|
||||
@@ -963,7 +1085,10 @@ export function createRendering({ state, services, parts }) {
|
||||
setShown(
|
||||
entry,
|
||||
Boolean(
|
||||
visible && !entry.heightPending && entry.surfaceReady !== false,
|
||||
visible &&
|
||||
!entry.heightPending &&
|
||||
entry.surfaceReady !== false &&
|
||||
!entry.modelOwnsVisual,
|
||||
),
|
||||
);
|
||||
visibility.heightPending = !!entry.heightPending;
|
||||
@@ -1166,5 +1291,7 @@ export function createRendering({ state, services, parts }) {
|
||||
setStylePreset,
|
||||
onPreRender,
|
||||
syncRenderHold,
|
||||
startModels,
|
||||
stopModels,
|
||||
};
|
||||
}
|
||||
@@ -23,14 +23,16 @@ export function createSelection({ state, services, parts }) {
|
||||
* (the tracked-aircraft readout uses the same), so the anchor moves with the
|
||||
* sprite at frame rate, through poll arrivals, settling, a late floor and a
|
||||
* reset alike, with no per-frame work here. Null when there is nothing to
|
||||
* anchor to: a hidden or removed marker draws no card.
|
||||
* anchor to: a hidden or removed marker draws no card, unless the vehicle's
|
||||
* 3D model is drawing it in the marker's place.
|
||||
* @param {object} entry
|
||||
* @returns {() => {x: number, y: number, z: number}|null} ECEF
|
||||
*/
|
||||
function anchorFor(entry) {
|
||||
return () => {
|
||||
const marker = entry.marker;
|
||||
const p = marker?.show !== false ? marker?.position : null;
|
||||
const drawn = marker?.show !== false || entry.modelOwnsVisual === true;
|
||||
const p = drawn ? marker?.position : null;
|
||||
return p &&
|
||||
Number.isFinite(p.x) &&
|
||||
Number.isFinite(p.y) &&
|
||||
|
||||
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
|
||||
import { createSelection } from './selection.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { createCards } from './cards.js';
|
||||
import { createPhotos } from './photos.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createQueries } from './queries.js';
|
||||
@@ -24,6 +25,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
parts.selection = createSelection(context);
|
||||
parts.tracking = createTracking(context);
|
||||
parts.cards = createCards(context);
|
||||
parts.photos = createPhotos(context);
|
||||
parts.testing = createTesting(context);
|
||||
parts.evidence = createEvidence(context);
|
||||
parts.queries = createQueries(context);
|
||||
@@ -90,6 +92,9 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
buildVesselCard: parts.cards.buildVesselCard,
|
||||
buildSelectedVesselCard: parts.cards.buildSelectedVesselCard,
|
||||
cardScreenSeparated: parts.cards.cardScreenSeparated,
|
||||
/** The vessel's Open Vessel Photos photo, once its lookup answered. */
|
||||
getVesselPhoto: (id) =>
|
||||
parts.photos.vesselPhoto(vesselState.state.records.byId.get(id)),
|
||||
});
|
||||
Object.defineProperty(layer, 'testing', { value: parts.testing });
|
||||
return layer;
|
||||
|
||||
@@ -213,6 +213,8 @@ export function createIngestion({
|
||||
imo: record.imo,
|
||||
type: record.type,
|
||||
destination: record.destination,
|
||||
length: record.lengthM ?? null,
|
||||
beam: record.beamM ?? null,
|
||||
speed: record.speedMps == null ? null : record.speedMps / 0.514444,
|
||||
course: record.courseDeg,
|
||||
heading: record.headingDeg,
|
||||
|
||||
@@ -242,6 +242,7 @@ export function createLifecycle({
|
||||
if (state.preRenderRemover) {
|
||||
state.preRenderRemover();
|
||||
}
|
||||
components.rendering.destroyModels();
|
||||
resetState();
|
||||
},
|
||||
};
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
import { MMSI, parseOpenVesselPhoto } from '../../data/openVesselPhoto.js';
|
||||
|
||||
/** A failed lookup is asked again after this long; a miss is final. */
|
||||
const PHOTO_RETRY_MS = 5 * 60 * 1000;
|
||||
/** Lookups remembered per session, oldest dropped first. */
|
||||
const PHOTO_CACHE_LIMIT = 500;
|
||||
|
||||
/**
|
||||
* The selected vessel's photo, looked up once per MMSI when it is selected.
|
||||
* The answer is read with `parseOpenVesselPhoto` whatever shape the source
|
||||
* returns, so only a checked photo is ever kept. A source without
|
||||
* `getEnrichment` has no photos.
|
||||
*/
|
||||
export function createPhotos({ vesselState }) {
|
||||
/** MMSI → photo, `null` for a final miss, or `{failedAtMs}`/`{pending}`. */
|
||||
const answers = new Map();
|
||||
|
||||
function remember(mmsi, answer) {
|
||||
answers.delete(mmsi);
|
||||
answers.set(mmsi, answer);
|
||||
if (answers.size > PHOTO_CACHE_LIMIT)
|
||||
answers.delete(answers.keys().next().value);
|
||||
}
|
||||
|
||||
/** Ask for the record's photo unless it is known, asked or cooling down. */
|
||||
function requestVesselPhoto(record, now = Date.now()) {
|
||||
const mmsi = String(record?.mmsi || '');
|
||||
const source = vesselState._source;
|
||||
if (!MMSI.test(mmsi) || typeof source?.getEnrichment !== 'function') return;
|
||||
const known = answers.get(mmsi);
|
||||
if (known !== undefined) {
|
||||
if (known?.pending || known === null || known.found) return;
|
||||
if (now - known.failedAtMs < PHOTO_RETRY_MS) return;
|
||||
}
|
||||
remember(mmsi, { pending: true });
|
||||
Promise.resolve()
|
||||
.then(() => source.getEnrichment({ kind: 'photo', id: mmsi }))
|
||||
.then(
|
||||
(answer) => {
|
||||
const photo = parseOpenVesselPhoto(answer);
|
||||
remember(mmsi, photo.found ? photo : null);
|
||||
},
|
||||
() => remember(mmsi, { failedAtMs: Date.now() }),
|
||||
);
|
||||
}
|
||||
|
||||
/** The vessel's checked photo, or null. */
|
||||
function vesselPhoto(record) {
|
||||
const answer = answers.get(String(record?.mmsi || ''));
|
||||
if (!answer?.found) return null;
|
||||
const { src, width, height, photographer, licence, link } = answer;
|
||||
return { src, width, height, photographer, licence, link };
|
||||
}
|
||||
|
||||
return { requestVesselPhoto, vesselPhoto };
|
||||
}
|
||||
@@ -0,0 +1,87 @@
|
||||
// src/layers/vessels/photos.test.mjs — a selected vessel's photo is asked for
|
||||
// once per MMSI; a miss is final and a failure is retried only after a pause.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createPhotos } from './photos.js';
|
||||
|
||||
const ANSWER = Object.freeze({
|
||||
mmsi: '366999709',
|
||||
photos: [
|
||||
{
|
||||
urls: {
|
||||
mmsi: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg',
|
||||
},
|
||||
credit: 'Gordon Leggett',
|
||||
licenceName: 'CC BY 4.0',
|
||||
width: 1600,
|
||||
height: 1200,
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
const settle = () => new Promise((resolve) => setImmediate(resolve));
|
||||
|
||||
function fixture(answer) {
|
||||
const asked = [];
|
||||
const source = {
|
||||
getSnapshot() {},
|
||||
async getEnrichment(query) {
|
||||
asked.push(query);
|
||||
return answer(query);
|
||||
},
|
||||
};
|
||||
const photos = createPhotos({ vesselState: { _source: source } });
|
||||
return { photos, asked };
|
||||
}
|
||||
|
||||
test('a selected vessel is asked once and shows its checked photo', async () => {
|
||||
const { photos, asked } = fixture(() => ANSWER);
|
||||
const record = { id: 'v1', mmsi: '366999709' };
|
||||
photos.requestVesselPhoto(record);
|
||||
photos.requestVesselPhoto(record);
|
||||
await settle();
|
||||
photos.requestVesselPhoto(record);
|
||||
assert.deepEqual(asked, [{ kind: 'photo', id: '366999709' }]);
|
||||
assert.deepEqual(photos.vesselPhoto(record), {
|
||||
src: 'https://openvesselphotos.org/v1/mmsi/366999709/photos/1.jpg?size=800',
|
||||
width: 800,
|
||||
height: 600,
|
||||
photographer: 'Gordon Leggett',
|
||||
licence: 'CC BY 4.0',
|
||||
link: 'https://openvesselphotos.org/vessels/mmsi/366999709',
|
||||
});
|
||||
});
|
||||
|
||||
test('a vessel without a valid MMSI, or a source without lookups, is never asked', async () => {
|
||||
const { photos, asked } = fixture(() => ANSWER);
|
||||
photos.requestVesselPhoto({ id: 'v1', mmsi: '' });
|
||||
photos.requestVesselPhoto({ id: 'v2', mmsi: '12345' });
|
||||
await settle();
|
||||
assert.equal(asked.length, 0);
|
||||
const bare = createPhotos({ vesselState: { _source: { getSnapshot() {} } } });
|
||||
bare.requestVesselPhoto({ id: 'v3', mmsi: '366999709' });
|
||||
assert.equal(bare.vesselPhoto({ mmsi: '366999709' }), null);
|
||||
});
|
||||
|
||||
test('a miss is final; a failure is asked again only after the pause', async () => {
|
||||
let fail = true;
|
||||
const { photos, asked } = fixture(({ id }) => {
|
||||
if (id === '111111111') return { mmsi: id, photos: [] };
|
||||
if (fail) throw new Error('down');
|
||||
return ANSWER;
|
||||
});
|
||||
const missing = { mmsi: '111111111' };
|
||||
const flaky = { mmsi: '366999709' };
|
||||
photos.requestVesselPhoto(missing);
|
||||
photos.requestVesselPhoto(flaky, 0);
|
||||
await settle();
|
||||
photos.requestVesselPhoto(missing);
|
||||
photos.requestVesselPhoto(flaky, Date.now() + 1000);
|
||||
assert.equal(asked.length, 2);
|
||||
fail = false;
|
||||
photos.requestVesselPhoto(flaky, Date.now() + 10 * 60 * 1000);
|
||||
await settle();
|
||||
assert.equal(asked.length, 3);
|
||||
assert.equal(photos.vesselPhoto(missing), null);
|
||||
assert.equal(photos.vesselPhoto(flaky).photographer, 'Gordon Leggett');
|
||||
});
|
||||
@@ -654,6 +654,7 @@ export function createQueries({
|
||||
if ((idx - start) % stride !== 0) continue;
|
||||
const record = records[idx];
|
||||
const visual = components.rendering.getVisual(record);
|
||||
// Horizon visibility: a vessel drawn as its model still counts.
|
||||
if (!visual.visible) continue;
|
||||
const position = visual.position;
|
||||
if (!position) continue;
|
||||
|
||||
@@ -25,6 +25,9 @@ export function normalizeVessel(row) {
|
||||
imo: String(row.imo || ''),
|
||||
type: String(row.type || ''),
|
||||
destination: String(row.destination || ''),
|
||||
// Hull length and beam (metres), null when unreported.
|
||||
length: positiveNumber(row.length),
|
||||
beam: positiveNumber(row.beam),
|
||||
speed: finiteNumber(row.speed),
|
||||
course: finiteNumber(row.course),
|
||||
heading: finiteNumber(row.heading),
|
||||
@@ -46,6 +49,11 @@ function stampFix(record, receivedAtMs, feedLatestEpoch) {
|
||||
record.fixFeedEpoch = feedLatestEpoch;
|
||||
}
|
||||
|
||||
function positiveNumber(value) {
|
||||
const number = finiteNumber(value);
|
||||
return number !== null && number > 0 ? number : null;
|
||||
}
|
||||
|
||||
function finiteNumber(value) {
|
||||
if (value === null || value === undefined || value === '') return null;
|
||||
const number = Number(value);
|
||||
@@ -146,6 +154,8 @@ export class VesselRecords {
|
||||
record.imo = next.imo;
|
||||
record.type = next.type;
|
||||
record.destination = next.destination;
|
||||
record.length = next.length;
|
||||
record.beam = next.beam;
|
||||
record.speed = next.speed;
|
||||
record.course = next.course;
|
||||
record.heading = next.heading;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
} from '../../data/vesselLabels.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { horizonFrom, liftedForHorizon } from '../../geo/horizon.js';
|
||||
import { distance } from '../../geo/vector.js';
|
||||
import { distance, distanceSquared } from '../../geo/vector.js';
|
||||
import {
|
||||
canvasOf,
|
||||
drawOf,
|
||||
@@ -29,6 +29,12 @@ import {
|
||||
followsClock,
|
||||
} from './policy.js';
|
||||
import { vesselPositionAt } from './motion.js';
|
||||
import {
|
||||
fleetModelSet,
|
||||
loadFleetModelSet,
|
||||
vesselModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
|
||||
/** How often vessels move on as the world clock plays (wall ms). */
|
||||
const FOLLOW_POSITION_MS = 250;
|
||||
@@ -38,6 +44,9 @@ const SHIP_ICON_PX = 32;
|
||||
|
||||
let instances = 0;
|
||||
|
||||
/** How often the vessels near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
|
||||
export function createRendering({
|
||||
vesselState,
|
||||
services,
|
||||
@@ -71,6 +80,8 @@ export function createRendering({
|
||||
visualRecords.set(record, visual);
|
||||
}
|
||||
visual.position = anchorPosition(record);
|
||||
// A ship model's origin is its waterline: the sea surface, unlifted.
|
||||
visual.waterline = anchorPosition(record, 0);
|
||||
return visual;
|
||||
}
|
||||
|
||||
@@ -79,16 +90,18 @@ export function createRendering({
|
||||
* (the geoid, once its grid has loaded). Following the world clock, a
|
||||
* vessel is drawn where it was at the time.
|
||||
* @param {Object} record - Vessel record with a finite lat/lon.
|
||||
* @param {number} [liftM] Height above the sea surface (the icon's lift by
|
||||
* default; 0 for a ship model's waterline).
|
||||
* @returns {{x: number, y: number, z: number}} ECEF metres: icon items,
|
||||
* focus and the layer's queries take it as it is.
|
||||
*/
|
||||
function anchorPosition(record) {
|
||||
function anchorPosition(record, liftM = VESSEL_LIFT_M) {
|
||||
const { lat, lon } = followsClock(vesselState)
|
||||
? vesselPositionAt(record, vesselState.worldNow())
|
||||
: record;
|
||||
const heightM = components.queries.vesselDatumHeightM(
|
||||
components.tracking.currentGeoidN(lat, lon),
|
||||
VESSEL_LIFT_M,
|
||||
liftM,
|
||||
);
|
||||
return fromDegrees(lon, lat, heightM);
|
||||
}
|
||||
@@ -142,6 +155,7 @@ export function createRendering({
|
||||
* at the geoid would clip behind local tide/mesh noise).
|
||||
*/
|
||||
function ensureCollections(viewer) {
|
||||
ensureModels(viewer);
|
||||
if (!viewer || state.icons) return;
|
||||
const set = drawOf(viewer).icons({
|
||||
id: `ais-vessels:${++instances}`,
|
||||
@@ -193,7 +207,8 @@ export function createRendering({
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
return {
|
||||
id: visual.iconId,
|
||||
show: !isCockpitSubject(record),
|
||||
// Hidden while the bridge camera rides it, or its model draws it.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual,
|
||||
pos: visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
@@ -302,6 +317,128 @@ export function createRendering({
|
||||
return icon;
|
||||
}
|
||||
|
||||
// Under the DISPLAY rail's 3D toggle, vessels near the camera are drawn as
|
||||
// the project's procedural fleet models at their reported length and beam,
|
||||
// on the aircraft layers' icon-to-model rules (services.fleet). The fleet
|
||||
// set loads once, up front, when the layer starts.
|
||||
let fleetModels = null;
|
||||
/** Items drawn last frame, and the map the next frame's are gathered into. */
|
||||
let modelItems = new Map();
|
||||
let spareItems = new Map();
|
||||
let modelCandidatesAtMs = -Infinity;
|
||||
|
||||
function ensureModels(viewer) {
|
||||
const fleet = services.fleet;
|
||||
if (!viewer || fleetModels || !fleet?.policy) return;
|
||||
loadFleetModelSet({ resolveAsset: fleet.resolveAsset }).catch(() => {
|
||||
/* models stay off; vessels keep their icons */
|
||||
});
|
||||
fleetModels = createFleetModelLayer({
|
||||
viewer,
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
// A hull below the waterline would show through a plain globe.
|
||||
waterline: true,
|
||||
});
|
||||
}
|
||||
|
||||
/** The model item for `record`, its spec rebuilt only when its type or size changes. */
|
||||
function modelItem(record, set) {
|
||||
let item = modelItems.get(record.id);
|
||||
if (!item || item.record !== record)
|
||||
item = {
|
||||
record,
|
||||
pickId: getVisual(record).meta,
|
||||
tint: null,
|
||||
modelOwnsVisual: false,
|
||||
};
|
||||
const specKey = `${record.type}|${record.length}|${record.beam}|${record.name}`;
|
||||
if (item.specKey !== specKey) {
|
||||
item.specKey = specKey;
|
||||
item.spec = vesselModelSpec(set, record);
|
||||
}
|
||||
item.position = getVisual(record).waterline;
|
||||
item.headingDeg = vesselCourseDeg(record);
|
||||
item.show = record.id !== state.cockpitSubjectId;
|
||||
return item;
|
||||
}
|
||||
|
||||
/** Gather the vessels within the models' keep radius of the camera into `into`. */
|
||||
function gatherModelItems(set, into) {
|
||||
const eye = state.viewer
|
||||
? findCamera(state.viewer)?.pose()?.position
|
||||
: null;
|
||||
if (!eye) return;
|
||||
const policy = services.fleet.policy;
|
||||
const keepM =
|
||||
services.fleet.display?.()?.models3dMode === 'all'
|
||||
? policy.keepAllM
|
||||
: policy.keepM;
|
||||
const limitSq = keepM * keepM * 1.44;
|
||||
for (const record of state.records.all) {
|
||||
const waterline = getVisual(record).waterline;
|
||||
if (!waterline) continue;
|
||||
if (distanceSquared(eye, waterline) > limitSq) continue;
|
||||
into.set(record.id, modelItem(record, set));
|
||||
}
|
||||
}
|
||||
|
||||
/** Give a vessel's chevron back when its model no longer draws it. */
|
||||
function handBackVisual(record) {
|
||||
const visual = getVisual(record);
|
||||
if (!visual.modelOwnsVisual) return;
|
||||
visual.modelOwnsVisual = false;
|
||||
syncRecordIcon(record);
|
||||
}
|
||||
|
||||
function updateModels() {
|
||||
if (!fleetModels) return;
|
||||
if (!fleetModels.active()) {
|
||||
if (modelItems.size) {
|
||||
modelItems.clear();
|
||||
fleetModels.frame(modelItems, performance.now());
|
||||
for (const record of state.records.all) handBackVisual(record);
|
||||
}
|
||||
return;
|
||||
}
|
||||
const set = fleetModelSet();
|
||||
const now = performance.now();
|
||||
const next = spareItems;
|
||||
next.clear();
|
||||
if (now - modelCandidatesAtMs >= MODEL_CANDIDATES_MS) {
|
||||
modelCandidatesAtMs = now;
|
||||
gatherModelItems(set, next);
|
||||
} else {
|
||||
for (const [id, item] of modelItems)
|
||||
if (state.records.byId.get(id) === item.record)
|
||||
next.set(id, modelItem(item.record, set));
|
||||
}
|
||||
for (const [id, item] of modelItems)
|
||||
if (next.get(id) !== item) handBackVisual(item.record);
|
||||
spareItems = modelItems;
|
||||
modelItems = next;
|
||||
fleetModels.frame(modelItems, now);
|
||||
for (const item of modelItems.values()) {
|
||||
const visual = getVisual(item.record);
|
||||
if (item.modelOwnsVisual) {
|
||||
if (!visual.modelOwnsVisual) {
|
||||
visual.modelOwnsVisual = true;
|
||||
syncRecordIcon(item.record);
|
||||
}
|
||||
} else handBackVisual(item.record);
|
||||
}
|
||||
if (fleetModels.settling) governorRequestRender('ais-vessels-models');
|
||||
}
|
||||
|
||||
function destroyModels() {
|
||||
fleetModels?.destroy();
|
||||
fleetModels = null;
|
||||
modelItems = new Map();
|
||||
spareItems = new Map();
|
||||
modelCandidatesAtMs = -Infinity;
|
||||
}
|
||||
|
||||
// Vessels move only when a poll lands, so the layer does not hold the
|
||||
// continuous render loop. Its passes run in preRender, which idle mode fires
|
||||
// only for rendered frames: a forced pass (new data, selection) requests its
|
||||
@@ -316,6 +453,7 @@ export function createRendering({
|
||||
findFrame(viewer)?.on('preRender', () => {
|
||||
if (followsClock(vesselState)) followClockPositions();
|
||||
updateVisibility();
|
||||
if (state.feed.enabled) updateModels();
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
@@ -670,6 +808,13 @@ export function createRendering({
|
||||
|
||||
function setVisible(show) {
|
||||
if (state.icons) state.icons.show = show;
|
||||
fleetModels?.setVisible(show);
|
||||
if (!show && fleetModels) {
|
||||
fleetModels.clear();
|
||||
for (const item of modelItems.values())
|
||||
getVisual(item.record).modelOwnsVisual = false;
|
||||
modelItems.clear();
|
||||
}
|
||||
vesselState._vesselOverlayHost.setVisible(VESSEL_OVERLAY_SOURCE_ID, show);
|
||||
}
|
||||
return {
|
||||
@@ -699,5 +844,7 @@ export function createRendering({
|
||||
labelPriority,
|
||||
hasUsefulName,
|
||||
setVisible,
|
||||
updateModels,
|
||||
destroyModels,
|
||||
};
|
||||
}
|
||||
@@ -165,6 +165,7 @@ export function createSelection({
|
||||
// click, not up to VISIBILITY_UPDATE_MS later.
|
||||
components.rendering.updateVisibility(true);
|
||||
components.cards.updateSelectedVesselHud(record);
|
||||
components.photos.requestVesselPhoto(record);
|
||||
if (registerSelectedContext(record)) {
|
||||
selectEntityContext(record);
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user