Merge remote-tracking branch 'origin/main' into german/cctv-camera-counts

# Conflicts:
#	src/layers/cctv/lifecycle.test.mjs
This commit is contained in:
German Khokhlov committed 2026-11-19 14:34:39 +04:00
commit 2b7a6b0c63
1463 files changed
+48705 -10313

No files matched your search

+4
View File
@@ -1,5 +1,6 @@
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
@@ -581,6 +582,9 @@ export function createAlprPresentation({ state, services, source }) {
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// The painted overlay answers first; the scene is picked only if not.
const hit = event.drawHit;
const id =
+176
View File
@@ -0,0 +1,176 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { createAlprMarkerSet } from './markerState.js';
import { createAlprPresentation } from './presentation.js';
/** One camera drawn and painted at (100, 100), over a viewer whose clicks a
* label may take. */
function harness(t) {
const previousImage = globalThis.Image;
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
globalThis.Image = class {
complete = true;
naturalWidth = 128;
};
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 100, y: 100 });
const record = {
id: 'camera:0',
latitude: 30,
longitude: -97,
directionDeg: 90,
};
const drawPort = fakeDrawPort();
const markers = createAlprMarkerSet();
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
const viewer = {
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500),
pickEllipsoid: () => Cesium.Cartesian3.fromDegrees(-97, 30),
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
globe: { show: true, getHeight: () => 150 },
pick: () => null,
},
};
const { unbind } = bindFakeCesiumScene(viewer, { draw: drawPort });
const fake = fakeInputUnderLabel(viewer);
const state = {
viewer,
enabled: true,
selectedId: null,
markers,
records: [record],
recordById: new Map([[record.id, record]]),
renderRevision: 0,
lastAnchorSampleAt: 0,
};
let selected = null;
let paint;
const presentation = createAlprPresentation({
state,
source: { label: 'Test cameras' },
services: {
render: { governorRequestRender() {} },
context: {
clearSelectedEntityContextForLayer() {
selected = null;
},
getSelectedEntityContext: () => selected,
registerEntityContext() {},
removeEntityContextsForLayer() {},
selectEntityContext(carrier) {
selected = { id: carrier.id, layerId: 'alpr-cameras' };
},
},
groundFloor: { cachedGroundFloor: () => 150 },
overlays: {
registerPaintLane(_lane, painter) {
paint = painter;
return { setActive() {}, requestPaint() {}, unregister() {} };
},
keyholeAlpha: () => 1,
},
},
});
presentation.initOverlay();
presentation.installInteraction(viewer);
t.after(() => {
presentation.destroyOverlay();
fake.destroy();
unbind();
if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project;
});
presentation.renderRecords();
const ctx = {
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
moveTo() {},
lineTo() {},
closePath() {},
stroke() {},
fill() {},
createLinearGradient: () => ({ addColorStop() {} }),
drawImage() {},
};
paint({ ctx, width: 800, height: 600 });
return { state, fake, at: { x: 100, y: 100 } };
}
test('a click on a mission label over a camera never selects it, and keeps the selected camera', (t) => {
const h = harness(t);
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, null, 'the camera under the label');
// Off the label, the same click selects the camera.
h.fake.label.over = false;
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0');
// The label on top is its own click: the selection stays.
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0', 'the selection stays');
});
// The card or label painted on top takes the click: ALPR does not even pick
// under another layer's card, so no camera is selected or released there.
test("another layer's card over an ALPR camera keeps the click", (t) => {
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const noop = () => {};
const state = {
enabled: true,
viewer,
clickSubscription: null,
markers: { icons: null },
recordById: new Map(),
selectedId: null,
};
const presentation = createAlprPresentation({
state,
services: {
render: { governorRequestRender: noop },
context: {
clearSelectedEntityContextForLayer: noop,
getSelectedEntityContext: () => null,
registerEntityContext: noop,
removeEntityContextsForLayer: noop,
selectEntityContext: noop,
},
groundFloor: { cachedGroundFloor: () => null },
},
});
presentation.installInteraction(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => {
setClickCardHitTest(null);
state.clickSubscription?.();
input.destroy();
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+3 -7
View File
@@ -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 || '');
}
/**
+1 -1
View File
@@ -96,7 +96,7 @@ export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
* (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they
* rest too. While they run they never hold
* continuous rendering; each drawn frame arms one more step after the
* Cyber sonar's 80 ms cadence, so the two never beat. Fronts and band,
* sonar's 80 ms cadence, so the two never beat. Fronts and band,
* fixed in the world, step at that cadence however many frames are
* drawn, so they look the same whether the camera moves or not; crossing
* the rim height shows or hides them at once.
+6 -6
View File
@@ -430,7 +430,7 @@ export function createRangeRing({
* Run the range pulses again for `activeMs`, after a camera move. Call it
* during a frame (lifecycle's preRender): that frame's postRender arms the
* next request, so waking asks for no extra frame of its own. Pulses at
* rest start in this frame; running ones keep their Cyber sonar interval,
* rest start in this frame; running ones keep their sonar interval,
* however many frames a drag draws.
*/
function wakePulses() {
@@ -506,7 +506,7 @@ export function createRangeRing({
const { lines, band } = setsOn(viewer);
const frame = findFrame(viewer);
// A renderer without frame hooks gets the static ring only, as the
// Cyber sonar scene does. So does a viewer who prefers reduced motion.
// sonar scene does. So does a viewer who prefers reduced motion.
const animate = Boolean(!reducedMotion && frame?.on);
// Pulses run from now until `wake.untilMs`, then rest.
const wake = animate
@@ -681,7 +681,7 @@ export function createRangeRing({
bandShown = false;
return;
}
// The soft band is painted at most once a Cyber sonar interval;
// The soft band is painted at most once a sonar interval;
// the fronts, crisp lines, move on every step.
if (
bandShown &&
@@ -726,7 +726,7 @@ export function createRangeRing({
// Whether the camera was below the rim at the last step.
let wasBelow = belowRim();
// The fronts and band are fixed in the world: a camera move needs
// nothing of them, so they step a Cyber sonar interval apart however
// nothing of them, so they step a sonar interval apart however
// many frames are drawn, and look the same parked or moving. Each
// frame checks only whether the camera crossed the rim height, which
// shows or hides them at once. A step asks for the frame that draws
@@ -746,8 +746,8 @@ export function createRangeRing({
stepRunning(nowMs);
}
});
// Each drawn frame, whoever asked for it, arms one step a Cyber
// sonar interval later, as the Cyber sonar scene does, whose changes
// Each drawn frame, whoever asked for it, arms one step a
// sonar interval later, as the sonar scene does, whose changes
// ask for the frame that draws them. Requests never land within
// 80 ms of a frame, so they cannot beat the detection lane's 80 ms
// gate, and they stop once the pulses rest.
+3 -3
View File
@@ -488,7 +488,7 @@ test('pulses ask for a frame 80 ms after each drawn frame instead of holding con
const { rendering, pulseFrames } = ring;
const loop = frameLoop(t, ring);
rendering.renderVisual(flight(3));
// A Contacts view repaints at the Cyber sonar cadence, ~12.5 fps, while
// A Contacts view repaints at the sonar cadence, ~12.5 fps, while
// the pulses run, never every display frame.
assert.equal(pulseFrames(), 0);
loop.advance(1); // the frame the new ring asked for arms the first request
@@ -972,14 +972,14 @@ test('disabling the layer tears the pulses down completely', (t) => {
);
});
test('pulse requests wait 80 ms after any frame, so they cannot beat the Cyber sonar', (t) => {
test('pulse requests wait 80 ms after any frame, so they cannot beat the sonar', (t) => {
const ring = ringRendering(t);
const { rendering, pulseFrames } = ring;
const loop = frameLoop(t, ring);
rendering.renderVisual(flight(3));
loop.advance(1);
const frames = pulseFrames();
// Another owner (the Cyber sonar, a data update) draws 67 ms after ours.
// Another owner (the sonar, a data update) draws 67 ms after ours.
loop.advance(67);
loop.draw();
loop.advance(CYBER_SONAR_RENDER_INTERVAL_MS - 1);
+139
View File
@@ -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');
});
+18 -2
View File
@@ -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;
+16
View File
@@ -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;
+26
View File
@@ -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;
}
/**
+50
View File
@@ -1,10 +1,15 @@
import { t } from '../../i18n/index.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
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,16 +144,60 @@ 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;
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (hit) {
// 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 +232,6 @@ export function createSelection({
_selectStation,
_installClickHandler,
_onKeyDown,
coverageCityOf,
};
}
+68
View File
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
/** A station layer's selection on a viewer whose pick is scripted. */
function harness(t) {
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
let picked = null;
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
const input = fakeInput(viewer);
const noop = () => {};
const state = {
_selectedKey: null,
_clickSubscription: null,
_stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
_stationSet: { id: 'bikeshare:stations', upsert: noop },
_selectedSet: {
id: 'bikeshare:selected',
set: noop,
size: () => 0,
clear: noop,
},
_overlayHost: { setEntries: noop, clearSource: noop },
};
const selection = createSelection({
state,
services: {},
parts: { rendering: { stationItem: () => ({}) } },
});
selection._installClickHandler(viewer);
t.after(() => {
state._clickSubscription?.();
input.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
return {
state,
click(hit) {
picked = hit ? { id: hit } : null;
input.tap({ x: 10, y: 10 });
},
};
}
// The card or label painted on top takes the click: a station under another
// layer's card is neither selected nor let go.
test("another layer's card over a station keeps the click", (t) => {
const h = harness(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const station = { set: 'bikeshare:stations', id: 'nyc:1' };
h.click(station);
assert.equal(h.state._selectedKey, null, 'covered: not selected');
top = null;
h.click(station);
assert.equal(h.state._selectedKey, 'nyc:1');
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
h.click(null);
assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
top = null;
h.click(null);
assert.equal(h.state._selectedKey, null, 'open map lets it go');
});
+11
View File
@@ -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;
+15
View File
@@ -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,
};
}
+19
View File
@@ -336,6 +336,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={}]
+20 -24
View File
@@ -23,7 +23,7 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -420,6 +420,20 @@ export function createLifecycle({
(event) => {
if (!layerState._enabled) return;
const picked = event.topHit;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: a live card of ours acts whatever
// is drawn under it; another layer's is that layer's click.
const top = clickCard?.(event) ?? null;
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
if (top) {
// A card of ours that is going away is still not the scene.
if (layerState._recordById.has(top.entryId))
activateCctvCameraFromWorldClick(
top.entryId,
parts.selection.setActiveCamera,
);
return;
}
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
@@ -430,29 +444,11 @@ export function createLifecycle({
);
return;
}
// Any identified scene object owns this click even if its layer does not
// register a shared pick predicate. This keeps selectable siblings ahead
// of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
// remain eligible for true empty-space deselection.
const pickedId = resolvePickId(picked);
if (pickedId !== null) return;
// Item A (owner round 2): the scene pick found no camera — try the
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
event.screenPosition.x,
event.screenPosition.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
activateCctvCameraFromWorldClick(
cardId,
parts.selection.setActiveCamera,
);
return;
}
// Any identified scene object owns this click even if its layer
// does not register a shared pick predicate. This keeps selectable
// siblings ahead of the CCTV selection while ID-less globe, terrain
// and tile surfaces remain eligible for empty-space deselection.
if (resolvePickId(picked) !== null) return;
if (
parts.selection.cctvEmptyClickDeselects(picked, {
activeCameraId: layerState._activeCameraId,
+266
View File
@@ -1,6 +1,10 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { createSelection } from './selection.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
@@ -106,3 +110,265 @@ test('terrain loading and surface changes rerun the view pass', () => {
lifecycle.detachViewListeners();
assert.ok(removed);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
new Proxy(own, {
get: (target, name) => (name in target ? target[name] : () => {}),
});
test("a click on a mission label over a camera's card never turns that camera on, and keeps the active one", async (t) => {
const { viewer } = viewerWithCamera();
viewer.scene = { canvas: {}, pick: () => null };
// The card of camera `cam-1` lies under every click, under the label.
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({ sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }),
});
t.after(() => fake.destroy());
const activated = [];
const deactivated = [];
const state = {};
const lifecycle = createLifecycle({
state,
services: {
activation: {
activateCctvCameraFromWorldClick: (id) => activated.push(id),
},
picking,
focus: {},
render: {},
},
parts: {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => null,
},
rendering: inert({ refreshHorizonCulling: () => false }),
health: { syncHealthState: async () => {} },
geometryQueue: inert(),
cards: inert(),
projection: inert(),
presentation: inert(),
navigation: inert(),
hover: inert(),
selection: {
// The camera's own gate takes only clean clicks; these are.
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
extractPickedCameraId: () => null,
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
Boolean(activeCameraId) && picking.resolvePickId(picked) === null,
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
},
},
});
// Init's bounded wait for ground heights never runs out here: they are in.
t.mock.timers.enable({ apis: ['setTimeout'] });
await lifecycle.methods.init(viewer);
t.after(() => state._clickSubscription?.());
state._enabled = true;
state._activeCameraId = 'cam-0';
state._recordById.set('cam-1', {});
fake.label.over = true;
fake.click();
assert.deepEqual(activated, [], 'the camera under the label stays off');
assert.deepEqual(deactivated, [], 'the active camera stays on');
// Off the label, a click on the card turns its camera on.
fake.label.over = false;
fake.click();
assert.deepEqual(activated, ['cam-1']);
});
test('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
const noop = () => {};
const { viewer } = viewerWithCamera();
let picked = null;
viewer.scene = {
canvas: {},
pick: () => (picked ? { id: picked } : undefined),
drillPick: () => drilled.map((id) => ({ id })),
};
let drilled = [];
const input = fakeInput(viewer);
// An aircraft layer that runs before ours and tracks the plane it was
// clicked on, standing aside under another layer's card.
let tracked = null;
input.input.onClick((event) => {
if (picking.isUnderOtherCard(event)) return;
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
});
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
const foreignCard = {
sourceId: 'earthquake-card',
entryId: 'earthquake-card:qa',
};
let painted = [];
const actions = [];
// The card on top at a click, as the host answers the pick registry.
picking.setClickCardHitTest(() => painted[0] ?? null);
const state = {
_cctvOverlayHost: {
hitTest: (_x, _y, options = {}) =>
painted.find(
(hit) => !options.sourceId || hit.sourceId === options.sourceId,
) ?? null,
},
};
const parts = {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => 'terrain-globe',
},
cards: { teardownAmbientCards: noop },
projection: { clearProjectionOverlay: noop },
geometryQueue: { stopGeometryLoadQueue: noop },
rendering: {
createCameraIcons: noop,
refreshHorizonCulling: () => false,
refreshCoverageStyles: noop,
extractPickedCameraId: (hit) =>
hit?.set === 'cctv:fixture' ? hit.id : null,
},
hover: { handleHoverMove: noop },
health: { syncHealthState: async () => {} },
presentation: { notifyListeners: noop },
};
const services = {
sprites: {},
focus: { onFocusTargetAppear: () => noop },
render: { releaseContinuousRender: noop },
picking,
activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) },
};
parts.selection = createSelection({ state, services, parts });
parts.selection.deactivateActiveCamera = () => actions.push('clear');
const lifecycle = createLifecycle({ state, services, parts });
t.after(() => {
state._clickSubscription?.();
lifecycle.detachViewListeners();
input.destroy();
picking.setClickCardHitTest(null);
picking.unregisterPickOwner('area-control');
picking.unregisterPickOwner('test-trails');
picking.unregisterPickOwner('test-planes');
picking.unregisterPickOwner('test-tracking');
picking.unregisterPickOwner('test-exact');
});
await lifecycle.methods.init(viewer);
state._enabled = true;
state._activeCameraId = 'cam-1';
state._recordById.set('cam-1', { camera: { id: 'cam-1' } });
const click = (hit, cards, expected) => {
picked = hit;
painted = cards;
actions.length = 0;
input.tap();
assert.deepEqual(actions, expected, JSON.stringify({ hit, cards }));
};
const drone = {
set: 'drone-airspace:1:fills',
id: 'drone-airspace:zone:0',
surface: false,
};
const perimeter = {
set: 'fire-perimeters:1:lines',
id: 'fire-perimeter:incident:0',
surface: false,
};
const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false };
const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false };
const launch = {
set: 'launches:1:markers',
id: 'rocket-x:1',
surface: false,
};
const backgrounds = [drone, perimeter, quake, cable, launch];
for (const area of backgrounds) {
click(area, [ownCard], ['cam-1']);
click(area, [], []);
click(area, [foreignCard, ownCard], []);
}
// The live top card acts over anything drawn under it; with no card an
// identified object is not empty map.
for (const hit of [
{ set: 'flights:1', id: 'aircraft', surface: false },
{ set: '', id: 'unregistered-local-entity', surface: false },
{ ...drone, set: 'unrelated:1:fills' },
{ ...drone, id: 'unregistered-local-entity' },
]) {
click(hit, [ownCard], ['cam-1']);
click(hit, [], []);
}
// A trail under the live top card: the card keeps the click, and with no
// card the owned pick is not empty map.
const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false };
picking.registerPickOwner('test-trails', (id) => id === trail.id);
click(trail, [ownCard], ['cam-1']);
click(trail, [], []);
click(trail, [foreignCard, ownCard], []);
picking.unregisterPickOwner('test-trails');
// A coarse tap whose touch contact is an aircraft (a layer that acts on
// nearby contacts) under a live CCTV card is the card's.
const previousMatch = globalThis.matchMedia;
const restoreMatch = () => {
if (previousMatch) globalThis.matchMedia = previousMatch;
else delete globalThis.matchMedia;
};
// Restored below for the fine-pointer clicks that follow; here too, so a
// failing assertion cannot leave the coarse pointer for later tests.
t.after(restoreMatch);
globalThis.matchMedia = () => ({ matches: true });
picking.registerPickOwner('test-planes', (id) => id === 'plane:1');
drilled = ['plane:1'];
click(null, [ownCard], ['cam-1']);
// With no card, the bare tap near the aircraft still deselects.
click(null, [], ['clear']);
// A contact whose layer acts only on exact hits leaves the card its tap.
picking.registerPickOwner('test-exact', (id) => id === 'exact:1');
drilled = ['exact:1'];
click(null, [ownCard], ['cam-1']);
picking.unregisterPickOwner('test-exact');
drilled = [];
click(null, [ownCard], ['cam-1']);
picking.unregisterPickOwner('test-planes');
restoreMatch();
// The live card over an aircraft takes the click; the aircraft layer,
// run first, stands aside and does not track.
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
click(
{ set: 'flights:1', id: 'plane:9', surface: false },
[ownCard],
['cam-1'],
);
assert.equal(tracked, null, 'the aircraft did not track');
picking.unregisterPickOwner('test-tracking');
picking.registerPickOwner('area-control', (id) => id === drone.id);
click(drone, [ownCard], ['cam-1']);
picking.unregisterPickOwner('area-control');
click(null, [foreignCard, ownCard], []);
click(null, [ownCard], ['cam-1']);
click(null, [], ['clear']);
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
// A card of ours that is going away is still not the scene under it: no
// camera beneath it activates, and nothing clears.
const staleCard = { ...ownCard, entryId: 'stale-camera' };
click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
click(null, [staleCard], []);
// A camera icon under another layer's card is that card's click.
click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
});
+24 -7
View File
@@ -12,14 +12,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) {
@@ -36,6 +42,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.
@@ -214,6 +230,7 @@ export function createNavigation({
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
}
return {
nearestCameraIdToPoint,
nearestCameraIdToViewer,
openingCameraId,
reopenNearestCamera,
+53
View File
@@ -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);
}
});
+10 -62
View File
@@ -1,7 +1,6 @@
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { inputFor } from '../../input/dispatcher.js';
import {
clickCard,
registerPickOwner,
unregisterPickOwner,
} from '../../data/pickRegistry.js';
@@ -79,7 +78,6 @@ const intensityText = (storm) => {
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
feed,
hitTestOverlay = hitTestWorldOverlay,
overlayHost,
context = null,
createRendering = createCycloneRendering,
@@ -97,8 +95,7 @@ export function createCyclonesLayer({
selectionIntent = 'auto',
navigationGeneration = 0,
selectionOwner = null,
selectedContextStormId = null,
removeClickCapture = null;
selectedContextStormId = null;
let enabled = false,
loading = false,
error = null,
@@ -169,75 +166,28 @@ export function createCyclonesLayer({
rendering?.setSelection(id);
}
function installSelection() {
const canvas = canvasOf(viewer);
if (selectionOwner || !canvas) return;
if (selectionOwner || !canvasOf(viewer)) return;
const owner = {};
selectionOwner = owner;
// Snapshot before sibling bubble listeners can rebuild the overlay hit
// rectangles. A vessel selection does that synchronously in the same click.
let capturedHit = null;
const overlayHit = (x, y) => {
const hit = hitTestOverlay(x, y);
return { sourceId: hit?.sourceId, entryId: hit?.entryId };
};
const capture = (event) => {
capturedHit = null;
const point = event.changedTouches?.[0] || event;
if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
return;
const rect = canvas.getBoundingClientRect();
const x = point.clientX - rect.left,
y = point.clientY - rect.top;
capturedHit = { x, y, ...overlayHit(x, y) };
};
const resetCapture = () => {
capturedHit = null;
};
const resetEvents = [
'pointerdown',
'mousedown',
'touchstart',
'pointercancel',
'touchcancel',
];
for (const type of resetEvents)
canvas.addEventListener?.(type, resetCapture, { capture: true });
const events = ['pointerup', 'mouseup', 'touchend'];
for (const type of events)
canvas.addEventListener?.(type, capture, { capture: true });
removeClickCapture = () => {
for (const type of events)
canvas.removeEventListener?.(type, capture, { capture: true });
for (const type of resetEvents)
canvas.removeEventListener?.(type, resetCapture, { capture: true });
capturedHit = null;
};
const unsubscribe = inputFor(viewer).onClick((event) => {
const nativeHit = capturedHit;
capturedHit = null;
// Ambient selection yields to draw tools and Director (the dispatcher
// skips a held pointer); it never claims the pointer, camera, or
// tracking state.
const position = event.screenPosition;
if (!enabled || destroyed || selectionOwner !== owner || !position)
return;
// AIS cards paint above the globe on a pointer-events:none canvas. The
// vessel handler resolves this same topmost hit before cyclone geometry.
const captureMatches =
nativeHit &&
Math.abs(nativeHit.x - position.x) < 1 &&
Math.abs(nativeHit.y - position.y) < 1;
const hit = captureMatches
? nativeHit
: overlayHit(position.x, position.y);
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
// The card or label painted on top, as it was when the click landed.
const card = clickCard(event);
// Storm cards and lead-hour labels paint on the same canvas; a click on
// one selects its storm. An id from a superseded advisory changes nothing.
if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(hit.entryId);
if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(card.entryId);
if (id) layer.setParams({ stormId: id });
return;
}
// Another layer's card on top takes the click: the storm under it does
// not act, and the click is not empty map either.
if (card) return;
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
// clears the selection.
const id = rendering?.pickStorm(event.drawHit);
@@ -249,8 +199,6 @@ export function createCyclonesLayer({
function removeSelection() {
const owner = selectionOwner;
selectionOwner = null;
removeClickCapture?.();
removeClickCapture = null;
owner?.unsubscribe?.();
}
const layer = {
+19 -45
View File
@@ -6,7 +6,10 @@ import {
releasePointer,
isPointerFree,
} from '../../data/inputOwnership.js';
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
import {
isOwnedByOtherLayer,
setClickCardHitTest,
} from '../../data/pickRegistry.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
@@ -77,7 +80,7 @@ const deferred = () => {
return { promise, resolve };
};
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
const handlers = [],
// A pick of an item in one of the layer's draw sets, and one of another
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
@@ -109,11 +112,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
createRendering: () => rendering,
hitTestOverlay: () => {
overlayTests++;
return overlayHit;
},
});
setClickCardHitTest(() => {
overlayTests++;
return overlayHit;
});
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = {
@@ -180,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
'foreground AIS card wins before scene picking',
);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// A native capture runs before an earlier sibling handler clears hit rects.
const up = new Event('pointerup');
Object.assign(up, { clientX: 110, clientY: 220 });
canvas.dispatchEvent(up);
overlayHit = null;
// Any other layer's card on top takes the click, not only a vessel's.
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
handlers[0].click(click);
assert.equal(
layer.getDiagnostics().selectedId,
'ep152026',
'captured AIS hit survives synchronous sibling overlay rebuild',
'a camera card over the storm keeps the click',
);
// A captured background hit remains background even if a sibling adds a card.
canvas.dispatchEvent(up);
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
// A new gesture clears an unconsumed release snapshot.
canvas.dispatchEvent(up);
canvas.dispatchEvent(new Event('pointerdown'));
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click({ position: { x: 15, y: 25 } });
assert.equal(
layer.getDiagnostics().selectedId,
'ep162026',
'a different click cannot reuse the captured card',
);
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
const before = notices;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
@@ -264,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
assert.equal(layer.getDiagnostics().selectionActive, false);
const afterDisable = picks;
const afterDisableOverlay = overlayTests;
canvas.dispatchEvent(up);
handlers[0].click(click);
assert.equal(
overlayTests,
afterDisableOverlay,
'disable removes native capture listeners',
'a disabled layer reads no card',
);
handlers[0].click(click);
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
layer.enable();
await layer.update();
@@ -289,7 +266,7 @@ test('map selection yields to pointer owners and owns only its enabled handler',
);
assert.equal(handlers[1].destroyed, true);
});
test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
const handlers = [];
let picks = 0,
overlayHit = null,
@@ -309,8 +286,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
getDiagnostics: () => ({}),
};
},
hitTestOverlay: () => overlayHit,
});
setClickCardHitTest(() => overlayHit);
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
const viewer = {
@@ -343,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// The native release snapshot carries the card identity too.
const up = new Event('pointerup');
Object.assign(up, { clientX: 10, clientY: 20 });
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
assert.equal(picks, 0, 'card clicks never fall through to the scene');
overlayHit = null;
handlers[0].click(click);
assert.equal(picks, 1);
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
+3
View File
@@ -1584,6 +1584,9 @@ export function createDirectionsLayer({ services, source }) {
// yields the moment a tool (this one included) owns the click.
const offSelect = input.onClick((event) => {
if (!_enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (services.picking?.isUnderOtherCard?.(event)) return;
let hit = null;
try {
hit = event.drawHit;
+5 -6
View File
@@ -130,12 +130,11 @@ export function createDroneAirspaceLayer({
// cards inert anywhere over a zone. Unowned, our picks read as
// "empty space" to siblings — the same contract as fire perimeters.
_clickSubscription = inputFor(_viewer).onClick((event) => {
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: DRONE_AIRSPACE_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) return;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: this area's shapes are background to
// another layer's card or label painted over them, and a click on our
// own card leaves the selection as it is.
if (picking.clickCard?.(event)) return;
const picked = event.topHit;
const zoneId = picked ? pickedZoneId(event.drawHit) : null;
if (zoneId) {
+92 -3
View File
@@ -2,7 +2,8 @@ import assert from 'node:assert/strict';
import test from 'node:test';
import { createDroneAirspaceLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { clickCard } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
// The fills set of the layer the last harness made: zone picks name it.
@@ -19,11 +20,12 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
const owners = new Map();
const viewer = { scene: { pick } };
const { draw } = bindFakeDraw(viewer);
const input = fakeInput(viewer);
const input = fakeInputUnderLabel(viewer);
const clicks = {
handler: (click) => input.click(click.position),
// Only the label's own overlay handler is left.
get destroyed() {
return input.input.subscriberCount() === 0 ? 1 : 0;
return input.input.subscriberCount() === 1 ? 1 : 0;
},
};
const layer = createDroneAirspaceLayer({
@@ -47,6 +49,11 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
String(pickedId).startsWith('other-layer:'),
registerPickOwner: (layerId, predicate) => owners.set(layerId, predicate),
unregisterPickOwner: (layerId) => owners.delete(layerId),
// The card on top at a click, as the registry answers from the host.
// A mission label painted over everything comes first.
clickCard: (click) =>
clickCard(click) ??
cardHit(click.screenPosition?.x, click.screenPosition?.y, {}),
},
});
layer.init(viewer);
@@ -61,6 +68,8 @@ function harness(source, { pick = () => null, cardHit = () => null } = {}) {
overlay,
clicks,
owners,
/** A label painted over the map: while `over`, it takes each click. */
label: input.label,
};
}
@@ -143,6 +152,86 @@ test('clicking a zone publishes its card; empty space clears it', async () => {
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
});
test('a click on a mission label over the open zone card keeps it open and takes no zone beneath', async () => {
let pickResult = null;
let cardHitResult = null;
const h = harness(
{ getSnapshot: async () => [row] },
{ pick: () => pickResult, cardHit: () => cardHitResult },
);
await h.layer.update(h.viewer);
pickResult = zonePick('drone-airspace:310:0');
h.clicks.handler({ position: { x: 10, y: 10 } });
const [card] = h.overlay.entries.get('drone-airspace');
// The open card and its zone lie under the label: the label on top is
// its own click, so the card stays open.
cardHitResult = { sourceId: 'drone-airspace', entryId: card.id };
h.label.over = true;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.[0]?.id, card.id);
pickResult = null;
cardHitResult = null;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(
h.overlay.entries.get('drone-airspace')?.[0]?.id,
card.id,
'a label over bare map is not empty space either',
);
// Off the label, the same click on bare map closes the card.
h.label.over = false;
h.clicks.handler({ position: { x: 12, y: 12 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
h.layer.destroy();
});
// Another layer's card or label painted over the area (a quake's card or
// magnitude label) is that layer's click: the area under it stands aside.
test("another layer's overlay on top keeps a click off the area", async () => {
let pickResult = null;
let foreignOnTop = false;
const h = harness(
{ getSnapshot: async () => [row] },
{
pick: () => pickResult,
// Unfiltered: the topmost entry of any source.
// As the host does: drone-airspace cards are not interactive, so only
// another layer's card painted on top is ever hit.
cardHit: (_x, _y, options) =>
foreignOnTop && !options?.sourceId
? { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' }
: null,
},
);
await h.layer.update(h.viewer);
pickResult = zonePick('drone-airspace:310:0');
foreignOnTop = true;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(h.overlay.entries.get('drone-airspace')?.length ?? 0, 0);
// With nothing painted over it, the same click selects the area.
foreignOnTop = false;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
);
// An overlay on top covers the selected area's card.
foreignOnTop = true;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
);
pickResult = null;
h.clicks.handler({ position: { x: 10, y: 10 } });
assert.equal(
h.overlay.entries.get('drone-airspace')[0].id,
'drone-airspace-card:310',
'the foreground overlay preserves selection over bare map too',
);
});
test('late refresh cannot publish after disable or destroy', async () => {
for (const action of ['disable', 'destroy']) {
let resolve, signal;
+416 -30
View File
@@ -1,6 +1,10 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
isTrackingClickGesture,
isTrackingSelectionGesture,
} from '../../data/trackingClickGesture.js';
import {
EARTHQUAKE_OVERLAY_SOURCE_ID,
EARTHQUAKE_OVERLAY_COHORT_LIMIT,
@@ -11,6 +15,11 @@ import {
selectEarthquakeOverlayCohort,
mapAnalystRecord,
earthquakeCoverage,
earthquakeMarkLabel,
earthquakeMagnitudeTitle,
earthquakeZoomLabel,
earthquakeDiscRadiusM,
describeEarthquake,
} from './model.js';
export * from './model.js';
export { createUsgsEarthquakeSource } from './source.js';
@@ -25,6 +34,20 @@ const msg = (text) => text;
* as `Hit.set`.
*/
export const EARTHQUAKE_DISC_SET_ID = 'earthquakes';
export const EARTHQUAKES_LAYER_ID = 'earthquakes';
/** The overlay source the clicked quake's detail card is shown in. */
export const EARTHQUAKE_CARD_SOURCE_ID = 'earthquake-card';
/** A disc's item id is this prefix and the event's stable id. */
const PICK_PREFIX = 'earthquake:';
/** Fly-to range per metre of disc radius: 220 km frames an M6 (64 km). */
const EARTHQUAKE_FOCUS_RANGE_PER_RADIUS = 3.5;
/** The selected quake's flat fill, faint under the painted gradient. */
const SELECTED_DISC_ALPHA = 0.04;
const CARD_HOST_OPTIONS = Object.freeze({
cohortLimit: 1,
collisionCapacity: 1,
moving: false,
});
let instances = 0;
/**
@@ -33,8 +56,48 @@ let instances = 0;
* The discs are one renderer draw set (`drawOf(viewer)`), made at `init`.
* Given a Cesium viewer with no renderer bound, the
* caller loads the package's `./render/cesium/unbound` export first.
*
* Clicking a disc shows that quake's detail card and selects it in the
* shared context. The application gives the click and selection services;
* without `input` and `picking` the discs are drawn but take no clicks.
* @param {object} options
* @param {object} options.source Snapshot source.
* @param {object} options.overlayHost World-overlay host.
* @param {(viewer: object) => {onClick: Function}} [options.input] The
* viewer's click dispatcher.
* @param {{resolvePickId: Function, isOwnedByOtherLayer: Function,
* clickCard?: Function}} [options.picking] The pick
* registry; `clickCard` names the card or label painted on top of a
* click, which takes it (the quake card and labels need it to act).
* @param {{registerEntityContext: Function, selectEntityContext: Function,
* clearSelectedEntityContextForLayer: Function,
* getContextStore: Function}} [options.context] Shared selection store.
* @param {{isPointerFree: () => boolean}} [options.pointer]
* @param {(url: string) => void} [options.openExternal]
* @param {{requestWorldFocus: (detail: object) => boolean}} [options.focus]
* The camera transfer a clicked magnitude label asks for.
* @param {{show: (target: {id: string, lon: number, lat: number,
* heightM?: number, heightAt?: () => number|null, radiusM: number,
* color: string}) => void, hide: () => void}} [options.ripples]
* The selected quake's animated contour rings.
* @param {(viewer: object, lon: number, lat: number) => number|null} [options.groundHeight]
* The loaded ground height under a point, so the rings sit on the disc
* that is draped there; null (or no service) draws them at sea level.
* @param {object} [options.text] Card formatters (see describeEarthquake).
*/
export function createEarthquakesLayer({ source, overlayHost } = {}) {
export function createEarthquakesLayer({
source,
overlayHost,
input = null,
picking = null,
context = null,
pointer = null,
openExternal = null,
focus = null,
ripples = null,
groundHeight = null,
text = undefined,
} = {}) {
if (typeof source?.getSnapshot !== 'function')
throw new TypeError('Earthquakes require a snapshot source');
if (!overlayHost) throw new TypeError('Earthquakes require an overlay host');
@@ -60,6 +123,307 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_marksKey = key;
worldClock.coverageChanged();
};
// The drawn events by stable id, for clicks; the selected one's id, card
// and the context record it was published as.
let _eventById = new Map();
let _selectedId = null;
let _selectedCardId = null;
let _selectedLink = null;
let _contextId = null;
let _clickHandler = null;
const canSelect = () => Boolean(input && picking);
// The disc whose flat fill is faded while the painter draws its gradient.
let _fadedDiscId = null;
/**
* A quake's disc: filled on the ground, with static axes (re-tessellating
* clamped ground geometry every frame is what once cost 30 fps). No
* outline: clamped to the ground, Cesium never drew one. A selected
* quake's disc is all but clear: the ripples painter fills it with a
* gradient instead, and the faint fill keeps it pickable.
*/
function discItem(event, faded = false) {
const radius = earthquakeDiscRadiusM(event.mag);
const [r, g, b] = depthColor(event.depthKm || 0);
const fillAlpha = faded
? SELECTED_DISC_ALPHA
: event.mag >= 5.0
? 0.4
: 0.3;
return {
id: `${PICK_PREFIX}${event.stableId}`,
geometry: {
kind: 'ellipse',
center: { lon: event.lon, lat: event.lat },
semiMajor: radius,
semiMinor: radius,
},
fill: [r, g, b, fillAlpha],
height: 'clampGround',
clampTo: 'both',
};
}
/** Fade one disc's flat fill (and restore the one faded before). */
function fadeDisc(stableId) {
if (!ripples || !_discs || _fadedDiscId === stableId) return;
const changed = [];
const before = _eventById.get(_fadedDiscId);
if (before) changed.push(discItem(before, false));
const next = _eventById.get(stableId);
if (next) changed.push(discItem(next, true));
_fadedDiscId = next ? stableId : null;
if (changed.length) _discs.upsert(changed);
}
/** The drawn event a pick id names, or null. */
function eventOfPickId(pickId) {
if (typeof pickId !== 'string' || !pickId.startsWith(PICK_PREFIX))
return null;
return _eventById.get(pickId.slice(PICK_PREFIX.length)) ?? null;
}
/** The drawn event a click's draw hit is on: an item of this layer's set. */
function pickedEvent(hit) {
if (!hit || hit.surface || !_discs || hit.set !== _discs.id) return null;
return eventOfPickId(hit.id);
}
/**
* Show the selected quake's card, context and contours. `user`: a click or
* a label's activation, which claims the shared selection and runs the
* contours again; a feed refresh only brings them up to date, so it never
* takes back a selection made since, nor restarts the animation.
*/
function publishCard({ user = false } = {}) {
const event = _selectedId ? _eventById.get(_selectedId) : null;
if (!_enabled || !event) {
// A refresh that no longer carries the selected quake evicts it, as
// other feeds report; anything else is a deliberate clear.
clearSelection({ evicted: _enabled && Boolean(_selectedId) && !user });
return;
}
const { title, details, link, accessibilityLabel } = describeEarthquake(
event,
{ ...text, canOpen: Boolean(openExternal) },
);
_selectedLink = link && openExternal ? link : null;
const card = {
id: `earthquake-card:${event.stableId}`,
selected: true,
// Always hit-testable (the host only hit-tests interactive entries),
// so a click on a card with no link keeps it rather than falling
// through to the ground under it and clearing the selection.
interactive: true,
title,
details,
accent: depthAccent(event.depthKm || 0),
priority: Number.MAX_SAFE_INTEGER,
gapPx: 15,
verticalOnly: true,
placement: 'above',
stateless: true,
horizonCull: true,
position: fromDegrees(event.lon, event.lat),
};
if (_selectedLink) {
const target = _selectedLink;
card.accessibilityLabel = accessibilityLabel;
card.activate = () => {
openExternal(target);
return true;
};
} else if (focus?.requestWorldFocus) {
// No source to open: the card's keyboard action flies to its quake,
// as a fire card's focuses its fire, so it stays in the action list.
const stableId = event.stableId;
card.accessibilityLabel = accessibilityLabel;
card.activate = () => selectAndFocus(stableId);
}
_selectedCardId = card.id;
overlayHost.setEntries(
EARTHQUAKE_CARD_SOURCE_ID,
[card],
CARD_HOST_OPTIONS,
);
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, true);
publishContext(event, user);
fadeDisc(event.stableId);
let heightM = null;
try {
heightM = groundHeight?.(_viewer, event.lon, event.lat) ?? null;
} catch {
heightM = null;
}
ripples?.show?.(
{
id: event.stableId,
lon: event.lon,
lat: event.lat,
heightM: Number.isFinite(heightM) ? heightM : 0,
// Read again as the ground loads: a label's fly-to starts far away.
heightAt: groundHeight
? () => groundHeight(_viewer, event.lon, event.lat)
: null,
radiusM: earthquakeDiscRadiusM(event.mag),
color: depthAccent(event.depthKm || 0),
},
{ restart: user },
);
}
/**
* Select the event in the shared context store, so "what's selected"
* (voice, the Cockpit) answers with it, as a clicked fire does.
*/
function publishContext(event, select) {
if (!context) return;
const id = `${PICK_PREFIX}${event.stableId}`;
try {
if (_contextId && _contextId !== id)
context.getContextStore().entities.delete(_contextId);
const carrier = { show: true };
context.registerEntityContext(carrier, {
id,
layerId: EARTHQUAKES_LAYER_ID,
layerName: layer.name,
source: 'USGS',
// Hidden with the layer: the context store reads its `show`.
dataSource: _discs,
targetPosition: fromDegrees(event.lon, event.lat),
// i18n-ignore: English entity label, as the analyst records are
label: `Earthquake · ${earthquakeMarkLabel(event)}`,
latitude: event.lat,
longitude: event.lon,
properties: {
magnitude: event.mag,
depthKm: event.depthKm ?? null,
place: event.place ?? null,
time: Number.isFinite(event.time)
? new Date(event.time).toISOString()
: null,
usgsId: event.usgsId ?? null,
},
});
_contextId = id;
if (select) context.selectEntityContext(carrier);
} catch {
// No context store (no window): the card still shows.
}
}
function clearContext({ evicted = false } = {}) {
if (!context || !_contextId) return;
try {
context.clearSelectedEntityContextForLayer(EARTHQUAKES_LAYER_ID, {
evicted,
});
context.getContextStore().entities.delete(_contextId);
} catch {
// store unavailable: nothing to clean
}
_contextId = null;
}
function clearSelection({ evicted = false } = {}) {
const had = _selectedId || _selectedCardId;
_selectedId = null;
_selectedCardId = null;
_selectedLink = null;
clearContext({ evicted });
ripples?.hide?.();
fadeDisc(null);
if (had)
overlayHost.setEntries(EARTHQUAKE_CARD_SOURCE_ID, [], CARD_HOST_OPTIONS);
}
function installClickHandler() {
if (!canSelect() || _clickHandler || !_viewer) return;
// Deliberately NOT registered in the pick-ownership registry, like drone
// airspace and fire perimeters: siblings yield to owned picks before
// their own card hit-tests and treat an owned pick as not empty space,
// so claiming these large discs would make their cards inert and their
// selections stick anywhere over a quake. Unowned, a disc reads as
// empty space to them; this handler finds its own discs by draw set.
// A viewer with no renderer input bound takes no clicks.
let clicks = null;
try {
clicks = input(_viewer) ?? null;
} catch {
clicks = null;
}
if (!clicks) return;
_clickHandler = clicks.onClick((click) => {
if (!_enabled || (pointer && !pointer.isPointerFree())) return;
// A pan that ends near where it began still raises a click. As for the
// tracking layers and Context, a press that travelled is a drag, not a
// pick; opening the source and clearing also need a short press.
if (!isTrackingSelectionGesture(click.gesture)) return;
const clean = isTrackingClickGesture(click.gesture);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: another layer's is that layer's click
// (the disc under it is background), and ours acts whatever is drawn
// under it.
const top = picking.clickCard?.(click) ?? null;
if (top?.sourceId === EARTHQUAKE_CARD_SOURCE_ID) {
// The card's action, as its keyboard action: open the source, or
// with none, fly to the quake.
if (top.entryId !== _selectedCardId) return;
if (_selectedLink) {
if (clean) openExternal(_selectedLink);
} else if (focus?.requestWorldFocus && _selectedId)
selectAndFocus(_selectedId);
return;
}
// A magnitude label is what a far view (the whole globe) can click:
// it selects the quake and flies to it.
if (top?.sourceId === EARTHQUAKE_OVERLAY_SOURCE_ID) {
if (_eventById.has(top.entryId)) selectAndFocus(top.entryId);
return;
}
if (top) return;
// Another layer's pick (an aircraft, a camera, a flight trail) is not
// empty space and not this layer's: leave the selection alone.
const hit = click.hit;
const pickId = picking.resolvePickId(hit);
if (pickId && picking.isOwnedByOtherLayer(EARTHQUAKES_LAYER_ID, pickId))
return;
const event = pickedEvent(hit);
if (event) {
_selectedId = event.stableId;
publishCard({ user: true });
return;
}
if (clean) clearSelection();
});
}
/** Select a drawn quake, show its card, and ask the camera to go there. */
function selectAndFocus(stableId) {
const event = _eventById.get(stableId);
if (!_enabled || !event) return false;
_selectedId = stableId;
publishCard({ user: true });
focus?.requestWorldFocus?.({
kind: 'earthquake',
id: `${PICK_PREFIX}${stableId}`,
label: earthquakeMagnitudeTitle(event.mag),
position: fromDegrees(event.lon, event.lat),
// The whole disc in view: the framing's range fits an M6 disc, so only
// a larger one asks for its own range (the framing stays the floor).
radiusM: earthquakeDiscRadiusM(event.mag),
rangeM:
event.mag > 6
? earthquakeDiscRadiusM(event.mag) * EARTHQUAKE_FOCUS_RANGE_PER_RADIUS
: undefined,
});
return true;
}
function removeClickHandler() {
_clickHandler?.();
_clickHandler = null;
}
const layer = {
id: 'earthquakes',
@@ -93,6 +457,7 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
// layer has no per-frame animator to keep the render loop alive for.
if (_discs) _discs.show = true;
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, true);
installClickHandler();
coverageChanged();
},
@@ -101,6 +466,10 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
_request = null;
_enabled = false;
if (_discs) _discs.show = false;
removeClickHandler();
clearSelection();
overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
coverageChanged();
@@ -132,41 +501,52 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
time,
} of rows) {
count++;
const baseRadius = Math.pow(2, mag) * 1000;
const color = depthColor(depthKm || 0);
const [r, g, b] = color;
const isSignificant = mag >= 5.0;
const fillAlpha = isSignificant ? 0.4 : 0.3;
const position = fromDegrees(lon, lat);
nextEvents.push({ usgsId, mag, place, time, depthKm, lon, lat });
// A filled disc on the ground, with static axes: re-tessellating
// clamped ground geometry every frame is what once cost 30 fps.
// No outline: clamped to the ground, Cesium never drew one.
nextDiscs.push({
id: `earthquake:${stableId}`,
geometry: {
kind: 'ellipse',
center: { lon, lat },
semiMajor: baseRadius,
semiMinor: baseRadius,
},
fill: [r, g, b, fillAlpha],
height: 'clampGround',
clampTo: 'both',
});
overlayEntries.push(
createEarthquakeOverlayEntry({
id: String(stableId),
position,
magnitude: mag,
accent: depthAccent(depthKm || 0),
}),
const event = {
stableId: String(stableId),
usgsId,
mag,
place,
time,
depthKm,
lon,
lat,
};
nextEvents.push(event);
nextDiscs.push(
discItem(event, Boolean(ripples) && event.stableId === _selectedId),
);
const label = createEarthquakeOverlayEntry({
id: String(stableId),
position,
magnitude: mag,
accent: depthAccent(depthKm || 0),
});
if (canSelect()) {
const id = String(stableId);
label.interactive = true;
label.accessibilityLabel = earthquakeZoomLabel(
{ mag, place },
text,
);
label.activate = () => selectAndFocus(id);
}
overlayEntries.push(label);
}
// Bigger quakes first, so a small quake inside a big one's disc is
// drawn, and picked, on top of it.
nextDiscs.sort((a, b) => b.geometry.semiMajor - a.geometry.semiMajor);
_discs.set(nextDiscs);
_events = nextEvents;
_eventById = new Map(
nextEvents.map((event) => [event.stableId, event]),
);
_fadedDiscId =
ripples && _eventById.has(_selectedId) ? _selectedId : null;
// A selected quake still in the feed keeps its card, refreshed; one
// that left the 24 h window loses it.
if (_selectedId) publishCard();
coverageChanged();
if (_enabled) {
overlayHost.setEntries(
@@ -199,13 +579,19 @@ export function createEarthquakesLayer({ source, overlayHost } = {}) {
destroy(viewer = _viewer) {
_request?.abort();
_request = null;
removeClickHandler();
clearSelection();
ripples?.dispose?.();
_viewer = null;
_enabled = false;
overlayHost.clearSource(EARTHQUAKE_CARD_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_CARD_SOURCE_ID, false);
overlayHost.clearSource(EARTHQUAKE_OVERLAY_SOURCE_ID);
overlayHost.setVisible(EARTHQUAKE_OVERLAY_SOURCE_ID, false);
_discs?.dispose();
_discs = null;
_events = [];
_eventById = new Map();
_uncover?.();
_uncover = null;
_marksKey = null;
+332
View File
@@ -23,6 +23,12 @@ export const EARTHQUAKE_MARK_MAGNITUDE = 6;
/** The longest place a timeline mark's label carries, ellipsis and all. */
const MARK_PLACE_LENGTH = 40;
/**
* The longest place line the detail card shows, ellipsis and all, so a long
* place or translation keeps the card inside a phone's width. The card's
* accessible name carries the whole place.
*/
const CARD_PLACE_LENGTH = 48;
/** A magnitude as the map's labels show it: `M6.4`. */
export const earthquakeMagnitudeTitle = (magnitude) =>
@@ -123,6 +129,332 @@ export function createEarthquakeOverlayEntry({
};
}
/** Where USGS publishes one event's page, its event id appended. */
export const USGS_EVENT_PAGE_URL =
'https://earthquake.usgs.gov/earthquakes/eventpage/';
/**
* The USGS page for an event id, or null when there is no usable id (a
* fallback `event-N` id never names a USGS page, and is never sent).
* @param {unknown} usgsId
* @returns {string|null}
*/
export function earthquakeEventLink(usgsId) {
const id =
typeof usgsId === 'string' || typeof usgsId === 'number'
? String(usgsId).trim()
: '';
return /^[A-Za-z0-9_-]{1,64}$/.test(id)
? `${USGS_EVENT_PAGE_URL}${id}`
: null;
}
// The package carries no i18n: with no translator given, the card stays
// English, its `{name}` slots filled in.
const english = (text, values) =>
String(text).replace(/\{(\w+)\}/g, (all, key) =>
values && Object.hasOwn(values, key) ? String(values[key]) : all,
);
const utcMinute = (time) =>
`${new Date(time).toISOString().slice(0, 16).replace('T', ' ')} UTC`;
const oneDecimal = (value) => String(Math.round(value * 10) / 10);
/**
* The detail card one clicked earthquake shows: its magnitude as the title,
* then where, when and how deep, and the source. With a USGS event id the
* card opens that event's page.
* @param {{mag: number, place?: string|null, time?: number|null,
* depthKm?: number|null, usgsId?: string|null}} event
* @param {object} [text] The application's formatters.
* @param {(text: string, values?: object) => string} [text.t] Translator.
* @param {(time: number) => string} [text.formatTime] An event time.
* @param {(value: number) => string} [text.formatDepth] A depth in km.
* @param {boolean} [text.canOpen] Whether a link can be opened here (an
* opener is injected); without one the card offers no link to click.
* @returns {{title: string, details: string[], link: string|null,
* accessibilityLabel: string}} `accessibilityLabel` names the card's
* action, with its details: opening the source, or focusing the quake.
*/
export function describeEarthquake(
event,
{
t = english,
formatTime = utcMinute,
formatDepth = oneDecimal,
canOpen = true,
} = {},
) {
const details = [];
// What the card says, spoken: depth, the whole place, and the time.
const spoken = [];
// Severity at a glance, right under the title: the class meter, then
// where in the crust it broke.
const glance = [earthquakeSeverityMeter(event?.mag)];
if (Number.isFinite(event?.depthKm)) {
const depth = `${earthquakeDepthBandName(event.depthKm, t)} · ${t(
'{km} km deep',
{ km: formatDepth(event.depthKm) },
)}`;
glance.push(depth);
spoken.push(depth);
}
details.push(glance.join(' '));
const place =
typeof event?.place === 'string'
? event.place.replace(/\s+/g, ' ').trim()
: '';
if (place) {
// Cut by characters, not UTF-16 units, so a pair is never split.
const chars = Array.from(place);
details.push(
chars.length > CARD_PLACE_LENGTH
? `${chars
.slice(0, CARD_PLACE_LENGTH - 1)
.join('')
.trimEnd()}…`
: place,
);
spoken.push(place);
}
if (Number.isFinite(event?.time)) {
const time = formatTime(event.time);
details.push(time);
spoken.push(time);
}
const source = t('Source: {value}', { value: 'USGS' });
details.push(source);
// The source closes the spoken details, so they are never empty.
spoken.push(source);
const link = earthquakeEventLink(event?.usgsId);
const opens = Boolean(link) && canOpen;
if (opens) details.push(t('Click the card to open the source ↗'));
const title = `${earthquakeMagnitudeTitle(event?.mag)} · ${earthquakeSeverityName(
event?.mag,
t,
)}`;
const summary = { title, details: spoken.join(', ') };
return {
title,
details,
link,
accessibilityLabel: opens
? t('Open the source for {title}, {details}', summary)
: t('Focus earthquake {title}, {details}', summary),
};
}
/**
* USGS's magnitude classes, weakest first: minor (under 4; the feed starts
* at M2.5), light, moderate, strong, major, great (8 and up).
*/
export const EARTHQUAKE_SEVERITY_LEVELS = 6;
/**
* A magnitude's USGS class, 0 (minor) to 5 (great).
* @param {number} magnitude
* @returns {number}
*/
export function earthquakeSeverityLevel(magnitude) {
const mag = Number(magnitude);
if (!Number.isFinite(mag) || mag < 4) return 0;
return Math.min(EARTHQUAKE_SEVERITY_LEVELS - 1, Math.floor(mag) - 3);
}
/** A magnitude's class, as a word in the page's language. */
export function earthquakeSeverityName(magnitude, t = english) {
switch (earthquakeSeverityLevel(magnitude)) {
case 5:
return t('Great', { context: 'earthquake' });
case 4:
return t('Major', { context: 'earthquake' });
case 3:
return t('Strong', { context: 'earthquake' });
case 2:
return t('Moderate', { context: 'earthquake' });
case 1:
return t('Light', { context: 'earthquake' });
default:
return t('Minor', { context: 'earthquake' });
}
}
/**
* The class as a six-step meter, one filled block per class up to this one:
* `■■□□□□` for a light quake. Plain text, so the card shows it as it is.
* @param {number} magnitude
* @returns {string}
*/
export function earthquakeSeverityMeter(magnitude) {
const filled = earthquakeSeverityLevel(magnitude) + 1;
return '■'.repeat(filled) + '□'.repeat(EARTHQUAKE_SEVERITY_LEVELS - filled);
}
/**
* The depth band the disc's colour shows, as a word: shallow (under 70 km,
* red), intermediate (to 300 km, orange), deep (yellow).
*/
export function earthquakeDepthBandName(depthKm, t = english) {
const band = depthBand(depthKm);
if (band === SHALLOW) return t('Shallow', { context: 'earthquake' });
if (band === INTERMEDIATE)
return t('Intermediate', { context: 'earthquake' });
return t('Deep', { context: 'earthquake' });
}
/**
* A quake's disc radius on the ground, in metres: it doubles with each
* magnitude step (about 5.7 km at M2.5, 32 km at M5, 64 km at M6).
* @param {number} magnitude
* @returns {number}
*/
export const earthquakeDiscRadiusM = (magnitude) =>
Math.pow(2, magnitude) * 1000;
/** How many contour lines run out from a selected quake at once. */
export const EARTHQUAKE_RIPPLE_RINGS = 6;
/** How long one contour line takes from the marker to the disc's edge. */
export const EARTHQUAKE_RIPPLE_PERIOD_MS = 4800;
/** Every this many lines one is an index contour, drawn heavier. */
export const EARTHQUAKE_INDEX_CONTOUR_EVERY = 3;
/**
* How far a contour line dents in from the circle, as a share of its
* radius. Kept with the drift below so nested lines never cross: a line's
* radius grows with `fraction` faster than its dents move (see
* earthquakeContourScale).
*/
export const EARTHQUAKE_CONTOUR_WOBBLE = 0.24;
const CONTOUR_HARMONICS = Object.freeze([2, 3, 5]);
const CONTOUR_WEIGHTS = Object.freeze([1, 0.6, 0.3]);
const CONTOUR_MAX_DRIFT = 1.5;
/** A stable 32-bit hash of a string (FNV-1a). */
function hashString(text) {
let h = 0x811c9dc5;
for (const ch of String(text ?? '')) {
h ^= ch.codePointAt(0);
h = Math.imul(h, 0x01000193);
}
return h >>> 0;
}
/**
* One quake's contour shape: a few harmonics around the circle, each with
* its own phase and a drift that turns it as a line runs outward, seeded by
* the quake's id so the same quake always draws the same contours.
* @param {string} seed The quake's stable id.
* @returns {ReadonlyArray<{harmonic: number, weight: number, phase: number, drift: number}>}
*/
export function earthquakeContourShape(seed) {
let state = hashString(seed) || 1;
// xorshift32: a small, stable stream from the seed.
const next = () => {
state ^= state << 13;
state ^= state >>> 17;
state ^= state << 5;
return (state >>> 0) / 0x100000000;
};
return Object.freeze(
CONTOUR_HARMONICS.map((harmonic, i) =>
Object.freeze({
harmonic,
weight: CONTOUR_WEIGHTS[i],
phase: next() * 2 * Math.PI,
drift: (next() * 2 - 1) * CONTOUR_MAX_DRIFT,
}),
),
);
}
/**
* Where a contour line runs at `angle` (radians), as a share of a circle of
* the same `fraction`: between 1 - EARTHQUAKE_CONTOUR_WOBBLE and 1, so the
* outermost line never leaves the disc. The dents turn as `fraction` grows,
* and no faster than the line grows, so lines never cross: with wobble A
* and drift D, d(fraction · scale)/d(fraction) ≥ 1 - A - A·D/2 > 0.
* @param {ReturnType<typeof earthquakeContourShape>} shape
* @param {number} angle
* @param {number} fraction 0 at the marker, 1 at the disc's edge.
* @returns {number}
*/
export function earthquakeContourScale(shape, angle, fraction) {
let sum = 0;
let total = 0;
for (const { harmonic, weight, phase, drift } of shape) {
sum += weight * Math.sin(harmonic * angle + phase + drift * fraction);
total += weight;
}
const n = total > 0 ? sum / total : 0;
return 1 - (EARTHQUAKE_CONTOUR_WOBBLE * (1 - n)) / 2;
}
/**
* The selected quake's contour lines at a time: each runs from the marker
* (`fraction` 0) out to the disc's edge (1), evenly staggered, fading in
* just after it starts and out as it reaches the edge; every
* EARTHQUAKE_INDEX_CONTOUR_EVERY-th is an index contour. Pure: the painter
* gives the clock.
* @param {number} timeMs Any steady clock, in milliseconds.
* @param {{count?: number, periodMs?: number}} [options]
* @returns {Array<{fraction: number, alpha: number, index: boolean}>}
*/
export function earthquakeRippleRings(
timeMs,
{
count = EARTHQUAKE_RIPPLE_RINGS,
periodMs = EARTHQUAKE_RIPPLE_PERIOD_MS,
} = {},
) {
const phase = Number.isFinite(timeMs) && periodMs > 0 ? timeMs / periodMs : 0;
const rings = [];
for (let k = 0; k < count; k++) {
const fraction = (((phase + k / count) % 1) + 1) % 1;
rings.push({
fraction,
alpha: earthquakeRippleAlpha(fraction),
index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
});
}
return rings;
}
/**
* Still contour lines, for viewers who ask for reduced motion: the same
* lines as the animation, held evenly spaced out to the edge.
* @param {number} [count]
* @returns {Array<{fraction: number, alpha: number, index: boolean}>}
*/
export function earthquakeContourRings(count = EARTHQUAKE_RIPPLE_RINGS) {
const rings = [];
for (let k = 1; k <= count; k++)
rings.push({
fraction: k / count,
alpha: 0.7,
index: k % EARTHQUAKE_INDEX_CONTOUR_EVERY === 0,
});
return rings;
}
const RIPPLE_FADE_IN = 0.12;
/** A ring's opacity where it is: in from 0 near the marker, out to 0 at the edge. */
function earthquakeRippleAlpha(fraction) {
if (fraction <= 0 || fraction >= 1) return 0;
return fraction < RIPPLE_FADE_IN
? fraction / RIPPLE_FADE_IN
: (1 - fraction) / (1 - RIPPLE_FADE_IN);
}
/**
* What a magnitude label says to assistive technology: activating it zooms
* to the quake (`Zoom to M5.0 · 42 km SW of Anchorage, Alaska`).
* @param {{mag: number, place?: string|null}} event
* @param {{t?: (text: string, values?: object) => string}} [text]
* @returns {string}
*/
export function earthquakeZoomLabel(event, { t = english } = {}) {
return t('Zoom to {name}', { name: earthquakeMarkLabel(event) });
}
/** Keep the largest events, with stable identity as the tie-break. */
export function selectEarthquakeOverlayCohort(
entries,
+9 -4
View File
@@ -28,10 +28,15 @@ export function normalizeEarthquakeSnapshot(geojson) {
return null;
// A missing magnitude cannot establish that this event meets M2.5+.
if (mag == null || mag < 2.5) continue;
const stableId =
feature.id == null || feature.id === ''
? `event-${index + 1}`
: String(feature.id);
// An id-less event is named by what it is (time, position, depth and
// magnitude), not by its row, so a refresh that inserts a row keeps the
// selection on the same quake; a revision to any of those names a new
// one. Two id-less events that match exactly fall back to the row.
const idless = feature.id == null || feature.id === '';
let stableId = idless
? `event-${[properties.time ?? 'na', lon, lat, depthKm ?? 'na', mag].join(':')}`
: String(feature.id);
if (idless && ids.has(stableId)) stableId = `${stableId}:${index + 1}`;
if (ids.has(stableId)) return null;
ids.add(stableId);
rows.push({
+28 -3
View File
@@ -37,7 +37,7 @@ test('normalizeEarthquakeSnapshot parses valid GeoJSON earthquake features', ()
});
});
test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is missing or blank', () => {
test('normalizeEarthquakeSnapshot names id-less events by their content, not their row', () => {
const geojson = {
features: [
{
@@ -55,10 +55,35 @@ test('normalizeEarthquakeSnapshot generates index-based stable IDs when id is mi
const rows = normalizeEarthquakeSnapshot(geojson);
assert.equal(rows.length, 2);
assert.equal(rows[0].stableId, 'event-1');
assert.equal(rows[0].stableId, 'event-1711930000000:139.6917:35.6895:25:3.5');
assert.equal(rows[0].usgsId, null);
assert.equal(rows[1].stableId, 'event-2');
assert.equal(
rows[1].stableId,
'event-1711931000000:-70.6693:-33.4489:45.2:5.1',
);
assert.equal(rows[1].usgsId, '');
// A row inserted ahead of them keeps each id-less quake's id, so a selected
// one stays selected across the refresh.
const inserted = normalizeEarthquakeSnapshot({
features: [
{
id: 'us7000new',
geometry: { type: 'Point', coordinates: [10, 20, 5] },
properties: { mag: 4, place: 'New', time: 1711932000000 },
},
...geojson.features,
],
});
assert.deepEqual(
inserted.map((row) => row.stableId).slice(1),
rows.map((row) => row.stableId),
);
// Two id-less events that match exactly stay apart.
const twins = normalizeEarthquakeSnapshot({
features: [geojson.features[0], geojson.features[0]],
});
assert.equal(twins.length, 2);
assert.notEqual(twins[0].stableId, twins[1].stableId);
});
test('normalizeEarthquakeSnapshot filters events below M2.5 without dropping the feed', () => {
File diff suppressed because it is too large. Load diff
+4 -1
View File
@@ -76,7 +76,10 @@ export function createCards({
const height = canvas.clientHeight;
let ambientCount = 0;
for (const candidate of layerState._labelCandidates) {
// An application drawing the detections in place of the markers draws
// them unlabelled: only the selected fire's card shows then.
const candidates = layerState._standIn ? [] : layerState._labelCandidates;
for (const candidate of candidates) {
if (ambientCount >= MAX_AMBIENT_LABELS) break;
if (candidate.fire && candidate.fire === layerState._selectedFire)
continue;
+14
View File
@@ -0,0 +1,14 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { DEFAULT_FIRE_FILTER, filterFires } from './index.js';
test('the fire layer exports the filter its markers use', () => {
const fires = [
{ frp: 2, confidence: 0.3 },
{ frp: 40, confidence: 0.9 },
];
assert.equal(filterFires(fires, DEFAULT_FIRE_FILTER), fires);
assert.deepEqual(filterFires(fires, { minFrp: 10, confidence: 'all' }), [
fires[1],
]);
});
+3
View File
@@ -40,3 +40,6 @@ export { createFirmsSource } from './source.js';
export { createFireAnchors, FIRE_ANCHOR_LIFT_M } from './anchors.js';
export * from '../../data/firmsAdapt.js';
export * from '../../data/firmsLabels.js';
// The layer's own FRP and Confidence filter, for an application drawing the same detections
// another way: what it draws then matches the layer's markers under the same filter.
export { DEFAULT_FIRE_FILTER, filterFires } from '../../data/firmsIntensity.js';
+31 -2
View File
@@ -52,10 +52,12 @@ export function createLifecycle({
if (layerState._cells) layerState._cells.show = true;
// The GPU culls the far side each frame, so retained rows are right
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
if (layerState._icons) layerState._icons.show = !layerState._standIn;
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, true);
// A filter can leave an old raster cached while the current set is empty.
layerState._heatImagery?.setShow(layerState._fires.length > 0);
layerState._heatImagery?.setShow(
layerState._fires.length > 0 && !layerState._standIn,
);
// The camera can have crossed the hand-off while the layer was off.
components.rendering.applyHandoffFade(true);
components.viewport.installLodWatcher();
@@ -68,6 +70,32 @@ export function createLifecycle({
await components.ingestion.loadHeatmap();
},
/**
* Let an application draw the detections in place of the layer's
* markers. While a stand-in is set, the glows, the heatmap and the
* ambient cards are hidden and everything else works as before: a click
* on a fire the stand-in draws (`standIn.hitTest(screenPosition)`, which
* answers a detection record from the same source, or null) selects it
* and moves the camera to it as a click on its marker does, the selected
* fire's card shows, and a click on empty space clears the selection.
* Its optional `focusRangeM(record)` gives how far, in metres, the camera
* stands from a fire it draws when moving to it, for fires drawn larger
* than a marker; without one, or for null, the usual fire framing holds.
* `null` brings the markers back. The selection is kept either way.
* @param {?{hitTest: (screenPosition: {x: number, y: number}) => ?Object, focusRangeM?: (record: Object) => ?number}} standIn
*/
setMarkerStandIn(standIn) {
layerState._standIn =
typeof standIn?.hitTest === 'function' ? standIn : null;
layerState._heatImagery?.setShow(
layerState._enabled &&
layerState._fires.length > 0 &&
!layerState._standIn,
);
components.rendering.applyHandoffFade(true);
components.cards.rebuildAmbientLabels();
},
disable() {
layerState.request?.abort();
layerState.request = null;
@@ -129,6 +157,7 @@ export function createLifecycle({
layerState._currentLodIndex = -1;
layerState._lastViewRect = null;
layerState._selectedFire = null;
layerState._standIn = null;
layerState._labelCandidates = [];
layerState._labelLodDistance = 0;
layerState._pickIndexById.clear();
+6 -3
View File
@@ -122,7 +122,7 @@ export function createRendering({
glowAlpha = alpha;
const set = layerState._icons;
if (!set) return;
set.show = layerState._enabled && heat < 1;
set.show = layerState._enabled && !layerState._standIn && heat < 1;
if (!changed || !drawnGlows.size) return;
const faded = [];
for (const drawn of drawnGlows.values()) {
@@ -273,7 +273,7 @@ export function createRendering({
// The map stack may have changed since the last render.
imagery.rehome();
ensureHeatRaster(now);
imagery.setShow(layerState._enabled);
imagery.setShow(layerState._enabled && !layerState._standIn);
}
/**
@@ -469,7 +469,10 @@ export function createRendering({
// Blended as one translucent pass, as its billboards were.
blend: 'translucent',
horizonCull: true,
show: layerState._enabled && !(layerState._handoffHeat >= 1),
show:
layerState._enabled &&
!layerState._standIn &&
!(layerState._handoffHeat >= 1),
drawOrder: spriteDrawOrder?.('firms') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
+56 -22
View File
@@ -13,7 +13,7 @@ export function createSelection({
config,
feed,
}) {
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, clickCard } = services.picking;
const { requestWorldFocus } = services.focus;
const {
selectEntityContext,
@@ -21,7 +21,7 @@ export function createSelection({
getContextStore,
registerEntityContext,
} = services.context;
const { id, name, overlayHost } = config;
const { id, name } = config;
/**
* Install the LEFT_CLICK handler for fire selection (enable-time only,
@@ -34,30 +34,33 @@ export function createSelection({
if (layerState._clickSubscription || !layerState._viewer) return;
const input = inputFor(layerState._viewer);
layerState._clickSubscription = input.onClick((event) => {
const picked = event.topHit;
const fire = pickedFire(event.drawHit);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours acts whatever is drawn under it;
// another layer's is that layer's click.
const top = clickCard?.(event) ?? null;
if (top) {
if (top.sourceId !== FIRMS_OVERLAY_SOURCE_ID) return;
const carded = layerState._fireByCardId.get(top.entryId);
if (carded) selectAndFocusFire(carded);
return;
}
const pickedId = resolvePickId(event.topHit ?? null);
// A pick that belongs to a sibling layer (an aircraft, a flight trail)
// is not "empty space": leave the selection alone.
const otherLayer = Boolean(pickedId && isOwnedByOtherLayer(id, pickedId));
// The stand-in is asked where markers are picked: the click corrected
// for the sensor style (`event.position`), and only when no sibling
// layer's item is on top, as a marker under that item would not be hit.
const fire = layerState._standIn
? otherLayer
? null
: standInFire(event.position ?? event.screenPosition)
: pickedFire(event.drawHit);
if (fire) {
selectAndFocusFire(fire);
return;
}
// A pick that belongs to a sibling layer (e.g. an aircraft) is not
// "empty space" — leave the selection alone and let that layer handle it.
if (picked) {
const pickedId = resolvePickId(picked);
if (pickedId && isOwnedByOtherLayer(id, pickedId)) return;
}
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{
sourceId: FIRMS_OVERLAY_SOURCE_ID,
},
);
if (cardHit) {
const carded = layerState._fireByCardId.get(cardHit.entryId);
if (carded) selectAndFocusFire(carded);
return;
}
if (otherLayer) return;
clearFireSelection();
});
}
@@ -71,11 +74,15 @@ export function createSelection({
function selectAndFocusFire(fire) {
selectFire(fire);
// A stand-in that draws the fire larger than a marker says how far the
// camera stands from it (`setMarkerStandIn`).
const rangeM = layerState._standIn?.focusRangeM?.(fire);
requestWorldFocus({
kind: 'fire',
id: fireDetectionKey(fire),
label: t('FIRE'),
position: components.model.firePosition(fire),
...(Number.isFinite(rangeM) && rangeM > 0 ? { rangeM } : {}),
});
}
@@ -93,6 +100,32 @@ export function createSelection({
return layerState._pickIndexById.get(hit.id) ?? null;
}
/** The shown detections by their key, for the shown set they were made from. */
let keyed = { fires: null, byKey: null };
/**
* Resolve a click to one of this layer's fire records through the
* application's stand-in for its markers (`setMarkerStandIn`), or null:
* the record its hit test answers, matched by its detection key to a fire
* the layer shows now (so one the filter hides is not selected).
* @param {?{x: number, y: number}} screenPosition - Where the user clicked.
* @returns {?Object} Fire record.
*/
function standInFire(screenPosition) {
if (!screenPosition) return null;
const record = layerState._standIn?.hitTest(screenPosition);
if (!record) return null;
if (keyed.fires !== layerState._fires)
keyed = {
fires: layerState._fires,
byKey: new Map(
layerState._fires.map((fire) => [fireDetectionKey(fire), fire]),
),
};
return keyed.byKey.get(fireDetectionKey(record)) ?? null;
}
/**
* Select a fire: show its detail label and mark it selected in the shared
* context store so voice "what's selected" resolves to it.
@@ -229,6 +262,7 @@ export function createSelection({
removeClickHandler,
selectAndFocusFire,
pickedFire,
standInFire,
selectFire,
clearFireSelection,
refreshContextRegistrations,
+80
View File
@@ -0,0 +1,80 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { clickCard, resolvePickId } from '../../data/pickRegistry.js';
import { fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { createSelection } from './selection.js';
/** The fire selection over a viewer whose clicks a Space Missions label may
* take, with a fire's card under every click. */
function selectionHarness(t) {
const viewer = { scene: { canvas: {}, pick: () => null } };
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({
sourceId: FIRMS_OVERLAY_SOURCE_ID,
entryId: 'firms-card:1',
}),
});
t.after(() => fake.destroy());
const fire = { lat: 1, lon: 2, acqMs: 3, frp: 40, satellite: 'N' };
const focused = [];
const cleared = [];
const layerState = {
_viewer: viewer,
_icons: { id: 'firms:icons' },
_pickIndexById: new Map(),
_fireByCardId: new Map([['firms-card:1', fire]]),
_selectedFire: null,
_contextIds: new Set(),
};
const selection = createSelection({
layerState,
services: {
picking: { resolvePickId, isOwnedByOtherLayer: () => false, clickCard },
focus: { requestWorldFocus: (request) => focused.push(request.kind) },
context: {
selectEntityContext() {},
clearSelectedEntityContextForLayer: (id) => cleared.push(id),
getContextStore() {},
registerEntityContext() {},
},
},
components: {
model: {
firePosition: () => ({ x: 0, y: 0, z: 0 }),
formatFrp: String,
confidenceBucket: String,
},
cards: { rebuildAmbientLabels() {} },
},
config: {
id: 'firms',
name: 'Fires',
},
});
selection.installClickHandler();
t.after(() => selection.removeClickHandler());
return { fake, layerState, fire, focused, cleared };
}
test("a click on a mission label over a fire's card never selects or focuses the fire", (t) => {
const h = selectionHarness(t);
h.fake.label.over = true;
h.fake.click();
assert.equal(h.layerState._selectedFire, null);
assert.deepEqual(h.focused, [], 'the camera is not sent to the fire');
});
test('a click on a mission label keeps the selected fire', (t) => {
const h = selectionHarness(t);
// Off the label, a click on the card selects and focuses its fire.
h.fake.click();
assert.equal(h.layerState._selectedFire, h.fire);
assert.deepEqual(h.focused, ['fire']);
// The label on top is its own click: the fire stays selected.
h.fake.label.over = true;
h.fake.click();
assert.equal(h.layerState._selectedFire, h.fire);
assert.deepEqual(h.cleared, []);
assert.deepEqual(h.focused, ['fire']);
});
+8
View File
@@ -98,6 +98,14 @@ export function createFirmsState({ services, config }) {
layerState._selectedFire = null;
/**
* What an application draws in place of the markers (`setMarkerStandIn`):
* while set, the glows, heatmap and ambient cards are hidden and clicks
* resolve through its `hitTest`.
*/
layerState._standIn = null;
/** Priority-ordered label candidates from the last rebuild (detections or cells). */
layerState._labelCandidates = [];
+55 -1
View File
@@ -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 };
}
+5 -1
View File
@@ -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) {
+14 -4
View File
@@ -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(
+26 -5
View File
@@ -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');
+266
View File
@@ -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);
}
});
+18 -10
View File
@@ -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,
+73 -3
View File
@@ -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));
+118
View File
@@ -4,6 +4,8 @@ import { createCivilFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createEnrichment } from './enrichment.js';
import { createTracking } from './tracking.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { LiveSourceError } from '../../sources/live/contract.js';
function services() {
@@ -608,3 +610,119 @@ test('a route answer for a callsign the plane no longer flies is dropped', async
assert.equal(meta.routeCallsign, 'UAL10');
flightState.lifetime.abort();
});
// The card or label painted on top takes the click: an aircraft under another
// layer's card is not even picked, so it is neither tracked nor released.
test("another layer's card over an aircraft keeps the click", (t) => {
const previousDocument = globalThis.document;
globalThis.document = Object.assign(new EventTarget(), {
body: { classList: { contains: () => false } },
});
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const flightState = createFlightState({ services: services() });
flightState._trackedEntityChangedRemove = () => {};
const tracking = createTracking({
flightState,
services: { ...services(), picking },
parts: {},
layer: {},
});
tracking._installClickHandler(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
picking.setClickCardHitTest(() => top);
t.after(() => {
picking.setClickCardHitTest(null);
flightState._clickSubscription?.();
input.destroy();
flightState.lifetime.abort();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
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();
});
+7 -2
View File
@@ -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,
+39 -38
View File
@@ -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,
});
+4 -3
View File
@@ -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' } = {}) {
+98 -24
View File
@@ -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,10 @@ export class FlightRecords {
geoAltitudeM,
renderAltitudeM,
renderAltitudeInvented,
// The feed estimated this position: it places the aircraft, and stands
// in on the tracked trail only until the next received report.
estimated: observation.estimated === true,
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 +354,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 +389,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 +456,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 +481,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 +537,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);
+193 -8
View File
@@ -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);
});
+10 -13
View File
@@ -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;
}
+43
View File
@@ -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);
});
+39 -10
View File
@@ -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();
@@ -209,6 +217,7 @@ export function createFlightSnapshotRenderer({
{
nullAltitude: meta.renderAltitudeInvented === true,
track: meta.true_track,
estimated: meta.estimated === true,
},
);
} else {
@@ -254,7 +263,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 +303,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 +327,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 +362,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 &&
+12
View File
@@ -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
+13 -6
View File
@@ -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),
};
}
+79 -31
View File
@@ -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,
@@ -86,7 +88,8 @@ export function createTracking({
const { trackedLabelModelFromText, refreshTrackedReadout } = services.readout;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
services.picking;
const flightsLayer = layer;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
@@ -222,11 +225,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)
@@ -332,15 +337,17 @@ export function createTracking({
* @param {{x: number, y: number, z: number}} position - The report's ECEF position.
* @param {number} [epochMs] - The report's time; defaults to the tracked
* aircraft's newest position-history fix, which every caller has just pushed.
* @param {{nullAltitude?: boolean, track?: number}} [options] - `nullAltitude`:
* @param {{nullAltitude?: boolean, track?: number, estimated?: boolean}} [options] - `nullAltitude`:
* the report had no altitude, so its position is not kept and the line
* breaks there; `track`: its reported track, which the line leaves it along.
* breaks there; `track`: its reported track, which the line leaves it along;
* `estimated`: the feed estimated it, so it stands in only until the next
* received report.
*/
function _appendTrailFix(
position,
epochMs,
{ nullAltitude = false, track = undefined } = {},
{ nullAltitude = false, track = undefined, estimated = false } = {},
) {
const history = flightState._positionHistory.get(flightState._trackedIcao);
const timeMs = Number.isFinite(epochMs)
@@ -351,7 +358,7 @@ export function createTracking({
position,
timeMs,
TRAIL_MAX_POINTS,
{ nullAltitude, track },
{ nullAltitude, track, estimated },
);
_refreshTrailDisplay();
}
@@ -390,12 +397,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 +453,7 @@ export function createTracking({
if (
!flightState._trackedIcao ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
_trailWarmingUp()
)
return [];
const head =
@@ -435,7 +476,7 @@ export function createTracking({
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
_trailDisplayMs(),
),
head,
parts.motion._trackedModelCenterWorld(),
@@ -697,10 +738,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 +855,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 +958,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 +1121,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 +1135,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,
@@ -1272,6 +1317,9 @@ export function createTracking({
// first-person reference. A globe click must not fall through to the
// normal empty-space deselection path; cockpit has explicit exit controls.
if (document.body.classList.contains('cockpit-mode')) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
+144 -2
View File
@@ -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);
});
+11 -2
View File
@@ -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();
+13 -7
View File
@@ -707,13 +707,19 @@ export function createGhostMapsLayer({
typeof pickedId === 'string' && pickedId.startsWith(PICK_PREFIX),
);
_clickSubscription = inputFor(_viewer).onClick((event) => {
const cardHit = overlayHost.hitTest?.(
event.screenPosition?.x,
event.screenPosition?.y,
{ sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID },
);
if (cardHit && cardHit.entryId === _selectedCardId) {
if (_selectedLink && openExternal) openExternal(_selectedLink);
// The card or label painted on top takes the click, read once per
// click so every layer agrees: ours opens its source whatever is drawn
// under it; another layer's is that layer's click, so the maps under
// it do not act and the selection stays.
const cardHit = picking.clickCard?.(event) ?? null;
if (cardHit) {
if (
cardHit.sourceId === GHOSTMAPS_OVERLAY_SOURCE_ID &&
cardHit.entryId === _selectedCardId &&
_selectedLink &&
openExternal
)
openExternal(_selectedLink);
return;
}
const picked = event.topHit;
+110 -1
View File
@@ -1,8 +1,11 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
import { createGhostMapsLayer } from './index.js';
import { createGhostMapsLayer, GHOSTMAPS_OVERLAY_SOURCE_ID } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { inputFor } from '../../input/dispatcher.js';
import { MISSION_LABEL } from '../../input/testDoubles.mjs';
import { clickCard, setClickCardHitTest } from '../../data/pickRegistry.js';
import { GHOSTMAPS_PRODUCTS, GHOSTMAPS_LATEST_DROP } from './catalog.js';
function element(localName, children = [], value = '', attributes = {}) {
@@ -672,3 +675,109 @@ test('narrowing to a window the loaded data covers clears a failed wider reload'
assert.equal(layer.getStats().error, null);
assert.equal(layer.getStats().count, 1);
});
test("a click on a mission label over the open card never opens the card's link, and keeps the card open", async (t) => {
const cards = [];
const opened = [];
let cardUnder = null;
// A Space Missions label painted over the map: while it is over, it takes
// each click and is the card on top; under it may lie our open card.
let labelOver = false;
setClickCardHitTest(() =>
labelOver
? MISSION_LABEL
: cardUnder
? { sourceId: GHOSTMAPS_OVERLAY_SOURCE_ID, entryId: cardUnder }
: null,
);
t.after(() => setClickCardHitTest(null));
const { layer, viewer, click } = fixture(t, {
now: () => Date.UTC(2026, 10, 3, 12),
reports: [
{
name: 'Linked',
description:
'<table><tr><td>Date</td><td>11/2/2026</td></tr>' +
'<tr><td>Source</td><td><a href="https://example.com/report">report</a></td></tr></table>',
},
],
controls: {
overlayHost: { setEntries: (_id, entries) => cards.push(entries) },
picking: { resolvePickId: (picked) => picked?.id ?? null, clickCard },
openExternal: (url) => opened.push(url),
},
});
inputFor(viewer).onOverlayClick(() => labelOver);
await layer.update(viewer);
click('ghostmaps:cip:0:0');
const [card] = cards.at(-1);
assert.equal(card.interactive, true);
// The open card lies under the label: the click opens nothing, and the
// label on top is its own click, so the card stays open.
cardUnder = card.id;
labelOver = true;
click(null);
assert.deepEqual(opened, [], 'the link beneath the label is not opened');
assert.equal(cards.at(-1)[0]?.id, card.id, 'the card stays open');
// Off the label, a click on the open card opens its link.
labelOver = false;
click(null);
assert.deepEqual(opened, ['https://example.com/report']);
});
test('a covered selected card yields while genuine GhostMaps markers still select', async (t) => {
const cards = [];
const opened = [];
let painted = [];
const { layer, viewer, click } = fixture(t, {
reports: [
{
name: 'First',
description: '<a href="https://example.com/first">Source</a>',
},
{
name: 'Second',
description: '<a href="https://example.com/second">Source</a>',
},
],
controls: {
overlayHost: {
setEntries: (_id, entries) => cards.push(entries),
hitTest: (_x, _y, { sourceId } = {}) =>
painted.find((hit) => !sourceId || hit.sourceId === sourceId) ?? null,
},
picking: {
resolvePickId: (picked) => picked,
// The card on top at a click, as the registry answers from the host.
clickCard: () => painted[0] ?? null,
},
openExternal: (url) => opened.push(url),
},
});
await layer.update(viewer);
click('ghostmaps:cip:0:0');
const first = cards.at(-1)[0];
const foreign = {
sourceId: 'earthquake-card',
entryId: 'earthquake-card:ak1',
};
painted = [foreign, { sourceId: 's2-ghostmaps', entryId: first.id }];
click(null);
assert.deepEqual(opened, []);
assert.equal(cards.at(-1)[0].id, first.id);
// A marker under another layer's card is that card's click too.
click('ghostmaps:cip:1:0');
assert.equal(cards.at(-1)[0].id, first.id, 'a covered marker yields');
painted = [];
click('ghostmaps:cip:1:0');
const second = cards.at(-1)[0];
assert.notEqual(second.id, first.id, 'a bare marker selects');
painted = [{ sourceId: 's2-ghostmaps', entryId: second.id }];
click(null);
assert.deepEqual(opened, ['https://example.com/second']);
painted = [];
click(null);
assert.deepEqual(cards.at(-1), [], 'bare map still clears the selection');
});
+8 -35
View File
@@ -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);
}
});
+4
View File
@@ -1,4 +1,5 @@
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -52,6 +53,9 @@ export function createSelection({
const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit;
@@ -7,6 +7,7 @@ import { createRendering } from './rendering.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
function harness(t) {
const previousWindow = globalThis.window;
@@ -186,6 +187,30 @@ test('a click on a named marker point selects its site; again releases it', (t)
h.assertSelected(false);
});
// The card or label painted on top takes the click: a site under another
// layer's card neither selects nor releases.
test("another layer's card over a site keeps the click", (t) => {
const h = harness(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const setId = h.parts.namedMarkers.setId;
const item = h.draw.set(setId).items.get(namedPointId('base'));
const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
h.click(pointPick);
h.assertSelected(true);
h.click(undefined);
h.assertSelected(true);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.parts.rendering.renderRecords();
h.click(pointPick);
h.assertSelected(false);
top = null;
h.click(pointPick);
h.assertSelected(true);
});
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
+109
View File
@@ -0,0 +1,109 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createLifecycle } from './lifecycle.js';
import { createOverlays } from './overlays.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
/** Any part method is a no-op unless the test supplies it. */
const stubs = (given = {}) =>
new Proxy(given, {
get: (target, key) => (key in target ? target[key] : () => undefined),
});
// A mission label on top takes its click through the overlay handler first;
// here an overlay entry under the pointer is another layer's card or label
// painted over the mission (a quake label), and that layer takes the click,
// so the mission is not also selected.
test('a card painted over a launch marker keeps its click; with none the mission selects', () => {
const viewer = {
scene: {
pick: () => null,
canvas: { clientWidth: 100, clientHeight: 100 },
},
};
const input = fakeInput(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
const selected = [];
const state = { _launches: [{ id: 'L1' }], _enabled: false };
const { methods: lifecycle } = createLifecycle({
state,
services: {
render: { holdContinuousRender() {}, releaseContinuousRender() {} },
// The card on top at a click, as the registry answers from the host.
picking: { ...picking, clickCard: () => top },
},
parts: {
panel: stubs(),
overlays: stubs(),
launchPad: stubs(),
orbitRendering: stubs(),
replay: stubs(),
ingestion: stubs(),
rendering: stubs({
missionsShown: () => true,
missionHitsAt: () => [{ id: 'mission:L1' }],
launchIdFromPicks: (hits) =>
hits.some((hit) => hit?.id === 'mission:L1') ? 'L1' : null,
}),
selection: stubs({ setSelectedMission: (id) => selected.push(id) }),
},
source: {},
});
try {
// init installs the click handler; enable would start a feed load.
lifecycle.init(viewer);
state._enabled = true;
input.click();
assert.deepEqual(selected, [], 'the mission stands aside');
top = null;
input.click();
assert.deepEqual(
selected,
['L1'],
'with no card on top, the mission selects',
);
} finally {
state._inputSubscription?.();
input.destroy();
}
});
// A mission label is an interactive world-overlay entry, so the host's hit
// test names it and every other layer reads it as the card on top: a click
// on it never acts on what lies under it.
test('a mission label is the card on top for every other layer', (t) => {
const overlays = createOverlays({
state: {},
services: {},
parts: {},
source: {},
});
const launch = {
id: 'L1',
name: 'Starlink Group 1',
launchTime: '2026-11-01T00:00:00Z',
};
for (const selected of [false, true]) {
const entry = overlays.createRocketMissionMarkerOverlayEntry(
launch,
{ x: 1, y: 2, z: 3 },
selected,
);
assert.equal(entry.interactive, true, `selected: ${selected}`);
}
for (const sourceId of [
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
]) {
picking.setClickCardHitTest(() => ({ sourceId, entryId: 'launch:L1' }));
t.after(() => picking.setClickCardHitTest(null));
const click = { screenPosition: { x: 10, y: 10 } };
assert.equal(picking.isUnderOtherCard(click, ['vessels']), true);
assert.equal(picking.isUnderOtherCard(click, [sourceId]), false);
}
});
+106 -1
View File
@@ -1,4 +1,35 @@
import { formatNumber, t } from '../../i18n/index.js';
export function createControls({ state: layerState, services, parts, source }) {
let unsubscribeRowControls = null;
function cycleMission(step) {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const next =
index < 0
? step > 0
? 0
: entries.length - 1
: (index + step + entries.length) % entries.length;
parts.panel.selectMissionAt(entries[next].index);
// Stepped from the Data Layers row: the panel opens, as for a globe pick.
const id = layerState._selectedLaunchId;
for (const listener of [...(layerState._globePickListeners || [])]) {
try {
listener(id);
} catch (error) {
console.warn(
'[Data:RocketLaunches] mission step listener failed',
error,
);
}
}
}
const methods = {
id: 'rocket-launches',
@@ -10,6 +41,67 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: 300000,
getRowControls() {
const entries = layerState._missionRosterView?.entries;
if (!layerState._enabled || !entries?.length) return null;
const index = entries.findIndex(
({ id }) => id === layerState._selectedLaunchId,
);
const disabled = entries.length === 1 && index >= 0;
return {
info:
index < 0
? t('SELECT A MISSION TO INSPECT')
: `${formatNumber(index + 1)} / ${formatNumber(entries.length)} · ${entries[index].label}`,
chips: [
{
id: 'previous-mission',
label: t('Previous mission'),
icon: 'chevron_left',
action: true,
disabled,
onClick: () => cycleMission(-1),
},
{
id: 'next-mission',
label: t('Next mission'),
icon: 'chevron_right',
action: true,
disabled,
onClick: () => cycleMission(1),
},
],
};
},
setRowControlsListener(listener) {
unsubscribeRowControls?.();
unsubscribeRowControls = null;
if (!listener) return;
let previousRoster;
let previousSelection;
unsubscribeRowControls = parts.panel.subscribePanel(({ roster }) => {
// Replay and telemetry can update without changing the roster or pick.
const selection = layerState._selectedLaunchId;
if (roster === previousRoster && selection === previousSelection)
return;
previousRoster = roster;
previousSelection = selection;
listener();
});
},
/**
* Hear each mission picked on the globe (a marker or its label), after
* it is selected. The app reveals the Space Missions panel for it.
* @param {(launchId: string) => void} listener
* @returns {() => void} Unsubscribe.
*/
subscribeGlobePick(listener) {
layerState._globePickListeners.add(listener);
return () => layerState._globePickListeners.delete(listener);
},
/** Release only Space Mission camera ownership, preserving layer and selection state. */
releaseCameraOwnership() {
// Navigation takes the camera; a failed entry must not restore the old view.
@@ -54,19 +146,32 @@ export function createControls({ state: layerState, services, parts, source }) {
return result;
},
/**
* Why a start failed, for the person: the mission index never loaded.
* Null when the failure is not the index's (the app then names it).
* @returns {?string}
*/
enableFailureMessage() {
return layerState._lastError && layerState._lastUpdate == null
? t(
'Space Missions unavailable: the mission index could not load. Try again later.',
)
: null;
},
getStats() {
return {
count: layerState._count,
orbitMatches: layerState._orbitMatches,
lastUpdate: layerState._lastUpdate,
error: layerState._lastError,
errorAt: layerState._lastErrorAt,
stale: layerState._stale,
};
},
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
parts.satelliteIntents.connect(dataManager);
},
};
+432 -47
View File
@@ -4,12 +4,12 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { DataLayerManager } from '../../data/manager.js';
import { ContextControls } from '../../ui/contextControls.js';
import { spaceMissionsIndexFailure } from '../../ui/contextActions.js';
import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createPanel } from './panel.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
@@ -98,7 +98,7 @@ function fakeCamera() {
return camera;
}
async function fixture(t) {
async function fixture(t, { beforeConnect } = {}) {
const upstream = { status: 429, results: [launchRecord] };
const source = createLaunchSource({
async fetchImpl(url) {
@@ -191,6 +191,7 @@ async function fixture(t) {
parts.panel = createPanel(context);
parts.replay = createReplay(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const missions = Object.assign(
@@ -206,6 +207,7 @@ async function fixture(t) {
manager.register(plainLayer('earthquakes', 'Earthquakes (24h)'));
manager.register(plainLayer('satellites', 'Satellites'));
manager.register(plainLayer('wind', 'Wind'));
manager.register(plainLayer('military-awareness', 'Global Context'));
manager.register(missions);
missions.attachDataManager(manager);
@@ -224,12 +226,19 @@ async function fixture(t) {
setPanelCollapsed: noop,
},
});
beforeConnect?.(manager);
controls.connect(manager);
t.after(async () => {
controls.stop();
controls.disconnect();
for (const id of ['rocket-launches', 'satellites', 'earthquakes', 'wind'])
for (const id of [
'rocket-launches',
'satellites',
'earthquakes',
'wind',
'military-awareness',
])
await manager.setEnabled(id, false);
await missions.destroy(viewer);
});
@@ -257,46 +266,37 @@ async function fixture(t) {
state,
camera,
rosters,
panel: parts.panel,
enabledIds,
view,
settle,
};
}
const entries = {
direct: (f) =>
f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
'Context-panel': async (f) =>
(
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
})
).ok,
};
test('a Space Missions start that gets HTTP 429 rolls back and leaves other layers alone', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
for (const [path, enter] of Object.entries(entries))
test(`a ${path} Space Missions entry that gets HTTP 429 rolls back instead of isolating`, async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
const before = f.view();
const entered = await enter(f);
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
const entered = await f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
await f.settle();
assert.equal(entered, false, 'a failed mission index fails the enable');
assert.deepEqual(f.enabledIds(), ['earthquakes']);
assert.equal(f.controls.getContextModeState().mode, null);
assert.equal(f.controls.getContextModeState().active, false);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.deepEqual(f.view(), before, 'the pre-entry view comes back');
assert.ok(f.camera.cancelled > 0, 'the full-globe flight is cancelled');
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'an unrelated layer is not blocked after the failed entry',
);
});
// Holds the /api/launches reply until the returned release is called.
function holdReply(f) {
@@ -410,7 +410,12 @@ test('the roster reports a failed mission index instead of loading forever', asy
await f.settle();
assert.equal(f.rosters.slice(loadingFrom).includes(null), true);
assert.equal(f.rosters.at(-1).entries.length, 1);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.controls.getContextModeState().mode,
null,
'not a Context mode',
);
});
test('a valid empty mission index is a successful entry', async (t) => {
@@ -422,7 +427,7 @@ test('a valid empty mission index is a successful entry', async (t) => {
true,
);
await f.settle();
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(
f.rosters.at(-1).empty,
'NO MISSIONS AVAILABLE IN THE CURRENT 30-DAY WINDOW',
@@ -430,7 +435,383 @@ test('a valid empty mission index is a successful entry', async (t) => {
assert.ok(f.camera.flights > 0, 'a successful entry frames the globe');
});
test('a refresh failure after a loaded index keeps the mode and its records', async (t) => {
for (const phase of ['while starting', 'after start']) {
test(`Space Missions runs beside Contacts and a later Satellites OFF ends it (${phase})`, async (t) => {
const gate = Promise.withResolvers();
const guardReached = Promise.withResolvers();
const f = await fixture(t, {
beforeConnect(manager) {
if (phase !== 'while starting') return;
manager.addVisibilityGuard(async ({ layerId, enabled }) => {
if (layerId !== 'rocket-launches' || !enabled) return;
guardReached.resolve();
await gate.promise;
});
},
});
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(
f.enabledIds(),
['military-awareness', 'satellites'],
'Contacts leaves Satellites alone',
);
const launch = f.manager.setEnabled('rocket-launches', true, {
origin: 'user',
});
try {
if (phase === 'while starting') {
await guardReached.promise;
} else {
assert.equal(await launch, true);
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
}
assert.equal(
f.controls.getContextModeState().mode,
'flights',
'starting Space Missions leaves Contacts on',
);
assert.equal(
await f.manager.setEnabled('satellites', false, { origin: 'voice' }),
true,
);
} finally {
gate.resolve();
}
assert.equal(await launch, phase === 'after start');
await f.missions.waitForSatelliteIntents?.();
await f.settle();
assert.deepEqual(f.enabledIds(), ['military-awareness']);
assert.equal(f.controls.getContextModeState().mode, 'flights');
});
}
test('Contacts started and ended while Space Missions runs leaves it and Satellites alone', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
const missionParams = f.manager.getLayerParams('satellites');
assert.equal(missionParams.showPoints, false, 'the mission display applied');
assert.equal(await f.controls._selectContextMode('flights'), true);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'military-awareness',
'rocket-launches',
'satellites',
]);
assert.equal(await f.controls._selectContextMode(null), true);
await f.settle();
assert.deepEqual(f.enabledIds(), ['rocket-launches', 'satellites']);
assert.deepEqual(f.manager.getLayerParams('satellites'), missionParams);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.enabledIds(), []);
const after = f.manager.getLayerParams('satellites');
assert.notEqual(after.showPoints, false, 'Satellites shows its points again');
assert.notEqual(after.showOrbits, false, 'and its orbits');
});
test('a Satellites OFF requested before Space Missions entry does not cancel it', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('satellites', true, { origin: 'user' });
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
const gate = Promise.withResolvers();
const disabling = Promise.withResolvers();
satellites.disable = async () => {
disabling.resolve();
await gate.promise;
};
let entry;
try {
const off = f.manager.setEnabled('satellites', false, { origin: 'user' });
await disabling.promise;
// The entry is requested while the earlier OFF is still settling.
entry = f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
gate.resolve();
assert.equal(await off, true);
} finally {
gate.resolve();
satellites.disable = disable;
}
assert.equal(await entry, true, 'the later entry is not cancelled');
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
// Leaving keeps the earlier Satellites OFF.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
assert.equal(f.manager.isEnabled('rocket-launches'), false);
});
test('Space Missions is an ordinary layer: it neither isolates nor opens a Context session', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.deepEqual(f.enabledIds(), [
'earthquakes',
'rocket-launches',
'satellites',
]);
assert.equal(f.controls._contextSessionSnapshot, null);
assert.equal(
await f.manager.setEnabled('wind', true, { origin: 'user' }),
true,
'other layers are not refused while Space Missions is on',
);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(
f.enabledIds(),
['earthquakes', 'wind'],
'Space Missions gives back only the Satellites it turned on',
);
});
test('a Satellites enable that never settles still lets mission disable complete', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
// A programmatic Satellites restart whose enable hangs.
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
const exit = f.manager.setEnabled('rocket-launches', false, {
origin: 'user',
});
const outcome = await Promise.race([
exit.then(() => 'settled'),
new Promise((resolve) => setTimeout(() => resolve('hung'), 2000)),
]);
assert.equal(
outcome,
'settled',
'the mission disable does not wait forever',
);
assert.equal(f.missions.getAnalystRecords().length, 0);
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
// The saved Satellites state was kept: turning Space Missions off again
// once Satellites settles gives back the Satellites it turned on.
assert.equal(f.manager.isEnabled('satellites'), true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), false);
assert.equal(f.manager.isEnabled('satellites'), false);
});
test('Space Missions turned on again after a busy restore switches Satellites on', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
// Something else switches Satellites off, then Space Missions comes back.
await f.manager.setEnabled('satellites', false);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), true);
// Its own off still gives back the Satellites from before the first start.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
});
test('a Satellites switch made between missions is what the next mission gives back', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
// The person switches Satellites on, then something else switches it off.
await f.manager.setEnabled('satellites', true, { origin: 'user' });
await f.settle();
await f.manager.setEnabled('satellites', false);
await f.settle();
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), false);
});
test('a Satellites setting changed between missions survives the next one', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.state.satelliteSettleTimeoutMs = 50;
const satellites = f.manager.layers.get('satellites').module;
const enable = satellites.enable;
const stuck = Promise.withResolvers();
satellites.enable = () => stuck.promise;
try {
await f.manager.setEnabled('satellites', false);
void f.manager.setEnabled('satellites', true);
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
} finally {
satellites.enable = enable;
stuck.resolve();
}
await f.settle();
f.manager.setLayerParams(
'satellites',
{ showOrbits: false },
{ origin: 'user' },
);
await f.settle();
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(f.manager.getLayerParams('satellites').showOrbits, false);
});
test('tracking stopped by a place search during a mission stays stopped after it', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
f.manager.setLayerParams(
'satellites',
{ selectedSatTrackingId: 25544 },
{ origin: 'voice' },
);
await f.settle();
// A place search stops tracking with the tool origin.
f.manager.setLayerParams(
'satellites',
{ selectedSatTrackingId: null },
{ origin: 'tool' },
);
await f.settle();
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.equal(
f.manager.getLayerParams('satellites').selectedSatTrackingId ?? null,
null,
);
});
test('a failed Satellites restore still clears the selected mission panel', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
assert.equal(
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' }),
true,
);
await f.settle();
assert.equal(f.manager.isEnabled('satellites'), true);
let panelView;
const unsubscribe = f.panel.subscribePanel((view) => {
panelView = view;
});
const satellites = f.manager.layers.get('satellites').module;
const disable = satellites.disable;
try {
f.state._selectedLaunchId = f.state._launches[0].id;
f.panel.renderMissionPanel();
assert.ok(panelView.mission);
satellites.disable = () => {
throw new Error('injected Satellites restore failure');
};
assert.equal(
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' }),
false,
);
const { enabled, uncertain } =
f.manager.getLayerLifecycleState('rocket-launches');
assert.equal(enabled, true);
assert.equal(uncertain, true);
assert.equal(panelView.mission, null);
} finally {
satellites.disable = disable;
unsubscribe();
}
});
test('a refresh failure after a loaded index keeps the layer and its records', async (t) => {
const f = await fixture(t);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
@@ -442,12 +823,11 @@ test('a refresh failure after a loaded index keeps the mode and its records', as
await f.settle();
assert.equal(f.manager.isEnabled('rocket-launches'), true);
assert.equal(f.controls.getContextModeState().mode, 'space-missions');
assert.equal(f.missions.getStats().count, 1);
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.rosters.at(-1).entries.length, 1);
// Leaving a loaded mode does not restore the pre-entry view.
// Leaving after a loaded index does not restore the pre-entry view.
await f.manager.setEnabled('rocket-launches', false, { origin: 'user' });
await f.settle();
assert.deepEqual(f.view(), framed);
@@ -475,11 +855,9 @@ test('a failed first load tells the user the mission index is unavailable', asyn
const f = await fixture(t);
await f.manager.setEnabled('earthquakes', true, { origin: 'user' });
await f.controls.setContextMode('space-missions', {
claimVisualAuthority: false,
});
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.equal(f.controls.getContextModeState().mode, null, 'rolled back');
assert.equal(f.manager.isEnabled('rocket-launches'), false, 'rolled back');
assert.ok(
f.toasts.some((message) => /mission index/i.test(message)),
`visible feedback names the failure, got ${JSON.stringify(f.toasts)}`,
@@ -504,10 +882,17 @@ test('navigation taking the camera keeps a mission flight it asked to preserve',
assert.equal(f.camera.flight, other);
});
test("an earlier attempt's index error is not blamed for a later failure", async (t) => {
test('a refresh error after a loaded index is not blamed on the index', async (t) => {
const f = await fixture(t);
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
assert.match(spaceMissionsIndexFailure(f.manager), /mission index/);
assert.equal(spaceMissionsIndexFailure(f.manager, Date.now() + 1), null);
assert.match(f.missions.enableFailureMessage(), /mission index/);
f.upstream.status = 200;
await f.manager.setEnabled('rocket-launches', true, { origin: 'user' });
await f.settle();
f.upstream.status = 429;
await f.missions.update();
assert.equal(f.missions.getStats().error, 'HTTP 429');
assert.equal(f.missions.enableFailureMessage(), null);
});
+3
View File
@@ -1,5 +1,6 @@
import { createPolicyHelpers } from './policyHelpers.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createOrbitRendering } from './orbitRendering.js';
import { createOverlays } from './overlays.js';
import { createSelection } from './selection.js';
@@ -24,6 +25,7 @@ export function createRocketLaunchesLayer({ services, source }) {
const context = { state, services, parts, source };
parts.policyHelpers = createPolicyHelpers(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.orbitRendering = createOrbitRendering(context);
parts.overlays = createOverlays(context);
parts.selection = createSelection(context);
@@ -45,6 +47,7 @@ export function createRocketLaunchesLayer({ services, source }) {
parts.panel.commands,
{
subscribePanel: parts.panel.subscribePanel,
waitForSatelliteIntents: parts.satelliteIntents.settled,
subscribeReplayOverlay: parts.overlays.subscribeReplayOverlay,
satelliteParamsForSpaceMissions:
parts.policyHelpers.satelliteParamsForSpaceMissions,
+82 -28
View File
@@ -1,4 +1,18 @@
import { MAX_POST_TLE_RETRIES, POST_TLE_RETRY_DELAY_MS } from './policy.js';
import {
MAX_POST_TLE_RETRIES,
POST_TLE_RETRY_DELAY_MS,
cockpitActive,
} from './policy.js';
/**
* Let pending Satellites work finish, including requests that join it while
* waiting, so the mission dependency cannot overtake it. Bounded: a
* Satellites change that never settles cannot hold missions forever.
*/
async function waitForSatelliteVisibility(manager, { signal, timeoutMs }) {
if (typeof manager.waitForLayerIdle !== 'function') return true;
return manager.waitForLayerIdle('satellites', { signal, timeoutMs });
}
export function createIngestion({
state: layerState,
@@ -97,28 +111,51 @@ export function createIngestion({
}
async function captureSatelliteDependency() {
if (!layerState._dataManager || layerState._satelliteStateBeforeMission)
const manager = layerState._dataManager;
if (!manager) return;
const token = layerState._lifecycleToken;
// Let a pending Satellites action finish before reserving dependency ON.
// A successful explicit OFF can cancel this mission entry while we wait.
const idle = await waitForSatelliteVisibility(manager, {
signal: layerState._sourceController?.signal,
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (token !== layerState._lifecycleToken) return;
if (!idle && layerState._enabled)
throw new Error(
'Space Missions could not start: the satellites layer did not settle',
);
if (
!layerState._enabled ||
(manager.layers?.has('rocket-launches') &&
!manager.isEffectivelyEnabled('rocket-launches'))
)
return;
layerState._satelliteStateBeforeMission = {
// Effective visibility: a user enable still mid-activation is intent ON —
// capturing settled false would restore the user's enable away on exit.
enabled:
layerState._dataManager.isEffectivelyEnabled?.('satellites') ??
layerState._dataManager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
layerState._dataManager.getLayerParams('satellites'),
),
};
layerState._dataManager.setLayerParams(
// A saved state kept by a restore that could not finish (Satellites was
// busy) is still the one from before the mission: keep it, and switch
// Satellites on for the mission again. A Satellites switch the person
// made since (restoreVisibility false) settled its visibility, so it
// is taken as it is now; its params are still the saved ones.
const kept = layerState._satelliteStateBeforeMission;
if (kept?.restoreVisibility === false)
layerState._satelliteStateBeforeMission = {
enabled: manager.isEnabled('satellites'),
params: kept.params,
};
else if (!kept)
layerState._satelliteStateBeforeMission = {
enabled: manager.isEnabled('satellites'),
params: parts.policyHelpers.satelliteParamsAfterSpaceMissions(
manager.getLayerParams('satellites'),
),
};
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsForSpaceMissions(
layerState._satelliteStateBeforeMission.params,
),
);
const token = layerState._lifecycleToken;
const activation = Promise.resolve(
layerState._dataManager.setEnabled('satellites', true),
);
const activation = Promise.resolve(manager.setEnabled('satellites', true));
layerState._satelliteActivationPromise = activation;
try {
const activated = await activation;
@@ -128,8 +165,7 @@ export function createIngestion({
if (
token === layerState._lifecycleToken &&
layerState._enabled &&
(activated === false ||
!layerState._dataManager.isEnabled('satellites'))
(activated === false || !manager.isEnabled('satellites'))
) {
throw new Error(
'Space Missions requires the satellites layer, which failed to start',
@@ -146,21 +182,38 @@ export function createIngestion({
}
async function restoreSatelliteDependency() {
const manager = layerState._dataManager;
const snapshot = layerState._satelliteStateBeforeMission;
if (!snapshot || !layerState._dataManager) return;
if (!snapshot || !manager) return;
// Keep the snapshot available until any explicit Satellites action settles.
const token = layerState._lifecycleToken;
const idle = await waitForSatelliteVisibility(manager, {
timeoutMs: layerState.satelliteSettleTimeoutMs,
});
if (
token !== layerState._lifecycleToken ||
layerState._satelliteStateBeforeMission !== snapshot
)
return;
// An accepted Satellites action owns visibility through mission teardown.
const restoreVisibility = snapshot.restoreVisibility !== false;
// Satellites is still busy: change nothing and keep the saved state, so
// turning Space Missions off again can finish the restore.
if (restoreVisibility && !idle)
throw new Error(
'Space Missions could not restore the satellites layer: it did not settle',
);
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager.setLayerParams(
manager.setLayerParams(
'satellites',
parts.policyHelpers.satelliteParamsAfterSpaceMissions(snapshot.params),
);
const restored = await layerState._dataManager.setEnabled(
'satellites',
snapshot.enabled,
);
if (!restoreVisibility) return;
const restored = await manager.setEnabled('satellites', snapshot.enabled);
if (
restored === false ||
layerState._dataManager.isEnabled('satellites') !== snapshot.enabled
manager.isEnabled('satellites') !== snapshot.enabled
) {
throw new Error('Space Missions could not restore the satellites layer');
}
@@ -215,7 +268,9 @@ export function createIngestion({
parts.selection.setSelectedMission(null, false);
} else {
parts.selection.setSelectedMission(layerState._selectedLaunchId, true);
if (layerState._focusAfterActiveLookup) {
// The cockpit holds the camera: a mission picked there is not flown
// to when its orbit arrives.
if (layerState._focusAfterActiveLookup && !cockpitActive()) {
parts.selection.focusMission(
launches.find(
(launch) => launch.id === layerState._selectedLaunchId,
@@ -230,7 +285,6 @@ export function createIngestion({
} catch (error) {
if (layerState._enabled && token === layerState._lifecycleToken) {
layerState._lastError = error.message;
layerState._lastErrorAt = Date.now();
console.warn('[Data:RocketLaunches] Fetch error:', error);
// No index yet: fail the enable so Context rolls back.
// After a loaded index, a failed refresh keeps its records.
+7 -1
View File
@@ -8,6 +8,7 @@ import { createLaunchSource } from './source.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
import { createControls } from './controls.js';
import { createLifecycle } from './lifecycle.js';
import { layerFeedState } from '../../data/feedState.js';
@@ -147,6 +148,7 @@ async function fixture({ legacySource = false } = {}) {
const context = { state, services, parts, source };
parts.model = createModel(context);
parts.ingestion = createIngestion(context);
parts.satelliteIntents = createSatelliteIntents(context);
parts.controls = createControls(context);
parts.lifecycle = createLifecycle(context);
const current = () => {
@@ -326,7 +328,11 @@ test('destroy followed by actual init starts a clean instance with owned handler
assert.equal(typeof f.state._inputSubscription, 'function');
await f.destroy();
assert.equal(f.state._inputSubscription, null);
assert.equal(input.subscriberCount(), before - 2, 'click and hover');
assert.equal(
input.subscriberCount(),
before - 3,
'label click, point click and hover',
);
assert.equal(f.attachedSets(), 0);
assert.equal(f.viewer.scene.preRender.numberOfListeners, 0);
+252
View File
@@ -0,0 +1,252 @@
// Clicks on painted mission labels, routed through the real input dispatcher.
import test from 'node:test';
import assert from 'node:assert/strict';
import { Event } from 'cesium';
import { createLifecycle } from './lifecycle.js';
import { createState } from './state.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
} from './policy.js';
import {
FAKE_EVENT_TYPES,
FakeScreenSpaceEventHandler,
fakeInput,
} from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
const noop = () => {};
/** Parts whose every method is a no-op unless given. */
function stub(methods = {}) {
return new Proxy(methods, {
get: (target, key) => (key in target ? target[key] : noop),
});
}
function rig(t, { overlayHit = null, geometryLaunchId = null } = {}) {
const stock = new FakeScreenSpaceEventHandler();
stock.setInputAction(noop, FAKE_EVENT_TYPES.LEFT_CLICK);
const viewer = bindFakeCesiumCamera({
isDestroyed: () => false,
screenSpaceEventHandler: stock,
camera: {
moveStart: new Event(),
moveEnd: new Event(),
pickEllipsoid: () => null,
},
scene: {
canvas: { style: { cursor: '' } },
screenSpaceCameraController: { enableInputs: true },
pick: () => undefined,
drillPick: () => [],
},
});
const pointer = fakeInput(viewer);
const services = {
overlays: {
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
clearOverlaySource: noop,
hitTestWorldOverlay: () => overlayHit,
},
render: { holdContinuousRender: noop, releaseContinuousRender: noop },
};
const state = createState({ services });
const focused = [];
const moved = [];
const restoreFailure = { error: null };
const parts = {
panel: stub(),
overlays: stub(),
replay: stub(),
launchPad: stub(),
orbitRendering: stub(),
selection: stub({
setSelectedMission: (id) => focused.push(id),
focusMission: (launch) => moved.push(launch.id),
}),
satelliteIntents: stub(),
ingestion: stub({
async restoreSatelliteDependency() {
if (restoreFailure.error) throw restoreFailure.error;
},
}),
rendering: stub({
missionsShown: () => true,
missionHitsAt: () => [],
launchIdFromPicks: () => geometryLaunchId,
launchMarkerAt: () => null,
}),
};
const lifecycle = createLifecycle({
state,
services,
parts,
source: {},
}).methods;
lifecycle.init(viewer);
state._enabled = true;
state._launches = [{ id: 'L1' }, { id: 'L2' }];
// Another layer's ambient click handler, as aircraft or the cockpit has.
const ambient = [];
const offAmbient = pointer.input.onClick((event) => ambient.push(event));
t.after(async () => {
restoreFailure.error = null;
offAmbient();
await lifecycle.destroy(viewer);
pointer.input.destroy();
});
return {
focused,
moved,
ambient,
state,
lifecycle,
viewer,
input: pointer.input,
restoreFailure,
setHit(hit) {
overlayHit = hit;
},
click: () => pointer.tap({ x: 40, y: 30 }),
};
}
const label = (
entryId,
sourceId = ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
) => ({
sourceId,
entryId,
});
test('a mission label click focuses its launch and covers the geometry beneath', (t) => {
const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
r.click();
assert.deepEqual(r.focused, ['L2'], 'the mission beneath is not picked');
// Other layers still hear it, as a click on the label rather than on the
// geometry beneath; the label is the card on top, so they keep their
// selections.
assert.equal(r.ambient.length, 1);
assert.equal(r.ambient[0].overlay, true);
assert.equal(r.ambient[0].drawHit, null);
r.setHit(label('launch:L1', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID));
r.click();
assert.deepEqual(r.focused, ['L2', 'L1'], 'the selected label routes too');
});
test('a mission picked on the globe is announced, after it is selected', (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const picks = [];
r.state._globePickListeners.add((id) => picks.push([id, [...r.focused]]));
r.click();
assert.deepEqual(picks, [['L2', ['L2']]], 'the label pick is announced');
r.setHit(null);
r.click();
assert.equal(picks.length, 1, 'a click on nothing announces nothing');
});
test('a throwing globe-pick listener does not stop the pick', (t) => {
const r = rig(t, { overlayHit: label('launch:L1') });
const warn = console.warn;
console.warn = noop;
t.after(() => {
console.warn = warn;
});
const heard = [];
r.state._globePickListeners.add(() => {
throw new Error('listener failure');
});
r.state._globePickListeners.add((id) => heard.push(id));
r.click();
assert.deepEqual(r.focused, ['L1']);
assert.deepEqual(heard, ['L1']);
assert.equal(r.ambient.length, 1);
assert.equal(r.ambient[0].overlay, true);
});
test('a mission label for an unknown launch selects nothing', (t) => {
const r = rig(t, {
overlayHit: label('launch:gone'),
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'nothing is focused');
// Other layers hear the click; the label is still the card on top for
// them (clickYield.test.mjs), so none acts under it.
assert.equal(r.ambient.length, 1);
});
test("another layer's label keeps the click above mission geometry", (t) => {
// An aircraft label painted over a mission path.
const r = rig(t, {
overlayHit: { sourceId: 'aircraft-labels', entryId: 'launch:L1' },
geometryLaunchId: 'L1',
});
r.click();
assert.deepEqual(r.focused, [], 'the mission under the label is not picked');
assert.equal(r.ambient.length, 1, "the label's owner gets the click");
// With no label there, the same click picks the mission geometry.
r.setHit(null);
r.click();
assert.deepEqual(r.focused, ['L1']);
});
test('in the cockpit a mission label or dot selects its mission without moving the camera', (t) => {
const r = rig(t, { overlayHit: label('launch:L2'), geometryLaunchId: 'L1' });
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: {
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
},
});
try {
r.click();
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
assert.deepEqual(r.focused, ['L2'], 'the mission is selected');
assert.deepEqual(r.moved, [], 'the cockpit keeps the camera');
// The dot, with no label over it, does the same.
r.setHit(null);
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: {
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
},
});
try {
r.click();
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
assert.deepEqual(r.focused, ['L2', 'L1']);
assert.deepEqual(r.moved, []);
r.setHit(label('launch:L2'));
// Out of the cockpit the same click moves there too.
r.click();
assert.deepEqual(r.moved, ['L2']);
});
test('destroy releases the click handlers when the Satellites restore fails', async (t) => {
const r = rig(t, { overlayHit: label('launch:L2') });
const before = r.input.subscriberCount();
r.restoreFailure.error = new Error('injected Satellites restore failure');
await assert.rejects(r.lifecycle.destroy(r.viewer), /injected/);
assert.equal(r.state._inputSubscription, null);
// The rest of teardown still ran before the failure was reported.
assert.equal(r.state._viewer, null, 'the viewer is released');
assert.deepEqual(r.state._launches, [], 'the records are dropped');
assert.equal(r.state._dataManager, null, 'the manager is released');
assert.ok(r.input.subscriberCount() < before, 'the handlers unsubscribed');
r.click();
assert.deepEqual(r.focused, [], 'a later label click reaches no mission');
assert.equal(r.ambient.length, 1);
});
+80 -15
View File
@@ -2,6 +2,11 @@ import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { worldClock } from '../../time/worldClock.js';
import {
ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID,
ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID,
cockpitActive,
} from './policy.js';
const HOVER_PICK_INTERVAL_MS = 120;
@@ -150,6 +155,15 @@ function restoreCameraView(viewer, view, landedView) {
/** The longest name a timeline mark carries, as in the mission index. */
const MARK_LABEL_LENGTH = 27;
function markerLaunchId(hit) {
if (
hit?.sourceId !== ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID &&
hit?.sourceId !== ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID
)
return null;
return hit.entryId.startsWith('launch:') ? hit.entryId.slice(7) : null;
}
export function createLifecycle({
state: layerState,
services,
@@ -157,6 +171,25 @@ export function createLifecycle({
source,
}) {
const { holdContinuousRender, releaseContinuousRender } = services.render;
const overlayAt = (position) =>
services.overlays?.hitTestWorldOverlay?.(position?.x, position?.y);
const missionsShown = () =>
layerState._enabled && parts.rendering.missionsShown();
const focusLaunch = (id, { move = true } = {}) => {
if (!id) return false;
const launch = layerState._launches.find((entry) => entry.id === id);
if (!launch) return false;
parts.selection.setSelectedMission(launch.id);
if (move) parts.selection.focusMission(launch);
for (const listener of [...layerState._globePickListeners]) {
try {
listener(launch.id);
} catch (error) {
console.warn('[Data:RocketLaunches] globe pick listener failed', error);
}
}
return true;
};
let hover = null;
// While on, the launches loaded span the time from the first to the last,
// each one a mark labelled with its mission's name (the launch's where it
@@ -204,25 +237,48 @@ export function createLifecycle({
layerState._orbitMatches = 0;
parts.overlays.clearMissionOverlaySources();
const input = inputFor(viewer);
const overlayClicks = new WeakSet();
const unsubscribeLabelClick = input.onOverlayClick((event) => {
if (!missionsShown()) return false;
const hit = overlayAt(event.screenPosition);
if (!hit) return false;
// Capture the painted hit before other handlers can invalidate the
// overlay. An unrelated label keeps the click above mission geometry.
overlayClicks.add(event);
// The label is the card on top, so every other layer and the cockpit
// leave its click alone. In the cockpit, which holds the camera, the
// label and the dot select the mission without moving there.
return focusLaunch(markerLaunchId(hit), { move: !cockpitActive() });
});
const unsubscribeClick = input.onClick((event) => {
if (!layerState._enabled || !parts.rendering.missionsShown()) return;
// The click's pick position (CSS px), as the click picked it.
const launchId = parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
);
if (!launchId) return;
parts.selection.setSelectedMission(launchId);
parts.selection.focusMission(
layerState._launches.find((launch) => launch.id === launchId),
// Another layer's card or label on top is that layer's click, read
// once per click as every layer reads it.
if (
!missionsShown() ||
overlayClicks.has(event) ||
services.picking?.clickCard?.(event)
)
return;
focusLaunch(
parts.rendering.launchIdFromPicks(
parts.rendering.missionHitsAt(event.position, 12),
),
{ move: !cockpitActive() },
);
});
hover = createLaunchHover({
viewer,
enabled: () => layerState._enabled && parts.rendering.missionsShown(),
launchAt: parts.rendering.launchMarkerAt,
enabled: missionsShown,
launchAt(position) {
const hit = overlayAt(position);
return hit
? Boolean(markerLaunchId(hit))
: parts.rendering.launchMarkerAt(position);
},
});
const unsubscribeHover = input.onPointer('move', hover.move);
layerState._inputSubscription = () => {
unsubscribeLabelClick();
unsubscribeClick();
unsubscribeHover();
};
@@ -321,8 +377,8 @@ export function createLifecycle({
parts.overlays.hideReplayVehicleOverlay();
layerState._selectedLaunchId = null;
parts.overlays.clearMissionOverlaySources();
await parts.ingestion.restoreSatelliteDependency();
parts.panel.renderMissionPanel();
await parts.ingestion.restoreSatelliteDependency();
layerState.coverageChanged();
},
@@ -336,14 +392,22 @@ export function createLifecycle({
layerState._enabled = false;
layerState._lifecycleToken++;
layerState._updateDirty = false;
await parts.ingestion.restoreSatelliteDependency();
// A failed Satellites restore still tears everything else down; the
// failure is reported once teardown is complete.
let restoreError = null;
try {
await parts.ingestion.restoreSatelliteDependency();
} catch (error) {
restoreError = error;
}
layerState._inputSubscription?.();
layerState._inputSubscription = null;
parts.satelliteIntents.connect(null);
parts.panel.clearMissionRosterHover();
parts.replay.stopMissionReplay();
layerState._cameraReleased = true;
parts.selection.stopMissionZoomAnchor();
parts.ingestion.clearPostTleRetry();
layerState._inputSubscription?.();
layerState._inputSubscription = null;
if (layerState._declutterHandler) layerState._declutterHandler();
layerState._declutterHandler = null;
parts.launchPad.destroyLaunchPadZonePrimitive();
@@ -370,6 +434,7 @@ export function createLifecycle({
layerState._satelliteStateBeforeMission = null;
layerState._satelliteActivationPromise = null;
layerState._dataManager = null;
if (restoreError) throw restoreError;
},
};
+212
View File
@@ -0,0 +1,212 @@
// The Data Layers row's previous/next mission controls, and the Satellites
// restore an explicit Satellites action takes over.
import test from 'node:test';
import assert from 'node:assert/strict';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createSatelliteIntents } from './satelliteIntents.js';
const roster = (...ids) => ({
entries: ids.map((id, index) => ({ id, index, label: `Mission ${id}` })),
});
function rig({ ids = ['A', 'B', 'C'], selected = null, enabled = true } = {}) {
const panelListeners = new Set();
const state = {
_enabled: enabled,
_selectedLaunchId: selected,
_missionRosterView: ids ? roster(...ids) : null,
};
const parts = {
panel: {
selectMissionAt(index) {
state._selectedLaunchId = state._missionRosterView.entries[index].id;
},
subscribePanel(listener) {
panelListeners.add(listener);
return () => panelListeners.delete(listener);
},
},
};
const { methods } = createControls({ state, services: {}, parts });
return {
state,
methods,
chip: (id) => methods.getRowControls().chips.find((c) => c.id === id),
publish: (view) => {
for (const listener of [...panelListeners]) listener(view);
},
listenerCount: () => panelListeners.size,
};
}
test('next and previous wrap around the roster', () => {
const r = rig({ selected: 'C' });
r.chip('next-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'A',
'next after the last is the first',
);
r.chip('previous-mission').onClick();
assert.equal(
r.state._selectedLaunchId,
'C',
'previous before the first is the last',
);
r.chip('previous-mission').onClick();
assert.equal(r.state._selectedLaunchId, 'B');
assert.match(r.methods.getRowControls().info, /^2 \/ 3 · Mission B$/);
});
test('with nothing selected, next picks the first mission and previous the last', () => {
const next = rig();
next.chip('next-mission').onClick();
assert.equal(next.state._selectedLaunchId, 'A');
const previous = rig();
previous.chip('previous-mission').onClick();
assert.equal(previous.state._selectedLaunchId, 'C');
});
test('the controls disable only when the one mission is already selected', () => {
const only = rig({ ids: ['A'], selected: 'A' });
assert.equal(only.chip('next-mission').disabled, true);
assert.equal(only.chip('previous-mission').disabled, true);
// One mission, not yet picked: the controls can still select it.
const unpicked = rig({ ids: ['A'] });
assert.equal(unpicked.chip('next-mission').disabled, false);
unpicked.chip('next-mission').onClick();
assert.equal(unpicked.state._selectedLaunchId, 'A');
assert.equal(rig({ selected: 'B' }).chip('next-mission').disabled, false);
});
test('there are no controls while the layer is off or the roster is empty', () => {
assert.equal(rig({ enabled: false }).methods.getRowControls(), null);
assert.equal(rig({ ids: [] }).methods.getRowControls(), null);
assert.equal(rig({ ids: null }).methods.getRowControls(), null);
// A stale click after the layer stops selects nothing.
const r = rig({ selected: 'A' });
const next = r.chip('next-mission');
r.state._enabled = false;
next.onClick();
assert.equal(r.state._selectedLaunchId, 'A');
});
test('the row listener fires only when the roster or the selection changes', () => {
const r = rig();
let calls = 0;
r.methods.setRowControlsListener(() => calls++);
const view = r.state._missionRosterView;
r.publish({ roster: view });
assert.equal(calls, 1, 'the first view is a change');
r.publish({ roster: view });
assert.equal(calls, 1, 'a replay or telemetry update is not');
r.state._selectedLaunchId = 'B';
r.publish({ roster: view });
assert.equal(calls, 2, 'a new selection is');
r.publish({ roster: roster('A', 'B') });
assert.equal(calls, 3, 'a new roster is');
// A new listener replaces the old one; null removes it.
let replaced = 0;
r.methods.setRowControlsListener(() => replaced++);
assert.equal(r.listenerCount(), 1);
r.methods.setRowControlsListener(null);
assert.equal(r.listenerCount(), 0);
r.publish({ roster: roster('C') });
assert.equal(calls, 3);
assert.equal(replaced, 0);
});
function satelliteRig({ enabledBefore }) {
const calls = [];
let satellitesOn = true;
const manager = {
layers: new Map([['satellites', { toggleChain: null }]]),
waitForLayerIdle: async () => true,
isEnabled: () => satellitesOn,
isEffectivelyEnabled: (id) =>
id === 'satellites' ? satellitesOn : id === 'rocket-launches',
setLayerParams: (id, params) => calls.push(['params', id, params]),
async setEnabled(id, enabled) {
calls.push(['enabled', id, enabled]);
satellitesOn = enabled;
return true;
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: {
enabled: enabledBefore,
params: { mode: 'before' },
},
_satelliteActivationPromise: null,
};
const parts = {
policyHelpers: { satelliteParamsAfterSpaceMissions: (params) => params },
};
const ingestion = createIngestion({ state, services: {}, parts, source: {} });
parts.satelliteIntents = createSatelliteIntents({ state });
const { methods } = createControls({ state, services: {}, parts });
return { state, calls, ingestion, methods, intents: parts.satelliteIntents };
}
test('an accepted Satellites action keeps its visibility through mission exit', async () => {
const r = satelliteRig({ enabledBefore: false });
// The person turns Satellites on themselves while the missions are on.
r.intents.handleVisibility({
type: 'visibility',
layerId: 'satellites',
enabled: true,
origin: 'user',
});
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(
r.calls,
[['params', 'satellites', { mode: 'before' }]],
'the parameters come back, the visibility is left alone',
);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
test('without a Satellites action the exit restores the pre-mission visibility', async () => {
const r = satelliteRig({ enabledBefore: false });
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [
['params', 'satellites', { mode: 'before' }],
['enabled', 'satellites', false],
]);
});
test('a Satellites layer that does not settle keeps the saved state for the next exit', async () => {
const r = satelliteRig({ enabledBefore: false });
let idle = false;
r.state._dataManager.waitForLayerIdle = async () => idle;
await assert.rejects(
r.ingestion.restoreSatelliteDependency(),
/did not settle/,
);
assert.deepEqual(r.calls, [], 'nothing changes while Satellites is busy');
assert.deepEqual(r.state._satelliteStateBeforeMission, {
enabled: false,
params: { mode: 'before' },
});
// Turning Space Missions off again once Satellites settles finishes it.
idle = true;
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [
['params', 'satellites', { mode: 'before' }],
['enabled', 'satellites', false],
]);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
test('a Satellites action the person took still gets its parameters back when Satellites is busy', async () => {
const r = satelliteRig({ enabledBefore: false });
r.state._dataManager.waitForLayerIdle = async () => false;
r.state._satelliteStateBeforeMission.restoreVisibility = false;
await r.ingestion.restoreSatelliteDependency();
assert.deepEqual(r.calls, [['params', 'satellites', { mode: 'before' }]]);
assert.equal(r.state._satelliteStateBeforeMission, null);
});
+1 -1
View File
@@ -135,7 +135,7 @@ export function createOverlays({ state: layerState, services, parts, source }) {
protected: selected,
paintLane: selected ? 'selected' : 'ambient-label',
collisionGroup: 'ambient-label',
interactive: false,
interactive: true,
distanceScale: {
near: 1000,
nearValue: 1.08,
+8 -2
View File
@@ -380,14 +380,20 @@ export function createPanel({ state: layerState, services, parts, source }) {
function scheduleMissionRosterPreview(index) {
const launch = layerState._launches[index];
if (!launch || layerState._selectedLaunchId) return;
// Once the layer is going off (its Satellites restore may still be
// running) hovering or focusing a roster row moves no camera.
if (!launch || layerState._selectedLaunchId || !layerState._enabled) return;
if (layerState._missionRosterHoverTimer)
clearTimeout(layerState._missionRosterHoverTimer);
layerState._hoveredRosterLaunchId = launch.id;
parts.overlays.syncMissionOverlayEntries();
layerState._missionRosterHoverTimer = setTimeout(() => {
layerState._missionRosterHoverTimer = null;
if (layerState._hoveredRosterLaunchId !== launch.id) return;
if (
layerState._hoveredRosterLaunchId !== launch.id ||
!layerState._enabled
)
return;
const currentLaunch = resolveMissionRosterPreviewLaunch(
layerState._launches,
launch.id,
+24
View File
@@ -9,6 +9,7 @@ function fixture() {
const state = createState({
services: { overlays: {}, render: {} },
});
state._enabled = true;
const calls = [];
const parts = {
overlays: {
@@ -194,3 +195,26 @@ test('the panel commands act on the selected mission', () => {
['select', null, undefined],
]);
});
test('a roster row hovered or focused while the layer goes off moves no camera', async () => {
const { state, panel, calls } = fixture();
state._launches = [launch('a'), launch('b')];
panel.createMissionPanel();
panel.renderMissionRoster();
// Hovered just before the layer goes off: the pending preview is dropped.
panel.commands.rosterPointerEnter(0);
state._enabled = false;
await new Promise((resolve) => setTimeout(resolve, 160));
// Hovered or focused after it went off, while the panel still shows.
panel.commands.rosterPointerEnter(1);
panel.commands.rosterFocus(1);
assert.equal(state._missionRosterHoverTimer, null, 'no preview is pending');
await new Promise((resolve) => setTimeout(resolve, 160));
assert.deepEqual(
calls.filter(([name]) => name === 'preview'),
[],
);
panel.clearMissionPanel();
});
+10
View File
@@ -2,6 +2,9 @@ import { TWO_PI, toRadians } from '../../geo/vector.js';
export const WINDOW_DAYS = 30;
/** Longest Space Missions waits for pending Satellites work to settle. */
export const SATELLITE_SETTLE_TIMEOUT_MS = 30000;
export const ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID = 'rocket-missions';
export const ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID =
@@ -100,3 +103,10 @@ export const TRAJECTORY_STAGE_COLORS = [
'#ffd166',
'#60a5fa',
];
/** Whether the cockpit view is on; it holds the camera while it is. */
export function cockpitActive() {
return Boolean(
globalThis.document?.body?.classList?.contains?.('cockpit-mode'),
);
}
+2
View File
@@ -336,6 +336,8 @@ export function createReplay({ state: layerState, services, parts, source }) {
// The chase camera moves on the frame loop; without one, no replay.
const frame = findFrame(layerState._viewer);
if (!layerState._viewer || !launch || !track || !frame) return false;
// Not while the layer is going off.
if (!layerState._enabled) return false;
if (layerState._replayCameraLaunchId === launchId) {
stopMissionReplay();
return false;
+156
View File
@@ -0,0 +1,156 @@
/**
* Space Missions owns its Satellites dependency. While the layer is on or
* starting, an explicit Satellites action from the person (a Data Layers
* click, a voice command) wins over the dependency:
* - the mission teardown leaves Satellites as that action set it, and
* - a Satellites OFF asked for after the newest Space Missions ON ends Space
* Missions, which cannot replay without it.
* Whether an OFF ends the missions depends on which of the two was asked for
* first, not on which settles first, so request order is recorded when each
* intent is published.
*/
const ORDERED_REQUEST_LAYER_IDS = new Set(['rocket-launches', 'satellites']);
const LAYER_ID = 'rocket-launches';
function isExplicitOrigin(origin) {
return origin === 'user' || origin === 'voice';
}
/**
* A setting changed on purpose: by the person, by voice, or by a tool such
* as a place search (the layer state's own rule, isExplicitLayerStateOrigin
* in src/data/layerState.js).
*/
function isDeliberateOrigin(origin) {
return isExplicitOrigin(origin) || origin === 'tool';
}
export function createSatelliteIntents({ state: layerState }) {
const requestOrder = new Map();
let sequence = 0;
let unsubscribe = null;
/** The Space Missions stop a Satellites OFF started, while it runs. */
let pendingStop = null;
/**
* Whether an accepted Satellites OFF was requested after the newest Space
* Missions ON. An OFF asked for before the entry belongs to the view the
* entry started from, so the entry it races with is kept. Without request
* records the OFF is treated as the newer action.
*/
function offFollowsMissionsEntry(change) {
const satellites = requestOrder.get('satellites');
const missions = requestOrder.get(LAYER_ID);
if (satellites?.intentEpoch !== change.intentEpoch || !missions?.enabled)
return true;
return satellites.sequence > missions.sequence;
}
function recordRequest(change) {
if (!ORDERED_REQUEST_LAYER_IDS.has(change?.layerId)) return;
requestOrder.set(change.layerId, {
enabled: change.enabled,
intentEpoch: change.intentEpoch,
sequence: ++sequence,
});
}
/**
* Hand an explicit Satellites action its visibility while Space Missions is
* on or starting.
* @returns {Promise<boolean>|boolean} Whether Space Missions was asked to stop.
*/
function handleVisibility(change) {
const manager = layerState._dataManager;
if (
!manager ||
change?.type !== 'visibility' ||
change.layerId !== 'satellites' ||
!isExplicitOrigin(change.origin)
)
return false;
const missionsRequested = manager.isEffectivelyEnabled(LAYER_ID);
if (!missionsRequested && !layerState._satelliteStateBeforeMission)
return false;
// A newer Satellites request is queued; it will report for itself.
if (manager.isEffectivelyEnabled('satellites') !== change.enabled)
return false;
// The person's choice survives the mission teardown.
const previous = layerState._satelliteStateBeforeMission;
if (previous) previous.restoreVisibility = false;
if (
change.enabled ||
!missionsRequested ||
!offFollowsMissionsEntry(change)
)
return false;
const stop = Promise.resolve(
manager.setEnabled(LAYER_ID, false, { origin: change.origin }),
)
.then(() => true)
.catch((error) => {
console.warn(
'[Data:RocketLaunches] Satellites OFF could not stop Space Missions',
error,
);
return false;
})
.finally(() => {
if (pendingStop === stop) pendingStop = null;
});
pendingStop = stop;
return stop;
}
/**
* Keep a Satellites setting changed on purpose while Space Missions holds
* its saved state ("show orbits" off, tracking a satellite, or a place
* search that stops tracking): it survives the mission teardown, as a
* visibility choice does.
*/
function handleParams(change) {
if (
change?.type !== 'params' ||
change.layerId !== 'satellites' ||
!isDeliberateOrigin(change.origin)
)
return;
const previous = layerState._satelliteStateBeforeMission;
const requested = change.requestedParams;
if (!previous || !requested || typeof requested !== 'object') return;
previous.params = { ...previous.params, ...requested };
}
/** Settle once a Satellites OFF has finished stopping Space Missions. */
function settled() {
return pendingStop ?? Promise.resolve(false);
}
/** Follow the manager the layer is attached to; null detaches. */
function connect(manager) {
unsubscribe?.();
unsubscribe = null;
requestOrder.clear();
if (!manager) return;
const unsubscribeRequests =
manager.subscribeVisibilityRequests?.(recordRequest) ?? null;
const unsubscribeChanges =
manager.subscribe?.((change) => {
handleParams(change);
void handleVisibility(change);
}) ?? null;
unsubscribe = () => {
unsubscribeRequests?.();
unsubscribeChanges?.();
};
}
return {
connect,
settled,
handleVisibility,
handleParams,
recordRequest,
offFollowsMissionsEntry,
};
}
@@ -0,0 +1,167 @@
// An explicit Satellites action while Space Missions is on or starting.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createSatelliteIntents } from './satelliteIntents.js';
/** A manager whose effective and settled state can differ. */
function rig({ effective, snapshot = { enabled: false } } = {}) {
const calls = [];
const listeners = { requests: new Set(), changes: new Set() };
const manager = {
isEffectivelyEnabled: (id) => Boolean(effective[id]),
async setEnabled(id, enabled, options) {
calls.push([id, enabled, options?.origin]);
return true;
},
subscribeVisibilityRequests(listener) {
listeners.requests.add(listener);
return () => listeners.requests.delete(listener);
},
subscribe(listener) {
listeners.changes.add(listener);
return () => listeners.changes.delete(listener);
},
};
const state = {
_dataManager: manager,
_satelliteStateBeforeMission: snapshot,
};
const intents = createSatelliteIntents({ state });
intents.connect(manager);
const request = (layerId, enabled, intentEpoch) => {
for (const listener of listeners.requests)
listener({
type: 'visibility-requested',
layerId,
enabled,
intentEpoch,
});
};
const settle = (change) => {
for (const listener of listeners.changes) listener(change);
};
return { calls, intents, listeners, manager, state, request, settle };
}
const satellitesOff = {
type: 'visibility',
layerId: 'satellites',
enabled: false,
origin: 'user',
intentEpoch: 7,
};
test('a Satellites OFF asked for after the mission start ends Space Missions', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('rocket-launches', true, 3);
r.request('satellites', false, 7);
r.settle(satellitesOff);
assert.equal(await r.intents.settled(), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
false,
'the teardown leaves Satellites as the person set it',
);
});
test('a Satellites OFF asked for before the mission start leaves the start alone', () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.request('satellites', false, 7);
r.request('rocket-launches', true, 3);
r.settle(satellitesOff);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('a Satellites OFF without request records is treated as the newer action', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
assert.equal(await r.intents.handleVisibility(satellitesOff), true);
assert.deepEqual(r.calls, [['rocket-launches', false, 'user']]);
});
test('a superseded Satellites event is left to the newer request', () => {
// A newer Satellites ON is queued, but this OFF has already settled.
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
});
test('a Satellites ON while the missions are on is kept through their exit', () => {
const r = rig({ effective: { satellites: true, 'rocket-launches': true } });
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, enabled: true }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(r.state._satelliteStateBeforeMission.restoreVisibility, false);
});
test('only direct user and voice Satellites actions count', () => {
// Settled: a scene, story, preset or other programmatic Satellites OFF
// neither ends Space Missions nor survives its teardown.
for (const origin of [
'programmatic',
'context-restore',
'dependency',
'scene',
'tool',
]) {
const r = rig({
effective: { satellites: false, 'rocket-launches': true },
});
assert.equal(
r.intents.handleVisibility({ ...satellitesOff, origin }),
false,
);
assert.deepEqual(r.calls, []);
assert.equal(
r.state._satelliteStateBeforeMission.restoreVisibility,
undefined,
);
}
const voice = rig({
effective: { satellites: false, 'rocket-launches': true },
});
voice.settle({ ...satellitesOff, origin: 'voice' });
assert.deepEqual(voice.calls, [['rocket-launches', false, 'voice']]);
});
test('with Space Missions off, a Satellites action is not its business', () => {
const r = rig({ effective: { satellites: false }, snapshot: null });
assert.equal(r.intents.handleVisibility(satellitesOff), false);
assert.deepEqual(r.calls, []);
});
test('reconnecting and detaching release each manager subscription', () => {
const r = rig({ effective: {} });
assert.equal(r.listeners.requests.size, 1);
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(r.manager);
assert.equal(r.listeners.requests.size, 1, 'no duplicate subscription');
assert.equal(r.listeners.changes.size, 1);
r.intents.connect(null);
assert.equal(r.listeners.requests.size, 0);
assert.equal(r.listeners.changes.size, 0);
});
test('a failed stop is reported, not thrown', async () => {
const r = rig({ effective: { satellites: false, 'rocket-launches': true } });
r.manager.setEnabled = async () => {
throw new Error('injected stop failure');
};
const warn = console.warn;
const warnings = [];
console.warn = (...args) => warnings.push(args);
try {
assert.equal(await r.intents.handleVisibility(satellitesOff), false);
} finally {
console.warn = warn;
}
assert.equal(warnings.length, 1);
assert.equal(await r.intents.settled(), false, 'nothing left pending');
});
+13 -3
View File
@@ -11,7 +11,11 @@ import {
toRadians,
vec,
} from '../../geo/vector.js';
import { MISSION_GLOBE_VIEW_RANGE_M, MISSION_FOCUS_RANGE_M } from './policy.js';
import {
MISSION_GLOBE_VIEW_RANGE_M,
MISSION_FOCUS_RANGE_M,
cockpitActive,
} from './policy.js';
import { cameraOf, canvasOf, findCamera } from '../../render/rendererOf.js';
export function createSelection({
@@ -66,6 +70,9 @@ export function createSelection({
}
function setSelectedMission(launchId, isolate = true) {
// Once the layer is going off (its Satellites restore may still be
// running) a roster click selects nothing and moves no camera.
if (launchId && !layerState._enabled) return;
if (launchId) parts.panel.clearMissionRosterHover();
if (
layerState._replayCameraLaunchId &&
@@ -118,7 +125,10 @@ export function createSelection({
}
function focusMission(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
// The cockpit holds the camera: a mission chosen there, by its label,
// its dot or the layer row's arrows, is selected without flying to it.
if (cockpitActive()) return;
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
const camera = cameraOf(layerState._viewer);
@@ -163,7 +173,7 @@ export function createSelection({
}
function focusLaunchSite(launch) {
if (!layerState._viewer || !launch) return;
if (!layerState._viewer || !launch || !layerState._enabled) return;
parts.replay.stopMissionReplay();
stopMissionZoomAnchor();
parts.rendering.selectLaunchEntity(launch.id);
+5 -2
View File
@@ -1,4 +1,5 @@
import { worldClock, worldTimeFor } from '../../time/worldClock.js';
import { SATELLITE_SETTLE_TIMEOUT_MS } from './policy.js';
export function createState({ services }) {
const { setOverlayEntries, setOverlaySourceVisible, clearOverlaySource } =
@@ -20,8 +21,6 @@ export function createState({ services }) {
state._lastError = null;
state._lastErrorAt = null;
state._entryCameraView = null;
state._entryLandedView = null;
@@ -53,6 +52,9 @@ export function createState({ services }) {
state._lifecycleToken = 0;
/** Bound on waiting for pending Satellites work around a mission. */
state.satelliteSettleTimeoutMs = SATELLITE_SETTLE_TIMEOUT_MS;
state._enabled = false;
state._selectedLaunchId = null;
@@ -68,6 +70,7 @@ export function createState({ services }) {
state._missionPanelSignature = null;
state._missionPanelListeners = new Set();
state._globePickListeners = new Set();
state._missionRosterView = null;
+24 -1
View File
@@ -36,10 +36,14 @@ function scene(t) {
],
};
const viewer = { scene: {} };
const flights = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: {
pose: () => ({ position: { x: 2e7, y: 0, z: 0 } }),
on: () => () => {},
flyTo: (...args) => flights.push(args),
lookAt: noop,
release: noop,
},
});
t.after(unbind);
@@ -69,6 +73,7 @@ function scene(t) {
};
parts.selection = createSelection({ state, services, parts });
const rendering = createRendering({ state, services, parts });
parts.rendering = rendering;
rendering.attach(viewer);
rendering.showMissions(true);
rendering.addLaunchEntity(launch, null);
@@ -88,7 +93,7 @@ function scene(t) {
path: item(`rocket-trajectory:${launch.id}:0`).show,
};
};
return { state, rendering, launch, syncs, shown, draw };
return { state, rendering, launch, syncs, shown, draw, parts, flights };
}
test('live shows every launch in the window, lifted off or not', (t) => {
@@ -127,3 +132,21 @@ test('the live orbit rings turn at the frame time, not the wall clock', (t) => {
);
assert.deepEqual(orbits.spec.motionClock, { kind: 'scene' });
});
test('in the cockpit a chosen mission is not flown to', (t) => {
const { launch, parts, flights } = scene(t);
const previous = Object.getOwnPropertyDescriptor(globalThis, 'document');
Object.defineProperty(globalThis, 'document', {
configurable: true,
value: {
body: { classList: { contains: (name) => name === 'cockpit-mode' } },
},
});
try {
parts.selection.focusMission(launch);
} finally {
if (previous) Object.defineProperty(globalThis, 'document', previous);
else delete globalThis.document;
}
assert.deepEqual(flights, [], 'the cockpit keeps the camera');
});
+2 -1
View File
@@ -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 || ''),
};
}
+32 -10
View File
@@ -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);
@@ -684,6 +703,9 @@ export function createLocalAdsbLayer({
if (clickSubscription || !viewer) return;
clickSubscription = inputFor(viewer).onClick((event) => {
if (!enabled) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (services.picking.isUnderOtherCard?.(event)) return;
const target = clickTarget(event);
// Clicking a local aircraft always (re)selects it and republishes its
// card, including the one already selected: its card may have been
+141 -11
View File
@@ -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,
@@ -14,9 +15,14 @@ import {
} from './index.js';
import { createLocalAdsbModels } from './models.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { resolvePickId } from '../../data/pickRegistry.js';
import {
isUnderOtherCard,
resolvePickId,
setClickCardHitTest,
} from '../../data/pickRegistry.js';
import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { inputFor } from '../../input/dispatcher.js';
import { MISSION_LABEL, fakeInput } from '../../input/testDoubles.mjs';
import { hexColor } from '../../render/color.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
@@ -196,13 +202,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 +245,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 +272,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 +301,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 };
@@ -1133,7 +1179,8 @@ function iconPick(draw, id) {
return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } };
}
/** A viewer with a canvas and scripted picks, plus the layer's click action. */
/** A viewer with a canvas and scripted picks, plus the layer's click action.
* A click drills through the viewer's `drillHits`. */
function clickHarness() {
const scene = {
canvas: {},
@@ -1141,6 +1188,8 @@ function clickHarness() {
pick() {
return scene.pickResult;
},
drillPick: () =>
(base.viewer.drillHits ?? []).map((hit) => ({ primitive: {}, id: hit })),
};
const base = fakeViewer({ scene });
return {
@@ -1172,6 +1221,41 @@ test('clicking the selected aircraft keeps it selected and republishes its card'
assert.deepEqual(calls.cleared, []);
});
// The card or label painted on top takes the click: a local aircraft under
// another layer's card is neither selected nor released.
test("another layer's card over a local aircraft keeps the click", async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const harness = clickHarness();
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer,
services: {
picking: {
registerPickOwner() {},
unregisterPickOwner() {},
resolvePickId,
isUnderOtherCard,
},
},
});
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
harness.click();
assert.deepEqual(calls.selected, [], 'covered: not selected');
top = null;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
harness.scene.pickResult = null;
harness.click();
assert.deepEqual(calls.cleared, [], 'covered: the selection stays');
});
test('a click on a local aircraft under an unowned or trail pick still selects it', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
@@ -1224,6 +1308,52 @@ test('a click on a local aircraft under an unowned or trail pick still selects i
assert.equal(calls.selected.length, 2, 'the Flights contact is not taken');
});
test('a click on a mission label over a local aircraft never selects the aircraft, and keeps the selection', async (t) => {
const receiver = fakeReceiver({ mode: 'adsb', connected: true });
const clock = { now: 100_000 };
const harness = clickHarness();
// A Space Missions label painted over the map: while it is over, it takes
// each click and is the card on top.
const label = { over: true };
setClickCardHitTest(() => (label.over ? MISSION_LABEL : null));
t.after(() => setClickCardHitTest(null));
const { layer, calls, draw } = await enabledLayer(receiver, clock, null, {
viewer: harness.viewer,
services: {
picking: {
registerPickOwner() {},
unregisterPickOwner() {},
resolvePickId,
isUnderOtherCard,
},
},
});
t.after(() => layer.destroy());
receiver.set({ aircraft: [record()] });
await layer.update();
inputFor(harness.viewer.viewer).onOverlayClick(() => label.over);
const model = {
set: layerSet(draw, ':models').spec.id,
id: 'local-adsb:abc123',
surface: false,
};
// The aircraft is under the label, both exactly and in the drill.
harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123');
harness.viewer.viewer.drillHits = [model];
harness.click();
assert.deepEqual(calls.selected, [], 'the aircraft beneath is not taken');
// Off the label the same click selects it; the label on top is its own
// click, so the selection stays.
label.over = false;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
label.over = true;
harness.click();
assert.deepEqual(calls.selected, ['local-adsb:abc123']);
assert.equal(calls.cleared.length, 0, 'the selection stays');
});
test('a grounded aircraft changing type keeps its drawn model on its own belly offset until the new one is ready', () => {
const { draw, viewer, camera } = modelViewer();
const models = createLocalAdsbModels({
+43 -11
View File
@@ -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;
+54 -1
View File
@@ -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 };
}
+14 -4
View File
@@ -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(
+26 -5
View File
@@ -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');
+180
View File
@@ -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']);
});
+18 -11
View File
@@ -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,
+46
View File
@@ -3,6 +3,8 @@ import assert from 'node:assert/strict';
import { createMilitaryFlightLayer } from './index.js';
import { createFlightState } from './state.js';
import { createTracking } from './tracking.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
function services() {
const names = [
@@ -294,3 +296,47 @@ test('a military layer without an icon set declines contact refreshes', () => {
assert.equal(layer.refreshTr3b('abc123'), false);
assert.equal(layer.trackById('abc123'), false);
});
// The card or label painted on top takes the click: an aircraft under another
// layer's card is not even picked, so it is neither tracked nor released.
test("another layer's card over an aircraft keeps the click", (t) => {
const previousDocument = globalThis.document;
globalThis.document = Object.assign(new EventTarget(), {
body: { classList: { contains: () => false } },
});
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const flightState = createFlightState({ services: services() });
flightState._trackedEntityChangedRemove = () => {};
const tracking = createTracking({
flightState,
services: { ...services(), picking },
parts: {},
layer: {},
});
tracking._installClickHandler(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
picking.setClickCardHitTest(() => top);
t.after(() => {
picking.setClickCardHitTest(null);
flightState._clickSubscription?.();
input.destroy();
flightState.lifetime.abort();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+27 -34
View File
@@ -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`). */
+5 -4
View File
@@ -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' } = {}) {
+4 -11
View File
@@ -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;
}
+38 -10
View File
@@ -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 &&
+12
View File
@@ -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
+13 -6
View File
@@ -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),
};
}
+74 -32
View File
@@ -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,
@@ -87,7 +86,8 @@ export function createTracking({
const { clearFocusTarget } = services.focus;
const { FOLLOW_MIN_RANGE_M, SELECTION_FOLLOW_TRANSITION_S, followViewFrom } =
services.camera;
const { resolvePickId, isOwnedByOtherLayer } = services.picking;
const { resolvePickId, isOwnedByOtherLayer, isUnderOtherCard } =
services.picking;
/** The tracked contact's billboard (an icon set on the draw port). */
const trackedIcon = createTrackedAircraftIcon({
viewer: () => flightState._viewer,
@@ -212,11 +212,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 +308,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 +410,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 +614,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 +670,7 @@ export function createTracking({
if (
!flightState._trackedIcao ||
!flightState._trailFixes.length ||
parts.motion._isTrackWarmingUp()
_trailWarmingUp()
)
return [];
const head =
@@ -661,7 +698,7 @@ export function createTracking({
trailHeadCurvePoints(
flightState._trailFixes,
flightState._trailBodyCount,
flightState.now() - displayDelayMs(flightState),
_trailDisplayMs(),
),
end,
parts.motion._trackedModelCenterWorld(),
@@ -926,10 +963,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 +1082,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 +1096,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,
@@ -1191,6 +1230,9 @@ export function createTracking({
// first-person reference. Empty globe clicks are inert until the user
// exits with C, Escape, or the dedicated button.
if (document.body.classList.contains('cockpit-mode')) return;
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard?.(event)) return;
const picked = event.hit;
if (picked) {
Loaded 100 of 1463 files, more files were not shown because too many files have changed in this diff. Show more