Merge branch 'main' into fix/i18n-installations-note

# Conflicts:
#	scripts/package-boundaries.json
#	src/layers/installations/controls.js
This commit is contained in:
German Khokhlov committed 2026-11-18 16:35:52 +04:00
commit 93b091d082
2063 files changed
+322399 -46202

No files matched your search

+14 -3
View File
@@ -64,7 +64,11 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
const geometricFeet = finiteNumber(aircraft?.alt_geom);
const groundSpeedKnots = finiteNumber(aircraft?.gs);
const verticalRateFpm = readAdsbVerticalRateFpm(aircraft);
const track = finiteNumber(aircraft?.track);
// A parked or slow aircraft reports no ground track, but often its true
// heading (surface messages): the way its nose points, which is what an
// aircraft standing still is drawn by. Magnetic heading is not true north.
const track =
finiteNumber(aircraft?.track) ?? finiteNumber(aircraft?.true_heading);
return [
hex,
@@ -94,7 +98,7 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
* Normalize an adsb.lol point response to an OpenSky-compatible response.
* Invalid rows and positionless contacts are intentionally excluded.
* @param {object} payload adsb.lol v2 response.
* @returns {{time:number,states:Array[]}}
* @returns {{time:number,states:Array[],emergencyByIcao?:object,typeByIcao?:object}}
*/
export function normalizeAdsbLolPointResponse(payload) {
const responseNow = finiteNumber(payload?.now);
@@ -107,9 +111,10 @@ export function normalizeAdsbLolPointResponse(payload) {
const aircraft = Array.isArray(payload?.ac) ? payload.ac : [];
const states = [];
// Keep the OpenSky vectors unchanged. The regional fallback's extra readsb
// status travels alongside them, keyed only to admitted aircraft.
// status and type travel alongside them, keyed only to admitted aircraft.
const admitted = new Set();
const statuses = [];
const types = [];
for (const row of aircraft) {
const state = normalizeAdsbLolAircraftState(row, nowSeconds);
if (!state) continue;
@@ -121,11 +126,17 @@ export function normalizeAdsbLolPointResponse(payload) {
admitted.add(id);
if (typeof row.emergency === 'string')
statuses.push([id, row.emergency.trim().toLowerCase()]);
const type = typeof row.t === 'string' ? row.t.trim().toUpperCase() : '';
if (type) types.push([id, type]);
}
const emergencyByIcao = Object.fromEntries(statuses);
const typeByIcao = Object.fromEntries(types);
return {
time: nowSeconds,
states,
...(Object.keys(emergencyByIcao).length ? { emergencyByIcao } : {}),
// The ICAO type designator (readsb `t`), so the aircraft is classed from
// its first fix instead of after a lookup.
...(types.length ? { typeByIcao } : {}),
};
}
+31
View File
@@ -49,3 +49,34 @@ test('keeps grounded fallback contacts and rejects rows without positions', () =
assert.equal(normalized.states[0][7], null);
assert.equal(normalized.states[0][8], true);
});
test('an aircraft with no track takes its true heading, never its magnetic one', () => {
const at = (extra) =>
normalizeAdsbLolAircraftState(
{ hex: 'abc123', lat: 37.7, lon: -122.2, alt_baro: 'ground', ...extra },
1000,
)[10];
assert.equal(at({ track: 56.25, true_heading: 40 }), 56.25, 'track first');
assert.equal(at({ true_heading: 244.69 }), 244.69, 'true heading');
assert.equal(at({ mag_heading: 278.44 }), null, 'not magnetic');
assert.equal(at({}), null, 'none');
});
test('the point response sends each admitted aircraft type alongside the vectors', () => {
const response = normalizeAdsbLolPointResponse({
now: 1000,
ac: [
{ hex: 'A1B2C3', lat: 30, lon: -97, t: 'ec45' },
{ hex: 'A1B2C3', lat: 31, lon: -97, t: 'B738' },
{ hex: 'D4E5F6', lat: 30, lon: -98 },
{ hex: 'BAD000', t: 'A320' },
],
});
assert.equal(response.states.length, 3);
assert.deepEqual(response.typeByIcao, { a1b2c3: 'EC45' });
const untyped = normalizeAdsbLolPointResponse({
now: 1000,
ac: [{ hex: 'D4E5F6', lat: 30, lon: -98 }],
});
assert.equal(Object.hasOwn(untyped, 'typeByIcao'), false);
});
+35 -64
View File
@@ -401,6 +401,11 @@ const OPENSKY_CATEGORY = {
7: 'fastjet', // High performance (>5g, >400 kt)
8: 'helicopter', // Rotorcraft
9: 'glider',
16: 'vehicle', // Surface vehicle, emergency
17: 'vehicle', // Surface vehicle, service
18: 'station', // Point obstacle
19: 'station', // Cluster obstacle
20: 'station', // Line obstacle
};
/** ADS-B emitter-category string → class. */
@@ -413,13 +418,35 @@ const EMITTER_CATEGORY = {
A6: 'fastjet',
A7: 'helicopter',
B1: 'glider',
C1: 'vehicle', // Surface vehicle, emergency
C2: 'vehicle', // Surface vehicle, service
C3: 'station', // Point obstacle
C4: 'station', // Cluster obstacle
C5: 'station', // Line obstacle
};
/**
* The type codes feeds give what is not an aircraft: an airport vehicle
* (ZVEH) and a ground station (GRND).
*/
const GROUND_TYPE_CLASS = { ZVEH: 'vehicle', GRND: 'station' };
/**
* The class an aircraft draws and reads as, from its ICAO type code (which
* outranks the category), else its OpenSky integer or ADS-B emitter category.
* Besides the aircraft classes, `vehicle` is an airport vehicle (type ZVEH,
* emitter C1 or C2) and `station` a ground station or obstacle (type GRND,
* emitter C3 to C5). A known type code outside every set is an airliner, and
* so is a contact with nothing to go on.
* @param {{typeCode?: string|null, category?: string|number|null}} [record]
* @returns {string}
*/
export function classifyAircraft({ typeCode, category } = {}) {
const code = String(typeCode || '')
.trim()
.toUpperCase();
if (code) {
if (GROUND_TYPE_CLASS[code]) return GROUND_TYPE_CLASS[code];
if (FASTJET.has(code)) return 'fastjet';
if (UAV.has(code)) return 'uav';
if (HELI.has(code)) return 'helicopter';
@@ -452,69 +479,13 @@ export const AIRCRAFT_CLASS_LABELS = Object.freeze({
fastjet: msg('Fast jet'),
bizjet: msg('Business jet'),
uav: msg('Drone'),
vehicle: msg('Airport vehicle'),
station: msg('Ground station / obstacle'),
});
/** 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,
};
/** 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,
};
/** 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',
};
/** Real per-class GLBs (2026-08-15 Hangar fleet, owner picks; CC-BY 4.0 —
* provenance in public/models/README.md). Every asset is vertex-baked to the
* airplane.glb convention: Y-up, X = length, Z = span, nose −X (so the layers'
* MODEL_HEADING_OFFSET_DEG = 180 applies unchanged), origin at bbox centre,
* REAL-WORLD METERS (render at scale 1 — no MODEL_SCALE, no CLASS_SCALE_3D).
* bellyM = origin→lowest-vertex distance (grounded-model lift, replaces the
* airplane.glb MODEL_BELLY_OFFSET_NATIVE formula); radiusM = bounding-sphere
* radius in meters (pixel-size math). Values measured from the shipped GLBs —
* 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 },
};
/**
* The tint an airport vehicle's sprite draws with in Flights and Local
* ADS-B: an orange amber, apart from aircraft white and the military layer's
* yellow amber (#FFB800).
*/
export const VEHICLE_TINT_CSS = '#FF8F1F';
+47 -13
View File
@@ -1,7 +1,7 @@
// src/data/aircraftClass.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { classifyAircraft, CLASS_SCALE_2D, CLASS_SCALE_3D, CLASS_MODEL_URL, CLASS_MODEL_REAL } from './aircraftClass.js';
import { AIRCRAFT_CLASS_LABELS, classifyAircraft } from './aircraftClass.js';
test('type-code classification (military layer path)', () => {
assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet');
@@ -48,19 +48,53 @@ test('typeCode outranks category; unknown → airliner', () => {
assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner');
});
test('scale/url tables cover every class', () => {
for (const kind of ['light','glider','turboprop','airliner','widebody','quadjet','helicopter','fastjet','bizjet','uav']) {
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
assert.ok(CLASS_SCALE_3D[kind] >= 0.75 && CLASS_SCALE_3D[kind] <= 1.45, kind);
assert.ok(typeof CLASS_MODEL_URL[kind] === 'string', kind);
test('every class has a label', () => {
for (const kind of [
'light',
'glider',
'turboprop',
'airliner',
'widebody',
'quadjet',
'helicopter',
'fastjet',
'bizjet',
'uav',
'vehicle',
'station',
]) {
assert.ok(AIRCRAFT_CLASS_LABELS[kind], kind);
}
});
test('CLASS_MODEL_REAL entries carry the fields the layers consume', () => {
for (const [kind, spec] of Object.entries(CLASS_MODEL_REAL)) {
assert.ok(spec.url.startsWith('/models/') && spec.url.endsWith('.glb'), kind);
assert.ok(spec.radiusM > 0 && spec.bellyM > 0, kind);
// every real-model class must also exist in the classifier tables
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
}
test('airport vehicles and ground stations class apart from aircraft', () => {
// A feed's own types, in any case.
assert.equal(classifyAircraft({ typeCode: 'ZVEH' }), 'vehicle');
assert.equal(classifyAircraft({ typeCode: ' zveh ' }), 'vehicle');
assert.equal(classifyAircraft({ typeCode: 'GRND' }), 'station');
// Emitter categories: surface vehicles, then obstacles.
assert.equal(classifyAircraft({ category: 'C1' }), 'vehicle');
assert.equal(classifyAircraft({ category: 'C2' }), 'vehicle');
for (const category of ['C3', 'C4', 'C5'])
assert.equal(classifyAircraft({ category }), 'station', category);
// OpenSky's integer categories for the same.
assert.equal(classifyAircraft({ category: 16 }), 'vehicle');
assert.equal(classifyAircraft({ category: 17 }), 'vehicle');
assert.equal(classifyAircraft({ category: 18 }), 'station');
// A type code still outranks the category.
assert.equal(
classifyAircraft({ typeCode: 'ZVEH', category: 'A3' }),
'vehicle',
);
assert.equal(
classifyAircraft({ typeCode: 'A320', category: 'C1' }),
'airliner',
);
});
test('helicopter types and categories', () => {
for (const typeCode of ['EC35', 'R44', 'S76', 'H60', 'AS50', 'B407'])
assert.equal(classifyAircraft({ typeCode }), 'helicopter', typeCode);
assert.equal(classifyAircraft({ category: 'A7' }), 'helicopter');
assert.equal(classifyAircraft({ category: 8 }), 'helicopter');
});
+67 -24
View File
@@ -1,8 +1,17 @@
import * as Cesium from 'cesium';
import { TRACKED_ICON_COLOR } from '../layers/military/policy.js';
import { createRendering as civilRendering } from '../layers/flights/rendering.js';
import { createRendering as militaryRendering } from '../layers/military/rendering.js';
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
import { createIcons as createMilitaryIcons } from '../layers/military/icons.js';
import { createContactIcons } from './aircraftIconLayer.js';
import {
aircraftMotionRegime,
createMotionRegime,
fixEpochMs,
fixPosition,
copyPosition,
historyFix,
julianAt,
} from './aircraftMotionRegime.js';
import { aircraftEmergency } from './aircraftEmergency.js';
// Source-to-voice provenance, status retention/clearing, contact-time contracts,
// and civil/military billboard, Cockpit and model tint regressions.
@@ -138,6 +147,7 @@ test('changed status without contact time retains general contact, including voi
const runner = createGevActionRunner({
viewer: {
clock: { onTick: { addEventListener: () => () => {} } },
canvas: { addEventListener() {}, removeEventListener() {} },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
@@ -444,36 +454,36 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
const red = rendering._fleetBillboardColor('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
assert.ok(red.red > 0.9 && red.green < 0.5);
assert.ok(red[0] > 0.9 && red[1] < 0.5);
flightState.records.data.set('civil', {
emergency: aircraftEmergency({ squawk: '7700' }),
});
assert.equal(rendering._modelColor('civil'), red);
if (rendering._cockpitContactColor)
assert.equal(rendering._cockpitContactColor('civil'), red);
// Tracking never recolours: a tracked emergency stays red.
flightState._trackedIcao = 'civil';
assert.equal(
rendering._modelColor('civil'),
factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR,
);
assert.equal(rendering._modelColor('civil'), red);
flightState._trackedIcao = null;
flightState.records.data.set('civil', { emergency: null });
assert.equal(rendering._modelColor('civil'), normal);
// An ordinary model draws its mesh's own colours, whatever the billboard's.
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
flightState._trackedIcao = 'civil';
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
flightState._trackedIcao = null;
}
});
test('GERMAN: an existing untracked military billboard repaints each poll without alpha loss', () => {
test('GERMAN: an existing untracked military icon repaints each poll without losing its fade', () => {
const { flightState, rendering } = renderHarness(militaryRendering);
const bb = {
color: rendering._fleetBillboardColor('abc123').withAlpha(0.65),
};
Object.assign(flightState, {
_billboards: new Map([['abc123', bb]]),
_icons: createContactIcons(),
_models: new Map(),
_positionHistory: new Map(),
_cullPositions: new Map(),
_displayCourse: new Map(),
_groundSnap: { forget() {} },
_cockpitContactMode: false,
_cockpitNearContacts: new Set(),
});
const records = new MilitaryFlightRecords({
geoidHeight: () => 0,
@@ -481,18 +491,51 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
floorAltitudeM: (value) => value,
});
flightState.records = records;
const parts = {
rendering: {
...rendering,
_iconKind: () => 'jet',
_syncModelToClass() {},
},
motion: {
_motionRegime: (history, info, renderTime) =>
aircraftMotionRegime(
history,
info,
renderTime,
{ speed: 'speedMps', track: 'track' },
createMotionRegime(),
),
_displayTimeAt: julianAt,
_fixEpochMs: fixEpochMs,
_fixPosition: fixPosition,
_copyPosition: copyPosition,
_historyFix: historyFix,
_refloorStaleGroundedContacts() {},
_sampleMeshFloor() {},
},
};
const icons = createMilitaryIcons({
flightState,
services: { focus: { focusPassIsNeeded: () => false } },
parts,
});
const row = 'abc123';
flightState._icons.put({
id: row,
pos: { x: 0, y: 0, z: 0 },
meta: { layer: 'military', id: row },
});
// The focus fade the fleet tick composes lives in its own field.
flightState._icons.setFocus(row, 0.65);
const apply = createMilitarySnapshotRenderer({
flightState,
records,
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
meshFloor: { sampleMeshFloorCells() {} },
groundFloor: { warmGroundFloor() {} },
militaryRegistry: { registerMilitaryIcaos() {} },
rendering: {
...rendering,
_syncModelToClass() {},
_applyFleetBillboardPresentation() {},
},
motion: {},
rendering: parts.rendering,
motion: parts.motion,
icons,
tracking: {},
queries: {},
});
@@ -518,7 +561,7 @@ test('GERMAN: an existing untracked military billboard repaints each poll withou
{ observedAtMs: NOW_MS },
);
apply(snapshot, {});
assert.equal(bb.color.green < 0.5, red);
assert.equal(bb.color.alpha, 0.65);
assert.equal(flightState._icons.item(row).color[1] < 0.5, red);
assert.ok(Math.abs(flightState._icons.focus(row) - 0.65) < 1e-6);
}
});
File diff suppressed because it is too large. Load diff
+483
View File
@@ -0,0 +1,483 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
COAST_FLOOR_LOOKAHEAD_MS,
createAircraftIcons,
createContactIcons,
floorCoastArc,
} from './aircraftIconLayer.js';
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { createDisplayDelay } from './displayDelay.js';
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
import { ROTOR_STILL_FRAME } from './rotorFrames.js';
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
test('following the world clock, contacts draw at the world’s time on the scene clock', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS + 86_400_000 });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = {
_viewer: viewer,
now: () => (following ? WORLD_MS : Date.now()),
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
// Live: a poll interval behind real time, on the delayed live clock.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
assert.equal(icons._displayMs(), Date.now() - 30_000);
following = true;
assert.equal(icons._displayMs(), WORLD_MS, 'the world’s time, no delay');
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
icons._disposeIcons();
});
test('as the display delay moves, the renderer’s live clock and the layer’s display time move with it; the world clock ignores it', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const viewer = {};
const { draw } = bindFakeDraw(viewer);
let following = false;
const state = { _viewer: viewer, now: () => Date.now() };
const delay = createDisplayDelay({ floorMs: 30_000, pollMs: 30_000 });
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {},
layerId: 'flights',
displayDelay: delay,
followsClock: () => following,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
icons._createIcons(viewer);
const set = draw.find('flights-icons:');
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 30_000 });
// Reports 90 s old every 30 s: the delay heads for about two minutes.
for (let i = 0; i < 20; i++)
delay.noteReport(WORLD_MS, WORLD_MS - 90_000, WORLD_MS - 120_000);
delay.settle(WORLD_MS);
t.mock.timers.setTime(WORLD_MS + 10_000);
icons._syncMotionClock();
// 10 s at 0.2 s/s: 2 s more, on both the renderer's clock and the layer's.
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 32_000 });
assert.equal(icons._displayMs(), Date.now() - 32_000);
// Following the world clock: no delay, and it is not moved on meanwhile.
following = true;
t.mock.timers.setTime(WORLD_MS + 20_000);
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'scene' });
assert.equal(icons._displayMs(), Date.now());
assert.equal(delay.currentMs, 32_000);
following = false;
icons._syncMotionClock();
assert.deepEqual(set.spec.motionClock, { kind: 'live', delayMs: 34_000 });
icons._disposeIcons();
});
test('a coasting icon is kept above rising ground, as the CPU coast is', () => {
const T0 = WORLD_MS;
let now = T0;
const cosLat = Math.cos((30 * Math.PI) / 180);
const metresEast = (lonDeg) => lonDeg * 111_320 * cosLat;
// A slope rising east from 100 m out, half a metre per metre.
const ground = (_lat, lon) => Math.max(0, (metresEast(lon) - 100) * 0.5);
const fix = { epochMs: T0, position: fromDegrees(0, 30, 100) };
const state = {
now: () => now,
_icons: createContactIcons(),
_positionHistory: new Map([['c', [fix]]]),
records: { data: new Map([['c', {}]]) },
};
const icons = createAircraftIcons({
state,
services: {
focus: { focusPassIsNeeded: () => false },
groundFloor: { cachedGroundFloor: ground },
},
parts: {
motion: {
_displayTimeAt: (ms) => ms,
_fixEpochMs: (f) => f.epochMs,
// Coasting east past its only fix at 100 m/s, for five minutes.
_motionRegime: () => ({
kind: 'fix',
fix,
speed: 100,
heading: 90,
turnRateDps: 0,
minDt: -60,
maxDt: 300,
}),
},
},
layerId: 'flights',
renderDelaySec: 30,
followsClock: () => true,
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
state._icons.put(
{
id: 'c',
pos: fix.position,
motion: { kind: 'hold', courseDeg: 90 },
course: 90,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
icons._planIcon('c');
// The fleet pass, every 80 ms for 12 s: the icon never sinks into the
// slope, and over open ground it coasts level.
let lowest = Infinity;
for (now = T0; now <= T0 + 12_000; now += 80) {
icons._replanExpired(now);
const p = icons._iconPosition('c');
const carto = toCartographicRadians(p);
const floor = ground(0, (carto.lon * 180) / Math.PI) + COAST_FLOOR_LIFT_M;
lowest = Math.min(lowest, carto.height - floor);
if (now - T0 <= 2_000)
assert.ok(Math.abs(carto.height - 100) < 0.1, 'level over open ground');
assert.ok(Math.abs(icons._iconCourse('c') - 90) < 1e-6, 'nose east');
}
assert.ok(lowest > -0.05, `at most 5 cm under the floor (${lowest} m)`);
// 1.2 km east, the slope is at 550 m: it rode up the slope.
now = T0 + 12_000;
icons._replanExpired(now);
const end = toCartographicRadians(icons._iconPosition('c'));
const east = metresEast((end.lon * 180) / Math.PI);
assert.ok(Math.abs(east - 1_200) < 5, `1.2 km east (${east} m)`);
assert.ok(end.height > 550, `on the slope (${end.height} m)`);
});
test('a coast over known ground that never rises is planned once', () => {
const fix = { position: fromDegrees(0, 30, 100) };
const arc = {
kind: 'arc',
fix: fix.position,
t0: 0,
minDtS: -60,
maxDtS: 5,
speedMps: 100,
trackDeg: 90,
turnRateDps: 0,
};
assert.deepEqual(
floorCoastArc(arc, 0, () => 0),
{ expiresAt: Infinity },
);
assert.deepEqual(
floorCoastArc(arc, 0, () => null),
{ expiresAt: COAST_FLOOR_LOOKAHEAD_MS },
'unknown ground is read again',
);
assert.equal(
floorCoastArc({ ...arc, fix: fromDegrees(0, 30, 10_000) }, 0, () => 0),
null,
'a cruise above any terrain never reads it',
);
// Stopped at the end of its coast, under ground that rose since.
const held = floorCoastArc(arc, 6_000, () => 200);
assert.equal(held.motion.kind, 'hold');
assert.ok(
Math.abs(toCartographicRadians(held.pos).height - 201.5) < 1e-6,
'held on the ground where the coast stopped',
);
});
test('only airborne helicopters in view turn their rotor, written when the frame steps', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const here = fromDegrees(0, 30, 300);
const away = fromDegrees(90, 30, 300);
const records = new Map([
['h1', { klass: 'helicopter', onGround: false }],
['h2', { klass: 'helicopter', onGround: true }],
['p1', { klass: 'airliner', onGround: false }],
['h3', { klass: 'helicopter', onGround: false }],
]);
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (_id, klass) => klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1,
},
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
for (const id of records.keys()) {
state._icons.put(
{
id,
pos: id === 'h3' ? away : here,
motion: { kind: 'hold', courseDeg: 0 },
size: [20, 20],
},
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
const image = (id) => state._icons.item(id).image;
// The grounded helicopter holds the still frame.
assert.equal(
image('h2'),
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
const h3Before = image('h3');
const writes = new Map();
const update = state._icons.update;
state._icons.update = (id, patch, options) => {
writes.set(id, (writes.get(id) ?? 0) + 1);
return update(id, patch, options);
};
// The fleet pass, every 80 ms for a second; h3 is out of view.
const inView = (p) => Math.abs(p.x - here.x) < 1;
const seen = new Set();
for (let step = 0; step <= 12; step++) {
if (step) t.mock.timers.tick(80);
icons._turnRotors(Date.now(), Date.now(), inView);
seen.add(image('h1'));
}
// Through every frame, written only on the steps its frame changed.
assert.equal(seen.size, 3);
for (const frame of [0, 1, 2])
assert.ok(seen.has(aircraftIcon('helicopter', FLEET_ICON_PX, frame)));
assert.ok(
writes.get('h1') >= 8 && writes.get('h1') <= 11,
`${writes.get('h1')} writes`,
);
assert.equal(writes.get('h2') ?? 0, 0, 'grounded: frozen');
assert.equal(writes.get('p1') ?? 0, 0, 'not a helicopter');
assert.equal(writes.get('h3') ?? 0, 0, 'out of view');
assert.equal(image('h3'), h3Before);
// Landing freezes it on the still frame.
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
const landed = writes.get('h1');
t.mock.timers.tick(400);
icons._turnRotors(Date.now(), Date.now(), inView);
assert.equal(writes.get('h1'), landed);
assert.equal(
image('h1'),
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
});
/** An icon layer over helicopters `ids`, all at `here`, for the rotor tests. */
function rotorFixture(records, positions, tracking = {}) {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map(),
_cockpitNearContacts: new Set(),
records: { data: records, missingPolls: new Map() },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
rendering: {
_iconKind: (_id, klass) => klass,
_fleetBillboardColor: () => [1, 1, 1, 1],
_fleetBillboardScale: () => 1,
},
tracking,
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
});
for (const id of records.keys()) {
state._icons.put(
{
id,
pos: positions[id],
motion: { kind: 'hold', courseDeg: 0 },
size: [20, 20],
},
{ expiresAt: Infinity },
);
icons._applyIconPresentation(id);
}
return { state, icons };
}
test('a tracked helicopter that lands shows the still frame at once', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
let synced = 0;
const { state, icons } = rotorFixture(
records,
{ h1: fromDegrees(0, 30, 300) },
{ _syncTrackedBillboardImage: () => synced++ },
);
state._trackedIcao = 'h1';
assert.equal(icons._rotorsTurning(), true);
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
assert.equal(synced, 1, 'the tracked billboard is given its images again');
assert.equal(icons._rotorsTurning(), false);
assert.equal(
icons._fleetLook('h1').image,
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
);
// Taxiing faster than 1 m/s, its rotor turns again, as the model's does.
records.get('h1').velocity = 5;
icons._applyIconPresentation('h1');
assert.equal(icons._rotorsTurning(), true);
records.get('h1').velocity = 0;
icons._applyIconPresentation('h1');
assert.equal(synced, 2);
assert.equal(icons._rotorsTurning(), false);
// An untracked one landing does not touch the tracked billboard.
records.get('h1').onGround = false;
icons._applyIconPresentation('h1');
state._trackedIcao = null;
records.get('h1').onGround = true;
icons._applyIconPresentation('h1');
assert.equal(synced, 2);
});
test('a helicopter out of view is judged once per rotor frame, not every pass', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const records = new Map();
const positions = {};
for (let i = 0; i < 300; i++) {
const id = `h${i}`;
records.set(id, { klass: 'helicopter', onGround: false });
positions[id] = fromDegrees(90, 30, 300);
}
const { state, icons } = rotorFixture(records, positions);
let judged = 0;
const inView = () => {
judged++;
return false;
};
const writes = [];
const update = state._icons.update;
state._icons.update = (id, ...rest) => {
writes.push(id);
return update(id, ...rest);
};
// Passes 10 ms apart for 2 s: 200 passes over 300 helicopters, all out of
// view. Each is judged at most once per frame step (20 steps), and not on
// a step back onto the frame it is drawn at.
for (let pass = 0; pass < 200; pass++) {
t.mock.timers.tick(10);
icons._turnRotors(Date.now(), Date.now(), inView);
}
assert.ok(judged <= 300 * 21, `${judged} judgements`);
assert.ok(judged >= 300 * 10, `${judged} judgements`);
assert.equal(writes.length, 0, 'none in view: no image written');
});
test('back at live, a placed contact eases from where it is drawn over a recovery, nose along the way', (t) => {
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
const drawnAt = fromDegrees(0, 30, 3_000);
const SPEED = 200;
// The placement has it 2 km east of where it is drawn, flying east.
const placedAt = (wallMs) => {
const east = 2_000 + (SPEED * (wallMs - WORLD_MS)) / 1000;
return fromDegrees(east / (111_320 * Math.cos(Math.PI / 6)), 30, 3_000);
};
const plan = (handover, keep = {}) => {
const state = {
now: () => Date.now(),
_icons: createContactIcons(),
_positionHistory: new Map([['c', [{ epochMs: WORLD_MS }]]]),
records: { data: new Map([['c', {}]]) },
};
const icons = createAircraftIcons({
state,
services: { focus: { focusPassIsNeeded: () => false } },
parts: {
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
},
layerId: 'flights',
courseMaxDps: 3,
cockpitContactSizePx: 8,
placeAt: (_id, wallMs, _info, _history, out) => {
Object.assign(out, placedAt(wallMs));
return { courseDeg: 90, speedMps: SPEED };
},
});
state._icons.put(
{
id: 'c',
pos: drawnAt,
motion: { kind: 'hold', courseDeg: 0 },
course: 0,
size: [20, 20],
},
{ expiresAt: -Infinity },
);
icons._planIcon('c', handover ? { handover: true } : undefined);
keep.icons = icons;
return state._icons;
};
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
const eased = plan(true);
const end = eased.expires('c');
assert.equal(end, WORLD_MS + recoveryMs(2_000, SPEED));
assert.ok(end - WORLD_MS > 1_000, 'longer than a placed plan');
assert.ok(metres(eased.position('c', WORLD_MS, {}), drawnAt) < 1);
assert.ok(metres(eased.position('c', end, {}), placedAt(end)) < 1);
// The nose points along the way from where it is drawn to where it goes.
assert.ok(Math.abs(eased.course('c', WORLD_MS) - 90) < 1);
const plain = plan(false);
assert.ok(
metres(plain.position('c', WORLD_MS, {}), placedAt(WORLD_MS)) < 1,
'without the handover it is drawn where it is placed',
);
// The next answer comes 15 s in, the ease still running: it eases on from
// where it is drawn then, not cut to where it is placed.
const keep = {};
const easing = plan(true, keep);
const firstEnd = easing.expires('c');
assert.ok(firstEnd - WORLD_MS > 15_000, 'an ease longer than a poll');
t.mock.timers.tick(15_000);
const at = Date.now();
const drawnThen = easing.position('c', at, {});
keep.icons._planIcon('c');
assert.ok(metres(easing.position('c', at, {}), drawnThen) < 1);
const reEnd = easing.expires('c');
assert.ok(reEnd > at + 1_000, 'eases on');
assert.ok(metres(easing.position('c', reEnd, {}), placedAt(reEnd)) < 1);
// Once it has caught up, the next answer draws it where it is placed.
t.mock.timers.tick(reEnd - at + 1);
keep.icons._planIcon('c');
assert.ok(
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
);
});
+119 -30
View File
@@ -8,9 +8,9 @@
* width/height 20 (24 tracked) in flights.js / militaryFlights.js, so Cesium
* DOWN-samples this larger, higher-precision source to the same on-screen
* footprint — crisp anti-aliased edges instead of an upscaled 32px bitmap. The
* on-screen size is unchanged and CLASS_SCALE_2D is untouched (no scale
* compensation needed: the billboard's explicit width/height, not the SVG's,
* sets the pixel size — the intrinsic SVG size only controls raster fidelity).
* on-screen size is unchanged (the billboard's explicit width/height, not the
* SVG's, sets the pixel size — the intrinsic SVG size only controls raster
* fidelity).
*
* All glyphs are nose-up (nose toward -Y at rotation 0; the screen-projected
* rotation pipeline in iconOrientation.js spins the whole glyph). Fill is white
@@ -23,12 +23,19 @@
* quadjet/glider use the "bold" chart-symbol redraw; light/fastjet keep the
* original drawings. Raster fidelity doubled (192px source, same 96 coords).
*
* The helicopter is a top-down body under a four-blade rotor drawn in three
* frames (`aircraftIcon('helicopter', px, frame)`, turned by
* `rotorFrames.js`). Two kinds are not aircraft: `vehicle`, one sprite for
* every airport vehicle, and `station`, a mast for ground stations, drawn
* upright.
*
* Silhouette language follows skylight's type-aware glyphs (MIT,
* https://github.com/cpaczek/skylight): slender fuselages, swept wings for
* jets, long high-aspect wings for the glider, straight wings + prop discs for
* props, a rotor disc + tail boom + tail-rotor for the helicopter, and a delta
* for the fast jet. Each class has a DISTINCT planform so it reads at ~20px by
* shape, not just by footprint size.
* shape alone: every glyph is fitted to the same extent, so none is bigger
* than another.
*/
const VIEW = 96;
@@ -130,23 +137,6 @@ const BODIES = {
L -3,-25 C -3,-29 -2.4,-33 0,-35 Z" fill="white" ${STROKE_BOLD}/>
<rect x="-10.5" y="32.5" width="21" height="5" rx="1.5" fill="white" ${STROKE_BOLD}/>`,
// ── Helicopter: a SOLID translucent main-rotor disc (survives downscale as an
// obvious circle, unlike a thin ring) with a bold two-blade cross, a
// teardrop cabin, a tail boom, and a tail rotor. Unmistakable "disc on top"
// silhouette that never reads as a fixed-wing.
helicopter: `
<circle cx="0" cy="-6" r="31" fill="white" fill-opacity="0.22"/>
<g transform="rotate(45 0 -6)">
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9"/>
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9" transform="rotate(90 0 -6)"/>
</g>
<path d="M0,-22 C 8,-20 10.5,-13 10.5,-6 C 10.5,2 7.5,7 0,8.5
C -7.5,7 -10.5,2 -10.5,-6 C -10.5,-13 -8,-20 0,-22 Z" fill="white" ${STROKE}/>
<path d="M-2.6,8 L 2.6,8 L 1.8,32 L -1.8,32 Z" fill="white" ${STROKE}/>
<path d="M-8,27 L 8,27 L 8,30.6 L -8,30.6 Z" fill="white"/>
<circle cx="5.6" cy="35" r="6" fill="white" fill-opacity="0.6"/>
<circle cx="5.6" cy="35" r="2.1" fill="white"/>`,
// ── Fast jet: sharp delta/cropped-delta with a pointed nose, LERX root
// blend, and twin tail fins. Aggressive, all-wing.
fastjet: `
@@ -160,8 +150,8 @@ const BODIES = {
L -3,31 L -8,34 L -8,30 L -6,16
L -27,26 L -27,20 L -5,-8
C -4.6,-16 -4,-24 -3.5,-30 Z" fill="white" ${STROKE}/>`,
// 2026-08-15 Hangar additions: two NEW classes shipped with the real-model
// fleet (CLASS_MODEL_REAL). Same contract as the set above: 96×96 nose-up,
// 2026-08-15 additions: two NEW classes (bizjet, uav). Same contract as
// the set above: 96×96 nose-up,
// white fill, hairline stroke, tint-safe.
// Business jet — slender fuselage, modest swept wing, aft engines, T-tail.
bizjet: `
@@ -236,6 +226,87 @@ const BODIES = {
L -1.6,30 L -13,36 L -13,32 L -2.1,24
L -2.3,0 L -43,-2.5 L -43,-7 L -2.4,-12
L -4.4,-30 C -4.6,-35 -3.6,-40 0,-40 Z" fill="white" ${STROKE}/>`,
// ── Airport vehicle (type ZVEH, emitter C1/C2): one service van seen from
// above, front up, for every kind (fire truck, tug, car, de-icer). A
// boxy body, a dark windscreen band and a roof light bar; the layer
// tints it amber so it reads apart from aircraft.
vehicle: `
<path d="M-12,-39 L 12,-39 L 15,-36 L 15,38 L 13,40 L -13,40 L -15,38
L -15,-36 Z" fill="white" ${STROKE}/>
<path d="M-18.5,-25 h4 v3 h-4 Z M14.5,-25 h4 v3 h-4 Z" fill="white" ${STROKE}/>
<path d="M-13,-32 L 13,-32 L 12,-21 L -12,-21 Z" fill="rgba(0,0,0,0.62)"/>
<rect x="-10" y="-13" width="20" height="5" rx="1.5" fill="rgba(0,0,0,0.45)"/>`,
// ── Ground station or obstacle (type GRND, emitter C3–C5): a radio mast
// with two pairs of signal arcs, drawn upright on screen, never turned.
station: `
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
fill="none" stroke="rgba(0,0,0,0.32)" stroke-width="5" stroke-linecap="round"/>
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
fill="none" stroke="white" stroke-width="3.4" stroke-linecap="round"/>
<circle cx="0" cy="-30" r="4.5" fill="white" ${STROKE}/>
<path d="M-2.5,-25 L 2.5,-25 L 7,34 L 13,34 L 13,38 L -13,38 L -13,34
L -7,34 Z" fill="white" ${STROKE}/>`,
};
/**
* The helicopter, seen from above: a cabin, tail boom and tail plane under a
* four-blade main rotor. The rotor turns in {@link ROTOR_FRAMES} frames 30°
* apart; four blades repeat every 90°, so the third frame steps back onto
* the first and the loop is seamless. The middle frame (blades as an X) is
* the still one.
*/
const HELI_ROTOR_CENTRE_Y = -11.2;
const HELI_DISC = `<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="32.8" fill="white" fill-opacity="0.22"/>`;
const HELI_BODY = `
<path d="M0,-33.4 L -2.3,-32.1 L -4.2,-28 L -4.3,-30.6 L -6.2,-30.6
L -6.2,0.2 L -4.3,0.2 L -4.2,-3.1 L -1.9,7.9 L -1.7,18.9
L -7.4,19.2 L -7.8,24 L -2.9,24.4 L -3.2,35.6 L -1.2,36
L 0,34.3 L 1.2,36 L 3.2,35.6 L 2.9,24.4 L 7.8,24 L 7.4,19.2
L 1.7,18.9 L 1.9,7.9 L 4.2,-3.1 L 4.3,0.2 L 6.2,0.2 L 6.2,-30.6
L 4.3,-30.6 L 4.2,-28 L 2.3,-32.1 Z" fill="white" ${STROKE}/>
<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="3.2" fill="white" ${STROKE}/>`;
/** Main-rotor blade angle of each frame, degrees clockwise. */
const ROTOR_ANGLES_DEG = [15, 45, 75];
/** How many rotor frames the helicopter turns through. */
export const ROTOR_FRAMES = ROTOR_ANGLES_DEG.length;
/** The frame a helicopter holds when its rotor does not turn. */
export const ROTOR_STILL_FRAME = 1;
/** One rotor frame: the disc, two crossed blades at `angle`, the body over them. */
function helicopterBody(frame) {
const angle = ROTOR_ANGLES_DEG[frame] ?? ROTOR_ANGLES_DEG[ROTOR_STILL_FRAME];
const blade = (deg) =>
`<rect x="-32.2" y="${HELI_ROTOR_CENTRE_Y - 2.2}" width="64.4" height="4.4" rx="2.2" fill="white" fill-opacity="0.92" stroke="rgba(0,0,0,0.25)" stroke-width="0.8" transform="rotate(${deg} 0 ${HELI_ROTOR_CENTRE_Y})"/>`;
return `${HELI_DISC}${blade(angle)}${blade(angle + 90)}${HELI_BODY}`;
}
/**
* Every sprite draws at one size. The bodies were drawn at different spans
* (a light aircraft's half-extent is 32.8 units, a quadjet's 47), so each is
* scaled until its farthest painted edge, stroke included, sits
* {@link GLYPH_HALF_EXTENT} units from the centre. Values are each body's
* measured half-extent; aircraftIcons.test.mjs re-measures the rasters.
*/
const GLYPH_HALF_EXTENT = 44;
const BODY_HALF_EXTENT = {
airliner: 42.7,
widebody: 45.7,
quadjet: 47.0,
turboprop: 40.7,
light: 32.8,
glider: 46.0,
fastjet: 44.7,
bizjet: 42.7,
uav: 43.7,
helicopter: 44.0,
vehicle: 40.7,
station: 47.1,
tr3b: 40.8,
tr3bHot: 42.3,
};
const _iconCache = new Map();
@@ -252,21 +323,39 @@ const _b64 = (s) =>
* NEAR the display size lets the browser's SVG AA do the work: crisp AND
* smooth. 64 covers the 40–58 px fleet band with ≤1.6× minification. */
const FLEET_RASTER_PX = 64;
/** Raster size of the default fleet glyph. */
export const FLEET_ICON_PX = FLEET_RASTER_PX;
/** Tracked raster: the tracked billboard is the one SUSTAINED large 2D glyph
* (close-zoom fleet flybys hand off to 3D models). Keep the 192 px texture so
* it stays crisp at its biggest on-screen sizes. */
const TRACKED_RASTER_PX = 192;
/** Data URI for a class silhouette (lazily built, cached per kind+size).
* Default size serves the fleet; pass `aircraftIcon(kind, TRACKED_ICON_PX)`
* (re-exported below) for the tracked billboard. */
/** Raster size of the tracked glyph and every glyph's near image. */
export const TRACKED_ICON_PX = TRACKED_RASTER_PX;
export function aircraftIcon(kind, px = FLEET_RASTER_PX) {
const k = BODIES[kind] ? kind : 'airliner';
const key = `${k}@${px}`;
/**
* Data URI for a class silhouette (lazily built, cached per kind, size and
* frame). The default size serves the fleet; pass
* `aircraftIcon(kind, TRACKED_ICON_PX)` for the near image.
* @param {string} kind A `classifyAircraft()` class, or a TR-3B kind.
* @param {number} [px] Raster size.
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
* (the still frame by default); other kinds have one image.
* @returns {string}
*/
export function aircraftIcon(kind, px = FLEET_RASTER_PX, frame) {
const heli = kind === 'helicopter';
const k = heli || BODIES[kind] ? kind : 'airliner';
const f = heli
? Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
? frame
: ROTOR_STILL_FRAME
: 0;
const key = `${k}@${px}#${f}`;
let uri = _iconCache.get(key);
if (!uri) {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${BODIES[k]}</g></svg>`;
const body = heli ? helicopterBody(f) : BODIES[k];
const fit = +(GLYPH_HALF_EXTENT / BODY_HALF_EXTENT[k]).toFixed(4);
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C}) scale(${fit})">${body}</g></svg>`;
uri = 'data:image/svg+xml;base64,' + _b64(svg);
_iconCache.set(key, uri);
}
+57
View File
@@ -0,0 +1,57 @@
// src/data/aircraftIcons.test.mjs
import { test } from 'node:test';
import assert from 'node:assert/strict';
import sharp from 'sharp';
import { aircraftIcon, ROTOR_FRAMES } from './aircraftIcons.js';
const KINDS = [
'airliner',
'widebody',
'quadjet',
'turboprop',
'light',
'glider',
'fastjet',
'bizjet',
'uav',
'helicopter',
'vehicle',
'station',
'tr3b',
'tr3bHot',
];
const PX = 480;
/** Farthest painted pixel from the centre, in the 96-unit glyph space. */
async function halfExtent(uri) {
const svg = Buffer.from(uri.split(',')[1], 'base64');
const { data, info } = await sharp(svg)
.ensureAlpha()
.raw()
.toBuffer({ resolveWithObject: true });
let half = 0;
const c = info.width / 2;
for (let y = 0; y < info.height; y++) {
for (let x = 0; x < info.width; x++) {
if (data[(y * info.width + x) * 4 + 3] <= 8) continue;
half = Math.max(half, c - x, x + 1 - c, c - y, y + 1 - c);
}
}
return (half * 96) / info.width;
}
test('every sprite fills the same extent, whatever its class', async () => {
const extents = {};
for (const kind of KINDS) {
extents[kind] = await halfExtent(aircraftIcon(kind, PX));
}
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
extents[`helicopter#${frame}`] = await halfExtent(
aircraftIcon('helicopter', PX, frame),
);
}
for (const [kind, half] of Object.entries(extents)) {
assert.ok(Math.abs(half - 44) <= 0.6, `${kind}: ${half.toFixed(2)}`);
}
});
File diff suppressed because it is too large. Load diff
+478
View File
@@ -0,0 +1,478 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createAircraftModels } from './aircraftModelLayer.js';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import * as flightsPolicy from '../layers/flights/policy.js';
// The flights layer's own model policy: its radii, ceiling and caps.
const POLICY = {
...flightsPolicy,
MODEL_MAX: 40,
MODEL_HEADING_OFFSET_DEG: 0,
};
/** The eye's height (m): 1 km above the contacts. */
const EYE_M = 11_000;
const SPEC = {
url: 'plane.glb',
scale: 1,
bellyM: 3,
nativeRadiusM: 20,
blendAmount: 0.9,
};
/**
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
* models layer over a fake draw port whose fleet set can be told to fail a
* write. The eye sits at `eyeM`, by default 1 km above them (`EYE_M`).
*/
function fleetFixture(positions, { eyeM = EYE_M } = {}) {
const base = fakeDrawPort();
const removes = [];
let failNextUpsert = false;
const draw = {
...base,
models(spec) {
const set = base.models(spec);
return {
...set,
get show() {
return set.show;
},
set show(value) {
set.show = value;
},
id: set.id,
upsert(items) {
if (failNextUpsert && spec.id.includes('-models:')) {
failNextUpsert = false;
throw new Error('simulated write failure');
}
return set.upsert(items);
},
remove(ids) {
removes.push([...ids]);
return set.remove(ids);
},
};
},
};
const eye = fromDegrees(-97.71, 30.21, eyeM);
const viewer = {};
bindRenderer(viewer, {
draw,
camera: {
pose: () => ({
position: eye,
direction: { x: 0, y: 0, z: -1 },
up: { x: 0, y: 1, z: 0 },
right: { x: 1, y: 0, z: 0 },
fovy: Math.PI / 3,
aspectRatio: 1,
height: eyeM,
}),
},
});
const shown = new Map([...positions.keys()].map((id) => [id, true]));
let alphaOf = 1;
let focusOf = 1;
const unseenIds = new Set();
const icons = {
show: true,
setId: 'flights-icons:1',
ids: () => [...positions.keys()],
has: (id) => positions.has(id),
position: (id) => positions.get(id),
course: () => 90,
alpha: () => alphaOf,
focus: () => focusOf,
setShown: (id, value) => shown.set(id, value),
unseen: (id) => unseenIds.has(id),
flush() {},
};
const state = {
_viewer: viewer,
_icons: icons,
_models: new Map(),
_modelSets: null,
_trackedIcao: null,
_trackedModel: null,
_models3dEnabled: true,
_models3dMode: 'proximity',
_cockpitContactMode: false,
_irBoost: false,
_lastFleetTickMs: 0,
_lastModelCapWarnMs: 0,
records: {
data: new Map(
[...positions.keys()].map((id) => [id, { klass: 'airliner' }]),
),
},
};
let now = 1_000_000;
let iconRecedeSyncs = 0;
const parts = {
icons: {
_displayMs: () => now,
_syncImageSwitch() {},
_replanExpired() {},
_focusIcons() {},
_occluder: () => null,
_aboveHorizon: () => true,
_syncRecede() {
iconRecedeSyncs += 1;
},
},
motion: { _displayTimeAt: () => null },
tracking: {
_refreshCockpitNearContacts() {},
_trackedModelRegimeActive: () => false,
},
};
const models = createAircraftModels({
state,
services: {
aircraftPresentation: { isTr3b: () => false },
camera: { trackedModelScaleForPixelCap: ({ baseScale }) => baseScale },
focus: { focusNowMs: () => now, getFocusTarget: () => null },
},
parts,
resolveAsset: (url) => url,
logLabel: 'Test',
setPrefix: 'flights',
policy: POLICY,
modelSpec: () => SPEC,
modelColor: () => ({ red: 1, green: 1, blue: 1, alpha: 1 }),
});
models._createModelSets(viewer);
const fleetId = models._modelSetIds()[0];
return {
models,
state,
draw: base,
fleet: () => base.set(fleetId),
fleetId,
removes,
shown,
failNextUpsert: () => (failNextUpsert = true),
/** How often the icons were told to recede by the tuning as it is now. */
iconRecedeSyncs: () => iconRecedeSyncs,
/** Mark a contact as not there yet at the time drawn, or there again. */
setUnseen(id, value) {
if (value) unseenIds.add(id);
else unseenIds.delete(id);
},
/** The icons' alpha and focus the fleet models take. */
look(alpha, focus) {
alphaOf = alpha;
focusOf = focus;
},
/** One fleet tick, past the tick interval. */
tick() {
now += 1000;
models._fleetTick();
},
};
}
// About 0.5 km apart, within 2 km of the eye.
const near = (k) => fromDegrees(-97.71 + k * 0.005, 30.21, 10_000);
/** A contact at the eye's height, `m` metres north of it. */
const north = (m) => fromDegrees(-97.71, 30.21 + m / 110_850, EYE_M);
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
test('the fleet tick hands contacts to ready models and back without a gap', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
]);
const f = fleetFixture(positions);
f.tick();
assert.deepEqual([...f.fleet().items.keys()].sort(), ['a1', 'a2']);
assert.equal(
f.shown.get('a1'),
true,
'icons carry contacts until models load',
);
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.shown.get('a1'), false, 'a ready, placed model takes over');
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(
f.shown.get('a2'),
true,
'a model still loading leaves its icon',
);
});
test('contacts leaving the model band are released in one write', () => {
const positions = new Map([
['a1', near(1)],
['a2', near(2)],
['a3', near(3)],
]);
const f = fleetFixture(positions);
f.tick();
for (const id of ['a1', 'a2', 'a3']) f.draw.ready(f.fleetId, id);
f.tick();
positions.set('a2', far(2));
positions.set('a3', far(3));
f.removes.length = 0;
f.tick();
assert.deepEqual(
f.removes,
[['a2', 'a3']],
'one remove for every evicted model',
);
assert.deepEqual([...f.fleet().items.keys()], ['a1']);
assert.equal(
f.shown.get('a2'),
true,
'a released model hands back to its icon',
);
assert.equal(f.shown.get('a3'), true);
});
test('a failed fleet write leaves the icons in charge and is sent again', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
f.tick();
f.draw.ready(f.fleetId, 'a1');
const realWarn = console.warn;
console.warn = () => {};
try {
f.failNextUpsert();
f.tick();
} finally {
console.warn = realWarn;
}
assert.equal(f.shown.get('a1'), true, 'the contact keeps its icon');
assert.equal(
f.fleet().items.get('a1').show,
false,
'the set still has the hidden model',
);
assert.equal(f.models._modelOwnsVisual('a1'), false);
f.tick();
assert.equal(
f.fleet().items.get('a1').show,
true,
'the next tick sends it again',
);
assert.equal(f.shown.get('a1'), false);
});
test('a fleet model whose load failed is loaded again after a wait, not before', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
const realNow = Date.now;
let clock = 50_000_000;
Date.now = () => clock;
try {
f.tick();
const writes = f.fleet().writes;
clock += 60_000;
f.tick();
assert.equal(
f.fleet().writes,
writes,
'a model still loading is not rewritten, however long it takes',
);
f.draw.loadFailed(f.fleetId, 'a1');
f.removes.length = 0;
clock += 4_999;
f.tick();
assert.deepEqual(f.removes, [], 'not before the wait');
assert.equal(f.shown.get('a1'), true, 'the icon carries the contact');
clock += 1;
f.tick();
assert.deepEqual(f.removes, [['a1']], 'removed once the wait is over');
assert.ok(f.fleet().items.has('a1'), 'and added again in the same tick');
assert.equal(f.state._models.get('a1').failedAt, 0);
assert.equal(f.state._models.get('a1').ready, false, 'a fresh load');
f.removes.length = 0;
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'tried again only after another failure');
// A renderer's own retry that loads before the layer's: nothing is due.
f.draw.loadFailed(f.fleetId, 'a1');
f.draw.ready(f.fleetId, 'a1');
clock += 60_000;
f.tick();
assert.deepEqual(f.removes, [], 'a model that loaded is not tried again');
assert.equal(
f.shown.get('a1'),
false,
'the model takes over once it loads',
);
} finally {
Date.now = realNow;
}
});
test('fleet model alpha is worked out once a fleet tick from the camera then, as base × max(floor, focus × haze); the IR boost draws full strength', async () => {
const {
aircraftTreatmentAlpha,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const position = near(1);
const f = fleetFixture(new Map([['a1', position]]));
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
const eye = fromDegrees(-97.71, 30.21, EYE_M);
const expected = (focusFactor) =>
aircraftTreatmentAlpha({
baseAlpha: 0.8,
focusFactor,
cameraDistanceM: Math.hypot(
eye.x - position.x,
eye.y - position.y,
eye.z - position.z,
),
cameraHeightM: EYE_M,
});
try {
// Recede from the eye on, so the haze is not 1 here.
setAircraftRecessionParams({ startLimbRatio: 0, alphaFloor: 0.05 });
f.look(0.8, 0.5);
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
const item = f.fleet().items.get('a1');
assert.equal(item.tint[3], expected(0.5), 'the tint carries it all');
assert.equal(item.focus ?? 1, 1, 'with no focus for the set to compose');
// A frame inside the fleet interval writes nothing, whatever changed.
f.look(0.8, 0.25);
f.models._fleetTick();
assert.equal(f.fleet().items.get('a1').tint[3], item.tint[3]);
f.tick();
assert.equal(
f.fleet().items.get('a1').tint[3],
expected(0.25),
'the next tick takes it',
);
} finally {
resetAircraftRecessionParams();
}
f.state._irBoost = true;
f.models._reloadModelsForIrBoost();
f.tick();
assert.equal(f.fleet().items.get('a1').tint[3], 1, 'boosted: full strength');
});
test('a tuning change reaches the icons on the next frame, icons shown or not', async () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.state._icons.show = false;
const before = f.iconRecedeSyncs();
f.models._fleetTick();
assert.ok(f.iconRecedeSyncs() > before, 'the icons are told');
});
test('a contact not there yet at the time drawn has its fleet model hidden, as one beyond the horizon', () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn while there');
f.setUnseen('a1', true);
f.tick();
assert.equal(f.fleet().items.get('a1').show, false, 'hidden while unseen');
f.setUnseen('a1', false);
f.tick();
f.tick();
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
});
test('aircraft draw as models only within 3 km of the camera, in either mode', () => {
for (const mode of ['proximity', 'all']) {
const positions = new Map([
['inside', north(2_900)],
['outside', north(3_100)],
]);
const f = fleetFixture(positions);
f.state._models3dMode = mode;
f.tick();
for (const id of positions.keys())
if (f.fleet().items.has(id)) f.draw.ready(f.fleetId, id);
f.tick();
assert.equal(f.shown.get('inside'), false, `${mode}: a model at 2.9 km`);
assert.equal(f.fleet().items.get('inside').show, true);
assert.equal(f.shown.get('outside'), true, `${mode}: an icon at 3.1 km`);
assert.equal(f.fleet().items.has('outside'), false);
}
});
test('a model is kept out to about 3.6 km, then its icon takes over', () => {
const positions = new Map([['a1', north(2_000)]]);
const f = fleetFixture(positions);
f.tick();
f.draw.ready(f.fleetId, 'a1');
f.tick();
assert.equal(f.shown.get('a1'), false, 'a model at 2 km');
positions.set('a1', north(3_500));
f.tick();
assert.equal(f.shown.get('a1'), false, 'kept at 3.5 km');
assert.equal(f.fleet().items.get('a1').show, true);
positions.set('a1', north(3_700));
f.tick();
assert.equal(f.shown.get('a1'), true, 'released at 3.7 km');
assert.equal(f.fleet().items.has('a1'), false);
positions.set('a1', north(3_300));
f.tick();
assert.equal(
f.fleet().items.has('a1'),
false,
'not taken again until it is back within 3 km',
);
});
test('a camera high above the ground still models an aircraft within 3 km of it', () => {
// A plane at 30 km with the camera 2 km above it: the altitude ceiling
// sits above every contact's height plus the keep radius.
const plane = fromDegrees(-97.71, 30.21, 30_000);
const f = fleetFixture(new Map([['high', plane]]), { eyeM: 32_000 });
f.tick();
f.draw.ready(f.fleetId, 'high');
f.tick();
assert.equal(f.shown.get('high'), false, 'its model draws it');
assert.equal(
POLICY.MODEL_ALT_CEIL_M,
POLICY.MODEL_HIGHEST_CONTACT_M + POLICY.MODEL_KEEP_M,
);
});
test('models are drawn at their true size, with no minimum pixel size', () => {
const f = fleetFixture(new Map([['a1', near(1)]]));
f.tick();
assert.equal(f.fleet().items.get('a1').minPixelSize ?? 0, 0);
});
test('the selected contact keeps a loaded, hidden fleet model that takes it back on deselect', () => {
const positions = new Map([['a1', near(1)]]);
const f = fleetFixture(positions);
// Selected while an icon: the fleet pass admits its model all the same.
f.state._trackedIcao = 'a1';
f.shown.set('a1', false); // selecting it hides its icon
f.tick();
assert.ok(f.fleet().items.has('a1'), 'admitted and loading while selected');
f.draw.ready(f.fleetId, 'a1');
positions.set('a1', near(2));
f.tick();
const item = f.fleet().items.get('a1');
assert.equal(item.show, false, 'never drawn while selected');
assert.deepEqual(
item.pos,
{ x: near(2).x, y: near(2).y, z: near(2).z },
'placed where its icon is',
);
assert.equal(f.shown.get('a1'), false, 'the icon stays hidden');
// Deselected: its model draws it in the same frame, its icon never shows.
f.state._trackedIcao = null;
f.models._handBackDeselected('a1');
assert.equal(f.fleet().items.get('a1').show, true);
assert.equal(f.shown.get('a1'), false);
});
+33 -5
View File
@@ -6,12 +6,40 @@
* the model and reads the result back from the GPU (`readPixels`) to light it,
* when the model is first placed and again when it moves more than 1 km, when
* the scene's atmosphere settings change, or every scene hour under sunlight
* lighting. Aircraft models take 94% of their surface from the class colour
* (`colorBlendAmount`), so that lighting contributes little; without it they
* are lit from Cesium's default spherical harmonics. Measured 2026-10-24
* (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest
* 14.3-14.8 -> 12.1-12.5 ms.
* lighting. Without it they are lit from Cesium's default spherical
* harmonics. Measured 2026-10-24 (Intel Arc, Google 3D, ~150 models in the
* scene): GPU per frame at rest 14.3-14.8 -> 12.1-12.5 ms.
*/
export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
enabled: false,
});
const HIGHLIGHT = Object.freeze({ mode: 'highlight' });
const FLAT = Object.freeze({ mode: 'mix', amount: 1 });
/**
* How much of an emergency colour a model takes over its paint. Multiplying
* by a saturated tint zeroes every channel the tint lacks: a cyan tint (no
* red) draws a red helicopter black and a white Cessna flat cyan. Mixed in at
* this share, the paint stays readable and the colour still marks the model.
*/
export const AIRCRAFT_MODEL_TINT_MIX = 0.3;
const TINTED = Object.freeze({ mode: 'mix', amount: AIRCRAFT_MODEL_TINT_MIX });
/**
* How an aircraft model's colour meets its mesh, as a draw item's
* `colorBlend`. White (no tint) multiplies (`highlight`), which draws the
* mesh's own colours as built. An emergency colour is mixed in at
* `AIRCRAFT_MODEL_TINT_MIX`, so it tints the mesh without hiding its paint.
* The IR boost draws the model flat white instead (`mix` at 1, unlit).
* @param {boolean} irBoost
* @param {ArrayLike<number>|null} [tint] The model's RGBA tint, 0..1; white
* or none draws the mesh's own colours.
* @returns {{mode: 'highlight'|'mix', amount?: number}}
*/
export function aircraftModelBlend(irBoost, tint = null) {
if (irBoost) return FLAT;
const white = !tint || (tint[0] >= 1 && tint[1] >= 1 && tint[2] >= 1);
return white ? HIGHLIGHT : TINTED;
}
+88 -24
View File
@@ -2,13 +2,16 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs';
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
import {
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
aircraftModelBlend,
} from './aircraftModelLighting.js';
import * as flightsPolicy from '../layers/flights/policy.js';
import * as militaryPolicy from '../layers/military/policy.js';
/**
* Every aircraft model drawn in the scene skips Cesium's dynamic environment
* map (a sky render and GPU readback per model). The preload calls only warm
* the glTF cache and are never added to the scene, so they are left out:
* drawn models are the calls that set a minimum pixel size.
* Every aircraft model drawn in the scene skips the renderer's dynamic
* environment map (a sky render and GPU readback per model).
*/
const SOURCES = [
{
@@ -19,13 +22,6 @@ const SOURCES = [
name: 'militaryFlights',
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
},
{
name: 'localAdsb',
source: readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
),
},
];
test('the shared option turns the dynamic environment map off', () => {
@@ -35,17 +31,85 @@ test('the shared option turns the dynamic environment map off', () => {
for (const { name, source } of SOURCES) {
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
const calls = [
...source.matchAll(/(?:fromGltfAsync|loadModel)\(\{([\s\S]*?)\}\)/g),
]
.map((match) => match[1])
.filter((options) => /\bminimumPixelSize:/.test(options));
assert.ok(calls.length >= 1, `expected drawn model calls in ${name}`);
for (const [index, options] of calls.entries())
assert.match(
options,
/\benvironmentMapOptions:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\b/,
`${name} model call ${index + 1} must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`,
);
// Its models are draw-port items; every item it builds (fleet and
// tracked) carries the shared option.
assert.doesNotMatch(source, /fromGltfAsync|loadModel\(/);
const items = [...source.matchAll(/\burl: record\.url,/g)];
assert.ok(items.length >= 1, `expected model items in ${name}`);
const flags = [
...source.matchAll(/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/g),
];
assert.equal(flags.length, items.length, `${name} model items must pass AIRCRAFT_ENVIRONMENT_MAP_OPTIONS`);
});
}
test('localAdsb: its draw-port models skip the dynamic environment map', () => {
const source = readFileSync(
new URL('../layers/localAdsb/models.js', import.meta.url),
'utf8',
);
assert.match(
source,
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
);
});
/**
* The colour a model draws in, as the renderer blends its tint over the
* shaded paint (`ModelItem.colorBlend`, Cesium's model colour stage): `mix`
* moves the paint toward the tint by `amount`; `highlight` multiplies.
*/
function blended(paint, tint, blend) {
if (blend.mode === 'mix')
return paint.map((c, i) => c + (tint[i] - c) * blend.amount);
if (blend.mode === 'highlight') return paint.map((c, i) => c * tint[i]);
return tint.slice(0, 3);
}
/** Paints the fleet models carry: a red helicopter, a white airliner, a dark blue tail. */
const PAINTS = {
red: [0.8, 0.05, 0.05],
white: [0.9, 0.9, 0.9],
blue: [0.05, 0.1, 0.5],
};
test('an untinted model draws its mesh in its own colours', () => {
for (const tint of [null, [1, 1, 1, 1], flightsPolicy.MODEL_WHITE]) {
const blend = aircraftModelBlend(false, tint);
for (const paint of Object.values(PAINTS))
assert.deepEqual(blended(paint, [1, 1, 1], blend), paint);
}
});
test('the emergency tints keep every paint, never black or one flat colour', () => {
const tints = {
emergency: flightsPolicy.EMERGENCY_TINT,
'military emergency': militaryPolicy.EMERGENCY_ICON_COLOR,
// Any saturated tint: one with no red once drew a red helicopter black.
cyan: [0, 1, 1, 1],
};
for (const [tintName, tint] of Object.entries(tints)) {
const blend = aircraftModelBlend(false, tint);
const drawn = {};
for (const [paintName, paint] of Object.entries(PAINTS)) {
const out = blended(paint, tint, blend);
drawn[paintName] = out;
// Multiplying by a tint with no red drew a red helicopter black.
paint.forEach((c, i) =>
assert.ok(
out[i] >= c * 0.6,
`${tintName} over ${paintName}: channel ${i} ${out[i].toFixed(2)} keeps most of ${c}`,
),
);
}
// Paints that differ still differ: the tint is not one flat colour.
const spread = (a, b) => Math.max(...a.map((c, i) => Math.abs(c - b[i])));
assert.ok(spread(drawn.red, drawn.white) > 0.4, `${tintName}: red and white apart`);
assert.ok(spread(drawn.blue, drawn.white) > 0.4, `${tintName}: blue and white apart`);
}
});
test('the IR boost draws every model flat white whatever its tint', () => {
for (const tint of [null, flightsPolicy.EMERGENCY_TINT])
assert.deepEqual(aircraftModelBlend(true, tint), { mode: 'mix', amount: 1 });
});
+336
View File
@@ -0,0 +1,336 @@
import { fromDegrees } from '../geo/ellipsoid.js';
import {
julianFromEpochMs,
julianLessThan,
julianLessThanOrEquals,
julianToEpochMs,
secondsDifference,
} from '../geo/julian.js';
import { clone, distance } from '../geo/vector.js';
import { curvePieceAt, fixCurveCached } from './fixCurve.js';
import { historyBracketIndex, historyUnseenAt } from './timelineHistory.js';
import {
COAST_MAX_SPEED_MPS,
courseBetweenCartesians,
speedRamp,
STALE_COAST_MAX_SEC,
staleCoastLimitSeconds,
staleHoldsForFix,
} from './motionModel.js';
/**
* Which record fields carry an aircraft layer's reported ground speed (m/s)
* and track (degrees clockwise from north).
* @typedef {{speed: string, track: string}} AircraftRecordFields
*/
/** A fix's own ground speed, else the record's; never over COAST_MAX_SPEED_MPS. */
export function fixSpeedMps(fix, info, fields) {
return Math.min(
Number.isFinite(fix.velocity)
? fix.velocity
: (info && info[fields.speed]) || 0,
COAST_MAX_SPEED_MPS,
);
}
/** A fix's own track, else the record's. */
export function fixTrackDeg(fix, info, fields) {
return Number.isFinite(fix.track)
? fix.track
: (info && info[fields.track]) || 0;
}
/**
* The instant `epochMs` as a Julian date (into `result` when given), for
* `aircraftMotionRegime`'s `renderTime`.
*/
export function julianAt(epochMs, result) {
return julianFromEpochMs(epochMs, result);
}
/** A history fix's time in epoch ms: its `epochMs`, else its `time`'s. */
export function fixEpochMs(fix) {
return Number.isFinite(fix.epochMs) ? fix.epochMs : julianToEpochMs(fix.time);
}
/** A feed fix's ECEF position, from its degrees and render altitude. */
export function fixPosition(lonDeg, latDeg, heightM) {
return fromDegrees(lonDeg, latDeg, heightM);
}
/** A copy of a fix position, for a trail that keeps it. */
export function copyPosition(position) {
return clone(position);
}
/**
* A position-history entry for a feed fix at `epochMs`, carrying the fix's
* own speed and track; it keeps a copy of `position`.
*/
export function historyFix(epochMs, position, velocity, track) {
return {
time: julianAt(epochMs),
epochMs,
position: clone(position),
velocity,
track,
};
}
/**
* Whether a history fix is a forward synthetic fix (a motion aid built from
* a repeated report's new speed or course, `synthesizeForwardKinematicsFix`)
* rather than a report.
*/
export const isSyntheticFix = (fix) => Number.isFinite(fix?.reportEpochMs);
/**
* Put a new report at the end of a contact's history: forward synthetic
* fixes after the previous report go (the report supersedes them), and past
* `limit` the oldest fixes go.
* @param {Array<object>} history Oldest first; mutated.
* @param {object} fix The report's history fix.
* @param {number} limit
*/
export function pushReport(history, fix, limit) {
while (history.length && isSyntheticFix(history[history.length - 1]))
history.pop();
history.push(fix);
while (history.length > limit) history.shift();
}
/** The newest report in a history (not a synthetic fix), or undefined. */
export function newestReport(history) {
for (let i = history.length - 1; i >= 0; i--)
if (!isSyntheticFix(history[i])) return history[i];
return undefined;
}
/** The curve a contact is drawn along between two history fixes, or null. */
export function historyCurve(a, b) {
return fixCurveCached(
a.position,
fixEpochMs(a),
a.track,
b.position,
fixEpochMs(b),
b.track,
);
}
/** A reusable result for `aircraftMotionRegime`. */
export function createMotionRegime() {
return {
kind: 'fix',
a: null,
b: null,
piece: null,
span: 0,
speed: 0,
trackFrom: 0,
trackTo: 0,
chordCourse: null,
blend: 0,
fix: null,
heading: 0,
turnRateDps: 0,
minDt: 0,
maxDt: 0,
unseen: false,
};
}
/**
* Which motion an aircraft's history gives at `renderTime` — the one choice
* the CPU dead reckoning and the icon planner (GPU segment) both draw from.
*
* - `between`: between the bracketing pair `a`→`b`, no extrapolation
* error and no snap-back. Along their curve (`data/fixCurve`) when the
* pair describes one: `piece` is the curve's piece at `renderTime`, a
* contract `arc` segment with its times. Otherwise straight from `a` to
* `b` (`piece` null), and the course of the DISPLAYED motion blends the
* time-interpolated reported track toward the chord by `blend`: the chord
* is only trustworthy when the segment covers real ground (at hover its
* direction is GPS jitter; on a slow tight turn it STEPS the whole
* per-segment turn at each boundary), and helicopters never use it
* (rotorcraft chords are noise-dominated at their typical speeds).
* - `fix`: extrapolate `fix` by the elapsed time clamped to [minDt, maxDt].
* Warm-up (renderTime predates ALL history: freshly seen or just tracked,
* before a poll interval of history exists) runs the OLDEST fix BACKWARD,
* preserving the behind-real-time invariant, so as history fills the icon
* glides FORWARD into interpolation with no freeze and no backward snap
* (holding the oldest fix froze the icon; extrapolating the newest to
* wall-clock made it jump back a poll interval when interpolation took
* over). Otherwise the newest fix coasts on its last speed and heading for
* five minutes past it, then stops (SIGNAL LOST). A contact last heard on
* or near the ground holds there instead (`staleHoldsForFix`, decided once
* per report), and a chain of synthetic fixes never coasts further than
* the real report they were built from would. Following the clock, a
* warm-up well before a contact's own first fix is `unseen`: it was not
* there yet, and is not drawn (`historyUnseenAt`).
*
* @param {Array<object>} history Non-empty, oldest first.
* @param {object|undefined} info The contact's record.
* @param {{dayNumber: number, secondsOfDay: number}} renderTime A Julian date (geo/julian).
* @param {AircraftRecordFields} fields
* @param {object} result From `createMotionRegime`; returned filled in.
* @param {{cachedGroundFloor?: (latDeg: number, lonDeg: number) => number|null}} [options]
* The ground under a report, where known, for the hold decision.
*/
export function aircraftMotionRegime(
history,
info,
renderTime,
fields,
result,
{ cachedGroundFloor } = {},
) {
// A synthetic fix a later report superseded is not on the path: the
// contact is drawn report to report, as its trail is.
let report = history.length - 1;
while (report >= 0 && isSyntheticFix(history[report])) report--;
// The pairs are read back from the fix after the first one at or after
// the render time (so a fix at exactly that time takes the later pair, as
// it always did; past any superseded synthetic fix there), found by
// halving, and stop at the first pair wholly before it: a contact
// following the clock keeps a long history.
let start = Math.min(
historyBracketIndex(history, renderTime) + 1,
history.length - 1,
);
while (start < report && isSyntheticFix(history[start])) start++;
let b = null;
for (let i = start; i >= 0; i--) {
const a = history[i];
if (i < report && isSyntheticFix(a)) continue;
const pairB = b;
b = a;
if (!pairB) continue;
if (julianLessThan(pairB.time, renderTime)) break;
if (
!julianLessThanOrEquals(a.time, renderTime) ||
!julianLessThanOrEquals(renderTime, pairB.time)
)
continue;
const span = secondsDifference(pairB.time, a.time);
const chordLenM = distance(a.position, pairB.position);
const speed =
span > 0 ? chordLenM / span : (info && info[fields.speed]) || 0;
const fallbackTrack = (info && info[fields.track]) || 0;
const trackFrom = Number.isFinite(a.track) ? a.track : fallbackTrack;
const blend = info && info.klass === 'helicopter' ? 0 : speedRamp(speed);
const curve = span > 0 ? historyCurve(a, pairB) : null;
result.kind = 'between';
result.a = a;
result.b = pairB;
result.piece = curve
? curvePieceAt(curve, julianToEpochMs(renderTime))
: null;
result.span = span;
result.speed = speed;
result.trackFrom = trackFrom;
result.trackTo = Number.isFinite(pairB.track) ? pairB.track : trackFrom;
result.chordCourse =
blend > 0 ? courseBetweenCartesians(a.position, pairB.position) : null;
result.blend = blend;
result.unseen = false;
return result;
}
const newest = history[history.length - 1];
const warming = julianLessThan(renderTime, history[0].time);
result.kind = 'fix';
result.piece = null;
result.fix = warming ? history[0] : newest;
result.unseen = warming && historyUnseenAt(history, renderTime);
result.speed = fixSpeedMps(result.fix, info, fields);
result.heading = fixTrackDeg(result.fix, info, fields);
// Past the newest report it flies straight on along its course: a turn
// rate averaged over earlier reports outlives the turn it measured, and
// coasting on it put contacts kilometres off a straight path.
result.turnRateDps = 0;
result.minDt = -60;
// A warm-up ends when real time reaches the oldest fix; a single fix keeps
// coasting forward on the same line.
result.maxDt =
warming && history.length > 1
? 0
: staleCoastSeconds(newest, info, cachedGroundFloor);
return result;
}
/**
* How long `newest` coasts at most: five minutes, less what a synthetic
* fix's chain already coasted since its real report (`reportEpochMs`); none
* for a report that holds (judged once per report, from its ground flag and
* the ground under it where `cachedGroundFloor` knows it).
* @param {object} newest
* @param {object|undefined} info
* @param {Function} [cachedGroundFloor]
* @returns {number}
*/
export function staleCoastSeconds(newest, info, cachedGroundFloor) {
const newestMs = fixEpochMs(newest);
const limitSec = staleCoastLimitSeconds({
fixEpochMs: newestMs,
lastContactEpochMs: info?.lastContactEpochMs,
// A plane that stops reporting keeps flying for five minutes, whatever
// its contact time, then stops dimmed as SIGNAL LOST. A missed update
// shows STALE throughout.
minimumSec: 300,
maximumSec: 300,
});
if (staleHoldsForFix(newest, { onGround: info?.onGround, cachedGroundFloor }))
return 0;
const alreadySec = Number.isFinite(newest.reportEpochMs)
? Math.max(0, (newestMs - newest.reportEpochMs) / 1000)
: 0;
return Math.max(0, Math.min(limitSec, STALE_COAST_MAX_SEC - alreadySec));
}
/** A raw position this far (m) off its own path, plus half its step, is a jump. */
const RAW_JUMP_SLACK_M = 5;
/**
* Whether a tracked aircraft's raw position jumped this frame: a new report
* moved its path. Judged against the path itself, where its last frame's
* step carries it, not against a reported speed (which can be stale or 0
* while the drawn motion, minutes behind the newest report, is fast). A
* frame with no step to go by (the first on a track, or the one after a
* jump) is never a jump.
* @param {{x: number, y: number, z: number}} raw This frame's raw position.
* @param {{x: number, y: number, z: number}} prevRaw Last frame's.
* @param {{x: number, y: number, z: number}} prevRawStep Last frame's step.
* @param {number} prevRawStepSec Last frame's length, s (0: no step).
* @param {number} dtSec This frame's length, s.
* @returns {boolean}
*/
export function rawPositionJumped(
raw,
prevRaw,
prevRawStep,
prevRawStepSec,
dtSec,
) {
if (!(prevRawStepSec > 0)) return false;
const k = dtSec / prevRawStepSec;
const dx = raw.x - (prevRaw.x + prevRawStep.x * k);
const dy = raw.y - (prevRaw.y + prevRawStep.y * k);
const dz = raw.z - (prevRaw.z + prevRawStep.z * k);
const stepM =
Math.hypot(prevRawStep.x, prevRawStep.y, prevRawStep.z) * Math.abs(k);
return Math.hypot(dx, dy, dz) > RAW_JUMP_SLACK_M + 0.5 * stepM;
}
/**
* How fast the drawn path moves (m/s), from its last raw step; `fallback`
* (a reported speed) with no step to go by.
* @param {{x: number, y: number, z: number}} step
* @param {number} stepSec
* @param {number} fallback
* @returns {number}
*/
export function rawStepSpeedMps(step, stepSec, fallback) {
if (!(stepSec > 0)) return fallback;
return Math.hypot(step.x, step.y, step.z) / stepSec;
}
+53 -143
View File
@@ -1,35 +1,33 @@
/**
* Limb-relative recession for distant aircraft billboards.
* Limb-relative recession for distant aircraft: the tuning the aircraft icon
* and model sets recede by (`aircraftRecedeSpec`), and the factors and alpha
* those sets draw with, for evidence and checks.
*
* This multiplies the billboard's ordinary scale, which Cesium then composes
* with the locked NearFarScalar. It never edits that scalar, culls a contact,
* or allows alpha to reach zero.
* It multiplies an icon's ordinary scale, which composes with its locked
* NearFarScalar. It never edits that scalar, culls a contact, or allows alpha
* to reach zero. The maths is the Cesium-free `render/recession.js`,
* which the sets drawing aircraft recede by (`SetSpec.recede`).
*/
import {
RECEDE_DEFAULTS,
limbDistanceM,
recedeFactors,
recedeFrame,
recedeParams,
recededAlpha,
} from '../render/recession.js';
export const DEFAULT_AIRCRAFT_RECESSION_PARAMS = Object.freeze({
startLimbRatio: 0.5,
scaleFloor: 0.45,
alphaFloor: 0.35,
combinedAlphaFloor: 0.2,
globeViewBlendStartM: 3_500_000,
globeViewBlendEndM: 4_500_000,
earthRadiusM: 6_378_137,
...RECEDE_DEFAULTS,
writeEpsilon: 0.005,
});
let _params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
const _scratchFactors = { scale: 1, alpha: 1, limbRatio: null };
const _treatmentResult = {
scale: 1,
alpha: 1,
scaleWrites: 0,
alphaWrites: 0,
factors: _scratchFactors,
};
function clamp(value, min, max) {
return Math.min(max, Math.max(min, value));
}
const _scratchFrame = { active: false, limbM: 1, strength: 0 };
// The tuning `_recede` was made from, and the set option made from it.
let _recedeFor = null;
let _recede = null;
function resolvedParams(overrides) {
if (!overrides || overrides === _params) return _params;
@@ -42,47 +40,12 @@ function aircraftRecessionFactorsResolved(
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;
return result;
}
const limbDistance = cameraLimbDistanceM(cameraHeightM, tuning.earthRadiusM);
if (!Number.isFinite(limbDistance) || limbDistance <= 0) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = null;
return result;
}
const limbRatio = cameraDistanceM / limbDistance;
if (limbRatio <= tuning.startLimbRatio) {
result.scale = 1;
result.alpha = 1;
result.limbRatio = limbRatio;
return result;
}
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 globeT = clamp(globeRawT, 0, 1);
const globeEase = globeT * globeT * (3 - 2 * globeT);
const strength = 1 - globeEase;
result.scale = 1 + (tuning.scaleFloor - 1) * limbEase * strength;
result.alpha = 1 + (tuning.alphaFloor - 1) * limbEase * strength;
result.limbRatio = limbRatio;
return result;
return recedeFactors(
cameraDistanceM,
recedeFrame(cameraHeightM, tuning, _scratchFrame),
tuning,
result,
);
}
/**
@@ -91,45 +54,34 @@ function aircraftRecessionFactorsResolved(
* @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS}
*/
export function setAircraftRecessionParams(patch = {}) {
const next = { ..._params };
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.combinedAlphaFloor)) {
next.combinedAlphaFloor = clamp(patch.combinedAlphaFloor, 0.05, 1);
}
if (Number.isFinite(patch.globeViewBlendStartM)) {
next.globeViewBlendStartM = Math.max(1, patch.globeViewBlendStartM);
}
if (Number.isFinite(patch.globeViewBlendEndM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewBlendEndM,
);
}
// Backward-compatible evidence override: the former hard threshold now
// names the identity end of the blend band.
if (Number.isFinite(patch.globeViewHeightM)) {
next.globeViewBlendEndM = Math.max(
next.globeViewBlendStartM + 1,
patch.globeViewHeightM,
);
}
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);
const given = Number.isFinite(patch.globeViewHeightM)
? { ...patch, globeViewBlendEndM: patch.globeViewHeightM }
: patch;
const next = {
...recedeParams(given, _params),
writeEpsilon: _params.writeEpsilon,
};
if (Number.isFinite(patch.writeEpsilon))
next.writeEpsilon = Math.max(0, patch.writeEpsilon);
_params = next;
return { ..._params };
}
/**
* The tuning as the `recede` of the sets that draw aircraft: the same
* object until the tuning changes.
* @returns {import('../render/contract/index').RecedeSpec}
*/
export function aircraftRecedeSpec() {
if (_recedeFor !== _params) {
_recedeFor = _params;
_recede = Object.freeze(recedeParams(_params));
}
return _recede;
}
/** @returns {typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS} Current tuning. */
export function getAircraftRecessionParams() {
return _params;
@@ -148,13 +100,7 @@ export function resetAircraftRecessionParams() {
* @param {number} [earthRadiusM]
* @returns {number}
*/
export function cameraLimbDistanceM(
cameraHeightM,
earthRadiusM = DEFAULT_AIRCRAFT_RECESSION_PARAMS.earthRadiusM,
) {
if (!Number.isFinite(cameraHeightM) || cameraHeightM <= 0) return Number.NaN;
return Math.sqrt(cameraHeightM * (2 * earthRadiusM + cameraHeightM));
}
export const cameraLimbDistanceM = limbDistanceM;
/**
* Pure recession factors for one aircraft.
@@ -178,28 +124,18 @@ export function aircraftRecessionFactors(
}
/**
* Production wire helper: compose base scale/alpha, focus emphasis, and limb
* recession into one deadband-gated billboard write site.
* The alpha an aircraft draws with: base × max(combined floor, focus × limb
* haze). Icon sets compose the same thing in their shader; models need it here.
* @param {object} input
* @param {object} input.billboard
* @param {number} input.baseScale
* @param {number} input.baseAlpha
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
* @param {number} input.focusFactor
* @param {number} input.cameraDistanceM
* @param {number} input.cameraHeightM
* @param {Partial<typeof DEFAULT_AIRCRAFT_RECESSION_PARAMS>} [input.params]
*
* IMPORTANT: the returned object (including `factors`) is a module-owned
* mutable singleton. Consume every needed property before the next call;
* never retain it as a snapshot.
* @returns {{scale:number,alpha:number,scaleWrites:number,alphaWrites:number,factors:object}}
* @returns {number}
*/
export function applyAircraftBillboardTreatment({
billboard,
baseScale,
export function aircraftTreatmentAlpha({
baseAlpha,
baseColor,
focusFactor,
cameraDistanceM,
cameraHeightM,
@@ -212,38 +148,12 @@ export function applyAircraftBillboardTreatment({
tuning,
_scratchFactors,
);
const scale = baseScale * factors.scale;
const composedTreatment = Math.max(
tuning.combinedAlphaFloor,
clamp(focusFactor, 0, 1) * factors.alpha,
);
const alpha = baseAlpha * composedTreatment;
let scaleWrites = 0;
let alphaWrites = 0;
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
) {
billboard.color = baseColor.withAlpha(alpha);
alphaWrites = 1;
}
_treatmentResult.scale = scale;
_treatmentResult.alpha = alpha;
_treatmentResult.scaleWrites = scaleWrites;
_treatmentResult.alphaWrites = alphaWrites;
return _treatmentResult;
return baseAlpha * recededAlpha(focusFactor, factors.alpha, tuning);
}
/**
* Apply layer-owned hue and composed aircraft alpha to an ambient glTF model without
* disturbing Cesium's existing MIX/colorBlendAmount presentation semantics.
* changing the model's colour blend mode or amount.
* @param {object} input
* @param {object} input.model
* @param {{withAlpha:(alpha:number)=>object}} input.baseColor
+24 -60
View File
@@ -3,9 +3,9 @@ import assert from 'node:assert/strict';
import {
DEFAULT_AIRCRAFT_RECESSION_PARAMS,
aircraftRecessionFactors,
applyAircraftBillboardTreatment,
applyAircraftModelTreatment,
cameraLimbDistanceM,
aircraftTreatmentAlpha,
} from './aircraftRecession.js';
const params = { ...DEFAULT_AIRCRAFT_RECESSION_PARAMS };
@@ -66,72 +66,15 @@ test('globe-view transition eases to identity without a threshold pop', () => {
assert.deepEqual(end, { scale: 1, alpha: 1, limbRatio: null });
});
test('aircraft billboard wire writes scale and alpha only for the far treatment', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const near = { scale: 1.2, color: { alpha: 0.8 } };
const nearResult = applyAircraftBillboardTreatment({
billboard: near,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 1,
cameraDistanceM: limb * 0.4,
cameraHeightM,
params,
});
assert.equal(nearResult.scaleWrites, 0);
assert.equal(nearResult.alphaWrites, 0);
const far = { scale: 1.2, color: { alpha: 0.8 } };
const farResult = applyAircraftBillboardTreatment({
billboard: far,
baseScale: 1.2,
baseAlpha: 0.8,
baseColor: color,
focusFactor: 0.5,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(farResult.scaleWrites, 1);
assert.equal(farResult.alphaWrites, 1);
assert.ok(Math.abs(far.scale - (1.2 * 0.45)) < 1e-12);
assert.ok(Math.abs(far.color.alpha - (0.8 * 0.20)) < 1e-12);
});
test('combined focus and haze product is clamped at the composed alpha floor', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 0.45, color: { alpha: 1 } };
const result = applyAircraftBillboardTreatment({
billboard,
baseScale: 1,
const alpha = aircraftTreatmentAlpha({
baseAlpha: 1,
baseColor: color,
focusFactor: 0.25,
cameraDistanceM: limb,
cameraHeightM,
params,
});
assert.equal(result.alpha, 0.20);
assert.equal(billboard.color.alpha, 0.20);
});
test('applyAircraftBillboardTreatment returns its documented module singleton', () => {
const color = { withAlpha: (alpha) => ({ alpha }) };
const billboard = { scale: 1, color: { alpha: 1 } };
const input = {
billboard,
baseAlpha: 1,
baseColor: color,
focusFactor: 1,
cameraDistanceM: 0,
cameraHeightM,
params,
};
const first = applyAircraftBillboardTreatment({ ...input, baseScale: 1 });
const second = applyAircraftBillboardTreatment({ ...input, baseScale: 0.5 });
assert.strictEqual(first, second);
assert.equal(first.scale, 0.5, 'the prior reference reflects the next call');
assert.equal(alpha, 0.2);
});
test('ambient model presentation receives composed alpha without changing blend semantics', () => {
@@ -154,3 +97,24 @@ test('model hue changes at constant alpha, then clears without redundant writes'
assert.equal(applyAircraftModelTreatment({model,baseColor:color(1,1,1),alpha:0.65}),1);
assert.equal(model.color.green,1);
});
test('the aircraft sets recede by the tuning: one object until it changes', async () => {
const {
aircraftRecedeSpec,
setAircraftRecessionParams,
resetAircraftRecessionParams,
} = await import('./aircraftRecession.js');
const { RECEDE_DEFAULTS } = await import('../render/recession.js');
resetAircraftRecessionParams();
const first = aircraftRecedeSpec();
assert.deepEqual(first, { ...RECEDE_DEFAULTS });
assert.equal(aircraftRecedeSpec(), first);
setAircraftRecessionParams({ scaleFloor: 0.6, globeViewHeightM: 4_000_000 });
const tuned = aircraftRecedeSpec();
assert.notEqual(tuned, first);
assert.equal(tuned.scaleFloor, 0.6);
assert.equal(tuned.globeViewBlendEndM, 4_000_000);
assert.equal('writeEpsilon' in tuned, false);
resetAircraftRecessionParams();
assert.deepEqual(aircraftRecedeSpec(), first);
});
+12
View File
@@ -6,6 +6,7 @@ import assert from 'node:assert/strict';
import { mapAnalystRecord } from './aisLiveVessels.js';
const FULL_RECORD = {
id: '353136000',
mmsi: '353136000',
name: 'EVER GIVEN',
lat: 29.55,
@@ -20,6 +21,7 @@ test('ais analyst record: full record maps every contract field', () => {
const r = mapAnalystRecord(FULL_RECORD);
assert.deepEqual(r, {
id: 'EVER GIVEN',
vesselId: '353136000',
mmsi: '353136000',
name: 'EVER GIVEN',
lat: 29.55,
@@ -38,6 +40,16 @@ test('ais analyst record: nameless vessel falls back to mmsi id', () => {
assert.equal(r.name, null);
});
test('ais analyst record: the key is the source id; the MMSI rides along when known', () => {
const shared = mapAnalystRecord({ ...FULL_RECORD, id: 'provider-a' });
assert.equal(shared.vesselId, 'provider-a');
assert.equal(shared.mmsi, '353136000');
const noMmsi = mapAnalystRecord({ ...FULL_RECORD, id: 'provider-b', mmsi: '', name: '' });
assert.equal(noMmsi.vesselId, 'provider-b');
assert.equal(noMmsi.mmsi, null);
assert.equal(noMmsi.id, 'provider-b', 'a nameless vessel with no MMSI is labelled by its id');
});
test('ais analyst record: empty strings and NaN become null, never undefined', () => {
const r = mapAnalystRecord({ mmsi: '', name: 'TUG', speed: NaN, type: '', destination: '' });
assert.equal(r.mmsi, null);
File diff suppressed because it is too large. Load diff
+152
View File
@@ -258,3 +258,155 @@ test('partial static data keeps newer live metadata ahead of the old static cach
assert.equal(rowFor(mmsi).type, '80');
assert.equal(rowFor(mmsi).destination, 'HAMBURG');
});
// A static report's dimensions are the antenna's distances to bow (A), stern
// (B), port (C) and starboard (D): length A+B, beam C+D. Zero is AIS's "not
// available", so a vessel reporting none has no size, not a size of zero.
test('a static report gives a vessel its hull length and beam', () => {
ingestAisStreamEnvelope(positionReport('636019825', { Sog: 14 }));
ingestAisStreamEnvelope({
MessageType: 'ShipStaticData',
Message: {
ShipStaticData: {
UserID: 636019825,
Name: 'EVER GIVEN',
Type: 70,
Dimension: { A: 330, B: 70, C: 30, D: 29 },
},
},
MetaData: { MMSI: '636019825' },
});
const row = rowFor('636019825');
assert.equal(row.length, 400);
assert.equal(row.beam, 59);
ingestAisStreamEnvelope(positionReport('636019826', { Sog: 3 }));
ingestAisStreamEnvelope({
MessageType: 'ShipStaticData',
Message: {
ShipStaticData: {
UserID: 636019826,
Type: 52,
Dimension: { A: 0, B: 0, C: 0, D: 0 },
},
},
MetaData: { MMSI: '636019826' },
});
assert.equal(rowFor('636019826').length, null);
assert.equal(rowFor('636019826').beam, null);
});
test('a Class B report carries its dimensions in part B', () => {
ingestAisStreamEnvelope(positionReport('244000777', { Sog: 6 }));
ingestAisStreamEnvelope({
MessageType: 'StaticDataReport',
Message: {
StaticDataReport: {
UserID: 244000777,
ReportB: {
Valid: true,
ShipType: 37,
Dimension: { A: 8, B: 4, C: 2, D: 2 },
},
},
},
MetaData: { MMSI: '244000777' },
});
const row = rowFor('244000777');
assert.equal(row.length, 12);
assert.equal(row.beam, 4);
});
test('an aid-to-navigation report is a row named by its kind of aid, not a ship type', () => {
assert.equal(
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: {
UserID: 993672001,
Type: 20,
Name: 'SF APPROACH N',
},
},
MetaData: {
MMSI: '993672001',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
}),
true,
);
const row = rowFor('993672001');
assert.equal(row.type, 'Cardinal Mark N');
assert.equal(row.name, 'SF APPROACH N');
assert.equal(row.speed, null);
});
test("an aid's name runs on into its name extension", () => {
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: {
UserID: 993672002,
Type: 13,
Name: 'SAN FRANCISCO MAIN S',
NameExtension: 'HIP CHANNEL 2',
},
},
MetaData: {
MMSI: '993672002',
ShipName: 'SAN FRANCISCO MAIN S',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
assert.equal(rowFor('993672002').name, 'SAN FRANCISCO MAIN SHIP CHANNEL 2');
});
test('a capped row request keeps every vessel ahead of aids to navigation', () => {
// The aid reports last, so it is the newest row.
ingestAisStreamEnvelope(positionReport('244060901', { Sog: 3 }));
ingestAisStreamEnvelope({
MessageType: 'AidsToNavigationReport',
Message: { AidsToNavigationReport: { UserID: 993672003, Type: 24 } },
MetaData: {
MMSI: '993672003',
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
const rows = aisStreamRows(50000);
const firstAid = rows.findIndex((row) => row.mmsi.startsWith('99'));
const lastVessel = rows.findLastIndex((row) => !row.mmsi.startsWith('99'));
assert.ok(firstAid > lastVessel, `${firstAid} > ${lastVessel}`);
const vesselCount =
rows.length - rows.filter((row) => row.mmsi.startsWith('99')).length;
assert.ok(
aisStreamRows(vesselCount).every((row) => !row.mmsi.startsWith('99')),
);
});
test('a virtual aid to navigation is marked virtual; a real one carries no flag', () => {
const aidReport = (mmsi, VirtualAtoN) => ({
MessageType: 'AidsToNavigationReport',
Message: {
AidsToNavigationReport: { UserID: Number(mmsi), Type: 28, VirtualAtoN },
},
MetaData: {
MMSI: mmsi,
latitude: 37.79,
longitude: -122.52,
time_utc: '2026-09-17 20:00:00.000000000 +0000 UTC',
},
});
ingestAisStreamEnvelope(aidReport('993672004', true));
ingestAisStreamEnvelope(aidReport('993672005', false));
assert.equal(rowFor('993672004').virtual, true);
assert.equal('virtual' in rowFor('993672005'), false);
// A later real report of the same aid drops the flag.
ingestAisStreamEnvelope(aidReport('993672004', false));
assert.equal('virtual' in rowFor('993672004'), false);
});
+152 -123
View File
@@ -3,6 +3,11 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import alprCamerasLayer, {
createAlprCamerasLayer,
configureAlprSource,
@@ -31,6 +36,8 @@ import {
isAlprSurveillanceType,
normalizeAlprNode,
} from './alprCameras.js';
import { readEntityRecord } from './entityRecords.js';
import { alprMarkers } from '../layers/alpr/markerState.js';
test('normalizeAlprNode: maps a full OSM node to a plain record', () => {
const record = normalizeAlprNode({
@@ -308,7 +315,7 @@ function cameraHarness(layer = alprCamerasLayer) {
},
});
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let source, click, picked;
let click, picked;
const credits = new Set();
const viewer = {
creditDisplay: {
@@ -333,20 +340,27 @@ function cameraHarness(layer = alprCamerasLayer) {
postRender: new Cesium.Event(),
pick: () => picked,
},
dataSources: {
add: (value) => {
source = value;
},
remove() {},
},
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
};
const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, ports);
// The renderer's camera port relays moveEnd; the layer's own come on top.
const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners;
const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (
fn,
type,
modifier,
) {
if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) click = fn;
// The unmodified click: the input port binds one per modifier.
if (
type === Cesium.ScreenSpaceEventType.LEFT_CLICK &&
modifier === undefined
)
click = fn;
return setInput.call(this, fn, type, modifier);
};
try {
@@ -355,13 +369,22 @@ function cameraHarness(layer = alprCamerasLayer) {
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput;
}
layer.enable();
const icons = () => {
const set = [...ports.draw.sets.values()].find(
(candidate) => candidate.kind === 'icons' && !candidate.disposed,
);
return set && { ...set, id: set.spec.id };
};
const marker = (id) =>
icons()?.items.has(id)
? getContextStore().entities.get(id)?.entity
: undefined;
return {
viewer,
ports,
portMoveEndListeners,
requests,
credits,
get source() {
return source;
},
setFetch(fn) {
response = fn;
},
@@ -374,9 +397,16 @@ function cameraHarness(layer = alprCamerasLayer) {
advance(ms) {
now += ms;
},
/** The layer's icon set, as the fake draw port holds it. */
icons,
/** The icon drawn for a camera, or undefined. */
icon: (id) => icons()?.items.get(id),
/** The drawn markers' carriers (their context entities), in draw order. */
markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)),
marker,
click(id) {
const entity = typeof id === 'string' ? source.entities.getById(id) : id;
picked = entity ? { id: entity } : undefined;
const item = typeof id === 'string' ? icons()?.items.get(id) : null;
picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
click({ position: new Cesium.Cartesian2() });
},
restore() {
@@ -440,28 +470,28 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
]),
);
await alprCamerasLayer.update();
const entities = h.source.entities.values;
const entities = h.markers();
assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual(
entities.map((entity) => entity.gevLabelModel.title),
entities.map((entity) => readEntityRecord(entity)?.labelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
);
assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size,
new Set(entities.map((entity) => h.icon(entity.id).image)).size,
1,
);
assert.deepEqual(entities[0].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [
'OSM MAPPED',
'FLOCK SAFETY · CITY POLICE · FIXED',
'PUBLIC MAP DATA',
]);
assert.deepEqual(entities[1].gevLabelModel.details, [
assert.deepEqual(readEntityRecord(entities[1])?.labelModel.details, [
'OSM MAPPED',
'MOTOROLA SOLUTIONS',
'PUBLIC MAP DATA',
]);
assert.deepEqual(
entities[2].gevLabelModel.details,
readEntityRecord(entities[2])?.labelModel.details,
['OSM MAPPED', 'PUBLIC MAP DATA'],
'unknown metadata is not guessed, but the source is always named',
);
@@ -486,7 +516,7 @@ test('the camera label stays English data in a translated interface', async () =
]),
);
await alprCamerasLayer.update();
h.click(h.source.entities.values[0].id);
h.click(h.markers()[0].id);
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
assert.equal(
shownEntityLabel(getSelectedEntityContext().label),
@@ -523,10 +553,7 @@ test('clicking the selected camera or empty map deselects, including after refre
h.expire();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
}
} finally {
h.restore();
@@ -582,10 +609,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n
alprCamerasLayer.enable();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.icon('alpr:42').size[0], 38);
} finally {
h.restore();
}
@@ -674,7 +698,7 @@ test('duplicate nodes render once with a count that agrees with the entity set',
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'ready');
assert.equal(alprCamerasLayer.getStats().count, 1);
assert.equal(h.source.entities.values.length, 1);
assert.equal(h.icons().items.size, 1);
} finally {
h.restore();
}
@@ -690,7 +714,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(alprCamerasLayer.getStats().count, 0);
assert.equal(getSelectedEntityContext(), null);
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
assert.equal(h.requests.length, 1);
} finally {
h.restore();
@@ -750,7 +774,7 @@ test('nearby camera moves reuse the snapped query but count and register only in
await alprCamerasLayer.update();
assert.equal(h.requests.length, 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']);
@@ -797,9 +821,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di
try {
let samples = 0;
h.viewer.scene.sampleHeightSupported = true;
h.viewer.scene.sampleHeight = (point, excluded) => {
h.viewer.scene.sampleHeight = () => {
samples += 1;
assert.equal(excluded[0].id, 'alpr:42');
return 187;
};
h.setFetch(async () =>
@@ -811,9 +834,9 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian(
entity.gevDisplayPosition(),
readEntityRecord(entity)?.displayPosition(),
);
assert.ok(Math.abs(anchor.height - 187) < 0.001);
assert.ok(
@@ -821,7 +844,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
for (let i = 0; i < 60; i++) {
h.viewer.scene.postRender.raiseEvent();
entity.gevDisplayPosition();
readEntityRecord(entity)?.displayPosition();
}
assert.equal(samples, 1, 'no per-frame raycasts');
h.advance(1000);
@@ -859,6 +882,7 @@ test('a late network failure after disable cannot resurrect retries or an error
});
test('two factories keep their requests, records and destruction independent', async () => {
const carriers = new Map();
const services = {
render: { governorRequestRender() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
@@ -872,7 +896,9 @@ test('two factories keep their requests, records and destruction independent', a
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -918,14 +944,17 @@ test('two factories keep their requests, records and destruction independent', a
await pending;
assert.equal(first.getStats().count, 0);
assert.equal(second.getStats().count, 1);
assert.equal(b.source.entities.values[0].id, 'directory:99');
assert.deepEqual([...b.icons().items.keys()], ['directory:99']);
assert.equal(second.source, 'Test camera directory');
assert.ok(
b.source.entities.values[0].gevLabelModel.details.includes(
'Source: Test directory',
),
readEntityRecord(
carriers.get('directory:99'),
)?.labelModel.details.includes('Source: Test directory'),
);
assert.equal(
a.viewer.camera.moveEnd.numberOfListeners,
a.portMoveEndListeners,
);
assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.viewer.scene.postRender.numberOfListeners, 0);
} finally {
b.restore();
@@ -937,6 +966,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
// Ground clamping re-samples every marker whenever a photoreal tile streams
// in; a whole-city view (about 1,000 cameras) stuttered while zooming.
const floors = new Map([['30.2672', 150]]);
const carriers = new Map();
let resolveCalls = 0;
let releaseResolve;
const services = {
@@ -957,7 +987,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
getSelectedEntityContext() {
return null;
},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -978,38 +1010,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
const h = cameraHarness(layer);
try {
await layer.update();
const known = h.source.entities.getById('directory:1');
const unknown = h.source.entities.getById('directory:2');
assert.equal(
known.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
const known = h.icon('directory:1');
const unknown = () => h.icon('directory:2');
const unknownCarrier = carriers.get('directory:2');
assert.equal(known.height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(known.position.getValue()).height -
151.5,
) < 0.01,
);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) <
0.01,
);
assert.equal(unknown().height, 'clampGround');
assert.equal(resolveCalls, 1);
const writes = h.icons().writes;
releaseResolve();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.equal(unknown().height, 'absolute');
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height -
161.5,
Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5,
) < 0.01,
);
assert.equal(h.icons().writes, writes + 1, 'one write for the move');
assert.equal(
h.source.entities.getById('directory:2'),
unknown,
carriers.get('directory:2'),
unknownCarrier,
'placed in place, not rebuilt',
);
} finally {
@@ -1061,23 +1084,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const position = entity.position,
line = entity.polyline;
const entity = h.marker('alpr:42');
const icon = h.icon('alpr:42');
// Ground-clamped native wedges cost ~40 ms per frame for a downtown view;
// bearings are painted by the overlay for the nearest cameras instead.
assert.equal(line, undefined);
assert.equal(entity.polygon, undefined);
assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry');
let selections = 0,
clears = 0,
collectionChanges = 0;
clears = 0;
window.addEventListener('gev:entity-selected', () => selections++);
window.addEventListener('gev:entity-selection-cleared', () => clears++);
h.source.entities.collectionChanged.addEventListener(
(_collection, added, removed) => {
collectionChanges += added.length + removed.length;
},
);
const writes = h.icons().writes;
h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 });
await alprCamerasLayer.update();
h.expire();
@@ -1093,30 +1109,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
]),
);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(entity.position, position);
assert.equal(entity.polyline, line);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again');
assert.equal(
getSelectedEntityContext().properties.operator,
'Updated directory',
);
assert.equal(selections, 0);
assert.equal(clears, 0);
assert.equal(collectionChanges, 0);
assert.equal(h.icons().writes, writes, 'no icon added or removed');
assert.equal(h.requests.length, 2, 'only expiry needs another request');
h.expire();
h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })]));
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(
entity.polyline,
undefined,
'removed direction must not persist',
);
assert.equal(h.marker('alpr:42'), entity);
assert.ok(
Cesium.Cartesian3.equals(
entity.position.getValue(),
Cesium.Cartesian3.equalsEpsilon(
h.icon('alpr:42').pos,
Cesium.Cartesian3.fromDegrees(-97.742, 30.2672),
0,
1e-6,
),
);
} finally {
@@ -1156,7 +1168,7 @@ test('moves inside a pending query do not restart it; moving to another city can
resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })]));
await second;
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
@@ -1174,12 +1186,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200);
try {
await alprCamerasLayer.update();
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
h.click('alpr:42');
for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) {
h.setBox(box);
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(getSelectedEntityContext().id, 'alpr:42');
assert.equal(h.requests.length, 1);
}
@@ -1190,7 +1202,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
camera.pickEllipsoid = () => undefined;
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
@@ -1235,14 +1247,14 @@ test('nearby count and discovery control frame a real loaded camera without fetc
);
assert.equal(flights[0].options.offset.range, 800);
assert.equal(h.requests.length, 1);
h.viewer.trackedEntity = {};
followEntity(h.viewer, {});
assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true);
assert.equal(
controls.chips[0].onClick(),
false,
'a stale button cannot steal the follow camera',
);
h.viewer.trackedEntity = undefined;
followEntity(h.viewer, null);
alprCamerasLayer.disable();
assert.equal(alprCamerasLayer.getStats().countLabel, '');
assert.equal(controls.chips[0].onClick(), false);
@@ -1385,7 +1397,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an
requests[1].release();
await new Promise((done) => setTimeout(done, 0));
assert.equal(requests.length, 2, 'queued final cells are discarded');
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.icons().items.size, 0);
layer.enable();
await layer.update();
assert.equal(
@@ -1404,10 +1416,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an
}
});
test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => {
test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => {
let floor = 180;
let listener;
let removed = 0;
const carriers = new Map();
const records = Array.from({ length: 70 }, (_, i) => ({
id: `surface:${i}`,
latitude: 30.2672 + i * 0.00001,
@@ -1433,7 +1446,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
context: {
clearSelectedEntityContextForLayer() {},
getSelectedEntityContext() {},
registerEntityContext() {},
registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
@@ -1442,40 +1457,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
const h = cameraHarness(layer);
try {
await layer.update();
const entities = [...h.source.entities.values];
const entities = [...carriers.values()];
// One marker under a canvas badge: its icon is the faint pick target.
const saved = entities[1];
saved.gevAlprNativeAppearance = {
position: saved.position,
heightReference: saved.billboard.heightReference,
};
saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190);
saved.gevAlprPickPosition = saved.position;
Object.assign(alprMarkers.write(saved), {
canvasOwned: true,
canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190),
});
for (const next of [150, 120, null, 180]) {
floor = next;
// Includes a provider switch with the same globe.show value.
h.viewer.scene.globe.show = next !== 180;
listener({ detail: { status: 'ready' } });
for (const entity of entities) {
assert.equal(h.source.entities.getById(entity.id), entity);
const icon = h.icon(entity.id);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(entity.position.getValue())
.height - (next == null ? 0 : next + 1.5),
Cesium.Cartographic.fromCartesian(icon.pos).height -
(next == null ? 0 : next + 1.5),
) < 0.01,
`${entity.id} refreshes at ${next}`,
);
assert.equal(
entity.billboard.heightReference.getValue(),
next == null
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
);
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(icon.height, next == null ? 'clampGround' : 'absolute');
assert.equal(icon.color, undefined, 'drawn as a badge');
assert.equal(alprMarkers.read(entity)?.canvasPosition, null);
}
assert.equal(
saved.gevAlprNativeAppearance,
null,
'saved appearance restores at the new floor',
alprMarkers.read(saved)?.canvasOwned,
false,
'the badge comes back at the new floor',
);
}
} finally {
@@ -1488,7 +1496,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const h = cameraHarness();
try {
await alprCamerasLayer.update();
const previous = h.source.entities.getById('alpr:42');
const previous = h.marker('alpr:42');
const revision = alprCamerasLayer.getStats().renderRevision;
let release;
h.setFetch(
@@ -1501,7 +1509,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const pending = alprCamerasLayer.update();
await alprCamerasLayer.update();
assert.equal(
h.source.entities.getById('alpr:42'),
h.marker('alpr:42'),
previous,
'do not show an intermediate filtered snapshot while the new query prepares',
);
@@ -1511,10 +1519,31 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
await pending;
assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
h.markers().map((e) => e.id),
['alpr:43'],
);
} finally {
h.restore();
}
});
test('ALPR display tags collapse controls and cap final text without erasing Unicode', () => {
const record = normalizeAlprNode({
type: 'node',
id: 1,
lat: 30,
lon: -97,
tags: {
'surveillance:type': 'ALPR',
operator: ' Şehir\n\u0000 PD ',
manufacturer: '😀'.repeat(200),
'camera:type': null,
'surveillance:zone': '\t traffic zone ',
},
});
assert.equal(record.operator, 'Şehir PD');
assert.equal(record.manufacturer.length, 180);
assert.equal(record.manufacturer, '😀'.repeat(90));
assert.equal(record.cameraType, null);
assert.equal(record.zone, 'traffic zone');
});
+26 -17
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium';
import {
canvasOf,
findCamera,
findFrame,
findQuery,
} from '../render/rendererOf.js';
import { dot, sub } from '../geo/vector.js';
import { t, msg, onLocaleChange } from '../i18n/index.js';
const YOUTUBE_HOSTS = new Set([
@@ -538,23 +544,22 @@ function ensureProviderConnections(documentRef, provider) {
}
}
/**
* Where an anchor (ECEF) is in the card root, through the renderer's camera
* and query ports; null behind the eye, off the root, or with no renderer.
*/
function anchorOnScreen(viewer, anchor, root) {
if (!viewer?.scene || !anchor || !root) return null;
const camera = viewer.camera;
if (camera?.positionWC && camera?.directionWC) {
const delta = Cesium.Cartesian3.subtract(
anchor,
camera.positionWC,
new Cesium.Cartesian3(),
);
if (Cesium.Cartesian3.dot(delta, camera.directionWC) <= 0) return null;
}
const pixel = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
anchor,
);
if (!anchor || !root) return null;
const camera = findCamera(viewer);
const query = findQuery(viewer);
if (!camera || !query) return null;
const pose = camera.pose();
if (dot(sub(anchor, pose.position), pose.direction) <= 0) return null;
const pixel = query.project(anchor);
if (!pixel) return null;
const canvasBounds = viewer.canvas?.getBoundingClientRect?.();
// The renderer's canvas; a viewer with no renderer bound, its own.
const canvas = canvasOf(viewer);
const canvasBounds = canvas?.getBoundingClientRect?.();
const rootBounds = root.getBoundingClientRect?.();
if (!canvasBounds || !rootBounds) return null;
const x = pixel.x + canvasBounds.left - rootBounds.left;
@@ -636,6 +641,8 @@ export function placeCard(card, leader, anchor) {
function createRoot(documentRef, viewer) {
const root = documentRef.createElement('div');
root.id = 'bhote-koshi-embedded-media-root';
// Drawn over the globe for the scene: Stories keeps it while one plays.
root.setAttribute('data-globe-overlay', '');
root.setAttribute('aria-live', 'polite');
(viewer?.container || documentRef.body)?.append(root);
return root;
@@ -865,7 +872,7 @@ export function createBhoteKoshiEmbeddedMedia({
}
};
const removePostRender =
viewer.scene?.postRender?.addEventListener?.(position);
findFrame(viewer)?.on('postRender', () => position()) ?? null;
function hide({ immediate = false, preserveWarm = false } = {}) {
if (!preserveWarm) clearWarm();
@@ -1115,6 +1122,8 @@ export function createBhoteKoshiEmbeddedMedia({
footer.append(title, status, link);
const body = documentRef.createElement('div');
body.className = 'bhote-embedded-callout-body';
// The card takes taps (its container and leader do not); Stories keeps that.
body.setAttribute('data-overlay-input', '');
body.append(player, footer);
card.append(leader, body);
root.append(card);
+53
View File
@@ -10,6 +10,7 @@ import {
publicEmbeddedMediaUrl,
resolveEmbeddedMediaSource,
} from './bhoteKoshiEmbeddedMedia.js';
import { bindRenderer } from '../render/rendererOf.js';
test('Pinokio fallback never creates provider DOM or loads SDKs', async () => {
const unexpected = () => { throw new Error('Provider resource allocated in Pinokio'); };
@@ -417,3 +418,55 @@ test('a media card stays between the panels when right-to-left swaps their sides
assert.ok(left >= 340 + 18, `card at ${left}px lands on the context rail`);
assert.ok(left + 392 <= 1040 - 18, `card at ${left}px lands on the scene panel`);
});
test('a shown card follows its anchor through the renderer ports', () => {
class Element extends EventTarget {
constructor(tag) {
super(); this.tag = tag; this.children = []; this.dataset = {}; this.style = {};
this.classList = { add() {}, remove() {}, contains() { return false; } };
}
setAttribute() {}
removeAttribute() {}
querySelector() { return null; }
getBoundingClientRect() { return { left: 0, top: 0, right: 1000, bottom: 800, width: 1000, height: 800 }; }
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 listeners = new Set();
const viewer = { canvas: { getBoundingClientRect: () => ({ left: 500, top: 500 }) } };
let pose = { position: { x: 0, y: 0, z: 0 }, direction: { x: 1, y: 0, z: 0 } };
const projected = [];
// The renderer's canvas, not the viewer's, places the card.
const unbind = bindRenderer(viewer, {
canvas: { getBoundingClientRect: () => ({ left: 10, top: 5 }) },
camera: { pose: () => pose },
query: { project: (p) => { projected.push(p); return { x: 300, y: 200 }; } },
frame: {
on(phase, cb) {
const entry = [phase, cb];
listeners.add(entry);
return () => listeners.delete(entry);
},
},
});
const media = createBhoteKoshiEmbeddedMedia({ viewer, documentRef, globalRef: {} });
assert.deepEqual([...listeners].map(([phase]) => phase), ['postRender']);
const anchor = { x: 10, y: 0, z: 0 };
assert.equal(media.show({ observation: { title: 'Clip', media: { sourceUrl: 'https://youtu.be/DbqRexFxv3k' } }, anchor }), true);
const card = documentRef.body.children[0].children.find((node) => node.tag === 'section');
assert.equal(card.hidden, false);
assert.equal(projected.at(-1), anchor);
assert.equal(card.style.left, `${300 + 10 + 42}px`);
// Behind the eye: hidden on the next drawn frame.
pose = { ...pose, direction: { x: -1, y: 0, z: 0 } };
for (const [, cb] of listeners) cb();
assert.equal(card.hidden, true);
media.destroy();
assert.equal(listeners.size, 0);
unbind();
});
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+333 -291
View File
@@ -1,9 +1,13 @@
import * as Cesium from 'cesium';
import {
clearOverlaySource,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { governorRequestRender } from '../renderGovernor.js';
import { drawOf, findCamera } from '../render/rendererOf.js';
import { hexColor } from '../render/color.js';
import { fromDegrees } from '../geo/ellipsoid.js';
import { toRadians } from '../geo/vector.js';
import { lengthFraction } from '../geo/polyline.js';
import {
BHOTE_KOSHI_LOCATOR_CREDIT,
registerDynamicCredit,
@@ -144,10 +148,11 @@ const NEARBY_CITIES = Object.freeze([
placement: 'right-lower',
}),
]);
const BORDER_COLOR = Cesium.Color.fromCssColorString('#20e7f2');
const BORDER_ACCENT = '#20e7f2';
const INCIDENT_ACCENT = '#ffad55';
const INCIDENT_COLOR = Cesium.Color.fromCssColorString(INCIDENT_ACCENT);
// Each layer's draw sets have ids of their own.
let layerSerial = 0;
const DEFAULT_OVERLAY_HOST = Object.freeze({
setEntries: setOverlayEntries,
@@ -194,10 +199,6 @@ function presentationUsesBoundary(value) {
);
}
function presentationAnimatesBoundary(value) {
return value === BHOTE_KOSHI_REGIONAL_PRESENTATION;
}
function smoothstep(from, to, value) {
if (to <= from) return value >= to ? 1 : 0;
const amount = Math.max(0, Math.min(1, (value - from) / (to - from)));
@@ -219,26 +220,21 @@ export function anchoredCalloutPresentation(elapsedMs) {
};
}
/** Return the progressive prefix used by the animated Nepal border. */
export function revealPolylinePositions(positions, progress) {
if (!Array.isArray(positions) || positions.length < 2) return [];
/**
* How much of a line's length is drawn when it is revealed vertex by
* vertex: `progress` of its vertices (the head between two of them), as a
* fraction of its length, for the draw port's `revealFraction`.
* @param {Array<{x: number, y: number, z: number}>} positions
* @param {number} progress 0..1
*/
export function revealLengthFraction(positions, progress) {
if (!Array.isArray(positions) || positions.length < 2) return 0;
const clamped = Math.max(0, Math.min(1, Number(progress) || 0));
if (clamped >= 1) return positions;
if (clamped >= 1) return 1;
if (clamped <= 0) return 0;
const scaled = clamped * (positions.length - 1);
const completed = Math.floor(scaled);
const revealed = positions.slice(0, completed + 1);
const next = Math.min(completed + 1, positions.length - 1);
if (next > completed) {
revealed.push(
Cesium.Cartesian3.lerp(
positions[completed],
positions[next],
scaled - completed,
new Cesium.Cartesian3(),
),
);
}
return revealed.length >= 2 ? revealed : [positions[0], positions[0]];
const index = Math.floor(scaled);
return lengthFraction(positions, index, scaled - index);
}
/** Close a region ring without duplicating an already-closed final vertex. */
@@ -285,14 +281,27 @@ export function createBhoteKoshiLocatorLayer({
cancelDelay = (handle) => clearTimeout(handle),
} = {}) {
let _viewer = null;
let _dataSource = null;
const _serial = ++layerSerial;
// Whether the layer draws: from enable until it is let go.
let _drawing = false;
let _sets = null;
// What the presentation draws, each item worked out for the time now:
// pulsing halos, lines revealed as they grow, and the country fill, drawn
// once it is due.
let _halos = [];
let _lines = [];
let _fill = null;
let _fillShown = false;
// Each line's reveal and show as last drawn.
const _drawnLines = new Map();
// Each halo's look as last drawn.
const _drawnHalos = new Map();
let _enabled = false;
let _boundaryReady = false;
let _boundaryResolved = false;
let _boundaryRing = null;
let _generation = 0;
let _presentation = BHOTE_KOSHI_REGIONAL_PRESENTATION;
let _borderAnimationFrame = null;
let _calloutPulseFrame = null;
let _triggerApproachTimer = null;
let _removeTriggerMoveStart = null;
@@ -332,30 +341,164 @@ export function createBhoteKoshiLocatorLayer({
_removeTriggerMoveEnd = null;
const wasInFlight = _triggerApproachInFlight;
_triggerApproachInFlight = false;
if (wasInFlight) _viewer?.camera?.cancelFlight?.();
if (wasInFlight) findCamera(_viewer)?.cancelFlight();
if (!preserveCallout) _triggerCalloutStartedAt = Number.POSITIVE_INFINITY;
}
function stopAnimations() {
if (_borderAnimationFrame !== null) cancelFrame(_borderAnimationFrame);
if (_calloutPulseFrame !== null) cancelFrame(_calloutPulseFrame);
_borderAnimationFrame = null;
_calloutPulseFrame = null;
_placeRevealMoving = false;
_placeRevealSettledAt = Number.POSITIVE_INFINITY;
clearTriggerApproach();
}
function removeDataSource() {
function removeDrawn() {
stopAnimations();
overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
if (_dataSource && _viewer?.dataSources)
_viewer.dataSources.remove(_dataSource, true);
_dataSource = null;
if (_sets) for (const set of Object.values(_sets)) set.dispose();
_sets = null;
_drawing = false;
resetDrawn();
}
function resetDrawn() {
_halos = [];
_lines = [];
_fill = null;
_fillShown = false;
_drawnLines.clear();
_drawnHalos.clear();
}
/** The layer's draw sets, made on first use: fill under lines under halos. */
function drawSets() {
if (_sets) return _sets;
const draw = drawOf(_viewer);
const prefix = `${BHOTE_KOSHI_LOCATOR_LAYER_ID}:${_serial}`;
// Presentation only: clicks go through to what is under them.
_sets = {
fill: draw.shapes({ id: `${prefix}:fill`, pickable: false }),
lines: draw.lines({ id: `${prefix}:lines`, pickable: false }),
halos: draw.points({ id: `${prefix}:halos`, pickable: false }),
};
return _sets;
}
/** Draw the presentation as it now stands, in place of what was drawn. */
function commitDrawn() {
const sets = drawSets();
_drawnLines.clear();
_fillShown = Boolean(_fill?.visible());
sets.fill.set(_fillShown ? [_fill.item] : []);
sets.lines.set(
_lines.map((line) => {
const item = line();
_drawnLines.set(item.id, lineKey(item));
return item;
}),
);
_drawnHalos.clear();
sets.halos.set(
_halos.map((halo) => {
const item = halo();
_drawnHalos.set(item.id, haloKey(item));
return item;
}),
);
}
const haloKey = (item) =>
`${item.pixelSize}:${item.color}:${item.outlineColor}:${item.show}`;
const lineKey = (item) => `${item.revealFraction}:${item.show !== false}`;
/**
* Bring what is drawn to the time now: halos pulse, lines that grew or
* showed are changed in place, and the fill shows once it is due.
*/
function syncDrawn() {
if (!_drawing || !_sets) return;
if (!_fillShown && _fill?.visible()) {
_fillShown = true;
_sets.fill.set([_fill.item]);
}
const changed = [];
for (const line of _lines) {
const item = line();
const key = lineKey(item);
if (_drawnLines.get(item.id) === key) continue;
_drawnLines.set(item.id, key);
changed.push(item);
}
if (changed.length) _sets.lines.upsert(changed);
const pulsed = [];
for (const halo of _halos) {
const item = halo();
const key = haloKey(item);
if (_drawnHalos.get(item.id) === key) continue;
_drawnHalos.set(item.id, key);
pulsed.push(item);
}
if (pulsed.length) _sets.halos.upsert(pulsed);
}
/**
* A pulsing halo point: `progress()` (0..1) sizes it and fades its fill
* and ring (`fillAlpha`, `ringAlpha`), shown while `visible()`.
*/
function addHalo({
id,
subject,
color,
visible,
progress,
fillAlpha,
ringAlpha,
scaleByDistance,
}) {
const pos = { lon: subject.lon, lat: subject.lat, height: subject.heightM };
_halos.push(() => {
const p = progress();
return {
id,
pos,
pixelSize: CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * p,
color: hexColor(color, fillAlpha(p)),
outlineColor: hexColor(color, ringAlpha(p)),
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
scaleByDistance,
show: visible(),
};
});
}
/**
* A draped line revealed vertex by vertex as `progress()` runs 0..1,
* shown while `visible()`.
*/
function addRevealedLine({
id,
positions,
widthPx,
color,
progress,
visible,
}) {
_lines.push(() => ({
id,
positions,
widthPx,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color },
revealFraction: revealLengthFraction(positions, progress()),
show: visible(),
}));
}
function addCallout(
dataSource,
subject,
color,
{
@@ -365,51 +508,27 @@ export function createBhoteKoshiLocatorLayer({
showAnchor = true,
} = {},
) {
const position = Cesium.Cartesian3.fromDegrees(
subject.lon,
subject.lat,
subject.heightM,
);
const position = fromDegrees(subject.lon, subject.lat, subject.heightM);
const visibleAt = sequenceStartedAt + visibleAfterMs;
const isVisible = () => now() >= visibleAt;
const pulseProgress = () => {
const elapsed = Math.max(0, now() - visibleAt);
return (elapsed % CALLOUT_PULSE_DURATION_MS) / CALLOUT_PULSE_DURATION_MS;
};
const ringSize = new Cesium.CallbackProperty(() => {
return (
CALLOUT_RING_MIN_SIZE_PX + CALLOUT_RING_SIZE_RANGE_PX * pulseProgress()
);
}, false);
const ringColor = new Cesium.CallbackProperty((_time, result) => {
const dynamicColor = Cesium.Color.clone(color, result);
dynamicColor.alpha = isVisible() ? 0.14 * (1 - pulseProgress()) : 0;
return dynamicColor;
}, false);
const ringOutlineColor = new Cesium.CallbackProperty((_time, result) => {
const dynamicColor = Cesium.Color.clone(color, result);
dynamicColor.alpha = isVisible()
? 0.08 + 0.72 * (1 - pulseProgress())
: 0;
return dynamicColor;
}, false);
if (showAnchor) {
dataSource.entities.add({
addHalo({
id: `${subject === INCIDENT ? 'bhote-koshi-incident' : 'nepal-context'}-halo`,
position,
show: new Cesium.CallbackProperty(isVisible, false),
point: {
pixelSize: ringSize,
color: ringColor,
outlineColor: ringOutlineColor,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(
250000,
0.8,
25000000,
1.35,
),
subject,
color,
visible: isVisible,
progress: pulseProgress,
fillAlpha: (p) => (isVisible() ? 0.14 * (1 - p) : 0),
ringAlpha: (p) => (isVisible() ? 0.08 + 0.72 * (1 - p) : 0),
scaleByDistance: {
near: 250000,
nearValue: 0.8,
far: 25000000,
farValue: 1.35,
},
});
}
@@ -498,25 +617,22 @@ export function createBhoteKoshiLocatorLayer({
_placeRevealSettledAt = Number.POSITIVE_INFINITY;
publishOverlayEntries();
}
syncDrawn();
requestRender('bhote-koshi-locator-callout-pulse');
_calloutPulseFrame = scheduleFrame(pulseFrame);
};
_calloutPulseFrame = scheduleFrame(pulseFrame);
}
function addIncidentCallout(
dataSource,
sequenceStartedAt,
visibleAfterMs = 0,
) {
addCallout(dataSource, INCIDENT, INCIDENT_COLOR, {
function addIncidentCallout(sequenceStartedAt, visibleAfterMs = 0) {
addCallout(INCIDENT, INCIDENT_ACCENT, {
sequenceStartedAt,
visibleAfterMs,
});
}
function addTriggerRecordCallout(dataSource) {
const position = Cesium.Cartesian3.fromDegrees(
function addTriggerRecordCallout() {
const position = fromDegrees(
TRIGGER_RECORD.lon,
TRIGGER_RECORD.lat,
TRIGGER_RECORD.heightM,
@@ -531,30 +647,19 @@ export function createBhoteKoshiLocatorLayer({
CALLOUT_PULSE_DURATION_MS
);
};
dataSource.entities.add({
addHalo({
id: 'bhote-koshi-trigger-record-halo',
position,
show: new Cesium.CallbackProperty(isVisible, false),
point: {
pixelSize: new Cesium.CallbackProperty(
() =>
CALLOUT_RING_MIN_SIZE_PX +
CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(),
false,
),
color: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.16 * (1 - pulseProgress());
return color;
}, false),
outlineColor: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = isVisible() ? 0.08 + 0.78 * (1 - pulseProgress()) : 0;
return color;
}, false),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(3000, 1, 250000, 0.82),
subject: TRIGGER_RECORD,
color: INCIDENT_ACCENT,
visible: isVisible,
progress: pulseProgress,
fillAlpha: (p) => 0.16 * (1 - p),
ringAlpha: (p) => (isVisible() ? 0.08 + 0.78 * (1 - p) : 0),
scaleByDistance: {
near: 3000,
nearValue: 1,
far: 250000,
farValue: 0.82,
},
});
queueOverlayEntry({
@@ -618,8 +723,8 @@ export function createBhoteKoshiLocatorLayer({
_removeTriggerMoveEnd = null;
_triggerCalloutStartedAt = now();
requestRender('bhote-koshi-trigger-record-reveal');
const camera = _viewer?.camera;
if (!camera?.flyTo) return;
const port = findCamera(_viewer);
if (!port) return;
const generation = _generation;
_triggerApproachInFlight = true;
const finish = () => {
@@ -627,50 +732,54 @@ export function createBhoteKoshiLocatorLayer({
attempt.phase = 'finished';
_triggerApproachInFlight = false;
};
camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
TRIGGER_APPROACH_CAMERA.lon,
TRIGGER_APPROACH_CAMERA.lat,
TRIGGER_APPROACH_CAMERA.alt,
),
orientation: {
heading: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.heading),
pitch: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.pitch),
roll: Cesium.Math.toRadians(TRIGGER_APPROACH_CAMERA.roll),
port.flyTo(
{
lon: TRIGGER_APPROACH_CAMERA.lon,
lat: TRIGGER_APPROACH_CAMERA.lat,
height: TRIGGER_APPROACH_CAMERA.alt,
},
duration: TRIGGER_APPROACH_DURATION_SEC,
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
complete: () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying')
return;
if (
!_enabled ||
generation !== _generation ||
_presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION
) {
finish();
return;
}
attempt.phase = 'orbiting';
camera.flyTo({
destination: Cesium.Cartesian3.fromDegrees(
TRIGGER_ORBIT_CAMERA.lon,
TRIGGER_ORBIT_CAMERA.lat,
TRIGGER_ORBIT_CAMERA.alt,
),
orientation: {
heading: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.heading),
pitch: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.pitch),
roll: Cesium.Math.toRadians(TRIGGER_ORBIT_CAMERA.roll),
},
duration: TRIGGER_ORBIT_DURATION_SEC,
easingFunction: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
complete: finish,
cancel: finish,
});
{
orientation: {
heading: toRadians(TRIGGER_APPROACH_CAMERA.heading),
pitch: toRadians(TRIGGER_APPROACH_CAMERA.pitch),
roll: toRadians(TRIGGER_APPROACH_CAMERA.roll),
},
durationS: TRIGGER_APPROACH_DURATION_SEC,
easing: 'cubicInOut',
onComplete: () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'flying')
return;
if (
!_enabled ||
generation !== _generation ||
_presentation !== BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION
) {
finish();
return;
}
attempt.phase = 'orbiting';
port.flyTo(
{
lon: TRIGGER_ORBIT_CAMERA.lon,
lat: TRIGGER_ORBIT_CAMERA.lat,
height: TRIGGER_ORBIT_CAMERA.alt,
},
{
orientation: {
heading: toRadians(TRIGGER_ORBIT_CAMERA.heading),
pitch: toRadians(TRIGGER_ORBIT_CAMERA.pitch),
roll: toRadians(TRIGGER_ORBIT_CAMERA.roll),
},
durationS: TRIGGER_ORBIT_DURATION_SEC,
easing: 'sineInOut',
onComplete: finish,
onCancel: finish,
},
);
},
onCancel: finish,
},
cancel: finish,
});
);
}
function armTriggerApproach() {
@@ -681,40 +790,36 @@ export function createBhoteKoshiLocatorLayer({
const attempt = { phase: 'armed' };
_triggerApproachAttempt = attempt;
const start = () => startTriggerApproach(attempt);
const camera = _viewer?.camera;
if (
!camera?.moveStart?.addEventListener ||
!camera?.moveEnd?.addEventListener
) {
const camera = findCamera(_viewer);
if (!camera) {
start();
return;
}
_removeTriggerMoveStart = camera.moveStart.addEventListener(() => {
_removeTriggerMoveStart = camera.on('moveStart', () => {
if (_triggerApproachAttempt !== attempt || attempt.phase !== 'armed')
return;
if (_triggerApproachTimer !== null) cancelDelay(_triggerApproachTimer);
_triggerApproachTimer = null;
_removeTriggerMoveStart?.();
_removeTriggerMoveStart = null;
_removeTriggerMoveEnd = camera.moveEnd.addEventListener(start);
_removeTriggerMoveEnd = camera.on('moveEnd', start);
});
_triggerApproachTimer = scheduleDelay(start, TRIGGER_APPROACH_ARM_MS);
}
function addNepalCallout(
dataSource,
sequenceStartedAt = now(),
labelPlacement = 'right',
{ showAnchor = true } = {},
) {
addCallout(dataSource, NEPAL, BORDER_COLOR, {
addCallout(NEPAL, BORDER_ACCENT, {
labelPlacement,
sequenceStartedAt,
showAnchor,
});
}
function addNearbyCityCallouts(dataSource, sequenceStartedAt) {
function addNearbyCityCallouts(sequenceStartedAt) {
NEARBY_CITIES.forEach((city, index) => {
const visibleAt =
sequenceStartedAt +
@@ -724,11 +829,7 @@ export function createBhoteKoshiLocatorLayer({
smoothstep(0, 1, (now() - visibleAt) / CITY_CALLOUT_REVEAL_MS);
const labelOnLeft = city.placement === 'left';
const labelLower = city.placement === 'right-lower';
const position = Cesium.Cartesian3.fromDegrees(
city.lon,
city.lat,
city.heightM,
);
const position = fromDegrees(city.lon, city.lat, city.heightM);
queueOverlayEntry({
id: `bhote-koshi-city-${city.id}`,
position,
@@ -765,7 +866,6 @@ export function createBhoteKoshiLocatorLayer({
}
function addIncidentPlaceCallouts(
dataSource,
sequenceStartedAt,
{ pulseHalos = false, places = INCIDENT_OVERVIEW_PLACES } = {},
) {
@@ -778,11 +878,7 @@ export function createBhoteKoshiLocatorLayer({
smoothstep(0, 1, (now() - visibleAt) / PLACE_CALLOUT_REVEAL_MS);
const labelOnLeft = place.placement === 'left';
const labelLower = place.placement === 'right-lower';
const position = Cesium.Cartesian3.fromDegrees(
place.lon,
place.lat,
place.heightM,
);
const position = fromDegrees(place.lon, place.lat, place.heightM);
if (pulseHalos) {
const pulseSequenceDurationMs =
PLACE_CALLOUT_STAGGER_MS * places.length;
@@ -810,30 +906,19 @@ export function createBhoteKoshiLocatorLayer({
Math.min(1, pulseWindowElapsed() / PLACE_CALLOUT_STAGGER_MS),
);
};
dataSource.entities.add({
addHalo({
id: `bhote-koshi-place-${place.id}-halo`,
position,
show: new Cesium.CallbackProperty(pulseIsActive, false),
point: {
pixelSize: new Cesium.CallbackProperty(
() =>
CALLOUT_RING_MIN_SIZE_PX +
CALLOUT_RING_SIZE_RANGE_PX * pulseProgress(),
false,
),
color: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.16 * (1 - pulseProgress());
return color;
}, false),
outlineColor: new Cesium.CallbackProperty((_time, result) => {
const color = Cesium.Color.clone(INCIDENT_COLOR, result);
color.alpha = 0.08 + 0.78 * (1 - pulseProgress());
return color;
}, false),
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(5000, 1, 500000, 0.82),
subject: place,
color: INCIDENT_ACCENT,
visible: pulseIsActive,
progress: pulseProgress,
fillAlpha: (p) => 0.16 * (1 - p),
ringAlpha: (p) => 0.08 + 0.78 * (1 - p),
scaleByDistance: {
near: 5000,
nearValue: 1,
far: 500000,
farValue: 0.82,
},
});
}
@@ -872,105 +957,67 @@ export function createBhoteKoshiLocatorLayer({
});
}
function addIncidentFloodPath(dataSource, sequenceStartedAt) {
function addIncidentFloodPath(sequenceStartedAt) {
const positions = BHOTE_KOSHI_FLOOD_PATH.map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
fromDegrees(lon, lat),
);
const drawStartedAt = sequenceStartedAt + FLOOD_PATH_START_DELAY_MS;
const animatedPositions = new Cesium.CallbackProperty(
() =>
revealPolylinePositions(
positions,
(now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS,
),
false,
);
dataSource.entities.add({
addRevealedLine({
id: 'bhote-koshi-flood-path',
show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false),
polyline: {
positions: animatedPositions,
width: 3.5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.96),
classificationType: Cesium.ClassificationType.BOTH,
},
positions,
widthPx: 3.5,
color: hexColor(BORDER_ACCENT, 0.96),
progress: () => (now() - drawStartedAt) / FLOOD_PATH_DRAW_DURATION_MS,
visible: () => now() >= drawStartedAt,
});
}
function addNepalBoundary(dataSource, ring, sequenceStartedAt) {
function addNepalBoundary(ring, sequenceStartedAt) {
const closed = closeRegionRing(ring);
if (closed.length < 4) return false;
const positions = Cesium.Cartesian3.fromDegreesArray(closed.flat());
const hierarchy = new Cesium.PolygonHierarchy(positions.slice(0, -1));
const positions = closed.map(([lon, lat]) => fromDegrees(lon, lat));
const drawStartedAt = sequenceStartedAt + BORDER_START_DELAY_MS;
const animatedPositions = new Cesium.CallbackProperty(
() =>
revealPolylinePositions(
positions,
(now() - drawStartedAt) / BORDER_DRAW_DURATION_MS,
),
false,
);
dataSource.entities.add({
id: 'nepal-border-fill',
show: new Cesium.CallbackProperty(() => now() >= drawStartedAt, false),
polygon: {
hierarchy,
material: BORDER_COLOR.withAlpha(0.055),
classificationType: Cesium.ClassificationType.BOTH,
const progress = () => (now() - drawStartedAt) / BORDER_DRAW_DURATION_MS;
_fill = {
visible: () => now() >= drawStartedAt,
item: {
id: 'nepal-border-fill',
geometry: {
kind: 'polygon',
rings: [closed.slice(0, -1).map(([lon, lat]) => ({ lon, lat }))],
},
fill: hexColor(BORDER_ACCENT, 0.055),
height: 'clampGround',
clampTo: 'both',
},
});
dataSource.entities.add({
id: 'nepal-border-halo',
polyline: {
positions: animatedPositions,
width: 5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.12),
classificationType: Cesium.ClassificationType.BOTH,
},
});
dataSource.entities.add({
id: 'nepal-border-highlight',
polyline: {
positions: animatedPositions,
width: 2.5,
clampToGround: true,
material: BORDER_COLOR.withAlpha(0.96),
classificationType: Cesium.ClassificationType.BOTH,
},
});
const generation = _generation;
const drawFrame = () => {
if (
!_enabled ||
generation !== _generation ||
!presentationAnimatesBoundary(_presentation)
)
return;
requestRender('bhote-koshi-locator-border-draw');
if (now() - drawStartedAt < BORDER_DRAW_DURATION_MS) {
_borderAnimationFrame = scheduleFrame(drawFrame);
} else {
_borderAnimationFrame = null;
}
};
_borderAnimationFrame = scheduleFrame(drawFrame);
for (const [id, widthPx, alpha] of [
['nepal-border-halo', 5, 0.12],
['nepal-border-highlight', 2.5, 0.96],
])
addRevealedLine({
id,
positions,
widthPx,
color: hexColor(BORDER_ACCENT, alpha),
progress,
visible: () => true,
});
// The callout pulse draws each step of the reveal (`syncDrawn`).
return true;
}
function renderPresentation() {
if (!_dataSource) return;
if (!_drawing) return;
stopAnimations();
overlayHost.clearSource(BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID);
_overlayEntries = [];
_dataSource.entities.removeAll();
resetDrawn();
if (_presentation === NEPAL_CONTEXT_PRESENTATION) {
addNepalCallout(_dataSource);
addNepalCallout();
} else if (_presentation === BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION) {
const sequenceStartedAt = now();
addIncidentPlaceCallouts(_dataSource, sequenceStartedAt, {
addIncidentPlaceCallouts(sequenceStartedAt, {
pulseHalos: true,
places: INCIDENT_OVERVIEW_PLACES,
});
@@ -987,8 +1034,8 @@ export function createBhoteKoshiLocatorLayer({
PLACE_CALLOUT_START_DELAY_MS -
(INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS -
PLACE_CALLOUT_REVEAL_MS;
addIncidentFloodPath(_dataSource, sequenceStartedAt);
addIncidentPlaceCallouts(_dataSource, settledPlacesAt);
addIncidentFloodPath(sequenceStartedAt);
addIncidentPlaceCallouts(settledPlacesAt);
} else if (_presentation === BHOTE_KOSHI_PATH_OVERVIEW_PRESENTATION) {
const sequenceStartedAt = now();
const settledPathAt =
@@ -1000,21 +1047,22 @@ export function createBhoteKoshiLocatorLayer({
PLACE_CALLOUT_START_DELAY_MS -
(INCIDENT_OVERVIEW_PLACES.length - 1) * PLACE_CALLOUT_STAGGER_MS -
PLACE_CALLOUT_REVEAL_MS;
addIncidentFloodPath(_dataSource, settledPathAt);
addIncidentPlaceCallouts(_dataSource, settledPlacesAt);
addIncidentFloodPath(settledPathAt);
addIncidentPlaceCallouts(settledPlacesAt);
} else if (_presentation === BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION) {
const sequenceStartedAt = now();
const settledPathAt =
sequenceStartedAt -
FLOOD_PATH_START_DELAY_MS -
FLOOD_PATH_DRAW_DURATION_MS;
addIncidentFloodPath(_dataSource, settledPathAt);
addTriggerRecordCallout(_dataSource);
addIncidentFloodPath(settledPathAt);
addTriggerRecordCallout();
armTriggerApproach();
} else {
const sequenceStartedAt = now();
addNepalCallout(_dataSource, sequenceStartedAt, 'left');
addNepalCallout(sequenceStartedAt, 'left');
if (!_boundaryResolved) {
commitDrawn();
publishOverlayEntries();
startCalloutAnimation();
requestRender('bhote-koshi-locator-presentation');
@@ -1023,24 +1071,20 @@ export function createBhoteKoshiLocatorLayer({
if (_presentation === BHOTE_KOSHI_CITY_CONTEXT_PRESENTATION) {
const settledAt =
sequenceStartedAt - BORDER_START_DELAY_MS - BORDER_DRAW_DURATION_MS;
if (_boundaryRing)
addNepalBoundary(_dataSource, _boundaryRing, settledAt);
addIncidentCallout(
_dataSource,
sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS,
);
addNearbyCityCallouts(_dataSource, sequenceStartedAt);
if (_boundaryRing) addNepalBoundary(_boundaryRing, settledAt);
addIncidentCallout(sequenceStartedAt - CALLOUT_REVEAL_DURATION_MS);
addNearbyCityCallouts(sequenceStartedAt);
} else {
if (_boundaryRing)
addNepalBoundary(_dataSource, _boundaryRing, sequenceStartedAt);
if (_boundaryRing) addNepalBoundary(_boundaryRing, sequenceStartedAt);
const incidentDelayMs = _boundaryRing
? BORDER_START_DELAY_MS +
BORDER_DRAW_DURATION_MS +
INCIDENT_CALLOUT_GAP_MS
: BORDER_START_DELAY_MS;
addIncidentCallout(_dataSource, sequenceStartedAt, incidentDelayMs);
addIncidentCallout(sequenceStartedAt, incidentDelayMs);
}
}
commitDrawn();
publishOverlayEntries({ moving: _placeRevealMoving });
startCalloutAnimation();
requestRender('bhote-koshi-locator-presentation');
@@ -1058,11 +1102,9 @@ export function createBhoteKoshiLocatorLayer({
_boundaryResolved = false;
_boundaryRing = null;
const generation = ++_generation;
removeDataSource();
const dataSource = new Cesium.CustomDataSource('bhote-koshi-locator');
_dataSource = dataSource;
removeDrawn();
_drawing = true;
renderPresentation();
viewer.dataSources.add(dataSource);
registerDynamicCredit(viewer, BHOTE_KOSHI_LOCATOR_CREDIT);
showOsmCredit(viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID);
requestRender('bhote-koshi-locator-callout');
@@ -1084,7 +1126,7 @@ export function createBhoteKoshiLocatorLayer({
return true;
} catch (error) {
if (error?.name === 'AbortError') {
if (generation === _generation) removeDataSource();
if (generation === _generation) removeDrawn();
throw error;
}
console.warn(
@@ -1106,7 +1148,7 @@ export function createBhoteKoshiLocatorLayer({
_boundaryResolved = false;
_boundaryRing = null;
_generation += 1;
removeDataSource();
removeDrawn();
requestRender('bhote-koshi-locator-disable');
return true;
}
+241 -155
View File
@@ -1,3 +1,6 @@
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import assert from 'node:assert/strict';
import test from 'node:test';
import { readFile } from 'node:fs/promises';
@@ -24,32 +27,58 @@ import {
createBhoteKoshiLocatorLayer,
largestGeoJsonRing,
NEPAL_CONTEXT_PRESENTATION,
revealPolylinePositions,
revealLengthFraction,
} from './bhoteKoshiLocator.js';
function viewerFixture() {
const added = [];
const removed = [];
return {
/**
* A viewer with a fake draw port bound; with `camera`, the Cesium camera
* port over that fake camera too. `_test` reads what is drawn: every live
* item by id (`drawn`), and `sets` of the layer.
*/
function viewerFixture({ camera } = {}) {
const draw = fakeDrawPort();
const viewer = {
creditDisplay: { addStaticCredit() {}, removeStaticCredit() {} },
dataSources: {
add(source) {
added.push(source);
},
remove(source) {
removed.push(source);
},
},
_test: { added, removed },
};
if (camera) {
viewer.camera = camera;
bindFakeCesiumCamera(viewer, { draw });
} else bindRenderer(viewer, { draw });
const live = () =>
[...draw.sets.values()].filter(
(set) => !set.disposed && set.spec.id.startsWith('bhote-koshi-locator:'),
);
viewer._test = {
draw,
live,
/** Every live item, by id. */
drawn() {
const items = new Map();
for (const set of live())
for (const [id, item] of set.items) items.set(id, item);
return items;
},
ids: () => [...viewer._test.drawn().keys()],
item: (id) => viewer._test.drawn().get(id),
};
return viewer;
}
/** Frames that run only when a test ticks them. */
function nonRunningAnimation() {
let queued = [];
return {
scheduleFrame() {
return 1;
scheduleFrame(callback) {
queued.push(callback);
return queued.length;
},
cancelFrame() {},
/** Run the frames asked for so far (each asks for its next). */
tick() {
const run = queued;
queued = [];
for (const callback of run) callback();
},
};
}
@@ -132,21 +161,18 @@ test('Bhote Koshi locator selects the largest GeoJSON country exterior', () => {
);
});
test('Bhote Koshi locator reveals a border progressively', () => {
test('Bhote Koshi locator reveals a border progressively, vertex by vertex', () => {
const positions = [
new Cesium.Cartesian3(0, 0, 0),
new Cesium.Cartesian3(10, 0, 0),
new Cesium.Cartesian3(20, 0, 0),
{ x: 0, y: 0, z: 0 },
{ x: 10, y: 0, z: 0 },
{ x: 40, y: 0, z: 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);
assert.equal(revealLengthFraction(positions, 0), 0);
// A quarter of the vertices: halfway along the first, shorter segment.
assert.equal(revealLengthFraction(positions, 0.25), 5 / 40);
assert.equal(revealLengthFraction(positions, 0.75), 25 / 40);
assert.equal(revealLengthFraction(positions, 1), 1);
assert.equal(revealLengthFraction(positions.slice(0, 1), 0.5), 0);
});
test('Bhote Koshi locator stages its anchored callout from dot to leader to text', () => {
@@ -169,6 +195,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
const overlayHost = overlayHostFixture();
const renders = [];
let nowMs = 0;
const frames = nonRunningAnimation();
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({
name: 'Nepal',
@@ -182,24 +209,29 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
requestRender: (reason) => renders.push(reason),
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
...frames,
});
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);
const sets = viewer._test.live();
assert.deepEqual(
sets.map(({ kind }) => kind),
['shapes', 'lines', 'points'],
'the fill under the lines under the halos',
);
assert.ok(sets.every(({ spec }) => spec.pickable === false));
// The fill is drawn once it is due, below.
const ids = viewer._test.ids();
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 incidentHalo = () => viewer._test.item('bhote-koshi-incident-halo');
const border = () => viewer._test.item('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);
@@ -225,15 +257,31 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
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);
assert.equal(border().revealFraction, 0);
assert.equal(border().mode, 'draped');
assert.equal(border().positions.length, 5);
assert.equal(viewer._test.item('nepal-border-fill'), undefined);
assert.equal(incidentHalo().show, false);
assert.equal(incidentHalo().pixelSize, 16);
nowMs = 800;
frames.tick();
const fill = viewer._test.item('nepal-border-fill');
assert.equal(fill.height, 'clampGround', 'the fill, due, drapes');
assert.equal(fill.geometry.rings[0].length, 4);
assert.ok(border().revealFraction > 0 && border().revealFraction < 0.1);
nowMs = 3100;
frames.tick();
assert.equal(nepal.sourceAlpha(), 1);
assert.equal(border.polyline.positions.getValue().length, 5);
assert.equal(incidentHalo.show.getValue(), false);
assert.equal(border().revealFraction, 1);
assert.equal(incidentHalo().show, false);
const lines = sets.find(({ kind }) => kind === 'lines');
const lineWrites = lines.writes;
nowMs = 3300;
assert.equal(incidentHalo.show.getValue(), true);
frames.tick();
frames.tick();
assert.equal(lines.writes, lineWrites, 'settled lines are not drawn again');
assert.equal(incidentHalo().show, true);
assert.equal(incidentHalo().disableDepthTest, Number.POSITIVE_INFINITY);
assert.equal(incident.sourceAlpha(), 0);
nowMs = 4500;
assert.equal(incident.sourceAlpha(), 1);
@@ -247,7 +295,7 @@ test('Bhote Koshi regional locator sequences Nepal, border, then the incident',
assert.ok(renders.includes('bhote-koshi-locator-boundary'));
assert.equal(await layer.disable(), true);
assert.equal(viewer._test.removed.length, 1);
assert.equal(viewer._test.live().length, 0, 'its sets let go');
assert.equal(
overlayHost._test.clears.at(-1),
BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
@@ -275,10 +323,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
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'],
);
assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']);
const nepalLabel = overlayHost._test.publications.at(-1).entries[0];
assert.equal(nepalLabel.variant, 'label');
assert.equal(nepalLabel.placement, 'right');
@@ -298,11 +343,8 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
);
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.ok(viewer._test.item('nepal-border-highlight'));
assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined);
assert.equal(
overlayHost._test.publications
.at(-1)
@@ -311,10 +353,7 @@ test('Bhote Koshi locator switches between Nepal context and the regional incide
);
layer.setParams({ presentation: NEPAL_CONTEXT_PRESENTATION });
assert.deepEqual(
viewer._test.added[0].entities.values.map((entity) => entity.id),
['nepal-context-halo'],
);
assert.deepEqual(viewer._test.ids(), ['nepal-context-halo']);
await layer.destroy();
});
@@ -336,7 +375,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
});
layer.setParams({ presentation: BHOTE_KOSHI_INCIDENT_PLACES_PRESENTATION });
await layer.enable(viewer);
const source = viewer._test.added[0];
const tick = () => {
const frame = pulseFrame;
frame?.();
};
const event = JSON.parse(
await readFile(
new URL(
@@ -348,7 +390,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
);
assert.equal(event.evidenceSpine.length, 16);
assert.equal(event.evidenceSpine.at(-1).id, 'charaudi');
assert.equal(source.entities.values.length, 15);
assert.equal(viewer._test.ids().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);
@@ -371,10 +413,11 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
nowMs = 349 + index * 650;
assert.equal(pin.sourceAlpha(), 0);
nowMs += 1;
tick();
assert.equal(pin.sourceAlpha(), 0);
assert.equal(
source.entities.values.filter(
(entity) => entity.id.endsWith('-halo') && entity.show.getValue(),
[...viewer._test.drawn().values()].filter(
(item) => item.id.endsWith('-halo') && item.show,
).length,
1,
);
@@ -384,10 +427,10 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
assert.ok(nowMs < INCIDENT_OVERVIEW_HOLD_SEC * 1000);
// A repeat halo cycle must not erase already revealed labels.
nowMs = 350 + 15 * 650;
tick();
assert.equal(
source.entities
.getById('bhote-koshi-place-immediate-collapse-viewpoint-halo')
.show.getValue(),
viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo')
.show,
true,
);
assert.equal(
@@ -405,9 +448,7 @@ test('Incident Corridor reveals all fifteen overview pins and keeps layout activ
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-'),
),
viewer._test.ids().some((id) => id.startsWith('bhote-koshi-place-')),
false,
);
await layer.destroy();
@@ -457,18 +498,18 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh
const viewer = viewerFixture();
const overlayHost = overlayHostFixture();
let nowMs = 0;
const frames = nonRunningAnimation();
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
overlayHost,
now: () => nowMs,
...nonRunningAnimation(),
...frames,
});
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 path = () => viewer._test.item('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
const trigger = labels.find(
({ id }) => id === 'bhote-koshi-place-immediate-collapse-viewpoint',
@@ -477,46 +518,56 @@ test('Bhote Koshi flood path draws a solid cyan sourced route after the place sh
({ id }) => id === 'bhote-koshi-place-bidur-trishuli-bridge',
);
assert.equal(source.entities.values.length, 1);
assert.equal(viewer._test.ids().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.equal(path().mode, 'draped');
assert.equal(path().clampTo, 'both');
assert.equal(path().widthPx, 3.5);
assert.equal(path().style.kind, 'solid');
const color = Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96);
assert.ok(
path.polyline.material.color
.getValue()
.equalsEpsilon(
Cesium.Color.fromCssColorString('#20e7f2').withAlpha(0.96),
path().style.color.every(
(value, i) =>
Math.abs(value - Cesium.Color.pack(color, [])[i]) <
Cesium.Math.EPSILON7,
),
),
);
assert.equal(path.show.getValue(), false);
assert.equal(path().show, 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);
frames.tick();
assert.equal(path().show, true);
assert.equal(path().revealFraction, 0);
nowMs = 2250;
const halfwayCount = path.polyline.positions.getValue().length;
assert.ok(Math.abs(halfwayCount - BHOTE_KOSHI_FLOOD_PATH.length / 2) <= 2);
frames.tick();
// Halfway through its vertices.
const positions = path().positions;
assert.equal(path().revealFraction, revealLengthFraction(positions, 0.5));
assert.ok(path().revealFraction > 0.2 && path().revealFraction < 0.8);
nowMs = 4250;
assert.equal(
path.polyline.positions.getValue().length,
BHOTE_KOSHI_FLOOD_PATH.length,
);
frames.tick();
assert.equal(path().revealFraction, 1);
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.equal(positions.length, BHOTE_KOSHI_FLOOD_PATH.length);
positions.forEach((position, i) => {
const [lon, lat] = BHOTE_KOSHI_FLOOD_PATH[i];
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
position,
Cesium.Cartesian3.fromDegrees(lon, lat),
0,
1e-6,
),
);
});
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(), {
@@ -547,11 +598,10 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep
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 path = viewer._test.item('bhote-koshi-flood-path');
const labels = overlayHost._test.publications.at(-1).entries;
assert.equal(source.entities.values.length, 1);
assert.equal(viewer._test.ids().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}`);
@@ -561,23 +611,21 @@ test('Bhote Koshi path-overview presentation keeps the route settled without Nep
);
assert.equal(pin.sourceAlpha(), 1);
}
assert.equal(path.show.getValue(), true);
assert.equal(
path.polyline.positions.getValue().length,
BHOTE_KOSHI_FLOOD_PATH.length,
);
assert.equal(path.show, true);
assert.equal(path.revealFraction, 1);
assert.equal(path.positions.length, BHOTE_KOSHI_FLOOD_PATH.length);
assert.ok(
Cesium.Cartesian3.equals(
path.polyline.positions.getValue()[0],
Cesium.Cartesian3.equalsEpsilon(
path.positions[0],
Cesium.Cartesian3.fromDegrees(85.48476, 28.33255),
0,
1e-6,
),
);
assert.equal(source.entities.getById('nepal-border-fill'), undefined);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('nepal-border-fill'), undefined);
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(
source.entities.getById(
'bhote-koshi-place-immediate-collapse-viewpoint-halo',
),
viewer._test.item('bhote-koshi-place-immediate-collapse-viewpoint-halo'),
undefined,
);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Path overview');
@@ -604,14 +652,13 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
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.deepEqual(viewer._test.ids(), [
'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',
@@ -624,7 +671,7 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
assert.equal(record.sourceAlpha(), 0);
nowMs = 1200;
assert.equal(record.sourceAlpha(), 1);
assert.equal(source.entities.getById('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(layer.getStats().coverage, 'Bhote Koshi · Trigger record');
assert.deepEqual(layer.getParams(), {
presentation: BHOTE_KOSHI_TRIGGER_RECORD_PRESENTATION,
@@ -633,20 +680,21 @@ test('Bhote Koshi trigger-record presentation reveals sourced incident details',
});
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);
const viewer = viewerFixture({
camera: {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
},
cancelFlight() {},
},
cancelFlight() {},
};
});
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
requestRender() {},
@@ -688,21 +736,24 @@ test('Bhote Koshi trigger-record waits for the scene camera, zooms, then orbits'
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);
const viewer = viewerFixture({
camera: {
moveStart,
moveEnd,
flyTo(options) {
flights.push(options);
},
cancelFlight() {},
},
cancelFlight() {},
};
});
// The renderer's camera port relays these; the layer's own come on top.
const portListeners = [moveStart, moveEnd].map((e) => e.numberOfListeners);
const layer = createBhoteKoshiLocatorLayer({
boundaryResolver: async () => null,
overlayHost: overlayHostFixture(),
@@ -745,8 +796,10 @@ for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
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);
assert.deepEqual(
[moveStart, moveEnd].map((e) => e.numberOfListeners),
portListeners,
);
callbacks[0]();
moveEnd.raiseEvent();
for (const flight of oldFlights) flight.complete();
@@ -807,8 +860,7 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities
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 borderFill = viewer._test.item('nepal-border-fill');
const entries = overlayHost._test.publications.at(-1).entries;
const incident = entries.find(
({ id }) => id === 'bhote-koshi-incident-callout',
@@ -823,7 +875,8 @@ test('Bhote Koshi locator keeps the regional context settled while nearby cities
({ id }) => id === 'bhote-koshi-city-dhulikhel',
);
assert.equal(borderFill.show.getValue(), true);
assert.ok(borderFill, 'the settled fill is drawn at once');
assert.equal(viewer._test.item('nepal-border-highlight').revealFraction, 1);
assert.equal(incident.contentAlpha(), 1);
assert.equal(kathmandu.title, 'KATHMANDU');
assert.equal(bhaktapur.title, 'BHAKTAPUR');
@@ -866,9 +919,7 @@ test('Bhote Koshi locator degrades to labels when the regional boundary is unava
});
try {
await layer.enable(viewer);
const ids = viewer._test.added[0].entities.values.map(
(entity) => entity.id,
);
const ids = viewer._test.ids();
assert.ok(ids.includes('nepal-context-halo'));
assert.ok(ids.includes('bhote-koshi-incident-halo'));
assert.equal(ids.includes('bhote-koshi-city-kathmandu'), false);
@@ -899,15 +950,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu
});
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.ok(viewer._test.item('nepal-context-halo'));
assert.equal(viewer._test.item('nepal-border-highlight'), undefined);
assert.equal(viewer._test.item('bhote-koshi-incident-halo'), undefined);
assert.equal(overlayHost._test.publications.length, 1);
assert.deepEqual(
overlayHost._test.publications[0].entries.map(({ id }) => id),
@@ -923,14 +968,9 @@ test('Bhote Koshi regional locator waits for its boundary before starting the fu
],
});
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.ok(viewer._test.item('bhote-koshi-incident-halo'));
assert.ok(viewer._test.item('nepal-border-highlight'));
assert.equal(viewer._test.item('bhote-koshi-city-kathmandu'), undefined);
assert.equal(overlayHost._test.publications.length, 2);
assert.deepEqual(
overlayHost._test.publications.at(-1).entries.map(({ id }) => id),
@@ -960,6 +1000,52 @@ test('Bhote Koshi locator cancels a stale boundary resolution and removes its su
[88, 30],
],
});
assert.ok(viewer._test.live().length > 0, 'drawn while it resolves');
await assert.rejects(enabling, (error) => error?.name === 'AbortError');
assert.equal(viewer._test.removed.length, 1);
assert.equal(viewer._test.live().length, 0, 'let go');
});
test('Bhote Koshi locator layers draw sets of their own, and halos only as they change', async () => {
const viewer = viewerFixture();
const ring = [
[80, 26],
[88, 26],
[88, 30],
[80, 30],
];
let nowMs = 0;
const frames = nonRunningAnimation();
const make = () =>
createBhoteKoshiLocatorLayer({
boundaryResolver: async () => ({ name: 'Nepal', ring }),
requestRender() {},
overlayHost: overlayHostFixture(),
now: () => nowMs,
...frames,
});
const first = make();
const second = make();
assert.equal(await first.enable(viewer, { origin: 'scene' }), true);
assert.equal(await second.enable(viewer, { origin: 'scene' }), true);
const ids = viewer._test.live().map(({ spec }) => spec.id);
assert.equal(ids.length, 6);
assert.equal(new Set(ids).size, 6, 'no two layers share a set');
// Before the incident halo is due, nothing about any halo changes.
const halos = viewer._test.live().filter(({ kind }) => kind === 'points');
nowMs = 100;
frames.tick();
const writes = halos.map((set) => set.writes);
frames.tick();
frames.tick();
assert.deepEqual(
halos.map((set) => set.writes),
writes,
'unchanged halos are not drawn again',
);
assert.equal(await first.disable(), true);
assert.equal(viewer._test.live().length, 3, 'the other layer keeps its sets');
assert.equal(await second.disable(), true);
assert.equal(viewer._test.live().length, 0);
});
+25 -15
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fromDegrees } from '../geo/ellipsoid.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
_clearBikeshareSelectionForTest,
@@ -19,17 +20,17 @@ function makeRecord() {
isInstalled: true,
isRenting: false,
isReturning: true,
point: {
position: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 2),
show: true,
},
key: 'austin-capmetro:3790',
position: fromDegrees(-97.7431, 30.2672, 2),
pixelSize: 8,
color: [0, 1, 0, 1],
};
}
test('selected bikeshare entry preserves source copy and protected-lane policy', () => {
const record = makeRecord();
const entry = createBikeshareSelectedOverlayEntry('austin-capmetro:3790', record);
assert.equal(entry.position, record.point.position);
assert.equal(entry.position, record.position);
assert.equal(entry.title, 'Congress & 6th');
assert.deepEqual(entry.details, [
'🚲 7 avail · 4 docks · 11 cap',
@@ -44,7 +45,7 @@ test('selected bikeshare entry preserves source copy and protected-lane policy',
assert.equal(entry.horizonCull, true);
});
test('real station select/clear path publishes one card and creates no native label graphic', () => {
test('real station select/clear path publishes one card and draws no native label', () => {
const calls = [];
const overlayHost = {
setEntries: (...args) => calls.push(['entries', ...args]),
@@ -53,27 +54,36 @@ test('real station select/clear path publishes one card and creates no native la
};
const key = 'austin-capmetro:3790';
const record = makeRecord();
const viewer = { entities: new Cesium.EntityCollection() };
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
_setBikeshareSelectionStateForTest({ viewer, key, record, overlayHost });
const live = (suffix) =>
[...draw.sets.values()].find((set) => !set.disposed && set.spec.id.endsWith(suffix));
const stations = live(':stations');
const selected = live(':selected');
try {
_selectBikeshareStationForTest(key);
assert.equal(record.point.show, false);
assert.equal(viewer.entities.values.length, 1, 'runtime guard requires a real selected entity');
assert.equal(viewer.entities.values[0].label, undefined);
assert.ok(viewer.entities.values[0].point, 'selected point highlight remains native');
assert.equal(stations.items.get(key).show, false, 'the station’s own dot is hidden');
assert.equal(selected.items.size, 1, 'one highlight dot replaces it');
const [highlight] = selected.items.values();
assert.equal(highlight.pos, record.position);
assert.deepEqual(highlight.color, [0, 1, 1, 1], 'cyan');
assert.equal(highlight.pixelSize, 14);
assert.equal(highlight.disableDepthTest, Infinity);
const publication = calls.find(([type]) => type === 'entries');
assert.ok(publication);
assert.equal(publication[1], 'bikeshare-selected');
assert.equal(publication[2].length, 1);
assert.equal(publication[2][0].position, record.point.position);
assert.equal(publication[2][0].position, record.position);
assert.deepEqual(publication[3], BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS);
_clearBikeshareSelectionForTest();
assert.equal(record.point.show, true);
assert.equal(viewer.entities.values.length, 0);
assert.equal(stations.items.get(key).show, true);
assert.equal(selected.items.size, 0);
assert.deepEqual(calls.at(-1), ['clear', 'bikeshare-selected']);
} finally {
_clearBikeshareSelectionForTest();
unbind();
}
});
+29 -20
View File
@@ -8,6 +8,8 @@ import { readFileSync } from 'node:fs';
import * as Cesium from 'cesium';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from '../annotations/resolver.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js';
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
@@ -21,7 +23,7 @@ const DATA_MODULES = [
'./local_data/wof_neighborhoods/files.js',
];
/** Modules that use Cesium for outlines but must not draw text with it. */
/** Modules that draw outlines but must not draw text with Cesium. */
const CESIUM_MODULES = [
'../annotations/resolver.js',
'../annotations/worldAnnotationRenderer.js',
@@ -109,21 +111,22 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
featureSource,
});
const primitives = [];
const dataSources = [];
const viewer = {
camera: {
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7431,
30.2672,
3000,
),
const draw = fakeDrawPort();
// The resolver reads the camera through the renderer's camera port; the
// world renderer draws through its draw port.
const viewer = bindFakeCesiumCamera(
{
camera: {
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7431,
30.2672,
3000,
),
},
scene: { primitives: { add: (p) => primitives.push(p) } },
},
scene: { primitives: { add: (p) => primitives.push(p) } },
dataSources: {
add: (ds) => dataSources.push(ds),
remove() {},
},
};
{ draw },
);
const renderer = createWorldAnnotationRenderer(viewer);
for (const [target, lon, lat] of [
['Austin', -97.7431, 30.2672],
@@ -135,8 +138,8 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
3000,
);
const resolved = await resolveAnnotationTarget({
// The resolver reads only the camera (no scene to pick from).
viewer: { camera: viewer.camera },
// The resolver reads only the camera (no query port to pick with).
viewer,
target,
footprint: true,
deferFootprint: true,
@@ -155,8 +158,14 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
});
}
assert.equal(primitives.length, 0, 'no primitive collections');
const entities = dataSources.flatMap((ds) => ds.entities.values);
assert.ok(entities.length >= 2, 'the outlines were drawn');
for (const entity of entities) assert.equal(entity.label, undefined);
const live = [...draw.sets.values()].filter((record) => !record.disposed);
const items = live.flatMap((record) => [...record.items.values()]);
assert.ok(items.length >= 2, 'the outlines were drawn');
// Fills and lines only: no point, text or label is drawn for a name.
assert.deepEqual([...new Set(live.map((record) => record.kind))].sort(), [
'lines',
'shapes',
]);
for (const item of items) assert.equal(item.label, undefined);
renderer.destroy();
});
+23 -4
View File
@@ -1,10 +1,29 @@
import * as Cesium from 'cesium';
import { toRadians } from '../geo/index.js';
import { findCamera } from '../render/rendererOf.js';
/** The camera port's pose, or null when there is none to read. */
function poseOf(viewer) {
try {
return findCamera(viewer)?.pose() ?? null;
} catch {
return null;
}
}
/** Camera range with breathing room in both viewport dimensions. */
export function rangeForBoundingSphere(viewer, radius) {
const frustum = viewer.camera?.frustum;
const verticalFov = Number(frustum?.fov) || Cesium.Math.toRadians(60);
const aspectRatio = Math.max(0.5, Number(frustum?.aspectRatio) || 1);
const pose = poseOf(viewer);
const fovy = Number(pose?.fovy);
const aspect = Number(pose?.aspectRatio);
// The frustum's field of view: along its wider side.
const fov =
fovy > 0 && aspect > 1
? 2 * Math.atan(Math.tan(fovy / 2) * aspect)
: fovy > 0
? fovy
: NaN;
const verticalFov = fov || toRadians(60);
const aspectRatio = Math.max(0.5, aspect || 1);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio);
const limitingFov = Math.min(verticalFov, horizontalFov);
// Target 57% sphere occupancy so perspective still leaves at least 40%
+36
View File
@@ -0,0 +1,36 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { rangeForBoundingSphere } from './cameraFraming.js';
/** The range as it was read from Cesium's frustum before the camera port. */
function rangeFromFrustum(frustum, radius) {
const verticalFov = frustum.fov;
const aspectRatio = Math.max(0.5, frustum.aspectRatio);
const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio);
const limitingFov = Math.min(verticalFov, horizontalFov);
return (radius / Math.sin((limitingFov * 0.57) / 2)) * 1.05;
}
for (const aspectRatio of [16 / 9, 390 / 844, 1]) {
test(`framing reads the frustum's field of view through the camera port (aspect ${aspectRatio.toFixed(2)})`, () => {
const frustum = new Cesium.PerspectiveFrustum({
fov: Math.PI / 3,
aspectRatio,
near: 1,
far: 1e8,
});
const viewer = bindFakeCesiumCamera({ camera: { frustum } });
const range = rangeForBoundingSphere(viewer, 250);
assert.ok(
Math.abs(range - rangeFromFrustum(frustum, 250)) < 1e-6,
`${range} vs ${rangeFromFrustum(frustum, 250)}`,
);
});
}
test('framing without a camera assumes a 60 degree square view', () => {
const expected = rangeFromFrustum({ fov: Math.PI / 3, aspectRatio: 1 }, 100);
assert.ok(Math.abs(rangeForBoundingSphere({}, 100) - expected) < 1e-9);
});
-93
View File
@@ -1,93 +0,0 @@
// 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()] : [];
}
+2
View File
@@ -29,6 +29,7 @@ export const writeCalibrationStoreV2 = layer.writeCalibrationStoreV2;
export const deriveCalBadge = layer.deriveCalBadge;
export const computeFrustumGeometry = layer.computeFrustumGeometry;
export const activationProbeClampRange = layer.activationProbeClampRange;
export const flatGroundAxisDistance = layer.flatGroundAxisDistance;
export const frameSignatureFromPixels = layer.frameSignatureFromPixels;
export const _createCctvProjectionPlaneForTest =
layer._createCctvProjectionPlaneForTest;
@@ -65,6 +66,7 @@ export const materializeCctvVisibleCoverageEntities =
export const _extractPickedCameraIdForTest =
layer._extractPickedCameraIdForTest;
export const _setCctvCoverageStateForTest = layer._setCctvCoverageStateForTest;
export const _cctvIconsForTest = layer._cctvIconsForTest;
export const focusCctvRecord = layer.focusCctvRecord;
export const maybeAutoHop = layer.maybeAutoHop;
export const openingCameraId = layer.openingCameraId;
+189 -141
View File
@@ -13,6 +13,11 @@
//
// computeFrustumGeometry is PURE (no viewer, no scene queries) so it runs under
// plain node:test.
import {
bindFakeCesiumCamera,
followEntity,
} from '../testSupport/fakeCameraPort.mjs';
import { entityFollowTarget, followedOf } from './followed.js';
import { test } from 'node:test';
// Preserve structural pins across component qualification and formatter wrapping.
function componentFunctionSource(fn) {
@@ -32,9 +37,11 @@ import cctvLayer, {
_extractPickedCameraIdForTest,
_updateCctvProjectionPlaneForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_pushAmbientCardEntriesForTest,
_setCctvOverlayHostForTest,
activationProbeClampRange,
flatGroundAxisDistance,
bindCctvWorldClickGesture,
clearProbeClampOnDeactivation,
computeFrustumGeometry,
@@ -81,27 +88,12 @@ import {
IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
const ASPECT = 16 / 9;
const toRad = (deg) => (deg * Math.PI) / 180;
const GESTURE_TYPES = {
LEFT_DOWN: 'left-down',
MOUSE_MOVE: 'mouse-move',
LEFT_UP: 'left-up',
LEFT_CLICK: 'left-click',
};
function makeGestureHandler() {
const actions = new Map();
return {
setInputAction(callback, type) {
actions.set(type, callback);
},
fire(type, event) {
actions.get(type)?.(event);
},
};
}
const GESTURE_TYPES = FAKE_EVENT_TYPES;
// Same spherical earth radius projectPoint uses (R = 6371 km) so the
// lat/lon→metres conversion in the assertions matches the module's math.
const M_PER_DEG = (Math.PI / 180) * 6371000;
@@ -292,15 +284,9 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
coverageEntities: [],
projection: null,
}));
const inserted = [];
const viewer = {
entities: {
add(entity) {
inserted.push(entity);
return entity;
},
},
};
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const inserted = () => draw.find('cctv:')?.items ?? new Map();
const activeRecord = records.at(-1);
try {
@@ -315,10 +301,16 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
(record) => record.coverageEntities.length > 0,
);
assert.equal(
inserted.length,
inserted().size,
14 * 5,
'default COVERAGE ON builds the 14-camera visible cohort',
);
assert.ok(
[...inserted().keys()].every((id) =>
/^cctv-cam-\d+-(ray-..|cap)$/.test(id),
),
'coverage lines keep the cctv-<id>-<role> ids',
);
assert.equal(materialized.length, 14);
assert.equal(
activeRecord.coverageEntities.length,
@@ -334,7 +326,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
...records[0],
camera: { ...records[0].camera, id: 'projection-only' },
coverageEntities: [],
projection: { planeEntity: { show: false } },
projection: { plane: { show: false } },
};
_setCctvCoverageStateForTest({
viewer,
@@ -349,22 +341,31 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
projectionOnly.coverageEntities.every((entity) => entity.show),
'COVERAGE OFF keeps the active projection frustum materialized and visible',
);
assert.ok(
projectionOnly.coverageEntities.every(
(entity) => inserted().get(entity.id)?.show === true,
),
'and draws it',
);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
billboard: {},
// Every catalog record is placed as it is made, and drawn there.
position: { x: 6378137, y: 0, z: 0 },
coverageEntities: [],
projection: null,
});
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = { entities: { add: (entity) => entity } };
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
try {
// Disabled keeps the active video camera from opening a real projection;
@@ -377,18 +378,23 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
coverageMode: 'off',
});
refreshCoverageStyles();
assert.equal(idleVideo.billboard.color, LIVE_CAMERA_COLOR);
assert.equal(idleStill.billboard.color, IDLE_CAMERA_COLOR);
assert.equal(activeVideo.billboard.color, ACTIVE_CAMERA_COLOR);
const icons = _cctvIconsForTest();
const color = (record) => icons.item(record.camera.id).color;
assert.deepEqual(color(idleVideo), LIVE_CAMERA_COLOR);
assert.deepEqual(color(idleStill), IDLE_CAMERA_COLOR);
assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.equal(icons.item(idleVideo.camera.id).scale, 1);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
test('geometry drain pacing yields to tracked and cockpit camera ownership', () => {
assert.deepEqual(cctvGeometryDrainPacing(), { batchSize: 4, delayMs: 120 });
assert.deepEqual(
cctvGeometryDrainPacing({ trackedEntity: { id: 'flight-1' } }),
cctvGeometryDrainPacing({ followed: { key: 'flights:1' } }),
{ batchSize: 2, delayMs: 250 },
);
assert.deepEqual(cctvGeometryDrainPacing({ cockpitActive: true }), {
@@ -403,13 +409,13 @@ test('geometry drain pacing yields to tracked and cockpit camera ownership', ()
});
test('geometry drain rechecks pacing when tracking releases between batches', () => {
let trackedEntity = { id: 'flight-1' };
let followed = { key: 'flights:1' };
const queue = Array.from({ length: 10 }, (_, index) => index + 1);
const visited = [];
const runBatch = () =>
processCctvGeometryDrainBatch({
queue,
readOwnership: () => ({ trackedEntity, cockpitActive: false }),
readOwnership: () => ({ followed, cockpitActive: false }),
visit: (record) => visited.push(record),
progress: () => {},
complete: () => {},
@@ -419,7 +425,7 @@ test('geometry drain rechecks pacing when tracking releases between batches', ()
assert.deepEqual(trackedBatch, { hasMore: true, batchSize: 2, delayMs: 250 });
assert.deepEqual(visited, [1, 2]);
trackedEntity = null;
followed = null;
const untrackedBatch = runBatch();
assert.deepEqual(untrackedBatch, {
hasMore: true,
@@ -655,6 +661,17 @@ test('activation obstruction clamp uses the field-derived 12 m floor', () => {
assert.equal(activationProbeClampRange(210, 250), null);
});
test('on a globe map the axis ends on flat ground at the mount ground', () => {
// A 24 m mount pitched 30° down meets the ground 48 m along its axis.
assert.ok(Math.abs(flatGroundAxisDistance(24, -30) - 48) < 1e-9);
// The default 700 m range then clamps just short of that, not 700 m out.
const clamp = activationProbeClampRange(700, flatGroundAxisDistance(24, -30));
assert.ok(Math.abs(clamp - 44) < 1e-9);
assert.equal(flatGroundAxisDistance(24, 0), null);
assert.equal(flatGroundAxisDistance(24, 10), null);
assert.equal(flatGroundAxisDistance(0, -30), null);
});
test('deactivation clears the probe clamp and restores nominal frustum geometry', () => {
const record = {
camera: { ...UNCLAMPED_CAMERA },
@@ -684,18 +701,16 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
camera: { id: 'a' },
activationDone: true,
probeClampRangeM: 105,
billboard: { color: 'keep-color', scale: 1.25 },
coverageEntities: [{ show: true }, { show: true }],
projection: { planeEntity: { show: true } },
viewshedPrimitive: viewshedA,
projection: { plane: { show: true } },
viewshedVolume: viewshedA,
},
{
camera: { id: 'b' },
activationDone: true,
probeClampRangeM: 146,
billboard: { color: 'keep-color', scale: 1 },
projection: null,
viewshedPrimitive: viewshedB,
viewshedVolume: viewshedB,
},
];
const destroyed = [];
@@ -704,7 +719,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
records,
(record) => {
destroyed.push(record.camera.id);
record.viewshedPrimitive = null;
record.viewshedVolume = null;
},
'a',
);
@@ -715,10 +730,10 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
),
[false, false],
);
assert.equal(records[0].projection.planeEntity.show, false);
assert.equal(records[0].projection.plane.show, false);
assert.deepEqual(destroyed, ['a', 'b']);
assert.equal(records[0].viewshedPrimitive, null);
assert.equal(records[1].viewshedPrimitive, null);
assert.equal(records[0].viewshedVolume, null);
assert.equal(records[1].viewshedVolume, null);
assert.deepEqual(
records.map((record) => record.probeClampRangeM),
[null, null],
@@ -727,13 +742,6 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
records.map((record) => record.activationDone),
[false, true],
);
assert.deepEqual(
records.map((record) => record.billboard),
[
{ color: 'keep-color', scale: 1.25 },
{ color: 'keep-color', scale: 1 },
],
);
});
test('real active monitor plane owns one protected host label and no native label entity', () => {
@@ -743,7 +751,8 @@ test('real active monitor plane owns one protected host label and no native labe
setVisible: (...args) => calls.push(['visible', ...args]),
clearSource: (...args) => calls.push(['clear', ...args]),
};
const viewer = { entities: new Cesium.EntityCollection() };
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const record = {
camera: {
...UNCLAMPED_CAMERA,
@@ -767,17 +776,23 @@ test('real active monitor plane owns one protected host label and no native labe
});
refreshCoverageStyles();
assert.ok(runtime.plane, 'runtime guard requires a real monitor plane');
const planes = draw.find('cctv:')
? [...draw.sets.values()].filter((set) => set.kind === 'quads')
: [];
assert.equal(planes.length, 1, 'the plane draws as a quad');
const quad = planes[0].items.get(`cctv-${record.camera.id}-plane`);
assert.ok(quad, 'under its cctv-<id>-plane id');
assert.equal(quad.alpha, 0.95);
assert.deepEqual(quad.size, [
record.frustumGeometry.halfW * 2,
record.frustumGeometry.halfH * 2,
]);
assert.ok(quad.outline, 'with its outline');
assert.equal(quad.meta.cameraId, record.camera.id);
assert.ok(
runtime.planeEntity,
'runtime guard requires a real monitor-plane entity',
);
assert.equal(runtime.planeEntity.label, undefined);
assert.ok(
runtime.planeEntity.plane,
'monitor plane geometry remains native',
);
assert.ok(
viewer.entities.values.every((entity) => entity.label === undefined),
[...draw.sets.values()].every((set) => set.kind !== 'labels'),
'and no native label',
);
const publication = calls.find(
([type, sourceId]) =>
@@ -793,7 +808,8 @@ test('real active monitor plane owns one protected host label and no native labe
assert.equal(entry.position(), runtime.labelPosition);
assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'selected');
assert.equal(runtime.planeEntity.show, true);
assert.equal(runtime.plane.show, true);
assert.equal(quad.show, true, 'shown once projected');
const cachedPosition = runtime.labelPosition;
record.frustumPositions.label = Cesium.Cartesian3.add(
@@ -821,7 +837,8 @@ test('real active monitor plane owns one protected host label and no native labe
showProjection: false,
});
refreshCoverageStyles();
assert.equal(runtime.planeEntity.show, false);
assert.equal(runtime.plane.show, false);
assert.equal(planes[0].items.get(quad.id).show, false);
assert.deepEqual(calls.slice(-2), [
['clear', 'cctv-projection'],
['visible', 'cctv-projection', false],
@@ -829,6 +846,7 @@ test('real active monitor plane owns one protected host label and no native labe
} finally {
_setCctvCoverageStateForTest({ enabled: false });
_setCctvOverlayHostForTest();
unbind();
}
});
@@ -881,13 +899,18 @@ test('CCTV disable→enable defers the active-camera re-probe until its next act
test('CCTV focus distinguishes tracking ownership from a missing active camera', () => {
let flyCalls = 0;
const viewer = {
trackedEntity: { id: 'tracked-flight' },
camera: {
flyToBoundingSphere() {
flyCalls += 1;
},
},
// Cesium's entity tracking, without entities of its own: the camera
// port follows on a tracking widget of the fake's.
trackedEntityChanged: new Cesium.Event(),
entities: {},
};
bindFakeCesiumCamera(viewer);
followEntity(viewer, { id: 'tracked-flight' });
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -919,6 +942,7 @@ test('CCTV focus reports when the camera flight starts', () => {
},
},
};
bindFakeCesiumCamera(viewer);
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -939,6 +963,7 @@ test('CCTV focus refuses camera flights while cockpit owns the view', () => {
},
},
};
bindFakeCesiumCamera(viewer);
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -991,7 +1016,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
assert.deepEqual(requests, [{ cameraId: 'atx-cam-3' }]);
assert.match(
componentFunctionSource(cctvLayer.init),
/bindCctvWorldClickGesture\(_clickHandler/,
/bindCctvWorldClickGesture\(\s*input,/,
);
assert.match(
componentFunctionSource(cctvLayer.init),
@@ -1014,10 +1039,8 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
// ─── Empty-space deselection and stable null-active state ──────────────────
function makeDeselectViewer() {
return {
entities: new Cesium.EntityCollection(),
const viewer = {
isDestroyed: () => false,
trackedEntity: { id: 'sibling-track-owner' },
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 4_000),
positionCartographic: Cesium.Cartographic.fromDegrees(
@@ -1040,6 +1063,20 @@ function makeDeselectViewer() {
requestRender() {},
},
};
// The layer's lines and plane draw through this. The eye has a pose only
// once a test places it (`viewer.eye`, degrees and metres).
viewer.draw = bindFakeDraw(viewer, {
camera: {
pose: () => (viewer.eye ? { ...viewer.eye } : undefined),
on: () => () => {},
// A sibling layer's follow owns the camera.
followed: entityFollowTarget({ id: 'sibling-track-owner' }, {}),
follow(target) {
this.followed = target;
},
},
}).draw;
return viewer;
}
function makeDeselectRecord(id, index = 0) {
@@ -1073,7 +1110,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
assert.equal(cctvEmptyClickDeselects(null, { activeCameraId: null }), false);
assert.equal(
cctvEmptyClickDeselects(
{ id: 'registered-sibling' },
{ set: 'flights:1', id: 'registered-sibling', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1082,7 +1119,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ id: { id: 'unregistered-local-entity' } },
{ set: '', id: 'unregistered-local-entity', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1091,7 +1128,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ primitive: { id: 'unregistered-primitive' } },
{ set: '', id: 'unregistered-primitive', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1100,7 +1137,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ id: '' },
{ set: '', id: '', surface: false },
{
activeCameraId: 'cam-1',
},
@@ -1110,13 +1147,13 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
);
assert.equal(
cctvEmptyClickDeselects(
{ primitive: {} },
{ set: '', id: null, surface: false },
{
activeCameraId: 'cam-1',
},
),
true,
'an ID-less surface pick remains true empty space',
'something with no id remains true empty space',
);
const initSource = componentFunctionSource(cctvLayer.init);
@@ -1130,55 +1167,86 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
});
test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => {
const billboard = { id: 'shared-id' };
const ownedCoverageEntity = {
id: 'cctv-shared-id-cap',
properties: { cctvCameraId: 'shared-id' },
};
const record = {
...makeDeselectRecord('shared-id'),
billboard,
coverageEntities: [ownedCoverageEntity],
};
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const record = makeDeselectRecord('shared-id');
_setCctvCoverageStateForTest({
viewer,
records: [record],
activeCameraId: 'shared-id',
});
try {
refreshCoverageStyles();
const coverage = [...draw.sets.values()].find(
(set) => set.kind === 'lines' && set.spec.id.startsWith('cctv:'),
);
assert.ok(coverage.items.has('cctv-shared-id-cap'));
const lineHit = (set, id) => ({
set,
id,
meta: { cameraId: 'shared-id' },
surface: false,
});
assert.equal(
_extractPickedCameraIdForTest({ id: 'shared-id', primitive: billboard }),
_extractPickedCameraIdForTest({
set: _cctvIconsForTest().setId,
id: 'shared-id',
surface: false,
}),
'shared-id',
);
assert.equal(
_extractPickedCameraIdForTest({
set: 'sibling:1:icons',
id: 'shared-id',
primitive: { id: 'shared-id' },
surface: false,
}),
null,
'a sibling primitive with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: { id: 'shared-id' } }),
null,
'a sibling Entity with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: ownedCoverageEntity }),
'shared-id',
'an exact stored CCTV coverage Entity retains activation ownership',
"a sibling set's icon with the same canonical ID cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({
id: {
id: 'sibling-entity',
properties: { cctvCameraId: 'shared-id' },
},
set: _cctvIconsForTest().setId,
id: 'not-a-camera',
surface: false,
}),
null,
'an id the icon book does not draw is not a camera',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-cap'),
),
'shared-id',
'a coverage line the record draws retains activation ownership',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit('sibling:1:lines', 'cctv-shared-id-cap'),
),
null,
"a sibling set's item with a CCTV id and meta cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({
set: 'sibling:1:entities',
id: 'sibling-entity',
meta: { cctvCameraId: 'shared-id', cameraId: 'shared-id' },
surface: false,
}),
null,
'a sibling cannot impersonate CCTV by copying its property shape',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-stray'),
),
null,
'a camera id alone is not ownership: the record must draw the item',
);
} finally {
_setCctvCoverageStateForTest({ enabled: false });
unbind();
}
});
@@ -1219,7 +1287,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
transform: Cesium.Matrix4.clone(viewer.camera.transform),
trackedEntity: viewer.trackedEntity,
followed: followedOf(viewer),
};
assert.equal(deactivateActiveCamera(), true);
@@ -1232,7 +1300,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(publications.at(-1).activeCameraId, null);
assert.equal(publications.at(-1).activeCamera, null);
assert.equal(publications.at(-1).enabled, true);
assert.equal(runtime.planeEntity.show, false);
assert.equal(runtime.plane.show, false);
assert.equal(record.probeClampRangeM, null);
assert.equal(record.activationDone, false);
assert.deepEqual(viewer.camera.positionWC, pose.positionWC);
@@ -1244,7 +1312,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(viewer.camera.pitch, pose.pitch);
assert.equal(viewer.camera.roll, pose.roll);
assert.deepEqual(viewer.camera.transform, pose.transform);
assert.equal(viewer.trackedEntity, pose.trackedEntity);
assert.equal(followedOf(viewer), pose.followed);
assert.equal(viewer.camera.flyCalls || 0, 0);
unsubscribe();
} finally {
@@ -1302,16 +1370,7 @@ test('CCTV opens on the camera nearest the viewer, not the first in the catalog'
// QA 2026-11-05: at King's Cross, turning CCTV on showed a Sydney camera,
// the first catalog record, instead of the TfL camera 0.3 km away.
const viewer = makeDeselectViewer();
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 };
const sydney = makeDeselectRecord('au-sydney');
sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 };
const london = makeDeselectRecord('gb-kings-cross');
@@ -1346,11 +1405,7 @@ test('the opening camera follows a shared view that lands after CCTV turned on,
// A share link turns CCTV on before its flight lands, so enable() picks
// from the startup view; the flight's settled move re-picks near London.
const viewer = makeDeselectViewer();
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-0.1209,
51.5295,
187,
);
viewer.eye = { lon: -0.1209, lat: 51.5295, height: 187 };
const sydney = makeDeselectRecord('au-sydney');
sydney.camera = { ...sydney.camera, lat: -34.03, lon: 151.11 };
const london = makeDeselectRecord('gb-kings-cross');
@@ -1517,29 +1572,22 @@ test('active CCTV camera is absent from host by default and protected only when
test('CCTV drag-then-release over a camera is inert, while a clean tap activates and dispatches', () => {
let timeMs = 0;
let activationCalls = 0;
const handler = makeGestureHandler();
const { input, handler } = fakeInput({ scene: {} }, { now: () => timeMs });
const target = new EventTarget();
const requests = [];
target.addEventListener(CCTV_FOCUS_REQUEST_EVENT, (event) =>
requests.push(event.detail),
);
bindCctvWorldClickGesture(
handler,
() => {
activateCctvCameraFromWorldClick(
'atx-cam-3',
() => {
activationCalls += 1;
return CCTV_ACTIVATION_RESULT.ACTIVATED;
},
target,
);
},
{
now: () => timeMs,
eventTypes: GESTURE_TYPES,
},
);
bindCctvWorldClickGesture(input, () => {
activateCctvCameraFromWorldClick(
'atx-cam-3',
() => {
activationCalls += 1;
return CCTV_ACTIVATION_RESULT.ACTIVATED;
},
target,
);
});
handler.fire(GESTURE_TYPES.LEFT_DOWN, { position: { x: 10, y: 10 } });
timeMs = 20;
+241 -224
View File
@@ -8,7 +8,7 @@
* - Pure drag math (this top section): ray↔axis closest-point, ray↔plane
* intersection with a grazing-angle guard, ring angles. All unit-tested
* under node:test with zero scene dependencies.
* - createCalibrationGizmo (below): the entity + ScreenSpaceEventHandler
* - createCalibrationGizmo (below): the draw-set + pointer-input
* controller that renders grab-able handles on the ACTIVE camera and turns
* drags into calibration patches through a narrow callback interface. It
* never touches the layer's records/stores directly.
@@ -23,8 +23,10 @@
* throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query
* invariant is untouched.
*/
import * as Cesium from 'cesium';
import { isPointerFree } from './inputOwnership.js';
import { inputFor } from '../input/dispatcher.js';
import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js';
import { eastNorthUp } from '../geo/frames.js';
import { add, dot, scale, sub } from '../geo/vector.js';
// Grazing guard (spec §5): reject plane intersections when the view ray is
// nearly parallel to the constraint plane — the hit point races to infinity
@@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08;
// Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²).
const PARALLEL_EPS = 1e-6;
const scratchW = new Cesium.Cartesian3();
/**
* Parameter t (metres) along an axis line of the point on that axis closest
* to a mouse ray. Both directions must be normalized.
@@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3();
* t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin,
* d = rayDir·w, e = axisDir·w.
*
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} axisOrigin
* @param {Cesium.Cartesian3} axisDir - Unit.
* Vectors are ECEF `{x, y, z}`.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} axisOrigin
* @param {{x: number, y: number, z: number}} axisDir - Unit.
* @returns {number|null} Axis parameter in metres, or null when near-parallel.
*/
export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) {
const b = Cesium.Cartesian3.dot(rayDir, axisDir);
const b = dot(rayDir, axisDir);
const denom = 1 - b * b;
if (Math.abs(denom) < PARALLEL_EPS) return null;
const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW);
const d = Cesium.Cartesian3.dot(rayDir, w);
const e = Cesium.Cartesian3.dot(axisDir, w);
const w = sub(rayOrigin, axisOrigin);
const d = dot(rayDir, w);
const e = dot(axisDir, w);
return (e - b * d) / denom;
}
/**
* Intersects a mouse ray with a plane, refusing grazing configurations
* (|rayDir·normal| < 0.08) and hits behind the ray origin.
* @param {Cesium.Cartesian3} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit.
* @param {Cesium.Cartesian3} planeOrigin
* @param {Cesium.Cartesian3} planeNormal - Unit.
* @returns {Cesium.Cartesian3|null} Hit point (new instance), or null.
* @param {{x: number, y: number, z: number}} rayOrigin
* @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {{x: number, y: number, z: number}} planeOrigin
* @param {{x: number, y: number, z: number}} planeNormal - Unit.
* @returns {{x: number, y: number, z: number}|null} Hit point (new), or null.
*/
export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
const denom = Cesium.Cartesian3.dot(rayDir, planeNormal);
const denom = dot(rayDir, planeNormal);
if (Math.abs(denom) < GRAZING_DOT_MIN) return null;
const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW);
const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom;
const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom;
if (s < 0) return null;
const hit = Cesium.Cartesian3.multiplyByScalar(
rayDir,
s,
new Cesium.Cartesian3(),
);
return Cesium.Cartesian3.add(rayOrigin, hit, hit);
return add(rayOrigin, scale(rayDir, s));
}
/**
* Angle (radians, atan2 convention) of a point around a ring center in the
* plane spanned by two orthonormal basis vectors.
* @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane.
* @param {Cesium.Cartesian3} center - Ring center.
* @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0).
* @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°).
* @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane.
* @param {{x: number, y: number, z: number}} center - Ring center.
* @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0).
* @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°).
* @returns {number} Angle in (−π, π].
*/
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),
);
const v = sub(hitPoint, center);
return Math.atan2(dot(v, basisB), dot(v, basisA));
}
/**
@@ -117,9 +109,9 @@ export function signedAngleDelta(fromRad, toRad) {
// Gizmo controller
// ---------------------------------------------------------------------------
/** Entity id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo entities NEVER carry a
* `cctvCameraId` property, so the layer's selection path ignores them. */
/** Item id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo parts NEVER get a camera id in
* the layer's pick store, so the layer's selection path ignores them. */
export const GIZMO_ID_PREFIX = 'cctv-gizmo-';
const RING_SEGMENTS = 96;
@@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6;
const DRAG_THROTTLE_MS = 16;
const HOVER_THROTTLE_MS = 120;
const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff');
const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0');
const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252');
const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a');
const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff');
const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a');
/** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */
function rgba(hex, alpha = 1) {
const n = Number.parseInt(hex.slice(1), 16);
return [
((n >> 16) & 255) / 255,
((n >> 8) & 255) / 255,
(n & 255) / 255,
alpha,
];
}
const COLOR_RING_HEADING = '#35d8ff';
const COLOR_RING_PITCH = '#ff5fd0';
const COLOR_MOVE_EAST = '#ff5252';
const COLOR_MOVE_NORTH = '#52ff7a';
const COLOR_MOVE_UP = '#5b8cff';
const COLOR_HANDLE = '#ffd97a';
const HANDLE_OUTLINE = [0, 0, 0, 0.7];
const toRadians = (deg) => (deg * Math.PI) / 180;
const toDeg = (rad) => (rad * 180) / Math.PI;
/**
* Local ENU unit axes at an ECEF position.
* @param {Cesium.Cartesian3} position
* @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}}
* @param {{x: number, y: number, z: number}} position
* @returns {{east: object, north: object, up: object}}
*/
function enuAxes(position) {
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3());
return {
east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()),
north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()),
up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()),
};
const frame = eastNorthUp(position);
return { east: frame.x, north: frame.y, up: frame.z };
}
/** a*sa + b*sb (fresh Cartesian3). */
/** a*sa + b*sb. */
function combine2(a, sa, b, sb) {
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);
return add(scale(a, sa), scale(b, sb));
}
/** The midpoint of two points. */
const midpoint = (a, b) => scale(add(a, b), 0.5);
/**
* View-frame unit vectors for a pose within a local ENU frame: horizontal
* forward, viewer-right, and the full pitched view axis.
@@ -192,25 +188,57 @@ 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,
positions.push(
add(
center,
combine2(
basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
),
),
);
positions.push(Cesium.Cartesian3.add(center, offset, offset));
}
return positions;
}
/** The ring and arrow parts: their colour, width and whether an arrow. */
const LINE_PARTS = Object.freeze([
['ring-heading', COLOR_RING_HEADING, 3, false],
['ring-pitch', COLOR_RING_PITCH, 3, false],
['move-east', COLOR_MOVE_EAST, 12, true],
['move-north', COLOR_MOVE_NORTH, 12, true],
['move-up', COLOR_MOVE_UP, 12, true],
]);
/** The point parts (an arrow's tip included): colour and first size. */
const POINT_PARTS = Object.freeze([
['move-east', COLOR_MOVE_EAST, 14],
['move-north', COLOR_MOVE_NORTH, 14],
['move-up', COLOR_MOVE_UP, 14],
['handle-range', COLOR_HANDLE, 13],
['handle-fov-l', COLOR_HANDLE, 10],
['handle-fov-r', COLOR_HANDLE, 10],
]);
/** Every part a pick can grab. */
const PARTS = new Set([
...LINE_PARTS.map(([part]) => part),
...POINT_PARTS.map(([part]) => part),
]);
let gizmoInstances = 0;
/**
* Creates the calibration gizmo controller (design §3c). Renders grab-able
* handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags
* into calibration patches through a narrow callback interface — the gizmo
* never touches layer records/stores directly.
* never touches layer records/stores directly. It draws through the
* renderer's draw port (a line set for the rings and arrows, a point set
* for the handles and arrow tips, each item `cctv-gizmo-<part>`) and picks
* and casts rays through its query port.
*
* @param {Object} deps
* @param {Cesium.Viewer} deps.viewer
* @param {object} deps.viewer - The viewer whose renderer draws it.
* @param {function(): Object|null} deps.getActiveRecord - Returns the record
* the gizmo should attach to, or null to hide (layer decides: enabled +
* calibration mode + active camera).
@@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) {
* end, for the PINNED drag record.
* @returns {{setEnabled: function(boolean): void, refresh: function(): void,
* destroy: function(): void, isDragging: function(): boolean,
* isEnabled: function(): boolean}}
* isEnabled: function(): boolean, partsForTest: function(): Object}}
*/
export function createCalibrationGizmo({
viewer,
@@ -234,73 +262,70 @@ export function createCalibrationGizmo({
let hoveredId = null;
let lastDragAt = 0;
let lastHoverAt = 0;
const entities = new Map(); // part -> Entity
// Whether the parts are drawn now, and each point part's pixel size.
let shown = false;
const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size]));
// The parts' geometry as last drawn: ECEF line positions and point spots.
const linePositions = new Map();
const pointPositions = new Map();
const scene = viewer.scene;
const handler = new Cesium.ScreenSpaceEventHandler(scene.canvas);
const input = inputFor(viewer);
let releaseCamera = null;
/** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */
function addEntity(part, options) {
const id = `${GIZMO_ID_PREFIX}${part}`;
const stale = viewer.entities.getById(id);
if (stale) viewer.entities.remove(stale);
const entity = viewer.entities.add({ id, show: false, ...options });
entities.set(part, entity);
return entity;
}
const instance = ++gizmoInstances;
const draw = drawOf(viewer);
const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` });
const points = draw.points({ id: `cctv-gizmo:${instance}:points` });
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,
},
}
: {}),
polyline: {
positions: [],
width,
material: arrow
? new Cesium.PolylineArrowMaterialProperty(color)
: color.withAlpha(0.9),
/** The rings and arrows as they now are. */
function lineItems() {
const items = [];
for (const [part, color, widthPx, arrow] of LINE_PARTS) {
const positions = linePositions.get(part);
if (!positions) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
positions,
widthPx,
mode: '3d',
style: arrow
? { kind: 'arrow', color: rgba(color) }
: { kind: 'solid', color: rgba(color, 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).
depthFailMaterial: color.withAlpha(0.45),
},
});
depthFail: { kind: 'solid', color: rgba(color, 0.45) },
show: shown,
});
}
return items;
}
function pointPart(part, color, pixelSize) {
addEntity(part, {
position: Cesium.Cartesian3.ZERO,
point: {
pixelSize,
color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7),
/** The handles and arrow tips as they now are. */
function pointItems() {
const items = [];
for (const [part, color] of POINT_PARTS) {
const pos = pointPositions.get(part);
if (!pos) continue;
items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
pos,
pixelSize: pointSizes.get(part),
color: rgba(color),
outlineColor: HANDLE_OUTLINE,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
disableDepthTest: Number.POSITIVE_INFINITY,
show: shown,
});
}
return items;
}
polylinePart('ring-heading', COLOR_RING_HEADING, 3);
polylinePart('ring-pitch', COLOR_RING_PITCH, 3);
polylinePart('move-east', COLOR_MOVE_EAST, 12, true);
polylinePart('move-north', COLOR_MOVE_NORTH, 12, true);
polylinePart('move-up', COLOR_MOVE_UP, 12, true);
pointPart('handle-range', COLOR_HANDLE, 13);
pointPart('handle-fov-l', COLOR_HANDLE, 10);
pointPart('handle-fov-r', COLOR_HANDLE, 10);
function hideAll() {
for (const entity of entities.values()) entity.show = false;
if (!shown) return;
shown = false;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Recomputes every handle's geometry from the active record's CURRENT pose
@@ -328,69 +353,52 @@ export function createCalibrationGizmo({
);
const arrowLen = radius * ARROW_LENGTH_FACTOR;
entities.get('ring-heading').polyline.positions = ringPositions(
mount,
radius,
axes.north,
axes.east,
linePositions.set(
'ring-heading',
ringPositions(mount, radius, axes.north, axes.east),
);
entities.get('ring-pitch').polyline.positions = ringPositions(
mount,
radius,
forwardHoriz,
axes.up,
linePositions.set(
'ring-pitch',
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);
entities.get('move-east').polyline.positions = eastArrow;
entities.get('move-east').position = eastArrow[1];
entities.get('move-north').polyline.positions = northArrow;
entities.get('move-north').position = northArrow[1];
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(),
);
for (const entity of entities.values()) entity.show = true;
const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))];
for (const [part, dir] of [
['move-east', axes.east],
['move-north', axes.north],
['move-up', axes.up],
]) {
const arrow = arrowTo(dir);
linePositions.set(part, arrow);
pointPositions.set(part, arrow[1]);
}
pointPositions.set('handle-range', positions.capCenter);
pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl));
pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br));
shown = true;
lines.upsert(lineItems());
points.upsert(pointItems());
}
/** Extracts a gizmo part name from a pick result, or null. */
function gizmoPartFrom(picked) {
const id = picked?.id?.id ?? picked?.id;
/** The gizmo part a pick hit is, or null. */
function gizmoPartFrom(hit) {
if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null;
const id = hit.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null;
return id.slice(GIZMO_ID_PREFIX.length);
const part = id.slice(GIZMO_ID_PREFIX.length);
return PARTS.has(part) ? part : null;
}
function pickGizmoPart(windowPosition) {
const query = findQuery(viewer);
if (!query || !windowPosition) return null;
const { x, y } = windowPosition;
// Gizmo primitives render depth-test-free and should be the topmost pick.
// Take the cheap single-result path first: a full drillPick can stall for
// tens of seconds under software GL even when its first result is already
// the gizmo. Retain drillPick for uncommon overlap/fallback cases.
try {
const picked = scene.pick(windowPosition, 14, 14);
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 }));
if (part && shown) return part;
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] pick threw:', err?.message || err);
@@ -399,7 +407,8 @@ export function createCalibrationGizmo({
let results = [];
try {
results = scene.drillPick(windowPosition, 6, 14, 14) || [];
results =
query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || [];
} catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err);
@@ -409,52 +418,54 @@ export function createCalibrationGizmo({
if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug(
'[CCTV:gizmo] drillPick @',
windowPosition?.x,
windowPosition?.y,
x,
y,
'→',
JSON.stringify(
results.map((r) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name),
results.map((hit) =>
hit.surface ? '(surface)' : `${hit.set}/${hit.id}`,
),
),
);
}
for (const picked of results) {
const part = gizmoPartFrom(picked);
if (part && entities.get(part)?.show) return part;
for (const hit of results) {
const part = gizmoPartFrom(hit);
if (part && shown) return part;
}
return null;
}
function pickRay(windowPosition) {
try {
return viewer.camera.getPickRay(windowPosition) || null;
return (
findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null
);
} catch {
return null;
}
}
function setCursor(value) {
if (scene.canvas?.style) scene.canvas.style.cursor = value;
const style = canvasOf(viewer)?.style;
if (style) style.cursor = value;
}
function setHovered(part) {
const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null;
if (nextId === hoveredId) return;
hoveredId = nextId;
// Hover feedback must NEVER touch polyline geometry: a width change makes
// Cesium rebuild the batched polyline primitive, and until the next render
// the part vanishes from the pick buffer — so the very hover that finds a
// ring makes the following LEFT_DOWN miss it (root-caused via the QA
// harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback
// only; point handles are PointPrimitives (live-updatable, no rebuild), so
// they keep the size bump.
for (const [name, entity] of entities.entries()) {
if (!entity.point) continue;
// Hover feedback must NEVER touch line geometry: a width change rebuilds
// the line, and until the next render the part vanishes from the pick
// buffer — so the very hover that finds a ring makes the following
// LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag,
// 2026-07-05). Rings/arrows get cursor feedback only; point handles
// (an arrow's tip included) change size in place, so they keep the size
// bump.
for (const [name] of POINT_PARTS) {
const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`;
entity.point.pixelSize =
(name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0));
}
points.upsert(pointItems());
setCursor(hoveredId ? 'grab' : '');
}
@@ -468,8 +479,8 @@ export function createCalibrationGizmo({
const ray = pickRay(windowPosition);
if (!ray) return false;
const mount = Cesium.Cartesian3.clone(positions.mount);
const capCenter = Cesium.Cartesian3.clone(positions.capCenter);
const mount = { ...positions.mount };
const capCenter = { ...positions.capCenter };
const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg,
@@ -533,9 +544,7 @@ export function createCalibrationGizmo({
drag = state;
setCursor('grabbing');
if (scene.screenSpaceCameraController) {
scene.screenSpaceCameraController.enableInputs = false;
}
releaseCamera = input.suspendCamera('cctv-gizmo-drag');
return true;
}
@@ -596,12 +605,7 @@ export function createCalibrationGizmo({
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(dot(sub(hit, capCenter), right));
const halfW = Math.max(0.5, lateral);
const fovDeg = toDeg(
2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)),
@@ -615,9 +619,8 @@ export function createCalibrationGizmo({
if (!drag) return;
const record = drag.record;
drag = null;
if (scene.screenSpaceCameraController) {
scene.screenSpaceCameraController.enableInputs = true;
}
releaseCamera?.();
releaseCamera = null;
setCursor(hoveredId ? 'grab' : '');
endPatch(record);
}
@@ -629,18 +632,21 @@ export function createCalibrationGizmo({
}
}
handler.setInputAction((event) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the press.
if (!isPointerFree()) return;
// An ambient press: the dispatcher withholds it while a tool owns the pointer
// (src/data/inputOwnership.js).
const offDown = input.onPointer('down', (event) => {
if (!enabled) return;
// A release Cesium never reported (one with a modifier key held) leaves
// the last drag open; a new press ends it, hold and patch included.
if (drag) endDrag();
const part = pickGizmoPart(event.position);
debugLog('LEFT_DOWN', event.position, 'part:', part);
if (!part) return;
const started = beginDrag(part, event.position);
debugLog('beginDrag', part, '→', started);
}, Cesium.ScreenSpaceEventType.LEFT_DOWN);
});
handler.setInputAction((event) => {
const offMove = input.onPointer('move', (event) => {
if (!enabled) return;
const now = Date.now();
if (drag) {
@@ -667,12 +673,12 @@ export function createCalibrationGizmo({
if (now - lastHoverAt < HOVER_THROTTLE_MS) return;
lastHoverAt = now;
setHovered(pickGizmoPart(event.endPosition));
}, Cesium.ScreenSpaceEventType.MOUSE_MOVE);
});
handler.setInputAction(() => {
const offUp = input.onPointer('up', () => {
if (!enabled) return;
endDrag();
}, Cesium.ScreenSpaceEventType.LEFT_UP);
});
return {
setEnabled(value) {
@@ -688,14 +694,25 @@ export function createCalibrationGizmo({
refresh,
destroy() {
if (drag) endDrag();
handler.destroy();
for (const entity of entities.values()) {
viewer.entities.remove(entity);
}
entities.clear();
offDown();
offMove();
offUp();
lines.dispose();
points.dispose();
setCursor('');
},
isDragging: () => !!drag,
isEnabled: () => enabled,
/**
* The parts as last drawn, by item id, for the QA harness: whether each
* shows, a line's `positions` and a point's `pos` (an arrow has both).
*/
partsForTest() {
const parts = {};
for (const item of [...lineItems(), ...pointItems()])
parts[item.id] = { ...parts[item.id], ...item };
for (const item of lineItems()) parts[item.id].show = item.show;
return parts;
},
};
}
+351 -19
View File
@@ -8,66 +8,99 @@
// - rayPlaneIntersect refuses grazing rays (|dir·normal| < 0.08 — spec §5
// precision guard) and behind-origin hits;
// - ringAngle/signedAngleDelta give quadrant-correct, wrap-safe angles for
// the heading/pitch ring drags.
// the heading/pitch ring drags;
// - the controller ends an open drag, and its camera hold, on the next press.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
GIZMO_ID_PREFIX,
closestParamOnAxis,
createCalibrationGizmo,
rayPlaneIntersect,
ringAngle,
signedAngleDelta,
} from './cctvGizmo.js';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fromDegrees } from '../geo/ellipsoid.js';
import { add, distance, negate, normalize, scale } from '../geo/vector.js';
const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z);
const c3 = (x, y, z) => ({ x, y, z });
test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => {
// Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5):
// nearest axis point is x=10 → t=10.
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(0, 0, 0), c3(1, 0, 0));
const t = closestParamOnAxis(
c3(10, 0, 5),
c3(0, 0, -1),
c3(0, 0, 0),
c3(1, 0, 0),
);
assert.ok(Math.abs(t - 10) < 1e-9, `expected 10, got ${t}`);
});
test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => {
// Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the
// axis around x=10 (it reaches y=0 at x=10).
const dir = Cesium.Cartesian3.normalize(c3(1, -1, 0), new Cesium.Cartesian3());
const dir = normalize(c3(1, -1, 0));
const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0));
assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`);
});
test('closestParamOnAxis: axis origin offset shifts the parameter', () => {
const t = closestParamOnAxis(c3(10, 0, 5), c3(0, 0, -1), c3(4, 0, 0), c3(1, 0, 0));
const t = closestParamOnAxis(
c3(10, 0, 5),
c3(0, 0, -1),
c3(4, 0, 0),
c3(1, 0, 0),
);
assert.ok(Math.abs(t - 6) < 1e-9, `expected 6, got ${t}`);
});
test('closestParamOnAxis: near-parallel ray/axis returns null', () => {
assert.equal(closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), null);
const nearly = Cesium.Cartesian3.normalize(c3(1, 1e-9, 0), new Cesium.Cartesian3());
assert.equal(closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), null);
assert.equal(
closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)),
null,
);
const nearly = normalize(c3(1, 1e-9, 0));
assert.equal(
closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)),
null,
);
});
test('rayPlaneIntersect: straight-on hit lands at the expected point', () => {
const hit = rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, -1), c3(0, 0, 0), c3(0, 0, 1));
const hit = rayPlaneIntersect(
c3(0, 0, 10),
c3(0, 0, -1),
c3(0, 0, 0),
c3(0, 0, 1),
);
assert.ok(hit, 'expected a hit');
assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9);
assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9);
});
test('rayPlaneIntersect: oblique hit resolves correctly', () => {
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -1), new Cesium.Cartesian3());
const dir = normalize(c3(1, 0, -1));
const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1));
assert.ok(hit);
assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`);
assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`);
});
test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => {
// dir almost in-plane: z component 0.05 < 0.08 threshold.
const dir = Cesium.Cartesian3.normalize(c3(1, 0, -0.05), new Cesium.Cartesian3());
assert.equal(rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), null);
const dir = normalize(c3(1, 0, -0.05));
assert.equal(
rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)),
null,
);
});
test('rayPlaneIntersect: plane behind the ray origin returns null', () => {
assert.equal(rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)), null);
assert.equal(
rayPlaneIntersect(c3(0, 0, 10), c3(0, 0, 1), c3(0, 0, 0), c3(0, 0, 1)),
null,
);
});
test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
@@ -75,9 +108,15 @@ test('ringAngle: quadrant sweep in the (basisA, basisB) frame', () => {
const a = c3(1, 0, 0);
const b = c3(0, 1, 0);
assert.ok(Math.abs(ringAngle(c3(5, 0, 0), center, a, b) - 0) < 1e-9);
assert.ok(Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9);
assert.ok(Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9);
assert.ok(Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9);
assert.ok(
Math.abs(ringAngle(c3(0, 5, 0), center, a, b) - Math.PI / 2) < 1e-9,
);
assert.ok(
Math.abs(Math.abs(ringAngle(c3(-5, 0, 0), center, a, b)) - Math.PI) < 1e-9,
);
assert.ok(
Math.abs(ringAngle(c3(0, -5, 0), center, a, b) + Math.PI / 2) < 1e-9,
);
});
test('signedAngleDelta: shortest-path wrap', () => {
@@ -86,3 +125,296 @@ test('signedAngleDelta: shortest-path wrap', () => {
assert.ok(Math.abs(signedAngleDelta(d2r(-170), d2r(170)) - d2r(-20)) < 1e-9);
assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9);
});
/**
* A viewer double drawing through a fake draw port, whose query port picks
* `picked` and casts the ray `ray` (a ray,
* or a function of the window position).
*/
function gizmoViewer(t, { picked, ray }) {
const viewer = {
scene: {
canvas: { style: {} },
screenSpaceCameraController: { enableInputs: true },
},
};
const queries = [];
const { draw, unbind } = bindFakeDraw(viewer, {
query: {
pick: (x, y, window) => (queries.push(['pick', window]), picked()),
drillPick: (x, y, options) => (queries.push(['drill', options]), []),
pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray),
},
});
t.after(unbind);
return { viewer, draw, queries };
}
const mount = fromDegrees(0, 0, 10);
const east = c3(0, 1, 0); // east at lon 0, lat 0
const gizmoRecord = () => ({
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
});
test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => {
const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
const lines = draw.find('cctv-gizmo:');
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
assert.equal(lines.kind, 'lines');
assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
assert.deepEqual(
[...lines.items.keys()],
['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map(
(part) => GIZMO_ID_PREFIX + part,
),
);
assert.deepEqual(
[...points.items.keys()],
[
'move-east',
'move-north',
'move-up',
'handle-range',
'handle-fov-l',
'handle-fov-r',
].map((part) => GIZMO_ID_PREFIX + part),
);
const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`);
assert.equal(ring.mode, '3d');
assert.equal(ring.widthPx, 3);
assert.equal(ring.positions.length, 97, 'a closed 96-segment ring');
assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12);
assert.ok(Math.abs(ring.depthFail.color[3] - 0.45) < 1e-12);
const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.equal(arrow.style.kind, 'arrow');
assert.equal(arrow.widthPx, 12);
// The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up.
assert.ok(
distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6,
);
const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.deepEqual(tip.pos, arrow.positions[1]);
assert.equal(tip.pixelSize, 14);
assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => item.show,
),
);
gizmo.setEnabled(false);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => !item.show,
),
'hidden off ADJUST',
);
gizmo.destroy();
assert.equal(lines.disposed, true);
assert.equal(points.disposed, true);
});
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
let lineSet = null;
const { viewer, draw, queries } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-up`,
surface: false,
}),
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const ended = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch: (r) => ended.push(r),
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
const controller = viewer.scene.screenSpaceCameraController;
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]);
assert.equal(controller.enableInputs, false);
// The release came with a modifier key held: Cesium raised no LEFT_UP.
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.deepEqual(ended, [record], 'the open drag was committed');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false);
assert.equal(controller.enableInputs, true, 'no hold was stranded');
});
test('a pick of another set or a stray id is no gizmo part', (t) => {
let picked = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => picked,
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
gizmo.setEnabled(true);
picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false };
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'another set');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
picked = {
set: draw.find('cctv-gizmo:').spec.id,
id: `${GIZMO_ID_PREFIX}nothing`,
surface: false,
};
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'no such part');
});
test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => {
const up = c3(1, 0, 0); // up at lon 0, lat 0
let lineSet = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-east`,
surface: false,
}),
// Straight down onto the east axis, `x` metres east of the mount.
ray: (x) => ({
origin: add(add(mount, scale(east, x)), scale(up, 100)),
direction: negate(up),
}),
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
record.camera.calibration = { offsetEastM: 2 };
const patches = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch: (patch, pinned) => patches.push([patch, pinned]),
endPatch() {},
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.equal(viewer.scene.canvas.style.cursor, 'grabbing');
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 12, y: 5 },
});
assert.equal(patches.length, 1);
const [patch, pinned] = patches[0];
assert.equal(pinned, record, 'patched on the record dragged');
assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`);
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } });
assert.equal(gizmo.isDragging(), false);
});
test('hovering a handle grows it and shows the grab cursor', (t) => {
let pointSet = null;
let over = true;
const { viewer, draw } = gizmoViewer(t, {
picked: () =>
over
? {
set: pointSet,
id: `${GIZMO_ID_PREFIX}handle-range`,
surface: false,
}
: null,
ray: null,
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
pointSet = points.spec.id;
gizmo.setEnabled(true);
const size = () =>
points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize;
assert.equal(size(), 13);
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 6, y: 5 },
});
assert.equal(size(), 17);
assert.equal(viewer.scene.canvas.style.cursor, 'grab');
});
test('the harness reads each part as drawn, an arrow with its line and tip', (t) => {
const { viewer } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
const parts = gizmo.partsForTest();
const arrow = parts[`${GIZMO_ID_PREFIX}move-east`];
assert.equal(arrow.positions.length, 2, 'its line');
assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip');
assert.equal(arrow.show, true);
assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true);
assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos);
gizmo.setEnabled(false);
assert.ok(
Object.values(gizmo.partsForTest()).every((part) => part.show === false),
);
});
+88 -69
View File
@@ -2,10 +2,13 @@
// near the screen show, a zoomed-out view keeps one camera per world-anchored
// cell, and the layer's UI state never rebuilds every camera for a listener
// that does not read the list.
import { test } from 'node:test';
import { afterEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_setCctvCoverageStateForTest,
_viewRecordIdsForTest,
refreshHorizonCulling,
@@ -14,18 +17,10 @@ import cctvLayer, {
const WIDTH = 800;
const HEIGHT = 600;
/**
* Records at the given [lon, lat] degrees near the origin, each drawn at the
* screen point `screenAt` gives it (default: the middle of the screen).
*/
function recordsAt(
lonLats,
screenAt = () => ({ x: WIDTH / 2, y: HEIGHT / 2 }),
) {
const screenByPosition = new Map();
/** Records at the given [lon, lat] degrees near the origin. */
function recordsAt(lonLats) {
const records = lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10);
screenByPosition.set(position, screenAt(index));
return {
camera: {
id: `cam-${index}`,
@@ -39,36 +34,62 @@ function recordsAt(
rangeM: 145,
mountHeightM: 8,
},
position,
billboard: { position, show: true },
position: { x: position.x, y: position.y, z: position.z },
coverageEntities: [],
projection: null,
};
});
return { records, screenByPosition };
return { records };
}
function viewerAt(heightM, screenByPosition, shiftX = 0) {
return {
isDestroyed: () => false,
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM),
positionCartographic: { latitude: 0, longitude: 0, height: heightM },
frustum: { fovy: Math.PI / 3 },
/**
* A viewer looking straight down from `heightM` over `lonDeg` on the
* equator, north up, through a camera port: the view pass projects the
* cameras from its pose.
*/
function viewerAt(heightM, lonDeg = 0) {
const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const north = { x: 0, y: 0, z: 1 };
const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3());
const { port } = fakeCameraPort({
pose: {
lon: lonDeg,
lat: 0,
height: heightM,
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: north,
right: { x: right.x, y: right.y, z: right.z },
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
scene: {
});
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
cartesianToCanvasCoordinates: (position) => {
const screen = screenByPosition.get(position);
return screen && { x: screen.x + shiftX, y: screen.y };
},
},
};
}),
);
return viewer;
}
/** The renderers bound for the running test, let go when it ends. */
const bindings = [];
afterEach(() => {
for (const unbind of bindings.splice(0)) unbind();
});
function shownIds(records) {
const icons = _cctvIconsForTest();
return records
.filter((record) => record.billboard.show)
.filter((record) => icons.item(record.camera.id)?.show === true)
.map((record) => record.camera.id)
.sort();
}
@@ -82,9 +103,9 @@ const CLUSTER = [
];
test('zoomed out, cameras sharing a ground cell show one icon', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
});
assert.equal(
@@ -99,34 +120,34 @@ test('zoomed out, cameras sharing a ground cell show one icon', () => {
});
test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
const { records, screenByPosition } = recordsAt(CLUSTER, (index) => ({
x: 100 + index * 7,
y: 300,
}));
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
});
refreshHorizonCulling();
const before = shownIds(records);
const list = _viewRecordIdsForTest();
for (const shiftX of [3, 11, 20, 37]) {
// A pan of a few to some 40 px (a pixel is about 30 m from 20 km up).
for (const shiftM of [90, 330, 600, 1110]) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition, shiftX),
viewer: viewerAt(20_000, shiftM / 111_320),
records,
});
refreshHorizonCulling();
assert.deepEqual(shownIds(records), before, `pan by ${shiftX} px`);
assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`);
}
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing');
assert.deepEqual(_viewRecordIdsForTest(), list);
});
test('a small zoom within one cell size keeps the same winners', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
const shownAt = (heightM) => {
_setCctvCoverageStateForTest({
viewer: viewerAt(heightM, screenByPosition),
viewer: viewerAt(heightM),
records,
});
refreshHorizonCulling();
@@ -138,11 +159,11 @@ test('a small zoom within one cell size keeps the same winners', () => {
});
test('a healthy camera wins its cell over an unknown one', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2));
const { records } = recordsAt(CLUSTER.slice(0, 2));
// Whichever camera the id order would pick, the healthy one must win.
for (const id of ['cam-0', 'cam-1']) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
healthById: new Map([[id, { status: 'ok' }]]),
});
@@ -152,30 +173,31 @@ test('a healthy camera wins its cell over an unknown one', () => {
});
test('the active camera always shows, even in a crowded cell', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3));
const { records } = recordsAt(CLUSTER.slice(0, 3));
for (const active of records) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
activeCameraId: active.camera.id,
});
refreshHorizonCulling();
assert.ok(active.billboard.show, `${active.camera.id} shows while active`);
const icons = _cctvIconsForTest();
assert.ok(
icons.item(active.camera.id).show,
`${active.camera.id} shows while active`,
);
}
});
test('close up, every camera near the screen shows and far-off ones hide', () => {
const { records, screenByPosition } = recordsAt(
[
[0, 0],
[0.0001, 0],
[0.0002, 0],
],
(index) =>
index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 },
);
// From 300 m up the screen spans some 460 m: the third camera is 1.1 km off.
const { records } = recordsAt([
[0, 0],
[0.0001, 0],
[0.01, 0],
]);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
});
refreshHorizonCulling();
@@ -183,9 +205,9 @@ test('close up, every camera near the screen shows and far-off ones hide', () =>
});
test('a disabled layer skips the view pass', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
viewer: viewerAt(20_000),
records,
enabled: false,
});
@@ -194,9 +216,9 @@ test('a disabled layer skips the view pass', () => {
});
test('UI state builds the full camera list only when it is read', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2));
const { records } = recordsAt(CLUSTER.slice(0, 2));
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
});
refreshHorizonCulling();
@@ -227,16 +249,13 @@ test('UI state builds the full camera list only when it is read', () => {
});
test('the camera picker lists the view, with the active camera first', () => {
const { records, screenByPosition } = recordsAt(
[
[0, 0],
[0.0001, 0],
[0.0002, 0],
],
(index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }),
);
const { records } = recordsAt([
[0, 0],
[0.01, 0],
[0.0002, 0],
]);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
viewer: viewerAt(300),
records,
activeCameraId: 'cam-1',
});
+14 -56
View File
@@ -6,17 +6,17 @@
*
* Two responsibilities, both pure of layer state:
* - Color identity: a stable per-camera hue (golden-angle spaced over the
* id-sorted catalog index) and the derived fill/line Cesium colors.
* - Volume geometry: a translucent frustum pyramid primitive built FROM the
* exact frustumCartesians positions the wireframe uses — welded by
* construction, never recomputed independently. 5 vertices, 6 triangles,
* synchronous build (trivially small), no picking.
* id-sorted catalog index) and the derived fill/line renderer colors.
* - Volume geometry: the vertex and index buffers of a translucent frustum
* pyramid built FROM the exact frustumCartesians positions the wireframe
* uses — welded by construction, never recomputed independently. 5
* vertices, 6 triangles; the layer's rendering part draws them.
*
* Nothing here queries the scene or persists anything: colors are
* presentation-only and volumes are rebuilt only at the moments the frustum
* wireframe already rewrites (pose edits / visible-set changes).
*/
import * as Cesium from 'cesium';
import { hslColor } from '../render/color.js';
/** Golden angle in degrees — maximally spreads consecutive indices around the hue wheel. */
const GOLDEN_ANGLE_DEG = 137.50776405003785;
@@ -43,15 +43,16 @@ export function cameraHue(index) {
* Derived viewshed colors for a hue: translucent volume fills (idle/active)
* and wireframe line tints (idle/active), all in the same hue family.
* @param {number} hueDeg - Hue in degrees.
* @returns {{fill: Cesium.Color, fillActive: Cesium.Color, line: Cesium.Color, lineActive: Cesium.Color}}
* @returns {{fill: number[], fillActive: number[], line: number[], lineActive: number[]}}
* Renderer colours, [r, g, b, a] in 0..1.
*/
export function viewshedColors(hueDeg) {
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),
line: Cesium.Color.fromHsl(hue, 0.9, 0.65, LINE_ALPHA_IDLE),
lineActive: Cesium.Color.fromHsl(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE),
fill: hslColor(hue, 0.85, 0.6, FILL_ALPHA_IDLE),
fillActive: hslColor(hue, 0.85, 0.6, FILL_ALPHA_ACTIVE),
line: hslColor(hue, 0.9, 0.65, LINE_ALPHA_IDLE),
lineActive: hslColor(hue, 0.9, 0.7, LINE_ALPHA_ACTIVE),
};
}
@@ -61,8 +62,8 @@ export function viewshedColors(hueDeg) {
* the apex + the far cap split into 2 triangles. Pure — this is the ONLY
* geometry definition (weld-by-construction with the wireframe, which draws
* its rays/cap from the same 5 Cartesians).
* @param {{mount: Cesium.Cartesian3, tl: Cesium.Cartesian3, tr: Cesium.Cartesian3,
* br: Cesium.Cartesian3, bl: Cesium.Cartesian3}} positions - frustumCartesians shape.
* @param {{mount: object, tl: object, tr: object, br: object, bl: object}}
* positions - frustumCartesians shape: ECEF points with x, y and z.
* @returns {{positions: Float64Array, indices: Uint16Array}}
*/
export function frustumVolumeGeometryData(positions) {
@@ -85,46 +86,3 @@ export function frustumVolumeGeometryData(positions) {
]);
return { positions: flat, indices };
}
/**
* Builds the translucent frustum-volume primitive for one camera.
* Synchronous (6 triangles — cheaper than the async geometry pipeline's
* bookkeeping), unlit flat color, both faces visible (the viewer is routinely
* inside or behind a cone), never pickable (clicks fall through to the
* billboard/wireframe/plane, whose pick semantics are established).
* @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData).
* @param {Cesium.Color} color - Per-camera fill color (already alpha'd).
* @returns {Cesium.Primitive}
*/
export function createFrustumVolumePrimitive(positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: flat,
}),
},
indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)),
});
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
renderState: {
cull: { enabled: false },
},
}),
asynchronous: false,
allowPicking: false,
});
}
+18 -6
View File
@@ -62,14 +62,26 @@ test('cameraHue: consecutive indices separated by >= 80 degrees', () => {
test('viewshedColors: fill/line pairs with the designed alphas', () => {
const colors = viewshedColors(210);
for (const key of ['fill', 'fillActive', 'line', 'lineActive']) {
assert.ok(colors[key] instanceof Cesium.Color, `${key} must be a Cesium.Color`);
assert.ok(Array.isArray(colors[key]) && colors[key].length === 4, `${key} must be a renderer colour`);
}
assert.ok(Math.abs(colors.fill.alpha - 0.12) < 1e-6);
assert.ok(Math.abs(colors.fillActive.alpha - 0.22) < 1e-6);
assert.ok(Math.abs(colors.line.alpha - 0.85) < 1e-6);
assert.ok(Math.abs(colors.lineActive.alpha - 1.0) < 1e-6);
assert.ok(Math.abs(colors.fill[3] - 0.12) < 1e-6);
assert.ok(Math.abs(colors.fillActive[3] - 0.22) < 1e-6);
assert.ok(Math.abs(colors.line[3] - 0.85) < 1e-6);
assert.ok(Math.abs(colors.lineActive[3] - 1.0) < 1e-6);
// Same hue family: fill and line of the same hue must not be gray.
assert.ok(colors.line.red !== colors.line.green || colors.line.green !== colors.line.blue);
assert.ok(colors.line[0] !== colors.line[1] || colors.line[1] !== colors.line[2]);
});
test('viewshedColors: the same colours the renderer derived from the hue', () => {
const asArray = (c) => [c.red, c.green, c.blue, c.alpha];
for (const hueDeg of [0, 137.5, 210, 359.9, -30]) {
const hue = (((hueDeg % 360) + 360) % 360) / 360;
const colors = viewshedColors(hueDeg);
assert.deepEqual(colors.fill, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.12)));
assert.deepEqual(colors.fillActive, asArray(Cesium.Color.fromHsl(hue, 0.85, 0.6, 0.22)));
assert.deepEqual(colors.line, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.65, 0.85)));
assert.deepEqual(colors.lineActive, asArray(Cesium.Color.fromHsl(hue, 0.9, 0.7, 1.0)));
}
});
/** Minimal frustumCartesians-shaped fixture. */
+4 -4
View File
@@ -27,8 +27,8 @@ const LAYERS = [
_setTrackedFlightRefreshStateForTest({
icao24,
entity: null,
billboard: candidateBillboard(icao24),
billboardCollection: { show: true, remove() {} },
icon: candidateBillboard(icao24),
iconLayer: { show: true, remove() {} },
viewer: candidateViewer(),
tracked: false,
meta: {
@@ -48,8 +48,8 @@ const LAYERS = [
_setTrackedMilitaryRefreshStateForTest({
icao24,
entity: null,
billboard: candidateBillboard(icao24),
billboardCollection: { show: true, remove() {} },
icon: candidateBillboard(icao24),
iconLayer: { show: true, remove() {} },
viewer: candidateViewer(),
tracked: false,
meta: {
+60 -24
View File
@@ -1,4 +1,5 @@
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import { readFileSync } from 'node:fs';
import test from 'node:test';
import assert from 'node:assert/strict';
@@ -12,6 +13,11 @@ import assert from 'node:assert/strict';
* regression would silently revert. These assertions pin the decisions.
*/
const DRAW_MODELS_SOURCE = readFileSync(
new URL('../render/cesium/drawModels.js', import.meta.url),
'utf8',
);
const LAYERS = [
{ name: 'flights', path: new URL('./flights.js', import.meta.url) },
{ name: 'militaryFlights', path: new URL('./militaryFlights.js', import.meta.url) },
@@ -28,20 +34,23 @@ for (const layer of LAYERS) {
const source = readLayerSource(layer.path);
test(`${layer.name}: every GLB creation bypasses the tile-contended frame-spread queue`, () => {
const calls = [...source.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
assert.ok(calls.length >= 3, `expected fleet, tracked, and preload model calls; found ${calls.length}`);
// The fleet and tracked models are draw-port models sets; the Cesium
// draw port creates every model off the frame-spread queue.
assert.match(source, /\.models\(\{\s*id:/, 'the layer draws its models as draw-port models sets');
const calls = [...DRAW_MODELS_SOURCE.matchAll(/Cesium\.Model\.fromGltfAsync\(\{([\s\S]*?)\}\)/g)];
assert.ok(calls.length >= 1, 'the draw port creates models');
for (const [index, call] of calls.entries()) {
assert.match(call[1], /\basynchronous:\s*false\b/,
`Model.fromGltfAsync call ${index + 1} must keep bounded GLB readiness independent of tile jobs`);
`_createModel call ${index + 1} must keep bounded GLB readiness independent of tile jobs`);
}
});
test(`${layer.name}: Cockpit 3D obeys the shared Display toggle`, () => {
const regime = /^([ \t]*)function _modelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(regime, '_modelRegimeActive is defined');
assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_models3dEnabled,?\s*\)\s*return\s*false;/,
assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_models3dEnabled,?\s*\)\s*return\s*false;/,
'OFF must keep Cockpit AIR contacts in 2D');
assert.doesNotMatch(regime, /!(?:flightState\.)?_models3dEnabled\s*&&\s*!(?:flightState\.)?_cockpitContactMode/,
assert.doesNotMatch(regime, /!(?:(?:flightState|state)\.)?_models3dEnabled\s*&&\s*!(?:(?:flightState|state)\.)?_cockpitContactMode/,
'Cockpit must not bypass the owner-visible Display toggle');
});
@@ -53,7 +62,7 @@ for (const layer of LAYERS) {
// suppression is now an explicit early return.
const regime = /^([ \t]*)function _trackedModelRegimeActive\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(regime, '_trackedModelRegimeActive is defined');
assert.match(regime, /if\s*\(\s*!(?:flightState\.)?_trackedIcao\s*\|\|\s*(?:flightState\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/,
assert.match(regime, /if\s*\(\s*!(?:(?:flightState|state)\.)?_trackedIcao\s*\|\|\s*(?:(?:flightState|state)\.)?_cockpitContactMode\s*\|\|[\s\S]*?return\s*false;/,
'_trackedModelRegimeActive excludes cockpit');
const tracked = /^([ \t]*)function _updateTrackedModel\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.ok(tracked, '_updateTrackedModel is defined');
@@ -61,46 +70,73 @@ for (const layer of LAYERS) {
'the tracked-model driver uses the cockpit-aware predicate');
});
test(`${layer.name}: Cockpit uses standard Proximity and All radii with a lower cap`, () => {
assert.equal(numericConstant(source, 'MODEL_PROX_ADD_M'), 150_000);
assert.equal(numericConstant(source, 'MODEL_PROX_KEEP_M'), 185_000);
assert.equal(numericConstant(source, 'MODEL_ALL_ADD_M'), 400_000);
assert.equal(numericConstant(source, 'MODEL_ALL_KEEP_M'), 450_000);
test(`${layer.name}: models draw within 3 km in both modes; Cockpit's AIR band keeps its own radii`, () => {
assert.equal(numericConstant(source, 'MODEL_ADD_M'), 3000);
assert.equal(numericConstant(source, 'MODEL_KEEP_M'), 3600);
assert.equal(numericConstant(source, 'COCKPIT_MODEL_MAX'), 60);
const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(add, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_ADD_M\s*:\s*MODEL_PROX_ADD_M/);
assert.match(keep, /(?:flightState\.)?_models3dMode\s*===\s*'all'\s*\?\s*MODEL_ALL_KEEP_M\s*:\s*MODEL_PROX_KEEP_M/);
assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/);
assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/);
assert.match(add, /return\s+(?:policy\.)?MODEL_ADD_M;/, 'Proximity and All share the add radius');
assert.match(keep, /return\s+(?:policy\.)?MODEL_KEEP_M;/, 'Proximity and All share the keep radius');
// The AIR silhouettes are icons, not models: their band stays mode-aware.
assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_ADD_M'), 150_000);
assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_KEEP_M'), 185_000);
assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_ADD_M'), 400_000);
assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_KEEP_M'), 450_000);
const near = /^([ \t]*)function _refreshCockpitNearContacts\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_ADD_M\s*:\s*COCKPIT_AIR_PROX_ADD_M/);
assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_KEEP_M\s*:\s*COCKPIT_AIR_PROX_KEEP_M/);
const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(cap, /Math\.min\(\s*COCKPIT_MODEL_MAX/,
assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/,
'Cockpit keeps its 60-model performance ceiling');
});
test(`${layer.name}: near AIR state is independent from model admission`, () => {
assert.match(source, /nextCockpitNearContacts\(/,
'Cockpit derives a separate near-contact hysteresis set');
assert.match(source, /isCockpitContact && !isCockpitNear[\s\S]*cockpitContactDotImage\(\)/,
assert.match(source, /!state\._cockpitNearContacts\.has\(icao24\);\s*const look = cockpitDot\s*\?\s*\{\s*image: cockpitDotImage\(\)/,
'only out-of-range Cockpit contacts become dots');
// `_iconKind` is identity for every unconverted contact (see
// tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the
// operator explicitly converted into a TR-3B.
assert.match(source, /bb\.image\s*=\s*aircraftIcon\(\s*_iconKind\(\s*icao24,\s*meta\?\.klass,?\s*\)(,\s*bb\._gevIconLarge\s*\?\s*TRACKED_ICON_PX\s*:\s*undefined)?,?\s*\)/,
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?(?:frame,?\s*)?\)/,
'near contacts and model fallbacks retain the class-derived aircraft silhouette');
assert.match(source, /bb\.rotation\s*=\s*0;/,
assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/,
'far dots are reset to a rotation-free presentation');
assert.match(source, /\(\s*!(?:flightState\.)?_cockpitContactMode\s*\|\|\s*isCockpitNear,?\s*\)\s*&&\s*\(\s*doRotations\s*\|\|\s*revealed,?\s*\)/,
assert.match(source, /color: rgba\(rendering\._fleetBillboardColor\(icao24, info\)\),\s*rotationMode: 'course',/,
'near 2D silhouettes continue to receive projected course');
assert.match(source, /if\s*\(\s*bb\.show,?\s*\)\s*bb\.show\s*=\s*false;\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/,
'the gap-proof billboard-to-model handoff remains intact');
assert.match(source, /icons\.setShown\(icao24, false\);\s*\/\/\s*hand\s*off\s*ONLY\s*once\s*the\s*model\s*renders/,
'the gap-proof icon-to-model handoff remains intact');
});
test(`${layer.name}: Cockpit exit clears near state before restoring map presentation`, () => {
const setMode = /^([ \t]*)function _setCockpitContactMode\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
assert.match(setMode, /else\s*(?:flightState\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/);
assert.match(setMode, /for\s*\(\s*const\s*\[icao24,\s*bb\]\s*of\s*(?:flightState\.)?_billboards,?\s*\)\s*(?:parts\.\w+\.)?_applyFleetBillboardPresentation\(\s*icao24,\s*bb,?\s*\);/);
assert.match(setMode, /else\s*(?:(?:flightState|state)\.)?_cockpitNearContacts\s*=\s*new\s*Set\(\s*,?\s*\);/);
assert.match(setMode, /for \(const icao24 of (?:flightState\._)?icons\?\.ids\(\) \?\? \[\]\)\s*parts\.icons\._applyIconPresentation\(icao24\);/);
});
}
// The source reads above include the shared model module, so they pass from it
// alone. These pin that each layer actually builds its models from it, and that
// flights keeps its own hooks.
const RENDERING = {
flights: new URL('../layers/flights/rendering.js', import.meta.url),
militaryFlights: new URL('../layers/military/rendering.js', import.meta.url),
};
for (const [name, url] of Object.entries(RENDERING)) {
test(`${name}: 3D models come from the shared aircraft model module`, () => {
const source = readFileSync(url, 'utf8');
assert.match(source, /createAircraftModels\(\{/);
assert.match(source, /\.\.\.models\b/);
});
}
test('flights: model eligibility nudges enrichment and the tick floors grounded icons', () => {
const source = readFileSync(RENDERING.flights, 'utf8');
assert.match(source, /onModelEligible:[\s\S]*?_requestTypeEnrichment\(icao24, true\)/);
assert.match(source, /afterReplan:[\s\S]*?_floorGroundedIcons\(/);
});
+199 -214
View File
@@ -1,4 +1,19 @@
import * as Cesium from 'cesium';
/**
* @module contactTrailRenderer
* @description The selected transit vehicle's trail, drawn through the
* renderer's draw port as draped lines: a history body and a moving head.
*
* The body is every subdivision of the vehicle's history, each a segment of
* a draped line in two lanes (a dark 5 px backing under a 3 px line in the
* mode colour). A segment shows once the vehicle has passed it and fades
* with its age; both change in place (`segmentShow`, `segmentColors`), so
* the body is rebuilt only when the history changes. The head is the
* subdivision the vehicle is on, revealed up to the vehicle
* (`revealFraction`): it moves only where the vehicle crosses into the
* next subdivision, and a frame writes how far it is revealed.
*/
import { cssColor } from '../render/color.js';
import { findDraw } from '../render/rendererOf.js';
const ALPHA_STOPS = [
[0, 0.8],
@@ -19,95 +34,141 @@ export function trailAlpha(ageMs) {
return 0.08;
}
/** One static history batch and one frequently updated head. Never entities. */
export function createContactTrailRenderer(scene) {
const ground =
!!scene.frameState?.context &&
Cesium.GroundPolylinePrimitive.isSupported(scene);
const collection = ground ? scene.groundPrimitives : scene.primitives;
// One 25 m corridor is clipped in material coordinates. Only subdivision
// crossings build geometry; frame updates write a scalar, never vertex buffers.
const headMaterial = (alpha) =>
new Cesium.Material({
fabric: {
type: 'TransitTrailHead',
uniforms: {
color: new Cesium.Color(0.37, 0.94, 0.54, alpha),
fraction: 0,
backing: true,
},
source: `czm_material czm_getMaterial(czm_materialInput materialInput) {
if (materialInput.st.s > fraction) discard;
czm_material m = czm_getDefaultMaterial(materialInput);
bool edge = abs(materialInput.st.t - 0.5) > 0.3;
m.diffuse = czm_gammaCorrect(vec4(edge && backing ? vec3(0.02, 0.03, 0.05) : color.rgb, 1.0)).rgb;
m.alpha = color.a;
return m;
}`,
},
translucent: true,
});
const material = headMaterial(0.8),
depthMaterial = headMaterial(0.55);
depthMaterial.uniforms.backing = false;
const head = { positions: [], show: false, width: 3, material };
/** The backing lane's colour, under the mode colour. */
const BACKING = [0.02, 0.03, 0.05];
/** Alpha of the head, and of a body segment the vehicle has just passed. */
const HEAD_ALPHA = 0.8;
const WHITE = [1, 1, 1, 1];
/** The two lanes, drawn in this order: the backing, then the line. */
const LANES = [
{ name: 'backing', widthPx: 5, dark: true },
{ name: 'line', widthPx: 3, dark: false },
];
/** Uniquifier for each renderer's set ids. */
let trailSeq = 0;
const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
/**
* The history as runs of joined segments (each segment starting where the
* one before it ends), so each lane is a few lines rather than one a
* segment. `first` is the index of the run's first segment; a segment with
* no length ends a run.
*/
function runsOf(segments) {
const runs = [];
let run = null;
for (let i = 0; i < segments.length; i++) {
const [from, to] = segments[i].positions;
if (!from || !to) run = null;
else if (run && samePoint(run.positions.at(-1), from))
run.positions.push(to);
else runs.push((run = { first: i, positions: [from, to] }));
}
return runs;
}
/**
* The trail renderer of one selection, over `viewer`'s draw port. Never
* entities; nothing it draws takes part in picks.
* @param {object} viewer
*/
export function createContactTrailRenderer(viewer) {
const draw = findDraw(viewer);
const prefix = `transit-trail:${++trailSeq}`;
const body = draw?.lines({ id: `${prefix}:body`, pickable: false }) ?? null;
const headLines =
draw?.lines({ id: `${prefix}:head`, pickable: false, show: false }) ?? null;
/** What the head draws now, for diagnostics: its start to the vehicle. */
const endpoint = { x: 0, y: 0, z: 0 };
const headPositions = [null, endpoint];
const head = { positions: [], show: false, width: 3 };
const backing = { positions: [], show: false, width: 5 };
let headPrimitive = null,
headRebuilds = 0;
function geometry(positions, width, material = false) {
return ground
? new Cesium.GroundPolylineGeometry({ positions, width, granularity: 0 })
: new Cesium.PolylineGeometry({
positions,
width,
arcType: Cesium.ArcType.NONE,
vertexFormat: material
? Cesium.PolylineMaterialAppearance.VERTEX_FORMAT
: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
});
}
function primitive(instances, appearance, depthFailAppearance) {
return ground
? new Cesium.GroundPolylinePrimitive({
geometryInstances: instances,
appearance,
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
asynchronous: true,
show: visible,
})
: new Cesium.Primitive({
geometryInstances: instances,
appearance,
depthFailAppearance,
allowPicking: false,
asynchronous: false,
show: visible,
});
}
let body = null,
segments = [],
let segments = [],
runs = [],
revision = -1,
visible = true,
style = '#5EF08A';
style = '#5EF08A',
styleColor = cssColor(style).slice(0, 3);
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;
active = null,
revealed = -1,
restyled = false;
let rebuilds = 0,
headRebuilds = 0;
const tint = (alpha, dark) => [...(dark ? BACKING : styleColor), alpha];
/** The body's lines: each lane's runs, segments shown up to `done`. */
function bodyLines(displayT, done) {
const lines = [];
for (const lane of LANES)
for (let r = 0; r < runs.length; r++) {
const run = runs[r];
const count = run.positions.length - 1;
const segmentColors = new Array(count);
const segmentShow = new Array(count);
for (let k = 0; k < count; k++) {
const i = run.first + k;
const alpha =
displayT === null
? HEAD_ALPHA
: trailAlpha(displayT - segments[i].toT);
segmentColors[k] = tint(alpha, lane.dark);
segmentShow[k] = i <= done;
}
lines.push({
id: `${lane.name}:${r}`,
positions: run.positions,
widthPx: lane.widthPx,
mode: 'draped',
clampTo: 'both',
// Every segment has its own colour: the line's own never
// changes, so a new mode colour is written in place.
style: { kind: 'solid', color: lane.dark ? [...BACKING, 1] : WHITE },
segmentColors,
segmentShow,
});
}
return lines;
}
/**
* The head over `segment`, revealed to `fraction`: one line the backing's
* width, its edge the backing's colour and its centre the line's width,
* in one pass. Two lanes stacked would darken the centre where their
* translucent passes overlap.
*/
function headItems(segment, fraction) {
const [backingLane, lineLane] = LANES;
return [
{
id: 'head',
positions: segment.positions,
widthPx: backingLane.widthPx,
mode: 'draped',
clampTo: 'both',
style: {
kind: 'solid',
color: tint(HEAD_ALPHA, false),
outline: {
color: tint(HEAD_ALPHA, true),
widthPx: backingLane.widthPx - lineLane.widthPx,
},
},
revealFraction: fraction,
},
];
}
// Written only when it changes: a renderer may redraw for each write.
function showHead(show) {
head.show = backing.show = show;
if (headLines && headLines.show !== show) headLines.show = show;
}
function replaceHistory(next) {
if (next.revision === revision) return;
revision = next.revision;
@@ -115,51 +176,22 @@ export function createContactTrailRenderer(scene) {
completed = -1;
lastSecond = -1;
active = null;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
head.show = backing.show = false;
if (body) collection.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: geometry(segment.positions, lane ? 3 : 5),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.55),
),
show: new Cesium.ShowGeometryInstanceAttribute(false),
},
}),
);
}
}
if (instances.length) {
body = collection.add(
primitive(
instances,
new Cesium.PolylineColorAppearance({ translucent: true }),
new Cesium.PolylineColorAppearance({ translucent: true }),
),
);
rebuilds++;
revealed = -1;
showHead(false);
headLines?.clear();
runs = runsOf(segments);
if (!body) return;
if (!runs.length) {
body.clear();
return;
}
body.set(bodyLines(null, -1));
rebuilds++;
}
function setDisplaySample(sample, renderedPosition) {
if (!sample || !renderedPosition) {
head.show = false;
backing.show = false;
if (headPrimitive) headPrimitive.show = false;
showHead(false);
return;
}
const second = Math.floor(sample.displayT / 1000);
@@ -179,114 +211,69 @@ export function createContactTrailRenderer(scene) {
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;
// Cesium getters return copies. Write back the array we changed.
const show = attributes.show;
show[0] = i <= done ? 1 : 0;
attributes.show = show;
}
}
// Passed segments show, and every segment fades with its age, once a
// second; the port writes only the segments that change.
if (body && runs.length && (done !== completed || second !== lastSecond)) {
body.upsert(bodyLines(sample.displayT, done));
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;
const rgba = attributes.color;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
rgba,
);
attributes.color = rgba;
if (!ground) {
const depthRgba = attributes.depthFailColor;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(0.55),
depthRgba,
);
attributes.depthFailColor = depthRgba;
}
}
}
lastSecond = second;
}
const show = visible && !!segment && sample.fraction < 1;
head.show = show;
backing.show = show;
if (headPrimitive) headPrimitive.show = show;
const show =
visible &&
!!segment?.positions[0] &&
!!segment.positions[1] &&
sample.fraction < 1;
showHead(show);
if (!show) return;
if (active !== segment) {
active = segment;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = collection.add(
primitive(
new Cesium.GeometryInstance({
geometry: geometry(segment.positions, 5, true),
}),
new Cesium.PolylineMaterialAppearance({
material,
translucent: true,
}),
new Cesium.PolylineMaterialAppearance({
material: depthMaterial,
translucent: true,
}),
),
);
headRebuilds++;
headPositions[0] = segment.positions[0];
headPositions[1] = endpoint;
}
Cesium.Cartesian3.clone(renderedPosition, endpoint);
head.positions = headPositions;
backing.positions = headPositions;
material.uniforms.fraction = Math.max(
const fraction = Math.max(
0,
Math.min(
1,
(sample.displayT - segment.fromT) / (segment.toT - segment.fromT),
),
);
depthMaterial.uniforms.fraction = material.uniforms.fraction;
Cesium.Color.clone(tint(0.8), material.uniforms.color);
Cesium.Color.clone(tint(0.55), depthMaterial.uniforms.color);
if (active !== segment || restyled) {
if (active !== segment) headRebuilds++;
active = segment;
restyled = false;
revealed = fraction;
// Upserted, not set: a renderer can move a draped line to where it
// now runs in the same frame, instead of building it anew.
headLines?.upsert(headItems(segment, fraction));
} else if (fraction !== revealed) {
revealed = fraction;
headLines?.upsert(headItems(segment, fraction));
}
headPositions[0] = segment.positions[0];
endpoint.x = renderedPosition.x;
endpoint.y = renderedPosition.y;
endpoint.z = renderedPosition.z;
head.positions = backing.positions = headPositions;
}
return {
replaceHistory,
setDisplaySample,
setStyle(next) {
if (next === style) return;
style = next;
Cesium.Color.fromCssColorString(style, styleColor);
styleColor = cssColor(style)?.slice(0, 3) ?? styleColor;
// Faded again in the new colour on the next sample, and the head
// drawn in it.
lastSecond = -1;
restyled = true;
},
setVisible(next) {
visible = next;
if (headPrimitive) headPrimitive.show = next && head.show;
if (body) body.show = next;
if (body && body.show !== next) body.show = next;
if (!next) showHead(false);
},
destroy() {
if (body) collection.remove(body);
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
material.destroy();
depthMaterial.destroy();
body = null;
body?.dispose();
headLines?.dispose();
segments = [];
runs = [];
active = null;
},
diagnostics() {
return {
@@ -294,13 +281,11 @@ export function createContactTrailRenderer(scene) {
rebuilds,
segments: segments.length,
body,
headLines,
head,
backing,
headPrimitive,
headStrategy: ground
? 'draped corridor with material clip'
: 'depth-fail corridor with material clip',
ground,
headStrategy: 'draped lines revealed to the vehicle',
ground: !!draw,
headRebuilds,
entitiesAdded: 0,
};
+253 -317
View File
@@ -1,153 +1,289 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { readFileSync } from 'node:fs';
import { TRAIL_VERTEX_LIMIT } from '../layers/transit/trails.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
createContactTrailRenderer,
trailAlpha,
} from './contactTrailRenderer.js';
function fixture(t, ground = false) {
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 width = Cesium.ContextLimits._maximumAliasedLineWidth;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
t.after(() => {
Cesium.ContextLimits._maximumAliasedLineWidth = width;
});
const primitives = new Cesium.PrimitiveCollection();
t.after(() => primitives.destroy());
const groundPrimitives = new Cesium.PrimitiveCollection();
t.after(() => groundPrimitives.destroy());
return {
primitives,
groundPrimitives,
frameState: { context: { depthTexture: ground } },
globe: { show: false },
};
const GREEN = [0x5e / 255, 0xf0 / 255, 0x8a / 255];
const DARK = [0.02, 0.03, 0.05];
function viewerWithDraw(t) {
const viewer = { isDestroyed: () => false };
const { draw, unbind } = bindFakeDraw(viewer);
t.after(unbind);
return { viewer, draw };
}
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,
const point = (i) => ({ x: 1000 * i, y: 2000, z: 3000 });
function history(revision = 1) {
return {
revision,
segments: [
{
fromSeq: 0,
toSeq: 1,
fromT: 0,
toT: 10000,
positions: positions.slice(0, 2),
positions: [point(0), point(1)],
},
{
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 20000,
positions: positions.slice(1, 3),
positions: [point(1), point(2)],
},
],
});
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,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
}
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) => {
const stored = attributes.get(id),
accessor = {};
for (const name of ['show', 'color', 'depthFailColor'])
Object.defineProperty(accessor, name, {
get: () => stored[name].slice(),
set: (value) => {
stored[name] = value.slice();
},
});
return accessor;
};
const marker = Cesium.Cartesian3.lerp(
positions[1],
positions[2],
0.5,
new Cesium.Cartesian3(),
}
/** The trail's live set whose id ends with `suffix`. */
const setOf = (draw, suffix) =>
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(suffix),
);
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
const close = (actual, expected) =>
actual.every((value, i) => Math.abs(value - expected[i]) < 1e-9);
test('the body is two draped lanes whose passed segments show, faded by age', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const body = setOf(draw, ':body');
assert.equal(body.spec.pickable, false);
const lines = [...body.items.values()];
// One run (the segments join): a backing lane under the mode colour.
assert.deepEqual(
[...attributes.values()].map((a) => a.show[0]),
[1, 1, 0, 0],
lines.map((line) => [line.id, line.widthPx, line.mode, line.clampTo]),
[
['backing:0', 5, 'draped', 'both'],
['line:0', 3, 'draped', 'both'],
],
);
for (const a of attributes.values())
assert.deepEqual(
a.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
const result = renderer.diagnostics();
assert.equal(result.body, body);
assert.equal(result.rebuilds, 1);
assert.equal(result.headRebuilds, 1, '120 frames retain head geometry');
assert.equal(result.head.material.uniforms.fraction, 0.5);
assert.equal(result.head.width, 3);
assert.equal(result.backing.width, 5);
assert.ok(Cesium.Cartesian3.equals(result.head.positions.at(-1), marker));
assert.equal(result.head.positions.length, 2);
assert.deepEqual(lines[0].positions, [point(0), point(1), point(2)]);
assert.deepEqual(lines[0].segmentShow, [false, false], 'none passed yet');
const marker = { x: 1500, y: 2000, z: 3000 };
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample(sample, marker);
const [backing, line] = body.items.values();
assert.deepEqual(line.segmentShow, [true, false], 'the future is clipped');
assert.deepEqual(backing.segmentShow, [true, false]);
assert.ok(close(line.segmentColors[0], [...GREEN, trailAlpha(5000)]));
assert.ok(close(backing.segmentColors[0], [...DARK, trailAlpha(5000)]));
// Within the second, nothing is written again; a rewind hides again.
const writes = body.writes;
for (let i = 0; i < 60; i++) renderer.setDisplaySample(sample, marker);
assert.equal(body.writes, writes);
renderer.setDisplaySample(
{ ...sample, displayT: 5000, fraction: 0.25 },
positions[0],
point(0),
);
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
assert.deepEqual(
body.items.get('line:0').segmentShow,
[false, false],
'rewind hides future geometry again',
);
assert.equal(renderer.diagnostics().rebuilds, 1);
renderer.destroy();
assert.equal(scene.primitives.length, 0);
assert.equal(body.disposed, true);
});
test('the head is revealed to the vehicle and drawn anew only at a crossing', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const head = renderer.diagnostics().headLines;
const record = setOf(draw, ':head');
assert.equal(record.spec.pickable, false);
const marker = { x: 1500, y: 2000, z: 3000 };
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
assert.equal(head.show, true);
// One line, its dark edge in the same pass: lanes stacked would darken
// its centre where their translucent passes overlap.
const lines = [...record.items.values()];
assert.deepEqual(
lines.map((line) => [line.id, line.widthPx, line.revealFraction]),
[['head', 5, 0.5]],
);
assert.deepEqual(lines[0].positions, [point(1), point(2)]);
assert.ok(close(lines[0].style.color, [...GREEN, 0.8]));
assert.ok(close(lines[0].style.outline.color, [...DARK, 0.8]));
assert.equal(lines[0].style.outline.widthPx, 2);
const result = renderer.diagnostics();
assert.equal(result.headRebuilds, 1, '120 frames retain head geometry');
assert.equal(result.entitiesAdded, 0);
assert.equal(result.ground, true);
assert.deepEqual(result.head.positions, [point(1), marker]);
assert.equal(result.head.width, 3);
assert.equal(result.backing.width, 5);
// A frame further along writes only how far it is revealed.
renderer.setDisplaySample({ ...sample, displayT: 17500 }, marker);
assert.equal(record.items.get('head').revealFraction, 0.75);
assert.equal(renderer.diagnostics().headRebuilds, 1);
// The next subdivision, or the end of the leg, hides it.
renderer.setDisplaySample({ ...sample, fraction: 1 }, marker);
assert.equal(head.show, false);
renderer.setVisible(false);
renderer.setDisplaySample(sample, marker);
assert.equal(head.show, false, 'hidden with the trail');
assert.equal(result.body.show, false);
});
test('a new mode colour is written into the segments, never rebuilding the body', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample(sample, point(1));
const body = setOf(draw, ':body');
const look = body.items.get('line:0').style;
renderer.setStyle('#FFFFFF');
renderer.setDisplaySample(sample, point(1));
const line = body.items.get('line:0');
assert.deepEqual(line.style, look, 'the line itself is unchanged');
assert.ok(close(line.segmentColors[0], [1, 1, 1, trailAlpha(5000)]));
assert.equal(renderer.diagnostics().rebuilds, 1);
assert.equal(renderer.diagnostics().headRebuilds, 1, 'no crossing');
const headLine = setOf(draw, ':head').items.get('head');
assert.ok(close(headLine.style.color, [1, 1, 1, 0.8]), 'and the head');
});
test('separate runs of the history are separate lines', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
const { segments } = history();
segments[1] = { ...segments[1], positions: [point(5), point(6)] };
renderer.replaceHistory({ revision: 2, segments });
assert.deepEqual(
[...setOf(draw, ':body').items.keys()],
['backing:0', 'backing:1', 'line:0', 'line:1'],
);
renderer.replaceHistory({ revision: 3, segments: [] });
assert.equal(setOf(draw, ':body').items.size, 0);
});
test('a viewer with nothing to draw with draws no trail', () => {
const renderer = createContactTrailRenderer({ isDestroyed: () => false });
assert.doesNotThrow(() => {
renderer.replaceHistory(history());
renderer.setDisplaySample(
{ displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 },
point(1),
);
});
assert.equal(renderer.diagnostics().ground, false);
renderer.destroy();
});
test('playback across a crossing redraws the head once and shows the passed segment', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory({
revision: 1,
segments: history().segments.map((segment) => ({ ...segment, toSeq: 2 })),
});
const body = setOf(draw, ':body'),
head = setOf(draw, ':head');
// 60 fps through both subdivisions of one leg.
for (let t = 0; t < 20000; t += 16)
renderer.setDisplaySample(
{ displayT: t, fromSeq: 0, toSeq: 2, fraction: t / 20000 },
point(t / 10000),
);
assert.equal(renderer.diagnostics().headRebuilds, 2, 'one per subdivision');
assert.deepEqual(body.items.get('line:0').segmentShow, [true, false]);
assert.deepEqual(head.items.get('head').positions, [point(1), point(2)]);
assert.ok(head.items.get('head').revealFraction > 0.99);
// Body writes: one a second, and one at the crossing at most.
assert.ok(body.writes <= 1 + 20 + 1, `${body.writes} body writes`);
});
test('the head hides off its leg and with no sample, and shows again', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const head = renderer.diagnostics().headLines;
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setDisplaySample({ ...sample, toSeq: 9 }, point(1));
assert.equal(head.show, false, 'another leg');
renderer.setDisplaySample(sample, point(1));
assert.equal(head.show, true);
renderer.setDisplaySample(null, null);
assert.equal(head.show, false, 'no sample');
renderer.setVisible(false);
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
assert.equal(head.show, true, 'shown again with the trail');
assert.equal(renderer.diagnostics().body.show, true);
const sets = [setOf(draw, ':body'), setOf(draw, ':head')];
renderer.destroy();
assert.ok(
sets.every((set) => set.disposed),
'both sets disposed',
);
});
test('a segment with no length ends a run and later ones keep their times', (t) => {
const { viewer, draw } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
const { segments } = history();
segments.splice(1, 0, {
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 10000,
positions: [],
});
segments[2] = { ...segments[2], fromT: 10000, toT: 20000 };
renderer.replaceHistory({ revision: 1, segments });
renderer.setDisplaySample(
{ displayT: 25000, fromSeq: 0, toSeq: 1, fraction: 1 },
point(2),
);
const body = setOf(draw, ':body');
assert.deepEqual(
[...body.items.keys()],
['backing:0', 'backing:1', 'line:0', 'line:1'],
);
const later = body.items.get('line:1');
assert.deepEqual(later.positions, [point(1), point(2)]);
assert.deepEqual(later.segmentShow, [true]);
assert.ok(close(later.segmentColors[0], [...GREEN, trailAlpha(5000)]));
});
test('frames that change nothing write no show', (t) => {
const { viewer } = viewerWithDraw(t);
const renderer = createContactTrailRenderer(viewer);
renderer.replaceHistory(history());
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
const { body, headLines } = renderer.diagnostics();
let writes = 0;
for (const set of [body, headLines]) {
let show = set.show;
Object.defineProperty(set, 'show', {
get: () => show,
set(value) {
writes++;
show = value;
},
});
}
for (let i = 0; i < 30; i++) {
renderer.setVisible(true);
renderer.setDisplaySample(sample, point(1));
}
assert.equal(writes, 0, 'a renderer may redraw for each show written');
});
test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(0), 0.8);
assert.equal(trailAlpha(120000), 0.45);
@@ -155,203 +291,3 @@ test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(900000), 0.08);
assert.ok(Math.abs(trailAlpha(60000) - 0.625) < 1e-10);
});
test('ground body and clipped head stay inside rebuild and frame geometry budgets', async () => {
Cesium.ApproximateTerrainHeights._terrainHeights = JSON.parse(
readFileSync(
new URL(
import.meta
.resolve('@cesium/engine/Source/Assets/approximateTerrainHeights.json'),
),
),
);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
const start = performance.now();
const instances = async (count) =>
Promise.all(
Array.from(
{ length: count },
async (_, i) =>
new Cesium.GeometryInstance({
id: i,
geometry: await Cesium.GroundPolylineGeometry.createGeometry(
new Cesium.GroundPolylineGeometry({
positions,
width: i % 2 ? 3 : 5,
granularity: 0,
}),
),
}),
),
);
const pipelineBytes = async (count) => {
// Match GroundPolylinePrimitive's internal Primitive options and the
// application's morph-capable scene, including batch IDs and encoding.
const result = Cesium.PrimitivePipeline.combineGeometry({
instances: await instances(count),
projection: new Cesium.GeographicProjection(),
ellipsoid: Cesium.Ellipsoid.WGS84,
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
elementIndexUintSupported: true,
scene3DOnly: false,
vertexCacheOptimize: false,
compressVertices: false,
createPickOffsets: false,
});
return result.geometries.reduce(
(sum, geometry) =>
sum +
Object.values(geometry.attributes).reduce(
(n, a) => n + (a?.values?.byteLength || 0),
0,
) +
geometry.indices.byteLength,
0,
);
};
const bytes = await pipelineBytes(1);
const bodyInstances = 2 * (TRAIL_VERTEX_LIMIT - 1);
const bodyBytes = await pipelineBytes(bodyInstances);
assert.equal(bytes, 1576, 'measure final encoded and batched geometry');
assert.equal(bodyBytes, 2014128);
const instanceReserve = 64 * bodyInstances;
assert.ok(bodyBytes + instanceReserve <= 2 * 1024 * 1024);
assert.ok(
bytes <= 2048,
'subdivision crossings stay below 2 KiB of head geometry',
);
console.log(
`trail final pipeline: ${bytes} bytes/head crossing, 0 bytes/ordinary head frame, ${bodyBytes} bytes/body (${bodyInstances} instances), ${instanceReserve} bytes instance reserve; geometry CPU ${(performance.now() - start).toFixed(3)} ms`,
);
});
test('supported scenes drape body and clipped head on 3D tiles and retain head geometry', (t) => {
const scene = fixture(t, true),
renderer = createContactTrailRenderer(scene);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
renderer.replaceHistory({
revision: 1,
segments: [{ fromSeq: 0, toSeq: 1, fromT: 0, toT: 20000, positions }],
});
const first = renderer.diagnostics();
assert.ok(first.body instanceof Cesium.GroundPolylinePrimitive);
assert.equal(first.body.classificationType, Cesium.ClassificationType.BOTH);
assert.ok(scene.groundPrimitives.contains(first.body));
for (const instance of first.body.geometryInstances)
assert.ok(instance.geometry instanceof Cesium.GroundPolylineGeometry);
for (let i = 1; i <= 120; i++)
renderer.setDisplaySample(
{ displayT: i * 100, fromSeq: 0, toSeq: 1, fraction: i / 200 },
positions[1],
);
const result = renderer.diagnostics();
assert.equal(result.body, first.body);
assert.equal(result.headRebuilds, 1);
assert.ok(result.headPrimitive instanceof Cesium.GroundPolylinePrimitive);
assert.equal(result.head.material.uniforms.fraction, 0.6);
assert.match(result.head.material.shaderSource, /discard/);
for (const stack of ['Google', 'OSM', 'Bing', 'Google']) {
scene.globe.show = stack !== 'Google';
renderer.setDisplaySample(
{ displayT: 12000, fromSeq: 0, toSeq: 1, fraction: 0.6 },
positions[1],
);
const retained = renderer.diagnostics();
assert.equal(retained.body, result.body, `${stack}: retained history`);
assert.equal(retained.headPrimitive, result.headPrimitive);
for (const primitive of [retained.body, retained.headPrimitive]) {
assert.equal(
primitive.classificationType,
Cesium.ClassificationType.BOTH,
stack,
);
assert.equal(primitive.show, true, stack);
}
}
renderer.setVisible(false);
assert.equal(result.body.show, false);
assert.equal(result.headPrimitive.show, false);
renderer.destroy();
assert.equal(scene.groundPrimitives.length, 0);
assert.equal(scene.primitives.length, 0);
});
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.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#FF4538').withAlpha(0.55),
),
);
});
+5 -3
View File
@@ -1,3 +1,5 @@
import { entityRecord, readEntityRecord } from './entityRecords.js';
const STORE_KEY = '__gevContextStore';
function createStore() {
@@ -36,14 +38,14 @@ export function registerEntityContext(entity, metadata) {
entity,
updatedAt: Date.now(),
};
entity.__gevContextId = metadata.id;
entityRecord(entity).contextId = metadata.id;
store.entities.set(metadata.id, record);
return record;
}
export function selectEntityContext(entity) {
const store = getContextStore();
const contextId = entity?.__gevContextId;
const contextId = readEntityRecord(entity)?.contextId;
if (!contextId || !store.entities.has(contextId)) return null;
store.selectedEntityId = contextId;
store.selectedAt = Date.now();
@@ -84,7 +86,7 @@ export function selectTrackedSubjectContext(metadata) {
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 };
const carrier = store.entities.get(id)?.entity || {};
const record = registerEntityContext(carrier, { ...metadata, id });
if (!record) return null;
store.selectedEntityId = id;
+2 -2
View File
@@ -96,7 +96,7 @@ test('a sibling tracking layer keeps its own subject slot', () => {
test('the per-poll refresh updates values without stealing the selection', () => {
withWindow(() => {
selectTrackedSubjectContext(flightSubject('aaa001'));
const other = registerEntityContext({ __gevContextId: 'dc-7' }, {
const other = registerEntityContext({}, {
id: 'dc-7', layerId: 'local-datacenters', label: 'Datacenter 7',
});
selectEntityContext(other.entity);
@@ -130,7 +130,7 @@ test('deselecting a contact releases the shared slot', () => {
test('clearing one tracking layer leaves another layer selection alone', () => {
withWindow(() => {
const other = registerEntityContext({ __gevContextId: 'dam-3' }, {
const other = registerEntityContext({}, {
id: 'dam-3', layerId: 'local-dams', label: 'Dam 3',
});
selectEntityContext(other.entity);
+61
View File
@@ -0,0 +1,61 @@
/**
* The course of a contact whose feed reports neither a ground track nor a
* true heading, read from its own fixes.
*
* The course runs from an anchor fix to the newest fix once they are at least
* COURSE_FROM_FIXES_MIN_M apart; the anchor then moves to the newest fix.
* Nearer fixes leave the anchor where it is, so frequent fixes of a slow
* aircraft still add up to a course, while position noise on a parked one
* never makes one. A fix that does not move time on by a second (a repeat, or
* an older position from another feed) never moves the anchor or gives a
* course, and neither does one reported slower than
* COURSE_FROM_FIXES_MIN_SPEED_MPS.
*/
import { approxDistanceKm } from './approxDistance.js';
/** Metres between fixes before a course is read from them. */
export const COURSE_FROM_FIXES_MIN_M = 30;
/** A contact reported slower than this (m/s) is standing: no course is read. */
export const COURSE_FROM_FIXES_MIN_SPEED_MPS = 2;
/**
* Initial great-circle bearing from one point to another, in degrees from
* true north (0–360), or null when either is missing or they are less than
* COURSE_FROM_FIXES_MIN_M apart.
*/
export function courseBetweenFixes(fromLat, fromLon, toLat, toLon) {
if (![fromLat, fromLon, toLat, toLon].every(Number.isFinite)) return null;
if (
approxDistanceKm(fromLat, fromLon, toLat, toLon) * 1000 <
COURSE_FROM_FIXES_MIN_M
)
return null;
const φ1 = (fromLat * Math.PI) / 180;
const φ2 = (toLat * Math.PI) / 180;
const Δλ = ((toLon - fromLon) * Math.PI) / 180;
const y = Math.sin(Δλ) * Math.cos(φ2);
const x =
Math.cos(φ1) * Math.sin(φ2) - Math.sin(φ1) * Math.cos(φ2) * Math.cos(Δλ);
return ((Math.atan2(y, x) * 180) / Math.PI + 360) % 360;
}
/**
* Read a course from a new fix.
* @param {{lat: number, lon: number, ms: number}|null|undefined} anchor The
* anchor fix kept from the last call (null at first).
* @param {{lat: number, lon: number, ms: number, speedMps?: number|null}} fix
* @returns {{courseDeg: number|null, anchor: {lat: number, lon: number, ms: number}|null}}
* The course, or null when none can be read, and the anchor to keep.
*/
export function courseFromFixes(anchor, { lat, lon, ms, speedMps = null }) {
const keep = anchor ?? null;
if (![lat, lon, ms].every(Number.isFinite))
return { courseDeg: null, anchor: keep };
if (!keep) return { courseDeg: null, anchor: { lat, lon, ms } };
if (ms < keep.ms + 1000) return { courseDeg: null, anchor: keep };
if (Number.isFinite(speedMps) && speedMps < COURSE_FROM_FIXES_MIN_SPEED_MPS)
return { courseDeg: null, anchor: keep };
const courseDeg = courseBetweenFixes(keep.lat, keep.lon, lat, lon);
if (courseDeg === null) return { courseDeg: null, anchor: keep };
return { courseDeg, anchor: { lat, lon, ms } };
}
+42
View File
@@ -0,0 +1,42 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { courseBetweenFixes, courseFromFixes } from './courseFromFixes.js';
test('course between fixes reads true bearings, across the antimeridian too', () => {
assert.ok(Math.abs(courseBetweenFixes(0, 0, 0, 0.01) - 90) < 1e-6);
assert.ok(Math.abs(courseBetweenFixes(0, 0, -0.01, 0) - 180) < 1e-6);
assert.ok(
Math.abs(courseBetweenFixes(0, 179.9997, 0, -179.9997) - 90) < 1e-6,
);
assert.equal(courseBetweenFixes(30, -97, 30.0001, -97), null, 'about 11 m');
assert.equal(courseBetweenFixes(null, 0, 0, 0.01), null);
});
test('the anchor moves only with a course, and only forward in time', () => {
let state = courseFromFixes(null, { lat: 0, lon: 0, ms: 0 });
assert.equal(state.courseDeg, null);
assert.deepEqual(state.anchor, { lat: 0, lon: 0, ms: 0 });
const first = state.anchor;
state = courseFromFixes(first, { lat: 0, lon: 0.0001, ms: 1000 });
assert.equal(state.courseDeg, null, '11 m: no course');
assert.equal(state.anchor, first, 'the anchor stays');
state = courseFromFixes(first, { lat: 0, lon: 0.0005, ms: 500 });
assert.equal(state.courseDeg, null, 'not a second newer');
state = courseFromFixes(first, {
lat: 0,
lon: 0.0005,
ms: 2000,
speedMps: 1,
});
assert.equal(state.courseDeg, null, 'standing');
state = courseFromFixes(first, {
lat: 0,
lon: 0.0005,
ms: 2000,
speedMps: 8,
});
assert.ok(Math.abs(state.courseDeg - 90) < 1e-6);
assert.deepEqual(state.anchor, { lat: 0, lon: 0.0005, ms: 2000 });
state = courseFromFixes(first, { lat: NaN, lon: 0, ms: 3000 });
assert.equal(state.anchor, first);
});
+177 -49
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { creditFromMarkup } from '../render/creditMarkup.js';
import { findCredits } from '../render/rendererOf.js';
/**
* Per-layer data attribution registered into Cesium's credit display.
@@ -44,6 +45,20 @@ export const ACARTIA_CREDIT = Object.freeze({
const osmDisplays = new WeakMap();
/** The short inline OSM credits, as the renderer's credits port takes them. */
const OSM_INLINE_CREDITS = Object.freeze({
osm: Object.freeze({
text: '© OpenStreetMap',
href: 'https://www.openstreetmap.org/copyright',
inline: true,
}),
tiles: Object.freeze({
text: '© OpenMapTiles',
href: 'https://openmaptiles.org',
inline: true,
}),
});
function updateOsmDisplay(viewer, state) {
const osm = state.owners.size > 0;
let tiles = false;
@@ -52,37 +67,27 @@ function updateOsmDisplay(viewer, state) {
['osm', osm],
['tiles', tiles],
]) {
if (state[key].visible === visible) continue;
state[key].visible = visible;
viewer.creditDisplay[visible ? 'addStaticCredit' : 'removeStaticCredit'](
state[key].credit,
);
viewer.scene?.requestRender?.();
if (Boolean(state.offs[key]) === visible) continue;
if (visible) {
// Looked up each time: a renderer bound later takes over.
const credits = findCredits(viewer);
if (credits) state.offs[key] = credits.addStatic(OSM_INLINE_CREDITS[key]);
} else {
state.offs[key]();
state.offs[key] = null;
}
}
}
/** Keep one short inline credit while an OSM display owner has visible data. */
/**
* Keep one short inline credit, through the renderer's credits port, while
* an OSM display owner has visible data.
*/
export function showOsmCredit(viewer, owner, { openMapTiles = false } = {}) {
if (!viewer?.creditDisplay?.addStaticCredit || !owner) return false;
if (!owner || !findCredits(viewer)) return false;
let state = osmDisplays.get(viewer);
if (!state) {
state = {
owners: new Map(),
osm: {
visible: false,
credit: new Cesium.Credit(
'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">© OpenStreetMap</a>',
true,
),
},
tiles: {
visible: false,
credit: new Cesium.Credit(
'<a href="https://openmaptiles.org" target="_blank" rel="noopener">© OpenMapTiles</a>',
true,
),
},
};
state = { owners: new Map(), offs: { osm: null, tiles: null } };
osmDisplays.set(viewer, state);
}
if (state.owners.get(owner) === openMapTiles) return false;
@@ -134,6 +139,20 @@ export const DATA_CREDITS = [
'copied, published, or incorporated into other databases without the ' +
'explicit permission of David J Taylor, Edinburgh',
},
{
key: 'planespotters',
html:
'Aircraft photos: ' +
'<a href="https://www.planespotters.net" target="_blank" rel="noopener">Planespotters.net</a> ' +
'· each photo is © its photographer, credited beside it',
},
{
key: 'openvesselphotos',
html:
'Vessel photos: ' +
'<a href="https://openvesselphotos.org" target="_blank" rel="noopener">Open Vessel Photos</a> ' +
"· each photo keeps its author's open licence, credited beside it",
},
{
key: 'aisstream',
html:
@@ -496,6 +515,10 @@ export const DATA_CREDITS = [
key: 'gtfs-rt',
html: 'Transit vehicles: operator GTFS-Realtime feeds (each operator is credited below when its vehicles are shown)',
},
{
key: 'rail-gtfs-rt',
html: 'Trains: operator realtime feeds (each operator is credited below when its trains are shown)',
},
{
key: 'radio-browser',
html:
@@ -566,6 +589,38 @@ export const DATA_CREDITS = [
'licensed under <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank" rel="noopener">CC BY-NC-SA 4.0</a>. ' +
'Shown as published; reports are S2 assessments, not verified fact.',
},
{
key: 'news',
html:
'News: every report is credited to its own publisher and links to the original article; ' +
'pictures are the publishers’ own, shown from their sites with the publisher named. ' +
'Places, categories, severity and English headlines are derived automatically, by ' +
'bundled rules, the news provider or the configured news server, and can be wrong.',
},
{
// GDELT's terms ask for a citation and a link.
key: 'gdelt-news',
html:
'News, Conflicts without a news server: events and page titles from the ' +
'<a href="https://www.gdeltproject.org/" target="_blank" rel="noopener">GDELT Project</a> ' +
'(GDELT 2.0 events and GKG; places and categories are machine-coded)',
},
{
// World News API's free plan asks for a visible "World News API" link to
// its site; always listed, so a free-plan key is never shown without it.
key: 'worldnewsapi',
html:
'News, Local without a news server: headlines from ' +
'<a href="https://worldnewsapi.com/" target="_blank" rel="noopener">World News API</a>',
},
{
key: 'shipwrecks',
html:
'Shipwrecks (Europe): <a href="https://emodnet.ec.europa.eu/en/human-activities" target="_blank" rel="noopener">EMODnet Human Activities</a> ' +
'(data originator AND-International, compiled from SHOM, Ireland&rsquo;s National Monuments Service, Historic England and the Oxford Roman Economy Project), ' +
'licensed under <a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>' +
' · Shipwrecks (worldwide): <a href="https://www.wikidata.org/" target="_blank" rel="noopener">Wikidata</a> (CC0)',
},
{
key: 'drivebc-cctv',
html:
@@ -632,6 +687,15 @@ export const TOMTOM_CREDIT = {
'<a href="https://www.tomtom.com" target="_blank" rel="noopener">TomTom</a>',
};
/** Registered when the News layer shows a Liveuamap report (only with
* LIVEUAMAP_API_KEY set and no news server). */
export const LIVEUAMAP_CREDIT = {
key: 'liveuamap',
html:
'News, Conflicts: mapped reports from ' +
'<a href="https://liveuamap.com/" target="_blank" rel="noopener">Liveuamap</a>',
};
/** Registered when the first Natural Earth region or state/province outline
* resolves (public domain — no attribution required; credited as a courtesy). */
export const NATURAL_EARTH_CREDIT = {
@@ -641,6 +705,15 @@ export const NATURAL_EARTH_CREDIT = {
'<a href="https://www.naturalearthdata.com" target="_blank" rel="noopener">Natural Earth</a> (public domain)',
};
/** Registered when a name from the bundled Wikidata places packs is first
* shown (CC0 — no attribution required; credited as a courtesy). */
export const WIKIDATA_PLACES_CREDIT = {
key: 'wikidata-places',
html:
'City, town and village names from ' +
'<a href="https://www.wikidata.org" target="_blank" rel="noopener">Wikidata</a> (CC0)',
};
/** Registered when the first bundled US county or place outline resolves
* (public domain — credited as a courtesy). */
export const US_CENSUS_CREDIT = {
@@ -711,6 +784,20 @@ export function transitFeedCredit(feed, snapshot = null) {
};
}
/**
* Per-feed rail credit, registered the first time that feed's trains render
* (see `src/data/railFeeds.js` for the licence of each).
* @param {{ id: string, attribution: string, license: string, licenseUrl: string }} feed
* @returns {{ key: string, html: string }}
*/
export function railFeedCredit(feed) {
const transit = transitFeedCredit(feed);
return {
key: `rail-${feed.id}`,
html: transit.html.replace(/^Transit \(/, 'Trains ('),
};
}
/** Registered when the Bhote Koshi event reconstruction activates. */
export const BHOTE_KOSHI_CREDIT = {
key: 'bhote-koshi-2026',
@@ -730,43 +817,84 @@ export const BHOTE_KOSHI_LOCATOR_CREDIT = {
'(CC BY-NC 4.0)',
};
/** A link, its whole element. */
const LINK = /<a\b(?:[^>"']|"[^"]*"|'[^']*')*>[\s\S]*?<\/a\s*>/gi;
/**
* The separators text between two links can break at; it breaks at its
* last. A semicolon ending a character reference is not one. A full stop
* after an abbreviation reads as one, so keep "Dr." and "e.g." out of the
* text between links.
*/
const SEPARATOR = /\s*(?:[,·—–]|(?<!&#?\w+);)\s*|\.\s+|\s+(?=\()/g;
/**
* A credit's markup as the renderer's credits, one link each: the
* contract's credit carries one link, so markup with several becomes one
* credit per link, shown together in order. The text between two links
* breaks at its last separator (a comma, semicolon, dot or dash, a full
* stop, or before an opening bracket); closing brackets right after a link
* stay with it, and a break's comma, semicolon, dot or dash is dropped.
* @param {string} html
* @returns {import('../render/contract/credits').Credit[]}
*/
export function creditsFromMarkup(html) {
const markup = String(html);
const pieces = [''];
let at = 0;
for (const link of markup.matchAll(LINK)) {
let gap = markup.slice(at, link.index);
if (at > 0) {
const close = /^[)\]]*/.exec(gap)[0];
gap = gap.slice(close.length);
const cut = [...gap.matchAll(SEPARATOR)].at(-1);
const before = cut ? gap.slice(0, cut.index) : '';
const stop = cut && cut[0].trimStart().startsWith('.') ? '.' : '';
pieces[pieces.length - 1] += close + before + stop;
pieces.push(cut ? gap.slice(cut.index + cut[0].length) : gap);
} else pieces[0] += gap;
pieces[pieces.length - 1] += link[0];
at = link.index + link[0].length;
}
pieces[pieces.length - 1] += markup.slice(at);
return pieces
.map((piece) => ({ ...creditFromMarkup(piece), inline: false }))
.filter((credit) => credit.text);
}
/** Add a data credit to the attribution list through the renderer. */
function addDataCredit(viewer, credit) {
const credits = findCredits(viewer);
if (!credits) return false;
for (const one of creditsFromMarkup(credit.html)) credits.addStatic(one);
return true;
}
/** @type {Set<string>} Keys of dynamic credits already registered this session. */
const _dynamicCreditKeys = new Set();
/**
* Register a conditional credit at the moment its data source activates.
* Idempotent per `credit.key`; lands in the same "Data attribution" popover
* as the static credits (showOnScreen=false).
* @param {Cesium.Viewer} viewer — the initialized Cesium viewer
* Idempotent per `credit.key`; lands in the same "Data attribution" list
* as the static credits, through the renderer's credits port.
* @param {object} viewer — the scene object the renderer is bound to
* @param {{ key: string, html: string }} credit — e.g. `TOMTOM_CREDIT`
* @returns {boolean} True when the credit is (now) registered.
*/
export function registerDynamicCredit(viewer, credit) {
const creditDisplay = viewer?.creditDisplay;
if (!creditDisplay || typeof creditDisplay.addStaticCredit !== 'function') {
return false;
}
if (!credit?.key || !credit?.html) return false;
if (_dynamicCreditKeys.has(credit.key)) return true;
creditDisplay.addStaticCredit(new Cesium.Credit(credit.html, false));
if (!viewer || !credit?.key || !credit?.html) return false;
if (_dynamicCreditKeys.has(credit.key)) return Boolean(findCredits(viewer));
if (!addDataCredit(viewer, credit)) return false;
_dynamicCreditKeys.add(credit.key);
return true;
}
/**
* Register every per-layer data credit into the viewer's credit display.
* Idempotent: safe to call once at init. Credits are static and always
* present in the "Data attribution" popover.
* @param {Cesium.Viewer} viewer — the initialized Cesium viewer
* Register every per-layer data credit through the renderer's credits
* port. Safe to call once at init. Credits are static and always present
* in the "Data attribution" list, not on the map's credit line.
* @param {object} viewer — the scene object the renderer is bound to
*/
export function registerDataCredits(viewer, credits = DATA_CREDITS) {
const creditDisplay = viewer?.creditDisplay;
if (!creditDisplay || typeof creditDisplay.addStaticCredit !== 'function') {
return;
}
for (const { html } of credits) {
// showOnScreen=false → lives in the expandable "Data attribution" popover,
// not the on-globe credit line.
creditDisplay.addStaticCredit(new Cesium.Credit(html, false));
}
if (!viewer) return;
for (const credit of credits) addDataCredit(viewer, credit);
}
+152 -4
View File
@@ -2,10 +2,12 @@ import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
DATA_CREDITS,
LIVEUAMAP_CREDIT,
NYC_DOT_DISCLAIMER,
transitFeedCredit,
} from './dataCredits.js';
import { getTransitFeed } from './transitFeeds.js';
import { bindFakeCesiumCredits } from '../testSupport/fakeCreditsPort.mjs';
test('every credit carries a unique key and some markup to render', () => {
const keys = DATA_CREDITS.map((entry) => entry.key);
@@ -43,6 +45,20 @@ test('adsbdb is credited and carries its published route-data restriction', () =
assert.match(credit.html, /href="https:\/\/www\.adsbdb\.com"/);
});
test('Planespotters is credited with a plain followable link', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'planespotters');
assert.ok(credit, 'the tracked aircraft photos come from Planespotters');
assert.match(credit.html, /href="https:\/\/www\.planespotters\.net"/);
assert.doesNotMatch(credit.html, /nofollow/);
});
test('Open Vessel Photos is credited with a plain followable link', () => {
const credit = DATA_CREDITS.find((entry) => entry.key === 'openvesselphotos');
assert.ok(credit, 'the selected vessel photos come from Open Vessel Photos');
assert.match(credit.html, /href="https:\/\/openvesselphotos\.org"/);
assert.doesNotMatch(credit.html, /nofollow/);
});
test('the UCS Satellite Database is acknowledged with its version and webpage', () => {
// UCS database manual, section 3: references name the version (the Excel
// file's name) and link www.ucsusa.org/satellite_database.
@@ -88,13 +104,13 @@ test('inline OSM attribution persists until its last display owner leaves', asyn
const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js');
t.mock.timers.enable({ apis: ['setTimeout'] });
const visible = new Set();
const viewer = {
const viewer = bindFakeCesiumCredits({
creditDisplay: {
addStaticCredit: (c) => visible.add(c),
removeStaticCredit: (c) => visible.delete(c),
},
scene: { requestRender() {} },
};
});
assert.equal(showOsmCredit(viewer, 'alpr'), true);
assert.equal(showOsmCredit(viewer, 'alpr'), false);
assert.equal(visible.size, 1);
@@ -128,13 +144,13 @@ test('tile attribution follows source changes and viewers have independent owner
const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js');
const create = () => {
const credits = new Set();
return {
return bindFakeCesiumCredits({
credits,
creditDisplay: {
addStaticCredit: (c) => credits.add(c),
removeStaticCredit: (c) => credits.delete(c),
},
};
});
};
const a = create(),
b = create();
@@ -182,6 +198,129 @@ test('every Street Level imagery source is in the attribution lightbox', () => {
);
});
test('a credit with several links becomes one credit per link, in order', async () => {
const {
creditsFromMarkup,
OSM_CREDIT,
OPENMAPTILES_CREDIT,
WOF_CREDIT,
BHOTE_KOSHI_CREDIT,
} = await import('./dataCredits.js');
const html = (key) => DATA_CREDITS.find((entry) => entry.key === key).html;
const read = (markup) =>
creditsFromMarkup(markup).map(({ text, href }) => [text, href]);
assert.deepEqual(read(OSM_CREDIT.html), [
[
'Map and place data © OpenStreetMap contributors',
'https://www.openstreetmap.org/copyright',
],
['(ODbL)', 'https://opendatacommons.org/licenses/odbl/1-0/'],
]);
assert.deepEqual(read(OPENMAPTILES_CREDIT.html), [
['Vector tiles: OpenFreeMap', 'https://openfreemap.org'],
['© OpenMapTiles', 'https://openmaptiles.org'],
]);
assert.deepEqual(read(html('nasa-gibs'))[1], [
'HLS product page',
'https://lpdaac.usgs.gov/products/hlss30v002/',
]);
assert.deepEqual(read(html('wfigs')), [
[
'Wildfire perimeters: National Interagency Fire Center (WFIGS)',
'https://data-nifc.opendata.arcgis.com/',
],
['Incident information: InciWeb', 'https://inciweb.wildfire.gov/'],
]);
assert.deepEqual(read(html('eccc-aqhi')), [
[
'Air quality (AQHI): Environment and Climate Change Canada — MSC GeoMet (eccc-msc.github.io/open-data)',
'https://eccc-msc.github.io/open-data/',
],
[
'ECCC Data Servers End-use Licence',
'https://eccc-msc.github.io/open-data/licence/readme_en/',
],
]);
assert.deepEqual(
read(BHOTE_KOSHI_CREDIT.html)[1][0].slice(0, 15),
'and GeoPera (CC',
);
assert.deepEqual(
read(WOF_CREDIT.html).map(([text]) => text),
[
"Neighborhood boundaries: Who's On First and contributors, simplified",
'(sources and licences)',
],
);
const link = (text) => `<a href="https://example.org">${text}</a>`;
assert.deepEqual(
read(`${link('A')} by Hoffleit &amp; Warren ${link('B')}`).map(
([text]) => text,
),
['A', 'by Hoffleit & Warren B'],
'a character reference is not a separator',
);
assert.deepEqual(read(html('usgs')), [
['Earthquakes: Data courtesy of the U.S. Geological Survey', undefined],
]);
for (const entry of DATA_CREDITS) {
const credits = creditsFromMarkup(entry.html);
const links = entry.html.match(/<a\b/g)?.length ?? 0;
assert.equal(credits.length, Math.max(links, 1), entry.key);
assert.ok(
credits.every((credit) => credit.inline === false),
`${entry.key} belongs in the attribution list`,
);
}
});
test('data credits go through the renderer to the attribution list', async () => {
const { registerDataCredits, registerDynamicCredit, TOMTOM_CREDIT } =
await import('./dataCredits.js');
const shown = [];
const viewer = bindFakeCesiumCredits({
creditDisplay: {
addStaticCredit: (c) => shown.push(c),
removeStaticCredit() {},
},
});
const credits = DATA_CREDITS.filter((entry) =>
['openstreetmap', 'usgs'].includes(entry.key),
);
registerDataCredits(viewer, credits);
assert.equal(shown.length, 3);
assert.ok(shown.every((credit) => !credit.showOnScreen));
const odbl = shown.find((credit) => credit.html.includes('opendatacommons'));
assert.match(odbl.html, /href="https:\/\/opendatacommons.org/);
// As the source wrote it: only the licence's name is the link.
assert.match(odbl.html, /\(<a [^>]*>ODbL<\/a>\)/);
assert.equal(registerDynamicCredit(viewer, TOMTOM_CREDIT), true);
assert.equal(registerDynamicCredit(viewer, TOMTOM_CREDIT), true);
assert.equal(shown.length, 4, 'a dynamic credit is added once');
assert.match(shown[3].html, /Traffic flow data © <a [^>]*>TomTom<\/a>/);
assert.equal(registerDynamicCredit({}, { key: 'none', html: 'x' }), false);
});
test('the News layer credits its built-in sources', () => {
const credit = (key) => DATA_CREDITS.find((entry) => entry.key === key);
// GDELT's terms ask for a citation and a link.
assert.match(
credit('gdelt-news').html,
/href="https:\/\/www\.gdeltproject\.org\/"[^>]*>GDELT Project</,
);
// World News API's free plan asks for this exact link.
assert.match(
credit('worldnewsapi').html,
/<a href="https:\/\/worldnewsapi\.com\/"[^>]*>World News API<\/a>/,
);
assert.match(LIVEUAMAP_CREDIT.html, />Liveuamap</);
assert.ok(
!DATA_CREDITS.some((entry) => entry.key === LIVEUAMAP_CREDIT.key),
'Liveuamap is credited only once its key is in use',
);
assert.doesNotMatch(credit('news').html, /No single provider/);
});
test('the PR #1506 camera packs are credited with their sources and terms', () => {
const html = (key) => DATA_CREDITS.find((entry) => entry.key === key)?.html;
assert.match(html('ottawa-cctv') || '', /traffic\.ottawa\.ca/);
@@ -216,3 +355,12 @@ test('Warsaw and Poznań credits carry the data date their licences ask for', ()
assert.equal(mbta.key, 'transit-mbta');
assert.doesNotMatch(mbta.html, /data of/);
});
test('the always-on rail credit names live feeds only, never timetables', () => {
// Every train shown is where its operator reported it; none is placed
// from a timetable.
const rail = DATA_CREDITS.find((entry) => entry.key === 'rail-gtfs-rt');
assert.ok(rail);
assert.match(rail.html, /realtime feeds/);
assert.doesNotMatch(rail.html, /timetable|placed from/i);
});
+158 -16
View File
@@ -1,5 +1,4 @@
import { paintTransitBracket } from './detectionDraw.js';
import * as Cesium from 'cesium';
import { governorRequestRender } from '../renderGovernor.js';
import {
DETECTION_ENABLE_FADE_MS,
@@ -21,7 +20,10 @@ import {
getKeyholeFadeTuning,
keyholeLabelAlphaFromGeometry,
} from '../celestialRing.js';
import { registerWorldOverlayPaintLane } from '../overlays/worldOverlay.js';
import {
getQueuedOverlayEntryAlpha,
registerWorldOverlayPaintLane,
} from '../overlays/worldOverlay.js';
import {
DETECTION_STYLE,
DETECTION_THEME_MAP,
@@ -47,6 +49,8 @@ import {
viewScaleForAltitude,
} from './detectionPolicy.js';
import { detectionBracketOpacity } from './detectionPresentation.js';
import { SurfaceOcclusion } from './detectionOcclusion.js';
import { rendererOf } from '../render/rendererOf.js';
import {
createCyberSonarSampler,
cyberSonarFrameDelay,
@@ -107,6 +111,8 @@ const THEME_MAP = DETECTION_THEME_MAP;
const SPARSE_ZONE_FRACTION = 0.5;
/** Solve cadence for membership/collision; accepted identities still reproject every frame. */
const LABEL_SOLVE_INTERVAL_MS = 125;
/** Own-card opacity that fully hides a callout; below it the callout fades in. */
const CARD_ALPHA_HIDING_CALLOUT = 0.5;
/** Alpha bands retain bracket batching while approximating a continuous radial fade. */
const BRACKET_ALPHA_STEPS = 4;
/** Finer bands for Global Context echo brackets, whose fade is animated. */
@@ -197,11 +203,9 @@ export function countFadingRenderEntries(renderEntries) {
return count;
}
// ---------------------------------------------------------------------------
// Module-level state — singleton lifecycle tied to the Cesium viewer
// Module-level state — singleton lifecycle tied to the shared overlay host
// ---------------------------------------------------------------------------
/** @type {Cesium.Viewer|null} */
let _viewer = null;
/** @type {number} Current mode index into MODE_LABELS */
let _mode = MODE_OFF;
/** @type {HTMLCanvasElement|null} Shared host canvas used for QA diagnostics. */
@@ -263,6 +267,51 @@ let _allocationStrategy = ALLOCATION_ELASTIC;
let _lastNonOffMode = MODE_BALANCED;
/** @type {LabelArbiter} Shared stable callout selector. */
const _labelArbiter = new LabelArbiter();
/**
* A probe that tests nothing: a renderer without an occlusion probe of its
* own draws every depth-tested contact's bracket and callout.
*/
const NO_OCCLUSION_PROBE = Object.freeze({
mode: 'off',
maxPerFrame: 0,
lastFrameMs: 0,
lastFrameTests: 0,
beginFrame() {},
add: () => false,
endFrame() {},
reset() {},
destroy() {},
});
/**
* Hides the bracket and callout of a depth-tested contact (a street vehicle)
* that the scene drew something in front of. `_occlusionProbe` asks the GPU
* about each such contact without waiting for the answer (the renderer's
* `query.occlusionTest()`, where it has the `occlusionTest` capability);
* `_surfaceOcclusion` remembers the answers and decides, every frame, who is
* drawn.
*/
let _occlusionProbe = NO_OCCLUSION_PROBE;
const _surfaceOcclusion = new SurfaceOcclusion(_occlusionProbe);
/** Use the occlusion probe of `viewer`'s renderer, or none. */
function _useOcclusionProbe(viewer) {
_occlusionProbe.destroy();
const renderer = rendererOf(viewer);
_occlusionProbe =
(renderer?.capabilities?.has('occlusionTest') &&
renderer.query.occlusionTest?.()) ||
NO_OCCLUSION_PROBE;
_surfaceOcclusion.clear();
_surfaceOcclusion.probe = _occlusionProbe;
}
/**
* Keys of callouts the label arbiter still holds for contacts last seen
* hidden. A key stays here until its contact is seen drawn again or the
* arbiter lets the callout go, so the callout cannot come back at its old
* place just because its contact has since left the view.
*/
const _surfaceSuppressedKeys = new Set();
let _surfaceDepthFallbackReported = false;
let _lastLabelSolveAt = 0;
let _labelSolveDirty = true;
let _lastDiagnostics = null;
@@ -288,7 +337,9 @@ let _cockpitModeListener = null;
/**
* Initializes detection inside the shared world-overlay host and stores
* references to data layers. The host owns the canvas and render listener.
* @param {Cesium.Viewer} viewer - The active Cesium viewer instance.
* @param {object} viewer - The host the renderer is bound to. The
* world-overlay host hands each paint its camera; the renderer's occlusion
* probe, where it has one, tests depth-tested contacts.
* @param {Array} layers - Data layer modules that may implement getDetectableObjects().
* @param {Function} onModeChange - Callback invoked with the new mode label string on mode changes.
*/
@@ -301,9 +352,9 @@ export function initDetection(viewer, layers, onModeChange) {
}
_hostLane?.unregister?.();
_calloutLane?.unregister?.();
_viewer = viewer;
_layers = layers;
_onModeChange = onModeChange;
_useOcclusionProbe(viewer);
_debugBanner = detectionDebugRequested(
typeof window !== 'undefined' ? window.location?.search : '',
);
@@ -357,7 +408,6 @@ export function destroyDetection() {
_calloutLane = null;
_transitBracketPaths.clear();
_calloutCount = 0;
_viewer = null;
_layers = [];
_onModeChange = null;
_hostCanvas = null;
@@ -367,6 +417,9 @@ export function destroyDetection() {
_suspended = false;
_suspendReason = '';
_labelArbiter.clear();
_surfaceOcclusion.clear();
_surfaceSuppressedKeys.clear();
_useOcclusionProbe(null);
_lastLabelSolveAt = 0;
_labelSolveDirty = true;
_lastDiagnostics = null;
@@ -576,7 +629,8 @@ export function getDetectionDiagnostics() {
// sprites/strokes. Nothing is copied on the production paint path.
result.calloutRects = _calloutPool
.slice(0, _calloutCount)
.map(({ x, y, w, h, alpha }) => ({ x, y, w, h, alpha }));
.filter((row) => row.paintAlpha > 0.001)
.map(({ x, y, w, h, paintAlpha }) => ({ x, y, w, h, alpha: paintAlpha }));
return result;
}
@@ -691,6 +745,9 @@ function _applyModeState() {
_syncSurfaceVisibility();
_setLanesActive(false);
_labelArbiter.clear();
_surfaceOcclusion.clear();
_surfaceSuppressedKeys.clear();
_occlusionProbe.reset();
_lastLabelSolveAt = 0;
_labelSolveDirty = true;
_lastSolveSnapshot = {
@@ -1077,6 +1134,9 @@ function _stashCallout(entry, acquireFade, keyhole) {
font: FONT,
microFont: MICRO_FONT,
alpha: 1,
cardSourceId: '',
cardEntryId: '',
paintAlpha: 1,
};
_calloutPool[_calloutCount] = row;
}
@@ -1103,6 +1163,8 @@ function _stashCallout(entry, acquireFade, keyhole) {
row.font = FONT;
row.microFont = MICRO_FONT;
row.alpha = alpha;
row.cardSourceId = candidate.cardSourceId;
row.cardEntryId = candidate.cardEntryId;
_calloutCount++;
}
@@ -1134,7 +1196,15 @@ function _paintCalloutLane(frame) {
ctx.textBaseline = 'alphabetic';
for (let i = 0; i < _calloutCount; i++) {
const row = _calloutPool[i];
paintDetectionCallout(ctx, row, row.alpha);
// The callout would show through its contact's own card: fade it by the
// opacity that card paints with this frame.
const cardAlpha =
row.cardEntryId === ''
? 0
: getQueuedOverlayEntryAlpha(row.cardSourceId, row.cardEntryId);
row.paintAlpha =
row.alpha * Math.max(0, 1 - cardAlpha / CARD_ALPHA_HIDING_CALLOUT);
if (row.paintAlpha > 0.001) paintDetectionCallout(ctx, row, row.paintAlpha);
}
ctx.globalAlpha = 1;
}
@@ -1151,6 +1221,15 @@ function _plateScaleForBackdrop(skyFactor) {
return 1 + (SKY_PLATE_SCALE - 1) * skyFactor;
}
/**
* The eye's height above the ellipsoid (m) for this paint, from the host
* frame (the camera port's pose); undefined when the pose has none.
*/
function _eyeHeight(frame) {
const height = frame.cameraHeight;
return Number.isFinite(height) ? height : undefined;
}
/** Materialize one bounded rich-callout candidate for the existing arbiter. */
function _materializeCandidate(
obj,
@@ -1211,6 +1290,8 @@ function _materializeCandidate(
primary,
micro,
hasMicro: card.hasMicro,
cardSourceId: obj.cardSourceId ? String(obj.cardSourceId) : '',
cardEntryId: obj.cardEntryId ? String(obj.cardEntryId) : '',
};
}
@@ -1273,9 +1354,7 @@ function _drawOverlay(frame) {
profile: MODE_LABELS[_mode],
densityPct: _densityPct,
allocationStrategy: _allocationStrategy,
viewScale: viewScaleForAltitude(
_viewer?.camera?.positionCartographic?.height,
),
viewScale: viewScaleForAltitude(_eyeHeight(frame)),
candidateCount: 0,
observationCount: 0,
visibleCount: 0,
@@ -1316,6 +1395,9 @@ function _drawOverlay(frame) {
// every host lane. Detection retains the manual scalar projection below.
const occluder = frame.occluder;
const camPos = frame.cameraPosition;
// Answers to the occlusion tests started on earlier frames land here.
_surfaceOcclusion.beginFrame(now);
_occlusionProbe.beginFrame(_surfaceOcclusion.now);
const keyhole = frame.keyhole;
// Read the OUTSIDE setting ONCE per paint, from the same module state the
// host's own keyhole alpha comes from, so a bracket and its callout can never
@@ -1402,8 +1484,11 @@ function _drawOverlay(frame) {
let halfW;
let halfH;
if (obj.type === 'AIR') {
const dx = camPos.x - obj.position.x;
const dy = camPos.y - obj.position.y;
const dz = camPos.z - obj.position.z;
const bscale = nearFarScale(
Cesium.Cartesian3.distance(camPos, obj.position),
Math.sqrt(dx * dx + dy * dy + dz * dz),
BILL_NEAR,
BILL_NEAR_SCALE,
BILL_FAR,
@@ -1426,6 +1511,29 @@ function _drawOverlay(frame) {
// The bracket follows the same linear radial keyhole fade as its callout.
const color = colorFor(resolveTier(obj));
const keyholeAlpha = keyholeLabelAlphaFromGeometry(sx, sy, keyhole);
// Something the scene drew in front of a depth-tested contact hides its
// bracket and callout too, on every frame, not only on solves.
if (obj.depthTested === true) {
const testedLayerId = obj._layerId || 'unknown';
const testedSourceId = obj.sourceId ?? obj.id ?? i;
const hidden = _surfaceOcclusion.isHidden(
testedLayerId,
testedSourceId,
obj.position,
);
// If the arbiter holds a callout for this contact it would keep painting
// it until the next solve, and then fade it out where it last stood;
// see `_surfaceSuppressedKeys`. Only held contacts cost a key.
if (
(hidden || _surfaceSuppressedKeys.size > 0) &&
renderIdentities.get(testedLayerId)?.has(testedSourceId)
) {
const key = _detectionKey(testedLayerId, testedSourceId);
if (hidden) _surfaceSuppressedKeys.add(key);
else _surfaceSuppressedKeys.delete(key);
}
if (hidden) continue;
}
const sonarFactor =
sonarActive && !obj.skipLabel ? sonarSampler.at(sx, sy) : 1;
const sonarLabelFactor = sonarSampler.label(sonarFactor);
@@ -1526,8 +1634,10 @@ function _drawOverlay(frame) {
candidateMap.set(candidate.key, candidate);
}
}
// Start this frame's occlusion tests; nothing here waits for them.
_occlusionProbe.endFrame();
const altitude = _viewer?.camera?.positionCartographic?.height ?? 1e9;
const altitude = _eyeHeight(frame) ?? 1e9;
const collectiveBudget = labelBudgetFor(altitude, _densityPct);
const ambientBudget = Math.max(
0,
@@ -1536,6 +1646,13 @@ function _drawOverlay(frame) {
let didSolve = false;
let solveMs = 0;
if (shouldSolve) {
_surfaceOcclusion.prune();
if (_occlusionProbe.mode === 'sync' && !_surfaceDepthFallbackReported) {
_surfaceDepthFallbackReported = true;
console.info(
'[detection] No occlusion queries here (WebGL 1); street-vehicle label occlusion reads the frame depth back synchronously, about 8 times a second.',
);
}
const quotas = allocateLayerQuotas(
demandByLayer,
ambientBudget,
@@ -1622,7 +1739,25 @@ function _drawOverlay(frame) {
_ctx.lineWidth = bracketWidth;
}
const renderEntries = _labelArbiter.renderEntries(candidateMap, now);
let renderEntries = _labelArbiter.renderEntries(candidateMap, now);
// A callout whose contact has gone behind something goes with it at once:
// no carry-over to the next solve and no fade painted on the facade.
if (_surfaceSuppressedKeys.size > 0) {
const allEntries = renderEntries;
renderEntries = allEntries.filter(
(entry) => !_surfaceSuppressedKeys.has(entry.candidate.key),
);
// The arbiter has let some of them go: forget those.
if (
allEntries.length - renderEntries.length !==
_surfaceSuppressedKeys.size
) {
const held = new Set();
for (const entry of allEntries) held.add(entry.candidate.key);
for (const key of _surfaceSuppressedKeys)
if (!held.has(key)) _surfaceSuppressedKeys.delete(key);
}
}
const fadingCount = countFadingRenderEntries(renderEntries);
// Demand counts fades in BOTH directions; `fadingCount` above stays the
// fade-OUT tail because that is what the published diagnostics have always
@@ -1677,6 +1812,13 @@ function _drawOverlay(frame) {
keyholeRadius: keyhole.radius,
keyholeFeatherPx: keyhole.featherPx,
calloutOcclusionCount: calloutOcclusionRects.length,
surfaceTestedCount: _surfaceOcclusion.testedCount,
surfaceHiddenCount: _surfaceOcclusion.hiddenCount,
surfaceDepthMode: _occlusionProbe.mode,
// Tests started on the last frame, and what collecting answers and
// drawing them cost it.
surfaceProbeTests: _occlusionProbe.lastFrameTests,
surfaceProbeMs: _occlusionProbe.lastFrameMs,
};
} else {
const selectedCount = _labelArbiter.selectedKeys.size;
+499
View File
@@ -1,3 +1,4 @@
import { bindOverlayPorts } from '../testSupport/fakeOverlayPorts.mjs';
import { readShellSource } from '../testSupport/readShellSource.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
@@ -20,15 +21,30 @@ import {
} from './detection.js';
import {
destroyWorldOverlay,
getOverlayPaintRect,
initWorldOverlay,
setOverlayEntries,
} from '../overlays/worldOverlay.js';
import { applyVesselOverlayPolicy } from './vesselLabels.js';
import {
getKeyholeFadeTuning,
getKeyholeGeometry,
keyholeLabelAlphaFromGeometry,
} from '../celestialRing.js';
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
import {
clearAwarenessEchoField,
setAwarenessEchoField,
} from '../awarenessEcho.js';
import { composeLabel, resolveTier } from './detectionDraw.js';
import {
createFakeDepthScene,
createFakeGl,
depthImage,
viewDistanceToDepth,
} from '../render/cesium/fixtures/fakeDepthScene.mjs';
import { createSceneOcclusionTest } from '../render/cesium/sceneOcclusionProbe.js';
import { rendererOf } from '../render/rendererOf.js';
test('detection diagnostics count rendered fading rows instead of absent selected identities', () => {
assert.equal(countFadingRenderEntries([
@@ -251,6 +267,7 @@ function installEnvironment({ width = 800, height = 600, dpr = 2, search = '' }
},
scene: { postRender, requestRender() {} },
};
bindOverlayPorts(viewer);
return {
viewer,
@@ -541,6 +558,25 @@ test('callouts stop painting the moment the last detectable object goes away', (
}
});
test('the view scale reads the camera height the overlay host gives each paint', () => {
const env = installEnvironment();
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'flights', getDetectableObjects: () => [] }], () => {});
setMode('DENSE');
const scaleAt = (height) => {
env.viewer.camera.positionCartographic.height = height;
env.advance(250);
env.postRender.raise();
return getDetectionDiagnostics().viewScale;
};
assert.equal(scaleAt(1000), 'street');
assert.equal(scaleAt(10000), 'metro');
} finally {
env.cleanup();
}
});
test('every style paints its OWN plate token through the production callout path', () => {
// The token table and the direct painter are both pinned elsewhere, but a
// pin on either one still passes if the runtime stops consulting the active
@@ -579,6 +615,178 @@ test('every style paints its OWN plate token through the production callout path
}
});
/** A vessel detection contact that names its ambient card, like the AIS layer does. */
function shipWithCard(mmsi, position) {
return {
position,
sourceId: mmsi,
id: `SHIP-${mmsi}`,
metric: '6 kn',
type: 'SEA',
cardSourceId: 'ais-live-vessels',
cardEntryId: `vessel:${mmsi}`,
};
}
/** The production ambient vessel card (not protected: it goes through the arbiter). */
function ambientVesselCard(mmsi, position) {
return applyVesselOverlayPolicy({
id: `vessel:${mmsi}`,
position,
title: `CARD-${mmsi}`,
details: ['CARGO · 6KT · 80°'],
gapPx: 10,
});
}
test('a callout stays readable when its own card is faded out at the keyhole rim', () => {
// Default keyhole tuning: 7% feather, 1% outside opacity.
assert.deepEqual(getKeyholeFadeTuning(), { fadeRatio: 0.07, outsideOpacity: 0.01 });
const width = 1600;
const height = 900;
const keyhole = getKeyholeGeometry(width, height);
const env = installEnvironment({ width, height, dpr: 1 });
// Just outside the keyhole's left rim: the card sits above or below the
// anchor (outside, 1% alpha), the callout to its right (inside the feather).
const position = new Cesium.Cartesian3(270 / (width / 2) - 1, 1 - 460 / (height / 2), 6_356_752);
const ship = shipWithCard('200', position);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
const [alone] = getDetectionDiagnostics().calloutRects;
assert.ok(alone && alone.alpha >= 0.5, 'without a card the callout is clearly visible');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', position)]);
for (let i = 0; i < 4; i++) settleFrame(env);
const rect = getOverlayPaintRect('ais-live-vessels', 'vessel:200');
assert.ok(rect, 'the host paints the card (at the outside opacity)');
const cardAlpha = keyholeLabelAlphaFromGeometry(rect.x + rect.w / 2, rect.y + rect.h / 2, keyhole);
assert.ok(cardAlpha <= 0.05, `the card is invisible at the rim (keyhole alpha ${cardAlpha})`);
const callouts = getDetectionDiagnostics().calloutRects;
assert.equal(callouts.length, 1, 'the callout keeps painting while its card is faded out');
assert.ok(callouts[0].alpha >= 0.4, 'and stays readable');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a callout stays hidden while its card fades out after leaving the published cohort', () => {
const env = installEnvironment({ width: 1600, height: 900, dpr: 1 });
const at = (x, y) => new Cesium.Cartesian3(x, y, 6_356_752);
const ship = shipWithCard('200', at(0.1, 0.1));
const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text);
const frame = (ms) => {
env.ctx.calls.length = 0;
env.advance(ms);
env.postRender.raise();
};
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]);
for (let i = 0; i < 6; i++) frame(250);
frame(16);
assert.ok(painted('CARD-200') && !painted('SHIP-200'), 'steady state: card only');
// The vessel layer republishes its screen-grid cohort after a camera move:
// this vessel's card is replaced by another one, the vessel stays detectable.
setOverlayEntries('ais-live-vessels', [ambientVesselCard('300', at(-0.5, -0.4))]);
frame(16);
assert.ok(getOverlayPaintRect('ais-live-vessels', 'vessel:200'), 'the dropped card is still fading out');
assert.ok(painted('CARD-200'), 'and its text still paints');
assert.ok(!painted('SHIP-200'), 'no full callout under the fading card');
for (let i = 0; i < 4; i++) frame(250);
assert.ok(!painted('CARD-200'), 'the card has faded out');
assert.ok(painted('SHIP-200'), 'and the callout is back');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a vessel whose ambient card loses the collision keeps its callout', () => {
const env = installEnvironment({ width: 900, height: 600, dpr: 1 });
// Four vessels a few pixels apart: their cards collide (a card goes only
// above or below its anchor), so the arbiter paints only some of them.
const ships = [0, 1, 2, 3].map((i) =>
shipWithCard(String(100 + i), new Cesium.Cartesian3(-0.2 + i * 0.005, i * 0.005, 6_356_752)),
);
const painted = (text) => env.ctx.calls.some(([name, value]) => name === 'fillText' && value === text);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => ships }], () => {});
setOverlayEntries(
'ais-live-vessels',
ships.map((ship) => ambientVesselCard(ship.sourceId, ship.position)),
);
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
env.ctx.calls.length = 0;
settleFrame(env);
const winners = ships.filter((ship) => getOverlayPaintRect('ais-live-vessels', ship.cardEntryId));
assert.ok(
winners.length >= 1 && winners.length < ships.length,
`the colliding cards leave some unpainted (${winners.length} of ${ships.length} painted)`,
);
for (const ship of ships) {
const carded = winners.includes(ship);
assert.equal(
painted(ship.id),
!carded,
carded ? `${ship.id} draws no callout under its card` : `${ship.id} keeps its callout`,
);
}
assert.equal(
getDetectionDiagnostics().calloutRects.length,
ships.length - winners.length,
'only the callouts that painted are reported',
);
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('a callout fades out while its card fades in instead of vanishing at once', () => {
const env = installEnvironment({ width: 1600, height: 900, dpr: 1 });
const ship = shipWithCard('200', new Cesium.Cartesian3(0.1, 0.1, 6_356_752));
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, [{ id: 'ais-live-vessels', getDetectableObjects: () => [ship] }], () => {});
setMode('DENSE');
for (let i = 0; i < 4; i++) settleFrame(env);
const [alone] = getDetectionDiagnostics().calloutRects;
assert.ok(alone.alpha >= 0.9, 'the callout starts fully visible');
setOverlayEntries('ais-live-vessels', [ambientVesselCard('200', ship.position)]);
const alphas = [];
for (let i = 0; i < 30; i++) {
env.advance(16);
env.postRender.raise();
alphas.push(getDetectionDiagnostics().calloutRects[0]?.alpha ?? 0);
}
assert.ok(
alphas.some((alpha) => alpha > 0.1 && alpha < alone.alpha - 0.1),
`the callout passes through partial opacity: ${alphas.map((a) => a.toFixed(2)).join(' ')}`,
);
assert.equal(alphas.at(-1), 0, 'and is gone once the card is fully in');
} finally {
destroyDetection();
destroyWorldOverlay();
env.cleanup();
}
});
test('space-tier callouts take the heavier plate while air contacts keep the light one', () => {
// Satellites sit over the high-albedo lit Earth disc far more often than
// aircraft do, so the space tier carries the heavier backing. Losing the
@@ -1190,3 +1398,294 @@ test('transit contacts take the vehicle tier, not the civil-air one', () => {
assert.equal(resolveTier({ type: 'AIR' }), 'civil');
assert.equal(resolveTier({ type: 'SEA' }), 'sea');
});
/**
* Give the host environment a scene that keeps frame depth: the camera 10,000
* km up the +Z axis looking down it, and one depth range in which the whole
* frame is a surface `surfaceDistance()` metres in front of the camera.
*/
function installDepthScene(env, surfaceDistance, { webgl2 = true } = {}) {
const near = 1;
const far = 100_000_000;
const gl = createFakeGl({ webgl2 });
const camera = env.viewer.camera;
camera.viewMatrix = Cesium.Matrix4.fromTranslation(new Cesium.Cartesian3(0, 0, -10_000_000));
camera.frustum.fovy = Math.PI / 2;
camera.frustum.aspectRatio = 800 / 600;
const paint = () =>
depthImage(8, 6, () => viewDistanceToDepth(surfaceDistance(), near, far, true));
const image = paint();
const scene = createFakeDepthScene({ gl, ranges: [{ near, far, image }] });
Object.assign(env.viewer.scene, scene, { camera });
// The renderer's occlusion test, as the Cesium query port gives it.
const renderer = rendererOf(env.viewer);
renderer.capabilities = new Set(['occlusionTest']);
renderer.query.occlusionTest = () =>
createSceneOcclusionTest(env.viewer.scene);
return {
gl,
/** Draw the next frame's depth. */
redraw() {
image.data.set(paint().data);
},
};
}
/** Street contacts 3,643 km and 2,000 km below the camera, and a flight. */
function occlusionLayers() {
return [
{
id: 'traffic',
getDetectableObjects: () => [
{ position: new Cesium.Cartesian3(-0.4, 0, 6_356_752), id: 'VEH-0001', type: 'VEH', depthTested: true },
{ position: new Cesium.Cartesian3(0.4, 0, 8_000_000), id: 'VEH-0002', type: 'VEH', depthTested: true },
],
},
{
id: 'flights',
// The same nearer surface is in front of it, but it is not depth-tested.
getDetectableObjects: () => [
{ position: new Cesium.Cartesian3(-0.4, 0.3, 6_356_752), sourceId: 'f1', id: 'AIR1', metric: 'FL300', type: 'AIR' },
],
},
];
}
function paintedText(env) {
return env.ctx.calls.filter(([name]) => name === 'fillText').map(([, text]) => text);
}
/** One rendered frame 16 ms on; `settleFrame` is one 250 ms on (a solve). */
function nextFrame(env) {
env.advance(16);
env.postRender.raise();
}
test('a depth-tested contact behind drawn geometry loses its bracket and callout, tested on the GPU without anything read back', () => {
const env = installEnvironment();
// A roof 3,000 km below the camera: in front of VEH-0001, behind VEH-0002.
let surface = 3_000_000;
const depth = installDepthScene(env, () => surface);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, occlusionLayers(), () => {});
setMode('DENSE');
settleFrame(env);
let diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceDepthMode, 'async');
assert.equal(diagnostics.surfaceTestedCount, 2, 'only the depth-tested contacts');
assert.equal(diagnostics.surfaceProbeTests, 2);
// New to the view, so held back for the frame or two the first answer
// takes: neither is drawn yet. The flight is.
assert.equal(diagnostics.surfaceHiddenCount, 2, 'no answer has arrived yet');
assert.equal(diagnostics.visibleCount, 1);
assert.equal(depth.gl.counts.queries, 3, 'a control point and one query per contact');
// Frames before the GPU answers start nothing new and wait for nothing.
nextFrame(env);
nextFrame(env);
assert.equal(depth.gl.counts.queries, 3);
assert.equal(depth.gl.counts.resultReads, 0);
// The answers land. The contact above the roof is drawn from then on; the
// one under it never is.
depth.gl.finishGpu();
nextFrame(env);
depth.gl.finishGpu();
settleFrame(env);
env.ctx.calls.length = 0;
nextFrame(env);
assert.ok(!paintedText(env).includes('VEH-0001'));
assert.ok(paintedText(env).includes('VEH-0002'));
// It stays gone, frame after frame and solve after solve.
for (let i = 0; i < 40; i++) {
depth.gl.finishGpu();
env.ctx.calls.length = 0;
nextFrame(env);
assert.ok(!paintedText(env).includes('VEH-0001'), `frame ${i}`);
}
depth.gl.finishGpu();
settleFrame(env);
diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceHiddenCount, 1);
assert.equal(diagnostics.visibleCount, 2, 'the hidden contact has no bracket');
assert.ok(diagnostics.labeledKeys.includes('traffic:VEH-0002'));
assert.ok(!diagnostics.labeledKeys.includes('traffic:VEH-0001'));
assert.ok(diagnostics.labeledKeys.includes('flights:f1'));
assert.ok(paintedText(env).includes('AIR1'));
assert.equal(depth.gl.counts.readPixels, 0, 'depth never left the GPU');
// The roof goes away: the bracket returns once visible answers have kept
// coming for the reappear time, and the callout once a solve re-admits it.
surface = 5_000_000;
depth.redraw();
for (let i = 0; i < 80; i++) {
depth.gl.finishGpu();
nextFrame(env);
}
for (let i = 0; i < 8; i++) {
depth.gl.finishGpu();
settleFrame(env);
}
diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceHiddenCount, 0);
assert.equal(diagnostics.visibleCount, 3);
assert.ok(diagnostics.labeledKeys.includes('traffic:VEH-0001'));
} finally {
env.cleanup();
}
});
test('a labelled contact that goes behind something loses its callout at once, and does not get it back by leaving the view', () => {
const env = installEnvironment();
// To begin with the drawn surface is below both vehicles.
let surface = 5_000_000;
const depth = installDepthScene(env, () => surface);
const layers = occlusionLayers();
const everyVehicle = layers[0].getDetectableObjects;
const answerAndSolve = (count) => {
for (let i = 0; i < count; i++) {
depth.gl.finishGpu();
settleFrame(env);
}
};
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, layers, () => {});
setMode('DENSE');
answerAndSolve(6);
assert.ok(getDetectionDiagnostics().labeledKeys.includes('traffic:VEH-0001'));
env.ctx.calls.length = 0;
nextFrame(env);
assert.ok(paintedText(env).includes('VEH-0001'));
// A roof is drawn over VEH-0001. Its callout goes on the frame the answer
// lands, which is not a solve: no carry-over, no fade.
surface = 3_000_000;
depth.redraw();
let gone = -1;
for (let i = 0; i < 30 && gone < 0; i++) {
depth.gl.finishGpu();
env.ctx.calls.length = 0;
nextFrame(env);
if (!paintedText(env).includes('VEH-0001')) gone = i;
}
assert.ok(gone >= 0, 'the callout went');
// The layer stops reporting it (it drove out of view). The arbiter still
// remembers where its callout was; it must not paint it there again.
layers[0].getDetectableObjects = () => everyVehicle().slice(1);
for (let i = 0; i < 12; i++) {
depth.gl.finishGpu();
env.ctx.calls.length = 0;
nextFrame(env);
assert.ok(!paintedText(env).includes('VEH-0001'), `frame ${i}`);
}
} finally {
env.cleanup();
}
});
test('without scene depth every contact keeps its bracket and callout', () => {
const env = installEnvironment();
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, occlusionLayers(), () => {});
setMode('DENSE');
settleFrame(env);
settleFrame(env);
const diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceDepthMode, 'off');
assert.equal(diagnostics.surfaceTestedCount, 2);
assert.equal(diagnostics.surfaceProbeTests, 0);
assert.equal(diagnostics.surfaceHiddenCount, 0);
assert.equal(diagnostics.visibleCount, 3);
assert.ok(diagnostics.labeledKeys.includes('traffic:VEH-0001'));
} finally {
env.cleanup();
}
});
test('scene depth that goes away puts hidden contacts back', () => {
const env = installEnvironment();
const depth = installDepthScene(env, () => 3_000_000);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, occlusionLayers(), () => {});
setMode('DENSE');
settleFrame(env);
depth.gl.finishGpu();
settleFrame(env);
assert.equal(getDetectionDiagnostics().surfaceHiddenCount, 1);
// The scene stops keeping pick depth (a 2D view, depth picking turned off).
depth.gl.finishGpu();
env.viewer.scene.useDepthPicking = false;
// The hidden time runs on painted frames, so paint a second's worth.
for (let i = 0; i < 70; i++) nextFrame(env);
settleFrame(env);
const diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceDepthMode, 'off');
assert.equal(diagnostics.surfaceHiddenCount, 0);
assert.equal(diagnostics.visibleCount, 3);
} finally {
env.cleanup();
}
});
test('turning detection off drops every test in flight; tearing it down frees the GPU objects', () => {
const env = installEnvironment();
const depth = installDepthScene(env, () => 3_000_000);
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, occlusionLayers(), () => {});
setMode('DENSE');
settleFrame(env);
assert.equal(depth.gl.liveQueries.size, 3);
// Off keeps the GPU objects (the shader is not compiled again on the next
// on) but the answers in flight are no longer wanted.
setMode('OFF');
assert.equal(depth.gl.counts.deleted, 0);
depth.gl.finishGpu();
setMode('DENSE');
settleFrame(env);
assert.equal(depth.gl.counts.queries, 6, 'both contacts are tested afresh');
assert.equal(depth.gl.liveQueries.size, 3, 'on the same queries, reused');
depth.gl.finishGpu();
nextFrame(env);
settleFrame(env);
assert.equal(getDetectionDiagnostics().surfaceHiddenCount, 1);
assert.equal(getDetectionDiagnostics().visibleCount, 2);
} finally {
env.cleanup();
}
// Tearing detection down releases everything.
assert.equal(depth.gl.liveQueries.size, 0);
assert.equal(depth.gl.counts.deleted, 5);
});
test('a WebGL 1 scene reads depth synchronously and reports it once', () => {
const env = installEnvironment();
const depth = installDepthScene(env, () => 3_000_000, { webgl2: false });
const originalInfo = console.info;
const reported = [];
console.info = (...args) => reported.push(args.join(' '));
try {
initWorldOverlay(env.viewer);
initDetection(env.viewer, occlusionLayers(), () => {});
setMode('DENSE');
for (let i = 0; i < 30; i++) nextFrame(env);
settleFrame(env);
const diagnostics = getDetectionDiagnostics();
assert.equal(diagnostics.surfaceDepthMode, 'sync');
assert.equal(diagnostics.surfaceHiddenCount, 1);
assert.equal(diagnostics.visibleCount, 2);
// Half a second of frames: a read about every eighth of one, not one per
// frame and not one per contact.
assert.ok(depth.gl.counts.readPixels >= 3 && depth.gl.counts.readPixels <= 6, `${depth.gl.counts.readPixels} reads`);
assert.equal(reported.length, 1);
assert.match(reported[0], /synchronously/);
} finally {
console.info = originalInfo;
env.cleanup();
}
});
+469
View File
@@ -0,0 +1,469 @@
/**
* Scene-geometry occlusion for detection contacts.
*
* The overlay's own horizon test only knows about the Earth's curve. A contact
* whose marker the scene depth-tests (a street vehicle's dot) can still sit
* behind a building, a 3D tile or a hill, and painting its bracket and callout
* there puts a label on the facade in front of it.
*
* The fix compares each such contact with what the renderer actually drew: if
* the drawn surface along the contact's ray is nearer than the contact by more
* than a small margin, something stands in front of it and its bracket and
* callout are not drawn. The renderer's occlusion test (`query.occlusionTest`;
* the GPU probe is `src/render/occlusion/depthProbe.js`) runs that comparison
* on the GPU, against the frame's own depth, and hands back a yes or no per
* contact a frame or two later without ever waiting on the GPU. This file holds the
* arithmetic both sides share and the per-contact memory of the answers.
*
* Only contacts that opt in with `depthTested: true` are tested: the ones whose
* marker the scene itself hides behind geometry. Everything else keeps its
* label exactly as before, which covers contacts high above the ground
* (aircraft, satellites): their markers are drawn on top of the scene by
* design, their 3D models can fill the very pixel being read, and a label
* that hid while its marker stayed on screen would be the worse mismatch.
*
* This file is plain arithmetic; it never touches the renderer.
*/
/** Never less than this: covers a dot drawn a little above or into its road. */
export const SURFACE_OCCLUSION_MIN_MARGIN_M = 3;
/** The most the margin grows with range: 2% of it. */
export const SURFACE_OCCLUSION_MARGIN_FRACTION = 0.02;
/**
* How far above a contact a drawn surface on its line of sight must stand to
* count as in front of it, when the camera looks down on the contact.
*/
export const SURFACE_OCCLUSION_RISE_M = 2;
/**
* How much nearer than the contact the drawn surface must be before it counts
* as standing in front of it.
*
* The margin absorbs a contact placed a little above or below the drawn
* ground: a vehicle's position and the scene's road surface are not the same
* height to the metre. Looking down at the contact, a point on its line of
* sight `s` metres in front of it stands `s * sinElevation` metres above it,
* so a surface there only hides the contact once `s` passes
* `SURFACE_OCCLUSION_RISE_M / sinElevation`. That keeps the margin to a few
* metres from above, where a fixed share of the range would let a wall,
* awning or tree 10 to 20 m in front of a street at 1 km pass as "the road".
* At grazing angles, or looking up, the margin is 2% of the range at most
* (never under 3 m); depth precision is far finer than that at every range
* the overlay labels.
*
* @param {number} contactDistance Camera-to-contact distance in metres.
* @param {number} [sinElevation] Sine of the camera's elevation seen from the
* contact (1 straight overhead, 0 level, negative below); unknown when
* omitted.
* @returns {number} Margin in metres.
*/
export function surfaceOcclusionMargin(contactDistance, sinElevation = 0) {
const distance = Number(contactDistance);
if (!(distance > 0)) return SURFACE_OCCLUSION_MIN_MARGIN_M;
let margin = distance * SURFACE_OCCLUSION_MARGIN_FRACTION;
const rise = Number(sinElevation);
if (rise > 0) margin = Math.min(margin, SURFACE_OCCLUSION_RISE_M / rise);
return Math.max(SURFACE_OCCLUSION_MIN_MARGIN_M, margin);
}
/**
* Whether a drawn surface hides a contact.
* @param {number} contactDistance Camera-to-contact distance in metres.
* @param {number|undefined} surfaceDistance Camera-to-drawn-surface distance
* along the contact's ray; undefined or non-finite when nothing was drawn.
* @param {number} [sinElevation] See `surfaceOcclusionMargin`.
* @returns {boolean}
*/
export function surfaceHidesContact(
contactDistance,
surfaceDistance,
sinElevation = 0,
) {
if (!Number.isFinite(contactDistance) || !Number.isFinite(surfaceDistance))
return false;
return (
surfaceDistance <
contactDistance - surfaceOcclusionMargin(contactDistance, sinElevation)
);
}
/**
* Unpack a depth the renderer stored across the four bytes of an RGBA8 texel
* (most significant byte first, each byte a base-255 digit).
* @param {ArrayLike<number>} bytes
* @param {number} offset Index of the texel's red byte.
* @returns {number} Window-space depth in [0, 1].
*/
export function unpackDepth(bytes, offset) {
return (
bytes[offset] / 255 +
bytes[offset + 1] / 65025 +
bytes[offset + 2] / 16581375 +
bytes[offset + 3] / 4228250625
);
}
/**
* Convert a window-space depth to the distance in front of the camera, measured
* along the view direction, for one depth range ("frustum") of the frame.
*
* Logarithmic depth stores `log2(z - near + 1) / log2(far - near + 1)`.
* Standard perspective depth stores `far * (z - near) / (z * (far - near))`.
*
* @param {number} depth Window-space depth in [0, 1].
* @param {number} near Near plane of the range, metres.
* @param {number} far Far plane of the range, metres.
* @param {boolean} logDepth Whether the frame was drawn with logarithmic depth.
* @returns {number} Metres along the view direction, or NaN where the range
* drew nothing (depth at or outside the ends of [0, 1]).
*/
export function depthToViewDistance(depth, near, far, logDepth) {
if (!(depth > 0) || !(depth < 1)) return Number.NaN;
if (!(near >= 0) || !(far > near)) return Number.NaN;
if (logDepth)
return near + Math.pow(2, depth * Math.log2(far - near + 1)) - 1;
// Standard depth needs a near plane in front of the eye; log depth does not
// (it can be written with none, as log2(1 + d) / log2(far + 1)).
if (!(near > 0)) return Number.NaN;
return (near * far) / (far - depth * (far - near));
}
/**
* Where a world position falls in a frame, and how near a drawn surface has to
* be there to hide it.
*
* A surface hides the contact when its distance along the contact's ray is
* under the contact's own distance less the margin. Along one ray, distance
* and view distance (depth in front of the camera) are in a fixed ratio, so
* the same rule reads: the surface's view distance is under
* `viewDistance * (1 - margin / contactDistance)`. That number is `threshold`,
* and comparing a decoded depth with it is all the GPU has to do.
*
* The margin depends on how steeply the camera looks down on the contact
* (see `surfaceOcclusionMargin`). "Up" at the contact is taken as the
* direction from the world origin to it, which is the Earth's centre in the
* Earth-fixed frame the scene is drawn in; it differs from the true vertical
* by a fraction of a degree at most.
*
* @param {ArrayLike<number>} view World-to-camera matrix, column-major, the
* camera looking down its own -Z axis.
* @param {number} tanHalfFovX
* @param {number} tanHalfFovY
* @param {{x: number, y: number, z: number}} position
* @param {{u: number, v: number, threshold: number}} out `u`, `v` in [0, 1)
* from the bottom-left corner of the frame.
* @returns {boolean} False when the position is behind the camera or outside
* the frame; `out` is then untouched.
*/
export function projectContact(view, tanHalfFovX, tanHalfFovY, position, out) {
const { x, y, z } = position;
const viewDistance = -(view[2] * x + view[6] * y + view[10] * z + view[14]);
if (!(viewDistance > 0)) return false;
const ex = view[0] * x + view[4] * y + view[8] * z + view[12];
const ey = view[1] * x + view[5] * y + view[9] * z + view[13];
const u = (ex / (viewDistance * tanHalfFovX)) * 0.5 + 0.5;
const v = (ey / (viewDistance * tanHalfFovY)) * 0.5 + 0.5;
if (!(u >= 0 && u < 1 && v >= 0 && v < 1)) return false;
const contactDistance = Math.sqrt(
ex * ex + ey * ey + viewDistance * viewDistance,
);
// Up at the contact, turned into camera axes, against the direction from
// the contact to the camera (-ex, -ey, viewDistance in camera axes).
const radius = Math.sqrt(x * x + y * y + z * z);
let sinElevation = 0;
if (radius > 0) {
const ux = (view[0] * x + view[4] * y + view[8] * z) / radius;
const uy = (view[1] * x + view[5] * y + view[9] * z) / radius;
const uz = (view[2] * x + view[6] * y + view[10] * z) / radius;
sinElevation = (-ux * ex - uy * ey + uz * viewDistance) / contactDistance;
}
out.u = u;
out.v = v;
out.threshold =
viewDistance *
(1 -
surfaceOcclusionMargin(contactDistance, sinElevation) / contactDistance);
return true;
}
/**
* One frame of depth read back to memory, with the camera it was drawn from.
* Only the synchronous fallback uses this (see `src/render/occlusion/depthProbe.js`); the
* normal path never copies depth off the GPU.
*
* `bytes` holds `frustums.length` stacked images of `width` x `height` RGBA8
* texels, nearest depth range first, rows bottom to top (the order the
* graphics API reads them back in).
*/
export class DepthSnapshot {
/**
* @param {{
* width: number, height: number, bytes: Uint8Array,
* frustums: Array<{near: number, far: number}>, logDepth: boolean,
* view: ArrayLike<number>, tanHalfFovX: number, tanHalfFovY: number,
* }} fields
*/
constructor(fields) {
this.width = fields.width;
this.height = fields.height;
this.bytes = fields.bytes;
this.frustums = fields.frustums;
this.logDepth = fields.logDepth === true;
this.view = fields.view;
this.tanHalfFovX = fields.tanHalfFovX;
this.tanHalfFovY = fields.tanHalfFovY;
this._projected = { u: 0, v: 0, threshold: 0 };
}
/**
* Distance along the view direction to the nearest surface drawn at a texel.
* @param {number} column
* @param {number} row Counted from the bottom of the frame.
* @returns {number} Metres, or NaN where nothing was drawn.
*/
surfaceViewDistance(column, row) {
const { width, height, bytes, frustums, logDepth } = this;
const texel = (row * width + column) * 4;
const layer = width * height * 4;
for (let i = 0; i < frustums.length; i++) {
const distance = depthToViewDistance(
unpackDepth(bytes, i * layer + texel),
frustums[i].near,
frustums[i].far,
logDepth,
);
if (distance === distance) return distance;
}
return Number.NaN;
}
/**
* Whether the frame drew something in front of a world position.
* @param {{x: number, y: number, z: number}} position
* @returns {boolean|null} Null when the position is outside the frame.
*/
hides(position) {
const projected = this._projected;
if (
!projectContact(
this.view,
this.tanHalfFovX,
this.tanHalfFovY,
position,
projected,
)
)
return null;
return (
this.surfaceViewDistance(
Math.floor(projected.u * this.width),
Math.floor(projected.v * this.height),
) < projected.threshold
);
}
}
/**
* A contact is tested again at most this long, and at least half this long,
* after its last test was started, so a view full of contacts spreads its
* tests over about ten frames instead of repeating all of them on every one.
* With more contacts in view than the probe's per-frame budget can serve at
* that pace, the interval stretches (see `SurfaceOcclusion.beginFrame`).
*/
export const SURFACE_RETEST_MS = 200;
/**
* A contact stays hidden at least this long after the last test that found it
* hidden, and never less than three retest intervals.
*
* Going behind something takes effect as soon as the answer arrives. Coming
* back takes several visible answers in a row, so a contact on a silhouette
* edge, which tests either way from one frame to the next while the camera
* orbits, stays off instead of blinking. It is also the clean failure: when
* answers stop arriving (no depth to test against) every contact is drawn
* again within this time, exactly as before this test existed.
*/
export const SURFACE_REAPPEAR_MS = 600;
/**
* A contact that has never had an answer is held back this long, at most,
* while a working probe gets it one.
*
* A contact new to the view would otherwise be drawn for the frame or two its
* first test takes, and then vanish if it turned out to be behind something:
* a camera orbiting a city would flash a bracket for every vehicle that
* swings into the frame behind a building. With no working probe nothing is
* held back, and past this time the contact is drawn whatever happens.
*/
export const SURFACE_FIRST_ANSWER_MS = 400;
/**
* The most one frame advances the occlusion clock.
*
* Every interval above is measured on a clock that only runs while the
* overlay is painting: each painted frame moves it on by the time since the
* last one, but never by more than this. Answers only arrive while frames are
* painted, so on a wall clock a pause (a hidden tab, a scene with nothing to
* redraw) would run out every "hidden" at once and the first frame afterwards
* would paint every label over the buildings again until fresh answers came.
* On this clock a pause of any length counts as one slow frame.
*/
export const SURFACE_MAX_FRAME_STEP_MS = 50;
/** A contact not drawn for this long is forgotten. */
export const SURFACE_FORGET_MS = 2000;
/**
* What is remembered about one contact.
* @typedef {{lastHiddenAt: number, hiddenUntil: number, appliedHiddenAt: number,
* queuedAt: number, pending: boolean, answered: boolean, firstSeenAt: number,
* seenAt: number}} SurfaceContact Times are on the occlusion clock.
*/
/**
* Per-contact occlusion answers, and the schedule that keeps them fresh.
*
* `probe` is whatever tests a contact against the drawn scene. It has
* `add(contact, position)`, which starts a test (setting `contact.pending`)
* and returns false when it cannot take one now, and it reports back by
* clearing `contact.pending`, setting `contact.answered` and, when the
* contact was hidden, setting `contact.lastHiddenAt`. `probe.maxPerFrame`, if
* set, is how many tests it takes in one frame; `probe.mode` reads `'async'`
* while answers come a frame or two after the test.
*/
export class SurfaceOcclusion {
/**
* @param {{add: (contact: SurfaceContact, position: object) => boolean}} probe
*/
constructor(probe) {
this.probe = probe;
/** @type {Map<string, Map<*, SurfaceContact>>} Layer id -> source id. */
this.contacts = new Map();
/**
* The occlusion clock, in milliseconds of painted time (see
* `SURFACE_MAX_FRAME_STEP_MS`). The probe must date its answers by it.
*/
this.now = 0;
this._wall = Number.NEGATIVE_INFINITY;
/** Depth-tested contacts drawn or hidden this frame. */
this.testedCount = 0;
this.hiddenCount = 0;
this.retestMs = SURFACE_RETEST_MS;
this.reappearMs = SURFACE_REAPPEAR_MS;
this.firstAnswerMs = SURFACE_FIRST_ANSWER_MS;
this._phase = 0;
}
/**
* Open a frame and move the occlusion clock on.
* @param {number} wallNow Monotonic milliseconds.
*/
beginFrame(wallNow) {
// Contacts arrive in the same order every frame and the probe takes only
// so many, so if more fell due per frame than it takes, the ones at the
// end of the order would never be tested. Pace the retests to what the
// last frame showed the probe can keep up with: all of the contacts, once
// per interval, with a third of the budget to spare.
const elapsed = wallNow - this._wall;
const frameMs =
elapsed > 0 ? Math.min(SURFACE_MAX_FRAME_STEP_MS, elapsed) : 0;
this._wall = wallNow;
const budget = Number(this.probe.maxPerFrame) || Number.POSITIVE_INFINITY;
this.retestMs = Math.max(
SURFACE_RETEST_MS,
(this.testedCount / budget) * frameMs * 2,
);
this.reappearMs = Math.max(SURFACE_REAPPEAR_MS, this.retestMs * 3);
// At a stretched pace a crowd of new contacts takes longer to get its
// first answers; the hold-back stretches with it.
this.firstAnswerMs = Math.max(SURFACE_FIRST_ANSWER_MS, this.retestMs * 2);
this.now += frameMs;
this.testedCount = 0;
this.hiddenCount = 0;
}
/**
* Whether a contact's bracket and callout should be left out of this frame.
* Starts a fresh test of the contact when one is due.
* @param {string} layerId
* @param {*} sourceId
* @param {{x: number, y: number, z: number}} position
* @returns {boolean}
*/
isHidden(layerId, sourceId, position) {
const now = this.now;
let layer = this.contacts.get(layerId);
if (!layer) {
layer = new Map();
this.contacts.set(layerId, layer);
}
let contact = layer.get(sourceId);
if (!contact || now - contact.seenAt > this.retestMs) {
// New, or back in view after longer than a retest interval. A returning
// contact's last answer is older than any contact that stayed in view
// runs on, and the view has probably turned since: it is held back
// like a new one until a fresh answer comes, or orbiting flashes it
// behind the building it went behind while out of view. It gets a new
// record, so a test still in flight from before answers the old one
// and cannot end the hold-back with what the previous view showed. A
// "hidden" it already had keeps running.
contact = {
lastHiddenAt: contact?.lastHiddenAt ?? Number.NEGATIVE_INFINITY,
hiddenUntil: contact?.hiddenUntil ?? Number.NEGATIVE_INFINITY,
appliedHiddenAt: contact?.appliedHiddenAt ?? Number.NEGATIVE_INFINITY,
queuedAt: Number.NEGATIVE_INFINITY,
pending: false,
answered: false,
firstSeenAt: now,
seenAt: now,
};
layer.set(sourceId, contact);
}
contact.seenAt = now;
this.testedCount++;
if (
!contact.pending &&
now - contact.queuedAt >= this.retestMs &&
this.probe.add(contact, position)
) {
// Contacts that came into view together would otherwise all fall due on
// the same frames for ever. Each test backdates itself by a different
// part of half the interval, which spreads them out within a second.
contact.queuedAt = now - this.retestMs * 0.5 * this._phase;
this._phase = (this._phase + 0.618034) % 1;
}
// A new "hidden" answer sets when the contact may come back, once, with
// the pace in force now. A later change of pace must not bring back a
// "hidden" that has already run out.
if (contact.lastHiddenAt !== contact.appliedHiddenAt) {
contact.appliedHiddenAt = contact.lastHiddenAt;
contact.hiddenUntil = contact.lastHiddenAt + this.reappearMs;
}
const hidden =
now < contact.hiddenUntil ||
// Not yet answered: held back while a working probe finds out.
(!contact.answered &&
this.probe.mode === 'async' &&
now - contact.firstSeenAt < this.firstAnswerMs);
if (hidden) this.hiddenCount++;
return hidden;
}
/** Forget contacts that are no longer drawn. */
prune() {
for (const [layerId, layer] of this.contacts) {
for (const [sourceId, contact] of layer) {
if (this.now - contact.seenAt > SURFACE_FORGET_MS)
layer.delete(sourceId);
}
if (layer.size === 0) this.contacts.delete(layerId);
}
}
/** Forget every contact (mode off, viewer swap). */
clear() {
this.contacts.clear();
this.testedCount = 0;
this.hiddenCount = 0;
}
}
+860
View File
@@ -0,0 +1,860 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
DepthSnapshot,
SURFACE_FIRST_ANSWER_MS,
SURFACE_FORGET_MS,
SURFACE_MAX_FRAME_STEP_MS,
SURFACE_OCCLUSION_MIN_MARGIN_M,
SURFACE_REAPPEAR_MS,
SURFACE_RETEST_MS,
SurfaceOcclusion,
depthToViewDistance,
projectContact,
surfaceHidesContact,
surfaceOcclusionMargin,
unpackDepth,
} from './detectionOcclusion.js';
import {
depthImage,
packDepth,
viewDistanceToDepth,
} from '../render/cesium/fixtures/fakeDepthScene.mjs';
test('the margin is 3 m near the camera and 2% of the range beyond 150 m', () => {
assert.equal(surfaceOcclusionMargin(10), SURFACE_OCCLUSION_MIN_MARGIN_M);
assert.equal(surfaceOcclusionMargin(150), 3);
assert.equal(surfaceOcclusionMargin(500), 10);
assert.equal(surfaceOcclusionMargin(5000), 100);
assert.equal(surfaceOcclusionMargin(0), 3);
assert.equal(surfaceOcclusionMargin(Number.NaN), 3);
});
test('looking down on a contact, the margin is what a 2 m rise on its line of sight takes', () => {
// 1 km away, seen from 30 degrees up: 2 m of rise is 4 m along the ray.
assert.ok(Math.abs(surfaceOcclusionMargin(1000, 0.5) - 4) < 1e-9);
// Straight down: the 3 m floor.
assert.equal(surfaceOcclusionMargin(1000, 1), SURFACE_OCCLUSION_MIN_MARGIN_M);
// Grazing, level or from below: never more than 2% of the range.
assert.equal(surfaceOcclusionMargin(1000, 0.01), 20);
assert.equal(surfaceOcclusionMargin(1000, 0), 20);
assert.equal(surfaceOcclusionMargin(1000, -0.3), 20);
assert.equal(surfaceOcclusionMargin(1000, Number.NaN), 20);
assert.equal(surfaceOcclusionMargin(100, 0.05), 3);
// A low wall 15 m in front of a street 1 km off, seen from 25 degrees up,
// stands about 6 m above the vehicle's line of sight: it hides it.
const sin25 = Math.sin((25 * Math.PI) / 180);
assert.equal(surfaceHidesContact(1000, 985, sin25), true);
assert.equal(surfaceHidesContact(1000, 985), false, 'unknown angle: 2%');
assert.equal(surfaceHidesContact(1000, 996, sin25), false, 'its own road');
});
test('a surface hides a contact only when nearer by more than the margin', () => {
// 500 m away: margin 10 m.
assert.equal(surfaceHidesContact(500, 489), true, 'a facade 11 m in front');
assert.equal(surfaceHidesContact(500, 491), false, 'its own road or dot');
assert.equal(surfaceHidesContact(500, 500), false);
assert.equal(surfaceHidesContact(500, 520), false, 'the ground behind it');
// Close range keeps the 3 m floor.
assert.equal(surfaceHidesContact(60, 56), true);
assert.equal(surfaceHidesContact(60, 58), false);
});
test('nothing drawn, or no distance, never hides a contact', () => {
assert.equal(surfaceHidesContact(500, undefined), false);
assert.equal(surfaceHidesContact(500, Number.NaN), false);
assert.equal(surfaceHidesContact(Number.NaN, 10), false);
});
test('packed depth unpacks most significant byte first', () => {
assert.equal(unpackDepth([0, 0, 0, 0], 0), 0);
assert.equal(unpackDepth([255, 0, 0, 0], 0), 1);
assert.equal(unpackDepth([9, 9, 51, 0, 0, 0], 2), 0.2);
for (const depth of [0.000123, 0.25, 0.5, 0.987654321]) {
const round = unpackDepth(packDepth(depth), 0);
assert.ok(Math.abs(round - depth) < 1e-9, `${depth} -> ${round}`);
}
});
test('logarithmic depth decodes to metres in front of the camera', () => {
const near = 0.1;
const far = 10_000_000;
// depth = log2(z - near + 1) / log2(far - near + 1)
for (const z of [0.5, 12, 480, 25_000, 3_000_000]) {
const depth = Math.log2(z - near + 1) / Math.log2(far - near + 1);
const decoded = depthToViewDistance(depth, near, far, true);
assert.ok(Math.abs(decoded - z) / z < 1e-9, `${z} -> ${decoded}`);
}
});
test('standard perspective depth decodes to metres in front of the camera', () => {
const near = 1;
const far = 5000;
// depth = far * (z - near) / (z * (far - near))
for (const z of [1.5, 40, 900, 4999]) {
const depth = (far * (z - near)) / (z * (far - near));
const decoded = depthToViewDistance(depth, near, far, false);
assert.ok(Math.abs(decoded - z) / z < 1e-9, `${z} -> ${decoded}`);
}
assert.ok(
Math.abs(depthToViewDistance(0.5, 1, 5000, false) - 10000 / 5001) < 1e-9,
'half depth sits just past twice the near plane',
);
});
test('the ends of the depth range, and a bad range, mean nothing was drawn', () => {
for (const log of [true, false]) {
assert.ok(Number.isNaN(depthToViewDistance(0, 1, 100, log)));
assert.ok(Number.isNaN(depthToViewDistance(1, 1, 100, log)));
assert.ok(Number.isNaN(depthToViewDistance(Number.NaN, 1, 100, log)));
assert.ok(Number.isNaN(depthToViewDistance(0.5, -1, 100, log)));
assert.ok(Number.isNaN(depthToViewDistance(0.5, 100, 100, log)));
}
// No near plane: standard depth has nothing to decode against.
assert.ok(Number.isNaN(depthToViewDistance(0.5, 0, 100, false)));
});
test('log depth with no near plane decodes as log2(1 + d) / log2(far + 1)', () => {
const depth = Math.log2(1 + 400) / Math.log2(100_000 + 1);
assert.ok(
Math.abs(depthToViewDistance(depth, 0, 100_000, true) - 400) < 1e-6,
);
});
const IDENTITY = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1];
/** A point `distance` metres ahead, `side` of the way to the frame edge. */
const ahead = (distance, side = 0, up = 0) => ({
x: side * distance,
y: up * distance,
z: -distance,
});
test('a contact projects to its place in the frame, from the bottom-left corner', () => {
const out = { u: -1, v: -1, threshold: -1 };
// 90 degree field of view: the frame edge is as far out as the point is ahead.
assert.equal(projectContact(IDENTITY, 1, 1, ahead(500), out), true);
assert.deepEqual([out.u, out.v], [0.5, 0.5]);
assert.equal(
projectContact(IDENTITY, 1, 1, ahead(500, -0.5, 0.5), out),
true,
);
assert.deepEqual([out.u, out.v], [0.25, 0.75]);
// A wider horizontal field of view pulls the same point towards the middle.
assert.equal(
projectContact(IDENTITY, 2, 1, ahead(500, -0.5, 0.5), out),
true,
);
assert.deepEqual([out.u, out.v], [0.375, 0.75]);
});
test('the threshold is the margin rule restated as a view distance', () => {
const out = { u: 0, v: 0, threshold: 0 };
// Straight ahead, distance and view distance are the same thing.
projectContact(IDENTITY, 1, 1, ahead(500), out);
assert.ok(Math.abs(out.threshold - 490) < 1e-9, '500 m less 2%');
projectContact(IDENTITY, 1, 1, ahead(60), out);
assert.ok(Math.abs(out.threshold - 57) < 1e-9, '60 m less the 3 m floor');
// Off axis the ray is longer than the view distance; the rule holds along
// the ray, so a surface at view distance d sits d * range / viewDistance out.
const corner = ahead(400, -0.9, 0.9);
const range = Math.hypot(corner.x, corner.y, corner.z);
projectContact(IDENTITY, 1, 1, corner, out);
for (const surfaceView of [out.threshold - 0.01, out.threshold + 0.01]) {
const alongRay = (surfaceView * range) / 400;
assert.equal(
surfaceHidesContact(range, alongRay),
surfaceView < out.threshold,
);
}
assert.ok(Math.abs(out.threshold - 400 * 0.98) < 1e-9);
});
test('the threshold uses how steeply the camera looks down on the contact', () => {
// A street on a sphere the size of the Earth, under a camera 1 km up and
// 1 km back along the surface, looking straight at it: 45 degrees down.
const R = 6_371_000;
const street = { x: 0, y: 0, z: R };
const camera = { x: 0, y: -1000, z: R + 1000 };
// Camera axes: x along world x, looking along (0, 1, -1) / sqrt 2.
const s = Math.SQRT1_2;
const forward = [0, s, -s];
const up = [0, s, s];
const right = [1, 0, 0];
const t = (axis) =>
-(axis[0] * camera.x + axis[1] * camera.y + axis[2] * camera.z);
// Rows: right, up, -forward (the camera looks down its -Z).
const back = forward.map((c) => -c);
const view = [
right[0],
up[0],
back[0],
0,
right[1],
up[1],
back[1],
0,
right[2],
up[2],
back[2],
0,
t(right),
t(up),
t(back),
1,
];
const out = { u: 0, v: 0, threshold: 0 };
assert.equal(projectContact(view, 1, 1, street, out), true);
assert.ok(Math.abs(out.u - 0.5) < 1e-9 && Math.abs(out.v - 0.5) < 1e-9);
const range = Math.SQRT2 * 1000;
// 2 m of rise at 45 degrees is 2.83 m along the ray: the 3 m floor, not
// 2% of 1414 m (28 m).
assert.ok(Math.abs(out.threshold - (range - 3)) < 1e-6, `${out.threshold}`);
});
test('off the middle of the frame, with the camera turned, the threshold matches the world-space rule', () => {
// Rotations about the three axes, then a camera placed and turned freely;
// the threshold must equal the margin rule worked out in world space.
const rot = (ax, ay, az) => {
const [cx, sx, cy, sy, cz, sz] = [
Math.cos(ax),
Math.sin(ax),
Math.cos(ay),
Math.sin(ay),
Math.cos(az),
Math.sin(az),
];
// Rows of Rz * Ry * Rx.
return [
[cz * cy, cz * sy * sx - sz * cx, cz * sy * cx + sz * sx],
[sz * cy, sz * sy * sx + cz * cx, sz * sy * cx - cz * sx],
[-sy, cy * sx, cy * cx],
];
};
const R = 6_371_000;
let checked = 0;
for (let k = 0; k < 200; k++) {
// A deterministic spread of poses.
const a = (n) => Math.sin(k * 12.9898 + n * 78.233) * 3;
const m = rot(a(1), a(2), a(3)); // world-to-camera rotation
const lat = a(4) / 3;
const lon = a(5);
const contact = {
x: R * Math.cos(lat) * Math.cos(lon),
y: R * Math.cos(lat) * Math.sin(lon),
z: R * Math.sin(lat),
};
// Camera 300 to 2300 m from the contact, in a direction above or below it.
const d = [a(6), a(7), a(8)];
const dl = Math.hypot(...d) || 1;
const dist = 1300 + 1000 * Math.sin(k);
const cam = {
x: contact.x + (d[0] / dl) * dist,
y: contact.y + (d[1] / dl) * dist,
z: contact.z + (d[2] / dl) * dist,
};
const t = m.map(
(row) => -(row[0] * cam.x + row[1] * cam.y + row[2] * cam.z),
);
const view = [
m[0][0],
m[1][0],
m[2][0],
0,
m[0][1],
m[1][1],
m[2][1],
0,
m[0][2],
m[1][2],
m[2][2],
0,
t[0],
t[1],
t[2],
1,
];
const out = { u: 0, v: 0, threshold: 0 };
if (!projectContact(view, 2, 2, contact, out)) continue;
checked++;
const toCam = [cam.x - contact.x, cam.y - contact.y, cam.z - contact.z];
const range = Math.hypot(...toCam);
const sinElevation =
(toCam[0] * contact.x + toCam[1] * contact.y + toCam[2] * contact.z) /
(range * R);
const viewDistance = -(
m[2][0] * contact.x +
m[2][1] * contact.y +
m[2][2] * contact.z +
t[2]
);
const expected =
viewDistance * (1 - surfaceOcclusionMargin(range, sinElevation) / range);
assert.ok(
Math.abs(out.threshold - expected) < 1e-6,
`pose ${k}: ${out.threshold} vs ${expected}`,
);
}
assert.ok(checked > 20, `${checked} poses in frame`);
});
test('behind the camera or outside the frame there is nothing to test', () => {
const out = { u: 7, v: 7, threshold: 7 };
assert.equal(
projectContact(IDENTITY, 1, 1, { x: 0, y: 0, z: 500 }, out),
false,
);
assert.equal(
projectContact(IDENTITY, 1, 1, { x: 0, y: 0, z: 0 }, out),
false,
);
assert.equal(projectContact(IDENTITY, 1, 1, ahead(500, -1.2), out), false);
assert.equal(projectContact(IDENTITY, 1, 1, ahead(500, 0, 1.01), out), false);
assert.equal(
projectContact(IDENTITY, 1, 1, ahead(500, 1), out),
false,
'u = 1',
);
assert.deepEqual(out, { u: 7, v: 7, threshold: 7 }, 'left untouched');
});
test('a contact is projected with the camera it is given', () => {
// Camera 1000 m up the +Z axis looking down -Z: view = translate(0, 0, -1000).
const view = [1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0, 0, 0, -1000, 1];
const out = { u: 0, v: 0, threshold: 0 };
assert.equal(
projectContact(view, 1, 1, { x: -250, y: 0, z: 500 }, out),
true,
);
assert.equal(out.u, 0.25);
assert.equal(projectContact(view, 1, 1, { x: 0, y: 0, z: 1500 }, out), false);
});
/**
* A snapshot from a camera at the origin looking down -Z with a 90 degree
* field of view. By default one depth range in which the left half of the
* frame is a wall `wall` metres away and the right half is ground `ground`
* metres away.
*/
function snapshotWithWall({
wall = 400,
ground = 500,
logDepth = true,
size = 8,
frustums,
images,
} = {}) {
const ranges = frustums || [{ near: 1, far: 100_000 }];
const layers = images || [
depthImage(size, size, (column) =>
viewDistanceToDepth(
column < size / 2 ? wall : ground,
ranges[0].near,
ranges[0].far,
logDepth,
),
),
];
const bytes = new Uint8Array(size * size * 4 * layers.length);
layers.forEach((image, i) => bytes.set(image.data, i * size * size * 4));
return new DepthSnapshot({
width: size,
height: size,
bytes,
frustums: ranges,
logDepth,
view: IDENTITY,
tanHalfFovX: 1,
tanHalfFovY: 1,
});
}
test('a contact behind a drawn wall is hidden; one on drawn ground, or in front of the wall, is not', () => {
for (const logDepth of [true, false]) {
const snapshot = snapshotWithWall({ logDepth });
assert.equal(snapshot.hides(ahead(500, -0.5)), true);
assert.equal(snapshot.hides(ahead(500, 0.5)), false);
assert.equal(snapshot.hides(ahead(300, -0.5)), false);
// 2% of 405 m is 8.1 m: 5 m behind the wall is still the wall's own face.
assert.equal(snapshot.hides(ahead(405, -0.5)), false);
assert.equal(snapshot.hides(ahead(412, -0.5)), true);
assert.equal(snapshot.hides(ahead(500, -1.5)), null, 'outside the frame');
}
});
test('rows are read bottom to top', () => {
const size = 8;
const image = depthImage(size, size, (_column, row) =>
viewDistanceToDepth(row < size / 2 ? 400 : 500, 1, 100_000, true),
);
const snapshot = snapshotWithWall({ images: [image] });
assert.equal(snapshot.hides(ahead(500, 0, -0.5)), true, 'below centre');
assert.equal(snapshot.hides(ahead(500, 0, 0.5)), false, 'above centre');
});
test('the nearest depth range that drew something answers', () => {
const size = 4;
const frustums = [
{ near: 1, far: 1000 },
{ near: 999, far: 1_000_000 },
];
// Near range: a wall 400 m away on the left, nothing on the right.
const nearImage = depthImage(size, size, (column) =>
column < 2 ? viewDistanceToDepth(400, 1, 1000, true) : 1,
);
// Far range: ground 20 km away everywhere.
const farImage = depthImage(size, size, () =>
viewDistanceToDepth(20_000, 999, 1_000_000, true),
);
const snapshot = snapshotWithWall({
size,
frustums,
images: [nearImage, farImage],
});
assert.ok(Math.abs(snapshot.surfaceViewDistance(0, 0) - 400) < 0.01);
assert.ok(Math.abs(snapshot.surfaceViewDistance(3, 0) - 20_000) < 1);
assert.equal(snapshot.hides(ahead(15_000, -0.5)), true);
assert.equal(snapshot.hides(ahead(15_000, 0.5)), false);
assert.equal(snapshot.hides(ahead(30_000, 0.5)), true);
});
test('where nothing was drawn a contact is visible', () => {
const size = 4;
const snapshot = snapshotWithWall({
size,
images: [depthImage(size, size, () => 1)],
});
assert.ok(Number.isNaN(snapshot.surfaceViewDistance(1, 1)));
assert.equal(snapshot.hides(ahead(500)), false);
});
/**
* A probe that answers when told to. `hidden` decides each test's answer at
* the time it is resolved.
*/
function manualProbe() {
const inFlight = [];
return {
accepting: true,
started: 0,
inFlight,
add(contact) {
if (!this.accepting) return false;
this.started++;
contact.pending = true;
inFlight.push(contact);
return true;
},
/** Deliver every answer in flight. */
answer(hidden, now) {
for (const contact of inFlight.splice(0)) {
contact.pending = false;
contact.answered = true;
if (hidden) contact.lastHiddenAt = now;
}
},
};
}
const anywhere = { x: 0, y: 0, z: -500 };
test('a contact is drawn until an answer says it is hidden, then hidden at once', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(1000);
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), false);
assert.equal(probe.started, 1, 'a new contact is tested straight away');
occlusion.beginFrame(1016);
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), false);
assert.equal(probe.started, 1, 'one test in flight per contact');
probe.answer(true, occlusion.now);
occlusion.beginFrame(1032);
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), true);
assert.equal(occlusion.testedCount, 1);
assert.equal(occlusion.hiddenCount, 1);
// The same source id on another layer is another contact.
assert.equal(occlusion.isHidden('transit', 'a', anywhere), false);
});
test('with a working probe a new contact is held back until its first answer, and no longer than the limit', () => {
const probe = manualProbe();
probe.mode = 'async';
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(0);
// New to the view: tested at once, and not drawn while the answer is out.
assert.equal(occlusion.isHidden('traffic', 'street', anywhere), true);
assert.equal(occlusion.isHidden('traffic', 'roofed', anywhere), true);
assert.equal(occlusion.isHidden('traffic', 'unanswered', anywhere), true);
assert.equal(probe.started, 3);
const [street, roofed] = probe.inFlight.splice(0, 2);
street.pending = false;
street.answered = true;
roofed.pending = false;
roofed.answered = true;
roofed.lastHiddenAt = occlusion.now;
occlusion.beginFrame(16);
assert.equal(
occlusion.isHidden('traffic', 'street', anywhere),
false,
'drawn from its first answer',
);
assert.equal(
occlusion.isHidden('traffic', 'roofed', anywhere),
true,
'never drawn at all',
);
// The third answer never comes. It is drawn once the limit has passed.
const firstSeen = occlusion.now - 16;
const drawn = [];
for (let wall = 32; wall < 1000; wall += 16) {
occlusion.beginFrame(wall);
drawn.push([
occlusion.now - firstSeen,
!occlusion.isHidden('traffic', 'unanswered', anywhere),
]);
}
for (const [age, shown] of drawn)
assert.equal(shown, age >= SURFACE_FIRST_ANSWER_MS, `at ${age} ms`);
// No working probe: a new contact is drawn at once, as before.
for (const mode of ['off', 'sync', undefined]) {
const idle = manualProbe();
idle.mode = mode;
const plain = new SurfaceOcclusion(idle);
plain.beginFrame(0);
assert.equal(plain.isHidden('traffic', 'a', anywhere), false, String(mode));
}
});
test('a contact is retested at most every retest interval and at least every half of it', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
const starts = [];
let before = 0;
for (let now = 0; now <= 2000; now += 4) {
probe.answer(false, now);
occlusion.beginFrame(now);
occlusion.isHidden('traffic', 'a', anywhere);
if (probe.started !== before) {
starts.push(now);
before = probe.started;
}
}
const gaps = starts.slice(1).map((at, i) => at - starts[i]);
assert.ok(gaps.length >= 9);
assert.ok(
gaps.every((gap) => gap <= SURFACE_RETEST_MS),
`${gaps}`,
);
assert.ok(
gaps.every((gap) => gap >= SURFACE_RETEST_MS / 2),
`${gaps}`,
);
assert.ok(new Set(gaps).size > 3, 'not all on the same beat');
});
test('contacts that appear together drift apart instead of all testing on the same frames', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
const perFrame = [];
for (let frame = 0; frame < 240; frame++) {
const now = frame * 16;
probe.answer(false, now);
occlusion.beginFrame(now);
const before = probe.started;
for (let id = 0; id < 600; id++)
occlusion.isHidden('traffic', id, anywhere);
perFrame.push(probe.started - before);
}
assert.equal(perFrame[0], 600, 'every new contact is tested at once');
const settled = perFrame.slice(120);
assert.ok(Math.max(...settled) < 200, `peak ${Math.max(...settled)}`);
assert.ok(Math.min(...settled) > 0);
});
test('with more contacts than the probe takes per frame, the retests slow down and none is starved', () => {
// A probe that takes 256 tests a frame, 2,400 contacts in view, 30 fps.
const inFlight = [];
let taken = 0;
const probe = {
maxPerFrame: 256,
add(contact) {
if (taken >= 256) return false;
taken++;
contact.pending = true;
inFlight.push(contact);
return true;
},
};
const occlusion = new SurfaceOcclusion(probe);
const tests = new Array(2400).fill(0);
const lastStart = new Array(2400).fill(0);
let longestGap = 0;
for (let frame = 0; frame < 300; frame++) {
const now = frame * 33;
for (const contact of inFlight.splice(0)) contact.pending = false;
taken = 0;
occlusion.beginFrame(now);
for (let id = 0; id < 2400; id++) {
const before = taken;
occlusion.isHidden('traffic', id, anywhere);
if (taken !== before) {
tests[id]++;
if (frame > 60) longestGap = Math.max(longestGap, now - lastStart[id]);
lastStart[id] = now;
}
}
}
assert.ok(
Math.min(...tests) >= 8,
`fewest tests for one contact: ${Math.min(...tests)}`,
);
assert.ok(occlusion.retestMs > SURFACE_RETEST_MS);
assert.ok(longestGap <= occlusion.retestMs + 33, `longest gap ${longestGap}`);
assert.ok(occlusion.reappearMs >= 3 * occlusion.retestMs);
// A view the budget covers easily keeps the normal pace.
const few = new SurfaceOcclusion(probe);
for (let frame = 0; frame < 10; frame++) {
taken = 0;
few.beginFrame(frame * 16);
for (let id = 0; id < 300; id++) few.isHidden('traffic', id, anywhere);
}
assert.equal(few.retestMs, SURFACE_RETEST_MS);
assert.equal(few.reappearMs, SURFACE_REAPPEAR_MS);
});
test('a hidden contact comes back only after the reappear time without a hidden answer', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(0);
occlusion.isHidden('traffic', 'a', anywhere);
const hiddenAt = occlusion.now;
probe.answer(true, hiddenAt);
// Visible answers from now on; the contact still waits out the time.
let reappeared = null;
for (let wall = 16; wall < 2000 && reappeared === null; wall += 16) {
probe.answer(false, occlusion.now);
occlusion.beginFrame(wall);
if (!occlusion.isHidden('traffic', 'a', anywhere))
reappeared = occlusion.now;
}
assert.ok(reappeared - hiddenAt >= SURFACE_REAPPEAR_MS);
assert.ok(reappeared - hiddenAt < SURFACE_REAPPEAR_MS + 17);
});
test('a contact on an edge, answering either way in turn, stays hidden', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
const drawn = [];
let answers = 0;
for (let wall = 0; wall < 4000; wall += 16) {
if (probe.inFlight.length > 0)
probe.answer(answers++ % 2 === 0, occlusion.now);
occlusion.beginFrame(wall);
drawn.push(!occlusion.isHidden('traffic', 'a', anywhere));
}
// Drawn only until the first answer arrives.
assert.equal(drawn.lastIndexOf(true), 0);
});
test('when the probe stops answering, hidden contacts are drawn again and stay drawn', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(0);
occlusion.isHidden('traffic', 'a', anywhere);
const hiddenAt = occlusion.now;
probe.answer(true, hiddenAt);
// No depth any more: the probe takes no tests and answers nothing.
probe.accepting = false;
const drawn = [];
for (let wall = 16; wall < 3000; wall += 16) {
occlusion.beginFrame(wall);
drawn.push([
occlusion.now - hiddenAt,
!occlusion.isHidden('traffic', 'a', anywhere),
]);
}
for (const [age, shown] of drawn)
assert.equal(shown, age >= SURFACE_REAPPEAR_MS, `at ${age} ms`);
// A probe that never accepted anything hides nothing.
const dead = new SurfaceOcclusion({ add: () => false });
dead.beginFrame(0);
assert.equal(dead.isHidden('traffic', 'a', anywhere), false);
});
test('a change of pace does not bring back a hidden that has run out', () => {
// 2,400 contacts with a 256-a-frame probe: the hide time is longer at 33 ms
// frames than at 16 ms ones.
const inFlight = [];
let taken = 0;
const probe = {
maxPerFrame: 256,
add(contact) {
if (taken >= 256) return false;
taken++;
contact.pending = true;
inFlight.push(contact);
return true;
},
};
const occlusion = new SurfaceOcclusion(probe);
let wall = 0;
const paint = (step) => {
wall += step;
for (const contact of inFlight.splice(0)) contact.pending = false;
taken = 0;
occlusion.beginFrame(wall);
let watched = false;
for (let id = 0; id < 2400; id++) {
const hidden = occlusion.isHidden('traffic', id, anywhere);
if (id === 0) watched = hidden;
}
return watched;
};
for (let i = 0; i < 30; i++) paint(16);
// One hidden answer for contact 0, then visible answers only.
occlusion.contacts.get('traffic').get(0).lastHiddenAt = occlusion.now;
const states = [];
for (let i = 0; i < 80; i++) states.push(paint(16));
assert.equal(states[0], true);
assert.equal(states.at(-1), false, 'ran out at the fast pace');
// The frames slow down, which lengthens the hide time for new answers.
const slow = [];
for (let i = 0; i < 40; i++) slow.push(paint(33));
assert.ok(occlusion.reappearMs > SURFACE_REAPPEAR_MS);
assert.ok(
slow.every((hidden) => hidden === false),
'and stays out',
);
});
test('a pause in painting does not run the hidden time out', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(0);
occlusion.isHidden('traffic', 'a', anywhere);
probe.answer(true, occlusion.now);
occlusion.beginFrame(16);
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), true);
// Nothing is painted for a minute (a hidden tab, an idle scene). On the
// first frame back the contact is still hidden: no answer could have come.
const before = occlusion.now;
occlusion.beginFrame(60_016);
assert.equal(occlusion.now - before, SURFACE_MAX_FRAME_STEP_MS);
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), true);
// A clock that jumps backwards moves nothing.
occlusion.beginFrame(100);
assert.equal(occlusion.now - before, SURFACE_MAX_FRAME_STEP_MS);
});
test('prune forgets contacts that are no longer drawn; clear forgets everything', () => {
const probe = manualProbe();
const occlusion = new SurfaceOcclusion(probe);
let wall = 0;
/** Paint frames for `ms` of painted time, drawing the given contacts. */
const paint = (ms, ids) => {
for (const end = occlusion.now + ms; occlusion.now < end;) {
wall += 50;
occlusion.beginFrame(wall);
for (const id of ids) occlusion.isHidden('traffic', id, anywhere);
}
};
paint(100, ['gone', 'here']);
paint(SURFACE_FORGET_MS + 50, ['here']);
occlusion.prune();
assert.deepEqual([...occlusion.contacts.get('traffic').keys()], ['here']);
paint(SURFACE_FORGET_MS + 50, []);
occlusion.prune();
assert.equal(occlusion.contacts.size, 0);
occlusion.isHidden('traffic', 'again', anywhere);
occlusion.clear();
assert.equal(occlusion.contacts.size, 0);
assert.equal(occlusion.testedCount, 0);
});
test('a contact back in view after a while waits for a fresh answer, like a new one', () => {
const probe = manualProbe();
probe.mode = 'async';
const occlusion = new SurfaceOcclusion(probe);
let wall = 0;
const step = () => occlusion.beginFrame((wall += 16));
step();
occlusion.isHidden('traffic', 'a', anywhere);
probe.answer(false, occlusion.now);
step();
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), false);
// Out of view for a moment shorter than a retest: drawn straight away.
for (let i = 0; i < 5; i++) step();
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), false);
// Out of view for longer (the camera swung away and back): the old
// "visible" may now be behind a building. Held back, and tested at once.
const started = probe.started;
for (let i = 0; i < 30; i++) step();
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), true);
assert.equal(probe.started, started + 1);
probe.answer(true, occlusion.now);
step();
assert.equal(occlusion.isHidden('traffic', 'a', anywhere), true);
// It leaves with a test in flight, and comes back. That test's answer was
// about the previous view: when it lands, it must not end the hold-back.
const other = new SurfaceOcclusion(probe);
probe.answer(false, 0);
other.beginFrame((wall += 16));
other.isHidden('traffic', 'b', anywhere);
assert.equal(probe.inFlight.length, 1, 'tested, unanswered');
for (let i = 0; i < 30; i++) other.beginFrame((wall += 16));
const before = probe.started;
assert.equal(other.isHidden('traffic', 'b', anywhere), true);
assert.equal(probe.started, before + 1, 'tested afresh at once');
const [stale] = probe.inFlight.splice(0, 1);
stale.pending = false;
stale.answered = true;
other.beginFrame((wall += 16));
assert.equal(
other.isHidden('traffic', 'b', anywhere),
true,
'the old answer did not end the hold-back',
);
probe.answer(false, other.now);
other.beginFrame((wall += 16));
assert.equal(other.isHidden('traffic', 'b', anywhere), false);
});
test('at a stretched retest pace, new contacts are held back longer for their first answer', () => {
const probe = manualProbe();
probe.mode = 'async';
probe.maxPerFrame = 100;
const occlusion = new SurfaceOcclusion(probe);
occlusion.beginFrame(0);
for (let id = 0; id < 2000; id++) occlusion.isHidden('traffic', id, anywhere);
occlusion.beginFrame(33);
// 2000 contacts at 100 a frame and 33 ms frames: a retest every 1.3 s.
assert.ok(occlusion.retestMs > 1000, `${occlusion.retestMs}`);
assert.equal(occlusion.firstAnswerMs, occlusion.retestMs * 2);
assert.ok(occlusion.firstAnswerMs > SURFACE_FIRST_ANSWER_MS);
// A contact the probe has not reached yet is still held back past the
// usual limit, and drawn once the stretched one has run out.
probe.accepting = false;
let wall = 33;
const ages = [];
const firstSeen = occlusion.now;
occlusion.isHidden('traffic', 'late', anywhere);
while (occlusion.now - firstSeen < occlusion.firstAnswerMs + 100) {
occlusion.beginFrame((wall += 33));
for (let id = 0; id < 2000; id++)
occlusion.isHidden('traffic', id, anywhere);
ages.push([
occlusion.now - firstSeen,
occlusion.isHidden('traffic', 'late', anywhere),
]);
}
const limit = occlusion.firstAnswerMs;
assert.ok(
ages.some(([age, hidden]) => age > SURFACE_FIRST_ANSWER_MS + 50 && hidden),
'held past 400 ms',
);
for (const [age, hidden] of ages)
if (age >= limit) assert.equal(hidden, false, `at ${age} ms`);
});
+7 -11
View File
@@ -4,20 +4,18 @@ import { createDirectionsSource } from '../layers/directions/source.js';
* @description Service bundle for the Directions layer.
*
* The layer itself lives in `src/layers/directions/`, which imports nothing
* but Cesium and the pure step formatter. This module is the one place that
* names the application's shared services — the render governor, sprite order,
* the pick registry, the world overlay, the annotation material, the camera
* verbs, the shared ground floor and the pointer arbiter — and it re-exports
* the layer's pure helpers for the tests and the share-link code.
* but the renderer's draw port, geodesy and the pure step formatter. This
* module is the one place that names the application's shared services —
* the render governor, sprite order, the pick registry, the world overlay,
* the camera verbs, the shared ground floor and the pointer arbiter — and it
* re-exports the layer's pure helpers for the tests and the share-link code.
*/
import * as credits from './dataCredits.js';
import * as render from '../renderGovernor.js';
import * as sprites from './spriteOrder.js';
import * as picking from './pickRegistry.js';
import * as scenePick from './scenePick.js';
import * as overlays from '../overlays/worldOverlay.js';
import * as annotations from '../annotations/worldAnnotationRenderer.js';
import * as camera from '../cameraVerbs.js';
import * as ground from './groundFloor.js';
import * as input from './inputOwnership.js';
@@ -29,9 +27,7 @@ const directionsServices = Object.freeze({
render,
sprites,
picking,
scenePick,
overlays,
annotations,
camera,
ground,
input,
@@ -49,11 +45,12 @@ export {
DIRECTIONS_MODES,
DIRECTIONS_POINTER_OWNER,
DIRECTIONS_ROUTE_COLOR,
POINTER_TOOL_EXITS,
STEP_ANCHOR_DEADLINE_MS,
STEP_ANCHOR_FAST_ATTEMPTS,
STEP_ANCHOR_RETRY_MS,
STEP_ANCHOR_SLOW_RETRY_MS,
DIRECTIONS_MARKER_OVERLAY_SOURCE_ID,
createDirectionsMarkerOverlayEntry,
createDirectionsStepOverlayEntry,
directionsRequestUrl,
directionsRowControls,
@@ -62,7 +59,6 @@ export {
directionsStepList,
normalizeDirectionsParams,
normalizeRoutePayload,
pointerBlockedMessage,
stepAnchorDelayMs,
stepIndexAtDistance,
stepMarkerHeightM,
+108 -101
View File
@@ -1,11 +1,14 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import {
DEFAULT_DIRECTIONS_MODE,
DIRECTIONS_MODES,
DIRECTIONS_POINTER_OWNER,
DIRECTIONS_ROUTE_COLOR,
DIRECTIONS_MARKER_OVERLAY_SOURCE_ID,
createDirectionsMarkerOverlayEntry,
createDirectionsStepOverlayEntry,
directionsRequestUrl,
directionsRowControls,
@@ -18,8 +21,6 @@ import {
stepIndexAtDistance,
stepMarkerHeightM,
stepMarkerIndices,
pointerBlockedMessage,
POINTER_TOOL_EXITS,
STEP_ANCHOR_DEADLINE_MS,
STEP_ANCHOR_RETRY_MS,
STEP_ANCHOR_SLOW_RETRY_MS,
@@ -437,12 +438,6 @@ test('the FLY chip reports a flight in progress', () => {
assert.equal(flying.active, true);
});
test('a blocked pointer is reported instead of silently doing nothing', () => {
const blocked = directionsStats({ ...idle, pointerBlocked: true });
assert.match(blocked.error, /Another map tool is using clicks/);
assert.equal(blocked.count, 0);
});
test('a step selection can be requested and cleared through params', () => {
assert.deepEqual(normalizeDirectionsParams({ step: 3 }), { step: 3 });
assert.deepEqual(normalizeDirectionsParams({ step: 0 }), { step: 0 });
@@ -514,37 +509,40 @@ test('placing an endpoint takes the pointer, and every exit path gives it back',
assert.equal(isPointerFree(), true, 'destroy releases');
});
test('arming is refused, and said so, while another tool holds the pointer', (t) => {
test('arming takes the pointer from another tool, which is told', (t) => {
ownershipFixture(t);
const releaseDraw = claimAs('draw');
assert.equal(
directionsLayer.setParams({ arm: 'a' }),
true,
'the write is accepted',
);
assert.equal(
pointerOwner(),
'draw',
"the other tool's claim is never stolen",
);
let lost = 0;
claimPointer('draw', { onLost: () => (lost += 1) });
assert.equal(directionsLayer.setParams({ arm: 'a' }), true);
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'the newest wins');
assert.equal(lost, 1, 'the other tool is told once');
const chips = directionsLayer.getRowControls().chips;
assert.equal(
chips.find((chip) => chip.id === 'set-a').active,
false,
'nothing is armed',
);
assert.match(
directionsLayer.getStats().error,
/Another map tool is using clicks/,
'the row says why the click did nothing',
);
assert.equal(chips.find((chip) => chip.id === 'set-a').active, true);
assert.equal(directionsLayer.getStats().error, null);
});
// Once the other tool lets go, arming works and the complaint clears.
test('a newer tool taking the pointer disarms, as Escape would', (t) => {
ownershipFixture(t);
let told = 0;
directionsLayer.setRowControlsListener(() => (told += 1));
t.after(() => directionsLayer.setRowControlsListener(null));
directionsLayer.setParams({ arm: 'b' });
told = 0;
const releaseDraw = claimAs('draw');
const chips = directionsLayer.getRowControls().chips;
assert.equal(chips.find((chip) => chip.id === 'set-b').active, false);
assert.ok(told > 0, 'the row hears it');
assert.equal(
directionsLayer.getStats().error,
null,
'nothing to complain of',
);
// Its own later release frees nothing of the newer tool's.
directionsLayer.setParams({ arm: null });
assert.equal(pointerOwner(), 'draw');
assert.equal(releaseDraw(), true);
directionsLayer.setParams({ arm: 'a' });
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
assert.equal(directionsLayer.getStats().error, null);
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER, 'it arms again');
});
test('a release names this layer, so it cannot free a successor tool claim', (t) => {
@@ -564,11 +562,10 @@ test('a release names this layer, so it cannot free a successor tool claim', (t)
test('the pointer claim outlives the click that consumed it', async (t) => {
ownershipFixture(t);
// Every layer binds its own handler to the same canvas and they all run
// inside ONE browser event. Releasing the claim the moment the endpoint is
// placed hands the rest of that same click to every ambient handler
// registered after this one — which is how placing A on top of a bikeshare
// station also deselected the station.
// The renderer's click comes from the pointer's up, and the browser's own
// `click` on the canvas follows inside ONE input event; DOM listeners there
// ask `isPointerFree()` then. Releasing the claim the moment the endpoint is
// placed hands the rest of that same click to them.
directionsLayer.setParams({ arm: 'a' });
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
@@ -724,68 +721,6 @@ test('a stale lease cannot free the claim a later arming holds', async (t) => {
);
});
test('a refused arming names the tool holding the pointer and how to leave it', () => {
// Owner field test: he pressed SET A while Draw was open, nothing happened,
// and he concluded Directions was broken. Silence was the bug.
assert.equal(
pointerBlockedMessage('draw', 'a'),
'Draw is active — press Escape twice to leave Draw, then set A',
);
assert.equal(
pointerBlockedMessage('draw', 'b'),
'Draw is active — press Escape twice to leave Draw, then set B',
);
// A tool nobody has written an exit for still gets a usable sentence.
assert.equal(
pointerBlockedMessage('measure', 'a'),
'measure is active — turn measure off, then set A',
);
// A registered owner without an exit is named by its tool, not its id.
assert.equal(
pointerBlockedMessage('recent-imagery-box', 'a'),
'Recent imagery is active — turn Recent imagery off, then set A',
);
// Nothing to say when nothing is in the way, or when we are the holder.
assert.equal(pointerBlockedMessage(null, 'a'), null);
assert.equal(pointerBlockedMessage('', 'a'), null);
assert.equal(pointerBlockedMessage(' ', 'a'), null);
assert.equal(pointerBlockedMessage(DIRECTIONS_POINTER_OWNER, 'a'), null);
// Every exit the table knows names its tool and says how to leave it.
for (const [id, exit] of Object.entries(POINTER_TOOL_EXITS)) {
assert.match(
pointerBlockedMessage(id, 'a'),
new RegExp(`^${exit.name} is active — `),
);
assert.match(pointerBlockedMessage(id, 'a'), /, then set A$/);
}
});
test('the refusal reaches the app toast, and a successful arming says nothing', (t) => {
ownershipFixture(t);
const toasts = [];
directionsLayer.attachShellServices({
showToast: (text) => toasts.push(text),
});
t.after(() => directionsLayer.attachShellServices(null));
const releaseDraw = claimAs('draw');
directionsLayer.setParams({ arm: 'a' });
assert.deepEqual(toasts, [
'Draw is active — press Escape twice to leave Draw, then set A',
]);
// The row status the operator can also read is still set.
assert.match(
directionsLayer.getStats().error,
/Another map tool is using clicks/,
);
// Once Draw lets go, arming works and says nothing at all.
releaseDraw();
directionsLayer.setParams({ arm: 'a' });
assert.equal(toasts.length, 1, 'a successful arming is silent');
assert.equal(pointerOwner(), DIRECTIONS_POINTER_OWNER);
});
test('maneuvers are phrased on the page, in English word for word as the proxy does', () => {
const types = [
'depart',
@@ -950,3 +885,75 @@ test('the reroute tooltip keeps German mode nouns capitalized', (t) => {
'Fahrrad – Route im Modus „Fahrrad“ neu berechnen',
);
});
test('the A and B letters are protected overlay labels in the marker colour', () => {
const position = Cesium.Cartesian3.fromDegrees(-122.39, 37.79);
const entry = createDirectionsMarkerOverlayEntry('B', position, '#ff6b6b');
assert.equal(entry.id, 'directions-marker-b');
assert.equal(entry.title, 'B');
assert.equal(entry.variant, 'label');
assert.equal(entry.accent, '#ff6b6b');
assert.equal(entry.protected, true);
assert.equal(entry.position, position);
assert.equal(entry.placement, 'above');
});
test('a placed endpoint draws its letter through the overlay, not as entity text', async (t) => {
const published = [];
const cleared = [];
const visibility = [];
const markerVisibility = () =>
visibility
.filter(([source]) => source === DIRECTIONS_MARKER_OVERLAY_SOURCE_ID)
.at(-1)?.[1];
directionsLayer = createApplicationDirectionsLayer();
directionsLayer._setOverlayHostForTest({
setEntries: (source, entries) => published.push([source, entries]),
setVisible: (source, visible) => visibility.push([source, visible]),
clearSource: (source) => cleared.push(source),
});
resetPointerOwnership();
const viewer = {
isDestroyed: () => false,
scene: { requestRender() {} },
};
const { draw, unbind } = bindFakeDraw(viewer);
t.after(() => {
unbind();
directionsLayer.destroy(viewer);
directionsLayer._setOverlayHostForTest(null);
resetPointerOwnership();
});
directionsLayer.init(viewer);
assert.equal(markerVisibility(), false, 'hidden until enabled');
directionsLayer.placeEndpoint('a', { lat: 37.7955, lon: -122.3937 });
const markers = [...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(':markers'),
);
assert.deepEqual([...markers.items.keys()], ['directions:marker:A']);
const marker = markers.items.get('directions:marker:A');
assert.equal(marker.label, undefined, 'no renderer label on the marker');
assert.equal(marker.height, 'clampGround', 'a dot on the ground');
const [source, entries] = published.at(-1);
assert.equal(source, DIRECTIONS_MARKER_OVERLAY_SOURCE_ID);
assert.deepEqual(
entries.map((entry) => entry.title),
['A'],
);
// Hidden until the floor cell settles, then anchored (the ellipsoid here,
// where the test resolver finds no height).
assert.equal(entries[0].position(), null);
const started = Date.now();
while (!entries[0].position() && Date.now() - started < 5000)
await new Promise((resolve) => setTimeout(resolve, 10));
const anchor = Cesium.Cartographic.fromCartesian(entries[0].position());
assert.ok(Math.abs(Cesium.Math.toDegrees(anchor.latitude) - 37.7955) < 1e-9);
directionsLayer.setParams({ clear: true });
assert.equal(markers.items.size, 0, 'CLEAR takes the markers');
assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID));
cleared.length = 0;
directionsLayer.destroy(viewer);
assert.ok(cleared.includes(DIRECTIONS_MARKER_OVERLAY_SOURCE_ID));
});
+178
View File
@@ -0,0 +1,178 @@
/**
* @module data/displayDelay
* @description How far behind real time a live aircraft feed is drawn.
*
* Contacts are drawn at `now − delay` so that, at the time drawn, every
* contact has a report on both sides and is placed between two real reports
* instead of dead reckoned past its newest one. The delay has to cover how
* late the feed really is: a feed whose reports arrive 90 s old every 30 s
* needs about two minutes, a fresh one about half a minute.
*
* Each time a contact's report moves on, the feed's lag is how long the
* display had to wait for it: its receipt time less the contact's previous
* report time (lateness, the gap between reports and the wait for the next
* poll together). The delay aimed at is the 90th percentile of the newest 256
* lags plus 5 s, within the layer's floor and a five-minute cap. Before a
* feed has given 16 lags, its first reports stand in: their age plus one poll
* interval. A delivery that comes more than three poll intervals after the
* one before it (a hidden tab's polls paused, or the feed failed) gives no
* lags: the wait was not the feed's lateness.
*
* The delay drawn with moves toward that aim at a bounded rate, rising by at
* most 0.2 s and falling by at most 0.05 s per second, so every contact
* slows or speeds up a little rather than the whole fleet jumping; an aim
* within 2 s of where it is leaves it there. Until a layer has drawn a
* contact, it takes its aim at once.
*/
/** @constant {number} Percentile of the recent lags the delay covers. */
export const DISPLAY_DELAY_RANK = 0.9;
/** @constant {number} How many recent lags the percentile is taken over. */
export const DISPLAY_DELAY_LAGS = 256;
/** @constant {number} Lags before they, rather than first reports, set the aim. */
export const DISPLAY_DELAY_MIN_LAGS = 16;
/** @constant {number} Added to the percentile for jitter (ms). */
export const DISPLAY_DELAY_MARGIN_MS = 5_000;
/** @constant {number} The longest delay (ms). */
export const DISPLAY_DELAY_CAP_MS = 300_000;
/** @constant {number} Delay gained per unit of real time, at most. */
export const DISPLAY_DELAY_RISE = 0.2;
/** @constant {number} Delay shed per unit of real time, at most. */
export const DISPLAY_DELAY_FALL = 0.05;
/** @constant {number} An aim this close (ms) to the delay leaves it be. */
export const DISPLAY_DELAY_DEADBAND_MS = 2_000;
/** @constant {number} Poll intervals between deliveries past which a delivery gives no lags. */
export const DISPLAY_DELAY_GAP_POLLS = 3;
function createWindow(capacity) {
return { values: new Float64Array(capacity), count: 0, cursor: 0 };
}
function add(window, value) {
if (!Number.isFinite(value) || value < 0) return;
window.values[window.cursor] = value;
window.cursor = (window.cursor + 1) % window.values.length;
window.count = Math.min(window.count + 1, window.values.length);
}
function percentile(window, rank) {
const sorted = window.values.slice(0, window.count).sort();
return sorted[Math.max(0, Math.ceil(sorted.length * rank) - 1)];
}
/**
* One live feed's display delay.
* @param {object} options
* @param {number} options.floorMs The shortest delay (ms), and where it starts.
* @param {number} options.pollMs How often the feed is asked (ms).
* @param {number} [options.capMs] The longest delay (ms).
*/
export function createDisplayDelay({
floorMs,
pollMs,
capMs = DISPLAY_DELAY_CAP_MS,
}) {
const lags = createWindow(DISPLAY_DELAY_LAGS);
const firstAges = createWindow(DISPLAY_DELAY_LAGS);
let aimMs = floorMs;
let fromMs = floorMs;
let fromAtMs = NaN;
let currentMs = floorMs;
// The delivery being noted, the one before it, and whether a pause
// separated them.
let deliveryMs = NaN;
let afterGap = false;
const clamp = (ms) => Math.max(floorMs, Math.min(capMs, ms));
/** The delay at `nowMs` on its way from `fromMs` toward the aim. */
function delayAt(nowMs) {
if (!Number.isFinite(fromAtMs)) return fromMs;
const elapsed = Math.max(0, nowMs - fromAtMs);
const change = Math.max(
-DISPLAY_DELAY_FALL * elapsed,
Math.min(DISPLAY_DELAY_RISE * elapsed, aimMs - fromMs),
);
return fromMs + change;
}
return {
/** The delay contacts are drawn with now (whole ms), as last stepped. */
get currentMs() {
return currentMs;
},
/** The delay it is moving toward (ms). */
get aimMs() {
return aimMs;
},
/** Lags seen so far, up to the window. */
get lagCount() {
return lags.count;
},
/**
* A contact's report received at `receiptMs`: its time, and the
* contact's previous report time (none for a contact seen first).
*/
noteReport(receiptMs, reportMs, previousReportMs) {
if (receiptMs !== deliveryMs) {
afterGap = receiptMs - deliveryMs > DISPLAY_DELAY_GAP_POLLS * pollMs;
deliveryMs = receiptMs;
}
if (Number.isFinite(previousReportMs)) {
if (reportMs > previousReportMs && !afterGap)
add(lags, receiptMs - previousReportMs);
} else if (Number.isFinite(reportMs))
add(firstAges, receiptMs - reportMs);
},
/**
* Aim again after a delivery. `jump`: nothing is drawn yet, so the delay
* takes the aim at once.
* @param {number} nowMs
* @param {{jump?: boolean}} [options]
* @returns {number} The delay now (whole ms).
*/
settle(nowMs, { jump = false } = {}) {
let next = aimMs;
if (lags.count >= DISPLAY_DELAY_MIN_LAGS)
next = clamp(
percentile(lags, DISPLAY_DELAY_RANK) + DISPLAY_DELAY_MARGIN_MS,
);
else if (firstAges.count)
next = clamp(
percentile(firstAges, DISPLAY_DELAY_RANK) +
pollMs +
DISPLAY_DELAY_MARGIN_MS,
);
const now = delayAt(nowMs);
fromMs = jump ? next : now;
fromAtMs = nowMs;
// An aim this close leaves the delay where it is.
aimMs =
Math.abs(next - now) < DISPLAY_DELAY_DEADBAND_MS && !jump ? now : next;
currentMs = Math.round(fromMs);
return currentMs;
},
/**
* Move the delay on to `nowMs`: what the contacts are drawn with until
* the next step.
* @returns {number} Whole ms.
*/
step(nowMs) {
currentMs = Math.round(delayAt(nowMs));
return currentMs;
},
/** Forget the feed: back to the floor, nothing learned. */
reset() {
lags.count = lags.cursor = 0;
firstAges.count = firstAges.cursor = 0;
aimMs = fromMs = currentMs = floorMs;
fromAtMs = NaN;
deliveryMs = NaN;
afterGap = false;
},
};
}
+185
View File
@@ -0,0 +1,185 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createDisplayDelay,
DISPLAY_DELAY_CAP_MS,
DISPLAY_DELAY_DEADBAND_MS,
DISPLAY_DELAY_FALL,
DISPLAY_DELAY_LAGS,
DISPLAY_DELAY_MARGIN_MS,
DISPLAY_DELAY_MIN_LAGS,
DISPLAY_DELAY_RISE,
} from './displayDelay.js';
// A live feed is drawn far enough behind real time that every contact has a
// report on both sides of the time drawn.
const SEC = 1000;
const FLOOR = 30 * SEC;
const POLL = 30 * SEC;
/**
* A feed polled every 30 s whose reports arrive `ageMs` old, one new report
* per contact per poll: each lag is the age plus the poll interval.
*/
function feed(delay, { contacts = 20, polls = 4, ageMs, startMs = 0 }) {
let now = startMs;
for (let p = 0; p < polls; p++) {
now += POLL;
for (let c = 0; c < contacts; c++) {
const reportMs = now - ageMs - c * 10;
delay.noteReport(now, reportMs, reportMs - POLL);
}
}
return now;
}
test('the aim is the 90th percentile of recent lags plus the margin', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.ok(delay.lagCount >= DISPLAY_DELAY_MIN_LAGS);
delay.settle(now, { jump: true });
// Lags 120 s (plus the spread of 0–190 ms): 125 s and a little.
assert.ok(
Math.abs(delay.currentMs - (120 * SEC + DISPLAY_DELAY_MARGIN_MS)) < 300,
`${delay.currentMs}`,
);
});
test('a fresh feed stays at the floor', () => {
// Polled every 10 s, reports 2 s old: lags of 12 s, aim 17 s, under the floor.
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: 10 * SEC });
for (let i = 1; i <= 40; i++)
delay.noteReport(
i * 10 * SEC,
i * 10 * SEC - 2 * SEC,
(i - 1) * 10 * SEC - 2 * SEC,
);
assert.equal(delay.settle(400 * SEC, { jump: true }), FLOOR);
});
test('the delay never passes the cap', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 20 * 60 * SEC });
assert.equal(delay.settle(now, { jump: true }), DISPLAY_DELAY_CAP_MS);
});
test('before enough lags, first reports stand in: their age plus a poll', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
for (let c = 0; c < 10; c++)
delay.noteReport(1_000 * SEC, 1_000 * SEC - 90 * SEC);
assert.equal(delay.lagCount, 0);
assert.equal(
delay.settle(1_000 * SEC, { jump: true }),
90 * SEC + POLL + DISPLAY_DELAY_MARGIN_MS,
);
});
test('a report that did not move on gives no lag', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
delay.noteReport(100 * SEC, 50 * SEC, 50 * SEC);
delay.noteReport(100 * SEC, 40 * SEC, 50 * SEC);
assert.equal(delay.lagCount, 0);
});
test('only the newest lags count', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, {
ageMs: 200 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
});
now = feed(delay, {
ageMs: 10 * SEC,
contacts: DISPLAY_DELAY_LAGS,
polls: 1,
startMs: now,
});
assert.ok(delay.settle(now, { jump: true }) < 50 * SEC);
});
test('the delay rises toward its aim at most 0.2 s per second, then holds there', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
assert.equal(delay.settle(now), FLOOR, 'not jumped once drawing');
const aim = delay.aimMs;
let prev = delay.currentMs;
for (let s = 1; s <= 600; s++) {
const d = delay.step(now + s * SEC);
assert.ok(d - prev <= DISPLAY_DELAY_RISE * SEC + 1, `rose ${d - prev} ms`);
assert.ok(d >= prev);
prev = d;
}
assert.equal(prev, aim);
// Rising by 0.2 s a second, the time drawn still moves forward at 0.8×.
assert.ok(DISPLAY_DELAY_RISE < 1);
});
test('the delay falls at most 0.05 s per second', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const high = delay.currentMs;
now = feed(delay, {
ageMs: 0,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.ok(Math.abs(delay.aimMs - 35 * SEC) < 300, `${delay.aimMs}`);
const later = delay.step(now + 100 * SEC);
assert.equal(high - later, DISPLAY_DELAY_FALL * 100 * SEC);
});
test('an aim within the deadband leaves the delay where it is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
const was = delay.currentMs;
now = feed(delay, {
ageMs: 90 * SEC + DISPLAY_DELAY_DEADBAND_MS / 2,
polls: 13,
startMs: now,
});
delay.settle(now);
assert.equal(delay.aimMs, was);
assert.equal(delay.step(now + 60 * SEC), was);
});
test('a delivery mid-slew carries on from where the delay is', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now);
const mid = delay.step(now + 100 * SEC);
now = feed(delay, {
ageMs: 90 * SEC,
polls: 1,
startMs: now + 100 * SEC - POLL,
});
assert.equal(delay.settle(now), mid);
});
test('reset forgets the feed', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
const now = feed(delay, { ageMs: 90 * SEC });
delay.settle(now, { jump: true });
delay.reset();
assert.equal(delay.currentMs, FLOOR);
assert.equal(delay.lagCount, 0);
assert.equal(delay.settle(now, { jump: true }), FLOOR);
});
test('a delivery after a pause in polling gives no lags, and the next one does', () => {
const delay = createDisplayDelay({ floorMs: FLOOR, pollMs: POLL });
let now = feed(delay, { ageMs: 10 * SEC, contacts: 20, polls: 2 });
const learned = delay.lagCount;
// A hidden tab: ten minutes with no polls, then a delivery whose reports
// moved on from ones ten minutes old.
now += 10 * 60 * SEC;
for (let c = 0; c < 20; c++)
delay.noteReport(now, now - 10 * SEC, now - 10 * 60 * SEC);
assert.equal(delay.lagCount, learned, 'the pause is not the feed’s lateness');
assert.ok(delay.settle(now, { jump: true }) < 60 * SEC);
feed(delay, { ageMs: 10 * SEC, contacts: 20, polls: 1, startMs: now });
assert.equal(delay.lagCount, learned + 20, 'polling again, lags count again');
});
+11
View File
@@ -0,0 +1,11 @@
/** One-line text capped at `maxLength` without splitting a surrogate pair. Still untrusted. */
export function normalizeDisplayText(value, maxLength = 180) {
if (value == null || typeof value === 'object') return '';
return String(value)
.replace(/[\u0000-\u001f\u007f-\u009f]/g, ' ')
.replace(/\s+/g, ' ')
.trim()
.slice(0, maxLength)
.replace(/[\uD800-\uDBFF]$/, '')
.trim();
}
+59 -67
View File
@@ -10,6 +10,8 @@ import {
EARTHQUAKE_OVERLAY_COLLISION_CAPACITY,
createEarthquakeOverlayEntry,
createEarthquakesLayer,
depthAccent,
depthColor,
mapAnalystRecord,
selectEarthquakeOverlayCohort,
} from './earthquakes.js';
@@ -19,6 +21,11 @@ import {
installRenderGovernor,
_resetRenderGovernorForTest,
} from '../renderGovernor.js';
import { framePortFor } from '../testSupport/fakeFramePort.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
/** The layer's disc set, as the fake draw port holds it. */
const discsOf = (draw) => draw.find('earthquakes:');
const FULL_RAW = {
id: 'us7000abcd',
@@ -92,25 +99,16 @@ test('earthquake overlay copy keeps source-side magnitude formatting and bounded
assert.equal(cohort.at(-1).id, 'quake-020');
});
test('real earthquake lifecycle publishes host labels while runtime entities carry no label graphic', async () => {
test('real earthquake lifecycle publishes host labels while the drawn discs carry no label graphic', async () => {
const originalFetch = globalThis.fetch;
const hostCalls = [];
const dataSources = [];
const overlayHost = {
setEntries: (...args) => hostCalls.push(['entries', ...args]),
setVisible: (...args) => hostCalls.push(['visible', ...args]),
clearSource: (...args) => hostCalls.push(['clear', ...args]),
};
const viewer = {
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer);
globalThis.fetch = async () => ({
ok: true,
json: async () => ({
@@ -134,9 +132,9 @@ test('real earthquake lifecycle publishes host labels while runtime entities car
layer.enable(viewer);
await layer.update(viewer);
const entities = dataSources[0].entities.values;
assert.equal(entities.length, 2, 'runtime guard requires populated real source entities');
assert.ok(entities.every((entity) => entity.label === undefined));
const discs = [...discsOf(draw).items.values()];
assert.equal(discs.length, 2, 'runtime guard requires populated real discs');
assert.ok(discs.every((disc) => disc.geometry.kind === 'ellipse'), 'discs, no label graphic');
const publication = hostCalls.find(([type]) => type === 'entries');
assert.ok(publication, 'real update path must publish the overlay source');
assert.deepEqual(publication[2].map(({ title }) => title), ['M5.2', 'M3.0']);
@@ -147,13 +145,13 @@ test('real earthquake lifecycle publishes host labels while runtime entities car
});
layer.disable(viewer);
assert.equal(dataSources[0].show, false);
assert.equal(discsOf(draw).show, false);
assert.deepEqual(hostCalls.slice(-2), [
['clear', 'earthquakes'],
['visible', 'earthquakes', false],
]);
layer.destroy(viewer);
assert.equal(dataSources.length, 0);
assert.equal(discsOf(draw), undefined, 'the set is disposed');
assert.deepEqual(hostCalls.slice(-2), [
['clear', 'earthquakes'],
['visible', 'earthquakes', false],
@@ -164,20 +162,16 @@ test('real earthquake lifecycle publishes host labels while runtime entities car
});
// ── Perf pin: the 2026-08-20 earthquakes frame-rate cliff ────────────────────
// Every disc is a CLAMP_TO_GROUND ellipse. When its axes were a
// Every disc is a ground-clamped ellipse. When its axes were a Cesium
// `CallbackProperty`, Cesium re-tessellated all 58 ground primitives on EVERY
// frame: 32.4 ms/frame and 30 fps for 58 contacts, against 1.4 ms/60 fps with
// the layer off. Static axes restored 60 fps. Both halves of the fix are
// pinned — the runtime property shape, and the source-level guards.
// the layer off. Static axes restored 60 fps. The discs are plain draw items
// now, written once per poll; both the item shape and the source-level guards
// are pinned.
test('quake disc axes are STATIC — a per-frame callback re-tessellates ground geometry', async () => {
const originalFetch = globalThis.fetch;
const dataSources = [];
const viewer = {
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove() { return true; },
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const layer = createEarthquakesLayer({
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
@@ -196,19 +190,21 @@ test('quake disc axes are STATIC — a per-frame callback re-tessellates ground
layer.enable(viewer);
await layer.update(viewer);
const [entity] = dataSources[0].entities.values;
assert.ok(entity.ellipse, 'the disc is an ellipse graphic');
for (const axis of ['semiMajorAxis', 'semiMinorAxis']) {
const property = entity.ellipse[axis];
assert.equal(
property instanceof Cesium.CallbackProperty,
false,
`${axis} must not be a CallbackProperty — it rebuilds the ground primitive every frame`,
);
assert.equal(property.isConstant, true, `${axis} must be a constant property`);
// Magnitude 5.5 → 2^5.5 * 1000 m, unchanged by the dropped pulse.
assert.equal(property.getValue(Cesium.JulianDate.now()), Math.pow(2, 5.5) * 1000);
}
const [disc] = discsOf(draw).items.values();
// Magnitude 5.5 → 2^5.5 * 1000 m: plain numbers, drawn once per poll.
assert.deepEqual(disc, {
id: 'earthquake:us-static-1',
geometry: {
kind: 'ellipse',
center: { lon: -122.4, lat: 37.79 },
semiMajor: Math.pow(2, 5.5) * 1000,
semiMinor: Math.pow(2, 5.5) * 1000,
},
// Shallow (8.2 km): red; significant (M5+): 0.4 fill.
fill: [1, 0, 0, 0.4],
height: 'clampGround',
clampTo: 'both',
});
} finally {
globalThis.fetch = originalFetch;
layer.destroy(viewer);
@@ -223,14 +219,10 @@ test('quake disc axes are STATIC — a per-frame callback re-tessellates ground
test('a quake poll still reaches the screen with the render loop idle', async () => {
const originalFetch = globalThis.fetch;
const renderRequests = [];
const dataSources = [];
const viewer = {
scene: { requestRenderMode: false, requestRender: () => renderRequests.push(Date.now()) },
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove() { return true; },
},
};
const { draw } = bindFakeDraw(viewer);
const layer = createEarthquakesLayer({
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
@@ -246,7 +238,7 @@ test('a quake poll still reaches the screen with the render loop idle', async ()
});
_resetRenderGovernorForTest();
installRenderGovernor(viewer);
installRenderGovernor(framePortFor(viewer.scene));
// Installing the governor enters idle mode, which itself paints one settling
// frame. Drop that from the baseline or the enable assertion below can pass on
// the install alone, without the manager ever requesting anything.
@@ -264,7 +256,7 @@ test('a quake poll still reaches the screen with the render loop idle', async ()
// ...and the poll that populated the discs must still have asked for a frame,
// because in idle mode nothing repaints on its own.
assert.ok(dataSources[0].entities.values.length > 0, 'the enable poll produced discs');
assert.ok(discsOf(draw).items.size > 0, 'the enable poll produced discs');
assert.ok(renderRequests.length > 0, 'enabling the layer must request a render in idle mode');
// Named, not merely counted: the frame has to come from the manager's
// visibility request, not from some incidental repaint.
@@ -298,7 +290,7 @@ test('the earthquakes layer installs no per-frame callback and no continuous-ren
readFileSync(new URL(`../layers/earthquakes/${name}.js`, import.meta.url), 'utf8')).join('\n');
assert.doesNotMatch(
source,
/new Cesium\.CallbackProperty/,
/CallbackProperty/,
'reverting the discs to a per-frame axis callback must fail this pin',
);
assert.doesNotMatch(
@@ -310,13 +302,8 @@ test('the earthquakes layer installs no per-frame callback and no continuous-ren
test('earthquake refresh reports failure and clears it only after a successful response', async () => {
const originalFetch = globalThis.fetch;
const dataSources = [];
const viewer = {
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove() { return true; },
},
};
const viewer = {};
bindFakeDraw(viewer);
const layer = createEarthquakesLayer({
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
@@ -340,13 +327,11 @@ test('earthquake refresh reports failure and clears it only after a successful r
}
});
test('malformed earthquake refresh preserves entities, overlays, count and timestamp', async () => {
test('malformed earthquake refresh preserves discs, overlays, count and timestamp', async () => {
const originalFetch = globalThis.fetch;
const dataSources = [];
const publications = [];
const viewer = { dataSources: {
add(source) { dataSources.push(source); }, remove() { return true; },
} };
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const layer = createEarthquakesLayer({ overlayHost: {
setEntries(...args) { publications.push(args); }, setVisible() {}, clearSource() {},
} });
@@ -358,15 +343,15 @@ test('malformed earthquake refresh preserves entities, overlays, count and times
layer.enable(viewer);
respond([good]);
assert.equal(await layer.update(viewer), true);
const entity = dataSources[0].entities.values[0];
const writes = discsOf(draw).writes;
const stats = layer.getStats();
for (const properties of ['invalid', 123, [], true]) {
const bad = { ...good, id: 'bad-properties', properties };
for (const features of [[bad], [good, bad]]) {
respond(features);
assert.equal(await layer.update(viewer), false);
assert.equal(dataSources[0].entities.values.length, 1);
assert.equal(dataSources[0].entities.values[0], entity);
assert.equal(discsOf(draw).items.size, 1);
assert.equal(discsOf(draw).writes, writes, 'not redrawn');
assert.equal(layer.getStats().count, stats.count);
assert.equal(layer.getStats().lastUpdate, stats.lastUpdate);
assert.equal(layer.getStats().error, 'Malformed USGS response');
@@ -382,8 +367,8 @@ test('malformed earthquake refresh preserves entities, overlays, count and times
{ ...good, properties: { mag: Infinity } }, good]) {
respond([good, bad]);
assert.equal(await layer.update(viewer), false);
assert.equal(dataSources[0].entities.values.length, 1);
assert.equal(dataSources[0].entities.values[0], entity);
assert.equal(discsOf(draw).items.size, 1);
assert.equal(discsOf(draw).writes, writes, 'not redrawn');
assert.equal(layer.getStats().count, stats.count);
assert.equal(layer.getStats().lastUpdate, stats.lastUpdate);
assert.equal(layer.getStats().error, 'Malformed USGS response');
@@ -391,14 +376,21 @@ test('malformed earthquake refresh preserves entities, overlays, count and times
}
respond([{ ...good, properties: { mag: null } }]);
assert.equal(await layer.update(viewer), true);
assert.equal(dataSources[0].entities.values.length, 0);
assert.equal(discsOf(draw).items.size, 0);
assert.equal(layer.getStats().error, null);
assert.equal(publications.at(-1)[1].length, 0);
respond([good]);
assert.equal(await layer.update(viewer), true);
assert.equal(dataSources[0].entities.values.length, 1);
assert.equal(discsOf(draw).items.size, 1);
} finally {
globalThis.fetch = originalFetch;
layer.destroy(viewer);
}
});
test('depth bands keep the renderer colours and label accents they had as Cesium colours', () => {
for (const [depthKm, color] of [[10, Cesium.Color.RED], [100, Cesium.Color.ORANGE], [400, Cesium.Color.YELLOW]]) {
assert.deepEqual(depthColor(depthKm), [color.red, color.green, color.blue, color.alpha]);
assert.equal(depthAccent(depthKm), color.toCssColorString());
}
});
File diff suppressed because it is too large. Load diff
+506
View File
@@ -0,0 +1,506 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
aircraftInsights,
describeEntity,
findRecord,
formatFact,
layerBreakdown,
nearbyEntities,
recordTitle,
recordWarnings,
searchEntities,
viewSummary,
} from './entityContext.js';
/** A data manager over fixed layer records. */
function manager(layers) {
const map = new Map(
Object.entries(layers).map(([id, { name, records }]) => [
id,
{ id, name, enabled: true, module: { getAnalystRecords: () => records } },
]),
);
return {
layers: map,
isEnabled: (id) => map.get(id)?.enabled === true,
getAll: () => [...map.values()],
};
}
const flights = Array.from({ length: 2500 }, (_, i) => ({
id: `FLT${i}`,
icao24: `a${String(i).padStart(5, '0')}`,
callsign: `FLT${i}`,
lat: 34 + i * 0.001,
lon: -118,
altitudeM: 10000,
}));
const dams = [
{
id: 'Grand Coulee Dam',
name: 'Grand Coulee Dam',
lat: 47.957,
lon: -118.981,
operator: 'Bureau of Reclamation',
},
{
id: '123456',
name: null,
lat: 47.9,
lon: -118.9,
operator: 'Some Utility',
},
];
const dm = manager({
flights: { name: 'Live Flights', records: flights },
'local-dams': { name: 'Dams', records: dams },
});
test('a click identity finds its record by key, past the first 2000 records', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'a02400',
lat: 0,
lon: 0,
});
assert.equal(record?.callsign, 'FLT2400');
});
test('a transit click finds its vehicle by the layer key and reads its state', () => {
const buses = manager({
transit: {
name: 'Transit',
records: [
{
id: 'M634',
key: 'capmetro-austin:M634',
route: '801',
operator: 'CapMetro',
status: 'IN_TRANSIT_TO',
lat: 30.2,
lon: -97.7,
},
],
},
});
const card = describeEntity(buses, {
layerId: 'transit',
id: 'capmetro-austin:M634',
lat: 30.21,
lon: -97.71,
});
assert.equal(card?.title, 'M634');
const facts = Object.fromEntries(
card.facts.map((fact) => [fact.label, fact.value]),
);
assert.equal(facts.Operator, 'CapMetro');
assert.equal(facts.Status, 'Heading to next stop');
assert.equal(facts.Key, undefined, 'the layer key is not shown');
});
test('transit vehicles break down by motion, mode and reported state', () => {
const at = { lat: 30.2, lon: -97.7 };
const buses = manager({
transit: {
name: 'Transit',
records: [
{
id: '1',
mode: 'bus',
motion: 'moving',
status: 'IN_TRANSIT_TO',
...at,
},
{
id: '2',
mode: 'bus',
motion: 'stopped',
status: 'STOPPED_AT',
...at,
},
{ id: '3', mode: 'rail', motion: 'moving', occupancy: 'FULL', ...at },
],
},
});
const breakdown = layerBreakdown(buses, 'transit');
assert.equal(breakdown.total, 3);
const split = (title) =>
Object.fromEntries(
breakdown.splits
.find((item) => item.title === title)
.parts.map((part) => [part.label, part.count]),
);
assert.deepEqual(split('Motion'), { Moving: 2, Stopped: 1 });
assert.deepEqual(split('Mode'), { Bus: 2, Rail: 1 });
assert.deepEqual(split('Last reported'), {
'Heading to next stop': 1,
'Stopped at a stop': 1,
});
assert.deepEqual(split('Crowding'), { Full: 1 });
});
test('a moving item never borrows a nearby craft when its key is unknown', () => {
const record = findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.0004,
lon: -118.05,
});
assert.equal(record, null);
});
test('an unnamed site goes by its operator, not its database number', () => {
assert.equal(recordTitle(dams[1]), 'Some Utility');
});
test('a card lists facts with units and keeps the title out of them', () => {
const card = describeEntity(dm, { layerId: 'flights', id: 'a00001' });
assert.equal(card.title, 'FLT1');
assert.equal(card.kind, 'aircraft');
assert.ok(
card.facts.some(
(fact) => fact.label === 'Altitude' && fact.value === '32,808 ft',
),
);
assert.ok(!card.facts.some((fact) => fact.value === 'FLT1'));
});
test('nearby lists the closest of the same kind and one of each other layer', () => {
const card = describeEntity(dm, {
layerId: 'local-dams',
id: 'Grand Coulee Dam',
});
const { same, other } = nearbyEntities(dm, card, { radiusKm: 2000 });
assert.equal(same[0].title, 'Some Utility');
assert.equal(other.length, 1);
assert.equal(other[0].layerId, 'flights');
});
test('search ranks an exact name first and needs two characters', () => {
assert.deepEqual(searchEntities(dm, 'f'), []);
const [first] = searchEntities(dm, 'FLT12');
assert.equal(first.title, 'FLT12');
assert.equal(searchEntities(dm, 'coulee')[0]?.title, 'Grand Coulee Dam');
});
test('fact formatting follows the field suffix', () => {
assert.equal(formatFact('speedMps', 100).value, '194 kt');
// Orbital speeds read in km/s, road and rail in km/h.
assert.equal(formatFact('speedMps', 7670).value, '7.67 km/s');
assert.equal(
formatFact('speedMps', 10, { kind: 'vehicle' }).value,
'36 km/h',
);
// Units follow the field's suffix; feed codes and bare words read as words.
assert.equal(formatFact('containedPct', 96).value, '96%');
assert.equal(formatFact('windKt', 30).value, '30 kt');
assert.equal(formatFact('pressureHpa', 1009).value, '1,009 hPa');
assert.equal(formatFact('classification', 'TD').value, 'Tropical depression');
assert.equal(formatFact('telecom', 'data_center').value, 'Data center');
assert.equal(formatFact('icao24', 'abcdef').value, 'abcdef');
assert.equal(formatFact('shipType', 70).value, 'Cargo');
assert.equal(formatFact('shipType', 'Tanker').value, 'Tanker');
assert.equal(
formatFact('discoveredTime', Date.UTC(2026, 5, 29)).value,
'29 Jun 2026',
);
assert.equal(
formatFact('updatedTime', 1_700_000_000_000, { nowMs: 1_700_000_060_000 })
.age,
60_000,
);
assert.equal(formatFact('altitudeM', 420000).value, '420 km');
assert.equal(formatFact('confidence', 0.82).value, '82%');
assert.equal(formatFact('onGround', false), null);
assert.equal(
formatFact('lastContactAtMs', 1_700_000_000_000, {
nowMs: 1_700_000_060_000,
}).age,
60_000,
);
});
test('warnings lead with an emergency, then the squawk code, and stay out of the facts', () => {
assert.deepEqual(
recordWarnings({ emergency: true, emergencyKind: 'medical' }),
['Emergency: medical'],
);
assert.deepEqual(recordWarnings({ squawk: '7600' }), [
'Radio failure (squawk 7600)',
]);
assert.deepEqual(
recordWarnings({ squawk: '1200', emergencyKind: 'none' }),
[],
);
assert.deepEqual(recordWarnings({ tsunami: 1 }), ['Tsunami warning issued']);
const urgent = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'X1',
icao24: 'x00001',
callsign: 'X1',
lat: 1,
lon: 1,
emergency: true,
emergencyKind: 'fuel',
},
],
},
});
const card = describeEntity(urgent, { layerId: 'flights', id: 'x00001' });
assert.deepEqual(card.warnings, ['Emergency: fuel']);
assert.ok(!card.facts.some((fact) => /emergency/i.test(fact.label)));
});
test('the view summary counts each layer inside the view, closest to the middle first', () => {
const groups = viewSummary(
dm,
{ west: -119, south: 34, east: -117, north: 34.5 },
{ lat: 34.1, lon: -118 },
{ perLayer: 2 },
);
assert.equal(groups.length, 1);
assert.equal(groups[0].layerId, 'flights');
assert.equal(groups[0].count, 501);
assert.equal(groups[0].items[0].title, 'FLT100');
});
test('flight insights work out phase, flight level, Mach, squawk meaning and signal age', () => {
const insights = aircraftInsights(
{
altitudeM: 10668,
verticalRateMps: 0,
speedMps: 230,
squawk: '7000',
lastContactAtMs: 1_000_000,
},
{ nowMs: 1_012_000 },
);
const value = (label) => insights.find((item) => item.label === label)?.value;
assert.equal(value('Phase'), 'Cruising, level');
assert.equal(value('Flight level'), 'FL350');
assert.equal(value('Mach'), 'M 0.78');
assert.equal(value('Squawk {code}'), 'VFR conspicuity');
assert.deepEqual(
insights.find((item) => item.label === 'Squawk {code}').labelValues,
{ code: '7000' },
);
assert.equal(value('Signal'), '12 s ago');
assert.equal(aircraftInsights({ onGround: true })[0].value, 'On the ground');
assert.match(
aircraftInsights({ verticalRateMps: -8 })[0].value,
/^Descending 1600 ft\/min$/,
);
});
test('a layer breakdown splits aircraft by status and type, inside a view when given', () => {
const craft = [
{
id: 'A',
lat: 10,
lon: 10,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
{
id: 'B',
lat: 10,
lon: 11,
onGround: false,
military: true,
aircraftClass: 'fastjet',
},
{
id: 'C',
lat: 10,
lon: 12,
onGround: true,
military: true,
aircraftClass: 'airliner',
},
{
id: 'D',
lat: 60,
lon: 12,
onGround: false,
military: false,
aircraftClass: 'airliner',
},
];
const data = manager({
flights: { name: 'Live Flights', records: craft },
'local-dams': { name: 'Dams', records: dams },
});
const all = layerBreakdown(data, 'flights');
assert.equal(all.total, 4);
assert.deepEqual(all.splits[0].parts, [
{ label: 'Civilian, in the air', count: 2 },
{ label: 'Military, in the air', count: 1 },
{ label: 'On the ground', count: 1 },
]);
assert.deepEqual(all.splits[1].parts, [
{ label: 'Airliners', count: 3 },
{ label: 'Fast jets', count: 1 },
]);
const near = layerBreakdown(data, 'flights', {
rect: { west: 9, east: 13, south: 9, north: 11 },
});
assert.equal(near.total, 3);
assert.equal(layerBreakdown(data, 'local-dams'), null);
});
test('a moving item with an unknown key is not matched to a craft right beside it', () => {
// About 110 m from FLT0: well inside any nearest-item reach.
assert.equal(
findRecord(dm, {
layerId: 'flights',
id: 'zzzzzz',
label: 'NOPE',
lat: 34.001,
lon: -118,
}),
null,
);
});
test('sites that share a key are told apart by where the identity says they are', () => {
const sites = [
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -52.942,
lon: -70.849,
},
{
id: 'Amazon Web Services',
name: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
},
];
const data = manager({
'local-datacenters': { name: 'Datacenters', records: sites },
});
const identity = {
layerId: 'local-datacenters',
id: 'Amazon Web Services',
label: 'Amazon Web Services',
lat: -33.557,
lon: -70.813,
};
assert.equal(findRecord(data, identity), sites[1]);
const card = describeEntity(data, identity);
assert.equal(card.lat, -33.557);
// The card's own identity finds the same site again, as its refresh does.
assert.equal(findRecord(data, card.identity), sites[1]);
});
test('a link is built only from a language code, and a level is not a warning', () => {
const site = {
id: 'X',
name: 'X',
lat: 1,
lon: 1,
wikipedia: 'evil.example/a#:Y',
};
const data = manager({ 'local-dams': { name: 'Dams', records: [site] } });
assert.deepEqual(
describeEntity(data, { layerId: 'local-dams', id: 'X', lat: 1, lon: 1 })
.links,
[],
);
assert.deepEqual(recordWarnings({ alert: 'green' }), []);
});
test('a breakdown names "Other" once', () => {
const ships = [30, 30, 70, 70, 70, 80, 80, 60, 37, 52, 52, 90, 90, 90].map(
(shipType, i) => ({
id: `S${i}`,
mmsi: String(i),
lat: 1,
lon: 1 + i * 0.01,
shipType,
}),
);
const data = manager({
'ais-live-vessels': { name: 'Vessels', records: ships },
});
const labels = layerBreakdown(data, 'ais-live-vessels').splits[0].parts.map(
(part) => part.label,
);
assert.equal(labels.filter((label) => label === 'Other').length <= 1, true);
assert.equal(new Set(labels).size, labels.length);
});
test('a card shows the photo its layer looked up: the tracked airliner, the selected vessel', () => {
const photo = {
src: 'https://cdn.example/p.jpg',
link: 'https://example/p',
photographer: 'A. Spotter',
width: 640,
};
const planes = manager({
flights: {
name: 'Live Flights',
records: [
{
id: 'DAL1',
icao24: 'aa0001',
callsign: 'DAL1',
lat: 34,
lon: -118,
typeCode: 'B739',
category: 'A3',
},
{ id: 'DAL2', icao24: 'aa0002', callsign: 'DAL2', lat: 35, lon: -118 },
],
},
'ais-live-vessels': {
name: 'Vessels',
records: [
{
id: 'EVER GIVEN',
vesselId: 'v1',
mmsi: '353136000',
lat: 30,
lon: 32,
},
],
},
});
planes.layers.get('flights').module.getTrackedSubject = () => ({
id: 'aa0001',
photo,
});
planes.layers.get('ais-live-vessels').module.getVesselPhoto = (id) =>
id === 'v1' ? { ...photo, licence: 'CC BY 4.0' } : null;
const tracked = describeEntity(planes, { layerId: 'flights', id: 'aa0001' });
assert.deepEqual(tracked.photo, {
src: photo.src,
link: photo.link,
photographer: 'A. Spotter',
licence: '',
});
// What picks the globe's fleet model for it.
assert.deepEqual(tracked.aircraftModel, {
typeCode: 'B739',
category: 'A3',
callsign: 'DAL1',
});
// Photos are looked up for the tracked plane only.
assert.equal(
describeEntity(planes, { layerId: 'flights', id: 'aa0002' }).photo,
null,
);
assert.equal(
describeEntity(planes, { layerId: 'ais-live-vessels', id: 'EVER GIVEN' })
.photo.licence,
'CC BY 4.0',
);
});
+75
View File
@@ -0,0 +1,75 @@
/**
* @module entityRecords
* @description Records for the entities layers draw, so layer state lives in the app
* rather than on the renderer's objects. A layer writes the record for an entity it draws;
* the tracked readout, follow camera, cockpit, share links and awareness read it back
* through the entity the renderer hands them (a pick or the tracked entity).
*
* Fields a record may hold:
* - `trackedId`: the normalized `layer:id` identity, e.g. `flights:a1b2c3`.
* - `displayPosition()`: the layer's cached display position (the follow camera's
* anti-jitter contract: the value the camera settled on, never recomputed late).
* - `visualPosition()`: where a 3D model is actually drawn, for the tracked card.
* - `labelModel`: the tracked card's `{ title, details, accent, … }`.
* - `selectionOrigin`: what started the selection (`'user'`, …).
* - `sprite`: a tracked billboard's pushed `{ width, height, scale, scaleByDistance }`, for
* the close-range camera guard and the screen annotations' tracked footprint.
* - `groundSets()`: the draw set ids a height sample under the contact sees through (its own
* icons and models), for Cockpit's ground probe.
*
* A layer's private per-entity state goes in its own store ({@link createEntityStore}).
*/
/**
* A store of one record per renderer object, held by the app and dropped with the object.
* @returns {{ write: (entity: Object) => Object, read: (entity: unknown) => Object|null }}
* `write` makes the record empty on first use; `read` gives null when there is none.
*/
export function createEntityStore() {
const records = new WeakMap();
return {
write(entity) {
let record = records.get(entity);
if (!record) {
record = {};
records.set(entity, record);
}
return record;
},
read(entity) {
if (!entity || typeof entity !== 'object') return null;
return records.get(entity) ?? null;
},
};
}
const shared = createEntityStore();
/**
* The record for `entity`, made empty on first use. For layers writing their own state.
* @param {Object} entity An entity the layer draws.
* @returns {Object}
*/
export function entityRecord(entity) {
return shared.write(entity);
}
/**
* The record for `entity`, or null when it has none (or there is no entity). For readers.
* @param {Object|null|undefined} entity
* @returns {Object|null}
*/
export function readEntityRecord(entity) {
return shared.read(entity);
}
/**
* Write `fields` into `entity`'s record and return the entity.
* @param {Object} entity
* @param {Object} fields Record fields to set.
* @returns {Object} `entity`
*/
export function withEntityRecord(entity, fields) {
Object.assign(entityRecord(entity), fields);
return entity;
}
+48
View File
@@ -0,0 +1,48 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import {
createEntityStore,
entityRecord,
readEntityRecord,
withEntityRecord,
} from './entityRecords.js';
test('an entity record is made on first write and read back by the same entity', () => {
const entity = {};
assert.equal(readEntityRecord(entity), null);
entityRecord(entity).trackedId = 'flights:a1b2c3';
assert.equal(entityRecord(entity), entityRecord(entity), 'one record per entity');
assert.equal(readEntityRecord(entity)?.trackedId, 'flights:a1b2c3');
assert.equal(readEntityRecord({}), null, 'another entity has its own record');
});
test('the record lives in the app, not on the entity', () => {
const entity = {};
entityRecord(entity).labelModel = { title: 'DAL123', details: [] };
assert.deepEqual(Object.keys(entity), []);
});
test('reading without an entity gives null', () => {
assert.equal(readEntityRecord(null), null);
assert.equal(readEntityRecord(undefined), null);
assert.equal(readEntityRecord('flights:a1b2c3'), null);
});
test('withEntityRecord writes fields into the record and returns the entity', () => {
const entity = withEntityRecord({ id: 'alpr:42' }, { trackedId: 'alpr:42' });
assert.equal(entity.id, 'alpr:42');
assert.equal(readEntityRecord(entity)?.trackedId, 'alpr:42');
assert.equal(Object.hasOwn(entity, 'trackedId'), false);
});
test('a layer store is separate from the shared records and from other stores', () => {
const entity = {};
const a = createEntityStore();
const b = createEntityStore();
a.write(entity).canvasPosition = 1;
assert.equal(a.read(entity)?.canvasPosition, 1);
assert.equal(b.read(entity), null);
assert.equal(readEntityRecord(entity), null);
assert.equal(a.read(null), null);
assert.deepEqual(Object.keys(entity), []);
});
+4 -1
View File
@@ -16,6 +16,8 @@ import {
import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js';
import { getLocale, setLocale } from '../i18n/index.js';
import { reportMeshFloorCell, setMeshFloorPreferred } from './groundFloor.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
const NOW = Date.UTC(2026, 6, 17, 4, 0);
const H = 3600000;
@@ -232,6 +234,8 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async ()
primitives: { contains() { return false; } },
},
};
bindFakeCesiumScene(viewer);
fakeInput(viewer);
const layer = createFirmsHeatmapLayer({
id: 'firms',
name: 'FIRMS',
@@ -240,7 +244,6 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async ()
setVisible: (...args) => calls.push(['visible', ...args]),
clearSource: (...args) => calls.push(['clear', ...args]),
},
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
});
try {
layer.init(viewer);
-1
View File
@@ -16,7 +16,6 @@ const helpers = createFirmsHelpers({
});
export const mapAnalystRecord = helpers.mapAnalystRecord;
export const fireCullPosition = helpers.fireCullPosition;
export const applyHorizonCull = helpers.applyHorizonCull;
export const buildSelectedFireCard = helpers.buildSelectedFireCard;
export const buildFireCard = helpers.buildFireCard;
export const buildCellCard = helpers.buildCellCard;
+181 -134
View File
@@ -1,11 +1,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
applyHorizonCull,
createFirmsHeatmapLayer,
fireCullPosition,
} from './firmsHeatmap.js';
import { createFirmsHeatmapLayer, fireCullPosition } from './firmsHeatmap.js';
import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js';
import { FIRMS_AMBIENT_COHORT_LIMIT, FIRMS_OVERLAY_SOURCE_ID } from './firmsLabels.js';
import {
@@ -13,8 +9,12 @@ import {
reportMeshFloorCell,
setMeshFloorPreferred,
} from './groundFloor.js';
import { unregisterSpriteCollection } from './spriteOrder.js';
import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldOverlay.js';
import { createIconSet, ICON_CULL_LIFT } from './iconSet.js';
import { writeHoldSegment } from './iconSegment.js';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
import { createCesiumDraw } from '../render/cesium/draw.js';
const AUSTIN = { lon: -97.7, lat: 30.2 };
/** Antipode of Austin — as far behind the limb as a point on Earth can be. */
@@ -28,24 +28,26 @@ const REPRO_HEIGHT_M = 1_500_000;
* at −22 m but visible at +5/+12 m. Measured against Cesium's own occluder.
*/
const LIMB_DLON = 41.87;
/** Farther east, where 11 m reads hidden and 12 m visible from the same camera. */
const LIFT_BAND_DLON = 41.9452;
/**
* Billboard stub that records every write to `show` so the tests can assert
* the pass does not dirty the collection's vertex buffer needlessly.
* Whether the icon set's GPU pass draws `row` from `occluder`'s camera: the
* shader's horizon test on the row's cull point (its CPU twin).
*/
function billboard(position, show = true) {
return {
position,
_show: show,
writes: 0,
get show() { return this._show; },
set show(value) { this._show = value; this.writes += 1; },
};
function gpuShows(set, row, occluder) {
const position = set.position(row, 0, new Cesium.Cartesian3());
return set.shown(row) && occluder.isPointVisible(set.cullPoint(row, position));
}
/** Cesium BillboardCollection-shaped stub. */
function collection(items) {
return { length: items.length, get: (i) => items[i] };
/** A fire-shaped row (shown, CULL_LIFT) held at `position`. */
function fireRow(set, id, position) {
const row = set.add(id, { layer: 'firms', id });
set.setFlag(row, ICON_CULL_LIFT, true);
set.setShown(row, true);
writeHoldSegment(set.segments, row, position, 0);
set.segmentWritten(row);
return row;
}
/** Horizon occluder for a camera directly above Austin at `heightM`. */
@@ -57,92 +59,71 @@ function occluderOverAustin(heightM) {
}
// ---------------------------------------------------------------------------
// The pure cull predicate
// The GPU horizon cull a fire row gets
// ---------------------------------------------------------------------------
test('applyHorizonCull: far-side fires are hidden, near-side fires stay visible', () => {
test('icon cull: far-side fires are hidden, near-side fires stay visible', () => {
const occluder = occluderOverAustin(REPRO_HEIGHT_M);
const near = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0));
const nearby = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon + 6, AUSTIN.lat + 4, 0));
const far = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 0));
const otherSide = billboard(Cesium.Cartesian3.fromDegrees(TOKYO.lon, TOKYO.lat, 0));
const set = createIconSet();
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, 0);
const near = fireRow(set, 'near', at(AUSTIN));
const nearby = fireRow(set, 'nearby', at({ lon: AUSTIN.lon + 6, lat: AUSTIN.lat + 4 }));
const far = fireRow(set, 'far', at(ANTIPODE));
const otherSide = fireRow(set, 'tokyo', at(TOKYO));
const visible = applyHorizonCull(collection([near, nearby, far, otherSide]), occluder);
assert.equal(near.show, true, 'the fire under the camera renders');
assert.equal(nearby.show, true, 'a fire well inside the horizon renders');
assert.equal(far.show, false, 'the antipodal fire must not shine through the planet');
assert.equal(otherSide.show, false, 'Tokyo is beyond the limb from Austin at 1.5 Mm');
assert.equal(visible, 2, 'returns the surviving count');
assert.equal(gpuShows(set, near, occluder), true, 'the fire under the camera renders');
assert.equal(gpuShows(set, nearby, occluder), true, 'a fire well inside the horizon renders');
assert.equal(gpuShows(set, far, occluder), false, 'the antipodal fire must not shine through the planet');
assert.equal(gpuShows(set, otherSide, occluder), false, 'Tokyo is beyond the limb from Austin at 1.5 Mm');
});
test('applyHorizonCull: raising the camera reveals fires the low camera hid', () => {
const paris = () => billboard(Cesium.Cartesian3.fromDegrees(2.35, 48.86, 0));
const low = paris();
applyHorizonCull(collection([low]), occluderOverAustin(REPRO_HEIGHT_M));
assert.equal(low.show, false, 'Paris is over the horizon from a 1.5 Mm Austin camera');
const high = paris();
applyHorizonCull(collection([high]), occluderOverAustin(35_000_000));
assert.equal(high.show, true, 'from geostationary height the same fire is in view');
test('icon cull: raising the camera reveals fires the low camera hid', () => {
const set = createIconSet();
const paris = fireRow(set, 'paris', Cesium.Cartesian3.fromDegrees(2.35, 48.86, 0));
assert.equal(gpuShows(set, paris, occluderOverAustin(REPRO_HEIGHT_M)), false);
assert.equal(gpuShows(set, paris, occluderOverAustin(35_000_000)), true, 'in view from geostationary height');
});
test('applyHorizonCull: a hidden fire is restored when it swings back into view', () => {
const revealed = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0), false);
applyHorizonCull(collection([revealed]), occluderOverAustin(REPRO_HEIGHT_M));
assert.equal(revealed.show, true, 'the cull un-hides as well as hides');
assert.equal(revealed.writes, 1);
});
test('applyHorizonCull: only flipped billboards are written (vertex-buffer churn)', () => {
test('icon cull: a sub-ellipsoid anchor is judged lifted, a far-side one still culls', () => {
const occluder = occluderOverAustin(REPRO_HEIGHT_M);
const stays = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0), true);
const flips = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 0), true);
const set = createIconSet();
const sunken = fireRow(set, 'sunken', Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, -22));
assert.equal(gpuShows(set, sunken, occluder), true, 'the lifted cull point keeps the near-limb fire on screen');
set.setFlag(sunken, ICON_CULL_LIFT, false);
assert.equal(gpuShows(set, sunken, occluder), false, 'baseline: the raw anchor false-hides at the limb');
applyHorizonCull(collection([stays, flips]), occluder);
applyHorizonCull(collection([stays, flips]), occluder);
assert.equal(stays.writes, 0, 'an already-visible billboard is never re-assigned');
assert.equal(flips.writes, 1, 'a hidden billboard is written once, not once per pass');
const far = fireRow(set, 'far', Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, -22));
assert.equal(gpuShows(set, far, occluder), false, '12 m of lift must not defeat the actual horizon cull');
});
test('applyHorizonCull: missing collection/occluder/holes are no-ops, not throws', () => {
assert.equal(applyHorizonCull(null, occluderOverAustin(REPRO_HEIGHT_M)), 0);
assert.equal(applyHorizonCull({ length: 3 }, occluderOverAustin(REPRO_HEIGHT_M)), 0, 'non-collection shape');
const item = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0));
assert.equal(applyHorizonCull(collection([item]), null), 0, 'no occluder → leave the layer alone');
assert.equal(applyHorizonCull(collection([item]), {}), 0, 'occluder without isPointVisible');
assert.equal(item.writes, 0, 'a skipped pass must not touch show');
assert.equal(
applyHorizonCull(collection([undefined, item]), occluderOverAustin(REPRO_HEIGHT_M)),
1,
'sparse slots are skipped, surviving neighbours still counted',
);
});
// ---------------------------------------------------------------------------
// Sub-ellipsoid anchors: datum-correct render point, lifted CULL point
// ---------------------------------------------------------------------------
test('applyHorizonCull: an index-aligned cull position overrides the render anchor', () => {
test('fireCullPosition: a card is judged where its sprite is', () => {
const occluder = occluderOverAustin(REPRO_HEIGHT_M);
const sunken = billboard(Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, -22));
const lifted = Cesium.Cartesian3.fromDegrees(AUSTIN.lon + LIMB_DLON, AUSTIN.lat, 12);
applyHorizonCull(collection([sunken]), occluder);
assert.equal(sunken.show, false, 'baseline: the raw sub-ellipsoid anchor false-hides at the limb');
applyHorizonCull(collection([sunken]), occluder, [lifted]);
assert.equal(sunken.show, true, 'the lifted cull point keeps the near-limb fire on screen');
});
test('applyHorizonCull: a lifted cull point does NOT resurrect a genuinely far-side fire', () => {
const occluder = occluderOverAustin(REPRO_HEIGHT_M);
const far = billboard(Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, -22));
const lifted = Cesium.Cartesian3.fromDegrees(ANTIPODE.lon, ANTIPODE.lat, 12);
applyHorizonCull(collection([far]), occluder, [lifted]);
assert.equal(far.show, false, '12 m of lift must not defeat the actual horizon cull');
const set = createIconSet();
setMeshFloorPreferred(true);
try {
// Sunk, an 11 m anchor (floor 6 + lift), and well above: each card must
// agree with the GPU test on its own row, at limb points where they can.
for (const [i, floor] of [-27, 6, 900].entries()) {
_clearMeshFloorCellsForTest(); // a reported cell latches its first floor
for (const dLon of [LIMB_DLON, LIFT_BAND_DLON]) {
const lat = AUSTIN.lat;
const lon = AUSTIN.lon + dLon;
reportMeshFloorCell(lat, lon, floor);
const fire = { index: i, lat, lon, frp: 10, position: null };
const cull = fireCullPosition(fire);
assert.equal(fire.positionHeight, floor + FIRE_ANCHOR_LIFT_M);
const row = fireRow(set, `${floor}:${dLon}`, fire.position);
assert.equal(
occluder.isPointVisible(cull),
gpuShows(set, row, occluder),
`floor ${floor} m at +${dLon}°`,
);
}
}
} finally {
_clearMeshFloorCellsForTest();
setMeshFloorPreferred(false);
}
});
test('fireCullPosition: negative-geoid anchor renders at the datum but culls lifted', () => {
@@ -226,8 +207,9 @@ test('isOverlayPointVisible: horizon test prefers entry.cullPosition when presen
test('normalizeOverlayEntry: carries a valid cullPosition, nulls a junk one', () => {
const position = { x: 1, y: 2, z: 3 };
const kept = normalizeOverlayEntry('firms', { id: 'a', position, cullPosition: { x: 4, y: 5, z: 6 } });
assert.ok(kept.cullPosition instanceof Cesium.Cartesian3, 'stored as a host-owned Cartesian3');
const cullPosition = { x: 4, y: 5, z: 6 };
const kept = normalizeOverlayEntry('firms', { id: 'a', position, cullPosition });
assert.notEqual(kept.cullPosition, cullPosition, 'stored as a host-owned copy');
assert.deepEqual(
[kept.cullPosition.x, kept.cullPosition.y, kept.cullPosition.z],
[4, 5, 6],
@@ -304,17 +286,21 @@ class MockEvent {
emit() { for (const listener of [...this.listeners]) listener(); }
}
/** Canvas stub good enough for the pre-baked glow sprites. */
/**
* Canvas stub good enough for the pre-baked glow sprites. Its data URL names
* the gradient's colours, so each colour stop gets its own atlas slot.
*/
function canvasStub() {
const stops = [];
return {
width: 0,
height: 0,
getContext: () => ({
createRadialGradient: () => ({ addColorStop() {} }),
createRadialGradient: () => ({ addColorStop: (offset, color) => stops.push(color) }),
fillStyle: null,
fillRect() {},
}),
toDataURL: () => 'data:image/png;base64,iVBORw0KGgo=',
toDataURL: () => `data:image/png;base64,iVBORw0KGgo=#${stops.join('|')}`,
};
}
@@ -335,9 +321,8 @@ function rawFire(lat, lon, frp) {
}
/**
* Boots the REAL layer against a headless viewer stub with a REAL
* Cesium.BillboardCollection, so the production hooks (not just the pure
* predicate) are what the assertions exercise.
* Boots the REAL layer against a headless viewer stub; what the GPU would draw
* is read off the layer's real icon set (`gpuShows`) from the stub camera.
*/
function createHarness(rawFires) {
const originalFetch = globalThis.fetch;
@@ -383,13 +368,26 @@ function createHarness(rawFires) {
preRender,
primitives: {
add: (value) => { primitives.push(value); return value; },
remove: () => {},
remove: (value) => {
const at = primitives.indexOf(value);
if (at < 0) return false;
primitives.splice(at, 1);
value.destroy();
return true;
},
contains: () => false,
},
frameState: { mode: Cesium.SceneMode.SCENE3D, mapProjection: new Cesium.GeographicProjection() },
mapProjection: new Cesium.GeographicProjection(),
requestRender: () => {},
isDestroyed: () => false,
},
};
// The Cesium draw port over the stub scene: the glows are a real GPU icon
// set, whose rows say what the GPU would draw.
const draw = createCesiumDraw({ scene: viewer.scene, report: () => {} });
bindFakeCesiumScene(viewer, { draw: draw.port });
fakeInput(viewer);
const layer = createFirmsHeatmapLayer({
id: 'firms',
@@ -399,7 +397,6 @@ function createHarness(rawFires) {
setVisible: () => {},
clearSource: () => {},
},
screenSpaceEventHandlerFactory: () => ({ setInputAction() {}, destroy() {} }),
});
return {
@@ -407,15 +404,19 @@ function createHarness(rawFires) {
viewer,
preRender,
moveEnd,
/** The real BillboardCollection the layer created. */
billboards: () => primitives[0],
/** The icon set the layer draws its detections from. */
icons: () => primitives[0].set,
/** Primitives currently in the stub scene. */
primitives,
/** Latest entry list published to the overlay host. */
latestEntries: () => entryCalls[entryCalls.length - 1] || [],
/** `show` flags keyed by billboard pick id. */
/** Whether the GPU draws each row from the current camera, by pick id. */
showById() {
const bb = primitives[0];
const set = primitives[0].set;
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84, viewer.camera.positionWC);
const out = new Map();
for (let i = 0; i < bb.length; i += 1) out.set(bb.get(i).id, bb.get(i).show);
for (let row = 0; row < set.count; row += 1)
out.set(set.idAt(row), primitives[0].show !== false && set.show && gpuShows(set, row, occluder));
return out;
},
moveCameraTo(lon, lat, height = REPRO_HEIGHT_M) {
@@ -424,7 +425,6 @@ function createHarness(rawFires) {
},
cleanup() {
layer.destroy(viewer);
unregisterSpriteCollection('firms');
Cesium.SceneTransforms.worldToWindowCoordinates = originalProject;
globalThis.fetch = originalFetch;
if (originalWindow === undefined) delete globalThis.window; else globalThis.window = originalWindow;
@@ -433,7 +433,7 @@ function createHarness(rawFires) {
};
}
test('layer: a detection rebuild culls its own freshly-added sprites', async () => {
test('layer: far-side detections are culled from the first frame', async () => {
const harness = createHarness([
rawFire(AUSTIN.lat, AUSTIN.lon, 120),
rawFire(ANTIPODE.lat, ANTIPODE.lon, 900),
@@ -453,7 +453,7 @@ test('layer: a detection rebuild culls its own freshly-added sprites', async ()
}
});
test('layer: camera moveEnd re-culls without a rebuild', async () => {
test('layer: the GPU cull follows the camera with no CPU show pass', async () => {
const harness = createHarness([
rawFire(AUSTIN.lat, AUSTIN.lon, 120),
rawFire(TOKYO.lat, TOKYO.lon, 800),
@@ -466,6 +466,9 @@ test('layer: camera moveEnd re-culls without a rebuild', async () => {
harness.moveCameraTo(TOKYO.lon, TOKYO.lat);
harness.moveEnd.emit();
const set = harness.icons();
for (let row = 0; row < set.count; row += 1)
assert.equal(set.shown(row), true, `${set.idAt(row)} keeps its row shown; the GPU decides`);
const show = harness.showById();
assert.equal(show.get('firms-1'), true, 'Tokyo becomes visible once the camera is over it');
assert.equal(show.get('firms-0'), false, 'Austin drops behind the limb');
@@ -474,32 +477,34 @@ test('layer: camera moveEnd re-culls without a rebuild', async () => {
}
});
test('layer: the throttled preRender watcher re-culls on a camera move', async () => {
const harness = createHarness([
rawFire(AUSTIN.lat, AUSTIN.lon, 120),
rawFire(TOKYO.lat, TOKYO.lon, 800),
]);
test('layer: a refresh keeps rows and restyles one whose index now holds another fire', async () => {
const fires = [rawFire(AUSTIN.lat, AUSTIN.lon, 400), rawFire(TOKYO.lat, TOKYO.lon, 800)];
const harness = createHarness(fires);
try {
harness.layer.init(harness.viewer);
await harness.layer.enable(harness.viewer);
harness.moveCameraTo(TOKYO.lon, TOKYO.lat);
// The watcher is throttled to LOD_CHECK_MS (650 ms) against
// performance.now(), whose value at this point depends on process
// start-up — so emit, wait out the full throttle window, and emit again.
// Whichever tick passes the gate, one of them must run the pass.
harness.preRender.emit();
await new Promise((resolve) => { setTimeout(resolve, 700); });
harness.preRender.emit();
const set = harness.icons();
const austin = set.row('firms-0');
const handle = set.handleAt(austin);
const drawnPx = (row) => set.width(row) * set.scale(row);
const before = drawnPx(austin);
const beforeImage = set.imageFar(austin);
const show = harness.showById();
assert.equal(show.get('firms-1'), true, 'Tokyo revealed by the preRender pass');
assert.equal(show.get('firms-0'), false, 'Austin culled by the preRender pass');
fires[0] = rawFire(AUSTIN.lat + 0.5, AUSTIN.lon, 1);
await harness.layer.update();
const row = set.row('firms-0');
assert.equal(set.handleAt(row), handle, 'the row (and its pick id) survives the rebuild');
assert.ok(drawnPx(row) < before, `restyled for the weaker fire: ${drawnPx(row)} < ${before}`);
assert.notEqual(set.imageFar(row), beforeImage, 'a red glow becomes a yellow one');
const carto = Cesium.Cartographic.fromCartesian(set.position(row, 0, new Cesium.Cartesian3()));
assert.ok(Math.abs(Cesium.Math.toDegrees(carto.latitude) - (AUSTIN.lat + 0.5)) < 1e-6, 'moved to the new fire');
} finally {
harness.cleanup();
}
});
test('layer: re-enabling after the camera moved does not expose stale far-side sprites', async () => {
test('layer: re-enabling after the camera moved shows the icons, culled from the new camera', async () => {
const harness = createHarness([
rawFire(AUSTIN.lat, AUSTIN.lon, 120),
rawFire(TOKYO.lat, TOKYO.lon, 800),
@@ -516,10 +521,10 @@ test('layer: re-enabling after the camera moved does not expose stale far-side s
await harness.layer.enable(harness.viewer);
// Assert with NO camera event fired and NO refetch (fires are already
// loaded, so enable() does not reload): the enable path itself must have
// re-culled before the collection went visible.
// loaded, so enable() does not reload): the GPU culls from the current
// camera on the first frame.
const show = harness.showById();
assert.equal(harness.billboards().show, true, 'the collection is visible again');
assert.notEqual(harness.primitives[0].show, false, 'the icon set is visible again');
assert.equal(show.get('firms-1'), true, 'the Tokyo fire is revealed at enable time');
assert.equal(show.get('firms-0'), false, 'the Austin fire is NOT left shining through the planet');
} finally {
@@ -527,6 +532,48 @@ test('layer: re-enabling after the camera moved does not expose stale far-side s
}
});
test('layer: a refresh drops rows whose fires left, and an empty one drops them all', async () => {
const fires = [
rawFire(AUSTIN.lat, AUSTIN.lon, 120),
rawFire(AUSTIN.lat + 1, AUSTIN.lon, 300),
rawFire(AUSTIN.lat + 2, AUSTIN.lon, 200),
];
const harness = createHarness(fires);
try {
harness.layer.init(harness.viewer);
await harness.layer.enable(harness.viewer);
const set = harness.icons();
assert.equal(set.count, 3);
// Index 0 still holds a fire; 1 and 2 are gone, so their rows swap out.
fires.splice(1, 2);
await harness.layer.update();
assert.deepEqual(
Array.from({ length: set.count }, (_, row) => set.idAt(row)),
['firms-0'],
);
const kept = Cesium.Cartographic.fromCartesian(set.position(set.row('firms-0'), 0, new Cesium.Cartesian3()));
assert.ok(Math.abs(Cesium.Math.toDegrees(kept.latitude) - AUSTIN.lat) < 1e-6, 'the kept row holds its own fire');
fires.length = 0;
await harness.layer.update();
assert.equal(set.count, 0, 'an empty refresh leaves no sprite behind');
assert.equal(harness.latestEntries().length, 0, 'nor any card');
} finally {
harness.cleanup();
}
});
test('layer: destroy takes the icons out of the scene', async () => {
const harness = createHarness([rawFire(AUSTIN.lat, AUSTIN.lon, 120)]);
harness.layer.init(harness.viewer);
await harness.layer.enable(harness.viewer);
const primitive = harness.primitives[0];
harness.cleanup();
assert.equal(harness.primitives.includes(primitive), false);
assert.equal(primitive.isDestroyed(), true);
});
test('layer: a near-limb fire on a sub-ellipsoid anchor is not culled by its datum', async () => {
const lat = AUSTIN.lat;
const lon = AUSTIN.lon + LIMB_DLON;
@@ -542,14 +589,14 @@ test('layer: a near-limb fire on a sub-ellipsoid anchor is not culled by its dat
harness.layer.init(harness.viewer);
await harness.layer.enable(harness.viewer);
const bb = harness.billboards();
const sunken = bb.get(1);
const carto = Cesium.Cartographic.fromCartesian(sunken.position);
const set = harness.icons();
const sunken = set.row('firms-1');
const carto = Cesium.Cartographic.fromCartesian(set.position(sunken, 0, new Cesium.Cartesian3()));
assert.ok(
Math.abs(carto.height - (-27 + FIRE_ANCHOR_LIFT_M)) < 0.5,
`the sprite still RENDERS at the datum-correct anchor, got ${carto.height}`,
);
assert.equal(sunken.show, true, 'the near-limb fire stays on screen (lifted cull anchor)');
assert.equal(harness.showById().get('firms-1'), true, 'the near-limb fire stays on screen (lifted cull anchor)');
assert.equal(harness.showById().get('firms-0'), true, 'the camera-nadir fire is unaffected');
} finally {
harness.cleanup();
+221 -105
View File
@@ -5,7 +5,11 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer, applyFirmsOverlayPolicy, buildCellCard } from './firmsHeatmap.js';
import {
createFirmsHeatmapLayer,
applyFirmsOverlayPolicy,
buildCellCard,
} from './firmsHeatmap.js';
import { fireDetectionKey } from './firmsLabels.js';
import { registerPickOwner, unregisterPickOwner } from './pickRegistry.js';
import { getSelectedEntityContext } from './contextStore.js';
@@ -15,6 +19,11 @@ import { WORLD_FOCUS_REQUEST_EVENT } from '../worldFocus.js';
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs';
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
import { fakeGlobePort } from '../testSupport/fakeGlobePort.mjs';
import { bindRenderer } from '../render/rendererOf.js';
import { HEAT_REBUILD_MS } from '../layers/firms/policy.js';
const LAYER_SOURCE = readLayerSource(
@@ -36,6 +45,9 @@ function makeFire(overrides = {}) {
};
}
/** A pick of the layer's glow `id`, as the renderer reports one of its icons. */
const glowPick = (id) => ({ glow: id });
/**
* Stand the layer up far enough to drive one click. `cardHit` is what the
* overlay host reports under the click position — the real host only publishes
@@ -43,8 +55,13 @@ function makeFire(overrides = {}) {
* actionable card presents.
*/
function harness({
fires = [makeFire()], picked = null, cardHit = null, cameraPosition = null,
withDataSource = false, feed = null,
fires = [makeFire()],
picked = null,
cardHit = null,
cameraPosition = null,
withDataSource = false,
withGlobe = false,
feed = null,
} = {}) {
const hadWindow = Object.hasOwn(globalThis, 'window');
const priorWindow = globalThis.window;
@@ -60,7 +77,6 @@ function harness({
};
const published = [];
let handler = null;
const layer = createFirmsHeatmapLayer({
...(feed ? { feed } : {}),
id: 'firms-test',
@@ -71,28 +87,57 @@ function harness({
clearSource() {},
hitTest: () => (cardHit ? { sourceId: 'firms', entryId: cardHit } : null),
},
screenSpaceEventHandlerFactory: () => {
handler = { click: null, setInputAction(cb) { this.click = cb; }, destroy() {} };
return handler;
},
});
const draw = fakeDrawPort();
// A glow pick names the layer's own icon set, as the renderer's pick does.
const pick = () =>
picked?.glow
? {
primitive: {},
id: {
set: [...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
)?.spec.id,
id: picked.glow,
},
}
: picked;
const viewer = {
scene: {
pick: () => picked,
pick,
canvas: { clientWidth: 1280, clientHeight: 800 },
camera: cameraPosition ? { positionWC: cameraPosition } : undefined,
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
},
dataSources: { add() {}, remove() {} },
};
// The camera the fade and the bands read, when the test places one.
if (cameraPosition)
viewer.camera = {
positionWC: cameraPosition,
positionCartographic: Cesium.Cartographic.fromCartesian(cameraPosition),
};
// The heatmap drapes through the globe port, for the tests that give one.
const globe = fakeGlobePort();
{
const { unbind, ...ports } = bindFakeCesiumScene(viewer, { draw });
unbind();
bindRenderer(viewer, withGlobe ? { ...ports, globe } : ports);
}
// Without one, the map stack has nowhere to drape imagery.
if (!withGlobe)
layer.attachShellServices({ imageryHost: () => ({ kind: 'none' }) });
const input = fakeInput(viewer);
// The LOD rebuild (and with it the context-registration sweep) is inert
// without a data source, so tests that drive a real refresh need one.
if (withDataSource) layer.init(viewer);
layer._bindInteractionForTest(viewer, fires);
const requests = [];
windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (e) => requests.push(e.detail));
windowTarget.addEventListener(WORLD_FOCUS_REQUEST_EVENT, (e) =>
requests.push(e.detail),
);
return {
layer,
@@ -101,7 +146,13 @@ function harness({
requests,
published,
fires,
click: () => handler.click({ position: { x: 400, y: 300 } }),
globe,
/** The live glow icon set. */
icons: () =>
[...draw.sets.values()].find(
(record) => record.kind === 'icons' && !record.disposed,
),
click: () => input.click({ x: 400, y: 300 }),
cleanup() {
Cesium.SceneTransforms.worldToWindowCoordinates = priorProjection;
if (hadWindow) globalThis.window = priorWindow;
@@ -112,10 +163,19 @@ function harness({
test('fire detection key survives a refetch that renumbers the index', () => {
const fire = makeFire();
assert.equal(fireDetectionKey(fire), fireDetectionKey({ ...fire, index: 999 }));
assert.equal(
fireDetectionKey(fire),
fireDetectionKey({ ...fire, index: 999 }),
);
// Different pass over the same pixel is a different detection.
assert.notEqual(fireDetectionKey(fire), fireDetectionKey({ ...fire, acqMs: fire.acqMs + 1 }));
assert.notEqual(fireDetectionKey(fire), fireDetectionKey({ ...fire, lat: 31.0 }));
assert.notEqual(
fireDetectionKey(fire),
fireDetectionKey({ ...fire, acqMs: fire.acqMs + 1 }),
);
assert.notEqual(
fireDetectionKey(fire),
fireDetectionKey({ ...fire, lat: 31.0 }),
);
assert.match(fireDetectionKey({}), /^firms:x:x:0:x$/);
});
@@ -131,11 +191,20 @@ test('two satellites over the same pixel at the same time stay distinct', () =>
assert.notEqual(fireDetectionKey(base), fireDetectionKey(suomi));
assert.notEqual(fireDetectionKey(twin), fireDetectionKey(suomi));
// Satellite naming variants normalize to one identity, not three.
assert.equal(fireDetectionKey(base), fireDetectionKey(makeFire({ satellite: 'NOAA-20' })));
assert.equal(fireDetectionKey(suomi), fireDetectionKey(makeFire({ satellite: 'Suomi NPP' })));
assert.equal(
fireDetectionKey(base),
fireDetectionKey(makeFire({ satellite: 'NOAA-20' })),
);
assert.equal(
fireDetectionKey(suomi),
fireDetectionKey(makeFire({ satellite: 'Suomi NPP' })),
);
// A record with no satellite falls back to its sensor, not to a shared blank.
const sensorOnly = makeFire({ satellite: '', sensor: 'MODIS' });
assert.notEqual(fireDetectionKey(sensorOnly), fireDetectionKey(makeFire({ satellite: '', sensor: 'VIIRS' })));
assert.notEqual(
fireDetectionKey(sensorOnly),
fireDetectionKey(makeFire({ satellite: '', sensor: 'VIIRS' })),
);
});
test('duplicate-coordinate detections get their own cards and focus targets', () => {
@@ -147,11 +216,21 @@ test('duplicate-coordinate detections get their own cards and focus targets', ()
cardHit: `fire:${fireDetectionKey(n21)}`,
});
try {
const cardIds = h.published.filter((e) => e.id.startsWith('fire:')).map((e) => e.id);
assert.equal(new Set(cardIds).size, 2, 'co-located detections must not collapse to one card');
const cardIds = h.published
.filter((e) => e.id.startsWith('fire:'))
.map((e) => e.id);
assert.equal(
new Set(cardIds).size,
2,
'co-located detections must not collapse to one card',
);
h.click();
assert.equal(h.requests.length, 1);
assert.equal(h.requests[0].id, fireDetectionKey(n21), 'the clicked card wins, not its twin');
assert.equal(
h.requests[0].id,
fireDetectionKey(n21),
'the clicked card wins, not its twin',
);
} finally {
h.cleanup();
}
@@ -162,7 +241,9 @@ test('selection restoration uses the same key the cards and focus use', () => {
// detections from different satellites — the selection could come back on
// the wrong record. Reachable only through the 30-minute refetch, so this is
// a source contract; the key's own behavior is proven above.
const match = LAYER_SOURCE.match(/function findMatchingFire\(previous\) \{([\s\S]*?)\n \}\n/);
const match = LAYER_SOURCE.match(
/function findMatchingFire\(previous\) \{([\s\S]*?)\n \}\n/,
);
assert.ok(match, 'findMatchingFire is missing');
assert.match(match[1], /fireDetectionKey\(previous\)/);
assert.match(match[1], /fireDetectionKey\(fire\) === key/);
@@ -175,7 +256,11 @@ test('painted detection cards are keyed by the stable detection key', () => {
const card = h.published.find((entry) => entry.id.startsWith('fire:'));
assert.ok(card, 'a detection card was painted');
assert.equal(card.id, `fire:${fireDetectionKey(h.fires[0])}`);
assert.equal(card.interactive, true, 'a detection card must publish a hit rect');
assert.equal(
card.interactive,
true,
'a detection card must publish a hit rect',
);
assert.match(card.accessibilityLabel, /^Focus fire detection /);
assert.equal(card.activate(), true);
assert.equal(h.requests.length, 1);
@@ -187,7 +272,16 @@ test('painted detection cards are keyed by the stable detection key', () => {
test('an aggregated cell card is never actionable — it is not one fire', () => {
const cell = buildCellCard(
{ cell: { count: 14, maxFrp: 210, newestAcqMs: 0, latCell: 30, lonCell: -98 }, position: {} },
{
cell: {
count: 14,
maxFrp: 210,
newestAcqMs: 0,
latCell: 30,
lonCell: -98,
},
position: {},
},
Date.now(),
);
assert.equal(applyFirmsOverlayPolicy(cell, 1e6).interactive, false);
@@ -196,10 +290,16 @@ test('an aggregated cell card is never actionable — it is not one fire', () =>
test('far-side detections cannot consume the bounded ambient-card cohort', () => {
const front = makeFire({ index: 1, lat: 30.51, lon: -98.21, frp: 100 });
const rear = makeFire({ index: 2, lat: -30.51, lon: 81.79, frp: 1000 });
const cameraPosition = Cesium.Cartesian3.fromDegrees(front.lon, front.lat, 10_000_000);
const cameraPosition = Cesium.Cartesian3.fromDegrees(
front.lon,
front.lat,
10_000_000,
);
const h = harness({ fires: [rear, front], cameraPosition });
try {
const cardIds = h.published.filter((entry) => entry.id.startsWith('fire:')).map((entry) => entry.id);
const cardIds = h.published
.filter((entry) => entry.id.startsWith('fire:'))
.map((entry) => entry.id);
assert.deepEqual(cardIds, [`fire:${fireDetectionKey(front)}`]);
} finally {
h.cleanup();
@@ -208,7 +308,7 @@ test('far-side detections cannot consume the bounded ambient-card cohort', () =>
test('clicking a fire sprite selects it and requests the camera transfer', () => {
const fire = makeFire();
const h = harness({ fires: [fire], picked: { id: 'firms-7' } });
const h = harness({ fires: [fire], picked: glowPick('firms-7') });
try {
h.click();
assert.equal(h.requests.length, 1);
@@ -220,6 +320,22 @@ test('clicking a fire sprite selects it and requests the camera transfer', () =>
}
});
test('an item named like a fire in another draw set is not a fire', () => {
const h = harness({
fires: [makeFire()],
picked: {
primitive: {},
id: { set: 'other-layer:1:icons', id: 'firms-7' },
},
});
try {
h.click();
assert.equal(h.requests.length, 0);
} finally {
h.cleanup();
}
});
test('clicking a fire CARD behaves exactly like clicking its sprite', () => {
const fire = makeFire();
// The click lands on the card, but the scene pick returns the 3D-Tiles
@@ -242,7 +358,7 @@ test('clicking a fire CARD behaves exactly like clicking its sprite', () => {
// The voice model reads these labels as data (track_entity, get_entity_context,
// pointer_context); the voice card translates them where it shows them.
test('fire labels stay English data in a translated interface', () => {
const h = harness({ fires: [makeFire()], picked: { id: 'firms-7' } });
const h = harness({ fires: [makeFire()], picked: glowPick('firms-7') });
try {
setLocale('ru');
h.click();
@@ -276,7 +392,7 @@ test('a click on neither sprite nor card clears without moving the camera', () =
const SIBLING_PICKS = [
['flights', 'a1b2c3', { id: 'a1b2c3' }],
['flights', 'a1b2c3', { primitive: { id: 'a1b2c3' } }],
['ais-live-vessels', '353136000', { id: { mmsi: '353136000', name: 'EVER GIVEN' } }],
['ais-live-vessels', '353136000', { id: '353136000' }],
['cctv', 'atx-cam-3', { id: { id: 'atx-cam-3', name: 'entity-like' } }],
['satellites', '25544', { id: 25544 }],
];
@@ -292,7 +408,11 @@ for (const [layerId, ownedId, picked] of SIBLING_PICKS) {
});
try {
h.click();
assert.equal(h.requests.length, 0, `the ${layerId} layer is already acting on this click`);
assert.equal(
h.requests.length,
0,
`the ${layerId} layer is already acting on this click`,
);
} finally {
h.cleanup();
unregisterPickOwner(layerId);
@@ -319,7 +439,11 @@ test('a refresh that drops the selected fire emits an eviction the readout can a
// record first and the clear then fails its ownership guard silently.
const kept = makeFire({ index: 0 });
const dropped = makeFire({
index: 1, lat: 31.77, lon: -99.02, acqMs: 1_753_600_100_000, satellite: 'N20',
index: 1,
lat: 31.77,
lon: -99.02,
acqMs: 1_753_600_100_000,
satellite: 'N20',
});
const h = harness({
fires: [dropped, kept],
@@ -327,12 +451,18 @@ test('a refresh that drops the selected fire emits an eviction the readout can a
withDataSource: true,
});
const cleared = [];
h.windowTarget.addEventListener('gev:entity-selection-cleared', (e) => cleared.push(e.detail));
h.windowTarget.addEventListener('gev:entity-selection-cleared', (e) =>
cleared.push(e.detail),
);
const priorFetch = globalThis.fetch;
try {
h.click();
assert.equal(h.requests.length, 1, 'the click must select the fire we are about to drop');
assert.equal(
h.requests.length,
1,
'the click must select the fire we are about to drop',
);
assert.equal(h.requests[0].id, fireDetectionKey(dropped));
assert.deepEqual(cleared, [], 'selecting must not clear anything yet');
@@ -343,18 +473,20 @@ test('a refresh that drops the selected fire emits an eviction the readout can a
json: async () => ({
fetchedAt: Date.now(),
stale: false,
fires: [{
lat: kept.lat,
lon: kept.lon,
frp: kept.frp,
confidence: 'h',
brightness: 330,
daynight: 'D',
acqDate: '2025-07-27',
acqTime: '0412',
instrument: 'VIIRS',
satellite: kept.satellite,
}],
fires: [
{
lat: kept.lat,
lon: kept.lon,
frp: kept.frp,
confidence: 'h',
brightness: 330,
daynight: 'D',
acqDate: '2025-07-27',
acqTime: '0412',
instrument: 'VIIRS',
satellite: kept.satellite,
},
],
}),
});
await h.layer.update();
@@ -379,9 +511,17 @@ test('a refresh that drops the selected fire emits an eviction the readout can a
test('disable cancels a pending source and a late response cannot repopulate the layer', async () => {
let resolve, signal;
const h = harness({ withDataSource: true, feed: { getSnapshot(options) {
signal = options.signal; return new Promise(done => { resolve = done; });
} } });
const h = harness({
withDataSource: true,
feed: {
getSnapshot(options) {
signal = options.signal;
return new Promise((done) => {
resolve = done;
});
},
},
});
try {
const before = h.layer.getStats();
const pending = h.layer.update();
@@ -392,7 +532,10 @@ test('disable cancels a pending source and a late response cannot repopulate the
assert.equal(h.layer.getStats().count, before.count);
assert.equal(h.layer.getStats().lastUpdate, before.lastUpdate);
assert.equal(h.layer.getStats().loading, false);
} finally { h.layer.destroy(h.viewer); h.cleanup(); }
} finally {
h.layer.destroy(h.viewer);
h.cleanup();
}
});
test('the heatmap is preloaded under the markers before the first zoom-out', (t) => {
@@ -401,7 +544,9 @@ test('the heatmap is preloaded under the markers before the first zoom-out', (t)
globalThis.document = {
createElement: () => ({
getContext: () => ({
createImageData: (w, hh) => ({ data: new Uint8ClampedArray(w * hh * 4) }),
createImageData: (w, hh) => ({
data: new Uint8ClampedArray(w * hh * 4),
}),
putImageData() {},
createRadialGradient: () => ({ addColorStop() {} }),
fillRect() {},
@@ -411,27 +556,12 @@ test('the heatmap is preloaded under the markers before the first zoom-out', (t)
};
const h = harness({
withDataSource: true,
withGlobe: true,
cameraPosition: Cesium.Cartesian3.fromDegrees(-98, 30, 1_000_000),
});
h.viewer.camera = { positionCartographic: { height: 1_000_000 } };
h.viewer.scene.primitives = { add() {}, remove() {}, raiseToTop() {}, contains: () => true };
h.viewer.scene.frameState = { mode: Cesium.SceneMode.SCENE3D };
const added = [];
const added = h.globe.added;
try {
h.layer.attachShellServices({
imageryHost: () => ({
kind: 'globe',
collection: {
addImageryProvider: (provider) => {
const layer = { provider, show: true, alpha: 1 };
added.push(layer);
return layer;
},
remove() {},
raiseToTop() {},
},
}),
});
h.layer.attachShellServices({ imageryHost: () => ({ kind: 'globe' }) });
h.layer._renderLodForTest('close');
assert.equal(added.length, 0, 'the markers paint first; the build trails');
t.mock.timers.tick(HEAT_REBUILD_MS);
@@ -469,46 +599,34 @@ test('far zoom drapes one heatmap and the hand-off cross-fades it with the marke
const h = harness({
fires: [makeFire(), makeFire({ index: 8, lat: 30.6, lon: -98.3, frp: 12 })],
withDataSource: true,
withGlobe: true,
cameraPosition: Cesium.Cartesian3.fromDegrees(-98, 30, 12_000_000),
});
const added = [];
const removed = [];
let markers = null;
// The fade reads the camera height; the cull reads scene.camera.
const added = h.globe.added;
// The fade and the bands read the camera height.
const setHeight = (height) => {
h.viewer.camera = { positionCartographic: { height } };
h.viewer.camera.positionCartographic.height = height;
};
setHeight(12_000_000);
h.viewer.scene.primitives = {
add(primitive) {
markers = primitive;
},
remove() {},
raiseToTop() {},
contains: () => true,
};
h.viewer.scene.frameState = { mode: Cesium.SceneMode.SCENE3D };
const markers = () => h.icons();
const glow = (i) => [...markers().items.values()][i];
try {
const collection = {
addImageryProvider: (provider) => {
const layer = { provider, show: true, alpha: 1 };
added.push(layer);
return layer;
},
remove: (layer, destroy) => removed.push({ layer, destroy }),
raiseToTop() {},
};
h.layer.attachShellServices({
imageryHost: () => ({ kind: 'globe', collection }),
});
h.layer.attachShellServices({ imageryHost: () => ({ kind: 'globe' }) });
h.layer._renderLodForTest('global');
assert.equal(added.length, 1, 'one heat imagery layer');
assert.equal(added[0].show, true);
assert.equal(added[0].alpha, 1);
assert.equal(h.layer._entityCountForTest(), 0, 'no rectangle entities');
assert.ok(h.published.length > 0, 'the far band still paints cards');
assert.equal(markers.length, 2, 'the markers are built under the heatmap');
assert.equal(markers.show, false, 'and hidden while the heatmap is whole');
assert.equal(
markers().items.size,
2,
'the markers are built under the heatmap',
);
assert.equal(
markers().show,
false,
'and hidden while the heatmap is whole',
);
h.layer._renderLodForTest('regional');
assert.equal(added.length, 1, 'switching far bands reuses the raster');
@@ -518,27 +636,25 @@ test('far zoom drapes one heatmap and the hand-off cross-fades it with the marke
assert.equal(added.length, 1, 'the markers band keeps the same heat layer');
assert.equal(added[0].show, true, 'still mapped onto the globe tiles');
assert.equal(added[0].alpha, 0, 'faded out under the markers');
assert.equal(markers.show, true);
assert.equal(markers.get(0).color.alpha, 1);
assert.equal(markers().show, true);
assert.equal(glow(0).alpha, 1);
// Mid hand-off both are drawn, half each, in either band.
setHeight(4_500_000);
h.layer._applyHandoffFadeForTest();
assert.equal(added[0].alpha, 0.5);
assert.equal(markers.show, true);
assert.equal(markers.get(0).color.alpha, 0.5);
assert.equal(markers().show, true);
assert.equal(glow(0).alpha, 0.5);
h.layer._renderLodForTest('regional');
assert.equal(added[0].alpha, 0.5);
assert.equal(markers.get(1).color.alpha, 0.5, 'rebuilt markers get the fade');
assert.equal(glow(1).alpha, 0.5, 'rebuilt markers get the fade');
h.layer.disable();
assert.equal(added[0].show, false, 'disable hides the heatmap');
h.layer.destroy(h.viewer);
assert.deepEqual(
removed.map((entry) => [entry.layer, entry.destroy]),
[[added[0], true]],
);
assert.equal(added[0].removed, true);
assert.equal(h.globe.imagery.list().length, 0);
} finally {
h.cleanup();
restoreDocument();
+310
View File
@@ -0,0 +1,310 @@
/**
* @module data/fixCurve
* @description The path an aircraft is drawn along between two of its
* reports, and the trail drawn behind it: a smooth curve that passes through
* both reports and leaves each one along its reported track.
*
* The curve is a biarc: two constant-rate turns, each a renderer `arc`
* motion segment (`render/contract/draw.d.ts`), joined where they share a
* course. So the renderer draws exactly this curve, the app reads it back with
* `render/motion/iconMotion`, and the trail samples the same segments: the
* icon always sits on its own trail. Speed is constant between the two
* reports, height changes evenly with time.
*
* The straight line between the reports is drawn instead (no curve) when
* either report has no track, the pair is slower than 40 m/s (taxiing,
* hovering, holding still), or a track points more than 75° off the line
* between them: the reports do not describe one smooth turn.
*
* Each segment runs on for two seconds past its end along the same turn, so
* when the next segment comes a little late the renderer keeps the icon moving
* instead of holding it.
*/
import { eastNorthUp } from '../geo/frames.js';
import { motionCourse, motionPosition } from '../render/motion/iconMotion.js';
import { norm180, norm360 } from '../geo/vector.js';
/** @constant {number} Pairs slower than this (m/s) are joined straight. */
export const CURVE_MIN_SPEED_MPS = 40;
/** @constant {number} A track further than this (°) off the chord is joined straight. */
export const CURVE_MAX_TRACK_OFF_DEG = 75;
/** @constant {number} How long (s) a segment runs on past its end. */
export const CURVE_RUN_ON_S = 2;
/** @constant {number} Turn (°) between points a trail samples along a curve. */
export const CURVE_POINT_STEP_DEG = 1;
const DEG = Math.PI / 180;
/** Turn rates under this (rad/s) fly straight, as `iconMotion` draws them. */
const STRAIGHT_BELOW_RAD_PER_S = 1e-4;
function sinc(x) {
return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x;
}
const dot3 = (a, b) => a.x * b.x + a.y * b.y + a.z * b.z;
const sub3 = (a, b) => ({ x: a.x - b.x, y: a.y - b.y, z: a.z - b.z });
/** A course (degrees) at `from`'s frame, read in `to`'s frame. */
function courseIn(courseDeg, fromFrame, toFrame) {
const s = Math.sin(courseDeg * DEG);
const c = Math.cos(courseDeg * DEG);
const t = {
x: s * fromFrame.x.x + c * fromFrame.y.x,
y: s * fromFrame.x.y + c * fromFrame.y.y,
z: s * fromFrame.x.z + c * fromFrame.y.z,
};
return Math.atan2(dot3(t, toFrame.x), dot3(t, toFrame.y)) / DEG;
}
/**
* A constant-rate turn from `from` at `t0` setting off on `courseDeg`, that
* reaches `to` at `t1` (epoch ms): an `arc` segment, straight when the turn
* is too slow to draw as one.
* @returns {{segment: object, endCourseDeg: number}}
*/
function arcThrough(from, frame, t0, t1, courseDeg, to) {
const d = sub3(to, from);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const seconds = (t1 - t0) / 1000;
const chord = Math.hypot(e, n);
const bearing = Math.atan2(e, n) / DEG;
let turn = 2 * norm180(bearing - courseDeg);
let track = courseDeg;
if (Math.abs((turn * DEG) / seconds) < STRAIGHT_BELOW_RAD_PER_S) {
turn = 0;
track = bearing;
}
const length = chord / sinc((turn * DEG) / 2);
return {
segment: {
kind: 'arc',
fix: { x: from.x, y: from.y, z: from.z },
t0,
minDtS: 0,
maxDtS: seconds + CURVE_RUN_ON_S,
speedMps: length / seconds,
trackDeg: norm360(track),
turnRateDps: turn / seconds,
climbMps: u / seconds,
},
endCourseDeg: track + turn,
};
}
/**
* A straight `arc` segment from `from` at `t0` that reaches `to` at `t1`
* (epoch ms) and runs on past it for CURVE_RUN_ON_S.
*/
export function straightSegment(from, t0, t1, to) {
const frame = eastNorthUp(from);
const d = sub3(to, from);
const bearing = Math.atan2(dot3(d, frame.x), dot3(d, frame.y)) / DEG;
return arcThrough(from, frame, t0, t1, bearing, to).segment;
}
/**
* The curve between two reports, or null to join them straight.
* @param {{x: number, y: number, z: number}} fromPos The earlier report (ECEF).
* @param {number} fromMs Its time, epoch ms.
* @param {number} fromTrackDeg Its reported track.
* @param {{x: number, y: number, z: number}} toPos The later report.
* @param {number} toMs
* @param {number} toTrackDeg
* @returns {{pieces: Array<{segment: object, t0: number, t1: number}>}|null}
* One or two pieces in time order, together running from `fromMs` to
* `toMs`; each `segment` is a contract `arc` motion segment.
*/
export function fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!Number.isFinite(fromTrackDeg) || !Number.isFinite(toTrackDeg))
return null;
if (!(toMs > fromMs) || !fromPos || !toPos) return null;
const seconds = (toMs - fromMs) / 1000;
const frame = eastNorthUp(fromPos);
const d = sub3(toPos, fromPos);
const e = dot3(d, frame.x);
const n = dot3(d, frame.y);
const u = dot3(d, frame.z);
const chord = Math.hypot(e, n);
if (!(chord / seconds >= CURVE_MIN_SPEED_MPS)) return null;
const toFrame = eastNorthUp(toPos);
const startDeg = fromTrackDeg;
// The later report's track, read in the earlier report's frame.
const endDeg = courseIn(toTrackDeg, toFrame, frame);
const bearing = Math.atan2(e, n) / DEG;
if (
Math.abs(norm180(startDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG ||
Math.abs(norm180(endDeg - bearing)) > CURVE_MAX_TRACK_OFF_DEG
)
return null;
// The biarc's join with equal tangent lengths: p0 = 0, p1 = (e, n),
// unit tangents t0 and t1.
const t0x = Math.sin(startDeg * DEG);
const t0y = Math.cos(startDeg * DEG);
const t1x = Math.sin(endDeg * DEG);
const t1y = Math.cos(endDeg * DEG);
const vv = e * e + n * n;
const vt = e * (t0x + t1x) + n * (t0y + t1y);
const tt = t0x * t1x + t0y * t1y;
const denom = 2 * (1 - tt);
const reach =
denom < 1e-9
? vv / (4 * (e * t1x + n * t1y))
: (-vt + Math.sqrt(vt * vt + denom * vv)) / denom;
if (!(reach > 0) || !Number.isFinite(reach)) return null;
const jx = (reach * t0x + e - reach * t1x) / 2;
const jy = (reach * t0y + n - reach * t1y) / 2;
// Each arc's length from its chord and turn, to share the time by.
const arcLength = (cx, cy, courseDeg) => {
const c = Math.hypot(cx, cy);
const turn = 2 * norm180(Math.atan2(cx, cy) / DEG - courseDeg);
return { length: c / sinc((turn * DEG) / 2), turn };
};
const first = arcLength(jx, jy, startDeg);
const second = arcLength(e - jx, n - jy, startDeg + first.turn);
const total = first.length + second.length;
if (!(total > 0)) return null;
// One arc where a piece would be under a metre.
if (first.length < 1 || second.length < 1) {
const only = arcThrough(fromPos, frame, fromMs, toMs, startDeg, toPos);
return { pieces: [{ segment: only.segment, t0: fromMs, t1: toMs }] };
}
const joinMs = fromMs + (toMs - fromMs) * (first.length / total);
const share = first.length / total;
const join = {
x: fromPos.x + frame.x.x * jx + frame.y.x * jy + frame.z.x * u * share,
y: fromPos.y + frame.x.y * jx + frame.y.y * jy + frame.z.y * u * share,
z: fromPos.z + frame.x.z * jx + frame.y.z * jy + frame.z.z * u * share,
};
const a = arcThrough(fromPos, frame, fromMs, joinMs, startDeg, join);
// The second arc starts exactly where the first is drawn to end.
const joined = motionPosition(a.segment, null, joinMs);
const joinFrame = eastNorthUp(joined);
const b = arcThrough(
joined,
joinFrame,
joinMs,
toMs,
courseIn(a.endCourseDeg, frame, joinFrame),
toPos,
);
return {
pieces: [
{ segment: a.segment, t0: fromMs, t1: joinMs },
{ segment: b.segment, t0: joinMs, t1: toMs },
],
};
}
const cache = new WeakMap();
/**
* `fixCurve` for two report objects that keep their position object, kept
* per earlier report's position until either report changes.
*/
export function fixCurveCached(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
) {
if (!fromPos || typeof fromPos !== 'object') return null;
const hit = cache.get(fromPos);
if (
hit &&
hit.toPos === toPos &&
hit.fromMs === fromMs &&
hit.toMs === toMs &&
hit.fromTrackDeg === fromTrackDeg &&
hit.toTrackDeg === toTrackDeg &&
hit.fx === fromPos.x &&
hit.fy === fromPos.y &&
hit.fz === fromPos.z &&
hit.tx === toPos.x &&
hit.ty === toPos.y &&
hit.tz === toPos.z
)
return hit.curve;
const curve = fixCurve(
fromPos,
fromMs,
fromTrackDeg,
toPos,
toMs,
toTrackDeg,
);
cache.set(fromPos, {
toPos,
fromMs,
toMs,
fromTrackDeg,
toTrackDeg,
fx: fromPos.x,
fy: fromPos.y,
fz: fromPos.z,
tx: toPos?.x,
ty: toPos?.y,
tz: toPos?.z,
curve,
});
return curve;
}
/** The piece of `curve` drawn at `tMs` (the last one past its end). */
export function curvePieceAt(curve, tMs) {
const pieces = curve.pieces;
for (let i = 0; i < pieces.length - 1; i++)
if (tMs < pieces[i].t1) return pieces[i];
return pieces[pieces.length - 1];
}
/** Where the curve puts the aircraft at `tMs`, and its course. */
export function curvePositionAt(curve, tMs) {
const piece = curvePieceAt(curve, tMs);
const t = Math.min(tMs, piece.t1);
return {
position: motionPosition(piece.segment, null, t),
courseDeg: motionCourse(piece.segment, undefined, t),
};
}
/**
* Points along the curve from `fromMs` to `toMs` (exclusive of both ends),
* one at least every CURVE_POINT_STEP_DEG of turn, so the line drawn
* through them stays within a couple of metres of the curve.
* @returns {Array<{x: number, y: number, z: number}>}
*/
export function curvePoints(curve, fromMs, toMs) {
const out = [];
for (const piece of curve.pieces) {
const start = Math.max(fromMs, piece.t0);
const end = Math.min(toMs, piece.t1);
if (!(end > start)) continue;
const seconds = (end - start) / 1000;
const turned = Math.abs(piece.segment.turnRateDps * seconds);
const steps = Math.max(1, Math.ceil(turned / CURVE_POINT_STEP_DEG));
// The piece's start, unless it is the curve's own start.
if (start > fromMs) out.push(motionPosition(piece.segment, null, start));
for (let k = 1; k < steps; k++)
out.push(
motionPosition(
piece.segment,
null,
start + ((end - start) * k) / steps,
),
);
}
return out;
}
+141
View File
@@ -0,0 +1,141 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
CURVE_RUN_ON_S,
curvePieceAt,
curvePoints,
curvePositionAt,
fixCurve,
straightSegment,
} from './fixCurve.js';
import { motionPosition } from '../render/motion/iconMotion.js';
// Between two reports an aircraft is drawn along a curve through both that
// leaves each along its reported track, made of contract `arc` segments.
const SEC = 1000;
const T0 = Date.UTC(2026, 10, 9, 12);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(
Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 0),
);
const at = (e, n, u = 3_000) =>
Cesium.Matrix4.multiplyByPoint(
enu,
new Cesium.Cartesian3(e, n, u),
new Cesium.Cartesian3(),
);
const near = (a, b, m, label) => {
const d = Cesium.Cartesian3.distance(a, b);
assert.ok(d < m, `${label}: ${d.toFixed(2)} m`);
};
const angleDiff = (a, b) => Math.abs(((a - b + 540) % 360) - 180);
// A 100 m/s left turn on a 2 km circle centred at (0, R), heading east at
// the origin.
const R = 2_000;
const W = 100 / R;
const circle = (t) => at(R * Math.sin(W * t), R - R * Math.cos(W * t));
const trackAt = (t) => (90 - (W * t * 180) / Math.PI + 360) % 360;
test('the curve passes through both reports and leaves each along its track', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
assert.ok(curve);
near(curvePositionAt(curve, T0).position, circle(0), 0.01, 'start');
near(curvePositionAt(curve, T0 + 15 * SEC).position, circle(15), 0.01, 'end');
assert.ok(angleDiff(curvePositionAt(curve, T0).courseDeg, trackAt(0)) < 0.1);
assert.ok(
angleDiff(curvePositionAt(curve, T0 + 15 * SEC).courseDeg, trackAt(15)) <
0.1,
);
// A true turn: the curve is the turn, within a couple of metres.
for (let s = 0; s <= 15; s += 0.5)
near(curvePositionAt(curve, T0 + s * SEC).position, circle(s), 3, `${s} s`);
});
test('its pieces are contiguous arc segments in time order', () => {
// Tracks that need an S: the first turn and the second do not agree.
const curve = fixCurve(at(0, 0), T0, 45, at(3_000, 0), T0 + 30 * SEC, 45);
assert.ok(curve);
assert.equal(curve.pieces.length, 2);
assert.equal(curve.pieces[0].t0, T0);
assert.equal(curve.pieces.at(-1).t1, T0 + 30 * SEC);
for (const piece of curve.pieces) assert.equal(piece.segment.kind, 'arc');
const [a, b] = curve.pieces;
assert.equal(a.t1, b.t0);
near(
motionPosition(a.segment, null, a.t1),
motionPosition(b.segment, null, b.t0),
0.01,
'join',
);
assert.equal(curvePieceAt(curve, a.t1 - 1), a);
assert.equal(curvePieceAt(curve, a.t1), b);
assert.equal(curvePieceAt(curve, T0 + 60 * SEC), b);
});
test('each segment runs on past its end rather than holding', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const last = curve.pieces.at(-1);
const end = motionPosition(last.segment, null, last.t1);
const later = motionPosition(
last.segment,
null,
last.t1 + CURVE_RUN_ON_S * SEC,
);
near(later, circle(15 + CURVE_RUN_ON_S), 3, 'run on');
assert.ok(Cesium.Cartesian3.distance(end, later) > 150);
});
test('no curve without tracks, below 40 m/s, or with a track far off the line', () => {
const a = at(0, 0);
const b = at(1_500, 0);
assert.equal(fixCurve(a, T0, undefined, b, T0 + 15 * SEC, 90), null);
assert.equal(fixCurve(a, T0, 90, b, T0 + 60 * SEC, 90), null, 'slow');
assert.equal(fixCurve(a, T0, 180, b, T0 + 15 * SEC, 90), null, 'off line');
assert.equal(fixCurve(a, T0, 90, b, T0, 90), null, 'no time between');
});
test('trail points follow the curve, exclusive of both ends, a degree of turn apart', () => {
const curve = fixCurve(
circle(0),
T0,
trackAt(0),
circle(15),
T0 + 15 * SEC,
trackAt(15),
);
const points = curvePoints(curve, T0, T0 + 15 * SEC);
// 15 s at 2.86°/s: about 43° of turn.
assert.ok(points.length >= 42 && points.length <= 46, `${points.length}`);
for (const p of points)
assert.ok(
Math.abs(Cesium.Cartesian3.distance(p, at(0, R)) - R) < 3,
'off the turn',
);
assert.ok(Cesium.Cartesian3.distance(points[0], circle(0)) > 1);
assert.ok(Cesium.Cartesian3.distance(points.at(-1), circle(15)) > 1);
});
test('a straight segment reaches its end at its time and runs on along the same line', () => {
const a = at(0, 0);
const b = at(1_000, 0);
const segment = straightSegment(a, T0, T0 + 10 * SEC, b);
near(motionPosition(segment, null, T0), a, 0.01, 'start');
near(motionPosition(segment, null, T0 + 5 * SEC), at(500, 0), 1, 'middle');
near(motionPosition(segment, null, T0 + 10 * SEC), b, 0.01, 'end');
});
+451
View File
@@ -0,0 +1,451 @@
import { selectModelEligible } from './modelEligibility.js';
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
import { findCamera, findDraw } from '../render/rendererOf.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { horizonFrom } from '../geo/horizon.js';
import {
distanceSquared,
dot,
RADIANS_PER_DEGREE,
sub,
} from '../geo/vector.js';
/**
* Models of the procedural fleet set (`fleetModels.js`) drawn through the
* renderer's draw port, and the icon-to-model handoff the Vessels, Transit
* and Rail layers share.
*/
/** Every fleet GLB is nose -X: opposite the draw contract's heading 0. */
export const FLEET_HEADING_OFFSET_DEG = 180;
/** How long (ms) a model whose load failed waits before it loads again. */
const RETRY_MS = 5000;
/** A white tint: what a model under the NVG/FLIR styles draws with. */
const WHITE = Object.freeze([1, 1, 1, 1]);
/**
* A colour as the draw contract takes it: a CSS string or `[r, g, b, a]`
* as given, `{red, green, blue, alpha}` as an array; null for none.
*/
export function fleetColor(color) {
if (color === undefined || color === null) return null;
if (typeof color === 'string' || Array.isArray(color)) return color;
if (typeof color.red === 'number')
return [color.red, color.green, color.blue, color.alpha ?? 1];
return null;
}
/**
* The per-axis stretch a fleet spec draws with on top of its length scale,
* along the model's glTF axes (`x` its length, `y` its height, `z` its
* beam), or undefined when it keeps its proportions.
* @param {object} spec `fleetModelSpec`.
* @returns {[number, number, number]|undefined}
*/
export function fleetAxisScale(spec) {
const [length, beam, height] = spec?.scaleXYZ ?? [];
if (!(length > 0) || (beam === length && height === length)) return;
return [1, height / length, beam / length];
}
/**
* Whether `point` is inside the eye's view cone (`pose`), a metre's slack.
* @param {object} pose The camera port's pose.
* @param {{x:number,y:number,z:number}} point
* @returns {boolean}
*/
function inView(pose, point) {
const v = sub(point, pose.position);
const depth = dot(v, pose.direction);
if (depth < -1) return false;
const tanY = Math.tan(pose.fovy / 2);
const tanX = tanY * pose.aspectRatio;
return (
Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 &&
Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1
);
}
/** Two colours as `fleetColor` gives them, alike (arrays element by element). */
function sameColor(a, b) {
if (a === b) return true;
if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length)
return false;
for (let i = 0; i < a.length; i++) if (a[i] !== b[i]) return false;
return true;
}
let instances = 0;
/**
* 3D models for one layer's vehicles under the DISPLAY rail's 3D toggle (the
* Flights layer's `models3d`/`models3dMode`), on the same rules the aircraft
* layers follow: models only below the camera altitude ceiling, for the
* nearest `cap` vehicles in the add/keep band, on-screen first. A vehicle's
* icon stays the visual until its model is loaded and placed; the layer reads
* `modelOwnsVisual` back from each item and hides that icon.
*
* The models are one `models` set of the viewer's draw port, built from the
* fleet set's bytes loaded up front (`gltf`), so none is fetched
* mid-session. Without a draw port that draws models the layer stays icons.
*
* Each frame the layer passes its vehicles as items:
* `{position, headingDeg, spec, tint, pickId, show, groundLiftM}`,
* `position` the ECEF point the model's origin stands on (the waterline,
* the road or rail top; the spec's `elevationM` is added here),
* `groundLiftM` any lift the layer's icon carries above that point (taken
* off again), `tint` the route colour a tinted model paints where its
* `_TINT` attribute marks it (a CSS colour or `[r, g, b, a]`, or null),
* `pickId` what a pick on the model hands back (the item's `meta`), `show`
* false to keep it hidden.
*
* Under the luminance-mapped NVG/FLIR styles (`irBoost`) models draw unlit
* flat white, as aircraft models do. With `waterline`, each model is clipped
* at its origin's horizontal plane and only the part above it is drawn: a
* ship's hull below the waterline would otherwise show through a plain
* globe, which models are not depth-tested against.
* @param {object} options
* @param {object} options.viewer The scene host.
* @param {() => object|null} [options.display] `{models3d, models3dMode,
* irBoost}`.
* @param {object} options.policy `{altitudeCeilingM, cap, capAll, addM,
* keepM, intervalMs}`: both 3D modes share the add/keep radii and differ
* by their caps. Models are drawn at their true size.
* @param {(url: string) => string} [options.resolveAsset]
* @param {boolean} [options.waterline] Clip each model at its waterline.
* @param {(item: object, table: object) => object|undefined} [options.partState]
* The moving parts a vehicle's model is posed with (`ModelItem.parts`),
* from its item and its model's part table (`modelPartDrivers.js`); asked
* only for a model that has a part table.
* @param {object} [options.draw] Stands in for the viewer's draw port (tests).
* @returns {object}
*/
export function createFleetModelLayer({
viewer,
display = () => null,
policy,
waterline = false,
resolveAsset = (url) => url,
partState = null,
draw,
}) {
const port = draw ?? findDraw(viewer);
const set =
typeof port?.models === 'function'
? port.models({ id: `fleet-models:${++instances}` })
: null;
/** @type {Map<string, object>} id -> admitted model */
const models = new Map();
let destroyed = false;
let lastEligibilityAt = -Infinity;
let eligible = new Set();
let settling = 0;
const offs = set
? [
set.on('ready', (id) => {
const record = models.get(id);
if (!record) return;
record.ready = true;
record.failedAt = 0;
}),
set.on('loadFailed', (id) => {
const record = models.get(id);
if (record) record.failedAt = Date.now();
}),
]
: [];
function release(id) {
if (!models.delete(id)) return;
set?.remove([id]);
}
function releaseAll() {
if (models.size) set?.clear();
models.clear();
}
function preferences() {
return display?.() || null;
}
function pose() {
try {
return findCamera(viewer)?.pose() ?? null;
} catch {
return null;
}
}
function regime(prefs, eye = pose()) {
if (!set || !prefs?.models3d || !fleetModelSet()) return false;
const height = eye?.height ?? Infinity;
return height < policy.altitudeCeilingM;
}
function admit(id, item, cap) {
const fleet = fleetModelSet();
const gltf = fleet?.bytes?.get(item.spec.model);
// A model whose GLB did not load draws nothing: the icon stays.
if (!gltf) return;
const current = models.get(id);
if (current && current.specKey === item.spec.key) return;
if (current) release(id);
if (models.size >= cap) return;
models.set(id, {
specKey: item.spec.key,
url: resolveAsset(item.spec.url),
gltf,
ready: false,
failedAt: 0,
sent: null,
});
}
function refreshEligibility(items, prefs, eye) {
const all = prefs.models3dMode === 'all';
const cap = all ? policy.capAll : policy.cap;
const { addM, keepM } = policy;
const candidates = [];
for (const [id, item] of items) {
if (!item.position || item.show === false || !item.spec?.url) continue;
const distanceSq = distanceSquared(eye.position, item.position);
if (distanceSq > keepM * keepM) continue;
candidates.push([id, distanceSq, inView(eye, item.position)]);
}
candidates.sort((a, b) => a[1] - b[1]);
eligible = selectModelEligible(candidates, {
cap,
addDistSq: addM * addM,
isModeled: (id) => models.has(id),
});
for (const id of [...models.keys()]) if (!eligible.has(id)) release(id);
for (const id of eligible) admit(id, items.get(id), cap);
}
/** Where the model's origin stands: the item's point raised by the spec's elevation. */
function placement(item) {
const lift = (item.spec.elevationM || 0) - (item.groundLiftM || 0);
if (!lift) return item.position;
const at = toLonLatH(item.position);
if (!at) return item.position;
return fromDegrees(at.lon, at.lat, at.height + lift);
}
/** The part state an item's model is posed with, or undefined. */
function partsOf(item) {
if (!partState) return undefined;
const table = fleetPartTable(fleetModelSet(), item.spec?.model);
return table ? partState(item, table) : undefined;
}
/** The draw item for an admitted model, as the set draws it, at `at`. */
function itemOf(id, record, item, show, boost, at, parts) {
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
return {
id,
pos: { x: at.x, y: at.y, z: at.z },
url: record.url,
gltf: record.gltf,
orientation: {
heading:
((item.headingDeg || 0) + FLEET_HEADING_OFFSET_DEG) *
RADIANS_PER_DEGREE,
pitch: 0,
roll: 0,
},
scale: item.spec.scale,
...(fleetAxisScale(item.spec)
? { axisScale: fleetAxisScale(item.spec) }
: {}),
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
...(boost
? {
shading: 'unlit',
tint: WHITE,
colorBlend: { mode: 'mix', amount: 1 },
}
: { shading: 'pbr' }),
...(mask ? { maskColor: mask } : {}),
...(waterline ? { clip: 'belowOrigin' } : {}),
...(parts ? { parts } : {}),
meta: item.pickId ?? id,
show,
};
}
/**
* The item to write for a record, or null when nothing it draws changed:
* what it was last written with is compared value by value, and the item
* is built only when something did (a fleet passes every model each
* frame, and most of what it draws stays).
*/
function changed(id, record, item, show, boost) {
const at = placement(item);
const heading = item.headingDeg || 0;
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
const meta = item.pickId ?? id;
const parts = partsOf(item);
const partsKey = parts ? JSON.stringify(parts) : '';
const sent = record.sent;
if (
sent !== null &&
sent.x === at.x &&
sent.y === at.y &&
sent.z === at.z &&
sent.heading === heading &&
sent.specKey === item.spec.key &&
sameColor(sent.mask, mask) &&
sent.boost === boost &&
sent.show === show &&
sent.meta === meta &&
sent.partsKey === partsKey
)
return null;
const next = (record.sent ??= {});
next.x = at.x;
next.y = at.y;
next.z = at.z;
next.heading = heading;
next.specKey = item.spec.key;
// A colour array is kept as a copy: the layer may change its own.
next.mask = Array.isArray(mask) ? [...mask] : mask;
next.boost = boost;
next.show = show;
next.meta = meta;
next.partsKey = partsKey;
return itemOf(id, record, item, show, boost, at, parts);
}
return {
/** Ids whose model admission is current. */
get eligible() {
return eligible;
},
/**
* Per-frame pass: re-derive eligibility at the policy's cadence, then
* place every admitted model and hand each item's visual to its model
* only once the model is ready and placed (`item.modelOwnsVisual`).
* @param {Map<string, object>} items
* @param {number} nowMs
* @returns {boolean} Whether any model is drawn.
*/
frame(items, nowMs) {
if (destroyed) return false;
const prefs = preferences();
const eye = pose();
if (!eye || !regime(prefs, eye)) {
settling = 0;
if (models.size) releaseAll();
eligible = new Set();
for (const item of items.values()) item.modelOwnsVisual = false;
return false;
}
const boost = prefs.irBoost === true;
if (nowMs - lastEligibilityAt >= policy.intervalMs) {
lastEligibilityAt = nowMs;
refreshEligibility(items, prefs, eye);
}
for (const item of items.values()) item.modelOwnsVisual = false;
const horizon = horizonFrom(eye.position);
const writes = [];
let drawn = false;
settling = 0;
for (const [id, record] of models) {
const item = items.get(id);
if (!item) {
release(id);
continue;
}
if (item.spec?.key !== record.specKey) {
// A new type or size: the next eligibility pass admits it.
lastEligibilityAt = -Infinity;
release(id);
continue;
}
if (record.failedAt && Date.now() - record.failedAt >= RETRY_MS) {
// Removed and added again, the set loads it again.
record.failedAt = 0;
record.sent = null;
record.ready = false;
set.remove([id]);
}
const visible =
!!item.position &&
item.show !== false &&
horizon.isPointVisible(item.position);
if (!visible) {
if (record.sent !== null) {
const write = changed(id, record, item, false, boost);
if (write) writes.push(write);
}
continue;
}
// Placed before the readiness test: its first drawn frame is here.
const show = record.ready;
const write = changed(id, record, item, show, boost);
if (write) writes.push(write);
if (!show) {
if (!record.failedAt) settling += 1;
continue;
}
item.modelOwnsVisual = true;
drawn = true;
}
if (writes.length) set.upsert(writes);
return drawn;
},
/**
* Models loading or not yet ready after the last frame: the layer keeps
* frames coming while any are, so each one takes over as soon as it can.
*/
get settling() {
return settling;
},
/**
* Whether models are drawn now: 3D on, the set loaded and the camera
* below the altitude ceiling. A layer skips building items while not.
* @returns {boolean}
*/
active() {
return !destroyed && regime(preferences());
},
/** The record of the model drawing `id`, if one is admitted. */
modelFor(id) {
return models.get(id) || null;
},
/** Show or hide every model (the layer's own visibility). */
setVisible(show) {
if (set) set.show = show;
},
/** Drop every model (3D off, layer disabled). */
clear: releaseAll,
/** Number of admitted models (tests and diagnostics). */
get size() {
return models.size;
},
/** The draw set's id, for picks and height queries to name it. */
get setId() {
return set?.id ?? null;
},
destroy() {
if (destroyed) return;
destroyed = true;
releaseAll();
for (const off of offs) off();
set?.dispose();
},
};
}
+502
View File
@@ -0,0 +1,502 @@
// The icon-to-model handoff the Vessels, Transit and Rail layers share
// (fleetModelInstances.js): models only under the DISPLAY 3D toggle and the
// altitude ceiling, at most `cap` of the nearest, each vehicle's icon the
// visual until its model is loaded, ready and placed, drawn through the
// renderer's model sets from the bytes loaded up front, and a tinted model
// painted with its route colour.
import test from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import {
createFleetModelLayer,
fleetAxisScale,
fleetColor,
FLEET_HEADING_OFFSET_DEG,
} from './fleetModelInstances.js';
import {
loadFleetModelSet,
transitModelSpec,
vesselModelSpec,
} from './fleetModels.js';
import { fetchPublicFile } from '../testSupport/fleetGlb.mjs';
import { FLEET_MODEL_POLICY } from '../layers/flights/policy.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { eastNorthUp } from '../geo/frames.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { add, distance, scale } from '../geo/vector.js';
const realInfo = console.info;
console.info = () => {};
const set = await loadFleetModelSet({ fetchImpl: fetchPublicFile });
console.info = realInfo;
// The layers' own policy (3 km add, about 3.6 km keep), with small caps.
const POLICY = Object.freeze({
...FLEET_MODEL_POLICY,
cap: 2,
capAll: 4,
intervalMs: 80,
});
const CENTRE = fromDegrees(-122.4, 37.8, 0);
/** A scene host with a fake draw port and a camera `height` m above CENTRE, looking down. */
function fakeViewer(height = 1_000) {
const viewer = {};
const position = fromDegrees(-122.4, 37.8, height);
const enu = eastNorthUp(position);
const { draw } = bindFakeDraw(viewer, {
camera: {
pose: () => ({
lon: -122.4,
lat: 37.8,
height,
position,
direction: scale(enu.z, -1),
up: enu.y,
right: enu.x,
fovy: Math.PI / 3,
aspectRatio: 1.5,
}),
},
});
return { viewer, draw };
}
/** A vehicle `metres` east of the camera's foot. */
function itemAt(metres, spec, extra = {}) {
const position = add(CENTRE, scale(eastNorthUp(CENTRE).x, metres));
return { position, headingDeg: 90, spec, tint: null, pickId: null, ...extra };
}
/** The layer's model set in the fake draw port. */
const modelSet = (draw) => draw.find('fleet-models:');
test('models are drawn from the up-front set, never fetched by URL', () => {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
resolveAsset: (url) => `/base${url}`,
});
const spec = vesselModelSpec(set, { type: '70', length: 200, beam: 32 });
layer.frame(new Map([['s', itemAt(10, spec, { pickId: 's' })]]), 0);
const item = modelSet(draw).items.get('s');
assert.ok(item.gltf instanceof Uint8Array, 'the loaded GLB bytes');
assert.equal(item.gltf, set.bytes.get(spec.model));
assert.equal(item.url, `/base${spec.url}`, 'the url names it');
assert.equal(item.environmentMap, false);
layer.destroy();
});
test('the icon stays the visual until the model is ready; only the nearest are drawn', () => {
const { viewer, draw } = fakeViewer();
const display = { models3d: true, models3dMode: 'proximity' };
const layer = createFleetModelLayer({
viewer,
display: () => display,
policy: POLICY,
});
const spec = transitModelSpec(set, { mode: 'tram' });
const items = new Map([
['near', itemAt(100, spec, { pickId: 'near' })],
['mid', itemAt(1_000, spec, { pickId: 'mid' })],
['far', itemAt(4_000, spec, { pickId: 'far' })],
]);
layer.frame(items, 0);
const models = modelSet(draw);
assert.equal(models.items.size, POLICY.cap, 'the cap holds');
assert.deepEqual(
[...models.items.keys()].sort(),
['mid', 'near'],
'the nearest are modelled',
);
const near = models.items.get('near');
assert.equal(near.scale, spec.scale, 'drawn life size');
assert.equal(near.minPixelSize ?? 0, 0, 'at its true size: no pixel floor');
assert.equal(near.meta, 'near', 'picked as its vehicle');
assert.equal(near.show, false, 'hidden until ready');
layer.frame(items, 100);
for (const item of items.values())
assert.equal(item.modelOwnsVisual, false, 'not ready: the icon draws');
assert.ok(
layer.settling > 0,
'the layer asks for frames while models settle',
);
draw.ready(models.spec.id, 'near');
draw.ready(models.spec.id, 'mid');
layer.frame(items, 200);
assert.equal(items.get('near').modelOwnsVisual, true);
assert.equal(items.get('mid').modelOwnsVisual, true);
assert.equal(items.get('far').modelOwnsVisual, false);
assert.equal(layer.settling, 0);
assert.equal(models.items.get('near').show, true);
// A placed model stands on its item's point, nose along its heading.
const placed = models.items.get('near');
assert.ok(distance(placed.pos, items.get('near').position) < 1e-6);
assert.ok(
Math.abs(
placed.orientation.heading -
((90 + FLEET_HEADING_OFFSET_DEG) * Math.PI) / 180,
) < 1e-12,
);
// 3D off: every model goes and every icon comes back.
display.models3d = false;
layer.frame(items, 300);
assert.equal(layer.size, 0);
assert.equal(models.items.size, 0, 'released from the set');
for (const item of items.values()) assert.equal(item.modelOwnsVisual, false);
layer.destroy();
assert.equal(models.disposed, true);
});
test('vehicles draw as models within 3 km in either mode, and keep them to about 3.6 km', () => {
// The camera 1 km up: a vehicle `metres` east is sqrt(1 km² + metres²) away.
const at = (km) => Math.sqrt(km * km - 1) * 1_000;
for (const mode of ['proximity', 'all']) {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true, models3dMode: mode }),
policy: POLICY,
});
const spec = transitModelSpec(set, { mode: 'tram' });
const items = new Map([
['in', itemAt(at(2.9), spec, { pickId: 'in' })],
['out', itemAt(at(3.1), spec, { pickId: 'out' })],
]);
layer.frame(items, 0);
const models = modelSet(draw);
assert.deepEqual(
[...models.items.keys()],
['in'],
`${mode}: 2.9 km, not 3.1 km`,
);
items.set('in', itemAt(at(3.5), spec, { pickId: 'in' }));
layer.frame(items, 100);
assert.ok(models.items.has('in'), `${mode}: kept at 3.5 km`);
items.set('in', itemAt(at(3.7), spec, { pickId: 'in' }));
layer.frame(items, 200);
assert.equal(models.items.size, 0, `${mode}: released at 3.7 km`);
layer.destroy();
}
});
test('models stay off above the altitude ceiling', () => {
const { viewer, draw } = fakeViewer(POLICY.altitudeCeilingM + 1);
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
});
assert.equal(layer.active(), false);
layer.frame(new Map([['a', itemAt(0, transitModelSpec(set, {}))]]), 0);
assert.equal(modelSet(draw).items.size, 0);
layer.destroy();
});
test('a tinted model is painted with its route colour; an untinted one is not', () => {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
});
const tram = transitModelSpec(set, { mode: 'tram' });
const ship = vesselModelSpec(set, { type: '70', length: 180 });
assert.equal(tram.tinted, true);
assert.equal(ship.tinted, false);
const items = new Map([
['tram', itemAt(10, tram, { pickId: 'tram', tint: '#ff0000' })],
['ship', itemAt(20, ship, { pickId: 'ship', tint: '#ff0000' })],
]);
layer.frame(items, 0);
const models = modelSet(draw);
assert.equal(models.items.get('tram').maskColor, '#ff0000');
assert.equal(models.items.get('ship').maskColor, undefined);
// A new route colour is written in place.
items.get('tram').tint = [0, 0, 1, 1];
layer.frame(items, 10);
assert.deepEqual(models.items.get('tram').maskColor, [0, 0, 1, 1]);
assert.deepEqual(fleetColor({ red: 1, green: 0, blue: 0 }), [1, 0, 0, 1]);
layer.destroy();
});
test('an elevated vehicle is raised by its type elevation', () => {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
});
const monorail = transitModelSpec(set, { mode: 'monorail' });
assert.equal(monorail.elevationM, set.types.transit.elevation.monorail);
const item = itemAt(10, monorail, { pickId: 'm' });
layer.frame(new Map([['m', item]]), 0);
const placed = modelSet(draw).items.get('m');
const lifted = toLonLatH(placed.pos).height;
const ground = toLonLatH(item.position).height;
assert.ok(Math.abs(lifted - ground - monorail.elevationM) < 1e-3);
layer.destroy();
});
test('a vessel stretched to its reported beam keeps its length scale on the model', () => {
const spec = vesselModelSpec(set, { type: '70', length: 200, beam: 60 });
assert.ok(spec.scaleXYZ[1] > spec.scaleXYZ[0], 'a wide hull for its length');
// Along the model's glTF axes: x its length, y its height, z its beam.
const [x, y, z] = fleetAxisScale(spec);
assert.equal(x, 1);
assert.ok(Math.abs(y - spec.scaleXYZ[2] / spec.scaleXYZ[0]) < 1e-12);
assert.ok(Math.abs(z - spec.scaleXYZ[1] / spec.scaleXYZ[0]) < 1e-12);
assert.equal(
fleetAxisScale(transitModelSpec(set, { mode: 'tram' })),
undefined,
'a model at its own proportions is not stretched',
);
assert.equal(FLEET_HEADING_OFFSET_DEG, 180, 'fleet models are built nose -X');
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
});
layer.frame(new Map([['s', itemAt(10, spec, { pickId: 's' })]]), 0);
const item = modelSet(draw).items.get('s');
assert.equal(item.scale, spec.scale, 'its length scale');
assert.deepEqual(item.axisScale, [x, y, z], 'stretched to its beam');
layer.destroy();
});
test('Vessels, Transit and Rail draw fleet models under the shared 3D toggle', () => {
for (const file of [
'src/layers/vessels/rendering.js',
'src/layers/transit/rendering.js',
'src/layers/rail/rendering.js',
]) {
const source = fs.readFileSync(
new URL(`../../${file}`, import.meta.url),
'utf8',
);
assert.match(
source,
/createFleetModelLayer\(/,
`${file}: draws fleet models`,
);
assert.match(
source,
/loadFleetModelSet\(/,
`${file}: loads the set up front`,
);
assert.match(
source,
/modelOwnsVisual/,
`${file}: hands its icon to the model`,
);
}
for (const file of [
'src/app/layers/aisLiveVessels.js',
'src/app/layers/transit.js',
'src/app/layers/rail.js',
]) {
const source = fs.readFileSync(
new URL(`../../${file}`, import.meta.url),
'utf8',
);
assert.match(
source,
/fleet: fleetModelServices\(/,
`${file}: given the fleet service`,
);
}
const catalog = fs.readFileSync(
new URL('../app/constructCatalog.js', import.meta.url),
'utf8',
);
assert.equal(
catalog.match(/displayParams: \(\) => flights\.getParams\(\)/g)?.length,
4,
'Local ADS-B, Vessels, Transit and Rail follow the Flights 3D toggle',
);
});
/** A layer whose models are all ready as soon as they are written. */
function readyLayer({ display, waterline = false } = {}) {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => display,
policy: POLICY,
waterline,
});
const frame = (items, nowMs) => {
layer.frame(items, nowMs);
const models = modelSet(draw);
for (const id of models.items.keys()) draw.ready(models.spec.id, id);
layer.frame(items, nowMs + 1);
return models;
};
return { layer, draw, frame };
}
test('a model stands on the floor its icon is lifted above', () => {
const { layer, frame } = readyLayer({ display: { models3d: true } });
const tram = transitModelSpec(set, { mode: 'tram' });
const item = itemAt(10, tram, { pickId: 't', groundLiftM: 1.5 });
const models = frame(new Map([['t', item]]), 0);
const drop =
toLonLatH(item.position).height -
toLonLatH(models.items.get('t').pos).height;
assert.ok(Math.abs(drop - 1.5) < 1e-3, `dropped ${drop} m`);
layer.destroy();
});
test('a model that did not change is not written, nor built anew to find that out', () => {
const { layer, frame } = readyLayer({ display: { models3d: true } });
const tram = transitModelSpec(set, { mode: 'tram' });
// Reads of what only the draw item takes (its scales): a model whose item
// is built again reads them.
let shapeReads = 0;
const spec = new Proxy(tram, {
get(target, key) {
if (key === 'scale' || key === 'scaleXYZ') shapeReads += 1;
return target[key];
},
});
const tint = [1, 0, 0, 1];
const item = itemAt(10, spec, { pickId: 't', tint });
const items = new Map([['t', item]]);
const models = frame(items, 0);
const writes = models.writes;
shapeReads = 0;
for (let at = 2; at < 6; at++) layer.frame(items, at);
assert.equal(models.writes, writes, 'nothing written');
assert.equal(shapeReads, 0, 'no draw item built');
// A move, a turn and a route colour the layer changes in its own array
// are each written.
item.position = add(item.position, { x: 1, y: 0, z: 0 });
layer.frame(items, 6);
assert.equal(models.writes, writes + 1, 'a move is written');
item.headingDeg += 10;
layer.frame(items, 7);
assert.equal(models.writes, writes + 2, 'a turn is written');
tint[2] = 1;
layer.frame(items, 8);
assert.equal(models.writes, writes + 3, 'a colour changed in place');
assert.deepEqual(models.items.get('t').maskColor, [1, 0, 1, 1]);
layer.frame(items, 9);
assert.equal(models.writes, writes + 3, 'and then nothing');
layer.destroy();
});
test('under NVG/FLIR models draw unlit white, and lit again on exit, without loading again', () => {
const display = { models3d: true, irBoost: false };
const { layer, frame } = readyLayer({ display });
const tram = transitModelSpec(set, { mode: 'tram' });
const items = new Map([
['t', itemAt(10, tram, { pickId: 't', tint: '#ff0000' })],
]);
let models = frame(items, 0);
let item = models.items.get('t');
assert.equal(item.shading, 'pbr');
assert.equal(item.maskColor, '#ff0000');
display.irBoost = true;
layer.frame(items, 100);
item = models.items.get('t');
assert.equal(item.shading, 'unlit');
assert.deepEqual(item.tint, [1, 1, 1, 1]);
assert.deepEqual(item.colorBlend, { mode: 'mix', amount: 1 });
assert.equal(item.maskColor, undefined, 'no route colour under NVG/FLIR');
assert.equal(item.show, true, 'still the visual: restyled in place');
display.irBoost = false;
layer.frame(items, 200);
item = models.items.get('t');
assert.equal(item.shading, 'pbr');
assert.equal(item.maskColor, '#ff0000');
layer.destroy();
});
test('a waterline layer clips each model at its origin, keeping the part above', () => {
const { layer, frame } = readyLayer({
display: { models3d: true },
waterline: true,
});
const ship = vesselModelSpec(set, { type: '70', length: 200, beam: 32 });
const models = frame(new Map([['s', itemAt(10, ship, { pickId: 's' })]]), 0);
assert.equal(models.items.get('s').clip, 'belowOrigin');
layer.destroy();
const plain = readyLayer({ display: { models3d: true } });
const others = plain.frame(
new Map([['t', itemAt(10, transitModelSpec(set, { mode: 'tram' }))]]),
0,
);
assert.equal(others.items.get('t').clip, undefined, 'others unclipped');
plain.layer.destroy();
});
test('a failed model loads again after a while; the icon stays meanwhile', () => {
const { viewer, draw } = fakeViewer();
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
});
const tram = transitModelSpec(set, { mode: 'tram' });
const items = new Map([['t', itemAt(10, tram, { pickId: 't' })]]);
layer.frame(items, 0);
const models = modelSet(draw);
draw.loadFailed(models.spec.id, 't');
layer.frame(items, 100);
assert.equal(items.get('t').modelOwnsVisual, false);
assert.equal(layer.settling, 0, 'a failed model is not waited on');
layer.destroy();
});
test('without a draw port that draws models, vehicles stay icons', () => {
const viewer = {};
const layer = createFleetModelLayer({
viewer,
display: () => ({ models3d: true }),
policy: POLICY,
draw: { models: undefined },
});
const items = new Map([
['t', itemAt(10, transitModelSpec(set, { mode: 'tram' }))],
]);
assert.equal(layer.active(), false);
assert.equal(layer.frame(items, 0), false);
assert.equal(items.get('t').modelOwnsVisual, false);
layer.destroy();
});
test('a vehicle drawn as its model keeps its card and its detection entry', () => {
const read = (file) =>
fs.readFileSync(new URL(`../../${file}`, import.meta.url), 'utf8');
assert.match(
read('src/layers/transit/selection.js'),
/marker\?\.show !== false \|\| entry\.modelOwnsVisual === true/,
);
assert.match(
read('src/layers/rail/selection.js'),
/entry\.marker\?\.show !== false \|\| entry\.modelOwnsVisual === true/,
);
assert.match(
read('src/layers/transit/queries.js'),
/marker\.show === false && entry\.modelOwnsVisual !== true/,
);
assert.match(
read('src/layers/vessels/queries.js'),
/if \(!visual\.visible\) continue;/,
);
assert.match(
read('src/layers/transit/rendering.js'),
/entry\.mode === 'unknown'/,
'a vehicle of unknown mode keeps its icon',
);
});
+647
View File
@@ -0,0 +1,647 @@
/**
* @module fleetModels
* @description The project's procedural fleet models (`public/models/fleet/`):
* which model draws an aircraft, a vessel or a transit or rail vehicle, and at
* what size, from the set's `catalog.json` (each model's file, bounds,
* length, beam, clearance and icon class) and `types.json` (which model
* draws which type, and the fallbacks).
*
* Every model is metres, glTF Y-up, nose toward local -X, origin at the body
* centre (an aircraft's fuselage axis, a vessel's waterline, a road or rail
* vehicle's road or rail top), and is drawn life size: a type's published
* length over the model's built length is its scale.
*
* An aid to navigation (a buoy, beacon, mark, RACON or light) is drawn as
* the set's buoy of its IALA mark, by the mark its type names.
*
* The resolvers are plain functions over the parsed JSON; `loadFleetModelSet`
* fetches the JSON and every GLB once, up front, so no model is fetched
* mid-session.
*/
import { classifyAircraft } from './aircraftClass.js';
import { readPartTable } from '../render/modelParts.js';
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
import { isAidToNavigation } from './vesselTypes.js';
/** Where the model set is served, relative to the application base. */
export const FLEET_MODEL_BASE = '/models/fleet/';
/**
* Longest and widest hulls afloat, metres (Seawise Giant 458 m; the TI
* tankers 68 m abeam). AIS gives the bow and stern from the antenna in 9 bits
* and each side in 6, their largest values (511, 63) meaning "that or more"
* or a set never configured: a 30 m tug reported 511 m long would be drawn 17
* times its size.
*/
const MAX_HULL_LENGTH_M = 460;
const MAX_HULL_BEAM_M = 75;
/** The model a known aircraft class draws when its type has no entry. */
const CLASS_MODELS = Object.freeze({
light: 'c172',
glider: 'glider',
turboprop: 'at72',
widebody: 'b789',
quadjet: 'b744',
helicopter: 'generic_heli',
fastjet: 't38',
bizjet: 'c56x',
uav: 'mq9',
});
/** OpenSky's integer aircraft category (state vector index 17) → ADS-B emitter category. */
const OPENSKY_EMITTER_CATEGORY = Object.freeze({
2: 'A1',
3: 'A2',
4: 'A3',
5: 'A4',
6: 'A5',
7: 'A6',
8: 'A7',
9: 'B1',
10: 'B2',
11: 'B3',
12: 'B4',
14: 'B6',
15: 'B7',
16: 'C1',
17: 'C2',
18: 'C3',
19: 'C4',
20: 'C5',
});
/** A text vessel type (as some AIS sources name it) → a representative AIS ship-type code. */
const TEXT_SHIP_TYPES = [
[/tanker|lng|lpg|gas carrier/i, 80],
[/cargo|container|bulk|carrier|freighter|ro-?ro/i, 70],
[/passenger|ferry|cruise/i, 60],
[/high.?speed/i, 40],
[/fishing|trawler/i, 30],
[/tug|towing/i, 52],
[/pilot/i, 50],
[/search|rescue|\bsar\b/i, 51],
[/dredg/i, 33],
[/military|naval|navy/i, 35],
[/law|police|patrol|coast ?guard/i, 55],
[/sail/i, 36],
[/pleasure|yacht/i, 37],
];
/**
* The buoy an aid to navigation is drawn as, by the mark its type names
* ("Cardinal Mark N", "Beacon, Port hand", "Safe Water"): the first pattern
* that matches. Beacons, lights, RACONs and reference points with no mark of
* their own are the special mark.
*/
const AID_MODELS = [
[/cardinal\b.*\bn(orth)?$/i, 'buoy_cardinal_north'],
[/cardinal\b.*\be(ast)?$/i, 'buoy_cardinal_east'],
[/cardinal\b.*\bs(outh)?$/i, 'buoy_cardinal_south'],
[/cardinal\b.*\bw(est)?$/i, 'buoy_cardinal_west'],
[/isolated danger/i, 'buoy_isolated_danger'],
[/safe water/i, 'buoy_safe_water'],
[/port hand/i, 'buoy_lateral_port'],
[/starboard hand/i, 'buoy_lateral_starboard'],
[/special mark|light vessel|lanby/i, 'buoy_special'],
[
/^(beacon|light\b|leading light|racon|reference point|navigation aid)/i,
'buoy_special',
],
];
/** The buoy an aid to navigation whose type names no mark is drawn as. */
export const DEFAULT_AID_MODEL = 'can_red';
/**
* The buoy model of an aid to navigation's type, else undefined when the
* type names no mark.
* @param {string|null} [type]
* @returns {string|undefined}
*/
export function aidToNavigationModel(type) {
const text = String(type ?? '').trim();
for (const [pattern, model] of AID_MODELS)
if (pattern.test(text)) return model;
return undefined;
}
/**
* The model for an aircraft of ICAO type `type` (A320, B738, R44), ADS-B
* emitter category `category` and callsign `callsign`: the first of the
* type's callsign rules (`aircraft_callsign`) the callsign matches, else the
* type's, else the category's, else `default_aircraft`. An airport vehicle
* (type ZVEH) is a fire truck, tug or van by its callsign, else a car.
* @param {object} types Parsed `types.json`.
* @param {string} [type]
* @param {string} [category]
* @param {string} [callsign]
* @returns {{model: string, length: number|null}}
*/
export function resolveAircraft(types, type, category, callsign) {
const t = type?.trim().toUpperCase();
const index = aircraftCallsignRule(types, t, callsign);
if (index >= 0) {
const rule = types.aircraft_callsign[t][index];
return { model: rule.model, length: rule.length };
}
const [model, length] =
(t && (types.aircraft[t] ?? types.helicopters[t])) ||
(category && types.categories[category]) ||
types.default_aircraft;
return { model, length };
}
/**
* A callsign as the rules read it: upper case, spaces removed.
* @param {string} callsign
* @returns {string}
*/
function callsignKey(callsign) {
return String(callsign).toUpperCase().replace(/\s+/g, '');
}
/**
* Which of type `type`'s callsign rules (`types.json`'s
* `aircraft_callsign[type]`, each `{prefixes, model, length}`, first match
* wins) `callsign` matches: its index, -1 when none does or the type has
* none. A callsign matches a rule when, upper-cased with spaces removed, it
* starts with one of the rule's prefixes.
* @param {object} types Parsed `types.json`.
* @param {string|null} [type] ICAO type.
* @param {string|null} [callsign]
* @returns {number}
*/
export function aircraftCallsignRule(types, type, callsign) {
const t = String(type ?? '')
.trim()
.toUpperCase();
const rules = t ? types.aircraft_callsign?.[t] : undefined;
if (!rules || !callsign) return -1;
const c = callsignKey(callsign);
return rules.findIndex((rule) =>
rule.prefixes.some((prefix) => c.startsWith(callsignKey(prefix))),
);
}
/**
* Whether an aircraft of ICAO type `type` picks its model by callsign.
* @param {object} types Parsed `types.json`.
* @param {string|null} [type]
* @returns {boolean}
*/
export function aircraftModelByCallsign(types, type) {
const t = String(type ?? '')
.trim()
.toUpperCase();
return Boolean(t && types.aircraft_callsign?.[t]);
}
/**
* A reported length as one a hull can have, else undefined (drawn as built).
* @param {number} [length]
* @returns {number|undefined}
*/
export function hullLength(length) {
return length !== undefined &&
length !== null &&
length > 0 &&
length <= MAX_HULL_LENGTH_M
? length
: undefined;
}
/**
* A reported beam as one a hull can have, else undefined.
* @param {number} [beam]
* @returns {number|undefined}
*/
export function hullBeam(beam) {
return beam !== undefined &&
beam !== null &&
beam > 0 &&
beam <= MAX_HULL_BEAM_M
? beam
: undefined;
}
/**
* The model for a vessel of AIS ship type `shipType` and the reported length
* and beam (metres) and name: the first rule that matches in the first type
* range that has one, else `default_vessel`. Drawn at the reported length;
* when it is unknown (most live feeds send none), chosen and drawn at the
* range's `typical_len`, else as built.
* @param {object} types Parsed `types.json`.
* @param {number} [shipType]
* @param {number} [length]
* @param {number} [beam]
* @param {string} [name]
* @returns {{model: string, length: number|null}}
*/
export function resolveVessel(types, shipType, length, beam, name) {
const L = hullLength(length) ?? 0;
const B = hullBeam(beam) ?? 0;
if (shipType !== undefined && shipType !== null) {
for (const group of types.vessels) {
if (!(shipType >= group.types[0] && shipType <= group.types[1])) continue;
const len = L > 0 ? L : (group.typical_len ?? 0);
const drawn = len > 0 ? len : null;
for (const rule of group.rules) {
if (rule.min_len && len < rule.min_len) continue;
if (rule.max_len && len > rule.max_len) continue;
if (rule.name_re && !new RegExp(rule.name_re).test(name ?? ''))
continue;
if (rule.max_bl && !(B > 0 && L > 0 && B / L <= rule.max_bl)) continue;
return { model: rule.model, length: drawn };
}
}
}
return { model: types.default_vessel, length: L > 0 ? L : null };
}
/**
* The model for a public transport vehicle: a rail category and mode
* (`transit`/`local`/`regional`/`national`/`international` × `rail`/`metro`/
* `tram`), else a GTFS `route_type` (basic 0-12 or extended 100-1507), else a
* mode name (`bus`, `tram`, `subway`, `rail`, `ferry`, `light_rail`, …),
* else `transit.default`. Each comes with the length to draw it at.
* @param {object} types Parsed `types.json`.
* @param {{railCategory?: string, railMode?: string, routeType?: number|string,
* mode?: string}} vehicle
* @returns {{model: string, length: number|null}}
*/
export function resolveTransit(
types,
{ railCategory, railMode, routeType, mode } = {},
) {
const transit = types.transit;
const rail = railCategory ? transit.rail[railCategory] : null;
const routeKey =
routeType === undefined || routeType === null || routeType === ''
? null
: String(Number(routeType));
const [model, length] =
(rail && (rail[railMode || 'rail'] ?? rail.rail)) ||
(routeKey && transit.route_types[routeKey]) ||
(mode && transit.modes[mode]) ||
transit.default;
return { model, length };
}
/**
* An AIS ship type as its numeric code: a code as given ("70"), or the code
* of the family a text type names ("Cargo" → 70); undefined when it names
* none.
* @param {string|number|null|undefined} type
* @returns {number|undefined}
*/
export function aisShipTypeCode(type) {
const text = String(type ?? '').trim();
if (!text) return undefined;
if (/^\d+$/.test(text)) {
const code = Number(text);
return code > 0 && code < 100 ? code : undefined;
}
for (const [pattern, code] of TEXT_SHIP_TYPES)
if (pattern.test(text)) return code;
return undefined;
}
/**
* An aircraft category as an ADS-B emitter category: an emitter string as
* given ("A3"), or OpenSky's integer category mapped to one.
* @param {string|number|null|undefined} category
* @returns {string|undefined}
*/
export function emitterCategory(category) {
if (typeof category === 'number')
return OPENSKY_EMITTER_CATEGORY[category] || undefined;
const text = String(category ?? '')
.trim()
.toUpperCase();
if (/^\d+$/.test(text)) return OPENSKY_EMITTER_CATEGORY[Number(text)];
return /^[A-D][0-7]$/.test(text) ? text : undefined;
}
/**
* The scale of model `model` drawn `length` metres long, along the model's
* length, beam and height. A vessel's reported beam stretches it sideways;
* its height follows the mean of the two.
* @param {object} model Catalog entry.
* @param {number|null} length
* @param {number} [beam] A vessel's reported beam.
* @returns {[number, number, number]}
*/
export function placeScale(model, length, beam) {
if (length === null || length === undefined || !(model.length > 0))
return [1, 1, 1];
const sx = length / model.length;
const b = hullBeam(beam);
const sy = b !== undefined && model.beam > 0 ? b / model.beam : sx;
return [sx, sy, (sx + sy) / 2];
}
/** Half the diagonal of a model's bounds: the radius Cesium bounds it by. */
function boundingRadius(model) {
const [x0, y0, z0] = model.min;
const [x1, y1, z1] = model.max;
return Math.hypot(x1 - x0, y1 - y0, z1 - z0) / 2;
}
/**
* The drawing of model `name` at `length` metres: what the layers place.
*
* `scale` is the uniform scale (along the model's length) a Cesium Model
* takes; `scaleXYZ` the model's length, beam and height scales, for a vessel
* stretched to its reported beam. `clearanceM` is how far the model reaches
* below its origin at that scale (wheels below an aircraft's axis, a keel
* below the waterline): a grounded aircraft stands its origin that far up.
* `elevationM` lifts a vehicle off the route it follows (a monorail, a
* gondola). `tinted` models carry the `_TINT` vertex attribute marking where
* a route colour applies. `nativeRadiusM` (unscaled), `visualCenterNative`
* and `trailAnchorNative` (raw glTF axes, unscaled) serve the aircraft
* layers' pixel-size, bracket and trail geometry.
* @param {{catalog: object, types: object}} set
* @param {string} name Catalog model name.
* @param {number|null} length Metres along the body; null draws it as built.
* @param {{beam?: number}} [options]
* @returns {object}
*/
export function fleetModelSpec(set, name, length, { beam } = {}) {
const model = set.catalog[name];
// Ground vehicles, balloons and obstacles are built at the size their type
// names (a tower's 60 m is its height, not a length to scale to).
const drawnLength = model.category === 'other' ? null : length;
const scaleXYZ = placeScale(model, drawnLength, beam);
const elevationM = set.types.transit?.elevation?.[name] || 0;
return Object.freeze({
model: name,
url: FLEET_MODEL_BASE + model.file,
category: model.category,
icon: model.icon,
length: model.length * scaleXYZ[0],
scale: scaleXYZ[0],
scaleXYZ: Object.freeze(scaleXYZ),
clearanceM: model.clearance * scaleXYZ[2],
elevationM,
tinted: model.category === 'transit',
nativeRadiusM: boundingRadius(model),
visualCenterNative: CENTRED,
trailAnchorNative: FLEET_TRAIL_ANCHORS[name] || CENTRED,
key: `${name}@${scaleXYZ.map((s) => s.toFixed(4)).join('x')}`,
});
}
const CENTRED = Object.freeze([0, 0, 0]);
/** `resolved` drawn from `set`, its model replaced by `fallback` when the catalog lacks it. */
function specOf(set, resolved, fallback, options) {
const known = set.catalog[resolved.model] ? resolved : fallback(resolved);
return fleetModelSpec(set, known.model, known.length, options);
}
/**
* The model an aircraft is drawn with. The type's callsign rules (an airport
* vehicle by its callsign), then the type's entry; then, for a
* type the map lacks, the model of its class (a fast jet, a helicopter, a
* glider) when the type names one; then the emitter category's; then
* `default_aircraft`.
* @param {{catalog: object, types: object}} set
* @param {{typeCode?: string|null, type?: string|null,
* category?: string|number|null, callsign?: string|null}} aircraft
* @returns {object} {@link fleetModelSpec}
*/
export function aircraftModelSpec(
set,
{ typeCode, type, category, callsign } = {},
) {
const { types, catalog } = set;
const code = String(typeCode ?? type ?? '')
.trim()
.toUpperCase();
const emitter = emitterCategory(category);
const sign = callsign ? String(callsign) : undefined;
let resolved = resolveAircraft(types, code, emitter, sign);
// A callsign rule names the model outright; a type's class only stands in
// for a type the map lacks.
const ruled = aircraftCallsignRule(types, code, sign) >= 0;
const typed = code && (types.aircraft[code] || types.helicopters[code]);
if (!ruled && !typed && code) {
const model = CLASS_MODELS[classifyAircraft({ typeCode: code })];
if (model && catalog[model])
resolved = { model, length: catalog[model].length };
}
return specOf(set, resolved, () => ({
model: types.default_aircraft[0],
length: types.default_aircraft[1],
}));
}
/**
* The model a vessel is drawn with, from its AIS ship type (a code or a text
* family), reported length and beam (metres) and name. An aid to navigation
* ({@link isAidToNavigation}: its type names a buoy, beacon, mark, RACON or
* light, or its MMSI is an aid's) is the buoy of its mark
* ({@link aidToNavigationModel}), else {@link DEFAULT_AID_MODEL}, drawn as
* built and flagged `fixed`: it has no heading to turn to. A virtual aid
* (`virtual`) is broadcast where nothing physical stands, so it has no model.
* @param {{catalog: object, types: object}} set
* @param {{type?: string|number|null, mmsi?: string|number|null,
* virtual?: boolean, length?: number|null, beam?: number|null,
* name?: string|null}} vessel
* @returns {object|null} {@link fleetModelSpec}, with `fixed` for an aid;
* null for a virtual aid
*/
export function vesselModelSpec(
set,
{ type, mmsi, virtual, length, beam, name } = {},
) {
if (virtual === true) return null;
if (isAidToNavigation({ type, mmsi })) {
const model = aidToNavigationModel(type);
const known = model && set.catalog[model] ? model : DEFAULT_AID_MODEL;
if (set.catalog[known])
return Object.freeze({
...fleetModelSpec(set, known, null),
fixed: true,
});
}
// A beam counts only beside a reported length: a vessel drawn at its type's
// typical length keeps the model's proportions.
const reported = hullLength(length ?? undefined);
const hullWidth = reported === undefined ? undefined : (beam ?? undefined);
const resolved = resolveVessel(
set.types,
aisShipTypeCode(type),
reported,
hullWidth,
name ?? undefined,
);
return specOf(
set,
resolved,
(r) => ({ model: set.types.default_vessel, length: r.length }),
{ beam: hullWidth },
);
}
/**
* The model a transit or rail vehicle is drawn with ({@link resolveTransit}).
* @param {{catalog: object, types: object}} set
* @param {object} vehicle
* @returns {object} {@link fleetModelSpec}
*/
export function transitModelSpec(set, vehicle) {
return specOf(set, resolveTransit(set.types, vehicle), () => ({
model: set.types.transit.default[0],
length: set.types.transit.default[1],
}));
}
/**
* Every model the type map names, defaults and fallbacks included.
* @param {object} types Parsed `types.json`.
* @returns {Set<string>}
*/
export function namedFleetModels(types) {
const pairs = (map) => Object.values(map).map(([model]) => model);
const transit = types.transit;
return new Set([
...pairs(types.aircraft),
...pairs(types.helicopters),
...pairs(types.categories),
...Object.values(types.aircraft_callsign ?? {}).flatMap((rules) =>
rules.map((rule) => rule.model),
),
...types.vessels.flatMap((group) => group.rules.map((rule) => rule.model)),
types.default_aircraft[0],
types.default_vessel,
...pairs(transit.modes),
...pairs(transit.route_types),
...Object.values(transit.rail).flatMap(pairs),
transit.default[0],
...Object.keys(transit.elevation),
...Object.values(CLASS_MODELS),
...AID_MODELS.map(([, model]) => model),
DEFAULT_AID_MODEL,
]);
}
/** Each loaded set's part tables by model name (null for a model without one). */
const partTables = new WeakMap();
/**
* The part table of model `name` in a loaded set, read once from its GLB:
* which moving parts it has (`render/modelParts.js`); null for a model
* without one, or whose GLB did not load.
* @param {{bytes?: Map<string, Uint8Array>}|null|undefined} set
* @param {string|null|undefined} name
* @returns {import('../render/modelParts').PartTable|null}
*/
export function fleetPartTable(set, name) {
const bytes = name ? set?.bytes?.get(name) : undefined;
if (!bytes) return null;
let tables = partTables.get(set);
if (!tables) partTables.set(set, (tables = new Map()));
if (!tables.has(name)) {
let table = null;
try {
table = readPartTable(bytes);
} catch {
// A malformed table: the model draws whole.
}
tables.set(name, table);
}
return tables.get(name);
}
let loading = null;
let loaded = null;
/**
* The model set once {@link loadFleetModelSet} has loaded it, else null.
* @returns {object|null}
*/
export function fleetModelSet() {
return loaded;
}
/**
* The load a layer has started (resolving to the set), or null when none
* has: for a view that needs the set but does not fetch it itself.
* @returns {Promise<object>|null}
*/
export function fleetModelSetLoading() {
return loading;
}
/**
* Fetch the model set once for every layer: `catalog.json`, `types.json` and
* every GLB the catalog names, all up front, so no model is fetched while a
* session runs. Resolves to `{catalog, types, bytes, loadMs, totalBytes}`,
* `bytes` holding each model's GLB by name; a GLB that fails to load is left
* out (that model then draws nothing and its entities stay icons).
* @param {{resolveAsset?: (url: string) => string,
* fetchImpl?: typeof fetch, now?: () => number}} [options]
* @returns {Promise<object>}
*/
export function loadFleetModelSet({
resolveAsset = (url) => url,
fetchImpl = globalThis.fetch,
now = () => globalThis.performance?.now?.() ?? Date.now(),
} = {}) {
if (loading) return loading;
const started = now();
const json = async (name) => {
const response = await fetchImpl(resolveAsset(FLEET_MODEL_BASE + name));
if (!response.ok) throw new Error(`${name}: HTTP ${response.status}`);
return response.json();
};
loading = (async () => {
const [catalog, types] = await Promise.all([
json('catalog.json'),
json('types.json'),
]);
const bytes = new Map();
let totalBytes = 0;
await Promise.all(
Object.entries(catalog).map(async ([name, model]) => {
try {
const response = await fetchImpl(
resolveAsset(FLEET_MODEL_BASE + model.file),
);
if (!response.ok) return;
const glb = new Uint8Array(await response.arrayBuffer());
bytes.set(name, glb);
totalBytes += glb.byteLength;
} catch {
/* that model draws nothing; its entities stay icons */
}
}),
);
loaded = Object.freeze({
catalog,
types,
bytes,
loadMs: now() - started,
totalBytes,
});
console.info(
`[Fleet] ${bytes.size}/${Object.keys(catalog).length} models ` +
`(${(totalBytes / 1048576).toFixed(2)} MB) loaded in ${Math.round(loaded.loadMs)} ms`,
);
return loaded;
})();
// A failed catalog load may be retried by the next layer that starts.
loading.catch(() => {
loading = null;
});
return loading;
}
/** Forget the loaded set (tests). */
export function resetFleetModelSet() {
loading = null;
loaded = null;
}
+629
View File
@@ -0,0 +1,629 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import {
DEFAULT_AID_MODEL,
FLEET_MODEL_BASE,
aidToNavigationModel,
aircraftModelSpec,
aisShipTypeCode,
emitterCategory,
fleetModelSet,
fleetModelSpec,
hullBeam,
hullLength,
loadFleetModelSet,
namedFleetModels,
placeScale,
resetFleetModelSet,
resolveAircraft,
resolveTransit,
resolveVessel,
transitModelSpec,
vesselModelSpec,
} from './fleetModels.js';
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
import { TRANSIT_MODES } from './transitFeeds.js';
import {
centrelineSegments,
distanceToSurface,
fleetMesh,
measuredTrailAnchor,
readGlb,
vertexBounds,
} from '../testSupport/fleetGlb.mjs';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..',
);
const DIR = path.join(ROOT, 'public', 'models', 'fleet');
const json = (name) =>
JSON.parse(fs.readFileSync(path.join(DIR, name), 'utf8'));
const catalog = json('catalog.json');
const types = json('types.json');
const set = { catalog, types };
// A slice of the set's types.json and catalog.json, as the resolver's own
// reference tests use, so these read independently of later model changes.
const sliceTypes = {
aircraft: {
A320: ['a320', 37.57],
A21N: ['a320', 44.51],
A319: ['a320', 33.84],
B38M: ['b738', 39.52],
ZVEH: ['car', 4.61],
GRND: ['radio_mast', 1.9],
},
helicopters: { EC35: ['ec35', 10.2] },
aircraft_callsign: {
ZVEH: [
{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 },
{ prefixes: ['PUSH', 'TUG'], model: 'pushback', length: 6 },
{ prefixes: ['DEICER', 'SQUID', 'SQB'], model: 'van', length: 5.51 },
],
},
categories: { A1: ['c172', 8.3] },
vessels: [
{
types: [70, 79],
typical_len: 300,
rules: [
{ min_len: 70, max_len: 140, max_bl: 0.12, model: 'inland_cargo' },
{
name_re: '\\b(LEADER|HIGHWAY|ACE|GLOVIS|HOEGH|SPIRIT OF)\\b',
min_len: 150,
model: 'car_carrier',
},
{ min_len: 250, model: 'container_ship' },
{ model: 'general_cargo' },
],
},
{ types: [31, 32], rules: [{ model: 'tug' }] },
{ types: [52, 52], rules: [{ model: 'tug' }] },
{ types: [0, 99], rules: [{ model: 'generic_vessel' }] },
],
default_aircraft: ['generic_plane', 36],
default_vessel: 'generic_vessel',
};
const model = (category, file, length, beam, clearance) => ({
category,
file,
min: [0, 0, 0],
max: [0, 0, 0],
length,
beam,
clearance,
tris: 1,
icon: 'jet',
});
const sliceCatalog = {
a320: model('aircraft', 'aircraft/a320.glb', 37.57, 35.6, 3.063),
container_ship: model('ships', 'ships/container_ship.glb', 309.9, 48, 13.9),
};
test('aircraft resolve by type, then emitter category, then the generic plane', () => {
assert.deepEqual(resolveAircraft(sliceTypes, 'A320'), {
model: 'a320',
length: 37.57,
});
assert.deepEqual(resolveAircraft(sliceTypes, ' b38m '), {
model: 'b738',
length: 39.52,
});
assert.equal(resolveAircraft(sliceTypes, 'EC35').model, 'ec35');
assert.deepEqual(resolveAircraft(sliceTypes, 'ZZZZ', 'A1'), {
model: 'c172',
length: 8.3,
});
assert.deepEqual(resolveAircraft(sliceTypes, undefined, 'Q9'), {
model: 'generic_plane',
length: 36,
});
});
test('airport vehicles (ZVEH) by callsign, first rule wins, else the type: spaces and case ignored', () => {
const zveh = (callsign) =>
resolveAircraft(sliceTypes, 'ZVEH', undefined, callsign);
assert.deepEqual(zveh('FIRE 2'), { model: 'fire_truck', length: 11.01 });
assert.deepEqual(resolveAircraft(sliceTypes, 'zveh', undefined, ' fire2 '), {
model: 'fire_truck',
length: 11.01,
});
assert.equal(zveh('PUSH 14').model, 'pushback');
assert.equal(zveh('TUG3').model, 'pushback');
assert.deepEqual(zveh('DEICER 4'), { model: 'van', length: 5.51 });
assert.equal(zveh('SQUID20').model, 'van');
assert.equal(zveh('SQB9').model, 'van');
assert.equal(zveh('S Q B 9').model, 'van');
assert.deepEqual(zveh('LEADER 7'), { model: 'car', length: 4.61 });
assert.deepEqual(zveh(undefined), { model: 'car', length: 4.61 });
// Callsign rules belong to their type: a fire-named airliner is still an airliner.
assert.equal(
resolveAircraft(sliceTypes, 'A320', undefined, 'FIRE1').model,
'a320',
);
assert.deepEqual(resolveAircraft(sliceTypes, 'GRND', undefined, 'RX5'), {
model: 'radio_mast',
length: 1.9,
});
});
test('vessels: the first matching rule of the first type range with one, else the generic vessel', () => {
assert.equal(resolveVessel(sliceTypes, 70, 366, 51).model, 'container_ship');
assert.equal(
resolveVessel(sliceTypes, 71, 199, 32, 'GLOVIS SPIRIT').model,
'car_carrier',
);
assert.equal(resolveVessel(sliceTypes, 79, 110, 11.4).model, 'inland_cargo');
assert.equal(resolveVessel(sliceTypes, 70, 90, 15).model, 'general_cargo');
assert.deepEqual(resolveVessel(sliceTypes, 52, 30, 10), {
model: 'tug',
length: 30,
});
assert.deepEqual(resolveVessel(sliceTypes, undefined, 50), {
model: 'generic_vessel',
length: 50,
});
assert.deepEqual(resolveVessel(sliceTypes, 0), {
model: 'generic_vessel',
length: null,
});
});
test("vessels of unknown length are chosen and drawn at their range's typical length", () => {
assert.deepEqual(resolveVessel(sliceTypes, 70), {
model: 'container_ship',
length: 300,
});
assert.deepEqual(resolveVessel(sliceTypes, 70, 511, 126), {
model: 'container_ship',
length: 300,
});
assert.deepEqual(resolveVessel(sliceTypes, 70, 90, 15), {
model: 'general_cargo',
length: 90,
});
assert.deepEqual(resolveVessel(sliceTypes, 31), {
model: 'tug',
length: null,
});
// Every passenger, cargo and tanker range of the set has one.
for (const code of [60, 70, 80]) {
assert.ok(resolveVessel(types, code).length > 100, String(code));
}
});
test("vessels: AIS's out-of-range sizes (511 m long, 126 m abeam) are unknown, drawn as built", () => {
assert.deepEqual(resolveVessel(sliceTypes, 52, 511), {
model: 'tug',
length: null,
});
assert.equal(hullLength(511), undefined);
assert.equal(hullLength(0), undefined);
assert.equal(hullBeam(126), undefined);
assert.equal(hullBeam(32), 32);
const ship = sliceCatalog.container_ship;
assert.deepEqual(placeScale(ship, ship.length, 126), [1, 1, 1]);
});
test('scale: aircraft by the type length, vessels by length and beam', () => {
const a320 = sliceCatalog.a320;
const [sx, sy, sz] = placeScale(a320, 44.51);
assert.ok(Math.abs(sx - 44.51 / 37.57) < 1e-12);
assert.equal(sy, sx);
assert.equal(sz, sx);
const ship = sliceCatalog.container_ship;
assert.deepEqual(placeScale(ship, ship.length / 2, 24), [0.5, 0.5, 0.5]);
assert.deepEqual(placeScale(ship, null), [1, 1, 1]);
});
test('every model the type map names is in the catalog, and its file is a GLB on disk', () => {
for (const name of namedFleetModels(types))
assert.ok(
catalog[name],
`${name}: named by types.json but not in the catalog`,
);
assert.equal(catalog.generic_plane?.category, 'aircraft');
assert.equal(catalog.generic_vessel?.category, 'ships');
assert.equal(catalog.city_bus?.category, 'transit');
for (const [name, metres] of Object.entries(types.transit.elevation)) {
assert.ok(catalog[name], name);
assert.ok(metres > 0, name);
}
let total = 0;
for (const [name, entry] of Object.entries(catalog)) {
const file = path.join(DIR, entry.file);
assert.ok(fs.existsSync(file), `${name}: ${entry.file} is missing`);
const bytes = fs.readFileSync(file);
assert.equal(bytes.subarray(0, 4).toString('latin1'), 'glTF', name);
assert.ok(entry.length > 0, name);
assert.ok(entry.tris <= 50_000, name);
total += bytes.length;
}
// The set ships with the repository and loads up front: keep it small.
assert.ok(total < 3 * 1024 * 1024, `fleet GLBs total ${total} bytes`);
});
test('transit bodies mark the share of the route colour they take; other models mark none', () => {
for (const [name, entry] of Object.entries(catalog)) {
const { json: gltf } = readGlb(path.join(DIR, entry.file));
for (const mesh of gltf.meshes)
for (const primitive of mesh.primitives)
assert.equal(
'_TINT' in primitive.attributes,
entry.category === 'transit',
name,
);
assert.equal(
fleetModelSpec(set, name, null).tinted,
entry.category === 'transit',
);
}
});
test('aircraft specs: airport vehicles by callsign, ground stations as a mast, as the set says', () => {
const zveh = (callsign) =>
aircraftModelSpec(set, { typeCode: 'ZVEH', category: 'UNKNOWN', callsign })
.model;
assert.equal(zveh('FIRE 2'), 'fire_truck');
assert.equal(zveh('PUSHBACK1'), 'pushback');
assert.equal(zveh('TUG 4'), 'pushback');
assert.equal(zveh('DEICER 4'), 'van');
assert.equal(zveh('SQUID20'), 'van');
assert.equal(zveh('SQB9'), 'van');
assert.equal(zveh('LEADER 7'), 'car');
assert.equal(zveh('AOPS'), 'car');
assert.equal(zveh(null), 'car');
const mast = aircraftModelSpec(set, { typeCode: 'GRND', callsign: 'RX5' });
assert.equal(mast.model, 'radio_mast');
assert.equal(mast.scale, 1);
});
test('a callsign rule outranks the class model of a type the map lacks', () => {
const ruled = {
...set,
types: {
...set.types,
aircraft_callsign: {
...set.types.aircraft_callsign,
PUMA: [{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 }],
},
},
};
assert.equal(
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'FIRE 1' }).model,
'fire_truck',
);
// No rule matched: the class model, as before.
assert.equal(
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'RESCUE1' }).model,
'generic_heli',
);
});
test('aircraft specs: by type, then class for an unlisted type, then emitter category', () => {
assert.equal(aircraftModelSpec(set, { typeCode: 'A320' }).model, 'a320');
assert.equal(aircraftModelSpec(set, { type: 'b744' }).model, 'b744');
// An unlisted fast jet is still a fast jet, not the generic airliner.
assert.equal(
aircraftModelSpec(set, { typeCode: 'FA18', category: 'A3' }).model,
't38',
);
assert.equal(aircraftModelSpec(set, { typeCode: 'MQ9' }).model, 'mq9');
assert.equal(
aircraftModelSpec(set, { typeCode: 'PUMA' }).model,
'generic_heli',
);
// An unlisted type of no special class falls to its category.
assert.equal(
aircraftModelSpec(set, { typeCode: 'ZZZZ', category: 'A5' }).model,
'b77w',
);
// OpenSky's integer category: 8 is rotorcraft (A7), 2 light (A1).
assert.equal(emitterCategory(8), 'A7');
assert.equal(emitterCategory('a3'), 'A3');
assert.equal(emitterCategory(1), undefined);
assert.equal(aircraftModelSpec(set, { category: 8 }).model, 'generic_heli');
assert.equal(aircraftModelSpec(set, { category: 2 }).model, 'c172');
assert.equal(aircraftModelSpec(set, {}).model, types.default_aircraft[0]);
});
test('aircraft specs are life size, standing on their scaled clearance', () => {
const spec = aircraftModelSpec(set, { typeCode: 'A21N' });
const [, length] = types.aircraft.A21N;
assert.equal(spec.model, types.aircraft.A21N[0]);
assert.ok(Math.abs(spec.length - length) < 1e-9);
assert.ok(Math.abs(spec.scale - length / catalog[spec.model].length) < 1e-12);
assert.ok(
Math.abs(spec.clearanceM - catalog[spec.model].clearance * spec.scale) <
1e-12,
);
assert.equal(spec.url, `${FLEET_MODEL_BASE}${catalog[spec.model].file}`);
assert.equal(spec.tinted, false);
assert.equal(spec.elevationM, 0);
assert.ok(
spec.nativeRadiusM * spec.scale > 25 &&
spec.nativeRadiusM * spec.scale < 60,
);
assert.deepEqual(spec.trailAnchorNative, FLEET_TRAIL_ANCHORS[spec.model]);
// A grounded service vehicle and an obstacle are drawn as built: the
// tower's 60 m is its height, not a length to stretch it to.
const tower = aircraftModelSpec(set, { category: 'C3' });
assert.equal(tower.model, 'tower');
assert.equal(tower.scale, 1);
assert.equal(aircraftModelSpec(set, { category: 'C1' }).scale, 1);
});
test('vessel specs read AIS codes and text families, stretched to the reported beam', () => {
assert.equal(aisShipTypeCode('70'), 70);
assert.equal(aisShipTypeCode(' Cargo '), 70);
assert.equal(aisShipTypeCode('Tanker'), 80);
assert.equal(aisShipTypeCode('Tug'), 52);
assert.equal(aisShipTypeCode('0'), undefined);
assert.equal(aisShipTypeCode(''), undefined);
const box = vesselModelSpec(set, { type: '71', length: 366, beam: 51 });
assert.equal(box.model, 'container_ship');
assert.ok(Math.abs(box.length - 366) < 1e-9);
const [sx, sy, sz] = box.scaleXYZ;
assert.ok(Math.abs(sy - 51 / catalog.container_ship.beam) < 1e-12);
assert.ok(Math.abs(sz - (sx + sy) / 2) < 1e-12);
// A beam with no reported length: the type's typical length, in the model's
// own proportions, not a typical-length hull squeezed to that beam.
const unsized = vesselModelSpec(set, { type: '70', length: 0, beam: 14 });
assert.equal(unsized.model, 'container_ship');
const [ux, uy, uz] = unsized.scaleXYZ;
assert.ok(Math.abs(uy - ux) < 1e-12 && Math.abs(uz - ux) < 1e-12);
assert.equal(vesselModelSpec(set, { type: 'Tug', length: 30 }).model, 'tug');
assert.equal(vesselModelSpec(set, { type: '36' }).model, 'sailboat');
// No type, no size: the generic vessel as built.
const unknown = vesselModelSpec(set, {});
assert.equal(unknown.model, types.default_vessel);
assert.equal(unknown.scale, 1);
});
test('aids to navigation are the buoy of the mark their type names', () => {
const cases = [
['Cardinal Mark N', 'buoy_cardinal_north'],
['Beacon, Cardinal E', 'buoy_cardinal_east'],
['Cardinal Mark S', 'buoy_cardinal_south'],
['Beacon, Cardinal W', 'buoy_cardinal_west'],
['Port Hand Mark', 'buoy_lateral_port'],
['Beacon, Port hand', 'buoy_lateral_port'],
['Starboard Hand Mark', 'buoy_lateral_starboard'],
['Preferred Channel Starboard hand', 'buoy_lateral_starboard'],
['Safe Water', 'buoy_safe_water'],
['Isolated danger', 'buoy_isolated_danger'],
['Beacon, Special Mark', 'buoy_special'],
['Special Mark', 'buoy_special'],
['Light Vessel / LANBY / Rigs', 'buoy_special'],
['RACON', 'buoy_special'],
['Light, with Sectors', 'buoy_special'],
['Reference point', 'buoy_special'],
['Navigation aid', 'buoy_special'],
];
for (const [type, model] of cases) {
assert.equal(aidToNavigationModel(type), model, type);
assert.ok(catalog[model], model);
const spec = vesselModelSpec(set, { type, mmsi: '993672001' });
assert.equal(spec.model, model, type);
assert.equal(spec.category, 'buoys', type);
assert.equal(spec.fixed, true, type);
// A buoy is drawn as built, whatever length the report gives.
assert.equal(spec.scale, 1, type);
}
assert.equal(
vesselModelSpec(set, { type: 'Safe Water', length: 120, beam: 30 }).scale,
1,
);
// An aid of no stated kind, known only by its MMSI, is the default can.
assert.ok(catalog[DEFAULT_AID_MODEL]);
const unnamed = vesselModelSpec(set, { type: '', mmsi: '993660123' });
assert.equal(unnamed.model, DEFAULT_AID_MODEL);
assert.equal(unnamed.fixed, true);
assert.equal(aidToNavigationModel('Fixed structure off shore'), undefined);
// A virtual aid is broadcast where nothing stands: it keeps its disc.
assert.equal(
vesselModelSpec(set, {
type: 'Cardinal Mark N',
mmsi: '993672001',
virtual: true,
}),
null,
);
// Vessels, including those that work on buoys, keep their hulls.
for (const vessel of [
{ type: 'Buoy Tender', mmsi: '366999001', length: 60 },
{ type: '70', mmsi: '366999002' },
{ type: 'Tug', mmsi: '' },
]) {
const spec = vesselModelSpec(set, vessel);
assert.notEqual(spec.category, 'buoys', vessel.type);
assert.equal(spec.fixed, undefined, vessel.type);
}
});
test('every transit mode but unknown draws its own model, and a route type a finer one', () => {
for (const mode of TRANSIT_MODES.filter((m) => m !== 'unknown')) {
assert.ok(types.transit.modes[mode], `${mode} has a model`);
assert.equal(
resolveTransit(types, { mode }).model,
types.transit.modes[mode][0],
);
}
for (const [mode, model] of [
['trolleybus', 'trolleybus'],
['cable_tram', 'cable_tram'],
['aerial_lift', 'gondola'],
['funicular', 'funicular'],
['monorail', 'monorail'],
])
assert.equal(resolveTransit(types, { mode }).model, model, mode);
// A route type outranks the mode: a coach and a high-speed set are still
// the bus and rail modes.
for (const [routeType, mode, model] of [
[200, 'bus', 'coach'],
[101, 'rail', 'high_speed'],
[106, 'rail', 'regional_dmu'],
[710, 'bus', 'double_decker'],
])
assert.equal(resolveTransit(types, { routeType, mode }).model, model);
// A type the table lacks falls back to the mode.
assert.equal(
resolveTransit(types, { routeType: 300, mode: 'rail' }).model,
'commuter_emu',
);
});
test('transit specs: rail category and mode, then route type, then mode, then the default', () => {
assert.deepEqual(resolveTransit(types, { railCategory: 'national' }), {
model: 'intercity',
length: types.transit.rail.national.rail[1],
});
assert.equal(
resolveTransit(types, { railCategory: 'transit', railMode: 'metro' }).model,
'metro',
);
assert.equal(
resolveTransit(types, { railCategory: 'regional', railMode: 'tram' }).model,
'light_rail',
);
assert.equal(resolveTransit(types, { routeType: 3 }).model, 'city_bus');
assert.equal(resolveTransit(types, { routeType: '0' }).model, 'tram');
assert.equal(resolveTransit(types, { routeType: 109 }).model, 'commuter_emu');
assert.equal(resolveTransit(types, { mode: 'subway' }).model, 'metro');
assert.equal(resolveTransit(types, { mode: 'ferry' }).model, 'fast_ferry');
assert.equal(
resolveTransit(types, { mode: 'unknown' }).model,
types.transit.default[0],
);
const tram = transitModelSpec(set, { mode: 'tram' });
assert.equal(tram.tinted, true);
assert.equal(tram.clearanceM, 0);
assert.ok(Math.abs(tram.length - types.transit.modes.tram[1]) < 1e-9);
assert.equal(
transitModelSpec(set, { routeType: 12 }).elevationM,
types.transit.elevation.monorail,
);
assert.equal(
transitModelSpec(set, { mode: 'gondola' }).elevationM,
types.transit.elevation.gondola,
);
assert.equal(transitModelSpec(set, { mode: 'ferry' }).tinted, false);
});
test('a model missing from the catalog falls back to the default of its kind', () => {
const thin = {
catalog: { ...catalog },
types: {
...types,
aircraft: { ...types.aircraft, XXXX: ['no_such_model', 20] },
},
};
assert.equal(
aircraftModelSpec(thin, { typeCode: 'XXXX' }).model,
types.default_aircraft[0],
);
});
const ANCHORED = Object.entries(catalog).filter(([, entry]) =>
['aircraft', 'helicopters', 'other'].includes(entry.category),
);
test('every aircraft-layer model has a trail anchor on its real aft-belly hull', async () => {
assert.deepEqual(
new Set(Object.keys(FLEET_TRAIL_ANCHORS)),
new Set(ANCHORED.map(([name]) => name)),
're-run scripts/measure-fleet-trail-anchors.mjs',
);
for (const [name, entry] of ANCHORED) {
const mesh = await fleetMesh(path.join(DIR, entry.file));
const { min, max } = vertexBounds(mesh.verts);
const anchor = FLEET_TRAIL_ANCHORS[name];
// On the hull, not in the air beside it.
const offHull = distanceToSurface(anchor, mesh.verts, mesh.tris);
assert.ok(
offHull <= 1e-3,
`${name}: trail anchor is ${offHull.toFixed(4)} m off the hull`,
);
// Aft of the middle, so the head segment does not run into the body.
assert.ok(
anchor[0] > (min[0] + max[0]) / 2,
`${name}: trail anchor is not aft`,
);
// Nothing of the centreline hangs lower at or behind its station.
const lowest = centrelineSegments(mesh.verts, mesh.tris)
.flat()
.filter((p) => p[0] >= anchor[0] - 1e-3)
.reduce((low, p) => Math.min(low, p[1]), Infinity);
assert.ok(
anchor[1] <= lowest + 1e-3,
`${name}: trail anchor is above the hull aft of it`,
);
assert.equal(anchor[2], 0, `${name}: trail anchor is off the centreline`);
// And it is the construction, re-derived.
const measured = measuredTrailAnchor(mesh);
for (const axis of [0, 1])
assert.ok(
Math.abs(anchor[axis] - measured[axis]) <= 1e-3,
`${name} axis ${axis}: table ${anchor[axis]} vs measured ${measured[axis].toFixed(4)}`,
);
}
});
test('catalog bounds match the GLBs they describe', async () => {
for (const [name, entry] of Object.entries(catalog)) {
const { min, max } = vertexBounds(
(await fleetMesh(path.join(DIR, entry.file))).verts,
);
// The catalog is Z up (glTF Y), glTF Z across.
const tolerance = 0.01 * Math.max(1, entry.length);
assert.ok(Math.abs(min[0] - entry.min[0]) <= tolerance, `${name} min x`);
assert.ok(Math.abs(max[0] - entry.max[0]) <= tolerance, `${name} max x`);
assert.ok(Math.abs(min[1] - entry.min[2]) <= tolerance, `${name} min up`);
assert.ok(
Math.abs(-min[1] - entry.clearance) <= tolerance,
`${name} clearance`,
);
assert.ok(
Math.abs(max[2] - min[2] - (entry.max[1] - entry.min[1])) <= tolerance,
`${name} beam`,
);
}
});
test('the model set loads once, every GLB up front, shared by every layer', async () => {
resetFleetModelSet();
const requested = [];
const fetchImpl = async (url) => {
requested.push(url);
const file = path.join(ROOT, 'public', url.replace(/^\/app/, ''));
if (!fs.existsSync(file)) return { ok: false, status: 404 };
const bytes = fs.readFileSync(file);
return {
ok: true,
json: async () => JSON.parse(bytes.toString('utf8')),
arrayBuffer: async () =>
bytes.buffer.slice(
bytes.byteOffset,
bytes.byteOffset + bytes.byteLength,
),
};
};
const resolveAsset = (url) => `/app${url}`;
const [first, second] = await Promise.all([
loadFleetModelSet({ resolveAsset, fetchImpl }),
loadFleetModelSet({ resolveAsset, fetchImpl }),
]);
assert.equal(first, second);
assert.equal(fleetModelSet(), first);
assert.equal(first.bytes.size, Object.keys(catalog).length);
assert.equal(requested.length, Object.keys(catalog).length + 2);
assert.ok(requested.every((url) => url.startsWith('/app/models/fleet/')));
assert.ok(first.totalBytes > 0 && Number.isFinite(first.loadMs));
await loadFleetModelSet({ resolveAsset, fetchImpl });
assert.equal(requested.length, Object.keys(catalog).length + 2);
resetFleetModelSet();
});
+67
View File
@@ -0,0 +1,67 @@
/**
* Aft-belly trail attachment points of the fleet models the aircraft layers
* draw, in raw glTF axes (X along the body, nose toward -X; Y up), metres
* before scale, node transforms applied. Each is the point of the model's
* centreline profile (its z = 0 slice) nearest its aft-belly bounding-box
* corner: on the hull, aft, and on the centreline (see modelVisualAnchor.js).
*
* Written by scripts/measure-fleet-trail-anchors.mjs; re-measured against the
* GLBs by fleetModels.test.mjs.
*/
export const FLEET_TRAIL_ANCHORS = Object.freeze({
a139: Object.freeze([6.8847, 0.2766, 0]),
a320: Object.freeze([17.2078, 0.7416, 0]),
a333: Object.freeze([29.7276, 1.1084, 0]),
a343: Object.freeze([30.0371, 1.2335, 0]),
a359: Object.freeze([31.0731, 1.1573, 0]),
a388: Object.freeze([34.3139, 1.9279, 0]),
as50: Object.freeze([5.2278, -0.0999, 0]),
at72: Object.freeze([12.8258, 0.6792, 0]),
b06: Object.freeze([4.62, -0.3002, 0]),
b407: Object.freeze([5.1264, -0.2797, 0]),
b738: Object.freeze([18.3819, 0.8391, 0]),
b744: Object.freeze([33.6232, 1.5411, 0]),
b763: Object.freeze([25.5464, 0.9889, 0]),
b77w: Object.freeze([34.4639, 1.2084, 0]),
b789: Object.freeze([29.0604, 1.0649, 0]),
balloon: Object.freeze([3.8215, -0.0009, 0]),
bcs3: Object.freeze([17.8658, 0.713, 0]),
be20: Object.freeze([6.6699, 0.5505, 0]),
blimp: Object.freeze([32.2493, -7.1382, 0]),
c17: Object.freeze([26.5207, 2.332, 0]),
c172: Object.freeze([4.0507, 0.4481, 0]),
c30j: Object.freeze([13.568, 0.9917, 0]),
c56x: Object.freeze([7.4627, 0.4526, 0]),
car: Object.freeze([2.1851, 0.301, 0]),
cl35: Object.freeze([10.4607, 0.8247, 0]),
crj9: Object.freeze([17.8413, 0.8624, 0]),
dh8d: Object.freeze([15.7902, 0.7501, 0]),
e175: Object.freeze([14.697, 0.6077, 0]),
e55p: Object.freeze([7.6566, 0.503, 0]),
ec35: Object.freeze([5.1003, 0.1471, 0]),
ec45: Object.freeze([5.8004, 0.555, 0]),
fire_truck: Object.freeze([5.39, 0.4227, 0]),
generic_heli: Object.freeze([5.4997, 0.1604, 0]),
generic_plane: Object.freeze([16.5228, 0.712, 0]),
glf4: Object.freeze([13.4603, 0.8243, 0]),
glider: Object.freeze([3.3997, 0.1283, 0]),
h47: Object.freeze([7.7303, 0.0035, 0]),
h60: Object.freeze([7.6295, 0.1365, 0]),
h64: Object.freeze([6.9228, -0.5553, 0]),
k35r: Object.freeze([28.0221, -2.4508, 0]),
md11: Object.freeze([30.8002, 1.2291, 0]),
mq9: Object.freeze([5.8498, -0.062, 0]),
p28a: Object.freeze([3.3695, 0.3959, 0]),
pc12: Object.freeze([6.6416, 0.5288, 0]),
pushback: Object.freeze([2.9536, 0.388, 0]),
r44: Object.freeze([4.4219, -0.3001, 0]),
radio_mast: Object.freeze([1.2, 0, 0]),
s76: Object.freeze([6.6001, 0.1915, 0]),
sr22: Object.freeze([3.6762, 0.2376, 0]),
t38: Object.freeze([7.0246, -0.3791, 0]),
tex2: Object.freeze([4.7383, 0.2302, 0]),
tower: Object.freeze([1.2952, -0.0007, 0]),
ultralight: Object.freeze([3.2271, 0.3259, 0]),
v22: Object.freeze([7.9868, 0.2956, 0]),
van: Object.freeze([2.695, 0.2812, 0]),
});
+10 -1
View File
@@ -9,7 +9,6 @@ const flightsLayer = createApplicationFlights({
source: createFlightSource(),
militaryRegistry,
});
export { TRACKED_MODEL_MAX_PX } from '../layers/flights/policy.js';
export const _floorGroundedDisplayPositionForTest =
flightsLayer.testing._floorGroundedDisplayPositionForTest;
export const _clearDisplayFloorStateForTest =
@@ -40,5 +39,15 @@ export const _driveFleetModelHandoffForTest =
flightsLayer.testing._driveFleetModelHandoffForTest;
export const _ensureFleetModelForTest =
flightsLayer.testing._ensureFleetModelForTest;
export const _trackedModelForTest = flightsLayer.testing._trackedModelForTest;
export const _trackedIconLookForTest =
flightsLayer.testing._trackedIconLookForTest;
export const _modelSetIdsForTest = flightsLayer.testing._modelSetIdsForTest;
export const _iconForTest = flightsLayer.testing._iconForTest;
export const _setIconForTest = flightsLayer.testing._setIconForTest;
export const _floorGroundedIconsForTest =
flightsLayer.testing._floorGroundedIconsForTest;
export const _resetEnrichmentForTest =
flightsLayer.testing._resetEnrichmentForTest;
export const mapAnalystRecord = flightsLayer.mapAnalystRecord;
export default flightsLayer;
+448 -69
View File
@@ -1,8 +1,10 @@
// src/data/flights.test.mjs
// Focused tests for the pure analyst-record mapper (analyst query engine seam).
// Pure function — no viewer/DOM needed; imported directly.
import { test } from 'node:test';
import { after, afterEach, before, test } from 'node:test';
import assert from 'node:assert/strict';
import { followedOf } from './followed.js';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import * as Cesium from 'cesium';
import flightsLayer, {
_addFlightTrackingCandidateForTest,
@@ -14,9 +16,16 @@ import flightsLayer, {
_setTrackedFlightRefreshStateForTest,
_floorGroundedDisplayPositionForTest,
_clearDisplayFloorStateForTest,
_iconForTest,
_floorGroundedIconsForTest,
_resetEnrichmentForTest,
mapAnalystRecord,
} from './flights.js';
import { setMilitaryLayerActive } from './militaryRegistry.js';
import {
isMilitaryLayerActive,
registerMilitaryIcaos,
setMilitaryLayerActive,
} from './militaryRegistry.js';
import {
GROUND_FLOOR_LIFT_M,
reportMeshFloorCell,
@@ -30,6 +39,32 @@ import {
destroyTrackedReadout,
initTrackedReadout,
} from './trackedReadout.js';
import { readEntityRecord, withEntityRecord } from './entityRecords.js';
// Unit tests never reach the network. A test that tracks a plane queues its
// enrichment (type, route, photo), so every test ends on an empty queue, and a
// fetch of any absolute URL fails the test it happened in. A test that needs
// answers installs its own fetch and restores this one.
const nodeFetch = globalThis.fetch;
const networkRequests = [];
before(() => {
globalThis.fetch = async (url) => {
const href = String(url?.url ?? url);
if (/^https?:\/\//i.test(href)) networkRequests.push(href);
throw new TypeError(`Failed to parse URL from ${href}`);
};
});
afterEach(() => {
_resetEnrichmentForTest();
assert.deepEqual(
networkRequests.splice(0),
[],
'no test reaches the network',
);
});
after(() => {
globalThis.fetch = nodeFetch;
});
test('share-Follow absence requires an accepted OpenSky snapshot', async () => {
_setFlightTrackingRefreshOutcomeForTest({ status: 'source-unavailable' });
@@ -56,6 +91,8 @@ const FULL_INFO = {
verticalRate: -4.5,
onGround: false,
klass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
airline: 'Southwest Airlines',
route: { origin: { code: 'AUS' }, destination: { code: 'LAX' } },
@@ -79,6 +116,8 @@ test('flights analyst record: full record maps every contract field', () => {
onGround: false,
military: false,
aircraftClass: 'airliner',
typeCode: 'B738',
category: 'A3',
originCountry: 'United States',
operator: 'Southwest Airlines',
squawk: null,
@@ -89,6 +128,9 @@ test('flights analyst record: full record maps every contract field', () => {
lastContactAtMs: null,
routeOrigin: 'AUS',
routeDestination: 'LAX',
routeFrom: null,
routeTo: null,
routeScheduled: null,
});
});
@@ -186,9 +228,12 @@ test('flights first update forwards caller cancellation into the feed request',
test('nonempty OpenSky payload with zero usable rows cannot prove share target absence', async () => {
_setTrackedFlightRefreshStateForTest({
icao24: 'abc123',
entity: { gevLabelModel: { title: 'WARM', details: [] } },
billboard: { show: false },
billboardCollection: { show: true, remove() {} },
entity: withEntityRecord(
{},
{ labelModel: { title: 'WARM', details: [] } },
),
icon: { show: false },
iconLayer: { show: true, remove() {} },
viewer: { camera: { positionCartographic: null }, scene: {} },
meta: { rawLat: 30.2, rawLon: -97.7, onGround: false },
});
@@ -226,27 +271,18 @@ test('nonempty OpenSky payload with zero usable rows cannot prove share target a
test('a newly seen aircraft appears at its delayed position, not ahead of it', async () => {
// The fleet renders RENDER_DELAY_SEC behind real time, so a fresh contact's
// first displayed position is its fix projected back to that delayed time.
// Creating the billboard at the raw fix drew it ahead until the next fleet
// Creating the icon at the raw fix drew it ahead until the next fleet
// tick, which then jumped it back about one delay of travel.
const added = [];
const billboardCollection = {
show: false,
add(options) {
const billboard = { ...options };
added.push(billboard);
return billboard;
},
remove() {},
};
const iconLayer = { show: false };
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24: 'seed00',
entity: null,
billboard: {
icon: {
show: false,
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
billboardCollection,
iconLayer,
viewer,
meta: { rawLat: 0, rawLon: 0, onGround: false },
tracked: false,
@@ -294,9 +330,9 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a
};
try {
await flightsLayer.update(viewer);
const billboard = added.find((entry) => entry.id === icao24);
assert.ok(billboard, 'the new contact gets a billboard');
const shown = Cesium.Cartographic.fromCartesian(billboard.position);
const icon = _iconForTest(icao24);
assert.ok(icon, 'the new contact gets an icon');
const shown = Cesium.Cartographic.fromCartesian(icon.position);
const fix = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_700);
const behindM = Cesium.Cartesian3.distance(
Cesium.Cartesian3.fromRadians(shown.longitude, shown.latitude, 10_700),
@@ -319,19 +355,22 @@ test('a newly seen aircraft appears at its delayed position, not ahead of it', a
test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STALE', async () => {
const icao24 = 'a1b2c3';
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord(
{},
{ labelModel: { title: 'OLD', details: [] } },
);
const billboard = {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
show: false,
};
const billboardCollection = { show: false, remove() {} };
const iconLayer = { show: false, remove() {} };
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24,
entity,
billboard,
billboardCollection,
icon: billboard,
iconLayer,
viewer,
meta: {
callsign: 'OLD1',
@@ -390,13 +429,22 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA
try {
await flightsLayer.update(viewer);
assert.equal(entity.gevLabelModel.title, 'DAL123');
assert.match(entity.gevLabelModel.details.join(' · '), /FL350/);
assert.match(entity.gevLabelModel.details.join(' · '), /486 kts/);
assert.equal(readEntityRecord(entity)?.labelModel.title, 'DAL123');
assert.match(
readEntityRecord(entity)?.labelModel.details.join(' · '),
/FL350/,
);
assert.match(
readEntityRecord(entity)?.labelModel.details.join(' · '),
/486 kts/,
);
await flightsLayer.update(viewer);
assert.match(
[entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '),
[
readEntityRecord(entity)?.labelModel.title,
...readEntityRecord(entity)?.labelModel.details,
].join(' · '),
/STALE/,
);
} finally {
@@ -404,6 +452,232 @@ test('flights poll refreshes tracked callsign/FL/kts and marks a missed poll STA
}
});
test('a tracked plane whose photo lookup failed asks again on the first poll after the cool-down', async (t) => {
const icao24 = 'b2c3d4';
const realNow = Date.now.bind(Date);
let offsetMs = 0;
t.mock.method(Date, 'now', () => realNow() + offsetMs);
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24,
entity,
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
show: false,
},
billboardCollection: { show: false, remove() {} },
viewer,
meta: {
callsign: 'UAL9',
altitude: 9_000,
renderAltitudeM: 9_050,
velocity: 180,
true_track: 80,
klass: 'airliner',
onGround: false,
wasAirborne: true,
turnRateDps: 0,
rawLat: 30.2,
rawLon: -97.7,
},
});
let callsign = 'UAL9 ';
const photoRequests = [];
const routeRequests = [];
const guardFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
url = String(url);
if (url.startsWith('https://api.planespotters.net/')) {
photoRequests.push(url);
return { ok: false, status: 503, json: async () => ({}) };
}
if (url.startsWith('/api/adsbdb/route/UAL')) routeRequests.push(url);
if (!url.startsWith('/api/flights'))
return { ok: true, status: 200, json: async () => ({ found: false }) };
const nowSec = Math.floor(Date.now() / 1000);
return {
ok: true,
status: 200,
headers: { get: () => null },
json: async () => ({
time: nowSec,
states: [
[
icao24,
callsign,
'United States',
nowSec,
nowSec,
-97.6,
30.3,
10_668,
false,
250,
95,
5,
null,
10_700,
null,
null,
null,
5,
],
],
}),
};
};
// Lookups drip out one per 200 ms. Wait for what must arrive (with a
// generous deadline, so a loaded machine cannot fail it), then a little
// longer so anything that must NOT arrive would have.
const until = async (ready) => {
const deadline = realNow() + 5_000;
while (!ready() && realNow() < deadline)
await new Promise((done) => setTimeout(done, 20));
await new Promise((done) => setTimeout(done, 450));
};
try {
await flightsLayer.update(viewer);
await until(() => photoRequests.length >= 1 && routeRequests.length >= 1);
assert.equal(photoRequests.length, 1, 'the first poll asks for the photo');
assert.deepEqual(routeRequests, ['/api/adsbdb/route/UAL9']);
// Well inside the 60 s cool-down, and well past it below, so real time
// spent between polls cannot move either side across the line.
offsetMs += 30_000;
callsign = 'UAL10 ';
await flightsLayer.update(viewer);
await until(() => routeRequests.length >= 2);
assert.equal(photoRequests.length, 1, 'not within the cool-down');
assert.deepEqual(
routeRequests,
['/api/adsbdb/route/UAL9', '/api/adsbdb/route/UAL10'],
'the route follows the callsign the poll just recorded',
);
offsetMs += 60_000;
await flightsLayer.update(viewer);
await until(() => photoRequests.length >= 2);
assert.deepEqual(
photoRequests,
[
'https://api.planespotters.net/pub/photos/hex/b2c3d4',
'https://api.planespotters.net/pub/photos/hex/b2c3d4',
],
'asked again on the first poll after the cool-down',
);
} finally {
globalThis.fetch = guardFetch;
// The moved clock dated this layer's dispatch and cool-downs into the
// future; reset before the real clock comes back.
_resetEnrichmentForTest();
t.mock.restoreAll();
}
});
test('a known-military aircraft tracked in the flights layer is never looked up and shows no photo', async () => {
const icao24 = 'ae5e01';
// The registry has no way to forget one hex (only a whole-registry reset,
// which would also drop its source), so the test uses a hex no other test
// reads and restores the layer-active flag it changes.
const militaryWasActive = isMilitaryLayerActive();
registerMilitaryIcaos([icao24]);
setMilitaryLayerActive(false);
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24,
entity: { gevLabelModel: { title: 'OLD', details: [] } },
billboard: {
position: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 9_000),
color: Cesium.Color.WHITE,
show: false,
},
billboardCollection: { show: false, remove() {} },
viewer,
meta: {
callsign: 'RCH123',
altitude: 9_000,
renderAltitudeM: 9_050,
velocity: 180,
true_track: 80,
klass: 'airliner',
onGround: false,
wasAirborne: true,
turnRateDps: 0,
rawLat: 30.2,
rawLon: -97.7,
// Even a photo already on the record is never shown.
photo: {
src: 'https://t.plnspttrs.net/1/ae5e01_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/x',
},
},
});
const photoRequests = [];
const routeRequests = [];
const guardFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
url = String(url);
if (url.startsWith('https://api.planespotters.net/')) {
photoRequests.push(url);
return { ok: false, status: 503, json: async () => ({}) };
}
if (url.startsWith('/api/adsbdb/route/')) routeRequests.push(url);
if (!url.startsWith('/api/flights'))
return { ok: true, status: 200, json: async () => ({ found: false }) };
const nowSec = Math.floor(Date.now() / 1000);
return {
ok: true,
status: 200,
headers: { get: () => null },
json: async () => ({
time: nowSec,
states: [
[
icao24,
'RCH123 ',
'United States',
nowSec,
nowSec,
-97.6,
30.3,
10_668,
false,
250,
95,
5,
null,
10_700,
null,
null,
null,
5,
],
],
}),
};
};
try {
await flightsLayer.update(viewer);
// A photo lookup would go out ahead of the route; wait for the route.
const deadline = Date.now() + 5_000;
while (!routeRequests.length && Date.now() < deadline)
await new Promise((done) => setTimeout(done, 20));
assert.deepEqual(routeRequests, ['/api/adsbdb/route/RCH123']);
assert.deepEqual(photoRequests, [], 'no photo lookup for a military hex');
assert.equal(flightsLayer.getTrackedInfo()?.icao24, icao24);
assert.equal(flightsLayer.getTrackedInfo()?.photo, null);
assert.equal(flightsLayer.getTrackedSubject()?.photo, null);
} finally {
globalThis.fetch = guardFetch;
setMilitaryLayerActive(militaryWasActive);
}
});
test('real civil track path creates no native label and publishes every cached host line', async () => {
const icao24 = 'civ001';
const position = Cesium.Cartesian3.fromDegrees(-97.6699, 30.1945, 10_668);
@@ -447,6 +721,7 @@ test('real civil track path creates no native label and publishes every cached h
},
});
viewer.scene.camera = viewer.camera;
bindFakeCesiumCamera(viewer);
const billboard = {
position,
rotation: 0.3,
@@ -481,8 +756,8 @@ test('real civil track path creates no native label and publishes every cached h
_setTrackedFlightRefreshStateForTest({
icao24,
entity: null,
billboard,
billboardCollection: { show: true, remove() {} },
icon: billboard,
iconLayer: { show: true, remove() {} },
viewer,
tracked: false,
history: [
@@ -520,16 +795,27 @@ test('real civil track path creates no native label and publishes every cached h
flightsLayer.trackById(icao24, { origin: 'programmatic' }),
true,
);
const entity = viewer.trackedEntity;
const entity = followedOf(viewer)?.entity;
assert.ok(
entity instanceof Cesium.Entity,
'trackById must create the real Cesium entity',
readEntityRecord(entity)?.trackedId,
'trackById must record the tracked contact',
);
assert.ok(
!(entity instanceof Cesium.Entity),
'tracking draws through the draw port, not a viewer entity',
);
assert.ok(entity.position, 'Cockpit sees a contact it can fly');
assert.equal(readEntityRecord(entity).drawn(), true);
assert.ok(
Array.isArray(readEntityRecord(entity).groundSets()),
'Cockpit asks which draw sets its ground probe sees through',
);
assert.equal(entity.show, true);
assert.equal(entity.label, undefined);
assert.ok(
entities.values.every((candidate) => candidate.label === undefined),
);
assert.deepEqual(entity.gevLabelModel, {
assert.deepEqual(readEntityRecord(entity)?.labelModel, {
title: 'N12345 · FL350 · 486 kts',
details: ['TEST AIR · A320', 'AUS → LAX'],
accent: '#39d0ff',
@@ -548,7 +834,7 @@ test('real civil track path creates no native label and publishes every cached h
'user',
'same-target selection upgrades durable authority',
);
assert.equal(entity.gevSelectionOrigin, 'user');
assert.equal(readEntityRecord(entity)?.selectionOrigin, 'user');
assert.equal(flightsLayer.refocusTrackedById('different-flight'), false);
assert.equal(
flightsLayer.refocusTrackedById(icao24, { origin: 'voice' }),
@@ -562,7 +848,7 @@ test('real civil track path creates no native label and publishes every cached h
assert.equal(flightsLayer.refocusTrackedById(icao24), true);
viewer.scene.preUpdate.raiseEvent();
assert.equal(
viewer.trackedEntity,
followedOf(viewer)?.entity,
entity,
'refocus must retain the exact tracked entity',
);
@@ -581,11 +867,14 @@ test('real civil track path creates no native label and publishes every cached h
const entry = publication.entries[0];
assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'tracked');
assert.equal(entry.title, entity.gevLabelModel.title);
assert.deepEqual(entry.details, entity.gevLabelModel.details);
assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title);
assert.deepEqual(
entry.details,
readEntityRecord(entity)?.labelModel.details,
);
const display = entity.position.getValue(now);
assert.ok(display, 'tracked position callback must seed its frame cache');
const display = followedOf(viewer)?.position(Date.now());
assert.ok(display, 'the follow target must seed the frame cache');
assert.equal(
entry.position(),
display,
@@ -605,7 +894,7 @@ test('real civil track path creates no native label and publishes every cached h
);
_addFlightTrackingCandidateForTest({
icao24: 'late001',
billboard: {
icon: {
...billboard,
position: Cesium.Cartesian3.fromDegrees(-97.5, 30.4, 9_000),
},
@@ -629,7 +918,7 @@ test('real civil track path creates no native label and publishes every cached h
);
_addFlightTrackingCandidateForTest({
icao24: 'late002',
billboard: {
icon: {
...billboard,
position: Cesium.Cartesian3.fromDegrees(-97.4, 30.5, 8_000),
},
@@ -652,7 +941,7 @@ test('real civil track path creates no native label and publishes every cached h
);
_addFlightTrackingCandidateForTest({
icao24: 'late003',
billboard: {
icon: {
...billboard,
position: Cesium.Cartesian3.fromDegrees(-97.3, 30.6, 7_000),
},
@@ -669,7 +958,7 @@ test('real civil track path creates no native label and publishes every cached h
assert.equal(_pendingFlightTrackingRestoreForTest(), 'late004');
_addFlightTrackingCandidateForTest({
icao24: 'late004',
billboard: {
icon: {
...billboard,
position: Cesium.Cartesian3.fromDegrees(-97.2, 30.7, 6_000),
},
@@ -694,7 +983,7 @@ test('real civil track path creates no native label and publishes every cached h
);
_addFlightTrackingCandidateForTest({
icao24: 'late005',
billboard: {
icon: {
...billboard,
position: Cesium.Cartesian3.fromDegrees(-97.1, 30.8, 5_000),
},
@@ -740,12 +1029,12 @@ function seedLabelContact({
_setTrackedFlightRefreshStateForTest({
icao24: LABEL_ICAO,
entity: null,
billboard: {
icon: {
position: LABEL_POSITION,
color: Cesium.Color.WHITE,
show: true,
},
billboardCollection: { show: true, remove() {} },
iconLayer: { show: true, remove() {} },
viewer: { camera: { positionCartographic: null }, scene: {} },
tracked,
meta: {
@@ -943,17 +1232,20 @@ test('civil label chain: the awareness selection EVENT uses the canonical chain'
});
test('civil tracked readout: a callsign-less enriched contact reads as its registration', async () => {
const entity = { gevLabelModel: { title: 'OLD', details: [] } };
const entity = withEntityRecord(
{},
{ labelModel: { title: 'OLD', details: [] } },
);
seedLabelContact({ callsign: ' ', registration: ' N123AB ', tracked: true });
_setTrackedFlightRefreshStateForTest({
icao24: LABEL_ICAO,
entity,
billboard: {
icon: {
position: LABEL_POSITION,
color: Cesium.Color.WHITE,
show: false,
},
billboardCollection: { show: false, remove() {} },
iconLayer: { show: false, remove() {} },
viewer: { camera: { positionCartographic: null }, scene: {} },
meta: {
callsign: ' ',
@@ -983,9 +1275,12 @@ test('civil tracked readout: a callsign-less enriched contact reads as its regis
camera: { positionCartographic: null },
scene: {},
});
assert.match(entity.gevLabelModel.title, /^N123AB\b/);
assert.match(readEntityRecord(entity)?.labelModel.title, /^N123AB\b/);
assert.doesNotMatch(
[entity.gevLabelModel.title, ...entity.gevLabelModel.details].join(' · '),
[
readEntityRecord(entity)?.labelModel.title,
...readEntityRecord(entity)?.labelModel.details,
].join(' · '),
/ae1fa4/,
);
} finally {
@@ -1067,30 +1362,21 @@ const _floorCarto = (pos) =>
test('a newly seen taxiing aircraft starts on the floor under its delayed position', async () => {
// A grounded contact is drawn at its delayed position lifted onto the floor
// under it. Creating the billboard without that lift started it on the
// under it. Creating the icon without that lift started it on the
// floor of its reported fix, then the next fleet tick raised it.
_clearDisplayFloorStateForTest();
_clearMeshFloorCellsForTest();
setMeshFloorPreferred(true);
const added = [];
const billboardCollection = {
show: false,
add(options) {
const billboard = { ...options };
added.push(billboard);
return billboard;
},
remove() {},
};
const iconLayer = { show: false };
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24: 'seed00',
entity: null,
billboard: {
icon: {
show: false,
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
billboardCollection,
iconLayer,
viewer,
meta: { rawLat: 0, rawLon: 0, onGround: false },
tracked: false,
@@ -1143,9 +1429,9 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi
};
try {
await flightsLayer.update(viewer);
const billboard = added.find((entry) => entry.id === icao24);
assert.ok(billboard, 'the new contact gets a billboard');
const shown = _floorCarto(billboard.position);
const icon = _iconForTest(icao24);
assert.ok(icon, 'the new contact gets an icon');
const shown = _floorCarto(icon.position);
assert.ok(
Cesium.Math.toDegrees(shown.longitude) < fixLon,
'drawn behind the fix',
@@ -1161,6 +1447,99 @@ test('a newly seen taxiing aircraft starts on the floor under its delayed positi
}
});
test('far grounded contacts take turns on the floor; near ones refloor every tick', async () => {
// The floor pass is the fleet tick's only per-contact CPU work. Past
// FLOOR_NEAR_M a contact is refloored once per FLOOR_FAR_EVERY_TICKS.
_clearDisplayFloorStateForTest();
_clearMeshFloorCellsForTest();
setMeshFloorPreferred(true);
const viewer = { camera: { positionCartographic: null }, scene: {} };
_setTrackedFlightRefreshStateForTest({
icao24: 'seed00',
entity: null,
icon: {
show: false,
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
iconLayer: { show: false },
viewer,
meta: { rawLat: 0, rawLon: 0, onGround: false },
tracked: false,
});
const icao24 = 'taxi02';
const fixLon = -97.66;
const fixLat = 30.2;
for (let k = -40; k <= 40; k += 1) {
reportMeshFloorCell(fixLat, fixLon + k * 0.0001, 131.5);
}
const nowSec = Math.floor(Date.now() / 1000);
const realFetch = globalThis.fetch;
globalThis.fetch = async (url) => {
if (!String(url).startsWith('/api/flights')) {
return { ok: true, status: 200, json: async () => ({ ac: [] }) };
}
return {
ok: true,
status: 200,
headers: { get: () => null },
json: async () => ({
time: nowSec,
states: [
[
icao24,
'TAXI02 ',
'United States',
nowSec - 2,
nowSec - 2,
fixLon,
fixLat,
null,
true,
10,
90,
0,
null,
null,
null,
null,
null,
5,
],
],
}),
};
};
try {
await flightsLayer.update(viewer);
// A grounded report holds once its time is past, so the ticks run in
// the 40 s before it, while the contact still taxis toward its fix.
const start = Cesium.JulianDate.fromDate(
new Date((nowSec - 2 - 40) * 1000),
);
const at = (s) =>
Cesium.JulianDate.addSeconds(start, s, new Cesium.JulianDate());
const far = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 3_000_000);
const near = Cesium.Cartesian3.fromDegrees(fixLon, fixLat, 10_000);
let last = _iconForTest(icao24).position;
const moves = (camera, from, to) => {
let count = 0;
for (let tick = from; tick <= to; tick += 1) {
_floorGroundedIconsForTest(at(tick), camera);
const now = _iconForTest(icao24).position;
if (Cesium.Cartesian3.distance(now, last) > 1) count += 1;
last = now;
}
return count;
};
assert.equal(moves(far, 1, 24), 2, 'far: once per 12 ticks');
assert.equal(moves(near, 25, 30), 6, 'near: every tick');
} finally {
globalThis.fetch = realFetch;
_clearMeshFloorCellsForTest();
_clearDisplayFloorStateForTest();
}
});
test('display floor: a grounded contact that drifted onto a higher cell is lifted', () => {
_clearDisplayFloorStateForTest();
_clearMeshFloorCellsForTest();
+1 -1
View File
@@ -23,6 +23,6 @@ test('converged focus treatment stays within the GC-bracketed allocation budget'
assert.equal(result.status, 0, result.stderr || result.stdout);
const report = JSON.parse(result.stdout.trim());
assert.ok(report.advanceSpriteFocus.roundedMedian <= 16, result.stdout);
assert.ok(report.applyAircraftBillboardTreatment.roundedMedian <= 16, result.stdout);
assert.ok(report.aircraftTreatmentAlpha.roundedMedian <= 16, result.stdout);
assert.ok(report.productionSpriteTick.roundedMedian <= 212, result.stdout);
});
+48 -85
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { findCamera, findQuery } from '../render/rendererOf.js';
/**
* Focus-aware sprite treatment shared by the live contact layers.
@@ -30,7 +30,6 @@ export const DEFAULT_FOCUS_DEEMPHASIS_PARAMS = Object.freeze({
let _params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS };
let _focusTarget = null;
const _spriteStates = new WeakMap();
const _scratchScreen = new Cesium.Cartesian2();
const _advanceResult = {
factor: 1,
changed: false,
@@ -172,47 +171,76 @@ export function resetFocusDeemphasisParams() {
/**
* Publish a focus target from the exact world position already cached by its
* tracking/render path. Callers must never re-derive a position here: a second
* tracking/render path, through the renderer bound to `viewer`: its query
* port projects the position and its camera's pose gives the distance.
* Callers must never re-derive a position here: a second
* propagation/dead-reckoning sample at a different frame phase recreates the
* tracked-target jitter class this service is designed to avoid.
*
* @param {object} input
* @param {string} input.ownerLayer
* @param {string|number} input.id
* @param {Cesium.Scene} input.scene
* @param {Cesium.Camera} input.camera
* @param {Cesium.Cartesian3} input.displayPosition Cached display position.
* @param {number} [input.widthPx=24] Projected visual width before padding.
* @param {number} [input.heightPx=24] Projected visual height before padding.
* @param {object} input.viewer The host the renderer is bound to.
* @param {{x: number, y: number, z: number}} input.displayPosition Cached display position.
* @param {number} [input.widthPx=24]
* @param {number} [input.heightPx=24]
* @param {Partial<typeof DEFAULT_FOCUS_DEEMPHASIS_PARAMS>} [input.params]
* @returns {object|null} Published target, or null when it cannot be projected.
*/
export function publishFocusTargetFromCachedPosition({
export function publishFocusTargetAt({
ownerLayer,
id,
scene,
camera,
viewer,
displayPosition,
widthPx = 24,
heightPx = 24,
params,
}) {
const query = viewer ? findQuery(viewer) : null;
let eye = null;
try {
eye = viewer ? (findCamera(viewer)?.pose().position ?? null) : null;
} catch {
eye = null;
}
if (
!ownerLayer ||
id === null ||
id === undefined ||
!scene ||
!camera ||
!query ||
!eye ||
!displayPosition
) {
clearFocusTarget(ownerLayer, id);
return null;
}
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
displayPosition,
_scratchScreen,
);
return publishFocusRect({
ownerLayer,
id,
screen: query.project(displayPosition),
cameraDistance: Math.hypot(
displayPosition.x - eye.x,
displayPosition.y - eye.y,
displayPosition.z - eye.z,
),
frameNumber: -1,
widthPx,
heightPx,
params,
});
}
/** Publish the focus rectangle around `screen`, or clear it when there is none. */
function publishFocusRect({
ownerLayer,
id,
screen,
cameraDistance,
frameNumber,
widthPx,
heightPx,
params,
}) {
if (!screen || !Number.isFinite(screen.x) || !Number.isFinite(screen.y)) {
clearFocusTarget(ownerLayer, id);
return null;
@@ -232,11 +260,8 @@ export function publishFocusTargetFromCachedPosition({
bottom: screen.y + halfHeight + padding,
},
paddingPx: padding,
cameraDistance: Cesium.Cartesian3.distance(
camera.positionWC,
displayPosition,
),
frameNumber: scene.frameState?.frameNumber ?? -1,
cameraDistance,
frameNumber,
};
if (appeared) {
for (const listener of _focusAppearListeners) {
@@ -440,68 +465,6 @@ export function advanceSpriteFocus(
return _advanceResult;
}
/**
* Project and advance one world-anchored sprite using an owning layer's
* existing render pass.
* @param {object} sprite Stable primitive identity.
* @param {Cesium.Cartesian3} position Current cached/rendered world position.
* @param {Cesium.Scene} scene
* @param {Cesium.Camera} camera
* @param {number} nowMs
* @param {object|null} [target]
* @param {Partial<typeof DEFAULT_FOCUS_DEEMPHASIS_PARAMS>} [params]
* @param {number} [spriteHalfWidthPx=0]
* @param {number} [spriteHalfHeightPx=spriteHalfWidthPx]
* @returns {{factor:number, changed:boolean, transitioning:boolean,active:boolean,desired:number}}
*/
export function advanceProjectedSpriteFocus(
sprite,
position,
scene,
camera,
nowMs,
target = _focusTarget,
params,
spriteHalfWidthPx = 0,
spriteHalfHeightPx = spriteHalfWidthPx,
) {
// Common case: nothing tracked and this sprite holds no dimming state —
// advanceSpriteFocus would return identity without reading the projection,
// so skip the worldToWindowCoordinates round trip entirely (it was N
// wasted projections per fleet tick with nothing tracked). Sprites still
// relaxing keep their state entry until fully settled (see the delete at
// the transition tail), so they keep projecting until done. (perf item 8)
if (!target && !_spriteStates.has(sprite)) {
_advanceResult.factor = 1;
_advanceResult.changed = false;
_advanceResult.transitioning = false;
_advanceResult.active = false;
_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;
return advanceSpriteFocus(sprite, {
screenPosition: screen,
cameraDistance,
nowMs,
target,
params,
spriteHalfWidthPx,
spriteHalfHeightPx,
});
}
/**
* A gated consumer must keep ticking until every previously dimmed sprite has
* returned to identity, even when no target remains.
+44 -35
View File
@@ -4,6 +4,8 @@ import { applyVesselFocusDeemphasis } from './aisLiveVessels.js';
import { applyCctvFocusDeemphasis } from './cctv.js';
import { applySatellitePointFocusDeemphasis } from './satellites.js';
import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js';
import { createIconBook } from '../render/motion/iconBook.js';
import { createVesselIconBook } from '../layers/vessels/iconBook.js';
const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 };
const target = {
@@ -27,7 +29,11 @@ function assertResumeGate(name, makePass) {
const { pass, readAlpha } = makePass();
let activeCount = 0;
const tick = (nowMs, focusTarget) => {
const result = pass({ nowMs, target: focusTarget, previousActiveCount: activeCount });
const result = pass({
nowMs,
target: focusTarget,
previousActiveCount: activeCount,
});
activeCount = result.activeCount;
return result;
};
@@ -38,7 +44,11 @@ function assertResumeGate(name, makePass) {
assert.equal(readAlpha(), params.dimFloor);
const releaseStart = tick(params.attackMs + 1, null);
assert.equal(releaseStart.ran, true, 'active count keeps the no-target release pass alive');
assert.equal(
releaseStart.ran,
true,
'active count keeps the no-target release pass alive',
);
assert.equal(releaseStart.activeCount, 1);
const restored = tick(params.attackMs + params.releaseMs + 2, null);
@@ -46,71 +56,71 @@ function assertResumeGate(name, makePass) {
assert.equal(restored.activeCount, 0);
assert.equal(readAlpha(), 1);
assert.equal(tick(params.attackMs + params.releaseMs + 82, null).ran, false);
assert.equal(
tick(params.attackMs + params.releaseMs + 82, null).ran,
false,
);
});
}
assertResumeGate('vessel', () => {
const billboard = {
const icons = createVesselIconBook();
icons.put({ id: '353136000', size: [32, 32], meta: { id: '353136000' } });
const record = {
iconId: '353136000',
position: { x: 1, y: 2, z: 3 },
show: true,
width: 32,
height: 32,
scale: 1,
color: color(),
visible: true,
};
return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) => (
pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
applyVesselFocusDeemphasis({
records: [{ billboard }],
records: [record],
icons,
target: focusTarget,
previousActiveCount,
nowMs,
screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200,
params,
})
),
readAlpha: () => billboard.color.alpha,
}),
readAlpha: () => icons.focus('353136000'),
};
});
assertResumeGate('CCTV', () => {
const billboard = {
position: { x: 1, y: 2, z: 3 },
show: true,
width: 24,
height: 24,
scale: 1,
color: color(),
};
const record = { camera: { id: 'cam-1' }, billboard };
const icons = createIconBook();
icons.put({
id: 'cam-1',
pos: { x: 1, y: 2, z: 3 },
size: [24, 24],
meta: { id: 'cam-1' },
});
const record = { camera: { id: 'cam-1' }, position: { x: 1, y: 2, z: 3 } };
return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) => (
pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
applyCctvFocusDeemphasis({
records: [record],
icons,
target: focusTarget,
previousActiveCount,
nowMs,
screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200,
baseColorFor: () => color(),
params,
})
),
readAlpha: () => billboard.color.alpha,
}),
readAlpha: () => icons.focus('cam-1'),
};
});
assertResumeGate('satellite', () => {
const point = {
position: { x: 1, y: 2, z: 3 },
pos: { x: 1, y: 2, z: 3 },
show: true,
pixelSize: 6,
color: color(),
color: [1, 1, 1, 1],
};
return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) => (
pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
applySatellitePointFocusDeemphasis({
points: new Map([[42, point]]),
trackedId: null,
@@ -119,10 +129,9 @@ assertResumeGate('satellite', () => {
nowMs,
screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200,
baseColorFor: () => color(),
baseColorFor: () => [1, 1, 1, 1],
params,
})
),
readAlpha: () => point.color.alpha,
}),
readAlpha: () => point.color[3],
};
});
+172
View File
@@ -0,0 +1,172 @@
/**
* @module data/followed
* @description What the camera follows, for the code that reads it.
*
* A layer follows through the camera port with a FollowTarget that also
* carries what the app shows about it (key, display position, sprite, label).
* A layer that keeps its target as a holder of its own (an entity record)
* follows through the port with `entityFollowTarget`, whose presentation
* fields read that record. Readers ask this module, never the renderer.
*
* Its readers (the tracked card, Cockpit, the share link's thing view,
* north-up) read where the target is shown (`followedPosition`): its
* `displayPosition`, else its own `position` at scene time.
*/
import { findCamera, findFrame } from '../render/rendererOf.js';
import { readEntityRecord } from './entityRecords.js';
/**
* @typedef {object} Followed
* @property {string|null} key Stable id, e.g. `'flights:a1b2c3'`.
* @property {string} [name] Display name, when the target has one.
* @property {() => object|null} [displayPosition] Where the follow camera
* frames the target this frame (the layer's display cache).
* @property {() => object|null} [visualPosition] Where the target is drawn.
* @property {object} [sprite] Size of the drawn billboard.
* @property {object} [labelModel]
* @property {string} [selectionOrigin]
* @property {object} [entity] The holder whose entity record the
* presentation fields read (`entityFollowTarget`).
*/
/** @type {WeakMap<object, Followed>} */
const entityViews = new WeakMap();
function entityView(entity) {
let view = entityViews.get(entity);
if (!view) {
const id = String(entity.id ?? '').trim();
view = {
entity,
get key() {
const explicit = String(readEntityRecord(entity)?.trackedId ?? '');
return explicit.trim() || (id ? `entity:${id}` : null);
},
get name() {
return entity.name;
},
get displayPosition() {
return readEntityRecord(entity)?.displayPosition;
},
get visualPosition() {
return readEntityRecord(entity)?.visualPosition;
},
get sprite() {
return readEntityRecord(entity)?.sprite;
},
get labelModel() {
return readEntityRecord(entity)?.labelModel;
},
get selectionOrigin() {
return readEntityRecord(entity)?.selectionOrigin;
},
};
entityViews.set(entity, view);
}
return view;
}
/**
* What `viewer`'s camera follows, or null. The same object comes back for
* as long as the same thing is followed.
* @param {object|null|undefined} viewer
* @returns {Followed|null}
*/
export function followedOf(viewer) {
if (!viewer) return null;
return findCamera(viewer)?.followed ?? null;
}
/** Whether `viewer`'s camera follows anything. */
export function isFollowing(viewer) {
return followedOf(viewer) !== null;
}
/**
* Run `cb` whenever what `viewer`'s camera follows changes.
* @param {object} viewer
* @param {(followed: Followed|null) => void} cb
* @returns {() => void} Off.
*/
export function onFollowChanged(viewer, cb) {
let last = followedOf(viewer);
let port = null;
let offPort = null;
// The port is looked up again on every change: a renderer bound after
// this subscribed replaces the one it listened to.
const listenToPort = () => {
const current = findCamera(viewer);
if (current === port) return;
offPort?.();
port = current;
offPort = port?.on('followChanged', check) ?? null;
};
function check() {
listenToPort();
const now = followedOf(viewer);
if (now === last) return;
last = now;
cb(now);
}
listenToPort();
return () => {
offPort?.();
offPort = null;
};
}
/** Stop the camera following anything. */
export function stopFollowing(viewer) {
if (!viewer) return;
const camera = findCamera(viewer);
if (camera?.followed) camera.follow(null);
}
/**
* A FollowTarget for a layer that draws its target as an entity of its own:
* the camera fields given (`position`, `viewFrom`, `frame`, `minRange`, ...)
* plus what the app shows about it, read live from the entity's record, so the
* layer keeps writing that record as before. `entity` is the drawn entity.
* @param {object} entity
* @param {object} camera The FollowTarget's camera fields.
* @returns {Followed & object}
*/
export function entityFollowTarget(entity, camera) {
const target = Object.create(entityView(entity));
// Defined, not assigned: the record's fields are getters, and a camera
// field of the same name (`key`, say) takes their place.
for (const [name, value] of Object.entries(camera))
Object.defineProperty(target, name, {
value,
enumerable: true,
writable: true,
configurable: true,
});
return target;
}
/**
* Follow `followed` again after `stopFollowing`, through the camera port.
* @param {object} viewer
* @param {Followed|null} followed What `followedOf` gave.
*/
export function resumeFollowing(viewer, followed) {
if (!viewer || !followed) return;
findCamera(viewer)?.follow(followed);
}
/**
* Where `followed` is shown this frame: the layer's display cache, else the
* target's own position at the frame port's scene time; null when neither
* answers.
* @param {object} viewer
* @param {Followed|null} followed
*/
export function followedPosition(viewer, followed) {
const display = followed?.displayPosition;
const shown = typeof display === 'function' ? display() : null;
if (shown) return shown;
if (typeof followed?.position !== 'function') return null;
const time = findFrame(viewer)?.time?.();
return followed.position(Number.isFinite(time) ? time : Date.now()) || null;
}
+129
View File
@@ -0,0 +1,129 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { entityRecord } from './entityRecords.js';
import {
entityFollowTarget,
followedOf,
followedPosition,
isFollowing,
onFollowChanged,
resumeFollowing,
stopFollowing,
} from './followed.js';
import { bindRenderer } from '../render/rendererOf.js';
import { createCameraEvents } from '../render/camera/events.js';
import { createStubRenderer } from '../render/stub/index.js';
/** A camera port that follows, for a viewer bound to a renderer. */
function followingPort() {
const events = createCameraEvents({ pose: () => ({}), report: () => {} });
let followed = null;
return {
on: (event, cb) => events.on(event, cb),
get followed() {
return followed;
},
follow(target) {
if (followed === target) return;
followed = target;
events.emit('followChanged');
},
};
}
test('what the camera port follows is the target itself', (t) => {
const viewer = {};
assert.equal(followedOf(viewer), null, 'nothing without a renderer');
const camera = followingPort();
t.after(bindRenderer(viewer, { camera }));
assert.equal(followedOf(viewer), null);
assert.equal(isFollowing(viewer), false);
const target = { key: 'flights:abc', position: () => null };
camera.follow(target);
assert.equal(followedOf(viewer), target);
assert.equal(isFollowing(viewer), true);
});
test('onFollowChanged fires once per change', (t) => {
const viewer = {};
const camera = followingPort();
t.after(bindRenderer(viewer, { camera }));
const seen = [];
const off = onFollowChanged(viewer, (f) => seen.push(f?.key ?? null));
const target = { key: 'flights:abc' };
camera.follow(target);
camera.follow(target);
camera.follow(null);
off();
camera.follow({ key: 'after' });
assert.deepEqual(seen, ['flights:abc', null]);
});
test('stopFollowing ends a port follow', (t) => {
const viewer = {};
stopFollowing(viewer);
const camera = followingPort();
t.after(bindRenderer(viewer, { camera }));
camera.follow({ key: 'k' });
stopFollowing(viewer);
assert.equal(camera.followed, null);
stopFollowing(null);
});
test('an entity follow target reads its entity record live', () => {
const entity = new Cesium.Entity({ id: 'drawn', name: 'N2' });
const position = () => ({ x: 1, y: 2, z: 3 });
const target = entityFollowTarget(entity, { position, minRange: 150 });
assert.equal(target.key, 'entity:drawn');
entityRecord(entity).trackedId = 'flights:abc';
entityRecord(entity).labelModel = { title: 'N2' };
assert.equal(target.key, 'flights:abc');
assert.equal(target.labelModel.title, 'N2');
assert.equal(target.entity, entity);
assert.equal(target.position, position);
assert.equal(target.minRange, 150);
const keyed = entityFollowTarget(entity, { key: 'flights:given' });
assert.equal(keyed.key, 'flights:given', 'a camera field takes the place');
assert.equal(keyed.labelModel.title, 'N2');
});
test('resumeFollowing follows a port target again', (t) => {
const viewer = {};
const camera = followingPort();
t.after(bindRenderer(viewer, { camera }));
const target = entityFollowTarget(new Cesium.Entity({ id: 'p' }), {});
camera.follow(target);
stopFollowing(viewer);
resumeFollowing(viewer, target);
assert.equal(camera.followed, target);
resumeFollowing(viewer, null);
assert.equal(camera.followed, target);
});
test('followedPosition reads the display cache', () => {
const entity = new Cesium.Entity({ id: 'e' });
const view = entityFollowTarget(entity, {});
assert.equal(followedPosition({}, view), null, 'none without a cache');
entityRecord(entity).displayPosition = () => ({ x: 7, y: 8, z: 9 });
assert.deepEqual(followedPosition({}, view), { x: 7, y: 8, z: 9 });
assert.equal(followedPosition({}, null), null);
});
test('followedPosition falls back to the target position at scene time', () => {
const renderer = createStubRenderer();
const viewer = {};
bindRenderer(viewer, renderer);
renderer.frame.setTime(1234);
const seen = [];
const target = {
key: 't',
frame: 'enu',
viewFrom: { x: 0, y: 0, z: 1 },
position: (time) => (seen.push(time), { x: 1, y: 2, z: 3 }),
};
assert.deepEqual(followedPosition(viewer, target), { x: 1, y: 2, z: 3 });
assert.deepEqual(seen, [1234]);
target.displayPosition = () => ({ x: 4, y: 5, z: 6 });
assert.deepEqual(followedPosition(viewer, target), { x: 4, y: 5, z: 6 });
});
+43 -363
View File
@@ -1,23 +1,27 @@
/** Session-local geodata loading with bounded geometry and local-only file references. */
import * as Cesium from 'cesium';
import { createImportImageBudget } from './geoImportImages.js';
import { createImportedPins } from './geoImportPins.js';
import { readGeoJsonFeatures, readKmlFeatures } from './geoImportFeatures.js';
import { settleImportedDrawing } from './geoImportPins.js';
import {
GeoImportError,
MAX_IMPORT_ENTITIES,
boundedImport,
importFeatureName,
} from './geoImportShared.js';
import { msg } from '../i18n/marker.js';
export { GeoImportError, MAX_IMPORT_ENTITIES, importFeatureName };
/** Largest file accepted, in bytes. */
const MAX_IMPORT_BYTES = 50 * 1024 * 1024;
/** Largest total a KMZ may inflate to — a zip bomb stops here. */
const MAX_KMZ_INFLATED_BYTES = 120 * 1024 * 1024;
/** Most files on the globe at once. */
export const MAX_IMPORTED_FILES = 12;
/** Most entities one file may create before it is refused. */
export const MAX_IMPORT_ENTITIES = 20_000;
/** Most vertices (points of every line, ring and marker) in one file. */
export const MAX_IMPORT_POSITIONS = 250_000;
/** Most normalized style definitions and local image links in one KML/KMZ. */
const MAX_KML_LINKS = 2_000;
/** Longest plain-text name kept from a file's features. */
const MAX_IMPORT_NAME_LENGTH = 120;
/** What the file picker offers. */
export const GEO_FILE_ACCEPT = '.geojson,.json,.kml,.kmz,.gpx';
@@ -62,21 +66,6 @@ const KML_REMOVED_ELEMENTS = new Set([
'httpQuery',
]);
/**
* An error whose message is meant for the person who chose the file. The
* message stays English; `template` and `values`, when given, let the UI show
* it in the active language. Numbers stay numbers in `values`: the UI formats
* them in that language's numerals.
*/
export class GeoImportError extends Error {
constructor(message, template = message, values = {}) {
super(message);
this.name = 'GeoImportError';
this.template = template;
this.values = values;
}
}
/**
* The format of a file, from its name first and its first bytes second.
* @param {string} name File name.
@@ -212,8 +201,8 @@ export function countGeoJsonGeometry(
MultiPolygon: 3,
}[node.type];
if (depth !== undefined) {
// Multipart geometries create one Cesium entity per component, even
// when the document wraps them in just one Feature.
// Multipart geometries are one map object per component, even when
// the document wraps them in just one Feature.
entities += node.type.startsWith('Multi')
? Array.isArray(node.coordinates)
? node.coordinates.length
@@ -293,7 +282,7 @@ function overLimitError({ over, features }) {
}
// The import uses WGS84 ground footprints and a short name only. Remove
// loader-sensitive metadata before Cesium allocates properties or entity IDs.
// everything else before the features are read.
function prepareGeoJson(geojson) {
const stack = [geojson];
while (stack.length) {
@@ -520,7 +509,7 @@ export function kmzImageResolver(
* Strip everything from a parsed KML document that would make the page reach
* outside the file. `resolveLocal(href)` returns a URL for an image packed in
* the same KMZ (or null); every other href is removed, so icons fall back to
* Cesium's default pin and a ground overlay without a local image is dropped.
* the default pin and a ground overlay without a local image is dropped.
* @param {Document} doc
* @param {(href: string) => string|null} [resolveLocal]
* @returns {{removed: number}} How many elements were taken out.
@@ -534,8 +523,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
}
};
// One snapshot and pass, rather than rescanning the whole XML tree for
// every discarded element type. Strip unused metadata before the loader
// constructs descriptions, availability intervals and camera objects.
// every discarded element type. Strip unused metadata (descriptions,
// times and cameras) before the features are read.
for (const el of [...doc.getElementsByTagName('*')])
if (
KML_REMOVED_ELEMENTS.has(el.localName) ||
@@ -557,8 +546,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
drop(overlay);
continue;
}
// An empty Icon explicitly hides the billboard in Cesium. Remove the
// blocked icon definition so the loader supplies its local default pin.
// An empty Icon explicitly hides the icon. Remove the blocked icon
// definition so the placemark gets the local default pin.
// Authored empty Icons (with no blocked href) still mean no marker.
drop(
icon?.localName === 'Icon' && icon.parentNode?.localName === 'IconStyle'
@@ -579,9 +568,8 @@ export function sanitizeKmlDocument(doc, resolveLocal = () => null) {
!childrenNamed(pair, 'Style').length)
)
drop(pair);
// Draw recorded KML paths as their original static vertices. Letting the
// loader build time-dynamic tracks would expand each into thousands of
// interpolated points later and exceed the checked geometry budget.
// Draw recorded KML paths as their original static vertices, the
// geometry the budget checked, never as time-dynamic tracks.
for (const track of elementsNamed(doc, 'Track')) {
const line = doc.createElementNS(
'http://www.opengis.net/kml/2.2',
@@ -647,11 +635,11 @@ const childText = (el, localName) =>
(childrenNamed(el, localName)[0]?.textContent || '').trim();
/**
* Share identical styles before the loader builds their graphics. Inline
* Share identical styles before the features are read. Inline
* overrides stay inline StyleMaps, so an existing styleUrl still supplies
* properties the override leaves unset. Named references are redirected.
* Random-color styles remain unchanged; duplicate IDs
* keep the loader's original precedence instead of being rewritten.
* keep their original precedence instead of being rewritten.
* @param {Document} doc Sanitized KML.
* @param {{serializeStyle?: Function, maxStyles?: number}} [options]
* @returns {number} Number of original style blocks replaced.
@@ -754,8 +742,8 @@ export function deduplicateKmlStyles(
}
/**
* Count placemarks and vertices in a parsed KML document before Cesium reads
* it: every `<coordinates>` tuple and every `gx:coord`, plus normalized
* Count placemarks and vertices in a parsed KML document before it is read:
* every `<coordinates>` tuple and every `gx:coord`, plus normalized
* style definitions and distinct image `<href>` values (`links`).
* Inline StyleMaps are references, not additional shared style definitions.
* @param {Document} doc
@@ -805,8 +793,8 @@ export function countKmlGeometry(
)
throw new GeoImportError(msg('That KML has invalid geometry bounds.'));
}
// Cesium creates entities for folders, a parent for every placemark, and
// a child for each geometry in a MultiGeometry, including nested containers.
// A map object for each folder, a parent for every placemark, and a
// child for each geometry in a MultiGeometry, including nested containers.
if (
name === 'Placemark' ||
name === 'Folder' ||
@@ -952,95 +940,6 @@ export function gpxToGeoJson(
return { type: 'FeatureCollection', features };
}
/** A feature name as short plain text (no control characters), or undefined. */
export function importFeatureName(value) {
const text = String(value ?? '')
.replace(/[\u0000-\u001f\u007f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) return undefined;
return text.length > MAX_IMPORT_NAME_LENGTH
? `${text.slice(0, MAX_IMPORT_NAME_LENGTH - 1)}…`
: text;
}
/**
* Make every entity of an imported data source inert: no description,
* balloon, extended data or properties, no native label, and a name that is
* short plain text. Generated pin canvases share a data URL so Cesium uploads
* each image once, rather than allocating a texture entry for every entity.
* Returns how many entities were touched.
* @param {{entities: {values: object[]}}} dataSource
* @returns {number}
*/
export function scrubImportedEntities(dataSource) {
const collection = dataSource?.entities;
const list = collection?.values || [];
const images = new Map();
collection?.suspendEvents?.();
try {
for (let i = 0; i < list.length; i++) {
const entity = list[i];
let name;
try {
name = importFeatureName(
typeof entity.name === 'string' ? entity.name : undefined,
);
} catch {
name = undefined;
}
entity.name = name;
entity.description = undefined;
entity.label = undefined;
entity.properties = undefined;
if (entity.kml && typeof entity.kml === 'object') entity.kml = undefined;
if (
entity.billboard?.heightReference?.getValue?.() ===
Cesium.HeightReference.CLAMP_TO_GROUND
)
entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY;
const property = entity.billboard?.image;
if (property?.isConstant === false) continue;
const image = property?.getValue?.();
if (image?.tagName === 'CANVAS') {
let url = images.get(image);
if (!url) {
url = image.toDataURL();
images.set(image, url);
}
entity.billboard.image = url;
}
}
} finally {
collection?.resumeEvents?.();
}
return list.length;
}
/**
* Take time out of an imported data source so adding it cannot move the app's
* shared clock: the data source reports no clock (the viewer adopts the clock
* of every added source that has one), every entity is available for all
* time. KML tracks have already become their original static vertices in
* `sanitizeKmlDocument`, so no sampled-position fallback is needed here.
* @param {object} dataSource
* @returns {object} The same data source.
*/
export function detachImportedTime(dataSource) {
Object.defineProperty(dataSource, 'clock', {
configurable: true,
enumerable: false,
get: () => undefined,
set: () => {},
});
const list = dataSource?.entities?.values || [];
for (let i = 0; i < list.length; i++) {
const entity = list[i];
entity.availability = undefined;
}
return dataSource;
}
/** Repair only the first KML opening tag, scanning its delimiter once. */
export function repairKmlRootNamespaces(value, what = 'KML') {
const text = String(value);
@@ -1137,7 +1036,7 @@ export function repairKmlRootNamespaces(value, what = 'KML') {
/** Parse KML or GPX with the shared namespace repairs and XML validation. */
export function parseXml(text, what) {
// Match the namespace repairs Cesium applies to ordinary exported KML.
// The namespace repairs ordinary exported KML needs.
if (what !== 'GPX') text = repairKmlRootNamespaces(text, what);
const doc = new DOMParser().parseFromString(
String(text).replace(/^/, ''),
@@ -1195,172 +1094,12 @@ function checkLocalImages(doc, entries = new Map(), main = '') {
}
}
// Cesium also processes KML in deferred tasks; an exception there does not
// reject its load promise. Keep a failed file from blocking the serial queue.
async function loadKml(doc, viewer, signal) {
let removeError;
try {
return await boundedImport(
Promise.race([
Cesium.KmlDataSource.load(doc, {
camera: viewer.scene.camera,
canvas: viewer.scene.canvas,
clampToGround: true,
}),
new Promise((_, reject) => {
const failed = () => {
reject(new GeoImportError(msg('That KML could not be read.')));
};
globalThis.addEventListener?.('error', failed);
removeError = () => globalThis.removeEventListener?.('error', failed);
}),
]),
signal,
);
} finally {
removeError?.();
}
}
// Resolve a static file's ground pins in batches before they are visualized.
// Per-billboard CLAMP_TO_GROUND subscriptions scale poorly on large imports.
const groundPins = new WeakMap();
async function settleGroundPins(dataSource, viewer, signal) {
let pins = groundPins.get(dataSource);
if (!pins) {
pins = [];
for (const entity of dataSource.entities.values) {
const reference = entity.billboard?.heightReference?.getValue?.();
if (
reference === Cesium.HeightReference.CLAMP_TO_GROUND ||
reference === Cesium.HeightReference.RELATIVE_TO_GROUND
) {
const position = entity.position?.getValue?.(Cesium.JulianDate.now());
if (!position) continue;
const cartographic = Cesium.Cartographic.fromCartesian(position);
if (!cartographic)
throw new GeoImportError(
msg('That file has invalid point coordinates.'),
);
pins.push({
entity,
original: position,
cartographic,
offset:
reference === Cesium.HeightReference.RELATIVE_TO_GROUND
? cartographic.height
: 0,
});
entity.billboard.heightReference = Cesium.HeightReference.NONE;
entity.billboard.disableDepthTestDistance = Number.POSITIVE_INFINITY;
}
}
groundPins.set(dataSource, pins);
}
for (let at = 0; at < pins.length; at += 256) {
signal?.throwIfAborted();
const batch = pins.slice(at, at + 256);
const positions = batch.map(
({ cartographic: c }) =>
new Cesium.Cartographic(c.longitude, c.latitude, 0),
);
const mesh =
viewer.scene?.globe?.show === false &&
viewer.scene?.clampToHeightSupported;
// A coarse rendered ellipsoid mesh can report a height kilometres below
// zero. Its provider's exact height is zero even while a 3D map hides it;
// a buried starting point can make the downward mesh ray miss the surface.
const ellipsoid =
viewer.terrainProvider instanceof Cesium.EllipsoidTerrainProvider;
for (let i = 0; i < positions.length; i++) {
const sampled = ellipsoid
? 0
: viewer.scene?.globe?.getHeight?.(positions[i]);
positions[i].height = mesh
? (batch[i].groundHeight ??
Math.max(0, Number.isFinite(sampled) ? sampled : 0))
: Number.isFinite(sampled)
? sampled
: batch[i].groundHeight || 0;
}
const points = positions.map((c) =>
Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height),
);
const height = viewer.camera?.positionCartographic?.height;
if (mesh && Number.isFinite(height) && height < 250_000) {
const rectangle = viewer.camera.computeViewRectangle?.();
const indices = [];
for (let i = 0; i < positions.length; i++)
if (rectangle && Cesium.Rectangle.contains(rectangle, positions[i]))
indices.push(i);
if (indices.length) {
const resolved = await boundedImport(
viewer.scene.clampToHeightMostDetailed(
indices.map((i) => {
const c = positions[i];
return Cesium.Cartesian3.fromRadians(
c.longitude,
c.latitude,
Math.max(0, c.height),
);
}),
),
signal,
);
for (let i = 0; i < indices.length; i++)
if (resolved[i]) points[indices[i]] = resolved[i];
}
}
signal?.throwIfAborted();
for (let i = 0; i < batch.length; i++) {
const item = batch[i];
const c = points[i] && Cesium.Cartographic.fromCartesian(points[i]);
if (!c)
throw new GeoImportError(
msg(
'Ground heights are not available for that file. Try again when the map has loaded.',
),
);
item.groundHeight = c.height;
c.height += item.offset;
item.entity.position =
Math.abs(c.height - item.cartographic.height) < 1e-6
? item.original
: Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, c.height);
}
if (at + batch.length < pins.length)
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
async function boundedImport(promise, signal) {
let timer, abort;
try {
signal?.throwIfAborted();
return await Promise.race([
promise,
new Promise((_, reject) => {
abort = () => reject(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
timer = setTimeout(
() =>
reject(new GeoImportError(msg('That file took too long to read.'))),
60_000,
);
}),
]);
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', abort);
}
}
/**
* Load a ground footprint, retaining explicit KML altitude modes. Call mount after
* adding the source; revoke owns pin and blob cleanup.
* Load a ground footprint, retaining explicit KML altitude modes. Call mount
* to draw it; revoke owns the drawing and blob cleanup.
* @param {File|Blob & {name?: string}} file
* @param {{viewer: Cesium.Viewer, color?: string}} options `color` is a CSS color.
* @returns {Promise<{dataSource: Cesium.DataSource, name: string,
* @param {{viewer: object, color?: string}} options `color` is a CSS color.
* @returns {Promise<{drawing: object, name: string,
* format: string, entityCount: number, removed: number, mount: Function, revoke: Function}>}
*/
export async function loadGeoFile(
@@ -1385,15 +1124,14 @@ export async function loadGeoFile(
throw new GeoImportError(
msg('Only GeoJSON, KML, KMZ and GPX files can be imported.'),
);
const stroke = Cesium.Color.fromCssColorString(color);
const urls = [];
let pins;
let drawn;
const revoke = () => {
pins?.destroy();
drawn?.drawing.destroy();
urls.splice(0).forEach((url) => URL.revokeObjectURL(url));
};
const name = importDisplayName(file.name);
let dataSource;
let read;
let removed = 0;
try {
if (format === 'geojson' || format === 'gpx') {
@@ -1409,18 +1147,7 @@ export async function loadGeoFile(
throw new GeoImportError(msg('That file has nothing to draw.'));
prepareGeoJson(geojson);
bytes = null;
dataSource = await boundedImport(
Cesium.GeoJsonDataSource.load(geojson, {
clampToGround: true,
stroke,
fill: stroke.withAlpha(0.25),
strokeWidth: 3,
markerColor: stroke,
// No HTML description table is built from the file's properties.
describe: () => undefined,
}),
signal,
);
read = readGeoJsonFeatures(geojson, color);
} else {
let text;
let entries;
@@ -1449,7 +1176,7 @@ export async function loadGeoFile(
deduplicateKmlStyles(doc);
const normalizedSize = countKmlGeometry(doc);
if (normalizedSize.over) throw overLimitError(normalizedSize);
dataSource = await loadKml(doc, viewer, signal);
read = readKmlFeatures(doc);
}
} catch (error) {
revoke();
@@ -1460,69 +1187,22 @@ export async function loadGeoFile(
{ format: format.toUpperCase() },
);
}
const entityCount = dataSource.entities.values.length;
if (entityCount > MAX_IMPORT_ENTITIES) {
revoke();
throw new GeoImportError(
`That file has ${entityCount.toLocaleString()} map objects; the limit is ${MAX_IMPORT_ENTITIES.toLocaleString()}.`,
msg('That file has {count} map objects; the limit is {limit}.'),
{
count: entityCount,
limit: MAX_IMPORT_ENTITIES,
},
);
}
const now = Cesium.JulianDate.now();
const drawable = dataSource.entities.values.some(
(e) =>
e.billboard?.image?.getValue(now) ||
e.point ||
e.rectangle ||
e.polyline?.positions?.getValue(now)?.length >= 2 ||
e.wall?.positions?.getValue(now)?.length >= 2 ||
e.polygon?.hierarchy?.getValue(now)?.positions?.length >= 3,
);
if (!drawable) {
revoke();
throw new GeoImportError(msg('That file has nothing to draw.'));
}
scrubImportedEntities(dataSource);
try {
await settleGroundPins(dataSource, viewer, signal);
drawn = await settleImportedDrawing(read, viewer, signal);
} catch (error) {
revoke();
throw error instanceof GeoImportError
? error
: new GeoImportError(
msg('Ground heights could not be read. Try that file again.'),
);
throw error;
}
// Keep the clock invariant explicit even though unused KML dates have
// already been stripped and all supported geometries are static.
detachImportedTime(dataSource);
try {
pins = createImportedPins(dataSource, viewer);
} catch {
revoke();
throw new GeoImportError(msg('That file has invalid point graphics.'));
}
// The display name travels beside the data source (the file name, not
// The display name travels beside the drawing (the file name, not
// anything the document says about itself).
return {
dataSource,
drawing: drawn.drawing,
name,
format,
entityCount,
entityCount: drawn.entityCount,
removed,
revoke,
mount: () => pins.mount(),
refreshGround: (refreshSignal) =>
settleGroundPins(
dataSource,
viewer,
refreshSignal
? AbortSignal.any([refreshSignal, AbortSignal.timeout(15_000)])
: AbortSignal.timeout(15_000),
).then(() => pins.sync()),
mount: () => drawn.drawing.mount(),
refreshGround: drawn.refreshGround,
};
}
+216 -264
View File
@@ -2,7 +2,6 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { deflateRawSync } from 'node:zlib';
import { spawnSync } from 'node:child_process';
import * as Cesium from 'cesium';
import {
GeoImportError,
repairKmlRootNamespaces,
@@ -12,10 +11,8 @@ import {
countGeoJsonGeometry,
countKmlGeometry,
deduplicateKmlStyles,
detachImportedTime,
gpxToGeoJson,
importFeatureName,
scrubImportedEntities,
sanitizeKmlDocument,
detectGeoFileFormat,
importDisplayName,
@@ -26,105 +23,125 @@ import {
readZipEntries,
resolveKmzPath,
} from './geoFileImport.js';
import { readKmlFeatures } from './geoImportFeatures.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
/** The point `at` (lon, lat) at `height`, ECEF. */
const fromDegreesHeight = (at, height) => fromDegrees(at.lon, at.lat, height);
import { createImportImageBudget, importImageSize } from './geoImportImages.js';
test('real loader grounds XYZ GeoJSON and strips loader-sensitive metadata before allocation', async () => {
const previous = Cesium.PinBuilder.prototype.fromColor;
Cesium.PinBuilder.prototype.fromColor = () => ({
toDataURL: () => 'data:image/png;base64,local',
tagName: 'CANVAS',
/**
* A viewer bound to a renderer double for the import: draw sets kept,
* terrain heights from `terrain` (the globe shown) or from `hidden` (the
* globe hidden over a mesh), mesh clamps from `clamp`, and a camera
* `eyeHeight` up looking at `view`.
*/
function importViewer({
terrain = () => null,
hidden = null,
clamp = null,
eyeHeight = 1_000_000,
view = { west: -180, south: -90, east: 180, north: 90 },
} = {}) {
const viewer = {};
const ground = bindFakeGroundRenderer(viewer, {
sampleHeight: Boolean(clamp),
eye: { lon: 0, lat: 0, height: eyeHeight },
});
try {
const object = {
type: 'FeatureCollection',
crs: { type: 'name', properties: { name: 'unsupported' } },
features: [
{
type: 'Feature',
id: 'kartaview-owned',
properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' },
geometry: { type: 'Point', coordinates: [1, 2, 999] },
},
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[1, 2, 0],
[2, 2, 0],
[2, 3, 0],
[1, 2, 0],
],
],
},
},
],
};
const loaded = await loadGeoFile(
new File([JSON.stringify(object)], 'xyz.geojson'),
ground.globe.show = !hidden;
ground.globe.terrain = terrain;
const query = ground.renderer.query;
const sampleHeightNow = query.sampleHeightNow;
query.sampleHeightNow = (point, options = {}) =>
hidden && options.against === 'terrain'
? hidden(point)
: sampleHeightNow(point, options);
if (clamp) query.clampToSurface = async (points) => clamp(points);
ground.renderer.camera.viewRectangle = () => view;
return { viewer, camera: ground.renderer.camera, ...ground };
}
/** The live import set of a kind (`pins`, `lines`, `shapes`). */
const importSet = (ground, kind) =>
[...ground.draw.sets.values()].find(
(record) =>
!record.disposed &&
record.spec.id.startsWith('geo-import:') &&
record.spec.id.endsWith(`:${kind}`),
);
test('GeoJSON points stand on the ground and lose everything but a name', async () => {
const object = {
type: 'FeatureCollection',
crs: { type: 'name', properties: { name: 'unsupported' } },
features: [
{
viewer: {
scene: {
frameState: { mode: Cesium.SceneMode.SCENE3D },
primitives: new Cesium.PrimitiveCollection(),
globe: { getHeight: () => 1234 },
},
type: 'Feature',
id: 'kartaview-owned',
properties: { name: 'Test', addProperty: 1, 'marker-symbol': 'rail' },
geometry: { type: 'Point', coordinates: [1, 2, 999] },
},
{
type: 'Feature',
geometry: {
type: 'Polygon',
coordinates: [
[
[1, 2, 0],
[2, 2, 0],
[2, 3, 0],
[1, 2, 0],
],
],
},
},
],
};
const t = importViewer({ terrain: () => 1234 });
try {
const loaded = await loadGeoFile(
new File([JSON.stringify(object)], 'xyz.geojson'),
{ viewer: t.viewer, color: '#ff0000' },
);
const [point, polygon] =
loaded.dataSource.importedEntities || loaded.dataSource.entities.values;
assert.notEqual(point.id, 'kartaview-owned');
assert.equal(point.name, 'Test');
assert.equal(point.properties, undefined);
assert.equal(
point.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.equal(point.billboard.disableDepthTestDistance.getValue(), Infinity);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(
point.position.getValue(Cesium.JulianDate.now()),
).height - 1234,
) < 1e-6,
);
assert.notEqual(polygon.polygon.perPositionHeight?.getValue(), true);
assert.equal(loaded.dataSource.clock, undefined);
assert.equal(
loaded.dataSource.entities.values.length,
1,
'only polygon geometry remains in the per-frame entity collection',
);
assert.equal(loaded.dataSource.importedBillboards.length, 1);
const update = Cesium.BillboardCollection.prototype.update;
let passes = 0;
Cesium.BillboardCollection.prototype.update = () => passes++;
try {
const collection = loaded.dataSource.importedBillboards;
collection.update({ passes: { pick: true, offscreen: true } });
assert.equal(passes, 0, 'height picks ignore imported markers');
collection.update({ passes: { pick: true, offscreen: false } });
collection.update({ passes: { render: true, offscreen: true } });
assert.equal(passes, 2, 'ordinary picks and screenshots include markers');
} finally {
Cesium.BillboardCollection.prototype.update = update;
}
assert.equal(importSet(t, 'pins'), undefined, 'nothing drawn before mount');
loaded.mount();
loaded.dataSource.show = false;
assert.equal(loaded.dataSource.importedBillboards.show, false);
loaded.dataSource.show = true;
const [pin] = importSet(t, 'pins').items.values();
assert.equal(pin.meta.name, 'Test');
assert.deepEqual(Object.keys(pin.meta), ['name']);
assert.equal(pin.height, 'absolute');
assert.equal(pin.pos.height, 1234, 'on the terrain, not at 999 m');
assert.equal(pin.disableDepthTest, Infinity);
assert.equal(pin.anchor, 'bottom');
assert.deepEqual(pin.size, [48, 48]);
assert.match(pin.image.svg, /rgba\(255,0,0,1\)/);
assert.equal(
importSet(t, 'pins').spec.includeInHeightQueries,
undefined,
'height queries never see imported markers',
);
const [polygon] = importSet(t, 'shapes').items.values();
assert.equal(polygon.height, 'clampGround');
assert.deepEqual(polygon.fill, [1, 0, 0, 0.25]);
assert.equal(polygon.outline, undefined, 'no outline on the ground');
assert.equal(loaded.entityCount, 2);
loaded.drawing.show = false;
assert.equal(importSet(t, 'pins').show, false);
assert.equal(importSet(t, 'shapes').show, false);
loaded.drawing.show = true;
t.globe.terrain = () => 50;
await loaded.refreshGround();
assert.equal(
point.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
[...importSet(t, 'pins').items.values()][0].pos.height,
50,
'a refresh moves the pin onto the ground now under it',
);
loaded.revoke();
assert.ok(loaded.dataSource.importedBillboards.isDestroyed());
assert.equal(importSet(t, 'pins'), undefined);
assert.equal(importSet(t, 'shapes'), undefined);
} finally {
Cesium.PinBuilder.prototype.fromColor = previous;
t.unbind();
}
});
@@ -241,81 +258,54 @@ test('pending file reads can be cancelled without waiting for the loader timeout
});
test('a hidden coarse globe never seeds a mesh-clamp ray below the surface', async () => {
const previous = Cesium.PinBuilder.prototype.fromColor;
Cesium.PinBuilder.prototype.fromColor = () => ({
tagName: 'CANVAS',
toDataURL: () => 'data:image/png;base64,local',
});
const starts = [];
const t = importViewer({
eyeHeight: 100_000,
hidden: () => -12311,
clamp: (points) =>
points.map((p) => {
const at = toLonLatH(p);
starts.push(at.height);
return at.height < -9000
? null
: { ...p, ...fromDegreesHeight(at, 2000) };
}),
});
try {
for (const terrainProvider of [new Cesium.EllipsoidTerrainProvider(), {}]) {
const viewer = {
terrainProvider,
camera: {
positionCartographic: { height: 100000 },
computeViewRectangle: () => Cesium.Rectangle.MAX_VALUE,
},
scene: {
frameState: { mode: Cesium.SceneMode.SCENE3D },
globe: { show: false, getHeight: () => -12311 },
clampToHeightSupported: true,
clampToHeightMostDetailed: async (points) =>
points.map((p) => {
const c = Cesium.Cartographic.fromCartesian(p);
starts.push(c.height);
return c.height < -9000
? undefined
: Cesium.Cartesian3.fromRadians(c.longitude, c.latitude, 2000);
}),
},
};
const loaded = await loadGeoFile(
new File(
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
'surface.geojson',
),
{ viewer },
);
assert.ok(
Math.abs(starts.at(-1)) < 1e-6,
`ray started at ${starts.at(-1)}`,
);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(
loaded.dataSource.importedBillboards.get(0).position,
).height - 2000,
) < 1e-6,
);
const sampled = starts.length;
viewer.camera.computeViewRectangle = () => undefined;
await loaded.refreshGround();
assert.equal(
starts.length,
sampled,
'distant points do not start a detailed mesh sweep',
);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(
loaded.dataSource.importedBillboards.get(0).position,
).height - 2000,
) < 1e-6,
'the last valid mesh height survives outside the camera footprint',
);
const point = loaded.dataSource.importedEntities[0];
const other = new Cesium.Entity({ id: 'unrelated-aircraft' });
viewer.trackedEntity = starts.length === 1 ? other : point;
viewer.selectedEntity = point;
loaded.revoke();
assert.equal(viewer.selectedEntity, undefined);
assert.equal(
viewer.trackedEntity,
starts.length === 1 ? other : undefined,
);
}
const loaded = await loadGeoFile(
new File(
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
'surface.geojson',
),
{ viewer: t.viewer },
);
loaded.mount();
const height = () => [...importSet(t, 'pins').items.values()][0].pos.height;
assert.ok(
Math.abs(starts.at(-1)) < 1e-6,
`ray started at ${starts.at(-1)}`,
);
assert.ok(Math.abs(height() - 2000) < 1e-6);
const sampled = starts.length;
t.camera.viewRectangle = () => ({
west: 10,
south: 10,
east: 11,
north: 11,
});
await loaded.refreshGround();
assert.equal(
starts.length,
sampled,
'distant points do not start a detailed mesh sweep',
);
assert.ok(
Math.abs(height() - 2000) < 1e-6,
'the last valid mesh height survives outside the camera footprint',
);
loaded.revoke();
} finally {
Cesium.PinBuilder.prototype.fromColor = previous;
t.unbind();
}
});
@@ -709,7 +699,7 @@ test('distinct style definitions and named StyleMaps still have a pre-loader bud
assert.equal(countKmlGeometry(maps, { maxLinks: 1 }).over, 'links');
});
test('KML extended metadata is removed before the document reaches the loader', () => {
test('KML extended metadata is removed before the document is read for drawing', () => {
const point = xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2,0')]);
const metadata = xmlEl('ExtendedData', {}, [
xmlEl('Data', { name: 'note' }, [xmlEl('value', {}, 'ordinary metadata')]),
@@ -810,7 +800,7 @@ test('GPX keeps each track segment as its own line, names as text, no times', ()
assert.throws(() => gpxToGeoJson(xmlDoc(xmlEl('kml'))), GeoImportError);
});
test('GPX past the point limit is refused while reading, before Cesium', () => {
test('GPX past the point limit is refused while reading, before anything is drawn', () => {
const seg = xmlEl(
'trkseg',
{},
@@ -967,7 +957,7 @@ test('KML vertex counting recognizes the Unicode whitespace Cesium accepts', ()
}
});
test('KML multipart geometries count every Cesium entity before loading', () => {
test('KML multipart geometries count every map object before drawing', () => {
const doc = xmlDoc(
xmlEl('kml', {}, [
xmlEl('Placemark', {}, [
@@ -1050,69 +1040,47 @@ test('a KMZ image gets one blob URL however many hrefs name it', () => {
assert.deepEqual(kept, ['blob:test/1', 'blob:test/2']);
});
test('imported entities keep only a short plain-text name: no description, label or properties', () => {
const ds = new Cesium.CustomDataSource('t');
const e = ds.entities.add({
name: 'Trail\u0007 <b>head</b>\n' + 'x'.repeat(300),
description: '<img src="https://example.invalid/x.png" onerror="alert(1)">',
label: { text: 'Trail head' },
properties: { note: '<script>alert(1)</script>' },
position: Cesium.Cartesian3.fromDegrees(1, 2),
});
e.kml = { extendedData: { note: { value: '<iframe src=//x>' } } };
ds.entities.add({ name: 42, position: Cesium.Cartesian3.fromDegrees(1, 2) });
assert.equal(scrubImportedEntities(ds), 2);
assert.equal(e.description, undefined);
assert.equal(e.label, undefined);
assert.equal(e.properties, undefined);
assert.equal(e.kml, undefined);
assert.ok(e.name.startsWith('Trail <b>head</b> x'));
assert.ok(e.name.length <= 120 && !/[\u0000-\u001f]/.test(e.name));
assert.equal(ds.entities.values[1].name, undefined);
test('imported features keep only a short plain-text name', () => {
const placemark = (name) =>
xmlEl('Placemark', {}, [
xmlEl('name', {}, name),
xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2')]),
]);
const doc = xmlDoc(
xmlEl('kml', {}, [
xmlEl('Document', {}, [
placemark('Trail\u0007 <b>head</b>\n' + 'x'.repeat(300)),
placemark(' '),
]),
]),
);
const { features } = readKmlFeatures(doc);
assert.ok(features[0].name.startsWith('Trail <b>head</b> x'));
assert.ok(
features[0].name.length <= 120 && !/[\u0000-\u001f]/.test(features[0].name),
);
assert.equal(features[1].name, undefined);
assert.equal(importFeatureName(' '), undefined);
});
test('generated pin canvases are encoded once and shared without changing authored image URLs', () => {
const ds = new Cesium.CustomDataSource('pins');
let encoded = 0;
const canvas = {
tagName: 'CANVAS',
toDataURL: () => {
encoded++;
return 'data:image/png;base64,shared-pin';
},
};
for (let i = 0; i < 1000; i++)
ds.entities.add({
billboard: { image: canvas },
label: { text: 'discard' },
properties: { discard: true },
});
const authored = ds.entities.add({
billboard: { image: 'blob:packed-image' },
});
const dynamicImage = new Cesium.CallbackProperty(() => canvas, false);
const dynamic = ds.entities.add({ billboard: { image: dynamicImage } });
let notifications = 0;
ds.entities.collectionChanged.addEventListener(() => notifications++);
scrubImportedEntities(ds);
assert.equal(encoded, 1);
assert.equal(
notifications,
1,
'normalization publishes one complete collection change',
);
for (const e of ds.entities.values.slice(0, 1000))
assert.equal(
e.billboard.image.getValue(),
'data:image/png;base64,shared-pin',
);
assert.equal(authored.billboard.image.getValue(), 'blob:packed-image');
assert.equal(
dynamic.billboard.image,
dynamicImage,
'time-dependent image properties stay intact',
test('placemarks without an icon of their own share one default pin', () => {
const doc = xmlDoc(
xmlEl('kml', {}, [
xmlEl(
'Document',
{},
Array.from({ length: 1000 }, () =>
xmlEl('Placemark', {}, [
xmlEl('Point', {}, [xmlEl('coordinates', {}, '1,2')]),
]),
),
),
]),
);
const { features } = readKmlFeatures(doc);
assert.equal(features.length, 1000);
assert.ok(features.every((f) => f.image === features[0].image));
assert.match(features[0].image.svg, /rgba\(255,255,0,1\)/);
});
test('unused KML time and camera metadata is removed before loading without changing geometry', () => {
@@ -1133,47 +1101,6 @@ test('unused KML time and camera metadata is removed before loading without chan
assert.equal(coordinates.textContent, '1,2,0 3,4,0');
});
test('a dated import exposes no clock and draws for all time', () => {
// A data source with its own clock, as KmlDataSource has for a dated file.
class DatedSource extends Cesium.CustomDataSource {
get clock() {
return this._testClock;
}
}
const ds = new DatedSource('dated');
ds._testClock = new Cesium.DataSourceClock();
const start = Cesium.JulianDate.fromIso8601('2020-01-01T00:00:00Z');
const stop = Cesium.JulianDate.fromIso8601('2020-01-01T01:00:00Z');
const span = new Cesium.TimeIntervalCollection([
new Cesium.TimeInterval({ start, stop }),
]);
// KML tracks become their original static vertices before Cesium loading.
const track = ds.entities.add({
availability: span,
polyline: {
positions: Cesium.Cartesian3.fromDegreesArray([10, 10, 10.1, 10.1]),
clampToGround: true,
},
});
const recorded = track.polyline.positions;
const pin = ds.entities.add({
availability: span,
position: Cesium.Cartesian3.fromDegrees(1, 1),
});
assert.ok(ds.clock);
detachImportedTime(ds);
assert.equal(ds.clock, undefined);
// The viewer reads `clock` from every added source; setting it is ignored.
ds.clock = new Cesium.DataSourceClock();
assert.equal(ds.clock, undefined);
assert.equal(pin.availability, undefined);
assert.ok(pin.isAvailable(Cesium.JulianDate.now()));
assert.equal(track.availability, undefined);
assert.equal(track.polyline.positions, recorded);
assert.equal(recorded.getValue(Cesium.JulianDate.now()).length, 2);
assert.ok(track.polyline.clampToGround.getValue());
});
test('KML root namespace repair respects quoted delimiters and preserves the document tail', () => {
const text =
'<KML note="a > b" xmlns:x="first" xmlns:x="second"><Placemark xsi:type="test"/></KML>';
@@ -1262,3 +1189,28 @@ test('KML namespace repair ignores declaration text inside quoted attribute valu
/note="xmlns:xsi='x'" xmlns:xsi="http:\/\/www.w3.org\/2001\/XMLSchema-instance">/,
);
});
test('a failed mesh clamp fails the import instead of leaving pins at sea level', async () => {
const t = importViewer({
eyeHeight: 100_000,
hidden: () => 0,
clamp: () => {
throw new Error('tile request failed');
},
});
try {
await assert.rejects(
loadGeoFile(
new File(
[JSON.stringify({ type: 'Point', coordinates: [1, 2] })],
'surface.geojson',
),
{ viewer: t.viewer },
),
/Ground heights could not be read/,
);
assert.equal(importSet(t, 'pins'), undefined);
} finally {
t.unbind();
}
});
+686
View File
@@ -0,0 +1,686 @@
/**
* What an imported file draws, read from its parsed KML document or its
* prepared GeoJSON as the default renderer's KML and GeoJSON loaders read
* them: placemark pins with their icons, colours and anchors, paths,
* polygons, walls and ground overlays, each with its altitude mode. Plain
* data in degrees and metres, drawn by `geoImportPins.js`.
*
* `entityCount` counts what those loaders made of the file (folders,
* placemarks, each part of a multi-geometry), the number the import limit
* is checked against. `drawable` says whether any of it can be drawn.
*/
import { plainPin } from './geojsonPins.js';
import { importFeatureName } from './geoImportShared.js';
import { cssColor } from '../render/color.js';
/** KML icons are drawn this many pixels square, times their scale. */
const KML_ICON_SIZE = 32;
/** KML icons shrink with distance: full size near, a tenth far. */
const KML_ICON_SCALE_BY_DISTANCE = Object.freeze({
near: 2414016,
nearValue: 1,
far: 1.6093e7,
farValue: 0.1,
});
const WHITE = Object.freeze([1, 1, 1, 1]);
const BLACK = Object.freeze([0, 0, 0, 1]);
/** A placemark without an icon of its own: a yellow pin. */
const DEFAULT_KML_PIN = plainPin([1, 1, 0, 1], 64);
/** GeoJSON markers are pins this many pixels square, standing on the point. */
const GEOJSON_PIN_SIZE = 48;
const GX = 'http://www.google.com/kml/ext/2.2';
/** The namespaces KML elements come in: none, or a KML version's. */
const KML_NAMESPACES = new Set([
null,
undefined,
'',
'http://www.opengis.net/kml/2.2',
'http://earth.google.com/kml/2.2',
'http://earth.google.com/kml/2.1',
'http://earth.google.com/kml/2.0',
]);
const isGx = (el) => el.namespaceURI === GX;
const isKml = (el) => KML_NAMESPACES.has(el.namespaceURI);
/** Element children of `el` with this local name, KML (not gx) unless `gx`. */
function children(el, name, gx = false) {
const out = [];
const kids = el?.childNodes;
if (!kids) return out;
for (let i = 0; i < kids.length; i++) {
const kid = kids[i];
if (
kid.nodeType === 1 &&
kid.localName === name &&
(gx ? isGx(kid) : isKml(kid))
)
out.push(kid);
}
return out;
}
const child = (el, name, gx) => children(el, name, gx)[0];
const text = (el, name, gx) => child(el, name, gx)?.textContent.trim();
function number(el, name, gx) {
const value = Number.parseFloat(child(el, name, gx)?.textContent);
return Number.isNaN(value) ? undefined : value;
}
function flag(el, name) {
const value = text(el, name);
return value === undefined
? undefined
: value === '1' || /^true$/i.test(value);
}
function attribute(el, name) {
const value = el?.getAttribute(name);
if (value === null || value === undefined) return undefined;
const parsed = Number.parseFloat(value);
return Number.isNaN(parsed) ? undefined : parsed;
}
/**
* A KML `aabbggrr` colour as `[r, g, b, a]`; with `colorMode` random, each
* channel drawn at random up to its own value.
*/
function kmlColor(el, name = 'color') {
let value = text(el, name);
if (!value) return undefined;
if (value[0] === '#') value = value.slice(1);
const channel = (at) => Number.parseInt(value.slice(at, at + 2), 16) / 255;
const alpha = channel(0);
const rgb = [channel(6), channel(4), channel(2)];
if (text(el, 'colorMode') === 'random')
for (let i = 0; i < 3; i++)
rgb[i] = rgb[i] > 0 ? Math.random() * rgb[i] : 0;
return [...rgb, alpha];
}
/** One `lon,lat[,height]` tuple; missing or unreadable numbers are 0. */
function readCoordinate(value) {
const digits = value?.match(/[^\s,\n]+/g);
const at = (i) => {
const n = Number.parseFloat(digits?.[i]);
return Number.isNaN(n) ? 0 : n;
};
return [at(0), at(1), at(2)];
}
function readCoordinates(el) {
const tuples = el?.textContent.match(/[^\s\n]+/g);
return tuples ? tuples.map(readCoordinate) : undefined;
}
/** Copy each graphic's unset properties from `from`, as styles merge. */
function merge(into, from) {
for (const kind of ['billboard', 'polyline', 'polygon']) {
if (!from?.[kind]) continue;
if (!into[kind]) into[kind] = { ...from[kind] };
else
for (const key of Object.keys(from[kind]))
if (into[kind][key] === undefined) into[kind][key] = from[kind][key];
}
return into;
}
const defaultBillboard = () => ({});
/** The icon, line and polygon look a `<Style>` gives, merged into `style`. */
function applyStyle(styleEl, style) {
if (!styleEl) return style;
for (const node of styleEl.childNodes) {
if (node.nodeType !== 1 || !isKml(node)) continue;
if (node.localName === 'IconStyle') {
const billboard = (style.billboard ??= defaultBillboard());
const icon = child(node, 'Icon');
const href = text(icon, 'href');
// An empty <Icon> draws no icon; none at all, the default pin.
billboard.image = href ? href : icon ? false : undefined;
const scale = number(node, 'scale');
billboard.scale = scale;
billboard.color = kmlColor(node);
const heading = number(node, 'heading');
// Heading 0 is no heading; north is 360.
if (heading !== undefined && heading !== 0) billboard.course = heading;
const spot = child(node, 'hotSpot');
const x = attribute(spot, 'x');
const y = attribute(spot, 'y');
const s = scale ?? 1;
let dx;
let dy;
if (x !== undefined) {
// Units left out are a fraction, as KML has it.
const units = spot.getAttribute('xunits') || 'fraction';
if (units === 'pixels') dx = -x * s;
else if (units === 'insetPixels') dx = (x - KML_ICON_SIZE) * s;
else if (units === 'fraction') dx = -x * KML_ICON_SIZE * s;
if (dx !== undefined) dx += KML_ICON_SIZE * 0.5 * s;
else dx = Number.NaN;
}
if (y !== undefined) {
const units = spot.getAttribute('yunits') || 'fraction';
if (units === 'pixels') dy = y * s;
else if (units === 'insetPixels') dy = (-y + KML_ICON_SIZE) * s;
else if (units === 'fraction') dy = y * KML_ICON_SIZE * s;
if (dy !== undefined) dy -= KML_ICON_SIZE * 0.5 * s;
else dy = Number.NaN;
}
if (dx !== undefined || dy !== undefined)
billboard.pixelOffset = {
x: Number.isFinite(dx) ? dx : 0,
y: Number.isFinite(dy) ? dy : 0,
};
} else if (node.localName === 'LineStyle') {
const polyline = (style.polyline ??= {});
polyline.width = number(node, 'width');
polyline.color = kmlColor(node);
} else if (node.localName === 'PolyStyle') {
const polygon = (style.polygon ??= { outline: true });
polygon.color = kmlColor(node) ?? polygon.color;
polygon.fill = flag(node, 'fill') ?? polygon.fill;
polygon.outline = flag(node, 'outline') ?? polygon.outline;
}
}
return style;
}
/**
* The document's shared styles by `#id`: each `<Style>` with an id, then
* each `<StyleMap>` as its normal pair; the first of an id wins.
*/
function sharedStyles(doc) {
const styles = new Map();
for (const el of doc.getElementsByTagName('*')) {
if (el.localName !== 'Style' || !isKml(el)) continue;
const id = el.getAttribute('id');
if (id && !styles.has(`#${id}`)) styles.set(`#${id}`, applyStyle(el, {}));
}
for (const el of doc.getElementsByTagName('*')) {
if (el.localName !== 'StyleMap' || !isKml(el)) continue;
const id = el.getAttribute('id');
if (!id || styles.has(`#${id}`)) continue;
for (const pair of children(el, 'Pair')) {
if (text(pair, 'key') !== 'normal') continue;
const style = {};
let url = text(pair, 'styleUrl');
if (url !== undefined) {
if (url[0] !== '#') url = `#${url}`;
merge(style, styles.get(url));
} else applyStyle(child(pair, 'Style'), style);
styles.set(`#${id}`, style);
break;
}
}
return styles;
}
/** A feature's own style: its last inline Style or StyleMap, then its styleUrl. */
function finalStyle(feature, styles) {
const style = {};
const lookup = (url) => styles.get(url) ?? styles.get(`#${url}`);
let inline;
for (const node of feature.childNodes)
if (
node.nodeType === 1 &&
isKml(node) &&
(node.localName === 'Style' || node.localName === 'StyleMap')
)
inline = node;
if (inline?.localName === 'Style') applyStyle(inline, style);
else if (inline)
for (const pair of children(inline, 'Pair')) {
if (text(pair, 'key') !== 'normal') continue;
const url = text(pair, 'styleUrl');
if (url !== undefined) merge(style, lookup(url));
else applyStyle(child(pair, 'Style'), style);
}
const url = text(feature, 'styleUrl');
if (url !== undefined) merge(style, lookup(url));
return style;
}
const extrudable = (mode, gxMode) =>
mode === 'absolute' ||
mode === 'relativeToGround' ||
gxMode === 'relativeToSeaFloor';
/** How a point stands: on the ground, above it, or at its own height. */
function pinHeightMode(mode, gxMode) {
if ((!mode && !gxMode) || mode === 'clampToGround') return 'clamp';
if (mode === 'relativeToGround') return 'relative';
if (mode === 'absolute') return 'absolute';
if (gxMode === 'relativeToSeaFloor') return 'relative';
return 'clamp';
}
/** A placemark pin as a KML point draws it. */
function kmlPin(name, style, at, mode) {
const billboard = style.billboard ?? defaultBillboard();
const image =
billboard.image === undefined
? DEFAULT_KML_PIN
: billboard.image === false
? null
: billboard.image;
return {
kind: 'pin',
name,
lon: at?.[0],
lat: at?.[1],
height: at?.[2] ?? 0,
mode,
image,
size: [KML_ICON_SIZE, KML_ICON_SIZE],
scale: billboard.scale,
color: billboard.color,
course: billboard.course,
pixelOffset: billboard.pixelOffset,
scaleByDistance: KML_ICON_SCALE_BY_DISTANCE,
// Its hot spot's offset shrinks with it, as Cesium's KML icons' did.
offsetScalesByDistance: true,
};
}
/** One KML geometry element of a placemark as features; false for none. */
function kmlGeometry(el, name, style, out) {
const mode = text(el, 'altitudeMode');
const gxMode = text(el, 'altitudeMode', true);
const canExtrude = extrudable(mode, gxMode);
const extrude = flag(el, 'extrude');
switch (el.localName) {
case 'Point': {
out.push(
kmlPin(
name,
style,
readCoordinate(text(el, 'coordinates')),
pinHeightMode(mode, gxMode),
),
);
return true;
}
case 'LineString':
case 'LinearRing': {
const coords = readCoordinates(child(el, 'coordinates'));
const line = style.polyline;
if (canExtrude && extrude) {
const polygon = style.polygon;
out.push({
kind: 'wall',
name,
coords,
fill: polygon?.fill === false ? null : (polygon?.color ?? WHITE),
outline: line
? (line.color ?? WHITE)
: polygon
? (polygon.color ?? WHITE)
: BLACK,
outlineWidth: line?.width,
});
} else if (!canExtrude && flag(el, 'tessellate')) {
out.push({
kind: 'line',
name,
coords,
mode: 'draped',
color: line?.color ?? WHITE,
width: line?.width ?? 1,
});
} else {
// Straight in space: at the heights given where the altitude mode
// allows, otherwise on the ellipsoid (a clamped line the import did
// not tessellate, such as one with an explicit tessellate 0).
out.push({
kind: 'line',
name,
coords: canExtrude
? coords
: coords?.map(([lon, lat]) => [lon, lat, 0]),
mode: '3d',
color: line?.color ?? WHITE,
width: line?.width ?? 1,
});
}
return true;
}
case 'Polygon': {
const ring = (boundary) =>
readCoordinates(child(child(boundary, 'LinearRing'), 'coordinates'));
const outer = ring(child(el, 'outerBoundaryIs'));
const holes = [];
for (const inner of children(el, 'innerBoundaryIs'))
for (const linear of children(inner, 'LinearRing')) {
const coords = readCoordinates(child(linear, 'coordinates'));
if (coords) holes.push(coords);
}
const polygon = style.polygon ?? { outline: true };
const line = style.polyline;
out.push({
kind: 'polygon',
name,
rings: outer ? [outer, ...holes] : [],
clamp: !canExtrude,
extrude: canExtrude && extrude === true,
fill: polygon.fill === false ? null : (polygon.color ?? WHITE),
outline:
polygon.outline === false
? null
: line
? (line.color ?? WHITE)
: WHITE,
outlineWidth: line?.width,
});
return true;
}
case 'MultiGeometry': {
let any = false;
for (const part of el.childNodes) {
if (part.nodeType !== 1 || !KML_GEOMETRIES.has(part.localName))
continue;
// Each part is a map object of its own, named as its placemark.
out.entities += 1;
if (kmlGeometry(part, name, style, out)) any = true;
}
return any;
}
default:
return false;
}
}
const KML_GEOMETRIES = new Set([
'Point',
'LineString',
'LinearRing',
'Polygon',
'MultiGeometry',
'Model',
'Track',
'MultiTrack',
]);
/** A ground overlay: an image (or colour) on a box or a quad. */
function kmlOverlay(el, name, out) {
const quad = readCoordinates(child(el, 'LatLonQuad', true));
const href = text(child(el, 'Icon'), 'href') || null;
const color = kmlColor(el);
const mode = text(el, 'altitudeMode');
const gxMode = text(el, 'altitudeMode', true);
const height =
mode === 'absolute' || (!mode && gxMode === 'relativeToSeaFloor')
? number(el, 'altitude')
: undefined;
let rect = null;
let rotation;
const box = quad ? null : child(el, 'LatLonBox');
// Neither box nor quad: nowhere to draw it, as before.
if (box) {
// Missing bounds are 0; longitudes wrap into [-180, 180].
const wrap = (lon = 0) =>
lon >= -180 && lon <= 180
? lon
: ((((lon + 180) % 360) + 360) % 360) - 180;
const clampLat = (lat = 0) => Math.max(-90, Math.min(90, lat));
rect = {
west: wrap(number(box, 'west')),
south: clampLat(number(box, 'south')),
east: wrap(number(box, 'east')),
north: clampLat(number(box, 'north')),
};
// A box upside down has no area to draw (Cesium refused it too).
if (rect.north < rect.south) rect = null;
const turn = number(box, 'rotation');
if (turn !== undefined) rotation = (turn * Math.PI) / 180;
}
out.push({
kind: 'overlay',
name,
rect,
quad,
rotation,
image: href,
// Without an image, the overlay's colour; an image is drawn untinted.
color: href ? undefined : (color ?? WHITE),
height,
});
}
/** A feature's short plain-text name, or undefined. */
function featureName(el) {
try {
return importFeatureName(text(el, 'name'));
} catch {
return undefined;
}
}
/**
* The features of a sanitized KML document.
* @param {Document} doc
* @returns {{features: object[], entityCount: number, drawable: boolean}}
*/
export function readKmlFeatures(doc) {
const styles = sharedStyles(doc);
const out = [];
out.entities = 0;
let positionless = false;
const visit = (node) => {
switch (node.localName) {
case 'Document':
for (const kid of node.childNodes) if (kid.nodeType === 1) visit(kid);
return;
case 'Folder':
out.entities += 1;
for (const kid of node.childNodes) if (kid.nodeType === 1) visit(kid);
return;
case 'Placemark': {
out.entities += 1;
const name = featureName(node);
const style = finalStyle(node, styles);
// Only the first geometry of a placemark is drawn.
const geometry = [...node.childNodes].find(
(kid) => kid.nodeType === 1 && KML_GEOMETRIES.has(kid.localName),
);
if (geometry) kmlGeometry(geometry, name, style, out);
else {
// No geometry: an icon with nowhere to stand.
const pin = kmlPin(name, style, null, 'absolute');
if (pin.image) positionless = true;
}
return;
}
case 'GroundOverlay':
out.entities += 1;
kmlOverlay(node, featureName(node), out);
return;
default:
}
};
let root = doc.documentElement;
if (root?.localName === 'kml')
root = [...root.childNodes].find(
(kid) =>
kid.nodeType === 1 &&
['Document', 'Folder', 'Placemark', 'GroundOverlay'].includes(
kid.localName,
),
);
if (root) visit(root);
const entityCount = out.entities;
const features = [...out];
return {
features,
entityCount,
drawable: positionless || features.some(drawable),
};
}
/** The longest step, in degrees, of a rhumb line drawn as a path. */
const RHUMB_STEP = 0.5;
/**
* The most points the steps may add to one file, as many as it may hold
* (`MAX_IMPORT_POSITIONS`); past it, the rest are drawn as they are.
*/
const RHUMB_BUDGET = 250_000;
const mercatorY = (lat) =>
Math.log(Math.tan(Math.PI / 4 + (lat * Math.PI) / 360));
const fromMercatorY = (y) => (Math.atan(Math.sinh(y)) * 180) / Math.PI;
/**
* A path along rhumb lines, as GeoJSON is drawn: each long step split at
* most `RHUMB_STEP` degrees apart along the line of constant bearing (the
* draw port joins points the short way over the globe), the short way
* round in longitude. Steps are added while `budget.left` allows.
* @param {number[][]} coords `[lon, lat, height]`
* @param {{left: number}} [budget] Points it may still add, shared by a file.
* @returns {number[][]}
*/
export function rhumbPath(coords, budget = { left: RHUMB_BUDGET }) {
const out = [];
for (let i = 0; i < coords.length; i++) {
const b = coords[i];
const a = coords[i - 1];
if (a) {
const dLon = ((((b[0] - a[0] + 180) % 360) + 360) % 360) - 180;
const steps = Math.ceil(
Math.max(Math.abs(dLon), Math.abs(b[1] - a[1])) / RHUMB_STEP,
);
if (
steps > 1 &&
steps - 1 <= budget.left &&
Math.abs(a[1]) < 89.9 &&
Math.abs(b[1]) < 89.9
) {
budget.left -= steps - 1;
const ya = mercatorY(a[1]);
const yb = mercatorY(b[1]);
for (let k = 1; k < steps; k++) {
const f = k / steps;
let lon = a[0] + dLon * f;
if (lon > 180) lon -= 360;
else if (lon < -180) lon += 360;
out.push([
lon,
fromMercatorY(ya + (yb - ya) * f),
a[2] + (b[2] - a[2]) * f,
]);
}
}
}
out.push(b);
}
return out;
}
/** Whether a feature draws anything, as the loaders' output is checked. */
function drawable(feature) {
switch (feature.kind) {
case 'pin':
return Boolean(feature.image);
case 'line':
case 'wall':
return (feature.coords?.length ?? 0) >= 2;
case 'polygon':
return (feature.rings[0]?.length ?? 0) >= 3;
case 'overlay':
// Counted as before even without bounds, though it then draws nothing.
return true;
default:
return false;
}
}
/**
* The features of prepared GeoJSON (names only, two-dimensional
* coordinates), drawn in one colour: pins in it standing on the ground,
* lines draped in it three pixels wide, polygons filled with it at a
* quarter opacity.
* @param {object} geojson
* @param {string} color A CSS colour.
* @returns {{features: object[], entityCount: number, drawable: boolean}}
*/
export function readGeoJsonFeatures(geojson, color) {
const rgba = cssColor(color) ?? [...WHITE];
const fill = [rgba[0], rgba[1], rgba[2], 0.25];
const pin = plainPin(rgba, GEOJSON_PIN_SIZE);
const features = [];
let entityCount = 0;
const at = (c) => [c[0], c[1], c[2] ?? 0];
const geometry = (g, name) => {
switch (g?.type) {
case 'Point':
entityCount += 1;
features.push(geoPin(name, g.coordinates));
return;
case 'MultiPoint':
for (const c of g.coordinates) {
entityCount += 1;
features.push(geoPin(name, c));
}
return;
case 'LineString':
entityCount += 1;
features.push(geoLine(name, g.coordinates));
return;
case 'MultiLineString':
for (const c of g.coordinates) {
entityCount += 1;
features.push(geoLine(name, c));
}
return;
case 'Polygon':
entityCount += 1;
features.push(geoPolygon(name, g.coordinates));
return;
case 'MultiPolygon':
for (const c of g.coordinates) {
entityCount += 1;
features.push(geoPolygon(name, c));
}
return;
case 'GeometryCollection':
for (const part of g.geometries) geometry(part, name);
return;
default:
}
};
const geoPin = (name, c) => ({
kind: 'pin',
name,
lon: c[0],
lat: c[1],
height: c[2] ?? 0,
mode: c.length > 2 ? 'absolute' : 'clamp',
image: pin,
size: [GEOJSON_PIN_SIZE, GEOJSON_PIN_SIZE],
anchor: 'bottom',
});
const budget = { left: RHUMB_BUDGET };
const geoLine = (name, coords) => ({
kind: 'line',
name,
coords: rhumbPath(coords.map(at), budget),
mode: 'draped',
color: rgba,
width: 3,
});
const geoPolygon = (name, rings) => ({
kind: 'polygon',
name,
rings: rings.map((ring) => rhumbPath(ring.map(at), budget)),
clamp: true,
extrude: false,
fill,
outline: null,
});
const feature = (f) => {
if (f.geometry === null) {
// A feature without geometry is a map object that draws nothing.
entityCount += 1;
return;
}
geometry(f.geometry, f.properties?.name || undefined);
};
if (geojson?.type === 'FeatureCollection')
for (const f of geojson.features) feature(f);
else if (geojson?.type === 'Feature') feature(geojson);
else geometry(geojson, undefined);
return { features, entityCount, drawable: features.some(drawable) };
}
+342
View File
@@ -0,0 +1,342 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { Window } from 'happy-dom';
import {
readGeoJsonFeatures,
readKmlFeatures,
rhumbPath,
} from './geoImportFeatures.js';
const { DOMParser } = new Window();
/** A KML document around `body`, parsed. */
const kml = (body) =>
new DOMParser().parseFromString(
'<?xml version="1.0" encoding="UTF-8"?>' +
'<kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2">' +
`<Document>${body}</Document></kml>`,
'application/xml',
);
const point = (coordinates = '1,2,0', extra = '') =>
`<Point>${extra}<coordinates>${coordinates}</coordinates></Point>`;
test('a placemark takes its last inline style over its shared one, property by property', () => {
const { features } = readKmlFeatures(
kml(`
<Style id="shared">
<IconStyle><scale>2</scale><color>ff0000ff</color>
<Icon><href>data:image/png;base64,AAAA</href></Icon></IconStyle>
</Style>
<StyleMap id="map">
<Pair><key>normal</key><styleUrl>#shared</styleUrl></Pair>
<Pair><key>highlight</key><styleUrl>#other</styleUrl></Pair>
</StyleMap>
<Placemark><name>shared</name><styleUrl>#map</styleUrl>${point()}</Placemark>
<Placemark><name>inline</name><styleUrl>#shared</styleUrl>
<Style><IconStyle><color>ff00ff00</color></IconStyle></Style>
<Style><IconStyle><scale>0.5</scale></IconStyle></Style>
${point()}</Placemark>
<Placemark><name>none</name><Style><IconStyle><Icon/></IconStyle></Style>${point()}</Placemark>
<Placemark><name>default</name>${point()}</Placemark>`),
);
const [shared, inline, none, fallback] = features;
assert.equal(shared.image, 'data:image/png;base64,AAAA');
assert.equal(shared.scale, 2);
assert.deepEqual(shared.color, [1, 0, 0, 1], 'aabbggrr is red');
// Only the last inline style counts; the shared one fills what it leaves.
assert.equal(inline.scale, 0.5);
assert.deepEqual(inline.color, [1, 0, 0, 1]);
assert.equal(inline.image, 'data:image/png;base64,AAAA');
assert.equal(none.image, null, 'an empty Icon draws no icon');
assert.match(fallback.image.svg, /rgba\(255,255,0,1\)/, 'the yellow pin');
for (const f of features) {
assert.deepEqual(f.size, [32, 32]);
assert.deepEqual(f.scaleByDistance, {
near: 2414016,
nearValue: 1,
far: 1.6093e7,
farValue: 0.1,
});
assert.equal(f.offsetScalesByDistance, true, 'its offset shrinks too');
}
});
test('an icon hot spot and heading place and turn the icon', () => {
const { features } = readKmlFeatures(
kml(`
<Placemark><Style><IconStyle><scale>0.8</scale><heading>90</heading>
<hotSpot x="0.5" y="0" xunits="fraction" yunits="fraction"/>
</IconStyle></Style>${point()}</Placemark>
<Placemark><Style><IconStyle><heading>0</heading>
<hotSpot x="4" y="8" xunits="pixels" yunits="insetPixels"/>
</IconStyle></Style>${point()}</Placemark>`),
);
// Standing on its bottom centre: up by half its 25.6 px height.
assert.deepEqual(features[0].pixelOffset, { x: 0, y: -12.8 });
assert.equal(features[0].course, 90);
assert.deepEqual(features[1].pixelOffset, { x: 12, y: 8 });
assert.equal(features[1].course, undefined, 'heading 0 is no heading');
});
test('points, paths and polygons keep their altitude modes', () => {
const { features } = readKmlFeatures(
kml(`
<Style id="s"><LineStyle><color>ff00ffff</color><width>6</width></LineStyle>
<PolyStyle><color>66ff0000</color></PolyStyle></Style>
<Placemark>${point('1,2,30')}</Placemark>
<Placemark>${point('1,2,30', '<altitudeMode>relativeToGround</altitudeMode>')}</Placemark>
<Placemark>${point('1,2,30', '<altitudeMode>absolute</altitudeMode>')}</Placemark>
<Placemark><styleUrl>#s</styleUrl><LineString><tessellate>1</tessellate>
<coordinates>1,2 3,4</coordinates></LineString></Placemark>
<Placemark><styleUrl>#s</styleUrl><LineString><tessellate>1</tessellate>
<altitudeMode>absolute</altitudeMode><coordinates>1,2,600 3,4,900</coordinates></LineString></Placemark>
<Placemark><styleUrl>#s</styleUrl><LineString><extrude>1</extrude>
<altitudeMode>relativeToGround</altitudeMode><coordinates>1,2,150 3,4,150</coordinates></LineString></Placemark>
<Placemark><styleUrl>#s</styleUrl><Polygon><outerBoundaryIs><LinearRing>
<coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></outerBoundaryIs>
<innerBoundaryIs><LinearRing><coordinates>0.1,0.1 0.2,0.1 0.2,0.2 0.1,0.1</coordinates></LinearRing></innerBoundaryIs>
</Polygon></Placemark>
<Placemark><Polygon><extrude>1</extrude><altitudeMode>absolute</altitudeMode>
<outerBoundaryIs><LinearRing><coordinates>0,0,200 1,0,200 1,1,200 0,0,200</coordinates></LinearRing></outerBoundaryIs>
</Polygon></Placemark>
<Placemark><Style><PolyStyle><fill>0</fill><outline>0</outline></PolyStyle></Style>
<Polygon><outerBoundaryIs><LinearRing><coordinates>0,0 1,0 1,1 0,0</coordinates></LinearRing></outerBoundaryIs></Polygon></Placemark>`),
);
const [
clamped,
relative,
absolute,
draped,
inAir,
wall,
ground,
block,
bare,
] = features;
assert.deepEqual(
[clamped.mode, relative.mode, absolute.mode],
['clamp', 'relative', 'absolute'],
);
assert.equal(relative.height, 30);
assert.deepEqual(
[draped.mode, draped.width, draped.color],
['draped', 6, [1, 1, 0, 1]],
);
assert.deepEqual([inAir.mode, inAir.coords[1]], ['3d', [3, 4, 900]]);
assert.equal(wall.kind, 'wall');
assert.deepEqual(wall.fill, [0, 0, 1, 0x66 / 255]);
assert.deepEqual(wall.outline, [1, 1, 0, 1], 'outlined in its line colour');
assert.equal(wall.outlineWidth, 6);
assert.equal(ground.clamp, true);
assert.equal(ground.rings.length, 2, 'with its hole');
assert.deepEqual(ground.fill, [0, 0, 1, 0x66 / 255]);
assert.equal(block.clamp, false);
assert.equal(block.extrude, true);
assert.deepEqual(block.fill, [1, 1, 1, 1], 'white by default');
assert.deepEqual(block.outline, [1, 1, 1, 1]);
assert.equal(bare.fill, null);
assert.equal(bare.outline, null);
});
test('ground overlays are boxes turned by their rotation, or quads', () => {
const { features, drawable } = readKmlFeatures(
kml(`
<GroundOverlay><name>box</name><Icon><href>blob:packed</href></Icon>
<altitudeMode>absolute</altitudeMode><altitude>120</altitude>
<LatLonBox><north>2</north><south>1</south><east>200</east><west>-10</west>
<rotation>20</rotation></LatLonBox></GroundOverlay>
<GroundOverlay><color>80ff0000</color>
<gx:LatLonQuad><coordinates>0,0 1,0 1,1 0,1</coordinates></gx:LatLonQuad></GroundOverlay>`),
);
const [box, quad] = features;
assert.equal(drawable, true);
assert.deepEqual(box.rect, { west: -10, south: 1, east: -160, north: 2 });
assert.ok(Math.abs(box.rotation - (20 * Math.PI) / 180) < 1e-12);
assert.equal(box.image, 'blob:packed');
assert.equal(box.color, undefined, 'an image is drawn untinted');
assert.equal(box.height, 120);
assert.equal(quad.quad.length, 4);
assert.deepEqual(quad.color, [0, 0, 1, 128 / 255]);
assert.equal(quad.height, undefined, 'on the ground');
});
test('map objects are counted as before: folders, placemarks and each part', () => {
const read = readKmlFeatures(
kml(`
<Folder><name>f</name>
<Placemark><MultiGeometry>${point()}<LineString><coordinates>1,2 3,4</coordinates></LineString>
<MultiGeometry>${point()}</MultiGeometry></MultiGeometry></Placemark>
<Placemark><name>only the first geometry</name>${point()}${point('5,6')}</Placemark>
</Folder>
<Placemark><name>nowhere</name></Placemark>`),
);
// Folder, two placemarks and the empty one, three parts and one nested.
assert.equal(read.entityCount, 8);
assert.deepEqual(
read.features.map((f) => f.kind),
['pin', 'line', 'pin', 'pin'],
);
assert.deepEqual([read.features[3].lon, read.features[3].lat], [1, 2]);
assert.equal(read.drawable, true);
assert.equal(
readKmlFeatures(
kml(
'<Placemark><Style><IconStyle><Icon/></IconStyle></Style></Placemark>',
),
).drawable,
false,
'a placemark with no icon and nowhere to stand draws nothing',
);
});
test('GeoJSON draws in one colour: pins on the ground, draped lines, quarter fills', () => {
const read = readGeoJsonFeatures(
{
type: 'FeatureCollection',
features: [
{
type: 'Feature',
properties: { name: 'a' },
geometry: {
type: 'MultiPoint',
coordinates: [
[1, 2],
[3, 4],
],
},
},
{
type: 'Feature',
properties: {},
geometry: {
type: 'LineString',
coordinates: [
[1, 2],
[3, 4],
],
},
},
{
type: 'Feature',
properties: {},
geometry: {
type: 'MultiPolygon',
coordinates: [
[
[
[0, 0],
[1, 0],
[1, 1],
[0, 0],
],
],
[
[
[2, 2],
[3, 2],
[3, 3],
[2, 2],
],
],
],
},
},
{
type: 'Feature',
properties: {},
geometry: {
type: 'GeometryCollection',
geometries: [{ type: 'Point', coordinates: [5, 6] }],
},
},
{ type: 'Feature', properties: {}, geometry: null },
],
},
'#39d0ff',
);
assert.equal(read.entityCount, 7);
const [a, b, line, p1, p2, gc] = read.features;
assert.equal(a.name, 'a');
assert.deepEqual([a.mode, a.anchor, a.size], ['clamp', 'bottom', [48, 48]]);
assert.equal(a.image, b.image, 'one pin image for the file');
assert.deepEqual([line.mode, line.width], ['draped', 3]);
assert.deepEqual(line.color, [0x39 / 255, 0xd0 / 255, 1, 1]);
assert.deepEqual(p1.fill, [0x39 / 255, 0xd0 / 255, 1, 0.25]);
assert.equal(p1.outline, null);
assert.equal(p2.clamp, true);
assert.equal(gc.kind, 'pin');
assert.equal(read.drawable, true);
});
test('a ground overlay without bounds, or upside down, draws nowhere', () => {
const { features, drawable } = readKmlFeatures(
kml(`
<GroundOverlay><color>ff00ff00</color></GroundOverlay>
<GroundOverlay><color>ff00ff00</color>
<LatLonBox><north>1</north><south>2</south><east>3</east><west>4</west></LatLonBox></GroundOverlay>`),
);
assert.deepEqual(
features.map((f) => [f.kind, f.rect, f.quad]),
[
['overlay', null, undefined],
['overlay', null, undefined],
],
);
assert.equal(drawable, true, 'counted as before');
});
test('a hot spot without units is a fraction', () => {
const { features } = readKmlFeatures(
kml(
`<Placemark><Style><IconStyle><hotSpot x="0.5" y="0"/></IconStyle></Style>${point()}</Placemark>`,
),
);
assert.deepEqual(features[0].pixelOffset, { x: 0, y: -16 });
});
test('GeoJSON lines and rings follow rhumb lines, as they were drawn', () => {
const path = rhumbPath([
[0, 60, 0],
[10, 60, 0],
]);
assert.equal(path.length, 21, 'half a degree apart');
assert.ok(
path.every(([, lat]) => Math.abs(lat - 60) < 1e-9),
'along the parallel',
);
const across = rhumbPath([
[179, 0, 0],
[-179, 0, 0],
]);
assert.deepEqual(
across.map(([lon]) => lon),
[179, 179.5, 180, -179.5, -179],
'the short way over the antimeridian',
);
const short = rhumbPath([
[0, 0, 0],
[0.2, 0.2, 0],
]);
assert.equal(short.length, 2, 'short steps are left alone');
const { features } = readGeoJsonFeatures(
{
type: 'LineString',
coordinates: [
[0, 60],
[10, 60],
],
},
'#39d0ff',
);
assert.equal(features[0].coords.length, 21);
});
test('rhumb steps stop once a file has added as many points as it may hold', () => {
const budget = { left: 30 };
const zigzag = Array.from({ length: 6 }, (_, i) => [i % 2 ? 10 : 0, 0, 0]);
const path = rhumbPath(zigzag, budget);
// Each 10-degree step adds 19 points: one fits, the rest are drawn as given.
assert.equal(path.length, 6 + 19);
assert.equal(budget.left, 11);
});
+527 -113
View File
@@ -1,128 +1,542 @@
import * as Cesium from 'cesium';
/**
* The drawn part of the file import: what `geoImportFeatures.js` read from
* a file, drawn through the draw port in three sets (its pins, its lines,
* its shapes), its ground pins placed on the ground in batches, and its
* footprint read back.
*/
import {
GeoImportError,
MAX_IMPORT_ENTITIES,
boundedImport,
} from './geoImportShared.js';
import { msg } from '../i18n/marker.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { heightsOf } from '../queries/heights.js';
import {
drawOf,
findCamera,
findFrame,
findGlobe,
} from '../render/rendererOf.js';
const STYLE = [
'image',
'scale',
'rotation',
'alignedAxis',
'horizontalOrigin',
'verticalOrigin',
'color',
'eyeOffset',
'pixelOffset',
'width',
'height',
'scaleByDistance',
'translucencyByDistance',
'pixelOffsetScaleByDistance',
'distanceDisplayCondition',
'sizeInMeters',
'disableDepthTestDistance',
'imageSubRegion',
];
/** Ground pins are placed this many at a time, yielding between batches. */
const GROUND_BATCH = 256;
/** Below this camera height, in-view pins over a mesh are clamped to it. */
const MESH_CLAMP_HEIGHT = 250_000;
/** How long the terrain has to say it is the bare ellipsoid (it answers at once). */
const ELLIPSOID_PROBE_MS = 100;
class ImportedBillboards extends Cesium.BillboardCollection {
update(frameState) {
// Height queries should find the map, never another imported marker.
// Ordinary click picks and rendered screenshots still include the pins.
if (frameState.passes.pick && frameState.passes.offscreen) return;
super.update(frameState);
}
let drawings = 0;
const finite = (n) => Number.isFinite(n);
/** Whether `rect` (degrees, maybe across the antimeridian) holds the point. */
function inRect(rect, lon, lat) {
if (lat < rect.south || lat > rect.north) return false;
return rect.west <= rect.east
? lon >= rect.west && lon <= rect.east
: lon >= rect.west || lon <= rect.east;
}
/** Own static imported pins without a per-frame Entity visualizer walk. */
export function createImportedPins(dataSource, viewer) {
const all = dataSource.entities.values.slice();
const now = Cesium.JulianDate.now();
const pins = all.filter((entity) => entity.billboard && entity.position);
if (!pins.length) return { mount() {}, sync() {}, destroy() {} };
const collection = new ImportedBillboards({ scene: viewer.scene });
const billboards = [];
try {
for (const entity of pins) {
const position = entity.position.getValue(now);
if (
!position ||
![position.x, position.y, position.z].every(Number.isFinite)
)
throw new Error('Invalid imported point position.');
const options = {
id: entity,
position,
show:
entity.isShowing && entity.billboard.show?.getValue(now) !== false,
heightReference: Cesium.HeightReference.NONE,
};
for (const key of STYLE) {
const value = entity.billboard[key]?.getValue(now);
if (value !== undefined) options[key] = value;
}
billboards.push(collection.add(options));
/**
* The corners of an overlay's box turned by its rotation (radians
* counter-clockwise about its centre), as `[lon, lat]`.
*/
function turnedCorners({ west, south, east: eastEdge, north }, rotation = 0) {
// Across the antimeridian, east is past 180 while turning.
const east = eastEdge < west ? eastEdge + 360 : eastEdge;
const wrap = (lon) => (lon > 180 ? lon - 360 : lon < -180 ? lon + 360 : lon);
const corners = [
[west, south],
[east, south],
[west, north],
[east, north],
];
if (!rotation) return corners.map(([lon, lat]) => [wrap(lon), lat]);
const lon0 = (west + east) / 2;
const lat0 = (south + north) / 2;
const k = Math.cos((lat0 * Math.PI) / 180) || 1;
const cos = Math.cos(rotation);
const sin = Math.sin(rotation);
return corners.map(([lon, lat]) => {
const x = (lon - lon0) * k;
const y = lat - lat0;
return [wrap(lon0 + (x * cos - y * sin) / k), lat0 + x * sin + y * cos];
});
}
/**
* Draw an imported file's features on `viewer`. Nothing is drawn until
* `mount()`; `refreshGround()` places the ground pins first.
* @param {object} viewer
* @param {object[]} features From `readKmlFeatures` or `readGeoJsonFeatures`.
*/
export function createImportedDrawing(viewer, features) {
const prefix = `geo-import:${++drawings}`;
const ids = {
icons: `${prefix}:pins`,
lines: `${prefix}:lines`,
shapes: `${prefix}:shapes`,
};
const pins = features.filter((f) => f.kind === 'pin');
for (const pin of pins)
if (!finite(pin.lon) || !finite(pin.lat) || !finite(pin.height))
throw new GeoImportError(msg('That file has invalid point coordinates.'));
// Pins on the ground or above it, placed there by `refreshGround`.
const grounded = pins
.filter((pin) => pin.mode !== 'absolute')
.map((pin) => ({
pin,
offset: pin.mode === 'relative' ? pin.height : 0,
groundHeight: undefined,
}));
let sets = null;
/** The items last handed to each set, for inspection. */
let drawn = { icons: [], lines: [], shapes: [] };
let show = true;
let destroyed = false;
/** The surface last asked whether it is the bare ellipsoid, and its answer. */
let probed;
let ellipsoid = false;
const meta = (feature) => (feature.name ? { name: feature.name } : undefined);
const pos = ([lon, lat, height]) => ({ lon, lat, height });
const ecef = ([lon, lat, height]) => fromDegrees(lon, lat, height);
function pinItem(pin, index) {
const item = {
id: `p${index}`,
pos: { lon: pin.lon, lat: pin.lat, height: pin.height },
height: 'absolute',
image: pin.image,
size: pin.size,
meta: meta(pin),
};
if (pin.scale !== undefined) item.scale = pin.scale;
if (pin.color) item.color = pin.color;
if (pin.anchor) item.anchor = pin.anchor;
if (pin.scaleByDistance) item.scaleByDistance = pin.scaleByDistance;
if (pin.pixelOffset) item.pixelOffset = pin.pixelOffset;
if (pin.offsetScalesByDistance) item.offsetScalesByDistance = true;
if (pin.course !== undefined) {
// Turned clockwise by its heading from the Earth's axis as it stands
// on screen, as Cesium's KML icons were.
item.rotationMode = 'axis';
item.alignedAxis = { x: 0, y: 0, z: 1 };
item.rotation = (-pin.course * Math.PI) / 180;
}
} catch (error) {
collection.destroy();
throw error;
// On the ground or above it, drawn over what is in front.
if (pin.mode !== 'absolute') item.disableDepthTest = Infinity;
return item;
}
// Rebuild once before the source is added to DataSourceDisplay. Removing
// one entity at a time would itself make this transition quadratic.
dataSource.entities.suspendEvents();
try {
dataSource.entities.removeAll();
for (const entity of all)
if (!entity.billboard || !entity.position)
dataSource.entities.add(entity);
} finally {
dataSource.entities.resumeEvents();
function lineItem(line, id) {
if ((line.coords?.length ?? 0) < 2) return null;
return {
id,
positions: line.coords.map((c) =>
ecef(line.mode === 'draped' ? [c[0], c[1], 0] : c),
),
widthPx: line.width,
mode: line.mode,
style: { kind: 'solid', color: line.color },
meta: meta(line),
};
}
Object.defineProperty(dataSource, 'importedEntities', {
value: all,
configurable: true,
});
Object.defineProperty(dataSource, 'importedBillboards', {
value: collection,
configurable: true,
});
let show = dataSource.show,
mounted = false,
destroyed = false;
Object.defineProperty(dataSource, 'show', {
configurable: true,
get: () => show,
set(value) {
show = Boolean(value);
dataSource.entities.show = show;
collection.show = show;
},
});
collection.show = show;
return {
mount() {
if (destroyed || mounted) return;
viewer.scene.primitives?.add(collection);
mounted = true;
},
sync() {
if (destroyed) return;
for (let i = 0; i < pins.length; i++) {
billboards[i].position = pins[i].position.getValue(now);
billboards[i].show =
pins[i].isShowing && pins[i].billboard.show?.getValue(now) !== false;
function shapeItem(feature, id) {
switch (feature.kind) {
case 'polygon': {
const rings = feature.rings.filter((ring) => ring.length >= 3);
if (!rings.length || feature.rings[0].length < 3) return null;
if (feature.clamp)
// On the ground its outline is not drawn, as before.
return feature.fill
? {
id,
geometry: {
kind: 'polygon',
rings: rings.map((ring) =>
ring.map(([lon, lat]) => ({ lon, lat })),
),
},
fill: feature.fill,
height: 'clampGround',
meta: meta(feature),
}
: null;
const item = {
id,
geometry: {
kind: 'polygon',
rings: rings.map((ring) => ring.map(pos)),
perPositionHeight: true,
},
fill: feature.fill,
outline: feature.outline,
lit: true,
meta: meta(feature),
};
if (feature.outlineWidth !== undefined)
item.outlineWidth = feature.outlineWidth;
if (feature.extrude) item.extrudeHeight = 0;
return item;
}
viewer.scene.requestRender?.();
case 'wall': {
if ((feature.coords?.length ?? 0) < 2) return null;
const item = {
id,
geometry: { kind: 'wall', positions: feature.coords.map(pos) },
fill: feature.fill,
outline: feature.outline,
lit: true,
meta: meta(feature),
};
if (feature.outlineWidth !== undefined)
item.outlineWidth = feature.outlineWidth;
return item;
}
case 'overlay': {
const fill = feature.image ? { image: feature.image } : feature.color;
const height =
feature.height === undefined ? 'clampGround' : 'absolute';
if (feature.quad) {
if (feature.quad.length < 3) return null;
const at = feature.height ?? 0;
return {
id,
geometry: {
kind: 'polygon',
rings: [
feature.quad.map(([lon, lat]) => ({ lon, lat, height: at })),
],
},
fill,
height,
...(feature.height !== undefined ? { lit: true } : {}),
meta: meta(feature),
};
}
if (!feature.rect) return null;
const geometry = { kind: 'rectangle', rect: feature.rect };
if (feature.rotation) geometry.rotation = feature.rotation;
if (feature.height !== undefined) geometry.height = feature.height;
const item = { id, geometry, fill, height, meta: meta(feature) };
// In the air it is lit, as it was; on the ground it is not.
if (feature.height !== undefined) item.lit = true;
return item;
}
default:
return null;
}
}
/** A feature's footprint, `[lon, lat, height]`. */
function footprintOf(feature) {
switch (feature.kind) {
case 'pin':
return [[feature.lon, feature.lat, feature.height]];
case 'line':
return (feature.coords ?? []).map((c) =>
feature.mode === 'draped' ? [c[0], c[1], 0] : c,
);
case 'wall':
return feature.coords ?? [];
case 'polygon':
return feature.rings.flatMap((ring) =>
feature.clamp ? ring.map(([lon, lat]) => [lon, lat, 0]) : ring,
);
case 'overlay':
if (feature.quad)
return feature.quad.map(([lon, lat]) => [lon, lat, 0]);
if (!feature.rect) return [];
return turnedCorners(feature.rect, feature.rotation).map(
([lon, lat]) => [lon, lat, feature.height || 0],
);
default:
return [];
}
}
function draw() {
const port = drawOf(viewer);
const icons = [];
const lines = [];
const shapes = [];
features.forEach((feature, index) => {
if (feature.kind === 'pin') {
// A pin with no icon draws nothing, but frames its file.
if (!feature.image) return;
const item = pinItem(feature, index);
icons.push(item);
} else if (feature.kind === 'line') {
const item = lineItem(feature, `l${index}`);
if (!item) return;
lines.push(item);
} else {
const item = shapeItem(feature, `s${index}`);
if (!item) return;
shapes.push(item);
}
});
drawn = { icons, lines, shapes };
sets = {};
try {
if (shapes.length) {
sets.shapes = port.shapes({ id: ids.shapes, show });
sets.shapes.set(shapes);
}
if (lines.length) {
sets.lines = port.lines({ id: ids.lines, show });
sets.lines.set(lines);
}
if (icons.length) {
sets.icons = port.icons({ id: ids.icons, show });
sets.icons.set(icons);
}
} catch (error) {
disposeSets();
throw error;
}
}
function disposeSets() {
for (const set of Object.values(sets ?? {})) set.dispose();
sets = null;
}
/** Move the drawn pins to where they now stand. */
function redrawPins() {
if (!sets?.icons) return;
const items = [];
features.forEach((feature, index) => {
if (feature.kind === 'pin' && feature.image)
items.push(pinItem(feature, index));
});
sets.icons.upsert(items);
drawn = { ...drawn, icons: items };
findFrame(viewer)?.requestRender('geo-import');
}
/**
* Whether the terrain at `point` is the bare ellipsoid, whose height is
* exactly 0 while its drawn tiles can sag kilometres below it. It answers
* at once; any other terrain is left to load in its own time.
*/
async function onEllipsoid(heights, point, signal) {
const terrain = { against: 'terrain' };
let timer;
try {
// The ellipsoid answers 0, and nothing once told to miss there.
const [plain, missing] = await Promise.race([
Promise.all([
heights.batch([point], terrain),
heights.batch([point], { ...terrain, ellipsoidMisses: true }),
]),
new Promise((resolve) => {
timer = setTimeout(() => resolve([[], []]), ELLIPSOID_PROBE_MS);
}),
]);
return plain[0] === 0 && missing[0] === null;
} catch {
return false;
} finally {
clearTimeout(timer);
signal?.throwIfAborted();
}
}
/**
* Place the ground pins on the ground now under them, in batches: the
* terrain's height (0 on the bare ellipsoid), or over a mesh (the globe
* hidden) the mesh in view below 250 km; relative pins that far above it.
*/
async function settle(signal) {
const heights = heightsOf(viewer);
// Whether the terrain is the bare ellipsoid, asked once for each
// surface (each time when the renderer cannot say the surface changed).
const version = findGlobe(viewer)?.surfaceVersion?.();
if (grounded.length && (version === undefined || version !== probed)) {
const { pin } = grounded[0];
ellipsoid = await onEllipsoid(
heights,
{ lon: pin.lon, lat: pin.lat },
signal,
);
probed = version;
}
for (let at = 0; at < grounded.length; at += GROUND_BATCH) {
signal?.throwIfAborted();
const batch = grounded.slice(at, at + GROUND_BATCH);
const mesh =
findGlobe(viewer)?.isGlobeVisible?.() === false &&
heights.supported().clamp;
const sampled = batch.map(({ pin }) =>
ellipsoid
? 0
: heights.now({ lon: pin.lon, lat: pin.lat }, { against: 'terrain' }),
);
const ground = batch.map(({ groundHeight }, i) => {
// A hidden coarse globe can answer kilometres below the surface;
// the mesh ray must not start there.
const h = sampled[i];
if (mesh) return groundHeight ?? Math.max(0, finite(h) ? h : 0);
return finite(h) ? h : groundHeight || 0;
});
const camera = findCamera(viewer);
const height = camera?.pose?.()?.height;
if (mesh && finite(height) && height < MESH_CLAMP_HEIGHT) {
const rect = camera.viewRectangle?.();
const indices = [];
if (rect)
for (let i = 0; i < batch.length; i++)
if (inRect(rect, batch[i].pin.lon, batch[i].pin.lat))
indices.push(i);
if (indices.length) {
const resolved = await boundedImport(
heights.clampBatch(
indices.map((i) =>
fromDegrees(
batch[i].pin.lon,
batch[i].pin.lat,
Math.max(0, ground[i]),
),
),
),
signal,
);
for (let k = 0; k < indices.length; k++) {
const h = resolved[k] && toLonLatH(resolved[k])?.height;
if (finite(h)) ground[indices[k]] = h;
}
}
}
signal?.throwIfAborted();
for (let i = 0; i < batch.length; i++) {
if (!finite(ground[i]))
throw new GeoImportError(
msg(
'Ground heights are not available for that file. Try again when the map has loaded.',
),
);
batch[i].groundHeight = ground[i];
batch[i].pin.height = ground[i] + batch[i].offset;
}
if (at + batch.length < grounded.length)
await new Promise((resolve) => setTimeout(resolve, 0));
}
}
return {
get show() {
return show;
},
set show(value) {
show = Boolean(value);
for (const set of Object.values(sets ?? {})) set.show = show;
},
/** Draw it; once, and never after `destroy`. */
mount() {
if (destroyed || sets) return;
draw();
},
/** Place the ground pins again, and move the drawn ones. */
async refreshGround(signal) {
if (destroyed) return;
await settle(signal);
if (!destroyed) redrawPins();
},
/** Every shown position, path vertex, ring vertex and overlay corner. */
points() {
if (!show) return [];
return features.flatMap(footprintOf);
},
/** The draw sets' ids, by kind. */
ids,
/** The items each set was last given (contract items), by kind. */
items() {
return {
icons: [...drawn.icons],
lines: [...drawn.lines],
shapes: [...drawn.shapes],
};
},
destroy() {
if (destroyed) return;
destroyed = true;
if (viewer.trackedEntity && pins.includes(viewer.trackedEntity))
viewer.trackedEntity = undefined;
if (viewer.selectedEntity && pins.includes(viewer.selectedEntity))
viewer.selectedEntity = undefined;
if (mounted && !viewer.scene.primitives?.isDestroyed?.())
viewer.scene.primitives?.remove(collection);
if (!collection.isDestroyed()) collection.destroy();
all.length = 0;
pins.length = 0;
billboards.length = 0;
disposeSets();
drawn = { icons: [], lines: [], shapes: [] };
},
};
}
/**
* Check what was read of a file and place its ground pins. The refusals a
* person reads are `GeoImportError`s; the caller revokes what it owns on
* any failure.
* @param {{features: object[], entityCount: number, drawable: boolean}} read
* @param {object} viewer
* @param {AbortSignal} [signal]
* @returns {Promise<{entityCount: number, drawing: object, refreshGround: Function}>}
*/
export async function settleImportedDrawing(read, viewer, signal) {
const { features, entityCount, drawable } = read;
if (entityCount > MAX_IMPORT_ENTITIES)
throw new GeoImportError(
`That file has ${entityCount.toLocaleString()} map objects; the limit is ${MAX_IMPORT_ENTITIES.toLocaleString()}.`,
msg('That file has {count} map objects; the limit is {limit}.'),
{
count: entityCount,
limit: MAX_IMPORT_ENTITIES,
},
);
if (!drawable)
throw new GeoImportError(msg('That file has nothing to draw.'));
const drawing = createImportedDrawing(viewer, features);
try {
await drawing.refreshGround(signal);
} catch (error) {
drawing.destroy();
throw error instanceof GeoImportError
? error
: new GeoImportError(
msg('Ground heights could not be read. Try that file again.'),
);
}
return {
entityCount,
drawing,
refreshGround: (refreshSignal) =>
drawing.refreshGround(
refreshSignal
? AbortSignal.any([refreshSignal, AbortSignal.timeout(15_000)])
: AbortSignal.timeout(15_000),
),
};
}
/**
* Take an imported file's drawing off the globe.
* @param {object} drawing
*/
export function removeImportedDrawing(drawing) {
drawing?.destroy();
}
/**
* Show or hide an imported file's drawing.
* @param {object} drawing
* @param {boolean} show
*/
export function showImportedDrawing(drawing, show) {
drawing.show = show;
}
/**
* The footprint of an imported file's drawing, `[lon, lat, height]`; none
* while it is hidden.
* @param {object} drawing
*/
export function importedDrawingPoints(drawing) {
return drawing?.points?.() ?? [];
}
+234
View File
@@ -0,0 +1,234 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createImportedDrawing } from './geoImportPins.js';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
import { toLonLatH } from '../geo/ellipsoid.js';
const FEATURES = [
{
kind: 'pin',
name: 'tower',
lon: 1,
lat: 2,
height: 0,
mode: 'absolute',
image: 'blob:icon',
size: [32, 32],
scale: 1.5,
color: [1, 0, 0, 1],
course: 90,
pixelOffset: { x: 0, y: -16 },
scaleByDistance: { near: 1, nearValue: 1, far: 2, farValue: 0.1 },
offsetScalesByDistance: true,
},
{ kind: 'pin', lon: 3, lat: 4, height: 0, mode: 'clamp', image: null },
{
kind: 'line',
name: 'walk',
coords: [
[1, 2, 50],
[3, 4, 50],
],
mode: 'draped',
color: [1, 1, 0, 1],
width: 6,
},
{
kind: 'polygon',
rings: [
[
[0, 0, 200],
[1, 0, 200],
[1, 1, 200],
],
],
clamp: false,
extrude: true,
fill: [1, 0, 0, 0.8],
outline: [0, 0, 0, 1],
outlineWidth: 2,
},
{
kind: 'wall',
coords: [
[1, 2, 150],
[3, 4, 150],
],
fill: [0, 1, 0, 0.5],
outline: [0, 1, 0, 1],
},
{
kind: 'overlay',
rect: { west: 0, south: 0, east: 1, north: 1 },
rotation: 0.3,
image: 'blob:overlay',
},
];
/** A drawing of `features` on a renderer double. */
function drawn(features = FEATURES) {
const viewer = {};
const ground = bindFakeGroundRenderer(viewer);
const drawing = createImportedDrawing(viewer, features);
drawing.mount();
const items = (kind) => [
...ground.draw.set(drawing.ids[kind]).items.values(),
];
return { ground, drawing, items };
}
test('pins draw as icons with the look their file gave them', (t) => {
const { ground, drawing, items } = drawn();
t.after(ground.unbind);
const [pin, ...others] = items('icons');
assert.deepEqual(drawing.items().icons, [pin], 'what it hands the set');
assert.equal(others.length, 0, 'a pin with no icon draws nothing');
assert.deepEqual(pin.pos, { lon: 1, lat: 2, height: 0 });
assert.equal(pin.height, 'absolute');
assert.deepEqual(
[pin.image, pin.size, pin.scale, pin.color],
['blob:icon', [32, 32], 1.5, [1, 0, 0, 1]],
);
// As Cesium's KML icon: turned by its heading from the Earth's axis.
assert.deepEqual(
[pin.rotationMode, pin.alignedAxis, pin.rotation],
['axis', { x: 0, y: 0, z: 1 }, -Math.PI / 2],
);
assert.deepEqual(pin.pixelOffset, { x: 0, y: -16 });
assert.equal(pin.offsetScalesByDistance, true);
assert.equal(pin.scaleByDistance.farValue, 0.1);
assert.equal(pin.disableDepthTest, undefined, 'at its own height');
assert.deepEqual(pin.meta, { name: 'tower' });
});
test('paths, polygons, walls and overlays draw as lines and shapes', (t) => {
const { ground, items } = drawn();
t.after(ground.unbind);
const [line] = items('lines');
assert.equal(line.mode, 'draped');
assert.equal(line.widthPx, 6);
assert.deepEqual(line.style, { kind: 'solid', color: [1, 1, 0, 1] });
assert.ok(
line.positions.every((p) => Math.abs(toLonLatH(p).height) < 1e-6),
'draped from the surface',
);
const [polygon, wall, overlay] = items('shapes');
assert.equal(polygon.geometry.perPositionHeight, true);
assert.equal(polygon.extrudeHeight, 0, 'down to the ellipsoid');
assert.deepEqual(polygon.outline, [0, 0, 0, 1]);
assert.equal(polygon.outlineWidth, 2);
assert.equal(polygon.lit, true);
assert.equal(polygon.height, undefined);
assert.equal(wall.geometry.kind, 'wall');
assert.deepEqual(wall.geometry.positions[0], { lon: 1, lat: 2, height: 150 });
assert.equal(overlay.geometry.kind, 'rectangle');
assert.equal(overlay.geometry.rotation, 0.3);
assert.deepEqual(overlay.fill, { image: 'blob:overlay' });
assert.equal(overlay.height, 'clampGround');
});
test('destroying a file takes its sets with it', (t) => {
const { ground, drawing } = drawn();
t.after(ground.unbind);
drawing.destroy();
assert.equal(ground.liveSets().length, 0);
assert.deepEqual(drawing.items(), { icons: [], lines: [], shapes: [] });
});
test('hiding a file hides its sets', (t) => {
const { ground, drawing } = drawn();
t.after(ground.unbind);
drawing.show = false;
for (const id of Object.values(drawing.ids))
assert.equal(ground.draw.set(id).show, false);
drawing.show = true;
assert.equal(ground.draw.set(drawing.ids.icons).show, true);
});
test('a ground pin on the bare ellipsoid stands at 0, not on its sagging tiles', async (t) => {
const pin = { kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp' };
for (const [source, sag, expected] of [
['ellipsoid', -46000, 0],
['ellipsoid', -500, 0],
['terrain', -30, -30],
['terrain', -4000, -4000],
]) {
const { ground, drawing } = drawn([
{ ...pin, image: 'blob:icon' },
{ ...pin, lon: 3, image: 'blob:icon' },
]);
t.after(ground.unbind);
ground.globe.terrain = () => sag;
const probes = [];
ground.renderer.query.sampleHeight = async (points) => {
probes.push(points);
return points.map(() => ({ height: 0, source }));
};
await drawing.refreshGround();
assert.deepEqual(
drawing.items().icons.map((i) => i.pos.height),
[expected, expected],
`${source} ${sag}`,
);
assert.equal(probes.length, 2, 'asked once for the file, both ways');
assert.deepEqual(probes[0], [{ lon: 1, lat: 2 }]);
drawing.destroy();
}
});
test('the ellipsoid is asked about once for each surface', async (t) => {
const pin = { kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp' };
const { ground, drawing } = drawn([{ ...pin, image: 'blob:icon' }]);
t.after(ground.unbind);
let version = 1;
ground.renderer.globe.surfaceVersion = () => version;
ground.globe.terrain = () => -30;
let asked = 0;
ground.renderer.query.sampleHeight = async (points) => {
asked += 1;
return points.map(() => ({ height: -30, source: 'terrain' }));
};
await drawing.refreshGround();
await drawing.refreshGround();
assert.equal(asked, 2, 'one probe, both ways, for the first surface');
version = 2;
await drawing.refreshGround();
assert.equal(asked, 4, 'and again for the next');
assert.equal(drawing.items().icons[0].pos.height, -30);
});
test('nothing draws after destroy, and an overlay without bounds draws nowhere', async (t) => {
const { ground, drawing } = drawn([
{ kind: 'pin', lon: 1, lat: 2, height: 0, mode: 'clamp', image: 'b' },
{ kind: 'overlay', rect: null, color: [1, 1, 1, 1] },
]);
t.after(ground.unbind);
assert.equal(ground.draw.set(drawing.ids.shapes), undefined, 'no shapes');
assert.equal(drawing.points().length, 1, 'framed by its pin alone');
const pending = drawing.refreshGround();
drawing.destroy();
await pending;
drawing.mount();
await drawing.refreshGround();
assert.equal(ground.liveSets().length, 0);
assert.deepEqual(drawing.items(), { icons: [], lines: [], shapes: [] });
});
test('a turned overlay across the antimeridian frames there', (t) => {
const { ground, drawing } = drawn([
{
kind: 'overlay',
rect: { west: 179, south: -1, east: -179, north: 1 },
rotation: Math.PI / 4,
color: [1, 1, 1, 1],
},
]);
t.after(ground.unbind);
const points = drawing.points();
assert.equal(points.length, 4);
for (const [lon, lat] of points) {
assert.ok(Math.abs(lat) < 2, `latitude ${lat}`);
assert.ok(Math.abs(lon) > 178 && Math.abs(lon) <= 180, `longitude ${lon}`);
}
});
+57
View File
@@ -0,0 +1,57 @@
/** What the file import's parsing and drawing parts share: its error, its limits, its deadline and feature names. */
import { msg } from '../i18n/marker.js';
/** Most entities one file may create before it is refused. */
export const MAX_IMPORT_ENTITIES = 20_000;
/** Longest plain-text name kept from a file's features. */
const MAX_IMPORT_NAME_LENGTH = 120;
/**
* An error whose message is meant for the person who chose the file. The
* message stays English; `template` and `values`, when given, let the UI show
* it in the active language. Numbers stay numbers in `values`: the UI formats
* them in that language's numerals.
*/
export class GeoImportError extends Error {
constructor(message, template = message, values = {}) {
super(message);
this.name = 'GeoImportError';
this.template = template;
this.values = values;
}
}
/** A feature name as short plain text (no control characters), or undefined. */
export function importFeatureName(value) {
const text = String(value ?? '')
.replace(/[\u0000-\u001f\u007f]/g, ' ')
.replace(/\s+/g, ' ')
.trim();
if (!text) return undefined;
return text.length > MAX_IMPORT_NAME_LENGTH
? `${text.slice(0, MAX_IMPORT_NAME_LENGTH - 1)}…`
: text;
}
/** `promise`, or a refusal when the import is aborted or takes over a minute. */
export async function boundedImport(promise, signal) {
let timer, abort;
try {
signal?.throwIfAborted();
return await Promise.race([
promise,
new Promise((_, reject) => {
abort = () => reject(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
timer = setTimeout(
() =>
reject(new GeoImportError(msg('That file took too long to read.'))),
60_000,
);
}),
]);
} finally {
clearTimeout(timer);
signal?.removeEventListener('abort', abort);
}
}
+320
View File
@@ -0,0 +1,320 @@
/**
* @module data/geojsonPins
* @description The map pins a GeoJSON point stands on, drawn as the default
* renderer's GeoJSON loader drew them: its pin shape in the marker colour,
* outlined in that colour brightened, and a simplestyle `marker-symbol`
* stamped on it in white outlined in black: a single character as bold
* text, anything longer as that Maki icon from the renderer's assets. A
* symbol that cannot be drawn leaves the plain pin, as the loader did.
*/
/** The pin's outline, in its own 24-unit box. */
const PIN_PATH =
'M6.72 0.422L17.28 0.422C18.553 0.422 19.577 1.758 19.577 3.415L19.577 10.973' +
'C19.577 12.63 18.553 13.966 17.282 13.966L14.386 14.008L11.826 23.578L9.614 14.008' +
'L6.719 13.965C5.446 13.983 4.422 12.629 4.422 10.972L4.422 3.416C4.423 1.76 5.447 0.423 6.718 0.423Z';
/** A colour channel as a CSS byte, as the default renderer writes one. */
const cssByte = (value) => (value === 1 ? 255 : (value * 256) | 0);
/** `[r, g, b, a]` as the default renderer writes a CSS colour. */
export function pinCss([r, g, b, a]) {
return a === 1
? `rgb(${cssByte(r)},${cssByte(g)},${cssByte(b)})`
: `rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`;
}
/** `rgba` brightened by 0.6, as the pin's outline is. */
const brighter = (rgba) => [
1 - (1 - rgba[0]) * 0.4,
1 - (1 - rgba[1]) * 0.4,
1 - (1 - rgba[2]) * 0.4,
rgba[3],
];
/** `[r, g, b, a]` as the plain pin has always written it, alpha and all. */
const svgCss = ([r, g, b, a]) =>
`rgba(${cssByte(r)},${cssByte(g)},${cssByte(b)},${a})`;
/**
* The plain pin at `size` pixels in `rgba`, as SVG.
* @param {number[]} rgba
* @param {number} size
* @returns {{svg: string}}
*/
export function plainPin(rgba, size) {
return {
svg:
`<svg xmlns="http://www.w3.org/2000/svg" width="${size}" height="${size}" viewBox="0 0 24 24">` +
`<path d="${PIN_PATH}" fill="${svgCss(rgba)}" stroke="${svgCss(brighter(rgba))}" stroke-width="0.846"/></svg>`,
};
}
/**
* Draw the pin, as the loader's pin builder does.
* @param {CanvasRenderingContext2D} context
* @param {number[]} rgba
* @param {number} size
*/
function drawPin(context, rgba, size) {
context.save();
context.scale(size / 24, size / 24);
context.fillStyle = pinCss(rgba);
context.strokeStyle = pinCss(brighter(rgba));
context.lineWidth = 0.846;
context.beginPath();
context.moveTo(6.72, 0.422);
context.lineTo(17.28, 0.422);
context.bezierCurveTo(18.553, 0.422, 19.577, 1.758, 19.577, 3.415);
context.lineTo(19.577, 10.973);
context.bezierCurveTo(19.577, 12.63, 18.553, 13.966, 17.282, 13.966);
context.lineTo(14.386, 14.008);
context.lineTo(11.826, 23.578);
context.lineTo(9.614, 14.008);
context.lineTo(6.719, 13.965);
context.bezierCurveTo(5.446, 13.983, 4.422, 12.629, 4.422, 10.972);
context.lineTo(4.422, 3.416);
context.bezierCurveTo(4.423, 1.76, 5.447, 0.423, 6.718, 0.423);
context.closePath();
context.fill();
context.stroke();
context.restore();
}
/**
* Stamp `image` on the pin's head: only its alpha counts, drawn white with
* a one-pixel black edge, as the loader's pin builder stamps it.
* @param {CanvasRenderingContext2D} context
* @param {{width: number, height: number}} image
* @param {number} size
*/
function drawIcon(context, image, size) {
const imageSize = size / 2.5;
let sizeX = imageSize;
let sizeY = imageSize;
if (image.width > image.height)
sizeY = imageSize * (image.height / image.width);
else if (image.width < image.height)
sizeX = imageSize * (image.width / image.height);
const x = Math.round((size - sizeX) / 2);
const y = Math.round((7 / 24) * size - sizeY / 2);
context.globalCompositeOperation = 'destination-out';
context.drawImage(image, x - 1, y, sizeX, sizeY);
context.drawImage(image, x, y - 1, sizeX, sizeY);
context.drawImage(image, x + 1, y, sizeX, sizeY);
context.drawImage(image, x, y + 1, sizeX, sizeY);
context.globalCompositeOperation = 'destination-over';
context.fillStyle = 'rgb(0,0,0)';
context.fillRect(x - 1, y - 1, sizeX + 2, sizeY + 2);
context.globalCompositeOperation = 'destination-out';
context.drawImage(image, x, y, sizeX, sizeY);
context.globalCompositeOperation = 'destination-over';
context.fillStyle = 'rgb(255,255,255)';
context.fillRect(x - 1, y - 2, sizeX + 2, sizeY + 2);
}
/**
* `text` written white on a canvas just big enough for it, in `font`, as
* the default renderer writes text to a canvas.
* @param {(width: number, height: number) => HTMLCanvasElement} makeCanvas
* @param {string} text
* @param {string} font
*/
function textCanvas(makeCanvas, text, font) {
const canvas = makeCanvas(1, 1);
let context = canvas.getContext('2d', { willReadFrequently: true });
context.font = font;
const metrics = context.measureText(text);
const blank = !/\S/.test(text);
const ascent = blank ? 0 : Math.round(metrics.actualBoundingBoxAscent);
const descent = blank ? 0 : Math.round(metrics.actualBoundingBoxDescent);
const height = blank ? 0 : Math.max(ascent + descent, 1);
const x = blank ? 0 : Math.round(metrics.actualBoundingBoxLeft);
canvas.width = Math.ceil(metrics.width) + x;
canvas.height = height;
// Resizing a canvas resets its context's state.
context = canvas.getContext('2d', { willReadFrequently: true });
context.font = font;
context.lineJoin = 'round';
context.lineWidth = 1;
context.imageSmoothingEnabled = false;
context.fillStyle = 'rgb(255,255,255)';
context.fillText(text, x, ascent);
return canvas;
}
/** The renderer's script on the page, and the folder it is served from. */
const RENDERER_SCRIPT = /((?:.*\/)|^)Cesium\.js(?:\?|#|$)/;
/**
* Where the renderer's assets are served, as the renderer finds them: the
* `CESIUM_BASE_URL` global, else the folder of its script on the page; null
* when neither says (a renderer bundled as modules, which finds them from
* its own module address).
*/
function assetBase() {
const document = globalThis.document;
let base = globalThis.CESIUM_BASE_URL;
if (typeof base !== 'string' || !base) {
base = null;
for (const script of document?.getElementsByTagName?.('script') ?? []) {
const found = RENDERER_SCRIPT.exec(script.getAttribute?.('src') ?? '');
if (found) {
base = found[1];
break;
}
}
}
if (base === null) return null;
// The renderer reads its base as a folder, slash or not; a script beside
// the page is in the page's own folder.
if (base === '') base = './';
else if (!base.endsWith('/')) base += '/';
try {
return new URL(base, document?.baseURI).href;
} catch {
return null;
}
}
/**
* The Maki icon `id` from the renderer's assets, or null when it cannot be
* loaded.
* @param {string} id
* @param {AbortSignal} [signal]
* @returns {Promise<ImageBitmap|null>}
*/
export async function loadMaki(id, signal) {
const base = assetBase();
if (!base || typeof globalThis.createImageBitmap !== 'function') return null;
try {
const url = new URL(
`Assets/Textures/maki/${encodeURIComponent(id)}.png`,
base,
);
const response = await fetch(url, signal ? { signal } : undefined);
if (!response.ok) return null;
return await globalThis.createImageBitmap(await response.blob());
} catch {
return null;
}
}
/** A canvas on the page, when there is one to draw on. */
function documentCanvas(width, height) {
const canvas = globalThis.document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
}
/**
* Makes the pins a set of points stands on. Symbols are loaded first
* (`load`), so the pins can then be made at once (`pin`).
* @param {object} [options]
* @param {(width: number, height: number) => HTMLCanvasElement} [options.makeCanvas]
* Default: a canvas on the page; without a page every pin is plain.
* @param {(id: string, signal?: AbortSignal) => Promise<object|null>} [options.loadIcon]
* A Maki icon by id. Default: from the renderer's assets.
*/
export function createGeojsonPins({ makeCanvas, loadIcon = loadMaki } = {}) {
const canvasFor =
makeCanvas ??
(typeof globalThis.document?.createElement === 'function'
? documentCanvas
: null);
/** Maki icons by id; null for one that failed. */
const icons = new Map();
const pins = new Map();
return {
/** Let go of every pin and icon made so far. */
clear() {
icons.clear();
pins.clear();
},
/**
* Load the icons `symbols` need. One that fails stays the plain pin.
* @param {Iterable<unknown>} symbols `marker-symbol` values.
* @param {{signal?: AbortSignal}} [options] Ends the loads early.
*/
async load(symbols, { signal } = {}) {
if (!canvasFor) return;
const wanted = new Set();
for (const symbol of symbols)
if (isIconSymbol(symbol) && !icons.has(String(symbol)))
wanted.add(String(symbol));
await Promise.all(
[...wanted].map(async (id) => {
const icon = await Promise.resolve()
.then(() => loadIcon(id, signal))
.catch(() => null);
// An aborted load is not a missing icon: a later load asks again.
if (!signal?.aborted) icons.set(id, icon ?? null);
}),
);
},
/**
* The pin for a marker: its colour, size and symbol (none for the
* plain pin). One image per distinct marker, shared.
* @param {{color: number[], size: number, symbol?: unknown}} marker
* @returns {import('../render/contract/draw').ImageRef}
*/
pin({ color, size, symbol }) {
const drawn = hasSymbol(symbol) && canvasFor ? symbol : undefined;
const key = JSON.stringify([stampKey(drawn), color, size]);
let image = pins.get(key);
if (!image) {
image = symbolPin(drawn, color, size) ?? plainPin(color, size);
pins.set(key, image);
}
return image;
},
};
function symbolPin(symbol, color, size) {
if (symbol === undefined) return null;
let stamp;
if (isIconSymbol(symbol)) {
stamp = icons.get(String(symbol));
if (!stamp) return null;
} else
stamp = textCanvas(
canvasFor,
symbol.toUpperCase(),
`bold ${size}px sans-serif`,
);
const canvas = canvasFor(size, size);
const context = canvas.getContext('2d');
drawPin(context, color, size);
drawIcon(context, stamp, size);
return {
canvas,
key: `geojson-pin:${JSON.stringify([stampKey(symbol), color, size])}`,
};
}
}
/** Whether a `marker-symbol` asks for a symbol, as the loader reads one. */
const hasSymbol = (symbol) => symbol !== undefined && symbol !== null;
/**
* What a symbol stamps, as the loader's pin builder told its pins apart:
* text by its upper-cased character, an icon by its id.
*/
const stampKey = (symbol) =>
symbol === undefined
? null
: isIconSymbol(symbol)
? ['icon', String(symbol)]
: ['text', symbol.toUpperCase()];
/** Whether a symbol is an icon (anything but a single-character string). */
const isIconSymbol = (symbol) =>
hasSymbol(symbol) && !(typeof symbol === 'string' && symbol.length === 1);
+269
View File
@@ -0,0 +1,269 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import {
createGeojsonPins,
loadMaki,
pinCss,
plainPin,
} from './geojsonPins.js';
/** A canvas whose context records what is drawn on it. */
function fakeCanvas(width, height) {
const calls = [];
const state = {};
const context = {
calls,
save: () => calls.push(['save']),
restore: () => calls.push(['restore']),
scale: (...a) => calls.push(['scale', ...a]),
beginPath: () => calls.push(['beginPath']),
moveTo: () => {},
lineTo: () => {},
bezierCurveTo: () => {},
closePath: () => {},
fill: () => calls.push(['fill', state.fillStyle]),
stroke: () => calls.push(['stroke', state.strokeStyle, state.lineWidth]),
fillRect: (...a) =>
calls.push([
'fillRect',
state.globalCompositeOperation,
state.fillStyle,
...a,
]),
drawImage: (image, ...a) =>
calls.push([
'drawImage',
state.globalCompositeOperation,
image.tag,
...a,
]),
fillText: (...a) => calls.push(['fillText', state.font, ...a]),
measureText: (text) => ({
width: text.length * 10,
actualBoundingBoxAscent: 9.4,
actualBoundingBoxDescent: 0.6,
actualBoundingBoxLeft: 0,
}),
};
for (const key of [
'fillStyle',
'strokeStyle',
'lineWidth',
'globalCompositeOperation',
'font',
'lineJoin',
'imageSmoothingEnabled',
])
Object.defineProperty(context, key, {
get: () => state[key],
set: (value) => (state[key] = value),
});
return { width, height, tag: 'canvas', getContext: () => context, context };
}
test('a pin with no symbol is the plain pin, in the marker colour outlined brighter', () => {
const pins = createGeojsonPins({ makeCanvas: fakeCanvas });
const pin = pins.pin({ color: [1, 0, 0, 1], size: 48 });
assert.deepEqual(pin, plainPin([1, 0, 0, 1], 48));
assert.match(pin.svg, /width="48" height="48"/);
assert.match(pin.svg, /fill="rgba\(255,0,0,1\)"/);
assert.match(pin.svg, /stroke="rgba\(255,153,153,1\)"/);
assert.equal(pins.pin({ color: [1, 0, 0, 1], size: 48 }), pin, 'shared');
assert.equal(pinCss([0, 0.5, 1, 0.3]), 'rgba(0,128,255,0.3)');
});
test('a single-character symbol is stamped on the pin as bold upper-case text', async () => {
const made = [];
const pins = createGeojsonPins({
makeCanvas: (w, h) => {
const canvas = fakeCanvas(w, h);
made.push(canvas);
return canvas;
},
});
await pins.load(['a']);
const pin = pins.pin({ color: [0, 0, 1, 1], size: 48, symbol: 'a' });
assert.equal(typeof pin.key, 'string');
assert.match(pin.key, /^geojson-pin:/);
const [text, canvas] = made;
assert.equal(pin.canvas, canvas);
assert.deepEqual([canvas.width, canvas.height], [48, 48]);
// The text canvas: just big enough for the text.
assert.deepEqual([text.width, text.height], [10, 10]);
assert.deepEqual(
text.context.calls.find((c) => c[0] === 'fillText'),
['fillText', 'bold 48px sans-serif', 'A', 0, 9],
);
const calls = canvas.context.calls;
assert.deepEqual(
calls.find((c) => c[0] === 'scale'),
['scale', 2, 2],
);
assert.deepEqual(
calls.find((c) => c[0] === 'fill'),
['fill', 'rgb(0,0,255)'],
);
assert.deepEqual(
calls.find((c) => c[0] === 'stroke'),
['stroke', 'rgb(153,153,255)', 0.846],
);
// Stamped white with a black edge, centred on the pin's head: the text
// is 10 wide in a 19.2 box, so it is drawn square at 19.2.
const stamps = calls.filter(
(c) => c[0] === 'drawImage' || c[0] === 'fillRect',
);
const x = Math.round((48 - 19.2) / 2);
const y = Math.round((7 / 24) * 48 - 19.2 / 2);
assert.deepEqual(stamps, [
['drawImage', 'destination-out', 'canvas', x - 1, y, 19.2, 19.2],
['drawImage', 'destination-out', 'canvas', x, y - 1, 19.2, 19.2],
['drawImage', 'destination-out', 'canvas', x + 1, y, 19.2, 19.2],
['drawImage', 'destination-out', 'canvas', x, y + 1, 19.2, 19.2],
['fillRect', 'destination-over', 'rgb(0,0,0)', x - 1, y - 1, 21.2, 21.2],
['drawImage', 'destination-out', 'canvas', x, y, 19.2, 19.2],
[
'fillRect',
'destination-over',
'rgb(255,255,255)',
x - 1,
y - 2,
21.2,
21.2,
],
]);
assert.equal(
pins.pin({ color: [0, 0, 1, 1], size: 48, symbol: 'a' }),
pin,
'one image per distinct marker',
);
});
test('a longer symbol is that icon, loaded first; one that fails leaves the plain pin', async () => {
const asked = [];
const pins = createGeojsonPins({
makeCanvas: fakeCanvas,
loadIcon: async (id) => {
asked.push(id);
if (id === 'rail') return { width: 30, height: 15, tag: 'rail' };
if (id === 'boom') throw new Error('boom');
return null;
},
});
await pins.load(['rail', 'nope', 'boom', 'x', 7, null, undefined, 'rail']);
assert.deepEqual(asked.sort(), ['7', 'boom', 'nope', 'rail']);
const rail = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'rail' });
const draws = rail.canvas.context.calls.filter((c) => c[0] === 'drawImage');
// Wider than high: its height is scaled down.
assert.deepEqual(draws.at(-1), [
'drawImage',
'destination-out',
'rail',
7,
5,
9.6,
4.8,
]);
for (const symbol of ['nope', 'boom', 7])
assert.deepEqual(
pins.pin({ color: [1, 1, 1, 1], size: 24, symbol }),
plainPin([1, 1, 1, 1], 24),
);
// Loaded again, a known icon is not fetched again.
await pins.load(['rail']);
assert.equal(asked.length, 4);
});
test('without a page to draw on, every pin is plain', async () => {
const pins = createGeojsonPins({ loadIcon: () => assert.fail('no load') });
await pins.load(['rail']);
assert.deepEqual(
pins.pin({ color: [1, 1, 1, 1], size: 8, symbol: 'a' }),
plainPin([1, 1, 1, 1], 8),
);
});
test('a number is an icon id and a character is text, each pinned apart; text by its upper case', async () => {
const loaded = [];
const pins = createGeojsonPins({
makeCanvas: fakeCanvas,
loadIcon: async (id) => (loaded.push(id), { width: 4, height: 4, tag: id }),
});
await pins.load([7, '7', 'a', 'A']);
assert.deepEqual(loaded, ['7']);
const icon = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 7 });
const text = pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: '7' });
assert.notEqual(icon, text);
assert.notEqual(icon.key, text.key);
assert.equal(
pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'a' }),
pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'A' }),
);
});
test('an aborted icon load is asked again later; a failing loader leaves the plain pin', async () => {
const controller = new AbortController();
let calls = 0;
const pins = createGeojsonPins({
makeCanvas: fakeCanvas,
loadIcon: (id) => {
calls += 1;
if (id === 'sync') throw new Error('sync');
controller.abort();
return Promise.resolve(null);
},
});
await pins.load(['rail'], { signal: controller.signal });
await pins.load(['rail']);
assert.equal(calls, 2);
await pins.load(['sync']);
assert.deepEqual(
pins.pin({ color: [1, 1, 1, 1], size: 24, symbol: 'sync' }),
plainPin([1, 1, 1, 1], 24),
);
});
test('icons come from the renderer’s assets: its base global, else its script’s folder', async (t) => {
const saved = {
document: globalThis.document,
base: globalThis.CESIUM_BASE_URL,
bitmap: globalThis.createImageBitmap,
fetch: globalThis.fetch,
};
t.after(() => {
for (const [key, name] of [
['document', 'document'],
['base', 'CESIUM_BASE_URL'],
['bitmap', 'createImageBitmap'],
['fetch', 'fetch'],
])
if (saved[key] === undefined) delete globalThis[name];
else globalThis[name] = saved[key];
});
const asked = [];
globalThis.fetch = async (url) => {
asked.push(String(url));
return { ok: true, blob: async () => 'png' };
};
globalThis.createImageBitmap = async () => ({ width: 1, height: 1 });
const scripts = [];
globalThis.document = {
baseURI: 'http://gev.test/app/',
getElementsByTagName: () =>
scripts.map((src) => ({ getAttribute: () => src })),
};
globalThis.CESIUM_BASE_URL = '/assets/cesium';
assert.ok(await loadMaki('rail'));
delete globalThis.CESIUM_BASE_URL;
scripts.push('/other.js', 'lib/Cesium.js?v=1');
assert.ok(await loadMaki('a b'));
scripts.length = 0;
scripts.push('Cesium.js');
assert.ok(await loadMaki('dam'));
scripts.length = 0;
assert.equal(await loadMaki('rail'), null, 'nothing says where');
assert.deepEqual(asked, [
'http://gev.test/assets/cesium/Assets/Textures/maki/rail.png',
'http://gev.test/app/lib/Assets/Textures/maki/a%20b.png',
'http://gev.test/app/Assets/Textures/maki/dam.png',
]);
});
+234
View File
@@ -0,0 +1,234 @@
/**
* @module iconAtlas
* @description The images icon sets draw, packed into one canvas. A layer asks for a
* slot by image URL and raster size and gets a number at once; the image loads and is
* packed later, and until then its slot is empty and rows using it draw nothing (as a
* Cesium billboard waits for its image).
*
* The renderer uploads {@link iconAtlas}.canvas whenever `version` changes and reads
* each slot's texture rectangle from `rects`.
*/
/**
* Drawn width in device pixels (the drawing buffer's) past which an icon
* row with no switch of its own draws its near image: the aircraft layers'
* switch.
*/
export const NEAR_IMAGE_DEVICE_PX = 76;
/**
* `NEAR_IMAGE_DEVICE_PX` in CSS pixels, for an icon item's
* `imageLod.switchPx`, which the draw contract measures in CSS pixels: the
* device switch divided by the drawing buffer's pixels per CSS pixel. That
* is the scene's pixel ratio, which the quality port's frame signals report
* as `pixelRatio`: on the default renderer its `pixelRatio` setting, or 1
* while that is 0 (browser recommended). `devicePixelRatio` does not enter
* it. A layer drawing through the port passes the ratio its frames report
* and rewrites its rows' switch when that changes.
* @param {number} [pixelRatio] Drawing-buffer pixels per CSS pixel (1).
*/
export function nearImageSwitchPx(pixelRatio = 1) {
const ratio = Number.isFinite(pixelRatio) && pixelRatio > 0 ? pixelRatio : 1;
return NEAR_IMAGE_DEVICE_PX / ratio;
}
/**
* Slots the atlas holds. A renderer addresses each through one vec4
* uniform, as many as its context has room for (`addressableIconSlots`):
* every WebGL 2 context has room for all of them.
*/
export const MAX_ICON_SLOTS = 176;
/** Slots the renderer addresses, however few uniforms its context has. */
export const MIN_ICON_SLOTS = 64;
/**
* Vertex uniform vectors the icon shader keeps for everything else: its own
* and the renderer's (about 34), with room for drivers that keep constants
* in uniforms.
*/
const OTHER_VERTEX_UNIFORMS = 80;
/**
* How many slots a context with `maxVertexUniformVectors` addresses: all of
* them on WebGL 2 (at least 256 vectors), at least `MIN_ICON_SLOTS`.
* @param {number} maxVertexUniformVectors
*/
export function addressableIconSlots(maxVertexUniformVectors) {
const room = Math.floor(maxVertexUniformVectors) - OTHER_VERTEX_UNIFORMS;
return Math.max(
MIN_ICON_SLOTS,
Math.min(MAX_ICON_SLOTS, Number.isFinite(room) ? room : 0),
);
}
const PADDING_PX = 2;
const START_SIZE_PX = 1024;
const MAX_SIZE_PX = 4096;
function createAtlas() {
const slotOfKey = new Map();
const entries = [];
const listeners = new Set();
const atlas = {
/** Bumped whenever the canvas or a slot rectangle changes. */
version: 0,
canvas: null,
width: 0,
height: 0,
/** Per slot `[u0, v0, u1, v1]`, zero until the image is packed. */
rects: new Float32Array(MAX_ICON_SLOTS * 4),
get size() {
return entries.length;
},
/**
* The slot for `url` rasterised at `sizePx` square. Given a `source` (a
* canvas, or anything else `drawImage` takes), `url` is only its key:
* the source is packed at once, as it is now, and never loaded.
* @param {string} url
* @param {number} sizePx
* @param {CanvasImageSource} [source]
* @returns {number}
*/
slot(url, sizePx, source) {
const key = `${sizePx}|${url}`;
const known = slotOfKey.get(key);
if (known !== undefined) return known;
if (entries.length >= MAX_ICON_SLOTS)
throw new RangeError(
`The icon atlas holds at most ${MAX_ICON_SLOTS} images`,
);
const slot = entries.length;
const entry = { url, sizePx, image: null, x: 0, y: 0 };
entries.push(entry);
slotOfKey.set(key, slot);
if (source) placeLoaded(entry, source);
else load(entry);
return slot;
},
/** Whether `url` at `sizePx` already has a slot. */
has(url, sizePx) {
return slotOfKey.has(`${sizePx}|${url}`);
},
/** Whether a slot's image is packed and drawable. */
ready(slot) {
return atlas.rects[slot * 4 + 2] > 0;
},
/** Whether a slot's image failed to load, or had no room to pack. */
failed(slot) {
return entries[slot]?.failed === true;
},
/**
* Call `listener` after every repack, so the renderer, drawing on demand,
* can ask for the frame that shows a newly loaded image.
* @param {() => void} listener
* @returns {() => void} Stops listening.
*/
onChange(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
};
/** Pack an entry's loaded image, or leave its slot empty when it does not fit. */
function placeLoaded(entry, image) {
entry.image = image;
// Node: nothing to pack into.
if (
typeof document === 'undefined' &&
typeof OffscreenCanvas === 'undefined'
)
return;
if (!pack()) {
entry.image = null; // does not fit: leave its slot empty, keep the rest
entry.failed = true;
console.warn(
`[iconAtlas] No room for ${entry.sizePx} px icon; slot stays empty`,
);
pack();
}
}
function load(entry) {
if (typeof Image === 'undefined') return; // Node: slots only
const image = new Image(entry.sizePx, entry.sizePx);
image.decoding = 'async';
// A cross-origin image would taint the canvas and every texture upload.
image.crossOrigin = 'anonymous';
image.onload = () => placeLoaded(entry, image);
image.onerror = () => {
entry.failed = true;
console.warn(
`[iconAtlas] Icon failed to load: ${entry.url.slice(0, 80)}`,
);
};
image.src = entry.url;
}
// Shelf packing over every loaded image, largest first, growing the canvas
// until they fit. Rebuilt in full: the set is a few dozen images. Returns false,
// changing nothing, when they cannot fit at the largest size.
function pack() {
const loaded = entries.filter((entry) => entry.image);
loaded.sort((a, b) => b.sizePx - a.sizePx);
let size = Math.max(atlas.width, START_SIZE_PX);
while (!place(loaded, size)) {
size *= 2;
if (size > MAX_SIZE_PX) return false;
}
if (!atlas.canvas || atlas.width !== size) {
atlas.canvas =
typeof document !== 'undefined'
? Object.assign(document.createElement('canvas'), {
width: size,
height: size,
})
: new OffscreenCanvas(size, size);
atlas.width = size;
atlas.height = size;
}
const g = atlas.canvas.getContext('2d');
g.clearRect(0, 0, size, size);
atlas.rects.fill(0);
for (const entry of loaded) {
g.drawImage(entry.image, entry.x, entry.y, entry.sizePx, entry.sizePx);
const slot = entries.indexOf(entry);
const o = slot * 4;
atlas.rects[o] = entry.x / size;
atlas.rects[o + 1] = entry.y / size;
atlas.rects[o + 2] = (entry.x + entry.sizePx) / size;
atlas.rects[o + 3] = (entry.y + entry.sizePx) / size;
}
atlas.version++;
for (const listener of listeners) listener();
return true;
}
function place(loaded, size) {
let x = 0;
let y = 0;
let shelf = 0;
for (const entry of loaded) {
const cell = entry.sizePx + PADDING_PX * 2;
if (x + cell > size) {
x = 0;
y += shelf;
shelf = 0;
}
if (y + cell > size) return false;
entry.x = x + PADDING_PX;
entry.y = y + PADDING_PX;
x += cell;
shelf = Math.max(shelf, cell);
}
return true;
}
return atlas;
}
/** The one atlas every icon set draws from. */
export const iconAtlas = createAtlas();
+10 -240
View File
@@ -2,7 +2,11 @@
* Shared icon-orientation + horizon helpers. Orientation and culling serve the
* moving-entity layers (commercial flights, military flights, AIS vessels);
* `skyBackdropFactor` serves the detection overlay, which needs the same
* silhouette geometry to know what a label is being read against.
* silhouette geometry to know what a label is being read against. The helpers
* that read the default renderer's scene or camera (`screenProjectedRotation`,
* `perspectiveProjectedRotation`, `horizonOccluder`, `cameraPoseSignature`)
* live in `src/render/cesium/iconOrientation.js`; the camera-basis rotation
* itself is `courseScreenRotation` in `screenRotation.js`.
*
* THE ORIENTATION PROBLEM (2026-06-10 playtest): billboards are camera-facing
* quads, so "point along the real-world course" must be computed in SCREEN
@@ -21,104 +25,10 @@
* keeps rotation continuous through tracked orbits; field evidence, not an
* unverified math swap, decides whether exact projection becomes preferred.
*/
import * as Cesium from 'cesium';
import { WGS84 } from '../geo/ellipsoid.js';
import { stabilizeScreenRotation } from './screenRotation.js';
/** Meters used to give the course vector a stable projection magnitude. */
const FORWARD_PROBE_M = 2000;
/**
* Minimum camera-plane component before we trust the angle — below this the
* course points almost exactly into/out of the screen and the angle is noise.
*/
const MIN_SCREEN_COMPONENT_M = 0.5;
/** Ignore sub-degree projection noise while retaining deliberate camera-orbit rotation. */
const ROTATION_DEADBAND_RAD = Cesium.Math.toRadians(0.5);
const _scratchEnu = new Cesium.Matrix4();
const _scratchForward = new Cesium.Cartesian3();
const _scratchWorldForward = new Cesium.Cartesian3();
/**
* Computes the billboard rotation (radians, CCW-positive, for
* alignedAxis = Cartesian3.ZERO) that points an icon along its real-world
* course in the stable camera-basis approximation described above.
*
* @param {Cesium.Scene} scene - The scene (projection source).
* @param {Cesium.Cartesian3} position - Entity world position.
* @param {number} courseDeg - Course/track in degrees clockwise from north.
* @param {number|null} previous - Rotation to keep when projection is
* unavailable (off-screen/behind camera/degenerate).
* @returns {number|null} Rotation in radians, or `previous` when unknown.
*/
export function screenProjectedRotation(
scene,
position,
courseDeg,
previous = null,
) {
const camera = scene?.camera;
if (!camera?.rightWC || !camera?.upWC || !position) return previous;
const courseRad = Cesium.Math.toRadians(courseDeg || 0);
Cesium.Cartesian3.fromElements(
Math.sin(courseRad) * FORWARD_PROBE_M,
Math.cos(courseRad) * FORWARD_PROBE_M,
0,
_scratchForward,
);
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;
// Window y grows downward; rotation 0 = icon pointing screen-up.
// Icon direction in window coords after CCW rotation r is (-sin r, -cos r),
// so matching the projected course (dx, dy) gives r = atan2(-dx, -dy).
return Math.atan2(-dx, -dy);
}
/**
* Hold a billboard rotation when the newly projected angle differs only by
* sub-degree render noise. The comparison uses the shortest wrapped arc so
* values around ±π do not jump.
*
* @param {number|null} previous Last displayed rotation.
* @param {number|null} next Newly projected rotation.
* @param {number} [deadbandRad=ROTATION_DEADBAND_RAD] Angular hold threshold.
* @returns {number|null} Stable rotation.
*/
export function stabilizeScreenRotation(
previous,
next,
deadbandRad = ROTATION_DEADBAND_RAD,
) {
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),
);
return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next;
}
const _occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
new Cesium.Cartesian3(),
);
export { stabilizeScreenRotation };
/**
* Half-width of the crossfade band centred on the ellipsoid silhouette, in
@@ -129,7 +39,7 @@ const _occluder = new Cesium.EllipsoidalOccluder(
*/
export const HORIZON_FEATHER_RAD = 0.019;
const _wgs84OneOverRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
const _wgs84OneOverRadii = WGS84.oneOverRadii;
/**
* How much SKY sits behind a world point from this camera: 0 (planet behind)
@@ -141,7 +51,7 @@ const _wgs84OneOverRadii = Cesium.Ellipsoid.WGS84.oneOverRadii;
* ABOVE the ellipsoid the horizon is the tangent silhouette and the test is a
* genuine ray/ellipsoid hit test: 1 means the view ray through the point misses
* the planet entirely. Here the function is the exact complement of
* {@link horizonOccluder} — the occluder asks whether the planet is in FRONT of
* `horizonOccluder` (`src/render/cesium/iconOrientation.js`) — the occluder asks whether the planet is in FRONT of
* a point (cull it), this asks whether it is BEHIND (what a screen-space label
* anchored there is read against). For any point the occluder keeps, a ray that
* hits the ellipsoid must hit it beyond the point, so the hit/miss test alone
@@ -235,143 +145,3 @@ export function skyBackdropFactor(
// than steps, and the fade has no visible corner at either edge of the band.
return t * t * (3 - 2 * t);
}
/**
* Returns the shared horizon occluder, updated to the camera's position.
* With the Cesium globe hidden (Google 3D tiles provide the planet) nothing
* writes far-side depth, so billboards must be horizon-culled manually.
* Call once per tick, then test points with occluder.isPointVisible(pos).
*
* @param {Cesium.Camera} camera - The scene camera.
* @returns {Cesium.EllipsoidalOccluder}
*/
export function horizonOccluder(camera) {
_occluder.cameraPosition = camera.positionWC;
return _occluder;
}
/**
* Cheap camera pose signature for "did the camera move" gating of rotation
* passes (position quantized to ~10m, angles to ~0.06 deg).
* @param {Cesium.Camera} camera - The scene camera.
* @returns {string}
*/
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)}`
);
}
/**
* 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;
+95 -3
View File
@@ -3,11 +3,13 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
HORIZON_FEATHER_RAD,
horizonOccluder,
screenProjectedRotation,
skyBackdropFactor,
stabilizeScreenRotation,
} from './iconOrientation.js';
import {
horizonOccluder,
screenProjectedRotation,
} from '../render/cesium/iconOrientation.js';
const equatorPosition = Cesium.Cartesian3.fromDegrees(0, 0, 0);
@@ -563,7 +565,7 @@ import {
PERSPECTIVE_BLEND_MIN_PX,
PERSPECTIVE_PROBE_M,
perspectiveProjectedRotation,
} from './iconOrientation.js';
} from '../render/cesium/iconOrientation.js';
/**
* A scene the exact projector accepts: 3D mode, a canvas, and a camera with a
@@ -745,3 +747,93 @@ test('the perspective helper is continuous through the sub-pixel band, not a 23
`exact alone at ${s.separation.toFixed(2)} px`,
);
});
test('the port-side perspective rotation matches the Cesium one through the whole band', async () => {
// The transit layer turns its icons with `perspectiveCourseRotation`, which
// projects through the query port and blends with the camera-port basis;
// given the same projection and basis it must answer as the scene helper.
const { perspectiveCourseRotation } = await import('./screenRotation.js');
let compared = 0;
for (let altitude = 500; altitude <= 600_000; altitude *= 1.05) {
const scene = obliqueScene(altitude, 45);
const project = (p) => {
const s = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
new Cesium.Cartesian3(p.x, p.y, p.z),
);
return s ? { x: s.x, y: s.y } : null;
};
const basis = { right: scene.camera.rightWC, up: scene.camera.upWC };
for (const [east, north] of [
[0.7, 1.2],
[-0.4, 0.9],
[0, 0.5],
[0, -2],
])
for (const course of [0, 37, 90, 181, 300]) {
const contact = Cesium.Cartesian3.fromDegrees(
(east * altitude) / 111_320,
(north * altitude) / 111_320,
0,
);
for (const previous of [null, 0.25]) {
const expected = perspectiveProjectedRotation(
scene,
contact,
course,
previous,
);
const actual = perspectiveCourseRotation(
project,
basis,
{ x: contact.x, y: contact.y, z: contact.z },
course,
previous,
);
if (expected === null || actual === null)
assert.equal(actual, expected);
else
assert.ok(
Math.abs(actual - expected) < 1e-9,
`${altitude.toFixed(0)} m, course ${course}: ${actual} vs ${expected}`,
);
compared += 1;
}
}
}
assert.ok(compared > 1000);
assert.equal(perspectiveCourseRotation(null, null, null, 0, 0.5), 0.5);
});
test('the port-side perspective rotation probes along the east-north frame, poles included', async () => {
const { perspectiveCourseRotation, PERSPECTIVE_PROBE_M: probeM } =
await import('./screenRotation.js');
const { eastNorthUp, frameVector } = await import('../geo/frames.js');
const { fromDegrees } = await import('../geo/ellipsoid.js');
for (const position of [
fromDegrees(-71.06, 42.36, 12),
fromDegrees(150, -60, 0),
{ x: 0, y: 0, z: 6_356_752.314245 },
])
for (const course of [0, 45, 200]) {
const seen = [];
perspectiveCourseRotation(
(p) => (seen.push({ x: p.x, y: p.y, z: p.z }), { x: 0, y: 0 }),
null,
position,
course,
);
const rad = (course * Math.PI) / 180;
const forward = frameVector(eastNorthUp(position), {
x: Math.sin(rad) * probeM,
y: Math.cos(rad) * probeM,
z: 0,
});
const [, ahead] = seen;
for (const axis of ['x', 'y', 'z'])
assert.ok(
Math.abs(ahead[axis] - (position[axis] + forward[axis])) < 1e-6,
`${axis} at course ${course}`,
);
}
});
+84
View File
@@ -0,0 +1,84 @@
/**
* Icon motion segments packed for the GPU (`iconSegment.js`): one row per
* icon, read by `ICON_SEGMENT_GLSL` as `iconPosition` draws it.
*/
import type { Ecef } from '../render/contract/index';
/** Floats per packed row. */
export const SEGMENT_STRIDE: number;
export const SEGMENT_HOLD: number;
export const SEGMENT_LERP: number;
export const SEGMENT_ARC: number;
/** GLSL that evaluates a packed row. */
export const ICON_SEGMENT_GLSL: string;
/** Stay at `position` facing `courseDeg`. */
export function writeHoldSegment(
out: Float32Array,
row: number,
position: Ecef,
courseDeg: number,
): void;
export function writeLerpSegment(
out: Float32Array,
row: number,
segment: {
from: Ecef;
to: Ecef;
t0: number;
t1: number;
course0Deg: number;
courseSlopeDeg: number;
},
): void;
export function writeArcSegment(
out: Float32Array,
row: number,
segment: {
fix: Ecef;
t0: number;
minDt: number;
maxDt: number;
speedMps: number;
trackDeg: number;
turnRateDps: number;
climbMps?: number;
},
): void;
/**
* Glide row `row`'s drawn course from `fromCourseDeg` onto its segment's,
* at most `rateDps` from `t0` (seconds, as its times were packed).
*/
export function writeCourseGlide(
out: Float32Array,
row: number,
fromCourseDeg: number,
t0: number,
rateDps: number,
offsetDeg?: number,
): void;
/** Move a row's stored times by `deltaSec`. */
export function shiftSegmentTimes(
out: Float32Array,
row: number,
deltaSec: number,
): void;
/** The displayed course at `tau`, degrees clockwise from north. */
export function segmentCourse(
seg: Float32Array,
row: number,
tau: number,
): number;
/** The course the row glides toward at `tau`. */
export function segmentTargetCourse(
seg: Float32Array,
row: number,
tau: number,
): number;
/** Where the row is at `tau`, ECEF, into `result`. */
export function segmentPosition(
seg: Float32Array,
row: number,
tau: number,
result?: Ecef,
): Ecef;
+410
View File
@@ -0,0 +1,410 @@
/**
* @module iconSegment
* @description The motion an icon row follows between CPU updates: one segment, packed
* into a row of floats that the CPU ({@link evaluateSegment}) and the GPU
* ({@link ICON_SEGMENT_GLSL}) evaluate the same way at a render time.
*
* A segment is `position(τ) = base + U·e(τ) + V·n(τ)` plus a course:
* - hold: stays at `base`, course fixed;
* - lerp: straight from `base` to `base + U` between two fix times (the interpolation
* between two known fixes), course affine in the fraction;
* - arc: a constant-rate turn from a fix in its east/north plane (`U`, `V`), with the
* elapsed time clamped (warm-up before the first fix, coast after the last),
* climbing along the fix's up axis (`U × V`) at a constant rate.
*
* The arc uses `cos a − cos(a+b) = 2 sin(b/2) sin(a+b/2)`, so its offset is
* `v·t·sinc(ωt/2)·(sin, cos)(a + ωt/2)`: no cancellation in float32 and no branch
* between straight and turning motion. Turn rates under 1e-4 rad/s fly straight,
* as `arcOffsetEnu` does.
*
* Times are seconds since the owning set's epoch. `base` is stored as high and low
* float32 parts (split at multiples of 65536 m, as the default renderer's
* EncodedCartesian3 splits them) so the GPU can draw it relative to the eye.
*/
import { WGS84 } from '../geo/ellipsoid.js';
import { norm180, norm360 } from './motionModel.js';
/** Floats per packed segment. */
export const SEGMENT_STRIDE = 24;
export const SEGMENT_HOLD = 0;
export const SEGMENT_LERP = 1;
export const SEGMENT_ARC = 2;
// Offsets inside one packed segment. The GPU reads them as six vec4s in this order.
const BASE_HIGH = 0;
const BASE_LOW = 3;
const AXIS_U = 6;
const AXIS_V = 9;
const KIND = 12;
const T0 = 13;
const P1 = 14; // lerp: span (s); arc: smallest elapsed time (s)
const P2 = 15; // arc: largest elapsed time (s)
const SPEED = 16; // m/s
const TRACK = 17; // rad, clockwise from north
const OMEGA = 18; // rad/s
const COURSE0 = 19; // deg
const COURSE_SLOPE = 20; // lerp: deg per unit fraction
const CLIMB = 20; // arc: m/s along the fix's up axis (U × V)
const SLEW_OFFSET = 21; // deg still to glide at SLEW_T0
const SLEW_T0 = 22; // s
const SLEW_RATE = 23; // deg/s; negative holds the course at the glide's start
const DEG = Math.PI / 180;
const STRAIGHT_BELOW_RAD_PER_SEC = 1e-4;
const SPLIT = 65536.0;
/**
* One coordinate as its high part (a multiple of 65536 toward zero) and the
* remainder, written at `high` and `low`: `EncodedCartesian3.encode` step
* for step, so the stored floats are the same.
*/
function writeSplit(out, high, low, value) {
let doubleHigh;
if (value >= 0.0) {
doubleHigh = Math.floor(value / SPLIT) * SPLIT;
out[high] = doubleHigh;
out[low] = value - doubleHigh;
} else {
doubleHigh = Math.floor(-value / SPLIT) * SPLIT;
out[high] = -doubleHigh;
out[low] = value + doubleHigh;
}
}
const POLE_EPSILON = 1e-14;
/**
* The east and north unit axes at `p` into `out` at `u` and `v`: the
* default renderer's `Transforms.eastNorthUpToFixedFrame` step for step (signed zeros at a pole included), without allocating.
*/
function writeEastNorth(out, u, v, p) {
if (Math.abs(p.x) <= POLE_EPSILON && Math.abs(p.y) <= POLE_EPSILON) {
// At the centre the default renderer's fixed frame; at a pole east is +y
// and north (its signed zeros included) points away from the pole.
const sign = Math.abs(p.z) <= POLE_EPSILON ? 1 : p.z > 0 ? 1 : -1;
out[u] = 0;
out[u + 1] = 1;
out[u + 2] = 0;
out[v] = -1 * sign;
out[v + 1] = 0 * sign;
out[v + 2] = 0 * sign;
return;
}
const o = WGS84.oneOverRadiiSquared;
let ux = p.x * o.x;
let uy = p.y * o.y;
let uz = p.z * o.z;
const um = Math.sqrt(ux * ux + uy * uy + uz * uz);
ux /= um;
uy /= um;
uz /= um;
let ex = -p.y;
let ey = p.x;
let ez = 0;
const em = Math.sqrt(ex * ex + ey * ey + ez * ez);
ex /= em;
ey /= em;
ez /= em;
out[u] = ex;
out[u + 1] = ey;
out[u + 2] = ez;
// North is up × east.
out[v] = uy * ez - uz * ey;
out[v + 1] = uz * ex - ux * ez;
out[v + 2] = ux * ey - uy * ex;
}
function writeBase(out, o, position) {
writeSplit(out, o + BASE_HIGH, o + BASE_LOW, position.x);
writeSplit(out, o + BASE_HIGH + 1, o + BASE_LOW + 1, position.y);
writeSplit(out, o + BASE_HIGH + 2, o + BASE_LOW + 2, position.z);
}
function clearMotion(out, o) {
out.fill(0, o + AXIS_U, o + SEGMENT_STRIDE);
}
/**
* Stay at `position` facing `courseDeg`.
* @param {Float32Array} out
* @param {number} row
* @param {{x: number, y: number, z: number}} position ECEF.
* @param {number} courseDeg
*/
export function writeHoldSegment(out, row, position, courseDeg) {
const o = row * SEGMENT_STRIDE;
writeBase(out, o, position);
clearMotion(out, o);
out[o + KIND] = SEGMENT_HOLD;
out[o + COURSE0] = norm360(courseDeg || 0);
}
/**
* Move straight from `from` (at `t0`) to `to` (at `t1`), holding at either end.
* The course runs from `course0Deg` by `courseSlopeDeg` over the segment.
* @param {Float32Array} out
* @param {number} row
* @param {{from: object, to: object, t0: number, t1: number,
* course0Deg: number, courseSlopeDeg: number}} segment
*/
export function writeLerpSegment(out, row, segment) {
const o = row * SEGMENT_STRIDE;
const { from, to } = segment;
writeBase(out, o, from);
clearMotion(out, o);
out[o + AXIS_U] = to.x - from.x;
out[o + AXIS_U + 1] = to.y - from.y;
out[o + AXIS_U + 2] = to.z - from.z;
out[o + KIND] = SEGMENT_LERP;
out[o + T0] = segment.t0;
out[o + P1] = Math.max(0, segment.t1 - segment.t0);
out[o + COURSE0] = norm360(segment.course0Deg || 0);
out[o + COURSE_SLOPE] = segment.courseSlopeDeg || 0;
}
/**
* Turn at a constant rate from `fix` (at `t0`) in its east/north plane, with the
* elapsed time clamped to `[minDt, maxDt]`, climbing along the fix's up axis at
* `climbMps` (default 0).
* @param {Float32Array} out
* @param {number} row
* @param {{fix: object, t0: number, minDt: number, maxDt: number,
* speedMps: number, trackDeg: number, turnRateDps: number,
* climbMps?: number}} segment
*/
export function writeArcSegment(out, row, segment) {
const o = row * SEGMENT_STRIDE;
const { fix } = segment;
writeBase(out, o, fix);
clearMotion(out, o);
writeEastNorth(out, o + AXIS_U, o + AXIS_V, fix);
const omega = (segment.turnRateDps || 0) * DEG;
out[o + KIND] = SEGMENT_ARC;
out[o + T0] = segment.t0;
out[o + P1] = segment.minDt;
out[o + P2] = segment.maxDt;
out[o + SPEED] = segment.speedMps || 0;
out[o + TRACK] = (segment.trackDeg || 0) * DEG;
out[o + OMEGA] = Math.abs(omega) < STRAIGHT_BELOW_RAD_PER_SEC ? 0 : omega;
out[o + COURSE0] = norm360(segment.trackDeg || 0);
out[o + CLIMB] = segment.climbMps || 0;
}
/**
* Glide the displayed course from `fromCourseDeg` onto the segment's own course,
* at most `rateDps`, starting at `t0` (the rate limit at a segment boundary).
* A rate of zero or less holds `fromCourseDeg` for the whole segment instead
* (a hover: the nose keeps its heading however the track moves).
* Call after writing the segment.
* @param {Float32Array} out
* @param {number} row
* @param {number} fromCourseDeg
* @param {number} t0
* @param {number} rateDps
* @param {number} [offsetDeg] The glide's start offset from the segment's
* course, when the caller has it (render/motion/iconMotion's
* `glideOffset`): its sign then picks the way an exact half turn goes.
*/
export function writeCourseGlide(
out,
row,
fromCourseDeg,
t0,
rateDps,
offsetDeg,
) {
const o = row * SEGMENT_STRIDE;
out[o + SLEW_OFFSET] = 0;
const target = targetCourse(out, o, t0);
out[o + SLEW_OFFSET] = offsetDeg ?? norm180(fromCourseDeg - target);
out[o + SLEW_T0] = t0;
out[o + SLEW_RATE] = rateDps > 0 ? rateDps : -1;
}
/**
* Move a row's stored times by `deltaSec` (the epoch moved by `-deltaSec`).
* @param {Float32Array} out
* @param {number} row
* @param {number} deltaSec
*/
export function shiftSegmentTimes(out, row, deltaSec) {
const o = row * SEGMENT_STRIDE;
out[o + T0] += deltaSec;
out[o + SLEW_T0] += deltaSec;
}
/** Elapsed fraction (lerp) or clamped elapsed seconds (arc) at `tau`. */
function segmentParameter(seg, o, tau) {
const kind = seg[o + KIND];
if (kind === SEGMENT_LERP) {
const span = seg[o + P1];
return span > 0 ? Math.min(1, Math.max(0, (tau - seg[o + T0]) / span)) : 1;
}
if (kind === SEGMENT_ARC)
return Math.min(seg[o + P2], Math.max(seg[o + P1], tau - seg[o + T0]));
return 0;
}
function sinc(x) {
return Math.abs(x) < 1e-4 ? 1 - (x * x) / 6 : Math.sin(x) / x;
}
/**
* The displayed course at `tau`, in degrees clockwise from north.
* @param {Float32Array} seg
* @param {number} row
* @param {number} tau
* @returns {number}
*/
export function segmentCourse(seg, row, tau) {
const o = row * SEGMENT_STRIDE;
const course = targetCourse(seg, o, tau);
const offset = seg[o + SLEW_OFFSET];
if (seg[o + SLEW_RATE] < 0)
return norm360(targetCourse(seg, o, seg[o + SLEW_T0]) + offset);
if (offset === 0) return norm360(course);
// limitCourseStep: the displayed course turns at the rate toward the segment's
// own (possibly turning) course until it reaches it, then follows it. The
// segment's course is linear and unwrapped, so the gap needs no modulo.
const t0 = seg[o + SLEW_T0];
const toward = -Math.sign(offset);
const start = targetCourse(seg, o, t0);
const turned = seg[o + SLEW_RATE] * Math.max(0, tau - t0);
const gap = toward * (course - start - offset);
return norm360(turned < gap ? start + offset + toward * turned : course);
}
/**
* The course the row glides toward at `tau` (its segment's own course).
* @param {Float32Array} seg
* @param {number} row
* @param {number} tau
* @returns {number}
*/
export function segmentTargetCourse(seg, row, tau) {
return norm360(targetCourse(seg, row * SEGMENT_STRIDE, tau));
}
/** The segment's own course at `tau`, before any glide. */
function targetCourse(seg, o, tau) {
const kind = seg[o + KIND];
const p = segmentParameter(seg, o, tau);
let course = seg[o + COURSE0];
if (kind === SEGMENT_LERP) course += seg[o + COURSE_SLOPE] * p;
else if (kind === SEGMENT_ARC) course += (seg[o + OMEGA] / DEG) * p;
return course;
}
/**
* Where the row is at `tau`, in ECEF.
* @param {Float32Array} seg
* @param {number} row
* @param {number} tau
* @param {{x: number, y: number, z: number}} [result]
* @returns {{x: number, y: number, z: number}}
*/
export function segmentPosition(seg, row, tau, result = { x: 0, y: 0, z: 0 }) {
const o = row * SEGMENT_STRIDE;
let x = seg[o + BASE_HIGH] + seg[o + BASE_LOW];
let y = seg[o + BASE_HIGH + 1] + seg[o + BASE_LOW + 1];
let z = seg[o + BASE_HIGH + 2] + seg[o + BASE_LOW + 2];
const kind = seg[o + KIND];
if (kind === SEGMENT_LERP) {
const f = segmentParameter(seg, o, tau);
x += seg[o + AXIS_U] * f;
y += seg[o + AXIS_U + 1] * f;
z += seg[o + AXIS_U + 2] * f;
} else if (kind === SEGMENT_ARC) {
const dt = segmentParameter(seg, o, tau);
const half = seg[o + OMEGA] * dt * 0.5;
const reach = seg[o + SPEED] * dt * sinc(half);
const heading = seg[o + TRACK] + half;
const e = reach * Math.sin(heading);
const n = reach * Math.cos(heading);
x += seg[o + AXIS_U] * e + seg[o + AXIS_V] * n;
y += seg[o + AXIS_U + 1] * e + seg[o + AXIS_V + 1] * n;
z += seg[o + AXIS_U + 2] * e + seg[o + AXIS_V + 2] * n;
const climb = seg[o + CLIMB] * dt;
if (climb !== 0) {
// Up is east × north.
const ux = seg[o + AXIS_U];
const uy = seg[o + AXIS_U + 1];
const uz = seg[o + AXIS_U + 2];
const vx = seg[o + AXIS_V];
const vy = seg[o + AXIS_V + 1];
const vz = seg[o + AXIS_V + 2];
x += (uy * vz - uz * vy) * climb;
y += (uz * vx - ux * vz) * climb;
z += (ux * vy - uy * vx) * climb;
}
}
result.x = x;
result.y = y;
result.z = z;
return result;
}
/**
* GLSL for the same evaluation. Expects the six segment vec4s as `seg0`…`seg5`
* (floats 0–3, 4–7, … of the packed row) and returns the eye-relative position in
* `positionRte` and the course in degrees.
*/
export const ICON_SEGMENT_GLSL = /* glsl */ `
float iconSinc(float x) {
return abs(x) < 1e-4 ? 1.0 - x * x / 6.0 : sin(x) / x;
}
float iconSegmentParameter(vec4 seg3, vec4 seg4, float tau) {
float kind = seg3.x;
if (kind == 1.0) {
float span = seg3.z;
return span > 0.0 ? clamp((tau - seg3.y) / span, 0.0, 1.0) : 1.0;
}
if (kind == 2.0) return clamp(tau - seg3.y, seg3.z, seg3.w);
return 0.0;
}
vec3 iconSegmentPosition(vec4 seg0, vec4 seg1, vec4 seg2, vec4 seg3, vec4 seg4, vec4 seg5, float tau) {
vec3 high = seg0.xyz;
vec3 low = vec3(seg0.w, seg1.xy);
vec3 axisU = vec3(seg1.zw, seg2.x);
vec3 axisV = seg2.yzw;
vec4 rte = czm_translateRelativeToEye(high, low);
vec3 p = rte.xyz;
float kind = seg3.x;
float t = iconSegmentParameter(seg3, seg4, tau);
if (kind == 1.0) {
p += axisU * t;
} else if (kind == 2.0) {
float half_ = seg4.z * t * 0.5;
float reach = seg4.x * t * iconSinc(half_);
float heading = seg4.y + half_;
p += axisU * (reach * sin(heading)) + axisV * (reach * cos(heading));
p += cross(axisU, axisV) * (seg5.x * t);
}
return p;
}
float iconTargetCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) {
float kind = seg3.x;
float t = iconSegmentParameter(seg3, seg4, tau);
float course = seg4.w;
if (kind == 1.0) course += seg5.x * t;
else if (kind == 2.0) course += degrees(seg4.z) * t;
return course;
}
float iconSegmentCourse(vec4 seg3, vec4 seg4, vec4 seg5, float tau) {
float course = iconTargetCourse(seg3, seg4, seg5, tau);
float offset = seg5.y;
if (seg5.w < 0.0) return iconTargetCourse(seg3, seg4, seg5, seg5.z) + offset;
if (offset == 0.0) return course;
float toward = -sign(offset);
float start = iconTargetCourse(seg3, seg4, seg5, seg5.z);
float turned = seg5.w * max(0.0, tau - seg5.z);
float gap = toward * (course - start - offset);
return turned < gap ? start + offset + toward * turned : course;
}
`;
+333
View File
@@ -0,0 +1,333 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
SEGMENT_STRIDE,
segmentCourse,
segmentPosition,
writeArcSegment,
writeCourseGlide,
writeHoldSegment,
writeLerpSegment,
} from './iconSegment.js';
import {
arcOffsetEnu,
lerpAngleDeg,
limitCourseStep,
norm180,
} from './motionModel.js';
const fix = Cesium.Cartesian3.fromDegrees(-97.04, 32.9, 10_500);
/** What the flights layer's _extrapolateFix draws for the same fix and dt. */
function productionArc(position, speed, trackDeg, turnRateDps, dt) {
const arc = arcOffsetEnu(speed, trackDeg, turnRateDps, dt, {});
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(position);
const offset = new Cesium.Cartesian3(arc.east, arc.north, 0);
return {
position: Cesium.Matrix4.multiplyByPoint(
enu,
offset,
new Cesium.Cartesian3(),
),
course: arc.endCourseDeg,
};
}
function courseGap(a, b) {
return Math.abs(norm180(a - b));
}
test('a hold stays put to float32 encoding precision', () => {
const seg = new Float32Array(SEGMENT_STRIDE * 2);
writeHoldSegment(seg, 1, fix, 271);
const at = segmentPosition(seg, 1, 1234);
assert.ok(Cesium.Cartesian3.distance(at, fix) < 0.005);
assert.equal(segmentCourse(seg, 1, 99), 271);
});
test('a lerp matches Cesium.Cartesian3.lerp between two fixes and holds at both ends', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
const to = Cesium.Cartesian3.fromDegrees(-97.0, 32.93, 10_650);
writeLerpSegment(seg, 0, {
from: fix,
to,
t0: 100,
t1: 110,
course0Deg: 40,
courseSlopeDeg: 6,
});
for (const tau of [100, 102.5, 107, 110]) {
const want = Cesium.Cartesian3.lerp(
fix,
to,
(tau - 100) / 10,
new Cesium.Cartesian3(),
);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, tau), want) < 0.01,
`τ=${tau}`,
);
}
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 50), fix) < 0.01,
);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 500), to) < 0.01,
);
assert.ok(courseGap(segmentCourse(seg, 0, 105), 43) < 1e-4);
});
test('a lerp course reproduces the blended track-and-chord course across the segment', () => {
// _deadReckon: lerpAngle(lerpAngle(trackFrom, trackTo, t), chord, w).
const trackFrom = 350;
const trackTo = 20;
const chord = 10;
const w = 0.6;
const at = (t) => lerpAngleDeg(lerpAngleDeg(trackFrom, trackTo, t), chord, w);
const course0 = at(0);
const slope = norm180(trackTo - trackFrom) * (1 - w);
const seg = new Float32Array(SEGMENT_STRIDE);
const to = Cesium.Cartesian3.fromDegrees(-97.0, 32.93, 10_650);
writeLerpSegment(seg, 0, {
from: fix,
to,
t0: 0,
t1: 10,
course0Deg: course0,
courseSlopeDeg: slope,
});
for (const t of [0, 0.25, 0.5, 0.9, 1])
assert.ok(courseGap(segmentCourse(seg, 0, t * 10), at(t)) < 1e-3, `t=${t}`);
});
test('an arc matches the production turn for straight, slow, standard and tight turns', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
for (const turnRateDps of [0, 0.004, 0.01, 0.5, 3, -3, 12]) {
for (const dt of [0.08, 1, 30, 120, 300]) {
writeArcSegment(seg, 0, {
fix,
t0: 1000,
minDt: -60,
maxDt: 300,
speedMps: 240,
trackDeg: 305,
turnRateDps,
});
const want = productionArc(fix, 240, 305, turnRateDps, dt);
const got = segmentPosition(seg, 0, 1000 + dt);
assert.ok(
Cesium.Cartesian3.distance(got, want.position) < 0.05,
`ω=${turnRateDps}°/s dt=${dt}s off by ${Cesium.Cartesian3.distance(got, want.position)} m`,
);
assert.ok(
courseGap(segmentCourse(seg, 0, 1000 + dt), want.course) < 1e-3,
);
}
}
});
test('an arc extrapolates backward for warm-up and clamps both ends', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix,
t0: 500,
minDt: -60,
maxDt: 0,
speedMps: 200,
trackDeg: 90,
turnRateDps: 1.5,
});
const back = productionArc(fix, 200, 90, 1.5, -20);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 480), back.position) <
0.05,
);
const earliest = productionArc(fix, 200, 90, 1.5, -60);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 0), earliest.position) <
0.05,
);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 900), fix) < 0.01,
);
});
test('the course glide follows limitCourseStep onto a steady target', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeHoldSegment(seg, 0, fix, 10);
writeCourseGlide(seg, 0, 300, 50, 24);
let prev = 300;
for (let tau = 50; tau <= 56; tau += 0.08) {
assert.ok(courseGap(segmentCourse(seg, 0, tau), prev) < 1e-3, `τ=${tau}`);
prev = limitCourseStep(prev, 10, 24, 0.08);
}
assert.equal(segmentCourse(seg, 0, 80), 10);
});
test('writing a segment clears the previous one', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix,
t0: 0,
minDt: 0,
maxDt: 300,
speedMps: 250,
trackDeg: 0,
turnRateDps: 3,
});
writeCourseGlide(seg, 0, 90, 0, 30);
writeHoldSegment(seg, 0, fix, 5);
assert.ok(
Cesium.Cartesian3.distance(segmentPosition(seg, 0, 100), fix) < 0.005,
);
assert.equal(segmentCourse(seg, 0, 0), 5);
});
test('the course glide never outruns the rate while its target turns', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix,
t0: 0,
minDt: 0,
maxDt: 300,
speedMps: 200,
trackDeg: 90,
turnRateDps: 3,
});
writeCourseGlide(seg, 0, 60, 0, 24);
let prev = 60;
for (let tau = 0; tau <= 4; tau += 0.01) {
assert.ok(
courseGap(segmentCourse(seg, 0, tau), prev) < 0.05,
`τ=${tau.toFixed(2)}`,
);
prev = limitCourseStep(prev, 90 + 3 * (tau + 0.01), 24, 0.01);
}
assert.ok(
courseGap(segmentCourse(seg, 0, 1), 84) < 0.05,
'24° in the first second, not 27°',
);
assert.ok(
courseGap(segmentCourse(seg, 0, 10), 120) < 1e-3,
'then it follows the turn',
);
});
test('a zero-rate glide holds the course however the segment turns', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
const to = Cesium.Cartesian3.fromDegrees(-97.04, 32.90001, 10_500);
for (const from of [0, 30]) {
writeLerpSegment(seg, 0, {
from: fix,
to,
t0: 0,
t1: 30,
course0Deg: 0,
courseSlopeDeg: 90,
});
writeCourseGlide(seg, 0, from, 0, 0);
for (const tau of [0, 10, 20, 30, 60])
assert.ok(
courseGap(segmentCourse(seg, 0, tau), from) < 1e-4,
`from ${from}° at τ=${tau}`,
);
}
writeArcSegment(seg, 0, {
fix,
t0: 0,
minDt: 0,
maxDt: 300,
speedMps: 1,
trackDeg: 90,
turnRateDps: 3,
});
writeCourseGlide(seg, 0, 90, 0, 0);
assert.ok(courseGap(segmentCourse(seg, 0, 20), 90) < 1e-4, 'arc turn held');
});
test('an arc climbs along the fix’s up axis at its climb rate, inside its clamped time', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix,
t0: 100,
minDt: -10,
maxDt: 20,
speedMps: 200,
trackDeg: 90,
turnRateDps: 3,
climbMps: 15,
});
const up = Cesium.Ellipsoid.WGS84.geodeticSurfaceNormal(fix);
for (const [tau, dt] of [
[108, 8],
[130, 20],
[80, -10],
]) {
const flat = productionArc(fix, 200, 90, 3, dt).position;
const want = Cesium.Cartesian3.add(
flat,
Cesium.Cartesian3.multiplyByScalar(up, 15 * dt, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const at = segmentPosition(seg, 0, tau);
assert.ok(
Cesium.Cartesian3.distance(at, want) < 0.05,
`at ${dt} s: ${Cesium.Cartesian3.distance(at, want)} m off`,
);
}
// The climb does not turn the course.
assert.ok(courseGap(segmentCourse(seg, 0, 108), 90 + 3 * 8) < 1e-3);
});
test('an arc written without a climb stays in its tangent plane', () => {
const seg = new Float32Array(SEGMENT_STRIDE);
seg.fill(7);
writeArcSegment(seg, 0, {
fix,
t0: 0,
minDt: 0,
maxDt: 30,
speedMps: 100,
trackDeg: 0,
turnRateDps: 0,
});
const at = segmentPosition(seg, 0, 30);
const want = productionArc(fix, 100, 0, 0, 30).position;
assert.ok(Cesium.Cartesian3.distance(at, want) < 0.05);
});
test('segments store the floats the default renderer encodes, east and north included', () => {
const points = [
fix,
Cesium.Cartesian3.fromDegrees(151.2, -33.9, 40),
Cesium.Cartesian3.fromDegrees(-0.0001, 0.0001, -31),
Cesium.Cartesian3.fromDegrees(12, 89.9999, 9_000),
new Cesium.Cartesian3(0, 0, 6_356_752.3),
new Cesium.Cartesian3(0, 0, -6_356_752.3),
new Cesium.Cartesian3(-65536, 131072.5, -1),
new Cesium.Cartesian3(0, 0, 0),
new Cesium.Cartesian3(0, 0, -1e-15),
];
const encoded = new Cesium.EncodedCartesian3();
const enu = new Cesium.Matrix4();
for (const p of points) {
const seg = new Float32Array(SEGMENT_STRIDE);
writeArcSegment(seg, 0, {
fix: p,
t0: 0,
minDt: 0,
maxDt: 10,
speedMps: 100,
trackDeg: 30,
turnRateDps: 1,
});
const want = new Float32Array(SEGMENT_STRIDE);
Cesium.EncodedCartesian3.fromCartesian(p, encoded);
Cesium.Transforms.eastNorthUpToFixedFrame(p, Cesium.Ellipsoid.WGS84, enu);
want.set([encoded.high.x, encoded.high.y, encoded.high.z], 0);
want.set([encoded.low.x, encoded.low.y, encoded.low.z], 3);
want.set([enu[0], enu[1], enu[2], enu[4], enu[5], enu[6]], 6);
assert.deepStrictEqual(seg.slice(0, 12), want.slice(0, 12), `at ${p}`);
}
});
+775
View File
@@ -0,0 +1,775 @@
/**
* @module iconSet
* @description A set of icons the app draws, held as typed-array columns: the only copy of
* what was pushed. Each row is one icon, keyed by a string id and carrying an opaque
* `meta` that comes back on picks. A row moves along its segment ({@link module:iconSegment})
* on the renderer's clock, so the CPU writes a row only when its motion or style changes.
*
* Rows are packed: removing one moves the last row into its place, so the renderer
* draws `count` instances and the CPU walks rows by index. Writes mark rows dirty per
* column ({@link DirtyRows}) for the renderer to upload.
*
* Segment times are float32 seconds since the set's epoch. The renderer calls
* {@link rebase} once a frame so they stay small (sub-millisecond steps) however
* long the session runs.
*/
import { WGS84 } from '../geo/ellipsoid.js';
import { HORIZON_LIFT_M } from '../geo/horizon.js';
import { cloneJulian, julianNow, secondsDifference } from '../geo/julian.js';
import {
SEGMENT_STRIDE,
segmentCourse,
segmentPosition,
shiftSegmentTimes,
} from './iconSegment.js';
/**
* Floats per row of style: size, scale, alpha, atlas slots, flags, focus,
* near/far scaler, near-image switch, pick proxy and depth-test distance.
*/
export const STYLE_STRIDE = 16;
const WIDTH = 0;
const HEIGHT = 1;
const SCALE = 2;
const ALPHA = 3;
const IMAGE_FAR = 4;
const IMAGE_NEAR = 5;
const FLAGS = 6;
const FOCUS = 7;
const NEAR_DISTANCE = 8;
const NEAR_VALUE = 9;
const FAR_DISTANCE = 10;
const FAR_VALUE = 11;
const IMAGE_SWITCH = 12;
const PROXY_WIDTH = 13;
const PROXY_HEIGHT = 14;
const DEPTH_TEST_DISTANCE = 15;
/**
* Floats per row of extras, as `ICON_EXTRA_TEXELS` RGBA texels the renderer
* reads by instance: the screen offset, anchor and rotation; the fade by
* distance; the aligned axis and display range; the ground mode and the
* ground heights under the segment's two ends, and those ends. All zero (the
* default) is none of them.
*/
export const ICON_EXTRA_TEXELS = 6;
export const EXTRA_STRIDE = ICON_EXTRA_TEXELS * 4;
const OFFSET_X = 0;
const OFFSET_Y = 1;
const ANCHOR = 2;
const ROTATION = 3;
const FADE_NEAR = 4;
const FADE_NEAR_VALUE = 5;
const FADE_FAR = 6;
const FADE_FAR_VALUE = 7;
const AXIS_X = 8;
const AXIS_Y = 9;
const AXIS_Z = 10;
const RANGE_NEAR = 11;
const RANGE_FAR = 12;
const GROUND_MODE = 13;
const GROUND_FROM = 14;
const GROUND_TO = 15;
const SPAN_FROM = 16;
const SPAN_TO = 20;
/** Ground modes of a row's extras. */
export const ICON_GROUND_NONE = 0;
/** Drawn on the ground under it. */
export const ICON_GROUND_CLAMP = 1;
/** Drawn its height above the ground under it. */
export const ICON_GROUND_RELATIVE = 2;
/**
* A depth-test distance at or past this draws over depth at any distance
* (Infinity, which a float column does not carry through every GPU).
*/
export const ICON_ALWAYS_OVER_DEPTH = 1e30;
/** Row flags, combined in the style's flags float. */
export const ICON_SHOWN = 1;
/** Rotate the icon along its course on screen (otherwise upright). */
export const ICON_ROTATES = 2;
/** Fade and shrink toward the globe's limb (aircraft recession). */
export const ICON_RECEDES = 4;
/**
* Judge the row at no lower than ICON_CULL_HEIGHT_M above the ellipsoid in the
* horizon test. A fix near or below the ellipsoid (a grounded contact at geoid
* −31 m before its floor warms) otherwise reads as beyond the limb.
*/
export const ICON_CULL_LIFT = 8;
/** The ellipsoid height a CULL_LIFT row is raised to for the horizon test. */
export const ICON_CULL_HEIGHT_M = HORIZON_LIFT_M;
/**
* Contacts whose fix is below this height (m) get CULL_LIFT in the aircraft
* layers' icon sets; theirs are the only rows flagged by height.
*
* Through the draw port a `horizonCull` set flags every row, so every row
* drawn below ICON_CULL_HEIGHT_M is lifted. The two agree on every row this
* rule flags (lifted either way) and every row drawn at or above
* ICON_CULL_HEIGHT_M (no lift either way). They differ only on rows this
* rule leaves unflagged (fix at or above 10 m) while drawn below 12 m: a
* contact between 10 and 12 m (judged up to 2 m higher), or one whose drawn
* position sits lower than its fix (a climb-out from a lower earlier fix, a
* dead-reckoned ground drift). The port judges those higher, so it never
* hides what this rule shows, and shows near-ground contacts at the limb that
* this rule culled, which is what the lift is for.
*/
export const ICON_CULL_LIFT_BELOW_M = 10;
/** Move the epoch once render times are this many seconds from it. */
const REBASE_AFTER_SEC = 1800;
/**
* Rows written since the last upload, for one column. Uploads go out as runs of
* nearby rows, so a removal near the top and a write near the bottom send two
* small runs rather than the whole column.
*/
export class DirtyRows {
constructor(capacity) {
this._marked = new Uint8Array(capacity);
this._rows = [];
this._all = false;
}
mark(row) {
if (this._all || this._marked[row]) return;
this._marked[row] = 1;
this._rows.push(row);
}
markAll() {
this._all = true;
}
get empty() {
return !this._all && this._rows.length === 0;
}
/**
* Coalesced `[from, to]` runs of dirty rows below `count`, merging rows closer
* than `gap`; everything when marked all or when most rows are dirty.
* @param {number} count
* @param {number} [gap]
* @returns {Array<[number, number]>}
*/
runs(count, gap = 32) {
if (count === 0) return [];
if (this._all || this._rows.length * 4 > count) return [[0, count - 1]];
const rows = this._rows.filter((row) => row < count).sort((a, b) => a - b);
const runs = [];
for (const row of rows) {
const last = runs[runs.length - 1];
if (last && row - last[1] <= gap) last[1] = row;
else runs.push([row, row]);
}
return runs;
}
clear() {
for (const row of this._rows) this._marked[row] = 0;
this._rows.length = 0;
this._all = false;
}
grow(capacity) {
const marked = new Uint8Array(capacity);
marked.set(this._marked);
this._marked = marked;
this.markAll();
}
}
/** A 0..1 colour channel as a byte, as the default renderer's `Color.floatToByte`. */
const floatToByte = (value) => (value === 1.0 ? 255.0 : (value * 256.0) | 0);
/**
* @param {{ capacity?: number,
* epoch?: {dayNumber: number, secondsOfDay: number} }} [options] `epoch`
* is a Julian date (`geo/julian.js`, or the renderer's own, which is the
* same numbers).
*/
export function createIconSet({ capacity = 1024, epoch } = {}) {
capacity = Math.max(1, capacity);
const rowOfId = new Map();
let ids = [];
let metas = [];
let handles = [];
let segments = new Float32Array(capacity * SEGMENT_STRIDE);
let style = new Float32Array(capacity * STYLE_STRIDE);
let colors = new Uint8Array(capacity * 4);
let extras = new Float32Array(capacity * EXTRA_STRIDE);
// CPU only: until when (seconds since the epoch) the row's segment holds.
let expires = new Float64Array(capacity);
let count = 0;
const epochTime = cloneJulian(epoch ?? julianNow(), {});
const set = {
/** Bumped when the columns are reallocated; the renderer rebuilds its buffers. */
generation: 0,
dirty: {
segments: new DirtyRows(capacity),
style: new DirtyRows(capacity),
colors: new DirtyRows(capacity),
extras: new DirtyRows(capacity),
},
show: true,
/** Called with a row's renderer handle when the row goes away. */
onRelease: null,
get count() {
return count;
},
get capacity() {
return capacity;
},
get segments() {
return segments;
},
get style() {
return style;
},
get colors() {
return colors;
},
get extras() {
return extras;
},
get epoch() {
return epochTime;
},
/** Seconds since the set's epoch: the clock segments are written in. */
seconds(julianDate) {
return secondsDifference(julianDate, epochTime);
},
/**
* Move the epoch to `julianDate` once it is more than half an hour away
* (ahead, or behind on a clock set back), shifting every stored time. Call between frames, never while a caller holds
* times in the old base.
* @returns {boolean} Whether it moved.
*/
rebase(julianDate) {
const shift = set.seconds(julianDate);
if (Math.abs(shift) < REBASE_AFTER_SEC) return false;
for (let row = 0; row < count; row++) {
shiftSegmentTimes(segments, row, -shift);
expires[row] -= shift;
}
cloneJulian(julianDate, epochTime);
set.dirty.segments.markAll();
return true;
},
has(id) {
return rowOfId.has(id);
},
row(id) {
return rowOfId.get(id) ?? -1;
},
idAt(row) {
return ids[row];
},
metaAt(row) {
return metas[row];
},
handleAt(row) {
return handles[row];
},
setHandle(row, handle) {
handles[row] = handle;
},
/**
* Add a row (hidden, no image) or return the existing row for `id`.
* @param {string} id
* @param {*} [meta]
* @returns {number} The row.
*/
add(id, meta) {
const existing = rowOfId.get(id);
if (existing !== undefined) {
metas[existing] = meta;
return existing;
}
if (count === capacity) grow(capacity * 2);
const row = count++;
rowOfId.set(id, row);
ids[row] = id;
metas[row] = meta;
handles[row] = undefined;
segments.fill(0, row * SEGMENT_STRIDE, (row + 1) * SEGMENT_STRIDE);
style.fill(0, row * STYLE_STRIDE, (row + 1) * STYLE_STRIDE);
const o = row * STYLE_STRIDE;
style[o + SCALE] = 1;
style[o + ALPHA] = 1;
style[o + FOCUS] = 1;
style[o + IMAGE_FAR] = -1;
style[o + IMAGE_NEAR] = -1;
style[o + DEPTH_TEST_DISTANCE] = ICON_ALWAYS_OVER_DEPTH;
colors.fill(255, row * 4, row * 4 + 4);
extras.fill(0, row * EXTRA_STRIDE, (row + 1) * EXTRA_STRIDE);
expires[row] = -Infinity;
markRow(row);
return row;
},
/** Remove `id`'s row; the last row moves into its place. */
remove(id) {
const row = rowOfId.get(id);
if (row === undefined) return false;
rowOfId.delete(id);
const handle = handles[row];
const last = --count;
if (row !== last) {
segments.copyWithin(
row * SEGMENT_STRIDE,
last * SEGMENT_STRIDE,
(last + 1) * SEGMENT_STRIDE,
);
style.copyWithin(
row * STYLE_STRIDE,
last * STYLE_STRIDE,
(last + 1) * STYLE_STRIDE,
);
colors.copyWithin(row * 4, last * 4, last * 4 + 4);
extras.copyWithin(
row * EXTRA_STRIDE,
last * EXTRA_STRIDE,
(last + 1) * EXTRA_STRIDE,
);
expires[row] = expires[last];
ids[row] = ids[last];
metas[row] = metas[last];
handles[row] = handles[last];
rowOfId.set(ids[row], row);
markRow(row);
}
ids[last] = undefined;
metas[last] = undefined;
handles[last] = undefined;
if (handle !== undefined) set.onRelease?.(handle);
return true;
},
clear() {
for (let row = 0; row < count; row++)
if (handles[row] !== undefined) set.onRelease?.(handles[row]);
rowOfId.clear();
ids = [];
metas = [];
handles = [];
count = 0;
},
/** Mark a row's segment written (after a write*Segment call on `segments`). */
segmentWritten(row, expiresAt = Infinity) {
expires[row] = expiresAt;
set.dirty.segments.mark(row);
},
/** Until when (seconds since the epoch) the row's segment holds. */
expires(row) {
return expires[row];
},
setShown(row, shown) {
setFlag(row, ICON_SHOWN, shown);
},
shown(row) {
return (style[row * STYLE_STRIDE + FLAGS] & ICON_SHOWN) !== 0;
},
setFlag(row, flag, on) {
setFlag(row, flag, on);
},
flags(row) {
return style[row * STYLE_STRIDE + FLAGS];
},
setSize(row, width, height) {
const o = row * STYLE_STRIDE;
if (
style[o + WIDTH] === Math.fround(width) &&
style[o + HEIGHT] === Math.fround(height)
)
return;
style[o + WIDTH] = width;
style[o + HEIGHT] = height;
set.dirty.style.mark(row);
},
width(row) {
return style[row * STYLE_STRIDE + WIDTH];
},
height(row) {
return style[row * STYLE_STRIDE + HEIGHT];
},
setScale(row, scale) {
writeStyle(row, SCALE, scale);
},
scale(row) {
return style[row * STYLE_STRIDE + SCALE];
},
/** The row's own alpha; the renderer multiplies in recession and focus. */
setAlpha(row, alpha) {
writeStyle(row, ALPHA, alpha);
},
alpha(row) {
return style[row * STYLE_STRIDE + ALPHA];
},
/** Focus de-emphasis factor, 1 when not de-emphasised. */
setFocus(row, factor) {
writeStyle(row, FOCUS, factor);
},
focus(row) {
return style[row * STYLE_STRIDE + FOCUS];
},
/** Atlas slots: `far` for small on-screen sizes, `near` once the icon is large. */
setImage(row, far, near = far) {
const o = row * STYLE_STRIDE;
if (style[o + IMAGE_FAR] === far && style[o + IMAGE_NEAR] === near)
return;
style[o + IMAGE_FAR] = far;
style[o + IMAGE_NEAR] = near;
set.dirty.style.mark(row);
},
imageFar(row) {
return style[row * STYLE_STRIDE + IMAGE_FAR];
},
imageNear(row) {
return style[row * STYLE_STRIDE + IMAGE_NEAR];
},
/**
* Draw the near image once the icon is wider than `px` CSS pixels on
* screen; 0 (the default) switches past the renderer's own device-pixel
* threshold.
*/
setImageSwitch(row, px) {
writeStyle(row, IMAGE_SWITCH, px);
},
imageSwitch(row) {
return style[row * STYLE_STRIDE + IMAGE_SWITCH];
},
/**
* An invisible pick target of `width × height` CSS pixels, picked
* wherever it or the icon covers; 0 × 0 (the default) picks the icon's
* drawn pixels only.
*/
setPickProxy(row, width, height) {
const o = row * STYLE_STRIDE;
if (
style[o + PROXY_WIDTH] === Math.fround(width) &&
style[o + PROXY_HEIGHT] === Math.fround(height)
)
return;
style[o + PROXY_WIDTH] = width;
style[o + PROXY_HEIGHT] = height;
set.dirty.style.mark(row);
},
pickProxyWidth(row) {
return style[row * STYLE_STRIDE + PROXY_WIDTH];
},
pickProxyHeight(row) {
return style[row * STYLE_STRIDE + PROXY_HEIGHT];
},
/**
* Draw over depth within `metres` of the eye, as a billboard's
* `disableDepthTestDistance`: 0 tests depth everywhere, Infinity (the
* default) never does.
*/
setDepthTestDistance(row, metres) {
writeStyle(
row,
DEPTH_TEST_DISTANCE,
metres >= ICON_ALWAYS_OVER_DEPTH ? ICON_ALWAYS_OVER_DEPTH : metres,
);
},
depthTestDistance(row) {
return style[row * STYLE_STRIDE + DEPTH_TEST_DISTANCE];
},
/**
* Size by camera distance, as a `{near, nearValue, far, farValue}` curve
* (the default renderer's NearFarScalar; unset: 1 everywhere).
*/
setScaleByDistance(row, scalar) {
const o = row * STYLE_STRIDE;
const near = scalar?.near ?? 0;
const nearValue = scalar?.nearValue ?? 1;
const far = scalar?.far ?? 0;
const farValue = scalar?.farValue ?? 1;
if (
style[o + NEAR_DISTANCE] === Math.fround(near) &&
style[o + NEAR_VALUE] === Math.fround(nearValue) &&
style[o + FAR_DISTANCE] === Math.fround(far) &&
style[o + FAR_VALUE] === Math.fround(farValue)
)
return;
style[o + NEAR_DISTANCE] = near;
style[o + NEAR_VALUE] = nearValue;
style[o + FAR_DISTANCE] = far;
style[o + FAR_VALUE] = farValue;
set.dirty.style.mark(row);
},
scaleByDistance(
row,
result = { near: 0, nearValue: 0, far: 0, farValue: 0 },
) {
const o = row * STYLE_STRIDE;
result.near = style[o + NEAR_DISTANCE];
result.nearValue = style[o + NEAR_VALUE];
result.far = style[o + FAR_DISTANCE];
result.farValue = style[o + FAR_VALUE];
return result;
},
/**
* Tint as `{red, green, blue, alpha}` (0..1, the default renderer's
* Color); its alpha multiplies the row's own alpha.
*/
setColor(row, color) {
const o = row * 4;
const r = floatToByte(color.red);
const g = floatToByte(color.green);
const b = floatToByte(color.blue);
const a = floatToByte(color.alpha);
if (
colors[o] === r &&
colors[o + 1] === g &&
colors[o + 2] === b &&
colors[o + 3] === a
)
return;
colors[o] = r;
colors[o + 1] = g;
colors[o + 2] = b;
colors[o + 3] = a;
set.dirty.colors.mark(row);
},
/** The row's tint as `{red, green, blue, alpha}`, 0..1. */
color(row, result = { red: 0, green: 0, blue: 0, alpha: 0 }) {
const o = row * 4;
result.red = colors[o] / 255.0;
result.green = colors[o + 1] / 255.0;
result.blue = colors[o + 2] / 255.0;
result.alpha = colors[o + 3] / 255.0;
return result;
},
/**
* Shift on screen by `x` right and `y` down, CSS pixels, as a billboard's
* `pixelOffset`.
*/
setOffset(row, x, y) {
writeExtra(row, OFFSET_X, x);
writeExtra(row, OFFSET_Y, y);
},
offset(row) {
const o = row * EXTRA_STRIDE;
return { x: extras[o + OFFSET_X], y: extras[o + OFFSET_Y] };
},
/**
* Which edge sits on the position: 0 the centre, 1 the bottom, -1 the
* top (a billboard's vertical origin).
*/
setAnchor(row, anchor) {
writeExtra(row, ANCHOR, anchor);
},
anchor(row) {
return extras[row * EXTRA_STRIDE + ANCHOR];
},
/** Radians counter-clockwise on screen. */
setRotation(row, radians) {
writeExtra(row, ROTATION, radians);
},
rotation(row) {
return extras[row * EXTRA_STRIDE + ROTATION];
},
/**
* Turn the icon's up along an ECEF axis on screen, as a billboard's
* `alignedAxis` (zero: upright).
*/
setAxis(row, x, y, z) {
writeExtra(row, AXIS_X, x);
writeExtra(row, AXIS_Y, y);
writeExtra(row, AXIS_Z, z);
},
axis(row) {
const o = row * EXTRA_STRIDE;
return {
x: extras[o + AXIS_X],
y: extras[o + AXIS_Y],
z: extras[o + AXIS_Z],
};
},
/**
* Fade by camera distance, as a `{near, nearValue, far, farValue}`
* curve multiplying the alpha (unset: none); faded to nothing, the row
* is not drawn.
*/
setFade(row, curve) {
writeExtra(row, FADE_NEAR, curve?.near ?? 0);
writeExtra(row, FADE_NEAR_VALUE, curve?.nearValue ?? 0);
writeExtra(row, FADE_FAR, curve?.far ?? 0);
writeExtra(row, FADE_FAR_VALUE, curve?.farValue ?? 0);
},
fade(row) {
const o = row * EXTRA_STRIDE;
return {
near: extras[o + FADE_NEAR],
nearValue: extras[o + FADE_NEAR_VALUE],
far: extras[o + FADE_FAR],
farValue: extras[o + FADE_FAR_VALUE],
};
},
/**
* Drawn only at camera distances from `near` to `far`, metres; a `far`
* not past `near` is no range.
*/
setDisplayRange(row, near, far) {
writeExtra(row, RANGE_NEAR, near);
writeExtra(row, RANGE_FAR, Math.min(far, ICON_ALWAYS_OVER_DEPTH));
},
displayRange(row) {
const o = row * EXTRA_STRIDE;
return [extras[o + RANGE_NEAR], extras[o + RANGE_FAR]];
},
/**
* Draw on the ground (`ICON_GROUND_CLAMP`) or above it
* (`ICON_GROUND_RELATIVE`) along the segment from `from` to `to` (ECEF,
* its two ends), the ground taken between the heights at those ends
* (`setGroundHeights`); `ICON_GROUND_NONE` where it is.
*/
setGround(row, mode, from, to) {
writeExtra(row, GROUND_MODE, mode);
for (const [at, p] of [
[SPAN_FROM, from],
[SPAN_TO, to],
]) {
writeExtra(row, at, p?.x ?? 0);
writeExtra(row, at + 1, p?.y ?? 0);
writeExtra(row, at + 2, p?.z ?? 0);
}
},
groundMode(row) {
return extras[row * EXTRA_STRIDE + GROUND_MODE];
},
/** The ground's ellipsoid heights under the segment's ends, metres. */
setGroundHeights(row, from, to) {
writeExtra(row, GROUND_FROM, from);
writeExtra(row, GROUND_TO, to);
},
/** The segment's ends the ground is taken along, ECEF. */
groundSpan(row) {
const o = row * EXTRA_STRIDE;
return [SPAN_FROM, SPAN_TO].map((at) => ({
x: extras[o + at],
y: extras[o + at + 1],
z: extras[o + at + 2],
}));
},
groundHeights(row) {
const o = row * EXTRA_STRIDE;
return [extras[o + GROUND_FROM], extras[o + GROUND_TO]];
},
/** Where the row is at `tau` (seconds since the epoch). */
position(row, tau, result) {
return segmentPosition(segments, row, tau, result);
},
/** The row's displayed course at `tau`, degrees clockwise from north. */
course(row, tau) {
return segmentCourse(segments, row, tau);
},
/** The point the horizon test judges for a row drawn at `position`. */
cullPoint(row, position, result = { x: 0, y: 0, z: 0 }) {
const { x, y, z } = position;
if (!(style[row * STYLE_STRIDE + FLAGS] & ICON_CULL_LIFT)) {
result.x = x;
result.y = y;
result.z = z;
return result;
}
// Height above the ellipsoid along the geocentric ray, as the shader
// computes it: exact to millimetres this close to the surface.
const o = WGS84.oneOverRadii;
const radius = Math.sqrt(x * x + y * y + z * z);
const sx = x * o.x;
const sy = y * o.y;
const sz = z * o.z;
const height = radius * (1 - 1 / Math.sqrt(sx * sx + sy * sy + sz * sz));
const lift = Math.max(0, ICON_CULL_HEIGHT_M - height);
result.x = x + (x / radius) * lift;
result.y = y + (y / radius) * lift;
result.z = z + (z / radius) * lift;
return result;
},
};
function markRow(row) {
set.dirty.segments.mark(row);
set.dirty.style.mark(row);
set.dirty.colors.mark(row);
set.dirty.extras.mark(row);
}
function writeExtra(row, field, value) {
const o = row * EXTRA_STRIDE + field;
if (extras[o] === Math.fround(value)) return;
extras[o] = value;
set.dirty.extras.mark(row);
}
function writeStyle(row, field, value) {
const o = row * STYLE_STRIDE + field;
if (style[o] === Math.fround(value)) return;
style[o] = value;
set.dirty.style.mark(row);
}
function setFlag(row, flag, on) {
const o = row * STYLE_STRIDE + FLAGS;
const flags = style[o];
const next = on ? flags | flag : flags & ~flag;
if (next === flags) return;
style[o] = next;
set.dirty.style.mark(row);
}
function grow(next) {
const s = new Float32Array(next * SEGMENT_STRIDE);
s.set(segments);
const st = new Float32Array(next * STYLE_STRIDE);
st.set(style);
const c = new Uint8Array(next * 4);
c.set(colors);
const x = new Float32Array(next * EXTRA_STRIDE);
x.set(extras);
const e = new Float64Array(next);
e.set(expires);
segments = s;
style = st;
colors = c;
extras = x;
expires = e;
capacity = next;
set.generation++;
for (const rows of Object.values(set.dirty)) rows.grow(next);
}
return set;
}
+412
View File
@@ -0,0 +1,412 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import {
createIconSet,
DirtyRows,
ICON_ALWAYS_OVER_DEPTH,
ICON_CULL_HEIGHT_M,
ICON_CULL_LIFT,
ICON_ROTATES,
ICON_SHOWN,
ICON_CULL_LIFT_BELOW_M,
} from './iconSet.js';
import {
writeArcSegment,
writeCourseGlide,
writeHoldSegment,
} from './iconSegment.js';
import { liftedForHorizon } from '../geo/horizon.js';
function place(set, id, lon, course = 0) {
const row = set.add(id, { id });
writeHoldSegment(
set.segments,
row,
Cesium.Cartesian3.fromDegrees(lon, 10, 1000),
course,
);
set.segmentWritten(row);
return row;
}
function settle(set) {
for (const rows of Object.values(set.dirty)) rows.clear();
}
test('rows are added once per id and carry their meta', () => {
const set = createIconSet({ capacity: 4 });
assert.equal(set.add('a', 1), 0);
assert.equal(set.add('b', 2), 1);
assert.equal(set.add('a', 3), 0, 'same id, same row');
assert.equal(set.metaAt(0), 3);
assert.equal(set.count, 2);
assert.equal(set.row('missing'), -1);
});
test('a new row starts hidden, unscaled, opaque white and unfocused', () => {
const set = createIconSet();
const row = set.add('a');
assert.equal(set.shown(row), false);
assert.equal(set.scale(row), 1);
assert.equal(set.alpha(row), 1);
assert.equal(set.focus(row), 1);
assert.ok(Cesium.Color.equals(set.color(row), Cesium.Color.WHITE));
});
test('removing a row moves the last row into its place with all its columns', () => {
const set = createIconSet({ capacity: 4 });
place(set, 'a', 1);
place(set, 'b', 2);
const c = place(set, 'c', 3, 120);
set.setShown(c, true);
set.setFlag(c, ICON_ROTATES, true);
set.setSize(c, 20, 24);
set.setScale(c, 1.3);
set.setColor(c, Cesium.Color.fromCssColorString('#FFB800'));
set.setHandle(c, 'handle-c');
settle(set);
assert.ok(set.remove('a'));
assert.equal(set.count, 2);
assert.equal(set.row('c'), 0);
assert.equal(set.idAt(0), 'c');
assert.deepEqual(set.metaAt(0), { id: 'c' });
assert.equal(set.handleAt(0), 'handle-c');
assert.equal(set.flags(0), ICON_SHOWN | ICON_ROTATES);
assert.equal(set.width(0), 20);
assert.equal(set.height(0), 24);
assert.ok(Math.abs(set.scale(0) - 1.3) < 1e-6);
assert.deepEqual([...set.colors.subarray(0, 4)], [255, 184, 0, 255]);
const at = set.position(0, 0);
assert.ok(
Cesium.Cartesian3.distance(at, Cesium.Cartesian3.fromDegrees(3, 10, 1000)) <
0.01,
);
assert.equal(set.course(0, 0), 120);
assert.equal(
set.dirty.segments.runs(set.count)[0][0],
0,
'the moved row uploads',
);
assert.equal(set.remove('a'), false);
});
test('removing the last row moves nothing', () => {
const set = createIconSet();
place(set, 'a', 1);
place(set, 'b', 2);
settle(set);
set.remove('b');
assert.equal(set.count, 1);
assert.ok(set.dirty.segments.empty);
});
test('a released row hands its renderer handle back', () => {
const set = createIconSet();
const released = [];
set.onRelease = (handle) => released.push(handle);
set.setHandle(set.add('a'), 'ha');
set.setHandle(set.add('b'), 'hb');
set.remove('a');
set.clear();
assert.deepEqual(released, ['ha', 'hb']);
assert.equal(set.count, 0);
assert.equal(set.has('b'), false);
});
test('unchanged writes leave the columns clean', () => {
const set = createIconSet();
const row = set.add('a');
set.setSize(row, 20, 20);
set.setScale(row, 0.8);
set.setShown(row, true);
set.setColor(row, Cesium.Color.CYAN);
set.setScaleByDistance(row, new Cesium.NearFarScalar(1000, 3, 8e6, 0.5));
settle(set);
set.setSize(row, 20, 20);
set.setScale(row, 0.8);
set.setShown(row, true);
set.setColor(row, Cesium.Color.CYAN);
set.setScaleByDistance(row, new Cesium.NearFarScalar(1000, 3, 8e6, 0.5));
assert.ok(set.dirty.style.empty);
assert.ok(set.dirty.colors.empty);
set.setScale(row, 0.9);
assert.deepEqual(set.dirty.style.runs(set.count), [[0, 0]]);
});
test('the set grows past its capacity and keeps every row', () => {
const set = createIconSet({ capacity: 2 });
for (let i = 0; i < 5; i++) place(set, `r${i}`, i, i * 10);
assert.equal(set.count, 5);
assert.ok(set.capacity >= 5);
assert.equal(set.generation, 2);
for (let i = 0; i < 5; i++)
assert.equal(set.course(set.row(`r${i}`), 0), i * 10);
});
test('times are seconds since the epoch', () => {
const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z');
const set = createIconSet({ epoch });
assert.equal(
set.seconds(
Cesium.JulianDate.addSeconds(epoch, 42.5, new Cesium.JulianDate()),
),
42.5,
);
});
test('dirty rows go out as coalesced runs, or whole when most rows changed', () => {
const rows = new DirtyRows(1000);
for (const row of [900, 3, 5, 40, 901, 3]) rows.mark(row);
assert.deepEqual(rows.runs(1000), [
[3, 5],
[40, 40],
[900, 901],
]);
assert.deepEqual(rows.runs(1000, 64), [
[3, 40],
[900, 901],
]);
assert.deepEqual(
rows.runs(500),
[
[3, 5],
[40, 40],
],
'rows past the count are dropped',
);
rows.clear();
assert.ok(rows.empty);
for (let row = 0; row < 300; row++) rows.mark(row * 3);
assert.deepEqual(rows.runs(1000), [[0, 999]]);
});
test('a new row has no image until one is set', () => {
const set = createIconSet();
const row = set.add('a');
assert.equal(set.imageFar(row), -1);
assert.equal(set.imageNear(row), -1);
set.setImage(row, 3, 4);
assert.equal(set.imageNear(row), 4);
});
test('a set of capacity zero still grows', () => {
const set = createIconSet({ capacity: 0 });
set.add('a');
set.add('b');
assert.equal(set.count, 2);
});
test('rebasing moves the epoch without moving any row', () => {
const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z');
const set = createIconSet({ epoch });
const fix = Cesium.Cartesian3.fromDegrees(-97, 33, 10_000);
const row = set.add('a');
writeArcSegment(set.segments, row, {
fix,
t0: 5000,
minDt: 0,
maxDt: 300,
speedMps: 240,
trackDeg: 80,
turnRateDps: 2,
});
writeCourseGlide(set.segments, row, 30, 5000, 20);
set.segmentWritten(row, 5100);
const tau = 5060;
const before = set.position(row, tau);
const courseBefore = set.course(row, tau);
settle(set);
const later = (s) =>
Cesium.JulianDate.addSeconds(epoch, s, new Cesium.JulianDate());
assert.equal(set.rebase(later(1000)), false, 'under half an hour: stays');
assert.equal(set.rebase(later(4000)), true);
assert.equal(set.seconds(later(4000)), 0);
const after = set.position(row, tau - 4000);
assert.ok(Cesium.Cartesian3.distance(before, after) < 0.01);
assert.ok(Math.abs(set.course(row, tau - 4000) - courseBefore) < 1e-3);
assert.equal(set.expires(row), 1100);
assert.deepEqual(set.dirty.segments.runs(set.count), [[0, 0]]);
});
test('a clock set back more than half an hour moves the epoch back too', () => {
const epoch = Cesium.JulianDate.fromIso8601('2026-11-03T12:00:00Z');
const set = createIconSet({ epoch });
const row = place(set, 'a', 4);
const before = set.position(row, 0);
const earlier = (s) =>
Cesium.JulianDate.addSeconds(epoch, s, new Cesium.JulianDate());
assert.equal(set.rebase(earlier(-1000)), false);
assert.equal(set.rebase(earlier(-86400)), true);
assert.equal(set.seconds(earlier(-86400)), 0);
assert.ok(
Cesium.Cartesian3.distance(set.position(row, 86400), before) < 0.01,
);
});
test('a cull-lift row is judged at no lower than the cull height above the ellipsoid', () => {
const set = createIconSet();
const row = set.add('a');
const height = (p) => Cesium.Cartographic.fromCartesian(p).height;
const at = (h) => Cesium.Cartesian3.fromDegrees(-84.43, 33.64, h);
assert.ok(
Math.abs(height(set.cullPoint(row, at(-31))) - -31) < 1e-6,
'unflagged: as drawn',
);
set.setFlag(row, ICON_CULL_LIFT, true);
for (const h of [-31, 0, 5]) {
assert.ok(
Math.abs(height(set.cullPoint(row, at(h))) - ICON_CULL_HEIGHT_M) < 0.01,
`${h} m is judged at ${ICON_CULL_HEIGHT_M} m`,
);
}
assert.ok(
Math.abs(height(set.cullPoint(row, at(131))) - 131) < 1e-6,
'a contact floored higher keeps its own height',
);
});
test('the Cesium-free horizon lift judges the point a cull-lift row is judged at', () => {
const set = createIconSet();
const row = set.add('a');
set.setFlag(row, ICON_CULL_LIFT, true);
for (const [lon, lat, h] of [
[4.05, 51.93, -40],
[4.05, 51.93, 3],
[-84.43, 33.64, 11.9],
[139.7, 35.6, 500],
[0, 89.5, -10],
]) {
const p = Cesium.Cartesian3.fromDegrees(lon, lat, h);
const lifted = liftedForHorizon(p);
assert.ok(
Cesium.Cartesian3.distance(set.cullPoint(row, p), lifted) < 1e-6,
`${lon}, ${lat}, ${h} m`,
);
}
});
test('a new row draws over depth everywhere, with no proxy and the default image switch', () => {
const set = createIconSet();
const row = set.add('a');
assert.equal(set.depthTestDistance(row), Math.fround(ICON_ALWAYS_OVER_DEPTH));
assert.equal(set.pickProxyWidth(row), 0);
assert.equal(set.pickProxyHeight(row), 0);
assert.equal(set.imageSwitch(row), 0);
});
test('the switch, proxy and depth-test columns mark the row only when they change', () => {
const set = createIconSet();
const row = set.add('a');
settle(set);
set.setImageSwitch(row, 40);
set.setPickProxy(row, 30, 20);
set.setDepthTestDistance(row, 5000);
assert.deepEqual(set.dirty.style.runs(set.count), [[0, 0]]);
assert.equal(set.imageSwitch(row), 40);
assert.equal(set.pickProxyWidth(row), 30);
assert.equal(set.pickProxyHeight(row), 20);
assert.equal(set.depthTestDistance(row), 5000);
settle(set);
set.setImageSwitch(row, 40);
set.setPickProxy(row, 30, 20);
set.setDepthTestDistance(row, 5000);
assert.ok(set.dirty.style.empty, 'unchanged writes leave it clean');
set.setDepthTestDistance(row, Infinity);
assert.equal(
set.depthTestDistance(row),
Math.fround(ICON_ALWAYS_OVER_DEPTH),
'Infinity is carried as the always-over-depth value',
);
});
test('removing a row moves its switch, proxy and depth-test columns too', () => {
const set = createIconSet({ capacity: 4 });
set.add('a');
const b = set.add('b');
set.setPickProxy(b, 44, 33);
set.setDepthTestDistance(b, 0);
set.remove('a');
const moved = set.row('b');
assert.equal(moved, 0);
assert.equal(set.pickProxyWidth(moved), 44);
assert.equal(set.pickProxyHeight(moved), 33);
assert.equal(set.depthTestDistance(moved), 0);
});
test('a horizon-culled draw set lifts what the aircraft layers lift, and lifts the rest no lower', () => {
const set = createIconSet();
const row = set.add('a');
set.setFlag(row, ICON_CULL_LIFT, true);
const heightOf = (p) => Cesium.Cartographic.fromCartesian(p).height;
// The aircraft layers' rule, by fix height h for a row drawn at d.
const aircraft = (h, d) =>
h < ICON_CULL_LIFT_BELOW_M ? Math.max(d, ICON_CULL_HEIGHT_M) : d;
for (const [h, d] of [
[-31, -31],
[5, 5],
[9.99, 9.99],
[12, 12],
[400, 400],
[9, 15],
[20, 20],
]) {
const at = Cesium.Cartesian3.fromDegrees(-97.04, 32.9, d);
const judged = heightOf(set.cullPoint(row, at));
assert.ok(
Math.abs(judged - aircraft(h, d)) < 1e-3,
`${h}/${d} m: ${judged}`,
);
}
// Unflagged by the aircraft rule, drawn below 12 m: judged higher, never lower.
for (const [h, d] of [
[10, 10],
[11, 11],
[20, 5],
]) {
const at = Cesium.Cartesian3.fromDegrees(4.1, 51.95, d);
const judged = heightOf(set.cullPoint(row, at));
assert.ok(Math.abs(judged - ICON_CULL_HEIGHT_M) < 1e-3, `${h}/${d} m`);
assert.ok(judged > aircraft(h, d), 'judged higher');
}
});
test('colours and cull points read as the default renderer computes them', () => {
const set = createIconSet({ capacity: 2 });
const row = set.add('a');
for (const css of ['#FFB800', '#00000080', 'rgba(12, 200, 99, 0.37)']) {
const color = Cesium.Color.fromCssColorString(css);
set.setColor(row, color);
const want = Cesium.Color.fromBytes(
Cesium.Color.floatToByte(color.red),
Cesium.Color.floatToByte(color.green),
Cesium.Color.floatToByte(color.blue),
Cesium.Color.floatToByte(color.alpha),
);
assert.ok(Cesium.Color.equals(set.color(row), want), css);
}
set.setFlag(row, ICON_CULL_LIFT, true);
for (const h of [-31, 0, 5, 11.9]) {
const p = Cesium.Cartesian3.fromDegrees(-84.43, 33.64, h);
const scaled = Cesium.Cartesian3.multiplyComponents(
p,
Cesium.Ellipsoid.WGS84.oneOverRadii,
new Cesium.Cartesian3(),
);
const radius = Cesium.Cartesian3.magnitude(p);
const height = radius * (1 - 1 / Cesium.Cartesian3.magnitude(scaled));
const lift = Math.max(0, ICON_CULL_HEIGHT_M - height);
const want = Cesium.Cartesian3.add(
p,
Cesium.Cartesian3.multiplyByScalar(
Cesium.Cartesian3.normalize(p, new Cesium.Cartesian3()),
lift,
new Cesium.Cartesian3(),
),
new Cesium.Cartesian3(),
);
assert.ok(Cesium.Cartesian3.equals(set.cullPoint(row, p), want), `h=${h}`);
}
});
+43 -25
View File
@@ -2,9 +2,10 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { spawnSync } from 'node:child_process';
import { readFileSync } from 'node:fs';
import * as Cesium from 'cesium';
import { createInfrastructureLayers } from 'gods-eye-view/infrastructure';
import { createLocalGeoJsonLayer } from 'gods-eye-view/infrastructure/geojson';
import { fakeInput } from '../input/testDoubles.mjs';
import { bindFakeGroundRenderer } from '../testSupport/fakeGroundRenderer.mjs';
function services() {
const records = new Map();
@@ -118,8 +119,6 @@ test('two viewers use their supplied contexts and dispose independently', async
}));
const hosts = [services(), services()];
const instances = hosts.map((host) => {
const sources = new Cesium.DataSourceCollection();
let click;
const layer = createLocalGeoJsonLayer(
{
id: 'local-dams',
@@ -127,27 +126,25 @@ test('two viewers use their supplied contexts and dispose independently', async
osmDerived: true,
color: '#0088ff',
url: '/dams.geojsonl',
screenSpaceEventHandlerFactory: () => ({
setInputAction(fn) {
click = fn;
},
destroy() {},
}),
},
host,
);
// A click picks the feature's stem, as the renderer's pick names it.
const viewer = {
dataSources: sources,
scene: {
canvas: {},
preRender: new Cesium.Event(),
requestRender() {},
screenSpaceCameraController: { enableInputs: true },
pick: () => ({ id: sources.get(0).entities.values[0] }),
},
camera: { moveEnd: new Cesium.Event(), flyTo() {} },
scene: { screenSpaceCameraController: { enableInputs: true } },
};
return { layer, viewer, click: () => click({ position: {} }) };
const fake = bindFakeGroundRenderer(viewer);
fake.setPick(() => {
const [stem] = fake.set('stems').items.values();
return {
set: fake.set('stems').spec.id,
id: stem.id,
meta: stem.meta,
surface: false,
};
});
const input = fakeInput(viewer);
return { layer, viewer, fake, click: () => input.click({ x: 0, y: 0 }) };
});
t.after(() =>
instances.forEach(({ layer, viewer }) => layer.destroy(viewer)),
@@ -162,10 +159,16 @@ test('two viewers use their supplied contexts and dispose independently', async
instances[0].click();
assert.ok(hosts[0].selection());
assert.equal(hosts[1].selection(), undefined);
assert.deepEqual(
instances[0].fake.flights.map(({ destination }) => destination.height),
[5000],
'the click flies to the feature',
);
instances[0].layer.destroy(instances[0].viewer);
assert.equal(hosts[0].records.size, 0);
assert.equal(hosts[1].records.size, 1);
assert.equal(instances[1].viewer.dataSources.length, 1);
assert.equal(instances[0].fake.liveSets().length, 0);
assert.equal(instances[1].fake.liveSets().length, 6);
});
test('consumer build includes only infrastructure code and resolves assets under a non-root base', async () => {
@@ -190,18 +193,33 @@ test('consumer build includes only infrastructure code and resolves assets under
const output = result.output;
const entry = output.find((item) => item.type === 'chunk' && item.isEntry);
const sources = Object.keys(entry.modules).filter((id) => id.endsWith('.js'));
// It draws and takes clicks through the renderer's ports: a viewer with no
// renderer bound draws once the caller has loaded
// `./render/cesium/unbound`.
assert.deepEqual(sources.map((id) => id.split('/').at(-1)).sort(), [
'color.js',
'dispatcher.js',
'ellipsoid.js',
'frustum.js',
'geojsonPins.js',
'heights.js',
'horizon.js',
'infrastructure.js',
'infrastructureData.js',
'infrastructureOverlayEntry.js',
'inputOwnership.js',
'localGeojsonCore.js',
'localGeojsonLod.js',
'pickRegistry.js',
'rendererOf.js',
'rhumb.js',
'scenePick.js',
'sensorPick.js',
'sphere.js',
'styleStages.js',
'vector.js',
]);
assert.deepEqual(
entry.imports,
['cesium'],
'the viewer supplies the same Cesium dependency',
);
assert.deepEqual(entry.imports, [], 'it reaches no Cesium of its own');
for (const name of ['datacenters', 'dams']) {
const asset = output.find(
(item) => item.type === 'asset' && item.fileName.includes(name),
+117 -23
View File
@@ -1,7 +1,7 @@
/**
* Who owns the pointer over the globe.
*
* Most layers bind their own `ScreenSpaceEventHandler` to the same canvas and
* Most layers read the same globe clicks (src/input/dispatcher.js) and
* select whatever is under a left click. That is right when nothing else is
* going on, and wrong the moment a tool needs the pointer for itself: a draw
* session placing a vertex on top of an aircraft must not also track the
@@ -10,21 +10,32 @@
*
* So there is one claim, held by at most one owner at a time:
*
* - A TOOL that needs the pointer calls `claimPointer('draw')` when it turns on
* and gets back a LEASE — an opaque token. It releases with
* - A TOOL that needs the pointer calls `claimPointer('draw', {onLost})` when
* it turns on and gets back a LEASE — an opaque token. It releases with
* `releasePointer(lease)` when it turns off. It does not consult anyone;
* holding the claim is what makes it the owner.
* - An AMBIENT SELECTION HANDLER — anything that picks an entity because the
* user clicked — early-returns while `isPointerFree()` is false. It never
* claims.
* user clicked — is not called while `isPointerFree()` is false: the input
* dispatcher skips it. It never claims.
*
* Claims do not stack and are never stolen: while one owner holds the pointer,
* a second `claimPointer` returns null rather than displacing it — and so does
* a second claim under the SAME name, because two live instances of one tool
* (an old one mid-teardown, its replacement already running) are two owners,
* not one. The lease is what tells them apart: releasing takes the token that
* was issued, so a superseded instance calling `releasePointer` with its own
* stale lease frees nothing and its successor keeps the pointer.
* The newest claim takes over, as a claim on the renderer's input port does
* (`src/render/contract/input.d.ts`): a second `claimPointer` ends the lease
* out, and its holder's `onLost` is called once, after the new lease holds the
* pointer, so that tool turns itself off as if the person had turned it off.
* That holds for a second claim under the SAME name too: an old instance
* mid-teardown and its replacement already running are two owners, and the
* replacement wins. The lease is what tells them apart: releasing takes the
* token that was issued, so a superseded instance calling `releasePointer`
* with its own stale lease frees nothing and its successor keeps the pointer.
*
* Each scene's input dispatcher bridges its renderer's input port here
* (`bridgePointer`): while a tool holds the pointer the port holds a lease
* for it, so the port is not free, and a claim made on the port itself
* takes over from the tool here like any newer claim. While such a claim is
* out the pointer is not free. The bridge's lease takes no press (its `grab`
* refuses each one): the dispatcher decides who hears each event when it
* arrives, and the renderer's own select and double-click follow run unless
* a tool holds them off (`suppressStockClicks`).
*
* Ownership is page-scoped, like the layers and handlers it arbitrates.
*/
@@ -34,19 +45,93 @@
/** @type {PointerLease|null} */
let currentLease = null;
let nextLeaseId = 1;
/** @type {WeakMap<PointerLease, () => void>} each lease's `onLost` */
const lostHandlers = new WeakMap();
/** @type {Set<{claimed: (lease: PointerLease|null) => void, isFree: () => boolean}>} */
const bridges = new Set();
/**
* Take the pointer for `owner`.
* Take the pointer for `owner`. The newest claim takes over: the lease out
* ends, and its `onLost` is called once, after this one holds the pointer.
* @param {string} owner Stable identifier for the claiming tool, e.g. 'draw'.
* @returns {PointerLease|null} The lease to release with, or null if the
* pointer is already held — including by another instance of the same tool.
* @param {{onLost?: () => void}} [options] `onLost`: called once when a newer
* claim, here or on a bridged port, ends this lease; never when it is
* released. A tool turns itself off in it.
* @returns {PointerLease|null} The lease to release with, or null for an
* owner with no name.
*/
export function claimPointer(owner) {
export function claimPointer(owner, { onLost } = {}) {
const name = normalizeOwner(owner);
if (!name) return null;
if (currentLease !== null) return null;
currentLease = Object.freeze({ owner: name, id: nextLeaseId++ });
return currentLease;
const previous = currentLease;
const lease = Object.freeze({ owner: name, id: nextLeaseId++ });
currentLease = lease;
if (typeof onLost === 'function') lostHandlers.set(lease, onLost);
announce();
if (previous) tellLost(previous);
return lease;
}
/** Each bridged port hears who holds the pointer now. */
function announce() {
for (const bridge of [...bridges]) bridge.claimed(currentLease);
}
/** Tell the holder of an ended `lease`, once. */
function tellLost(lease) {
const onLost = lostHandlers.get(lease);
lostHandlers.delete(lease);
if (!onLost) return;
try {
onLost();
} catch (error) {
console.error('Pointer owner failed to let go', error);
}
}
/**
* Hold a lease on a renderer's input port for as long as a tool holds the
* pointer here, made afresh for each claim. A claim made on the port by
* anyone else ends the tool's lease here, and its holder is told; while that
* claim is out, `isPointerFree()` is false.
* @param {import('../render/contract/input').InputPort} port
* @returns {{lease: () => import('../render/contract/input').Lease|null, off: () => void}}
* `lease` is the port lease standing for the tool's, null while no tool
* here holds the pointer; `off` gives it back and stops bridging.
*/
export function bridgePointer(port) {
let held = null;
const bridge = {
claimed(lease) {
held?.release();
held = null;
if (!lease) return;
held = port.claimPointer(lease.owner, {
// Every press goes on to the port's other listeners; the dispatcher
// decides who hears it when it arrives.
grab: () => false,
// A claim on the port that is not this bridge's.
onLost: () => {
held = null;
if (currentLease !== lease) return;
currentLease = null;
announce();
tellLost(lease);
},
});
},
isFree: () => port.isPointerFree(),
};
bridges.add(bridge);
bridge.claimed(currentLease);
return {
lease: () => (held?.current ? held : null),
off() {
if (!bridges.delete(bridge)) return;
held?.release();
held = null;
},
};
}
/**
@@ -57,7 +142,9 @@ export function claimPointer(owner) {
*/
export function releasePointer(lease) {
if (!currentLease || !lease || lease.id !== currentLease.id) return false;
lostHandlers.delete(currentLease);
currentLease = null;
announce();
return true;
}
@@ -66,9 +153,14 @@ export function pointerOwner() {
return currentLease ? currentLease.owner : null;
}
/** @returns {boolean} True when no tool holds the pointer. */
/**
* @returns {boolean} True when no tool holds the pointer, here or through a
* claim on a bridged port.
*/
export function isPointerFree() {
return currentLease === null;
if (currentLease !== null) return false;
for (const bridge of bridges) if (!bridge.isFree()) return false;
return true;
}
/**
@@ -89,13 +181,15 @@ export function isLeaseCurrent(lease) {
}
/**
* Drop any claim. For tests and for application teardown, which cannot rely on
* a half-disposed tool to release its own lease.
* Drop any claim, telling no one. For tests and for application teardown,
* which cannot rely on a half-disposed tool to release its own lease.
* @returns {string|null} The owner that was holding it, if any.
*/
export function resetPointerOwnership() {
const previous = pointerOwner();
if (currentLease) lostHandlers.delete(currentLease);
currentLease = null;
announce();
return previous;
}
+156 -56
View File
@@ -11,7 +11,9 @@ import {
pointerOwner,
releasePointer,
resetPointerOwnership,
bridgePointer,
} from './inputOwnership.js';
import { createInputRouter } from '../render/input/router.js';
const ROOT = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
@@ -35,22 +37,61 @@ test('the pointer starts free and a claim hands back a lease', () => {
assert.equal(isLeaseCurrent(lease), true);
});
test('a claim is never stolen — not even by the same tool name', () => {
const first = claimPointer('draw');
assert.ok(first);
test('the newest claim takes over and the holder it replaces is told, once', () => {
const told = [];
const first = claimPointer('draw', { onLost: () => told.push('draw') });
const second = claimPointer('directions', {
onLost: () => told.push('directions'),
});
assert.ok(second, 'a second claim is not refused');
assert.deepEqual(told, ['draw']);
assert.equal(pointerOwner(), 'directions');
assert.equal(isLeaseCurrent(first), false);
assert.equal(isLeaseCurrent(second), true);
assert.equal(
releasePointer(first),
false,
'the old late release frees nothing',
);
assert.equal(pointerOwner(), 'directions');
assert.deepEqual(told, ['draw'], 'told once');
assert.equal(releasePointer(second), true);
assert.deepEqual(told, ['draw'], 'a holder that lets go is not told');
});
assert.equal(
claimPointer('directions'),
null,
'another tool must not displace it',
);
assert.equal(
claimPointer('draw'),
null,
'a SECOND instance of the same tool is a second owner, not a no-op',
);
assert.equal(pointerOwner(), 'draw');
assert.equal(isLeaseCurrent(first), true);
test('a second instance of the same tool takes over from the first', () => {
// An old instance mid-teardown and its replacement already running are two
// owners: the replacement wins, and the old one is told to turn off.
let lost = 0;
const old = claimPointer('draw', { onLost: () => (lost += 1) });
const live = claimPointer('draw');
assert.notEqual(live.id, old.id);
assert.equal(lost, 1);
assert.equal(isLeaseCurrent(live), true);
});
test('the holder is told after the new claim holds the pointer; its error stays its own', (t) => {
const errors = [];
t.mock.method(console, 'error', (...args) => errors.push(args));
let seen = null;
const first = claimPointer('draw', {
onLost: () => {
seen = { owner: pointerOwner(), current: isLeaseCurrent(first) };
throw new Error('onLost');
},
});
const second = claimPointer('directions');
assert.deepEqual(seen, { owner: 'directions', current: false });
assert.equal(isLeaseCurrent(second), true);
assert.equal(errors.length, 1);
});
test('reset tells no one', () => {
let lost = 0;
claimPointer('draw', { onLost: () => (lost += 1) });
resetPointerOwnership();
claimPointer('directions');
assert.equal(lost, 0);
});
test('a replaced instance cannot free its successor’s claim', () => {
@@ -109,62 +150,60 @@ test('reset reports who was holding it, for teardown', () => {
assert.equal(isLeaseCurrent(lease), false);
});
test('every scene click handler consults ownership before it picks', () => {
// This is the whole point of a shared contract: a new tool must not have to
// find and edit each of these. If a layer grows a click handler it has to
// appear here too.
const guarded = [
['src/data/trackingClickGesture.js', 'onClick(click, gesture);'],
['src/data/localGeojsonCore.js', 'viewer.scene.pick(click.position)'],
['src/data/cctvGizmo.js', 'pickGizmoPart(event.position)'],
['src/layers/alpr/presentation.js', 'viewer.scene.pick(click.position)'],
['src/layers/bikeshare/selection.js', 'viewer.scene.pick(click.position)'],
['src/layers/firms/selection.js', 'scene.pick(click.position)'],
test('pointer input, camera holds and the stock clicks go through the one dispatcher', () => {
// The dispatcher (src/input/dispatcher.js) applies the pointer claim once
// per event for every subscriber, so a new tool does not have to find and
// edit each layer. A layer that binds its own handler, writes the camera
// flag or takes the stock clicks itself steps around that contract.
const DISPATCHER = 'src/input/dispatcher.js';
// Each rule names the one other module it belongs in, if any.
const rules = [
[
'src/layers/installations/selection.js',
'viewer.scene.pick(click.position)',
],
['src/layers/launches/lifecycle.js', 'drillPick(movement.position'],
['src/layers/radio/interaction.js', 'pickedRadioStationAt(click.position)'],
[
'src/layers/satellites/interaction.js',
'viewer.scene.pick(click.position)',
/new\s+[\w.]*ScreenSpaceEventHandler\(/,
'binds its own ScreenSpaceEventHandler',
// The Cesium renderer's input port, the renderer's one handler.
['src/render/cesium/input.js'],
],
[
'src/layers/submarineCables/interaction.js',
'viewer.scene.pick(click.position)',
/\.enableInputs\s*=(?!=)/,
'writes enableInputs instead of suspendCamera()',
// The scene's camera-input holds, which own the flag; the Context
// card's previews turn it off in their own small scenes, which take
// no input at all.
['src/render/cesium/cameraInput.js', 'src/render/cesium/cardPreviews.js'],
],
[
'src/layers/vessels/selection.js',
'pickContact(viewer.scene, click.position)',
/(?:screenSpaceEventHandler|stockHandler)\??\.removeInputAction\(/,
'removes stock clicks instead of suppressStockClicks()',
// It runs the stock clicks itself; the viewer's factory drops the
// stock double-click before any input port exists.
['src/render/cesium/input.js', 'src/render/cesium/applicationViewer.js'],
],
];
for (const [file, firstPick] of guarded) {
const walk = (dir) =>
fs
.readdirSync(path.join(ROOT, dir), { withFileTypes: true })
.flatMap((entry) => {
const rel = path.join(dir, entry.name);
if (entry.isDirectory()) return walk(rel);
return entry.name.endsWith('.js') ? [rel] : [];
});
const offenders = [];
for (const file of walk('src')) {
if (file === DISPATCHER) continue;
const source = read(file);
assert.match(
source,
/import \{ isPointerFree \} from '[^']*inputOwnership\.js';/,
`${file} must consult the shared pointer claim`,
);
const guardAt = source.indexOf('if (!isPointerFree()) return;');
const pickAt = source.indexOf(firstPick);
assert.ok(guardAt >= 0, `${file} is missing the guard`);
assert.ok(
pickAt >= 0,
`${file}: could not find its pick call (${firstPick})`,
);
assert.ok(
guardAt < pickAt,
`${file} must yield before it picks, not after`,
);
for (const [pattern, what, allowed] of rules)
if (!allowed.includes(file) && pattern.test(source))
offenders.push(`${file} ${what}`);
}
assert.deepEqual(offenders, []);
});
test('ambient selection handlers never claim the pointer themselves', () => {
// Claiming from a selection handler would deadlock every other layer the
// moment a user clicked anything. Only tools claim.
for (const file of [
'src/data/trackingClickGesture.js',
'src/input/dispatcher.js',
'src/data/localGeojsonCore.js',
'src/data/cctvGizmo.js',
'src/layers/vessels/selection.js',
@@ -177,3 +216,64 @@ test('ambient selection handlers never claim the pointer themselves', () => {
);
}
});
/** A renderer's input port, as the contract's router keeps it. */
const portOf = () =>
createInputRouter({
report: (error) => {
throw error;
},
suspendCamera: () => () => {},
}).port;
test('a bridged port holds a lease for as long as a tool holds the pointer', () => {
const port = portOf();
const bridge = bridgePointer(port);
assert.equal(bridge.lease(), null);
const lease = claimPointer('draw');
assert.equal(port.isPointerFree(), false, 'the port is taken too');
assert.equal(bridge.lease().owner, 'draw');
assert.equal(bridge.lease().current, true);
const next = claimPointer('directions');
assert.equal(bridge.lease().owner, 'directions');
releasePointer(lease);
assert.equal(port.isPointerFree(), false, 'a stale release frees nothing');
releasePointer(next);
assert.equal(port.isPointerFree(), true);
assert.equal(bridge.lease(), null);
bridge.off();
});
test('a claim made on the port takes over from the page’s tool, and back', () => {
const port = portOf();
const bridge = bridgePointer(port);
const told = [];
const page = claimPointer('draw', { onLost: () => told.push('draw') });
const other = port.claimPointer('other', {
onLost: () => told.push('other'),
});
assert.deepEqual(told, ['draw'], 'the page’s tool is told');
assert.equal(isLeaseCurrent(page), false);
assert.equal(
isPointerFree(),
false,
'the port’s own claim holds the pointer',
);
assert.equal(bridge.lease(), null);
claimPointer('directions');
assert.deepEqual(told, ['draw', 'other'], 'a newer page claim takes it back');
assert.equal(other.current, false);
assert.equal(bridge.lease().owner, 'directions');
bridge.off();
});
test('a port bridged while a tool holds the pointer takes its lease at once; off gives it back', () => {
const lease = claimPointer('draw');
const port = portOf();
const bridge = bridgePointer(port);
assert.equal(port.isPointerFree(), false);
bridge.off();
assert.equal(port.isPointerFree(), true);
assert.equal(isLeaseCurrent(lease), true, 'the page claim stands');
assert.equal(isPointerFree(), false);
});
Loaded 100 of 2063 files, more files were not shown because too many files have changed in this diff. Show more