Draw CCTV coverage, viewsheds and the monitor plane through the renderer ports and take projection.js off the Cesium list

The frustum wireframes, viewshed volumes and the active camera's monitor
plane are now line, mesh and quad items of the layer's own draw sets
(layers/cctv/drawSets.js), written from plain handles only as they change.
The plane takes its canvas double buffer or its video as a quad source.
Picks of lines and planes are matched by set, item id and the record that
draws them. The activation obstruction probe casts through the query
port's rayCast; its clamp lands a microtask later, rewrites the geometry
and asks again for the footprint ground, and a newer activation, a range
edit, a deactivation or a re-init drops an answer still to come.
This commit is contained in:
Sameh Khamis committed 2026-11-08 08:35:12 -08:00
1 parent bbad02b73e
commit 2a607ec4d8
20 files changed
+918 -492

No files matched your search

+2
View File
@@ -261,6 +261,8 @@ export function createCalibration({
// §9.1: touching range takes manual control — clear the activation clamp.
if ('rangeScale' in patch) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
}
const anchorMoved = calibrationPatchMovesAnchor(patch);
if (options.transient === true && anchorMoved) {
+188
View File
@@ -0,0 +1,188 @@
/**
* @module layers/cctv/drawSets
* @description The CCTV layer's draw sets: the frustum wireframes
* (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the
* active camera's monitor plane (`plane`, a quad), made through the draw
* port of the viewer the layer is on. They are made when first drawn into
* and made again on another viewer. Item ids keep the layer's
* `cctv-<cameraId>-<role>` scheme the shared pick registry reads, and each
* line's and plane's `meta.cameraId` names its camera (volumes are never
* picked and carry none).
*
* Coverage lines and the plane are written from handles the layer keeps
* (a record's `coverageEntities`, a projection runtime's `plane`): plain
* objects the layer changes and then writes, only what changed reaching
* the set.
*/
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
let instances = 0;
/** A line handle's item, or null for a handle that names no line yet. */
function lineItemOf(handle) {
if (!handle?.id || !Array.isArray(handle.positions)) return null;
const color = handle.color;
return {
id: handle.id,
positions: handle.positions,
widthPx: handle.widthPx,
// As a polyline entity runs: along the ellipsoid between its positions.
mode: 'geodesic',
style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color },
depthFailColor: handle.depthFailColor ?? null,
meta: { cameraId: handle.cameraId },
show: handle.show !== false,
};
}
/** What a line item draws, as a key: an unchanged key is not written. */
const lineKey = (item) =>
[
item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'),
item.widthPx,
item.style.kind,
item.style.color.join(','),
item.depthFailColor ? item.depthFailColor.join(',') : '',
item.show,
].join('|');
/** The plane handle's quad item. */
function quadItemOf(plane) {
return {
id: plane.id,
center: plane.center,
orientation: plane.orientation,
size: plane.size,
source: plane.source,
alpha: plane.alpha,
outline: plane.outline,
meta: { cameraId: plane.cameraId },
show: plane.show === true,
};
}
export function createDrawSets({ state: layerState }) {
/** The live sets and the viewer they draw on, or null. */
let current = null;
/** Viewshed volumes written, ever (the QA harness checks for churn). */
let volumeWrites = 0;
/** The layer's sets on its viewer now, made if need be; null with none. */
function sets() {
const viewer = layerState._viewer;
if (!viewer) return null;
if (current?.viewer === viewer) return current;
dispose();
const draw = drawOf(viewer);
const n = ++instances;
current = {
viewer,
coverage: draw.lines({ id: `cctv:${n}:coverage` }),
viewshed: draw.meshes({ id: `cctv:${n}:viewshed`, pickable: false }),
plane: draw.quads({ id: `cctv:${n}:plane` }),
// What each line item was last written as, by id.
lineKeys: new Map(),
};
return current;
}
/** The live sets, without making them. */
const live = () =>
current && current.viewer === layerState._viewer ? current : null;
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set.dispose();
} catch {
// Its viewer went first.
}
current = null;
}
/** The ids of the sets that draw the layer's lines and plane. */
function pickableSetIds() {
const s = live();
return s ? [s.coverage.id, s.plane.id] : [];
}
/** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */
function roleOfSet(setId) {
const s = live();
if (!s) return null;
if (setId === s.coverage.id) return 'coverage';
if (setId === s.plane.id) return 'plane';
return null;
}
/** Write line handles that changed since they were last written. */
function writeLines(handles) {
if (!handles?.length) return;
const s = handles.some((h) => h?.id) ? sets() : null;
if (!s) return;
const changed = [];
for (const handle of handles) {
const item = lineItemOf(handle);
if (!item) continue;
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
}
/** Take every line out. */
function clearLines() {
const s = live();
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
sets()?.plane.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
if (plane?.id) live()?.plane.remove([plane.id]);
}
/** Write a viewshed volume. */
function writeVolume(item) {
const s = sets();
if (!s) return;
s.viewshed.upsert([item]);
volumeWrites += 1;
}
/** Take a viewshed volume out. */
function removeVolume(id) {
if (id) live()?.viewshed.remove([id]);
}
/** How many viewshed volumes were written, for the QA harness. */
const volumeWritesForTest = () => volumeWrites;
return {
sets,
dispose,
pickableSetIds,
roleOfSet,
writeLines,
clearLines,
writePlane,
removePlane,
writeVolume,
removeVolume,
volumeWritesForTest,
};
}
+110
View File
@@ -0,0 +1,110 @@
// The CCTV layer's draw sets: lines written only as they change, dashed for
// an estimated bearing, the depth-fail colour passed as it is; the sets made
// again on another viewer and let go on dispose.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDrawSets } from './drawSets.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const line = (id, fields = {}) => ({
id,
cameraId: 'cam',
role: 'edge',
positions: [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
],
widthPx: 1.2,
color: [0.1, 0.2, 0.3, 0.4],
dashed: false,
depthFailColor: null,
show: true,
...fields,
});
test('lines are written as they change, and drawn as their handles say', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
const a = line('cctv-cam-ray-tl');
const b = line('cctv-cam-cap', { role: 'cap' });
drawSets.writeLines([a, b]);
const coverage = draw.find('cctv:');
assert.equal(coverage.kind, 'lines');
assert.equal(coverage.writes, 1);
assert.deepEqual(coverage.items.get(a.id), {
id: a.id,
positions: a.positions,
widthPx: 1.2,
mode: 'geodesic',
style: { kind: 'solid', color: a.color },
depthFailColor: null,
meta: { cameraId: 'cam' },
show: true,
});
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 1, 'unchanged handles write nothing');
b.dashed = true;
b.depthFailColor = [1, 1, 1, 0.2];
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 2);
const cap = coverage.items.get(b.id);
assert.deepEqual(cap.style, {
kind: 'dash',
color: b.color,
length: 16,
pattern16: 255,
});
assert.deepEqual(cap.depthFailColor, [1, 1, 1, 0.2]);
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null);
drawSets.clearLines();
assert.equal(coverage.items.size, 0);
drawSets.writeLines([a]);
assert.ok(coverage.items.has(a.id), 'a cleared line is written again');
} finally {
unbind();
}
});
test('another viewer gets sets of its own; dispose lets them go', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
const old = one.draw.find('cctv:');
assert.equal(drawSets.volumeWritesForTest(), 1);
state._viewer = second;
assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet');
drawSets.writeLines([a]);
assert.ok(old.disposed, 'the old viewer’s sets are let go');
const now = two.draw.find('cctv:');
assert.ok(now.items.has(a.id), 'the line is written anew');
const [coverage, plane] = drawSets.pickableSetIds();
assert.equal(two.draw.set(coverage).kind, 'lines');
assert.equal(two.draw.set(plane).kind, 'quads');
assert.equal(drawSets.roleOfSet(plane), 'plane');
drawSets.dispose();
assert.ok(
[...two.draw.sets.values()].every((set) => set.disposed),
'every set is let go',
);
assert.equal(drawSets.roleOfSet(coverage), null);
} finally {
one.unbind();
two.unbind();
}
});
+8 -8
View File
@@ -106,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Blits the latest projection canvas into the next of two alternating
* offscreen buffer canvases and returns it (H5).
*
* Two buffers are required because Cesium's Material image path re-uploads a
* canvas texture only when the uniform receives a NEW object reference —
* redrawing the same canvas in place is invisible to the GPU. Alternating
* Two buffers are required because the plane re-uploads a canvas texture
* only when it is given a NEW canvas — redrawing the same canvas in place
* is invisible to the GPU. Alternating
* references forces a texture recreate, which at <=1Hz and 1080p is cheap.
*
* @param {Object} runtime - Projection runtime with `.canvas`.
@@ -139,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Pushes fresh pixels into the monitor plane material. Called every
* projection tick.
*
* Video feeds are skipped entirely — their HTMLVideoElement uniform is
* updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap
* Video feeds are skipped entirely — the renderer reads their
* HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap
* the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS.
*
* @param {Object} record - Camera record with an initialized projection runtime.
@@ -156,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
)
return;
const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial);
const planeShowing = !!runtime.plane?.show;
if (!planeShowing) return;
// Only swap when the canvas content actually changed since the last swap.
@@ -170,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
if (!buffer) return;
runtime.lastTextureSwapAt = now;
runtime.lastSwappedCanvasStamp = runtime.canvasStamp;
runtime.planeMaterial.image = buffer;
parts.projection.setPlaneSource(runtime, { canvas: buffer });
}
/**
@@ -346,7 +346,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
// camera republished once in 5 minutes, an Austin one not at all.
// Redrawing regardless bumped canvasStamp, which forced a buffer swap
// and a fresh 1920x1080 texture upload; the plane renders its white
// base color (planeMaterial color = WHITE, alpha .95) for the frame or
// base color (white, alpha .95) for the frame or
// two Cesium needs to rebind, which IS the periodic white flash from the
// owner field tests (2026-07-04 and 2026-07-30).
const fit = fitToProjection(
+46 -37
View File
@@ -314,30 +314,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.position = positions.mount;
record.camera.absoluteHeightM = geometry.mount.alt;
parts.rendering.moveCameraIcon(record);
record.groundAltM = groundAltM;
if (record.coverageEntities?.length >= 5) {
record.coverageEntities[0].polyline.positions = [
positions.mount,
positions.tl,
];
record.coverageEntities[1].polyline.positions = [
positions.mount,
positions.tr,
];
record.coverageEntities[2].polyline.positions = [
positions.mount,
positions.br,
];
record.coverageEntities[3].polyline.positions = [
positions.mount,
positions.bl,
];
record.coverageEntities[4].polyline.positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
parts.rendering.placeCoverageLines(record.coverageEntities, positions);
parts.drawSets.writeLines(record.coverageEntities);
}
// A live viewshed volume tracks its wireframe: rebuild from the SAME fresh
// positions (weld invariant). Only records currently showing a volume pay
@@ -345,7 +325,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
// Tint derives from the live active id, not the cached viewshedActiveTint —
// during an activation switch this runs BEFORE refreshCoverageStyles, and
// the cache is stale for exactly that window.
if (record.viewshedPrimitive) {
if (record.viewshedVolume) {
parts.rendering.rebuildViewshedVolume(
record,
record.camera.id === layerState._activeCameraId,
@@ -420,11 +400,9 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.groundMeshSampleRequestCount =
(record.groundMeshSampleRequestCount || 0) + 1;
const eye = parts.model.eyePose();
const excludeObjects = [...(record.coverageEntities || [])];
if (record.projection?.planeEntity)
excludeObjects.push(record.projection.planeEntity);
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
excludeObjects: excludeObjects.filter(Boolean),
// The layer's own lines and plane are not ground; named all the same.
sampleMeshFloorCells(layerState._viewer, [point], {
sets: parts.drawSets.pickableSetIds(),
viewerLat: eye ? eye.lat : undefined,
viewerLon: eye ? eye.lon : undefined,
});
@@ -526,7 +504,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
/**
* §9.1 activation obstruction probe (LOCKED owner decision): on camera
* ACTIVATION only, fire ONE scene.pickFromRay along the frustum axis
* ACTIVATION only, cast ONE ray against the scene along the frustum axis
* (mount → cap-center direction). If it hits the tiles closer than the pose
* range, clamp the plane's effective range just short of the first hit so the
* "big and dramatic" true end cap never clips into downtown buildings.
@@ -535,28 +513,58 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* never per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range.
*
* The cast is made now, against the scene as it is, and answers a
* microtask later: the clamp then lands by rewriting the geometry from the
* ground it was last written at, before the next frame draws. A newer
* activation, or the camera's deactivation, drops an answer still to come.
* @param {Object} record - Camera record being activated.
* @returns {Promise<void>} Settled once the clamp (if any) has landed.
*/
function runActivationObstructionProbe(record) {
record.probeClampRangeM = null;
if (!parts.rendering.canPickFromRay()) return;
const token = (record.probeToken = (record.probeToken || 0) + 1);
const viewer = layerState._viewer;
if (!parts.rendering.canPickFromRay()) return Promise.resolve();
const camera = record.camera;
const rangeScale = parts.calibration.normalizeCalibration(
camera.calibration,
).rangeScale;
if (Math.abs(rangeScale - 1) > 0.0001) return; // slider overrides the clamp
// The slider overrides the clamp.
if (Math.abs(rangeScale - 1) > 0.0001) return Promise.resolve();
try {
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
const { dir } = frustumFrameEcef(camera, mountPos);
// The rendering part sees through everything the layer draws.
const hit = parts.rendering.obstructionHit(mountPos, dir);
if (!hit?.position) return;
const dist = distance(mountPos, hit.position);
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
// The cast sees through everything the layer draws.
return Promise.resolve(parts.rendering.obstructionHit(mountPos, dir))
.then((hit) => {
if (!hit || record.probeToken !== token) return;
if (record.camera.id !== layerState._activeCameraId) return;
// A layer torn down or re-initialised since (another viewer, or
// a new record for the same camera) is not the one it asked for.
if (layerState._viewer !== viewer) return;
if (layerState._recordById?.get(record.camera.id) !== record) return;
const dist = distance(mountPos, hit);
const clamp = activationProbeClampRange(camera.rangeM, dist);
if (!Number.isFinite(clamp)) return;
record.probeClampRangeM = clamp;
if (Number.isFinite(record.groundAltM))
applyFrustumGeometry(record, record.groundAltM);
// The activation asked for the ground under the unclamped plane's
// footprint; the clamped plane's is asked for now, and the layer
// restyles and tells its listeners, as that answer will.
void parts.ground.resolveFootprintGround(record);
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
})
.catch(() => {
// probe failure → keep the unclamped range
});
} catch {
// probe failure → keep the unclamped range
return Promise.resolve();
}
}
@@ -569,6 +577,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
*/
function clearProbeClampOnDeactivation(record, rewriteGeometry) {
if (record) record.probeToken = (record.probeToken || 0) + 1;
if (!record || !Number.isFinite(record.probeClampRangeM)) return false;
record.probeClampRangeM = null;
rewriteGeometry?.(record);
+88
View File
@@ -92,3 +92,91 @@ test('the frustum axis and plane orientation match the renderer transforms exact
assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]);
}
});
test('the activation probe clamps the range once its ray answers, unless the camera moved on', async () => {
const { createRendering } = await import('./rendering.js');
const p = {};
const state = { _activeCameraId: 'cam', _viewer: {} };
const context = {
state,
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
const written = [];
const footprints = [];
let restyles = 0;
let notices = 0;
let hitAtM = 80;
p.model = createModel(context);
p.geometry = createGeometry(context);
p.rendering = {
...createRendering(context),
canPickFromRay: () => true,
refreshCoverageStyles: () => (restyles += 1),
// The first surface `hitAtM` metres along the axis.
obstructionHit: async (origin, direction) => ({
x: origin.x + direction.x * hitAtM,
y: origin.y + direction.y * hitAtM,
z: origin.z + direction.z * hitAtM,
}),
};
p.calibration = { normalizeCalibration: () => ({ rangeScale: 1 }) };
p.ground = {
groundAltFor: () => 100,
resolveFootprintGround: async (r) =>
footprints.push(p.geometry.footprintPose(r)),
};
p.presentation = { notifyListeners: () => (notices += 1) };
p.drawSets = { writeLines: (lines) => written.push(lines) };
p.projection = { updatePlanePlacement() {} };
const record = {
camera: {
id: 'cam',
lon: -97.74,
lat: 30.27,
headingDeg: 90,
pitchDeg: -10,
fovDeg: 60,
rangeM: 200,
mountHeightM: 8,
},
coverageEntities: [],
};
state._recordById = new Map([['cam', record]]);
p.geometry.applyFrustumGeometry(record, 100);
assert.equal(record.frustumGeometry.rangeM, 200, 'unclamped at first');
const landed = p.geometry.runActivationObstructionProbe(record);
assert.equal(record.probeClampRangeM, null, 'the answer is still to come');
await landed;
const clamp = p.geometry.activationProbeClampRange(200, 80);
assert.ok(Math.abs(record.probeClampRangeM - clamp) < 1e-6);
assert.ok(
Math.abs(record.frustumGeometry.rangeM - clamp) < 1e-6,
'the geometry is rewritten at the clamp, from the ground it had',
);
assert.equal(record.frustumGeometry.mount.alt, 108);
assert.deepEqual(
footprints,
[p.geometry.footprintPose(record)],
"the clamped plane's footprint ground is asked for",
);
assert.ok(
Math.abs(footprints[0].rangeM - clamp) < 1e-6,
'at the clamped pose',
);
assert.deepEqual([restyles, notices], [1, 1]);
// A probe whose camera is deactivated before it answers lands nothing.
hitAtM = 50;
const stale = p.geometry.runActivationObstructionProbe(record);
p.geometry.clearProbeClampOnDeactivation(record, () => {});
await stale;
assert.equal(record.probeClampRangeM, null);
// Nor does one whose record a re-init replaced for the same camera.
const replaced = p.geometry.runActivationObstructionProbe(record);
state._recordById = new Map([['cam', { ...record }]]);
await replaced;
assert.equal(record.probeClampRangeM, null);
});
+2
View File
@@ -18,6 +18,7 @@ import { createHealth } from './health.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
import { createDrawSets } from './drawSets.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createCctvLayer({ services, source }) {
@@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) {
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.drawSets = createDrawSets(context);
parts.calibration = createCalibration(context);
parts.testing = createTesting(context);
parts.projection = createProjection(context);
+5 -1
View File
@@ -157,6 +157,9 @@ export function createLifecycle({
// Idempotent — also covers a re-init without a prior destroy().
parts.cards.teardownAmbientCards();
parts.projection.clearProjectionOverlay();
// An activation probe still to answer lands on none of these records.
for (const record of layerState._records || [])
if (record) record.probeToken = (record.probeToken || 0) + 1;
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
@@ -317,7 +320,7 @@ export function createLifecycle({
viewshedColors: viewshedColors(
cameraHue(hueIndexById.get(camera.id) ?? 0),
),
viewshedPrimitive: null,
viewshedVolume: null,
viewshedActiveTint: false,
};
layerState._records.push(record);
@@ -582,6 +585,7 @@ export function createLifecycle({
parts.cards.teardownAmbientCards();
parts.geometry.destroyCoverageEntities();
parts.rendering.destroyCameraIcons();
parts.drawSets.dispose();
clearRuntimeState();
layerState._viewer = null;
layerState._enabled = false;
-7
View File
@@ -1,7 +0,0 @@
import { createEntityStore } from '../../data/entityRecords.js';
/**
* The camera a picked coverage ray or projection plane belongs to: `cameraId`
* is the upstream camera id. Gizmo entities never get one.
*/
export const cctvPicks = createEntityStore();
+86 -72
View File
@@ -1,16 +1,30 @@
import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
PLANE_OUTLINE_COLOR as PLANE_OUTLINE_RGBA,
PLANE_OUTLINE_COLOR,
PROJECTION_CANVAS_WIDTH,
PROJECTION_CANVAS_HEIGHT,
} from './policy.js';
import { cctvPicks } from './pickState.js';
import { toColor } from '../../render/cesium/draw.js';
const PLANE_OUTLINE_COLOR = toColor(PLANE_OUTLINE_RGBA);
/** The monitor plane's alpha over its frame, as its image material had it. */
const PLANE_ALPHA = 0.95;
/** A plain white image, for a plane with no media (tests). */
const WHITE_IMAGE =
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">' +
'<rect width="1" height="1" fill="#fff"/></svg>',
);
/** Copy a position's coordinates into `out`. */
function copyPosition(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
export function createProjection({
state: layerState,
@@ -20,15 +34,9 @@ export function createProjection({
}) {
const { holdContinuousRender, releaseContinuousRender } = services.render;
/** The monitor plane's orientation, as the Cesium quaternion its entity takes. */
function planeOrientation(camera, capCenter) {
const q = parts.model.planeOrientationFor(camera, capCenter);
return new Cesium.Quaternion(q.x, q.y, q.z, q.w);
}
/**
* Build the protected label associated with one active monitor plane.
* @param {{cameraId: string, name: string, position: Cesium.Cartesian3|Function}} input
* @param {{cameraId: string, name: string, position: object|Function}} input
* @returns {Object} Shared-host presentation entry.
*/
@@ -56,7 +64,7 @@ export function createProjection({
}
/**
* Re-derives the monitor plane entity's placement (position, orientation,
* Re-derives the monitor plane's placement (position, orientation,
* dimensions) + label from the record's current frustum geometry, so the plane
* always caps the wireframe exactly (corner rays terminate on its corners).
* No-op when the record has no plane runtime (idle neighbors have no plane).
@@ -65,7 +73,8 @@ export function createProjection({
function updatePlanePlacement(record) {
const runtime = record?.projection;
if (!runtime?.planeEntity) return;
const plane = runtime?.plane;
if (!plane) return;
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -75,20 +84,32 @@ export function createProjection({
);
const positions =
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
runtime.planeEntity.position = positions.capCenter;
runtime.planeEntity.orientation = planeOrientation(
record.camera,
placePlane(plane, record.camera, geometry, positions);
if (runtime.labelPosition)
copyPosition(positions.label, runtime.labelPosition);
parts.drawSets.writePlane(plane);
}
/** Pose a plane handle on the frustum's far cap. */
function placePlane(plane, camera, geometry, positions) {
plane.center = positions.capCenter;
plane.orientation = parts.model.planeOrientationFor(
camera,
positions.capCenter,
);
if (runtime.planeEntity.plane) {
runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
);
}
if (runtime.labelPosition) {
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
}
plane.size = [geometry.halfW * 2, geometry.halfH * 2];
}
/**
* Give the monitor plane another image: a canvas, or the video element.
* @param {Object} runtime - Projection runtime.
* @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source
*/
function setPlaneSource(runtime, source) {
runtime.planeSource = source;
if (!runtime.plane) return;
runtime.plane.source = source;
parts.drawSets.writePlane(runtime.plane);
}
/**
@@ -112,7 +133,10 @@ export function createProjection({
function setPlaneVisible(runtime, visible) {
if (!runtime) return;
if (runtime.planeEntity) runtime.planeEntity.show = !!visible;
if (runtime.plane && runtime.plane.show !== !!visible) {
runtime.plane.show = !!visible;
parts.drawSets.writePlane(runtime.plane);
}
if (visible && runtime.overlayEntry && runtime.cameraId) {
if (layerState._projectionOverlayOwnerId !== runtime.cameraId) {
layerState._cctvOverlayHost.setEntries(
@@ -131,40 +155,34 @@ export function createProjection({
}
}
/** A plain white plane material, for a plane with no media (tests). */
function plainPlaneMaterial() {
return new Cesium.ColorMaterialProperty(Cesium.Color.WHITE);
/** A plain white plane image, for a plane with no media (tests). */
function plainPlaneSource() {
return { image: WHITE_IMAGE };
}
/** Create the native monitor plane plus its cached host-label presentation. */
/** Create the monitor plane plus its cached host-label presentation. */
function createProjectionPlane(record, runtime, geometry, positions) {
runtime.labelPosition ||= new Cesium.Cartesian3();
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
runtime.labelPosition ||= { x: 0, y: 0, z: 0 };
copyPosition(positions.label, runtime.labelPosition);
runtime.cameraId = String(record.camera.id);
runtime.overlayEntry = createCctvProjectionOverlayEntry({
cameraId: runtime.cameraId,
name: record.camera.name,
position: () => runtime.labelPosition,
});
runtime.planeEntity = layerState._viewer.entities.add({
const plane = {
id: `cctv-${record.camera.id}-plane`,
cameraId: record.camera.id,
source: runtime.planeSource || plainPlaneSource(),
alpha: PLANE_ALPHA,
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
show: false,
position: positions.capCenter,
orientation: planeOrientation(record.camera, positions.capCenter),
plane: {
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
dimensions: new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
),
material: runtime.planeMaterial,
outline: true,
outlineColor: PLANE_OUTLINE_COLOR,
},
});
cctvPicks.write(runtime.planeEntity).cameraId = record.camera.id;
return runtime.planeEntity;
};
placePlane(plane, record.camera, geometry, positions);
runtime.plane = plane;
parts.drawSets.writePlane(plane);
return plane;
}
/**
@@ -196,11 +214,11 @@ export function createProjection({
ctx,
image: null,
video: null,
planeEntity: null,
plane: null,
cameraId: String(record.camera.id),
labelPosition: new Cesium.Cartesian3(),
labelPosition: { x: 0, y: 0, z: 0 },
overlayEntry: null,
planeMaterial: null,
planeSource: { canvas },
buffers: null,
bufferIndex: 0,
lastTextureSwapAt: 0,
@@ -231,16 +249,17 @@ export function createProjection({
video.playsInline = true;
video.crossOrigin = 'anonymous';
video.preload = 'auto';
// Cesium sizes the video texture from the element's width/height
// attributes at first upload. Set them from the real stream dimensions
// and rebind on any resolution change (camera switch, adaptive source).
// The plane shows the video once it knows its size (the element's
// width/height follow the real stream dimensions); the renderer reads
// it at a new size on any later resolution change (camera switch,
// adaptive source).
const bindVideoTexture = () => {
if (runtime.video !== video || !runtime.planeMaterial) return;
if (runtime.video !== video || runtime.disposed) return;
if (!(video.videoWidth > 0 && video.videoHeight > 0)) return;
video.width = video.videoWidth;
video.height = video.videoHeight;
runtime.planeMaterial.image = runtime.canvas;
runtime.planeMaterial.image = video;
if (runtime.planeSource?.video !== video)
setPlaneSource(runtime, { video });
};
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
@@ -265,7 +284,7 @@ export function createProjection({
runtime.imageLoading = false;
runtime.imageReady = false;
};
runtime.planeMaterial.image = runtime.canvas;
setPlaneSource(runtime, { canvas: runtime.canvas });
parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners();
},
@@ -288,9 +307,8 @@ export function createProjection({
}
// Monitor plane = the frustum's far cap: video feeds bind the video element
// directly (Cesium updates video-backed entity materials per frame); image
// feeds start on the placeholder canvas and switch to double-buffer swaps
// at <=1Hz.
// directly (the renderer reads it every frame); image feeds start on the
// placeholder canvas and switch to double-buffer swaps at <=1Hz.
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -300,11 +318,6 @@ export function createProjection({
);
const positions =
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
image: canvas,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
createProjectionPlane(record, runtime, geometry, positions);
return runtime;
@@ -349,15 +362,15 @@ export function createProjection({
runtime.video.removeAttribute('src');
runtime.video.load();
}
if (runtime.planeEntity && layerState._viewer) {
layerState._viewer.entities.remove(runtime.planeEntity);
runtime.planeEntity = null;
if (runtime.plane) {
parts.drawSets.removePlane(runtime.plane);
runtime.plane = null;
}
if (layerState._projectionOverlayOwnerId === runtime.cameraId)
clearProjectionOverlay();
runtime.overlayEntry = null;
runtime.labelPosition = null;
runtime.planeMaterial = null;
runtime.planeSource = null;
}
function startProjectionLoop() {
@@ -439,7 +452,8 @@ export function createProjection({
updatePlanePlacement,
clearProjectionOverlay,
setPlaneVisible,
plainPlaneMaterial,
setPlaneSource,
plainPlaneSource,
createProjectionPlane,
createProjectionRuntime,
ensureProjectionRuntime,
+178 -218
View File
@@ -5,13 +5,13 @@ import {
CAMERA_ICON,
IDLE_CAMERA_COLOR as IDLE_CAMERA_RGBA,
LIVE_CAMERA_COLOR as LIVE_CAMERA_RGBA,
ACTIVE_COVERAGE_CENTER as ACTIVE_COVERAGE_CENTER_RGBA,
IDLE_COVERAGE_CENTER_MUTED as IDLE_COVERAGE_CENTER_MUTED_RGBA,
ACTIVE_COVERAGE_CENTER_DEPTHFAIL as ACTIVE_COVERAGE_CENTER_DEPTHFAIL_RGBA,
ACTIVE_COVERAGE_EDGE as ACTIVE_COVERAGE_EDGE_RGBA,
IDLE_COVERAGE_EDGE_MUTED as IDLE_COVERAGE_EDGE_MUTED_RGBA,
ACTIVE_COVERAGE_EDGE_DEPTHFAIL as ACTIVE_COVERAGE_EDGE_DEPTHFAIL_RGBA,
IDLE_COVERAGE_COLOR as IDLE_COVERAGE_RGBA,
ACTIVE_COVERAGE_CENTER,
IDLE_COVERAGE_CENTER_MUTED,
ACTIVE_COVERAGE_CENTER_DEPTHFAIL,
ACTIVE_COVERAGE_EDGE,
IDLE_COVERAGE_EDGE_MUTED,
ACTIVE_COVERAGE_EDGE_DEPTHFAIL,
IDLE_COVERAGE_COLOR,
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
@@ -20,11 +20,13 @@ import { createIconSet } from '../../data/iconSet.js';
import { writeHoldSegment } from '../../data/iconSegment.js';
import { IconSetPrimitive } from '../../render/cesium/iconSetPrimitive.js';
import { iconAtlas } from '../../data/iconAtlas.js';
import { cctvPicks } from './pickState.js';
import { horizonOccluder } from '../../render/cesium/iconOrientation.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
import { entityRecord } from '../../data/entityRecords.js';
import { toColor } from '../../render/cesium/draw.js';
import { drawHitOf } from '../../render/cesium/drawHit.js';
import { findQuery } from '../../render/rendererOf.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
// Loads the factory a viewer of a caller's own gets its camera port from,
// which the rest of the layer reads the eye through.
import '../../render/cesium/camera.js';
@@ -34,17 +36,9 @@ import '../../render/cesium/globe.js';
const ACTIVE_CAMERA_COLOR = toColor(ACTIVE_CAMERA_RGBA);
const IDLE_CAMERA_COLOR = toColor(IDLE_CAMERA_RGBA);
const LIVE_CAMERA_COLOR = toColor(LIVE_CAMERA_RGBA);
const ACTIVE_COVERAGE_CENTER = toColor(ACTIVE_COVERAGE_CENTER_RGBA);
const IDLE_COVERAGE_CENTER_MUTED = toColor(IDLE_COVERAGE_CENTER_MUTED_RGBA);
const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = toColor(
ACTIVE_COVERAGE_CENTER_DEPTHFAIL_RGBA,
);
const ACTIVE_COVERAGE_EDGE = toColor(ACTIVE_COVERAGE_EDGE_RGBA);
const IDLE_COVERAGE_EDGE_MUTED = toColor(IDLE_COVERAGE_EDGE_MUTED_RGBA);
const IDLE_COVERAGE_COLOR = toColor(IDLE_COVERAGE_RGBA);
const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = toColor(
ACTIVE_COVERAGE_EDGE_DEPTHFAIL_RGBA,
);
/** An RGBA colour with another alpha. */
const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha];
/** The camera icon's drawn size (px). */
const CAMERA_ICON_PX = 24;
@@ -61,67 +55,37 @@ const CAMERA_SCALE_BY_DISTANCE = new Cesium.NearFarScalar(
);
/**
* Builds the translucent frustum-volume primitive for one camera.
* Synchronous (6 triangles — cheaper than the async geometry pipeline's
* bookkeeping), unlit flat color, both faces visible (the viewer is routinely
* inside or behind a cone), never pickable (clicks fall through to the
* billboard/wireframe/plane, whose pick semantics are established).
* @param {Object} positions - frustumCartesians shape (see frustumVolumeGeometryData).
* @param {Cesium.Color} color - Per-camera fill color (already alpha'd).
* @returns {Cesium.Primitive}
* The translucent frustum volume of one camera, as a mesh item: the same 5
* points the wireframe draws (frustumVolumeGeometryData), in the
* east-north-up frame at the mount. Unlit flat colour, both faces visible
* (the viewer is routinely inside or behind a cone); its set is never
* pickable (clicks fall through to the icon/wireframe/plane, whose pick
* semantics are established).
* @param {string} id - Item id.
* @param {Object} positions - frustumCartesians shape.
* @param {number[]} color - Per-camera fill colour (already alpha'd).
*/
function createFrustumVolumePrimitive(positions, color) {
function frustumVolumeItem(id, positions, color) {
const { positions: flat, indices } = frustumVolumeGeometryData(positions);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values: flat,
}),
},
indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(flat)),
});
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: true,
renderState: {
cull: { enabled: false },
},
}),
asynchronous: false,
allowPicking: false,
});
}
/**
* A record's viewshed colours as Cesium colours, made once per palette
* object: a record gets a new palette rather than having one changed in place.
*/
const viewshedCesium = new WeakMap();
function viewshedCesiumColors(record) {
const colors = record.viewshedColors;
if (!colors) return null;
let cesium = viewshedCesium.get(colors);
if (!cesium) {
cesium = {
fill: toColor(colors.fill),
fillActive: toColor(colors.fillActive),
line: toColor(colors.line),
lineActive: toColor(colors.lineActive),
};
viewshedCesium.set(colors, cesium);
const origin = positions.mount;
const frame = eastNorthUp(origin);
const local = new Float32Array(flat.length);
for (let i = 0; i < flat.length; i += 3) {
const dx = flat[i] - origin.x;
const dy = flat[i + 1] - origin.y;
const dz = flat[i + 2] - origin.z;
local[i] = dx * frame.x.x + dy * frame.x.y + dz * frame.x.z;
local[i + 1] = dx * frame.y.x + dy * frame.y.y + dz * frame.y.z;
local[i + 2] = dx * frame.z.x + dy * frame.z.y + dz * frame.z.z;
}
return cesium;
return {
id,
origin: { x: origin.x, y: origin.y, z: origin.z },
positions: local,
indices,
color,
flat: true,
};
}
/** FNV-1a over a camera id: a stable, well-spread order for crowded cells. */
@@ -522,12 +486,18 @@ export function createRendering({
for (const record of Array.isArray(records) ? records : []) {
if (record) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
if (record.camera?.id === activeCameraId) record.activationDone = false;
}
for (const entity of record?.coverageEntities || []) entity.show = false;
if (record?.viewshedPrimitive) destroyVolume?.(record);
if (record?.projection?.planeEntity)
record.projection.planeEntity.show = false;
parts.drawSets.writeLines(record?.coverageEntities);
if (record?.viewshedVolume) destroyVolume?.(record);
const plane = record?.projection?.plane;
if (plane?.show) {
plane.show = false;
parts.drawSets.writePlane(plane);
}
}
}
@@ -594,10 +564,6 @@ export function createRendering({
// rather than rendering identically to a surveyed one (#639). Colors,
// widths, and the active/idle emphasis are unchanged.
const bearingEstimated = isHeadingEstimated(record.camera);
const lineMaterial = (color) =>
bearingEstimated
? new Cesium.PolylineDashMaterialProperty({ color })
: color;
for (const entity of record.coverageEntities || []) {
// The frustum wireframe is part of the projection representation —
// force it on for the active camera and let it read through geometry
@@ -606,45 +572,43 @@ export function createRendering({
layerState._enabled &&
((coverageOn && inVisibleSet) || planeShowing)
);
if (!entity.polyline) continue;
if (!entity.role) continue;
// Viewshed mode swaps the cyan/green scheme for the camera's own hue so
// adjacent cones read as distinct coverage claims (design §3b); the
// active camera keeps its width/alpha emphasis in both schemes.
const hue = viewshedOn ? viewshedCesiumColors(record) : null;
if (entity._coverageRole === 'cap') {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED,
);
entity.polyline.width = isActive ? 2.2 : 1.0;
entity.polyline.depthFailMaterial = planeShowing
const hue = viewshedOn ? record.viewshedColors || null : null;
entity.dashed = bearingEstimated;
if (entity.role === 'cap') {
entity.color = hue
? isActive
? hue.lineActive
: hue.line
: isActive
? ACTIVE_COVERAGE_CENTER
: IDLE_COVERAGE_CENTER_MUTED;
entity.widthPx = isActive ? 2.2 : 1.0;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.26)
? withAlpha(hue.line, 0.26)
: ACTIVE_COVERAGE_CENTER_DEPTHFAIL
: undefined;
: null;
} else {
entity.polyline.material = lineMaterial(
hue
? isActive
? hue.lineActive
: hue.line.withAlpha(0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED,
);
entity.polyline.width = isActive ? 1.8 : 0.9;
entity.polyline.depthFailMaterial = planeShowing
entity.color = hue
? isActive
? hue.lineActive
: withAlpha(hue.line, 0.6)
: isActive
? ACTIVE_COVERAGE_EDGE
: IDLE_COVERAGE_EDGE_MUTED;
entity.widthPx = isActive ? 1.8 : 0.9;
entity.depthFailColor = planeShowing
? hue
? hue.line.withAlpha(0.18)
? withAlpha(hue.line, 0.18)
: ACTIVE_COVERAGE_EDGE_DEPTHFAIL
: undefined;
: null;
}
}
parts.drawSets.writeLines(record.coverageEntities);
// Viewshed volume lifecycle: exists iff enabled + viewshed mode + in the
// visible set. Rebuild on active-tint flips (rare); otherwise leave the
@@ -656,13 +620,10 @@ export function createRendering({
record.frustumPositions
);
if (wantVolume) {
if (
!record.viewshedPrimitive ||
record.viewshedActiveTint !== isActive
) {
if (!record.viewshedVolume || record.viewshedActiveTint !== isActive) {
rebuildViewshedVolume(record, isActive);
}
} else if (record.viewshedPrimitive) {
} else if (record.viewshedVolume) {
destroyViewshedVolume(record);
}
@@ -716,17 +677,16 @@ export function createRendering({
}
/**
* Converts a computeFrustumGeometry result into the Cartesian3 positions the
* entities consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and entities must never share scratch objects).
* Converts a computeFrustumGeometry result into the ECEF positions the
* drawn items consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and items must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: Cesium.Cartesian3, capCenter: Cesium.Cartesian3,
* tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, br: Cesium.Cartesian3,
* bl: Cesium.Cartesian3, label: Cesium.Cartesian3 }}
* @returns {{ mount: object, capCenter: object, tl: object, tr: object,
* br: object, bl: object, label: object }} ECEF points with x, y and z.
*/
function frustumCartesians(geometry) {
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt);
const at = (p) => fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
@@ -734,7 +694,7 @@ export function createRendering({
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: Cesium.Cartesian3.fromDegrees(
label: fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
@@ -743,12 +703,13 @@ export function createRendering({
}
/**
* Creates the five Cesium polyline entities that visualize a camera's pitched
* frustum: 4 corner rays (mount → far-plane corner) + the closed far-plane
* rectangle. Entity ids stay in the `cctv-<id>-<role>` scheme (pick-owner
* regex depends on it): roles ray-tl / ray-tr / ray-br / ray-bl / cap.
* Creates the five lines that visualize a camera's pitched frustum: 4
* corner rays (mount → far-plane corner) + the closed far-plane rectangle,
* as line handles the layer restyles and then writes to its coverage set.
* Item ids stay in the `cctv-<id>-<role>` scheme (pick-owner regex depends
* on it): ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Cesium.Entity[]} Array of five coverage entities.
* @returns {Object[]} Array of five coverage line handles.
*/
function buildCoverageEntities(record) {
@@ -771,76 +732,74 @@ export function createRendering({
moveCameraIcon(record);
}
const addPolyline = (role, linePositions) => {
const entity = layerState._viewer.entities.add({
id: `cctv-${camera.id}-${role}`,
polyline: {
positions: linePositions,
width: 1.2,
material: IDLE_COVERAGE_COLOR,
},
});
cctvPicks.write(entity).cameraId = camera.id;
return entity;
};
const line = (name, role) => ({
id: `cctv-${camera.id}-${name}`,
cameraId: camera.id,
role,
positions: null,
widthPx: 1.2,
color: IDLE_COVERAGE_COLOR,
dashed: false,
depthFailColor: null,
show: true,
});
const entities = [
addPolyline('ray-tl', [positions.mount, positions.tl]),
addPolyline('ray-tr', [positions.mount, positions.tr]),
addPolyline('ray-br', [positions.mount, positions.br]),
addPolyline('ray-bl', [positions.mount, positions.bl]),
addPolyline('cap', [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
]),
line('ray-tl', 'edge'),
line('ray-tr', 'edge'),
line('ray-br', 'edge'),
line('ray-bl', 'edge'),
line('cap', 'cap'),
];
entities[0]._coverageRole = 'edge';
entities[1]._coverageRole = 'edge';
entities[2]._coverageRole = 'edge';
entities[3]._coverageRole = 'edge';
entities[4]._coverageRole = 'cap';
placeCoverageLines(entities, positions);
parts.drawSets.writeLines(entities);
return entities;
}
/**
* The activation obstruction probe's one ray pick against the scene: the
* first thing along the ray from `origin`, seeing through `exclude` (the
* layer's own entities).
* Put a camera's five coverage line handles on its frustum positions (not
* written: the caller writes them).
* @param {Object[]} entities - The record's coverage handles.
* @param {Object} positions - frustumCartesians shape.
*/
function placeCoverageLines(entities, positions) {
if (!(entities?.length >= 5)) return;
entities[0].positions = [positions.mount, positions.tl];
entities[1].positions = [positions.mount, positions.tr];
entities[2].positions = [positions.mount, positions.br];
entities[3].positions = [positions.mount, positions.bl];
entities[4].positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
}
/**
* The activation obstruction probe's one ray cast against the scene: the
* first surface along the ray from `origin`. The layer's own lines, plane
* and volumes are not ground, so the cast sees through them.
* @param {{x: number, y: number, z: number}} origin - ECEF ray origin.
* @param {{x: number, y: number, z: number}} direction - Unit ECEF direction.
* @returns {{position?: object}|undefined} Undefined as well when the
* scene cannot pick along a ray.
* @returns {Promise<{x: number, y: number, z: number}|null>} Null as well
* when the scene cannot cast rays.
*/
function obstructionHit(origin, direction) {
const scene = layerState._viewer?.scene;
if (!scene || typeof scene.pickFromRay !== 'function') return undefined;
// Exclude everything the layer itself draws so the probe can only hit the
// world (3D tiles), not our own polylines/planes. Icons never draw into
// ray picks.
const exclude = [...layerState._coverageEntities];
for (const runtime of layerState._projectionEntities) {
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
}
return scene.pickFromRay(new Cesium.Ray(origin, direction), exclude);
async function obstructionHit(origin, direction) {
const query = findQuery(layerState._viewer);
if (!query) return null;
return query.rayCast({ origin, direction }, { against: 'surface' });
}
/** Whether the scene can pick along a ray (the activation probe needs it). */
/** Whether there is a query port to cast the activation probe through. */
function canPickFromRay() {
return typeof layerState._viewer?.scene?.pickFromRay === 'function';
return typeof findQuery(layerState._viewer)?.rayCast === 'function';
}
/** Removes the layer's coverage entities from the scene. */
/** Removes the layer's coverage lines from the scene. */
function removeCoverageEntities() {
const viewer = layerState._viewer;
if (!viewer) return;
for (const entity of layerState._coverageEntities) {
viewer.entities.remove(entity);
}
parts.drawSets.clearLines();
}
/**
@@ -853,25 +812,24 @@ export function createRendering({
function extractPickedCameraId(picked) {
if (!picked) return null;
const entity = cctvPicks.read(picked.id)
? picked.id
: cctvPicks.read(picked.primitive?.id)
? picked.primitive.id
: null;
const value = cctvPicks.read(entity)?.cameraId;
if (value !== undefined) {
// A coverage line or monitor plane: an item of the layer's own sets
// that its record still draws.
const hit = drawHitOf(picked);
const role = hit ? parts.drawSets.roleOfSet(hit.set) : null;
if (role) {
const value = hit.meta?.cameraId;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
const ownsCoverageEntity = Boolean(
record?.coverageEntities?.includes(entity),
);
const ownsProjectionEntity =
record?.projection?.planeEntity === entity ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.planeEntity === entity,
);
if (record && (ownsCoverageEntity || ownsProjectionEntity)) return value;
if (!record) return null;
const owns =
role === 'coverage'
? Boolean(record.coverageEntities?.some((h) => h?.id === hit.id))
: record.projection?.plane?.id === hit.id ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.plane?.id === hit.id,
);
return owns ? value : null;
}
// Camera icon row IDs are intentionally the upstream camera ID, so a
@@ -934,10 +892,9 @@ export function createRendering({
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedPrimitive && layerState._viewer) {
layerState._viewer.scene.primitives.remove(record.viewshedPrimitive);
}
record.viewshedPrimitive = null;
if (record.viewshedVolume)
parts.drawSets.removeVolume(record.viewshedVolume);
record.viewshedVolume = null;
}
/**
@@ -952,23 +909,25 @@ export function createRendering({
*/
function rebuildViewshedVolume(record, isActive) {
destroyViewshedVolume(record);
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
)
) {
destroyViewshedVolume(record);
return;
const colors = viewshedCesiumColors(record);
const color = isActive ? colors.fillActive : colors.fill;
const primitive = createFrustumVolumePrimitive(
record.frustumPositions,
color,
}
const colors = record.viewshedColors;
const id = `cctv-${record.camera.id}-viewshed`;
// Replaced where it is: the volume draws in the frame its old one did.
parts.drawSets.writeVolume(
frustumVolumeItem(
id,
record.frustumPositions,
isActive ? colors.fillActive : colors.fill,
),
);
// QA tag: the harness counts viewshed volumes by this record field.
entityRecord(primitive).viewshedCameraId = record.camera.id;
record.viewshedPrimitive =
layerState._viewer.scene.primitives.add(primitive);
record.viewshedVolume = id;
record.viewshedActiveTint = !!isActive;
}
@@ -976,6 +935,7 @@ export function createRendering({
projectionTilesReady,
frustumCartesians,
buildCoverageEntities,
placeCoverageLines,
obstructionHit,
canPickFromRay,
removeCoverageEntities,
+30 -24
View File
@@ -14,6 +14,7 @@ import {
import { isVideoFeedType } from '../../sources/cctvTypes.js';
import * as Cesium from 'cesium';
import { createIconSet } from '../../data/iconSet.js';
import { bindRenderer } from '../../render/rendererOf.js';
const FOCUS_FACTOR = 0.5;
@@ -112,40 +113,45 @@ test('icons leave the scene they were added to, whichever viewer tears down', ()
assert.equal(state._icons, null);
});
test('the obstruction probe sees through the layer and needs a ray pick', () => {
const coverage = [{ id: 'cov' }];
const plane = { id: 'plane' };
test('the obstruction probe casts one ray through the query port', async () => {
const calls = [];
const state = {
_viewer: {
scene: {
pickFromRay(ray, exclude) {
calls.push({ ray, exclude });
return { position: { x: 1, y: 2, z: 3 } };
},
const viewer = {};
const unbind = bindRenderer(viewer, {
query: {
rayCast: async (ray, options) => {
calls.push({ ray, options });
return { x: 1, y: 2, z: 3 };
},
},
_coverageEntities: coverage,
_projectionEntities: [{ planeEntity: plane }, null, {}],
};
});
const state = { _viewer: viewer };
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
assert.equal(rendering.canPickFromRay(), true);
const hit = rendering.obstructionHit(
{ x: 0, y: 0, z: 0 },
{ x: 1, y: 0, z: 0 },
);
assert.deepEqual(hit.position, { x: 1, y: 2, z: 3 });
assert.deepEqual(calls[0].exclude, [...coverage, plane]);
assert.ok(calls[0].ray instanceof Cesium.Ray);
state._viewer = { scene: {} };
try {
assert.equal(rendering.canPickFromRay(), true);
const origin = { x: 0, y: 0, z: 0 };
const direction = { x: 1, y: 0, z: 0 };
assert.deepEqual(await rendering.obstructionHit(origin, direction), {
x: 1,
y: 2,
z: 3,
});
// The layer's own sets are not ground: the cast sees through them
// without naming them.
assert.deepEqual(calls, [
{ ray: { origin, direction }, options: { against: 'surface' } },
]);
} finally {
unbind();
}
state._viewer = {};
assert.equal(rendering.canPickFromRay(), false);
assert.equal(
rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
undefined,
await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
null,
);
});
+7 -6
View File
@@ -103,12 +103,13 @@ export function createSelection({
layerState._geoQueue.splice(queueIdx, 1);
layerState._geoQueue.unshift(record);
}
// §9.1: one obstruction probe per activation, BEFORE the geometry pass so
// the range clamp lands in the same rewrite. A FIRST-EVER activation (no
// real ground sample yet) probes from the catalog-prior altitude — if that
// prior is off, the clamp is measured from a shifted origin, but a
// re-activation after the one-shot snap lands re-probes from real ground,
// so it self-corrects.
// §9.1: one obstruction probe per activation, cast before the geometry
// pass; its range clamp lands a microtask later, before the next frame,
// rewriting the geometry and asking again for the footprint ground. A
// FIRST-EVER activation (no real ground sample yet) probes from the
// catalog-prior altitude — if that prior is off, the clamp is measured
// from a shifted origin, but a re-activation after the one-shot snap
// lands re-probes from real ground, so it self-corrects.
parts.geometry.runActivationObstructionProbe(record);
// Coverage is activation-lazy even while the mode is OFF: the active
// camera's projection representation must be ready without materializing
+24 -5
View File
@@ -19,7 +19,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
/**
* Create the production monitor-plane/host-label pair without media setup.
* @param {Object} viewer Cesium viewer seam.
* @param {Object} viewer Viewer whose renderer draws the plane.
* @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime.
*/
@@ -39,11 +39,11 @@ export function createTesting({ state: layerState, services, parts, source }) {
record.frustumPositions = positions;
const runtime = {
cameraId: String(record.camera.id),
planeEntity: null,
plane: null,
// createProjectionPlane gives it its label position.
labelPosition: null,
overlayEntry: null,
planeMaterial: parts.projection.plainPlaneMaterial(),
planeSource: parts.projection.plainPlaneSource(),
};
parts.projection.createProjectionPlane(
record,
@@ -122,10 +122,29 @@ export function createTesting({ state: layerState, services, parts, source }) {
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
/** What the layer draws now, for the QA harness: the gizmo's parts. */
/**
* What the layer draws now, for the QA harness: the gizmo's parts, the
* coverage lines and monitor planes by item id, the viewshed volumes'
* ids, and how many volumes were ever written.
*/
function _cctvDrawnForTest() {
return { gizmo: layerState._gizmo?.partsForTest() ?? {} };
const coverage = {};
for (const record of layerState._records)
for (const line of record.coverageEntities || [])
if (line?.id) coverage[line.id] = line;
const planes = {};
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
viewsheds: layerState._records
.map((record) => record.viewshedVolume)
.filter(Boolean),
viewshedWrites: parts.drawSets.volumeWritesForTest(),
};
}
/** The layer's icon set, for tests that read what the rows draw. */