feat(installations): add Navara renderer

This commit is contained in:
German Khokhlov committed 2026-10-28 12:18:03 +04:00
1 parent 965a82144c
commit 1a694baf5a
27 files changed
+1426 -47

No files matched your search

@@ -0,0 +1,113 @@
import * as Cesium from 'cesium';
import { LAYER_ID } from '../../policy.js';
import { engineFromViewer } from '../../../../globe/cesium/engineFromViewer.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../../../data/cameraSensitivity.js';
export function createLifecycle({
state: layerState,
services,
parts,
source,
}) {
const { registerPickOwner, unregisterPickOwner } = services.picking;
const { clearSelectedEntityContextForLayer } = services.context;
const methods = {
init(viewer, { engine = null } = {}) {
engine ||= engineFromViewer(viewer);
layerState.viewer = viewer;
layerState.engine = engine;
layerState.dataSource = new Cesium.CustomDataSource(
'military-installations',
);
const added = viewer.dataSources.add(layerState.dataSource);
const camera = engine?.camera ?? viewer.camera;
const cameraChanged = () => {
if (!layerState.contextAnchor) parts.viewport.scheduleLoad();
};
layerState.moveEndRemove = camera.moveEnd.addEventListener(cameraChanged);
layerState.changedRemove =
camera.changed?.addEventListener(cameraChanged);
parts.selection.installInteraction(viewer);
return added;
},
enable() {
layerState.enabled = true;
layerState.surfaceChangedRemove ||= services.maps?.subscribeMapStack(
parts.rendering.syncSelectionFill,
);
// Cached markers and geometry become visible before the next fetch.
if (
layerState.records?.some((r) =>
r.sources?.some((s) => s.name === 'OpenStreetMap'),
)
)
services.credits?.showOsmCredit?.(layerState.viewer, LAYER_ID, {
openMapTiles: layerState.records.some((r) =>
r.sources?.some(
(s) => s.name === 'OpenStreetMap' && s.id?.startsWith('tile:'),
),
),
});
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;
// DataLayerManager invokes update() immediately after enable(), which owns
// the first fetch. Avoid racing it with a second aborting request here.
},
disable() {
layerState.enabled = false;
services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
services.credits?.hideGooglePlacesCredit?.(layerState.viewer, LAYER_ID);
parts.namedMarkers?.hide();
releaseCameraSensitivity(layerState.viewer?.camera, LAYER_ID);
layerState.contextAnchor = null;
layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' };
layerState.cameraLoadKey = null;
layerState.cameraLoadOwner = null;
unregisterPickOwner(LAYER_ID);
parts.viewport.clearUnavailableRetry();
clearTimeout(layerState.timer);
layerState.abort?.abort();
layerState.abort = null;
layerState.loading = false;
if (layerState.dataSource) layerState.dataSource.show = false;
clearSelectedEntityContextForLayer(LAYER_ID);
layerState.selectedId = null;
parts.rendering.clearSelectionFill?.();
layerState.surfaceChangedRemove?.();
layerState.surfaceChangedRemove = null;
layerState.failureReason = null;
parts.ingestion.setInstallationStatus('idle');
},
destroy(viewer) {
source.destroy?.();
this.disable();
layerState.contextAnchor = null;
layerState.contextPosition = null;
layerState.coverage = { kind: 'viewport' };
layerState.moveEndRemove?.();
layerState.changedRemove?.();
parts.selection.destroy?.();
layerState.clickHandler?.destroy();
layerState.clickHandler = null;
parts.namedMarkers?.destroy();
parts.rendering.clearRendered();
if (layerState.dataSource && viewer)
viewer.dataSources.remove(layerState.dataSource, true);
layerState.dataSource = null;
layerState.engine = null;
},
};
return { methods };
}
@@ -0,0 +1,226 @@
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 { createInfrastructureOverlayEntry } from '../../../../data/infrastructureOverlayEntry.js';
/** Bounded point markers; the shared overlay owns text projection and decluttering. */
export function createNamedMarkers({ state, services, parts, overlayHost }) {
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;
let ordered = [];
const viewMatrix = new Cesium.Matrix4();
let width = 0,
height = 0;
let removeChanged = null,
removeEnd = null,
removeFrame = null;
function refresh() {
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;
for (let index = 0; index < ordered.length; index++) {
const marker = ordered[index];
const point = marker.point;
point.show = Boolean(
marker.named && occluder.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++;
}
}
function publishLabels() {
overlayHost.setEntries(LAYER_ID, entries, {
// Keep the bounded point cohort available while Contacts owns the window.
// The arbiter spends at most 24 slots on currently visible, separated titles.
cohortLimit: MILITARY_POINT_CAP,
collisionCapacity: MILITARY_LABEL_CAP,
maxVisible: MILITARY_LABEL_CAP - (state.selectedId ? 1 : 0),
moving: false,
visible: state.enabled,
});
}
function cameraChanged() {
refresh();
services.render.governorRequestRender('installation-names');
}
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();
}
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);
if (points) points.show = true;
publishLabels();
overlayHost.setVisible(LAYER_ID, true);
cameraChanged();
}
function hide() {
removeChanged?.();
removeEnd?.();
removeFrame?.();
removeChanged = removeEnd = removeFrame = null;
if (points) points.show = false;
overlayHost.clearSource(LAYER_ID);
overlayHost.setVisible(LAYER_ID, false);
shownPoints = 0;
}
function sync(records) {
const viewer = state.viewer;
if (!viewer?.scene?.primitives) return;
if (!points) {
points = viewer.scene.primitives.add(
new Cesium.PointPrimitiveCollection(),
);
}
points.show = state.enabled;
const named = records
.filter((r) => r.namedArea || r.id === state.selectedId)
.sort(
(a, b) =>
Number(b.id === state.selectedId) -
Number(a.id === state.selectedId) || b.areaM2 - a.areaM2,
)
.slice(0, MILITARY_POINT_CAP);
const keep = new Set(named.map((r) => r.id));
for (const record of named) {
if (markers.has(record.id)) continue;
const alias = record.aliasIds?.find(
(id) => !keep.has(id) && markers.has(id),
);
if (!alias) continue;
const marker = markers.get(alias);
markers.delete(alias);
marker.point.id = { installationId: 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);
}
ordered = [];
entries = [];
for (const record of named) {
const position = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
record.pointOnly
? 0
: parts.rendering.installationSurfaceHeightM(record),
);
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,
}),
entry: createInfrastructureOverlayEntry({
id: record.id,
source: LAYER_ID,
position,
title: record.name,
priority: record.areaM2 || 0,
accent: COLOR_BY_CLASS[record.class] || '#9ca6b0',
}),
};
markers.set(record.id, marker);
} else {
marker.point.position = position;
}
marker.named = record.namedArea;
marker.entry.variant =
record.id === state.selectedId ? 'selected' : 'card';
marker.entry.selected = record.id === state.selectedId;
marker.entry.details = marker.entry.selected
? [
String(record.class || 'installation')
.replaceAll('_', ' ')
.toUpperCase(),
...(record.memberNames || []).slice(0, 3),
]
: [];
marker.entry.position = position;
marker.entry.title = record.name;
marker.entry.priority = record.areaM2 || 0;
entries.push(marker.entry);
ordered.push(marker);
}
if (state.enabled) publishLabels();
refresh();
services.render.governorRequestRender('installation-names');
}
return {
sync,
visit(visitor) {
for (let i = 0; i < ordered.length; i++) {
const marker = ordered[i];
visitor(marker.point.id.installationId, marker.point);
}
},
refresh,
enable,
hide,
stats: () => ({
namedMarkers: markers.size,
pointsOnScreen: shownPoints,
labelsOnScreen: state.enabled
? overlayHost.getDiagnostics?.().paintedBySource[LAYER_ID] || 0
: 0,
labelCap: MILITARY_LABEL_CAP,
}),
destroy() {
hide();
ordered = [];
if (points) state.viewer?.scene.primitives.remove(points);
points = null;
entries = [];
markers.clear();
},
};
}
@@ -0,0 +1,374 @@
import * as Cesium from 'cesium';
import { LAYER_ID, MAX_RENDERED, COLOR_BY_CLASS } from '../../policy.js';
export function createRendering({
state: layerState,
services,
parts,
source,
}) {
const { floorAltitudeM, cachedGroundFloor } = services.ground;
const {
removeEntityContextsForLayer,
getSelectedEntityContext,
registerEntityContext,
selectEntityContext,
} = services.context;
const { governorRequestRender } = services.render;
const { warmFireAnchorFloors } = services.anchors;
/**
* Shared rendered-surface height for an installation anchor or footprint.
* @param {{latitude:number, longitude:number}} record Installation record.
* @returns {number} Ellipsoidal render height in metres.
*/
function installationSurfaceHeightM(record) {
return (
floorAltitudeM(
null,
cachedGroundFloor(record?.latitude, record?.longitude),
) ?? 0
);
}
let selectedFillKey = null;
const selectedFillIds = [];
function clearSelectionFill() {
for (const id of selectedFillIds)
layerState.dataSource?.entities.removeById(id);
selectedFillIds.length = 0;
selectedFillKey = null;
}
/** Ground geometry classifies the active surface; no height/extrusion plane. */
function syncSelectionFill() {
const record =
layerState.enabled && 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}`;
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);
}
governorRequestRender('installation-selection-fill');
}
function clearRendered() {
clearSelectionFill();
if (layerState.dataSource?.entities)
layerState.dataSource.entities.removeAll();
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.
* @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] : []);
let points = 0;
for (const rings of footprints)
for (const ring of rings) points += ring.length;
for (const line of outlines) points += line.length;
return [
record.latitude.toFixed(6),
record.longitude.toFixed(6),
record.class,
record.kind,
record.name,
footprints.length,
outlines.length,
points,
].join('|');
}
function removeRecordEntities(id) {
const entities = layerState.dataSource.entities;
for (const entityId of layerState.renderedKeys.get(id)?.entityIds || [])
entities.removeById(entityId);
layerState.renderedKeys.delete(id);
}
/**
* The records that get entities 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
* on the floor, leaving the Context subject stale so NEXT offered the same
* installation forever. One extra entity keeps every cohort item selectable
* and the cohort count honest.
* @returns {Array<object>} Records to render this paint.
*/
function renderableRecords() {
const rendered = layerState.records
.filter((r) => !r.pointOnly)
.slice(0, MAX_RENDERED);
if (!layerState.selectedId) return rendered;
if (rendered.some((record) => record.id === layerState.selectedId))
return rendered;
const selected = layerState.recordById.get(layerState.selectedId);
return selected ? [...rendered, selected] : rendered;
}
function syncPlacesCredit(records) {
const usesPlaces = records.some((record) =>
record.sources?.some((source) => source.name === 'Google Maps Places'),
);
if (usesPlaces)
services.credits?.showGooglePlacesCredit?.(layerState.viewer, LAYER_ID);
else
services.credits?.hideGooglePlacesCredit?.(layerState.viewer, LAYER_ID);
}
function renderRecords({ claimSelection = false } = {}) {
// Context navigation can select another layer without a canvas click.
// A delayed floor/data repaint must not steal that newer selection back.
const selectedContext = getSelectedEntityContext();
if (
!claimSelection &&
layerState.selectedId &&
(!selectedContext || selectedContext.id !== layerState.selectedId)
) {
layerState.selectedId = null;
}
let migratedSelection = false;
if (
layerState.selectedId &&
!layerState.recordById.has(layerState.selectedId)
) {
const replacement = layerState.records.find((record) =>
record.aliasIds?.includes(layerState.selectedId),
);
if (replacement) {
layerState.selectedId = replacement.id;
migratedSelection = true;
}
}
// Post-moveEnd debounced fetches commit after the camera settles; the
// rebuilt entities need one frame in idle mode. (perf wave 2 fix)
governorRequestRender('installations-render');
if (
layerState.records.some((r) =>
r.sources?.some((s) => s.name === 'OpenStreetMap'),
)
)
services.credits?.showOsmCredit?.(layerState.viewer, LAYER_ID, {
openMapTiles: layerState.records.some((r) =>
r.sources?.some(
(s) => s.name === 'OpenStreetMap' && s.id?.startsWith('tile:'),
),
),
});
else services.credits?.hideOsmCredit?.(layerState.viewer, LAYER_ID);
syncPlacesCredit(layerState.records);
const records = renderableRecords();
const keys = new Map(
records.map((record) => [record.id, renderKey(record)]),
);
const entities = layerState.dataSource.entities;
entities.suspendEvents();
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 surfaceHeightM = installationSurfaceHeightM(record);
const displayPosition = Cesium.Cartesian3.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, {
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: new Cesium.ColorMaterialProperty(color.withAlpha(0.85)),
clampToGround: true,
classificationType: Cesium.ClassificationType.BOTH,
},
});
outline.installationId = record.id;
entityIds.push(outline.id);
}
entity.gevInstallationHeightM = surfaceHeightM;
entity.gevInstallationSelected = selectedRecord;
entity.gevTrackedId = `installations:${record.id}`;
entity.gevDisplayPosition = () => displayPosition;
entity.gevLabelModel = {
title: record.name || 'MAPPED INSTALLATION',
details: [
String(record.class || 'installation')
.replaceAll('_', ' ')
.toUpperCase(),
...(record.memberNames || []).slice(0, 3),
],
accent: COLOR_BY_CLASS[record.class] || '#9ca6b0',
};
registerEntityContext(entity, {
id: record.id,
layerId: LAYER_ID,
layerName:
record.kind === 'place_candidate'
? 'Military Site Search Candidates'
: 'Mapped Military Installations',
source: parts.model.installationSourceLabel(record),
label: record.name,
latitude: record.latitude,
longitude: record.longitude,
properties: {
class: record.class,
memberNames: record.memberNames || [],
primaryType: record.primaryType || null,
placeTypes: Array.isArray(record.placeTypes) ? record.placeTypes : [],
validation: record.validation,
retrievedAt: record.retrievedAt,
},
});
}
entities.resumeEvents();
const selectedEntity = layerState.selectedId
? layerState.dataSource.entities.getById(layerState.selectedId)
: null;
if (selectedEntity && (claimSelection || migratedSelection))
selectEntityContext(selectedEntity);
else if (!selectedEntity) 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);
syncSelectionFill();
}
/**
* Second paint for floors that missed the bounded pre-render deadline.
*
* `resolveGroundFloorCellsBounded` gives up after FLOOR_RESOLVE_DEADLINE_MS so
* a cold DEM can never hold the dots hostage — but the resolve keeps running
* and lands seconds later, and without this the records it covers stay pinned
* at ellipsoid height 0, sitting visibly under the 3D tiles (owner playtest
* 2026-08-18: "orange dots at the bottom").
*
* This is the render -> warm -> re-render chain FIRMS already uses, with one
* difference the installations path forces: the trigger is whether a cell that
* was COLD AT PAINT TIME is warm now, not whether this particular batch warmed
* it. The bounded resolve above is still running against the same cells, so
* asking "did MY batch warm anything" would answer false exactly when the other
* resolve won the race — the common case. Still terminating: a set that is
* wholly cold afterwards re-renders zero times and the next camera-driven load
* retries.
* @param {Array<object>} records Records just rendered.
* @returns {void}
*/
function warmInstallationFloors(records) {
const cold = records
.filter(
(record) =>
cachedGroundFloor(record.latitude, record.longitude) == null,
)
.map((record) => ({ lat: record.latitude, lon: record.longitude }));
if (!cold.length) return;
warmFireAnchorFloors(cold).then(() => {
if (!layerState.enabled || !layerState.dataSource) return;
if (
!cold.some((point) => cachedGroundFloor(point.lat, point.lon) != null)
)
return;
renderRecords();
});
}
return {
installationSurfaceHeightM,
clearSelectionFill,
syncSelectionFill,
clearRendered,
renderableRecords,
renderRecords,
warmInstallationFloors,
};
}
@@ -0,0 +1,72 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { rgbaFromCss } from '../../../shared/color.js';
import { createRendering } from './rendering.js';
test('Cesium installation outlines use a valid material and retain ground clamping', () => {
const id = 'osm:way:980001';
const footprint = [
[-122.438, 37.758],
[-122.402, 37.758],
[-122.402, 37.782],
[-122.438, 37.782],
];
const record = {
id,
kind: 'installation',
class: 'airfield',
name: 'QA Airfield',
latitude: 37.77,
longitude: -122.42,
footprint,
};
const state = {
enabled: true,
selectedId: null,
records: [record],
recordById: new Map([[id, record]]),
renderedKeys: new Map(),
dataSource: new Cesium.CustomDataSource('military-installations'),
viewer: { scene: { globe: { show: false } } },
};
const services = {
ground: { floorAltitudeM: () => 125, cachedGroundFloor: () => ({}) },
anchors: { warmFireAnchorFloors: async () => false },
render: { governorRequestRender() {} },
context: {
getSelectedEntityContext: () => null,
registerEntityContext() {},
removeEntityContextsForLayer() {},
selectEntityContext() {},
},
};
const parts = {
model: {
colorFor: () => rgbaFromCss('#ff8000'),
installationSourceLabel: () => 'OpenStreetMap',
},
};
Object.assign(
parts,
createRendering({ state, services, parts, source: {} }),
);
parts.renderRecords();
const time = Cesium.JulianDate.now();
const marker = state.dataSource.entities.getById(id);
const outline = state.dataSource.entities.getById(`${id}:outline:0`);
assert.equal(
marker.point.heightReference.getValue(time),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
assert.ok(outline.polyline.material instanceof Cesium.ColorMaterialProperty);
assert.equal(outline.polyline.clampToGround.getValue(time), true);
for (const position of outline.polyline.positions.getValue(time))
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(position).height,
) < 0.01,
);
});
@@ -0,0 +1,84 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../../../data/inputOwnership.js';
import { LAYER_ID } from '../../policy.js';
export function createSelection({
state: layerState,
services,
parts,
source,
}) {
const { clearSelectedEntityContextForLayer } = services.context;
let removeContextListeners = null;
function syncContextSelection(event) {
if (!layerState.enabled) return;
// Tracking layers publish this event before replacing the shared context.
const selected =
event?.type === 'gev:awareness-subject-selected'
? event.detail
: services.context.getSelectedEntityContext();
const next =
selected?.layerId === LAYER_ID && layerState.recordById.has(selected.id)
? selected.id
: null;
if (next === layerState.selectedId) return;
layerState.selectedId = next;
parts.rendering.renderRecords();
}
function selectRecord(id) {
const record = layerState.recordById.get(id);
if (!record || !layerState.dataSource) return false;
layerState.selectedId = id;
parts.rendering.renderRecords({ claimSelection: true });
// renderRecords drops selectedId when the record produced no entity.
return layerState.selectedId === id;
}
function installInteraction(viewer) {
if (layerState.clickHandler) return;
const events = [
'gev:entity-selected',
'gev:entity-selection-cleared',
'gev:awareness-subject-selected',
];
for (const event of events)
globalThis.window?.addEventListener?.(event, syncContextSelection);
removeContextListeners = () => {
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;
if (!layerState.enabled) return;
const picked = viewer.scene.pick(click.position);
const id =
picked?.id?.installationId ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
if (id && layerState.recordById.has(id) && id !== layerState.selectedId) {
selectRecord(id);
} else if (layerState.selectedId) {
// Clicking the selected site again, empty map, or another contact
// releases this layer's selection. Clear only our shared context so a
// sibling click handler's newly selected aircraft/site stays intact.
layerState.selectedId = null;
clearSelectedEntityContextForLayer(LAYER_ID);
parts.rendering.renderRecords();
}
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
}
return {
selectRecord,
installInteraction,
destroy() {
removeContextListeners?.();
removeContextListeners = null;
},
};
}