Merge main through #1556 into the renderer seam

Brings in fire intensity and the draped heatmap (#1426), provider labels
(#1521), Rio transit (#1481), chat autocomplete and provider switching
(#1561, #1546) and Cockpit entry by the ridden layer alone (#1556).

What main added that reached Cesium or the viewer:
- The fires heatmap drapes as one image through the globe port's imagery
  (heatImagery.js), above the port's other imagery, and drapes again when
  the map stack's surface changes. The far bands no longer draw heat
  rectangles; the layer's shape set stays as its initialized marker and
  the visibility the context store reads.
- The hand-off between heatmap and markers fades the glow icons' own
  alpha and the icon set's visibility. Markers keep their glows across
  rebuilds; the set culls the horizon itself.
- A double-click on the followed track enters the Cockpit through the
  input dispatcher. The renderer's own double-click follow would let go
  of the track first and cannot be refused from a subscriber, so a press
  on the followed track holds that behaviour off for the press.
- Cockpit entry and the ridden layer read the follow service; the camera
  takes its eye offsets from a profile.
This commit is contained in:
Sameh Khamis committed 2026-11-09 20:52:52 -08:00
commit 823b5dc301
119 files changed
+5782 -577

No files matched your search

+1
View File
@@ -23,6 +23,7 @@ export function createControls({ state: layerState, services, parts, source }) {
attachDataManager(dataManager) {
layerState.dataManager = dataManager;
parts.dependencies.watchAdoptions(dataManager);
},
setParams(params = {}) {
+20
View File
@@ -79,6 +79,25 @@ export function createDependencies({
});
}
/**
* Give up a dependency the user adopts. A direct selection, or the Cockpit
* riding one of its aircraft, promotes a layer Contacts turned on into the
* user's own (`DataLayerManager.adoptLayerVisibility`). Releasing it when
* Contacts goes off would tear down that track or Cockpit before the
* Context restore could put the layer back.
*/
function relinquishAdoptedDependency(change) {
if (change?.type === 'visibility' && change.adopted && change.enabled)
layerState.ownedDependencies.delete(change.layerId);
}
/** Follow one manager's adoptions; null stops following. */
function watchAdoptions(dataManager) {
layerState.unwatchAdoptions?.();
layerState.unwatchAdoptions =
dataManager?.subscribe?.(relinquishAdoptedDependency) || null;
}
function activateOperationalContext() {
const activationId = ++layerState.activationId;
layerState.autoFocusRetryPending = false;
@@ -113,6 +132,7 @@ export function createDependencies({
refreshAfterDeferredDependency,
enableDependencies,
releaseOwnedDependencies,
watchAdoptions,
activateOperationalContext,
};
}
+1
View File
@@ -348,6 +348,7 @@ export function createLifecycle({
layerState.clearListener = null;
layerState.subjectClearListener = null;
layerState.viewer = null;
parts.dependencies.watchAdoptions(null);
layerState.dataManager = null;
},
};
+1
View File
@@ -196,6 +196,7 @@ export function createModel({ state: layerState, services, parts, source }) {
id: cohort.id,
label: cohort.label,
source: cohort.source,
sourceStatus: cohort.sourceStatus || null,
coverage: cohort.coverage || null,
relationship: cohort.summary.relationship,
count: cohort.summary.count,
+2 -1
View File
@@ -8,6 +8,7 @@ import {
t,
translateKnown,
} from '../../i18n/index.js';
import { sourceStatusLabel } from '../../ui/layerNames.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js';
import { distanceParts } from '../../data/distanceFormat.js';
@@ -150,7 +151,7 @@ export function createPanel({ state: layerState, parts }) {
relationship: summary.relationship.toLowerCase(),
label: cohort.label,
count: `${presentAwarenessCount(summary)}${pageLabel}`,
detail: `${cohort.source}${coverage} · ${presentAwarenessReason(summary)}`,
detail: `${sourceStatusLabel(cohort.source, cohort.sourceStatus)}${coverage} · ${presentAwarenessReason(summary)}`,
nearest,
};
}
+38
View File
@@ -0,0 +1,38 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createPanel } from './panel.js';
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
const cohort = (id, source, sourceStatus) => ({
id,
label: id,
source,
sourceStatus,
summary: { relationship: 'OBSERVED', count: 1, nearest: [], reason: 'observed' },
});
const state = {
enabled: true,
results: {
subject: { label: 'AFR38JF' },
cohorts: [
cohort('flights', 'adsb.lol', 'fallback'),
cohort('military', 'adsb.lol', null),
cohort('ais-live-vessels', 'Datalastic', 'stale'),
],
},
cohortPages: new Map(),
panelListeners: new Set(),
panelSignature: '',
navigationIndex: 0,
};
const parts = {
navigation: { canNavigateNext: () => false },
rendering: { hideDirectionOverlay() {} },
};
createPanel({ state, parts }).renderResults();
assert.deepEqual(
state.panelView.rows.map((row) => row.detail),
['adsb.lol · FALLBACK · observed', 'adsb.lol · observed', 'Datalastic · STALE · observed'],
);
state.offPanelLocale?.();
});
+1
View File
@@ -91,6 +91,7 @@ export function createQueries({ state: layerState, services, parts, source }) {
stats.count ?? null,
stats.status || null,
stats.error || null,
stats.source || null,
];
})
.map((parts) => parts.join(':'))
+26
View File
@@ -81,3 +81,29 @@ test('Contacts excludes square corners and measures from the current moving subj
assert.equal(moved.reason, 'mapped matches within 100 km of the subject');
assert.deepEqual(installationState.contextAnchor, { latitude: 0, longitude: 0 });
});
test('Contacts cohorts carry the provider and whether it answered as a fallback or stale', () => {
const services = { installations: { getNearby: () => [], getStats: () => ({}) },
flights: { getNearby: () => [] }, military: { getNearby: () => [] }, vessels: { getNearby: () => [] } };
const parts = { navigation: { summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source) } };
parts.queries = createQueries({ state: {}, services, parts });
const subjectOwner = createSubject({ state: {}, services, parts });
const states = {
// The OpenSky proxy answers from adsb.lol when OpenSky fails.
flights: { available: true, stats: { source: 'adsb.lol', coverage: '250nm regional fallback', count: 4, lastUpdate: 1 } },
military: { available: true, stats: { source: 'adsb.lol', fallback: false, count: 2, lastUpdate: 1 } },
'ais-live-vessels': { available: true, stats: { source: 'Datalastic', stale: true, count: 3, lastUpdate: 1 } },
'military-installations': { available: true, stats: { coverage: { kind: 'subject', radiusM: 100000 } } },
};
const { cohorts } = subjectOwner.evaluateSubject({
id: 'subject', layerId: 'flights', position: Cesium.Cartesian3.fromDegrees(0, 0, 10000),
}, states);
const byId = Object.fromEntries(cohorts.map((cohort) => [cohort.id, cohort]));
assert.equal(byId.flights.source, 'adsb.lol');
assert.equal(byId.flights.sourceStatus, 'fallback');
assert.equal(byId.military.sourceStatus, null);
assert.equal(byId['ais-live-vessels'].source, 'Datalastic');
assert.equal(byId['ais-live-vessels'].sourceStatus, 'stale');
assert.equal(byId['military-installations'].sourceStatus, null);
});
@@ -0,0 +1,159 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createQueries } from './queries.js';
import { createSubject } from './subject.js';
import { createModel } from './model.js';
import { summarizeAwarenessCohort } from '../../data/militaryAwarenessEngine.js';
import { layerFeedState } from '../../data/feedState.js';
import aisLiveVesselsLayer, {
_setVesselStateForTest,
_beginAisSessionForTest,
_applyAisFeedSnapshotForTest,
_setAisRuntimeForTest,
} from '../../data/aisLiveVessels.js';
test('a poll that returns the same stale AIS snapshot restores STALE on Contacts cohorts', () => {
globalThis.document ??= { body: null };
const services = {
installations: { getNearby: () => [], getStats: () => ({}) },
flights: { getNearby: () => [] },
military: { getNearby: () => [] },
vessels: { getNearby: () => [] },
};
const layerState = {
enabled: true,
passive: true,
sourceRevision: '',
cohortPages: new Map(),
subject: {
id: 'site-1',
layerId: 'military-installations',
label: 'Site',
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
};
let states;
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {} },
};
const realQueries = createQueries({ state: layerState, services, parts });
parts.queries = { ...realQueries, collectSourceStates: () => states };
parts.model = createModel({ state: layerState, services, parts });
const subject = createSubject({ state: layerState, services, parts });
const flights = (lastUpdate) => ({
available: true, enabled: true, stale: false,
stats: { source: 'OpenSky Network', count: 4, lastUpdate },
});
const vessels = (loading) => ({
available: true, enabled: true, stale: true,
stats: { source: 'Datalastic', stale: true, count: 3, lastUpdate: 1000, loading },
});
const rest = {
military: { available: true, enabled: true, stale: false, stats: { source: 'adsb.lol', fallback: false, count: 1, lastUpdate: 1 } },
'military-installations': { available: true, enabled: true, stale: false, stats: { coverage: { kind: 'subject', radiusM: 100000 } } },
};
const ais = () => layerState.results.cohorts.find((c) => c.id === 'ais-live-vessels');
// 1. Stale AIS cache, nothing loading.
states = { flights: flights(1), 'ais-live-vessels': vessels(false), ...rest };
subject.refreshSelectedSubject(true);
assert.equal(ais().sourceStatus, 'stale');
// 2. AIS re-poll in flight while the flights poll lands (revision changes).
states = { flights: flights(2), 'ais-live-vessels': vessels(true), ...rest };
subject.refreshSelectedSubject();
assert.equal(ais().sourceStatus, 'stale', 'a poll in flight keeps the snapshot stale');
// 3. AIS poll returns the same stale snapshot; only loading flips back.
states = { flights: flights(2), 'ais-live-vessels': vessels(false), ...rest };
subject.refreshSelectedSubject();
subject.refreshSelectedSubject();
assert.equal(ais().sourceStatus, 'stale', 'Layers reads STALE again; Contacts/Cockpit must too');
});
function fakeRuntime() {
return {
now: () => 1000,
setTimeout: () => ({}),
clearTimeout() {},
};
}
test('first AIS connect (no snapshot yet) carries no STALE on the Contacts cohort', () => {
globalThis.document ??= { body: null };
_setAisRuntimeForTest(fakeRuntime());
_setVesselStateForTest({ viewer: {}, records: [] });
try {
_beginAisSessionForTest();
// What server/providers/vessels/ais-live.js answers while its socket connects.
_applyAisFeedSnapshotForTest({}, {
rows: [], source: 'AISStream', status: 'connecting', refreshing: true,
});
const vesselStats = aisLiveVesselsLayer.getStats();
assert.equal(vesselStats.loading, true);
assert.equal(vesselStats.stale, true);
assert.equal(vesselStats.lastUpdate, null);
assert.equal(layerFeedState(vesselStats), 'loading', 'Layers chip reads LOADING');
const flightsStats = { source: 'OpenSky Network', count: 2, lastUpdate: 5 };
const militaryStats = { source: 'adsb.lol', fallback: false, count: 1, lastUpdate: 5 };
const installStats = { coverage: { kind: 'subject', radiusM: 100000 } };
const statsById = {
flights: flightsStats,
military: militaryStats,
'ais-live-vessels': vesselStats,
'military-installations': installStats,
};
const services = {
installations: { getNearby: () => [], getStats: () => installStats },
flights: { getNearby: () => [] },
military: { getNearby: () => [] },
vessels: aisLiveVesselsLayer,
};
const layerState = {
enabled: true,
passive: true,
sourceRevision: '',
cohortPages: new Map(),
dataManager: {
isEnabled: () => true,
getLayerLifecycleState: () => ({ enabled: true, lifecycleState: 'enabled' }),
layers: new Map(Object.entries(statsById).map(([id, s]) => [id, { module: { getStats: () => s } }])),
},
subject: {
id: 'site-1',
layerId: 'military-installations',
label: 'Site',
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
};
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) => summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {} },
};
parts.queries = createQueries({ state: layerState, services, parts });
parts.model = createModel({ state: layerState, services, parts });
const subject = createSubject({ state: layerState, services, parts });
const vesselsSource = parts.queries.collectSourceStates()['ais-live-vessels'];
assert.equal(vesselsSource.available, false, 'never-answered source is unavailable');
subject.refreshSelectedSubject(true);
const ais = layerState.results.cohorts.find((c) => c.id === 'ais-live-vessels');
assert.equal(ais.sourceStatus, null, 'no snapshot yet: no STALE label, Layers says LOADING');
} finally {
_setVesselStateForTest({ enabled: false });
_setAisRuntimeForTest();
}
});
+2
View File
@@ -12,6 +12,8 @@ export function createState({ services }) {
// layers activate only after Contacts is explicitly selected.
passive: true,
ownedDependencies: new Set(),
/** Stops following the manager's adoptions (see watchAdoptions). */
unwatchAdoptions: null,
subject: null,
results: null,
visual: null,
+17
View File
@@ -3,6 +3,7 @@ import {
AWARENESS_RADIUS_M,
AWARENESS_RELATIONSHIP,
} from '../../data/militaryAwarenessEngine.js';
import { layerFeedState } from '../../data/feedState.js';
import { t } from '../../i18n/index.js';
import { clone, distance, fromDegrees } from '../../geo/index.js';
import {
@@ -55,6 +56,18 @@ export function createSubject({ state: layerState, services, parts, source }) {
const vesselsState = sourceStates['ais-live-vessels'];
const installationsState = sourceStates['military-installations'];
const evaluatedAt = Date.now();
// A poll in flight keeps FALLBACK or STALE: the revision key ignores loading.
// Before the first answer there is no snapshot, so loading stays.
const sourceStatus = (sourceState) => {
const feedState = layerFeedState(
sourceState.available
? { ...sourceState.stats, loading: false }
: sourceState.stats,
);
return feedState === 'fallback' || feedState === 'stale'
? feedState
: null;
};
const retainedProvenance = (id, label, sourceState, fallbackSource) => {
const retainedSource = sourceState.stats.source || fallbackSource;
return {
@@ -97,6 +110,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'flights',
label: t('Flights'),
source: flightsState.stats.source || SOURCE_LABEL.flights,
sourceStatus: sourceStatus(flightsState),
provenance: retainedProvenance(
'flights',
'Flights',
@@ -116,6 +130,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'military',
label: t('Military flights'),
source: militaryState.stats.source || SOURCE_LABEL.military,
sourceStatus: sourceStatus(militaryState),
provenance: retainedProvenance(
'military',
'Military flights',
@@ -135,6 +150,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'ais-live-vessels',
label: t('AIS vessels'),
source: vesselsState.stats.source || SOURCE_LABEL['ais-live-vessels'],
sourceStatus: sourceStatus(vesselsState),
provenance: retainedProvenance(
'ais-live-vessels',
'AIS vessels',
@@ -152,6 +168,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
source:
installationsState.stats.source ||
SOURCE_LABEL['military-installations'],
sourceStatus: sourceStatus(installationsState),
provenance: retainedProvenance(
'military-installations',
'Mapped installations',
+84 -80
View File
@@ -5,6 +5,7 @@ import { createFirmsHeatmapLayer } from '../../data/firmsHeatmap.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeGlobePort } from '../../testSupport/fakeGlobePort.mjs';
// Ports built over a viewer of the test's own, with no renderer bound: the
// adapter's factories load as `./render/cesium/unbound` loads them.
import '../../render/cesium/unbound.js';
@@ -22,13 +23,15 @@ const raw = (lat, lon, frp) => ({
satellite: 'N20',
});
/** Enough canvas for the glow sprites. */
/** Enough canvas for the glow sprites and the heat raster. */
const canvasStub = () => ({
width: 0,
height: 0,
getContext: () => ({
createRadialGradient: () => ({ addColorStop() {} }),
fillRect() {},
createImageData: (w, h) => ({ data: new Uint8ClampedArray(w * h * 4) }),
putImageData() {},
}),
toDataURL: () => 'data:image/png;base64,iVBORw0KGgo=',
});
@@ -73,13 +76,20 @@ function harness(fires, heightM, { sceneFromViewer = false } = {}) {
},
},
};
const ports = bindFakeCesiumScene(viewer);
let ports = bindFakeCesiumScene(viewer);
const { draw } = ports;
// The heatmap drapes through the globe port.
const globe = fakeGlobePort();
{
const { unbind, ...bound } = ports;
unbind();
ports = { ...bound, unbind: bindRenderer(viewer, { ...bound, globe }) };
}
// A renderer with no query or frame: the Cesium adapter builds them over
// the viewer's scene, as it does for a viewer with no renderer.
if (sceneFromViewer) {
ports.unbind();
bindRenderer(viewer, { draw, camera: ports.camera });
bindRenderer(viewer, { draw, camera: ports.camera, globe });
Object.assign(viewer.scene, {
preUpdate: new Cesium.Event(),
postRender: new Cesium.Event(),
@@ -103,10 +113,16 @@ function harness(fires, heightM, { sceneFromViewer = false } = {}) {
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(':cells'),
);
const icons = () =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(':icons'),
);
return {
layer,
viewer,
cells,
icons,
globe,
cleanup() {
layer.destroy(viewer);
input.destroy();
@@ -118,100 +134,88 @@ function harness(fires, heightM, { sceneFromViewer = false } = {}) {
};
}
test('far out, the heat cells are clamped rectangles in one draw set, shown with the layer', async () => {
/** Put the camera at `heightM` and run a frame past the LOD check's throttle. */
function moveTo(h, heightM) {
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
heightM,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
heightM,
);
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
try {
h.viewer.scene.preRender.raiseEvent();
} finally {
performance.now = now;
}
}
test('far out, one heatmap is draped through the globe port and the markers under it are hidden', async () => {
const h = harness(
[raw(30.5, -98.2, 1500), raw(30.6, -98.3, 20), raw(-12.1, 131.4, 5)],
12_000_000,
);
try {
h.layer.init(h.viewer);
assert.equal(h.cells().show, false, 'hidden until enabled');
await h.layer.enable(h.viewer);
const cells = h.cells();
assert.equal(cells.show, true);
assert.equal(cells.spec.clampTo, 'both');
const items = [...cells.items.values()];
// Global band: 2° cells; the two Texas fires share one.
assert.equal(items.length, 2);
const texas = items.find((item) => item.geometry.rect.west === -100);
assert.deepEqual(texas.geometry, {
kind: 'rectangle',
rect: { west: -100, south: 30, east: -98, north: 32 },
assert.equal(h.cells().items.size, 0, 'no heat rectangles any more');
const [heat] = h.globe.imagery.list();
assert.equal(h.globe.imagery.list().length, 1);
assert.equal(heat.spec.kind, 'single-image');
assert.deepEqual(heat.spec.rectangle, {
west: -180,
south: -90,
east: 180,
north: 90,
});
assert.equal(texas.height, 'clampGround');
// The hottest cell: red at the top of the alpha ramp.
assert.deepEqual(texas.fill, [1, 0, 0, 0.66]);
const other = items.find((item) => item !== texas);
assert.equal(other.fill.length, 4);
assert.ok(other.fill[3] >= 0.16 && other.fill[3] < 0.66);
assert.equal(heat.show, true);
assert.equal(heat.alpha, 1, 'past the hand-off: all heat');
// The nearest band's markers stay built for the hand-off, hidden.
assert.equal(h.icons().items.size, 3);
assert.equal(h.icons().show, false);
h.layer.disable();
assert.equal(h.cells().show, false, 'hidden with the layer');
assert.equal(heat.show, false, 'hidden with the layer');
h.layer.destroy(h.viewer);
assert.equal(h.cells(), undefined, 'destroy disposes the set');
assert.equal(h.globe.imagery.list().length, 0, 'destroy takes it down');
assert.equal(h.icons(), undefined);
} finally {
h.cleanup();
}
});
test('close in, detections replace the cells', async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000);
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
assert.equal(h.cells().items.size, 1);
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
500_000,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
500_000,
);
// A frame past the LOD check's throttle, however fast the start was.
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
for (const sceneFromViewer of [false, true]) {
const title = sceneFromViewer
? "with no query or frame port, the layer still follows the camera through ports built over the viewer's scene"
: 'zooming in cross-fades the heatmap out and the markers in';
test(title, async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000, {
sceneFromViewer,
});
try {
h.viewer.scene.preRender.raiseEvent();
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
const [heat] = h.globe.imagery.list();
assert.equal(heat.alpha, 1);
assert.equal(h.icons().show, false);
// Half way through the hand-off (3,600 to 5,400 km): both show.
moveTo(h, 4_500_000);
assert.equal(heat.alpha, 0.5);
assert.equal(h.icons().show, true);
assert.equal([...h.icons().items.values()][0].alpha, 0.5);
// Close in: markers alone; the heatmap stays mapped at alpha 0.
moveTo(h, 500_000);
assert.equal(heat.alpha, 0);
assert.equal(heat.show, true);
assert.equal(h.icons().show, true);
assert.equal([...h.icons().items.values()][0].alpha, 1);
} finally {
performance.now = now;
h.cleanup();
}
assert.equal(h.cells().items.size, 0, 'no cells in a detections band');
} finally {
h.cleanup();
}
});
test("with no query or frame port, the layer still follows the camera through ports built over the viewer's scene", async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000, {
sceneFromViewer: true,
});
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
assert.equal(h.cells().items.size, 1);
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
500_000,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
500_000,
);
// A frame past the LOD check's throttle, however fast the start was.
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
try {
h.viewer.scene.preRender.raiseEvent();
} finally {
performance.now = now;
}
assert.equal(h.cells().items.size, 0, 'no cells in a detections band');
} finally {
h.cleanup();
}
});
}
+112
View File
@@ -0,0 +1,112 @@
/**
* Drapes the Active Fires heat raster over the globe as one full-extent
* image on the renderer's imagery (`globe.imagery`, the globe port), like
* the wind layer's scalar field. It drapes on whatever the map stack draws
* (the globe's surface, or the 3D tiles). Owns the canvas and the imagery
* layer; nothing else in the fires layer touches imagery.
*
* `show` is only for the layer being on or off. The zoom hand-off fades
* `alpha` instead: a renderer may unmap a hidden imagery layer from the
* surface and re-map it when shown, so a show toggle at the band edge left
* a beat with neither markers nor heat. At alpha 0 the layer stays mapped
* and costs no draw.
*/
const WORLD = Object.freeze({ west: -180, south: -90, east: 180, north: 90 });
/**
* Drawn over the port's other imagery, the weather layers included
* (`WEATHER_IMAGERY_Z` tops out at 4): each drape went to the top of the
* stack.
*/
export const HEAT_IMAGERY_Z = 5;
const defaultCanvas = (width, height) => {
const canvas = document.createElement('canvas');
canvas.width = width;
canvas.height = height;
return canvas;
};
/**
* @param {object} options
* @param {() => {globe: object|null, kind: string}|null} options.getHost
* Where draped imagery goes now: the renderer's globe port, and the kind
* of surface the active map stack drapes on (`'none'`: nothing to drape
* on, so nothing is draped).
* @param {(width: number, height: number) => object} [options.createCanvas]
*/
export function createHeatImagery({ getHost, createCanvas = defaultCanvas }) {
let raster = null;
let layer = null;
/** The host the layer is draped on: its globe port and kind. */
let globe = null;
let kind = 'none';
let show = true;
let opacity = 1;
const hostNow = () => {
const host = getHost?.();
return host?.globe && host.kind !== 'none'
? host
: { globe: null, kind: 'none' };
};
function detach() {
layer?.remove();
layer = null;
globe = null;
kind = 'none';
}
function attach() {
detach();
if (!raster) return;
const host = hostNow();
if (!host.globe) return;
const canvas = createCanvas(raster.width, raster.height);
const ctx = canvas.getContext('2d');
const image = ctx.createImageData(raster.width, raster.height);
image.data.set(raster.rgba);
ctx.putImageData(image, 0, 0);
layer = host.globe.imagery.add({
kind: 'single-image',
url: canvas.toDataURL('image/png'),
rectangle: WORLD,
zOrder: HEAT_IMAGERY_Z,
});
globe = host.globe;
kind = host.kind;
layer.show = show;
layer.alpha = opacity;
}
return {
setRaster(next) {
raster = next;
attach();
},
/** True once a raster was handed over (painted or waiting for a host). */
hasRaster() {
return raster !== null;
},
setShow(value) {
show = Boolean(value);
if (layer) layer.show = show;
},
/** Hand-off fade, 0..1; the layer stays mapped at 0. */
setOpacity(value) {
opacity = Math.min(1, Math.max(0, Number(value) || 0));
if (layer) layer.alpha = opacity;
},
/** Drape again when the map stack's surface has changed. */
rehome() {
const host = hostNow();
if (host.globe !== globe || host.kind !== kind) attach();
},
destroy() {
detach();
raster = null;
},
};
}
+148
View File
@@ -0,0 +1,148 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createHeatImagery } from './heatImagery.js';
import { buildHeatRaster } from '../../data/firmsHeatRaster.js';
import { HEAT_RASTER } from './policy.js';
function harness() {
const layers = [];
const removed = [];
// The renderer's globe port, reduced to its imagery.
const globe = {
imagery: {
add(spec) {
const layer = {
spec,
show: true,
alpha: 1,
remove() {
layers.splice(layers.indexOf(layer), 1);
removed.push(layer);
},
};
layers.push(layer);
return layer;
},
},
};
let host = { globe, kind: 'globe' };
const createCanvas = (w, h) => ({
width: w,
height: h,
getContext: () => ({
createImageData: (cw, ch) => ({
data: new Uint8ClampedArray(cw * ch * 4),
}),
putImageData() {},
}),
toDataURL: () => 'data:image/png;base64,AAAA',
});
const imagery = createHeatImagery({
getHost: () => host,
createCanvas,
});
return {
imagery,
layers,
removed,
globe,
setHost: (h) => (host = h),
};
}
const raster = { width: 4, height: 2, rgba: new Uint8ClampedArray(32) };
test('setRaster drapes one full-globe tile and replaces it on the next build', () => {
const h = harness();
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 1);
assert.equal(h.layers[0].spec.kind, 'single-image');
assert.deepEqual(h.layers[0].spec.rectangle, {
west: -180,
south: -90,
east: 180,
north: 90,
});
assert.equal(h.layers[0].spec.url, 'data:image/png;base64,AAAA');
assert.equal(h.layers[0].spec.zOrder, 5, 'over the other imagery');
const first = h.layers[0];
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 1, 'never two heat layers');
assert.deepEqual(h.removed, [first]);
});
test('setShow toggles without rebuilding', () => {
const h = harness();
h.imagery.setRaster(raster);
const layer = h.layers[0];
h.imagery.setShow(false);
assert.equal(layer.show, false);
h.imagery.setShow(true);
assert.equal(h.layers[0], layer);
assert.equal(layer.show, true);
});
test('setOpacity fades the same layer and survives a rebuild', () => {
const h = harness();
h.imagery.setRaster(raster);
const layer = h.layers[0];
h.imagery.setOpacity(0);
assert.equal(layer.alpha, 0);
assert.equal(layer.show, true, 'a faded layer stays mapped');
h.imagery.setOpacity(0.25);
assert.equal(h.layers[0], layer);
assert.equal(layer.alpha, 0.25);
h.imagery.setRaster(raster);
assert.equal(h.layers[0].alpha, 0.25, 'a rebuilt layer keeps the fade');
h.imagery.setOpacity(7);
assert.equal(h.layers[0].alpha, 1);
});
test('no imagery host keeps nothing draped; rehome brings it back', () => {
const h = harness();
h.setHost({ globe: h.globe, kind: 'none' });
h.imagery.setRaster(raster);
assert.equal(h.layers.length, 0);
h.setHost({ globe: h.globe, kind: 'globe' });
h.imagery.rehome();
assert.equal(h.layers.length, 1);
// The same surface: nothing is draped again.
const kept = h.layers[0];
h.imagery.rehome();
assert.equal(h.layers[0], kept);
// The map stack moves to 3D tiles: draped again, once.
h.setHost({ globe: h.globe, kind: 'tileset' });
h.imagery.rehome();
assert.equal(h.layers.length, 1);
assert.notEqual(h.layers[0], kept);
});
test('destroy removes the layer', () => {
const h = harness();
h.imagery.setRaster(raster);
h.imagery.destroy();
assert.equal(h.layers.length, 0);
});
test('the shipped raster paints a lone weak fire as a distinct spot', () => {
// A hot cluster elsewhere sets the scale, as Africa does on real data.
const fires = [{ lat: 0, lon: 0, frp: 5 }];
for (let i = 0; i < 40; i++) {
fires.push({ lat: -10 + (i % 5) * 0.1, lon: 25 + i * 0.05, frp: 300 });
}
const r = buildHeatRaster(fires, HEAT_RASTER);
const y = Math.floor((90 / 180) * r.height);
const painted = [];
for (let x = 0; x < r.width; x++) {
const lon = ((x + 0.5) / r.width) * 360 - 180;
if (Math.abs(lon) < 5 && r.rgba[(y * r.width + x) * 4 + 3] > 0) {
painted.push(x);
}
}
const kmPerPx = 40075 / r.width;
assert.ok(painted.length > 0, 'the weak fire still shows');
assert.ok(
painted.length * kmPerPx <= 100,
`spot ${Math.round(painted.length * kmPerPx)} km wide`,
);
});
+44
View File
@@ -0,0 +1,44 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
test('reenabling an empty filtered layer never reveals the retained pre-filter heat raster', async () => {
let shown = false;
const noop = () => {};
const layerState = {
_enabled: false,
_viewer: {},
_cells: {},
_fires: [],
_loading: true,
_pickIndexById: new Map(),
_heatImagery: {
setShow(v) {
shown = v;
},
},
};
const lifecycle = createLifecycle({
layerState,
services: {
picking: { registerPickOwner: noop, unregisterPickOwner: noop },
sprites: { restoreSpriteOrderOnEnable: noop },
context: { clearSelectedEntityContextForLayer: noop },
},
config: { id: 'local-firms', overlayHost: { setVisible: noop } },
components: {
rendering: { applyHandoffFade: noop },
viewport: { installLodWatcher: noop, installMoveEndWatcher: noop },
selection: { installClickHandler: noop },
},
});
await lifecycle.methods.enable(layerState._viewer);
assert.equal(
shown,
false,
'empty current set must keep the old raster hidden while refresh is pending',
);
layerState._fires = [{ frp: null, confidence: null }];
await lifecycle.methods.enable(layerState._viewer);
assert.equal(shown, true, 'nonempty sets still resume their raster');
});
+28 -5
View File
@@ -1,5 +1,6 @@
import { adaptFirmsRecords } from '../../data/firmsAdapt.js';
import { fireDetectionKey } from '../../data/firmsLabels.js';
import { filterFires } from '../../data/firmsIntensity.js';
import { msg } from '../../i18n/index.js';
export function createIngestion({
@@ -40,12 +41,13 @@ export function createIngestion({
layerState._stale = Boolean(payload?.stale);
const previousSelection = layerState._selectedFire;
layerState._selectedFire = null;
layerState._fires = adaptFirmsRecords(payload?.fires);
layerState._cellCacheByGrid.clear(); // aggregation is per-dataset — new fires, new cells
layerState._firesByFrp = [...layerState._fires].sort(
layerState._allFires = adaptFirmsRecords(payload?.fires);
// Sorted once per payload; applyFilter only filters, so a slider drag
// over 200k detections never re-sorts.
layerState._allFiresByFrp = [...layerState._allFires].sort(
(a, b) => b.frp - a.frp,
);
layerState._count = layerState._fires.length;
applyFilter();
// Data age, not response age: a stale proxy payload truthfully reads old.
layerState._lastUpdate = Number.isFinite(payload?.fetchedAt)
? payload.fetchedAt
@@ -65,6 +67,7 @@ export function createIngestion({
}
components.rendering.renderCurrentLod(true);
if (reselected) components.selection.selectFire(reselected, false);
layerState._rowControlsListener?.();
} catch (error) {
if (
request.signal.aborted ||
@@ -83,6 +86,26 @@ export function createIngestion({
}
}
/**
* Run the intensity filter over the loaded payload. This is the ONE place
* the shown set is derived: `_fires` / `_firesByFrp` feed markers, cards,
* the heatmap, the context store, the top-fires query and the analyst
* records, so none of them can disagree about which fires exist. Cells and
* the heat raster are built per shown set, so their caches go with it.
*/
function applyFilter() {
layerState._fires = filterFires(layerState._allFires, layerState._filter);
layerState._cellCacheByGrid.clear();
layerState._heatRaster = null;
layerState._firesByFrp = filterFires(
layerState._allFiresByFrp,
layerState._filter,
);
layerState._count = layerState._fires.length;
layerState._totalCount = layerState._allFires.length;
}
/**
* Find the record in the freshly-loaded set matching a previous selection.
* Identity is the detection itself (lat/lon/acquisition time) — indices
@@ -109,5 +132,5 @@ export function createIngestion({
},
};
return { loadHeatmap, findMatchingFire, methods };
return { loadHeatmap, applyFilter, findMatchingFire, methods };
}
+31 -1
View File
@@ -2,7 +2,7 @@ import { drawOf } from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
/**
* The heat cells' draw sets start with this; each layer has its own
* The layer's shape sets start with this; each layer has its own
* (`firms:1:cells`, …), so several can share a renderer.
*/
export const FIRMS_CELL_SET_PREFIX = 'firms';
@@ -20,6 +20,20 @@ export function createLifecycle({
const { id, overlayHost } = config;
const methods = {
/**
* Shell services: `imageryHost()` resolves where draped imagery goes on
* the active map stack (globe or 3D tiles, src/maps/imageryHost.js). The
* heatmap moves with it; without a host it drapes on viewer.imageryLayers.
* @param {{imageryHost?: () => {collection: ?Object, kind: string}}|null} services
*/
attachShellServices(services) {
layerState._imageryHost =
typeof services?.imageryHost === 'function'
? services.imageryHost
: null;
layerState._heatImagery?.rehome();
},
init(viewer) {
if (layerState._destroyed) return;
layerState._viewer = viewer;
@@ -40,6 +54,10 @@ export function createLifecycle({
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
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);
// The camera can have crossed the hand-off while the layer was off.
components.rendering.applyHandoffFade(true);
components.viewport.installLodWatcher();
components.viewport.installMoveEndWatcher();
components.selection.installClickHandler();
@@ -58,6 +76,7 @@ export function createLifecycle({
components.selection.clearFireSelection();
if (layerState._cells) layerState._cells.show = false;
if (layerState._icons) layerState._icons.show = false;
layerState._heatImagery?.setShow(false);
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
clearSelectedEntityContextForLayer(id);
@@ -83,10 +102,21 @@ export function createLifecycle({
components.rendering.removeDetectionCollections(viewer);
components.selection.clearContextRegistrations();
clearSelectedEntityContextForLayer(id);
layerState._allFires = [];
layerState._allFiresByFrp = [];
layerState._fires = [];
layerState._firesByFrp = [];
layerState._cellCacheByGrid.clear();
clearTimeout(layerState._heatRebuildTimer);
layerState._heatRebuildTimer = null;
layerState._heatImagery?.destroy();
layerState._heatImagery = null;
layerState._heatRaster = null;
layerState._handoffHeat = -1;
layerState._imageryHost = null;
layerState._count = 0;
layerState._totalCount = 0;
layerState._rowControlsListener = null;
layerState._cellCount = 0;
layerState._lastUpdate = null;
layerState._keyRequired = false;
+43 -27
View File
@@ -13,6 +13,7 @@ import {
accentForSeverity,
formatFrpMw,
} from '../../data/firmsLabels.js';
import { FRP_RAMP, frpRampStop } from '../../data/firmsIntensity.js';
import {
VIEW_PADDING,
DETECTION_COLOR_STOPS,
@@ -127,27 +128,30 @@ export function createModel({
);
}
/** A cell's heat colour, `[r, g, b, alpha]`, on the detection stops. */
function heatColor(value, alpha) {
const stop = DETECTION_COLOR_STOPS[value > 0.72 ? 0 : value > 0.42 ? 1 : 2];
return [stop.color[0], stop.color[1], stop.color[2], alpha];
/**
* The ramp stop for a fire radiative power (stepped, weakest first).
* Intensity alone drives the color: confidence feeds the card text and the
* switch, brightness is unreliable (saturates at 367 K) — see HAL-675.
* @param {number} frp - Megawatts.
* @returns {{name: string, minFrp: number, color: number[]}}
*/
function frpColorStop(frp) {
const name = frpRampStop(frp).name;
return (
DETECTION_COLOR_STOPS.find((stop) => stop.name === name) ||
DETECTION_COLOR_STOPS[0]
);
}
/**
* Pick a sprite color stop from FRP + confidence, reusing the same
* yellow → orange → red thresholds as the aggregated heat cells.
* Pick a sprite color stop for one detection from its FRP on the shared ramp.
* @param {Object} fire - Detection record.
* @returns {{name: string, color: number[]}}
*/
function detectionColorStop(fire) {
const heat = Math.min(
1,
Math.sqrt(Math.max(0, fire.frp) / 150) * 0.85 + fire.confidence * 0.15,
);
if (heat > 0.72) return DETECTION_COLOR_STOPS[0];
if (heat > 0.42) return DETECTION_COLOR_STOPS[1];
return DETECTION_COLOR_STOPS[2];
return frpColorStop(fire?.frp);
}
/** FRP → core marker pixel size, clamped to 8..28px. */
@@ -234,6 +238,19 @@ export function createModel({
return fire.position;
}
/**
* The anchor already built for a detection, without the floor lookup;
* for the far marker band, where floors are never warmed and the height
* difference is invisible, so tens of thousands of markers skip a cache
* read each per rebuild. Builds one through {@link firePosition} once.
* @param {Object} fire - Detection record.
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function fireBuiltPosition(fire) {
return fire.position ?? firePosition(fire);
}
/**
* Occlusion-test anchor for one detection. Returns the render position
* outright for anchors comfortably above the ellipsoid (the common case) and
@@ -245,11 +262,11 @@ export function createModel({
* feeds rendering: the datum-correct anchor from {@link firePosition} is what
* the sprite and the card are drawn at.
* @param {Object} fire - Detection record.
* @param {{x: number, y: number, z: number}} [position] Its render anchor, if at hand.
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function fireCullPosition(fire) {
const position = firePosition(fire);
function fireCullPosition(fire, position = firePosition(fire)) {
if (fire.positionHeight >= ICON_CULL_HEIGHT_M) return position;
if (!fire.cullPosition) {
fire.cullPosition = fromDegrees(fire.lon, fire.lat, ICON_CULL_HEIGHT_M);
@@ -365,8 +382,8 @@ export function createModel({
/**
* Card model for an aggregated heat cell, e.g. title "14 FIRES", detail
* "max 210 MW · new 3h". Accent comes from the candidate (heat-normalized
* score is only known at renderCells time). Exported for unit tests.
* "max 210 MW · new 3h". Accent comes from the candidate (renderHeat sets
* it with {@link cellCardAccent}). Exported for unit tests.
* @param {{cell: Object, position: {x: number, y: number, z: number}, accent: string}} candidate
* @param {number} nowMs - Current epoch milliseconds.
* @returns {Object} firmsLabels entry.
@@ -384,7 +401,7 @@ export function createModel({
position: candidate.position,
cullPosition: candidate.cullPosition || candidate.position,
gapPx: 10,
accent: candidate.accent || accentForSeverity('yellow'),
accent: candidate.accent || accentForSeverity(FRP_RAMP[0].name),
// The count picks the plural form of the language ("حريقان (2)",
// "14 حريقًا", "14 ПОЖАРОВ"); the card shows it in capitals like the
// other card titles.
@@ -431,16 +448,14 @@ export function createModel({
}
/**
* Heat-normalized cell score → severity accent, mirroring heatColor's
* red/orange/yellow thresholds.
* @param {number} normalized - 0..1 normalized heat score.
* Cell card accent: the cell's strongest fire on the FRP ramp, the same
* color its markers take once the camera is close enough to show them.
* @param {{maxFrp?: number}} cell - Aggregated cell.
* @returns {string} "r, g, b" accent string.
*/
function cellAccent(normalized) {
if (normalized > 0.72) return accentForSeverity('red');
if (normalized > 0.42) return accentForSeverity('orange');
return accentForSeverity('yellow');
function cellCardAccent(cell) {
return accentForSeverity(frpColorStop(cell?.maxFrp ?? 0).name);
}
/** Coordinate line like "30.512°N 75.831°E". */
@@ -546,12 +561,13 @@ export function createModel({
boundsContainPoint,
cellIntersectsBounds,
heatScore,
heatColor,
frpColorStop,
detectionColorStop,
frpPixelSize,
sizeBucket,
glowSprite,
firePosition,
fireBuiltPosition,
fireCullPosition,
cellCullPosition,
screenSeparated,
@@ -559,7 +575,7 @@ export function createModel({
buildFireCard,
buildCellCard,
applyFirmsOverlayPolicy,
cellAccent,
cellCardAccent,
formatLatLon,
formatFrp,
formatAge,
+57 -14
View File
@@ -1,13 +1,16 @@
import { FIRMS_AMBIENT_COHORT_LIMIT } from '../../data/firmsLabels.js';
import { FRP_RAMP } from '../../data/firmsIntensity.js';
import { cssColor } from '../../render/color.js';
/** Client poll interval; the proxy's 30 min TTL is what guards upstream quota. */
export const REFRESH_INTERVAL_MS = 600_000;
/**
* LOD bands keyed by camera height. `cells` bands render aggregated
* ground-clamped heat rectangles; `detections` bands (< ~750km plus the
* local band) render individual fire detections as glow-sprite icons.
* LOD bands keyed by camera height. `heat` bands (above ~4,500 km) drape a
* Snap Map–style heatmap over the globe (firmsHeatRaster.js); their
* `gridDegrees` aggregation only feeds the "N FIRES" cards. `detections`
* bands render individual fire detections as glow-sprite icons.
* Labels in every band go through the shared screen-space greedy declutter
* (hard cap MAX_AMBIENT_LABELS) — there are no per-band label knobs.
*/
@@ -16,24 +19,28 @@ export const LOD_LEVELS = [
{
id: 'global',
minHeight: 9000000,
mode: 'cells',
mode: 'heat',
gridDegrees: 2.0,
maxCells: 1800,
labelDistance: 12000000,
},
{
id: 'regional',
minHeight: 3000000,
mode: 'cells',
minHeight: 4500000,
mode: 'heat',
gridDegrees: 1.0,
maxCells: 3600,
labelDistance: 8500000,
},
{
// Up to 40,000 markers: at the 3,600 km end of the hand-off the padded
// view over Africa, the densest region, holds ~40,000 detections, and a
// tighter cap left the heatmap's weak spots dissolving into nothing.
// A rebuild of that many costs ~60 ms, only there.
id: 'local',
minHeight: 750000,
mode: 'detections',
maxDetections: 2500,
maxDetections: 40000,
labelDistance: 4500000,
},
{
@@ -45,6 +52,38 @@ export const LOD_LEVELS = [
},
];
/**
* Global heat raster for the `heat` bands: ≈0.09° (≈10 km) per pixel and a
* one-pixel Gaussian σ, so a lone fire is a spot about the size of its
* marker near the hand-off and the two cross-fade without a jump;
* neighbours merge only when they nearly touch (σ 3 on a 2048 grid smeared
* each fire over ~200 km). Built once per data refresh or filter change,
* never per camera move.
*/
export const HEAT_RASTER = Object.freeze({
width: 4096,
height: 2048,
sigmaPx: 1,
});
/**
* Camera heights, in metres, over which the heatmap and the markers
* cross-fade around the 4,500 km band edge: markers alone below `from`,
* heatmap alone above `to`. Wider than the ±10 % band hysteresis, so
* whichever band is active inside it, both layers are already built.
*/
export const HANDOFF_FADE = Object.freeze({ from: 3_600_000, to: 5_400_000 });
/**
* Trailing delay before a stale heatmap is rebuilt while one is already on
* screen: a slider drag fires many filter changes, and a build plus PNG
* encode costs a few hundred milliseconds. The first paint is immediate.
*/
export const HEAT_REBUILD_MS = 150;
export const LOD_CHECK_MS = 650;
/** +/-10% hysteresis on LOD band edges so slow zooms don't thrash rebuilds. */
@@ -80,12 +119,16 @@ export const LABEL_VIEW_MARGIN_PX = 16;
export const GLOW_SPRITE_PX = 56;
/**
* Color stops shared by cell heat fills and detection glow sprites, as
* renderer colours `[r, g, b, a]` (CSS red, orange and yellow).
* Color stops for detection glow sprites and card accents: the
* six-stop ember → white-hot FRP ramp (firmsIntensity.js), weakest first, as
* renderer colours `[r, g, b, a]`. Stop names key the glow-sprite cache and
* the card accents.
*/
export const DETECTION_COLOR_STOPS = [
{ name: 'red', color: Object.freeze([1, 0, 0, 1]) },
{ name: 'orange', color: Object.freeze([1, 165 / 255, 0, 1]) },
{ name: 'yellow', color: Object.freeze([1, 1, 0, 1]) },
];
export const DETECTION_COLOR_STOPS = FRP_RAMP.map((stop) =>
Object.freeze({
name: stop.name,
minFrp: stop.minFrp,
color: Object.freeze(cssColor(stop.hex)),
}),
);
+161 -2
View File
@@ -1,6 +1,18 @@
import { fireDetectionKey } from '../../data/firmsLabels.js';
import { t } from '../../i18n/index.js';
import { REFRESH_INTERVAL_MS } from './policy.js';
import {
FIRMS_CONFIDENCE_MODES,
FRP_SLIDER_TICKS,
firePassesFilter,
frpForSliderPosition,
normalizeFireFilter,
rampTrackGradient,
sliderPositionForFrp,
} from '../../data/firmsIntensity.js';
import { formatNumber, t } from '../../i18n/index.js';
import { LOD_LEVELS, REFRESH_INTERVAL_MS } from './policy.js';
/** Slider resolution: whole-percent positions along the log axis. */
const SLIDER_STEPS = 1000;
export function createQueries({
layerState,
@@ -11,6 +23,25 @@ export function createQueries({
}) {
const { id, name, icon, source } = config;
/** Whole-megawatt label for a slider value or tick ("0", "20", "1 000"). */
function frpLabel(frp) {
return formatNumber(frp, { maximumFractionDigits: 0 });
}
const confidenceLabels = () => ({
all: t('All', { context: 'fire confidence filter' }),
nominal: t('Nominal+', { context: 'fire confidence filter' }),
high: t('High', { context: 'fire confidence filter' }),
});
const confidenceTitles = () => ({
all: t(
'Every detection — many of the strongest fires are rated low confidence',
),
nominal: t('Nominal and high confidence detections'),
high: t('High confidence detections only'),
});
const methods = {
/** Return the selected detection as a plain record for application consumers. */
getSelectedInfo() {
@@ -51,6 +82,110 @@ export function createQueries({
// not this interval — is what protects the upstream FIRMS quota).
updateInterval: REFRESH_INTERVAL_MS,
/**
* The intensity filter as layer options (share token `w`, owner
* `local-firms` in layerState.js).
* @returns {{minFrp: number, confidence: string}}
*/
getParams() {
return { ...layerState._filter };
},
/**
* Apply a (partial) intensity filter. Invalid fields keep their current
* value. The filter runs in one place (ingestion.applyFilter) and the LOD
* rebuild re-derives markers, cells, cards and context registrations from
* the shown set; a selected fire that no longer passes is deselected.
* @param {{minFrp?: number, confidence?: string}} params
* @returns {boolean} True — the request is always accepted.
*/
setParams(params = {}) {
const next = normalizeFireFilter(params, layerState._filter);
if (
next.minFrp === layerState._filter.minFrp &&
next.confidence === layerState._filter.confidence
)
return true;
layerState._filter = next;
if (!layerState._allFires.length) return true;
components.ingestion.applyFilter();
if (
layerState._selectedFire &&
!firePassesFilter(layerState._selectedFire, next)
) {
components.selection.clearFireSelection();
}
if (layerState._enabled) components.rendering.renderCurrentLod(true);
layerState._rowControlsListener?.();
return true;
},
/**
* Row controls under the Active Fires row: the log-scale minimum-FRP
* slider whose track is painted with the intensity ramp (so it doubles as
* the legend), the All / Nominal+ / High confidence switch, and the
* "N of M shown" counter.
*/
getRowControls() {
const { minFrp, confidence } = layerState._filter;
const labels = confidenceLabels();
const titles = confidenceTitles();
const shown = layerState._count;
const total = layerState._totalCount;
return {
slider: {
id: 'min-frp',
label: t('Fire intensity (FRP)'),
ariaLabel: t('Minimum fire radiative power, megawatts'),
valueText:
minFrp > 0
? t('≥ {value} MW', { value: frpLabel(minFrp) })
: t('All', { context: 'fire intensity filter' }),
min: 0,
max: SLIDER_STEPS,
step: 1,
value: Math.round(sliderPositionForFrp(minFrp) * SLIDER_STEPS),
track: rampTrackGradient(),
ticks: FRP_SLIDER_TICKS.map((frp) => ({
at: sliderPositionForFrp(frp),
label: frpLabel(frp),
})),
params: (value) => ({
minFrp: frpForSliderPosition(Number(value) / SLIDER_STEPS),
}),
},
segmented: {
id: 'confidence',
label: t('Confidence'),
ariaLabel: t('Detection confidence'),
options: FIRMS_CONFIDENCE_MODES.map((mode) => ({
id: `confidence-${mode}`,
label: labels[mode],
title: titles[mode],
active: mode === confidence,
params: { confidence: mode },
})),
},
info: total
? t('{shown} of {total} shown', {
shown: formatNumber(shown),
total: formatNumber(total),
})
: '',
};
},
/**
* Install the panel's "row controls changed" callback: a load or a filter
* change moves the counter, and nothing else repaints the row before the
* next scheduled refresh.
* @param {(() => void)|null} listener
*/
setRowControlsListener(listener) {
layerState._rowControlsListener =
typeof listener === 'function' ? listener : null;
},
/**
* Layer stats for the data panel. Degraded feed states surface through
* `error` (established qa-failstate pattern: a dead feed must never look
@@ -84,7 +219,9 @@ export function createQueries({
});
}
return {
// Shown (filtered) detections; `total` is the loaded payload.
count: layerState._count,
total: layerState._totalCount,
cells: layerState._cellCount,
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
@@ -173,12 +310,34 @@ export function createQueries({
return result;
},
/** Test seam: render one named LOD band against a near-global view. */
_renderLodForTest(lodId) {
components.rendering.renderBand(
LOD_LEVELS.find((level) => level.id === lodId),
null,
);
},
/** Test seam: one frame of the hand-off fade at the current camera. */
_applyHandoffFadeForTest() {
components.rendering.applyHandoffFade();
},
/** Test seam: shapes drawn in the layer's own set (none: the heat is imagery). */
_entityCountForTest() {
return layerState._cells?.size() ?? 0;
},
/** Test seam that binds the production click path and indexes. */
_bindInteractionForTest(viewer, fires = []) {
layerState._viewer = viewer;
layerState._enabled = true;
layerState._allFires = fires;
layerState._allFiresByFrp = [...fires];
layerState._fires = fires;
layerState._firesByFrp = [...fires];
layerState._count = fires.length;
layerState._totalCount = fires.length;
layerState._pickIndexById.clear();
layerState._labelLodDistance = 1e7;
components.rendering.ensureDetectionCollections();
+233 -108
View File
@@ -1,11 +1,31 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf, findFrame, findQuery } from '../../render/rendererOf.js';
import {
drawOf,
findFrame,
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { LOD_LEVELS, CONTEXT_TOP_N, GLOW_SPRITE_PX } from './policy.js';
import { buildHeatRaster } from '../../data/firmsHeatRaster.js';
import {
LOD_LEVELS,
CONTEXT_TOP_N,
GLOW_SPRITE_PX,
HANDOFF_FADE,
HEAT_RASTER,
HEAT_REBUILD_MS,
} from './policy.js';
import { createHeatImagery } from './heatImagery.js';
/** Icon sets made so far, by every fire layer: set ids unique to each. */
let iconSets = 0;
/** The markers drawn under the far bands' heatmap for the hand-off fade. */
const HANDOFF_MARKER_LOD = LOD_LEVELS.find((lod) => lod.mode === 'detections');
/** Fade steps: a moving camera rewrites marker opacity at most this often. */
const FADE_STEPS = 32;
export function createRendering({
layerState,
services,
@@ -28,6 +48,8 @@ export function createRendering({
function renderCurrentLod(force = false) {
if (!layerState._cells || !layerState._viewer) return false;
if (!layerState._fires.length) {
// A filter that leaves nothing shown must not leave the old heat behind.
layerState._heatImagery?.setShow(false);
// A refresh that came back empty takes down what the last one drew, so
// no sprite or card is left on screen (and clickable) for a fire that is
// gone.
@@ -52,23 +74,68 @@ export function createRendering({
? components.model.paddedDegreeBounds(viewRect)
: null;
if (lod.mode === 'detections') {
renderDetections(lod, bounds);
} else {
renderCells(aggregateFires(lod, bounds), lod, bounds);
}
renderBand(lod, bounds);
return true;
}
/** Take every heat cell down (no write when there are none). */
function clearCells() {
if (layerState._cells?.size()) layerState._cells.clear();
/**
* Draw one band. Markers and heatmap stay built in every band; the
* hand-off only fades between them.
* @param {Object} lod - Band descriptor.
* @param {?Object} bounds - Padded view bounds in degrees, or null.
*/
function renderBand(lod, bounds) {
prepareHeat(lod.mode === 'heat');
if (lod.mode === 'detections') renderDetections(lod, bounds);
else renderHeat(lod, bounds);
applyHandoffFade(true);
}
/** The opacity the drawn glows were last written with. */
let glowAlpha = 1;
/**
* Cross-fade between markers and heatmap by camera height (HANDOFF_FADE),
* on every rendered frame, so a fast zoom never outruns the throttled band
* check. Cheap when nothing changed: one height read and a compare.
* @param {boolean} [force] Reapply, e.g. to freshly added markers.
*/
function applyHandoffFade(force = false) {
const height = components.viewport.cameraHeight();
const t = Math.min(
1,
Math.max(
0,
(height - HANDOFF_FADE.from) / (HANDOFF_FADE.to - HANDOFF_FADE.from),
),
);
const heat = Math.round(t * t * (3 - 2 * t) * FADE_STEPS) / FADE_STEPS;
if (!force && heat === layerState._handoffHeat) return;
layerState._handoffHeat = heat;
layerState._heatImagery?.setOpacity(heat);
// Glows written from here on carry the fade (fireGlow); those already
// drawn are rewritten only when it changed.
const alpha = 1 - heat;
const changed = alpha !== glowAlpha;
glowAlpha = alpha;
const set = layerState._icons;
if (!set) return;
set.show = layerState._enabled && heat < 1;
if (!changed || !drawnGlows.size) return;
const faded = [];
for (const drawn of drawnGlows.values()) {
drawn.glow = { ...drawn.glow, alpha };
faded.push(drawn.glow);
}
set.upsert(faded);
}
/**
* Each drawn glow's detection and anchor, by its item id: what it was last
* written with, so a rebuild writes only the glows that changed.
* @type {Map<string, {fire: object, position: object}>}
* Each drawn glow's detection, anchor and item, by its item id: what it
* was last written with, so a rebuild writes only the glows that changed.
* @type {Map<string, {fire: object, position: object, glow: object}>}
*/
const drawnGlows = new Map();
@@ -80,7 +147,6 @@ export function createRendering({
}
function clearRendered() {
clearCells();
clearIcons();
layerState._pickIndexById.clear();
layerState._cellCount = 0;
@@ -148,63 +214,100 @@ export function createRendering({
return clipped;
}
/** The heat imagery adapter, created on first use. */
function heatImagery() {
if (!layerState._heatImagery) {
layerState._heatImagery = createHeatImagery({
// Draped through the renderer's globe port, on the surface the
// active map stack draws (the shell's imagery host names it; without
// a shell, the globe).
getHost: () => ({
globe: findGlobe(layerState._viewer),
kind: layerState._imageryHost?.()?.kind ?? 'globe',
}),
});
}
return layerState._heatImagery;
}
/** Build the heat raster from the shown set and drape it. */
function rebuildHeatRaster() {
clearTimeout(layerState._heatRebuildTimer);
layerState._heatRebuildTimer = null;
if (layerState._destroyed) return;
layerState._heatRaster = buildHeatRaster(layerState._fires, HEAT_RASTER);
heatImagery().setRaster(layerState._heatRaster);
}
/**
* Render aggregated heat cells (global/regional bands) as ground-clamped
* rectangles, one draw set. Cell labels do NOT live on the cells — they go
* through the same unclamped, screen-space-decluttered label pipeline as
* detections (see {@link rebuildAmbientLabels}).
* @param {Array<Object>} cells - Aggregated cells, heat-sorted descending.
* Make sure the draped heatmap matches the shown set. The first paint in a
* far band is immediate; other builds (filter drags, refreshes, the
* preload under the markers) trail by HEAT_REBUILD_MS and keep the
* previous heatmap on screen meanwhile.
* @param {boolean} now Build at once when nothing is draped yet.
*/
function ensureHeatRaster(now) {
if (layerState._heatRaster) return;
if (now && !heatImagery().hasRaster()) {
rebuildHeatRaster();
return;
}
clearTimeout(layerState._heatRebuildTimer);
layerState._heatRebuildTimer = setTimeout(
rebuildHeatRaster,
HEAT_REBUILD_MS,
);
}
/**
* Keep the heatmap draped on the current map stack and current with the
* shown set in every band; the hand-off fade decides how much of it shows.
* @param {boolean} now The camera is in a far band.
*/
function prepareHeat(now) {
const imagery = heatImagery();
// The map stack may have changed since the last render.
imagery.rehome();
ensureHeatRaster(now);
imagery.setShow(layerState._enabled);
}
/**
* Far bands (global/regional): a Snap Map–style heatmap draped over the
* globe, transparent where nothing burns, plus the decluttered "N FIRES"
* cards from the coarse aggregation. The nearest band's markers are kept
* built underneath for the hand-off fade and hidden once it completes;
* cards go through the same screen-space label pipeline as detections
* (see {@link rebuildAmbientLabels}).
* @param {Object} lod - Active LOD descriptor.
* @param {?Object} bounds - Padded view bounds in degrees, or null.
*/
function renderCells(cells, lod, bounds) {
ensureDetectionCollections();
clearIcons();
layerState._pickIndexById.clear();
layerState._cellCount = cells.length;
const maxScore = Math.max(1, ...cells.map(components.model.heatScore));
function renderHeat(lod, bounds) {
paintMarkers(HANDOFF_MARKER_LOD, bounds);
const cells = aggregateFires(lod, bounds);
layerState._cellCount = cells.length;
layerState._labelCandidates = [];
layerState._labelLodDistance = lod.labelDistance;
const items = [];
// Cells arrive heat-sorted, so candidate order doubles as label priority.
for (const cell of cells) {
const score = components.model.heatScore(cell);
const normalized = Math.min(1, Math.sqrt(score / maxScore));
const alpha = 0.16 + normalized * 0.5;
const color = components.model.heatColor(normalized, alpha);
const centerLon = cell.lonCell + lod.gridDegrees / 2;
const centerLat = cell.latCell + lod.gridDegrees / 2;
const position = fromDegrees(centerLon, centerLat, 0);
items.push({
id: `firms-cell:${lod.gridDegrees}:${cell.latCell}:${cell.lonCell}`,
geometry: {
kind: 'rectangle',
rect: {
west: cell.lonCell,
south: cell.latCell,
east: cell.lonCell + lod.gridDegrees,
north: cell.latCell + lod.gridDegrees,
},
},
fill: color,
height: 'clampGround',
});
// Cells arrive heat-sorted, so candidate order doubles as label priority.
// Accent is resolved here because `normalized` only exists in this walk.
layerState._labelCandidates.push({
position,
position: fromDegrees(centerLon, centerLat, 0),
cullPosition: components.model.cellCullPosition(centerLon, centerLat),
fire: null,
cell,
accent: components.model.cellAccent(normalized),
accent: components.model.cellCardAccent(cell),
});
}
layerState._cells.set(items);
components.cards.rebuildAmbientLabels();
components.selection.refreshContextRegistrations(
components.selection.topFiresWithinBounds(bounds),
@@ -227,63 +330,15 @@ export function createRendering({
*/
function renderDetections(lod, bounds) {
ensureDetectionCollections();
clearCells();
const set = layerState._icons;
if (!set) return;
layerState._pickIndexById.clear();
let candidates;
if (bounds) {
// Walk the pre-sorted FRP index and early-exit at the cap — the old
// collect-then-sort touched and sorted every in-view detection per
// rebuild (tens of thousands mid-zoom; field-test round 1 chug).
candidates = [];
for (const fire of layerState._firesByFrp) {
if (!components.model.boundsContainPoint(bounds, fire.lat, fire.lon))
continue;
candidates.push(fire);
if (candidates.length >= lod.maxDetections) break;
}
} else {
// Sky/horizon view: fall back to the globally strongest detections.
candidates = layerState._firesByFrp.slice(0, lod.maxDetections);
}
const markers = paintMarkers(lod, bounds);
if (!markers) return;
const candidates = markers.map((marker) => marker.fire);
layerState._cellCount = candidates.length;
layerState._labelCandidates = [];
// FRP-sorted walk: marker order doubles as label priority.
layerState._labelCandidates = markers;
layerState._labelLodDistance = lod.labelDistance;
// Fires keep their glows across rebuilds: a pan that keeps a fire in
// view rewrites nothing for it, and only glows that left the view go.
const keep = new Set();
const writes = [];
for (const fire of candidates) {
const position = components.model.firePosition(fire);
const pickId = `firms-${fire.index}`;
layerState._pickIndexById.set(pickId, fire);
keep.add(pickId);
const glow = fireGlow(pickId, fire, position);
if (glow) writes.push({ glow, fire, position });
// FRP-sorted walk: candidate order doubles as label priority.
layerState._labelCandidates.push({
position,
cullPosition: components.model.fireCullPosition(fire),
fire,
cell: null,
});
}
const gone = [];
for (const pickId of drawnGlows.keys())
if (!keep.has(pickId)) gone.push(pickId);
for (const pickId of gone) drawnGlows.delete(pickId);
if (gone.length) set.remove(gone);
if (writes.length) {
set.upsert(writes.map((write) => write.glow));
for (const { glow, fire, position } of writes)
drawnGlows.set(glow.id, { fire, position });
}
components.cards.rebuildAmbientLabels();
components.selection.refreshContextRegistrations(
candidates.slice(0, CONTEXT_TOP_N),
@@ -304,6 +359,72 @@ export function createRendering({
}
}
/**
* The glow-sprite markers for a detections band: the strongest fires in
* view, capped at the band's maxDetections. The set culls the far side of
* the globe itself (`horizonCull`).
* @param {Object} lod - Detections band descriptor.
* @param {?Object} bounds - Padded view bounds in degrees, or null.
* @returns {?Array<Object>} Label candidates for the fires drawn,
* strongest first; null before the icon set exists.
*/
function paintMarkers(lod, bounds) {
ensureDetectionCollections();
const set = layerState._icons;
if (!set) return null;
layerState._pickIndexById.clear();
let candidates;
if (bounds) {
// Walk the pre-sorted FRP index and early-exit at the cap — the old
// collect-then-sort touched and sorted every in-view detection per
// rebuild (tens of thousands mid-zoom; field-test round 1 chug).
candidates = [];
for (const fire of layerState._firesByFrp) {
if (!components.model.boundsContainPoint(bounds, fire.lat, fire.lon))
continue;
candidates.push(fire);
if (candidates.length >= lod.maxDetections) break;
}
} else {
// Sky/horizon view: fall back to the globally strongest detections.
candidates = layerState._firesByFrp.slice(0, lod.maxDetections);
}
const markers = [];
// Only the close band warms terrain floors (renderDetections).
const anchor =
lod.id === 'close'
? components.model.firePosition
: components.model.fireBuiltPosition;
// Fires keep their glows across rebuilds: a pan that keeps a fire in
// view rewrites nothing for it, and only glows that left the view go.
const keep = new Set();
const writes = [];
for (const fire of candidates) {
const position = anchor(fire);
const cullPosition = components.model.fireCullPosition(fire, position);
const pickId = `firms-${fire.index}`;
layerState._pickIndexById.set(pickId, fire);
keep.add(pickId);
const glow = fireGlow(pickId, fire, position);
if (glow) writes.push({ glow, fire, position });
markers.push({ position, cullPosition, fire, cell: null });
}
const gone = [];
for (const pickId of drawnGlows.keys())
if (!keep.has(pickId)) gone.push(pickId);
for (const pickId of gone) drawnGlows.delete(pickId);
if (gone.length) set.remove(gone);
if (writes.length) {
set.upsert(writes.map((write) => write.glow));
for (const { glow, fire, position } of writes)
drawnGlows.set(glow.id, { fire, position, glow });
}
return markers;
}
/**
* A fire's glow icon, when it is new or changed since it was last drawn
* (else null): drawn depth-test-free at its anchor (a detection is never
@@ -312,7 +433,8 @@ export function createRendering({
* (Google 3D Tiles render the planet), so nothing writes far-side depth,
* and the cull is what keeps fires from shining through the planet. The
* anchor moves once, when its floor warms. A refresh reuses indices, so a
* kept id can hold a different detection, restyled then.
* kept id can hold a different detection, restyled then. It is written at
* the hand-off fade's current opacity (applyHandoffFade).
*
* The glow is rasterised once per colour at GLOW_SPRITE_PX and drawn at
* the fire's own size by its scale. Its hold motion draws it on the
@@ -333,6 +455,7 @@ export function createRendering({
),
size: [GLOW_SPRITE_PX, GLOW_SPRITE_PX],
scale: (corePx * 2) / GLOW_SPRITE_PX,
alpha: glowAlpha,
disableDepthTest: Infinity,
motion: { kind: 'hold' },
meta: { layer: 'firms', id: pickId },
@@ -344,7 +467,7 @@ export function createRendering({
const set = drawOf(layerState._viewer).icons({
id: `firms:${++iconSets}:icons`,
horizonCull: true,
show: layerState._enabled,
show: layerState._enabled && !(layerState._handoffHeat >= 1),
drawOrder: spriteDrawOrder?.('firms') ?? 0,
});
// Columns of no rows put the set's host in the scene now, rather than
@@ -381,9 +504,11 @@ export function createRendering({
return {
scenePorts,
renderCurrentLod,
renderBand,
aggregateFires,
renderCells,
renderHeat,
renderDetections,
applyHandoffFade,
ensureDetectionCollections,
removeDetectionCollections,
};
+57 -1
View File
@@ -1,3 +1,5 @@
import { DEFAULT_FIRE_FILTER } from '../../data/firmsIntensity.js';
export function createFirmsState({ services, config }) {
const layerState = {};
@@ -7,7 +9,11 @@ export function createFirmsState({ services, config }) {
layerState._viewer = null;
/** The heat cells' draw set (made at `init`). */
/**
* The layer's own shape set (made at `init`): empty since the heat became
* draped imagery, it marks the layer initialized and carries the `show`
* the context store reads.
*/
layerState._cells = null;
@@ -33,12 +39,39 @@ export function createFirmsState({ services, config }) {
layerState._error = null;
/** Every adapted detection in the current payload, before the filter. */
layerState._allFires = [];
/** `_allFires` sorted by FRP descending, once per payload. */
layerState._allFiresByFrp = [];
/**
* The detections that pass the intensity filter — the ONLY set rendering,
* selection, cells, the top-fires query and the analyst records ever walk.
*/
layerState._fires = [];
layerState._firesByFrp = [];
/** Shown (filtered) detection count. */
layerState._count = 0;
/** Loaded detection count before the filter ("N of M shown"). */
layerState._totalCount = 0;
/** Minimum FRP (MW) and confidence mode; see firmsIntensity.js. */
layerState._filter = { ...DEFAULT_FIRE_FILTER };
/** Panel callback: repaint the row controls (counter) after a load. */
layerState._rowControlsListener = null;
layerState._cellCount = 0;
layerState._lastUpdate = null;
@@ -87,6 +120,29 @@ export function createFirmsState({ services, config }) {
layerState._cellCacheByGrid = new Map();
/**
* Heat raster for the far bands (firmsHeatRaster.js); null = stale, rebuilt
* on the next far render. Cleared with the cell cache on every new shown set.
*/
layerState._heatRaster = null;
/** Pending debounced heat rebuild (see HEAT_REBUILD_MS). */
layerState._heatRebuildTimer = null;
/** Last applied hand-off fade (0 markers … 1 heatmap); -1 forces a reapply. */
layerState._handoffHeat = -1;
/** Imagery adapter (heatImagery.js), created on the first far render. */
layerState._heatImagery = null;
/** Shell-provided imagery host resolver; without one, the globe. */
layerState._imageryHost = null;
/** Camera idle snapshot so the throttled LOD check is ~free when parked. */
layerState._camSnapValid = false;
+4 -1
View File
@@ -158,9 +158,12 @@ export function createViewport({
layerState._preRenderRemover = frame.on('preRender', () => {
// NOTE: `_loading`/empty-data are deliberately NOT part of this guard.
// A refresh has no timeout, and sprites from the previous payload stay
// on screen throughout it — so the horizon pass below must keep running
// on screen throughout it — so the hand-off fade below must keep running
// while a fetch is in flight. Only the rebuild is gated on fresh data.
if (!layerState._enabled) return;
// Every frame, ahead of the throttle: a fast zoom crosses the whole
// hand-off between two band checks.
components.rendering.applyHandoffFade();
const now = performance.now();
if (now - layerState._lastLodCheck < LOD_CHECK_MS) return;
layerState._lastLodCheck = now;
+6 -1
View File
@@ -12,6 +12,11 @@ import {
} from '../../data/transitFeeds.js';
import { transitModeTier } from '../../data/transitPresetStyle.js';
/** Regions, not feeds: one region can carry several feeds (Rio has two). */
const TRANSIT_REGION_COUNT = new Set(
TRANSIT_ENABLED_FEEDS.map((feed) => feed.region),
).size;
/**
* The registry entry behind a vehicle. Live feeds answer first so a feed the
* session disabled stops supplying vocabulary; the registry is the fallback,
@@ -249,7 +254,7 @@ export function createQueries({ state, parts }) {
// English data (the analyst's empty note to the model); the voice
// card shows it through NOTE_PATTERNS (voice/resultDisplay.js).
coverage: state._altitudeGateOpen
? `No feed here yet · ${TRANSIT_ENABLED_FEEDS.length} regions available`
? `No feed here yet · ${TRANSIT_REGION_COUNT} regions available`
: `Fly below ${Math.round(ACTIVATION_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered region`,
};
}
+28
View File
@@ -0,0 +1,28 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createQueries } from './queries.js';
import { TRANSIT_ENABLED_FEEDS } from '../../data/transitFeeds.js';
test('the empty-coverage note counts regions, not feeds', () => {
const rio = TRANSIT_ENABLED_FEEDS.filter(
(feed) => feed.region === 'Rio de Janeiro, RJ',
);
assert.equal(rio.length, 2, 'Rio is one region with two feeds');
const regions = new Set(TRANSIT_ENABLED_FEEDS.map((feed) => feed.region));
assert.ok(regions.size < TRANSIT_ENABLED_FEEDS.length);
const stats = createQueries({
state: {
_activeFeeds: new Map(),
_vehicles: new Map(),
_enabled: true,
_altitudeGateOpen: true,
},
parts: {},
}).methods.getStats();
assert.equal(stats.status, 'zoom-in');
assert.equal(
stats.coverage,
`No feed here yet · ${regions.size} regions available`,
);
});
+12
View File
@@ -451,3 +451,15 @@ test('cards and detection judge the horizon where the icon shader culls the row'
);
layer.testing._setVesselStateForTest({ enabled: false });
});
test('vessel stats name the provider the last snapshot reported', async () => {
const { layer } = setup({
label: 'Vessels',
async getSnapshot() {
return snapshot([observation('111')], { source: 'Datalastic' });
},
});
assert.equal(layer.getStats().source, 'Vessels');
await layer.update();
assert.equal(layer.getStats().source, 'Datalastic');
});
+2
View File
@@ -539,6 +539,8 @@ export function createQueries({
// backing off, say how long until the next attempt instead of leaving
// the user to guess whether anything is still happening.
retryInSec: aisRetryInSec(),
// Same field as flights and military, so Contacts names the provider.
source: layer.source,
};
},
};