mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 16:22:20 +00:00
Merge branch 'main' into denis/gev-cockpit-entry
This commit is contained in:
90 files changed
+4333
-460
No files matched your search
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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?.();
|
||||
});
|
||||
@@ -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(':'))
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
AWARENESS_RELATIONSHIP,
|
||||
} from '../../data/militaryAwarenessEngine.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { layerFeedState } from '../../data/feedState.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import {
|
||||
AWARENESS_QUERY_LIMIT,
|
||||
@@ -52,6 +53,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 {
|
||||
@@ -94,6 +107,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',
|
||||
@@ -113,6 +127,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',
|
||||
@@ -132,6 +147,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',
|
||||
@@ -149,6 +165,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',
|
||||
|
||||
@@ -12,20 +12,28 @@
|
||||
* Cameras without an identified model are untouched — unknown never implies
|
||||
* anything.
|
||||
*
|
||||
* Spec records are vendored verbatim from the CCTV Camera Database
|
||||
* Specification fields are vendored from the CCTV Camera Database
|
||||
* (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) — an open dataset
|
||||
* of 28,000+ camera models transcribed from manufacturer datasheets (84% with
|
||||
* FOV, as of v2.26.0). This module vendors the records that the currently integrated public
|
||||
* of 29,000+ camera models transcribed from manufacturer datasheets (76% with
|
||||
* FOV, as of v2.29.0). This module vendors records that the integrated public
|
||||
* catalogs publish hardware for — King County WA (Cohu, Bosch AUTODOME, Axis
|
||||
* Q6135-LE), plus the Bosch AUTODOME and Axis PTZ/multisensor models that
|
||||
* appear in Sarasota County FL and Sioux Falls SD open data; packs that
|
||||
* appear in Sarasota County FL and Sioux Falls SD open data, plus the Bosch MIC
|
||||
* PTZs for the City of Amsterdam camera register proposed in #251; packs that
|
||||
* publish other hardware models can grow it, or vendor the full extract.
|
||||
*
|
||||
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
|
||||
* night vision) — never endpoints, stream paths, or access/config data.
|
||||
*/
|
||||
|
||||
/** Verbatim records from the dataset's model-enrichment extract (v2.26.0). */
|
||||
/**
|
||||
* Records from the dataset's model-enrichment extract: v2.26.0, plus the Bosch
|
||||
* MIC records from v2.29.0 with titles shortened to model codes.
|
||||
* A Bosch MIC order code ends in a colour letter (B, G, W; registries write
|
||||
* `x`) on one shared datasheet. The colours are aliases of one record whose
|
||||
* `model` leaves the letter out, so the HUD never names a variant the source
|
||||
* did not.
|
||||
*/
|
||||
const RECORDS = [
|
||||
{
|
||||
id: 'axis-q6135-le',
|
||||
@@ -264,6 +272,67 @@ const RECORDS = [
|
||||
autotracking: true,
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7130-pb4',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7130-P_4',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7130-pb4/',
|
||||
aliases: [
|
||||
'MIC IP starlight 7000 HD',
|
||||
'MIC-7130-PB4',
|
||||
'MIC-7130-PG4',
|
||||
'MIC-7130-PW4',
|
||||
'MIC-7130-Px4',
|
||||
],
|
||||
fov_deg: '2.1-59',
|
||||
resolution: { mp: 1, w: 1280, h: 720, label: '720p' },
|
||||
ptz: true,
|
||||
autotracking: true,
|
||||
varifocal: true,
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7502-z30b',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7502-Z30',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7502-z30b/',
|
||||
aliases: [
|
||||
'MIC-7502-Z30B',
|
||||
'MIC-7502-Z30G',
|
||||
'MIC-7502-Z30W',
|
||||
'MIC-7502-Z30x',
|
||||
],
|
||||
fov_deg: '2.3-63.7',
|
||||
resolution: { mp: 2.13, w: 1920, h: 1080, label: '1080p' },
|
||||
ptz: true,
|
||||
autotracking: true,
|
||||
varifocal: true,
|
||||
night_vision: { type: 'color' },
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7522-z30b',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7522-Z30',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/',
|
||||
aliases: [
|
||||
'MIC-7522-Z30B',
|
||||
'MIC-7522-Z30G',
|
||||
'MIC-7522-Z30W',
|
||||
'MIC-7522-Z30x',
|
||||
],
|
||||
fov_deg: '2.1-58.3',
|
||||
// i18n-ignore: datasheet label
|
||||
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' },
|
||||
ptz: true,
|
||||
varifocal: true,
|
||||
night_vision: { type: 'color' },
|
||||
environment: ['outdoor'],
|
||||
ndaa_compliant: true,
|
||||
},
|
||||
{
|
||||
id: 'cohu-3920-idome',
|
||||
brand: 'Cohu',
|
||||
@@ -431,7 +500,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => {
|
||||
* guesses).
|
||||
* @param {string} model - Hardware model as named by a source pack or seed.
|
||||
* @param {string} [manufacturer] - The source's manufacturer, when published.
|
||||
* @returns {Object|null} The verbatim spec record, or null when unknown.
|
||||
* @returns {Object|null} The matched spec record, or null when unknown.
|
||||
*/
|
||||
export function lookupModelSpec(model, manufacturer) {
|
||||
const query = words(model).map(stripVariantSuffix);
|
||||
|
||||
@@ -245,6 +245,95 @@ test('King County snapshot model strings still resolve', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Amsterdam camera register model strings resolve', () => {
|
||||
// The register writes the Bosch MIC colour letter as `x`.
|
||||
assert.equal(
|
||||
lookupModelSpec('Bosch MIC-7522-Z30x')?.id,
|
||||
'bosch-mic-7522-z30b',
|
||||
);
|
||||
assert.equal(
|
||||
lookupModelSpec('Bosch MIC-7502-Z30x')?.id,
|
||||
'bosch-mic-7502-z30b',
|
||||
);
|
||||
assert.equal(lookupModelSpec('Bosch MIC-7130-Px4')?.id, 'bosch-mic-7130-pb4');
|
||||
assert.equal(lookupModelSpec('MIC-7522-Z30W')?.id, 'bosch-mic-7522-z30b');
|
||||
// Its ANPR units are not in the table: unknown, never a guess.
|
||||
assert.equal(lookupModelSpec('CSG-8800'), null);
|
||||
// The MIC and AUTODOME starlight 7000 HD (code-less names, so the brand
|
||||
// is needed) stay apart.
|
||||
assert.equal(
|
||||
lookupModelSpec('MIC IP starlight 7000 HD', 'Bosch')?.id,
|
||||
'bosch-mic-7130-pb4',
|
||||
);
|
||||
assert.equal(
|
||||
lookupModelSpec('AUTODOME IP starlight 7000 HD', 'Bosch')?.id,
|
||||
'bosch-autodome-ip-starlight-7000-hd',
|
||||
);
|
||||
// The MIC datasheets state FOV without an axis, so no horizontal range.
|
||||
assert.equal(horizontalFovRangeDeg(lookupModelSpec('MIC-7522-Z30B')), null);
|
||||
});
|
||||
|
||||
test('Bosch MIC colour aliases resolve without accepting unknown variants', () => {
|
||||
for (const [pattern, id] of [
|
||||
['MIC-7130-P?4', 'bosch-mic-7130-pb4'],
|
||||
['MIC-7502-Z30?', 'bosch-mic-7502-z30b'],
|
||||
['MIC-7522-Z30?', 'bosch-mic-7522-z30b'],
|
||||
]) {
|
||||
for (const colour of ['B', 'G', 'W', 'x']) {
|
||||
const model = pattern.replace('?', colour);
|
||||
assert.equal(lookupModelSpec(model)?.id, id, model);
|
||||
assert.equal(lookupModelSpec(`bosch ${model.toLowerCase()}`)?.id, id);
|
||||
assert.equal(lookupModelSpec(model, 'Bosch')?.id, id);
|
||||
assert.equal(lookupModelSpec(model, 'Axis'), null);
|
||||
assert.equal(lookupModelSpec(`${model}-UNKNOWN`), null);
|
||||
}
|
||||
assert.equal(lookupModelSpec(pattern.replace('?', 'R')), null);
|
||||
}
|
||||
});
|
||||
|
||||
test('Bosch MIC HUD summary never names a colour the source did not', () => {
|
||||
assert.equal(
|
||||
specSummary(lookupModelSpec('MIC-7522-Z30W')),
|
||||
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
|
||||
);
|
||||
assert.equal(
|
||||
specSummary(lookupModelSpec('Bosch MIC-7522-Z30x')),
|
||||
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
|
||||
);
|
||||
for (const pattern of ['MIC-7130-P?4', 'MIC-7502-Z30?', 'MIC-7522-Z30?']) {
|
||||
for (const colour of ['B', 'G', 'W', 'x']) {
|
||||
const spec = lookupModelSpec(pattern.replace('?', colour));
|
||||
const summary = specSummary(spec);
|
||||
for (const other of ['B', 'G', 'W', 'x']) {
|
||||
assert.ok(!summary.includes(pattern.replace('?', other)), summary);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Bosch MIC catalog enrichment preserves estimated and explicit optics', () => {
|
||||
for (const model of [
|
||||
'Bosch MIC-7130-Px4',
|
||||
'Bosch MIC-7502-Z30x',
|
||||
'Bosch MIC-7522-Z30x',
|
||||
]) {
|
||||
for (const pose of [{}, { fovDeg: 44 }, { poseSource: 'curated' }]) {
|
||||
const [camera] = browserCatalog().buildCatalogFromSources([
|
||||
{ id: 'amsterdam-mic', lat: 52.37, lon: 4.9, model, ...pose },
|
||||
]);
|
||||
assert.ok(camera.spec, model);
|
||||
assert.equal(camera.fovDeg, pose.fovDeg ?? 74, model);
|
||||
assert.equal(camera.fovSource, undefined);
|
||||
assert.equal(camera.specFovMinDeg, undefined);
|
||||
assert.equal(camera.specFovMaxDeg, undefined);
|
||||
assert.equal(horizontalFovRangeDeg(camera.spec), null);
|
||||
assert.equal(fixedHorizontalFovDeg(camera.spec), null);
|
||||
assert.equal(specFovCapabilityToken(camera), null);
|
||||
assert.match(specSummary(camera.spec), /^Bosch MIC-.* · PTZ$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('catalog never overwrites an explicit FOV or a curated pose', () => {
|
||||
const [explicit, curated, cohu, pelco] =
|
||||
browserCatalog().buildCatalogFromSources([
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
/**
|
||||
* Drapes the Active Fires heat raster over the globe as one full-extent
|
||||
* imagery tile on the active imagery host (globe or 3D-tiles), like the wind
|
||||
* layer's scalar field. 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: Cesium unmaps a hidden imagery layer from the globe
|
||||
* tiles and re-maps 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 defaultCanvas = (width, height) => {
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = width;
|
||||
canvas.height = height;
|
||||
return canvas;
|
||||
};
|
||||
|
||||
export function createHeatImagery({
|
||||
cesium,
|
||||
getHost,
|
||||
createCanvas = defaultCanvas,
|
||||
}) {
|
||||
let raster = null;
|
||||
let layer = null;
|
||||
let collection = null;
|
||||
let show = true;
|
||||
let opacity = 1;
|
||||
|
||||
function detach() {
|
||||
if (layer && collection) collection.remove(layer, true);
|
||||
layer = null;
|
||||
collection = null;
|
||||
}
|
||||
|
||||
function attach() {
|
||||
detach();
|
||||
if (!raster) return;
|
||||
const host = getHost?.() ?? { collection: null, kind: 'none' };
|
||||
if (!host.collection) 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);
|
||||
const provider = new cesium.SingleTileImageryProvider({
|
||||
url: canvas.toDataURL('image/png'),
|
||||
tileWidth: raster.width,
|
||||
tileHeight: raster.height,
|
||||
rectangle: cesium.Rectangle.MAX_VALUE,
|
||||
});
|
||||
collection = host.collection;
|
||||
layer = collection.addImageryProvider(provider);
|
||||
layer.show = show;
|
||||
layer.alpha = opacity;
|
||||
collection.raiseToTop?.(layer);
|
||||
}
|
||||
|
||||
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;
|
||||
},
|
||||
rehome() {
|
||||
const host = getHost?.();
|
||||
if ((host?.collection ?? null) !== collection) attach();
|
||||
},
|
||||
destroy() {
|
||||
detach();
|
||||
raster = null;
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
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 = [];
|
||||
const collection = {
|
||||
addImageryProvider(provider) {
|
||||
const layer = { provider, show: true, alpha: 1 };
|
||||
layers.push(layer);
|
||||
return layer;
|
||||
},
|
||||
remove(layer, destroy) {
|
||||
layers.splice(layers.indexOf(layer), 1);
|
||||
removed.push({ layer, destroy });
|
||||
},
|
||||
raiseToTop() {},
|
||||
};
|
||||
let host = { collection, kind: 'globe' };
|
||||
const cesium = {
|
||||
Rectangle: { MAX_VALUE: { max: true } },
|
||||
SingleTileImageryProvider: class {
|
||||
constructor(options) {
|
||||
this.options = options;
|
||||
}
|
||||
},
|
||||
};
|
||||
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({
|
||||
cesium,
|
||||
getHost: () => host,
|
||||
createCanvas,
|
||||
});
|
||||
return { imagery, layers, removed, collection, 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.deepEqual(h.layers[0].provider.options.rectangle, { max: true });
|
||||
assert.equal(h.layers[0].provider.options.tileWidth, 4);
|
||||
h.imagery.setRaster(raster);
|
||||
assert.equal(h.layers.length, 1, 'never two heat layers');
|
||||
assert.equal(h.removed[0].destroy, true);
|
||||
});
|
||||
|
||||
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({ collection: null, kind: 'none' });
|
||||
h.imagery.setRaster(raster);
|
||||
assert.equal(h.layers.length, 0);
|
||||
h.setHost({ collection: h.collection, kind: 'globe' });
|
||||
h.imagery.rehome();
|
||||
assert.equal(h.layers.length, 1);
|
||||
});
|
||||
|
||||
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`,
|
||||
);
|
||||
});
|
||||
@@ -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: {},
|
||||
_dataSource: {},
|
||||
_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');
|
||||
});
|
||||
@@ -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 };
|
||||
}
|
||||
@@ -14,6 +14,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({
|
||||
layerState._billboards.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();
|
||||
@@ -64,6 +82,7 @@ export function createLifecycle({
|
||||
components.selection.clearFireSelection();
|
||||
if (layerState._dataSource) layerState._dataSource.show = false;
|
||||
if (layerState._billboards) layerState._billboards.show = false;
|
||||
layerState._heatImagery?.setShow(false);
|
||||
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
|
||||
clearSelectedEntityContextForLayer(id);
|
||||
@@ -91,10 +110,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
@@ -6,6 +6,7 @@ import {
|
||||
accentForSeverity,
|
||||
formatFrpMw,
|
||||
} from '../../data/firmsLabels.js';
|
||||
import { FRP_RAMP, frpRampStop } from '../../data/firmsIntensity.js';
|
||||
import {
|
||||
VIEW_PADDING,
|
||||
DETECTION_COLOR_STOPS,
|
||||
@@ -119,27 +120,30 @@ export function createModel({
|
||||
);
|
||||
}
|
||||
|
||||
function heatColor(value, alpha) {
|
||||
if (value > 0.72) return Cesium.Color.RED.withAlpha(alpha);
|
||||
if (value > 0.42) return Cesium.Color.ORANGE.withAlpha(alpha);
|
||||
return Cesium.Color.YELLOW.withAlpha(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: Cesium.Color}}
|
||||
*/
|
||||
|
||||
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: Cesium.Color}}
|
||||
*/
|
||||
|
||||
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. */
|
||||
@@ -227,6 +231,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 {Cesium.Cartesian3}
|
||||
*/
|
||||
|
||||
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
|
||||
@@ -234,11 +251,11 @@ export function createModel({
|
||||
* NEVER 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 {Cesium.Cartesian3} [position] Its render anchor, if at hand.
|
||||
* @returns {Cesium.Cartesian3}
|
||||
*/
|
||||
|
||||
function fireCullPosition(fire) {
|
||||
const position = firePosition(fire);
|
||||
function fireCullPosition(fire, position = firePosition(fire)) {
|
||||
if (fire.positionHeight >= CULL_LIFT_THRESHOLD_M) return position;
|
||||
if (!fire.cullPosition) {
|
||||
fire.cullPosition = Cesium.Cartesian3.fromDegrees(
|
||||
@@ -398,8 +415,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: Cesium.Cartesian3, accent: string}} candidate
|
||||
* @param {number} nowMs - Current epoch milliseconds.
|
||||
* @returns {Object} firmsLabels entry.
|
||||
@@ -417,7 +434,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.
|
||||
@@ -464,16 +481,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". */
|
||||
@@ -579,12 +594,13 @@ export function createModel({
|
||||
boundsContainPoint,
|
||||
cellIntersectsBounds,
|
||||
heatScore,
|
||||
heatColor,
|
||||
frpColorStop,
|
||||
detectionColorStop,
|
||||
frpPixelSize,
|
||||
sizeBucket,
|
||||
glowSprite,
|
||||
firePosition,
|
||||
fireBuiltPosition,
|
||||
fireCullPosition,
|
||||
cellCullPosition,
|
||||
applyHorizonCull,
|
||||
@@ -593,7 +609,7 @@ export function createModel({
|
||||
buildFireCard,
|
||||
buildCellCard,
|
||||
applyFirmsOverlayPolicy,
|
||||
cellAccent,
|
||||
cellCardAccent,
|
||||
formatLatLon,
|
||||
formatFrp,
|
||||
formatAge,
|
||||
|
||||
+57
-13
@@ -1,4 +1,5 @@
|
||||
import { FIRMS_AMBIENT_COHORT_LIMIT } from '../../data/firmsLabels.js';
|
||||
import { FRP_RAMP } from '../../data/firmsIntensity.js';
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/** Client poll interval; the proxy's 30 min TTL is what guards upstream quota. */
|
||||
@@ -6,9 +7,10 @@ import * as Cesium from 'cesium';
|
||||
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 billboards.
|
||||
* 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 billboards.
|
||||
* Labels in every band go through the shared screen-space greedy declutter
|
||||
* (hard cap MAX_AMBIENT_LABELS) — there are no per-band label knobs.
|
||||
*/
|
||||
@@ -17,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,
|
||||
},
|
||||
{
|
||||
@@ -46,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. */
|
||||
@@ -88,10 +126,16 @@ export const CULL_LIFT_THRESHOLD_M = 10;
|
||||
|
||||
export const CULL_LIFT_M = 12;
|
||||
|
||||
/** Color stops shared by cell heat fills and detection glow sprites. */
|
||||
/**
|
||||
* Color stops for detection glow sprites and card accents: the
|
||||
* six-stop ember → white-hot FRP ramp (firmsIntensity.js), weakest first, as Cesium
|
||||
* colors. Stop names key the glow-sprite cache and the card accents.
|
||||
*/
|
||||
|
||||
export const DETECTION_COLOR_STOPS = [
|
||||
{ name: 'red', color: Cesium.Color.RED },
|
||||
{ name: 'orange', color: Cesium.Color.ORANGE },
|
||||
{ name: 'yellow', color: Cesium.Color.YELLOW },
|
||||
];
|
||||
export const DETECTION_COLOR_STOPS = FRP_RAMP.map((stop) =>
|
||||
Object.freeze({
|
||||
name: stop.name,
|
||||
minFrp: stop.minFrp,
|
||||
color: Cesium.Color.fromCssColorString(stop.hex),
|
||||
}),
|
||||
);
|
||||
+161
-2
@@ -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,
|
||||
@@ -172,12 +309,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: entities drawn by the layer's data source. */
|
||||
_entityCountForTest() {
|
||||
return layerState._dataSource?.entities?.values?.length ?? 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;
|
||||
layerState._labelCandidates = fires.map((fire) => {
|
||||
|
||||
+191
-83
@@ -1,7 +1,21 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
|
||||
import { horizonOccluder } from '../../data/iconOrientation.js';
|
||||
import { LOD_LEVELS, CONTEXT_TOP_N } from './policy.js';
|
||||
import { buildHeatRaster } from '../../data/firmsHeatRaster.js';
|
||||
import {
|
||||
LOD_LEVELS,
|
||||
CONTEXT_TOP_N,
|
||||
HANDOFF_FADE,
|
||||
HEAT_RASTER,
|
||||
HEAT_REBUILD_MS,
|
||||
} from './policy.js';
|
||||
import { createHeatImagery } from './heatImagery.js';
|
||||
|
||||
/** 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 colors at most this often. */
|
||||
const FADE_STEPS = 32;
|
||||
|
||||
export function createRendering({
|
||||
layerState,
|
||||
@@ -29,8 +43,11 @@ export function createRendering({
|
||||
!layerState._dataSource ||
|
||||
!layerState._fires.length ||
|
||||
!layerState._viewer
|
||||
)
|
||||
) {
|
||||
// A filter that leaves nothing shown must not leave the old heat behind.
|
||||
if (!layerState._fires.length) layerState._heatImagery?.setShow(false);
|
||||
return false;
|
||||
}
|
||||
const lodIndex = components.viewport.selectLodIndex(
|
||||
components.viewport.cameraHeight(),
|
||||
);
|
||||
@@ -51,14 +68,54 @@ 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;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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);
|
||||
}
|
||||
|
||||
const fadeColor = new Cesium.Color();
|
||||
|
||||
/**
|
||||
* 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);
|
||||
const billboards = layerState._billboards;
|
||||
if (!billboards) return;
|
||||
billboards.show = layerState._enabled && heat < 1;
|
||||
const color = Cesium.Color.WHITE.withAlpha(1 - heat, fadeColor);
|
||||
for (let i = 0; i < billboards.length; i += 1)
|
||||
billboards.get(i).color = color;
|
||||
}
|
||||
|
||||
/**
|
||||
* Bin all detections into grid cells, then viewport-clip BEFORE the
|
||||
* top-N cap so fires in view never lose their slot to higher-scoring
|
||||
@@ -118,65 +175,96 @@ export function createRendering({
|
||||
return clipped;
|
||||
}
|
||||
|
||||
/** The heat imagery adapter, created on first use. */
|
||||
|
||||
function heatImagery() {
|
||||
if (!layerState._heatImagery) {
|
||||
layerState._heatImagery = createHeatImagery({
|
||||
cesium: Cesium,
|
||||
getHost: () =>
|
||||
layerState._imageryHost?.() ?? {
|
||||
collection: layerState._viewer?.imageryLayers ?? null,
|
||||
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. Cell labels do NOT live on the entities anymore — 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();
|
||||
layerState._dataSource.entities.removeAll();
|
||||
if (layerState._billboards) layerState._billboards.removeAll();
|
||||
layerState._pickIndexById.clear();
|
||||
layerState._cullPositions.length = 0;
|
||||
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;
|
||||
|
||||
// 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 = Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 0);
|
||||
|
||||
layerState._dataSource.entities.add({
|
||||
rectangle: {
|
||||
coordinates: Cesium.Rectangle.fromDegrees(
|
||||
cell.lonCell,
|
||||
cell.latCell,
|
||||
cell.lonCell + lod.gridDegrees,
|
||||
cell.latCell + lod.gridDegrees,
|
||||
),
|
||||
material: new Cesium.ColorMaterialProperty(color),
|
||||
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
|
||||
},
|
||||
position,
|
||||
properties: {
|
||||
count: cell.count,
|
||||
intensity: score,
|
||||
maxFrp: cell.maxFrp,
|
||||
night: cell.night,
|
||||
},
|
||||
});
|
||||
|
||||
// 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: Cesium.Cartesian3.fromDegrees(centerLon, centerLat, 0),
|
||||
cullPosition: components.model.cellCullPosition(centerLon, centerLat),
|
||||
fire: null,
|
||||
cell,
|
||||
accent: components.model.cellAccent(normalized),
|
||||
accent: components.model.cellCardAccent(cell),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -202,9 +290,48 @@ export function createRendering({
|
||||
*/
|
||||
|
||||
function renderDetections(lod, bounds) {
|
||||
const markers = paintMarkers(lod, bounds);
|
||||
if (!markers) return;
|
||||
const candidates = markers.map((marker) => marker.fire);
|
||||
|
||||
layerState._cellCount = candidates.length;
|
||||
// FRP-sorted walk: marker order doubles as label priority.
|
||||
layerState._labelCandidates = markers;
|
||||
layerState._labelLodDistance = lod.labelDistance;
|
||||
|
||||
components.cards.rebuildAmbientLabels();
|
||||
components.selection.refreshContextRegistrations(
|
||||
candidates.slice(0, CONTEXT_TOP_N),
|
||||
);
|
||||
|
||||
if (lod.id === 'close') {
|
||||
// Batched (chunked ≤200, sequential, session-cached) DEM warm for the
|
||||
// rendered subset; fires are static so each coarse cell resolves once
|
||||
// ever. Re-render ONLY when a floor actually landed — a failed resolve
|
||||
// reports false, so this chain terminates instead of looping against a
|
||||
// down proxy (the next camera-driven rebuild retries).
|
||||
warmFireAnchorFloors(candidates).then((warmed) => {
|
||||
if (!warmed || !layerState._enabled || !layerState._viewer) return;
|
||||
const currentLod = LOD_LEVELS[layerState._currentLodIndex];
|
||||
if (!currentLod || currentLod.mode !== 'detections') return;
|
||||
renderCurrentLod(true);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* The glow-sprite markers for a detections band: the strongest fires in
|
||||
* view, capped at the band's maxDetections, horizon-culled.
|
||||
* @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 sprite collection exists.
|
||||
*/
|
||||
|
||||
function paintMarkers(lod, bounds) {
|
||||
ensureDetectionCollections();
|
||||
layerState._dataSource.entities.removeAll();
|
||||
if (!layerState._billboards) return;
|
||||
if (!layerState._billboards) return null;
|
||||
layerState._billboards.removeAll();
|
||||
layerState._pickIndexById.clear();
|
||||
layerState._cullPositions.length = 0;
|
||||
@@ -226,17 +353,20 @@ export function createRendering({
|
||||
candidates = layerState._firesByFrp.slice(0, lod.maxDetections);
|
||||
}
|
||||
|
||||
layerState._cellCount = candidates.length;
|
||||
layerState._labelCandidates = [];
|
||||
layerState._labelLodDistance = lod.labelDistance;
|
||||
|
||||
const markers = [];
|
||||
// Only the close band warms terrain floors (renderDetections).
|
||||
const anchor =
|
||||
lod.id === 'close'
|
||||
? components.model.firePosition
|
||||
: components.model.fireBuiltPosition;
|
||||
for (const fire of candidates) {
|
||||
const coreSize = components.model.frpPixelSize(fire.frp);
|
||||
const position = components.model.firePosition(fire);
|
||||
const cullPosition = components.model.fireCullPosition(fire);
|
||||
const position = anchor(fire);
|
||||
const cullPosition = components.model.fireCullPosition(fire, position);
|
||||
const pickId = `firms-${fire.index}`;
|
||||
layerState._pickIndexById.set(pickId, fire);
|
||||
layerState._cullPositions.push(cullPosition);
|
||||
markers.push({ position, cullPosition, fire, cell: null });
|
||||
layerState._billboards.add({
|
||||
id: pickId,
|
||||
position,
|
||||
@@ -248,37 +378,13 @@ export function createRendering({
|
||||
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
});
|
||||
// FRP-sorted walk: candidate order doubles as label priority.
|
||||
layerState._labelCandidates.push({
|
||||
position,
|
||||
cullPosition,
|
||||
fire,
|
||||
cell: null,
|
||||
});
|
||||
}
|
||||
|
||||
// Freshly-added sprites default to show=true; cull the far side now so a
|
||||
// rebuild never flashes through-the-planet detections while the camera
|
||||
// sits still (the moveEnd/preRender hooks only fire on camera motion).
|
||||
refreshHorizonCulling();
|
||||
components.cards.rebuildAmbientLabels();
|
||||
components.selection.refreshContextRegistrations(
|
||||
candidates.slice(0, CONTEXT_TOP_N),
|
||||
);
|
||||
|
||||
if (lod.id === 'close') {
|
||||
// Batched (chunked ≤200, sequential, session-cached) DEM warm for the
|
||||
// rendered subset; fires are static so each coarse cell resolves once
|
||||
// ever. Re-render ONLY when a floor actually landed — a failed resolve
|
||||
// reports false, so this chain terminates instead of looping against a
|
||||
// down proxy (the next camera-driven rebuild retries).
|
||||
warmFireAnchorFloors(candidates).then((warmed) => {
|
||||
if (!warmed || !layerState._enabled || !layerState._viewer) return;
|
||||
const currentLod = LOD_LEVELS[layerState._currentLodIndex];
|
||||
if (!currentLod || currentLod.mode !== 'detections') return;
|
||||
renderCurrentLod(true);
|
||||
});
|
||||
}
|
||||
return markers;
|
||||
}
|
||||
|
||||
function ensureDetectionCollections() {
|
||||
@@ -344,9 +450,11 @@ export function createRendering({
|
||||
}
|
||||
return {
|
||||
renderCurrentLod,
|
||||
renderBand,
|
||||
aggregateFires,
|
||||
renderCells,
|
||||
renderHeat,
|
||||
renderDetections,
|
||||
applyHandoffFade,
|
||||
ensureDetectionCollections,
|
||||
removeDetectionCollections,
|
||||
fireHorizonOccluder,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { DEFAULT_FIRE_FILTER } from '../../data/firmsIntensity.js';
|
||||
|
||||
export function createFirmsState({ services, config }) {
|
||||
const layerState = {};
|
||||
@@ -39,12 +40,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;
|
||||
@@ -103,6 +131,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; falls back to viewer.imageryLayers. */
|
||||
|
||||
layerState._imageryHost = null;
|
||||
|
||||
/** Camera idle snapshot so the throttled LOD check is ~free when parked. */
|
||||
|
||||
layerState._camSnapValid = false;
|
||||
|
||||
@@ -151,6 +151,9 @@ export function createViewport({
|
||||
// on screen throughout it — so the horizon pass 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;
|
||||
|
||||
@@ -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`,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -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`,
|
||||
);
|
||||
});
|
||||
@@ -409,3 +409,15 @@ test('empty coverage cannot hide stale, incomplete or rejected source data', asy
|
||||
assert.ok(layer.getStats().error, JSON.stringify(patch));
|
||||
}
|
||||
});
|
||||
|
||||
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');
|
||||
});
|
||||
@@ -548,6 +548,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,
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
Reference in new issue
Block a user