merge: reconcile voice satellite candidate with current main

This commit is contained in:
Bilawal Sidhu committed 2026-09-15 10:53:37 -05:00
commit 3385e6b713
251 files changed
+48213 -4281

No files matched your search

+414 -67
View File
@@ -8,90 +8,415 @@
*/
const HELI = new Set([
'EC20', 'EC25', 'EC30', 'EC35', 'EC45', 'EC55', 'AS50', 'AS55', 'AS65', 'AS32',
'A109', 'A119', 'A139', 'A169', 'A189', 'B06', 'B06T', 'B407', 'B412', 'B427',
'B429', 'B430', 'B505', 'S76', 'S92', 'S61', 'S64', 'H60', 'H500', 'MD52',
'MD60', 'R22', 'R44', 'R66', 'EXEC', 'EXPL', 'GAZL', 'LYNX', 'NH90', 'PUMA',
'SCAV', 'UH1', 'B105', 'B212', 'B214', 'B222', 'AC', 'H47', 'H64',
'EC20',
'EC25',
'EC30',
'EC35',
'EC45',
'EC55',
'AS50',
'AS55',
'AS65',
'AS32',
'A109',
'A119',
'A139',
'A169',
'A189',
'B06',
'B06T',
'B407',
'B412',
'B427',
'B429',
'B430',
'B505',
'S76',
'S92',
'S61',
'S64',
'H60',
'H500',
'MD52',
'MD60',
'R22',
'R44',
'R66',
'EXEC',
'EXPL',
'GAZL',
'LYNX',
'NH90',
'PUMA',
'SCAV',
'UH1',
'B105',
'B212',
'B214',
'B222',
'AC',
'H47',
'H64',
]);
const QUAD = new Set([
'B741', 'B742', 'B743', 'B744', 'B748', 'B74S', 'B74R', 'B74D', 'A388', 'A342',
'A343', 'A345', 'A346', 'A124', 'C5M', 'A225', 'IL96', 'B52', 'A140',
'B741',
'B742',
'B743',
'B744',
'B748',
'B74S',
'B74R',
'B74D',
'A388',
'A342',
'A343',
'A345',
'A346',
'A124',
'C5M',
'A225',
'IL96',
'B52',
'A140',
]);
const WIDE = new Set([
'A306', 'A30B', 'A310', 'A332', 'A333', 'A338', 'A339', 'A359', 'A35K', 'B762',
'B763', 'B764', 'B772', 'B77L', 'B773', 'B77W', 'B778', 'B779', 'B788', 'B789',
'B78X', 'MD11', 'IL86', 'DC10', 'L101', 'A337', 'B767', 'B777', 'B787',
'C17', 'K35R', // military heavies that read as widebodies
'A306',
'A30B',
'A310',
'A332',
'A333',
'A338',
'A339',
'A359',
'A35K',
'B762',
'B763',
'B764',
'B772',
'B77L',
'B773',
'B77W',
'B778',
'B779',
'B788',
'B789',
'B78X',
'MD11',
'IL86',
'DC10',
'L101',
'A337',
'B767',
'B777',
'B787',
'C17',
'K35R', // military heavies that read as widebodies
]);
const TPROP = new Set([
'DH8A', 'DH8B', 'DH8C', 'DH8D', 'AT43', 'AT44', 'AT45', 'AT46', 'AT72', 'AT73',
'AT75', 'AT76', 'SF34', 'SB20', 'SW3', 'SW4', 'E110', 'E120', 'C208', 'C212',
'C408', 'PC12', 'B190', 'BE20', 'B350', 'B300', 'JS31', 'JS32', 'JS41', 'D228',
'D328', 'F50', 'F27', 'ATP', 'TBM7', 'TBM8', 'TBM9', 'TBM0', 'PC6', 'C441',
'C425', 'DHC6', 'DHC7', 'C130', 'AN12', 'AN26', 'AN32', 'SH36', 'CVLT', 'SAAB',
'DH8A',
'DH8B',
'DH8C',
'DH8D',
'AT43',
'AT44',
'AT45',
'AT46',
'AT72',
'AT73',
'AT75',
'AT76',
'SF34',
'SB20',
'SW3',
'SW4',
'E110',
'E120',
'C208',
'C212',
'C408',
'PC12',
'B190',
'BE20',
'B350',
'B300',
'JS31',
'JS32',
'JS41',
'D228',
'D328',
'F50',
'F27',
'ATP',
'TBM7',
'TBM8',
'TBM9',
'TBM0',
'PC6',
'C441',
'C425',
'DHC6',
'DHC7',
'C130',
'AN12',
'AN26',
'AN32',
'SH36',
'CVLT',
'SAAB',
'A400',
]);
const GLIDER = new Set([
'DISC', 'DUOD', 'VENT', 'NIMB', 'NIM3', 'NIM4', 'JANS', 'ARCE', 'DG40', 'DG80',
'DG1T', 'DG30', 'DG50', 'LS3', 'LS4', 'LS6', 'LS7', 'LS8', 'STD3', 'G103',
'G102', 'G104', 'PW5', 'PW6', 'L13', 'L23', 'L33', 'PIK', 'PEGA', 'KEST',
'TWIN', 'AS33', 'ASW', 'ASG', 'ASK', 'VENS', 'GLID', 'MOSQ', 'DIMO',
'DISC',
'DUOD',
'VENT',
'NIMB',
'NIM3',
'NIM4',
'JANS',
'ARCE',
'DG40',
'DG80',
'DG1T',
'DG30',
'DG50',
'LS3',
'LS4',
'LS6',
'LS7',
'LS8',
'STD3',
'G103',
'G102',
'G104',
'PW5',
'PW6',
'L13',
'L23',
'L33',
'PIK',
'PEGA',
'KEST',
'TWIN',
'AS33',
'ASW',
'ASG',
'ASK',
'VENS',
'GLID',
'MOSQ',
'DIMO',
]);
const LIGHT = new Set([
'C150', 'C152', 'C162', 'C172', 'C72R', 'C175', 'C177', 'C180', 'C182', 'C185',
'C188', 'C206', 'C207', 'C210', 'C310', 'C337', 'SR20', 'SR22', 'S22T', 'PA18',
'PA24', 'PA28', 'P28A', 'P28B', 'P28R', 'PA32', 'P32R', 'PA34', 'PA38', 'PA44',
'PA46', 'DA20', 'DA40', 'DA42', 'DA62', 'BE33', 'BE35', 'BE36', 'BE58', 'BE76',
'BE19', 'BE23', 'BE24', 'M20P', 'M20T', 'AA1', 'AA5', 'GLAS', 'COL4', 'RV4',
'RV6', 'RV7', 'RV8', 'RV9', 'RV10', 'RV14', 'GA8', 'G115', 'BL8', 'CH7',
'C150',
'C152',
'C162',
'C172',
'C72R',
'C175',
'C177',
'C180',
'C182',
'C185',
'C188',
'C206',
'C207',
'C210',
'C310',
'C337',
'SR20',
'SR22',
'S22T',
'PA18',
'PA24',
'PA28',
'P28A',
'P28B',
'P28R',
'PA32',
'P32R',
'PA34',
'PA38',
'PA44',
'PA46',
'DA20',
'DA40',
'DA42',
'DA62',
'BE33',
'BE35',
'BE36',
'BE58',
'BE76',
'BE19',
'BE23',
'BE24',
'M20P',
'M20T',
'AA1',
'AA5',
'GLAS',
'COL4',
'RV4',
'RV6',
'RV7',
'RV8',
'RV9',
'RV10',
'RV14',
'GA8',
'G115',
'BL8',
'CH7',
]);
// GEV addition (2026-08-15 Hangar fleet): business jets — distinct class so the
// Citation II GLB + a slimmer glyph read apart from airliners.
const BIZJET = new Set([
'C500', 'C501', 'C510', 'C525', 'C25A', 'C25B', 'C25C', 'C25M', 'C550',
'C551', 'C560', 'C56X', 'C650', 'C680', 'C68A', 'C700', 'C750',
'CL30', 'CL35', 'CL60', 'GLF2', 'GLF3', 'GLF4', 'GLF5', 'GLF6', 'GA5C',
'GA6C', 'G150', 'G280', 'GL5T', 'GL7T', 'GLEX',
'LJ23', 'LJ24', 'LJ25', 'LJ31', 'LJ35', 'LJ40', 'LJ45', 'LJ55', 'LJ60',
'LJ70', 'LJ75', 'FA10', 'FA20', 'FA50', 'FA7X', 'FA8X', 'F900', 'F2TH',
'H25A', 'H25B', 'H25C', 'HDJT', 'E50P', 'E55P', 'E545', 'E550', 'PC24',
'PRM1', 'BE40', 'ASTR', 'WW24',
'C500',
'C501',
'C510',
'C525',
'C25A',
'C25B',
'C25C',
'C25M',
'C550',
'C551',
'C560',
'C56X',
'C650',
'C680',
'C68A',
'C700',
'C750',
'CL30',
'CL35',
'CL60',
'GLF2',
'GLF3',
'GLF4',
'GLF5',
'GLF6',
'GA5C',
'GA6C',
'G150',
'G280',
'GL5T',
'GL7T',
'GLEX',
'LJ23',
'LJ24',
'LJ25',
'LJ31',
'LJ35',
'LJ40',
'LJ45',
'LJ55',
'LJ60',
'LJ70',
'LJ75',
'FA10',
'FA20',
'FA50',
'FA7X',
'FA8X',
'F900',
'F2TH',
'H25A',
'H25B',
'H25C',
'HDJT',
'E50P',
'E55P',
'E545',
'E550',
'PC24',
'PRM1',
'BE40',
'ASTR',
'WW24',
'SF50', // Cirrus Vision Jet — a JET (was mis-set in LIGHT before the bizjet class existed)
]);
// GEV addition (2026-08-15 Hangar fleet): large UAVs — ICAO designators seen on
// ADS-B/adsb.lol for Predator/Reaper/Global Hawk-class airframes.
const UAV = new Set([
'Q1', 'Q4', 'Q9', 'MQ1', 'MQ4', 'MQ9', 'RQ4', 'TB2', 'SHDW', 'HERN',
'Q1',
'Q4',
'Q9',
'MQ1',
'MQ4',
'MQ9',
'RQ4',
'TB2',
'SHDW',
'HERN',
]);
// GEV addition: fast jets, for the military layer's adsb.lol `t` codes.
const FASTJET = new Set([
'F16', 'F15', 'F18', 'FA18', 'F14', 'F22', 'F35', 'F4', 'F5', 'A10', 'AV8B',
'TYPH', 'EUFI', 'RFAL', 'RAFL', 'GRIP', 'JAS39', 'TOR', 'MIR2', 'M2000',
'SU27', 'SU30', 'SU33', 'SU34', 'SU35', 'SU57', 'MG29', 'MIG29', 'MG31', 'J20',
'T38', 'HAWK', 'L39', 'M346', 'T7A',
'F16',
'F15',
'F18',
'FA18',
'F14',
'F22',
'F35',
'F4',
'F5',
'A10',
'AV8B',
'TYPH',
'EUFI',
'RFAL',
'RAFL',
'GRIP',
'JAS39',
'TOR',
'MIR2',
'M2000',
'SU27',
'SU30',
'SU33',
'SU34',
'SU35',
'SU57',
'MG29',
'MIG29',
'MG31',
'J20',
'T38',
'HAWK',
'L39',
'M346',
'T7A',
]);
/** OpenSky extended-states integer category → class. */
const OPENSKY_CATEGORY = {
2: 'light', // Light (< 15 500 lbs)
3: 'airliner', // Small
4: 'airliner', // Large
5: 'airliner', // High-vortex large (B757)
6: 'widebody', // Heavy
7: 'fastjet', // High performance (>5g, >400 kt)
2: 'light', // Light (< 15 500 lbs)
3: 'airliner', // Small
4: 'airliner', // Large
5: 'airliner', // High-vortex large (B757)
6: 'widebody', // Heavy
7: 'fastjet', // High performance (>5g, >400 kt)
8: 'helicopter', // Rotorcraft
9: 'glider',
};
/** ADS-B emitter-category string → class. */
const EMITTER_CATEGORY = {
A1: 'light', A2: 'light', A3: 'airliner', A4: 'airliner',
A5: 'widebody', A6: 'fastjet', A7: 'helicopter', B1: 'glider',
A1: 'light',
A2: 'light',
A3: 'airliner',
A4: 'airliner',
A5: 'widebody',
A6: 'fastjet',
A7: 'helicopter',
B1: 'glider',
};
export function classifyAircraft({ typeCode, category } = {}) {
const code = String(typeCode || '').trim().toUpperCase();
const code = String(typeCode || '')
.trim()
.toUpperCase();
if (code) {
if (FASTJET.has(code)) return 'fastjet';
if (UAV.has(code)) return 'uav';
@@ -104,37 +429,59 @@ export function classifyAircraft({ typeCode, category } = {}) {
if (LIGHT.has(code)) return 'light';
return 'airliner'; // known type code, not in a special set → default jet
}
if (Number.isFinite(category) && OPENSKY_CATEGORY[category]) return OPENSKY_CATEGORY[category];
const cat = String(category || '').trim().toUpperCase();
if (Number.isFinite(category) && OPENSKY_CATEGORY[category])
return OPENSKY_CATEGORY[category];
const cat = String(category || '')
.trim()
.toUpperCase();
if (EMITTER_CATEGORY[cat]) return EMITTER_CATEGORY[cat];
return 'airliner';
}
/** Billboard scale multipliers (skylight GLYPH_SCALE, + fastjet). */
export const CLASS_SCALE_2D = {
light: 0.62, glider: 0.58, turboprop: 0.86, airliner: 1.0,
widebody: 1.3, quadjet: 1.45, helicopter: 0.82, fastjet: 0.8,
bizjet: 0.72, uav: 0.75,
light: 0.62,
glider: 0.58,
turboprop: 0.86,
airliner: 1.0,
widebody: 1.3,
quadjet: 1.45,
helicopter: 0.82,
fastjet: 0.8,
bizjet: 0.72,
uav: 0.75,
};
/** 3D model scale multipliers — clamped [0.75, 1.45] while every class shares
* the single airplane.glb (a jet mesh at C172 scale reads wrong). Widen when
* real per-class models land in CLASS_MODEL_URL. */
export const CLASS_SCALE_3D = {
light: 0.75, glider: 0.75, turboprop: 0.85, airliner: 1.0,
widebody: 1.3, quadjet: 1.45, helicopter: 0.8, fastjet: 0.8,
bizjet: 0.8, uav: 0.8,
light: 0.75,
glider: 0.75,
turboprop: 0.85,
airliner: 1.0,
widebody: 1.3,
quadjet: 1.45,
helicopter: 0.8,
fastjet: 0.8,
bizjet: 0.8,
uav: 0.8,
};
/** Per-class glTF — all the shared airplane today; drop real assets in here.
* NOTE for future models: each asset may need its own heading offset (the
* shared GLB uses MODEL_HEADING_OFFSET_DEG = 180 in both layers). */
export const CLASS_MODEL_URL = {
light: '/models/airplane.glb', glider: '/models/airplane.glb',
turboprop: '/models/airplane.glb', airliner: '/models/airplane.glb',
widebody: '/models/airplane.glb', quadjet: '/models/airplane.glb',
helicopter: '/models/airplane.glb', fastjet: '/models/airplane.glb',
bizjet: '/models/airplane.glb', uav: '/models/airplane.glb',
light: '/models/airplane.glb',
glider: '/models/airplane.glb',
turboprop: '/models/airplane.glb',
airliner: '/models/airplane.glb',
widebody: '/models/airplane.glb',
quadjet: '/models/airplane.glb',
helicopter: '/models/airplane.glb',
fastjet: '/models/airplane.glb',
bizjet: '/models/airplane.glb',
uav: '/models/airplane.glb',
};
/** Real per-class GLBs (2026-08-15 Hangar fleet, owner picks; CC-BY 4.0 —
@@ -148,10 +495,10 @@ export const CLASS_MODEL_URL = {
* pinned by modelScale.test.mjs. Classes NOT listed (airliner, quadjet,
* glider, fastjet) still render the shared airplane.glb via CLASS_MODEL_URL. */
export const CLASS_MODEL_REAL = {
helicopter: { url: '/models/bell206.glb', bellyM: 1.66, radiusM: 8.24 },
light: { url: '/models/c172.glb', bellyM: 1.36, radiusM: 7.0 },
bizjet: { url: '/models/citation2.glb', bellyM: 2.86, radiusM: 11.24 },
uav: { url: '/models/mq9.glb', bellyM: 2.02, radiusM: 12.0 },
widebody: { url: '/models/b789.glb', bellyM: 7.81, radiusM: 44.08 },
turboprop: { url: '/models/atr72.glb', bellyM: 3.81, radiusM: 19.49 },
helicopter: { url: '/models/bell206.glb', bellyM: 1.66, radiusM: 8.24 },
light: { url: '/models/c172.glb', bellyM: 1.36, radiusM: 7.0 },
bizjet: { url: '/models/citation2.glb', bellyM: 2.86, radiusM: 11.24 },
uav: { url: '/models/mq9.glb', bellyM: 2.02, radiusM: 12.0 },
widebody: { url: '/models/b789.glb', bellyM: 7.81, radiusM: 44.08 },
turboprop: { url: '/models/atr72.glb', bellyM: 3.81, radiusM: 19.49 },
};
+7 -3
View File
@@ -35,9 +35,11 @@ const VIEW = 96;
const C = VIEW / 2; // 48 — glyph centre
// Hairline dark edge (scaled for the 96 box: ~1.5u ≈ the old 0.5u at 32).
const STROKE = 'stroke="rgba(0,0,0,0.32)" stroke-width="1.4" stroke-linejoin="round"';
const STROKE =
'stroke="rgba(0,0,0,0.32)" stroke-width="1.4" stroke-linejoin="round"';
// Heavier edge for the chart-symbol ("bold") glyphs adopted 2026-08-15.
const STROKE_BOLD = 'stroke="rgba(0,0,0,0.38)" stroke-width="2" stroke-linejoin="round"';
const STROKE_BOLD =
'stroke="rgba(0,0,0,0.38)" stroke-width="2" stroke-linejoin="round"';
// Softer white for translucent detail (prop discs, rotor disc) — still white so
// the tint multiplies cleanly; only the alpha differs.
const DISC = 'fill="white" fill-opacity="0.5"';
@@ -239,7 +241,9 @@ const BODIES = {
const _iconCache = new Map();
const _b64 = (s) =>
typeof btoa === 'function' ? btoa(s) : Buffer.from(s, 'utf8').toString('base64');
typeof btoa === 'function'
? btoa(s)
: Buffer.from(s, 'utf8').toString('base64');
/** Fleet raster: billboards render at ~40–58 DEVICE px (width 20–24 CSS ×
* Retina × class scale). Cesium's billboard atlas has no mipmaps, so a big
+3 -1
View File
@@ -11,5 +11,7 @@ export function aircraftIncludedInNearby({
modelRendering = false,
includeHidden = false,
} = {}) {
return Boolean(includeHidden || isTracked || billboardShown || modelRendering);
return Boolean(
includeHidden || isTracked || billboardShown || modelRendering,
);
}
+50 -19
View File
@@ -10,7 +10,7 @@ export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.20,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
@@ -36,10 +36,19 @@ function resolvedParams(overrides) {
return { ..._params, ...overrides };
}
function aircraftRecessionFactorsResolved(cameraDistanceM, cameraHeightM, tuning, result) {
if (!Number.isFinite(cameraDistanceM) || cameraDistanceM < 0
|| !Number.isFinite(cameraHeightM) || cameraHeightM <= 0
|| cameraHeightM >= tuning.globeViewBlendEndM) {
function aircraftRecessionFactorsResolved(
cameraDistanceM,
cameraHeightM,
tuning,
result,
) {
if (
!Number.isFinite(cameraDistanceM) ||
cameraDistanceM < 0 ||
!Number.isFinite(cameraHeightM) ||
cameraHeightM <= 0 ||
cameraHeightM >= tuning.globeViewBlendEndM
) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
@@ -60,11 +69,13 @@ function aircraftRecessionFactorsResolved(cameraDistanceM, cameraHeightM, tuning
return result;
}
const rawT = (limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
const rawT =
(limbRatio - tuning.startLimbRatio) / (1 - tuning.startLimbRatio);
const t = clamp(rawT, 0, 1);
const limbEase = t * t * (3 - 2 * t); // smoothstep: zero slope at both band edges
const globeRawT = (cameraHeightM - tuning.globeViewBlendStartM)
/ (tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
const globeRawT =
(cameraHeightM - tuning.globeViewBlendStartM) /
(tuning.globeViewBlendEndM - tuning.globeViewBlendStartM);
const globeT = clamp(globeRawT, 0, 1);
const globeEase = globeT * globeT * (3 - 2 * globeT);
const strength = 1 - globeEase;
@@ -84,8 +95,10 @@ export function setAircraftRecessionParams(patch = {}) {
if (Number.isFinite(patch.startLimbRatio)) {
next.startLimbRatio = clamp(patch.startLimbRatio, 0, 0.99);
}
if (Number.isFinite(patch.scaleFloor)) next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
if (Number.isFinite(patch.alphaFloor)) next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
if (Number.isFinite(patch.scaleFloor))
next.scaleFloor = clamp(patch.scaleFloor, 0.05, 1);
if (Number.isFinite(patch.alphaFloor))
next.alphaFloor = clamp(patch.alphaFloor, 0.05, 1);
if (Number.isFinite(patch.combinedAlphaFloor)) {
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
}
@@ -109,8 +122,10 @@ export function setAircraftRecessionParams(patch = {}) {
if (next.globeViewBlendStartM >= next.globeViewBlendEndM) {
next.globeViewBlendStartM = Math.max(1, next.globeViewBlendEndM - 1);
}
if (Number.isFinite(patch.earthRadiusM)) next.earthRadiusM = Math.max(1, patch.earthRadiusM);
if (Number.isFinite(patch.writeEpsilon)) next.writeEpsilon = Math.max(0, patch.writeEpsilon);
if (Number.isFinite(patch.earthRadiusM))
next.earthRadiusM = Math.max(1, patch.earthRadiusM);
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
@@ -149,7 +164,10 @@ export function cameraLimbDistanceM(
* @param {Partial<typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS>} [params]
* @returns {{scale:number,alpha:number,limbRatio:number|null}}
*/
export function aircraftRecessionFactors({ cameraDistanceM, cameraHeightM }, params) {
export function aircraftRecessionFactors(
{ cameraDistanceM, cameraHeightM },
params,
) {
const tuning = resolvedParams(params);
return aircraftRecessionFactorsResolved(
cameraDistanceM,
@@ -202,12 +220,17 @@ export function applyAircraftBillboardTreatment({
const alpha = baseAlpha * composedTreatment;
let scaleWrites = 0;
let alphaWrites = 0;
if (!Number.isFinite(billboard.scale) || Math.abs(billboard.scale - scale) > tuning.writeEpsilon) {
if (
!Number.isFinite(billboard.scale) ||
Math.abs(billboard.scale - scale) > tuning.writeEpsilon
) {
billboard.scale = scale;
scaleWrites = 1;
}
if (!Number.isFinite(billboard.color?.alpha)
|| Math.abs(billboard.color.alpha - alpha) > tuning.writeEpsilon) {
if (
!Number.isFinite(billboard.color?.alpha) ||
Math.abs(billboard.color.alpha - alpha) > tuning.writeEpsilon
) {
billboard.color = baseColor.withAlpha(alpha);
alphaWrites = 1;
}
@@ -228,11 +251,19 @@ export function applyAircraftBillboardTreatment({
* @param {Partial<typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS>} [input.params]
* @returns {number} One when a color write occurred, otherwise zero.
*/
export function applyAircraftModelTreatment({ model, baseColor, alpha, params }) {
export function applyAircraftModelTreatment({
model,
baseColor,
alpha,
params,
}) {
const tuning = resolvedParams(params);
if (!model || !baseColor || !Number.isFinite(alpha)) return 0;
if (Number.isFinite(model.color?.alpha)
&& Math.abs(model.color.alpha - alpha) <= tuning.writeEpsilon) return 0;
if (
Number.isFinite(model.color?.alpha) &&
Math.abs(model.color.alpha - alpha) <= tuning.writeEpsilon
)
return 0;
model.color = baseColor.withAlpha(alpha);
return 1;
}
+74 -32
View File
@@ -46,8 +46,9 @@ export function haversineKm(lat1, lon1, lat2, lon2) {
const d2r = Math.PI / 180;
const dLat = (lat2 - lat1) * d2r;
const dLon = (lon2 - lon1) * d2r;
const a = Math.sin(dLat / 2) ** 2
+ Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r) * Math.sin(dLon / 2) ** 2;
const a =
Math.sin(dLat / 2) ** 2 +
Math.cos(lat1 * d2r) * Math.cos(lat2 * d2r) * Math.sin(dLon / 2) ** 2;
return 2 * EARTH_R_KM * Math.asin(Math.min(1, Math.sqrt(a)));
}
@@ -59,17 +60,25 @@ export function applyFilter(records, filter) {
const got = r[field];
if (got === null || got === undefined) return false;
switch (op) {
case 'gt': return Number(got) > Number(value);
case 'gte': return Number(got) >= Number(value);
case 'lt': return Number(got) < Number(value);
case 'lte': return Number(got) <= Number(value);
case 'gt':
return Number(got) > Number(value);
case 'gte':
return Number(got) >= Number(value);
case 'lt':
return Number(got) < Number(value);
case 'lte':
return Number(got) <= Number(value);
case 'eq': {
if (typeof got === 'boolean' || typeof value === 'boolean') return Boolean(got) === Boolean(value);
if (typeof got === 'boolean' || typeof value === 'boolean')
return Boolean(got) === Boolean(value);
return String(got).toLowerCase() === String(value).toLowerCase();
}
case 'neq': return String(got).toLowerCase() !== String(value).toLowerCase();
case 'contains': return String(got).toLowerCase().includes(String(value).toLowerCase());
default: return true;
case 'neq':
return String(got).toLowerCase() !== String(value).toLowerCase();
case 'contains':
return String(got).toLowerCase().includes(String(value).toLowerCase());
default:
return true;
}
});
}
@@ -78,15 +87,23 @@ export function applyFilter(records, filter) {
export function applyScope(records, scope, resolved) {
if (!scope || scope.kind === 'anywhere') return records;
if (scope.kind === 'region' && resolved?.ring) {
return records.filter((r) => Number.isFinite(r.lat) && Number.isFinite(r.lon)
&& pointInRing(resolved.ring, r.lat, r.lon));
return records.filter(
(r) =>
Number.isFinite(r.lat) &&
Number.isFinite(r.lon) &&
pointInRing(resolved.ring, r.lat, r.lon),
);
}
if (scope.kind === 'radius' || scope.kind === 'view') {
const c = resolved?.center;
const km = resolved?.km;
if (!c || !Number.isFinite(km)) return records;
return records.filter((r) => Number.isFinite(r.lat) && Number.isFinite(r.lon)
&& haversineKm(c.lat, c.lon, r.lat, r.lon) <= km);
return records.filter(
(r) =>
Number.isFinite(r.lat) &&
Number.isFinite(r.lon) &&
haversineKm(c.lat, c.lon, r.lat, r.lon) <= km,
);
}
return records;
}
@@ -112,9 +129,12 @@ export function createAnalystEngine(providers) {
let lastResult = null;
async function query(spec = {}) {
const layers = (spec.followUp && lastResult)
const layers =
spec.followUp && lastResult
? null // follow-up: re-filter the remembered set, no re-snapshot
: (Array.isArray(spec.layers) && spec.layers.length ? spec.layers : ['flights']);
: Array.isArray(spec.layers) && spec.layers.length
? spec.layers
: ['flights'];
// 1) Source records
let records;
@@ -173,20 +193,23 @@ export function createAnalystEngine(providers) {
// camera made the two disagree — a parked, high-altitude camera answered
// "46 within 250 km" while the panel showed a far larger contact-centred
// count. Same question, two numbers.
const explicitCenter = scope.center && Number.isFinite(scope.center.lat)
? scope.center
: null;
const subject = explicitCenter ? null : providers.getContextSubject?.() || null;
const explicitCenter =
scope.center && Number.isFinite(scope.center.lat) ? scope.center : null;
const subject = explicitCenter
? null
: providers.getContextSubject?.() || null;
const view = providers.getViewContext();
// Only a subject that actually SUPPLIED the centre may name it. A
// subject present but without usable coordinates silently fell back to
// the camera while the label still read "within 250 km of <contact>" —
// a count centred on one place, reported as centred on another, with
// nothing in the payload to show which.
const subjectCenter = Number.isFinite(subject?.lat) && Number.isFinite(subject?.lon)
const subjectCenter =
Number.isFinite(subject?.lat) && Number.isFinite(subject?.lon)
? { lat: subject.lat, lon: subject.lon }
: null;
const center = explicitCenter || subjectCenter || { lat: view.lat, lon: view.lon };
const center = explicitCenter ||
subjectCenter || { lat: view.lat, lon: view.lon };
resolvedScope = { center, km: Number(scope.km) || 100 };
if (subjectCenter) resolvedScope.centeredOn = subject.label || null;
scopeNote = resolvedScope.centeredOn
@@ -197,7 +220,10 @@ export function createAnalystEngine(providers) {
: `within ${resolvedScope.km} km`;
} else if (scope.kind === 'view') {
const view = providers.getViewContext();
resolvedScope = { center: { lat: view.lat, lon: view.lon }, km: view.viewRadiusKm };
resolvedScope = {
center: { lat: view.lat, lon: view.lon },
km: view.viewRadiusKm,
};
scopeNote = `view:${Math.round(view.viewRadiusKm)}km`;
scopeLabel = 'in view';
} else {
@@ -214,15 +240,22 @@ export function createAnalystEngine(providers) {
if (sortBy === 'distance') {
const ref = resolvedScope?.center || providers.getViewContext();
for (const it of items) {
it.distanceKm = (Number.isFinite(it.lat) && Number.isFinite(it.lon))
? Math.round(haversineKm(ref.lat, ref.lon, it.lat, it.lon) * 10) / 10 : null;
it.distanceKm =
Number.isFinite(it.lat) && Number.isFinite(it.lon)
? Math.round(haversineKm(ref.lat, ref.lon, it.lat, it.lon) * 10) /
10
: null;
}
}
if (sortBy) {
const dir = spec.sortDir === 'asc' ? 1 : -1;
items.sort((a, b) => (Number(a[sortBy]) - Number(b[sortBy])) * dir
|| String(a.id).localeCompare(String(b.id)));
if (sortBy === 'distance') items.sort((a, b) => (a.distanceKm ?? 1e9) - (b.distanceKm ?? 1e9));
items.sort(
(a, b) =>
(Number(a[sortBy]) - Number(b[sortBy])) * dir ||
String(a.id).localeCompare(String(b.id)),
);
if (sortBy === 'distance')
items.sort((a, b) => (a.distanceKm ?? 1e9) - (b.distanceKm ?? 1e9));
}
const limit = Math.max(1, Math.min(50, Number(spec.limit) || 10));
const top = items.slice(0, limit);
@@ -232,7 +265,10 @@ export function createAnalystEngine(providers) {
count: items.length,
items: top,
truncated: items.length > top.length,
summary: summarize(items, sortBy && sortBy !== 'distance' ? sortBy : null),
summary: summarize(
items,
sortBy && sortBy !== 'distance' ? sortBy : null,
),
scopeLabel,
coverage: {
layersQueried,
@@ -245,7 +281,9 @@ export function createAnalystEngine(providers) {
},
// Surfaced so the narration can name the centre it measured from rather
// than implying a view-centred answer.
...(resolvedScope?.centeredOn ? { centeredOn: resolvedScope.centeredOn } : {}),
...(resolvedScope?.centeredOn
? { centeredOn: resolvedScope.centeredOn }
: {}),
};
lastResult = { items, coverage: result.coverage };
return result;
@@ -253,7 +291,11 @@ export function createAnalystEngine(providers) {
return {
query,
reset() { lastResult = null; },
hasMemory() { return Boolean(lastResult); },
reset() {
lastResult = null;
},
hasMemory() {
return Boolean(lastResult);
},
};
}
File diff suppressed because it is too large. Load diff
+345
View File
@@ -0,0 +1,345 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import {
createBhoteKoshiEmbeddedMedia,
createTrimmedYouTubePlayback,
embeddedMediaFrameUrl,
publicEmbeddedMediaUrl,
resolveEmbeddedMediaSource,
} from './bhoteKoshiEmbeddedMedia.js';
function trimmedPlaybackFixture() {
let now = 0;
let nextId = 0;
const timers = new Map();
const globalRef = {
setTimeout(fn, delay) { const id = ++nextId; timers.set(id, { at: now + delay, fn }); return id; },
clearTimeout(id) { timers.delete(id); },
};
const advance = (ms) => {
const until = now + ms;
while (true) {
const entry = [...timers].filter(([, item]) => item.at <= until).sort((a, b) => a[1].at - b[1].at)[0];
if (!entry) break;
const [id, item] = entry; timers.delete(id); now = item.at; item.fn();
}
now = until;
};
let events;
const calls = [];
let time = 0;
let state = -1;
const player = {
mute: () => calls.push('mute'), playVideo: () => calls.push('play'),
pauseVideo: () => calls.push('pause'), destroy: () => calls.push('destroy'),
getCurrentTime: () => time,
getPlayerState: () => state,
};
const api = { Player: class { constructor(_iframe, options) { events = options.events; return player; } } };
const statuses = [];
const session = createTrimmedYouTubePlayback({ iframe: {}, endAtSec: 7, globalRef,
loadApi: () => api, onStatus: (phase) => statuses.push(phase) });
return { session, advance, calls, timers, statuses, player, get events() { return events; }, setTime(value) { time = value; }, setState(value) { state = value; } };
}
test('trimmed YouTube reconciles already-playing READY and missed PLAYING callbacks', async () => {
for (const alreadyPlaying of [true, false]) {
const f = trimmedPlaybackFixture();
await Promise.resolve(); await Promise.resolve();
if (alreadyPlaying) { f.setState(1); f.setTime(1); }
f.events.onReady({ target: f.player });
if (!alreadyPlaying) { f.setState(1); f.setTime(1); f.advance(100); }
f.setTime(6); f.advance(5000);
assert.deepEqual(f.session.getState(), { phase: 'playing', currentTime: 6 });
f.setTime(7); f.advance(100);
assert.deepEqual(f.session.getState(), { phase: 'completed', currentTime: 7 });
assert.deepEqual(f.statuses, ['completed']);
assert.equal(f.timers.size, 0);
f.session.destroy();
}
});
test('trimmed YouTube accepts ENDED before PLAYING and never replays a completed READY', async () => {
for (const endedCallback of [true, false]) {
const f = trimmedPlaybackFixture();
await Promise.resolve(); await Promise.resolve();
f.setState(0); f.setTime(7);
if (endedCallback) f.events.onStateChange({ data: 0, target: f.player });
f.events.onReady({ target: f.player });
assert.deepEqual(f.session.getState(), { phase: 'completed', currentTime: 7 });
assert.deepEqual(f.calls, ['pause']);
assert.deepEqual(f.statuses, ['completed']);
assert.equal(f.timers.size, 0);
f.session.destroy();
}
});
test('trimmed YouTube waits through delayed startup, stops at source 0:07, and releases its timers', async () => {
const f = trimmedPlaybackFixture();
await Promise.resolve(); await Promise.resolve();
f.advance(3000);
assert.equal(f.session.getState().phase, 'starting');
f.events.onReady({ target: f.player });
f.events.onStateChange({ data: 1 });
f.setTime(4); f.advance(4000);
assert.equal(f.session.getState().phase, 'playing', 'seven wall-clock seconds do not truncate a delayed clip');
f.setTime(7); f.advance(100);
assert.deepEqual(f.session.getState(), { phase: 'completed', currentTime: 7 });
assert.deepEqual(f.statuses, ['completed']);
assert.equal(f.timers.size, 0);
assert.equal(f.calls.at(-1), 'pause');
f.session.destroy();
});
test('trimmed YouTube bounds blocked, failed, stalled and never-started playback', async () => {
for (const outcome of ['blocked', 'unavailable', 'timeout', 'stalled']) {
const f = trimmedPlaybackFixture();
await Promise.resolve(); await Promise.resolve();
if (outcome === 'blocked') f.events.onAutoplayBlocked();
else if (outcome === 'unavailable') f.events.onError();
else if (outcome === 'stalled') { f.events.onStateChange({ data: 1 }); f.advance(12000); }
else f.advance(5000);
assert.equal(f.session.getState().phase, outcome === 'stalled' ? 'timeout' : outcome);
assert.equal(f.timers.size, 0);
const calls = [...f.calls];
f.events.onReady({ target: f.player });
f.events.onStateChange({ data: 1 });
assert.deepEqual(f.calls, calls, 'late provider callbacks cannot restart a terminal attempt');
f.session.destroy();
}
});
test('trimmed YouTube teardown revokes pending SDK and player callbacks', async () => {
const f = trimmedPlaybackFixture();
await Promise.resolve(); await Promise.resolve();
f.session.destroy();
f.events.onReady({ target: f.player });
f.events.onStateChange({ data: 1 });
f.events.onError(); f.advance(20000);
assert.deepEqual(f.calls, ['destroy']);
assert.deepEqual(f.statuses, []);
assert.equal(f.timers.size, 0);
let constructCount = 0;
let resolveApi;
const session = createTrimmedYouTubePlayback({ iframe: {}, endAtSec: 7,
loadApi: () => new Promise((resolve) => { resolveApi = resolve; }) });
await Promise.resolve();
session.destroy();
resolveApi({ Player: class { constructor() { constructCount++; } } });
await Promise.resolve(); await Promise.resolve();
assert.equal(constructCount, 0);
});
test('pausing YouTube removes its frame and rejects a late load from the stopped generation', () => {
const nodes = [];
class Element extends EventTarget {
constructor(tag) { super(); this.tag = tag; this.children = []; this.dataset = {}; this.classList = { add() {}, remove() {} }; nodes.push(this); }
setAttribute() {}
append(...children) { for (const child of children) { child.parent = this; this.children.push(child); } }
remove() { if (this.parent) this.parent.children = this.parent.children.filter((child) => child !== this); this.parent = null; }
}
const documentRef = {
body: new Element('body'),
createElement: (tag) => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {} });
const options = { observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor: {}, autoplay: true };
assert.equal(media.show(options), true);
const frame = nodes.find((node) => node.tag === 'iframe');
const card = nodes.find((node) => node.tag === 'section');
assert.ok(card.parent);
assert.equal(media.pause(), true);
assert.equal(card.parent, null);
frame.dispatchEvent(new Event('load'));
assert.equal(card.parent, null);
assert.equal(media.show(options), true, 'an explicit replay creates a fresh player');
media.destroy();
assert.equal(documentRef.body.children.length, 0);
});
test('resolves supported embedded callout providers from canonical public URLs', () => {
assert.deepEqual(
resolveEmbeddedMediaSource('https://www.youtube.com/watch?v=DbqRexFxv3k'),
{
provider: 'youtube',
id: 'DbqRexFxv3k',
url: 'https://www.youtube.com/watch?v=DbqRexFxv3k',
},
);
assert.equal(
resolveEmbeddedMediaSource('https://www.facebook.com/reel/1571491657757829').provider,
'facebook',
);
assert.deepEqual(
resolveEmbeddedMediaSource('https://x.com/Indowatchosint/status/2092640554568007958'),
{
provider: 'x',
id: '2092640554568007958',
url: 'https://x.com/Indowatchosint/status/2092640554568007958',
},
);
assert.equal(
resolveEmbeddedMediaSource('https://twitter.com/Indowatchosint/status/2092640554568007958').provider,
'x',
);
assert.equal(
resolveEmbeddedMediaSource('https://www.youtube.com/shorts/DbqRexFxv3k').id,
'DbqRexFxv3k',
);
});
test('rejects deceptive hosts, non-post X links, private targets, and iframe markup', () => {
for (const value of [
'https://x.com.evil.example/user/status/2092640554568007958',
'https://x.com/Indowatchosint',
'https://youtube.com.evil.example/watch?v=DbqRexFxv3k',
'http://www.youtube.com/watch?v=DbqRexFxv3k',
'https://localhost/video.mp4',
'<iframe src="https://x.com/user/status/2092640554568007958"></iframe>',
]) {
assert.equal(resolveEmbeddedMediaSource(value), null, value);
}
assert.equal(publicEmbeddedMediaUrl('https://user:[email protected]/name/status/123'), null);
});
test('builds privacy-aware provider frames and keeps X on its widget runtime', () => {
const youtube = resolveEmbeddedMediaSource('https://youtu.be/DbqRexFxv3k');
const youtubeFrame = new URL(embeddedMediaFrameUrl(youtube, { autoplay: true }));
assert.equal(youtubeFrame.hostname, 'www.youtube-nocookie.com');
assert.equal(youtubeFrame.pathname, '/embed/DbqRexFxv3k');
assert.equal(youtubeFrame.searchParams.get('autoplay'), '1');
assert.equal(youtubeFrame.searchParams.get('mute'), '1');
const timestampedFrame = new URL(embeddedMediaFrameUrl(youtube, {
autoplay: true,
startAtSec: 26,
}));
assert.equal(timestampedFrame.searchParams.get('start'), '26');
const facebook = resolveEmbeddedMediaSource('https://www.facebook.com/watch/?v=456');
const facebookFrame = new URL(embeddedMediaFrameUrl(facebook, { autoplay: false }));
assert.equal(facebookFrame.hostname, 'www.facebook.com');
assert.equal(facebookFrame.pathname, '/plugins/video.php');
assert.equal(facebookFrame.searchParams.get('href'), facebook.url);
assert.equal(facebookFrame.searchParams.get('autoplay'), 'false');
const x = resolveEmbeddedMediaSource('https://x.com/Indowatchosint/status/2092640554568007958');
assert.equal(embeddedMediaFrameUrl(x), null);
});
test('Mailung playback stops at source timestamp 0:07 without changing other clips', async () => {
const event = JSON.parse(await readFile(new URL('../../public/events/bhote-koshi-2026/event.json', import.meta.url), 'utf8'));
const bounded = event.evidenceSpine.filter(point => point.media?.embedEndAtSec != null);
assert.deepEqual(bounded.map(point => point.id), ['mailung-bazzar']);
const media = bounded[0].media;
assert.equal(media.embedEndAtSec, 7);
const source = resolveEmbeddedMediaSource(media.sourceUrl);
for (const autoplay of [false, true]) {
const url = new URL(embeddedMediaFrameUrl(source, {
autoplay, startAtSec: media.clipInSec, endAtSec: media.embedEndAtSec,
}));
assert.equal(url.searchParams.get('end'), '7');
}
for (const endAtSec of [undefined, null, NaN, Infinity, -1, 0, 3]) {
const url = new URL(embeddedMediaFrameUrl(source, {startAtSec: 3, endAtSec}));
assert.equal(url.searchParams.has('end'), false);
}
});
function preloadFixture(options = {}) {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
append(...children) {
for (const child of children) { child.remove(); child.parent = this; this.children.push(child); }
}
remove() {
if (this.parent) this.parent.children = this.parent.children.filter(child => child !== this);
this.parent = null;
}
}
const documentRef = {
body: new Element('body'),
createElement: tag => new Element(tag),
createElementNS: (_, tag) => new Element(tag),
};
const media = createBhoteKoshiEmbeddedMedia({ viewer: {}, documentRef, globalRef: {}, ...options });
return { media, root: documentRef.body.children[0] };
}
for (const operation of ['pause', 'hide', 'destroy']) {
test(`${operation} removes a hidden YouTube preload`, () => {
const { media, root } = preloadFixture();
media.warm({ sourceUrl: 'https://youtu.be/DbqRexFxv3k' });
assert.equal(root.children.length, 1);
media[operation]();
assert.equal(root.children.length, 0);
media.destroy();
});
}
test('camera updates retain a preload until the visible player loads', () => {
const { media, root } = preloadFixture();
const observation = { media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } };
media.warm({ observation });
const frame = root.children[0];
media.hide({ preserveWarm: true });
media.warm({ observation });
assert.equal(root.children[0], frame);
assert.equal(media.show({ observation, anchor: {} }), true);
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
const card = root.children.find(node => node.tag === 'section');
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
const player = body.children.find(node => node.className === 'bhote-embedded-callout-player');
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
media.destroy();
assert.equal(root.children.length, 0);
});
test('hiding revokes a pending Facebook SDK before it can mount or subscribe', async () => {
let resolveApi;
const calls = [];
const { media, root } = preloadFixture({
facebookLoader: () => new Promise(resolve => { resolveApi = resolve; }),
});
media.warm({ sourceUrl: 'https://www.facebook.com/reel/1571491657757829' });
assert.equal(root.children.length, 1);
media.hide();
assert.equal(root.children.length, 0);
resolveApi({ Event: { subscribe() { calls.push('subscribe'); } }, XFBML: { parse() { calls.push('parse'); } } });
await Promise.resolve(); await Promise.resolve();
assert.deepEqual(calls, []);
media.destroy();
});
test('pausing cancels a mounted Facebook preload and rejects its late ready callback', async () => {
let ready;
let unsubscribed = 0;
const timers = new Set();
const playerCalls = [];
const { media, root } = preloadFixture({
globalRef: { setTimeout(fn) { timers.add(fn); return fn; }, clearTimeout(fn) { timers.delete(fn); } },
facebookLoader: async () => ({
Event: { subscribe(_name, callback) { ready = callback; }, unsubscribe() { unsubscribed++; } },
XFBML: { parse() {} },
}),
});
media.warm({ sourceUrl: 'https://www.facebook.com/reel/1571491657757829' });
await Promise.resolve(); await Promise.resolve();
assert.equal(timers.size, 1);
media.pause();
assert.equal(root.children.length, 0);
assert.equal(timers.size, 0);
assert.equal(unsubscribed, 1);
ready({ type: 'video', instance: { play() { playerCalls.push('play'); }, pause() { playerCalls.push('pause'); } } });
assert.deepEqual(playerCalls, []);
media.destroy();
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+499
View File
@@ -0,0 +1,499 @@
/**
* Simplified GeoPera river centerline from the point nearest the owner-provided
* Debris-Dammed Lake observation through Trishuli Bazaar. Every fourth published
* vertex is retained, plus the exact endpoint nearest the verified bazaar pin.
*
* Source: https://github.com/geo-pera/bhotekoshi-2026-reconstruction/blob/main/vectors/river_centerline.geojson
* License: CC BY-NC 4.0 (derived data; Planet Labs PBC / Vantor open data)
*/
export const BHOTE_KOSHI_FLOOD_PATH = Object.freeze([
Object.freeze([85.48476, 28.33255]),
Object.freeze([85.48353, 28.33308]),
Object.freeze([85.48231, 28.33279]),
Object.freeze([85.48108, 28.33278]),
Object.freeze([85.47985, 28.33304]),
Object.freeze([85.47863, 28.33275]),
Object.freeze([85.47741, 28.33301]),
Object.freeze([85.47618, 28.33299]),
Object.freeze([85.47496, 28.33325]),
Object.freeze([85.47373, 28.33351]),
Object.freeze([85.4725, 28.33377]),
Object.freeze([85.47128, 28.33375]),
Object.freeze([85.47005, 28.33401]),
Object.freeze([85.46881, 28.33481]),
Object.freeze([85.46759, 28.33506]),
Object.freeze([85.46636, 28.33532]),
Object.freeze([85.46513, 28.33585]),
Object.freeze([85.4639, 28.33584]),
Object.freeze([85.46267, 28.33609]),
Object.freeze([85.46145, 28.33635]),
Object.freeze([85.46022, 28.33661]),
Object.freeze([85.45899, 28.33659]),
Object.freeze([85.45777, 28.33685]),
Object.freeze([85.45655, 28.33629]),
Object.freeze([85.45533, 28.33628]),
Object.freeze([85.45411, 28.336]),
Object.freeze([85.45289, 28.33544]),
Object.freeze([85.45167, 28.33543]),
Object.freeze([85.45045, 28.33514]),
Object.freeze([85.44922, 28.33513]),
Object.freeze([85.448, 28.33511]),
Object.freeze([85.44677, 28.33537]),
Object.freeze([85.44554, 28.33563]),
Object.freeze([85.44432, 28.33534]),
Object.freeze([85.4431, 28.33533]),
Object.freeze([85.44188, 28.33504]),
Object.freeze([85.44065, 28.3353]),
Object.freeze([85.43943, 28.33529]),
Object.freeze([85.43821, 28.335]),
Object.freeze([85.43699, 28.33472]),
Object.freeze([85.43577, 28.33416]),
Object.freeze([85.43456, 28.33334]),
Object.freeze([85.43335, 28.33251]),
Object.freeze([85.43214, 28.33141]),
Object.freeze([85.43093, 28.33059]),
Object.freeze([85.42971, 28.33057]),
Object.freeze([85.42848, 28.33056]),
Object.freeze([85.42726, 28.33027]),
Object.freeze([85.42604, 28.33026]),
Object.freeze([85.42482, 28.33025]),
Object.freeze([85.4236, 28.32996]),
Object.freeze([85.42238, 28.32968]),
Object.freeze([85.42116, 28.32939]),
Object.freeze([85.41995, 28.32829]),
Object.freeze([85.41873, 28.32774]),
Object.freeze([85.41752, 28.32718]),
Object.freeze([85.41629, 28.32744]),
Object.freeze([85.41508, 28.32634]),
Object.freeze([85.41387, 28.32524]),
Object.freeze([85.41297, 28.32415]),
Object.freeze([85.41268, 28.32306]),
Object.freeze([85.41239, 28.32198]),
Object.freeze([85.41241, 28.3209]),
Object.freeze([85.41273, 28.31982]),
Object.freeze([85.41275, 28.31873]),
Object.freeze([85.41276, 28.31765]),
Object.freeze([85.41308, 28.31657]),
Object.freeze([85.41249, 28.31548]),
Object.freeze([85.4122, 28.3144]),
Object.freeze([85.41252, 28.31332]),
Object.freeze([85.41254, 28.31223]),
Object.freeze([85.41194, 28.31114]),
Object.freeze([85.41196, 28.31006]),
Object.freeze([85.41167, 28.30897]),
Object.freeze([85.41077, 28.30788]),
Object.freeze([85.40955, 28.30705]),
Object.freeze([85.40865, 28.30596]),
Object.freeze([85.40744, 28.30513]),
Object.freeze([85.40623, 28.30404]),
Object.freeze([85.40503, 28.30294]),
Object.freeze([85.40381, 28.30238]),
Object.freeze([85.4026, 28.30156]),
Object.freeze([85.40139, 28.30046]),
Object.freeze([85.40019, 28.29936]),
Object.freeze([85.39898, 28.29827]),
Object.freeze([85.39777, 28.29717]),
Object.freeze([85.39748, 28.29608]),
Object.freeze([85.39658, 28.29499]),
Object.freeze([85.39629, 28.2939]),
Object.freeze([85.3957, 28.29281]),
Object.freeze([85.39449, 28.29172]),
Object.freeze([85.39328, 28.29062]),
Object.freeze([85.39238, 28.28953]),
Object.freeze([85.39117, 28.28897]),
Object.freeze([85.38996, 28.28787]),
Object.freeze([85.38875, 28.28678]),
Object.freeze([85.38754, 28.28622]),
Object.freeze([85.38632, 28.28593]),
Object.freeze([85.38511, 28.28511]),
Object.freeze([85.3839, 28.28401]),
Object.freeze([85.383, 28.28292]),
Object.freeze([85.38179, 28.28182]),
Object.freeze([85.38089, 28.28073]),
Object.freeze([85.37968, 28.28017]),
Object.freeze([85.37846, 28.27934]),
Object.freeze([85.37725, 28.27852]),
Object.freeze([85.37666, 28.27743]),
Object.freeze([85.37668, 28.27634]),
Object.freeze([85.37669, 28.27526]),
Object.freeze([85.37701, 28.27418]),
Object.freeze([85.37642, 28.27309]),
Object.freeze([85.37644, 28.27201]),
Object.freeze([85.37615, 28.27092]),
Object.freeze([85.37616, 28.26984]),
Object.freeze([85.37648, 28.26876]),
Object.freeze([85.37558, 28.26767]),
Object.freeze([85.37499, 28.26658]),
Object.freeze([85.37378, 28.26548]),
Object.freeze([85.37288, 28.26439]),
Object.freeze([85.37198, 28.26329]),
Object.freeze([85.37169, 28.26221]),
Object.freeze([85.37048, 28.26111]),
Object.freeze([85.36928, 28.26001]),
Object.freeze([85.36806, 28.25973]),
Object.freeze([85.36685, 28.25863]),
Object.freeze([85.36656, 28.25754]),
Object.freeze([85.36566, 28.25645]),
Object.freeze([85.36507, 28.25536]),
Object.freeze([85.36478, 28.25427]),
Object.freeze([85.36449, 28.25318]),
Object.freeze([85.36512, 28.25211]),
Object.freeze([85.36452, 28.25102]),
Object.freeze([85.36423, 28.24993]),
Object.freeze([85.36425, 28.24885]),
Object.freeze([85.36335, 28.24776]),
Object.freeze([85.36245, 28.24666]),
Object.freeze([85.36124, 28.24556]),
Object.freeze([85.36004, 28.24447]),
Object.freeze([85.35882, 28.24391]),
Object.freeze([85.35823, 28.24282]),
Object.freeze([85.35733, 28.24173]),
Object.freeze([85.35734, 28.24064]),
Object.freeze([85.35797, 28.23957]),
Object.freeze([85.35799, 28.23849]),
Object.freeze([85.3577, 28.2374]),
Object.freeze([85.35802, 28.23632]),
Object.freeze([85.35834, 28.23524]),
Object.freeze([85.35928, 28.23417]),
Object.freeze([85.3596, 28.23309]),
Object.freeze([85.36023, 28.23202]),
Object.freeze([85.36024, 28.23093]),
Object.freeze([85.36057, 28.22985]),
Object.freeze([85.36058, 28.22877]),
Object.freeze([85.3609, 28.22769]),
Object.freeze([85.36092, 28.22661]),
Object.freeze([85.36094, 28.22553]),
Object.freeze([85.36126, 28.22445]),
Object.freeze([85.36067, 28.22336]),
Object.freeze([85.36007, 28.22227]),
Object.freeze([85.35886, 28.22117]),
Object.freeze([85.35796, 28.22008]),
Object.freeze([85.35706, 28.21898]),
Object.freeze([85.35616, 28.21789]),
Object.freeze([85.35526, 28.21679]),
Object.freeze([85.35467, 28.2157]),
Object.freeze([85.35469, 28.21462]),
Object.freeze([85.3547, 28.21354]),
Object.freeze([85.35472, 28.21246]),
Object.freeze([85.35443, 28.21137]),
Object.freeze([85.35414, 28.21028]),
Object.freeze([85.35416, 28.2092]),
Object.freeze([85.35448, 28.20812]),
Object.freeze([85.3548, 28.20704]),
Object.freeze([85.35482, 28.20596]),
Object.freeze([85.35392, 28.20486]),
Object.freeze([85.35332, 28.20377]),
Object.freeze([85.35303, 28.20269]),
Object.freeze([85.35275, 28.2016]),
Object.freeze([85.35246, 28.20052]),
Object.freeze([85.35247, 28.19943]),
Object.freeze([85.35188, 28.19834]),
Object.freeze([85.35128, 28.19725]),
Object.freeze([85.35038, 28.19616]),
Object.freeze([85.3501, 28.19507]),
Object.freeze([85.3495, 28.19398]),
Object.freeze([85.34891, 28.19289]),
Object.freeze([85.34862, 28.1918]),
Object.freeze([85.34802, 28.19071]),
Object.freeze([85.34743, 28.18962]),
Object.freeze([85.34622, 28.18853]),
Object.freeze([85.34593, 28.18744]),
Object.freeze([85.34565, 28.18635]),
Object.freeze([85.34475, 28.18526]),
Object.freeze([85.34385, 28.18417]),
Object.freeze([85.34325, 28.18308]),
Object.freeze([85.34266, 28.18199]),
Object.freeze([85.34237, 28.1809]),
Object.freeze([85.34239, 28.17982]),
Object.freeze([85.34271, 28.17874]),
Object.freeze([85.34272, 28.17765]),
Object.freeze([85.34274, 28.17657]),
Object.freeze([85.34215, 28.17548]),
Object.freeze([85.34216, 28.1744]),
Object.freeze([85.34249, 28.17332]),
Object.freeze([85.34189, 28.17223]),
Object.freeze([85.34191, 28.17115]),
Object.freeze([85.34192, 28.17006]),
Object.freeze([85.34255, 28.16899]),
Object.freeze([85.34226, 28.1679]),
Object.freeze([85.34289, 28.16683]),
Object.freeze([85.3423, 28.16574]),
Object.freeze([85.3417, 28.16465]),
Object.freeze([85.34048, 28.16436]),
Object.freeze([85.33928, 28.16353]),
Object.freeze([85.33807, 28.16271]),
Object.freeze([85.33747, 28.16162]),
Object.freeze([85.33718, 28.16053]),
Object.freeze([85.33628, 28.15971]),
Object.freeze([85.33507, 28.15888]),
Object.freeze([85.33385, 28.15859]),
Object.freeze([85.33295, 28.15777]),
Object.freeze([85.33174, 28.15694]),
Object.freeze([85.33053, 28.15639]),
Object.freeze([85.32932, 28.15529]),
Object.freeze([85.32842, 28.1542]),
Object.freeze([85.32721, 28.15337]),
Object.freeze([85.32631, 28.15228]),
Object.freeze([85.3251, 28.15145]),
Object.freeze([85.32389, 28.15089]),
Object.freeze([85.32267, 28.15061]),
Object.freeze([85.32147, 28.14978]),
Object.freeze([85.32026, 28.14895]),
Object.freeze([85.31904, 28.1484]),
Object.freeze([85.31783, 28.14784]),
Object.freeze([85.31663, 28.14674]),
Object.freeze([85.31541, 28.14619]),
Object.freeze([85.3142, 28.14536]),
Object.freeze([85.313, 28.14426]),
Object.freeze([85.3124, 28.14317]),
Object.freeze([85.31181, 28.14208]),
Object.freeze([85.31058, 28.14261]),
Object.freeze([85.30936, 28.14232]),
Object.freeze([85.30816, 28.14122]),
Object.freeze([85.30695, 28.14012]),
Object.freeze([85.30575, 28.13903]),
Object.freeze([85.30485, 28.13793]),
Object.freeze([85.30456, 28.13685]),
Object.freeze([85.30366, 28.13575]),
Object.freeze([85.30307, 28.13466]),
Object.freeze([85.30248, 28.13357]),
Object.freeze([85.30127, 28.13274]),
Object.freeze([85.30067, 28.13165]),
Object.freeze([85.30039, 28.13057]),
Object.freeze([85.3001, 28.12948]),
Object.freeze([85.29889, 28.12838]),
Object.freeze([85.29799, 28.12729]),
Object.freeze([85.29709, 28.12647]),
Object.freeze([85.29588, 28.12591]),
Object.freeze([85.29467, 28.12508]),
Object.freeze([85.29347, 28.12398]),
Object.freeze([85.29226, 28.12316]),
Object.freeze([85.29105, 28.12206]),
Object.freeze([85.28985, 28.12096]),
Object.freeze([85.28864, 28.11986]),
Object.freeze([85.28775, 28.11877]),
Object.freeze([85.28653, 28.11821]),
Object.freeze([85.28532, 28.11765]),
Object.freeze([85.28411, 28.11683]),
Object.freeze([85.2829, 28.116]),
Object.freeze([85.28231, 28.11491]),
Object.freeze([85.28172, 28.11382]),
Object.freeze([85.28082, 28.11272]),
Object.freeze([85.27961, 28.11217]),
Object.freeze([85.2787, 28.11134]),
Object.freeze([85.27749, 28.11079]),
Object.freeze([85.27629, 28.10969]),
Object.freeze([85.27508, 28.10859]),
Object.freeze([85.27388, 28.10749]),
Object.freeze([85.27267, 28.10667]),
Object.freeze([85.27177, 28.10584]),
Object.freeze([85.27056, 28.10474]),
Object.freeze([85.26936, 28.10392]),
Object.freeze([85.26815, 28.10309]),
Object.freeze([85.26695, 28.10199]),
Object.freeze([85.26574, 28.10089]),
Object.freeze([85.26454, 28.09979]),
Object.freeze([85.26364, 28.0987]),
Object.freeze([85.26274, 28.09761]),
Object.freeze([85.26153, 28.09678]),
Object.freeze([85.26033, 28.09568]),
Object.freeze([85.25911, 28.09539]),
Object.freeze([85.2579, 28.09511]),
Object.freeze([85.25668, 28.09509]),
Object.freeze([85.25546, 28.09481]),
Object.freeze([85.25425, 28.09398]),
Object.freeze([85.25304, 28.09342]),
Object.freeze([85.25183, 28.09286]),
Object.freeze([85.25061, 28.09285]),
Object.freeze([85.24939, 28.09256]),
Object.freeze([85.24818, 28.09201]),
Object.freeze([85.24696, 28.09199]),
Object.freeze([85.24573, 28.09252]),
Object.freeze([85.24451, 28.0925]),
Object.freeze([85.24328, 28.09248]),
Object.freeze([85.24207, 28.0922]),
Object.freeze([85.24085, 28.09191]),
Object.freeze([85.23963, 28.0919]),
Object.freeze([85.23841, 28.09161]),
Object.freeze([85.2372, 28.09132]),
Object.freeze([85.23598, 28.09104]),
Object.freeze([85.23476, 28.09102]),
Object.freeze([85.23355, 28.09019]),
Object.freeze([85.23234, 28.08964]),
Object.freeze([85.23113, 28.08881]),
Object.freeze([85.22993, 28.08771]),
Object.freeze([85.22872, 28.08688]),
Object.freeze([85.22782, 28.08579]),
Object.freeze([85.22692, 28.08496]),
Object.freeze([85.22571, 28.08414]),
Object.freeze([85.2245, 28.08358]),
Object.freeze([85.22329, 28.08302]),
Object.freeze([85.22208, 28.08219]),
Object.freeze([85.22087, 28.08164]),
Object.freeze([85.21966, 28.08108]),
Object.freeze([85.21876, 28.08026]),
Object.freeze([85.21755, 28.07943]),
Object.freeze([85.21635, 28.07833]),
Object.freeze([85.21514, 28.07723]),
Object.freeze([85.21394, 28.0764]),
Object.freeze([85.21272, 28.07585]),
Object.freeze([85.21151, 28.07529]),
Object.freeze([85.2103, 28.075]),
Object.freeze([85.2094, 28.07391]),
Object.freeze([85.20881, 28.07282]),
Object.freeze([85.20791, 28.07172]),
Object.freeze([85.20762, 28.07063]),
Object.freeze([85.20672, 28.06954]),
Object.freeze([85.20552, 28.06844]),
Object.freeze([85.20523, 28.06735]),
Object.freeze([85.20495, 28.06627]),
Object.freeze([85.20588, 28.0652]),
Object.freeze([85.2062, 28.06412]),
Object.freeze([85.20683, 28.06304]),
Object.freeze([85.20716, 28.06196]),
Object.freeze([85.20717, 28.06088]),
Object.freeze([85.2078, 28.05981]),
Object.freeze([85.20751, 28.05872]),
Object.freeze([85.20814, 28.05765]),
Object.freeze([85.20847, 28.05657]),
Object.freeze([85.20787, 28.05548]),
Object.freeze([85.20759, 28.05439]),
Object.freeze([85.20699, 28.0533]),
Object.freeze([85.2061, 28.0522]),
Object.freeze([85.20489, 28.05138]),
Object.freeze([85.20369, 28.05028]),
Object.freeze([85.2031, 28.04919]),
Object.freeze([85.2022, 28.04809]),
Object.freeze([85.20191, 28.04701]),
Object.freeze([85.20101, 28.04591]),
Object.freeze([85.19981, 28.04508]),
Object.freeze([85.1986, 28.04398]),
Object.freeze([85.19739, 28.04343]),
Object.freeze([85.1965, 28.04233]),
Object.freeze([85.19529, 28.0415]),
Object.freeze([85.19439, 28.04041]),
Object.freeze([85.1938, 28.03932]),
Object.freeze([85.19382, 28.03824]),
Object.freeze([85.19384, 28.03715]),
Object.freeze([85.19355, 28.03607]),
Object.freeze([85.19357, 28.03498]),
Object.freeze([85.19328, 28.0339]),
Object.freeze([85.1936, 28.03282]),
Object.freeze([85.19362, 28.03174]),
Object.freeze([85.19364, 28.03065]),
Object.freeze([85.19305, 28.02956]),
Object.freeze([85.19215, 28.02847]),
Object.freeze([85.19156, 28.02738]),
Object.freeze([85.19097, 28.02629]),
Object.freeze([85.18976, 28.02573]),
Object.freeze([85.18854, 28.02571]),
Object.freeze([85.18732, 28.02515]),
Object.freeze([85.18611, 28.0246]),
Object.freeze([85.18522, 28.0235]),
Object.freeze([85.18493, 28.02242]),
Object.freeze([85.18556, 28.02134]),
Object.freeze([85.1868, 28.02027]),
Object.freeze([85.18742, 28.0192]),
Object.freeze([85.18714, 28.01811]),
Object.freeze([85.18746, 28.01703]),
Object.freeze([85.18656, 28.01594]),
Object.freeze([85.18536, 28.01484]),
Object.freeze([85.18446, 28.01375]),
Object.freeze([85.18418, 28.01266]),
Object.freeze([85.18389, 28.01157]),
Object.freeze([85.1836, 28.01049]),
Object.freeze([85.18362, 28.0094]),
Object.freeze([85.18364, 28.00832]),
Object.freeze([85.18366, 28.00724]),
Object.freeze([85.18368, 28.00615]),
Object.freeze([85.1843, 28.00508]),
Object.freeze([85.18432, 28.004]),
Object.freeze([85.18404, 28.00291]),
Object.freeze([85.18375, 28.00182]),
Object.freeze([85.18438, 28.00075]),
Object.freeze([85.18501, 27.99967]),
Object.freeze([85.18533, 27.9986]),
Object.freeze([85.18596, 27.99752]),
Object.freeze([85.18567, 27.99643]),
Object.freeze([85.18477, 27.99534]),
Object.freeze([85.18357, 27.99424]),
Object.freeze([85.18237, 27.99314]),
Object.freeze([85.18239, 27.99206]),
Object.freeze([85.18302, 27.99098]),
Object.freeze([85.18273, 27.9899]),
Object.freeze([85.18152, 27.98907]),
Object.freeze([85.18062, 27.98824]),
Object.freeze([85.18034, 27.98716]),
Object.freeze([85.18066, 27.98608]),
Object.freeze([85.18037, 27.98499]),
Object.freeze([85.18039, 27.98391]),
Object.freeze([85.18041, 27.98283]),
Object.freeze([85.18043, 27.98174]),
Object.freeze([85.18075, 27.98067]),
Object.freeze([85.18138, 27.97959]),
Object.freeze([85.1814, 27.97851]),
Object.freeze([85.18172, 27.97743]),
Object.freeze([85.18204, 27.97635]),
Object.freeze([85.18236, 27.97527]),
Object.freeze([85.18299, 27.9742]),
Object.freeze([85.18362, 27.97312]),
Object.freeze([85.18425, 27.97205]),
Object.freeze([85.18396, 27.97096]),
Object.freeze([85.18275, 27.9704]),
Object.freeze([85.18154, 27.97012]),
Object.freeze([85.18033, 27.96956]),
Object.freeze([85.17911, 27.96927]),
Object.freeze([85.17821, 27.96818]),
Object.freeze([85.17762, 27.96709]),
Object.freeze([85.17703, 27.966]),
Object.freeze([85.17613, 27.9649]),
Object.freeze([85.17492, 27.96434]),
Object.freeze([85.17371, 27.96406]),
Object.freeze([85.1725, 27.9635]),
Object.freeze([85.17128, 27.96321]),
Object.freeze([85.17008, 27.96238]),
Object.freeze([85.16888, 27.96129]),
Object.freeze([85.16859, 27.9602]),
Object.freeze([85.168, 27.95911]),
Object.freeze([85.16771, 27.95802]),
Object.freeze([85.16682, 27.95693]),
Object.freeze([85.16561, 27.95637]),
Object.freeze([85.1644, 27.95581]),
Object.freeze([85.16318, 27.95552]),
Object.freeze([85.16198, 27.95442]),
Object.freeze([85.1623, 27.95335]),
Object.freeze([85.16232, 27.95226]),
Object.freeze([85.16234, 27.95118]),
Object.freeze([85.16236, 27.9501]),
Object.freeze([85.16238, 27.94902]),
Object.freeze([85.1627, 27.94794]),
Object.freeze([85.16241, 27.94685]),
Object.freeze([85.16152, 27.94576]),
Object.freeze([85.16093, 27.94466]),
Object.freeze([85.16034, 27.94357]),
Object.freeze([85.15974, 27.94248]),
Object.freeze([85.15915, 27.94139]),
Object.freeze([85.15887, 27.9403]),
Object.freeze([85.15797, 27.93921]),
Object.freeze([85.15738, 27.93812]),
Object.freeze([85.15679, 27.93703]),
Object.freeze([85.1562, 27.93594]),
Object.freeze([85.15561, 27.93485]),
Object.freeze([85.15532, 27.93376]),
Object.freeze([85.15473, 27.93267]),
Object.freeze([85.15352, 27.93184]),
Object.freeze([85.15229, 27.93291]),
Object.freeze([85.15105, 27.9337]),
Object.freeze([85.15015, 27.93288]),
Object.freeze([85.14987, 27.93179]),
Object.freeze([85.14988, 27.93071]),
Object.freeze([85.14929, 27.92962]),
Object.freeze([85.14901, 27.92853]),
Object.freeze([85.14994, 27.92746]),
Object.freeze([85.15057, 27.92639]),
Object.freeze([85.15089, 27.92531]),
Object.freeze([85.15121, 27.92423]),
Object.freeze([85.15123, 27.92315]),
Object.freeze([85.15034, 27.92205]),
Object.freeze([85.14943, 27.92177]),
]);
+117
View File
@@ -0,0 +1,117 @@
// Overview pins follow the event pack through Devighat.
// Charaudi remains a separate evidence shot, and none of these observation
// locations extends the mapped flood path.
export const INCIDENT_OVERVIEW_PLACES = Object.freeze(
[
[
'immediate-collapse-viewpoint',
'COLLAPSE VIEWPOINT',
28.3632333,
85.4423639,
2850,
'left',
],
[
'debris-dammed-lake',
'DAMMED LAKE',
28.3346111,
85.4861389,
2750,
'right',
],
[
'second-landslide',
'SECOND LANDSLIDE',
28.3379706,
85.4688823,
2750,
'left',
],
[
'gyirong-border-gate',
'BORDER GATE',
28.2808338,
85.3780248,
1818,
'right',
],
['timure-cluster', 'TIMURE', 28.2519361, 85.3665833, 1689, 'left'],
[
'syabru-besi',
'SYABRU BESI',
28.1602583333333,
85.3325666666667,
1417,
'right',
],
['dhunche', 'DHUNCHE', 28.1131861111111, 85.2953305555556, 1300, 'left'],
[
'mailung-upper-trishuli',
'UPPER TRISHULI',
28.090925,
85.2322916666667,
950,
'right',
],
[
'mailung-bazzar',
'MAILUNG',
28.0761666666667,
85.2125277777778,
800,
'left',
],
[
'dandagaun',
'DANDAGAUN',
28.0751944444444,
85.2076944444444,
780,
'right-lower',
],
[
'dandagaun-viewpoint',
'DANDAGAUN VIEWPOINT',
28.0354,
85.1894361111111,
700,
'right',
],
[
'betrawati-bazaar',
'BETRAWATI',
27.9758992572246,
85.1835331689033,
600,
'left',
],
[
'bhainse',
'BHAINSE',
27.9623111111111,
85.1739777777778,
500,
'right-lower',
],
[
'bidur-trishuli-bridge',
'BIDUR BRIDGE',
27.920858,
85.148029,
510,
'left',
],
[
'devighat-taadi-khola-bridge',
'DEVIGHAT BRIDGE',
27.8585278,
85.1090318,
350,
'right',
],
].map(([id, title, lat, lon, heightM, placement]) =>
Object.freeze({ id, title, lat, lon, heightM, placement }),
),
);
export const INCIDENT_OVERVIEW_HOLD_SEC = 11;
File diff suppressed because it is too large. Load diff
+671
View File
@@ -0,0 +1,671 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
import { INCIDENT_OVERVIEW_HOLD_SEC, INCIDENT_OVERVIEW_PLACES } from './bhoteKoshiIncidentPlaces.js';
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
import * as Cesium from 'cesium';
import { SceneDirector } from '../scenes/director.js';
import {
anchoredCalloutPresentation,
BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION,
BHOTE_KOSHI_FLOOD_PATH_PRESENTATION,
BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION,
BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION,
BHOTE_KOSHI_REGIONAL_PRESENTATION,
BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION,
closeRegionRing,
createBhoteKoshiLocatorLayer,
largestGeoJsonRing,
NEPAL_CONTEXT_PRESENTATION,
revealPolylinePositions,
} from './bhoteKoshiLocator.js';
function viewerFixture() {
const added = [];
const removed = [];
return {
creditDisplay: { addStaticCredit() {} },
dataSources: {
add(source) { added.push(source); },
remove(source) { removed.push(source); },
},
_test: { added, removed },
};
}
function nonRunningAnimation() {
return {
scheduleFrame() { return 1; },
cancelFrame() {},
};
}
function overlayHostFixture() {
const publications = [];
const clears = [];
return {
setEntries(sourceId, entries, options) {
publications.push({ sourceId, entries, options });
},
clearSource(sourceId) {
clears.push(sourceId);
},
_test: { publications, clears },
};
}
test('Bhote Koshi locator closes valid region rings once', () => {
assert.deepEqual(closeRegionRing([[80, 26], [88, 26], [88, 30]]), [
[80, 26], [88, 26], [88, 30], [80, 26],
]);
assert.deepEqual(closeRegionRing([[80, 26], [88, 26], [80, 26]]), [
[80, 26], [88, 26], [80, 26],
]);
assert.deepEqual(closeRegionRing([[80, 26], ['bad', 27]]), []);
});
test('Bhote Koshi locator selects the largest GeoJSON country exterior', () => {
const main = [[80, 26], [88, 26], [88, 30], [80, 30], [80, 26]];
const island = [[82, 25], [83, 25], [82, 25]];
assert.equal(largestGeoJsonRing({ type: 'Polygon', coordinates: [main] }), main);
assert.equal(largestGeoJsonRing({
type: 'MultiPolygon',
coordinates: [[island], [main]],
}), main);
assert.deepEqual(largestGeoJsonRing({ type: 'Point', coordinates: [84, 28] }), []);
});
test('Bhote Koshi locator reveals a border progressively', () => {
const positions = [
new Cesium.Cartesian3(0, 0, 0),
new Cesium.Cartesian3(10, 0, 0),
new Cesium.Cartesian3(20, 0, 0),
];
assert.deepEqual(revealPolylinePositions(positions, 0), [positions[0], positions[0]]);
assert.deepEqual(revealPolylinePositions(positions, 0.25), [
positions[0],
new Cesium.Cartesian3(5, 0, 0),
]);
assert.equal(revealPolylinePositions(positions, 1), positions);
});
test('Bhote Koshi locator stages its anchored callout from dot to leader to text', () => {
assert.deepEqual(anchoredCalloutPresentation(0), {
alpha: 0,
leaderProgress: 0,
contentAlpha: 0,
scale: 0.96,
});
assert.deepEqual(anchoredCalloutPresentation(1200), {
alpha: 1,
leaderProgress: 1,
contentAlpha: 1,
scale: 1,
});
});
test('Bhote Koshi regional locator sequences Nepal, border, then the incident', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
const renders = [];
let nowMs = 0;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
ring: [[80, 26], [88, 26], [88, 30], [80, 30]],
}),
requestRender: (reason) => renders.push(reason),
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
});
assert.equal(await layer.init(viewer), true);
assert.equal(await layer.enable(viewer, { origin: 'scene' }), true);
assert.equal(viewer._test.added.length, 1);
const source = viewer._test.added[0];
const ids = source.entities.values.map((entity) => entity.id);
for (const id of [
'nepal-context-halo',
'nepal-border-fill',
'nepal-border-highlight',
'bhote-koshi-incident-halo',
]) {
assert.ok(ids.includes(id), `${id} belongs to the regional sequence`);
}
const incidentHalo = source.entities.getById('bhote-koshi-incident-halo');
const border = source.entities.getById('nepal-border-highlight');
const publication = overlayHost._test.publications.at(-1);
assert.equal(publication.sourceId, BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
assert.equal(publication.entries.length, 2);
const nepal = publication.entries.find(({ id }) => id === 'nepal-context-callout');
const incident = publication.entries.find(({ id }) => id === 'bhote-koshi-incident-callout');
assert.equal(nepal.variant, 'label');
assert.equal(nepal.title, 'NEPAL');
assert.equal(nepal.anchorDot, true);
assert.equal(incident.variant, 'card');
assert.equal(incident.paintLane, 'thumbnail');
assert.equal(incident.title, 'BHOTE KOSHI FLOOD INCIDENT');
assert.deepEqual(incident.details, ['NEPAL · 26 AUG 2026']);
assert.equal(incident.anchorDot, true);
assert.equal(incident.leaderStyle, 'elbow');
assert.equal('image' in incident, false);
assert.equal('requireImage' in incident, false);
assert.equal(incident.sourceAlpha(), 0);
assert.equal(incident.leaderProgress(), 0);
assert.equal(incident.contentAlpha(), 0);
assert.equal(incident.presentationScale(), 0.96);
assert.equal(nepal.sourceAlpha(), 0);
assert.ok(border.polyline.positions.getValue().length < 5);
assert.equal(incidentHalo.show.getValue(), false);
assert.equal(incidentHalo.point.pixelSize.getValue(), 16);
nowMs = 3100;
assert.equal(nepal.sourceAlpha(), 1);
assert.equal(border.polyline.positions.getValue().length, 5);
assert.equal(incidentHalo.show.getValue(), false);
nowMs = 3300;
assert.equal(incidentHalo.show.getValue(), true);
assert.equal(incident.sourceAlpha(), 0);
nowMs = 4500;
assert.equal(incident.sourceAlpha(), 1);
assert.equal(incident.leaderProgress(), 1);
assert.equal(incident.contentAlpha(), 1);
assert.equal(incident.presentationScale(), 1);
assert.equal(layer.getStats().status, 'nominal');
assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION });
assert.ok(renders.includes('bhote-koshi-locator-boundary'));
assert.equal(await layer.disable(), true);
assert.equal(viewer._test.removed.length, 1);
assert.equal(overlayHost._test.clears.at(-1), BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
assert.equal(layer.getStats().status, 'idle');
});
test('Bhote Koshi locator switches between Nepal context and the regional incident treatment', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
ring: [[80, 26], [88, 26], [88, 30], [80, 30]],
}),
requestRender() {},
overlayHost,
...nonRunningAnimation(),
});
layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION });
await layer.enable(viewer);
assert.deepEqual(viewer._test.added[0].entities.values.map((entity) => entity.id), [
'nepal-context-halo',
]);
const nepalLabel = overlayHost._test.publications.at(-1).entries[0];
assert.equal(nepalLabel.variant, 'label');
assert.equal(nepalLabel.placement, 'right');
assert.equal(nepalLabel.anchorDot, true);
assert.equal(layer.getStats().coverage, 'Nepal context');
assert.deepEqual(layer.getRowControls().chips.map(({ id, active }) => ({ id, active })), [
{ id: 'nepal-context', active: true },
{ id: 'bhote-koshi-regional', active: false },
{ id: 'bhote-koshi-city-context', active: false },
{ id: 'bhote-koshi-incident-places', active: false },
{ id: 'bhote-koshi-flood-path', active: false },
{ id: 'bhote-koshi-path-overview', active: false },
{ id: 'bhote-koshi-trigger-record', active: false },
]);
layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION });
assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight'));
assert.equal(viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), undefined);
assert.equal(
overlayHost._test.publications.at(-1).entries
.find(({ id }) => id === 'bhote-koshi-incident-callout').variant,
'card',
);
layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION });
assert.deepEqual(viewer._test.added[0].entities.values.map((entity) => entity.id), [
'nepal-context-halo',
]);
await layer.destroy();
});
test('Incident Corridor reveals all fifteen overview pins and keeps layout active through the sequence', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
let pulseFrame = null;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null, requestRender() {},
overlayHost,
now: () => nowMs,
scheduleFrame(callback) { pulseFrame = callback; return 1; },
cancelFrame() {},
});
layer.setParams({ presentation: BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const event = JSON.parse(await readFile(new URL('../../public/events/bhote-koshi-2026/event.json', import.meta.url), 'utf8'));
assert.equal(event.evidenceSpine.length, 16);
assert.equal(event.evidenceSpine.at(-1).id, 'charaudi');
assert.equal(source.entities.values.length, 15);
const labels = overlayHost._test.publications.at(-1).entries;
assert.equal(labels.length, 15);
assert.equal(overlayHost._test.publications.at(-1).options.moving, true);
for (const [index, point] of INCIDENT_OVERVIEW_PLACES.entries()) {
const id = `bhote-koshi-place-${point.id}`;
const pin = labels.find((entry) => entry.id === id);
assert.ok(pin, point.id);
assert.equal(pin.title, `${String(index + 1).padStart(2, '0')} · ${point.title}`);
assert.equal(pin.variant, 'label');
const location = Cesium.Cartographic.fromCartesian(pin.position);
assert.ok(Math.abs(Cesium.Math.toDegrees(location.latitude) - point.lat) < 1e-6);
assert.ok(Math.abs(Cesium.Math.toDegrees(location.longitude) - point.lon) < 1e-6);
nowMs = 349 + index * 650;
assert.equal(pin.sourceAlpha(), 0);
nowMs += 1;
assert.equal(pin.sourceAlpha(), 0);
assert.equal(source.entities.values.filter(entity => entity.id.endsWith('-halo') && entity.show.getValue()).length, 1);
nowMs += 520;
assert.equal(pin.sourceAlpha(), 1);
}
assert.ok(nowMs < INCIDENT_OVERVIEW_HOLD_SEC * 1000);
// A repeat halo cycle must not erase already revealed labels.
nowMs = 350 + 15 * 650;
assert.equal(source.entities.getById('bhote-koshi-place-immediate-collapse-viewpoint-halo').show.getValue(), true);
assert.equal(labels.find(({ id }) => id === 'bhote-koshi-place-devighat-taadi-khola-bridge').sourceAlpha(), 1);
assert.equal(labels.some(({ id }) => id === 'bhote-koshi-place-charaudi'), false);
assert.equal(typeof pulseFrame, 'function');
pulseFrame();
assert.equal(overlayHost._test.publications.at(-1).options.moving, false);
layer.setParams({ presentation: BHOTE_KOSHI_REGIONAL_PRESENTATION });
assert.equal(source.entities.values.some(entity => entity.id.startsWith('bhote-koshi-place-')), false);
await layer.destroy();
});
test('Bhote Koshi flood path draws a solid cyan sourced route after the place shot', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
});
layer.setParams({ presentation: BHOTE_KOSHI_FLOOD_PATH_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const path = source.entities.getById('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
const trigger = labels.find(({ id }) => id === 'bhote-koshi-place-immediate-collapse-viewpoint');
const bidur = labels.find(({ id }) => id === 'bhote-koshi-place-bidur-trishuli-bridge');
assert.equal(source.entities.values.length, 1);
assert.equal(labels.length, 15);
assert.equal(bidur.title, '14 · BIDUR BRIDGE');
for (const place of INCIDENT_OVERVIEW_PLACES) {
const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`);
assert.equal(pin.sourceAlpha(), 1, place.id);
}
assert.equal(path.polyline.clampToGround.getValue(), true);
assert.ok(path.polyline.material instanceof Cesium.ColorMaterialProperty);
assert.ok(path.polyline.material.color.getValue().equalsEpsilon(
Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96),
Cesium.Math.EPSILON7,
));
assert.equal(path.show.getValue(), false);
assert.equal(trigger.sourceAlpha(), 1);
assert.equal(bidur.sourceAlpha(), 1);
nowMs = 250;
assert.equal(path.show.getValue(), true);
assert.equal(path.polyline.positions.getValue().length, 2);
nowMs = 2250;
const halfwayCount = path.polyline.positions.getValue().length;
assert.ok(Math.abs(halfwayCount - BHOTE_KOSHI_FLOOD_PATH.length / 2) <= 2);
nowMs = 4250;
assert.equal(path.polyline.positions.getValue().length, BHOTE_KOSHI_FLOOD_PATH.length);
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH[0], [85.48476, 28.33255]);
// More observation pins must not extend or straighten the sourced route.
assert.deepEqual(path.polyline.positions.getValue(), BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => (
Cesium.Cartesian3.fromDegrees(lon, lat)
)));
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH.at(-1), [85.14943, 27.92177]);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Flood path');
assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_FLOOD_PATH_PRESENTATION });
await layer.destroy();
});
test('Bhote Koshi path-overview presentation keeps the route settled without Nepal border', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
ring: [[80, 26], [88, 26], [88, 30], [80, 30]],
}),
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
});
layer.setParams({ presentation: BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const path = source.entities.getById('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
assert.equal(source.entities.values.length, 1);
assert.equal(labels.length, 15);
for (const [index, place] of INCIDENT_OVERVIEW_PLACES.entries()) {
const pin = labels.find(({ id }) => id === `bhote-koshi-place-${place.id}`);
assert.equal(pin.title, `${String(index + 1).padStart(2, '0')} · ${place.title}`);
assert.equal(pin.sourceAlpha(), 1);
}
assert.equal(path.show.getValue(), true);
assert.equal(path.polyline.positions.getValue().length, BHOTE_KOSHI_FLOOD_PATH.length);
assert.ok(Cesium.Cartesian3.equals(path.polyline.positions.getValue()[0],
Cesium.Cartesian3.fromDegrees(85.48476, 28.33255)));
assert.equal(source.entities.getById('nepal-border-fill'), undefined);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(
source.entities.getById('bhote-koshi-place-immediate-collapse-viewpoint-halo'),
undefined,
);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Path overview');
assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION });
await layer.destroy();
});
test('Bhote Koshi trigger-record presentation reveals sourced incident details', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
});
layer.setParams({
presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION,
preview: true,
});
await layer.enable(viewer);
const source = viewer._test.added[0];
const publication = overlayHost._test.publications.at(-1);
const record = publication.entries[0];
assert.deepEqual(source.entities.values.map(({ id }) => id), [
'bhote-koshi-flood-path',
'bhote-koshi-trigger-record-halo',
]);
assert.equal(record.title, 'USGS INITIAL REPORT');
assert.deepEqual(record.details, [
'26 AUG 2026 · 08:37 NPT',
'28.2710° N · 85.5150° E',
'INITIAL M4.4 · RECLASSIFIED M5.2 LANDSLIDE',
'USGS EVENT us7000tbwb · OPEN SOURCE',
]);
assert.equal(record.interactive, true);
assert.equal(typeof record.activate, 'function');
assert.equal(record.sourceAlpha(), 0);
nowMs = 1200;
assert.equal(record.sourceAlpha(), 1);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Trigger record');
assert.deepEqual(layer.getParams(), {
presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION,
});
await layer.destroy();
});
test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
const moveStart = new Cesium.Event();
const moveEnd = new Cesium.Event();
const flights = [];
let armedCallback = null;
viewer.camera = {
moveStart,
moveEnd,
flyTo(options) { flights.push(options); },
cancelFlight() {},
};
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
scheduleDelay(callback) {
armedCallback = callback;
return 1;
},
cancelDelay() {},
...nonRunningAnimation(),
});
layer.setParams({ presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION });
await layer.enable(viewer);
assert.equal(flights.length, 0);
assert.equal(typeof armedCallback, 'function');
moveStart.raiseEvent();
assert.equal(flights.length, 0);
moveEnd.raiseEvent();
assert.equal(flights.length, 1);
assert.equal(flights[0].duration, 4.6);
const destination = Cesium.Cartographic.fromCartesian(flights[0].destination);
assert.ok(Math.abs(Cesium.Math.toDegrees(destination.latitude) - 28.368) < 1e-6);
assert.ok(Math.abs(Cesium.Math.toDegrees(destination.longitude) - 85.473) < 1e-6);
assert.ok(Math.abs(destination.height - 10526) < 1e-4);
flights[0].complete();
assert.equal(flights.length, 2);
assert.equal(flights[1].duration, 2.8);
const orbit = Cesium.Cartographic.fromCartesian(flights[1].destination);
assert.ok(Math.abs(Cesium.Math.toDegrees(orbit.latitude) - 28.3769) < 1e-6);
assert.ok(Math.abs(Cesium.Math.toDegrees(orbit.longitude) - 85.4923) < 1e-6);
assert.ok(Math.abs(orbit.height - 10526) < 1e-4);
await layer.destroy();
});
for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
test(`Scene Stop revokes locator ${phase} and stale callbacks cannot own a successor`, async () => {
const viewer = viewerFixture();
const timers = new Map();
const callbacks = [];
const flights = [];
let nextTimer = 0;
const moveStart = new Cesium.Event();
const moveEnd = new Cesium.Event();
viewer.camera = {
moveStart, moveEnd,
flyTo(options) { flights.push(options); },
cancelFlight() {},
};
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
overlayHost: overlayHostFixture(),
requestRender() {},
scheduleDelay(callback) {
callbacks.push(callback);
timers.set(++nextTimer, callback);
return nextTimer;
},
cancelDelay(id) { timers.delete(id); },
...nonRunningAnimation(),
});
const director = {
dataManager: { layers: new Map([[layer.id, { module: layer }]]) },
viewer,
_sceneSeekGeneration: 0,
_loadGeneration: 0,
_cancelActiveSceneTravel: SceneDirector.prototype._cancelActiveSceneTravel,
};
try {
layer.setParams({ presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION });
await layer.enable(viewer);
if (phase === 'move-end') moveStart.raiseEvent();
if (phase === 'approach' || phase === 'orbit') callbacks[0]();
if (phase === 'orbit') flights[0].complete();
const oldFlights = [...flights];
SceneDirector.prototype.stopScene.call(director);
assert.equal(timers.size, 0, 'Stop cancels the actual delayed work');
assert.equal(moveStart.numberOfListeners, 0);
assert.equal(moveEnd.numberOfListeners, 0);
callbacks[0]();
moveEnd.raiseEvent();
for (const flight of oldFlights) flight.complete();
assert.equal(flights.length, oldFlights.length, 'no post-Stop approach or orbit');
assert.equal(layer.getStats().count, 1, 'Stop preserves the visible locator');
layer.setParams({ presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION });
callbacks.at(-1)();
const successor = flights.at(-1);
const count = flights.length;
callbacks[0]();
for (const flight of oldFlights) { flight.cancel(); flight.complete(); }
assert.equal(flights.length, count, 'old callbacks cannot add a flight');
successor.complete();
assert.equal(flights.length, count + 1, 'successor retains its own orbit');
} finally { await layer.destroy(); }
});
}
test('Bhote Koshi locator keeps the regional context settled while nearby cities stagger in', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
ring: [[80, 26], [88, 26], [88, 30], [80, 30]],
}),
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
});
layer.setParams({ presentation: BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const borderFill = source.entities.getById('nepal-border-fill');
const entries = overlayHost._test.publications.at(-1).entries;
const incident = entries.find(({ id }) => id === 'bhote-koshi-incident-callout');
const kathmandu = entries.find(({ id }) => id === 'bhote-koshi-city-kathmandu');
const bhaktapur = entries.find(({ id }) => id === 'bhote-koshi-city-bhaktapur');
const dhulikhel = entries.find(({ id }) => id === 'bhote-koshi-city-dhulikhel');
assert.equal(borderFill.show.getValue(), true);
assert.equal(incident.contentAlpha(), 1);
assert.equal(kathmandu.title, 'KATHMANDU');
assert.equal(bhaktapur.title, 'BHAKTAPUR');
assert.equal(dhulikhel.title, 'DHULIKHEL');
assert.ok([kathmandu, bhaktapur, dhulikhel].every(({ variant, anchorDot }) => (
variant === 'label' && anchorDot === true
)));
assert.equal(kathmandu.sourceAlpha(), 0);
assert.equal(bhaktapur.sourceAlpha(), 0);
assert.equal(dhulikhel.sourceAlpha(), 0);
nowMs = 350;
assert.equal(kathmandu.sourceAlpha(), 0);
assert.equal(bhaktapur.sourceAlpha(), 0);
nowMs = 850;
assert.equal(kathmandu.sourceAlpha(), 1);
assert.ok(bhaktapur.sourceAlpha() > 0);
assert.ok(dhulikhel.sourceAlpha() > 0);
nowMs = 1300;
assert.equal(dhulikhel.sourceAlpha(), 1);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Nearby cities');
assert.deepEqual(layer.getParams(), { presentation: BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION });
await layer.destroy();
});
test('Bhote Koshi locator degrades to labels when the regional boundary is unavailable', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
const originalWarn = console.warn;
console.warn = () => {};
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
...nonRunningAnimation(),
});
try {
await layer.enable(viewer);
const ids = viewer._test.added[0].entities.values.map((entity) => entity.id);
assert.ok(ids.includes('nepal-context-halo'));
assert.ok(ids.includes('bhote-koshi-incident-halo'));
assert.equal(ids.includes('bhote-koshi-city-kathmandu'), false);
assert.equal(ids.includes('nepal-border-highlight'), false);
assert.deepEqual(overlayHost._test.publications.at(-1).entries.map(({ id }) => id), [
'nepal-context-callout',
'bhote-koshi-incident-callout',
]);
assert.equal(layer.getStats().status, 'degraded');
} finally {
console.warn = originalWarn;
await layer.destroy();
}
});
test('Bhote Koshi regional locator waits for its boundary before starting the full sequence', async () => {
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let releaseBoundary;
const boundary = new Promise((resolve) => { releaseBoundary = resolve; });
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => boundary,
requestRender() {},
overlayHost,
...nonRunningAnimation(),
});
const enabling = layer.enable(viewer);
assert.ok(viewer._test.added[0].entities.getById('nepal-context-halo'));
assert.equal(viewer._test.added[0].entities.getById('nepal-border-highlight'), undefined);
assert.equal(viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'), undefined);
assert.equal(overlayHost._test.publications.length, 1);
assert.deepEqual(overlayHost._test.publications[0].entries.map(({ id }) => id), [
'nepal-context-callout',
]);
releaseBoundary({ ring: [[80, 26], [88, 26], [88, 30], [80, 30]] });
await enabling;
assert.ok(viewer._test.added[0].entities.getById('bhote-koshi-incident-halo'));
assert.ok(viewer._test.added[0].entities.getById('nepal-border-highlight'));
assert.equal(viewer._test.added[0].entities.getById('bhote-koshi-city-kathmandu'), undefined);
assert.equal(overlayHost._test.publications.length, 2);
assert.deepEqual(overlayHost._test.publications.at(-1).entries.map(({ id }) => id), [
'nepal-context-callout',
'bhote-koshi-incident-callout',
]);
await layer.destroy();
});
test('Bhote Koshi locator cancels a stale boundary resolution and removes its surface', async () => {
const viewer = viewerFixture();
const controller = new AbortController();
let releaseBoundary;
const boundary = new Promise((resolve) => { releaseBoundary = resolve; });
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => boundary,
requestRender() {},
...nonRunningAnimation(),
});
const enabling = layer.enable(viewer, { signal: controller.signal });
controller.abort();
releaseBoundary({ ring: [[80, 26], [88, 26], [88, 30]] });
await assert.rejects(enabling, (error) => error?.name === 'AbortError');
assert.equal(viewer._test.removed.length, 1);
});
+97
View File
@@ -0,0 +1,97 @@
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
export const SOURCE_PATH_BEAT_IDS = Object.freeze([
'debris-dammed-lake',
'second-landslide',
'dhunche',
'mailung-upper-trishuli',
'mailung-bazzar',
'dandagaun',
'dandagaun-viewpoint',
'betrawati-bazaar',
'bhainse',
'bidur-trishuli-bridge',
]);
function nearestVertex(point, route) {
if (!point || !Number.isFinite(point.lon) || !Number.isFinite(point.lat))
return -1;
const longitudeScale = Math.cos((point.lat * Math.PI) / 180);
let nearest = -1;
let distance = 1000; // Witness viewpoints can sit beside the river, not on it.
route.forEach(([lon, lat], index) => {
const metres =
Math.hypot((lon - point.lon) * longitudeScale, lat - point.lat) * 111195;
if (metres < distance) {
distance = metres;
nearest = index;
}
});
return nearest;
}
/** Split the already-bundled GeoPera centreline; never connect witness pins. */
export function buildSourceShotPaths(event, route = BHOTE_KOSHI_FLOOD_PATH) {
const observations = new Map(
(event.evidenceSpine || []).map((point) => [point.id, point]),
);
const result = new Map();
const add = (id, from, to, { joinComparison = false } = {}) => {
let start = nearestVertex(from, route);
const end = nearestVertex(to, route);
if (start < 0 || end <= start) return;
const startHeight = from.fallbackElevationM ?? from.elevationM;
const endHeight = to.fallbackElevationM ?? to.elevationM;
if (!Number.isFinite(startHeight) || !Number.isFinite(endHeight)) return;
if (joinComparison) {
// The raster corridor ends between simplified centreline vertices.
// Snapping to its nearest vertex can move the head upstream on entry.
// Keep that already-sourced endpoint and continue to the next vertex
// downstream of it, rather than replaying the upstream half-segment.
const [lon, lat] = route[start];
const [nextLon, nextLat] = route[start + 1];
const scale = Math.cos((from.lat * Math.PI) / 180);
const along =
(from.lon - lon) * (nextLon - lon) * scale * scale +
(from.lat - lat) * (nextLat - lat);
if (along > 0) start++;
}
const coordinates = route.slice(start, end + 1);
if (
joinComparison &&
(coordinates[0][0] !== from.lon || coordinates[0][1] !== from.lat)
) {
coordinates.unshift([from.lon, from.lat]);
}
result.set(
id,
coordinates.map(([lon, lat], index) => ({
lon,
lat,
// Stable source profile for explicit source-elevation shots; otherwise a
// fallback when neither rendered mesh nor elevation terrain can be sampled.
fallbackElevationM:
startHeight +
((endHeight - startHeight) * index) / (coordinates.length - 1),
})),
);
};
add(
'debris-dammed-lake',
observations.get('debris-dammed-lake'),
observations.get('second-landslide'),
);
add(
'second-landslide',
observations.get('second-landslide'),
observations.get('gyirong-border-gate'),
);
let previous = event.reconstruction?.corridor?.at(-1);
for (const id of SOURCE_PATH_BEAT_IDS.slice(2)) {
const point = observations.get(id);
add(id, previous, point, { joinComparison: id === 'dhunche' });
// Missing coverage breaks continuity rather than inventing a long connector.
previous = point;
}
return result;
}
+58
View File
@@ -0,0 +1,58 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import { buildSourceShotPaths, SOURCE_PATH_BEAT_IDS } from './bhoteKoshiShotPaths.js';
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
const event = JSON.parse(await readFile(new URL('../../public/events/bhote-koshi-2026/event.json', import.meta.url)));
test('overview and evidence paths start at the lake reach, never the earlier trigger reach', () => {
const lakeStart = [85.48476, 28.33255];
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH[0], lakeStart);
assert.equal(BHOTE_KOSHI_FLOOD_PATH.some(([lon, lat]) => lon === 85.5306 && lat === 28.2916), false);
const paths = buildSourceShotPaths(event);
const first = paths.get('debris-dammed-lake')[0];
assert.deepEqual([first.lon, first.lat], lakeStart);
assert.deepEqual(BHOTE_KOSHI_FLOOD_PATH.slice(0, paths.get('debris-dammed-lake').length),
paths.get('debris-dammed-lake').map(({lon, lat}) => [lon, lat]));
});
test('ten shot paths use only the existing centreline and join at shared endpoints', () => {
const paths = buildSourceShotPaths(event);
assert.deepEqual([...paths.keys()], SOURCE_PATH_BEAT_IDS);
const vertices = new Set(BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) => `${lon},${lat}`));
const boundary = event.reconstruction.corridor.at(-1);
vertices.add(`${boundary.lon},${boundary.lat}`); // Exact sourced comparison handoff.
for (const points of paths.values()) {
assert.ok(points.length >= 2);
assert.ok(points.every(({ lon, lat, fallbackElevationM }) => (
vertices.has(`${lon},${lat}`) && Number.isFinite(fallbackElevationM)
)));
}
const coordinate = (point) => [point.lon, point.lat];
for (const ids of [SOURCE_PATH_BEAT_IDS.slice(0, 2), SOURCE_PATH_BEAT_IDS.slice(2)]) {
for (let index = 1; index < ids.length; index++) {
assert.deepEqual(coordinate(paths.get(ids[index - 1]).at(-1)), coordinate(paths.get(ids[index])[0]));
}
}
assert.deepEqual(coordinate(paths.get('bidur-trishuli-bridge').at(-1)), BHOTE_KOSHI_FLOOD_PATH.at(-1));
for (const id of ['immediate-collapse-viewpoint', 'devighat-taadi-khola-bridge', 'charaudi']) {
assert.equal(paths.has(id), false, 'out-of-coverage media must not gain a fabricated river route');
}
});
test('missing and distant observations fail closed without connecting witness coordinates', () => {
const broken = structuredClone(event);
broken.evidenceSpine.find(({ id }) => id === 'dhunche').lon = 0;
const paths = buildSourceShotPaths(broken);
assert.equal(paths.has('dhunche'), false);
assert.equal(paths.has('mailung-upper-trishuli'), false);
assert.equal(buildSourceShotPaths({}).size, 0);
});
test('Dhunche starts at the exact comparison endpoint without stepping upstream first', () => {
const boundary = event.reconstruction.corridor.at(-1);
const path = buildSourceShotPaths(event).get('dhunche');
assert.deepEqual([path[0].lon, path[0].lat], [boundary.lon, boundary.lat]);
assert.ok(path[1].lat < boundary.lat, 'the first new vertex is downstream of the comparison endpoint');
});
+93
View File
@@ -0,0 +1,93 @@
// src/data/cameraSensitivity.js
/**
* Shared claims on `camera.percentageChanged`.
*
* `camera.changed` fires once the view has moved by this fraction, and it is a
* single number on the camera that every listener in the app shares. Several
* layers want it finer than the default — traffic, bikeshare and transit all
* ask for 0.05 so they notice they have entered a coverage area — and each of
* them used to write the number directly and hand back whatever it remembered.
*
* That cannot work, because a number is not an owner. Two layers asking for the
* same 0.05 write the same value, so when the first one leaves it sees its own
* number still in place, concludes nothing else has claimed it, and restores
* the coarse default out from under a layer that is still running. The symptom
* is a camera-driven layer that quietly stops noticing the camera: Transit is
* turned off and Bikeshare stops loading new cities until something else nudges
* it.
*
* So ownership is tracked explicitly. Claims are named, the camera gets the
* finest value anyone has asked for, and the original value returns only when
* the last claim is gone. Claiming twice under one name replaces that claim.
*
* This is bookkeeping, not policy: it never decides what a layer should ask
* for, only that nobody's answer is taken away while they still need it.
*/
/** @type {WeakMap<object, {base: number, claims: Map<string, number>}>} */
const _cameras = new WeakMap();
/** The value Cesium starts a camera at, used when the camera reports nothing. */
const DEFAULT_PERCENTAGE_CHANGED = 0.5;
function ledgerFor(camera) {
let ledger = _cameras.get(camera);
if (!ledger) {
const base = Number.isFinite(camera.percentageChanged)
? camera.percentageChanged
: DEFAULT_PERCENTAGE_CHANGED;
ledger = { base, claims: new Map() };
_cameras.set(camera, ledger);
}
return ledger;
}
function applyLedger(camera, ledger) {
let value = ledger.base;
for (const claimed of ledger.claims.values()) {
if (claimed < value) value = claimed;
}
camera.percentageChanged = value;
return value;
}
/**
* Ask for a camera-change sensitivity at least as fine as `value`.
* @param {object|null|undefined} camera A Cesium camera (or anything with `percentageChanged`).
* @param {string} owner Stable claim name, usually the layer id.
* @param {number} value Requested `percentageChanged`.
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function claimCameraSensitivity(camera, owner, value) {
if (!camera || !owner || !Number.isFinite(value)) return null;
const ledger = ledgerFor(camera);
ledger.claims.set(owner, value);
return applyLedger(camera, ledger);
}
/**
* Give up one claim. The camera keeps the finest value still claimed by
* somebody else, and returns to its original only when none are left.
* @param {object|null|undefined} camera
* @param {string} owner
* @returns {number|null} The value now in force, or null when there is no camera.
*/
export function releaseCameraSensitivity(camera, owner) {
if (!camera || !owner) return null;
const ledger = _cameras.get(camera);
if (!ledger) return null;
if (!ledger.claims.delete(owner)) return camera.percentageChanged;
const applied = applyLedger(camera, ledger);
if (ledger.claims.size === 0) _cameras.delete(camera);
return applied;
}
/**
* Who currently holds a claim. For tests and diagnostics only.
* @param {object|null|undefined} camera
* @returns {Array<string>}
*/
export function cameraSensitivityClaims(camera) {
const ledger = camera ? _cameras.get(camera) : null;
return ledger ? [...ledger.claims.keys()] : [];
}
+67 -19
View File
@@ -110,8 +110,12 @@ export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({
*/
export function isCctvCardAnchorSafe({ sy, viewH, pinned = false } = {}) {
if (pinned) return Number.isFinite(sy);
if (!Number.isFinite(sy) || !Number.isFinite(viewH) || viewH <= 0) return false;
const safeTop = Math.min(CCTV_CARD_SAFE_TOP_MAX_PX, viewH * CCTV_CARD_SAFE_TOP_RATIO);
if (!Number.isFinite(sy) || !Number.isFinite(viewH) || viewH <= 0)
return false;
const safeTop = Math.min(
CCTV_CARD_SAFE_TOP_MAX_PX,
viewH * CCTV_CARD_SAFE_TOP_RATIO,
);
return sy >= safeTop;
}
@@ -126,11 +130,24 @@ export function isCctvCardAnchorSafe({ sy, viewH, pinned = false } = {}) {
* @param {number} [options.limit]
* @returns {string[]} Accepted ids, nearest-first.
*/
export function declutterCctvCards(candidates, { minSepPx = CCTV_CARD_MIN_SEP_PX, limit = Infinity } = {}) {
export function declutterCctvCards(
candidates,
{ minSepPx = CCTV_CARD_MIN_SEP_PX, limit = Infinity } = {},
) {
const valid = (Array.isArray(candidates) ? candidates : [])
.filter((c) => c && typeof c.id === 'string' && c.id
&& Number.isFinite(c.sx) && Number.isFinite(c.sy))
.sort((a, b) => (a.distanceKm ?? Infinity) - (b.distanceKm ?? Infinity) || a.id.localeCompare(b.id));
.filter(
(c) =>
c &&
typeof c.id === 'string' &&
c.id &&
Number.isFinite(c.sx) &&
Number.isFinite(c.sy),
)
.sort(
(a, b) =>
(a.distanceKm ?? Infinity) - (b.distanceKm ?? Infinity) ||
a.id.localeCompare(b.id),
);
const minSq = minSepPx * minSepPx;
const accepted = [];
const acceptedIds = [];
@@ -140,7 +157,10 @@ export function declutterCctvCards(candidates, { minSepPx = CCTV_CARD_MIN_SEP_PX
for (let i = 0; i < accepted.length; i++) {
const dx = candidate.sx - accepted[i].sx;
const dy = candidate.sy - accepted[i].sy;
if (dx * dx + dy * dy < minSq) { clear = false; break; }
if (dx * dx + dy * dy < minSq) {
clear = false;
break;
}
}
if (!clear) continue;
accepted.push(candidate);
@@ -165,15 +185,26 @@ export function cardScaleForAltitude(cameraHeightM) {
const h = Number.isFinite(cameraHeightM) ? Math.max(0, cameraHeightM) : 0;
if (h <= CCTV_CARD_SCALE_FULL_M) return { scale: 1, alpha: 1 };
if (h <= CCTV_CARD_SCALE_MID_M) {
const t = (h - CCTV_CARD_SCALE_FULL_M) / (CCTV_CARD_SCALE_MID_M - CCTV_CARD_SCALE_FULL_M);
const t =
(h - CCTV_CARD_SCALE_FULL_M) /
(CCTV_CARD_SCALE_MID_M - CCTV_CARD_SCALE_FULL_M);
const s = t * t * (3 - 2 * t); // smoothstep — no visible kink at either end
return { scale: 1 + (CCTV_CARD_SCALE_AT_MID - 1) * s, alpha: 1 };
}
const t = Math.min(1, (h - CCTV_CARD_SCALE_MID_M) / (CCTV_CARD_FADE_END_M - CCTV_CARD_SCALE_MID_M));
const scale = CCTV_CARD_SCALE_AT_MID + (CCTV_CARD_SCALE_MIN - CCTV_CARD_SCALE_AT_MID) * t;
if (h >= CCTV_CARD_FADE_END_M) return { scale: CCTV_CARD_SCALE_MIN, alpha: 0 };
const t = Math.min(
1,
(h - CCTV_CARD_SCALE_MID_M) /
(CCTV_CARD_FADE_END_M - CCTV_CARD_SCALE_MID_M),
);
const scale =
CCTV_CARD_SCALE_AT_MID + (CCTV_CARD_SCALE_MIN - CCTV_CARD_SCALE_AT_MID) * t;
if (h >= CCTV_CARD_FADE_END_M)
return { scale: CCTV_CARD_SCALE_MIN, alpha: 0 };
if (h <= CCTV_CARD_FADE_START_M) return { scale, alpha: 1 };
const alpha = 1 - (h - CCTV_CARD_FADE_START_M) / (CCTV_CARD_FADE_END_M - CCTV_CARD_FADE_START_M);
const alpha =
1 -
(h - CCTV_CARD_FADE_START_M) /
(CCTV_CARD_FADE_END_M - CCTV_CARD_FADE_START_M);
return { scale, alpha };
}
@@ -192,17 +223,23 @@ export function cardScaleForAltitude(cameraHeightM) {
* @param {number} [input.sinceLastLaunchMs] - Ms since the last fetch launch.
* @returns {{mode:('burst'|'steady'), launch:boolean}}
*/
export function cardFetchPolicy({ coldFill = false, inFlight = 0, sinceLastLaunchMs = Infinity } = {}) {
export function cardFetchPolicy({
coldFill = false,
inFlight = 0,
sinceLastLaunchMs = Infinity,
} = {}) {
if (coldFill) {
return {
mode: 'burst',
launch: inFlight < CCTV_CARD_FETCH_BURST_LIMIT
&& sinceLastLaunchMs >= CCTV_CARD_FETCH_BURST_SPACING_MS,
launch:
inFlight < CCTV_CARD_FETCH_BURST_LIMIT &&
sinceLastLaunchMs >= CCTV_CARD_FETCH_BURST_SPACING_MS,
};
}
return {
mode: 'steady',
launch: inFlight === 0 && sinceLastLaunchMs >= CCTV_CARD_FETCH_STEADY_SPACING_MS,
launch:
inFlight === 0 && sinceLastLaunchMs >= CCTV_CARD_FETCH_STEADY_SPACING_MS,
};
}
@@ -230,7 +267,12 @@ export function createFrameSlot() {
export function applyFrameResult(prev, result, nowMs) {
const base = prev || createFrameSlot();
if (result?.ok && result.frame) {
return { frame: result.frame, stamp: nowMs, failCount: 0, lastAttemptAt: nowMs };
return {
frame: result.frame,
stamp: nowMs,
failCount: 0,
lastAttemptAt: nowMs,
};
}
return {
frame: base.frame,
@@ -278,11 +320,17 @@ export function frameFetchDue(slot, refreshMs, nowMs) {
* @param {number} [cap]
* @returns {string[]} Ids to drop from the cache.
*/
export function planFrameCachePrune(slots, keepIds, cap = CCTV_FRAME_CACHE_MAX) {
export function planFrameCachePrune(
slots,
keepIds,
cap = CCTV_FRAME_CACHE_MAX,
) {
const keep = new Set(keepIds);
const spare = (Array.isArray(slots) ? slots : [])
.filter((slot) => slot && typeof slot.id === 'string' && !keep.has(slot.id))
.sort((a, b) => (b.stamp || 0) - (a.stamp || 0) || a.id.localeCompare(b.id));
.sort(
(a, b) => (b.stamp || 0) - (a.stamp || 0) || a.id.localeCompare(b.id),
);
const capacity = Math.max(0, cap - keep.size);
return spare.slice(capacity).map((slot) => slot.id);
}
+173 -44
View File
@@ -74,7 +74,11 @@ export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW);
const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom;
if (s < 0) return null;
const hit = Cesium.Cartesian3.multiplyByScalar(rayDir, s, new Cesium.Cartesian3());
const hit = Cesium.Cartesian3.multiplyByScalar(
rayDir,
s,
new Cesium.Cartesian3(),
);
return Cesium.Cartesian3.add(rayOrigin, hit, hit);
}
@@ -89,7 +93,10 @@ export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
*/
export function ringAngle(hitPoint, center, basisA, basisB) {
const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW);
return Math.atan2(Cesium.Cartesian3.dot(v, basisB), Cesium.Cartesian3.dot(v, basisA));
return Math.atan2(
Cesium.Cartesian3.dot(v, basisB),
Cesium.Cartesian3.dot(v, basisA),
);
}
/**
@@ -150,7 +157,11 @@ function enuAxes(position) {
/** a*sa + b*sb (fresh Cartesian3). */
function combine2(a, sa, b, sb) {
const out = Cesium.Cartesian3.multiplyByScalar(a, sa, new Cesium.Cartesian3());
const out = Cesium.Cartesian3.multiplyByScalar(
a,
sa,
new Cesium.Cartesian3(),
);
const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3());
return Cesium.Cartesian3.add(out, t, out);
}
@@ -165,7 +176,12 @@ function combine2(a, sa, b, sb) {
function viewAxesFor(headingDeg, pitchDeg, axes) {
const h = toRadians(headingDeg);
const p = toRadians(pitchDeg);
const forwardHoriz = combine2(axes.east, Math.sin(h), axes.north, Math.cos(h));
const forwardHoriz = combine2(
axes.east,
Math.sin(h),
axes.north,
Math.cos(h),
);
const right = combine2(axes.east, Math.cos(h), axes.north, -Math.sin(h));
const view = combine2(forwardHoriz, Math.cos(p), axes.up, Math.sin(p));
return { forwardHoriz, right, view };
@@ -176,7 +192,12 @@ function ringPositions(center, radius, basisA, basisB) {
const positions = [];
for (let i = 0; i <= RING_SEGMENTS; i++) {
const angle = (i / RING_SEGMENTS) * 2 * Math.PI;
const offset = combine2(basisA, Math.cos(angle) * radius, basisB, Math.sin(angle) * radius);
const offset = combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
);
positions.push(Cesium.Cartesian3.add(center, offset, offset));
}
return positions;
@@ -202,7 +223,12 @@ function ringPositions(center, radius, basisA, basisB) {
* destroy: function(): void, isDragging: function(): boolean,
* isEnabled: function(): boolean}}
*/
export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, endPatch }) {
export function createCalibrationGizmo({
viewer,
getActiveRecord,
applyPatch,
endPatch,
}) {
let enabled = false;
let drag = null; // { part, startCal, basePose, refs... }
let hoveredId = null;
@@ -225,20 +251,24 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
function polylinePart(part, color, width, arrow = false) {
addEntity(part, {
...(arrow ? {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 14,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
} : {}),
...(arrow
? {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize: 14,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
}
: {}),
polyline: {
positions: [],
width,
material: arrow ? new Cesium.PolylineArrowMaterialProperty(color) : color.withAlpha(0.9),
material: arrow
? new Cesium.PolylineArrowMaterialProperty(color)
: color.withAlpha(0.9),
// Standard gizmo convention: parts behind geometry stay clearly
// visible, just dimmed (a street-level mount buries half the heading
// ring in sloped photogrammetry tiles — smoke-tested 2026-07-05).
@@ -286,16 +316,42 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
}
const mount = positions.mount;
const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor(camera.headingDeg, camera.pitchDeg, axes);
const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg,
camera.pitchDeg,
axes,
);
const rangeM = Math.max(1, Number(camera.rangeM) || 1);
const radius = Math.min(RING_RADIUS_MAX_M, Math.max(RING_RADIUS_MIN_M, rangeM * RING_RADIUS_FACTOR));
const radius = Math.min(
RING_RADIUS_MAX_M,
Math.max(RING_RADIUS_MIN_M, rangeM * RING_RADIUS_FACTOR),
);
const arrowLen = radius * ARROW_LENGTH_FACTOR;
entities.get('ring-heading').polyline.positions = ringPositions(mount, radius, axes.north, axes.east);
entities.get('ring-pitch').polyline.positions = ringPositions(mount, radius, forwardHoriz, axes.up);
const arrowTo = (dir) => [mount, Cesium.Cartesian3.add(
mount, Cesium.Cartesian3.multiplyByScalar(dir, arrowLen, new Cesium.Cartesian3()), new Cesium.Cartesian3()
)];
entities.get('ring-heading').polyline.positions = ringPositions(
mount,
radius,
axes.north,
axes.east,
);
entities.get('ring-pitch').polyline.positions = ringPositions(
mount,
radius,
forwardHoriz,
axes.up,
);
const arrowTo = (dir) => [
mount,
Cesium.Cartesian3.add(
mount,
Cesium.Cartesian3.multiplyByScalar(
dir,
arrowLen,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
];
const eastArrow = arrowTo(axes.east);
const northArrow = arrowTo(axes.north);
const upArrow = arrowTo(axes.up);
@@ -306,8 +362,16 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
entities.get('move-up').polyline.positions = upArrow;
entities.get('move-up').position = upArrow[1];
entities.get('handle-range').position = positions.capCenter;
entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint(positions.tl, positions.bl, new Cesium.Cartesian3());
entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint(positions.tr, positions.br, new Cesium.Cartesian3());
entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint(
positions.tl,
positions.bl,
new Cesium.Cartesian3(),
);
entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint(
positions.tr,
positions.br,
new Cesium.Cartesian3(),
);
for (const entity of entities.values()) entity.show = true;
}
@@ -343,8 +407,17 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
return null;
}
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick @', windowPosition?.x, windowPosition?.y, '→',
JSON.stringify(results.map((r) => String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name))));
console.debug(
'[CCTV:gizmo] drillPick @',
windowPosition?.x,
windowPosition?.y,
'→',
JSON.stringify(
results.map((r) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name),
),
),
);
}
for (const picked of results) {
const part = gizmoPartFrom(picked);
@@ -379,7 +452,8 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
for (const [name, entity] of entities.entries()) {
if (!entity.point) continue;
const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`;
entity.point.pixelSize = (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
entity.point.pixelSize =
(name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
}
setCursor(hoveredId ? 'grab' : '');
}
@@ -397,7 +471,11 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
const mount = Cesium.Cartesian3.clone(positions.mount);
const capCenter = Cesium.Cartesian3.clone(positions.capCenter);
const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor(camera.headingDeg, camera.pitchDeg, axes);
const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg,
camera.pitchDeg,
axes,
);
const startCal = { ...camera.calibration };
const basePose = { ...camera.basePose };
const state = {
@@ -405,7 +483,15 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
// mid-drag active-camera switch (voice select / auto-hop) onto a
// different camera — its basePose makes the captured offsets wrong.
record,
part, startCal, basePose, mount, capCenter, axes, forwardHoriz, right, view,
part,
startCal,
basePose,
mount,
capCenter,
axes,
forwardHoriz,
right,
view,
effectiveRangeM: geometry.rangeM,
startAngle: null,
startParam: null,
@@ -419,8 +505,17 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
const hit = rayPlaneIntersect(ray.origin, ray.direction, mount, right);
if (!hit) return false;
state.startAngle = ringAngle(hit, mount, forwardHoriz, axes.up); // 0 = level, + = up
} else if (part === 'move-east' || part === 'move-north' || part === 'move-up') {
const dir = part === 'move-east' ? axes.east : part === 'move-north' ? axes.north : axes.up;
} else if (
part === 'move-east' ||
part === 'move-north' ||
part === 'move-up'
) {
const dir =
part === 'move-east'
? axes.east
: part === 'move-north'
? axes.north
: axes.up;
state.axisDir = dir;
const t = closestParamOnAxis(ray.origin, ray.direction, mount, dir);
if (t === null) return false;
@@ -448,26 +543,49 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
function dragPatch(windowPosition) {
const ray = pickRay(windowPosition);
if (!ray || !drag) return null;
const { part, startCal, basePose, mount, capCenter, axes, forwardHoriz, right, view } = drag;
const {
part,
startCal,
basePose,
mount,
capCenter,
axes,
forwardHoriz,
right,
view,
} = drag;
if (part === 'ring-heading') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, mount, axes.up);
if (!hit) return null;
const angle = ringAngle(hit, mount, axes.north, axes.east);
return { headingDeg: startCal.headingDeg + toDeg(signedAngleDelta(drag.startAngle, angle)) };
return {
headingDeg:
startCal.headingDeg + toDeg(signedAngleDelta(drag.startAngle, angle)),
};
}
if (part === 'ring-pitch') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, mount, right);
if (!hit) return null;
const angle = ringAngle(hit, mount, forwardHoriz, axes.up);
return { pitchDeg: startCal.pitchDeg + toDeg(signedAngleDelta(drag.startAngle, angle)) };
return {
pitchDeg:
startCal.pitchDeg + toDeg(signedAngleDelta(drag.startAngle, angle)),
};
}
if (part === 'move-east' || part === 'move-north' || part === 'move-up') {
const t = closestParamOnAxis(ray.origin, ray.direction, mount, drag.axisDir);
const t = closestParamOnAxis(
ray.origin,
ray.direction,
mount,
drag.axisDir,
);
if (t === null) return null;
const delta = t - drag.startParam;
if (part === 'move-east') return { offsetEastM: startCal.offsetEastM + delta };
if (part === 'move-north') return { offsetNorthM: startCal.offsetNorthM + delta };
if (part === 'move-east')
return { offsetEastM: startCal.offsetEastM + delta };
if (part === 'move-north')
return { offsetNorthM: startCal.offsetNorthM + delta };
return { heightM: startCal.heightM + delta };
}
if (part === 'handle-range') {
@@ -478,11 +596,16 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
if (part === 'handle-fov-l' || part === 'handle-fov-r') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view);
if (!hit) return null;
const lateral = Math.abs(Cesium.Cartesian3.dot(
Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()), right
));
const lateral = Math.abs(
Cesium.Cartesian3.dot(
Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()),
right,
),
);
const halfW = Math.max(0.5, lateral);
const fovDeg = toDeg(2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)));
const fovDeg = toDeg(
2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)),
);
return { fovDeg: fovDeg - basePose.fovDeg };
}
return null;
@@ -531,7 +654,13 @@ export function createCalibrationGizmo({ viewer, getActiveRecord, applyPatch, en
return;
}
const patch = dragPatch(event.endPosition);
debugLog('dragPatch', drag.part, event.endPosition, '→', patch ? JSON.stringify(patch) : null);
debugLog(
'dragPatch',
drag.part,
event.endPosition,
'→',
patch ? JSON.stringify(patch) : null,
);
if (patch) applyPatch(patch, drag.record);
return;
}
+9 -8
View File
@@ -46,7 +46,7 @@ export function cameraHue(index) {
* @returns {{fill: Cesium.Color, fillActive: Cesium.Color, line: Cesium.Color, lineActive: Cesium.Color}}
*/
export function viewshedColors(hueDeg) {
const hue = ((Number(hueDeg) % 360) + 360) % 360 / 360;
const hue = (((Number(hueDeg) % 360) + 360) % 360) / 360;
return {
fill: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_IDLE),
fillActive: Cesium.Color.fromHsl(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE),
@@ -66,7 +66,13 @@ export function viewshedColors(hueDeg) {
* @returns {{positions: Float64Array, indices: Uint16Array}}
*/
export function frustumVolumeGeometryData(positions) {
const pts = [positions.mount, positions.tl, positions.tr, positions.br, positions.bl];
const pts = [
positions.mount,
positions.tl,
positions.tr,
positions.br,
positions.bl,
];
const flat = new Float64Array(15);
pts.forEach((p, i) => {
flat[i * 3] = p.x;
@@ -75,12 +81,7 @@ export function frustumVolumeGeometryData(positions) {
});
// apex=0, tl=1, tr=2, br=3, bl=4 — 4 side faces + far cap (2 triangles).
const indices = new Uint16Array([
0, 1, 2,
0, 2, 3,
0, 3, 4,
0, 4, 1,
1, 2, 3,
1, 3, 4,
0, 1, 2, 0, 2, 3, 0, 3, 4, 0, 4, 1, 1, 2, 3, 1, 3, 4,
]);
return { positions: flat, indices };
}
+1 -2
View File
@@ -21,7 +21,7 @@ export function nextCockpitNearContacts(
) {
const previous = previousIds instanceof Set ? previousIds : new Set();
const addSq = Math.max(0, Number(addDistanceM) || 0) ** 2;
const keepSq = Math.max(addSq, (Math.max(0, Number(keepDistanceM) || 0) ** 2));
const keepSq = Math.max(addSq, Math.max(0, Number(keepDistanceM) || 0) ** 2);
const next = new Set();
for (const [id, distanceSq] of distancesSquared || []) {
@@ -32,4 +32,3 @@ export function nextCockpitNearContacts(
return next;
}
+27 -8
View File
@@ -42,7 +42,9 @@ export const CONTACT_MATCH_TIER = Object.freeze({
* @returns {string} Canonical form, or '' when there is nothing to compare.
*/
export function canonicalizeContactId(value) {
return String(value ?? '').replace(/[^a-z0-9]/gi, '').toUpperCase();
return String(value ?? '')
.replace(/[^a-z0-9]/gi, '')
.toUpperCase();
}
/**
@@ -57,16 +59,31 @@ export function canonicalizeContactId(value) {
* @param {string} [params.registration] Contact's registration, if any.
* @returns {number} A {@link CONTACT_MATCH_TIER} value; `NONE` when no match.
*/
export function rankContactMatch({ query, hex = '', callsign = '', registration = '' }) {
const rawQuery = String(query ?? '').trim().toLowerCase();
export function rankContactMatch({
query,
hex = '',
callsign = '',
registration = '',
}) {
const rawQuery = String(query ?? '')
.trim()
.toLowerCase();
if (!rawQuery) return CONTACT_MATCH_TIER.NONE;
if (String(hex ?? '').trim().toLowerCase() === rawQuery) return CONTACT_MATCH_TIER.HEX_EXACT;
if (
String(hex ?? '')
.trim()
.toLowerCase() === rawQuery
)
return CONTACT_MATCH_TIER.HEX_EXACT;
const callsignText = String(callsign ?? '').trim().toLowerCase();
const callsignText = String(callsign ?? '')
.trim()
.toLowerCase();
// Callsigns carry no separators, so they compare raw — canonicalizing them
// would silently widen the long-standing callsign contract.
if (callsignText && callsignText === rawQuery) return CONTACT_MATCH_TIER.CALLSIGN_EXACT;
if (callsignText && callsignText === rawQuery)
return CONTACT_MATCH_TIER.CALLSIGN_EXACT;
const canonicalQuery = canonicalizeContactId(rawQuery);
const canonicalRegistration = canonicalizeContactId(registration);
@@ -74,11 +91,13 @@ export function rankContactMatch({ query, hex = '', callsign = '', registration
return CONTACT_MATCH_TIER.REGISTRATION_EXACT;
}
if (callsignText && callsignText.startsWith(rawQuery)) return CONTACT_MATCH_TIER.CALLSIGN_PREFIX;
if (callsignText && callsignText.startsWith(rawQuery))
return CONTACT_MATCH_TIER.CALLSIGN_PREFIX;
if (canonicalQuery && canonicalRegistration.startsWith(canonicalQuery)) {
return CONTACT_MATCH_TIER.REGISTRATION_PREFIX;
}
if (callsignText && callsignText.includes(rawQuery)) return CONTACT_MATCH_TIER.CALLSIGN_SUBSTRING;
if (callsignText && callsignText.includes(rawQuery))
return CONTACT_MATCH_TIER.CALLSIGN_SUBSTRING;
if (canonicalQuery && canonicalRegistration.includes(canonicalQuery)) {
return CONTACT_MATCH_TIER.REGISTRATION_SUBSTRING;
}
+691
View File
@@ -0,0 +1,691 @@
/** Portable retained report-time playback. No scene or scheduling ownership. */
export const FIX_BYTES = 48;
export const FIX_FLAGS = Object.freeze({
VEHICLE_TIME: 1,
FEED_TIME: 2,
RECEIPT_TIME: 4,
FLOOR: 8,
BREAK: 16,
LIVE: 32,
});
const clampDelay = (n) => Math.max(25_000, Math.min(120_000, n));
export function createLagReservoir(capacity = 256) {
return { values: new Float64Array(capacity), count: 0, cursor: 0 };
}
function addLag(reservoir, value) {
if (!reservoir || !Number.isFinite(value) || value < 0) return;
reservoir.values[reservoir.cursor] = value;
reservoir.cursor = (reservoir.cursor + 1) % reservoir.values.length;
reservoir.count = Math.min(reservoir.count + 1, reservoir.values.length);
}
function percentile(reservoir, rank) {
if (!reservoir?.count) return 0;
const sorted = reservoir.values.slice(0, reservoir.count).sort();
return sorted[Math.ceil(sorted.length * rank) - 1];
}
/** Optional shared payload budget. Call trimTrack on lower-priority tracks first. */
export function createHistoryBudget(maxBytes = 32 * 1024 * 1024) {
return { maxBytes, allocatedBytes: 0 };
}
/** Numeric fields are reserved up front, including unknown mesh heights. */
export function createFixSample() {
return {
t: NaN,
lat: NaN,
lon: NaN,
heightM: NaN,
h: NaN,
receivedAt: NaN,
bearingDeg: NaN,
flags: 0,
epoch: 0,
seq: -1,
};
}
export function createTrack({
capacity = 128,
retentionMs = 900_000,
policy = {},
budget = null,
} = {}) {
capacity = Math.max(2, Math.min(128, Math.floor(capacity)));
return {
capacity,
retentionMs,
policy,
budget,
metricsScratchA: createFixSample(),
metricsScratchB: createFixSample(),
storage: new DataView(new ArrayBuffer(0)),
slots: 0,
head: 0,
count: 0,
baseSeq: 0,
revision: 0,
truncated: false,
epochs: new Map(),
lag: createLagReservoir(32),
targetDelayMs: 25_000,
displayT: NaN,
wallAnchor: NaN,
monoAnchor: NaN,
lastMono: NaN,
offset: 0,
rate: 1,
phase: 'buffering',
resets: 0,
resetReason: null,
acceptedAt: NaN,
acceptedMono: NaN,
resumePending: false,
bracket: 0,
metricsRevision: -1,
metricsIndex: -1,
from: createFixSample(),
to: createFixSample(),
metrics: { speed: NaN, course: NaN, nextMotionT: Infinity },
latest: createFixSample(),
pending: null,
pendingCount: 0,
};
}
function address(track, index) {
return ((track.head + index) % track.slots) * FIX_BYTES;
}
export function readFix(track, index, out = {}) {
if (index < 0 || index >= track.count) return null;
const v = track.storage,
o = address(track, index);
out.t = v.getFloat64(o);
out.lat = v.getFloat64(o + 8);
out.lon = v.getFloat64(o + 16);
out.heightM = v.getFloat32(o + 24);
out.h = out.heightM;
out.receivedAt = v.getFloat64(o + 28);
out.bearingDeg = v.getFloat32(o + 36);
out.flags = v.getUint32(o + 40);
out.epoch = v.getUint32(o + 44);
out.seq = track.baseSeq + index;
return out;
}
function writeFix(track, index, fix) {
const v = track.storage,
o = address(track, index);
v.setFloat64(o, fix.t);
v.setFloat64(o + 8, fix.lat);
v.setFloat64(o + 16, fix.lon);
v.setFloat32(o + 24, fix.heightM ?? fix.h ?? NaN);
v.setFloat64(o + 28, fix.receivedAt ?? NaN);
v.setFloat32(o + 36, fix.bearingDeg ?? NaN);
v.setUint32(o + 40, fix.flags || 0);
v.setUint32(o + 44, fix.epoch || 0);
}
function resize(track, slots) {
const bytes = slots * FIX_BYTES,
delta = bytes - track.storage.byteLength;
if (
delta > 0 &&
track.budget &&
track.budget.allocatedBytes + delta > track.budget.maxBytes
)
return false;
const old = track.storage,
head = track.head,
oldSlots = track.slots;
const next = new Uint8Array(bytes),
previous = new Uint8Array(old.buffer);
for (let i = 0; i < track.count; i++) {
const o = ((head + i) % oldSlots) * FIX_BYTES;
next.set(previous.subarray(o, o + FIX_BYTES), i * FIX_BYTES);
}
track.storage = new DataView(next.buffer);
track.slots = slots;
track.head = 0;
if (track.budget) track.budget.allocatedBytes += delta;
return true;
}
export function destroyTrack(track) {
if (track.budget) track.budget.allocatedBytes -= track.storage.byteLength;
track.storage = new DataView(new ArrayBuffer(0));
track.count = 0;
track.slots = 0;
track.epochs.clear();
}
function timeAt(track, i) {
return track.storage.getFloat64(address(track, i));
}
function dropOldest(track) {
track.head = (track.head + 1) % track.slots;
track.count--;
track.baseSeq++;
track.revision++;
track.truncated = true;
}
/** Retention never evicts the bracket currently on screen. */
export function trimTrack(track, nowMs, keep = track.capacity) {
while (
track.count > 2 &&
(track.count > keep || timeAt(track, 1) < nowMs - track.retentionMs)
) {
if (Number.isFinite(track.displayT) && timeAt(track, 1) > track.displayT)
break;
dropOldest(track);
}
if (keep < track.slots && track.count <= keep)
resize(track, Math.max(2, track.count));
const used = new Set();
for (let i = 0; i < track.count; i++)
used.add(track.storage.getUint32(address(track, i) + 44));
for (const id of track.epochs.keys())
if (!used.has(id)) track.epochs.delete(id);
}
export function validFix(fix) {
return (
Number.isFinite(fix?.t) &&
fix.t >= 0 &&
Number.isFinite(fix.lat) &&
Math.abs(fix.lat) <= 90 &&
Number.isFinite(fix.lon) &&
Math.abs(fix.lon) <= 180
);
}
function distance(a, b) {
const lon = ((b.lon - a.lon + 540) % 360) - 180;
return Math.hypot(
(b.lat - a.lat) * 111320,
lon * 111320 * Math.cos((a.lat * Math.PI) / 180),
);
}
function append(track, fix) {
if (track.count === track.slots && track.slots < track.capacity)
resize(track, Math.min(track.capacity, Math.max(8, track.slots * 2)));
if (track.count === track.slots) {
if (track.count < 2) return false;
if (Number.isFinite(track.displayT) && timeAt(track, 1) > track.displayT) {
// Pin both active ends; drop the next future observation and mark the gap.
if (track.count < 4) return false;
const scratch = {};
for (let i = 2; i < track.count - 1; i++) {
readFix(track, i + 1, scratch);
if (i === 2) scratch.flags |= FIX_FLAGS.BREAK;
writeFix(track, i, scratch);
}
track.count--;
track.truncated = true;
} else dropOldest(track);
}
writeFix(track, track.count++, fix);
track.revision++;
return true;
}
export function insertFix(track, fix, observation = {}) {
if (
!validFix(fix) ||
(Number.isFinite(observation.wallNowMs) &&
fix.t > observation.wallNowMs + 10_000)
)
return { accepted: false, reason: 'malformed' };
const last = readFix(track, track.count - 1, track.latest);
if (last && fix.t === last.t)
return {
accepted: false,
reason:
fix.lat === last.lat && fix.lon === last.lon ? 'repeat' : 'conflict',
};
let reason = last ? 'moved' : 'first';
if (
last &&
(fix.t < last.t || (track.policy.accept && !track.policy.accept(last, fix)))
) {
reason = fix.t < last.t ? 'out-of-order' : 'implausible';
const prior = track.pending;
if (
!prior ||
prior.reason !== reason ||
fix.t <= prior.t ||
(track.policy.accept && !track.policy.accept(prior, fix))
) {
if (!prior || fix.t !== prior.t) {
track.pending = { ...fix, reason };
track.pendingCount = 1;
}
return { accepted: false, reason };
}
track.pendingCount++;
const required = reason === 'out-of-order' ? 3 : 2;
if (track.pendingCount < required) {
track.pending = { ...fix, reason };
return { accepted: false, reason };
}
// Clock correction starts a new time domain. A spatial replacement retains a visible gap.
if (reason === 'out-of-order') {
track.count = 0;
track.head = 0;
track.baseSeq += 128;
}
const epoch = (last.epoch + 1) >>> 0;
append(track, {
...prior,
epoch,
flags: (prior.flags || 0) | FIX_FLAGS.BREAK,
});
fix = { ...fix, epoch };
if (reason === 'out-of-order') track.displayT = NaN;
track.resetReason = reason;
track.resets++;
}
const receivedAt =
observation.receivedAt ?? fix.receivedAt ?? observation.wallNowMs ?? fix.t;
trimTrack(track, receivedAt);
const accepted = append(track, {
...fix,
receivedAt,
flags: (fix.flags || 0) | FIX_FLAGS.LIVE,
});
if (accepted) {
if (!observation.replayed) {
if (last && fix.t > last.t && reason === 'moved') {
addLag(track.lag, receivedAt - last.t);
addLag(track.policy.feedLag, receivedAt - last.t);
track.targetDelayMs = clampDelay(
Math.max(
percentile(track.lag, 0.95),
percentile(track.policy.feedLag, 0.9),
) + 5000,
);
} else if (!last)
track.targetDelayMs = clampDelay(
Math.max(0, receivedAt - fix.t) + 20_000,
);
}
track.acceptedAt = receivedAt;
track.acceptedMono = observation.monoNowMs ?? NaN;
track.resumePending = true;
track.pending = null;
track.pendingCount = 0;
}
return { accepted, reason: accepted ? reason : 'capacity' };
}
/** Bounded backfill; live positions win conflicts and the clock/health are untouched. */
export function mergeHistory(track, fixes) {
const merged = new Map();
for (const fix of fixes.slice(-128))
if (
validFix(fix) &&
(!Number.isFinite(track.acceptedAt) ||
fix.t >= track.acceptedAt - track.retentionMs)
)
merged.set(fix.t, { ...fix, flags: (fix.flags || 0) & ~FIX_FLAGS.LIVE });
for (let i = 0; i < track.count; i++) {
const fix = readFix(track, i);
merged.set(fix.t, fix);
}
const retained = Array.from({ length: track.count }, (_, i) =>
readFix(track, i),
);
const active = Number.isFinite(track.displayT)
? retained.findLastIndex((f) => f.t <= track.displayT)
: -1;
const pinnedFrom = retained[active],
pinnedTo = retained[active + 1];
const trusted = new Set(retained.map((f) => f.t));
const candidates = [...merged.values()]
.sort((a, b) => a.t - b.t)
.filter(
(f) =>
trusted.has(f.t) ||
!pinnedFrom ||
!pinnedTo ||
f.t < pinnedFrom.t ||
f.t > pinnedTo.t,
);
const ordered = [];
// Start from an admitted live position, including when walking backwards
// into retained history. A lone outlier is quarantined in either direction.
// Never borrow the live pending observation as a second vote for itself.
function admit(sequence, anchor, backwards = false) {
let last = anchor,
pending = null;
const plausible = (a, b) =>
!track.policy.accept ||
(backwards ? track.policy.accept(b, a) : track.policy.accept(a, b));
for (const fix of sequence) {
if (trusted.has(fix.t) || !last || plausible(last, fix)) {
ordered.push(fix);
last = fix;
pending = null;
} else if (pending && plausible(pending, fix)) {
// Two distinct coherent observations establish a replacement segment.
// Keep a visible gap between it and the authoritative live path.
if (backwards) last.flags |= FIX_FLAGS.BREAK;
else pending.flags |= FIX_FLAGS.BREAK;
ordered.push(pending, fix);
last = fix;
pending = null;
} else pending = fix;
}
}
const first = retained[0];
if (first) {
admit(
candidates.filter((f) => f.t < first.t).reverse(),
merged.get(first.t),
true,
);
admit(
candidates.filter((f) => f.t >= first.t),
null,
);
} else admit(candidates, null);
ordered.sort((a, b) => a.t - b.t);
while (ordered.length > track.capacity) {
const i = ordered.findIndex(
(f) => f.t !== pinnedFrom?.t && f.t !== pinnedTo?.t,
);
if (i > 0 && i + 1 < ordered.length)
ordered[i + 1].flags |= FIX_FLAGS.BREAK;
ordered.splice(Math.max(0, i), 1);
track.truncated = true;
}
for (let i = 1; i < ordered.length; i++) {
if (track.policy.accept && !track.policy.accept(ordered[i - 1], ordered[i]))
ordered[i].flags |= FIX_FLAGS.BREAK;
}
track.count = 0;
track.head = 0;
track.baseSeq += 128;
for (const fix of ordered) append(track, fix);
track.revision++;
track.bracket = 0;
}
export function correctHeight(track, seq, heightM) {
const i = seq - track.baseSeq;
if (i < 0 || i >= track.count || !Number.isFinite(heightM)) return false;
const o = address(track, i),
value = Math.fround(heightM);
if (track.storage.getFloat32(o + 24) === value) return false;
track.storage.setFloat32(o + 24, value);
track.storage.setUint32(
o + 40,
track.storage.getUint32(o + 40) | FIX_FLAGS.FLOOR,
);
track.revision++;
return true;
}
function anchoredWall(track, clocks) {
if (!Number.isFinite(track.wallAnchor)) {
track.wallAnchor = clocks.wallNowMs;
track.monoAnchor = clocks.monoNowMs;
}
return track.wallAnchor + Math.max(0, clocks.monoNowMs - track.monoAnchor);
}
/** Stable numeric fields avoid dictionary properties and boxed doubles in hot samples. */
export function createSample() {
return {
displayT: NaN,
revision: 0,
nextWakeMonoMs: Infinity,
phase: 'buffering',
motion: 'unknown',
fromSeq: -1,
toSeq: -1,
lat: NaN,
lon: NaN,
heightM: NaN,
segmentCourseDeg: NaN,
segmentSpeedMps: NaN,
fraction: NaN,
fromT: NaN,
toT: NaN,
nextMotionT: Infinity,
latestReportAgeMs: NaN,
actualDelayMs: NaN,
};
}
/** Sample an explicit report time into caller-owned storage. */
export function sampleAt(track, displayTimeMs, out) {
out.displayT = displayTimeMs;
return sampleCurrent(track, out);
}
/** The frame path keeps its changing double in storage across this call. */
function sampleCurrent(track, out) {
const sampleTime = out.displayT;
out.revision = track.revision;
out.nextWakeMonoMs = Infinity;
out.phase = track.phase;
out.motion = 'unknown';
out.fromSeq = -1;
out.toSeq = -1;
out.lat = NaN;
out.lon = NaN;
out.heightM = NaN;
out.segmentCourseDeg = NaN;
out.segmentSpeedMps = 0;
if (!track.count) return out;
let i = Math.min(track.bracket, track.count - 1);
if (timeAt(track, i) > sampleTime) i = 0;
while (i + 1 < track.count && timeAt(track, i + 1) <= sampleTime) i++;
track.bracket = i;
const a = readFix(track, i, track.from);
const j = sampleTime < a.t ? i : Math.min(i + 1, track.count - 1);
const b = readFix(track, j, track.to);
const continuous =
i !== j && a.epoch === b.epoch && !(b.flags & FIX_FLAGS.BREAK);
out.fromSeq = a.seq;
out.toSeq = continuous ? b.seq : a.seq;
out.fraction = continuous
? Math.max(0, Math.min(1, (sampleTime - a.t) / (b.t - a.t)))
: 1;
out.fromT = a.t;
out.toT = continuous ? b.t : a.t;
if (
track.metricsRevision !== track.revision ||
track.metricsIndex !== i ||
track.metricsTo !== j
) {
const metres = continuous ? distance(a, b) : 0;
const metrics = track.metrics;
metrics.speed = continuous ? (metres * 1000) / (b.t - a.t) : 0;
metrics.course = NaN;
if (metres >= (track.policy.courseMinTravelM ?? 12)) {
metrics.course =
((Math.atan2(
(((b.lon - a.lon + 540) % 360) - 180) *
Math.cos((a.lat * Math.PI) / 180),
b.lat - a.lat,
) *
180) /
Math.PI +
360) %
360;
} else {
// Tiny displacement holds the last reliable course in this epoch.
// With no reliable displacement yet, use the earliest known bearing.
const p = track.metricsScratchA,
q = track.metricsScratchB;
for (let k = i; k >= 0; k--) {
readFix(track, k, q);
if (q.epoch !== a.epoch) break;
if (Number.isFinite(q.bearingDeg)) metrics.course = q.bearingDeg;
if (k === 0 || q.flags & FIX_FLAGS.BREAK) continue;
readFix(track, k - 1, p);
if (
p.epoch === q.epoch &&
distance(p, q) >= (track.policy.courseMinTravelM ?? 12)
) {
metrics.course =
((Math.atan2(
(((q.lon - p.lon + 540) % 360) - 180) *
Math.cos((p.lat * Math.PI) / 180),
q.lat - p.lat,
) *
180) /
Math.PI +
360) %
360;
break;
}
}
}
metrics.nextMotionT = Infinity;
const p = track.metricsScratchA,
q = track.metricsScratchB;
for (let k = i; k + 1 < track.count; k++) {
readFix(track, k, p);
readFix(track, k + 1, q);
if (
p.lat !== q.lat ||
p.lon !== q.lon ||
p.epoch !== q.epoch ||
q.flags & FIX_FLAGS.BREAK
) {
metrics.nextMotionT =
p.epoch !== q.epoch || q.flags & FIX_FLAGS.BREAK ? q.t : p.t;
break;
}
}
track.metricsRevision = track.revision;
track.metricsIndex = i;
track.metricsTo = j;
}
const f = out.fraction;
out.lat = continuous ? a.lat + (b.lat - a.lat) * f : a.lat;
out.lon = continuous
? a.lon + (((b.lon - a.lon + 540) % 360) - 180) * f
: a.lon;
if (out.lon > 180) out.lon -= 360;
if (out.lon < -180) out.lon += 360;
out.heightM = continuous
? a.heightM + (b.heightM - a.heightM) * f
: a.heightM;
out.segmentCourseDeg = track.metrics.course;
out.segmentSpeedMps = track.metrics.speed;
out.motion = continuous
? track.metrics.speed > 0
? 'moving'
: 'stopped'
: 'unknown';
out.nextMotionT = track.metrics.nextMotionT;
out.latestReportAgeMs = Number.isFinite(track.wallAnchor)
? track.wallAnchor +
track.lastMono -
track.monoAnchor -
timeAt(track, track.count - 1)
: NaN;
out.actualDelayMs = Number.isFinite(track.wallAnchor)
? track.wallAnchor + track.lastMono - track.monoAnchor - sampleTime
: NaN;
return out;
}
export function advance(track, clocks, out) {
const wall = anchoredWall(track, clocks),
previousMono = track.lastMono;
const dt = Number.isFinite(previousMono)
? Math.max(0, clocks.monoNowMs - previousMono)
: 0;
track.lastMono = clocks.monoNowMs;
if (!track.count) return sampleAt(track, NaN, out);
const newest = timeAt(track, track.count - 1),
oldest = timeAt(track, 0);
const ceiling = Math.min(newest, wall - track.targetDelayMs + track.offset);
const delayBlocked =
track.offset === 0 &&
track.phase !== 'playing' &&
ceiling < track.displayT &&
track.displayT < newest;
if (!Number.isFinite(track.displayT))
track.displayT = Math.min(
newest,
wall - track.targetDelayMs + track.offset,
);
else if (
track.offset === 0 &&
track.rate !== 0 &&
(ceiling - track.displayT > 90_000 ||
(track.truncated && track.displayT < oldest))
) {
track.resetReason =
ceiling - track.displayT > 90_000 ? 'backlog' : 'unavailable-bracket';
track.displayT = ceiling;
track.resets++;
} else if (track.rate !== 0) {
// While playing, finish the active segment at 1x even if lag grows.
const activeCeiling =
track.offset < 0 || track.phase === 'playing' ? newest : ceiling;
let next = track.displayT + dt * track.rate;
if (track.phase === 'held' && track.resumePending) {
const sinceReceipt = Number.isFinite(track.acceptedMono)
? Math.max(0, clocks.monoNowMs - track.acceptedMono)
: 0;
next = track.displayT + Math.min(dt, sinceReceipt) * track.rate;
}
track.displayT = Math.max(track.displayT, Math.min(next, activeCeiling));
}
track.phase =
track.rate === 0
? 'paused'
: track.displayT < oldest || delayBlocked
? 'buffering'
: track.displayT >= newest
? 'held'
: 'playing';
track.resumePending = false;
out.displayT = track.displayT;
sampleCurrent(track, out);
if (out.motion !== 'moving' || track.phase !== 'playing') {
const boundary = Math.max(oldest, out.nextMotionT);
if (
Number.isFinite(boundary) &&
boundary > track.displayT &&
track.rate > 0
)
out.nextWakeMonoMs =
clocks.monoNowMs + (boundary - track.displayT) / track.rate;
}
if (delayBlocked && track.rate > 0)
out.nextWakeMonoMs =
clocks.monoNowMs + Math.max(1, track.displayT - ceiling);
if (out.latestReportAgeMs > (track.policy.staleMs ?? 90_000))
out.motion = 'stale';
return out;
}
export function seek(track, displayTimeMs, clocks) {
if (!Number.isFinite(displayTimeMs))
throw new TypeError('A seek needs a finite time');
anchoredWall(track, clocks);
track.displayT = displayTimeMs;
track.offset = -1;
track.rate = 0;
track.phase = 'paused';
track.lastMono = clocks.monoNowMs;
track.bracket = 0;
track.resets++;
track.resetReason = 'seek';
}
export function setTimeOffsetMs(track, offset, clocks) {
if (!Number.isFinite(offset) || offset > 0)
throw new RangeError('Offset must be zero or negative');
if (Number.isFinite(track.displayT)) {
track.resets++;
track.resetReason = 'time-offset';
}
track.offset = offset;
track.rate = 1;
track.displayT = anchoredWall(track, clocks) - track.targetDelayMs + offset;
track.lastMono = clocks.monoNowMs;
track.phase = 'buffering';
track.bracket = 0;
}
export function setRate(track, rate, clocks) {
if (!Number.isFinite(rate) || rate < 0 || rate > 16)
throw new RangeError('Rate must be in [0, 16]');
if (track.offset === 0 && rate !== 0 && rate !== 1)
throw new RangeError('Live playback uses 1x or hold');
track.rate = rate;
track.lastMono = clocks.monoNowMs;
track.phase = rate === 0 ? 'paused' : 'buffering';
}
+302
View File
@@ -0,0 +1,302 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createTrack,
createLagReservoir,
createHistoryBudget,
insertFix,
readFix,
advance,
sampleAt,
seek,
setRate,
setTimeOffsetMs,
mergeHistory,
correctHeight,
trimTrack,
destroyTrack,
FIX_BYTES,
FIX_FLAGS,
} from './contactPlayback.js';
const fix = (t, metres = t / 100) => ({
t,
lat: 42 + metres / 111320,
lon: -71,
bearingDeg: 0,
});
const clocks = (t) => ({ wallNowMs: t, monoNowMs: t });
const put = (track, t, metres, receipt = t) =>
insertFix(track, fix(t, metres), { receivedAt: receipt, wallNowMs: receipt });
test('10 s reports / 15 s polls and a 6 m crawl move at report speed on ordinary frames', () => {
for (const speed of [10, 0.6]) {
const track = createTrack(),
out = {};
let prior = null,
moving = 0,
pollJumps = 0;
for (let now = 5000; now <= 180000; now += 16) {
if (
!prior ||
Math.floor((now - 5000) / 15000) !== Math.floor((now - 5016) / 15000)
) {
const t = Math.floor((now - 5000) / 10000) * 10000;
put(track, t, (t / 1000) * speed, now);
}
advance(track, clocks(now), out);
if (prior && out.displayT >= 0 && prior.displayT >= 0) {
const d = (out.lat - prior.lat) * 111320;
const dt = out.displayT - prior.displayT;
assert.ok(dt >= 0 && dt <= 16.0001);
if (dt > 0 && d > 0) {
assert.ok(Math.abs(d / (dt / 1000) - speed) < speed * 0.02);
moving++;
}
if (d > speed * 0.0161) pollJumps++;
}
prior = { ...out };
}
assert.ok(
moving > 5000,
`non-vacuous ${speed} m/s trace: ${moving} moving frames`,
);
assert.equal(pollJumps, 0);
}
});
test('stationary observations survive, schedule departure, and distinguish underflow', () => {
const track = createTrack(),
out = {};
put(track, 0, 0);
put(track, 15000, 0);
put(track, 30000, 6);
setTimeOffsetMs(track, 0, clocks(35000));
advance(track, clocks(35000), out);
assert.equal(out.motion, 'stopped');
assert.equal(out.nextWakeMonoMs, 40000);
advance(track, clocks(40000), out);
assert.equal(out.motion, 'moving');
advance(track, clocks(55000), out);
assert.equal(out.phase, 'held');
assert.equal(out.segmentSpeedMps, 0);
});
test('same-time conflicts and invalid coordinates never make zero-duration segments', () => {
const track = createTrack();
put(track, 0, 0);
assert.equal(put(track, 0, 0).reason, 'repeat');
assert.equal(put(track, 0, 1).reason, 'conflict');
for (const value of [
{ t: 1, lat: 91, lon: 0 },
{ t: 1, lat: 0, lon: NaN },
{ t: -1, lat: 0, lon: 0 },
])
assert.equal(insertFix(track, value).accepted, false);
assert.equal(track.count, 1);
assert.equal(put(track, 15000, 0).accepted, true);
});
test('ring wrap retains 15 minutes and pins an active bracket under capacity pressure', () => {
const track = createTrack({ capacity: 8 });
for (let i = 0; i < 8; i++) put(track, i * 10000, i);
seek(track, 5000, clocks(80000));
for (let i = 8; i < 30; i++) put(track, i * 10000, i);
const sample = sampleAt(track, 5000, {});
assert.equal(sample.fromT, 0);
assert.equal(sample.toT, 10000);
assert.equal(track.count, 8);
assert.equal(track.storage.byteLength, 8 * FIX_BYTES);
assert.equal(track.truncated, true);
assert.ok(readFix(track, 2).flags & FIX_FLAGS.BREAK);
seek(track, 250000, clocks(300000));
trimTrack(track, 300000, 2);
assert.ok(track.count <= 5);
});
test('backward seek and history merge leave clock and live health alone', () => {
const track = createTrack(),
out = {};
put(track, 30000, 30);
put(track, 45000, 45);
seek(track, 37500, clocks(80000));
const health = track.acceptedAt;
mergeHistory(track, [fix(0, 0), fix(15000, 15), fix(30000, 999)]);
assert.equal(track.displayT, 37500);
assert.equal(track.acceptedAt, health);
assert.equal(readFix(track, 2).lat, fix(30000, 30).lat);
seek(track, 7500, clocks(80000));
advance(track, clocks(90000), out);
assert.equal(out.displayT, 7500);
assert.equal(out.phase, 'paused');
setRate(track, 1, clocks(90000));
advance(track, clocks(91000), out);
assert.equal(out.displayT, 8500);
});
test('system-clock changes do not alter animation elapsed time', () => {
const track = createTrack(),
out = {};
put(track, 0, 0);
put(track, 60000, 600);
advance(track, clocks(60000), out);
const before = out.displayT;
advance(track, { wallNowMs: 999999999, monoNowMs: 60016 }, out);
assert.equal(out.displayT - before, 16);
setTimeOffsetMs(track, -10000, clocks(60016));
assert.equal(track.resetReason, 'time-offset');
assert.equal(track.resets, 1);
});
test('a 90 s outage holds, then resumes without a sprint; backlog reset adds no second delay', () => {
const track = createTrack(),
out = {};
put(track, 0, 0);
put(track, 15000, 15);
for (let t = 25000; t <= 120000; t += 100) advance(track, clocks(t), out);
assert.equal(out.displayT, 15000);
put(track, 105000, 105, 120000);
advance(track, clocks(120100), out);
assert.ok(out.displayT - 15000 <= 100);
track.targetDelayMs = 25000;
put(track, 300000, 300, 300000);
track.targetDelayMs = 25000;
advance(track, clocks(300000), out);
assert.equal(track.resets, 1);
assert.equal(track.resetReason, 'backlog');
assert.equal(out.displayT, 275000);
});
test('lag measures receipt of current minus report of previous and ignores cached deliveries', () => {
const feedLag = createLagReservoir(),
track = createTrack({ policy: { feedLag } });
put(track, 0, 0, 5000);
put(track, 10000, 100, 20000);
assert.equal(track.lag.values[0], 20000);
put(track, 10000, 100, 80000);
assert.equal(track.lag.count, 1);
put(track, 20000, 200, 50000);
assert.equal(track.targetDelayMs, 45000);
});
test('displayed bearing never reads a future fix; height corrections revise typed storage', () => {
const track = createTrack();
insertFix(track, { ...fix(0, 0), bearingDeg: 90 });
insertFix(track, { ...fix(15000, 6), bearingDeg: 270 });
const out = sampleAt(track, 7500, {});
assert.equal(out.segmentCourseDeg, 90);
assert.ok(Number.isNaN(out.heightM));
correctHeight(track, out.fromSeq, 11.5);
correctHeight(track, out.toSeq, 21.5);
assert.equal(sampleAt(track, 7500, out).heightM, 16.5);
});
test('allocation budget is hard and destruction returns payload bytes', () => {
const budget = createHistoryBudget(48 * 16),
tracks = Array.from({ length: 3 }, () => createTrack({ budget }));
for (const track of tracks)
for (let t = 0; t < 100; t++) put(track, t * 1000, t);
assert.ok(budget.allocatedBytes <= budget.maxBytes);
for (const track of tracks) destroyTrack(track);
assert.equal(budget.allocatedBytes, 0);
});
test('tiny displacement holds a preceding reliable course instead of a changed bearing', () => {
const track = createTrack();
insertFix(track, { ...fix(0, 0), bearingDeg: 90 });
insertFix(track, { ...fix(15000, 100), bearingDeg: 270 });
insertFix(track, { ...fix(30000, 106), bearingDeg: 180 });
assert.equal(sampleAt(track, 20000, {}).segmentCourseDeg, 0);
});
test('an epoch gap wakes at its far boundary without drawing a connecting segment', () => {
const track = createTrack(),
out = {};
insertFix(track, { ...fix(0, 0), epoch: 1 });
insertFix(track, { ...fix(30000, 100), epoch: 2 });
advance(track, clocks(40000), out);
assert.equal(out.segmentSpeedMps, 0);
assert.equal(out.nextWakeMonoMs, 65000);
});
test('increased lag is adopted while rebuffering, with one monotonic wake and no slow playback', () => {
const track = createTrack(),
out = {};
put(track, 0, 0);
put(track, 15000, 15);
for (let now = 25000; now <= 120000; now += 100)
advance(track, clocks(now), out);
insertFix(track, fix(105000, 105), {
receivedAt: 120000,
wallNowMs: 120000,
monoNowMs: 120000,
});
advance(track, clocks(120100), out);
assert.equal(out.displayT, 15000);
assert.equal(out.phase, 'buffering');
assert.equal(out.nextWakeMonoMs, 125000);
advance(track, { wallNowMs: -9999999, monoNowMs: 125000 }, out);
assert.equal(out.displayT, 15000);
advance(track, { wallNowMs: 9999999, monoNowMs: 125016 }, out);
assert.equal(out.displayT, 15016);
});
test('capacity rejection leaves both lag reservoirs and clock policy unchanged', () => {
const feedLag = createLagReservoir();
const track = createTrack({ capacity: 2, policy: { feedLag } });
put(track, 0, 0);
put(track, 10000, 10);
seek(track, 5000, clocks(10000));
const policyState = () =>
structuredClone({
lag: track.lag,
feedLag,
targetDelayMs: track.targetDelayMs,
acceptedAt: track.acceptedAt,
acceptedMono: track.acceptedMono,
resumePending: track.resumePending,
displayT: track.displayT,
wallAnchor: track.wallAnchor,
monoAnchor: track.monoAnchor,
resetReason: track.resetReason,
resets: track.resets,
});
const before = policyState();
assert.deepEqual(put(track, 20000, 20, 300000), {
accepted: false,
reason: 'capacity',
});
assert.deepEqual(policyState(), before);
});
test('sampleAt writes the supplied output without replacing nested scratch', () => {
const track = createTrack();
put(track, 0, 0);
put(track, 15000, 150);
const out = {},
from = track.from,
to = track.to,
metrics = track.metrics;
for (let i = 0; i < 10000; i++) {
assert.equal(sampleAt(track, i, out), out);
assert.equal(track.from, from);
assert.equal(track.to, to);
assert.equal(track.metrics, metrics);
}
});
test('backfill pins the live bracket and quarantines outliers on either side', () => {
const track = createTrack({
policy: {
accept: (a, b) =>
Math.abs(b.lat - a.lat) * 111320 <= ((b.t - a.t) / 1000) * 36,
},
});
put(track, 10000, 0);
put(track, 25000, 100);
seek(track, 17500, clocks(40000));
const before = { ...sampleAt(track, 17500, {}) };
mergeHistory(track, [fix(0, -111320), fix(17500, 25), fix(40000, 111320)]);
const after = sampleAt(track, 17500, {});
assert.equal(track.count, 2);
assert.equal(after.fromT, before.fromT);
assert.equal(after.toT, before.toT);
assert.equal(after.lat, before.lat);
mergeHistory(track, [fix(40000, 111320), fix(55000, 111420)]);
assert.equal(
track.count,
4,
'two coherent replacement fixes can be retained',
);
assert.ok(readFix(track, 2).flags & FIX_FLAGS.BREAK);
assert.equal(sampleAt(track, 30000, {}).lat, fix(25000, 100).lat);
});
+229
View File
@@ -0,0 +1,229 @@
import * as Cesium from 'cesium';
const ALPHA_STOPS = [
[0, 0.8],
[120000, 0.45],
[600000, 0.2],
[900000, 0.08],
];
export function trailAlpha(ageMs) {
const stops = ALPHA_STOPS;
for (let i = 1; i < stops.length; i++) {
if (ageMs === stops[i][0]) return stops[i][1];
if (ageMs < stops[i][0]) {
const [a, x] = stops[i - 1],
[b, y] = stops[i];
return x + ((y - x) * Math.max(0, ageMs - a)) / (b - a);
}
}
return 0.08;
}
/** One static history batch and one frequently updated head. Never entities. */
export function createContactTrailRenderer(scene) {
const heads = scene.primitives.add(new Cesium.PolylineCollection());
const backing = heads.add({
positions: [],
width: 4,
show: false,
material: Cesium.Material.fromType('Color', {
color: new Cesium.Color(0.02, 0.03, 0.05, 0.8),
}),
});
const head = heads.add({
positions: [],
width: 2,
show: false,
material: Cesium.Material.fromType('Color', {
color: Cesium.Color.WHITE.clone(),
}),
});
let body = null,
segments = [],
revision = -1,
visible = true,
style = '#5EF08A';
let lastSecond = -1,
completed = -1,
active = null;
const styleColor = Cesium.Color.fromCssColorString(style);
const attributeIds = [];
const color = new Cesium.Color(),
endpoint = new Cesium.Cartesian3();
const headPositions = [new Cesium.Cartesian3(), endpoint];
let rebuilds = 0;
function tint(alpha, dark = false) {
if (dark) {
color.red = 0.02;
color.green = 0.03;
color.blue = 0.05;
} else Cesium.Color.clone(styleColor, color);
color.alpha = alpha;
return color;
}
function replaceHistory(next) {
if (next.revision === revision) return;
revision = next.revision;
segments = next.segments;
completed = -1;
lastSecond = -1;
active = null;
if (body) scene.primitives.remove(body);
body = null;
const instances = [];
attributeIds.length = 0;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
attributeIds.push([`${i}:0`, `${i}:1`]);
if (segment.positions.length < 2) continue;
for (let lane = 0; lane < 2; lane++) {
instances.push(
new Cesium.GeometryInstance({
id: `${i}:${lane}`,
geometry: new Cesium.PolylineGeometry({
positions: segment.positions,
width: lane ? 2 : 4,
arcType: Cesium.ArcType.NONE,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
show: new Cesium.ShowGeometryInstanceAttribute(false),
},
}),
);
}
}
if (instances.length) {
const depthFailAppearance = new Cesium.PolylineColorAppearance({
translucent: true,
fragmentShaderSource:
'in vec4 v_color; void main() { out_FragColor = czm_gammaCorrect(vec4(v_color.rgb, v_color.a * 0.2)); }',
});
body = scene.primitives.add(
new Cesium.Primitive({
geometryInstances: instances,
appearance: new Cesium.PolylineColorAppearance({ translucent: true }),
depthFailAppearance,
allowPicking: false,
asynchronous: false,
show: visible,
}),
);
rebuilds++;
}
}
function setDisplaySample(sample, renderedPosition) {
if (!sample || !renderedPosition) {
head.show = false;
backing.show = false;
return;
}
const second = Math.floor(sample.displayT / 1000);
let lo = 0,
hi = segments.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (segments[mid].toT <= sample.displayT) lo = mid + 1;
else hi = mid;
}
const done = lo - 1;
const candidate = segments[lo];
const segment =
candidate &&
candidate.fromT <= sample.displayT &&
candidate.fromSeq === sample.fromSeq &&
candidate.toSeq === sample.toSeq
? candidate
: null;
if (body?.ready && done !== completed) {
for (
let i = Math.min(done, completed) + 1;
i <= Math.max(done, completed);
i++
) {
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
attributes.show[0] = i <= done ? 1 : 0;
attributes.show = attributes.show;
}
}
completed = done;
}
if (body?.ready && second !== lastSecond) {
for (let i = 0; i < segments.length; i++) {
const alpha = trailAlpha(sample.displayT - segments[i].toT);
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
attributes.color,
);
attributes.color = attributes.color;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
attributes.depthFailColor,
);
attributes.depthFailColor = attributes.depthFailColor;
}
}
lastSecond = second;
}
const show = visible && !!segment && sample.fraction < 1;
head.show = show;
backing.show = show;
if (!show) return;
if (active !== segment) {
active = segment;
headPositions[0] = segment.positions[0];
headPositions[1] = endpoint;
}
Cesium.Cartesian3.clone(renderedPosition, endpoint);
head.positions = headPositions;
backing.positions = headPositions;
Cesium.Color.clone(tint(0.8), head.material.uniforms.color);
}
return {
replaceHistory,
setDisplaySample,
setStyle(next) {
if (next === style) return;
style = next;
Cesium.Color.fromCssColorString(style, styleColor);
lastSecond = -1;
},
setVisible(next) {
visible = next;
heads.show = next;
if (body) body.show = next;
},
destroy() {
if (body) scene.primitives.remove(body);
scene.primitives.remove(heads);
body = null;
segments = [];
},
diagnostics() {
return {
revision,
rebuilds,
segments: segments.length,
body,
head,
backing,
entitiesAdded: 0,
};
},
};
}
+210
View File
@@ -0,0 +1,210 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createContactTrailRenderer,
trailAlpha,
} from './contactTrailRenderer.js';
function fixture(t) {
for (const key of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
]) {
const prior = globalThis[key];
globalThis[key] = class {};
t.after(() => {
if (prior === undefined) delete globalThis[key];
else globalThis[key] = prior;
});
}
const primitives = new Cesium.PrimitiveCollection();
t.after(() => primitives.destroy());
return { primitives };
}
test('body clips future subdivisions, head ends at exact marker, and frames retain geometry', (t) => {
const scene = fixture(t),
renderer = createContactTrailRenderer(scene);
const positions = [0, 1, 2].map((i) =>
Cesium.Cartesian3.fromDegrees(-71, 42 + i * 0.001, 11.5),
);
renderer.replaceHistory({
revision: 1,
segments: [
{
fromSeq: 0,
toSeq: 1,
fromT: 0,
toT: 10000,
positions: positions.slice(0, 2),
},
{
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 20000,
positions: positions.slice(1, 3),
},
],
});
const { body } = renderer.diagnostics();
assert.equal(body.allowPicking, false);
// The constructor defers this check until shader preparation. Run the real
// Cesium validator without WebGL, including a missing-attribute control.
const source = body.depthFailAppearance.vertexShaderSource;
body._batchTableAttributeIndices = { color: 0 };
assert.throws(
() => Cesium.Primitive._updateColorAttribute(body, source, true),
/depthFailColor/,
);
for (const instance of body.geometryInstances) {
assert.deepEqual(
instance.attributes.depthFailColor.value,
instance.attributes.color.value,
);
}
body._batchTableAttributeIndices = { color: 0, depthFailColor: 1 };
assert.doesNotThrow(() =>
Cesium.Primitive._updateColorAttribute(body, source, true),
);
const attributes = new Map(
body.geometryInstances.map((instance) => [
instance.id,
{
show: new Uint8Array([0]),
color: new Uint8Array(4),
depthFailColor: new Uint8Array(4),
},
]),
);
// Simulate Cesium's completed upload; exercise public attribute writes.
body._ready = true;
body.getGeometryInstanceAttributes = (id) => attributes.get(id);
const marker = Cesium.Cartesian3.lerp(
positions[1],
positions[2],
0.5,
new Cesium.Cartesian3(),
);
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
assert.deepEqual(
[...attributes.values()].map((a) => a.show[0]),
[1, 1, 0, 0],
);
for (const a of attributes.values())
assert.deepEqual(a.depthFailColor, a.color);
const result = renderer.diagnostics();
assert.equal(result.body, body);
assert.equal(result.rebuilds, 1);
assert.ok(Cesium.Cartesian3.equals(result.head.positions.at(-1), marker));
assert.equal(result.head.positions.length, 2);
renderer.setDisplaySample(
{ ...sample, displayT: 5000, fraction: 0.25 },
positions[0],
);
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
'rewind hides future geometry again',
);
renderer.destroy();
assert.equal(scene.primitives.length, 0);
});
test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(0), 0.8);
assert.equal(trailAlpha(120000), 0.45);
assert.equal(trailAlpha(600000), 0.2);
assert.equal(trailAlpha(900000), 0.08);
assert.ok(Math.abs(trailAlpha(60000) - 0.625) < 1e-10);
});
test('the maximum prepared body stays below the 2 MiB geometry budget', () => {
const geometry = Cesium.PolylineGeometry.createGeometry(
new Cesium.PolylineGeometry({
positions: [
Cesium.Cartesian3.fromDegrees(-71, 42, 11.5),
Cesium.Cartesian3.fromDegrees(-71, 42.0002, 11.5),
],
width: 2,
arcType: Cesium.ArcType.NONE,
vertexFormat: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
}),
);
const bytes =
Object.values(geometry.attributes).reduce(
(total, attribute) => total + (attribute?.values?.byteLength || 0),
0,
) + geometry.indices.byteLength;
assert.ok(bytes * 2 * 2047 < 2 * 1024 * 1024);
});
test('subdivision crossings only write the changed show range and age colors once per second', (t) => {
const renderer = createContactTrailRenderer(fixture(t));
const positions = [
Cesium.Cartesian3.fromDegrees(-71, 42),
Cesium.Cartesian3.fromDegrees(-71, 42.001),
];
renderer.replaceHistory({
revision: 1,
segments: Array.from({ length: 100 }, (_, i) => ({
fromSeq: 0,
toSeq: 1,
fromT: i * 500,
toT: (i + 1) * 500,
positions,
})),
});
const { body } = renderer.diagnostics();
const counts = { show: 0, color: 0, depthFailColor: 0 };
const attributes = new Map(
body.geometryInstances.map((instance) => {
const result = {};
for (const name of Object.keys(counts)) {
let value = instance.attributes[name].value;
Object.defineProperty(result, name, {
get: () => value,
set(next) {
value = next;
counts[name]++;
},
});
}
return [instance.id, result];
}),
);
body._ready = true;
body.getGeometryInstanceAttributes = (id) => attributes.get(id);
const display = (displayT) =>
renderer.setDisplaySample(
{ displayT, fromSeq: 0, toSeq: 1, fraction: 0.1 },
positions[0],
);
const reset = () => {
for (const name of Object.keys(counts)) counts[name] = 0;
};
display(100);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
reset();
display(600);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
reset();
display(100);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
'backward seek hides the completed range',
);
reset();
display(1100);
assert.deepEqual(counts, { show: 4, color: 200, depthFailColor: 200 });
reset();
display(1200);
assert.deepEqual(counts, { show: 0, color: 0, depthFailColor: 0 });
renderer.setStyle('#FF4538');
display(1200);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
for (const a of attributes.values())
assert.deepEqual(a.color, a.depthFailColor);
});
+23 -11
View File
@@ -48,7 +48,9 @@ export function selectEntityContext(entity) {
store.selectedEntityId = contextId;
store.selectedAt = Date.now();
const record = store.entities.get(contextId);
window.dispatchEvent(new CustomEvent('gev:entity-selected', { detail: record }));
window.dispatchEvent(
new CustomEvent('gev:entity-selected', { detail: record }),
);
return record;
}
@@ -78,7 +80,8 @@ export function selectTrackedSubjectContext(metadata) {
const store = getContextStore();
const id = String(metadata.id);
for (const [key, record] of store.entities) {
if (record?.layerId === metadata.layerId && key !== id) store.entities.delete(key);
if (record?.layerId === metadata.layerId && key !== id)
store.entities.delete(key);
}
// Reuse the existing carrier so a per-poll refresh does not churn identity.
const carrier = store.entities.get(id)?.entity || { __gevContextId: id };
@@ -146,16 +149,21 @@ export function getSelectedEntityContext({ dataManager = null } = {}) {
* rather than being deselected. Readouts that stay on screen hold their
* last-known values for an eviction and only tear down on a deliberate clear.
*/
export function clearSelectedEntityContextForLayer(layerId, { evicted = false } = {}) {
export function clearSelectedEntityContextForLayer(
layerId,
{ evicted = false } = {},
) {
const store = getContextStore();
if (!store.selectedEntityId) return;
const record = store.entities.get(store.selectedEntityId);
if (record?.layerId === layerId) {
store.selectedEntityId = null;
store.selectedAt = null;
window.dispatchEvent(new CustomEvent('gev:entity-selection-cleared', {
detail: { layerId, reason: evicted ? 'evicted' : 'deliberate' },
}));
window.dispatchEvent(
new CustomEvent('gev:entity-selection-cleared', {
detail: { layerId, reason: evicted ? 'evicted' : 'deliberate' },
}),
);
}
}
@@ -166,16 +174,19 @@ export function clearSelectedEntityContextForLayer(layerId, { evicted = false }
export function removeEntityContextsForLayer(layerId, { retainIds } = {}) {
const store = getContextStore();
for (const [id, record] of store.entities) {
if (record?.layerId === layerId && !retainIds?.has(id)) store.entities.delete(id);
if (record?.layerId === layerId && !retainIds?.has(id))
store.entities.delete(id);
}
if (store.selectedEntityId && !store.entities.has(store.selectedEntityId)) {
store.selectedEntityId = null;
store.selectedAt = null;
// A viewport refresh dropped the record out from under the selection —
// the user did not deselect anything.
window.dispatchEvent(new CustomEvent('gev:entity-selection-cleared', {
detail: { layerId, reason: 'evicted' },
}));
window.dispatchEvent(
new CustomEvent('gev:entity-selection-cleared', {
detail: { layerId, reason: 'evicted' },
}),
);
}
}
@@ -183,6 +194,7 @@ export function isContextRecordActive(record, dataManager = null) {
if (!record) return false;
if (record.entity?.show === false) return false;
if (record.dataSource && record.dataSource.show === false) return false;
if (dataManager && record.layerId && !dataManager.isEnabled(record.layerId)) return false;
if (dataManager && record.layerId && !dataManager.isEnabled(record.layerId))
return false;
return true;
}
+47
View File
@@ -183,6 +183,10 @@ export const DATA_CREDITS = [
'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">© OpenStreetMap contributors</a> (ODbL) · ' +
'<a href="https://www.openstreetmap.org/fixthemap" target="_blank" rel="noopener">fix the map</a>',
},
{
key: 'gtfs-rt',
html: 'Transit vehicles: operator GTFS-Realtime feeds (each operator is credited below when its vehicles are shown)',
},
{
key: 'radio-browser',
html:
@@ -287,6 +291,49 @@ export const NATURAL_EARTH_CREDIT = {
'<a href="https://www.naturalearthdata.com" target="_blank" rel="noopener">Natural Earth</a> (public domain)',
};
/**
* Per-feed transit credit, registered the first time that feed's vehicles
* render (see `src/data/transitFeeds.js` for the license of each).
* @param {{ id: string, attribution: string, license: string, licenseUrl: string }} feed
* @returns {{ key: string, html: string }}
*/
export function transitFeedCredit(feed) {
const escape = (text) =>
String(text)
.replaceAll('&', '&amp;')
.replaceAll('<', '&lt;')
.replaceAll('>', '&gt;')
.replaceAll('"', '&quot;');
return {
key: `transit-${feed.id}`,
html:
`Transit (${escape(feed.attribution)}): ` +
`<a href="${escape(feed.licenseUrl)}" target="_blank" rel="noopener">${escape(feed.license)}</a>`,
};
}
/** Registered when the Bhote Koshi event reconstruction activates. */
export const BHOTE_KOSHI_CREDIT = {
key: 'bhote-koshi-2026',
html:
'Bhote Koshi 2026 event imagery and derived reconstruction: ' +
'<a href="https://vantor.com/company/open-data-program" target="_blank" rel="noopener">Vantor Open Data</a> ' +
'and <a href="https://github.com/geo-pera/bhotekoshi-2026-reconstruction" target="_blank" rel="noopener">GeoPera</a> ' +
'(CC BY-NC 4.0); terrain © Re:Earth / Mapterhorn (CC BY 4.0)',
};
/** Registered when the scene-friendly Nepal incident locator activates. */
export const BHOTE_KOSHI_LOCATOR_CREDIT = {
key: 'bhote-koshi-locator',
html:
'Nepal administrative boundary and nearby-city locations: ' +
'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">© OpenStreetMap contributors</a> ' +
'(ODbL 1.0); incident-place anchors use an owner-curated, source-verified geolocation union; ' +
'flood corridor derived from the ' +
'<a href="https://github.com/geo-pera/bhotekoshi-2026-reconstruction/blob/main/vectors/river_centerline.geojson" target="_blank" rel="noopener">GeoPera river centerline</a> ' +
'(CC BY-NC 4.0)',
};
/** @type {Set<string>} Keys of dynamic credits already registered this session. */
const _dynamicCreditKeys = new Set();
+240 -70
View File
@@ -1,3 +1,4 @@
import { paintTransitBracket } from './detectionDraw.js';
import * as Cesium from 'cesium';
import { governorRequestRender } from '../renderGovernor.js';
import {
@@ -10,6 +11,7 @@ import {
import {
acquireAlpha,
appendCornerBracket,
appendTransitBracket,
resolveTier,
measureTrackLabel,
nearFarScale,
@@ -217,6 +219,8 @@ let _hostLane = null;
* @type {{surface:HTMLCanvasElement|null,setActive:Function,requestPaint:Function,unregister:Function}|null}
*/
let _calloutLane = null;
let _transitBracketPaths = new Map();
let _transitBracketAlpha = 1;
/**
* Callouts solved by the sensor lane this frame, replayed by the callout lane.
* The array and its rows are POOLED — `_calloutCount` is the live length — so a
@@ -275,7 +279,10 @@ let _cockpitModeListener = null;
*/
export function initDetection(viewer, layers, onModeChange) {
if (_cockpitModeListener && typeof window !== 'undefined') {
window.removeEventListener('gev:cockpit-mode-changed', _cockpitModeListener);
window.removeEventListener(
'gev:cockpit-mode-changed',
_cockpitModeListener,
);
}
_hostLane?.unregister?.();
_calloutLane?.unregister?.();
@@ -319,7 +326,10 @@ export function initDetection(viewer, layers, onModeChange) {
/** Release the host lane and all retained detection runtime state. */
export function destroyDetection() {
if (_cockpitModeListener && typeof window !== 'undefined') {
window.removeEventListener('gev:cockpit-mode-changed', _cockpitModeListener);
window.removeEventListener(
'gev:cockpit-mode-changed',
_cockpitModeListener,
);
}
_cockpitModeListener = null;
_cockpitActive = false;
@@ -329,6 +339,7 @@ export function destroyDetection() {
_hostLane = null;
_calloutLane?.unregister?.();
_calloutLane = null;
_transitBracketPaths.clear();
_calloutCount = 0;
_viewer = null;
_layers = [];
@@ -392,7 +403,8 @@ export function setMode(modeLabel) {
_mode = MODE_OFF;
} else {
const requestedDensity = defaultDensityForProfile(target);
if (profileForDensity(_densityPct) !== target) _densityPct = requestedDensity;
if (profileForDensity(_densityPct) !== target)
_densityPct = requestedDensity;
_mode = _modeForDensity();
_lastNonOffMode = _mode;
}
@@ -457,7 +469,10 @@ export function isDetectionSuspended() {
*/
export function setDetectionTuning(options = {}) {
let modeChanged = false;
if (typeof options.densityPct === 'number' && Number.isFinite(options.densityPct)) {
if (
typeof options.densityPct === 'number' &&
Number.isFinite(options.densityPct)
) {
const nextDensity = canonicalizeDensity(options.densityPct);
if (nextDensity !== _densityPct) {
_densityPct = nextDensity;
@@ -472,7 +487,10 @@ export function setDetectionTuning(options = {}) {
}
}
if (options.allocationStrategy != null) {
const nextStrategy = normalizeAllocationStrategy(options.allocationStrategy, _allocationStrategy);
const nextStrategy = normalizeAllocationStrategy(
options.allocationStrategy,
_allocationStrategy,
);
if (nextStrategy !== _allocationStrategy) {
_allocationStrategy = nextStrategy;
_labelSolveDirty = true;
@@ -517,7 +535,14 @@ export function markDetectionSourcesChanged(reason = 'sources-changed') {
/** Read-only diagnostics for unit/browser QA. */
export function getDetectionDiagnostics() {
return _lastDiagnostics ? JSON.parse(JSON.stringify(_lastDiagnostics)) : null;
if (!_lastDiagnostics) return null;
const result = JSON.parse(JSON.stringify(_lastDiagnostics));
// Readback only: expose painted plates so pixel QA can exclude occluded
// sprites/strokes. Nothing is copied on the production paint path.
result.calloutRects = _calloutPool
.slice(0, _calloutCount)
.map(({ x, y, w, h, alpha }) => ({ x, y, w, h, alpha }));
return result;
}
function _publishDiagnostics() {
@@ -525,19 +550,30 @@ function _publishDiagnostics() {
const dataset = _hostCanvas.dataset;
dataset.profile = _lastDiagnostics.profile || 'OFF';
dataset.densityPct = String(_lastDiagnostics.densityPct ?? _densityPct);
dataset.allocationStrategy = _lastDiagnostics.allocationStrategy || _allocationStrategy;
dataset.allocationStrategy =
_lastDiagnostics.allocationStrategy || _allocationStrategy;
dataset.solveRevision = String(_lastDiagnostics.solveRevision ?? 0);
dataset.collectiveLabelBudget = String(_lastDiagnostics.collectiveLabelBudget ?? 0);
dataset.collectiveLabelBudget = String(
_lastDiagnostics.collectiveLabelBudget ?? 0,
);
dataset.labelsByLayer = JSON.stringify(_lastDiagnostics.labelsByLayer || {});
dataset.entitlementByLayer = JSON.stringify(_lastDiagnostics.entitlementByLayer || {});
dataset.entitlementByLayer = JSON.stringify(
_lastDiagnostics.entitlementByLayer || {},
);
dataset.labeledKeys = JSON.stringify(_lastDiagnostics.labeledKeys || []);
dataset.labelAlphaByKey = JSON.stringify(_lastDiagnostics.labelAlphaByKey || {});
dataset.bracketOpacityCounts = JSON.stringify(_lastDiagnostics.bracketOpacityCounts || {});
dataset.labelAlphaByKey = JSON.stringify(
_lastDiagnostics.labelAlphaByKey || {},
);
dataset.bracketOpacityCounts = JSON.stringify(
_lastDiagnostics.bracketOpacityCounts || {},
);
dataset.keyholeRadius = String(_lastDiagnostics.keyholeRadius ?? 0);
dataset.keyholeFeatherPx = String(_lastDiagnostics.keyholeFeatherPx ?? 0);
dataset.demandByLayer = JSON.stringify(_lastDiagnostics.demandByLayer || {});
dataset.cohortByLayer = JSON.stringify(_lastDiagnostics.cohortByLayer || {});
dataset.placementBuildCount = String(_lastDiagnostics.placementBuildCount ?? 0);
dataset.placementBuildCount = String(
_lastDiagnostics.placementBuildCount ?? 0,
);
dataset.observationCount = String(_lastDiagnostics.observationCount ?? 0);
dataset.selectedCount = String(_lastDiagnostics.selectedCount ?? 0);
dataset.fadingCount = String(_lastDiagnostics.fadingCount ?? 0);
@@ -622,7 +658,11 @@ function _applyModeState() {
_labelArbiter.clear();
_lastLabelSolveAt = 0;
_labelSolveDirty = true;
_lastSolveSnapshot = { demandByLayer: {}, cohortByLayer: {}, cohortCount: 0 };
_lastSolveSnapshot = {
demandByLayer: {},
cohortByLayer: {},
cohortCount: 0,
};
} else {
_enableTime = _nowMs(); // restart the subtle fade-in on (re)activation
_syncSurfaceVisibility();
@@ -655,8 +695,10 @@ function _shouldPaintDetectionLane(frame) {
});
if (decision.skip) {
_throttleSkipCount++;
if (_lastDiagnostics) _lastDiagnostics.throttleSkipCount = _throttleSkipCount;
if (decision.requestFollowUp) governorRequestRender('detection-paint-skipped');
if (_lastDiagnostics)
_lastDiagnostics.throttleSkipCount = _throttleSkipCount;
if (decision.requestFollowUp)
governorRequestRender('detection-paint-skipped');
return false;
}
return true;
@@ -677,8 +719,13 @@ function _paintDetectionLane(frame) {
_labelSolveDirty = true;
}
const start = performance.now();
const result = _drawOverlay(frame)
|| { didSolve: false, solveMs: 0, fadingCount: 0, animatingCount: 0, solvePending: false };
const result = _drawOverlay(frame) || {
didSolve: false,
solveMs: 0,
fadingCount: 0,
animatingCount: 0,
solvePending: false,
};
_lastRenderMs = performance.now() - start;
_lastSolveMs = result.solveMs || 0;
_lastPaintMs = Math.max(0, _lastRenderMs - _lastSolveMs);
@@ -695,17 +742,19 @@ function _paintDetectionLane(frame) {
// exactly what makes it safe where the old blanket hold was not. On a parked
// scene with nothing animating it asks for nothing, and the governor stays
// idle. See `detectionRenderDemand.js`.
if (detectionNeedsFollowUpFrame({
active: _mode !== MODE_OFF && !_suspended,
// The frame's OWN timestamp, not a fresh sample — re-reading the clock here
// is what dropped the terminal frame of a fade (paint at 219 ms, policy at
// 220 ms, and the settled alpha never painted).
nowMs: Number.isFinite(frame.timestamp) ? frame.timestamp : _nowMs(),
enabledAtMs: _enableTime,
fadeMs: FADE_MS,
animatingLabelCount: result.animatingCount || 0,
solvePending: result.solvePending === true,
})) {
if (
detectionNeedsFollowUpFrame({
active: _mode !== MODE_OFF && !_suspended,
// The frame's OWN timestamp, not a fresh sample — re-reading the clock here
// is what dropped the terminal frame of a fade (paint at 219 ms, policy at
// 220 ms, and the settled alpha never painted).
nowMs: Number.isFinite(frame.timestamp) ? frame.timestamp : _nowMs(),
enabledAtMs: _enableTime,
fadeMs: FADE_MS,
animatingLabelCount: result.animatingCount || 0,
solvePending: result.solvePending === true,
})
) {
governorRequestRender('detection-animation');
}
}
@@ -794,7 +843,8 @@ function _drawModeBanner(visibleCount, sampledCount) {
if (!_debugBanner) return;
const mode = MODE_LABELS[_mode];
const paused = _suspended ? ` PAUSED:${_suspendReason || 'transition'}` : '';
const allocation = _allocationStrategy === ALLOCATION_ELASTIC ? 'ELASTIC' : 'WEIGHTED';
const allocation =
_allocationStrategy === ALLOCATION_ELASTIC ? 'ELASTIC' : 'WEIGHTED';
const text = `${mode} VIS:${visibleCount} SRC:${sampledCount} DENS:${_densityPct}% ${allocation} ${_lastRenderMs.toFixed(1)}ms${paused}`;
_ctx.fillStyle = _theme.labelBg;
_ctx.fillRect(12, 12, Math.max(180, _ctx.measureText(text).width + 12), 16);
@@ -890,16 +940,27 @@ function _buildLabelPlacements(
const placements = [];
for (const placement of raw) {
const { cardX, cardY } = placement;
if (cardX < margin || cardY < margin || cardX + card.w > width - margin || cardY + card.h > height - margin) {
if (
cardX < margin ||
cardY < margin ||
cardX + card.w > width - margin ||
cardY + card.h > height - margin
) {
continue;
}
const cardRect = { x: cardX, y: cardY, w: card.w, h: card.h };
if (rectIntersectsAny(cardRect, occlusionRects)) continue;
const leadToX = placement.leadToSide.endsWith('E') ? cardX + card.w : cardX;
const leadToY = placement.leadToSide.startsWith('S') ? cardY + card.h : cardY;
const leadToY = placement.leadToSide.startsWith('S')
? cardY + card.h
: cardY;
const centerX = cardX + card.w * 0.5;
const centerY = cardY + card.h * 0.5;
const radialAlpha = keyholeLabelAlphaFromGeometry(centerX, centerY, keyhole);
const radialAlpha = keyholeLabelAlphaFromGeometry(
centerX,
centerY,
keyhole,
);
if (radialAlpha <= 0) continue;
placements.push({
...placement,
@@ -930,18 +991,37 @@ function _buildLabelPlacements(
*/
function _stashCallout(entry, acquireFade, keyhole) {
const { candidate, placement, temporalAlpha } = entry;
const radialAlpha = keyholeLabelAlphaFromGeometry(placement.centerX, placement.centerY, keyhole);
const radialAlpha = keyholeLabelAlphaFromGeometry(
placement.centerX,
placement.centerY,
keyhole,
);
const alpha = acquireFade * temporalAlpha * radialAlpha;
if (alpha <= 0.001) return;
let row = _calloutPool[_calloutCount];
if (!row) {
row = {
x: 0, y: 0, w: 0, h: 0,
primaryX: 0, microX: 0, baseline: 0,
leadFromX: 0, leadFromY: 0, leadToX: 0, leadToY: 0,
plate: '', plateScale: 1, accent: '', label: '', primary: '', micro: '',
font: FONT, microFont: MICRO_FONT, alpha: 1,
x: 0,
y: 0,
w: 0,
h: 0,
primaryX: 0,
microX: 0,
baseline: 0,
leadFromX: 0,
leadFromY: 0,
leadToX: 0,
leadToY: 0,
plate: '',
plateScale: 1,
accent: '',
label: '',
primary: '',
micro: '',
font: FONT,
microFont: MICRO_FONT,
alpha: 1,
};
_calloutPool[_calloutCount] = row;
}
@@ -981,9 +1061,20 @@ function _stashCallout(entry, acquireFade, keyhole) {
* @param {Object} frame Host paint frame.
*/
function _paintCalloutLane(frame) {
if (_mode === MODE_OFF || _suspended || _calloutCount === 0) return;
if (_mode === MODE_OFF || _suspended) return;
const ctx = frame.ctx;
if (!ctx) return;
for (const bands of _transitBracketPaths.values()) {
for (const entry of bands) {
if (entry)
paintTransitBracket(
ctx,
entry.path,
entry.color,
entry.alpha * _transitBracketAlpha,
);
}
}
ctx.textAlign = 'left';
ctx.textBaseline = 'alphabetic';
for (let i = 0; i < _calloutCount; i++) {
@@ -1006,7 +1097,14 @@ function _plateScaleForBackdrop(skyFactor) {
}
/** Materialize one bounded rich-callout candidate for the existing arbiter. */
function _materializeCandidate(obj, width, height, keyhole, occlusionRects, cameraPosition) {
function _materializeCandidate(
obj,
width,
height,
keyhole,
occlusionRects,
cameraPosition,
) {
const primary = obj._candidatePrimary;
const micro = obj._candidateMicro;
const card = measureTrackLabel(primary, micro, _charWidth);
@@ -1027,7 +1125,10 @@ function _materializeCandidate(obj, width, height, keyhole, occlusionRects, came
for (const placement of placements) {
centerDistance = Math.min(
centerDistance,
Math.hypot(placement.centerX - keyhole.centerX, placement.centerY - keyhole.centerY),
Math.hypot(
placement.centerX - keyhole.centerX,
placement.centerY - keyhole.centerY,
),
);
keyholeAlpha = Math.max(keyholeAlpha, placement.keyholeAlpha);
}
@@ -1048,7 +1149,9 @@ function _materializeCandidate(obj, width, height, keyhole, occlusionRects, came
// Costed here rather than in the object sweep: the sweep walks every
// observation in view, while this runs only for callouts that actually
// placed — a budgeted handful per frame.
plateScale: _plateScaleForBackdrop(skyBackdropFactor(cameraPosition, obj.position)),
plateScale: _plateScaleForBackdrop(
skyBackdropFactor(cameraPosition, obj.position),
),
primary,
micro,
hasMicro: card.hasMicro,
@@ -1061,9 +1164,16 @@ function _materializeCandidate(obj, width, height, keyhole, occlusionRects, came
* for a bounded cohort on solve ticks.
*/
function _drawOverlay(frame) {
_transitBracketPaths.clear();
const { width, height } = frame;
if (!_ctx || width <= 0 || height <= 0) {
return { didSolve: false, solveMs: 0, fadingCount: 0, animatingCount: 0, solvePending: false };
return {
didSolve: false,
solveMs: 0,
fadingCount: 0,
animatingCount: 0,
solvePending: false,
};
}
// ONE timestamp per frame, monotonic, shared with the demand policy below and
@@ -1071,12 +1181,16 @@ function _drawOverlay(frame) {
// animation's final state is the same frame that ends its demand.
const now = Number.isFinite(frame.timestamp) ? frame.timestamp : _nowMs();
const bracketPresentationOpacity = detectionBracketOpacity(_cockpitActive);
const shouldSolve = _labelSolveDirty || now - _lastLabelSolveAt >= LABEL_SOLVE_INTERVAL_MS;
const shouldSolve =
_labelSolveDirty || now - _lastLabelSolveAt >= LABEL_SOLVE_INTERVAL_MS;
const calloutOcclusionRects = frame.uiRects;
const selectedIdentities = shouldSolve
? _labelArbiter.liveIdentities({ includeFading: false, now })
: null;
const renderIdentities = _labelArbiter.liveIdentities({ includeFading: true, now });
const renderIdentities = _labelArbiter.liveIdentities({
includeFading: true,
now,
});
const objects = _collectDetectableObjects();
const sampledCount = objects.length;
if (objects.length === 0) {
@@ -1100,7 +1214,9 @@ function _drawOverlay(frame) {
profile: MODE_LABELS[_mode],
densityPct: _densityPct,
allocationStrategy: _allocationStrategy,
viewScale: viewScaleForAltitude(_viewer?.camera?.positionCartographic?.height),
viewScale: viewScaleForAltitude(
_viewer?.camera?.positionCartographic?.height,
),
candidateCount: 0,
observationCount: 0,
visibleCount: 0,
@@ -1128,7 +1244,13 @@ function _drawOverlay(frame) {
// whole mechanism exists to remove.
_lastLabelSolveAt = now;
_labelSolveDirty = false;
return { didSolve: false, solveMs: 0, fadingCount: 0, animatingCount: 0, solvePending: false };
return {
didSolve: false,
solveMs: 0,
fadingCount: 0,
animatingCount: 0,
solvePending: false,
};
}
// Horizon culling, keyhole geometry, and camera transforms are shared with
@@ -1163,7 +1285,10 @@ function _drawOverlay(frame) {
const colorFor = (key) => (tiers && tiers[key]) || _theme.line;
const bracketPaths = new Map();
const pathFor = (map, color, alpha) => {
const band = Math.max(1, Math.min(BRACKET_ALPHA_STEPS, Math.ceil(alpha * BRACKET_ALPHA_STEPS)));
const band = Math.max(
1,
Math.min(BRACKET_ALPHA_STEPS, Math.ceil(alpha * BRACKET_ALPHA_STEPS)),
);
let bands = map.get(color);
if (!bands) {
bands = new Array(BRACKET_ALPHA_STEPS + 1);
@@ -1201,8 +1326,10 @@ function _drawOverlay(frame) {
const clipW = vp3 * px + vp7 * py + vp11 * pz + vp15;
if (clipW <= 0) continue;
const invW = 1 / clipW;
const sx = ((vp0 * px + vp4 * py + vp8 * pz + vp12) * invW * 0.5 + 0.5) * width;
const sy = (0.5 - (vp1 * px + vp5 * py + vp9 * pz + vp13) * invW * 0.5) * height;
const sx =
((vp0 * px + vp4 * py + vp8 * pz + vp12) * invW * 0.5 + 0.5) * width;
const sy =
(0.5 - (vp1 * px + vp5 * py + vp9 * pz + vp13) * invW * 0.5) * height;
// Tracked objects (skipLabel) get larger boxes. AIR reticles scale with the
// plane's on-screen size (same scaleByDistance curve as the billboards) so
@@ -1213,26 +1340,49 @@ function _drawOverlay(frame) {
if (obj.type === 'AIR') {
const bscale = nearFarScale(
Cesium.Cartesian3.distance(camPos, obj.position),
BILL_NEAR, BILL_NEAR_SCALE, BILL_FAR, BILL_FAR_SCALE,
BILL_NEAR,
BILL_NEAR_SCALE,
BILL_FAR,
BILL_FAR_SCALE,
);
halfW = _clamp((isTracked ? 14 : 9) * bscale, 7, 48);
halfH = _clamp((isTracked ? 11 : 7) * bscale, 5, 38);
} else if (obj.tier?.startsWith('transit_') && obj.bracketHalfWidth > 0) {
halfW = obj.bracketHalfWidth;
halfH = obj.bracketHalfHeight;
} else {
halfW = _mode === MODE_DENSE ? (isTracked ? 28 : 11) : 16;
halfH = _mode === MODE_DENSE ? (isTracked ? 22 : 7) : 10;
}
// Viewport bounds check with padding
if (sx < -halfW || sx > width + halfW || sy < -halfH || sy > height + halfH) continue;
if (sx < -halfW || sx > width + halfW || sy < -halfH || sy > height + halfH)
continue;
// Tier color drives the bracket, accent bar, and leader line for this object.
// The bracket follows the same linear radial keyhole fade as its callout.
const color = colorFor(resolveTier(obj));
const keyholeAlpha = keyholeLabelAlphaFromGeometry(sx, sy, keyhole);
const bracketAlpha = detectionBracketAlpha(obj.type, keyholeAlpha, keyholeOutsideOpacity);
const bracketAlpha = detectionBracketAlpha(
obj.type,
keyholeAlpha,
keyholeOutsideOpacity,
);
if (bracketAlpha > 0) {
appendCornerBracket(pathFor(bracketPaths, color, bracketAlpha), sx, sy, halfW, halfH);
const transit = obj.tier?.startsWith('transit_');
(transit ? appendTransitBracket : appendCornerBracket)(
pathFor(
transit ? _transitBracketPaths : bracketPaths,
color,
bracketAlpha,
),
sx,
sy,
halfW,
halfH,
);
visibleCount++;
if (obj.type === 'AIR') aircraftBracketSectors[detectionHorizontalSector(sx, width)]++;
if (obj.type === 'AIR')
aircraftBracketSectors[detectionHorizontalSector(sx, width)]++;
if (bracketAlpha >= 1) bracketOpacityCounts.full++;
else bracketOpacityCounts.partial++;
} else {
@@ -1266,8 +1416,10 @@ function _drawOverlay(frame) {
if (shouldSolve && keyholeAlpha > 0) {
demandByLayer.set(layerId, (demandByLayer.get(layerId) || 0) + 1);
if (!cohortBuilders.has(layerId)) cohortBuilders.set(layerId, new BoundedCohort(256));
const incumbent = selectedIdentities?.get(layerId)?.has(sourceId) || false;
if (!cohortBuilders.has(layerId))
cohortBuilders.set(layerId, new BoundedCohort(256));
const incumbent =
selectedIdentities?.get(layerId)?.has(sourceId) || false;
cohortBuilders.get(layerId).consider(obj, incumbent);
}
@@ -1281,13 +1433,17 @@ function _drawOverlay(frame) {
calloutOcclusionRects,
camPos,
);
if (candidate && !candidateMap.has(candidate.key)) candidateMap.set(candidate.key, candidate);
if (candidate && !candidateMap.has(candidate.key))
candidateMap.set(candidate.key, candidate);
}
}
const altitude = _viewer?.camera?.positionCartographic?.height ?? 1e9;
const collectiveBudget = labelBudgetFor(altitude, _densityPct);
const ambientBudget = Math.max(0, collectiveBudget - Math.min(collectiveBudget, protectedVisibleCount));
const ambientBudget = Math.max(
0,
collectiveBudget - Math.min(collectiveBudget, protectedVisibleCount),
);
let didSolve = false;
let solveMs = 0;
if (shouldSolve) {
@@ -1300,7 +1456,9 @@ function _drawOverlay(frame) {
const solveCandidates = [];
const cohortByLayer = {};
for (const [layerId, builder] of cohortBuilders) {
const cohort = builder.values(cohortCapForQuota(quotas.get(layerId) || 0));
const cohort = builder.values(
cohortCapForQuota(quotas.get(layerId) || 0),
);
for (const obj of cohort) {
const key = _detectionKey(layerId, obj._cohortSourceId);
let candidate = candidateMap.get(key);
@@ -1318,7 +1476,9 @@ function _drawOverlay(frame) {
}
if (candidate) solveCandidates.push(candidate);
}
cohortByLayer[layerId] = solveCandidates.filter((candidate) => candidate.layerId === layerId).length;
cohortByLayer[layerId] = solveCandidates.filter(
(candidate) => candidate.layerId === layerId,
).length;
}
const solveStarted = performance.now();
_labelArbiter.solve(solveCandidates, {
@@ -1346,6 +1506,7 @@ function _drawOverlay(frame) {
const fade = acquireAlpha(_enableTime, now, FADE_MS);
const bracketWidth = _mode === MODE_DENSE ? 1 : 1.25;
_transitBracketAlpha = fade * bracketPresentationOpacity;
// Brackets — batched by tier color and linear radial-opacity band.
_ctx.lineWidth = bracketWidth;
@@ -1398,14 +1559,17 @@ function _drawOverlay(frame) {
labelsByLayer: arbiterDiagnostics.labelsByLayer || {},
entitlementByLayer: arbiterDiagnostics.quotas || {},
labeledKeys: Array.from(_labelArbiter.selectedKeys),
labelAlphaByKey: Object.fromEntries(renderEntries.map((entry) => [
entry.candidate.key,
entry.temporalAlpha * keyholeLabelAlphaFromGeometry(
entry.placement.centerX,
entry.placement.centerY,
keyhole,
),
])),
labelAlphaByKey: Object.fromEntries(
renderEntries.map((entry) => [
entry.candidate.key,
entry.temporalAlpha *
keyholeLabelAlphaFromGeometry(
entry.placement.centerX,
entry.placement.centerY,
keyhole,
),
]),
),
solveRevision: _labelArbiter.solveRevision,
keyholeRadius: keyhole.radius,
keyholeFeatherPx: keyhole.featherPx,
@@ -1430,5 +1594,11 @@ function _drawOverlay(frame) {
_drawModeBanner(visibleCount, sampledCount);
// `_labelSolveDirty` surviving a paint means the solve was owed and did not
// run — the frame that carried the request cannot be the last one.
return { didSolve, solveMs, fadingCount, animatingCount, solvePending: _labelSolveDirty };
return {
didSolve,
solveMs,
fadingCount,
animatingCount,
solvePending: _labelSolveDirty,
};
}
+41 -12
View File
@@ -19,11 +19,14 @@ export function stableIdentityHash(layerId, sourceId) {
/** Negative means a is a better deterministic contender than b. */
export function compareCohortContenders(a, b) {
const priorityDelta = (Number(b?._cohortPriority) || 0) - (Number(a?._cohortPriority) || 0);
const priorityDelta =
(Number(b?._cohortPriority) || 0) - (Number(a?._cohortPriority) || 0);
if (priorityDelta) return priorityDelta;
const bandDelta = (Number(b?._cohortBand) || 0) - (Number(a?._cohortBand) || 0);
const bandDelta =
(Number(b?._cohortBand) || 0) - (Number(a?._cohortBand) || 0);
if (bandDelta) return bandDelta;
const hashDelta = (Number(a?._cohortHash) >>> 0) - (Number(b?._cohortHash) >>> 0);
const hashDelta =
(Number(a?._cohortHash) >>> 0) - (Number(b?._cohortHash) >>> 0);
if (hashDelta) return hashDelta;
return String(a?._cohortSourceId).localeCompare(String(b?._cohortSourceId));
}
@@ -39,8 +42,14 @@ function isWorse(a, b) {
*/
export class BoundedCohort {
constructor(maxSize = DEFAULT_MAX_COHORT, hardMax = DEFAULT_MAX_COHORT) {
const ceiling = Math.max(1, Math.floor(Number(hardMax) || DEFAULT_MAX_COHORT));
this.maxSize = Math.max(1, Math.min(ceiling, Math.floor(Number(maxSize) || DEFAULT_MAX_COHORT)));
const ceiling = Math.max(
1,
Math.floor(Number(hardMax) || DEFAULT_MAX_COHORT),
);
this.maxSize = Math.max(
1,
Math.min(ceiling, Math.floor(Number(maxSize) || DEFAULT_MAX_COHORT)),
);
this.incumbents = [];
this.heap = [];
}
@@ -62,11 +71,20 @@ export class BoundedCohort {
}
values(limit = this.maxSize) {
const cap = Math.max(0, Math.min(this.maxSize, Math.floor(Number(limit) || 0)));
const incumbents = this.incumbents.slice().sort(compareCohortContenders).slice(0, cap);
const cap = Math.max(
0,
Math.min(this.maxSize, Math.floor(Number(limit) || 0)),
);
const incumbents = this.incumbents
.slice()
.sort(compareCohortContenders)
.slice(0, cap);
const remaining = Math.max(0, cap - incumbents.length);
if (remaining === 0) return incumbents;
const contenders = this.heap.slice().sort(compareCohortContenders).slice(0, remaining);
const contenders = this.heap
.slice()
.sort(compareCohortContenders)
.slice(0, remaining);
return incumbents.concat(contenders);
}
@@ -75,7 +93,10 @@ export class BoundedCohort {
while (current > 0) {
const parent = Math.floor((current - 1) / 2);
if (!isWorse(this.heap[current], this.heap[parent])) break;
[this.heap[current], this.heap[parent]] = [this.heap[parent], this.heap[current]];
[this.heap[current], this.heap[parent]] = [
this.heap[parent],
this.heap[current],
];
current = parent;
}
}
@@ -86,10 +107,18 @@ export class BoundedCohort {
const left = current * 2 + 1;
const right = left + 1;
let worst = current;
if (left < this.heap.length && isWorse(this.heap[left], this.heap[worst])) worst = left;
if (right < this.heap.length && isWorse(this.heap[right], this.heap[worst])) worst = right;
if (left < this.heap.length && isWorse(this.heap[left], this.heap[worst]))
worst = left;
if (
right < this.heap.length &&
isWorse(this.heap[right], this.heap[worst])
)
worst = right;
if (worst === current) return;
[this.heap[current], this.heap[worst]] = [this.heap[worst], this.heap[current]];
[this.heap[current], this.heap[worst]] = [
this.heap[worst],
this.heap[current],
];
current = worst;
}
}
+33 -5
View File
@@ -211,11 +211,14 @@ export function measureTrackLabel(primary, micro, charWidth) {
*/
export function rectIntersectsAny(rect, obstacles, padding = 0) {
if (!rect || !Array.isArray(obstacles)) return false;
return obstacles.some((obstacle) => obstacle
&& rect.x < obstacle.x + obstacle.w + padding
&& rect.x + rect.w + padding > obstacle.x
&& rect.y < obstacle.y + obstacle.h + padding
&& rect.y + rect.h + padding > obstacle.y);
return obstacles.some(
(obstacle) =>
obstacle &&
rect.x < obstacle.x + obstacle.w + padding &&
rect.x + rect.w + padding > obstacle.x &&
rect.y < obstacle.y + obstacle.h + padding &&
rect.y + rect.h + padding > obstacle.y,
);
}
/**
@@ -237,3 +240,28 @@ export function nearFarScale(distance, near, nearValue, far, farValue) {
const t = (distance - near) / (far - near);
return nearValue + t * (farValue - nearValue);
}
/** Transit keeps literal mode colour on the normal-composite surface. */
export function paintTransitBracket(ctx, path, color, alpha = 1) {
ctx.save?.();
ctx.globalCompositeOperation = 'source-over';
ctx.globalAlpha = alpha;
ctx.strokeStyle = '#05080C';
ctx.lineWidth = 3.25;
ctx.stroke(path);
ctx.strokeStyle = color;
ctx.lineWidth = 1.25;
ctx.stroke(path);
ctx.restore?.();
}
/** Centre 1.25 px strokes on pixels, so their cores are fully covered. */
export function appendTransitBracket(sink, sx, sy, halfW, halfH) {
appendCornerBracket(
sink,
Math.floor(sx) + 0.5,
Math.floor(sy) + 0.5,
Math.round(halfW),
Math.round(halfH),
);
}
+31
View File
@@ -161,3 +161,34 @@ test('nearFarScale interpolates by distance and clamps to the near/far values',
const mid = nearFarScale((1000 + 8000000) / 2, 1000, 3.0, 8000000, 0.5);
assert.ok(Math.abs(mid - 1.75) < 1e-6, `midpoint ~1.75, got ${mid}`);
});
test('transit brackets paint a 1.25 px mode stroke over 3.25 px dark backing', async () => {
const { paintTransitBracket } = await import('./detectionDraw.js');
const strokes = [];
const ctx = { stroke(path) { strokes.push([path, this.lineWidth, this.strokeStyle, this.globalAlpha]); } };
const path = {};
paintTransitBracket(ctx, path, '#FF4538', 0.75);
assert.deepEqual(strokes, [[path, 3.25, '#05080C', 0.75], [path, 1.25, '#FF4538', 0.75]]);
});
test('transit bracket backing and colour use source-over under every inherited sensor theme', async () => {
const {paintTransitBracket}=await import('./detectionDraw.js');
for(const theme of ['normal','thermal','surveillance','noir','retro']) {
const strokes=[];
const ctx={globalCompositeOperation:'screen',globalAlpha:0.3,stroke(p){strokes.push([this.globalCompositeOperation,this.lineWidth,this.strokeStyle]);},save(){this.saved=[this.globalCompositeOperation,this.globalAlpha];},restore(){[this.globalCompositeOperation,this.globalAlpha]=this.saved;}};
paintTransitBracket(ctx,{},'#FF4538',1);
assert.deepEqual(strokes,[['source-over',3.25,'#05080C'],['source-over',1.25,'#FF4538']],theme);
assert.equal(ctx.globalCompositeOperation,'screen');
}
});
test('transit bracket stroke centres have full pixel coverage at the failing fractional positions', async () => {
const {appendTransitBracket}=await import('./detectionDraw.js');
for(const sy of [305.076,490.54,279.56]) {
const points=[],sink={moveTo:(x,y)=>points.push([x,y]),lineTo:(x,y)=>points.push([x,y])};
appendTransitBracket(sink,759.016,sy,11,7);
assert.equal(points.length,12);
for(const [x,y] of points){assert.equal(x%1,0.5);assert.equal(y%1,0.5);}
}
});
+87 -1
View File
@@ -24,6 +24,7 @@ import {
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
import { composeLabel, resolveTier } from './detectionDraw.js';
test('detection diagnostics count rendered fading rows instead of absent selected identities', () => {
assert.equal(countFadingRenderEntries([
@@ -97,7 +98,7 @@ function mockContext(target, trace) {
// set at some point during the frame. globalAlpha rides along for the same
// reason: the backdrop feather is an alpha, not a colour.
fill(path) { record('fill', path, this.fillStyle, this.globalAlpha); },
stroke(path) { record('stroke', path); },
stroke(path) { record('stroke', path, this.strokeStyle, this.lineWidth); },
fillRect(...args) { record('fillRect', ...args); },
fillText(...args) { record('fillText', ...args); },
drawImage(...args) { record('drawImage', ...args); },
@@ -378,6 +379,12 @@ test('detection lifecycle re-hosts unchanged painters behind the sole host liste
env.postRender.raise();
const first = getDetectionDiagnostics();
assert.equal(first.profile, 'DENSE');
assert.ok(Array.isArray(first.calloutRects));
if (first.calloutRects.length) {
const x=first.calloutRects[0].x;
first.calloutRects[0].x=NaN;
assert.equal(getDetectionDiagnostics().calloutRects[0].x,x,'QA owns a copy, never a live plate');
}
assert.equal(first.observationCount, 2);
assert.equal(first.didSolve, true);
assert.ok(first.solveRevision > 0);
@@ -874,3 +881,82 @@ test('the backdrop feather reaches the canvas as a lighter plate against sky', (
env.cleanup();
}
});
test('a transit vehicle is a contact: box, route, mode and operator on the shared canvas', () => {
// The owner's finding was that buses were "green dots moving around
// clumsily" — the layer rendered them and the detection overlay ignored
// them, because transit published no detectable objects at all. This drives
// the real host with the shape the layer now returns.
const env = installEnvironment();
const objects = [
{
position: new Cesium.Cartesian3(0, 0, 6_356_752),
sourceId: 'mbta:y1276',
tier: 'transit_bus',
id: '111',
type: 'VEH',
klass: 'MBTA',
metric: 'BUS 34 KM/H',
},
{
position: new Cesium.Cartesian3(0, 900, 6_356_752),
sourceId: 'mbta:R-548BBB14',
id: 'RED',
type: 'VEH',
klass: 'MBTA',
metric: 'METRO STOPPED',
skipLabel: true,
},
];
try {
initWorldOverlay(env.viewer);
initDetection(
env.viewer,
[{ id: 'transit', getDetectableObjects: () => objects }],
() => {},
);
setMode('DENSE');
env.advance(250);
env.postRender.raise();
env.advance(250);
env.postRender.raise();
const painted = env.ctx.calls
.filter(([name]) => name === 'fillText')
.map(([, text]) => text);
assert.ok(
painted.includes('111'),
`the route is the bright line; painted ${JSON.stringify(painted)}`,
);
// The host paints a single-line track label — bright id, one dim micro
// field — so the mode and what the vehicle is doing share that field.
assert.ok(
painted.some((text) => String(text).includes('BUS')),
`the mode rides along on the micro line; painted ${JSON.stringify(painted)}`,
);
assert.ok(
painted.some((text) => String(text).includes('34 KM/H')),
'and so does what the vehicle is doing',
);
assert.ok(env.ctx.calls.some(([name, , color, width]) => name === 'stroke' && color === '#5EF08A' && width === 1.25));
assert.ok(env.ctx.calls.some(([name, , color, width]) => name === 'stroke' && color === '#05080C' && width === 3.25));
assert.ok(!env.detectionCtx.calls.some(([name, , color]) => name === 'stroke' && color === '#5EF08A'));
// The operator travels on the object for the two-tier card form, which is
// where `klass` is read; the host's track label does not paint it.
assert.equal(composeLabel(objects[0]).secondary, 'MBTA · BUS 34 KM/H');
// The selected vehicle carries its own fuller card, so detection must not
// label it a second time.
assert.equal(
painted.includes('RED'),
false,
'skipLabel keeps the selected vehicle from being labelled twice',
);
} finally {
env.cleanup();
}
});
test('transit contacts take the vehicle tier, not the civil-air one', () => {
assert.equal(resolveTier({ type: 'VEH' }), 'vehicle');
assert.equal(resolveTier({ type: 'AIR' }), 'civil');
assert.equal(resolveTier({ type: 'SEA' }), 'sea');
});
+66 -20
View File
@@ -8,7 +8,10 @@
export const DENSITY_STOPS = Object.freeze([0, 25, 50, 75, 100]);
export const ALLOCATION_ELASTIC = 'ELASTIC';
export const ALLOCATION_WEIGHTED = 'WEIGHTED';
export const ALLOCATION_STRATEGIES = Object.freeze([ALLOCATION_ELASTIC, ALLOCATION_WEIGHTED]);
export const ALLOCATION_STRATEGIES = Object.freeze([
ALLOCATION_ELASTIC,
ALLOCATION_WEIGHTED,
]);
// The keyhole's default 1% outside opacity is appropriate for text, but it
// made side aircraft brackets effectively disappear while the same contacts
@@ -71,10 +74,16 @@ export function aircraftBracketAlphaFloor(outsideOpacity) {
: AIRCRAFT_BRACKET_FLOOR_ANCHOR;
if (outside <= 0) return 0;
if (outside <= AIRCRAFT_BRACKET_FLOOR_ANCHOR) {
return AIRCRAFT_BRACKET_ALPHA_FLOOR * (outside / AIRCRAFT_BRACKET_FLOOR_ANCHOR);
return (
AIRCRAFT_BRACKET_ALPHA_FLOOR * (outside / AIRCRAFT_BRACKET_FLOOR_ANCHOR)
);
}
const progress = (outside - AIRCRAFT_BRACKET_FLOOR_ANCHOR) / (1 - AIRCRAFT_BRACKET_FLOOR_ANCHOR);
return AIRCRAFT_BRACKET_ALPHA_FLOOR + (1 - AIRCRAFT_BRACKET_ALPHA_FLOOR) * progress;
const progress =
(outside - AIRCRAFT_BRACKET_FLOOR_ANCHOR) /
(1 - AIRCRAFT_BRACKET_FLOOR_ANCHOR);
return (
AIRCRAFT_BRACKET_ALPHA_FLOOR + (1 - AIRCRAFT_BRACKET_ALPHA_FLOOR) * progress
);
}
/**
@@ -85,7 +94,11 @@ export function aircraftBracketAlphaFloor(outsideOpacity) {
* the default, so a caller that does not know it reproduces the shipped look.
* @returns {number} Paint alpha, 0-1.
*/
export function detectionBracketAlpha(type, keyholeAlpha, outsideOpacity = AIRCRAFT_BRACKET_FLOOR_ANCHOR) {
export function detectionBracketAlpha(
type,
keyholeAlpha,
outsideOpacity = AIRCRAFT_BRACKET_FLOOR_ANCHOR,
) {
const alpha = Math.max(0, Math.min(1, Number(keyholeAlpha) || 0));
if (String(type || '').toUpperCase() !== 'AIR' || alpha <= 0) return alpha;
return Math.max(aircraftBracketAlphaFloor(outsideOpacity), alpha);
@@ -97,7 +110,7 @@ export function detectionHorizontalSector(screenX, viewportWidth) {
const x = Number(screenX);
if (!(width > 0) || !Number.isFinite(x)) return 'front';
if (x < width / 3) return 'left';
if (x > width * 2 / 3) return 'right';
if (x > (width * 2) / 3) return 'right';
return 'front';
}
@@ -140,19 +153,29 @@ export function defaultDensityForProfile(profile) {
/** Normalize current and legacy profile labels. OFF remains an enabled-state value. */
export function normalizeProfile(profile) {
const raw = String(profile || '').trim().toUpperCase();
const raw = String(profile || '')
.trim()
.toUpperCase();
if (raw === 'OFF') return 'OFF';
if (raw === 'SPARSE' || raw === 'SURVEY') return 'SPARSE';
if (raw === 'BALANCED' || raw === 'NORMAL') return 'BALANCED';
if (raw === 'DENSE' || raw === 'PANOPTIC' || raw === 'GOD' || raw === 'ON') return 'DENSE';
if (raw === 'DENSE' || raw === 'PANOPTIC' || raw === 'GOD' || raw === 'ON')
return 'DENSE';
return null;
}
/** Normalize the user-selectable layer allocation strategy. */
export function normalizeAllocationStrategy(strategy, fallback = ALLOCATION_ELASTIC) {
const raw = String(strategy || '').trim().toUpperCase();
export function normalizeAllocationStrategy(
strategy,
fallback = ALLOCATION_ELASTIC,
) {
const raw = String(strategy || '')
.trim()
.toUpperCase();
if (ALLOCATION_STRATEGIES.includes(raw)) return raw;
const normalizedFallback = String(fallback || '').trim().toUpperCase();
const normalizedFallback = String(fallback || '')
.trim()
.toUpperCase();
return ALLOCATION_STRATEGIES.includes(normalizedFallback)
? normalizedFallback
: ALLOCATION_ELASTIC;
@@ -160,7 +183,9 @@ export function normalizeAllocationStrategy(strategy, fallback = ALLOCATION_ELAS
/** Classify camera altitude into the shared label-budget view scale. */
export function viewScaleForAltitude(altitudeM) {
const altitude = Number.isFinite(Number(altitudeM)) ? Math.max(0, Number(altitudeM)) : 1e9;
const altitude = Number.isFinite(Number(altitudeM))
? Math.max(0, Number(altitudeM))
: 1e9;
if (altitude < 1200) return 'street';
if (altitude < 4500) return 'city';
if (altitude < 20000) return 'metro';
@@ -181,25 +206,46 @@ export function labelBudgetFor(altitudeM, densityPct) {
* density was below 75; legacy Sparse remains inside the Sparse band.
*/
export function migrateDetectionState(mode, densityPct, fallbackDensity = 50) {
const rawMode = String(mode || '').trim().toUpperCase();
const rawMode = String(mode || '')
.trim()
.toUpperCase();
const normalized = normalizeProfile(rawMode);
if (normalized === 'OFF') {
const supplied = Number.isFinite(Number(densityPct)) ? densityPct : fallbackDensity;
const supplied = Number.isFinite(Number(densityPct))
? densityPct
: fallbackDensity;
const stop = canonicalizeDensity(supplied, fallbackDensity);
return { enabled: false, profile: profileForDensity(stop), densityPct: stop };
return {
enabled: false,
profile: profileForDensity(stop),
densityPct: stop,
};
}
if (rawMode === 'PANOPTIC' || rawMode === 'GOD' || rawMode === 'ON') {
const density = Number.isFinite(Number(densityPct)) ? Math.max(75, Number(densityPct)) : 75;
return { enabled: true, profile: 'DENSE', densityPct: canonicalizeDensity(density) };
const density = Number.isFinite(Number(densityPct))
? Math.max(75, Number(densityPct))
: 75;
return {
enabled: true,
profile: 'DENSE',
densityPct: canonicalizeDensity(density),
};
}
if (rawMode === 'SPARSE' || rawMode === 'SURVEY') {
const density = Number.isFinite(Number(densityPct)) ? Math.min(25, Number(densityPct)) : 25;
const density = Number.isFinite(Number(densityPct))
? Math.min(25, Number(densityPct))
: 25;
const stop = canonicalizeDensity(density, 25);
return { enabled: true, profile: 'SPARSE', densityPct: stop };
}
if (normalized === 'BALANCED' || normalized === 'DENSE') {
const supplied = Number.isFinite(Number(densityPct)) ? canonicalizeDensity(densityPct) : defaultDensityForProfile(normalized);
const stop = profileForDensity(supplied) === normalized ? supplied : defaultDensityForProfile(normalized);
const supplied = Number.isFinite(Number(densityPct))
? canonicalizeDensity(densityPct)
: defaultDensityForProfile(normalized);
const stop =
profileForDensity(supplied) === normalized
? supplied
: defaultDensityForProfile(normalized);
return { enabled: true, profile: normalized, densityPct: stop };
}
const stop = canonicalizeDensity(densityPct, fallbackDensity);
-1
View File
@@ -10,4 +10,3 @@ export const COCKPIT_BRACKET_OPACITY = 0.45;
export function detectionBracketOpacity(cockpitActive) {
return cockpitActive === true ? COCKPIT_BRACKET_OPACITY : 1;
}
+1 -1
View File
@@ -17,7 +17,7 @@ test('Cockpit reduces only the bracket presentation multiplier', () => {
test('detection owns and releases the Cockpit lifecycle listener', async () => {
const source = await readFile(new URL('./detection.js', import.meta.url), 'utf8');
assert.match(source, /addEventListener\('gev:cockpit-mode-changed', _cockpitModeListener\)/);
assert.match(source, /removeEventListener\('gev:cockpit-mode-changed', _cockpitModeListener\)/);
assert.match(source, /removeEventListener\(\s*'gev:cockpit-mode-changed',\s*_cockpitModeListener,?\s*\)/);
assert.match(
source,
/fade \* entry\.alpha \* bracketPresentationOpacity/,
+4 -3
View File
@@ -158,9 +158,10 @@ export function detectionPaintSkipDecision({
frameCount,
thresholdMs = DETECTION_PAINT_SKIP_THRESHOLD_MS,
} = {}) {
const skip = !layoutChanged
&& Number(lastPaintMs) > thresholdMs
&& Number(frameCount) % 2 !== 0;
const skip =
!layoutChanged &&
Number(lastPaintMs) > thresholdMs &&
Number(frameCount) % 2 !== 0;
return { skip, requestFollowUp: skip };
}
+4 -4
View File
@@ -277,7 +277,7 @@ test('detection holds nothing, and asks for its own frames instead', async () =>
assert.match(source, /governorRequestRender\('detection-visibility'\)/,
'mode/suspend transitions request their own repaint');
assert.match(source, /if \(detectionNeedsFollowUpFrame\(\{[\s\S]*?\}\)\) \{\s*\n\s*governorRequestRender\('detection-animation'\);/,
assert.match(source, /if \(\s*detectionNeedsFollowUpFrame\(\{[\s\S]*?\}\)\s*\) \{\s*\n\s*governorRequestRender\('detection-animation'\);/,
'the follow-up frame is gated on the policy, never unconditional');
// The demand call must read the FRAME's timestamp, not a fresh sample.
@@ -306,7 +306,7 @@ test('detection holds nothing, and asks for its own frames instead', async () =>
// the emptiest possible scene. (Caught by the governor gate at 301 renders/5 s
// with zero layers; the fix settles the solve there, because with nothing
// detectable it is vacuously complete.)
const emptyExit = /\/\/ Drop the replay buffer with it[\s\S]*?return \{ didSolve: false[^\n]*\n/.exec(source)?.[0];
const emptyExit = /\/\/ Drop the replay buffer with it[\s\S]*?return \{\s*didSolve: false[\s\S]*?\};/.exec(source)?.[0];
assert.ok(emptyExit, 'the zero-objects exit is still identifiable');
assert.match(emptyExit, /_labelSolveDirty = false;/,
'the zero-objects exit settles the solve instead of carrying it forward');
@@ -318,7 +318,7 @@ test('detection holds nothing, and asks for its own frames instead', async () =>
assert.ok(drawOverlay, 'detection.js still has a draw pass');
assert.doesNotMatch(drawOverlay, /Date\.now\(\)/,
'the draw pass must run on the frame timestamp, not a wall clock');
assert.match(drawOverlay, /const now = Number\.isFinite\(frame\.timestamp\) \? frame\.timestamp : _nowMs\(\);/);
assert.match(drawOverlay, /const now =\s*Number\.isFinite\(frame\.timestamp\) \? frame\.timestamp : _nowMs\(\);/);
assert.match(source, /_enableTime = _nowMs\(\);/,
'the enable stamp shares the monotonic clock the fade is measured against');
@@ -331,7 +331,7 @@ test('detection holds nothing, and asks for its own frames instead', async () =>
'the valve asks the shared policy instead of inlining its own threshold');
assert.doesNotMatch(shouldPaint, /_lastPaintMs > 22/,
'the old inline threshold must be gone, not shadowing the policy');
assert.match(shouldPaint, /if \(decision\.requestFollowUp\) governorRequestRender\('detection-paint-skipped'\)/,
assert.match(shouldPaint, /if \(decision\.requestFollowUp\)\s*governorRequestRender\('detection-paint-skipped'\)/,
'skipping a paint must hand the request forward, not swallow it');
// The scanline must not go back to the frame counter: that is what made a
+3 -1
View File
@@ -24,7 +24,9 @@
* @returns {number} Heading in degrees [0..360), or NaN if unrecognized.
*/
export function directionToHeading(value, allowBare = false) {
const text = String(value || '').trim().toUpperCase();
const text = String(value || '')
.trim()
.toUpperCase();
if (!text) return NaN;
// Explicit travel/intercardinal forms — safe on free-form text (a street
// name almost never contains "NORTHBOUND" or a lone "NB" token).
+6 -2
View File
@@ -79,8 +79,12 @@ export function parseAcquisitionMs(date, time, cache = new Map()) {
const hhmm = String(time ?? '0000').padStart(4, '0');
const hours = Number(hhmm.slice(0, 2));
const minutes = Number(hhmm.slice(2, 4));
const valid = Number.isFinite(year) && Number.isFinite(month) && Number.isFinite(day)
&& Number.isFinite(hours) && Number.isFinite(minutes);
const valid =
Number.isFinite(year) &&
Number.isFinite(month) &&
Number.isFinite(day) &&
Number.isFinite(hours) &&
Number.isFinite(minutes);
const ms = valid ? Date.UTC(year, month - 1, day, hours, minutes) : 0;
cache.set(key, ms);
return ms;
+11 -5
View File
@@ -12,10 +12,14 @@ export const FIRMS_OVERLAY_SOURCE_ID = 'firms';
export function fireDetectionKey(fire) {
const lat = Number.isFinite(fire?.lat) ? fire.lat.toFixed(4) : 'x';
const lon = Number.isFinite(fire?.lon) ? fire.lon.toFixed(4) : 'x';
const acq = Number.isFinite(fire?.acqMs) && fire.acqMs > 0 ? String(fire.acqMs) : '0';
const source = satelliteShortName(fire?.satellite)
|| String(fire?.sensor || '').trim().toUpperCase()
|| 'x';
const acq =
Number.isFinite(fire?.acqMs) && fire.acqMs > 0 ? String(fire.acqMs) : '0';
const source =
satelliteShortName(fire?.satellite) ||
String(fire?.sensor || '')
.trim()
.toUpperCase() ||
'x';
return `firms:${lat}:${lon}:${acq}:${source}`;
}
@@ -37,7 +41,9 @@ export function accentForSeverity(stopName) {
/** Raw FIRMS satellite code → short display name (N = Suomi NPP). */
export function satelliteShortName(satellite) {
const s = String(satellite || '').trim().toUpperCase();
const s = String(satellite || '')
.trim()
.toUpperCase();
if (s === 'N20' || s === 'NOAA-20') return 'N20';
if (s === 'N21' || s === 'NOAA-21') return 'N21';
if (s === 'N' || s === 'NPP' || s === 'SUOMI NPP') return 'SNPP';
+29 -9
View File
@@ -45,7 +45,9 @@ export function median(values) {
if (!Array.isArray(values) || values.length === 0) return null;
const sorted = [...values].sort((a, b) => a - b);
const mid = sorted.length >> 1;
return sorted.length % 2 === 1 ? sorted[mid] : (sorted[mid - 1] + sorted[mid]) / 2;
return sorted.length % 2 === 1
? sorted[mid]
: (sorted[mid - 1] + sorted[mid]) / 2;
}
/** Bearing (degrees, 0 = north, clockwise) of a projected dx/dy vector. */
@@ -98,13 +100,19 @@ export function matchFlowToRoads(roads, flowSegments) {
const roadCount = Array.isArray(roads) ? roads.length : 0;
const matches = new Array(roadCount).fill(null);
const empty = { matches, matchedCount: 0, candidateCount: 0 };
if (roadCount === 0 || !Array.isArray(flowSegments) || flowSegments.length === 0) {
if (
roadCount === 0 ||
!Array.isArray(flowSegments) ||
flowSegments.length === 0
) {
return empty;
}
// Local equirectangular projection anchored at the first flow coordinate —
// over a ≤0.05° fetch box the distortion is negligible.
const anchor = flowSegments.find((f) => Array.isArray(f?.coords) && f.coords.length >= 2);
const anchor = flowSegments.find(
(f) => Array.isArray(f?.coords) && f.coords.length >= 2,
);
if (!anchor) return empty;
const [refLon, refLat] = anchor.coords[0];
const mPerDegLon = M_PER_DEG_LAT * Math.cos((refLat * Math.PI) / 180);
@@ -114,7 +122,8 @@ export function matchFlowToRoads(roads, flowSegments) {
// ── 1. Spatial hash of flow segments (midpoint-keyed 100 m cells) ──
/** @type {Map<string, Array<{ax:number,ay:number,bx:number,by:number,bearing:number,level:number,closure:boolean}>>} */
const grid = new Map();
const cellOf = (x, y) => `${Math.floor(x / CELL_SIZE_M)},${Math.floor(y / CELL_SIZE_M)}`;
const cellOf = (x, y) =>
`${Math.floor(x / CELL_SIZE_M)},${Math.floor(y / CELL_SIZE_M)}`;
for (const flow of flowSegments) {
const coords = flow?.coords;
@@ -173,7 +182,8 @@ export function matchFlowToRoads(roads, flowSegments) {
for (let i = 0; i < coords.length; i++) {
xs[i] = projX(coords[i][0]);
ys[i] = projY(coords[i][1]);
if (i > 0) cum[i] = cum[i - 1] + Math.hypot(xs[i] - xs[i - 1], ys[i] - ys[i - 1]);
if (i > 0)
cum[i] = cum[i - 1] + Math.hypot(xs[i] - xs[i - 1], ys[i] - ys[i - 1]);
}
const totalLen = cum[coords.length - 1];
if (!(totalLen > 0)) continue;
@@ -188,10 +198,14 @@ export function matchFlowToRoads(roads, flowSegments) {
// cross-street flow lines meet at intersections.
const target = (totalLen * (s + 0.5)) / ROAD_SAMPLES;
while (cursor < coords.length - 1 && cum[cursor] < target) cursor++;
const segT = (target - cum[cursor - 1]) / (cum[cursor] - cum[cursor - 1] || 1);
const segT =
(target - cum[cursor - 1]) / (cum[cursor] - cum[cursor - 1] || 1);
const px = xs[cursor - 1] + (xs[cursor] - xs[cursor - 1]) * segT;
const py = ys[cursor - 1] + (ys[cursor] - ys[cursor - 1]) * segT;
const sampleBearing = bearingDeg(xs[cursor] - xs[cursor - 1], ys[cursor] - ys[cursor - 1]);
const sampleBearing = bearingDeg(
xs[cursor] - xs[cursor - 1],
ys[cursor] - ys[cursor - 1],
);
// 3×3 cell probe around the sample.
const cx = Math.floor(px / CELL_SIZE_M);
@@ -206,7 +220,11 @@ export function matchFlowToRoads(roads, flowSegments) {
const d2 = pointSegDist2(px, py, seg.ax, seg.ay, seg.bx, seg.by);
if (d2 > radius2) continue;
hadCandidate = true; // within radius, bearing not yet checked
if (bearingDiffDeg(seg.bearing, sampleBearing) >= BEARING_TOLERANCE_DEG) continue;
if (
bearingDiffDeg(seg.bearing, sampleBearing) >=
BEARING_TOLERANCE_DEG
)
continue;
if (d2 <= bestDist2) {
bestDist2 = d2;
best = seg;
@@ -221,7 +239,9 @@ export function matchFlowToRoads(roads, flowSegments) {
}
if (hadCandidate) candidateCount++;
if (matchedLevels.length >= Math.max(MIN_MATCHED_SAMPLES, ROAD_SAMPLES / 2)) {
if (
matchedLevels.length >= Math.max(MIN_MATCHED_SAMPLES, ROAD_SAMPLES / 2)
) {
matches[r] = { level: median(matchedLevels), closure: matchedClosure };
matchedCount++;
}
+114 -50
View File
@@ -59,24 +59,35 @@ function focusTargetEmphasisResolved(
previouslyFarther,
) {
if (!target?.screenRect || !spriteScreenPosition) return 1;
if (!Number.isFinite(spriteScreenPosition.x) || !Number.isFinite(spriteScreenPosition.y)) return 1;
if (
!Number.isFinite(spriteScreenPosition.x) ||
!Number.isFinite(spriteScreenPosition.y)
)
return 1;
// Published rects already contain their publication-time padding. The
// delta keeps direct pure-function calls and runtime A/B overrides honest.
// The ambient extent makes overlap mean visual overlap, not center-point
// containment: a class-sized icon whose edge intrudes into the focus rect
// yields even when its center remains just outside it.
const paddingDelta = tuning.paddingPx - (Number.isFinite(target.paddingPx) ? target.paddingPx : 0);
const paddingDelta =
tuning.paddingPx -
(Number.isFinite(target.paddingPx) ? target.paddingPx : 0);
const hysteresis = previouslyCompeting ? tuning.hysteresisPx : 0;
const expansionX = paddingDelta + hysteresis
+ Math.max(0, Number.isFinite(spriteHalfWidthPx) ? spriteHalfWidthPx : 0);
const expansionY = paddingDelta + hysteresis
+ Math.max(0, Number.isFinite(spriteHalfHeightPx) ? spriteHalfHeightPx : 0);
const expansionX =
paddingDelta +
hysteresis +
Math.max(0, Number.isFinite(spriteHalfWidthPx) ? spriteHalfWidthPx : 0);
const expansionY =
paddingDelta +
hysteresis +
Math.max(0, Number.isFinite(spriteHalfHeightPx) ? spriteHalfHeightPx : 0);
const rect = target.screenRect;
const inside = spriteScreenPosition.x >= rect.left - expansionX
&& spriteScreenPosition.x <= rect.right + expansionX
&& spriteScreenPosition.y >= rect.top - expansionY
&& spriteScreenPosition.y <= rect.bottom + expansionY;
const inside =
spriteScreenPosition.x >= rect.left - expansionX &&
spriteScreenPosition.x <= rect.right + expansionX &&
spriteScreenPosition.y >= rect.top - expansionY &&
spriteScreenPosition.y <= rect.bottom + expansionY;
if (!inside) return 1;
const floor = clamp(tuning.dimFloor, 0.01, 1);
@@ -88,24 +99,33 @@ function focusTargetEmphasisResolved(
const fartherThreshold = Number.isFinite(target.cameraDistance)
? target.cameraDistance + (previouslyFarther ? -distanceBand : distanceBand)
: Number.NaN;
const farther = !Number.isFinite(spriteCameraDistance)
|| !Number.isFinite(fartherThreshold)
|| spriteCameraDistance >= fartherThreshold;
const farther =
!Number.isFinite(spriteCameraDistance) ||
!Number.isFinite(fartherThreshold) ||
spriteCameraDistance >= fartherThreshold;
if (farther) return floor;
if (tuning.nearerBehavior === 'partial') return floor + (1 - floor) * 0.5;
return 1;
}
function smoothFocusEmphasisResolved(current, target, elapsedMs, tuning) {
const from = clamp(Number.isFinite(current) ? current : 1, tuning.dimFloor, 1);
const from = clamp(
Number.isFinite(current) ? current : 1,
tuning.dimFloor,
1,
);
const to = clamp(Number.isFinite(target) ? target : 1, tuning.dimFloor, 1);
if (Math.abs(to - from) < Number.EPSILON) return to;
const duration = to < from ? tuning.attackMs : tuning.releaseMs;
if (duration <= 0) return to;
const t = clamp((Number.isFinite(elapsedMs) ? elapsedMs : 0) / duration, 0, 1);
const t = clamp(
(Number.isFinite(elapsedMs) ? elapsedMs : 0) / duration,
0,
1,
);
// Cubic ease-out reaches the exact endpoint at the configured duration and
// stays continuous when a moving contact reverses direction mid-transition.
const eased = 1 - ((1 - t) ** 3);
const eased = 1 - (1 - t) ** 3;
return clamp(from + (to - from) * eased, tuning.dimFloor, 1);
}
@@ -118,18 +138,24 @@ function smoothFocusEmphasisResolved(current, target, elapsedMs, tuning) {
*/
export function setFocusDeemphasisParams(patch = {}) {
const next = { ..._params };
if (Number.isFinite(patch.paddingPx)) next.paddingPx = Math.max(0, patch.paddingPx);
if (Number.isFinite(patch.dimFloor)) next.dimFloor = clamp(patch.dimFloor, 0.01, 1);
if (Number.isFinite(patch.paddingPx))
next.paddingPx = Math.max(0, patch.paddingPx);
if (Number.isFinite(patch.dimFloor))
next.dimFloor = clamp(patch.dimFloor, 0.01, 1);
if (['allow', 'dim', 'partial'].includes(patch.nearerBehavior)) {
next.nearerBehavior = patch.nearerBehavior;
}
if (Number.isFinite(patch.hysteresisPx)) next.hysteresisPx = Math.max(0, patch.hysteresisPx);
if (Number.isFinite(patch.hysteresisPx))
next.hysteresisPx = Math.max(0, patch.hysteresisPx);
if (Number.isFinite(patch.distanceHysteresisRatio)) {
next.distanceHysteresisRatio = clamp(patch.distanceHysteresisRatio, 0, 0.5);
}
if (Number.isFinite(patch.attackMs)) next.attackMs = Math.max(0, patch.attackMs);
if (Number.isFinite(patch.releaseMs)) next.releaseMs = Math.max(0, patch.releaseMs);
if (Number.isFinite(patch.writeEpsilon)) next.writeEpsilon = Math.max(0, patch.writeEpsilon);
if (Number.isFinite(patch.attackMs))
next.attackMs = Math.max(0, patch.attackMs);
if (Number.isFinite(patch.releaseMs))
next.releaseMs = Math.max(0, patch.releaseMs);
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
@@ -171,11 +197,22 @@ export function publishFocusTargetFromCachedPosition({
heightPx = 24,
params,
}) {
if (!ownerLayer || id === null || id === undefined || !scene || !camera || !displayPosition) {
if (
!ownerLayer ||
id === null ||
id === undefined ||
!scene ||
!camera ||
!displayPosition
) {
clearFocusTarget(ownerLayer, id);
return null;
}
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(scene, displayPosition, _scratchScreen);
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
displayPosition,
_scratchScreen,
);
if (!screen || !Number.isFinite(screen.x) || !Number.isFinite(screen.y)) {
clearFocusTarget(ownerLayer, id);
return null;
@@ -195,12 +232,19 @@ export function publishFocusTargetFromCachedPosition({
bottom: screen.y + halfHeight + padding,
},
paddingPx: padding,
cameraDistance: Cesium.Cartesian3.distance(camera.positionWC, displayPosition),
cameraDistance: Cesium.Cartesian3.distance(
camera.positionWC,
displayPosition,
),
frameNumber: scene.frameState?.frameNumber ?? -1,
};
if (appeared) {
for (const listener of _focusAppearListeners) {
try { listener(); } catch (e) { console.warn('[focus] appear listener error:', e); }
try {
listener();
} catch (e) {
console.warn('[focus] appear listener error:', e);
}
}
}
return _focusTarget;
@@ -311,15 +355,18 @@ export function smoothFocusEmphasis(current, target, elapsedMs, params) {
* every needed property before the next call; never retain it as a snapshot.
* @returns {{factor:number, changed:boolean, transitioning:boolean,active:boolean,desired:number}}
*/
export function advanceSpriteFocus(sprite, {
screenPosition,
cameraDistance,
nowMs,
target = _focusTarget,
params,
spriteHalfWidthPx = 0,
spriteHalfHeightPx = spriteHalfWidthPx,
}) {
export function advanceSpriteFocus(
sprite,
{
screenPosition,
cameraDistance,
nowMs,
target = _focusTarget,
params,
spriteHalfWidthPx = 0,
spriteHalfHeightPx = spriteHalfWidthPx,
},
) {
const tuning = resolvedParams(params);
let state = _spriteStates.get(sprite);
if (!state) {
@@ -369,12 +416,18 @@ export function advanceSpriteFocus(sprite, {
state.desired = desired;
}
const elapsedMs = Math.max(0, nowMs - state.transitionStartMs);
const next = smoothFocusEmphasisResolved(state.transitionFrom, desired, elapsedMs, tuning);
const next = smoothFocusEmphasisResolved(
state.transitionFrom,
desired,
elapsedMs,
tuning,
);
const changed = Math.abs(next - state.factor) > tuning.writeEpsilon;
state.factor = next;
state.desired = desired;
state.wasFarther = tuning.nearerBehavior !== 'dim'
&& Math.abs(desired - tuning.dimFloor) <= tuning.writeEpsilon;
state.wasFarther =
tuning.nearerBehavior !== 'dim' &&
Math.abs(desired - tuning.dimFloor) <= tuning.writeEpsilon;
const transitioning = Math.abs(next - desired) > tuning.writeEpsilon;
const active = Math.abs(next - 1) > tuning.writeEpsilon;
@@ -426,12 +479,18 @@ export function advanceProjectedSpriteFocus(
_advanceResult.desired = 1;
return _advanceResult;
}
const screen = position && scene
? Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, _scratchScreen)
: null;
const cameraDistance = position && camera?.positionWC
? Cesium.Cartesian3.distance(camera.positionWC, position)
: Number.NaN;
const screen =
position && scene
? Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
_scratchScreen,
)
: null;
const cameraDistance =
position && camera?.positionWC
? Cesium.Cartesian3.distance(camera.positionWC, position)
: Number.NaN;
return advanceSpriteFocus(sprite, {
screenPosition: screen,
cameraDistance,
@@ -451,8 +510,10 @@ export function advanceProjectedSpriteFocus(
* @returns {boolean}
*/
export function focusPassIsNeeded(target, activeCount) {
return target !== null && target !== undefined
|| (Number.isFinite(activeCount) && activeCount > 0);
return (
(target !== null && target !== undefined) ||
(Number.isFinite(activeCount) && activeCount > 0)
);
}
/**
@@ -466,8 +527,9 @@ export function nearFarScalarValueAtDistance(scalar, cameraDistanceM) {
if (!scalar || !Number.isFinite(cameraDistanceM)) return 1;
const nearSq = scalar.near * scalar.near;
const farSq = scalar.far * scalar.far;
if (!Number.isFinite(nearSq) || !Number.isFinite(farSq) || farSq <= nearSq) return 1;
const rawT = ((cameraDistanceM * cameraDistanceM) - nearSq) / (farSq - nearSq);
if (!Number.isFinite(nearSq) || !Number.isFinite(farSq) || farSq <= nearSq)
return 1;
const rawT = (cameraDistanceM * cameraDistanceM - nearSq) / (farSq - nearSq);
const t = Math.pow(clamp(rawT, 0, 1), 0.2);
return scalar.nearValue + (scalar.farValue - scalar.nearValue) * t;
}
@@ -507,6 +569,8 @@ export function forgetSpriteFocus(sprite) {
*/
export function focusAlphaNeedsWrite(currentAlpha, nextAlpha, params) {
const tuning = resolvedParams(params);
return !Number.isFinite(currentAlpha)
|| Math.abs(currentAlpha - nextAlpha) > tuning.writeEpsilon;
return (
!Number.isFinite(currentAlpha) ||
Math.abs(currentAlpha - nextAlpha) > tuning.writeEpsilon
);
}
+1 -1
View File
@@ -51,7 +51,7 @@ export function geoidHeight(latDeg, lonDeg) {
if (!egm96Module) {
throw new Error(
'geoid.js: geoidHeight() called before ensureGeoidReady() resolved — ' +
'await ensureGeoidReady() first.'
'await ensureGeoidReady() first.',
);
}
return egm96Module.meanSeaLevel(latDeg, lonDeg);
+29 -1
View File
@@ -1,4 +1,32 @@
import { createGroundFloor } from '../services/groundFloor.js';
import * as terrain from './terrainHeights.js';
const groundFloor = createGroundFloor({ terrain });
export const { GROUND_FLOOR_LIFT_M, MESH_FLOOR_BELOW_PRIOR_M, MESH_FLOOR_ABOVE_PRIOR_M, coarseFloorCoord, floorAltitudeM, displayFloorHeightM, FLOOR_CELL_DEG, NEIGHBOR_FLOOR_MIN_SAMPLES, neighborFloorM, CORRIDOR_MAX_CELLS, CORRIDOR_WALK_STEP_DEG, CELL_HYSTERESIS_DEG, stickyFloorCell, corridorFloorCells, allocateCorridorCells, setMeshFloorPreferred, meshFloorPreferred, reportMeshFloorCell, meshFloorSampleWithinPrior, reportValidatedMeshFloorCell, cachedMeshFloor, _clearMeshFloorCellsForTest, cachedGroundFloor, FLOOR_RESOLVE_DEADLINE_MS, resolveGroundFloorCellsBounded, resolveGroundFloorCells, warmGroundFloor } = groundFloor;
export const {
GROUND_FLOOR_LIFT_M,
MESH_FLOOR_BELOW_PRIOR_M,
MESH_FLOOR_ABOVE_PRIOR_M,
coarseFloorCoord,
floorAltitudeM,
displayFloorHeightM,
FLOOR_CELL_DEG,
NEIGHBOR_FLOOR_MIN_SAMPLES,
neighborFloorM,
CORRIDOR_MAX_CELLS,
CORRIDOR_WALK_STEP_DEG,
CELL_HYSTERESIS_DEG,
stickyFloorCell,
corridorFloorCells,
allocateCorridorCells,
setMeshFloorPreferred,
meshFloorPreferred,
reportMeshFloorCell,
meshFloorSampleWithinPrior,
reportValidatedMeshFloorCell,
cachedMeshFloor,
_clearMeshFloorCellsForTest,
cachedGroundFloor,
FLOOR_RESOLVE_DEADLINE_MS,
resolveGroundFloorCellsBounded,
resolveGroundFloorCells,
warmGroundFloor,
} = groundFloor;
+3 -1
View File
@@ -1,4 +1,6 @@
import { createGroundSnap as createSnap } from '../services/groundSnap.js';
import * as groundFloor from './groundFloor.js';
/** Compatibility constructor using the default floor cache. */
export function createGroundSnap() { return createSnap({ groundFloor }); }
export function createGroundSnap() {
return createSnap({ groundFloor });
}
+274
View File
@@ -0,0 +1,274 @@
/**
* @module gtfsRealtime
* @description Minimal GTFS-Realtime decoder for VehiclePosition feeds.
*
* Decodes only what the Transit layer needs from a `FeedMessage` — the header
* and every entity's `VehiclePosition` — straight from the protobuf wire
* format with `pbf` (already a dependency via the TomTom flow tiles). No
* `gtfs-realtime-bindings`, no protobufjs, no generated code: the GTFS-RT
* schema is stable, and field numbers are the contract.
*
* Field numbers (gtfs-realtime.proto, v2.0):
* FeedMessage 1 header, 2 entity[]
* FeedHeader 1 gtfs_realtime_version, 2 incrementality, 3 timestamp
* FeedEntity 1 id, 2 is_deleted, 3 trip_update, 4 vehicle, 5 alert
* VehiclePosition 1 trip, 2 position, 3 current_stop_sequence,
* 4 current_status, 5 timestamp, 6 congestion_level,
* 7 stop_id, 8 vehicle, 9 occupancy_status
* TripDescriptor 1 trip_id, 2 start_time, 3 start_date,
* 4 schedule_relationship, 5 route_id, 6 direction_id
* Position 1 latitude, 2 longitude, 3 bearing, 4 odometer, 5 speed
* VehicleDescriptor 1 id, 2 label, 3 license_plate
*
* Unknown fields (extensions, newer additions) are skipped by pbf, so a feed
* that carries OVapi/NYCT extensions decodes the same as a plain one.
*
* Decoding is bounded, because a byte cap alone does not bound what a decode
* COSTS: entities past `GTFS_MAX_ENTITIES` are left unread so pbf skips them
* whole (the result says it truncated), and every string field — the feed
* header's version included — is refused past `GTFS_MAX_STRING_CHARS` rather
* than carried into the snapshot.
*
* Pure: safe to import from the browser layer, the Vite proxy, and node:test.
*/
import { PbfReader } from 'pbf';
/** VehiclePosition.VehicleStopStatus enum → label. */
export const VEHICLE_STOP_STATUS = Object.freeze({
0: 'INCOMING_AT',
1: 'STOPPED_AT',
2: 'IN_TRANSIT_TO',
});
/** VehiclePosition.OccupancyStatus enum → label. */
export const OCCUPANCY_STATUS = Object.freeze({
0: 'EMPTY',
1: 'MANY_SEATS_AVAILABLE',
2: 'FEW_SEATS_AVAILABLE',
3: 'STANDING_ROOM_ONLY',
4: 'CRUSHED_STANDING_ROOM_ONLY',
5: 'FULL',
6: 'NOT_ACCEPTING_PASSENGERS',
7: 'NO_DATA_AVAILABLE',
8: 'NOT_BOARDABLE',
});
/**
* Hard ceiling on decoded entities. Every registered feed is a metropolitan or
* national fleet — the largest observed is a few thousand vehicles — so this is
* two orders of magnitude above any honest payload.
*/
export const GTFS_MAX_ENTITIES = 50_000;
/** Longest accepted string field. GTFS ids, labels and stop ids are short. */
export const GTFS_MAX_STRING_CHARS = 256;
/** FeedHeader.Incrementality: only FULL_DATASET carries a complete snapshot. */
export const GTFS_INCREMENTALITY_FULL_DATASET = 0;
export const GTFS_INCREMENTALITY_DIFFERENTIAL = 1;
/**
* Read a length-delimited string, refusing one that is implausibly long.
* An over-long field marks its containing message `oversize`, and the whole
* record is then dropped — never truncated. Half an id is a different vehicle,
* not a shorter name for the same one.
* @param {object} pbf
* @param {object} target Message being read, flagged when the field is refused.
* @returns {string|null}
*/
function readBoundedString(pbf, target) {
const value = pbf.readString();
if (value.length <= GTFS_MAX_STRING_CHARS) return value;
target.oversize = true;
return null;
}
function readFeedHeader(tag, header, pbf) {
if (tag === 1) header.version = readBoundedString(pbf, header);
else if (tag === 2) header.incrementality = pbf.readVarint();
else if (tag === 3) header.timestamp = pbf.readVarint();
}
function readTripDescriptor(tag, trip, pbf) {
if (tag === 1) trip.tripId = readBoundedString(pbf, trip);
else if (tag === 2) trip.startTime = readBoundedString(pbf, trip);
else if (tag === 3) trip.startDate = readBoundedString(pbf, trip);
else if (tag === 4) trip.scheduleRelationship = pbf.readVarint();
else if (tag === 5) trip.routeId = readBoundedString(pbf, trip);
else if (tag === 6) trip.directionId = pbf.readVarint();
}
function readPosition(tag, position, pbf) {
if (tag === 1) position.latitude = pbf.readFloat();
else if (tag === 2) position.longitude = pbf.readFloat();
else if (tag === 3) position.bearing = pbf.readFloat();
else if (tag === 4) position.odometer = pbf.readDouble();
else if (tag === 5) position.speed = pbf.readFloat();
}
function readVehicleDescriptor(tag, descriptor, pbf) {
if (tag === 1) descriptor.id = readBoundedString(pbf, descriptor);
else if (tag === 2) descriptor.label = readBoundedString(pbf, descriptor);
else if (tag === 3)
descriptor.licensePlate = readBoundedString(pbf, descriptor);
}
function readVehiclePosition(tag, vehicle, pbf) {
if (tag === 1) vehicle.trip = pbf.readMessage(readTripDescriptor, {});
else if (tag === 2) vehicle.position = pbf.readMessage(readPosition, {});
else if (tag === 3) vehicle.currentStopSequence = pbf.readVarint();
else if (tag === 4) vehicle.currentStatus = pbf.readVarint();
else if (tag === 5) vehicle.timestamp = pbf.readVarint();
else if (tag === 6) vehicle.congestionLevel = pbf.readVarint();
else if (tag === 7) vehicle.stopId = readBoundedString(pbf, vehicle);
else if (tag === 8)
vehicle.vehicle = pbf.readMessage(readVehicleDescriptor, {});
else if (tag === 9) vehicle.occupancyStatus = pbf.readVarint();
}
function readFeedEntity(tag, entity, pbf) {
if (tag === 1) entity.id = readBoundedString(pbf, entity);
else if (tag === 2) entity.isDeleted = pbf.readBoolean();
else if (tag === 4) entity.vehicle = pbf.readMessage(readVehiclePosition, {});
// 3 (trip_update) and 5 (alert) are skipped: pbf advances past any tag the
// reader leaves untouched.
}
function readFeedMessage(tag, message, pbf) {
if (tag === 1) message.header = pbf.readMessage(readFeedHeader, {});
else if (tag === 2) {
// Past the cap the field is left UNREAD. pbf skips any field its handler
// did not consume, so the excess costs one length varint each instead of a
// full nested decode that is then thrown away.
if (message.entities.length >= GTFS_MAX_ENTITIES) {
message.truncated = true;
return;
}
message.entities.push(pbf.readMessage(readFeedEntity, {}));
}
}
/**
* Decode a raw GTFS-Realtime FeedMessage.
* @param {Uint8Array|ArrayBuffer} bytes Protobuf wire bytes.
* @returns {{ header: {version?: string, incrementality?: number, timestamp?: number},
* entities: object[], truncated: boolean }}
*/
export function decodeFeedMessage(bytes) {
const view = bytes instanceof Uint8Array ? bytes : new Uint8Array(bytes);
const pbf = new PbfReader(view);
return pbf.readFields(readFeedMessage, {
header: {},
entities: [],
truncated: false,
});
}
function finiteOrNull(value) {
return Number.isFinite(value) ? value : null;
}
function nonEmptyString(value) {
const text = typeof value === 'string' ? value.trim() : '';
return text ? text : null;
}
/**
* True when a lat/lon pair is a usable surface position. Rejects non-finite
* values, out-of-range degrees, and the (0,0) null island a cold GPS reports.
* @param {number} lat
* @param {number} lon
* @returns {boolean}
*/
export function isPlausibleVehiclePosition(lat, lon) {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return false;
if (Math.abs(lat) > 90 || Math.abs(lon) > 180) return false;
if (Math.abs(lat) < 1e-6 && Math.abs(lon) < 1e-6) return false;
return true;
}
/**
* Flatten one decoded FeedEntity into the record the Transit layer renders,
* or null when the entity carries no usable vehicle position.
* @param {object} entity Decoded FeedEntity.
* @returns {object|null}
*/
export function normalizeVehicleEntity(entity) {
if (!entity || entity.isDeleted === true) return null;
const vehicle = entity.vehicle;
const position = vehicle?.position;
if (!vehicle || !position) return null;
// Any refused (over-long) string anywhere in this entity makes the whole
// record untrustworthy — drop it rather than render a half-identified dot.
if (
entity.oversize ||
vehicle.oversize ||
vehicle.trip?.oversize ||
vehicle.vehicle?.oversize
) {
return null;
}
const lat = finiteOrNull(position.latitude);
const lon = finiteOrNull(position.longitude);
if (!isPlausibleVehiclePosition(lat, lon)) return null;
const id = nonEmptyString(vehicle.vehicle?.id) || nonEmptyString(entity.id);
if (!id) return null;
const bearing = finiteOrNull(position.bearing);
const speed = finiteOrNull(position.speed);
const timestamp =
Number.isFinite(vehicle.timestamp) && vehicle.timestamp > 0
? vehicle.timestamp
: null;
return {
id,
lat: Number(lat.toFixed(6)),
lon: Number(lon.toFixed(6)),
bearing: bearing === null ? null : ((bearing % 360) + 360) % 360,
speedMps: speed === null || speed < 0 ? null : speed,
timestamp,
routeId: nonEmptyString(vehicle.trip?.routeId),
tripId: nonEmptyString(vehicle.trip?.tripId),
directionId: Number.isInteger(vehicle.trip?.directionId)
? vehicle.trip.directionId
: null,
label: nonEmptyString(vehicle.vehicle?.label),
stopId: nonEmptyString(vehicle.stopId),
status: VEHICLE_STOP_STATUS[vehicle.currentStatus] || null,
occupancy: OCCUPANCY_STATUS[vehicle.occupancyStatus] || null,
};
}
/**
* Decode a VehiclePositions feed into the compact snapshot the proxy serves.
* Duplicate vehicle ids keep the newest timestamp (feeds occasionally repeat
* a vehicle across two trip entities during a handover).
* @param {Uint8Array|ArrayBuffer} bytes Protobuf wire bytes.
* @returns {{ version: string|null, timestamp: number|null, incrementality: number,
* entityCount: number, truncated: boolean, vehicles: object[] }}
*/
export function decodeVehiclePositions(bytes) {
const message = decodeFeedMessage(bytes);
const byId = new Map();
for (const entity of message.entities) {
const record = normalizeVehicleEntity(entity);
if (!record) continue;
const existing = byId.get(record.id);
if (!existing || (record.timestamp ?? 0) >= (existing.timestamp ?? 0)) {
byId.set(record.id, record);
}
}
const headerTimestamp = message.header?.timestamp;
const incrementality = Number.isFinite(message.header?.incrementality)
? message.header.incrementality
: GTFS_INCREMENTALITY_FULL_DATASET;
return {
version: nonEmptyString(message.header?.version),
timestamp:
Number.isFinite(headerTimestamp) && headerTimestamp > 0
? headerTimestamp
: null,
incrementality,
entityCount: message.entities.length,
truncated: message.truncated === true,
vehicles: [...byId.values()],
};
}
+348
View File
@@ -0,0 +1,348 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import {
GTFS_MAX_ENTITIES,
GTFS_MAX_STRING_CHARS,
decodeFeedMessage,
decodeVehiclePositions,
isPlausibleVehiclePosition,
normalizeVehicleEntity,
} from './gtfsRealtime.js';
/** Encode a nested message with a fresh writer and embed it as a bytes field. */
function embed(writer, tag, build) {
const inner = new PbfWriter();
build(inner);
writer.writeBytesField(tag, inner.finish());
}
/**
* Hand-encode one FeedEntity carrying a VehiclePosition, from the proto field
* numbers — the same contract the decoder reads, written independently.
*/
function writeVehicleEntity(
writer,
{
entityId,
vehicleId,
label,
lat,
lon,
bearing,
speed,
timestamp,
routeId,
tripId,
directionId,
stopId,
status,
occupancy,
isDeleted,
extraUnknownFields = false,
},
) {
embed(writer, 2, (entity) => {
if (entityId != null) entity.writeStringField(1, entityId);
if (isDeleted) entity.writeBooleanField(2, true);
embed(entity, 4, (vehicle) => {
if (routeId != null || tripId != null || directionId != null) {
embed(vehicle, 1, (trip) => {
if (tripId != null) trip.writeStringField(1, tripId);
if (routeId != null) trip.writeStringField(5, routeId);
if (directionId != null) trip.writeVarintField(6, directionId);
});
}
if (lat != null) {
embed(vehicle, 2, (position) => {
position.writeFloatField(1, lat);
position.writeFloatField(2, lon);
if (bearing != null) position.writeFloatField(3, bearing);
if (speed != null) position.writeFloatField(5, speed);
if (extraUnknownFields) position.writeDoubleField(4, 123456.5); // odometer
});
}
if (status != null) vehicle.writeVarintField(4, status);
if (timestamp != null) vehicle.writeVarintField(5, timestamp);
if (stopId != null) vehicle.writeStringField(7, stopId);
if (vehicleId != null || label != null) {
embed(vehicle, 8, (descriptor) => {
if (vehicleId != null) descriptor.writeStringField(1, vehicleId);
if (label != null) descriptor.writeStringField(2, label);
});
}
if (occupancy != null) vehicle.writeVarintField(9, occupancy);
if (extraUnknownFields)
vehicle.writeStringField(1001, 'operator-extension');
});
});
}
function encodeFeed(
entities,
{ version = '2.0', timestamp = 1_788_936_000 } = {},
) {
const writer = new PbfWriter();
embed(writer, 1, (header) => {
header.writeStringField(1, version);
header.writeVarintField(2, 0);
header.writeVarintField(3, timestamp);
});
for (const entity of entities) writeVehicleEntity(writer, entity);
return writer.finish();
}
test('decodes header and every VehiclePosition field the layer renders', () => {
const bytes = encodeFeed([
{
entityId: 'e1',
vehicleId: 'bus-17',
label: '1557',
lat: 44.927551,
lon: -93.386711,
bearing: 248,
speed: 11.2,
timestamp: 1_788_936_945,
routeId: '17',
tripId: '1134773',
directionId: 0,
stopId: '57458',
status: 1,
occupancy: 2,
},
]);
const snapshot = decodeVehiclePositions(bytes);
assert.equal(snapshot.version, '2.0');
assert.equal(snapshot.timestamp, 1_788_936_000);
assert.equal(snapshot.entityCount, 1);
assert.equal(snapshot.vehicles.length, 1);
const [v] = snapshot.vehicles;
assert.equal(v.id, 'bus-17');
assert.equal(v.label, '1557');
assert.ok(Math.abs(v.lat - 44.927551) < 1e-5);
assert.ok(Math.abs(v.lon + 93.386711) < 1e-5);
assert.equal(v.bearing, 248);
assert.ok(Math.abs(v.speedMps - 11.2) < 1e-5);
assert.equal(v.timestamp, 1_788_936_945);
assert.equal(v.routeId, '17');
assert.equal(v.tripId, '1134773');
assert.equal(v.directionId, 0);
assert.equal(v.stopId, '57458');
assert.equal(v.status, 'STOPPED_AT');
assert.equal(v.occupancy, 'FEW_SEATS_AVAILABLE');
});
test('unknown and extension fields are skipped, not misread', () => {
const bytes = encodeFeed([
{ entityId: 'x', lat: 51.3, lon: 5.33, extraUnknownFields: true },
]);
const snapshot = decodeVehiclePositions(bytes);
assert.equal(snapshot.vehicles.length, 1);
assert.equal(snapshot.vehicles[0].id, 'x');
assert.ok(Math.abs(snapshot.vehicles[0].lat - 51.3) < 1e-5);
});
test('entities without a usable position are dropped and never throw', () => {
const bytes = encodeFeed([
{ entityId: 'no-position' },
{ entityId: 'deleted', lat: 1, lon: 1, isDeleted: true },
{ entityId: 'null-island', lat: 0, lon: 0 },
{ entityId: 'out-of-range', lat: 91, lon: 10 },
{ entityId: 'nan', lat: Number.NaN, lon: 10 },
{ entityId: 'keeper', lat: 60.17, lon: 24.94 },
]);
const snapshot = decodeVehiclePositions(bytes);
assert.equal(snapshot.entityCount, 6);
assert.deepEqual(
snapshot.vehicles.map((v) => v.id),
['keeper'],
);
});
test('vehicle id falls back to the entity id and the vehicle is dropped when neither exists', () => {
const bytes = encodeFeed([
{ entityId: 'entity-only', lat: 42.3, lon: -71.1 },
{ lat: 42.3, lon: -71.1 },
]);
const snapshot = decodeVehiclePositions(bytes);
assert.deepEqual(
snapshot.vehicles.map((v) => v.id),
['entity-only'],
);
});
test('duplicate vehicle ids keep the newest timestamp', () => {
const bytes = encodeFeed([
{ entityId: 'a', vehicleId: 'v1', lat: 42.3, lon: -71.1, timestamp: 100 },
{ entityId: 'b', vehicleId: 'v1', lat: 42.31, lon: -71.11, timestamp: 200 },
{ entityId: 'c', vehicleId: 'v1', lat: 42.32, lon: -71.12, timestamp: 150 },
]);
const snapshot = decodeVehiclePositions(bytes);
assert.equal(snapshot.vehicles.length, 1);
assert.equal(snapshot.vehicles[0].timestamp, 200);
assert.ok(Math.abs(snapshot.vehicles[0].lat - 42.31) < 1e-5);
});
test('bearing is normalized to [0, 360) and negative speed is treated as unknown', () => {
const bytes = encodeFeed([
{ entityId: 'neg', lat: 30.2, lon: -97.7, bearing: -90, speed: -1 },
{ entityId: 'wrap', lat: 30.2, lon: -97.7, bearing: 450 },
]);
const [neg, wrap] = decodeVehiclePositions(bytes).vehicles;
assert.equal(neg.bearing, 270);
assert.equal(neg.speedMps, null);
assert.equal(wrap.bearing, 90);
});
test('missing header yields null version/timestamp rather than garbage', () => {
const writer = new PbfWriter();
writeVehicleEntity(writer, { entityId: 'solo', lat: 10, lon: 10 });
const snapshot = decodeVehiclePositions(writer.finish());
assert.equal(snapshot.version, null);
assert.equal(snapshot.timestamp, null);
assert.equal(snapshot.vehicles.length, 1);
});
test('decodeFeedMessage accepts an ArrayBuffer and an empty feed', () => {
const empty = decodeFeedMessage(new ArrayBuffer(0));
assert.deepEqual(empty, { header: {}, entities: [], truncated: false });
const bytes = encodeFeed([]);
const asBuffer = bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
);
assert.equal(decodeFeedMessage(asBuffer).header.version, '2.0');
});
test('isPlausibleVehiclePosition and normalizeVehicleEntity guard their inputs', () => {
assert.equal(isPlausibleVehiclePosition(45, 90), true);
assert.equal(isPlausibleVehiclePosition(0, 0), false);
assert.equal(isPlausibleVehiclePosition(-90.0001, 0), false);
assert.equal(isPlausibleVehiclePosition(1, Infinity), false);
assert.equal(normalizeVehicleEntity(null), null);
assert.equal(normalizeVehicleEntity({ id: 'no-vehicle' }), null);
assert.equal(
normalizeVehicleEntity({
id: 'v',
vehicle: { position: { latitude: 1, longitude: 2 }, currentStatus: 99 },
})?.status,
null,
);
});
test('the decode is bounded by entity count as well as by bytes', () => {
const entities = [];
for (let index = 0; index < GTFS_MAX_ENTITIES + 25; index += 1) {
entities.push({
entityId: `e${index}`,
vehicleId: `v${index}`,
lat: 42 + index * 1e-6,
lon: -71,
timestamp: 1_788_936_000,
});
}
const decoded = decodeVehiclePositions(encodeFeed(entities));
assert.equal(decoded.entityCount, GTFS_MAX_ENTITIES);
assert.equal(decoded.truncated, true);
assert.equal(decoded.vehicles.length, GTFS_MAX_ENTITIES);
// A feed inside the cap is not flagged.
assert.equal(
decodeVehiclePositions(encodeFeed(entities.slice(0, 3))).truncated,
false,
);
});
test('an implausibly long string drops the whole record rather than truncating an id', () => {
const long = 'x'.repeat(GTFS_MAX_STRING_CHARS + 1);
const decoded = decodeVehiclePositions(
encodeFeed([
{
entityId: 'ok',
vehicleId: 'good',
lat: 42.1,
lon: -71.1,
timestamp: 1_788_936_000,
},
{
entityId: 'bad',
vehicleId: long,
lat: 42.2,
lon: -71.2,
timestamp: 1_788_936_000,
},
{
entityId: 'bad-route',
vehicleId: 'v3',
routeId: long,
lat: 42.3,
lon: -71.3,
timestamp: 1_788_936_000,
},
]),
);
// The entity is still counted — the decoder had to walk past it — but it is
// never rendered, because half an id is a different vehicle.
assert.equal(decoded.entityCount, 3);
assert.deepEqual(
decoded.vehicles.map((vehicle) => vehicle.id),
['good'],
);
// A string exactly at the cap is fine.
const atCap = 'y'.repeat(GTFS_MAX_STRING_CHARS);
const kept = decodeVehiclePositions(
encodeFeed([
{ entityId: 'e', vehicleId: atCap, lat: 42, lon: -71, timestamp: 1 },
]),
);
assert.deepEqual(
kept.vehicles.map((vehicle) => vehicle.id),
[atCap],
);
});
test('incrementality is reported, not silently discarded', () => {
assert.equal(decodeVehiclePositions(encodeFeed([])).incrementality, 0);
const writer = new PbfWriter();
embed(writer, 1, (header) => {
header.writeStringField(1, '2.0');
header.writeVarintField(2, 1);
header.writeVarintField(3, 1_788_936_000);
});
assert.equal(decodeVehiclePositions(writer.finish()).incrementality, 1);
});
test('the feed header version is bounded like every other string', () => {
const writer = new PbfWriter();
embed(writer, 1, (header) => {
header.writeStringField(1, 'v'.repeat(GTFS_MAX_STRING_CHARS + 1));
header.writeVarintField(2, 0);
header.writeVarintField(3, 1_788_936_000);
});
const decoded = decodeVehiclePositions(writer.finish());
// Refused, not carried: an unbounded header field is the one string a feed
// can grow without the entity cap ever seeing it.
assert.equal(decoded.version, null);
assert.equal(decoded.timestamp, 1_788_936_000);
});
test('entities past the cap are skipped whole rather than decoded and discarded', () => {
const decoded = decodeVehiclePositions(
encodeFeed(
Array.from({ length: GTFS_MAX_ENTITIES + 5 }, (_, index) => ({
entityId: `e${index}`,
vehicleId: `v${index}`,
lat: 42 + index * 1e-6,
lon: -71,
timestamp: 1_788_936_000,
})),
),
);
assert.equal(decoded.entityCount, GTFS_MAX_ENTITIES);
assert.equal(decoded.truncated, true);
// The skipped tail never becomes an object, so the last retained vehicle is
// the one at the cap and nothing beyond it appears.
assert.equal(
decoded.vehicles.some((item) => item.id === `v${GTFS_MAX_ENTITIES}`),
false,
);
});
+150 -14
View File
@@ -49,7 +49,12 @@ const _scratchWorldForward = new Cesium.Cartesian3();
* unavailable (off-screen/behind camera/degenerate).
* @returns {number|null} Rotation in radians, or `previous` when unknown.
*/
export function screenProjectedRotation(scene, position, courseDeg, previous = null) {
export function screenProjectedRotation(
scene,
position,
courseDeg,
previous = null,
) {
const camera = scene?.camera;
if (!camera?.rightWC || !camera?.upWC || !position) return previous;
@@ -58,20 +63,26 @@ export function screenProjectedRotation(scene, position, courseDeg, previous = n
Math.sin(courseRad) * FORWARD_PROBE_M,
Math.cos(courseRad) * FORWARD_PROBE_M,
0,
_scratchForward
_scratchForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
position,
Cesium.Ellipsoid.WGS84,
_scratchEnu,
);
Cesium.Matrix4.multiplyByPointAsVector(
enu,
_scratchForward,
_scratchWorldForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position, Cesium.Ellipsoid.WGS84, _scratchEnu);
Cesium.Matrix4.multiplyByPointAsVector(enu, _scratchForward, _scratchWorldForward);
// Screen x follows camera-right. Window y grows downward, the opposite of
// camera-up. Projecting the vector itself avoids clipping/behind-camera
// failure modes from the old forward-point worldToWindowCoordinates probe.
const dx = Cesium.Cartesian3.dot(_scratchWorldForward, camera.rightWC);
const dy = -Cesium.Cartesian3.dot(_scratchWorldForward, camera.upWC);
if (
(dx * dx + dy * dy)
< MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M
) return previous;
if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M)
return previous;
// Window y grows downward; rotation 0 = icon pointing screen-up.
// Icon direction in window coords after CCW rotation r is (-sin r, -cos r),
@@ -94,13 +105,20 @@ export function stabilizeScreenRotation(
next,
deadbandRad = ROTATION_DEADBAND_RAD,
) {
if (!Number.isFinite(next)) return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(next))
return Number.isFinite(previous) ? previous : null;
if (!Number.isFinite(previous)) return next;
const delta = Math.atan2(Math.sin(next - previous), Math.cos(next - previous));
const delta = Math.atan2(
Math.sin(next - previous),
Math.cos(next - previous),
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
const _occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, new Cesium.Cartesian3());
const _occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(),
);
/**
* Half-width of the crossfade band centred on the ellipsoid silhouette, in
@@ -169,7 +187,11 @@ const _wgs84OneOverRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
* @param {number} [featherRad=HORIZON_FEATHER_RAD] Half-width of the blend band.
* @returns {number} 0 (ground behind) … 1 (sky behind).
*/
export function skyBackdropFactor(cameraPosition, position, featherRad = HORIZON_FEATHER_RAD) {
export function skyBackdropFactor(
cameraPosition,
position,
featherRad = HORIZON_FEATHER_RAD,
) {
if (!cameraPosition || !position) return 0;
const s = _wgs84OneOverRadii;
@@ -236,6 +258,120 @@ export function horizonOccluder(camera) {
*/
export function cameraPoseSignature(camera) {
const p = camera.positionWC;
return `${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${camera.heading.toFixed(3)}:${camera.pitch.toFixed(3)}:${camera.roll.toFixed(3)}`;
return (
`${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${camera.heading.toFixed(3)}:${camera.pitch.toFixed(3)}:${camera.roll.toFixed(3)}`
);
}
/**
* Meters ahead used by the exact projection below. Short on purpose: the point
* of a perspective projection is that it is LOCAL to the contact, and a two
* kilometre probe on a bus at six hundred metres would sample a part of the
* frustum the vehicle is nowhere near.
*/
const NEAR_PROBE_M = 30;
const _scratchProbe = new Cesium.Cartesian3();
const _scratchWindowAt = new Cesium.Cartesian2();
const _scratchWindowAhead = new Cesium.Cartesian2();
/**
* Billboard rotation for a SURFACE contact, projected exactly — perspective
* division included — instead of through the camera-basis approximation.
*
* `screenProjectedRotation` above deliberately projects the course vector onto
* the camera's right/up basis, which is orthographic: exact at the viewport
* centre and an approximation away from it. That is the right trade for
* aircraft, where the alternative loses continuity through a tracked orbit and
* the contacts are far enough away for the error to be small.
*
* It is the wrong trade for street-level vehicles. A probe with a real Cesium
* camera at 600 m and −45° pitch, on a northbound contact 350 m right of
* centre, put the orthographic answer at 0° where the true screen direction of
* travel was 22.5°. At that pitch and that range the vehicles fill the frame
* away from the centre, and every one of them points visibly wrong.
*
* So this projects two nearby world points through the actual view-projection
* and reads the angle between them on screen. When either point cannot be
* projected — behind the camera, off the frustum, degenerate — it falls back to
* the camera-basis answer rather than inventing one.
*
* @param {Cesium.Scene} scene The scene (projection source).
* @param {Cesium.Cartesian3} position Entity world position.
* @param {number} courseDeg Course in degrees clockwise from north.
* @param {number|null} previous Rotation to keep when projection is unavailable.
* @returns {number|null} Rotation in radians, or the fallback.
*/
export function perspectiveProjectedRotation(
scene,
position,
courseDeg,
previous = null,
) {
if (!scene?.camera || !position || !Number.isFinite(courseDeg)) {
return previous;
}
const courseRad = Cesium.Math.toRadians(courseDeg);
Cesium.Cartesian3.fromElements(
Math.sin(courseRad) * NEAR_PROBE_M,
Math.cos(courseRad) * NEAR_PROBE_M,
0,
_scratchForward,
);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
position,
Cesium.Ellipsoid.WGS84,
_scratchEnu,
);
Cesium.Matrix4.multiplyByPointAsVector(
enu,
_scratchForward,
_scratchWorldForward,
);
Cesium.Cartesian3.add(position, _scratchWorldForward, _scratchProbe);
const at = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
_scratchWindowAt,
);
const ahead = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
_scratchProbe,
_scratchWindowAhead,
);
if (!at || !ahead) {
return screenProjectedRotation(scene, position, courseDeg, previous);
}
const dx = ahead.x - at.x;
const dy = ahead.y - at.y;
const separation = Math.hypot(dx, dy);
// Window y grows downward; rotation 0 = icon pointing screen-up.
const exact = Math.atan2(-dx, -dy);
if (separation >= PERSPECTIVE_BLEND_MAX_PX) return exact;
// Below a pixel or so of separation the exact answer is dominated by
// projection noise, and above it the camera-basis answer is the wrong one
// by up to twenty-odd degrees. A hard cutoff between the two flipped a
// sprite by 23° for a 20 m change of camera altitude; the two answers are
// blended across the band instead, the short way round, so the rotation is
// continuous through it.
const basis = screenProjectedRotation(scene, position, courseDeg, previous);
if (!Number.isFinite(basis)) return exact;
if (separation <= PERSPECTIVE_BLEND_MIN_PX) return basis;
const weight =
(separation - PERSPECTIVE_BLEND_MIN_PX) /
(PERSPECTIVE_BLEND_MAX_PX - PERSPECTIVE_BLEND_MIN_PX);
const delta = Math.atan2(Math.sin(exact - basis), Math.cos(exact - basis));
return basis + delta * weight;
}
/**
* Probe separations (px) between which the exact and camera-basis answers
* are blended. At or below the floor the camera-basis answer is used alone;
* at or above the ceiling the exact one.
*/
export const PERSPECTIVE_BLEND_MIN_PX = 0.5;
export const PERSPECTIVE_BLEND_MAX_PX = 3;
/** Exported for tests: how far ahead the exact projection probes. */
export const PERSPECTIVE_PROBE_M = NEAR_PROBE_M;
+342 -53
View File
@@ -47,8 +47,12 @@ test('off-center oblique contacts pin the documented perspective divergence', ()
const right = new Cesium.Cartesian3(0, 1, 0);
const up = new Cesium.Cartesian3(Math.sin(pitch), 0, Math.cos(pitch));
const forward = new Cesium.Cartesian3(-Math.cos(pitch), 0, Math.sin(pitch));
const basisRotation = screenProjectedRotation({ camera: { rightWC: right, upWC: up } },
equatorPosition, 0, null);
const basisRotation = screenProjectedRotation(
{ camera: { rightWC: right, upWC: up } },
equatorPosition,
0,
null,
);
// Exact pinhole derivative for a contact 2 km right of center and 5 km in
// front. North has a depth component under this oblique camera, so exact
@@ -65,26 +69,29 @@ test('off-center oblique contacts pin the documented perspective divergence', ()
const exactRotation = Math.atan2(-exactScreenX, exactScreenUp);
assert.ok(Math.abs(basisRotation) < 1e-12);
assert.ok(Math.abs(wrappedDelta(exactRotation, basisRotation)) > Cesium.Math.toRadians(5));
assert.ok(
Math.abs(wrappedDelta(exactRotation, basisRotation)) >
Cesium.Math.toRadians(5),
);
});
test('screen rotation holds sub-degree projection noise', () => {
const previous = 1;
assert.equal(
stabilizeScreenRotation(previous, previous + (0.25 * Math.PI / 180)),
stabilizeScreenRotation(previous, previous + (0.25 * Math.PI) / 180),
previous,
);
});
test('screen rotation accepts deliberate camera-orbit movement', () => {
const previous = 1;
const next = previous + (2 * Math.PI / 180);
const next = previous + (2 * Math.PI) / 180;
assert.equal(stabilizeScreenRotation(previous, next), next);
});
test('screen rotation compares across the wrapped angle boundary', () => {
const previous = Math.PI - (0.1 * Math.PI / 180);
const next = -Math.PI + (0.1 * Math.PI / 180);
const previous = Math.PI - (0.1 * Math.PI) / 180;
const next = -Math.PI + (0.1 * Math.PI) / 180;
assert.equal(stabilizeScreenRotation(previous, next), previous);
});
@@ -102,10 +109,12 @@ const cruiseCamera = Cesium.Cartesian3.fromDegrees(0, 0, CRUISE_M);
* tangent condition is exact here and the expected answer is derived, not
* guessed.
*/
const tangentLonDeg = Cesium.Math.toDegrees(Math.acos(
Cesium.Ellipsoid.WGS84.maximumRadius
/ (Cesium.Ellipsoid.WGS84.maximumRadius + CRUISE_M),
));
const tangentLonDeg = Cesium.Math.toDegrees(
Math.acos(
Cesium.Ellipsoid.WGS84.maximumRadius /
(Cesium.Ellipsoid.WGS84.maximumRadius + CRUISE_M),
),
);
test('a contact above the silhouette is read against sky', () => {
// Another aircraft at the same flight level 200 km ahead. The chord between
@@ -124,7 +133,10 @@ test('a contact below the silhouette keeps ground behind it', () => {
// the horizon, so the plate has real imagery to separate the text from.
const below = Cesium.Cartesian3.fromDegrees(30_000 / 111_320, 0, 2_000);
assert.equal(skyBackdropFactor(cruiseCamera, below), 0);
assert.equal(skyBackdropFactor(cruiseCamera, Cesium.Cartesian3.fromDegrees(0.05, 0, 0)), 0);
assert.equal(
skyBackdropFactor(cruiseCamera, Cesium.Cartesian3.fromDegrees(0.05, 0, 0)),
0,
);
});
test('the silhouette itself lands exactly mid-band', () => {
@@ -144,10 +156,12 @@ test('the silhouette itself lands exactly mid-band', () => {
function climbSweep(step = 500) {
const samples = [];
for (let height = 0; height <= 12_000; height += step) {
samples.push(skyBackdropFactor(
cruiseCamera,
Cesium.Cartesian3.fromDegrees(100_000 / 111_320, 0, height),
));
samples.push(
skyBackdropFactor(
cruiseCamera,
Cesium.Cartesian3.fromDegrees(100_000 / 111_320, 0, height),
),
);
}
return samples;
}
@@ -163,9 +177,16 @@ test('the band lerps monotonically and saturates on both sides', () => {
);
}
assert.equal(samples[0], 0, 'well below the horizon is fully grounded');
assert.equal(samples[samples.length - 1], 1, 'well above the horizon is fully sky');
assert.equal(
samples[samples.length - 1],
1,
'well above the horizon is fully sky',
);
const partial = samples.filter((value) => value > 0 && value < 1);
assert.ok(partial.length >= 3, `expected a real blend band, saw ${partial.length} partial samples`);
assert.ok(
partial.length >= 3,
`expected a real blend band, saw ${partial.length} partial samples`,
);
});
test('the band, not the geometry, is what smooths the crossing', () => {
@@ -174,13 +195,19 @@ test('the band, not the geometry, is what smooths the crossing', () => {
// if the two ever get conflated, only one of these two tests goes red.
const hard = [];
for (let height = 0; height <= 12_000; height += 500) {
hard.push(skyBackdropFactor(
cruiseCamera,
Cesium.Cartesian3.fromDegrees(100_000 / 111_320, 0, height),
0,
));
hard.push(
skyBackdropFactor(
cruiseCamera,
Cesium.Cartesian3.fromDegrees(100_000 / 111_320, 0, height),
0,
),
);
}
assert.deepEqual([...new Set(hard)], [0, 1], 'a zero band must produce only the two end states');
assert.deepEqual(
[...new Set(hard)],
[0, 1],
'a zero band must produce only the two end states',
);
});
/**
@@ -200,12 +227,19 @@ test('below the ellipsoid, a contact against open sky still reads as sky', () =>
// ~6.5° above eye level — the whole band is 1.09° per side, so this is not a
// near call. Before the fix a sub-ellipsoid camera fell into the degenerate
// guard and every one of these came back 0: a row of dark boxes on empty sky.
const approach = Cesium.Cartesian3.fromDegrees(JFK_LON, JFK_LAT + 8_000 * DEG_PER_M_LAT, 900);
const approach = Cesium.Cartesian3.fromDegrees(
JFK_LON,
JFK_LAT + 8_000 * DEG_PER_M_LAT,
900,
);
assert.equal(skyBackdropFactor(jfkCockpit, approach), 1);
// Straight overhead is the unambiguous case, from under the surface as much
// as from cruise altitude.
assert.equal(
skyBackdropFactor(jfkCockpit, Cesium.Cartesian3.fromDegrees(JFK_LON, JFK_LAT, 10_000)),
skyBackdropFactor(
jfkCockpit,
Cesium.Cartesian3.fromDegrees(JFK_LON, JFK_LAT, 10_000),
),
1,
);
});
@@ -225,7 +259,11 @@ test('below the ellipsoid, a contact on the ramp still keeps its plate', () => {
assert.equal(
skyBackdropFactor(
jfkCockpit,
Cesium.Cartesian3.fromDegrees(JFK_LON, JFK_LAT + 400 * DEG_PER_M_LAT, JFK_RAMP_H - 5),
Cesium.Cartesian3.fromDegrees(
JFK_LON,
JFK_LAT + 400 * DEG_PER_M_LAT,
JFK_RAMP_H - 5,
),
),
0,
);
@@ -246,14 +284,21 @@ test('at the surface the horizon is exactly eye level, geodetic not geocentric',
new Cesium.Cartesian3(20_000, 0, 0),
new Cesium.Cartesian3(),
);
const alongHorizontal = Cesium.Cartesian3.add(onSurface, east, new Cesium.Cartesian3());
const alongHorizontal = Cesium.Cartesian3.add(
onSurface,
east,
new Cesium.Cartesian3(),
);
assert.ok(
Math.abs(skyBackdropFactor(onSurface, alongHorizontal) - 0.5) < 1e-5,
`eye level must be the band centre, got ${skyBackdropFactor(onSurface, alongHorizontal)}`,
);
// The geocentric radial is NOT the answer: a contact perpendicular to it
// lands measurably off centre, so this test cannot pass by accident.
const radialUp = Cesium.Cartesian3.normalize(onSurface, new Cesium.Cartesian3());
const radialUp = Cesium.Cartesian3.normalize(
onSurface,
new Cesium.Cartesian3(),
);
const perpToRadial = Cesium.Cartesian3.cross(
radialUp,
Cesium.Cartesian3.UNIT_Z,
@@ -265,7 +310,11 @@ test('at the surface the horizon is exactly eye level, geodetic not geocentric',
20_000,
perpToRadial,
);
const alongRadialPlane = Cesium.Cartesian3.add(onSurface, perpToRadial, new Cesium.Cartesian3());
const alongRadialPlane = Cesium.Cartesian3.add(
onSurface,
perpToRadial,
new Cesium.Cartesian3(),
);
assert.ok(
Math.abs(skyBackdropFactor(onSurface, alongRadialPlane) - 0.5) > 0.05,
'a geocentric horizontal would be a different plane; the test must be able to tell',
@@ -284,7 +333,9 @@ function surfaceCrossingSweep(from = -50, to = 50, step = 1) {
const contact = Cesium.Cartesian3.fromDegrees(30_000 / 111_319.49, 0, 0);
const samples = [];
for (let height = from; height <= to; height += step) {
samples.push(skyBackdropFactor(Cesium.Cartesian3.fromDegrees(0, 0, height), contact));
samples.push(
skyBackdropFactor(Cesium.Cartesian3.fromDegrees(0, 0, height), contact),
);
}
return samples;
}
@@ -300,7 +351,10 @@ test('the answer stays continuous as the camera rises through the surface', () =
for (let i = 1; i < samples.length; i++) {
worst = Math.max(worst, Math.abs(samples[i] - samples[i - 1]));
}
assert.ok(worst < 0.05, `no step across the surface may pop; worst adjacent jump ${worst}`);
assert.ok(
worst < 0.05,
`no step across the surface may pop; worst adjacent jump ${worst}`,
);
});
test('the crossover has no seam at the surface itself', () => {
@@ -308,9 +362,18 @@ test('the crossover has no seam at the surface itself', () => {
// 1 cm is 5.6e-5 rad, a thousandth of the band, so any visible difference
// here is a discontinuity in the code rather than in the geometry.
const contact = Cesium.Cartesian3.fromDegrees(30_000 / 111_319.49, 0, 0);
const under = skyBackdropFactor(Cesium.Cartesian3.fromDegrees(0, 0, -0.01), contact);
const over = skyBackdropFactor(Cesium.Cartesian3.fromDegrees(0, 0, 0.01), contact);
assert.ok(Math.abs(under - over) < 5e-3, `seam at the surface: ${under} vs ${over}`);
const under = skyBackdropFactor(
Cesium.Cartesian3.fromDegrees(0, 0, -0.01),
contact,
);
const over = skyBackdropFactor(
Cesium.Cartesian3.fromDegrees(0, 0, 0.01),
contact,
);
assert.ok(
Math.abs(under - over) < 5e-3,
`seam at the surface: ${under} vs ${over}`,
);
});
test('a sub-surface camera carries real information, not one frozen answer', () => {
@@ -319,7 +382,10 @@ test('a sub-surface camera carries real information, not one frozen answer', ()
// sub-surface camera heights must produce different answers.
const belowOnly = surfaceCrossingSweep(-200, -1, 1);
const spread = Math.max(...belowOnly) - Math.min(...belowOnly);
assert.ok(spread > 0.05, `a sub-surface camera must still discriminate; spread ${spread}`);
assert.ok(
spread > 0.05,
`a sub-surface camera must still discriminate; spread ${spread}`,
);
assert.ok(
belowOnly.every((value) => value > 0 && value < 1),
'this sweep is deliberately mid-band the whole way',
@@ -334,7 +400,11 @@ test('a sub-surface camera carries real information, not one frozen answer', ()
* a future edit to the shared lines could drift the cruise answer while every
* sub-surface test stayed green.
*/
function legacyAboveSurfaceFactor(cameraPosition, position, featherRad = HORIZON_FEATHER_RAD) {
function legacyAboveSurfaceFactor(
cameraPosition,
position,
featherRad = HORIZON_FEATHER_RAD,
) {
const s = Cesium.Ellipsoid.WGS84.oneOverRadii;
const cx = cameraPosition.x * s.x;
const cy = cameraPosition.y * s.y;
@@ -415,22 +485,39 @@ test('below the surface the backdrop test agrees with the occluder beside it', (
const camera = Cesium.Cartesian3.fromDegrees(JFK_LON, JFK_LAT, -18);
const occluder = horizonOccluder({ positionWC: camera });
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(camera);
const offsetBy = (up) => Cesium.Cartesian3.add(
camera,
Cesium.Matrix4.multiplyByPointAsVector(
enu,
new Cesium.Cartesian3(0, 20_000, up),
const offsetBy = (up) =>
Cesium.Cartesian3.add(
camera,
Cesium.Matrix4.multiplyByPointAsVector(
enu,
new Cesium.Cartesian3(0, 20_000, up),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
);
// 20 km out and 600 m clear of eye level is well outside the 1.09° band.
const aboveEye = offsetBy(600);
const belowEye = offsetBy(-600);
assert.equal(occluder.isPointVisible(aboveEye), true, 'the occluder keeps what is above eye level');
assert.equal(skyBackdropFactor(camera, aboveEye), 1, 'and the backdrop test must call it sky');
assert.equal(occluder.isPointVisible(belowEye), false, 'the occluder culls what is below it');
assert.equal(skyBackdropFactor(camera, belowEye), 0, 'and the backdrop test must call it ground');
assert.equal(
occluder.isPointVisible(aboveEye),
true,
'the occluder keeps what is above eye level',
);
assert.equal(
skyBackdropFactor(camera, aboveEye),
1,
'and the backdrop test must call it sky',
);
assert.equal(
occluder.isPointVisible(belowEye),
false,
'the occluder culls what is below it',
);
assert.equal(
skyBackdropFactor(camera, belowEye),
0,
'and the backdrop test must call it ground',
);
});
test('a degenerate camera or contact reports ground rather than throwing', () => {
@@ -442,12 +529,24 @@ test('a degenerate camera or contact reports ground rather than throwing', () =>
assert.equal(skyBackdropFactor(cruiseCamera, cruiseCamera), 0);
// The planet's centre has no local vertical to measure against.
assert.equal(skyBackdropFactor(Cesium.Cartesian3.ZERO, cruiseCamera), 0);
assert.equal(skyBackdropFactor(new Cesium.Cartesian3(NaN, NaN, NaN), cruiseCamera), 0);
assert.equal(skyBackdropFactor(cruiseCamera, new Cesium.Cartesian3(NaN, NaN, NaN)), 0);
assert.equal(
skyBackdropFactor(new Cesium.Cartesian3(NaN, NaN, NaN), cruiseCamera),
0,
);
assert.equal(
skyBackdropFactor(cruiseCamera, new Cesium.Cartesian3(NaN, NaN, NaN)),
0,
);
// An infinite coordinate normalizes to NaN a few lines later, and a NaN plate
// alpha reaches the canvas as an invisible label rather than a caught error.
assert.equal(skyBackdropFactor(new Cesium.Cartesian3(Infinity, 0, 0), cruiseCamera), 0);
assert.equal(skyBackdropFactor(cruiseCamera, new Cesium.Cartesian3(Infinity, 0, 0)), 0);
assert.equal(
skyBackdropFactor(new Cesium.Cartesian3(Infinity, 0, 0), cruiseCamera),
0,
);
assert.equal(
skyBackdropFactor(cruiseCamera, new Cesium.Cartesian3(Infinity, 0, 0)),
0,
);
});
test('the feather band is a named constant in a sane screen-space range', () => {
@@ -456,3 +555,193 @@ test('the feather band is a named constant in a sane screen-space range', () =>
// band of arc-seconds would pop.
assert.ok(HORIZON_FEATHER_RAD > 0.002 && HORIZON_FEATHER_RAD < 0.09);
});
// --- Perspective projection through a real view-projection --------------------
import {
PERSPECTIVE_BLEND_MAX_PX,
PERSPECTIVE_BLEND_MIN_PX,
PERSPECTIVE_PROBE_M,
perspectiveProjectedRotation,
} from './iconOrientation.js';
/**
* A scene the exact projector accepts: 3D mode, a canvas, and a camera with a
* real view matrix and perspective frustum. The camera sits `altitudeM` above
* the origin and looks north, pitched down by `pitchDeg`, with world east as
* screen right — the oblique street-level pose where the camera-basis answer
* is wrong off-centre and the exact one is not.
*/
function obliqueScene(
altitudeM,
pitchDeg,
{ width = 1280, height = 800 } = {},
) {
const position = Cesium.Cartesian3.fromDegrees(0, 0, altitudeM);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const east = Cesium.Matrix4.getColumn(enu, 0, new Cesium.Cartesian3());
const north = Cesium.Matrix4.getColumn(enu, 1, new Cesium.Cartesian3());
const up = Cesium.Matrix4.getColumn(enu, 2, new Cesium.Cartesian3());
const pitch = Cesium.Math.toRadians(pitchDeg);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.add(
Cesium.Cartesian3.multiplyByScalar(
north,
Math.cos(pitch),
new Cesium.Cartesian3(),
),
Cesium.Cartesian3.multiplyByScalar(
up,
-Math.sin(pitch),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const cameraUp = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.add(
Cesium.Cartesian3.multiplyByScalar(
north,
Math.sin(pitch),
new Cesium.Cartesian3(),
),
Cesium.Cartesian3.multiplyByScalar(
up,
Math.cos(pitch),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
const viewMatrix = Cesium.Matrix4.computeView(
position,
direction,
cameraUp,
east,
new Cesium.Matrix4(),
);
const frustum = new Cesium.PerspectiveFrustum({
fov: Cesium.Math.toRadians(60),
aspectRatio: width / height,
near: 1,
far: 1e7,
});
return {
frameState: { mode: Cesium.SceneMode.SCENE3D },
canvas: { clientWidth: width, clientHeight: height },
camera: {
viewMatrix,
frustum,
rightWC: east,
upWC: cameraUp,
positionWC: position,
},
};
}
/** Probe separation (px) the helper sees for a contact and course in a scene. */
function probeSeparation(scene, contact, courseDeg) {
const courseRad = Cesium.Math.toRadians(courseDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(contact);
const forward = Cesium.Matrix4.multiplyByPointAsVector(
enu,
new Cesium.Cartesian3(
Math.sin(courseRad) * PERSPECTIVE_PROBE_M,
Math.cos(courseRad) * PERSPECTIVE_PROBE_M,
0,
),
new Cesium.Cartesian3(),
);
const probe = Cesium.Cartesian3.add(
contact,
forward,
new Cesium.Cartesian3(),
);
const at = Cesium.SceneTransforms.worldToWindowCoordinates(scene, contact);
const ahead = Cesium.SceneTransforms.worldToWindowCoordinates(scene, probe);
const dx = ahead.x - at.x;
const dy = ahead.y - at.y;
return { separation: Math.hypot(dx, dy), exact: Math.atan2(-dx, -dy) };
}
test('the perspective helper is continuous through the sub-pixel band, not a 23° flip', () => {
// Codex's reproduction: a contact near the right edge of an oblique view,
// the camera altitude walked so the probe separation crosses half a pixel.
// The rotation jumped 23° → 0° between two adjacent altitudes. The exact
// and camera-basis answers now blend across a band, the short way round.
//
// The contact keeps the SAME screen position across the walk — its ground
// offsets scale with the altitude — so the two answers disagree by the
// same twenty-odd degrees at every altitude while the separation alone
// walks from well above the band to well below it.
const course = 0; // northbound
const contactFor = (altitude) =>
Cesium.Cartesian3.fromDegrees(
(0.7 * altitude) / 111_320,
(1.2 * altitude) / 111_320,
0,
);
const samples = [];
// Geometric steps: separation scales with altitude, so equal ratios give
// equal-sized steps in the quantity the band is defined on.
for (let altitude = 500; altitude <= 600_000; altitude *= 1.02) {
const scene = obliqueScene(altitude, 45);
const contact = contactFor(altitude);
if (!Cesium.SceneTransforms.worldToWindowCoordinates(scene, contact))
continue;
const { separation, exact } = probeSeparation(scene, contact, course);
samples.push({
altitude,
separation,
exact,
rotation: perspectiveProjectedRotation(scene, contact, course, null),
basis: screenProjectedRotation(scene, contact, course, null),
});
}
const inBand = samples.filter(
(s) =>
s.separation > PERSPECTIVE_BLEND_MIN_PX &&
s.separation < PERSPECTIVE_BLEND_MAX_PX,
);
const above = samples.filter((s) => s.separation >= PERSPECTIVE_BLEND_MAX_PX);
const below = samples.filter((s) => s.separation <= PERSPECTIVE_BLEND_MIN_PX);
assert.ok(
inBand.length >= 5 && above.length >= 5 && below.length >= 5,
`the walk crosses the whole band (${below.length}/${inBand.length}/${above.length})`,
);
// Off-centre and oblique, the two answers genuinely disagree — that is the
// divergence the exact projection exists to fix.
const disagreement = Math.abs(
wrappedDelta(above[0].rotation, above[0].basis),
);
assert.ok(
disagreement > Cesium.Math.toRadians(5),
`exact and camera-basis differ by ${Cesium.Math.toDegrees(disagreement).toFixed(1)}° above the band`,
);
let worstStep = 0;
for (let i = 1; i < samples.length; i += 1) {
worstStep = Math.max(
worstStep,
Math.abs(wrappedDelta(samples[i].rotation, samples[i - 1].rotation)),
);
}
assert.ok(
worstStep < Cesium.Math.toRadians(3),
`no step between neighbouring altitudes exceeds 3° (worst ${Cesium.Math.toDegrees(worstStep).toFixed(2)}°)`,
);
// Below the band it is the camera-basis answer; above it the exact one, unblended.
for (const s of below)
assert.ok(
Math.abs(wrappedDelta(s.rotation, s.basis)) < 1e-6,
`basis alone at ${s.separation.toFixed(2)} px`,
);
for (const s of above)
assert.ok(
Math.abs(wrappedDelta(s.rotation, s.exact)) < 1e-6,
`exact alone at ${s.separation.toFixed(2)} px`,
);
});
+175 -72
View File
@@ -16,11 +16,15 @@ function clampInt(value, min, max) {
}
function demandEntries(demandByLayer) {
const entries = demandByLayer instanceof Map
? Array.from(demandByLayer.entries())
: Object.entries(demandByLayer || {});
const entries =
demandByLayer instanceof Map
? Array.from(demandByLayer.entries())
: Object.entries(demandByLayer || {});
return entries
.map(([layerId, demand]) => [String(layerId), Math.max(0, Math.floor(Number(demand) || 0))])
.map(([layerId, demand]) => [
String(layerId),
Math.max(0, Math.floor(Number(demand) || 0)),
])
.filter(([, demand]) => demand > 0)
.sort(([a], [b]) => a.localeCompare(b));
}
@@ -104,7 +108,9 @@ function allocateLayerQuotasInto(
weighted.length = idCount;
priorityOrder.length = idCount;
remainders.length = idCount;
priorityOrder.sort((a, b) => b.weight - a.weight || a.layerId.localeCompare(b.layerId));
priorityOrder.sort(
(a, b) => b.weight - a.weight || a.layerId.localeCompare(b.layerId),
);
let remaining = capacity;
if (capacity >= idCount) {
@@ -115,7 +121,7 @@ function allocateLayerQuotasInto(
let apportioned = 0;
for (let i = 0; i < idCount; i++) {
const entry = weighted[i];
const exact = remaining * entry.weight / totalWeight;
const exact = (remaining * entry.weight) / totalWeight;
const room = entry.count - (quotas.get(entry.layerId) || 0);
const whole = Math.min(room, Math.floor(exact));
quotas.set(entry.layerId, (quotas.get(entry.layerId) || 0) + whole);
@@ -123,9 +129,12 @@ function allocateLayerQuotasInto(
entry.fraction = exact - Math.floor(exact);
}
remaining -= apportioned;
remainders.sort((a, b) => b.fraction - a.fraction
|| b.weight - a.weight
|| a.layerId.localeCompare(b.layerId));
remainders.sort(
(a, b) =>
b.fraction - a.fraction ||
b.weight - a.weight ||
a.layerId.localeCompare(b.layerId),
);
for (let i = 0; i < idCount && remaining > 0; i++) {
const entry = remainders[i];
const current = quotas.get(entry.layerId) || 0;
@@ -156,7 +165,12 @@ function allocateLayerQuotasInto(
* Allocate a collective capacity across non-empty layers. Both strategies are
* work-conserving and deterministic; unused entitlement is always borrowed.
*/
export function allocateLayerQuotas(demandByLayer, capacity, strategy = ALLOCATION_ELASTIC, layerWeights = {}) {
export function allocateLayerQuotas(
demandByLayer,
capacity,
strategy = ALLOCATION_ELASTIC,
layerWeights = {},
) {
const entries = demandEntries(demandByLayer);
const totalDemand = entries.reduce((sum, [, demand]) => sum + demand, 0);
const cap = clampInt(capacity, 0, totalDemand);
@@ -198,15 +212,24 @@ export function allocateLayerQuotas(demandByLayer, capacity, strategy = ALLOCATI
if (remaining > 0 && totalWeight > 0) {
let apportioned = 0;
for (const entry of weighted) {
const exact = remaining * entry.weight / totalWeight;
const exact = (remaining * entry.weight) / totalWeight;
const room = entry.count - (quotas.get(entry.layerId) || 0);
const whole = Math.min(room, Math.floor(exact));
quotas.set(entry.layerId, (quotas.get(entry.layerId) || 0) + whole);
apportioned += whole;
remainders.push({ layerId: entry.layerId, fraction: exact - Math.floor(exact), weight: entry.weight });
remainders.push({
layerId: entry.layerId,
fraction: exact - Math.floor(exact),
weight: entry.weight,
});
}
remaining -= apportioned;
remainders.sort((a, b) => b.fraction - a.fraction || b.weight - a.weight || a.layerId.localeCompare(b.layerId));
remainders.sort(
(a, b) =>
b.fraction - a.fraction ||
b.weight - a.weight ||
a.layerId.localeCompare(b.layerId),
);
for (const entry of remainders) {
if (remaining <= 0) break;
const current = quotas.get(entry.layerId) || 0;
@@ -220,20 +243,24 @@ export function allocateLayerQuotas(demandByLayer, capacity, strategy = ALLOCATI
}
function rectIsFinite(rect) {
return rect
&& Number.isFinite(rect.x)
&& Number.isFinite(rect.y)
&& Number.isFinite(rect.w)
&& Number.isFinite(rect.h)
&& rect.w > 0
&& rect.h > 0;
return (
rect &&
Number.isFinite(rect.x) &&
Number.isFinite(rect.y) &&
Number.isFinite(rect.w) &&
Number.isFinite(rect.h) &&
rect.w > 0 &&
rect.h > 0
);
}
function overlaps(a, b, padding = 4) {
return a.x < b.x + b.w + padding
&& a.x + a.w + padding > b.x
&& a.y < b.y + b.h + padding
&& a.y + a.h + padding > b.y;
return (
a.x < b.x + b.w + padding &&
a.x + a.w + padding > b.x &&
a.y < b.y + b.h + padding &&
a.y + a.h + padding > b.y
);
}
const CELL_ORIGIN = 8192;
@@ -271,8 +298,10 @@ class SpatialHash {
* never hide a real collision.
*/
_cellKey(x, y) {
const cx = Math.max(-CELL_ORIGIN, Math.min(CELL_ORIGIN - 1, x)) + CELL_ORIGIN;
const cy = Math.max(-CELL_ORIGIN, Math.min(CELL_ORIGIN - 1, y)) + CELL_ORIGIN;
const cx =
Math.max(-CELL_ORIGIN, Math.min(CELL_ORIGIN - 1, x)) + CELL_ORIGIN;
const cy =
Math.max(-CELL_ORIGIN, Math.min(CELL_ORIGIN - 1, y)) + CELL_ORIGIN;
// Both coordinates occupy 14 bits. Bit-packing forces the lookup key to a
// Smi; arithmetic multiplication materializes a boxed double at each
// spatial-hash get/add on this hot solve path.
@@ -325,8 +354,14 @@ function candidateCompare(a, b, states, now) {
// A stateless candidate is never lifetime-pinned: its source shipped as a
// per-frame rebuild, so it must be free to lose its slot the moment something
// better wants it. Plain incumbency ordering below still applies.
const aPinned = !!aState?.selected && a.stateless !== true && now - aState.selectedAt < MIN_LIFETIME_MS;
const bPinned = !!bState?.selected && b.stateless !== true && now - bState.selectedAt < MIN_LIFETIME_MS;
const aPinned =
!!aState?.selected &&
a.stateless !== true &&
now - aState.selectedAt < MIN_LIFETIME_MS;
const bPinned =
!!bState?.selected &&
b.stateless !== true &&
now - bState.selectedAt < MIN_LIFETIME_MS;
if (aPinned !== bPinned) return aPinned ? -1 : 1;
const aIncumbent = !!aState?.selected;
const bIncumbent = !!bState?.selected;
@@ -346,12 +381,20 @@ function candidateCompare(a, b, states, now) {
function cacheCandidateAnchorScalars(candidate) {
let anchorX = Number.NaN;
let anchorY = Number.NaN;
if (Number.isFinite(candidate?.screenX) && Number.isFinite(candidate?.screenY)) {
if (
Number.isFinite(candidate?.screenX) &&
Number.isFinite(candidate?.screenY)
) {
anchorX = candidate.screenX;
anchorY = candidate.screenY;
} else {
const placement = Array.isArray(candidate?.placements) ? candidate.placements[0] : null;
if (Number.isFinite(placement?.leadFromX) && Number.isFinite(placement?.leadFromY)) {
const placement = Array.isArray(candidate?.placements)
? candidate.placements[0]
: null;
if (
Number.isFinite(placement?.leadFromX) &&
Number.isFinite(placement?.leadFromY)
) {
anchorX = placement.leadFromX;
anchorY = placement.leadFromY;
} else if (rectIsFinite(placement?.rect)) {
@@ -401,7 +444,16 @@ class SpatialCandidateQueue {
* stay unboxed. Few-placement candidates already blocked by the
* monotonically growing collision field are dismissed before anchor scans.
*/
reset(candidates, count, anchors, anchorCount, attemptStamps, stamp, spatial, states) {
reset(
candidates,
count,
anchors,
anchorCount,
attemptStamps,
stamp,
spatial,
states,
) {
this.candidates = candidates;
this.count = count;
this.anchorCount = anchorCount;
@@ -529,10 +581,13 @@ class SpatialCandidateQueue {
const rectY = placementYs[rectIndex];
const rectW = placementWs[rectIndex];
const rectH = placementHs[rectIndex];
if (rectX < anchorRectX + anchorRectW + 4
&& rectX + rectW + 4 > anchorRectX
&& rectY < anchorRectY + anchorRectH + 4
&& rectY + rectH + 4 > anchorRectY) freeMask &= ~bit;
if (
rectX < anchorRectX + anchorRectW + 4 &&
rectX + rectW + 4 > anchorRectX &&
rectY < anchorRectY + anchorRectH + 4 &&
rectY + rectH + 4 > anchorRectY
)
freeMask &= ~bit;
}
placementMasks[i] = freeMask;
if (freeMask === 0 && this._dismissBlockedKey(i)) continue;
@@ -558,7 +613,8 @@ class SpatialCandidateQueue {
bestIndex = i;
continue;
}
const priorityDelta = (Number(candidate.priority) || 0) - (Number(best.priority) || 0);
const priorityDelta =
(Number(candidate.priority) || 0) - (Number(best.priority) || 0);
if (priorityDelta !== 0) {
if (priorityDelta > 0) {
best = candidate;
@@ -621,7 +677,8 @@ function firstFreePlacement(candidate, stickyCorner, spatial) {
if (stickyCorner) {
for (let i = 0; i < placements.length; i++) {
const placement = placements[i];
if (placement?.corner !== stickyCorner || !rectIsFinite(placement.rect)) continue;
if (placement?.corner !== stickyCorner || !rectIsFinite(placement.rect))
continue;
if (!spatial.collides(placement.rect)) return placement;
}
}
@@ -790,7 +847,13 @@ export class LabelArbiter {
let candidateCount = 0;
for (let i = 0; i < source.length; i++) {
const candidate = source[i];
if (!candidate || !candidate.key || !candidate.layerId || !(candidate.keyholeAlpha > 0)) continue;
if (
!candidate ||
!candidate.key ||
!candidate.layerId ||
!(candidate.keyholeAlpha > 0)
)
continue;
cacheCandidateAnchorScalars(candidate);
candidateList[candidateCount++] = candidate;
let bucket = byLayer.get(candidate.layerId);
@@ -815,13 +878,15 @@ export class LabelArbiter {
});
} else if (options.demandByLayer != null) {
const supplied = demandEntries(options.demandByLayer);
for (let i = 0; i < supplied.length; i++) demand.set(supplied[i][0], supplied[i][1]);
for (let i = 0; i < supplied.length; i++)
demand.set(supplied[i][0], supplied[i][1]);
}
// A supplied demand map describes the full lightweight field while the
// candidate list may be only a bounded materialized cohort. Keep defensive
// support for candidate layers omitted by an incomplete caller map.
byLayer.forEach((bucket, layerId) => {
if (bucket.count > 0 && !demand.has(layerId)) demand.set(layerId, bucket.count);
if (bucket.count > 0 && !demand.has(layerId))
demand.set(layerId, bucket.count);
});
const activeLayers = this._activeLayersScratch;
@@ -857,14 +922,20 @@ export class LabelArbiter {
let sameActiveLayers = activeCount === this.lastActiveLayers.length;
for (let i = 0; sameActiveLayers && i < activeCount; i++) {
if (activeLayers[i] !== this.lastActiveLayers[i]) sameActiveLayers = false;
if (activeLayers[i] !== this.lastActiveLayers[i])
sameActiveLayers = false;
}
const preserveIncumbents = options.preserveIncumbents !== false && sameActiveLayers;
const preserveIncumbents =
options.preserveIncumbents !== false && sameActiveLayers;
let spatialQueueBuildCount = 0;
let spatialQueueNextCount = 0;
const attempt = (candidate, allowOverlapFallback = false) => {
if (selectedCount >= capacity || attemptStamps.get(candidate.key) === stamp) return false;
if (
selectedCount >= capacity ||
attemptStamps.get(candidate.key) === stamp
)
return false;
attemptStamps.set(candidate.key, stamp);
const previous = this.states.get(candidate.key);
const stateless = candidate.stateless === true;
@@ -872,10 +943,12 @@ export class LabelArbiter {
// very next solve, as their stateless originals did) and carry no sticky
// corner, so above/below is re-decided from geometry every solve instead
// of being pinned by whichever side happened to be free once.
if (!stateless && !previous?.selected && previous?.cooldownUntil > now) return false;
if (!stateless && !previous?.selected && previous?.cooldownUntil > now)
return false;
const sticky = stateless ? undefined : previous?.corner;
let placement = firstFreePlacement(candidate, sticky, spatial);
if (!placement && allowOverlapFallback) placement = firstOrderedPlacement(candidate, sticky);
if (!placement && allowOverlapFallback)
placement = firstOrderedPlacement(candidate, sticky);
if (!placement) return false;
spatial.add(placement.rect);
selectStamps.set(candidate.key, stamp);
@@ -953,7 +1026,8 @@ export class LabelArbiter {
}
let retainedIncumbents = 0;
for (let i = 0; i < selectedCount; i++) {
if (this.selectedKeys.has(selectedCandidates[i].key)) retainedIncumbents++;
if (this.selectedKeys.has(selectedCandidates[i].key))
retainedIncumbents++;
}
const exitingStates = this._refreshStateList();
@@ -964,7 +1038,9 @@ export class LabelArbiter {
state.exitStartedAt = now;
// Stateless entries may be re-selected immediately; the cooldown exists
// to damp thrash for sources that shipped with hysteresis.
state.cooldownUntil = state.stateless ? 0 : now + FADE_OUT_MS + COOLDOWN_MS;
state.cooldownUntil = state.stateless
? 0
: now + FADE_OUT_MS + COOLDOWN_MS;
}
}
@@ -1002,7 +1078,8 @@ export class LabelArbiter {
this._stateListDirty = true;
}
if (labelsByLayer) {
labelsByLayer[candidate.layerId] = (labelsByLayer[candidate.layerId] || 0) + 1;
labelsByLayer[candidate.layerId] =
(labelsByLayer[candidate.layerId] || 0) + 1;
}
}
@@ -1013,7 +1090,10 @@ export class LabelArbiter {
const livingStates = this._refreshStateList();
for (let i = 0; i < livingStates.length; i++) {
const state = livingStates[i];
if (!state.selected && now - (state.exitStartedAt || now) > FADE_OUT_MS + COOLDOWN_MS) {
if (
!state.selected &&
now - (state.exitStartedAt || now) > FADE_OUT_MS + COOLDOWN_MS
) {
this.states.delete(state.key);
this._stateListDirty = true;
}
@@ -1026,25 +1106,28 @@ export class LabelArbiter {
});
for (let i = 0; i < droppedCount; i++) this.selectedKeys.delete(dropped[i]);
dropped.length = droppedCount;
for (let i = 0; i < selectedCount; i++) this.selectedKeys.add(selectedCandidates[i].key);
for (let i = 0; i < selectedCount; i++)
this.selectedKeys.add(selectedCandidates[i].key);
const previousActiveLayers = this.lastActiveLayers;
this.lastActiveLayers = activeLayers;
this._activeLayersScratch = previousActiveLayers;
this.solveRevision++;
this.lastDiagnostics = collectDiagnostics ? {
strategy,
capacity,
selectedCount,
quotas: Object.fromEntries(quotas),
demand: Object.fromEntries(demand),
labelsByLayer,
solveRevision: this.solveRevision,
spatialQueueBuildCount,
spatialQueueNextCount,
eligibleIncumbents,
retainedIncumbents,
} : null;
this.lastDiagnostics = collectDiagnostics
? {
strategy,
capacity,
selectedCount,
quotas: Object.fromEntries(quotas),
demand: Object.fromEntries(demand),
labelsByLayer,
solveRevision: this.solveRevision,
spatialQueueBuildCount,
spatialQueueNextCount,
eligibleIncumbents,
retainedIncumbents,
}
: null;
selectedCandidates.length = selectedCount;
selectedPlacements.length = selectedCount;
pruneStampMap(attemptStamps, candidateCount);
@@ -1057,9 +1140,15 @@ export class LabelArbiter {
* A caller-owned output array enables allocation-free per-frame rendering.
*/
renderEntries(currentCandidates, now = Date.now(), out = []) {
const current = currentCandidates instanceof Map
? currentCandidates
: new Map((currentCandidates || []).map((candidate) => [candidate.key, candidate]));
const current =
currentCandidates instanceof Map
? currentCandidates
: new Map(
(currentCandidates || []).map((candidate) => [
candidate.key,
candidate,
]),
);
const states = this._refreshStateList();
let outIndex = 0;
for (let i = 0; i < states.length; i++) {
@@ -1070,14 +1159,23 @@ export class LabelArbiter {
// fully painted this solve or gone. No enter ramp, no exit tail.
temporalAlpha = state.selected ? 1 : 0;
} else if (state.selected) {
temporalAlpha = Math.min(1, Math.max(0, (now - state.enterStartedAt) / FADE_IN_MS));
temporalAlpha = Math.min(
1,
Math.max(0, (now - state.enterStartedAt) / FADE_IN_MS),
);
} else {
temporalAlpha = 1 - Math.min(1, Math.max(0, (now - state.exitStartedAt) / FADE_OUT_MS));
temporalAlpha =
1 -
Math.min(1, Math.max(0, (now - state.exitStartedAt) / FADE_OUT_MS));
}
if (temporalAlpha <= 0) continue;
const candidate = current.get(state.key) || state.lastCandidate;
if (!candidate) continue;
const placement = renderPlacement(candidate, state.stateless ? undefined : state.corner, state.lastPlacement);
const placement = renderPlacement(
candidate,
state.stateless ? undefined : state.corner,
state.lastPlacement,
);
if (!placement) continue;
const entry = out[outIndex] || (out[outIndex] = {});
entry.candidate = candidate;
@@ -1100,11 +1198,16 @@ export class LabelArbiter {
for (const state of this.states.values()) {
if (!state.selected) {
if (!includeFading) continue;
if (!Number.isFinite(state.exitStartedAt) || now - state.exitStartedAt >= FADE_OUT_MS) continue;
if (
!Number.isFinite(state.exitStartedAt) ||
now - state.exitStartedAt >= FADE_OUT_MS
)
continue;
}
const candidate = state.lastCandidate;
if (!candidate?.layerId || candidate.sourceId == null) continue;
if (!grouped.has(candidate.layerId)) grouped.set(candidate.layerId, new Set());
if (!grouped.has(candidate.layerId))
grouped.set(candidate.layerId, new Set());
grouped.get(candidate.layerId).add(candidate.sourceId);
}
return grouped;
+449 -179
View File
File diff suppressed because it is too large. Load diff
+11 -4
View File
@@ -158,8 +158,9 @@ function encode(state) {
test('production registry is exact, canonical, and rejects incomplete contracts', async () => {
assert.equal(validateLayerStateRegistry(), true);
assert.equal(REGISTERED_LAYER_IDS.length, 18);
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 18);
assert.equal(REGISTERED_LAYER_IDS.length, 21);
assert.equal(new Set(REGISTERED_LAYER_IDS).size, 21);
assert.ok(REGISTERED_LAYER_IDS.includes('transit'));
assert.deepEqual(REGISTERED_LAYER_IDS, [...REGISTERED_LAYER_IDS].sort());
assert.throws(
() => validateLayerStateRegistry([...LAYER_STATE_REGISTRY, LAYER_STATE_REGISTRY[0]]),
@@ -226,8 +227,14 @@ test('v2 codec distinguishes absent from empty and keeps canonical deterministic
});
test('unknown enabled-layer tokens reject the payload instead of becoming an empty set', () => {
assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=z')), null);
assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=c.z')), null);
assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=unknown')), null);
assert.equal(decodeLayerStateParams(new URLSearchParams('v=2&l=c.unknown')), null);
});
test('Nepal event and locator have distinct enabled-only share tokens', () => {
const decoded = decodeLayerStateParams(new URLSearchParams('v=2&l=h.z'));
assert.deepEqual(decoded.enabledLayerIds, ['bhote-koshi-2026', 'bhote-koshi-locator']);
assert.ok(encode(decoded).includes('l=h.z'));
});
test('unknown and forbidden option fields are ignored while missing options use codec defaults', () => {
+8 -3
View File
@@ -11,8 +11,10 @@ export * from './localGeojsonCore.js';
export function createLocalGeoJsonLayer(options) {
return createLayer(options, {
...localGeoJsonServices,
overlayHost: options.overlayHost === undefined
? localGeoJsonServices.overlayHost : options.overlayHost,
overlayHost:
options.overlayHost === undefined
? localGeoJsonServices.overlayHost
: options.overlayHost,
});
}
@@ -20,6 +22,9 @@ export function createLocalGeoJsonLayer(options) {
export function createLocalInfrastructureOverlayPublisher(options) {
return createPublisher({
...options,
host: options.host === undefined ? localGeoJsonServices.overlayHost : options.host,
host:
options.host === undefined
? localGeoJsonServices.overlayHost
: options.host,
});
}
+1 -6
View File
@@ -15,9 +15,4 @@ const fires = createFirmsHeatmapLayer({
source: 'NASA FIRMS · LIVE',
});
export default [
datacenters,
dams,
submarineCablesLayer,
fires,
];
export default [datacenters, dams, submarineCablesLayer, fires];
+4 -1
View File
@@ -1,4 +1,7 @@
import { createMeshFloorSampler } from '../services/meshFloorSampler.js';
import * as groundFloor from './groundFloor.js';
const meshFloorSampler = createMeshFloorSampler({ groundFloor, eventTarget: typeof window === 'undefined' ? null : window });
const meshFloorSampler = createMeshFloorSampler({
groundFloor,
eventTarget: typeof window === 'undefined' ? null : window,
});
export const { sampleMeshFloorCells, cachedGroundFloor } = meshFloorSampler;
+73 -18
View File
@@ -18,10 +18,13 @@ export const AWARENESS_RELATIONSHIP = Object.freeze({
* @param {{initialRadiusM?: number, maxRadiusM?: number}} [options] Bounds.
* @returns {{candidate: T, radiusM: number}|null} First match and radius used.
*/
export function findByDoublingRadius(search, {
initialRadiusM = AWARENESS_RADIUS_M,
maxRadiusM = AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
} = {}) {
export function findByDoublingRadius(
search,
{
initialRadiusM = AWARENESS_RADIUS_M,
maxRadiusM = AWARENESS_MAX_FLIGHT_SEARCH_RADIUS_M,
} = {},
) {
if (typeof search !== 'function') return null;
if (!Number.isFinite(initialRadiusM) || initialRadiusM <= 0) return null;
if (!Number.isFinite(maxRadiusM) || maxRadiusM < initialRadiusM) return null;
@@ -39,13 +42,22 @@ export function findByDoublingRadius(search, {
/** @param {number} meters @returns {string} */
export function formatAwarenessDistance(meters) {
if (!Number.isFinite(meters) || meters < 0) return '—';
return meters < 1000 ? `${Math.round(meters)} m` : `${(meters / 1000).toFixed(meters < 10000 ? 1 : 0)} km`;
return meters < 1000
? `${Math.round(meters)} m`
: `${(meters / 1000).toFixed(meters < 10000 ? 1 : 0)} km`;
}
/** Return a stable visible label without leaking missing values into UI text. */
export function formatAwarenessLabel(value) {
if (value && typeof value === 'object') {
for (const candidate of [value.callsign, value.name, value.label, value.id, value.icao24, value.mmsi]) {
for (const candidate of [
value.callsign,
value.name,
value.label,
value.id,
value.icao24,
value.mmsi,
]) {
const label = formatAwarenessLabel(candidate);
if (label !== '—') return label;
}
@@ -61,19 +73,41 @@ export function formatAwarenessLabel(value) {
* negative finding. `UNKNOWN` is an input-data state, never an out-of-range
* claim in this MVP.
*/
export function summarizeAwarenessCohort(items, { available = true, stale = false, limit = 3 } = {}) {
if (!available) return { relationship: AWARENESS_RELATIONSHIP.UNKNOWN, count: null, nearest: [], reason: 'feed unavailable' };
if (stale) return { relationship: AWARENESS_RELATIONSHIP.UNKNOWN, count: null, nearest: [], reason: 'feed stale' };
export function summarizeAwarenessCohort(
items,
{ available = true, stale = false, limit = 3 } = {},
) {
if (!available)
return {
relationship: AWARENESS_RELATIONSHIP.UNKNOWN,
count: null,
nearest: [],
reason: 'feed unavailable',
};
if (stale)
return {
relationship: AWARENESS_RELATIONSHIP.UNKNOWN,
count: null,
nearest: [],
reason: 'feed stale',
};
const normalized = (Array.isArray(items) ? items : [])
.filter((item) => Number.isFinite(item?.distanceM ?? item?.distance)
&& (item.distanceM ?? item.distance) >= 0)
.filter(
(item) =>
Number.isFinite(item?.distanceM ?? item?.distance) &&
(item.distanceM ?? item.distance) >= 0,
)
.map((item) => ({ ...item, distanceM: item.distanceM ?? item.distance }))
.sort((a, b) => a.distanceM - b.distanceM);
return {
relationship: normalized.length ? AWARENESS_RELATIONSHIP.NEARBY : AWARENESS_RELATIONSHIP.UNKNOWN,
relationship: normalized.length
? AWARENESS_RELATIONSHIP.NEARBY
: AWARENESS_RELATIONSHIP.UNKNOWN,
count: normalized.length,
nearest: normalized.slice(0, limit),
reason: normalized.length ? 'observed or mapped nearby context' : 'no observed or mapped objects in current feeds',
reason: normalized.length
? 'observed or mapped nearby context'
: 'no observed or mapped objects in current feeds',
};
}
@@ -84,21 +118,40 @@ export function summarizeAwarenessCohort(items, { available = true, stale = fals
* @param {Iterable<string>} [visitedKeys] Previously visited layer/id keys.
* @returns {Array<{layerId: string, id: string, item: Object}>} Selectable targets.
*/
export function getAwarenessNavigationTargets(cohorts, subject = null, visitedKeys = []) {
export function getAwarenessNavigationTargets(
cohorts,
subject = null,
visitedKeys = [],
) {
const visited = new Set(visitedKeys);
const targets = [];
for (const cohort of Array.isArray(cohorts) ? cohorts : []) {
const layerId = cohort?.id;
if (!['flights', 'military', 'ais-live-vessels', 'military-installations'].includes(layerId)) continue;
if (
![
'flights',
'military',
'ais-live-vessels',
'military-installations',
].includes(layerId)
)
continue;
const sourceItems = Array.isArray(cohort?.summary?.navigationNearest)
? cohort.summary.navigationNearest
: (Array.isArray(cohort?.summary?.nearest) ? cohort.summary.nearest : []);
: Array.isArray(cohort?.summary?.nearest)
? cohort.summary.nearest
: [];
for (const item of sourceItems) {
const id = item?.icao24 || item?.mmsi || item?.id;
if (!id) continue;
const key = `${layerId}:${id}`;
if (key === `${subject?.layerId}:${subject?.id}`) continue;
targets.push({ layerId, id: String(id), item, visited: visited.has(key) });
targets.push({
layerId,
id: String(id),
item,
visited: visited.has(key),
});
}
}
targets.sort((a, b) => {
@@ -108,7 +161,9 @@ export function getAwarenessNavigationTargets(cohorts, subject = null, visitedKe
// reached vessels, installations, or the other flight layer at all.
const visitedOrder = Number(a.visited) - Number(b.visited);
if (visitedOrder) return visitedOrder;
const subjectOrder = Number(a.layerId !== subject?.layerId) - Number(b.layerId !== subject?.layerId);
const subjectOrder =
Number(a.layerId !== subject?.layerId) -
Number(b.layerId !== subject?.layerId);
if (subjectOrder) return subjectOrder;
return (a.item.distanceM ?? Infinity) - (b.item.distanceM ?? Infinity);
});
+57 -18
View File
@@ -37,10 +37,14 @@ const MAX_FOOTPRINT_POINTS = 400;
* @returns {string} Display label, never empty.
*/
export function humanizeInstallationClass(klass) {
const key = String(klass || '').trim().toLowerCase();
const key = String(klass || '')
.trim()
.toLowerCase();
if (LABEL_BY_CLASS[key]) return LABEL_BY_CLASS[key];
const words = key.replaceAll('_', ' ').trim();
return words ? `${words[0].toUpperCase()}${words.slice(1)}` : 'Mapped installation';
return words
? `${words[0].toUpperCase()}${words.slice(1)}`
: 'Mapped installation';
}
function finiteLatitude(value) {
@@ -54,7 +58,8 @@ function finiteLongitude(value) {
function pointFrom(element) {
const lat = Number(element?.lat ?? element?.center?.lat);
const longitude = Number(element?.lon ?? element?.center?.lon);
if (finiteLatitude(lat) && finiteLongitude(longitude)) return { latitude: lat, longitude };
if (finiteLatitude(lat) && finiteLongitude(longitude))
return { latitude: lat, longitude };
// Bounds midpoint fallback (field test 2026-08-28, Warendorf: nothing drawn).
// The proxy asks for `out center tags geom`, but Overpass takes the LAST
@@ -67,8 +72,12 @@ function pointFrom(element) {
// recovers all of them without touching the query or the footprint path.
const bounds = element?.bounds;
// JSON nulls, booleans, and empty strings must not coerce to a false 0,0 site.
if (![bounds?.minlat, bounds?.minlon, bounds?.maxlat, bounds?.maxlon]
.every((value) => typeof value === 'number' && Number.isFinite(value))) return null;
if (
![bounds?.minlat, bounds?.minlon, bounds?.maxlat, bounds?.maxlon].every(
(value) => typeof value === 'number' && Number.isFinite(value),
)
)
return null;
const south = Number(bounds?.minlat);
const west = Number(bounds?.minlon);
const north = Number(bounds?.maxlat);
@@ -79,17 +88,28 @@ function pointFrom(element) {
// A single installation footprint is never wider than the request bbox cap
// (10°): an ascending box that spans the antimeridian (minlon -179, maxlon
// 179) passes the ordering check yet midpoints to longitude 0.
if (finiteLatitude(south) && finiteLatitude(north)
&& finiteLongitude(west) && finiteLongitude(east)
&& south <= north && west <= east
&& north - south <= 10 && east - west <= 10) {
if (
finiteLatitude(south) &&
finiteLatitude(north) &&
finiteLongitude(west) &&
finiteLongitude(east) &&
south <= north &&
west <= east &&
north - south <= 10 &&
east - west <= 10
) {
return { latitude: (south + north) / 2, longitude: (west + east) / 2 };
}
return null;
}
function footprintFrom(element) {
if (!Array.isArray(element?.geometry) || element.geometry.length < 3 || element.geometry.length > MAX_FOOTPRINT_POINTS) return null;
if (
!Array.isArray(element?.geometry) ||
element.geometry.length < 3 ||
element.geometry.length > MAX_FOOTPRINT_POINTS
)
return null;
const points = [];
for (const point of element.geometry) {
const latitude = Number(point?.lat);
@@ -106,21 +126,30 @@ function footprintFrom(element) {
* @param {string} [retrievedAt]
* @returns {{records: Array, droppedCount: number}}
*/
export function normalizeMilitaryInstallations(payload, retrievedAt = new Date().toISOString()) {
export function normalizeMilitaryInstallations(
payload,
retrievedAt = new Date().toISOString(),
) {
const records = [];
const ids = new Set();
let droppedCount = 0;
for (const element of Array.isArray(payload?.elements) ? payload.elements : []) {
for (const element of Array.isArray(payload?.elements)
? payload.elements
: []) {
const type = String(element?.type || '');
const osmId = Number(element?.id);
if (!['node', 'way', 'relation'].includes(type) || !Number.isSafeInteger(osmId)) {
if (
!['node', 'way', 'relation'].includes(type) ||
!Number.isSafeInteger(osmId)
) {
droppedCount += 1;
continue;
}
const id = `osm:${type}:${osmId}`;
const tags = element?.tags || {};
const klass = CLASS_BY_MILITARY_TAG[String(tags.military || '').toLowerCase()]
|| (tags.landuse === 'military' ? 'military_land' : null);
const klass =
CLASS_BY_MILITARY_TAG[String(tags.military || '').toLowerCase()] ||
(tags.landuse === 'military' ? 'military_land' : null);
const point = pointFrom(element);
if (!klass || !point || ids.has(id)) {
droppedCount += 1;
@@ -134,7 +163,9 @@ export function normalizeMilitaryInstallations(payload, retrievedAt = new Date()
// geometry, while a footprint-less way/relation has unknown extent.
osmType: type,
class: klass,
name: String(tags.name || tags['name:en'] || '').trim() || humanizeInstallationClass(klass),
name:
String(tags.name || tags['name:en'] || '').trim() ||
humanizeInstallationClass(klass),
...point,
footprint: footprintFrom(element),
sources: [{ name: 'OpenStreetMap', id: `${type}/${osmId}`, retrievedAt }],
@@ -152,6 +183,14 @@ export function isValidInstallationBoundingBox(value) {
const west = Number(box.west);
const north = Number(box.north);
const east = Number(box.east);
return finiteLatitude(south) && finiteLatitude(north) && finiteLongitude(west) && finiteLongitude(east)
&& south < north && west < east && north - south <= 10 && east - west <= 10;
return (
finiteLatitude(south) &&
finiteLatitude(north) &&
finiteLongitude(west) &&
finiteLongitude(east) &&
south < north &&
west < east &&
north - south <= 10 &&
east - west <= 10
);
}
+33 -7
View File
@@ -77,7 +77,9 @@ export const MODEL_TRAIL_ANCHOR_NATIVE = Object.freeze({
* trail anchor has to ride the same chain or it lands on a different axis than
* the aircraft it is supposed to be attached to. */
const AXIS_CORRECTION = Cesium.Matrix4.multiplyTransformation(
Cesium.Axis.Y_UP_TO_Z_UP, Cesium.Axis.Z_UP_TO_X_UP, new Cesium.Matrix4(),
Cesium.Axis.Y_UP_TO_Z_UP,
Cesium.Axis.Z_UP_TO_X_UP,
new Cesium.Matrix4(),
);
const _anchorScratch = new Cesium.Cartesian3();
const _chainScratch = new Cesium.Matrix4();
@@ -124,7 +126,11 @@ export function modelAnchorWorld(model, nativeAnchor, result) {
components || Cesium.Matrix4.IDENTITY,
_chainScratch,
);
Cesium.Matrix4.multiplyTransformation(_chainScratch, AXIS_CORRECTION, _chainScratch);
Cesium.Matrix4.multiplyTransformation(
_chainScratch,
AXIS_CORRECTION,
_chainScratch,
);
return Cesium.Matrix4.multiplyByPoint(_chainScratch, _anchorScratch, result);
}
@@ -220,9 +226,17 @@ export function trailHeadStart(start, anchor, center, radiusM, result) {
// a real trail.
if (!anchor || !center || !result) return start;
if (!Number.isFinite(radiusM) || radiusM <= 0) return start;
const startD = Math.hypot(start.x - center.x, start.y - center.y, start.z - center.z);
const startD = Math.hypot(
start.x - center.x,
start.y - center.y,
start.z - center.z,
);
if (startD >= radiusM) return start;
const anchorD = Math.hypot(anchor.x - center.x, anchor.y - center.y, anchor.z - center.z);
const anchorD = Math.hypot(
anchor.x - center.x,
anchor.y - center.y,
anchor.z - center.z,
);
// A degenerate shell (an anchor at or outside the envelope — no shipped asset
// has one, since every anchor is a measured hull point) leaves nothing to
// ramp across; fall back to the containment verdict rather than divide by it.
@@ -252,8 +266,20 @@ export function modelVisualAnchor(modelMatrix, nativeCenter, scale, result) {
const x = (nativeCenter?.[0] || 0) * safeScale;
const y = (nativeCenter?.[1] || 0) * safeScale;
const z = (nativeCenter?.[2] || 0) * safeScale;
result.x = modelMatrix[0] * x + modelMatrix[4] * y + modelMatrix[8] * z + modelMatrix[12];
result.y = modelMatrix[1] * x + modelMatrix[5] * y + modelMatrix[9] * z + modelMatrix[13];
result.z = modelMatrix[2] * x + modelMatrix[6] * y + modelMatrix[10] * z + modelMatrix[14];
result.x =
modelMatrix[0] * x +
modelMatrix[4] * y +
modelMatrix[8] * z +
modelMatrix[12];
result.y =
modelMatrix[1] * x +
modelMatrix[5] * y +
modelMatrix[9] * z +
modelMatrix[13];
result.z =
modelMatrix[2] * x +
modelMatrix[6] * y +
modelMatrix[10] * z +
modelMatrix[14];
return result;
}
+102 -27
View File
@@ -29,10 +29,14 @@ export function norm360(deg) {
export function liftRepeatedGroundFix(newest, candidatePosition, onGround) {
if (!onGround || !newest?.position || !candidatePosition) return false;
const stored = Cesium.Cartographic.fromCartesian(
newest.position, Cesium.Ellipsoid.WGS84, _mmCarto,
newest.position,
Cesium.Ellipsoid.WGS84,
_mmCarto,
);
const candidate = Cesium.Cartographic.fromCartesian(
candidatePosition, Cesium.Ellipsoid.WGS84, _mmCandidateCarto,
candidatePosition,
Cesium.Ellipsoid.WGS84,
_mmCandidateCarto,
);
if (!stored || !candidate || candidate.height <= stored.height) return false;
Cesium.Cartesian3.fromRadians(
@@ -62,7 +66,11 @@ export function courseBetweenCartesians(from, to, minChordM = 25) {
const dy = to.y - from.y;
const dz = to.z - from.z;
if (dx * dx + dy * dy + dz * dz < minChordM * minChordM) return null;
const carto = Cesium.Cartographic.fromCartesian(from, Cesium.Ellipsoid.WGS84, _mmCarto);
const carto = Cesium.Cartographic.fromCartesian(
from,
Cesium.Ellipsoid.WGS84,
_mmCarto,
);
if (!carto) return null;
const sLat = Math.sin(carto.latitude);
const cLat = Math.cos(carto.latitude);
@@ -110,7 +118,10 @@ export function speedRamp(speedMps) {
if (!Number.isFinite(speedMps)) return 1;
if (speedMps <= COURSE_TRACK_ONLY_MPS) return 0;
if (speedMps >= COURSE_CHORD_ONLY_MPS) return 1;
return (speedMps - COURSE_TRACK_ONLY_MPS) / (COURSE_CHORD_ONLY_MPS - COURSE_TRACK_ONLY_MPS);
return (
(speedMps - COURSE_TRACK_ONLY_MPS) /
(COURSE_CHORD_ONLY_MPS - COURSE_TRACK_ONLY_MPS)
);
}
/** Shortest-arc angle lerp: from → to by t (t=0 → from, t=1 → to). Also the
@@ -141,10 +152,16 @@ export function displayedKinematics({
reportedTrackDeg,
} = {}) {
return {
speedMps: Number.isFinite(derivedSpeedMps) ? Math.max(0, derivedSpeedMps)
: (Number.isFinite(reportedSpeedMps) ? Math.max(0, reportedSpeedMps) : null),
trackDeg: Number.isFinite(derivedTrackDeg) ? derivedTrackDeg
: (Number.isFinite(reportedTrackDeg) ? reportedTrackDeg : null),
speedMps: Number.isFinite(derivedSpeedMps)
? Math.max(0, derivedSpeedMps)
: Number.isFinite(reportedSpeedMps)
? Math.max(0, reportedSpeedMps)
: null,
trackDeg: Number.isFinite(derivedTrackDeg)
? derivedTrackDeg
: Number.isFinite(reportedTrackDeg)
? reportedTrackDeg
: null,
};
}
@@ -167,10 +184,17 @@ export function staleCoastLimitSeconds({
maximumSec = 300,
} = {}) {
const floor = Math.max(0, Number.isFinite(minimumSec) ? minimumSec : 60);
const ceiling = Math.max(floor, Number.isFinite(maximumSec) ? maximumSec : 300);
if (!Number.isFinite(fixEpochMs) || !Number.isFinite(lastContactEpochMs)) return floor;
const ceiling = Math.max(
floor,
Number.isFinite(maximumSec) ? maximumSec : 300,
);
if (!Number.isFinite(fixEpochMs) || !Number.isFinite(lastContactEpochMs))
return floor;
const contactLeadSec = Math.max(0, (lastContactEpochMs - fixEpochMs) / 1000);
const grace = Math.max(0, Number.isFinite(contactGraceSec) ? contactGraceSec : 60);
const grace = Math.max(
0,
Number.isFinite(contactGraceSec) ? contactGraceSec : 60,
);
return Math.min(ceiling, Math.max(floor, contactLeadSec + grace));
}
@@ -197,18 +221,31 @@ export function limitCourseStep(prevDeg, targetDeg, maxDegPerSec, dtSec) {
* is GPS-vector noise, not a turn (samples without a speed keep the legacy
* behavior: no way to tell, so they still count).
*/
export function estimateTurnRateDps(samples, noiseFloorDps = 0.4, maxDps = 4, minSpeedMps = 0) {
export function estimateTurnRateDps(
samples,
noiseFloorDps = 0.4,
maxDps = 4,
minSpeedMps = 0,
) {
if (!samples || samples.length < 2) return 0;
let sum = 0;
let n = 0;
for (let i = 1; i < samples.length; i++) {
const dt = samples[i].tSec - samples[i - 1].tSec;
if (dt < 2 || dt > 120) continue;
if (!Number.isFinite(samples[i].trackDeg) || !Number.isFinite(samples[i - 1].trackDeg)) continue;
if (
!Number.isFinite(samples[i].trackDeg) ||
!Number.isFinite(samples[i - 1].trackDeg)
)
continue;
if (minSpeedMps > 0) {
const v0 = samples[i - 1].speedMps;
const v1 = samples[i].speedMps;
if ((Number.isFinite(v0) && v0 < minSpeedMps) || (Number.isFinite(v1) && v1 < minSpeedMps)) continue;
if (
(Number.isFinite(v0) && v0 < minSpeedMps) ||
(Number.isFinite(v1) && v1 < minSpeedMps)
)
continue;
}
sum += norm180(samples[i].trackDeg - samples[i - 1].trackDeg) / dt;
n += 1;
@@ -274,13 +311,31 @@ const _scratchProjectArc = { east: 0, north: 0, endCourseDeg: 0 };
* @param {number} dtSec - Seconds ahead; 0 or negative returns the start.
* @returns {{lat: number, lon: number}} Projected coordinate, degrees.
*/
export function projectGroundArcLatLon(lat, lon, courseDeg, speedMps, turnRateDps, dtSec) {
export function projectGroundArcLatLon(
lat,
lon,
courseDeg,
speedMps,
turnRateDps,
dtSec,
) {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return { lat, lon };
if (!Number.isFinite(courseDeg) || !Number.isFinite(speedMps) || !Number.isFinite(dtSec)
|| speedMps <= 0 || dtSec <= 0) {
if (
!Number.isFinite(courseDeg) ||
!Number.isFinite(speedMps) ||
!Number.isFinite(dtSec) ||
speedMps <= 0 ||
dtSec <= 0
) {
return { lat, lon };
}
const off = arcOffsetEnu(speedMps, courseDeg, turnRateDps || 0, dtSec, _scratchProjectArc);
const off = arcOffsetEnu(
speedMps,
courseDeg,
turnRateDps || 0,
dtSec,
_scratchProjectArc,
);
// Guard the pole: cos(lat) → 0 would send the longitude to infinity.
const cosLat = Math.max(Math.cos(lat * DEG), 1e-6);
return {
@@ -320,8 +375,15 @@ export function projectGroundArcLatLon(lat, lon, courseDeg, speedMps, turnRateDp
* @returns {Array<{lat: number, lon: number}>} Polyline, display position first.
*/
export function corridorPathLatLon({
extrapolating, displayLat, displayLon, courseDeg, speedMps, turnRateDps = 0,
fixLat, fixLon, lookaheadSec,
extrapolating,
displayLat,
displayLon,
courseDeg,
speedMps,
turnRateDps = 0,
fixLat,
fixLon,
lookaheadSec,
}) {
if (!Number.isFinite(displayLat) || !Number.isFinite(displayLon)) return [];
const start = { lat: displayLat, lon: displayLon };
@@ -338,9 +400,16 @@ export function corridorPathLatLon({
const n = Math.max(1, Math.ceil(arcLengthM / CORRIDOR_SAMPLE_SPACING_M));
const out = [start];
for (let i = 1; i <= n; i++) {
out.push(projectGroundArcLatLon(
displayLat, displayLon, courseDeg, speed, turnRateDps, cappedSec * (i / n),
));
out.push(
projectGroundArcLatLon(
displayLat,
displayLon,
courseDeg,
speed,
turnRateDps,
cappedSec * (i / n),
),
);
}
return out;
}
@@ -385,13 +454,17 @@ const _forwardFixOffset = new Cesium.Cartesian3();
* velocity: number, track: number}|null} Forward synthetic fix, or null.
*/
export function synthesizeForwardKinematicsFix(newest, next = {}) {
if (!newest?.position || !newest?.time || !Number.isFinite(next.epochMs)) return null;
if (!newest?.position || !newest?.time || !Number.isFinite(next.epochMs))
return null;
const startEpochMs = Number.isFinite(newest.epochMs)
? newest.epochMs
: Cesium.JulianDate.toDate(newest.time).getTime();
if (!Number.isFinite(startEpochMs) || next.epochMs <= startEpochMs) return null;
if (!Number.isFinite(startEpochMs) || next.epochMs <= startEpochMs)
return null;
const previousVelocity = Number.isFinite(newest.velocity) ? Math.max(0, newest.velocity) : 0;
const previousVelocity = Number.isFinite(newest.velocity)
? Math.max(0, newest.velocity)
: 0;
const previousTrack = Number.isFinite(newest.track) ? newest.track : 0;
const dtSec = (next.epochMs - startEpochMs) / 1000;
arcOffsetEnu(
@@ -421,7 +494,9 @@ export function synthesizeForwardKinematicsFix(newest, next = {}) {
time: Cesium.JulianDate.fromDate(new Date(next.epochMs)),
epochMs: next.epochMs,
position,
velocity: Number.isFinite(next.velocity) ? Math.max(0, next.velocity) : previousVelocity,
velocity: Number.isFinite(next.velocity)
? Math.max(0, next.velocity)
: previousVelocity,
track: Number.isFinite(next.track) ? next.track : previousTrack,
};
}
+3 -2
View File
@@ -32,7 +32,8 @@ export function resolvePickId(picked) {
if (id === null || id === undefined) return undefined;
if (typeof id === 'object') {
// AIS vessel record (id object with .mmsi) or Cesium Entity (.id string)
if (typeof id.mmsi === 'string' || typeof id.mmsi === 'number') return id.mmsi;
if (typeof id.mmsi === 'string' || typeof id.mmsi === 'number')
return id.mmsi;
if (typeof id.id === 'string' || typeof id.id === 'number') return id.id;
return undefined;
}
@@ -40,7 +41,7 @@ export function resolvePickId(picked) {
};
let id = unwrap(picked.id);
if (id === undefined) id = unwrap(picked.primitive?.id);
return (typeof id === 'string' || typeof id === 'number') ? String(id) : null;
return typeof id === 'string' || typeof id === 'number' ? String(id) : null;
}
/**
+22 -13
View File
@@ -1,6 +1,7 @@
const RADIO_COUNTRY_MAX_LENGTH = 80;
const ISO_ALPHA_2_CODES = Object.freeze(`
const ISO_ALPHA_2_CODES = Object.freeze(
`
AD AE AF AG AI AL AM AO AQ AR AS AT AU AW AX AZ BA BB BD BE BF BG BH BI BJ BL BM BN BO BQ BR BS BT BV BW BY BZ
CA CC CD CF CG CH CI CK CL CM CN CO CR CU CV CW CX CY CZ DE DJ DK DM DO DZ EC EE EG EH ER ES ET FI FJ FK FM FO FR
GA GB GD GE GF GG GH GI GL GM GN GP GQ GR GS GT GU GW GY HK HM HN HR HT HU ID IE IL IM IN IO IQ IR IS IT JE JM JO
@@ -8,12 +9,16 @@ JP KE KG KH KI KM KN KP KR KW KY KZ LA LB LC LI LK LR LS LT LU LV LY MA MC MD ME
MS MT MU MV MW MX MY MZ NA NC NE NF NG NI NL NO NP NR NU NZ OM PA PE PF PG PH PK PL PM PN PR PS PT PW PY QA RE RO
RS RU RW SA SB SC SD SE SG SH SI SJ SK SL SM SN SO SR SS ST SV SX SY SZ TC TD TF TG TH TJ TK TL TM TN TO TR TT TV
TW TZ UA UG UM US UY UZ VA VC VE VG VI VN VU WF WS YE YT ZA ZM ZW
`.trim().split(/\s+/));
`
.trim()
.split(/\s+/),
);
const ISO_ALPHA_2_SET = new Set(ISO_ALPHA_2_CODES);
const ENGLISH_REGION_NAMES = typeof Intl?.DisplayNames === 'function'
? new Intl.DisplayNames(['en'], { type: 'region' })
: null;
const ENGLISH_REGION_NAMES =
typeof Intl?.DisplayNames === 'function'
? new Intl.DisplayNames(['en'], { type: 'region' })
: null;
function countryKey(value) {
return String(value || '')
@@ -29,7 +34,8 @@ function countryKey(value) {
const COUNTRY_NAME_TO_CODE = new Map();
for (const code of ISO_ALPHA_2_CODES) {
const displayName = ENGLISH_REGION_NAMES?.of(code);
if (displayName && displayName !== code) COUNTRY_NAME_TO_CODE.set(countryKey(displayName), code);
if (displayName && displayName !== code)
COUNTRY_NAME_TO_CODE.set(countryKey(displayName), code);
}
for (const [name, code] of Object.entries({
@@ -71,7 +77,8 @@ for (const [name, code] of Object.entries({
'east timor': 'TL',
'cabo verde': 'CV',
vatican: 'VA',
})) COUNTRY_NAME_TO_CODE.set(countryKey(name), code);
}))
COUNTRY_NAME_TO_CODE.set(countryKey(name), code);
function canonicalCountryName(code) {
return ENGLISH_REGION_NAMES?.of(code) || code;
@@ -90,17 +97,19 @@ export function normalizeRadioCountryInput(value) {
}
const trimmed = value.normalize('NFKC').trim().replace(/\s+/g, ' ');
if (
!trimmed
|| trimmed.length > RADIO_COUNTRY_MAX_LENGTH
|| /[\u0000-\u001f\u007f]/.test(trimmed)
|| !/^[\p{L}\p{M}.&'’()\-\s]+$/u.test(trimmed)
) return Object.freeze({ valid: false, empty: false, code: '', name: '' });
!trimmed ||
trimmed.length > RADIO_COUNTRY_MAX_LENGTH ||
/[\u0000-\u001f\u007f]/.test(trimmed) ||
!/^[\p{L}\p{M}.&'’()\-\s]+$/u.test(trimmed)
)
return Object.freeze({ valid: false, empty: false, code: '', name: '' });
const possibleCode = trimmed.toUpperCase();
const code = ISO_ALPHA_2_SET.has(possibleCode)
? possibleCode
: COUNTRY_NAME_TO_CODE.get(countryKey(trimmed)) || '';
if (!code) return Object.freeze({ valid: false, empty: false, code: '', name: '' });
if (!code)
return Object.freeze({ valid: false, empty: false, code: '', name: '' });
return Object.freeze({
valid: true,
empty: false,
+2 -1
View File
@@ -2,6 +2,7 @@ import { applicationServices } from '../services/application.js';
export * from './regionalModel.js';
/** Fetch a bounded regional brief through the same-origin dev/preview proxy. */
export async function fetchRegionalBrief(latitude, longitude, { signal } = {}) {
if (![latitude, longitude].every(Number.isFinite)) throw new Error('Valid coordinates are required');
if (![latitude, longitude].every(Number.isFinite))
throw new Error('Valid coordinates are required');
return applicationServices.regional.getBrief(latitude, longitude, { signal });
}
+52 -20
View File
@@ -1,13 +1,18 @@
const MAX_ARTICLES = 5;
function cleanText(value, maxLength = 180) {
return String(value || '').replace(/\s+/g, ' ').trim().slice(0, maxLength);
return String(value || '')
.replace(/\s+/g, ' ')
.trim()
.slice(0, maxLength);
}
function safeHttpUrl(value) {
try {
const parsed = new URL(String(value || ''));
return parsed.protocol === 'http:' || parsed.protocol === 'https:' ? parsed.href : null;
return parsed.protocol === 'http:' || parsed.protocol === 'https:'
? parsed.href
: null;
} catch {
return null;
}
@@ -17,14 +22,27 @@ function safeHttpUrl(value) {
export function normalizeRegionalPlace(payload) {
const address = payload?.address || {};
const locality = cleanText(
address.city || address.town || address.village || address.municipality
|| address.hamlet || address.county,
address.city ||
address.town ||
address.village ||
address.municipality ||
address.hamlet ||
address.county,
90,
);
const region = cleanText(
address.state || address.region || address.county,
90,
);
const region = cleanText(address.state || address.region || address.county, 90);
const country = cleanText(address.country, 90);
const label = [locality, region].filter((value, index, values) => value && values.indexOf(value) === index)
.join(', ') || country || cleanText(payload?.display_name, 120);
const label =
[locality, region]
.filter(
(value, index, values) => value && values.indexOf(value) === index,
)
.join(', ') ||
country ||
cleanText(payload?.display_name, 120);
if (!label) return null;
return {
label,
@@ -51,11 +69,16 @@ export function normalizeRegionalArticles(payload, limit = MAX_ARTICLES) {
const compactDate = /^(\d{8})T(\d{6})Z$/.exec(rawDate);
const publishedAt = compactDate
? `${compactDate[1].slice(0, 4)}-${compactDate[1].slice(4, 6)}-${compactDate[1].slice(6, 8)}T${compactDate[2].slice(0, 2)}:${compactDate[2].slice(2, 4)}:${compactDate[2].slice(4, 6)}Z`
: Number.isNaN(Date.parse(rawDate)) ? null : new Date(rawDate).toISOString();
: Number.isNaN(Date.parse(rawDate))
? null
: new Date(rawDate).toISOString();
articles.push({
title,
url,
domain: cleanText(row?.domain || new URL(url).hostname.replace(/^www\./, ''), 80),
domain: cleanText(
row?.domain || new URL(url).hostname.replace(/^www\./, ''),
80,
),
publishedAt,
sourceCountry: cleanText(row?.sourcecountry, 60) || null,
});
@@ -74,11 +97,15 @@ export function normalizeRegionalWeather(payload) {
};
// Open-Meteo reports zone-naive timestamps ("2026-08-17T00:15") that are UTC,
// but JS parses zoneless date-times as LOCAL — pin them to UTC explicitly.
const observedRaw = typeof current.time === 'string' && !/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(current.time)
? `${current.time}Z`
: current.time;
const observedRaw =
typeof current.time === 'string' &&
!/(?:[zZ]|[+-]\d\d:?\d\d)$/.test(current.time)
? `${current.time}Z`
: current.time;
return {
observedAt: Number.isNaN(Date.parse(observedRaw)) ? null : new Date(observedRaw).toISOString(),
observedAt: Number.isNaN(Date.parse(observedRaw))
? null
: new Date(observedRaw).toISOString(),
temperatureC: numberOrNull(current.temperature_2m),
apparentTemperatureC: numberOrNull(current.apparent_temperature),
precipitationMm: numberOrNull(current.precipitation),
@@ -109,14 +136,19 @@ export function weatherCodeLabel(code) {
/** Great-circle distance used to avoid refetching a regional brief every animation frame. */
export function regionalDistanceM(from, to) {
if (![from?.latitude, from?.longitude, to?.latitude, to?.longitude].every(Number.isFinite)) {
if (
![from?.latitude, from?.longitude, to?.latitude, to?.longitude].every(
Number.isFinite,
)
) {
return Infinity;
}
const phi1 = from.latitude * Math.PI / 180;
const phi2 = to.latitude * Math.PI / 180;
const deltaPhi = (to.latitude - from.latitude) * Math.PI / 180;
const deltaLambda = (to.longitude - from.longitude) * Math.PI / 180;
const a = Math.sin(deltaPhi / 2) ** 2
+ Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
const phi1 = (from.latitude * Math.PI) / 180;
const phi2 = (to.latitude * Math.PI) / 180;
const deltaPhi = ((to.latitude - from.latitude) * Math.PI) / 180;
const deltaLambda = ((to.longitude - from.longitude) * Math.PI) / 180;
const a =
Math.sin(deltaPhi / 2) ** 2 +
Math.cos(phi1) * Math.cos(phi2) * Math.sin(deltaLambda / 2) ** 2;
return 6371000 * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
+13 -2
View File
@@ -26,7 +26,13 @@
* none of the above are usable — the caller applies its OWN existing sticky/default
* fallback (this helper never invents one, so it can't drift from the caller's policy).
*/
export function pickRenderAltitudeM({ geoAltM, baroAltM, onGround, surfaceM, geoidN }) {
export function pickRenderAltitudeM({
geoAltM,
baroAltM,
onGround,
surfaceM,
geoidN,
}) {
if (onGround && Number.isFinite(surfaceM)) {
return surfaceM;
}
@@ -89,7 +95,12 @@ export function reuseGroundedSurfaceM(currentM, previousM) {
* @param {number|null|undefined} params.geoidN - Geoid undulation N here.
* @returns {number|null} The geoid guess, or null when it must not be used.
*/
export function geoidSurfaceLastResortM({ geoAltM, baroAltM, priorRenderM, geoidN }) {
export function geoidSurfaceLastResortM({
geoAltM,
baroAltM,
priorRenderM,
geoidN,
}) {
if (Number.isFinite(geoAltM) || Number.isFinite(baroAltM)) return null;
if (Number.isFinite(priorRenderM)) return null;
return Number.isFinite(geoidN) ? geoidN : null;
+12 -6
View File
@@ -34,11 +34,14 @@ export const RETRY_COOLDOWN_MAX_MS = 300_000;
* @param {() => number} [options.now] - Clock seam for tests.
* @returns {() => Promise<T>} Memoized loader; retries once the cooldown elapses.
*/
export function createRetryableLoader(load, {
cooldownMs = RETRY_COOLDOWN_MS,
maxCooldownMs = RETRY_COOLDOWN_MAX_MS,
now = () => Date.now(),
} = {}) {
export function createRetryableLoader(
load,
{
cooldownMs = RETRY_COOLDOWN_MS,
maxCooldownMs = RETRY_COOLDOWN_MAX_MS,
now = () => Date.now(),
} = {},
) {
/** @type {Promise<T>|null} */
let inflight = null;
/** @type {*} Last rejection, replayed to callers inside the cooldown. */
@@ -51,7 +54,10 @@ export function createRetryableLoader(load, {
return function loadOnce() {
if (inflight) return inflight;
if (hasFailure) {
const wait = Math.min(cooldownMs * 2 ** (consecutiveFailures - 1), maxCooldownMs);
const wait = Math.min(
cooldownMs * 2 ** (consecutiveFailures - 1),
maxCooldownMs,
);
// Replay the recorded reason rather than re-running a loader that is
// probably still broken. Callers see identical behavior either way.
if (now() - failedAt < wait) return Promise.reject(failure);
+44 -12
View File
@@ -19,7 +19,8 @@ export function greatCircleKm(lat1, lon1, lat2, lon2) {
const p2 = lat2 * D2R;
const dp = (lat2 - lat1) * D2R;
const dl = (lon2 - lon1) * D2R;
const a = Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
const a =
Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
return R_KM * 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
}
@@ -28,7 +29,8 @@ function bearingRad(lat1, lon1, lat2, lon2) {
const p2 = lat2 * D2R;
const dl = (lon2 - lon1) * D2R;
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
const x =
Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return Math.atan2(y, x);
}
@@ -42,8 +44,8 @@ export function crossTrackKm(lat, lon, lat1, lon1, lat2, lon2) {
const NEAR_ENDPOINT_KM = 130;
const CROSS_TRACK_KM = 200;
const LOW_ALT_M = 3700; // ~12 000 ft
const VERT_TREND_MPS = 2; // ~400 fpm
const LOW_ALT_M = 3700; // ~12 000 ft
const VERT_TREND_MPS = 2; // ~400 fpm
const LOCAL_AIRPORT_KM = 150;
/**
@@ -55,16 +57,35 @@ const LOCAL_AIRPORT_KM = 150;
* @param {{lat:number|null, lon:number|null}|null} [p.destination]
* @returns {boolean} false ONLY when the route is confidently wrong.
*/
export function routePlausible({ latDeg, lonDeg, altitudeM = null, verticalRateMps = null, origin = null, destination = null }) {
export function routePlausible({
latDeg,
lonDeg,
altitudeM = null,
verticalRateMps = null,
origin = null,
destination = null,
}) {
const haveO = Number.isFinite(origin?.lat) && Number.isFinite(origin?.lon);
const haveD = Number.isFinite(destination?.lat) && Number.isFinite(destination?.lon);
const haveD =
Number.isFinite(destination?.lat) && Number.isFinite(destination?.lon);
if (!haveO && !haveD) return true; // no coordinates — cannot judge, do not hide
// (a) Geographic consistency: near an endpoint, or roughly on the path.
const near = (pt) => greatCircleKm(latDeg, lonDeg, pt.lat, pt.lon) < NEAR_ENDPOINT_KM;
const near = (pt) =>
greatCircleKm(latDeg, lonDeg, pt.lat, pt.lon) < NEAR_ENDPOINT_KM;
let geomOk = (haveO && near(origin)) || (haveD && near(destination));
if (!geomOk && haveO && haveD) {
geomOk = Math.abs(crossTrackKm(latDeg, lonDeg, origin.lat, origin.lon, destination.lat, destination.lon)) < CROSS_TRACK_KM;
geomOk =
Math.abs(
crossTrackKm(
latDeg,
lonDeg,
origin.lat,
origin.lon,
destination.lat,
destination.lon,
),
) < CROSS_TRACK_KM;
} else if (!geomOk) {
geomOk = true; // only one endpoint known and not near — cannot judge, allow
}
@@ -72,13 +93,24 @@ export function routePlausible({ latDeg, lonDeg, altitudeM = null, verticalRateM
// (b) Vertical-trend consistency for low traffic (observer-free adaptation).
if (
Number.isFinite(altitudeM) && altitudeM < LOW_ALT_M &&
Number.isFinite(verticalRateMps) && Math.abs(verticalRateMps) > VERT_TREND_MPS
Number.isFinite(altitudeM) &&
altitudeM < LOW_ALT_M &&
Number.isFinite(verticalRateMps) &&
Math.abs(verticalRateMps) > VERT_TREND_MPS
) {
if (verticalRateMps > 0) {
if (haveO && greatCircleKm(latDeg, lonDeg, origin.lat, origin.lon) > LOCAL_AIRPORT_KM) return false; // departing — origin should be local
if (
haveO &&
greatCircleKm(latDeg, lonDeg, origin.lat, origin.lon) > LOCAL_AIRPORT_KM
)
return false; // departing — origin should be local
} else {
if (haveD && greatCircleKm(latDeg, lonDeg, destination.lat, destination.lon) > LOCAL_AIRPORT_KM) return false; // arriving — destination should be local
if (
haveD &&
greatCircleKm(latDeg, lonDeg, destination.lat, destination.lon) >
LOCAL_AIRPORT_KM
)
return false; // arriving — destination should be local
}
}
return true;
+19 -4
View File
@@ -69,7 +69,13 @@ export const SATELLITE_CLASSES = Object.freeze({
});
/** Legend/report order for the classes above. */
export const SATELLITE_CLASS_ORDER = Object.freeze(['station', 'nav', 'geo', 'visual', 'comms']);
export const SATELLITE_CLASS_ORDER = Object.freeze([
'station',
'nav',
'geo',
'visual',
'comms',
]);
/**
* CelesTrak group tag → { class, subtype }. Subtype names the specific
@@ -150,8 +156,11 @@ export function satelliteClassLabel(group, { isIss = false } = {}) {
export function tallySatelliteClasses(entries) {
const counts = Object.create(null);
for (const entry of entries || []) {
const descriptor = entry && typeof entry === 'object' ? entry : { group: entry };
const { klass } = satelliteClassOf(descriptor.group, { isIss: descriptor.isIss });
const descriptor =
entry && typeof entry === 'object' ? entry : { group: entry };
const { klass } = satelliteClassOf(descriptor.group, {
isIss: descriptor.isIss,
});
counts[klass] = (counts[klass] || 0) + 1;
}
return counts;
@@ -171,7 +180,13 @@ export function satelliteClassLegend(counts) {
const count = counts?.[klass];
if (!(count > 0)) continue;
const spec = SATELLITE_CLASSES[klass];
result.push({ klass, label: spec.label, color: spec.color, blurb: spec.blurb, count });
result.push({
klass,
label: spec.label,
color: spec.color,
blurb: spec.blurb,
count,
});
}
return result;
}
+2 -1
View File
@@ -42,7 +42,8 @@ const MAX_PICK_MAGNITUDE_M = 1_000_000_000;
export function isPickedWorldPosition(position) {
if (!position) return false;
const { x, y, z } = position;
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z)) return false;
if (!Number.isFinite(x) || !Number.isFinite(y) || !Number.isFinite(z))
return false;
const magnitude = Math.hypot(x, y, z);
return magnitude >= MIN_PICK_MAGNITUDE_M && magnitude <= MAX_PICK_MAGNITUDE_M;
}
+6 -2
View File
@@ -3,6 +3,8 @@ export const SPRITE_LAYER_ORDER = Object.freeze([
'cctv',
'firms',
'bikeshare',
'transit',
'transit-motion',
'directions',
'ais',
'military',
@@ -45,7 +47,8 @@ export function restoreSpriteOrder(viewer) {
if (!viewer || viewer.isDestroyed?.()) return;
const scene = viewer.scene;
const primitives = scene?.primitives;
if (!primitives || scene.isDestroyed?.() || primitives.isDestroyed?.()) return;
if (!primitives || scene.isDestroyed?.() || primitives.isDestroyed?.())
return;
for (const layerId of SPRITE_LAYER_ORDER) {
const collection = _collections.get(layerId);
@@ -69,6 +72,7 @@ export function restoreSpriteOrderOnEnable(
viewer,
restore = restoreSpriteOrder,
) {
if (!SPRITE_LAYER_ORDER.includes(layerId) || typeof restore !== 'function') return;
if (!SPRITE_LAYER_ORDER.includes(layerId) || typeof restore !== 'function')
return;
restore(viewer);
}
+8 -2
View File
@@ -1,4 +1,10 @@
import { createTerrainHeights } from '../services/terrainHeights.js';
import { applicationServices } from '../services/application.js';
const terrainHeights = createTerrainHeights({ source: applicationServices.terrain });
export const { cachedEllipsoidalGround, cachedRealEllipsoidalGround, resolveEllipsoidalGround } = terrainHeights;
const terrainHeights = createTerrainHeights({
source: applicationServices.terrain,
});
export const {
cachedEllipsoidalGround,
cachedRealEllipsoidalGround,
resolveEllipsoidalGround,
} = terrainHeights;
+3 -1
View File
@@ -38,7 +38,9 @@ export const TR3B_CLASS = 'tr3b';
/** @param {*} id Raw contact id. @returns {string} Normalized registry key. */
function key(id) {
return String(id ?? '').trim().toLowerCase();
return String(id ?? '')
.trim()
.toLowerCase();
}
/**
+37 -19
View File
@@ -26,17 +26,23 @@ export function trackedModelScaleForPixelCap({
maximumPixelSize,
}) {
if (
!Number.isFinite(baseScale) || baseScale <= 0
|| !Number.isFinite(nativeRadiusM) || nativeRadiusM <= 0
|| !Number.isFinite(rangeM) || rangeM <= 0
|| !Number.isFinite(viewportHeightPx) || viewportHeightPx <= 0
|| !Number.isFinite(fovyRad) || fovyRad <= 0
|| !Number.isFinite(maximumPixelSize) || maximumPixelSize <= 0
) return baseScale;
!Number.isFinite(baseScale) ||
baseScale <= 0 ||
!Number.isFinite(nativeRadiusM) ||
nativeRadiusM <= 0 ||
!Number.isFinite(rangeM) ||
rangeM <= 0 ||
!Number.isFinite(viewportHeightPx) ||
viewportHeightPx <= 0 ||
!Number.isFinite(fovyRad) ||
fovyRad <= 0 ||
!Number.isFinite(maximumPixelSize) ||
maximumPixelSize <= 0
)
return baseScale;
const focalLengthPx = viewportHeightPx / (2 * Math.tan(fovyRad / 2));
const projectedDiameterPx = (
2 * nativeRadiusM * baseScale * focalLengthPx
) / rangeM;
const projectedDiameterPx =
(2 * nativeRadiusM * baseScale * focalLengthPx) / rangeM;
if (projectedDiameterPx <= maximumPixelSize) return baseScale;
return baseScale * (maximumPixelSize / projectedDiameterPx);
}
@@ -99,17 +105,25 @@ export function clampTrackedCameraPosition(
previousPosition,
minimumRangeM = MIN_TRACKED_RANGE_M,
) {
const crossedOrigin = Cesium.Cartesian3.dot(camera.position, previousPosition) <= 0;
const forwardDistance = -Cesium.Cartesian3.dot(camera.position, camera.direction);
const crossedOrigin =
Cesium.Cartesian3.dot(camera.position, previousPosition) <= 0;
const forwardDistance = -Cesium.Cartesian3.dot(
camera.position,
camera.direction,
);
const rangeSquared = Cesium.Cartesian3.magnitudeSquared(camera.position);
if (crossedOrigin) {
Cesium.Cartesian3.normalize(previousPosition, camera.position);
Cesium.Cartesian3.multiplyByScalar(camera.position, minimumRangeM, camera.position);
Cesium.Cartesian3.multiplyByScalar(
camera.position,
minimumRangeM,
camera.position,
);
return true;
}
if (
forwardDistance < minimumRangeM
|| rangeSquared < minimumRangeM * minimumRangeM
forwardDistance < minimumRangeM ||
rangeSquared < minimumRangeM * minimumRangeM
) {
Cesium.Cartesian3.multiplyByScalar(
camera.direction,
@@ -192,10 +206,14 @@ export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
Cesium.Ellipsoid.WGS84,
trackedTransform,
);
const offset = typeof viewFrom.getValue === 'function'
? viewFrom.getValue(viewer.clock.currentTime, resolvedViewFrom)
: Cesium.Cartesian3.clone(viewFrom, resolvedViewFrom);
if (!offset || Cesium.Cartesian3.magnitudeSquared(offset) < Cesium.Math.EPSILON12) {
const offset =
typeof viewFrom.getValue === 'function'
? viewFrom.getValue(viewer.clock.currentTime, resolvedViewFrom)
: Cesium.Cartesian3.clone(viewFrom, resolvedViewFrom);
if (
!offset ||
Cesium.Cartesian3.magnitudeSquared(offset) < Cesium.Math.EPSILON12
) {
stop();
return;
}
+4 -1
View File
@@ -76,5 +76,8 @@ export const TRACKED_MODEL_EXIT_ALT_M =
*/
export function trackedModelZoomActive(cameraHeightM, wasActive = false) {
if (!Number.isFinite(cameraHeightM)) return false;
return cameraHeightM < (wasActive ? TRACKED_MODEL_EXIT_ALT_M : TRACKED_MODEL_ENTER_ALT_M);
return (
cameraHeightM <
(wasActive ? TRACKED_MODEL_EXIT_ALT_M : TRACKED_MODEL_ENTER_ALT_M)
);
}
+59 -21
View File
@@ -49,17 +49,24 @@ let _overlayHost = DEFAULT_TRACKED_OVERLAY_HOST;
* @param {string} accent Source-owned accent color.
* @returns {{title:string,details:string[],accent:string}}
*/
export function trackedLabelModelFromText(text, accent = WORLD_OVERLAY_STYLE.accent) {
export function trackedLabelModelFromText(
text,
accent = WORLD_OVERLAY_STYLE.accent,
) {
const raw = String(text || '').trim();
if (!raw) return { title: '', details: [], accent };
let lines;
if (raw.includes('\n')) {
lines = raw.split('\n').map((line) => line.trim()).filter(Boolean);
lines = raw
.split('\n')
.map((line) => line.trim())
.filter(Boolean);
} else {
const parts = raw.split(' · ');
lines = parts.length > 1
? [parts[0].trim(), parts.slice(1).join(' · ').trim()]
: [raw];
lines =
parts.length > 1
? [parts[0].trim(), parts.slice(1).join(' · ').trim()]
: [raw];
}
return { title: lines[0] || '', details: lines.slice(1), accent };
}
@@ -101,7 +108,9 @@ export function cachedTrackedVisualPosition(entity) {
try {
const visual = entity.gevVisualPosition();
if (visual) return visual;
} catch { /* fall through to the display position */ }
} catch {
/* fall through to the display position */
}
}
return cachedTrackedDisplayPosition(entity);
}
@@ -140,7 +149,9 @@ export function createTrackedOverlayEntry(entity) {
collisionGroup: 'ambient-card',
priority: Number.MAX_SAFE_INTEGER,
title,
details: Array.isArray(model.details) ? model.details.map((line) => String(line)) : [],
details: Array.isArray(model.details)
? model.details.map((line) => String(line))
: [],
accent: model.accent || WORLD_OVERLAY_STYLE.accent,
cardStyle: model.cardStyle,
selected: model.selected === true,
@@ -149,9 +160,14 @@ export function createTrackedOverlayEntry(entity) {
leaderAnimationStartedAt: model.leaderAnimationStartedAt,
leaderDrawRatio: model.leaderDrawRatio,
anchorRadiusPx: Number.isFinite(Number(model.anchorRadiusPx))
? Math.max(0, Number(model.anchorRadiusPx)) : 10,
anchorRadiusScale: Object.prototype.hasOwnProperty.call(model, 'anchorRadiusScale')
? model.anchorRadiusScale : TRACKED_BILLBOARD_SCALE,
? Math.max(0, Number(model.anchorRadiusPx))
: 10,
anchorRadiusScale: Object.prototype.hasOwnProperty.call(
model,
'anchorRadiusScale',
)
? model.anchorRadiusScale
: TRACKED_BILLBOARD_SCALE,
minAnchorGapPx: 16,
anchorGapPaddingPx: 10,
verticalOnly: true,
@@ -203,7 +219,10 @@ export function getActiveTrackedReadoutId() {
}
/** Static-context layers whose click selection publishes the readout card. */
const READOUT_CONTEXT_LAYERS = new Set(['military-installations', 'alpr-cameras']);
const READOUT_CONTEXT_LAYERS = new Set([
'military-installations',
'alpr-cameras',
]);
/**
* Initialize the model bridge and selection listeners. No render listener is
@@ -215,10 +234,11 @@ export function initTrackedReadout(viewer) {
if (_viewer) destroyTrackedReadout();
_viewer = viewer;
_overlayHost.setVisible(TRACKED_OVERLAY_SOURCE_ID, true);
_trackedEntityChangedRemove = viewer.trackedEntityChanged?.addEventListener?.(() => {
if (viewer.trackedEntity) _selectedContext = null;
syncActiveEntity();
}) || null;
_trackedEntityChangedRemove =
viewer.trackedEntityChanged?.addEventListener?.(() => {
if (viewer.trackedEntity) _selectedContext = null;
syncActiveEntity();
}) || null;
_contextSelectedHandler = (event) => {
const record = event.detail;
if (READOUT_CONTEXT_LAYERS.has(record?.layerId)) {
@@ -232,7 +252,10 @@ export function initTrackedReadout(viewer) {
}
};
_contextClearedHandler = (event) => {
if (!_selectedContext || event.detail?.layerId === _selectedContext.layerId) {
if (
!_selectedContext ||
event.detail?.layerId === _selectedContext.layerId
) {
_selectedContext = null;
syncActiveEntity();
}
@@ -242,8 +265,14 @@ export function initTrackedReadout(viewer) {
if (!_viewer?.trackedEntity) clearTrackedSource();
};
window.addEventListener('gev:entity-selected', _contextSelectedHandler);
window.addEventListener('gev:entity-selection-cleared', _contextClearedHandler);
window.addEventListener('gev:awareness-subject-selected', _aircraftSelectedHandler);
window.addEventListener(
'gev:entity-selection-cleared',
_contextClearedHandler,
);
window.addEventListener(
'gev:awareness-subject-selected',
_aircraftSelectedHandler,
);
syncActiveEntity();
// Boot-verification contract: the track regression harness asserts this
// exact line at init (dropped by the host migration; restored).
@@ -254,9 +283,18 @@ export function initTrackedReadout(viewer) {
export function destroyTrackedReadout() {
_trackedEntityChangedRemove?.();
_trackedEntityChangedRemove = null;
if (_contextSelectedHandler) window.removeEventListener('gev:entity-selected', _contextSelectedHandler);
if (_contextClearedHandler) window.removeEventListener('gev:entity-selection-cleared', _contextClearedHandler);
if (_aircraftSelectedHandler) window.removeEventListener('gev:awareness-subject-selected', _aircraftSelectedHandler);
if (_contextSelectedHandler)
window.removeEventListener('gev:entity-selected', _contextSelectedHandler);
if (_contextClearedHandler)
window.removeEventListener(
'gev:entity-selection-cleared',
_contextClearedHandler,
);
if (_aircraftSelectedHandler)
window.removeEventListener(
'gev:awareness-subject-selected',
_aircraftSelectedHandler,
);
_contextSelectedHandler = null;
_contextClearedHandler = null;
_aircraftSelectedHandler = null;
+10 -3
View File
@@ -28,8 +28,10 @@ export function isTrackingClickGesture(gesture = {}) {
const durationMs = Number.isFinite(gesture.durationMs)
? Math.max(0, gesture.durationMs)
: Number.POSITIVE_INFINITY;
return isTrackingSelectionGesture(gesture)
&& durationMs <= MAX_TRACKING_CLICK_DURATION_MS;
return (
isTrackingSelectionGesture(gesture) &&
durationMs <= MAX_TRACKING_CLICK_DURATION_MS
);
}
/**
@@ -53,7 +55,12 @@ export function bindTrackingClickGesture(handler, onClick, options = {}) {
let completedGesture = null;
const appendTravel = (position) => {
if (!pressActive || !Number.isFinite(position?.x) || !Number.isFinite(position?.y)) return;
if (
!pressActive ||
!Number.isFinite(position?.x) ||
!Number.isFinite(position?.y)
)
return;
if (previousPosition) {
travelPx += Math.hypot(
position.x - previousPosition.x,
+19 -9
View File
@@ -33,8 +33,8 @@ export function greatCircleKm(lat1, lon1, lat2, lon2) {
const p2 = toRad(lat2);
const dp = toRad(lat2 - lat1);
const dl = toRad(lon2 - lon1);
const a = Math.sin(dp / 2) ** 2
+ Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
const a =
Math.sin(dp / 2) ** 2 + Math.cos(p1) * Math.cos(p2) * Math.sin(dl / 2) ** 2;
return 2 * EARTH_RADIUS_KM * Math.asin(Math.min(1, Math.sqrt(a)));
}
@@ -49,7 +49,8 @@ function initialBearingRad(lat1, lon1, lat2, lon2) {
const p2 = toRad(lat2);
const dl = toRad(lon2 - lon1);
const y = Math.sin(dl) * Math.cos(p2);
const x = Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
const x =
Math.cos(p1) * Math.sin(p2) - Math.sin(p1) * Math.cos(p2) * Math.cos(dl);
return Math.atan2(y, x);
}
@@ -68,12 +69,15 @@ function destinationPoint(lat, lon, bearingRad, distKm) {
const p1 = toRad(lat);
const l1 = toRad(lon);
const p2 = Math.asin(
Math.sin(p1) * Math.cos(delta) + Math.cos(p1) * Math.sin(delta) * Math.cos(bearingRad)
);
const l2 = l1 + Math.atan2(
Math.sin(bearingRad) * Math.sin(delta) * Math.cos(p1),
Math.cos(delta) - Math.sin(p1) * Math.sin(p2)
Math.sin(p1) * Math.cos(delta) +
Math.cos(p1) * Math.sin(delta) * Math.cos(bearingRad),
);
const l2 =
l1 +
Math.atan2(
Math.sin(bearingRad) * Math.sin(delta) * Math.cos(p1),
Math.cos(delta) - Math.sin(p1) * Math.sin(p2),
);
// Normalize longitude to [-180, 180)
const lonDeg = ((toDeg(l2) + 540) % 360) - 180;
return { lat: toDeg(p2), lon: lonDeg };
@@ -100,7 +104,13 @@ function destinationPoint(lat, lon, bearingRad, distKm) {
* @returns {{lat:number, lon:number, source:'hit'|'nadir'|'pulled'}}
* The fetch center and which rule produced it.
*/
export function deriveFetchCenter({ nadirLat, nadirLon, hitLat, hitLon, maxPullKm = 12 }) {
export function deriveFetchCenter({
nadirLat,
nadirLon,
hitLat,
hitLon,
maxPullKm = 12,
}) {
if (!Number.isFinite(hitLat) || !Number.isFinite(hitLon)) {
return { lat: nadirLat, lon: nadirLon, source: 'nadir' };
}
+30 -9
View File
@@ -36,9 +36,9 @@
/** @const {Object<string,'mono'|'crt'>} Style name → non-normal profile. */
const PROFILE_BY_STYLE = {
surveillance: 'mono', // NVG — P43 phosphor × luma
thermal: 'mono', // FLIR — grayscale/ironbow × luma
noir: 'mono', // full desaturation
retro: 'crt', // CRT — hue survives, small dots don't
thermal: 'mono', // FLIR — grayscale/ironbow × luma
noir: 'mono', // full desaturation
retro: 'crt', // CRT — hue survives, small dots don't
};
/**
@@ -49,13 +49,33 @@ const PROFILE_BY_STYLE = {
*/
const DOT_STYLE = {
mono: {
jam: { rgba: [255, 255, 255, 0.95], sizeDelta: 3, outline: { rgba: [0, 0, 0, 0.9], width: 2 } },
slow: { rgba: [255, 255, 255, 0.9], sizeDelta: 1, outline: { rgba: [0, 0, 0, 0.85], width: 1 } },
free: { rgba: [255, 255, 255, 0.85], sizeDelta: 0, outline: { rgba: [0, 0, 0, 0.8], width: 1 } },
jam: {
rgba: [255, 255, 255, 0.95],
sizeDelta: 3,
outline: { rgba: [0, 0, 0, 0.9], width: 2 },
},
slow: {
rgba: [255, 255, 255, 0.9],
sizeDelta: 1,
outline: { rgba: [0, 0, 0, 0.85], width: 1 },
},
free: {
rgba: [255, 255, 255, 0.85],
sizeDelta: 0,
outline: { rgba: [0, 0, 0, 0.8], width: 1 },
},
},
crt: {
jam: { rgba: [255, 59, 48, 0.95], sizeDelta: 3, outline: { rgba: [0, 0, 0, 0.9], width: 2 } },
slow: { rgba: [255, 179, 0, 0.92], sizeDelta: 2, outline: { rgba: [0, 0, 0, 0.85], width: 1 } },
jam: {
rgba: [255, 59, 48, 0.95],
sizeDelta: 3,
outline: { rgba: [0, 0, 0, 0.9], width: 2 },
},
slow: {
rgba: [255, 179, 0, 0.92],
sizeDelta: 2,
outline: { rgba: [0, 0, 0, 0.85], width: 1 },
},
free: { rgba: [0, 255, 102, 0.9], sizeDelta: 1, outline: null },
},
};
@@ -123,7 +143,8 @@ export function presetDotOutline(styleName, bucket) {
* @returns {string|null} Tier key, or null (no override → stock 'vehicle').
*/
export function trafficBucketTier(bucket) {
if (bucket === 'free' || bucket === 'slow' || bucket === 'jam') return `veh_${bucket}`;
if (bucket === 'free' || bucket === 'slow' || bucket === 'jam')
return `veh_${bucket}`;
if (bucket === 'sim') return 'veh_nodata';
return null;
}
+3 -2
View File
@@ -33,13 +33,14 @@ const GAP_SPREAD_M = 6;
*/
export function queuePlatoons(totalLen, count, rng = Math.random) {
const platoons = [];
if (!Number.isFinite(totalLen) || totalLen <= 0 || !(count > 0)) return platoons;
if (!Number.isFinite(totalLen) || totalLen <= 0 || !(count > 0))
return platoons;
let placed = 0;
while (placed < count) {
const platoonSize = Math.min(
count - placed,
PLATOON_MIN + Math.floor(rng() * PLATOON_SPREAD)
PLATOON_MIN + Math.floor(rng() * PLATOON_SPREAD),
);
const anchor = rng() * totalLen;
const platoon = [];
+14 -3
View File
@@ -28,7 +28,9 @@ import { registerPickOwner } from './pickRegistry.js';
// plane being tracked. Claiming the 'gev-trail:' id namespace makes
// isOwnedByOtherLayer() true for every layer — clicking a trail is a no-op
// everywhere. Registered once at module load; the predicate is pure.
registerPickOwner('trails', (pickedId) => String(pickedId).startsWith('gev-trail:'));
registerPickOwner('trails', (pickedId) =>
String(pickedId).startsWith('gev-trail:'),
);
/** @type {number} Uniquifier for trail entity ids (Cesium requires unique entity ids). */
let _trailSeq = 0;
@@ -99,7 +101,12 @@ export function createTrail(viewer, { color, width = 2.5 }) {
for (const position of Array.isArray(cartesians) ? cartesians : []) {
if (!position) continue;
const last = positions[positions.length - 1];
if (last && Cesium.Cartesian3.distanceSquared(last, position) < MIN_SEGMENT_DISTANCE_SQ) continue;
if (
last &&
Cesium.Cartesian3.distanceSquared(last, position) <
MIN_SEGMENT_DISTANCE_SQ
)
continue;
positions.push(position);
}
current = positions.length >= 2 ? positions : [];
@@ -122,7 +129,11 @@ export function createTrail(viewer, { color, width = 2.5 }) {
destroyed = true;
current = [];
if (entity && viewer && !viewer.isDestroyed()) {
try { viewer.entities.remove(entity); } catch { /* torn down */ }
try {
viewer.entities.remove(entity);
} catch {
/* torn down */
}
}
entity = null;
},
+56
View File
@@ -0,0 +1,56 @@
import { createTransitLayer } from '../layers/transit/index.js';
import * as render from '../renderGovernor.js';
import * as sprites from './spriteOrder.js';
import * as picking from './pickRegistry.js';
import * as overlays from '../overlays/worldOverlay.js';
import { registerDynamicCredit, transitFeedCredit } from './dataCredits.js';
import {
GROUND_FLOOR_LIFT_M,
cachedGroundFloor,
coarseFloorCoord,
neighborFloorM,
warmGroundFloor,
} from './groundFloor.js';
import { sampleMeshFloorCells } from './meshFloorSampler.js';
const layer = createTransitLayer({
services: {
render,
sprites,
picking,
overlays,
credits: { registerDynamicCredit, transitFeedCredit },
ground: {
GROUND_FLOOR_LIFT_M,
cachedGroundFloor,
coarseFloorCoord,
neighborFloorM,
warmGroundFloor,
},
// The legacy sampler over the same legacy floor, so this standalone
// module warms its own mesh floors the way the application layer does.
mesh: { sampleMeshFloorCells },
},
});
export const _setTransitOverlayHostForTest =
layer._setTransitOverlayHostForTest;
export const _transitStateForTest = layer._transitStateForTest;
export {
TRANSIT_MODE_COLORS,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_ID,
TRANSIT_SELECTED_OVERLAY_SOURCE_OPTIONS,
aggregateTransitFeedHealth,
buildTransitSelectionCopy,
createTransitSelectedOverlayEntry,
interpolatedVehiclePosition,
isStaleVehicleFix,
transitDetectionClass,
transitDetectionId,
transitDetectionMetric,
transitVehicleKey,
vehicleFixAgeMs,
createTransitLayer,
} from '../layers/transit/index.js';
export default layer;
+225
View File
@@ -0,0 +1,225 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import transitLayer, {
TRANSIT_MODE_COLORS,
TRANSIT_POLL_MS,
TRANSIT_SELECTED_OVERLAY_SOURCE_OPTIONS,
buildTransitSelectionCopy,
createTransitSelectedOverlayEntry,
interpolatedVehiclePosition,
isStaleVehicleFix,
transitVehicleKey,
} from './transit.js';
import { TRANSIT_MODES, getTransitFeed } from './transitFeeds.js';
import { LAYER_STATE_REGISTRY } from './layerState.js';
import { SPRITE_LAYER_ORDER } from './spriteOrder.js';
test('layer module declares the manager contract', () => {
assert.equal(transitLayer.id, 'transit');
assert.equal(typeof transitLayer.name, 'string');
assert.equal(typeof transitLayer.icon, 'string');
assert.equal(transitLayer.updateInterval, TRANSIT_POLL_MS);
for (const method of [
'init',
'enable',
'disable',
'update',
'getStats',
'destroy',
]) {
assert.equal(
typeof transitLayer[method],
'function',
`${method} is implemented`,
);
}
});
test('the layer is registered for share links and sprite stacking', () => {
const entry = LAYER_STATE_REGISTRY.find((row) => row.id === 'transit');
assert.ok(entry, 'transit has a share-link token');
assert.equal(entry.disposition, 'enabled-only');
assert.equal(
LAYER_STATE_REGISTRY.filter((row) => row.token === entry.token).length,
1,
'token is unique',
);
const index = SPRITE_LAYER_ORDER.indexOf('transit');
assert.ok(
index > SPRITE_LAYER_ORDER.indexOf('bikeshare'),
'vehicles draw above bikeshare stations',
);
assert.ok(
index < SPRITE_LAYER_ORDER.indexOf('flights'),
'aircraft stay on top',
);
});
test('every transit mode has a colour and the selected card uses it as accent', () => {
for (const mode of TRANSIT_MODES) {
assert.match(
TRANSIT_MODE_COLORS[mode],
/^#[0-9a-f]{6}$/i,
`${mode} has a colour`,
);
}
const position = Cesium.Cartesian3.fromDegrees(-71.06, 42.36, 3);
const card = createTransitSelectedOverlayEntry(
'mbta:1',
position,
{ title: 'T', details: ['d'] },
'subway',
);
assert.equal(card.accent, TRANSIT_MODE_COLORS.subway);
assert.equal(card.selected, true);
assert.equal(card.protected, true);
assert.equal(card.position, position);
assert.equal(
createTransitSelectedOverlayEntry(
'',
position,
{ title: 'T', details: [] },
'bus',
),
null,
);
assert.equal(
createTransitSelectedOverlayEntry(
'k',
null,
{ title: 'T', details: [] },
'bus',
),
null,
);
assert.equal(
TRANSIT_SELECTED_OVERLAY_SOURCE_OPTIONS.moving,
true,
'the card follows a moving vehicle',
);
});
test('position queries read the published display sample', () => {
const entry = { track: {}, sample: { lat: 1, lon: 2, phase: 'playing' } };
assert.deepEqual(interpolatedVehiclePosition(entry), {
lat: 1,
lon: 2,
settled: false,
});
entry.sample.phase = 'held';
assert.equal(interpolatedVehiclePosition(entry).settled, true);
});
test('fixes older than ten minutes are stale; feeds without timestamps are trusted', () => {
const now = 1_700_000_000_000;
assert.equal(isStaleVehicleFix({ timestamp: now / 1000 - 30 }, now), false);
assert.equal(isStaleVehicleFix({ timestamp: now / 1000 - 601 }, now), true);
assert.equal(isStaleVehicleFix({ timestamp: null }, now), false);
assert.equal(isStaleVehicleFix({}, now), false);
});
test('selection copy reads like a transit card and never leaks nulls', () => {
const feed = getTransitFeed('metrotransit-msp');
const now = 1_788_936_960_000;
const full = buildTransitSelectionCopy(
feed,
{
id: '1557',
label: '1557',
routeId: '17',
lat: 44.9,
lon: -93.4,
bearing: 248,
speedMps: 11.2,
timestamp: 1_788_936_945,
stopId: '57458',
status: 'STOPPED_AT',
occupancy: 'FEW_SEATS_AVAILABLE',
timestampSource: 'vehicle',
},
'bus',
now,
);
assert.equal(full.title, '🚌 Route 17');
assert.deepEqual(full.details, [
// The mode is said in words: a glyph and a route number do not tell a
// reader whether the dot on the street is a bus or a subway train.
'Bus · Metro Transit · Minneapolis–St Paul, MN',
'Reported 15 s ago',
// The operator's speed is labelled as a report: it describes the newest
// fix, not the older segment the screen is drawing.
'reported 40 km/h · reported hdg 248°',
// The operator's claim is kept as a REPORT, not as the live state. It
// describes the moment of the report, which the display may not have
// reached yet — presenting it as "now" is what put STOPPED on a metro
// gliding across the owner's screen.
'Last report: stopped at stop 57458 · few seats available',
'Vehicle 1557',
]);
// A time the feed gave for the SNAPSHOT rather than for this vehicle is
// labelled, so the card never presents a borrowed time as the bus's own.
const borrowed = buildTransitSelectionCopy(
feed,
{
id: '9',
lat: 1,
lon: 1,
timestamp: 1_788_936_900,
timestampSource: 'header',
},
'bus',
now,
);
assert.equal(borrowed.details[1], 'Reported 60 s ago (feed time)');
// A subway says where it is drawn, because a train on a road is otherwise
// read as a bug rather than as a deliberate surface projection.
const underground = buildTransitSelectionCopy(
feed,
{
id: 'T1',
routeId: 'Blue',
lat: 44.9,
lon: -93.4,
timestamp: 1_788_936_945,
},
'subway',
now,
);
assert.deepEqual(underground.details, [
'Subway · Metro Transit · Minneapolis–St Paul, MN',
'Reported 15 s ago',
'Shown at street level · depth not in the feed',
'Vehicle T1',
]);
// No timestamp at all is aged from the fetch, never from "now".
const sparse = buildTransitSelectionCopy(
feed,
{ id: 'abc', lat: 1, lon: 1 },
'rail',
now,
now - 120_000,
);
assert.equal(sparse.title, '🚆 Vehicle abc');
assert.deepEqual(sparse.details, [
'Train · Metro Transit · Minneapolis–St Paul, MN',
'Reported 2 min ago (feed time)',
'Vehicle abc',
]);
for (const line of [...full.details, ...sparse.details])
assert.doesNotMatch(line, /null|undefined|NaN/);
assert.equal(transitVehicleKey('mbta', '17'), 'mbta:17');
});
test('the layer accepts a manager handle for out-of-tick panel repaints', () => {
assert.equal(typeof transitLayer.attachDataManager, 'function');
transitLayer.attachDataManager({ refreshLayerStats() {} });
transitLayer.attachDataManager(null);
});
test('stats before enable are an honest zero, not a fake feed state', () => {
const stats = transitLayer.getStats();
assert.equal(stats.count, 0);
assert.equal(stats.source, 'GTFS-RT');
assert.equal(stats.error, null);
});
+404
View File
@@ -0,0 +1,404 @@
/**
* @module transitFeeds
* @description Registry of keyless, openly licensed GTFS-Realtime
* VehiclePositions feeds the Transit layer can show.
*
* Every entry here is a URL the SERVER fetches — the browser only ever asks
* `/api/transit/vehicles/<id>` for a registered id (see SECURITY.md: proxies
* never fetch client-supplied URLs). Adding a feed means adding a row here,
* a DATA_SOURCES.md row with its license, and a credit in dataCredits.js.
*
* Admission rules for a feed:
* - No key, token, or registration required (identify-yourself headers are
* fine — Entur asks for `ET-Client-Name`, OVapi for a User-Agent).
* - An open license that permits display with attribution.
* - Real coordinates in VehiclePosition.position — NYCT subway, for example,
* publishes stop-relative positions only and is deliberately absent.
*
* `defaultEnabled` is separate from being registered. A feed ships switched ON
* only when its operator's own published terms were READ and plainly cover this
* use. A registered feed with `defaultEnabled: false` is never polled and never
* offered to the browser; it is here so the decision is visible and reversible
* in one line. `terms` records the passage that decision rests on, so the next
* reader does not have to take the licence string on faith.
*
* Pure data + pure helpers: imported by the browser layer, the Vite proxy, and
* node:test. No Cesium, no Node built-ins.
*/
/** Transit modes the layer colors. `routeMode` hints refine a feed's default. */
export const TRANSIT_MODES = Object.freeze([
'bus',
'tram',
'subway',
'rail',
'ferry',
'unknown',
]);
/** Per-mode icon used in labels and the selection card. */
export const TRANSIT_MODE_ICON = Object.freeze({
bus: '🚌',
tram: '🚊',
subway: '🚇',
rail: '🚆',
ferry: '⛴️',
unknown: '🚏',
});
/**
* MBTA route ids are human-readable and mode-typed: rapid-transit lines carry
* colour names, commuter rail is prefixed `CR-`, ferries `Boat-`, buses are
* numeric (or `SL`/`CT` express families).
* @param {string|null} routeId
* @returns {string}
*/
function mbtaRouteMode(routeId) {
if (!routeId) return 'unknown';
if (/^(Red|Orange|Blue)\b/.test(routeId)) return 'subway';
if (/^(Green|Mattapan)/.test(routeId)) return 'tram';
if (/^CR-/.test(routeId)) return 'rail';
if (/^Boat-/.test(routeId)) return 'ferry';
if (/^Shuttle/i.test(routeId)) return 'bus';
return 'bus';
}
/**
* Entur (Norway) route ids are `<codespace>:Line:<local-id>`; the codespace
* tells the operator, not the mode, but a few are single-mode operators.
* @param {string|null} routeId
* @returns {string}
*/
function enturRouteMode(routeId) {
if (!routeId) return 'unknown';
const codespace = routeId.split(':')[0];
if (
codespace === 'VYG' ||
codespace === 'GJB' ||
codespace === 'SJN' ||
codespace === 'FLT' ||
codespace === 'GOA' ||
codespace === 'NSB' ||
codespace === 'VYT'
)
return 'rail';
if (codespace === 'FLB') return 'rail';
return 'bus';
}
/**
* HSL route ids start with a four-digit code whose first digit is the mode
* family in HSL's numbering: 1xxx/2xxx… are trams (1001–1010) for 4-digit ids
* beginning with `10`, metro routes are `31M…`, ferries `1019`.
* @param {string|null} routeId
* @returns {string}
*/
function hslRouteMode(routeId) {
if (!routeId) return 'unknown';
if (/^31M/.test(routeId)) return 'subway';
if (/^10(0[1-9]|10|15)/.test(routeId)) return 'tram';
if (/^1019/.test(routeId)) return 'ferry';
if (/^300[0-9A-Z]/.test(routeId)) return 'rail';
return 'bus';
}
/**
* Metro Transit (Minneapolis–St Paul): light rail is the Blue/Green line
* (route ids 901/902), Northstar commuter rail is 888.
* @param {string|null} routeId
* @returns {string}
*/
function metroTransitRouteMode(routeId) {
if (!routeId) return 'unknown';
if (routeId === '901' || routeId === '902') return 'tram';
if (routeId === '888') return 'rail';
return 'bus';
}
/**
* Registry of feeds. Order is presentation order in the stats/credit text.
* `loadRadiusKm` is the distance from `center` inside which the feed is polled.
* @type {ReadonlyArray<Readonly<{
* id: string, name: string, operator: string, region: string,
* center: {lat: number, lon: number}, loadRadiusKm: number,
* url: string, headers?: Record<string, string>,
* license: string, licenseUrl: string, attribution: string,
* defaultMode: string, routeMode?: (routeId: string|null) => string,
* }>>}
*/
export const TRANSIT_FEED_REGISTRY = Object.freeze([
Object.freeze({
id: 'mbta',
historyRetention: true,
name: 'MBTA',
operator: 'Massachusetts Bay Transportation Authority',
region: 'Boston, MA',
center: Object.freeze({ lat: 42.3601, lon: -71.0589 }),
loadRadiusKm: 70,
url: 'https://cdn.mbta.com/realtime/VehiclePositions.pb',
license: 'MassDOT Developers License Agreement',
licenseUrl:
'https://cdn.mbta.com/sites/default/files/2023-08/mbta-massdot-develop-license-agreement.pdf',
attribution: 'MBTA / MassDOT',
defaultEnabled: true,
terms: Object.freeze({
quote:
'MassDOT ... hereby grants You (Licensee) non-exclusive, limited, and revocable rights to use, reproduce, and redistribute the Data. ... Clearly acknowledge MassDOT as the provider of the Data.',
note: 'Credit is text only: the agreement forbids using MBTA/MassDOT logos or trademarks with the data.',
}),
defaultMode: 'bus',
routeMode: mbtaRouteMode,
}),
Object.freeze({
id: 'capmetro-austin',
name: 'CapMetro',
operator: 'Capital Metropolitan Transportation Authority',
region: 'Austin, TX',
center: Object.freeze({ lat: 30.2672, lon: -97.7431 }),
loadRadiusKm: 60,
url: 'https://data.texas.gov/download/eiei-9rpf/application%2Foctet-stream',
license: 'CapMetro Developer Tools license',
licenseUrl: 'https://www.capmetro.org/developertools',
attribution:
'Capital Metropolitan Transportation Authority — data.texas.gov',
defaultEnabled: true,
terms: Object.freeze({
quote:
'Capital Metropolitan Transportation Authority (CMTA) hereby grants you (Licensee) non-exclusive, limited and revocable rights to use, reproduce, and redistribute CMTA Data.',
note: 'CMTA trademarks may not be used in association with the data, so the credit is the operator name as text.',
}),
defaultMode: 'bus',
}),
Object.freeze({
id: 'metrotransit-msp',
name: 'Metro Transit',
operator: 'Metro Transit (Metropolitan Council)',
region: 'Minneapolis–St Paul, MN',
center: Object.freeze({ lat: 44.9778, lon: -93.265 }),
loadRadiusKm: 70,
url: 'https://svc.metrotransit.org/mtgtfs/vehiclepositions.pb',
license: 'Public Metro Transit vehicle position data',
licenseUrl: 'https://svc.metrotransit.org/',
attribution: 'Metro Transit — Metropolitan Council',
defaultEnabled: true,
terms: Object.freeze({
quote:
"Metro Transit's GTFS-realtime feeds are refreshed every 5 seconds.",
note: 'The realtime feed is published from a developer page carrying operational guidance and no licence text of its own. The public-domain statement below belongs to the Metropolitan Council metadata for the COMPANION SCHEDULE dataset, not to this feed: "None. This dataset is public domain under the Minnesota Government Data Practices Act". Credited as a courtesy, the way the other public agency feeds are.',
}),
defaultMode: 'bus',
routeMode: metroTransitRouteMode,
}),
Object.freeze({
id: 'hsl-helsinki',
name: 'HSL',
operator: 'Helsinki Region Transport (HSL)',
region: 'Helsinki, Finland',
center: Object.freeze({ lat: 60.1699, lon: 24.9384 }),
loadRadiusKm: 70,
url: 'https://realtime.hsl.fi/realtime/vehicle-positions/v2/hsl',
license: 'CC BY 4.0',
licenseUrl: 'https://www.hsl.fi/en/hsl/open-data',
attribution: 'HSL (Helsinki Region Transport)',
defaultEnabled: true,
terms: Object.freeze({
quote: null,
note: 'The open-data page refuses automated readers (HTTP 403, bot protection), so this entry rests on the owner opening it and accepting it rather than on a passage quoted here. HSL publishes its open data under CC BY 4.0 and asks to be credited as the source; the feed needs no key.',
}),
defaultMode: 'bus',
routeMode: hslRouteMode,
}),
Object.freeze({
id: 'ovapi-nl',
name: 'OVapi',
operator: 'Stichting OpenGeo (NDOV data)',
region: 'Netherlands',
center: Object.freeze({ lat: 52.2, lon: 5.3 }),
loadRadiusKm: 220,
url: 'https://gtfs.ovapi.nl/nl/vehiclePositions.pb',
license: 'Free to use per the OVapi README (best effort, no SLA)',
licenseUrl: 'https://gtfs.ovapi.nl/README',
attribution:
'OVapi / Stichting OpenGeo — Dutch integrated real-time transit data',
defaultEnabled: true,
terms: Object.freeze({
quote:
'You are free to use this data, but there is no service level agreement (best-effort) nor are you allowed to say you represent or impersonate any of the transit agencies listed here.',
note: 'The README asks consumers to identify themselves in the User-Agent, to send If-Modified-Since / If-None-Match when polling faster than once a minute, and to accept gzip. The proxy does all three.',
}),
defaultMode: 'bus',
}),
Object.freeze({
id: 'entur-norway',
name: 'Entur',
operator: 'Entur AS (Norwegian national transit data)',
region: 'Norway',
// Circle chosen to hold Oslo, Bergen, Bodø and Tromsø while leaving
// Helsinki (≈820 km) out — a national feed must not poll from next door.
center: Object.freeze({ lat: 64.0, lon: 11.5 }),
loadRadiusKm: 720,
url: 'https://api.entur.io/realtime/v1/gtfs-rt/vehicle-positions',
headers: Object.freeze({ 'ET-Client-Name': 'gods-eye-view-transit' }),
license: 'Norwegian Licence for Open Government Data (NLOD)',
licenseUrl: 'https://developer.entur.org/pages-intro-authentication',
attribution: 'Entur — data under NLOD',
defaultEnabled: true,
terms: Object.freeze({
quote:
'This API is open under NLOD licence, however, it is required that all consumers identify themselves by using the header ET-Client-Name.',
note: 'The header is mandatory — unidentified consumers may be rate-limited or blocked — and the proxy sends it on every request.',
}),
defaultMode: 'bus',
routeMode: enturRouteMode,
}),
Object.freeze({
id: 'translink-seq',
name: 'TransLink',
operator: 'TransLink (Queensland Government)',
region: 'South East Queensland, Australia',
center: Object.freeze({ lat: -27.4698, lon: 153.0251 }),
loadRadiusKm: 150,
url: 'https://gtfsrt.api.translink.com.au/api/realtime/seq/VehiclePositions',
license: 'CC BY 4.0',
licenseUrl: 'https://translink.com.au/about-translink/open-data',
attribution: 'TransLink — Queensland Government (CC BY 4.0)',
defaultEnabled: true,
terms: Object.freeze({
quote:
'Our data is licensed under a Creative Commons Attribution 4.0 International License. ... You must not represent that the State in any way endorses your Application.',
note: 'No key, no stated rate limit, no caching rule. Logos and network imagery need separate approval, so the credit is text only.',
}),
defaultMode: 'bus',
}),
]);
/**
* The feeds this build actually polls. A registered feed that is not here is
* inert everywhere: it resolves to no route, is never offered to the browser,
* and never appears in a coverage check.
*/
export const TRANSIT_ENABLED_FEEDS = Object.freeze(
TRANSIT_FEED_REGISTRY.filter((feed) => feed.defaultEnabled === true),
);
const FEED_BY_ID = new Map(
TRANSIT_ENABLED_FEEDS.map((feed) => [feed.id, feed]),
);
const ANY_FEED_BY_ID = new Map(
TRANSIT_FEED_REGISTRY.map((feed) => [feed.id, feed]),
);
/** Feed ids are path segments: lowercase letters, digits, hyphens only. */
export const TRANSIT_FEED_ID_PATTERN = /^[a-z0-9][a-z0-9-]{1,63}$/;
/**
* Look up a POLLABLE feed by id. Unknown ids, malformed ids, and feeds that are
* registered but switched off all return null — this is the only door from a
* request path to an upstream URL, so a feed the owner has not cleared must not
* be reachable through it.
* @param {string} id
* @returns {object|null}
*/
export function getTransitFeed(id) {
if (typeof id !== 'string' || !TRANSIT_FEED_ID_PATTERN.test(id)) return null;
return FEED_BY_ID.get(id) || null;
}
/**
* Look up any registered feed, enabled or not. For credits and documentation
* only — never for resolving a request into an upstream fetch.
* @param {string} id
* @returns {object|null}
*/
export function getRegisteredTransitFeed(id) {
if (typeof id !== 'string' || !TRANSIT_FEED_ID_PATTERN.test(id)) return null;
return ANY_FEED_BY_ID.get(id) || null;
}
/**
* Great-circle distance in km.
* @param {number} aLat
* @param {number} aLon
* @param {number} bLat
* @param {number} bLon
* @returns {number}
*/
export function haversineKm(aLat, aLon, bLat, bLon) {
const toRad = (deg) => (deg * Math.PI) / 180;
const dLat = toRad(bLat - aLat);
const dLon = toRad(bLon - aLon);
const h =
Math.sin(dLat / 2) ** 2 +
Math.cos(toRad(aLat)) * Math.cos(toRad(bLat)) * Math.sin(dLon / 2) ** 2;
return 2 * 6371 * Math.asin(Math.min(1, Math.sqrt(h)));
}
/**
* Feeds whose coverage circle contains the point, nearest first.
* @param {number} lat
* @param {number} lon
* @param {number} [slackKm=0] Extra radius (hysteresis) so a feed at the edge
* of coverage does not flap on small camera moves.
* @returns {object[]}
*/
export function transitFeedsInRange(lat, lon, slackKm = 0) {
if (!Number.isFinite(lat) || !Number.isFinite(lon)) return [];
return TRANSIT_ENABLED_FEEDS.map((feed) => ({
feed,
km: haversineKm(lat, lon, feed.center.lat, feed.center.lon),
}))
.filter(({ feed, km }) => km <= feed.loadRadiusKm + Math.max(0, slackKm))
.sort((a, b) => a.km - b.km)
.map(({ feed }) => feed);
}
/**
* Mode for a vehicle: the feed's route hint when it has one, else its default.
* @param {object} feed Registry entry.
* @param {string|null} routeId GTFS route_id from the vehicle's trip.
* @returns {string} One of TRANSIT_MODES.
*/
export function transitModeFor(feed, routeId) {
const hinted =
typeof feed?.routeMode === 'function' ? feed.routeMode(routeId) : null;
const mode =
hinted && hinted !== 'unknown' ? hinted : feed?.defaultMode || 'unknown';
return TRANSIT_MODES.includes(mode) ? mode : 'unknown';
}
/**
* Whether the mode came from the route id rather than the feed's default. A
* default is a guess about a fleet — TransLink's is "bus" while it publishes
* rail in the same feed — so a consumer judging physical plausibility must
* not hold a defaulted vehicle to a bus's limits.
* @param {object} feed Registry entry.
* @param {string|null} routeId
* @returns {boolean}
*/
export function transitModeResolved(feed, routeId) {
const hinted =
typeof feed?.routeMode === 'function' ? feed.routeMode(routeId) : null;
return (
Boolean(hinted) && hinted !== 'unknown' && TRANSIT_MODES.includes(hinted)
);
}
/**
* Public catalog shape served by `/api/transit/feeds` — everything the browser
* needs to gate polling and credit the source, and nothing it could misuse.
* @returns {object[]}
*/
export function publicTransitCatalog() {
return TRANSIT_ENABLED_FEEDS.map((feed) => ({
id: feed.id,
name: feed.name,
operator: feed.operator,
region: feed.region,
center: { ...feed.center },
loadRadiusKm: feed.loadRadiusKm,
license: feed.license,
licenseUrl: feed.licenseUrl,
attribution: feed.attribution,
historyRetention: feed.historyRetention === true,
}));
}
+241
View File
@@ -0,0 +1,241 @@
import { readFileSync } from 'node:fs';
import test from 'node:test';
import assert from 'node:assert/strict';
import {
TRANSIT_ENABLED_FEEDS,
TRANSIT_FEED_REGISTRY,
TRANSIT_FEED_ID_PATTERN,
TRANSIT_MODES,
getRegisteredTransitFeed,
getTransitFeed,
haversineKm,
publicTransitCatalog,
transitFeedsInRange,
transitModeFor,
transitModeResolved,
} from './transitFeeds.js';
test('every registered feed is keyless, https, licensed, and uniquely identified', () => {
const ids = new Set();
for (const feed of TRANSIT_FEED_REGISTRY) {
assert.match(
feed.id,
TRANSIT_FEED_ID_PATTERN,
`${feed.id} is a valid path segment`,
);
assert.equal(ids.has(feed.id), false, `${feed.id} is unique`);
ids.add(feed.id);
const url = new URL(feed.url);
assert.equal(url.protocol, 'https:', `${feed.id} fetches over https`);
assert.equal(
url.search.includes('key='),
false,
`${feed.id} carries no key in its URL`,
);
assert.ok(
feed.license && feed.licenseUrl && feed.attribution,
`${feed.id} names its license`,
);
assert.ok(
feed.loadRadiusKm > 0 && feed.loadRadiusKm <= 1000,
`${feed.id} radius is sane`,
);
assert.ok(
Math.abs(feed.center.lat) <= 90 && Math.abs(feed.center.lon) <= 180,
);
assert.ok(
TRANSIT_MODES.includes(feed.defaultMode),
`${feed.id} default mode is known`,
);
assert.ok(Object.isFrozen(feed), `${feed.id} is immutable`);
}
});
test('getTransitFeed is the only door to an upstream URL and refuses anything unregistered', () => {
assert.equal(
getTransitFeed('mbta')?.url,
'https://cdn.mbta.com/realtime/VehiclePositions.pb',
);
assert.equal(getTransitFeed('MBTA'), null);
assert.equal(getTransitFeed('../etc/passwd'), null);
assert.equal(getTransitFeed('https://evil.example'), null);
assert.equal(getTransitFeed(''), null);
assert.equal(getTransitFeed(null), null);
assert.equal(getTransitFeed(42), null);
});
test('haversine matches known city distances', () => {
const bostonToNyc = haversineKm(42.3601, -71.0589, 40.7128, -74.006);
assert.ok(
Math.abs(bostonToNyc - 306) < 5,
`Boston–NYC ≈ 306 km, got ${bostonToNyc}`,
);
assert.equal(haversineKm(0, 0, 0, 0), 0);
});
test('feeds in range are nearest-first and honor slack as hysteresis', () => {
// Camera over Cambridge, MA → MBTA only.
const boston = transitFeedsInRange(42.37, -71.11);
assert.deepEqual(
boston.map((f) => f.id),
['mbta'],
);
// Mid-Atlantic: nothing.
assert.deepEqual(transitFeedsInRange(40, -40), []);
// Just outside MBTA's 70 km circle (≈ 80 km south) — out without slack, in with 20 km slack.
const farLat = 42.3601 - 80 / 111;
assert.deepEqual(transitFeedsInRange(farLat, -71.0589), []);
assert.deepEqual(
transitFeedsInRange(farLat, -71.0589, 20).map((f) => f.id),
['mbta'],
);
// Bad input never throws.
assert.deepEqual(transitFeedsInRange(NaN, 1), []);
// A national feed covers its own cities and not the neighbour's capital.
for (const [city, lat, lon] of [
['Oslo', 59.91, 10.75],
['Bergen', 60.39, 5.32],
['Tromsø', 69.65, 18.96],
]) {
assert.ok(
transitFeedsInRange(lat, lon).some((f) => f.id === 'entur-norway'),
`${city} is covered by Entur`,
);
}
assert.deepEqual(
transitFeedsInRange(60.17, 24.94).map((f) => f.id),
['hsl-helsinki'],
'Helsinki polls HSL only',
);
});
test('route hints refine a feed default and never escape the known modes', () => {
const mbta = getTransitFeed('mbta');
assert.equal(transitModeFor(mbta, 'Red'), 'subway');
assert.equal(transitModeFor(mbta, 'Green-B'), 'tram');
assert.equal(transitModeFor(mbta, 'CR-Fitchburg'), 'rail');
assert.equal(transitModeFor(mbta, 'Boat-F1'), 'ferry');
assert.equal(transitModeFor(mbta, '66'), 'bus');
assert.equal(transitModeFor(mbta, null), 'bus');
const hsl = getTransitFeed('hsl-helsinki');
assert.equal(transitModeFor(hsl, '31M1'), 'subway');
assert.equal(transitModeFor(hsl, '1006'), 'tram');
assert.equal(transitModeFor(hsl, '9982'), 'bus');
const msp = getTransitFeed('metrotransit-msp');
assert.equal(transitModeFor(msp, '901'), 'tram');
assert.equal(transitModeFor(msp, '17'), 'bus');
const entur = getTransitFeed('entur-norway');
assert.equal(transitModeFor(entur, 'VYG:Line:R10'), 'rail');
assert.equal(transitModeFor(entur, 'TRO:Line:1_310'), 'bus');
assert.equal(transitModeFor({ defaultMode: 'spaceship' }, 'x'), 'unknown');
assert.equal(transitModeFor(null, 'x'), 'unknown');
});
test('the public catalog exposes coverage and credit, never the upstream URL or headers', () => {
const catalog = publicTransitCatalog();
assert.equal(catalog.length, TRANSIT_ENABLED_FEEDS.length);
for (const entry of catalog) {
assert.equal('url' in entry, false);
assert.equal('headers' in entry, false);
assert.ok(entry.id && entry.name && entry.region && entry.attribution);
assert.ok(
Number.isFinite(entry.center.lat) && Number.isFinite(entry.loadRadiusKm),
);
}
});
test('the enabled set is a gate on the registry, not a copy of it', () => {
// Every registered feed is switched on today. The gate still has to be the
// thing that decides that, because the moment an operator's terms change the
// owner flips one flag and expects the feed to become unreachable — not to
// stay routable because the filter had quietly become a no-op.
assert.deepEqual(
TRANSIT_ENABLED_FEEDS.map((feed) => feed.id),
TRANSIT_FEED_REGISTRY.filter((feed) => feed.defaultEnabled === true).map(
(feed) => feed.id,
),
);
for (const feed of TRANSIT_FEED_REGISTRY) {
assert.equal(
typeof feed.defaultEnabled,
'boolean',
`${feed.id} states whether it ships on`,
);
assert.equal(
Boolean(getTransitFeed(feed.id)),
feed.defaultEnabled,
`${feed.id} is routable exactly when it is enabled`,
);
assert.ok(getRegisteredTransitFeed(feed.id), `${feed.id} stays documented`);
}
});
test('a mode the route id established is resolved; a feed default is only a guess', () => {
// TransLink publishes rail in a feed whose default is bus. A consumer that
// judges physical plausibility must know the difference, or a 140 km/h
// train is refused as an impossible bus.
const translink = getTransitFeed('translink-seq');
assert.equal(transitModeFor(translink, '600'), 'bus');
assert.equal(transitModeResolved(translink, '600'), false, 'defaulted');
const mbta = getTransitFeed('mbta');
assert.equal(transitModeResolved(mbta, 'Red'), true);
assert.equal(
transitModeResolved(mbta, '66'),
true,
'a numeric MBTA route is a bus by rule, not by default',
);
assert.equal(transitModeResolved(mbta, null), false);
assert.equal(transitModeResolved({ defaultMode: 'bus' }, 'x'), false);
assert.equal(
transitModeResolved({ routeMode: () => 'spaceship' }, 'x'),
false,
'an unknown hint resolves nothing',
);
});
test('only MBTA retains proxy history while every other registered feed stays live-enabled', () => {
assert.deepEqual(
publicTransitCatalog()
.filter((feed) => feed.historyRetention)
.map((feed) => feed.id),
['mbta'],
);
assert.equal(getTransitFeed('capmetro-austin').defaultEnabled, true);
assert.equal(getTransitFeed('mbta').attribution, 'MBTA / MassDOT');
});
test('published transit history scope agrees with the catalog capability', () => {
const retained = publicTransitCatalog().filter(
(feed) => feed.historyRetention,
);
assert.deepEqual(
retained.map((feed) => feed.id),
['mbta'],
);
const sources = readFileSync(
new URL('../../DATA_SOURCES.md', import.meta.url),
'utf8',
);
const row = sources
.split('\n')
.find((line) => line.startsWith('| **MBTA / MassDOT**'));
assert.match(
row,
/live vehicles and up to 15 minutes of recently observed positions/,
);
assert.match(row, /MBTA \/ MassDOT.*courtesy/);
assert.match(sources, /other feeds have no proxy retention/);
const state = readFileSync(
new URL('../../docs/CURRENT-STATE.md', import.meta.url),
'utf8',
);
const transit = state.slice(
state.indexOf('Transit is off by default'),
state.indexOf('`src/data/militaryAwareness.js` remains'),
);
assert.match(transit, /Restart clears it/);
assert.doesNotMatch(
transit,
/four fixes|0\.95x|guaranteed lower|one poll interval behind/,
);
});
+214
View File
@@ -0,0 +1,214 @@
import {
presetSpriteScale,
presetSpriteOutlinePx,
transitStyleProfile,
} from './transitPresetStyle.js';
// src/data/transitIcons.js
/**
* Front-up transit-vehicle silhouettes, one per mode, as SVG data URIs for
* Cesium billboards.
*
* Same house language as `aircraftIcons.js`: a 96-unit viewBox with the glyph
* centred at (48,48), drawn nose toward -Y so the screen-projected rotation in
* `iconOrientation.js` can spin the whole glyph, filled WHITE with a dark
* hairline edge so the tint pipeline (billboard.color = the mode colour, plus
* `.withAlpha` fades) keeps working. No glyph carries a colour of its own; a
* hardcoded fill would fight the tint that tells a person what they are looking
* at.
*
* These are plan views, the way a vehicle reads from a camera above a street —
* not side elevations. Each mode has a DISTINCT outline so it is recognisable
* at the ~18 px the fleet renders at, by shape and not only by colour: a bus is
* short and blunt, a tram is long and slender with articulation joints, a metro
* car is squared off, a mainline train has a tapered nose, and a ferry is a
* hull with a bow.
*
* Interior detail is drawn with the same dark hairline as the edge — windscreen
* lines, articulation joints, a deck line — because a solid dark panel would
* darken the tint and a white-on-white panel would vanish.
*/
const VIEW = 96;
const C = VIEW / 2; // 48 — glyph centre
/** Hairline dark edge, matching the aircraft glyph weight at this box size. */
const STROKE =
'stroke="rgba(0,0,0,0.34)" stroke-width="1.5" stroke-linejoin="round"';
/** Interior panel lines: the same ink, thinner, capped so joints read cleanly. */
const DETAIL =
'stroke="rgba(0,0,0,0.30)" stroke-width="1.5" stroke-linecap="round" fill="none"';
/**
* Each body is drawn in a centred frame (origin 0,0 = glyph centre), front
* toward -Y, in the 96-unit space (half-extent up to ~45).
*/
const BODIES = {
// ── Bus: short, blunt, square-shouldered. The shape everything else reads
// against, and the one most people will see most often.
bus: `
<path d="M-17,-28 C-17,-32 -14,-34 0,-34 C14,-34 17,-32 17,-28
L17,28 C17,32 14,34 0,34 C-14,34 -17,32 -17,28 Z"
fill="white" ${STROKE}/>
<path d="M-11,-24 L11,-24" ${DETAIL}/>
<path d="M-11,20 L11,20" ${DETAIL}/>`,
// ── Tram / light rail: longer and slimmer than a bus, with the two
// articulation joints that make a modern low-floor tram unmistakable.
tram: `
<path d="M-10,-38 C-10,-41 -8,-42.5 0,-42.5 C8,-42.5 10,-41 10,-38
L10,38 C10,41 8,42.5 0,42.5 C-8,42.5 -10,41 -10,38 Z"
fill="white" ${STROKE}/>
<path d="M-10,-13 L10,-13" ${DETAIL}/>
<path d="M-10,13 L10,13" ${DETAIL}/>
<path d="M-8,-34 L8,-34" ${DETAIL}/>`,
// ── Metro / subway: squared off at both ends, wider than a tram, a single
// cab line at the front. Reads as rolling stock, not a road vehicle.
subway: `
<path d="M-11.5,-40 L11.5,-40 L11.5,40 L-11.5,40 Z"
fill="white" ${STROKE}/>
<path d="M-11.5,-32 L11.5,-32" ${DETAIL}/>
<path d="M-11.5,0 L11.5,0" ${DETAIL}/>
<path d="M-11.5,32 L11.5,32" ${DETAIL}/>`,
// ── Mainline / commuter rail: the tapered nose of an intercity set, longer
// than anything else in the set.
rail: `
<path d="M0,-45 C5,-45 9.5,-41 10.5,-34 L10.5,40
C10.5,43 8.5,44.5 0,44.5 C-8.5,44.5 -10.5,43 -10.5,40
L-10.5,-34 C-9.5,-41 -5,-45 0,-45 Z"
fill="white" ${STROKE}/>
<path d="M-9,-30 L9,-30" ${DETAIL}/>
<path d="M-10.5,6 L10.5,6" ${DETAIL}/>`,
// ── Ferry: a hull. Pointed bow, square stern, superstructure amidships —
// the only glyph in the set that is not a box on rails or rubber.
ferry: `
<path d="M0,-44 C6,-38 12,-26 12.5,-14 L12.5,34
C12.5,37 11,38 0,38 C-11,38 -12.5,37 -12.5,34
L-12.5,-14 C-12,-26 -6,-38 0,-44 Z"
fill="white" ${STROKE}/>
<path d="M-7.5,-6 L7.5,-6 L7.5,20 L-7.5,20 Z" ${DETAIL}/>`,
// ── Unknown: a plain rounded marker. Deliberately featureless, so an
// unclassified vehicle never pretends to be a mode it is not.
unknown: `
<path d="M-10,-26 C-10,-30 -7,-32 0,-32 C7,-32 10,-30 10,-26
L10,26 C10,30 7,32 0,32 C-7,32 -10,30 -10,26 Z"
fill="white" ${STROKE}/>`,
};
/** The modes this module can draw. */
export const TRANSIT_ICON_KINDS = Object.freeze(Object.keys(BODIES));
const _iconCache = new Map();
const _b64 = (s) =>
typeof btoa === 'function'
? btoa(s)
: Buffer.from(s, 'utf8').toString('base64');
/**
* Fleet raster size. Same reasoning as the aircraft fleet glyphs: Cesium's
* billboard atlas has no mipmaps, so a texture far larger than its on-screen
* footprint is GPU-minified into mush. Transit billboards render around 14–20
* CSS px, so 48 px of source covers the band on a Retina display with very
* little minification.
*/
const FLEET_RASTER_PX = 48;
/** The selected vehicle draws bigger and deserves a crisper source. */
export const SELECTED_ICON_PX = 96;
/**
* On-screen size the fleet glyph is authored for. A halo width asked for in
* screen pixels is converted to viewBox units against this, so "two pixels of
* ring" means two pixels on an eighteen-pixel billboard.
*/
export const FLEET_SCREEN_PX = 20;
/**
* How a halo changes the glyph's frame. A thick outer stroke would clip at
* the 96-unit box (the tram already reaches 42.5 of 48), so the viewBox is
* padded by the stroke and the billboard has to grow by the same ratio to
* keep the body its shipped size on screen.
*
* @param {number} haloScreenPx Ring width in final screen pixels (0 = none).
* @param {number} [screenPx] Billboard size the ring is specified against.
* @returns {{units: number, pad: number, ratio: number}} Stroke width in
* viewBox units (the visible ring is half of it, outside the body), the
* padding added on every side, and the frame growth factor to apply to the
* billboard's width and height.
*/
export function haloFrame(haloScreenPx, screenPx = FLEET_SCREEN_PX) {
const ring = Number.isFinite(haloScreenPx) ? Math.max(0, haloScreenPx) : 0;
if (ring === 0) return { units: 0, pad: 0, ratio: 1 };
// Half the stroke lies outside the body, so a ring of R px needs 2R of
// stroke. One screen pixel is VIEW/screenPx units.
const units = (2 * ring * VIEW) / Math.max(1, screenPx);
const pad = Math.ceil(units / 2) + 1;
return { units, pad, ratio: (VIEW + 2 * pad) / VIEW };
}
/** Number of raster variants ever built — a bound a test can hold the cache to. */
export function transitIconCacheSize() {
return _iconCache.size;
}
/**
* Data URI for one mode's silhouette, lazily built and cached per kind, size
* and halo.
*
* With a halo, the body is drawn twice: first as a wide dark stroke, then as
* the shipped white fill with its hairline edge on top, so the ring sits
* OUTSIDE the silhouette and the interior detail is untouched. The dark ring
* is what survives NVG's auto-gain and FLIR's luma mapping when the bright
* core alone would merge with a bright road.
*
* @param {string} kind One of TRANSIT_ICON_KINDS; anything else draws `unknown`.
* @param {number} [px] Raster size.
* @param {{haloScreenPx?: number, screenPx?: number}} [options]
* @returns {string} `data:image/svg+xml;base64,...`
*/
export function transitIcon(kind, px = FLEET_RASTER_PX, options = {}) {
const k = BODIES[kind] ? kind : 'unknown';
const selected = px > FLEET_RASTER_PX;
px = selected ? SELECTED_ICON_PX : FLEET_RASTER_PX;
const profile = transitStyleProfile(
options.style ||
(options.haloScreenPx >= 2
? 'thermal'
: options.haloScreenPx === 1.25
? 'retro'
: 'normal'),
);
const style =
profile === 'mono' ? 'thermal' : profile === 'crt' ? 'retro' : 'normal';
const displayPx = (selected ? 30 : 20) * presetSpriteScale(style, selected);
const frame = haloFrame(presetSpriteOutlinePx(style, selected), displayPx);
const key = `${k}:${selected ? 1 : 0}:${profile}`;
let uri = _iconCache.get(key);
if (!uri) {
const size = VIEW + 2 * frame.pad;
// Sensor signatures use a broad rounded envelope, without dark interior
// joints or a second outline eating into the hot core at display resolution.
const halfW = k === 'bus' || k === 'ferry' || k === 'unknown' ? 48 : 47;
const halfH = 48;
const radius = k === 'subway' ? 8 : k === 'rail' ? 12 : 14;
const capsule = `<path d="M${-halfW + radius},${-halfH} H${halfW - radius} Q${halfW},${-halfH} ${halfW},${-halfH + radius} V${halfH - radius} Q${halfW},${halfH} ${halfW - radius},${halfH} H${-halfW + radius} Q${-halfW},${halfH} ${-halfW},${halfH - radius} V${-halfH + radius} Q${-halfW},${-halfH} ${-halfW + radius},${-halfH} Z" fill="white" />`;
const body = profile === 'mono' ? capsule : BODIES[k];
const halo =
frame.units > 0
? body.replace(
/<path d="([^"]+)"\s+fill="white" [^/]*\/>/,
(_m, d) =>
`<path d="${d}" fill="none" stroke="${profile === 'mono' ? '#000000' : '#05080C'}" stroke-opacity="${profile === 'mono' ? 1 : 0.95}" stroke-width="${frame.units.toFixed(2)}" stroke-linejoin="round"/>`,
)
: '';
const svg =
`<svg xmlns="http://www.w3.org/2000/svg" width="${Math.round(px * frame.ratio)}" height="${Math.round(px * frame.ratio)}" viewBox="${-frame.pad} ${-frame.pad} ${size} ${size}">` +
`<g transform="translate(${C},${C})">${halo}${body}</g></svg>`;
uri = 'data:image/svg+xml;base64,' + _b64(svg);
_iconCache.set(key, uri);
}
return uri;
}
+136
View File
@@ -0,0 +1,136 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
FLEET_SCREEN_PX,
TRANSIT_ICON_KINDS,
haloFrame,
transitIcon,
transitIconCacheSize,
} from './transitIcons.js';
const decode = (uri) =>
Buffer.from(uri.replace('data:image/svg+xml;base64,', ''), 'base64').toString(
'utf8',
);
test('a halo is sized in screen pixels and pads the frame so it cannot clip', () => {
const none = haloFrame(0);
assert.deepEqual(none, { units: 0, pad: 0, ratio: 1 });
const two = haloFrame(2, FLEET_SCREEN_PX);
// Two pixels of ring on an eighteen-pixel glyph is a 4-px stroke: 21.3 of 96 units.
assert.ok(Math.abs(two.units - (4 * 96) / 20) < 1e-9);
assert.ok(
two.pad >= two.units / 2,
'padding covers the half-stroke outside the body',
);
assert.ok(two.ratio > 1, 'and the billboard grows by the same ratio');
});
test('a haloed glyph draws the dark ring under the shipped white body', () => {
const plain = decode(transitIcon('bus'));
const haloed = decode(transitIcon('bus', 48, { haloScreenPx: 2 }));
assert.notEqual(plain, haloed);
assert.match(
haloed,
/stroke="#000000" stroke-opacity="1" stroke-width="19\.20"/,
);
assert.ok(
haloed.indexOf('#000000') < haloed.indexOf('fill="white"'),
'ring first, body on top',
);
assert.match(haloed, /viewBox="-\d+ -\d+ \d+ \d+"/, 'padded frame');
assert.match(plain, /stroke-width="9\.60"/, 'normal has a one-pixel halo');
});
test('the raster cache is bounded by kind, size and halo — never by call count', () => {
const before = transitIconCacheSize();
for (let i = 0; i < 50; i += 1) {
transitIcon('tram', 48, { haloScreenPx: 2 });
transitIcon('tram', 48);
transitIcon('tram', 128, { haloScreenPx: 1.25 });
}
assert.ok(
transitIconCacheSize() - before <= 3,
`three variants, not ${transitIconCacheSize() - before}`,
);
assert.equal(
transitIcon('tram', 48, { haloScreenPx: 2 }),
transitIcon('tram', 48, { haloScreenPx: 2 }),
);
for (const kind of TRANSIT_ICON_KINDS)
transitIcon(kind, 48, { haloScreenPx: 2 });
assert.ok(transitIconCacheSize() <= before + 3 + TRANSIT_ICON_KINDS.length);
});
test('all 36 variants retain the specified final halo at both display sizes', async () => {
const { presetSpriteScale, presetSpriteOutlinePx } =
await import('./transitPresetStyle.js');
for (const kind of TRANSIT_ICON_KINDS) {
for (const selected of [false, true]) {
for (const style of ['normal', 'thermal', 'retro']) {
const display =
(selected ? 30 : 20) * presetSpriteScale(style, selected);
const svg = decode(transitIcon(kind, selected ? 96 : 48, { style }));
const units = Number(
svg.match(/stroke-opacity="(?:0.95|1)" stroke-width="([\d.]+)"/)[1],
);
assert.ok(
Math.abs(
(units * display) / 192 - presetSpriteOutlinePx(style, selected),
) < 0.001,
);
const frame = haloFrame(
presetSpriteOutlinePx(style, selected),
display,
);
assert.match(
svg,
new RegExp(
`width="${Math.round((selected ? 96 : 48) * frame.ratio)}"`,
),
);
}
}
}
for (let i = 0; i < 100; i++)
transitIcon('invalid', i, { haloScreenPx: i, screenPx: i });
assert.equal(transitIconCacheSize(), 36);
});
test('sensor bodies cover sixty percent of the padded display with opaque white', async () => {
const sharp = (await import('sharp')).default;
const { presetSpriteScale, presetSpriteOutlinePx } =
await import('./transitPresetStyle.js');
for (const selected of [false, true])
for (const kind of TRANSIT_ICON_KINDS) {
const display =
(selected ? 30 : 20) * presetSpriteScale('thermal', selected);
assert.equal(display, selected ? 36 : 30);
assert.equal(presetSpriteOutlinePx('thermal', selected), 3);
const svg = decode(
transitIcon(kind, selected ? 96 : 48, { style: 'thermal' }),
);
const frame = haloFrame(3, display);
const width = Math.round(display * frame.ratio);
const { data, info } = await sharp(Buffer.from(svg))
.resize(width, width)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
let white = 0;
for (let i = 0; i < data.length; i += 4)
if (
data[i] >= 240 &&
data[i + 1] >= 240 &&
data[i + 2] >= 240 &&
data[i + 3] >= 240
)
white++;
assert.ok(
white / (info.width * info.height) >= 0.6,
`${kind}/${display}: white ${white / (info.width * info.height)}`,
);
const c = (Math.floor(width / 2) * width + Math.floor(width / 2)) * 4;
assert.deepEqual([...data.subarray(c, c + 4)], [255, 255, 255, 255]);
}
});
+147
View File
@@ -0,0 +1,147 @@
/**
* @file Preset-aware transit sprite styling — pure lookup tables mapping the
* active post-FX style to a sprite treatment the shaders cannot destroy, and
* the detection tier that carries each mode's colour above them.
*
* Why: transit sprites are in-scene billboards, so they pass THROUGH the
* post-FX chain. NVG and FLIR reduce the scene to luminance, and the mode
* palette's luma is middling — a green bus, a red metro and an amber tram all
* collapse to the same dim grey, on a road NVG's auto-gain has pushed to
* white. The owner's Boston test: "you can barely see these guys".
*
* Encoding per profile, the traffic-dot precedent applied to a glyph:
* - `mono` (surveillance/NVG, thermal/FLIR, noir, cockpit nvg/thermal): the
* sprite is WHITE — the hottest end of grayscale FLIR and of the Ironbow
* ramp, and the brightest phosphor under NVG — drawn larger, with a dark
* halo sized in SCREEN pixels so it keeps local contrast on a bright road
* through any luma mapping. Black-hot FLIR inverts it, deliberately: a
* black sprite with a light ring is what a hot object looks like there.
* - `crt` (retro): saturated per-mode colours that survive posterisation,
* a size boost to out-shout the pixel grid, and a thinner halo.
* - `normal` (normal/anime/snow/unknown): every lookup returns the shipped
* value — mode colour, shipped size, hairline edge only.
*
* Brackets are a different matter. The detection canvas composites ABOVE the
* post-FX chain, so a tier colour is literal screen RGB in every preset: the
* brackets carry the mode colour the sprites can no longer encode, the way
* traffic's brackets carry congestion. Tier colours per theme live in
* `src/overlays/worldOverlayTokens.js`.
*
* Cesium-free so the tables are unit-testable; the layer maps them to Cesium
* colours and billboard sizes at spawn and restyle time.
*
* @module data/transitPresetStyle
*/
/** @const {Object<string,'mono'|'crt'>} Style name → non-normal profile. */
const PROFILE_BY_STYLE = Object.freeze({
surveillance: 'mono', // NVG — P43 phosphor × luma
thermal: 'mono', // FLIR — grayscale/Ironbow × luma
noir: 'mono', // full desaturation
nvg: 'mono', // cockpit vision names its modes directly
retro: 'crt', // CRT — hue survives, small glyphs don't
});
/**
* Per-profile sprite treatment. `rgba` is [r,g,b] 0–255 + alpha 0–1;
* `scale` multiplies the shipped billboard size; `outlinePx` is the dark
* halo's width in FINAL SCREEN PIXELS, which is the only unit that means
* anything for a glyph rendered at eighteen pixels — the shipped 1.5-unit
* hairline in a 96-unit box is 0.28 px on screen, and vanishes.
*/
const SPRITE_STYLE = Object.freeze({
mono: Object.freeze({
rgba: Object.freeze([255, 255, 255, 1]),
scale: 1.5,
outlinePx: 3,
}),
crt: Object.freeze({
scale: 1.3,
outlinePx: 1.25,
rgbaByMode: Object.freeze({
bus: Object.freeze([0, 255, 102, 1]),
tram: Object.freeze([255, 179, 0, 1]),
subway: Object.freeze([255, 59, 48, 1]),
rail: Object.freeze([215, 139, 255, 1]),
ferry: Object.freeze([58, 208, 255, 1]),
unknown: Object.freeze([255, 255, 255, 1]),
}),
}),
});
/** Modes with a bracket tier of their own. */
const TIER_MODES = Object.freeze([
'bus',
'tram',
'subway',
'rail',
'ferry',
'unknown',
]);
/**
* Classify a style name into a transit styling profile.
* @param {string|null|undefined} styleName - Active style (e.g. 'thermal').
* @returns {'normal'|'mono'|'crt'} Styling profile; unknown → 'normal'.
*/
export function transitStyleProfile(styleName) {
return PROFILE_BY_STYLE[styleName] || 'normal';
}
/**
* Preset sprite colour, or null to keep the shipped mode colour.
* @param {string|null|undefined} styleName
* @param {string} mode Transit mode.
* @returns {number[]|null} [r,g,b,a] with rgb 0–255, alpha 0–1, or null.
*/
export function presetSpriteRgba(styleName, mode) {
const profile = transitStyleProfile(styleName);
if (profile === 'mono') return SPRITE_STYLE.mono.rgba;
if (profile === 'crt') {
return (
SPRITE_STYLE.crt.rgbaByMode[mode] || SPRITE_STYLE.crt.rgbaByMode.unknown
);
}
return null;
}
/**
* Multiplier a preset applies to the shipped billboard size.
* @param {string|null|undefined} styleName
* @returns {number} 1 under the normal profile.
*/
export function presetSpriteScale(styleName, selected = false) {
if (transitStyleProfile(styleName) === 'mono')
return selected ? 36 / 30 : 30 / 20;
return SPRITE_STYLE[transitStyleProfile(styleName)]?.scale ?? 1;
}
/**
* Dark-halo width in final screen pixels, or 0 for the shipped hairline only.
* @param {string|null|undefined} styleName
* @returns {number}
*/
export function presetSpriteOutlinePx(styleName, selected = false) {
return (
SPRITE_STYLE[transitStyleProfile(styleName)]?.outlinePx ??
(selected ? 1.5 : 1)
);
}
/**
* Detection-overlay tier key for a transit mode. Every theme's `tiers`
* table carries these six, so the bracket colour is per mode in every
* preset. Unlike traffic, transit sets its tier keyless as well: the feeds
* are keyless, and there is no separate keyless experience to keep
* byte-identical.
* @param {string} mode
* @returns {string}
*/
export function transitModeTier(mode) {
return `transit_${TIER_MODES.includes(mode) ? mode : 'unknown'}`;
}
/** The tier keys this module can produce, for the tables that must carry them. */
export const TRANSIT_TIER_KEYS = Object.freeze(
TIER_MODES.map((mode) => `transit_${mode}`),
);
+96
View File
@@ -0,0 +1,96 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
TRANSIT_TIER_KEYS,
presetSpriteOutlinePx,
presetSpriteRgba,
presetSpriteScale,
transitModeTier,
transitStyleProfile,
} from './transitPresetStyle.js';
import { TRANSIT_MODES } from './transitFeeds.js';
test('profile mapping: NVG/FLIR/noir and cockpit nvg are mono, retro is crt, everything else normal', () => {
for (const mono of ['surveillance', 'thermal', 'noir', 'nvg'])
assert.equal(transitStyleProfile(mono), 'mono', mono);
assert.equal(transitStyleProfile('retro'), 'crt');
for (const plain of [
'normal',
'anime',
'snow',
'minecraft',
'',
null,
undefined,
'optical',
])
assert.equal(transitStyleProfile(plain), 'normal', String(plain));
});
test('normal uses mode colour, unit scale and a one-pixel halo', () => {
for (const mode of TRANSIT_MODES) {
assert.equal(presetSpriteRgba('normal', mode), null);
assert.equal(presetSpriteRgba(undefined, mode), null);
}
assert.equal(presetSpriteScale('normal'), 1);
assert.equal(presetSpriteOutlinePx('normal'), 1);
});
test('mono: every mode is a white core, larger, with a dark halo in screen pixels', () => {
for (const style of ['surveillance', 'thermal', 'noir', 'nvg']) {
for (const mode of TRANSIT_MODES) {
assert.deepEqual(
presetSpriteRgba(style, mode),
[255, 255, 255, 1],
`${style} ${mode}`,
);
}
assert.ok(presetSpriteScale(style) === 1.5, `${style} is drawn larger`);
// At least a whole screen pixel and a half of ring around a five-pixel
// body: thinner than that vanishes through blur and pixelation.
assert.ok(
presetSpriteOutlinePx(style) >= 1.5,
`${style} halo is ${presetSpriteOutlinePx(style)} px`,
);
}
});
test('crt: saturated per-mode colours, distinct, upsized, thinner halo', () => {
const seen = new Set();
for (const mode of TRANSIT_MODES) {
const rgba = presetSpriteRgba('retro', mode);
assert.ok(Array.isArray(rgba) && rgba.length === 4, mode);
seen.add(rgba.slice(0, 3).join(','));
const [r, g, b] = rgba;
assert.ok(
Math.max(r, g, b) === 255,
`${mode} is fully saturated on one channel`,
);
}
assert.equal(seen.size, TRANSIT_MODES.length, 'no two modes share a colour');
assert.ok(presetSpriteScale('retro') > 1.2);
assert.ok(
presetSpriteOutlinePx('retro') > 0 &&
presetSpriteOutlinePx('retro') < presetSpriteOutlinePx('thermal'),
);
});
test('every mode has its own bracket tier, unknown modes fall to transit_unknown', () => {
const tiers = new Set();
for (const mode of TRANSIT_MODES) tiers.add(transitModeTier(mode));
assert.equal(tiers.size, TRANSIT_MODES.length);
assert.equal(transitModeTier('spaceship'), 'transit_unknown');
assert.equal(transitModeTier(undefined), 'transit_unknown');
assert.deepEqual([...tiers].sort(), [...TRANSIT_TIER_KEYS].sort());
});
test('all styled tuples are valid rgba: channels 0–255 ints, alpha in (0, 1]', () => {
for (const style of ['thermal', 'retro']) {
for (const mode of TRANSIT_MODES) {
const [r, g, b, a] = presetSpriteRgba(style, mode);
for (const c of [r, g, b])
assert.ok(Number.isInteger(c) && c >= 0 && c <= 255);
assert.ok(a > 0 && a <= 1);
}
}
});
+310
View File
@@ -0,0 +1,310 @@
import { validTransitIdentifier } from '../sources/transitHistory.js';
export {
validTransitIdentifier,
fetchTransitHistory,
} from '../sources/transitHistory.js';
/**
* @module transitProxy
* @description Pure server-side mechanics for the `/api/transit` proxy.
*
* Kept free of Vite/Node middleware state (the terrainHeightsProxy pattern)
* so path resolution, snapshot shaping, and the cache/stale policy can be
* exercised by the offline node:test suite. The middleware in vite.config.js
* only does I/O: fetch the registered upstream, hand the bytes here, send.
*/
import {
GTFS_INCREMENTALITY_FULL_DATASET,
decodeVehiclePositions,
} from './gtfsRealtime.js';
import { getTransitFeed } from './transitFeeds.js';
/** Fresh window: a snapshot younger than this is served without refetching. */
export const TRANSIT_PROXY_TTL_MS = 15_000;
/** Serve-stale window: after an upstream failure, a snapshot this old still ships (marked stale). */
export const TRANSIT_PROXY_STALE_MAX_MS = 10 * 60_000;
/** Upstream fetch timeout. National feeds (Entur ≈ 1.4 MB) need headroom. */
export const TRANSIT_PROXY_TIMEOUT_MS = 15_000;
/** Hard cap on upstream bytes: the largest registered feed is well under 1 MB. */
export const TRANSIT_PROXY_MAX_BODY_BYTES = 8 * 1024 * 1024;
/** Redirect hops followed before a feed is declared unreachable. */
export const TRANSIT_MAX_REDIRECTS = 3;
/**
* The 3xx codes that actually mean "go somewhere else". 304 is NOT one of them:
* it is the successful answer to a conditional request and carries no Location,
* so treating the whole 3xx range as a redirect turns every healthy unchanged
* feed into a failure and walks it up the backoff ladder.
*/
export const TRANSIT_REDIRECT_STATUSES = Object.freeze([
301, 302, 303, 307, 308,
]);
/**
* Whether an upstream status is a redirect this proxy should follow.
* @param {number} status
* @returns {boolean}
*/
export function isTransitRedirectStatus(status) {
return TRANSIT_REDIRECT_STATUSES.includes(Number(status));
}
/**
* Admission window for upstream requests. One browser polls a feed every 15 s
* (4/min); the allowance leaves room for a second tab and a manual reload, and
* the global figure bounds what this process can ask of ALL operators at once.
*/
export const TRANSIT_ADMISSION_WINDOW_MS = 60_000;
export const TRANSIT_ADMISSION_MAX_PER_FEED = 8;
export const TRANSIT_ADMISSION_MAX_GLOBAL = 40;
/**
* Cooldown ladder after consecutive upstream failures, in ms. A cold feed that
* is simply down must not be re-asked once per poll for the whole session: the
* first retry is quick, the last rung is five minutes, and the ladder resets on
* the first success.
*/
export const TRANSIT_BACKOFF_LADDER_MS = Object.freeze([
5_000, 15_000, 60_000, 300_000,
]);
/**
* Resolve `/vehicles/<feedId>` (the path after the `/api/transit` mount) to a
* registered feed. Anything else — a different route, an unknown id, path
* tricks, a query string — resolves to null and the caller 404s.
* @param {string} url Request URL relative to the mount point.
* @returns {{ route: 'feeds' } | { route: 'vehicles', feed: object } | null}
*/
export function resolveTransitRoute(url) {
const pathname = String(url || '').split('?')[0];
if (pathname === '/feeds' || pathname === '/feeds/')
return { route: 'feeds' };
const match = /^\/(vehicles|trail)\/([^/]+)(?:\/([^/]+))?\/?$/.exec(pathname);
if (!match) return null;
let id, vehicleId;
try {
id = decodeURIComponent(match[2]);
vehicleId = match[3] === undefined ? null : decodeURIComponent(match[3]);
} catch {
return null;
}
const feed = getTransitFeed(id);
if (!feed) return null;
if (match[1] === 'vehicles')
return vehicleId === null ? { route: 'vehicles', feed } : null;
return feed.historyRetention === true && validTransitIdentifier(vehicleId)
? { route: 'trail', feed, vehicleId }
: null;
}
/**
* Request headers for one upstream fetch.
*
* Three of these are obligations, not politeness. Feeds that ask consumers to
* identify themselves get their header from the registry (Entur requires
* `ET-Client-Name`; OVapi asks that the User-Agent say who you are). OVapi also
* asks anyone polling faster than once a minute to send conditional-request
* validators and to accept gzip, so both are sent to every feed: harmless
* where it is not asked for, and it spares each operator a full body whenever
* nothing has changed.
*
* @param {object} feed Registry entry.
* @param {{etag?: string|null, lastModified?: string|null}} [validators] From the cached snapshot.
* @returns {Record<string, string>}
*/
export function transitUpstreamHeaders(feed, validators = null) {
return {
'User-Agent':
'gods-eye-view-transit-proxy/1.0 (+https://github.com/bilawalsidhu/gods-eye-view)',
Accept: 'application/x-protobuf, application/octet-stream;q=0.9, */*;q=0.1',
'Accept-Encoding': 'gzip',
...(validators?.etag ? { 'If-None-Match': validators.etag } : {}),
...(validators?.lastModified
? { 'If-Modified-Since': validators.lastModified }
: {}),
...(feed?.headers || {}),
};
}
/**
* Only https upstreams are fetched.
* @param {string} url Request or response URL.
* @returns {boolean}
*/
export function isAcceptableTransitUpstreamUrl(url) {
try {
return new URL(url).protocol === 'https:';
} catch {
return false;
}
}
/**
* Decide whether one redirect hop may be followed, BEFORE it is requested.
*
* Checking the FINAL url after `redirect: 'follow'` is too late: by then the
* disallowed host has already been contacted, has already seen this server's
* request, and has already answered. So every hop is resolved here first and a
* hop that leaves the feed's own origin, or drops to plain http, is refused —
* the same rule the CCTV frame proxy applies to camera images.
*
* @param {string} originUrl The registered feed URL (defines the allowed origin).
* @param {string} currentUrl The URL that produced this redirect (for relative Location).
* @param {string|null} location Raw `Location` header value.
* @returns {{ ok: true, url: string } | { ok: false, reason: string }}
*/
export function transitRedirectDecision(originUrl, currentUrl, location) {
if (!location)
return { ok: false, reason: 'redirect without a Location header' };
let origin;
let next;
try {
origin = new URL(originUrl).origin;
next = new URL(location, currentUrl);
} catch {
return { ok: false, reason: 'redirect target is not a valid URL' };
}
if (next.protocol !== 'https:')
return { ok: false, reason: 'redirect left https' };
if (next.origin !== origin)
return { ok: false, reason: `redirect left ${origin}` };
return { ok: true, url: next.toString() };
}
/**
* Cooldown before the next upstream attempt after `failures` consecutive
* failures. Zero while the feed is healthy.
* @param {number} failures Consecutive failures (0 = none).
* @returns {number} ms to wait before the next upstream attempt.
*/
export function nextTransitBackoffMs(failures) {
const count = Number.isFinite(failures) ? Math.floor(failures) : 0;
if (count <= 0) return 0;
const index = Math.min(count, TRANSIT_BACKOFF_LADDER_MS.length) - 1;
return TRANSIT_BACKOFF_LADDER_MS[index];
}
/**
* Error thrown when a feed's shape is unusable rather than merely unavailable.
* Carries `transitReason` so the middleware can answer honestly.
*/
export class TransitFeedShapeError extends Error {
constructor(message, reason) {
super(message);
this.name = 'TransitFeedShapeError';
this.transitReason = reason;
}
}
/**
* Give every vehicle a best-available report time, and say WHERE it came from.
*
* A feed that omits `VehiclePosition.timestamp` is not reporting "now" — it is
* reporting nothing, and treating the moment WE fetched as the moment the bus
* was there is how a five-minute-old fix gets drawn as live. The ladder is
* explicit instead: the vehicle's own timestamp, else the feed header's
* timestamp (the operator's own statement about the snapshot), else fetch time,
* which is labelled as a guess so the layer can age it conservatively.
*
* @param {object[]} vehicles Normalized vehicle records.
* @param {number|null} headerTimestamp Feed header timestamp (epoch seconds).
* @param {number} fetchedAtS Fetch time (epoch seconds).
* @returns {object[]} Records with `timestamp` and `timestampSource` set.
*/
export function repairVehicleTimestamps(vehicles, headerTimestamp, fetchedAtS) {
const header =
Number.isFinite(headerTimestamp) && headerTimestamp > 0
? headerTimestamp
: null;
return (vehicles || []).map((vehicle) => {
if (Number.isFinite(vehicle.timestamp) && vehicle.timestamp > 0) {
return { ...vehicle, timestampSource: 'vehicle' };
}
if (header !== null)
return { ...vehicle, timestamp: header, timestampSource: 'header' };
return { ...vehicle, timestamp: fetchedAtS, timestampSource: 'fetch' };
});
}
/**
* Decode upstream bytes into the JSON snapshot the browser consumes.
*
* A DIFFERENTIAL feed is refused outright. Differential GTFS-Realtime carries
* only what changed, so reading one as if it were a full snapshot would make
* every unmentioned vehicle look like it had vanished. Deletion semantics are
* not implemented, so the honest answer is to decline the feed, not to render
* a wrong one.
*
* @param {object} feed Registry entry.
* @param {Uint8Array|ArrayBuffer} bytes Raw GTFS-RT FeedMessage.
* @param {number} [now=Date.now()] Fetch time (ms epoch).
* @returns {{ feedId: string, name: string, fetchedAt: number, feedTimestamp: number|null,
* version: string|null, entityCount: number, truncated: boolean, count: number, vehicles: object[] }}
*/
export function buildTransitSnapshot(feed, bytes, now = Date.now()) {
const decoded = decodeVehiclePositions(bytes);
if (decoded.incrementality !== GTFS_INCREMENTALITY_FULL_DATASET) {
throw new TransitFeedShapeError(
`feed is differential (incrementality ${decoded.incrementality})`,
'differential',
);
}
return {
feedId: feed.id,
name: feed.name,
fetchedAt: now,
feedTimestamp: decoded.timestamp,
version: decoded.version,
entityCount: decoded.entityCount,
truncated: decoded.truncated,
count: decoded.vehicles.length,
vehicles: repairVehicleTimestamps(
decoded.vehicles,
decoded.timestamp,
Math.floor(now / 1000),
),
};
}
/**
* Classify a cache entry for the request policy.
* @param {{ at: number }|null|undefined} entry Cached snapshot (`at` = fetch ms).
* @param {number} now
* @returns {'none'|'fresh'|'stale'|'expired'}
*/
export function transitCacheState(entry, now) {
if (!entry || !Number.isFinite(entry.at)) return 'none';
const age = now - entry.at;
if (age < 0) return 'fresh';
if (age < TRANSIT_PROXY_TTL_MS) return 'fresh';
if (age < TRANSIT_PROXY_STALE_MAX_MS) return 'stale';
return 'expired';
}
/**
* Response headers for a snapshot. `X-GEV-Cache` mirrors the other proxies
* (HIT / MISS / INFLIGHT / STALE-ERROR) so the layer can surface staleness.
* @param {'HIT'|'MISS'|'INFLIGHT'|'STALE-ERROR'} cacheState
* @param {string} [upstreamHost]
* @returns {Record<string, string>}
*/
export function transitResponseHeaders(
cacheState,
upstreamHost = '',
contactedAt = null,
) {
return {
'Content-Type': 'application/json; charset=utf-8',
'Cache-Control':
cacheState === 'STALE-ERROR'
? 'no-store'
: `public, max-age=${Math.floor(TRANSIT_PROXY_TTL_MS / 1000)}`,
'X-GEV-Cache': cacheState,
...(upstreamHost ? { 'X-Transit-Upstream': upstreamHost } : {}),
// When the operator last ANSWERED, which is not when the body was fetched.
// A feed whose file has not changed answers 304 forever, and the body we
// keep serving carries its original fetch time; without this the browser
// would read a healthy revalidated feed as one that had gone silent.
...(Number.isFinite(contactedAt)
? { 'X-Transit-Contact': String(Math.floor(contactedAt)) }
: {}),
};
}
+367
View File
@@ -0,0 +1,367 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { PbfWriter } from 'pbf';
import {
TRANSIT_BACKOFF_LADDER_MS,
TRANSIT_PROXY_STALE_MAX_MS,
TRANSIT_PROXY_TTL_MS,
TransitFeedShapeError,
buildTransitSnapshot,
isAcceptableTransitUpstreamUrl,
nextTransitBackoffMs,
repairVehicleTimestamps,
resolveTransitRoute,
transitCacheState,
transitRedirectDecision,
transitResponseHeaders,
transitUpstreamHeaders,
} from './transitProxy.js';
import { getTransitFeed } from './transitFeeds.js';
test('route resolution admits only the catalog and registered feed ids', () => {
assert.deepEqual(resolveTransitRoute('/feeds'), { route: 'feeds' });
assert.deepEqual(resolveTransitRoute('/feeds/?x=1'), { route: 'feeds' });
assert.equal(resolveTransitRoute('/vehicles/mbta')?.feed?.id, 'mbta');
assert.equal(resolveTransitRoute('/vehicles/mbta/')?.feed?.id, 'mbta');
assert.equal(resolveTransitRoute('/vehicles/mbta?trip=1')?.feed?.id, 'mbta');
assert.equal(resolveTransitRoute('/vehicles/nope'), null);
assert.equal(resolveTransitRoute('/vehicles/'), null);
assert.equal(resolveTransitRoute('/vehicles/mbta/extra'), null);
assert.equal(resolveTransitRoute('/vehicles/..%2F..%2Fetc'), null);
assert.equal(resolveTransitRoute('/vehicles/%E0%A4%A'), null); // malformed escape never throws
assert.equal(resolveTransitRoute('/'), null);
assert.equal(resolveTransitRoute(''), null);
assert.equal(resolveTransitRoute(undefined), null);
});
test('upstream headers identify the proxy and carry feed-specific identification', () => {
const plain = transitUpstreamHeaders(getTransitFeed('mbta'));
assert.match(plain['User-Agent'], /gods-eye-view-transit-proxy/);
assert.match(plain.Accept, /x-protobuf/);
const entur = transitUpstreamHeaders(getTransitFeed('entur-norway'));
assert.equal(entur['ET-Client-Name'], 'gods-eye-view-transit');
assert.ok(transitUpstreamHeaders(null)['User-Agent']);
});
test('only https upstreams are acceptable, including after a redirect', () => {
assert.equal(
isAcceptableTransitUpstreamUrl('https://cdn.mbta.com/x.pb'),
true,
);
assert.equal(
isAcceptableTransitUpstreamUrl(
'http://gtfs.ovapi.nl/nl/vehiclePositions.pb',
),
false,
);
assert.equal(isAcceptableTransitUpstreamUrl('ftp://x'), false);
assert.equal(isAcceptableTransitUpstreamUrl('not a url'), false);
});
test('snapshot shape carries provenance the layer displays', () => {
const writer = new PbfWriter();
const header = new PbfWriter();
header.writeStringField(1, '2.0');
header.writeVarintField(3, 1_700_000_000);
writer.writeBytesField(1, header.finish());
const snapshot = buildTransitSnapshot(
getTransitFeed('mbta'),
writer.finish(),
12345,
);
assert.equal(snapshot.feedId, 'mbta');
assert.equal(snapshot.name, 'MBTA');
assert.equal(snapshot.fetchedAt, 12345);
assert.equal(snapshot.feedTimestamp, 1_700_000_000);
assert.equal(snapshot.version, '2.0');
assert.equal(snapshot.count, 0);
assert.deepEqual(snapshot.vehicles, []);
});
test('cache policy: fresh within TTL, stale until the serve-stale window, expired after', () => {
const now = 1_000_000;
assert.equal(transitCacheState(null, now), 'none');
assert.equal(transitCacheState({ at: Number.NaN }, now), 'none');
assert.equal(transitCacheState({ at: now }, now), 'fresh');
assert.equal(
transitCacheState({ at: now - TRANSIT_PROXY_TTL_MS + 1 }, now),
'fresh',
);
assert.equal(
transitCacheState({ at: now - TRANSIT_PROXY_TTL_MS }, now),
'stale',
);
assert.equal(
transitCacheState({ at: now - TRANSIT_PROXY_STALE_MAX_MS + 1 }, now),
'stale',
);
assert.equal(
transitCacheState({ at: now - TRANSIT_PROXY_STALE_MAX_MS }, now),
'expired',
);
assert.equal(transitCacheState({ at: now + 5000 }, now), 'fresh'); // clock skew never expires a fresh fetch
});
test('response headers mark cache state and never let a stale-error response be cached downstream', () => {
assert.equal(
transitResponseHeaders('HIT', 'cdn.mbta.com')['X-Transit-Upstream'],
'cdn.mbta.com',
);
assert.equal(
transitResponseHeaders('HIT')['Cache-Control'],
'public, max-age=15',
);
assert.equal(
transitResponseHeaders('STALE-ERROR')['Cache-Control'],
'no-store',
);
assert.equal(transitResponseHeaders('MISS')['X-GEV-Cache'], 'MISS');
});
/** A minimal FeedMessage with the given header fields and vehicle entities. */
function encodeFeed({
incrementality = null,
timestamp = 1_700_000_000,
entities = [],
}) {
const writer = new PbfWriter();
const header = new PbfWriter();
header.writeStringField(1, '2.0');
if (incrementality !== null) header.writeVarintField(2, incrementality);
if (timestamp !== null) header.writeVarintField(3, timestamp);
writer.writeBytesField(1, header.finish());
for (const entity of entities) {
const feedEntity = new PbfWriter();
feedEntity.writeStringField(1, entity.id);
const vehicle = new PbfWriter();
const position = new PbfWriter();
position.writeFloatField(1, entity.lat);
position.writeFloatField(2, entity.lon);
vehicle.writeBytesField(2, position.finish());
if (entity.timestamp) vehicle.writeVarintField(5, entity.timestamp);
const descriptor = new PbfWriter();
descriptor.writeStringField(1, entity.vehicleId || entity.id);
vehicle.writeBytesField(8, descriptor.finish());
feedEntity.writeBytesField(4, vehicle.finish());
writer.writeBytesField(2, feedEntity.finish());
}
return writer.finish();
}
test('a redirect is judged before it is followed, not after it has been answered', () => {
const feed = { url: 'https://data.example.gov/download/feed.pb' };
// Same origin, absolute and relative, is the only case that may proceed.
assert.deepEqual(
transitRedirectDecision(
feed.url,
feed.url,
'https://data.example.gov/files/a.pb',
),
{ ok: true, url: 'https://data.example.gov/files/a.pb' },
);
assert.deepEqual(transitRedirectDecision(feed.url, feed.url, '/files/b.pb'), {
ok: true,
url: 'https://data.example.gov/files/b.pb',
});
// Another host is refused even though it is https — this is the hop that used
// to be contacted first and inspected afterwards.
const offOrigin = transitRedirectDecision(
feed.url,
feed.url,
'https://cdn.elsewhere.test/a.pb',
);
assert.equal(offOrigin.ok, false);
assert.match(offOrigin.reason, /left https:\/\/data\.example\.gov/);
// A downgrade to http, a missing Location, and a malformed target all refuse.
assert.equal(
transitRedirectDecision(feed.url, feed.url, 'http://data.example.gov/a.pb')
.ok,
false,
);
assert.equal(transitRedirectDecision(feed.url, feed.url, null).ok, false);
assert.equal(
transitRedirectDecision(feed.url, feed.url, 'javascript:alert(1)').ok,
false,
);
assert.equal(
transitRedirectDecision(feed.url, feed.url, 'data:text/plain,x').ok,
false,
);
assert.equal(
transitRedirectDecision('not-a-url', 'not-a-url', '/a.pb').ok,
false,
);
// A sibling port is a different origin.
assert.equal(
transitRedirectDecision(
feed.url,
feed.url,
'https://data.example.gov:8443/a.pb',
).ok,
false,
);
});
test('failure cooldown climbs and stops climbing, and a healthy feed waits for nothing', () => {
assert.equal(nextTransitBackoffMs(0), 0);
assert.equal(nextTransitBackoffMs(-3), 0);
assert.deepEqual([1, 2, 3, 4].map(nextTransitBackoffMs), [
...TRANSIT_BACKOFF_LADDER_MS,
]);
// Past the ladder the wait stays at its last rung rather than growing forever.
assert.equal(nextTransitBackoffMs(9), TRANSIT_BACKOFF_LADDER_MS.at(-1));
assert.equal(nextTransitBackoffMs(500), TRANSIT_BACKOFF_LADDER_MS.at(-1));
});
test('a differential feed is refused rather than read as a full snapshot', () => {
const feed = getTransitFeed('mbta');
const differential = encodeFeed({
incrementality: 1,
entities: [{ id: 'v1', lat: 42.36, lon: -71.05, timestamp: 1_700_000_000 }],
});
assert.throws(
() => buildTransitSnapshot(feed, differential, 1_700_000_000_000),
(error) =>
error instanceof TransitFeedShapeError &&
error.transitReason === 'differential',
);
// The same bytes with FULL_DATASET decode normally, so the refusal is about
// the header and not about the payload.
const full = encodeFeed({
incrementality: 0,
entities: [{ id: 'v1', lat: 42.36, lon: -71.05, timestamp: 1_700_000_000 }],
});
assert.equal(buildTransitSnapshot(feed, full, 1_700_000_000_000).count, 1);
// An absent incrementality field means FULL_DATASET by the spec's default.
assert.equal(
buildTransitSnapshot(feed, encodeFeed({ entities: [] }), 1).count,
0,
);
});
test('a vehicle with no time of its own borrows the feed header time and says so', () => {
const fetchedAtS = 1_700_000_500;
const repaired = repairVehicleTimestamps(
[
{ id: 'own', timestamp: 1_700_000_400 },
{ id: 'none' },
{ id: 'zero', timestamp: 0 },
],
1_700_000_450,
fetchedAtS,
);
assert.deepEqual(
repaired.map((vehicle) => [
vehicle.id,
vehicle.timestamp,
vehicle.timestampSource,
]),
[
['own', 1_700_000_400, 'vehicle'],
['none', 1_700_000_450, 'header'],
['zero', 1_700_000_450, 'header'],
],
);
// With no header either, fetch time is used and is labelled as such — never
// presented as the vehicle's own report.
const noHeader = repairVehicleTimestamps([{ id: 'none' }], null, fetchedAtS);
assert.deepEqual(
[noHeader[0].timestamp, noHeader[0].timestampSource],
[fetchedAtS, 'fetch'],
);
assert.deepEqual(repairVehicleTimestamps(null, null, fetchedAtS), []);
});
test('the snapshot builder fills timestamps from the header it decoded', () => {
const feed = getTransitFeed('mbta');
const bytes = encodeFeed({
timestamp: 1_700_000_000,
entities: [{ id: 'unstamped', lat: 42.36, lon: -71.05 }],
});
const snapshot = buildTransitSnapshot(feed, bytes, 1_700_000_900_000);
assert.equal(snapshot.vehicles[0].timestamp, 1_700_000_000);
assert.equal(snapshot.vehicles[0].timestampSource, 'header');
assert.equal(snapshot.feedTimestamp, 1_700_000_000);
});
test('conditional-request validators and gzip ride along with feed identification', () => {
const entur = getTransitFeed('entur-norway');
const plain = transitUpstreamHeaders(entur);
assert.equal(plain['Accept-Encoding'], 'gzip');
assert.equal(plain['ET-Client-Name'], 'gods-eye-view-transit');
assert.equal('If-None-Match' in plain, false);
const conditional = transitUpstreamHeaders(entur, {
etag: 'W/"abc"',
lastModified: 'Wed, 10 Sep 2026 12:00:00 GMT',
});
assert.equal(conditional['If-None-Match'], 'W/"abc"');
assert.equal(
conditional['If-Modified-Since'],
'Wed, 10 Sep 2026 12:00:00 GMT',
);
assert.match(conditional['User-Agent'], /gods-eye-view/);
});
test('retained routes validate the entire identifier and only MBTA is opted in', () => {
assert.equal(resolveTransitRoute('/trail/mbta/bus%201').vehicleId, 'bus 1');
for (const path of [
'/trail/mbta/a%2Fb',
'/trail/mbta/%00',
'/trail/mbta/%5C',
'/trail/mbta/%2E%2E',
'/trail/mbta/%E0%A4%A',
`/trail/mbta/${encodeURIComponent('é'.repeat(129))}`,
'/trail/capmetro-austin/b',
])
assert.equal(resolveTransitRoute(path), null);
});
test('client history validates response bounds, epochs and cancellation through parsing', async () => {
const { fetchTransitHistory } = await import('./transitProxy.js');
const payload = {
version: 1,
feedId: 'mbta',
vehicleId: 'b',
epochs: [{ id: 1, trip: '', route: '1', mode: 'bus' }],
fixes: [[1000, 42, -71, 1, 1]],
};
assert.deepEqual(
await fetchTransitHistory(
'mbta',
'b',
new AbortController().signal,
async () => new Response(JSON.stringify(payload)),
),
payload,
);
for (const value of [
{ ...payload, vehicleId: 'wrong' },
{ ...payload, fixes: [[1000, 91, -71, 1, 1]] },
{ ...payload, fixes: Array(129).fill(payload.fixes[0]) },
{ ...payload, epochs: [] },
])
await assert.rejects(
fetchTransitHistory(
'mbta',
'b',
undefined,
async () => new Response(JSON.stringify(value)),
),
);
await assert.rejects(
fetchTransitHistory(
'mbta',
'b',
undefined,
async () => new Response('x'.repeat(32769)),
),
/limit/,
);
const controller = new AbortController();
await assert.rejects(
fetchTransitHistory('mbta', 'b', controller.signal, async () => {
controller.abort();
return new Response(JSON.stringify(payload));
}),
{ name: 'AbortError' },
);
});
+51 -12
View File
@@ -20,21 +20,48 @@ export const VESSEL_CARD_FADE_DISTANCE_M = 5_000_000;
*/
const TYPE_STYLES = [
{ pattern: /tanker/i, css: '#ffb347', accent: '255, 179, 71' },
{ pattern: /cargo|container|bulk|carrier/i, css: '#39d5ff', accent: '57, 213, 255' },
{ pattern: /passenger|ferry|cruise/i, css: '#ff7adf', accent: '255, 122, 223' },
{
pattern: /cargo|container|bulk|carrier/i,
css: '#39d5ff',
accent: '57, 213, 255',
},
{
pattern: /passenger|ferry|cruise/i,
css: '#ff7adf',
accent: '255, 122, 223',
},
{ pattern: /fishing/i, css: '#7cff9b', accent: '124, 255, 155' },
{ pattern: /tug|tow|pilot|supply|service/i, css: '#f7f0a3', accent: '247, 240, 163' },
{
pattern: /tug|tow|pilot|supply|service/i,
css: '#f7f0a3',
accent: '247, 240, 163',
},
];
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
const NUMERIC_TYPE_SPECIALS = {
30: 'FISHING', 31: 'TOWING', 32: 'TOWING', 33: 'DREDGER', 34: 'DIVE OPS',
35: 'MILITARY', 36: 'SAILING', 37: 'PLEASURE',
50: 'PILOT', 51: 'SAR', 52: 'TUG', 53: 'PORT TENDER', 54: 'ANTI-POLLUTION',
55: 'LAW ENFORCE', 58: 'MEDICAL',
30: 'FISHING',
31: 'TOWING',
32: 'TOWING',
33: 'DREDGER',
34: 'DIVE OPS',
35: 'MILITARY',
36: 'SAILING',
37: 'PLEASURE',
50: 'PILOT',
51: 'SAR',
52: 'TUG',
53: 'PORT TENDER',
54: 'ANTI-POLLUTION',
55: 'LAW ENFORCE',
58: 'MEDICAL',
};
const NUMERIC_TYPE_FAMILIES = {
4: 'HIGH-SPEED', 6: 'PASSENGER', 7: 'CARGO', 8: 'TANKER', 9: 'OTHER',
4: 'HIGH-SPEED',
6: 'PASSENGER',
7: 'CARGO',
8: 'TANKER',
9: 'OTHER',
};
/**
@@ -76,13 +103,22 @@ function styleForType(type) {
* @param {number} [rowLimit=900] Configured source row ceiling.
* @returns {number}
*/
export function vesselOverlayCohortLimit(width, height, rowLimit = VESSEL_DEFAULT_LABEL_LIMIT) {
export function vesselOverlayCohortLimit(
width,
height,
rowLimit = VESSEL_DEFAULT_LABEL_LIMIT,
) {
const w = Number(width);
const h = Number(height);
const requested = Number(rowLimit);
if (!(w > 0) || !(h > 0) || !(requested > 0)) return 0;
const gridCapacity = Math.ceil(w / VESSEL_LABEL_GRID_PX) * Math.ceil(h / VESSEL_LABEL_GRID_PX);
return Math.min(VESSEL_OVERLAY_MAX_COHORT, Math.floor(requested), gridCapacity);
const gridCapacity =
Math.ceil(w / VESSEL_LABEL_GRID_PX) * Math.ceil(h / VESSEL_LABEL_GRID_PX);
return Math.min(
VESSEL_OVERLAY_MAX_COHORT,
Math.floor(requested),
gridCapacity,
);
}
/**
@@ -93,7 +129,10 @@ export function vesselOverlayCohortLimit(width, height, rowLimit = VESSEL_DEFAUL
* @param {number} [fadeDistance=5000000] Ambient distance-fade endpoint.
* @returns {Object}
*/
export function applyVesselOverlayPolicy(card, fadeDistance = VESSEL_CARD_FADE_DISTANCE_M) {
export function applyVesselOverlayPolicy(
card,
fadeDistance = VESSEL_CARD_FADE_DISTANCE_M,
) {
const selected = card?.selected === true;
const rawGap = Number(card?.gapPx) || 10;
const gapPx = Math.max(12, rawGap + 8);