Move the installations layer's camera, geometry and colours onto renderer ports

The layer's view rectangle, wide-view pose, flights and camera events now
go through the camera port, and its distance and position maths through
the geo helpers: getNearby confirms candidates with the ported
ellipsoidal geodesic, as before, and returns plain ECEF positions. Class
colours are renderer colours; the entities convert them. The layer's
camera `changed` listener has its own 0.01 threshold on the port, the
sensitivity it already claimed while on; the claim stays for other raw
camera listeners.

Controls, lifecycle, model, state and viewport no longer import Cesium
and leave the allow-list. Rendering and the named markers stay on
Cesium: the site markers are entities because the camera follows them
on double-click and the tracked card reads its title and position from
them, and the entity data source moves from lifecycle into rendering.
Rendering loads the unbound camera factory for the parts that reach the
port.

The test camera bound over a Cesium-shaped fake now answers its view
rectangle from the fake's computeViewRectangle when it has one.
This commit is contained in:
Sameh Khamis committed 2026-11-06 22:10:53 -08:00
1 parent e74c7c1f44
commit 1d2b853576
18 files changed
+126 -90

No files matched your search

+20 -26
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { describeInstallationFeedback } from '../../data/installationFeedback.js';
import {
LAYER_ID,
@@ -6,7 +5,10 @@ import {
ANCHOR_REFRESH_M,
} from './policy.js';
import { formatNumber, t, tn } from '../../i18n/index.js';
import { cameraOf } from '../../render/cesium/camera.js';
import { fromDegrees, toCartographicRadians } from '../../geo/ellipsoid.js';
import { surfaceDistance } from '../../geo/geodesic.js';
import { toDegrees, toRadians } from '../../geo/vector.js';
import { cameraOf } from '../../render/rendererOf.js';
// installationFeedback.js is shared with the HUD (src/loadingFeedback.js) and
// hands back msg()-marked English plus values; getStats translates them here.
@@ -66,7 +68,7 @@ export function createControls({ state: layerState, services, parts, source }) {
* only area that answers "what is near this contact". The window moves
* only after the subject travels ANCHOR_REFRESH_M, and cached tiles make
* that cheap. Passing null returns the layer to viewport loading.
* @param {Cesium.Cartesian3|{latitude:number, longitude:number}|null} position
* @param {{x:number, y:number, z:number}|{latitude:number, longitude:number}|null} position
* Subject position.
* @returns {boolean} Whether a new load was scheduled.
*/
@@ -79,17 +81,17 @@ export function createControls({ state: layerState, services, parts, source }) {
)
next = { latitude: position.latitude, longitude: position.longitude };
else {
const carto = Cesium.Cartographic.fromCartesian(position);
const carto = toCartographicRadians(position);
if (carto)
next = {
latitude: Cesium.Math.toDegrees(carto.latitude),
longitude: Cesium.Math.toDegrees(carto.longitude),
latitude: toDegrees(carto.lat),
longitude: toDegrees(carto.lon),
};
}
}
// Keep the live centre even when the coarse fetch anchor has not moved.
layerState.contextPosition = next
? Cesium.Cartesian3.fromDegrees(next.longitude, next.latitude)
? fromDegrees(next.longitude, next.latitude)
: null;
const previous = layerState.contextAnchor;
if (!next) {
@@ -101,8 +103,8 @@ export function createControls({ state: layerState, services, parts, source }) {
if (
previous &&
parts.model.approximateSurfaceDistanceM(
Cesium.Math.toRadians(previous.latitude),
Cesium.Math.toRadians(previous.longitude),
toRadians(previous.latitude),
toRadians(previous.longitude),
next.latitude,
next.longitude,
) < ANCHOR_REFRESH_M
@@ -116,7 +118,7 @@ export function createControls({ state: layerState, services, parts, source }) {
getNearby(center, rangeM, maxCount = 50) {
if (!center) return [];
const range = Number.isFinite(rangeM) ? rangeM : Infinity;
const centerCartographic = Cesium.Cartographic.fromCartesian(center);
const centerCartographic = toCartographicRadians(center);
if (!centerCartographic) return [];
const nearby = [];
const approximateLimit = Number.isFinite(range)
@@ -126,31 +128,23 @@ export function createControls({ state: layerState, services, parts, source }) {
if (record.kind !== 'installation') continue;
if (
parts.model.approximateSurfaceDistanceM(
centerCartographic.latitude,
centerCartographic.longitude,
centerCartographic.lat,
centerCartographic.lon,
record.latitude,
record.longitude,
) > approximateLimit
)
continue;
// The awareness disk is projected onto the ground. Confirm candidates
// with an exact ellipsoidal surface distance and reusable scratch state.
layerState.distanceEndpointScratch.longitude = Cesium.Math.toRadians(
record.longitude,
);
layerState.distanceEndpointScratch.latitude = Cesium.Math.toRadians(
record.latitude,
);
layerState.distanceEndpointScratch.height = 0;
layerState.distanceGeodesicScratch.setEndPoints(
centerCartographic,
layerState.distanceEndpointScratch,
);
const distanceM = layerState.distanceGeodesicScratch.surfaceDistance;
// with an exact ellipsoidal surface distance.
const distanceM = surfaceDistance(centerCartographic, {
lon: toRadians(record.longitude),
lat: toRadians(record.latitude),
});
if (!Number.isFinite(distanceM) || distanceM > range) continue;
nearby.push({
...record,
position: Cesium.Cartesian3.fromDegrees(
position: fromDegrees(
record.longitude,
record.latitude,
parts.rendering.installationSurfaceHeightM(record),
+17 -14
View File
@@ -1,5 +1,5 @@
import * as Cesium from 'cesium';
import { LAYER_ID } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
import { CAMERA_CHANGED_THRESHOLD, LAYER_ID } from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
@@ -17,17 +17,18 @@ export function createLifecycle({
const methods = {
init(viewer) {
layerState.viewer = viewer;
layerState.dataSource = new Cesium.CustomDataSource(
'military-installations',
);
viewer.dataSources.add(layerState.dataSource);
parts.rendering.attach(viewer);
const cameraChanged = () => {
if (!layerState.contextAnchor) parts.viewport.scheduleLoad();
};
layerState.moveEndRemove =
viewer.camera.moveEnd.addEventListener(cameraChanged);
layerState.changedRemove =
viewer.camera.changed?.addEventListener(cameraChanged);
const camera = cameraOf(viewer);
layerState.moveEndRemove = camera.on('moveEnd', cameraChanged);
// Measured for this listener alone; off, a load is never scheduled.
// The sensitivity claim in enable() is for raw camera listeners
// elsewhere, which this layer has always made finer while on.
layerState.changedRemove = camera.on('changed', cameraChanged, {
threshold: CAMERA_CHANGED_THRESHOLD,
});
parts.selection.installInteraction(viewer);
},
@@ -51,7 +52,11 @@ export function createLifecycle({
});
parts.namedMarkers?.enable();
parts.namedMarkers?.sync(layerState.records || []);
claimCameraSensitivity(layerState.viewer.camera, LAYER_ID, 0.01);
claimCameraSensitivity(
layerState.viewer.camera,
LAYER_ID,
CAMERA_CHANGED_THRESHOLD,
);
registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id));
layerState.dataSource.show = true;
// DataLayerManager invokes update() immediately after enable(), which owns
@@ -97,9 +102,7 @@ export function createLifecycle({
layerState.clickSubscription = null;
parts.namedMarkers?.destroy();
parts.rendering.clearRendered();
if (layerState.dataSource && viewer)
viewer.dataSources.remove(layerState.dataSource, true);
layerState.dataSource = null;
parts.rendering.detach(viewer);
},
};
+1 -1
View File
@@ -38,7 +38,7 @@ for (const source of [
markersVisible = false;
},
},
rendering: {},
rendering: { attach: noop, detach: noop },
viewport: { clearUnavailableRetry: noop },
ingestion: { setInstallationStatus: noop },
};
+6 -6
View File
@@ -1,5 +1,6 @@
import { installationResponseSaturated } from './source.js';
import * as Cesium from 'cesium';
import { toRadians } from '../../geo/vector.js';
import { hexColor } from '../../render/color.js';
import {
EARTH_MEAN_RADIUS_M,
COLOR_BY_CLASS,
@@ -18,8 +19,8 @@ export function createModel({ state: layerState, services, parts, source }) {
latitudeBDeg,
longitudeBDeg,
) {
const latitudeBRad = Cesium.Math.toRadians(latitudeBDeg);
const longitudeBRad = Cesium.Math.toRadians(longitudeBDeg);
const latitudeBRad = toRadians(latitudeBDeg);
const longitudeBRad = toRadians(longitudeBDeg);
const latitudeDelta = latitudeBRad - latitudeARad;
const longitudeDelta = Math.atan2(
Math.sin(longitudeBRad - longitudeARad),
@@ -38,10 +39,9 @@ export function createModel({ state: layerState, services, parts, source }) {
);
}
/** The record's class colour, as a renderer colour (`[r, g, b, a]`). */
function colorFor(record) {
return Cesium.Color.fromCssColorString(
COLOR_BY_CLASS[record.class] || '#9ca6b0',
);
return hexColor(COLOR_BY_CLASS[record.class] || '#9ca6b0');
}
/**
+1 -1
View File
@@ -157,7 +157,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
id: { installationId: record.id },
position,
pixelSize: 7,
color: parts.model.colorFor(record),
color: new Cesium.Color(...parts.model.colorFor(record)),
outlineColor: Cesium.Color.BLACK,
outlineWidth: 1,
disableDepthTestDistance: Infinity,
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import * as C from 'cesium';
import { createNamedMarkers } from './namedMarkers.js';
import { createLifecycle } from './lifecycle.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js';
function setup(t) {
@@ -20,9 +21,10 @@ function setup(t) {
t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', (_scene, _point, scratch) => { projections.add(scratch); scratch.x = x; scratch.y = 300; return scratch; });
const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), viewMatrix: C.Matrix4.clone(C.Matrix4.IDENTITY) };
const state = { viewer: { camera, dataSources: { add() {}, remove() {} }, scene: { canvas: { clientWidth: 1280, clientHeight: 800 }, preRender: new C.Event(), primitives: { add: (p) => p, remove() {} } } }, enabled: true, contextAnchor: { latitude: 0, longitude: 0 } };
bindFakeCesiumCamera(state.viewer);
const services = { render: { governorRequestRender() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} }, context: { clearSelectedEntityContextForLayer() {} } };
let loads = 0;
const parts = { model: { colorFor: () => C.Color.ORANGE }, rendering: { installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } };
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { attach() { state.dataSource = { show: false }; }, detach() {}, installationSurfaceHeightM: () => 0, clearRendered() {} }, viewport: { scheduleLoad: () => loads++, clearUnavailableRetry() {} }, selection: { installInteraction() {} }, ingestion: { setInstallationStatus() {} } };
const ctx = { state, services, parts, source: {}, overlayHost };
parts.namedMarkers = createNamedMarkers(ctx);
const lifecycle = createLifecycle(ctx).methods;
@@ -57,7 +59,7 @@ test('Contacts camera motion reprojects and declutters existing labels without s
assert.equal(h.publications(), 5);
h.lifecycle.destroy(h.state.viewer);
assert.equal(h.camera.changed.numberOfListeners, 0);
assert.equal(h.camera.moveEnd.numberOfListeners, 0);
assert.equal(h.camera.moveEnd.numberOfListeners, 1, "only the camera port's own");
assert.equal(h.state.viewer.scene.preRender.numberOfListeners, 0);
});
+16 -3
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createViewport } from './viewport.js';
import { createLifecycle } from './lifecycle.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and recover from wide views', (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
@@ -18,11 +19,18 @@ test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and
scene: { globe: { ellipsoid: Cesium.Ellipsoid.WGS84 } },
dataSources: { add() {}, remove() {} },
};
bindFakeCesiumCamera(viewer);
const state = { enabled: false, renderedKeys: new Map() };
const loads = [];
const parts = {
selection: { installInteraction() {} },
rendering: { clearRendered() {} },
rendering: {
attach() {
state.dataSource = { show: false };
},
detach() {},
clearRendered() {},
},
ingestion: {
loadInstallations() {
state.abort = new AbortController();
@@ -92,7 +100,8 @@ test('camera changes debounce, deduplicate moveEnd, cancel superseded loads and
assert.equal(loads.at(-1).coverage.kind, 'viewport');
life.destroy(viewer);
assert.equal(camera.changed.numberOfListeners, 0);
assert.equal(camera.moveEnd.numberOfListeners, 0);
// The camera port's own moveEnd listener stays; the layer's is gone.
assert.equal(camera.moveEnd.numberOfListeners, 1);
assert.equal(camera.percentageChanged, 0.5);
});
@@ -104,6 +113,7 @@ test('an aborting real ingestion cannot clear the next scheduled view key', asyn
camera: { computeViewRectangle: () => rectangle },
scene: { globe: { ellipsoid: Cesium.Ellipsoid.WGS84 } },
};
bindFakeCesiumCamera(viewer);
const state = { enabled: true, viewer };
const pending = [];
const parts = {
@@ -167,7 +177,10 @@ test('wide views refresh screen decluttering when the globe rectangle stays unch
};
const state = {
enabled: true,
viewer: { camera, scene: { globe: { ellipsoid: Cesium.Ellipsoid.WGS84 } } },
viewer: bindFakeCesiumCamera({
camera,
scene: { globe: { ellipsoid: Cesium.Ellipsoid.WGS84 } },
}),
};
let loads = 0;
const parts = {
+3
View File
@@ -2,6 +2,9 @@ export const LAYER_ID = 'military-installations';
export const REQUEST_DEBOUNCE_MS = 180;
/** How far the view moves before the layer looks again (camera `changed`). */
export const CAMERA_CHANGED_THRESHOLD = 0.01;
export const MAX_RENDERED = 700;
export const GOOGLE_MILITARY_PLACE_TYPES = new Set(['military_base']);
+30 -2
View File
@@ -1,5 +1,8 @@
import { installationClassLabel, installationTitle } from './classLabel.js';
import * as Cesium from 'cesium';
// Still Cesium for its entities, so this layer loads the unbound camera
// factory its other parts reach the renderer through.
import '../../render/cesium/camera.js';
import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import { entityRecord } from '../../data/entityRecords.js';
@@ -21,6 +24,29 @@ export function createRendering({
const { governorRequestRender } = services.render;
const { warmFireAnchorFloors } = services.anchors;
/** A record's class colour, for the entities. */
function colorFor(record) {
const [r, g, b, a] = parts.model.colorFor(record);
return new Cesium.Color(r, g, b, a);
}
/**
* The layer's entities. They stay entities: the camera can follow a site
* (double-click), and the tracked card reads what it shows from them.
*/
function attach(viewer) {
layerState.dataSource = new Cesium.CustomDataSource(
'military-installations',
);
viewer.dataSources.add(layerState.dataSource);
}
function detach(viewer) {
if (layerState.dataSource && viewer)
viewer.dataSources.remove(layerState.dataSource, true);
layerState.dataSource = null;
}
/**
* Shared rendered-surface height for an installation anchor or footprint.
* @param {{latitude:number, longitude:number}} record Installation record.
@@ -65,7 +91,7 @@ export function createRendering({
const footprints =
record.footprints || (record.footprint ? [[record.footprint]] : []);
const material = new Cesium.ColorMaterialProperty(
parts.model.colorFor(record).withAlpha(0.22),
colorFor(record).withAlpha(0.22),
);
for (let i = 0; i < footprints.length; i++) {
const rings = footprints[i];
@@ -207,7 +233,7 @@ export function createRendering({
for (const [id, rendered] of [...layerState.renderedKeys])
if (keys.get(id) !== rendered.key) removeRecordEntities(id);
for (const record of records) {
const color = parts.model.colorFor(record);
const color = colorFor(record);
const surfaceHeightM = installationSurfaceHeightM(record);
const displayPosition = Cesium.Cartesian3.fromDegrees(
record.longitude,
@@ -357,6 +383,8 @@ export function createRendering({
});
}
return {
attach,
detach,
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
+1 -1
View File
@@ -66,7 +66,7 @@ function harness(t) {
};
const parts = {
model: {
colorFor: () => Cesium.Color.ORANGE,
colorFor: () => [1, 165 / 255, 0, 1],
installationSourceLabel: () => 'OpenStreetMap',
},
};
@@ -12,7 +12,7 @@ function harness() {
let listener, removed = 0;
const noop = () => {};
const services = { ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {}, render: { governorRequestRender: noop }, context: { removeEntityContextsForLayer: noop, clearSelectedEntityContextForLayer: noop }, picking: { registerPickOwner: noop, unregisterPickOwner: noop }, maps: { subscribeMapStack(cb) { listener = cb; return () => { listener = null; removed++; }; } } };
const parts = { model: { colorFor: () => C.Color.ORANGE, installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } };
const parts = { model: { colorFor: () => [1, 165 / 255, 0, 1], installationSourceLabel: () => 'OpenStreetMap' }, viewport: { clearUnavailableRetry: noop }, ingestion: { setInstallationStatus: noop } };
parts.rendering = createRendering({ state, services, parts });
const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods;
return { state, record, parts, lifecycle, changeSurface: () => listener(), removed: () => removed };
-6
View File
@@ -1,12 +1,6 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const state = {};
state.distanceEndpointScratch = new Cesium.Cartographic();
state.distanceGeodesicScratch = new Cesium.EllipsoidGeodesic();
Object.assign(state, {
viewer: null,
dataSource: null,
+14 -18
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { findCamera } from '../../render/rendererOf.js';
import { REQUEST_DEBOUNCE_MS } from './policy.js';
import { installationAnchorBox } from './source.js';
@@ -7,7 +7,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
* The area this load describes: the window around a Contacts subject while
* one is set (a follow or Cockpit camera never settles and often looks at the
* horizon), otherwise the settled camera viewport.
* @param {object} viewer Cesium viewer.
* @param {object} viewer Viewer.
* @returns {{box: object|null, coverage: object}} Query box and its coverage.
*/
function loadArea(viewer) {
@@ -23,14 +23,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
}
function viewportBox(viewer) {
const rectangle = viewer?.camera?.computeViewRectangle(
viewer.scene.globe.ellipsoid,
);
const rectangle = findCamera(viewer)?.viewRectangle();
if (!rectangle) return null;
const south = Cesium.Math.toDegrees(rectangle.south);
const north = Cesium.Math.toDegrees(rectangle.north);
const west = Cesium.Math.toDegrees(rectangle.west);
const east = Cesium.Math.toDegrees(rectangle.east);
const { south, north, west, east } = rectangle;
// Wide and dateline views use the bundled point index.
if (
!Number.isFinite(south + north + west + east) ||
@@ -89,19 +84,20 @@ export function createViewport({ state: layerState, services, parts, source }) {
function scheduleLoad() {
if (!layerState.enabled) return;
const { box, coverage } = loadArea(layerState.viewer);
const camera = layerState.viewer.camera;
const widePose =
const wide =
coverage.kind === 'viewport' &&
box &&
(box.east < box.west ||
box.east - box.west > 10 ||
box.north - box.south > 10)
? [camera.positionWC, camera.directionWC]
.map((v) =>
v ? [v.x, v.y, v.z].map((n) => n.toFixed(4)).join(',') : '',
)
.join(':')
: '';
box.north - box.south > 10);
const pose = wide ? findCamera(layerState.viewer)?.pose() : null;
const widePose = pose
? [pose.position, pose.direction]
.map((v) =>
v ? [v.x, v.y, v.z].map((n) => n.toFixed(4)).join(',') : '',
)
.join(':')
: '';
const key = `${coverage.kind}:${box ? [box.south, box.west, box.north, box.east].map((v) => v.toFixed(6)).join(',') : 'wide'}:${widePose}`;
if (layerState.cameraLoadKey === key && !layerState.error) return;
layerState.cameraLoadKey = key;
+1 -1
View File
@@ -2260,7 +2260,7 @@ test('installation titles share persistent card arbitration and retain a bounded
const state = { enabled: true, viewer: env.viewer, contextAnchor: {} };
const markers = createNamedMarkers({ state,
services: { render: { governorRequestRender() {} } },
parts: { model: { colorFor: () => Cesium.Color.ORANGE }, rendering: { installationSurfaceHeightM: () => 0 } },
parts: { model: { colorFor: () => [1, 165 / 255, 0, 1] }, rendering: { installationSurfaceHeightM: () => 0 } },
overlayHost: { setEntries: setOverlayEntries, clearSource: clearOverlaySource,
setVisible: setOverlaySourceVisible, getDiagnostics: getWorldOverlayDiagnostics },
});
-5
View File
@@ -72,13 +72,8 @@
"src/layers/flights/testing.js",
"src/layers/flights/tracking.js",
"src/layers/ghostMaps/index.js",
"src/layers/installations/controls.js",
"src/layers/installations/lifecycle.js",
"src/layers/installations/model.js",
"src/layers/installations/namedMarkers.js",
"src/layers/installations/rendering.js",
"src/layers/installations/state.js",
"src/layers/installations/viewport.js",
"src/layers/launches/camera.js",
"src/layers/launches/launchPad.js",
"src/layers/launches/lifecycle.js",
+2 -2
View File
@@ -220,7 +220,7 @@ test('named A+B to B to A+B preserves canonical identity, parent title and selec
source: {},
parts: {
model: {
colorFor: () => C.Color.ORANGE,
colorFor: () => [1, 165 / 255, 0, 1],
installationSourceLabel: () => 'OpenStreetMap',
},
},
@@ -299,7 +299,7 @@ test('cold names reconcile selection through enrichment, identical groups at ano
source: {},
parts: {
model: {
colorFor: () => C.Color.ORANGE,
colorFor: () => [1, 165 / 255, 0, 1],
installationSourceLabel: () => 'OpenStreetMap',
},
},
+5 -1
View File
@@ -165,7 +165,11 @@ export function bindFakeCesiumCamera(viewer, ports = {}) {
};
},
},
viewRectangle: { value: () => null },
// A fake that computes a view rectangle answers with it, as the
// renderer does; one that does not has none.
viewRectangle: {
value: () => (fake.computeViewRectangle ? real.viewRectangle() : null),
},
on: {
value(event, cb) {
const source = fake[event];