diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index aad5932ec..7b7ae510c 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1757,10 +1757,23 @@ "src/data/iconOrientation.js", "src/layers/firms/anchors.js", "src/layers/firms/cards.js", + "src/geo/index.js", + "src/render/rendererOf.js", + "src/render/cesium/camera.js", + "src/render/camera/events.js", + "src/geo/celestial.js", + "src/geo/quaternion.js", + "src/geo/frames.js", + "src/render/cesium/credits.js", + "src/render/creditMarkup.js", + "src/render/cesium/draw.js", "src/layers/firms/index.js", "src/layers/firms/ingestion.js", "src/layers/firms/lifecycle.js", "src/layers/firms/model.js", + "src/geo/ellipsoid.js", + "src/geo/rectangle.js", + "src/geo/vector.js", "src/layers/firms/policy.js", "src/layers/firms/queries.js", "src/layers/firms/rendering.js", diff --git a/src/data/firmsCards.test.mjs b/src/data/firmsCards.test.mjs index 09e51e4d0..355ffeee9 100644 --- a/src/data/firmsCards.test.mjs +++ b/src/data/firmsCards.test.mjs @@ -17,6 +17,7 @@ import { FIRE_ANCHOR_LIFT_M } from './fireAnchors.js'; import { getLocale, setLocale } from '../i18n/index.js'; import { reportMeshFloorCell, setMeshFloorPreferred } from './groundFloor.js'; import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; const NOW = Date.UTC(2026, 6, 17, 4, 0); const H = 3600000; @@ -217,6 +218,7 @@ test('real FIRMS lifecycle clears host entries on disable and destroy', async () primitives: { contains() { return false; } }, }, }; + bindFakeCesiumScene(viewer); fakeInput(viewer); const layer = createFirmsHeatmapLayer({ id: 'firms', diff --git a/src/data/firmsHorizonCull.test.mjs b/src/data/firmsHorizonCull.test.mjs index c6ae77b9b..0f8076daa 100644 --- a/src/data/firmsHorizonCull.test.mjs +++ b/src/data/firmsHorizonCull.test.mjs @@ -14,6 +14,7 @@ import { isOverlayPointVisible, normalizeOverlayEntry } from '../overlays/worldO import { createIconSet, ICON_CULL_LIFT } from './iconSet.js'; import { writeHoldSegment } from './iconSegment.js'; import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; const AUSTIN = { lon: -97.7, lat: 30.2 }; /** Antipode of Austin — as far behind the limb as a point on Earth can be. */ @@ -379,6 +380,7 @@ function createHarness(rawFires) { mapProjection: new Cesium.GeographicProjection(), }, }; + bindFakeCesiumScene(viewer); fakeInput(viewer); const layer = createFirmsHeatmapLayer({ diff --git a/src/data/firmsInteraction.test.mjs b/src/data/firmsInteraction.test.mjs index 77e1f8d49..d4a4538b6 100644 --- a/src/data/firmsInteraction.test.mjs +++ b/src/data/firmsInteraction.test.mjs @@ -16,6 +16,7 @@ import { readLayerSource } from '../testSupport/readLayerSource.mjs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; import { fakeInput } from '../input/testDoubles.mjs'; +import { bindFakeCesiumScene } from '../testSupport/fakeCesiumScene.mjs'; const LAYER_SOURCE = readLayerSource( path.join(path.dirname(fileURLToPath(import.meta.url)), 'firmsHeatmap.js'), @@ -81,6 +82,7 @@ function harness({ }, dataSources: { add() {}, remove() {} }, }; + bindFakeCesiumScene(viewer); const input = fakeInput(viewer); // The LOD rebuild (and with it the context-registration sweep) is inert // without a data source, so tests that drive a real refresh need one. diff --git a/src/layers/firms/cards.js b/src/layers/firms/cards.js index c99d29e1c..d29ca7644 100644 --- a/src/layers/firms/cards.js +++ b/src/layers/firms/cards.js @@ -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 || diff --git a/src/layers/firms/cells.test.mjs b/src/layers/firms/cells.test.mjs new file mode 100644 index 000000000..8ea76acf6 --- /dev/null +++ b/src/layers/firms/cells.test.mjs @@ -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(); + } +}); diff --git a/src/layers/firms/ingestion.js b/src/layers/firms/ingestion.js index 494ab5f1e..2a9c949eb 100644 --- a/src/layers/firms/ingestion.js +++ b/src/layers/firms/ingestion.js @@ -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; diff --git a/src/layers/firms/lifecycle.js b/src/layers/firms/lifecycle.js index 2b5740335..5e0e5dc50 100644 --- a/src/layers/firms/lifecycle.js +++ b/src/layers/firms/lifecycle.js @@ -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); diff --git a/src/layers/firms/model.js b/src/layers/firms/model.js index a6fc1028e..b759e3288 100644 --- a/src/layers/firms/model.js +++ b/src/layers/firms/model.js @@ -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. */ diff --git a/src/layers/firms/policy.js b/src/layers/firms/policy.js index 72ecf2db1..fcd4cd41a 100644 --- a/src/layers/firms/policy.js +++ b/src/layers/firms/policy.js @@ -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]) }, ]; diff --git a/src/layers/firms/queries.js b/src/layers/firms/queries.js index 0656abf16..0a3a9c41b 100644 --- a/src/layers/firms/queries.js +++ b/src/layers/firms/queries.js @@ -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 []; diff --git a/src/layers/firms/rendering.js b/src/layers/firms/rendering.js index 34257718e..7ecc72245 100644 --- a/src/layers/firms/rendering.js +++ b/src/layers/firms/rendering.js @@ -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} 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, }; } diff --git a/src/layers/firms/selection.js b/src/layers/firms/selection.js index b89a3ae6e..ddc53cb1d 100644 --- a/src/layers/firms/selection.js +++ b/src/layers/firms/selection.js @@ -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, diff --git a/src/layers/firms/state.js b/src/layers/firms/state.js index 4b33afeff..a77c56cc3 100644 --- a/src/layers/firms/state.js +++ b/src/layers/firms/state.js @@ -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; } diff --git a/src/layers/firms/viewport.js b/src/layers/firms/viewport.js index 5ea2b191a..5b200e2f7 100644 --- a/src/layers/firms/viewport.js +++ b/src/layers/firms/viewport.js @@ -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() { diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index ae4ab4761..9ba356c15 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -851,3 +851,83 @@ test('the GNSS layer draws its cells as ground fills that stay out of the pick p layer.destroy(); assert.equal(scene.added.length, 0); }); + +test('the fires layer draws its heat cells as ground fills through the Cesium draw port', async (t) => { + const { createFirmsHeatmapLayer } = + await import('../../data/firmsHeatmap.js'); + const { unregisterSpriteCollection } = + await import('../../data/spriteOrder.js'); + const { fakeInput } = await import('../../input/testDoubles.mjs'); + const { bindFakeCesiumScene } = + await import('../../testSupport/fakeCesiumScene.mjs'); + const saved = globalThis.window; + globalThis.window = new EventTarget(); + const scene = fakeScene(); + // The layer keeps its detection icons over other sprites. + scene.primitives.contains = (p) => scene.added.includes(p); + scene.primitives.raiseToTop = () => {}; + // Far out, where the layer draws heat cells rather than detections. + const viewer = { + scene, + camera: { + moveEnd: new Cesium.Event(), + positionWC: Cesium.Cartesian3.fromDegrees(-97.7, 30.2, 2e7), + directionWC: new Cesium.Cartesian3(0, 0, -1), + positionCartographic: Cesium.Cartographic.fromDegrees(-97.7, 30.2, 2e7), + }, + }; + // The real Cesium draw port; camera and frame from the viewer double. + const { unbind } = bindFakeCesiumScene(viewer, { draw: drawOf(viewer) }); + const input = fakeInput(viewer); + const raw = (lat, lon, frp) => ({ + lat, + lon, + frp, + confidence: 'h', + brightness: 340, + daynight: 'D', + acqDate: '2026-08-03', + acqTime: '0412', + instrument: 'VIIRS', + satellite: 'N20', + }); + const layer = createFirmsHeatmapLayer({ + id: 'firms', + name: 'FIRMS', + feed: { + getSnapshot: async () => ({ + fires: [raw(30.5, -98.2, 1500), raw(-12.1, 131.4, 5)], + fetchedAt: Date.now(), + }), + }, + overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} }, + }); + t.after(() => { + input.destroy(); + unbind(); + unregisterSpriteCollection('firms'); + if (saved === undefined) delete globalThis.window; + else globalThis.window = saved; + }); + layer.init(viewer); + await layer.enable(viewer); + const all = (host, out = []) => { + out.push(host); + if (host instanceof Cesium.PrimitiveCollection) + for (let i = 0; i < host.length; i++) all(host.get(i), out); + return out; + }; + const grounds = () => + scene.added + .flatMap((host) => all(host)) + .filter((p) => p instanceof Cesium.GroundPrimitive); + const instances = grounds().flatMap((g) => g.geometryInstances); + assert.equal(instances.length, 2, 'one fill per cell'); + for (const instance of instances) { + assert.ok(instance.geometry instanceof Cesium.RectangleGeometry); + assert.match(instance.id.set, /^firms:\d+:cells$/); + } + assert.equal(grounds()[0].classificationType, Cesium.ClassificationType.BOTH); + layer.destroy(viewer); + assert.equal(grounds().length, 0); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 1e18ab80c..d01749e65 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -63,13 +63,7 @@ "src/layers/cctv/state.js", "src/layers/cctv/testing.js", "src/layers/directions/index.js", - "src/layers/firms/cards.js", - "src/layers/firms/lifecycle.js", - "src/layers/firms/model.js", - "src/layers/firms/policy.js", "src/layers/firms/rendering.js", - "src/layers/firms/state.js", - "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", "src/layers/flights/evidence.js", diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs new file mode 100644 index 000000000..de6cb2cdb --- /dev/null +++ b/src/testSupport/fakeCesiumScene.mjs @@ -0,0 +1,107 @@ +/** + * Renderer ports over a Cesium-shaped viewer double, for tests of layers + * that reach the camera, projection, frame loop and drawing through the + * renderer: everything reads the double live, as the Cesium ports read + * their scene. + * + * - camera: `pose()` from the double's camera (`viewer.camera`, else + * `viewer.scene.camera`): `positionWC`, `directionWC` and + * `positionCartographic`; `viewRectangle()` from its + * `computeViewRectangle()`, in degrees; events from its own `moveEnd`, + * `moveStart` and `changed`. + * - query: `project` through `Cesium.SceneTransforms.worldToWindowCoordinates` + * (which a test may stub), `isOccluded` against the ellipsoid's horizon + * from the camera's `positionWC` (never occluded without one). + * - frame: phases from the scene's own `preUpdate`, `preRender` and + * `postRender` events. + * - draw: a fake draw port (`fakeDrawPort.mjs`) unless one is given. + */ +import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeDrawPort } from './fakeDrawPort.mjs'; + +const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z); +const plain = (c) => ({ x: c.x, y: c.y, z: c.z }); + +/** Subscribe to a Cesium-style event, if the double has it. */ +function listen(source, cb) { + const off = source?.addEventListener?.(cb); + if (typeof off === 'function') return off; + return () => source?.removeEventListener?.(cb); +} + +/** + * Bind the ports to `viewer`. + * @param {object} viewer + * @param {{draw?: object}} [options] + * @returns {{draw: object, camera: object, query: object, frame: object, unbind: () => void}} + */ +export function bindFakeCesiumScene(viewer, { draw = fakeDrawPort() } = {}) { + const cam = () => + viewer.camera?.positionWC || !viewer.scene?.camera + ? viewer.camera + : viewer.scene.camera; + const camera = { + pose() { + const c = cam(); + const carto = c?.positionCartographic; + const deg = (r) => + Number.isFinite(r) ? Cesium.Math.toDegrees(r) : Number.NaN; + return { + lon: deg(carto?.longitude), + lat: deg(carto?.latitude), + height: carto?.height ?? Number.NaN, + heading: c?.heading ?? 0, + pitch: c?.pitch ?? -Math.PI / 2, + roll: c?.roll ?? 0, + position: c?.positionWC ? plain(c.positionWC) : { x: 0, y: 0, z: 0 }, + direction: c?.directionWC + ? plain(c.directionWC) + : { x: 0, y: 0, z: -1 }, + up: { x: 0, y: 1, z: 0 }, + right: { x: 1, y: 0, z: 0 }, + fovy: Math.PI / 3, + aspectRatio: 1, + near: 1, + far: 5e8, + frameIsIdentity: true, + }; + }, + viewRectangle() { + const rect = cam()?.computeViewRectangle?.(); + if (!rect) return null; + const deg = Cesium.Math.toDegrees; + return { + west: deg(rect.west), + south: deg(rect.south), + east: deg(rect.east), + north: deg(rect.north), + }; + }, + on: (event, cb) => listen(cam()?.[event], cb), + }; + const query = { + project(position) { + // The position itself, so a stub can tell positions apart by identity. + const s = Cesium.SceneTransforms.worldToWindowCoordinates( + viewer.scene, + position, + ); + return s ? { x: s.x, y: s.y } : null; + }, + isOccluded(position) { + const eye = cam()?.positionWC; + if (!eye) return false; + return !new Cesium.EllipsoidalOccluder( + Cesium.Ellipsoid.WGS84, + eye, + ).isPointVisible(toCartesian(position)); + }, + }; + const frame = { + on: (phase, cb) => listen(viewer.scene?.[phase], cb), + requestRender: () => viewer.scene?.requestRender?.(), + }; + const unbind = bindRenderer(viewer, { draw, camera, query, frame }); + return { draw, camera, query, frame, unbind }; +}