mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-23 03:32:19 +00:00
Merge main into codex/fix-cctv-session-admission
Resolve the conflicts by keeping main's keyless CCTV gate, which already refuses cross-site requests on every /api/cctv route and keeps the routes reachable behind a reverse proxy, instead of the strict gate on /media/. Keep the per-request client id the lease calls use, and both sides of the CURRENT-STATE paragraphs and the media tests.
This commit is contained in:
commit
90e464eb5a
4310 files changed
+635935
-70111
No files matched your search
+166
-13
@@ -150,17 +150,60 @@ export function polygonsContain(polygons, lat, lon) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether polygons contain a point. A part whose outer ring crosses the
|
||||
* antimeridian ([179.99, …], [-179.99, …]) is read contiguously in its own
|
||||
* longitude frame, with the point moved into that frame; every other part,
|
||||
* including one genuinely wider than 180°, is tested as stored. Crossing is
|
||||
* read from an edge jumping more than 180°, which assumes densely noded rings
|
||||
* (OSM, Nominatim, tiles); a ring that is both wider than 180° and crossing, or
|
||||
* a non-crossing ring with a single edge over 180°, is not supported.
|
||||
*/
|
||||
export function containsAnchor(polygons, lat, lon) {
|
||||
if (!Number.isFinite(lon)) return false;
|
||||
for (const part of polygons || []) {
|
||||
const outer = part?.[0];
|
||||
if (!Array.isArray(outer) || !outer.length) continue;
|
||||
const reference = outer[0][0];
|
||||
const shift = (x) => x - 360 * Math.round((x - reference) / 360);
|
||||
const span = (ring, f) => {
|
||||
let west = Infinity;
|
||||
let east = -Infinity;
|
||||
for (const [x] of ring) {
|
||||
west = Math.min(west, f(x));
|
||||
east = Math.max(east, f(x));
|
||||
}
|
||||
return east - west;
|
||||
};
|
||||
// An edge jumping more than 180° wraps the line; a polar ring whose
|
||||
// edges run along ±180 collapses when reframed and is read as stored.
|
||||
const jumps = outer.some(
|
||||
([x], i) => i > 0 && Math.abs(x - outer[i - 1][0]) > 180,
|
||||
);
|
||||
const framedSpan = jumps ? span(outer, shift) : 0;
|
||||
const crosses = framedSpan > 0 && framedSpan < 180;
|
||||
const framed = crosses
|
||||
? part.map((ring) => ring.map(([x, y]) => [shift(x), y]))
|
||||
: part;
|
||||
if (polygonsContain([framed], lat, crosses ? shift(lon) : lon)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* A unit's geometry, decoded on first use. Longitudes are unwrapped around
|
||||
* the largest part for the box so units cut at the antimeridian (Alaska,
|
||||
* Chukotka) get a box on the right side of the globe.
|
||||
* Chukotka) get a box on the right side of the globe. An entry from another
|
||||
* encoding supplies `decode()` returning the same `[outer, ...holes][]`.
|
||||
*/
|
||||
function geometryOf(entry) {
|
||||
export function geometryOf(entry) {
|
||||
if (entry.geometry) return entry.geometry;
|
||||
const decimals = entry.feature.d ?? entry.decimals;
|
||||
const polygons = entry.feature.polygons.map((poly) =>
|
||||
poly.map((ring) => decodeRing(ring, decimals)),
|
||||
);
|
||||
const polygons = entry.decode
|
||||
? entry.decode()
|
||||
: entry.feature.polygons.map((poly) =>
|
||||
poly.map((ring) => decodeRing(ring, decimals)),
|
||||
);
|
||||
const ref = polygons[0]?.[0]?.[0]?.[0] ?? 0;
|
||||
let west = Infinity;
|
||||
let south = Infinity;
|
||||
@@ -178,7 +221,7 @@ function geometryOf(entry) {
|
||||
if (lat > north) north = lat;
|
||||
}
|
||||
}
|
||||
const label = entry.feature.label
|
||||
const label = Array.isArray(entry.feature.label)
|
||||
? { lon: entry.feature.label[0], lat: entry.feature.label[1] }
|
||||
: ringCentroid(polygons[0][0]);
|
||||
entry.geometry = {
|
||||
@@ -208,7 +251,7 @@ function ringCentroid(ring) {
|
||||
}
|
||||
|
||||
/** Km from a point to a unit's box (0 inside it). */
|
||||
function boxDistanceKm(bbox, lat, lon) {
|
||||
export function boxDistanceKm(bbox, lat, lon) {
|
||||
const [west, south, east, north] = bbox;
|
||||
const mid = (west + east) / 2;
|
||||
const x = lon - 360 * Math.round((lon - mid) / 360);
|
||||
@@ -378,6 +421,49 @@ const COUNTRY_TARGET_ALIASES = new Map([
|
||||
['drc', 'democratic republic of the congo'],
|
||||
]);
|
||||
|
||||
/**
|
||||
* Country aliases that are another name for the very same unit. "Great
|
||||
* Britain" and "Britain" are islands, "America" is also two continents and
|
||||
* "Korea" two countries, so those find a country without naming it.
|
||||
*/
|
||||
const COUNTRY_IDENTITY_ALIASES = new Set([
|
||||
'usa',
|
||||
'us',
|
||||
'u s',
|
||||
'u s a',
|
||||
'united states',
|
||||
'uk',
|
||||
'u k',
|
||||
'russian federation',
|
||||
'czechia',
|
||||
'tanzania',
|
||||
'drc',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The unit an ask names in the matcher's own terms, when its words differ
|
||||
* from the unit's name: "State of Texas" names Texas at admin level 1, and
|
||||
* "USA" or "Country of USA" names United States of America. Null when the
|
||||
* ask is just a name. Names are folded with `normalizeAdminName`.
|
||||
* @param {string} text
|
||||
* @returns {{name: string, level: 'country'|'admin1'}|null}
|
||||
*/
|
||||
export function adminQueryIdentity(text) {
|
||||
const parsed = parseAdminQuery(text);
|
||||
if (!parsed?.name) return null;
|
||||
if (parsed.kind === 'state' && parsed.form === 'prefix')
|
||||
return { name: parsed.name, level: 'admin1' };
|
||||
if (parsed.kind !== 'country' && parsed.kind !== 'any') return null;
|
||||
if (COUNTRY_IDENTITY_ALIASES.has(parsed.name))
|
||||
return {
|
||||
name: COUNTRY_TARGET_ALIASES.get(parsed.name),
|
||||
level: 'country',
|
||||
};
|
||||
return parsed.kind === 'country'
|
||||
? { name: parsed.name, level: 'country' }
|
||||
: null;
|
||||
}
|
||||
|
||||
const COUNTRY_ALIASES = new Map([
|
||||
...COUNTRY_TARGET_ALIASES,
|
||||
['england', 'united kingdom'],
|
||||
@@ -399,8 +485,8 @@ const COUNTY_WORDS = [
|
||||
];
|
||||
const COUNTY_WORD_RE = new RegExp(`\\b(${COUNTY_WORDS.join('|')})\\b`);
|
||||
const STATE_PREFIX_RE =
|
||||
/^(?:free state|state|commonwealth|province|territory|prefecture|region|land|canton|department) of (.+)$/;
|
||||
const STATE_SUFFIX_RE = /^(.+) (?:state|province|prefecture|territory)$/;
|
||||
/^(free state|state|commonwealth|province|territory|prefecture|region|land|canton|department) of (.+)$/;
|
||||
const STATE_SUFFIX_RE = /^(.+) (state|province|prefecture|territory)$/;
|
||||
|
||||
/**
|
||||
* Split an ask into what it names and how.
|
||||
@@ -461,14 +547,17 @@ export function parseAdminQuery(text) {
|
||||
if (prefix)
|
||||
return {
|
||||
kind: 'state',
|
||||
name: prefix[1],
|
||||
name: prefix[2],
|
||||
qualifiers,
|
||||
postal: null,
|
||||
countyWord: null,
|
||||
full: head,
|
||||
form: 'prefix',
|
||||
adminType: prefix[1],
|
||||
};
|
||||
const suffix = STATE_SUFFIX_RE.exec(head);
|
||||
// South Africa's canonical province name is literally "Free State"; do not
|
||||
// strip its final word as though the ask explicitly named an admin type.
|
||||
const suffix = head === 'free state' ? null : STATE_SUFFIX_RE.exec(head);
|
||||
if (suffix)
|
||||
return {
|
||||
kind: 'state',
|
||||
@@ -478,6 +567,7 @@ export function parseAdminQuery(text) {
|
||||
countyWord: null,
|
||||
full: head,
|
||||
form: 'suffix',
|
||||
adminType: suffix[2],
|
||||
};
|
||||
return {
|
||||
kind: 'any',
|
||||
@@ -489,6 +579,30 @@ export function parseAdminQuery(text) {
|
||||
};
|
||||
}
|
||||
|
||||
/** Explicit wording is stronger than a stale same-name geometry. */
|
||||
function explicitStateTypeFits(entry, parsed) {
|
||||
if (!parsed.adminType) return true;
|
||||
const words = new Set(
|
||||
normalizeAdminName(entry.feature?.type)
|
||||
.split(/[^a-z]+/)
|
||||
.filter(Boolean),
|
||||
);
|
||||
const accepted =
|
||||
{
|
||||
'free state': ['state'],
|
||||
state: ['state'],
|
||||
commonwealth: ['state'],
|
||||
province: ['province'],
|
||||
territory: ['territory'],
|
||||
prefecture: ['prefecture'],
|
||||
region: ['region'],
|
||||
land: ['state'],
|
||||
canton: ['canton'],
|
||||
department: ['department', 'departamento'],
|
||||
}[parsed.adminType] || [];
|
||||
return accepted.some((word) => words.has(word));
|
||||
}
|
||||
|
||||
/** A qualifier names the unit's country ("Bavaria, Germany") or the unit
|
||||
* itself ("Washington, DC"). */
|
||||
function qualifierMatches(entry, qualifier) {
|
||||
@@ -505,7 +619,7 @@ function qualifierMatches(entry, qualifier) {
|
||||
* Rank candidates: a unit containing `near` first, then the match tier,
|
||||
* then distance from `near`, then larger area. Returns the ranked list.
|
||||
*/
|
||||
function rank(candidates, near) {
|
||||
export function rank(candidates, near) {
|
||||
const hasNear = Number.isFinite(near?.lat) && Number.isFinite(near?.lon);
|
||||
const scored = candidates.map(({ entry, tier }) => {
|
||||
const geometry = geometryOf(entry);
|
||||
@@ -626,6 +740,10 @@ async function stateCandidates(parsed, { allowAmbiguous = false } = {}) {
|
||||
list = list.filter((i) =>
|
||||
parsed.qualifiers.every((q) => qualifierMatches(i.entry, q)),
|
||||
);
|
||||
// Preserve explicit identity at the selector seam. In particular,
|
||||
// "Bagmati Province" must not select Natural Earth's historical NP-BA
|
||||
// Bagmati Zone merely because the point and normalized name overlap.
|
||||
list = list.filter((i) => explicitStateTypeFits(i.entry, parsed));
|
||||
if (allowAmbiguous) return list;
|
||||
// A bare name answers alone only for a prominent unit — a US state, a
|
||||
// Canadian province, Bavaria — never a French département, an English
|
||||
@@ -721,6 +839,35 @@ export async function findAdminArea(query, { near = null } = {}) {
|
||||
return toResult(ranked[0], candidates.length);
|
||||
}
|
||||
|
||||
/**
|
||||
* Every prominent unit an ask's words could mean — countries, and states or
|
||||
* provinces that would answer a bare name (see `stateCandidates`) — for a
|
||||
* caller that asks the user which one ("Georgia", "Punjab") instead of
|
||||
* letting the camera decide. Qualifiers narrow the list as in
|
||||
* `findAdminArea`; minor units ("Kent", "Santa Barbara") are left out.
|
||||
*
|
||||
* @param {string} query
|
||||
* @returns {Promise<AdminArea[]>} Largest first; empty when none.
|
||||
*/
|
||||
export async function findAdminCandidates(query) {
|
||||
const parsed = parseAdminQuery(query);
|
||||
if (!parsed?.name || parsed.kind === 'county') return [];
|
||||
const prominent = ({ entry }) =>
|
||||
entry.kind === 'country' ||
|
||||
(entry.feature.rank ?? Infinity) <= BARE_NAME_MAX_RANK ||
|
||||
Boolean(entry.feature.cityState);
|
||||
const candidates = [
|
||||
...(await countryCandidates(parsed)),
|
||||
...(parsed.kind === 'country'
|
||||
? []
|
||||
: await stateCandidates(parsed, { allowAmbiguous: true })),
|
||||
].filter(prominent);
|
||||
const seen = new Set();
|
||||
return rank(candidates, null)
|
||||
.filter(({ entry }) => !seen.has(entry) && seen.add(entry))
|
||||
.map((scored) => toResult(scored, candidates.length));
|
||||
}
|
||||
|
||||
/**
|
||||
* Geocoder-confirmed lookup: the geocoder typed a country, state or
|
||||
* county, so the unit must carry one of `names` AND contain the geocoded
|
||||
@@ -738,6 +885,12 @@ export async function findAdminAreaAt(names, lat, lon, scope) {
|
||||
.map(parseAdminQuery)
|
||||
.filter((p) => p?.name);
|
||||
if (!parsedList.length) return null;
|
||||
// If the ask explicitly names an admin type, do not let the geocoder's
|
||||
// untyped alias reopen an incompatible historical same-name boundary.
|
||||
const explicitStates = parsedList.filter(
|
||||
(parsed) => parsed.kind === 'state' && parsed.adminType,
|
||||
);
|
||||
const stateParses = explicitStates.length ? explicitStates : parsedList;
|
||||
const containing = (items) => {
|
||||
const out = [];
|
||||
for (const item of items)
|
||||
@@ -782,7 +935,7 @@ export async function findAdminAreaAt(names, lat, lon, scope) {
|
||||
return toResult(rank(found, { lat, lon })[0], found.length);
|
||||
}
|
||||
const states = [];
|
||||
for (const parsed of parsedList)
|
||||
for (const parsed of stateParses)
|
||||
states.push(
|
||||
...(await stateCandidates(
|
||||
{ ...parsed, qualifiers: [] },
|
||||
|
||||
@@ -7,6 +7,7 @@ import {
|
||||
decodeRing,
|
||||
findAdminArea,
|
||||
findAdminAreaAt,
|
||||
findAdminCandidates,
|
||||
normalizeAdminName,
|
||||
packLoads,
|
||||
parseAdminQuery,
|
||||
@@ -225,6 +226,29 @@ test('geocoder-confirmed lookup: the named unit that contains the point', async
|
||||
assert.equal(await findAdminAreaAt(['Georgia'], 41.7, 44.8, 'state'), null);
|
||||
const newYork = await findAdminAreaAt(['New York'], 42.9, -75.5, 'state');
|
||||
assert.equal(newYork?.id, 'US-NY');
|
||||
assert.equal(
|
||||
(
|
||||
await findAdminAreaAt(
|
||||
['Ontario Province', 'Ontario'],
|
||||
43.6532,
|
||||
-79.3832,
|
||||
'state',
|
||||
)
|
||||
)?.id,
|
||||
'CA-ON',
|
||||
);
|
||||
// Natural Earth still carries the historical NP-BA Bagmati Zone. An ask
|
||||
// for today's province must not silently select that incompatible geometry.
|
||||
assert.equal(
|
||||
await findAdminAreaAt(
|
||||
['Bagmati Province', 'Bagmati'],
|
||||
27.7172,
|
||||
85.324,
|
||||
'state',
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.deepEqual(await findAdminCandidates('Bagmati Province'), []);
|
||||
// A county the geocoder typed, named without the county word.
|
||||
const travis = await findAdminAreaAt(
|
||||
['Travis', 'Travis County'],
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { readAdsbVerticalRateFpm } from '../sources/adsbFields.js';
|
||||
|
||||
const KNOT_TO_MPS = 0.514444;
|
||||
const FOOT_TO_M = 0.3048;
|
||||
const FPM_TO_MPS = 0.00508;
|
||||
@@ -61,9 +63,12 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
|
||||
const barometricFeet = onGround ? null : finiteNumber(aircraft?.alt_baro);
|
||||
const geometricFeet = finiteNumber(aircraft?.alt_geom);
|
||||
const groundSpeedKnots = finiteNumber(aircraft?.gs);
|
||||
const verticalRateFpm =
|
||||
finiteNumber(aircraft?.baro_rate) ?? finiteNumber(aircraft?.geom_rate);
|
||||
const track = finiteNumber(aircraft?.track);
|
||||
const verticalRateFpm = readAdsbVerticalRateFpm(aircraft);
|
||||
// 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,
|
||||
@@ -93,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);
|
||||
@@ -106,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;
|
||||
@@ -120,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 } : {}),
|
||||
};
|
||||
}
|
||||
@@ -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
@@ -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';
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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
@@ -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
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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
@@ -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);
|
||||
});
|
||||
@@ -0,0 +1,45 @@
|
||||
/**
|
||||
* Lighting options shared by every aircraft 3D model (Flights, Military
|
||||
* Flights, Local ADS-B).
|
||||
*
|
||||
* Cesium gives each Model a dynamic environment map: it renders the sky around
|
||||
* 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. 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;
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
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,
|
||||
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 the renderer's dynamic
|
||||
* environment map (a sky render and GPU readback per model).
|
||||
*/
|
||||
const SOURCES = [
|
||||
{
|
||||
name: 'flights',
|
||||
source: readLayerSource(new URL('./flights.js', import.meta.url)),
|
||||
},
|
||||
{
|
||||
name: 'militaryFlights',
|
||||
source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)),
|
||||
},
|
||||
];
|
||||
|
||||
test('the shared option turns the dynamic environment map off', () => {
|
||||
assert.deepEqual({ ...AIRCRAFT_ENVIRONMENT_MAP_OPTIONS }, { enabled: false });
|
||||
assert.ok(Object.isFrozen(AIRCRAFT_ENVIRONMENT_MAP_OPTIONS));
|
||||
});
|
||||
|
||||
for (const { name, source } of SOURCES) {
|
||||
test(`${name}: every drawn aircraft model skips the dynamic environment map`, () => {
|
||||
// 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 });
|
||||
});
|
||||
@@ -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
@@ -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
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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);
|
||||
|
||||
+1083
-353
File diff suppressed because it is too large.
Load diff
@@ -215,7 +215,7 @@ export const AIS_RECOGNIZED_MESSAGE_TYPES = Object.freeze(
|
||||
* @param {Object} body
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function aisEnvelopeMmsi(envelope, body = {}) {
|
||||
function aisEnvelopeMmsi(envelope, body = {}) {
|
||||
const metadata = envelope?.MetaData || envelope?.Metadata || {};
|
||||
const raw = metadata.MMSI ?? body.UserID ?? body.UserId ?? body.Mmsi;
|
||||
if (raw === null || raw === undefined) return null;
|
||||
|
||||
@@ -1,8 +1,10 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
AISSTREAM_STALE_MS,
|
||||
aisStreamRows,
|
||||
ingestAisStreamEnvelope,
|
||||
readAisTrack,
|
||||
} from '../../server/providers/vessels/ais-store.js';
|
||||
|
||||
// ITU-R M.1371 encodes speed over ground in 0.1-knot units and course over
|
||||
@@ -63,3 +65,348 @@ test('the fastest encodable reading below the unavailable code is kept', () => {
|
||||
assert.equal(row.speed, 102.2);
|
||||
assert.equal(row.course, 359.9);
|
||||
});
|
||||
|
||||
test('a static data report keeps the motion and fix time of a tracked vessel', () => {
|
||||
ingestAisStreamEnvelope(
|
||||
positionReport('244690000', { Sog: 12.4, Cog: 86.7, TrueHeading: 87 }),
|
||||
);
|
||||
// AISStream's MetaData carries the last known position on every message,
|
||||
// static data included.
|
||||
assert.equal(
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: 'ShipStaticData',
|
||||
Message: {
|
||||
ShipStaticData: {
|
||||
UserID: 244690000,
|
||||
Name: 'EXAMPLE VESSEL',
|
||||
Type: 70,
|
||||
Destination: 'ROTTERDAM',
|
||||
ImoNumber: 9876543,
|
||||
},
|
||||
},
|
||||
MetaData: {
|
||||
MMSI: '244690000',
|
||||
latitude: 53.40879,
|
||||
longitude: 6.19741,
|
||||
time_utc: '2026-09-17 20:05:00.000000000 +0000 UTC',
|
||||
},
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const row = rowFor('244690000');
|
||||
assert.equal(row.speed, 12.4);
|
||||
assert.equal(row.course, 86.7);
|
||||
assert.equal(row.heading, 87);
|
||||
assert.equal(row.last_position_UTC, '2026-09-17T20:00:00.000Z');
|
||||
assert.equal(row.destination, 'ROTTERDAM');
|
||||
assert.equal(row.imo, '9876543');
|
||||
});
|
||||
|
||||
// AISStream carries both Class B parts; the unused part has Valid: false.
|
||||
const classBStatic = (part, value) => ({
|
||||
MessageID: 24,
|
||||
RepeatIndicator: 0,
|
||||
Valid: true,
|
||||
Reserved: 0,
|
||||
PartNumber: part === 'B',
|
||||
ReportA: { Valid: part === 'A', Name: part === 'A' ? value : '' },
|
||||
ReportB: {
|
||||
Valid: part === 'B',
|
||||
ShipType: part === 'B' ? value : 0,
|
||||
VendorIDName: '',
|
||||
VenderIDModel: 0,
|
||||
VenderIDSerial: 0,
|
||||
CallSign: '',
|
||||
Dimension: { A: 0, B: 0, C: 0, D: 0 },
|
||||
FixType: 0,
|
||||
Spare: 0,
|
||||
},
|
||||
});
|
||||
|
||||
for (const [index, scenario] of [
|
||||
{
|
||||
type: 'ShipStaticData',
|
||||
initial: [
|
||||
{
|
||||
Name: 'OLD VESSEL',
|
||||
Type: 70,
|
||||
Destination: 'ROTTERDAM',
|
||||
ImoNumber: 9876543,
|
||||
},
|
||||
],
|
||||
updates: [
|
||||
{
|
||||
Name: 'NEW VESSEL',
|
||||
Type: 80,
|
||||
Destination: 'HAMBURG',
|
||||
ImoNumber: 9876544,
|
||||
},
|
||||
],
|
||||
empty: { Name: ' ', Type: 0, Destination: '', ImoNumber: 0 },
|
||||
expected: {
|
||||
name: 'NEW VESSEL',
|
||||
type: '80',
|
||||
destination: 'HAMBURG',
|
||||
imo: '9876544',
|
||||
},
|
||||
},
|
||||
{
|
||||
type: 'StaticDataReport',
|
||||
initial: [classBStatic('A', 'OLD VESSEL'), classBStatic('B', 36)],
|
||||
updates: [classBStatic('A', 'NEW VESSEL'), classBStatic('B', 37)],
|
||||
empty: classBStatic('A', ''),
|
||||
expected: { name: 'NEW VESSEL', type: '37', destination: '', imo: '' },
|
||||
},
|
||||
].entries()) {
|
||||
test(`${scenario.type} replaces static fields without inventing a position fix`, (t) => {
|
||||
const mmsi = String(244690100 + index);
|
||||
const start = Date.parse('2026-09-17T20:00:00Z');
|
||||
let now = start;
|
||||
t.mock.method(Date, 'now', () => now);
|
||||
const position = (
|
||||
lat,
|
||||
body = { Sog: 12.4, Cog: 86.7, TrueHeading: 87 },
|
||||
) => {
|
||||
const envelope = positionReport(mmsi, body);
|
||||
Object.assign(envelope.MetaData, {
|
||||
latitude: lat,
|
||||
time_utc: new Date(now).toISOString(),
|
||||
});
|
||||
return ingestAisStreamEnvelope(envelope);
|
||||
};
|
||||
const sendStatic = (body) =>
|
||||
ingestAisStreamEnvelope({
|
||||
MessageType: scenario.type,
|
||||
Message: { [scenario.type]: { UserID: Number(mmsi), ...body } },
|
||||
MetaData: {
|
||||
MMSI: mmsi,
|
||||
ShipName: 'STALE HEADER',
|
||||
latitude: 54,
|
||||
longitude: 7,
|
||||
time_utc: new Date(now).toISOString(),
|
||||
},
|
||||
});
|
||||
position(53.40879);
|
||||
for (const body of scenario.initial) assert.equal(sendStatic(body), true);
|
||||
now += 60_000;
|
||||
position(53.41879);
|
||||
const before = rowFor(mmsi);
|
||||
const track = readAisTrack(mmsi);
|
||||
assert.equal(track.length, 2);
|
||||
|
||||
now += 5 * 60_000;
|
||||
for (const body of scenario.updates) assert.equal(sendStatic(body), true);
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
assert.deepEqual(readAisTrack(mmsi), track);
|
||||
|
||||
// Empty or omitted static fields must not erase known metadata, including
|
||||
// the cached values used when the next actual position arrives.
|
||||
assert.equal(sendStatic(scenario.empty), true);
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
assert.deepEqual(readAisTrack(mmsi), track);
|
||||
if (scenario.type === 'StaticDataReport') {
|
||||
sendStatic({
|
||||
...classBStatic('A', ''),
|
||||
ReportA: { Valid: false, Name: 'INVALID NAME' },
|
||||
ReportB: { ...classBStatic('B', 99).ReportB, Valid: false },
|
||||
});
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, ...scenario.expected });
|
||||
}
|
||||
now = start + 60_000 + AISSTREAM_STALE_MS + 1;
|
||||
assert.equal(
|
||||
rowFor(mmsi),
|
||||
undefined,
|
||||
'static traffic must not renew position freshness',
|
||||
);
|
||||
position(53.42879, { Sog: 0, Cog: 0, TrueHeading: 0 });
|
||||
const next = rowFor(mmsi);
|
||||
for (const [key, value] of Object.entries(scenario.expected))
|
||||
assert.equal(next[key], value, key);
|
||||
assert.equal(next.speed, 0);
|
||||
assert.equal(next.course, 0);
|
||||
assert.equal(next.heading, 0);
|
||||
assert.equal(next.last_position_epoch, Math.floor(now / 1000));
|
||||
assert.equal(readAisTrack(mmsi).length, 3);
|
||||
});
|
||||
}
|
||||
|
||||
test('partial static data keeps newer live metadata ahead of the old static cache', () => {
|
||||
const mmsi = '244690200';
|
||||
const staticReport = (body) => ({
|
||||
MessageType: 'ShipStaticData',
|
||||
Message: { ShipStaticData: { UserID: Number(mmsi), ...body } },
|
||||
MetaData: { MMSI: mmsi },
|
||||
});
|
||||
ingestAisStreamEnvelope(staticReport({ Name: 'OLD VESSEL', Type: 70 }));
|
||||
const extended = positionReport(mmsi, {});
|
||||
extended.MessageType = 'ExtendedClassBPositionReport';
|
||||
extended.Message = {
|
||||
ExtendedClassBPositionReport: {
|
||||
UserID: Number(mmsi),
|
||||
Type: 80,
|
||||
Sog: 12,
|
||||
Cog: 86,
|
||||
},
|
||||
};
|
||||
extended.MetaData.ShipName = 'NEW VESSEL';
|
||||
ingestAisStreamEnvelope(extended);
|
||||
const before = rowFor(mmsi);
|
||||
ingestAisStreamEnvelope(staticReport({ Destination: 'HAMBURG' }));
|
||||
assert.deepEqual(rowFor(mmsi), { ...before, destination: 'HAMBURG' });
|
||||
ingestAisStreamEnvelope(positionReport(mmsi, { Sog: 12, Cog: 86 }));
|
||||
assert.equal(rowFor(mmsi).name, 'NEW VESSEL');
|
||||
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);
|
||||
});
|
||||
+1
-21
@@ -46,28 +46,8 @@ export const AIS_WATCHDOG_DEFAULTS = Object.freeze({
|
||||
authProbeMs: 3_600_000,
|
||||
});
|
||||
|
||||
/**
|
||||
* Statuses reported to the browser. 'missing-key' and 'unsupported' keep their
|
||||
* pre-watchdog meaning so a keyless install still reads as "feature off".
|
||||
*/
|
||||
export const AIS_WATCHDOG_STATUSES = Object.freeze([
|
||||
'idle',
|
||||
'missing-key',
|
||||
'unsupported',
|
||||
'connecting',
|
||||
'live',
|
||||
'stale',
|
||||
'reconnecting',
|
||||
'down',
|
||||
'auth-failed',
|
||||
]);
|
||||
|
||||
/** Failure classes. Only 'transport' is allowed to walk the fast ladder. */
|
||||
export const AIS_FAILURE_KINDS = Object.freeze([
|
||||
'transport',
|
||||
'auth',
|
||||
'rate-limit',
|
||||
]);
|
||||
const AIS_FAILURE_KINDS = Object.freeze(['transport', 'auth', 'rate-limit']);
|
||||
|
||||
/** Statuses that must not flip back to a hopeful 'connecting' on a retry. */
|
||||
const QUIET_TERMINAL = new Set(['down', 'auth-failed']);
|
||||
|
||||
+176
-122
@@ -3,12 +3,19 @@
|
||||
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,
|
||||
} from './alprCameras.js';
|
||||
import { createAlprTileSource } from '../layers/alpr/source.js';
|
||||
import { DATA_CREDITS } from './dataCredits.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import { shownEntityLabel } from '../voice/speech.js';
|
||||
import {
|
||||
clearSelectedEntityContextForLayer,
|
||||
getContextStore,
|
||||
@@ -29,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({
|
||||
@@ -306,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: {
|
||||
@@ -331,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 {
|
||||
@@ -353,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;
|
||||
},
|
||||
@@ -372,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() {
|
||||
@@ -438,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',
|
||||
);
|
||||
@@ -473,6 +505,29 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
|
||||
}
|
||||
});
|
||||
|
||||
// The voice model reads the label as data; the voice card translates it.
|
||||
test('the camera label stays English data in a translated interface', async () => {
|
||||
const h = cameraHarness();
|
||||
try {
|
||||
setLocale('ru');
|
||||
h.setFetch(async () =>
|
||||
cameraResponse([
|
||||
cameraNode(42, { tags: { 'surveillance:type': 'ALPR' } }),
|
||||
]),
|
||||
);
|
||||
await alprCamerasLayer.update();
|
||||
h.click(h.markers()[0].id);
|
||||
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
|
||||
assert.equal(
|
||||
shownEntityLabel(getSelectedEntityContext().label),
|
||||
'Камера ALPR',
|
||||
);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
h.restore();
|
||||
}
|
||||
});
|
||||
|
||||
test('invalid OSM ids and out-of-range coordinates never become camera entities', () => {
|
||||
for (const id of [undefined, null, 0, -1, 1.5, '42', NaN])
|
||||
assert.equal(normalizeAlprNode(cameraNode(id, { id })), null);
|
||||
@@ -498,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();
|
||||
@@ -557,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();
|
||||
}
|
||||
@@ -649,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();
|
||||
}
|
||||
@@ -665,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();
|
||||
@@ -725,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']);
|
||||
@@ -772,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 () =>
|
||||
@@ -786,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(
|
||||
@@ -796,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);
|
||||
@@ -834,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() {} },
|
||||
@@ -847,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() {},
|
||||
},
|
||||
@@ -893,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();
|
||||
@@ -912,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 = {
|
||||
@@ -932,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() {},
|
||||
},
|
||||
@@ -953,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 {
|
||||
@@ -1036,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();
|
||||
@@ -1068,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 {
|
||||
@@ -1131,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 {
|
||||
@@ -1149,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);
|
||||
}
|
||||
@@ -1165,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');
|
||||
@@ -1210,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);
|
||||
@@ -1360,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(
|
||||
@@ -1379,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,
|
||||
@@ -1408,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() {},
|
||||
},
|
||||
@@ -1417,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 {
|
||||
@@ -1463,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(
|
||||
@@ -1476,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',
|
||||
);
|
||||
@@ -1486,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');
|
||||
});
|
||||
+233
-110
@@ -18,7 +18,11 @@
|
||||
*
|
||||
* Providers (injected — keeps the engine pure and node-testable):
|
||||
* getRecords(layerKey) → Array<record> (layer accessor snapshot)
|
||||
* resolveRegionRing(name, signal?) → Promise<{ring, name}|{error:'region-timeout'}|null>
|
||||
* resolveRegionRing(name, {signal}?) → Promise<{name, geometry|ring, prepared?, source?}
|
||||
* |{error:'region-timeout'}|{needsClarification, candidates}|null>
|
||||
* (geometry = MultiPolygon coordinates; islands and holes all count)
|
||||
* resolveAreaScope(scope) → Promise<{ok:true, area:{areaId, name, prepared,
|
||||
* source, approximate}}|{ok:false, code, error}> (area/drawn/annotation)
|
||||
* getViewContext() → {lat, lon, viewRadiusKm, bounds?} (camera-derived)
|
||||
*
|
||||
* @module data/analystEngine
|
||||
@@ -26,6 +30,7 @@
|
||||
|
||||
import { feedProvenanceEnvelope } from './layerSnapshot.js';
|
||||
import { pointInRing } from './naturalEarthRegions.js';
|
||||
import { pointInPreparedArea, prepareArea } from './areaGeometry.js';
|
||||
import { VOICE_LAYER_MANIFEST, voiceLayer } from '../voice/layerManifest.js';
|
||||
import { greatCircleKm } from '../geoDistance.js';
|
||||
|
||||
@@ -62,11 +67,14 @@ const COMMON_FIELDS = Object.freeze(['id', 'lat', 'lon']);
|
||||
/** Derived per-record field for layers with a time field (hours before now). */
|
||||
const AGE_FIELD = 'ageHours';
|
||||
/** Spatial scope kinds `query()` accepts. */
|
||||
export const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
'view',
|
||||
'region',
|
||||
'radius',
|
||||
'anywhere',
|
||||
'area',
|
||||
'drawn',
|
||||
'annotation',
|
||||
]);
|
||||
|
||||
/**
|
||||
@@ -74,7 +82,7 @@ export const ANALYST_SCOPE_KINDS = Object.freeze([
|
||||
* @param {string[]} layerKeys Queried layer ids.
|
||||
* @returns {string[]} Field names, common fields first.
|
||||
*/
|
||||
export function analystFieldsFor(layerKeys) {
|
||||
function analystFieldsFor(layerKeys) {
|
||||
const fields = new Set(COMMON_FIELDS);
|
||||
for (const key of layerKeys) {
|
||||
const layer = ANALYST_LAYERS[key];
|
||||
@@ -104,47 +112,14 @@ export function haversineKm(lat1, lon1, lat2, lon2) {
|
||||
return greatCircleKm({ lat: lat1, lon: lon1 }, { lat: lat2, lon: lon2 });
|
||||
}
|
||||
|
||||
/**
|
||||
* One filter: {field, op:'gt'|'lt'|'gte'|'lte'|'eq'|'neq'|'contains', value}.
|
||||
* With `time: true`, both sides compare as epoch ms (ISO strings accepted).
|
||||
*/
|
||||
export function applyFilter(records, filter, { time = false } = {}) {
|
||||
const { field, op } = filter || {};
|
||||
if (!field || !op) return records;
|
||||
const value = time ? toEpochMs(filter.value) : filter.value;
|
||||
return records.filter((r) => {
|
||||
const got = time ? toEpochMs(r[field]) : r[field];
|
||||
if (got === null || got === undefined || (time && !Number.isFinite(got)))
|
||||
return false;
|
||||
if (time && (op === 'eq' || op === 'neq'))
|
||||
return (got === value) === (op === 'eq');
|
||||
switch (op) {
|
||||
case 'gt':
|
||||
return Number(got) > Number(value);
|
||||
case 'gte':
|
||||
return Number(got) >= Number(value);
|
||||
case 'lt':
|
||||
return Number(got) < Number(value);
|
||||
case 'lte':
|
||||
return Number(got) <= Number(value);
|
||||
case 'eq': {
|
||||
if (typeof got === 'boolean' || typeof value === 'boolean')
|
||||
return Boolean(got) === Boolean(value);
|
||||
return String(got).toLowerCase() === String(value).toLowerCase();
|
||||
}
|
||||
case 'neq':
|
||||
return String(got).toLowerCase() !== String(value).toLowerCase();
|
||||
case 'contains':
|
||||
return String(got).toLowerCase().includes(String(value).toLowerCase());
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/** Scope records spatially. scope: {kind:'view'|'region'|'radius'|'anywhere', …}. */
|
||||
/** Scope records spatially. scope: {kind:'view'|'region'|'radius'|'anywhere'|'area', …}. */
|
||||
export function applyScope(records, scope, resolved) {
|
||||
if (!scope || scope.kind === 'anywhere') return records;
|
||||
if (resolved?.prepared) {
|
||||
return records.filter((r) =>
|
||||
pointInPreparedArea(resolved.prepared, r.lat, r.lon),
|
||||
);
|
||||
}
|
||||
if (scope.kind === 'region' && resolved?.ring) {
|
||||
return records.filter(
|
||||
(r) =>
|
||||
@@ -167,28 +142,6 @@ export function applyScope(records, scope, resolved) {
|
||||
return records;
|
||||
}
|
||||
|
||||
/** Numeric summary for the narration layer. */
|
||||
function summarize(items, sortField) {
|
||||
const summary = { count: items.length };
|
||||
if (sortField && items.length) {
|
||||
// A loop, not Math.min(...vals): a full FIRMS day is ~160k values, past
|
||||
// the engine's argument limit.
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
for (const item of items) {
|
||||
const value = Number(item[sortField]);
|
||||
if (!Number.isFinite(value)) continue;
|
||||
if (value < min) min = value;
|
||||
if (value > max) max = value;
|
||||
}
|
||||
if (Number.isFinite(min)) {
|
||||
summary[`${sortField}Min`] = min;
|
||||
summary[`${sortField}Max`] = max;
|
||||
}
|
||||
}
|
||||
return summary;
|
||||
}
|
||||
|
||||
const OPS_BY_TYPE = Object.freeze({
|
||||
number: ['gt', 'gte', 'lt', 'lte', 'eq', 'neq'],
|
||||
time: ['gt', 'gte', 'lt', 'lte', 'eq', 'neq'],
|
||||
@@ -213,7 +166,7 @@ const COMMON_UNITS = Object.freeze({
|
||||
* @param {string} field Field name.
|
||||
* @returns {'number'|'text'|'flag'|'time'|null} Field type.
|
||||
*/
|
||||
export function analystFieldType(layerKeys, field) {
|
||||
function analystFieldType(layerKeys, field) {
|
||||
if (!analystFieldsFor(layerKeys).includes(field)) return null;
|
||||
if (COMMON_TYPES[field]) return COMMON_TYPES[field];
|
||||
for (const key of layerKeys) {
|
||||
@@ -380,6 +333,24 @@ function normalizeSpec(spec, layerKeys) {
|
||||
return {
|
||||
refusal: refusal('BAD_SCOPE', 'A region scope needs a place name.'),
|
||||
};
|
||||
if (
|
||||
kind === 'area' &&
|
||||
(typeof scope.areaId !== 'string' || !scope.areaId.trim())
|
||||
)
|
||||
return {
|
||||
refusal: refusal(
|
||||
'BAD_SCOPE',
|
||||
'An area scope needs the areaId resolve_area returned.',
|
||||
),
|
||||
};
|
||||
if (
|
||||
kind === 'annotation' &&
|
||||
scope.id !== undefined &&
|
||||
(typeof scope.id !== 'string' || !scope.id.trim())
|
||||
)
|
||||
return {
|
||||
refusal: refusal('BAD_SCOPE', 'scope.id must be an annotation id.'),
|
||||
};
|
||||
if (scope.center !== undefined && scope.center !== null) {
|
||||
if (!validLat(scope.center.lat) || !validLon(scope.center.lon))
|
||||
return {
|
||||
@@ -516,7 +487,16 @@ const ANSWERABLE = new Set(['ok', 'empty']);
|
||||
|
||||
/** Rows per scan slice before yielding to the page. */
|
||||
const SCAN_CHUNK = 20_000;
|
||||
/**
|
||||
* A slice also ends after this long: a row inside a large area pays a ray
|
||||
* cast over every edge (a 6,000-vertex outline takes ~200 ms per 20,000 rows),
|
||||
* so the row count alone would still make long tasks.
|
||||
*/
|
||||
const SCAN_BUDGET_MS = 8;
|
||||
/** Rows between clock checks. */
|
||||
const SCAN_CLOCK_EVERY = 256;
|
||||
const yieldToPage = () => new Promise((resolve) => setTimeout(resolve, 0));
|
||||
const clockMs = () => globalThis.performance?.now?.() ?? Date.now();
|
||||
|
||||
/**
|
||||
* Compile the filters into one predicate over (layerKey, row).
|
||||
@@ -657,12 +637,19 @@ export async function selectAnalystRows(
|
||||
let min = Infinity;
|
||||
let max = -Infinity;
|
||||
let seen = 0;
|
||||
let sliceStart = clockMs();
|
||||
for (const { key, rows } of groups) {
|
||||
const kept = [];
|
||||
for (const row of rows) {
|
||||
if (++seen % SCAN_CHUNK === 0) {
|
||||
seen += 1;
|
||||
if (
|
||||
seen % SCAN_CHUNK === 0 ||
|
||||
(seen % SCAN_CLOCK_EVERY === 0 &&
|
||||
clockMs() - sliceStart >= SCAN_BUDGET_MS)
|
||||
) {
|
||||
await yieldToPage();
|
||||
if (!isCurrent()) return null;
|
||||
sliceStart = clockMs();
|
||||
}
|
||||
if (inScope && !inScope(row)) continue;
|
||||
if (!passes(key, row)) continue;
|
||||
@@ -710,9 +697,8 @@ export function createAnalystEngine(providers) {
|
||||
/**
|
||||
* Run one query.
|
||||
* @param {object} spec Query arguments (see the analyst_query tool).
|
||||
* @param {{isCurrent?: () => boolean, signal?: AbortSignal,
|
||||
* beforeCommit?: (result: object) => Promise<object|void>}} [options]
|
||||
* A query that is no longer current
|
||||
* @param {{signal?: AbortSignal, isCurrent?: () => boolean, beforeCommit?: (result: object) =>
|
||||
* Promise<object|void>}} [options] A query that is no longer current
|
||||
* (cancelled or superseded while awaiting a boundary or between scan
|
||||
* slices) returns CANCELLED and never replaces the follow-up memory.
|
||||
* `beforeCommit` lets a caller finish required async projection work and
|
||||
@@ -722,7 +708,7 @@ export function createAnalystEngine(providers) {
|
||||
*/
|
||||
async function query(
|
||||
spec = {},
|
||||
{ isCurrent = () => true, signal = undefined, beforeCommit = null } = {},
|
||||
{ signal = null, isCurrent = () => true, beforeCommit = null } = {},
|
||||
) {
|
||||
const cancelled = () =>
|
||||
refusal('CANCELLED', 'This query was superseded.', { cancelled: true });
|
||||
@@ -733,6 +719,7 @@ export function createAnalystEngine(providers) {
|
||||
{ coverage: { layersQueried: [], scope: 'none' } },
|
||||
);
|
||||
const followUp = Boolean(spec.followUp);
|
||||
const inheritsRememberedScope = followUp && spec.scope == null;
|
||||
// A follow-up re-filters the remembered set. Layers named explicitly
|
||||
// must be that set: "those hospitals" after an aircraft answer is a new
|
||||
// question, never a filter over the old aircraft.
|
||||
@@ -875,25 +862,37 @@ export function createAnalystEngine(providers) {
|
||||
}
|
||||
|
||||
// 2) Spatial scope
|
||||
const rememberedScope =
|
||||
followUp && !spec.scope ? lastResult.scopePresentation || null : null;
|
||||
const rememberedDistanceOf =
|
||||
followUp && !spec.scope ? lastResult.distanceOf || null : null;
|
||||
const rememberedPresentation = inheritsRememberedScope
|
||||
? lastResult.presentation || null
|
||||
: null;
|
||||
const rememberedCoverageNote =
|
||||
rememberedPresentation?.coverageNote ||
|
||||
(inheritsRememberedScope ? lastResult.coverage?.note : null);
|
||||
const rememberedDistanceOf = inheritsRememberedScope
|
||||
? lastResult.distanceOf || null
|
||||
: null;
|
||||
let resolvedScope = null;
|
||||
let scopeNote = rememberedScope?.coverage || 'anywhere';
|
||||
let scopeSource = rememberedScope?.source || null;
|
||||
let scopeNote =
|
||||
rememberedPresentation?.coverageScope ||
|
||||
(inheritsRememberedScope ? lastResult.coverage?.scope : null) ||
|
||||
'anywhere';
|
||||
let scopeSource =
|
||||
rememberedPresentation?.coverageScopeSource ||
|
||||
(inheritsRememberedScope ? lastResult.coverage?.scopeSource : null) ||
|
||||
null;
|
||||
// Human phrasing for the same scope, so every spoken count can name what it
|
||||
// measured ("8 in view", "about 30 within 250 km of Austin") instead of
|
||||
// arriving as a bare number that contradicts the panel.
|
||||
let scopeLabel = rememberedScope?.label || 'anywhere in the loaded data';
|
||||
let scopeDetail = rememberedScope?.detail || scopeLabel;
|
||||
let scopeLabel =
|
||||
rememberedPresentation?.scopeLabel || 'anywhere in the loaded data';
|
||||
let scopeDetail = rememberedPresentation?.display?.scope || scopeLabel;
|
||||
// A follow-up re-filters a set that was already scoped, so it only narrows
|
||||
// further when a new scope is given.
|
||||
const scope = spec.scope || { kind: followUp ? 'anywhere' : 'view' };
|
||||
if (scope.kind === 'region') {
|
||||
let region;
|
||||
try {
|
||||
region = await providers.resolveRegionRing(scope.name, signal);
|
||||
region = await providers.resolveRegionRing(scope.name, { signal });
|
||||
} catch (error) {
|
||||
// Cancellation belongs to the query owner, not an error's name: a
|
||||
// resource-local AbortError from a current lookup still propagates.
|
||||
@@ -909,7 +908,32 @@ export function createAnalystEngine(providers) {
|
||||
coverage: { layersQueried, scope: `region:${scope.name}:timeout` },
|
||||
};
|
||||
}
|
||||
if (!region?.ring) {
|
||||
if (region?.needsClarification) {
|
||||
return refusal(
|
||||
'NEEDS_CLARIFICATION',
|
||||
region.error ||
|
||||
`"${scope.name}" names more than one place — ask which one.`,
|
||||
{
|
||||
needsClarification: true,
|
||||
query: scope.name,
|
||||
candidates: region.candidates || [],
|
||||
// The way back once the user picks: count over that area.
|
||||
then: 'After the user picks, call resolve_area with that candidateId, then analyst_query with scope {kind:"area", areaId}.',
|
||||
coverage: {
|
||||
layersQueried,
|
||||
scope: `region:${scope.name}:ambiguous`,
|
||||
},
|
||||
},
|
||||
);
|
||||
}
|
||||
const prepared =
|
||||
region?.prepared ||
|
||||
(region?.geometry
|
||||
? prepareArea(region.geometry)
|
||||
: region?.ring
|
||||
? prepareArea([[region.ring]])
|
||||
: null);
|
||||
if (!prepared) {
|
||||
return {
|
||||
ok: false,
|
||||
code: 'REGION_UNRESOLVED',
|
||||
@@ -917,11 +941,39 @@ export function createAnalystEngine(providers) {
|
||||
coverage: { layersQueried, scope: `region:${scope.name}:unresolved` },
|
||||
};
|
||||
}
|
||||
resolvedScope = region;
|
||||
resolvedScope = { ...region, prepared };
|
||||
scopeNote = `region:${region.name}`;
|
||||
scopeSource = region.source || null;
|
||||
scopeLabel = `over ${region.name}`;
|
||||
scopeDetail = scopeLabel;
|
||||
const regionSource = region.sourceLabel || region.source;
|
||||
scopeDetail = `${scopeLabel}${region.approximate ? ' (approximate outline)' : ''}${regionSource ? ` · ${regionSource}` : ''}`;
|
||||
} else if (
|
||||
scope.kind === 'area' ||
|
||||
scope.kind === 'drawn' ||
|
||||
scope.kind === 'annotation'
|
||||
) {
|
||||
const found = providers.resolveAreaScope
|
||||
? await providers.resolveAreaScope(scope)
|
||||
: {
|
||||
ok: false,
|
||||
code: 'AREA_UNAVAILABLE',
|
||||
error: 'Area scopes are not available here.',
|
||||
};
|
||||
if (!isCurrent()) return cancelled();
|
||||
if (!found?.ok || !found.area?.prepared) {
|
||||
return refusal(
|
||||
found?.code || 'AREA_UNKNOWN',
|
||||
found?.error || 'That area is not available.',
|
||||
{ coverage: { layersQueried, scope: `${scope.kind}:unresolved` } },
|
||||
);
|
||||
}
|
||||
const area = found.area;
|
||||
resolvedScope = { prepared: area.prepared, name: area.name };
|
||||
scopeNote = `area:${area.areaId || scope.kind}`;
|
||||
scopeLabel = `inside ${area.name}`;
|
||||
const sourceLabel = area.sourceLabel || area.source;
|
||||
scopeDetail = `${scopeLabel}${area.approximate ? ' (approximate outline)' : ''}${sourceLabel ? ` · ${sourceLabel}` : ''}`;
|
||||
if (area.areaId) resolvedScope.areaId = area.areaId;
|
||||
} else if (scope.kind === 'radius') {
|
||||
// An explicit center always wins. Otherwise, when Contacts is active its
|
||||
// SUBJECT is the centre the operator is actually reasoning about: the
|
||||
@@ -966,25 +1018,21 @@ export function createAnalystEngine(providers) {
|
||||
scopeLabel = 'in view';
|
||||
scopeDetail = `within ${Math.round(view.viewRadiusKm)} km of the view centre`;
|
||||
}
|
||||
const inScope =
|
||||
scope.kind === 'region' && resolvedScope?.ring
|
||||
const inScope = resolvedScope?.prepared
|
||||
? (row) => pointInPreparedArea(resolvedScope.prepared, row.lat, row.lon)
|
||||
: (scope.kind === 'radius' || scope.kind === 'view') &&
|
||||
resolvedScope?.center &&
|
||||
Number.isFinite(resolvedScope.km)
|
||||
? (row) =>
|
||||
Number.isFinite(row.lat) &&
|
||||
Number.isFinite(row.lon) &&
|
||||
pointInRing(resolvedScope.ring, row.lat, row.lon)
|
||||
: (scope.kind === 'radius' || scope.kind === 'view') &&
|
||||
resolvedScope?.center &&
|
||||
Number.isFinite(resolvedScope.km)
|
||||
? (row) =>
|
||||
Number.isFinite(row.lat) &&
|
||||
Number.isFinite(row.lon) &&
|
||||
haversineKm(
|
||||
resolvedScope.center.lat,
|
||||
resolvedScope.center.lon,
|
||||
row.lat,
|
||||
row.lon,
|
||||
) <= resolvedScope.km
|
||||
: null;
|
||||
haversineKm(
|
||||
resolvedScope.center.lat,
|
||||
resolvedScope.center.lon,
|
||||
row.lat,
|
||||
row.lon,
|
||||
) <= resolvedScope.km
|
||||
: null;
|
||||
|
||||
// 3) Filter, count and rank in one pass, yielding between slices.
|
||||
const selection = await selectAnalystRows(groups, {
|
||||
@@ -1052,15 +1100,25 @@ export function createAnalystEngine(providers) {
|
||||
// For on-screen text; the model speaks the count and scopeLabel only.
|
||||
display: {
|
||||
scope: scopeDetail,
|
||||
...(windows.length ? { window: windows.join('; ') } : {}),
|
||||
...(caveats.length ? { caveat: caveats.join('; ') } : {}),
|
||||
...(rememberedPresentation?.display?.window || windows.length
|
||||
? {
|
||||
window:
|
||||
rememberedPresentation?.display?.window || windows.join('; '),
|
||||
}
|
||||
: {}),
|
||||
...(rememberedPresentation?.display?.caveat || caveats.length
|
||||
? {
|
||||
caveat:
|
||||
rememberedPresentation?.display?.caveat || caveats.join('; '),
|
||||
}
|
||||
: {}),
|
||||
},
|
||||
coverage: {
|
||||
layersQueried,
|
||||
records: totals,
|
||||
scope: scopeNote,
|
||||
...(scopeSource ? { scopeSource } : {}),
|
||||
...(rememberedScope?.note ? { note: rememberedScope.note } : {}),
|
||||
...(rememberedCoverageNote ? { note: rememberedCoverageNote } : {}),
|
||||
...(queriedSnapshots.length
|
||||
? { feedProvenance: feedProvenanceEnvelope(queriedSnapshots) }
|
||||
: {}),
|
||||
@@ -1070,37 +1128,102 @@ export function createAnalystEngine(providers) {
|
||||
// than implying a view-centred answer.
|
||||
...(resolvedScope?.centeredOn
|
||||
? { centeredOn: resolvedScope.centeredOn }
|
||||
: rememberedPresentation?.centeredOn
|
||||
? { centeredOn: rememberedPresentation.centeredOn }
|
||||
: {}),
|
||||
...(rememberedPresentation?.window
|
||||
? { window: structuredClone(rememberedPresentation.window) }
|
||||
: {}),
|
||||
...(resolvedScope?.areaId
|
||||
? { areaId: resolvedScope.areaId }
|
||||
: rememberedPresentation?.areaId
|
||||
? { areaId: rememberedPresentation.areaId }
|
||||
: {}),
|
||||
};
|
||||
const memoryOverride =
|
||||
typeof beforeCommit === 'function'
|
||||
? (await beforeCommit(result)) || null
|
||||
: null;
|
||||
if (!isCurrent()) return cancelled();
|
||||
const committedCoverage = memoryOverride?.coverage || result.coverage;
|
||||
lastResult = {
|
||||
matched: memoryOverride?.matched || selection.matched,
|
||||
distanceOf: memoryOverride?.distanceOf || rememberedDistanceOf,
|
||||
layerKeys: [...(memoryOverride?.layerKeys || layers)],
|
||||
coverage: committedCoverage,
|
||||
coverage: memoryOverride?.coverage || result.coverage,
|
||||
unanswered: [
|
||||
...(memoryOverride?.unanswered === undefined
|
||||
? unanswered
|
||||
: memoryOverride.unanswered),
|
||||
],
|
||||
scopePresentation: {
|
||||
label: memoryOverride?.scopeLabel || result.scopeLabel,
|
||||
detail: memoryOverride?.scopeDetail || result.display.scope,
|
||||
coverage: committedCoverage.scope,
|
||||
source: committedCoverage.scopeSource || null,
|
||||
note: committedCoverage.note || null,
|
||||
},
|
||||
presentation: structuredClone(
|
||||
memoryOverride?.presentation || {
|
||||
scopeLabel: result.scopeLabel,
|
||||
display: result.display,
|
||||
coverageScope: result.coverage?.scope,
|
||||
...(result.coverage?.scopeSource
|
||||
? { coverageScopeSource: result.coverage.scopeSource }
|
||||
: {}),
|
||||
...(result.coverage?.note
|
||||
? { coverageNote: result.coverage.note }
|
||||
: {}),
|
||||
...(result.centeredOn ? { centeredOn: result.centeredOn } : {}),
|
||||
...(result.window ? { window: result.window } : {}),
|
||||
...(result.areaId ? { areaId: result.areaId } : {}),
|
||||
},
|
||||
),
|
||||
};
|
||||
return result;
|
||||
}
|
||||
|
||||
return {
|
||||
query,
|
||||
/**
|
||||
* Make another tool's result set "the last answer" (osm_query's places),
|
||||
* so a follow-up filters exactly what the user just heard about.
|
||||
* @param {string} layerKey Queryable layer the rows belong to.
|
||||
* @param {Array<object>} rows Records in that layer's analyst shape.
|
||||
* @param {{scope?: string, presentation?: object|null, truncated?: boolean}} [options]
|
||||
* `presentation` is how the set was scoped ("inside Kathmandu"), so a
|
||||
* follow-up names the same scope instead of "anywhere". `truncated`
|
||||
* says the set is only the first part of a larger one, so follow-ups
|
||||
* stay incomplete (a count is a floor) rather than claiming the whole.
|
||||
*/
|
||||
remember(
|
||||
layerKey,
|
||||
rows,
|
||||
{ scope = 'handoff', presentation = null, truncated = false } = {},
|
||||
) {
|
||||
if (!ANALYST_LAYERS[layerKey] || !Array.isArray(rows)) return false;
|
||||
const capped = truncated === true;
|
||||
// A capped set's true size is unknown.
|
||||
const total = capped ? null : rows.length;
|
||||
lastResult = {
|
||||
...(presentation
|
||||
? { presentation: structuredClone(presentation) }
|
||||
: {}),
|
||||
matched: [{ key: layerKey, rows: rows.slice() }],
|
||||
layerKeys: [layerKey],
|
||||
coverage: {
|
||||
layersQueried: [
|
||||
{
|
||||
layerKey,
|
||||
status: rows.length ? 'ok' : 'empty',
|
||||
returned: rows.length,
|
||||
total,
|
||||
truncated: capped,
|
||||
},
|
||||
],
|
||||
records: {
|
||||
returned: rows.length,
|
||||
total,
|
||||
truncated: capped,
|
||||
},
|
||||
scope,
|
||||
followUp: false,
|
||||
},
|
||||
};
|
||||
return true;
|
||||
},
|
||||
reset() {
|
||||
lastResult = null;
|
||||
},
|
||||
|
||||
@@ -275,14 +275,18 @@ for (const [label, committedScope, scopeSource] of [
|
||||
const { scopeSource: _originalSource, ...coverage } = result.coverage;
|
||||
return {
|
||||
matched: [{ key: 'flights', rows: [FLIGHTS[1]] }],
|
||||
scopeLabel: 'the presented cohort',
|
||||
scopeDetail: 'the presented cohort window',
|
||||
coverage: {
|
||||
...coverage,
|
||||
scope: committedScope,
|
||||
...(scopeSource ? { scopeSource } : {}),
|
||||
feedProvenance: { layers: [committedSnapshot] },
|
||||
},
|
||||
presentation: {
|
||||
scopeLabel: 'the presented cohort',
|
||||
display: { scope: 'the presented cohort window' },
|
||||
coverageScope: committedScope,
|
||||
...(scopeSource ? { coverageScopeSource: scopeSource } : {}),
|
||||
},
|
||||
};
|
||||
},
|
||||
},
|
||||
@@ -436,6 +440,87 @@ test('analyst: failed pre-commit work cannot replace follow-up memory', async ()
|
||||
assert.deepEqual(followUp.items.map((item) => item.id), ['SWA1']);
|
||||
});
|
||||
|
||||
test('analyst: follow-ups preserve partial and unanswered coverage', async () => {
|
||||
const eng = createAnalystEngine({
|
||||
getRecords: (key) => (key === 'flights' ? FLIGHTS : []),
|
||||
getLayerSnapshot: (key) => ({
|
||||
enabled: key === 'flights',
|
||||
feedState: key === 'flights' ? 'nominal' : 'off',
|
||||
}),
|
||||
getViewContext: () => ({ lat: 30.27, lon: -97.74, viewRadiusKm: 150 }),
|
||||
});
|
||||
const first = await eng.query({
|
||||
layers: ['flights', 'military'],
|
||||
scope: { kind: 'anywhere' },
|
||||
});
|
||||
assert.equal(first.partial, true);
|
||||
assert.deepEqual(first.unanswered, ['military']);
|
||||
|
||||
const followUp = await eng.query({ followUp: true, limit: 1 });
|
||||
assert.equal(followUp.partial, true);
|
||||
assert.deepEqual(followUp.unanswered, ['military']);
|
||||
assert.deepEqual(
|
||||
followUp.coverage.layersQueried.map(({ layerKey, status }) => [
|
||||
layerKey,
|
||||
status,
|
||||
]),
|
||||
first.coverage.layersQueried.map(({ layerKey, status }) => [
|
||||
layerKey,
|
||||
status,
|
||||
]),
|
||||
);
|
||||
});
|
||||
|
||||
test('analyst: cancelled pre-commit work cannot replace follow-up memory', async () => {
|
||||
const eng = makeEngine();
|
||||
await eng.query({
|
||||
layers: ['flights'],
|
||||
scope: { kind: 'anywhere' },
|
||||
filters: [{ field: 'id', op: 'eq', value: 'SWA1' }],
|
||||
});
|
||||
let current = true;
|
||||
const stale = await eng.query(
|
||||
{ layers: ['local-firms'], scope: { kind: 'anywhere' } },
|
||||
{
|
||||
isCurrent: () => current,
|
||||
beforeCommit: async () => {
|
||||
current = false;
|
||||
},
|
||||
},
|
||||
);
|
||||
assert.equal(stale.code, 'CANCELLED');
|
||||
const followUp = await eng.query({ followUp: true });
|
||||
assert.deepEqual(
|
||||
followUp.items.map((item) => item.id),
|
||||
['SWA1'],
|
||||
);
|
||||
});
|
||||
|
||||
test('analyst: failed pre-commit work cannot replace follow-up memory', async () => {
|
||||
const eng = makeEngine();
|
||||
await eng.query({
|
||||
layers: ['flights'],
|
||||
scope: { kind: 'anywhere' },
|
||||
filters: [{ field: 'id', op: 'eq', value: 'SWA1' }],
|
||||
});
|
||||
await assert.rejects(
|
||||
eng.query(
|
||||
{ layers: ['local-firms'], scope: { kind: 'anywhere' } },
|
||||
{
|
||||
beforeCommit: async () => {
|
||||
throw new Error('projection failed');
|
||||
},
|
||||
},
|
||||
),
|
||||
/projection failed/,
|
||||
);
|
||||
const followUp = await eng.query({ followUp: true });
|
||||
assert.deepEqual(
|
||||
followUp.items.map((item) => item.id),
|
||||
['SWA1'],
|
||||
);
|
||||
});
|
||||
|
||||
test('analyst: unresolved region is an honest failure, not empty success', async () => {
|
||||
const r = await makeEngine().query({ layers: ['flights'], scope: { kind: 'region', name: 'Atlantis' } });
|
||||
assert.equal(r.ok, false);
|
||||
@@ -460,7 +545,7 @@ test('analyst: region lookup receives and obeys the owning action signal', async
|
||||
let receivedSignal = null;
|
||||
const eng = createAnalystEngine({
|
||||
getRecords: () => FLIGHTS,
|
||||
resolveRegionRing: async (_name, signal) => {
|
||||
resolveRegionRing: async (_name, { signal }) => {
|
||||
receivedSignal = signal;
|
||||
await new Promise((resolve) =>
|
||||
signal.addEventListener('abort', resolve, { once: true }),
|
||||
@@ -514,7 +599,7 @@ for (const [label, reason, trackAuthority] of [
|
||||
};
|
||||
const engine = createAnalystEngine({
|
||||
getRecords: () => FLIGHTS,
|
||||
resolveRegionRing: (name, signal) => resolveRegionRingForQuery(
|
||||
resolveRegionRing: (name, { signal } = {}) => resolveRegionRingForQuery(
|
||||
name, signal, placeSearch, { budgetMs: Infinity },
|
||||
),
|
||||
});
|
||||
@@ -720,7 +805,9 @@ test('unknown fields, operators, scopes and wrong-typed values are refused with
|
||||
assert.equal(num.code, 'BAD_VALUE');
|
||||
const scope = await engine.query({ layers: ['flights'], scope: { kind: 'polygon' } });
|
||||
assert.equal(scope.code, 'UNKNOWN_SCOPE');
|
||||
assert.deepEqual(scope.allowed, ['view', 'region', 'radius', 'anywhere']);
|
||||
assert.deepEqual(scope.allowed, ['view', 'region', 'radius', 'anywhere', 'area', 'drawn', 'annotation']);
|
||||
const noId = await engine.query({ layers: ['flights'], scope: { kind: 'area' } });
|
||||
assert.equal(noId.code, 'BAD_SCOPE', 'an area scope needs its areaId');
|
||||
const sort = await engine.query({ layers: ['flights'], sortBy: 'loudness' });
|
||||
assert.equal(sort.code, 'UNKNOWN_FIELD');
|
||||
assert.equal(engine.hasMemory(), false, 'refusals never become follow-up memory');
|
||||
@@ -963,3 +1050,193 @@ test('analyst: a follow-up naming other layers than the last answer is refused',
|
||||
assert.equal(r.code, 'FOLLOW_UP_MISMATCH');
|
||||
assert.equal(engine.hasMemory(), true, 'the earlier answer is still the last answer');
|
||||
});
|
||||
|
||||
// ── Area handles: region multipolygons and the area / drawn / annotation scopes ──
|
||||
|
||||
const box = (w, s, e, n) => [[w, s], [e, s], [e, n], [w, n], [w, s]];
|
||||
|
||||
function makeAreaEngine(overrides = {}) {
|
||||
return createAnalystEngine({
|
||||
getRecords: (key) => ({ flights: FLIGHTS, 'local-firms': FIRES }[key] || []),
|
||||
resolveRegionRing: async () => null,
|
||||
getViewContext: () => ({ lat: 30.27, lon: -97.74, viewRadiusKm: 150 }),
|
||||
...overrides,
|
||||
});
|
||||
}
|
||||
|
||||
test('analyst: a region counts every part of a multipolygon and skips its holes', async () => {
|
||||
// Main part around Austin with a hole over the airport ground traffic, and a
|
||||
// separate island over Oregon: the old largest-ring shortcut dropped N123.
|
||||
const engine = makeAreaEngine({
|
||||
resolveRegionRing: async () => ({
|
||||
name: 'Archipelago',
|
||||
geometry: [
|
||||
[box(-100, 28, -94, 33), box(-97.7, 30.1, -97.6, 30.25)],
|
||||
[box(-123, 44, -121, 46)],
|
||||
],
|
||||
source: 'osm',
|
||||
}),
|
||||
});
|
||||
const r = await engine.query({ layers: ['flights'], scope: { kind: 'region', name: 'Archipelago' }, limit: 10 });
|
||||
assert.equal(r.ok, true);
|
||||
assert.deepEqual(r.items.map((i) => i.id).sort(), ['N123', 'RCH01']);
|
||||
assert.equal(r.count, 2, 'SWA1 and GND1 sit in the hole');
|
||||
assert.match(r.display.scope, /over Archipelago · osm/);
|
||||
});
|
||||
|
||||
test('analyst: an ambiguous region asks instead of counting', async () => {
|
||||
const engine = makeAreaEngine({
|
||||
resolveRegionRing: async () => ({
|
||||
ok: false,
|
||||
needsClarification: true,
|
||||
candidates: [{ candidateId: 'osm:r1', name: 'Georgia', level: 'country' }],
|
||||
error: '"Georgia" matches 2 places — ask which one.',
|
||||
}),
|
||||
});
|
||||
const r = await engine.query({ layers: ['flights'], scope: { kind: 'region', name: 'Georgia' } });
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.code, 'NEEDS_CLARIFICATION');
|
||||
assert.equal(r.candidates.length, 1);
|
||||
assert.match(r.then, /resolve_area.*candidateId.*analyst_query.*kind.*area/, 'the model gets a route back');
|
||||
assert.equal(engine.hasMemory(), false);
|
||||
});
|
||||
|
||||
test('analyst: region lookup receives the caller lifetime signal', async () => {
|
||||
const controller = new AbortController();
|
||||
let received;
|
||||
const engine = makeAreaEngine({
|
||||
resolveRegionRing: async (_name, options) => {
|
||||
received = options?.signal;
|
||||
return { error: 'region-timeout' };
|
||||
},
|
||||
});
|
||||
const result = await engine.query(
|
||||
{
|
||||
layers: ['flights'],
|
||||
scope: { kind: 'region', name: 'Signal Region' },
|
||||
},
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
assert.equal(received, controller.signal);
|
||||
assert.equal(result.code, 'region-timeout');
|
||||
});
|
||||
|
||||
test('analyst: an area scope counts inside the stored handle and names it', async () => {
|
||||
const { prepareArea } = await import('./areaGeometry.js');
|
||||
const prepared = prepareArea([[box(-99, 30, -97.5, 31)]]);
|
||||
const seen = [];
|
||||
const engine = makeAreaEngine({
|
||||
resolveAreaScope: async (scope) => {
|
||||
seen.push(scope);
|
||||
if (scope.kind === 'area' && scope.areaId === 'osm:r42')
|
||||
return { ok: true, area: { areaId: 'osm:r42', name: 'Hill Country', prepared, source: 'osm' } };
|
||||
if (scope.kind === 'drawn')
|
||||
return { ok: true, area: { areaId: 'anno:anno-7', name: 'the drawn area', prepared, source: 'drawn' } };
|
||||
return { ok: false, code: 'AREA_UNKNOWN', error: 'No such area' };
|
||||
},
|
||||
});
|
||||
const fires = await engine.query({ layers: ['local-firms'], scope: { kind: 'area', areaId: 'osm:r42' } });
|
||||
assert.equal(fires.ok, true);
|
||||
assert.equal(fires.count, 2);
|
||||
assert.equal(fires.scopeLabel, 'inside Hill Country');
|
||||
assert.equal(fires.areaId, 'osm:r42');
|
||||
assert.equal(fires.coverage.scope, 'area:osm:r42');
|
||||
const followUp = await engine.query({ followUp: true, limit: 1 });
|
||||
assert.equal(followUp.scopeLabel, 'inside Hill Country');
|
||||
assert.match(followUp.display.scope, /inside Hill Country/);
|
||||
assert.equal(followUp.coverage.scope, 'area:osm:r42');
|
||||
assert.equal(followUp.areaId, 'osm:r42');
|
||||
const drawn = await engine.query({ layers: ['flights'], scope: { kind: 'drawn' } });
|
||||
assert.equal(drawn.ok, true);
|
||||
assert.equal(drawn.count, 2, 'SWA1 and GND1 sit inside the drawn box');
|
||||
const missing = await engine.query({ layers: ['flights'], scope: { kind: 'area', areaId: 'osm:r0' } });
|
||||
assert.equal(missing.ok, false);
|
||||
assert.equal(missing.code, 'AREA_UNKNOWN');
|
||||
assert.deepEqual(seen.map((s) => s.kind), ['area', 'drawn', 'area']);
|
||||
});
|
||||
|
||||
test('analyst: an area scope superseded while resolving is cancelled and leaves no memory', async () => {
|
||||
const { prepareArea } = await import('./areaGeometry.js');
|
||||
let current = true;
|
||||
const engine = makeAreaEngine({
|
||||
resolveAreaScope: async () => {
|
||||
current = false; // a newer turn arrived while the area was looked up
|
||||
return { ok: true, area: { name: 'X', prepared: prepareArea([[box(-100, 28, -94, 33)]]) } };
|
||||
},
|
||||
});
|
||||
const r = await engine.query(
|
||||
{ layers: ['flights'], scope: { kind: 'annotation' } },
|
||||
{ isCurrent: () => current },
|
||||
);
|
||||
assert.equal(r.code, 'CANCELLED');
|
||||
assert.equal(engine.hasMemory(), false);
|
||||
});
|
||||
|
||||
test('analyst: without an area provider the area scopes refuse plainly', async () => {
|
||||
const r = await makeAreaEngine().query({ layers: ['flights'], scope: { kind: 'drawn' } });
|
||||
assert.equal(r.ok, false);
|
||||
assert.equal(r.code, 'AREA_UNAVAILABLE');
|
||||
});
|
||||
|
||||
test('a follow-up on handed-off places keeps the area they were found in', async () => {
|
||||
const rows = [
|
||||
{ id: 'node/1', lat: 27.7, lon: 85.3, name: 'Bir Hospital', kind: 'hospital', emergency: 'yes' },
|
||||
{ id: 'node/2', lat: 27.71, lon: 85.31, name: 'Teaching Hospital', kind: 'hospital', emergency: 'no' },
|
||||
];
|
||||
const engine = createAnalystEngine({
|
||||
getRecords: (key) => (key === 'osm-places' ? rows : []),
|
||||
resolveRegionRing: async () => null,
|
||||
getViewContext: () => ({ lat: 27.7, lon: 85.3, viewRadiusKm: 20 }),
|
||||
});
|
||||
assert.equal(
|
||||
engine.remember('osm-places', rows, {
|
||||
presentation: { scopeLabel: 'inside Kathmandu', coverageScope: 'area:area-1', areaId: 'area-1' },
|
||||
}),
|
||||
true,
|
||||
);
|
||||
const result = await engine.query({
|
||||
layers: ['osm-places'],
|
||||
followUp: true,
|
||||
filters: [{ field: 'emergency', op: 'eq', value: 'yes' }],
|
||||
});
|
||||
assert.equal(result.count, 1);
|
||||
assert.equal(result.scopeLabel, 'inside Kathmandu');
|
||||
assert.equal(result.coverage.scope, 'area:area-1');
|
||||
});
|
||||
|
||||
test('a follow-up on a capped handed-off set is not complete', async () => {
|
||||
const rows = [
|
||||
{ id: 'node/1', lat: 27.7, lon: 85.3, name: 'Bir Hospital', kind: 'hospital', emergency: 'yes' },
|
||||
];
|
||||
const engine = createAnalystEngine({
|
||||
getRecords: (key) => (key === 'osm-places' ? rows : []),
|
||||
resolveRegionRing: async () => null,
|
||||
getViewContext: () => ({ lat: 27.7, lon: 85.3, viewRadiusKm: 20 }),
|
||||
});
|
||||
engine.remember('osm-places', rows, { truncated: true });
|
||||
const result = await engine.query({ layers: ['osm-places'], followUp: true });
|
||||
assert.equal(result.count, 1);
|
||||
assert.equal(result.complete, false);
|
||||
assert.equal(result.coverage.records.truncated, true);
|
||||
assert.equal(result.coverage.records.total, null, 'the true size is unknown');
|
||||
});
|
||||
|
||||
test('a slow scan yields on a time budget, not only every 20,000 rows', async () => {
|
||||
// 4,000 rows that each cost ~0.05 ms to read: ~200 ms of work in one slice
|
||||
// under a row-count budget alone.
|
||||
const slow = () => {
|
||||
const until = performance.now() + 0.05;
|
||||
while (performance.now() < until);
|
||||
return 5;
|
||||
};
|
||||
const rows = Array.from({ length: 4_000 }, (_, i) => ({ id: `S${i}`, lat: 0, lon: 0, get frp() { return slow(); } }));
|
||||
const engine = createAnalystEngine({ getRecords: () => rows, getViewContext: () => ({ lat: 0, lon: 0, viewRadiusKm: 25 }) });
|
||||
// Count the scan's yields (other timers run only when it yields), not wall
|
||||
// gaps, so a loaded machine cannot fail it.
|
||||
let ticks = 0;
|
||||
const timer = setInterval(() => ticks++, 0);
|
||||
const result = await engine.query({ layers: ['local-firms'], scope: { kind: 'anywhere' }, filters: [{ field: 'frp', op: 'gt', value: 1 }] });
|
||||
clearInterval(timer);
|
||||
assert.equal(result.count, 4_000);
|
||||
assert.ok(ticks >= 5, `the scan yielded ${ticks} times in ~200 ms of work`);
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
/**
|
||||
* Area geometry for voice area handles: normalization, containment, size and
|
||||
* display simplification over full MultiPolygons (islands and holes kept).
|
||||
*
|
||||
* Coordinates follow GeoJSON: a MultiPolygon is `Array<Polygon>`, a Polygon is
|
||||
* `Array<Ring>` with the outer ring first and holes after it, a Ring is
|
||||
* `Array<[lon, lat]>`.
|
||||
*
|
||||
* Counting uses the geometry exactly as resolved. Display simplification
|
||||
* (`displayParts`) makes a separate copy for drawing and never feeds back into
|
||||
* containment.
|
||||
*
|
||||
* Antimeridian: a ring whose consecutive longitudes jump by more than 180° is
|
||||
* unwrapped into one continuous span (e.g. 170..190) when the jumps cancel
|
||||
* out. Containment then tests the point at lon, lon + 360 and lon − 360. A ring
|
||||
* that circles a pole (jumps that do not cancel) is used as given.
|
||||
*
|
||||
* Pure: no Cesium, DOM or network.
|
||||
* @module data/areaGeometry
|
||||
*/
|
||||
|
||||
const EARTH_RADIUS_KM = 6371;
|
||||
const toRad = (degrees) => (degrees * Math.PI) / 180;
|
||||
|
||||
const validPair = (p) =>
|
||||
Array.isArray(p) &&
|
||||
Number.isFinite(p[0]) &&
|
||||
Number.isFinite(p[1]) &&
|
||||
Math.abs(p[0]) <= 540 &&
|
||||
Math.abs(p[1]) <= 90;
|
||||
|
||||
const samePoint = (a, b, eps = 1e-9) =>
|
||||
Math.abs(a[0] - b[0]) <= eps && Math.abs(a[1] - b[1]) <= eps;
|
||||
|
||||
/** A ring as closed [lon, lat] pairs, or null with fewer than 3 distinct points. */
|
||||
function cleanRing(ring) {
|
||||
if (!Array.isArray(ring)) return null;
|
||||
const out = [];
|
||||
for (const p of ring) {
|
||||
if (!validPair(p)) continue;
|
||||
const pair = [Number(p[0]), Number(p[1])];
|
||||
if (out.length && samePoint(out[out.length - 1], pair)) continue;
|
||||
out.push(pair);
|
||||
}
|
||||
if (out.length && samePoint(out[0], out[out.length - 1])) out.pop();
|
||||
if (out.length < 3) return null;
|
||||
out.push([out[0][0], out[0][1]]);
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* GeoJSON Polygon/MultiPolygon geometry (or bare coordinates) → MultiPolygon
|
||||
* coordinates with closed rings; null when nothing usable remains. Degenerate
|
||||
* holes are dropped; a polygon whose outer ring is degenerate is dropped whole.
|
||||
* @param {object|Array} geometry
|
||||
* @returns {Array|null}
|
||||
*/
|
||||
export function normalizeMultiPolygon(geometry) {
|
||||
let polygons;
|
||||
if (Array.isArray(geometry)) {
|
||||
// Bare coordinates: a ring, a polygon or a multipolygon, by nesting depth.
|
||||
const depth = (value) => (Array.isArray(value) ? 1 + depth(value[0]) : 0);
|
||||
const d = depth(geometry);
|
||||
polygons = d === 2 ? [[geometry]] : d === 3 ? [geometry] : geometry;
|
||||
} else if (geometry?.type === 'Polygon') polygons = [geometry.coordinates];
|
||||
else if (geometry?.type === 'MultiPolygon') polygons = geometry.coordinates;
|
||||
else return null;
|
||||
const out = [];
|
||||
for (const polygon of Array.isArray(polygons) ? polygons : []) {
|
||||
if (!Array.isArray(polygon)) continue;
|
||||
const outer = cleanRing(polygon[0]);
|
||||
if (!outer) continue;
|
||||
const holes = polygon.slice(1).map(cleanRing).filter(Boolean);
|
||||
out.push([outer, ...holes]);
|
||||
}
|
||||
return out.length ? out : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Longitudes made continuous across the antimeridian. Returns the ring as
|
||||
* given when it has no jump, or when its jumps do not cancel (a ring that
|
||||
* circles a pole).
|
||||
*/
|
||||
export function unwrapRing(ring) {
|
||||
let shift = 0;
|
||||
let jumped = false;
|
||||
const out = [[ring[0][0], ring[0][1]]];
|
||||
for (let i = 1; i < ring.length; i += 1) {
|
||||
const delta = ring[i][0] - ring[i - 1][0];
|
||||
if (delta > 180) {
|
||||
shift -= 360;
|
||||
jumped = true;
|
||||
} else if (delta < -180) {
|
||||
shift += 360;
|
||||
jumped = true;
|
||||
}
|
||||
out.push([ring[i][0] + shift, ring[i][1]]);
|
||||
}
|
||||
if (!jumped) return ring;
|
||||
return shift === 0 ? out : ring;
|
||||
}
|
||||
|
||||
function ringBbox(ring) {
|
||||
let w = Infinity;
|
||||
let s = Infinity;
|
||||
let e = -Infinity;
|
||||
let n = -Infinity;
|
||||
for (const [lon, lat] of ring) {
|
||||
if (lon < w) w = lon;
|
||||
if (lon > e) e = lon;
|
||||
if (lat < s) s = lat;
|
||||
if (lat > n) n = lat;
|
||||
}
|
||||
return [w, s, e, n];
|
||||
}
|
||||
|
||||
/** Even-odd ray cast. */
|
||||
function pointInRingXY(ring, lon, lat) {
|
||||
let inside = false;
|
||||
for (let i = 0, j = ring.length - 1; i < ring.length; j = i, i += 1) {
|
||||
const xi = ring[i][0];
|
||||
const yi = ring[i][1];
|
||||
const xj = ring[j][0];
|
||||
const yj = ring[j][1];
|
||||
if (
|
||||
yi > lat !== yj > lat &&
|
||||
lon < ((xj - xi) * (lat - yi)) / (yj - yi) + xi
|
||||
)
|
||||
inside = !inside;
|
||||
}
|
||||
return inside;
|
||||
}
|
||||
|
||||
const wrap180 = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180;
|
||||
const wrap360 = (lon) => {
|
||||
const wrapped = lon % 360;
|
||||
return wrapped < 0 ? wrapped + 360 : wrapped;
|
||||
};
|
||||
|
||||
/** The shortest circular longitude interval containing every outer-ring vertex. */
|
||||
function longitudeEnvelope(parts) {
|
||||
const values = parts
|
||||
.flatMap(({ outer }) => outer.map(([lon]) => wrap360(lon)))
|
||||
.sort((a, b) => a - b);
|
||||
if (values.length === 0) return null;
|
||||
let gapIndex = values.length - 1;
|
||||
let largestGap = values[0] + 360 - values.at(-1);
|
||||
for (let i = 0; i < values.length - 1; i += 1) {
|
||||
const gap = values[i + 1] - values[i];
|
||||
if (gap > largestGap) {
|
||||
largestGap = gap;
|
||||
gapIndex = i;
|
||||
}
|
||||
}
|
||||
const start = values[(gapIndex + 1) % values.length];
|
||||
let end = values[gapIndex];
|
||||
if (end < start) end += 360;
|
||||
const span = end - start;
|
||||
if (span >= 360 - 1e-9) return { west: -180, east: 180, crosses: false };
|
||||
const west = start > 180 ? start - 360 : start;
|
||||
const endOnCircle = end >= 360 ? end - 360 : end;
|
||||
const east = endOnCircle > 180 ? endOnCircle - 360 : endOnCircle;
|
||||
return { west, east, crosses: west > east };
|
||||
}
|
||||
|
||||
/**
|
||||
* Index a MultiPolygon for repeated containment tests: unwrapped rings with
|
||||
* per-part bounding boxes, plus the overall bbox as [west, south, east, north]
|
||||
* in −180..180 (west > east when it crosses the antimeridian).
|
||||
* @param {Array} coordinates MultiPolygon coordinates.
|
||||
* @returns {{parts: Array, bbox: number[], vertexCount: number, crossesAntimeridian: boolean}|null}
|
||||
*/
|
||||
export function prepareArea(coordinates) {
|
||||
const multi = normalizeMultiPolygon(coordinates);
|
||||
if (!multi) return null;
|
||||
let vertexCount = 0;
|
||||
let crosses = false;
|
||||
const parts = multi.map((polygon) => {
|
||||
const outer = unwrapRing(polygon[0]);
|
||||
if (outer !== polygon[0]) crosses = true;
|
||||
const holes = polygon.slice(1).map((ring) => {
|
||||
let hole = unwrapRing(ring);
|
||||
// Keep a hole in the same longitude frame as its outer ring.
|
||||
const hb = ringBbox(hole);
|
||||
const ob = ringBbox(outer);
|
||||
const mid = (hb[0] + hb[2]) / 2;
|
||||
if (mid < ob[0]) hole = hole.map(([x, y]) => [x + 360, y]);
|
||||
else if (mid > ob[2]) hole = hole.map(([x, y]) => [x - 360, y]);
|
||||
return hole;
|
||||
});
|
||||
for (const ring of polygon) vertexCount += ring.length;
|
||||
return { outer, holes, bbox: ringBbox(outer) };
|
||||
});
|
||||
let south = Infinity;
|
||||
let north = -Infinity;
|
||||
for (const { bbox } of parts) {
|
||||
south = Math.min(south, bbox[1]);
|
||||
north = Math.max(north, bbox[3]);
|
||||
}
|
||||
const envelope = longitudeEnvelope(parts);
|
||||
const bbox = [envelope.west, south, envelope.east, north];
|
||||
crosses ||= envelope.crosses;
|
||||
return { parts, bbox, vertexCount, crossesAntimeridian: crosses };
|
||||
}
|
||||
|
||||
function inPart(part, lon, lat) {
|
||||
const [w, s, e, n] = part.bbox;
|
||||
if (lat < s || lat > n || lon < w || lon > e) return false;
|
||||
if (!pointInRingXY(part.outer, lon, lat)) return false;
|
||||
for (const hole of part.holes)
|
||||
if (pointInRingXY(hole, lon, lat)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a point lies inside the area: inside some part's outer ring and in
|
||||
* none of that part's holes. Points exactly on an edge follow the ray-cast
|
||||
* convention and may land either side.
|
||||
* @param {object} prepared From prepareArea.
|
||||
* @param {number} lat
|
||||
* @param {number} lon
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function pointInPreparedArea(prepared, lat, lon) {
|
||||
if (!prepared || !Number.isFinite(lat) || !Number.isFinite(lon)) return false;
|
||||
for (const part of prepared.parts) {
|
||||
if (inPart(part, lon, lat)) return true;
|
||||
if (inPart(part, lon + 360, lat)) return true;
|
||||
if (inPart(part, lon - 360, lat)) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/** Spherical-excess ring area in km² (unsigned). */
|
||||
export function ringAreaKm2(ring) {
|
||||
const n = ring.length;
|
||||
if (n < 3) return 0;
|
||||
let sum = 0;
|
||||
for (let i = 0; i < n - 1; i += 1) {
|
||||
const [lon1, lat1] = ring[i];
|
||||
const [lon2, lat2] = ring[i + 1];
|
||||
sum +=
|
||||
toRad(lon2 - lon1) * (2 + Math.sin(toRad(lat1)) + Math.sin(toRad(lat2)));
|
||||
}
|
||||
return Math.abs((sum * EARTH_RADIUS_KM * EARTH_RADIUS_KM) / 2);
|
||||
}
|
||||
|
||||
/**
|
||||
* Area of a MultiPolygon in km², holes subtracted.
|
||||
* @param {Array} coordinates
|
||||
* @returns {number}
|
||||
*/
|
||||
export function multiPolygonAreaKm2(coordinates) {
|
||||
const multi = normalizeMultiPolygon(coordinates);
|
||||
if (!multi) return 0;
|
||||
let total = 0;
|
||||
for (const polygon of multi) {
|
||||
total += ringAreaKm2(unwrapRing(polygon[0]));
|
||||
for (const hole of polygon.slice(1)) total -= ringAreaKm2(unwrapRing(hole));
|
||||
}
|
||||
return Math.max(0, total);
|
||||
}
|
||||
|
||||
/** Counts of parts and holes. */
|
||||
export function multiPolygonCounts(coordinates) {
|
||||
const multi = normalizeMultiPolygon(coordinates) || [];
|
||||
return {
|
||||
parts: multi.length,
|
||||
holes: multi.reduce((sum, polygon) => sum + polygon.length - 1, 0),
|
||||
};
|
||||
}
|
||||
|
||||
/** Mean of the largest part's outer ring vertices, wrapped to −180..180. */
|
||||
export function areaAnchor(coordinates) {
|
||||
const multi = normalizeMultiPolygon(coordinates);
|
||||
if (!multi) return null;
|
||||
let best = null;
|
||||
let bestArea = -1;
|
||||
for (const polygon of multi) {
|
||||
const ring = unwrapRing(polygon[0]);
|
||||
const area = ringAreaKm2(ring);
|
||||
if (area > bestArea) {
|
||||
bestArea = area;
|
||||
best = ring;
|
||||
}
|
||||
}
|
||||
let lon = 0;
|
||||
let lat = 0;
|
||||
const pts = best.slice(0, -1);
|
||||
for (const [x, y] of pts) {
|
||||
lon += x;
|
||||
lat += y;
|
||||
}
|
||||
return { lon: wrap180(lon / pts.length), lat: lat / pts.length };
|
||||
}
|
||||
|
||||
// ── Display copies ────────────────────────────────────────────
|
||||
|
||||
function dpRing(ring, tol) {
|
||||
const n = ring.length;
|
||||
if (n <= 5) return ring;
|
||||
const keep = new Uint8Array(n);
|
||||
keep[0] = 1;
|
||||
keep[n - 1] = 1;
|
||||
const stack = [[0, n - 1]];
|
||||
while (stack.length) {
|
||||
const [a, b] = stack.pop();
|
||||
if (b - a < 2) continue;
|
||||
const [ax, ay] = ring[a];
|
||||
const vx = ring[b][0] - ax;
|
||||
const vy = ring[b][1] - ay;
|
||||
const c2 = vx * vx + vy * vy;
|
||||
let worst = -1;
|
||||
let worstD = tol;
|
||||
for (let i = a + 1; i < b; i += 1) {
|
||||
const wx = ring[i][0] - ax;
|
||||
const wy = ring[i][1] - ay;
|
||||
const t =
|
||||
c2 === 0 ? 0 : Math.max(0, Math.min(1, (vx * wx + vy * wy) / c2));
|
||||
const d = Math.hypot(wx - t * vx, wy - t * vy);
|
||||
if (d > worstD) {
|
||||
worstD = d;
|
||||
worst = i;
|
||||
}
|
||||
}
|
||||
if (worst >= 0) {
|
||||
keep[worst] = 1;
|
||||
stack.push([a, worst], [worst, b]);
|
||||
}
|
||||
}
|
||||
const out = [];
|
||||
for (let i = 0; i < n; i += 1) if (keep[i]) out.push(ring[i]);
|
||||
return out.length >= 4 ? out : ring;
|
||||
}
|
||||
|
||||
/**
|
||||
* A simplified copy of the area for drawing only: the largest `maxParts`
|
||||
* parts, each ring Douglas-Peucker simplified until the whole copy fits in
|
||||
* `maxVertices`. Rings keep their antimeridian-unwrapped longitudes so a
|
||||
* crossing part draws as one shape.
|
||||
* @param {Array} coordinates MultiPolygon coordinates.
|
||||
* @param {{maxVertices?: number, maxParts?: number}} [options]
|
||||
* @returns {{parts: Array<{outer: Array, holes: Array}>, drawnParts: number, totalParts: number}}
|
||||
*/
|
||||
export function displayParts(
|
||||
coordinates,
|
||||
{ maxVertices = 6000, maxParts = 40 } = {},
|
||||
) {
|
||||
const multi = normalizeMultiPolygon(coordinates) || [];
|
||||
const ranked = multi
|
||||
.map((polygon) => ({
|
||||
rings: polygon.map((ring) => unwrapRing(ring)),
|
||||
area: ringAreaKm2(unwrapRing(polygon[0])),
|
||||
}))
|
||||
.sort((a, b) => b.area - a.area)
|
||||
.slice(0, maxParts);
|
||||
const bbox = ranked.length ? ringBbox(ranked[0].rings[0]) : [0, 0, 0, 0];
|
||||
let tol = Math.max(
|
||||
1e-6,
|
||||
Math.max(bbox[2] - bbox[0], bbox[3] - bbox[1]) / 1500,
|
||||
);
|
||||
let parts = [];
|
||||
for (let attempt = 0; attempt < 12; attempt += 1) {
|
||||
parts = ranked.map(({ rings }) => ({
|
||||
outer: dpRing(rings[0], tol),
|
||||
holes: rings.slice(1).map((ring) => dpRing(ring, tol)),
|
||||
}));
|
||||
const total = parts.reduce(
|
||||
(sum, p) =>
|
||||
sum + p.outer.length + p.holes.reduce((h, r) => h + r.length, 0),
|
||||
0,
|
||||
);
|
||||
if (total <= maxVertices) break;
|
||||
tol *= 2;
|
||||
}
|
||||
return { parts, drawnParts: parts.length, totalParts: multi.length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A circle as a closed ring (planar metres around the centre — accurate for
|
||||
* the few-kilometre buffers it is used for).
|
||||
* @returns {Array<[number, number]>}
|
||||
*/
|
||||
export function circleRing(lat, lon, radiusM, segments = 48) {
|
||||
const mPerDegLat = 111_320;
|
||||
const mPerDegLon = mPerDegLat * Math.max(0.01, Math.cos(toRad(lat)));
|
||||
const ring = [];
|
||||
for (let i = 0; i < segments; i += 1) {
|
||||
const a = (i / segments) * Math.PI * 2;
|
||||
ring.push([
|
||||
lon + (Math.cos(a) * radiusM) / mPerDegLon,
|
||||
lat + (Math.sin(a) * radiusM) / mPerDegLat,
|
||||
]);
|
||||
}
|
||||
ring.push([ring[0][0], ring[0][1]]);
|
||||
return ring;
|
||||
}
|
||||
@@ -0,0 +1,178 @@
|
||||
// Area geometry: containment over full MultiPolygons (islands, holes, the
|
||||
// antimeridian), OSM relation assembly and display copies that never touch the
|
||||
// counting geometry.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
circleRing,
|
||||
displayParts,
|
||||
multiPolygonAreaKm2,
|
||||
multiPolygonCounts,
|
||||
normalizeMultiPolygon,
|
||||
pointInPreparedArea,
|
||||
prepareArea,
|
||||
} from './areaGeometry.js';
|
||||
|
||||
const square = (w, s, e, n) => [
|
||||
[w, s],
|
||||
[e, s],
|
||||
[e, n],
|
||||
[w, n],
|
||||
[w, s],
|
||||
];
|
||||
|
||||
test('a point on an island counts, not only on the largest part', () => {
|
||||
// Mainland 0..10, island 20..22: the old largest-ring shortcut dropped the island.
|
||||
const area = prepareArea([[square(0, 0, 10, 10)], [square(20, 0, 22, 2)]]);
|
||||
assert.equal(pointInPreparedArea(area, 5, 5), true);
|
||||
assert.equal(pointInPreparedArea(area, 1, 21), true);
|
||||
assert.equal(pointInPreparedArea(area, 1, 15), false);
|
||||
});
|
||||
|
||||
test('a point inside a hole is outside the area', () => {
|
||||
const area = prepareArea([[square(0, 0, 10, 10), square(4, 4, 6, 6)]]);
|
||||
assert.equal(pointInPreparedArea(area, 5, 5), false);
|
||||
assert.equal(pointInPreparedArea(area, 2, 2), true);
|
||||
// An island inside the hole (an enclave within an enclave) counts again.
|
||||
const nested = prepareArea([
|
||||
[square(0, 0, 10, 10), square(3, 3, 7, 7)],
|
||||
[square(4, 4, 6, 6)],
|
||||
]);
|
||||
assert.equal(pointInPreparedArea(nested, 5, 5), true);
|
||||
assert.equal(pointInPreparedArea(nested, 3.5, 3.5), false);
|
||||
});
|
||||
|
||||
test('a ring crossing the antimeridian contains points on both sides', () => {
|
||||
// 175E → 175W as one continuous ring (a drawn box over Fiji).
|
||||
const ring = [
|
||||
[175, -20],
|
||||
[-175, -20],
|
||||
[-175, -15],
|
||||
[175, -15],
|
||||
[175, -20],
|
||||
];
|
||||
const area = prepareArea([[ring]]);
|
||||
assert.equal(area.crossesAntimeridian, true);
|
||||
assert.equal(pointInPreparedArea(area, -17, 178), true);
|
||||
assert.equal(pointInPreparedArea(area, -17, -178), true);
|
||||
assert.equal(pointInPreparedArea(area, -17, 0), false);
|
||||
assert.equal(pointInPreparedArea(area, -17, 170), false);
|
||||
// bbox is west > east across the line.
|
||||
assert.deepEqual(area.bbox, [175, -20, -175, -15]);
|
||||
// Area of a 10°×5° box near 17°S, not the 350° long way round.
|
||||
const km2 = multiPolygonAreaKm2([[ring]]);
|
||||
assert.ok(km2 > 500_000 && km2 < 620_000, `area ${km2}`);
|
||||
});
|
||||
|
||||
test('a multipolygon split at ±180 keeps a tight bbox', () => {
|
||||
const area = prepareArea([
|
||||
[square(177, -19, 180, -16)],
|
||||
[square(-180, -19, -178, -16)],
|
||||
]);
|
||||
assert.equal(area.crossesAntimeridian, true);
|
||||
assert.deepEqual(area.bbox, [177, -19, -178, -16]);
|
||||
assert.equal(pointInPreparedArea(area, -17, -179), true);
|
||||
assert.equal(pointInPreparedArea(area, -17, 179), true);
|
||||
});
|
||||
|
||||
test('a crossing part and a separate island share one tight longitude frame', () => {
|
||||
const crossing = [
|
||||
[175, -20],
|
||||
[-175, -20],
|
||||
[-175, -15],
|
||||
[175, -15],
|
||||
[175, -20],
|
||||
];
|
||||
const area = prepareArea([[crossing], [square(-170, -19, -160, -16)]]);
|
||||
assert.equal(area.crossesAntimeridian, true);
|
||||
assert.deepEqual(area.bbox, [175, -20, -160, -15]);
|
||||
assert.equal(pointInPreparedArea(area, -17, 178), true);
|
||||
assert.equal(pointInPreparedArea(area, -17, -165), true);
|
||||
assert.equal(pointInPreparedArea(area, -17, 0), false);
|
||||
});
|
||||
|
||||
test('normalization closes rings and drops degenerate parts', () => {
|
||||
const multi = normalizeMultiPolygon({
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[0, 0],
|
||||
[1, 0],
|
||||
[1, 1],
|
||||
],
|
||||
[
|
||||
[0.2, 0.2],
|
||||
[0.2, 0.2],
|
||||
],
|
||||
],
|
||||
});
|
||||
assert.equal(multi.length, 1);
|
||||
assert.equal(multi[0].length, 1, 'degenerate hole dropped');
|
||||
assert.deepEqual(multi[0][0][0], multi[0][0][3]);
|
||||
assert.equal(
|
||||
normalizeMultiPolygon({ type: 'LineString', coordinates: [] }),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
normalizeMultiPolygon([
|
||||
[
|
||||
[0, 0],
|
||||
[1, 1],
|
||||
],
|
||||
]),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('area subtracts holes and counts parts', () => {
|
||||
const coords = [
|
||||
[square(0, 0, 1, 1), square(0.25, 0.25, 0.75, 0.75)],
|
||||
[square(5, 5, 6, 6)],
|
||||
];
|
||||
const whole = multiPolygonAreaKm2([[square(0, 0, 1, 1)]]);
|
||||
const km2 = multiPolygonAreaKm2(coords);
|
||||
assert.ok(km2 < whole * 2 && km2 > whole * 1.7, `${km2} vs ${whole}`);
|
||||
assert.deepEqual(multiPolygonCounts(coords), { parts: 2, holes: 1 });
|
||||
});
|
||||
|
||||
test('display copies are bounded and leave the counting geometry intact', () => {
|
||||
const dense = [];
|
||||
for (let i = 0; i < 20_000; i += 1) {
|
||||
const a = (i / 20_000) * Math.PI * 2;
|
||||
dense.push([
|
||||
Math.cos(a) * (1 + 0.01 * Math.sin(a * 200)),
|
||||
Math.sin(a) * (1 + 0.01 * Math.sin(a * 200)),
|
||||
]);
|
||||
}
|
||||
dense.push(dense[0].slice());
|
||||
const coords = [[dense]];
|
||||
const snapshot = JSON.stringify(coords);
|
||||
const shown = displayParts(coords, { maxVertices: 2000 });
|
||||
const total = shown.parts.reduce((sum, p) => sum + p.outer.length, 0);
|
||||
assert.ok(total <= 2000, `${total} vertices`);
|
||||
assert.equal(JSON.stringify(coords), snapshot, 'input untouched');
|
||||
// A point the simplified copy might shave off still counts on the original.
|
||||
const area = prepareArea(coords);
|
||||
assert.equal(pointInPreparedArea(area, 0, 0), true);
|
||||
});
|
||||
|
||||
test('display copies keep the largest parts first', () => {
|
||||
const coords = [
|
||||
[square(0, 0, 1, 1)],
|
||||
[square(10, 10, 15, 15)],
|
||||
[square(20, 20, 20.1, 20.1)],
|
||||
];
|
||||
const shown = displayParts(coords, { maxParts: 2 });
|
||||
assert.equal(shown.totalParts, 3);
|
||||
assert.equal(shown.drawnParts, 2);
|
||||
assert.equal(shown.parts[0].outer[0][0], 10);
|
||||
});
|
||||
|
||||
test('a circle ring is closed and about the requested radius', () => {
|
||||
const ring = circleRing(37.8, -122.39, 500);
|
||||
assert.deepEqual(ring[0], ring[ring.length - 1]);
|
||||
const km2 = multiPolygonAreaKm2([[ring]]);
|
||||
assert.ok(Math.abs(km2 - Math.PI * 0.25) < 0.02, `${km2}`);
|
||||
});
|
||||
@@ -0,0 +1,668 @@
|
||||
/**
|
||||
* Named place → area handle, through the outline ladder that needs no public
|
||||
* Overpass:
|
||||
*
|
||||
* 1. the area store (a query already resolved this session);
|
||||
* 2. bundled Natural Earth physical/marine regions;
|
||||
* 3. bundled countries and states/provinces by name — a name several
|
||||
* prominent units share ("Georgia", "Punjab") asks which one, unless
|
||||
* the view is inside exactly one of them;
|
||||
* 4. the annotation outline ladder (`resolveNamedOutline`): bundled
|
||||
* counties, US Census places and neighbourhood packs, then the guarded
|
||||
* Nominatim outline route, then Overpass only when an operator
|
||||
* configured it.
|
||||
*
|
||||
* Providers are injected, so the ladder runs under node:test:
|
||||
* findNaturalRegion(query) → {name, polygons, kind}|null
|
||||
* findAdminCandidates(query) → Array<AdminArea> (see data/adminBoundaries.js)
|
||||
* resolveNamedOutline(query, {level, levelHint, signal}) →
|
||||
* {ok:true, name, polygons, source, rung, approximate?, country?}
|
||||
* |{ok:false, code, error}
|
||||
* viewCenter() → {lat, lon}|null
|
||||
*
|
||||
* @module data/areaResolver
|
||||
*/
|
||||
|
||||
import { AREA_LEVELS } from './areaStore.js';
|
||||
import { pointInPreparedArea, prepareArea } from './areaGeometry.js';
|
||||
import { adminQueryIdentity, normalizeAdminName } from './adminBoundaries.js';
|
||||
import {
|
||||
isAreaCandidateId,
|
||||
MAX_AREA_CANDIDATE_ID_LENGTH,
|
||||
} from '../voice/areaCandidateContract.js';
|
||||
export {
|
||||
AREA_CANDIDATE_ID_PATTERN,
|
||||
isAreaCandidateId,
|
||||
MAX_AREA_CANDIDATE_ID_LENGTH,
|
||||
} from '../voice/areaCandidateContract.js';
|
||||
|
||||
/** Most candidates a clarification offers. */
|
||||
export const MAX_AREA_CANDIDATES = 4;
|
||||
/** Candidates remembered for a follow-up `candidateId`. */
|
||||
const CANDIDATE_MEMORY = 24;
|
||||
|
||||
/**
|
||||
* A place name as a cache and matching key: case-folded and NFKC-normalized,
|
||||
* punctuation dropped, letters, marks and digits in every script kept (東京
|
||||
* and 大阪 are different keys). Empty when the text names nothing.
|
||||
*/
|
||||
export function normalizeAreaQuery(text) {
|
||||
return String(text || '')
|
||||
.normalize('NFKC')
|
||||
.toLowerCase()
|
||||
.replace(/[^\p{L}\p{M}\p{N} ]+/gu, ' ')
|
||||
.replace(/\s+/g, ' ')
|
||||
.trim()
|
||||
.replace(/^the /, '');
|
||||
}
|
||||
|
||||
/** Words that name the kind of area rather than the area. */
|
||||
const LEVEL_WORDS = [
|
||||
[/\b(province|state|region|oblast|prefecture|canton|governorate)$/, 'admin1'],
|
||||
[/\b(county|district|department)$/, 'admin2'],
|
||||
[/\b(city|town|municipality|metropolitan city)$/, 'city'],
|
||||
[/\b(neighbou?rhood|borough|suburb|quarter)$/, 'district'],
|
||||
[/\b(country|nation)$/, 'country'],
|
||||
];
|
||||
|
||||
/**
|
||||
* Strip a trailing level word ("Bagmati province" → "bagmati", admin1). The
|
||||
* word is kept as a hint, not a filter, since names often contain it.
|
||||
*/
|
||||
export function splitLevelWord(query) {
|
||||
const norm = normalizeAreaQuery(query);
|
||||
for (const [re, level] of LEVEL_WORDS) {
|
||||
if (re.test(norm)) {
|
||||
const bare = norm.replace(re, '').trim();
|
||||
if (bare) return { bare, level };
|
||||
}
|
||||
}
|
||||
return { bare: norm, level: null };
|
||||
}
|
||||
|
||||
/** Area level of a bundled admin unit. */
|
||||
const ADMIN_LEVEL = Object.freeze({
|
||||
country: 'country',
|
||||
state: 'admin1',
|
||||
county: 'admin2',
|
||||
natural: 'natural',
|
||||
});
|
||||
|
||||
/**
|
||||
* One of several same-name natural places as a clarification choice, located
|
||||
* by its rough centre ("39 N 31 W") since it has no country.
|
||||
*/
|
||||
function naturalCandidate(place, kind) {
|
||||
const { lat, lon } = place.center || {};
|
||||
const locator = Number.isFinite(lat)
|
||||
? `${Math.abs(Math.round(lat))} ${lat >= 0 ? 'N' : 'S'} ${Math.abs(Math.round(lon))} ${lon >= 0 ? 'E' : 'W'}`
|
||||
: '';
|
||||
return {
|
||||
kind: 'natural',
|
||||
name: place.name,
|
||||
country: '',
|
||||
regionCode: locator,
|
||||
polygons: place.polygons.map((ring) => [ring]),
|
||||
source: 'natural-earth',
|
||||
meta: { kind },
|
||||
};
|
||||
}
|
||||
|
||||
const ADMIN_NAME_LEVEL = Object.freeze({
|
||||
country: 'country',
|
||||
nation: 'country',
|
||||
province: 'admin1',
|
||||
state: 'admin1',
|
||||
region: 'admin1',
|
||||
oblast: 'admin1',
|
||||
prefecture: 'admin1',
|
||||
canton: 'admin1',
|
||||
governorate: 'admin1',
|
||||
county: 'admin2',
|
||||
district: 'admin2',
|
||||
department: 'admin2',
|
||||
});
|
||||
|
||||
/**
|
||||
* Drop accents from Latin letters only, for comparing names: speech often
|
||||
* loses them ("Quebec" for "Québec"), while a Thai or Devanagari mark changes
|
||||
* the name and is kept.
|
||||
*/
|
||||
export function foldLatinMarks(text) {
|
||||
return String(text || '')
|
||||
.normalize('NFD')
|
||||
.replace(/(\p{Script=Latin})\p{M}+/gu, '$1')
|
||||
.normalize('NFC');
|
||||
}
|
||||
|
||||
function explicitAdminName(text) {
|
||||
const normalized = normalizeAreaQuery(String(text).split(',')[0]);
|
||||
const match = normalized.match(
|
||||
/\b(country|nation|province|state|region|zone|oblast|prefecture|canton|governorate|county|district|department)$/,
|
||||
);
|
||||
return {
|
||||
normalized,
|
||||
bare: foldLatinMarks(
|
||||
match ? normalized.slice(0, -match[0].length).trim() : normalized,
|
||||
),
|
||||
word: match?.[1] || null,
|
||||
level: match ? ADMIN_NAME_LEVEL[match[1]] || null : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Fail closed when a bundled unit's own name contradicts the requested unit.
|
||||
* With `aliases`, an ask the administrative matcher reads as naming this very
|
||||
* unit at its level ("State of Texas", "USA") also matches; the natural-region
|
||||
* check leaves it off, since "Great Britain" is not the United Kingdom.
|
||||
*/
|
||||
function bundledAdminIdentityRefusal(
|
||||
admin,
|
||||
query,
|
||||
wantedLevel,
|
||||
{ aliases = true } = {},
|
||||
) {
|
||||
const source = explicitAdminName(admin?.name || '');
|
||||
const requested = explicitAdminName(query);
|
||||
const expectedLevel = wantedLevel || requested.level;
|
||||
const emittedLevel = ADMIN_LEVEL[admin?.kind] || null;
|
||||
if (!source.normalized || source.word === 'zone')
|
||||
return {
|
||||
ok: false,
|
||||
code: 'AREA_IDENTITY_UNVERIFIED',
|
||||
error: `The bundled boundary is ${admin?.name || 'an unverified administrative unit'}, not a verified current match for "${query}".`,
|
||||
};
|
||||
const alias = aliases ? adminQueryIdentity(query) : null;
|
||||
const named =
|
||||
source.bare === requested.bare ||
|
||||
Boolean(
|
||||
alias &&
|
||||
alias.level === emittedLevel &&
|
||||
alias.name === normalizeAdminName(admin.name),
|
||||
);
|
||||
if (
|
||||
!named ||
|
||||
(source.level && expectedLevel && source.level !== expectedLevel) ||
|
||||
(expectedLevel && emittedLevel !== expectedLevel)
|
||||
)
|
||||
return {
|
||||
ok: false,
|
||||
code: 'AREA_IDENTITY_MISMATCH',
|
||||
error: `The bundled boundary is ${admin.name}, not the requested administrative area "${query}".`,
|
||||
};
|
||||
return null;
|
||||
}
|
||||
|
||||
function stableCandidateHash(value) {
|
||||
let hash = 0x811c9dc5;
|
||||
for (const char of String(value)) {
|
||||
hash ^= char.codePointAt(0);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
return (hash >>> 0).toString(16).padStart(8, '0');
|
||||
}
|
||||
|
||||
function candidateIdOf(admin) {
|
||||
const prefix = `ne:${admin.kind}:`;
|
||||
// The region code keeps same-named units apart: "Washington" is both WA
|
||||
// and DC, which would otherwise share one candidate and one stored area.
|
||||
const slug = normalizeAreaQuery(
|
||||
`${admin.country} ${admin.name} ${admin.regionCode || ''}`,
|
||||
).replace(/ /g, '-');
|
||||
const full = `${prefix}${slug}`;
|
||||
if (full.length <= MAX_AREA_CANDIDATE_ID_LENGTH) return full;
|
||||
const suffix = `-${stableCandidateHash(slug)}`;
|
||||
let shortened = '';
|
||||
for (const char of slug) {
|
||||
if (
|
||||
`${prefix}${shortened}${char}${suffix}`.length >
|
||||
MAX_AREA_CANDIDATE_ID_LENGTH
|
||||
)
|
||||
break;
|
||||
shortened += char;
|
||||
}
|
||||
return `${prefix}${shortened.replace(/-+$/u, '')}${suffix}`;
|
||||
}
|
||||
|
||||
/** Short, speakable identity for a clarification choice. */
|
||||
function describeCandidate(admin) {
|
||||
return {
|
||||
candidateId: candidateIdOf(admin),
|
||||
name: admin.name,
|
||||
level: ADMIN_LEVEL[admin.kind] || null,
|
||||
// Tells same-named units apart when spoken: Washington WA vs DC.
|
||||
...(admin.regionCode && admin.kind !== 'country'
|
||||
? { region: String(admin.regionCode) }
|
||||
: {}),
|
||||
...(admin.country && admin.kind !== 'country'
|
||||
? { country: admin.country }
|
||||
: {}),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Distinct places among bundled candidates. Within one country, the country
|
||||
* itself stands for its same-named state ("Mexico" is the country, not the
|
||||
* State of Mexico); across countries each name is its own place.
|
||||
*/
|
||||
/** A coarse ~2° cell of the view, or "none", for keying view-picked answers. */
|
||||
function viewCell(center) {
|
||||
if (!Number.isFinite(center?.lat) || !Number.isFinite(center?.lon))
|
||||
return 'none';
|
||||
return `${Math.floor(center.lat / 2)},${Math.floor(center.lon / 2)}`;
|
||||
}
|
||||
|
||||
export function distinctAdminPlaces(candidates) {
|
||||
const byCountry = new Map();
|
||||
for (const admin of candidates) {
|
||||
const list = byCountry.get(admin.country) || [];
|
||||
list.push(admin);
|
||||
byCountry.set(admin.country, list);
|
||||
}
|
||||
const out = [];
|
||||
for (const list of byCountry.values()) {
|
||||
const country = list.find((admin) => admin.kind === 'country');
|
||||
out.push(...(country ? [country] : list));
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a resolver bound to an area store and providers.
|
||||
* @param {object} options
|
||||
*/
|
||||
export function createAreaResolver({
|
||||
store,
|
||||
findNaturalRegion = async () => null,
|
||||
findAdminCandidates = async () => [],
|
||||
resolveNamedOutline = async () => ({
|
||||
ok: false,
|
||||
code: 'AREA_UNAVAILABLE',
|
||||
error: 'Boundary lookup is unavailable here.',
|
||||
}),
|
||||
viewCenter = () => null,
|
||||
onCredit = () => {},
|
||||
now = () => Date.now(),
|
||||
maxInFlight = 8,
|
||||
} = {}) {
|
||||
if (!store) throw new TypeError('An area store is required');
|
||||
/** candidateId → bundled unit and original ask, for a clarification answered later. */
|
||||
const candidateMemory = new Map();
|
||||
/** query key → in-flight lookup, so a repeat joins the first. */
|
||||
const inFlight = new Map();
|
||||
const lifetime = new AbortController();
|
||||
const inFlightLimit = Number.isFinite(maxInFlight)
|
||||
? Math.max(1, Math.floor(maxInFlight))
|
||||
: 8;
|
||||
let activeLookups = 0;
|
||||
let disposed = false;
|
||||
|
||||
const assertActive = () => lifetime.signal.throwIfAborted();
|
||||
|
||||
const remember = (admin, identity) => {
|
||||
const id = candidateIdOf(admin);
|
||||
candidateMemory.delete(id);
|
||||
candidateMemory.set(id, { admin, identity });
|
||||
while (candidateMemory.size > CANDIDATE_MEMORY)
|
||||
candidateMemory.delete(candidateMemory.keys().next().value);
|
||||
};
|
||||
|
||||
function storeAdmin(admin, confidence, identity) {
|
||||
assertActive();
|
||||
const refused = bundledAdminIdentityRefusal(
|
||||
admin,
|
||||
identity?.query,
|
||||
identity?.wantedLevel,
|
||||
);
|
||||
if (refused) return refused;
|
||||
const record = store.put({
|
||||
geometry: admin.polygons,
|
||||
name: admin.name,
|
||||
level: ADMIN_LEVEL[admin.kind] || null,
|
||||
source: admin.source,
|
||||
sourceId: candidateIdOf(admin),
|
||||
meta: {
|
||||
...(admin.kind !== 'country' && admin.country
|
||||
? { country: admin.country }
|
||||
: {}),
|
||||
rung: 'bundled',
|
||||
},
|
||||
});
|
||||
if (!record)
|
||||
return {
|
||||
ok: false,
|
||||
code: 'AREA_NOT_FOUND',
|
||||
error: `The boundary for ${admin.name} is not a usable polygon.`,
|
||||
};
|
||||
onCredit(admin.source);
|
||||
return { ok: true, record, confidence, rung: 'bundled' };
|
||||
}
|
||||
|
||||
async function lookup({ query, level, within }, { signal }) {
|
||||
const { level: levelHint } = splitLevelWord(query);
|
||||
const searchText = within ? `${query}, ${within}` : query;
|
||||
let bundledRefusal = null;
|
||||
// Offline first: a named natural region, unless an admin level or a
|
||||
// country/state qualifier was given (the pack cannot check `within`).
|
||||
if ((!level || level === 'natural') && !within) {
|
||||
const ne = await findNaturalRegion(query, { signal }).catch(() => null);
|
||||
signal?.throwIfAborted?.();
|
||||
// A region named like a country or state ("India" the peninsula,
|
||||
// "Punjab" the desert) never hides it; asked for by level, it answers.
|
||||
// Only a unit that really has this name counts: "Great Britain" finds
|
||||
// the United Kingdom by alias, which is not a Great Britain.
|
||||
// A feature split into parts is one place with every part; distant
|
||||
// namesakes (Flores in the Azores and Indonesia) are asked about.
|
||||
const places = ne?.places?.length
|
||||
? ne.places
|
||||
: ne?.polygons?.length
|
||||
? [{ name: ne.name, polygons: ne.polygons }]
|
||||
: [];
|
||||
const shadowsAdmin =
|
||||
places.length > 0 &&
|
||||
level !== 'natural' &&
|
||||
(await findAdminCandidates(query, { signal }).catch(() => [])).some(
|
||||
(admin) =>
|
||||
!bundledAdminIdentityRefusal(admin, query, null, {
|
||||
aliases: false,
|
||||
}),
|
||||
);
|
||||
signal?.throwIfAborted?.();
|
||||
if (places.length > 1 && !shadowsAdmin) {
|
||||
const offered = places
|
||||
.slice(0, MAX_AREA_CANDIDATES)
|
||||
.map((place) => naturalCandidate(place, ne.kind));
|
||||
const identity = { query, wantedLevel: 'natural' };
|
||||
offered.forEach((admin) => remember(admin, identity));
|
||||
return {
|
||||
ok: false,
|
||||
needsClarification: true,
|
||||
code: 'AMBIGUOUS_AREA',
|
||||
candidates: offered.map(describeCandidate),
|
||||
error: `"${query}" names ${offered.length} places — ask which one.`,
|
||||
};
|
||||
}
|
||||
if (places.length === 1 && !shadowsAdmin) {
|
||||
const record = store.put({
|
||||
geometry: places[0].polygons.map((ring) => [ring]),
|
||||
name: ne.name,
|
||||
level: 'natural',
|
||||
source: 'natural-earth',
|
||||
sourceId: `ne:${normalizeAreaQuery(ne.name).replace(/ /g, '-')}`,
|
||||
meta: { kind: ne.kind, rung: 'bundled' },
|
||||
});
|
||||
if (record) {
|
||||
onCredit('natural-earth');
|
||||
return { ok: true, record, confidence: 0.95, rung: 'bundled' };
|
||||
}
|
||||
}
|
||||
}
|
||||
signal?.throwIfAborted?.();
|
||||
// Bundled countries and states by name. A name prominent units share is
|
||||
// asked about, never guessed — except when the view is inside one.
|
||||
const wanted = level || levelHint;
|
||||
if (!wanted || wanted === 'country' || wanted === 'admin1') {
|
||||
let admins = await findAdminCandidates(searchText, { signal }).catch(
|
||||
() => [],
|
||||
);
|
||||
signal?.throwIfAborted?.();
|
||||
if (wanted) admins = admins.filter((a) => ADMIN_LEVEL[a.kind] === wanted);
|
||||
let places = distinctAdminPlaces(admins);
|
||||
const identity = { query, wantedLevel: wanted };
|
||||
const checked = places.map((admin) => ({
|
||||
admin,
|
||||
refused: bundledAdminIdentityRefusal(admin, query, wanted),
|
||||
}));
|
||||
places = checked
|
||||
.filter(({ refused }) => !refused)
|
||||
.map(({ admin }) => admin);
|
||||
if (!places.length && checked.length) {
|
||||
const refused = checked.find((entry) => entry.refused)?.refused;
|
||||
// A retired or unverifiable unit is final. A different unit that
|
||||
// merely shares the name ("Azad Kashmir" for "Kashmir") is not an
|
||||
// answer, so the outline ladder still gets to look.
|
||||
if (refused?.code !== 'AREA_IDENTITY_MISMATCH') return refused;
|
||||
bundledRefusal = refused;
|
||||
}
|
||||
if (places.length === 1) {
|
||||
return storeAdmin(places[0], 0.95, identity);
|
||||
}
|
||||
if (places.length > 1) {
|
||||
const center = viewCenter();
|
||||
const holding = center
|
||||
? places.filter((admin) => {
|
||||
const prepared = prepareArea(admin.polygons);
|
||||
return (
|
||||
prepared &&
|
||||
pointInPreparedArea(prepared, center.lat, center.lon)
|
||||
);
|
||||
})
|
||||
: [];
|
||||
// Chosen by the view, so never remembered for the name: asked again
|
||||
// over the other one, it answers the other one.
|
||||
if (holding.length === 1)
|
||||
return { ...storeAdmin(holding[0], 0.85, identity), byView: true };
|
||||
const offered = places.slice(0, MAX_AREA_CANDIDATES);
|
||||
offered.forEach((admin) => remember(admin, identity));
|
||||
return {
|
||||
ok: false,
|
||||
needsClarification: true,
|
||||
code: 'AMBIGUOUS_AREA',
|
||||
candidates: offered.map(describeCandidate),
|
||||
error: `"${query}" names ${offered.length} places — ask which one.`,
|
||||
};
|
||||
}
|
||||
}
|
||||
signal?.throwIfAborted?.();
|
||||
// Everything else: the annotation outline ladder.
|
||||
const outline = await resolveNamedOutline(searchText, {
|
||||
level,
|
||||
levelHint,
|
||||
signal,
|
||||
});
|
||||
signal?.throwIfAborted?.();
|
||||
if (!outline?.ok)
|
||||
return (
|
||||
bundledRefusal || {
|
||||
ok: false,
|
||||
code: outline?.code || 'AREA_NOT_FOUND',
|
||||
error: outline?.error || `No boundary found for "${query}".`,
|
||||
}
|
||||
);
|
||||
const record = store.put({
|
||||
geometry: outline.polygons,
|
||||
name: outline.name || query,
|
||||
level: level || levelHint || outline.adminLevel || null,
|
||||
source: outline.approximate ? 'approximate' : outline.source,
|
||||
approximate: Boolean(outline.approximate),
|
||||
meta: {
|
||||
...(outline.country ? { country: outline.country } : {}),
|
||||
...(outline.adminName ? { adminName: outline.adminName } : {}),
|
||||
...(outline.adminLevel ? { adminLevel: outline.adminLevel } : {}),
|
||||
rung: outline.rung || null,
|
||||
...(outline.basis ? { basis: outline.basis } : {}),
|
||||
},
|
||||
});
|
||||
if (!record)
|
||||
return {
|
||||
ok: false,
|
||||
code: 'AREA_NOT_FOUND',
|
||||
error: `The boundary for ${query} is not a usable polygon.`,
|
||||
};
|
||||
return {
|
||||
ok: true,
|
||||
record,
|
||||
confidence: outline.approximate ? 0.5 : 0.8,
|
||||
rung: outline.rung || null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve a place to an area handle.
|
||||
* @param {{query?: string, level?: string, within?: string, candidateId?: string}} args
|
||||
* @param {{signal?: AbortSignal, budgetMs?: number}} [options] Past the
|
||||
* budget the call answers AREA_TIMEOUT while the lookup continues and
|
||||
* fills the caches, so asking again shortly is fast.
|
||||
* @returns {Promise<object>}
|
||||
*/
|
||||
async function resolve(args = {}, { signal, budgetMs = 8000 } = {}) {
|
||||
const started = now();
|
||||
const level = AREA_LEVELS.includes(args.level) ? args.level : null;
|
||||
const within = String(args.within || '').trim();
|
||||
const candidateId = String(args.candidateId || '').trim();
|
||||
const finish = (result, cached = false) => ({
|
||||
...result,
|
||||
cached,
|
||||
ms: now() - started,
|
||||
});
|
||||
|
||||
if (disposed)
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'CANCELLED',
|
||||
cancelled: true,
|
||||
error: 'Area resolver has been disposed.',
|
||||
});
|
||||
|
||||
if (candidateId) {
|
||||
if (!isAreaCandidateId(candidateId))
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'BAD_CANDIDATE',
|
||||
error:
|
||||
'candidateId is malformed or too long. Resolve the name again.',
|
||||
});
|
||||
const remembered = candidateMemory.get(candidateId);
|
||||
if (!remembered)
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'UNKNOWN_CANDIDATE',
|
||||
error: `Unknown candidateId "${candidateId}". Resolve the name again.`,
|
||||
});
|
||||
if (signal?.aborted)
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'CANCELLED',
|
||||
cancelled: true,
|
||||
error: 'This request was superseded.',
|
||||
});
|
||||
return finish(storeAdmin(remembered.admin, 0.9, remembered.identity));
|
||||
}
|
||||
|
||||
const query = String(args.query || '').trim();
|
||||
if (!query)
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'BAD_AREA',
|
||||
error: 'Name a place to resolve.',
|
||||
});
|
||||
const nameKey = normalizeAreaQuery(query);
|
||||
// The outline ladder and geocoder pick by the view ("Springfield" over
|
||||
// Illinois), so an answer is reused or shared only within the same
|
||||
// ~2° view cell. A name that normalizes to nothing is never cached.
|
||||
const key = nameKey
|
||||
? `${nameKey}|${level || ''}|${normalizeAreaQuery(within)}|${viewCell(viewCenter())}`
|
||||
: null;
|
||||
const recalled = key ? store.recallQuery(key) : null;
|
||||
if (recalled)
|
||||
return finish(
|
||||
{ ok: true, record: recalled, confidence: 0.95, rung: 'store' },
|
||||
true,
|
||||
);
|
||||
|
||||
let pending = key ? inFlight.get(key) : null;
|
||||
if (!pending) {
|
||||
if (activeLookups >= inFlightLimit)
|
||||
return finish({
|
||||
ok: false,
|
||||
code: 'AREA_BUSY',
|
||||
error:
|
||||
'Too many area lookups are already running — try again shortly.',
|
||||
});
|
||||
// The shared lookup outlives any one caller's signal: a superseded turn
|
||||
// must not cancel the answer a repeat is waiting on. The resolver's own
|
||||
// lifetime still owns the provider work, so final teardown stops it.
|
||||
activeLookups += 1;
|
||||
pending = lookup({ query, level, within }, { signal: lifetime.signal })
|
||||
.then((result) => {
|
||||
assertActive();
|
||||
if (result.ok && key && !result.byView)
|
||||
store.rememberQuery(key, result.record.areaId);
|
||||
return result;
|
||||
})
|
||||
.catch((error) =>
|
||||
lifetime.signal.aborted
|
||||
? {
|
||||
ok: false,
|
||||
code: 'CANCELLED',
|
||||
cancelled: true,
|
||||
error: 'Area resolver has been disposed.',
|
||||
}
|
||||
: {
|
||||
ok: false,
|
||||
code: 'AREA_UNAVAILABLE',
|
||||
error: error?.message || 'Boundary lookup failed.',
|
||||
},
|
||||
)
|
||||
.finally(() => {
|
||||
activeLookups -= 1;
|
||||
if (key) inFlight.delete(key);
|
||||
});
|
||||
if (key) inFlight.set(key, pending);
|
||||
}
|
||||
let timer;
|
||||
const racers = [pending];
|
||||
if (Number.isFinite(budgetMs))
|
||||
racers.push(
|
||||
new Promise((resolveTimeout) => {
|
||||
timer = setTimeout(
|
||||
() =>
|
||||
resolveTimeout({
|
||||
ok: false,
|
||||
code: 'AREA_TIMEOUT',
|
||||
error: `Looking up "${query}" is taking a while — ask again in a moment.`,
|
||||
}),
|
||||
budgetMs,
|
||||
);
|
||||
}),
|
||||
);
|
||||
// Detached once this call settles: a caller's long-lived signal must not
|
||||
// collect one listener per completed lookup.
|
||||
let cancelled = null;
|
||||
if (signal)
|
||||
racers.push(
|
||||
new Promise((resolveAbort) => {
|
||||
const superseded = {
|
||||
ok: false,
|
||||
code: 'CANCELLED',
|
||||
cancelled: true,
|
||||
error: 'Superseded.',
|
||||
};
|
||||
if (signal.aborted) return resolveAbort(superseded);
|
||||
cancelled = () => resolveAbort(superseded);
|
||||
signal.addEventListener?.('abort', cancelled, { once: true });
|
||||
return undefined;
|
||||
}),
|
||||
);
|
||||
try {
|
||||
return finish(await Promise.race(racers));
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
if (cancelled) signal.removeEventListener?.('abort', cancelled);
|
||||
}
|
||||
}
|
||||
|
||||
function dispose() {
|
||||
if (disposed) return;
|
||||
disposed = true;
|
||||
lifetime.abort();
|
||||
inFlight.clear();
|
||||
candidateMemory.clear();
|
||||
}
|
||||
|
||||
return {
|
||||
resolve,
|
||||
dispose,
|
||||
candidate: (id) => candidateMemory.get(id) || null,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,896 @@
|
||||
// Area handles: the session store and the resolution ladder (bundled Natural
|
||||
// Earth regions → bundled countries and states → the annotation outline
|
||||
// ladder), with every rung mocked. Pins the clarification contract for
|
||||
// ambiguous names and the fast cached path.
|
||||
//
|
||||
// Run with: npm test
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createAreaStore, summarizeArea } from './areaStore.js';
|
||||
import {
|
||||
AREA_CANDIDATE_ID_PATTERN,
|
||||
createAreaResolver,
|
||||
distinctAdminPlaces,
|
||||
isAreaCandidateId,
|
||||
MAX_AREA_CANDIDATE_ID_LENGTH,
|
||||
splitLevelWord,
|
||||
} from './areaResolver.js';
|
||||
import { pointInPreparedArea } from './areaGeometry.js';
|
||||
import { findAdminCandidates } from './adminBoundaries.js';
|
||||
|
||||
const square = (w, s, e, n) => [
|
||||
[w, s],
|
||||
[e, s],
|
||||
[e, n],
|
||||
[w, n],
|
||||
[w, s],
|
||||
];
|
||||
|
||||
const admin = (kind, name, country, box, extra = {}) => ({
|
||||
kind,
|
||||
name,
|
||||
country,
|
||||
source: 'natural-earth',
|
||||
polygons: [[square(...box)]],
|
||||
...extra,
|
||||
});
|
||||
const GEORGIA_COUNTRY = admin(
|
||||
'country',
|
||||
'Georgia',
|
||||
'Georgia',
|
||||
[40, 41, 46.7, 43.6],
|
||||
);
|
||||
const GEORGIA_STATE = admin(
|
||||
'state',
|
||||
'Georgia',
|
||||
'United States of America',
|
||||
[-85.6, 30.4, -80.8, 35],
|
||||
);
|
||||
const PUNJAB_IN = admin('state', 'Punjab', 'India', [73.8, 29.5, 77, 32.5]);
|
||||
const PUNJAB_PK = admin('state', 'Punjab', 'Pakistan', [69.3, 27.7, 73.7, 34]);
|
||||
const TEXAS = admin(
|
||||
'state',
|
||||
'Texas',
|
||||
'United States of America',
|
||||
[-106, 26, -94, 36],
|
||||
);
|
||||
|
||||
const BAGMATI = {
|
||||
ok: true,
|
||||
name: 'Bagmati Province',
|
||||
polygons: [[square(84.4, 26.9, 86.6, 28.4), square(85.3, 27.6, 85.4, 27.7)]],
|
||||
source: 'osm',
|
||||
rung: 'nominatim',
|
||||
adminName: 'Bagmati Province',
|
||||
};
|
||||
|
||||
function makeResolver(overrides = {}) {
|
||||
const store = createAreaStore();
|
||||
const calls = { outline: [], natural: 0, admin: 0 };
|
||||
const resolver = createAreaResolver({
|
||||
store,
|
||||
findNaturalRegion: async (q) => {
|
||||
calls.natural += 1;
|
||||
return /alps/i.test(q)
|
||||
? {
|
||||
name: 'Alps',
|
||||
kind: 'natural',
|
||||
polygons: [square(5, 44, 16, 48), square(17, 44, 18, 45)],
|
||||
}
|
||||
: null;
|
||||
},
|
||||
findAdminCandidates: async (q) => {
|
||||
calls.admin += 1;
|
||||
if (/^georgia$/i.test(q)) return [GEORGIA_STATE, GEORGIA_COUNTRY];
|
||||
if (/^georgia, united states/i.test(q)) return [GEORGIA_STATE];
|
||||
if (/^punjab$/i.test(q)) return [PUNJAB_PK, PUNJAB_IN];
|
||||
if (/^punjab, pakistan/i.test(q)) return [PUNJAB_PK];
|
||||
if (/^texas$/i.test(q)) return [TEXAS];
|
||||
return [];
|
||||
},
|
||||
resolveNamedOutline: async (q, options) => {
|
||||
calls.outline.push({ q, ...options, signal: undefined });
|
||||
if (/bagmati/i.test(q)) return BAGMATI;
|
||||
return {
|
||||
ok: false,
|
||||
code: 'AREA_NOT_FOUND',
|
||||
error: `No boundary found for "${q}".`,
|
||||
};
|
||||
},
|
||||
...overrides,
|
||||
});
|
||||
return { store, resolver, calls };
|
||||
}
|
||||
|
||||
test('the store keeps geometry local and summarizes without coordinates', () => {
|
||||
const store = createAreaStore({ maxEntries: 2 });
|
||||
const a = store.put({
|
||||
geometry: [[square(0, 0, 1, 1)]],
|
||||
name: 'A',
|
||||
source: 'drawn',
|
||||
level: 'drawn',
|
||||
});
|
||||
const b = store.put({
|
||||
geometry: [[square(2, 2, 3, 3)]],
|
||||
name: 'B',
|
||||
source: 'us-census',
|
||||
sourceId: 'place:1',
|
||||
});
|
||||
assert.equal(b.areaId, 'place:1');
|
||||
assert.equal(b.source, 'us-census');
|
||||
store.get(a.areaId); // A is now the most recently used
|
||||
store.put({ geometry: [[square(4, 4, 5, 5)]], name: 'C', source: 'osm' });
|
||||
assert.equal(store.has('place:1'), false, 'least recently used evicted');
|
||||
assert.ok(store.get(a.areaId));
|
||||
const summary = summarizeArea(a);
|
||||
assert.deepEqual(
|
||||
Object.keys(summary).sort(),
|
||||
[
|
||||
'areaId',
|
||||
'areaKm2',
|
||||
'bbox',
|
||||
'holes',
|
||||
'level',
|
||||
'name',
|
||||
'parts',
|
||||
'source',
|
||||
].sort(),
|
||||
);
|
||||
assert.equal(JSON.stringify(summary).includes('geometry'), false);
|
||||
assert.equal(
|
||||
store.put({
|
||||
geometry: [
|
||||
[
|
||||
[0, 0],
|
||||
[1, 1],
|
||||
],
|
||||
],
|
||||
name: 'bad',
|
||||
}),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('query aliases have their own LRU bound even for one stable area', () => {
|
||||
const store = createAreaStore({ maxEntries: 2, maxQueryEntries: 3 });
|
||||
const area = store.put({
|
||||
geometry: [[square(0, 0, 1, 1)]],
|
||||
name: 'Stable',
|
||||
source: 'osm',
|
||||
sourceId: 'osm:stable',
|
||||
});
|
||||
for (let i = 0; i < 50; i += 1)
|
||||
store.rememberQuery(`alias-${i}`, area.areaId);
|
||||
assert.equal(store.recallQuery('alias-0'), null, 'old aliases are evicted');
|
||||
assert.equal(store.recallQuery('alias-46'), null, 'the bound is independent');
|
||||
assert.equal(store.recallQuery('alias-47')?.areaId, area.areaId);
|
||||
assert.equal(store.recallQuery('alias-49')?.areaId, area.areaId);
|
||||
assert.equal(store.size, 1, 'alias churn does not evict the area record');
|
||||
});
|
||||
|
||||
test('a stable source keeps one handle when stored again', () => {
|
||||
const store = createAreaStore();
|
||||
for (let i = 0; i < 2; i += 1)
|
||||
store.put({
|
||||
geometry: [[square(0, 0, 1, 1)]],
|
||||
name: 'X',
|
||||
source: 'natural-earth',
|
||||
sourceId: 'ne:state:x',
|
||||
});
|
||||
assert.equal(store.size, 1);
|
||||
});
|
||||
|
||||
test('a named natural region resolves offline with every part', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'the Alps' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.record.source, 'natural-earth');
|
||||
assert.equal(result.record.parts, 2);
|
||||
assert.equal(calls.outline.length, 0, 'no lookup');
|
||||
assert.ok(result.ms < 300);
|
||||
});
|
||||
|
||||
test('a bundled state resolves by name with no lookup', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'Texas' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.rung, 'bundled');
|
||||
assert.equal(result.record.level, 'admin1');
|
||||
assert.equal(result.record.source, 'natural-earth');
|
||||
assert.equal(result.record.meta.country, 'United States of America');
|
||||
assert.equal(calls.outline.length, 0);
|
||||
});
|
||||
|
||||
test('Bagmati goes to the outline ladder and keeps its hole', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'Bagmati province' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.rung, 'nominatim');
|
||||
assert.equal(result.record.source, 'osm');
|
||||
assert.equal(result.record.level, 'admin1', 'the level word is kept');
|
||||
assert.equal(result.record.holes, 1);
|
||||
assert.equal(pointInPreparedArea(result.record.prepared, 27.2, 85), true);
|
||||
assert.equal(
|
||||
pointInPreparedArea(result.record.prepared, 27.65, 85.35),
|
||||
false,
|
||||
'inside the hole',
|
||||
);
|
||||
assert.equal(calls.outline[0].levelHint, 'admin1');
|
||||
});
|
||||
|
||||
test('a legacy bundled zone is never stored as the requested current province', async () => {
|
||||
const legacy = admin(
|
||||
'state',
|
||||
'Bagmati Zone',
|
||||
'Nepal',
|
||||
[84.645, 27.357, 86.055, 28.335],
|
||||
);
|
||||
const { store, resolver } = makeResolver({
|
||||
findAdminCandidates: async () => [legacy],
|
||||
});
|
||||
const result = await resolver.resolve({ query: 'Bagmati province' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.code, 'AREA_IDENTITY_UNVERIFIED');
|
||||
assert.equal(result.record, undefined);
|
||||
assert.equal(store.size, 0);
|
||||
const repeated = await resolver.resolve({ query: 'Bagmati province' });
|
||||
assert.equal(repeated.code, 'AREA_IDENTITY_UNVERIFIED');
|
||||
assert.equal(repeated.cached, false);
|
||||
assert.equal(store.size, 0);
|
||||
});
|
||||
|
||||
test('legacy zone identity cannot escape through view choice or candidate memory', async () => {
|
||||
const nepal = admin(
|
||||
'state',
|
||||
'Bagmati Zone',
|
||||
'Nepal',
|
||||
[84.645, 27.357, 86.055, 28.335],
|
||||
);
|
||||
const namesake = admin(
|
||||
'state',
|
||||
'Bagmati Zone',
|
||||
'Elsewhere',
|
||||
[10, 10, 11, 11],
|
||||
);
|
||||
const { store, resolver } = makeResolver({
|
||||
findAdminCandidates: async () => [nepal, namesake],
|
||||
viewCenter: () => ({ lat: 27.7, lon: 85.3 }),
|
||||
});
|
||||
const result = await resolver.resolve({ query: 'Bagmati province' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.code, 'AREA_IDENTITY_UNVERIFIED');
|
||||
assert.equal(result.needsClarification, undefined);
|
||||
assert.equal(result.candidates, undefined);
|
||||
assert.equal(store.size, 0);
|
||||
assert.equal(
|
||||
(await resolver.resolve({ candidateId: 'ne:state:nepal-bagmati-zone' }))
|
||||
.code,
|
||||
'UNKNOWN_CANDIDATE',
|
||||
);
|
||||
assert.equal(store.size, 0);
|
||||
});
|
||||
|
||||
test('a repeat is answered from the store without a lookup', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
await resolver.resolve({ query: 'Bagmati' });
|
||||
const again = await resolver.resolve({ query: 'bagmati' });
|
||||
assert.equal(again.ok, true);
|
||||
assert.equal(again.cached, true);
|
||||
assert.equal(calls.outline.length, 1);
|
||||
});
|
||||
|
||||
test('an ambiguous name asks instead of guessing, and the choice resolves', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'Georgia' });
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(result.needsClarification, true);
|
||||
assert.equal(result.candidates.length, 2);
|
||||
assert.deepEqual(result.candidates[0], {
|
||||
candidateId: 'ne:state:united-states-of-america-georgia',
|
||||
name: 'Georgia',
|
||||
level: 'admin1',
|
||||
country: 'United States of America',
|
||||
});
|
||||
assert.equal(result.candidates[1].level, 'country');
|
||||
assert.equal(calls.outline.length, 0, 'no lookup spent on a question');
|
||||
const chosen = await resolver.resolve({
|
||||
candidateId: result.candidates[0].candidateId,
|
||||
});
|
||||
assert.equal(chosen.ok, true);
|
||||
assert.equal(chosen.record.meta.country, 'United States of America');
|
||||
});
|
||||
|
||||
test('an already-aborted clarification choice does not persist page state', async () => {
|
||||
const { store, resolver } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'Georgia' });
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const chosen = await resolver.resolve(
|
||||
{ candidateId: result.candidates[0].candidateId },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
assert.equal(chosen.code, 'CANCELLED');
|
||||
assert.equal(chosen.cancelled, true);
|
||||
assert.equal(store.size, 0);
|
||||
});
|
||||
|
||||
test('candidate IDs accept every emitted choice and reject malformed or oversized input', async () => {
|
||||
const { store, resolver } = makeResolver();
|
||||
const result = await resolver.resolve({ query: 'Georgia' });
|
||||
const grammar = new RegExp(AREA_CANDIDATE_ID_PATTERN, 'u');
|
||||
for (const choice of result.candidates) {
|
||||
assert.ok(choice.candidateId.length <= MAX_AREA_CANDIDATE_ID_LENGTH);
|
||||
assert.match(choice.candidateId, grammar);
|
||||
assert.equal(isAreaCandidateId(choice.candidateId), true);
|
||||
assert.equal(
|
||||
(await resolver.resolve({ candidateId: choice.candidateId })).ok,
|
||||
true,
|
||||
);
|
||||
}
|
||||
assert.equal(result.candidates[0].candidateId.length, 41);
|
||||
|
||||
store.put({
|
||||
geometry: [[square(0, 0, 1, 1)]],
|
||||
name: 'Not a candidate',
|
||||
source: 'osm',
|
||||
sourceId: 'area-1',
|
||||
});
|
||||
for (const bad of [
|
||||
'area-1',
|
||||
'ne:state:bad slug',
|
||||
'ne:state:../../etc',
|
||||
'ne:state:!!!',
|
||||
'ne:state:a_b',
|
||||
'ne:planet:earth',
|
||||
`ne:state:${'a'.repeat(MAX_AREA_CANDIDATE_ID_LENGTH)}`,
|
||||
]) {
|
||||
const rejected = await resolver.resolve({ candidateId: bad });
|
||||
assert.equal(rejected.code, 'BAD_CANDIDATE');
|
||||
}
|
||||
});
|
||||
|
||||
test('long bundled names produce bounded, distinct candidate handles', async () => {
|
||||
const name = 'A'.repeat(70);
|
||||
const candidates = [
|
||||
admin('state', name, `B${'b'.repeat(70)}`, [0, 0, 1, 1]),
|
||||
admin('state', name, `C${'c'.repeat(70)}`, [2, 2, 3, 3]),
|
||||
];
|
||||
const { resolver } = makeResolver({
|
||||
findAdminCandidates: async () => candidates,
|
||||
});
|
||||
const result = await resolver.resolve({ query: name });
|
||||
assert.equal(result.needsClarification, true);
|
||||
assert.equal(
|
||||
new Set(result.candidates.map((choice) => choice.candidateId)).size,
|
||||
2,
|
||||
);
|
||||
for (const choice of result.candidates) {
|
||||
assert.equal(isAreaCandidateId(choice.candidateId), true);
|
||||
assert.ok(choice.candidateId.length <= MAX_AREA_CANDIDATE_ID_LENGTH);
|
||||
assert.equal(
|
||||
(await resolver.resolve({ candidateId: choice.candidateId })).ok,
|
||||
true,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('within or level settles an ambiguous name', async () => {
|
||||
const { resolver } = makeResolver();
|
||||
const state = await resolver.resolve({
|
||||
query: 'Georgia',
|
||||
within: 'United States',
|
||||
});
|
||||
assert.equal(state.ok, true);
|
||||
assert.equal(state.record.level, 'admin1');
|
||||
const country = await resolver.resolve({
|
||||
query: 'Georgia',
|
||||
level: 'country',
|
||||
});
|
||||
assert.equal(country.ok, true);
|
||||
assert.equal(country.record.level, 'country');
|
||||
const both = await resolver.resolve({ query: 'Punjab', level: 'admin1' });
|
||||
assert.equal(both.needsClarification, true, 'both Punjabs are admin1');
|
||||
const pk = await resolver.resolve({ query: 'Punjab', within: 'Pakistan' });
|
||||
assert.equal(pk.record.meta.country, 'Pakistan');
|
||||
});
|
||||
|
||||
test('the view settles an ambiguous name only when it is inside one of them', async () => {
|
||||
const { resolver } = makeResolver({
|
||||
viewCenter: () => ({ lat: 31, lon: 75.5 }),
|
||||
});
|
||||
const result = await resolver.resolve({ query: 'Punjab' });
|
||||
assert.equal(result.ok, true);
|
||||
assert.equal(result.record.meta.country, 'India');
|
||||
const away = makeResolver({ viewCenter: () => ({ lat: 0, lon: 0 }) });
|
||||
const asked = await away.resolver.resolve({ query: 'Punjab' });
|
||||
assert.equal(asked.needsClarification, true);
|
||||
// A choice the view made is not remembered for the name.
|
||||
let view = { lat: 31, lon: 75.5 };
|
||||
const moving = makeResolver({ viewCenter: () => view });
|
||||
await moving.resolver.resolve({ query: 'Punjab' });
|
||||
view = { lat: 31, lon: 71 };
|
||||
const again = await moving.resolver.resolve({ query: 'Punjab' });
|
||||
assert.equal(again.record.meta.country, 'Pakistan');
|
||||
});
|
||||
|
||||
test('a qualifier skips the natural-region pack, which cannot check it', async () => {
|
||||
const { resolver, calls } = makeResolver();
|
||||
await resolver.resolve({ query: 'the Alps', within: 'Austria' });
|
||||
assert.equal(calls.natural, 0);
|
||||
assert.equal(calls.outline.length, 1);
|
||||
});
|
||||
|
||||
test('the area just stored survives eviction even when every other area is pinned', () => {
|
||||
const store = createAreaStore({ maxEntries: 2, isPinned: () => true });
|
||||
for (let i = 0; i < 3; i += 1)
|
||||
store.put({
|
||||
geometry: [[square(i, 0, i + 0.5, 0.5)]],
|
||||
name: `A${i}`,
|
||||
source: 'drawn',
|
||||
});
|
||||
const last = store.put({
|
||||
geometry: [[square(9, 0, 9.5, 0.5)]],
|
||||
name: 'new',
|
||||
source: 'drawn',
|
||||
});
|
||||
assert.ok(store.get(last.areaId), 'the new handle is usable');
|
||||
});
|
||||
|
||||
test('a country stands for its same-named state; namesakes abroad are rivals', () => {
|
||||
const mexico = admin('country', 'Mexico', 'Mexico', [-118, 14, -86, 33]);
|
||||
const state = admin(
|
||||
'state',
|
||||
'State of Mexico',
|
||||
'Mexico',
|
||||
[-100, 18, -98, 20],
|
||||
);
|
||||
assert.deepEqual(distinctAdminPlaces([state, mexico]), [mexico]);
|
||||
assert.equal(distinctAdminPlaces([PUNJAB_IN, PUNJAB_PK]).length, 2);
|
||||
});
|
||||
|
||||
test('bundled candidates: shared prominent names list every unit, minor ones none', async () => {
|
||||
const names = async (q) =>
|
||||
(await findAdminCandidates(q)).map((a) => `${a.kind}:${a.country}`);
|
||||
assert.deepEqual((await names('Punjab')).sort(), [
|
||||
'state:India',
|
||||
'state:Pakistan',
|
||||
]);
|
||||
assert.deepEqual((await names('Georgia')).sort(), [
|
||||
'country:Georgia',
|
||||
'state:United States of America',
|
||||
]);
|
||||
assert.deepEqual(await names('Punjab, India'), ['state:India']);
|
||||
assert.deepEqual(await names('Kent'), [], 'minor units are the geocoder’s');
|
||||
});
|
||||
|
||||
test('an outline ladder refusal passes through with its code', async () => {
|
||||
const { resolver } = makeResolver();
|
||||
const miss = await resolver.resolve({ query: 'Nowhere Province' });
|
||||
assert.equal(miss.ok, false);
|
||||
assert.equal(miss.code, 'AREA_NOT_FOUND');
|
||||
const down = makeResolver({
|
||||
resolveNamedOutline: async () => ({
|
||||
ok: false,
|
||||
code: 'AREA_UNAVAILABLE',
|
||||
error: 'No outline source can trace it here.',
|
||||
}),
|
||||
});
|
||||
const failed = await down.resolver.resolve({ query: 'Kathmandu' });
|
||||
assert.equal(failed.code, 'AREA_UNAVAILABLE');
|
||||
});
|
||||
|
||||
test('an approximate outline is stored and labelled as such', async () => {
|
||||
const { resolver } = makeResolver({
|
||||
resolveNamedOutline: async () => ({
|
||||
ok: true,
|
||||
name: 'Mission',
|
||||
polygons: [[square(0, 0, 0.01, 0.01)]],
|
||||
source: 'osm',
|
||||
rung: 'overpass',
|
||||
approximate: true,
|
||||
basis: 'buffer sized to the place',
|
||||
}),
|
||||
});
|
||||
const result = await resolver.resolve({ query: 'the Mission' });
|
||||
assert.equal(result.record.approximate, true);
|
||||
assert.equal(result.record.source, 'approximate');
|
||||
assert.equal(result.record.meta.basis, 'buffer sized to the place');
|
||||
});
|
||||
|
||||
test('a slow lookup times out but keeps filling the cache', async () => {
|
||||
let release;
|
||||
const gate = new Promise((r) => {
|
||||
release = r;
|
||||
});
|
||||
const { resolver } = makeResolver({
|
||||
resolveNamedOutline: async () => {
|
||||
await gate;
|
||||
return BAGMATI;
|
||||
},
|
||||
});
|
||||
const first = await resolver.resolve({ query: 'Bagmati' }, { budgetMs: 20 });
|
||||
assert.equal(first.code, 'AREA_TIMEOUT');
|
||||
release();
|
||||
await new Promise((r) => setTimeout(r, 10));
|
||||
const second = await resolver.resolve({ query: 'Bagmati' }, { budgetMs: 20 });
|
||||
assert.equal(second.ok, true);
|
||||
assert.equal(second.cached, true);
|
||||
});
|
||||
|
||||
test('a cancelled caller returns at once without cancelling the shared lookup', async () => {
|
||||
const { resolver } = makeResolver();
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const result = await resolver.resolve(
|
||||
{ query: 'Bagmati' },
|
||||
{ signal: controller.signal },
|
||||
);
|
||||
assert.equal(result.code, 'CANCELLED');
|
||||
await new Promise((r) => setTimeout(r, 5));
|
||||
const again = await resolver.resolve({ query: 'Bagmati' });
|
||||
assert.equal(again.ok, true);
|
||||
});
|
||||
|
||||
test('distinct area lookups are hard-bounded while same-key callers still coalesce', async () => {
|
||||
let release;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
let calls = 0;
|
||||
const { resolver } = makeResolver({
|
||||
maxInFlight: 1,
|
||||
resolveNamedOutline: async (query) => {
|
||||
calls += 1;
|
||||
await gate;
|
||||
return { ...BAGMATI, name: query };
|
||||
},
|
||||
});
|
||||
const first = resolver.resolve({ query: 'First Area' });
|
||||
const joined = resolver.resolve({ query: 'First Area' });
|
||||
const refused = await resolver.resolve({ query: 'Second Area' });
|
||||
assert.equal(refused.code, 'AREA_BUSY');
|
||||
release();
|
||||
const [a, b] = await Promise.all([first, joined]);
|
||||
assert.equal(calls, 1, 'the same key shares the one live provider lookup');
|
||||
assert.equal(a.ok, true);
|
||||
assert.equal(b.ok, true);
|
||||
});
|
||||
|
||||
test("settled lookups leave no listener on the caller's signal", async () => {
|
||||
const { resolver } = makeResolver();
|
||||
const controller = new AbortController();
|
||||
let added = 0;
|
||||
let removed = 0;
|
||||
const add = controller.signal.addEventListener.bind(controller.signal);
|
||||
const remove = controller.signal.removeEventListener.bind(controller.signal);
|
||||
controller.signal.addEventListener = (...args) => {
|
||||
if (args[0] === 'abort') added += 1;
|
||||
return add(...args);
|
||||
};
|
||||
controller.signal.removeEventListener = (...args) => {
|
||||
if (args[0] === 'abort') removed += 1;
|
||||
return remove(...args);
|
||||
};
|
||||
for (const query of ['Texas', 'Bagmati', 'Nowhere at all'])
|
||||
await resolver.resolve({ query }, { signal: controller.signal });
|
||||
assert.ok(added > 0, 'the lookups listened while running');
|
||||
assert.equal(removed, added, 'every listener is detached once settled');
|
||||
|
||||
const aborted = AbortSignal.abort();
|
||||
let attached = 0;
|
||||
aborted.addEventListener = () => {
|
||||
attached += 1;
|
||||
};
|
||||
const late = await resolver.resolve(
|
||||
{ query: 'Punjab, Pakistan' },
|
||||
{ signal: aborted },
|
||||
);
|
||||
assert.equal(late.code, 'CANCELLED');
|
||||
assert.equal(attached, 0, 'an aborted signal gets no listener');
|
||||
});
|
||||
|
||||
test('resolver disposal aborts provider lifetime and prevents late store/cache writes', async () => {
|
||||
let release;
|
||||
let providerSignal;
|
||||
const gate = new Promise((resolve) => {
|
||||
release = resolve;
|
||||
});
|
||||
const { resolver, store } = makeResolver({
|
||||
resolveNamedOutline: async (_query, { signal }) => {
|
||||
providerSignal = signal;
|
||||
await gate; // Deliberately ignores abort until it returns.
|
||||
return BAGMATI;
|
||||
},
|
||||
});
|
||||
const pending = resolver.resolve({ query: 'Late Area' });
|
||||
await new Promise((resolve) => setTimeout(resolve, 0));
|
||||
resolver.dispose();
|
||||
assert.equal(providerSignal.aborted, true);
|
||||
release();
|
||||
const result = await pending;
|
||||
assert.equal(result.ok, false);
|
||||
assert.equal(store.size, 0, 'late provider data never reaches the store');
|
||||
const after = await resolver.resolve({ query: 'Late Area' });
|
||||
assert.equal(after.code, 'CANCELLED');
|
||||
});
|
||||
|
||||
test('level words map to area levels', () => {
|
||||
assert.deepEqual(splitLevelWord('Bagmati Province'), {
|
||||
bare: 'bagmati',
|
||||
level: 'admin1',
|
||||
});
|
||||
assert.deepEqual(splitLevelWord('Kathmandu'), {
|
||||
bare: 'kathmandu',
|
||||
level: null,
|
||||
});
|
||||
});
|
||||
|
||||
test('non-Latin names are distinct keys: 東京 then 大阪 looks up both', async () => {
|
||||
const asked = [];
|
||||
const { resolver } = makeResolver({
|
||||
resolveNamedOutline: async (q) => {
|
||||
asked.push(q);
|
||||
return { ...BAGMATI, name: q };
|
||||
},
|
||||
});
|
||||
const first = await resolver.resolve({ query: '東京' });
|
||||
const second = await resolver.resolve({ query: '大阪' });
|
||||
assert.notEqual(first.record.areaId, second.record.areaId);
|
||||
assert.equal(second.cached, false, 'not the cached Tokyo');
|
||||
assert.deepEqual(asked, ['東京', '大阪']);
|
||||
// The same name with a different `within` is a different question.
|
||||
await resolver.resolve({ query: '東京', within: '日本' });
|
||||
assert.equal(asked.length, 3);
|
||||
assert.equal((await resolver.resolve({ query: '東京' })).cached, true);
|
||||
});
|
||||
|
||||
test('a name that normalizes to nothing is never cached or shared', async () => {
|
||||
let calls = 0;
|
||||
const { resolver } = makeResolver({
|
||||
resolveNamedOutline: async () => {
|
||||
calls += 1;
|
||||
return BAGMATI;
|
||||
},
|
||||
});
|
||||
await resolver.resolve({ query: '!!!' });
|
||||
await resolver.resolve({ query: '???' });
|
||||
assert.equal(calls, 2, 'two punctuation-only asks are two lookups');
|
||||
});
|
||||
|
||||
test('a natural region never hides a country or state of the same name', async () => {
|
||||
const desert = {
|
||||
name: 'Punjab',
|
||||
kind: 'natural',
|
||||
polygons: [square(70, 28, 76, 33)],
|
||||
};
|
||||
const { resolver } = makeResolver({
|
||||
findNaturalRegion: async (q) => (/^punjab$/i.test(q) ? desert : null),
|
||||
});
|
||||
const bare = await resolver.resolve({ query: 'Punjab' });
|
||||
assert.equal(bare.ok, false);
|
||||
assert.equal(bare.code, 'AMBIGUOUS_AREA', 'the two states are asked about');
|
||||
const natural = await resolver.resolve({ query: 'Punjab', level: 'natural' });
|
||||
assert.equal(natural.ok, true);
|
||||
assert.equal(natural.record.level, 'natural', 'asked for, the region wins');
|
||||
});
|
||||
|
||||
test('same-named states in one country get their own candidate and area', async () => {
|
||||
const wa = admin(
|
||||
'state',
|
||||
'Washington',
|
||||
'United States of America',
|
||||
[-124, 45.5, -117, 49],
|
||||
{ regionCode: 'WA' },
|
||||
);
|
||||
const dc = admin(
|
||||
'state',
|
||||
'Washington',
|
||||
'United States of America',
|
||||
[-77.2, 38.8, -76.9, 39],
|
||||
{ regionCode: 'DC' },
|
||||
);
|
||||
const { resolver } = makeResolver({
|
||||
findAdminCandidates: async (q) => (/^washington$/i.test(q) ? [wa, dc] : []),
|
||||
});
|
||||
const asked = await resolver.resolve({ query: 'Washington' });
|
||||
assert.equal(asked.code, 'AMBIGUOUS_AREA');
|
||||
const ids = asked.candidates.map((c) => c.candidateId);
|
||||
assert.equal(new Set(ids).size, 2, `distinct ids: ${ids.join(', ')}`);
|
||||
assert.deepEqual(
|
||||
asked.candidates.map((c) => c.region),
|
||||
['WA', 'DC'],
|
||||
'the choices can be told apart',
|
||||
);
|
||||
const picked = await Promise.all(
|
||||
ids.map((candidateId) => resolver.resolve({ candidateId })),
|
||||
);
|
||||
assert.ok(picked.every((p) => p.ok));
|
||||
assert.notEqual(
|
||||
picked[0].record.areaId,
|
||||
picked[1].record.areaId,
|
||||
'two areas, not one overwritten',
|
||||
);
|
||||
assert.equal(
|
||||
pointInPreparedArea(picked[0].record.prepared, 47, -120),
|
||||
true,
|
||||
'Washington State',
|
||||
);
|
||||
assert.equal(
|
||||
pointInPreparedArea(picked[1].record.prepared, 38.9, -77),
|
||||
true,
|
||||
'District of Columbia',
|
||||
);
|
||||
});
|
||||
|
||||
test('a bundled name mismatch falls through to the outline ladder', async () => {
|
||||
const azad = admin('state', 'Azad Kashmir', 'Pakistan', [73, 33, 75, 35.5]);
|
||||
const kashmir = {
|
||||
ok: true,
|
||||
name: 'Kashmir',
|
||||
polygons: [[square(73, 32, 80, 37)]],
|
||||
source: 'osm',
|
||||
rung: 'nominatim',
|
||||
};
|
||||
let outlineOk = true;
|
||||
const { resolver } = makeResolver({
|
||||
findAdminCandidates: async (q) => (/^kashmir$/i.test(q) ? [azad] : []),
|
||||
resolveNamedOutline: async () =>
|
||||
outlineOk
|
||||
? kashmir
|
||||
: { ok: false, code: 'AREA_NOT_FOUND', error: 'none' },
|
||||
});
|
||||
const found = await resolver.resolve({ query: 'Kashmir' });
|
||||
assert.equal(found.ok, true, found.error);
|
||||
assert.equal(found.record.name, 'Kashmir');
|
||||
outlineOk = false;
|
||||
const { resolver: offline } = makeResolver({
|
||||
findAdminCandidates: async () => [azad],
|
||||
resolveNamedOutline: async () => ({
|
||||
ok: false,
|
||||
code: 'AREA_NOT_FOUND',
|
||||
error: 'none',
|
||||
}),
|
||||
});
|
||||
const refused = await offline.resolve({ query: 'Kashmir' });
|
||||
assert.equal(
|
||||
refused.code,
|
||||
'AREA_IDENTITY_MISMATCH',
|
||||
'the bundled refusal is kept',
|
||||
);
|
||||
});
|
||||
|
||||
test('a view-picked outline answer is not reused for the same name elsewhere', async () => {
|
||||
let view = { lat: 39.8, lon: -89.6 }; // Springfield, Illinois
|
||||
const springfield = (center) => ({
|
||||
ok: true,
|
||||
name:
|
||||
center.lon < -80 ? 'Springfield, Illinois' : 'Springfield, Massachusetts',
|
||||
polygons: [
|
||||
[
|
||||
square(
|
||||
center.lon - 0.1,
|
||||
center.lat - 0.1,
|
||||
center.lon + 0.1,
|
||||
center.lat + 0.1,
|
||||
),
|
||||
],
|
||||
],
|
||||
source: 'osm',
|
||||
rung: 'nominatim',
|
||||
});
|
||||
const { resolver } = makeResolver({
|
||||
viewCenter: () => view,
|
||||
resolveNamedOutline: async () => springfield(view),
|
||||
});
|
||||
const illinois = await resolver.resolve({ query: 'Springfield' });
|
||||
assert.equal(illinois.record.name, 'Springfield, Illinois');
|
||||
const again = await resolver.resolve({ query: 'Springfield' });
|
||||
assert.equal(again.cached, true, 'the same view still reuses it');
|
||||
view = { lat: 42.1, lon: -72.6 }; // Springfield, Massachusetts
|
||||
const massachusetts = await resolver.resolve({ query: 'Springfield' });
|
||||
assert.equal(massachusetts.cached, false);
|
||||
assert.equal(massachusetts.record.name, 'Springfield, Massachusetts');
|
||||
});
|
||||
|
||||
test('a name spoken without accents matches its accented unit, Latin letters only', async () => {
|
||||
const quebec = admin('state', 'Québec', 'Canada', [-79.8, 45, -57.1, 62.6]);
|
||||
const cordobaAr = admin(
|
||||
'state',
|
||||
'Córdoba',
|
||||
'Argentina',
|
||||
[-65.8, -35, -61.8, -29.5],
|
||||
);
|
||||
const cordobaEs = admin('state', 'Córdoba', 'Spain', [-5.6, 37.2, -4, 38.7]);
|
||||
const thai = admin('state', 'ป่าย', 'Thailand', [98, 19, 99, 20]);
|
||||
const { resolver } = makeResolver({
|
||||
findAdminCandidates: async (q) =>
|
||||
/^quebec$/i.test(q)
|
||||
? [quebec]
|
||||
: /^cordoba$/i.test(q)
|
||||
? [cordobaAr, cordobaEs]
|
||||
: q === 'ปาย'
|
||||
? [thai]
|
||||
: [],
|
||||
});
|
||||
const qc = await resolver.resolve({ query: 'Quebec' });
|
||||
assert.equal(qc.ok, true, qc.error);
|
||||
assert.equal(qc.record.name, 'Québec');
|
||||
const cordoba = await resolver.resolve({ query: 'Cordoba' });
|
||||
assert.equal(cordoba.code, 'AMBIGUOUS_AREA', 'both Córdobas are asked about');
|
||||
assert.equal(cordoba.candidates.length, 2);
|
||||
const tone = await resolver.resolve({ query: 'ปาย' });
|
||||
assert.equal(tone.ok, false, 'a Thai tone mark still tells names apart');
|
||||
});
|
||||
|
||||
test('a natural name for two distant places is asked about, and the choice resolves', async () => {
|
||||
const azores = {
|
||||
name: 'Flores',
|
||||
featurecla: 'Island',
|
||||
polygons: [square(-31.3, 39.4, -31.1, 39.5)],
|
||||
areaKm2: 140,
|
||||
center: { lat: 39.45, lon: -31.2 },
|
||||
};
|
||||
const indonesia = {
|
||||
name: 'Flores',
|
||||
featurecla: 'Island',
|
||||
polygons: [square(119.8, -8.9, 123, -8.1)],
|
||||
areaKm2: 14000,
|
||||
center: { lat: -8.5, lon: 121.4 },
|
||||
};
|
||||
const { resolver } = makeResolver({
|
||||
findNaturalRegion: async (q) =>
|
||||
/^flores$/i.test(q)
|
||||
? {
|
||||
name: 'Flores',
|
||||
kind: 'natural',
|
||||
polygons: indonesia.polygons,
|
||||
places: [indonesia, azores],
|
||||
}
|
||||
: null,
|
||||
});
|
||||
const asked = await resolver.resolve({ query: 'Flores' });
|
||||
assert.equal(asked.code, 'AMBIGUOUS_AREA');
|
||||
assert.equal(asked.candidates.length, 2);
|
||||
assert.ok(asked.candidates.every((c) => c.level === 'natural' && c.region));
|
||||
const picked = await resolver.resolve({
|
||||
candidateId: asked.candidates[1].candidateId,
|
||||
});
|
||||
assert.equal(picked.ok, true, picked.error);
|
||||
assert.equal(picked.record.level, 'natural');
|
||||
assert.equal(
|
||||
pointInPreparedArea(picked.record.prepared, 39.45, -31.2),
|
||||
true,
|
||||
'the Azores Flores',
|
||||
);
|
||||
});
|
||||
|
||||
test('a natural feature in several parts is stored whole', async () => {
|
||||
const north = square(33.7, 2.4, 44.2, 15.4);
|
||||
const south = square(28.9, -15.6, 35.8, 2.4);
|
||||
const { resolver } = makeResolver({
|
||||
findNaturalRegion: async (q) =>
|
||||
/rift/i.test(q)
|
||||
? {
|
||||
name: 'Great Rift Valley',
|
||||
kind: 'natural',
|
||||
polygons: [north],
|
||||
places: [
|
||||
{
|
||||
name: 'Great Rift Valley',
|
||||
featurecla: 'Valley',
|
||||
polygons: [north, south],
|
||||
areaKm2: 2,
|
||||
center: { lat: 0, lon: 36 },
|
||||
},
|
||||
],
|
||||
}
|
||||
: null,
|
||||
});
|
||||
const rift = await resolver.resolve({ query: 'Great Rift Valley' });
|
||||
assert.equal(rift.ok, true);
|
||||
assert.equal(
|
||||
pointInPreparedArea(rift.record.prepared, -10, 33),
|
||||
true,
|
||||
'the southern part counts',
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
/**
|
||||
* Session-scoped store of area handles. A voice turn refers to an area by its
|
||||
* `areaId`; the geometry itself stays here and never goes to the model.
|
||||
*
|
||||
* Records are immutable once stored. A source with a stable identity (an OSM
|
||||
* relation, a Natural Earth region, an annotation) keeps the same id when it
|
||||
* is stored again, so repeating "outline Bagmati" does not mint new handles.
|
||||
* Least recently used records are evicted past `maxEntries`, except those
|
||||
* `isPinned` reports as still in use.
|
||||
*
|
||||
* Pure: no Cesium, DOM or network.
|
||||
* @module data/areaStore
|
||||
*/
|
||||
|
||||
import {
|
||||
multiPolygonAreaKm2,
|
||||
multiPolygonCounts,
|
||||
normalizeMultiPolygon,
|
||||
prepareArea,
|
||||
} from './areaGeometry.js';
|
||||
|
||||
/** Where an area came from, as the model and the panel name it. */
|
||||
export const AREA_SOURCES = Object.freeze([
|
||||
'natural-earth',
|
||||
'us-census',
|
||||
'wof',
|
||||
'datasf',
|
||||
'osm',
|
||||
'openfreemap',
|
||||
'annotation',
|
||||
'drawn',
|
||||
'approximate',
|
||||
]);
|
||||
|
||||
/** Levels a resolved area can have. */
|
||||
export const AREA_LEVELS = Object.freeze([
|
||||
'country',
|
||||
'admin1',
|
||||
'admin2',
|
||||
'city',
|
||||
'district',
|
||||
'natural',
|
||||
'site',
|
||||
'drawn',
|
||||
]);
|
||||
|
||||
const round = (value, digits) => {
|
||||
const f = 10 ** digits;
|
||||
return Math.round(value * f) / f;
|
||||
};
|
||||
|
||||
/**
|
||||
* Create an area store.
|
||||
* @param {{maxEntries?: number, maxQueryEntries?: number, now?: () => number, isPinned?: (areaId: string) => boolean}} [options]
|
||||
*/
|
||||
export function createAreaStore({
|
||||
maxEntries = 32,
|
||||
maxQueryEntries = Math.max(32, maxEntries * 8),
|
||||
now = () => Date.now(),
|
||||
isPinned = () => false,
|
||||
} = {}) {
|
||||
/** Insertion order doubles as recency: get() re-inserts. */
|
||||
const records = new Map();
|
||||
/** query key → areaId, for cached resolutions. */
|
||||
const queries = new Map();
|
||||
let seq = 0;
|
||||
|
||||
function forgetRecordQueries(areaId) {
|
||||
for (const [key, queried] of queries)
|
||||
if (queried === areaId) queries.delete(key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Drop least recently used records past the bound, skipping pinned ones
|
||||
* (an area an outline on the map still refers to keeps its geometry for as
|
||||
* long as the outline exists; the annotation cap bounds how many that is).
|
||||
*/
|
||||
function evict(keep) {
|
||||
if (records.size <= maxEntries) return;
|
||||
for (const id of [...records.keys()]) {
|
||||
if (records.size <= maxEntries) break;
|
||||
// The record just stored is always kept; pinned ones may exceed the bound.
|
||||
if (id === keep || isPinned(id)) continue;
|
||||
records.delete(id);
|
||||
forgetRecordQueries(id);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Store an area. Returns the stored record, or null when the geometry is
|
||||
* unusable.
|
||||
* @param {object} input
|
||||
* @param {object|Array} input.geometry GeoJSON Polygon/MultiPolygon or coordinates.
|
||||
* @param {string} input.name
|
||||
* @param {string} input.source One of AREA_SOURCES.
|
||||
* @param {string} [input.sourceId] Stable identity, e.g. `ne:state:india-punjab`.
|
||||
* @param {string} [input.level]
|
||||
* @param {boolean} [input.approximate]
|
||||
* @param {object} [input.meta] Extra facts (country, license, completeness).
|
||||
* @returns {object|null}
|
||||
*/
|
||||
function put(input) {
|
||||
const geometry = normalizeMultiPolygon(input?.geometry);
|
||||
if (!geometry) return null;
|
||||
const prepared = prepareArea(geometry);
|
||||
if (!prepared) return null;
|
||||
const areaId = input.sourceId
|
||||
? String(input.sourceId)
|
||||
: `area-${(seq += 1)}`;
|
||||
const counts = multiPolygonCounts(geometry);
|
||||
const record = Object.freeze({
|
||||
areaId,
|
||||
name: String(input.name || 'Unnamed area').slice(0, 160),
|
||||
level: AREA_LEVELS.includes(input.level) ? input.level : null,
|
||||
source: AREA_SOURCES.includes(input.source)
|
||||
? input.source
|
||||
: 'approximate',
|
||||
approximate: Boolean(input.approximate),
|
||||
geometry,
|
||||
prepared,
|
||||
bbox: prepared.bbox,
|
||||
areaKm2: multiPolygonAreaKm2(geometry),
|
||||
parts: counts.parts,
|
||||
holes: counts.holes,
|
||||
meta: Object.freeze({ ...(input.meta || {}) }),
|
||||
storedAt: now(),
|
||||
});
|
||||
records.delete(areaId);
|
||||
records.set(areaId, record);
|
||||
evict(areaId);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** The record for an id, marking it recently used; null when unknown or evicted. */
|
||||
function get(areaId) {
|
||||
const record = records.get(String(areaId ?? ''));
|
||||
if (!record) return null;
|
||||
records.delete(record.areaId);
|
||||
records.set(record.areaId, record);
|
||||
return record;
|
||||
}
|
||||
|
||||
return {
|
||||
put,
|
||||
get,
|
||||
has: (areaId) => records.has(String(areaId ?? '')),
|
||||
/** Remember which area a query resolved to. */
|
||||
rememberQuery(key, areaId) {
|
||||
if (!key || !records.has(areaId)) return;
|
||||
queries.delete(key);
|
||||
queries.set(key, areaId);
|
||||
while (queries.size > maxQueryEntries)
|
||||
queries.delete(queries.keys().next().value);
|
||||
},
|
||||
/** The area a query resolved to earlier, if still stored. */
|
||||
recallQuery(key) {
|
||||
const id = queries.get(key);
|
||||
const record = id ? get(id) : null;
|
||||
if (!record) {
|
||||
queries.delete(key);
|
||||
return null;
|
||||
}
|
||||
queries.delete(key);
|
||||
queries.set(key, id);
|
||||
return record;
|
||||
},
|
||||
/** Newest first. */
|
||||
list: () => [...records.values()].reverse(),
|
||||
/** The most recently stored or used record matching `predicate`. */
|
||||
latest(predicate = () => true) {
|
||||
return [...records.values()].reverse().find(predicate) || null;
|
||||
},
|
||||
delete(areaId) {
|
||||
const id = String(areaId ?? '');
|
||||
const deleted = records.delete(id);
|
||||
if (deleted) forgetRecordQueries(id);
|
||||
return deleted;
|
||||
},
|
||||
clear() {
|
||||
records.clear();
|
||||
queries.clear();
|
||||
},
|
||||
get size() {
|
||||
return records.size;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The model-facing summary of an area: identity, size and provenance, never
|
||||
* coordinates beyond a rounded bbox.
|
||||
* @param {object} record
|
||||
* @returns {object}
|
||||
*/
|
||||
export function summarizeArea(record) {
|
||||
if (!record) return null;
|
||||
return {
|
||||
areaId: record.areaId,
|
||||
name: record.name,
|
||||
level: record.level,
|
||||
source: record.source,
|
||||
...(record.meta.country ? { country: record.meta.country } : {}),
|
||||
bbox: record.bbox.map((v) => round(v, 3)),
|
||||
areaKm2:
|
||||
record.areaKm2 >= 100
|
||||
? Math.round(record.areaKm2)
|
||||
: round(record.areaKm2, 2),
|
||||
parts: record.parts,
|
||||
holes: record.holes,
|
||||
...(record.approximate ? { approximate: true } : {}),
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,11 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
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([
|
||||
'youtube.com',
|
||||
@@ -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;
|
||||
@@ -569,7 +574,8 @@ function anchorOnScreen(viewer, anchor, root) {
|
||||
return { x, y, width: rootBounds.width, height: rootBounds.height };
|
||||
}
|
||||
|
||||
function placeCard(card, leader, anchor) {
|
||||
/** Place a media card beside its map anchor, in the lane between the panels. */
|
||||
export function placeCard(card, leader, anchor) {
|
||||
const margin = 18;
|
||||
const gap = 42;
|
||||
const width = card.offsetWidth || 392;
|
||||
@@ -580,22 +586,22 @@ function placeCard(card, leader, anchor) {
|
||||
let laneRight = anchor.width - margin;
|
||||
let laneBottom = anchor.height - margin;
|
||||
if (rootBounds && documentRef?.querySelector) {
|
||||
const leftPanel = documentRef
|
||||
.querySelector('#scene-panel')
|
||||
?.getBoundingClientRect?.();
|
||||
const rightRail = documentRef
|
||||
.querySelector('#right-context-rail')
|
||||
?.getBoundingClientRect?.();
|
||||
const commandDock = documentRef
|
||||
.querySelector('#command-dock')
|
||||
?.getBoundingClientRect?.();
|
||||
if (leftPanel?.width > 0)
|
||||
laneLeft = Math.max(laneLeft, leftPanel.right - rootBounds.left + margin);
|
||||
if (rightRail?.width > 0)
|
||||
laneRight = Math.min(
|
||||
laneRight,
|
||||
rightRail.left - rootBounds.left - margin,
|
||||
);
|
||||
// The scene panel and the context rail swap sides in right-to-left
|
||||
// languages: each narrows the lane from the side it sits on.
|
||||
for (const selector of ['#scene-panel', '#right-context-rail']) {
|
||||
const panel = documentRef
|
||||
.querySelector(selector)
|
||||
?.getBoundingClientRect?.();
|
||||
if (!(panel?.width > 0)) continue;
|
||||
const start = panel.left - rootBounds.left;
|
||||
const end = panel.right - rootBounds.left;
|
||||
if (start + end < rootBounds.width)
|
||||
laneLeft = Math.max(laneLeft, end + margin);
|
||||
else laneRight = Math.min(laneRight, start - margin);
|
||||
}
|
||||
if (commandDock?.height > 0)
|
||||
laneBottom = Math.min(
|
||||
laneBottom,
|
||||
@@ -635,6 +641,8 @@ 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;
|
||||
@@ -674,6 +682,30 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
let record = null;
|
||||
let warmRecord = null;
|
||||
let generation = 0;
|
||||
// Text the cards show, kept as the calls that word it so a locale change
|
||||
// words it again. A node is forgotten once it has left the page.
|
||||
const worded = new Map();
|
||||
function forgetDetached() {
|
||||
for (const node of worded.keys())
|
||||
if (!node.isConnected) worded.delete(node);
|
||||
}
|
||||
function word(node, property, text) {
|
||||
let properties = worded.get(node);
|
||||
if (!properties) worded.set(node, (properties = new Map()));
|
||||
properties.set(property, text);
|
||||
writeWord(node, property, text());
|
||||
}
|
||||
function writeWord(node, property, value) {
|
||||
if (property === 'textContent' || property === 'title')
|
||||
node[property] = value;
|
||||
else node.setAttribute(property, value);
|
||||
}
|
||||
const offLocale = onLocaleChange(() => {
|
||||
forgetDetached();
|
||||
for (const [node, properties] of worded)
|
||||
for (const [property, text] of properties)
|
||||
writeWord(node, property, text());
|
||||
});
|
||||
const leavingRecords = new Set();
|
||||
|
||||
const prefersReducedMotion = () =>
|
||||
@@ -818,6 +850,7 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
current.youtubeSession?.destroy();
|
||||
current.card?.remove?.();
|
||||
leavingRecords.delete(current);
|
||||
forgetDetached();
|
||||
}
|
||||
|
||||
const position = () => {
|
||||
@@ -839,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();
|
||||
@@ -871,6 +904,7 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
destroyFacebookSession(warmRecord.facebookSession);
|
||||
else warmRecord.iframe?.remove?.();
|
||||
warmRecord = null;
|
||||
forgetDetached();
|
||||
}
|
||||
|
||||
function takeWarmFacebook(key, host) {
|
||||
@@ -917,9 +951,11 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
startAtSec,
|
||||
endAtSec,
|
||||
});
|
||||
iframe.title = t('Preloading {provider} media', {
|
||||
provider: providerLabel(source.provider),
|
||||
});
|
||||
word(iframe, 'title', () =>
|
||||
t('Preloading {provider} media', {
|
||||
provider: providerLabel(source.provider),
|
||||
}),
|
||||
);
|
||||
iframe.tabIndex = -1;
|
||||
iframe.setAttribute('aria-hidden', 'true');
|
||||
iframe.loading = 'eager';
|
||||
@@ -930,7 +966,7 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
}
|
||||
|
||||
async function mountX(current, token) {
|
||||
current.status.textContent = t('LOADING X POST…');
|
||||
word(current.status, 'textContent', () => t('LOADING X POST…'));
|
||||
try {
|
||||
const api = await xLoader(documentRef, globalRef);
|
||||
if (token !== generation || record !== current) return;
|
||||
@@ -950,14 +986,18 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
throw new Error(
|
||||
msg('The X post is unavailable or cannot be embedded.'),
|
||||
);
|
||||
current.status.textContent = t('X POST · PROVIDER CONTROLS');
|
||||
word(current.status, 'textContent', () =>
|
||||
t('X POST · PROVIDER CONTROLS'),
|
||||
);
|
||||
position();
|
||||
} catch (error) {
|
||||
if (token !== generation || record !== current) return;
|
||||
current.card.classList.add('is-unavailable');
|
||||
current.status.textContent = t('{reason} OPEN ORIGINAL.', {
|
||||
reason: t(String(error?.message || msg('X embed unavailable'))),
|
||||
});
|
||||
word(current.status, 'textContent', () =>
|
||||
t('{reason} OPEN ORIGINAL.', {
|
||||
reason: t(String(error?.message || msg('X embed unavailable'))),
|
||||
}),
|
||||
);
|
||||
position();
|
||||
}
|
||||
}
|
||||
@@ -970,22 +1010,28 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
session.shouldPlay = autoplay === true;
|
||||
session.onReady = () => {
|
||||
if (token !== generation || record !== current) return;
|
||||
current.status.textContent = t('FACEBOOK · PROVIDER CONTROLS');
|
||||
word(current.status, 'textContent', () =>
|
||||
t('FACEBOOK · PROVIDER CONTROLS'),
|
||||
);
|
||||
current.card.classList.remove('is-unavailable');
|
||||
position();
|
||||
};
|
||||
session.onError = (error) => {
|
||||
if (token !== generation || record !== current) return;
|
||||
current.card.classList.add('is-unavailable');
|
||||
current.status.textContent = t('{reason} OPEN ORIGINAL.', {
|
||||
reason: t(String(error?.message || msg('Facebook embed unavailable'))),
|
||||
});
|
||||
word(current.status, 'textContent', () =>
|
||||
t('{reason} OPEN ORIGINAL.', {
|
||||
reason: t(
|
||||
String(error?.message || msg('Facebook embed unavailable')),
|
||||
),
|
||||
}),
|
||||
);
|
||||
position();
|
||||
};
|
||||
session.onPlaybackBlocked = () => {
|
||||
if (token !== generation || record !== current) return;
|
||||
current.status.textContent = t(
|
||||
'AUTOPLAY BLOCKED · USE PROVIDER CONTROLS',
|
||||
word(current.status, 'textContent', () =>
|
||||
t('AUTOPLAY BLOCKED · USE PROVIDER CONTROLS'),
|
||||
);
|
||||
};
|
||||
if (session.ready) session.onReady();
|
||||
@@ -1036,8 +1082,7 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
const portraitClass = isPortraitMedia(media) ? ' is-portrait' : '';
|
||||
card.className = `bhote-embedded-callout is-${source.provider}${portraitClass}`;
|
||||
card.dataset.provider = source.provider;
|
||||
card.setAttribute(
|
||||
'aria-label',
|
||||
word(card, 'aria-label', () =>
|
||||
t('Embedded {provider} media for {source}', {
|
||||
provider: providerLabel(source.provider),
|
||||
source: observation?.title
|
||||
@@ -1054,25 +1099,31 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
leader.innerHTML =
|
||||
'<path pathLength="1" fill="none" stroke="rgba(147,213,228,.72)" stroke-width="1.5"/><circle r="4" fill="#6be8ff" stroke="#ffffff" stroke-width="1.5"/>';
|
||||
const player = documentRef.createElement('div');
|
||||
player.className = 'bhote-embedded-callout-player';
|
||||
player.className = 'bhote-embedded-callout-player ui-scroll';
|
||||
const footer = documentRef.createElement('footer');
|
||||
const title = documentRef.createElement('strong');
|
||||
title.textContent = bhoteEventText(
|
||||
observation?.shortTitle || observation?.title || t('Witness source'),
|
||||
).toUpperCase();
|
||||
word(title, 'textContent', () =>
|
||||
bhoteEventText(
|
||||
observation?.shortTitle || observation?.title || t('Witness source'),
|
||||
).toUpperCase(),
|
||||
);
|
||||
const status = documentRef.createElement('small');
|
||||
status.setAttribute('role', 'status');
|
||||
status.textContent = t('{provider} · EMBEDDED SOURCE', {
|
||||
provider: providerLabel(source.provider),
|
||||
});
|
||||
word(status, 'textContent', () =>
|
||||
t('{provider} · EMBEDDED SOURCE', {
|
||||
provider: providerLabel(source.provider),
|
||||
}),
|
||||
);
|
||||
const link = documentRef.createElement('a');
|
||||
link.href = source.url;
|
||||
link.target = '_blank';
|
||||
link.rel = 'noopener noreferrer';
|
||||
link.textContent = t('OPEN ORIGINAL ↗');
|
||||
word(link, 'textContent', () => t('OPEN ORIGINAL ↗'));
|
||||
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);
|
||||
@@ -1109,12 +1160,14 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
url.searchParams.set('origin', globalRef.location.origin);
|
||||
iframe.src = url.href;
|
||||
}
|
||||
iframe.title = t('{provider} media: {source}', {
|
||||
provider: providerLabel(source.provider),
|
||||
source: observation?.title
|
||||
? bhoteEventText(observation.title)
|
||||
: t('witness source'),
|
||||
});
|
||||
word(iframe, 'title', () =>
|
||||
t('{provider} media: {source}', {
|
||||
provider: providerLabel(source.provider),
|
||||
source: observation?.title
|
||||
? bhoteEventText(observation.title)
|
||||
: t('witness source'),
|
||||
}),
|
||||
);
|
||||
iframe.allow =
|
||||
'autoplay; encrypted-media; picture-in-picture; fullscreen';
|
||||
iframe.allowFullscreen = true;
|
||||
@@ -1131,9 +1184,11 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
record.youtubeSession.getState().phase,
|
||||
)
|
||||
) {
|
||||
status.textContent = t('{provider} · PROVIDER CONTROLS', {
|
||||
provider: providerLabel(source.provider),
|
||||
});
|
||||
word(status, 'textContent', () =>
|
||||
t('{provider} · PROVIDER CONTROLS', {
|
||||
provider: providerLabel(source.provider),
|
||||
}),
|
||||
);
|
||||
}
|
||||
position();
|
||||
},
|
||||
@@ -1151,11 +1206,13 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
isCurrent: () => token === generation && record === current,
|
||||
onStatus: (phase) => {
|
||||
if (phase !== 'completed')
|
||||
status.textContent = t('YOUTUBE {state} · OPEN ORIGINAL', {
|
||||
state: YOUTUBE_PHASE_LABELS[phase]
|
||||
? t(YOUTUBE_PHASE_LABELS[phase])
|
||||
: phase.toUpperCase(),
|
||||
});
|
||||
word(status, 'textContent', () =>
|
||||
t('YOUTUBE {state} · OPEN ORIGINAL', {
|
||||
state: YOUTUBE_PHASE_LABELS[phase]
|
||||
? t(YOUTUBE_PHASE_LABELS[phase])
|
||||
: phase.toUpperCase(),
|
||||
}),
|
||||
);
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1165,6 +1222,8 @@ export function createBhoteKoshiEmbeddedMedia({
|
||||
}
|
||||
|
||||
function destroy() {
|
||||
offLocale();
|
||||
worded.clear();
|
||||
hide({ immediate: true });
|
||||
for (const current of [...leavingRecords]) removeRecord(current);
|
||||
clearWarm();
|
||||
|
||||
@@ -6,9 +6,11 @@ import {
|
||||
createBhoteKoshiEmbeddedMedia,
|
||||
createTrimmedYouTubePlayback,
|
||||
embeddedMediaFrameUrl,
|
||||
placeCard,
|
||||
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'); };
|
||||
@@ -348,7 +350,7 @@ test('camera updates retain a preload until the visible player loads', () => {
|
||||
assert.equal(frame.parent, root, 'keep the preload while the visible player starts');
|
||||
const card = root.children.find(node => node.tag === 'section');
|
||||
const body = card.children.find(node => node.className === 'bhote-embedded-callout-body');
|
||||
const player = body.children.find(node => node.className === 'bhote-embedded-callout-player');
|
||||
const player = body.children.find(node => node.className.split(' ').includes('bhote-embedded-callout-player'));
|
||||
player.children.find(node => node.tag === 'iframe').dispatchEvent(new Event('load'));
|
||||
assert.equal(frame.parent, null, 'visible player readiness releases the preload');
|
||||
media.destroy();
|
||||
@@ -394,3 +396,77 @@ test('pausing cancels a mounted Facebook preload and rejects its late ready call
|
||||
assert.deepEqual(playerCalls, []);
|
||||
media.destroy();
|
||||
});
|
||||
|
||||
test('a media card stays between the panels when right-to-left swaps their sides', () => {
|
||||
const rect = (left, right, top = 0, bottom = 900) => ({ left, right, top, bottom, width: right - left, height: bottom - top });
|
||||
// Arabic: the scene panel sits on the right, the context rail on the left.
|
||||
const panels = {
|
||||
'#scene-panel': rect(1040, 1420),
|
||||
'#right-context-rail': rect(20, 340),
|
||||
'#command-dock': rect(500, 940, 820, 880),
|
||||
};
|
||||
const card = {
|
||||
offsetWidth: 392,
|
||||
offsetHeight: 360,
|
||||
parentElement: { getBoundingClientRect: () => rect(0, 1440) },
|
||||
ownerDocument: { querySelector: (selector) => ({ getBoundingClientRect: () => panels[selector] }) },
|
||||
classList: { contains: () => false },
|
||||
style: {},
|
||||
};
|
||||
placeCard(card, { querySelector: () => null }, { x: 700, y: 400, width: 1440, height: 900 });
|
||||
const left = parseFloat(card.style.left);
|
||||
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();
|
||||
});
|
||||
+595
-458
File diff suppressed because it is too large.
Load diff
+600
-181
File diff suppressed because it is too large.
Load diff
+372
-298
@@ -1,9 +1,16 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
clearOverlaySource,
|
||||
setOverlayEntries,
|
||||
} from '../overlays/worldOverlay.js';
|
||||
import { inputFor } from '../input/dispatcher.js';
|
||||
import { clickCard } from './pickRegistry.js';
|
||||
import { isTrackingSelectionGesture } from './trackingClickGesture.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,
|
||||
@@ -12,9 +19,9 @@ import {
|
||||
} from './dataCredits.js';
|
||||
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
|
||||
import { INCIDENT_OVERVIEW_PLACES } from './bhoteKoshiIncidentPlaces.js';
|
||||
import { t, msg, getLocale } from '../i18n/index.js';
|
||||
import { t, msg, getLocale, isolate } from '../i18n/index.js';
|
||||
|
||||
export const BHOTE_KOSHI_LOCATOR_LAYER_ID = 'bhote-koshi-locator';
|
||||
const BHOTE_KOSHI_LOCATOR_LAYER_ID = 'bhote-koshi-locator';
|
||||
export const BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID =
|
||||
'bhote-koshi-locator-callout';
|
||||
export const NEPAL_CONTEXT_PRESENTATION = 'nepal-context';
|
||||
@@ -35,7 +42,6 @@ const BORDER_START_DELAY_MS = 700;
|
||||
const INCIDENT_CALLOUT_GAP_MS = 200;
|
||||
const CALLOUT_REVEAL_DURATION_MS = 1200;
|
||||
const CALLOUT_PULSE_DURATION_MS = 1800;
|
||||
const CALLOUT_DOT_SIZE_PX = 7;
|
||||
const CALLOUT_RING_MIN_SIZE_PX = 16;
|
||||
const CALLOUT_RING_SIZE_RANGE_PX = 14;
|
||||
const CITY_CALLOUT_START_DELAY_MS = 350;
|
||||
@@ -68,7 +74,10 @@ const PLACE_TITLE_TEXT = new Map(
|
||||
|
||||
function placeTitle(title) {
|
||||
const text = PLACE_TITLE_TEXT.get(title);
|
||||
return text ? t(text).toLocaleUpperCase(getLocale()) : title;
|
||||
// Isolated: the card draws left to right after its "11 · " counter, so in
|
||||
// Arabic a translated title with a Latin place name («نقطة الإطلالة في
|
||||
// DANDAGAUN») must keep its own right-to-left order.
|
||||
return text ? isolate(t(text).toLocaleUpperCase(getLocale())) : title;
|
||||
}
|
||||
|
||||
const INCIDENT = Object.freeze({
|
||||
@@ -142,10 +151,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,
|
||||
@@ -192,10 +202,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)));
|
||||
@@ -217,26 +223,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. */
|
||||
@@ -281,16 +282,32 @@ export function createBhoteKoshiLocatorLayer({
|
||||
cancelFrame = (handle) => cancelAnimationFrame(handle),
|
||||
scheduleDelay = (callback, delayMs) => setTimeout(callback, delayMs),
|
||||
cancelDelay = (handle) => clearTimeout(handle),
|
||||
input = inputFor,
|
||||
} = {}) {
|
||||
let _viewer = null;
|
||||
let _dataSource = null;
|
||||
// The globe click that opens an actionable callout of ours on top.
|
||||
let _removeClick = 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;
|
||||
@@ -330,30 +347,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,
|
||||
{
|
||||
@@ -363,51 +514,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,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -496,25 +623,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,
|
||||
@@ -529,30 +653,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({
|
||||
@@ -616,8 +729,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 = () => {
|
||||
@@ -625,50 +738,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() {
|
||||
@@ -679,40 +796,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 +
|
||||
@@ -722,11 +835,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,
|
||||
@@ -763,7 +872,6 @@ export function createBhoteKoshiLocatorLayer({
|
||||
}
|
||||
|
||||
function addIncidentPlaceCallouts(
|
||||
dataSource,
|
||||
sequenceStartedAt,
|
||||
{ pulseHalos = false, places = INCIDENT_OVERVIEW_PLACES } = {},
|
||||
) {
|
||||
@@ -776,11 +884,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;
|
||||
@@ -808,30 +912,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,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -870,105 +963,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,
|
||||
});
|
||||
@@ -985,8 +1040,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 =
|
||||
@@ -998,21 +1053,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');
|
||||
@@ -1021,24 +1077,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');
|
||||
@@ -1056,13 +1108,12 @@ 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);
|
||||
installCalloutClick(viewer);
|
||||
requestRender('bhote-koshi-locator-callout');
|
||||
|
||||
try {
|
||||
@@ -1082,7 +1133,7 @@ export function createBhoteKoshiLocatorLayer({
|
||||
return true;
|
||||
} catch (error) {
|
||||
if (error?.name === 'AbortError') {
|
||||
if (generation === _generation) removeDataSource();
|
||||
if (generation === _generation) removeDrawn();
|
||||
throw error;
|
||||
}
|
||||
console.warn(
|
||||
@@ -1097,14 +1148,40 @@ export function createBhoteKoshiLocatorLayer({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* An actionable callout of ours (the trigger record's) is a card painted
|
||||
* over the globe: a click on it opens its source, as its keyboard action
|
||||
* does. Like the other cards, it leaves a drag alone and, on top, takes the
|
||||
* click over whatever is drawn under it.
|
||||
*/
|
||||
function installCalloutClick(viewer) {
|
||||
if (_removeClick) return;
|
||||
let clicks = null;
|
||||
try {
|
||||
clicks = input?.(viewer) ?? null;
|
||||
} catch {
|
||||
clicks = null;
|
||||
}
|
||||
_removeClick =
|
||||
clicks?.onClick?.((event) => {
|
||||
if (!_enabled || !isTrackingSelectionGesture(event.gesture)) return;
|
||||
// The card painted on top, read once per click so every layer agrees.
|
||||
const top = clickCard(event);
|
||||
if (top?.sourceId !== BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID) return;
|
||||
if (typeof top.entry?.activate === 'function') top.entry.activate();
|
||||
}) ?? null;
|
||||
}
|
||||
|
||||
async function disable() {
|
||||
hideOsmCredit(_viewer, BHOTE_KOSHI_LOCATOR_LAYER_ID);
|
||||
_removeClick?.();
|
||||
_removeClick = null;
|
||||
_enabled = false;
|
||||
_boundaryReady = false;
|
||||
_boundaryResolved = false;
|
||||
_boundaryRing = null;
|
||||
_generation += 1;
|
||||
removeDataSource();
|
||||
removeDrawn();
|
||||
requestRender('bhote-koshi-locator-disable');
|
||||
return true;
|
||||
}
|
||||
@@ -1248,6 +1325,3 @@ export function createBhoteKoshiLocatorLayer({
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
const bhoteKoshiLocatorLayer = createBhoteKoshiLocatorLayer();
|
||||
export default bhoteKoshiLocatorLayer;
|
||||
+319
-155
@@ -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';
|
||||
@@ -8,6 +11,11 @@ import {
|
||||
import { BHOTE_KOSHI_FLOOD_PATH } from './bhoteKoshiFloodPath.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
registerPickOwner,
|
||||
setClickCardHitTest,
|
||||
unregisterPickOwner,
|
||||
} from './pickRegistry.js';
|
||||
import { SceneDirector } from '../scenes/director.js';
|
||||
import { createPlaybackClock } from '../director/clock.js';
|
||||
import { createDefaultScenePacks } from '../scenes/packs/defaults.js';
|
||||
@@ -24,32 +32,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 +166,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 +200,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 +214,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 +262,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 +300,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 +328,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 +348,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 +358,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 +380,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 +395,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 +418,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 +432,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 +453,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 +503,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 +523,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 +603,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 +616,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 +657,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 +676,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 +685,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 +741,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(),
|
||||
@@ -728,6 +784,8 @@ for (const phase of ['timer', 'move-end', 'approach', 'orbit']) {
|
||||
viewer,
|
||||
_sceneSeekGeneration: 0,
|
||||
_loadGeneration: 0,
|
||||
_bumpSceneSeekGeneration:
|
||||
SceneDirector.prototype._bumpSceneSeekGeneration,
|
||||
_cancelActiveSceneTravel:
|
||||
SceneDirector.prototype._cancelActiveSceneTravel,
|
||||
_setSceneMediaPlayback: SceneDirector.prototype._setSceneMediaPlayback,
|
||||
@@ -743,8 +801,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();
|
||||
@@ -805,8 +865,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',
|
||||
@@ -821,7 +880,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');
|
||||
@@ -864,9 +924,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);
|
||||
@@ -897,15 +955,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),
|
||||
@@ -921,14 +973,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),
|
||||
@@ -958,6 +1005,123 @@ 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);
|
||||
});
|
||||
|
||||
// The trigger record's callout is an actionable card: the layers under it
|
||||
// stand aside for it, so a click on it opens its source, as its keyboard
|
||||
// action does; anything else on top is left alone.
|
||||
test('a click on the locator callout runs its action', async () => {
|
||||
const viewer = viewerFixture();
|
||||
let onClick = null;
|
||||
let top = null;
|
||||
const activated = [];
|
||||
const layer = createBhoteKoshiLocatorLayer({
|
||||
overlayHost: overlayHostFixture(),
|
||||
requestRender() {},
|
||||
...nonRunningAnimation(),
|
||||
input: () => ({
|
||||
onClick(callback) {
|
||||
onClick = callback;
|
||||
return () => {
|
||||
onClick = null;
|
||||
};
|
||||
},
|
||||
}),
|
||||
});
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
setClickCardHitTest(() => top);
|
||||
await layer.init(viewer);
|
||||
await layer.enable(viewer);
|
||||
const click = (extra = {}) =>
|
||||
onClick?.({
|
||||
screenPosition: { x: 5, y: 5 },
|
||||
gesture: { travelPx: 0, durationMs: 80 },
|
||||
topHit: null,
|
||||
hit: null,
|
||||
...extra,
|
||||
});
|
||||
top = {
|
||||
sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
|
||||
entryId: 'bhote-koshi-trigger-record-callout',
|
||||
entry: { activate: () => activated.push('trigger') },
|
||||
};
|
||||
click();
|
||||
assert.deepEqual(activated, ['trigger']);
|
||||
top = {
|
||||
sourceId: 'earthquake-card',
|
||||
entry: { activate: () => activated.push('other') },
|
||||
};
|
||||
click();
|
||||
assert.deepEqual(activated, ['trigger'], 'another layer on top is its own');
|
||||
// A drag that ends on it is not a click on it.
|
||||
top = {
|
||||
sourceId: BHOTE_KOSHI_LOCATOR_OVERLAY_SOURCE_ID,
|
||||
entry: { activate: () => activated.push('trigger') },
|
||||
};
|
||||
click({ gesture: { travelPx: 30, durationMs: 80 } });
|
||||
assert.deepEqual(activated, ['trigger'], 'a drag does not open it');
|
||||
// On top, it takes the click over an aircraft or a camera under it, exact
|
||||
// or a touch contact: those layers stand aside under a card.
|
||||
registerPickOwner('test-planes', (id) => id === 'plane:1');
|
||||
try {
|
||||
const plane = { set: 'planes:1', id: 'plane:1' };
|
||||
const cam = { set: 'cams:1', id: 'cam:1' };
|
||||
click({ topHit: plane, hit: plane });
|
||||
click({ topHit: null, hit: plane });
|
||||
click({ topHit: cam, hit: cam });
|
||||
assert.equal(activated.length, 4, 'the callout on top acts each time');
|
||||
} finally {
|
||||
unregisterPickOwner('test-planes');
|
||||
setClickCardHitTest(null);
|
||||
}
|
||||
await layer.disable();
|
||||
assert.equal(onClick, null, 'disable removes the click handler');
|
||||
});
|
||||
@@ -0,0 +1,212 @@
|
||||
// src/data/bhoteKoshiPanelView.test.mjs — the context rail renders the Bhote
|
||||
// Koshi reconstruction panel the event layer presents and sends its clicks
|
||||
// and slider moves back.
|
||||
import '../testSupport/registerDom.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createApp, nextTick } from 'vue';
|
||||
import { createPinia } from 'pinia';
|
||||
import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js';
|
||||
import ContextView from '../ui/views/ContextView.vue';
|
||||
|
||||
const record = (initial = {}) => ({
|
||||
textContent: '',
|
||||
hidden: false,
|
||||
disabled: false,
|
||||
value: '',
|
||||
attributes: {},
|
||||
...initial,
|
||||
});
|
||||
|
||||
function presentation(patch = {}) {
|
||||
return {
|
||||
owner: {},
|
||||
sceneBeat: false,
|
||||
beforeDate: { name: 'Historical reference', date: '2021-05-01' },
|
||||
afterDate: { name: 'Post-event', date: '' },
|
||||
reports: [
|
||||
{ label: 'Report A', status: 'Verified' },
|
||||
{ label: 'Report B', status: 'Unverified' },
|
||||
],
|
||||
refs: {
|
||||
imagerySection: record(),
|
||||
observedStatus: record(),
|
||||
time: record({ textContent: '~0:00 / 2:00' }),
|
||||
caveat: record({ textContent: 'Schematic only.' }),
|
||||
imageryCloudNote: record(),
|
||||
playButton: record({ textContent: '▶ PLAY' }),
|
||||
playSceneButton: record({ textContent: '▶ PLAY SCENE', hidden: true }),
|
||||
cinematicButton: record({
|
||||
textContent: '◉ CINEMATIC',
|
||||
attributes: { 'aria-pressed': 'false' },
|
||||
}),
|
||||
storyReplayButton: record({ textContent: '↺ FULL STORY' }),
|
||||
corridorButton: record(),
|
||||
previousButton: record({
|
||||
disabled: true,
|
||||
attributes: { 'aria-label': 'Previous story beat' },
|
||||
}),
|
||||
nextButton: record({ attributes: { 'aria-label': 'Next story beat' } }),
|
||||
openSourceButton: record(),
|
||||
progressInput: record({
|
||||
value: '0',
|
||||
attributes: { 'aria-label': 'Schematic downstream progression' },
|
||||
}),
|
||||
splitInput: record({ value: '50' }),
|
||||
splitReadout: record({ textContent: '50 / 50' }),
|
||||
timelineLabel: record({ textContent: 'RECONSTRUCTION CLOCK' }),
|
||||
beatIndex: record({ textContent: '01 / 06' }),
|
||||
beatTitle: record({ textContent: 'CAUSE' }),
|
||||
beatMeta: record({ textContent: 'CAPTURE TIME UNVERIFIED' }),
|
||||
},
|
||||
...patch,
|
||||
};
|
||||
}
|
||||
|
||||
function fixture(t) {
|
||||
document.body.replaceChildren();
|
||||
const pinia = createPinia();
|
||||
const app = createApp(ContextView).use(pinia);
|
||||
app.mount(document.body.appendChild(document.createElement('div')));
|
||||
t.after(() => app.unmount());
|
||||
const store = useBhoteKoshiPanelStore(pinia);
|
||||
const calls = [];
|
||||
store.connect(
|
||||
new Proxy(
|
||||
{},
|
||||
{
|
||||
get:
|
||||
(_, name) =>
|
||||
(...args) =>
|
||||
calls.push([name, ...args]),
|
||||
},
|
||||
),
|
||||
);
|
||||
const rail = document.getElementById('right-context-rail');
|
||||
const $ = (selector) => rail.querySelector(selector);
|
||||
return { store, calls, rail, $ };
|
||||
}
|
||||
|
||||
test('the panel renders last in the context rail and marks the rail while on', async (t) => {
|
||||
const { store, rail, $ } = fixture(t);
|
||||
assert.equal($('#bhote-koshi-event-panel'), null);
|
||||
assert.equal(rail.classList.contains('bhote-event-active'), false);
|
||||
store.publish(presentation());
|
||||
await nextTick();
|
||||
const panel = $('#bhote-koshi-event-panel');
|
||||
assert.equal(panel.tagName, 'ASIDE');
|
||||
assert.ok(rail.lastElementChild === panel);
|
||||
assert.ok(rail.classList.contains('ui-scroll'));
|
||||
assert.ok(rail.classList.contains('bhote-event-active'));
|
||||
assert.equal(
|
||||
panel.getAttribute('aria-label'),
|
||||
'Bhote Koshi flood reconstruction controls',
|
||||
);
|
||||
assert.match(
|
||||
panel.textContent,
|
||||
/2021 HISTORICAL REFERENCE \/ 2026 POST-EVENT/,
|
||||
);
|
||||
assert.match(panel.textContent, /RECONSTRUCTION CLOCK/);
|
||||
assert.match(panel.textContent, /OPEN PUBLIC MAP/);
|
||||
assert.equal(
|
||||
$('[data-role="before-date"]').textContent,
|
||||
'Historical reference · 2021-05-01',
|
||||
);
|
||||
assert.equal(
|
||||
$('[data-role="before-date"] .bhote-event-date').textContent,
|
||||
'2021-05-01',
|
||||
);
|
||||
assert.equal($('[data-role="after-date"]').textContent, 'Post-event');
|
||||
assert.equal($('[data-role="after-date"] .bhote-event-date'), null);
|
||||
assert.equal($('[data-action="play-scene"]').hidden, true);
|
||||
assert.ok($('[data-action="open-source"]'));
|
||||
assert.equal($('[data-action="witness"]'), null);
|
||||
assert.doesNotMatch(panel.innerHTML, /witness/i);
|
||||
assert.equal($('[data-action="previous-beat"]').disabled, true);
|
||||
assert.equal($('[data-action="previous-beat"]').title, 'Previous story beat');
|
||||
assert.equal(
|
||||
$('[data-action="cinematic"]').getAttribute('aria-pressed'),
|
||||
'false',
|
||||
);
|
||||
assert.equal($('[data-action="play"]').hasAttribute('aria-label'), false);
|
||||
assert.equal($('[data-role="progress"]').value, '0');
|
||||
assert.equal($('[data-role="split"]').value, '50');
|
||||
assert.equal($('summary').textContent, 'FIELD REPORTS · 2');
|
||||
assert.deepEqual(
|
||||
[...$('.bhote-event-report-list').children].map(
|
||||
(button) => button.textContent,
|
||||
),
|
||||
['Report AVerified', 'Report BUnverified'],
|
||||
);
|
||||
store.publish(null);
|
||||
await nextTick();
|
||||
assert.equal($('#bhote-koshi-event-panel'), null);
|
||||
assert.equal(rail.classList.contains('bhote-event-active'), false);
|
||||
assert.ok(rail.classList.contains('ui-scroll'));
|
||||
});
|
||||
|
||||
test('a later presentation updates the controls in place', async (t) => {
|
||||
const { store, $ } = fixture(t);
|
||||
store.publish(presentation());
|
||||
await nextTick();
|
||||
const play = $('[data-action="play"]');
|
||||
const next = presentation({ sceneBeat: true });
|
||||
next.refs.playButton = record({
|
||||
textContent: '▶ PLAY SHOT',
|
||||
disabled: true,
|
||||
attributes: { 'aria-label': 'Play Global context' },
|
||||
});
|
||||
next.refs.progressInput = record({ value: '250', hidden: true });
|
||||
next.refs.imagerySection = record({ hidden: true });
|
||||
store.publish(next);
|
||||
await nextTick();
|
||||
assert.ok($('[data-action="play"]') === play);
|
||||
assert.equal(play.textContent, '▶ PLAY SHOT');
|
||||
assert.equal(play.disabled, true);
|
||||
assert.equal(play.getAttribute('aria-label'), 'Play Global context');
|
||||
assert.ok(
|
||||
$('#bhote-koshi-event-panel').classList.contains('bhote-event-scene-beat'),
|
||||
);
|
||||
assert.equal($('[data-role="progress"]').value, '250');
|
||||
assert.equal($('[data-role="progress"]').hidden, true);
|
||||
assert.equal($('[data-role="imagery-comparison"]').hidden, true);
|
||||
});
|
||||
|
||||
test('buttons, sliders and reports call the connected controls', async (t) => {
|
||||
const { store, calls, $ } = fixture(t);
|
||||
store.publish(presentation());
|
||||
await nextTick();
|
||||
for (const action of [
|
||||
'close',
|
||||
'play',
|
||||
'cinematic',
|
||||
'story-replay',
|
||||
'open-source',
|
||||
'corridor',
|
||||
'next-beat',
|
||||
'geolocation-map',
|
||||
])
|
||||
$(`[data-action="${action}"]`).click();
|
||||
$('.bhote-event-report-list').children[1].click();
|
||||
const progress = $('[data-role="progress"]');
|
||||
progress.value = '500';
|
||||
progress.dispatchEvent(new Event('input'));
|
||||
progress.dispatchEvent(new Event('change'));
|
||||
const split = $('[data-role="split"]');
|
||||
split.value = '25';
|
||||
split.dispatchEvent(new Event('input'));
|
||||
assert.deepEqual(calls, [
|
||||
['close'],
|
||||
['play'],
|
||||
['toggleCinematic'],
|
||||
['replayCinematic'],
|
||||
['openActiveSource'],
|
||||
['focusCorridor'],
|
||||
['nextBeat'],
|
||||
['openGeolocationMap'],
|
||||
['openReport', 1],
|
||||
['previewProgress', 0.5],
|
||||
['commitProgress', 0.5, { final: true }],
|
||||
['setSplit', 0.25],
|
||||
]);
|
||||
});
|
||||
@@ -23,4 +23,3 @@ export {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
} from '../layers/bikeshare/index.js';
|
||||
export default layer;
|
||||
+25
-15
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,171 @@
|
||||
// Outline names are drawn by the DOM annotation overlay, never as Cesium
|
||||
// text labels: the boundary data modules, the outline resolver and the
|
||||
// annotation renderers must not import or construct Cesium label primitives,
|
||||
// and drawing a bundled outline must create none at runtime.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
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');
|
||||
|
||||
/** Pure data modules: no Cesium at all. */
|
||||
const DATA_MODULES = [
|
||||
'./adminBoundaries.js',
|
||||
'./placeBoundaries.js',
|
||||
'./neighborhoodPolygons.js',
|
||||
'./local_data/us_census_places/files.js',
|
||||
'./local_data/wof_neighborhoods/files.js',
|
||||
];
|
||||
|
||||
/** Modules that draw outlines but must not draw text with Cesium. */
|
||||
const CESIUM_MODULES = [
|
||||
'../annotations/resolver.js',
|
||||
'../annotations/worldAnnotationRenderer.js',
|
||||
'../annotations/hybridAnnotationRenderer.js',
|
||||
];
|
||||
|
||||
/** The DOM overlay: callout elements, never Cesium label primitives. */
|
||||
const OVERLAY_MODULES = ['../annotations/screenAnnotationRenderer.js'];
|
||||
|
||||
const LABEL_PRIMITIVES = [
|
||||
/\bLabelCollection\b/,
|
||||
/\bLabelGraphics\b/,
|
||||
/\bLabelStyle\b/,
|
||||
/\bLabelVisualizer\b/,
|
||||
];
|
||||
|
||||
/** Entity label options, inline or assigned later. */
|
||||
const ENTITY_LABELS = [
|
||||
// `label: { text: … }` or `label: new …`
|
||||
/\blabel\s*:\s*\{[^{}]*\btext\s*:/s,
|
||||
/\blabel\s*:\s*new\b/,
|
||||
// `label: labelOptions` (anything but `null`)
|
||||
/\blabel\s*:\s*(?!null\b)[A-Za-z_$][\w$]*\s*[,}\n]/,
|
||||
// `entity.label = …`
|
||||
/\.label\s*=(?!=)/,
|
||||
];
|
||||
|
||||
test('boundary data modules never import Cesium', () => {
|
||||
for (const path of DATA_MODULES) {
|
||||
const source = read(path);
|
||||
assert.doesNotMatch(source, /from\s+['"]cesium['"]/, path);
|
||||
assert.doesNotMatch(source, /import\(\s*['"]cesium['"]/, path);
|
||||
}
|
||||
});
|
||||
|
||||
test('outline modules and renderers construct no Cesium labels', () => {
|
||||
for (const path of [...DATA_MODULES, ...CESIUM_MODULES, ...OVERLAY_MODULES])
|
||||
for (const pattern of LABEL_PRIMITIVES)
|
||||
assert.doesNotMatch(read(path), pattern, `${path}: ${pattern}`);
|
||||
for (const path of [...DATA_MODULES, ...CESIUM_MODULES])
|
||||
for (const pattern of ENTITY_LABELS)
|
||||
assert.doesNotMatch(read(path), pattern, `${path}: ${pattern}`);
|
||||
});
|
||||
|
||||
test('the static check catches a Cesium label however it is written', () => {
|
||||
const offending = [
|
||||
'viewer.scene.primitives.add(new Cesium.LabelCollection());',
|
||||
"viewer.entities.add({ position, label: { text: 'Austin' } });",
|
||||
'const graphics = new LabelGraphics({ text });',
|
||||
'viewer.entities.add({ position, label: labelOptions });',
|
||||
'entity.label = new Cesium.LabelGraphics(options);',
|
||||
'entity.label = options;',
|
||||
];
|
||||
const all = [...LABEL_PRIMITIVES, ...ENTITY_LABELS];
|
||||
for (const source of offending)
|
||||
assert.ok(
|
||||
all.some((pattern) => pattern.test(source)),
|
||||
source,
|
||||
);
|
||||
// Data, not Cesium labels: a result's label point, a stripped proxy label.
|
||||
for (const source of [
|
||||
'label: geometry.label,',
|
||||
'liveProxy(anno, { label: null });',
|
||||
'if (entity.label === x) {}',
|
||||
])
|
||||
assert.ok(!ENTITY_LABELS.some((p) => p.test(source)), source);
|
||||
});
|
||||
|
||||
test('drawing bundled place and neighborhood outlines creates no Cesium label', async (t) => {
|
||||
// Cesium's material setup checks for these browser image types.
|
||||
for (const name of [
|
||||
'HTMLCanvasElement',
|
||||
'HTMLImageElement',
|
||||
'ImageBitmap',
|
||||
'OffscreenCanvas',
|
||||
]) {
|
||||
if (name in globalThis) continue;
|
||||
globalThis[name] = class {};
|
||||
t.after(() => delete globalThis[name]);
|
||||
}
|
||||
const featureSource = {};
|
||||
for (const method of FEATURE_SOURCE_METHODS)
|
||||
featureSource[method] = async () => null;
|
||||
const { resolveAnnotationTarget } = createAnnotationResolver({
|
||||
featureSource,
|
||||
});
|
||||
const primitives = [];
|
||||
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) } },
|
||||
},
|
||||
{ draw },
|
||||
);
|
||||
const renderer = createWorldAnnotationRenderer(viewer);
|
||||
for (const [target, lon, lat] of [
|
||||
['Austin', -97.7431, 30.2672],
|
||||
['Notting Hill', -0.2, 51.511],
|
||||
]) {
|
||||
viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
|
||||
lon,
|
||||
lat,
|
||||
3000,
|
||||
);
|
||||
const resolved = await resolveAnnotationTarget({
|
||||
// The resolver reads only the camera (no query port to pick with).
|
||||
viewer,
|
||||
target,
|
||||
footprint: true,
|
||||
deferFootprint: true,
|
||||
});
|
||||
assert.equal(resolved.source, 'bundled', target);
|
||||
renderer.add({
|
||||
id: target,
|
||||
type: 'area',
|
||||
label: resolved.label,
|
||||
ring: resolved.ring,
|
||||
polygons: resolved.polygons,
|
||||
footprintKind: resolved.footprintKind,
|
||||
synthesized: resolved.synthesized,
|
||||
anchor: { lon: resolved.lon, lat: resolved.lat, height: 0 },
|
||||
color: 'primary',
|
||||
});
|
||||
}
|
||||
assert.equal(primitives.length, 0, 'no primitive collections');
|
||||
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();
|
||||
});
|
||||
@@ -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%
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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()] : [];
|
||||
}
|
||||
@@ -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;
|
||||
@@ -47,6 +48,8 @@ export const prioritizeActiveCctvGeometryRecord =
|
||||
export const processGeometryBatch = layer.processGeometryBatch;
|
||||
export const hideCctvRecordVisuals = layer.hideCctvRecordVisuals;
|
||||
export const refreshCoverageStyles = layer.refreshCoverageStyles;
|
||||
export const refreshHorizonCulling = layer.refreshHorizonCulling;
|
||||
export const _viewRecordIdsForTest = layer._viewRecordIdsForTest;
|
||||
export const clearProbeClampOnDeactivation =
|
||||
layer.clearProbeClampOnDeactivation;
|
||||
export const cctvRecordNeedsActivation = layer.cctvRecordNeedsActivation;
|
||||
@@ -63,8 +66,11 @@ 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;
|
||||
export const reopenNearestCamera = layer.reopenNearestCamera;
|
||||
export const cctvCycleIndex = layer.cctvCycleIndex;
|
||||
export {
|
||||
CCTV_CALIBRATION_STORAGE_KEY_V1,
|
||||
|
||||
+294
-163
@@ -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) {
|
||||
@@ -25,9 +30,6 @@ function componentFunctionSource(fn) {
|
||||
.replace(/\(\s+/g, '(');
|
||||
}
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import * as Cesium from 'cesium';
|
||||
import cctvLayer, {
|
||||
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -35,9 +37,11 @@ import cctvLayer, {
|
||||
_extractPickedCameraIdForTest,
|
||||
_updateCctvProjectionPlaneForTest,
|
||||
_setCctvCoverageStateForTest,
|
||||
_cctvIconsForTest,
|
||||
_pushAmbientCardEntriesForTest,
|
||||
_setCctvOverlayHostForTest,
|
||||
activationProbeClampRange,
|
||||
flatGroundAxisDistance,
|
||||
bindCctvWorldClickGesture,
|
||||
clearProbeClampOnDeactivation,
|
||||
computeFrustumGeometry,
|
||||
@@ -64,6 +68,8 @@ import cctvLayer, {
|
||||
materializeCctvActiveCoverageEntities,
|
||||
materializeCctvVisibleCoverageEntities,
|
||||
maybeAutoHop,
|
||||
openingCameraId,
|
||||
reopenNearestCamera,
|
||||
prioritizeActiveCctvGeometryRecord,
|
||||
processCctvGeometryDrainBatch,
|
||||
processCctvGeometryQueueBatch,
|
||||
@@ -82,37 +88,12 @@ import {
|
||||
IDLE_CAMERA_COLOR,
|
||||
LIVE_CAMERA_COLOR,
|
||||
} from '../layers/cctv/policy.js';
|
||||
|
||||
const CCTV_PRESENTATION_SOURCE = fs.readFileSync(
|
||||
path.join(
|
||||
path.dirname(fileURLToPath(import.meta.url)),
|
||||
'..',
|
||||
'ui',
|
||||
'cctvPresentation.js',
|
||||
),
|
||||
'utf8',
|
||||
);
|
||||
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;
|
||||
@@ -303,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 {
|
||||
@@ -326,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,
|
||||
@@ -345,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,
|
||||
@@ -360,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;
|
||||
@@ -388,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 }), {
|
||||
@@ -414,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: () => {},
|
||||
@@ -430,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,
|
||||
@@ -666,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 },
|
||||
@@ -695,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 = [];
|
||||
@@ -715,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',
|
||||
);
|
||||
@@ -726,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],
|
||||
@@ -738,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', () => {
|
||||
@@ -754,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,
|
||||
@@ -778,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]) =>
|
||||
@@ -804,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(
|
||||
@@ -832,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],
|
||||
@@ -840,6 +846,7 @@ test('real active monitor plane owns one protected host label and no native labe
|
||||
} finally {
|
||||
_setCctvCoverageStateForTest({ enabled: false });
|
||||
_setCctvOverlayHostForTest();
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -892,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 },
|
||||
@@ -930,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 },
|
||||
@@ -950,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 },
|
||||
@@ -1002,15 +1016,11 @@ 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),
|
||||
/_cctvOverlayHost\.hitTest/,
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/sourceId: CCTV_OVERLAY_SOURCE_ID/,
|
||||
/clickCard\?\.\(event\)/,
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
@@ -1018,17 +1028,15 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
|
||||
);
|
||||
assert.match(
|
||||
componentFunctionSource(cctvLayer.init),
|
||||
/activateCctvCameraFromWorldClick\(cardId, setActiveCamera\)/,
|
||||
/activateCctvCameraFromWorldClick\(\s*top\.entryId,/,
|
||||
);
|
||||
});
|
||||
|
||||
// ─── 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(
|
||||
@@ -1051,6 +1059,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) {
|
||||
@@ -1084,7 +1106,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',
|
||||
},
|
||||
@@ -1093,7 +1115,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',
|
||||
},
|
||||
@@ -1102,7 +1124,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',
|
||||
},
|
||||
@@ -1111,7 +1133,7 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
|
||||
);
|
||||
assert.equal(
|
||||
cctvEmptyClickDeselects(
|
||||
{ id: '' },
|
||||
{ set: '', id: '', surface: false },
|
||||
{
|
||||
activeCameraId: 'cam-1',
|
||||
},
|
||||
@@ -1121,75 +1143,103 @@ 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);
|
||||
assert.ok(
|
||||
initSource.indexOf('if (pickedId !== null) return') <
|
||||
initSource.indexOf('_cctvOverlayHost.hitTest'),
|
||||
'every identified sibling must win before an overlapping CCTV card hit test',
|
||||
);
|
||||
// The real init-bound click route, including identified-object barriers,
|
||||
// is exercised in layers/cctv/lifecycle.test.mjs.
|
||||
assert.match(initSource, /activeCameraId: _activeCameraId/);
|
||||
assert.match(initSource, /calibrationMode: _calibrationMode/);
|
||||
});
|
||||
|
||||
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();
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1230,7 +1280,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);
|
||||
@@ -1243,7 +1293,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);
|
||||
@@ -1255,7 +1305,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,19 +1352,6 @@ test('CCTV null-active coverage, auto-hop, cycling, and panel targets stay hones
|
||||
assert.equal(cctvCycleIndex(-1, -1, records.length), records.length - 1);
|
||||
assert.equal(cctvCycleIndex(2, 1, records.length), 0);
|
||||
assert.equal(cctvCycleIndex(0, -1, records.length), records.length - 1);
|
||||
|
||||
const renderer = CCTV_PRESENTATION_SOURCE.match(
|
||||
/_renderCctvState\(state\) \{[\s\S]*?\n\}\n/,
|
||||
);
|
||||
assert.ok(renderer, '_renderCctvState is missing');
|
||||
assert.match(
|
||||
renderer[0],
|
||||
/else if \(!activeId\)[\s\S]*?selectedIndex = -1/,
|
||||
);
|
||||
assert.match(
|
||||
renderer[0],
|
||||
/_cctvFocusBtn\.disabled\s*=\s*!enabled\s*\|\|\s*cameras\.length === 0\s*\|\|\s*!activeId/,
|
||||
);
|
||||
} finally {
|
||||
cctvLayer.setParams({ autoHop: false });
|
||||
_setCctvOverlayHostForTest();
|
||||
@@ -1322,6 +1359,107 @@ test('CCTV null-active coverage, auto-hop, cycling, and panel targets stay hones
|
||||
}
|
||||
});
|
||||
|
||||
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.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');
|
||||
london.camera = { ...london.camera, lat: 51.5318, lon: -0.1209 };
|
||||
try {
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer,
|
||||
records: [sydney, london],
|
||||
activeCameraId: null,
|
||||
enabled: false,
|
||||
});
|
||||
assert.equal(openingCameraId(), 'gb-kings-cross');
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: null,
|
||||
records: [sydney, london],
|
||||
activeCameraId: null,
|
||||
enabled: false,
|
||||
});
|
||||
assert.equal(
|
||||
openingCameraId(),
|
||||
'au-sydney',
|
||||
'with no viewer position the first record is the fallback',
|
||||
);
|
||||
_setCctvCoverageStateForTest({ viewer, records: [], enabled: false });
|
||||
assert.equal(openingCameraId(), null);
|
||||
} finally {
|
||||
_setCctvCoverageStateForTest({ enabled: false });
|
||||
}
|
||||
});
|
||||
|
||||
test('the opening camera follows a shared view that lands after CCTV turned on, until someone picks one', () => {
|
||||
// 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.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');
|
||||
london.camera = { ...london.camera, lat: 51.5318, lon: -0.1209 };
|
||||
for (const record of [sydney, london])
|
||||
Object.assign(record, {
|
||||
groundResolved: {},
|
||||
groundSamples: {},
|
||||
groundPrior: 0,
|
||||
frustumGeometry: null,
|
||||
frustumPositions: null,
|
||||
probeClampRangeM: null,
|
||||
});
|
||||
_setCctvOverlayHostForTest({
|
||||
setEntries() {},
|
||||
setVisible() {},
|
||||
clearSource() {},
|
||||
});
|
||||
// Activation builds the projection canvas and frame image.
|
||||
const originalDocument = globalThis.document;
|
||||
const originalImage = globalThis.Image;
|
||||
globalThis.document = {
|
||||
createElement: () => ({ getContext: () => null }),
|
||||
};
|
||||
globalThis.Image = class {};
|
||||
try {
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer,
|
||||
records: [sydney, london],
|
||||
activeCameraId: 'au-sydney',
|
||||
enabled: true,
|
||||
openingCameraProvisional: true,
|
||||
});
|
||||
assert.equal(reopenNearestCamera(), true);
|
||||
assert.equal(cctvLayer.getUIState().activeCameraId, 'gb-kings-cross');
|
||||
assert.equal(reopenNearestCamera(), false, 'already the nearest');
|
||||
|
||||
// Someone chooses a camera: settled moves leave it alone.
|
||||
setActiveCamera('au-sydney');
|
||||
assert.equal(reopenNearestCamera(), false);
|
||||
assert.equal(cctvLayer.getUIState().activeCameraId, 'au-sydney');
|
||||
|
||||
// A deselect is a choice too.
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer,
|
||||
records: [sydney, london],
|
||||
activeCameraId: 'au-sydney',
|
||||
enabled: true,
|
||||
openingCameraProvisional: true,
|
||||
});
|
||||
deactivateActiveCamera();
|
||||
assert.equal(reopenNearestCamera(), false);
|
||||
assert.equal(cctvLayer.getUIState().activeCameraId, null);
|
||||
} finally {
|
||||
globalThis.document = originalDocument;
|
||||
globalThis.Image = originalImage;
|
||||
_setCctvOverlayHostForTest();
|
||||
_setCctvCoverageStateForTest({ enabled: false });
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV disable clears and hides its shared-host source through the real layer lifecycle', () => {
|
||||
const calls = [];
|
||||
_setCctvOverlayHostForTest({
|
||||
@@ -1427,29 +1565,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;
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
a22WebcamToSource,
|
||||
loadA22SourcesFromOpenDataHub,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
A22_DEFAULT_GROUND_ELEVATION_M,
|
||||
A22_IMAGE_ORIGIN,
|
||||
DEFAULT_A22_CCTV_URL,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
import { fetchWithinHost } from '../../server/providers/cctv/media.js';
|
||||
import { staticFrameRefreshMs } from './cctvLod.js';
|
||||
|
||||
/** One Open Data Hub `WebcamInfo` item, shaped like the live a22 payload. */
|
||||
const item = (
|
||||
patch = {},
|
||||
{ km = '68', lat = 46.53591, lon = 11.49772 } = {},
|
||||
) => ({
|
||||
Id: `A22_${km}`,
|
||||
Active: true,
|
||||
Source: 'a22',
|
||||
Shortname: 'ADS Sciliar',
|
||||
Webcamname: { it: 'ADS Sciliar' },
|
||||
Webcamurl: `https://www.autobrennero.it/WebCamImg/km${km}.jpg`,
|
||||
Mapping: { a22: { km } },
|
||||
GpsInfo: [{ Gpstype: 'position', Latitude: lat, Longitude: lon }],
|
||||
LicenseInfo: {
|
||||
ClosedData: false,
|
||||
LicenseHolder: 'https://www.autobrennero.it/',
|
||||
},
|
||||
...patch,
|
||||
});
|
||||
|
||||
test('an A22 webcam maps to a source on the pinned operator frame', () => {
|
||||
const source = a22WebcamToSource(item());
|
||||
assert.equal(source.id, 'it-a22-km68');
|
||||
assert.equal(source.name, 'A22 ADS Sciliar (km 68)');
|
||||
assert.equal(source.city, 'A22 Brennero');
|
||||
assert.equal(source.cityId, 'a22');
|
||||
assert.equal(source.provider, 'Autostrada del Brennero');
|
||||
assert.equal(source.lat, 46.53591);
|
||||
assert.equal(source.lon, 11.49772);
|
||||
assert.equal(source.headingConfidence, 'low');
|
||||
assert.equal(source.feedType, 'image');
|
||||
assert.equal(source.sourceKind, 'a22-opendatahub');
|
||||
assert.equal(source.code, 'ADS SCILIAR');
|
||||
assert.equal(source.url, `${A22_IMAGE_ORIGIN}km68.jpg`);
|
||||
assert.equal(source.snapshotUrl, source.url);
|
||||
});
|
||||
|
||||
test('ground elevation follows the motorway from the Brenner Pass to the Po', () => {
|
||||
const brenner = a22WebcamToSource(
|
||||
item({ Shortname: 'Brennero' }, { km: '1', lat: 46.99682, lon: 11.50218 }),
|
||||
);
|
||||
const ponte = a22WebcamToSource(
|
||||
item(
|
||||
{ Shortname: 'Ponte Po' },
|
||||
{ km: '272', lat: 45.03145, lon: 10.85369 },
|
||||
),
|
||||
);
|
||||
assert.ok(brenner.groundElevationM > 1300);
|
||||
assert.ok(ponte.groundElevationM < 50);
|
||||
// A kilometre the table does not know falls back to the corridor prior.
|
||||
const unknown = a22WebcamToSource(
|
||||
item({}, { km: '150', lat: 45.95, lon: 11.05 }),
|
||||
);
|
||||
assert.equal(unknown.groundElevationM, A22_DEFAULT_GROUND_ELEVATION_M);
|
||||
});
|
||||
|
||||
test('inactive cameras, off-host frames and bad geometry are dropped', () => {
|
||||
assert.equal(a22WebcamToSource(item({ Active: false })), null);
|
||||
assert.equal(a22WebcamToSource(item({ Source: 'other' })), null);
|
||||
assert.equal(
|
||||
a22WebcamToSource(
|
||||
item({ Webcamurl: 'https://evil.test/WebCamImg/km68.jpg' }),
|
||||
),
|
||||
null,
|
||||
);
|
||||
// The frame must be exactly the camera's own kilometre image.
|
||||
assert.equal(
|
||||
a22WebcamToSource(
|
||||
item({ Webcamurl: 'https://www.autobrennero.it/WebCamImg/km1.jpg' }),
|
||||
),
|
||||
null,
|
||||
);
|
||||
assert.equal(
|
||||
a22WebcamToSource(item({ Mapping: { a22: { km: '../x' } } })),
|
||||
null,
|
||||
);
|
||||
// Milan: plausible, but off the Brenner–Modena corridor.
|
||||
assert.equal(
|
||||
a22WebcamToSource(item({}, { km: '68', lat: 45.46, lon: 9.19 })),
|
||||
null,
|
||||
);
|
||||
assert.equal(a22WebcamToSource(item({ GpsInfo: [] })), null);
|
||||
assert.equal(a22WebcamToSource(null), null);
|
||||
});
|
||||
|
||||
test('the loader dedupes, orders north to south, and degrades to empty', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const requested = [];
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return Response.json({
|
||||
TotalResults: 3,
|
||||
Items: [
|
||||
item(
|
||||
{ Shortname: 'Ponte Po' },
|
||||
{ km: '272', lat: 45.03145, lon: 10.85369 },
|
||||
),
|
||||
item(),
|
||||
item(),
|
||||
item(
|
||||
{ Shortname: 'Brennero' },
|
||||
{ km: '1', lat: 46.99682, lon: 11.50218 },
|
||||
),
|
||||
],
|
||||
});
|
||||
});
|
||||
const cameras = await loadA22SourcesFromOpenDataHub();
|
||||
assert.deepEqual(requested, [DEFAULT_A22_CCTV_URL]);
|
||||
assert.deepEqual(
|
||||
cameras.map((c) => c.id),
|
||||
['it-a22-km1', 'it-a22-km68', 'it-a22-km272'],
|
||||
);
|
||||
|
||||
fetchMock.mock.mockImplementation(
|
||||
async () => new Response('nope', { status: 503 }),
|
||||
);
|
||||
assert.deepEqual(await loadA22SourcesFromOpenDataHub(), []);
|
||||
fetchMock.mock.mockImplementation(
|
||||
async () =>
|
||||
new Response(null, {
|
||||
status: 302,
|
||||
headers: { Location: 'https://evil.test/' },
|
||||
}),
|
||||
);
|
||||
assert.deepEqual(await loadA22SourcesFromOpenDataHub(), []);
|
||||
fetchMock.mock.mockImplementation(async () => {
|
||||
throw new Error('offline');
|
||||
});
|
||||
assert.deepEqual(await loadA22SourcesFromOpenDataHub(), []);
|
||||
});
|
||||
|
||||
const runCatalog = async (t) => {
|
||||
const requested = [];
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const href = String(url);
|
||||
requested.push(href);
|
||||
if (href === DEFAULT_A22_CCTV_URL) {
|
||||
return Response.json({ Items: [item()] });
|
||||
}
|
||||
return Response.json([]);
|
||||
});
|
||||
const sources = await createCctvCatalog({ sourceRoot: '/nonexistent' })();
|
||||
return { requested, sources };
|
||||
};
|
||||
|
||||
const withEnv = async (patch, fn) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
delete process.env.CCTV_SOURCES_FILE;
|
||||
delete process.env.CCTV_SOURCES_JSON;
|
||||
delete process.env.CCTV_A22_ENABLED;
|
||||
Object.assign(process.env, patch);
|
||||
await fn();
|
||||
} finally {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in saved)) delete process.env[key];
|
||||
}
|
||||
Object.assign(process.env, saved);
|
||||
}
|
||||
};
|
||||
|
||||
test('the A22 lane is wired into the catalog', async (t) => {
|
||||
await withEnv({}, async () => {
|
||||
const { requested, sources } = await runCatalog(t);
|
||||
assert.ok(requested.includes(DEFAULT_A22_CCTV_URL));
|
||||
assert.deepEqual(
|
||||
sources.filter((s) => s.cityId === 'a22').map((s) => s.id),
|
||||
['it-a22-km68'],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('CCTV_A22_ENABLED=0 keeps the lane from being loaded', async (t) => {
|
||||
await withEnv({ CCTV_A22_ENABLED: '0' }, async () => {
|
||||
const { requested, sources } = await runCatalog(t);
|
||||
assert.equal(requested.includes(DEFAULT_A22_CCTV_URL), false);
|
||||
assert.deepEqual(
|
||||
sources.filter((s) => s.cityId === 'a22'),
|
||||
[],
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
test('a redirect on the A22 frame host stays inside WebCamImg/', async () => {
|
||||
const frame = `${A22_IMAGE_ORIGIN}km68.jpg`;
|
||||
const redirectTo = (location) => async (url) =>
|
||||
url === frame
|
||||
? new Response(null, { status: 302, headers: { location } })
|
||||
: new Response('frame', { headers: { 'content-type': 'image/jpeg' } });
|
||||
for (const location of ['/it/area-riservata/', '/WebCamImg/../x.jpg'])
|
||||
assert.equal(
|
||||
await fetchWithinHost(frame, {}, redirectTo(location)),
|
||||
null,
|
||||
location,
|
||||
);
|
||||
const followed = await fetchWithinHost(
|
||||
frame,
|
||||
{},
|
||||
redirectTo('/WebCamImg/km77.jpg'),
|
||||
);
|
||||
assert.equal(await followed.text(), 'frame');
|
||||
});
|
||||
|
||||
test('A22 ambient cards refresh on the highway cadence, not the default', () => {
|
||||
const source = a22WebcamToSource(item());
|
||||
assert.equal(staticFrameRefreshMs(source), 3 * 60 * 1000);
|
||||
});
|
||||
@@ -12,7 +12,7 @@ import {
|
||||
CALGARY_IMAGE_ORIGIN,
|
||||
CALGARY_MAX_CATALOG_BYTES,
|
||||
DEFAULT_CALGARY_ROWS_URL,
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { CAMERA_CODE_MAX_CHARS } from '../../server/providers/cctv/normalize.js';
|
||||
import { allocateSourceCap } from '../../server/providers/cctv/cap.js';
|
||||
@@ -384,6 +384,6 @@ test('CCTV_CALGARY_ENABLED=0 keeps the lane from being loaded at all', async (t)
|
||||
}
|
||||
});
|
||||
|
||||
test('the shipped catalog ceiling is not raised to make room for this pack', () => {
|
||||
assert.equal(DEFAULT_CCTV_MAX_SOURCES, 4000);
|
||||
test('the shared catalog slots are not raised to make room for this pack', () => {
|
||||
assert.equal(CCTV_SHARED_SOURCE_SLOTS, 4000);
|
||||
});
|
||||
@@ -6,9 +6,12 @@ import {
|
||||
} from '../../server/providers/cctv/cap.js';
|
||||
import {
|
||||
CCTV_MAX_SOURCES_CEILING,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
CCTV_SOURCE_CACHE_MS,
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
WORLD_CCTV_SOURCE_COUNT,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { QUEBEC_CAMERA_SOURCE_COUNT } from '../../server/providers/cctv/quebec.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
|
||||
const pack = (name, count, prefix = name) => ({
|
||||
@@ -99,6 +102,68 @@ test('duplicate ids resolve last-pack-wins and count against the winning pack',
|
||||
]);
|
||||
});
|
||||
|
||||
/** Shared packs plus two reserved ones, shaped like the default catalog. */
|
||||
const reservedFixture = () => [
|
||||
...Array.from({ length: 20 }, (_, i) => pack(`shared${i}`, 250)),
|
||||
{ ...pack('quebec', 1120), reservedCount: 1120 },
|
||||
{ ...pack('world', 2230), reservedCount: 2230 },
|
||||
];
|
||||
const keptByName = (packs) =>
|
||||
Object.fromEntries(packs.map(({ name, kept }) => [name, kept]));
|
||||
|
||||
test('the default cap is the shared floor plus the reserved Québec and World packs', () => {
|
||||
assert.equal(
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS +
|
||||
QUEBEC_CAMERA_SOURCE_COUNT +
|
||||
WORLD_CCTV_SOURCE_COUNT,
|
||||
);
|
||||
});
|
||||
|
||||
test('at the default cap reserved packs are whole and shared packs keep the floor', () => {
|
||||
const { sources, packs } = allocateSourceCap(
|
||||
reservedFixture(),
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
);
|
||||
const kept = keptByName(packs);
|
||||
assert.equal(sources.length, DEFAULT_CCTV_MAX_SOURCES);
|
||||
assert.equal(kept.quebec, 1120);
|
||||
assert.equal(kept.world, 2230);
|
||||
for (let i = 0; i < 20; i++) assert.equal(kept[`shared${i}`], 200);
|
||||
assert.match(
|
||||
sources[0].id,
|
||||
/^shared0-/,
|
||||
'the first camera stays in a shared pack',
|
||||
);
|
||||
});
|
||||
|
||||
test('a cap at the shared floor reserves nothing and thins every pack evenly', () => {
|
||||
const { packs } = allocateSourceCap(reservedFixture(), 4000);
|
||||
const kept = keptByName(packs);
|
||||
// 22 lanes share 4,000 round-robin: nobody is wiped out by the reservation.
|
||||
for (const count of Object.values(kept))
|
||||
assert.ok(count >= 181 && count <= 182);
|
||||
});
|
||||
|
||||
test('a small cap (dev-secure 48) still reaches the shared packs first', () => {
|
||||
const { sources, packs } = allocateSourceCap(reservedFixture(), 48);
|
||||
const kept = keptByName(packs);
|
||||
assert.equal(sources.length, 48);
|
||||
for (let i = 0; i < 20; i++) assert.ok(kept[`shared${i}`] >= 2);
|
||||
assert.match(sources[0].id, /^shared0-/);
|
||||
});
|
||||
|
||||
test('reservations fill only the room above the floor, round-robin between reserved packs', () => {
|
||||
const { packs } = allocateSourceCap(reservedFixture(), 4100);
|
||||
const kept = keptByName(packs);
|
||||
const shared = Object.entries(kept)
|
||||
.filter(([name]) => name.startsWith('shared'))
|
||||
.reduce((sum, [, count]) => sum + count, 0);
|
||||
// 100 reserved slots split between Québec and World, then 4,000 round-robin.
|
||||
assert.ok(shared >= 4000 - 2 * 182, `shared packs kept ${shared}`);
|
||||
assert.equal(shared + kept.quebec + kept.world, 4100);
|
||||
});
|
||||
|
||||
test('resolveCatalogCap bounds the env value and falls back to the default', () => {
|
||||
assert.equal(resolveCatalogCap(undefined), DEFAULT_CCTV_MAX_SOURCES);
|
||||
assert.equal(resolveCatalogCap('nonsense'), DEFAULT_CCTV_MAX_SOURCES);
|
||||
|
||||
@@ -14,6 +14,8 @@ import {
|
||||
DEFAULT_ONTARIO_MAX_SOURCES,
|
||||
DEFAULT_FINTRAFFIC_MAX_SOURCES,
|
||||
DEFAULT_TXDOT_MAX_SOURCES,
|
||||
DEFAULT_OTTAWA_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
DEFAULT_TALLINN_MAX_SOURCES,
|
||||
DEFAULT_TARKTEE_MAX_SOURCES,
|
||||
DEFAULT_NSW_MAX_SOURCES,
|
||||
@@ -222,7 +224,7 @@ test('CCTV catalog merges DriveBC cameras and CCTV_DRIVEBC_ENABLED=0 skips the r
|
||||
);
|
||||
});
|
||||
|
||||
test('default caps of the original packs fit inside the default catalog cap', () => {
|
||||
test('default caps of the original packs fit inside the shared catalog slots', () => {
|
||||
// Every default pack at its own cap (Warendorf ships 1 curated camera).
|
||||
const packs =
|
||||
DEFAULT_AUSTIN_MAX_SOURCES +
|
||||
@@ -231,15 +233,18 @@ test('default caps of the original packs fit inside the default catalog cap', ()
|
||||
DEFAULT_ONTARIO_MAX_SOURCES +
|
||||
DEFAULT_FINTRAFFIC_MAX_SOURCES +
|
||||
DEFAULT_DRIVEBC_MAX_SOURCES +
|
||||
DEFAULT_OTTAWA_MAX_SOURCES +
|
||||
DEFAULT_TXDOT_MAX_SOURCES +
|
||||
DEFAULT_TALLINN_MAX_SOURCES +
|
||||
DEFAULT_TARKTEE_MAX_SOURCES +
|
||||
DEFAULT_NSW_MAX_SOURCES +
|
||||
DEFAULT_CATALONIA_MAX_SOURCES +
|
||||
1;
|
||||
// The reserved Québec and World packs sit above the shared floor, so the
|
||||
// shared packs must fit the floor itself, not the whole default cap.
|
||||
assert.ok(
|
||||
packs <= DEFAULT_CCTV_MAX_SOURCES,
|
||||
`default packs (${packs}) would be thinned by the catalog cap (${DEFAULT_CCTV_MAX_SOURCES})`,
|
||||
packs <= CCTV_SHARED_SOURCE_SLOTS,
|
||||
`default packs (${packs}) would be thinned by the shared slots (${CCTV_SHARED_SOURCE_SLOTS})`,
|
||||
);
|
||||
assert.ok(
|
||||
DEFAULT_CCTV_MAX_SOURCES <= CCTV_MAX_SOURCES_CEILING,
|
||||
|
||||
@@ -17,7 +17,7 @@
|
||||
*/
|
||||
|
||||
const EARTH_RADIUS_M = 6371000;
|
||||
export const PLANE_VERT_ASPECT = 16 / 9;
|
||||
const PLANE_VERT_ASPECT = 16 / 9;
|
||||
export const SUPPORT_KEYS = Object.freeze([
|
||||
'bl',
|
||||
'bm',
|
||||
@@ -128,7 +128,7 @@ export function planeSupportPoints(pose) {
|
||||
* @param {number} capAltM @param {-1|0|1} row @param {{upVert:number}} dims
|
||||
* @returns {number}
|
||||
*/
|
||||
export function supportAltitude(capAltM, row, dims) {
|
||||
function supportAltitude(capAltM, row, dims) {
|
||||
return capAltM + row * dims.upVert;
|
||||
}
|
||||
|
||||
|
||||
+242
-225
@@ -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
|
||||
@@ -316,7 +341,7 @@ export function createCalibrationGizmo({
|
||||
}
|
||||
const mount = positions.mount;
|
||||
const axes = enuAxes(mount);
|
||||
const { forwardHoriz, right, view } = viewAxesFor(
|
||||
const { forwardHoriz } = viewAxesFor(
|
||||
camera.headingDeg,
|
||||
camera.pitchDeg,
|
||||
axes,
|
||||
@@ -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
@@ -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),
|
||||
);
|
||||
});
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
parseHkCameraLocationsXml,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
DEFAULT_HK_CAMERAS_URL,
|
||||
DEFAULT_HK_MAX_SOURCES,
|
||||
HK_ANCHORS,
|
||||
@@ -396,8 +396,8 @@ test('CCTV_HK_ENABLED=0 keeps the lane from being loaded at all', async (t) => {
|
||||
}
|
||||
});
|
||||
|
||||
test('the shipped catalog ceiling is not raised to make room for this pack', () => {
|
||||
assert.equal(DEFAULT_CCTV_MAX_SOURCES, 4000);
|
||||
test('the shared catalog slots are not raised to make room for this pack', () => {
|
||||
assert.equal(CCTV_SHARED_SOURCE_SLOTS, 4000);
|
||||
});
|
||||
|
||||
test('the HK pack default sits above the full TD catalog and anchors the New Territories', () => {
|
||||
@@ -406,7 +406,7 @@ test('the HK pack default sits above the full TD catalog and anchors the New Ter
|
||||
'default cap should keep nearly all published TD cameras',
|
||||
);
|
||||
assert.ok(
|
||||
DEFAULT_HK_MAX_SOURCES <= DEFAULT_CCTV_MAX_SOURCES,
|
||||
DEFAULT_HK_MAX_SOURCES <= CCTV_SHARED_SOURCE_SLOTS,
|
||||
'a single pack must not outgrow the catalog-wide ceiling alone',
|
||||
);
|
||||
const places = HK_ANCHORS.map(
|
||||
|
||||
@@ -10,6 +10,77 @@ const playlist =
|
||||
'#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:12\n#EXTINF:2,\na.ts\n#EXTINF:2,\nb.ts\n#EXTINF:2,\nc.ts\n';
|
||||
const base = 'https://camera.example/live/list.m3u8';
|
||||
|
||||
test('high-resolution HLS segments play while the retained session cache stays bounded', async (t) => {
|
||||
// Giroc publishes roughly ten-second TS segments; one measured 6,437,120
|
||||
// bytes. The former 4 MiB download cap rejected it before playback began.
|
||||
const segmentBytes = 6_437_120;
|
||||
const master =
|
||||
'#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=4570000\ntracks-v1a1/mono.m3u8\n';
|
||||
const media =
|
||||
'#EXTM3U\n#EXT-X-MEDIA-SEQUENCE:100\n' +
|
||||
[0, 1, 2, 3, 4].map((i) => `#EXTINF:10.272,\n${i}.ts\n`).join('');
|
||||
const manager = createHlsPuller({
|
||||
limits: { ...HLS_LIMITS, pollMs: 100000 },
|
||||
fetchImpl: async (url) => {
|
||||
if (url === base) return new Response(master);
|
||||
if (url === 'https://camera.example/live/tracks-v1a1/mono.m3u8')
|
||||
return new Response(media);
|
||||
const match =
|
||||
/^https:\/\/camera\.example\/live\/tracks-v1a1\/([0-4])\.ts$/.exec(url);
|
||||
if (!match) throw new Error('Unexpected playlist reference');
|
||||
// No Content-Length: the actual streamed bytes must also be accepted.
|
||||
return new Response(Buffer.alloc(segmentBytes, Number(match[1])));
|
||||
},
|
||||
});
|
||||
t.after(() => manager.shutdown());
|
||||
const entry = await manager.ensure('giroc', base);
|
||||
await entry.polling;
|
||||
const result = await manager.buildPlaylist(entry, 'giroc');
|
||||
assert.ok(result, 'large valid segments should produce a playable playlist');
|
||||
assert.match(result, /#EXT-X-MEDIA-SEQUENCE:2\n/);
|
||||
assert.equal(manager.getSegment('giroc', entry.token, 0), null);
|
||||
const newest = manager.getSegment('giroc', entry.token, 4);
|
||||
assert.equal(newest.length, segmentBytes);
|
||||
assert.equal(newest[0], 4);
|
||||
assert.deepEqual(manager.stats(), { sessions: 1, bytes: 19_311_360 });
|
||||
});
|
||||
|
||||
test('HLS downloads still reject declared and chunked bodies above 8 MiB', async () => {
|
||||
for (const declared of [true, false]) {
|
||||
let chunks = 0;
|
||||
let cancelled = false;
|
||||
await assert.rejects(
|
||||
fetchHlsBytes(base, {
|
||||
maxBytes: HLS_LIMITS.segmentBytes,
|
||||
fetchImpl: async () =>
|
||||
new Response(
|
||||
declared
|
||||
? 'small body'
|
||||
: new ReadableStream({
|
||||
pull(controller) {
|
||||
// Each chunk fits on its own; only their cumulative size
|
||||
// crosses the cap. Leave it open to verify cancellation.
|
||||
controller.enqueue(
|
||||
Buffer.alloc(4 * 1024 * 1024 + (++chunks === 2 ? 1 : 0)),
|
||||
);
|
||||
},
|
||||
cancel() {
|
||||
cancelled = true;
|
||||
},
|
||||
}),
|
||||
{
|
||||
headers: declared
|
||||
? { 'content-length': String(8 * 1024 * 1024 + 1) }
|
||||
: {},
|
||||
},
|
||||
),
|
||||
}),
|
||||
/HLS response too large/,
|
||||
);
|
||||
if (!declared) assert.equal(cancelled, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('playlist parser uses sequence, refuses escaping and unsupported references', () => {
|
||||
assert.deepEqual(
|
||||
parseHlsMedia(playlist, base).map((s) => s.seq),
|
||||
|
||||
@@ -0,0 +1,403 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import {
|
||||
houstonCameraName,
|
||||
houstonCameraToSource,
|
||||
loadHoustonSourcesFromOpenData,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
DEFAULT_HOUSTON_MAX_SOURCES,
|
||||
HOUSTON_CAMERAS_URL,
|
||||
HOUSTON_GROUND_ELEVATION_M,
|
||||
HOUSTON_IMAGE_ORIGIN,
|
||||
HOUSTON_IMAGE_URL,
|
||||
HOUSTON_MAX_CATALOG_BYTES,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import {
|
||||
CAMERA_CODE_MAX_CHARS,
|
||||
isLikelyHoustonCoordinate,
|
||||
} from '../../server/providers/cctv/normalize.js';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
|
||||
/**
|
||||
* A response whose body is a live stream, plus a flag that flips when the
|
||||
* stream is cancelled. A rejection path that returns without cancelling holds
|
||||
* the transport open, so the flag is what the refusal tests actually assert.
|
||||
*/
|
||||
const streamingResponse = (init = {}) => {
|
||||
const state = { cancelled: false };
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('{'));
|
||||
},
|
||||
cancel() {
|
||||
state.cancelled = true;
|
||||
},
|
||||
});
|
||||
return { response: new Response(body, init), state };
|
||||
};
|
||||
|
||||
const DOWNTOWN_ID = '1002';
|
||||
const GALLERIA_ID = '2001';
|
||||
|
||||
/** One TranStar camera row, shaped like the live `cctvSnapshots_json.js` payload. */
|
||||
const row = (overrides = {}) => ({
|
||||
location: '10 EAST @ SAN JACINTO',
|
||||
id: DOWNTOWN_ID,
|
||||
lat: '29.76824',
|
||||
lng: '-95.355711',
|
||||
dir: 'South',
|
||||
fc: '6',
|
||||
fp: '300',
|
||||
url: "showWin('/layers/gc.aspx?cam=1002&loc=IH-10_East_at_SAN_JACINTO')",
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test('a Houston row maps to a source on the pinned HTTPS frame host', () => {
|
||||
const source = houstonCameraToSource(row());
|
||||
assert.equal(source.id, `houston-${DOWNTOWN_ID}`);
|
||||
assert.equal(source.name, '10 EAST @ SAN JACINTO');
|
||||
assert.equal(source.city, 'Houston');
|
||||
assert.equal(source.cityId, 'houston');
|
||||
assert.equal(source.provider, 'Houston TranStar');
|
||||
assert.equal(source.lat, 29.76824);
|
||||
assert.equal(source.lon, -95.355711);
|
||||
assert.equal(source.feedType, 'image');
|
||||
assert.equal(source.sourceKind, 'houston-transtar');
|
||||
assert.equal(
|
||||
source.license,
|
||||
'TranStar disclaimer — redistribution and external framing need TxDOT written permission',
|
||||
);
|
||||
assert.equal(source.groundElevationM, HOUSTON_GROUND_ELEVATION_M);
|
||||
assert.equal(source.url, HOUSTON_IMAGE_URL(DOWNTOWN_ID));
|
||||
assert.equal(source.url, source.snapshotUrl);
|
||||
assert.ok(source.url.startsWith(HOUSTON_IMAGE_ORIGIN));
|
||||
// dir South = the camera sits south of I-10; the nearest lanes run east.
|
||||
assert.equal(source.headingConfidence, 'low');
|
||||
assert.equal(source.headingDeg, 90);
|
||||
});
|
||||
|
||||
test('frame URLs are synthesized from the numeric id; the payload URL is ignored', () => {
|
||||
const source = houstonCameraToSource(
|
||||
row({ url: 'https://evil.example/cameras/x/image' }),
|
||||
);
|
||||
assert.equal(source.url, HOUSTON_IMAGE_URL(DOWNTOWN_ID));
|
||||
assert.equal(source.snapshotUrl, source.url);
|
||||
});
|
||||
|
||||
test('zero ids, off-city geometry and unusable ids are dropped', () => {
|
||||
assert.equal(houstonCameraToSource(row({ id: '0' })), null);
|
||||
assert.equal(houstonCameraToSource(row({ id: '00' })), null);
|
||||
assert.equal(houstonCameraToSource(row({ id: '../etc/passwd' })), null);
|
||||
assert.equal(houstonCameraToSource(row({ id: '12' })), null);
|
||||
assert.equal(houstonCameraToSource(row({ id: '1002/../x' })), null);
|
||||
// Dallas: a plausible lat/lon, but not a Houston camera.
|
||||
assert.equal(
|
||||
houstonCameraToSource(row({ lat: '32.7767', lng: '-96.797' })),
|
||||
null,
|
||||
);
|
||||
assert.equal(houstonCameraToSource(row({ lat: '0', lng: '0' })), null);
|
||||
assert.equal(houstonCameraToSource(null), null);
|
||||
// 3-digit and 5-digit snapshot ids stay.
|
||||
assert.equal(houstonCameraToSource(row({ id: '102' })).id, 'houston-102');
|
||||
assert.equal(houstonCameraToSource(row({ id: '13711' })).id, 'houston-13711');
|
||||
});
|
||||
|
||||
test('dir is the side of the road: it gives a low-confidence travel heading', () => {
|
||||
// TranStar's map reads dir as "Traffic closest to the camera is traveling":
|
||||
// South -> Eastbound, North -> Westbound, West -> Southbound, East -> Northbound.
|
||||
const expected = { South: 90, North: 270, West: 180, East: 0, south: 90 };
|
||||
for (const [dir, heading] of Object.entries(expected)) {
|
||||
const source = houstonCameraToSource(row({ dir }));
|
||||
assert.equal(source.headingDeg, heading, `dir ${dir}`);
|
||||
assert.equal(source.headingConfidence, 'low', `dir ${dir}`);
|
||||
assert.equal(source.pitchDeg, -18, `dir ${dir}`);
|
||||
assert.equal(source.fovDeg, 44, `dir ${dir}`);
|
||||
assert.equal(source.rangeM, 145, `dir ${dir}`);
|
||||
assert.equal(source.mountHeightM, 8, `dir ${dir}`);
|
||||
}
|
||||
|
||||
const none = houstonCameraToSource(row({ dir: 'None' }));
|
||||
assert.equal(none.headingConfidence, 'low');
|
||||
assert.ok(Number.isFinite(none.headingDeg));
|
||||
assert.equal(
|
||||
none.headingDeg,
|
||||
houstonCameraToSource(row({ dir: '' })).headingDeg,
|
||||
);
|
||||
for (const dir of ['Northeast', 'constructor', '__proto__', undefined]) {
|
||||
assert.equal(
|
||||
houstonCameraToSource(row({ dir })).headingDeg,
|
||||
none.headingDeg,
|
||||
`dir ${dir} falls back to the id hash`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a nameless row still gets a label', () => {
|
||||
assert.equal(
|
||||
houstonCameraName({ location: ' 45 GULF @ WEST DALLAS ' }, 'houston-102'),
|
||||
'45 GULF @ WEST DALLAS',
|
||||
);
|
||||
assert.equal(houstonCameraName({}, 'houston-102'), 'Houston Camera 102');
|
||||
assert.equal(houstonCameraName({}, ''), 'Houston Camera');
|
||||
});
|
||||
|
||||
test('the unselected label is the interchange, trimmed to the code width', () => {
|
||||
assert.equal(houstonCameraToSource(row()).code, '10 EAST @ SAN JACINTO');
|
||||
const long = houstonCameraToSource(
|
||||
row({
|
||||
location:
|
||||
'IH-10 Katy Managed Lanes Eastbound at a very long interchange name that must truncate',
|
||||
}),
|
||||
);
|
||||
assert.equal(long.code.length, CAMERA_CODE_MAX_CHARS);
|
||||
assert.ok(long.code.endsWith('…'));
|
||||
});
|
||||
|
||||
test('the loader reads the keyless catalog and collapses duplicate ids', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
requested.push([String(url), init.headers.Accept, init.redirect]);
|
||||
return Response.json({
|
||||
cameras: [
|
||||
row(),
|
||||
row({ location: '10 EAST @ SAN JACINTO (duplicate)' }),
|
||||
row({
|
||||
id: GALLERIA_ID,
|
||||
location: '610 WEST LOOP @ SAN FELIPE',
|
||||
lat: '29.749',
|
||||
lng: '-95.461',
|
||||
dir: 'North',
|
||||
}),
|
||||
row({ url: 'https://evil.example/x.jpg', id: '0' }),
|
||||
],
|
||||
});
|
||||
});
|
||||
const cameras = await loadHoustonSourcesFromOpenData();
|
||||
assert.deepEqual(requested, [[HOUSTON_CAMERAS_URL, '*/*', 'manual']]);
|
||||
assert.deepEqual(
|
||||
cameras.map((camera) => camera.id),
|
||||
[`houston-${GALLERIA_ID}`, `houston-${DOWNTOWN_ID}`],
|
||||
'nearest-to-anchor first: Uptown sits closer to its pin than downtown does',
|
||||
);
|
||||
assert.equal(cameras[1].name, '10 EAST @ SAN JACINTO');
|
||||
});
|
||||
|
||||
test('an upstream failure yields an empty pack and releases the response', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const failed = streamingResponse({ status: 503 });
|
||||
t.mock.method(globalThis, 'fetch', async () => failed.response);
|
||||
assert.deepEqual(await loadHoustonSourcesFromOpenData(), []);
|
||||
assert.equal(failed.state.cancelled, true, 'the failed body is cancelled');
|
||||
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new Error('network down');
|
||||
});
|
||||
assert.deepEqual(await loadHoustonSourcesFromOpenData(), []);
|
||||
});
|
||||
|
||||
test('the catalog fetch refuses redirects and oversized bodies', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const seen = [];
|
||||
const redirected = streamingResponse({
|
||||
status: 302,
|
||||
headers: { location: 'https://evil.example/cameras.js' },
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
seen.push([String(url), init.redirect]);
|
||||
return redirected.response;
|
||||
});
|
||||
assert.deepEqual(await loadHoustonSourcesFromOpenData(), []);
|
||||
assert.deepEqual(seen, [[HOUSTON_CAMERAS_URL, 'manual']]);
|
||||
assert.equal(
|
||||
redirected.state.cancelled,
|
||||
true,
|
||||
'the redirect body is cancelled',
|
||||
);
|
||||
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
const body = JSON.stringify({ cameras: [row()] });
|
||||
return new Response(body, {
|
||||
headers: {
|
||||
'Content-Type': 'application/javascript',
|
||||
'content-length': String(HOUSTON_MAX_CATALOG_BYTES + 1),
|
||||
},
|
||||
});
|
||||
});
|
||||
assert.deepEqual(await loadHoustonSourcesFromOpenData(), []);
|
||||
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
// Valid JSON with a usable camera, so only the byte cap can refuse it.
|
||||
const oversized = JSON.stringify({
|
||||
cameras: [row()],
|
||||
padding: 'x'.repeat(HOUSTON_MAX_CATALOG_BYTES + 1024),
|
||||
});
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(oversized));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
{ headers: { 'Content-Type': 'application/javascript' } },
|
||||
);
|
||||
});
|
||||
assert.deepEqual(await loadHoustonSourcesFromOpenData(), []);
|
||||
});
|
||||
|
||||
test('a reduced pack cap keeps cameras nearest the metro anchors', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
const saved = process.env.CCTV_HOUSTON_MAX_SOURCES;
|
||||
t.after(() => {
|
||||
if (saved === undefined) delete process.env.CCTV_HOUSTON_MAX_SOURCES;
|
||||
else process.env.CCTV_HOUSTON_MAX_SOURCES = saved;
|
||||
});
|
||||
process.env.CCTV_HOUSTON_MAX_SOURCES = '8';
|
||||
const rows = [
|
||||
...[29.32, 29.322, 29.324, 29.326, 29.328, 29.33].map((lat, i) =>
|
||||
row({
|
||||
id: String(3000 + i),
|
||||
lat: String(lat),
|
||||
lng: '-94.80',
|
||||
location: `Galveston ${i}`,
|
||||
dir: 'East',
|
||||
}),
|
||||
),
|
||||
...[29.76, 29.759, 29.758, 29.757, 29.756, 29.755].map((lat, i) =>
|
||||
row({
|
||||
id: String(4000 + i),
|
||||
lat: String(lat),
|
||||
lng: '-95.3698',
|
||||
location: `Downtown ${i}`,
|
||||
dir: 'North',
|
||||
}),
|
||||
),
|
||||
];
|
||||
t.mock.method(globalThis, 'fetch', async () =>
|
||||
Response.json({ cameras: rows }),
|
||||
);
|
||||
const cameras = await loadHoustonSourcesFromOpenData();
|
||||
assert.equal(cameras.length, 8);
|
||||
assert.deepEqual(
|
||||
cameras.map((camera) => camera.name.slice(0, 8)),
|
||||
[
|
||||
'Downtown',
|
||||
'Downtown',
|
||||
'Downtown',
|
||||
'Downtown',
|
||||
'Downtown',
|
||||
'Downtown',
|
||||
'Galvesto',
|
||||
'Galvesto',
|
||||
],
|
||||
'downtown fills first; the Galveston anchor still keeps a share',
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* Serve the Houston catalog to the Houston endpoint and an empty payload to
|
||||
* every other pack, so one catalog refresh exercises the registration without
|
||||
* reaching the network.
|
||||
*/
|
||||
const runCatalogWithMockedUpstreams = async (t) => {
|
||||
const requested = [];
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
const href = String(url);
|
||||
requested.push(href);
|
||||
if (href === HOUSTON_CAMERAS_URL) {
|
||||
return Response.json({
|
||||
cameras: [
|
||||
row(),
|
||||
row({
|
||||
id: GALLERIA_ID,
|
||||
location: '610 WEST LOOP @ SAN FELIPE',
|
||||
lat: '29.749',
|
||||
lng: '-95.461',
|
||||
dir: 'West',
|
||||
}),
|
||||
],
|
||||
});
|
||||
}
|
||||
return Response.json([]);
|
||||
});
|
||||
const sources = await createCctvCatalog({ sourceRoot: '/nonexistent' })();
|
||||
return { requested, sources };
|
||||
};
|
||||
|
||||
test('the Houston lane is wired into the catalog and its loader runs', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
delete process.env.CCTV_SOURCES_FILE;
|
||||
delete process.env.CCTV_SOURCES_JSON;
|
||||
process.env.CCTV_HOUSTON_ENABLED = '1';
|
||||
const { requested, sources } = await runCatalogWithMockedUpstreams(t);
|
||||
assert.ok(
|
||||
requested.includes(HOUSTON_CAMERAS_URL),
|
||||
'the catalog refresh invokes the Houston loader',
|
||||
);
|
||||
assert.deepEqual(
|
||||
sources.filter((s) => s.cityId === 'houston').map((s) => s.id),
|
||||
[`houston-${GALLERIA_ID}`, `houston-${DOWNTOWN_ID}`],
|
||||
'Houston cameras reach the served catalog through the registered lane',
|
||||
);
|
||||
} finally {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in saved)) delete process.env[key];
|
||||
}
|
||||
Object.assign(process.env, saved);
|
||||
}
|
||||
});
|
||||
|
||||
test('Houston stays unloaded unless CCTV_HOUSTON_ENABLED=1', async (t) => {
|
||||
const saved = { ...process.env };
|
||||
try {
|
||||
delete process.env.CCTV_SOURCES_FILE;
|
||||
delete process.env.CCTV_SOURCES_JSON;
|
||||
for (const value of [undefined, '0']) {
|
||||
if (value === undefined) delete process.env.CCTV_HOUSTON_ENABLED;
|
||||
else process.env.CCTV_HOUSTON_ENABLED = value;
|
||||
const { requested, sources } = await runCatalogWithMockedUpstreams(t);
|
||||
assert.equal(
|
||||
requested.includes(HOUSTON_CAMERAS_URL),
|
||||
false,
|
||||
'the pack reaches TranStar only after an explicit opt-in',
|
||||
);
|
||||
assert.deepEqual(
|
||||
sources.filter((s) => s.cityId === 'houston'),
|
||||
[],
|
||||
);
|
||||
}
|
||||
} finally {
|
||||
for (const key of Object.keys(process.env)) {
|
||||
if (!(key in saved)) delete process.env[key];
|
||||
}
|
||||
Object.assign(process.env, saved);
|
||||
}
|
||||
});
|
||||
|
||||
test('the shared catalog slots are not raised to make room for this pack', () => {
|
||||
assert.equal(CCTV_SHARED_SOURCE_SLOTS, 4000);
|
||||
assert.equal(DEFAULT_HOUSTON_MAX_SOURCES, 250);
|
||||
});
|
||||
|
||||
test('isLikelyHoustonCoordinate spans the metro and rejects the rest', () => {
|
||||
assert.equal(isLikelyHoustonCoordinate(29.7604, -95.3698), true); // Downtown
|
||||
assert.equal(isLikelyHoustonCoordinate(29.3013, -94.7977), true); // Galveston
|
||||
assert.equal(isLikelyHoustonCoordinate(29.9902, -95.3368), true); // IAH
|
||||
assert.equal(isLikelyHoustonCoordinate(32.7767, -96.797), false); // Dallas
|
||||
assert.equal(isLikelyHoustonCoordinate(30.2672, -97.7431), false); // Austin
|
||||
assert.equal(isLikelyHoustonCoordinate(0, 0), false);
|
||||
assert.equal(isLikelyHoustonCoordinate(NaN, -95.37), false);
|
||||
});
|
||||
@@ -0,0 +1,429 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
import {
|
||||
DEFAULT_ICELAND_MAX_SOURCES,
|
||||
ICELAND_CAMERAS_URL,
|
||||
ICELAND_IMAGE_ORIGIN,
|
||||
ICELAND_MAX_CATALOG_BYTES,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { fetchWithinHost } from '../../server/providers/cctv/media.js';
|
||||
import { isLikelyIcelandCoordinate } from '../../server/providers/cctv/normalize.js';
|
||||
import {
|
||||
icelandCameraToSource,
|
||||
icelandHeadingFromDescription,
|
||||
loadIcelandSourcesFromOpenData,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
|
||||
/** Set (or, for `undefined`, delete) environment variables for one test. */
|
||||
function withEnv(t, env) {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
const previous = process.env[name];
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env[name];
|
||||
else process.env[name] = previous;
|
||||
});
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/** One row shaped like the live `vefmyndavelar2014_1` payload. */
|
||||
const row = (over = {}) => ({
|
||||
Maelist_nr: 7001,
|
||||
Myndavel: 'Hellisheiði',
|
||||
Vegheiti: 'Hringvegur',
|
||||
NrVegur: '1',
|
||||
Skyring: 'Hellisheiði séð til vesturs',
|
||||
Slod: `${ICELAND_IMAGE_ORIGIN}hellisheidi_1.jpg`,
|
||||
PntX: 395000,
|
||||
PntY: 390000,
|
||||
Breidd: 64.0136,
|
||||
Lengd: -21.4,
|
||||
...over,
|
||||
});
|
||||
|
||||
/** A live response body plus a flag that flips when the stream is cancelled. */
|
||||
const streamingResponse = (init = {}) => {
|
||||
const state = { cancelled: false };
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode('['));
|
||||
},
|
||||
cancel() {
|
||||
state.cancelled = true;
|
||||
},
|
||||
});
|
||||
return { response: new Response(body, init), state };
|
||||
};
|
||||
|
||||
const json = (value) =>
|
||||
new Response(JSON.stringify(value), {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
});
|
||||
|
||||
test('an Iceland row maps to a source on the pinned frame directory', () => {
|
||||
const source = icelandCameraToSource(row());
|
||||
assert.equal(source.id, 'is-vegagerdin-hellisheidi_1');
|
||||
assert.equal(source.name, 'Hellisheiði séð til vesturs');
|
||||
assert.equal(source.city, 'Iceland');
|
||||
assert.equal(source.cityId, 'iceland');
|
||||
assert.equal(source.provider, 'Vegagerðin (IRCA)');
|
||||
assert.equal(source.lat, 64.0136);
|
||||
assert.equal(source.lon, -21.4);
|
||||
assert.equal(source.headingDeg, 270);
|
||||
assert.equal(source.headingConfidence, 'high');
|
||||
assert.equal(source.pitchDeg, -24);
|
||||
assert.equal(source.fovDeg, 56);
|
||||
assert.equal(source.rangeM, 210);
|
||||
assert.equal(source.mountHeightM, 10);
|
||||
assert.equal(source.feedType, 'image');
|
||||
assert.equal(source.sourceKind, 'iceland-vegagerdin');
|
||||
assert.equal(source.code, 'HELLISHEIÐI');
|
||||
assert.match(source.license, /CC BY 4\.0/);
|
||||
assert.ok(source.url.startsWith(ICELAND_IMAGE_ORIGIN));
|
||||
assert.equal(source.snapshotUrl, source.url);
|
||||
});
|
||||
|
||||
test('a view that states no facing takes the low-confidence id-hash pose', () => {
|
||||
const source = icelandCameraToSource(
|
||||
row({
|
||||
Skyring: 'Hellisheiði séð niður á veg',
|
||||
Slod: `${ICELAND_IMAGE_ORIGIN}hellisheidi_2.jpg`,
|
||||
}),
|
||||
);
|
||||
assert.equal(source.headingConfidence, 'low');
|
||||
assert.equal(source.headingDeg % 22.5, 0);
|
||||
assert.equal(
|
||||
source.headingDeg,
|
||||
icelandCameraToSource(
|
||||
row({ Slod: `${ICELAND_IMAGE_ORIGIN}hellisheidi_2.jpg` }),
|
||||
).headingDeg,
|
||||
'the fallback depends on the id, not on the text',
|
||||
);
|
||||
});
|
||||
|
||||
test('the label collapses the feed’s doubled spaces and repeated words', () => {
|
||||
assert.equal(
|
||||
icelandCameraToSource(
|
||||
row({ Skyring: 'Strandarheiði séð niður á veg til til austurs' }),
|
||||
).name,
|
||||
'Strandarheiði séð niður á veg til austurs',
|
||||
);
|
||||
const label = (Skyring) => icelandCameraToSource(row({ Skyring })).name;
|
||||
// Repeats of words with Icelandic letters collapse too.
|
||||
assert.equal(
|
||||
label('Hellisheiði séð séð til austurs'),
|
||||
'Hellisheiði séð til austurs',
|
||||
);
|
||||
assert.equal(label('Brú á á Jökulsá'), 'Brú á Jökulsá');
|
||||
// A word ending in a letter the next word starts with is not a repeat.
|
||||
for (const text of [
|
||||
'Þverá Árnessýslu',
|
||||
'brú Úlfarsá',
|
||||
'Vesturlandsvegur við Elliðaá Ártúnsbrekku',
|
||||
])
|
||||
assert.equal(label(text), text);
|
||||
});
|
||||
|
||||
test('a row with no label, station or station number is named by its frame', () => {
|
||||
const source = icelandCameraToSource(
|
||||
row({ Skyring: '', Myndavel: '', Maelist_nr: undefined }),
|
||||
);
|
||||
assert.equal(source.name, 'Vegagerðin hellisheidi_1');
|
||||
});
|
||||
|
||||
test('only an explicit facing sets a heading', () => {
|
||||
const cases = [
|
||||
['Hellisheiði séð til vesturs', 270],
|
||||
['Holtavörðuheiði til norðurs', 0],
|
||||
['Klettsháls í suður', 180],
|
||||
['Arnarneshæð séð austur', 90],
|
||||
['Bústaðabrú séð norður Kringlumýrarbraut', 0],
|
||||
['Staður séð til norðausturs', 45],
|
||||
['Staður séð til suðausturs', 135],
|
||||
['Staður séð í suðvestur', 225],
|
||||
['Staður séð til norðvesturs', 315],
|
||||
['STAÐUR SÉÐ TIL VESTURS', 270],
|
||||
['Brú séð til austurs og Selfoss', 90], // "og" then a place, not a facing
|
||||
['Staður séð til austurs og Vesturlandsvegur', 90],
|
||||
];
|
||||
for (const [text, heading] of cases) {
|
||||
assert.equal(icelandHeadingFromDescription(text), heading, text);
|
||||
}
|
||||
for (const text of [
|
||||
'',
|
||||
null,
|
||||
'Gautsdalur niður á veg',
|
||||
'Miklabraut austur', // a road direction, not a facing
|
||||
'Biskupsháls - norður',
|
||||
'Hringtorg norðan Selfoss',
|
||||
'Norðurárdalur niður á veg', // a place name that contains a cardinal
|
||||
'Staður séð til suðurlands', // a longer word, not "suður"
|
||||
'Staður séð til norðurs og til suðurs', // two facings: ambiguous
|
||||
'Staður séð til austurs og vesturs', // the second facing shares "til"
|
||||
'Staður séð í norður og suður',
|
||||
'Staður séð í norður og í suður',
|
||||
'Norðfjarðargöng séð til Eskifjarðar',
|
||||
]) {
|
||||
assert.ok(Number.isNaN(icelandHeadingFromDescription(text)), String(text));
|
||||
}
|
||||
});
|
||||
|
||||
test('rows off the pinned directory, or with unusable frames or places, are dropped', () => {
|
||||
const bad = [
|
||||
{ Slod: 'https://example.com/vgdata/vefmyndavelar/a_1.jpg' },
|
||||
{ Slod: 'http://www.vegagerdin.is/vgdata/vefmyndavelar/a_1.jpg' },
|
||||
{ Slod: 'https://user:[email protected]/vgdata/vefmyndavelar/a_1.jpg' },
|
||||
{ Slod: 'https://www.vegagerdin.is:8443/vgdata/vefmyndavelar/a_1.jpg' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/other/a_1.jpg' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/../x/a_1.jpg' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/a%2Fb_1.jpg' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/a_1.php' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/a_1' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/' },
|
||||
{ Slod: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/a b_1.jpg' },
|
||||
{ Slod: '' },
|
||||
{ Slod: null },
|
||||
{ Breidd: 0, Lengd: 0 },
|
||||
{ Breidd: null, Lengd: null },
|
||||
{ Breidd: '64.01', Lengd: '-21.4' },
|
||||
{ Breidd: '64.01' }, // each coordinate must be a number on its own
|
||||
{ Lengd: '-21.4' },
|
||||
{ Breidd: 59.9, Lengd: 10.7 }, // Oslo
|
||||
{ Breidd: 64.01, Lengd: 21.4 }, // wrong hemisphere
|
||||
];
|
||||
for (const over of bad) {
|
||||
assert.equal(icelandCameraToSource(row(over)), null, JSON.stringify(over));
|
||||
}
|
||||
assert.equal(icelandCameraToSource(null), null);
|
||||
assert.equal(icelandCameraToSource({}), null);
|
||||
assert.equal(isLikelyIcelandCoordinate(64.1466, -21.9426), true);
|
||||
assert.equal(isLikelyIcelandCoordinate(66.3, -14.0), true);
|
||||
});
|
||||
|
||||
test('the Iceland loader reads the list with redirects refused and keeps the nearest cameras', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
withEnv(t, { CCTV_ICELAND_MAX_SOURCES: '8' });
|
||||
const rows = Array.from({ length: 12 }, (_, i) =>
|
||||
row({
|
||||
Maelist_nr: 8000 + i,
|
||||
Slod: `${ICELAND_IMAGE_ORIGIN}far_${i}.jpg`,
|
||||
Skyring: `Far ${i}`,
|
||||
Breidd: 66.2,
|
||||
Lengd: -15.9 + i * 0.01,
|
||||
}),
|
||||
);
|
||||
// Reykjavík cameras come last in the feed but first in the priority order.
|
||||
// A frame the feed repeats keeps its last row, as the other packs do.
|
||||
rows.push(row({ Slod: `${ICELAND_IMAGE_ORIGIN}rvk_1.jpg`, Skyring: 'Old' }));
|
||||
rows.push(
|
||||
row({
|
||||
Slod: `${ICELAND_IMAGE_ORIGIN}rvk_1.jpg`,
|
||||
Skyring: 'Kringlumýrarbraut',
|
||||
Breidd: 64.1466,
|
||||
Lengd: -21.9426,
|
||||
}),
|
||||
);
|
||||
const seen = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
seen.push([String(url), init.redirect]);
|
||||
return json(rows);
|
||||
});
|
||||
const sources = await loadIcelandSourcesFromOpenData();
|
||||
assert.deepEqual(seen, [[ICELAND_CAMERAS_URL, 'manual']]);
|
||||
assert.equal(sources.length, 8);
|
||||
assert.equal(sources[0].id, 'is-vegagerdin-rvk_1');
|
||||
assert.equal(sources[0].name, 'Kringlumýrarbraut');
|
||||
assert.equal(sources[0].lat, 64.1466);
|
||||
assert.equal(
|
||||
new Set(sources.map((s) => s.id)).size,
|
||||
sources.length,
|
||||
'a frame the feed repeats collapses to one camera',
|
||||
);
|
||||
assert.equal(sources.available, 13);
|
||||
});
|
||||
|
||||
test('the default Iceland cap is DEFAULT_ICELAND_MAX_SOURCES', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
withEnv(t, { CCTV_ICELAND_MAX_SOURCES: undefined });
|
||||
const rows = Array.from(
|
||||
{ length: DEFAULT_ICELAND_MAX_SOURCES + 40 },
|
||||
(_, i) => row({ Slod: `${ICELAND_IMAGE_ORIGIN}cam_${i}.jpg` }),
|
||||
);
|
||||
t.mock.method(globalThis, 'fetch', async () => json(rows));
|
||||
assert.equal(
|
||||
(await loadIcelandSourcesFromOpenData()).length,
|
||||
DEFAULT_ICELAND_MAX_SOURCES,
|
||||
);
|
||||
});
|
||||
|
||||
test('CCTV_ICELAND_MAX_SOURCES is clamped to 8..600 and ignored when not a number', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
withEnv(t, { CCTV_ICELAND_MAX_SOURCES: undefined });
|
||||
const rows = Array.from({ length: 650 }, (_, i) =>
|
||||
row({ Slod: `${ICELAND_IMAGE_ORIGIN}cam_${i}.jpg` }),
|
||||
);
|
||||
t.mock.method(globalThis, 'fetch', async () => json(rows));
|
||||
for (const [value, expected] of [
|
||||
['0', 8],
|
||||
['3', 8],
|
||||
['1000', 600],
|
||||
['abc', DEFAULT_ICELAND_MAX_SOURCES],
|
||||
]) {
|
||||
process.env.CCTV_ICELAND_MAX_SOURCES = value;
|
||||
assert.equal(
|
||||
(await loadIcelandSourcesFromOpenData()).length,
|
||||
expected,
|
||||
value,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('a redirect on the Iceland frame host stays inside vefmyndavelar/', async () => {
|
||||
const frame = `${ICELAND_IMAGE_ORIGIN}hellisheidi_1.jpg`;
|
||||
const redirectTo = (location) => async (url) =>
|
||||
url === frame
|
||||
? new Response(null, { status: 302, headers: { location } })
|
||||
: new Response('frame', { headers: { 'content-type': 'image/jpeg' } });
|
||||
for (const location of [
|
||||
'/vgdata/other/x.jpg',
|
||||
'/vgdata/vefmyndavelar/../x.jpg',
|
||||
'/',
|
||||
])
|
||||
assert.equal(
|
||||
await fetchWithinHost(frame, {}, redirectTo(location)),
|
||||
null,
|
||||
location,
|
||||
);
|
||||
const followed = await fetchWithinHost(
|
||||
frame,
|
||||
{},
|
||||
redirectTo('/vgdata/vefmyndavelar/hellisheidi_1b.jpg'),
|
||||
);
|
||||
assert.equal(await followed.text(), 'frame');
|
||||
});
|
||||
|
||||
test('the Iceland loader fails soft on HTTP errors, bad payloads and network errors', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () => new Response('x', { status: 503 }),
|
||||
);
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => json({ rows: [] }));
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
t.mock.method(
|
||||
globalThis,
|
||||
'fetch',
|
||||
async () => new Response('<html>', { status: 200 }),
|
||||
);
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new Error('network down');
|
||||
});
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
});
|
||||
|
||||
test('the Iceland catalog fetch refuses redirects and oversized bodies', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const redirected = streamingResponse({
|
||||
status: 302,
|
||||
headers: {
|
||||
location: 'http://gagnaveita.vegagerdin.is/api/vefmyndavelar2014_1',
|
||||
},
|
||||
});
|
||||
t.mock.method(globalThis, 'fetch', async () => redirected.response);
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
assert.equal(
|
||||
redirected.state.cancelled,
|
||||
true,
|
||||
'the redirect body is cancelled',
|
||||
);
|
||||
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const failed = streamingResponse({ status: 500 });
|
||||
t.mock.method(globalThis, 'fetch', async () => failed.response);
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
assert.equal(failed.state.cancelled, true, 'the error body is cancelled');
|
||||
|
||||
const valid = JSON.stringify([row()]);
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
return new Response(valid, {
|
||||
headers: { 'content-length': String(ICELAND_MAX_CATALOG_BYTES + 1) },
|
||||
});
|
||||
});
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
|
||||
t.mock.restoreAll();
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async () => {
|
||||
const padded = valid + ' '.repeat(ICELAND_MAX_CATALOG_BYTES + 1024);
|
||||
return new Response(
|
||||
new ReadableStream({
|
||||
start(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(padded));
|
||||
controller.close();
|
||||
},
|
||||
}),
|
||||
);
|
||||
});
|
||||
assert.deepEqual(await loadIcelandSourcesFromOpenData(), []);
|
||||
});
|
||||
|
||||
test('CCTV catalog merges Iceland cameras and CCTV_ICELAND_ENABLED=0 skips the request', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const sourceRoot = fs.mkdtempSync(
|
||||
path.join(os.tmpdir(), 'gev-cctv-catalog-iceland-'),
|
||||
);
|
||||
t.after(() => fs.rmSync(sourceRoot, { recursive: true, force: true }));
|
||||
withEnv(t, {
|
||||
CCTV_SOURCES_FILE: undefined,
|
||||
CCTV_SOURCES_JSON: undefined,
|
||||
CCTV_FORCE_AUSTIN: undefined,
|
||||
CCTV_PREFER_AUSTIN: undefined,
|
||||
CCTV_MAX_SOURCES: undefined,
|
||||
CCTV_CALTRANS_DISTRICTS: undefined,
|
||||
CCTV_TFL_ENABLED: undefined,
|
||||
CCTV_ICELAND_ENABLED: undefined,
|
||||
CCTV_ICELAND_MAX_SOURCES: undefined,
|
||||
});
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init) => {
|
||||
requested.push([String(url), init.redirect]);
|
||||
if (String(url) !== ICELAND_CAMERAS_URL) {
|
||||
return new Response('unavailable', { status: 503 });
|
||||
}
|
||||
return json([row()]);
|
||||
});
|
||||
|
||||
const sources = await createCctvCatalog({ sourceRoot })();
|
||||
assert.deepEqual(
|
||||
sources.map((source) => source.id),
|
||||
['is-vegagerdin-hellisheidi_1'],
|
||||
);
|
||||
|
||||
process.env.CCTV_ICELAND_ENABLED = '0';
|
||||
requested.length = 0;
|
||||
assert.deepEqual(await createCctvCatalog({ sourceRoot })(), []);
|
||||
assert.ok(requested.length > 0, 'the other live packs still load');
|
||||
assert.equal(
|
||||
requested.some(([url]) => url === ICELAND_CAMERAS_URL),
|
||||
false,
|
||||
'a disabled pack makes no request',
|
||||
);
|
||||
});
|
||||
+8
-3
@@ -34,6 +34,8 @@ const PROVIDER_STATIC_REFRESH_MS = Object.freeze({
|
||||
'ontario 511': 3 * 60 * 1000,
|
||||
// TxDOT publishes roughly once a minute; 3 min matches the other highway packs.
|
||||
txdot: 3 * 60 * 1000,
|
||||
// TranStar says snapshots update about every 3 minutes.
|
||||
'houston transtar': 3 * 60 * 1000,
|
||||
// Digitraffic publishes a new weathercam frame on each station's
|
||||
// collectionInterval, 600 s for every station sampled; polling faster only
|
||||
// re-fetches the same JPEG.
|
||||
@@ -42,6 +44,9 @@ const PROVIDER_STATIC_REFRESH_MS = Object.freeze({
|
||||
// every 20s showed no change inside 64s but a new frame by ~90-150s later —
|
||||
// matches the other highway packs' 3-minute cadence.
|
||||
'servei català de trànsit': 3 * 60 * 1000,
|
||||
// Autobrennero (A22) refreshes its stills about once a minute (Last-Modified
|
||||
// tracks the minute); 3 min matches the other highway packs.
|
||||
'autostrada del brennero': 3 * 60 * 1000,
|
||||
});
|
||||
|
||||
/**
|
||||
@@ -94,7 +99,7 @@ export function incumbentRankKm(
|
||||
export const CCTV_CARD_CENTER_WEIGHT = 0.5;
|
||||
|
||||
/** Robust pool-distance percentile used to scale the screen-space term. */
|
||||
export const CCTV_CARD_SPREAD_PERCENTILE = 0.9;
|
||||
const CCTV_CARD_SPREAD_PERCENTILE = 0.9;
|
||||
|
||||
/** True only when both viewport dimensions are finite positive pixels. */
|
||||
export function hasFiniteCctvViewport(viewW, viewH) {
|
||||
@@ -172,8 +177,8 @@ export function blendCenterRankKm(
|
||||
// viewport is bucketed into this grid and every occupied cell gets its best
|
||||
// candidate before global rank fills the rest. Owner-tunable together with
|
||||
// the budgets above.
|
||||
export const CCTV_CARD_GRID_COLS = 5;
|
||||
export const CCTV_CARD_GRID_ROWS = 4;
|
||||
const CCTV_CARD_GRID_COLS = 5;
|
||||
const CCTV_CARD_GRID_ROWS = 4;
|
||||
|
||||
/**
|
||||
* Screen-space distribution pass (owner round 2, item C). Buckets the
|
||||
|
||||
@@ -639,6 +639,7 @@ test('staticFrameRefreshMs follows known pack cadences and bounds explicit value
|
||||
assert.equal(staticFrameRefreshMs({ provider: 'Caltrans' }), 180_000);
|
||||
assert.equal(staticFrameRefreshMs({ provider: 'Ontario 511' }), 180_000);
|
||||
assert.equal(staticFrameRefreshMs({ provider: 'TxDOT' }), 180_000);
|
||||
assert.equal(staticFrameRefreshMs({ provider: 'Houston TranStar' }), 180_000);
|
||||
// Digitraffic publishes one weathercam frame per 600 s collection interval.
|
||||
assert.equal(staticFrameRefreshMs({ provider: 'Fintraffic' }), 600_000);
|
||||
assert.equal(
|
||||
|
||||
@@ -33,6 +33,14 @@ const VIDEO = {
|
||||
feedType: 'video',
|
||||
url: 'https://cams.upstream.invalid/live.mp4',
|
||||
};
|
||||
const WEBM = {
|
||||
id: 'webm-fixture',
|
||||
name: 'WebM fixture',
|
||||
lat: 30.27,
|
||||
lon: -97.74,
|
||||
feedType: 'webm',
|
||||
url: 'https://cams.upstream.invalid/live.webm',
|
||||
};
|
||||
const MJPEG = {
|
||||
id: 'mjpeg-fixture',
|
||||
name: 'MJPEG fixture',
|
||||
@@ -69,7 +77,10 @@ function recordingResponse() {
|
||||
body: '',
|
||||
writeHead(status, headers) {
|
||||
res.statusCode = status;
|
||||
res.headers = headers || {};
|
||||
res.headers = { ...res.headers, ...headers };
|
||||
},
|
||||
setHeader(name, value) {
|
||||
res.headers[name] = value;
|
||||
},
|
||||
write(chunk) {
|
||||
chunks.push(Buffer.from(chunk));
|
||||
@@ -105,6 +116,7 @@ function mount(t, respond) {
|
||||
STILL,
|
||||
STILL_ALIAS,
|
||||
VIDEO,
|
||||
WEBM,
|
||||
MJPEG,
|
||||
]);
|
||||
process.env.CCTV_SOURCES_FILE = 'absent-source-file.json';
|
||||
@@ -143,9 +155,9 @@ function mount(t, respond) {
|
||||
});
|
||||
assert.ok(handler, 'the CCTV provider must mount a middleware');
|
||||
|
||||
const call = async (path) => {
|
||||
const call = async (path, headers = {}) => {
|
||||
const { res, done } = recordingResponse();
|
||||
await handler({ url: path, headers: {}, method: 'GET', on() {} }, res);
|
||||
await handler({ url: path, headers, method: 'GET', on() {} }, res);
|
||||
await done;
|
||||
return res;
|
||||
};
|
||||
@@ -269,6 +281,254 @@ test('/frame does not follow a still camera off its origin', async (t) => {
|
||||
);
|
||||
});
|
||||
|
||||
/** An upstream Response whose body records whether it was cancelled. */
|
||||
function trackedUpstream({ status = 200, headers = {}, body = 'payload' }) {
|
||||
const state = { cancelled: false };
|
||||
const response = new Response(
|
||||
new ReadableStream(
|
||||
{
|
||||
pull(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(body));
|
||||
controller.close();
|
||||
},
|
||||
cancel() {
|
||||
state.cancelled = true;
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
),
|
||||
{ status, headers },
|
||||
);
|
||||
return { response, state };
|
||||
}
|
||||
|
||||
test('/media refuses an upstream type that does not match the feed kind', async (t) => {
|
||||
let current;
|
||||
const app = mount(t, () => current.response);
|
||||
for (const [camera, contentType, body] of [
|
||||
[VIDEO, 'text/html', '<!doctype html><p>x</p>'],
|
||||
[VIDEO, 'image/svg+xml', '<svg xmlns="http://www.w3.org/2000/svg"/>'],
|
||||
[VIDEO, 'application/vnd.apple.mpegurl', '#EXTM3U'],
|
||||
[VIDEO, 'video/webm', 'video'],
|
||||
[VIDEO, undefined, 'video'],
|
||||
[WEBM, 'video/mp4', 'video'],
|
||||
[MJPEG, 'multipart/x-mixed-replace', '--frame'],
|
||||
[MJPEG, 'multipart/x-mixed-replace; boundary=', '--frame'],
|
||||
[MJPEG, 'image/jpeg', 'jpeg'],
|
||||
[MJPEG, 'text/html; boundary=frame', '<!doctype html><p>x</p>'],
|
||||
]) {
|
||||
current = trackedUpstream({
|
||||
headers: contentType === undefined ? {} : { 'content-type': contentType },
|
||||
body,
|
||||
});
|
||||
const label = `${camera.id}: ${contentType}`;
|
||||
const res = await app.call(`/media/${camera.id}`);
|
||||
assert.equal(res.statusCode, 502, label);
|
||||
assert.equal(res.headers['Content-Type'], 'application/json', label);
|
||||
assert.deepEqual(JSON.parse(res.body), { error: 'Media proxy failed' });
|
||||
assert.equal(current.state.cancelled, true, `${label}: upstream cancelled`);
|
||||
const health = await app.health(camera.id);
|
||||
assert.equal(health.status, 'degraded', label);
|
||||
assert.equal(health.message, 'Unexpected media type', label);
|
||||
}
|
||||
});
|
||||
|
||||
test('/media relays each feed kind under its canonical type, including a partial response', async (t) => {
|
||||
let current;
|
||||
const app = mount(t, () => current);
|
||||
for (const [camera, upstream, expected] of [
|
||||
[VIDEO, { 'content-type': 'Video/MP4; codecs="avc1.42E01E"' }, 'video/mp4'],
|
||||
[
|
||||
VIDEO,
|
||||
{
|
||||
'content-type': 'video/mp4',
|
||||
'content-range': 'bytes 0-4/100',
|
||||
'content-length': '5',
|
||||
'accept-ranges': 'bytes',
|
||||
},
|
||||
'video/mp4',
|
||||
],
|
||||
[WEBM, { 'content-type': 'video/webm' }, 'video/webm'],
|
||||
[
|
||||
MJPEG,
|
||||
{ 'content-type': 'multipart/x-mixed-replace;boundary="frame"' },
|
||||
'multipart/x-mixed-replace; boundary=frame',
|
||||
],
|
||||
[
|
||||
MJPEG,
|
||||
{ 'content-type': 'multipart/x-mixed-replace; boundary="a b"' },
|
||||
'multipart/x-mixed-replace; boundary="a b"',
|
||||
],
|
||||
]) {
|
||||
const status = upstream['content-range'] ? 206 : 200;
|
||||
current = upstreamResponse({ status, headers: upstream, body: 'bytes' });
|
||||
const res = await app.call(`/media/${camera.id}`);
|
||||
assert.equal(res.statusCode, status, camera.id);
|
||||
assert.equal(res.headers['Content-Type'], expected);
|
||||
assert.equal(res.body, 'bytes');
|
||||
if (status === 206)
|
||||
assert.equal(res.headers['Content-Range'], 'bytes 0-4/100');
|
||||
assert.equal((await app.health(camera.id)).status, 'ok');
|
||||
}
|
||||
});
|
||||
|
||||
test('/media does not follow a live camera off its origin', async (t) => {
|
||||
const app = mount(t, ({ url }) =>
|
||||
url === VIDEO.url
|
||||
? upstreamResponse({
|
||||
status: 302,
|
||||
headers: { location: 'https://elsewhere.invalid/live.mp4' },
|
||||
body: '',
|
||||
})
|
||||
: upstreamResponse({
|
||||
headers: { 'content-type': 'video/mp4' },
|
||||
body: 'elsewhere',
|
||||
}),
|
||||
);
|
||||
const res = await app.call(`/media/${VIDEO.id}`);
|
||||
assert.equal(res.statusCode, 502);
|
||||
assert.doesNotMatch(res.body, /elsewhere/);
|
||||
assert.deepEqual(app.requests, [{ url: VIDEO.url, redirect: 'manual' }]);
|
||||
});
|
||||
|
||||
test('every CCTV route refuses cross-site requests and admits the app itself', async (t) => {
|
||||
const app = mount(t, ({ url }) =>
|
||||
upstreamResponse({
|
||||
headers: {
|
||||
'content-type': url === VIDEO.url ? 'video/mp4' : 'image/jpeg',
|
||||
},
|
||||
body: 'bytes',
|
||||
}),
|
||||
);
|
||||
const host = 'localhost:5173';
|
||||
const paths = [
|
||||
'/sources',
|
||||
'/health',
|
||||
`/stream/${STILL.id}`,
|
||||
`/frame/${STILL.id}`,
|
||||
`/media/${VIDEO.id}`,
|
||||
];
|
||||
for (const headers of [
|
||||
{ host, 'sec-fetch-site': 'cross-site' },
|
||||
{ host, 'sec-fetch-site': 'same-site' },
|
||||
{ host, origin: 'https://elsewhere.example' },
|
||||
{ host, origin: 'null' },
|
||||
])
|
||||
for (const path of paths) {
|
||||
const res = await app.call(path, headers);
|
||||
assert.equal(res.statusCode, 403, `${path} ${JSON.stringify(headers)}`);
|
||||
}
|
||||
assert.deepEqual(app.requests, [], 'a refused request reached an upstream');
|
||||
for (const headers of [
|
||||
{ host, 'sec-fetch-site': 'same-origin' },
|
||||
{ host, origin: `http://${host}` },
|
||||
{},
|
||||
]) {
|
||||
const frame = await app.call(`/frame/${STILL.id}`, headers);
|
||||
assert.equal(frame.statusCode, 200);
|
||||
assert.equal(frame.headers['X-CCTV-Source'], 'upstream-image');
|
||||
const media = await app.call(`/media/${VIDEO.id}`, headers);
|
||||
assert.equal(media.statusCode, 200);
|
||||
assert.equal(media.headers['Content-Type'], 'video/mp4');
|
||||
}
|
||||
});
|
||||
|
||||
test('/frame falls back past a non-raster upstream and Street View frame', async (t) => {
|
||||
let streetViewType;
|
||||
const app = mount(t, ({ url }) =>
|
||||
url.startsWith('https://maps.googleapis.com/')
|
||||
? trackedUpstream({
|
||||
headers:
|
||||
streetViewType === undefined
|
||||
? {}
|
||||
: { 'content-type': streetViewType },
|
||||
body: 'street-view',
|
||||
}).response
|
||||
: upstreamResponse({
|
||||
headers: { 'content-type': 'image/svg+xml' },
|
||||
body: '<svg xmlns="http://www.w3.org/2000/svg"/>',
|
||||
}),
|
||||
);
|
||||
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
|
||||
for (const type of [
|
||||
'image/svg+xml',
|
||||
'text/html',
|
||||
'application/xml',
|
||||
undefined,
|
||||
]) {
|
||||
streetViewType = type;
|
||||
const res = await app.call(`/frame/${STILL.id}`);
|
||||
assert.equal(res.statusCode, 200);
|
||||
assert.equal(res.headers['X-CCTV-Source'], 'synthetic', String(type));
|
||||
assert.doesNotMatch(res.body, /street-view/);
|
||||
}
|
||||
streetViewType = 'image/JPEG; charset=x';
|
||||
const res = await app.call(`/frame/${STILL.id}`);
|
||||
assert.equal(res.headers['X-CCTV-Source'], 'streetview');
|
||||
assert.equal(res.headers['Content-Type'], 'image/jpeg');
|
||||
assert.equal(res.body, 'street-view');
|
||||
});
|
||||
|
||||
test('a forwarded same-origin request reaches every CCTV route but not the Street View fallback', async (t) => {
|
||||
const app = mount(t, ({ url }) => {
|
||||
if (url.startsWith('https://maps.googleapis.com/'))
|
||||
return trackedUpstream({
|
||||
headers: { 'content-type': 'image/jpeg' },
|
||||
body: 'street-view',
|
||||
}).response;
|
||||
return url === VIDEO.url
|
||||
? upstreamResponse({ headers: { 'content-type': 'video/mp4' } })
|
||||
: upstreamResponse({ status: 503, body: '' });
|
||||
});
|
||||
process.env.GOOGLE_MAPS_SERVER_API_KEY = 'fixture-key';
|
||||
const host = 'localhost:5173';
|
||||
const streetViewCalls = () =>
|
||||
app.requests.filter(({ url }) =>
|
||||
url.startsWith('https://maps.googleapis.com/'),
|
||||
).length;
|
||||
for (const forwarded of [
|
||||
{ 'x-forwarded-for': '203.0.113.9' },
|
||||
{ via: '1.1 proxy' },
|
||||
{ forwarded: 'for=203.0.113.9' },
|
||||
{ 'x-real-ip': '203.0.113.9' },
|
||||
{ 'x-forwarded-for': '' },
|
||||
{ 'x-forwarded-for': ' ' },
|
||||
{ 'cf-connecting-ip': '' },
|
||||
]) {
|
||||
const headers = { host, 'sec-fetch-site': 'same-origin', ...forwarded };
|
||||
const label = JSON.stringify(forwarded);
|
||||
assert.equal((await app.call('/sources', headers)).statusCode, 200, label);
|
||||
const media = await app.call(`/media/${VIDEO.id}`, headers);
|
||||
assert.equal(media.statusCode, 200, label);
|
||||
assert.equal(media.headers['Content-Type'], 'video/mp4', label);
|
||||
const frame = await app.call(`/frame/${STILL.id}`, headers);
|
||||
assert.equal(frame.statusCode, 200, label);
|
||||
assert.equal(frame.headers['X-CCTV-Source'], 'synthetic', label);
|
||||
assert.equal(frame.headers['Content-Type'], 'image/svg+xml', label);
|
||||
// Cross-site stays refused whatever the forwarding headers say.
|
||||
for (const path of ['/sources', `/frame/${STILL.id}`, `/media/${VIDEO.id}`])
|
||||
assert.equal(
|
||||
(
|
||||
await app.call(path, {
|
||||
...forwarded,
|
||||
host,
|
||||
'sec-fetch-site': 'cross-site',
|
||||
})
|
||||
).statusCode,
|
||||
403,
|
||||
`${label} ${path}`,
|
||||
);
|
||||
}
|
||||
assert.equal(streetViewCalls(), 0, 'a forwarded request spent the key');
|
||||
const direct = await app.call(`/frame/${STILL.id}`, {
|
||||
host,
|
||||
'sec-fetch-site': 'same-origin',
|
||||
});
|
||||
assert.equal(direct.headers['X-CCTV-Source'], 'streetview');
|
||||
assert.equal(direct.body, 'street-view');
|
||||
assert.equal(streetViewCalls(), 1);
|
||||
});
|
||||
|
||||
test('cross-site media creation, segment reads and release fail before any catalog or media fetch', async (t) => {
|
||||
let handler;
|
||||
const originalFetch = globalThis.fetch;
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
nycCameraToSource,
|
||||
} from '../../server/providers/cctv/sources.js';
|
||||
import {
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
DEFAULT_NYC_MAX_SOURCES,
|
||||
NYC_CAMERAS_URL,
|
||||
NYC_GROUND_ELEVATION_M,
|
||||
@@ -375,8 +375,8 @@ for (const [label, flag] of [
|
||||
});
|
||||
}
|
||||
|
||||
test('the shipped catalog ceiling is not raised to make room for this pack', () => {
|
||||
assert.equal(DEFAULT_CCTV_MAX_SOURCES, 4000);
|
||||
test('the shared catalog slots are not raised to make room for this pack', () => {
|
||||
assert.equal(CCTV_SHARED_SOURCE_SLOTS, 4000);
|
||||
assert.equal(DEFAULT_NYC_MAX_SOURCES, 250);
|
||||
});
|
||||
|
||||
|
||||
@@ -0,0 +1,255 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { createCctvCatalog } from '../../server/providers/cctv/catalog.js';
|
||||
import {
|
||||
OTTAWA_CAMERAS_URL,
|
||||
OTTAWA_IMAGE_ORIGIN,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import {
|
||||
fallbackHeadingFromId,
|
||||
pinnedCameraUrl,
|
||||
} from '../../server/providers/cctv/normalize.js';
|
||||
import {
|
||||
_resetOttawaCertificateWarningForTest,
|
||||
loadOttawaSourcesFromOpenData,
|
||||
ottawaAuthorizedFrameUrl,
|
||||
} from '../../server/providers/cctv/ottawa.js';
|
||||
|
||||
const CERT = { OTTAWA_CAMERA_CERTIFICATE: 'CERT123' };
|
||||
|
||||
/** Set (or, for `undefined`, delete) environment variables for one test. */
|
||||
function withEnv(t, env) {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
const previous = process.env[name];
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env[name];
|
||||
else process.env[name] = previous;
|
||||
});
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/** Silence the loader's progress and failure logging. */
|
||||
function quiet(t) {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
}
|
||||
|
||||
/** One documented `/map/service/camera` row carrying the fields the loader reads. */
|
||||
function ottawaRow(number, lat, lon, overrides = {}) {
|
||||
return {
|
||||
id: number + 10000,
|
||||
camera_number: number,
|
||||
name: `Camera ${number}`,
|
||||
name_french: `Caméra ${number}`,
|
||||
cameraOwner: 'CITY',
|
||||
latitude: lat,
|
||||
longitude: lon,
|
||||
...overrides,
|
||||
};
|
||||
}
|
||||
|
||||
/** The feed's envelope around its rows. */
|
||||
const ottawaPayload = (rows) => Response.json({ cameras: rows });
|
||||
|
||||
test('without OTTAWA_CAMERA_CERTIFICATE the Ottawa pack is skipped with no request, logged once', async (t) => {
|
||||
_resetOttawaCertificateWarningForTest();
|
||||
const lines = [];
|
||||
t.mock.method(console, 'warn', (line) => lines.push(String(line)));
|
||||
const fetchMock = t.mock.method(globalThis, 'fetch', async () => {
|
||||
throw new Error('no request expected');
|
||||
});
|
||||
assert.deepEqual(await loadOttawaSourcesFromOpenData({}, {}), []);
|
||||
assert.deepEqual(
|
||||
await loadOttawaSourcesFromOpenData({}, { OTTAWA_CAMERA_CERTIFICATE: ' ' }),
|
||||
[],
|
||||
);
|
||||
assert.equal(fetchMock.mock.callCount(), 0);
|
||||
assert.equal(lines.length, 1);
|
||||
assert.match(lines[0], /OTTAWA_CAMERA_CERTIFICATE/);
|
||||
});
|
||||
|
||||
test('Ottawa frame URLs are signed only inside the opendata camera path', () => {
|
||||
assert.equal(
|
||||
ottawaAuthorizedFrameUrl('https://traffic.ottawa.ca/opendata/camera?c=16', CERT),
|
||||
'https://traffic.ottawa.ca/opendata/camera?c=16&certificate=CERT123&id=gev',
|
||||
);
|
||||
assert.equal(
|
||||
ottawaAuthorizedFrameUrl('https://traffic.ottawa.ca/opendata/camera?c=16', {}),
|
||||
'',
|
||||
'no certificate, no signed URL',
|
||||
);
|
||||
for (const url of [
|
||||
'https://traffic.ottawa.ca/opendata/camera?c=16x',
|
||||
'https://traffic.ottawa.ca/opendata/other?c=16',
|
||||
'https://traffic.ottawa.ca/map/camera?id=16',
|
||||
'https://traffic.ottawa.ca.evil.test/opendata/camera?c=16',
|
||||
'http://traffic.ottawa.ca/opendata/camera?c=16',
|
||||
])
|
||||
assert.equal(ottawaAuthorizedFrameUrl(url, CERT), '', url);
|
||||
});
|
||||
|
||||
test('Ottawa loader keeps in-city cameras and builds keyless frame URLs from the camera number', async (t) => {
|
||||
quiet(t);
|
||||
withEnv(t, { CCTV_OTTAWA_MAX_SOURCES: undefined });
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
return ottawaPayload([
|
||||
ottawaRow(2025, 45.341343, -75.81467, {
|
||||
name: '(MTO) Hwy 416 NB ramp to Hwy 417 East',
|
||||
cameraOwner: 'MTO',
|
||||
}),
|
||||
ottawaRow(1, 45.4215, -75.6972, {
|
||||
name: 'Bank St at Somerset St',
|
||||
camera_owner: 'CITY',
|
||||
cameraOwner: undefined,
|
||||
}),
|
||||
ottawaRow(1, 45.4216, -75.6973, { name: 'duplicate number' }),
|
||||
ottawaRow(0, 45.4215, -75.6972),
|
||||
ottawaRow(-3, 45.4215, -75.6972),
|
||||
ottawaRow(7, null, -75.7),
|
||||
ottawaRow(8, 45.4, null),
|
||||
ottawaRow(9, 43.6532, -79.3832, { description: 'Toronto' }),
|
||||
ottawaRow(10, 45.9, -75.7),
|
||||
]);
|
||||
});
|
||||
|
||||
const cameras = await loadOttawaSourcesFromOpenData({}, CERT);
|
||||
|
||||
assert.deepEqual(requested, [OTTAWA_CAMERAS_URL]);
|
||||
assert.deepEqual(cameras.map((camera) => camera.id).sort(), [
|
||||
'ottawa-1',
|
||||
'ottawa-2025',
|
||||
]);
|
||||
|
||||
const mto = cameras.find((camera) => camera.id === 'ottawa-2025');
|
||||
const city = cameras.find((camera) => camera.id === 'ottawa-1');
|
||||
assert.equal(mto.url, 'https://traffic.ottawa.ca/opendata/camera?c=2025');
|
||||
assert.doesNotMatch(mto.url, /certificate/, 'the catalog URL carries no key');
|
||||
assert.equal(mto.snapshotUrl, mto.url);
|
||||
assert.equal(mto.frameRefreshMs, 60000, 'the API allows one fetch a minute');
|
||||
assert.equal(city.name, 'Bank St at Somerset St');
|
||||
assert.equal(mto.name, '(MTO) Hwy 416 NB ramp to Hwy 417 East');
|
||||
assert.equal(mto.city, 'Ottawa');
|
||||
assert.equal(mto.provider, 'City of Ottawa');
|
||||
assert.equal(mto.feedType, 'image');
|
||||
assert.equal(mto.sourceKind, 'ottawa-traffic');
|
||||
assert.equal(mto.headingConfidence, 'low');
|
||||
assert.equal(
|
||||
mto.headingDeg,
|
||||
fallbackHeadingFromId('ottawa-2025'),
|
||||
'the feed publishes no bearing, so the id-hash fallback is deterministic',
|
||||
);
|
||||
assert.match(mto.license, /City of Ottawa/);
|
||||
assert.equal(
|
||||
mto.credit,
|
||||
'Ministry of Transportation of Ontario (MTO) camera',
|
||||
'a provincial camera carried on the city feed names its owner',
|
||||
);
|
||||
assert.equal(city.credit, '', 'a city camera carries no partner credit');
|
||||
});
|
||||
|
||||
test('Ottawa loader keeps the cameras nearest downtown under its cap', async (t) => {
|
||||
quiet(t);
|
||||
withEnv(t, { CCTV_OTTAWA_MAX_SOURCES: '8' });
|
||||
const rows = [
|
||||
// Far suburbs come first in payload order, so only distance can drop them.
|
||||
...[45.55, 45.54, 45.53, 45.52].map((lat, i) =>
|
||||
ottawaRow(100 + i, lat, -76.1),
|
||||
),
|
||||
...[45.42, 45.421, 45.422, 45.423, 45.424, 45.425, 45.426, 45.427].map(
|
||||
(lat, i) => ottawaRow(200 + i, lat, -75.7),
|
||||
),
|
||||
];
|
||||
t.mock.method(globalThis, 'fetch', async () => ottawaPayload(rows));
|
||||
|
||||
const cameras = await loadOttawaSourcesFromOpenData({}, CERT);
|
||||
|
||||
assert.equal(cameras.length, 8);
|
||||
assert.deepEqual(
|
||||
cameras.map((camera) => camera.id).filter((id) => /^ottawa-10\d$/.test(id)),
|
||||
[],
|
||||
'the far-suburb cameras are the ones dropped',
|
||||
);
|
||||
});
|
||||
|
||||
test('Ottawa loader fails soft on HTTP errors, unexpected payloads and network errors', async (t) => {
|
||||
quiet(t);
|
||||
let respond;
|
||||
t.mock.method(globalThis, 'fetch', (...args) => respond(...args));
|
||||
for (respond of [
|
||||
async () => new Response('unavailable', { status: 503 }),
|
||||
async () => Response.json({ cameras: [] }),
|
||||
async () => Response.json([ottawaRow(1, 45.4215, -75.6972)]),
|
||||
async () => {
|
||||
throw new TypeError('fetch failed');
|
||||
},
|
||||
]) {
|
||||
assert.deepEqual(await loadOttawaSourcesFromOpenData({}, CERT), []);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV catalog merges Ottawa cameras with a certificate and CCTV_OTTAWA_ENABLED=0 skips the request', async (t) => {
|
||||
quiet(t);
|
||||
const sourceRoot = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-cctv-ottawa-'));
|
||||
t.after(() => fs.rmSync(sourceRoot, { recursive: true, force: true }));
|
||||
withEnv(t, {
|
||||
CCTV_SOURCES_FILE: undefined,
|
||||
CCTV_SOURCES_JSON: undefined,
|
||||
CCTV_FORCE_AUSTIN: undefined,
|
||||
CCTV_PREFER_AUSTIN: undefined,
|
||||
CCTV_MAX_SOURCES: undefined,
|
||||
CCTV_OTTAWA_ENABLED: undefined,
|
||||
CCTV_OTTAWA_MAX_SOURCES: undefined,
|
||||
CCTV_QUEBEC_ENABLED: '0',
|
||||
CCTV_WORLD_CAMERAS_ENABLED: '0',
|
||||
OTTAWA_CAMERA_CERTIFICATE: 'CERT123',
|
||||
});
|
||||
const requested = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
requested.push(String(url));
|
||||
// Every other live pack is down; only Ottawa answers.
|
||||
return String(url) === OTTAWA_CAMERAS_URL
|
||||
? ottawaPayload([ottawaRow(1, 45.4215, -75.6972)])
|
||||
: new Response('unavailable', { status: 503 });
|
||||
});
|
||||
|
||||
const sources = await createCctvCatalog({ sourceRoot })();
|
||||
assert.deepEqual(
|
||||
sources.map((source) => source.id),
|
||||
['ottawa-1'],
|
||||
);
|
||||
assert.equal(sources[0].url, 'https://traffic.ottawa.ca/opendata/camera?c=1');
|
||||
|
||||
process.env.CCTV_OTTAWA_ENABLED = '0';
|
||||
requested.length = 0;
|
||||
assert.deepEqual(await createCctvCatalog({ sourceRoot })(), []);
|
||||
assert.ok(requested.length > 0, 'the other live packs still load');
|
||||
assert.equal(
|
||||
requested.includes(OTTAWA_CAMERAS_URL),
|
||||
false,
|
||||
'a disabled pack makes no request',
|
||||
);
|
||||
});
|
||||
|
||||
test('Ottawa frames stay inside the city image directory', () => {
|
||||
assert.ok(
|
||||
pinnedCameraUrl(
|
||||
'https://traffic.ottawa.ca/opendata/camera?c=309',
|
||||
OTTAWA_IMAGE_ORIGIN,
|
||||
),
|
||||
);
|
||||
for (const url of [
|
||||
'https://traffic.ottawa.ca.evil.test/opendata/camera?c=309',
|
||||
'https://traffic.ottawa.ca/map/camera?id=309',
|
||||
'https://user:[email protected]/opendata/camera?c=309',
|
||||
'https://traffic.ottawa.ca:8443/opendata/camera?c=309',
|
||||
'http://traffic.ottawa.ca/opendata/camera?c=309',
|
||||
])
|
||||
assert.equal(pinnedCameraUrl(url, OTTAWA_IMAGE_ORIGIN), null, url);
|
||||
});
|
||||
@@ -259,3 +259,288 @@ test('rejected snapshot responses abort the upstream download', async () => {
|
||||
assert.equal(signal.aborted, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV upstream frame fetch accepts only raster image types and sends their canonical type', async () => {
|
||||
const frame = (contentType, body = 'frame') => {
|
||||
const state = { cancelled: false };
|
||||
const headers = contentType === null ? {} : { 'Content-Type': contentType };
|
||||
const response = new Response(new ReadableStream({
|
||||
pull(controller) {
|
||||
controller.enqueue(new TextEncoder().encode(body));
|
||||
controller.close();
|
||||
},
|
||||
cancel() {
|
||||
state.cancelled = true;
|
||||
},
|
||||
}, { highWaterMark: 0 }), { status: 200, headers });
|
||||
return { response, state };
|
||||
};
|
||||
for (const [contentType, canonical] of [
|
||||
['image/jpeg', 'image/jpeg'],
|
||||
['image/JPEG; charset=x', 'image/jpeg'],
|
||||
[' Image/PNG ', 'image/png'],
|
||||
['image/gif', 'image/gif'],
|
||||
['image/webp;q=1', 'image/webp'],
|
||||
['image/avif', 'image/avif'],
|
||||
]) {
|
||||
const { response } = frame(contentType);
|
||||
const result = await fetchCctvImageFromUpstream('https://example.com/frame.jpg', {
|
||||
fetchImpl: async () => response,
|
||||
});
|
||||
assert.equal(result?.contentType, canonical, contentType);
|
||||
assert.equal(result.body.toString(), 'frame');
|
||||
}
|
||||
for (const [contentType, body] of [
|
||||
['image/svg+xml', '<svg xmlns="http://www.w3.org/2000/svg"/>'],
|
||||
['Image/SVG+XML; charset=utf-8', '<svg xmlns="http://www.w3.org/2000/svg"/>'],
|
||||
['text/html', '<!doctype html><p>x</p>'],
|
||||
['text/html; charset=utf-8', '<!doctype html><p>x</p>'],
|
||||
['application/xml', '<x/>'],
|
||||
['text/xml', '<x/>'],
|
||||
[null, 'frame'],
|
||||
['', 'frame'],
|
||||
['image', 'frame'],
|
||||
['image/', 'frame'],
|
||||
['image/jpeg/x', 'frame'],
|
||||
['image/jpeg, text/html', 'frame'],
|
||||
['application/octet-stream', 'frame'],
|
||||
]) {
|
||||
const { response, state } = frame(contentType, body);
|
||||
const result = await fetchCctvImageFromUpstream('https://example.com/frame.jpg', {
|
||||
fetchImpl: async () => response,
|
||||
});
|
||||
assert.equal(result, null, String(contentType));
|
||||
assert.equal(state.cancelled, true, `${contentType}: body cancelled`);
|
||||
}
|
||||
});
|
||||
|
||||
function multipartResponse(contentType, chunks, { onCancel = () => {} } = {}) {
|
||||
let nextChunk = 0;
|
||||
const body = new ReadableStream(
|
||||
{
|
||||
pull(controller) {
|
||||
if (nextChunk >= chunks.length) {
|
||||
controller.close();
|
||||
return;
|
||||
}
|
||||
controller.enqueue(chunks[nextChunk++]);
|
||||
},
|
||||
cancel() {
|
||||
onCancel();
|
||||
},
|
||||
},
|
||||
{ highWaterMark: 0 },
|
||||
);
|
||||
return new Response(body, {
|
||||
status: 200,
|
||||
headers: { 'Content-Type': contentType },
|
||||
});
|
||||
}
|
||||
|
||||
function jpegPart(boundary, body, contentType = 'image/jpeg', length = body.length) {
|
||||
return Buffer.concat([
|
||||
Buffer.from(
|
||||
'--' +
|
||||
boundary +
|
||||
'\r\nContent-Type: ' +
|
||||
contentType +
|
||||
'\r\nContent-Length: ' +
|
||||
length +
|
||||
'\r\n\r\n',
|
||||
),
|
||||
body,
|
||||
Buffer.from('\r\n'),
|
||||
]);
|
||||
}
|
||||
|
||||
test('CCTV upstream frame fetch extracts only the first JPEG from MJPEG', async () => {
|
||||
const boundary = 'DIGIEVER';
|
||||
const first = Buffer.from([0xff, 0xd8, 0x11, 0x22, 0xff, 0xd9]);
|
||||
const second = Buffer.from([0xff, 0xd8, 0x33, 0x44, 0xff, 0xd9]);
|
||||
for (const type of [
|
||||
'multipart/x-mixed-replace; boundary=DIGIEVER',
|
||||
'multipart/x-mixed-replace; boundary="DIGIEVER"',
|
||||
]) {
|
||||
let cancelled = false;
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
maxBytes: 1024,
|
||||
fetchImpl: async () =>
|
||||
multipartResponse(
|
||||
type,
|
||||
[
|
||||
jpegPart(boundary, first),
|
||||
jpegPart(boundary, second),
|
||||
Buffer.from('--' + boundary + '--\r\n'),
|
||||
],
|
||||
{ onCancel: () => { cancelled = true; } },
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.equal(result?.contentType, 'image/jpeg', type);
|
||||
assert.deepEqual(result?.body, first, type);
|
||||
assert.equal(cancelled, true, type);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV upstream frame fetch rejects malformed and non-JPEG MJPEG parts', async () => {
|
||||
const jpeg = Buffer.from([0xff, 0xd8, 0x01, 0x02, 0xff, 0xd9]);
|
||||
for (const [type, chunks] of [
|
||||
['multipart/x-mixed-replace', []],
|
||||
[
|
||||
'multipart/x-mixed-replace; boundary=DIGIEVER',
|
||||
[jpegPart('DIGIEVER', jpeg, 'image/png')],
|
||||
],
|
||||
]) {
|
||||
let cancelled = false;
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
fetchImpl: async () =>
|
||||
multipartResponse(type, chunks, { onCancel: () => { cancelled = true; } }),
|
||||
},
|
||||
);
|
||||
assert.equal(result, null, type);
|
||||
assert.equal(cancelled, true, type);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV upstream frame fetch rejects truncated or oversized MJPEG parts', async () => {
|
||||
const boundary = 'DIGIEVER';
|
||||
const full = Buffer.from([0xff, 0xd8, 0x01, 0x02, 0xff, 0xd9]);
|
||||
const truncated = Buffer.from([0xff, 0xd8, 0x01, 0x02]);
|
||||
for (const [chunks, maxBytes] of [
|
||||
[jpegPart(boundary, truncated, 'image/jpeg', full.length), 1024],
|
||||
[jpegPart(boundary, full), 5],
|
||||
]) {
|
||||
let cancelled = false;
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
maxBytes,
|
||||
fetchImpl: async () =>
|
||||
multipartResponse(
|
||||
'multipart/x-mixed-replace; boundary=' + boundary,
|
||||
[chunks],
|
||||
{ onCancel: () => { cancelled = true; } },
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.equal(result, null);
|
||||
assert.equal(cancelled, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV upstream frame fetch does not cross into a later part when the first JPEG is truncated', async () => {
|
||||
const boundary = 'DIGIEVER';
|
||||
const truncated = Buffer.from([0xff, 0xd8, 0x01, 0x02]);
|
||||
const valid = Buffer.from([0xff, 0xd8, 0x03, 0x04, 0xff, 0xd9]);
|
||||
const wire = Buffer.concat([
|
||||
Buffer.from(
|
||||
'--' + boundary + '\r\nContent-Type: image/jpeg\r\n\r\n',
|
||||
),
|
||||
truncated,
|
||||
Buffer.from(
|
||||
'\r\n--' +
|
||||
boundary +
|
||||
'\r\nContent-Type: image/jpeg\r\nContent-Length: ' +
|
||||
valid.length +
|
||||
'\r\n\r\n',
|
||||
),
|
||||
valid,
|
||||
Buffer.from('\r\n--' + boundary + '--\r\n'),
|
||||
]);
|
||||
let cancelled = false;
|
||||
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
maxBytes: 1024,
|
||||
fetchImpl: async () =>
|
||||
multipartResponse(
|
||||
'multipart/x-mixed-replace; boundary=' + boundary,
|
||||
[wire],
|
||||
{ onCancel: () => { cancelled = true; } },
|
||||
),
|
||||
},
|
||||
);
|
||||
|
||||
assert.equal(result, null);
|
||||
assert.equal(cancelled, true);
|
||||
});
|
||||
test('CCTV upstream frame fetch ignores MJPEG unless the source is registered as MJPEG', async () => {
|
||||
const boundary = 'DIGIEVER';
|
||||
const jpeg = Buffer.from([0xff, 0xd8, 0x11, 0x22, 0xff, 0xd9]);
|
||||
let cancelled = false;
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
fetchImpl: async () =>
|
||||
multipartResponse(
|
||||
'multipart/x-mixed-replace; boundary=' + boundary,
|
||||
[jpegPart(boundary, jpeg)],
|
||||
{ onCancel: () => { cancelled = true; } },
|
||||
),
|
||||
},
|
||||
);
|
||||
assert.equal(result, null);
|
||||
assert.equal(cancelled, true);
|
||||
});
|
||||
|
||||
test('CCTV upstream frame fetch accepts a CRLF preamble and a boundary that already starts with --', async () => {
|
||||
const jpeg = Buffer.from([0xff, 0xd8, 0x11, 0x22, 0xff, 0xd9]);
|
||||
for (const [type, wire] of [
|
||||
[
|
||||
'multipart/x-mixed-replace; boundary=DIGIEVER',
|
||||
Buffer.concat([Buffer.from('\r\n'), jpegPart('DIGIEVER', jpeg)]),
|
||||
],
|
||||
[
|
||||
'multipart/x-mixed-replace; boundary=--myboundary',
|
||||
Buffer.concat([
|
||||
Buffer.from(
|
||||
'--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length: ' +
|
||||
jpeg.length +
|
||||
'\r\n\r\n',
|
||||
),
|
||||
jpeg,
|
||||
Buffer.from('\r\n--myboundary\r\n'),
|
||||
]),
|
||||
],
|
||||
]) {
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
fetchImpl: async () => multipartResponse(type, [wire]),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(result?.body, jpeg, type);
|
||||
}
|
||||
});
|
||||
|
||||
test('CCTV MJPEG part without Content-Length ends at the next delimiter, not at an inner JPEG end marker', async () => {
|
||||
const boundary = 'DIGIEVER';
|
||||
// An EXIF thumbnail's own FF D9 sits inside the image.
|
||||
const jpeg = Buffer.from([0xff, 0xd8, 0x01, 0xff, 0xd9, 0x02, 0x03, 0xff, 0xd9]);
|
||||
const wire = Buffer.concat([
|
||||
Buffer.from('--' + boundary + '\r\nContent-Type: image/jpeg\r\n\r\n'),
|
||||
jpeg,
|
||||
Buffer.from('\r\n--' + boundary + '\r\nContent-Type: image/jpeg\r\n\r\n'),
|
||||
]);
|
||||
// Delivered one byte at a time, as a trickling upstream would.
|
||||
const chunks = [...wire].map((byte) => Buffer.from([byte]));
|
||||
const result = await fetchCctvImageFromUpstream(
|
||||
'https://cctv-ss02.thb.gov.tw/T62-9K+020',
|
||||
{
|
||||
allowMjpeg: true,
|
||||
fetchImpl: async () =>
|
||||
multipartResponse('multipart/x-mixed-replace; boundary=' + boundary, chunks),
|
||||
},
|
||||
);
|
||||
assert.deepEqual(result?.body, jpeg);
|
||||
});
|
||||
@@ -0,0 +1,114 @@
|
||||
// Camera catalogs are pinned to their agency's image directory. The pin is a
|
||||
// parsed-URL check, not a string prefix, so a path that only starts with the
|
||||
// directory before dot segments, an encoded separator, credentials or another
|
||||
// port are resolved never counts as inside it, and a redirect on a pinned host
|
||||
// cannot leave the directory either.
|
||||
//
|
||||
// Run with: npm test (node --test)
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { loadTflSourcesFromOpenData } from '../../server/providers/cctv/sources.js';
|
||||
import { fetchWithinHost } from '../../server/providers/cctv/media.js';
|
||||
import { pinnedCameraUrl } from '../../server/providers/cctv/normalize.js';
|
||||
|
||||
const BUCKET = 'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/';
|
||||
|
||||
/** One available JamCam whose frame is at `imageUrl`. */
|
||||
const jamCam = (n, imageUrl) => ({
|
||||
id: `JamCams_00001.0000${n}`,
|
||||
commonName: `JamCam ${n}`,
|
||||
lat: 51.5072,
|
||||
lon: -0.1276,
|
||||
additionalProperties: [
|
||||
{ key: 'available', value: 'true' },
|
||||
{ key: 'imageUrl', value: imageUrl },
|
||||
],
|
||||
});
|
||||
|
||||
test('TfL JamCams keep only frames inside the official bucket, by parsed URL', async (t) => {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
const accepted = [
|
||||
[`${BUCKET}00001.00001.jpg`, `${BUCKET}00001.00001.jpg`],
|
||||
[`${BUCKET}00001.00002.jpg?t=1`, `${BUCKET}00001.00002.jpg?t=1`],
|
||||
[
|
||||
'https://s3-eu-west-1.amazonaws.com:443/jamcams.tfl.gov.uk/00001.00003.jpg',
|
||||
`${BUCKET}00001.00003.jpg`,
|
||||
],
|
||||
];
|
||||
const rejected = [
|
||||
`${BUCKET}../other/x.jpg`,
|
||||
`${BUCKET}%2e%2e/other/x.jpg`,
|
||||
`${BUCKET}%2E%2E/other/x.jpg`,
|
||||
`${BUCKET}.%2e/other/x.jpg`,
|
||||
`${BUCKET}..%2fother/x.jpg`,
|
||||
`${BUCKET}..%5Cother/x.jpg`,
|
||||
`${BUCKET}..\\other\\x.jpg`,
|
||||
'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk.other/x.jpg',
|
||||
'https://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk-other/x.jpg',
|
||||
'https://s3-eu-west-1.amazonaws.com/other/jamcams.tfl.gov.uk/x.jpg',
|
||||
'https://user:[email protected]/jamcams.tfl.gov.uk/x.jpg',
|
||||
'https://s3-eu-west-1.amazonaws.com:8443/jamcams.tfl.gov.uk/x.jpg',
|
||||
'http://s3-eu-west-1.amazonaws.com/jamcams.tfl.gov.uk/x.jpg',
|
||||
'https://s3-eu-west-1.amazonaws.com.other.example/jamcams.tfl.gov.uk/x.jpg',
|
||||
'not a url',
|
||||
];
|
||||
t.mock.method(globalThis, 'fetch', async () =>
|
||||
Response.json(
|
||||
[...accepted.map(([url]) => url), ...rejected].map((url, i) =>
|
||||
jamCam(i + 1, url),
|
||||
),
|
||||
),
|
||||
);
|
||||
const cameras = await loadTflSourcesFromOpenData();
|
||||
assert.deepEqual(
|
||||
cameras.map((camera) => camera.url),
|
||||
accepted.map(([, normalized]) => normalized),
|
||||
);
|
||||
});
|
||||
|
||||
test('a redirect on a pinned camera host stays inside the pinned directory', async () => {
|
||||
const redirectTo = (location) => async (url) =>
|
||||
url === `${BUCKET}00001.00001.jpg`
|
||||
? new Response(null, { status: 302, headers: { location } })
|
||||
: new Response('frame', { headers: { 'content-type': 'image/jpeg' } });
|
||||
for (const location of [
|
||||
'/jamcams.tfl.gov.uk.other/x.jpg',
|
||||
'/other/x.jpg',
|
||||
'/jamcams.tfl.gov.uk/../other/x.jpg',
|
||||
'/jamcams.tfl.gov.uk/%2e%2e/other/x.jpg',
|
||||
'/jamcams.tfl.gov.uk/..%2fother/x.jpg',
|
||||
])
|
||||
assert.equal(
|
||||
await fetchWithinHost(
|
||||
`${BUCKET}00001.00001.jpg`,
|
||||
{},
|
||||
redirectTo(location),
|
||||
),
|
||||
null,
|
||||
location,
|
||||
);
|
||||
const followed = await fetchWithinHost(
|
||||
`${BUCKET}00001.00001.jpg`,
|
||||
{},
|
||||
redirectTo('/jamcams.tfl.gov.uk/00001.00002.jpg'),
|
||||
);
|
||||
assert.equal(await followed.text(), 'frame');
|
||||
// A host with no pinned directory keeps the same-origin rule alone.
|
||||
const unpinned = await fetchWithinHost(
|
||||
'https://cams.example/a/frame.jpg',
|
||||
{},
|
||||
async (url) =>
|
||||
url === 'https://cams.example/a/frame.jpg'
|
||||
? new Response(null, { status: 302, headers: { location: '/b/x.jpg' } })
|
||||
: new Response('frame'),
|
||||
);
|
||||
assert.equal(await unpinned.text(), 'frame');
|
||||
});
|
||||
|
||||
test('a pin prefix without a trailing slash still names a directory', () => {
|
||||
assert.equal(
|
||||
pinnedCameraUrl('https://h.example/camsX/a.jpg', 'https://h.example/cams'),
|
||||
null,
|
||||
);
|
||||
});
|
||||
@@ -182,6 +182,86 @@ test('loader deduplicates cameras that share a camera number', async (t) => {
|
||||
]);
|
||||
});
|
||||
|
||||
test('falls back to Highway Bureau MJPEG cameras when the Freeway catalog fails', async (t) => {
|
||||
const highwayUrl = 'https://cctv-maintain.thb.gov.tw/opendataCCTVs.xml';
|
||||
const requests = [];
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url, options) => {
|
||||
const href = String(url);
|
||||
requests.push(href);
|
||||
assert.equal(options.redirect, 'manual');
|
||||
if (href === TAIWAN_FREEWAY_CCTV_URL)
|
||||
return new Response('', { status: 503 });
|
||||
if (href === highwayUrl) {
|
||||
return new Response(
|
||||
cctvXml(
|
||||
block({
|
||||
id: 'CCTV-14-0620-009-002',
|
||||
stream: 'https://cctv-ss02.thb.gov.tw:443/T62-9K+020',
|
||||
lat: '24.9967',
|
||||
lon: '121.4521',
|
||||
}),
|
||||
),
|
||||
{ headers: { 'content-type': 'application/xml' } },
|
||||
);
|
||||
}
|
||||
throw new Error('Unexpected Taiwan feed URL: ' + href);
|
||||
});
|
||||
|
||||
const sources = await loadTaiwanSources();
|
||||
|
||||
assert.deepEqual(requests, [TAIWAN_FREEWAY_CCTV_URL, highwayUrl]);
|
||||
assert.equal(sources.length, 1);
|
||||
assert.equal(sources[0].id, 'tw-thb-cctv-14-0620-009-002');
|
||||
assert.equal(sources[0].cityId, 'taiwan');
|
||||
assert.equal(sources[0].provider, 'Highway Bureau, MOTC');
|
||||
assert.equal(sources[0].feedType, 'mjpeg');
|
||||
assert.equal(sources[0].sourceKind, 'taiwan-highway-motc');
|
||||
assert.equal(new URL(sources[0].url).hostname, 'cctv-ss02.thb.gov.tw');
|
||||
assert.equal(new URL(sources[0].url).pathname, '/T62-9K+020');
|
||||
});
|
||||
|
||||
test('the Highway Bureau fallback registers only approved HTTPS camera servers', async (t) => {
|
||||
const highwayUrl = 'https://cctv-maintain.thb.gov.tw/opendataCCTVs.xml';
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
t.mock.method(globalThis, 'fetch', async (url) => {
|
||||
if (String(url) === TAIWAN_FREEWAY_CCTV_URL)
|
||||
return new Response('', { status: 503 });
|
||||
if (String(url) === highwayUrl) {
|
||||
return new Response(
|
||||
cctvXml(
|
||||
block({
|
||||
id: 'CCTV-14-0620-009-001',
|
||||
stream: 'https://cctv-ss09.thb.gov.tw/T62-9K+019',
|
||||
}),
|
||||
block({
|
||||
id: 'CCTV-14-0620-009-003',
|
||||
stream: 'http://cctv-ss02.thb.gov.tw/T62-9K+021',
|
||||
}),
|
||||
block({
|
||||
id: 'CCTV-14-0620-009-004',
|
||||
stream: 'https://cctv-ss02.thb.gov.tw:8443/T62-9K+022',
|
||||
}),
|
||||
block({
|
||||
id: 'CCTV-14-0620-009-002',
|
||||
stream: 'https://cctv-ss02.thb.gov.tw:443/T62-9K+020',
|
||||
}),
|
||||
),
|
||||
{ headers: { 'content-type': 'application/xml' } },
|
||||
);
|
||||
}
|
||||
throw new Error('Unexpected Taiwan feed URL: ' + String(url));
|
||||
});
|
||||
|
||||
const sources = await loadTaiwanSources();
|
||||
|
||||
assert.deepEqual(
|
||||
sources.map((source) => source.id),
|
||||
['tw-thb-cctv-14-0620-009-002'],
|
||||
);
|
||||
});
|
||||
test('a redirected or failed catalog contributes an empty pack', async (t) => {
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
for (const status of [302, 503]) {
|
||||
@@ -214,13 +294,17 @@ test('the Taiwan pack is in the catalog by default', async (t) => {
|
||||
);
|
||||
});
|
||||
|
||||
test('CCTV_TAIWAN_ENABLED=0 makes no Freeway Bureau request', async (t) => {
|
||||
test('CCTV_TAIWAN_ENABLED=0 makes no Taiwan catalog request', async (t) => {
|
||||
const { requested, sources } = await runCatalogWithTaiwanFlag(t, '0');
|
||||
assert.ok(requested.length > 0, 'the other packs still refreshed');
|
||||
assert.equal(
|
||||
requested.some((href) => href.includes('freeway.gov.tw')),
|
||||
false,
|
||||
);
|
||||
assert.equal(
|
||||
requested.some((href) => href.includes('cctv-maintain.thb.gov.tw')),
|
||||
false,
|
||||
);
|
||||
assert.ok(!sources.some((c) => c.cityId === 'taiwan'));
|
||||
});
|
||||
|
||||
@@ -250,12 +334,12 @@ test('a failed download is not retried until the backoff ends', async (t) => {
|
||||
t.mock.method(Date, 'now', () => 1_000_000);
|
||||
assert.deepEqual(await loadTaiwanSources(), []);
|
||||
assert.deepEqual(await loadTaiwanSources(), []);
|
||||
assert.equal(calls, 1, 'the second refresh made no request');
|
||||
assert.equal(calls, 2, 'the second refresh made no request');
|
||||
Date.now.mock.mockImplementation(
|
||||
() => 1_000_000 + TAIWAN_RETRY_AFTER_FAILURE_MS + 1,
|
||||
);
|
||||
await loadTaiwanSources();
|
||||
assert.equal(calls, 2, 'the backoff ends after an hour');
|
||||
assert.equal(calls, 4, 'the backoff ends after an hour');
|
||||
});
|
||||
|
||||
test('a failed download serves the last good table', async (t) => {
|
||||
|
||||
@@ -10,7 +10,7 @@ import {
|
||||
TORONTO_RESCU_LIST_URL,
|
||||
TORONTO_RESCU_IMAGE_ORIGIN,
|
||||
TORONTO_MAX_CATALOG_BYTES,
|
||||
DEFAULT_CCTV_MAX_SOURCES,
|
||||
CCTV_SHARED_SOURCE_SLOTS,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import { CAMERA_CODE_MAX_CHARS } from '../../server/providers/cctv/normalize.js';
|
||||
import { allocateSourceCap } from '../../server/providers/cctv/cap.js';
|
||||
@@ -418,6 +418,6 @@ test('CCTV_TORONTO_ENABLED=0 keeps the lane from being loaded at all', async (t)
|
||||
}
|
||||
});
|
||||
|
||||
test('the shipped catalog ceiling is not raised to make room for this pack', () => {
|
||||
assert.equal(DEFAULT_CCTV_MAX_SOURCES, 4000);
|
||||
test('the shared catalog slots are not raised to make room for this pack', () => {
|
||||
assert.equal(CCTV_SHARED_SOURCE_SLOTS, 4000);
|
||||
});
|
||||
@@ -0,0 +1,270 @@
|
||||
// src/data/cctvViewThinning.test.mjs — the CCTV view pass: only cameras on or
|
||||
// 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 { 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,
|
||||
} from './cctv.js';
|
||||
|
||||
const WIDTH = 800;
|
||||
const HEIGHT = 600;
|
||||
|
||||
/** 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);
|
||||
return {
|
||||
camera: {
|
||||
id: `cam-${index}`,
|
||||
name: `Camera ${index}`,
|
||||
city: 'Test',
|
||||
lat,
|
||||
lon,
|
||||
headingDeg: 0,
|
||||
pitchDeg: -18,
|
||||
fovDeg: 44,
|
||||
rangeM: 145,
|
||||
mountHeightM: 8,
|
||||
},
|
||||
position: { x: position.x, y: position.y, z: position.z },
|
||||
coverageEntities: [],
|
||||
projection: null,
|
||||
};
|
||||
});
|
||||
return { records };
|
||||
}
|
||||
|
||||
/**
|
||||
* 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,
|
||||
},
|
||||
});
|
||||
const viewer = {};
|
||||
bindings.push(
|
||||
bindRenderer(viewer, {
|
||||
camera: port,
|
||||
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
|
||||
}),
|
||||
);
|
||||
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) => icons.item(record.camera.id)?.show === true)
|
||||
.map((record) => record.camera.id)
|
||||
.sort();
|
||||
}
|
||||
|
||||
// Three cameras within ~110 m, and one ~22 km away.
|
||||
const CLUSTER = [
|
||||
[0, 0],
|
||||
[0.001, 0],
|
||||
[0.0005, 0.0005],
|
||||
[0.2, 0],
|
||||
];
|
||||
|
||||
test('zoomed out, cameras sharing a ground cell show one icon', () => {
|
||||
const { records } = recordsAt(CLUSTER);
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(20_000),
|
||||
records,
|
||||
});
|
||||
assert.equal(
|
||||
refreshHorizonCulling(),
|
||||
true,
|
||||
'the first pass changes the view',
|
||||
);
|
||||
const shown = shownIds(records);
|
||||
assert.equal(shown.length, 2, 'one for the cluster, one for the far camera');
|
||||
assert.ok(shown.includes('cam-3'), 'a camera alone in its cell shows');
|
||||
assert.deepEqual(_viewRecordIdsForTest().sort(), shown);
|
||||
});
|
||||
|
||||
test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
|
||||
const { records } = recordsAt(CLUSTER);
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(20_000),
|
||||
records,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
const before = shownIds(records);
|
||||
const list = _viewRecordIdsForTest();
|
||||
// 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, shiftM / 111_320),
|
||||
records,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
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 } = recordsAt(CLUSTER);
|
||||
const shownAt = (heightM) => {
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(heightM),
|
||||
records,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
return shownIds(records);
|
||||
};
|
||||
// Cells come in power-of-two metre steps: about 1.5 km and 1.6 km cells at
|
||||
// these heights fall in the same step, so the same cameras win.
|
||||
assert.deepEqual(shownAt(20_500), shownAt(20_000));
|
||||
});
|
||||
|
||||
test('a healthy camera wins its cell over an unknown one', () => {
|
||||
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),
|
||||
records,
|
||||
healthById: new Map([[id, { status: 'ok' }]]),
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
assert.deepEqual(shownIds(records), [id]);
|
||||
}
|
||||
});
|
||||
|
||||
test('the active camera always shows, even in a crowded cell', () => {
|
||||
const { records } = recordsAt(CLUSTER.slice(0, 3));
|
||||
for (const active of records) {
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(20_000),
|
||||
records,
|
||||
activeCameraId: active.camera.id,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
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', () => {
|
||||
// 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),
|
||||
records,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']);
|
||||
});
|
||||
|
||||
test('a disabled layer skips the view pass', () => {
|
||||
const { records } = recordsAt(CLUSTER);
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(20_000),
|
||||
records,
|
||||
enabled: false,
|
||||
});
|
||||
assert.equal(refreshHorizonCulling(), false);
|
||||
assert.deepEqual(_viewRecordIdsForTest(), []);
|
||||
});
|
||||
|
||||
test('UI state builds the full camera list only when it is read', () => {
|
||||
const { records } = recordsAt(CLUSTER.slice(0, 2));
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(300),
|
||||
records,
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
let built = 0;
|
||||
for (const record of records) {
|
||||
const camera = record.camera;
|
||||
record.camera = new Proxy(camera, {
|
||||
get(target, key) {
|
||||
if (key === 'calibration') built += 1;
|
||||
return target[key];
|
||||
},
|
||||
});
|
||||
}
|
||||
const first = cctvLayer.getUIState();
|
||||
assert.equal(built, 0, 'listeners that skip `cameras` cost nothing');
|
||||
assert.deepEqual(
|
||||
first.cameraIndex.map((camera) => camera.id),
|
||||
['cam-0', 'cam-1'],
|
||||
);
|
||||
assert.equal(
|
||||
cctvLayer.getUIState().cameraIndex,
|
||||
first.cameraIndex,
|
||||
'the index keeps its identity while the view does',
|
||||
);
|
||||
assert.equal(first.cameras.length, 2);
|
||||
assert.ok(built > 0, 'reading `cameras` builds it');
|
||||
assert.equal(first.cameras, first.cameras, 'and builds it once');
|
||||
});
|
||||
|
||||
test('the camera picker lists the view, with the active camera first', () => {
|
||||
const { records } = recordsAt([
|
||||
[0, 0],
|
||||
[0.01, 0],
|
||||
[0.0002, 0],
|
||||
]);
|
||||
_setCctvCoverageStateForTest({
|
||||
viewer: viewerAt(300),
|
||||
records,
|
||||
activeCameraId: 'cam-1',
|
||||
});
|
||||
refreshHorizonCulling();
|
||||
const state = cctvLayer.getUIState();
|
||||
assert.deepEqual(
|
||||
state.cameraIndex.map((camera) => camera.id),
|
||||
['cam-1', 'cam-0', 'cam-2'],
|
||||
'the off-screen active camera leads, then what is in view',
|
||||
);
|
||||
assert.equal(state.cameras.length, 3, 'the full list is still every camera');
|
||||
});
|
||||
+14
-56
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -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. */
|
||||
|
||||
@@ -0,0 +1,316 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
import os from 'node:os';
|
||||
import path from 'node:path';
|
||||
import {
|
||||
DEFAULT_WORLD_CCTV_SOURCE_FILE,
|
||||
WORLD_CCTV_SOURCE_COUNT,
|
||||
} from '../../server/providers/cctv/constants.js';
|
||||
import {
|
||||
isMlitRiverAdjustmentImage,
|
||||
loadWorldCameraSources,
|
||||
} from '../../server/providers/cctv/worldCameras.js';
|
||||
import {
|
||||
loadQuebecSources,
|
||||
QUEBEC_CAMERA_SOURCE_COUNT,
|
||||
quebec511VideoUrl,
|
||||
quebecBrowserVideoEnabled,
|
||||
} from '../../server/providers/cctv/quebec.js';
|
||||
import { cctvProxy } from '../../server/providers/cctv.js';
|
||||
|
||||
const REPO_ROOT = path.resolve(import.meta.dirname, '../..');
|
||||
const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0x00, 0x10, 0xff, 0xd9]);
|
||||
|
||||
/** Silence the loaders' progress and failure logging. */
|
||||
function quiet(t) {
|
||||
t.mock.method(console, 'log', () => {});
|
||||
t.mock.method(console, 'warn', () => {});
|
||||
}
|
||||
|
||||
/** Set (or, for `undefined`, delete) environment variables for one test. */
|
||||
function withEnv(t, env) {
|
||||
for (const [name, value] of Object.entries(env)) {
|
||||
const previous = process.env[name];
|
||||
t.after(() => {
|
||||
if (previous === undefined) delete process.env[name];
|
||||
else process.env[name] = previous;
|
||||
});
|
||||
if (value === undefined) delete process.env[name];
|
||||
else process.env[name] = value;
|
||||
}
|
||||
}
|
||||
|
||||
/** A temporary source root holding the given World and Québec catalogs. */
|
||||
function sourceRoot(t, { world = [], quebec = null } = {}) {
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-cctv-world-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
const worldFile = path.join(root, DEFAULT_WORLD_CCTV_SOURCE_FILE);
|
||||
fs.mkdirSync(path.dirname(worldFile), { recursive: true });
|
||||
fs.writeFileSync(worldFile, JSON.stringify(world));
|
||||
if (quebec) {
|
||||
fs.mkdirSync(path.join(root, 'public'), { recursive: true });
|
||||
fs.writeFileSync(
|
||||
path.join(root, 'public/quebec-cameras.json'),
|
||||
JSON.stringify({ cameras: quebec }),
|
||||
);
|
||||
}
|
||||
return root;
|
||||
}
|
||||
|
||||
const oregonRow = (overrides = {}) => ({
|
||||
id: 'world-or-764',
|
||||
name: '3rd St at Harwood MP18.35',
|
||||
provider: 'TripCheck (ODOT)',
|
||||
lat: 44.3029,
|
||||
lon: -120.8549,
|
||||
sourceKind: 'tripcheck-odot',
|
||||
url: 'https://www.tripcheck.com/roadcams/cams/Harwood_pid3527.jpg',
|
||||
snapshotUrl: 'https://www.tripcheck.com/roadcams/cams/Harwood_pid3527.jpg',
|
||||
...overrides,
|
||||
});
|
||||
|
||||
test('the shipped World catalog loads every curated row', (t) => {
|
||||
quiet(t);
|
||||
const sources = loadWorldCameraSources({ sourceRoot: REPO_ROOT });
|
||||
assert.equal(sources.length, WORLD_CCTV_SOURCE_COUNT);
|
||||
const byKind = Object.groupBy(sources, (source) => source.sourceKind);
|
||||
// Iceland comes from the live Iceland pack, never a second World copy.
|
||||
assert.equal(byKind['vegagerdin-road'], undefined);
|
||||
assert.equal(byKind['tripcheck-odot'].length, 1176);
|
||||
assert.equal(byKind['mlit-river'].length, 1054);
|
||||
for (const source of byKind['mlit-river'])
|
||||
assert.equal(source.frameRefreshMs, 10 * 60 * 1000);
|
||||
});
|
||||
|
||||
test('the World loader accepts a pinned row and rejects anything outside its policy', (t) => {
|
||||
quiet(t);
|
||||
const rejected = [
|
||||
['unknown kind', { sourceKind: 'nzta-journeys' }],
|
||||
[
|
||||
'Iceland duplicates the Iceland pack',
|
||||
{
|
||||
sourceKind: 'vegagerdin-road',
|
||||
lat: 64.291877,
|
||||
lon: -15.028035,
|
||||
url: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/almannaskard_1.jpg',
|
||||
snapshotUrl: 'https://www.vegagerdin.is/vgdata/vefmyndavelar/almannaskard_1.jpg',
|
||||
},
|
||||
],
|
||||
['wrong id prefix', { id: 'world-jp-river-7075' }],
|
||||
['outside bounds', { lat: 40, lon: -15 }],
|
||||
['other host', { url: 'https://evil.test/roadcams/cams/a.jpg' }],
|
||||
['other directory', { url: 'https://www.tripcheck.com/other/a.jpg' }],
|
||||
['query string', { url: oregonRow().url + '?x=1' }],
|
||||
['not a jpg', { url: 'https://www.tripcheck.com/roadcams/cams/a.png' }],
|
||||
['plain http', { url: oregonRow().url.replace('https:', 'http:') }],
|
||||
[
|
||||
'url and snapshot differ',
|
||||
{ snapshotUrl: 'https://www.tripcheck.com/roadcams/cams/b.jpg' },
|
||||
],
|
||||
];
|
||||
const root = sourceRoot(t, {
|
||||
world: [
|
||||
oregonRow(),
|
||||
oregonRow(), // duplicate id
|
||||
...rejected.map(([, overrides], i) =>
|
||||
oregonRow({ id: `world-or-${9000 + i}`, ...overrides }),
|
||||
),
|
||||
],
|
||||
});
|
||||
const sources = loadWorldCameraSources({ sourceRoot: root });
|
||||
assert.deepEqual(
|
||||
sources.map((source) => source.id),
|
||||
['world-or-764'],
|
||||
);
|
||||
assert.equal(sources[0].frameRefreshMs, 5 * 60 * 1000);
|
||||
assert.equal(sources[0].feedType, 'image');
|
||||
});
|
||||
|
||||
test('the World loader fails soft on a missing or malformed catalog', (t) => {
|
||||
quiet(t);
|
||||
const root = fs.mkdtempSync(path.join(os.tmpdir(), 'gev-cctv-world-'));
|
||||
t.after(() => fs.rmSync(root, { recursive: true, force: true }));
|
||||
assert.deepEqual(loadWorldCameraSources({ sourceRoot: root }), []);
|
||||
const file = path.join(root, DEFAULT_WORLD_CCTV_SOURCE_FILE);
|
||||
fs.mkdirSync(path.dirname(file), { recursive: true });
|
||||
fs.writeFileSync(file, '{not json');
|
||||
assert.deepEqual(loadWorldCameraSources({ sourceRoot: root }), []);
|
||||
});
|
||||
|
||||
test('only the exact MLIT adjustment image is recognised', () => {
|
||||
assert.equal(isMlitRiverAdjustmentImage({ ok: true, body: JPEG }), false);
|
||||
assert.equal(isMlitRiverAdjustmentImage(null), false);
|
||||
assert.equal(isMlitRiverAdjustmentImage({ ok: false, body: JPEG }), false);
|
||||
});
|
||||
|
||||
test('the shipped Québec catalog loads every location', (t) => {
|
||||
quiet(t);
|
||||
const sources = loadQuebecSources({ sourceRoot: REPO_ROOT });
|
||||
assert.equal(sources.length, QUEBEC_CAMERA_SOURCE_COUNT);
|
||||
for (const source of sources) {
|
||||
assert.equal(source.url, '', 'the server never fetches Québec media');
|
||||
assert.equal(source.snapshotUrl, '');
|
||||
}
|
||||
});
|
||||
|
||||
test('the Québec loader maps ids by kind, keeps https viewer links, and splits the MTQ credit', (t) => {
|
||||
quiet(t);
|
||||
const at = { lat: 45.51651, lon: -73.5502 };
|
||||
const root = sourceRoot(t, {
|
||||
quebec: [
|
||||
{ id: '3735', kind: 'traffic', name: 'Route 136', viewerUrl: 'https://www.quebec511.info/Carte/Fenetres/FenetreVideo.html?id=3735', ...at },
|
||||
{ id: 'mtl-465', kind: 'montreal', name: 'Montréal 465', viewerUrl: 'http://ville.montreal.qc.ca/x', ...at },
|
||||
{ id: 'web-1', kind: 'webcam', name: 'Tremblant', operator: 'Station Mont-Tremblant', viewerUrl: 'https://user:[email protected]/', ...at },
|
||||
{ id: 'abc', kind: 'traffic', ...at }, // non-numeric traffic id
|
||||
{ id: '3735', kind: 'traffic', ...at }, // duplicate
|
||||
{ id: '9', kind: 'traffic', lat: 40, lon: -73.5 }, // outside Québec
|
||||
],
|
||||
});
|
||||
const sources = loadQuebecSources({ sourceRoot: root });
|
||||
const byId = new Map(sources.map((source) => [source.id, source]));
|
||||
assert.deepEqual([...byId.keys()], ['qc-511-3735', 'qc-mtl-465', 'qc-web-1']);
|
||||
|
||||
const mtq = byId.get('qc-511-3735');
|
||||
assert.equal(mtq.sourceKind, 'quebec-511-browser');
|
||||
assert.match(mtq.credit, /Locations: MTQ · CC BY 4\.0/);
|
||||
assert.match(mtq.credit, /Video: Québec 511/);
|
||||
assert.doesNotMatch(mtq.license, /^Données Québec \/ MTQ, CC BY 4\.0$/);
|
||||
assert.equal(byId.get('qc-mtl-465').sourceUrl, '', 'http viewer links are dropped');
|
||||
assert.equal(byId.get('qc-web-1').sourceUrl, '', 'credentialed links are dropped');
|
||||
assert.equal(
|
||||
quebec511VideoUrl('qc-511-3735'),
|
||||
'https://www.quebec511.info/Carte/Fenetres/camera.ashx?id=3735&format=mp4',
|
||||
);
|
||||
assert.equal(quebec511VideoUrl('qc-mtl-465'), '');
|
||||
});
|
||||
|
||||
test('Québec 511 browser video is opt-in', () => {
|
||||
assert.equal(quebecBrowserVideoEnabled({}), false);
|
||||
assert.equal(quebecBrowserVideoEnabled({ CCTV_QUEBEC_VIDEO_ENABLED: '0' }), false);
|
||||
assert.equal(quebecBrowserVideoEnabled({ CCTV_QUEBEC_VIDEO_ENABLED: ' 1 ' }), true);
|
||||
});
|
||||
|
||||
/** Mount the real proxy with a fixed fetch, and drive requests through it. */
|
||||
function mount(t, root, respond) {
|
||||
withEnv(t, {
|
||||
CCTV_SOURCES_FILE: 'absent-source-file.json',
|
||||
CCTV_SOURCES_JSON: undefined,
|
||||
CCTV_FORCE_AUSTIN: '0',
|
||||
CCTV_MAX_SOURCES: undefined,
|
||||
// A configured key makes any Street View fallback observable.
|
||||
GOOGLE_MAPS_SERVER_API_KEY: 'test-google-key',
|
||||
});
|
||||
const requests = [];
|
||||
t.mock.method(globalThis, 'fetch', async (url, init = {}) => {
|
||||
requests.push(String(url));
|
||||
return respond(String(url), init) || new Response('down', { status: 503 });
|
||||
});
|
||||
let handler;
|
||||
cctvProxy({ sourceRoot: root }).configureServer({
|
||||
middlewares: {
|
||||
use(_route, fn) {
|
||||
handler = fn;
|
||||
},
|
||||
},
|
||||
});
|
||||
const call = async (url) => {
|
||||
const res = {
|
||||
writeHead(status, headers) {
|
||||
Object.assign(this, { status, headers });
|
||||
},
|
||||
end(body) {
|
||||
this.body = body;
|
||||
},
|
||||
on() {},
|
||||
once() {},
|
||||
};
|
||||
await handler({ url, method: 'GET', headers: {}, on() {} }, res);
|
||||
return res;
|
||||
};
|
||||
return { call, requests };
|
||||
}
|
||||
|
||||
test('/sources lists Québec browser media only when the operator opts in', async (t) => {
|
||||
quiet(t);
|
||||
const root = sourceRoot(t, {
|
||||
quebec: [{ id: '3735', kind: 'traffic', name: 'Route 136', lat: 45.5, lon: -73.5 }],
|
||||
});
|
||||
withEnv(t, { CCTV_QUEBEC_VIDEO_ENABLED: undefined });
|
||||
const app = mount(t, root, () => null);
|
||||
const off = JSON.parse((await app.call('/sources')).body).sources;
|
||||
assert.equal(off.find((s) => s.id === 'qc-511-3735').browserMediaUrl, '');
|
||||
|
||||
process.env.CCTV_QUEBEC_VIDEO_ENABLED = '1';
|
||||
const on = JSON.parse((await app.call('/sources')).body).sources;
|
||||
assert.match(on.find((s) => s.id === 'qc-511-3735').browserMediaUrl, /camera\.ashx\?id=3735&format=mp4$/);
|
||||
});
|
||||
|
||||
test('a World frame is fetched once per refresh floor and the cooldown never spends Street View', async (t) => {
|
||||
quiet(t);
|
||||
const root = sourceRoot(t, { world: [oregonRow()] });
|
||||
let answer = () => new Response(JPEG, { headers: { 'content-type': 'image/jpeg' } });
|
||||
const app = mount(t, root, (url) =>
|
||||
url === oregonRow().url ? answer() : null,
|
||||
);
|
||||
const frame = '/frame/world-or-764';
|
||||
const upstreamHits = () =>
|
||||
app.requests.filter((url) => url === oregonRow().url).length;
|
||||
|
||||
const first = await app.call(frame);
|
||||
assert.equal(first.headers['X-CCTV-Source'], 'upstream-image');
|
||||
const second = await app.call(frame);
|
||||
assert.equal(second.headers['X-CCTV-Source'], 'upstream-image');
|
||||
assert.equal(upstreamHits(), 1, 'the second view reuses the cached frame');
|
||||
|
||||
// A camera whose first fetch fails is inside its failure backoff: it gets
|
||||
// the placeholder, not Google Street View, and no second upstream request.
|
||||
const failRoot = sourceRoot(t, { world: [oregonRow()] });
|
||||
answer = () => new Response('down', { status: 503 });
|
||||
const failing = mount(t, failRoot, (url) =>
|
||||
url === oregonRow().url ? answer() : null,
|
||||
);
|
||||
const failed = await failing.call(frame);
|
||||
assert.notEqual(failed.headers['X-CCTV-Source'], 'upstream-image');
|
||||
const retry = await failing.call(frame);
|
||||
assert.equal(retry.headers['X-CCTV-Source'], 'synthetic');
|
||||
assert.equal(
|
||||
failing.requests.filter((url) => url === oregonRow().url).length,
|
||||
1,
|
||||
'the backoff holds the provider cadence',
|
||||
);
|
||||
assert.equal(
|
||||
failing.requests.filter((url) => url.includes('maps.googleapis.com/maps/api/streetview')).length,
|
||||
1,
|
||||
'only the first miss, outside any cooldown, may try Street View',
|
||||
);
|
||||
});
|
||||
|
||||
test('Ottawa frames are signed with the certificate at fetch time only', async (t) => {
|
||||
quiet(t);
|
||||
const root = sourceRoot(t);
|
||||
withEnv(t, { OTTAWA_CAMERA_CERTIFICATE: 'CERT123' });
|
||||
const app = mount(t, root, (url) => {
|
||||
if (url === 'https://traffic.ottawa.ca/map/service/camera')
|
||||
return Response.json({
|
||||
cameras: [
|
||||
{ camera_number: 16, name: 'Bank & Hunt Club', latitude: 45.35, longitude: -75.65, cameraOwner: 'CITY' },
|
||||
],
|
||||
});
|
||||
if (url.startsWith('https://traffic.ottawa.ca/opendata/camera'))
|
||||
return new Response(JPEG, { headers: { 'content-type': 'image/jpeg' } });
|
||||
return null;
|
||||
});
|
||||
const sources = JSON.parse((await app.call('/sources')).body).sources;
|
||||
const ottawa = sources.find((source) => source.id === 'ottawa-16');
|
||||
assert.ok(ottawa);
|
||||
assert.doesNotMatch(JSON.stringify(sources), /CERT123/, 'no catalog field carries the certificate');
|
||||
|
||||
const frame = await app.call('/frame/ottawa-16');
|
||||
assert.equal(frame.headers['X-CCTV-Source'], 'upstream-image');
|
||||
await app.call('/frame/ottawa-16');
|
||||
const hits = app.requests.filter((url) => url.includes('/opendata/camera'));
|
||||
assert.deepEqual(hits, [
|
||||
'https://traffic.ottawa.ca/opendata/camera?c=16&certificate=CERT123&id=gev',
|
||||
], 'one signed request per camera per minute');
|
||||
});
|
||||
@@ -2,7 +2,6 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import { dispatchCockpitModeChanged, enter, exit, _adoptTrackedEntity } from '../ui/cockpitTrackingController.js';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import * as Cesium from 'cesium';
|
||||
import flightsLayer, {
|
||||
_setCockpitDetectionSubjectForTest as setFlightsCockpitSubject,
|
||||
@@ -28,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: {
|
||||
@@ -49,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: {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
/**
|
||||
* Cockpit 3D aircraft policy.
|
||||
@@ -13,6 +13,11 @@ import { readFileSync } from 'node:fs';
|
||||
* 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) },
|
||||
@@ -29,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');
|
||||
});
|
||||
|
||||
@@ -54,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');
|
||||
@@ -62,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\(/);
|
||||
});
|
||||
@@ -181,7 +181,7 @@ export function trimTrack(track, nowMs, keep = track.capacity) {
|
||||
for (const id of track.epochs.keys())
|
||||
if (!used.has(id)) track.epochs.delete(id);
|
||||
}
|
||||
export function validFix(fix) {
|
||||
function validFix(fix) {
|
||||
return (
|
||||
Number.isFinite(fix?.t) &&
|
||||
fix.t >= 0 &&
|
||||
|
||||
+199
-214
@@ -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,
|
||||
};
|
||||
|
||||
@@ -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),
|
||||
),
|
||||
);
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 } };
|
||||
}
|
||||
@@ -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);
|
||||
});
|
||||
@@ -115,7 +115,8 @@ test('status retains official clocks, knots, source links and finite current pos
|
||||
assert.equal(storm.issuedAt, TIME);
|
||||
assert.equal(storm.positionAt, TIME);
|
||||
assert.deepEqual(storm.position, { longitude: -125.8, latitude: 15.5 });
|
||||
assert.deepEqual(storm.movement, { directionDegrees: 255, speedKt: 12 });
|
||||
// NHC publishes movementSpeed in mph: 12 mph is 10 kt.
|
||||
assert.deepEqual(storm.movement, { directionDegrees: 255, speedKt: 10 });
|
||||
assert.equal(storm.windKt, 25);
|
||||
assert.equal(storm.pressureHpa, 1006);
|
||||
assert.match(storm.advisoryUrl, /^https:\/\/www\.nhc\.noaa\.gov\/text\//);
|
||||
|
||||
+350
-57
@@ -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.
|
||||
@@ -34,8 +35,30 @@ export const OPENMAPTILES_CREDIT = {
|
||||
html: 'Vector tiles: <a href="https://openfreemap.org" target="_blank" rel="noopener">OpenFreeMap</a> © <a href="https://openmaptiles.org" target="_blank" rel="noopener">OpenMapTiles</a>',
|
||||
};
|
||||
|
||||
/** Conditional Salish Sea coverage; registered when its sightings first render. */
|
||||
export const ACARTIA_CREDIT = Object.freeze({
|
||||
key: 'acartia',
|
||||
html:
|
||||
'Wildlife sightings: <a href="https://acartia.io" target="_blank" rel="noopener">Acartia</a> (CC BY 4.0; each provider credited per sighting) · ' +
|
||||
'<a href="https://www.bewhalewise.org" target="_blank" rel="noopener">Be Whale Wise</a>',
|
||||
});
|
||||
|
||||
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;
|
||||
@@ -44,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;
|
||||
@@ -126,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:
|
||||
@@ -135,10 +162,23 @@ export const DATA_CREDITS = [
|
||||
{
|
||||
key: 'celestrak',
|
||||
html:
|
||||
'Satellites (TLEs): CelesTrak ' +
|
||||
'Satellites (TLEs and SATCAT): CelesTrak ' +
|
||||
'(<a href="https://celestrak.org" target="_blank" rel="noopener">celestrak.org</a>), ' +
|
||||
'Dr. T.S. Kelso',
|
||||
},
|
||||
{
|
||||
key: 'ucs-satellite-database',
|
||||
html:
|
||||
'Satellite operators and purposes: ' +
|
||||
'<a href="https://www.ucsusa.org/satellite_database" target="_blank" rel="noopener">UCS Satellite Database</a> ' +
|
||||
'(UCS-Satellite-Database 5-1-2023), Union of Concerned Scientists',
|
||||
},
|
||||
{
|
||||
key: 'imaging-sensors',
|
||||
html:
|
||||
'Imaging sensor swaths: operator and agency specifications, ' +
|
||||
'cited per platform',
|
||||
},
|
||||
{
|
||||
key: 'launch-library-2',
|
||||
html:
|
||||
@@ -150,6 +190,20 @@ export const DATA_CREDITS = [
|
||||
key: 'usgs',
|
||||
html: 'Earthquakes: Data courtesy of the U.S. Geological Survey',
|
||||
},
|
||||
{
|
||||
key: 'openseamap',
|
||||
html:
|
||||
'Sea marks overlay: ' +
|
||||
'<a href="https://www.openseamap.org" target="_blank" rel="noopener">© OpenSeaMap contributors</a> (CC BY-SA 2.0) · ' +
|
||||
'Data © OpenStreetMap contributors (ODbL)',
|
||||
},
|
||||
{
|
||||
key: 'opensnowmap',
|
||||
html:
|
||||
'Ski pistes overlay: ' +
|
||||
'<a href="https://www.opensnowmap.org" target="_blank" rel="noopener">© www.opensnowmap.org</a> (CC BY-SA) · ' +
|
||||
'Data © OpenStreetMap contributors (ODbL)',
|
||||
},
|
||||
{
|
||||
key: 'nasa-gibs',
|
||||
html:
|
||||
@@ -167,6 +221,17 @@ export const DATA_CREDITS = [
|
||||
' · Incident information: ' +
|
||||
'<a href="https://inciweb.wildfire.gov/" target="_blank" rel="noopener">InciWeb</a>',
|
||||
},
|
||||
{
|
||||
key: 'faa-sua',
|
||||
html:
|
||||
'Prohibited & restricted airspace: ' +
|
||||
'<a href="https://adds-faa.opendata.arcgis.com/" target="_blank" rel="noopener">FAA Special Use Airspace</a>' +
|
||||
' (prohibited and restricted zones; informational only)',
|
||||
},
|
||||
{
|
||||
key: 'inaturalist',
|
||||
html: 'Wildlife sightings: <a href="https://www.inaturalist.org" target="_blank" rel="noopener">iNaturalist</a> contributors (licences per record; photos credited on each card)',
|
||||
},
|
||||
OSM_CREDIT,
|
||||
OPENMAPTILES_CREDIT,
|
||||
{
|
||||
@@ -266,6 +331,38 @@ export const DATA_CREDITS = [
|
||||
'CCTV static data (MOTC 2.0), released under the ' +
|
||||
'<a href="https://data.gov.tw/license" target="_blank" rel="noopener">Open Government Data License, Taiwan (Version 1.0)</a>',
|
||||
},
|
||||
{
|
||||
key: 'ottawa-cctv',
|
||||
html:
|
||||
'Traffic cameras (Ottawa, with an access certificate): ' +
|
||||
'<a href="https://traffic.ottawa.ca/en/traffic-map-data-lists-and-resources/about-the-data" target="_blank" rel="noopener">City of Ottawa Traffic Camera Images API</a>',
|
||||
},
|
||||
{
|
||||
key: 'quebec-cctv',
|
||||
html:
|
||||
'Camera locations (Québec): Ministère des Transports et de la Mobilité durable via ' +
|
||||
'<a href="https://www.donneesquebec.ca/" target="_blank" rel="noopener">Données Québec</a> ' +
|
||||
'(<a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>); ' +
|
||||
'Montréal camera locations © OpenStreetMap contributors (ODbL). ' +
|
||||
'Video (when enabled) and linked webcam pages stay with ' +
|
||||
'<a href="https://www.quebec511.info/" target="_blank" rel="noopener">Québec 511</a> and each operator, under their own terms',
|
||||
},
|
||||
{
|
||||
key: 'tripcheck-cctv',
|
||||
html:
|
||||
'Road camera stills (Oregon): camera courtesy of ODOT, via ' +
|
||||
'<a href="https://www.tripcheck.com/" target="_blank" rel="noopener">TripCheck</a>; ' +
|
||||
'partner cameras (counties, cities, Caltrans, WSDOT) are named in the camera label',
|
||||
},
|
||||
{
|
||||
key: 'mlit-river-cctv',
|
||||
html:
|
||||
'River camera stills (Japan): 出典:国土交通省 ' +
|
||||
'<a href="https://www.river.go.jp/" target="_blank" rel="noopener">川の防災情報</a> ' +
|
||||
'(Ministry of Land, Infrastructure, Transport and Tourism; ' +
|
||||
'<a href="https://www.river.go.jp/kawabou/kwb_apend/html/caution.html" target="_blank" rel="noopener">terms</a>), ' +
|
||||
'fetched on view, at most every ten minutes per camera',
|
||||
},
|
||||
{
|
||||
key: 'calgary-cctv',
|
||||
html:
|
||||
@@ -288,6 +385,15 @@ export const DATA_CREDITS = [
|
||||
'(Llicència oberta d’ús d’informació - Catalunya); some cameras are supplied by partners ' +
|
||||
'(Ajuntament de Barcelona, Ajuntament de Terrassa), each named in the CCTV panel',
|
||||
},
|
||||
{
|
||||
key: 'iceland-cctv',
|
||||
html:
|
||||
'CCTV cameras & frames (Iceland): road camera images, fetched live, from the ' +
|
||||
'<a href="https://www.vegagerdin.is/" target="_blank" rel="noopener">Icelandic Road and Coastal Administration (Vegagerðin)</a> — ' +
|
||||
'<a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a> ' +
|
||||
'(<a href="https://www.vegagerdin.is/vegagerdin/gagnasafn/vefthjonustur/terms-and-conditions" target="_blank" rel="noopener">terms</a>); ' +
|
||||
'no endorsement by IRCA is implied',
|
||||
},
|
||||
{
|
||||
key: 'kingcounty-cctv',
|
||||
html:
|
||||
@@ -297,6 +403,14 @@ export const DATA_CREDITS = [
|
||||
'<a href="https://kingcounty.gov/en/dept/kcit/data-information-services/gis-center/about/terms-conditions-copyrights" target="_blank" rel="noopener">KCGIS Center terms</a>. ' +
|
||||
'Partner-city cameras hosted on the county image handler (e.g. Newcastle) name their owner in the CCTV panel.',
|
||||
},
|
||||
{
|
||||
key: 'houston-cctv',
|
||||
html:
|
||||
'CCTV cameras & frames (Houston, when enabled): ' +
|
||||
'<a href="https://traffic.houstontranstar.org/cctv/transtar/" target="_blank" rel="noopener">Houston TranStar</a>. ' +
|
||||
"Copying, distributing or framing its images needs TxDOT's written permission under the " +
|
||||
'<a href="https://traffic.houstontranstar.org/disclaimer.aspx" target="_blank" rel="noopener">TranStar Content Usage terms</a>',
|
||||
},
|
||||
{
|
||||
key: 'hk-cctv',
|
||||
html:
|
||||
@@ -304,6 +418,14 @@ export const DATA_CREDITS = [
|
||||
'<a href="https://data.gov.hk/en-data/dataset/hk-td-tis_2-traffic-snapshot-images" target="_blank" rel="noopener">Transport Department / DATA.GOV.HK</a> ' +
|
||||
'(<a href="https://data.gov.hk/en/terms-and-conditions" target="_blank" rel="noopener">Terms of Use</a> — attribution required)',
|
||||
},
|
||||
{
|
||||
key: 'webcamromania-cctv',
|
||||
html:
|
||||
'Giroc camera (when configured): ' +
|
||||
'<a href="https://webcamromania.ro/webcam-orase/webcam-giroc/" target="_blank" rel="noopener">Webcam Romania</a>. ' +
|
||||
'Video rights remain with the camera operator; ' +
|
||||
'<a href="https://webcamromania.ro/termeni-si-conditii/" target="_blank" rel="noopener">provider terms</a> apply.',
|
||||
},
|
||||
{
|
||||
key: 'vegvesen-cctv',
|
||||
html:
|
||||
@@ -343,6 +465,13 @@ export const DATA_CREDITS = [
|
||||
key: 'panoramax',
|
||||
html: 'Street Level: imagery © <a href="https://panoramax.fr" target="_blank" rel="noopener">Panoramax</a> contributors, licence per picture',
|
||||
},
|
||||
{
|
||||
key: 'a22-cctv',
|
||||
html:
|
||||
'Motorway webcams (A22 Brennero–Modena): images © ' +
|
||||
'<a href="https://www.autobrennero.it/" target="_blank" rel="noopener">Autostrada del Brennero S.p.A.</a>, ' +
|
||||
'camera list via the <a href="https://opendatahub.com/" target="_blank" rel="noopener">Open Data Hub</a> (NOI Techpark)',
|
||||
},
|
||||
{
|
||||
key: 'gbfs',
|
||||
html:
|
||||
@@ -386,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:
|
||||
@@ -429,6 +562,13 @@ export const DATA_CREDITS = [
|
||||
'ECMWF does not accept any liability whatsoever for any error or omission in the data, their availability, or for any loss or damage arising from their use.',
|
||||
},
|
||||
// ── Bundled snapshots ───────────────────────────────────────────
|
||||
{
|
||||
key: 'sky-background',
|
||||
html:
|
||||
'Stars: <a href="https://cdsarc.cds.unistra.fr/viz-bin/cat/V/50" target="_blank" rel="noopener">Yale Bright Star Catalogue</a> ' +
|
||||
'(Hoffleit & Warren, via CDS). Milky Way: <a href="https://www.eso.org/public/images/eso0932a/" target="_blank" rel="noopener">ESO/S. Brunier</a> ' +
|
||||
'(<a href="https://creativecommons.org/licenses/by/4.0/" target="_blank" rel="noopener">CC BY 4.0</a>; stars removed, blurred and reprojected)',
|
||||
},
|
||||
{
|
||||
key: 'dams',
|
||||
html: 'Dams: Open Infrastructure Map',
|
||||
@@ -441,6 +581,46 @@ export const DATA_CREDITS = [
|
||||
'(<a href="https://earthdata.nasa.gov/firms" target="_blank" rel="noopener">earthdata.nasa.gov/firms</a>), ' +
|
||||
'part of NASA’s Earth Observing System Data and Information System (EOSDIS)',
|
||||
},
|
||||
{
|
||||
key: 's2-ghostmaps',
|
||||
html:
|
||||
'S2 GhostMaps intel products: S2 Underground © by S2A1, ' +
|
||||
'<a href="https://github.com/s2underground/GhostMaps" target="_blank" rel="noopener">github.com/s2underground/GhostMaps</a>, ' +
|
||||
'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’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:
|
||||
@@ -507,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 = {
|
||||
@@ -516,36 +705,99 @@ export const NATURAL_EARTH_CREDIT = {
|
||||
'<a href="https://www.naturalearthdata.com" target="_blank" rel="noopener">Natural Earth</a> (public domain)',
|
||||
};
|
||||
|
||||
/** Registered when the first bundled US county outline resolves (public
|
||||
* domain — credited as a courtesy). */
|
||||
/** 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 = {
|
||||
key: 'us-census-counties',
|
||||
html:
|
||||
'US county boundaries from the ' +
|
||||
'US county and place boundaries from the ' +
|
||||
'<a href="https://www.census.gov/geographies/mapping-files/time-series/geo/cartographic-boundary.html" target="_blank" rel="noopener">U.S. Census Bureau</a> (public domain)',
|
||||
};
|
||||
|
||||
/** Registered when the first bundled Who's On First neighborhood outline
|
||||
* resolves. The link leads to the pack's per-source credits and licences and
|
||||
* says how the boundaries were modified. */
|
||||
export const WOF_CREDIT = {
|
||||
key: 'wof-neighborhoods',
|
||||
html:
|
||||
'Neighborhood boundaries: ' +
|
||||
'<a href="https://whosonfirst.org/docs/licenses/" target="_blank" rel="noopener">Who\'s On First</a> and contributors, simplified (' +
|
||||
'<a href="https://github.com/bilawalsidhu/gods-eye-view/blob/main/src/data/local_data/wof_neighborhoods/ATTRIBUTION.md" target="_blank" rel="noopener">sources and licences</a>)',
|
||||
};
|
||||
|
||||
/** Registered when a voice place search (a configured Overpass) first shows places. */
|
||||
export const OSM_PLACES_CREDIT = {
|
||||
key: 'osm-places',
|
||||
html:
|
||||
'Places found by voice: ' +
|
||||
'<a href="https://www.openstreetmap.org/copyright" target="_blank" rel="noopener">© OpenStreetMap contributors</a> ' +
|
||||
'(ODbL 1.0)',
|
||||
};
|
||||
|
||||
/**
|
||||
* Per-feed transit credit, registered the first time that feed's vehicles
|
||||
* render (see `src/data/transitFeeds.js` for the license of each).
|
||||
* @param {{ id: string, attribution: string, license: string, licenseUrl: string }} feed
|
||||
*
|
||||
* Two optional registry fields serve licences that ask for more than a name:
|
||||
* `sourceUrl` links the attribution to the publisher (Warsaw asks for a link
|
||||
* to its API), and `creditDated` adds the UTC date of the data, from the feed
|
||||
* header or else the fetch time (Warsaw and Poznań ask for the download or
|
||||
* update date). A dated credit is keyed by its date, so a new day registers a
|
||||
* new line instead of keeping yesterday's.
|
||||
* @param {{ id: string, attribution: string, license: string, licenseUrl: string,
|
||||
* sourceUrl?: string, creditDated?: boolean }} feed
|
||||
* @param {{ feedTimestamp?: number|null, fetchedAt?: number|null }} [snapshot]
|
||||
* `feedTimestamp` in epoch seconds, `fetchedAt` in epoch ms.
|
||||
* @returns {{ key: string, html: string }}
|
||||
*/
|
||||
export function transitFeedCredit(feed) {
|
||||
export function transitFeedCredit(feed, snapshot = null) {
|
||||
const escape = (text) =>
|
||||
String(text)
|
||||
.replaceAll('&', '&')
|
||||
.replaceAll('<', '<')
|
||||
.replaceAll('>', '>')
|
||||
.replaceAll('"', '"');
|
||||
const source = feed.sourceUrl
|
||||
? `<a href="${escape(feed.sourceUrl)}" target="_blank" rel="noopener">${escape(feed.attribution)}</a>`
|
||||
: escape(feed.attribution);
|
||||
const dataMs = Number.isFinite(snapshot?.feedTimestamp)
|
||||
? snapshot.feedTimestamp * 1000
|
||||
: snapshot?.fetchedAt;
|
||||
const date =
|
||||
feed.creditDated === true && Number.isFinite(dataMs) && dataMs > 0
|
||||
? new Date(dataMs).toISOString().slice(0, 10)
|
||||
: null;
|
||||
return {
|
||||
key: `transit-${feed.id}`,
|
||||
key: date ? `transit-${feed.id}-${date}` : `transit-${feed.id}`,
|
||||
html:
|
||||
`Transit (${escape(feed.attribution)}): ` +
|
||||
`Transit (${source}${date ? `, data of ${date}` : ''}): ` +
|
||||
`<a href="${escape(feed.licenseUrl)}" target="_blank" rel="noopener">${escape(feed.license)}</a>`,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* 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',
|
||||
@@ -565,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);
|
||||
}
|
||||
@@ -1,6 +1,13 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { DATA_CREDITS, NYC_DOT_DISCLAIMER } from './dataCredits.js';
|
||||
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);
|
||||
@@ -38,6 +45,43 @@ 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.
|
||||
const credit = DATA_CREDITS.find(
|
||||
(entry) => entry.key === 'ucs-satellite-database',
|
||||
);
|
||||
assert.ok(credit, 'the satellite classes and operators come from UCS');
|
||||
assert.match(credit.html, /UCS-Satellite-Database 5-1-2023/);
|
||||
assert.match(
|
||||
credit.html,
|
||||
/href="https:\/\/www\.ucsusa\.org\/satellite_database"/,
|
||||
);
|
||||
});
|
||||
|
||||
test('the imaging sensor swaths credit operator and agency specifications', () => {
|
||||
// Each sensor-pack entry cites its operator's or agency's own pages;
|
||||
// no aggregator database is credited.
|
||||
const credit = DATA_CREDITS.find((entry) => entry.key === 'imaging-sensors');
|
||||
assert.ok(credit, 'the orbital zoom caps come from the sensor pack');
|
||||
assert.match(credit.html, /operator and agency specifications/);
|
||||
assert.doesNotMatch(credit.html, /OSCAR|wmo\.int/);
|
||||
});
|
||||
|
||||
test('OpenStreetMap has one generic data credit with separate tile and names distributors', () => {
|
||||
const osm = DATA_CREDITS.filter((entry) =>
|
||||
entry.html.includes('openstreetmap.org/copyright'),
|
||||
@@ -60,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);
|
||||
@@ -100,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();
|
||||
@@ -129,6 +173,18 @@ test('the NYC camera credit carries NYC DOT’s requested disclaimer', () => {
|
||||
assert.match(credit.html, /observe posted signage/);
|
||||
});
|
||||
|
||||
test("the Houston camera credit names TranStar's terms and the permission they require", () => {
|
||||
const credit = DATA_CREDITS.find((entry) => entry.key === 'houston-cctv');
|
||||
assert.ok(credit, 'Houston TranStar camera frames must be credited');
|
||||
assert.match(credit.html, /\(Houston, when enabled\)/);
|
||||
assert.ok(
|
||||
credit.html.includes(
|
||||
'href="https://traffic.houstontranstar.org/disclaimer.aspx"',
|
||||
),
|
||||
);
|
||||
assert.match(credit.html, /TxDOT's written permission/);
|
||||
});
|
||||
|
||||
test('every Street Level imagery source is in the attribution lightbox', () => {
|
||||
for (const key of [
|
||||
'mapillary',
|
||||
@@ -141,3 +197,170 @@ test('every Street Level imagery source is in the attribution lightbox', () => {
|
||||
`${key} has no credit`,
|
||||
);
|
||||
});
|
||||
|
||||
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 & 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/);
|
||||
assert.match(html('quebec-cctv') || '', /CC BY 4\.0/);
|
||||
assert.match(html('quebec-cctv') || '', /OpenStreetMap contributors/);
|
||||
assert.match(html('tripcheck-cctv') || '', /courtesy of ODOT/);
|
||||
// MLIT's terms ask for the source in this form, with the page link.
|
||||
assert.match(html('mlit-river-cctv') || '', /出典:国土交通省/);
|
||||
assert.match(
|
||||
html('mlit-river-cctv') || '',
|
||||
/href="https:\/\/www\.river\.go\.jp\//,
|
||||
);
|
||||
});
|
||||
|
||||
test('Warsaw and Poznań credits carry the data date their licences ask for', () => {
|
||||
const warsaw = getTransitFeed('ztm-warszawa');
|
||||
// 2026-11-09T06:00:00Z as a GTFS-RT header timestamp (seconds).
|
||||
const credit = transitFeedCredit(warsaw, { feedTimestamp: 1_794_204_000 });
|
||||
assert.match(credit.html, /, data of 2026-11-09\)/);
|
||||
assert.match(credit.html, /href="http:\/\/api\.um\.warszawa\.pl"/);
|
||||
assert.equal(credit.key, 'transit-ztm-warszawa-2026-11-09');
|
||||
// Without a feed timestamp the fetch time is the download date.
|
||||
const poznan = transitFeedCredit(getTransitFeed('ztm-poznan'), {
|
||||
feedTimestamp: null,
|
||||
fetchedAt: Date.UTC(2026, 10, 10, 12),
|
||||
});
|
||||
assert.match(poznan.html, /data of 2026-11-10/);
|
||||
// Undated feeds keep one credit line for the session.
|
||||
const mbta = transitFeedCredit(getTransitFeed('mbta'), {
|
||||
feedTimestamp: 1_794_204_000,
|
||||
});
|
||||
assert.equal(mbta.key, 'transit-mbta');
|
||||
assert.doesNotMatch(mbta.html, /data of/);
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
+203
-17
@@ -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,
|
||||
@@ -43,17 +45,24 @@ import {
|
||||
detectionHorizontalSector,
|
||||
labelBudgetFor,
|
||||
normalizeAllocationStrategy,
|
||||
normalizeProfile,
|
||||
profileForDensity,
|
||||
viewScaleForAltitude,
|
||||
} from './detectionPolicy.js';
|
||||
import { detectionBracketOpacity } from './detectionPresentation.js';
|
||||
import { SurfaceOcclusion } from './detectionOcclusion.js';
|
||||
import { rendererOf } from '../render/rendererOf.js';
|
||||
import {
|
||||
createCyberSonarSampler,
|
||||
cyberSonarFrameDelay,
|
||||
isCyberContactSonarActive as isCyberSonarActive,
|
||||
isCyberContactThemeActive as isCyberMapThemeActive,
|
||||
} from '../cyberSonar.js';
|
||||
import {
|
||||
awarenessEchoActive,
|
||||
awarenessEchoBracket,
|
||||
awarenessEchoColor,
|
||||
getAwarenessEchoField,
|
||||
} from '../awarenessEcho.js';
|
||||
|
||||
/**
|
||||
* @module detection
|
||||
@@ -102,8 +111,12 @@ 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. */
|
||||
const ECHO_ALPHA_STEPS = 8;
|
||||
/** Stable per-layer candidate safety cap; independent of density and camera bearing. */
|
||||
const LAYER_CANDIDATE_CAP = 2600;
|
||||
const LAYER_WEIGHTS = Object.freeze({
|
||||
@@ -190,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. */
|
||||
@@ -256,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;
|
||||
@@ -281,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.
|
||||
*/
|
||||
@@ -294,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 : '',
|
||||
);
|
||||
@@ -350,7 +408,6 @@ export function destroyDetection() {
|
||||
_calloutLane = null;
|
||||
_transitBracketPaths.clear();
|
||||
_calloutCount = 0;
|
||||
_viewer = null;
|
||||
_layers = [];
|
||||
_onModeChange = null;
|
||||
_hostCanvas = null;
|
||||
@@ -360,6 +417,9 @@ export function destroyDetection() {
|
||||
_suspended = false;
|
||||
_suspendReason = '';
|
||||
_labelArbiter.clear();
|
||||
_surfaceOcclusion.clear();
|
||||
_surfaceSuppressedKeys.clear();
|
||||
_useOcclusionProbe(null);
|
||||
_lastLabelSolveAt = 0;
|
||||
_labelSolveDirty = true;
|
||||
_lastDiagnostics = null;
|
||||
@@ -569,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;
|
||||
}
|
||||
|
||||
@@ -684,6 +745,9 @@ function _applyModeState() {
|
||||
_syncSurfaceVisibility();
|
||||
_setLanesActive(false);
|
||||
_labelArbiter.clear();
|
||||
_surfaceOcclusion.clear();
|
||||
_surfaceSuppressedKeys.clear();
|
||||
_occlusionProbe.reset();
|
||||
_lastLabelSolveAt = 0;
|
||||
_labelSolveDirty = true;
|
||||
_lastSolveSnapshot = {
|
||||
@@ -1070,6 +1134,9 @@ function _stashCallout(entry, acquireFade, keyhole) {
|
||||
font: FONT,
|
||||
microFont: MICRO_FONT,
|
||||
alpha: 1,
|
||||
cardSourceId: '',
|
||||
cardEntryId: '',
|
||||
paintAlpha: 1,
|
||||
};
|
||||
_calloutPool[_calloutCount] = row;
|
||||
}
|
||||
@@ -1096,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++;
|
||||
}
|
||||
|
||||
@@ -1127,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;
|
||||
}
|
||||
@@ -1144,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,
|
||||
@@ -1204,6 +1290,8 @@ function _materializeCandidate(
|
||||
primary,
|
||||
micro,
|
||||
hasMicro: card.hasMicro,
|
||||
cardSourceId: obj.cardSourceId ? String(obj.cardSourceId) : '',
|
||||
cardEntryId: obj.cardEntryId ? String(obj.cardEntryId) : '',
|
||||
};
|
||||
}
|
||||
|
||||
@@ -1266,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,
|
||||
@@ -1309,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
|
||||
@@ -1336,6 +1425,11 @@ function _drawOverlay(frame) {
|
||||
const tiers = _theme.tiers || null;
|
||||
const colorFor = (key) => (tiers && tiers[key]) || _theme.line;
|
||||
const bracketPaths = new Map();
|
||||
// Global Context sonar echoes: a second bracket, banded by strength, around
|
||||
// each flight or vessel a pulse front has just crossed.
|
||||
// Resting pulses light nothing, so the per-contact echo work is skipped.
|
||||
const echoField = awarenessEchoActive(now) ? getAwarenessEchoField() : null;
|
||||
const echoPaths = echoField ? new Array(ECHO_ALPHA_STEPS + 1) : null;
|
||||
const pathFor = (map, color, alpha) => {
|
||||
const band = Math.max(
|
||||
1,
|
||||
@@ -1390,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,
|
||||
@@ -1414,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);
|
||||
@@ -1438,6 +1558,24 @@ function _drawOverlay(frame) {
|
||||
halfH,
|
||||
);
|
||||
visibleCount++;
|
||||
if (echoPaths) {
|
||||
// Starts on the contact's bracket and spreads outward as it fades.
|
||||
const echo = awarenessEchoBracket(
|
||||
obj._layerId,
|
||||
obj.position,
|
||||
now,
|
||||
bracketAlpha,
|
||||
ECHO_ALPHA_STEPS,
|
||||
);
|
||||
if (echo)
|
||||
appendCornerBracket(
|
||||
(echoPaths[echo.band] ??= new Path2D()),
|
||||
sx,
|
||||
sy,
|
||||
halfW + echo.spreadPx,
|
||||
halfH + echo.spreadPx,
|
||||
);
|
||||
}
|
||||
if (obj.type === 'AIR')
|
||||
aircraftBracketSectors[detectionHorizontalSector(sx, width)]++;
|
||||
if (bracketAlpha >= 1) bracketOpacityCounts.full++;
|
||||
@@ -1496,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,
|
||||
@@ -1506,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,
|
||||
@@ -1577,8 +1724,40 @@ function _drawOverlay(frame) {
|
||||
_ctx.stroke(entry.path);
|
||||
}
|
||||
}
|
||||
if (echoPaths) {
|
||||
_ctx.lineWidth = echoField.echo.lineWidth;
|
||||
_ctx.strokeStyle = awarenessEchoColor(
|
||||
_theme.line,
|
||||
_theme === THEME_MAP._default,
|
||||
);
|
||||
for (let band = 1; band <= ECHO_ALPHA_STEPS; band++) {
|
||||
if (!echoPaths[band]) continue;
|
||||
_ctx.globalAlpha =
|
||||
fade * (band / ECHO_ALPHA_STEPS) * bracketPresentationOpacity;
|
||||
_ctx.stroke(echoPaths[band]);
|
||||
}
|
||||
_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
|
||||
@@ -1633,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;
|
||||
|
||||
@@ -0,0 +1,107 @@
|
||||
// src/data/detectionAwarenessEcho.test.mjs — Global Context sonar echoes pulse
|
||||
// a contact's own detection bracket: a second bracket that starts on it and
|
||||
// spreads outward as it fades, in the detection style's own colour.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
awarenessEchoBracket,
|
||||
awarenessEchoColor,
|
||||
clearAwarenessEchoField,
|
||||
setAwarenessEchoField,
|
||||
} from '../awarenessEcho.js';
|
||||
import { DETECTION_THEME_MAP } from '../overlays/worldOverlayTokens.js';
|
||||
|
||||
const STEPS = 8;
|
||||
const pulse = { count: 3, periodMs: 9000, startFraction: 0.02 };
|
||||
const echo = {
|
||||
fadeMs: 1400,
|
||||
layerIds: ['flights', 'military', 'ais-live-vessels'],
|
||||
spreadPx: 8,
|
||||
color: 'rgb(98, 181, 255)',
|
||||
};
|
||||
const center = Cesium.Cartesian3.fromDegrees(3, 27, 0);
|
||||
const field = { center, radiusM: 250_000, pulse, echo };
|
||||
|
||||
/** The moment pulse 0's front reaches the ground under `position`. */
|
||||
function arrivalAt(position) {
|
||||
const ground = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface(position);
|
||||
const d = Cesium.Cartesian3.distance(center, ground);
|
||||
return (
|
||||
((d / 250_000 - pulse.startFraction) / (1 - pulse.startFraction)) *
|
||||
pulse.periodMs +
|
||||
pulse.periodMs * 3
|
||||
);
|
||||
}
|
||||
|
||||
test('the echo bracket pulses outward from the contact bracket and fades', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
setAwarenessEchoField(field);
|
||||
const position = Cesium.Cartesian3.fromDegrees(3.5, 27, 10_000);
|
||||
const arrival = arrivalAt(position);
|
||||
const at = (nowMs, bracketAlpha = 1) =>
|
||||
awarenessEchoBracket('flights', position, nowMs, bracketAlpha, STEPS);
|
||||
|
||||
// The moment the front arrives: on the bracket, strongest band.
|
||||
const fresh = at(arrival);
|
||||
assert.ok(fresh);
|
||||
assert.ok(Math.abs(fresh.spreadPx) < 0.01, `${fresh.spreadPx}`);
|
||||
assert.equal(fresh.band, STEPS);
|
||||
// Half way through the fade: dimmer and spread outward, but not past
|
||||
// the field's spread.
|
||||
const half = at(arrival + echo.fadeMs / 2);
|
||||
assert.ok(half.spreadPx > echo.spreadPx * 0.5);
|
||||
assert.ok(half.spreadPx < echo.spreadPx);
|
||||
assert.ok(half.band < STEPS && half.band >= 1);
|
||||
// The bracket's own dimming (keyhole fade, sonar sweep) carries
|
||||
// over, and the echo is never drawn brighter than its bracket: a bracket
|
||||
// too dim for even one band draws no echo.
|
||||
assert.equal(at(arrival, 0.25).band, 2);
|
||||
assert.equal(at(arrival, 0.05), null);
|
||||
for (let alpha = 0.05; alpha <= 1; alpha += 0.05) {
|
||||
const echoed = at(arrival + echo.fadeMs / 3, alpha);
|
||||
if (echoed)
|
||||
assert.ok(
|
||||
echoed.band / STEPS <= alpha + 0.5 / STEPS + 1e-9,
|
||||
`band ${echoed.band} for a bracket at ${alpha}`,
|
||||
);
|
||||
}
|
||||
// Faded out, or between fronts: no echo bracket.
|
||||
assert.equal(at(arrival + echo.fadeMs + 5), null);
|
||||
});
|
||||
|
||||
test('no echo field, or a layer that does not echo, draws nothing extra', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
const position = Cesium.Cartesian3.fromDegrees(3.01, 27, 0);
|
||||
clearAwarenessEchoField();
|
||||
for (let now = 0; now < pulse.periodMs; now += 25)
|
||||
assert.equal(
|
||||
awarenessEchoBracket('flights', position, now, 1, STEPS),
|
||||
null,
|
||||
);
|
||||
setAwarenessEchoField(field);
|
||||
for (let now = 0; now < pulse.periodMs; now += 25)
|
||||
for (const layerId of ['cctv', 'satellites', 'traffic'])
|
||||
assert.equal(
|
||||
awarenessEchoBracket(layerId, position, now, 1, STEPS),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test('echoes take the detection style colour except on the default style', (t) => {
|
||||
t.after(clearAwarenessEchoField);
|
||||
assert.equal(
|
||||
awarenessEchoColor(DETECTION_THEME_MAP._default.line, true),
|
||||
null,
|
||||
);
|
||||
setAwarenessEchoField(field);
|
||||
assert.equal(
|
||||
awarenessEchoColor(DETECTION_THEME_MAP._default.line, true),
|
||||
echo.color,
|
||||
);
|
||||
// CRT, NVG and FLIR keep their monochrome palettes.
|
||||
for (const style of ['retro', 'surveillance', 'thermal']) {
|
||||
const { line } = DETECTION_THEME_MAP[style];
|
||||
assert.equal(awarenessEchoColor(line, false), line, style);
|
||||
}
|
||||
});
|
||||
@@ -18,7 +18,7 @@ export function stableIdentityHash(layerId, sourceId) {
|
||||
}
|
||||
|
||||
/** Negative means a is a better deterministic contender than b. */
|
||||
export function compareCohortContenders(a, b) {
|
||||
function compareCohortContenders(a, b) {
|
||||
const priorityDelta =
|
||||
(Number(b?._cohortPriority) || 0) - (Number(a?._cohortPriority) || 0);
|
||||
if (priorityDelta) return priorityDelta;
|
||||
|
||||
@@ -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,11 +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([
|
||||
@@ -50,8 +70,9 @@ class MockEvent {
|
||||
}
|
||||
|
||||
class MockPath2D {
|
||||
moveTo() {}
|
||||
lineTo() {}
|
||||
constructor() { this.points = []; }
|
||||
moveTo(x, y) { this.points.push([x, y]); }
|
||||
lineTo(x, y) { this.points.push([x, y]); }
|
||||
roundRect() {}
|
||||
arcTo() {}
|
||||
closePath() {}
|
||||
@@ -98,7 +119,7 @@ function mockContext(target, trace) {
|
||||
// set at some point during the frame. globalAlpha rides along for the same
|
||||
// reason: the backdrop feather is an alpha, not a colour.
|
||||
fill(path) { record('fill', path, this.fillStyle, this.globalAlpha); },
|
||||
stroke(path) { record('stroke', path, this.strokeStyle, this.lineWidth); },
|
||||
stroke(path) { record('stroke', path, this.strokeStyle, this.lineWidth, this.globalAlpha); },
|
||||
fillRect(...args) { record('fillRect', ...args); },
|
||||
fillText(...args) { record('fillText', ...args); },
|
||||
drawImage(...args) { record('drawImage', ...args); },
|
||||
@@ -246,6 +267,7 @@ function installEnvironment({ width = 800, height = 600, dpr = 2, search = '' }
|
||||
},
|
||||
scene: { postRender, requestRender() {} },
|
||||
};
|
||||
bindOverlayPorts(viewer);
|
||||
|
||||
return {
|
||||
viewer,
|
||||
@@ -536,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
|
||||
@@ -574,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
|
||||
@@ -627,6 +840,231 @@ test('surveillance military tier reaches the dedicated render target as shipped
|
||||
}
|
||||
});
|
||||
|
||||
test('Global Context echo brackets reach the canvas in the detection style colour', () => {
|
||||
const env = installEnvironment();
|
||||
// Fronts every millisecond with a long fade, so the contact is lit on
|
||||
// whatever frame paints; a distinctive width picks the echo stroke out.
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
const echoStrokes = () =>
|
||||
env.detectionCtx.calls
|
||||
.filter(([name, , , width]) => name === 'stroke' && width === echo.lineWidth)
|
||||
.map(([, , style]) => style);
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [militaryLayer()], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
assert.ok(echoStrokes().length > 0, 'the echo bracket is painted');
|
||||
assert.ok(echoStrokes().every((style) => style === echo.color));
|
||||
|
||||
// CRT, NVG and FLIR keep their own palettes.
|
||||
for (const style of ['retro', 'surveillance', 'thermal']) {
|
||||
env.detectionCtx.calls.length = 0;
|
||||
setDetectionStyle(style);
|
||||
settleFrame(env);
|
||||
const strokes = echoStrokes();
|
||||
assert.ok(strokes.length > 0, style);
|
||||
assert.ok(
|
||||
strokes.every((stroke) => stroke === DETECTION_THEME_MAP[style].line),
|
||||
`${style} echoes take the style line colour, got ${strokes}`,
|
||||
);
|
||||
}
|
||||
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a Global Context echo bracket is drawn outside its contact bracket and dimmer than it', () => {
|
||||
const env = installEnvironment();
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
// Fronts every millisecond keep the echo at full strength; a level of 0.5
|
||||
// halves it, so it sits 4 px out and draws at half the bracket's alpha.
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
level: () => 0.5,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [militaryLayer()], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
env.detectionCtx.calls.length = 0;
|
||||
settleFrame(env);
|
||||
const strokes = env.detectionCtx.calls.filter(([name]) => name === 'stroke');
|
||||
const echoStroke = strokes.find(([, , style, width]) => style === echo.color && width === echo.lineWidth);
|
||||
assert.ok(echoStroke, 'the echo bracket is painted');
|
||||
const bracketStroke = strokes.find(([, path, style, width]) =>
|
||||
path instanceof MockPath2D && path.points.length && width !== echo.lineWidth && style !== echo.color);
|
||||
assert.ok(bracketStroke, 'the contact bracket is painted');
|
||||
const extent = (path) => {
|
||||
const xs = path.points.map(([x]) => x);
|
||||
const ys = path.points.map(([, y]) => y);
|
||||
return { halfW: (Math.max(...xs) - Math.min(...xs)) / 2, halfH: (Math.max(...ys) - Math.min(...ys)) / 2 };
|
||||
};
|
||||
const echoBox = extent(echoStroke[1]);
|
||||
const bracketBox = extent(bracketStroke[1]);
|
||||
assert.ok(Math.abs(echoBox.halfW - bracketBox.halfW - echo.spreadPx / 2) < 1e-3,
|
||||
`echo ${echoBox.halfW} vs bracket ${bracketBox.halfW}`);
|
||||
assert.ok(Math.abs(echoBox.halfH - bracketBox.halfH - echo.spreadPx / 2) < 1e-3);
|
||||
const echoAlpha = echoStroke[4];
|
||||
const bracketAlpha = bracketStroke[4];
|
||||
assert.ok(echoAlpha > 0 && echoAlpha < bracketAlpha, `${echoAlpha} vs ${bracketAlpha}`);
|
||||
assert.ok(Math.abs(echoAlpha - bracketAlpha / 2) < 1e-6, `${echoAlpha} vs ${bracketAlpha}`);
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('under the sonar sweep an echo is never brighter than its own bracket', () => {
|
||||
const env = installEnvironment();
|
||||
// Sonar on with its HUD open turns the contact sonar on; its sweep dims
|
||||
// brackets it is not passing over.
|
||||
env.document.documentElement = {
|
||||
// The lowest sweep floor, so dimmed brackets drop a whole alpha band.
|
||||
dataset: { cyberSonar: 'on', cyberSonarOpacity: '35' },
|
||||
style: { setProperty() {}, removeProperty() {} },
|
||||
};
|
||||
const hud = env.document.createElement('div');
|
||||
hud.id = 'intel-hud';
|
||||
hud.classList = { contains: (name) => name === 'active' };
|
||||
env.document.body.appendChild(hud);
|
||||
const echo = {
|
||||
layerIds: ['military'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
};
|
||||
const contact = {
|
||||
id: 'military',
|
||||
getDetectableObjects: () => [{
|
||||
position: new Cesium.Cartesian3(0.5, 0.3, 6_356_752),
|
||||
sourceId: 'sonar-pin',
|
||||
id: 'SONAR',
|
||||
metric: 'FL300',
|
||||
type: 'AIR',
|
||||
tier: 'military',
|
||||
}],
|
||||
};
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo,
|
||||
level: () => 1,
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [contact], () => {});
|
||||
setMode('DENSE');
|
||||
setDetectionStyle('normal');
|
||||
settleFrame(env);
|
||||
let dimmed = 0;
|
||||
let compared = 0;
|
||||
for (let frame = 0; frame < 40; frame++) {
|
||||
env.detectionCtx.calls.length = 0;
|
||||
settleFrame(env);
|
||||
const strokes = env.detectionCtx.calls.filter(([name]) => name === 'stroke');
|
||||
const echoStroke = strokes.find(([, , style, width]) => style === echo.color && width === echo.lineWidth);
|
||||
const bracketStroke = strokes.find(([, path, style, width]) =>
|
||||
path instanceof MockPath2D && path.points.length && width !== echo.lineWidth && style !== echo.color);
|
||||
if (!bracketStroke) continue;
|
||||
const bracketAlpha = bracketStroke[4];
|
||||
if (bracketAlpha < 0.99) dimmed++;
|
||||
if (!echoStroke) continue;
|
||||
compared++;
|
||||
assert.ok(
|
||||
echoStroke[4] <= bracketAlpha + 1e-9,
|
||||
`echo ${echoStroke[4]} over bracket ${bracketAlpha} on frame ${frame}`,
|
||||
);
|
||||
}
|
||||
assert.ok(dimmed > 0, 'the sweep dimmed the bracket on some frame');
|
||||
assert.ok(compared > 0, 'an echo was painted');
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('resting Global Context pulses skip echo work for the whole frame, not per contact', () => {
|
||||
const env = installEnvironment();
|
||||
// Six echo-eligible flights on screen; the identity camera maps x/y
|
||||
// straight to device coordinates.
|
||||
const flights = Array.from({ length: 6 }, (_, index) => ({
|
||||
position: new Cesium.Cartesian3(-0.5 + index * 0.2, 0, 6_356_752),
|
||||
sourceId: `flight-${index}`,
|
||||
id: `ECHO${index}`,
|
||||
metric: `FL${300 + index}`,
|
||||
type: 'AIR',
|
||||
}));
|
||||
const layer = { id: 'flights', getDetectableObjects: () => flights };
|
||||
let levelCalls = 0;
|
||||
try {
|
||||
setAwarenessEchoField({
|
||||
center: Cesium.Cartesian3.fromDegrees(0, 89, 0),
|
||||
radiusM: 250_000,
|
||||
pulse: { count: 1000, periodMs: 1000, startFraction: 0 },
|
||||
echo: {
|
||||
layerIds: ['flights'],
|
||||
fadeMs: 60_000,
|
||||
color: 'rgb(1, 2, 3)',
|
||||
spreadPx: 8,
|
||||
lineWidth: 3.25,
|
||||
},
|
||||
level: () => {
|
||||
levelCalls++;
|
||||
return 0;
|
||||
},
|
||||
});
|
||||
initWorldOverlay(env.viewer);
|
||||
initDetection(env.viewer, [layer], () => {});
|
||||
setMode('DENSE');
|
||||
settleFrame(env);
|
||||
levelCalls = 0;
|
||||
settleFrame(env);
|
||||
const painted = getDetectionDiagnostics().visibleCount;
|
||||
assert.equal(painted, flights.length, 'every flight is on screen');
|
||||
// One check per painted frame, however many contacts are on screen.
|
||||
assert.ok(levelCalls >= 1, 'the frame asks whether echoes are live');
|
||||
assert.ok(levelCalls < painted, `${levelCalls} level checks for ${painted} contacts`);
|
||||
assert.ok(
|
||||
!env.detectionCtx.calls.some(
|
||||
([name, , style]) => name === 'stroke' && style === 'rgb(1, 2, 3)',
|
||||
),
|
||||
'no echoes while the pulses rest',
|
||||
);
|
||||
} finally {
|
||||
clearAwarenessEchoField();
|
||||
env.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('pathological detection paint holds alternate frames without freezing shared lanes', () => {
|
||||
// Opts into the telemetry banner: the held-frame assertions count banner paints.
|
||||
const env = installEnvironment({ search: '?detectDebug=1' });
|
||||
@@ -960,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();
|
||||
}
|
||||
});
|
||||
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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`);
|
||||
});
|
||||
@@ -5,7 +5,6 @@
|
||||
* module so density cannot drift into contradictory mode semantics again.
|
||||
*/
|
||||
|
||||
export const DENSITY_STOPS = Object.freeze([0, 25, 50, 75, 100]);
|
||||
export const ALLOCATION_ELASTIC = 'ELASTIC';
|
||||
export const ALLOCATION_WEIGHTED = 'WEIGHTED';
|
||||
export const ALLOCATION_STRATEGIES = Object.freeze([
|
||||
@@ -118,7 +117,7 @@ export function detectionHorizontalSector(screenX, viewportWidth) {
|
||||
return 'front';
|
||||
}
|
||||
|
||||
export const VIEW_SCALE_BUDGETS = Object.freeze({
|
||||
const VIEW_SCALE_BUDGETS = Object.freeze({
|
||||
street: Object.freeze({ 0: 9, 25: 23, 50: 45, 75: 68, 100: 90 }),
|
||||
city: Object.freeze({ 0: 7, 25: 18, 50: 35, 75: 53, 100: 70 }),
|
||||
metro: Object.freeze({ 0: 6, 25: 14, 50: 28, 75: 41, 100: 55 }),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { expandApplicationHtml } from '../../build/application-html.js';
|
||||
import { renderApplicationHtml } from '../testSupport/applicationHtml.mjs';
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import fs from 'node:fs';
|
||||
@@ -19,7 +19,7 @@ import {
|
||||
} from './detectionPolicy.js';
|
||||
import { KEYHOLE_OUTSIDE_OPACITY_DEFAULT } from '../celestialRing.js';
|
||||
|
||||
const indexHtml = expandApplicationHtml(fs.readFileSync(new URL('../../index.html', import.meta.url), 'utf8'));
|
||||
const indexHtml = await renderApplicationHtml(fs.readFileSync(new URL('../../index.html', import.meta.url), 'utf8'));
|
||||
|
||||
test('side aircraft brackets stay readable without changing zero-opacity intent', () => {
|
||||
assert.equal(detectionBracketAlpha('AIR', 0), 0);
|
||||
|
||||
+8
-16
@@ -4,34 +4,30 @@ 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';
|
||||
import { createDirectionsLayer } from '../layers/directions/index.js';
|
||||
|
||||
/** The shared scene owners every Directions instance runs on. */
|
||||
export const directionsServices = Object.freeze({
|
||||
const directionsServices = Object.freeze({
|
||||
credits,
|
||||
render,
|
||||
sprites,
|
||||
picking,
|
||||
scenePick,
|
||||
overlays,
|
||||
annotations,
|
||||
camera,
|
||||
ground,
|
||||
input,
|
||||
@@ -49,15 +45,12 @@ export {
|
||||
DIRECTIONS_MODES,
|
||||
DIRECTIONS_POINTER_OWNER,
|
||||
DIRECTIONS_ROUTE_COLOR,
|
||||
DIRECTIONS_STEP_OVERLAY_SOURCE_ID,
|
||||
DIRECTIONS_STEP_OVERLAY_SOURCE_OPTIONS,
|
||||
FLIGHT_PROGRESS_MS,
|
||||
POINTER_TOOL_EXITS,
|
||||
STEP_ANCHOR_DEADLINE_MS,
|
||||
STEP_ANCHOR_FAST_ATTEMPTS,
|
||||
STEP_ANCHOR_RETRY_MS,
|
||||
STEP_ANCHOR_SLOW_RETRY_MS,
|
||||
createDirectionsLayer,
|
||||
DIRECTIONS_MARKER_OVERLAY_SOURCE_ID,
|
||||
createDirectionsMarkerOverlayEntry,
|
||||
createDirectionsStepOverlayEntry,
|
||||
directionsRequestUrl,
|
||||
directionsRowControls,
|
||||
@@ -66,7 +59,6 @@ export {
|
||||
directionsStepList,
|
||||
normalizeDirectionsParams,
|
||||
normalizeRoutePayload,
|
||||
pointerBlockedMessage,
|
||||
stepAnchorDelayMs,
|
||||
stepIndexAtDistance,
|
||||
stepMarkerHeightM,
|
||||
|
||||
+247
-101
@@ -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,
|
||||
@@ -27,6 +28,8 @@ import {
|
||||
createApplicationDirectionsLayer,
|
||||
} from './directions.js';
|
||||
import { GROUND_FLOOR_LIFT_M } from './groundFloor.js';
|
||||
import { isOwnedByOtherLayer, setClickCardHitTest } from './pickRegistry.js';
|
||||
import { fakeInput } from '../input/testDoubles.mjs';
|
||||
import { instructionFor } from './routeSteps.js';
|
||||
import { setLocale } from '../i18n/index.js';
|
||||
import {
|
||||
@@ -437,12 +440,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 });
|
||||
@@ -470,6 +467,65 @@ function ownershipFixture(t) {
|
||||
});
|
||||
}
|
||||
|
||||
// Directions owns its route, markers and steps while enabled: none of them
|
||||
// is empty space to other layers.
|
||||
test('enabled, directions owns its picks', (t) => {
|
||||
ownershipFixture(t);
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => null,
|
||||
canvas: { clientWidth: 100, clientHeight: 100 },
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
t.after(() => input.destroy());
|
||||
directionsLayer.enable(viewer);
|
||||
try {
|
||||
for (const id of [
|
||||
'directions:route',
|
||||
'directions:marker:a',
|
||||
'directions:step:3',
|
||||
])
|
||||
assert.equal(isOwnedByOtherLayer('earthquakes', id), true, id);
|
||||
} finally {
|
||||
directionsLayer.disable(viewer);
|
||||
}
|
||||
assert.equal(isOwnedByOtherLayer('earthquakes', 'directions:route'), false);
|
||||
});
|
||||
|
||||
// The card or label painted on top takes the click: directions does not even
|
||||
// pick under another layer's card, so no step is selected or cleared there.
|
||||
test("another layer's card over directions keeps the click", (t) => {
|
||||
ownershipFixture(t);
|
||||
let picks = 0;
|
||||
const viewer = {
|
||||
scene: {
|
||||
pick: () => {
|
||||
picks++;
|
||||
return null;
|
||||
},
|
||||
canvas: { clientWidth: 100, clientHeight: 100 },
|
||||
},
|
||||
};
|
||||
const input = fakeInput(viewer);
|
||||
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
|
||||
setClickCardHitTest(() => top);
|
||||
t.after(() => {
|
||||
setClickCardHitTest(null);
|
||||
input.destroy();
|
||||
});
|
||||
directionsLayer.enable(viewer);
|
||||
try {
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
|
||||
top = null;
|
||||
input.tap({ x: 10, y: 10 });
|
||||
assert.ok(picks > 0, 'open map: the click reaches the scene');
|
||||
} finally {
|
||||
directionsLayer.disable(viewer);
|
||||
}
|
||||
});
|
||||
|
||||
test('placing an endpoint takes the pointer, and every exit path gives it back', (t) => {
|
||||
ownershipFixture(t);
|
||||
|
||||
@@ -514,37 +570,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 +623,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 +782,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',
|
||||
@@ -846,9 +842,15 @@ test('route numbers follow the page language and never break from their unit', (
|
||||
t.after(() => setLocale('en'));
|
||||
assert.equal(routeDistanceText(8.4), '8\u00a0m');
|
||||
assert.equal(routeDistanceText(236), '240\u00a0m');
|
||||
assert.equal(routeDistanceText(994), '990\u00a0m');
|
||||
assert.equal(routeDistanceText(996), '1.0\u00a0km');
|
||||
assert.equal(routeDistanceText(1500), '1.5\u00a0km');
|
||||
assert.equal(routeDistanceText(9940), '9.9\u00a0km');
|
||||
assert.equal(routeDistanceText(9960), '10\u00a0km');
|
||||
assert.equal(routeDistanceText(2_345_000), '2345\u00a0km');
|
||||
assert.equal(routeDurationText(39), '39\u00a0s');
|
||||
assert.equal(routeDurationText(59.4), '59\u00a0s');
|
||||
assert.equal(routeDurationText(59.6), '1\u00a0min');
|
||||
assert.equal(routeDurationText(3900), '1\u00a0h\u00a05\u00a0min');
|
||||
assert.equal(routeDurationText(7200), '2\u00a0h');
|
||||
assert.equal(routeDistanceText(-1), '');
|
||||
@@ -871,4 +873,148 @@ test('route numbers follow the page language and never break from their unit', (
|
||||
);
|
||||
const list = directionsStepList({ route });
|
||||
assert.equal(list.items[1].lead, '240\u00a0м');
|
||||
|
||||
// Japanese unit words follow the number: 1時間5分, but 1.5 km.
|
||||
setLocale('ja');
|
||||
assert.equal(routeDistanceText(1500), '1.5\u00a0km');
|
||||
assert.equal(routeDurationText(39), '39秒');
|
||||
assert.equal(routeDurationText(3900), '1時間5分');
|
||||
assert.equal(routeDurationText(7200), '2時間');
|
||||
});
|
||||
|
||||
test('ramp and lane wording stays localized after choosing the maneuver form', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const cases = [
|
||||
[
|
||||
'ru',
|
||||
'Въезжайте по съезду плавно налево на I-95',
|
||||
'Сверните на съезд резко направо',
|
||||
'Займите левую полосу',
|
||||
],
|
||||
[
|
||||
'es',
|
||||
'Toma la rampa ligeramente a la izquierda hacia I-95',
|
||||
'Toma la salida bruscamente a la derecha',
|
||||
'Toma el carril izquierdo',
|
||||
],
|
||||
[
|
||||
'ja',
|
||||
'ランプを斜め左に進んでI-95に入る',
|
||||
'出口を急角度で右に出る',
|
||||
'左車線を通行',
|
||||
],
|
||||
[
|
||||
'zh-CN',
|
||||
'向左前方驶入匝道,进入 I-95',
|
||||
'从出口向右后方驶出',
|
||||
'使用左转车道',
|
||||
],
|
||||
];
|
||||
for (const [locale, ramp, exit, lane] of cases) {
|
||||
setLocale(locale);
|
||||
assert.equal(
|
||||
directionsInstruction({
|
||||
type: 'on ramp',
|
||||
modifier: 'slight left',
|
||||
name: 'I-95',
|
||||
}),
|
||||
ramp,
|
||||
);
|
||||
assert.equal(
|
||||
directionsInstruction({ type: 'off ramp', modifier: 'sharp right' }),
|
||||
exit,
|
||||
);
|
||||
assert.equal(
|
||||
directionsInstruction({ type: 'use lane', modifier: 'sharp left' }),
|
||||
lane,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test('the reroute tooltip keeps German mode nouns capitalized', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const title = (id) =>
|
||||
directionsRowControls(idle).chips.find((chip) => chip.id === id).title;
|
||||
assert.equal(title('mode-foot'), 'Walk — reroute for walk');
|
||||
setLocale('de');
|
||||
assert.equal(
|
||||
title('mode-foot'),
|
||||
'Zu Fuß – Route im Modus „Zu Fuß“ neu berechnen',
|
||||
);
|
||||
assert.equal(
|
||||
title('mode-bike'),
|
||||
'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));
|
||||
});
|
||||
@@ -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;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -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');
|
||||
});
|
||||
@@ -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();
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
/**
|
||||
* Kilometre decimals for a distance: one below 10 km, none from there on.
|
||||
* The cut is taken on the tenth that prints, so 9.96 km reads 10 km, not 10.0.
|
||||
* @param {number} meters
|
||||
* @returns {0|1}
|
||||
*/
|
||||
export function kilometreDigits(meters) {
|
||||
return Math.round(meters / 100) < 100 ? 1 : 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* The unit and precision a distance prints with: metres below 1 km, then
|
||||
* kilometres with `kilometreDigits`. Metres round to `metreStep` (10 for tens),
|
||||
* except below `exactBelowM`, where they stay whole. Each cut is taken after
|
||||
* rounding, so 999.6 m reads 1.0 km rather than 1000 m.
|
||||
* @param {number} meters
|
||||
* @param {{metreStep?: number, exactBelowM?: number}} [options]
|
||||
* @returns {{value: number, unit: 'm'|'km', digits: 0|1}|null} null for a
|
||||
* distance that is negative or not finite. The value is already rounded to
|
||||
* `digits`, so toFixed and Intl render it the same way.
|
||||
*/
|
||||
export function distanceParts(meters, { metreStep = 1, exactBelowM = 0 } = {}) {
|
||||
if (!Number.isFinite(meters) || meters < 0) return null;
|
||||
const step = meters < exactBelowM ? 1 : metreStep;
|
||||
const shownMeters = Math.round(meters / step) * step;
|
||||
if (shownMeters < 1000) return { value: shownMeters, unit: 'm', digits: 0 };
|
||||
const digits = kilometreDigits(meters);
|
||||
const value =
|
||||
digits === 1 ? Math.round(meters / 100) / 10 : Math.round(meters / 1000);
|
||||
return { value, unit: 'km', digits };
|
||||
}
|
||||
|
||||
/**
|
||||
* Plain `850 m` / `4.6 km` / `12 km` text for labels that are not localized.
|
||||
* @param {number} meters
|
||||
* @param {{metreStep?: number, exactBelowM?: number}} [options]
|
||||
* @returns {string|null}
|
||||
*/
|
||||
export function formatDistanceText(meters, options) {
|
||||
const parts = distanceParts(meters, options);
|
||||
if (!parts) return null;
|
||||
return `${parts.value.toFixed(parts.digits)} ${parts.unit}`;
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import {
|
||||
distanceParts,
|
||||
formatDistanceText,
|
||||
kilometreDigits,
|
||||
} from './distanceFormat.js';
|
||||
|
||||
test('a distance switches to kilometres where its metres round to 1,000', () => {
|
||||
assert.equal(formatDistanceText(999.4), '999 m');
|
||||
assert.equal(formatDistanceText(999.5), '1.0 km');
|
||||
assert.equal(formatDistanceText(999.6), '1.0 km');
|
||||
assert.equal(formatDistanceText(994, { metreStep: 10 }), '990 m');
|
||||
assert.equal(formatDistanceText(995, { metreStep: 10 }), '1.0 km');
|
||||
});
|
||||
|
||||
test('kilometres drop their decimal where the tenth rounds to 10.0', () => {
|
||||
assert.equal(kilometreDigits(9949), 1);
|
||||
assert.equal(kilometreDigits(9950), 0);
|
||||
assert.equal(formatDistanceText(9949), '9.9 km');
|
||||
assert.equal(formatDistanceText(9950), '10 km');
|
||||
assert.equal(formatDistanceText(9960), '10 km');
|
||||
assert.equal(formatDistanceText(99950), '100 km');
|
||||
});
|
||||
|
||||
test('metres below exactBelowM stay whole while the rest round to the step', () => {
|
||||
const options = { metreStep: 10, exactBelowM: 100 };
|
||||
assert.equal(formatDistanceText(8, options), '8 m');
|
||||
assert.equal(formatDistanceText(99.4, options), '99 m');
|
||||
assert.equal(formatDistanceText(846, options), '850 m');
|
||||
assert.deepEqual(distanceParts(846, options), {
|
||||
value: 850,
|
||||
unit: 'm',
|
||||
digits: 0,
|
||||
});
|
||||
});
|
||||
|
||||
test('a negative or non-finite distance has no parts', () => {
|
||||
for (const value of [-1, Number.NaN, Infinity, -Infinity, null, undefined]) {
|
||||
assert.equal(distanceParts(value), null);
|
||||
assert.equal(formatDistanceText(value), null);
|
||||
}
|
||||
assert.equal(formatDistanceText(0), '0 m');
|
||||
});
|
||||
|
||||
test('kilometres come back rounded, so toFixed and Intl agree', () => {
|
||||
assert.deepEqual(distanceParts(1450), { value: 1.5, unit: 'km', digits: 1 });
|
||||
assert.equal(formatDistanceText(1450), '1.5 km');
|
||||
assert.equal(formatDistanceText(1150), '1.2 km');
|
||||
});
|
||||
@@ -0,0 +1,292 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { droneAirspaceProxy } from '../../server/providers/droneAirspace.js';
|
||||
|
||||
const feature = (id = 310, type = 'P') => ({
|
||||
properties: {
|
||||
NAME: `${type}-${id}`,
|
||||
TYPE_CODE: type,
|
||||
OBJECTID: id,
|
||||
UPPER_DESC: 'TNI',
|
||||
},
|
||||
geometry: {
|
||||
type: 'Polygon',
|
||||
coordinates: [
|
||||
[
|
||||
[-77, 38],
|
||||
[-76, 38],
|
||||
[-76, 39],
|
||||
[-77, 38],
|
||||
],
|
||||
],
|
||||
},
|
||||
});
|
||||
|
||||
function install(options = {}, hook = 'configureServer') {
|
||||
let handler;
|
||||
const plugin = droneAirspaceProxy(options);
|
||||
assert.equal(typeof plugin.configureServer, 'function');
|
||||
assert.equal(typeof plugin.configurePreviewServer, 'function');
|
||||
plugin[hook]({
|
||||
middlewares: {
|
||||
use(path, callback) {
|
||||
assert.equal(path, '/api/drone-airspace');
|
||||
handler = callback;
|
||||
},
|
||||
},
|
||||
});
|
||||
return async (url = '/', method = 'GET', peer = 'local', headers = {}) => {
|
||||
const res = {
|
||||
headers: {},
|
||||
writeHead(status, headers) {
|
||||
this.status = status;
|
||||
this.headers = headers;
|
||||
},
|
||||
setHeader(name, value) {
|
||||
this.headers[name] = value;
|
||||
},
|
||||
end(body) {
|
||||
this.status ??= this.statusCode;
|
||||
this.body = JSON.parse(body);
|
||||
},
|
||||
};
|
||||
await handler(
|
||||
{ url, method, headers, socket: { remoteAddress: peer } },
|
||||
res,
|
||||
);
|
||||
return res;
|
||||
};
|
||||
}
|
||||
|
||||
for (const hook of ['configureServer', 'configurePreviewServer']) {
|
||||
test(`${hook}: paging follows offsets and normalizes the combined snapshot`, async () => {
|
||||
const calls = [];
|
||||
const request = install(
|
||||
{
|
||||
now: () => 1234,
|
||||
fetchImpl: async (url, options) => {
|
||||
calls.push(new URL(url));
|
||||
assert.ok(options.signal instanceof AbortSignal);
|
||||
assert.equal(options.redirect, 'error');
|
||||
return Response.json({
|
||||
features: [feature(calls.length)],
|
||||
exceededTransferLimit: calls.length < 3,
|
||||
});
|
||||
},
|
||||
},
|
||||
hook,
|
||||
);
|
||||
const res = await request('/?url=https://invalid.example&resultOffset=999');
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.fetchedAt, 1234);
|
||||
assert.equal(res.body.rows.length, 3);
|
||||
assert.equal(calls.length, 3);
|
||||
assert.equal(calls[0].searchParams.get('where'), "TYPE_CODE IN ('P','R')");
|
||||
assert.equal(calls[0].searchParams.get('f'), 'geojson');
|
||||
assert.equal(calls[0].searchParams.has('resultOffset'), false);
|
||||
assert.equal(calls[1].searchParams.get('resultOffset'), '1');
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Serve one good snapshot, then let the upstream answer `bad` after the TTL:
|
||||
* the bad answer must not replace it, so the client gets the last good rows
|
||||
* marked stale, and a cold proxy answers 502 rather than caching the bad one.
|
||||
*/
|
||||
async function assertRejectedSnapshot(bad) {
|
||||
let now = 1000;
|
||||
let broken = false;
|
||||
let calls = 0;
|
||||
const request = install({
|
||||
now: () => now,
|
||||
fetchImpl: async () => {
|
||||
calls += 1;
|
||||
return broken ? bad(calls) : Response.json({ features: [feature(7)] });
|
||||
},
|
||||
});
|
||||
const first = await request();
|
||||
assert.equal(first.status, 200);
|
||||
broken = true;
|
||||
now += 3_600_001;
|
||||
const stale = await request();
|
||||
assert.equal(stale.status, 200);
|
||||
assert.equal(stale.headers['X-Data-Stale'], 'true');
|
||||
assert.equal(stale.body.stale, true);
|
||||
assert.equal(stale.body.fetchedAt, first.body.fetchedAt);
|
||||
assert.deepEqual(
|
||||
stale.body.rows.map((row) => row.stableId),
|
||||
['7'],
|
||||
);
|
||||
calls = 0;
|
||||
const cold = install({ fetchImpl: async () => bad(++calls) });
|
||||
const res = await cold();
|
||||
assert.equal(res.status, 502);
|
||||
assert.equal(res.body.error, 'drone_airspace_unavailable');
|
||||
}
|
||||
|
||||
test('an empty upstream snapshot keeps the last good one', () =>
|
||||
assertRejectedSnapshot(() => Response.json({ features: [] })));
|
||||
|
||||
test('a page whose every feature is invalid keeps the last good one', () =>
|
||||
assertRejectedSnapshot(() =>
|
||||
Response.json({
|
||||
features: [
|
||||
{
|
||||
...feature(8),
|
||||
properties: { ...feature(8).properties, TYPE_CODE: 'W' },
|
||||
},
|
||||
{ ...feature(9), geometry: null },
|
||||
],
|
||||
}),
|
||||
));
|
||||
|
||||
test('paging that exhausts its page limit still flagged keeps the last good one', () =>
|
||||
assertRejectedSnapshot((call) =>
|
||||
Response.json({
|
||||
features: [feature(100 + call)],
|
||||
exceededTransferLimit: true,
|
||||
}),
|
||||
));
|
||||
|
||||
test('a flagged page that adds no features keeps the last good one', () =>
|
||||
assertRejectedSnapshot((call) =>
|
||||
Response.json(
|
||||
call % 2
|
||||
? { features: [feature(100 + call)], exceededTransferLimit: true }
|
||||
: { features: [], properties: { exceededTransferLimit: true } },
|
||||
),
|
||||
));
|
||||
|
||||
test('a cached snapshot is reused until TTL, then refreshed', async () => {
|
||||
let now = 1000;
|
||||
let fetches = 0;
|
||||
const request = install({
|
||||
now: () => now,
|
||||
fetchImpl: async () => {
|
||||
fetches += 1;
|
||||
return Response.json({ features: [feature(fetches)] });
|
||||
},
|
||||
});
|
||||
const first = await request();
|
||||
now += 3_599_000;
|
||||
const cached = await request();
|
||||
now += 2000;
|
||||
const refreshed = await request();
|
||||
assert.equal(first.body.rows[0].stableId, '1');
|
||||
assert.equal(cached.body.rows[0].stableId, '1');
|
||||
assert.equal(refreshed.body.rows[0].stableId, '2');
|
||||
assert.equal(fetches, 2);
|
||||
});
|
||||
|
||||
test('a failed refresh serves the last good snapshot as stale', async () => {
|
||||
let now = 1000;
|
||||
let fail = false;
|
||||
const request = install({
|
||||
now: () => now,
|
||||
fetchImpl: async () => {
|
||||
if (fail) return new Response('nope', { status: 503 });
|
||||
return Response.json({ features: [feature(7)] });
|
||||
},
|
||||
});
|
||||
const first = await request();
|
||||
fail = true;
|
||||
now += 3_600_001;
|
||||
const stale = await request();
|
||||
assert.equal(first.status, 200);
|
||||
assert.equal(stale.status, 200);
|
||||
assert.equal(stale.headers['X-Data-Stale'], 'true');
|
||||
assert.equal(stale.body.stale, true);
|
||||
assert.equal(stale.body.rows[0].stableId, '7');
|
||||
});
|
||||
|
||||
test('method, unknown routes and rate limits are rejected', async () => {
|
||||
const request = install({
|
||||
fetchImpl: async () => Response.json({ features: [feature()] }),
|
||||
});
|
||||
assert.equal((await request('/', 'POST')).status, 405);
|
||||
assert.equal((await request('/nope')).status, 404);
|
||||
const limited = install({
|
||||
fetchImpl: async () => Response.json({ features: [feature()] }),
|
||||
});
|
||||
let last;
|
||||
for (let i = 0; i < 61; i++) last = await limited('/', 'GET', '10.0.0.9');
|
||||
assert.equal(last.status, 429);
|
||||
});
|
||||
|
||||
test('a cold upstream failure is 502, not an empty snapshot', async () => {
|
||||
const request = install({
|
||||
fetchImpl: async () => new Response('nope', { status: 503 }),
|
||||
});
|
||||
const res = await request();
|
||||
assert.equal(res.status, 502);
|
||||
assert.equal(res.body.error, 'drone_airspace_unavailable');
|
||||
});
|
||||
|
||||
test('a stale snapshot is served for at most a day, then refused', async () => {
|
||||
let now = 1_000_000_000;
|
||||
let up = true;
|
||||
const request = install({
|
||||
now: () => now,
|
||||
fetchImpl: async () => {
|
||||
if (!up) throw new Error('FAA unreachable');
|
||||
return Response.json({ features: [feature(7)] });
|
||||
},
|
||||
});
|
||||
const fresh = await request();
|
||||
assert.equal(fresh.status, 200);
|
||||
up = false;
|
||||
now += 23 * 60 * 60 * 1000;
|
||||
const stale = await request();
|
||||
assert.equal(stale.status, 200);
|
||||
assert.equal(stale.body.stale, true);
|
||||
assert.equal(stale.body.fetchedAt, fresh.body.fetchedAt);
|
||||
now += 2 * 60 * 60 * 1000;
|
||||
assert.equal((await request()).status, 502, 'a day-old snapshot is refused');
|
||||
});
|
||||
|
||||
test('a cross-site page is refused before it spends quota or reaches FAA', async () => {
|
||||
let fetches = 0;
|
||||
const request = install({
|
||||
fetchImpl: async () => {
|
||||
fetches += 1;
|
||||
return Response.json({ features: [feature()] });
|
||||
},
|
||||
});
|
||||
const host = 'localhost:5173';
|
||||
const refused = [
|
||||
{ host, 'sec-fetch-site': 'cross-site' },
|
||||
{ host, origin: 'https://evil.example' },
|
||||
{ host, origin: 'https://evil.example', 'sec-fetch-site': 'cross-site' },
|
||||
{ host, 'x-forwarded-for': '203.0.113.9', 'sec-fetch-site': 'cross-site' },
|
||||
];
|
||||
// More refusals than the 60/min per-client quota, all from one peer.
|
||||
for (let i = 0; i < 64; i++) {
|
||||
const headers = refused[i % refused.length];
|
||||
const res = await request('/', 'GET', '10.0.0.5', headers);
|
||||
assert.equal(res.status, 403, JSON.stringify(headers));
|
||||
}
|
||||
assert.equal(fetches, 0, 'refusals cost no upstream call');
|
||||
const app = await request('/', 'GET', '10.0.0.5', {
|
||||
host,
|
||||
origin: `http://${host}`,
|
||||
'sec-fetch-site': 'same-origin',
|
||||
});
|
||||
assert.equal(app.status, 200, 'the app keeps its full quota');
|
||||
assert.equal(fetches, 1);
|
||||
});
|
||||
|
||||
test('the app served behind a reverse proxy still gets the zones', async () => {
|
||||
const request = install({
|
||||
fetchImpl: async () => Response.json({ features: [feature()] }),
|
||||
});
|
||||
const host = 'gev.example.com';
|
||||
const res = await request('/', 'GET', '127.0.0.1', {
|
||||
host,
|
||||
origin: `https://${host}`,
|
||||
'sec-fetch-site': 'same-origin',
|
||||
'x-forwarded-for': '203.0.113.9',
|
||||
'x-forwarded-proto': 'https',
|
||||
});
|
||||
assert.equal(res.status, 200);
|
||||
assert.equal(res.body.rows.length, 1);
|
||||
});
|
||||
@@ -8,4 +8,3 @@ export function createEarthquakesLayer({
|
||||
} = {}) {
|
||||
return createApplicationEarthquakes({ source, ...options });
|
||||
}
|
||||
export default createEarthquakesLayer();
|
||||
@@ -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());
|
||||
}
|
||||
});
|
||||
Loaded 100 of 4310 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user