feat(map): add synthetic moving target layer

This commit is contained in:
Codex
2026-07-29 18:28:54 +03:00
parent 65644a8609
commit 08a3c47391
6 changed files with 578 additions and 14 deletions
@@ -1,12 +1,21 @@
import { useEffect, useRef } from "react";
import {
forwardRef,
useEffect,
useImperativeHandle,
useRef,
} from "react";
import type * as CesiumModule from "cesium";
import type {
CesiumMapRendererHandle,
CesiumMapRendererProps,
MapCamera,
MapGhostPin,
MapGhostPinLayer,
MapProviderId,
MapRuntimeState,
} from "./contracts.js";
import { advanceGhostPins } from "./ghostPins.js";
import {
parseProviderEndpoint,
type ProviderEndpoint,
@@ -30,31 +39,54 @@ type RendererRuntime = {
imageryLayer: CesiumModule.ImageryLayer | null;
buildings: CesiumModule.Cesium3DTileset | null;
grid: CesiumModule.CustomDataSource;
ghostPins: CesiumModule.CustomDataSource;
currentGhostPins: MapGhostPin[];
ghostPinSourceSignature: string;
stopGhostPinAnimation: (() => void) | null;
rebuildGrid: () => void;
};
export function CesiumMapRenderer({
runtimeConfigUrl,
camera,
layers,
settings,
cacheIntent,
rendererGeneration = 0,
className,
onRuntimeStateChange,
onCameraChange,
}: CesiumMapRendererProps) {
export const CesiumMapRenderer = forwardRef<
CesiumMapRendererHandle,
CesiumMapRendererProps
>(function CesiumMapRenderer({
runtimeConfigUrl,
camera,
layers,
settings,
cacheIntent,
ghostPins,
rendererGeneration = 0,
className,
onRuntimeStateChange,
onCameraChange,
}, forwardedRef) {
const containerRef = useRef<HTMLDivElement | null>(null);
const stateCallbackRef = useRef(onRuntimeStateChange);
const cameraCallbackRef = useRef(onCameraChange);
const runtimeRef = useRef<RendererRuntime | null>(null);
const settingsRef = useRef(settings);
const layersRef = useRef(layers);
const ghostPinsRef = useRef(ghostPins);
stateCallbackRef.current = onRuntimeStateChange;
cameraCallbackRef.current = onCameraChange;
settingsRef.current = settings;
layersRef.current = layers;
ghostPinsRef.current = ghostPins;
useImperativeHandle(forwardedRef, () => ({
getViewAnchor: () => {
const runtime = runtimeRef.current;
return runtime ? viewAnchor(runtime) : null;
},
snapshotGhostPins: () => {
const runtime = runtimeRef.current;
return runtime
? runtime.currentGhostPins.map((pin) => ({ ...pin }))
: null;
},
}), []);
useEffect(() => {
const runtime = runtimeRef.current;
@@ -63,7 +95,18 @@ export function CesiumMapRenderer({
}
applyPresentation(runtime, settings, layers);
runtime.rebuildGrid();
}, [settings, layers]);
syncGhostPinLayer(runtime, ghostPins);
updateGhostPinAnimation(
runtime,
Boolean(
ghostPins?.simulation_enabled
&& layers.targets
&& ghostPins.pins.length > 0
),
ghostPinsRef,
layersRef,
);
}, [settings, layers, ghostPins]);
useEffect(() => {
const container = containerRef.current;
@@ -101,7 +144,11 @@ export function CesiumMapRenderer({
viewer = createViewer(Cesium, container, creditContainer);
const ellipsoidTerrain = new Cesium.EllipsoidTerrainProvider();
const grid = new Cesium.CustomDataSource("nodedc-map-grid");
const ghostPinDataSource = new Cesium.CustomDataSource(
"nodedc-map-ghost-pins",
);
void viewer.dataSources.add(grid);
void viewer.dataSources.add(ghostPinDataSource);
const runtime: RendererRuntime = {
Cesium,
viewer,
@@ -110,6 +157,10 @@ export function CesiumMapRenderer({
imageryLayer: null,
buildings: null,
grid,
ghostPins: ghostPinDataSource,
currentGhostPins: [],
ghostPinSourceSignature: "",
stopGhostPinAnimation: null,
rebuildGrid: () => undefined,
};
runtime.rebuildGrid = () => {
@@ -121,6 +172,17 @@ export function CesiumMapRenderer({
applyPresentation(runtime, settingsRef.current, layersRef.current);
applyCamera(Cesium, viewer, camera);
runtime.rebuildGrid();
syncGhostPinLayer(runtime, ghostPinsRef.current);
updateGhostPinAnimation(
runtime,
Boolean(
ghostPinsRef.current?.simulation_enabled
&& layersRef.current.targets
&& ghostPinsRef.current.pins.length > 0
),
ghostPinsRef,
layersRef,
);
removeCameraListener = bindCamera(
Cesium,
viewer,
@@ -182,6 +244,7 @@ export function CesiumMapRenderer({
if (disposed) {
removeCameraListener?.();
removeRenderListener?.();
runtime.stopGhostPinAnimation?.();
}
} catch (error) {
if (!abortController.signal.aborted) {
@@ -204,6 +267,7 @@ export function CesiumMapRenderer({
abortController.abort();
removeCameraListener?.();
removeRenderListener?.();
runtimeRef.current?.stopGhostPinAnimation?.();
runtimeRef.current = null;
viewer?.destroy();
viewer = null;
@@ -220,7 +284,7 @@ export function CesiumMapRenderer({
]);
return <div ref={containerRef} className={className} data-nodedc-map-renderer="cesium" />;
}
});
function createViewer(
Cesium: CesiumNamespace,
@@ -426,6 +490,7 @@ function applyPresentation(
color: `color('${settings.buildings_color}', ${settings.buildings_opacity})`,
});
}
runtime.ghostPins.show = layers.targets;
viewer.terrainProvider =
layers.terrain && runtime.worldTerrain
? runtime.worldTerrain
@@ -486,6 +551,276 @@ function applyPresentation(
viewer.scene.requestRender();
}
function syncGhostPinLayer(
runtime: RendererRuntime,
layer: MapGhostPinLayer | undefined,
): void {
const nextPins = layer?.pins ?? [];
const sourceSignature = nextPins.map((pin) => [
pin.id,
pin.label,
pin.longitude,
pin.latitude,
pin.heading_degrees,
pin.speed_meters_per_second,
].join(":")).join("|");
if (sourceSignature !== runtime.ghostPinSourceSignature) {
runtime.currentGhostPins = nextPins.map((pin) => ({ ...pin }));
runtime.ghostPinSourceSignature = sourceSignature;
}
rebuildGhostPinEntities(runtime, layer);
}
function rebuildGhostPinEntities(
runtime: RendererRuntime,
layer: MapGhostPinLayer | undefined,
): void {
const { Cesium, viewer, ghostPins } = runtime;
ghostPins.entities.removeAll();
if (!layer) {
viewer.scene.requestRender();
return;
}
const presentation = layer.presentation;
const fillColor = cssColor(Cesium, presentation.color, "#6fb5fb").withAlpha(
clamp(presentation.opacity, 0, 1),
);
const outlineColor = cssColor(
Cesium,
presentation.outline_color,
"#0c0d12",
).withAlpha(clamp(presentation.outline_opacity, 0, 1));
const headImage = elevatedTargetImage(
fillColor,
outlineColor,
presentation.outline_width_px,
presentation.head_size_px,
);
const targetDistance = new Cesium.DistanceDisplayCondition(
0,
presentation.target_hide_camera_height_meters,
);
const labelDistance = new Cesium.DistanceDisplayCondition(
0,
presentation.label_hide_camera_height_meters,
);
for (const pin of runtime.currentGhostPins) {
const groundHeight = ghostPinGroundHeight(runtime, pin);
const headHeight = groundHeight + presentation.stem_height_meters;
const label = presentation.label_mode === "subject_id"
? pin.id
: pin.label;
ghostPins.entities.add({
id: pin.id,
position: Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
headHeight,
),
polyline: {
positions: [
Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
groundHeight,
),
Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
headHeight,
),
],
width: presentation.stem_width_px,
material: fillColor,
distanceDisplayCondition: targetDistance,
},
billboard: {
image: headImage.image,
width: headImage.size,
height: headImage.size,
horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
verticalOrigin: Cesium.VerticalOrigin.CENTER,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: targetDistance,
},
label: {
text: label.slice(0, presentation.label_max_length),
font: `${presentation.label_font_weight} ${presentation.label_size_px}px Arial`,
fillColor: cssColor(
Cesium,
presentation.label_color,
"#f5f5f5",
),
outlineColor: Cesium.Color.TRANSPARENT,
outlineWidth: 0,
style: Cesium.LabelStyle.FILL,
show: presentation.label_mode !== "none",
showBackground: presentation.label_background_opacity > 0,
backgroundColor: cssColor(
Cesium,
presentation.label_background_color,
"#0c0d12",
).withAlpha(clamp(presentation.label_background_opacity, 0, 1)),
backgroundPadding: new Cesium.Cartesian2(
presentation.label_padding_x,
presentation.label_padding_y,
),
pixelOffset: new Cesium.Cartesian2(
presentation.label_offset_x,
presentation.label_offset_y,
),
horizontalOrigin: Cesium.HorizontalOrigin.LEFT,
verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
heightReference: Cesium.HeightReference.NONE,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
distanceDisplayCondition: labelDistance,
},
});
}
viewer.scene.requestRender();
}
function animateGhostPins(
runtime: RendererRuntime,
layerRef: { current: MapGhostPinLayer | undefined },
layersRef: { current: CesiumMapRendererProps["layers"] },
): () => void {
let frame = 0;
let previousTime = performance.now();
const tick = (time: number) => {
const layer = layerRef.current;
const elapsedSeconds = (time - previousTime) / 1000;
previousTime = time;
if (
layer?.simulation_enabled
&& layersRef.current.targets
&& runtime.currentGhostPins.length > 0
) {
runtime.currentGhostPins = advanceGhostPins(
runtime.currentGhostPins,
layer.anchor,
layer.radius_meters,
elapsedSeconds,
);
updateGhostPinPositions(runtime, layer);
runtime.viewer.scene.requestRender();
}
frame = requestAnimationFrame(tick);
};
frame = requestAnimationFrame(tick);
return () => cancelAnimationFrame(frame);
}
function updateGhostPinAnimation(
runtime: RendererRuntime,
active: boolean,
layerRef: { current: MapGhostPinLayer | undefined },
layersRef: { current: CesiumMapRendererProps["layers"] },
): void {
runtime.stopGhostPinAnimation?.();
runtime.stopGhostPinAnimation = active
? animateGhostPins(runtime, layerRef, layersRef)
: null;
}
function updateGhostPinPositions(
runtime: RendererRuntime,
layer: MapGhostPinLayer,
): void {
const { Cesium, ghostPins } = runtime;
for (const pin of runtime.currentGhostPins) {
const entity = ghostPins.entities.getById(pin.id);
if (!entity) continue;
const groundHeight = ghostPinGroundHeight(runtime, pin);
const headHeight =
groundHeight + layer.presentation.stem_height_meters;
entity.position = new Cesium.ConstantPositionProperty(
Cesium.Cartesian3.fromDegrees(pin.longitude, pin.latitude, headHeight),
);
if (entity.polyline) {
entity.polyline.positions = new Cesium.ConstantProperty([
Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
groundHeight,
),
Cesium.Cartesian3.fromDegrees(
pin.longitude,
pin.latitude,
headHeight,
),
]);
}
}
}
function ghostPinGroundHeight(
runtime: RendererRuntime,
pin: MapGhostPin,
): number {
const cartographic = runtime.Cesium.Cartographic.fromDegrees(
pin.longitude,
pin.latitude,
);
return runtime.viewer.scene.globe.getHeight(cartographic) ?? 0;
}
function viewAnchor(runtime: RendererRuntime) {
const { Cesium, viewer } = runtime;
const canvas = viewer.scene.canvas;
const center = new Cesium.Cartesian2(
canvas.clientWidth / 2,
canvas.clientHeight / 2,
);
const ray = viewer.camera.getPickRay(center);
const intersection = ray
? viewer.scene.globe.pick(ray, viewer.scene)
: undefined;
const cartographic = intersection
? Cesium.Cartographic.fromCartesian(intersection)
: viewer.camera.positionCartographic;
if (!cartographic) return null;
return {
longitude: Cesium.Math.toDegrees(cartographic.longitude),
latitude: Cesium.Math.toDegrees(cartographic.latitude),
};
}
const elevatedTargetImageCache = new Map<string, string>();
function elevatedTargetImage(
fillColor: CesiumModule.Color,
outlineColor: CesiumModule.Color,
outlineWidthPx: number,
headSizePx: number,
) {
const safeHeadSize = Math.max(1, headSizePx);
const safeOutlineWidth = Math.max(0, outlineWidthPx);
const imageSize = Math.max(1, Math.ceil(safeHeadSize + safeOutlineWidth * 2));
const key = [
fillColor.toCssColorString(),
outlineColor.toCssColorString(),
safeOutlineWidth,
safeHeadSize,
imageSize,
].join("|");
const cached = elevatedTargetImageCache.get(key);
if (cached) return { image: cached, size: imageSize };
const center = imageSize / 2;
const radius = Math.max(0.5, safeHeadSize / 2);
const svg = [
`<svg xmlns="http://www.w3.org/2000/svg" width="${imageSize}" height="${imageSize}" viewBox="0 0 ${imageSize} ${imageSize}">`,
`<circle cx="${center}" cy="${center}" r="${radius}" fill="${fillColor.toCssColorString()}"`,
safeOutlineWidth > 0
? ` stroke="${outlineColor.toCssColorString()}" stroke-width="${safeOutlineWidth}"/>`
: "/>",
"</svg>",
].join("");
const image = `data:image/svg+xml;charset=utf-8,${encodeURIComponent(svg)}`;
elevatedTargetImageCache.set(key, image);
return { image, size: imageSize };
}
function rebuildElevatedGrid(
runtime: RendererRuntime,
settings: CesiumMapRendererProps["settings"],