mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-18 01:02:23 +00:00
Merge origin/main into german/navara
Brings the Active Fires intensity work: the FRP filter, the confidence switch, the ember-to-white-hot ramp and the far-zoom heatmap. The filter, switch and ramp work on both engines. The heatmap drapes on Cesium through the layer's Cesium renderer, which also fades the markers across the hand-off; it goes with that renderer on an engine switch and is built again on the next Cesium globe. Navara keeps heat cells for the far bands, now coloured on the FRP ramp.
This commit is contained in:
commit
0c0df50a40
51 files changed
+2702
-144
No files matched your search
@@ -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,46 @@
|
||||
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(),
|
||||
// The layer's renderer on the current globe (render/cesium.js).
|
||||
_renderer: { setVisible: noop, onEnable: noop },
|
||||
_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, renderCurrentLod: 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 };
|
||||
}
|
||||
@@ -11,7 +11,32 @@ export function createLifecycle({
|
||||
const { clearSelectedEntityContextForLayer } = services.context;
|
||||
const { id, overlayHost } = config;
|
||||
|
||||
// The heatmap is draped on the renderer's globe (Cesium only); it goes
|
||||
// with the renderer and is built again on the next one that can drape it.
|
||||
function releaseHeat() {
|
||||
clearTimeout(layerState._heatRebuildTimer);
|
||||
layerState._heatRebuildTimer = null;
|
||||
layerState._heatImagery?.destroy();
|
||||
layerState._heatImagery = null;
|
||||
layerState._heatRaster = null;
|
||||
layerState._handoffHeat = -1;
|
||||
}
|
||||
|
||||
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, options) {
|
||||
this.attachRenderer(viewer, options);
|
||||
},
|
||||
@@ -53,6 +78,7 @@ export function createLifecycle({
|
||||
components.viewport.removeLodWatcher();
|
||||
unregisterPickOwner(id);
|
||||
components.rendering.removeDetectionCollections(layerState._viewer);
|
||||
releaseHeat();
|
||||
layerState._renderer?.destroy();
|
||||
layerState._renderer = layerState._viewer = layerState._dataSource = null;
|
||||
layerState._pickIndexById.clear();
|
||||
@@ -73,6 +99,10 @@ export function createLifecycle({
|
||||
}
|
||||
layerState._renderer.setVisible(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();
|
||||
@@ -101,6 +131,7 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
components.selection.clearFireSelection();
|
||||
layerState._renderer?.setVisible(false);
|
||||
layerState._heatImagery?.setShow(false);
|
||||
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
|
||||
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
|
||||
clearSelectedEntityContextForLayer(id);
|
||||
@@ -128,11 +159,17 @@ export function createLifecycle({
|
||||
layerState._dataSource = null;
|
||||
components.selection.clearContextRegistrations();
|
||||
clearSelectedEntityContextForLayer(id);
|
||||
layerState._allFires = [];
|
||||
layerState._allFiresByFrp = [];
|
||||
layerState._fires = [];
|
||||
layerState._firesByFrp = [];
|
||||
layerState._cellCacheByGrid.clear();
|
||||
layerState.glowSpriteCache.clear();
|
||||
releaseHeat();
|
||||
layerState._imageryHost = null;
|
||||
layerState._count = 0;
|
||||
layerState._totalCount = 0;
|
||||
layerState._rowControlsListener = null;
|
||||
layerState._cellCount = 0;
|
||||
layerState._lastUpdate = null;
|
||||
layerState._keyRequired = false;
|
||||
|
||||
+43
-31
@@ -1,6 +1,5 @@
|
||||
import { rectangleWidth, rectangleHeight } from './rectangle.js';
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { constantRgba } from '../shared/color.js';
|
||||
import { formatNumber, getLocale, isolate, t, tn } from '../../i18n/index.js';
|
||||
import {
|
||||
satelliteShortName,
|
||||
@@ -8,6 +7,7 @@ import {
|
||||
accentForSeverity,
|
||||
formatFrpMw,
|
||||
} from '../../data/firmsLabels.js';
|
||||
import { FRP_RAMP, frpRampStop } from '../../data/firmsIntensity.js';
|
||||
import {
|
||||
VIEW_PADDING,
|
||||
DETECTION_COLOR_STOPS,
|
||||
@@ -15,9 +15,6 @@ import {
|
||||
CULL_LIFT_M,
|
||||
LABEL_MIN_SEP_PX,
|
||||
} from './policy.js';
|
||||
const FIRE_RED = constantRgba(1, 0, 0);
|
||||
const FIRE_ORANGE = constantRgba(1, 165 / 255, 0);
|
||||
const FIRE_YELLOW = constantRgba(1, 1, 0);
|
||||
|
||||
export function createModel({
|
||||
layerState,
|
||||
@@ -124,27 +121,30 @@ export function createModel({
|
||||
);
|
||||
}
|
||||
|
||||
function heatColor(value, alpha) {
|
||||
if (value > 0.72) return FIRE_RED.withAlpha(alpha);
|
||||
if (value > 0.42) return FIRE_ORANGE.withAlpha(alpha);
|
||||
return FIRE_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. */
|
||||
@@ -232,6 +232,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
|
||||
@@ -239,11 +252,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 = geo.cartesian3.fromDegrees(
|
||||
@@ -403,8 +416,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.
|
||||
@@ -422,7 +435,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.
|
||||
@@ -469,16 +482,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". */
|
||||
@@ -584,12 +595,13 @@ export function createModel({
|
||||
boundsContainPoint,
|
||||
cellIntersectsBounds,
|
||||
heatScore,
|
||||
heatColor,
|
||||
frpColorStop,
|
||||
detectionColorStop,
|
||||
frpPixelSize,
|
||||
sizeBucket,
|
||||
glowSprite,
|
||||
firePosition,
|
||||
fireBuiltPosition,
|
||||
fireCullPosition,
|
||||
cellCullPosition,
|
||||
applyHorizonCull,
|
||||
@@ -598,7 +610,7 @@ export function createModel({
|
||||
buildFireCard,
|
||||
buildCellCard,
|
||||
applyFirmsOverlayPolicy,
|
||||
cellAccent,
|
||||
cellCardAccent,
|
||||
formatLatLon,
|
||||
formatFrp,
|
||||
formatAge,
|
||||
|
||||
+58
-17
@@ -1,17 +1,16 @@
|
||||
import { FIRMS_AMBIENT_COHORT_LIMIT } from '../../data/firmsLabels.js';
|
||||
import { constantRgba } from '../shared/color.js';
|
||||
const FIRE_RED = constantRgba(1, 0, 0);
|
||||
const FIRE_ORANGE = constantRgba(1, 165 / 255, 0);
|
||||
const FIRE_YELLOW = constantRgba(1, 1, 0);
|
||||
import { rgbaFromCss } from '../shared/color.js';
|
||||
import { FRP_RAMP } from '../../data/firmsIntensity.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 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.
|
||||
*/
|
||||
@@ -20,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,
|
||||
},
|
||||
{
|
||||
@@ -49,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. */
|
||||
@@ -91,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: FIRE_RED },
|
||||
{ name: 'orange', color: FIRE_ORANGE },
|
||||
{ name: 'yellow', color: FIRE_YELLOW },
|
||||
];
|
||||
export const DETECTION_COLOR_STOPS = FRP_RAMP.map((stop) =>
|
||||
Object.freeze({
|
||||
name: stop.name,
|
||||
minFrp: stop.minFrp,
|
||||
color: rgbaFromCss(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) => {
|
||||
|
||||
@@ -3,6 +3,7 @@ import {
|
||||
worldToWindowCoordinates,
|
||||
horizonOccluder,
|
||||
} from '../../../data/render/cesiumProjection.js';
|
||||
import { createHeatImagery } from '../heatImagery.js';
|
||||
|
||||
// Cesium ScreenSpaceEventType.LEFT_CLICK; available before the SDK loads.
|
||||
export const FIRMS_LEFT_CLICK = 2;
|
||||
@@ -22,6 +23,7 @@ export function createFirmsCesiumRenderer(
|
||||
let sprites = null,
|
||||
visible = false,
|
||||
destroyed = false;
|
||||
const fadeColor = new Cesium.Color();
|
||||
const spriteServices = services.sprites;
|
||||
function removeSprites() {
|
||||
if (!sprites) return;
|
||||
@@ -110,6 +112,27 @@ export function createFirmsCesiumRenderer(
|
||||
});
|
||||
},
|
||||
removeSprites,
|
||||
/**
|
||||
* The far-zoom heatmap draped on this globe: on the active map stack's
|
||||
* imagery host (`imageryHost()`), else on the viewer's imagery layers.
|
||||
*/
|
||||
createHeatImagery(imageryHost) {
|
||||
return createHeatImagery({
|
||||
cesium: Cesium,
|
||||
getHost: () =>
|
||||
imageryHost?.() ?? {
|
||||
collection: viewer.imageryLayers ?? null,
|
||||
kind: 'globe',
|
||||
},
|
||||
});
|
||||
},
|
||||
/** The hand-off fade: every marker at `alpha`, shown while `show`. */
|
||||
fadeSprites(alpha, show) {
|
||||
if (destroyed || !sprites) return;
|
||||
sprites.show = show;
|
||||
const color = Cesium.Color.WHITE.withAlpha(alpha, fadeColor);
|
||||
for (let i = 0; i < sprites.length; i += 1) sprites.get(i).color = color;
|
||||
},
|
||||
onEnable() {
|
||||
if (!destroyed)
|
||||
spriteServices.restoreSpriteOrderOnEnable('firms', viewer);
|
||||
|
||||
+223
-46
@@ -1,7 +1,20 @@
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { cloneRectangle } from './rectangle.js';
|
||||
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.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';
|
||||
|
||||
/** 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,
|
||||
@@ -28,8 +41,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(),
|
||||
);
|
||||
@@ -48,14 +64,58 @@ 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. On a globe that can drape the heatmap (Cesium), markers
|
||||
* and heatmap stay built in every band and the hand-off only fades
|
||||
* between them. Elsewhere the far bands draw heat cells instead.
|
||||
* @param {Object} lod - Band descriptor.
|
||||
* @param {?Object} bounds - Padded view bounds in degrees, or null.
|
||||
*/
|
||||
|
||||
function renderBand(lod, bounds) {
|
||||
if (!heatImagery()) {
|
||||
if (lod.mode === 'detections') renderDetections(lod, bounds);
|
||||
else renderCells(aggregateFires(lod, bounds), lod, bounds);
|
||||
return;
|
||||
}
|
||||
prepareHeat(lod.mode === 'heat');
|
||||
if (lod.mode === 'detections') renderDetections(lod, bounds);
|
||||
else renderHeat(lod, bounds);
|
||||
applyHandoffFade(true);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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. A
|
||||
* globe without the heatmap keeps its markers as they are.
|
||||
* @param {boolean} [force] Reapply, e.g. to freshly added markers.
|
||||
*/
|
||||
|
||||
function applyHandoffFade(force = false) {
|
||||
if (!layerState._heatImagery) return;
|
||||
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);
|
||||
layerState._renderer?.fadeSprites(
|
||||
1 - heat,
|
||||
layerState._enabled && heat < 1,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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
|
||||
@@ -116,10 +176,105 @@ export function createRendering({
|
||||
}
|
||||
|
||||
/**
|
||||
* 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}).
|
||||
* The heat imagery adapter, created on first use, or null when the
|
||||
* renderer's globe cannot drape it.
|
||||
*/
|
||||
|
||||
function heatImagery() {
|
||||
layerState._heatImagery ??=
|
||||
layerState._renderer?.createHeatImagery?.(
|
||||
() => layerState._imageryHost?.() ?? null,
|
||||
) ?? null;
|
||||
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 || !layerState._heatImagery) return;
|
||||
layerState._heatRaster = buildHeatRaster(layerState._fires, HEAT_RASTER);
|
||||
layerState._heatImagery.setRaster(layerState._heatRaster);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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) on a globe with the heatmap: 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 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 centerLon = cell.lonCell + lod.gridDegrees / 2;
|
||||
const centerLat = cell.latCell + lod.gridDegrees / 2;
|
||||
layerState._labelCandidates.push({
|
||||
position: geo.cartesian3.fromDegrees(centerLon, centerLat, 0),
|
||||
cullPosition: components.model.cellCullPosition(centerLon, centerLat),
|
||||
fire: null,
|
||||
cell,
|
||||
accent: components.model.cellCardAccent(cell),
|
||||
});
|
||||
}
|
||||
|
||||
components.cards.rebuildAmbientLabels();
|
||||
components.selection.refreshContextRegistrations(
|
||||
components.selection.topFiresWithinBounds(bounds),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Far bands on a globe without the heatmap (Navara): aggregated heat cells
|
||||
* as ground rectangles colored on the FRP ramp by their strongest fire.
|
||||
* Labels go through the same screen-space pipeline as detections.
|
||||
* @param {Array<Object>} cells - Aggregated cells, heat-sorted descending.
|
||||
* @param {Object} lod - Active LOD descriptor.
|
||||
* @param {?Object} bounds - Padded view bounds in degrees, or null.
|
||||
@@ -141,7 +296,9 @@ export function createRendering({
|
||||
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 color = components.model
|
||||
.frpColorStop(cell.maxFrp)
|
||||
.color.withAlpha(alpha);
|
||||
const centerLon = cell.lonCell + lod.gridDegrees / 2;
|
||||
const centerLat = cell.latCell + lod.gridDegrees / 2;
|
||||
const position = geo.cartesian3.fromDegrees(centerLon, centerLat, 0);
|
||||
@@ -162,13 +319,12 @@ export function createRendering({
|
||||
});
|
||||
|
||||
// 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,
|
||||
cullPosition: components.model.cellCullPosition(centerLon, centerLat),
|
||||
fire: null,
|
||||
cell,
|
||||
accent: components.model.cellAccent(normalized),
|
||||
accent: components.model.cellCardAccent(cell),
|
||||
});
|
||||
}
|
||||
|
||||
@@ -194,9 +350,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._renderer.clearCells();
|
||||
if (!layerState._billboards) return;
|
||||
if (!layerState._billboards) return null;
|
||||
layerState._billboards.removeAll();
|
||||
layerState._pickIndexById.clear();
|
||||
layerState._cullPositions.length = 0;
|
||||
@@ -218,17 +413,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._renderer.addSprite({
|
||||
id: pickId,
|
||||
position,
|
||||
@@ -237,37 +435,13 @@ export function createRendering({
|
||||
components.model.sizeBucket(coreSize),
|
||||
),
|
||||
});
|
||||
// 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() {
|
||||
@@ -319,9 +493,12 @@ export function createRendering({
|
||||
}
|
||||
return {
|
||||
renderCurrentLod,
|
||||
renderBand,
|
||||
aggregateFires,
|
||||
renderHeat,
|
||||
renderCells,
|
||||
renderDetections,
|
||||
applyHandoffFade,
|
||||
ensureDetectionCollections,
|
||||
removeDetectionCollections,
|
||||
fireHorizonOccluder,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import * as geo from '../../geo/index.js';
|
||||
import { DEFAULT_FIRE_FILTER } from '../../data/firmsIntensity.js';
|
||||
|
||||
export function createFirmsState({ services, config }) {
|
||||
const layerState = {};
|
||||
@@ -41,12 +42,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;
|
||||
@@ -105,6 +133,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;
|
||||
|
||||
@@ -165,6 +165,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;
|
||||
|
||||
Reference in new issue
Block a user