mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-19 01:32:19 +00:00
Merge branch 'main' into feat/australia-transit
This commit is contained in:
298 files changed
+11215
-1369
No files matched your search
Vendored
+8
@@ -8,6 +8,9 @@ import { useDisplayStore } from '../ui/stores/display.js';
|
||||
import { applicationPinia } from '../ui/vueRuntime.js';
|
||||
import { t } from '../i18n/index.js';
|
||||
|
||||
/** Where the camera starts unless a host gives a `startView`. */
|
||||
export { START_VIEW };
|
||||
|
||||
/**
|
||||
* Construct the existing controls and camera presentation. `initialShareCode`
|
||||
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
|
||||
@@ -15,6 +18,9 @@ import { t } from '../i18n/index.js';
|
||||
* picker, for a host that offers its own language choice (`switchLocale` from
|
||||
* the `./i18n` entry). `startView` is where the camera starts (the whole
|
||||
* planet by default; a host may pass a city); a shared view flies from there.
|
||||
* `homeView` is where the title's logo goes back to (with the clock live): the
|
||||
* start view unless given, for a host whose `startView` only carries a view
|
||||
* across a rebuild.
|
||||
* `services.cockpitSubjects` adds the application's own first-person subjects
|
||||
* to the Cockpit (src/cockpitSubjectProviders.js).
|
||||
*/
|
||||
@@ -29,6 +35,7 @@ export function createApplicationControls({
|
||||
initialShareCode = null,
|
||||
localePicker = true,
|
||||
startView = START_VIEW,
|
||||
homeView = startView,
|
||||
}) {
|
||||
// Every boot starts from the same view, before share restoration flies on.
|
||||
applyStartView(viewer, startView);
|
||||
@@ -51,6 +58,7 @@ export function createApplicationControls({
|
||||
// A share code to open at start-up instead of the page's address.
|
||||
initialShareCode,
|
||||
localePicker,
|
||||
homeView,
|
||||
});
|
||||
defer(() => styleManager.orbitController.stop());
|
||||
defer(() => styleManager.hud.destroy());
|
||||
|
||||
@@ -48,6 +48,10 @@ import { overlayHost } from './layers/overlayHost.js';
|
||||
* Attach scene tools, rendering listeners and the application debug handle.
|
||||
* `scene` is what `createApplicationScene` returns; its `trimStaleCommands`
|
||||
* runs after each layer disable (a scene without one keeps that memory).
|
||||
* `library.fetchTile` and `library.fetchData` fetch the Data Library's tiles
|
||||
* and proxied datasets in place of the defaults (`createLibrarySource`).
|
||||
* `library.requireCatalog` offers only what the server's library catalog
|
||||
* names, and nothing while it does not answer.
|
||||
*/
|
||||
export function createApplicationTools({
|
||||
scene,
|
||||
@@ -60,6 +64,7 @@ export function createApplicationTools({
|
||||
onSceneDirector,
|
||||
sceneDataPacks,
|
||||
drawMarkActions = [],
|
||||
library = {},
|
||||
signal,
|
||||
defer,
|
||||
}) {
|
||||
@@ -158,6 +163,11 @@ export function createApplicationTools({
|
||||
mapStackController,
|
||||
shareLink: styleManager.shareLinkManager,
|
||||
requestRender: governorRequestRender,
|
||||
// An application's own tile and dataset fetches, when it keeps them in
|
||||
// its own cache.
|
||||
fetchTile: library.fetchTile ?? null,
|
||||
fetchData: library.fetchData ?? null,
|
||||
requireCatalog: library.requireCatalog === true,
|
||||
// Zoom to layer: an immediate navigation, so Cockpit can refuse it and
|
||||
// the current follow owner is released first (as for imported files).
|
||||
zoomTo: (extent) =>
|
||||
|
||||
@@ -98,7 +98,7 @@ export function normalizeAdsbLolAircraftState(aircraft, nowSeconds) {
|
||||
* Normalize an adsb.lol point response to an OpenSky-compatible response.
|
||||
* Invalid rows and positionless contacts are intentionally excluded.
|
||||
* @param {object} payload adsb.lol v2 response.
|
||||
* @returns {{time:number,states:Array[]}}
|
||||
* @returns {{time:number,states:Array[],emergencyByIcao?:object,typeByIcao?:object}}
|
||||
*/
|
||||
export function normalizeAdsbLolPointResponse(payload) {
|
||||
const responseNow = finiteNumber(payload?.now);
|
||||
@@ -111,9 +111,10 @@ export function normalizeAdsbLolPointResponse(payload) {
|
||||
const aircraft = Array.isArray(payload?.ac) ? payload.ac : [];
|
||||
const states = [];
|
||||
// Keep the OpenSky vectors unchanged. The regional fallback's extra readsb
|
||||
// status travels alongside them, keyed only to admitted aircraft.
|
||||
// status and type travel alongside them, keyed only to admitted aircraft.
|
||||
const admitted = new Set();
|
||||
const statuses = [];
|
||||
const types = [];
|
||||
for (const row of aircraft) {
|
||||
const state = normalizeAdsbLolAircraftState(row, nowSeconds);
|
||||
if (!state) continue;
|
||||
@@ -125,11 +126,17 @@ export function normalizeAdsbLolPointResponse(payload) {
|
||||
admitted.add(id);
|
||||
if (typeof row.emergency === 'string')
|
||||
statuses.push([id, row.emergency.trim().toLowerCase()]);
|
||||
const type = typeof row.t === 'string' ? row.t.trim().toUpperCase() : '';
|
||||
if (type) types.push([id, type]);
|
||||
}
|
||||
const emergencyByIcao = Object.fromEntries(statuses);
|
||||
const typeByIcao = Object.fromEntries(types);
|
||||
return {
|
||||
time: nowSeconds,
|
||||
states,
|
||||
...(Object.keys(emergencyByIcao).length ? { emergencyByIcao } : {}),
|
||||
// The ICAO type designator (readsb `t`), so the aircraft is classed from
|
||||
// its first fix instead of after a lookup.
|
||||
...(types.length ? { typeByIcao } : {}),
|
||||
};
|
||||
}
|
||||
@@ -61,3 +61,22 @@ test('an aircraft with no track takes its true heading, never its magnetic one',
|
||||
assert.equal(at({ mag_heading: 278.44 }), null, 'not magnetic');
|
||||
assert.equal(at({}), null, 'none');
|
||||
});
|
||||
|
||||
test('the point response sends each admitted aircraft type alongside the vectors', () => {
|
||||
const response = normalizeAdsbLolPointResponse({
|
||||
now: 1000,
|
||||
ac: [
|
||||
{ hex: 'A1B2C3', lat: 30, lon: -97, t: 'ec45' },
|
||||
{ hex: 'A1B2C3', lat: 31, lon: -97, t: 'B738' },
|
||||
{ hex: 'D4E5F6', lat: 30, lon: -98 },
|
||||
{ hex: 'BAD000', t: 'A320' },
|
||||
],
|
||||
});
|
||||
assert.equal(response.states.length, 3);
|
||||
assert.deepEqual(response.typeByIcao, { a1b2c3: 'EC45' });
|
||||
const untyped = normalizeAdsbLolPointResponse({
|
||||
now: 1000,
|
||||
ac: [{ hex: 'D4E5F6', lat: 30, lon: -98 }],
|
||||
});
|
||||
assert.equal(Object.hasOwn(untyped, 'typeByIcao'), false);
|
||||
});
|
||||
+35
-13
@@ -401,6 +401,11 @@ const OPENSKY_CATEGORY = {
|
||||
7: 'fastjet', // High performance (>5g, >400 kt)
|
||||
8: 'helicopter', // Rotorcraft
|
||||
9: 'glider',
|
||||
16: 'vehicle', // Surface vehicle, emergency
|
||||
17: 'vehicle', // Surface vehicle, service
|
||||
18: 'station', // Point obstacle
|
||||
19: 'station', // Cluster obstacle
|
||||
20: 'station', // Line obstacle
|
||||
};
|
||||
|
||||
/** ADS-B emitter-category string → class. */
|
||||
@@ -413,13 +418,35 @@ const EMITTER_CATEGORY = {
|
||||
A6: 'fastjet',
|
||||
A7: 'helicopter',
|
||||
B1: 'glider',
|
||||
C1: 'vehicle', // Surface vehicle, emergency
|
||||
C2: 'vehicle', // Surface vehicle, service
|
||||
C3: 'station', // Point obstacle
|
||||
C4: 'station', // Cluster obstacle
|
||||
C5: 'station', // Line obstacle
|
||||
};
|
||||
|
||||
/**
|
||||
* The type codes feeds give what is not an aircraft: an airport vehicle
|
||||
* (ZVEH) and a ground station (GRND).
|
||||
*/
|
||||
const GROUND_TYPE_CLASS = { ZVEH: 'vehicle', GRND: 'station' };
|
||||
|
||||
/**
|
||||
* The class an aircraft draws and reads as, from its ICAO type code (which
|
||||
* outranks the category), else its OpenSky integer or ADS-B emitter category.
|
||||
* Besides the aircraft classes, `vehicle` is an airport vehicle (type ZVEH,
|
||||
* emitter C1 or C2) and `station` a ground station or obstacle (type GRND,
|
||||
* emitter C3 to C5). A known type code outside every set is an airliner, and
|
||||
* so is a contact with nothing to go on.
|
||||
* @param {{typeCode?: string|null, category?: string|number|null}} [record]
|
||||
* @returns {string}
|
||||
*/
|
||||
export function classifyAircraft({ typeCode, category } = {}) {
|
||||
const code = String(typeCode || '')
|
||||
.trim()
|
||||
.toUpperCase();
|
||||
if (code) {
|
||||
if (GROUND_TYPE_CLASS[code]) return GROUND_TYPE_CLASS[code];
|
||||
if (FASTJET.has(code)) return 'fastjet';
|
||||
if (UAV.has(code)) return 'uav';
|
||||
if (HELI.has(code)) return 'helicopter';
|
||||
@@ -452,18 +479,13 @@ export const AIRCRAFT_CLASS_LABELS = Object.freeze({
|
||||
fastjet: msg('Fast jet'),
|
||||
bizjet: msg('Business jet'),
|
||||
uav: msg('Drone'),
|
||||
vehicle: msg('Airport vehicle'),
|
||||
station: msg('Ground station / obstacle'),
|
||||
});
|
||||
|
||||
/** Billboard scale multipliers (skylight GLYPH_SCALE, + fastjet). */
|
||||
export const CLASS_SCALE_2D = {
|
||||
light: 0.62,
|
||||
glider: 0.58,
|
||||
turboprop: 0.86,
|
||||
airliner: 1.0,
|
||||
widebody: 1.3,
|
||||
quadjet: 1.45,
|
||||
helicopter: 0.82,
|
||||
fastjet: 0.8,
|
||||
bizjet: 0.72,
|
||||
uav: 0.75,
|
||||
};
|
||||
/**
|
||||
* The tint an airport vehicle's sprite draws with in Flights and Local
|
||||
* ADS-B: an orange amber, apart from aircraft white and the military layer's
|
||||
* yellow amber (#FFB800).
|
||||
*/
|
||||
export const VEHICLE_TINT_CSS = '#FF8F1F';
|
||||
@@ -1,7 +1,7 @@
|
||||
// src/data/aircraftClass.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { classifyAircraft, CLASS_SCALE_2D } from './aircraftClass.js';
|
||||
import { AIRCRAFT_CLASS_LABELS, classifyAircraft } from './aircraftClass.js';
|
||||
|
||||
test('type-code classification (military layer path)', () => {
|
||||
assert.equal(classifyAircraft({ typeCode: 'F16' }), 'fastjet');
|
||||
@@ -48,8 +48,53 @@ test('typeCode outranks category; unknown → airliner', () => {
|
||||
assert.equal(classifyAircraft({ typeCode: null, category: 0 }), 'airliner');
|
||||
});
|
||||
|
||||
test('the icon scale table covers every class', () => {
|
||||
for (const kind of ['light','glider','turboprop','airliner','widebody','quadjet','helicopter','fastjet','bizjet','uav']) {
|
||||
assert.ok(Number.isFinite(CLASS_SCALE_2D[kind]), kind);
|
||||
test('every class has a label', () => {
|
||||
for (const kind of [
|
||||
'light',
|
||||
'glider',
|
||||
'turboprop',
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'helicopter',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
'vehicle',
|
||||
'station',
|
||||
]) {
|
||||
assert.ok(AIRCRAFT_CLASS_LABELS[kind], kind);
|
||||
}
|
||||
});
|
||||
|
||||
test('airport vehicles and ground stations class apart from aircraft', () => {
|
||||
// A feed's own types, in any case.
|
||||
assert.equal(classifyAircraft({ typeCode: 'ZVEH' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ typeCode: ' zveh ' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ typeCode: 'GRND' }), 'station');
|
||||
// Emitter categories: surface vehicles, then obstacles.
|
||||
assert.equal(classifyAircraft({ category: 'C1' }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 'C2' }), 'vehicle');
|
||||
for (const category of ['C3', 'C4', 'C5'])
|
||||
assert.equal(classifyAircraft({ category }), 'station', category);
|
||||
// OpenSky's integer categories for the same.
|
||||
assert.equal(classifyAircraft({ category: 16 }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 17 }), 'vehicle');
|
||||
assert.equal(classifyAircraft({ category: 18 }), 'station');
|
||||
// A type code still outranks the category.
|
||||
assert.equal(
|
||||
classifyAircraft({ typeCode: 'ZVEH', category: 'A3' }),
|
||||
'vehicle',
|
||||
);
|
||||
assert.equal(
|
||||
classifyAircraft({ typeCode: 'A320', category: 'C1' }),
|
||||
'airliner',
|
||||
);
|
||||
});
|
||||
|
||||
test('helicopter types and categories', () => {
|
||||
for (const typeCode of ['EC35', 'R44', 'S76', 'H60', 'AS50', 'B407'])
|
||||
assert.equal(classifyAircraft({ typeCode }), 'helicopter', typeCode);
|
||||
assert.equal(classifyAircraft({ category: 'A7' }), 'helicopter');
|
||||
assert.equal(classifyAircraft({ category: 8 }), 'helicopter');
|
||||
});
|
||||
@@ -1,5 +1,3 @@
|
||||
import { TRACKED_ICON_COLOR } from '../layers/military/policy.js';
|
||||
import { TRACKED_CYAN } from '../layers/flights/policy.js';
|
||||
import { createRendering as civilRendering } from '../layers/flights/rendering.js';
|
||||
import { createRendering as militaryRendering } from '../layers/military/rendering.js';
|
||||
import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js';
|
||||
@@ -463,15 +461,16 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do
|
||||
assert.equal(rendering._modelColor('civil'), red);
|
||||
if (rendering._cockpitContactColor)
|
||||
assert.equal(rendering._cockpitContactColor('civil'), red);
|
||||
// Tracking never recolours: a tracked emergency stays red.
|
||||
flightState._trackedIcao = 'civil';
|
||||
assert.equal(
|
||||
rendering._modelColor('civil'),
|
||||
factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR,
|
||||
);
|
||||
assert.equal(rendering._modelColor('civil'), red);
|
||||
flightState._trackedIcao = null;
|
||||
flightState.records.data.set('civil', { emergency: null });
|
||||
// An ordinary model draws its mesh's own colours, whatever the billboard's.
|
||||
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
|
||||
flightState._trackedIcao = 'civil';
|
||||
assert.deepEqual([...rendering._modelColor('civil')], [1, 1, 1, 1]);
|
||||
flightState._trackedIcao = null;
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
@@ -32,6 +32,7 @@ import {
|
||||
TRACKED_ICON_PX,
|
||||
} from './aircraftIcons.js';
|
||||
import { cockpitContactDotImage } from './cockpitContactDot.js';
|
||||
import { rotorFrame, rotorTurns } from './rotorFrames.js';
|
||||
import { aircraftRecedeSpec } from './aircraftRecession.js';
|
||||
import { TIMELINE_UNSEEN_MS } from '../time/timelineFixes.js';
|
||||
|
||||
@@ -456,6 +457,14 @@ export function createAircraftIcons({
|
||||
const { focusPassIsNeeded } = services.focus;
|
||||
// The near-image switch the rows were last written with (CSS px).
|
||||
let switchPx = nearImageSwitchPx(1);
|
||||
/**
|
||||
* Airborne helicopters drawn as their glyph, whose rotor turns: the rotor
|
||||
* frame each was last drawn at, and the frame it was last judged at
|
||||
* (`_turnRotors`), so one out of view is judged again only once its frame
|
||||
* has stepped on.
|
||||
* @type {Map<string, {drawn: number, checked: number}>}
|
||||
*/
|
||||
const rotors = new Map();
|
||||
|
||||
/** The delayed instant (epoch ms) every untracked contact is drawn at. */
|
||||
const _displayMs = () =>
|
||||
@@ -473,6 +482,9 @@ export function createAircraftIcons({
|
||||
* back before it (`_replanExpired`).
|
||||
*/
|
||||
const planFrom = new Map();
|
||||
/** When each placed contact's running ease ends (epoch ms): a new answer
|
||||
* while it runs eases on from where it is drawn instead of cutting it. */
|
||||
const easeEnds = new Map();
|
||||
/** The display time the rows were last checked against. */
|
||||
let replannedAt = -Infinity;
|
||||
|
||||
@@ -543,7 +555,9 @@ export function createAircraftIcons({
|
||||
state._icons?.dispose();
|
||||
state._icons = null;
|
||||
liveSet = null;
|
||||
rotors.clear();
|
||||
planFrom.clear();
|
||||
easeEnds.clear();
|
||||
replannedAt = -Infinity;
|
||||
}
|
||||
|
||||
@@ -607,13 +621,19 @@ export function createAircraftIcons({
|
||||
* Following the clock, a contact not there yet at the time drawn
|
||||
* (`regime.unseen`) is not drawn until its warm-up begins.
|
||||
* @param {string} icao24
|
||||
* @param {{fromCourseDeg?: number|null, rewound?: boolean}} [options]
|
||||
* @param {{fromCourseDeg?: number|null, rewound?: boolean,
|
||||
* handover?: boolean}} [options]
|
||||
* `fromCourseDeg`: nose to glide from when the row's own motion is not
|
||||
* what was on screen (tracking handoff). `rewound`: the time drawn moved
|
||||
* back before the row's motion; it is drawn where it was then, with no
|
||||
* easing from where it is drawn now.
|
||||
* easing from where it is drawn now. `handover`: the clock came back to
|
||||
* live and this is the contact's first live fix: it eases from where it
|
||||
* is drawn onto its live path, however its last plan ran out.
|
||||
*/
|
||||
function _planIcon(icao24, { fromCourseDeg, rewound = false } = {}) {
|
||||
function _planIcon(
|
||||
icao24,
|
||||
{ fromCourseDeg, rewound = false, handover = false } = {},
|
||||
) {
|
||||
const icons = state._icons;
|
||||
if (!icons?.has(icao24) || holdsPlan(icao24)) return;
|
||||
const history = state._positionHistory.get(icao24);
|
||||
@@ -628,7 +648,7 @@ export function createAircraftIcons({
|
||||
|
||||
// A host-supplied placement decides where a live contact is drawn; with
|
||||
// none, or no answer for this contact, the layer's own motion below does.
|
||||
if (_planPlaced(icao24, info, history, t)) return;
|
||||
if (_planPlaced(icao24, info, history, t, handover)) return;
|
||||
|
||||
const regime = parts.motion._motionRegime(history, info, renderTime);
|
||||
if (regime.unseen) {
|
||||
@@ -745,7 +765,7 @@ export function createAircraftIcons({
|
||||
fromCourseDeg == null &&
|
||||
!rewound &&
|
||||
icons.shown(icao24) &&
|
||||
icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS
|
||||
(handover || icons.expires(icao24) > t - RECOVER_STALE_PLAN_MS)
|
||||
) {
|
||||
const prev = icons.item(icao24);
|
||||
const drawn = motionPosition(prev.motion, prev.pos, t);
|
||||
@@ -804,13 +824,21 @@ export function createAircraftIcons({
|
||||
* @returns {boolean} False when there is no placement, the layer follows
|
||||
* the world clock, or it has no answer for this contact.
|
||||
*/
|
||||
function _planPlaced(icao24, info, history, t) {
|
||||
function _planPlaced(icao24, info, history, t, handover = false) {
|
||||
if (!placeAt || followsClock()) return false;
|
||||
const leadMs = displayDelay.currentMs;
|
||||
const from = vec();
|
||||
const start = placeAt(icao24, t + leadMs, info, history, from);
|
||||
if (!start) return false;
|
||||
const { courseDeg: course } = start;
|
||||
// Back at live, or while an ease runs, it eases on from where it is drawn.
|
||||
const easing = easeEnds.get(icao24) > t;
|
||||
if (
|
||||
(handover || easing) &&
|
||||
_easePlaced(icao24, info, history, t, from, start)
|
||||
)
|
||||
return true;
|
||||
easeEnds.delete(icao24);
|
||||
const t1 = t + PLACED_PLAN_MS;
|
||||
const to = vec();
|
||||
const end = placeAt(icao24, t1 + leadMs, info, history, to);
|
||||
@@ -835,6 +863,40 @@ export function createAircraftIcons({
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live, a placed contact still on screen eases from where it is
|
||||
* drawn onto where it is placed, as the layer's own motion recovers (and a
|
||||
* new answer while that ease runs eases on from where it is then): along
|
||||
* the straight line to where the placement has it when the ease ends, nose
|
||||
* along that line, unless it is nearer than a recovery or farther than a
|
||||
* jump would be.
|
||||
* @returns {boolean} Whether the contact was planned to ease.
|
||||
*/
|
||||
function _easePlaced(icao24, info, history, t, placed, start) {
|
||||
const icons = state._icons;
|
||||
if (!icons.shown(icao24)) return false;
|
||||
const prev = icons.item(icao24);
|
||||
const drawn = motionPosition(prev.motion, prev.pos, t);
|
||||
const errorM = distance(drawn, placed);
|
||||
if (!(errorM > RECOVER_MIN_M && errorM < RECOVER_SNAP_M)) return false;
|
||||
const speed = start.speedMps ?? info?.velocity ?? 0;
|
||||
const end = t + recoveryMs(errorM, speed);
|
||||
const target = vec();
|
||||
if (!placeAt(icao24, end + displayDelay.currentMs, info, history, target))
|
||||
return false;
|
||||
const motion = straightSegment(drawn, t, end, target);
|
||||
const course = motionCourse(motion, undefined, t);
|
||||
icons.setUnseen(icao24, false);
|
||||
icons.update(
|
||||
icao24,
|
||||
{ pos: clone(drawn), course, motion, courseGlide: undefined },
|
||||
{ expiresAt: end },
|
||||
);
|
||||
planFrom.set(icao24, t);
|
||||
easeEnds.set(icao24, end);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Re-plan every row whose regime ended by `t` (epoch ms), and, following
|
||||
* the clock, every row whose motion starts after `t` once the time drawn
|
||||
@@ -906,26 +968,94 @@ export function createAircraftIcons({
|
||||
* @returns {{image: string, imageLod: {near: string, switchPx: number},
|
||||
* size: [number, number], scale: number, scaleByDistance: object}}
|
||||
*/
|
||||
function _fleetLook(icao24, info = state.records.data.get(icao24)) {
|
||||
function _fleetLook(
|
||||
icao24,
|
||||
info = state.records.data.get(icao24),
|
||||
frame = _rotorFrameOf(icao24, info, Date.now()),
|
||||
) {
|
||||
const rendering = parts.rendering;
|
||||
return {
|
||||
image: aircraftIcon(
|
||||
rendering._iconKind(icao24, info?.klass),
|
||||
FLEET_ICON_PX,
|
||||
frame,
|
||||
),
|
||||
imageLod: {
|
||||
near: aircraftIcon(
|
||||
rendering._iconKind(icao24, info?.klass),
|
||||
TRACKED_ICON_PX,
|
||||
frame,
|
||||
),
|
||||
switchPx,
|
||||
},
|
||||
size: [FLEET_ICON_SIZE_PX, FLEET_ICON_SIZE_PX],
|
||||
scale: rendering._fleetBillboardScale(icao24, info?.klass),
|
||||
scale: rendering._fleetBillboardScale(icao24),
|
||||
scaleByDistance: NORMAL_SCALE_BY_DISTANCE,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotor frame a contact draws at `nowMs` (`rotorFrames.js`): a
|
||||
* helicopter's, which holds still on the ground unless it taxis; undefined
|
||||
* for every other kind.
|
||||
*/
|
||||
function _rotorFrameOf(icao24, info, nowMs) {
|
||||
if (parts.rendering._iconKind(icao24, info?.klass) !== 'helicopter')
|
||||
return undefined;
|
||||
return rotorFrame(icao24, nowMs, _rotorState(info));
|
||||
}
|
||||
|
||||
/** What turns a contact's rotor: whether it is grounded, and its speed (m/s). */
|
||||
function _rotorState(info) {
|
||||
const speed = info?.velocity ?? info?.speedMps;
|
||||
return {
|
||||
onGround: info?.onGround === true,
|
||||
speedMps: Number.isFinite(speed) ? speed : null,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Turn the rotors of the airborne helicopters in view: each one's images
|
||||
* are written again only when its rotor frame changed (`ROTOR_FPS`, run
|
||||
* from the fleet pass). One out of view, below the horizon, or hidden for
|
||||
* its 3D model keeps its frame. The tracked one is drawn by the tracked
|
||||
* icon, which is given its new images. With no airborne helicopter drawn
|
||||
* this does nothing.
|
||||
* @param {number} nowMs Epoch ms the frame is chosen at.
|
||||
* @param {number} t The display instant, epoch ms (where icons are drawn).
|
||||
* @param {((position: {x: number, y: number, z: number}) => boolean)|null}
|
||||
* [inView] Whether a position is in the camera's view; none: all are.
|
||||
*/
|
||||
function _turnRotors(nowMs, t, inView = null) {
|
||||
const icons = state._icons;
|
||||
if (!rotors.size || !icons) return;
|
||||
let occluder;
|
||||
for (const [id, rotor] of rotors) {
|
||||
const frame = rotorFrame(id, nowMs);
|
||||
// Drawn at this frame, or already judged at it: nothing to do.
|
||||
if (frame === rotor.drawn || frame === rotor.checked) continue;
|
||||
rotor.checked = frame;
|
||||
const tracked = id === state._trackedIcao;
|
||||
if (!icons.has(id) || (!tracked && !icons.shown(id))) continue;
|
||||
const position = icons.position(id, t);
|
||||
if (!position) continue;
|
||||
if (occluder === undefined) occluder = _occluder();
|
||||
if (!_aboveHorizon(position, occluder)) continue;
|
||||
if (inView && !inView(position)) continue;
|
||||
rotor.drawn = frame;
|
||||
if (tracked) {
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
continue;
|
||||
}
|
||||
const { image, imageLod } = _fleetLook(
|
||||
id,
|
||||
state.records.data.get(id),
|
||||
frame,
|
||||
);
|
||||
icons.update(id, { image, imageLod });
|
||||
}
|
||||
}
|
||||
|
||||
/** Image, size, scale, tint and freshness for one row under the current
|
||||
* normal/cockpit contract. Motion and course stay with `_planIcon`. */
|
||||
function _applyIconPresentation(icao24) {
|
||||
@@ -953,8 +1083,27 @@ export function createAircraftIcons({
|
||||
color: rgba(rendering._fleetBillboardColor(icao24, info)),
|
||||
rotationMode: 'course',
|
||||
};
|
||||
// A ground station's mast stands upright.
|
||||
if (!cockpitDot && info?.klass === 'station') {
|
||||
look.rotationMode = 'screen';
|
||||
look.rotation = 0;
|
||||
}
|
||||
look.alpha = state.records.missingPolls.get(icao24) ? staleAlpha : 1;
|
||||
icons.update(icao24, look);
|
||||
// An airborne helicopter drawn as its glyph turns its rotor.
|
||||
const frame = cockpitDot
|
||||
? undefined
|
||||
: _rotorFrameOf(icao24, info, Date.now());
|
||||
if (frame === undefined || !rotorTurns(_rotorState(info))) {
|
||||
// A tracked helicopter that lands shows the still frame at once.
|
||||
if (rotors.delete(icao24) && tracked)
|
||||
parts.tracking?._syncTrackedBillboardImage?.();
|
||||
} else rotors.set(icao24, { drawn: frame, checked: frame });
|
||||
}
|
||||
|
||||
/** Whether any airborne helicopter's rotor turns (`_turnRotors` has work). */
|
||||
function _rotorsTurning() {
|
||||
return rotors.size > 0;
|
||||
}
|
||||
|
||||
/** Add a row for a new contact, hidden while it is the tracked one. */
|
||||
@@ -990,7 +1139,9 @@ export function createAircraftIcons({
|
||||
/** Drop a contact and everything the layer keeps for it. */
|
||||
function _forgetContact(icao24) {
|
||||
state._icons?.remove(icao24);
|
||||
rotors.delete(icao24);
|
||||
planFrom.delete(icao24);
|
||||
easeEnds.delete(icao24);
|
||||
parts.rendering._releaseModel(icao24);
|
||||
state.records.forget(icao24);
|
||||
// The host-supplied placement, if any, forgets it as well.
|
||||
@@ -1025,6 +1176,8 @@ export function createAircraftIcons({
|
||||
_focusIcons,
|
||||
_applyIconPresentation,
|
||||
_fleetLook,
|
||||
_turnRotors,
|
||||
_rotorsTurning,
|
||||
_addIcon,
|
||||
_forgetContact,
|
||||
_iconIds,
|
||||
|
||||
@@ -6,10 +6,12 @@ import {
|
||||
createContactIcons,
|
||||
floorCoastArc,
|
||||
} from './aircraftIconLayer.js';
|
||||
import { COAST_FLOOR_LIFT_M } from './motionModel.js';
|
||||
import { COAST_FLOOR_LIFT_M, recoveryMs } from './motionModel.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../geo/ellipsoid.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { createDisplayDelay } from './displayDelay.js';
|
||||
import { aircraftIcon, FLEET_ICON_PX } from './aircraftIcons.js';
|
||||
import { ROTOR_STILL_FRAME } from './rotorFrames.js';
|
||||
|
||||
const WORLD_MS = Date.UTC(2026, 10, 1, 12, 0);
|
||||
|
||||
@@ -199,3 +201,283 @@ test('a coast over known ground that never rises is planned once', () => {
|
||||
'held on the ground where the coast stopped',
|
||||
);
|
||||
});
|
||||
|
||||
test('only airborne helicopters in view turn their rotor, written when the frame steps', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const here = fromDegrees(0, 30, 300);
|
||||
const away = fromDegrees(90, 30, 300);
|
||||
const records = new Map([
|
||||
['h1', { klass: 'helicopter', onGround: false }],
|
||||
['h2', { klass: 'helicopter', onGround: true }],
|
||||
['p1', { klass: 'airliner', onGround: false }],
|
||||
['h3', { klass: 'helicopter', onGround: false }],
|
||||
]);
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(),
|
||||
_cockpitNearContacts: new Set(),
|
||||
records: { data: records, missingPolls: new Map() },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
rendering: {
|
||||
_iconKind: (_id, klass) => klass,
|
||||
_fleetBillboardColor: () => [1, 1, 1, 1],
|
||||
_fleetBillboardScale: () => 1,
|
||||
},
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
});
|
||||
for (const id of records.keys()) {
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: id === 'h3' ? away : here,
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: Infinity },
|
||||
);
|
||||
icons._applyIconPresentation(id);
|
||||
}
|
||||
const image = (id) => state._icons.item(id).image;
|
||||
// The grounded helicopter holds the still frame.
|
||||
assert.equal(
|
||||
image('h2'),
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
const h3Before = image('h3');
|
||||
const writes = new Map();
|
||||
const update = state._icons.update;
|
||||
state._icons.update = (id, patch, options) => {
|
||||
writes.set(id, (writes.get(id) ?? 0) + 1);
|
||||
return update(id, patch, options);
|
||||
};
|
||||
// The fleet pass, every 80 ms for a second; h3 is out of view.
|
||||
const inView = (p) => Math.abs(p.x - here.x) < 1;
|
||||
const seen = new Set();
|
||||
for (let step = 0; step <= 12; step++) {
|
||||
if (step) t.mock.timers.tick(80);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
seen.add(image('h1'));
|
||||
}
|
||||
// Through every frame, written only on the steps its frame changed.
|
||||
assert.equal(seen.size, 3);
|
||||
for (const frame of [0, 1, 2])
|
||||
assert.ok(seen.has(aircraftIcon('helicopter', FLEET_ICON_PX, frame)));
|
||||
assert.ok(
|
||||
writes.get('h1') >= 8 && writes.get('h1') <= 11,
|
||||
`${writes.get('h1')} writes`,
|
||||
);
|
||||
assert.equal(writes.get('h2') ?? 0, 0, 'grounded: frozen');
|
||||
assert.equal(writes.get('p1') ?? 0, 0, 'not a helicopter');
|
||||
assert.equal(writes.get('h3') ?? 0, 0, 'out of view');
|
||||
assert.equal(image('h3'), h3Before);
|
||||
// Landing freezes it on the still frame.
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
const landed = writes.get('h1');
|
||||
t.mock.timers.tick(400);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
assert.equal(writes.get('h1'), landed);
|
||||
assert.equal(
|
||||
image('h1'),
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
});
|
||||
|
||||
/** An icon layer over helicopters `ids`, all at `here`, for the rotor tests. */
|
||||
function rotorFixture(records, positions, tracking = {}) {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map(),
|
||||
_cockpitNearContacts: new Set(),
|
||||
records: { data: records, missingPolls: new Map() },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
rendering: {
|
||||
_iconKind: (_id, klass) => klass,
|
||||
_fleetBillboardColor: () => [1, 1, 1, 1],
|
||||
_fleetBillboardScale: () => 1,
|
||||
},
|
||||
tracking,
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
});
|
||||
for (const id of records.keys()) {
|
||||
state._icons.put(
|
||||
{
|
||||
id,
|
||||
pos: positions[id],
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: Infinity },
|
||||
);
|
||||
icons._applyIconPresentation(id);
|
||||
}
|
||||
return { state, icons };
|
||||
}
|
||||
|
||||
test('a tracked helicopter that lands shows the still frame at once', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const records = new Map([['h1', { klass: 'helicopter', onGround: false }]]);
|
||||
let synced = 0;
|
||||
const { state, icons } = rotorFixture(
|
||||
records,
|
||||
{ h1: fromDegrees(0, 30, 300) },
|
||||
{ _syncTrackedBillboardImage: () => synced++ },
|
||||
);
|
||||
state._trackedIcao = 'h1';
|
||||
assert.equal(icons._rotorsTurning(), true);
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 1, 'the tracked billboard is given its images again');
|
||||
assert.equal(icons._rotorsTurning(), false);
|
||||
assert.equal(
|
||||
icons._fleetLook('h1').image,
|
||||
aircraftIcon('helicopter', FLEET_ICON_PX, ROTOR_STILL_FRAME),
|
||||
);
|
||||
// Taxiing faster than 1 m/s, its rotor turns again, as the model's does.
|
||||
records.get('h1').velocity = 5;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(icons._rotorsTurning(), true);
|
||||
records.get('h1').velocity = 0;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 2);
|
||||
assert.equal(icons._rotorsTurning(), false);
|
||||
// An untracked one landing does not touch the tracked billboard.
|
||||
records.get('h1').onGround = false;
|
||||
icons._applyIconPresentation('h1');
|
||||
state._trackedIcao = null;
|
||||
records.get('h1').onGround = true;
|
||||
icons._applyIconPresentation('h1');
|
||||
assert.equal(synced, 2);
|
||||
});
|
||||
|
||||
test('a helicopter out of view is judged once per rotor frame, not every pass', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const records = new Map();
|
||||
const positions = {};
|
||||
for (let i = 0; i < 300; i++) {
|
||||
const id = `h${i}`;
|
||||
records.set(id, { klass: 'helicopter', onGround: false });
|
||||
positions[id] = fromDegrees(90, 30, 300);
|
||||
}
|
||||
const { state, icons } = rotorFixture(records, positions);
|
||||
let judged = 0;
|
||||
const inView = () => {
|
||||
judged++;
|
||||
return false;
|
||||
};
|
||||
const writes = [];
|
||||
const update = state._icons.update;
|
||||
state._icons.update = (id, ...rest) => {
|
||||
writes.push(id);
|
||||
return update(id, ...rest);
|
||||
};
|
||||
// Passes 10 ms apart for 2 s: 200 passes over 300 helicopters, all out of
|
||||
// view. Each is judged at most once per frame step (20 steps), and not on
|
||||
// a step back onto the frame it is drawn at.
|
||||
for (let pass = 0; pass < 200; pass++) {
|
||||
t.mock.timers.tick(10);
|
||||
icons._turnRotors(Date.now(), Date.now(), inView);
|
||||
}
|
||||
assert.ok(judged <= 300 * 21, `${judged} judgements`);
|
||||
assert.ok(judged >= 300 * 10, `${judged} judgements`);
|
||||
assert.equal(writes.length, 0, 'none in view: no image written');
|
||||
});
|
||||
|
||||
test('back at live, a placed contact eases from where it is drawn over a recovery, nose along the way', (t) => {
|
||||
t.mock.timers.enable({ apis: ['Date'], now: WORLD_MS });
|
||||
const drawnAt = fromDegrees(0, 30, 3_000);
|
||||
const SPEED = 200;
|
||||
// The placement has it 2 km east of where it is drawn, flying east.
|
||||
const placedAt = (wallMs) => {
|
||||
const east = 2_000 + (SPEED * (wallMs - WORLD_MS)) / 1000;
|
||||
return fromDegrees(east / (111_320 * Math.cos(Math.PI / 6)), 30, 3_000);
|
||||
};
|
||||
const plan = (handover, keep = {}) => {
|
||||
const state = {
|
||||
now: () => Date.now(),
|
||||
_icons: createContactIcons(),
|
||||
_positionHistory: new Map([['c', [{ epochMs: WORLD_MS }]]]),
|
||||
records: { data: new Map([['c', {}]]) },
|
||||
};
|
||||
const icons = createAircraftIcons({
|
||||
state,
|
||||
services: { focus: { focusPassIsNeeded: () => false } },
|
||||
parts: {
|
||||
motion: { _displayTimeAt: (ms) => ms, _fixEpochMs: (f) => f.epochMs },
|
||||
},
|
||||
layerId: 'flights',
|
||||
courseMaxDps: 3,
|
||||
cockpitContactSizePx: 8,
|
||||
placeAt: (_id, wallMs, _info, _history, out) => {
|
||||
Object.assign(out, placedAt(wallMs));
|
||||
return { courseDeg: 90, speedMps: SPEED };
|
||||
},
|
||||
});
|
||||
state._icons.put(
|
||||
{
|
||||
id: 'c',
|
||||
pos: drawnAt,
|
||||
motion: { kind: 'hold', courseDeg: 0 },
|
||||
course: 0,
|
||||
size: [20, 20],
|
||||
},
|
||||
{ expiresAt: -Infinity },
|
||||
);
|
||||
icons._planIcon('c', handover ? { handover: true } : undefined);
|
||||
keep.icons = icons;
|
||||
return state._icons;
|
||||
};
|
||||
const metres = (a, b) => Math.hypot(a.x - b.x, a.y - b.y, a.z - b.z);
|
||||
|
||||
const eased = plan(true);
|
||||
const end = eased.expires('c');
|
||||
assert.equal(end, WORLD_MS + recoveryMs(2_000, SPEED));
|
||||
assert.ok(end - WORLD_MS > 1_000, 'longer than a placed plan');
|
||||
assert.ok(metres(eased.position('c', WORLD_MS, {}), drawnAt) < 1);
|
||||
assert.ok(metres(eased.position('c', end, {}), placedAt(end)) < 1);
|
||||
// The nose points along the way from where it is drawn to where it goes.
|
||||
assert.ok(Math.abs(eased.course('c', WORLD_MS) - 90) < 1);
|
||||
|
||||
const plain = plan(false);
|
||||
assert.ok(
|
||||
metres(plain.position('c', WORLD_MS, {}), placedAt(WORLD_MS)) < 1,
|
||||
'without the handover it is drawn where it is placed',
|
||||
);
|
||||
|
||||
// The next answer comes 15 s in, the ease still running: it eases on from
|
||||
// where it is drawn then, not cut to where it is placed.
|
||||
const keep = {};
|
||||
const easing = plan(true, keep);
|
||||
const firstEnd = easing.expires('c');
|
||||
assert.ok(firstEnd - WORLD_MS > 15_000, 'an ease longer than a poll');
|
||||
t.mock.timers.tick(15_000);
|
||||
const at = Date.now();
|
||||
const drawnThen = easing.position('c', at, {});
|
||||
keep.icons._planIcon('c');
|
||||
assert.ok(metres(easing.position('c', at, {}), drawnThen) < 1);
|
||||
const reEnd = easing.expires('c');
|
||||
assert.ok(reEnd > at + 1_000, 'eases on');
|
||||
assert.ok(metres(easing.position('c', reEnd, {}), placedAt(reEnd)) < 1);
|
||||
// Once it has caught up, the next answer draws it where it is placed.
|
||||
t.mock.timers.tick(reEnd - at + 1);
|
||||
keep.icons._planIcon('c');
|
||||
assert.ok(
|
||||
metres(easing.position('c', Date.now(), {}), placedAt(Date.now())) < 1,
|
||||
);
|
||||
});
|
||||
+115
-28
@@ -8,9 +8,9 @@
|
||||
* width/height 20 (24 tracked) in flights.js / militaryFlights.js, so Cesium
|
||||
* DOWN-samples this larger, higher-precision source to the same on-screen
|
||||
* footprint — crisp anti-aliased edges instead of an upscaled 32px bitmap. The
|
||||
* on-screen size is unchanged and CLASS_SCALE_2D is untouched (no scale
|
||||
* compensation needed: the billboard's explicit width/height, not the SVG's,
|
||||
* sets the pixel size — the intrinsic SVG size only controls raster fidelity).
|
||||
* on-screen size is unchanged (the billboard's explicit width/height, not the
|
||||
* SVG's, sets the pixel size — the intrinsic SVG size only controls raster
|
||||
* fidelity).
|
||||
*
|
||||
* All glyphs are nose-up (nose toward -Y at rotation 0; the screen-projected
|
||||
* rotation pipeline in iconOrientation.js spins the whole glyph). Fill is white
|
||||
@@ -23,12 +23,19 @@
|
||||
* quadjet/glider use the "bold" chart-symbol redraw; light/fastjet keep the
|
||||
* original drawings. Raster fidelity doubled (192px source, same 96 coords).
|
||||
*
|
||||
* The helicopter is a top-down body under a four-blade rotor drawn in three
|
||||
* frames (`aircraftIcon('helicopter', px, frame)`, turned by
|
||||
* `rotorFrames.js`). Two kinds are not aircraft: `vehicle`, one sprite for
|
||||
* every airport vehicle, and `station`, a mast for ground stations, drawn
|
||||
* upright.
|
||||
*
|
||||
* Silhouette language follows skylight's type-aware glyphs (MIT,
|
||||
* https://github.com/cpaczek/skylight): slender fuselages, swept wings for
|
||||
* jets, long high-aspect wings for the glider, straight wings + prop discs for
|
||||
* props, a rotor disc + tail boom + tail-rotor for the helicopter, and a delta
|
||||
* for the fast jet. Each class has a DISTINCT planform so it reads at ~20px by
|
||||
* shape, not just by footprint size.
|
||||
* shape alone: every glyph is fitted to the same extent, so none is bigger
|
||||
* than another.
|
||||
*/
|
||||
|
||||
const VIEW = 96;
|
||||
@@ -130,23 +137,6 @@ const BODIES = {
|
||||
L -3,-25 C -3,-29 -2.4,-33 0,-35 Z" fill="white" ${STROKE_BOLD}/>
|
||||
<rect x="-10.5" y="32.5" width="21" height="5" rx="1.5" fill="white" ${STROKE_BOLD}/>`,
|
||||
|
||||
// ── Helicopter: a SOLID translucent main-rotor disc (survives downscale as an
|
||||
// obvious circle, unlike a thin ring) with a bold two-blade cross, a
|
||||
// teardrop cabin, a tail boom, and a tail rotor. Unmistakable "disc on top"
|
||||
// silhouette that never reads as a fixed-wing.
|
||||
helicopter: `
|
||||
<circle cx="0" cy="-6" r="31" fill="white" fill-opacity="0.22"/>
|
||||
<g transform="rotate(45 0 -6)">
|
||||
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9"/>
|
||||
<rect x="-30.5" y="-8.2" width="61" height="4.4" rx="2.2" fill="white" fill-opacity="0.9" transform="rotate(90 0 -6)"/>
|
||||
</g>
|
||||
<path d="M0,-22 C 8,-20 10.5,-13 10.5,-6 C 10.5,2 7.5,7 0,8.5
|
||||
C -7.5,7 -10.5,2 -10.5,-6 C -10.5,-13 -8,-20 0,-22 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-2.6,8 L 2.6,8 L 1.8,32 L -1.8,32 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-8,27 L 8,27 L 8,30.6 L -8,30.6 Z" fill="white"/>
|
||||
<circle cx="5.6" cy="35" r="6" fill="white" fill-opacity="0.6"/>
|
||||
<circle cx="5.6" cy="35" r="2.1" fill="white"/>`,
|
||||
|
||||
// ── Fast jet: sharp delta/cropped-delta with a pointed nose, LERX root
|
||||
// blend, and twin tail fins. Aggressive, all-wing.
|
||||
fastjet: `
|
||||
@@ -236,6 +226,87 @@ const BODIES = {
|
||||
L -1.6,30 L -13,36 L -13,32 L -2.1,24
|
||||
L -2.3,0 L -43,-2.5 L -43,-7 L -2.4,-12
|
||||
L -4.4,-30 C -4.6,-35 -3.6,-40 0,-40 Z" fill="white" ${STROKE}/>`,
|
||||
|
||||
// ── Airport vehicle (type ZVEH, emitter C1/C2): one service van seen from
|
||||
// above, front up, for every kind (fire truck, tug, car, de-icer). A
|
||||
// boxy body, a dark windscreen band and a roof light bar; the layer
|
||||
// tints it amber so it reads apart from aircraft.
|
||||
vehicle: `
|
||||
<path d="M-12,-39 L 12,-39 L 15,-36 L 15,38 L 13,40 L -13,40 L -15,38
|
||||
L -15,-36 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-18.5,-25 h4 v3 h-4 Z M14.5,-25 h4 v3 h-4 Z" fill="white" ${STROKE}/>
|
||||
<path d="M-13,-32 L 13,-32 L 12,-21 L -12,-21 Z" fill="rgba(0,0,0,0.62)"/>
|
||||
<rect x="-10" y="-13" width="20" height="5" rx="1.5" fill="rgba(0,0,0,0.45)"/>`,
|
||||
|
||||
// ── Ground station or obstacle (type GRND, emitter C3–C5): a radio mast
|
||||
// with two pairs of signal arcs, drawn upright on screen, never turned.
|
||||
station: `
|
||||
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
|
||||
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
|
||||
fill="none" stroke="rgba(0,0,0,0.32)" stroke-width="5" stroke-linecap="round"/>
|
||||
<path d="M7.1,-38.4 A 11 11 0 0 1 7.1,-21.6 M-7.1,-38.4 A 11 11 0 0 0 -7.1,-21.6
|
||||
M12.2,-44.6 A 19 19 0 0 1 12.2,-15.4 M-12.2,-44.6 A 19 19 0 0 0 -12.2,-15.4"
|
||||
fill="none" stroke="white" stroke-width="3.4" stroke-linecap="round"/>
|
||||
<circle cx="0" cy="-30" r="4.5" fill="white" ${STROKE}/>
|
||||
<path d="M-2.5,-25 L 2.5,-25 L 7,34 L 13,34 L 13,38 L -13,38 L -13,34
|
||||
L -7,34 Z" fill="white" ${STROKE}/>`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The helicopter, seen from above: a cabin, tail boom and tail plane under a
|
||||
* four-blade main rotor. The rotor turns in {@link ROTOR_FRAMES} frames 30°
|
||||
* apart; four blades repeat every 90°, so the third frame steps back onto
|
||||
* the first and the loop is seamless. The middle frame (blades as an X) is
|
||||
* the still one.
|
||||
*/
|
||||
const HELI_ROTOR_CENTRE_Y = -11.2;
|
||||
const HELI_DISC = `<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="32.8" fill="white" fill-opacity="0.22"/>`;
|
||||
const HELI_BODY = `
|
||||
<path d="M0,-33.4 L -2.3,-32.1 L -4.2,-28 L -4.3,-30.6 L -6.2,-30.6
|
||||
L -6.2,0.2 L -4.3,0.2 L -4.2,-3.1 L -1.9,7.9 L -1.7,18.9
|
||||
L -7.4,19.2 L -7.8,24 L -2.9,24.4 L -3.2,35.6 L -1.2,36
|
||||
L 0,34.3 L 1.2,36 L 3.2,35.6 L 2.9,24.4 L 7.8,24 L 7.4,19.2
|
||||
L 1.7,18.9 L 1.9,7.9 L 4.2,-3.1 L 4.3,0.2 L 6.2,0.2 L 6.2,-30.6
|
||||
L 4.3,-30.6 L 4.2,-28 L 2.3,-32.1 Z" fill="white" ${STROKE}/>
|
||||
<circle cx="0" cy="${HELI_ROTOR_CENTRE_Y}" r="3.2" fill="white" ${STROKE}/>`;
|
||||
/** Main-rotor blade angle of each frame, degrees clockwise. */
|
||||
const ROTOR_ANGLES_DEG = [15, 45, 75];
|
||||
/** How many rotor frames the helicopter turns through. */
|
||||
export const ROTOR_FRAMES = ROTOR_ANGLES_DEG.length;
|
||||
/** The frame a helicopter holds when its rotor does not turn. */
|
||||
export const ROTOR_STILL_FRAME = 1;
|
||||
|
||||
/** One rotor frame: the disc, two crossed blades at `angle`, the body over them. */
|
||||
function helicopterBody(frame) {
|
||||
const angle = ROTOR_ANGLES_DEG[frame] ?? ROTOR_ANGLES_DEG[ROTOR_STILL_FRAME];
|
||||
const blade = (deg) =>
|
||||
`<rect x="-32.2" y="${HELI_ROTOR_CENTRE_Y - 2.2}" width="64.4" height="4.4" rx="2.2" fill="white" fill-opacity="0.92" stroke="rgba(0,0,0,0.25)" stroke-width="0.8" transform="rotate(${deg} 0 ${HELI_ROTOR_CENTRE_Y})"/>`;
|
||||
return `${HELI_DISC}${blade(angle)}${blade(angle + 90)}${HELI_BODY}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Every sprite draws at one size. The bodies were drawn at different spans
|
||||
* (a light aircraft's half-extent is 32.8 units, a quadjet's 47), so each is
|
||||
* scaled until its farthest painted edge, stroke included, sits
|
||||
* {@link GLYPH_HALF_EXTENT} units from the centre. Values are each body's
|
||||
* measured half-extent; aircraftIcons.test.mjs re-measures the rasters.
|
||||
*/
|
||||
const GLYPH_HALF_EXTENT = 44;
|
||||
const BODY_HALF_EXTENT = {
|
||||
airliner: 42.7,
|
||||
widebody: 45.7,
|
||||
quadjet: 47.0,
|
||||
turboprop: 40.7,
|
||||
light: 32.8,
|
||||
glider: 46.0,
|
||||
fastjet: 44.7,
|
||||
bizjet: 42.7,
|
||||
uav: 43.7,
|
||||
helicopter: 44.0,
|
||||
vehicle: 40.7,
|
||||
station: 47.1,
|
||||
tr3b: 40.8,
|
||||
tr3bHot: 42.3,
|
||||
};
|
||||
|
||||
const _iconCache = new Map();
|
||||
@@ -259,16 +330,32 @@ export const FLEET_ICON_PX = FLEET_RASTER_PX;
|
||||
* it stays crisp at its biggest on-screen sizes. */
|
||||
const TRACKED_RASTER_PX = 192;
|
||||
|
||||
/** Data URI for a class silhouette (lazily built, cached per kind+size).
|
||||
* Default size serves the fleet; pass `aircraftIcon(kind, TRACKED_ICON_PX)`
|
||||
* (re-exported below) for the tracked billboard. */
|
||||
/** Raster size of the tracked glyph and every glyph's near image. */
|
||||
export const TRACKED_ICON_PX = TRACKED_RASTER_PX;
|
||||
export function aircraftIcon(kind, px = FLEET_RASTER_PX) {
|
||||
const k = BODIES[kind] ? kind : 'airliner';
|
||||
const key = `${k}@${px}`;
|
||||
/**
|
||||
* Data URI for a class silhouette (lazily built, cached per kind, size and
|
||||
* frame). The default size serves the fleet; pass
|
||||
* `aircraftIcon(kind, TRACKED_ICON_PX)` for the near image.
|
||||
* @param {string} kind A `classifyAircraft()` class, or a TR-3B kind.
|
||||
* @param {number} [px] Raster size.
|
||||
* @param {number} [frame] A helicopter's rotor frame, 0 to `ROTOR_FRAMES - 1`
|
||||
* (the still frame by default); other kinds have one image.
|
||||
* @returns {string}
|
||||
*/
|
||||
export function aircraftIcon(kind, px = FLEET_RASTER_PX, frame) {
|
||||
const heli = kind === 'helicopter';
|
||||
const k = heli || BODIES[kind] ? kind : 'airliner';
|
||||
const f = heli
|
||||
? Number.isInteger(frame) && frame >= 0 && frame < ROTOR_FRAMES
|
||||
? frame
|
||||
: ROTOR_STILL_FRAME
|
||||
: 0;
|
||||
const key = `${k}@${px}#${f}`;
|
||||
let uri = _iconCache.get(key);
|
||||
if (!uri) {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${BODIES[k]}</g></svg>`;
|
||||
const body = heli ? helicopterBody(f) : BODIES[k];
|
||||
const fit = +(GLYPH_HALF_EXTENT / BODY_HALF_EXTENT[k]).toFixed(4);
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C}) scale(${fit})">${body}</g></svg>`;
|
||||
uri = 'data:image/svg+xml;base64,' + _b64(svg);
|
||||
_iconCache.set(key, uri);
|
||||
}
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
// src/data/aircraftIcons.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import sharp from 'sharp';
|
||||
|
||||
import { aircraftIcon, ROTOR_FRAMES } from './aircraftIcons.js';
|
||||
|
||||
const KINDS = [
|
||||
'airliner',
|
||||
'widebody',
|
||||
'quadjet',
|
||||
'turboprop',
|
||||
'light',
|
||||
'glider',
|
||||
'fastjet',
|
||||
'bizjet',
|
||||
'uav',
|
||||
'helicopter',
|
||||
'vehicle',
|
||||
'station',
|
||||
'tr3b',
|
||||
'tr3bHot',
|
||||
];
|
||||
const PX = 480;
|
||||
|
||||
/** Farthest painted pixel from the centre, in the 96-unit glyph space. */
|
||||
async function halfExtent(uri) {
|
||||
const svg = Buffer.from(uri.split(',')[1], 'base64');
|
||||
const { data, info } = await sharp(svg)
|
||||
.ensureAlpha()
|
||||
.raw()
|
||||
.toBuffer({ resolveWithObject: true });
|
||||
let half = 0;
|
||||
const c = info.width / 2;
|
||||
for (let y = 0; y < info.height; y++) {
|
||||
for (let x = 0; x < info.width; x++) {
|
||||
if (data[(y * info.width + x) * 4 + 3] <= 8) continue;
|
||||
half = Math.max(half, c - x, x + 1 - c, c - y, y + 1 - c);
|
||||
}
|
||||
}
|
||||
return (half * 96) / info.width;
|
||||
}
|
||||
|
||||
test('every sprite fills the same extent, whatever its class', async () => {
|
||||
const extents = {};
|
||||
for (const kind of KINDS) {
|
||||
extents[kind] = await halfExtent(aircraftIcon(kind, PX));
|
||||
}
|
||||
for (let frame = 0; frame < ROTOR_FRAMES; frame++) {
|
||||
extents[`helicopter#${frame}`] = await halfExtent(
|
||||
aircraftIcon('helicopter', PX, frame),
|
||||
);
|
||||
}
|
||||
for (const [kind, half] of Object.entries(extents)) {
|
||||
assert.ok(Math.abs(half - 44) <= 0.6, `${kind}: ${half.toFixed(2)}`);
|
||||
}
|
||||
});
|
||||
+190
-53
@@ -14,7 +14,8 @@ import {
|
||||
showModel,
|
||||
} from './modelRecord.js';
|
||||
import { modelDrawnScale } from './modelVisualAnchor.js';
|
||||
import { fleetModelSet } from './fleetModels.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { aircraftLayerPartState } from './modelPartDrivers.js';
|
||||
import { findCamera, findDraw, rendererOf } from '../render/rendererOf.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import {
|
||||
@@ -225,10 +226,10 @@ export function createAircraftModels({
|
||||
return sets ? [sets.fleet.id, sets.tracked.id] : [];
|
||||
}
|
||||
|
||||
/** The FLEET's 3D-model regime: models3d enabled AND the camera zoomed in past the altitude
|
||||
* ceiling. Since 2026-08-22 the toggle DEFAULTS ON in `proximity`, which is itself the
|
||||
* budget: models only appear below MODEL_ALT_CEIL_M and only for the nearest MODEL_MAX in
|
||||
* view. The toggle still OWNS the fleet — an operator who wants every in-view plane arms
|
||||
/** The FLEET's 3D-model regime: models3d enabled AND the camera below the altitude ceiling,
|
||||
* above which no contact can be within the model radius. Since 2026-08-22 the toggle DEFAULTS
|
||||
* ON in `proximity`, which is itself the budget: models only appear within MODEL_ADD_M of the
|
||||
* camera and only for the nearest MODEL_MAX. The toggle still OWNS the fleet — an operator who wants every in-view plane arms
|
||||
* `all`, and one who wants none turns 3D off — this predicate is unchanged. The TRACKED
|
||||
* contact routes through here too (`_trackedModelRegimeActive`), with its place in the
|
||||
* fleet's cap, so selecting a contact never changes its form. */
|
||||
@@ -254,20 +255,17 @@ export function createAircraftModels({
|
||||
: mapCap;
|
||||
}
|
||||
|
||||
/** Active ADD radius (m) — new planes inside this range get a model. Mode-aware: 'all' reaches far. */
|
||||
/** ADD radius (m) — new planes inside this range get a model. Both modes
|
||||
* share it; they differ by their caps. */
|
||||
|
||||
function _modelAddDistM() {
|
||||
return state._models3dMode === 'all'
|
||||
? policy.MODEL_ALL_ADD_M
|
||||
: policy.MODEL_PROX_ADD_M;
|
||||
return policy.MODEL_ADD_M;
|
||||
}
|
||||
|
||||
/** Active KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */
|
||||
/** KEEP radius (m) — a modeled plane keeps its model out to here (hysteresis vs ADD). */
|
||||
|
||||
function _modelKeepDistM() {
|
||||
return state._models3dMode === 'all'
|
||||
? policy.MODEL_ALL_KEEP_M
|
||||
: policy.MODEL_PROX_KEEP_M;
|
||||
return policy.MODEL_KEEP_M;
|
||||
}
|
||||
|
||||
/** What a grounded model's ground sample sees through: the vertical sample
|
||||
@@ -341,6 +339,54 @@ export function createAircraftModels({
|
||||
record.tint = [base[0], base[1], base[2], alpha];
|
||||
}
|
||||
|
||||
/** A finite number of the first of `values` that is one, else null. */
|
||||
const _finite = (...values) =>
|
||||
values.find((v) => typeof v === 'number' && Number.isFinite(v)) ?? null;
|
||||
|
||||
/**
|
||||
* How high an aircraft flies above the ground under it: its render
|
||||
* altitude over the cached ground floor there; null where that floor is
|
||||
* not known (the gear then follows the approach rule instead).
|
||||
*/
|
||||
function _heightAboveGround(meta) {
|
||||
const altitude = _finite(meta.renderAltitudeM);
|
||||
const floor =
|
||||
Number.isFinite(meta.rawLat) && Number.isFinite(meta.rawLon)
|
||||
? services.groundFloor?.cachedGroundFloor?.(meta.rawLat, meta.rawLon)
|
||||
: null;
|
||||
return altitude !== null && Number.isFinite(floor)
|
||||
? altitude - floor
|
||||
: null;
|
||||
}
|
||||
|
||||
/**
|
||||
* The moving parts a contact's model is posed with, from its record
|
||||
* (`aircraftLayerPartState`): gear, doors and flaps by its height and climb,
|
||||
* fans, propellers and rotors while it flies or taxis. An airport vehicle
|
||||
* is a road vehicle (`groundVehiclePartState`): its wheels roll with its
|
||||
* speed. Undefined for a model without parts.
|
||||
*/
|
||||
function _partsOf(meta, spec) {
|
||||
if (!meta) return undefined;
|
||||
const table = fleetPartTable(fleetModelSet(), spec?.model);
|
||||
if (!table) return undefined;
|
||||
return aircraftLayerPartState(table, {
|
||||
klass: meta.klass,
|
||||
onGround: meta.onGround === true,
|
||||
heightAboveGroundM: _heightAboveGround(meta),
|
||||
altitudeM: _finite(meta.altitude, meta.altitudeM),
|
||||
verticalRateMps: _finite(meta.verticalRate, meta.verticalRateMps),
|
||||
speedMps: _finite(meta.velocity, meta.speedMps),
|
||||
});
|
||||
}
|
||||
|
||||
/** Pose a record's parts as its contact's record says, and key them for `_send`. */
|
||||
function _poseParts(record, meta, spec) {
|
||||
const pose = _partsOf(meta, spec);
|
||||
record.parts = pose;
|
||||
record.partsKey = pose ? JSON.stringify(pose) : '';
|
||||
}
|
||||
|
||||
/** The record's item, as its set draws it. */
|
||||
function _itemOf(id, record) {
|
||||
return {
|
||||
@@ -354,10 +400,11 @@ export function createAircraftModels({
|
||||
minPixelSize: record.minPixelSize,
|
||||
shading: _shadingOf(),
|
||||
tint: record.tint ?? WHITE,
|
||||
// The mesh's own colours, tinted while tracked or in an emergency;
|
||||
// The mesh's own colours, tinted red in an emergency;
|
||||
// the IR boost draws it flat white.
|
||||
colorBlend: aircraftModelBlend(state._irBoost === true),
|
||||
colorBlend: aircraftModelBlend(state._irBoost === true, record.tint),
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(record.parts ? { parts: record.parts } : {}),
|
||||
show: record.show,
|
||||
};
|
||||
}
|
||||
@@ -367,7 +414,7 @@ export function createAircraftModels({
|
||||
if (!set) return;
|
||||
const p = record.position;
|
||||
const t = record.tint ?? WHITE;
|
||||
const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}`;
|
||||
const key = `${record.url}|${p.x},${p.y},${p.z}|${record.heading}|${record.scale}|${record.minPixelSize}|${t[0]},${t[1]},${t[2]},${t[3]}|${state._irBoost === true}|${record.show}|${record.partsKey ?? ''}`;
|
||||
if (key === record.sent) return;
|
||||
record.sent = key;
|
||||
const item = _itemOf(id, record);
|
||||
@@ -426,6 +473,7 @@ export function createAircraftModels({
|
||||
// Placed BEFORE the readiness test on purpose: a model can turn ready
|
||||
// between ticks, and its first drawn frame must be at this placement.
|
||||
placeModel(record, displayPos, _modelHeading(course, meta));
|
||||
_poseParts(record, meta, spec);
|
||||
if (!record.ready) {
|
||||
showModel(record, false); // not loaded yet → keep the 2D icon, no half-model flash
|
||||
_send(set, icao24, record, spec, out);
|
||||
@@ -565,12 +613,11 @@ export function createAircraftModels({
|
||||
state._lastFleetTickMs = 0;
|
||||
}
|
||||
|
||||
/** Admit a fleet model for an aircraft; the icon shows until it is ready. */
|
||||
/** Admit a fleet model for an aircraft; the icon shows until it is ready.
|
||||
* The selected aircraft's is admitted too, and kept loaded but hidden
|
||||
* while its tracked model draws it (`_keepTrackedFleetModel`). */
|
||||
|
||||
function _ensureModel(icao24) {
|
||||
// Never model the TRACKED aircraft — it owns a separate entity billboard, and the fleet
|
||||
// tick skips it, so a model here would be orphaned + double-rendered.
|
||||
if (icao24 === state._trackedIcao) return;
|
||||
onModelEligible(icao24);
|
||||
if (state._models.has(icao24)) return;
|
||||
// Without model sets (the renderer draws none) the icon stays.
|
||||
@@ -585,7 +632,6 @@ export function createAircraftModels({
|
||||
specKey: _specKeyFor(meta), // type-change sync compares against this
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
minPixelSize: policy.MODEL_MIN_PX,
|
||||
});
|
||||
record.url = resolveAsset(spec.url);
|
||||
record.gltf = _gltfOf(spec);
|
||||
@@ -676,24 +722,115 @@ export function createAircraftModels({
|
||||
);
|
||||
}
|
||||
|
||||
/** A fleet model still drawing the tracked contact (it was a model when
|
||||
* it was selected) lets go once the tracked model draws, or once the
|
||||
* contact is no longer drawn as a model at all. */
|
||||
/** The tracked contact's fleet model lets go once the contact is no
|
||||
* longer drawn as a model at all (out of range, 3D off, cockpit). */
|
||||
function _releaseTrackedFleetModel() {
|
||||
if (state._trackedIcao && state._models.has(state._trackedIcao))
|
||||
_releaseModel(state._trackedIcao);
|
||||
}
|
||||
|
||||
/** The tracked contact's fleet model (it was a model when it was
|
||||
* selected, or was admitted since) stops drawing once the tracked model
|
||||
* draws, or while the tracked icon carries the contact, but stays loaded:
|
||||
* deselecting hands the contact straight back to it
|
||||
* (`_handBackDeselected`), with no load and no icon in between. */
|
||||
function _hideTrackedFleetModel() {
|
||||
const icao24 = state._trackedIcao;
|
||||
const record = icao24 ? state._models.get(icao24) : null;
|
||||
if (!record?.show) return;
|
||||
showModel(record, false);
|
||||
_send(state._modelSets?.fleet, icao24, record, _modelSpec(_metaOf(icao24)));
|
||||
}
|
||||
|
||||
/** Keep the tracked contact's fleet model loaded and placed where its icon
|
||||
* is, one fleet tick at a time, so it is ready to take the contact back
|
||||
* the moment it is deselected. It never shows here: it draws the contact
|
||||
* only while the tracked model loads, as it did before the selection. */
|
||||
function _keepTrackedFleetModel(icao24, position, course, out) {
|
||||
_ensureModel(icao24);
|
||||
const record = state._models.get(icao24);
|
||||
if (!record) return;
|
||||
const meta = _metaOf(icao24);
|
||||
const set = state._modelSets?.fleet ?? null;
|
||||
_retryFailedFleetModel(set, icao24, record);
|
||||
const displayPos = _modelDisplayPosition(icao24, position);
|
||||
if (displayPos) placeModel(record, displayPos, _modelHeading(course, meta));
|
||||
else showModel(record, false); // nowhere safe to draw it
|
||||
_send(set, icao24, record, _modelSpec(meta), out);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hand a contact just deselected back to the fleet in the same frame: to
|
||||
* its fleet model when one is loaded (kept while it was selected), placed
|
||||
* where its icon is and shown, else to its icon. Runs once the contact no
|
||||
* longer reads as tracked.
|
||||
* @param {string} icao24
|
||||
*/
|
||||
function _handBackDeselected(icao24) {
|
||||
const icons = state._icons;
|
||||
const record = state._models.get(icao24);
|
||||
if (!icons?.has(icao24)) {
|
||||
if (record) _releaseModel(icao24);
|
||||
return;
|
||||
}
|
||||
if (!record) {
|
||||
icons.setShown(icao24, true);
|
||||
return;
|
||||
}
|
||||
const pose = _pose();
|
||||
if (!pose || !_modelRegimeActive(pose) || isTr3b(icao24)) {
|
||||
_releaseModel(icao24); // the icon takes it back
|
||||
return;
|
||||
}
|
||||
const t = parts.icons._displayMs();
|
||||
const position = icons.position(icao24, t);
|
||||
_driveFleetModelHandoff(
|
||||
icao24,
|
||||
record,
|
||||
position,
|
||||
icons.course(icao24, t),
|
||||
() =>
|
||||
_treatFleetModel(
|
||||
icao24,
|
||||
record,
|
||||
distance(pose.position, position),
|
||||
pose,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
/** A fleet model's tint and alpha this tick: the contact's colour, faded
|
||||
* as its icon is (focus, recession), or the IR boost's full-strength
|
||||
* white. */
|
||||
function _treatFleetModel(icao24, record, cameraDistanceM, pose) {
|
||||
const icons = state._icons;
|
||||
_treat(record, {
|
||||
// IR boost must survive the per-tick treatment write — otherwise
|
||||
// any alpha change would repaint the ordinary tint over the hot
|
||||
// white. Boosted models also skip the recession fade: hot targets
|
||||
// stay full-strength at any range (icons keep their normal
|
||||
// fade — full-opacity glyph walls read as overwhelming).
|
||||
base: state._irBoost ? WHITE : rgba(_modelColor(icao24)),
|
||||
alpha: state._irBoost
|
||||
? 1
|
||||
: aircraftTreatmentAlpha({
|
||||
baseAlpha: icons.alpha(icao24),
|
||||
focusFactor: icons.focus(icao24),
|
||||
cameraDistanceM,
|
||||
cameraHeightM: pose.height,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
/** Per-frame driver for the standalone tracked model. Runs every preUpdate (not the 80 ms fleet
|
||||
* cadence) so the centered plane moves smoothly. The tracked entity stays a pure billboard, so the
|
||||
* follow-camera's bounding sphere is ALWAYS ready — toggling 3D, or tracking while already zoomed
|
||||
* in, can never stall or freeze the centering (the old model-graphic-on-entity failure mode).
|
||||
*
|
||||
* The model draws exactly as the fleet would draw this contact: the same
|
||||
* asset at the same scale and `minPixelSize` (`MODEL_MIN_PX`), only its
|
||||
* tint the tracked colour; whether it draws at all is the fleet's rule too
|
||||
* (`_trackedModelRegimeActive`). Selecting a contact changes its colour,
|
||||
* never its size or form. */
|
||||
* asset at the same scale (its true size) in the same colours; whether it
|
||||
* draws at all is the fleet's rule too (`_trackedModelRegimeActive`).
|
||||
* Selecting a contact changes neither its colour nor its size or form. */
|
||||
|
||||
function _updateTrackedModel() {
|
||||
// A failed load is let go (the icon carries the contact); the budget
|
||||
@@ -717,7 +854,7 @@ export function createAircraftModels({
|
||||
parts.icons._iconPosition(state._trackedIcao);
|
||||
if (!pos) {
|
||||
_hideTrackedModel();
|
||||
_releaseTrackedFleetModel();
|
||||
_hideTrackedFleetModel();
|
||||
return;
|
||||
}
|
||||
const icao24 = state._trackedIcao;
|
||||
@@ -729,14 +866,13 @@ export function createAircraftModels({
|
||||
// The icon carries it: after the load budget is spent, or until the
|
||||
// fleet model set has loaded.
|
||||
if (!_trackedModelLoadAllowed() || !spec.url) {
|
||||
_releaseTrackedFleetModel();
|
||||
_hideTrackedFleetModel();
|
||||
return;
|
||||
}
|
||||
const record = createModelRecord({
|
||||
specKey: _specKeyFor(meta), // type-change sync compares against this
|
||||
bellyM: spec.bellyM,
|
||||
scale: spec.scale,
|
||||
minPixelSize: policy.MODEL_MIN_PX,
|
||||
});
|
||||
record.id = icao24;
|
||||
record.url = resolveAsset(spec.url);
|
||||
@@ -758,7 +894,7 @@ export function createAircraftModels({
|
||||
const displayPos = _modelDisplayPosition(icao24, pos);
|
||||
if (!displayPos) {
|
||||
_hideTrackedModel(); // no ground evidence → the icon carries it
|
||||
_releaseTrackedFleetModel();
|
||||
_hideTrackedFleetModel();
|
||||
return;
|
||||
}
|
||||
placeModel(
|
||||
@@ -766,9 +902,10 @@ export function createAircraftModels({
|
||||
displayPos,
|
||||
_modelHeading(parts.motion._trackedDisplayCourse(), meta),
|
||||
);
|
||||
_poseParts(record, meta, spec);
|
||||
showModel(record, record.ready);
|
||||
_send(state._modelSets.tracked, icao24, record, spec);
|
||||
if (record.ready) _releaseTrackedFleetModel();
|
||||
if (record.ready) _hideTrackedFleetModel();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -841,6 +978,13 @@ export function createAircraftModels({
|
||||
afterReplan(renderTime, t, nowMs, pose?.position ?? null);
|
||||
const focusTarget = getFocusTarget();
|
||||
parts.icons._focusIcons(t, nowMs, focusTarget);
|
||||
// Airborne helicopters in view step their rotor frame (none: no work).
|
||||
if (parts.icons._rotorsTurning?.())
|
||||
parts.icons._turnRotors(
|
||||
Date.now(),
|
||||
t,
|
||||
pose ? (position) => inView(pose, position) : null,
|
||||
);
|
||||
|
||||
// 3D model regime: only when enabled AND the camera is zoomed in past the altitude ceiling.
|
||||
// Drop all models the moment we leave it (toggled off / zoomed out) so icons resume.
|
||||
@@ -920,8 +1064,6 @@ export function createAircraftModels({
|
||||
const items = pendingItems;
|
||||
for (const icao24 of modelEligible) {
|
||||
if (isTr3b(icao24)) continue;
|
||||
// The tracked contact's model is `_updateTrackedModel`'s.
|
||||
if (icao24 === state._trackedIcao) continue;
|
||||
if (!icons.has(icao24)) continue;
|
||||
const position = icons.position(icao24, t);
|
||||
if (
|
||||
@@ -944,6 +1086,17 @@ export function createAircraftModels({
|
||||
}
|
||||
continue;
|
||||
}
|
||||
// The tracked contact draws as `_updateTrackedModel` says; its fleet
|
||||
// model is only kept ready for when it is deselected.
|
||||
if (icao24 === state._trackedIcao) {
|
||||
_keepTrackedFleetModel(
|
||||
icao24,
|
||||
position,
|
||||
icons.course(icao24, t),
|
||||
items,
|
||||
);
|
||||
continue;
|
||||
}
|
||||
_ensureModel(icao24);
|
||||
const record = state._models.get(icao24);
|
||||
const cameraDistanceM = distance(camPos, position);
|
||||
@@ -952,24 +1105,7 @@ export function createAircraftModels({
|
||||
record,
|
||||
position,
|
||||
icons.course(icao24, t),
|
||||
() => {
|
||||
_treat(record, {
|
||||
// IR boost must survive the per-tick treatment write — otherwise
|
||||
// any alpha change would repaint the ordinary tint over the hot
|
||||
// white. Boosted models also skip the recession fade: hot targets
|
||||
// stay full-strength at any range (icons keep their normal
|
||||
// fade — full-opacity glyph walls read as overwhelming).
|
||||
base: state._irBoost ? WHITE : rgba(_modelColor(icao24)),
|
||||
alpha: state._irBoost
|
||||
? 1
|
||||
: aircraftTreatmentAlpha({
|
||||
baseAlpha: icons.alpha(icao24),
|
||||
focusFactor: icons.focus(icao24),
|
||||
cameraDistanceM,
|
||||
cameraHeightM: pose.height,
|
||||
}),
|
||||
});
|
||||
},
|
||||
() => _treatFleetModel(icao24, record, cameraDistanceM, pose),
|
||||
items,
|
||||
);
|
||||
}
|
||||
@@ -997,6 +1133,7 @@ export function createAircraftModels({
|
||||
_releaseModels,
|
||||
_showReleasedIcon,
|
||||
_releaseTrackedModel,
|
||||
_handBackDeselected,
|
||||
_updateTrackedModel,
|
||||
_fleetTick,
|
||||
};
|
||||
|
||||
@@ -4,25 +4,18 @@ import { createAircraftModels } from './aircraftModelLayer.js';
|
||||
import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { bindRenderer } from '../render/rendererOf.js';
|
||||
import { fromDegrees } from '../geo/ellipsoid.js';
|
||||
import * as flightsPolicy from '../layers/flights/policy.js';
|
||||
|
||||
// The flights layer's own model policy: its radii, ceiling and caps.
|
||||
const POLICY = {
|
||||
MODEL_ALT_CEIL_M: 800_000,
|
||||
...flightsPolicy,
|
||||
MODEL_MAX: 40,
|
||||
MODEL_MAX_ALL: 350,
|
||||
COCKPIT_MODEL_MAX: 60,
|
||||
MODEL_PROX_ADD_M: 150_000,
|
||||
MODEL_PROX_KEEP_M: 185_000,
|
||||
MODEL_ALL_ADD_M: 400_000,
|
||||
MODEL_ALL_KEEP_M: 450_000,
|
||||
MODEL_MIN_PX: 24,
|
||||
TRACKED_MODEL_MIN_PX: 48,
|
||||
TRACKED_MODEL_MAX_PX: 600,
|
||||
MODEL_HEADING_OFFSET_DEG: 0,
|
||||
FLEET_DR_INTERVAL_MS: 80,
|
||||
TRACKED_MODEL_MAX_LOAD_FAILS: 3,
|
||||
TRACKED_MODEL_RETRY_BACKOFF_MS: 1500,
|
||||
};
|
||||
|
||||
/** The eye's height (m): 1 km above the contacts. */
|
||||
const EYE_M = 11_000;
|
||||
|
||||
const SPEC = {
|
||||
url: 'plane.glb',
|
||||
scale: 1,
|
||||
@@ -34,9 +27,9 @@ const SPEC = {
|
||||
/**
|
||||
* A fleet of airborne contacts at `positions` (icao → ECEF), drawn by a
|
||||
* models layer over a fake draw port whose fleet set can be told to fail a
|
||||
* write. The eye sits above them at 30 km.
|
||||
* write. The eye sits at `eyeM`, by default 1 km above them (`EYE_M`).
|
||||
*/
|
||||
function fleetFixture(positions) {
|
||||
function fleetFixture(positions, { eyeM = EYE_M } = {}) {
|
||||
const base = fakeDrawPort();
|
||||
const removes = [];
|
||||
let failNextUpsert = false;
|
||||
@@ -67,7 +60,7 @@ function fleetFixture(positions) {
|
||||
};
|
||||
},
|
||||
};
|
||||
const eye = fromDegrees(-97.71, 30.21, 30_000);
|
||||
const eye = fromDegrees(-97.71, 30.21, eyeM);
|
||||
const viewer = {};
|
||||
bindRenderer(viewer, {
|
||||
draw,
|
||||
@@ -79,7 +72,7 @@ function fleetFixture(positions) {
|
||||
right: { x: 1, y: 0, z: 0 },
|
||||
fovy: Math.PI / 3,
|
||||
aspectRatio: 1,
|
||||
height: 30_000,
|
||||
height: eyeM,
|
||||
}),
|
||||
},
|
||||
});
|
||||
@@ -185,7 +178,10 @@ function fleetFixture(positions) {
|
||||
};
|
||||
}
|
||||
|
||||
const near = (k) => fromDegrees(-97.71 + k * 0.01, 30.21, 10_000);
|
||||
// About 0.5 km apart, within 2 km of the eye.
|
||||
const near = (k) => fromDegrees(-97.71 + k * 0.005, 30.21, 10_000);
|
||||
/** A contact at the eye's height, `m` metres north of it. */
|
||||
const north = (m) => fromDegrees(-97.71, 30.21 + m / 110_850, EYE_M);
|
||||
const far = (k) => fromDegrees(-90 + k * 0.01, 30.21, 10_000);
|
||||
|
||||
test('the fleet tick hands contacts to ready models and back without a gap', () => {
|
||||
@@ -326,7 +322,7 @@ test('fleet model alpha is worked out once a fleet tick from the camera then, as
|
||||
const position = near(1);
|
||||
const f = fleetFixture(new Map([['a1', position]]));
|
||||
assert.equal(f.fleet().spec.recede ?? null, null, 'the set does not recede');
|
||||
const eye = fromDegrees(-97.71, 30.21, 30_000);
|
||||
const eye = fromDegrees(-97.71, 30.21, EYE_M);
|
||||
const expected = (focusFactor) =>
|
||||
aircraftTreatmentAlpha({
|
||||
baseAlpha: 0.8,
|
||||
@@ -336,7 +332,7 @@ test('fleet model alpha is worked out once a fleet tick from the camera then, as
|
||||
eye.y - position.y,
|
||||
eye.z - position.z,
|
||||
),
|
||||
cameraHeightM: 30_000,
|
||||
cameraHeightM: EYE_M,
|
||||
});
|
||||
try {
|
||||
// Recede from the eye on, so the haze is not 1 here.
|
||||
@@ -389,3 +385,94 @@ test('a contact not there yet at the time drawn has its fleet model hidden, as o
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').show, true, 'drawn again');
|
||||
});
|
||||
|
||||
test('aircraft draw as models only within 3 km of the camera, in either mode', () => {
|
||||
for (const mode of ['proximity', 'all']) {
|
||||
const positions = new Map([
|
||||
['inside', north(2_900)],
|
||||
['outside', north(3_100)],
|
||||
]);
|
||||
const f = fleetFixture(positions);
|
||||
f.state._models3dMode = mode;
|
||||
f.tick();
|
||||
for (const id of positions.keys())
|
||||
if (f.fleet().items.has(id)) f.draw.ready(f.fleetId, id);
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('inside'), false, `${mode}: a model at 2.9 km`);
|
||||
assert.equal(f.fleet().items.get('inside').show, true);
|
||||
assert.equal(f.shown.get('outside'), true, `${mode}: an icon at 3.1 km`);
|
||||
assert.equal(f.fleet().items.has('outside'), false);
|
||||
}
|
||||
});
|
||||
|
||||
test('a model is kept out to about 3.6 km, then its icon takes over', () => {
|
||||
const positions = new Map([['a1', north(2_000)]]);
|
||||
const f = fleetFixture(positions);
|
||||
f.tick();
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('a1'), false, 'a model at 2 km');
|
||||
positions.set('a1', north(3_500));
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('a1'), false, 'kept at 3.5 km');
|
||||
assert.equal(f.fleet().items.get('a1').show, true);
|
||||
positions.set('a1', north(3_700));
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('a1'), true, 'released at 3.7 km');
|
||||
assert.equal(f.fleet().items.has('a1'), false);
|
||||
positions.set('a1', north(3_300));
|
||||
f.tick();
|
||||
assert.equal(
|
||||
f.fleet().items.has('a1'),
|
||||
false,
|
||||
'not taken again until it is back within 3 km',
|
||||
);
|
||||
});
|
||||
|
||||
test('a camera high above the ground still models an aircraft within 3 km of it', () => {
|
||||
// A plane at 30 km with the camera 2 km above it: the altitude ceiling
|
||||
// sits above every contact's height plus the keep radius.
|
||||
const plane = fromDegrees(-97.71, 30.21, 30_000);
|
||||
const f = fleetFixture(new Map([['high', plane]]), { eyeM: 32_000 });
|
||||
f.tick();
|
||||
f.draw.ready(f.fleetId, 'high');
|
||||
f.tick();
|
||||
assert.equal(f.shown.get('high'), false, 'its model draws it');
|
||||
assert.equal(
|
||||
POLICY.MODEL_ALT_CEIL_M,
|
||||
POLICY.MODEL_HIGHEST_CONTACT_M + POLICY.MODEL_KEEP_M,
|
||||
);
|
||||
});
|
||||
|
||||
test('models are drawn at their true size, with no minimum pixel size', () => {
|
||||
const f = fleetFixture(new Map([['a1', near(1)]]));
|
||||
f.tick();
|
||||
assert.equal(f.fleet().items.get('a1').minPixelSize ?? 0, 0);
|
||||
});
|
||||
|
||||
test('the selected contact keeps a loaded, hidden fleet model that takes it back on deselect', () => {
|
||||
const positions = new Map([['a1', near(1)]]);
|
||||
const f = fleetFixture(positions);
|
||||
// Selected while an icon: the fleet pass admits its model all the same.
|
||||
f.state._trackedIcao = 'a1';
|
||||
f.shown.set('a1', false); // selecting it hides its icon
|
||||
f.tick();
|
||||
assert.ok(f.fleet().items.has('a1'), 'admitted and loading while selected');
|
||||
f.draw.ready(f.fleetId, 'a1');
|
||||
positions.set('a1', near(2));
|
||||
f.tick();
|
||||
const item = f.fleet().items.get('a1');
|
||||
assert.equal(item.show, false, 'never drawn while selected');
|
||||
assert.deepEqual(
|
||||
item.pos,
|
||||
{ x: near(2).x, y: near(2).y, z: near(2).z },
|
||||
'placed where its icon is',
|
||||
);
|
||||
assert.equal(f.shown.get('a1'), false, 'the icon stays hidden');
|
||||
|
||||
// Deselected: its model draws it in the same frame, its icon never shows.
|
||||
f.state._trackedIcao = null;
|
||||
f.models._handBackDeselected('a1');
|
||||
assert.equal(f.fleet().items.get('a1').show, true);
|
||||
assert.equal(f.shown.get('a1'), false);
|
||||
});
|
||||
@@ -17,15 +17,29 @@ export const AIRCRAFT_ENVIRONMENT_MAP_OPTIONS = Object.freeze({
|
||||
const HIGHLIGHT = Object.freeze({ mode: 'highlight' });
|
||||
const FLAT = Object.freeze({ mode: 'mix', amount: 1 });
|
||||
|
||||
/**
|
||||
* How much of an emergency colour a model takes over its paint. Multiplying
|
||||
* by a saturated tint zeroes every channel the tint lacks: a cyan tint (no
|
||||
* red) draws a red helicopter black and a white Cessna flat cyan. Mixed in at
|
||||
* this share, the paint stays readable and the colour still marks the model.
|
||||
*/
|
||||
export const AIRCRAFT_MODEL_TINT_MIX = 0.3;
|
||||
|
||||
const TINTED = Object.freeze({ mode: 'mix', amount: AIRCRAFT_MODEL_TINT_MIX });
|
||||
|
||||
/**
|
||||
* How an aircraft model's colour meets its mesh, as a draw item's
|
||||
* `colorBlend`. `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, unlit).
|
||||
* `colorBlend`. White (no tint) multiplies (`highlight`), which draws the
|
||||
* mesh's own colours as built. An emergency colour is mixed in at
|
||||
* `AIRCRAFT_MODEL_TINT_MIX`, so it tints the mesh without hiding its paint.
|
||||
* The IR boost draws the model flat white instead (`mix` at 1, unlit).
|
||||
* @param {boolean} irBoost
|
||||
* @param {ArrayLike<number>|null} [tint] The model's RGBA tint, 0..1; white
|
||||
* or none draws the mesh's own colours.
|
||||
* @returns {{mode: 'highlight'|'mix', amount?: number}}
|
||||
*/
|
||||
export function aircraftModelBlend(irBoost) {
|
||||
return irBoost ? FLAT : HIGHLIGHT;
|
||||
export function aircraftModelBlend(irBoost, tint = null) {
|
||||
if (irBoost) return FLAT;
|
||||
const white = !tint || (tint[0] >= 1 && tint[1] >= 1 && tint[2] >= 1);
|
||||
return white ? HIGHLIGHT : TINTED;
|
||||
}
|
||||
@@ -2,7 +2,12 @@ import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { readLayerSource } from '../testSupport/readLayerSource.mjs';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
|
||||
import {
|
||||
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
aircraftModelBlend,
|
||||
} from './aircraftModelLighting.js';
|
||||
import * as flightsPolicy from '../layers/flights/policy.js';
|
||||
import * as militaryPolicy from '../layers/military/policy.js';
|
||||
|
||||
/**
|
||||
* Every aircraft model drawn in the scene skips the renderer's dynamic
|
||||
@@ -48,3 +53,63 @@ test('localAdsb: its draw-port models skip the dynamic environment map', () => {
|
||||
/\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/,
|
||||
);
|
||||
});
|
||||
|
||||
/**
|
||||
* The colour a model draws in, as the renderer blends its tint over the
|
||||
* shaded paint (`ModelItem.colorBlend`, Cesium's model colour stage): `mix`
|
||||
* moves the paint toward the tint by `amount`; `highlight` multiplies.
|
||||
*/
|
||||
function blended(paint, tint, blend) {
|
||||
if (blend.mode === 'mix')
|
||||
return paint.map((c, i) => c + (tint[i] - c) * blend.amount);
|
||||
if (blend.mode === 'highlight') return paint.map((c, i) => c * tint[i]);
|
||||
return tint.slice(0, 3);
|
||||
}
|
||||
|
||||
/** Paints the fleet models carry: a red helicopter, a white airliner, a dark blue tail. */
|
||||
const PAINTS = {
|
||||
red: [0.8, 0.05, 0.05],
|
||||
white: [0.9, 0.9, 0.9],
|
||||
blue: [0.05, 0.1, 0.5],
|
||||
};
|
||||
|
||||
test('an untinted model draws its mesh in its own colours', () => {
|
||||
for (const tint of [null, [1, 1, 1, 1], flightsPolicy.MODEL_WHITE]) {
|
||||
const blend = aircraftModelBlend(false, tint);
|
||||
for (const paint of Object.values(PAINTS))
|
||||
assert.deepEqual(blended(paint, [1, 1, 1], blend), paint);
|
||||
}
|
||||
});
|
||||
|
||||
test('the emergency tints keep every paint, never black or one flat colour', () => {
|
||||
const tints = {
|
||||
emergency: flightsPolicy.EMERGENCY_TINT,
|
||||
'military emergency': militaryPolicy.EMERGENCY_ICON_COLOR,
|
||||
// Any saturated tint: one with no red once drew a red helicopter black.
|
||||
cyan: [0, 1, 1, 1],
|
||||
};
|
||||
for (const [tintName, tint] of Object.entries(tints)) {
|
||||
const blend = aircraftModelBlend(false, tint);
|
||||
const drawn = {};
|
||||
for (const [paintName, paint] of Object.entries(PAINTS)) {
|
||||
const out = blended(paint, tint, blend);
|
||||
drawn[paintName] = out;
|
||||
// Multiplying by a tint with no red drew a red helicopter black.
|
||||
paint.forEach((c, i) =>
|
||||
assert.ok(
|
||||
out[i] >= c * 0.6,
|
||||
`${tintName} over ${paintName}: channel ${i} ${out[i].toFixed(2)} keeps most of ${c}`,
|
||||
),
|
||||
);
|
||||
}
|
||||
// Paints that differ still differ: the tint is not one flat colour.
|
||||
const spread = (a, b) => Math.max(...a.map((c, i) => Math.abs(c - b[i])));
|
||||
assert.ok(spread(drawn.red, drawn.white) > 0.4, `${tintName}: red and white apart`);
|
||||
assert.ok(spread(drawn.blue, drawn.white) > 0.4, `${tintName}: blue and white apart`);
|
||||
}
|
||||
});
|
||||
|
||||
test('the IR boost draws every model flat white whatever its tint', () => {
|
||||
for (const tint of [null, flightsPolicy.EMERGENCY_TINT])
|
||||
assert.deepEqual(aircraftModelBlend(true, tint), { mode: 'mix', amount: 1 });
|
||||
});
|
||||
@@ -1461,6 +1461,36 @@ test('enable owns one grace timer and disable/re-enable starts a new session', a
|
||||
}
|
||||
});
|
||||
|
||||
test('the layer turns on and off when its feed fails', async () => {
|
||||
const harness = installWireHarness(undefined, { enabled: false });
|
||||
const priorFetch = globalThis.fetch;
|
||||
const priorWarn = console.warn;
|
||||
const clock = makeFakeAisRuntime();
|
||||
_setAisRuntimeForTest(clock.runtime);
|
||||
globalThis.fetch = async () => ({
|
||||
ok: false,
|
||||
status: 503,
|
||||
json: async () => ({
|
||||
status: 'missing-key',
|
||||
error: 'AISSTREAM_API_KEY is not set',
|
||||
}),
|
||||
});
|
||||
console.warn = () => {};
|
||||
try {
|
||||
// Turning it on succeeds; the failure is shown on the layer.
|
||||
assert.notEqual(await aisLiveVesselsLayer.enable(harness.viewer), false);
|
||||
const feed = _getVesselFeedStateForTest();
|
||||
assert.equal(feed.status, 'unavailable');
|
||||
assert.equal(feed.error, 'AISSTREAM_API_KEY not set');
|
||||
assert.notEqual(aisLiveVesselsLayer.disable(), false);
|
||||
} finally {
|
||||
globalThis.fetch = priorFetch;
|
||||
console.warn = priorWarn;
|
||||
harness.cleanup();
|
||||
_setAisRuntimeForTest();
|
||||
}
|
||||
});
|
||||
|
||||
test('vessel trail lifecycle: deselect clears the selected-vessel trail', () => {
|
||||
const harness = installWireHarness(undefined);
|
||||
try {
|
||||
|
||||
@@ -70,19 +70,24 @@ for (const layer of LAYERS) {
|
||||
'the tracked-model driver uses the cockpit-aware predicate');
|
||||
});
|
||||
|
||||
test(`${layer.name}: Cockpit uses standard Proximity and All radii with a lower cap`, () => {
|
||||
assert.equal(numericConstant(source, 'MODEL_PROX_ADD_M'), 150_000);
|
||||
assert.equal(numericConstant(source, 'MODEL_PROX_KEEP_M'), 185_000);
|
||||
assert.equal(numericConstant(source, 'MODEL_ALL_ADD_M'), 400_000);
|
||||
assert.equal(numericConstant(source, 'MODEL_ALL_KEEP_M'), 450_000);
|
||||
test(`${layer.name}: models draw within 3 km in both modes; Cockpit's AIR band keeps its own radii`, () => {
|
||||
assert.equal(numericConstant(source, 'MODEL_ADD_M'), 3000);
|
||||
assert.equal(numericConstant(source, 'MODEL_KEEP_M'), 3600);
|
||||
assert.equal(numericConstant(source, 'COCKPIT_MODEL_MAX'), 60);
|
||||
|
||||
const add = /^([ \t]*)function _modelAddDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
|
||||
const keep = /^([ \t]*)function _modelKeepDistM\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
|
||||
assert.match(add, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_ADD_M\s*:\s*(?:policy\.)?MODEL_PROX_ADD_M/);
|
||||
assert.match(keep, /(?:(?:flightState|state)\.)?_models3dMode\s*===\s*'all'\s*\?\s*(?:policy\.)?MODEL_ALL_KEEP_M\s*:\s*(?:policy\.)?MODEL_PROX_KEEP_M/);
|
||||
assert.doesNotMatch(add, /COCKPIT_MODEL_ADD_M/);
|
||||
assert.doesNotMatch(keep, /COCKPIT_MODEL_KEEP_M/);
|
||||
assert.match(add, /return\s+(?:policy\.)?MODEL_ADD_M;/, 'Proximity and All share the add radius');
|
||||
assert.match(keep, /return\s+(?:policy\.)?MODEL_KEEP_M;/, 'Proximity and All share the keep radius');
|
||||
|
||||
// The AIR silhouettes are icons, not models: their band stays mode-aware.
|
||||
assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_ADD_M'), 150_000);
|
||||
assert.equal(numericConstant(source, 'COCKPIT_AIR_PROX_KEEP_M'), 185_000);
|
||||
assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_ADD_M'), 400_000);
|
||||
assert.equal(numericConstant(source, 'COCKPIT_AIR_ALL_KEEP_M'), 450_000);
|
||||
const near = /^([ \t]*)function _refreshCockpitNearContacts\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
|
||||
assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_ADD_M\s*:\s*COCKPIT_AIR_PROX_ADD_M/);
|
||||
assert.match(near, /all\s*\?\s*COCKPIT_AIR_ALL_KEEP_M\s*:\s*COCKPIT_AIR_PROX_KEEP_M/);
|
||||
|
||||
const cap = /^([ \t]*)function _modelCap\b[\s\S]*?\n\1\}/m.exec(source)?.[0];
|
||||
assert.match(cap, /Math\.min\(\s*(?:policy\.)?COCKPIT_MODEL_MAX/,
|
||||
@@ -97,7 +102,7 @@ for (const layer of LAYERS) {
|
||||
// `_iconKind` is identity for every unconverted contact (see
|
||||
// tr3bRegistry.test.mjs) — it only swaps the glyph for a contact the
|
||||
// operator explicitly converted into a TR-3B.
|
||||
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?\)/,
|
||||
assert.match(source, /aircraftIcon\(\s*(?:parts\.)?rendering\._iconKind\(icao24, info\?\.klass\),?\s*(?:FLEET_ICON_PX,?\s*)?(?:frame,?\s*)?\)/,
|
||||
'near contacts and model fallbacks retain the class-derived aircraft silhouette');
|
||||
assert.match(source, /color: rgba\(rendering\._cockpitContactColor\(icao24, info\)\),\s*rotationMode: 'screen',/,
|
||||
'far dots are reset to a rotation-free presentation');
|
||||
|
||||
@@ -19,9 +19,8 @@
|
||||
* marker the scene itself hides behind geometry. Everything else keeps its
|
||||
* label exactly as before, which covers contacts high above the ground
|
||||
* (aircraft, satellites): their markers are drawn on top of the scene by
|
||||
* design, their 3D models can be scaled up to a minimum pixel size and so fill
|
||||
* the very pixel being read, and a label that hid while its marker stayed on
|
||||
* screen would be the worse mismatch.
|
||||
* design, their 3D models can fill the very pixel being read, and a label
|
||||
* that hid while its marker stayed on screen would be the worse mismatch.
|
||||
*
|
||||
* This file is plain arithmetic; it never touches the renderer.
|
||||
*/
|
||||
|
||||
@@ -1285,6 +1285,8 @@ const AIRCRAFT_CLASS_NAMES = {
|
||||
turboprop: msg('Turboprops'),
|
||||
fastjet: msg('Fast jets'),
|
||||
quadjet: msg('Four-engine jets'),
|
||||
vehicle: msg('Airport vehicles'),
|
||||
station: msg('Ground stations / obstacles'),
|
||||
};
|
||||
|
||||
/**
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { selectModelEligible } from './modelEligibility.js';
|
||||
import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from './aircraftModelLighting.js';
|
||||
import { fleetModelSet } from './fleetModels.js';
|
||||
import { fleetModelSet, fleetPartTable } from './fleetModels.js';
|
||||
import { findCamera, findDraw } from '../render/rendererOf.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
import { horizonFrom } from '../geo/horizon.js';
|
||||
@@ -111,10 +111,15 @@ let instances = 0;
|
||||
* @param {object} options.viewer The scene host.
|
||||
* @param {() => object|null} [options.display] `{models3d, models3dMode,
|
||||
* irBoost}`.
|
||||
* @param {object} options.policy `{altitudeCeilingM, minimumPixelSize,
|
||||
* cap, capAll, addM, addAllM, keepM, keepAllM, intervalMs}`.
|
||||
* @param {object} options.policy `{altitudeCeilingM, cap, capAll, addM,
|
||||
* keepM, intervalMs}`: both 3D modes share the add/keep radii and differ
|
||||
* by their caps. Models are drawn at their true size.
|
||||
* @param {(url: string) => string} [options.resolveAsset]
|
||||
* @param {boolean} [options.waterline] Clip each model at its waterline.
|
||||
* @param {(item: object, table: object) => object|undefined} [options.partState]
|
||||
* The moving parts a vehicle's model is posed with (`ModelItem.parts`),
|
||||
* from its item and its model's part table (`modelPartDrivers.js`); asked
|
||||
* only for a model that has a part table.
|
||||
* @param {object} [options.draw] Stands in for the viewer's draw port (tests).
|
||||
* @returns {object}
|
||||
*/
|
||||
@@ -124,6 +129,7 @@ export function createFleetModelLayer({
|
||||
policy,
|
||||
waterline = false,
|
||||
resolveAsset = (url) => url,
|
||||
partState = null,
|
||||
draw,
|
||||
}) {
|
||||
const port = draw ?? findDraw(viewer);
|
||||
@@ -202,8 +208,7 @@ export function createFleetModelLayer({
|
||||
function refreshEligibility(items, prefs, eye) {
|
||||
const all = prefs.models3dMode === 'all';
|
||||
const cap = all ? policy.capAll : policy.cap;
|
||||
const addM = all ? policy.addAllM : policy.addM;
|
||||
const keepM = all ? policy.keepAllM : policy.keepM;
|
||||
const { addM, keepM } = policy;
|
||||
const candidates = [];
|
||||
for (const [id, item] of items) {
|
||||
if (!item.position || item.show === false || !item.spec?.url) continue;
|
||||
@@ -230,8 +235,15 @@ export function createFleetModelLayer({
|
||||
return fromDegrees(at.lon, at.lat, at.height + lift);
|
||||
}
|
||||
|
||||
/** The part state an item's model is posed with, or undefined. */
|
||||
function partsOf(item) {
|
||||
if (!partState) return undefined;
|
||||
const table = fleetPartTable(fleetModelSet(), item.spec?.model);
|
||||
return table ? partState(item, table) : undefined;
|
||||
}
|
||||
|
||||
/** The draw item for an admitted model, as the set draws it, at `at`. */
|
||||
function itemOf(id, record, item, show, boost, at = placement(item)) {
|
||||
function itemOf(id, record, item, show, boost, at, parts) {
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
return {
|
||||
id,
|
||||
@@ -249,7 +261,6 @@ export function createFleetModelLayer({
|
||||
...(fleetAxisScale(item.spec)
|
||||
? { axisScale: fleetAxisScale(item.spec) }
|
||||
: {}),
|
||||
minPixelSize: policy.minimumPixelSize,
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(boost
|
||||
? {
|
||||
@@ -260,6 +271,7 @@ export function createFleetModelLayer({
|
||||
: { shading: 'pbr' }),
|
||||
...(mask ? { maskColor: mask } : {}),
|
||||
...(waterline ? { clip: 'belowOrigin' } : {}),
|
||||
...(parts ? { parts } : {}),
|
||||
meta: item.pickId ?? id,
|
||||
show,
|
||||
};
|
||||
@@ -276,6 +288,8 @@ export function createFleetModelLayer({
|
||||
const heading = item.headingDeg || 0;
|
||||
const mask = item.spec.tinted && !boost ? fleetColor(item.tint) : null;
|
||||
const meta = item.pickId ?? id;
|
||||
const parts = partsOf(item);
|
||||
const partsKey = parts ? JSON.stringify(parts) : '';
|
||||
const sent = record.sent;
|
||||
if (
|
||||
sent !== null &&
|
||||
@@ -287,7 +301,8 @@ export function createFleetModelLayer({
|
||||
sameColor(sent.mask, mask) &&
|
||||
sent.boost === boost &&
|
||||
sent.show === show &&
|
||||
sent.meta === meta
|
||||
sent.meta === meta &&
|
||||
sent.partsKey === partsKey
|
||||
)
|
||||
return null;
|
||||
const next = (record.sent ??= {});
|
||||
@@ -301,7 +316,8 @@ export function createFleetModelLayer({
|
||||
next.boost = boost;
|
||||
next.show = show;
|
||||
next.meta = meta;
|
||||
return itemOf(id, record, item, show, boost, at);
|
||||
next.partsKey = partsKey;
|
||||
return itemOf(id, record, item, show, boost, at, parts);
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
vesselModelSpec,
|
||||
} from './fleetModels.js';
|
||||
import { fetchPublicFile } from '../testSupport/fleetGlb.mjs';
|
||||
import { FLEET_MODEL_POLICY } from '../layers/flights/policy.js';
|
||||
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
|
||||
import { eastNorthUp } from '../geo/frames.js';
|
||||
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
|
||||
@@ -29,15 +30,11 @@ console.info = () => {};
|
||||
const set = await loadFleetModelSet({ fetchImpl: fetchPublicFile });
|
||||
console.info = realInfo;
|
||||
|
||||
// The layers' own policy (3 km add, about 3.6 km keep), with small caps.
|
||||
const POLICY = Object.freeze({
|
||||
altitudeCeilingM: 800_000,
|
||||
minimumPixelSize: 16,
|
||||
...FLEET_MODEL_POLICY,
|
||||
cap: 2,
|
||||
capAll: 4,
|
||||
addM: 5_000,
|
||||
addAllM: 20_000,
|
||||
keepM: 6_000,
|
||||
keepAllM: 24_000,
|
||||
intervalMs: 80,
|
||||
});
|
||||
|
||||
@@ -117,7 +114,7 @@ test('the icon stays the visual until the model is ready; only the nearest are d
|
||||
);
|
||||
const near = models.items.get('near');
|
||||
assert.equal(near.scale, spec.scale, 'drawn life size');
|
||||
assert.equal(near.minPixelSize, POLICY.minimumPixelSize);
|
||||
assert.equal(near.minPixelSize ?? 0, 0, 'at its true size: no pixel floor');
|
||||
assert.equal(near.meta, 'near', 'picked as its vehicle');
|
||||
assert.equal(near.show, false, 'hidden until ready');
|
||||
|
||||
@@ -158,6 +155,38 @@ test('the icon stays the visual until the model is ready; only the nearest are d
|
||||
assert.equal(models.disposed, true);
|
||||
});
|
||||
|
||||
test('vehicles draw as models within 3 km in either mode, and keep them to about 3.6 km', () => {
|
||||
// The camera 1 km up: a vehicle `metres` east is sqrt(1 km² + metres²) away.
|
||||
const at = (km) => Math.sqrt(km * km - 1) * 1_000;
|
||||
for (const mode of ['proximity', 'all']) {
|
||||
const { viewer, draw } = fakeViewer();
|
||||
const layer = createFleetModelLayer({
|
||||
viewer,
|
||||
display: () => ({ models3d: true, models3dMode: mode }),
|
||||
policy: POLICY,
|
||||
});
|
||||
const spec = transitModelSpec(set, { mode: 'tram' });
|
||||
const items = new Map([
|
||||
['in', itemAt(at(2.9), spec, { pickId: 'in' })],
|
||||
['out', itemAt(at(3.1), spec, { pickId: 'out' })],
|
||||
]);
|
||||
layer.frame(items, 0);
|
||||
const models = modelSet(draw);
|
||||
assert.deepEqual(
|
||||
[...models.items.keys()],
|
||||
['in'],
|
||||
`${mode}: 2.9 km, not 3.1 km`,
|
||||
);
|
||||
items.set('in', itemAt(at(3.5), spec, { pickId: 'in' }));
|
||||
layer.frame(items, 100);
|
||||
assert.ok(models.items.has('in'), `${mode}: kept at 3.5 km`);
|
||||
items.set('in', itemAt(at(3.7), spec, { pickId: 'in' }));
|
||||
layer.frame(items, 200);
|
||||
assert.equal(models.items.size, 0, `${mode}: released at 3.7 km`);
|
||||
layer.destroy();
|
||||
}
|
||||
});
|
||||
|
||||
test('models stay off above the altitude ceiling', () => {
|
||||
const { viewer, draw } = fakeViewer(POLICY.altitudeCeilingM + 1);
|
||||
const layer = createFleetModelLayer({
|
||||
|
||||
@@ -20,6 +20,7 @@
|
||||
*/
|
||||
|
||||
import { classifyAircraft } from './aircraftClass.js';
|
||||
import { readPartTable } from '../render/modelParts.js';
|
||||
import { FLEET_TRAIL_ANCHORS } from './fleetTrailAnchors.js';
|
||||
import { isAidToNavigation } from './vesselTypes.js';
|
||||
|
||||
@@ -527,6 +528,34 @@ export function namedFleetModels(types) {
|
||||
]);
|
||||
}
|
||||
|
||||
/** Each loaded set's part tables by model name (null for a model without one). */
|
||||
const partTables = new WeakMap();
|
||||
|
||||
/**
|
||||
* The part table of model `name` in a loaded set, read once from its GLB:
|
||||
* which moving parts it has (`render/modelParts.js`); null for a model
|
||||
* without one, or whose GLB did not load.
|
||||
* @param {{bytes?: Map<string, Uint8Array>}|null|undefined} set
|
||||
* @param {string|null|undefined} name
|
||||
* @returns {import('../render/modelParts').PartTable|null}
|
||||
*/
|
||||
export function fleetPartTable(set, name) {
|
||||
const bytes = name ? set?.bytes?.get(name) : undefined;
|
||||
if (!bytes) return null;
|
||||
let tables = partTables.get(set);
|
||||
if (!tables) partTables.set(set, (tables = new Map()));
|
||||
if (!tables.has(name)) {
|
||||
let table = null;
|
||||
try {
|
||||
table = readPartTable(bytes);
|
||||
} catch {
|
||||
// A malformed table: the model draws whole.
|
||||
}
|
||||
tables.set(name, table);
|
||||
}
|
||||
return tables.get(name);
|
||||
}
|
||||
|
||||
let loading = null;
|
||||
let loaded = null;
|
||||
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
/**
|
||||
* @module modelPartDrivers
|
||||
* @description What the live layers ask of a fleet model's moving parts
|
||||
* (`ModelItem.parts`), from a vehicle's own record: each a pure function of
|
||||
* the model's part table and what the record says, so the same record poses
|
||||
* the same parts at any time. A model without a part table gets none, and a
|
||||
* renderer that does not pose parts draws the model whole, at rest.
|
||||
*
|
||||
* Which parts each rule drives is read from the table by kind and name:
|
||||
*
|
||||
* - **Aircraft and helicopters** ({@link aircraftPartState}). Spin parts
|
||||
* named `fan…`, `prop…` and `rotor…` turn while the aircraft is airborne,
|
||||
* or on the ground moving faster than {@link MOVING_MPS}. Hinge parts named
|
||||
* `gear…` are down on the ground; in the air they come down between
|
||||
* {@link GEAR_APPROACH_M} metres above the ground when descending faster
|
||||
* than {@link DESCENDING_MPS} (an approach), and otherwise are down below
|
||||
* {@link GEAR_TAKEOFF_M}`[0]` and up above `[1]` (after take-off), in
|
||||
* between in proportion. Without a height above the ground (no ground
|
||||
* height known under it), the gear is down while it descends faster than
|
||||
* {@link DESCENDING_MPS} slower than {@link APPROACH_MPS} below
|
||||
* {@link APPROACH_CEILING_M} (an approach: the highest runways are about
|
||||
* 4,400 m up), and up otherwise. Their doors (`door…`) open over the first
|
||||
* quarter of the gear's travel and stay open while it is out; flaps
|
||||
* (`flap…`) follow the gear in the air and are up on the ground.
|
||||
* - **Vessels** ({@link vesselPartState}): spin parts named `radar…` sweep
|
||||
* while the vessel is under way, faster than {@link UNDER_WAY_MPS}.
|
||||
* - **Road and rail vehicles** ({@link groundVehiclePartState}): spin parts
|
||||
* named `axle…` roll with the vehicle's speed (their pivot's height is the
|
||||
* wheel's radius), and slide parts named `doors…` are open while the
|
||||
* vehicle is stopped at a stop.
|
||||
*
|
||||
* Fractions and speeds are rounded ({@link DEPLOY_STEP}, {@link SPEED_STEP_MPS})
|
||||
* so a record that barely changes asks for the same state.
|
||||
*/
|
||||
|
||||
/** Ground speed (m/s) above which a grounded aircraft's engines turn. */
|
||||
export const MOVING_MPS = 1;
|
||||
/** Vertical rate (m/s, negative down) below which an aircraft is descending. */
|
||||
export const DESCENDING_MPS = -1;
|
||||
/** Heights above the ground (m) over which the gear comes down on approach: up at the first, down at the second. */
|
||||
export const GEAR_APPROACH_M = Object.freeze([750, 600]);
|
||||
/** Heights above the ground (m) over which the gear goes up otherwise: down at the first, up at the second. */
|
||||
export const GEAR_TAKEOFF_M = Object.freeze([100, 300]);
|
||||
/** Ground speed (m/s) under which a descending aircraft is on approach, where no ground height is known (about 165 kt). */
|
||||
export const APPROACH_MPS = 85;
|
||||
/** Altitude (m) under which a descending aircraft may be on approach, where no ground height is known. */
|
||||
export const APPROACH_CEILING_M = 5000;
|
||||
/** Speed (m/s) above which a vessel is under way. */
|
||||
export const UNDER_WAY_MPS = 0.5;
|
||||
/** Speed (m/s) under which a vehicle at a stop is stopped there. */
|
||||
export const STOPPED_MPS = 0.5;
|
||||
/** Deploy fractions are rounded to this step. */
|
||||
export const DEPLOY_STEP = 1 / 32;
|
||||
/** Speeds are rounded to this step (m/s) before they turn wheels. */
|
||||
export const SPEED_STEP_MPS = 0.5;
|
||||
|
||||
/** Degrees a second each spinning part turns at, by name. */
|
||||
export const SPIN_RATES_DPS = Object.freeze({
|
||||
rotor_tail: 3000,
|
||||
rotor: 1080,
|
||||
prop: 1500,
|
||||
fan: 900,
|
||||
radar: 144,
|
||||
});
|
||||
|
||||
/** A wheel's radius (m) where its axle's pivot does not say. */
|
||||
const DEFAULT_WHEEL_RADIUS_M = 0.4;
|
||||
|
||||
const RADIANS_TO_DEGREES = 180 / Math.PI;
|
||||
|
||||
/** `value` rounded to `step`. */
|
||||
const rounded = (value, step) => Math.round(value / step) * step;
|
||||
|
||||
/** 0..1 between `from` (0) and `to` (1), linear, clamped. */
|
||||
function ramp(value, from, to) {
|
||||
const t = (value - from) / (to - from);
|
||||
return Math.min(1, Math.max(0, t));
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft's engines and rotors turn: airborne, or on the ground
|
||||
* moving faster than {@link MOVING_MPS}. The rotor sprite (`rotorFrames.js`)
|
||||
* follows the same rule as the model's spinning parts.
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} aircraft
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function enginesTurn({ onGround, speedMps }) {
|
||||
return (
|
||||
!onGround ||
|
||||
(typeof speedMps === 'number' &&
|
||||
Number.isFinite(speedMps) &&
|
||||
speedMps > MOVING_MPS)
|
||||
);
|
||||
}
|
||||
|
||||
/** A spin part's rate by its name, or 0 for a name not listed. */
|
||||
function spinRate(name) {
|
||||
if (name === 'rotor_tail') return SPIN_RATES_DPS.rotor_tail;
|
||||
for (const prefix of ['rotor', 'prop', 'fan', 'radar'])
|
||||
if (name.startsWith(prefix)) return SPIN_RATES_DPS[prefix];
|
||||
return 0;
|
||||
}
|
||||
|
||||
/** Each part of `kind` whose name starts with one of `prefixes`. */
|
||||
function* partsOf(table, kind, prefixes) {
|
||||
for (const part of table?.parts ?? [])
|
||||
if (part.kind === kind && prefixes.some((p) => part.name.startsWith(p)))
|
||||
yield part;
|
||||
}
|
||||
|
||||
/** A state with only the members that name a part; undefined for none. */
|
||||
function stateOf(spin, deploy) {
|
||||
const out = {};
|
||||
if (Object.keys(spin).length) out.spin = spin;
|
||||
if (Object.keys(deploy).length) out.deploy = deploy;
|
||||
return out.spin || out.deploy ? out : undefined;
|
||||
}
|
||||
|
||||
/**
|
||||
* How far an aircraft's gear is down, 0 (up) to 1 (down), by the rule in the
|
||||
* module comment.
|
||||
* @param {{onGround?: boolean, heightAboveGroundM?: number|null,
|
||||
* altitudeM?: number|null, verticalRateMps?: number|null,
|
||||
* speedMps?: number|null}} aircraft
|
||||
* @returns {number}
|
||||
*/
|
||||
export function gearDown({
|
||||
onGround,
|
||||
heightAboveGroundM,
|
||||
altitudeM,
|
||||
verticalRateMps,
|
||||
speedMps,
|
||||
}) {
|
||||
if (onGround) return 1;
|
||||
const known = (v) => typeof v === 'number' && Number.isFinite(v);
|
||||
const descending = known(verticalRateMps) && verticalRateMps < DESCENDING_MPS;
|
||||
const h = heightAboveGroundM;
|
||||
if (!known(h))
|
||||
return descending &&
|
||||
known(speedMps) &&
|
||||
speedMps < APPROACH_MPS &&
|
||||
(!known(altitudeM) || altitudeM < APPROACH_CEILING_M)
|
||||
? 1
|
||||
: 0;
|
||||
const down = descending
|
||||
? Math.max(
|
||||
ramp(h, GEAR_APPROACH_M[0], GEAR_APPROACH_M[1]),
|
||||
ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]),
|
||||
)
|
||||
: ramp(h, GEAR_TAKEOFF_M[1], GEAR_TAKEOFF_M[0]);
|
||||
return rounded(down, DEPLOY_STEP);
|
||||
}
|
||||
|
||||
/**
|
||||
* An aircraft's or helicopter's part state, by the rule in the module
|
||||
* comment; undefined when its model has no part the rule drives.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{onGround?: boolean, heightAboveGroundM?: number|null,
|
||||
* altitudeM?: number|null, verticalRateMps?: number|null,
|
||||
* speedMps?: number|null}} aircraft
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function aircraftPartState(table, aircraft) {
|
||||
if (!table) return undefined;
|
||||
const spin = {};
|
||||
const deploy = {};
|
||||
if (enginesTurn(aircraft))
|
||||
for (const part of partsOf(table, 'spin', ['fan', 'prop', 'rotor']))
|
||||
spin[part.name] = spinRate(part.name);
|
||||
const gear = gearDown(aircraft);
|
||||
const doors = Math.min(1, rounded(gear * 4, DEPLOY_STEP));
|
||||
for (const part of partsOf(table, 'hinge', ['gear']))
|
||||
deploy[part.name] = gear;
|
||||
for (const part of partsOf(table, 'hinge', ['door']))
|
||||
deploy[part.name] = doors;
|
||||
for (const part of partsOf(table, 'hinge', ['flap']))
|
||||
deploy[part.name] = aircraft.onGround ? 0 : gear;
|
||||
return stateOf(spin, deploy);
|
||||
}
|
||||
|
||||
/**
|
||||
* The part state of a contact in an aircraft layer: an airport vehicle
|
||||
* (class `vehicle`) is a road vehicle ({@link groundVehiclePartState}, its
|
||||
* wheels rolling with its speed, never at a stop), every other contact an
|
||||
* aircraft ({@link aircraftPartState}).
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{klass?: string|null, onGround?: boolean,
|
||||
* heightAboveGroundM?: number|null, altitudeM?: number|null,
|
||||
* verticalRateMps?: number|null, speedMps?: number|null}} contact
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function aircraftLayerPartState(table, contact) {
|
||||
return contact.klass === 'vehicle'
|
||||
? groundVehiclePartState(table, { speedMps: contact.speedMps })
|
||||
: aircraftPartState(table, contact);
|
||||
}
|
||||
|
||||
/**
|
||||
* A vessel's part state, by the rule in the module comment; undefined when
|
||||
* it is not under way or its model has no radar.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{speedMps?: number|null}} vessel
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function vesselPartState(table, { speedMps }) {
|
||||
if (!table || !(typeof speedMps === 'number' && speedMps > UNDER_WAY_MPS))
|
||||
return undefined;
|
||||
const spin = {};
|
||||
for (const part of partsOf(table, 'spin', ['radar']))
|
||||
spin[part.name] = SPIN_RATES_DPS.radar;
|
||||
return stateOf(spin, {});
|
||||
}
|
||||
|
||||
/**
|
||||
* A road or rail vehicle's part state, by the rule in the module comment;
|
||||
* undefined when it neither moves nor stands at a stop, or its model has no
|
||||
* part the rule drives.
|
||||
* @param {import('../render/modelParts').PartTable|null|undefined} table
|
||||
* @param {{speedMps?: number|null, atStop?: boolean}} vehicle
|
||||
* @returns {import('../render/contract/draw').ModelPartState|undefined}
|
||||
*/
|
||||
export function groundVehiclePartState(table, { speedMps, atStop }) {
|
||||
if (!table) return undefined;
|
||||
const speed =
|
||||
typeof speedMps === 'number' && Number.isFinite(speedMps)
|
||||
? rounded(Math.max(0, speedMps), SPEED_STEP_MPS)
|
||||
: 0;
|
||||
const spin = {};
|
||||
const deploy = {};
|
||||
if (speed > 0)
|
||||
for (const part of partsOf(table, 'spin', ['axle'])) {
|
||||
const radius =
|
||||
part.pivot[1] > 0.05 ? part.pivot[1] : DEFAULT_WHEEL_RADIUS_M;
|
||||
// Rolling forward (−X) on the ground turns a wheel about +Z (its left).
|
||||
const sign = Math.sign(part.axis?.[2] ?? 0);
|
||||
if (sign !== 0)
|
||||
spin[part.name] = (sign * speed * RADIANS_TO_DEGREES) / radius;
|
||||
}
|
||||
if (atStop && speed < STOPPED_MPS)
|
||||
for (const part of partsOf(table, 'slide', ['doors']))
|
||||
deploy[part.name] = 1;
|
||||
return stateOf(spin, deploy);
|
||||
}
|
||||
@@ -0,0 +1,257 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import { test } from 'node:test';
|
||||
|
||||
import {
|
||||
aircraftLayerPartState,
|
||||
aircraftPartState,
|
||||
enginesTurn,
|
||||
gearDown,
|
||||
groundVehiclePartState,
|
||||
SPIN_RATES_DPS,
|
||||
vesselPartState,
|
||||
} from './modelPartDrivers.js';
|
||||
import { fleetPartTable } from './fleetModels.js';
|
||||
import { partTableOf } from '../render/modelParts.js';
|
||||
import { partsModelGlb } from '../render/conformance/partsModel.js';
|
||||
|
||||
const AIRLINER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'flap_right', kind: 'hinge', axis: [0, 0, -1], limits: [0, 40] },
|
||||
{ name: 'engine_right', kind: 'marker' },
|
||||
{
|
||||
name: 'fan_right',
|
||||
kind: 'spin',
|
||||
parent: 'engine_right',
|
||||
axis: [1, 0, 0],
|
||||
},
|
||||
{ name: 'gear_nose', kind: 'hinge', axis: [0, 0, 1], limits: [90, 0] },
|
||||
{
|
||||
name: 'door_nose_right',
|
||||
kind: 'hinge',
|
||||
axis: [1, 0, 0],
|
||||
limits: [0, 90],
|
||||
},
|
||||
{ name: 'gear_right', kind: 'hinge', axis: [-1, 0, 0], limits: [90, 0] },
|
||||
],
|
||||
});
|
||||
|
||||
const HELICOPTER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] },
|
||||
{ name: 'rotor_tail', kind: 'spin', axis: [0, 0, -1] },
|
||||
{ name: 'skids', kind: 'marker' },
|
||||
],
|
||||
});
|
||||
|
||||
const TRAWLER = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'radar', kind: 'spin', pivot: [-4, 10, 0], axis: [0, 1, 0] },
|
||||
{ name: 'bridge', kind: 'marker' },
|
||||
],
|
||||
});
|
||||
|
||||
const BUS = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{
|
||||
name: 'doors_right',
|
||||
kind: 'slide',
|
||||
pivot: [-4.75, 0.35, -1.3],
|
||||
axis: [1, 0, 0],
|
||||
limits: [0, 1.08],
|
||||
},
|
||||
{ name: 'axle_1', kind: 'spin', pivot: [-3.3, 0.5, 0], axis: [0, 0, -1] },
|
||||
{ name: 'axle_2', kind: 'spin', pivot: [2.6, 0.5, 0], axis: [0, 0, -1] },
|
||||
],
|
||||
});
|
||||
|
||||
test('the gear is down on the ground and up in cruise', () => {
|
||||
assert.equal(gearDown({ onGround: true }), 1);
|
||||
assert.equal(gearDown({ heightAboveGroundM: 10000, verticalRateMps: 0 }), 0);
|
||||
assert.equal(
|
||||
gearDown({ heightAboveGroundM: 10000, verticalRateMps: -10 }),
|
||||
0,
|
||||
);
|
||||
// No height known: up.
|
||||
assert.equal(gearDown({ heightAboveGroundM: null }), 0);
|
||||
});
|
||||
|
||||
test('without a ground height, the gear is down on approach: descending, slow and low', () => {
|
||||
// Denver: 1,650 m up, the ground under it unknown.
|
||||
const at = (fields) => gearDown({ heightAboveGroundM: null, ...fields });
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: -4, speedMps: 70 }), 1);
|
||||
// Climbing out, cruising, or descending fast: up.
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: 8, speedMps: 70 }), 0);
|
||||
assert.equal(at({ altitudeM: 11000, verticalRateMps: -4, speedMps: 70 }), 0);
|
||||
assert.equal(at({ altitudeM: 3000, verticalRateMps: -8, speedMps: 140 }), 0);
|
||||
// Without a speed it cannot tell: up.
|
||||
assert.equal(at({ altitudeM: 2000, verticalRateMps: -4 }), 0);
|
||||
});
|
||||
|
||||
test('on approach the gear comes down between 750 and 600 m above the ground', () => {
|
||||
const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: -4 });
|
||||
assert.equal(at(800), 0);
|
||||
assert.equal(at(675), 0.5);
|
||||
assert.equal(at(600), 1);
|
||||
assert.equal(at(50), 1);
|
||||
});
|
||||
|
||||
test('climbing or level, the gear goes up between 100 and 300 m', () => {
|
||||
const at = (h) => gearDown({ heightAboveGroundM: h, verticalRateMps: 8 });
|
||||
assert.equal(at(50), 1);
|
||||
assert.equal(at(200), 0.5);
|
||||
assert.equal(at(300), 0);
|
||||
assert.equal(at(700), 0);
|
||||
// Level at 700 m: up; descending through it: up until the approach band.
|
||||
assert.equal(gearDown({ heightAboveGroundM: 700, verticalRateMps: 0 }), 0);
|
||||
});
|
||||
|
||||
test('an airliner in cruise spins its fans, gear, doors and flaps up', () => {
|
||||
const state = aircraftPartState(AIRLINER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 11000,
|
||||
verticalRateMps: 0,
|
||||
speedMps: 230,
|
||||
});
|
||||
assert.deepEqual(state, {
|
||||
spin: { fan_right: SPIN_RATES_DPS.fan },
|
||||
deploy: {
|
||||
flap_right: 0,
|
||||
gear_nose: 0,
|
||||
door_nose_right: 0,
|
||||
gear_right: 0,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
test('an airliner on final has gear, doors and flaps down', () => {
|
||||
const state = aircraftPartState(AIRLINER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
verticalRateMps: -4,
|
||||
speedMps: 70,
|
||||
});
|
||||
assert.deepEqual(state.deploy, {
|
||||
flap_right: 1,
|
||||
gear_nose: 1,
|
||||
door_nose_right: 1,
|
||||
gear_right: 1,
|
||||
});
|
||||
// The doors open over the first quarter of the gear's travel.
|
||||
const coming = aircraftPartState(AIRLINER, {
|
||||
heightAboveGroundM: 745,
|
||||
verticalRateMps: -4,
|
||||
});
|
||||
assert.ok(coming.deploy.gear_nose > 0 && coming.deploy.gear_nose < 0.25);
|
||||
assert.ok(coming.deploy.door_nose_right > coming.deploy.gear_nose);
|
||||
});
|
||||
|
||||
test('parked, its engines stop; taxiing, they turn; its flaps are up on the ground', () => {
|
||||
const parked = aircraftPartState(AIRLINER, { onGround: true, speedMps: 0 });
|
||||
assert.equal(parked.spin, undefined);
|
||||
assert.equal(parked.deploy.gear_nose, 1);
|
||||
assert.equal(parked.deploy.flap_right, 0);
|
||||
const taxiing = aircraftPartState(AIRLINER, { onGround: true, speedMps: 8 });
|
||||
assert.equal(taxiing.spin.fan_right, SPIN_RATES_DPS.fan);
|
||||
});
|
||||
|
||||
test('a helicopter’s rotors turn in the air and stop on the ground', () => {
|
||||
const flying = aircraftPartState(HELICOPTER, {
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
});
|
||||
assert.deepEqual(flying, {
|
||||
spin: {
|
||||
rotor_main: SPIN_RATES_DPS.rotor,
|
||||
rotor_tail: SPIN_RATES_DPS.rotor_tail,
|
||||
},
|
||||
});
|
||||
assert.equal(
|
||||
aircraftPartState(HELICOPTER, { onGround: true, speedMps: 0 }),
|
||||
undefined,
|
||||
);
|
||||
});
|
||||
|
||||
test('a vessel’s radar sweeps while it is under way', () => {
|
||||
assert.deepEqual(vesselPartState(TRAWLER, { speedMps: 4 }), {
|
||||
spin: { radar: SPIN_RATES_DPS.radar },
|
||||
});
|
||||
assert.equal(vesselPartState(TRAWLER, { speedMps: 0.2 }), undefined);
|
||||
assert.equal(vesselPartState(TRAWLER, { speedMps: null }), undefined);
|
||||
// A model without a radar, or without a table, gets nothing.
|
||||
assert.equal(vesselPartState(HELICOPTER, { speedMps: 4 }), undefined);
|
||||
assert.equal(vesselPartState(null, { speedMps: 4 }), undefined);
|
||||
});
|
||||
|
||||
test('a bus’s wheels roll with its speed, top forward; its doors open at a stop', () => {
|
||||
const moving = groundVehiclePartState(BUS, { speedMps: 10 });
|
||||
// 10 m/s on 0.5 m wheels: 20 rad/s, about +Z (its left), the top rolling forward.
|
||||
const rate = -(10 / 0.5) * (180 / Math.PI);
|
||||
assert.ok(Math.abs(moving.spin.axle_1 - rate) < 1e-9);
|
||||
assert.equal(moving.deploy, undefined);
|
||||
const stopped = groundVehiclePartState(BUS, { speedMps: 0, atStop: true });
|
||||
assert.deepEqual(stopped, { deploy: { doors_right: 1 } });
|
||||
assert.equal(
|
||||
groundVehiclePartState(BUS, { speedMps: 0, atStop: false }),
|
||||
undefined,
|
||||
);
|
||||
// Speeds are rounded: 10.1 m/s turns the wheels as 10 does.
|
||||
assert.deepEqual(groundVehiclePartState(BUS, { speedMps: 10.1 }), moving);
|
||||
});
|
||||
|
||||
test('an airport vehicle rolls its wheels and never holds its doors open; an aircraft is posed as one', () => {
|
||||
// A van: wheels roll with its speed.
|
||||
const rolling = aircraftLayerPartState(BUS, {
|
||||
klass: 'vehicle',
|
||||
onGround: true,
|
||||
speedMps: 10,
|
||||
});
|
||||
assert.deepEqual(rolling, groundVehiclePartState(BUS, { speedMps: 10 }));
|
||||
assert.ok(rolling.spin.axle_1 !== 0);
|
||||
// Stopped on the apron it is not at a stop: its doors stay shut.
|
||||
assert.equal(
|
||||
aircraftLayerPartState(BUS, {
|
||||
klass: 'vehicle',
|
||||
onGround: true,
|
||||
speedMps: 0,
|
||||
}),
|
||||
undefined,
|
||||
);
|
||||
// Every other class is an aircraft.
|
||||
const flying = {
|
||||
klass: 'helicopter',
|
||||
onGround: false,
|
||||
heightAboveGroundM: 300,
|
||||
};
|
||||
assert.deepEqual(
|
||||
aircraftLayerPartState(HELICOPTER, flying),
|
||||
aircraftPartState(HELICOPTER, flying),
|
||||
);
|
||||
});
|
||||
|
||||
test('engines and rotors turn in the air, or on the ground faster than 1 m/s', () => {
|
||||
assert.equal(enginesTurn({ onGround: false }), true);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 0 }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 1 }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: 1.5 }), true);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: null }), false);
|
||||
assert.equal(enginesTurn({ onGround: true, speedMps: Number.NaN }), false);
|
||||
});
|
||||
|
||||
test('a model of a loaded set has its part table, read once', () => {
|
||||
const set = { bytes: new Map([['pod', partsModelGlb()]]) };
|
||||
const table = fleetPartTable(set, 'pod');
|
||||
assert.deepEqual(
|
||||
table.parts.map((p) => p.name),
|
||||
['body', 'pod', 'ram', 'arm'],
|
||||
);
|
||||
assert.equal(fleetPartTable(set, 'pod'), table);
|
||||
assert.equal(fleetPartTable(set, 'missing'), null);
|
||||
assert.equal(fleetPartTable(null, 'pod'), null);
|
||||
// A model without a table has none.
|
||||
const plain = { bytes: new Map([['x', new Uint8Array(4)]]) };
|
||||
assert.equal(fleetPartTable(plain, 'x'), null);
|
||||
});
|
||||
+13
-5
@@ -127,19 +127,27 @@ export function courseSlewCapDps(speedMps, maxDps, minDps = COURSE_MIN_DPS) {
|
||||
* fixes still describe clear movement. The delayed renderer already derives a
|
||||
* matching segment speed and course from those fixes, so tracking and cockpit
|
||||
* consumers should prefer that pair over stale poll fields.
|
||||
*
|
||||
* A host-supplied placement's speed (`derivedFromPlacement`) is how fast the
|
||||
* marker is drawn, not how fast the aircraft goes: a placement waiting for its
|
||||
* fixes to catch up stands still at 0. The reported ground speed is shown
|
||||
* then, and the placement's only when nothing is reported.
|
||||
*/
|
||||
export function displayedKinematics({
|
||||
derivedSpeedMps,
|
||||
derivedTrackDeg,
|
||||
reportedSpeedMps,
|
||||
reportedTrackDeg,
|
||||
derivedFromPlacement = false,
|
||||
} = {}) {
|
||||
const reported = Number.isFinite(reportedSpeedMps);
|
||||
return {
|
||||
speedMps: Number.isFinite(derivedSpeedMps)
|
||||
? Math.max(0, derivedSpeedMps)
|
||||
: Number.isFinite(reportedSpeedMps)
|
||||
? Math.max(0, reportedSpeedMps)
|
||||
: null,
|
||||
speedMps:
|
||||
Number.isFinite(derivedSpeedMps) && !(derivedFromPlacement && reported)
|
||||
? Math.max(0, derivedSpeedMps)
|
||||
: reported
|
||||
? Math.max(0, reportedSpeedMps)
|
||||
: null,
|
||||
trackDeg: Number.isFinite(derivedTrackDeg)
|
||||
? derivedTrackDeg
|
||||
: Number.isFinite(reportedTrackDeg)
|
||||
|
||||
@@ -43,6 +43,13 @@ test('displayedKinematics preserves a derived stop and falls back when unavailab
|
||||
}), { speedMps: 80, trackDeg: 180 });
|
||||
});
|
||||
|
||||
test('displayedKinematics shows the reported speed over a placement standing still', () => {
|
||||
const placed = { derivedSpeedMps: 0, derivedTrackDeg: 90, derivedFromPlacement: true };
|
||||
assert.deepEqual(displayedKinematics({ ...placed, reportedSpeedMps: 230, reportedTrackDeg: 88 }),
|
||||
{ speedMps: 230, trackDeg: 90 });
|
||||
assert.deepEqual(displayedKinematics(placed), { speedMps: 0, trackDeg: 90 });
|
||||
});
|
||||
|
||||
test('stale coasting follows last source contact without allowing indefinite drift', () => {
|
||||
const fix = 1_000_000;
|
||||
assert.equal(staleCoastLimitSeconds({ fixEpochMs: fix }), 60);
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
// Turn-by-turn steps for a route, as Core's own /api/route serves them with
|
||||
// steps=1; a hosted route proxy projects the same OSRM answer.
|
||||
export { normalizeOsrmSteps } from './routeSteps.js';
|
||||
|
||||
function placeContextPriority(types) {
|
||||
const typeSet = new Set(types);
|
||||
if (typeSet.has('historical_landmark') || typeSet.has('monument')) return 100;
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
/**
|
||||
* @module rotorFrames
|
||||
* @description Which rotor frame a helicopter icon shows at a time
|
||||
* (`aircraftIcon('helicopter', px, frame)`). The frames step at
|
||||
* {@link ROTOR_FPS}; each contact starts at its own phase, taken from its
|
||||
* id, so helicopters flying together do not change frame in step. The
|
||||
* rotor turns as the 3D model's does (`enginesTurn`): airborne, or on the
|
||||
* ground moving faster than 1 m/s; otherwise it holds the still frame.
|
||||
*/
|
||||
|
||||
import { ROTOR_FRAMES, ROTOR_STILL_FRAME } from './aircraftIcons.js';
|
||||
import { enginesTurn } from './modelPartDrivers.js';
|
||||
|
||||
export { ROTOR_FRAMES, ROTOR_STILL_FRAME };
|
||||
|
||||
/** Rotor frames shown per second. */
|
||||
export const ROTOR_FPS = 10;
|
||||
|
||||
/** Phase by id: hashing each id once, as many as the helicopters seen. */
|
||||
const phases = new Map();
|
||||
const PHASES_MAX = 4096;
|
||||
|
||||
/**
|
||||
* A contact's phase, 0 (inclusive) to 1, the same for the same id every
|
||||
* time (FNV-1a over its characters, mixed).
|
||||
* @param {string} id
|
||||
* @returns {number}
|
||||
*/
|
||||
export function rotorPhase(id) {
|
||||
const key = String(id ?? '');
|
||||
let phase = phases.get(key);
|
||||
if (phase !== undefined) return phase;
|
||||
let hash = 0x811c9dc5;
|
||||
for (let i = 0; i < key.length; i++) {
|
||||
hash ^= key.charCodeAt(i);
|
||||
hash = Math.imul(hash, 0x01000193);
|
||||
}
|
||||
// Mixed (MurmurHash3's finaliser), so ids differing in their last
|
||||
// characters, as ICAO addresses do, spread over the whole range.
|
||||
hash ^= hash >>> 16;
|
||||
hash = Math.imul(hash, 0x85ebca6b);
|
||||
hash ^= hash >>> 13;
|
||||
hash = Math.imul(hash, 0xc2b2ae35);
|
||||
hash ^= hash >>> 16;
|
||||
phase = (hash >>> 0) / 0x100000000;
|
||||
if (phases.size >= PHASES_MAX) phases.clear();
|
||||
phases.set(key, phase);
|
||||
return phase;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a helicopter's rotor turns: airborne, or taxiing (`enginesTurn`).
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} [state]
|
||||
* @returns {boolean}
|
||||
*/
|
||||
export function rotorTurns({ onGround = false, speedMps = null } = {}) {
|
||||
return enginesTurn({ onGround, speedMps });
|
||||
}
|
||||
|
||||
/**
|
||||
* The rotor frame a helicopter shows at `nowMs`: the still frame while its
|
||||
* rotor does not turn ({@link rotorTurns}), else stepping through the frames
|
||||
* at `ROTOR_FPS` from its phase.
|
||||
* @param {string} id
|
||||
* @param {number} nowMs Epoch ms (any steady clock).
|
||||
* @param {{onGround?: boolean, speedMps?: number|null}} [state] Ground speed in m/s.
|
||||
* @returns {number} 0 to `ROTOR_FRAMES - 1`.
|
||||
*/
|
||||
export function rotorFrame(id, nowMs, state = {}) {
|
||||
if (!rotorTurns(state) || !Number.isFinite(nowMs)) return ROTOR_STILL_FRAME;
|
||||
const step = Math.floor(
|
||||
(nowMs / 1000) * ROTOR_FPS + rotorPhase(id) * ROTOR_FRAMES,
|
||||
);
|
||||
return ((step % ROTOR_FRAMES) + ROTOR_FRAMES) % ROTOR_FRAMES;
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aircraftPartState } from './modelPartDrivers.js';
|
||||
import { partTableOf } from '../render/modelParts.js';
|
||||
import {
|
||||
ROTOR_FPS,
|
||||
ROTOR_FRAMES,
|
||||
ROTOR_STILL_FRAME,
|
||||
rotorFrame,
|
||||
rotorPhase,
|
||||
rotorTurns,
|
||||
} from './rotorFrames.js';
|
||||
import { aircraftIcon } from './aircraftIcons.js';
|
||||
|
||||
const svg = (uri) =>
|
||||
Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8');
|
||||
|
||||
test('the helicopter has three rotor frames, each its own image', () => {
|
||||
assert.equal(ROTOR_FRAMES, 3);
|
||||
const frames = [0, 1, 2].map((frame) =>
|
||||
aircraftIcon('helicopter', 64, frame),
|
||||
);
|
||||
assert.equal(new Set(frames).size, 3);
|
||||
// Frames 30° apart on a four-blade rotor: the third steps back onto the
|
||||
// first, a seamless loop.
|
||||
assert.match(svg(frames[0]), /rotate\(15 0 -11\.2\)/);
|
||||
assert.match(svg(frames[1]), /rotate\(45 0 -11\.2\)/);
|
||||
assert.match(svg(frames[2]), /rotate\(75 0 -11\.2\)/);
|
||||
// No frame, or one out of range, is the still frame.
|
||||
assert.equal(aircraftIcon('helicopter', 64), frames[ROTOR_STILL_FRAME]);
|
||||
assert.equal(aircraftIcon('helicopter', 64, 7), frames[ROTOR_STILL_FRAME]);
|
||||
// Other kinds have one image whatever the frame.
|
||||
assert.equal(aircraftIcon('airliner', 64, 2), aircraftIcon('airliner', 64));
|
||||
});
|
||||
|
||||
test('frames step at the rotor rate through every frame in order', () => {
|
||||
const id = 'abc123';
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
const start = 1_700_000_000_000;
|
||||
const seen = [];
|
||||
for (let i = 0; i < 9; i++) seen.push(rotorFrame(id, start + i * stepMs + 1));
|
||||
for (let i = 1; i < seen.length; i++)
|
||||
assert.equal(seen[i], (seen[i - 1] + 1) % ROTOR_FRAMES, seen.join(','));
|
||||
// Within one step it holds.
|
||||
const at = start + 5 * stepMs + 1;
|
||||
const held = rotorFrame(id, at);
|
||||
for (let ms = 0; ms < stepMs; ms += 10) {
|
||||
const frame = rotorFrame(id, at + ms);
|
||||
assert.ok(frame === held || frame === (held + 1) % ROTOR_FRAMES);
|
||||
}
|
||||
});
|
||||
|
||||
test('each contact has its own phase, so a group does not change in step', () => {
|
||||
assert.equal(rotorPhase('abc123'), rotorPhase('abc123'));
|
||||
const ids = Array.from(
|
||||
{ length: 24 },
|
||||
(_, i) => `a${i.toString(16).padStart(5, '0')}`,
|
||||
);
|
||||
const phases = ids.map(rotorPhase);
|
||||
for (const phase of phases) assert.ok(phase >= 0 && phase < 1);
|
||||
assert.ok(new Set(phases).size > 20, 'phases differ by contact');
|
||||
// At one instant the group shows every frame, not one.
|
||||
const at = 1_700_000_000_000;
|
||||
const frames = new Set(ids.map((id) => rotorFrame(id, at)));
|
||||
assert.equal(frames.size, ROTOR_FRAMES);
|
||||
});
|
||||
|
||||
test('the rotor sprite turns exactly when the model’s rotor does: in the air, or taxiing', () => {
|
||||
const table = partTableOf({
|
||||
parts: [
|
||||
{ name: 'body', kind: 'body' },
|
||||
{ name: 'rotor_main', kind: 'spin', axis: [0, 1, 0] },
|
||||
],
|
||||
});
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
for (const state of [
|
||||
{ onGround: false },
|
||||
{ onGround: true, speedMps: 0 },
|
||||
{ onGround: true, speedMps: 1 },
|
||||
{ onGround: true, speedMps: 3 },
|
||||
{ onGround: true, speedMps: null },
|
||||
]) {
|
||||
const modelSpins = aircraftPartState(table, state)?.spin?.rotor_main > 0;
|
||||
assert.equal(rotorTurns(state), modelSpins, JSON.stringify(state));
|
||||
const frames = new Set(
|
||||
[0, 1, 2, 3].map((i) =>
|
||||
rotorFrame('abc123', 1_700_000_000_000 + i * stepMs + 1, state),
|
||||
),
|
||||
);
|
||||
assert.equal(frames.size, modelSpins ? ROTOR_FRAMES : 1);
|
||||
}
|
||||
});
|
||||
|
||||
test('a helicopter on the ground holds the still frame', () => {
|
||||
const stepMs = 1000 / ROTOR_FPS;
|
||||
for (let i = 0; i < 6; i++)
|
||||
assert.equal(
|
||||
rotorFrame('abc123', 1_700_000_000_000 + i * stepMs, { onGround: true }),
|
||||
ROTOR_STILL_FRAME,
|
||||
);
|
||||
assert.equal(rotorFrame('abc123', Number.NaN), ROTOR_STILL_FRAME);
|
||||
});
|
||||
@@ -38,6 +38,29 @@ function courseBetween(from, to) {
|
||||
return (toDegrees(Math.atan2(y, x)) + 360) % 360;
|
||||
}
|
||||
|
||||
/**
|
||||
* Where in `fixes` (in time order) the fixes to make begin: the last at or
|
||||
* before the newest a contact holds, so the held run goes on into the new
|
||||
* one and its seam is made again from the new run (its course heads where
|
||||
* the new run goes, at the new record's height), and those after it. 0
|
||||
* unless `history` is its own fixes around a time (`timeline` entries) and
|
||||
* `fixes` starts at or before the newest of them and reaches it.
|
||||
* @param {object[]|undefined} history
|
||||
* @param {Array<{atMs: number}>} fixes
|
||||
* @returns {number}
|
||||
*/
|
||||
function heldThrough(history, fixes) {
|
||||
const newest = history?.[history.length - 1];
|
||||
if (!newest || history[0].timeline !== true || newest.timeline !== true)
|
||||
return 0;
|
||||
const heldMs = newest.epochMs;
|
||||
if (!(fixes[0].atMs <= heldMs && fixes[fixes.length - 1].atMs >= heldMs))
|
||||
return 0;
|
||||
let index = 0;
|
||||
while (index < fixes.length && fixes[index].atMs <= heldMs) index++;
|
||||
return index - 1;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -65,7 +88,12 @@ export function mergeAircraftTimelineFixes(
|
||||
const baroM = Number.isFinite(observation.baroAltitudeM)
|
||||
? observation.baroAltitudeM
|
||||
: null;
|
||||
const entries = fixes.map((fix, index) => {
|
||||
// Playing on, the next snapshot's fixes mostly repeat those held: when its
|
||||
// run reaches back into the held fixes, those stay as they are and only
|
||||
// the seam and the fixes past it are made and added.
|
||||
const from = heldThrough(history, fixes);
|
||||
const entries = fixes.slice(from).map((fix, offset) => {
|
||||
const index = from + offset;
|
||||
const course =
|
||||
index + 1 < fixes.length
|
||||
? courseBetween(fix, fixes[index + 1])
|
||||
|
||||
@@ -145,3 +145,85 @@ test("a tracked trail takes the fixes after its newest point, up to the snapshot
|
||||
);
|
||||
assert.equal(historyAfterTrail(history, [], 120_000).length, 3);
|
||||
});
|
||||
|
||||
test('playing on, the fixes a contact holds stay as they are and only the seam and newer ones are made', () => {
|
||||
const held = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 1), fix(120_000, 2)] },
|
||||
META,
|
||||
100,
|
||||
60_000,
|
||||
);
|
||||
const kept = held.map((entry) => entry);
|
||||
// The next snapshot's run reaches back into the held fixes, a little
|
||||
// differently picked: those held stay, the newer are added after them.
|
||||
const next = mergeAircraftTimelineFixes(
|
||||
held,
|
||||
{
|
||||
fixes: [
|
||||
fix(30_000, 0.6),
|
||||
fix(90_000, 1.6),
|
||||
fix(120_000, 2.1),
|
||||
fix(180_000, 3),
|
||||
fix(240_000, 4),
|
||||
],
|
||||
},
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
next.map((entry) => entry.epochMs),
|
||||
[0, 60_000, 120_000, 180_000, 240_000],
|
||||
);
|
||||
for (const [k, entry] of kept.slice(0, -1).entries())
|
||||
assert.equal(next[k], entry, 'a held entry is kept, not made again');
|
||||
// The seam is made again from the new run: its course heads where the
|
||||
// new run goes, so the course and height do not step there.
|
||||
assert.notEqual(next[2], kept[2]);
|
||||
const lat = (entry) =>
|
||||
Cesium.Math.toDegrees(
|
||||
Cesium.Cartographic.fromCartesian(entry.position).latitude,
|
||||
);
|
||||
assert.ok(Math.abs(lat(next[2]) - 2.1) < 1e-9);
|
||||
assert.ok(Math.abs(lat(next[3]) - 3) < 1e-9);
|
||||
// Each new fix heads where the track goes next, read from the new run.
|
||||
assert.ok(
|
||||
Math.abs(next[3].track) < 1e-6 || Math.abs(next[3].track - 360) < 1e-6,
|
||||
);
|
||||
});
|
||||
|
||||
test('a run that starts after the held fixes, or a history not of its own fixes, is merged whole', () => {
|
||||
const held = mergeAircraftTimelineFixes(
|
||||
[],
|
||||
{ fixes: [fix(0, 0), fix(60_000, 1)] },
|
||||
META,
|
||||
100,
|
||||
0,
|
||||
);
|
||||
const later = mergeAircraftTimelineFixes(
|
||||
held,
|
||||
{ fixes: [fix(120_000, 2), fix(180_000, 3)] },
|
||||
META,
|
||||
100,
|
||||
120_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
later.map((entry) => entry.epochMs),
|
||||
[0, 60_000, 120_000, 180_000],
|
||||
);
|
||||
// A run reaching back over the held fixes replaces them, as before, when
|
||||
// the history holds a live report.
|
||||
const report = { ...held[1], timeline: undefined };
|
||||
const mixed = mergeAircraftTimelineFixes(
|
||||
[held[0], report],
|
||||
{ fixes: [fix(30_000, 0.5), fix(90_000, 1.5)] },
|
||||
META,
|
||||
100,
|
||||
60_000,
|
||||
);
|
||||
assert.deepEqual(
|
||||
mixed.map((entry) => entry.epochMs),
|
||||
[0, 30_000, 90_000],
|
||||
);
|
||||
});
|
||||
@@ -28,6 +28,33 @@ const sameColor = (a, b) =>
|
||||
a.length === b.length &&
|
||||
a.every((value, i) => value === b[i]));
|
||||
|
||||
/** `trackedIconColor`'s answers, by base colour then alpha. */
|
||||
const tintsAtAlpha = new Map();
|
||||
|
||||
/**
|
||||
* The tracked icon's colour: the contact's own colour (the one its fleet
|
||||
* icon draws in), at `alpha`. Tracking never recolours a contact; only the
|
||||
* alpha changes (faded while stale, clear while its model draws it). One
|
||||
* frozen array per colour and alpha, so a frame allocates nothing.
|
||||
* @param {ArrayLike<number>} color The contact's RGBA colour, 0..1.
|
||||
* @param {number} alpha
|
||||
* @returns {readonly number[]}
|
||||
*/
|
||||
export function trackedIconColor(color, alpha) {
|
||||
if (color[3] === alpha && Object.isFrozen(color)) return color;
|
||||
let byAlpha = tintsAtAlpha.get(color);
|
||||
if (!byAlpha) {
|
||||
byAlpha = new Map();
|
||||
tintsAtAlpha.set(color, byAlpha);
|
||||
}
|
||||
let tint = byAlpha.get(alpha);
|
||||
if (!tint) {
|
||||
tint = Object.freeze([color[0], color[1], color[2], alpha]);
|
||||
byAlpha.set(alpha, tint);
|
||||
}
|
||||
return tint;
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether `setId` names another layer's tracked icon set: a layer must not
|
||||
* take a pick of that icon for one of its own contacts.
|
||||
|
||||
@@ -5,6 +5,7 @@ import {
|
||||
createTrackedAircraftIcon,
|
||||
isOtherTrackedIconSet,
|
||||
trackedContactHolder,
|
||||
trackedIconColor,
|
||||
} from './trackedAircraftIcon.js';
|
||||
|
||||
/** A viewer double with a fake draw port and a frame port whose preRender the test runs. */
|
||||
@@ -188,3 +189,13 @@ test("a layer tells another layer's tracked icon set from its own sets", () => {
|
||||
);
|
||||
assert.equal(isOtherTrackedIconSet(undefined, 'military'), false);
|
||||
});
|
||||
|
||||
test('the tracked icon keeps its contact\'s colour; only the alpha changes', () => {
|
||||
const amber = Object.freeze([1, 0.72, 0, 1]);
|
||||
assert.equal(trackedIconColor(amber, 1), amber, 'unchanged at its own alpha');
|
||||
const stale = trackedIconColor(amber, 0.45);
|
||||
assert.deepEqual(stale, [1, 0.72, 0, 0.45]);
|
||||
assert.equal(trackedIconColor(amber, 0.45), stale, 'one array per alpha');
|
||||
assert.ok(Object.isFrozen(stale));
|
||||
assert.deepEqual(trackedIconColor(amber, 0), [1, 0.72, 0, 0]);
|
||||
});
|
||||
@@ -1176,11 +1176,10 @@ for (const fixture of LAYERS) {
|
||||
|
||||
viewer.draw.ready(modelSet(fixture, viewer, 'tracked').spec.id, ICAO);
|
||||
fixture.driveTrackedModel();
|
||||
assert.equal(
|
||||
fixture.ensureFleetModel(ICAO),
|
||||
null,
|
||||
'once the tracked model draws, the fleet model lets go',
|
||||
);
|
||||
const kept = fixture.ensureFleetModel(ICAO);
|
||||
assert.ok(kept, 'once the tracked model draws, the fleet model is kept');
|
||||
assert.equal(kept.ready, true, 'loaded');
|
||||
assert.equal(kept.show, false, 'but hidden: one model draws the contact');
|
||||
assert.equal(
|
||||
fixture.trackedBillboardColor()[3],
|
||||
0,
|
||||
@@ -1192,6 +1191,99 @@ for (const fixture of LAYERS) {
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: deselecting hands the contact straight back to its loaded fleet model, with no icon flash`, () => {
|
||||
clearTr3bRegistry();
|
||||
try {
|
||||
fixture.layer.setParams({ models3d: true });
|
||||
const viewer = viewerAtHeight(30_000);
|
||||
const position = Cesium.Cartesian3.fromDegrees(-97.71, 30.21, 10_668);
|
||||
const icon = fixture.seed({
|
||||
viewer,
|
||||
models: [
|
||||
[
|
||||
ICAO,
|
||||
{
|
||||
ready: true,
|
||||
show: true,
|
||||
modelMatrix: Cesium.Matrix4.fromTranslation(position),
|
||||
},
|
||||
],
|
||||
],
|
||||
trackedModelEligible: null,
|
||||
});
|
||||
fixture.driveTrackedModel();
|
||||
viewer.draw.ready(modelSet(fixture, viewer, 'tracked').spec.id, ICAO);
|
||||
fixture.driveTrackedModel();
|
||||
assert.equal(
|
||||
fixture.trackedModel().ready,
|
||||
true,
|
||||
'the tracked model draws',
|
||||
);
|
||||
icon.show = false; // as selecting it hides it
|
||||
|
||||
fixture.layer.stopTracking();
|
||||
const fleetItem = modelSet(fixture, viewer, 'fleet').items.get(ICAO);
|
||||
assert.equal(
|
||||
fleetItem?.show,
|
||||
true,
|
||||
'the kept fleet model draws the contact in the same frame',
|
||||
);
|
||||
assert.equal(icon.show, false, 'and its icon never shows');
|
||||
assert.equal(
|
||||
modelSet(fixture, viewer, 'tracked').items.has(ICAO),
|
||||
false,
|
||||
'the tracked model is gone',
|
||||
);
|
||||
} finally {
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: deselecting shows the icon only when no fleet model is loaded`, () => {
|
||||
clearTr3bRegistry();
|
||||
try {
|
||||
fixture.layer.setParams({ models3d: true });
|
||||
const viewer = viewerAtHeight(30_000);
|
||||
// Selected as an icon: no fleet model at all.
|
||||
let icon = fixture.seed({
|
||||
viewer,
|
||||
models: [],
|
||||
trackedModelEligible: null,
|
||||
});
|
||||
fixture.layer.stopTracking();
|
||||
assert.equal(icon.show, true, 'no fleet model: the icon');
|
||||
|
||||
// A fleet model still loading when it is deselected.
|
||||
icon = fixture.seed({
|
||||
viewer,
|
||||
models: [[ICAO, { ready: false, show: false }]],
|
||||
trackedModelEligible: null,
|
||||
});
|
||||
fixture.layer.stopTracking();
|
||||
assert.equal(icon.show, true, 'a fleet model not loaded yet: the icon');
|
||||
assert.notEqual(
|
||||
modelSet(fixture, viewer, 'fleet').items.get(ICAO)?.show,
|
||||
true,
|
||||
'and the model stays hidden until it loads',
|
||||
);
|
||||
|
||||
// 3D turned off meanwhile: the icon, and the fleet model goes.
|
||||
icon = fixture.seed({
|
||||
viewer,
|
||||
models: [[ICAO, { ready: true, show: false }]],
|
||||
trackedModelEligible: null,
|
||||
});
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
fixture.layer.stopTracking();
|
||||
assert.equal(icon.show, true, '3D off: the icon');
|
||||
assert.equal(fixture.ensureFleetModel(ICAO), null, 'no fleet model kept');
|
||||
} finally {
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
fixture.layer.stopTracking();
|
||||
}
|
||||
});
|
||||
|
||||
test(`${fixture.name}: the tracked model draws at the fleet's scale and minimum pixel size, even up close`, () => {
|
||||
clearTr3bRegistry();
|
||||
try {
|
||||
@@ -1229,10 +1321,11 @@ for (const fixture of LAYERS) {
|
||||
fleetItem.minPixelSize,
|
||||
'the same minimum pixel size',
|
||||
);
|
||||
assert.notDeepEqual(
|
||||
trackedItem.tint,
|
||||
fleetItem.tint,
|
||||
'only the colour differs',
|
||||
assert.deepEqual(trackedItem.tint, fleetItem.tint, 'the same colour');
|
||||
assert.deepEqual(
|
||||
trackedItem.colorBlend,
|
||||
fleetItem.colorBlend,
|
||||
'the same colour blend',
|
||||
);
|
||||
} finally {
|
||||
fixture.layer.setParams({ models3d: false });
|
||||
@@ -1263,6 +1356,7 @@ for (const fixture of LAYERS) {
|
||||
fleet.scaleByDistance,
|
||||
'the same scale by distance',
|
||||
);
|
||||
assert.deepEqual(tracked.color, fleet.color, 'the same colour');
|
||||
// A landing changes the fleet icon's scale, and the tracked one's with it.
|
||||
fixture.seed({ viewer, onGround: true });
|
||||
const grounded = fixture.trackedIconLook(ICAO);
|
||||
|
||||
@@ -293,6 +293,68 @@ export function trailHeadCurvePoints(fixes, count, displayMs) {
|
||||
return curvePoints(curve, last.timeMs, displayMs);
|
||||
}
|
||||
|
||||
/** @constant {number} How far back from the newest report `trailTimeAt` looks for the aircraft (ms). */
|
||||
export const TRAIL_TIME_AT_SEARCH_MS = 15 * 60_000;
|
||||
|
||||
/**
|
||||
* The time on the trail at which `position` lies: the pair of consecutive
|
||||
* reports, one path, whose straight line passes closest to it (the newest
|
||||
* pair when two are as close), and the time that far along between them.
|
||||
* Past the newest report the time runs on at that pair's pace; before the
|
||||
* oldest pair it runs back the same way. Only pairs ending within
|
||||
* TRAIL_TIME_AT_SEARCH_MS of the newest report are looked at, so a loop
|
||||
* flown earlier is not mistaken for where the aircraft is now.
|
||||
*
|
||||
* This is how the trail finds the time an aircraft placed by someone else
|
||||
* (a host-supplied placement) is drawn at: whatever delay that placement
|
||||
* draws with, the trail then ends where the aircraft is drawn.
|
||||
* @param {object[]} fixes - The trail, chronological.
|
||||
* @param {{x: number, y: number, z: number}|null|undefined} position - Where the aircraft is drawn.
|
||||
* @returns {number} Epoch ms; NaN when no pair of reports is one path.
|
||||
*/
|
||||
export function trailTimeAt(fixes, position) {
|
||||
if (!position || fixes.length < 2) return NaN;
|
||||
const newestMs = fixes[fixes.length - 1].timeMs;
|
||||
let bestM = Infinity;
|
||||
let bestMs = NaN;
|
||||
for (let i = fixes.length - 1; i > 0; i--) {
|
||||
const b = fixes[i];
|
||||
if (newestMs - b.timeMs > TRAIL_TIME_AT_SEARCH_MS) break;
|
||||
const a = fixes[i - 1];
|
||||
if (!a.position || !b.position || b.breakBefore) continue;
|
||||
const spanMs = b.timeMs - a.timeMs;
|
||||
if (!(spanMs > 0)) continue;
|
||||
const dx = b.position.x - a.position.x;
|
||||
const dy = b.position.y - a.position.y;
|
||||
const dz = b.position.z - a.position.z;
|
||||
const lengthSq = dx * dx + dy * dy + dz * dz;
|
||||
let u =
|
||||
lengthSq > 0
|
||||
? ((position.x - a.position.x) * dx +
|
||||
(position.y - a.position.y) * dy +
|
||||
(position.z - a.position.z) * dz) /
|
||||
lengthSq
|
||||
: 0;
|
||||
// Only the newest pair runs on past its end, only the oldest looked at
|
||||
// back past its start; the rest are their own segment.
|
||||
const newest = i === fixes.length - 1;
|
||||
const oldest =
|
||||
i === 1 || newestMs - fixes[i - 1].timeMs > TRAIL_TIME_AT_SEARCH_MS;
|
||||
const along = Math.min(Math.max(u, 0), 1);
|
||||
const offM = Math.hypot(
|
||||
position.x - (a.position.x + along * dx),
|
||||
position.y - (a.position.y + along * dy),
|
||||
position.z - (a.position.z + along * dz),
|
||||
);
|
||||
if (!(offM < bestM)) continue;
|
||||
if (!(u > 1 && newest)) u = Math.min(u, 1);
|
||||
if (!(u < 0 && oldest)) u = Math.max(u, 0);
|
||||
bestM = offM;
|
||||
bestMs = a.timeMs + u * spanMs;
|
||||
}
|
||||
return bestMs;
|
||||
}
|
||||
|
||||
/**
|
||||
* Draw body segments. A trail without breaks support draws only the newest
|
||||
* segment, never a line across a break.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
/**
|
||||
* @module units
|
||||
* @description Unit conversions the layers share.
|
||||
*/
|
||||
|
||||
/** Metres a second in one knot (one nautical mile, 1852 m, an hour). */
|
||||
export const KNOT_MPS = 1852 / 3600;
|
||||
+15
-37
@@ -5,7 +5,11 @@
|
||||
*/
|
||||
|
||||
import { t, msg } from '../i18n/index.js';
|
||||
import { normalizeVesselType } from './vesselTypes.js';
|
||||
import {
|
||||
normalizeVesselType,
|
||||
vesselKind,
|
||||
VESSEL_KIND_STYLES,
|
||||
} from './vesselTypes.js';
|
||||
|
||||
export { normalizeVesselType };
|
||||
|
||||
@@ -22,32 +26,7 @@ export const VESSEL_CARD_FADE_DISTANCE_M = 5_000_000;
|
||||
export const VESSEL_CARD_FADE_START_RATIO = 0.7;
|
||||
|
||||
/**
|
||||
* AIS type family → chevron hue + card accent. Single source of truth for
|
||||
* vessel type colors so billboard chevrons and host cards cannot drift apart.
|
||||
*/
|
||||
const TYPE_STYLES = [
|
||||
{ pattern: /tanker/i, css: '#ffb347', accent: '255, 179, 71' },
|
||||
{
|
||||
pattern: /cargo|container|bulk|carrier/i,
|
||||
css: '#39d5ff',
|
||||
accent: '57, 213, 255',
|
||||
},
|
||||
{
|
||||
pattern: /passenger|ferry|cruise/i,
|
||||
css: '#ff7adf',
|
||||
accent: '255, 122, 223',
|
||||
},
|
||||
{ pattern: /fishing/i, css: '#7cff9b', accent: '124, 255, 155' },
|
||||
{
|
||||
pattern: /tug|tow|pilot|supply|service/i,
|
||||
css: '#f7f0a3',
|
||||
accent: '247, 240, 163',
|
||||
},
|
||||
];
|
||||
const DEFAULT_STYLE = { css: '#39d5ff', accent: '57, 213, 255' };
|
||||
|
||||
/**
|
||||
* An aid to navigation's disc and card accent: a bone white apart from every
|
||||
* An aid to navigation's buoy and card accent: a bone white apart from every
|
||||
* ship type's colour.
|
||||
*/
|
||||
export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
@@ -55,8 +34,8 @@ export const AID_TO_NAVIGATION_STYLE = Object.freeze({
|
||||
accent: '217, 210, 192',
|
||||
});
|
||||
|
||||
// Card text for the type tokens above. The tokens stay English: TYPE_STYLES
|
||||
// and tests match on them.
|
||||
// Card text for the type tokens above. The tokens stay English: the vessel
|
||||
// kinds (`vesselKind`) and tests match on them.
|
||||
const TYPE_DISPLAY_KEYS = Object.freeze({
|
||||
FISHING: msg('FISHING'),
|
||||
TOWING: msg('TOWING'),
|
||||
@@ -91,19 +70,18 @@ export function displayVesselType(type) {
|
||||
return key ? t(key) : normalized;
|
||||
}
|
||||
|
||||
/** AIS ship type → CSS hex hue for the billboard chevron. */
|
||||
/**
|
||||
* AIS ship type → CSS hex colour its sprite is tinted with. The sprite and
|
||||
* the card take it from the vessel's kind (`vesselKind`), so they cannot
|
||||
* drift apart.
|
||||
*/
|
||||
export function vesselTypeCss(type) {
|
||||
return styleForType(type).css;
|
||||
return VESSEL_KIND_STYLES[vesselKind(type)].css;
|
||||
}
|
||||
|
||||
/** AIS ship type → "r, g, b" accent string for the host card. */
|
||||
export function accentForVesselType(type) {
|
||||
return styleForType(type).accent;
|
||||
}
|
||||
|
||||
function styleForType(type) {
|
||||
const text = normalizeVesselType(type);
|
||||
return TYPE_STYLES.find((entry) => entry.pattern.test(text)) || DEFAULT_STYLE;
|
||||
return VESSEL_KIND_STYLES[vesselKind(type)].accent;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/**
|
||||
* @module vesselSprites
|
||||
* @description The map sprites of the vessel layer, as SVG data URIs: one hull
|
||||
* per vessel kind (`vesselKind` in vesselTypes.js), seen from above with its
|
||||
* bow up (north), and one buoy for every aid to navigation, standing upright.
|
||||
*
|
||||
* Every sprite is white with dark detail, drawn on the 96-unit frame of
|
||||
* aircraftIcons.js (centre 48,48). The layer tints it at draw time (the
|
||||
* kind's colour, white while selected), so one image serves every colour and
|
||||
* state, as the aircraft glyphs do: one icon-atlas slot per shape. Hulls
|
||||
* share one length and differ in shape only; widths are exaggerated so they
|
||||
* read at small sizes.
|
||||
*/
|
||||
|
||||
const VIEW = 96;
|
||||
const C = VIEW / 2;
|
||||
|
||||
/** Raster size of every vessel sprite (px): sharp at its largest drawn size. */
|
||||
export const VESSEL_SPRITE_PX = 64;
|
||||
|
||||
/** The hull edge: dark so a light tint still reads on light ground. */
|
||||
const EDGE =
|
||||
'stroke="rgba(4,18,24,0.9)" stroke-width="2.1" stroke-linejoin="round"';
|
||||
/** Superstructure and deck detail: dark, so tinting leaves it dark. */
|
||||
const DETAIL = 'fill="rgba(4,18,24,0.42)"';
|
||||
|
||||
/** Each kind's hull and detail, centred, bow toward −Y. */
|
||||
const HULLS = {
|
||||
// Container ship: fine bow, long parallel sides, square stern; container
|
||||
// rows forward and the bridge aft.
|
||||
cargo: `
|
||||
<path d="M0,-43 C -7,-41 -13,-36 -16.8,-28 L -16.8,37 L -14.7,43 L 14.7,43
|
||||
L 16.8,37 L 16.8,-28 C 13,-36 7,-41 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-13,-26 h26 v5 h-26 Z M-13,-19 h26 v5 h-26 Z M-13,-12 h26 v5 h-26 Z
|
||||
M-13,-5 h26 v5 h-26 Z M-13,2 h26 v5 h-26 Z M-13,9 h26 v5 h-26 Z
|
||||
M-13,16 h26 v5 h-26 Z M-16,26 h32 v4 h-32 Z" ${DETAIL}/>`,
|
||||
|
||||
// Tanker: full bow, a pipe run down the centre line with its manifold
|
||||
// across, the bridge aft.
|
||||
tanker: `
|
||||
<path d="M0,-43 C -8,-42 -15,-37 -17.9,-30 L -17.9,36 L -15.3,43 L 15.3,43
|
||||
L 17.9,36 L 17.9,-30 C 15,-37 8,-42 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-1.3,-34 h2.6 v62 h-2.6 Z M-14,-5.6 h28 v3.2 h-28 Z
|
||||
M-17.4,28.6 h34.8 v5.3 h-34.8 Z" ${DETAIL}/>`,
|
||||
|
||||
// Passenger ship or ferry: a superstructure covering nearly the whole deck.
|
||||
passenger: `
|
||||
<path d="M0,-43 C -6,-41.5 -12,-36 -15.3,-29.6 L -17.1,-28 L -17.1,30.5
|
||||
L -15.6,39 L -14.2,43 L 14.2,43 L 15.6,39 L 17.1,30.5 L 17.1,-28
|
||||
L 15.3,-29.6 C 12,-36 6,-41.5 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-14.6,-27 h29.2 v55 h-29.2 Z" ${DETAIL}/>
|
||||
<path d="M-2.5,6 h5 v8 h-5 Z" fill="white"/>`,
|
||||
|
||||
// High-speed craft: a catamaran, two slim bows and a square stern.
|
||||
highspeed: `
|
||||
<path d="M-17.9,-32.3 L -16.1,-33.1 L -14.7,-39.9 L -13.4,-43 L -12.1,-40.7
|
||||
L -9.9,-32.4 L 9.9,-32.4 L 12.1,-40.7 L 13.4,-43 L 14.7,-39.9
|
||||
L 16.1,-33.1 L 17.9,-32.3 L 17.9,43 L 9.3,43 L 8.3,42.2 L -8.3,42.2
|
||||
L -9.3,43 L -17.9,43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-9.7,-14.6 h19.4 v12.8 h-19.4 Z" ${DETAIL}/>`,
|
||||
|
||||
// Fishing vessel: a narrow hull, the wheelhouse forward and outrigger
|
||||
// booms across amidships.
|
||||
fishing: `
|
||||
<path d="M-24,2.3 h48 v3.2 h-48 Z" fill="white" ${EDGE}/>
|
||||
<path d="M0,-43 C -5,-40 -9.5,-31 -11.7,-24.8 L -13.1,-17.7 L -13.1,30.4
|
||||
L -11.1,41.1 L -9.9,43 L 9.9,43 L 11.1,41.1 L 13.1,30.4 L 13.1,-17.7
|
||||
L 11.7,-24.8 C 9.5,-31 5,-40 0,-43 Z" fill="white" ${EDGE}/>
|
||||
<path d="M-8.8,-20.4 h17.6 v12.1 h-17.6 Z" ${DETAIL}/>`,
|
||||
|
||||
// Tug, pilot or service boat: short, wide and blunt, the wheelhouse
|
||||
// amidships and two towing bitts aft.
|
||||
tug: `
|
||||
<path d="M-7,-43 L 7,-43 C 14,-40 20,-33 22.5,-22 L 24,-13 L 24,19
|
||||
C 24,28 21,36 17,42 L 16,43 L -16,43 L -17,42 C -21,36 -24,28
|
||||
-24,19 L -24,-13 L -22.5,-22 C -20,-33 -14,-40 -7,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-13.9,-12.9 h27.8 v12.3 h-27.8 Z M-12.4,4.8 h5 v4.3 h-5 Z
|
||||
M7.4,4.8 h5 v4.3 h-5 Z" ${DETAIL}/>`,
|
||||
|
||||
// Sailing boat: a rounded hull with its sail filled to one side.
|
||||
sailing: `
|
||||
<path d="M0,-43 C -6,-40 -12,-31 -15.5,-21 C -18,-13 -19.4,-5 -19.4,3
|
||||
L -19.3,34.2 L -17.1,39.8 L -14.3,43 L 14.3,43 L 17.1,39.8
|
||||
L 19.3,34.2 L 19.4,3 C 19.4,-5 18,-13 15.5,-21 C 12,-31 6,-40 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M0,-30 Q 21.6,-6 2,26 L -1,26 Q 7.8,-4 0,-30 Z" fill="white"
|
||||
stroke="rgba(4,18,24,0.9)" stroke-width="1.4" stroke-linejoin="round"/>
|
||||
<circle cx="0" cy="-12" r="2.6" fill="rgba(4,18,24,0.85)"/>`,
|
||||
|
||||
// Pleasure craft: a motor yacht, fine bow and a long cabin.
|
||||
pleasure: `
|
||||
<path d="M0,-43 C -5,-40 -11,-31 -15.9,-19.8 L -17.9,-12.6 L -17.9,32.7
|
||||
L -17.2,37.6 L -16.2,38.2 L -16.2,43 L 16.2,43 L 16.2,38.2
|
||||
L 17.2,37.6 L 17.9,32.7 L 17.9,-12.6 L 15.9,-19.8 C 11,-31 5,-40 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-15.2,-12.8 h30.4 v34.5 h-30.4 Z" ${DETAIL}/>`,
|
||||
|
||||
// Military, law enforcement or rescue: a patrol boat, sharp bow, a gun
|
||||
// forward of the bridge.
|
||||
military: `
|
||||
<path d="M0,-43 C -4,-41 -9.6,-32 -12.6,-25.2 L -14.8,-17.1 L -15.3,-11.7
|
||||
L -15.1,36.8 L -13.8,41.3 L -12.6,43 L 12.6,43 L 13.8,41.3
|
||||
L 15.3,36.8 L 15.3,-11.7 L 14.8,-17.1 L 12.6,-25.2 C 9.6,-32 4,-41 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-10.2,-13.4 h20.4 v10 h-20.4 Z M-4.2,9.6 h8.4 v6.5 h-8.4 Z" ${DETAIL}/>
|
||||
<circle cx="0" cy="-22" r="3.2" ${DETAIL}/>`,
|
||||
|
||||
// Any other vessel: a plain hull with a deckhouse aft.
|
||||
other: `
|
||||
<path d="M0,-43 C -6,-42 -12,-37 -14.8,-29.9 L -17.4,-23.3 L -17.9,-19.4
|
||||
L -17.9,35.6 L -16.9,39.3 L -14.9,43 L 14.9,43 L 16.9,39.3
|
||||
L 17.9,35.6 L 17.9,-19.4 L 17.4,-23.3 L 14.8,-29.9 C 12,-37 6,-42 0,-43 Z"
|
||||
fill="white" ${EDGE}/>
|
||||
<path d="M-10.8,8.3 h21.6 v13.1 h-21.6 Z" ${DETAIL}/>`,
|
||||
};
|
||||
|
||||
/**
|
||||
* The buoy every aid to navigation is drawn as, seen from the side: a
|
||||
* flared float with a dark waterline band, a tapering body, a lantern and a
|
||||
* round top-mark, centred on the frame. No halo; it is never turned.
|
||||
*/
|
||||
const BUOY = `
|
||||
<path d="M27.6,36.5 L 26.4,31.5 L 25.2,27.5 L 14.4,23.5 L 11.4,-7.5
|
||||
L 12.6,-7.5 L 12.6,-10.5 L 3.8,-10.5 L 2.9,-17.5 L -2.9,-17.5
|
||||
L -3.8,-10.5 L -12.6,-10.5 L -12.6,-7.5 L -11.4,-7.5 L -14.4,23.5
|
||||
L -25.2,27.5 L -26.4,31.5 L -27.6,36.5 Z" fill="white" ${EDGE}/>
|
||||
<path d="M26.4,31.5 L 27.6,36.5 L -27.6,36.5 L -26.4,31.5 Z
|
||||
M-12.6,-10.5 h25.2 v3 h-25.2 Z" fill="rgba(4,18,24,0.7)"/>
|
||||
<path d="M-1.9,-22 h3.8 v4.5 h-3.8 Z" fill="white" ${EDGE}/>
|
||||
<circle cx="0" cy="-30" r="7" fill="white" ${EDGE}/>`;
|
||||
|
||||
const cache = new Map();
|
||||
|
||||
const b64 = (s) =>
|
||||
typeof btoa === 'function'
|
||||
? btoa(s)
|
||||
: Buffer.from(s, 'utf8').toString('base64');
|
||||
|
||||
function sprite(key, body) {
|
||||
let uri = cache.get(key);
|
||||
if (!uri) {
|
||||
const px = VESSEL_SPRITE_PX;
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${px}" height="${px}" viewBox="0 0 ${VIEW} ${VIEW}"><g transform="translate(${C},${C})">${body}</g></svg>`;
|
||||
uri = 'data:image/svg+xml;base64,' + b64(svg);
|
||||
cache.set(key, uri);
|
||||
}
|
||||
return uri;
|
||||
}
|
||||
|
||||
/**
|
||||
* The hull sprite of a vessel kind (`other` for one it does not know).
|
||||
* @param {string} kind One of `VESSEL_KINDS`.
|
||||
* @returns {string} SVG data URI.
|
||||
*/
|
||||
export function vesselSprite(kind) {
|
||||
const k = HULLS[kind] ? kind : 'other';
|
||||
return sprite(k, HULLS[k]);
|
||||
}
|
||||
|
||||
/**
|
||||
* The buoy sprite of every aid to navigation.
|
||||
* @returns {string} SVG data URI.
|
||||
*/
|
||||
export function aidSprite() {
|
||||
return sprite('aid', BUOY);
|
||||
}
|
||||
@@ -0,0 +1,71 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { aidSprite, vesselSprite, VESSEL_SPRITE_PX } from './vesselSprites.js';
|
||||
import { VESSEL_KINDS, VESSEL_KIND_STYLES, vesselKind } from './vesselTypes.js';
|
||||
import { AID_TO_NAVIGATION_STYLE, accentForVesselType, vesselTypeCss } from './vesselLabels.js';
|
||||
|
||||
const svg = (uri) =>
|
||||
Buffer.from(uri.slice(uri.indexOf(',') + 1), 'base64').toString('utf8');
|
||||
|
||||
test('vessel types pick their kind by AIS code or text family', () => {
|
||||
const cases = {
|
||||
cargo: ['70', '79', 'Container Ship', 'Bulk Carrier', 'Ro-Ro Cargo'],
|
||||
tanker: ['80', '89', 'Crude Oil Tanker', 'LNG Carrier', 'LPG'],
|
||||
passenger: ['60', '69', 'Passenger/Ferry', 'Cruise Ship'],
|
||||
highspeed: ['40', '49', 'High-Speed Craft', 'HSC'],
|
||||
fishing: ['30', 'Fishing Vessel', 'Trawler'],
|
||||
tug: ['31', '32', '50', '52', '53', '54', 'Tug', 'Pilot Vessel', 'Supply'],
|
||||
sailing: ['36', 'Sailing Vessel'],
|
||||
pleasure: ['37', 'Pleasure Craft', 'Yacht'],
|
||||
military: ['35', '55', '51', 'Military', 'Law Enforcement', 'Coast Guard', 'SAR'],
|
||||
other: ['0', '20', '33', '34', '58', '90', 'Dredger', '', null, undefined, '255'],
|
||||
};
|
||||
for (const [kind, types] of Object.entries(cases))
|
||||
for (const type of types) assert.equal(vesselKind(type), kind, String(type));
|
||||
assert.deepEqual(new Set(Object.keys(cases)), new Set(VESSEL_KINDS));
|
||||
});
|
||||
|
||||
test('each vessel kind has its own white hull sprite, bow up', () => {
|
||||
const sprites = VESSEL_KINDS.map(vesselSprite);
|
||||
assert.equal(new Set(sprites).size, VESSEL_KINDS.length);
|
||||
for (const uri of sprites) {
|
||||
const text = svg(uri);
|
||||
assert.match(text, new RegExp(`width="${VESSEL_SPRITE_PX}"`));
|
||||
assert.match(text, /viewBox="0 0 96 96"/);
|
||||
// Drawn white for the tint; nothing baked in colour.
|
||||
assert.match(text, /fill="white"/);
|
||||
assert.doesNotMatch(text, /#[0-9a-f]{6}/i);
|
||||
}
|
||||
assert.equal(vesselSprite('unknown'), vesselSprite('other'));
|
||||
});
|
||||
|
||||
test('vessel colours: one per kind, the new kinds apart from the rest', () => {
|
||||
const css = VESSEL_KINDS.map((kind) => VESSEL_KIND_STYLES[kind].css);
|
||||
// Only cargo and other share the default cyan.
|
||||
assert.equal(new Set(css).size, VESSEL_KINDS.length - 1);
|
||||
assert.equal(VESSEL_KIND_STYLES.cargo.css, VESSEL_KIND_STYLES.other.css);
|
||||
for (const kind of ['sailing', 'pleasure', 'military', 'highspeed']) {
|
||||
const own = VESSEL_KIND_STYLES[kind].css;
|
||||
for (const other of VESSEL_KINDS)
|
||||
if (other !== kind) assert.notEqual(own, VESSEL_KIND_STYLES[other].css, `${kind} vs ${other}`);
|
||||
assert.notEqual(own, AID_TO_NAVIGATION_STYLE.css);
|
||||
}
|
||||
// The sprite tint and the card accent are the same colour.
|
||||
for (const [type, kind] of [['36', 'sailing'], ['37', 'pleasure'], ['55', 'military'], ['41', 'highspeed'], ['71', 'cargo']]) {
|
||||
const { css: hex, accent } = VESSEL_KIND_STYLES[kind];
|
||||
assert.equal(vesselTypeCss(type), hex);
|
||||
assert.equal(accentForVesselType(type), accent);
|
||||
const rgb = [1, 3, 5].map((i) => Number.parseInt(hex.slice(i, i + 2), 16)).join(', ');
|
||||
assert.equal(accent, rgb, kind);
|
||||
}
|
||||
});
|
||||
|
||||
test('an aid to navigation is the one buoy sprite, white with no halo', () => {
|
||||
const text = svg(aidSprite());
|
||||
assert.equal(aidSprite(), aidSprite());
|
||||
assert.ok(!VESSEL_KINDS.map(vesselSprite).includes(aidSprite()));
|
||||
assert.match(text, /fill="white"/);
|
||||
// No light halo stroke around it.
|
||||
assert.doesNotMatch(text, /rgba\(235,240,245/);
|
||||
assert.doesNotMatch(text, /#[0-9a-f]{6}/i);
|
||||
});
|
||||
@@ -46,6 +46,76 @@ export function normalizeVesselType(type) {
|
||||
return NUMERIC_TYPE_FAMILIES[Math.floor(code / 10)] || 'OTHER';
|
||||
}
|
||||
|
||||
/**
|
||||
* The vessel kinds a ship is drawn as, each with its own hull sprite and
|
||||
* colour (`vesselSprites.js`), by the type family its AIS type resolves to
|
||||
* ({@link normalizeVesselType}), in order: the first that matches.
|
||||
*/
|
||||
const VESSEL_KIND_RULES = [
|
||||
['tanker', /tanker|\blng\b|\blpg\b|gas carrier/i],
|
||||
['highspeed', /high[- ]?speed|\bhsc\b/i],
|
||||
['passenger', /passenger|ferry|cruise/i],
|
||||
['cargo', /cargo|container|bulk|carrier|freighter|ro-?ro/i],
|
||||
['fishing', /fishing|trawler/i],
|
||||
[
|
||||
'military',
|
||||
/military|naval|navy|warship|law enforce|police|patrol|coast ?guard|\bsar\b|search and rescue/i,
|
||||
],
|
||||
['tug', /tug|tow|pilot|tender|supply|service|anti-pollution/i],
|
||||
['sailing', /sail/i],
|
||||
['pleasure', /pleasure|yacht/i],
|
||||
];
|
||||
|
||||
/** Every vessel kind {@link vesselKind} names, `other` last. */
|
||||
export const VESSEL_KINDS = Object.freeze([
|
||||
...VESSEL_KIND_RULES.map(([kind]) => kind),
|
||||
'other',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Each vessel kind's colour on the map and on its card, as CSS and as the
|
||||
* card's "r, g, b" accent. Every one reads on dark water and differs from
|
||||
* the rest; cargo and other share the default cyan.
|
||||
*/
|
||||
export const VESSEL_KIND_STYLES = Object.freeze({
|
||||
cargo: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }),
|
||||
tanker: Object.freeze({ css: '#ffb347', accent: '255, 179, 71' }),
|
||||
passenger: Object.freeze({ css: '#ff7adf', accent: '255, 122, 223' }),
|
||||
highspeed: Object.freeze({ css: '#c6ff3d', accent: '198, 255, 61' }),
|
||||
fishing: Object.freeze({ css: '#7cff9b', accent: '124, 255, 155' }),
|
||||
tug: Object.freeze({ css: '#f7f0a3', accent: '247, 240, 163' }),
|
||||
sailing: Object.freeze({ css: '#b49cff', accent: '180, 156, 255' }),
|
||||
pleasure: Object.freeze({ css: '#ff6f61', accent: '255, 111, 97' }),
|
||||
military: Object.freeze({ css: '#a9bccb', accent: '169, 188, 203' }),
|
||||
other: Object.freeze({ css: '#39d5ff', accent: '57, 213, 255' }),
|
||||
});
|
||||
|
||||
/** Kind by type text: a feed uses few distinct type texts. */
|
||||
const KIND_MEMO = new Map();
|
||||
const KIND_MEMO_MAX = 1024;
|
||||
|
||||
/**
|
||||
* The kind of vessel an AIS type names, a numeric ship-type code (ITU-R
|
||||
* M.1371) or a text type: `cargo` (70 to 79), `tanker` (80 to 89),
|
||||
* `passenger` (60 to 69), `highspeed` (40 to 49), `fishing` (30), `tug`
|
||||
* (tugs, towing, pilots, tenders, anti-pollution: 31, 32, 50, 52 to 54),
|
||||
* `sailing` (36), `pleasure` (37), `military` (military, law enforcement,
|
||||
* search and rescue: 35, 55, 51) or `other` (anything else, unknown types
|
||||
* included).
|
||||
* @param {string|number|null|undefined} type
|
||||
* @returns {string} One of {@link VESSEL_KINDS}.
|
||||
*/
|
||||
export function vesselKind(type) {
|
||||
const text = normalizeVesselType(type);
|
||||
let kind = KIND_MEMO.get(text);
|
||||
if (kind !== undefined) return kind;
|
||||
kind = VESSEL_KIND_RULES.find(([, pattern]) => pattern.test(text))?.[0];
|
||||
kind ??= 'other';
|
||||
if (KIND_MEMO.size >= KIND_MEMO_MAX) KIND_MEMO.clear();
|
||||
KIND_MEMO.set(text, kind);
|
||||
return kind;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
|
||||
@@ -1145,6 +1145,10 @@
|
||||
"Fast jet": "نفاثة سريعة",
|
||||
"Business jet": "طائرة رجال أعمال",
|
||||
"Drone": "طائرة مسيّرة",
|
||||
"Airport vehicle": "مركبة مطار",
|
||||
"Ground station / obstacle": "محطة أرضية / عائق",
|
||||
"Airport vehicles": "مركبات المطار",
|
||||
"Ground stations / obstacles": "محطات أرضية / عوائق",
|
||||
"General emergency": "طوارئ عامة",
|
||||
"Unlawful interference": "تدخل غير مشروع",
|
||||
"Radio failure": "عطل في الاتصال اللاسلكي",
|
||||
@@ -2687,9 +2691,7 @@
|
||||
"Delete scene \"{scene}\" and all shots?": "حذف المشهد «{scene}» وكل لقطاته؟",
|
||||
"Stopped (Esc)": "متوقف (Esc)",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "لا لقطات بعد. استخدم «التقاط لقطة» لحفظ المنظر الحالي.",
|
||||
"Double-click to rename": "انقر نقرًا مزدوجًا لإعادة التسمية",
|
||||
"Shot name": "اسم اللقطة",
|
||||
"LOAD": "تحميل",
|
||||
"{duration}s + {hold}s": "{duration} ث + {hold} ث",
|
||||
"Choose files": "اختيار ملفات",
|
||||
"{count} files selected": {
|
||||
@@ -3446,7 +3448,6 @@
|
||||
"Add the current view, style and layers as the next shot": "إضافة العرض الحالي والنمط والطبقات كلقطة تالية",
|
||||
"+ CAPTURE SHOT": "+ التقاط لقطة",
|
||||
"Replace the selected shot with the current view": "استبدال اللقطة المحددة بالعرض الحالي",
|
||||
"Click a shot to select it, double-click to rename.": "انقر على لقطة لتحديدها، وانقر عليها نقرًا مزدوجًا لإعادة تسميتها.",
|
||||
"Play from this scene through the rest of the project": "تشغيل من هذا المشهد حتى نهاية المشروع",
|
||||
"Stop playback (Esc)": "إيقاف التشغيل (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "تشغيل اللقطة التي تلي المحددة، مع الانتقال إلى المشهد التالي عند الحاجة",
|
||||
@@ -4543,5 +4544,11 @@
|
||||
"KT": "عقدة",
|
||||
"Course to {code}: {course}": "المسار إلى {code}: {course}",
|
||||
"Over {place}": "فوق {place}",
|
||||
"Below": "في الأسفل"
|
||||
"Below": "في الأسفل",
|
||||
"Go to this shot. Double-click to rename.": "انتقل إلى هذه اللقطة. انقر نقرًا مزدوجًا لإعادة التسمية.",
|
||||
"Move up": "نقل لأعلى",
|
||||
"Move down": "نقل لأسفل",
|
||||
"Click a shot to go to it, double-click to rename.": "انقر على لقطة للانتقال إليها، وانقر عليها نقرًا مزدوجًا لإعادة تسميتها.",
|
||||
"Back to live at the starting view": "العودة إلى البث المباشر في العرض الأولي",
|
||||
"Exit cockpit to fly to a bike share city": "اخرج من قمرة القيادة للانتقال إلى مدينة بها مشاركة دراجات"
|
||||
}
|
||||
@@ -1080,6 +1080,10 @@
|
||||
"Fast jet": "Kampfjet",
|
||||
"Business jet": "Businessjet",
|
||||
"Drone": "Drohne",
|
||||
"Airport vehicle": "Flughafenfahrzeug",
|
||||
"Ground station / obstacle": "Bodenstation / Hindernis",
|
||||
"Airport vehicles": "Flughafenfahrzeuge",
|
||||
"Ground stations / obstacles": "Bodenstationen / Hindernisse",
|
||||
"General emergency": "Allgemeiner Notfall",
|
||||
"Unlawful interference": "Widerrechtlicher Eingriff",
|
||||
"Radio failure": "Funkausfall",
|
||||
@@ -2518,9 +2522,7 @@
|
||||
"Delete scene \"{scene}\" and all shots?": "Szene „{scene}“ und alle Aufnahmen löschen?",
|
||||
"Stopped (Esc)": "Gestoppt (Esc)",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Noch keine Aufnahmen. Mit AUFNAHME SPEICHERN die aktuelle Ansicht sichern.",
|
||||
"Double-click to rename": "Doppelklick zum Umbenennen",
|
||||
"Shot name": "Name der Aufnahme",
|
||||
"LOAD": "LADEN",
|
||||
"{duration}s + {hold}s": "{duration} s + {hold} s",
|
||||
"Choose files": "Dateien wählen",
|
||||
"{count} files selected": {
|
||||
@@ -3129,7 +3131,6 @@
|
||||
"+ CAPTURE SHOT": "+ AUFNAHME SPEICHERN",
|
||||
"Add the current view, style and layers as the next shot": "Aktuelle Ansicht, Stil und Ebenen als nächste Aufnahme hinzufügen",
|
||||
"Replace the selected shot with the current view": "Ausgewählte Aufnahme durch die aktuelle Ansicht ersetzen",
|
||||
"Click a shot to select it, double-click to rename.": "Aufnahme anklicken zum Auswählen, Doppelklick zum Umbenennen.",
|
||||
"Play from this scene through the rest of the project": "Ab dieser Szene bis zum Ende des Projekts abspielen",
|
||||
"Stop playback (Esc)": "Wiedergabe stoppen (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Aufnahme nach der ausgewählten abspielen, bei Bedarf in der nächsten Szene",
|
||||
@@ -4131,5 +4132,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Kurs nach {code}: {course}",
|
||||
"Over {place}": "Über {place}",
|
||||
"Below": "Darunter"
|
||||
"Below": "Darunter",
|
||||
"Go to this shot. Double-click to rename.": "Zu dieser Aufnahme wechseln. Doppelklick zum Umbenennen.",
|
||||
"Move up": "Nach oben verschieben",
|
||||
"Move down": "Nach unten verschieben",
|
||||
"Click a shot to go to it, double-click to rename.": "Aufnahme anklicken, um zu ihr zu wechseln, Doppelklick zum Umbenennen.",
|
||||
"Back to live at the starting view": "Zurück zu Live in der Startansicht",
|
||||
"Exit cockpit to fly to a bike share city": "Cockpit verlassen, um zu einer Stadt mit Bike-Sharing zu fliegen"
|
||||
}
|
||||
@@ -1784,9 +1784,7 @@
|
||||
"Export failed · {error}": "La exportación falló · {error}",
|
||||
"← → preview · A or B pins the focused day": "← → vista previa · A o B fija el día enfocado",
|
||||
"← → preview the other side · A or B pins it": "← → vista previa del otro lado · A o B lo fija",
|
||||
"LOAD": "CARGAR",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Aún no hay planos. Usa CAPTURAR PLANO para guardar el aspecto actual.",
|
||||
"Double-click to rename": "Doble clic para cambiar el nombre",
|
||||
"Shot name": "Nombre del plano",
|
||||
"RETRYING ALPR CAMERAS": "REINTENTANDO CÁMARAS ALPR",
|
||||
"FETCHING ALPR CAMERAS": "OBTENIENDO CÁMARAS ALPR",
|
||||
@@ -2863,6 +2861,10 @@
|
||||
"Fast jet": "Avión de alto rendimiento",
|
||||
"Business jet": "Reactor ejecutivo",
|
||||
"Drone": "Dron",
|
||||
"Airport vehicle": "Vehículo de aeropuerto",
|
||||
"Ground station / obstacle": "Estación terrestre / obstáculo",
|
||||
"Airport vehicles": "Vehículos de aeropuerto",
|
||||
"Ground stations / obstacles": "Estaciones terrestres / obstáculos",
|
||||
"fire cause|Human": "humana",
|
||||
"fire cause|Natural": "natural",
|
||||
"fire cause|Undetermined": "indeterminada",
|
||||
@@ -3231,7 +3233,6 @@
|
||||
"+ CAPTURE SHOT": "+ CAPTURAR PLANO",
|
||||
"Add the current view, style and layers as the next shot": "Añade la vista, el estilo y las capas actuales como el siguiente plano",
|
||||
"Replace the selected shot with the current view": "Sustituye el plano seleccionado por la vista actual",
|
||||
"Click a shot to select it, double-click to rename.": "Haz clic en un plano para seleccionarlo y doble clic para cambiarle el nombre.",
|
||||
"scene|PLAY": "REPRODUCIR",
|
||||
"Stop playback (Esc)": "Detén la reproducción (Esc)",
|
||||
"SAVE & SHARE": "GUARDAR Y COMPARTIR",
|
||||
@@ -4234,5 +4235,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Rumbo a {code}: {course}",
|
||||
"Over {place}": "Sobre {place}",
|
||||
"Below": "Debajo"
|
||||
"Below": "Debajo",
|
||||
"Go to this shot. Double-click to rename.": "Ir a este plano. Doble clic para cambiar el nombre.",
|
||||
"Move up": "Subir",
|
||||
"Move down": "Bajar",
|
||||
"Click a shot to go to it, double-click to rename.": "Haz clic en un plano para ir a él y doble clic para cambiarle el nombre.",
|
||||
"Back to live at the starting view": "Volver al directo en la vista inicial",
|
||||
"Exit cockpit to fly to a bike share city": "Sal de la cabina para volar a una ciudad con bicicletas compartidas"
|
||||
}
|
||||
@@ -143,6 +143,10 @@
|
||||
"Fast jet": "Avion de chasse",
|
||||
"Business jet": "Jet d'affaires",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Véhicule d'aéroport",
|
||||
"Ground station / obstacle": "Station au sol / obstacle",
|
||||
"Airport vehicles": "Véhicules d'aéroport",
|
||||
"Ground stations / obstacles": "Stations au sol / obstacles",
|
||||
"General emergency": "Urgence générale",
|
||||
"Unlawful interference": "Intervention illicite",
|
||||
"Radio failure": "Panne radio",
|
||||
@@ -2272,9 +2276,7 @@
|
||||
"SPARSE": "ÉPARS",
|
||||
"BALANCED": "ÉQUILIBRÉ",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Aucun plan pour l'instant. Utilisez CAPTURER UN PLAN pour enregistrer le rendu actuel.",
|
||||
"Double-click to rename": "Double-cliquez pour renommer",
|
||||
"Shot name": "Nom du plan",
|
||||
"LOAD": "CHARGER",
|
||||
"DEL": "SUPPR.",
|
||||
"{duration}s + {hold}s": "{duration} s + {hold} s",
|
||||
"Choose files": "Choisir des fichiers",
|
||||
@@ -3210,7 +3212,6 @@
|
||||
"+ CAPTURE SHOT": "+ CAPTURER UN PLAN",
|
||||
"Add the current view, style and layers as the next shot": "Ajouter la vue, le style et les couches actuels comme plan suivant",
|
||||
"Replace the selected shot with the current view": "Remplacer le plan sélectionné par la vue actuelle",
|
||||
"Click a shot to select it, double-click to rename.": "Cliquez sur un plan pour le sélectionner, double-cliquez pour le renommer.",
|
||||
"Play from this scene through the rest of the project": "Lire à partir de cette scène jusqu'à la fin du projet",
|
||||
"Stop playback (Esc)": "Arrêter la lecture (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Lire le plan qui suit la sélection, en passant à la scène suivante si besoin",
|
||||
@@ -4234,5 +4235,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Cap vers {code} : {course}",
|
||||
"Over {place}": "Au-dessus de {place}",
|
||||
"Below": "En dessous"
|
||||
"Below": "En dessous",
|
||||
"Go to this shot. Double-click to rename.": "Aller à ce plan. Double-cliquez pour renommer.",
|
||||
"Move up": "Monter",
|
||||
"Move down": "Descendre",
|
||||
"Click a shot to go to it, double-click to rename.": "Cliquez sur un plan pour y aller, double-cliquez pour le renommer.",
|
||||
"Back to live at the starting view": "Revenir au direct dans la vue de départ",
|
||||
"Exit cockpit to fly to a bike share city": "Quittez le cockpit pour aller vers une ville avec vélos en libre-service"
|
||||
}
|
||||
@@ -52,6 +52,10 @@
|
||||
"Fast jet": "מטוס סילון מהיר",
|
||||
"Business jet": "מטוס מנהלים",
|
||||
"Drone": "רחפן",
|
||||
"Airport vehicle": "רכב שדה תעופה",
|
||||
"Ground station / obstacle": "תחנה קרקעית / מכשול",
|
||||
"Airport vehicles": "רכבי שדה תעופה",
|
||||
"Ground stations / obstacles": "תחנות קרקעיות / מכשולים",
|
||||
"General emergency": "חירום כללי",
|
||||
"Unlawful interference": "התערבות בלתי חוקית",
|
||||
"Radio failure": "כשל קשר",
|
||||
@@ -2352,7 +2356,6 @@
|
||||
"+ CAPTURE SHOT": "+ לכידת שוט",
|
||||
"Replace the selected shot with the current view": "החלפת השוט הנבחר בתצוגה הנוכחית",
|
||||
"UPDATE SHOT": "עדכון שוט",
|
||||
"Click a shot to select it, double-click to rename.": "לחץ על שוט לבחירתו, לחיצה כפולה לשינוי שם.",
|
||||
"Play from this scene through the rest of the project": "נגינה מהסצנה הזאת ועד סוף הפרויקט",
|
||||
"Stop playback (Esc)": "עצירת ההשמעה (Esc)",
|
||||
"STOP": "עצירה",
|
||||
@@ -2396,9 +2399,7 @@
|
||||
"ACTIVE STYLE": "הסגנון הפעיל",
|
||||
"ORBIT": "הקפה",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "אין עדיין שוטים. השתמש בלכידת שוט כדי לשמור את המראה הנוכחי.",
|
||||
"Double-click to rename": "לחיצה כפולה לשינוי שם",
|
||||
"Shot name": "שם השוט",
|
||||
"LOAD": "טעינה",
|
||||
"DEL": "מחיקה",
|
||||
"MISSION CONTROL · FIRST LAUNCH": "חדר בקרה · שיגור ראשון",
|
||||
"Choose your first view": "בחירת התצוגה הראשונה",
|
||||
@@ -4234,5 +4235,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "כיוון אל {code}: {course}",
|
||||
"Over {place}": "מעל {place}",
|
||||
"Below": "מתחת"
|
||||
"Below": "מתחת",
|
||||
"Go to this shot. Double-click to rename.": "מעבר לשוט הזה. לחיצה כפולה לשינוי שם.",
|
||||
"Move up": "הזזה למעלה",
|
||||
"Move down": "הזזה למטה",
|
||||
"Click a shot to go to it, double-click to rename.": "לחץ על שוט כדי לעבור אליו, לחיצה כפולה לשינוי שם.",
|
||||
"Back to live at the starting view": "חזרה לשידור החי בתצוגת הפתיחה",
|
||||
"Exit cockpit to fly to a bike share city": "צא מתא הטייס כדי לטוס לעיר עם שיתוף אופניים"
|
||||
}
|
||||
@@ -143,6 +143,10 @@
|
||||
"Fast jet": "Jet ad alte prestazioni",
|
||||
"Business jet": "Business jet",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Veicolo aeroportuale",
|
||||
"Ground station / obstacle": "Stazione a terra / ostacolo",
|
||||
"Airport vehicles": "Veicoli aeroportuali",
|
||||
"Ground stations / obstacles": "Stazioni a terra / ostacoli",
|
||||
"General emergency": "Emergenza generale",
|
||||
"Unlawful interference": "Interferenza illecita",
|
||||
"Radio failure": "Avaria radio",
|
||||
@@ -2272,9 +2276,7 @@
|
||||
"SPARSE": "RADO",
|
||||
"BALANCED": "BILANCIATO",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Ancora nessuno scatto. Usa CATTURA SCATTO per salvare l'aspetto attuale.",
|
||||
"Double-click to rename": "Doppio clic per rinominare",
|
||||
"Shot name": "Nome dello scatto",
|
||||
"LOAD": "CARICA",
|
||||
"DEL": "ELIM",
|
||||
"{duration}s + {hold}s": "{duration}s + {hold}s",
|
||||
"Choose files": "Scegli i file",
|
||||
@@ -3210,7 +3212,6 @@
|
||||
"+ CAPTURE SHOT": "+ CATTURA SCATTO",
|
||||
"Add the current view, style and layers as the next shot": "Aggiungi la vista, lo stile e i livelli attuali come scatto successivo",
|
||||
"Replace the selected shot with the current view": "Sostituisci lo scatto selezionato con la vista attuale",
|
||||
"Click a shot to select it, double-click to rename.": "Fai clic su uno scatto per selezionarlo, doppio clic per rinominarlo.",
|
||||
"Play from this scene through the rest of the project": "Riproduci da questa scena fino alla fine del progetto",
|
||||
"Stop playback (Esc)": "Interrompi la riproduzione (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Riproduci lo scatto dopo quello selezionato, passando alla scena successiva se serve",
|
||||
@@ -4234,5 +4235,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Rotta verso {code}: {course}",
|
||||
"Over {place}": "Sopra {place}",
|
||||
"Below": "Sotto"
|
||||
"Below": "Sotto",
|
||||
"Go to this shot. Double-click to rename.": "Vai a questo scatto. Doppio clic per rinominare.",
|
||||
"Move up": "Sposta su",
|
||||
"Move down": "Sposta giù",
|
||||
"Click a shot to go to it, double-click to rename.": "Fai clic su uno scatto per andarci, doppio clic per rinominarlo.",
|
||||
"Back to live at the starting view": "Torna alla diretta nella vista iniziale",
|
||||
"Exit cockpit to fly to a bike share city": "Esci dalla cabina per volare verso una città con bike sharing"
|
||||
}
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "高速ジェット機",
|
||||
"Business jet": "ビジネスジェット",
|
||||
"Drone": "ドローン",
|
||||
"Airport vehicle": "空港車両",
|
||||
"Ground station / obstacle": "地上局 / 障害物",
|
||||
"Airport vehicles": "空港車両",
|
||||
"Ground stations / obstacles": "地上局 / 障害物",
|
||||
"General emergency": "緊急事態",
|
||||
"Unlawful interference": "不法妨害",
|
||||
"Radio failure": "通信機故障",
|
||||
@@ -2186,9 +2190,7 @@
|
||||
"SPARSE": "低密度",
|
||||
"BALANCED": "標準",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "ショットはまだありません。[ショット取得]で現在の表示を保存してください。",
|
||||
"Double-click to rename": "ダブルクリックで名前を変更",
|
||||
"Shot name": "ショット名",
|
||||
"LOAD": "読込",
|
||||
"DEL": "削除",
|
||||
"{duration}s + {hold}s": "{duration}秒 + {hold}秒",
|
||||
"Choose files": "ファイルを選択",
|
||||
@@ -3048,7 +3050,6 @@
|
||||
"+ CAPTURE SHOT": "+ ショット取得",
|
||||
"Add the current view, style and layers as the next shot": "現在の視点・スタイル・レイヤーを次のショットとして追加",
|
||||
"Replace the selected shot with the current view": "選択中のショットを現在の視点で置き換え",
|
||||
"Click a shot to select it, double-click to rename.": "ショットをクリックして選択、ダブルクリックで名前を変更します。",
|
||||
"Play from this scene through the rest of the project": "このシーンからプロジェクトの最後まで再生",
|
||||
"Stop playback (Esc)": "再生を停止(Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "選択中のショットの次を再生(必要に応じて次のシーンへ進む)",
|
||||
@@ -4028,5 +4029,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "{code}への針路: {course}",
|
||||
"Over {place}": "{place}上空",
|
||||
"Below": "直下"
|
||||
"Below": "直下",
|
||||
"Go to this shot. Double-click to rename.": "このショットへ移動。ダブルクリックで名前を変更。",
|
||||
"Move up": "上へ移動",
|
||||
"Move down": "下へ移動",
|
||||
"Click a shot to go to it, double-click to rename.": "ショットをクリックしてそこへ移動、ダブルクリックで名前を変更します。",
|
||||
"Back to live at the starting view": "ライブに戻り、最初の表示へ",
|
||||
"Exit cockpit to fly to a bike share city": "シェアサイクルのある都市へ移動するにはコックピットを終了してください"
|
||||
}
|
||||
@@ -143,6 +143,10 @@
|
||||
"Fast jet": "Jato de alto desempenho",
|
||||
"Business jet": "Jato executivo",
|
||||
"Drone": "Drone",
|
||||
"Airport vehicle": "Veículo de aeroporto",
|
||||
"Ground station / obstacle": "Estação terrestre / obstáculo",
|
||||
"Airport vehicles": "Veículos de aeroporto",
|
||||
"Ground stations / obstacles": "Estações terrestres / obstáculos",
|
||||
"General emergency": "Emergência geral",
|
||||
"Unlawful interference": "Interferência ilícita",
|
||||
"Radio failure": "Falha de rádio",
|
||||
@@ -2272,9 +2276,7 @@
|
||||
"SPARSE": "ESPARSO",
|
||||
"BALANCED": "EQUILIBRADO",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Ainda não há planos. Use CAPTURAR PLANO para salvar o visual atual.",
|
||||
"Double-click to rename": "Clique duplo para renomear",
|
||||
"Shot name": "Nome do plano",
|
||||
"LOAD": "CARREGAR",
|
||||
"DEL": "EXCL.",
|
||||
"{duration}s + {hold}s": "{duration} s + {hold} s",
|
||||
"Choose files": "Escolher arquivos",
|
||||
@@ -3210,7 +3212,6 @@
|
||||
"+ CAPTURE SHOT": "+ CAPTURAR PLANO",
|
||||
"Add the current view, style and layers as the next shot": "Adicionar a vista, o estilo e as camadas atuais como próximo plano",
|
||||
"Replace the selected shot with the current view": "Substituir o plano selecionado pela vista atual",
|
||||
"Click a shot to select it, double-click to rename.": "Clique em um plano para selecioná-lo e clique duas vezes para renomeá-lo.",
|
||||
"Play from this scene through the rest of the project": "Reproduzir desta cena até o fim do projeto",
|
||||
"Stop playback (Esc)": "Parar a reprodução (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Reproduzir o plano após o selecionado, passando à próxima cena se necessário",
|
||||
@@ -4234,5 +4235,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Rumo para {code}: {course}",
|
||||
"Over {place}": "Sobre {place}",
|
||||
"Below": "Abaixo"
|
||||
"Below": "Abaixo",
|
||||
"Go to this shot. Double-click to rename.": "Ir para este plano. Clique duplo para renomear.",
|
||||
"Move up": "Mover para cima",
|
||||
"Move down": "Mover para baixo",
|
||||
"Click a shot to go to it, double-click to rename.": "Clique em um plano para ir até ele e clique duas vezes para renomeá-lo.",
|
||||
"Back to live at the starting view": "Voltar ao vivo na vista inicial",
|
||||
"Exit cockpit to fly to a bike share city": "Saia do cockpit para voar até uma cidade com bicicletas compartilhadas"
|
||||
}
|
||||
@@ -1821,9 +1821,7 @@
|
||||
"Export failed · {error}": "Ошибка экспорта · {error}",
|
||||
"← → preview · A or B pins the focused day": "← → просмотр · A или B закрепляет выбранный день",
|
||||
"← → preview the other side · A or B pins it": "← → просмотр другой стороны · A или B закрепляет её",
|
||||
"LOAD": "ЗАГРУЗИТЬ",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Кадров пока нет. Нажмите «СДЕЛАТЬ КАДР», чтобы сохранить текущий вид.",
|
||||
"Double-click to rename": "Дважды щёлкните, чтобы переименовать",
|
||||
"Shot name": "Название кадра",
|
||||
"RETRYING ALPR CAMERAS": "ПОВТОРНАЯ ЗАГРУЗКА КАМЕР ALPR",
|
||||
"FETCHING ALPR CAMERAS": "ЗАГРУЗКА КАМЕР ALPR",
|
||||
@@ -2931,6 +2929,10 @@
|
||||
"Fast jet": "Высокоманёвренный самолёт",
|
||||
"Business jet": "Бизнес-джет",
|
||||
"Drone": "Беспилотник",
|
||||
"Airport vehicle": "Аэродромная машина",
|
||||
"Ground station / obstacle": "Наземная станция / препятствие",
|
||||
"Airport vehicles": "Аэродромные машины",
|
||||
"Ground stations / obstacles": "Наземные станции / препятствия",
|
||||
"fire cause|Human": "деятельность человека",
|
||||
"fire cause|Natural": "природная",
|
||||
"fire cause|Undetermined": "не установлена",
|
||||
@@ -3312,7 +3314,6 @@
|
||||
"+ CAPTURE SHOT": "+ СДЕЛАТЬ КАДР",
|
||||
"Add the current view, style and layers as the next shot": "Добавить текущий вид, стиль и слои следующим кадром",
|
||||
"Replace the selected shot with the current view": "Заменить выбранный кадр текущим видом",
|
||||
"Click a shot to select it, double-click to rename.": "Щёлкните кадр, чтобы выбрать его, дважды — чтобы переименовать.",
|
||||
"scene|PLAY": "ПУСК",
|
||||
"Stop playback (Esc)": "Остановить воспроизведение (Esc)",
|
||||
"SAVE & SHARE": "СОХРАНЕНИЕ И ОБМЕН",
|
||||
@@ -4337,5 +4338,11 @@
|
||||
"KT": "УЗ",
|
||||
"Course to {code}: {course}": "Курс на {code}: {course}",
|
||||
"Over {place}": "Над: {place}",
|
||||
"Below": "Под спутником"
|
||||
"Below": "Под спутником",
|
||||
"Go to this shot. Double-click to rename.": "Перейти к этому кадру. Дважды щёлкните, чтобы переименовать.",
|
||||
"Move up": "Переместить вверх",
|
||||
"Move down": "Переместить вниз",
|
||||
"Click a shot to go to it, double-click to rename.": "Щёлкните кадр, чтобы перейти к нему, дважды — чтобы переименовать.",
|
||||
"Back to live at the starting view": "Вернуться в прямой эфир в начальном виде",
|
||||
"Exit cockpit to fly to a bike share city": "Выйдите из кабины, чтобы перелететь в город с прокатом велосипедов"
|
||||
}
|
||||
@@ -996,6 +996,10 @@
|
||||
"Fast jet": "Stridsflygplan",
|
||||
"Business jet": "Affärsjet",
|
||||
"Drone": "Drönare",
|
||||
"Airport vehicle": "Flygplatsfordon",
|
||||
"Ground station / obstacle": "Markstation / hinder",
|
||||
"Airport vehicles": "Flygplatsfordon",
|
||||
"Ground stations / obstacles": "Markstationer / hinder",
|
||||
"General emergency": "Allmänt nödläge",
|
||||
"Unlawful interference": "Olagligt ingripande",
|
||||
"Radio failure": "Radiobortfall",
|
||||
@@ -2434,9 +2438,7 @@
|
||||
"Delete scene \"{scene}\" and all shots?": "Radera scenen ”{scene}” och alla tagningar?",
|
||||
"Stopped (Esc)": "Stoppad (Esc)",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Inga tagningar än. Använd SPARA TAGNING för att spara nuvarande vy.",
|
||||
"Double-click to rename": "Dubbelklicka för att byta namn",
|
||||
"Shot name": "Namn på tagning",
|
||||
"LOAD": "LADDA",
|
||||
"{duration}s + {hold}s": "{duration} s + {hold} s",
|
||||
"Choose files": "Välj filer",
|
||||
"{count} files selected": {
|
||||
@@ -3040,7 +3042,6 @@
|
||||
"+ CAPTURE SHOT": "+ SPARA TAGNING",
|
||||
"Add the current view, style and layers as the next shot": "Lägg till aktuell vy, stil och lager som nästa tagning",
|
||||
"Replace the selected shot with the current view": "Ersätt vald tagning med aktuell vy",
|
||||
"Click a shot to select it, double-click to rename.": "Klicka på en tagning för att välja den, dubbelklicka för att byta namn.",
|
||||
"Play from this scene through the rest of the project": "Spela upp från den här scenen genom resten av projektet",
|
||||
"Stop playback (Esc)": "Stoppa uppspelningen (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Spela upp tagningen efter den valda och gå vidare till nästa scen vid behov",
|
||||
@@ -4131,5 +4132,11 @@
|
||||
"KT": "KT",
|
||||
"Course to {code}: {course}": "Kurs mot {code}: {course}",
|
||||
"Over {place}": "Över {place}",
|
||||
"Below": "Nedanför"
|
||||
"Below": "Nedanför",
|
||||
"Go to this shot. Double-click to rename.": "Gå till den här tagningen. Dubbelklicka för att byta namn.",
|
||||
"Move up": "Flytta upp",
|
||||
"Move down": "Flytta ned",
|
||||
"Click a shot to go to it, double-click to rename.": "Klicka på en tagning för att gå till den, dubbelklicka för att byta namn.",
|
||||
"Back to live at the starting view": "Tillbaka till live i startvyn",
|
||||
"Exit cockpit to fly to a bike share city": "Lämna cockpit för att flyga till en stad med lånecyklar"
|
||||
}
|
||||
@@ -151,6 +151,10 @@
|
||||
"Fast jet": "Швидкісний реактивний літак",
|
||||
"Business jet": "Бізнес-джет",
|
||||
"Drone": "Безпілотник",
|
||||
"Airport vehicle": "Аеродромний автомобіль",
|
||||
"Ground station / obstacle": "Наземна станція / перешкода",
|
||||
"Airport vehicles": "Аеродромні автомобілі",
|
||||
"Ground stations / obstacles": "Наземні станції / перешкоди",
|
||||
"General emergency": "Загальна аварійна ситуація",
|
||||
"Unlawful interference": "Незаконне втручання",
|
||||
"Radio failure": "Відмова радіозвʼязку",
|
||||
@@ -2314,9 +2318,7 @@
|
||||
"SPARSE": "РІДКО",
|
||||
"BALANCED": "ПОМІРНО",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "Кадрів поки немає. Натисніть «ЗНЯТИ КАДР», щоб зберегти поточний вигляд.",
|
||||
"Double-click to rename": "Двічі клацніть, щоб перейменувати",
|
||||
"Shot name": "Назва кадру",
|
||||
"LOAD": "ЗАВАНТАЖИТИ",
|
||||
"DEL": "ВИДАЛ.",
|
||||
"{duration}s + {hold}s": "{duration} с + {hold} с",
|
||||
"Choose files": "Вибрати файли",
|
||||
@@ -3304,7 +3306,6 @@
|
||||
"+ CAPTURE SHOT": "+ ЗНЯТИ КАДР",
|
||||
"Add the current view, style and layers as the next shot": "Додати поточний вигляд, стиль і шари як наступний кадр",
|
||||
"Replace the selected shot with the current view": "Замінити вибраний кадр поточним виглядом",
|
||||
"Click a shot to select it, double-click to rename.": "Клацніть кадр, щоб вибрати його, двічі — щоб перейменувати.",
|
||||
"Play from this scene through the rest of the project": "Відтворити від цієї сцени до кінця проєкту",
|
||||
"Stop playback (Esc)": "Зупинити відтворення (Esc)",
|
||||
"Play the shot after the selected one, moving on to the next scene when needed": "Відтворити кадр після вибраного, за потреби перейшовши до наступної сцени",
|
||||
@@ -4337,5 +4338,11 @@
|
||||
"KT": "ВУЗ",
|
||||
"Course to {code}: {course}": "Курс на {code}: {course}",
|
||||
"Over {place}": "Над: {place}",
|
||||
"Below": "Під супутником"
|
||||
"Below": "Під супутником",
|
||||
"Go to this shot. Double-click to rename.": "Перейти до цього кадру. Двічі клацніть, щоб перейменувати.",
|
||||
"Move up": "Перемістити вгору",
|
||||
"Move down": "Перемістити вниз",
|
||||
"Click a shot to go to it, double-click to rename.": "Клацніть кадр, щоб перейти до нього, двічі — щоб перейменувати.",
|
||||
"Back to live at the starting view": "Повернутися до прямого ефіру в початковому вигляді",
|
||||
"Exit cockpit to fly to a bike share city": "Вийдіть із кабіни, щоб перелетіти до міста з прокатом велосипедів"
|
||||
}
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "喷气战机",
|
||||
"Business jet": "公务机",
|
||||
"Drone": "无人机",
|
||||
"Airport vehicle": "机场车辆",
|
||||
"Ground station / obstacle": "地面站 / 障碍物",
|
||||
"Airport vehicles": "机场车辆",
|
||||
"Ground stations / obstacles": "地面站 / 障碍物",
|
||||
"General emergency": "一般紧急情况",
|
||||
"Unlawful interference": "非法干扰",
|
||||
"Radio failure": "无线电失效",
|
||||
@@ -2157,9 +2161,7 @@
|
||||
"SPARSE": "稀疏",
|
||||
"BALANCED": "均衡",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "暂无镜头。使用“保存镜头”保存当前视角及设置。",
|
||||
"Double-click to rename": "双击重命名",
|
||||
"Shot name": "镜头名称",
|
||||
"LOAD": "加载",
|
||||
"DEL": "删除",
|
||||
"{duration}s + {hold}s": "{duration} 秒 + {hold} 秒",
|
||||
"Choose files": "选择文件",
|
||||
@@ -3069,7 +3071,6 @@
|
||||
"+ CAPTURE SHOT": "+ 保存镜头",
|
||||
"Add the current view, style and layers as the next shot": "将当前视角、样式和图层添加为下一个镜头",
|
||||
"Replace the selected shot with the current view": "用当前视角替换所选镜头",
|
||||
"Click a shot to select it, double-click to rename.": "单击镜头即可选中,双击可重命名。",
|
||||
"scene|PLAY": "播放",
|
||||
"Stop playback (Esc)": "停止播放(Esc)",
|
||||
"SAVE & SHARE": "保存与分享",
|
||||
@@ -4028,5 +4029,11 @@
|
||||
"KT": "kt",
|
||||
"Course to {code}: {course}": "前往 {code} 的航向:{course}",
|
||||
"Over {place}": "{place}上空",
|
||||
"Below": "下方"
|
||||
"Below": "下方",
|
||||
"Go to this shot. Double-click to rename.": "转到此镜头。双击重命名。",
|
||||
"Move up": "上移",
|
||||
"Move down": "下移",
|
||||
"Click a shot to go to it, double-click to rename.": "单击镜头即可转到该镜头,双击可重命名。",
|
||||
"Back to live at the starting view": "回到实时并返回初始视图",
|
||||
"Exit cockpit to fly to a bike share city": "退出驾驶舱以飞往有共享单车的城市"
|
||||
}
|
||||
@@ -127,6 +127,10 @@
|
||||
"Fast jet": "噴氣戰機",
|
||||
"Business jet": "公務機",
|
||||
"Drone": "無人機",
|
||||
"Airport vehicle": "機場車輛",
|
||||
"Ground station / obstacle": "地面站 / 障礙物",
|
||||
"Airport vehicles": "機場車輛",
|
||||
"Ground stations / obstacles": "地面站 / 障礙物",
|
||||
"General emergency": "一般緊急情況",
|
||||
"Unlawful interference": "非法干擾",
|
||||
"Radio failure": "無線電失效",
|
||||
@@ -2157,9 +2161,7 @@
|
||||
"SPARSE": "稀疏",
|
||||
"BALANCED": "均衡",
|
||||
"No shots yet. Use CAPTURE SHOT to save current look.": "暫無鏡頭。使用“保存鏡頭”保存當前視角及設置。",
|
||||
"Double-click to rename": "雙擊重命名",
|
||||
"Shot name": "鏡頭名稱",
|
||||
"LOAD": "加載",
|
||||
"DEL": "刪除",
|
||||
"{duration}s + {hold}s": "{duration} 秒 + {hold} 秒",
|
||||
"Choose files": "選擇文件",
|
||||
@@ -3069,7 +3071,6 @@
|
||||
"+ CAPTURE SHOT": "+ 保存鏡頭",
|
||||
"Add the current view, style and layers as the next shot": "將當前視角、樣式和圖層添加為下一個鏡頭",
|
||||
"Replace the selected shot with the current view": "用當前視角替換所選鏡頭",
|
||||
"Click a shot to select it, double-click to rename.": "單擊鏡頭即可選中,雙擊可重命名。",
|
||||
"scene|PLAY": "播放",
|
||||
"Stop playback (Esc)": "停止播放(Esc)",
|
||||
"SAVE & SHARE": "保存與分享",
|
||||
@@ -4028,5 +4029,11 @@
|
||||
"KT": "kt",
|
||||
"Course to {code}: {course}": "前往 {code} 的航向:{course}",
|
||||
"Over {place}": "{place}上空",
|
||||
"Below": "下方"
|
||||
"Below": "下方",
|
||||
"Go to this shot. Double-click to rename.": "轉到此鏡頭。雙擊重命名。",
|
||||
"Move up": "上移",
|
||||
"Move down": "下移",
|
||||
"Click a shot to go to it, double-click to rename.": "單擊鏡頭即可轉到該鏡頭,雙擊可重命名。",
|
||||
"Back to live at the starting view": "回到實時並返回初始視圖",
|
||||
"Exit cockpit to fly to a bike share city": "退出駕駛艙以飛往有共享單車的城市"
|
||||
}
|
||||
@@ -0,0 +1,139 @@
|
||||
// Bike Share's covered cities on the globe (HAL-921): above the height
|
||||
// stations draw at, every system in the registry has a marker, so the globe
|
||||
// says where bike share is, and a click on one flies down into its city.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { GBFS_CITY_REGISTRY } from './registry.js';
|
||||
import { createState } from './state.js';
|
||||
import { createIngestion } from './ingestion.js';
|
||||
import { createModel } from './model.js';
|
||||
import { createViewport } from './viewport.js';
|
||||
import { createRendering } from './rendering.js';
|
||||
import { createSelection } from './selection.js';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { COVERAGE_FLY_HEIGHT_M } from './policy.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeInput } from '../../input/testDoubles.mjs';
|
||||
|
||||
globalThis.document ??= {
|
||||
addEventListener() {},
|
||||
removeEventListener() {},
|
||||
};
|
||||
|
||||
function makeLayer() {
|
||||
const owners = new Map();
|
||||
const services = {
|
||||
render: { governorRequestRender() {} },
|
||||
overlays: {
|
||||
setOverlayEntries() {},
|
||||
setOverlaySourceVisible() {},
|
||||
clearOverlaySource() {},
|
||||
},
|
||||
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
|
||||
picking: {
|
||||
registerPickOwner: (id, owns) => owners.set(id, owns),
|
||||
unregisterPickOwner: (id) => owners.delete(id),
|
||||
},
|
||||
};
|
||||
const source = { getStations: async () => ({ data: { stations: [] } }) };
|
||||
const state = createState({ services });
|
||||
const parts = {};
|
||||
const context = { state, services, parts, source };
|
||||
parts.ingestion = createIngestion(context);
|
||||
parts.model = createModel(context);
|
||||
parts.viewport = createViewport(context);
|
||||
parts.rendering = createRendering(context);
|
||||
parts.selection = createSelection(context);
|
||||
parts.queries = { collectDetectableStations: () => [] };
|
||||
parts.lifecycle = createLifecycle(context);
|
||||
|
||||
const camera = { lat: 20, lon: 0, height: 18_000_000 };
|
||||
const flights = [];
|
||||
const viewer = { scene: { pick: () => undefined, canvas: {} } };
|
||||
const { draw } = bindFakeDraw(viewer, {
|
||||
camera: {
|
||||
pose: () => ({ ...camera }),
|
||||
viewRectangle: () => null,
|
||||
on: () => () => {},
|
||||
flyTo: (destination, options) => flights.push({ destination, options }),
|
||||
},
|
||||
});
|
||||
// The layer's click subscription, called with a hit as the dispatcher gives it.
|
||||
const fake = fakeInput(viewer);
|
||||
const clicks = [];
|
||||
const subscribe = fake.input.onClick;
|
||||
fake.input.onClick = (fn) => {
|
||||
clicks.push(fn);
|
||||
return subscribe.call(fake.input, () => {});
|
||||
};
|
||||
parts.lifecycle.methods.init(viewer);
|
||||
const coverage = () =>
|
||||
draw.find('bikeshare:') &&
|
||||
[...draw.sets.values()].find(
|
||||
(set) => !set.disposed && set.spec.id.endsWith(':coverage'),
|
||||
);
|
||||
return {
|
||||
state,
|
||||
parts,
|
||||
owners,
|
||||
flights,
|
||||
coverage,
|
||||
click: (hit) => clicks.at(-1)({ drawHit: hit }),
|
||||
async moveTo(height) {
|
||||
camera.height = height;
|
||||
await parts.viewport.runProximityCheck();
|
||||
},
|
||||
enable: () => parts.lifecycle.methods.enable(viewer),
|
||||
disable: () => parts.lifecycle.methods.disable(),
|
||||
};
|
||||
}
|
||||
|
||||
test('every covered city has a marker, shown only while the layer is on and too high for stations', async () => {
|
||||
const layer = makeLayer();
|
||||
const set = layer.coverage();
|
||||
assert.equal(set.items.size, GBFS_CITY_REGISTRY.length);
|
||||
assert.equal(set.show, false, 'hidden while the layer is off');
|
||||
layer.enable();
|
||||
await layer.moveTo(18_000_000);
|
||||
assert.equal(set.show, true, 'the globe shows where bike share is');
|
||||
await layer.moveTo(20_000);
|
||||
assert.equal(
|
||||
set.show,
|
||||
false,
|
||||
'stations take over below the activation height',
|
||||
);
|
||||
await layer.moveTo(18_000_000);
|
||||
assert.equal(set.show, true);
|
||||
layer.disable();
|
||||
assert.equal(set.show, false, 'gone with the layer');
|
||||
});
|
||||
|
||||
test('a marker belongs to the layer and its click flies straight down into the city', async () => {
|
||||
const layer = makeLayer();
|
||||
layer.enable();
|
||||
await layer.moveTo(18_000_000);
|
||||
const city = GBFS_CITY_REGISTRY.find(
|
||||
(each) => each.id === 'boston-bluebikes',
|
||||
);
|
||||
const id = `city:${city.id}`;
|
||||
assert.equal(layer.owners.get('bikeshare')(id), true);
|
||||
assert.equal(layer.owners.get('bikeshare')('city:nowhere'), false);
|
||||
const navigated = [];
|
||||
layer.parts.lifecycle.methods.attachShellServices({
|
||||
runNavigation: (navigate) => {
|
||||
navigated.push('explicit');
|
||||
return navigate();
|
||||
},
|
||||
});
|
||||
layer.click({ set: layer.coverage().spec.id, id });
|
||||
assert.deepEqual(navigated, ['explicit'], 'an explicit camera action');
|
||||
assert.equal(layer.flights.length, 1);
|
||||
const { destination, options } = layer.flights[0];
|
||||
assert.deepEqual(destination, {
|
||||
lon: city.centerLon,
|
||||
lat: city.centerLat,
|
||||
height: COVERAGE_FLY_HEIGHT_M,
|
||||
});
|
||||
assert.equal(options.orientation.pitch, -Math.PI / 2);
|
||||
assert.ok(COVERAGE_FLY_HEIGHT_M < 48_000, 'below the activation height');
|
||||
});
|
||||
@@ -20,6 +20,18 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
const methods = {
|
||||
/**
|
||||
* The shell's services: `runNavigation(navigate)` runs a covered city's
|
||||
* flight as an explicit camera action, as the other camera controls are.
|
||||
* @param {{ runNavigation?: Function }|null} shellServices
|
||||
*/
|
||||
attachShellServices(shellServices) {
|
||||
layerState._runNavigation =
|
||||
typeof shellServices?.runNavigation === 'function'
|
||||
? shellServices.runNavigation
|
||||
: null;
|
||||
},
|
||||
|
||||
/**
|
||||
* Initialize the bikeshare layer. Makes the station draw sets on the
|
||||
* viewer's renderer (`drawOf`), resets all internal state, and installs
|
||||
@@ -81,8 +93,11 @@ export function createLifecycle({
|
||||
);
|
||||
parts.selection._installClickHandler(viewer);
|
||||
// Pick-ownership (H2): station point ids are string render-map keys.
|
||||
registerPickOwner('bikeshare', (pickedId) =>
|
||||
layerState._stationRenderMap.has(pickedId),
|
||||
registerPickOwner(
|
||||
'bikeshare',
|
||||
(pickedId) =>
|
||||
layerState._stationRenderMap.has(pickedId) ||
|
||||
parts.selection.coverageCityOf(pickedId) !== null,
|
||||
);
|
||||
|
||||
if (!layerState._cameraChangedOff) {
|
||||
@@ -124,6 +139,7 @@ export function createLifecycle({
|
||||
parts.viewport.deactivateAllCities();
|
||||
layerState._cityRuntime.clear();
|
||||
if (layerState._stationSet) layerState._stationSet.show = false;
|
||||
parts.viewport.showCoverage(false);
|
||||
layerState._count = 0;
|
||||
layerState._loading = false;
|
||||
layerState._loadingOps = 0;
|
||||
|
||||
@@ -15,6 +15,22 @@ const ACTIVATION_ALTITUDE_M = 50000;
|
||||
|
||||
export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 2000;
|
||||
|
||||
/**
|
||||
* Where a covered city's marker flies to: straight down from this height,
|
||||
* well inside the activation band, with the city's stations in view.
|
||||
*/
|
||||
export const COVERAGE_FLY_HEIGHT_M = 20000;
|
||||
|
||||
/** A covered city's marker: the stations' green, larger, ringed in white. */
|
||||
export const COVERAGE_PIXEL_SIZE = 11;
|
||||
export const COVERAGE_OUTLINE_WIDTH = 2;
|
||||
|
||||
/**
|
||||
* A marker's height: above the highest covered city's ground, so terrain
|
||||
* never hides it, while the globe itself hides the markers behind it.
|
||||
*/
|
||||
export const COVERAGE_HEIGHT_M = 5000;
|
||||
|
||||
/** Hysteresis exit threshold — layer deactivates when camera rises above this. */
|
||||
|
||||
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000;
|
||||
|
||||
@@ -13,7 +13,11 @@ import {
|
||||
POINT_SCALE_BY_DISTANCE,
|
||||
POINT_FADE_BY_DISTANCE,
|
||||
POINT_DISABLE_DEPTH_TEST_M,
|
||||
COVERAGE_PIXEL_SIZE,
|
||||
COVERAGE_OUTLINE_WIDTH,
|
||||
COVERAGE_HEIGHT_M,
|
||||
} from './policy.js';
|
||||
import { GBFS_CITY_REGISTRY } from './registry.js';
|
||||
import { heightsOf } from '../../queries/heights.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { drawOf } from '../../render/rendererOf.js';
|
||||
@@ -24,6 +28,9 @@ import { drawOf } from '../../render/rendererOf.js';
|
||||
* share a renderer. Picks name them as `Hit.set`.
|
||||
*/
|
||||
export const BIKESHARE_SET_ID = 'bikeshare';
|
||||
|
||||
/** A covered city's marker id: its registry id under this prefix. */
|
||||
export const COVERAGE_ID_PREFIX = 'city:';
|
||||
let instances = 0;
|
||||
|
||||
export function createRendering({
|
||||
@@ -51,6 +58,23 @@ export function createRendering({
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
|
||||
});
|
||||
layerState._selectedSet = draw.points({ id: `${prefix}:selected` });
|
||||
// One marker per covered city, drawn while the camera is too high for
|
||||
// stations: the globe shows where bike share is.
|
||||
layerState._coverageSet = draw.points({
|
||||
id: `${prefix}:coverage`,
|
||||
show: false,
|
||||
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
|
||||
});
|
||||
layerState._coverageSet.set(
|
||||
GBFS_CITY_REGISTRY.map((city) => ({
|
||||
id: `${COVERAGE_ID_PREFIX}${city.id}`,
|
||||
pos: fromDegrees(city.centerLon, city.centerLat, COVERAGE_HEIGHT_M),
|
||||
pixelSize: COVERAGE_PIXEL_SIZE,
|
||||
color: COLOR_GREEN,
|
||||
outlineColor: [1, 1, 1, 0.9],
|
||||
outlineWidth: COVERAGE_OUTLINE_WIDTH,
|
||||
})),
|
||||
);
|
||||
// Drawn from the start, empty, so both take their place in the scene
|
||||
// now, as the layer's collections did; the stations' place among the
|
||||
// other sprite layers is their draw order (`spriteDrawOrder`).
|
||||
@@ -62,8 +86,10 @@ export function createRendering({
|
||||
function detachSets() {
|
||||
layerState._stationSet?.dispose();
|
||||
layerState._selectedSet?.dispose();
|
||||
layerState._coverageSet?.dispose();
|
||||
layerState._stationSet = null;
|
||||
layerState._selectedSet = null;
|
||||
layerState._coverageSet = null;
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -4,7 +4,11 @@ import {
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
|
||||
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
|
||||
SELECTED_POINT_STYLE,
|
||||
COVERAGE_FLY_HEIGHT_M,
|
||||
} from './policy.js';
|
||||
import { GBFS_CITY_REGISTRY } from './registry.js';
|
||||
import { COVERAGE_ID_PREFIX } from './rendering.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
|
||||
export function createSelection({
|
||||
state: layerState,
|
||||
@@ -139,6 +143,38 @@ export function createSelection({
|
||||
* @param {object} viewer - The viewer the layer draws on.
|
||||
*/
|
||||
|
||||
/**
|
||||
* The covered city a marker id names, or null.
|
||||
* @param {unknown} id
|
||||
*/
|
||||
function coverageCityOf(id) {
|
||||
if (typeof id !== 'string' || !id.startsWith(COVERAGE_ID_PREFIX))
|
||||
return null;
|
||||
const cityId = id.slice(COVERAGE_ID_PREFIX.length);
|
||||
return GBFS_CITY_REGISTRY.find((city) => city.id === cityId) ?? null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Straight down over a covered city, low enough for its stations, as the
|
||||
* shell's camera action when it gave one.
|
||||
* @param {{ centerLat: number, centerLon: number }} city
|
||||
*/
|
||||
function flyIntoCity(city) {
|
||||
const viewer = layerState._viewer;
|
||||
if (!viewer) return;
|
||||
const fly = () =>
|
||||
cameraOf(viewer).flyTo(
|
||||
{
|
||||
lon: city.centerLon,
|
||||
lat: city.centerLat,
|
||||
height: COVERAGE_FLY_HEIGHT_M,
|
||||
},
|
||||
{ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 } },
|
||||
);
|
||||
if (layerState._runNavigation) layerState._runNavigation(fly);
|
||||
else fly();
|
||||
}
|
||||
|
||||
function _installClickHandler(viewer) {
|
||||
if (layerState._clickSubscription) return;
|
||||
|
||||
@@ -149,6 +185,15 @@ export function createSelection({
|
||||
// Clicking the selected highlight itself — ignore (don't deselect).
|
||||
if (hit.set === layerState._selectedSet?.id) return;
|
||||
|
||||
// A covered city's marker: fly down into it.
|
||||
if (hit.set === layerState._coverageSet?.id) {
|
||||
const city = coverageCityOf(hit.id);
|
||||
if (city) {
|
||||
flyIntoCity(city);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// A station dot of this layer's own set
|
||||
if (
|
||||
hit.set === layerState._stationSet?.id &&
|
||||
@@ -183,5 +228,6 @@ export function createSelection({
|
||||
_selectStation,
|
||||
_installClickHandler,
|
||||
_onKeyDown,
|
||||
coverageCityOf,
|
||||
};
|
||||
}
|
||||
@@ -27,6 +27,17 @@ export function createState({ services }) {
|
||||
|
||||
layerState._stationSet = null;
|
||||
|
||||
/**
|
||||
* Draw set of the covered cities' markers, shown above the activation
|
||||
* height so the globe says where bike share is, or null.
|
||||
*/
|
||||
|
||||
layerState._coverageSet = null;
|
||||
|
||||
/** The shell's camera action for a marker's flight (`attachShellServices`), or null. */
|
||||
|
||||
layerState._runNavigation = null;
|
||||
|
||||
/** Draw set of the selected station's highlight dot, or null. */
|
||||
|
||||
layerState._selectedSet = null;
|
||||
|
||||
@@ -115,6 +115,18 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
parts.rendering.removeCityPoints(cityId);
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the covered cities' markers, or hide them: shown while the layer is
|
||||
* on and the camera is too high for stations.
|
||||
* @param {boolean} shown
|
||||
*/
|
||||
function showCoverage(shown) {
|
||||
const set = layerState._coverageSet;
|
||||
if (!set || set.show === shown) return;
|
||||
set.show = shown;
|
||||
governorRequestRender('bikeshare-coverage');
|
||||
}
|
||||
|
||||
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
|
||||
function refreshRow() {
|
||||
layerState._dataManager?.refreshLayerStats?.('bikeshare');
|
||||
@@ -212,11 +224,13 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
const wasGateEnabled = layerState._altitudeGateEnabled;
|
||||
// Altitude gate: disable all cities when camera is too high
|
||||
if (!shouldActivateAtAltitude(altitude)) {
|
||||
showCoverage(true);
|
||||
deactivateAllCities();
|
||||
if (wasGateEnabled) refreshRow();
|
||||
return;
|
||||
}
|
||||
|
||||
showCoverage(false);
|
||||
const center = getCameraCenterLatLon(layerState._viewer);
|
||||
if (!center) return;
|
||||
|
||||
@@ -288,6 +302,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
|
||||
activateCity,
|
||||
runProximityCheck,
|
||||
scheduleProximityCheck,
|
||||
showCoverage,
|
||||
onCameraChanged,
|
||||
};
|
||||
}
|
||||
@@ -27,6 +27,60 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The contacts drawn now that the first live snapshot after the clock came
|
||||
* back to live lacks (the tracked one too): the snapshot judges them as a
|
||||
* poll judges any absence (see the snapshot renderer).
|
||||
* @param {{records: Array<{id: string}>}} snapshot
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
function absentAtHandover(snapshot) {
|
||||
const present = new Set(snapshot.records.map((record) => record.id));
|
||||
const drawn = [...(flightState._icons?.ids() ?? [])];
|
||||
if (flightState._trackedIcao) drawn.push(flightState._trackedIcao);
|
||||
return new Set(drawn.filter((id) => !present.has(id)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live: forget how every contact moved, as at a jump, but keep the
|
||||
* tracked trail, and keep the contacts `kept` (absentAtHandover) as they
|
||||
* were: their record, fixes and course. Each was last seen at its newest
|
||||
* fix, not when it was loaded, so absence judges how old it really is.
|
||||
* @param {Set<string>} kept
|
||||
*/
|
||||
function handOverMotion(kept) {
|
||||
const held = [];
|
||||
for (const id of kept)
|
||||
held.push([
|
||||
id,
|
||||
flightState.records.data.get(id),
|
||||
flightState._positionHistory.get(id),
|
||||
flightState._displayCourse.get(id),
|
||||
]);
|
||||
forgetPlacedAircraft(
|
||||
services?.placement,
|
||||
[...flightState._positionHistory.keys()].filter((id) => !kept.has(id)),
|
||||
);
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._displayFloorState.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
flightState._lastCamPoseSig = '';
|
||||
for (const [id, meta, history, course] of held) {
|
||||
if (meta)
|
||||
flightState.records.data.set(id, {
|
||||
...meta,
|
||||
observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs,
|
||||
});
|
||||
if (history) flightState._positionHistory.set(id, history);
|
||||
if (course !== undefined) flightState._displayCourse.set(id, course);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
@@ -40,5 +94,5 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
return { resetMotion, absentAtHandover, handOverMotion, clear };
|
||||
}
|
||||
@@ -156,7 +156,11 @@ export function createEnrichment({
|
||||
(data) => {
|
||||
const meta = flightState.records.data.get(icao24);
|
||||
if (!meta) return; // evicted while the lookup was in flight
|
||||
meta.typeCode = data.typeCode || meta.typeCode;
|
||||
// A looked-up type outranks the feed's own from now on.
|
||||
if (data.typeCode) {
|
||||
meta.typeCode = data.typeCode;
|
||||
meta.typeLookedUp = true;
|
||||
}
|
||||
meta.typeName = data.typeName || meta.typeName;
|
||||
meta.registration = data.registration || meta.registration;
|
||||
if (meta.typeCode) {
|
||||
|
||||
@@ -12,7 +12,10 @@ import { createEvidence } from './evidence.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one civil-flight layer with application-owned scene services. */
|
||||
export function createCivilFlightLayer({
|
||||
@@ -53,10 +56,19 @@ export function createCivilFlightLayer({
|
||||
getQuery: (viewer) =>
|
||||
parts.controller._flightQuery(viewer || flightState._viewer),
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
// At another time the snapshot takes the place of every contact: how
|
||||
// each moved belongs to the time the clock left. Back at live too, but
|
||||
// the contacts it lacks are kept as they were for it to judge.
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
if (options?.handover) {
|
||||
parts.clockFollow.handOverMotion(
|
||||
parts.clockFollow.absentAtHandover(snapshot),
|
||||
);
|
||||
}
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
timedAnswer: snapshotAnswer,
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -72,9 +84,7 @@ export function createCivilFlightLayer({
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
|
||||
@@ -12,6 +12,7 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
@@ -21,13 +22,27 @@ export function createIngestion({
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once, and let this live
|
||||
* snapshot stand in for every contact. Those it has keep their
|
||||
* icon and model and move on from where they are drawn; those it lacks
|
||||
* go. Resolves true once it is applied, else false (nothing to poll yet,
|
||||
* or the poll failed); rejects with an AbortError when it was dropped.
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async resumeLive(viewer) {
|
||||
return (await acquire(viewer, { handover: true })) === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* whether it was applied: `{ reachMs }`, the newest fix its records
|
||||
* carry, when they carry fixes; else true, or false when it was not.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
@@ -38,7 +53,10 @@ export function createIngestion({
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
async function acquire(
|
||||
viewer,
|
||||
{ signal = null, atMs, replace = false, handover = false },
|
||||
) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
@@ -85,7 +103,9 @@ export function createIngestion({
|
||||
setSourceLabel(feed._lastSource);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
: handover
|
||||
? applySnapshot(snapshot, viewer, { handover: true })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
// Freshness belongs to the source snapshot, not the moment this browser
|
||||
// received a cached 200 response.
|
||||
@@ -99,7 +119,8 @@ export function createIngestion({
|
||||
};
|
||||
console.log(`[Data:Flights] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Flights update aborted', 'AbortError');
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createFlightSnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createFlightFeed, createIngestion } from './ingestion.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
|
||||
// Back at live from another time, the first live snapshot stands in for
|
||||
// every contact: those it has keep their icon and ease on from where they
|
||||
// are drawn, and only those it lacks go (src/time/snapshotTimeline.js).
|
||||
|
||||
/** Any property is a no-op function unless given. */
|
||||
function stub(overrides = {}) {
|
||||
return new Proxy(overrides, {
|
||||
get: (target, key) => (key in target ? target[key] : () => undefined),
|
||||
});
|
||||
}
|
||||
|
||||
function harness() {
|
||||
const iconIds = new Set();
|
||||
const calls = [];
|
||||
const landed = new Set();
|
||||
const groundFloor = stub({
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
GROUND_FLOOR_LIFT_M: 0.5,
|
||||
});
|
||||
const services = stub({
|
||||
geoid: { geoidHeight: () => 0 },
|
||||
camera: stub(),
|
||||
focus: stub(),
|
||||
groundFloor,
|
||||
meshFloor: stub(),
|
||||
groundSnap: stub({ createGroundSnap: () => stub() }),
|
||||
placement: null,
|
||||
});
|
||||
const flightState = createFlightState({
|
||||
services,
|
||||
source: { label: 'Fixture aircraft' },
|
||||
});
|
||||
flightState._icons = {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
};
|
||||
const parts = {
|
||||
rendering: stub({ _modelOwnsVisual: () => false }),
|
||||
icons: stub({
|
||||
_addIcon: (id) => {
|
||||
calls.push(['add', id]);
|
||||
iconIds.add(id);
|
||||
},
|
||||
_forgetContact: (id) => {
|
||||
calls.push(['forget', id]);
|
||||
iconIds.delete(id);
|
||||
},
|
||||
_planIcon: (id, options) => calls.push(['plan', id, options]),
|
||||
}),
|
||||
tracking: stub({
|
||||
_militaryLayerSuppresses: () => false,
|
||||
_appendTrailFix: () => calls.push(['trail-append']),
|
||||
_startTrail: (id) => calls.push(['trail-start', id]),
|
||||
_clearTrail: () => calls.push(['trail-clear']),
|
||||
}),
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
const apply = createFlightSnapshotRenderer({
|
||||
flightState,
|
||||
records: flightState.records,
|
||||
militaryRegistry: stub({ isMilitaryIcao: () => false }),
|
||||
groundFloor,
|
||||
rendering: parts.rendering,
|
||||
tracking: parts.tracking,
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
enrichment: stub(),
|
||||
queries: stub({ _likelyLanded: (id) => landed.has(id) }),
|
||||
});
|
||||
const clockFollow = createClockFollow({ flightState, services, parts });
|
||||
return {
|
||||
calls,
|
||||
iconIds,
|
||||
flightState,
|
||||
clockFollow,
|
||||
landed,
|
||||
// `ids`: an id, or [id, fix age ms, on the ground].
|
||||
snapshot: (ids, fields = {}) => ({
|
||||
observedAtMs: Date.now(),
|
||||
records: ids.map((entry, k) => {
|
||||
const [id, ageMs = 5_000, onGround = false] = [entry].flat();
|
||||
return {
|
||||
id,
|
||||
reference: id,
|
||||
longitude: -115 + k,
|
||||
latitude: 36,
|
||||
callsign: 'TEST1',
|
||||
baroAltitudeM: onGround ? 0 : 9_000,
|
||||
onGround,
|
||||
speedMps: onGround ? 5 : 220,
|
||||
courseDeg: 90,
|
||||
positionTimeMs: Date.now() - ageMs,
|
||||
};
|
||||
}),
|
||||
complete: true,
|
||||
...fields,
|
||||
}),
|
||||
apply(ids, options, fields) {
|
||||
calls.length = 0;
|
||||
return apply(this.snapshot(ids, fields), null, options);
|
||||
},
|
||||
// Back at live, as the layer applies its first live snapshot.
|
||||
handOver(ids, fields) {
|
||||
calls.length = 0;
|
||||
const snapshot = this.snapshot(ids, fields);
|
||||
clockFollow.handOverMotion(clockFollow.absentAtHandover(snapshot));
|
||||
return apply(snapshot, null, { handover: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the first live snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
|
||||
|
||||
const accepted = h.handOver(['a00001', 'a00003']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00003']);
|
||||
assert.equal(accepted.count, 2);
|
||||
// The contact it has keeps its icon: no remove and add, and its motion is
|
||||
// planned as a handover, easing from where it is drawn.
|
||||
assert.equal(
|
||||
h.calls.some(
|
||||
([kind, id]) => id === 'a00001' && (kind === 'add' || kind === 'forget'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind, id]) => kind === 'plan' && id === 'a00001'),
|
||||
['plan', 'a00001', { handover: true }],
|
||||
);
|
||||
assert.ok(h.calls.some(([kind, id]) => kind === 'forget' && id === 'a00002'));
|
||||
assert.ok(h.calls.some(([kind, id]) => kind === 'add' && id === 'a00003'));
|
||||
});
|
||||
|
||||
test('a plain live poll keeps a missing contact as its absence rules say', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002']);
|
||||
h.apply(['a00001']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002']);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind]) => kind === 'plan'),
|
||||
['plan', 'a00001', undefined],
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, only the first live snapshot applied takes over; a failed poll says so', async () => {
|
||||
const applied = [];
|
||||
let fail = false;
|
||||
const feed = createFlightFeed({
|
||||
async getSnapshot() {
|
||||
if (fail) throw new Error('down');
|
||||
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
|
||||
},
|
||||
});
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
getQuery: () => ({}),
|
||||
applySnapshot: (_snapshot, _viewer, options) => {
|
||||
applied.push(options);
|
||||
return { count: 0, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
});
|
||||
assert.equal(await methods.resumeLive(null), true);
|
||||
await methods.update(null);
|
||||
assert.deepEqual(applied, [{ handover: true }, undefined]);
|
||||
|
||||
fail = true;
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await methods.resumeLive(null), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live, the tracked contact and those the snapshot retains stay, stale, and a partial snapshot drops none', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001', 'a00002', 'a00003', 'a00004']);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
const history = [{ epochMs: Date.now() - 60_000 }];
|
||||
h.flightState._positionHistory.set('a00001', history);
|
||||
h.handOver(['a00004'], { retainIds: new Set(['a00002']) });
|
||||
assert.deepEqual([...h.iconIds].sort(), ['a00001', 'a00002', 'a00004']);
|
||||
assert.equal(
|
||||
h.flightState._positionHistory.get('a00001'),
|
||||
history,
|
||||
'the tracked contact keeps its fixes for the next poll to judge',
|
||||
);
|
||||
assert.ok(h.flightState.records.data.has('a00001'));
|
||||
assert.equal(
|
||||
h.calls.some(([kind]) => kind === 'trail-clear' || kind === 'trail-start'),
|
||||
false,
|
||||
'its trail goes on',
|
||||
);
|
||||
|
||||
const partial = harness();
|
||||
partial.apply(['a00001', 'a00002']);
|
||||
partial.handOver(['a00003'], { complete: false });
|
||||
assert.deepEqual([...partial.iconIds].sort(), ['a00001', 'a00002', 'a00003']);
|
||||
});
|
||||
|
||||
test('back at live, the tracked contact the snapshot has goes on adding to its trail', () => {
|
||||
const h = harness();
|
||||
h.apply(['a00001']);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
h.handOver(['a00001']);
|
||||
assert.deepEqual(
|
||||
h.calls.filter(([kind]) => kind.startsWith('trail')),
|
||||
[['trail-append']],
|
||||
);
|
||||
});
|
||||
|
||||
const HOURS_3 = 3 * 3_600_000;
|
||||
|
||||
test('back at live, a partial snapshot keeps only contacts whose newest fix is recent, by the real absence rules', () => {
|
||||
const h = harness();
|
||||
// Shown from a time three hours back, and one from a minute ago.
|
||||
h.apply([
|
||||
['a00001', HOURS_3],
|
||||
['a00002', 60_000],
|
||||
]);
|
||||
h.handOver(['a00003'], { complete: false });
|
||||
assert.deepEqual(
|
||||
[...h.iconIds].sort(),
|
||||
['a00002', 'a00003'],
|
||||
'the three-hour-old contact is no ghost',
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, a tracked aircraft is kept only while its newest fix is recent and it has not landed', () => {
|
||||
for (const [label, setUp, kept] of [
|
||||
['recent', (h) => h.apply([['a00001', 60_000]]), true],
|
||||
['three hours old', (h) => h.apply([['a00001', HOURS_3]]), false],
|
||||
[
|
||||
'landed',
|
||||
(h) => {
|
||||
h.apply([['a00001', 120_000]]);
|
||||
h.apply([['a00001', 60_000, true]]);
|
||||
h.landed.add('a00001');
|
||||
},
|
||||
false,
|
||||
],
|
||||
]) {
|
||||
const h = harness();
|
||||
setUp(h);
|
||||
h.flightState._trackedIcao = 'a00001';
|
||||
h.handOver(['a00002']);
|
||||
assert.equal(h.iconIds.has('a00001'), kept, label);
|
||||
}
|
||||
});
|
||||
@@ -42,7 +42,6 @@ import {
|
||||
limitCourseStep,
|
||||
corridorPathLatLon,
|
||||
} from '../../data/motionModel.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { placeLiveAircraft } from './placed.js';
|
||||
import {
|
||||
modelVisualAnchor,
|
||||
@@ -50,7 +49,6 @@ import {
|
||||
} from '../../data/modelVisualAnchor.js';
|
||||
import {
|
||||
FOCUS_EVIDENCE_DEV,
|
||||
MODEL_MIN_PX,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
DR_CORRECTION_MS,
|
||||
COURSE_SLEW_DT_MAX_SEC,
|
||||
@@ -415,19 +413,17 @@ export function createMotion({
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24),
|
||||
);
|
||||
// Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX.
|
||||
// Drawn as the fleet draws it: at its true size.
|
||||
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
|
||||
const projectedDiameterPx =
|
||||
(2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM;
|
||||
return Math.max(MODEL_MIN_PX, projectedDiameterPx);
|
||||
return projectedDiameterPx;
|
||||
}
|
||||
|
||||
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
|
||||
const width = sprite?.width ?? 28;
|
||||
const height = sprite?.height ?? 28;
|
||||
const scale =
|
||||
sprite?.scale ??
|
||||
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
|
||||
const scale = sprite?.scale ?? 1;
|
||||
const scaleByDistance =
|
||||
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
|
||||
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
|
||||
@@ -456,6 +452,8 @@ export function createMotion({
|
||||
const sameTrack =
|
||||
flightState._drReconcileValid && flightState._drReconcileIcao === icao24;
|
||||
const raw = _deadReckon(icao24, flightState._scratchDrRaw);
|
||||
flightState._cachedDRPlaced =
|
||||
Boolean(raw) && flightState._drSpeedPlaced === true;
|
||||
flightState._cachedDRCourse = flightState._drCourseDeg;
|
||||
flightState._cachedDRSpeedMps = flightState._drSpeedMps;
|
||||
flightState._cachedDRHold = flightState._drCourseHold;
|
||||
@@ -601,6 +599,16 @@ export function createMotion({
|
||||
* against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when
|
||||
* there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */
|
||||
|
||||
/** Whether a host-supplied placement placed the tracked aircraft where
|
||||
* `_trackedDisplayCached` holds it this frame, rather than this layer's
|
||||
* own motion at its display delay. */
|
||||
|
||||
function _trackedPlaced() {
|
||||
return (
|
||||
_trackedDisplayCached() !== null && flightState._cachedDRPlaced === true
|
||||
);
|
||||
}
|
||||
|
||||
function _trackedDisplayCached() {
|
||||
return flightState._drReconcileValid &&
|
||||
flightState._drReconcileIcao === flightState._trackedIcao
|
||||
@@ -645,9 +653,8 @@ export function createMotion({
|
||||
/** Trail endpoint for the rendered tracked owner. Brackets/readouts stay on
|
||||
* the visual centre; only the trail moves to the model's lower-centre hardpoint. */
|
||||
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
|
||||
* contact is drawing. Carries the scale it is drawn at, which may be
|
||||
* above `scale` to satisfy its pixel floor — the trail head has to be judged
|
||||
* against the size the operator SEES, not the nominal one. */
|
||||
* contact is drawing, at the scale it is drawn at — the trail head has to
|
||||
* be judged against the size the operator SEES. */
|
||||
/** World-space origin of the tracked model, or null when no model of this
|
||||
* contact is drawing. This is the centre the rendered bounding sphere is
|
||||
* measured from, so the trail clip and the envelope agree on one frame. */
|
||||
@@ -1222,6 +1229,7 @@ export function createMotion({
|
||||
_trackedFocusSizePx,
|
||||
_trackedDisplayPosition,
|
||||
_trackedDisplayCached,
|
||||
_trackedPlaced,
|
||||
_trackedVisualCached,
|
||||
_trackedModelCenterWorld,
|
||||
_trackedModelEnvelopeM,
|
||||
|
||||
@@ -4,6 +4,8 @@ import * as Cesium from 'cesium';
|
||||
import { createMotion } from './motion.js';
|
||||
import { arcOffsetEnu } from '../../data/motionModel.js';
|
||||
import { createMotion as createMilitaryMotion } from '../military/motion.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createQueries as createMilitaryQueries } from '../military/queries.js';
|
||||
import { layerPlacement } from '../../data/placementProvider.js';
|
||||
import { observeLiveAircraft } from './placed.js';
|
||||
|
||||
@@ -248,18 +250,77 @@ const declining = (asked) =>
|
||||
);
|
||||
|
||||
// Each kind's record carries only its own kinematics fields.
|
||||
for (const [name, create, record] of [
|
||||
for (const [name, create, record, queriesOf] of [
|
||||
[
|
||||
'civil',
|
||||
createMotion,
|
||||
{ velocity: 100, true_track: 90, renderAltitudeM: 1234 },
|
||||
createQueries,
|
||||
],
|
||||
[
|
||||
'military',
|
||||
createMilitaryMotion,
|
||||
{ speedMps: 100, track: 90, renderAltitudeM: 1234 },
|
||||
createMilitaryQueries,
|
||||
],
|
||||
]) {
|
||||
test(`${name} aircraft waiting where a placement holds them still show their reported speed`, () => {
|
||||
// Drawn standing (speed 0) while its fixes catch up: the aircraft has
|
||||
// not stopped, and the panels say what it reports.
|
||||
const placement = layerPlacement(
|
||||
{
|
||||
layer: () => ({
|
||||
place: () => ({
|
||||
lat: 30.5,
|
||||
lon: -96.5,
|
||||
altitudeM: 2000,
|
||||
courseDeg: 90,
|
||||
speedMps: 0,
|
||||
extrapolating: false,
|
||||
}),
|
||||
}),
|
||||
},
|
||||
'aircraft',
|
||||
);
|
||||
const { flightState, motion, start } = placedScenario(
|
||||
create,
|
||||
placement,
|
||||
record,
|
||||
);
|
||||
flightState.now = () => start + 2000;
|
||||
flightState.feed = {};
|
||||
flightState.records.missingPolls = new Map();
|
||||
const describe = (kinematics) => {
|
||||
flightState.records.data.set('abc123', { ...record, ...kinematics });
|
||||
return queriesOf({
|
||||
flightState,
|
||||
services: {
|
||||
aircraftPresentation: {
|
||||
tr3bTypeLabel: (_, label) => label,
|
||||
tr3bAircraftClass: () => null,
|
||||
},
|
||||
labels: { formatFlightLevel: String },
|
||||
militaryRegistry: {},
|
||||
focus: {},
|
||||
recession: {},
|
||||
},
|
||||
parts: {
|
||||
motion,
|
||||
icons: { _iconPosition: () => null },
|
||||
tracking: { _routeIsPlausible: () => false },
|
||||
testing: {},
|
||||
},
|
||||
})._describeFlight('abc123');
|
||||
};
|
||||
const waiting = describe({});
|
||||
assert.equal(flightState._drSpeedMps, 0);
|
||||
assert.equal(waiting.velocityMps, 100);
|
||||
// Nothing reported: the speed it is drawn at.
|
||||
const unreported =
|
||||
name === 'civil' ? { velocity: undefined } : { speedMps: undefined };
|
||||
assert.equal(describe(unreported).velocityMps, 0);
|
||||
});
|
||||
|
||||
test(`${name} aircraft move as before without a placement or with one that places nothing`, () => {
|
||||
const own = placedScenario(create, null, record).drawn;
|
||||
const asked = [];
|
||||
@@ -338,14 +399,20 @@ test('an aircraft fix is told to the placement live, with its drawn height', ()
|
||||
'aircraft',
|
||||
);
|
||||
const state = { timeline: { active: () => false } };
|
||||
const meta = { rawLat: 1, rawLon: 2, renderAltitudeM: 300, onGround: false };
|
||||
const meta = {
|
||||
rawLat: 1,
|
||||
rawLon: 2,
|
||||
renderAltitudeM: 300,
|
||||
groundM: 1656,
|
||||
onGround: false,
|
||||
};
|
||||
observeLiveAircraft(state, placement, 'abc123', 5000, meta, 80, 270);
|
||||
observeLiveAircraft(
|
||||
state,
|
||||
placement,
|
||||
'abc123',
|
||||
6000,
|
||||
{ ...meta, renderAltitudeInvented: true, onGround: true },
|
||||
{ ...meta, renderAltitudeInvented: true, groundM: null, onGround: true },
|
||||
null,
|
||||
undefined,
|
||||
);
|
||||
@@ -360,12 +427,15 @@ test('an aircraft fix is told to the placement live, with its drawn height', ()
|
||||
lat: 1,
|
||||
lon: 2,
|
||||
altitudeM: 300,
|
||||
groundM: 1656,
|
||||
speedMps: 80,
|
||||
courseDeg: 270,
|
||||
headingDeg: NaN,
|
||||
onGround: false,
|
||||
},
|
||||
]);
|
||||
// Where the layer does not know the ground, it says so.
|
||||
assert.ok(Number.isNaN(told[1][1].groundM));
|
||||
assert.ok(Number.isNaN(told[1][1].altitudeM));
|
||||
assert.ok(Number.isNaN(told[1][1].speedMps));
|
||||
assert.ok(Number.isNaN(told[1][1].courseDeg));
|
||||
|
||||
@@ -608,3 +608,75 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
|
||||
assert.equal(meta.routeCallsign, 'UAL10');
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
|
||||
test("a type lookup overrides the feed's type and fills the type name", async () => {
|
||||
const queries = [];
|
||||
const source = {
|
||||
getEnrichment(query) {
|
||||
queries.push(query);
|
||||
return Promise.resolve({
|
||||
found: true,
|
||||
typeCode: 'B738',
|
||||
typeName: 'Boeing 737-800',
|
||||
registration: 'N123AB',
|
||||
});
|
||||
},
|
||||
};
|
||||
const flightState = createFlightState({ source, services: services() });
|
||||
const view = {
|
||||
viewerLatDeg: null,
|
||||
viewerLonDeg: null,
|
||||
trackedId: null,
|
||||
floorWarmPoints: [],
|
||||
};
|
||||
const { meta } = flightState.records.receive(
|
||||
{
|
||||
id: 'abc123',
|
||||
reference: 'abc123',
|
||||
longitude: -77,
|
||||
latitude: 39,
|
||||
callsign: 'TEST1',
|
||||
baroAltitudeM: 1000,
|
||||
typeCode: 'EC45',
|
||||
},
|
||||
view,
|
||||
);
|
||||
assert.equal(meta.klass, 'helicopter', 'classed by the feed type at once');
|
||||
const restyled = [];
|
||||
const synced = [];
|
||||
const enrichment = createEnrichment({
|
||||
flightState,
|
||||
services: enrichServices(),
|
||||
parts: {
|
||||
icons: { _applyIconPresentation: (id) => restyled.push(id) },
|
||||
rendering: { _syncModelToClass: (id) => synced.push(id) },
|
||||
},
|
||||
});
|
||||
// A present feed type does not skip the lookup.
|
||||
enrichment._requestTypeEnrichment('abc123', true);
|
||||
await new Promise((done) => setImmediate(done));
|
||||
assert.deepEqual(queries, [{ kind: 'type', id: 'abc123' }]);
|
||||
const looked = flightState.records.data.get('abc123');
|
||||
assert.equal(looked.typeCode, 'B738');
|
||||
assert.equal(looked.typeName, 'Boeing 737-800');
|
||||
assert.equal(looked.registration, 'N123AB');
|
||||
assert.equal(looked.klass, 'airliner');
|
||||
assert.deepEqual(restyled, ['abc123']);
|
||||
assert.deepEqual(synced, ['abc123']);
|
||||
// The next poll's feed type no longer wins.
|
||||
const next = flightState.records.receive(
|
||||
{
|
||||
id: 'abc123',
|
||||
reference: 'abc123',
|
||||
longitude: -77,
|
||||
latitude: 39,
|
||||
callsign: 'TEST1',
|
||||
baroAltitudeM: 1000,
|
||||
typeCode: 'EC45',
|
||||
},
|
||||
view,
|
||||
).meta;
|
||||
assert.equal(next.typeCode, 'B738');
|
||||
assert.equal(next.klass, 'airliner');
|
||||
flightState.lifetime.abort();
|
||||
});
|
||||
@@ -61,6 +61,7 @@ export function placeLiveAircraft(
|
||||
history,
|
||||
out,
|
||||
) {
|
||||
flightState._drSpeedPlaced = false;
|
||||
if (!placement || followsClock(flightState)) return false;
|
||||
const placed = placeAircraftAt(
|
||||
placement,
|
||||
@@ -73,6 +74,7 @@ export function placeLiveAircraft(
|
||||
if (!placed) return false;
|
||||
flightState._drCourseDeg = placed.courseDeg;
|
||||
flightState._drSpeedMps = placed.speedMps;
|
||||
flightState._drSpeedPlaced = true;
|
||||
flightState._drCourseHold = placed.speedMps < COURSE_HOLD_SPEED_MPS;
|
||||
flightState._drExtrapolating = placed.extrapolating;
|
||||
return true;
|
||||
@@ -93,13 +95,15 @@ export function forgetPlacedAircraft(placement, ids) {
|
||||
* Tell the host-supplied placement an aircraft's fix as the layer took it
|
||||
* (nothing while the layer follows the world clock): its own time, its
|
||||
* position, the height the layer draws it at (NaN when that height is
|
||||
* invented), and its reported speed, course and ground state.
|
||||
* invented), the ground under it in that height's reference (NaN where the
|
||||
* layer does not know it), and its reported speed, course and ground state.
|
||||
* @param {object} flightState
|
||||
* @param {object|null|undefined} placement
|
||||
* @param {string} icao24
|
||||
* @param {number} fixEpochMs
|
||||
* @param {{rawLat: number, rawLon: number, renderAltitudeM: number,
|
||||
* renderAltitudeInvented?: boolean, onGround?: boolean}} meta
|
||||
* renderAltitudeInvented?: boolean, groundM?: number|null,
|
||||
* onGround?: boolean}} meta
|
||||
* @param {number|null|undefined} speedMps
|
||||
* @param {number|null|undefined} courseDeg
|
||||
*/
|
||||
@@ -119,6 +123,7 @@ export function observeLiveAircraft(
|
||||
lon: meta.rawLon,
|
||||
altitudeM:
|
||||
meta.renderAltitudeInvented === true ? NaN : meta.renderAltitudeM,
|
||||
groundM: Number.isFinite(meta.groundM) ? meta.groundM : NaN,
|
||||
speedMps: Number.isFinite(speedMps) ? speedMps : NaN,
|
||||
courseDeg: Number.isFinite(courseDeg) ? courseDeg : NaN,
|
||||
headingDeg: NaN,
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
|
||||
/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */
|
||||
const rgba = (css, alpha) =>
|
||||
@@ -13,6 +14,10 @@ export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true;
|
||||
|
||||
export const MIL_TINT = rgba('#FFB800');
|
||||
|
||||
/** Amber tint for airport vehicles (type ZVEH, emitter C1/C2), apart from aircraft. */
|
||||
|
||||
export const VEHICLE_TINT = rgba(VEHICLE_TINT_CSS);
|
||||
|
||||
/** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */
|
||||
|
||||
export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
|
||||
@@ -39,18 +44,27 @@ export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS);
|
||||
export const GROUND_SCALE = 0.8;
|
||||
|
||||
// --- 3D model rendering (B3) ---------------------------------------------------------
|
||||
// When enabled, aircraft render as 3D glTF models once the camera is below MODEL_ALT_CEIL_M
|
||||
// (zoomed in); higher up they stay flat billboards. Eligibility is FRUSTUM-based (on-screen), and
|
||||
// the slots go to either the nearest planes ('proximity') or every in-view plane ('all'), each
|
||||
// backed by a hard cap so a draw-call explosion can't tank the frame (no instancing yet).
|
||||
// When enabled, an aircraft draws as its 3D glTF model only within MODEL_ADD_M of the camera
|
||||
// (eye to aircraft); farther away it stays its icon. Models are drawn at their true size, with no
|
||||
// minimum pixel size, so a model never balloons past its real extent. Eligibility is distance-based
|
||||
// with on-screen priority, and the slots go to either the nearest planes ('proximity') or every
|
||||
// in-range plane ('all'): the two modes share the radius and differ by their caps, each a hard
|
||||
// bound on the frame cost (every model is its own draw call).
|
||||
|
||||
export const MODEL_ALT_CEIL_M = 800000;
|
||||
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
|
||||
export const MODEL_ADD_M = 3000;
|
||||
// model NEW planes within 3 km of the camera
|
||||
|
||||
export const MODEL_MIN_PX = 24;
|
||||
// floor so distant models stay visible WITHOUT ballooning into a giant
|
||||
// min-pixel blob (was 54 — far planes at the All radius became white
|
||||
// star-bursts); ~matches the 2D icon size so the model↔billboard read is consistent
|
||||
export const MODEL_KEEP_M = 3600;
|
||||
// KEEP modeled planes out to 3.6 km: the hysteresis band (KEEP > ADD) stops a plane on the edge
|
||||
// from releasing and reloading its model as the camera moves (the zoom/pan flicker)
|
||||
|
||||
export const MODEL_HIGHEST_CONTACT_M = 30000;
|
||||
// m above the ellipsoid: no aircraft the layers draw flies higher (airliners cruise near 12 km,
|
||||
// the highest-flying aircraft near 21 km)
|
||||
|
||||
export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M;
|
||||
// m: above this camera altitude no contact can be within MODEL_KEEP_M, so no model is
|
||||
// considered at all (the eligibility pass is skipped)
|
||||
|
||||
// Per-mode caps. Each model is its own draw call (no instancing yet), so these bound the frame cost.
|
||||
|
||||
@@ -58,29 +72,22 @@ export const MODEL_MAX = 150;
|
||||
// 'proximity' cap (the planes immediately around you)
|
||||
|
||||
export const MODEL_MAX_ALL = 350;
|
||||
// 'all' cap (everything out to ~the horizon)
|
||||
// Per-mode ADD / KEEP radii. The two modes differ by RADIUS, not just cap — otherwise they look
|
||||
// IDENTICAL whenever fewer than a cap's worth of planes are in range (field bug: Proximity and All
|
||||
// rendered the same). 'proximity' = a tight ring; 'all' = roughly to the horizon (state-scale). Each
|
||||
// band has hysteresis (KEEP > ADD) so a plane doesn't release+reload its model when it straddles the
|
||||
// add edge (the zoom/pan flicker). Beyond ADD a model would force-clamp to minimumPixelSize into a
|
||||
// giant floating blob (the old 422 km airport-cluster bug), so far planes stay 2D dots; the cap +
|
||||
// on-screen priority then spend the model slots on planes you can actually see.
|
||||
|
||||
export const MODEL_PROX_ADD_M = 150000;
|
||||
// proximity: model NEW planes within 150 km
|
||||
|
||||
export const MODEL_PROX_KEEP_M = 185000;
|
||||
// proximity: KEEP modeled planes out to 185 km
|
||||
// 'all' cap (every plane in range)
|
||||
|
||||
export const COCKPIT_MODEL_MAX = 60;
|
||||
// max concurrent GLBs in cockpit (never raises the map cap)
|
||||
|
||||
export const MODEL_ALL_ADD_M = 400000;
|
||||
// all: model NEW planes within 400 km (~to the horizon)
|
||||
// Cockpit's AIR band: contacts within it draw as aircraft silhouettes, beyond
|
||||
// it as compact dots. Independent of the 3D model radius; per 3D mode, each
|
||||
// with its keep hysteresis.
|
||||
|
||||
export const MODEL_ALL_KEEP_M = 450000;
|
||||
// all: KEEP modeled planes out to 450 km
|
||||
export const COCKPIT_AIR_PROX_ADD_M = 150000;
|
||||
|
||||
export const COCKPIT_AIR_PROX_KEEP_M = 185000;
|
||||
|
||||
export const COCKPIT_AIR_ALL_ADD_M = 400000;
|
||||
|
||||
export const COCKPIT_AIR_ALL_KEEP_M = 450000;
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// every fleet model is nose -X: opposite the renderer's heading 0
|
||||
@@ -88,9 +95,6 @@ export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
/** A model's colour where it draws its mesh's own (`aircraftModelBlend`). */
|
||||
export const MODEL_WHITE = rgba('#FFFFFF');
|
||||
|
||||
/** The tracked contact's tint, and its billboard once a model takes over. */
|
||||
export const TRACKED_CYAN = rgba('#00FFFF');
|
||||
export const CYAN_TRANSPARENT = rgba('#00FFFF', 0);
|
||||
/** An ordinary fleet contact's tint. */
|
||||
export const FLEET_TINT = rgba('#FFFFFF');
|
||||
|
||||
@@ -201,18 +205,15 @@ export const FLEET_DR_INTERVAL_MS = 80;
|
||||
/**
|
||||
* The icon-to-model rules the aircraft layers follow, as the Vessels, Transit
|
||||
* and Rail layers take them (`createFleetModelLayer`): the same altitude
|
||||
* ceiling, minimum pixel size, proximity/all caps, add/keep radii and
|
||||
* eligibility cadence, so every layer turns icons into models at one distance.
|
||||
* ceiling, proximity/all caps, add/keep radii and eligibility cadence, so
|
||||
* every layer turns icons into models at one distance, drawn at true size.
|
||||
*/
|
||||
export const FLEET_MODEL_POLICY = Object.freeze({
|
||||
altitudeCeilingM: MODEL_ALT_CEIL_M,
|
||||
minimumPixelSize: MODEL_MIN_PX,
|
||||
cap: MODEL_MAX,
|
||||
capAll: MODEL_MAX_ALL,
|
||||
addM: MODEL_PROX_ADD_M,
|
||||
addAllM: MODEL_ALL_ADD_M,
|
||||
keepM: MODEL_PROX_KEEP_M,
|
||||
keepAllM: MODEL_ALL_KEEP_M,
|
||||
addM: MODEL_ADD_M,
|
||||
keepM: MODEL_KEEP_M,
|
||||
intervalMs: FLEET_DR_INTERVAL_MS,
|
||||
});
|
||||
|
||||
|
||||
@@ -145,6 +145,7 @@ export function createQueries({
|
||||
derivedSpeedMps: flightState._drSpeedMps,
|
||||
derivedTrackDeg: flightState._drCourseDeg,
|
||||
reportedSpeedMps: info?.velocity,
|
||||
derivedFromPlacement: flightState._drSpeedPlaced === true,
|
||||
reportedTrackDeg: info?.true_track,
|
||||
});
|
||||
const carto = toLonLatH(basePos);
|
||||
@@ -345,11 +346,11 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Live layer params.
|
||||
* `models3d` toggles 3D glTF model rendering for the FLEET (altitude-gated): when on,
|
||||
* surrounding aircraft become 3D models once the camera is zoomed in past MODEL_ALT_CEIL_M.
|
||||
* `models3d` toggles 3D glTF model rendering for the FLEET: when on, aircraft within
|
||||
* MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true size.
|
||||
* The TRACKED contact follows the same rule (`_trackedModelRegimeActive`), so selecting
|
||||
* a contact never turns its icon into a model or its model into an icon.
|
||||
* `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane).
|
||||
* `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius.
|
||||
* @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedFlightsTrackingId?: string|null}} params
|
||||
*/
|
||||
setParams(params = {}, { origin = 'programmatic' } = {}) {
|
||||
|
||||
@@ -92,11 +92,11 @@ export class FlightRecords {
|
||||
originCountry: origin_country,
|
||||
longitude: lon,
|
||||
latitude: lat,
|
||||
baroAltitudeM: baro_alt,
|
||||
baroAltitudeM: reportedBaroAlt,
|
||||
onGround: on_ground,
|
||||
speedMps: velocity,
|
||||
courseDeg: true_track,
|
||||
ellipsoidAltitudeM: geo_alt,
|
||||
ellipsoidAltitudeM: reportedGeoAlt,
|
||||
category,
|
||||
verticalRateMps: vertical_rate,
|
||||
} = observation;
|
||||
@@ -110,11 +110,12 @@ export class FlightRecords {
|
||||
// The airframe's facts: this record's, or those kept across a reset.
|
||||
const airframe = prevMeta ?? this.airframes.get(icao24);
|
||||
this.airframes.delete(icao24);
|
||||
// A ground vehicle or ground station (a feed's ZVEH or GRND: a model
|
||||
// built standing, catalog category `other`) takes the feed's own type,
|
||||
// which no airframe lookup knows; every other aircraft keeps waiting for
|
||||
// its looked-up type. With no altitude at all it stands on the ground,
|
||||
// where it is, instead of at the airborne default.
|
||||
// The feed's own ICAO type classes the contact and picks its model from
|
||||
// the first fix; a looked-up type outranks it once one has answered.
|
||||
// A ground vehicle or ground station (a feed's ZVEH or GRND) is known
|
||||
// from its feed type alone, which no airframe lookup knows. With no
|
||||
// altitude at all, a contact drawn with a model built standing is on the
|
||||
// ground, where it is, instead of at the airborne default.
|
||||
const groundModel = (typeCode) =>
|
||||
drawnAsGroundModel(
|
||||
this.fleetModels(),
|
||||
@@ -122,12 +123,33 @@ export class FlightRecords {
|
||||
category,
|
||||
stickyText(callsign, prevMeta?.callsign),
|
||||
);
|
||||
const feedType = observation.typeCode || null;
|
||||
const typeCode =
|
||||
airframe?.typeCode ??
|
||||
(feedType && groundModel(feedType) ? feedType : null);
|
||||
const feedType = cleanType(observation.typeCode);
|
||||
// A surface category keeps only a feed's ground type: a C1 contact whose
|
||||
// feed names an airliner type stays a vehicle.
|
||||
// A feed's ground type holds only for a contact that behaves as one: an
|
||||
// airport vehicle reported airborne, or faster than a vehicle drives (a
|
||||
// test transponder, a drone), is classed as any other aircraft.
|
||||
const driving =
|
||||
!(Number.isFinite(velocity) && velocity > VEHICLE_MAX_SPEED_MPS) &&
|
||||
(on_ground === true ||
|
||||
(!Number.isFinite(reportedBaroAlt) &&
|
||||
!Number.isFinite(reportedGeoAlt)));
|
||||
const keepFeedType =
|
||||
Boolean(feedType) &&
|
||||
(feedType !== 'ZVEH' || driving) &&
|
||||
(!groundCategory(category) || GROUND_FEED_TYPES.has(feedType));
|
||||
// A ground station is fixed: it stands on the ground whatever height its
|
||||
// reports carry, as if they carried none.
|
||||
const station = keepFeedType && feedType === 'GRND';
|
||||
const baro_alt = station ? null : reportedBaroAlt;
|
||||
const geo_alt = station ? null : reportedGeoAlt;
|
||||
const typeLookedUp = airframe?.typeLookedUp === true;
|
||||
const typeCode = typeLookedUp
|
||||
? airframe.typeCode
|
||||
: ((keepFeedType ? feedType : null) ?? airframe?.typeCode ?? null);
|
||||
const onGround =
|
||||
on_ground === true ||
|
||||
station ||
|
||||
(!Number.isFinite(baro_alt) &&
|
||||
!Number.isFinite(geo_alt) &&
|
||||
groundModel(typeCode));
|
||||
@@ -261,6 +283,10 @@ export class FlightRecords {
|
||||
// within GROUND_FLOOR_CLAMP_RADIUS_KM of the viewer — the only ones
|
||||
// whose burial is visible. Cells warm in one batch after the loop.
|
||||
// Airborne only (grounded planes keep the surface-cache path above).
|
||||
// The ground under the contact in its render height's reference, where
|
||||
// the warm cache knows it: the surface it stands on, or the floor under a
|
||||
// low contact near the view. A landing is judged above it.
|
||||
let groundM = onGround ? surfaceM : null;
|
||||
if (
|
||||
!onGround &&
|
||||
renderAltitudeM < GROUND_FLOOR_WARM_MAX_ALT_M &&
|
||||
@@ -269,10 +295,8 @@ export class FlightRecords {
|
||||
approxDistanceKm(viewerLatDeg, viewerLonDeg, lat, lon) <=
|
||||
GROUND_FLOOR_CLAMP_RADIUS_KM))
|
||||
) {
|
||||
renderAltitudeM = floorAltitudeM(
|
||||
renderAltitudeM,
|
||||
cachedGroundFloor(lat, lon),
|
||||
);
|
||||
groundM = cachedGroundFloor(lat, lon);
|
||||
renderAltitudeM = floorAltitudeM(renderAltitudeM, groundM);
|
||||
floorWarmPoints.push({ lat, lon });
|
||||
}
|
||||
|
||||
@@ -280,7 +304,8 @@ export class FlightRecords {
|
||||
const groundFlipped =
|
||||
!!prevMeta && (prevMeta.onGround === true) !== onGround;
|
||||
// Store flight metadata for click-to-track labels
|
||||
const cat = stickyNumber(category, prevMeta?.category, null);
|
||||
// OpenSky's integer category, or a feed's ADS-B emitter category ("C1").
|
||||
const cat = stickyCategory(category, prevMeta?.category);
|
||||
const nextCallsign = stickyText(callsign, prevMeta?.callsign);
|
||||
// A route (and its airline) belongs to the callsign it was looked up for;
|
||||
// a new callsign drops it, so an old flight's route never shows under it.
|
||||
@@ -311,6 +336,7 @@ export class FlightRecords {
|
||||
geoAltitudeM,
|
||||
renderAltitudeM,
|
||||
renderAltitudeInvented,
|
||||
groundM: Number.isFinite(groundM) ? groundM : null,
|
||||
onGround,
|
||||
// Round 7: sticky airborne history — the landed fast-cull only
|
||||
// applies to contacts that actually flew this session.
|
||||
@@ -325,11 +351,9 @@ export class FlightRecords {
|
||||
),
|
||||
courseAnchor: course.anchor,
|
||||
category: cat,
|
||||
// An adsbdb-enriched type code outranks the coarse OpenSky category.
|
||||
klass: classifyAircraft({
|
||||
typeCode: airframe?.typeCode ?? null,
|
||||
category: cat,
|
||||
}),
|
||||
// A type code (the feed's, or a looked-up one) outranks the coarse
|
||||
// emitter category, from the first fix.
|
||||
klass: classifyAircraft({ typeCode, category: cat }),
|
||||
turnRateDps: prevMeta?.turnRateDps || 0,
|
||||
verticalRate: stickyNumber(vertical_rate, prevMeta?.verticalRate, null),
|
||||
// Analyst seam: OpenSky origin_country (state[2]) — additive, sticky
|
||||
@@ -362,8 +386,9 @@ export class FlightRecords {
|
||||
null,
|
||||
),
|
||||
// adsbdb enrichment — written by the enrichment callbacks, carried
|
||||
// across polls; a ground vehicle's or station's from the feed:
|
||||
// across polls; the type is the feed's own until a lookup answers:
|
||||
typeCode,
|
||||
typeLookedUp,
|
||||
typeName: airframe?.typeName ?? null,
|
||||
registration: airframe?.registration ?? null,
|
||||
airline: routeHeld ? (airframe.airline ?? null) : null,
|
||||
@@ -428,6 +453,7 @@ export class FlightRecords {
|
||||
for (const [id, meta] of this.data) {
|
||||
this.airframes.set(id, {
|
||||
typeCode: meta.typeCode,
|
||||
typeLookedUp: meta.typeLookedUp,
|
||||
typeName: meta.typeName,
|
||||
registration: meta.registration,
|
||||
airline: meta.airline,
|
||||
@@ -452,13 +478,54 @@ export class FlightRecords {
|
||||
}
|
||||
}
|
||||
|
||||
/** An ADS-B emitter category as a feed gives it ("A3", "C1"). */
|
||||
const EMITTER_CATEGORY = /^[A-D][0-7]$/;
|
||||
|
||||
/**
|
||||
* A contact's category, kept across polls that omit it: OpenSky's integer
|
||||
* category or an ADS-B emitter category string, else the last one, else null.
|
||||
* @param {*} next
|
||||
* @param {*} prev
|
||||
* @returns {number|string|null}
|
||||
*/
|
||||
function stickyCategory(next, prev) {
|
||||
if (Number.isFinite(next)) return next;
|
||||
const text = typeof next === 'string' ? next.trim().toUpperCase() : '';
|
||||
if (EMITTER_CATEGORY.test(text)) return text;
|
||||
return prev ?? null;
|
||||
}
|
||||
|
||||
/** A feed's ICAO type designator, upper case, or null. */
|
||||
function cleanType(value) {
|
||||
const text = typeof value === 'string' ? value.trim().toUpperCase() : '';
|
||||
return text || null;
|
||||
}
|
||||
|
||||
/** The types a feed gives airport vehicles (ZVEH) and ground stations (GRND). */
|
||||
const GROUND_FEED_TYPES = new Set(['ZVEH', 'GRND']);
|
||||
/** The fastest an airport vehicle drives, m/s (144 km/h); faster, it is no vehicle. */
|
||||
const VEHICLE_MAX_SPEED_MPS = 40;
|
||||
|
||||
/** Per loaded fleet model set: whether a type, category and callsign rule draw a ground model. */
|
||||
const groundModelCaches = new WeakMap();
|
||||
|
||||
/**
|
||||
* Whether an emitter category is a surface one: a vehicle or an obstacle
|
||||
* (ADS-B C1 to C5, OpenSky 16 to 20).
|
||||
* @param {string|number|null} category
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function groundCategory(category) {
|
||||
if (Number.isInteger(category)) return category >= 16 && category <= 20;
|
||||
return typeof category === 'string' && /^C[1-5]$/i.test(category.trim());
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether an aircraft of this type, emitter category and callsign is drawn
|
||||
* with a model built standing on the ground (catalog category `other`: an
|
||||
* airport vehicle, a ground station's mast). False before the set loads.
|
||||
* airport vehicle, a ground station's mast). A surface emitter category
|
||||
* (C1 to C5, OpenSky 16 to 20) always is. Otherwise, before the set loads,
|
||||
* whether the type is one a feed gives ground vehicles and stations.
|
||||
* Answered once per type, category and callsign rule matched.
|
||||
* @param {object|null} set The loaded fleet model set.
|
||||
* @param {string|null} typeCode
|
||||
@@ -467,7 +534,11 @@ const groundModelCaches = new WeakMap();
|
||||
* @returns {boolean}
|
||||
*/
|
||||
function drawnAsGroundModel(set, typeCode, category, callsign) {
|
||||
if (!set || !typeCode) return false;
|
||||
if (groundCategory(category)) return true;
|
||||
if (!typeCode) return false;
|
||||
// Before the set loads, the feed's own ground types: an airport vehicle
|
||||
// must not be drawn as an aircraft until the set says what it is.
|
||||
if (!set) return GROUND_FEED_TYPES.has(typeCode.trim().toUpperCase());
|
||||
let cache = groundModelCaches.get(set);
|
||||
if (!cache) groundModelCaches.set(set, (cache = new Map()));
|
||||
const rule = aircraftCallsignRule(set.types, typeCode, callsign);
|
||||
|
||||
@@ -283,6 +283,7 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
|
||||
observation({
|
||||
id: 'v1',
|
||||
typeCode: 'ZVEH',
|
||||
speedMps: 8,
|
||||
callsign: 'FIRE 2',
|
||||
...noAltitude,
|
||||
}),
|
||||
@@ -298,26 +299,175 @@ test('a ground vehicle or station with no altitude stands on the ground; an airc
|
||||
assert.equal(mast.onGround, true);
|
||||
assert.equal(mast.typeCode, 'GRND');
|
||||
// An airliner with no altitude keeps the airborne default, and its feed
|
||||
// type still waits for the airframe lookup.
|
||||
// type from the first fix.
|
||||
const plane = store.receive(
|
||||
observation({ id: 'p1', typeCode: 'A320', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(plane.onGround, false);
|
||||
assert.equal(plane.altitude, 10000);
|
||||
assert.equal(plane.typeCode, null);
|
||||
// A vehicle reporting an altitude is placed by it.
|
||||
assert.equal(plane.typeCode, 'A320');
|
||||
// An "airport vehicle" reported airborne is no vehicle (a drone, a test
|
||||
// transponder): it is placed by its altitude and classed as an aircraft.
|
||||
const reported = store.receive(
|
||||
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 12 }),
|
||||
observation({ id: 'v2', typeCode: 'ZVEH', baroAltitudeM: 762 }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(reported.onGround, false);
|
||||
// Before the model set loads nothing is grounded by its model.
|
||||
const unloaded = records().receive(
|
||||
observation({ id: 'v3', typeCode: 'ZVEH', ...noAltitude }),
|
||||
assert.equal(reported.typeCode, null);
|
||||
assert.notEqual(reported.klass, 'vehicle');
|
||||
// Nor is one on the ground faster than a vehicle drives.
|
||||
const fast = store.receive(
|
||||
observation({
|
||||
id: 'v4',
|
||||
typeCode: 'ZVEH',
|
||||
onGround: true,
|
||||
speedMps: 77,
|
||||
...noAltitude,
|
||||
}),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(unloaded.onGround, false);
|
||||
assert.notEqual(fast.klass, 'vehicle');
|
||||
// A ground station stands on the ground whatever height it reports.
|
||||
const high = store.receive(
|
||||
observation({ id: 'm2', typeCode: 'GRND', baroAltitudeM: 11880 }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(high.onGround, true);
|
||||
assert.equal(high.klass, 'station');
|
||||
assert.equal(high.altitude, 0);
|
||||
assert.ok(
|
||||
!(high.renderAltitudeM > 1000),
|
||||
`drawn at ${high.renderAltitudeM} m`,
|
||||
);
|
||||
// Before the model set loads, the feed's ground types already count: an
|
||||
// airport vehicle is never drawn as an aircraft first.
|
||||
const early = records();
|
||||
const unloaded = early.receive(
|
||||
observation({ id: 'v3', typeCode: 'ZVEH', speedMps: 8, ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(unloaded.onGround, true);
|
||||
assert.equal(unloaded.typeCode, 'ZVEH');
|
||||
const earlyPlane = early.receive(
|
||||
observation({ id: 'p2', typeCode: 'A320', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(earlyPlane.onGround, false);
|
||||
assert.equal(earlyPlane.typeCode, 'A320');
|
||||
});
|
||||
|
||||
test('airport vehicles and ground stations take their class from the first fix', () => {
|
||||
// Before the model set loads, and after.
|
||||
for (const store of [records(), records(() => fleetSet)]) {
|
||||
const klass = (fields) =>
|
||||
store.receive(observation({ callsign: '', ...fields }), view()).meta
|
||||
.klass;
|
||||
// An airport vehicle reports itself on the ground, at a vehicle's speed.
|
||||
const driving = { onGround: true, speedMps: 8 };
|
||||
assert.equal(klass({ id: 'v1', typeCode: 'ZVEH', ...driving }), 'vehicle');
|
||||
assert.equal(
|
||||
klass({ id: 'v2', typeCode: 'ZVEH', callsign: 'FIRE 2', ...driving }),
|
||||
'vehicle',
|
||||
);
|
||||
assert.equal(klass({ id: 'v3', category: 'C1' }), 'vehicle');
|
||||
assert.equal(klass({ id: 'v4', category: 'C2' }), 'vehicle');
|
||||
assert.equal(klass({ id: 'm1', typeCode: 'GRND' }), 'station');
|
||||
assert.equal(klass({ id: 'm2', category: 'C4' }), 'station');
|
||||
// An aircraft's feed type outranks its emitter category.
|
||||
assert.equal(
|
||||
klass({ id: 'p1', typeCode: 'A320', category: 'A7' }),
|
||||
'airliner',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
test("an aircraft's feed type classes it from the first fix, until a lookup answers", () => {
|
||||
for (const store of [records(), records(() => fleetSet)]) {
|
||||
// A helicopter whose feed names its type, with an airliner-like category.
|
||||
const first = store.receive(
|
||||
observation({
|
||||
id: 'h1',
|
||||
callsign: 'NHC47',
|
||||
typeCode: 'ec45',
|
||||
category: 'A3',
|
||||
}),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(first.typeCode, 'EC45');
|
||||
assert.equal(first.klass, 'helicopter');
|
||||
assert.equal(first.typeLookedUp, false);
|
||||
// A later row without the type keeps it.
|
||||
const quiet = store.receive(
|
||||
observation({ id: 'h1', callsign: 'NHC47', category: 'A3' }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(quiet.klass, 'helicopter');
|
||||
assert.equal(quiet.typeCode, 'EC45');
|
||||
// A looked-up type outranks the feed's on every later poll and reset.
|
||||
quiet.typeCode = 'EC35';
|
||||
quiet.typeLookedUp = true;
|
||||
quiet.typeName = 'Airbus Helicopters H135';
|
||||
const after = store.receive(
|
||||
observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(after.typeCode, 'EC35');
|
||||
assert.equal(after.typeName, 'Airbus Helicopters H135');
|
||||
assert.equal(after.klass, 'helicopter');
|
||||
store.reset();
|
||||
const again = store.receive(
|
||||
observation({ id: 'h1', callsign: 'NHC47', typeCode: 'B738' }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(again.typeCode, 'EC35');
|
||||
// No type anywhere: the emitter category classes it.
|
||||
const bare = store.receive(
|
||||
observation({ id: 'h2', category: 'A7' }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(bare.typeCode, null);
|
||||
assert.equal(bare.klass, 'helicopter');
|
||||
}
|
||||
});
|
||||
|
||||
test('a surface emitter category stands on the ground, before and after the model set loads', () => {
|
||||
const noAltitude = { baroAltitudeM: null, ellipsoidAltitudeM: null };
|
||||
for (const store of [records(), records(() => fleetSet)]) {
|
||||
for (const [id, category] of [
|
||||
['c1', 'C1'],
|
||||
['c2', 'C2'],
|
||||
['c3', 'C3'],
|
||||
['c5', 'C5'],
|
||||
['o16', 16],
|
||||
['o20', 20],
|
||||
]) {
|
||||
const meta = store.receive(
|
||||
observation({ id, category, callsign: '', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(meta.onGround, true, `${id} stands on the ground`);
|
||||
assert.equal(meta.altitude, 0, id);
|
||||
}
|
||||
// An aircraft category with no altitude keeps the airborne default.
|
||||
const plane = store.receive(
|
||||
observation({ id: 'a3', category: 'A3', ...noAltitude }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(plane.onGround, false);
|
||||
// A feed's aircraft type on a surface category does not make it an aircraft.
|
||||
const odd = store.receive(
|
||||
observation({
|
||||
id: 'c9',
|
||||
category: 'C1',
|
||||
typeCode: 'A320',
|
||||
...noAltitude,
|
||||
}),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(odd.klass, 'vehicle');
|
||||
assert.equal(odd.onGround, true);
|
||||
}
|
||||
});
|
||||
|
||||
test('a contact reported with no course faces the way its newer fixes went', () => {
|
||||
@@ -365,3 +515,38 @@ test('a contact reported with no course faces the way its newer fixes went', ()
|
||||
taxi(30.188, 20);
|
||||
assert.equal(course(), 0);
|
||||
});
|
||||
|
||||
test('a low contact near the view carries the ground under it; others carry none', () => {
|
||||
const store = new FlightRecords({
|
||||
geoidHeight: () => 40,
|
||||
cachedGroundFloor: () => 1656,
|
||||
floorAltitudeM: (altitude, ground) =>
|
||||
Math.max(altitude, ground ?? -Infinity),
|
||||
fleetModels: () => null,
|
||||
});
|
||||
const denver = { latitude: 39.85, longitude: -104.67 };
|
||||
const near = { ...view(), viewerLatDeg: 39.8, viewerLonDeg: -104.7 };
|
||||
// Landing at Denver: 1,900 m above the ellipsoid over 1,656 m ground.
|
||||
const landing = store.receive(
|
||||
observation({ id: 'l1', ...denver, ellipsoidAltitudeM: 1900 }),
|
||||
near,
|
||||
).meta;
|
||||
assert.equal(landing.groundM, 1656);
|
||||
// At cruise the ground is not read.
|
||||
const cruise = store.receive(
|
||||
observation({
|
||||
id: 'c1',
|
||||
...denver,
|
||||
ellipsoidAltitudeM: 11000,
|
||||
baroAltitudeM: 11000,
|
||||
}),
|
||||
near,
|
||||
).meta;
|
||||
assert.equal(cruise.groundM, null);
|
||||
// Nor without a view to be near.
|
||||
const away = store.receive(
|
||||
observation({ id: 'a1', ...denver, ellipsoidAltitudeM: 1900 }),
|
||||
view(),
|
||||
).meta;
|
||||
assert.equal(away.groundM, null);
|
||||
});
|
||||
@@ -2,13 +2,12 @@ import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
} from './modelSpec.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { isEmergency } from '../../data/aircraftEmergency.js';
|
||||
import {
|
||||
MIL_TINT,
|
||||
EMERGENCY_TINT,
|
||||
VEHICLE_TINT,
|
||||
FLEET_TINT,
|
||||
TRACKED_CYAN,
|
||||
GROUND_SCALE,
|
||||
COCKPIT_CIVILIAN_COLOR,
|
||||
} from './policy.js';
|
||||
@@ -32,14 +31,16 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/** Fleet (untracked) billboard tint: red while broadcasting an emergency,
|
||||
* amber for known-military, white otherwise.
|
||||
* Ground traffic gets NO special tint (owner verdict 2026-07-03 field test). */
|
||||
* orange amber for an airport vehicle, amber for known-military, white
|
||||
* otherwise. Grounded aircraft get NO special tint (owner verdict
|
||||
* 2026-07-03 field test). */
|
||||
|
||||
function _fleetBillboardColor(
|
||||
icao24,
|
||||
info = flightState.records.data.get(icao24),
|
||||
) {
|
||||
if (_isEmergency(icao24, info)) return EMERGENCY_TINT;
|
||||
if (info?.klass === 'vehicle') return VEHICLE_TINT;
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : FLEET_TINT;
|
||||
}
|
||||
|
||||
@@ -53,13 +54,10 @@ export function createRendering({
|
||||
return isMilitaryIcao(icao24) ? MIL_TINT : COCKPIT_CIVILIAN_COLOR;
|
||||
}
|
||||
|
||||
/** Fleet billboard scale: per-class scale, ×GROUND_SCALE while grounded. */
|
||||
/** Fleet billboard scale: one size for every class, ×GROUND_SCALE while grounded. */
|
||||
|
||||
function _fleetBillboardScale(icao24, klass) {
|
||||
return (
|
||||
(CLASS_SCALE_2D[klass] || 1) *
|
||||
(flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
function _fleetBillboardScale(icao24) {
|
||||
return flightState.records.data.get(icao24)?.onGround ? GROUND_SCALE : 1;
|
||||
}
|
||||
|
||||
/** The fleet model an aircraft draws with, by its type and emitter category. */
|
||||
@@ -82,11 +80,10 @@ export function createRendering({
|
||||
const _iconKind = (icao24, klass) =>
|
||||
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
|
||||
|
||||
/** Model colour: the mesh's own (white), tinted cyan while tracked and red
|
||||
* while broadcasting an emergency. */
|
||||
/** Model colour: the mesh's own (white), tinted red while broadcasting an
|
||||
* emergency. Tracking never recolours it. */
|
||||
|
||||
function _modelColor(icao24) {
|
||||
if (icao24 === flightState._trackedIcao) return TRACKED_CYAN;
|
||||
return _isEmergency(icao24) ? EMERGENCY_TINT : policy.MODEL_WHITE;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
// src/layers/flights/rendering.test.mjs
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
|
||||
import { createRendering as createFlightsRendering } from './rendering.js';
|
||||
import { createRendering as createMilitaryRendering } from '../military/rendering.js';
|
||||
|
||||
function rendering(create) {
|
||||
const data = new Map([
|
||||
['light', { klass: 'light' }],
|
||||
['quadjet', { klass: 'quadjet' }],
|
||||
['vehicle', { klass: 'vehicle' }],
|
||||
['parked', { klass: 'quadjet', onGround: true }],
|
||||
]);
|
||||
return create({
|
||||
flightState: { records: { data } },
|
||||
services: {
|
||||
militaryRegistry: { isMilitaryIcao: () => false },
|
||||
aircraftPresentation: { tr3bIconKind: () => null },
|
||||
focus: { focusNowMs: () => 0, getFocusTarget: () => null },
|
||||
},
|
||||
parts: {},
|
||||
layer: {},
|
||||
resolveAsset: (url) => url,
|
||||
});
|
||||
}
|
||||
|
||||
test('Flights draws every class at one size, smaller on the ground', () => {
|
||||
const r = rendering(createFlightsRendering);
|
||||
for (const id of ['light', 'quadjet', 'vehicle']) {
|
||||
assert.equal(r._fleetBillboardScale(id), 1, id);
|
||||
}
|
||||
assert.equal(r._fleetBillboardScale('parked'), 0.8);
|
||||
});
|
||||
|
||||
test('Military draws every class at its one size, smaller on the ground', () => {
|
||||
const r = rendering(createMilitaryRendering);
|
||||
const size = r._fleetBillboardScale('light');
|
||||
for (const id of ['quadjet', 'vehicle']) {
|
||||
assert.equal(r._fleetBillboardScale(id), size, id);
|
||||
}
|
||||
assert.ok(Math.abs(r._fleetBillboardScale('parked') - size * 0.8) < 1e-12);
|
||||
});
|
||||
@@ -56,8 +56,16 @@ export function createFlightSnapshotRenderer({
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
* `handover`: the first live snapshot after the clock came back to live: it
|
||||
* stands in for every contact too, and those it has keep their icon and
|
||||
* model and ease on from where they are drawn; of those it lacks, only
|
||||
* those absence keeps (judged by their newest fix) stay.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
return function applySnapshot(
|
||||
snapshot,
|
||||
viewer,
|
||||
{ replace = false, handover = false } = {},
|
||||
) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
@@ -254,7 +262,7 @@ export function createFlightSnapshotRenderer({
|
||||
// freshness change and the cockpit contract all land on the row's
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
icons._planIcon(icao24, handover ? { handover } : undefined);
|
||||
// Poll-path type or category change: same model resync rule as the
|
||||
// enrichment path — the fleet model or its scale may have changed.
|
||||
if (
|
||||
@@ -294,6 +302,23 @@ export function createFlightSnapshotRenderer({
|
||||
// EXCEPTION: likely-landed planes (last fix low + slow) get only
|
||||
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
|
||||
// feed gap, and the full grace left phantom planes parked at airports.
|
||||
// Back at live, a contact it lacks is from the time the clock left: it
|
||||
// goes at once, unless absence keeps it as any poll would (a partial or
|
||||
// retaining snapshot, the tracked aircraft), judged by its newest fix.
|
||||
// No missed-poll grace, and a landed tracked aircraft is not kept.
|
||||
const absenceAtHandover = (icao24) => {
|
||||
const likelyLanded = queries._likelyLanded(icao24);
|
||||
const judged = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded,
|
||||
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
return judged === 'stale' && icao24 !== flightState._trackedIcao
|
||||
? 'remove'
|
||||
: judged;
|
||||
};
|
||||
const absentIds = [];
|
||||
for (const icao24 of flightState._icons.ids()) {
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
@@ -301,13 +326,15 @@ export function createFlightSnapshotRenderer({
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
: handover
|
||||
? absenceAtHandover(icao24)
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -334,7 +361,8 @@ export function createFlightSnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
// The tracked contact at the new time: its trail starts there. Back at
|
||||
// live its trail goes on.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
|
||||
@@ -266,6 +266,18 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drSpeedMps = null;
|
||||
|
||||
/** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's,
|
||||
* the speed it is drawn at (0 while it waits for its fixes), for motion
|
||||
* only; panels show the reported ground speed (`displayedKinematics`). */
|
||||
|
||||
flightState._drSpeedPlaced = false;
|
||||
|
||||
/** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed
|
||||
* it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail
|
||||
* ends where it is drawn rather than at the layer's display delay. */
|
||||
|
||||
flightState._cachedDRPlaced = false;
|
||||
|
||||
flightState._drCourseHold = false;
|
||||
|
||||
/** Sibling scratch: whether the position `_deadReckon` just returned came from
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CYAN_TRANSPARENT, TRACKED_CYAN } from './policy.js';
|
||||
import { trackedIconColor } from '../../data/trackedAircraftIcon.js';
|
||||
import { createModelRecord } from '../../data/modelRecord.js';
|
||||
import {
|
||||
aircraftIconTestSeams,
|
||||
@@ -217,9 +217,11 @@ export function createTesting({
|
||||
/** Evaluate the production tracked-billboard handoff colour for focused tests. */
|
||||
|
||||
function _trackedBillboardColorForTest() {
|
||||
return parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? CYAN_TRANSPARENT
|
||||
: TRACKED_CYAN;
|
||||
const icao24 = flightState._trackedIcao;
|
||||
const color = parts.rendering._fleetBillboardColor(icao24);
|
||||
return parts.rendering._modelOwnsVisual(icao24)
|
||||
? trackedIconColor(color, 0)
|
||||
: color;
|
||||
}
|
||||
|
||||
/** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */
|
||||
@@ -254,15 +256,20 @@ export function createTesting({
|
||||
}
|
||||
|
||||
/** How the tracked billboard is drawn (`_trackedBillboardLook`,
|
||||
* `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */
|
||||
* `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet
|
||||
* icon is (`_fleetLook`, `_fleetBillboardColor`). */
|
||||
|
||||
function _trackedIconLookForTest(icao24) {
|
||||
return {
|
||||
tracked: {
|
||||
...parts.tracking._trackedBillboardLook(),
|
||||
sprite: parts.tracking._trackedSprite(icao24),
|
||||
color: parts.tracking._trackedIconColor(),
|
||||
},
|
||||
fleet: {
|
||||
...parts.icons._fleetLook(icao24),
|
||||
color: parts.rendering._fleetBillboardColor(icao24),
|
||||
},
|
||||
fleet: parts.icons._fleetLook(icao24),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
createTrackedAircraftIcon,
|
||||
isOtherTrackedIconSet,
|
||||
trackedContactHolder,
|
||||
trackedIconColor,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { julianToEpochMs } from '../../geo/julian.js';
|
||||
@@ -28,10 +29,12 @@ import {
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
COCKPIT_AIR_ALL_ADD_M,
|
||||
COCKPIT_AIR_ALL_KEEP_M,
|
||||
COCKPIT_AIR_PROX_ADD_M,
|
||||
COCKPIT_AIR_PROX_KEEP_M,
|
||||
TRAIL_MAX_POINTS,
|
||||
TRAIL_COLOR,
|
||||
CYAN_TRANSPARENT,
|
||||
TRACKED_CYAN,
|
||||
STALE_ALPHA,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
@@ -46,6 +49,7 @@ import {
|
||||
trailBodySegments,
|
||||
trailHeadCurvePoints,
|
||||
trailHeadStartFix,
|
||||
trailTimeAt,
|
||||
} from '../../data/trailContinuity.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
@@ -61,8 +65,6 @@ function aircraftPickId(hit) {
|
||||
return isOtherTrackedIconSet(hit.set, 'flights') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
const STALE_CYAN = Object.freeze([...TRACKED_CYAN.slice(0, 3), STALE_ALPHA]);
|
||||
|
||||
export function createTracking({
|
||||
flightState,
|
||||
services,
|
||||
@@ -222,11 +224,13 @@ export function createTracking({
|
||||
);
|
||||
distancesSquared.push([icao24, distanceSquared(eye, position)]);
|
||||
}
|
||||
// The AIR band follows the 3D mode, not the 3D model radius.
|
||||
const all = flightState._models3dMode === 'all';
|
||||
const next = nextCockpitNearContacts(
|
||||
previous,
|
||||
distancesSquared,
|
||||
parts.rendering._modelAddDistM(),
|
||||
parts.rendering._modelKeepDistM(),
|
||||
all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M,
|
||||
all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M,
|
||||
);
|
||||
flightState._cockpitNearContacts = next;
|
||||
for (const icao24 of previous)
|
||||
@@ -390,12 +394,46 @@ export function createTracking({
|
||||
);
|
||||
}
|
||||
|
||||
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
|
||||
/** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */
|
||||
|
||||
function _trailBodyCountNow() {
|
||||
return trailBodyCount(
|
||||
return trailBodyCount(flightState._trailFixes, _trailDisplayMs());
|
||||
}
|
||||
|
||||
/**
|
||||
* The time on its trail at which a host-supplied placement draws the
|
||||
* aircraft, read off the trail where it is drawn (`trailTimeAt`): such a
|
||||
* placement draws at a delay of its own, not this layer's. NaN when this
|
||||
* layer's own motion draws it, or the trail has no pair to read.
|
||||
* @returns {number} Epoch ms or NaN.
|
||||
*/
|
||||
function _placedTrailMs() {
|
||||
if (!parts.motion._trackedPlaced?.()) return NaN;
|
||||
return trailTimeAt(
|
||||
flightState._trailFixes,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
parts.motion._trackedDisplayCached(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The time the trail runs up to: the time the aircraft is drawn at, now −
|
||||
* the display delay, or where a placement draws it. Otherwise the trail
|
||||
* ends short of a placed aircraft, or runs on ahead of it.
|
||||
* @returns {number} Epoch ms.
|
||||
*/
|
||||
function _trailDisplayMs() {
|
||||
const placedMs = _placedTrailMs();
|
||||
return Number.isFinite(placedMs)
|
||||
? placedMs
|
||||
: flightState.now() - displayDelayMs(flightState);
|
||||
}
|
||||
|
||||
/** Whether the trail holds no report behind the aircraft yet: this
|
||||
* layer's own motion draws it before its oldest fix. Never for an
|
||||
* aircraft a placement draws: its trail is read where it is drawn. */
|
||||
function _trailWarmingUp() {
|
||||
return (
|
||||
!Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -412,7 +450,7 @@ export function createTracking({
|
||||
if (
|
||||
!flightState._trackedIcao ||
|
||||
!flightState._trailFixes.length ||
|
||||
parts.motion._isTrackWarmingUp()
|
||||
_trailWarmingUp()
|
||||
)
|
||||
return [];
|
||||
const head =
|
||||
@@ -435,7 +473,7 @@ export function createTracking({
|
||||
trailHeadCurvePoints(
|
||||
flightState._trailFixes,
|
||||
flightState._trailBodyCount,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
_trailDisplayMs(),
|
||||
),
|
||||
head,
|
||||
parts.motion._trackedModelCenterWorld(),
|
||||
@@ -697,10 +735,11 @@ export function createTracking({
|
||||
// Hand the contact back to its icon only now: settling floors a grounded
|
||||
// contact, and while it still read as tracked its tracked model owned the
|
||||
// visual, so the floor would have stepped aside.
|
||||
if (flightState._icons?.has(clearedIcao)) {
|
||||
flightState._icons.setShown(clearedIcao, true);
|
||||
// Its fleet model, kept loaded while it was selected, takes it back in
|
||||
// this frame; the icon shows only when there is no loaded one.
|
||||
parts.rendering._handBackDeselected(clearedIcao);
|
||||
if (flightState._icons?.has(clearedIcao))
|
||||
parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg });
|
||||
}
|
||||
parts.icons._applyIconPresentation(clearedIcao);
|
||||
clearTrackedSubjectContext('flights');
|
||||
_emitAwarenessEvent('gev:awareness-subject-cleared', {
|
||||
@@ -813,14 +852,18 @@ export function createTracking({
|
||||
return { text: '', dimmed: false };
|
||||
}
|
||||
|
||||
/** The tracked billboard's colour: cyan, faded while stale, clear while the 3D model is the visual. */
|
||||
/** The tracked billboard's colour: the contact's own fleet colour (tracking
|
||||
* never recolours it), faded while stale, clear while the 3D model is the
|
||||
* visual. */
|
||||
|
||||
function _trackedIconColor() {
|
||||
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
|
||||
return CYAN_TRANSPARENT;
|
||||
return _trackedStaleCue(flightState._trackedIcao).dimmed
|
||||
? STALE_CYAN
|
||||
: TRACKED_CYAN;
|
||||
const icao24 = flightState._trackedIcao;
|
||||
const color = parts.rendering._fleetBillboardColor(icao24);
|
||||
if (parts.rendering._modelOwnsVisual(icao24))
|
||||
return trackedIconColor(color, 0);
|
||||
return _trackedStaleCue(icao24).dimmed
|
||||
? trackedIconColor(color, STALE_ALPHA)
|
||||
: color;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -912,10 +955,7 @@ export function createTracking({
|
||||
width: look.size[0],
|
||||
height: look.size[1],
|
||||
get scale() {
|
||||
return parts.rendering._fleetBillboardScale(
|
||||
icao24,
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
);
|
||||
return parts.rendering._fleetBillboardScale(icao24);
|
||||
},
|
||||
scaleByDistance: look.scaleByDistance,
|
||||
};
|
||||
@@ -1078,13 +1118,13 @@ export function createTracking({
|
||||
imageLod: _trackedBillboardLook().imageLod,
|
||||
sprite,
|
||||
position: getTrackedPosition,
|
||||
// Solid cyan (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// or model still loading); transparent once the tracked model is actually up.
|
||||
color: _trackedIconColor,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
// street level would otherwise bury the cyan icon inside the runway
|
||||
// street level would otherwise bury the icon inside the runway
|
||||
// skin, so it draws over depth like the fleet icon set; its
|
||||
// shared-host tracked card is top-composited separately.
|
||||
rotation: () => {
|
||||
@@ -1092,6 +1132,8 @@ export function createTracking({
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
// A ground station's mast stands upright.
|
||||
if (tracked.klass === 'station') return 0;
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
|
||||
@@ -4,7 +4,12 @@ import * as Cesium from 'cesium';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { TRAIL_MAX_POINTS } from './policy.js';
|
||||
import { trailHeadJoins, trailPairBreaks } from '../../data/trailContinuity.js';
|
||||
import {
|
||||
insertTrailFix,
|
||||
trailHeadJoins,
|
||||
trailPairBreaks,
|
||||
trailTimeAt,
|
||||
} from '../../data/trailContinuity.js';
|
||||
|
||||
const MINUTE = 60_000;
|
||||
const HOUR = 60 * MINUTE;
|
||||
@@ -92,6 +97,8 @@ function trackedHarness({
|
||||
nowMs,
|
||||
floor,
|
||||
head = null,
|
||||
placed = false,
|
||||
warmingUp = false,
|
||||
} = {}) {
|
||||
const trail = recordingTrail();
|
||||
const svc = services({ trails: trail, floor });
|
||||
@@ -122,7 +129,9 @@ function trackedHarness({
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_isTrackWarmingUp: () => warmingUp,
|
||||
_trackedPlaced: () => placed,
|
||||
_trackedDisplayCached: () => head,
|
||||
_trackedTrailCached: () => head,
|
||||
_trackedDisplayPosition: () => head,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
@@ -410,3 +419,136 @@ test('every waypoint of a 24 h history survives, and the trail stays within TRAI
|
||||
// The oldest go first: the newest live fix is still the last point.
|
||||
assert.equal(fixes[fixes.length - 1].timeMs, liveStart);
|
||||
});
|
||||
|
||||
/** A trail of `count` reports one minute apart flying east from (50, 1). */
|
||||
function eastTrail(t0, count) {
|
||||
const fixes = [];
|
||||
for (let i = 0; i < count; i++)
|
||||
insertTrailFix(
|
||||
fixes,
|
||||
Cesium.Cartesian3.fromDegrees(1 + i * 0.12, 50, 10_000),
|
||||
t0 + i * MINUTE,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
return fixes;
|
||||
}
|
||||
|
||||
test('the time on the trail is read where the aircraft is drawn', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const fixes = eastTrail(t0, 4);
|
||||
const at = (lon) =>
|
||||
trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(lon, 50, 10_000));
|
||||
// Halfway between the second and third reports.
|
||||
assert.ok(Math.abs(at(1.18) - (t0 + 1.5 * MINUTE)) < 2_000);
|
||||
// On a report.
|
||||
assert.ok(Math.abs(at(1.24) - (t0 + 2 * MINUTE)) < 2_000);
|
||||
// Past the newest report the time runs on; before the oldest it runs back.
|
||||
assert.ok(Math.abs(at(1.42) - (t0 + 3.5 * MINUTE)) < 2_000);
|
||||
assert.ok(Math.abs(at(0.94) - (t0 - 0.5 * MINUTE)) < 2_000);
|
||||
// Nothing to read without a pair of reports, or without a position.
|
||||
assert.ok(Number.isNaN(trailTimeAt(fixes.slice(0, 1), fixes[0].position)));
|
||||
assert.ok(Number.isNaN(trailTimeAt(fixes, null)));
|
||||
});
|
||||
|
||||
test('the time on the trail is never read across a break', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const fixes = eastTrail(t0, 2);
|
||||
// An hour later, far on: a new segment.
|
||||
insertTrailFix(
|
||||
fixes,
|
||||
Cesium.Cartesian3.fromDegrees(20, 50, 10_000),
|
||||
t0 + HOUR,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
insertTrailFix(
|
||||
fixes,
|
||||
Cesium.Cartesian3.fromDegrees(20.12, 50, 10_000),
|
||||
t0 + HOUR + MINUTE,
|
||||
TRAIL_MAX_POINTS,
|
||||
);
|
||||
assert.equal(fixes[2].breakBefore, true);
|
||||
// Halfway along the gap is not on the trail: it is read on the newest pair.
|
||||
const at = trailTimeAt(fixes, Cesium.Cartesian3.fromDegrees(10, 50, 10_000));
|
||||
assert.ok(at <= t0 + HOUR, `read ${at - t0} ms in, across the break`);
|
||||
});
|
||||
|
||||
test('a placed aircraft drawn ahead of the display delay keeps its trail joined to it', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2, 3].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 1 + i * 0.12,
|
||||
}));
|
||||
// The layer's own delay puts the aircraft before its first fix (warming
|
||||
// up), but the placement draws it between the third and fourth reports.
|
||||
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 10_000);
|
||||
const placed = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3.5 * MINUTE,
|
||||
head: near,
|
||||
placed: true,
|
||||
warmingUp: true,
|
||||
});
|
||||
placed.flightState._displayDelay = { currentMs: 10 * MINUTE };
|
||||
placed.tracking._startTrail('abc123');
|
||||
// The body runs to the last report behind the aircraft, none ahead of it.
|
||||
assert.deepEqual(
|
||||
placed.trail.last().map((segment) => segment.length > 0),
|
||||
[true],
|
||||
);
|
||||
const body = placed.trail.last()[0];
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(
|
||||
body[body.length - 1],
|
||||
Cesium.Cartesian3.fromDegrees(1.24, 50, 10_000),
|
||||
) < 1,
|
||||
);
|
||||
// The head joins it to the aircraft.
|
||||
const drawn = headPositions(placed);
|
||||
assert.ok(drawn.length >= 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1e-6);
|
||||
|
||||
// The layer's own motion, warming up, draws no head and no body.
|
||||
const own = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3.5 * MINUTE,
|
||||
head: near,
|
||||
warmingUp: true,
|
||||
});
|
||||
own.flightState._displayDelay = { currentMs: 10 * MINUTE };
|
||||
own.tracking._startTrail('abc123');
|
||||
assert.deepEqual(own.trail.last(), []);
|
||||
assert.deepEqual(headPositions(own), []);
|
||||
});
|
||||
|
||||
test('a placed aircraft drawn behind the display delay has no trail ahead of it', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2, 3].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 1 + i * 0.12,
|
||||
}));
|
||||
// The layer's delay would draw every report; the placement holds the
|
||||
// aircraft between the first and second.
|
||||
const behind = Cesium.Cartesian3.fromDegrees(1.06, 50, 10_000);
|
||||
const { trail, tracking, flightState } = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 4 * MINUTE,
|
||||
head: behind,
|
||||
placed: true,
|
||||
});
|
||||
flightState._displayDelay = { currentMs: 0 };
|
||||
tracking._startTrail('abc123');
|
||||
// One report behind it: no line yet, and nothing ahead of the aircraft.
|
||||
assert.deepEqual(trail.last(), []);
|
||||
const drawn = headPositions({ tracking });
|
||||
assert.equal(drawn.length, 2);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(
|
||||
drawn[0],
|
||||
Cesium.Cartesian3.fromDegrees(1, 50, 10_000),
|
||||
) < 1,
|
||||
);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[1], behind) < 1e-6);
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
import { FLEET_TINT, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
|
||||
// A tracked trail is the aircraft's reports joined along the curve the icon
|
||||
// is drawn along between them, so the icon always sits on its trail and a
|
||||
@@ -116,7 +116,11 @@ function harness({
|
||||
flightState.now = () => clock;
|
||||
flightState._positionHistory.set(ICAO, fixes);
|
||||
const parts = {
|
||||
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
|
||||
rendering: {
|
||||
_modelOwnsVisual: () => false,
|
||||
_modelSpec: () => ({}),
|
||||
_fleetBillboardColor: () => FLEET_TINT,
|
||||
},
|
||||
queries: { _contactLabel: (id, info) => info?.callsign || id },
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services: svc, parts });
|
||||
@@ -797,6 +801,11 @@ test('a stalled feed dims the tracked plane as STALE', () => {
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.deepEqual(
|
||||
h.tracking._trackedIconColor().slice(0, 3),
|
||||
FLEET_TINT.slice(0, 3),
|
||||
'faded in its own colour, never recoloured',
|
||||
);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
|
||||
@@ -24,7 +24,8 @@ export function localAdsbClass(record, meta = null) {
|
||||
const category = record?.category || null;
|
||||
return {
|
||||
klass: classifyAircraft({ typeCode, category }),
|
||||
evidence: Boolean(typeCode) || /^(?:A[1-7]|B1)$/.test(category || ''),
|
||||
evidence:
|
||||
Boolean(typeCode) || /^(?:A[1-7]|B1|C[1-5])$/.test(category || ''),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -1,5 +1,7 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import { rotorFrame } from '../../data/rotorFrames.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import {
|
||||
courseScreenRotation,
|
||||
stabilizeScreenRotation,
|
||||
@@ -133,6 +135,8 @@ export function createLocalAdsbLayer({
|
||||
} = services.context;
|
||||
const { registerPickOwner, unregisterPickOwner } = services.picking;
|
||||
const color = hexColor(LOCAL_ADSB_COLOR);
|
||||
// An airport vehicle's tint, as in the Flights layer.
|
||||
const vehicleColor = hexColor(VEHICLE_TINT_CSS);
|
||||
const uatRingColor = hexColor(LOCAL_ADSB_UAT_RING_COLOR);
|
||||
|
||||
let viewer = null;
|
||||
@@ -265,9 +269,7 @@ export function createLocalAdsbLayer({
|
||||
}
|
||||
|
||||
function billboardScale(marker) {
|
||||
return (
|
||||
(CLASS_SCALE_2D[marker.klass] || 1) * (marker.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
return marker.onGround ? GROUND_SCALE : 1;
|
||||
}
|
||||
|
||||
/** Class silhouette and per-class scale (×0.8 on the ground), magenta. */
|
||||
@@ -350,18 +352,34 @@ export function createLocalAdsbLayer({
|
||||
};
|
||||
}
|
||||
|
||||
/** A marker's icon, where and how it now draws. */
|
||||
function markerItem(marker, basis) {
|
||||
/**
|
||||
* A marker's icon, where and how it now draws: a helicopter's rotor frame
|
||||
* at `at` (still on the ground), an airport vehicle in its own tint, a
|
||||
* ground station's mast upright.
|
||||
*/
|
||||
function markerItem(marker, basis, at) {
|
||||
const kind = marker.iconKind ?? 'airliner';
|
||||
return {
|
||||
id: marker.id,
|
||||
pos: marker.position,
|
||||
image: aircraftIcon(marker.iconKind ?? 'airliner'),
|
||||
image: aircraftIcon(
|
||||
kind,
|
||||
undefined,
|
||||
kind === 'helicopter'
|
||||
? rotorFrame(marker.id, at, {
|
||||
onGround: marker.onGround,
|
||||
speedMps: Number.isFinite(marker.record?.groundSpeedKt)
|
||||
? marker.record.groundSpeedKt * KNOT_MPS
|
||||
: null,
|
||||
})
|
||||
: undefined,
|
||||
),
|
||||
size: [MARKER_SPRITE.width, MARKER_SPRITE.height],
|
||||
scale: marker.iconScale ?? 1,
|
||||
color,
|
||||
color: kind === 'vehicle' ? vehicleColor : color,
|
||||
scaleByDistance: MARKER_SPRITE.scaleByDistance,
|
||||
rotationMode: 'screen',
|
||||
rotation: markerRotation(marker, basis),
|
||||
rotation: kind === 'station' ? 0 : markerRotation(marker, basis),
|
||||
// The 3D model, once loaded and placed, is the visual instead.
|
||||
show: !marker.modelOwnsVisual,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
@@ -390,11 +408,12 @@ export function createLocalAdsbLayer({
|
||||
function drawMarkers() {
|
||||
if (!sets) return;
|
||||
const basis = cameraBasis();
|
||||
const at = now();
|
||||
const icons = [];
|
||||
const rings = [];
|
||||
for (const marker of markers.values()) {
|
||||
if (!marker.position) continue;
|
||||
icons.push(markerItem(marker, basis));
|
||||
icons.push(markerItem(marker, basis, at));
|
||||
if (marker.uat) rings.push(ringItem(marker));
|
||||
}
|
||||
if (icons.length) sets.markers.upsert(icons);
|
||||
|
||||
@@ -2,9 +2,10 @@ import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { VEHICLE_TINT_CSS } from '../../data/aircraftClass.js';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { aircraftIcon } from '../../data/aircraftIcons.js';
|
||||
import { ROTOR_STILL_FRAME, rotorFrame } from '../../data/rotorFrames.js';
|
||||
import {
|
||||
createLocalAdsbLayer,
|
||||
HEARD_BY_RECEIVER,
|
||||
@@ -196,13 +197,14 @@ function fakeFeeds(initial = {}) {
|
||||
};
|
||||
}
|
||||
|
||||
/** A viewer whose camera looks down on (0°, 0°) from 50 km. */
|
||||
/** A viewer whose camera looks down on (0°, 0°) from 2 km: within the 3 km
|
||||
* model radius of an aircraft there on the ground or at 10,000 ft. */
|
||||
function modelViewer() {
|
||||
return fakeViewer(
|
||||
{ scene: {} },
|
||||
{
|
||||
height: 50_000,
|
||||
position: { x: 6_378_137 + 50_000, y: 0, z: 0 },
|
||||
height: 2_000,
|
||||
position: { x: 6_378_137 + 2_000, y: 0, z: 0 },
|
||||
direction: { x: -1, y: 0, z: 0 },
|
||||
},
|
||||
);
|
||||
@@ -238,7 +240,7 @@ test('enabling Local ADS-B asks the shared tuner for 1090 MHz; disabling leaves
|
||||
);
|
||||
});
|
||||
|
||||
test('local aircraft use their class silhouette and scale in magenta', async (t) => {
|
||||
test('local aircraft use their class silhouette at one size in magenta', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const { layer, draw, calls } = await enabledLayer(receiver, clock);
|
||||
@@ -265,8 +267,17 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
|
||||
assert.equal(typeof readEntityRecord(carrier)?.displayPosition, 'function');
|
||||
|
||||
const heli = () => iconOf(draw, 'local-adsb:a0b702');
|
||||
assert.equal(heli().image, aircraftIcon('helicopter'));
|
||||
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter);
|
||||
// Airborne, its rotor turns: the frame of its own phase at the layer's time.
|
||||
assert.equal(
|
||||
heli().image,
|
||||
aircraftIcon(
|
||||
'helicopter',
|
||||
undefined,
|
||||
rotorFrame('local-adsb:a0b702', clock.now),
|
||||
),
|
||||
);
|
||||
assert.equal(heli().scale, 1, 'every class draws at one size');
|
||||
assert.equal(icon.scale, heli().scale);
|
||||
assert.deepEqual(
|
||||
heli().color,
|
||||
MAGENTA,
|
||||
@@ -285,18 +296,48 @@ test('local aircraft use their class silhouette and scale in magenta', async (t)
|
||||
icao: 'a0b702',
|
||||
category: 'A7',
|
||||
onGround: true,
|
||||
groundSpeedKt: 0,
|
||||
lastPositionAt: 100_500,
|
||||
}),
|
||||
],
|
||||
});
|
||||
await layer.update();
|
||||
assert.equal(heli().scale, CLASS_SCALE_2D.helicopter * 0.8);
|
||||
assert.equal(heli().scale, 0.8);
|
||||
// Parked on the ground its rotor holds still.
|
||||
assert.equal(
|
||||
heli().image,
|
||||
aircraftIcon('helicopter', undefined, ROTOR_STILL_FRAME),
|
||||
);
|
||||
|
||||
const [detectable] = layer.getDetectableObjects();
|
||||
assert.equal(detectable.sourceId, 'a0b702');
|
||||
assert.equal(detectable.type, 'AIR');
|
||||
});
|
||||
|
||||
test('local airport vehicles draw the amber vehicle sprite, ground stations the upright mast', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
const { layer, draw } = await enabledLayer(receiver, clock);
|
||||
t.after(() => layer.destroy());
|
||||
receiver.set({
|
||||
aircraft: [
|
||||
record({ icao: 'a0c001', category: 'C1', trackDeg: 90 }),
|
||||
record({ icao: 'a0c002', category: 'C2', trackDeg: 90 }),
|
||||
record({ icao: 'a0c003', category: 'C3', trackDeg: 90 }),
|
||||
],
|
||||
});
|
||||
await layer.update();
|
||||
for (const id of ['a0c001', 'a0c002']) {
|
||||
const icon = iconOf(draw, `local-adsb:${id}`);
|
||||
assert.equal(icon.image, aircraftIcon('vehicle'), id);
|
||||
assert.deepEqual(icon.color, hexColor(VEHICLE_TINT_CSS), id);
|
||||
}
|
||||
const mast = iconOf(draw, 'local-adsb:a0c003');
|
||||
assert.equal(mast.image, aircraftIcon('station'));
|
||||
assert.deepEqual(mast.color, MAGENTA);
|
||||
assert.equal(mast.rotation, 0, 'upright whatever its track');
|
||||
});
|
||||
|
||||
test('the heading slews toward a new track instead of snapping', async (t) => {
|
||||
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
|
||||
const clock = { now: 100_000 };
|
||||
|
||||
@@ -8,18 +8,21 @@ import {
|
||||
sub,
|
||||
} from '../../geo/vector.js';
|
||||
import { aircraftLayerModelSpec } from '../flights/modelSpec.js';
|
||||
import { fleetModelSet, loadFleetModelSet } from '../../data/fleetModels.js';
|
||||
import {
|
||||
fleetModelSet,
|
||||
fleetPartTable,
|
||||
loadFleetModelSet,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { aircraftLayerPartState } from '../../data/modelPartDrivers.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
import {
|
||||
FLEET_DR_INTERVAL_MS,
|
||||
MODEL_ALL_ADD_M,
|
||||
MODEL_ALL_KEEP_M,
|
||||
MODEL_ADD_M,
|
||||
MODEL_ALT_CEIL_M,
|
||||
MODEL_HEADING_OFFSET_DEG,
|
||||
MODEL_KEEP_M,
|
||||
MODEL_MAX,
|
||||
MODEL_MAX_ALL,
|
||||
MODEL_MIN_PX,
|
||||
MODEL_PROX_ADD_M,
|
||||
MODEL_PROX_KEEP_M,
|
||||
} from '../flights/policy.js';
|
||||
import {
|
||||
AIRCRAFT_ENVIRONMENT_MAP_OPTIONS,
|
||||
@@ -165,6 +168,36 @@ export function createLocalAdsbModels({
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The moving parts an aircraft's model is posed with, from its record
|
||||
* (`aircraftLayerPartState`). The receiver knows no ground height, so its gear
|
||||
* follows the approach rule by its reported altitude, climb and speed. An
|
||||
* airport vehicle is a road vehicle (`groundVehiclePartState`): its wheels
|
||||
* roll with its speed.
|
||||
*/
|
||||
function partsOf(marker, spec) {
|
||||
const table = fleetPartTable(fleetModelSet(), spec.model);
|
||||
if (!table) return undefined;
|
||||
const record = marker.record ?? {};
|
||||
const finite = (v) => (Number.isFinite(v) ? v : null);
|
||||
const speedMps =
|
||||
finite(record.groundSpeedKt) === null
|
||||
? null
|
||||
: record.groundSpeedKt * KNOT_MPS;
|
||||
return aircraftLayerPartState(table, {
|
||||
klass: marker.klass,
|
||||
onGround: marker.onGround === true,
|
||||
heightAboveGroundM: null,
|
||||
altitudeM:
|
||||
finite(record.altitudeFt) === null ? null : record.altitudeFt * 0.3048,
|
||||
verticalRateMps:
|
||||
finite(record.verticalRateFpm) === null
|
||||
? null
|
||||
: (record.verticalRateFpm * 0.3048) / 60,
|
||||
speedMps,
|
||||
});
|
||||
}
|
||||
|
||||
function regime(preferences, pose) {
|
||||
if (!preferences?.models3d) return false;
|
||||
return pose.height < MODEL_ALT_CEIL_M;
|
||||
@@ -173,19 +206,17 @@ export function createLocalAdsbModels({
|
||||
function refreshEligibility(markers, preferences, pose) {
|
||||
const all = preferences.models3dMode === 'all';
|
||||
const cap = all ? MODEL_MAX_ALL : MODEL_MAX;
|
||||
const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M;
|
||||
const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M;
|
||||
const candidates = [];
|
||||
for (const [id, marker] of markers) {
|
||||
if (!marker.position) continue;
|
||||
const distanceSq = distanceSquared(pose.position, marker.position);
|
||||
if (distanceSq > keepM * keepM) continue;
|
||||
if (distanceSq > MODEL_KEEP_M * MODEL_KEEP_M) continue;
|
||||
candidates.push([id, distanceSq, inView(pose, marker.position)]);
|
||||
}
|
||||
candidates.sort((a, b) => a[1] - b[1]);
|
||||
eligible = selectModelEligible(candidates, {
|
||||
cap,
|
||||
addDistSq: addM * addM,
|
||||
addDistSq: MODEL_ADD_M * MODEL_ADD_M,
|
||||
isModeled: (id) => models.has(id),
|
||||
});
|
||||
release([...models.keys()].filter((id) => !eligible.has(id)));
|
||||
@@ -246,6 +277,7 @@ export function createLocalAdsbModels({
|
||||
const gltf = fleetModelSet()?.bytes?.get(spec.model);
|
||||
noteAsset(record, url, spec.bellyM);
|
||||
const position = placement(id, marker);
|
||||
const parts = partsOf(marker, spec);
|
||||
const shown =
|
||||
Boolean(position) && horizon.isPointVisible(marker.position);
|
||||
items.push({
|
||||
@@ -263,11 +295,11 @@ export function createLocalAdsbModels({
|
||||
roll: 0,
|
||||
},
|
||||
scale: spec.scale,
|
||||
minPixelSize: MODEL_MIN_PX,
|
||||
// The mesh's own colours (white, multiplied).
|
||||
tint: WHITE,
|
||||
colorBlend: aircraftModelBlend(false),
|
||||
environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled,
|
||||
...(parts ? { parts } : {}),
|
||||
show: shown,
|
||||
});
|
||||
if (shown && record.ready) marker.modelOwnsVisual = true;
|
||||
|
||||
@@ -26,6 +26,59 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState._lastCamPoseSig = '';
|
||||
}
|
||||
|
||||
/**
|
||||
* The contacts drawn now that the first live snapshot after the clock came
|
||||
* back to live lacks (the tracked one too): the snapshot judges them as a
|
||||
* poll judges any absence (see the snapshot renderer).
|
||||
* @param {{records: Array<{id: string}>}} snapshot
|
||||
* @returns {Set<string>}
|
||||
*/
|
||||
function absentAtHandover(snapshot) {
|
||||
const present = new Set(snapshot.records.map((record) => record.id));
|
||||
const drawn = [...(flightState._icons?.ids() ?? [])];
|
||||
if (flightState._trackedIcao) drawn.push(flightState._trackedIcao);
|
||||
return new Set(drawn.filter((id) => !present.has(id)));
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live: forget how every contact moved, as at a jump, but keep the
|
||||
* tracked trail, and keep the contacts `kept` (absentAtHandover) as they
|
||||
* were: their record, fixes and course. Each was last seen at its newest
|
||||
* fix, not when it was loaded, so absence judges how old it really is.
|
||||
* @param {Set<string>} kept
|
||||
*/
|
||||
function handOverMotion(kept) {
|
||||
const held = [];
|
||||
for (const id of kept)
|
||||
held.push([
|
||||
id,
|
||||
flightState.records.data.get(id),
|
||||
flightState._positionHistory.get(id),
|
||||
flightState._displayCourse.get(id),
|
||||
]);
|
||||
forgetPlacedAircraft(
|
||||
services?.placement,
|
||||
[...flightState._positionHistory.keys()].filter((id) => !kept.has(id)),
|
||||
);
|
||||
flightState.records.reset();
|
||||
flightState._positionHistory.clear();
|
||||
flightState._displayCourse.clear();
|
||||
flightState._groundSnap.clear();
|
||||
flightState._drReconcileValid = false;
|
||||
flightState._cachedDRFrame = -1;
|
||||
flightState._cachedDRPosition = null;
|
||||
flightState._lastCamPoseSig = '';
|
||||
for (const [id, meta, history, course] of held) {
|
||||
if (meta)
|
||||
flightState.records.data.set(id, {
|
||||
...meta,
|
||||
observedReceiptMs: meta.newestFixMs ?? meta.observedReceiptMs,
|
||||
});
|
||||
if (history) flightState._positionHistory.set(id, history);
|
||||
if (course !== undefined) flightState._displayCourse.set(id, course);
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop every contact: the time has none to show, or the clock went live. */
|
||||
function clear() {
|
||||
if (flightState._trackedIcao)
|
||||
@@ -39,5 +92,5 @@ export function createClockFollow({ flightState, services, parts }) {
|
||||
flightState.feed._lastUpdate = null;
|
||||
}
|
||||
|
||||
return { resetMotion, clear };
|
||||
return { resetMotion, absentAtHandover, handOverMotion, clear };
|
||||
}
|
||||
@@ -10,7 +10,10 @@ import { createLifecycle } from './lifecycle.js';
|
||||
import { createTesting } from './testing.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one military-flight layer with application-owned scene services. */
|
||||
export function createMilitaryFlightLayer({
|
||||
@@ -46,10 +49,19 @@ export function createMilitaryFlightLayer({
|
||||
parts.ingestion = createIngestion({
|
||||
feed: flightState.feed,
|
||||
applySnapshot: (snapshot, viewer, options) => {
|
||||
// At another time the snapshot takes the place of every contact: how
|
||||
// each moved belongs to the time the clock left. Back at live too, but
|
||||
// the contacts it lacks are kept as they were for it to judge.
|
||||
if (options?.replace) parts.clockFollow.resetMotion();
|
||||
if (options?.handover) {
|
||||
parts.clockFollow.handOverMotion(
|
||||
parts.clockFollow.absentAtHandover(snapshot),
|
||||
);
|
||||
}
|
||||
return applySnapshot(snapshot, viewer, options);
|
||||
},
|
||||
followsClock: () => flightState.timeline.active(),
|
||||
timedAnswer: snapshotAnswer,
|
||||
setSourceLabel: (source) => {
|
||||
layer.source = source;
|
||||
},
|
||||
@@ -65,9 +77,7 @@ export function createMilitaryFlightLayer({
|
||||
load: (atMs, { signal, replace }) =>
|
||||
parts.ingestion.methods.loadAt(atMs, { signal, replace }),
|
||||
clear: () => parts.clockFollow.clear(),
|
||||
resumeLive: () => {
|
||||
layer.update(flightState._viewer).catch(() => {});
|
||||
},
|
||||
resumeLive: () => parts.ingestion.methods.resumeLive(flightState._viewer),
|
||||
});
|
||||
|
||||
Object.assign(
|
||||
|
||||
@@ -11,6 +11,7 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
applyPendingTrackingRestore,
|
||||
followsClock = () => false,
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
const methods = {
|
||||
async update(viewer, { signal = null } = {}) {
|
||||
@@ -20,13 +21,27 @@ export function createIngestion({
|
||||
await acquire(viewer, { signal });
|
||||
},
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once, and let this live
|
||||
* snapshot stand in for every contact. Those it has keep their
|
||||
* icon and model and move on from where they are drawn; those it lacks
|
||||
* go. Resolves true once it is applied, else false (nothing to poll yet,
|
||||
* or the poll failed); rejects with an AbortError when it was dropped.
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async resumeLive(viewer) {
|
||||
return (await acquire(viewer, { handover: true })) === true;
|
||||
},
|
||||
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every contact when `replace`. Resolves
|
||||
* whether it was applied.
|
||||
* whether it was applied: `{ reachMs }`, the newest fix its records
|
||||
* carry, when they carry fixes; else true, or false when it was not.
|
||||
* @param {number} atMs
|
||||
* @param {{signal?: AbortSignal|null, replace?: boolean, viewer?: object}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async loadAt(atMs, { signal = null, replace = false, viewer = null } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies.
|
||||
@@ -37,7 +52,10 @@ export function createIngestion({
|
||||
},
|
||||
};
|
||||
|
||||
async function acquire(viewer, { signal = null, atMs, replace = false }) {
|
||||
async function acquire(
|
||||
viewer,
|
||||
{ signal = null, atMs, replace = false, handover = false },
|
||||
) {
|
||||
const nowMs = Date.now();
|
||||
const timed = atMs !== undefined;
|
||||
const trackingRefreshEpoch = ++feed._trackingRefreshEpoch;
|
||||
@@ -77,7 +95,9 @@ export function createIngestion({
|
||||
: null);
|
||||
const accepted = timed
|
||||
? applySnapshot(snapshot, viewer, { replace })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
: handover
|
||||
? applySnapshot(snapshot, viewer, { handover: true })
|
||||
: applySnapshot(snapshot, viewer);
|
||||
feed._count = accepted.count;
|
||||
feed._lastUpdate = snapshot.observedAtMs;
|
||||
feed._lastTrackingRefreshOutcome = {
|
||||
@@ -88,7 +108,8 @@ export function createIngestion({
|
||||
};
|
||||
console.log(`[Data:Military] Updated: ${feed._count} aircraft`);
|
||||
applyPendingTrackingRestore();
|
||||
return true;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (e) {
|
||||
if (updateSignal.aborted || e?.name === 'AbortError') {
|
||||
throw new DOMException('Military update aborted', 'AbortError');
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createMilitarySnapshotRenderer } from './snapshotRenderer.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createIngestion, createMilitaryFeed } from './ingestion.js';
|
||||
import { MilitaryFlightRecords } from './records.js';
|
||||
import { createClockFollow } from './clockFollow.js';
|
||||
|
||||
// Back at live from another time, the first live snapshot stands in for
|
||||
// every military contact: those it has keep their icon, and only those it
|
||||
// lacks go (src/time/snapshotTimeline.js).
|
||||
|
||||
function harness() {
|
||||
const iconIds = new Set();
|
||||
const calls = [];
|
||||
const flightState = {
|
||||
_viewer: null,
|
||||
_icons: {
|
||||
has: (id) => iconIds.has(id),
|
||||
ids: () => [...iconIds],
|
||||
get count() {
|
||||
return iconIds.size;
|
||||
},
|
||||
},
|
||||
_positionHistory: new Map(),
|
||||
_groundSnap: { forget() {} },
|
||||
_models: new Map(),
|
||||
_trackedModel: null,
|
||||
_trackedIcao: null,
|
||||
records: { data: new Map() },
|
||||
};
|
||||
const parts = {
|
||||
rendering: {
|
||||
_modelOwnsVisual: () => false,
|
||||
_syncModelToClass() {},
|
||||
_groundSampleExclusions: () => ({ sets: [] }),
|
||||
},
|
||||
icons: {
|
||||
_addIcon: (id) => {
|
||||
calls.push(['add', id]);
|
||||
iconIds.add(id);
|
||||
},
|
||||
_applyIconPresentation() {},
|
||||
_planIcon: (id, options) => calls.push(['plan', id, options]),
|
||||
_forgetContact: (id) => {
|
||||
calls.push(['forget', id]);
|
||||
iconIds.delete(id);
|
||||
},
|
||||
},
|
||||
};
|
||||
const services = {
|
||||
camera: { trackedModelScaleForPixelCap: () => 1 },
|
||||
focus: {},
|
||||
groundFloor: { cachedGroundFloor: () => null, GROUND_FLOOR_LIFT_M: 0.5 },
|
||||
meshFloor: { sampleMeshFloorCells() {} },
|
||||
};
|
||||
parts.motion = createMotion({ flightState, services, parts, layer: {} });
|
||||
const records = new MilitaryFlightRecords({
|
||||
geoidHeight: () => 0,
|
||||
cachedGroundFloor: () => null,
|
||||
floorAltitudeM: (altitude) => altitude,
|
||||
now: () => Date.now(),
|
||||
});
|
||||
flightState.records = records;
|
||||
flightState.now = () => Date.now();
|
||||
flightState._displayCourse = new Map();
|
||||
flightState._groundSnap.clear = () => {};
|
||||
const apply = createMilitarySnapshotRenderer({
|
||||
flightState,
|
||||
records,
|
||||
groundFloor: { warmGroundFloor() {}, cachedGroundFloor: () => null },
|
||||
militaryRegistry: { registerMilitaryIcaos() {} },
|
||||
rendering: parts.rendering,
|
||||
tracking: {},
|
||||
motion: parts.motion,
|
||||
icons: parts.icons,
|
||||
queries: { _likelyLanded: () => false },
|
||||
});
|
||||
const clockFollow = createClockFollow({
|
||||
flightState,
|
||||
services: { placement: null },
|
||||
parts: { tracking: { _clearTrail() {} } },
|
||||
});
|
||||
// `ids`: an id, or [id, fix age ms].
|
||||
const snapshot = (ids, fields) => ({
|
||||
observedAtMs: Date.now(),
|
||||
records: ids.map((entry, k) => {
|
||||
const [id, ageMs = 5_000] = [entry].flat();
|
||||
return {
|
||||
id,
|
||||
reference: id,
|
||||
longitude: -97 + k,
|
||||
latitude: 30,
|
||||
baroAltitudeM: 3_000,
|
||||
onGround: false,
|
||||
speedMps: 200,
|
||||
courseDeg: 90,
|
||||
positionTimeMs: Date.now() - ageMs,
|
||||
};
|
||||
}),
|
||||
complete: true,
|
||||
...fields,
|
||||
});
|
||||
return {
|
||||
calls,
|
||||
iconIds,
|
||||
apply(ids, options, fields) {
|
||||
calls.length = 0;
|
||||
return apply(snapshot(ids, fields), null, options);
|
||||
},
|
||||
// Back at live, as the layer applies its first live snapshot.
|
||||
handOver(ids, fields) {
|
||||
calls.length = 0;
|
||||
const live = snapshot(ids, fields);
|
||||
clockFollow.handOverMotion(clockFollow.absentAtHandover(live));
|
||||
return apply(live, null, { handover: true });
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('the first live military snapshot keeps the icons of contacts it has and drops only those it lacks', () => {
|
||||
const h = harness();
|
||||
h.apply(['ae0001', 'ae0002']);
|
||||
h.handOver(['ae0001', 'ae0003']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
|
||||
assert.equal(
|
||||
h.calls.some(
|
||||
([kind, id]) => id === 'ae0001' && (kind === 'add' || kind === 'forget'),
|
||||
),
|
||||
false,
|
||||
);
|
||||
assert.deepEqual(
|
||||
h.calls.find(([kind, id]) => kind === 'plan' && id === 'ae0001'),
|
||||
['plan', 'ae0001', { handover: true }],
|
||||
);
|
||||
// A plain poll keeps a missing contact as its absence rules say.
|
||||
h.apply(['ae0001']);
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0001', 'ae0003']);
|
||||
});
|
||||
|
||||
test('back at live, only the first live military snapshot applied takes over; a failed poll says so', async () => {
|
||||
const applied = [];
|
||||
let fail = false;
|
||||
const feed = createMilitaryFeed({
|
||||
async getSnapshot() {
|
||||
if (fail) throw new Error('down');
|
||||
return { records: [], observedAtMs: Date.now(), freshness: 'current' };
|
||||
},
|
||||
});
|
||||
const { methods } = createIngestion({
|
||||
feed,
|
||||
applySnapshot: (_snapshot, _viewer, options) => {
|
||||
applied.push(options);
|
||||
return { count: 0, ids: new Set() };
|
||||
},
|
||||
setSourceLabel: () => {},
|
||||
applyPendingTrackingRestore: () => {},
|
||||
});
|
||||
assert.equal(await methods.resumeLive(null), true);
|
||||
await methods.update(null);
|
||||
assert.deepEqual(applied, [{ handover: true }, undefined]);
|
||||
fail = true;
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await methods.resumeLive(null), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live, a partial military snapshot keeps only contacts whose newest fix is recent', () => {
|
||||
const h = harness();
|
||||
h.apply([
|
||||
['ae0001', 3 * 3_600_000],
|
||||
['ae0002', 60_000],
|
||||
]);
|
||||
h.handOver(['ae0003'], { complete: false });
|
||||
assert.deepEqual([...h.iconIds].sort(), ['ae0002', 'ae0003']);
|
||||
});
|
||||
@@ -35,7 +35,6 @@ import {
|
||||
recoveryMs,
|
||||
limitCourseStep,
|
||||
} from '../../data/motionModel.js';
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import { placeLiveAircraft } from '../flights/placed.js';
|
||||
import {
|
||||
modelVisualAnchor,
|
||||
@@ -44,7 +43,6 @@ import {
|
||||
import {
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
MODEL_MIN_PX,
|
||||
BILLBOARD_SCALE,
|
||||
TRACKED_BILLBOARD_SCALE_BY_DISTANCE,
|
||||
DR_CORRECTION_MS,
|
||||
@@ -312,20 +310,17 @@ export function createMotion({
|
||||
const spec = parts.rendering._modelSpec(
|
||||
flightState.records.data.get(icao24),
|
||||
);
|
||||
// Drawn as the fleet draws it: its own size, never under MODEL_MIN_PX.
|
||||
// Drawn as the fleet draws it: at its true size.
|
||||
const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2));
|
||||
const projectedDiameterPx =
|
||||
(2 * spec.nativeRadiusM * spec.scale * focalLengthPx) / rangeM;
|
||||
return Math.max(MODEL_MIN_PX, projectedDiameterPx);
|
||||
return projectedDiameterPx;
|
||||
}
|
||||
|
||||
const sprite = readEntityRecord(flightState._trackedEntity)?.sprite;
|
||||
const width = sprite?.width ?? 28;
|
||||
const height = sprite?.height ?? 28;
|
||||
const scale =
|
||||
sprite?.scale ??
|
||||
BILLBOARD_SCALE *
|
||||
(CLASS_SCALE_2D[flightState.records.data.get(icao24)?.klass] || 1);
|
||||
const scale = sprite?.scale ?? BILLBOARD_SCALE;
|
||||
const scaleByDistance =
|
||||
sprite?.scaleByDistance ?? TRACKED_BILLBOARD_SCALE_BY_DISTANCE;
|
||||
const distanceScale = nearFarScalarValueAtDistance(scaleByDistance, rangeM);
|
||||
@@ -354,6 +349,8 @@ export function createMotion({
|
||||
const sameTrack =
|
||||
flightState._drReconcileValid && flightState._drReconcileIcao === icao24;
|
||||
const raw = _deadReckon(icao24, flightState._scratchDrRaw);
|
||||
flightState._cachedDRPlaced =
|
||||
Boolean(raw) && flightState._drSpeedPlaced === true;
|
||||
flightState._cachedDRCourse = flightState._drCourseDeg;
|
||||
flightState._cachedDRSpeedMps = flightState._drSpeedMps;
|
||||
flightState._cachedDRHold = flightState._drCourseHold;
|
||||
@@ -480,6 +477,16 @@ export function createMotion({
|
||||
* later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the
|
||||
* now-stable plane. Null when no valid fix (callers fall back to the icon position). */
|
||||
|
||||
/** Whether a host-supplied placement placed the tracked aircraft where
|
||||
* `_trackedDisplayCached` holds it this frame, rather than this layer's
|
||||
* own motion at its display delay. */
|
||||
|
||||
function _trackedPlaced() {
|
||||
return (
|
||||
_trackedDisplayCached() !== null && flightState._cachedDRPlaced === true
|
||||
);
|
||||
}
|
||||
|
||||
function _trackedDisplayCached() {
|
||||
return flightState._drReconcileValid &&
|
||||
flightState._drReconcileIcao === flightState._trackedIcao
|
||||
@@ -515,9 +522,8 @@ export function createMotion({
|
||||
}
|
||||
|
||||
/** The tracked model's rendered bounding radius (m), or 0 when no model of this
|
||||
* contact is drawing. Carries the scale it is drawn at, which may be
|
||||
* above `scale` to satisfy its pixel floor — the trail head has to be judged
|
||||
* against the size the operator SEES, not the nominal one. */
|
||||
* contact is drawing, at the scale it is drawn at — the trail head has to
|
||||
* be judged against the size the operator SEES. */
|
||||
/** World-space origin of the tracked model, or null when no model of this
|
||||
* contact is drawing. This is the centre the rendered bounding sphere is
|
||||
* measured from, so the trail clip and the envelope agree on one frame. */
|
||||
@@ -703,6 +709,7 @@ export function createMotion({
|
||||
_trackedFocusSizePx,
|
||||
_trackedDisplayPosition,
|
||||
_trackedDisplayCached,
|
||||
_trackedPlaced,
|
||||
_trackedVisualCached,
|
||||
_trackedModelCenterWorld,
|
||||
_trackedModelEnvelopeM,
|
||||
|
||||
@@ -31,10 +31,6 @@ export const BILLBOARD_SCALE = 0.7;
|
||||
|
||||
export const MIL_ICON_COLOR = rgba('#FFB800');
|
||||
|
||||
/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */
|
||||
|
||||
export const TRACKED_ICON_COLOR = rgba('#FFD166');
|
||||
|
||||
/** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */
|
||||
|
||||
export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS);
|
||||
@@ -61,21 +57,26 @@ export const MODEL_WHITE = rgba('#FFFFFF');
|
||||
export const GROUND_SCALE = 0.8;
|
||||
|
||||
// --- 3D model rendering (mirrors flights.js) -----------------------------------------
|
||||
// When enabled, military aircraft render as 3D glTF models once the camera is below
|
||||
// MODEL_ALT_CEIL_M (zoomed in); higher up they stay flat billboards. Eligibility is
|
||||
// FRUSTUM-based (on-screen), and the slots go to either the nearest planes ('proximity')
|
||||
// or every in-view plane ('all'), each backed by a hard cap so a draw-call explosion
|
||||
// can't tank the frame (no instancing yet). Each aircraft draws the fleet model of its
|
||||
// type, as the flights layer does; the amber tint sets this layer apart.
|
||||
// When enabled, a military aircraft draws as its 3D glTF model only within MODEL_ADD_M of the
|
||||
// camera (eye to aircraft); farther away it stays its icon. Models are drawn at their true size,
|
||||
// with no minimum pixel size. Eligibility is distance-based with on-screen priority, and the slots
|
||||
// go to either the nearest planes ('proximity') or every in-range plane ('all'): the two modes share
|
||||
// the radius and differ by their caps. Each aircraft draws the fleet model of its type, as the
|
||||
// flights layer does; the amber tint sets this layer apart.
|
||||
|
||||
export const MODEL_ALT_CEIL_M = 800000;
|
||||
// m: below this camera altitude, draw 3D models (raised so it's easy to trigger)
|
||||
export const MODEL_ADD_M = 3000;
|
||||
// model NEW planes within 3 km of the camera (mirror of flights.js)
|
||||
|
||||
export const MODEL_MIN_PX = 24;
|
||||
// floor so distant models stay visible without ballooning into a min-pixel blob (mirror of flights.js)
|
||||
export const MODEL_KEEP_M = 3600;
|
||||
// KEEP modeled planes out to 3.6 km (hysteresis, mirror of flights.js)
|
||||
|
||||
// Per-mode caps + radii — mirror of flights.js. Modes differ by RADIUS (not just cap) so Proximity
|
||||
// and All aren't identical when few planes are in range; on-screen planes win the cap (see flights.js).
|
||||
export const MODEL_HIGHEST_CONTACT_M = 30000;
|
||||
// m above the ellipsoid: no aircraft the layer draws flies higher (mirror of flights.js)
|
||||
|
||||
export const MODEL_ALT_CEIL_M = MODEL_HIGHEST_CONTACT_M + MODEL_KEEP_M;
|
||||
// m: above this camera altitude no contact can be within MODEL_KEEP_M (mirror of flights.js)
|
||||
|
||||
// Per-mode caps — mirror of flights.js; on-screen planes win the cap (see flights.js).
|
||||
|
||||
export const MODEL_MAX = 150;
|
||||
// 'proximity' cap
|
||||
@@ -83,32 +84,24 @@ export const MODEL_MAX = 150;
|
||||
export const MODEL_MAX_ALL = 350;
|
||||
// 'all' cap
|
||||
|
||||
export const MODEL_PROX_ADD_M = 150000;
|
||||
// proximity: model NEW planes within 150 km
|
||||
|
||||
export const MODEL_PROX_KEEP_M = 185000;
|
||||
// proximity: KEEP modeled planes out to 185 km
|
||||
|
||||
// Cockpit keeps the standard Display radii but lowers the GLB budget. Contacts
|
||||
// inside the selected band remain AIR silhouettes when they cannot own a model;
|
||||
// contacts outside the band use compact dots.
|
||||
|
||||
export const COCKPIT_MODEL_MAX = 60;
|
||||
// max concurrent GLBs in cockpit (never raises the map cap)
|
||||
|
||||
export const MODEL_ALL_ADD_M = 400000;
|
||||
// all: model NEW planes within 400 km (~to the horizon)
|
||||
// Cockpit's AIR band (mirror of flights.js): contacts inside it remain AIR
|
||||
// silhouettes when they cannot own a model; contacts outside it use compact
|
||||
// dots. Independent of the 3D model radius.
|
||||
|
||||
export const MODEL_ALL_KEEP_M = 450000;
|
||||
// all: KEEP modeled planes out to 450 km
|
||||
export const COCKPIT_AIR_PROX_ADD_M = 150000;
|
||||
|
||||
export const COCKPIT_AIR_PROX_KEEP_M = 185000;
|
||||
|
||||
export const COCKPIT_AIR_ALL_ADD_M = 400000;
|
||||
|
||||
export const COCKPIT_AIR_ALL_KEEP_M = 450000;
|
||||
|
||||
export const MODEL_HEADING_OFFSET_DEG = 180;
|
||||
// every fleet model is nose -X: opposite Cesium heading 0
|
||||
|
||||
/** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */
|
||||
|
||||
export const AMBER_TRANSPARENT = rgba('#FFB800', 0);
|
||||
|
||||
export const COCKPIT_CONTACT_SIZE_PX = 6;
|
||||
|
||||
/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */
|
||||
|
||||
@@ -109,6 +109,7 @@ export function createQueries({
|
||||
derivedSpeedMps: flightState._drSpeedMps,
|
||||
derivedTrackDeg: flightState._drCourseDeg,
|
||||
reportedSpeedMps: info?.speedMps,
|
||||
derivedFromPlacement: flightState._drSpeedPlaced === true,
|
||||
reportedTrackDeg: info?.track,
|
||||
});
|
||||
const carto = toLonLatH(basePos);
|
||||
@@ -249,11 +250,11 @@ export function createQueries({
|
||||
|
||||
/**
|
||||
* Live layer params.
|
||||
* `models3d` toggles 3D glTF jet-model rendering for the FLEET (altitude-gated): when on,
|
||||
* surrounding military aircraft become 3D models once the camera is zoomed in past
|
||||
* MODEL_ALT_CEIL_M. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`),
|
||||
* `models3d` toggles 3D glTF jet-model rendering for the FLEET: when on, military
|
||||
* aircraft within MODEL_ADD_M (3 km) of the camera become 3D models, drawn at their true
|
||||
* size. The TRACKED contact follows the same rule (`_trackedModelRegimeActive`),
|
||||
* so selecting a contact never turns its icon into a model or its model into an icon.
|
||||
* `models3dMode` is 'proximity' (nearest MODEL_MAX in view) or 'all' (every in-view plane).
|
||||
* `models3dMode` is 'proximity' (cap MODEL_MAX) or 'all' (cap MODEL_MAX_ALL); both use the 3 km radius.
|
||||
* @param {{models3d?: boolean, models3dMode?: 'proximity'|'all', selectedMilitaryTrackingId?: string|null}} params
|
||||
*/
|
||||
setParams(params = {}, { origin = 'programmatic' } = {}) {
|
||||
|
||||
@@ -1,4 +1,3 @@
|
||||
import { CLASS_SCALE_2D } from '../../data/aircraftClass.js';
|
||||
import {
|
||||
aircraftLayerModelSpec,
|
||||
aircraftModelSpecCacheKey,
|
||||
@@ -9,7 +8,6 @@ import {
|
||||
BILLBOARD_SCALE,
|
||||
GROUND_SCALE,
|
||||
MIL_ICON_COLOR,
|
||||
TRACKED_ICON_COLOR,
|
||||
EMERGENCY_ICON_COLOR,
|
||||
MODEL_WHITE,
|
||||
} from './policy.js';
|
||||
@@ -41,15 +39,11 @@ export function createRendering({
|
||||
return spec;
|
||||
}
|
||||
|
||||
/** Fleet icon scale: per-class scale, ×GROUND_SCALE while grounded. */
|
||||
/** Fleet icon scale: one size for every class, ×GROUND_SCALE while grounded. */
|
||||
|
||||
function _fleetBillboardScale(icao24) {
|
||||
const meta = flightState.records.data.get(icao24);
|
||||
return (
|
||||
BILLBOARD_SCALE *
|
||||
(CLASS_SCALE_2D[meta?.klass] || 1) *
|
||||
(meta?.onGround ? GROUND_SCALE : 1)
|
||||
);
|
||||
return BILLBOARD_SCALE * (meta?.onGround ? GROUND_SCALE : 1);
|
||||
}
|
||||
|
||||
/** Sprite kind for one contact's icon. Identity for every aircraft except
|
||||
@@ -61,11 +55,10 @@ export function createRendering({
|
||||
const _iconKind = (icao24, klass) =>
|
||||
tr3bIconKind(icao24, klass, { hot: flightState._irBoost });
|
||||
|
||||
/** Model colour: the mesh's own (white), tinted amber while tracked and red
|
||||
* while broadcasting an emergency. */
|
||||
/** Model colour: the mesh's own (white), tinted red while broadcasting an
|
||||
* emergency. Tracking never recolours it. */
|
||||
|
||||
function _modelColor(icao24) {
|
||||
if (icao24 === flightState._trackedIcao) return TRACKED_ICON_COLOR;
|
||||
const info = flightState.records.data.get(icao24);
|
||||
return isEmergency(info?.emergency) ? EMERGENCY_ICON_COLOR : MODEL_WHITE;
|
||||
}
|
||||
|
||||
@@ -55,8 +55,16 @@ export function createMilitarySnapshotRenderer({
|
||||
/**
|
||||
* `replace`: the snapshot is the world at another time (the world clock
|
||||
* jumped), so it stands in for every contact: one it lacks is gone at once.
|
||||
* `handover`: the first live snapshot after the clock came back to live: it
|
||||
* stands in for every contact too, and those it has keep their icon and
|
||||
* model and ease on from where they are drawn; of those it lacks, only
|
||||
* those absence keeps (judged by their newest fix) stay.
|
||||
*/
|
||||
return function applySnapshot(snapshot, viewer, { replace = false } = {}) {
|
||||
return function applySnapshot(
|
||||
snapshot,
|
||||
viewer,
|
||||
{ replace = false, handover = false } = {},
|
||||
) {
|
||||
// Before init (or after destroy) there is no icon set to draw into.
|
||||
if (!flightState._icons) return { count: 0, ids: new Set() };
|
||||
const currentIcaos = new Set();
|
||||
@@ -223,7 +231,7 @@ export function createMilitarySnapshotRenderer({
|
||||
// freshness change and the cockpit contract all land on the row's
|
||||
// style; motion re-plans from the updated history.
|
||||
icons._applyIconPresentation(icao24);
|
||||
icons._planIcon(icao24);
|
||||
icons._planIcon(icao24, handover ? { handover } : undefined);
|
||||
// Per-type fleet models: a type or category change can mean a
|
||||
// different model OR scale — resync the live model, any in-flight
|
||||
// load, and the tracked standalone (mirror of flights.js).
|
||||
@@ -279,6 +287,23 @@ export function createMilitarySnapshotRenderer({
|
||||
// EXCEPTION: likely-landed planes (last fix low + slow) get only
|
||||
// LANDED_MISSING_POLL_LIMIT — their disappearance means "landed", not a
|
||||
// feed gap, and the full grace left phantom planes parked at airports.
|
||||
// Back at live, a contact it lacks is from the time the clock left: it
|
||||
// goes at once, unless absence keeps it as any poll would (a partial or
|
||||
// retaining snapshot, the tracked aircraft), judged by its newest fix.
|
||||
// No missed-poll grace, and a landed tracked aircraft is not kept.
|
||||
const absenceAtHandover = (icao24) => {
|
||||
const likelyLanded = queries._likelyLanded(icao24);
|
||||
const judged = records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded,
|
||||
tracked: icao24 === flightState._trackedIcao && !likelyLanded,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
return judged === 'stale' && icao24 !== flightState._trackedIcao
|
||||
? 'remove'
|
||||
: judged;
|
||||
};
|
||||
const absentIds = [];
|
||||
for (const icao24 of flightState._icons.ids()) {
|
||||
if (!currentIcaos.has(icao24)) absentIds.push(icao24);
|
||||
@@ -286,13 +311,15 @@ export function createMilitarySnapshotRenderer({
|
||||
for (const icao24 of absentIds) {
|
||||
const absence = replace
|
||||
? 'remove'
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
: handover
|
||||
? absenceAtHandover(icao24)
|
||||
: records.absence(icao24, {
|
||||
complete: snapshot.complete,
|
||||
retainIds: snapshot.retainIds,
|
||||
likelyLanded: queries._likelyLanded(icao24),
|
||||
tracked: icao24 === flightState._trackedIcao,
|
||||
nowMs: flightState.now?.(),
|
||||
});
|
||||
if (absence === 'retain') continue;
|
||||
if (absence === 'stale') {
|
||||
icons._applyIconPresentation(icao24); // the faded freshness alpha
|
||||
@@ -319,7 +346,8 @@ export function createMilitarySnapshotRenderer({
|
||||
icons._forgetContact(icao24); // aged out: its 3D model goes too (no orphan / cap leak)
|
||||
}
|
||||
|
||||
// The tracked contact at the new time: its trail starts there.
|
||||
// The tracked contact at the new time: its trail starts there. Back at
|
||||
// live its trail goes on.
|
||||
if (
|
||||
replace &&
|
||||
flightState._trackedIcao &&
|
||||
|
||||
@@ -230,6 +230,18 @@ export function createFlightState({ source, services }) {
|
||||
|
||||
flightState._drSpeedMps = null;
|
||||
|
||||
/** Sibling scratch: whether `_drSpeedMps` is a host-supplied placement's,
|
||||
* the speed it is drawn at (0 while it waits for its fixes), for motion
|
||||
* only; panels show the reported ground speed (`displayedKinematics`). */
|
||||
|
||||
flightState._drSpeedPlaced = false;
|
||||
|
||||
/** Sibling of `_cachedDRPosition`: whether a host-supplied placement placed
|
||||
* it (`_drSpeedPlaced` as the tracked aircraft was drawn), so its trail
|
||||
* ends where it is drawn rather than at the layer's display delay. */
|
||||
|
||||
flightState._cachedDRPlaced = false;
|
||||
|
||||
flightState._drCourseHold = false;
|
||||
|
||||
/** Set by `_deadReckon`: following the clock, the time drawn is well
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { AMBER_TRANSPARENT, TRACKED_ICON_COLOR } from './policy.js';
|
||||
import { trackedIconColor } from '../../data/trackedAircraftIcon.js';
|
||||
import { createModelRecord } from '../../data/modelRecord.js';
|
||||
import {
|
||||
aircraftIconTestSeams,
|
||||
@@ -170,9 +170,11 @@ export function createTesting({
|
||||
/** Evaluate the production tracked-billboard handoff colour for focused tests. */
|
||||
|
||||
function _trackedBillboardColorForTest() {
|
||||
return parts.rendering._modelOwnsVisual(flightState._trackedIcao)
|
||||
? AMBER_TRANSPARENT
|
||||
: TRACKED_ICON_COLOR;
|
||||
const icao24 = flightState._trackedIcao;
|
||||
const color = parts.rendering._fleetBillboardColor(icao24);
|
||||
return parts.rendering._modelOwnsVisual(icao24)
|
||||
? trackedIconColor(color, 0)
|
||||
: color;
|
||||
}
|
||||
|
||||
/** Drive the exact fleet icon-to-model handoff used by `_fleetTick`. */
|
||||
@@ -194,15 +196,20 @@ export function createTesting({
|
||||
}
|
||||
|
||||
/** How the tracked billboard is drawn (`_trackedBillboardLook`,
|
||||
* `_trackedSprite`) next to how the contact's fleet icon is (`_fleetLook`). */
|
||||
* `_trackedSprite`, `_trackedIconColor`) next to how the contact's fleet
|
||||
* icon is (`_fleetLook`, `_fleetBillboardColor`). */
|
||||
|
||||
function _trackedIconLookForTest(icao24) {
|
||||
return {
|
||||
tracked: {
|
||||
...parts.tracking._trackedBillboardLook(),
|
||||
sprite: parts.tracking._trackedSprite(icao24),
|
||||
color: parts.tracking._trackedIconColor(),
|
||||
},
|
||||
fleet: {
|
||||
...parts.icons._fleetLook(icao24),
|
||||
color: parts.rendering._fleetBillboardColor(icao24),
|
||||
},
|
||||
fleet: parts.icons._fleetLook(icao24),
|
||||
};
|
||||
}
|
||||
|
||||
|
||||
@@ -15,6 +15,7 @@ import {
|
||||
createTrackedAircraftIcon,
|
||||
isOtherTrackedIconSet,
|
||||
trackedContactHolder,
|
||||
trackedIconColor,
|
||||
} from '../../data/trackedAircraftIcon.js';
|
||||
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
|
||||
import { julianToEpochMs } from '../../geo/julian.js';
|
||||
@@ -27,13 +28,15 @@ import {
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
COCKPIT_AIR_ALL_ADD_M,
|
||||
COCKPIT_AIR_ALL_KEEP_M,
|
||||
COCKPIT_AIR_PROX_ADD_M,
|
||||
COCKPIT_AIR_PROX_KEEP_M,
|
||||
TRAIL_MAX_POINTS,
|
||||
displayDelayMs,
|
||||
followsClock,
|
||||
STALE_ALPHA,
|
||||
TRAIL_COLOR,
|
||||
AMBER_TRANSPARENT,
|
||||
TRACKED_ICON_COLOR,
|
||||
} from './policy.js';
|
||||
import {
|
||||
drawTrailSegments,
|
||||
@@ -45,6 +48,7 @@ import {
|
||||
trailBodySegments,
|
||||
trailHeadCurvePoints,
|
||||
trailHeadStartFix,
|
||||
trailTimeAt,
|
||||
} from '../../data/trailContinuity.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
import { entityRecord } from '../../data/entityRecords.js';
|
||||
@@ -60,11 +64,6 @@ function aircraftPickId(hit) {
|
||||
return isOtherTrackedIconSet(hit.set, 'military') ? undefined : hit.id;
|
||||
}
|
||||
|
||||
const STALE_TRACKED_COLOR = Object.freeze([
|
||||
...TRACKED_ICON_COLOR.slice(0, 3),
|
||||
STALE_ALPHA,
|
||||
]);
|
||||
|
||||
export function createTracking({
|
||||
flightState,
|
||||
services,
|
||||
@@ -212,11 +211,13 @@ export function createTracking({
|
||||
);
|
||||
distancesSquared.push([icao24, distanceSquared(eye, position)]);
|
||||
}
|
||||
// The AIR band follows the 3D mode, not the 3D model radius.
|
||||
const all = flightState._models3dMode === 'all';
|
||||
const next = nextCockpitNearContacts(
|
||||
previous,
|
||||
distancesSquared,
|
||||
parts.rendering._modelAddDistM(),
|
||||
parts.rendering._modelKeepDistM(),
|
||||
all ? COCKPIT_AIR_ALL_ADD_M : COCKPIT_AIR_PROX_ADD_M,
|
||||
all ? COCKPIT_AIR_ALL_KEEP_M : COCKPIT_AIR_PROX_KEEP_M,
|
||||
);
|
||||
flightState._cockpitNearContacts = next;
|
||||
for (const icao24 of previous)
|
||||
@@ -306,14 +307,18 @@ export function createTracking({
|
||||
return { text: '', dimmed: false };
|
||||
}
|
||||
|
||||
/** The tracked billboard's colour: amber, faded while stale, clear while the 3D model is the visual. */
|
||||
/** The tracked billboard's colour: the contact's own fleet colour (tracking
|
||||
* never recolours it), faded while stale, clear while the 3D model is the
|
||||
* visual. */
|
||||
|
||||
function _trackedIconColor() {
|
||||
if (parts.rendering._modelOwnsVisual(flightState._trackedIcao))
|
||||
return AMBER_TRANSPARENT;
|
||||
return _trackedStaleCue(flightState._trackedIcao).dimmed
|
||||
? STALE_TRACKED_COLOR
|
||||
: TRACKED_ICON_COLOR;
|
||||
const icao24 = flightState._trackedIcao;
|
||||
const color = parts.rendering._fleetBillboardColor(icao24);
|
||||
if (parts.rendering._modelOwnsVisual(icao24))
|
||||
return trackedIconColor(color, 0);
|
||||
return _trackedStaleCue(icao24).dimmed
|
||||
? trackedIconColor(color, STALE_ALPHA)
|
||||
: color;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -404,10 +409,7 @@ export function createTracking({
|
||||
width: look.size[0],
|
||||
height: look.size[1],
|
||||
get scale() {
|
||||
return parts.rendering._fleetBillboardScale(
|
||||
icao24,
|
||||
flightState.records.data.get(icao24)?.klass,
|
||||
);
|
||||
return parts.rendering._fleetBillboardScale(icao24);
|
||||
},
|
||||
scaleByDistance: look.scaleByDistance,
|
||||
};
|
||||
@@ -611,12 +613,46 @@ export function createTracking({
|
||||
);
|
||||
}
|
||||
|
||||
/** Reports at or before the time the aircraft is drawn (now − the display delay). */
|
||||
/** Reports at or before the time the aircraft is drawn (`_trailDisplayMs`). */
|
||||
|
||||
function _trailBodyCountNow() {
|
||||
return trailBodyCount(
|
||||
return trailBodyCount(flightState._trailFixes, _trailDisplayMs());
|
||||
}
|
||||
|
||||
/**
|
||||
* The time on its trail at which a host-supplied placement draws the
|
||||
* aircraft, read off the trail where it is drawn (`trailTimeAt`): such a
|
||||
* placement draws at a delay of its own, not this layer's. NaN when this
|
||||
* layer's own motion draws it, or the trail has no pair to read.
|
||||
* @returns {number} Epoch ms or NaN.
|
||||
*/
|
||||
function _placedTrailMs() {
|
||||
if (!parts.motion._trackedPlaced?.()) return NaN;
|
||||
return trailTimeAt(
|
||||
flightState._trailFixes,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
parts.motion._trackedDisplayCached(),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* The time the trail runs up to: the time the aircraft is drawn at, now −
|
||||
* the display delay, or where a placement draws it. Otherwise the trail
|
||||
* ends short of a placed aircraft, or runs on ahead of it.
|
||||
* @returns {number} Epoch ms.
|
||||
*/
|
||||
function _trailDisplayMs() {
|
||||
const placedMs = _placedTrailMs();
|
||||
return Number.isFinite(placedMs)
|
||||
? placedMs
|
||||
: flightState.now() - displayDelayMs(flightState);
|
||||
}
|
||||
|
||||
/** Whether the trail holds no report behind the aircraft yet: this
|
||||
* layer's own motion draws it before its oldest fix. Never for an
|
||||
* aircraft a placement draws: its trail is read where it is drawn. */
|
||||
function _trailWarmingUp() {
|
||||
return (
|
||||
!Number.isFinite(_placedTrailMs()) && parts.motion._isTrackWarmingUp()
|
||||
);
|
||||
}
|
||||
|
||||
@@ -633,7 +669,7 @@ export function createTracking({
|
||||
if (
|
||||
!flightState._trackedIcao ||
|
||||
!flightState._trailFixes.length ||
|
||||
parts.motion._isTrackWarmingUp()
|
||||
_trailWarmingUp()
|
||||
)
|
||||
return [];
|
||||
const head =
|
||||
@@ -661,7 +697,7 @@ export function createTracking({
|
||||
trailHeadCurvePoints(
|
||||
flightState._trailFixes,
|
||||
flightState._trailBodyCount,
|
||||
flightState.now() - displayDelayMs(flightState),
|
||||
_trailDisplayMs(),
|
||||
),
|
||||
end,
|
||||
parts.motion._trackedModelCenterWorld(),
|
||||
@@ -926,10 +962,11 @@ export function createTracking({
|
||||
flightState._trackedIcao = null;
|
||||
// Hand the contact back to its icon only now, once it no longer reads as
|
||||
// tracked (the settle plans it as a fleet contact).
|
||||
if (flightState._icons?.has(clearedIcao)) {
|
||||
flightState._icons.setShown(clearedIcao, true);
|
||||
// Its fleet model, kept loaded while it was selected, takes it back in
|
||||
// this frame; the icon shows only when there is no loaded one.
|
||||
parts.rendering._handBackDeselected(clearedIcao);
|
||||
if (flightState._icons?.has(clearedIcao))
|
||||
parts.icons._settleIcon(clearedIcao, { fromCourseDeg: trackedCourseDeg });
|
||||
}
|
||||
parts.icons._applyIconPresentation(clearedIcao);
|
||||
clearTrackedSubjectContext('military');
|
||||
_emitAwarenessEvent('gev:awareness-subject-cleared', {
|
||||
@@ -1044,14 +1081,13 @@ export function createTracking({
|
||||
imageLod: _trackedBillboardLook().imageLod,
|
||||
sprite,
|
||||
position: getTrackedPosition,
|
||||
// Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading);
|
||||
// transparent once the tracked model is actually up (ready + shown).
|
||||
// Amber (faded while stale), transparent once the tracked model is the visual.
|
||||
// Its own colour (faded while stale) when the billboard is the visual (zoomed out, 3D off,
|
||||
// or model still loading); transparent once the tracked model is actually up (ready + shown).
|
||||
color: _trackedIconColor,
|
||||
// Screen-projected rotation, evaluated per frame on the camera's own
|
||||
// axes, so it stays exact through a tracked orbit. The tracked target
|
||||
// must never vanish into tile geometry — tracking a taxiing plane at
|
||||
// street level would otherwise bury the amber icon inside the runway
|
||||
// street level would otherwise bury the icon inside the runway
|
||||
// skin, so it draws over depth like the fleet icon set; its
|
||||
// shared-host tracked card is top-composited separately.
|
||||
rotation: () => {
|
||||
@@ -1059,6 +1095,8 @@ export function createTracking({
|
||||
const pos = getTrackedPosition();
|
||||
if (!tracked || !pos || !flightState._viewer)
|
||||
return flightState._lastTrackedRotation;
|
||||
// A ground station's mast stands upright.
|
||||
if (tracked.klass === 'station') return 0;
|
||||
const projected = courseScreenRotation(
|
||||
_pose(),
|
||||
pos,
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { readFileSync } from 'node:fs';
|
||||
|
||||
const source = (layer) =>
|
||||
readFileSync(new URL(`../${layer}/tracking.js`, import.meta.url), 'utf8');
|
||||
|
||||
for (const layer of ['military', 'flights']) {
|
||||
test(`${layer}: a tracked ground station's mast is never turned`, () => {
|
||||
// The tracked billboard's rotation answers 0 for a station before any
|
||||
// course is projected on screen.
|
||||
const rotation = /rotation: \(\) => \{[\s\S]*?courseScreenRotation\(/.exec(
|
||||
source(layer),
|
||||
)?.[0];
|
||||
assert.ok(rotation, 'the tracked billboard turns by a rotation callback');
|
||||
assert.match(
|
||||
rotation,
|
||||
/if \(tracked\.klass === 'station'\) return 0;\s*const projected = courseScreenRotation\(/,
|
||||
);
|
||||
});
|
||||
}
|
||||
@@ -65,7 +65,15 @@ function recordingTrail() {
|
||||
};
|
||||
}
|
||||
|
||||
function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
|
||||
function trackedHarness({
|
||||
liveFixes = [],
|
||||
trace = null,
|
||||
nowMs,
|
||||
floor,
|
||||
head,
|
||||
placed = false,
|
||||
warmingUp = false,
|
||||
}) {
|
||||
const trail = recordingTrail();
|
||||
const svc = services({ trails: trail, floor });
|
||||
const flightState = createFlightState({
|
||||
@@ -104,7 +112,9 @@ function trackedHarness({ liveFixes = [], trace = null, nowMs, floor, head }) {
|
||||
services: svc,
|
||||
parts: {
|
||||
motion: {
|
||||
_isTrackWarmingUp: () => false,
|
||||
_isTrackWarmingUp: () => warmingUp,
|
||||
_trackedPlaced: () => placed,
|
||||
_trackedDisplayCached: () => head ?? null,
|
||||
_trackedTrailCached: () => head ?? null,
|
||||
_trackedDisplayPosition: () => head ?? null,
|
||||
_trackedModelCenterWorld: () => null,
|
||||
@@ -256,3 +266,36 @@ test('a full 24 h military trace fits within TRAIL_MAX_POINTS without thinning',
|
||||
assert.ok(TRAIL_MAX_POINTS >= day + 500);
|
||||
assert.equal(flightState._trailFixes.length, day + 1);
|
||||
});
|
||||
|
||||
test('a placed military aircraft drawn ahead of the display delay keeps its trail joined to it', () => {
|
||||
const t0 = Date.UTC(2026, 10, 8, 0, 0);
|
||||
const liveFixes = [0, 1, 2, 3].map((i) => ({
|
||||
timeMs: t0 + i * MINUTE,
|
||||
lat: 50,
|
||||
lon: 1 + i * 0.12,
|
||||
}));
|
||||
// Warming up by the layer's own delay; the placement draws it between the
|
||||
// third and fourth reports.
|
||||
const near = Cesium.Cartesian3.fromDegrees(1.3, 50, 9_000);
|
||||
const harness = trackedHarness({
|
||||
liveFixes,
|
||||
nowMs: t0 + 3.5 * MINUTE,
|
||||
head: near,
|
||||
placed: true,
|
||||
warmingUp: true,
|
||||
});
|
||||
harness.flightState._displayDelay = { currentMs: 10 * MINUTE };
|
||||
harness.tracking._startTrail('ae0001');
|
||||
const body = harness.trail.last()[0];
|
||||
assert.equal(harness.trail.last().length, 1);
|
||||
assert.ok(
|
||||
Cesium.Cartesian3.distance(
|
||||
body[body.length - 1],
|
||||
Cesium.Cartesian3.fromDegrees(1.24, 50, 9_000),
|
||||
) < 1,
|
||||
);
|
||||
const drawn = harness.headPositions();
|
||||
assert.ok(drawn.length >= 2);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[0], body[body.length - 1]) < 1);
|
||||
assert.ok(Cesium.Cartesian3.distance(drawn[drawn.length - 1], near) < 1);
|
||||
});
|
||||
@@ -6,7 +6,7 @@ import { createStubRenderer } from '../../render/stub/index.js';
|
||||
import { createMotion } from './motion.js';
|
||||
import { createFlightState } from './state.js';
|
||||
import { createTracking } from './tracking.js';
|
||||
import { RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
import { MIL_ICON_COLOR, RENDER_DELAY_SEC, STALE_ALPHA } from './policy.js';
|
||||
|
||||
// A tracked military contact's trail is its reports joined along the curve
|
||||
// the icon is drawn along between them, so the icon always sits on its trail
|
||||
@@ -104,7 +104,11 @@ function harness({ fixes, info, nowMs, ground = () => null }) {
|
||||
flightState.now = () => clock;
|
||||
flightState._positionHistory.set(ICAO, fixes);
|
||||
const parts = {
|
||||
rendering: { _modelOwnsVisual: () => false, _modelSpec: () => ({}) },
|
||||
rendering: {
|
||||
_modelOwnsVisual: () => false,
|
||||
_modelSpec: () => ({}),
|
||||
_fleetBillboardColor: () => MIL_ICON_COLOR,
|
||||
},
|
||||
queries: {
|
||||
_toCleanText: (value) => (typeof value === 'string' ? value.trim() : ''),
|
||||
_formatAltitude: (ft) => `${ft} ft`,
|
||||
@@ -649,6 +653,11 @@ test('military: a stalled feed dims the tracked plane as STALE', () => {
|
||||
dimmed: true,
|
||||
});
|
||||
assert.equal(h.tracking._trackedIconColor()[3], STALE_ALPHA);
|
||||
assert.deepEqual(
|
||||
h.tracking._trackedIconColor().slice(0, 3),
|
||||
MIL_ICON_COLOR.slice(0, 3),
|
||||
'faded in its own colour, never recoloured',
|
||||
);
|
||||
assert.equal(h.flightState.records.missingPolls.has(ICAO), false);
|
||||
} finally {
|
||||
h.restore();
|
||||
|
||||
Loaded 100 of 298 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user