Move the active fires layer's cells, camera, cards and LOD onto renderer ports

Heat cells are clamped rectangle fills in one draw set per layer
(firms:N:cells) instead of entities. The LOD watcher follows the camera
port's pose, view rectangle and moveEnd and the frame port's preRender;
cards project and horizon-test through the query port. Colours, the view
change thresholds and the padded bounds are unchanged. On a viewer with
no renderer bound, the layer answers projection, occlusion and preRender
from the viewer's scene, as it did before.

Policy, model, state, viewport, cards and lifecycle no longer import
Cesium and leave the allow-list. Rendering keeps Cesium for the detection
icons, which stay on the shared icon-set primitive, and loads the unbound
camera and draw factories. Heat cells are no longer entities, so
double-clicking one no longer makes the camera follow its centre.
This commit is contained in:
Sameh Khamis committed 2026-11-06 20:30:33 -08:00
1 parent 6f82f9cc9c
commit 6e23d2aac9
18 files changed
+639 -197

No files matched your search

+14 -19
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import {
FIRMS_OVERLAY_SOURCE_ID,
@@ -19,8 +18,8 @@ export function createCards({
* Rebuild the card entries for the shared world-overlay host: the
* selected-fire detail card (if any) plus at most MAX_AMBIENT_LABELS
* ambient cards picked by a greedy screen-space declutter — walk the
* priority-ranked candidates, project each with
* SceneTransforms.worldToWindowCoordinates, and accept only candidates
* priority-ranked candidates, project each with the renderer's
* `query.project`, and accept only candidates
* ≥ LABEL_MIN_SEP_PX from every already-accepted card. Candidates whose
* projection fails are dropped silently. SELECTION runs here, on LOD/
* viewport rebuilds and camera moveEnd — never per frame; RENDERING is
@@ -31,19 +30,21 @@ export function createCards({
function rebuildAmbientLabels() {
if (!layerState._viewer) return;
const scene = layerState._viewer.scene;
const { query } = components.rendering.scenePorts();
const project = (position) => query?.project(position) ?? null;
const now = Date.now();
const entries = [];
/** @type {Array<{x: number, y: number}>} Screen positions of accepted labels. */
const accepted = [];
// worldToWindowCoordinates happily projects points on the FAR side of the
// planet, so without this the ≤18 ambient slots get spent on fires the
// overlay host will then horizon-cull at paint time (`horizonCull: true`
// in applyFirmsOverlayPolicy) — near-side fires silently lose their cards.
// Shared with the sprite pass (fireHorizonOccluder) so cards and sprites
// never disagree about which hemisphere a detection is on.
const occluder = components.rendering.fireHorizonOccluder();
// Projection happily answers for points on the FAR side of the planet,
// so without this the ≤18 ambient slots get spent on fires the overlay
// host will then horizon-cull at paint time (`horizonCull: true` in
// applyFirmsOverlayPolicy) — near-side fires silently lose their cards.
// The renderer's ellipsoid horizon from the eye, the test the sprites'
// GPU cull makes, so cards and sprites never disagree about which
// hemisphere a detection is on.
const beyondHorizon = (position) =>
occluder ? occluder.isPointVisible(position) !== true : false;
query ? query.isOccluded(position) : false;
layerState._fireByCardId.clear();
if (layerState._selectedFire) {
@@ -53,10 +54,8 @@ export function createCards({
);
layerState._fireByCardId.set(selectedCard.id, layerState._selectedFire);
entries.push(selectedCard);
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
const screen = project(
components.model.firePosition(layerState._selectedFire),
layerState.scratchWindowCoord,
);
// Seed the accepted list so ambient cards keep clear of the detail card.
// A selected fire behind the limb is not painted, so it must not reserve
@@ -83,11 +82,7 @@ export function createCards({
// LOD, far-side cells can still project on-canvas; accepting those first
// starves front-side cards before the host applies its authoritative cull.
if (beyondHorizon(candidate.cullPosition || candidate.position)) continue;
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
candidate.position,
layerState.scratchWindowCoord,
);
const screen = project(candidate.position);
if (!screen) continue; // projection failed (e.g. behind camera) — drop silently
if (
screen.x < -LABEL_VIEW_MARGIN_PX ||
+201
View File
@@ -0,0 +1,201 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import * as Cesium from 'cesium';
import { createFirmsHeatmapLayer } from '../../data/firmsHeatmap.js';
import { unregisterSpriteCollection } from '../../data/spriteOrder.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
const raw = (lat, lon, frp) => ({
lat,
lon,
frp,
confidence: 'h',
brightness: 340,
daynight: 'D',
acqDate: '2026-08-03',
acqTime: '0412',
instrument: 'VIIRS',
satellite: 'N20',
});
/** Enough canvas for the glow sprites. */
const canvasStub = () => ({
width: 0,
height: 0,
getContext: () => ({
createRadialGradient: () => ({ addColorStop() {} }),
fillRect() {},
}),
toDataURL: () => 'data:image/png;base64,iVBORw0KGgo=',
});
function harness(fires, heightM, { sceneFromViewer = false } = {}) {
const saved = {
window: globalThis.window,
document: globalThis.document,
project: Cesium.SceneTransforms.worldToWindowCoordinates,
};
globalThis.window = new EventTarget();
globalThis.document = { createElement: canvasStub };
// Headless: every position projects to the canvas middle.
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 400, y: 300 });
const primitives = [];
const viewer = {
camera: {
moveEnd: new Cesium.Event(),
positionWC: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, heightM),
directionWC: new Cesium.Cartesian3(0, 0, -1),
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
heightM,
),
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
preRender: new Cesium.Event(),
primitives: {
add: (value) => (primitives.push(value), value),
remove: (value) => {
const at = primitives.indexOf(value);
if (at >= 0) primitives.splice(at, 1);
value.destroy?.();
return at >= 0;
},
contains: () => false,
},
},
};
const ports = bindFakeCesiumScene(viewer);
const { draw } = ports;
// A renderer with no query or frame: the layer reads the viewer's scene.
if (sceneFromViewer) {
ports.unbind();
bindRenderer(viewer, { draw, camera: ports.camera });
}
const input = fakeInput(viewer);
const layer = createFirmsHeatmapLayer({
id: 'firms',
name: 'FIRMS',
feed: { getSnapshot: async () => ({ fires, fetchedAt: Date.now() }) },
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const cells = () =>
[...draw.sets.values()].find(
(record) => !record.disposed && record.spec.id.endsWith(':cells'),
);
return {
layer,
viewer,
cells,
cleanup() {
layer.destroy(viewer);
unregisterSpriteCollection('firms');
input.destroy();
Cesium.SceneTransforms.worldToWindowCoordinates = saved.project;
for (const key of ['window', 'document'])
if (saved[key] === undefined) delete globalThis[key];
else globalThis[key] = saved[key];
},
};
}
test('far out, the heat cells are clamped rectangles in one draw set, shown with the layer', async () => {
const h = harness(
[raw(30.5, -98.2, 1500), raw(30.6, -98.3, 20), raw(-12.1, 131.4, 5)],
12_000_000,
);
try {
h.layer.init(h.viewer);
assert.equal(h.cells().show, false, 'hidden until enabled');
await h.layer.enable(h.viewer);
const cells = h.cells();
assert.equal(cells.show, true);
assert.equal(cells.spec.clampTo, 'both');
const items = [...cells.items.values()];
// Global band: 2° cells; the two Texas fires share one.
assert.equal(items.length, 2);
const texas = items.find((item) => item.geometry.rect.west === -100);
assert.deepEqual(texas.geometry, {
kind: 'rectangle',
rect: { west: -100, south: 30, east: -98, north: 32 },
});
assert.equal(texas.height, 'clampGround');
// The hottest cell: red at the top of the alpha ramp.
assert.deepEqual(texas.fill, [1, 0, 0, 0.66]);
const other = items.find((item) => item !== texas);
assert.equal(other.fill.length, 4);
assert.ok(other.fill[3] >= 0.16 && other.fill[3] < 0.66);
h.layer.disable();
assert.equal(h.cells().show, false, 'hidden with the layer');
h.layer.destroy(h.viewer);
assert.equal(h.cells(), undefined, 'destroy disposes the set');
} finally {
h.cleanup();
}
});
test('close in, detections replace the cells', async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000);
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
assert.equal(h.cells().items.size, 1);
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
500_000,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
500_000,
);
// A frame past the LOD check's throttle, however fast the start was.
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
try {
h.viewer.scene.preRender.raiseEvent();
} finally {
performance.now = now;
}
assert.equal(h.cells().items.size, 0, 'no cells in a detections band');
} finally {
h.cleanup();
}
});
test("with no query or frame port, the layer still follows the camera through the viewer's scene", async () => {
const h = harness([raw(30.5, -98.2, 1500)], 12_000_000, {
sceneFromViewer: true,
});
try {
h.layer.init(h.viewer);
await h.layer.enable(h.viewer);
assert.equal(h.cells().items.size, 1);
h.viewer.camera.positionCartographic = Cesium.Cartographic.fromDegrees(
-97.7,
30.2,
500_000,
);
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7,
30.2,
500_000,
);
// A frame past the LOD check's throttle, however fast the start was.
const now = performance.now;
performance.now = () => now.call(performance) + 10_000;
try {
h.viewer.scene.preRender.raiseEvent();
} finally {
performance.now = now;
}
assert.equal(h.cells().items.size, 0, 'no cells in a detections band');
} finally {
h.cleanup();
}
});
+1 -1
View File
@@ -15,7 +15,7 @@ export function createIngestion({
/** Replace a validated snapshot while preserving source freshness and selection identity. */
async function loadHeatmap() {
if (!layerState._dataSource || !layerState._enabled) return;
if (!layerState._cells || !layerState._enabled) return;
layerState.request?.abort();
const request = new AbortController();
layerState.request = request;
+18 -11
View File
@@ -1,6 +1,13 @@
import * as Cesium from 'cesium';
import { drawOf } from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
/**
* The heat cells' draw sets start with this; each layer has its own
* (`firms:1:cells`, …), so several can share a renderer.
*/
export const FIRMS_CELL_SET_PREFIX = 'firms';
let instances = 0;
export function createLifecycle({
layerState,
services,
@@ -17,17 +24,19 @@ export function createLifecycle({
init(viewer) {
if (layerState._destroyed) return;
layerState._viewer = viewer;
layerState._dataSource = new Cesium.CustomDataSource(id);
layerState._dataSource.show = false;
viewer.dataSources.add(layerState._dataSource);
layerState._cells = drawOf(viewer).shapes({
id: `${FIRMS_CELL_SET_PREFIX}:${++instances}:cells`,
clampTo: 'both',
show: false,
});
},
async enable(viewer) {
if (layerState._destroyed) return;
layerState._enabled = true;
layerState._viewer = viewer;
if (!layerState._dataSource) this.init(viewer);
if (layerState._dataSource) layerState._dataSource.show = true;
if (!layerState._cells) this.init(viewer);
if (layerState._cells) layerState._cells.show = true;
// The GPU culls the far side each frame, so retained rows are right
// for wherever the camera went while the layer was off.
if (layerState._icons) layerState._icons.show = true;
@@ -54,7 +63,7 @@ export function createLifecycle({
layerState._loading = false;
layerState._enabled = false;
components.selection.clearFireSelection();
if (layerState._dataSource) layerState._dataSource.show = false;
if (layerState._cells) layerState._cells.show = false;
if (layerState._icons) layerState._icons.show = false;
overlayHost.clearSource(FIRMS_OVERLAY_SOURCE_ID);
overlayHost.setVisible(FIRMS_OVERLAY_SOURCE_ID, false);
@@ -76,10 +85,8 @@ export function createLifecycle({
components.viewport.removeMoveEndWatcher();
components.selection.removeClickHandler();
unregisterPickOwner(id);
if (layerState._dataSource && viewer) {
viewer.dataSources.remove(layerState._dataSource, true);
}
layerState._dataSource = null;
layerState._cells?.dispose();
layerState._cells = null;
components.rendering.removeDetectionCollections(viewer);
components.selection.clearContextRegistrations();
clearSelectedEntityContextForLayer(id);
+39 -35
View File
@@ -1,4 +1,11 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { rectangleHeight, rectangleWidth } from '../../geo/rectangle.js';
import {
PI_OVER_TWO,
TWO_PI,
negativePiToPi,
toDegrees,
} from '../../geo/vector.js';
import { formatNumber, getLocale, isolate, t, tn } from '../../i18n/index.js';
import {
satelliteShortName,
@@ -58,35 +65,36 @@ export function createModel({
* Expand a view rectangle by VIEW_PADDING per side and convert to degree
* bounds with an explicit anti-meridian wrap flag. Returns null for
* near-global views where clipping would be pointless.
* @param {Cesium.Rectangle} rect - Camera view rectangle (radians).
* @param {{west: number, south: number, east: number, north: number}} rect
* Camera view rectangle, radians.
* @returns {?{west: number, south: number, east: number, north: number, wraps: boolean}}
*/
function paddedDegreeBounds(rect) {
const width = Cesium.Rectangle.computeWidth(rect);
const height = Cesium.Rectangle.computeHeight(rect);
const width = rectangleWidth(rect);
const height = rectangleHeight(rect);
if (width >= Math.PI * 1.85) return null;
const padLon = width * VIEW_PADDING;
const padLat = height * VIEW_PADDING;
const south = Math.max(-Cesium.Math.PI_OVER_TWO, rect.south - padLat);
const north = Math.min(Cesium.Math.PI_OVER_TWO, rect.north + padLat);
const south = Math.max(-PI_OVER_TWO, rect.south - padLat);
const north = Math.min(PI_OVER_TWO, rect.north + padLat);
let west = rect.west - padLon;
let east = rect.east + padLon;
let wraps;
if (width + padLon * 2 >= Cesium.Math.TWO_PI) {
if (width + padLon * 2 >= TWO_PI) {
west = -Math.PI;
east = Math.PI;
wraps = false;
} else {
west = Cesium.Math.negativePiToPi(west);
east = Cesium.Math.negativePiToPi(east);
west = negativePiToPi(west);
east = negativePiToPi(east);
wraps = west > east;
}
return {
west: Cesium.Math.toDegrees(west),
south: Cesium.Math.toDegrees(south),
east: Cesium.Math.toDegrees(east),
north: Cesium.Math.toDegrees(north),
west: toDegrees(west),
south: toDegrees(south),
east: toDegrees(east),
north: toDegrees(north),
wraps,
};
}
@@ -119,17 +127,17 @@ export function createModel({
);
}
/** A cell's heat colour, `[r, g, b, alpha]`, on the detection stops. */
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);
const stop = DETECTION_COLOR_STOPS[value > 0.72 ? 0 : value > 0.42 ? 1 : 2];
return [stop.color[0], stop.color[1], stop.color[2], alpha];
}
/**
* Pick a sprite color stop from FRP + confidence, reusing the same
* yellow → orange → red thresholds as the aggregated heat cells.
* @param {Object} fire - Detection record.
* @returns {{name: string, color: Cesium.Color}}
* @returns {{name: string, color: number[]}}
*/
function detectionColorStop(fire) {
@@ -162,7 +170,7 @@ export function createModel({
* through the stop color to a transparent edge. The glow lives in the
* 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 {{name: string, color: number[]}} stop - Color stop.
* @returns {string} PNG data URL.
*/
@@ -178,9 +186,9 @@ export function createModel({
if (!context) return '';
const radius = dimension / 2;
const rgb = [
Math.round(stop.color.red * 255),
Math.round(stop.color.green * 255),
Math.round(stop.color.blue * 255),
Math.round(stop.color[0] * 255),
Math.round(stop.color[1] * 255),
Math.round(stop.color[2] * 255),
].join(',');
const gradient = context.createRadialGradient(
radius,
@@ -203,7 +211,7 @@ export function createModel({
}
/**
* Lazily-cached Cartesian3 anchor at the shared ground floor (DEM/mesh cell
* Lazily-cached ECEF anchor at the shared ground floor (DEM/mesh cell
* + lift) when the floor is warm, else ellipsoid height 0 (owner field
* finding 2026-07-21: height-0 anchors read as buried under high terrain at
* close/oblique zoom). Warm-cache read only — floors are warmed in batch by
@@ -214,13 +222,13 @@ export function createModel({
* free either way (contacts are ALWAYS visible — never below the surface,
* slightly above is fine).
* @param {Object} fire - Detection record.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function firePosition(fire) {
const height = fireAnchorHeight(fire.lat, fire.lon);
if (!fire.position || fire.positionHeight !== height) {
fire.position = Cesium.Cartesian3.fromDegrees(fire.lon, fire.lat, height);
fire.position = fromDegrees(fire.lon, fire.lat, height);
fire.positionHeight = height;
}
return fire.position;
@@ -237,18 +245,14 @@ export function createModel({
* feeds rendering: the datum-correct anchor from {@link firePosition} is what
* the sprite and the card are drawn at.
* @param {Object} fire - Detection record.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function fireCullPosition(fire) {
const position = firePosition(fire);
if (fire.positionHeight >= ICON_CULL_HEIGHT_M) return position;
if (!fire.cullPosition) {
fire.cullPosition = Cesium.Cartesian3.fromDegrees(
fire.lon,
fire.lat,
ICON_CULL_HEIGHT_M,
);
fire.cullPosition = fromDegrees(fire.lon, fire.lat, ICON_CULL_HEIGHT_M);
}
return fire.cullPosition;
}
@@ -259,18 +263,18 @@ export function createModel({
* boundary case, so they get the same lift as sub-ellipsoid fire anchors.
* @param {number} lon - Cell center longitude in degrees.
* @param {number} lat - Cell center latitude in degrees.
* @returns {Cesium.Cartesian3}
* @returns {{x: number, y: number, z: number}} ECEF.
*/
function cellCullPosition(lon, lat) {
return Cesium.Cartesian3.fromDegrees(lon, lat, ICON_CULL_HEIGHT_M);
return fromDegrees(lon, lat, ICON_CULL_HEIGHT_M);
}
/**
* True when `screen` is at least LABEL_MIN_SEP_PX away from every accepted
* screen position (greedy declutter accept test).
* @param {Array<{x: number, y: number}>} accepted - Accepted label positions.
* @param {Cesium.Cartesian2} screen - Candidate window coordinates.
* @param {{x: number, y: number}} screen - Candidate window coordinates.
* @returns {boolean}
*/
@@ -331,7 +335,7 @@ export function createModel({
* "high · 14h · N20". Ages are computed against each detection's acquisition
* time — with the live feed everything reads under 24 h (and a stale cache
* reads truthfully old). Exported for unit tests.
* @param {{fire: Object, position: Cesium.Cartesian3}} candidate - Label candidate.
* @param {{fire: Object, position: {x: number, y: number, z: number}}} candidate - Label candidate.
* @param {number} nowMs - Current epoch milliseconds.
* @returns {Object} firmsLabels entry.
*/
@@ -363,7 +367,7 @@ 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.
* @param {{cell: Object, position: Cesium.Cartesian3, accent: string}} candidate
* @param {{cell: Object, position: {x: number, y: number, z: number}, accent: string}} candidate
* @param {number} nowMs - Current epoch milliseconds.
* @returns {Object} firmsLabels entry.
*/
+7 -5
View File
@@ -1,5 +1,4 @@
import { FIRMS_AMBIENT_COHORT_LIMIT } from '../../data/firmsLabels.js';
import * as Cesium from 'cesium';
/** Client poll interval; the proxy's 30 min TTL is what guards upstream quota. */
@@ -80,10 +79,13 @@ export const LABEL_VIEW_MARGIN_PX = 16;
export const GLOW_SPRITE_PX = 56;
/** Color stops shared by cell heat fills and detection glow sprites. */
/**
* Color stops shared by cell heat fills and detection glow sprites, as
* renderer colours `[r, g, b, a]` (CSS red, orange and yellow).
*/
export const DETECTION_COLOR_STOPS = [
{ name: 'red', color: Cesium.Color.RED },
{ name: 'orange', color: Cesium.Color.ORANGE },
{ name: 'yellow', color: Cesium.Color.YELLOW },
{ name: 'red', color: Object.freeze([1, 0, 0, 1]) },
{ name: 'orange', color: Object.freeze([1, 165 / 255, 0, 1]) },
{ name: 'yellow', color: Object.freeze([1, 1, 0, 1]) },
];
+2 -1
View File
@@ -130,7 +130,8 @@ export function createQueries({
* layer's greedy declutter as the SELECTOR and the shared overlay remains
* the renderer. Walks the FRP-sorted index so the strongest fires come first.
* @param {{maxCount?: number}} [options]
* @returns {Array<{position: Cesium.Cartesian3, id: string, type: string}>}
* @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string}>}
* Positions are ECEF.
*/
getDetectableObjects(options = {}) {
if (!layerState._enabled || !layerState._firesByFrp.length) return [];
+73 -41
View File
@@ -1,7 +1,13 @@
import * as Cesium from 'cesium';
// Still Cesium for its icons, so this layer loads the unbound camera and
// draw factories its other parts reach the renderer through; see also
// scenePorts below.
import '../../render/cesium/camera.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { rendererOf } from '../../render/rendererOf.js';
import { FIRMS_OVERLAY_SOURCE_ID } from '../../data/firmsLabels.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { LOD_LEVELS, CONTEXT_TOP_N, GLOW_SPRITE_PX } from './policy.js';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { createIconSet, ICON_CULL_LIFT } from '../../data/iconSet.js';
import { writeHoldSegment } from '../../data/iconSegment.js';
import { IconSetPrimitive } from '../../data/iconSetPrimitive.js';
@@ -27,7 +33,7 @@ export function createRendering({
*/
function renderCurrentLod(force = false) {
if (!layerState._dataSource || !layerState._viewer) return false;
if (!layerState._cells || !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
@@ -48,9 +54,7 @@ export function createRendering({
return false;
layerState._currentLodIndex = lodIndex;
layerState._currentLodId = lod.id;
layerState._lastViewRect = viewRect
? Cesium.Rectangle.clone(viewRect)
: null;
layerState._lastViewRect = viewRect ? { ...viewRect } : null;
const bounds = viewRect
? components.model.paddedDegreeBounds(viewRect)
: null;
@@ -63,8 +67,13 @@ export function createRendering({
return true;
}
/** Take every heat cell down (no write when there are none). */
function clearCells() {
if (layerState._cells?.size()) layerState._cells.clear();
}
function clearRendered() {
layerState._dataSource.entities.removeAll();
clearCells();
layerState._icons?.clear();
layerState._pickIndexById.clear();
layerState._cellCount = 0;
@@ -134,7 +143,7 @@ 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
* rectangles, one draw set. Cell labels do NOT live on the cells — they go
* through the same unclamped, screen-space-decluttered label pipeline as
* detections (see {@link rebuildAmbientLabels}).
* @param {Array<Object>} cells - Aggregated cells, heat-sorted descending.
@@ -144,7 +153,6 @@ export function createRendering({
function renderCells(cells, lod, bounds) {
ensureDetectionCollections();
layerState._dataSource.entities.removeAll();
layerState._icons?.clear();
layerState._pickIndexById.clear();
layerState._cellCount = cells.length;
@@ -153,6 +161,7 @@ export function createRendering({
layerState._labelCandidates = [];
layerState._labelLodDistance = lod.labelDistance;
const items = [];
for (const cell of cells) {
const score = components.model.heatScore(cell);
const normalized = Math.min(1, Math.sqrt(score / maxScore));
@@ -160,26 +169,21 @@ export function createRendering({
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);
const position = 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,
items.push({
id: `firms-cell:${lod.gridDegrees}:${cell.latCell}:${cell.lonCell}`,
geometry: {
kind: 'rectangle',
rect: {
west: cell.lonCell,
south: cell.latCell,
east: cell.lonCell + lod.gridDegrees,
north: cell.latCell + lod.gridDegrees,
},
},
fill: color,
height: 'clampGround',
});
// Cells arrive heat-sorted, so candidate order doubles as label priority.
@@ -193,6 +197,7 @@ export function createRendering({
});
}
layerState._cells.set(items);
components.cards.rebuildAmbientLabels();
components.selection.refreshContextRegistrations(
components.selection.topFiresWithinBounds(bounds),
@@ -216,7 +221,7 @@ export function createRendering({
function renderDetections(lod, bounds) {
ensureDetectionCollections();
layerState._dataSource.entities.removeAll();
clearCells();
const set = layerState._icons;
if (!set) return;
layerState._pickIndexById.clear();
@@ -366,29 +371,56 @@ export function createRendering({
}
/**
* Shared horizon occluder positioned at the current camera, or null when
* there is no usable camera yet (init order / headless stubs).
* `viewer.camera` and `viewer.scene.camera` are the SAME object in Cesium;
* both are probed so a partial stub (either shape) still gets a real
* occluder rather than silently degrading to "nothing is ever occluded".
* @returns {?Cesium.EllipsoidalOccluder}
* The renderer's query and frame ports the cards and the LOD watcher use.
* A viewer with no renderer bound has neither yet;
* for one, this part (Cesium already, for its icons) answers the members
* the layer uses over the viewer's scene, as the layer did before.
* @returns {{query: object|null, frame: object|null}}
*/
function fireHorizonOccluder() {
const camera = layerState._viewer?.camera?.positionWC
? layerState._viewer.camera
: layerState._viewer?.scene?.camera;
if (!camera?.positionWC) return null;
return horizonOccluder(camera);
function scenePorts() {
const viewer = layerState._viewer;
const bound = rendererOf(viewer);
if (bound?.query && bound?.frame)
return { query: bound.query, frame: bound.frame };
const scene = viewer?.scene;
if (!scene)
return { query: bound?.query ?? null, frame: bound?.frame ?? null };
const eye = () =>
viewer.camera?.positionWC ? viewer.camera : scene.camera;
const query = bound?.query ?? {
project(position) {
const screen = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
Cesium.Cartesian3.clone(position),
);
return screen ? { x: screen.x, y: screen.y } : null;
},
isOccluded(position) {
const camera = eye();
if (!camera?.positionWC) return false;
return !horizonOccluder(camera).isPointVisible(
Cesium.Cartesian3.clone(position),
);
},
};
const frame = bound?.frame ?? {
on(phase, listener) {
const event = scene[phase];
return event?.addEventListener
? event.addEventListener(listener)
: () => {};
},
};
return { query, frame };
}
return {
scenePorts,
renderCurrentLod,
aggregateFires,
renderCells,
renderDetections,
ensureDetectionCollections,
removeDetectionCollections,
fireHorizonOccluder,
};
}
+2 -1
View File
@@ -184,7 +184,8 @@ export function createSelection({
layerId: id,
layerName: name,
source: 'NASA FIRMS',
dataSource: layerState._dataSource,
// Hidden with the layer: the context store reads its `show`.
dataSource: layerState._cells,
// i18n-ignore: English entity label; the voice card translates it (shownEntityLabel)
label: `Fire · FRP ${components.model.formatFrp(fire.frp)} MW`,
latitude: fire.lat,
+5 -13
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export function createFirmsState({ services, config }) {
const layerState = {};
@@ -7,17 +5,11 @@ export function createFirmsState({ services, config }) {
layerState.glowSpriteCache = new Map();
layerState.scratchViewRect = new Cesium.Rectangle();
layerState.scratchCenterA = new Cesium.Cartographic();
layerState.scratchCenterB = new Cesium.Cartographic();
layerState.scratchWindowCoord = new Cesium.Cartesian2();
layerState._viewer = null;
layerState._dataSource = null;
/** The heat cells' draw set (made at `init`). */
layerState._cells = null;
/** Detection glow rows and the primitive that draws them. */
@@ -101,9 +93,9 @@ export function createFirmsState({ services, config }) {
layerState._camSnapValid = false;
layerState._camPos = new Cesium.Cartesian3();
layerState._camPos = { x: 0, y: 0, z: 0 };
layerState._camDir = new Cesium.Cartesian3();
layerState._camDir = { x: 0, y: 0, z: 0 };
layerState.request = null;
return layerState;
}
+71 -64
View File
@@ -1,4 +1,10 @@
import * as Cesium from 'cesium';
import {
rectangleCenter,
rectangleHeight,
rectangleWidth,
} from '../../geo/rectangle.js';
import { TWO_PI, toRadians } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
import {
LOD_LEVELS,
LOD_HYSTERESIS,
@@ -6,6 +12,12 @@ import {
LOD_CHECK_MS,
} from './policy.js';
/** Each component of `a` within `epsilon` of `b`'s. */
const near = (a, b, epsilon) =>
Math.abs(a.x - b.x) <= epsilon &&
Math.abs(a.y - b.y) <= epsilon &&
Math.abs(a.z - b.z) <= epsilon;
export function createViewport({
layerState,
services,
@@ -14,6 +26,7 @@ export function createViewport({
feed,
}) {
const { governorRequestRender } = services.render;
const camera = () => findCamera(layerState._viewer);
/**
* Ambient labels are placed via screen-space projection, so they need a
@@ -23,10 +36,10 @@ export function createViewport({
function installMoveEndWatcher() {
if (layerState._moveEndRemover || !layerState._viewer) return;
layerState._moveEndRemover =
layerState._viewer.camera.moveEnd.addEventListener(() => {
camera()?.on('moveEnd', () => {
if (!layerState._enabled || layerState._loading) return;
components.cards.rebuildAmbientLabels();
});
}) ?? null;
}
function removeMoveEndWatcher() {
@@ -37,10 +50,8 @@ export function createViewport({
}
function cameraHeight() {
return (
layerState._viewer?.camera?.positionCartographic?.height ??
Number.POSITIVE_INFINITY
);
const height = camera()?.pose().height;
return Number.isFinite(height) ? height : Number.POSITIVE_INFINITY;
}
/** Raw LOD index for a camera height (0 = global ... 3 = close). */
@@ -78,15 +89,21 @@ export function createViewport({
return index;
}
/** Current camera view rectangle, or null when looking at sky/horizon. */
/**
* Current camera view rectangle, radians, or null when looking at
* sky/horizon.
*/
function computeViewRect() {
try {
const rect = layerState._viewer?.camera?.computeViewRectangle(
layerState._viewer?.scene?.globe?.ellipsoid,
layerState.scratchViewRect,
);
return rect || null;
const rect = camera()?.viewRectangle();
if (!rect) return null;
return {
west: toRadians(rect.west),
south: toRadians(rect.south),
east: toRadians(rect.east),
north: toRadians(rect.north),
};
} catch {
return null;
}
@@ -96,27 +113,25 @@ export function createViewport({
* True when the camera view rectangle drifted far enough from the last
* rendered one that the padding is at risk of being consumed (pan) or
* the footprint changed notably (zoom within a band).
* @param {?Cesium.Rectangle} viewRect - Current view rectangle.
* @param {?{west: number, south: number, east: number, north: number}} viewRect
* Current view rectangle, radians.
* @returns {boolean}
*/
function viewChangedEnough(viewRect) {
if (!viewRect) return false; // sky/horizon — keep the current render
if (!layerState._lastViewRect) return true; // previous render was global fallback
const lastWidth = Cesium.Rectangle.computeWidth(layerState._lastViewRect);
const lastHeight = Cesium.Rectangle.computeHeight(layerState._lastViewRect);
const width = Cesium.Rectangle.computeWidth(viewRect);
const height = Cesium.Rectangle.computeHeight(viewRect);
const lastWidth = rectangleWidth(layerState._lastViewRect);
const lastHeight = rectangleHeight(layerState._lastViewRect);
const width = rectangleWidth(viewRect);
const height = rectangleHeight(viewRect);
if (width > lastWidth * 1.3 || width < lastWidth * 0.75) return true;
if (height > lastHeight * 1.3 || height < lastHeight * 0.75) return true;
const lastCenter = Cesium.Rectangle.center(
layerState._lastViewRect,
layerState.scratchCenterA,
);
const center = Cesium.Rectangle.center(viewRect, layerState.scratchCenterB);
const latShift = Math.abs(center.latitude - lastCenter.latitude);
let lonShift = Math.abs(center.longitude - lastCenter.longitude);
if (lonShift > Math.PI) lonShift = Cesium.Math.TWO_PI - lonShift;
const lastCenter = rectangleCenter(layerState._lastViewRect);
const center = rectangleCenter(viewRect);
const latShift = Math.abs(center.lat - lastCenter.lat);
let lonShift = Math.abs(center.lon - lastCenter.lon);
if (lonShift > Math.PI) lonShift = TWO_PI - lonShift;
return (
latShift > lastHeight * VIEW_PADDING * 0.6 ||
lonShift > lastWidth * VIEW_PADDING * 0.6
@@ -130,50 +145,42 @@ export function createViewport({
// for a frame that idle mode never produces — schedule one. (perf wave 2)
if (!layerState._moveEndSettleRemover) {
layerState._moveEndSettleRemover =
layerState._viewer.camera.moveEnd.addEventListener(() => {
camera()?.on('moveEnd', () => {
if (!layerState._enabled) return;
setTimeout(
() => governorRequestRender('firms-lod-settle'),
LOD_CHECK_MS + 40,
);
});
}) ?? null;
}
layerState._preRenderRemover =
layerState._viewer.scene.preRender.addEventListener(() => {
// NOTE: `_loading`/empty-data are deliberately NOT part of this guard.
// A refresh has no timeout, and sprites from the previous payload stay
// on screen throughout it — so the horizon pass below must keep running
// while a fetch is in flight. Only the rebuild is gated on fresh data.
if (!layerState._enabled) return;
const now = performance.now();
if (now - layerState._lastLodCheck < LOD_CHECK_MS) return;
layerState._lastLodCheck = now;
// Idle camera: two scratch compares and out — no view-rect math, no
// aggregation, no allocation while the user is parked.
const camera = layerState._viewer.camera;
if (
layerState._camSnapValid &&
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
layerState._camPos,
0,
0.5,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
layerState._camDir,
0,
1e-7,
)
) {
return;
}
Cesium.Cartesian3.clone(camera.positionWC, layerState._camPos);
Cesium.Cartesian3.clone(camera.directionWC, layerState._camDir);
layerState._camSnapValid = true;
if (layerState._fires.length && !layerState._loading)
components.rendering.renderCurrentLod(false);
});
const { frame } = components.rendering.scenePorts();
if (!frame) return;
layerState._preRenderRemover = frame.on('preRender', () => {
// NOTE: `_loading`/empty-data are deliberately NOT part of this guard.
// A refresh has no timeout, and sprites from the previous payload stay
// on screen throughout it — so the horizon pass below must keep running
// while a fetch is in flight. Only the rebuild is gated on fresh data.
if (!layerState._enabled) return;
const now = performance.now();
if (now - layerState._lastLodCheck < LOD_CHECK_MS) return;
layerState._lastLodCheck = now;
// Idle camera: two compares and out — no view-rect math and no
// aggregation while the user is parked.
const pose = camera()?.pose();
if (!pose) return;
if (
layerState._camSnapValid &&
near(pose.position, layerState._camPos, 0.5) &&
near(pose.direction, layerState._camDir, 1e-7)
) {
return;
}
layerState._camPos = pose.position;
layerState._camDir = pose.direction;
layerState._camSnapValid = true;
if (layerState._fires.length && !layerState._loading)
components.rendering.renderCurrentLod(false);
});
}
function removeLodWatcher() {