Merge branch 'main' into fix/i18n-installations-note

# Conflicts:
#	scripts/package-boundaries.json
#	src/layers/installations/controls.js
This commit is contained in:
German Khokhlov committed 2026-11-18 16:35:52 +04:00
commit 93b091d082
2063 files changed
+322399 -46202

No files matched your search

+41 -43
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { installationFeedback } from '../../data/installationFeedback.js';
import {
LAYER_ID,
@@ -6,6 +5,10 @@ import {
ANCHOR_REFRESH_M,
} from './policy.js';
import { t } from '../../i18n/index.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';
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
@@ -39,7 +42,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.
*/
@@ -52,17 +55,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) {
@@ -74,8 +77,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
@@ -89,7 +92,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)
@@ -99,31 +102,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),
@@ -151,7 +146,7 @@ export function createControls({ state: layerState, services, parts, source }) {
if (!record || record.kind !== 'installation') return null;
return {
...record,
position: Cesium.Cartesian3.fromDegrees(
position: fromDegrees(
record.longitude,
record.latitude,
parts.rendering.installationSurfaceHeightM(record),
@@ -160,16 +155,19 @@ export function createControls({ state: layerState, services, parts, source }) {
},
/**
* The mapped installation a `scene.pick()` result landed on: a named
* marker point (`{ installationId }`) or a site entity, as this layer's
* own click selection reads them. Null for anything else.
* @param {object|null|undefined} picked
* The mapped installation a query port's pick landed on: a site's dot,
* outline or fill, or a named marker, each naming its installation in
* its `meta`, as this layer's own click selection reads them. Null for
* anything else.
* @param {object|null|undefined} hit A query port `Hit`.
* @returns {object|null} As {@link getById}.
*/
findByPick(picked) {
findByPick(hit) {
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId
: null;
return id ? methods.getById(id) : null;
},
@@ -184,16 +182,16 @@ export function createControls({ state: layerState, services, parts, source }) {
// No camera flight without a real selection: a flight plus a stale subject
// reads as success to Context navigation and strands NEXT on this item.
if (!parts.selection.selectRecord(record.id)) return false;
layerState.viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
parts.rendering.installationSurfaceHeightM(record),
),
18000,
),
{ duration: 1.4 },
cameraOf(layerState.viewer).flyToBounds(
{
center: {
lon: record.longitude,
lat: record.latitude,
height: parts.rendering.installationSurfaceHeightM(record),
},
radius: 18000,
},
{ durationS: 1.4 },
);
return true;
},
+14 -23
View File
@@ -1,9 +1,5 @@
import * as Cesium from 'cesium';
import { LAYER_ID } from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
import { cameraOf } from '../../render/rendererOf.js';
import { CAMERA_CHANGED_THRESHOLD, LAYER_ID } from './policy.js';
export function createLifecycle({
state: layerState,
@@ -17,17 +13,16 @@ 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.
layerState.changedRemove = camera.on('changed', cameraChanged, {
threshold: CAMERA_CHANGED_THRESHOLD,
});
parts.selection.installInteraction(viewer);
},
@@ -51,9 +46,8 @@ export function createLifecycle({
});
parts.namedMarkers?.enable();
parts.namedMarkers?.sync(layerState.records || []);
claimCameraSensitivity(layerState.viewer.camera, LAYER_ID, 0.01);
registerPickOwner(LAYER_ID, (id) => layerState.recordById.has(id));
layerState.dataSource.show = true;
parts.rendering.setShown(true);
// DataLayerManager invokes update() immediately after enable(), which owns
// the first fetch. Avoid racing it with a second aborting request here.
},
@@ -62,7 +56,6 @@ export function createLifecycle({
layerState.enabled = false;
services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
parts.namedMarkers?.hide();
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
layerState.contextAnchor = null;
layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' };
@@ -74,7 +67,7 @@ export function createLifecycle({
layerState.abort?.abort();
layerState.abort = null;
layerState.loading = false;
if (layerState.dataSource) layerState.dataSource.show = false;
parts.rendering.setShown(false);
clearSelectedEntityContextForLayer(LAYER_ID);
layerState.selectedId = null;
parts.rendering.clearSelectionFill?.();
@@ -93,13 +86,11 @@ export function createLifecycle({
layerState.moveEndRemove?.();
layerState.changedRemove?.();
parts.selection.destroy?.();
layerState.clickHandler?.destroy();
layerState.clickHandler = null;
layerState.clickSubscription?.();
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);
},
};
+13 -6
View File
@@ -3,6 +3,7 @@ import assert from 'node:assert/strict';
import * as credits from '../../data/dataCredits.js';
import { createLifecycle } from './lifecycle.js';
import { LAYER_ID } from './policy.js';
import { bindFakeCesiumCredits } from '../../testSupport/fakeCreditsPort.mjs';
for (const source of [
{ name: 'OpenStreetMap', id: 'tile:base' },
@@ -13,20 +14,20 @@ for (const source of [
test(`enable restores cached installation credits before a refresh: ${source?.id || 'empty'}`, () => {
const visibleCredits = new Set();
const noop = () => {};
const viewer = {
const viewer = bindFakeCesiumCredits({
camera: {},
creditDisplay: {
addStaticCredit: (credit) => visibleCredits.add(credit),
removeStaticCredit: (credit) => visibleCredits.delete(credit),
},
};
});
const state = {
viewer,
records: source ? [{ id: 'base', sources: [source] }] : [],
recordById: new Map(),
dataSource: { show: false },
};
let markersVisible = false;
let drawnShown = false;
const parts = {
namedMarkers: {
enable: () => {
@@ -37,7 +38,13 @@ for (const source of [
markersVisible = false;
},
},
rendering: {},
rendering: {
attach: noop,
detach: noop,
setShown: (shown) => {
drawnShown = shown;
},
},
viewport: { clearUnavailableRetry: noop },
ingestion: { setInstallationStatus: noop },
};
@@ -60,12 +67,12 @@ for (const source of [
try {
for (let cycle = 0; cycle < 2; cycle++) {
lifecycle.enable();
assert.equal(state.dataSource.show, true);
assert.equal(drawnShown, true);
assert.equal(markersVisible, true);
// No renderRecords or successful fetch occurs between toggles.
assert.equal(visibleCredits.size, expected);
lifecycle.disable();
assert.equal(state.dataSource.show, false);
assert.equal(drawnShown, false);
assert.equal(markersVisible, false);
assert.equal(visibleCredits.size, 0);
}
+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');
}
/**
+136 -61
View File
@@ -1,55 +1,114 @@
import { installationClassLabel, installationTitle } from './classLabel.js';
import * as Cesium from 'cesium';
import {
MILITARY_LABEL_CAP,
MILITARY_POINT_CAP,
} from '../../data/militaryNames.js';
import { LAYER_ID, COLOR_BY_CLASS } from './policy.js';
import { fromDegrees } from '../../geo/index.js';
import { horizonFrom } from '../../geo/horizon.js';
import {
cameraOf,
canvasOf,
drawOf,
findFrame,
findQuery,
} from '../../render/rendererOf.js';
import {
CAMERA_CHANGED_THRESHOLD,
LAYER_ID,
COLOR_BY_CLASS,
} from './policy.js';
import { createInfrastructureOverlayEntry } from '../../data/infrastructureOverlayEntry.js';
let instances = 0;
/**
* A named marker's point item id. Not the bare record id: the shared pick
* registry resolves a draw item's pick to its item id, and a point click has
* never been this layer's for sibling layers' owner checks (a tracked
* aircraft is released by it, as by a click on empty map). The click handler
* reads the record id from the item's `meta`.
*/
export const namedPointId = (recordId) => `named:${recordId}`;
const samePlace = (a, b) =>
Boolean(a) && a.x === b.x && a.y === b.y && a.z === b.z;
/** Bounded point markers; the shared overlay owns text projection and decluttering. */
export function createNamedMarkers({ state, services, parts, overlayHost }) {
const setId = `${LAYER_ID}:${++instances}:names`;
let points = null;
let entries = [];
const markers = new Map();
const screen = new Cesium.Cartesian2();
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84);
let shownPoints = 0;
/** Where each drawn point item is, by item id. */
let drawn = new Map();
let ordered = [];
const viewMatrix = new Cesium.Matrix4();
let lastPose = null;
let width = 0,
height = 0;
let removeChanged = null,
removeEnd = null,
removeFrame = null;
function refresh() {
/** Whether the eye moved or the canvas resized since the last refresh. */
function viewChanged(viewer, pose) {
const same = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z;
return (
!lastPose ||
!same(pose.position, lastPose.position) ||
!same(pose.direction, lastPose.direction) ||
!same(pose.up, lastPose.up) ||
width !== canvasOf(viewer).clientWidth ||
height !== canvasOf(viewer).clientHeight
);
}
// Reused projection buffers, grown to the marker count.
let worldXyz = new Float64Array(0);
let screenXy = new Float32Array(0);
function refresh(pose = null) {
const viewer = state.viewer;
if (!state.enabled || !points) return;
width = viewer.scene.canvas.clientWidth;
height = viewer.scene.canvas.clientHeight;
if (viewer.camera.viewMatrix)
Cesium.Matrix4.clone(viewer.camera.viewMatrix, viewMatrix);
occluder.cameraPosition = viewer.camera.positionWC;
shownPoints = 0;
const canvas = canvasOf(viewer);
width = canvas.clientWidth;
height = canvas.clientHeight;
pose ??= cameraOf(viewer).pose();
lastPose = {
position: { ...pose.position },
direction: { ...pose.direction },
up: { ...pose.up },
};
// The ellipsoid horizon from the eye, the test the draw set's own
// horizon cull makes, so the count agrees with what is drawn.
const horizon = horizonFrom(pose.position);
if (worldXyz.length < ordered.length * 3) {
worldXyz = new Float64Array(ordered.length * 3);
screenXy = new Float32Array(ordered.length * 2);
}
let shown = 0;
for (let index = 0; index < ordered.length; index++) {
const marker = ordered[index];
const point = marker.point;
point.show = marker.named && occluder.isPointVisible(point.position);
point.show = marker.named && horizon.isPointVisible(point.position);
if (!point.show) continue;
const projected = Cesium.SceneTransforms.worldToWindowCoordinates(
viewer.scene,
point.position,
screen,
);
if (
projected &&
screen.x >= 0 &&
screen.y >= 0 &&
screen.x < width &&
screen.y < height
)
shownPoints++;
worldXyz[shown * 3] = point.position.x;
worldXyz[shown * 3 + 1] = point.position.y;
worldXyz[shown * 3 + 2] = point.position.z;
shown++;
}
shownPoints = 0;
const query = findQuery(viewer);
if (!query || !shown) return;
query.projectMany(
worldXyz.subarray(0, shown * 3),
screenXy.subarray(0, shown * 2),
);
for (let i = 0; i < shown; i++) {
const x = screenXy[i * 2];
const y = screenXy[i * 2 + 1];
// NaN, behind the eye, fails every test.
if (x >= 0 && y >= 0 && x < width && y < height) shownPoints++;
}
}
@@ -71,20 +130,20 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
}
function frame() {
const viewer = state.viewer;
if (
viewer?.camera.viewMatrix &&
(!Cesium.Matrix4.equals(viewMatrix, viewer.camera.viewMatrix) ||
width !== viewer.scene.canvas.clientWidth ||
height !== viewer.scene.canvas.clientHeight)
)
refresh();
if (!viewer || !points) return;
const pose = cameraOf(viewer).pose();
if (viewChanged(viewer, pose)) refresh(pose);
}
function enable() {
const viewer = state.viewer;
if (!viewer || removeChanged || removeEnd || removeFrame) return;
removeChanged = viewer.camera.changed?.addEventListener(cameraChanged);
removeEnd = viewer.camera.moveEnd?.addEventListener(cameraChanged);
removeFrame = viewer.scene.preRender?.addEventListener(frame);
const camera = cameraOf(viewer);
// The sensitivity this layer claims for raw camera listeners while on.
removeChanged = camera.on('changed', cameraChanged, {
threshold: CAMERA_CHANGED_THRESHOLD,
});
removeEnd = camera.on('moveEnd', cameraChanged);
removeFrame = findFrame(viewer)?.on('preRender', frame) ?? null;
if (points) points.show = true;
publishLabels();
overlayHost.setVisible(LAYER_ID, true);
@@ -101,14 +160,25 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
shownPoints = 0;
}
/** The point item a marker draws. */
function pointItem(marker, record) {
return {
id: namedPointId(marker.recordId),
pos: marker.point.position,
pixelSize: 7,
color: parts.model.colorFor(record),
outlineColor: [0, 0, 0, 1],
outlineWidth: 1,
disableDepthTest: Infinity,
show: marker.named,
meta: { installationId: marker.recordId },
};
}
function sync(records) {
const viewer = state.viewer;
if (!viewer?.scene?.primitives) return;
if (!points) {
points = viewer.scene.primitives.add(
new Cesium.PointPrimitiveCollection(),
);
}
if (!viewer) return;
points ??= drawOf(viewer).points({ id: setId, horizonCull: true });
points.show = state.enabled;
const named = records
.filter((r) => r.namedArea || r.id === state.selectedId)
@@ -128,18 +198,16 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
const marker = markers.get(alias);
markers.delete(alias);
marker.point.id = { installationId: record.id };
marker.recordId = record.id;
marker.entry.id = record.id;
markers.set(record.id, marker);
}
for (const [id, marker] of markers)
if (!keep.has(id)) {
points.remove(marker.point);
markers.delete(id);
}
for (const id of markers.keys()) if (!keep.has(id)) markers.delete(id);
ordered = [];
entries = [];
const items = [];
for (const record of named) {
const position = Cesium.Cartesian3.fromDegrees(
const position = fromDegrees(
record.longitude,
record.latitude,
record.pointOnly
@@ -148,17 +216,11 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
);
let marker = markers.get(record.id);
if (!marker) {
const id = { installationId: record.id };
marker = {
point: points.add({
id,
position,
pixelSize: 7,
color: parts.model.colorFor(record),
outlineColor: Cesium.Color.BLACK,
outlineWidth: 1,
disableDepthTestDistance: Infinity,
}),
recordId: record.id,
// What `visit` hands out: the marker's id, position and whether
// it is on this side of the horizon.
point: { id: { installationId: record.id }, position, show: false },
entry: createInfrastructureOverlayEntry({
id: record.id,
source: LAYER_ID,
@@ -172,7 +234,7 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
} else {
marker.point.position = position;
}
marker.named = record.namedArea;
marker.named = Boolean(record.namedArea);
marker.entry.variant =
record.id === state.selectedId ? 'selected' : 'card';
marker.entry.selected = record.id === state.selectedId;
@@ -187,17 +249,29 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
marker.entry.priority = record.areaM2 || 0;
entries.push(marker.entry);
ordered.push(marker);
items.push(pointItem(marker, record));
}
// Restyled points that keep their ids and places change in place; any
// other change draws the set anew.
if (
items.length === drawn.size &&
items.every((item) => samePlace(drawn.get(item.id), item.pos))
)
points.upsert(items);
else points.set(items);
drawn = new Map(items.map((item) => [item.id, { ...item.pos }]));
if (state.enabled) publishLabels();
refresh();
services.render.governorRequestRender('installation-names');
}
return {
sync,
/** The draw set's id, for matching its click hits. */
setId,
visit(visitor) {
for (let i = 0; i < ordered.length; i++) {
const marker = ordered[i];
visitor(marker.point.id.installationId, marker.point);
visitor(marker.recordId, marker.point);
}
},
refresh,
@@ -214,8 +288,9 @@ export function createNamedMarkers({ state, services, parts, overlayHost }) {
destroy() {
hide();
ordered = [];
if (points) state.viewer?.scene.primitives.remove(points);
points?.dispose();
points = null;
drawn = new Map();
entries = [];
markers.clear();
},
+21 -12
View File
@@ -1,8 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import { createNamedMarkers } from './namedMarkers.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { createLifecycle } from './lifecycle.js';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { fakeSceneFrame, fakeSceneQuery } from '../../testSupport/fakeCesiumScene.mjs';
import { createLocalInfrastructureOverlayEntry } from '../../data/localGeojsonCore.js';
function setup(t) {
@@ -16,19 +19,21 @@ function setup(t) {
setVisible(_id, value) { visible = value; },
};
let x = -100;
const projections = new Set();
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) };
t.mock.method(C.SceneTransforms, 'worldToWindowCoordinates', () => new C.Cartesian2(x, 300));
const camera = { changed: new C.Event(), moveEnd: new C.Event(), positionWC: C.Cartesian3.fromDegrees(0, 0, 1e6), directionWC: new C.Cartesian3(0, 0, -1) };
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 } };
const draw = fakeDrawPort();
bindFakeCesiumCamera(state.viewer, { draw, query: fakeSceneQuery(state.viewer), frame: fakeSceneFrame(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() {}, setShown() {}, 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;
lifecycle.init(state.viewer); lifecycle.enable();
const records = [1, 2].map((n) => ({ id: `osm:military:w${n}`, name: `Site ${n}`, namedArea: true, areaM2: 100 / n, latitude: 0, longitude: 0, pointOnly: true }));
return { state, camera, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, projections, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
const points = () => [...draw.sets.values()].find((set) => set.kind === 'points' && !set.disposed);
return { state, camera, draw, points, get labels() { return labels; }, get options() { return options; }, get visible() { return visible; }, records, markers: parts.namedMarkers, lifecycle, setX: (value) => { x = value; }, publications: () => publications, loads: () => loads };
}
test('Contacts camera motion reprojects and declutters existing labels without source loads or primitive replacement', (t) => {
@@ -43,10 +48,14 @@ test('Contacts camera motion reprojects and declutters existing labels without s
assert.equal(h.visible, true);
assert.equal(h.loads(), 0);
assert.equal(h.publications(), 3);
assert.equal(h.projections.size, 1);
h.setX(1400); h.camera.viewMatrix[12] = 1; h.state.viewer.scene.preRender.raiseEvent();
const items = [...h.points().items.values()];
assert.deepEqual(items.map((item) => [item.id, item.pixelSize, item.outlineWidth, item.disableDepthTest, item.show]), h.records.map((r) => [namedPointId(r.id), 7, 1, Infinity, true]));
assert.equal(h.points().spec.horizonCull, true);
assert.equal(h.points().show, true);
h.setX(1400); h.camera.positionWC = C.Cartesian3.fromDegrees(0, 0, 1.1e6); h.state.viewer.scene.preRender.raiseEvent();
assert.equal(h.markers.stats().pointsOnScreen, 0, 'small pose changes refresh before render');
h.lifecycle.disable();
assert.equal(h.points().show, false);
assert.equal(h.camera.changed.numberOfListeners, 1, 'only the viewport listener remains');
assert.equal(h.state.viewer.scene.preRender.numberOfListeners, 0);
assert.equal(h.labels.length, 0);
@@ -57,7 +66,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);
});
@@ -83,7 +92,7 @@ test('wide named markers retain primitives until close polygons publish with the
h.lifecycle.destroy(h.state.viewer);
});
test('canonical aliases transfer named marker ownership without replacing primitives', (t) => {
test('canonical aliases transfer named marker ownership without replacing markers or labels', (t) => {
const h = setup(t);
h.setX(600);
const parent = h.records[1];
@@ -103,6 +112,7 @@ test('canonical aliases transfer named marker ownership without replacing primit
assert.equal(point, originalPoint);
assert.equal(currentLabel, label);
assert.equal(point.id.installationId, record.id);
assert.deepEqual(h.points().items.get(namedPointId(record.id)).meta, { installationId: record.id });
assert.equal(currentLabel.id, record.id);
});
}
@@ -124,12 +134,11 @@ test('the bounded host cohort ranks wide points and polygon titles by area', (t)
const first = h.labels[0];
const publications = h.publications();
for (let i = 0; i < 100; i++) {
h.camera.viewMatrix[12] += 0.01;
h.camera.positionWC = C.Cartesian3.fromDegrees(0, 0, 1e6 + i + 1);
h.state.viewer.scene.preRender.raiseEvent();
}
assert.equal(h.labels[0], first);
assert.equal(h.publications(), publications, 'camera frames never rebuild host entries');
assert.equal(h.projections.size, 1, 'point projection reuses scratch storage');
h.lifecycle.destroy(h.state.viewer);
assert.equal(h.labels.length, 0);
});
+15 -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,17 @@ 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() {},
setShown() {},
detach() {},
clearRendered() {},
},
ingestion: {
loadInstallations() {
state.abort = new AbortController();
@@ -92,7 +99,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 +112,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 +176,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']);
+241 -122
View File
@@ -1,8 +1,29 @@
import { installationClassLabel, installationTitle } from './classLabel.js';
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from './policy.js';
import { entityRecord } from '../../data/entityRecords.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf, findGlobe } from '../../render/rendererOf.js';
let instances = 0;
const DOT_OUTLINE = Object.freeze([0, 0, 0, 0.8]);
const SELECTED_DOT = Object.freeze([1, 1, 1, 1]);
/** A record's footprint polygons, each its rings of `[lon, lat]`. */
const footprintsOf = (record) =>
record.footprints || (record.footprint ? [[record.footprint]] : []);
/** A record's outline polylines of `[lon, lat]`. */
const outlinesOf = (record) =>
record.outlineLines || (record.footprint ? [record.footprint] : []);
/**
* The installations layer's drawing: a draw-port point set of site dots, a
* point set of the selected site's dot (so selecting one restyles no other
* dot), a line set of their ground outlines and a shape set of the selected
* site's footprint fill, on the viewer's renderer (`drawOf`).
*/
export function createRendering({
state: layerState,
services,
@@ -19,6 +40,45 @@ export function createRendering({
const { governorRequestRender } = services.render;
const { warmFireAnchorFloors } = services.anchors;
/** A record's class colour with alpha `alpha`, as the draw port takes it. */
function colorFor(record, alpha = null) {
const [r, g, b, a] = parts.model.colorFor(record);
return [r, g, b, alpha ?? a];
}
/** Make the layer's draw sets, hidden until the layer is enabled. */
function attach(viewer) {
const draw = drawOf(viewer);
selectedDotKey = null;
const prefix = `${LAYER_ID}:${++instances}`;
layerState.sets = {
dots: draw.points({ id: `${prefix}:dots`, show: false }),
selected: draw.points({ id: `${prefix}:selected`, show: false }),
outlines: draw.lines({ id: `${prefix}:outlines`, show: false }),
fills: draw.shapes({ id: `${prefix}:fills`, show: false }),
};
}
function detach() {
if (layerState.sets)
for (const set of Object.values(layerState.sets)) set.dispose();
layerState.sets = null;
}
/** Show or hide everything the layer draws. */
function setShown(shown) {
if (!layerState.sets) return;
for (const set of Object.values(layerState.sets)) set.show = shown;
}
/** Whether `setId` is one of this layer's sets. */
function ownsSet(setId) {
return Boolean(
layerState.sets &&
Object.values(layerState.sets).some((set) => set.id === setId),
);
}
/**
* Shared rendered-surface height for an installation anchor or footprint.
* @param {{latitude:number, longitude:number}} record Installation record.
@@ -38,8 +98,7 @@ export function createRendering({
const selectedFillIds = [];
function clearSelectionFill() {
for (const id of selectedFillIds)
layerState.dataSource?.entities.removeById(id);
if (selectedFillIds.length) layerState.sets?.fills.remove(selectedFillIds);
selectedFillIds.length = 0;
selectedFillKey = null;
}
@@ -47,68 +106,62 @@ export function createRendering({
/** Ground geometry classifies the active surface; no height/extrusion plane. */
function syncSelectionFill() {
const record =
layerState.enabled && layerState.recordById.get(layerState.selectedId);
layerState.enabled &&
layerState.sets &&
layerState.recordById.get(layerState.selectedId);
if (!record) {
clearSelectionFill();
return;
}
const classificationType =
layerState.viewer.scene.globe?.show === false
? Cesium.ClassificationType.CESIUM_3D_TILE
: Cesium.ClassificationType.BOTH;
const key = `${record.id}|${renderKey(record)}|${classificationType}`;
// Tiles alone while the globe surface is hidden, as under photoreal.
const clampTo =
findGlobe(layerState.viewer)?.isGlobeVisible?.() === false
? 'tiles'
: 'both';
const key = `${record.id}|${renderKey(record)}|${clampTo}`;
if (key === selectedFillKey) return;
clearSelectionFill();
selectedFillKey = key;
const footprints =
record.footprints || (record.footprint ? [[record.footprint]] : []);
const material = new Cesium.ColorMaterialProperty(
parts.model.colorFor(record).withAlpha(0.22),
);
for (let i = 0; i < footprints.length; i++) {
const rings = footprints[i];
const positions = (ring) =>
ring.map(([lon, lat]) => Cesium.Cartesian3.fromDegrees(lon, lat));
const fill = layerState.dataSource.entities.add({
id: `${record.id}:selected-fill:${i}`,
polygon: {
hierarchy: new Cesium.PolygonHierarchy(
positions(rings[0]),
rings
.slice(1)
.map((ring) => new Cesium.PolygonHierarchy(positions(ring))),
),
material,
classificationType,
},
});
fill.installationId = record.id;
selectedFillIds.push(fill.id);
}
const fill = colorFor(record, 0.22);
const meta = { installationId: record.id };
const items = footprintsOf(record).map((rings, i) => ({
id: `${record.id}:selected-fill:${i}`,
geometry: {
kind: 'polygon',
rings: rings.map((ring) => ring.map(([lon, lat]) => ({ lon, lat }))),
},
fill,
height: 'clampGround',
clampTo,
meta,
}));
if (items.length) layerState.sets.fills.upsert(items);
for (const item of items) selectedFillIds.push(item.id);
governorRequestRender('installation-selection-fill');
}
function clearRendered() {
clearSelectionFill();
if (layerState.dataSource?.entities)
layerState.dataSource.entities.removeAll();
if (layerState.sets) {
layerState.sets.dots.clear();
layerState.sets.selected.clear();
layerState.sets.outlines.clear();
}
selectedDotKey = null;
layerState.renderedKeys.clear();
removeEntityContextsForLayer(LAYER_ID);
}
/**
* Geometry identity of one rendered record. Records whose key is unchanged
* keep their Cesium entities across refreshes: ground-clamped outlines and
* classification fills rebuild asynchronously, so recreating them on every
* reload made unchanged sites blink.
* keep their drawn items across refreshes, only restyled or moved in
* place, so an unchanged site never blinks.
* @param {object} record Installation record.
* @returns {string} Stable key for the record's drawn geometry.
*/
function renderKey(record) {
const footprints =
record.footprints || (record.footprint ? [[record.footprint]] : []);
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
const footprints = footprintsOf(record);
const outlines = outlinesOf(record);
let points = 0;
for (const rings of footprints)
for (const ring of rings) points += ring.length;
@@ -125,22 +178,83 @@ export function createRendering({
].join('|');
}
function removeRecordEntities(id) {
const entities = layerState.dataSource.entities;
for (const entityId of layerState.renderedKeys.get(id)?.entityIds || [])
entities.removeById(entityId);
/**
* A site's dot. The selected site's is hidden here and drawn larger, in
* white, by the selected set (`selectedDotItem`): a clamped dot is
* restyled only by drawing it again, so its own set never changes look.
*/
function dotItem(record, rendered) {
return {
id: record.id,
pos: {
lon: record.longitude,
lat: record.latitude,
height: rendered.heightM,
},
height: 'clampGround',
show: !record.namedArea && !rendered.selected,
pixelSize: 9,
color: colorFor(record),
outlineColor: DOT_OUTLINE,
outlineWidth: 1,
disableDepthTest: Number.POSITIVE_INFINITY,
meta: rendered.carrier,
};
}
/** The selected site's dot, as its own set draws it. */
function selectedDotItem(record, rendered) {
return {
...dotItem(record, rendered),
show: true,
pixelSize: 13,
color: SELECTED_DOT,
};
}
/** What the selected set draws now (site, place, height), or null. */
let selectedDotKey = null;
/** Draw the selected site's dot, when it has one shown. */
function syncSelectedDot() {
const sets = layerState.sets;
if (!sets) return;
const rendered = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null;
const record = rendered
? layerState.recordById.get(layerState.selectedId)
: null;
const key =
record && rendered.selected && !record.namedArea
? [record.id, record.longitude, record.latitude, rendered.heightM].join(
'|',
)
: null;
if (key === selectedDotKey) return;
selectedDotKey = key;
if (key) sets.selected.set([selectedDotItem(record, rendered)]);
else sets.selected.clear();
}
/** Stop drawing a record's dot and outlines. */
function removeRecordItems(id, dotIds, outlineIds) {
const rendered = layerState.renderedKeys.get(id);
if (!rendered) return;
dotIds.push(id);
outlineIds.push(...rendered.outlineIds);
layerState.renderedKeys.delete(id);
}
/**
* The records that get entities this paint: the nearest `MAX_RENDERED`, plus
* The records that get drawn this paint: the nearest `MAX_RENDERED`, plus
* the selected one when it falls outside that window.
*
* Context navigation walks the FULL nearby cohort, which is not bounded by the
* render cap, so selecting item 701+ used to produce no entity at all — the
* camera flew, `getById` returned null, and the selection was silently dropped
* render cap, so selecting item 701+ used to produce no marker at all — the
* camera flew, the lookup returned null, and the selection was silently dropped
* on the floor, leaving the Context subject stale so NEXT offered the same
* installation forever. One extra entity keeps every cohort item selectable
* installation forever. One extra marker keeps every cohort item selectable
* and the cohort count honest.
* @returns {Array<object>} Records to render this paint.
*/
@@ -181,7 +295,7 @@ export function createRendering({
}
}
// Post-moveEnd debounced fetches commit after the camera settles; the
// rebuilt entities need one frame in idle mode. (perf wave 2 fix)
// rebuilt markers need one frame in idle mode. (perf wave 2 fix)
governorRequestRender('installations-render');
if (
layerState.records.some((r) =>
@@ -200,78 +314,74 @@ export function createRendering({
const keys = new Map(
records.map((record) => [record.id, renderKey(record)]),
);
const entities = layerState.dataSource.entities;
entities.suspendEvents();
const removedDots = [];
const removedOutlines = [];
for (const [id, rendered] of [...layerState.renderedKeys])
if (keys.get(id) !== rendered.key) removeRecordEntities(id);
if (keys.get(id) !== rendered.key)
removeRecordItems(id, removedDots, removedOutlines);
const dots = [];
const outlines = [];
for (const record of records) {
const color = parts.model.colorFor(record);
const surfaceHeightM = installationSurfaceHeightM(record);
const displayPosition = Cesium.Cartesian3.fromDegrees(
const selectedRecord = record.id === layerState.selectedId;
const retained = layerState.renderedKeys.get(record.id);
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
let changed = false;
if (retained.heightM !== surfaceHeightM) {
retained.heightM = surfaceHeightM;
const displayPosition = fromDegrees(
record.longitude,
record.latitude,
surfaceHeightM,
);
entityRecord(retained.carrier).displayPosition = () =>
displayPosition;
changed = true;
}
if (retained.selected !== selectedRecord) {
retained.selected = selectedRecord;
changed = true;
}
if (changed) dots.push(dotItem(record, retained));
continue;
}
const displayPosition = fromDegrees(
record.longitude,
record.latitude,
surfaceHeightM,
);
const selectedRecord = record.id === layerState.selectedId;
const retained = layerState.renderedKeys.has(record.id)
? entities.getById(record.id)
: null;
if (retained) {
// Same geometry: update the marker in place (selection, floor height).
if (retained.gevInstallationHeightM !== surfaceHeightM) {
retained.gevInstallationHeightM = surfaceHeightM;
retained.position = displayPosition;
retained.gevDisplayPosition = () => displayPosition;
}
if (retained.gevInstallationSelected !== selectedRecord) {
retained.gevInstallationSelected = selectedRecord;
retained.point.pixelSize = selectedRecord ? 13 : 9;
retained.point.color = selectedRecord ? Cesium.Color.WHITE : color;
}
continue;
}
const entityIds = [record.id];
layerState.renderedKeys.set(record.id, {
// What the dot's pick carries and the shared selection, the tracked
// card and a follow read this site through.
const carrier = { id: record.id, installationId: record.id };
const rendered = {
key: keys.get(record.id),
entityIds,
});
const entity = layerState.dataSource.entities.add({
id: record.id,
position: displayPosition,
point: {
show: !record.namedArea,
pixelSize: record.id === layerState.selectedId ? 13 : 9,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
color:
record.id === layerState.selectedId ? Cesium.Color.WHITE : color,
outlineColor: Cesium.Color.BLACK.withAlpha(0.8),
outlineWidth: 1,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
const outlines =
record.outlineLines || (record.footprint ? [record.footprint] : []);
for (let i = 0; i < outlines.length; i++) {
const outline = layerState.dataSource.entities.add({
id: `${record.id}:outline:${i}`,
polyline: {
positions: outlines[i].map(([lon, lat]) =>
Cesium.Cartesian3.fromDegrees(lon, lat),
),
width: 2,
material: color.withAlpha(0.85),
clampToGround: true,
classificationType: Cesium.ClassificationType.BOTH,
},
outlineIds: [],
carrier,
heightM: surfaceHeightM,
selected: selectedRecord,
};
layerState.renderedKeys.set(record.id, rendered);
dots.push(dotItem(record, rendered));
const outlineColor = colorFor(record, 0.85);
const outlineMeta = { installationId: record.id };
const lines = outlinesOf(record);
for (let i = 0; i < lines.length; i++) {
const id = `${record.id}:outline:${i}`;
outlines.push({
id,
positions: lines[i].map(([lon, lat]) => fromDegrees(lon, lat)),
widthPx: 2,
mode: 'draped',
clampTo: 'both',
style: { kind: 'solid', color: outlineColor },
meta: outlineMeta,
});
outline.installationId = record.id;
entityIds.push(outline.id);
rendered.outlineIds.push(id);
}
entity.gevInstallationHeightM = surfaceHeightM;
entity.gevInstallationSelected = selectedRecord;
entity.gevTrackedId = `installations:${record.id}`;
entity.gevDisplayPosition = () => displayPosition;
entity.gevLabelModel = {
entityRecord(carrier).trackedId = `installations:${record.id}`;
entityRecord(carrier).displayPosition = () => displayPosition;
entityRecord(carrier).labelModel = {
title: installationTitle(record.name) || t('MAPPED INSTALLATION'),
details: [
installationClassLabel(record.class),
@@ -279,7 +389,7 @@ export function createRendering({
],
accent: COLOR_BY_CLASS[record.class] || '#9ca6b0',
};
registerEntityContext(entity, {
registerEntityContext(carrier, {
id: record.id,
layerId: LAYER_ID,
layerName:
@@ -300,13 +410,18 @@ export function createRendering({
},
});
}
entities.resumeEvents();
const selectedEntity = layerState.selectedId
? layerState.dataSource.entities.getById(layerState.selectedId)
const sets = layerState.sets;
if (removedDots.length) sets.dots.remove(removedDots);
if (removedOutlines.length) sets.outlines.remove(removedOutlines);
if (dots.length) sets.dots.upsert(dots);
if (outlines.length) sets.outlines.upsert(outlines);
syncSelectedDot();
const selected = layerState.selectedId
? layerState.renderedKeys.get(layerState.selectedId)
: null;
if (selectedEntity && (claimSelection || migratedSelection))
selectEntityContext(selectedEntity);
else if (!selectedEntity) layerState.selectedId = null;
if (selected && (claimSelection || migratedSelection))
selectEntityContext(selected.carrier);
else if (!selected) layerState.selectedId = null;
// Re-register rebuilt geometry and migrate aliases before pruning old context.
removeEntityContextsForLayer(LAYER_ID, { retainIds: new Set(keys.keys()) });
parts.namedMarkers?.sync(layerState.records);
@@ -343,7 +458,7 @@ export function createRendering({
.map((record) => ({ lat: record.latitude, lon: record.longitude }));
if (!cold.length) return;
warmFireAnchorFloors(cold).then(() => {
if (!layerState.enabled || !layerState.dataSource) return;
if (!layerState.enabled || !layerState.sets) return;
if (
!cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null)
)
@@ -352,6 +467,10 @@ export function createRendering({
});
}
return {
attach,
detach,
setShown,
ownsSet,
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
+14 -15
View File
@@ -1,5 +1,4 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { LAYER_ID } from './policy.js';
export function createSelection({
@@ -30,15 +29,15 @@ export function createSelection({
function selectRecord(id) {
const record = layerState.recordById.get(id);
if (!record || !layerState.dataSource) return false;
if (!record || !layerState.sets) return false;
layerState.selectedId = id;
parts.rendering.renderRecords({ claimSelection: true });
// renderRecords drops selectedId when the record produced no entity.
// renderRecords drops selectedId when the record produced no marker.
return layerState.selectedId === id;
}
function installInteraction(viewer) {
if (layerState.clickHandler) return;
if (layerState.clickSubscription) return;
const events = [
'gev:entity-selected',
'gev:entity-selection-cleared',
@@ -50,17 +49,17 @@ export function createSelection({
for (const event of events)
globalThis.window?.removeEventListener?.(event, syncContextSelection);
};
layerState.clickHandler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas,
);
layerState.clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
const input = inputFor(viewer);
layerState.clickSubscription = input.onClick((event) => {
if (!layerState.enabled) return;
const picked = viewer.scene.pick(click.position);
// A site's dot, outline or fill, or a named marker: each draw item
// names its installation in its `meta`.
const hit = event.drawHit;
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
hit?.set === parts.namedMarkers?.setId ||
parts.rendering.ownsSet(hit?.set)
? hit.meta?.installationId
: null;
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id);
} else if (layerState.selectedId) {
@@ -71,7 +70,7 @@ export function createSelection({
clearSelectedEntityContextForLayer(LAYER_ID);
parts.rendering.renderRecords();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
}
return {
selectRecord,
+94 -14
View File
@@ -4,7 +4,9 @@ import * as Cesium from 'cesium';
import * as context from '../../data/contextStore.js';
import { createSelection } from './selection.js';
import { createRendering } from './rendering.js';
import { createNamedMarkers } from './namedMarkers.js';
import { createNamedMarkers, namedPointId } from './namedMarkers.js';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
function harness(t) {
const previousWindow = globalThis.window;
@@ -35,7 +37,6 @@ function harness(t) {
records: [record],
recordById: new Map([[record.id, record]]),
renderedKeys: new Map(),
dataSource: new Cesium.CustomDataSource(),
viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 1e6) },
scene: {
@@ -45,17 +46,17 @@ function harness(t) {
clientHeight: 800,
}),
primitives: { add: (p) => p, remove() {} },
pick: () => picked,
},
},
};
let picked;
const { draw } = bindFakeCesiumScene(state.viewer);
const input = fakeInput(state.viewer);
t.mock.method(
Cesium.SceneTransforms,
'worldToWindowCoordinates',
(_scene, _point, scratch) => {
scratch.x = 640;
scratch.y = 400;
return scratch;
},
() => new Cesium.Cartesian2(640, 400),
);
let labels = [];
const services = {
@@ -66,7 +67,7 @@ function harness(t) {
};
const parts = {
model: {
colorFor: () => Cesium.Color.ORANGE,
colorFor: () => [1, 165 / 255, 0, 1],
installationSourceLabel: () => 'OpenStreetMap',
},
};
@@ -83,14 +84,17 @@ function harness(t) {
},
};
parts.rendering = createRendering(ctx);
parts.rendering.attach(state.viewer);
parts.namedMarkers = createNamedMarkers(ctx);
const selection = createSelection(ctx);
selection.installInteraction(state.viewer);
t.after(() => {
selection.destroy();
state.clickHandler.destroy();
state.clickSubscription();
parts.namedMarkers.destroy();
parts.rendering.clearRendered();
parts.rendering.detach();
input.destroy();
if (previousWindow === undefined) delete globalThis.window;
else globalThis.window = previousWindow;
if (previousDocument === undefined) delete globalThis.document;
@@ -100,14 +104,23 @@ function harness(t) {
assert.equal(state.selectedId, selected ? record.id : null);
assert.equal(labels[0].selected, selected);
assert.equal(labels[0].variant, selected ? 'selected' : 'card');
assert.equal(
state.dataSource.entities.values.filter((e) => e.polygon).length,
selected ? 1 : 0,
);
assert.equal(state.sets.fills.size(), selected ? 1 : 0);
};
assert.equal(selection.selectRecord(record.id), true);
assertSelected(true);
return { state, selection, assertSelected };
return {
state,
selection,
assertSelected,
draw,
input,
parts,
/** Click on what `pick` names, as the scene would pick it. */
click(value) {
picked = value;
input.tap({ x: 640, y: 400 });
},
};
}
for (const layerId of ['flights', 'military', 'satellites']) {
@@ -153,3 +166,70 @@ test('destroy removes all installation context listeners', (t) => {
h.assertSelected(true);
}
});
test('a click on a named marker point selects its site; again releases it', (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.parts.rendering.renderRecords();
h.assertSelected(false);
const setId = h.parts.namedMarkers.setId;
const item = h.draw.set(setId).items.get(namedPointId('base'));
assert.deepEqual(item.meta, { installationId: 'base' });
const pointPick = { id: { set: setId, id: item.id, meta: item.meta } };
h.click(pointPick);
h.assertSelected(true);
h.click(pointPick);
h.assertSelected(false);
// Another set's item with the same meta is not this layer's point.
h.click({ id: { set: 'other:1', id: item.id, meta: item.meta } });
h.assertSelected(false);
});
test('a click on a site dot or its outline selects the site; another set does not', (t) => {
const h = harness(t);
h.state.selectedId = null;
context.clearSelectedEntityContextForLayer('military-installations');
h.state.records[0].namedArea = false;
h.state.records[0].outlineLines = [
[
[0, 0],
[0.01, 0],
],
];
h.parts.rendering.renderRecords();
const selectedNow = () => h.state.selectedId === 'base';
assert.equal(selectedNow(), false);
const dots = h.state.sets.dots;
const dot = h.draw.set(dots.id).items.get('base');
assert.equal(dot.show, true);
assert.equal(dot.height, 'clampGround');
assert.equal(dot.pixelSize, 9);
assert.equal(dot.disableDepthTest, Infinity);
// The dot carries the site's shared context record, for point-and-ask.
assert.equal(context.getContextStore().entities.get('base').entity, dot.meta);
h.click({ id: { set: dots.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), true);
assert.equal(context.getSelectedEntityContext().id, 'base');
// Drawn larger and white by the selected set, hidden in its own.
assert.equal(h.draw.set(dots.id).items.get('base').show, false);
assert.equal(h.draw.set(dots.id).items.get('base').pixelSize, 9);
const selectedSet = h.draw.set(h.state.sets.selected.id);
const selected = selectedSet.items.get('base');
assert.equal(selected.pixelSize, 13);
assert.deepEqual(selected.color, [1, 1, 1, 1]);
assert.equal(selected.meta, dot.meta);
// A click on the selected dot clears it.
h.click({ id: { set: selectedSet.spec.id, id: 'base', meta: dot.meta } });
assert.equal(selectedNow(), false);
assert.equal(selectedSet.items.size, 0);
assert.equal(h.draw.set(dots.id).items.get('base').show, true);
const outlines = h.state.sets.outlines;
const outline = h.draw.set(outlines.id).items.get('base:outline:0');
assert.equal(outline.mode, 'draped');
assert.equal(outline.clampTo, 'both');
h.click({ id: { set: outlines.id, id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), true);
h.click({ id: { set: 'other:1', id: outline.id, meta: outline.meta } });
assert.equal(selectedNow(), false);
});
+29 -22
View File
@@ -1,53 +1,59 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as C from 'cesium';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness() {
const ring = [[-97, 30], [-96.99, 30], [-96.99, 30.01], [-97, 30]];
const record = { id: 'base', latitude: 30, longitude: -97, name: 'Base', class: 'base', footprints: [[ring, ring.map(([x,y]) => [x+0.001,y+0.001])], [ring]] };
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), dataSource: new C.CustomDataSource(), viewer: { scene: { globe: { show: false } }, camera: {} } };
let globeVisible = false;
const viewer = { scene: {}, camera: {} };
const { draw } = bindFakeDraw(viewer, { globe: { isGlobeVisible: () => globeVisible } });
const state = { enabled: true, selectedId: 'base', records: [record], recordById: new Map([['base', record]]), renderedKeys: new Map(), viewer };
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 });
parts.rendering.attach(viewer);
const lifecycle = createLifecycle({ state, services, parts, source: {} }).methods;
return { state, record, parts, lifecycle, changeSurface: () => listener(), removed: () => removed };
const fills = () => [...draw.set(state.sets.fills.id).items.values()];
return { state, record, parts, lifecycle, draw, fills, showGlobe: (shown) => { globeVisible = shown; }, changeSurface: () => listener(), removed: () => removed };
}
test('selected multipart footprints classify Google tiles with one constant translucent material and holes', () => {
test('selected multipart footprints drape on Google tiles with one constant translucent colour and holes', () => {
const h = harness(), render = h.parts.rendering;
render.syncSelectionFill();
const fills = h.state.dataSource.entities.values.slice();
const fills = h.fills();
assert.equal(fills.length, 2);
for (const fill of fills) {
assert.equal(fill.installationId, 'base');
assert.equal(fill.polygon.classificationType.getValue(), C.ClassificationType.CESIUM_3D_TILE);
assert.equal(fill.polygon.height, undefined);
assert.equal(fill.polygon.extrudedHeight, undefined);
assert.equal(fill.polygon.material.isConstant, true);
assert.equal(fill.polygon.material.color.getValue().alpha, 0.22);
assert.equal(fill.meta.installationId, 'base');
assert.equal(fill.clampTo, 'tiles');
assert.equal(fill.height, 'clampGround');
assert.equal(fill.extrudeHeight, undefined);
assert.deepEqual(fill.fill, [1, 165 / 255, 0, 0.22]);
}
assert.equal(fills[0].polygon.hierarchy.getValue().holes.length, 1);
assert.equal(fills[0].polygon.material, fills[1].polygon.material);
assert.equal(fills[0].geometry.rings.length, 2, 'the hole is a second ring');
assert.equal(fills[0].fill, fills[1].fill);
const writes = h.draw.set(h.state.sets.fills.id).writes;
for (let i = 0; i < 100; i++) render.syncSelectionFill();
assert.deepEqual(h.state.dataSource.entities.values, fills, 'repaints retain ground geometry');
assert.equal(h.draw.set(h.state.sets.fills.id).writes, writes, 'repaints retain ground geometry');
assert.deepEqual(h.fills(), fills);
h.state.selectedId = null; render.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0);
assert.equal(h.fills().length, 0);
});
test('surface changes reclassify selected geometry and disable tears down fills and subscription', () => {
const h = harness();
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
h.state.viewer.scene.globe.show = true; h.changeSurface();
assert.ok(h.state.dataSource.entities.values.every(e => e.polygon.classificationType.getValue() === C.ClassificationType.BOTH));
h.showGlobe(true); h.changeSurface();
assert.ok(h.fills().every((fill) => fill.clampTo === 'both'));
h.lifecycle.disable();
assert.equal(h.state.dataSource.entities.values.length, 0);
assert.equal(h.fills().length, 0);
assert.equal(h.removed(), 1);
h.lifecycle.enable(); h.parts.rendering.syncSelectionFill();
assert.equal(h.state.dataSource.entities.values.length, 0, 'reenabling cannot revive a stale selection');
assert.equal(h.fills().length, 0, 'reenabling cannot revive a stale selection');
h.lifecycle.disable();
});
@@ -60,15 +66,16 @@ test('geometry rebuild and canonical alias migration preserve shared selection b
const h = harness();
const services = { context, render: { governorRequestRender() {} }, ground: { floorAltitudeM: () => 0, cachedGroundFloor: () => 0 }, anchors: {} };
const rendering = createRendering({ state: h.state, services, parts: h.parts });
rendering.attach(h.state.viewer);
const cleared = [];
window.addEventListener('gev:entity-selection-cleared', e => { cleared.push(e.detail); h.state.selectedId = null; });
rendering.renderRecords({ claimSelection: true });
const oldEntity = context.getSelectedEntityContext().entity;
const oldCarrier = context.getSelectedEntityContext().entity;
h.record.latitude += 0.001;
rendering.renderRecords();
assert.equal(h.state.selectedId, 'base');
assert.equal(context.getSelectedEntityContext().id, 'base');
assert.notEqual(context.getSelectedEntityContext().entity, oldEntity);
assert.notEqual(context.getSelectedEntityContext().entity, oldCarrier);
const replacement = { ...h.record, id: 'canonical', aliasIds: ['base'] };
h.state.records = [replacement]; h.state.recordById = new Map([['canonical', replacement]]);
rendering.renderRecords();
+7 -9
View File
@@ -1,15 +1,10 @@
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,
/** The layer's draw sets (`dots`, `outlines`, `fills`) while attached. */
sets: null,
enabled: false,
records: [],
recordById: new Map(),
@@ -29,7 +24,7 @@ export function createState({ services }) {
retryAt: 0,
failureReason: null,
moveEndRemove: null,
clickHandler: null,
clickSubscription: null,
timer: null,
googleSearchRequested: false,
/** Contacts subject position; when set, it replaces the camera viewport. */
@@ -38,7 +33,10 @@ export function createState({ services }) {
contextPosition: null,
/** Coverage of the last successful load: viewport, or radius around a subject. */
coverage: { kind: 'viewport' },
/** Per-record geometry keys of the rendered entities, for in-place updates. */
/**
* What each drawn record last drew: its geometry key, outline item ids,
* context carrier, height and selection, for in-place updates.
*/
renderedKeys: new Map(),
});
return state;
+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;