mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 18:22:25 +00:00
Merge upstream main into feat/iss-3d-model
Translation files: kept both sides' new keys. Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
commit
349b3a04ec
407 files changed
+23411
-2582
No files matched your search
@@ -64,7 +64,11 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
|
||||
const geometricFeet = finiteNumber(aircraft?.alt_geom);
|
||||
const groundSpeedKnots = finiteNumber(aircraft?.gs);
|
||||
const verticalRateFpm = readAdsbVerticalRateFpm(aircraft);
|
||||
const track = finiteNumber(aircraft?.track);
|
||||
// A parked or slow aircraft reports no ground track, but often its true
|
||||
// heading (surface messages): the way its nose points, which is what an
|
||||
// aircraft standing still is drawn by. Magnetic heading is not true north.
|
||||
const track =
|
||||
finiteNumber(aircraft?.track) ?? finiteNumber(aircraft?.true_heading);
|
||||
|
||||
return [
|
||||
hex,
|
||||
|
||||
@@ -49,3 +49,15 @@ 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');
|
||||
});
|
||||
@@ -458,7 +458,8 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
|
||||
);
|
||||
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.equal(rendering._modelColor('civil'), Cesium.Color.WHITE);
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* Lighting options shared by every aircraft 3D model (Flights, Military
|
||||
* Flights, Local ADS-B).
|
||||
@@ -6,12 +8,24 @@
|
||||
* the model and reads the result back from the GPU (`readPixels`) to light it,
|
||||
* when the model is first placed and again when it moves more than 1 km, when
|
||||
* the scene's atmosphere settings change, or every scene hour under sunlight
|
||||
* lighting. Aircraft models take 94% of their surface from the class colour
|
||||
* (`colorBlendAmount`), so that lighting contributes little; without it they
|
||||
* are lit from Cesium's default spherical harmonics. Measured 2026-10-24
|
||||
* (Intel Arc, Google 3D, ~150 models in the scene): GPU per frame at rest
|
||||
* 14.3-14.8 -> 12.1-12.5 ms.
|
||||
* lighting. Without it they are lit from Cesium's default spherical
|
||||
* harmonics. Measured 2026-10-24 (Intel Arc, Google 3D, ~150 models in the
|
||||
* scene): GPU per frame at rest 14.3-14.8 -> 12.1-12.5 ms.
|
||||
*/
|
||||
export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
|
||||
enabled: false,
|
||||
});
|
||||
|
||||
/**
|
||||
* How an aircraft model's colour meets its mesh. HIGHLIGHT multiplies, so
|
||||
* white draws the mesh's own colours as built, and the tracked or emergency
|
||||
* colour tints the mesh without hiding its paint. The IR boost draws the
|
||||
* model flat white instead (MIX at 1, with its unlit shader).
|
||||
* @param {boolean} irBoost
|
||||
* @returns {{colorBlendMode: Cesium.ColorBlendMode, colorBlendAmount: number}}
|
||||
*/
|
||||
export function aircraftModelBlend(irBoost) {
|
||||
return irBoost
|
||||
? { colorBlendMode: Cesium.ColorBlendMode.MIX, colorBlendAmount: 1 }
|
||||
: { colorBlendMode: Cesium.ColorBlendMode.HIGHLIGHT, colorBlendAmount: 0 };
|
||||
}
|
||||
@@ -243,7 +243,7 @@ export function applyAircraftBillboardTreatment({
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -1882,3 +1882,57 @@ test('detection objects name the vessel card their callout gives way to', () =>
|
||||
_setVesselStateForTest({ enabled: false });
|
||||
}
|
||||
});
|
||||
|
||||
test('an aid to navigation card shows its kind, never a speed or heading', () => {
|
||||
const aid = makeRecord({
|
||||
name: 'SF APPROACH N',
|
||||
mmsi: '993672001',
|
||||
type: 'Cardinal Mark N',
|
||||
speed: 0,
|
||||
course: 135,
|
||||
heading: 135,
|
||||
});
|
||||
const card = buildVesselCard(aid);
|
||||
assert.deepEqual(card.details, ['CARDINAL MARK N']);
|
||||
assert.equal(card.accent, '217, 210, 192');
|
||||
const selected = buildSelectedVesselCard(aid);
|
||||
assert.equal(selected.details[0], 'CARDINAL MARK N');
|
||||
assert.equal(selected.accent, '217, 210, 192');
|
||||
// Known only by its MMSI, an aid is named as one.
|
||||
const unnamed = buildSelectedVesselCard({ ...aid, type: '' });
|
||||
assert.equal(unnamed.details[0], 'AID TO NAVIGATION');
|
||||
assert.deepEqual(buildVesselCard({ ...aid, type: '' }).details, []);
|
||||
});
|
||||
|
||||
test('the HUD of a selected aid to navigation shows no speed or heading', () => {
|
||||
const harness = installWireHarness(undefined, { selectedRecord: null });
|
||||
try {
|
||||
Object.assign(harness.record, {
|
||||
type: 'Port hand Mark',
|
||||
speed: 0,
|
||||
heading: 135,
|
||||
course: 135,
|
||||
});
|
||||
assert.equal(aisLiveVesselsLayer.selectById(harness.record.mmsi), true);
|
||||
assert.match(harness.hud.readout.text, /\nPort hand Mark\n/);
|
||||
assert.doesNotMatch(harness.hud.readout.text, /SPD|HDG|KT/);
|
||||
harness.record.virtual = true;
|
||||
aisLiveVesselsLayer.selectById(harness.record.mmsi);
|
||||
assert.match(harness.hud.readout.text, /\nPort hand Mark · VIRTUAL\n/);
|
||||
} finally {
|
||||
harness.cleanup();
|
||||
}
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation card says it is virtual', () => {
|
||||
const aid = makeRecord({
|
||||
mmsi: '993672001',
|
||||
type: 'Isolated danger',
|
||||
virtual: true,
|
||||
});
|
||||
assert.deepEqual(buildVesselCard(aid).details, ['ISOLATED DANGER · VIRTUAL']);
|
||||
assert.equal(
|
||||
buildSelectedVesselCard(aid).details[0],
|
||||
'ISOLATED DANGER · VIRTUAL',
|
||||
);
|
||||
});
|
||||
@@ -316,3 +316,97 @@ test('a Class B report carries its dimensions in part B', () => {
|
||||
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);
|
||||
});
|
||||
@@ -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);
|
||||
});
|
||||
@@ -712,6 +712,15 @@ export const NATURAL_EARTH_CREDIT = {
|
||||
'<a href="https://www.naturalearthdata.com" target="_blank" rel="noopener">Natural Earth</a> (public domain)',
|
||||
};
|
||||
|
||||
/** Registered when a name from the bundled Wikidata places packs is first
|
||||
* shown (CC0 — no attribution required; credited as a courtesy). */
|
||||
export const WIKIDATA_PLACES_CREDIT = {
|
||||
key: 'wikidata-places',
|
||||
html:
|
||||
'City, town and village names from ' +
|
||||
'<a href="https://www.wikidata.org" target="_blank" rel="noopener">Wikidata</a> (CC0)',
|
||||
};
|
||||
|
||||
/** Registered when the first bundled US county or place outline resolves
|
||||
* (public domain — credited as a courtesy). */
|
||||
export const US_CENSUS_CREDIT = {
|
||||
|
||||
+142
-14
@@ -11,6 +11,9 @@
|
||||
* vehicle's road or rail top), and is drawn life size: a type's published
|
||||
* length over the model's built length is its scale.
|
||||
*
|
||||
* An aid to navigation (a buoy, beacon, mark, RACON or light) is drawn as
|
||||
* the set's buoy of its IALA mark, by the mark its type names.
|
||||
*
|
||||
* The resolvers are plain functions over the parsed JSON; `loadFleetModelSet`
|
||||
* fetches the JSON and every GLB once, up front, so no model is fetched
|
||||
* mid-session.
|
||||
@@ -18,6 +21,7 @@
|
||||
|
||||
import { classifyAircraft } from './aircraftClass.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
/** Where the model set is served, relative to the application base. */
|
||||
export const FLEET_MODEL_BASE = '/models/fleet/';
|
||||
@@ -85,16 +89,62 @@ const TEXT_SHIP_TYPES = [
|
||||
];
|
||||
|
||||
/**
|
||||
* The model for an aircraft of ICAO type `type` (A320, B738, R44) and ADS-B
|
||||
* emitter category `category`: the type's, else the category's, else
|
||||
* `default_aircraft`.
|
||||
* The buoy an aid to navigation is drawn as, by the mark its type names
|
||||
* ("Cardinal Mark N", "Beacon, Port hand", "Safe Water"): the first pattern
|
||||
* that matches. Beacons, lights, RACONs and reference points with no mark of
|
||||
* their own are the special mark.
|
||||
*/
|
||||
const AID_MODELS = [
|
||||
[/cardinal\b.*\bn(orth)?$/i, 'buoy_cardinal_north'],
|
||||
[/cardinal\b.*\be(ast)?$/i, 'buoy_cardinal_east'],
|
||||
[/cardinal\b.*\bs(outh)?$/i, 'buoy_cardinal_south'],
|
||||
[/cardinal\b.*\bw(est)?$/i, 'buoy_cardinal_west'],
|
||||
[/isolated danger/i, 'buoy_isolated_danger'],
|
||||
[/safe water/i, 'buoy_safe_water'],
|
||||
[/port hand/i, 'buoy_lateral_port'],
|
||||
[/starboard hand/i, 'buoy_lateral_starboard'],
|
||||
[/special mark|light vessel|lanby/i, 'buoy_special'],
|
||||
[
|
||||
/^(beacon|light\b|leading light|racon|reference point|navigation aid)/i,
|
||||
'buoy_special',
|
||||
],
|
||||
];
|
||||
|
||||
/** The buoy an aid to navigation whose type names no mark is drawn as. */
|
||||
export const DEFAULT_AID_MODEL = 'can_red';
|
||||
|
||||
/**
|
||||
* The buoy model of an aid to navigation's type, else undefined when the
|
||||
* type names no mark.
|
||||
* @param {string|null} [type]
|
||||
* @returns {string|undefined}
|
||||
*/
|
||||
export function aidToNavigationModel(type) {
|
||||
const text = String(type ?? '').trim();
|
||||
for (const [pattern, model] of AID_MODELS)
|
||||
if (pattern.test(text)) return model;
|
||||
return undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* The model for an aircraft of ICAO type `type` (A320, B738, R44), ADS-B
|
||||
* emitter category `category` and callsign `callsign`: the first of the
|
||||
* type's callsign rules (`aircraft_callsign`) the callsign matches, else the
|
||||
* type's, else the category's, else `default_aircraft`. An airport vehicle
|
||||
* (type ZVEH) is a fire truck, tug or van by its callsign, else a car.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string} [type]
|
||||
* @param {string} [category]
|
||||
* @param {string} [callsign]
|
||||
* @returns {{model: string, length: number|null}}
|
||||
*/
|
||||
export function resolveAircraft(types, type, category) {
|
||||
export function resolveAircraft(types, type, category, callsign) {
|
||||
const t = type?.trim().toUpperCase();
|
||||
const index = aircraftCallsignRule(types, t, callsign);
|
||||
if (index >= 0) {
|
||||
const rule = types.aircraft_callsign[t][index];
|
||||
return { model: rule.model, length: rule.length };
|
||||
}
|
||||
const [model, length] =
|
||||
(t && (types.aircraft[t] ?? types.helicopters[t])) ||
|
||||
(category && types.categories[category]) ||
|
||||
@@ -102,6 +152,51 @@ export function resolveAircraft(types, type, category) {
|
||||
return { model, length };
|
||||
}
|
||||
|
||||
/**
|
||||
* A callsign as the rules read it: upper case, spaces removed.
|
||||
* @param {string} callsign
|
||||
* @returns {string}
|
||||
*/
|
||||
function callsignKey(callsign) {
|
||||
return String(callsign).toUpperCase().replace(/\s+/g, '');
|
||||
}
|
||||
|
||||
/**
|
||||
* Which of type `type`'s callsign rules (`types.json`'s
|
||||
* `aircraft_callsign[type]`, each `{prefixes, model, length}`, first match
|
||||
* wins) `callsign` matches: its index, -1 when none does or the type has
|
||||
* none. A callsign matches a rule when, upper-cased with spaces removed, it
|
||||
* starts with one of the rule's prefixes.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string|null} [type] ICAO type.
|
||||
* @param {string|null} [callsign]
|
||||
* @returns {number}
|
||||
*/
|
||||
export function aircraftCallsignRule(types, type, callsign) {
|
||||
const t = String(type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const rules = t ? types.aircraft_callsign?.[t] : undefined;
|
||||
if (!rules || !callsign) return -1;
|
||||
const c = callsignKey(callsign);
|
||||
return rules.findIndex((rule) =>
|
||||
rule.prefixes.some((prefix) => c.startsWith(callsignKey(prefix))),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft of ICAO type `type` picks its model by callsign.
|
||||
* @param {object} types Parsed `types.json`.
|
||||
* @param {string|null} [type]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function aircraftModelByCallsign(types, type) {
|
||||
const t = String(type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
return Boolean(t && types.aircraft_callsign?.[t]);
|
||||
}
|
||||
|
||||
/**
|
||||
* A reported length as one a hull can have, else undefined (drawn as built).
|
||||
* @param {number} [length]
|
||||
@@ -306,24 +401,32 @@ function specOf(set, resolved, fallback, options) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The model an aircraft is drawn with. The type's entry first; then, for a
|
||||
* The model an aircraft is drawn with. The type's callsign rules (an airport
|
||||
* vehicle by its callsign), then the type's entry; then, for a
|
||||
* type the map lacks, the model of its class (a fast jet, a helicopter, a
|
||||
* glider) when the type names one; then the emitter category's; then
|
||||
* `default_aircraft`.
|
||||
* @param {{catalog: object, types: object}} set
|
||||
* @param {{typeCode?: string|null, type?: string|null,
|
||||
* category?: string|number|null}} aircraft
|
||||
* category?: string|number|null, callsign?: string|null}} aircraft
|
||||
* @returns {object} {@link fleetModelSpec}
|
||||
*/
|
||||
export function aircraftModelSpec(set, { typeCode, type, category } = {}) {
|
||||
export function aircraftModelSpec(
|
||||
set,
|
||||
{ typeCode, type, category, callsign } = {},
|
||||
) {
|
||||
const { types, catalog } = set;
|
||||
const code = String(typeCode ?? type ?? '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
const emitter = emitterCategory(category);
|
||||
let resolved = resolveAircraft(types, code, emitter);
|
||||
const sign = callsign ? String(callsign) : undefined;
|
||||
let resolved = resolveAircraft(types, code, emitter, sign);
|
||||
// A callsign rule names the model outright; a type's class only stands in
|
||||
// for a type the map lacks.
|
||||
const ruled = aircraftCallsignRule(types, code, sign) >= 0;
|
||||
const typed = code && (types.aircraft[code] || types.helicopters[code]);
|
||||
if (!typed && code) {
|
||||
if (!ruled && !typed && code) {
|
||||
const model = CLASS_MODELS[classifyAircraft({ typeCode: code })];
|
||||
if (model && catalog[model])
|
||||
resolved = { model, length: catalog[model].length };
|
||||
@@ -336,13 +439,33 @@ export function aircraftModelSpec(set, { typeCode, type, category } = {}) {
|
||||
|
||||
/**
|
||||
* The model a vessel is drawn with, from its AIS ship type (a code or a text
|
||||
* family), reported length and beam (metres) and name.
|
||||
* family), reported length and beam (metres) and name. An aid to navigation
|
||||
* ({@link isAidToNavigation}: its type names a buoy, beacon, mark, RACON or
|
||||
* light, or its MMSI is an aid's) is the buoy of its mark
|
||||
* ({@link aidToNavigationModel}), else {@link DEFAULT_AID_MODEL}, drawn as
|
||||
* built and flagged `fixed`: it has no heading to turn to. A virtual aid
|
||||
* (`virtual`) is broadcast where nothing physical stands, so it has no model.
|
||||
* @param {{catalog: object, types: object}} set
|
||||
* @param {{type?: string|number|null, length?: number|null,
|
||||
* beam?: number|null, name?: string|null}} vessel
|
||||
* @returns {object} {@link fleetModelSpec}
|
||||
* @param {{type?: string|number|null, mmsi?: string|number|null,
|
||||
* virtual?: boolean, length?: number|null, beam?: number|null,
|
||||
* name?: string|null}} vessel
|
||||
* @returns {object|null} {@link fleetModelSpec}, with `fixed` for an aid;
|
||||
* null for a virtual aid
|
||||
*/
|
||||
export function vesselModelSpec(set, { type, length, beam, name } = {}) {
|
||||
export function vesselModelSpec(
|
||||
set,
|
||||
{ type, mmsi, virtual, length, beam, name } = {},
|
||||
) {
|
||||
if (virtual === true) return null;
|
||||
if (isAidToNavigation({ type, mmsi })) {
|
||||
const model = aidToNavigationModel(type);
|
||||
const known = model && set.catalog[model] ? model : DEFAULT_AID_MODEL;
|
||||
if (set.catalog[known])
|
||||
return Object.freeze({
|
||||
...fleetModelSpec(set, known, null),
|
||||
fixed: true,
|
||||
});
|
||||
}
|
||||
// A beam counts only beside a reported length: a vessel drawn at its type's
|
||||
// typical length keeps the model's proportions.
|
||||
const reported = hullLength(length ?? undefined);
|
||||
@@ -387,6 +510,9 @@ export function namedFleetModels(types) {
|
||||
...pairs(types.aircraft),
|
||||
...pairs(types.helicopters),
|
||||
...pairs(types.categories),
|
||||
...Object.values(types.aircraft_callsign ?? {}).flatMap((rules) =>
|
||||
rules.map((rule) => rule.model),
|
||||
),
|
||||
...types.vessels.flatMap((group) => group.rules.map((rule) => rule.model)),
|
||||
types.default_aircraft[0],
|
||||
types.default_vessel,
|
||||
@@ -396,6 +522,8 @@ export function namedFleetModels(types) {
|
||||
transit.default[0],
|
||||
...Object.keys(transit.elevation),
|
||||
...Object.values(CLASS_MODELS),
|
||||
...AID_MODELS.map(([, model]) => model),
|
||||
DEFAULT_AID_MODEL,
|
||||
]);
|
||||
}
|
||||
|
||||
|
||||
@@ -4,7 +4,9 @@ import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import {
|
||||
DEFAULT_AID_MODEL,
|
||||
FLEET_MODEL_BASE,
|
||||
aidToNavigationModel,
|
||||
aircraftModelSpec,
|
||||
aisShipTypeCode,
|
||||
emitterCategory,
|
||||
@@ -23,6 +25,7 @@ import {
|
||||
vesselModelSpec,
|
||||
} from './fleetModels.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { TRANSIT_MODES } from './transitFeeds.js';
|
||||
import {
|
||||
centrelineSegments,
|
||||
distanceToSurface,
|
||||
@@ -51,8 +54,17 @@ const sliceTypes = {
|
||||
A21N: ['a320', 44.51],
|
||||
A319: ['a320', 33.84],
|
||||
B38M: ['b738', 39.52],
|
||||
ZVEH: ['car', 4.61],
|
||||
GRND: ['radio_mast', 1.9],
|
||||
},
|
||||
helicopters: { EC35: ['ec35', 10.2] },
|
||||
aircraft_callsign: {
|
||||
ZVEH: [
|
||||
{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 },
|
||||
{ prefixes: ['PUSH', 'TUG'], model: 'pushback', length: 6 },
|
||||
{ prefixes: ['DEICER', 'SQUID', 'SQB'], model: 'van', length: 5.51 },
|
||||
],
|
||||
},
|
||||
categories: { A1: ['c172', 8.3] },
|
||||
vessels: [
|
||||
{
|
||||
@@ -112,6 +124,33 @@ test('aircraft resolve by type, then emitter category, then the generic plane',
|
||||
});
|
||||
});
|
||||
|
||||
test('airport vehicles (ZVEH) by callsign, first rule wins, else the type: spaces and case ignored', () => {
|
||||
const zveh = (callsign) =>
|
||||
resolveAircraft(sliceTypes, 'ZVEH', undefined, callsign);
|
||||
assert.deepEqual(zveh('FIRE 2'), { model: 'fire_truck', length: 11.01 });
|
||||
assert.deepEqual(resolveAircraft(sliceTypes, 'zveh', undefined, ' fire2 '), {
|
||||
model: 'fire_truck',
|
||||
length: 11.01,
|
||||
});
|
||||
assert.equal(zveh('PUSH 14').model, 'pushback');
|
||||
assert.equal(zveh('TUG3').model, 'pushback');
|
||||
assert.deepEqual(zveh('DEICER 4'), { model: 'van', length: 5.51 });
|
||||
assert.equal(zveh('SQUID20').model, 'van');
|
||||
assert.equal(zveh('SQB9').model, 'van');
|
||||
assert.equal(zveh('S Q B 9').model, 'van');
|
||||
assert.deepEqual(zveh('LEADER 7'), { model: 'car', length: 4.61 });
|
||||
assert.deepEqual(zveh(undefined), { model: 'car', length: 4.61 });
|
||||
// Callsign rules belong to their type: a fire-named airliner is still an airliner.
|
||||
assert.equal(
|
||||
resolveAircraft(sliceTypes, 'A320', undefined, 'FIRE1').model,
|
||||
'a320',
|
||||
);
|
||||
assert.deepEqual(resolveAircraft(sliceTypes, 'GRND', undefined, 'RX5'), {
|
||||
model: 'radio_mast',
|
||||
length: 1.9,
|
||||
});
|
||||
});
|
||||
|
||||
test('vessels: the first matching rule of the first type range with one, else the generic vessel', () => {
|
||||
assert.equal(resolveVessel(sliceTypes, 70, 366, 51).model, 'container_ship');
|
||||
assert.equal(
|
||||
@@ -225,6 +264,46 @@ test('transit bodies mark the share of the route colour they take; other models
|
||||
}
|
||||
});
|
||||
|
||||
test('aircraft specs: airport vehicles by callsign, ground stations as a mast, as the set says', () => {
|
||||
const zveh = (callsign) =>
|
||||
aircraftModelSpec(set, { typeCode: 'ZVEH', category: 'UNKNOWN', callsign })
|
||||
.model;
|
||||
assert.equal(zveh('FIRE 2'), 'fire_truck');
|
||||
assert.equal(zveh('PUSHBACK1'), 'pushback');
|
||||
assert.equal(zveh('TUG 4'), 'pushback');
|
||||
assert.equal(zveh('DEICER 4'), 'van');
|
||||
assert.equal(zveh('SQUID20'), 'van');
|
||||
assert.equal(zveh('SQB9'), 'van');
|
||||
assert.equal(zveh('LEADER 7'), 'car');
|
||||
assert.equal(zveh('AOPS'), 'car');
|
||||
assert.equal(zveh(null), 'car');
|
||||
const mast = aircraftModelSpec(set, { typeCode: 'GRND', callsign: 'RX5' });
|
||||
assert.equal(mast.model, 'radio_mast');
|
||||
assert.equal(mast.scale, 1);
|
||||
});
|
||||
|
||||
test('a callsign rule outranks the class model of a type the map lacks', () => {
|
||||
const ruled = {
|
||||
...set,
|
||||
types: {
|
||||
...set.types,
|
||||
aircraft_callsign: {
|
||||
...set.types.aircraft_callsign,
|
||||
PUMA: [{ prefixes: ['FIRE'], model: 'fire_truck', length: 11.01 }],
|
||||
},
|
||||
},
|
||||
};
|
||||
assert.equal(
|
||||
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'FIRE 1' }).model,
|
||||
'fire_truck',
|
||||
);
|
||||
// No rule matched: the class model, as before.
|
||||
assert.equal(
|
||||
aircraftModelSpec(ruled, { typeCode: 'PUMA', callsign: 'RESCUE1' }).model,
|
||||
'generic_heli',
|
||||
);
|
||||
});
|
||||
|
||||
test('aircraft specs: by type, then class for an unlisted type, then emitter category', () => {
|
||||
assert.equal(aircraftModelSpec(set, { typeCode: 'A320' }).model, 'a320');
|
||||
assert.equal(aircraftModelSpec(set, { type: 'b744' }).model, 'b744');
|
||||
@@ -305,6 +384,99 @@ test('vessel specs read AIS codes and text families, stretched to the reported b
|
||||
assert.equal(unknown.scale, 1);
|
||||
});
|
||||
|
||||
test('aids to navigation are the buoy of the mark their type names', () => {
|
||||
const cases = [
|
||||
['Cardinal Mark N', 'buoy_cardinal_north'],
|
||||
['Beacon, Cardinal E', 'buoy_cardinal_east'],
|
||||
['Cardinal Mark S', 'buoy_cardinal_south'],
|
||||
['Beacon, Cardinal W', 'buoy_cardinal_west'],
|
||||
['Port Hand Mark', 'buoy_lateral_port'],
|
||||
['Beacon, Port hand', 'buoy_lateral_port'],
|
||||
['Starboard Hand Mark', 'buoy_lateral_starboard'],
|
||||
['Preferred Channel Starboard hand', 'buoy_lateral_starboard'],
|
||||
['Safe Water', 'buoy_safe_water'],
|
||||
['Isolated danger', 'buoy_isolated_danger'],
|
||||
['Beacon, Special Mark', 'buoy_special'],
|
||||
['Special Mark', 'buoy_special'],
|
||||
['Light Vessel / LANBY / Rigs', 'buoy_special'],
|
||||
['RACON', 'buoy_special'],
|
||||
['Light, with Sectors', 'buoy_special'],
|
||||
['Reference point', 'buoy_special'],
|
||||
['Navigation aid', 'buoy_special'],
|
||||
];
|
||||
for (const [type, model] of cases) {
|
||||
assert.equal(aidToNavigationModel(type), model, type);
|
||||
assert.ok(catalog[model], model);
|
||||
const spec = vesselModelSpec(set, { type, mmsi: '993672001' });
|
||||
assert.equal(spec.model, model, type);
|
||||
assert.equal(spec.category, 'buoys', type);
|
||||
assert.equal(spec.fixed, true, type);
|
||||
// A buoy is drawn as built, whatever length the report gives.
|
||||
assert.equal(spec.scale, 1, type);
|
||||
}
|
||||
assert.equal(
|
||||
vesselModelSpec(set, { type: 'Safe Water', length: 120, beam: 30 }).scale,
|
||||
1,
|
||||
);
|
||||
// An aid of no stated kind, known only by its MMSI, is the default can.
|
||||
assert.ok(catalog[DEFAULT_AID_MODEL]);
|
||||
const unnamed = vesselModelSpec(set, { type: '', mmsi: '993660123' });
|
||||
assert.equal(unnamed.model, DEFAULT_AID_MODEL);
|
||||
assert.equal(unnamed.fixed, true);
|
||||
assert.equal(aidToNavigationModel('Fixed structure off shore'), undefined);
|
||||
// A virtual aid is broadcast where nothing stands: it keeps its disc.
|
||||
assert.equal(
|
||||
vesselModelSpec(set, {
|
||||
type: 'Cardinal Mark N',
|
||||
mmsi: '993672001',
|
||||
virtual: true,
|
||||
}),
|
||||
null,
|
||||
);
|
||||
// Vessels, including those that work on buoys, keep their hulls.
|
||||
for (const vessel of [
|
||||
{ type: 'Buoy Tender', mmsi: '366999001', length: 60 },
|
||||
{ type: '70', mmsi: '366999002' },
|
||||
{ type: 'Tug', mmsi: '' },
|
||||
]) {
|
||||
const spec = vesselModelSpec(set, vessel);
|
||||
assert.notEqual(spec.category, 'buoys', vessel.type);
|
||||
assert.equal(spec.fixed, undefined, vessel.type);
|
||||
}
|
||||
});
|
||||
|
||||
test('every transit mode but unknown draws its own model, and a route type a finer one', () => {
|
||||
for (const mode of TRANSIT_MODES.filter((m) => m !== 'unknown')) {
|
||||
assert.ok(types.transit.modes[mode], `${mode} has a model`);
|
||||
assert.equal(
|
||||
resolveTransit(types, { mode }).model,
|
||||
types.transit.modes[mode][0],
|
||||
);
|
||||
}
|
||||
for (const [mode, model] of [
|
||||
['trolleybus', 'trolleybus'],
|
||||
['cable_tram', 'cable_tram'],
|
||||
['aerial_lift', 'gondola'],
|
||||
['funicular', 'funicular'],
|
||||
['monorail', 'monorail'],
|
||||
])
|
||||
assert.equal(resolveTransit(types, { mode }).model, model, mode);
|
||||
// A route type outranks the mode: a coach and a high-speed set are still
|
||||
// the bus and rail modes.
|
||||
for (const [routeType, mode, model] of [
|
||||
[200, 'bus', 'coach'],
|
||||
[101, 'rail', 'high_speed'],
|
||||
[106, 'rail', 'regional_dmu'],
|
||||
[710, 'bus', 'double_decker'],
|
||||
])
|
||||
assert.equal(resolveTransit(types, { routeType, mode }).model, model);
|
||||
// A type the table lacks falls back to the mode.
|
||||
assert.equal(
|
||||
resolveTransit(types, { routeType: 300, mode: 'rail' }).model,
|
||||
'commuter_emu',
|
||||
);
|
||||
});
|
||||
|
||||
test('transit specs: rail category and mode, then route type, then mode, then the default', () => {
|
||||
assert.deepEqual(resolveTransit(types, { railCategory: 'national' }), {
|
||||
model: 'intercity',
|
||||
|
||||
@@ -32,7 +32,7 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
c172: Object.freeze([4.0507, 0.4481, 0]),
|
||||
c30j: Object.freeze([13.568, 0.9917, 0]),
|
||||
c56x: Object.freeze([7.4627, 0.4526, 0]),
|
||||
car: Object.freeze([2.3, 0.418, 0]),
|
||||
car: Object.freeze([2.1851, 0.301, 0]),
|
||||
cl35: Object.freeze([10.4607, 0.8247, 0]),
|
||||
crj9: Object.freeze([17.8413, 0.8624, 0]),
|
||||
dh8d: Object.freeze([15.7902, 0.7501, 0]),
|
||||
@@ -40,7 +40,7 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
e55p: Object.freeze([7.6566, 0.503, 0]),
|
||||
ec35: Object.freeze([5.1003, 0.1471, 0]),
|
||||
ec45: Object.freeze([5.8004, 0.555, 0]),
|
||||
fire_truck: Object.freeze([5.5, 0.6051, 0]),
|
||||
fire_truck: Object.freeze([5.39, 0.4227, 0]),
|
||||
generic_heli: Object.freeze([5.4997, 0.1604, 0]),
|
||||
generic_plane: Object.freeze([16.5228, 0.712, 0]),
|
||||
glf4: Object.freeze([13.4603, 0.8243, 0]),
|
||||
@@ -53,8 +53,9 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
mq9: Object.freeze([5.8498, -0.062, 0]),
|
||||
p28a: Object.freeze([3.3695, 0.3959, 0]),
|
||||
pc12: Object.freeze([6.6416, 0.5288, 0]),
|
||||
pushback: Object.freeze([3, 0.2499, 0]),
|
||||
pushback: Object.freeze([2.9536, 0.388, 0]),
|
||||
r44: Object.freeze([4.4219, -0.3001, 0]),
|
||||
radio_mast: Object.freeze([1.2, 0, 0]),
|
||||
s76: Object.freeze([6.6001, 0.1915, 0]),
|
||||
sr22: Object.freeze([3.6762, 0.2376, 0]),
|
||||
t38: Object.freeze([7.0246, -0.3791, 0]),
|
||||
@@ -62,5 +63,5 @@ export const FLEET_TRAIL_ANCHORS = Object.freeze({
|
||||
tower: Object.freeze([1.2952, -0.0007, 0]),
|
||||
ultralight: Object.freeze([3.2271, 0.3259, 0]),
|
||||
v22: Object.freeze([7.9868, 0.2956, 0]),
|
||||
van: Object.freeze([2.75, 0.418, 0]),
|
||||
van: Object.freeze([2.695, 0.2812, 0]),
|
||||
});
|
||||
@@ -0,0 +1,42 @@
|
||||
# Wikidata cities pack
|
||||
|
||||
World cities and towns for naming a spot (the nearest city), the places
|
||||
around it and finding a place by name, read by `src/data/wikidataCities.js`. The app reads this file; it
|
||||
does not call Wikidata or any place service for these.
|
||||
|
||||
| File | Contents |
|
||||
|------|----------|
|
||||
| `cities.json` | Human settlements with coordinates and a population at or above the cut-off (see `meta.minPopulation`), largest first |
|
||||
|
||||
Each row is `[name, lat, lon, population, country, wikidata]`: the English
|
||||
label, coordinates to three decimals, the largest stated population, the
|
||||
ISO 3166-1 alpha-2 country code (empty when Wikidata gives none) and the
|
||||
Wikidata id.
|
||||
|
||||
**Source:** Wikidata, read once from the Wikidata Query Service by
|
||||
`scripts/build-wikidata-cities.mjs`. The build time and row count are in the
|
||||
file's `meta` header.
|
||||
|
||||
**License:** CC0 1.0 (https://www.wikidata.org/wiki/Wikidata:Licensing). No
|
||||
attribution is legally required.
|
||||
|
||||
**What is left out:** metropolitan areas, urban agglomerations, conurbations
|
||||
and similar groupings of settlements, so a view is named after the city
|
||||
rather than the area around it (an item of a narrower grouping kind that is
|
||||
also a city stays: Istanbul is a metropolitan municipality and a megacity);
|
||||
places that no longer stand (former entities, ghost towns, abandoned
|
||||
villages, archaeological sites) unless they are also a living settlement;
|
||||
and places Wikidata states as dissolved or abolished (P576) where another
|
||||
place within 15 km still names the spot. A dissolved unit with nothing
|
||||
else near it stays: many of Vietnam's provincial cities ended as units in
|
||||
2025 and still stand under their names. Also left out: places below the population cut-off and
|
||||
places without an English label.
|
||||
|
||||
**Rebuild:** `node scripts/build-wikidata-cities.mjs [--min-population 15000]`.
|
||||
The build runs one query at a time with pauses and honours the service's
|
||||
Retry-After; it takes about ten minutes. It fails if a short list of
|
||||
well-known cities is missing from the result, or a known grouping gets in.
|
||||
|
||||
**Limits:** populations are whatever Wikidata states and differ in date and
|
||||
definition between places (city proper, municipality, urban district). Some
|
||||
districts and suburbs appear as their own rows.
|
||||
@@ -0,0 +1 @@
|
||||
{"meta":{"source":"Wikidata (https://www.wikidata.org), via the Wikidata Query Service","license":"CC0 1.0","built":"2026-11-15T02:59:26.673Z","minPopulation":15000,"count":31827,"columns":["name","lat","lon","population","country","wikidata"]},"rows":[["Chongqing",29.55,106.507,32054159,"CN","Q11725"],["Delhi",28.667,77.217,26495000,"IN","Q1353"],["Shanghai",31.233,121.469,24870895,"CN","Q8686"],["Beijing",39.904,116.408,21893095,"CN","Q956"],["Chengdu",30.66,104.063,20937757,"CN","Q30002"],["Guangzhou",23.13,113.26,18676605,"CN","Q16572"],["Shenzhen",22.547,114.054,17494398,"CN","Q15174"],["Dhaka",23.729,90.394,16800000,"BD","Q1354"],["Istanbul",41.01,28.96,15655924,"TR","Q406"],["Mumbai",19.076,72.877,15414288,"IN","Q1156"],["Karachi",24.86,67.01,14910352,"PK","Q8660"],["Kinshasa",-4.322,15.312,14565700,"CD","Q3838"],["Tokyo",35.689,139.692,14264798,"JP","Q1490"],["Ho Chi Minh City",10.776,106.702,14002598,"VN","Q1854"],["Tianjin",39.147,117.206,13866009,"CN","Q11736"],["Moscow",55.751,37.617,13274285,"RU","Q649"],["Xi'an",34.261,108.942,12952907,"CN","Q5826"],["Suzhou",31.3,120.619,12748262,"CN","Q42622"],["Zhengzhou",34.749,113.661,12600574,"CN","Q30340"],["Bengaluru",12.979,77.591,12327000,"IN","Q1355"],["Wuhan",30.595,114.297,12326518,"CN","Q11746"],["Hangzhou",30.25,120.168,11936010,"CN","Q4970"],["Baoding",38.867,115.485,11544036,"CN","Q58584"],["São Paulo",-23.55,-46.634,11451999,"BR","Q174"],["Jakarta",-6.175,106.827,11135191,"ID","Q3630"],["Lahore",31.55,74.344,11126285,"PK","Q11739"],["Linyi",35.104,118.35,11018365,"CN","Q373346"],["Shijiazhuang",38.042,114.51,10640458,"CN","Q58401"],["Dongguan",23.047,113.749,10466625,"CN","Q59218"],["Qingdao",36.117,120.4,10071722,"CN","Q170322"],["Changsha",28.199,112.971,10047914,"CN","Q174091"],["Harbin",45.75,126.633,10009854,"CN","Q42956"],["Lima",-12.06,-77.037,9943800,"PE","Q2868"],["Cairo",30.044,31.236,9801536,"EG","Q85"],["Nanyang",32.999,112.529,9713112,"CN","Q404763"],["Seoul",37.56,126.99,9668465,"KR","Q8684"],["Tokyo",35.684,139.774,9640742,"JP","Q7473516"],["Wenzhou",27.999,120.656,9572903,"CN","Q42635"],["Foshan",23.029,113.106,9498863,"CN","Q34412"],["Handan",36.612,114.489,9413990,"CN","Q58570"],["Ningbo",29.875,121.549,9404283,"CN","Q42780"],["Weifang",36.717,119.1,9386705,"CN","Q217698"],["Hefei",31.864,117.281,9369881,"CN","Q185684"],["Nanjing",32.061,118.779,9314685,"CN","Q16666"],["Mexico City",19.354,-99.136,9209944,"MX","Q1489"],["Jinan",36.667,116.983,9202432,"CN","Q170247"],["Hyderabad",17.362,78.475,9191000,"IN","Q1361"],["Xuzhou",34.261,117.186,9083790,"CN","Q57719"],["Shenyang",41.803,123.428,9070093,"CN","Q11720"],["Changchun",43.88,125.323,9066906,"CN","Q92161"],["Zhoukou",33.625,114.642,9026015,"CN","Q198061"],["Kuala Lumpur",3.148,101.695,9000280,"MY","Q1865"],["Ganzhou",25.829,114.934,8970014,"CN","Q363166"],["New York City",40.713,-74.006,8804190,"US","Q60"],["London",51.507,-0.128,8799728,"GB","Q84"],["Heze",35.233,115.433,8795939,"CN","Q332753"],["Quanzhou",24.914,118.586,8782285,"CN","Q68695"],["Nanning",22.819,108.315,8741584,"CN","Q179608"],["Hanoi",21.024,105.841,8717600,"VN","Q1858"],["Tehran",35.689,51.39,8693706,"IR","Q3616"],["Kunming",25.043,102.706,8460088,"CN","Q182852"],["Jining",35.4,116.567,8357897,"CN","Q372791"],["Fuzhou",26.077,119.292,8291268,"CN","Q68481"],["Fuyang",32.899,115.804,8200264,"CN","Q360584"],["Baghdad",33.315,44.366,8126755,"IQ","Q1530"],["Veracruz",19.19,-96.153,8062579,"MX","Q173270"],["Bogotá",4.61,-74.082,8034649,"CO","Q2841"],["Shangqiu",34.426,115.647,7816831,"CN","Q404817"],["Nantong",31.983,120.887,7726635,"CN","Q57947"],["Tangshan",39.629,118.174,7717983,"CN","Q58422"],["Ahmedabad",23.022,72.58,7645000,"IN","Q1070"],["Wuxi",31.567,120.283,7462135,"CN","Q42651"],["Dalian",38.9,121.6,7450785,"CN","Q74881"],["Hong Kong",22.278,114.159,7413070,"CN","Q8646"],["Cangzhou",38.304,116.845,7300783,"CN","Q58695"],["Xingtai",37.066,114.475,7111106,"CN","Q58576"],["Yantai",37.464,121.448,7102116,"CN","Q210493"],["Luoyang",34.659,112.424,7056699,"CN","Q187136"],["Jinhua",29.105,119.649,7050683,"CN","Q58210"],["Riyadh",24.638,46.715,7009100,"SA","Q3692"],["Zhumadian",32.977,114.025,7008427,"CN","Q198240"],["Zhanjiang",21.197,110.403,6981236,"CN","Q59144"],["Bijie",27.302,105.286,6899636,"CN","Q486319"],["Yangon",16.795,96.16,6874000,"MM","Q37995"],["Yancheng",33.35,120.157,6709629,"CN","Q57866"],["Hengyang",26.897,112.586,6645243,"CN","Q144663"],["Taizhou",28.658,121.422,6622888,"CN","Q58273"],["Zunyi",27.705,106.934,6606675,"CN","Q28994"],["Chennai",13.082,80.275,6599000,"IN","Q1352"],["Shaoyang",27.242,111.472,6563520,"CN","Q194531"],["Shangrao",28.442,117.963,6491088,"CN","Q363479"],["Huanggang",30.45,114.875,6333000,"CN","Q71355"],["Moro",-6,144,6310129,"PG","Q103927888"],["Santiago",-33.438,-70.65,6257516,"CL","Q2887"],["Nanchang",28.684,115.887,6255007,"CN","Q171943"],["Xinxiang",35.299,113.885,6251929,"CN","Q404362"],["Xinyang",32.126,114.067,6234401,"CN","Q404873"],["Rio de Janeiro",-2Line truncated
|
||||
@@ -57,7 +57,14 @@ test('every typed aircraft renders at its published length, a real-world aircraf
|
||||
);
|
||||
// A grounded aircraft stands on its wheels: its origin the scaled
|
||||
// clearance above the ground, never below it.
|
||||
assert.ok(spec.clearanceM > 0, `${type}: clearance ${spec.clearanceM}`);
|
||||
// A model built standing on its origin (a ground vehicle, a ground
|
||||
// station's mast: its lowest point at z 0) has no clearance.
|
||||
if (set.catalog[model].min[2] > -0.05)
|
||||
assert.ok(
|
||||
spec.clearanceM >= 0 && spec.clearanceM < 0.05 * spec.scale,
|
||||
`${type}: built standing, clearance ${spec.clearanceM}`,
|
||||
);
|
||||
else assert.ok(spec.clearanceM > 0, `${type}: clearance ${spec.clearanceM}`);
|
||||
assert.ok(spec.clearanceM < radius, `${type}: clearance larger than the aircraft`);
|
||||
}
|
||||
}
|
||||
@@ -296,3 +303,41 @@ test('a layer asking every tick gets one cached spec per type and category', asy
|
||||
assert.notEqual(aircraftLayerModelSpec({ typeCode: 'B744' }, set), a);
|
||||
assert.ok(Object.isFrozen(a));
|
||||
});
|
||||
|
||||
test('an airport vehicle is cached by its callsign; other aircraft by type and category only', async () => {
|
||||
const { aircraftLayerModelSpec, aircraftModelSpecCacheKey } = await import(
|
||||
'../layers/flights/modelSpec.js'
|
||||
);
|
||||
const tender = aircraftLayerModelSpec(
|
||||
{ typeCode: 'ZVEH', callsign: 'FIRE 2' },
|
||||
set,
|
||||
);
|
||||
const car = aircraftLayerModelSpec(
|
||||
{ typeCode: 'ZVEH', callsign: 'LEADER 7' },
|
||||
set,
|
||||
);
|
||||
assert.equal(tender.model, 'fire_truck');
|
||||
assert.equal(car.model, 'car');
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'A320', callsign: 'BAW1' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'A320', callsign: 'DLH2' }, set),
|
||||
);
|
||||
assert.notEqual(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 2' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'LEADER 7' }, set),
|
||||
);
|
||||
// Keyed by the rule matched, not the callsign: at most one entry per rule
|
||||
// and one for the type's own model.
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 2' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'FIRE 9' }, set),
|
||||
);
|
||||
assert.equal(
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'LEADER 7' }, set),
|
||||
aircraftModelSpecCacheKey({ typeCode: 'ZVEH', callsign: 'ASD' }, set),
|
||||
);
|
||||
assert.equal(
|
||||
aircraftLayerModelSpec({ typeCode: 'ZVEH', callsign: 'FIRE 9' }, set),
|
||||
tender,
|
||||
);
|
||||
});
|
||||
@@ -0,0 +1,131 @@
|
||||
/**
|
||||
* A host-supplied placement provider: an application embedding the catalog
|
||||
* may decide where its moving contacts are drawn while live. Each layer that
|
||||
* takes one tells it every fix it accepts (`observe`) and asks it, each time
|
||||
* it draws a contact, where to draw it now (`place`). A layer given none, or
|
||||
* asking about a contact the provider does not place (`null`), draws the
|
||||
* contact with its own motion, exactly as without a provider. A provider
|
||||
* that throws is treated as having no answer for that call.
|
||||
*
|
||||
* Layers consult a provider only while live: following the world clock, the
|
||||
* layer's own motion places every contact.
|
||||
*
|
||||
* @typedef {'aircraft'|'military'|'vessels'|'transit'|'rail'} PlacementKind
|
||||
*
|
||||
* @typedef {object} PlacementFix
|
||||
* @property {number} timeMs The fix's own time, Unix ms.
|
||||
* @property {number} lat
|
||||
* @property {number} lon
|
||||
* @property {number} [altitudeM] The height the layer draws the fix at,
|
||||
* metres above the ellipsoid; NaN when the layer keeps its own height.
|
||||
* @property {number} [speedMps] Reported ground speed, NaN for none.
|
||||
* @property {number} [courseDeg] Reported course over ground, NaN for none.
|
||||
* @property {number} [headingDeg] Reported heading, NaN for none.
|
||||
* @property {boolean} [onGround] Reported on the ground (aircraft).
|
||||
* @property {string} [feedId] The feed the contact belongs to (transit, rail).
|
||||
*
|
||||
* @typedef {object} Placement
|
||||
* @property {number} lat
|
||||
* @property {number} lon
|
||||
* @property {number} altitudeM Metres above the ellipsoid, as the observed
|
||||
* fixes' `altitudeM`; NaN keeps the layer's own height.
|
||||
* @property {number} courseDeg Direction of travel, NaN for none.
|
||||
* @property {number} speedMps NaN for none.
|
||||
* @property {boolean} extrapolating Past the contact's newest fix.
|
||||
*
|
||||
* @typedef {object} LayerPlacement What a layer is handed: never throws.
|
||||
* @property {(id: string, fix: PlacementFix) => void} observe
|
||||
* @property {(id: string, wallMs: number) => Placement|null} place The
|
||||
* answer is one object reused by every call: read it before the next.
|
||||
* @property {(id: string) => void} forget The contact left the layer.
|
||||
*
|
||||
* @typedef {object} PlacementProvider
|
||||
* @property {(kind: PlacementKind) => object|null|undefined} layer The
|
||||
* placement for one kind of contact: an object with `place(id, wallMs)`
|
||||
* and optionally `observe(id, fix)` and `forget(id)`, or null to leave that
|
||||
* kind to its layer's own motion.
|
||||
*/
|
||||
|
||||
/** The kinds of contact a provider may place. */
|
||||
export const PLACEMENT_KINDS = Object.freeze([
|
||||
'aircraft',
|
||||
'military',
|
||||
'vessels',
|
||||
'transit',
|
||||
'rail',
|
||||
]);
|
||||
|
||||
const finiteOr = (value, fallback) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : fallback;
|
||||
|
||||
/**
|
||||
* One kind's placement from a provider, guarded so a layer can call it every
|
||||
* frame: null when there is no provider or it does not place `kind`.
|
||||
* @param {PlacementProvider|null|undefined} provider
|
||||
* @param {PlacementKind} kind
|
||||
* @returns {LayerPlacement|null}
|
||||
*/
|
||||
export function layerPlacement(provider, kind) {
|
||||
if (!PLACEMENT_KINDS.includes(kind))
|
||||
throw new TypeError(`Unknown placement kind: ${kind}`);
|
||||
if (provider == null) return null;
|
||||
if (typeof provider.layer !== 'function')
|
||||
throw new TypeError('A placement provider needs a layer(kind) function');
|
||||
const placement = provider.layer(kind);
|
||||
if (placement == null) return null;
|
||||
if (typeof placement.place !== 'function')
|
||||
throw new TypeError(`The ${kind} placement needs a place(id, wallMs)`);
|
||||
const observe =
|
||||
typeof placement.observe === 'function' ? placement.observe : null;
|
||||
const forget =
|
||||
typeof placement.forget === 'function' ? placement.forget : null;
|
||||
// Asked for every drawn contact every frame: one answer, reused.
|
||||
const answer = {
|
||||
lat: NaN,
|
||||
lon: NaN,
|
||||
altitudeM: NaN,
|
||||
courseDeg: NaN,
|
||||
speedMps: NaN,
|
||||
extrapolating: false,
|
||||
};
|
||||
return Object.freeze({
|
||||
observe(id, fix) {
|
||||
if (!observe) return;
|
||||
try {
|
||||
observe.call(placement, id, fix);
|
||||
} catch {
|
||||
// A provider that fails to take a fix only answers less.
|
||||
}
|
||||
},
|
||||
place(id, wallMs) {
|
||||
let placed;
|
||||
try {
|
||||
placed = placement.place(id, wallMs);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
if (
|
||||
!placed ||
|
||||
!Number.isFinite(placed.lat) ||
|
||||
!Number.isFinite(placed.lon) ||
|
||||
Math.abs(placed.lat) > 90
|
||||
)
|
||||
return null;
|
||||
answer.lat = placed.lat;
|
||||
answer.lon = placed.lon;
|
||||
answer.altitudeM = finiteOr(placed.altitudeM, NaN);
|
||||
answer.courseDeg = finiteOr(placed.courseDeg, NaN);
|
||||
answer.speedMps = finiteOr(placed.speedMps, NaN);
|
||||
answer.extrapolating = placed.extrapolating === true;
|
||||
return answer;
|
||||
},
|
||||
forget(id) {
|
||||
if (!forget) return;
|
||||
try {
|
||||
forget.call(placement, id);
|
||||
} catch {
|
||||
// Nothing to undo.
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { PLACEMENT_KINDS, layerPlacement } from './placementProvider.js';
|
||||
|
||||
test('no provider, or a provider that leaves a kind alone, gives no placement', () => {
|
||||
for (const kind of PLACEMENT_KINDS) {
|
||||
assert.equal(layerPlacement(null, kind), null);
|
||||
assert.equal(layerPlacement(undefined, kind), null);
|
||||
assert.equal(layerPlacement({ layer: () => null }, kind), null);
|
||||
}
|
||||
assert.throws(() => layerPlacement(null, 'satellites'), TypeError);
|
||||
assert.throws(() => layerPlacement({}, 'aircraft'), TypeError);
|
||||
assert.throws(
|
||||
() => layerPlacement({ layer: () => ({ observe() {} }) }, 'aircraft'),
|
||||
TypeError,
|
||||
);
|
||||
});
|
||||
|
||||
test('a placement is asked by id and wall time, and its answer is checked', () => {
|
||||
const asked = [];
|
||||
const seen = [];
|
||||
const forgotten = [];
|
||||
const answers = new Map([
|
||||
[
|
||||
'a',
|
||||
{ lat: 51.5, lon: -0.1, altitudeM: 900, courseDeg: 270, speedMps: 80 },
|
||||
],
|
||||
['partial', { lat: 10, lon: 20, altitudeM: 'high', extrapolating: true }],
|
||||
['off-globe', { lat: 91, lon: 0 }],
|
||||
['nan', { lat: NaN, lon: 0 }],
|
||||
]);
|
||||
const provider = {
|
||||
layer: (kind) =>
|
||||
kind === 'aircraft'
|
||||
? {
|
||||
observe: (id, fix) => seen.push([id, fix.timeMs]),
|
||||
place(id, wallMs) {
|
||||
asked.push([id, wallMs]);
|
||||
return answers.get(id) ?? null;
|
||||
},
|
||||
forget: (id) => forgotten.push(id),
|
||||
}
|
||||
: null,
|
||||
};
|
||||
assert.equal(layerPlacement(provider, 'vessels'), null);
|
||||
const placement = layerPlacement(provider, 'aircraft');
|
||||
placement.observe('a', { timeMs: 5, lat: 0, lon: 0 });
|
||||
assert.deepEqual(seen, [['a', 5]]);
|
||||
const placed = placement.place('a', 1000);
|
||||
assert.deepEqual(
|
||||
{ ...placed },
|
||||
{
|
||||
lat: 51.5,
|
||||
lon: -0.1,
|
||||
altitudeM: 900,
|
||||
courseDeg: 270,
|
||||
speedMps: 80,
|
||||
extrapolating: false,
|
||||
},
|
||||
);
|
||||
const partial = placement.place('partial', 2000);
|
||||
assert.equal(partial, placed, 'one answer object, reused');
|
||||
assert.ok(Number.isNaN(partial.altitudeM));
|
||||
assert.ok(Number.isNaN(partial.courseDeg));
|
||||
assert.ok(Number.isNaN(partial.speedMps));
|
||||
assert.equal(partial.extrapolating, true);
|
||||
assert.equal(placement.place('off-globe', 3000), null);
|
||||
assert.equal(placement.place('nan', 3000), null);
|
||||
assert.equal(placement.place('unknown', 3000), null);
|
||||
assert.deepEqual(
|
||||
asked.map(([id]) => id),
|
||||
['a', 'partial', 'off-globe', 'nan', 'unknown'],
|
||||
);
|
||||
placement.forget('a');
|
||||
assert.deepEqual(forgotten, ['a']);
|
||||
});
|
||||
|
||||
test('a provider that throws has no answer, and observe and forget are optional', () => {
|
||||
const placement = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place() {
|
||||
throw new Error('not ready');
|
||||
},
|
||||
}),
|
||||
},
|
||||
'transit',
|
||||
);
|
||||
assert.equal(placement.place('x', 0), null);
|
||||
assert.doesNotThrow(() => placement.observe('x', { timeMs: 0 }));
|
||||
assert.doesNotThrow(() => placement.forget('x'));
|
||||
const failing = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place: () => null,
|
||||
observe() {
|
||||
throw new Error('full');
|
||||
},
|
||||
forget() {
|
||||
throw new Error('gone');
|
||||
},
|
||||
}),
|
||||
},
|
||||
'rail',
|
||||
);
|
||||
assert.doesNotThrow(() => failing.observe('x', { timeMs: 0 }));
|
||||
assert.doesNotThrow(() => failing.forget('x'));
|
||||
});
|
||||
@@ -1244,7 +1244,15 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
|
||||
assert.equal(worldClock.coverage(), null, 'nothing loaded, no time to show');
|
||||
await rocketLaunchesLayer.update();
|
||||
const at = Date.parse(launchTime);
|
||||
assert.deepEqual(worldClock.coverage(), { start: at, end: at, marks: [at] });
|
||||
// The launch is a mark labelled with its mission's name.
|
||||
assert.deepEqual(worldClock.coverage(), {
|
||||
start: at,
|
||||
end: at,
|
||||
marks: [at],
|
||||
markDetails: [
|
||||
{ time: at, label: 'GAUNTLET PAYLOAD', id: 'mission-runtime', kind: 'launch' },
|
||||
],
|
||||
});
|
||||
assert.equal(worldClock.isSupported(), true, 'loaded launches bring up the timeline');
|
||||
|
||||
const entities = dataSources[0].entities.values;
|
||||
|
||||
@@ -0,0 +1,171 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
mergeTimelineRuns,
|
||||
readTimelineFixes,
|
||||
TIMELINE_UNSEEN_MS,
|
||||
} from '../time/timelineFixes.js';
|
||||
|
||||
/** Fixes nearer than this are too close to read a course between. */
|
||||
const COURSE_MIN_M = 5;
|
||||
const EARTH_RADIUS_M = 6_371_000;
|
||||
|
||||
/** The initial great-circle course from one fix to another (degrees from
|
||||
* north), or null when they are too close to tell. */
|
||||
function courseBetween(from, to) {
|
||||
const lat1 = Cesium.Math.toRadians(from.lat);
|
||||
const lat2 = Cesium.Math.toRadians(to.lat);
|
||||
const dLon = Cesium.Math.toRadians(to.lon - from.lon);
|
||||
const dLat = lat2 - lat1;
|
||||
const a =
|
||||
Math.sin(dLat / 2) ** 2 +
|
||||
Math.cos(lat1) * Math.cos(lat2) * Math.sin(dLon / 2) ** 2;
|
||||
if (2 * EARTH_RADIUS_M * Math.asin(Math.min(1, Math.sqrt(a))) < COURSE_MIN_M)
|
||||
return null;
|
||||
const y = Math.sin(dLon) * Math.cos(lat2);
|
||||
const x =
|
||||
Math.cos(lat1) * Math.sin(lat2) -
|
||||
Math.sin(lat1) * Math.cos(lat2) * Math.cos(dLon);
|
||||
return (Cesium.Math.toDegrees(Math.atan2(y, x)) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's motion history with the fixes its record carries at a time
|
||||
* (`observation.fixes`, see src/time/timelineFixes.js) merged in, so the
|
||||
* layer places it on its own track at any time they span; null when the
|
||||
* record carries none. Each fix is drawn at the record's render height,
|
||||
* moved by the fix's own barometric change from the record's, and heads
|
||||
* where its track goes next (the last, where it came from). Entries are
|
||||
* marked `timeline`.
|
||||
* @param {object[]|undefined} history The contact's history entries.
|
||||
* @param {object} observation The record, with `fixes` and `baroAltitudeM`.
|
||||
* @param {{renderAltitudeM: number, renderAltitudeInvented?: boolean}} meta
|
||||
* @param {number|null} velocity The record's ground speed (m/s).
|
||||
* @param {number} centreMs The snapshot's time: the fixes kept are nearest it.
|
||||
* @returns {object[]|null}
|
||||
*/
|
||||
export function mergeAircraftTimelineFixes(
|
||||
history,
|
||||
observation,
|
||||
meta,
|
||||
velocity,
|
||||
centreMs,
|
||||
) {
|
||||
const fixes = readTimelineFixes(observation?.fixes);
|
||||
if (!fixes) return null;
|
||||
const baroM = Number.isFinite(observation.baroAltitudeM)
|
||||
? observation.baroAltitudeM
|
||||
: null;
|
||||
const entries = fixes.map((fix, index) => {
|
||||
const course =
|
||||
index + 1 < fixes.length
|
||||
? courseBetween(fix, fixes[index + 1])
|
||||
: courseBetween(fixes[index - 1], fix);
|
||||
return {
|
||||
time: Cesium.JulianDate.fromDate(new Date(fix.atMs)),
|
||||
epochMs: fix.atMs,
|
||||
position: Cesium.Cartesian3.fromDegrees(
|
||||
fix.lon,
|
||||
fix.lat,
|
||||
baroM !== null && fix.altitudeM !== null
|
||||
? meta.renderAltitudeM + (fix.altitudeM - baroM)
|
||||
: meta.renderAltitudeM,
|
||||
),
|
||||
velocity,
|
||||
// No reported track per fix: the course is read from the fixes.
|
||||
track: course ?? undefined,
|
||||
inventedHeight: meta.renderAltitudeInvented === true,
|
||||
timeline: true,
|
||||
};
|
||||
});
|
||||
return mergeTimelineRuns(
|
||||
history ?? [],
|
||||
entries,
|
||||
(entry) => entry.epochMs,
|
||||
centreMs,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The index of the first history entry at or after `renderTime` (the last
|
||||
* entry when none is), by halving: a contact following the clock keeps up to
|
||||
* TIMELINE_FIXES_LIMIT entries, and it is placed on every fleet tick. The
|
||||
* bracketing pair is the entry before it and it.
|
||||
* @param {Array<{time: Cesium.JulianDate}>} history In time order.
|
||||
* @param {Cesium.JulianDate} renderTime
|
||||
* @returns {number}
|
||||
*/
|
||||
export function historyBracketIndex(history, renderTime) {
|
||||
let low = 0;
|
||||
let high = history.length - 1;
|
||||
while (low < high) {
|
||||
const mid = (low + high) >> 1;
|
||||
if (Cesium.JulianDate.lessThan(history[mid].time, renderTime))
|
||||
low = mid + 1;
|
||||
else high = mid;
|
||||
}
|
||||
return low;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a contact following the clock is not to be drawn at `renderTime`:
|
||||
* its history is its own fixes around the time (`timeline` entries), and the
|
||||
* time is more than TIMELINE_UNSEEN_MS before the first, when it was not
|
||||
* there yet.
|
||||
* @param {Array<{time: Cesium.JulianDate, timeline?: boolean}>|undefined} history
|
||||
* @param {Cesium.JulianDate} renderTime
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function historyUnseenAt(history, renderTime) {
|
||||
const first = history?.[0];
|
||||
return (
|
||||
first?.timeline === true &&
|
||||
Cesium.JulianDate.secondsDifference(first.time, renderTime) >
|
||||
TIMELINE_UNSEEN_MS / 1000
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Lift a grounded contact's history onto the floor: its newest fix to
|
||||
* `position`, or, when the history is its own fixes around the time
|
||||
* (`timeline` entries, the newest of them later than the time drawn), every
|
||||
* fix by the lift from `fromM` to `toM`, so it is not drawn rising to it.
|
||||
* @param {object[]|undefined} history
|
||||
* @param {Cesium.Cartesian3} position The newest fix lifted.
|
||||
* @param {number|null} fromM The height it was drawn at.
|
||||
* @param {number} toM The height it is lifted to.
|
||||
*/
|
||||
export function liftGroundedHistory(history, position, fromM, toM) {
|
||||
const newest = history?.[history.length - 1];
|
||||
if (!newest) return;
|
||||
if (history[0].timeline !== true || !Number.isFinite(fromM)) {
|
||||
newest.position = Cesium.Cartesian3.clone(position, newest.position);
|
||||
return;
|
||||
}
|
||||
for (const entry of history) {
|
||||
const carto = Cesium.Cartographic.fromCartesian(entry.position);
|
||||
if (!carto) continue;
|
||||
entry.position = Cesium.Cartesian3.fromRadians(
|
||||
carto.longitude,
|
||||
carto.latitude,
|
||||
carto.height + (toM - fromM),
|
||||
undefined,
|
||||
entry.position,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The history entries a tracked contact's trail has yet to take: those after
|
||||
* its newest point (`trail` entries have `timeMs`) up to `untilMs`, the
|
||||
* snapshot's time, so the trail grows as the snapshots bring fixes.
|
||||
* @param {Array<{epochMs: number}>} history
|
||||
* @param {Array<{timeMs: number}>} trail
|
||||
* @param {number} untilMs
|
||||
* @returns {object[]}
|
||||
*/
|
||||
export function historyAfterTrail(history, trail, untilMs) {
|
||||
const lastMs = trail.length ? trail[trail.length - 1].timeMs : -Infinity;
|
||||
return history.filter(
|
||||
(entry) => entry.epochMs > lastMs && entry.epochMs <= untilMs,
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
historyAfterTrail,
|
||||
historyBracketIndex,
|
||||
historyUnseenAt,
|
||||
liftGroundedHistory,
|
||||
mergeAircraftTimelineFixes,
|
||||
} from './timelineHistory.js';
|
||||
|
||||
const META = { renderAltitudeM: 3_000 };
|
||||
const fix = (atMs, lat, altitudeM = null, lon = 0) => ({
|
||||
atMs,
|
||||
lat,
|
||||
lon,
|
||||
altitudeM,
|
||||
});
|
||||
const julian = (ms) => Cesium.JulianDate.fromDate(new Date(ms));
|
||||
|
||||
test('an aircraft with no fixes merges nothing', () => {
|
||||
assert.equal(
|
||||
mergeAircraftTimelineFixes([], { fixes: null }, META, 100, 0),
|
||||
null,
|
||||
);
|
||||
});
|
||||
|
||||
test("an aircraft's fixes join its history in order, each at the render height moved by its own climb", () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
baroAltitudeM: 1_000,
|
||||
fixes: [fix(120_000, 1, 1_200), fix(60_000, 0, 1_000), fix(180_000, 2)],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
history.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000],
|
||||
);
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
assert.ok(Math.abs(height(history[0]) - 3_000) < 1e-3);
|
||||
assert.ok(Math.abs(height(history[1]) - 3_200) < 1e-3);
|
||||
assert.ok(
|
||||
Math.abs(height(history[2]) - 3_000) < 1e-3,
|
||||
'no altitude: the render height',
|
||||
);
|
||||
// A later snapshot's fixes add to the earlier ones.
|
||||
const more = mergeAircraftTimelineFixes(
|
||||
history,
|
||||
{ baroAltitudeM: 1_000, fixes: [fix(180_000, 2), fix(240_000, 3)] },
|
||||
META,
|
||||
100,
|
||||
180_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
more.map((entry) => entry.epochMs),
|
||||
[60_000, 120_000, 180_000, 240_000],
|
||||
);
|
||||
});
|
||||
|
||||
test('the bracketing entry is the first at or after the time, else the last', () => {
|
||||
const history = [1_000, 2_000, 3_000].map((ms) => ({
|
||||
time: Cesium.JulianDate.fromDate(new Date(ms)),
|
||||
}));
|
||||
const at = (ms) =>
|
||||
historyBracketIndex(history, Cesium.JulianDate.fromDate(new Date(ms)));
|
||||
assert.equal(at(500), 0);
|
||||
assert.equal(at(1_000), 0);
|
||||
assert.equal(at(1_500), 1);
|
||||
assert.equal(at(3_000), 2);
|
||||
assert.equal(at(9_000), 2);
|
||||
});
|
||||
|
||||
test('each fix heads where the track goes next, the last where it came from', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{
|
||||
fixes: [
|
||||
fix(0, 0, null, 0),
|
||||
fix(60_000, 0, null, 0.01),
|
||||
fix(120_000, 0.01, null, 0.01),
|
||||
fix(180_000, 0.01, null, 0.01),
|
||||
],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
0,
|
||||
);
|
||||
const tracks = history.map((entry) => entry.track);
|
||||
assert.ok(Math.abs(tracks[0] - 90) < 0.5, 'east');
|
||||
assert.ok(Math.abs(tracks[1]) < 0.5, 'north');
|
||||
assert.equal(tracks[2], undefined, 'no move to read');
|
||||
assert.equal(tracks[3], undefined);
|
||||
assert.ok(history.every((entry) => entry.timeline === true));
|
||||
});
|
||||
|
||||
test('a contact is unseen only well before the first of its own fixes', () => {
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(600_000, 0), fix(660_000, 1)] },
|
||||
META,
|
||||
100,
|
||||
600_000,
|
||||
);
|
||||
assert.equal(historyUnseenAt(history, julian(0)), true);
|
||||
assert.equal(historyUnseenAt(history, julian(560_000)), false);
|
||||
const live = [{ time: julian(600_000) }];
|
||||
assert.equal(historyUnseenAt(live, julian(0)), false, 'not on its fixes');
|
||||
assert.equal(historyUnseenAt(undefined, julian(0)), false);
|
||||
});
|
||||
|
||||
test('a grounded contact on its own fixes is lifted whole; else its newest fix', () => {
|
||||
const height = (entry) =>
|
||||
Cesium.Cartographic.fromCartesian(entry.position).height;
|
||||
const history = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 0.001)] },
|
||||
{ renderAltitudeM: 5 },
|
||||
0,
|
||||
0,
|
||||
);
|
||||
const lifted = Cesium.Cartesian3.fromDegrees(0, 0.001, 30);
|
||||
liftGroundedHistory(history, lifted, 5, 30);
|
||||
assert.ok(history.every((entry) => Math.abs(height(entry) - 30) < 1e-3));
|
||||
const live = [
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0, 5) },
|
||||
{ position: Cesium.Cartesian3.fromDegrees(0, 0.001, 5) },
|
||||
];
|
||||
liftGroundedHistory(live, lifted, 5, 30);
|
||||
assert.ok(Math.abs(height(live[0]) - 5) < 1e-3);
|
||||
assert.ok(Math.abs(height(live[1]) - 30) < 1e-3);
|
||||
});
|
||||
|
||||
test("a tracked trail takes the fixes after its newest point, up to the snapshot's time", () => {
|
||||
const history = [0, 60_000, 120_000, 180_000].map((epochMs) => ({ epochMs }));
|
||||
assert.deepEqual(
|
||||
historyAfterTrail(history, [{ timeMs: 60_000 }], 120_000).map(
|
||||
(entry) => entry.epochMs,
|
||||
),
|
||||
[120_000],
|
||||
);
|
||||
assert.equal(historyAfterTrail(history, [], 120_000).length, 3);
|
||||
});
|
||||
@@ -1,6 +1,8 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFrameWait } from '../time/frameWait.js';
|
||||
|
||||
const MAX_FRAME_ATTEMPTS = 120;
|
||||
/** Drawn time (ms) to wait for the tracked entity's first position. */
|
||||
const MAX_POSITION_WAIT_MS = 2_000;
|
||||
const MIN_TRACKED_RANGE_M = 150;
|
||||
const ZOOM_INERTIA_STATES = new WeakMap();
|
||||
|
||||
@@ -154,7 +156,7 @@ export function clampTrackedCameraPosition(
|
||||
*/
|
||||
export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
if (!viewer || !entity || !viewFrom) return;
|
||||
let attempts = 0;
|
||||
const positionWait = createFrameWait(MAX_POSITION_WAIT_MS);
|
||||
const trackedTransform = new Cesium.Matrix4();
|
||||
const trackedPosition = new Cesium.Cartesian3();
|
||||
const resolvedViewFrom = new Cesium.Cartesian3();
|
||||
@@ -184,7 +186,6 @@ export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
stop();
|
||||
return;
|
||||
}
|
||||
attempts += framed ? 0 : 1;
|
||||
// Prefer the display cache exposed by the flight layer. Calling the
|
||||
// CallbackProperty from preUpdate can advance dead reckoning again while
|
||||
// Cesium's billboard/label still holds the prior visualizer sample. At a
|
||||
@@ -198,7 +199,7 @@ export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
|
||||
trackedPosition,
|
||||
);
|
||||
if (!position) {
|
||||
if (attempts >= MAX_FRAME_ATTEMPTS) stop();
|
||||
if (positionWait.tick()) stop();
|
||||
return;
|
||||
}
|
||||
const transform = Cesium.Transforms.eastNorthUpToFixedFrame(
|
||||
|
||||
@@ -291,7 +291,7 @@ test('tracking layers write gevLabelModel and expose only their cached display p
|
||||
assert.equal(sources['satellites.js'].includes('_trackedEntity.label.text'), false);
|
||||
});
|
||||
|
||||
test('civilian and military trail heads use the lower-centre model anchor and weak-texture tint', async () => {
|
||||
test('civilian and military trail heads use the lower-centre model anchor', async () => {
|
||||
const files = await Promise.all(['flights.js', 'militaryFlights.js'].map(async (name) => (
|
||||
[name, readLayerSource(new URL(`./${name}`, import.meta.url))]
|
||||
)));
|
||||
@@ -300,7 +300,5 @@ test('civilian and military trail heads use the lower-centre model anchor and we
|
||||
(/const\s*head\s*=\s*(?:parts\.motion\.)?_trackedTrailCached\(\s*,?\s*\)\s*\|\|\s*(?:parts\.motion\.)?_trackedDisplayPosition\(\s*(?:flightState\.)?_trackedIcao,?\s*\);/).test(source),
|
||||
`${name} trail head uses the dedicated lower-centre model anchor`,
|
||||
);
|
||||
assert.ok(source.includes('const MODEL_COLOR_BLEND_AMOUNT = 0.94;'),
|
||||
`${name} keeps diffuse texture contribution weak through code-side MIX`);
|
||||
}
|
||||
});
|
||||
@@ -33,6 +33,7 @@
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { registerPickOwner } from './pickRegistry.js';
|
||||
import { createFrameWait } from '../time/frameWait.js';
|
||||
|
||||
// Round 6: trail ENTITIES are pickable (the old Primitive had
|
||||
// allowPicking:false). A trail hugs its aircraft, so an unclaimed pick would
|
||||
@@ -58,9 +59,9 @@ const MIN_SEGMENT_DISTANCE_SQ = 0.01;
|
||||
const NO_POSITIONS = Object.freeze([]);
|
||||
/** @constant {number} Points per chunk; adjacent chunks share one point. */
|
||||
export const CHUNK_POINTS = 128;
|
||||
/** @constant {number} Visible frames a frozen chunk's stand-in waits for its
|
||||
* static geometry before it is dropped anyway. */
|
||||
const STAND_IN_MAX_FRAMES = 600;
|
||||
/** @constant {number} Drawn time (ms) a frozen chunk's stand-in waits for its
|
||||
* static geometry while the trail is shown before it is dropped anyway. */
|
||||
const STAND_IN_MAX_MS = 10_000;
|
||||
|
||||
/**
|
||||
* Create an always-visible polyline trail bound to a viewer.
|
||||
@@ -80,7 +81,7 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
const depthFailMaterial = baseColor.withAlpha(TRAIL_OCCLUDED_ALPHA);
|
||||
let destroyed = false;
|
||||
let visible = true;
|
||||
/** @type {{positions: Cesium.Cartesian3[], entity: Cesium.Entity, standIn: boolean, frames: number}[]} */
|
||||
/** @type {{positions: Cesium.Cartesian3[], entity: Cesium.Entity, standIn: boolean, wait: {tick: () => boolean, pause: () => void}}[]} */
|
||||
let frozen = [];
|
||||
/** Newest chunk of the newest segment: the only part that changes. */
|
||||
let tail = NO_POSITIONS;
|
||||
@@ -152,9 +153,11 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
function staticReady(chunk) {
|
||||
const display = viewer.dataSourceDisplay;
|
||||
if (typeof display?.getBoundingSphere !== 'function') return true;
|
||||
if (!visible) return false;
|
||||
chunk.frames += 1;
|
||||
if (chunk.frames > STAND_IN_MAX_FRAMES) return true;
|
||||
if (!visible) {
|
||||
chunk.wait.pause();
|
||||
return false;
|
||||
}
|
||||
if (chunk.wait.tick()) return true;
|
||||
try {
|
||||
return (
|
||||
display.getBoundingSphere(chunk.entity, false, scratchSphere) ===
|
||||
@@ -262,7 +265,7 @@ export function createTrail(viewer, { color, width = 2.5 }) {
|
||||
positions,
|
||||
entity: addEntity(positions),
|
||||
standIn: true,
|
||||
frames: 0,
|
||||
wait: createFrameWait(STAND_IN_MAX_MS),
|
||||
});
|
||||
i = end;
|
||||
}
|
||||
|
||||
@@ -287,3 +287,38 @@ test('replacing the newest point and removing points inside the trail draws exac
|
||||
for (const run of drawnRuns(viewer))
|
||||
for (let i = 1; i < run.length; i++) assert.equal(next.get(run[i - 1]), run[i]);
|
||||
});
|
||||
|
||||
test('a stand-in is dropped after ten seconds of drawn time, whatever the frame rate', () => {
|
||||
const viewer = fakeViewer();
|
||||
const trail = createTrail(viewer, { color: '#ffffff' });
|
||||
const realNow = performance.now;
|
||||
let clock = 1_000;
|
||||
performance.now = () => clock;
|
||||
try {
|
||||
trail.setPositions(line(CHUNK_POINTS + 5));
|
||||
// 2,000 frames at 240 Hz is about 8.3 s: still waiting for the geometry.
|
||||
for (let i = 0; i < 2_000; i++) {
|
||||
viewer.frame();
|
||||
clock += 1000 / 240;
|
||||
}
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
// Hidden time does not count toward the wait.
|
||||
trail.setVisible(false);
|
||||
clock += 60_000;
|
||||
viewer.frame();
|
||||
trail.setVisible(true);
|
||||
viewer.frame();
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
// A background tab draws nothing: a long gap adds at most one frame step.
|
||||
clock += 60_000;
|
||||
viewer.frame();
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, true);
|
||||
for (let i = 0; i < 480 && trail._chunksForTest().frozen[0].standIn; i++) {
|
||||
clock += 1000 / 240;
|
||||
viewer.frame();
|
||||
}
|
||||
assert.equal(trail._chunksForTest().frozen[0].standIn, false);
|
||||
} finally {
|
||||
performance.now = realNow;
|
||||
}
|
||||
});
|
||||
+239
-16
@@ -29,12 +29,21 @@ import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
|
||||
* node:test. No Cesium, no Node built-ins.
|
||||
*/
|
||||
|
||||
/** Transit modes the layer colors. `routeMode` hints refine a feed's default. */
|
||||
/**
|
||||
* Transit modes the layer colors: the GTFS basic route types, by name. A
|
||||
* vehicle's GTFS `route_type` settles its mode when its record carries one;
|
||||
* otherwise `routeMode` hints refine a feed's default.
|
||||
*/
|
||||
export const TRANSIT_MODES = Object.freeze([
|
||||
'bus',
|
||||
'trolleybus',
|
||||
'tram',
|
||||
'cable_tram',
|
||||
'subway',
|
||||
'monorail',
|
||||
'rail',
|
||||
'funicular',
|
||||
'aerial_lift',
|
||||
'ferry',
|
||||
'unknown',
|
||||
]);
|
||||
@@ -42,13 +51,81 @@ export const TRANSIT_MODES = Object.freeze([
|
||||
/** Per-mode icon used in labels and the selection card. */
|
||||
export const TRANSIT_MODE_ICON = Object.freeze({
|
||||
bus: '🚌',
|
||||
trolleybus: '🚎',
|
||||
tram: '🚊',
|
||||
cable_tram: '🚋',
|
||||
subway: '🚇',
|
||||
monorail: '🚝',
|
||||
rail: '🚆',
|
||||
funicular: '🚞',
|
||||
aerial_lift: '🚡',
|
||||
ferry: '⛴️',
|
||||
unknown: '🚏',
|
||||
});
|
||||
|
||||
/** The basic GTFS route types (0–7, 11, 12) by mode. */
|
||||
const BASIC_ROUTE_TYPE_MODES = Object.freeze({
|
||||
0: 'tram',
|
||||
1: 'subway',
|
||||
2: 'rail',
|
||||
3: 'bus',
|
||||
4: 'ferry',
|
||||
5: 'cable_tram',
|
||||
6: 'aerial_lift',
|
||||
7: 'funicular',
|
||||
11: 'trolleybus',
|
||||
12: 'monorail',
|
||||
});
|
||||
|
||||
/**
|
||||
* A GTFS `route_type` as an integer: a basic type (0–12) or an extended one
|
||||
* (100–1799), as a number or its decimal text. Null for anything else.
|
||||
* @param {unknown} value
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function transitRouteType(value) {
|
||||
const n =
|
||||
typeof value === 'number'
|
||||
? value
|
||||
: typeof value === 'string' && /^\d{1,4}$/.test(value.trim())
|
||||
? Number(value.trim())
|
||||
: NaN;
|
||||
return Number.isInteger(n) && n >= 0 && n < 1800 ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The mode of a GTFS `route_type`: the basic types, and the extended ones
|
||||
* mapped to the basic mode they are a kind of (a coach, 200, is a bus; a
|
||||
* high-speed train, 101, is rail; 405 is a monorail). Air, taxi and other
|
||||
* services, and a value GTFS does not define, are `unknown`.
|
||||
* @param {unknown} routeType
|
||||
* @returns {string} One of TRANSIT_MODES.
|
||||
*/
|
||||
export function transitModeOfRouteType(routeType) {
|
||||
const n = transitRouteType(routeType);
|
||||
if (n === null) return 'unknown';
|
||||
if (n < 100) return BASIC_ROUTE_TYPE_MODES[n] ?? 'unknown';
|
||||
if (n === 405) return 'monorail';
|
||||
const family = Math.floor(n / 100);
|
||||
return (
|
||||
{
|
||||
1: 'rail', // railway
|
||||
2: 'bus', // coach
|
||||
3: 'rail', // suburban railway
|
||||
4: 'subway', // urban railway
|
||||
5: 'subway', // metro
|
||||
6: 'subway', // underground
|
||||
7: 'bus',
|
||||
8: 'trolleybus',
|
||||
9: 'tram',
|
||||
10: 'ferry', // water transport
|
||||
12: 'ferry', // ferry
|
||||
13: 'aerial_lift',
|
||||
14: 'funicular',
|
||||
}[family] ?? 'unknown'
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* MBTA route ids are human-readable and mode-typed: rapid-transit lines carry
|
||||
* colour names, commuter rail is prefixed `CR-`, ferries `Boat-`, buses are
|
||||
@@ -443,7 +520,7 @@ const liaRouteLabel = routeIdPattern(/^8-0*(\w.*)$/);
|
||||
function liaRouteMode(routeId) {
|
||||
if (!routeId) return 'unknown';
|
||||
const line = liaRouteLabel(routeId);
|
||||
if (line === 'FUNI') return 'rail';
|
||||
if (line === 'FUNI') return 'funicular';
|
||||
return /^[AB]$/.test(line) ? 'tram' : 'bus';
|
||||
}
|
||||
|
||||
@@ -470,10 +547,14 @@ function astuceRouteLabel(routeId) {
|
||||
return ASTUCE_ROUTES[routeId ?? '']?.label ?? astuceNetworkLabel(routeId);
|
||||
}
|
||||
|
||||
/** PID trolleybus lines: route_type 11 in PID's routes.txt (checked 2026-11-14). */
|
||||
const PID_TROLLEYBUS_LINES = new Set([51, 52, 53, 58, 59, 232, 275]);
|
||||
|
||||
/**
|
||||
* Prague PID route ids are `L` plus a number whose range says what runs it,
|
||||
* per PID's GTFS routes.txt (data.pid.cz, checked 2026-11-09): 1–99 trams
|
||||
* (50–59 trolleybuses, 49 the Petřín funicular `LD`), 100–990 buses (the
|
||||
* trolleybus routes 232 and 275 among them, GTFS route type 11; the
|
||||
* 800s are the X replacement lines, `L803` is X3), 991–993 metro A–C,
|
||||
* 1000s and 1100s the S and R trains (`L1004` is S4, `L1109` R9), the rest
|
||||
* of 1200–1399 other trains, 1700s town buses, 1800s the P ferries, and from
|
||||
@@ -487,7 +568,9 @@ function pidRoute(routeId) {
|
||||
if (!match) return { mode: 'unknown', label: routeId };
|
||||
const n = Number(match[1]);
|
||||
// i18n-ignore: line code, as signed
|
||||
if (n === 49) return { mode: 'rail', label: 'LD' };
|
||||
if (n === 49) return { mode: 'funicular', label: 'LD' };
|
||||
if (PID_TROLLEYBUS_LINES.has(n))
|
||||
return { mode: 'trolleybus', label: String(n) };
|
||||
if (n >= 50 && n <= 59) return { mode: 'bus', label: String(n) };
|
||||
if (n < 100) return { mode: 'tram', label: String(n) };
|
||||
if (n >= 800 && n < 900) return { mode: 'bus', label: `X${n - 800}` };
|
||||
@@ -512,6 +595,102 @@ function pidRouteLabel(routeId) {
|
||||
return pidRoute(routeId).label;
|
||||
}
|
||||
|
||||
/**
|
||||
* A feed's route hint from its static GTFS routes.txt: the route ids of
|
||||
* every mode but `bus`, which is everything else.
|
||||
* @param {Record<string, string[]>} idsByMode
|
||||
* @returns {(routeId: string|null) => string}
|
||||
*/
|
||||
function routeModeTable(idsByMode) {
|
||||
const modes = new Map(
|
||||
Object.entries(idsByMode).flatMap(([mode, ids]) =>
|
||||
ids.map((id) => [id, mode]),
|
||||
),
|
||||
);
|
||||
return (routeId) => (routeId ? (modes.get(routeId) ?? 'bus') : 'unknown');
|
||||
}
|
||||
|
||||
/**
|
||||
* Bucharest TPBI by route id, from its routes.txt (checked 2026-11-14): the
|
||||
* trams (route type 0), metro lines M1–M5 (1) and trolleybuses (11); every
|
||||
* other route is a bus. Realtime route ids are the static ones.
|
||||
*/
|
||||
const tpbiRouteMode = routeModeTable({
|
||||
tram: [
|
||||
'54',
|
||||
'55',
|
||||
'57',
|
||||
'61',
|
||||
'63',
|
||||
'65',
|
||||
'66',
|
||||
'67',
|
||||
'68',
|
||||
'69',
|
||||
'70',
|
||||
'814',
|
||||
'915',
|
||||
'1013',
|
||||
],
|
||||
subway: ['968', '969', '970', '971', '999'],
|
||||
trolleybus: [
|
||||
'72',
|
||||
'73',
|
||||
'74',
|
||||
'75',
|
||||
'76',
|
||||
'78',
|
||||
'81',
|
||||
'83',
|
||||
'84',
|
||||
'85',
|
||||
'86',
|
||||
'87',
|
||||
'247',
|
||||
'910',
|
||||
'916',
|
||||
'924',
|
||||
'925',
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Cluj-Napoca CTP by route id, from its routes.txt (checked 2026-11-14): the
|
||||
* trams 100–102L (route type 0) and the trolleybuses (11).
|
||||
*/
|
||||
const ctpClujRouteMode = routeModeTable({
|
||||
tram: ['2', '3', '4', '5'],
|
||||
trolleybus: [
|
||||
'1',
|
||||
'10',
|
||||
'14',
|
||||
'15',
|
||||
'22',
|
||||
'36',
|
||||
'49',
|
||||
'53',
|
||||
'54',
|
||||
'55',
|
||||
'117',
|
||||
'119',
|
||||
'120',
|
||||
'153',
|
||||
'166',
|
||||
'187',
|
||||
],
|
||||
});
|
||||
|
||||
/**
|
||||
* Turin GTT by route id, from its routes.txt (checked 2026-11-14): the trams
|
||||
* (route type 0), metro M1, and the Sassi–Superga rack tramway `79U`, which
|
||||
* the file types as a funicular (7).
|
||||
*/
|
||||
const gttRouteMode = routeModeTable({
|
||||
tram: ['3U', '4U', '7U', '9U', '10U', '13U', '15U', '16CDU', '16CSU'],
|
||||
subway: ['METROU'],
|
||||
funicular: ['79U'],
|
||||
});
|
||||
|
||||
/**
|
||||
* Bordeaux TBM tram and boat lines by route id, from TBM's static GTFS
|
||||
* routes.txt (checked 2026-11-09): the trams are numbered ids, not letters.
|
||||
@@ -571,6 +750,7 @@ function transitFeed(fields) {
|
||||
* url: string, headers?: Record<string, string>,
|
||||
* license: string, licenseUrl: string, attribution: string,
|
||||
* defaultMode: string, routeMode?: (routeId: string|null) => string,
|
||||
* routeCorrections?: Readonly<Record<string, string>>,
|
||||
* speedUnit?: 'km/h', refreshMs?: number, sourceUrl?: string,
|
||||
* creditDated?: boolean,
|
||||
* }>>}
|
||||
@@ -579,6 +759,9 @@ function transitFeed(fields) {
|
||||
* stretches the proxy's cache for an upstream that rate-limits below one
|
||||
* request per 15 s TTL. `sourceUrl` and `creditDated` add a link and a date
|
||||
* to the credit for licences that ask for them (`transitFeedCredit`).
|
||||
* `routeCorrections` names the routes whose `route_type` the operator's own
|
||||
* routes.txt gets wrong, `route_id` to the mode they really are; a correction
|
||||
* outranks the route type, which would otherwise outrank the route hint.
|
||||
*/
|
||||
export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
Object.freeze({
|
||||
@@ -1264,6 +1447,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Keyless public endpoint from the metropolitan transport authority; no licence found. Same basis as Metro Transit and OVapi.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: tpbiRouteMode,
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'roma-mobilita',
|
||||
@@ -1296,6 +1480,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Official keyless endpoint; no licence found. Same basis as Metro Transit and OVapi. Route ids append `U` for urban lines.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: gttRouteMode,
|
||||
routeLabel: gttRouteLabel,
|
||||
}),
|
||||
transitFeed({
|
||||
@@ -1401,6 +1586,7 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
note: 'Keyless; no licence found. Same basis as Metro Transit and OVapi.',
|
||||
},
|
||||
defaultMode: 'bus',
|
||||
routeMode: ctpClujRouteMode,
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'ctp-iasi',
|
||||
@@ -1567,6 +1753,8 @@ export const TRANSIT_FEED_REGISTRY = Object.freeze([
|
||||
defaultMode: 'bus',
|
||||
routeLabel: liaRouteLabel,
|
||||
routeMode: liaRouteMode,
|
||||
// LiA's routes.txt types the funicular (`8-FUNI`) as a bus (3).
|
||||
routeCorrections: Object.freeze({ '8-FUNI': 'funicular' }),
|
||||
}),
|
||||
transitFeed({
|
||||
id: 'filbleu-tours',
|
||||
@@ -1664,54 +1852,89 @@ export function transitFeedsInRange(lat, lon, slackKm = 0) {
|
||||
}
|
||||
|
||||
/**
|
||||
* The feed's own hint for a vehicle: its fleet number when the feed maps
|
||||
* those (`vehicleMode`), else its route (`routeMode`). Null when neither knows.
|
||||
* What settles a vehicle's mode, most specific first: the feed's fleet hint
|
||||
* (`vehicleMode`, which knows a bus standing in on a tram route), else the
|
||||
* feed's correction for a route its routes.txt mistypes (`routeCorrections`),
|
||||
* else the GTFS `route_type` of its route when the record carries one, else
|
||||
* the feed's route hint (`routeMode`). Null when none of them knows.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId
|
||||
* @param {string|null} vehicleId
|
||||
* @param {unknown} routeType GTFS `route_type`, when the record has one.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
function hintedMode(feed, routeId, vehicleId) {
|
||||
function hintedMode(feed, routeId, vehicleId, routeType) {
|
||||
const byVehicle =
|
||||
typeof feed?.vehicleMode === 'function'
|
||||
? feed.vehicleMode(vehicleId)
|
||||
: null;
|
||||
if (byVehicle && byVehicle !== 'unknown') return byVehicle;
|
||||
const corrections = feed?.routeCorrections;
|
||||
if (routeId && corrections && Object.hasOwn(corrections, routeId))
|
||||
return corrections[routeId];
|
||||
const byType = transitModeOfRouteType(routeType);
|
||||
if (byType !== 'unknown') return byType;
|
||||
return typeof feed?.routeMode === 'function' ? feed.routeMode(routeId) : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Mode for a vehicle: the feed's fleet or route hint when it has one, else
|
||||
* its default.
|
||||
* Mode for a vehicle: its fleet hint, route type or route hint when one
|
||||
* knows ({@link hintedMode}), else its feed's default.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId GTFS route_id from the vehicle's trip.
|
||||
* @param {string|null} [vehicleId] GTFS-RT vehicle id.
|
||||
* @param {unknown} [routeType] GTFS `route_type` of the route, when known.
|
||||
* @returns {string} One of TRANSIT_MODES.
|
||||
*/
|
||||
export function transitModeFor(feed, routeId, vehicleId = null) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId);
|
||||
export function transitModeFor(
|
||||
feed,
|
||||
routeId,
|
||||
vehicleId = null,
|
||||
routeType = null,
|
||||
) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId, routeType);
|
||||
const mode =
|
||||
hinted && hinted !== 'unknown' ? hinted : feed?.defaultMode || 'unknown';
|
||||
return TRANSIT_MODES.includes(mode) ? mode : 'unknown';
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the mode came from the route id rather than the feed's default. A
|
||||
* default is a guess about a fleet — TransLink's is "bus" while it publishes
|
||||
* rail in the same feed — so a consumer judging physical plausibility must
|
||||
* not hold a defaulted vehicle to a bus's limits.
|
||||
* Whether the mode came from the vehicle, its route type or its route id
|
||||
* rather than the feed's default. A default is a guess about a fleet —
|
||||
* TransLink's is "bus" while it publishes rail in the same feed — so a
|
||||
* consumer judging physical plausibility must not hold a defaulted vehicle
|
||||
* to a bus's limits.
|
||||
* @param {object} feed Registry entry.
|
||||
* @param {string|null} routeId
|
||||
* @param {string|null} [vehicleId]
|
||||
* @param {unknown} [routeType]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function transitModeResolved(feed, routeId, vehicleId = null) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId);
|
||||
export function transitModeResolved(
|
||||
feed,
|
||||
routeId,
|
||||
vehicleId = null,
|
||||
routeType = null,
|
||||
) {
|
||||
const hinted = hintedMode(feed, routeId, vehicleId, routeType);
|
||||
return (
|
||||
Boolean(hinted) && hinted !== 'unknown' && TRANSIT_MODES.includes(hinted)
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The route type a vehicle's model is chosen by: its record's, when that type
|
||||
* is a kind of the mode it was given. A fleet hint can overrule the route (a
|
||||
* bus on a tram route), and then the route's type does not describe it.
|
||||
* @param {string} mode The vehicle's mode ({@link transitModeFor}).
|
||||
* @param {unknown} routeType
|
||||
* @returns {number|null}
|
||||
*/
|
||||
export function transitModelRouteType(mode, routeType) {
|
||||
const n = transitRouteType(routeType);
|
||||
return n !== null && transitModeOfRouteType(n) === mode ? n : null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The route as a rider would say it. Most feeds publish that already, so this
|
||||
* is identity for them; a feed that publishes internal keys supplies its own
|
||||
|
||||
@@ -11,9 +11,13 @@ import {
|
||||
haversineKm,
|
||||
publicTransitCatalog,
|
||||
transitFeedsInRange,
|
||||
TRANSIT_MODE_ICON,
|
||||
transitModeFor,
|
||||
transitModeOfRouteType,
|
||||
transitModeResolved,
|
||||
transitModelRouteType,
|
||||
transitRouteLabel,
|
||||
transitRouteType,
|
||||
} from './transitFeeds.js';
|
||||
import { RIO_ROUTE_NAMES } from './rioRouteNames.js';
|
||||
|
||||
@@ -729,8 +733,10 @@ test('Prague route-id ranges give metro, trains, ferries and trolleybuses their
|
||||
transitRouteLabel(feed, routeId),
|
||||
];
|
||||
assert.deepEqual(read('L22'), ['tram', '22']);
|
||||
assert.deepEqual(read('L58'), ['bus', '58'], 'trolleybus');
|
||||
assert.deepEqual(read('L49'), ['rail', 'LD'], 'Petřín funicular');
|
||||
assert.deepEqual(read('L58'), ['trolleybus', '58']);
|
||||
assert.deepEqual(read('L55'), ['bus', '55'], 'not a PID trolleybus line');
|
||||
assert.deepEqual(read('L275'), ['trolleybus', '275'], 'route type 11');
|
||||
assert.deepEqual(read('L49'), ['funicular', 'LD'], 'Petřín funicular');
|
||||
assert.deepEqual(read('L135'), ['bus', '135']);
|
||||
assert.deepEqual(read('L803'), ['bus', 'X3']);
|
||||
assert.deepEqual(read('L991'), ['subway', 'A']);
|
||||
@@ -767,7 +773,7 @@ test('Rouen Métro and Calypso are not buses; Le Havre reads its own ids', () =>
|
||||
assert.equal(transitModeFor(feed, 'TCAR:93'), 'bus');
|
||||
assert.equal(transitRouteLabel(feed, 'TAE:F'), 'F');
|
||||
const lia = getTransitFeed('lia-le-havre');
|
||||
assert.equal(transitModeFor(lia, '8-FUNI'), 'rail');
|
||||
assert.equal(transitModeFor(lia, '8-FUNI'), 'funicular');
|
||||
assert.equal(transitRouteLabel(lia, '8-C3'), 'C3');
|
||||
assert.equal(transitRouteLabel(lia, '8-09'), '9');
|
||||
assert.equal(transitRouteLabel(lia, '8-A'), 'A');
|
||||
@@ -778,3 +784,114 @@ test('data.gov.my feeds ask the proxy for no more than its 4 a minute', () => {
|
||||
assert.ok(getTransitFeed(id).refreshMs >= 30_000, id);
|
||||
}
|
||||
});
|
||||
|
||||
test('a GTFS route type names its mode, basic and extended alike', () => {
|
||||
for (const [routeType, mode] of [
|
||||
[0, 'tram'],
|
||||
[1, 'subway'],
|
||||
[2, 'rail'],
|
||||
[3, 'bus'],
|
||||
[4, 'ferry'],
|
||||
[5, 'cable_tram'],
|
||||
[6, 'aerial_lift'],
|
||||
[7, 'funicular'],
|
||||
[11, 'trolleybus'],
|
||||
[12, 'monorail'],
|
||||
[101, 'rail'],
|
||||
[106, 'rail'],
|
||||
[200, 'bus'],
|
||||
[300, 'rail'],
|
||||
[401, 'subway'],
|
||||
[405, 'monorail'],
|
||||
[702, 'bus'],
|
||||
[800, 'trolleybus'],
|
||||
[900, 'tram'],
|
||||
[1000, 'ferry'],
|
||||
[1200, 'ferry'],
|
||||
[1300, 'aerial_lift'],
|
||||
[1400, 'funicular'],
|
||||
['11', 'trolleybus'],
|
||||
])
|
||||
assert.equal(transitModeOfRouteType(routeType), mode, String(routeType));
|
||||
// Air, taxi and other services, and values GTFS does not define.
|
||||
for (const other of [8, 1100, 1500, 1700, 1800, -1, 2.5, '', 'tram', null])
|
||||
assert.equal(transitModeOfRouteType(other), 'unknown', String(other));
|
||||
assert.equal(transitRouteType(' 200 '), 200);
|
||||
assert.equal(transitRouteType('2e2'), null);
|
||||
});
|
||||
|
||||
test('every mode has an icon, and every mode a route type names is a mode', () => {
|
||||
for (const mode of TRANSIT_MODES) assert.ok(TRANSIT_MODE_ICON[mode], mode);
|
||||
for (let routeType = 0; routeType < 1800; routeType++)
|
||||
assert.ok(TRANSIT_MODES.includes(transitModeOfRouteType(routeType)));
|
||||
});
|
||||
|
||||
test('a route type settles the mode before a route hint or the default', () => {
|
||||
const mbta = getTransitFeed('mbta');
|
||||
// The hint calls every numbered MBTA route a bus; a route type is finer.
|
||||
assert.equal(transitModeFor(mbta, '71'), 'bus');
|
||||
assert.equal(transitModeFor(mbta, '71', 'y1', 11), 'trolleybus');
|
||||
assert.equal(transitModeResolved(mbta, '71', 'y1', 11), true);
|
||||
// A default-only feed is resolved by a route type alone.
|
||||
const durham = getTransitFeed('durham-region');
|
||||
assert.equal(transitModeResolved(durham, '915', 'b1'), false);
|
||||
assert.equal(transitModeFor(durham, '915', 'b1', 200), 'bus');
|
||||
assert.equal(transitModeResolved(durham, '915', 'b1', 200), true);
|
||||
// A type that names no mode leaves the hints in charge.
|
||||
assert.equal(transitModeFor(mbta, 'Red', null, 1700), 'subway');
|
||||
assert.equal(transitModeFor(mbta, 'Red', null, 'x'), 'subway');
|
||||
});
|
||||
|
||||
test('a fleet hint outranks the route type, and then the type picks no model', () => {
|
||||
const ttc = getTransitFeed('ttc-toronto');
|
||||
// A bus standing in on the 501 streetcar route (route type 0).
|
||||
const mode = transitModeFor(ttc, '501', '8400', 0);
|
||||
assert.equal(mode, 'bus');
|
||||
assert.equal(transitModelRouteType(mode, 0), null);
|
||||
assert.equal(transitModelRouteType('tram', 0), 0);
|
||||
assert.equal(transitModelRouteType('bus', 200), 200, 'a coach is a bus');
|
||||
assert.equal(transitModelRouteType('bus', null), null);
|
||||
});
|
||||
|
||||
test('a route correction outranks a mistyped route type, and only for its route', () => {
|
||||
const lia = getTransitFeed('lia-le-havre');
|
||||
// LiA's routes.txt types the funicular as a bus (3).
|
||||
assert.equal(transitModeFor(lia, '8-FUNI', null, 3), 'funicular');
|
||||
assert.equal(transitModeResolved(lia, '8-FUNI', null, 3), true);
|
||||
// A correction is a mode, so the bus type picks no model for it.
|
||||
assert.equal(transitModelRouteType('funicular', 3), null);
|
||||
// Every other route still takes its route type.
|
||||
assert.equal(transitModeFor(lia, '8-A', null, 0), 'tram');
|
||||
assert.equal(transitModeFor(lia, '8-C3', null, 3), 'bus');
|
||||
assert.equal(transitModeFor(lia, null, null, 3), 'bus');
|
||||
// Corrections are narrow: a few named routes, each to a known mode.
|
||||
for (const feed of TRANSIT_FEED_REGISTRY) {
|
||||
if (!feed.routeCorrections) continue;
|
||||
assert.ok(Object.isFrozen(feed.routeCorrections), feed.id);
|
||||
for (const [route, mode] of Object.entries(feed.routeCorrections)) {
|
||||
assert.ok(TRANSIT_MODES.includes(mode), `${feed.id} ${route}`);
|
||||
assert.notEqual(mode, 'unknown', `${feed.id} ${route}`);
|
||||
}
|
||||
}
|
||||
// An inherited key is not a correction.
|
||||
assert.equal(transitModeFor(lia, 'toString', null, 3), 'bus');
|
||||
});
|
||||
|
||||
// Route ids as each realtime feed and its operator's routes.txt carried them
|
||||
// on 2026-11-14.
|
||||
test('Bucharest, Cluj and Turin route ids give trams, trolleybuses and a funicular', () => {
|
||||
const mode = (id, routeId) => transitModeFor(getTransitFeed(id), routeId);
|
||||
assert.equal(mode('tpbi-bucuresti', '85'), 'trolleybus', 'line 74');
|
||||
assert.equal(mode('tpbi-bucuresti', '1013'), 'tram', 'line 4');
|
||||
assert.equal(mode('tpbi-bucuresti', '968'), 'subway', 'M1');
|
||||
assert.equal(mode('tpbi-bucuresti', '828'), 'bus');
|
||||
assert.equal(mode('tpbi-bucuresti', 'PV1_407'), 'bus');
|
||||
assert.equal(mode('ctp-cluj', '1'), 'trolleybus');
|
||||
assert.equal(mode('ctp-cluj', '2'), 'tram', 'line 100');
|
||||
assert.equal(mode('ctp-cluj', '6'), 'bus', 'line 19');
|
||||
assert.equal(mode('gtt-torino', '79U'), 'funicular', 'Sassi–Superga');
|
||||
assert.equal(mode('gtt-torino', '16CDU'), 'tram');
|
||||
assert.equal(mode('gtt-torino', 'METROU'), 'subway');
|
||||
assert.equal(mode('gtt-torino', '6U'), 'bus');
|
||||
assert.equal(mode('gtt-torino', null), 'bus', 'no route: the default');
|
||||
});
|
||||
@@ -21,7 +21,9 @@ import {
|
||||
* at the ~18 px the fleet renders at, by shape and not only by colour: a bus is
|
||||
* short and blunt, a tram is long and slender with articulation joints, a metro
|
||||
* car is squared off, a mainline train has a tapered nose, and a ferry is a
|
||||
* hull with a bow.
|
||||
* hull with a bow. A trolleybus trails its two poles, a cable car is a short
|
||||
* single car, a monorail the slimmest bullet, a funicular hangs off its rope,
|
||||
* and a gondola is a cabin on its cable.
|
||||
*
|
||||
* Interior detail is drawn with the same dark hairline as the edge — windscreen
|
||||
* lines, articulation joints, a deck line — because a solid dark panel would
|
||||
@@ -103,6 +105,49 @@ const HEADING_BODIES = {
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-7.5,-6 L7.5,-6 L7.5,20 L-7.5,20 Z" ${DETAIL}/>`,
|
||||
|
||||
// ── Trolleybus: a bus a little narrower, trailing the two trolley poles
|
||||
// that reach back to its wires. Body and poles are one outline, so no
|
||||
// edge is drawn across the body.
|
||||
trolleybus: `
|
||||
<path d="M0,-41 L15,-26 L15,25 C15,28.5 13,30 9,30 L7.5,30 L7.5,42 L4,42
|
||||
L4,30 L-4,30 L-4,42 L-7.5,42 L-7.5,30 L-9,30 C-13,30 -15,28.5 -15,25
|
||||
L-15,-26 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-10,-21 L10,-21" ${DETAIL}/>`,
|
||||
|
||||
// ── Cable car (street cable railway): a short single car, under half a
|
||||
// tram, with open platforms at both ends.
|
||||
cable_tram: `
|
||||
<path d="M0,-30 L11,-21 L11,26 C11,28 9,29 0,29 C-9,29 -11,28 -11,26
|
||||
L-11,-21 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-12 L11,-12" ${DETAIL}/>
|
||||
<path d="M-11,18 L11,18" ${DETAIL}/>`,
|
||||
|
||||
// ── Monorail: the slimmest train in the set, a rounded bullet nose over
|
||||
// its beam.
|
||||
monorail: `
|
||||
<path d="M0,-45 C3,-45 8.5,-36 8.5,-22 L8.5,42 L-8.5,42 L-8.5,-22
|
||||
C-8.5,-36 -3,-45 0,-45 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M0,-18 L0,38" ${DETAIL}/>`,
|
||||
|
||||
// ── Funicular: a squat car hauled by the rope at its upper end.
|
||||
funicular: `
|
||||
<path d="M-6,-30 L6,-30 L11,-24 L11,36 L-11,36 L-11,-24 Z
|
||||
M-1.75,-46 L1.75,-46 L1.75,-30 L-1.75,-30 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-8 L11,-8" ${DETAIL}/>
|
||||
<path d="M-11,14 L11,14" ${DETAIL}/>`,
|
||||
|
||||
// ── Gondola (aerial lift): a cabin hung on the cable that runs through
|
||||
// it; the cabin's nose is its front.
|
||||
aerial_lift: `
|
||||
<path d="M0,-18 L12,-7 L12,14 C12,16 10,17 0,17 C-10,17 -12,16 -12,14
|
||||
L-12,-7 Z
|
||||
M-2.5,-40 L2.5,-40 L2.5,46 L-2.5,46 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
// ── Unknown: a plain marker with a nose and nothing else, so an
|
||||
// unclassified vehicle never pretends to be a mode it is not.
|
||||
unknown: `
|
||||
@@ -146,6 +191,40 @@ const NEUTRAL_BODIES = {
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-7.5,-13 L7.5,-13 L7.5,13 L-7.5,13 Z" ${DETAIL}/>`,
|
||||
|
||||
trolleybus: `
|
||||
<path d="M-15,-26 C-15,-30 -13,-32 -9,-32 L-7.5,-32 L-7.5,-42 L-4,-42
|
||||
L-4,-32 L4,-32 L4,-42 L7.5,-42 L7.5,-32 L9,-32 C13,-32 15,-30 15,-26
|
||||
L15,26 C15,30 13,32 9,32 L7.5,32 L7.5,42 L4,42 L4,32 L-4,32 L-4,42
|
||||
L-7.5,42 L-7.5,32 L-9,32 C-13,32 -15,30 -15,26 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
cable_tram: `
|
||||
<path d="M-11,-25 C-11,-27 -9,-28 0,-28 C9,-28 11,-27 11,-25
|
||||
L11,25 C11,27 9,28 0,28 C-9,28 -11,27 -11,25 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-17 L11,-17" ${DETAIL}/>
|
||||
<path d="M-11,17 L11,17" ${DETAIL}/>`,
|
||||
|
||||
monorail: `
|
||||
<path d="M0,-44 C5,-44 8.5,-38 8.5,-28 L8.5,28 C8.5,38 5,44 0,44
|
||||
C-5,44 -8.5,38 -8.5,28 L-8.5,-28 C-8.5,-38 -5,-44 0,-44 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M0,-24 L0,24" ${DETAIL}/>`,
|
||||
|
||||
funicular: `
|
||||
<path d="M-11,-30 L11,-30 L11,30 L-11,30 Z
|
||||
M-1.75,-46 L1.75,-46 L1.75,-30 L-1.75,-30 Z
|
||||
M-1.75,30 L1.75,30 L1.75,46 L-1.75,46 Z"
|
||||
fill="white" ${STROKE}/>
|
||||
<path d="M-11,-10 L11,-10" ${DETAIL}/>
|
||||
<path d="M-11,10 L11,10" ${DETAIL}/>`,
|
||||
|
||||
aerial_lift: `
|
||||
<path d="M-12,-14 C-12,-16 -10,-17 0,-17 C10,-17 12,-16 12,-14
|
||||
L12,14 C12,16 10,17 0,17 C-10,17 -12,16 -12,14 Z
|
||||
M-2.5,-46 L2.5,-46 L2.5,46 L-2.5,46 Z"
|
||||
fill="white" ${STROKE}/>`,
|
||||
|
||||
unknown: `
|
||||
<path d="M-10,-26 C-10,-30 -7,-32 0,-32 C7,-32 10,-30 10,-26
|
||||
L10,26 C10,30 7,32 0,32 C-7,32 -10,30 -10,26 Z"
|
||||
|
||||
@@ -62,7 +62,7 @@ test('the raster cache is bounded by kind, size and halo — never by call count
|
||||
assert.ok(transitIconCacheSize() <= before + 3 + TRANSIT_ICON_KINDS.length);
|
||||
});
|
||||
|
||||
test('all 72 variants retain the specified final halo at both display sizes', async () => {
|
||||
test('every variant retains the specified final halo at both display sizes', async () => {
|
||||
const { presetSpriteScale, presetSpriteOutlinePx } =
|
||||
await import('./transitPresetStyle.js');
|
||||
for (const kind of TRANSIT_ICON_KINDS) {
|
||||
@@ -97,7 +97,8 @@ test('all 72 variants retain the specified final halo at both display sizes', as
|
||||
}
|
||||
for (let i = 0; i < 100; i++)
|
||||
transitIcon('invalid', i, { haloScreenPx: i, screenPx: i });
|
||||
assert.equal(transitIconCacheSize(), 72);
|
||||
// Every kind at two sizes, three profiles, with and without a course.
|
||||
assert.equal(transitIconCacheSize(), TRANSIT_ICON_KINDS.length * 12);
|
||||
});
|
||||
|
||||
test('every mono raster preserves the normal silhouette mask and aspect at CRT display size', async () => {
|
||||
@@ -197,6 +198,11 @@ test('sensor raster halo stays dark across its screen-space band on a white roof
|
||||
subway: 11.5,
|
||||
rail: 10.5,
|
||||
ferry: 12.5,
|
||||
trolleybus: 15,
|
||||
cable_tram: 11,
|
||||
monorail: 8.5,
|
||||
funicular: 11,
|
||||
aerial_lift: 12,
|
||||
unknown: 10,
|
||||
};
|
||||
for (const selected of [false, true]) {
|
||||
|
||||
@@ -60,9 +60,14 @@ const SPRITE_STYLE = Object.freeze({
|
||||
outlinePx: 1.25,
|
||||
rgbaByMode: Object.freeze({
|
||||
bus: Object.freeze([0, 255, 102, 1]),
|
||||
trolleybus: Object.freeze([170, 255, 0, 1]),
|
||||
tram: Object.freeze([255, 179, 0, 1]),
|
||||
cable_tram: Object.freeze([255, 120, 0, 1]),
|
||||
subway: Object.freeze([255, 59, 48, 1]),
|
||||
monorail: Object.freeze([255, 64, 170, 1]),
|
||||
rail: Object.freeze([215, 139, 255, 1]),
|
||||
funicular: Object.freeze([255, 214, 140, 1]),
|
||||
aerial_lift: Object.freeze([90, 140, 255, 1]),
|
||||
ferry: Object.freeze([58, 208, 255, 1]),
|
||||
unknown: Object.freeze([255, 255, 255, 1]),
|
||||
}),
|
||||
@@ -72,9 +77,14 @@ const SPRITE_STYLE = Object.freeze({
|
||||
/** Modes with a bracket tier of their own. */
|
||||
const TIER_MODES = Object.freeze([
|
||||
'bus',
|
||||
'trolleybus',
|
||||
'tram',
|
||||
'cable_tram',
|
||||
'subway',
|
||||
'monorail',
|
||||
'rail',
|
||||
'funicular',
|
||||
'aerial_lift',
|
||||
'ferry',
|
||||
'unknown',
|
||||
]);
|
||||
@@ -128,7 +138,7 @@ export function presetSpriteOutlinePx(styleName, selected = false) {
|
||||
|
||||
/**
|
||||
* Detection-overlay tier key for a transit mode. Every theme's `tiers`
|
||||
* table carries these six, so the bracket colour is per mode in every
|
||||
* table carries one per mode, so the bracket colour is per mode in every
|
||||
* preset. Unlike traffic, transit sets its tier keyless as well: the feeds
|
||||
* are keyless, and there is no separate keyless experience to keep
|
||||
* byte-identical.
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
decodeVehiclePositions,
|
||||
} from './gtfsRealtime.js';
|
||||
import { getTransitFeed } from './transitFeeds.js';
|
||||
export { transitModeFor, transitRouteType } from './transitFeeds.js';
|
||||
|
||||
/** Fresh window: a snapshot younger than this is served without refetching. */
|
||||
export const TRANSIT_PROXY_TTL_MS = 15_000;
|
||||
|
||||
@@ -46,6 +46,15 @@ const TYPE_STYLES = [
|
||||
];
|
||||
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
|
||||
|
||||
/**
|
||||
* An aid to navigation's disc and card accent: a bone white apart from every
|
||||
* ship type's colour.
|
||||
*/
|
||||
export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
css: '#d9d2c0',
|
||||
accent: '217, 210, 192',
|
||||
});
|
||||
|
||||
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
|
||||
// and tests match on them.
|
||||
const TYPE_DISPLAY_KEYS = Object.freeze({
|
||||
|
||||
@@ -45,3 +45,110 @@ export function normalizeVesselType(type) {
|
||||
if (NUMERIC_TYPE_SPECIALS[code]) return NUMERIC_TYPE_SPECIALS[code];
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
|
||||
/**
|
||||
* The kind of aid to navigation an AIS aid-to-navigation report (message 21)
|
||||
* names by its type code, 0 to 31 (ITU-R M.1371, IALA marks): beacons and
|
||||
* floating marks by their cardinal quadrant, lateral side, safe water,
|
||||
* isolated danger or special mark, and the lights, RACONs and reference
|
||||
* points around them. Code 0 names no kind.
|
||||
*/
|
||||
const AID_TYPE_NAMES = Object.freeze([
|
||||
'Navigation aid',
|
||||
'Reference point',
|
||||
'RACON',
|
||||
'Fixed structure off shore',
|
||||
'Emergency wreck marking buoy',
|
||||
'Light, without sectors',
|
||||
'Light, with sectors',
|
||||
'Leading light front',
|
||||
'Leading light rear',
|
||||
'Beacon, Cardinal N',
|
||||
'Beacon, Cardinal E',
|
||||
'Beacon, Cardinal S',
|
||||
'Beacon, Cardinal W',
|
||||
'Beacon, Port hand',
|
||||
'Beacon, Starboard hand',
|
||||
'Beacon, Preferred channel port hand',
|
||||
'Beacon, Preferred channel starboard hand',
|
||||
'Beacon, Isolated danger',
|
||||
'Beacon, Safe water',
|
||||
'Beacon, Special mark',
|
||||
'Cardinal Mark N',
|
||||
'Cardinal Mark E',
|
||||
'Cardinal Mark S',
|
||||
'Cardinal Mark W',
|
||||
'Port hand Mark',
|
||||
'Starboard hand Mark',
|
||||
'Preferred Channel Port hand',
|
||||
'Preferred Channel Starboard hand',
|
||||
'Isolated danger',
|
||||
'Safe Water',
|
||||
'Special Mark',
|
||||
'Light Vessel / LANBY / Rigs',
|
||||
]);
|
||||
|
||||
/**
|
||||
* The kind an AIS aid-to-navigation type code names ("19" → "Beacon, Special
|
||||
* mark"); "Navigation aid" for code 0 and for a code outside 0 to 31.
|
||||
* @param {string|number|null|undefined} code
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aidToNavigationTypeName(code) {
|
||||
const text = String(code ?? '').trim();
|
||||
const index = /^\d+$/.test(text) ? Number(text) : -1;
|
||||
return AID_TYPE_NAMES[index] ?? AID_TYPE_NAMES[0];
|
||||
}
|
||||
|
||||
/** Every kind {@link aidToNavigationTypeName} names, lowercased. */
|
||||
const AID_TYPE_NAME_SET = new Set(
|
||||
AID_TYPE_NAMES.map((name) => name.toLowerCase()),
|
||||
);
|
||||
|
||||
/**
|
||||
* Words a vessel type uses for an aid to navigation. A vessel that works on
|
||||
* one ("Buoy Tender", "Buoy-Laying Vessel", "Buoy Layer") is a ship underway,
|
||||
* not a mark on the water.
|
||||
*/
|
||||
const AID_TYPE_TEXT =
|
||||
/navaid|\baton\b|aids? to nav|nav(igation)? aid|racon|lighthouse|lightship|light vessel|reference point|hand mark|cardinal|safe water|preferred channel|isolated danger|special mark|beacon|buoy/i;
|
||||
const AID_WORKER_TEXT = /tender|lay(ing|er)\b/i;
|
||||
|
||||
/** ITU MID 99: the MMSI of an AIS aid-to-navigation station (99MIDxxxx). */
|
||||
const AID_MMSI = /^99\d{7}$/;
|
||||
|
||||
/**
|
||||
* Whether each type text seen names an aid. Vessel layers ask per vessel on
|
||||
* their draw passes, and a feed uses few distinct type texts, so each is
|
||||
* matched once; the memo is bounded against a feed of free-form types.
|
||||
*/
|
||||
const AID_TYPE_MEMO = new Map();
|
||||
const AID_TYPE_MEMO_MAX = 1024;
|
||||
|
||||
function typeNamesAid(text) {
|
||||
let aid = AID_TYPE_MEMO.get(text);
|
||||
if (aid !== undefined) return aid;
|
||||
aid =
|
||||
AID_TYPE_NAME_SET.has(text.toLowerCase()) ||
|
||||
(AID_TYPE_TEXT.test(text) && !AID_WORKER_TEXT.test(text));
|
||||
if (AID_TYPE_MEMO.size >= AID_TYPE_MEMO_MAX) AID_TYPE_MEMO.clear();
|
||||
AID_TYPE_MEMO.set(text, aid);
|
||||
return aid;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a vessel record is an aid to navigation (a buoy, beacon, mark,
|
||||
* RACON or light) rather than a vessel: its type is one of the kinds an aid
|
||||
* report names or uses a word for one, or its MMSI is an aid-to-navigation
|
||||
* station's, or it is a virtual aid. A numeric AIS ship type never names one.
|
||||
* @param {{type?: string|number|null, mmsi?: string|number|null,
|
||||
* virtual?: boolean}} vessel
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function isAidToNavigation({ type, mmsi, virtual } = {}) {
|
||||
if (virtual === true) return true;
|
||||
const text = typeof type === 'string' ? type.trim() : String(type ?? '');
|
||||
if (text && typeNamesAid(text)) return true;
|
||||
if (mmsi === null || mmsi === undefined || mmsi === '') return false;
|
||||
return AID_MMSI.test(typeof mmsi === 'string' ? mmsi.trim() : String(mmsi));
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aidToNavigationTypeName, isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
test('an aid-to-navigation type code names its kind of aid', () => {
|
||||
assert.equal(aidToNavigationTypeName(20), 'Cardinal Mark N');
|
||||
assert.equal(aidToNavigationTypeName('13'), 'Beacon, Port hand');
|
||||
assert.equal(aidToNavigationTypeName(2), 'RACON');
|
||||
assert.equal(aidToNavigationTypeName(29), 'Safe Water');
|
||||
assert.equal(aidToNavigationTypeName(31), 'Light Vessel / LANBY / Rigs');
|
||||
// Code 0, a code past 31 and no code name no kind.
|
||||
for (const code of [0, 32, -1, '', null, undefined, 'x'])
|
||||
assert.equal(aidToNavigationTypeName(code), 'Navigation aid', code);
|
||||
});
|
||||
|
||||
test('aids to navigation are known by their type, else their MMSI', () => {
|
||||
for (const type of [
|
||||
'Beacon, Special Mark',
|
||||
'Cardinal Mark N',
|
||||
'Port Hand Mark',
|
||||
'Starboard Hand Mark',
|
||||
'Safe Water',
|
||||
'Isolated danger',
|
||||
'Preferred Channel Port hand',
|
||||
'RACON',
|
||||
'Light Vessel / LANBY / Rigs',
|
||||
'Reference point',
|
||||
'Navigation aid',
|
||||
'AtoN',
|
||||
'Lighthouse',
|
||||
'Buoy',
|
||||
// Every kind an aid report names is an aid, whatever its MMSI.
|
||||
'Light, with sectors',
|
||||
'Leading light rear',
|
||||
'Fixed structure off shore',
|
||||
'Emergency wreck marking buoy',
|
||||
])
|
||||
assert.equal(isAidToNavigation({ type, mmsi: '' }), true, type);
|
||||
// A virtual aid is an aid whatever its type or MMSI.
|
||||
assert.equal(
|
||||
isAidToNavigation({ type: '', mmsi: '', virtual: true }),
|
||||
true,
|
||||
);
|
||||
// AIS aid-to-navigation stations are numbered 99MIDxxxx.
|
||||
assert.equal(isAidToNavigation({ type: '', mmsi: '993672001' }), true);
|
||||
assert.equal(isAidToNavigation({ type: '0', mmsi: ' 992351234 ' }), true);
|
||||
for (const vessel of [
|
||||
{ type: 'Buoy Tender', mmsi: '366999001' },
|
||||
{ type: 'Buoy-Laying Vessel', mmsi: '' },
|
||||
{ type: 'Buoy Layer', mmsi: '' },
|
||||
{ type: 'Lighter', mmsi: '' },
|
||||
{ type: 'Flight deck', mmsi: '' },
|
||||
{ type: 70, mmsi: 366999002 },
|
||||
{ type: '70', mmsi: '366999002' },
|
||||
{ type: '0', mmsi: '' },
|
||||
{ type: 'Cargo', mmsi: '99' },
|
||||
{ type: 'Passenger', mmsi: '9936720011' },
|
||||
{},
|
||||
])
|
||||
assert.equal(isAidToNavigation(vessel), false, JSON.stringify(vessel));
|
||||
});
|
||||
@@ -0,0 +1,244 @@
|
||||
/**
|
||||
* The bundled world cities pack (Wikidata, CC0), read from
|
||||
* `local_data/wikidata_cities/cities.json` (built by
|
||||
* scripts/build-wikidata-cities.mjs). The file loads once, on first use, and
|
||||
* every answer comes from it: no place service is called.
|
||||
*
|
||||
* Rows are `[name, lat, lon, population, country, wikidata]`, largest first.
|
||||
*/
|
||||
|
||||
const CELL_DEG = 1;
|
||||
|
||||
// Letters that are not a base letter plus an accent, so NFD leaves them.
|
||||
const PLAIN_LETTERS = {
|
||||
ł: 'l',
|
||||
ø: 'o',
|
||||
đ: 'd',
|
||||
ð: 'd',
|
||||
ı: 'i',
|
||||
ß: 'ss',
|
||||
æ: 'ae',
|
||||
œ: 'oe',
|
||||
þ: 'th',
|
||||
};
|
||||
|
||||
/**
|
||||
* A name as the lookups compare it: lower case, without accents, so
|
||||
* "sao paulo" finds São Paulo, "zurich" Zürich, "lodz" Łódź and "tromso"
|
||||
* Tromsø.
|
||||
*/
|
||||
export const foldName = (name) =>
|
||||
String(name || '')
|
||||
.normalize('NFD')
|
||||
.replace(/\p{M}/gu, '')
|
||||
.toLocaleLowerCase('en')
|
||||
.replace(/[łøđðıßæœþ]/g, (letter) => PLAIN_LETTERS[letter])
|
||||
.trim();
|
||||
const EARTH_KM = 6371;
|
||||
const rad = (deg) => (deg * Math.PI) / 180;
|
||||
|
||||
function distanceKm(lat1, lon1, lat2, lon2) {
|
||||
const a =
|
||||
Math.sin(rad(lat2 - lat1) / 2) ** 2 +
|
||||
Math.cos(rad(lat1)) *
|
||||
Math.cos(rad(lat2)) *
|
||||
Math.sin(rad(lon2 - lon1) / 2) ** 2;
|
||||
return 2 * EARTH_KM * Math.asin(Math.min(1, Math.sqrt(a)));
|
||||
}
|
||||
|
||||
const cellKey = (lat, lon) =>
|
||||
`${Math.floor(lat / CELL_DEG)},${Math.floor(((((lon % 360) + 540) % 360) - 180) / CELL_DEG)}`;
|
||||
|
||||
/** Group rows by one-degree cell so a lookup reads only the cells near it. */
|
||||
export function indexCities(rows) {
|
||||
const cells = new Map();
|
||||
for (const row of rows) {
|
||||
const key = cellKey(row[1], row[2]);
|
||||
const cell = cells.get(key);
|
||||
if (cell) cell.push(row);
|
||||
else cells.set(key, [row]);
|
||||
}
|
||||
return cells;
|
||||
}
|
||||
|
||||
/** Rows by folded name, each list in the rows' own order (largest first). */
|
||||
export function indexNames(rows) {
|
||||
const names = new Map();
|
||||
for (const row of rows) {
|
||||
const key = foldName(row[0]);
|
||||
const list = names.get(key);
|
||||
if (list) list.push(row);
|
||||
else names.set(key, [row]);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
function toCity(row, km) {
|
||||
return {
|
||||
name: row[0],
|
||||
latitude: row[1],
|
||||
longitude: row[2],
|
||||
population: row[3],
|
||||
country: row[4] || null,
|
||||
wikidata: row[5],
|
||||
distanceKm: km,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Half the longitude a circle spans, in degrees: 180 when it reaches a pole,
|
||||
* where every meridian passes through it.
|
||||
*/
|
||||
export function lonHalfSpan(latitude, radiusKm) {
|
||||
const angle = radiusKm / EARTH_KM;
|
||||
const fromPole = Math.PI / 2 - Math.abs(rad(latitude));
|
||||
if (angle >= fromPole) return 180;
|
||||
return (Math.asin(Math.sin(angle) / Math.cos(rad(latitude))) * 180) / Math.PI;
|
||||
}
|
||||
const latHalfSpan = (radiusKm) => ((radiusKm / EARTH_KM) * 180) / Math.PI;
|
||||
|
||||
/** Rows within `radiusKm` of a point, each with its distance. */
|
||||
export function citiesWithin(cells, latitude, longitude, radiusKm) {
|
||||
const latSpan = Math.ceil(latHalfSpan(radiusKm) / CELL_DEG);
|
||||
const lonSpan = Math.ceil(lonHalfSpan(latitude, radiusKm) / CELL_DEG);
|
||||
const found = [];
|
||||
const seen = new Set();
|
||||
for (let dLat = -latSpan; dLat <= latSpan; dLat++) {
|
||||
const lat = latitude + dLat * CELL_DEG;
|
||||
if (lat < -90 - CELL_DEG || lat > 90 + CELL_DEG) continue;
|
||||
for (
|
||||
let dLon = -Math.min(lonSpan, 180);
|
||||
dLon <= Math.min(lonSpan, 180);
|
||||
dLon++
|
||||
) {
|
||||
const key = cellKey(lat, longitude + dLon * CELL_DEG);
|
||||
if (seen.has(key)) continue;
|
||||
seen.add(key);
|
||||
for (const row of cells.get(key) || []) {
|
||||
const km = distanceKm(latitude, longitude, row[1], row[2]);
|
||||
if (km <= radiusKm) found.push(toCity(row, km));
|
||||
}
|
||||
}
|
||||
}
|
||||
return found;
|
||||
}
|
||||
|
||||
// Each country in the pack by what a qualifier may call it: its code, its
|
||||
// English name and its name in the page language, folded.
|
||||
function countryNames(rows) {
|
||||
const names = new Map();
|
||||
for (const code of new Set(rows.map((row) => row[4]).filter(Boolean))) {
|
||||
for (const name of [code, countryName(code, 'en'), countryName(code)])
|
||||
names.set(foldName(name), code);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
let loading = null;
|
||||
/** The indexed pack; a failed load is retried on the next call. */
|
||||
export function loadCities(fetchImpl = (...args) => globalThis.fetch(...args)) {
|
||||
loading ??= fetchImpl(
|
||||
new URL('./local_data/wikidata_cities/cities.json', import.meta.url),
|
||||
)
|
||||
.then((response) => {
|
||||
if (!response.ok) throw new Error(`cities pack: HTTP ${response.status}`);
|
||||
return response.json();
|
||||
})
|
||||
.then((pack) => ({
|
||||
meta: pack.meta,
|
||||
rows: pack.rows,
|
||||
cells: indexCities(pack.rows),
|
||||
names: indexNames(pack.rows),
|
||||
countries: countryNames(pack.rows),
|
||||
}))
|
||||
.catch((error) => {
|
||||
loading = null;
|
||||
throw error;
|
||||
});
|
||||
return loading;
|
||||
}
|
||||
|
||||
/**
|
||||
* The city a point is in or nearest to: the largest within `nearKm`, else the
|
||||
* nearest within `radiusKm`, else null. Preferring the largest nearby keeps a
|
||||
* view over a metropolis from being named after one of its suburbs.
|
||||
*/
|
||||
export async function nearestCity(
|
||||
latitude,
|
||||
longitude,
|
||||
{ radiusKm = 60, nearKm = 12 } = {},
|
||||
) {
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
|
||||
const { cells } = await loadCities();
|
||||
const found = citiesWithin(cells, latitude, longitude, radiusKm);
|
||||
if (!found.length) return null;
|
||||
const near = found.filter((city) => city.distanceKm <= nearKm);
|
||||
if (near.length)
|
||||
return near.reduce((a, b) => (b.population > a.population ? b : a));
|
||||
return found.reduce((a, b) => (b.distanceKm < a.distanceKm ? b : a));
|
||||
}
|
||||
|
||||
/** Cities around a point, most populous first. */
|
||||
export async function citiesAround({
|
||||
latitude,
|
||||
longitude,
|
||||
radiusKm = 50,
|
||||
limit = 8,
|
||||
minPopulation = 0,
|
||||
}) {
|
||||
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return [];
|
||||
const { cells } = await loadCities();
|
||||
return citiesWithin(cells, latitude, longitude, radiusKm)
|
||||
.filter((city) => city.population >= minPopulation)
|
||||
.sort((a, b) => b.population - a.population || a.distanceKm - b.distanceKm)
|
||||
.slice(0, limit);
|
||||
}
|
||||
|
||||
/** A country's name in the page language, from its ISO code. */
|
||||
export function countryName(
|
||||
code,
|
||||
language = globalThis.document?.documentElement?.lang || 'en',
|
||||
) {
|
||||
if (!code) return null;
|
||||
try {
|
||||
return (
|
||||
new Intl.DisplayNames([language], { type: 'region' }).of(code) || code
|
||||
);
|
||||
} catch {
|
||||
return code;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The city with this name, or null. A qualifier after a comma that names a
|
||||
* country ("Paris, France", "Paris, US") keeps only cities there, and finds
|
||||
* nothing when none is; one that names no country ("Paris, Texas") is
|
||||
* ignored. A city of that name within `radiusKm` of `near` (the view) wins,
|
||||
* the nearest first, else the largest city of that name anywhere.
|
||||
*/
|
||||
export async function findPlace(
|
||||
name,
|
||||
{ near = null, radiusKm = 150 } = {},
|
||||
fetchImpl = (...args) => globalThis.fetch(...args),
|
||||
) {
|
||||
const [head, ...rest] = String(name || '').split(',');
|
||||
const wanted = foldName(head);
|
||||
if (!wanted) return null;
|
||||
const qualifier = foldName(rest.join(','));
|
||||
const { names, countries } = await loadCities(fetchImpl);
|
||||
const country = qualifier ? countries.get(qualifier) : undefined;
|
||||
const cities = (names.get(wanted) || []).filter(
|
||||
(row) => !country || row[4] === country,
|
||||
);
|
||||
if (!cities.length) return null;
|
||||
if (Number.isFinite(near?.latitude) && Number.isFinite(near?.longitude)) {
|
||||
let best = null;
|
||||
for (const row of cities) {
|
||||
const km = distanceKm(near.latitude, near.longitude, row[1], row[2]);
|
||||
if (km <= radiusKm && (!best || km < best.distanceKm))
|
||||
best = toCity(row, km);
|
||||
}
|
||||
if (best) return best;
|
||||
}
|
||||
return toCity(cities[0], 0);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
// src/data/wikidataCities.test.mjs — lookups over the bundled Wikidata
|
||||
// places packs, with the packs served from memory.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import {
|
||||
citiesWithin,
|
||||
foldName,
|
||||
indexCities,
|
||||
lonHalfSpan,
|
||||
} from './wikidataCities.js';
|
||||
|
||||
const ROWS = [
|
||||
['São Paulo', -23.55, -46.633, 11451999, 'BR', 'Q174'],
|
||||
['Austin', 30.267, -97.743, 961855, 'US', 'Q16559'],
|
||||
['Round Rock', 30.508, -97.679, 119468, 'US', 'Q128269'],
|
||||
['Zürich', 47.374, 8.541, 421878, 'CH', 'Q72'],
|
||||
];
|
||||
|
||||
test('names compare without case or accents', () => {
|
||||
assert.equal(foldName('São Paulo'), 'sao paulo');
|
||||
assert.equal(foldName(' ZÜRICH '), 'zurich');
|
||||
assert.equal(foldName(null), '');
|
||||
});
|
||||
|
||||
test('a lookup reads the cells around a point and measures each place', () => {
|
||||
const cells = indexCities(ROWS);
|
||||
const near = citiesWithin(cells, 30.27, -97.74, 40).sort(
|
||||
(a, b) => a.distanceKm - b.distanceKm,
|
||||
);
|
||||
assert.deepEqual(
|
||||
near.map((city) => city.name),
|
||||
['Austin', 'Round Rock'],
|
||||
);
|
||||
assert.ok(near[0].distanceKm < 1);
|
||||
assert.equal(near[1].country, 'US');
|
||||
assert.deepEqual(citiesWithin(cells, 0, 0, 50), []);
|
||||
});
|
||||
|
||||
test('findPlace finds a city by its name without accents', async () => {
|
||||
// A fresh module, so its pack cache starts empty.
|
||||
const { findPlace } = await import(`./wikidataCities.js?case=${Date.now()}`);
|
||||
const fetchImpl = async (url) => ({
|
||||
ok: true,
|
||||
json: async () =>
|
||||
String(url).includes('cities.json') ? { meta: {}, rows: ROWS } : null,
|
||||
});
|
||||
const found = await findPlace('sao paulo, Brazil', {}, fetchImpl);
|
||||
assert.equal(found?.wikidata, 'Q174');
|
||||
assert.equal(await findPlace('Atlantis', {}, fetchImpl), null);
|
||||
});
|
||||
|
||||
test('names fold letters that carry no separate accent', () => {
|
||||
assert.equal(foldName('Łódź'), 'lodz');
|
||||
assert.equal(foldName('Tromsø'), 'tromso');
|
||||
assert.equal(foldName('Đà Nẵng'), 'da nang');
|
||||
assert.equal(foldName('Diyarbakır'), 'diyarbakir');
|
||||
assert.equal(foldName('Straße'), 'strasse');
|
||||
});
|
||||
|
||||
const PARIS = [
|
||||
['Paris', 48.857, 2.352, 2145906, 'FR', 'Q90'],
|
||||
['Paris', 33.661, -95.556, 24476, 'US', 'Q830149'],
|
||||
];
|
||||
|
||||
async function freshPack(rows) {
|
||||
const module = await import(
|
||||
`./wikidataCities.js?case=${Date.now()}-${Math.random()}`
|
||||
);
|
||||
const fetchImpl = async () => ({
|
||||
ok: true,
|
||||
json: async () => ({ meta: {}, rows }),
|
||||
});
|
||||
return { ...module, fetchImpl };
|
||||
}
|
||||
|
||||
test('findPlace takes a country qualifier and prefers a namesake in view', async () => {
|
||||
const { findPlace, fetchImpl } = await freshPack(PARIS);
|
||||
const texas = { latitude: 33.2, longitude: -96.0 };
|
||||
assert.equal((await findPlace('Paris', {}, fetchImpl)).wikidata, 'Q90');
|
||||
assert.equal(
|
||||
(await findPlace('Paris', { near: texas }, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
assert.equal(
|
||||
(await findPlace('Paris, United States', {}, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
assert.equal(
|
||||
(await findPlace('paris, us', {}, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
// A qualifier the packs cannot place is ignored.
|
||||
assert.equal(
|
||||
(await findPlace('Paris, Texas', { near: texas }, fetchImpl)).wikidata,
|
||||
'Q830149',
|
||||
);
|
||||
});
|
||||
|
||||
test('a circle that reaches a pole spans every longitude', () => {
|
||||
assert.equal(lonHalfSpan(89, 150), 180);
|
||||
assert.ok(lonHalfSpan(60, 150) < 3);
|
||||
const cells = indexCities([['Pole camp', 89.9, 179, 1, '', 'Q1']]);
|
||||
assert.equal(citiesWithin(cells, 89, 0, 150).length, 1);
|
||||
});
|
||||
|
||||
test('a country qualifier that matches no namesake finds nothing', async () => {
|
||||
const { findPlace, fetchImpl } = await freshPack([
|
||||
...PARIS,
|
||||
['Berlin', 52.52, 13.405, 3755251, 'DE', 'Q64'],
|
||||
]);
|
||||
assert.equal(await findPlace('Paris, Germany', {}, fetchImpl), null);
|
||||
assert.equal(
|
||||
(await findPlace('Paris, France', {}, fetchImpl)).wikidata,
|
||||
'Q90',
|
||||
);
|
||||
});
|
||||
|
||||
test('a lookup wraps at the antimeridian', () => {
|
||||
const cells = indexCities([['Taveuni', -16.8, -179.9, 15000, 'FJ', 'Q2']]);
|
||||
assert.equal(citiesWithin(cells, -16.8, 179.9, 40).length, 1);
|
||||
});
|
||||
@@ -0,0 +1,65 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* A projector from world positions to window coordinates for one pass over
|
||||
* many positions under one camera, giving what
|
||||
* `Cesium.SceneTransforms.worldToWindowCoordinates` gives: in a 3D scene with
|
||||
* a perspective camera it runs the same arithmetic in the same order once the
|
||||
* camera's matrices and the canvas size are read, so the results are the same
|
||||
* numbers; otherwise it asks Cesium for each.
|
||||
*
|
||||
* Read the camera again (a new projector) whenever it may have moved.
|
||||
* @param {Cesium.Scene} scene
|
||||
* @returns {(position: Cesium.Cartesian3, result: Cesium.Cartesian2) =>
|
||||
* Cesium.Cartesian2|undefined} The window position in `result`, or
|
||||
* undefined behind the camera.
|
||||
*/
|
||||
export function createWindowProjector(scene) {
|
||||
const camera = scene?.camera;
|
||||
const frustum = camera?.frustum;
|
||||
if (
|
||||
scene?.frameState?.mode !== Cesium.SceneMode.SCENE3D ||
|
||||
!camera ||
|
||||
frustum instanceof Cesium.OrthographicFrustum ||
|
||||
frustum instanceof Cesium.OrthographicOffCenterFrustum
|
||||
)
|
||||
return (position, result) =>
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates(scene, position, result);
|
||||
const v = camera.viewMatrix;
|
||||
const p = frustum.projectionMatrix;
|
||||
const width = scene.canvas.clientWidth;
|
||||
const height = scene.canvas.clientHeight;
|
||||
const halfWidth = width * 0.5;
|
||||
const halfHeight = height * 0.5;
|
||||
return (position, result) => {
|
||||
if (!position)
|
||||
return Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
result,
|
||||
);
|
||||
const { x, y, z } = position;
|
||||
// Eye coordinates, as Matrix4.multiplyByVector computes them (w = 1).
|
||||
const ex = v[0] * x + v[4] * y + v[8] * z + v[12];
|
||||
const ey = v[1] * x + v[5] * y + v[9] * z + v[13];
|
||||
const ez = v[2] * x + v[6] * y + v[10] * z + v[14];
|
||||
const ew = v[3] * x + v[7] * y + v[11] * z + v[15];
|
||||
// At the eye itself Cesium's own steps have no direction to take.
|
||||
if (ex === 0 && ey === 0 && ez === 0)
|
||||
return Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
result,
|
||||
);
|
||||
// Clip coordinates.
|
||||
const cx = p[0] * ex + p[4] * ey + p[8] * ez + p[12] * ew;
|
||||
const cy = p[1] * ex + p[5] * ey + p[9] * ez + p[13] * ew;
|
||||
const cz = p[2] * ex + p[6] * ey + p[10] * ez + p[14] * ew;
|
||||
const cw = p[3] * ex + p[7] * ey + p[11] * ez + p[15] * ew;
|
||||
if (cz < 0) return undefined;
|
||||
// The viewport transform of the canvas, then window y downward.
|
||||
result.x = halfWidth * (cx / cw) + halfWidth;
|
||||
result.y = height - (halfHeight * (cy / cw) + halfHeight);
|
||||
return result;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createWindowProjector } from './windowProjection.js';
|
||||
|
||||
function sceneLooking(
|
||||
lon,
|
||||
lat,
|
||||
heightM,
|
||||
pitchDeg,
|
||||
mode = Cesium.SceneMode.SCENE3D,
|
||||
) {
|
||||
const scene = {
|
||||
canvas: { clientWidth: 1713, clientHeight: 941 },
|
||||
drawingBufferWidth: 1713,
|
||||
drawingBufferHeight: 941,
|
||||
mapProjection: new Cesium.GeographicProjection(),
|
||||
ellipsoid: Cesium.Ellipsoid.WGS84,
|
||||
frameState: { mode, mapProjection: new Cesium.GeographicProjection() },
|
||||
globe: undefined,
|
||||
tweens: { add() {} },
|
||||
screenSpaceCameraController: { minimumZoomDistance: 1 },
|
||||
};
|
||||
scene.camera = new Cesium.Camera(scene);
|
||||
scene.camera.frustum.aspectRatio = 1713 / 941;
|
||||
scene.camera.setView({
|
||||
destination: Cesium.Cartesian3.fromDegrees(lon, lat, heightM),
|
||||
orientation: {
|
||||
heading: 0.3,
|
||||
pitch: Cesium.Math.toRadians(pitchDeg),
|
||||
roll: 0,
|
||||
},
|
||||
});
|
||||
return scene;
|
||||
}
|
||||
|
||||
function positionsAround(lon, lat, spreadDeg, count) {
|
||||
let seed = 7;
|
||||
const rnd = () => (seed = (seed * 16807) % 2147483647) / 2147483647;
|
||||
return Array.from({ length: count }, () =>
|
||||
Cesium.Cartesian3.fromDegrees(
|
||||
lon + (rnd() - 0.5) * spreadDeg,
|
||||
lat + (rnd() - 0.5) * spreadDeg,
|
||||
rnd() * 50,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
test('a 3D perspective projector gives the same numbers Cesium gives', () => {
|
||||
for (const [pitch, spread, heightM] of [
|
||||
[-90, 1, 60_000],
|
||||
[-35, 4, 60_000],
|
||||
[-5, 40, 60_000],
|
||||
// Just above the sea, points near and behind the near plane.
|
||||
[-10, 0.002, 3],
|
||||
]) {
|
||||
const scene = sceneLooking(4.1, 51.95, heightM, pitch);
|
||||
const project = createWindowProjector(scene);
|
||||
let behind = 0;
|
||||
for (const position of positionsAround(4.1, 51.95, spread, 2000)) {
|
||||
const expected = Cesium.SceneTransforms.worldToWindowCoordinates(
|
||||
scene,
|
||||
position,
|
||||
new Cesium.Cartesian2(),
|
||||
);
|
||||
const actual = project(position, new Cesium.Cartesian2());
|
||||
if (!expected) {
|
||||
behind++;
|
||||
assert.equal(actual, undefined);
|
||||
continue;
|
||||
}
|
||||
assert.equal(actual.x, expected.x);
|
||||
assert.equal(actual.y, expected.y);
|
||||
}
|
||||
if (pitch === -5)
|
||||
assert.ok(behind > 0, 'some positions fall behind the camera');
|
||||
}
|
||||
});
|
||||
|
||||
test('outside a 3D scene the projector asks Cesium', () => {
|
||||
const scene = sceneLooking(
|
||||
4.1,
|
||||
51.95,
|
||||
60_000,
|
||||
-90,
|
||||
Cesium.SceneMode.COLUMBUS_VIEW,
|
||||
);
|
||||
const calls = [];
|
||||
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = (...args) => {
|
||||
calls.push(args);
|
||||
return args[2];
|
||||
};
|
||||
try {
|
||||
const result = new Cesium.Cartesian2();
|
||||
const position = Cesium.Cartesian3.fromDegrees(4.1, 51.95);
|
||||
assert.equal(createWindowProjector(scene)(position, result), result);
|
||||
assert.equal(calls.length, 1);
|
||||
assert.equal(calls[0][1], position);
|
||||
} finally {
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = original;
|
||||
}
|
||||
});
|
||||
|
||||
test('at the eye itself, or with no position, the projector asks Cesium', () => {
|
||||
const scene = sceneLooking(4.1, 51.95, 60_000, -90);
|
||||
const original = Cesium.SceneTransforms.worldToWindowCoordinates;
|
||||
const asked = [];
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = (_scene, position) => {
|
||||
asked.push(position);
|
||||
return undefined;
|
||||
};
|
||||
try {
|
||||
const project = createWindowProjector(scene);
|
||||
const eye = Cesium.Cartesian3.clone(scene.camera.positionWC);
|
||||
assert.equal(project(eye, new Cesium.Cartesian2()), undefined);
|
||||
assert.equal(project(undefined, new Cesium.Cartesian2()), undefined);
|
||||
assert.deepEqual(asked, [eye, undefined]);
|
||||
} finally {
|
||||
Cesium.SceneTransforms.worldToWindowCoordinates = original;
|
||||
}
|
||||
});
|
||||
Reference in new issue
Block a user