Draw FIRMS detections from a GPU icon set

This commit is contained in:
Sameh Khamis committed 2026-11-03 22:09:57 -08:00
1 parent 8aaf5564d7
commit c9f1fcd425
11 files changed
+318 -322

No files matched your search

+4 -13
View File
@@ -28,17 +28,9 @@ export function createLifecycle({
layerState._viewer = viewer;
if (!layerState._dataSource) this.init(viewer);
if (layerState._dataSource) layerState._dataSource.show = true;
if (layerState._billboards) {
// The camera can have moved anywhere while the layer was off: moveEnd
// was not being listened to, and the preRender watcher is inert while
// disabled AND while the (untimed) refetch below is in flight. So the
// retained per-sprite show flags describe the OLD viewpoint. Re-cull
// BEFORE the collection becomes visible — otherwise re-enabling at a
// new location flashes far-side fires through the planet (and keeps
// near-side ones hidden) until the fetch resolves.
components.rendering.refreshHorizonCulling();
layerState._billboards.show = true;
}
// The GPU culls the far side each frame, so retained rows are right
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, true);
components.viewport.installLodWatcher();
components.viewport.installMoveEndWatcher();
@@ -63,7 +55,7 @@ export function createLifecycle({
layerState._enabled = false;
components.selection.clearFireSelection();
if (layerState._dataSource) layerState._dataSource.show = false;
if (layerState._billboards) layerState._billboards.show = false;
if (layerState._icons) layerState._icons.show = false;
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
clearSelectedEntityContextForLayer(id);
@@ -110,7 +102,6 @@ export function createLifecycle({
layerState._labelLodDistance = 0;
layerState._pickIndexById.clear();
layerState._fireByCardId.clear();
layerState._cullPositions.length = 0;
layerState._camSnapValid = false;
},
};
+18 -58
View File
@@ -9,11 +9,10 @@ import {
import {
VIEW_PADDING,
DETECTION_COLOR_STOPS,
CULL_LIFT_THRESHOLD_M,
CULL_LIFT_M,
GLOW_SPRITE_PX,
LABEL_MIN_SEP_PX,
} from './policy.js';
import { billboardState, setBillboard } from '../../data/billboardMirror.js';
import { ICON_CULL_HEIGHT_M } from '../../data/iconSet.js';
export function createModel({
layerState,
@@ -161,18 +160,17 @@ export function createModel({
/**
* Build (and cache) a radial-glow sprite: hot near-white center fading
* through the stop color to a transparent edge. The glow lives in the
* sprite itself because global bloom defaults OFF.
* sprite itself because global bloom defaults OFF. One raster per color
* (GLOW_SPRITE_PX); each fire draws it at its own size.
* @param {{name: string, color: Cesium.Color}} stop - Color stop.
* @param {number} corePx - Bucketed core size in pixels.
* @returns {string} PNG data URL.
*/
function glowSprite(stop, corePx) {
const key = `${stop.name}:${corePx}`;
const cached = layerState.glowSpriteCache.get(key);
function glowSprite(stop) {
const cached = layerState.glowSpriteCache.get(stop.name);
if (cached) return cached;
const dimension = corePx * 2;
const dimension = GLOW_SPRITE_PX;
const canvas = document.createElement('canvas');
canvas.width = dimension;
canvas.height = dimension;
@@ -200,7 +198,7 @@ export function createModel({
context.fillRect(0, 0, dimension, dimension);
const dataUrl = canvas.toDataURL('image/png');
layerState.glowSpriteCache.set(key, dataUrl);
layerState.glowSpriteCache.set(stop.name, dataUrl);
return dataUrl;
}
@@ -231,21 +229,25 @@ export function createModel({
/**
* Occlusion-test anchor for one detection. Returns the render position
* outright for anchors comfortably above the ellipsoid (the common case) and
* a lazily-cached lifted point otherwise — see CULL_LIFT_THRESHOLD_M. This
* NEVER feeds rendering: the datum-correct anchor from {@link firePosition}
* is what the sprite and the card are drawn at.
* a lazily-cached lifted point otherwise, the point the icon set's GPU
* horizon test judges a fire row at (ICON_CULL_LIFT), so a card shows exactly
* when its sprite does. In negative-geoid coastal regions the floored anchor
* lands tens of metres BELOW the WGS84 ellipsoid, which the occluder judges
* beyond the horizon while true-surface neighbours stay visible. This 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.
* @returns {Cesium.Cartesian3}
*/
function fireCullPosition(fire) {
const position = firePosition(fire);
if (fire.positionHeight >= CULL_LIFT_THRESHOLD_M) return position;
if (fire.positionHeight >= ICON_CULL_HEIGHT_M) return position;
if (!fire.cullPosition) {
fire.cullPosition = Cesium.Cartesian3.fromDegrees(
fire.lon,
fire.lat,
CULL_LIFT_M,
ICON_CULL_HEIGHT_M,
);
}
return fire.cullPosition;
@@ -261,48 +263,7 @@ export function createModel({
*/
function cellCullPosition(lon, lat) {
return Cesium.Cartesian3.fromDegrees(lon, lat, CULL_LIFT_M);
}
/**
* Horizon-cull a billboard collection against an ellipsoid occluder.
*
* The Cesium globe is hidden in this app (Google 3D Tiles render the planet),
* so nothing writes far-side depth — and these sprites are additionally
* always-on-top (`disableDepthTestDistance: INFINITY`, so a detection is never
* swallowed by terrain it sits on). Without an explicit occluder pass, fires on
* the opposite side of the Earth shine through the planet at tilted mid-altitude
* views. Same pattern as the flights/CCTV layers' `EllipsoidalOccluder` passes.
*
* Pure and allocation-free: reads the billboard's mirrored position and show,
* and writes `show` only when it actually flips (assigning `show` dirties the
* collection's vertex buffer). Accepts any `{length, get(i)}` shape so it is unit-testable without
* a WebGL scene.
*
* @param {?{length: number, get: function(number): (Object|undefined)}} billboards
* Billboard collection (or collection-shaped stub).
* @param {?{isPointVisible: function(Object): boolean}} occluder Horizon occluder.
* @param {?Array<Cesium.Cartesian3>} [cullPositions=null] Index-aligned lifted
* occlusion-test anchors (see {@link fireCullPosition}); falls back to the
* billboard's own render position wherever an entry is absent.
* @returns {number} Count of billboards left visible (0 when nothing to test).
*/
function applyHorizonCull(billboards, occluder, cullPositions = null) {
if (!billboards || typeof billboards.get !== 'function') return 0;
if (typeof occluder?.isPointVisible !== 'function') return 0;
const total = Number(billboards.length) || 0;
let visibleCount = 0;
for (let i = 0; i < total; i += 1) {
const billboard = billboards.get(i);
if (!billboard) continue;
const pushed = billboardState(billboard);
const point = (cullPositions && cullPositions[i]) || pushed.position;
const visible = occluder.isPointVisible(point) === true;
if (pushed.show !== visible) setBillboard(billboard, 'show', visible);
if (visible) visibleCount += 1;
}
return visibleCount;
return Cesium.Cartesian3.fromDegrees(lon, lat, ICON_CULL_HEIGHT_M);
}
/**
@@ -589,7 +550,6 @@ export function createModel({
firePosition,
fireCullPosition,
cellCullPosition,
applyHorizonCull,
screenSeparated,
buildSelectedFireCard,
buildFireCard,
+5 -13
View File
@@ -8,7 +8,7 @@ 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.
* local band) render individual fire detections as glow-sprite icons.
* Labels in every band go through the shared screen-space greedy declutter
* (hard cap MAX_AMBIENT_LABELS) — there are no per-band label knobs.
*/
@@ -73,20 +73,12 @@ export const LABEL_MIN_SEP_PX = 150;
export const LABEL_VIEW_MARGIN_PX = 16;
/**
* Anchors below this height get a separate LIFTED point for occlusion tests
* (never for rendering). Mirrors the flights layer's `cullPosition` idiom
* (`renderAltitudeM < 10` → test at 12 m): `fireAnchorHeight` is ground floor
* + lift, and in negative-geoid coastal regions that lands a few tens of
* metres BELOW the WGS84 ellipsoid — EllipsoidalOccluder then judges such a
* point "beyond the horizon" while its true-surface neighbours stay visible,
* so near-limb fires would blink out for a datum reason.
* Glow sprites are rasterised once per colour at the largest core size
* (frpPixelSize tops out at 28 px, a 56 px sprite) and drawn smaller per fire:
* the gradient stops are relative, so the glow keeps its shape at any size.
*/
export const CULL_LIFT_THRESHOLD_M = 10;
/** Height of the lifted occlusion-test point (flights uses the same 12 m). */
export const CULL_LIFT_M = 12;
export const GLOW_SPRITE_PX = 56;
/** Color stops shared by cell heat fills and detection glow sprites. */
+107 -73
View File
@@ -1,8 +1,11 @@
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 { addBillboard } from '../../data/billboardMirror.js';
import { LOD_LEVELS, CONTEXT_TOP_N, GLOW_SPRITE_PX } from './policy.js';
import { createIconSet, ICON_CULL_LIFT } from '../../data/iconSet.js';
import { writeHoldSegment } from '../../data/iconSegment.js';
import { IconSetPrimitive } from '../../data/iconSetPrimitive.js';
import { iconAtlas } from '../../data/iconAtlas.js';
export function createRendering({
layerState,
@@ -20,18 +23,18 @@ export function createRendering({
* when neither the (hysteresis-damped) LOD band nor the padded view
* rectangle changed meaningfully.
* @param {boolean} force - Rebuild even if LOD/view appear unchanged.
* @returns {boolean} True when a rebuild actually ran. Callers use this to
* avoid a second horizon walk in the same tick: a rebuild already culls
* its freshly-added sprites, an early-out does not.
* @returns {boolean} True when a rebuild actually ran.
*/
function renderCurrentLod(force = false) {
if (
!layerState._dataSource ||
!layerState._fires.length ||
!layerState._viewer
)
if (!layerState._dataSource || !layerState._viewer) return false;
if (!layerState._fires.length) {
// A refresh that came back empty takes down what the last one drew, so
// no sprite or card is left on screen (and clickable) for a fire that is
// gone.
if (force) clearRendered();
return false;
}
const lodIndex = components.viewport.selectLodIndex(
components.viewport.cameraHeight(),
);
@@ -60,6 +63,16 @@ export function createRendering({
return true;
}
function clearRendered() {
layerState._dataSource.entities.removeAll();
layerState._icons?.clear();
layerState._pickIndexById.clear();
layerState._cellCount = 0;
layerState._labelCandidates = [];
components.cards.rebuildAmbientLabels();
components.selection.refreshContextRegistrations([]);
}
/**
* 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
@@ -132,9 +145,8 @@ export function createRendering({
function renderCells(cells, lod, bounds) {
ensureDetectionCollections();
layerState._dataSource.entities.removeAll();
if (layerState._billboards) layerState._billboards.removeAll();
layerState._icons?.clear();
layerState._pickIndexById.clear();
layerState._cullPositions.length = 0;
layerState._cellCount = cells.length;
const maxScore = Math.max(1, ...cells.map(components.model.heatScore));
@@ -189,7 +201,7 @@ export function createRendering({
/**
* Render individual detections (local/close bands) as pre-baked
* radial-glow sprite billboards sized by FRP, capped per viewport by
* radial-glow sprite icons sized by FRP, capped per viewport by
* highest FRP, depth test disabled. The 3D Tiles mesh is never sampled
* per point; instead, the CLOSE band (where terrain parallax is actually
* visible) batch-warms the shared cached DEM floor for its rendered
@@ -205,10 +217,9 @@ export function createRendering({
function renderDetections(lod, bounds) {
ensureDetectionCollections();
layerState._dataSource.entities.removeAll();
if (!layerState._billboards) return;
layerState._billboards.removeAll();
const set = layerState._icons;
if (!set) return;
layerState._pickIndexById.clear();
layerState._cullPositions.length = 0;
let candidates;
if (bounds) {
@@ -231,41 +242,28 @@ export function createRendering({
layerState._labelCandidates = [];
layerState._labelLodDistance = lod.labelDistance;
// Fires keep their rows across rebuilds: a pan that keeps a fire in view
// rewrites nothing for it, and only rows that left the view go.
const keep = new Set();
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 pickId = `firms-${fire.index}`;
layerState._pickIndexById.set(pickId, fire);
layerState._cullPositions.push(cullPosition);
const corePx = components.model.sizeBucket(coreSize);
addBillboard(layerState._billboards, {
id: pickId,
position,
image: components.model.glowSprite(
components.model.detectionColorStop(fire),
corePx,
),
// The glow sprite's own size (see glowSprite), stated for the app's mirror.
width: corePx * 2,
height: corePx * 2,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
});
keep.add(pickId);
placeFireIcon(set, pickId, fire, position);
// FRP-sorted walk: candidate order doubles as label priority.
layerState._labelCandidates.push({
position,
cullPosition,
cullPosition: components.model.fireCullPosition(fire),
fire,
cell: null,
});
}
for (let row = set.count - 1; row >= 0; row -= 1) {
const pickId = set.idAt(row);
if (!keep.has(pickId)) set.remove(pickId);
}
// 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),
@@ -286,30 +284,83 @@ export function createRendering({
}
}
/**
* A fire's glow row: drawn depth-test-free at its anchor (a detection is
* never swallowed by terrain it sits on), with the far side of the globe
* culled on the GPU each frame. The Cesium globe is hidden here (Google 3D
* Tiles render the planet), so nothing writes far-side depth, and the cull
* is what keeps fires from shining through the planet. The anchor moves
* once, when its floor warms.
*/
function placeFireIcon(set, pickId, fire, position) {
let row = set.row(pickId);
if (row < 0) {
row = set.add(pickId, {
layer: 'firms',
id: pickId,
fire: null,
position: null,
});
set.setFlag(row, ICON_CULL_LIFT, true);
set.setShown(row, true);
}
const meta = set.metaAt(row);
// A refresh reuses indices, so a kept row can hold a different detection.
if (meta.fire !== fire) {
meta.fire = fire;
const slot = iconAtlas.slot(
components.model.glowSprite(components.model.detectionColorStop(fire)),
GLOW_SPRITE_PX,
);
const corePx = components.model.sizeBucket(
components.model.frpPixelSize(fire.frp),
);
set.setImage(row, slot, slot);
set.setSize(row, corePx * 2, corePx * 2);
}
if (meta.position === position) return;
meta.position = position;
writeHoldSegment(set.segments, row, position, 0);
set.segmentWritten(row);
}
/** The scene the icon primitive was added to. */
let iconScene = null;
function ensureDetectionCollections() {
if (!layerState._viewer || layerState._billboards) return;
layerState._billboards = new Cesium.BillboardCollection({
scene: layerState._viewer.scene,
blendOption: Cesium.BlendOption.TRANSLUCENT,
if (!layerState._viewer || layerState._icons) return;
const epoch = Cesium.JulianDate.now();
layerState._icons = createIconSet({ epoch });
layerState._iconPrimitive = new IconSetPrimitive({
set: layerState._icons,
renderTime: () => epoch,
requestRender: () => layerState._viewer?.scene?.requestRender?.(),
});
layerState._billboards.show = layerState._enabled;
layerState._viewer.scene.primitives.add(layerState._billboards);
registerSpriteCollection('firms', layerState._billboards);
layerState._icons.show = layerState._enabled;
iconScene = layerState._viewer.scene;
iconScene.primitives.add(layerState._iconPrimitive);
registerSpriteCollection('firms', layerState._iconPrimitive);
restoreSpriteOrder(layerState._viewer);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, layerState._enabled);
}
function removeDetectionCollections(viewer) {
const scene = viewer?.scene || layerState._viewer?.scene;
if (scene && !scene.isDestroyed?.()) {
try {
if (layerState._billboards)
scene.primitives.remove(layerState._billboards);
} catch {
/* already torn down */
}
/**
* Take the icons out of the scene they were added to, whichever viewer the
* caller tears down, and free them: a destroyed primitive left in a live
* scene throws on its next frame.
*/
function removeDetectionCollections() {
const primitive = layerState._iconPrimitive;
try {
if (primitive && iconScene && !iconScene.isDestroyed?.())
iconScene.primitives.remove(primitive);
} catch {
/* already torn down */
}
layerState._billboards = null;
if (primitive && !primitive.isDestroyed()) primitive.destroy();
iconScene = null;
layerState._iconPrimitive = null;
layerState._icons = null;
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
}
@@ -331,22 +382,6 @@ export function createRendering({
return horizonOccluder(camera);
}
/**
* Hide detection sprites that sit beyond the ellipsoid horizon (see
* {@link applyHorizonCull}). Runs on the cadences that already exist in this
* layer — the throttled LOD preRender watcher (camera-moved only), camera
* moveEnd, and each detection rebuild — never as a new per-frame pass.
* No-ops in the `cells` bands, where the collection is empty.
*/
function refreshHorizonCulling() {
if (!layerState._billboards || !layerState._billboards.length) return;
components.model.applyHorizonCull(
layerState._billboards,
fireHorizonOccluder(),
layerState._cullPositions,
);
}
return {
renderCurrentLod,
aggregateFires,
@@ -355,6 +390,5 @@ export function createRendering({
ensureDetectionCollections,
removeDetectionCollections,
fireHorizonOccluder,
refreshHorizonCulling,
};
}
+2 -2
View File
@@ -88,8 +88,8 @@ export function createSelection({
/**
* Resolve a scene pick to one of this layer's fire records, or null.
* BillboardCollection picks surface our id either on picked.primitive.id
* or directly on picked.id depending on the CesiumJS pick path.
* Icon-set picks carry our row id on picked.id and on picked.primitive.id;
* either is accepted.
* @param {*} picked - Result of scene.pick().
* @returns {?Object} Fire record.
*/
+6 -12
View File
@@ -3,7 +3,7 @@ import * as Cesium from 'cesium';
export function createFirmsState({ services, config }) {
const layerState = {};
/** Pre-baked radial-glow sprites keyed by `<colorStop>:<sizeBucket>`. */
/** Pre-baked radial-glow sprites keyed by color stop name. */
layerState.glowSpriteCache = new Map();
@@ -19,7 +19,11 @@ export function createFirmsState({ services, config }) {
layerState._dataSource = null;
layerState._billboards = null;
/** Detection glow rows and the primitive that draws them. */
layerState._icons = null;
layerState._iconPrimitive = null;
layerState._enabled = false;
@@ -83,16 +87,6 @@ export function createFirmsState({ services, config }) {
layerState._fireByCardId = new Map();
/**
* Occlusion-test anchors index-aligned with the billboard collection (the
* collection is cleared and refilled in one ordered pass per rebuild, and
* nothing else adds to it). Lifted where the render anchor sits at/below
* the ellipsoid — see {@link fireCullPosition}.
* @type {Array<Cesium.Cartesian3>}
*/
layerState._cullPositions = [];
/**
* gridDegrees -> heat-sorted full cell list. The full-grid aggregation is
* viewport-independent but walks every detection (~200k live), so it is
+3 -19
View File
@@ -24,13 +24,7 @@ export function createViewport({
if (layerState._moveEndRemover || !layerState._viewer) return;
layerState._moveEndRemover =
layerState._viewer.camera.moveEnd.addEventListener(() => {
if (!layerState._enabled) return;
// Settled-camera exactness for the horizon pass (the throttled preRender
// watcher can last have run up to LOD_CHECK_MS before the camera
// stopped). Runs ahead of the `_loading` gate on purpose: the sprites on
// screen during a refresh are the ones that need culling.
components.rendering.refreshHorizonCulling();
if (layerState._loading) return;
if (!layerState._enabled || layerState._loading) return;
components.cards.rebuildAmbientLabels();
});
}
@@ -177,18 +171,8 @@ export function createViewport({
Cesium.Cartesian3.clone(camera.positionWC, layerState._camPos);
Cesium.Cartesian3.clone(camera.directionWC, layerState._camDir);
layerState._camSnapValid = true;
// The camera moved, so the horizon moved. A rebuild culls its own fresh
// sprites (renderDetections); an early-out — same LOD band and view
// rect, or a refresh in flight — does not, so cull here instead.
// Exactly ONE occlusion walk per tick either way, bounded by the
// idle-gate + LOD_CHECK_MS throttle above: a parked camera costs
// nothing, a moving one pays one ≤maxDetections show-flip walk at
// ~1.5 Hz.
const rebuilt =
layerState._fires.length && !layerState._loading
? components.rendering.renderCurrentLod(false)
: false;
if (!rebuilt) components.rendering.refreshHorizonCulling();
if (layerState._fires.length && !layerState._loading)
components.rendering.renderCurrentLod(false);
});
}