mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-19 01:32:19 +00:00
Merge branch 'main' into fix/cockpit-ride-transit-rail
This commit is contained in:
363 files changed
+13745
-1912
No files matched your search
@@ -2,13 +2,9 @@ import {
|
||||
formatAwarenessLabel,
|
||||
AWARENESS_RADIUS_M,
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import {
|
||||
formatNumber,
|
||||
onLocaleChange,
|
||||
t,
|
||||
translateKnown,
|
||||
} from '../../i18n/index.js';
|
||||
import { formatNumber, onLocaleChange, t } from '../../i18n/index.js';
|
||||
import { sourceStatusLabel } from '../../ui/layerNames.js';
|
||||
import { translateStatusMessage } from '../../ui/statusText.js';
|
||||
import { formatQuantity } from '../../ui/unitLabels.js';
|
||||
import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js';
|
||||
import { distanceParts } from '../../data/distanceFormat.js';
|
||||
@@ -45,7 +41,7 @@ export function presentAwarenessDistance(meters) {
|
||||
function presentAwarenessReason(summary = {}) {
|
||||
return summary.reasonTemplate
|
||||
? t(summary.reasonTemplate, summary.reasonValues)
|
||||
: translateKnown(summary.reason || '');
|
||||
: translateStatusMessage(summary.reason || '');
|
||||
}
|
||||
|
||||
/**
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
Vendored
+19
@@ -335,6 +335,25 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
return nextId;
|
||||
},
|
||||
|
||||
/**
|
||||
* Selects the camera nearest a WGS84 point and optionally flies to it.
|
||||
* @param {number} lat Latitude in degrees.
|
||||
* @param {number} lon Longitude in degrees.
|
||||
* @param {Object} [options={}]
|
||||
* @param {boolean} [options.focus=true] Whether to fly after selection.
|
||||
* @param {number} [options.durationSec] Fly-to duration in seconds.
|
||||
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
|
||||
*/
|
||||
focusNearestToPoint(lat, lon, options = {}) {
|
||||
const nearest = parts.navigation.nearestCameraIdToPoint(lat, lon);
|
||||
if (!nearest) return null;
|
||||
parts.selection.setActiveCamera(nearest);
|
||||
if (options.focus !== false) {
|
||||
parts.navigation.focusCamera(nearest, options.durationSec || 1.8);
|
||||
}
|
||||
return nearest;
|
||||
},
|
||||
|
||||
/**
|
||||
* Selects and flies to the camera nearest the current viewer position.
|
||||
* @param {Object} [options={}]
|
||||
|
||||
@@ -9,14 +9,20 @@ export function createNavigation({
|
||||
source,
|
||||
}) {
|
||||
/**
|
||||
* Finds the camera closest to the viewer's current position.
|
||||
* @returns {string|null} Camera ID of the nearest camera, or null.
|
||||
* Nearest catalog camera to a WGS84 point.
|
||||
* @param {number} lat Latitude in degrees.
|
||||
* @param {number} lon Longitude in degrees.
|
||||
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
|
||||
*/
|
||||
|
||||
function nearestCameraIdToViewer() {
|
||||
const pose = parts.model.eyePose();
|
||||
if (!pose || !layerState._records.length) return null;
|
||||
const { lat, lon } = pose;
|
||||
function nearestCameraIdToPoint(lat, lon) {
|
||||
if (
|
||||
!Number.isFinite(lat) ||
|
||||
!Number.isFinite(lon) ||
|
||||
Math.abs(lat) > 90 ||
|
||||
Math.abs(lon) > 180 ||
|
||||
!layerState._records.length
|
||||
)
|
||||
return null;
|
||||
|
||||
let best = null;
|
||||
for (const record of layerState._records) {
|
||||
@@ -33,6 +39,16 @@ export function createNavigation({
|
||||
return best?.id || null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Finds the camera closest to the viewer's current position.
|
||||
* @returns {string|null} Camera ID of the nearest camera, or null.
|
||||
*/
|
||||
function nearestCameraIdToViewer() {
|
||||
const pose = parts.model.eyePose();
|
||||
if (!pose) return null;
|
||||
return nearestCameraIdToPoint(pose.lat, pose.lon);
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera the layer opens on when none is selected: the one nearest the
|
||||
* viewer, or the first record when the viewer has no position yet.
|
||||
@@ -175,6 +191,7 @@ export function createNavigation({
|
||||
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
|
||||
}
|
||||
return {
|
||||
nearestCameraIdToPoint,
|
||||
nearestCameraIdToViewer,
|
||||
openingCameraId,
|
||||
reopenNearestCamera,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createNavigation } from './navigation.js';
|
||||
|
||||
function fixture() {
|
||||
const records = [
|
||||
{ camera: { id: 'west', lat: 40, lon: -120 } },
|
||||
{ camera: { id: 'east', lat: 40, lon: -100 } },
|
||||
];
|
||||
const state = { _records: records };
|
||||
const parts = {
|
||||
model: {
|
||||
eyePose: () => ({ lat: 40, lon: -101 }),
|
||||
haversineKm(lat1, lon1, lat2, lon2) {
|
||||
return Math.hypot(lat1 - lat2, lon1 - lon2);
|
||||
},
|
||||
},
|
||||
};
|
||||
const navigation = createNavigation({
|
||||
state,
|
||||
services: {},
|
||||
parts,
|
||||
source: {},
|
||||
});
|
||||
return { navigation };
|
||||
}
|
||||
|
||||
test('nearest camera can be resolved from an explicit WGS84 target', () => {
|
||||
const { navigation } = fixture();
|
||||
assert.equal(navigation.nearestCameraIdToPoint(40, -119), 'west');
|
||||
assert.equal(navigation.nearestCameraIdToPoint(40, -101), 'east');
|
||||
});
|
||||
|
||||
test('viewer-nearest delegates to the same target-point owner', () => {
|
||||
const { navigation } = fixture();
|
||||
assert.equal(navigation.nearestCameraIdToViewer(), 'east');
|
||||
});
|
||||
|
||||
test('invalid target coordinates fail closed', () => {
|
||||
const { navigation } = fixture();
|
||||
for (const [lat, lon] of [
|
||||
[NaN, 0],
|
||||
[null, 0],
|
||||
[0, Infinity],
|
||||
[90.00001, 0],
|
||||
[-90.00001, 0],
|
||||
[0, 180.00001],
|
||||
[0, -180.00001],
|
||||
]) {
|
||||
assert.equal(navigation.nearestCameraIdToPoint(lat, lon), null);
|
||||
}
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -857,9 +857,12 @@ export function createGhostMapsLayer({
|
||||
title:
|
||||
days === null
|
||||
? t('Show markers of every age')
|
||||
: t('Maximum event age: {days}d; undated markers are kept', {
|
||||
days: formatNumber(days),
|
||||
}),
|
||||
: tn(
|
||||
days,
|
||||
'Maximum event age: {days}d; undated markers are kept',
|
||||
'Maximum event age: {days}d; undated markers are kept',
|
||||
{ days: formatNumber(days) },
|
||||
),
|
||||
active: days === _ageDays,
|
||||
onClick: () => setAgeDays(days),
|
||||
})),
|
||||
@@ -894,7 +897,7 @@ export function createGhostMapsLayer({
|
||||
};
|
||||
}),
|
||||
legend: [],
|
||||
info: `${_ageDays === null ? t('All markers') : t('Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`,
|
||||
info: `${_ageDays === null ? t('All markers') : tn(_ageDays, 'Event age: {days}d · undated kept', 'Event age: {days}d · undated kept', { days: formatNumber(_ageDays) })} · ${info}`,
|
||||
infoTitle: t(
|
||||
'S2 Underground publishes these KMZ products to GitHub. New uploads are detected within seconds and replace the previous edition automatically. Click a marker for its report.',
|
||||
),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setLocale } from '../../i18n/index.js';
|
||||
import { createGhostMapsLayer } from './index.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
|
||||
@@ -310,6 +311,35 @@ test('age controls default to seven days and widening restores filtered and expi
|
||||
assert.equal(ageChip(layer, null).active, true);
|
||||
});
|
||||
|
||||
test('the event age agrees with its number of days', async (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const { layer, viewer } = fixture(t, { reports: [{ name: 'Undated' }] });
|
||||
await layer.update(viewer);
|
||||
const info = () =>
|
||||
layer.getRowControls().info.split(' · ').slice(0, 2).join(' · ');
|
||||
assert.equal(
|
||||
ageChip(layer, 1).title,
|
||||
'Maximum event age: 1d; undated markers are kept',
|
||||
);
|
||||
setLocale('de');
|
||||
assert.equal(
|
||||
ageChip(layer, 1).title,
|
||||
'Maximales Ereignisalter: 1 Tag; undatierte Markierungen bleiben erhalten',
|
||||
);
|
||||
assert.equal(
|
||||
ageChip(layer, 7).title,
|
||||
'Maximales Ereignisalter: 7 Tage; undatierte Markierungen bleiben erhalten',
|
||||
);
|
||||
assert.equal(info(), 'Ereignisalter: 7 Tage · undatierte bleiben');
|
||||
await ageChip(layer, 1).onClick();
|
||||
assert.equal(info(), 'Ereignisalter: 1 Tag · undatierte bleiben');
|
||||
setLocale('es');
|
||||
assert.equal(
|
||||
info(),
|
||||
'Antigüedad: 1 día · se conservan los marcadores sin fecha',
|
||||
);
|
||||
});
|
||||
|
||||
test('age preferences persist independently of product choices and reject invalid storage', async (t) => {
|
||||
const values = new Map([['gev.ghostmaps.products', '["cip"]']]);
|
||||
const storage = {
|
||||
|
||||
Vendored
+8
-35
@@ -1,41 +1,15 @@
|
||||
import { describeInstallationFeedback } from '../../data/installationFeedback.js';
|
||||
import { installationFeedback } from '../../data/installationFeedback.js';
|
||||
import {
|
||||
LAYER_ID,
|
||||
DISTANCE_PREFILTER_MARGIN_M,
|
||||
ANCHOR_REFRESH_M,
|
||||
} from './policy.js';
|
||||
import { formatNumber, t, tn } from '../../i18n/index.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
|
||||
import { surfaceDistance } from '../../geo/geodesic.js';
|
||||
import { toDegrees, toRadians } from '../../geo/vector.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
|
||||
// installationFeedback.js is shared with the HUD (src/loadingFeedback.js) and
|
||||
// hands back msg()-marked English plus values; getStats translates them here.
|
||||
function localizeInstallationFeedback(feedback) {
|
||||
if (feedback.text !== undefined) {
|
||||
const values = {};
|
||||
if (feedback.reason !== undefined) values.reason = t(feedback.reason);
|
||||
if (feedback.seconds !== undefined) values.seconds = feedback.seconds;
|
||||
return t(feedback.text, values);
|
||||
}
|
||||
const { count, km } = feedback;
|
||||
if (km) {
|
||||
const kmText = formatNumber(km);
|
||||
return count === 0
|
||||
? t('No mapped sites within {km} km of the contact', { km: kmText })
|
||||
: tn(
|
||||
count,
|
||||
'{count} mapped site within {km} km of the contact',
|
||||
'{count} mapped sites within {km} km of the contact',
|
||||
{ km: kmText },
|
||||
);
|
||||
}
|
||||
return count === 0
|
||||
? t('No mapped sites in view')
|
||||
: tn(count, '{count} mapped site in view', '{count} mapped sites in view');
|
||||
}
|
||||
|
||||
export function createControls({ state: layerState, services, parts, source }) {
|
||||
const methods = {
|
||||
id: LAYER_ID,
|
||||
@@ -285,13 +259,12 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
retryAt: layerState.retryAt,
|
||||
retrying: layerState.loading && Boolean(layerState.failureReason),
|
||||
failureReason: layerState.failureReason,
|
||||
statusMessage: localizeInstallationFeedback(
|
||||
describeInstallationFeedback({
|
||||
...layerState,
|
||||
count: layerState.lastUpdate ? mappedCount : undefined,
|
||||
retrying: layerState.loading && Boolean(layerState.failureReason),
|
||||
}),
|
||||
),
|
||||
// English: the analyst reads it as is; displays translate it.
|
||||
statusMessage: installationFeedback({
|
||||
...layerState,
|
||||
count: layerState.lastUpdate ? mappedCount : undefined,
|
||||
retrying: layerState.loading && Boolean(layerState.failureReason),
|
||||
}),
|
||||
loadingLabel: layerState.loading
|
||||
? t('loading mapped installation context')
|
||||
: '',
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// statusMessage stays English (the analyst's empty note); displays translate it.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale, translateKnown } from '../../i18n/index.js';
|
||||
import { setLocale, t, tn } from '../../i18n/index.js';
|
||||
import { translateStatusMessage } from '../../ui/statusText.js';
|
||||
import { createControls } from './controls.js';
|
||||
|
||||
function stats(state) {
|
||||
@@ -13,67 +15,113 @@ function stats(state) {
|
||||
}).methods.getStats();
|
||||
}
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: installation feedback is in the UI language`, () => {
|
||||
setLocale(locale);
|
||||
const empty = stats({ status: 'empty', lastUpdate: 1 }).statusMessage;
|
||||
assert.notEqual(empty, 'No mapped sites in view');
|
||||
const found = stats({
|
||||
function inLocale(locale, run) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
run();
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
}
|
||||
|
||||
// A retry a minute out reads "60s" (rounded up).
|
||||
const cases = [
|
||||
[
|
||||
{ status: 'empty', lastUpdate: 1 },
|
||||
'No mapped sites in view',
|
||||
() => t('No mapped sites in view'),
|
||||
],
|
||||
[
|
||||
{ status: 'ready', lastUpdate: 1, records: [{ kind: 'installation' }] },
|
||||
'1 mapped site in view',
|
||||
() => tn(1, '{count} mapped site in view', '{count} mapped sites in view'),
|
||||
],
|
||||
[
|
||||
{
|
||||
status: 'ready',
|
||||
lastUpdate: 1,
|
||||
records: [{ kind: 'installation' }, { kind: 'installation' }],
|
||||
}).statusMessage;
|
||||
assert.notEqual(found, '2 mapped sites in view');
|
||||
const tiles = stats({
|
||||
status: 'unavailable',
|
||||
failureReason: 'tiles_unavailable',
|
||||
}).statusMessage;
|
||||
assert.notEqual(tiles, 'Map tiles temporarily unavailable');
|
||||
const retry = stats({
|
||||
},
|
||||
'2 mapped sites in view',
|
||||
() => tn(2, '{count} mapped site in view', '{count} mapped sites in view'),
|
||||
],
|
||||
[
|
||||
{
|
||||
status: 'empty',
|
||||
lastUpdate: 1,
|
||||
wide: true,
|
||||
coverage: { kind: 'subject', radiusM: 25000 },
|
||||
},
|
||||
'No mapped sites within 25 km of the contact',
|
||||
() => t('No mapped sites within {km} km of the contact', { km: '25' }),
|
||||
],
|
||||
[
|
||||
{
|
||||
status: 'ready',
|
||||
lastUpdate: 1,
|
||||
wide: true,
|
||||
coverage: { kind: 'subject', radiusM: 25000 },
|
||||
records: [{ kind: 'installation' }],
|
||||
},
|
||||
'1 mapped site within 25 km of the contact',
|
||||
() =>
|
||||
tn(
|
||||
1,
|
||||
'{count} mapped site within {km} km of the contact',
|
||||
'{count} mapped sites within {km} km of the contact',
|
||||
{ km: '25' },
|
||||
),
|
||||
],
|
||||
[
|
||||
{ status: 'unavailable', failureReason: 'tiles_unavailable' },
|
||||
'Map tiles temporarily unavailable',
|
||||
() => t('Map tiles temporarily unavailable'),
|
||||
],
|
||||
[
|
||||
{
|
||||
status: 'unavailable',
|
||||
failureReason: 'names_unavailable',
|
||||
retryAt: Date.now() + 5000,
|
||||
}).statusMessage;
|
||||
assert.doesNotMatch(retry, /^Mapped names temporarily unavailable/);
|
||||
for (const text of [
|
||||
'Too many mapped sites in view to list them all',
|
||||
'Installation context unavailable',
|
||||
]) {
|
||||
assert.notEqual(translateKnown(text), text);
|
||||
}
|
||||
get retryAt() {
|
||||
return Date.now() + 60_000;
|
||||
},
|
||||
},
|
||||
'Mapped names temporarily unavailable — retrying in 60s',
|
||||
() =>
|
||||
t('{reason} — retrying in {seconds}s', {
|
||||
reason: t('Mapped names temporarily unavailable'),
|
||||
seconds: 60,
|
||||
}),
|
||||
],
|
||||
[
|
||||
{ status: 'zoom-in' },
|
||||
'Zoom in to search mapped installations',
|
||||
() => t('Zoom in to search mapped installations'),
|
||||
],
|
||||
];
|
||||
|
||||
for (const locale of ['es', 'ru']) {
|
||||
test(`${locale}: installation statusMessage stays English data`, () => {
|
||||
inLocale(locale, () => {
|
||||
for (const [state, english] of cases)
|
||||
assert.equal(stats(state).statusMessage, english);
|
||||
});
|
||||
});
|
||||
|
||||
test(`${locale}: installation statusMessage is shown in the UI language`, () => {
|
||||
inLocale(locale, () => {
|
||||
for (const [state, english, shown] of cases) {
|
||||
const shownText = translateStatusMessage(stats(state).statusMessage);
|
||||
assert.notEqual(shownText, english);
|
||||
assert.equal(shownText, shown());
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
test('en: installation feedback keeps its English wording', () => {
|
||||
setLocale('en');
|
||||
assert.equal(
|
||||
stats({ status: 'empty', lastUpdate: 1 }).statusMessage,
|
||||
'No mapped sites in view',
|
||||
);
|
||||
assert.equal(
|
||||
stats({
|
||||
status: 'ready',
|
||||
lastUpdate: 1,
|
||||
records: [{ kind: 'installation' }],
|
||||
}).statusMessage,
|
||||
'1 mapped site in view',
|
||||
);
|
||||
assert.equal(
|
||||
stats({
|
||||
status: 'ready',
|
||||
lastUpdate: 1,
|
||||
wide: true,
|
||||
coverage: { kind: 'subject', radiusM: 25000 },
|
||||
records: [{ kind: 'installation' }, { kind: 'installation' }],
|
||||
}).statusMessage,
|
||||
'2 mapped sites within 25 km of the contact',
|
||||
);
|
||||
assert.equal(
|
||||
stats({
|
||||
status: 'unavailable',
|
||||
failureReason: 'names_unavailable',
|
||||
retryAt: Date.now() + 5000,
|
||||
}).statusMessage,
|
||||
'Mapped names temporarily unavailable — retrying in 5s',
|
||||
);
|
||||
for (const [state, english] of cases) {
|
||||
assert.equal(stats(state).statusMessage, english);
|
||||
assert.equal(translateStatusMessage(english), english);
|
||||
}
|
||||
});
|
||||
@@ -69,3 +69,38 @@ test('the mission panel translates only the fallback status', (t) => {
|
||||
assert.equal(shownStatus(UNKNOWN_LAUNCH_STATUS), 'Desconocido');
|
||||
assert.equal(shownStatus('Launch Successful'), 'Launch Successful');
|
||||
});
|
||||
|
||||
test('a confirmed landing position is worded apart from the CONFIRMED sightings chip', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const position = () =>
|
||||
createPanel({
|
||||
state: {
|
||||
_selectedLaunchId: 'mission-1',
|
||||
_launches: [
|
||||
{
|
||||
id: 'mission-1',
|
||||
name: 'Example',
|
||||
status: 'Launch Successful',
|
||||
payloads: [],
|
||||
recoveryStages: [
|
||||
{
|
||||
name: 'B1080',
|
||||
endpoint: { lat: 28.41, lon: -80.6, accuracy: 'CONFIRMED' },
|
||||
},
|
||||
],
|
||||
},
|
||||
],
|
||||
_replayTracks: new Map(),
|
||||
},
|
||||
parts: {
|
||||
overlays: { shortMissionLabel: (name) => name },
|
||||
policyHelpers: { missionPathPresentation: () => ({}) },
|
||||
replay: { presentReplay: () => ({}) },
|
||||
},
|
||||
}).presentMission().stages[0].position;
|
||||
assert.match(position(), / · CONFIRMED$/);
|
||||
// One landing, singular: sv BEKRÄFTAD, where the sightings chip says
|
||||
// BEKRÄFTADE.
|
||||
setLocale('sv');
|
||||
assert.match(position(), / · BEKRÄFTAD$/);
|
||||
});
|
||||
@@ -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();
|
||||
|
||||
@@ -48,6 +48,7 @@ import {
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
|
||||
|
||||
/** How often the trains near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
@@ -924,6 +925,25 @@ export function createRendering({ state, services, parts }) {
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
partState: vehiclePartState,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheels rolling at the speed it is drawn moving at (else its reported
|
||||
* one), doors open while it stands at a stop.
|
||||
*/
|
||||
function vehiclePartState(item, table) {
|
||||
const entry = item.entry;
|
||||
const drawn = entry?.sample?.segmentSpeedMps;
|
||||
const reported = entry?.record?.speedMps;
|
||||
return groundVehiclePartState(table, {
|
||||
speedMps: Number.isFinite(drawn)
|
||||
? drawn
|
||||
: Number.isFinite(reported)
|
||||
? reported
|
||||
: null,
|
||||
atStop: entry?.record?.status === 'STOPPED_AT',
|
||||
});
|
||||
}
|
||||
|
||||
@@ -978,11 +998,7 @@ export function createRendering({ state, services, parts }) {
|
||||
if (now - modelCandidatesAtMs >= MODEL_CANDIDATES_MS) {
|
||||
modelCandidatesAtMs = now;
|
||||
const eye = cameraPose()?.position;
|
||||
const policy = services.fleet.policy;
|
||||
const keepM =
|
||||
services.fleet.display?.()?.models3dMode === 'all'
|
||||
? policy.keepAllM
|
||||
: policy.keepM;
|
||||
const keepM = services.fleet.policy.keepM;
|
||||
const limitSq = keepM * keepM * 1.44;
|
||||
if (eye)
|
||||
for (const entry of state._trains.values()) {
|
||||
|
||||
@@ -574,12 +574,14 @@ export function createRecentImageryLayer({
|
||||
const list = stripList();
|
||||
if (!list.length) return;
|
||||
reconcileFocus();
|
||||
thumbnails.requestOrdered(list, _box, {
|
||||
focusIndex: Math.max(0, focusIndexIn(list)),
|
||||
firstVisible: _visible.first,
|
||||
lastVisible: _visible.last,
|
||||
extra: 2,
|
||||
});
|
||||
const wanted = new Set(
|
||||
thumbnails.requestOrdered(list, _box, {
|
||||
focusIndex: Math.max(0, focusIndexIn(list)),
|
||||
firstVisible: _visible.first,
|
||||
lastVisible: _visible.last,
|
||||
extra: 2,
|
||||
}),
|
||||
);
|
||||
for (const key of new Set([
|
||||
_assigned.a,
|
||||
_assigned.b,
|
||||
@@ -587,8 +589,11 @@ export function createRecentImageryLayer({
|
||||
_followKey,
|
||||
])) {
|
||||
const candidate = candidateFor(key);
|
||||
if (sourceOn(candidate)) thumbnails.request(candidate, _box, 0);
|
||||
if (!sourceOn(candidate)) continue;
|
||||
thumbnails.request(candidate, _box, 0);
|
||||
wanted.add(candidate.key);
|
||||
}
|
||||
thumbnails.retain(wanted);
|
||||
}
|
||||
|
||||
function resetCatalog() {
|
||||
@@ -821,7 +826,16 @@ export function createRecentImageryLayer({
|
||||
// A probe can take a pinned day off the map or let a followed focus
|
||||
// preview; both change more than the cards, so a full notification
|
||||
// follows the thumbnail one.
|
||||
const previousFollow = _followKey;
|
||||
const previousPreview = _previewKey;
|
||||
const pruned = pruneEmpty();
|
||||
if (
|
||||
pruned &&
|
||||
(_followKey !== previousFollow || _previewKey !== previousPreview)
|
||||
) {
|
||||
// The new automatic day's probe may have been cancelled off-screen.
|
||||
requestThumbnails();
|
||||
}
|
||||
if (pruned) syncRender();
|
||||
const followed =
|
||||
Boolean(_followKey) &&
|
||||
|
||||
@@ -1105,6 +1105,10 @@ test('alpha, split and visible range notify without re-rendering the row', async
|
||||
f.layer.setSplit(0.25);
|
||||
f.layer.setVisibleRange(1, 3);
|
||||
assert.equal(f.thumbnails.calls.at(-1)[2].firstVisible, 1);
|
||||
assert.ok(
|
||||
f.thumbnails.retained.at(-1).includes(f.snap().focus.key),
|
||||
'the current focus remains in the retained refinement intent',
|
||||
);
|
||||
assert.equal(rowRenders, rows);
|
||||
assert.deepEqual(f.reasons.slice(-2), ['alpha', 'split']);
|
||||
f.layer.setAlpha('bad');
|
||||
@@ -1193,6 +1197,48 @@ const dailyViirs = () =>
|
||||
),
|
||||
);
|
||||
|
||||
test('empty auto VIIRS re-requests a cancelled successor', async () => {
|
||||
const f = fixture();
|
||||
const days = dailyViirs();
|
||||
const newest = days[0].key;
|
||||
const next = days[1].key;
|
||||
f.layer.setSources({ hls: false });
|
||||
await f.ready(days);
|
||||
|
||||
assert.equal(f.diag().following, newest);
|
||||
assert.ok(
|
||||
f.thumbnails.retained.at(-1).includes(next),
|
||||
'the next day was originally scheduled',
|
||||
);
|
||||
|
||||
// Move the visible window away before either day answers: retention
|
||||
// cancels the next day's probe but keeps the currently followed day.
|
||||
f.layer.setVisibleRange(25, 29);
|
||||
assert.equal(
|
||||
f.thumbnails.retained.at(-1).includes(next),
|
||||
false,
|
||||
'the next day is no longer retained',
|
||||
);
|
||||
const before = f.thumbnails.requests.filter(([key]) => key === next).length;
|
||||
|
||||
f.thumbnails.probe(newest, 'empty');
|
||||
assert.equal(f.diag().following, next);
|
||||
assert.equal(f.snap().preview.pending, next);
|
||||
assert.ok(
|
||||
f.thumbnails.retained.at(-1).includes(next),
|
||||
'the new follow day is retained without scrolling again',
|
||||
);
|
||||
assert.equal(
|
||||
f.thumbnails.requests.filter(([key]) => key === next).length,
|
||||
before + 1,
|
||||
'the cancelled successor is requested again',
|
||||
);
|
||||
|
||||
f.thumbnails.probe(next, 'present');
|
||||
assert.equal(f.snap().preview.key, next);
|
||||
assert.deepEqual(f.drapes(), { a: `${next}|none`, b: null });
|
||||
});
|
||||
|
||||
test('restored pins outside the visible strip window are probed and swipe once present', async () => {
|
||||
const f = fixture();
|
||||
const days = dailyViirs();
|
||||
|
||||
@@ -258,6 +258,7 @@ export function fakeThumbnails() {
|
||||
const requested = [];
|
||||
/** Direct `request` calls: `[key, priority]`. */
|
||||
const requests = [];
|
||||
const retained = [];
|
||||
const ask = (key) => {
|
||||
if (!requested.includes(key)) requested.push(key);
|
||||
};
|
||||
@@ -265,21 +266,28 @@ export function fakeThumbnails() {
|
||||
calls,
|
||||
requested,
|
||||
requests,
|
||||
retained,
|
||||
requestOrdered(candidates, box, window) {
|
||||
calls.push(['ordered', candidates.map((c) => c.key), window]);
|
||||
const { focusIndex, firstVisible, lastVisible, extra } = window;
|
||||
thumbnailOrder(
|
||||
const order = thumbnailOrder(
|
||||
focusIndex,
|
||||
firstVisible,
|
||||
lastVisible,
|
||||
candidates.length,
|
||||
extra,
|
||||
).forEach((index) => ask(candidates[index].key));
|
||||
);
|
||||
const keys = order.map((index) => candidates[index].key);
|
||||
keys.forEach(ask);
|
||||
return keys;
|
||||
},
|
||||
request(candidate, box, priority) {
|
||||
ask(candidate.key);
|
||||
requests.push([candidate.key, priority]);
|
||||
},
|
||||
retain(keys) {
|
||||
retained.push([...keys]);
|
||||
},
|
||||
/** Settle every requested key still unknown, as the loader would. */
|
||||
probeRequested(status = 'present') {
|
||||
for (const key of requested)
|
||||
|
||||
@@ -166,6 +166,19 @@ export function createThumbnailLoader({
|
||||
const existing = entries.get(key);
|
||||
if (existing) {
|
||||
touch(existing);
|
||||
if (existing.loading && existing.controller?.signal.aborted) {
|
||||
// Wanted again before the abort settles: a fresh entry, so the old
|
||||
// run cannot discard it.
|
||||
const renewed = {
|
||||
...existing,
|
||||
priority,
|
||||
loading: false,
|
||||
controller: null,
|
||||
};
|
||||
entries.set(key, renewed);
|
||||
enqueue(renewed);
|
||||
return;
|
||||
}
|
||||
if (existing.loading) return;
|
||||
if (existing.status === 'unknown') {
|
||||
existing.priority = priority;
|
||||
@@ -210,11 +223,33 @@ export function createThumbnailLoader({
|
||||
candidates.length,
|
||||
extra,
|
||||
);
|
||||
order.forEach((index, priority) => {
|
||||
return order.map((index, priority) => {
|
||||
this.request(candidates[index], box, priority);
|
||||
return candidates[index].key;
|
||||
});
|
||||
},
|
||||
|
||||
/**
|
||||
* Cancel queued and in-flight work for every key not in `keys`. Settled
|
||||
* entries stay under the LRU; a cancelled re-fetch of a present day keeps
|
||||
* its status.
|
||||
* @param {Iterable<string>} keys
|
||||
*/
|
||||
retain(keys) {
|
||||
const wanted = new Set(keys);
|
||||
for (let index = queue.length - 1; index >= 0; index -= 1) {
|
||||
const entry = queue[index];
|
||||
if (wanted.has(entry.key)) continue;
|
||||
queue.splice(index, 1);
|
||||
if (entry.status === 'unknown') entries.delete(entry.key);
|
||||
}
|
||||
for (const entry of [...entries.values()]) {
|
||||
if (!entry.loading || wanted.has(entry.key)) continue;
|
||||
entry.controller?.abort();
|
||||
if (entry.status === 'unknown') entries.delete(entry.key);
|
||||
}
|
||||
},
|
||||
|
||||
/**
|
||||
* Abort every fetch in flight and forget every unsettled request. A
|
||||
* known day whose image was being fetched again keeps what it knows.
|
||||
|
||||
@@ -336,3 +336,93 @@ test('injected thumbnail acquisition owns requests while the loader releases obj
|
||||
loader.destroy();
|
||||
assert.deepEqual(revoked, ['blob:1']);
|
||||
});
|
||||
|
||||
test('retain aborts stale acquisition while allowing the current intent to start', async () => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1 });
|
||||
const stale = candidate('S30', '2026-09-10');
|
||||
const current = candidate('S30', '2026-09-11');
|
||||
|
||||
loader.request(stale, BOX, 0);
|
||||
loader.request(current, BOX, 1);
|
||||
assert.equal(fetch.calls.length, 1);
|
||||
assert.match(fetch.calls[0].url, /TIME=2026-09-10/);
|
||||
|
||||
loader.retain([current.key]);
|
||||
assert.equal(fetch.calls[0].signal.aborted, true);
|
||||
await settle();
|
||||
|
||||
assert.equal(
|
||||
fetch.calls.length,
|
||||
2,
|
||||
'current intent starts after stale abort',
|
||||
);
|
||||
assert.match(fetch.calls[1].url, /TIME=2026-09-11/);
|
||||
assert.equal(loader.get(stale.key).status, 'unknown');
|
||||
});
|
||||
|
||||
test('a cancelled re-fetch of a known-present day keeps its status and is retryable', async () => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
|
||||
const stale = candidate('S30', '2026-09-10');
|
||||
const newer = candidate('S30', '2026-09-11');
|
||||
|
||||
loader.request(stale, BOX, 0);
|
||||
fetch.respond(0);
|
||||
await settle();
|
||||
const acquisitionTime = loader.get(stale.key).acquisitionTime;
|
||||
|
||||
loader.request(newer, BOX, 0);
|
||||
fetch.respond(1);
|
||||
await settle();
|
||||
assert.equal(loader.get(stale.key).status, 'present');
|
||||
assert.equal(loader.get(stale.key).objectUrl, null);
|
||||
|
||||
loader.request(stale, BOX, 0);
|
||||
assert.equal(fetch.calls.length, 3, 'an evicted known day re-fetches');
|
||||
loader.retain([]);
|
||||
assert.equal(fetch.calls[2].signal.aborted, true);
|
||||
|
||||
await settle();
|
||||
assert.equal(loader.get(stale.key).status, 'present');
|
||||
assert.equal(loader.get(stale.key).acquisitionTime, acquisitionTime);
|
||||
|
||||
loader.request(stale, BOX, 0);
|
||||
assert.equal(fetch.calls.length, 4, 'a cancelled re-fetch is retryable');
|
||||
fetch.respond(3);
|
||||
await settle();
|
||||
assert.equal(loader.get(stale.key).status, 'present');
|
||||
});
|
||||
|
||||
for (const cancelRenewed of [false, true]) {
|
||||
test(`a known-present day requested during abort settlement ${cancelRenewed ? 'can be cancelled again' : 'restarts without another intent change'}`, async (t) => {
|
||||
const { loader, fetch } = fixture({ maxInFlight: 1, maxDecoded: 1 });
|
||||
t.after(() => loader.destroy());
|
||||
const day = candidate('S30', '2026-09-10');
|
||||
const other = candidate('S30', '2026-09-11');
|
||||
loader.request(day, BOX);
|
||||
fetch.respond(0);
|
||||
await settle();
|
||||
const acquisitionTime = loader.get(day.key).acquisitionTime;
|
||||
loader.request(other, BOX);
|
||||
fetch.respond(1);
|
||||
await settle();
|
||||
assert.equal(loader.get(day.key).objectUrl, null);
|
||||
|
||||
loader.request(day, BOX);
|
||||
loader.retain([]);
|
||||
assert.equal(fetch.calls[2].signal.aborted, true);
|
||||
// Deliberately do not await: the old run still owns its in-flight slot.
|
||||
loader.request(day, BOX);
|
||||
loader.retain(cancelRenewed ? [] : [day.key]);
|
||||
assert.equal(fetch.calls.length, 3, 'renewal respects the concurrency cap');
|
||||
await settle();
|
||||
assert.equal(loader.get(day.key).acquisitionTime, acquisitionTime);
|
||||
assert.equal(fetch.calls.length, cancelRenewed ? 3 : 4);
|
||||
if (!cancelRenewed) {
|
||||
assert.equal(fetch.calls[3].signal.aborted, false);
|
||||
fetch.respond(3);
|
||||
await settle();
|
||||
assert.ok(loader.get(day.key).objectUrl);
|
||||
assert.equal(loader.get(day.key).loading, false);
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -271,13 +271,22 @@ test('the rendering part draws the dots, the tracked dot and the rings through t
|
||||
state._enabled = true;
|
||||
state._params = { showPoints: false, showOrbits: false };
|
||||
let at = { x: 10, y: 20, z: 30 };
|
||||
const carrier = rendering._addTrackedEntity({ position: () => at });
|
||||
const issRed = [1, 0.27, 0.27, 1];
|
||||
const carrier = rendering._addTrackedEntity({
|
||||
position: () => at,
|
||||
color: issRed,
|
||||
});
|
||||
assert.deepEqual(carrier, { noradId: 25544 });
|
||||
const tracked = draw.set(points.replace(':points', ':tracked'));
|
||||
assert.equal(tracked.items.size, 0);
|
||||
rendering._preRenderTick({ frame: 3 });
|
||||
assert.deepEqual(tracked.items.get('25544').pos, at);
|
||||
assert.equal(tracked.items.get('25544').pixelSize, 14);
|
||||
assert.deepEqual(
|
||||
tracked.items.get('25544').color,
|
||||
issRed,
|
||||
'the satellite keeps its own colour',
|
||||
);
|
||||
assert.equal(tracked.items.get('25544').disableDepthTest, Infinity);
|
||||
at = { x: 11, y: 21, z: 31 };
|
||||
rendering._preRenderTick({ frame: 4 });
|
||||
|
||||
@@ -34,12 +34,11 @@ const POINT_SCALE_BY_DISTANCE = Object.freeze({
|
||||
});
|
||||
|
||||
/**
|
||||
* The tracked satellite's dot: 14 px yellow with a white outline, drawn
|
||||
* over everything.
|
||||
* The tracked satellite's dot: 14 px in the satellite's own colour with a
|
||||
* white outline, drawn over everything. Tracking never recolours it.
|
||||
*/
|
||||
const TRACKED_DOT = Object.freeze({
|
||||
pixelSize: 14,
|
||||
color: Object.freeze([1, 1, 0, 1]),
|
||||
outlineColor: Object.freeze([1, 1, 1, 1]),
|
||||
outlineWidth: 2,
|
||||
disableDepthTest: Number.POSITIVE_INFINITY,
|
||||
@@ -386,12 +385,13 @@ export function createRendering({
|
||||
/**
|
||||
* Draw the tracked satellite's dot and make the carrier the follow target
|
||||
* and the tracked card read (its entity record holds the card).
|
||||
* @param {{position: () => object, viewFrom: {x: number, y: number,
|
||||
* z: number}}} options `position` is read as the follow camera reads
|
||||
* it, once each frame before the tick moves the sample on.
|
||||
* @param {{position: () => object, color: number[], viewFrom: {x: number,
|
||||
* y: number, z: number}}} options `position` is read as the follow
|
||||
* camera reads it, once each frame before the tick moves the sample on;
|
||||
* `color` is the satellite's own dot colour.
|
||||
* @returns {object} The carrier.
|
||||
*/
|
||||
function _addTrackedEntity({ position }) {
|
||||
function _addTrackedEntity({ position, color }) {
|
||||
const noradId = layerState._trackedNorad;
|
||||
const carrier = { noradId };
|
||||
trackedDot = {
|
||||
@@ -400,6 +400,7 @@ export function createRendering({
|
||||
id: String(noradId),
|
||||
pos: { x: 0, y: 0, z: 0 },
|
||||
...TRACKED_DOT,
|
||||
color,
|
||||
meta: { noradId },
|
||||
},
|
||||
drawn: false,
|
||||
|
||||
@@ -445,6 +445,8 @@ export function createTracking({ state: layerState, services, parts, source }) {
|
||||
|
||||
layerState._trackedEntity = parts.rendering._addTrackedEntity({
|
||||
position: trackedPosition,
|
||||
// Its own dot's colour: tracking never recolours a satellite.
|
||||
color: parts.controls._pointStyleFor(noradId, sat.group).color,
|
||||
viewFrom,
|
||||
});
|
||||
entityRecord(layerState._trackedEntity).selectionOrigin = origin;
|
||||
|
||||
@@ -4230,6 +4230,7 @@ test('the actual Transit lifecycle keeps exactly its own camera listener in ever
|
||||
onCameraChanged: noop,
|
||||
runProximityCheck: noop,
|
||||
deactivateAllCities: noop,
|
||||
showCoverage: noop,
|
||||
},
|
||||
ingestion: { abortAllInFlight: noop },
|
||||
},
|
||||
|
||||
@@ -43,6 +43,7 @@ import {
|
||||
transitModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { groundVehiclePartState } from '../../data/modelPartDrivers.js';
|
||||
|
||||
/** Layers built so far, so each one's draw sets have ids of their own. */
|
||||
let instances = 0;
|
||||
@@ -944,6 +945,25 @@ export function createRendering({ state, services, parts }) {
|
||||
display: fleet.display,
|
||||
policy: fleet.policy,
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
partState: vehiclePartState,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Wheels rolling at the speed it is drawn moving at (else its reported
|
||||
* one), doors open while it stands at a stop.
|
||||
*/
|
||||
function vehiclePartState(item, table) {
|
||||
const entry = item.entry;
|
||||
const drawn = entry?.sample?.segmentSpeedMps;
|
||||
const reported = entry?.record?.speedMps;
|
||||
return groundVehiclePartState(table, {
|
||||
speedMps: Number.isFinite(drawn)
|
||||
? drawn
|
||||
: Number.isFinite(reported)
|
||||
? reported
|
||||
: null,
|
||||
atStop: entry?.record?.status === 'STOPPED_AT',
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -216,3 +216,87 @@ test('back at live, the live poll goes out at once even while a snapshot at a ti
|
||||
assert.equal(Object.hasOwn(queries[1], 'atMs'), false);
|
||||
assert.equal(probe.applied.at(-1).rows.length, 1);
|
||||
});
|
||||
|
||||
test('back at live, only the first live vessel rows applied take over; a poll that fails or brings none says so', async () => {
|
||||
let answer = 'rows';
|
||||
const probe = ingestion({
|
||||
async getSnapshot() {
|
||||
if (answer === 'fail') throw new Error('down');
|
||||
return {
|
||||
records:
|
||||
answer === 'rows'
|
||||
? [{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 }]
|
||||
: [],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
};
|
||||
},
|
||||
});
|
||||
assert.equal(await probe.resumeLive({}), true);
|
||||
await probe.methods.update();
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }, { complete: true }],
|
||||
);
|
||||
answer = 'none';
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
answer = 'fail';
|
||||
const warn = console.warn;
|
||||
console.warn = () => {};
|
||||
try {
|
||||
assert.equal(await probe.resumeLive({}), false);
|
||||
} finally {
|
||||
console.warn = warn;
|
||||
}
|
||||
});
|
||||
|
||||
test('back at live while a live poll is already out, that poll takes over and its answer is awaited', async () => {
|
||||
let answer;
|
||||
const probe = ingestion({
|
||||
getSnapshot: () =>
|
||||
new Promise((resolve) => {
|
||||
answer = () =>
|
||||
resolve({
|
||||
records: [
|
||||
{ id: '111', latitude: 1, longitude: 2, observedAtMs: 5 },
|
||||
],
|
||||
observedAtMs: 5,
|
||||
freshness: 'current',
|
||||
complete: true,
|
||||
transportStatus: 'live',
|
||||
});
|
||||
}),
|
||||
});
|
||||
const poll = probe.methods.update();
|
||||
const resumed = probe.resumeLive({});
|
||||
answer();
|
||||
assert.equal(await resumed, true);
|
||||
await poll;
|
||||
assert.deepEqual(
|
||||
probe.applied.map(({ options }) => options),
|
||||
[{ complete: true, handover: true }],
|
||||
);
|
||||
});
|
||||
|
||||
test('without AbortSignal.any a vessel request still gives up after its timeout', async (t) => {
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
const any = AbortSignal.any;
|
||||
AbortSignal.any = undefined;
|
||||
try {
|
||||
const probe = ingestion({
|
||||
getSnapshot: (_query, { signal }) =>
|
||||
new Promise((_, reject) =>
|
||||
signal.addEventListener('abort', () => reject(signal.reason)),
|
||||
),
|
||||
});
|
||||
const resumed = probe.resumeLive({});
|
||||
await Promise.resolve();
|
||||
t.mock.timers.tick(10_000);
|
||||
assert.equal(await resumed, false);
|
||||
assert.equal(probe.feed.loading, false);
|
||||
} finally {
|
||||
AbortSignal.any = any;
|
||||
}
|
||||
});
|
||||
@@ -12,7 +12,10 @@ import { createTesting } from './testing.js';
|
||||
import { createEvidence } from './evidence.js';
|
||||
import { createQueries } from './queries.js';
|
||||
import { followsClock } from './policy.js';
|
||||
import { createSnapshotTimeline } from '../../time/snapshotTimeline.js';
|
||||
import {
|
||||
createSnapshotTimeline,
|
||||
snapshotAnswer,
|
||||
} from '../../time/snapshotTimeline.js';
|
||||
import { worldClock } from '../../time/worldClock.js';
|
||||
/** Compose one vessel layer with application-owned scene services. */
|
||||
export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
@@ -58,6 +61,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
layer.source = source;
|
||||
},
|
||||
followsClock: () => followsClock(vesselState),
|
||||
timedAnswer: snapshotAnswer,
|
||||
reloadAtClock: () => vesselState.timeline.reload(),
|
||||
});
|
||||
// Vessels follow the world clock while the source declares a timeline.
|
||||
@@ -77,9 +81,7 @@ export function createVesselLayer({ source, services, options = {} } = {}) {
|
||||
state.feed.count = state.records.all.length;
|
||||
state.feed.lastUpdate = null;
|
||||
},
|
||||
resumeLive: () => {
|
||||
void parts.ingestion.loadLivePositions(vesselState.state.viewer);
|
||||
},
|
||||
resumeLive: () => parts.ingestion.resumeLive(vesselState.state.viewer),
|
||||
});
|
||||
Object.assign(
|
||||
layer,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { AIS_FIRST_CONNECT_LABEL } from './recordPolicy.js';
|
||||
import { viewAreaMovedEnough } from './viewArea.js';
|
||||
|
||||
/** Longest a vessel request may take before it is given up. */
|
||||
const REQUEST_TIMEOUT_MS = 10_000;
|
||||
|
||||
// A portable export (package.json): no i18n here. The text stays English data
|
||||
// and the layer panel shows it translated.
|
||||
const msg = (text) => text;
|
||||
@@ -23,14 +26,62 @@ export function createIngestion({
|
||||
setSourceLabel,
|
||||
followsClock = () => false,
|
||||
reloadAtClock = () => {},
|
||||
timedAnswer = () => true,
|
||||
}) {
|
||||
// The live load in flight: its result, and its request, whose `handover`
|
||||
// may still be set while it loads (see resumeLive).
|
||||
let liveLoad = null;
|
||||
|
||||
/**
|
||||
* Poll the live vessels (or take the live poll already out). Resolves
|
||||
* when it is done, with nothing: a feed that fails is shown on the layer,
|
||||
* and turning the layer on still succeeds.
|
||||
* @param {object} viewer
|
||||
* @returns {Promise<void>}
|
||||
*/
|
||||
async function loadLivePositions(viewer) {
|
||||
await pollLive(viewer);
|
||||
}
|
||||
|
||||
/**
|
||||
* The live poll: resolves what loadPositions answers (false when it could
|
||||
* not be had), or that of the live poll already out.
|
||||
*/
|
||||
async function pollLive(viewer, { handover = false } = {}) {
|
||||
// Following the world clock, the layer shows the snapshots loadAt applies.
|
||||
if (followsClock()) return;
|
||||
if (followsClock()) return false;
|
||||
// Back at live, a snapshot at a time still loading no longer applies:
|
||||
// it would hold the live poll back until the next refresh.
|
||||
if (feed.loading && feed.loadingAtTime) dropLoad();
|
||||
await loadPositions(viewer);
|
||||
// A live load already out answers this one too.
|
||||
if (feed.loading && liveLoad) {
|
||||
if (handover) liveLoad.request.handover = true;
|
||||
return liveLoad.promise;
|
||||
}
|
||||
const request = { handover };
|
||||
const promise = loadPositions(viewer, { request });
|
||||
const load = { request, promise };
|
||||
liveLoad = load;
|
||||
try {
|
||||
return await promise;
|
||||
} finally {
|
||||
if (liveLoad === load) liveLoad = null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Back at live from another time: poll at once (or take the live poll
|
||||
* already out), and let its snapshot stand in for every vessel. Those it has keep their
|
||||
* icon and model and move on from where they are; those it lacks go.
|
||||
* Resolves true once it is applied, else false (it could not be had).
|
||||
* @param {object} [viewer]
|
||||
* @returns {Promise<boolean>}
|
||||
*/
|
||||
async function resumeLive(viewer) {
|
||||
const applied = await pollLive(viewer || readViewer(), {
|
||||
handover: true,
|
||||
});
|
||||
return applied === true;
|
||||
}
|
||||
|
||||
/** Let go of the load in flight, so another can start now. */
|
||||
@@ -44,10 +95,11 @@ export function createIngestion({
|
||||
/**
|
||||
* Apply the source's snapshot at world time `atMs` (its timeline says it
|
||||
* can answer one), in place of every vessel 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}} [options]
|
||||
* @returns {Promise<boolean>}
|
||||
* @returns {Promise<boolean|{reachMs: number}>}
|
||||
*/
|
||||
async function loadAt(atMs, { signal = null, replace = false } = {}) {
|
||||
// Whatever polls or loads for another time no longer applies: the
|
||||
@@ -56,7 +108,10 @@ export function createIngestion({
|
||||
return loadPositions(readViewer(), { atMs, replace, signal });
|
||||
}
|
||||
|
||||
async function loadPositions(viewer, { atMs, replace = false, signal } = {}) {
|
||||
async function loadPositions(
|
||||
viewer,
|
||||
{ atMs, replace = false, signal, request = null } = {},
|
||||
) {
|
||||
const timed = atMs !== undefined;
|
||||
if (!viewer || feed.loading) return false;
|
||||
feed.loading = true;
|
||||
@@ -65,18 +120,35 @@ export function createIngestion({
|
||||
const requestController = new AbortController();
|
||||
const requestSessionId = feed.sessionId;
|
||||
feed.abort = requestController;
|
||||
let timeout = null;
|
||||
|
||||
try {
|
||||
// Combine the layer's teardown-abort with a hard timeout so a hung upstream
|
||||
// can't wedge the poll indefinitely (parity with the track fetch + flights).
|
||||
const requestSignal =
|
||||
typeof AbortSignal.any === 'function'
|
||||
? AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(10000),
|
||||
...(signal ? [signal] : []),
|
||||
])
|
||||
: requestController.signal;
|
||||
let requestSignal;
|
||||
if (typeof AbortSignal.any === 'function')
|
||||
requestSignal = AbortSignal.any([
|
||||
requestController.signal,
|
||||
AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
||||
...(signal ? [signal] : []),
|
||||
]);
|
||||
else {
|
||||
// Without it, the request's own controller takes the timeout and
|
||||
// the caller's abort.
|
||||
timeout = setTimeout(
|
||||
() =>
|
||||
requestController.abort(
|
||||
new DOMException('Vessel request timed out', 'TimeoutError'),
|
||||
),
|
||||
REQUEST_TIMEOUT_MS,
|
||||
);
|
||||
signal?.addEventListener(
|
||||
'abort',
|
||||
() => requestController.abort(signal.reason),
|
||||
{ once: true },
|
||||
);
|
||||
requestSignal = requestController.signal;
|
||||
}
|
||||
// Ask for the vessels in view; a wide view asks for every vessel.
|
||||
const area = readArea(viewer);
|
||||
feed.lastArea = area;
|
||||
@@ -92,9 +164,10 @@ export function createIngestion({
|
||||
if (signal?.aborted) return false;
|
||||
// The clock left the live edge while this poll was out.
|
||||
if (!timed && followsClock()) return false;
|
||||
const takesOver = !timed && request?.handover === true;
|
||||
setSourceLabel(snapshot.source);
|
||||
// Map observations into the existing display store; source fields stop here.
|
||||
applyAisFeedSnapshot(viewer, {
|
||||
const applied = applyAisFeedSnapshot(viewer, {
|
||||
rows: snapshot.records.map(vesselDisplayRow),
|
||||
observedAtMs: snapshot.observedAtMs,
|
||||
freshness: snapshot.freshness,
|
||||
@@ -112,8 +185,12 @@ export function createIngestion({
|
||||
silentForMs: snapshot.silentForMs,
|
||||
reconnectAttempt: snapshot.reconnectAttempt,
|
||||
...(replace && { replace }),
|
||||
...(takesOver && { handover: true }),
|
||||
});
|
||||
return true;
|
||||
// Back at live, a snapshot that placed no vessel could not take over.
|
||||
if (takesOver) return applied.reconciled;
|
||||
// At a time, what the clock's follower is told of it.
|
||||
return timed ? timedAnswer(snapshot) : true;
|
||||
} catch (error) {
|
||||
// A snapshot at a time the source dropped for a newer one is no failure.
|
||||
if (timed && error?.name === 'AbortError') throw error;
|
||||
@@ -130,6 +207,7 @@ export function createIngestion({
|
||||
}
|
||||
return false;
|
||||
} finally {
|
||||
if (timeout !== null) clearTimeout(timeout);
|
||||
if (
|
||||
feed.abort === requestController &&
|
||||
feed.sessionId === requestSessionId
|
||||
@@ -197,6 +275,7 @@ export function createIngestion({
|
||||
applyRows(viewer, snapshot.acceptedRows, {
|
||||
complete: payload?.complete !== false,
|
||||
...(payload?.replace && { replace: true }),
|
||||
...(payload?.handover && { handover: true }),
|
||||
});
|
||||
feed.count = readCount();
|
||||
feed.stale =
|
||||
@@ -266,6 +345,7 @@ export function createIngestion({
|
||||
|
||||
return {
|
||||
loadLivePositions,
|
||||
resumeLive,
|
||||
loadAt,
|
||||
refreshIfMoved,
|
||||
ownsAisRequest,
|
||||
|
||||
@@ -7,6 +7,10 @@ import { createVesselIconBook } from './iconBook.js';
|
||||
import { liftedForHorizon } from '../../geo/horizon.js';
|
||||
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { VESSEL_KIND_STYLES } from '../../data/vesselTypes.js';
|
||||
import { AID_TO_NAVIGATION_STYLE } from '../../data/vesselLabels.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
|
||||
/** A query port with nothing on screen: the viewer doubles have no scene. */
|
||||
const offscreen = {
|
||||
@@ -90,7 +94,7 @@ const snapshot = (records, extra = {}) => ({
|
||||
...extra,
|
||||
});
|
||||
|
||||
test('vessel construction is inert and each instance owns its records, icon cache and clock', () => {
|
||||
test('vessel construction is inert and each instance owns its records and clock', () => {
|
||||
let requested = 0;
|
||||
const source = {
|
||||
getSnapshot() {
|
||||
@@ -99,8 +103,7 @@ test('vessel construction is inert and each instance owns its records, icon cach
|
||||
};
|
||||
const one = createVesselState({ source, services: services() });
|
||||
const two = createVesselState({ source, services: services() });
|
||||
for (const key of ['state', 'shipIconCache'])
|
||||
assert.notEqual(one[key], two[key]);
|
||||
assert.notEqual(one.state, two.state);
|
||||
assert.notEqual(one.state.records.byId, two.state.records.byId);
|
||||
assert.notEqual(one.state.feed, two.state.feed);
|
||||
assert.notEqual(one.state.records.all, two.state.records.all);
|
||||
@@ -557,7 +560,7 @@ test('AIS feed rows stay keyed by their MMSI', async () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('an aid to navigation is drawn as a disc, a vessel as its chevron', async () => {
|
||||
test('an aid to navigation is drawn as the upright buoy, a vessel as its kind’s hull turned with course', async () => {
|
||||
const aid = {
|
||||
...observation('993672001'),
|
||||
mmsi: '993672001',
|
||||
@@ -565,26 +568,62 @@ test('an aid to navigation is drawn as a disc, a vessel as its chevron', async (
|
||||
speedMps: 0,
|
||||
};
|
||||
const ship = { ...observation('366999002'), type: 'Cargo' };
|
||||
const sailing = { ...observation('366999003'), type: '36' };
|
||||
const { layer, icons } = setup({
|
||||
async getSnapshot() {
|
||||
return snapshot([aid, ship, sailing]);
|
||||
},
|
||||
});
|
||||
await layer.update();
|
||||
const itemOf = (id) => {
|
||||
assert.ok(icons.has(id), id);
|
||||
return icons.item(id);
|
||||
};
|
||||
const buoy = itemOf('993672001');
|
||||
assert.equal(buoy.image, aidSprite());
|
||||
assert.equal(buoy.rotationMode, 'screen', 'upright');
|
||||
assert.equal(buoy.rotation, 0, 'never turned');
|
||||
assert.deepEqual(buoy.color, cssColor(AID_TO_NAVIGATION_STYLE.css));
|
||||
// The source's virtual flag reaches the layer's record.
|
||||
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
|
||||
assert.equal(recordOf('993672001').virtual, false);
|
||||
assert.equal(recordOf('366999002').virtual, false);
|
||||
const cargo = itemOf('366999002');
|
||||
assert.equal(cargo.image, vesselSprite('cargo'));
|
||||
assert.equal(cargo.rotationMode, 'course');
|
||||
assert.deepEqual(cargo.color, cssColor(VESSEL_KIND_STYLES.cargo.css));
|
||||
const sail = itemOf('366999003');
|
||||
assert.equal(sail.image, vesselSprite('sailing'));
|
||||
assert.deepEqual(sail.color, cssColor(VESSEL_KIND_STYLES.sailing.css));
|
||||
// Every vessel and aid draws the same size before its speed scale.
|
||||
assert.deepEqual(cargo.size, buoy.size);
|
||||
assert.deepEqual(sail.size, buoy.size);
|
||||
});
|
||||
|
||||
test('selecting a vessel or an aid never changes its colour', async () => {
|
||||
const aid = {
|
||||
...observation('993672002'),
|
||||
mmsi: '993672002',
|
||||
type: 'Port Hand Mark',
|
||||
speedMps: 0,
|
||||
};
|
||||
const ship = { ...observation('366999004'), type: 'Cargo' };
|
||||
const { layer, icons } = setup({
|
||||
async getSnapshot() {
|
||||
return snapshot([aid, ship]);
|
||||
},
|
||||
});
|
||||
await layer.update();
|
||||
const svgOf = (id) => {
|
||||
assert.ok(icons.has(id), id);
|
||||
return atob(icons.item(id).image.split(',')[1]);
|
||||
};
|
||||
assert.match(svgOf('993672001'), /<circle/);
|
||||
// The source's virtual flag reaches the layer's record.
|
||||
const recordOf = (id) => layer.testing._vesselRecordForTest(id);
|
||||
assert.equal(recordOf('993672001').virtual, false);
|
||||
assert.equal(recordOf('366999002').virtual, false);
|
||||
assert.doesNotMatch(svgOf('993672001'), /<path/);
|
||||
assert.match(svgOf('366999002'), /<path/);
|
||||
for (const [id, css] of [
|
||||
['366999004', VESSEL_KIND_STYLES.cargo.css],
|
||||
['993672002', AID_TO_NAVIGATION_STYLE.css],
|
||||
]) {
|
||||
assert.equal(layer.selectById(id), true);
|
||||
assert.deepEqual(icons.item(id).color, cssColor(css), id);
|
||||
}
|
||||
});
|
||||
|
||||
test('a virtual aid to navigation keeps its disc and its virtual flag', async () => {
|
||||
test('a virtual aid to navigation keeps its buoy and its virtual flag', async () => {
|
||||
const aid = {
|
||||
...observation('993672009'),
|
||||
mmsi: '993672009',
|
||||
@@ -599,7 +638,7 @@ test('a virtual aid to navigation keeps its disc and its virtual flag', async ()
|
||||
await layer.update();
|
||||
assert.ok(icons.has('993672009'));
|
||||
assert.equal(layer.testing._vesselRecordForTest('993672009').virtual, true);
|
||||
assert.match(atob(icons.item('993672009').image.split(',')[1]), /<circle/);
|
||||
assert.equal(icons.item('993672009').image, aidSprite());
|
||||
});
|
||||
|
||||
test('a feed with no AISStream key reports its key as required, and a live one does not', async () => {
|
||||
|
||||
@@ -20,6 +20,7 @@ function harness({ placement = null, following = false } = {}) {
|
||||
const visuals = [];
|
||||
const state = { selectedRecord: null, trailId: null };
|
||||
const records = new VesselRecords({ now: () => 5_000_000 });
|
||||
const primitives = [];
|
||||
const rendering = {
|
||||
ensureCollections() {},
|
||||
makeOccluder: () => null,
|
||||
@@ -28,8 +29,12 @@ function harness({ placement = null, following = false } = {}) {
|
||||
visuals.push(record.id);
|
||||
return { billboard: null };
|
||||
},
|
||||
addRecordPrimitives() {},
|
||||
removeRecordPrimitives() {},
|
||||
addRecordPrimitives(record) {
|
||||
primitives.push(['add', record.id]);
|
||||
},
|
||||
removeRecordPrimitives(record) {
|
||||
primitives.push(['remove', record.id]);
|
||||
},
|
||||
shipIcon: () => 'icon',
|
||||
shipScale: () => 1,
|
||||
syncRecordIcon() {},
|
||||
@@ -41,12 +46,15 @@ function harness({ placement = null, following = false } = {}) {
|
||||
records,
|
||||
rendering,
|
||||
tracking: {},
|
||||
selection: {},
|
||||
cards: {},
|
||||
selection: { clearVesselInspection() {} },
|
||||
cards: { updateSelectedVesselHud() {} },
|
||||
followsClock: () => following,
|
||||
});
|
||||
return {
|
||||
visuals,
|
||||
primitives,
|
||||
state,
|
||||
records,
|
||||
reconcile: (rows, options) => renderer.reconcileVessels({}, rows, options),
|
||||
};
|
||||
}
|
||||
@@ -105,3 +113,61 @@ test('following the world clock, or rows at another time, tell the placement not
|
||||
harness({ placement }).reconcile([row('a')], { replace: true });
|
||||
assert.deepEqual(told, []);
|
||||
});
|
||||
|
||||
test('back at live, the first live vessel rows keep the vessels they have, drop the rest, and are told to the placement', () => {
|
||||
const { told, forgotten, placement } = recording();
|
||||
const probe = harness({ placement });
|
||||
probe.reconcile([row('a'), row('b')]);
|
||||
probe.primitives.length = 0;
|
||||
told.length = 0;
|
||||
probe.reconcile(
|
||||
[row('a', { lat: 52, last_position_epoch: 1_060 }), row('c')],
|
||||
{ handover: true },
|
||||
);
|
||||
// The vessel it has keeps its icon; the one it lacks goes; a new one is
|
||||
// added.
|
||||
assert.deepEqual(probe.primitives, [
|
||||
['add', 'c'],
|
||||
['remove', 'b'],
|
||||
]);
|
||||
assert.deepEqual(forgotten, ['b']);
|
||||
assert.deepEqual(
|
||||
told.map(([id]) => id),
|
||||
['a', 'c'],
|
||||
'live fixes, told to the placement',
|
||||
);
|
||||
});
|
||||
|
||||
test('back at live, partial vessel rows keep the vessels they lack whose newest fix is recent; complete rows pin the selected one', () => {
|
||||
const probe = harness();
|
||||
// The records' clock reads 5 000 s: 'recent' was fixed 100 s before it,
|
||||
// 'old' and 'picked' over an hour before.
|
||||
probe.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('old'),
|
||||
row('picked'),
|
||||
]);
|
||||
probe.state.selectedRecord = probe.records.byId.get('picked');
|
||||
probe.primitives.length = 0;
|
||||
probe.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
complete: false,
|
||||
handover: true,
|
||||
});
|
||||
// Partial rows prove no absence for a recent fix; an old one is gone.
|
||||
assert.ok(probe.records.byId.has('recent'));
|
||||
assert.equal(probe.records.byId.get('recent').motion, null);
|
||||
assert.equal(probe.records.byId.has('old'), false);
|
||||
|
||||
const complete = harness();
|
||||
complete.reconcile([
|
||||
row('recent', { last_position_epoch: 4_900 }),
|
||||
row('picked'),
|
||||
]);
|
||||
complete.state.selectedRecord = complete.records.byId.get('picked');
|
||||
complete.reconcile([row('c', { last_position_epoch: 4_990 })], {
|
||||
handover: true,
|
||||
});
|
||||
// Complete rows judge as a refresh does: the selected vessel is pinned for
|
||||
// a few refreshes, the rest go.
|
||||
assert.deepEqual([...complete.records.byId.keys()].sort(), ['c', 'picked']);
|
||||
});
|
||||
@@ -103,7 +103,12 @@ export class VesselRecords {
|
||||
* between the two (see motion.js). `replace`: the rows are the world at
|
||||
* another time (the clock jumped), so they stand in for every vessel: one
|
||||
* they lack is gone at once, selected or not, and none moves from where it
|
||||
* was at the time the clock left.
|
||||
* was at the time the clock left. `handover`: the first live rows after the
|
||||
* clock came back to live: a vessel they have moves to its live fix, not
|
||||
* from where it was at the time the clock left; one they lack is judged
|
||||
* as any live refresh judges it (a partial refresh, the selected vessel),
|
||||
* by how old its newest fix is rather than when it was loaded, and holds
|
||||
* at its last position meanwhile.
|
||||
*/
|
||||
reconcile(
|
||||
rows,
|
||||
@@ -112,6 +117,7 @@ export class VesselRecords {
|
||||
selectedRecord = null,
|
||||
cap = Infinity,
|
||||
replace = false,
|
||||
handover = false,
|
||||
follow = false,
|
||||
},
|
||||
effects,
|
||||
@@ -152,7 +158,7 @@ export class VesselRecords {
|
||||
record.fixReceivedAtMs = next.fixReceivedAtMs;
|
||||
record.fixFeedEpoch = next.fixFeedEpoch;
|
||||
}
|
||||
if (replace) {
|
||||
if (replace || handover) {
|
||||
record.motion = null;
|
||||
record.fixes = next.fixes;
|
||||
} else if (follow) {
|
||||
@@ -195,6 +201,13 @@ export class VesselRecords {
|
||||
}
|
||||
for (const [id, record] of this.byId) {
|
||||
if (seen.has(id)) continue;
|
||||
if (handover) {
|
||||
record.motion = null;
|
||||
record.fixes = null;
|
||||
// Loaded for another time: last seen at its newest fix.
|
||||
const fixMs = finiteNumber(record.lastPositionEpoch);
|
||||
if (fixMs !== null) record.receivedAtMs = fixMs * 1000;
|
||||
}
|
||||
if (replace) {
|
||||
effects.remove(record, record === selectedRecord);
|
||||
this.byId.delete(id);
|
||||
|
||||
@@ -43,7 +43,11 @@ import {
|
||||
vesselModelSpec,
|
||||
} from '../../data/fleetModels.js';
|
||||
import { createFleetModelLayer } from '../../data/fleetModelInstances.js';
|
||||
import { isAidToNavigation } from '../../data/vesselTypes.js';
|
||||
import { vesselPartState } from '../../data/modelPartDrivers.js';
|
||||
import { isAidToNavigation, vesselKind } from '../../data/vesselTypes.js';
|
||||
import { aidSprite, vesselSprite } from '../../data/vesselSprites.js';
|
||||
import { cssColor } from '../../render/color.js';
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
/** A moving vessel's next frame is asked for once it would move this far on
|
||||
* screen (pixels), so it glides when it moves visibly and the scene idles
|
||||
@@ -55,11 +59,14 @@ const PLACEMENT_FRAME_MS = 1000;
|
||||
* ms), so one that comes into view is judged where it is. */
|
||||
const HIDDEN_FOLLOW_MS = 250;
|
||||
|
||||
/** The ship artwork's own raster size (px). */
|
||||
/** A vessel or aid sprite's drawn size before its scale (CSS px). */
|
||||
const SHIP_ICON_PX = 32;
|
||||
|
||||
let instances = 0;
|
||||
|
||||
/** Tint by CSS colour: a handful of type colours. */
|
||||
const tints = new Map();
|
||||
|
||||
/** How often the vessels near enough for a model are gathered again (wall ms). */
|
||||
const MODEL_CANDIDATES_MS = 500;
|
||||
|
||||
@@ -404,7 +411,7 @@ export function createRendering({
|
||||
|
||||
/** The icon item a record draws, as it now is. */
|
||||
function iconItem(record, visual) {
|
||||
const selected = record === state.selectedRecord;
|
||||
const aid = isAidToNavigation(record);
|
||||
const courseDeg = vesselCourseDeg(record);
|
||||
// Following the clock, not there yet at the time drawn.
|
||||
visual.seen = seenYet(record);
|
||||
@@ -418,11 +425,14 @@ export function createRendering({
|
||||
// is not there yet.
|
||||
show: !isCockpitSubject(record) && !visual.modelOwnsVisual && visual.seen,
|
||||
pos: plan?.pos ?? visual.position,
|
||||
image: shipIcon(record, selected),
|
||||
image: shipIcon(record),
|
||||
size: [SHIP_ICON_PX, SHIP_ICON_PX],
|
||||
// Selection changes the colour only, never the size.
|
||||
// Tinted by type; selection changes neither the colour nor the size.
|
||||
color: shipTint(record),
|
||||
scale: shipScale(record),
|
||||
rotationMode: 'course',
|
||||
// An aid's buoy stands upright on screen; a vessel turns with course.
|
||||
rotationMode: aid ? 'screen' : 'course',
|
||||
rotation: 0,
|
||||
// Held on course, or along its track on the renderer's clock;
|
||||
// `course` for renderers without motion segments.
|
||||
course: courseDeg,
|
||||
@@ -519,40 +529,33 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* Build (and cache) a chevron/delta-wing SVG data URL tinted for the vessel.
|
||||
* The shape points north (up) so the row's course maps directly to heading.
|
||||
* An aid to navigation, which has no heading, is a ringed disc instead.
|
||||
* One icon is generated per color+variant and shares one atlas slot.
|
||||
* @param {Object} record - Vessel record (drives per-type tint).
|
||||
* @param {boolean} selected - True for the white/brighter selected variant.
|
||||
* The sprite a vessel is drawn as: the white hull of its kind
|
||||
* (`vesselKind`), bow up so the row's course turns it to its heading, or
|
||||
* for an aid to navigation the buoy. The layer tints it
|
||||
* (`shipTint`), so each shape takes one icon-atlas slot.
|
||||
* @param {Object} record - Vessel record.
|
||||
* @returns {string} SVG data URL.
|
||||
*/
|
||||
|
||||
function shipIcon(record, selected) {
|
||||
const aid = isAidToNavigation(record);
|
||||
const cssColor = selected
|
||||
? '#ffffff'
|
||||
: aid
|
||||
? AID_TO_NAVIGATION_STYLE.css
|
||||
: vesselTypeCss(record.type);
|
||||
const key = `${cssColor}:${selected ? 'selected' : 'normal'}:${aid ? 'aid' : 'ship'}`;
|
||||
if (vesselState.shipIconCache.has(key))
|
||||
return vesselState.shipIconCache.get(key);
|
||||
function shipIcon(record) {
|
||||
return isAidToNavigation(record)
|
||||
? aidSprite()
|
||||
: vesselSprite(vesselKind(record.type));
|
||||
}
|
||||
|
||||
const stroke = selected ? 'rgba(6,26,32,0.95)' : 'rgba(4,18,24,0.9)';
|
||||
const strokeWidth = selected ? 1.1 : 0.7;
|
||||
const shape = aid
|
||||
? `<circle r="8" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth * 2}"/>
|
||||
<circle r="3" fill="${stroke}"/>`
|
||||
: `<path d="M0,-14 L11,10 L4,7 L0,14 L-4,7 L-11,10 Z" fill="${cssColor}" stroke="${stroke}" stroke-width="${strokeWidth}" stroke-linejoin="round"/>`;
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="32" height="32" viewBox="0 0 32 32">
|
||||
<g transform="translate(16,16)">
|
||||
${shape}
|
||||
</g>
|
||||
</svg>`;
|
||||
const icon = 'data:image/svg+xml;base64,' + btoa(svg);
|
||||
vesselState.shipIconCache.set(key, icon);
|
||||
return icon;
|
||||
/**
|
||||
* A vessel's tint, `[r, g, b, a]`: its type's colour (vesselLabels.js,
|
||||
* shared with its card), an aid's bone white.
|
||||
* @param {Object} record - Vessel record.
|
||||
*/
|
||||
|
||||
function shipTint(record) {
|
||||
const css = isAidToNavigation(record)
|
||||
? AID_TO_NAVIGATION_STYLE.css
|
||||
: vesselTypeCss(record.type);
|
||||
let tint = tints.get(css);
|
||||
if (!tint) tints.set(css, (tint = Object.freeze(cssColor(css))));
|
||||
return tint;
|
||||
}
|
||||
|
||||
// Under the DISPLAY rail's 3D toggle, vessels near the camera are drawn as
|
||||
@@ -578,6 +581,13 @@ export function createRendering({
|
||||
resolveAsset: fleet.resolveAsset,
|
||||
// A hull below the waterline would show through a plain globe.
|
||||
waterline: true,
|
||||
// Its radar sweeps while it is under way (speed in knots).
|
||||
partState: (item, table) =>
|
||||
vesselPartState(table, {
|
||||
speedMps: Number.isFinite(item.record?.speed)
|
||||
? item.record.speed * KNOT_MPS
|
||||
: null,
|
||||
}),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -614,11 +624,7 @@ export function createRendering({
|
||||
? findCamera(state.viewer)?.pose()?.position
|
||||
: null;
|
||||
if (!eye) return;
|
||||
const policy = services.fleet.policy;
|
||||
const keepM =
|
||||
services.fleet.display?.()?.models3dMode === 'all'
|
||||
? policy.keepAllM
|
||||
: policy.keepM;
|
||||
const keepM = services.fleet.policy.keepM;
|
||||
const limitSq = keepM * keepM * 1.44;
|
||||
for (const record of state.records.all) {
|
||||
const waterline = getVisual(record).waterline;
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
const KNOT_MPS = 1852 / 3600;
|
||||
import { KNOT_MPS } from '../../data/units.js';
|
||||
|
||||
const finiteOrNaN = (value) =>
|
||||
typeof value === 'number' && Number.isFinite(value) ? value : NaN;
|
||||
|
||||
@@ -34,11 +35,15 @@ export function createVesselSnapshotRenderer({
|
||||
cards,
|
||||
followsClock = () => false,
|
||||
}) {
|
||||
/** `replace`: the rows are the world at another time (see VesselRecords). */
|
||||
/**
|
||||
* `replace`: the rows are the world at another time (see VesselRecords).
|
||||
* `handover`: the first live rows after the clock came back to live (see
|
||||
* VesselRecords); they are live fixes.
|
||||
*/
|
||||
function reconcileVessels(
|
||||
viewer,
|
||||
rows,
|
||||
{ complete = true, replace = false } = {},
|
||||
{ complete = true, replace = false, handover = false } = {},
|
||||
) {
|
||||
rendering.ensureCollections(viewer);
|
||||
const occluder = rendering.makeOccluder();
|
||||
@@ -57,6 +62,7 @@ export function createVesselSnapshotRenderer({
|
||||
selectedRecord: state.selectedRecord,
|
||||
cap: rendering.renderRowLimit(),
|
||||
...(replace && { replace }),
|
||||
...(handover && { handover }),
|
||||
...(follow && { follow }),
|
||||
},
|
||||
{
|
||||
|
||||
@@ -53,10 +53,6 @@ export function createVesselState({ source, services }) {
|
||||
|
||||
vesselState._geoidReady = false;
|
||||
|
||||
/** @type {Map<string, string>} `${cssColor}:${variant}` -> chevron SVG data URL */
|
||||
|
||||
vesselState.shipIconCache = new Map();
|
||||
|
||||
/** Row ids for unkeyed (no-id) records, which are rebuilt every poll. */
|
||||
|
||||
vesselState._unkeyedIconSequence = 0;
|
||||
|
||||
@@ -544,7 +544,7 @@ test('retention never revives an incumbent card after the observation window exp
|
||||
test('all heights and the sampled fallback use the same sightings-in-view count label', () => {
|
||||
const h = harness();
|
||||
h.state.renderedRows = [sighting];
|
||||
assert.equal(h.layer.getStats().countLabel, '1 sightings in view');
|
||||
assert.equal(h.layer.getStats().countLabel, '1 sighting in view');
|
||||
h.state.sightingCount = 2000;
|
||||
assert.equal(h.layer.getStats().count, 2000);
|
||||
assert.equal(
|
||||
@@ -562,6 +562,32 @@ test('all heights and the sampled fallback use the same sightings-in-view count
|
||||
}
|
||||
});
|
||||
|
||||
test('the sightings count takes the plural form of its number', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const h = harness();
|
||||
const label = (count) => {
|
||||
h.state.sightingCount = count;
|
||||
return h.layer.getStats().countLabel;
|
||||
};
|
||||
setLocale('ru');
|
||||
assert.equal(label(1), '1 наблюдение в кадре');
|
||||
assert.equal(label(3), '3 наблюдения в кадре');
|
||||
assert.equal(label(5), '5 наблюдений в кадре');
|
||||
setLocale('de');
|
||||
assert.equal(label(1), '1 Beobachtung im Bild');
|
||||
assert.equal(label(2000), '2.000 Beobachtungen im Bild');
|
||||
});
|
||||
|
||||
test('the CONFIRMED chip names the sightings, apart from a confirmed launch landing', (t) => {
|
||||
t.after(() => setLocale('en'));
|
||||
const h = harness();
|
||||
assert.equal(h.chip('quality-confirmed').label, 'CONFIRMED');
|
||||
setLocale('sv');
|
||||
assert.equal(h.chip('quality-confirmed').label, 'BEKRÄFTADE');
|
||||
setLocale('es');
|
||||
assert.equal(h.chip('quality-confirmed').label, 'CONFIRMADOS');
|
||||
});
|
||||
|
||||
test('a stale fallback with a failed-refresh deadline remains DEGRADED, retryable and dated to the cached data', async () => {
|
||||
const h = harness({
|
||||
getSnapshotDetail: async () => ({
|
||||
|
||||
+9
-5
@@ -1,4 +1,4 @@
|
||||
import { t, formatNumber, translateKnown } from '../../i18n/index.js';
|
||||
import { t, tn, formatNumber, translateKnown } from '../../i18n/index.js';
|
||||
import { msg } from '../../i18n/marker.js';
|
||||
import { translateFeedError } from '../../ui/statusText.js';
|
||||
import { wildlifeIconicGroup } from './model.js';
|
||||
@@ -138,7 +138,8 @@ export function createControls({ state, services, parts }) {
|
||||
const chips = [
|
||||
chip({
|
||||
id: WILDLIFE_CONFIRMED_CHIP_ID,
|
||||
label: t('CONFIRMED'),
|
||||
// The sightings, plural; a launch landing is CONFIRMED alone.
|
||||
label: t('CONFIRMED', { context: 'sightings filter' }),
|
||||
title: t('Show only community-confirmed (research-grade) sightings'),
|
||||
params: {
|
||||
confirmed: confirmedFailed ? state.confirmed : !state.confirmed,
|
||||
@@ -215,9 +216,12 @@ export function createControls({ state, services, parts }) {
|
||||
stale: state.stale,
|
||||
loading,
|
||||
refreshing,
|
||||
countLabel: t('{count} sightings in view', {
|
||||
count: formatNumber(count),
|
||||
}),
|
||||
countLabel: tn(
|
||||
count,
|
||||
'{count} sighting in view',
|
||||
'{count} sightings in view',
|
||||
{ count: formatNumber(count) },
|
||||
),
|
||||
loadingLabel: loading
|
||||
? t('loading...')
|
||||
: refreshing
|
||||
|
||||
@@ -1936,7 +1936,7 @@ test('unavailable grids fail closed to visible sampled sprites without a global
|
||||
assert.equal(h.clicks.collection.values[0].id, 'wildlife:inat:1');
|
||||
assert.ok(h.clicks.collection.values[0].size[0] * 0.5 >= 8);
|
||||
assert.equal(h.layer.getStats().count, 1);
|
||||
assert.match(h.layer.getStats().countLabel, /sightings in view/);
|
||||
assert.equal(h.layer.getStats().countLabel, '1 sighting in view');
|
||||
assert.equal(h.layer.getStats().partial, undefined);
|
||||
assert.equal(layerFeedState(h.layer.getStats()), 'degraded');
|
||||
assert.match(h.layer.getStats().error, /Malformed iNaturalist grid response/);
|
||||
@@ -1973,7 +1973,7 @@ test('an oversized view coarsens to a complete grid within the six-tile cap', as
|
||||
await h.update();
|
||||
assert.equal(h.clicks.collection.values.length, 1);
|
||||
assert.equal(h.clicks.collection.values[0].id, 'wildlife:inat:1');
|
||||
assert.match(h.layer.getStats().countLabel, /sightings in view/);
|
||||
assert.match(h.layer.getStats().countLabel, /sightings? in view/);
|
||||
assert.equal(layerFeedState(h.layer.getStats()), 'nominal');
|
||||
h.layer.destroy();
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user