mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-20 18:22:25 +00:00
Merge main and resolve the CCTV batch conflicts
Main released #1228 and #1233 and deleted their changelog fragments, so they stay deleted here. Main also rewrote the tracking arrival probe in scripts/track-regression.mjs, which supersedes this branch's version; main's file is kept unchanged.
This commit is contained in:
commit
d7db1090fd
4343 files changed
+644447
-86370
No files matched your search
@@ -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) {
|
||||
|
||||
+39
-34
@@ -1,3 +1,4 @@
|
||||
import { findFrame } from '../../render/rendererOf.js';
|
||||
import {
|
||||
createFrameSlot,
|
||||
CCTV_OVERLAY_SOURCE_ID,
|
||||
@@ -8,8 +9,6 @@ import {
|
||||
CCTV_FRAME_CANVAS_H,
|
||||
applyFrameResult,
|
||||
} from '../../data/cctvCards.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { horizonOccluder } from '../../data/iconOrientation.js';
|
||||
import { selectCctvLod, applyEvictionGrace } from '../../data/cctvLod.js';
|
||||
import {
|
||||
CCTV_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -35,7 +34,7 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
} = {}) {
|
||||
layerState._activeCameraCardEnabled = activeCameraCardEnabled === true;
|
||||
if (layerState._enabled) pushAmbientCardEntries();
|
||||
layerState._viewer?.scene?.requestRender?.();
|
||||
findFrame(layerState._viewer)?.requestRender('cctv-cards');
|
||||
|
||||
return { activeCameraCardEnabled: layerState._activeCameraCardEnabled };
|
||||
}
|
||||
@@ -83,44 +82,42 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
);
|
||||
return;
|
||||
}
|
||||
const scene = layerState._viewer.scene;
|
||||
const carto = layerState._viewer.camera.positionCartographic;
|
||||
const viewerLat = carto ? Cesium.Math.toDegrees(carto.latitude) : 0;
|
||||
const viewerLon = carto ? Cesium.Math.toDegrees(carto.longitude) : 0;
|
||||
// An eye with no geographic position (the earth's centre) measures from 0, 0.
|
||||
const pose = parts.model.eyePose();
|
||||
const viewerLat = pose ? pose.lat : 0;
|
||||
const viewerLon = pose ? pose.lon : 0;
|
||||
// The active camera is excluded from ambient selection ALWAYS (not just
|
||||
// after its async activation settles). It is published separately in the
|
||||
// protected lane below, and grace never applies to it.
|
||||
const activeId = layerState._activeCameraId;
|
||||
const occluder = horizonOccluder(layerState._viewer.camera);
|
||||
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
|
||||
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
|
||||
const view = parts.rendering.cardView();
|
||||
const { width, height } = view;
|
||||
const marginX = width * CARD_VIEW_MARGIN;
|
||||
const marginY = height * CARD_VIEW_MARGIN;
|
||||
|
||||
const candidates = [];
|
||||
const screenById = new Map();
|
||||
for (const record of layerState._records) {
|
||||
// Cards go only on the icons the view pass shows (refreshHorizonCulling).
|
||||
for (const record of layerState._viewRecords) {
|
||||
const id = record.camera.id;
|
||||
if (id === activeId || !record.position) continue;
|
||||
let inView = false;
|
||||
let sx = NaN;
|
||||
let sy = NaN;
|
||||
if (occluder.isPointVisible(record.position)) {
|
||||
const screen = scene.cartesianToCanvasCoordinates(record.position);
|
||||
if (
|
||||
screen &&
|
||||
Number.isFinite(screen.x) &&
|
||||
Number.isFinite(screen.y) &&
|
||||
screen.x >= -marginX &&
|
||||
screen.x <= width + marginX &&
|
||||
screen.y >= -marginY &&
|
||||
screen.y <= height + marginY
|
||||
) {
|
||||
inView = true;
|
||||
sx = screen.x;
|
||||
sy = screen.y;
|
||||
screenById.set(id, { sx, sy });
|
||||
}
|
||||
const screen = view.screenOf(record.position);
|
||||
if (
|
||||
screen &&
|
||||
Number.isFinite(screen.x) &&
|
||||
Number.isFinite(screen.y) &&
|
||||
screen.x >= -marginX &&
|
||||
screen.x <= width + marginX &&
|
||||
screen.y >= -marginY &&
|
||||
screen.y <= height + marginY
|
||||
) {
|
||||
inView = true;
|
||||
sx = screen.x;
|
||||
sy = screen.y;
|
||||
screenById.set(id, { sx, sy });
|
||||
}
|
||||
candidates.push({
|
||||
id,
|
||||
@@ -131,9 +128,11 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
record.camera.lon,
|
||||
),
|
||||
inView,
|
||||
isVideo: parts.model.isVideoFeedType(
|
||||
parts.model.normalizeFeedType(record.camera.feedType),
|
||||
),
|
||||
// Québec's browser-only sources have no registered frame endpoint;
|
||||
// keep them out of still-card fill just like video feeds.
|
||||
isVideo:
|
||||
parts.model.isVideoFeedCamera(record.camera) ||
|
||||
parts.model.isBrowserOverlayCamera(record.camera),
|
||||
sx,
|
||||
sy,
|
||||
});
|
||||
@@ -145,7 +144,7 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
// the budget fill through the screen-distribution grid, so periphery
|
||||
// cells hold cards instead of everything clustering at screen center.
|
||||
const { cardIds, budgets } = selectCctvLod(candidates, {
|
||||
cameraHeightM: carto?.height,
|
||||
cameraHeightM: pose?.height,
|
||||
incumbentIds: layerState._cardIds,
|
||||
viewW: width,
|
||||
viewH: height,
|
||||
@@ -187,7 +186,14 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
nowMs: Date.now(),
|
||||
cardLimit: budgets.cardLimit,
|
||||
});
|
||||
layerState._cardIds = new Set(retention.keepIds);
|
||||
// Grace keeps a card briefly after it loses selection, but never on a
|
||||
// camera whose icon the view pass has hidden.
|
||||
const shownIds = new Set(
|
||||
layerState._viewRecords.map((record) => record.camera.id),
|
||||
);
|
||||
layerState._cardIds = new Set(
|
||||
retention.keepIds.filter((id) => shownIds.has(id)),
|
||||
);
|
||||
layerState._cardGraceState = retention.graceState;
|
||||
|
||||
// Bounded thumbnail LRU: live cards (grace included) never lose their
|
||||
@@ -325,7 +331,7 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
slot,
|
||||
applyFrameResult(slot, { ok: !!frame, frame }, Date.now()),
|
||||
);
|
||||
layerState._viewer?.scene?.requestRender?.();
|
||||
findFrame(layerState._viewer)?.requestRender('cctv-card-frame');
|
||||
};
|
||||
image.onload = () => settle(true);
|
||||
image.onerror = () => settle(false);
|
||||
@@ -371,7 +377,6 @@ export function createCards({ state: layerState, services, parts, source }) {
|
||||
layerState._cctvOverlayHost.clearSource(CCTV_OVERLAY_SOURCE_ID);
|
||||
layerState._cctvOverlayHost.setVisible(CCTV_OVERLAY_SOURCE_ID, false);
|
||||
parts.hover.clearHoverCard();
|
||||
layerState._cameraMoving = false;
|
||||
layerState._cardIds = new Set();
|
||||
layerState._cardGraceState = new Map();
|
||||
layerState._cardFrameSlots = new Map();
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { CAMERA_SEEDS, SOURCE_ENDPOINT } from './policy.js';
|
||||
import { CAMERA_SEEDS } from './policy.js';
|
||||
import {
|
||||
lookupModelSpec,
|
||||
horizontalFovRangeDeg,
|
||||
@@ -237,9 +237,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
|
||||
groundElevationM,
|
||||
absoluteHeightM: groundElevationM + mountHeightM,
|
||||
pitchDeg,
|
||||
frameRefreshMs: parts.model.safeNumber(source.frameRefreshMs, NaN),
|
||||
license: String(source.license || source.licenseNote || ''),
|
||||
credit: String(source.credit || ''),
|
||||
code: String(source.code || ''),
|
||||
sourceUrl: String(source.sourceUrl || ''),
|
||||
browserMediaUrl: String(source.browserMediaUrl || ''),
|
||||
accuracyM: parts.model.safeNumber(source.accuracyM, NaN),
|
||||
positionSource: String(source.positionSource || ''),
|
||||
// Shipped precompute (see server/providers/cctv/groundHeights.js).
|
||||
groundHeights:
|
||||
source.groundHeights && typeof source.groundHeights === 'object'
|
||||
|
||||
Vendored
+28
-10
@@ -202,25 +202,24 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
* @param {Object} [options={}]
|
||||
* @param {number} [options.maxCount] - Maximum number of objects to return.
|
||||
* @param {number} [options.seed] - Offset seed for deterministic stride sampling.
|
||||
* @returns {{ position: Cesium.Cartesian3, id: string, type: string }[]}
|
||||
* @returns {{ position: {x: number, y: number, z: number}, id: string, type: string }[]}
|
||||
*/
|
||||
getDetectableObjects(options = {}) {
|
||||
if (!layerState._enabled || layerState._records.length === 0) return [];
|
||||
// The cameras the view pass shows, not icons it has hidden.
|
||||
const records = layerState._viewRecords;
|
||||
if (!layerState._enabled || records.length === 0) return [];
|
||||
const maxCount = Number.isFinite(options.maxCount)
|
||||
? Math.max(1, Math.floor(options.maxCount))
|
||||
: layerState._records.length;
|
||||
: records.length;
|
||||
const seed = Number.isFinite(options.seed) ? Math.floor(options.seed) : 0;
|
||||
const stride = Math.max(
|
||||
1,
|
||||
Math.ceil(layerState._records.length / maxCount),
|
||||
);
|
||||
const stride = Math.max(1, Math.ceil(records.length / maxCount));
|
||||
const start = seed % stride;
|
||||
|
||||
const objects = [];
|
||||
for (let i = start; i < layerState._records.length; i += stride) {
|
||||
const camera = layerState._records[i].camera;
|
||||
for (let i = start; i < records.length; i += stride) {
|
||||
const camera = records[i].camera;
|
||||
objects.push({
|
||||
position: layerState._records[i].position,
|
||||
position: records[i].position,
|
||||
sourceId: camera.id,
|
||||
// Short semantic code where the id is opaque (see cameraDisplayCode).
|
||||
id: `CAM-${camera.code || camera.id}`,
|
||||
@@ -336,6 +335,25 @@ export function createControls({ state: layerState, services, parts, source }) {
|
||||
return nextId;
|
||||
},
|
||||
|
||||
/**
|
||||
* Selects the camera nearest a WGS84 point and optionally flies to it.
|
||||
* @param {number} lat Latitude in degrees.
|
||||
* @param {number} lon Longitude in degrees.
|
||||
* @param {Object} [options={}]
|
||||
* @param {boolean} [options.focus=true] Whether to fly after selection.
|
||||
* @param {number} [options.durationSec] Fly-to duration in seconds.
|
||||
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
|
||||
*/
|
||||
focusNearestToPoint(lat, lon, options = {}) {
|
||||
const nearest = parts.navigation.nearestCameraIdToPoint(lat, lon);
|
||||
if (!nearest) return null;
|
||||
parts.selection.setActiveCamera(nearest);
|
||||
if (options.focus !== false) {
|
||||
parts.navigation.focusCamera(nearest, options.durationSec || 1.8);
|
||||
}
|
||||
return nearest;
|
||||
},
|
||||
|
||||
/**
|
||||
* Selects and flies to the camera nearest the current viewer position.
|
||||
* @param {Object} [options={}]
|
||||
|
||||
@@ -0,0 +1,195 @@
|
||||
/**
|
||||
* @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.
|
||||
*
|
||||
* Meshes and quads are capabilities: on a renderer without them there are
|
||||
* no viewshed volumes or monitor plane, and the lines still draw.
|
||||
*/
|
||||
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 },
|
||||
depthFail: handle.depthFailColor
|
||||
? { kind: 'solid', color: 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.depthFail ? item.depthFail.color.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 }) ?? null,
|
||||
plane: draw.quads?.({ id: `cctv:${n}:plane` }) ?? null,
|
||||
// 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();
|
||||
if (!s) return [];
|
||||
return s.plane ? [s.coverage.id, s.plane.id] : [s.coverage.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?.viewshed) 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,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,135 @@
|
||||
// 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 },
|
||||
depthFail: 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.depthFail, { kind: 'solid', color: [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();
|
||||
}
|
||||
});
|
||||
|
||||
test('a renderer without meshes or quads still draws the lines', () => {
|
||||
const viewer = {};
|
||||
const { draw, unbind } = bindFakeDraw(viewer);
|
||||
delete draw.meshes;
|
||||
delete draw.quads;
|
||||
const drawSets = createDrawSets({ state: { _viewer: viewer } });
|
||||
try {
|
||||
drawSets.writeLines([line('cctv-cam-ray-tl')]);
|
||||
const coverage = draw.find('cctv:');
|
||||
assert.equal(coverage.items.size, 1);
|
||||
// No viewshed volumes and no monitor plane: their writes do nothing.
|
||||
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
|
||||
drawSets.removeVolume('cctv-cam-viewshed');
|
||||
const plane = { id: 'cctv-cam-plane', cameraId: 'cam', show: true };
|
||||
drawSets.writePlane(plane);
|
||||
drawSets.removePlane(plane);
|
||||
assert.equal(drawSets.volumeWritesForTest(), 0);
|
||||
assert.deepEqual(drawSets.pickableSetIds(), [coverage.spec.id]);
|
||||
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
|
||||
drawSets.dispose();
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
+19
-13
@@ -5,9 +5,6 @@ import {
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
PROJECTION_MATTE_COLOR,
|
||||
PROJECTION_TEXTURE_SWAP_MS,
|
||||
ACTIVE_FRAME_REFRESH_MS,
|
||||
FRAME_ENDPOINT,
|
||||
MEDIA_ENDPOINT,
|
||||
PROJECTION_ACTIVE_REFRESH_MS,
|
||||
PROJECTION_IDLE_REFRESH_MS,
|
||||
PLACEHOLDER_REPAINT_MS,
|
||||
@@ -109,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`.
|
||||
@@ -142,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.
|
||||
@@ -159,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.
|
||||
@@ -173,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 });
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -258,11 +255,20 @@ export function createFrames({ state: layerState, services, parts, source }) {
|
||||
// clears this latch so the next normal tick can refresh.
|
||||
if (runtime.imageLoading) return;
|
||||
const now = Date.now();
|
||||
const refreshMs =
|
||||
const defaultRefreshMs =
|
||||
record.camera.id === layerState._activeCameraId
|
||||
? PROJECTION_ACTIVE_REFRESH_MS
|
||||
: PROJECTION_IDLE_REFRESH_MS;
|
||||
if (!force && now - runtime.lastImageRefreshAt < refreshMs) return;
|
||||
const sourceRefreshMs = parts.model.safeNumber(
|
||||
record.camera.frameRefreshMs,
|
||||
0,
|
||||
);
|
||||
const refreshMs = Math.max(defaultRefreshMs, sourceRefreshMs);
|
||||
const sinceLastRefresh = now - runtime.lastImageRefreshAt;
|
||||
// Forced activation may skip the normal active interval, but it cannot
|
||||
// bypass a provider's explicit minimum between image requests.
|
||||
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
|
||||
if (!force && sinceLastRefresh < refreshMs) return;
|
||||
runtime.lastImageRefreshAt = now;
|
||||
|
||||
const frameUrl = frameUrlFor(record.camera, refreshMs);
|
||||
@@ -349,7 +355,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(
|
||||
|
||||
+127
-223
@@ -1,13 +1,12 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createFrustumVolumePrimitive } from '../../data/cctvViewshed.js';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { eastNorthUp, frameVector } from '../../geo/frames.js';
|
||||
import { distance, vec } from '../../geo/vector.js';
|
||||
import {
|
||||
PROJECTION_VERT_ASPECT,
|
||||
FRUSTUM_GROUND_CLEARANCE_M,
|
||||
PROBE_MIN_RANGE_M,
|
||||
PROBE_CLEARANCE_M,
|
||||
COVERAGE_NEIGHBOR_RADIUS_KM,
|
||||
COVERAGE_NEIGHBOR_LIMIT,
|
||||
IDLE_COVERAGE_COLOR,
|
||||
PLANE_FOOTPRINT_LIFT_CAP_M,
|
||||
} from './policy.js';
|
||||
|
||||
@@ -262,30 +261,18 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* 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).
|
||||
* @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 }}
|
||||
* Distance along a pitched-down view axis to flat ground at the mount's own
|
||||
* ground height, or null for an axis at or above the horizon.
|
||||
* @param {number} mountHeightM Mount height above its ground.
|
||||
* @param {number} pitchDeg Axis pitch (negative looks down).
|
||||
* @returns {number|null}
|
||||
*/
|
||||
|
||||
function frustumCartesians(geometry) {
|
||||
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt);
|
||||
return {
|
||||
mount: at(geometry.mount),
|
||||
capCenter: at(geometry.capCenter),
|
||||
tl: at(geometry.corners.tl),
|
||||
tr: at(geometry.corners.tr),
|
||||
br: at(geometry.corners.br),
|
||||
bl: at(geometry.corners.bl),
|
||||
label: Cesium.Cartesian3.fromDegrees(
|
||||
geometry.topCenter.lon,
|
||||
geometry.topCenter.lat,
|
||||
geometry.topCenter.alt + 1.2,
|
||||
),
|
||||
};
|
||||
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
|
||||
const height = Number(mountHeightM);
|
||||
const pitch = Number(pitchDeg);
|
||||
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
|
||||
return height / Math.sin((Math.min(89, -pitch) * Math.PI) / 180);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -293,40 +280,35 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
* Used by the plane orientation and the activation obstruction probe — both
|
||||
* need the UNCLAMPED axis, so it comes from the pose, not from clamped points.
|
||||
* @param {Object} camera - Camera pose (headingDeg, pitchDeg).
|
||||
* @param {Cesium.Cartesian3} atPos - ECEF position defining the local ENU frame.
|
||||
* @returns {{ dir: Cesium.Cartesian3, up: Cesium.Cartesian3 }} View axis + the
|
||||
* @param {{x: number, y: number, z: number}} atPos - ECEF position defining the local ENU frame.
|
||||
* @returns {{ dir: {x: number, y: number, z: number}, up: {x: number, y: number, z: number} }} View axis + the
|
||||
* frame's in-plane "up" (both unit, mutually perpendicular).
|
||||
*/
|
||||
|
||||
function frustumFrameEcef(camera, atPos) {
|
||||
const h = parts.model.toRad(camera.headingDeg);
|
||||
const p = parts.model.toRad(camera.pitchDeg);
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
|
||||
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
|
||||
const enu = eastNorthUp(atPos);
|
||||
// ENU components: view axis + the perpendicular "up" of the pitched cap.
|
||||
const dirEnu = new Cesium.Cartesian3(
|
||||
const dirEnu = vec(
|
||||
Math.sin(h) * Math.cos(p),
|
||||
Math.cos(h) * Math.cos(p),
|
||||
Math.sin(p),
|
||||
);
|
||||
const upEnu = new Cesium.Cartesian3(
|
||||
const upEnu = vec(
|
||||
-Math.sin(p) * Math.sin(h),
|
||||
-Math.sin(p) * Math.cos(h),
|
||||
Math.cos(p),
|
||||
);
|
||||
return {
|
||||
dir: Cesium.Matrix3.multiplyByVector(
|
||||
rot,
|
||||
dirEnu,
|
||||
new Cesium.Cartesian3(),
|
||||
),
|
||||
up: Cesium.Matrix3.multiplyByVector(rot, upEnu, new Cesium.Cartesian3()),
|
||||
dir: frameVector(enu, dirEnu),
|
||||
up: frameVector(enu, upEnu),
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Recomputes the pure frustum geometry from the camera pose + the given ground
|
||||
* altitude and writes it into the scene: billboard position, the 5 wireframe
|
||||
* altitude and writes it into the scene: icon position, the 5 wireframe
|
||||
* polylines (4 corner rays + closed far-plane rectangle), and the monitor
|
||||
* plane placement. This is the ONLY place v2 geometry is written — called on
|
||||
* slider input / save / activation / the one-shot ground snap, never per frame.
|
||||
@@ -341,38 +323,16 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
record.probeClampRangeM,
|
||||
footprintGroundFor(record),
|
||||
);
|
||||
const positions = frustumCartesians(geometry);
|
||||
const positions = parts.rendering.frustumCartesians(geometry);
|
||||
record.frustumGeometry = geometry;
|
||||
record.frustumPositions = positions;
|
||||
record.position = positions.mount;
|
||||
record.camera.absoluteHeightM = geometry.mount.alt;
|
||||
if (record.billboard) {
|
||||
record.billboard.position = positions.mount;
|
||||
}
|
||||
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
|
||||
@@ -380,8 +340,8 @@ 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) {
|
||||
rebuildViewshedVolume(
|
||||
if (record.viewshedVolume) {
|
||||
parts.rendering.rebuildViewshedVolume(
|
||||
record,
|
||||
record.camera.id === layerState._activeCameraId,
|
||||
);
|
||||
@@ -449,24 +409,17 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
// Photoreal regime. Sampling is delegated to the shared coarse-cell
|
||||
// sampler. It remains event-driven, one-shot per cell, and keeps its
|
||||
// sampler. It remains event-driven, a few probes per cell, and keeps its
|
||||
// existing acceptance window; CCTV adds no rooftop rejection policy.
|
||||
if (sampleGround && parts.model.projectionTilesReady()) {
|
||||
record.groundMeshSampleRequestCount =
|
||||
(record.groundMeshSampleRequestCount || 0) + 1;
|
||||
const viewerCarto = layerState._viewer?.camera?.positionCartographic;
|
||||
const excludeObjects = [...(record.coverageEntities || [])];
|
||||
if (record.billboard) excludeObjects.push(record.billboard);
|
||||
if (record.projection?.planeEntity)
|
||||
excludeObjects.push(record.projection.planeEntity);
|
||||
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
|
||||
excludeObjects: excludeObjects.filter(Boolean),
|
||||
viewerLat: viewerCarto
|
||||
? Cesium.Math.toDegrees(viewerCarto.latitude)
|
||||
: undefined,
|
||||
viewerLon: viewerCarto
|
||||
? Cesium.Math.toDegrees(viewerCarto.longitude)
|
||||
: undefined,
|
||||
const eye = parts.model.eyePose();
|
||||
// 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,52 +479,6 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
return new Set(chosen);
|
||||
}
|
||||
|
||||
/**
|
||||
* Removes (and destroys) a record's viewshed volume primitive, if any.
|
||||
* @param {Object} record - Camera record.
|
||||
*/
|
||||
|
||||
function destroyViewshedVolume(record) {
|
||||
if (!record) return;
|
||||
if (record.viewshedPrimitive && layerState._viewer) {
|
||||
layerState._viewer.scene.primitives.remove(record.viewshedPrimitive);
|
||||
}
|
||||
record.viewshedPrimitive = null;
|
||||
}
|
||||
|
||||
/**
|
||||
* (Re)builds a record's translucent viewshed volume from its CURRENT
|
||||
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
|
||||
* is welded to the cone by construction. Called only where the wireframe
|
||||
* already rewrites (style refresh on mode/visible-set/active changes,
|
||||
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
|
||||
* queries (viewshed design §3b).
|
||||
* @param {Object} record - Camera record.
|
||||
* @param {boolean} isActive - Active camera gets the brighter fill.
|
||||
*/
|
||||
|
||||
function rebuildViewshedVolume(record, isActive) {
|
||||
destroyViewshedVolume(record);
|
||||
if (
|
||||
!layerState._viewer ||
|
||||
!record?.frustumPositions ||
|
||||
!record.viewshedColors
|
||||
)
|
||||
return;
|
||||
const color = isActive
|
||||
? record.viewshedColors.fillActive
|
||||
: record.viewshedColors.fill;
|
||||
const primitive = createFrustumVolumePrimitive(
|
||||
record.frustumPositions,
|
||||
color,
|
||||
);
|
||||
// QA tag: the harness counts viewshed volumes by this marker.
|
||||
primitive._gevViewshed = record.camera.id;
|
||||
record.viewshedPrimitive =
|
||||
layerState._viewer.scene.primitives.add(primitive);
|
||||
record.viewshedActiveTint = !!isActive;
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts how many other cameras have overlapping coverage with the target.
|
||||
* Overlap is approximated by comparing inter-camera distance against the
|
||||
@@ -582,6 +489,13 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
|
||||
function coverageNeighborCount(targetRecord) {
|
||||
if (!targetRecord) return 0;
|
||||
// The summary asks on every notification; scan the catalog only when the
|
||||
// camera, its pose or the catalog changed.
|
||||
const { id, lat, lon, rangeM } = targetRecord.camera;
|
||||
const key = `${id}|${lat}|${lon}|${rangeM}|${layerState._records.length}`;
|
||||
const cached = layerState._neighborCountCache;
|
||||
if (cached?.key === key && cached.records === layerState._records)
|
||||
return cached.count;
|
||||
let count = 0;
|
||||
for (const record of layerState._records) {
|
||||
if (record === targetRecord) continue;
|
||||
@@ -595,52 +509,104 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
((targetRecord.camera.rangeM + record.camera.rangeM) / 1000) * 0.92;
|
||||
if (dKm <= overlapKm) count++;
|
||||
}
|
||||
layerState._neighborCountCache = {
|
||||
key,
|
||||
records: layerState._records,
|
||||
count,
|
||||
};
|
||||
return count;
|
||||
}
|
||||
|
||||
/**
|
||||
* §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.
|
||||
*
|
||||
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
|
||||
* 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.
|
||||
* On a globe map it also casts along the same axis against the globe's
|
||||
* terrain (flat ground at the mount's ground when terrain is missed or met
|
||||
* beyond the range) and clamps at the nearer end. These are the ONLY
|
||||
* raycasts in the whole CCTV subsystem — once per activation, 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. A miss on the photoreal stack or a probe failure
|
||||
* keeps the unclamped range.
|
||||
*
|
||||
* The casts are made now, against the scene as it is, and answer 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;
|
||||
const scene = layerState._viewer?.scene;
|
||||
if (!scene || typeof scene.pickFromRay !== 'function') 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 = Cesium.Cartesian3.fromDegrees(
|
||||
camera.lon,
|
||||
camera.lat,
|
||||
mountAlt,
|
||||
);
|
||||
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
|
||||
const { dir } = frustumFrameEcef(camera, mountPos);
|
||||
// Exclude everything the layer itself draws so the probe can only hit the
|
||||
// world (3D tiles), not our own billboards/polylines/planes.
|
||||
const exclude = [layerState._billboards, ...layerState._coverageEntities];
|
||||
for (const runtime of layerState._projectionEntities) {
|
||||
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
|
||||
}
|
||||
const hit = scene.pickFromRay(new Cesium.Ray(mountPos, dir), exclude);
|
||||
if (!hit?.position) return;
|
||||
const dist = Cesium.Cartesian3.distance(mountPos, hit.position);
|
||||
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
|
||||
// The casts see through everything the layer draws. The surface cast
|
||||
// meets what is drawn on the globe (the photoreal tiles); on a globe
|
||||
// map the axis also ends on the globe's terrain, the nearer of that and
|
||||
// any surface hit. A hit at or beyond the range counts as none. Terrain
|
||||
// still loading at a coarse level can be missed or met beyond the
|
||||
// range; then flat ground at the mount's own ground stands in for it.
|
||||
const inRange = (d) => Number.isFinite(d) && d > 0 && d < camera.rangeM;
|
||||
return Promise.all([
|
||||
parts.rendering.obstructionHit(mountPos, dir),
|
||||
parts.rendering.terrainHit?.(mountPos, dir) ?? null,
|
||||
])
|
||||
.then(([hit, terrain]) => {
|
||||
if (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 hitDist = hit ? distance(mountPos, hit) : NaN;
|
||||
const distances = inRange(hitDist) ? [hitDist] : [];
|
||||
if (terrain) {
|
||||
const terrainDist = terrain.hit
|
||||
? distance(mountPos, terrain.hit)
|
||||
: NaN;
|
||||
const ground = inRange(terrainDist)
|
||||
? terrainDist
|
||||
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
|
||||
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
|
||||
}
|
||||
if (!distances.length) return;
|
||||
const clamp = activationProbeClampRange(
|
||||
camera.rangeM,
|
||||
Math.min(...distances),
|
||||
);
|
||||
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();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -653,77 +619,17 @@ 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);
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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.
|
||||
* @param {Object} record - Camera record.
|
||||
* @returns {Cesium.Entity[]} Array of five coverage entities.
|
||||
*/
|
||||
|
||||
function buildCoverageEntities(record) {
|
||||
const { camera } = record;
|
||||
// Prefer the record's already-refined geometry. Lazy creation commonly
|
||||
// happens after the staggered ground pass; recomputing from the catalog
|
||||
// prior here would regress the camera to its pre-sampled datum.
|
||||
let geometry = record.frustumGeometry;
|
||||
let positions = record.frustumPositions;
|
||||
if (!geometry || !positions) {
|
||||
geometry = computeFrustumGeometry(
|
||||
camera,
|
||||
parts.ground.groundPriorAltFor(record),
|
||||
record.probeClampRangeM,
|
||||
);
|
||||
positions = frustumCartesians(geometry);
|
||||
record.frustumGeometry = geometry;
|
||||
record.frustumPositions = positions;
|
||||
record.position = positions.mount;
|
||||
}
|
||||
|
||||
const addPolyline = (role, linePositions) =>
|
||||
layerState._viewer.entities.add({
|
||||
id: `cctv-${camera.id}-${role}`,
|
||||
properties: { cctvCameraId: camera.id },
|
||||
polyline: {
|
||||
positions: linePositions,
|
||||
width: 1.2,
|
||||
material: IDLE_COVERAGE_COLOR,
|
||||
},
|
||||
});
|
||||
|
||||
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,
|
||||
]),
|
||||
];
|
||||
|
||||
entities[0]._coverageRole = 'edge';
|
||||
entities[1]._coverageRole = 'edge';
|
||||
entities[2]._coverageRole = 'edge';
|
||||
entities[3]._coverageRole = 'edge';
|
||||
entities[4]._coverageRole = 'cap';
|
||||
return entities;
|
||||
}
|
||||
|
||||
/**
|
||||
* Materializes coverage entities for eligible records exactly once.
|
||||
* The helper is dependency-injected so unit tests can prove the enable policy
|
||||
* without constructing Cesium entities.
|
||||
* without constructing entities.
|
||||
*
|
||||
* @param {Object[]} records CCTV runtime records.
|
||||
* @param {(record: Object) => boolean} [isEligible] Eligibility predicate.
|
||||
@@ -781,7 +687,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
|
||||
function ensureActiveCoverageEntities(record) {
|
||||
return registerCoverageEntities(
|
||||
materializeCctvActiveCoverageEntities(record, buildCoverageEntities),
|
||||
materializeCctvActiveCoverageEntities(
|
||||
record,
|
||||
parts.rendering.buildCoverageEntities,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
||||
@@ -790,7 +699,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
materializeCctvVisibleCoverageEntities(
|
||||
records,
|
||||
visibleIds,
|
||||
buildCoverageEntities,
|
||||
parts.rendering.buildCoverageEntities,
|
||||
),
|
||||
);
|
||||
}
|
||||
@@ -801,13 +710,11 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
|
||||
function destroyCoverageEntities() {
|
||||
if (!layerState._viewer) return;
|
||||
for (const entity of layerState._coverageEntities) {
|
||||
layerState._viewer.entities.remove(entity);
|
||||
}
|
||||
parts.rendering.removeCoverageEntities();
|
||||
layerState._coverageEntities = [];
|
||||
|
||||
for (const record of layerState._records) {
|
||||
destroyViewshedVolume(record);
|
||||
parts.rendering.destroyViewshedVolume(record);
|
||||
}
|
||||
|
||||
for (const runtime of layerState._projectionEntities) {
|
||||
@@ -820,17 +727,14 @@ export function createGeometry({ state: layerState, services, parts, source }) {
|
||||
hasShippedFootprint,
|
||||
footprintPose,
|
||||
activationProbeClampRange,
|
||||
frustumCartesians,
|
||||
flatGroundAxisDistance,
|
||||
frustumFrameEcef,
|
||||
applyFrustumGeometry,
|
||||
updateRecordGeometry,
|
||||
buildCoverageVisibleSet,
|
||||
destroyViewshedVolume,
|
||||
rebuildViewshedVolume,
|
||||
coverageNeighborCount,
|
||||
runActivationObstructionProbe,
|
||||
clearProbeClampOnDeactivation,
|
||||
buildCoverageEntities,
|
||||
materializeCctvCoverageEntities,
|
||||
materializeCctvActiveCoverageEntities,
|
||||
materializeCctvVisibleCoverageEntities,
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
// src/layers/cctv/geometry.test.mjs
|
||||
// The frustum's view axis and the monitor plane's orientation are computed
|
||||
// with the shared geo helpers; they must give what the renderer's own transforms
|
||||
// gave, bit for bit, so frustums, probes and planes land where they did.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import * as Cesium from 'cesium';
|
||||
import { createGeometry } from './geometry.js';
|
||||
import { createModel } from './model.js';
|
||||
|
||||
function parts() {
|
||||
const p = {};
|
||||
const context = {
|
||||
state: {},
|
||||
services: { ground: {}, mesh: {}, focus: {} },
|
||||
parts: p,
|
||||
};
|
||||
p.model = createModel(context);
|
||||
p.geometry = createGeometry(context);
|
||||
return p;
|
||||
}
|
||||
|
||||
/** The renderer's own frame, as the layer computed it before. */
|
||||
function cesiumFrame(camera, atPos) {
|
||||
const h = Cesium.Math.toRadians(camera.headingDeg);
|
||||
const p = Cesium.Math.toRadians(camera.pitchDeg);
|
||||
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
|
||||
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
|
||||
const dirEnu = new Cesium.Cartesian3(
|
||||
Math.sin(h) * Math.cos(p),
|
||||
Math.cos(h) * Math.cos(p),
|
||||
Math.sin(p),
|
||||
);
|
||||
const upEnu = new Cesium.Cartesian3(
|
||||
-Math.sin(p) * Math.sin(h),
|
||||
-Math.sin(p) * Math.cos(h),
|
||||
Math.cos(p),
|
||||
);
|
||||
const dir = Cesium.Matrix3.multiplyByVector(
|
||||
rot,
|
||||
dirEnu,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const up = Cesium.Matrix3.multiplyByVector(
|
||||
rot,
|
||||
upEnu,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const right = Cesium.Cartesian3.cross(dir, up, new Cesium.Cartesian3());
|
||||
const normal = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
|
||||
const orientation = Cesium.Quaternion.fromRotationMatrix(
|
||||
new Cesium.Matrix3(
|
||||
right.x,
|
||||
up.x,
|
||||
normal.x,
|
||||
right.y,
|
||||
up.y,
|
||||
normal.y,
|
||||
right.z,
|
||||
up.z,
|
||||
normal.z,
|
||||
),
|
||||
);
|
||||
return { dir, up, orientation };
|
||||
}
|
||||
|
||||
const xyz = (v) => [v.x, v.y, v.z];
|
||||
|
||||
test('the frustum axis and plane orientation match the renderer transforms exactly', () => {
|
||||
const { geometry, model } = parts();
|
||||
let seed = 7;
|
||||
const random = () => {
|
||||
seed = (seed * 16807) % 2147483647;
|
||||
return seed / 2147483647;
|
||||
};
|
||||
for (let i = 0; i < 500; i++) {
|
||||
const camera = {
|
||||
headingDeg: random() * 360,
|
||||
pitchDeg: -89 + random() * 120,
|
||||
};
|
||||
const atPos = Cesium.Cartesian3.fromDegrees(
|
||||
-180 + random() * 360,
|
||||
-89 + random() * 178,
|
||||
random() * 3000,
|
||||
);
|
||||
const expected = cesiumFrame(camera, atPos);
|
||||
const frame = geometry.frustumFrameEcef(camera, atPos);
|
||||
assert.deepEqual(xyz(frame.dir), xyz(expected.dir));
|
||||
assert.deepEqual(xyz(frame.up), xyz(expected.up));
|
||||
const q = model.planeOrientationFor(camera, atPos);
|
||||
const e = expected.orientation;
|
||||
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);
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { followedOf } from '../../data/followed.js';
|
||||
import {
|
||||
GEO_PROGRESS_NOTIFY_INTERVAL_MS,
|
||||
GEO_PROGRESS_NOTIFY_BATCH_LIMIT,
|
||||
@@ -6,6 +6,8 @@ import {
|
||||
GEO_TRACKING_BATCH_DELAY_MS,
|
||||
GEO_LOAD_BATCH_SIZE,
|
||||
GEO_LOAD_BATCH_DELAY_MS,
|
||||
VIEW_GEOMETRY_ATTEMPTS,
|
||||
VIEW_GEOMETRY_RETRY_MS,
|
||||
} from './policy.js';
|
||||
|
||||
export function createGeometryQueue({
|
||||
@@ -25,6 +27,8 @@ export function createGeometryQueue({
|
||||
clearTimeout(layerState._geoQueueTimer);
|
||||
layerState._geoQueueTimer = 0;
|
||||
}
|
||||
clearTimeout(layerState._viewGeometryRetryTimer);
|
||||
layerState._viewGeometryRetryTimer = 0;
|
||||
layerState._geoQueue = [];
|
||||
layerState._geoProgressNotifier = null;
|
||||
if (clearProgress) {
|
||||
@@ -121,16 +125,16 @@ export function createGeometryQueue({
|
||||
* throughput without restarting the queue.
|
||||
*
|
||||
* @param {Object} [ownership={}] Current camera-ownership state.
|
||||
* @param {*} [ownership.trackedEntity] Cesium tracked entity, if any.
|
||||
* @param {*} [ownership.followed] What the camera follows, if anything.
|
||||
* @param {boolean} [ownership.cockpitActive] Whether cockpit owns the camera.
|
||||
* @returns {{ batchSize: number, delayMs: number }} Drain pacing.
|
||||
*/
|
||||
|
||||
function cctvGeometryDrainPacing({
|
||||
trackedEntity = null,
|
||||
followed = null,
|
||||
cockpitActive = false,
|
||||
} = {}) {
|
||||
if (trackedEntity || cockpitActive) {
|
||||
if (followed || cockpitActive) {
|
||||
return {
|
||||
batchSize: GEO_TRACKING_BATCH_SIZE,
|
||||
delayMs: GEO_TRACKING_BATCH_DELAY_MS,
|
||||
@@ -209,7 +213,7 @@ export function createGeometryQueue({
|
||||
const batchResult = processCctvGeometryDrainBatch({
|
||||
queue: layerState._geoQueue,
|
||||
readOwnership: () => ({
|
||||
trackedEntity: layerState._viewer.trackedEntity,
|
||||
followed: followedOf(layerState._viewer),
|
||||
cockpitActive:
|
||||
typeof document !== 'undefined' &&
|
||||
document.body?.classList.contains('cockpit-mode'),
|
||||
@@ -223,6 +227,7 @@ export function createGeometryQueue({
|
||||
err?.message || err,
|
||||
);
|
||||
}
|
||||
noteViewAttempt(record);
|
||||
if (
|
||||
layerState._geoLoading &&
|
||||
layerState._geoLoadDone < layerState._geoLoadTotal
|
||||
@@ -236,14 +241,15 @@ export function createGeometryQueue({
|
||||
layerState._geoLoading = false;
|
||||
if (wasInitialLoad) {
|
||||
layerState._geoLoadDone = layerState._geoLoadTotal;
|
||||
if (layerState._enabled) {
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
// Geometry refinement may have replaced record.position objects — the
|
||||
// one-shot drain completion re-anchors the card entries (event-driven,
|
||||
// not a per-frame or timer pass).
|
||||
parts.cards.refreshAmbientCards();
|
||||
}
|
||||
if (layerState._enabled) parts.rendering.refreshCoverageStyles();
|
||||
}
|
||||
// Geometry refinement may have replaced record.position objects — every
|
||||
// drain's completion re-anchors the card entries (event-driven, not a
|
||||
// per-frame or timer pass).
|
||||
// While the camera moves, moveEnd reselects them instead.
|
||||
if (layerState._enabled && !layerState._cameraMoving)
|
||||
parts.cards.refreshAmbientCards();
|
||||
scheduleViewGeometryRetry();
|
||||
// Completion is never coalesced: subscribers must observe the final
|
||||
// loading state even if the last progress tick just happened.
|
||||
layerState._geoProgressNotifier?.finish();
|
||||
@@ -261,16 +267,17 @@ export function createGeometryQueue({
|
||||
|
||||
/**
|
||||
* Appends records to the geometry queue (no progress tracking) and starts
|
||||
* the batch timer if idle. Used by update()'s ONE-SHOT tiles-ready completion
|
||||
* pass (records left `!groundResolved` by an enable-time drain that ran while
|
||||
* tiles were still streaming) so it shares the same stagger machinery as the
|
||||
* initial load. Fires at most once per enable — never on a recurring timer.
|
||||
* the batch timer if idle. Used by update()'s one-shot tiles-ready
|
||||
* completion pass and by enqueueViewGeometry, so both share the initial
|
||||
* load's stagger machinery. Never driven by a recurring timer.
|
||||
* @param {Object[]} records - Camera records needing geometry refresh.
|
||||
*/
|
||||
|
||||
function enqueueGeometryRefresh(records) {
|
||||
const queued = new Set(layerState._geoQueue);
|
||||
for (const record of records) {
|
||||
if (!layerState._geoQueue.includes(record)) {
|
||||
if (!queued.has(record)) {
|
||||
queued.add(record);
|
||||
layerState._geoQueue.push(record);
|
||||
}
|
||||
}
|
||||
@@ -283,10 +290,10 @@ export function createGeometryQueue({
|
||||
}
|
||||
|
||||
/**
|
||||
* Starts the initial staggered load: orders all records active-camera-first,
|
||||
* then by distance from the current viewer position (nearest first, so
|
||||
* cameras likely in view refine before off-screen ones), and exposes
|
||||
* loaded/total progress through uiState()/getStats() while running.
|
||||
* Starts the initial staggered load over the geometry working set: active
|
||||
* camera first, then by distance from the current viewer position (nearest
|
||||
* first), and exposes loaded/total progress through uiState()/getStats()
|
||||
* while running. Cameras outside the view refine when they come into it.
|
||||
*/
|
||||
|
||||
function startGeometryLoadQueue() {
|
||||
@@ -296,14 +303,10 @@ export function createGeometryQueue({
|
||||
layerState._tilesReadyReenqueued = false;
|
||||
if (!layerState._records.length) return;
|
||||
const active = parts.selection.getActiveRecord();
|
||||
const carto = layerState._viewer?.camera?.positionCartographic;
|
||||
const refLat = carto
|
||||
? Cesium.Math.toDegrees(carto.latitude)
|
||||
: (active?.camera.lat ?? 0);
|
||||
const refLon = carto
|
||||
? Cesium.Math.toDegrees(carto.longitude)
|
||||
: (active?.camera.lon ?? 0);
|
||||
const pending = layerState._records
|
||||
const pose = parts.model.eyePose();
|
||||
const refLat = pose ? pose.lat : (active?.camera.lat ?? 0);
|
||||
const refLon = pose ? pose.lon : (active?.camera.lon ?? 0);
|
||||
const pending = geometryWorkingSet()
|
||||
.filter((record) => record !== active)
|
||||
.map((record) => ({
|
||||
record,
|
||||
@@ -325,7 +328,134 @@ export function createGeometryQueue({
|
||||
);
|
||||
layerState._geoQueueTimer = setTimeout(processGeometryBatch, 0);
|
||||
}
|
||||
/**
|
||||
* The records whose geometry the view needs: the shown icons, the active
|
||||
* camera and the coverage cohort drawn around it.
|
||||
* @returns {Object[]}
|
||||
*/
|
||||
|
||||
function geometryWorkingSet() {
|
||||
const records = new Set(layerState._viewRecords);
|
||||
const active = parts.selection.getActiveRecord();
|
||||
if (active) records.add(active);
|
||||
for (const id of layerState._coverageVisibleIds) {
|
||||
const record = layerState._recordById.get(id);
|
||||
if (record) records.add(record);
|
||||
}
|
||||
return [...records];
|
||||
}
|
||||
|
||||
/** The regime key a view attempt counts against: interim while tiles stream. */
|
||||
function viewAttemptKey() {
|
||||
const regime = parts.ground.currentSurfaceRegime();
|
||||
const tilesReady =
|
||||
regime !== 'google-3d' || parts.model.projectionTilesReady();
|
||||
return { key: tilesReady ? regime : `${regime}:interim`, tilesReady };
|
||||
}
|
||||
|
||||
/**
|
||||
* Counts a processed geometry attempt against the current regime key; each
|
||||
* key keeps its own count, so tile streaming going on and off does not
|
||||
* reset the ready-tiles budget.
|
||||
*/
|
||||
function noteViewAttempt(record) {
|
||||
const { key } = viewAttemptKey();
|
||||
record.viewAttempts ??= {};
|
||||
record.viewAttempts[key] = (record.viewAttempts[key] || 0) + 1;
|
||||
record.viewAttemptAt = performance.now();
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether a record may be attempted again under `key`. After a first
|
||||
* unresolved attempt, the second waits out VIEW_GEOMETRY_RETRY_MS so its
|
||||
* elevation cell can warm, rather than going to the next motion tick.
|
||||
*/
|
||||
/** Whether a record still has an attempt left under the current key. */
|
||||
function withinViewBudget(record) {
|
||||
const { key } = viewAttemptKey();
|
||||
return (record.viewAttempts?.[key] || 0) < VIEW_GEOMETRY_ATTEMPTS;
|
||||
}
|
||||
|
||||
function attemptsLeft(record, key) {
|
||||
const attempts = record.viewAttempts?.[key] || 0;
|
||||
if (attempts >= VIEW_GEOMETRY_ATTEMPTS) return false;
|
||||
return (
|
||||
attempts === 0 ||
|
||||
performance.now() - record.viewAttemptAt >= VIEW_GEOMETRY_RETRY_MS
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* After a drain, gives working-set cameras it left ungrounded one more
|
||||
* attempt once their elevation cells have had time to warm. The timer is
|
||||
* set for the earliest such camera and re-arms for the rest when it fires.
|
||||
*/
|
||||
function scheduleViewGeometryRetry() {
|
||||
if (!layerState._enabled || layerState._viewGeometryRetryTimer) return;
|
||||
const { key } = viewAttemptKey();
|
||||
const active = parts.selection.getActiveRecord();
|
||||
let due = Infinity;
|
||||
for (const record of geometryWorkingSet()) {
|
||||
const attempts = record.viewAttempts?.[key] || 0;
|
||||
if (
|
||||
record === active ||
|
||||
attempts === 0 ||
|
||||
attempts >= VIEW_GEOMETRY_ATTEMPTS ||
|
||||
!parts.ground.needsGeometry(record)
|
||||
)
|
||||
continue;
|
||||
due = Math.min(due, record.viewAttemptAt + VIEW_GEOMETRY_RETRY_MS);
|
||||
}
|
||||
if (due === Infinity) return;
|
||||
layerState._viewGeometryRetryTimer = setTimeout(
|
||||
() => {
|
||||
layerState._viewGeometryRetryTimer = 0;
|
||||
enqueueViewGeometry();
|
||||
// A drain re-arms on completion; with none running, the cameras still
|
||||
// cooling down need their own timer.
|
||||
if (!layerState._geoQueueTimer) scheduleViewGeometryRetry();
|
||||
},
|
||||
Math.max(0, due - performance.now()),
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Queues working-set cameras the current surface has not grounded yet,
|
||||
* after a camera move brings new ones into view. Attempts are counted when
|
||||
* a record is processed, not queued, so a drain cut short by disable() is
|
||||
* not lost; each record gets VIEW_GEOMETRY_ATTEMPTS per surface regime,
|
||||
* spaced by VIEW_GEOMETRY_RETRY_MS, so a sample the shared floor refuses
|
||||
* (too far, too high) is not retried on every move. While photoreal tiles are still streaming the attempts are
|
||||
* interim, and the update() completion pass is re-armed to retry these
|
||||
* records when they land. The active camera is left to selection, which
|
||||
* owns its re-sampling.
|
||||
*/
|
||||
|
||||
function enqueueViewGeometry() {
|
||||
if (!layerState._enabled) return;
|
||||
const { key, tilesReady } = viewAttemptKey();
|
||||
const active = parts.selection.getActiveRecord();
|
||||
const pending = [];
|
||||
let coolingDown = false;
|
||||
for (const record of geometryWorkingSet()) {
|
||||
if (record === active || !parts.ground.needsGeometry(record)) continue;
|
||||
if (!attemptsLeft(record, key)) {
|
||||
coolingDown ||=
|
||||
(record.viewAttempts?.[key] || 0) < VIEW_GEOMETRY_ATTEMPTS;
|
||||
continue;
|
||||
}
|
||||
pending.push(record);
|
||||
}
|
||||
// A camera back in view during its cooldown still needs its retry timer.
|
||||
if (coolingDown && !layerState._geoQueueTimer) scheduleViewGeometryRetry();
|
||||
if (!pending.length) return;
|
||||
if (!tilesReady) layerState._tilesReadyReenqueued = false;
|
||||
enqueueGeometryRefresh(pending);
|
||||
}
|
||||
return {
|
||||
enqueueViewGeometry,
|
||||
withinViewBudget,
|
||||
geometryWorkingSet,
|
||||
stopGeometryLoadQueue,
|
||||
createGeometryProgressNotifier,
|
||||
processCctvGeometryQueueBatch,
|
||||
|
||||
@@ -1,3 +1,5 @@
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { findGlobe } from '../../render/rendererOf.js';
|
||||
import {
|
||||
SUPPORT_KEYS,
|
||||
planeSupportPoints,
|
||||
@@ -12,7 +14,7 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
const { resolveEllipsoidalGround } = services.terrain;
|
||||
|
||||
/**
|
||||
* Task 5 (height-datum fix): maps the scene's `globe.show` flag to the surface
|
||||
* Task 5 (height-datum fix): maps whether the renderer shows the globe to the surface
|
||||
* regime key the per-camera ground cache is keyed by (spec §2 "cache by
|
||||
* surface regime", collapsed to two keys — ion World Terrain and Re:Earth
|
||||
* globe terrain get the same handling):
|
||||
@@ -25,7 +27,8 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
* Only an explicit `false` (the photoreal stack hides the globe) selects
|
||||
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
|
||||
* that never touches the scene. Pure — exported for the unit suite.
|
||||
* @param {boolean|undefined|null} globeShow - `viewer.scene.globe.show`.
|
||||
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
|
||||
* globe (`globe.isGlobeVisible()`).
|
||||
* @returns {'google-3d'|'terrain-globe'}
|
||||
*/
|
||||
|
||||
@@ -35,15 +38,15 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
|
||||
/**
|
||||
* Task 5: the surface regime the scene is CURRENTLY rendering, derived live
|
||||
* from `globe.show` (mapStackController's `_activatePhotoreal` /
|
||||
* `_activateGlobeStack` flip exactly this flag). Reading scene state directly
|
||||
* from whether the renderer shows the globe (mapStackController's
|
||||
* `_activatePhotoreal` / `_activateGlobeStack` flip exactly this). Reading it live
|
||||
* — rather than caching the map-stack id — means the regime is correct even
|
||||
* for stack changes this module never got an event for.
|
||||
* @returns {'google-3d'|'terrain-globe'}
|
||||
*/
|
||||
|
||||
function currentSurfaceRegime() {
|
||||
return surfaceRegimeKey(layerState._viewer?.scene?.globe?.show);
|
||||
return surfaceRegimeKey(findGlobe(layerState._viewer)?.isGlobeVisible?.());
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -78,6 +81,14 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
return record?.groundResolved?.[regime] === true;
|
||||
}
|
||||
|
||||
/**
|
||||
* True until the record has geometry grounded for the regime. Cameras are
|
||||
* refined only once they enter the view, so many never have geometry.
|
||||
*/
|
||||
function needsGeometry(record, regime = currentSurfaceRegime()) {
|
||||
return !record?.frustumGeometry || !isGroundResolved(record, regime);
|
||||
}
|
||||
|
||||
/**
|
||||
* Ground altitude used for pure geometry recomputes: the given regime's
|
||||
* cached resolution (`record.groundSamples[regime]` — a shared mesh/DEM floor
|
||||
@@ -184,8 +195,11 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
* Task 5: applies a LATE-arriving ground-prior batch (init's bounded race
|
||||
* lost — cold proxy cache / slow upstream). Pure recomputes only, no scene
|
||||
* queries:
|
||||
* - records without geometry yet: only the icon moves onto the prior;
|
||||
* the frustum is built when the camera enters the view.
|
||||
* - terrain-globe regime: the prior IS the resolution → re-run the
|
||||
* resolution (updateRecordGeometry latches it) for every record.
|
||||
* resolution (updateRecordGeometry latches it) for every record with
|
||||
* geometry.
|
||||
* - google-3d regime: records still awaiting a shared floor move from the
|
||||
* catalog fallback onto the exact prior; records already holding a shared
|
||||
* mesh/DEM floor keep it untouched.
|
||||
@@ -198,6 +212,7 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
function applyLateGroundPriors(records, priors) {
|
||||
if (!Array.isArray(records) || !Array.isArray(priors)) return;
|
||||
let applied = 0;
|
||||
let moved = 0;
|
||||
for (let i = 0; i < records.length && i < priors.length; i++) {
|
||||
const record = records[i];
|
||||
const prior = priors[i];
|
||||
@@ -212,6 +227,26 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
record.camera.absoluteHeightM =
|
||||
prior.ellipsoid + record.camera.mountHeightM;
|
||||
}
|
||||
// Cameras without geometry only move their icon onto the prior, so the
|
||||
// view pass projects the right point; their frustums are built when
|
||||
// they enter the view, as recomputing the whole catalog here would
|
||||
// stall a large one.
|
||||
if (!record.frustumGeometry) {
|
||||
if (record.position) {
|
||||
// In place: the record keeps its position object.
|
||||
const { x, y, z } = fromDegrees(
|
||||
record.camera.lon,
|
||||
record.camera.lat,
|
||||
record.camera.absoluteHeightM,
|
||||
);
|
||||
record.position.x = x;
|
||||
record.position.y = y;
|
||||
record.position.z = z;
|
||||
parts.rendering.moveCameraIcon(record);
|
||||
moved += 1;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
const regime = currentSurfaceRegime();
|
||||
if (regime === 'terrain-globe') {
|
||||
// Prior IS the resolution — re-latch onto the fresh value.
|
||||
@@ -224,7 +259,9 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
applied += 1;
|
||||
}
|
||||
}
|
||||
if (applied) parts.presentation.notifyListeners();
|
||||
if (moved && parts.rendering.refreshHorizonCulling())
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
if (applied || moved) parts.presentation.notifyListeners();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -234,7 +271,7 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
* deck/building-top in google-3d vs bare Re:Earth DEM on globe stacks), so
|
||||
* on a REGIME change (photoreal ↔ globe; bing→osm stays 'terrain-globe' and
|
||||
* no-ops):
|
||||
* 1. every record's geometry recomputes IMMEDIATELY from the new regime's
|
||||
* 1. every record that has geometry recomputes IMMEDIATELY from the new regime's
|
||||
* resolution — cached sample if that regime has one, else the Re:Earth
|
||||
* prior (never blank, zero scene queries);
|
||||
* 2. entering google-3d re-arms the one-shot tiles-ready completion latch so
|
||||
@@ -250,6 +287,9 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
layerState._lastAppliedRegime = regime;
|
||||
|
||||
for (const record of layerState._records) {
|
||||
// Only cameras that already have geometry are rewritten; the rest are
|
||||
// grounded for the new regime when they enter the view.
|
||||
if (!record.frustumGeometry) continue;
|
||||
if (regime === 'terrain-globe') {
|
||||
// Prior IS the resolution — latch it (zero scene queries).
|
||||
record.groundSamples['terrain-globe'] = groundPriorAltFor(record);
|
||||
@@ -353,6 +393,7 @@ export function createGround({ state: layerState, services, parts, source }) {
|
||||
resolveFootprintGround,
|
||||
groundPriorAltFor,
|
||||
isGroundResolved,
|
||||
needsGeometry,
|
||||
groundAltFor,
|
||||
rearmGroundResolution,
|
||||
resolveCommittedGroundAnchor,
|
||||
|
||||
@@ -1,4 +1,5 @@
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
|
||||
|
||||
/**
|
||||
* @module headingConfidence
|
||||
@@ -44,7 +45,7 @@ export function isHeadingEstimated(camera) {
|
||||
* @returns {string}
|
||||
*/
|
||||
export function headingHudToken(camera) {
|
||||
const hdg = Math.round(Number(camera?.headingDeg) || 0);
|
||||
const hdg = roundHeadingDegrees(Number(camera?.headingDeg)) ?? 0;
|
||||
return isHeadingEstimated(camera)
|
||||
? t('HDG {value}° (ESTIMATED)', { value: hdg })
|
||||
: t('HDG {value}°', { value: hdg });
|
||||
|
||||
@@ -44,6 +44,15 @@ test('HUD token tags a synthetic bearing and rounds the degrees', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('HUD token reads a bearing that rounds to north as 0°, not 360°', () => {
|
||||
assert.equal(headingHudToken({ headingDeg: 359.4 }), 'HDG 359°');
|
||||
assert.equal(headingHudToken({ headingDeg: 359.6 }), 'HDG 0°');
|
||||
assert.equal(
|
||||
headingHudToken({ headingDeg: 359.5, headingConfidence: 'low' }),
|
||||
'HDG 0° (ESTIMATED)',
|
||||
);
|
||||
});
|
||||
|
||||
test('HUD token stays untagged for surveyed and calibrated bearings', () => {
|
||||
assert.equal(
|
||||
headingHudToken({ headingDeg: 67.5, headingConfidence: 'high' }),
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { HEALTH_SYNC_INTERVAL_MS, HEALTH_ENDPOINT } from './policy.js';
|
||||
import { HEALTH_SYNC_INTERVAL_MS } from './policy.js';
|
||||
|
||||
export function createHealth({ state: layerState, services, parts, source }) {
|
||||
/**
|
||||
|
||||
@@ -10,7 +10,7 @@ export function createHover({ state: layerState, services, parts, source }) {
|
||||
* Throttled MOUSE_MOVE hover pass (owner round 2, item B): pointing at a
|
||||
* camera icon that has no card summons its card immediately. This is
|
||||
* EVENT-DRIVEN picking on a user gesture, not steady-state work — the
|
||||
* ≥120 ms throttle caps it at ~8 scene.pick calls/s while the pointer is
|
||||
* ≥120 ms throttle caps it at ~8 scene picks/s while the pointer is
|
||||
* actually moving (a still pointer costs nothing), so it can never approach
|
||||
* per-frame cost. Skipped while the camera is in motion, while ADJUST mode
|
||||
* owns the pointer (gizmo drags), and while the layer is disabled.
|
||||
@@ -29,13 +29,7 @@ export function createHover({ state: layerState, services, parts, source }) {
|
||||
const now = Date.now();
|
||||
if (now - layerState._hoverLastPickAt < HOVER_PICK_THROTTLE_MS) return;
|
||||
layerState._hoverLastPickAt = now;
|
||||
let picked = null;
|
||||
try {
|
||||
picked = layerState._viewer.scene.pick(position);
|
||||
} catch {
|
||||
picked = null;
|
||||
}
|
||||
const cameraId = parts.selection.extractPickedCameraId(picked);
|
||||
const cameraId = parts.rendering.pickCameraIdAt(position);
|
||||
if (cameraId && cameraId === layerState._hoverCardId) {
|
||||
// Still on the hovered camera — keep the card alive.
|
||||
cancelHoverRelease();
|
||||
@@ -49,9 +43,8 @@ export function createHover({ state: layerState, services, parts, source }) {
|
||||
!!record &&
|
||||
cameraId !== layerState._activeCameraId &&
|
||||
!layerState._cardIds.has(cameraId) &&
|
||||
!parts.model.isVideoFeedType(
|
||||
parts.model.normalizeFeedType(record.camera.feedType),
|
||||
);
|
||||
!parts.model.isBrowserOverlayCamera(record.camera) &&
|
||||
!parts.model.isVideoFeedCamera(record.camera);
|
||||
if (eligible) {
|
||||
cancelHoverRelease();
|
||||
layerState._hoverCardId = cameraId;
|
||||
|
||||
@@ -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);
|
||||
@@ -73,6 +75,7 @@ export function createCctvLayer({ services, source }) {
|
||||
deriveCalBadge: parts.calibration.deriveCalBadge,
|
||||
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
|
||||
activationProbeClampRange: parts.geometry.activationProbeClampRange,
|
||||
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
|
||||
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
|
||||
_createCctvProjectionPlaneForTest:
|
||||
parts.testing._createCctvProjectionPlaneForTest,
|
||||
@@ -91,6 +94,9 @@ export function createCctvLayer({ services, source }) {
|
||||
processGeometryBatch: parts.geometryQueue.processGeometryBatch,
|
||||
hideCctvRecordVisuals: parts.rendering.hideCctvRecordVisuals,
|
||||
refreshCoverageStyles: parts.rendering.refreshCoverageStyles,
|
||||
refreshHorizonCulling: parts.rendering.refreshHorizonCulling,
|
||||
_viewRecordIdsForTest: () =>
|
||||
state._viewRecords.map((record) => record.camera.id),
|
||||
clearProbeClampOnDeactivation:
|
||||
parts.geometry.clearProbeClampOnDeactivation,
|
||||
cctvRecordNeedsActivation: parts.model.cctvRecordNeedsActivation,
|
||||
@@ -107,8 +113,12 @@ export function createCctvLayer({ services, source }) {
|
||||
_extractPickedCameraIdForTest:
|
||||
parts.testing._extractPickedCameraIdForTest,
|
||||
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
|
||||
_cctvIconsForTest: parts.testing._cctvIconsForTest,
|
||||
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
|
||||
focusCctvRecord: parts.navigation.focusCctvRecord,
|
||||
maybeAutoHop: parts.navigation.maybeAutoHop,
|
||||
openingCameraId: parts.navigation.openingCameraId,
|
||||
reopenNearestCamera: parts.navigation.reopenNearestCamera,
|
||||
cctvCycleIndex: parts.navigation.cctvCycleIndex,
|
||||
},
|
||||
);
|
||||
|
||||
@@ -29,16 +29,25 @@ export function createIngestion({
|
||||
layerState._tilesReadyReenqueued = true;
|
||||
// Per-regime resolution (Task 5): only records unresolved for the
|
||||
// CURRENT surface regime need the completion pass. On globe stacks
|
||||
// projectionTilesReady() is false while a (hidden) Google tileset
|
||||
// exists, so this latch effectively fires for the google-3d regime —
|
||||
// projectionTilesReady() is false (only drawn photoreal tiles can be
|
||||
// ready), so this latch fires for the google-3d regime alone —
|
||||
// terrain-globe records resolve from the prior in their drain pass.
|
||||
const unresolved = layerState._records.filter(
|
||||
(record) => !parts.ground.isGroundResolved(record),
|
||||
);
|
||||
const unresolved = parts.geometryQueue
|
||||
.geometryWorkingSet()
|
||||
.filter(
|
||||
(record) =>
|
||||
!parts.ground.isGroundResolved(record) &&
|
||||
parts.geometryQueue.withinViewBudget(record),
|
||||
);
|
||||
if (unresolved.length)
|
||||
parts.geometryQueue.enqueueGeometryRefresh(unresolved);
|
||||
}
|
||||
await parts.health.syncHealthState();
|
||||
// New health can change which camera wins a crowded cell.
|
||||
if (layerState._enabled && parts.rendering.refreshHorizonCulling()) {
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
parts.cards.refreshAmbientCards();
|
||||
}
|
||||
parts.navigation.maybeAutoHop(now);
|
||||
parts.presentation.notifyListeners();
|
||||
},
|
||||
|
||||
+246
-129
@@ -1,36 +1,174 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { fromDegrees } from '../../geo/ellipsoid.js';
|
||||
import { distance, dot } from '../../geo/vector.js';
|
||||
import { canvasOf, findCamera } from '../../render/rendererOf.js';
|
||||
import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js';
|
||||
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
|
||||
import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js';
|
||||
import { inputFor } from '../../input/dispatcher.js';
|
||||
import {
|
||||
GROUND_PRIOR_INIT_WAIT_MS,
|
||||
CAMERA_ICON,
|
||||
IDLE_CAMERA_COLOR,
|
||||
CALIBRATION_RANGE_FLOOR_M,
|
||||
VIEW_MOTION_REFRESH_MS,
|
||||
VIEW_MOTION_MIN_MOVE_FRACTION,
|
||||
VIEW_MOTION_MIN_TURN_DEG,
|
||||
VIEW_MOTION_COST_FACTOR,
|
||||
} from './policy.js';
|
||||
|
||||
const MIN_TURN_COS = Math.cos((VIEW_MOTION_MIN_TURN_DEG * Math.PI) / 180);
|
||||
|
||||
export function createLifecycle({
|
||||
state: layerState,
|
||||
services,
|
||||
parts,
|
||||
source,
|
||||
}) {
|
||||
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
|
||||
const { activateCctvCameraFromWorldClick } = services.activation;
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
|
||||
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
|
||||
services.picking;
|
||||
const { onFocusTargetAppear } = services.focus;
|
||||
const { releaseContinuousRender } = services.render;
|
||||
|
||||
/**
|
||||
* The settled-view pass: thin the icons, queue the newly visible geometry,
|
||||
* reselect cards, and tell subscribers (the camera picker) when the shown
|
||||
* set changed since they were last told, including by motion passes.
|
||||
*/
|
||||
function settleView() {
|
||||
const changed = parts.rendering.refreshHorizonCulling();
|
||||
noteViewPose();
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
parts.cards.refreshAmbientCards();
|
||||
if (changed || layerState._viewUnpublished) {
|
||||
layerState._viewUnpublished = false;
|
||||
parts.presentation.notifyListeners();
|
||||
}
|
||||
}
|
||||
|
||||
/** Records the camera pose the last view pass ran at. */
|
||||
function noteViewPose() {
|
||||
const pose = findCamera(layerState._viewer)?.pose();
|
||||
if (!pose) return;
|
||||
layerState._viewPose = {
|
||||
position: pose.position,
|
||||
direction: pose.direction,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Whether the camera moved or turned enough since the last view pass to
|
||||
* change what is on screen. A camera that tracks or flies without settling
|
||||
* would otherwise rerun the full pass on every tick.
|
||||
*/
|
||||
function viewPoseChanged() {
|
||||
const now = findCamera(layerState._viewer)?.pose();
|
||||
const pose = layerState._viewPose;
|
||||
if (!pose || !now) return true;
|
||||
// An eye with no geographic position (the earth's centre) has no height.
|
||||
const height = Math.max(1, Number.isFinite(now.height) ? now.height : 0);
|
||||
const moved = distance(now.position, pose.position);
|
||||
if (moved > height * VIEW_MOTION_MIN_MOVE_FRACTION) return true;
|
||||
return dot(now.direction, pose.direction) < MIN_TURN_COS;
|
||||
}
|
||||
|
||||
function viewMotionTick() {
|
||||
if (!layerState._enabled) return;
|
||||
const now = performance.now();
|
||||
const pass = layerState._viewMotionPass;
|
||||
if (pass && now - pass.at < pass.ms * VIEW_MOTION_COST_FACTOR) return;
|
||||
if (!viewPoseChanged()) return;
|
||||
if (parts.rendering.refreshHorizonCulling())
|
||||
layerState._viewUnpublished = true;
|
||||
noteViewPose();
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
layerState._viewMotionPass = { at: now, ms: performance.now() - now };
|
||||
}
|
||||
|
||||
function startViewMotionTimer() {
|
||||
if (layerState._viewMotionTimer) return;
|
||||
layerState._viewMotionTimer = setInterval(
|
||||
viewMotionTick,
|
||||
VIEW_MOTION_REFRESH_MS,
|
||||
);
|
||||
}
|
||||
|
||||
function stopViewMotionTimer() {
|
||||
clearInterval(layerState._viewMotionTimer);
|
||||
layerState._viewMotionTimer = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Listen for the camera's moves on the viewer's camera port: hover picking
|
||||
* pauses while it moves, and the view pass reruns on an interval until the
|
||||
* move ends, then once more. A re-init against a new viewer moves the
|
||||
* listeners to its camera; one against the same viewer keeps them.
|
||||
*/
|
||||
function attachViewListeners() {
|
||||
const viewCamera = findCamera(layerState._viewer);
|
||||
if (
|
||||
layerState._viewListenerCamera &&
|
||||
layerState._viewListenerCamera !== viewCamera
|
||||
) {
|
||||
layerState._horizonCullListener?.();
|
||||
layerState._moveStartListener?.();
|
||||
layerState._horizonCullListener = null;
|
||||
layerState._moveStartListener = null;
|
||||
layerState._cameraMoving = false;
|
||||
}
|
||||
layerState._viewListenerCamera = viewCamera;
|
||||
if (!layerState._horizonCullListener && viewCamera) {
|
||||
// Ambient cards piggyback the same settle event: moveEnd-driven
|
||||
// reselection only, never per frame (refreshAmbientCards no-ops while
|
||||
// the layer is disabled).
|
||||
layerState._horizonCullListener = viewCamera.on('moveEnd', () => {
|
||||
layerState._cameraMoving = false;
|
||||
stopViewMotionTimer();
|
||||
parts.navigation.reopenNearestCamera();
|
||||
settleView();
|
||||
});
|
||||
}
|
||||
if (!layerState._moveStartListener && viewCamera) {
|
||||
// Item B: hover picking pauses while the camera is in motion. A long
|
||||
// move (cockpit flight, a drag) never settles, so the view pass also
|
||||
// reruns on an interval until it does.
|
||||
layerState._moveStartListener = viewCamera.on('moveStart', () => {
|
||||
layerState._cameraMoving = true;
|
||||
// enable() starts it for a move already under way.
|
||||
if (layerState._enabled) startViewMotionTimer();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/** Drop the move listeners; nothing reports the end of a move after it. */
|
||||
function detachViewListeners() {
|
||||
layerState._horizonCullListener?.();
|
||||
layerState._horizonCullListener = null;
|
||||
layerState._moveStartListener?.();
|
||||
layerState._moveStartListener = null;
|
||||
layerState._cameraMoving = false;
|
||||
layerState._viewListenerCamera = null;
|
||||
stopViewMotionTimer();
|
||||
}
|
||||
|
||||
/** Resets all module-scoped runtime state to initial values. */
|
||||
|
||||
function clearRuntimeState() {
|
||||
parts.geometryQueue.stopGeometryLoadQueue();
|
||||
stopViewMotionTimer();
|
||||
// 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 = [];
|
||||
layerState._cameraIndexCache = null;
|
||||
layerState._coverageVisibleIds = new Set();
|
||||
layerState._neighborCountCache = null;
|
||||
layerState._viewUnpublished = false;
|
||||
layerState._viewPose = null;
|
||||
layerState._viewMotionPass = null;
|
||||
layerState._healthById = new Map();
|
||||
layerState._count = 0;
|
||||
layerState._lastUpdate = null;
|
||||
@@ -38,9 +176,6 @@ export function createLifecycle({
|
||||
layerState._lastError = null;
|
||||
layerState._lastFocusStyleAt = 0;
|
||||
layerState._activeFocusStyleCount = 0;
|
||||
// FIX ①/③: the discovered tileset handle is scene-scoped — drop it so a fresh
|
||||
// init re-discovers against the current scene primitives.
|
||||
layerState._activeTileset = null;
|
||||
// Task 5: the applied-regime tracker is record-set-scoped — a fresh init
|
||||
// recomputes it against the then-current scene.
|
||||
layerState._lastAppliedRegime = null;
|
||||
@@ -48,9 +183,9 @@ export function createLifecycle({
|
||||
const methods = {
|
||||
/**
|
||||
* Initializes the CCTV layer: loads camera sources, builds the catalog,
|
||||
* restores calibration from localStorage, creates billboards, sets up click
|
||||
* restores calibration from localStorage, creates camera icons, sets up click
|
||||
* handling, and performs initial health sync. Coverage entities stay lazy.
|
||||
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
|
||||
* @param {object} viewer - The viewer.
|
||||
*/
|
||||
async init(viewer) {
|
||||
layerState._sourceAbort?.abort();
|
||||
@@ -66,13 +201,12 @@ export function createLifecycle({
|
||||
layerState._enabled = false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
layerState._lastHopAt = 0;
|
||||
layerState._lastViewContext = '';
|
||||
layerState._calibrationById = parts.calibration.loadCalibrationStore();
|
||||
|
||||
layerState._billboards = new Cesium.BillboardCollection();
|
||||
layerState._viewer.scene.primitives.add(layerState._billboards);
|
||||
registerSpriteCollection('cctv', layerState._billboards);
|
||||
parts.rendering.createCameraIcons(layerState._viewer);
|
||||
|
||||
const sources = await parts.catalog.loadCameraSources();
|
||||
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
|
||||
@@ -140,32 +274,14 @@ export function createLifecycle({
|
||||
? groundPrior.ellipsoid
|
||||
: Number(camera.groundElevationM) || 0;
|
||||
camera.absoluteHeightM = priorGround + camera.mountHeightM;
|
||||
const position = Cesium.Cartesian3.fromDegrees(
|
||||
const position = fromDegrees(
|
||||
camera.lon,
|
||||
camera.lat,
|
||||
camera.absoluteHeightM,
|
||||
);
|
||||
const billboard = layerState._billboards.add({
|
||||
id: camera.id,
|
||||
image: CAMERA_ICON,
|
||||
position,
|
||||
color: IDLE_CAMERA_COLOR,
|
||||
width: 24,
|
||||
height: 24,
|
||||
// Field-test fix (2026-07-06): always-on-top. The old finite value
|
||||
// (1800 m) re-engaged the depth test at far zoom, where the COARSE
|
||||
// far-LOD Google-3D mesh sits above the true ground and swallowed
|
||||
// ground-anchored icons ("submerged" pills over SF). Far-side-of-globe
|
||||
// icons are handled by refreshHorizonCulling() (the flights-layer
|
||||
// EllipsoidalOccluder pattern), not by the depth test.
|
||||
disableDepthTestDistance: Number.POSITIVE_INFINITY,
|
||||
scaleByDistance: new Cesium.NearFarScalar(350, 1.25, 4_000_000, 0.42),
|
||||
});
|
||||
|
||||
const record = {
|
||||
camera,
|
||||
position,
|
||||
billboard,
|
||||
coverageEntities: [],
|
||||
projection: null,
|
||||
// Task 5 (height-datum fix): regime-aware ground resolution state.
|
||||
@@ -199,19 +315,17 @@ export function createLifecycle({
|
||||
viewshedColors: viewshedColors(
|
||||
cameraHue(hueIndexById.get(camera.id) ?? 0),
|
||||
),
|
||||
viewshedPrimitive: null,
|
||||
viewshedVolume: null,
|
||||
viewshedActiveTint: false,
|
||||
};
|
||||
layerState._records.push(record);
|
||||
layerState._recordById.set(camera.id, record);
|
||||
parts.rendering.addCameraIcon(record);
|
||||
}
|
||||
|
||||
layerState._count = layerState._records.length;
|
||||
if (layerState._records.length > 0) {
|
||||
// Projection runtime + first frame fetch are deferred to enable() so
|
||||
// initializing the catalog stays render-cheap.
|
||||
layerState._activeCameraId = layerState._records[0].camera.id;
|
||||
}
|
||||
// No camera is picked here: enable() opens on the one nearest the
|
||||
// viewer, unless restored params selected one first.
|
||||
|
||||
// Task 5: if the prior batch lost init's bounded race, apply it post-hoc
|
||||
// when it lands (pure recomputes — applyLateGroundPriors guards against
|
||||
@@ -241,41 +355,59 @@ export function createLifecycle({
|
||||
}
|
||||
|
||||
// Field-test fix (2026-07-06): horizon-cull on camera settle (pairs with
|
||||
// the billboards' always-on-top depth setting) + one initial pass so the
|
||||
// the icons' always-on-top drawing) + one initial pass so the
|
||||
// first paint is already culled.
|
||||
if (!layerState._horizonCullListener) {
|
||||
// Ambient cards piggyback the same settle event: moveEnd-driven
|
||||
// reselection only, never per frame (refreshAmbientCards no-ops while
|
||||
// the layer is disabled).
|
||||
layerState._horizonCullListener = () => {
|
||||
layerState._cameraMoving = false;
|
||||
parts.rendering.refreshHorizonCulling();
|
||||
parts.cards.refreshAmbientCards();
|
||||
};
|
||||
layerState._viewer.camera.moveEnd.addEventListener(
|
||||
layerState._horizonCullListener,
|
||||
);
|
||||
attachViewListeners();
|
||||
// A resize or rotation changes what is on screen without moving the
|
||||
// camera.
|
||||
const canvas = canvasOf(layerState._viewer);
|
||||
if (layerState._viewResizeCanvas !== canvas) {
|
||||
// A re-init against a new viewer observes its canvas instead.
|
||||
layerState._viewResizeObserver?.disconnect();
|
||||
layerState._viewResizeObserver = null;
|
||||
layerState._viewResizeCanvas = null;
|
||||
}
|
||||
if (!layerState._moveStartListener) {
|
||||
// Item B: hover picking pauses while the camera is in motion.
|
||||
layerState._moveStartListener = () => {
|
||||
layerState._cameraMoving = true;
|
||||
};
|
||||
layerState._viewer.camera.moveStart.addEventListener(
|
||||
layerState._moveStartListener,
|
||||
);
|
||||
if (
|
||||
!layerState._viewResizeObserver &&
|
||||
typeof ResizeObserver === 'function' &&
|
||||
canvas
|
||||
) {
|
||||
let frame = 0;
|
||||
layerState._viewResizeObserver = new ResizeObserver(() => {
|
||||
if (frame || !layerState._enabled) return;
|
||||
frame = requestAnimationFrame(() => {
|
||||
frame = 0;
|
||||
if (layerState._enabled) settleView();
|
||||
});
|
||||
});
|
||||
layerState._viewResizeObserver.observe(canvas);
|
||||
layerState._viewResizeCanvas = canvas;
|
||||
}
|
||||
parts.rendering.refreshHorizonCulling();
|
||||
|
||||
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
|
||||
layerState._viewer.scene.canvas,
|
||||
);
|
||||
parts.selection.bindCctvWorldClickGesture(
|
||||
layerState._clickHandler,
|
||||
(click) => {
|
||||
const input = inputFor(layerState._viewer);
|
||||
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
|
||||
input,
|
||||
(event) => {
|
||||
if (!layerState._enabled) return;
|
||||
const picked = layerState._viewer.scene.pick(click.position);
|
||||
const cameraId = parts.selection.extractPickedCameraId(picked);
|
||||
const picked = event.topHit;
|
||||
// The card or label painted on top takes the click, read once per
|
||||
// click so every layer agrees: a live card of ours acts whatever
|
||||
// is drawn under it; another layer's is that layer's click.
|
||||
const top = clickCard?.(event) ?? null;
|
||||
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
|
||||
if (top) {
|
||||
// A card of ours that is going away is still not the scene.
|
||||
if (layerState._recordById.has(top.entryId))
|
||||
activateCctvCameraFromWorldClick(
|
||||
top.entryId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const cameraId = parts.selection.extractPickedCameraId(
|
||||
event.drawHit ?? null,
|
||||
);
|
||||
if (cameraId) {
|
||||
activateCctvCameraFromWorldClick(
|
||||
cameraId,
|
||||
@@ -283,29 +415,11 @@ export function createLifecycle({
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Any identified scene object owns this click even if its layer does not
|
||||
// register a shared pick predicate. This keeps selectable siblings ahead
|
||||
// of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
|
||||
// remain eligible for true empty-space deselection.
|
||||
const pickedId = resolvePickId(picked);
|
||||
if (pickedId !== null) return;
|
||||
// Item A (owner round 2): the scene pick found no camera — try the
|
||||
// painted ambient cards. The cards canvas is pointer-events:none (this
|
||||
// handler owns the events), so a click landing on a card's rect selects
|
||||
// its camera exactly like a click on the icon. Cesium click positions
|
||||
// and the recorded rects are both CSS px — direct comparison.
|
||||
const cardId = layerState._cctvOverlayHost.hitTest(
|
||||
click.position.x,
|
||||
click.position.y,
|
||||
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
|
||||
)?.entryId;
|
||||
if (cardId && layerState._recordById.has(cardId)) {
|
||||
activateCctvCameraFromWorldClick(
|
||||
cardId,
|
||||
parts.selection.setActiveCamera,
|
||||
);
|
||||
return;
|
||||
}
|
||||
// Any identified scene object owns this click even if its layer
|
||||
// does not register a shared pick predicate. This keeps selectable
|
||||
// siblings ahead of the CCTV selection while ID-less globe, terrain
|
||||
// and tile surfaces remain eligible for empty-space deselection.
|
||||
if (resolvePickId(picked) !== null) return;
|
||||
if (
|
||||
parts.selection.cctvEmptyClickDeselects(picked, {
|
||||
activeCameraId: layerState._activeCameraId,
|
||||
@@ -315,19 +429,25 @@ export function createLifecycle({
|
||||
parts.selection.deactivateActiveCamera();
|
||||
}
|
||||
},
|
||||
{
|
||||
// Item B: hover summons a card on a cardless camera icon. The gesture
|
||||
// classifier owns MOUSE_MOVE too, so chain hover work through its seam
|
||||
// instead of replacing the travel accumulator's handler.
|
||||
onMouseMove: (movement) =>
|
||||
parts.hover.handleHoverMove(movement?.endPosition),
|
||||
},
|
||||
);
|
||||
// Item B: hover summons a card on a cardless camera icon.
|
||||
const unsubscribeHover = input.onPointer('move', (movement) =>
|
||||
parts.hover.handleHoverMove(movement?.endPosition),
|
||||
);
|
||||
layerState._clickSubscription = () => {
|
||||
unsubscribeClick();
|
||||
unsubscribeHover();
|
||||
};
|
||||
|
||||
await parts.health.syncHealthState(true);
|
||||
// Health ranks crowded cells: thin again now that it has arrived (a
|
||||
// no-op unless enable() ran while health was loading).
|
||||
if (parts.rendering.refreshHorizonCulling()) {
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
parts.cards.refreshAmbientCards();
|
||||
}
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
parts.presentation.notifyListeners();
|
||||
restoreSpriteOrder(layerState._viewer);
|
||||
console.log('[Data:CCTV] Initialized with', layerState._count, 'cameras');
|
||||
},
|
||||
|
||||
@@ -346,7 +466,7 @@ export function createLifecycle({
|
||||
)
|
||||
services.credits?.showOsmCredit?.(layerState._viewer, 'cctv');
|
||||
layerState._lastUpdate = Date.now();
|
||||
// Pick-ownership (H2): camera billboards use the camera id directly;
|
||||
// Pick-ownership (H2): camera icons use the camera id directly;
|
||||
// coverage polyline entities use `cctv-<cameraId>-<role>` entity ids.
|
||||
registerPickOwner('cctv', (pickedId) => {
|
||||
if (layerState._recordById.has(pickedId)) return true;
|
||||
@@ -362,14 +482,18 @@ export function createLifecycle({
|
||||
return Boolean(coverage && layerState._recordById.has(coverage[1]));
|
||||
});
|
||||
if (!layerState._activeCameraId && layerState._records.length) {
|
||||
layerState._activeCameraId = layerState._records[0].camera.id;
|
||||
layerState._activeCameraId = parts.navigation.openingCameraId();
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = true;
|
||||
}
|
||||
const activeRecord = parts.selection.getActiveRecord();
|
||||
if (activeRecord) {
|
||||
parts.projection.ensureProjectionRuntime(activeRecord);
|
||||
parts.frames.refreshProjectionImage(activeRecord, true);
|
||||
}
|
||||
parts.rendering.refreshHorizonCulling();
|
||||
// Re-enabled mid-flight: moveStart has already fired.
|
||||
if (layerState._cameraMoving) startViewMotionTimer();
|
||||
parts.geometryQueue.startGeometryLoadQueue();
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
parts.projection.startProjectionLoop();
|
||||
@@ -386,7 +510,6 @@ export function createLifecycle({
|
||||
parts.cards.startCardFrameLoop();
|
||||
parts.cards.refreshAmbientCards();
|
||||
parts.presentation.notifyListeners();
|
||||
restoreSpriteOrder(layerState._viewer);
|
||||
},
|
||||
|
||||
/** Disables the layer: hides entities, stops the projection loop and load queue. */
|
||||
@@ -402,19 +525,23 @@ export function createLifecycle({
|
||||
layerState._removeFocusAppearListener = null;
|
||||
parts.projection.stopProjectionLoop();
|
||||
parts.geometryQueue.stopGeometryLoadQueue();
|
||||
stopViewMotionTimer();
|
||||
// Ambient cards tear down COMPLETELY on disable (owner design point 6):
|
||||
// source entries, pacer timer, in-flight handlers, and caches.
|
||||
parts.cards.teardownAmbientCards();
|
||||
parts.rendering.hideCctvVisuals();
|
||||
// Nothing is in view while the layer is off.
|
||||
layerState._viewRecords = [];
|
||||
layerState._cameraIndexCache = null;
|
||||
parts.presentation.notifyListeners();
|
||||
},
|
||||
|
||||
/**
|
||||
* Tears down the layer: destroys click handler, projection loop, coverage
|
||||
* entities, billboards, and clears all runtime state and subscribers.
|
||||
* @param {Cesium.Viewer} [viewer] - Viewer instance (falls back to stored ref).
|
||||
* entities, icons, and clears all runtime state and subscribers. It
|
||||
* releases what init attached, whichever viewer it is handed.
|
||||
*/
|
||||
destroy(viewer) {
|
||||
destroy() {
|
||||
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
|
||||
layerState._sourceAbort?.abort();
|
||||
if (typeof document !== 'undefined')
|
||||
@@ -430,50 +557,40 @@ export function createLifecycle({
|
||||
);
|
||||
layerState._mapStackListener = null;
|
||||
}
|
||||
const teardownViewer = viewer || layerState._viewer;
|
||||
if (layerState._horizonCullListener && teardownViewer?.camera?.moveEnd) {
|
||||
teardownViewer.camera.moveEnd.removeEventListener(
|
||||
layerState._horizonCullListener,
|
||||
);
|
||||
layerState._horizonCullListener = null;
|
||||
}
|
||||
if (layerState._moveStartListener && teardownViewer?.camera?.moveStart) {
|
||||
teardownViewer.camera.moveStart.removeEventListener(
|
||||
layerState._moveStartListener,
|
||||
);
|
||||
layerState._moveStartListener = null;
|
||||
}
|
||||
detachViewListeners();
|
||||
layerState._viewResizeObserver?.disconnect();
|
||||
layerState._viewResizeObserver = null;
|
||||
layerState._viewResizeCanvas = null;
|
||||
if (layerState._gizmo) {
|
||||
layerState._gizmo.destroy();
|
||||
layerState._gizmo = null;
|
||||
}
|
||||
layerState._calibrationMode = false;
|
||||
releaseContinuousRender('cctv-adjust');
|
||||
if (layerState._clickHandler) {
|
||||
layerState._clickHandler.destroy();
|
||||
layerState._clickHandler = null;
|
||||
}
|
||||
if (teardownViewer?.scene?.screenSpaceCameraController) {
|
||||
teardownViewer.scene.screenSpaceCameraController.enableInputs = true;
|
||||
}
|
||||
layerState._clickSubscription?.();
|
||||
layerState._clickSubscription = null;
|
||||
parts.projection.stopProjectionLoop();
|
||||
parts.geometryQueue.stopGeometryLoadQueue();
|
||||
parts.cards.teardownAmbientCards();
|
||||
parts.geometry.destroyCoverageEntities();
|
||||
if (layerState._billboards && teardownViewer) {
|
||||
teardownViewer.scene.primitives.remove(layerState._billboards);
|
||||
layerState._billboards = null;
|
||||
}
|
||||
parts.rendering.destroyCameraIcons();
|
||||
parts.drawSets.dispose();
|
||||
clearRuntimeState();
|
||||
layerState._viewer = null;
|
||||
layerState._enabled = false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
// Clear existing subscribers rather than replacing the Set —
|
||||
// replacing would silently orphan any unsubscribe() closures
|
||||
layerState._listeners.clear();
|
||||
},
|
||||
};
|
||||
|
||||
return { clearRuntimeState, methods };
|
||||
return {
|
||||
clearRuntimeState,
|
||||
attachViewListeners,
|
||||
detachViewListeners,
|
||||
methods,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createLifecycle } from './lifecycle.js';
|
||||
import { createSelection } from './selection.js';
|
||||
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
|
||||
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
|
||||
import * as picking from '../../data/pickRegistry.js';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
|
||||
function viewerWithCamera() {
|
||||
const camera = fakeCameraPort();
|
||||
const viewer = {};
|
||||
bindRenderer(viewer, { camera: camera.port });
|
||||
return { viewer, camera };
|
||||
}
|
||||
|
||||
function lifecycleFor(state) {
|
||||
const passes = [];
|
||||
const lifecycle = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
sprites: {},
|
||||
activation: {},
|
||||
picking: {},
|
||||
focus: {},
|
||||
render: {},
|
||||
},
|
||||
parts: {
|
||||
rendering: {
|
||||
refreshHorizonCulling: () => {
|
||||
passes.push('view');
|
||||
return false;
|
||||
},
|
||||
},
|
||||
geometryQueue: { enqueueViewGeometry() {} },
|
||||
cards: { refreshAmbientCards() {} },
|
||||
presentation: { notifyListeners() {} },
|
||||
navigation: { reopenNearestCamera() {} },
|
||||
},
|
||||
});
|
||||
return { lifecycle, passes };
|
||||
}
|
||||
|
||||
test('the view listeners follow the camera port and let go on teardown', () => {
|
||||
const first = viewerWithCamera();
|
||||
const state = { _viewer: first.viewer, _enabled: false };
|
||||
const { lifecycle, passes } = lifecycleFor(state);
|
||||
const counts = (camera) => [
|
||||
camera.listenerCount('moveStart'),
|
||||
camera.listenerCount('moveEnd'),
|
||||
];
|
||||
|
||||
lifecycle.attachViewListeners();
|
||||
assert.deepEqual(counts(first.camera), [1, 1]);
|
||||
first.camera.emit('moveStart');
|
||||
assert.equal(state._cameraMoving, true, 'hover pauses while moving');
|
||||
first.camera.emit('moveEnd');
|
||||
assert.equal(state._cameraMoving, false);
|
||||
assert.deepEqual(passes, ['view'], 'a settled move reruns the view pass');
|
||||
|
||||
// A re-init on the same viewer keeps its listeners.
|
||||
lifecycle.attachViewListeners();
|
||||
assert.deepEqual(counts(first.camera), [1, 1]);
|
||||
|
||||
// One on a new viewer moves them to its camera.
|
||||
const second = viewerWithCamera();
|
||||
state._viewer = second.viewer;
|
||||
first.camera.emit('moveStart');
|
||||
lifecycle.attachViewListeners();
|
||||
assert.equal(state._cameraMoving, false, 'the old move is forgotten');
|
||||
assert.deepEqual(counts(first.camera), [0, 0]);
|
||||
assert.deepEqual(counts(second.camera), [1, 1]);
|
||||
|
||||
lifecycle.detachViewListeners();
|
||||
assert.deepEqual(counts(second.camera), [0, 0]);
|
||||
assert.equal(state._viewListenerCamera, null);
|
||||
});
|
||||
|
||||
/** A part whose members are `own`'s, and any other a function that does
|
||||
* nothing. */
|
||||
const inert = (own = {}) =>
|
||||
new Proxy(own, {
|
||||
get: (target, name) => (name in target ? target[name] : () => {}),
|
||||
});
|
||||
|
||||
test("a click on a mission label over a camera's card never turns that camera on, and keeps the active one", async (t) => {
|
||||
const { viewer } = viewerWithCamera();
|
||||
viewer.scene = { canvas: {}, pick: () => null };
|
||||
// The card of camera `cam-1` lies under every click, under the label.
|
||||
const fake = fakeInputUnderLabel(viewer, {
|
||||
beneath: () => ({ sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }),
|
||||
});
|
||||
t.after(() => fake.destroy());
|
||||
const activated = [];
|
||||
const deactivated = [];
|
||||
const state = {};
|
||||
const lifecycle = createLifecycle({
|
||||
state,
|
||||
services: {
|
||||
activation: {
|
||||
activateCctvCameraFromWorldClick: (id) => activated.push(id),
|
||||
},
|
||||
picking,
|
||||
focus: {},
|
||||
render: {},
|
||||
},
|
||||
parts: {
|
||||
calibration: { loadCalibrationStore: () => new Map() },
|
||||
catalog: {
|
||||
loadCameraSources: async () => [],
|
||||
buildCatalogFromSources: () => [],
|
||||
seedCatalog: () => [],
|
||||
},
|
||||
ground: {
|
||||
resolveGroundPriors: async () => [],
|
||||
currentSurfaceRegime: () => null,
|
||||
},
|
||||
rendering: inert({ refreshHorizonCulling: () => false }),
|
||||
health: { syncHealthState: async () => {} },
|
||||
geometryQueue: inert(),
|
||||
cards: inert(),
|
||||
projection: inert(),
|
||||
presentation: inert(),
|
||||
navigation: inert(),
|
||||
hover: inert(),
|
||||
selection: {
|
||||
// The camera's own gate takes only clean clicks; these are.
|
||||
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
|
||||
extractPickedCameraId: () => null,
|
||||
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
|
||||
Boolean(activeCameraId) && picking.resolvePickId(picked) === null,
|
||||
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
|
||||
},
|
||||
},
|
||||
});
|
||||
// Init's bounded wait for ground heights never runs out here: they are in.
|
||||
t.mock.timers.enable({ apis: ['setTimeout'] });
|
||||
await lifecycle.methods.init(viewer);
|
||||
t.after(() => state._clickSubscription?.());
|
||||
state._enabled = true;
|
||||
state._activeCameraId = 'cam-0';
|
||||
state._recordById.set('cam-1', {});
|
||||
|
||||
fake.label.over = true;
|
||||
fake.click();
|
||||
assert.deepEqual(activated, [], 'the camera under the label stays off');
|
||||
assert.deepEqual(deactivated, [], 'the active camera stays on');
|
||||
|
||||
// Off the label, a click on the card turns its camera on.
|
||||
fake.label.over = false;
|
||||
fake.click();
|
||||
assert.deepEqual(activated, ['cam-1']);
|
||||
});
|
||||
|
||||
test('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
|
||||
const noop = () => {};
|
||||
const { viewer } = viewerWithCamera();
|
||||
let picked = null;
|
||||
viewer.scene = {
|
||||
canvas: {},
|
||||
pick: () => (picked ? { id: picked } : undefined),
|
||||
drillPick: () => drilled.map((id) => ({ id })),
|
||||
};
|
||||
let drilled = [];
|
||||
const input = fakeInput(viewer);
|
||||
// An aircraft layer that runs before ours and tracks the plane it was
|
||||
// clicked on, standing aside under another layer's card.
|
||||
let tracked = null;
|
||||
input.input.onClick((event) => {
|
||||
if (picking.isUnderOtherCard(event)) return;
|
||||
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
|
||||
});
|
||||
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
|
||||
const foreignCard = {
|
||||
sourceId: 'earthquake-card',
|
||||
entryId: 'earthquake-card:qa',
|
||||
};
|
||||
let painted = [];
|
||||
const actions = [];
|
||||
// The card on top at a click, as the host answers the pick registry.
|
||||
picking.setClickCardHitTest(() => painted[0] ?? null);
|
||||
const state = {
|
||||
_cctvOverlayHost: {
|
||||
hitTest: (_x, _y, options = {}) =>
|
||||
painted.find(
|
||||
(hit) => !options.sourceId || hit.sourceId === options.sourceId,
|
||||
) ?? null,
|
||||
},
|
||||
};
|
||||
const parts = {
|
||||
calibration: { loadCalibrationStore: () => new Map() },
|
||||
catalog: {
|
||||
loadCameraSources: async () => [],
|
||||
buildCatalogFromSources: () => [],
|
||||
seedCatalog: () => [],
|
||||
},
|
||||
ground: {
|
||||
resolveGroundPriors: async () => [],
|
||||
currentSurfaceRegime: () => 'terrain-globe',
|
||||
},
|
||||
cards: { teardownAmbientCards: noop },
|
||||
projection: { clearProjectionOverlay: noop },
|
||||
geometryQueue: { stopGeometryLoadQueue: noop },
|
||||
rendering: {
|
||||
createCameraIcons: noop,
|
||||
refreshHorizonCulling: () => false,
|
||||
refreshCoverageStyles: noop,
|
||||
extractPickedCameraId: (hit) =>
|
||||
hit?.set === 'cctv:fixture' ? hit.id : null,
|
||||
},
|
||||
hover: { handleHoverMove: noop },
|
||||
health: { syncHealthState: async () => {} },
|
||||
presentation: { notifyListeners: noop },
|
||||
};
|
||||
const services = {
|
||||
sprites: {},
|
||||
focus: { onFocusTargetAppear: () => noop },
|
||||
render: { releaseContinuousRender: noop },
|
||||
picking,
|
||||
activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) },
|
||||
};
|
||||
parts.selection = createSelection({ state, services, parts });
|
||||
parts.selection.deactivateActiveCamera = () => actions.push('clear');
|
||||
const lifecycle = createLifecycle({ state, services, parts });
|
||||
t.after(() => {
|
||||
state._clickSubscription?.();
|
||||
lifecycle.detachViewListeners();
|
||||
input.destroy();
|
||||
picking.setClickCardHitTest(null);
|
||||
picking.unregisterPickOwner('area-control');
|
||||
picking.unregisterPickOwner('test-trails');
|
||||
picking.unregisterPickOwner('test-planes');
|
||||
picking.unregisterPickOwner('test-tracking');
|
||||
picking.unregisterPickOwner('test-exact');
|
||||
});
|
||||
await lifecycle.methods.init(viewer);
|
||||
state._enabled = true;
|
||||
state._activeCameraId = 'cam-1';
|
||||
state._recordById.set('cam-1', { camera: { id: 'cam-1' } });
|
||||
const click = (hit, cards, expected) => {
|
||||
picked = hit;
|
||||
painted = cards;
|
||||
actions.length = 0;
|
||||
input.tap();
|
||||
assert.deepEqual(actions, expected, JSON.stringify({ hit, cards }));
|
||||
};
|
||||
const drone = {
|
||||
set: 'drone-airspace:1:fills',
|
||||
id: 'drone-airspace:zone:0',
|
||||
surface: false,
|
||||
};
|
||||
const perimeter = {
|
||||
set: 'fire-perimeters:1:lines',
|
||||
id: 'fire-perimeter:incident:0',
|
||||
surface: false,
|
||||
};
|
||||
const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false };
|
||||
const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false };
|
||||
const launch = {
|
||||
set: 'launches:1:markers',
|
||||
id: 'rocket-x:1',
|
||||
surface: false,
|
||||
};
|
||||
const backgrounds = [drone, perimeter, quake, cable, launch];
|
||||
for (const area of backgrounds) {
|
||||
click(area, [ownCard], ['cam-1']);
|
||||
click(area, [], []);
|
||||
click(area, [foreignCard, ownCard], []);
|
||||
}
|
||||
// The live top card acts over anything drawn under it; with no card an
|
||||
// identified object is not empty map.
|
||||
for (const hit of [
|
||||
{ set: 'flights:1', id: 'aircraft', surface: false },
|
||||
{ set: '', id: 'unregistered-local-entity', surface: false },
|
||||
{ ...drone, set: 'unrelated:1:fills' },
|
||||
{ ...drone, id: 'unregistered-local-entity' },
|
||||
]) {
|
||||
click(hit, [ownCard], ['cam-1']);
|
||||
click(hit, [], []);
|
||||
}
|
||||
// A trail under the live top card: the card keeps the click, and with no
|
||||
// card the owned pick is not empty map.
|
||||
const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false };
|
||||
picking.registerPickOwner('test-trails', (id) => id === trail.id);
|
||||
click(trail, [ownCard], ['cam-1']);
|
||||
click(trail, [], []);
|
||||
click(trail, [foreignCard, ownCard], []);
|
||||
picking.unregisterPickOwner('test-trails');
|
||||
// A coarse tap whose touch contact is an aircraft (a layer that acts on
|
||||
// nearby contacts) under a live CCTV card is the card's.
|
||||
const previousMatch = globalThis.matchMedia;
|
||||
const restoreMatch = () => {
|
||||
if (previousMatch) globalThis.matchMedia = previousMatch;
|
||||
else delete globalThis.matchMedia;
|
||||
};
|
||||
// Restored below for the fine-pointer clicks that follow; here too, so a
|
||||
// failing assertion cannot leave the coarse pointer for later tests.
|
||||
t.after(restoreMatch);
|
||||
globalThis.matchMedia = () => ({ matches: true });
|
||||
picking.registerPickOwner('test-planes', (id) => id === 'plane:1');
|
||||
drilled = ['plane:1'];
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
// With no card, the bare tap near the aircraft still deselects.
|
||||
click(null, [], ['clear']);
|
||||
// A contact whose layer acts only on exact hits leaves the card its tap.
|
||||
picking.registerPickOwner('test-exact', (id) => id === 'exact:1');
|
||||
drilled = ['exact:1'];
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
picking.unregisterPickOwner('test-exact');
|
||||
drilled = [];
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
picking.unregisterPickOwner('test-planes');
|
||||
restoreMatch();
|
||||
// The live card over an aircraft takes the click; the aircraft layer,
|
||||
// run first, stands aside and does not track.
|
||||
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
|
||||
click(
|
||||
{ set: 'flights:1', id: 'plane:9', surface: false },
|
||||
[ownCard],
|
||||
['cam-1'],
|
||||
);
|
||||
assert.equal(tracked, null, 'the aircraft did not track');
|
||||
picking.unregisterPickOwner('test-tracking');
|
||||
picking.registerPickOwner('area-control', (id) => id === drone.id);
|
||||
click(drone, [ownCard], ['cam-1']);
|
||||
picking.unregisterPickOwner('area-control');
|
||||
click(null, [foreignCard, ownCard], []);
|
||||
click(null, [ownCard], ['cam-1']);
|
||||
click(null, [], ['clear']);
|
||||
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
|
||||
// A card of ours that is going away is still not the scene under it: no
|
||||
// camera beneath it activates, and nothing clears.
|
||||
const staleCard = { ...ownCard, entryId: 'stale-camera' };
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
|
||||
click(null, [staleCard], []);
|
||||
// A camera icon under another layer's card is that card's click.
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
|
||||
click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
|
||||
});
|
||||
+54
-64
@@ -1,4 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { cross, negate, toDegrees, toRadians } from '../../geo/vector.js';
|
||||
import { fromAxes } from '../../geo/quaternion.js';
|
||||
import { findCamera } from '../../render/rendererOf.js';
|
||||
import { greatCircleKm } from '../../geoDistance.js';
|
||||
import { staticFrameRefreshMs } from '../../data/cctvLod.js';
|
||||
import { frameFetchDue, cardFetchPolicy } from '../../data/cctvCards.js';
|
||||
@@ -14,7 +16,7 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
*/
|
||||
|
||||
function toRad(deg) {
|
||||
return Cesium.Math.toRadians(deg);
|
||||
return toRadians(deg);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -96,6 +98,19 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
return feedType === 'mp4' || feedType === 'hls' || feedType === 'webm';
|
||||
}
|
||||
|
||||
/** A browser-only source still counts as live-capable for map icon/LOD policy. */
|
||||
function isVideoFeedCamera(camera) {
|
||||
return (
|
||||
isVideoFeedType(normalizeFeedType(camera?.feedType)) ||
|
||||
Boolean(camera?.browserMediaUrl)
|
||||
);
|
||||
}
|
||||
|
||||
/** Québec source pages and browser-played MP4s use the DOM overlay path. */
|
||||
function isBrowserOverlayCamera(camera) {
|
||||
return String(camera?.sourceKind || '').startsWith('quebec-');
|
||||
}
|
||||
|
||||
/**
|
||||
* Coerces a value to a finite number or returns the fallback.
|
||||
*
|
||||
@@ -295,8 +310,8 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
const lon2 = lon1 + Math.atan2(y, x);
|
||||
|
||||
return {
|
||||
lat: Cesium.Math.toDegrees(lat2),
|
||||
lon: Cesium.Math.toDegrees(lon2),
|
||||
lat: toDegrees(lat2),
|
||||
lon: toDegrees(lon2),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -332,12 +347,22 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
* @returns {string} Grid key in the form "zoomBucket:latGrid:lonGrid".
|
||||
*/
|
||||
|
||||
/**
|
||||
* The eye's pose from the camera port, or null when there is no camera or
|
||||
* the eye has no geographic position (the earth's centre).
|
||||
* @returns {object|null}
|
||||
*/
|
||||
|
||||
function eyePose() {
|
||||
const pose = findCamera(layerState._viewer)?.pose();
|
||||
return Number.isFinite(pose?.lat) ? pose : null;
|
||||
}
|
||||
|
||||
function currentViewContext() {
|
||||
const carto = layerState._viewer?.camera?.positionCartographic;
|
||||
if (!carto) return 'none';
|
||||
const lat = Cesium.Math.toDegrees(carto.latitude);
|
||||
const lon = Cesium.Math.toDegrees(carto.longitude);
|
||||
const alt = carto.height || 0;
|
||||
const pose = eyePose();
|
||||
if (!pose) return 'none';
|
||||
const { lat, lon } = pose;
|
||||
const alt = pose.height || 0;
|
||||
const zoomBucket =
|
||||
alt < 1500
|
||||
? 'street'
|
||||
@@ -358,43 +383,13 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
}
|
||||
|
||||
/**
|
||||
* Reports whether the active Google Photorealistic 3D Tileset (if any) has
|
||||
* finished loading the tiles in view. Shared mesh-floor sampling is gated on
|
||||
* this so a one-shot cell never bakes in a miss from still-streaming tiles.
|
||||
* Discovers + caches the tileset lazily from scene
|
||||
* primitives (the CCTV module holds only a `_viewer` reference). When no
|
||||
* tileset is present (OSM fallback) this returns true so ground sampling is
|
||||
* not permanently blocked.
|
||||
*
|
||||
* Task 5 (review correction, spec §2): a HIDDEN tileset (`show === false`,
|
||||
* i.e. a globe stack is active) must NOT report ready — Cesium 1.138's
|
||||
* the shared sampler can only inspect *visible* 3D tilesets, so a sample taken
|
||||
* against the hidden Google tileset would silently miss.
|
||||
*
|
||||
* @returns {boolean} True when tiles are loaded AND visible (or no tileset
|
||||
* exists to wait on).
|
||||
* Whether the photoreal tiles in view have finished loading; the rendering
|
||||
* part, which reads the scene, answers.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
|
||||
function projectionTilesReady() {
|
||||
if (
|
||||
!layerState._activeTileset ||
|
||||
layerState._activeTileset.isDestroyed?.()
|
||||
) {
|
||||
layerState._activeTileset = null;
|
||||
const primitives = layerState._viewer?.scene?.primitives;
|
||||
if (primitives && typeof primitives.get === 'function') {
|
||||
for (let i = 0; i < primitives.length; i++) {
|
||||
const p = primitives.get(i);
|
||||
if (p instanceof Cesium.Cesium3DTileset && !p.isDestroyed?.()) {
|
||||
layerState._activeTileset = p;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (!layerState._activeTileset) return true;
|
||||
if (layerState._activeTileset.show === false) return false;
|
||||
return layerState._activeTileset.tilesLoaded === true;
|
||||
return parts.rendering.projectionTilesReady();
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -405,30 +400,17 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
* frame-up, so the 16:9 texture maps upright and unmirrored. Static geometry —
|
||||
* computed only on slider/save/activation, never per frame (§2b).
|
||||
* @param {Object} camera - Camera pose.
|
||||
* @param {Cesium.Cartesian3} capCenterPos - Plane center in ECEF.
|
||||
* @returns {Cesium.Quaternion}
|
||||
* @param {{x: number, y: number, z: number}} capCenterPos - Plane center in ECEF.
|
||||
* @returns {{x: number, y: number, z: number, w: number}} The quaternion.
|
||||
*/
|
||||
|
||||
function planeOrientationFor(camera, capCenterPos) {
|
||||
const frame = parts.geometry.frustumFrameEcef(camera, capCenterPos);
|
||||
const right = Cesium.Cartesian3.cross(
|
||||
frame.dir,
|
||||
frame.up,
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const normal = Cesium.Cartesian3.negate(frame.dir, new Cesium.Cartesian3());
|
||||
const m = new Cesium.Matrix3(
|
||||
right.x,
|
||||
frame.up.x,
|
||||
normal.x,
|
||||
right.y,
|
||||
frame.up.y,
|
||||
normal.y,
|
||||
right.z,
|
||||
frame.up.z,
|
||||
normal.z,
|
||||
);
|
||||
return Cesium.Quaternion.fromRotationMatrix(m);
|
||||
return fromAxes({
|
||||
x: cross(frame.dir, frame.up),
|
||||
y: frame.up,
|
||||
z: negate(frame.dir),
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -447,7 +429,12 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
|
||||
function projectionLoopIsNeeded() {
|
||||
if (!layerState._enabled || !layerState._viewer) return false;
|
||||
if (layerState._showProjection && parts.selection.getActiveRecord())
|
||||
const active = parts.selection.getActiveRecord();
|
||||
if (
|
||||
layerState._showProjection &&
|
||||
active &&
|
||||
!isBrowserOverlayCamera(active.camera)
|
||||
)
|
||||
return true;
|
||||
return focusPassIsNeeded(
|
||||
getFocusTarget(),
|
||||
@@ -546,6 +533,7 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
return cameraId !== activeCameraId || record?.activationDone !== true;
|
||||
}
|
||||
return {
|
||||
eyePose,
|
||||
toRad,
|
||||
normalizeHeading,
|
||||
clamp,
|
||||
@@ -553,6 +541,8 @@ export function createModel({ state: layerState, services, parts, source }) {
|
||||
angularDeltaAbs,
|
||||
normalizeFeedType,
|
||||
isVideoFeedType,
|
||||
isVideoFeedCamera,
|
||||
isBrowserOverlayCamera,
|
||||
safeNumber,
|
||||
headingFromId,
|
||||
quantize,
|
||||
|
||||
@@ -12,20 +12,28 @@
|
||||
* Cameras without an identified model are untouched — unknown never implies
|
||||
* anything.
|
||||
*
|
||||
* Spec records are vendored verbatim from the CCTV Camera Database
|
||||
* Specification fields are vendored from the CCTV Camera Database
|
||||
* (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) — an open dataset
|
||||
* of 28,000+ camera models transcribed from manufacturer datasheets (84% with
|
||||
* FOV, as of v2.26.0). This module vendors the records that the currently integrated public
|
||||
* of 29,000+ camera models transcribed from manufacturer datasheets (76% with
|
||||
* FOV, as of v2.29.0). This module vendors records that the integrated public
|
||||
* catalogs publish hardware for — King County WA (Cohu, Bosch AUTODOME, Axis
|
||||
* Q6135-LE), plus the Bosch AUTODOME and Axis PTZ/multisensor models that
|
||||
* appear in Sarasota County FL and Sioux Falls SD open data; packs that
|
||||
* appear in Sarasota County FL and Sioux Falls SD open data, plus the Bosch MIC
|
||||
* PTZs for the City of Amsterdam camera register proposed in #251; packs that
|
||||
* publish other hardware models can grow it, or vendor the full extract.
|
||||
*
|
||||
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
|
||||
* night vision) — never endpoints, stream paths, or access/config data.
|
||||
*/
|
||||
|
||||
/** Verbatim records from the dataset's model-enrichment extract (v2.26.0). */
|
||||
/**
|
||||
* Records from the dataset's model-enrichment extract: v2.26.0, plus the Bosch
|
||||
* MIC records from v2.29.0 with titles shortened to model codes.
|
||||
* A Bosch MIC order code ends in a colour letter (B, G, W; registries write
|
||||
* `x`) on one shared datasheet. The colours are aliases of one record whose
|
||||
* `model` leaves the letter out, so the HUD never names a variant the source
|
||||
* did not.
|
||||
*/
|
||||
const RECORDS = [
|
||||
{
|
||||
id: 'axis-q6135-le',
|
||||
@@ -264,6 +272,67 @@ const RECORDS = [
|
||||
autotracking: true,
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7130-pb4',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7130-P_4',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7130-pb4/',
|
||||
aliases: [
|
||||
'MIC IP starlight 7000 HD',
|
||||
'MIC-7130-PB4',
|
||||
'MIC-7130-PG4',
|
||||
'MIC-7130-PW4',
|
||||
'MIC-7130-Px4',
|
||||
],
|
||||
fov_deg: '2.1-59',
|
||||
resolution: { mp: 1, w: 1280, h: 720, label: '720p' },
|
||||
ptz: true,
|
||||
autotracking: true,
|
||||
varifocal: true,
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7502-z30b',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7502-Z30',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7502-z30b/',
|
||||
aliases: [
|
||||
'MIC-7502-Z30B',
|
||||
'MIC-7502-Z30G',
|
||||
'MIC-7502-Z30W',
|
||||
'MIC-7502-Z30x',
|
||||
],
|
||||
fov_deg: '2.3-63.7',
|
||||
resolution: { mp: 2.13, w: 1920, h: 1080, label: '1080p' },
|
||||
ptz: true,
|
||||
autotracking: true,
|
||||
varifocal: true,
|
||||
night_vision: { type: 'color' },
|
||||
environment: ['outdoor'],
|
||||
},
|
||||
{
|
||||
id: 'bosch-mic-7522-z30b',
|
||||
brand: 'Bosch',
|
||||
model: 'MIC-7522-Z30',
|
||||
type: 'ptz',
|
||||
url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/',
|
||||
aliases: [
|
||||
'MIC-7522-Z30B',
|
||||
'MIC-7522-Z30G',
|
||||
'MIC-7522-Z30W',
|
||||
'MIC-7522-Z30x',
|
||||
],
|
||||
fov_deg: '2.1-58.3',
|
||||
// i18n-ignore: datasheet label
|
||||
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' },
|
||||
ptz: true,
|
||||
varifocal: true,
|
||||
night_vision: { type: 'color' },
|
||||
environment: ['outdoor'],
|
||||
ndaa_compliant: true,
|
||||
},
|
||||
{
|
||||
id: 'cohu-3920-idome',
|
||||
brand: 'Cohu',
|
||||
@@ -431,7 +500,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => {
|
||||
* guesses).
|
||||
* @param {string} model - Hardware model as named by a source pack or seed.
|
||||
* @param {string} [manufacturer] - The source's manufacturer, when published.
|
||||
* @returns {Object|null} The verbatim spec record, or null when unknown.
|
||||
* @returns {Object|null} The matched spec record, or null when unknown.
|
||||
*/
|
||||
export function lookupModelSpec(model, manufacturer) {
|
||||
const query = words(model).map(stripVariantSuffix);
|
||||
|
||||
@@ -245,6 +245,95 @@ test('King County snapshot model strings still resolve', () => {
|
||||
);
|
||||
});
|
||||
|
||||
test('Amsterdam camera register model strings resolve', () => {
|
||||
// The register writes the Bosch MIC colour letter as `x`.
|
||||
assert.equal(
|
||||
lookupModelSpec('Bosch MIC-7522-Z30x')?.id,
|
||||
'bosch-mic-7522-z30b',
|
||||
);
|
||||
assert.equal(
|
||||
lookupModelSpec('Bosch MIC-7502-Z30x')?.id,
|
||||
'bosch-mic-7502-z30b',
|
||||
);
|
||||
assert.equal(lookupModelSpec('Bosch MIC-7130-Px4')?.id, 'bosch-mic-7130-pb4');
|
||||
assert.equal(lookupModelSpec('MIC-7522-Z30W')?.id, 'bosch-mic-7522-z30b');
|
||||
// Its ANPR units are not in the table: unknown, never a guess.
|
||||
assert.equal(lookupModelSpec('CSG-8800'), null);
|
||||
// The MIC and AUTODOME starlight 7000 HD (code-less names, so the brand
|
||||
// is needed) stay apart.
|
||||
assert.equal(
|
||||
lookupModelSpec('MIC IP starlight 7000 HD', 'Bosch')?.id,
|
||||
'bosch-mic-7130-pb4',
|
||||
);
|
||||
assert.equal(
|
||||
lookupModelSpec('AUTODOME IP starlight 7000 HD', 'Bosch')?.id,
|
||||
'bosch-autodome-ip-starlight-7000-hd',
|
||||
);
|
||||
// The MIC datasheets state FOV without an axis, so no horizontal range.
|
||||
assert.equal(horizontalFovRangeDeg(lookupModelSpec('MIC-7522-Z30B')), null);
|
||||
});
|
||||
|
||||
test('Bosch MIC colour aliases resolve without accepting unknown variants', () => {
|
||||
for (const [pattern, id] of [
|
||||
['MIC-7130-P?4', 'bosch-mic-7130-pb4'],
|
||||
['MIC-7502-Z30?', 'bosch-mic-7502-z30b'],
|
||||
['MIC-7522-Z30?', 'bosch-mic-7522-z30b'],
|
||||
]) {
|
||||
for (const colour of ['B', 'G', 'W', 'x']) {
|
||||
const model = pattern.replace('?', colour);
|
||||
assert.equal(lookupModelSpec(model)?.id, id, model);
|
||||
assert.equal(lookupModelSpec(`bosch ${model.toLowerCase()}`)?.id, id);
|
||||
assert.equal(lookupModelSpec(model, 'Bosch')?.id, id);
|
||||
assert.equal(lookupModelSpec(model, 'Axis'), null);
|
||||
assert.equal(lookupModelSpec(`${model}-UNKNOWN`), null);
|
||||
}
|
||||
assert.equal(lookupModelSpec(pattern.replace('?', 'R')), null);
|
||||
}
|
||||
});
|
||||
|
||||
test('Bosch MIC HUD summary never names a colour the source did not', () => {
|
||||
assert.equal(
|
||||
specSummary(lookupModelSpec('MIC-7522-Z30W')),
|
||||
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
|
||||
);
|
||||
assert.equal(
|
||||
specSummary(lookupModelSpec('Bosch MIC-7522-Z30x')),
|
||||
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
|
||||
);
|
||||
for (const pattern of ['MIC-7130-P?4', 'MIC-7502-Z30?', 'MIC-7522-Z30?']) {
|
||||
for (const colour of ['B', 'G', 'W', 'x']) {
|
||||
const spec = lookupModelSpec(pattern.replace('?', colour));
|
||||
const summary = specSummary(spec);
|
||||
for (const other of ['B', 'G', 'W', 'x']) {
|
||||
assert.ok(!summary.includes(pattern.replace('?', other)), summary);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('Bosch MIC catalog enrichment preserves estimated and explicit optics', () => {
|
||||
for (const model of [
|
||||
'Bosch MIC-7130-Px4',
|
||||
'Bosch MIC-7502-Z30x',
|
||||
'Bosch MIC-7522-Z30x',
|
||||
]) {
|
||||
for (const pose of [{}, { fovDeg: 44 }, { poseSource: 'curated' }]) {
|
||||
const [camera] = browserCatalog().buildCatalogFromSources([
|
||||
{ id: 'amsterdam-mic', lat: 52.37, lon: 4.9, model, ...pose },
|
||||
]);
|
||||
assert.ok(camera.spec, model);
|
||||
assert.equal(camera.fovDeg, pose.fovDeg ?? 74, model);
|
||||
assert.equal(camera.fovSource, undefined);
|
||||
assert.equal(camera.specFovMinDeg, undefined);
|
||||
assert.equal(camera.specFovMaxDeg, undefined);
|
||||
assert.equal(horizontalFovRangeDeg(camera.spec), null);
|
||||
assert.equal(fixedHorizontalFovDeg(camera.spec), null);
|
||||
assert.equal(specFovCapabilityToken(camera), null);
|
||||
assert.match(specSummary(camera.spec), /^Bosch MIC-.* · PTZ$/);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
test('catalog never overwrites an explicit FOV or a curated pose', () => {
|
||||
const [explicit, curated, cohu, pelco] =
|
||||
browserCatalog().buildCatalogFromSources([
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { isFollowing } from '../../data/followed.js';
|
||||
import { CCTV_FOCUS_RESULT } from './policy.js';
|
||||
import { cameraOf } from '../../render/rendererOf.js';
|
||||
|
||||
export function createNavigation({
|
||||
state: layerState,
|
||||
@@ -8,15 +9,20 @@ export function createNavigation({
|
||||
source,
|
||||
}) {
|
||||
/**
|
||||
* Finds the camera closest to the Cesium viewer's current position.
|
||||
* @returns {string|null} Camera ID of the nearest camera, or null.
|
||||
* Nearest catalog camera to a WGS84 point.
|
||||
* @param {number} lat Latitude in degrees.
|
||||
* @param {number} lon Longitude in degrees.
|
||||
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
|
||||
*/
|
||||
|
||||
function nearestCameraIdToViewer() {
|
||||
const carto = layerState._viewer?.camera?.positionCartographic;
|
||||
if (!carto || !layerState._records.length) return null;
|
||||
const lat = Cesium.Math.toDegrees(carto.latitude);
|
||||
const lon = Cesium.Math.toDegrees(carto.longitude);
|
||||
function nearestCameraIdToPoint(lat, lon) {
|
||||
if (
|
||||
!Number.isFinite(lat) ||
|
||||
!Number.isFinite(lon) ||
|
||||
Math.abs(lat) > 90 ||
|
||||
Math.abs(lon) > 180 ||
|
||||
!layerState._records.length
|
||||
)
|
||||
return null;
|
||||
|
||||
let best = null;
|
||||
for (const record of layerState._records) {
|
||||
@@ -34,9 +40,49 @@ export function createNavigation({
|
||||
}
|
||||
|
||||
/**
|
||||
* Flies the Cesium viewer camera to frame the specified CCTV camera,
|
||||
* Finds the camera closest to the viewer's current position.
|
||||
* @returns {string|null} Camera ID of the nearest camera, or null.
|
||||
*/
|
||||
function nearestCameraIdToViewer() {
|
||||
const pose = parts.model.eyePose();
|
||||
if (!pose) return null;
|
||||
return nearestCameraIdToPoint(pose.lat, pose.lon);
|
||||
}
|
||||
|
||||
/**
|
||||
* The camera the layer opens on when none is selected: the one nearest the
|
||||
* viewer, or the first record when the viewer has no position yet.
|
||||
* @returns {string|null} Camera ID, or null when the catalog is empty.
|
||||
*/
|
||||
|
||||
function openingCameraId() {
|
||||
return (
|
||||
nearestCameraIdToViewer() || layerState._records[0]?.camera?.id || null
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* After a settled move, moves the opening camera to the one nearest the
|
||||
* view, until someone chooses a camera. A shared view's flight lands after
|
||||
* enable() picked from the startup view.
|
||||
* @returns {boolean} True when the active camera changed.
|
||||
*/
|
||||
|
||||
function reopenNearestCamera() {
|
||||
if (!layerState._openingCameraProvisional || !layerState._enabled)
|
||||
return false;
|
||||
const nearest = nearestCameraIdToViewer();
|
||||
if (!nearest || nearest === layerState._activeCameraId) return false;
|
||||
parts.selection.setActiveCamera(nearest);
|
||||
// setActiveCamera ends the opening pick; this is still that pick.
|
||||
layerState._openingCameraProvisional = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flies the viewer's camera to frame the specified CCTV camera,
|
||||
* looking along its heading from above.
|
||||
* @param {Cesium.Viewer|null} viewer Cesium viewer that owns the camera.
|
||||
* @param {object|null} viewer The viewer that owns the camera.
|
||||
* @param {Object|null} record CCTV camera runtime record.
|
||||
* @param {number} [duration=2.2] - Flight duration in seconds.
|
||||
* @returns {'focused'|'no-active-camera'|'tracking-holds-view'|'cockpit-active'} Focus result.
|
||||
@@ -51,7 +97,7 @@ export function createNavigation({
|
||||
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
|
||||
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
|
||||
}
|
||||
if (viewer.trackedEntity) {
|
||||
if (isFollowing(viewer)) {
|
||||
console.debug(
|
||||
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
|
||||
);
|
||||
@@ -59,19 +105,16 @@ export function createNavigation({
|
||||
}
|
||||
const { camera } = record;
|
||||
const range = Math.max(280, camera.rangeM * 1.18);
|
||||
viewer.camera.flyToBoundingSphere(
|
||||
new Cesium.BoundingSphere(
|
||||
record.position,
|
||||
Math.max(40, camera.rangeM * 0.36),
|
||||
),
|
||||
cameraOf(viewer).flyToBounds(
|
||||
{ center: record.position, radius: Math.max(40, camera.rangeM * 0.36) },
|
||||
{
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
parts.model.toRad(camera.headingDeg),
|
||||
parts.model.toRad(-22),
|
||||
offset: {
|
||||
heading: parts.model.toRad(camera.headingDeg),
|
||||
pitch: parts.model.toRad(-22),
|
||||
range,
|
||||
),
|
||||
duration: Math.max(0.2, duration || 0),
|
||||
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
|
||||
},
|
||||
durationS: Math.max(0.2, duration || 0),
|
||||
easing: 'cubicInOut',
|
||||
},
|
||||
);
|
||||
return CCTV_FOCUS_RESULT.FOCUSED;
|
||||
@@ -148,7 +191,10 @@ export function createNavigation({
|
||||
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
|
||||
}
|
||||
return {
|
||||
nearestCameraIdToPoint,
|
||||
nearestCameraIdToViewer,
|
||||
openingCameraId,
|
||||
reopenNearestCamera,
|
||||
focusCctvRecord,
|
||||
focusCamera,
|
||||
maybeAutoHop,
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
|
||||
import { createNavigation } from './navigation.js';
|
||||
|
||||
function fixture() {
|
||||
const records = [
|
||||
{ camera: { id: 'west', lat: 40, lon: -120 } },
|
||||
{ camera: { id: 'east', lat: 40, lon: -100 } },
|
||||
];
|
||||
const state = { _records: records };
|
||||
const parts = {
|
||||
model: {
|
||||
eyePose: () => ({ lat: 40, lon: -101 }),
|
||||
haversineKm(lat1, lon1, lat2, lon2) {
|
||||
return Math.hypot(lat1 - lat2, lon1 - lon2);
|
||||
},
|
||||
},
|
||||
};
|
||||
const navigation = createNavigation({
|
||||
state,
|
||||
services: {},
|
||||
parts,
|
||||
source: {},
|
||||
});
|
||||
return { navigation };
|
||||
}
|
||||
|
||||
test('nearest camera can be resolved from an explicit WGS84 target', () => {
|
||||
const { navigation } = fixture();
|
||||
assert.equal(navigation.nearestCameraIdToPoint(40, -119), 'west');
|
||||
assert.equal(navigation.nearestCameraIdToPoint(40, -101), 'east');
|
||||
});
|
||||
|
||||
test('viewer-nearest delegates to the same target-point owner', () => {
|
||||
const { navigation } = fixture();
|
||||
assert.equal(navigation.nearestCameraIdToViewer(), 'east');
|
||||
});
|
||||
|
||||
test('invalid target coordinates fail closed', () => {
|
||||
const { navigation } = fixture();
|
||||
for (const [lat, lon] of [
|
||||
[NaN, 0],
|
||||
[null, 0],
|
||||
[0, Infinity],
|
||||
[90.00001, 0],
|
||||
[-90.00001, 0],
|
||||
[0, 180.00001],
|
||||
[0, -180.00001],
|
||||
]) {
|
||||
assert.equal(navigation.nearestCameraIdToPoint(lat, lon), null);
|
||||
}
|
||||
});
|
||||
+59
-36
@@ -1,13 +1,7 @@
|
||||
export {
|
||||
FRAME_ENDPOINT,
|
||||
SOURCE_ENDPOINT,
|
||||
HEALTH_ENDPOINT,
|
||||
MEDIA_ENDPOINT,
|
||||
ACTIVE_FRAME_REFRESH_MS,
|
||||
} from './sourcePolicy.js';
|
||||
import * as Cesium from 'cesium';
|
||||
export { ACTIVE_FRAME_REFRESH_MS } from './sourcePolicy.js';
|
||||
import { CCTV_CARD_FETCH_BURST_SPACING_MS } from '../../data/cctvCards.js';
|
||||
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
|
||||
import { hexColor } from '../../render/color.js';
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// API endpoints
|
||||
@@ -66,6 +60,45 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300;
|
||||
|
||||
export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10;
|
||||
|
||||
// View thinning: camera icons show only on or near the screen, and each
|
||||
// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX
|
||||
// at its distance from the viewer (in power-of-two metre steps, so a pan
|
||||
// keeps the same winners until a camera's distance crosses a step). Cells
|
||||
// smaller than VIEW_MIN_CELL_M do not thin:
|
||||
// close up every camera shows, co-located ones included.
|
||||
|
||||
export const VIEW_CELL_PX = 40;
|
||||
|
||||
export const VIEW_MIN_CELL_M = 60;
|
||||
|
||||
// Icons this far past the screen edge (fraction of its size) still show, so
|
||||
// a pan does not reveal empty ground before the next view pass.
|
||||
|
||||
export const VIEW_ICON_MARGIN = 0.5;
|
||||
|
||||
// While the camera moves, the view pass reruns at most this often.
|
||||
|
||||
export const VIEW_MOTION_REFRESH_MS = 250;
|
||||
// A motion tick is skipped unless the camera moved this fraction of its
|
||||
// ellipsoid height, or turned this many degrees, since the last pass.
|
||||
|
||||
export const VIEW_MOTION_MIN_MOVE_FRACTION = 0.01;
|
||||
|
||||
export const VIEW_MOTION_MIN_TURN_DEG = 0.5;
|
||||
|
||||
// Motion passes are spaced at least this many times the last pass's cost, so
|
||||
// a large catalog spends at most about a tenth of a long move on them.
|
||||
|
||||
export const VIEW_MOTION_COST_FACTOR = 10;
|
||||
|
||||
// A view camera's geometry is attempted at most this many times per surface
|
||||
// regime (a cold elevation cell can leave the first attempt unresolved); the
|
||||
// retry runs this long after the drain that left it unresolved.
|
||||
|
||||
export const VIEW_GEOMETRY_ATTEMPTS = 2;
|
||||
|
||||
export const VIEW_GEOMETRY_RETRY_MS = 1500;
|
||||
|
||||
// Throttle for placeholder repaints — the projection RAF loop must not
|
||||
// re-fill a 1080p canvas on every frame while a feed image is still loading.
|
||||
|
||||
@@ -90,9 +123,6 @@ export const CCTV_CALIBRATION_STORAGE_KEY_V2 =
|
||||
|
||||
export const PROJECTION_TEXTURE_SWAP_MS = 1000;
|
||||
|
||||
export const PROJECTION_VERT_ASPECT =
|
||||
PROJECTION_CANVAS_WIDTH / PROJECTION_CANVAS_HEIGHT;
|
||||
|
||||
// V2 frustum geometry (design §2a/§6): the far-cap center + corners never sink
|
||||
// below groundAlt + this clearance, so a fabricated pitch (-24°) cannot bury
|
||||
// the monitor plane in the 3D tiles. Exported for the unit suite.
|
||||
@@ -149,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
|
||||
heightM: 0,
|
||||
});
|
||||
|
||||
/** Base64-encoded SVG camera icon for billboard rendering. */
|
||||
/**
|
||||
* Base64-encoded SVG camera icon for the camera icons. Icons rasterise an
|
||||
* SVG at its own size, so it is 48 px: drawn at 24 px, 1.25× near scale on a
|
||||
* 2× display draws it at 60 device px, and it stays sharp there.
|
||||
*/
|
||||
|
||||
export const CAMERA_ICON = (() => {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
|
||||
<defs>
|
||||
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
|
||||
<stop offset="0%" stop-color="#c9f6ff"/>
|
||||
@@ -404,44 +438,33 @@ export const CAMERA_SEEDS = [
|
||||
];
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Visual style constants
|
||||
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
export const IDLE_CAMERA_COLOR =
|
||||
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.88);
|
||||
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
|
||||
|
||||
export const ACTIVE_CAMERA_COLOR =
|
||||
Cesium.Color.fromCssColorString('#ffd97a').withAlpha(0.95);
|
||||
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
|
||||
|
||||
export const LIVE_CAMERA_COLOR =
|
||||
Cesium.Color.fromCssColorString('#b48cff').withAlpha(0.88);
|
||||
export const LIVE_CAMERA_COLOR = hexColor('#b48cff', 0.88);
|
||||
|
||||
export const IDLE_COVERAGE_COLOR =
|
||||
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.24);
|
||||
export const IDLE_COVERAGE_COLOR = hexColor('#2fe0ff', 0.24);
|
||||
|
||||
export const IDLE_COVERAGE_CENTER_MUTED =
|
||||
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.2);
|
||||
export const IDLE_COVERAGE_CENTER_MUTED = hexColor('#2fe0ff', 0.2);
|
||||
|
||||
export const IDLE_COVERAGE_EDGE_MUTED =
|
||||
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.18);
|
||||
export const IDLE_COVERAGE_EDGE_MUTED = hexColor('#2fe0ff', 0.18);
|
||||
|
||||
export const ACTIVE_COVERAGE_EDGE =
|
||||
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.58);
|
||||
export const ACTIVE_COVERAGE_EDGE = hexColor('#8dff87', 0.58);
|
||||
|
||||
export const ACTIVE_COVERAGE_CENTER =
|
||||
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.82);
|
||||
export const ACTIVE_COVERAGE_CENTER = hexColor('#d7ff8d', 0.82);
|
||||
|
||||
// H6: dimmer depth-fail materials let the active frustum wireframe read
|
||||
// through buildings while in monitor fallback mode.
|
||||
|
||||
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL =
|
||||
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.18);
|
||||
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = hexColor('#8dff87', 0.18);
|
||||
|
||||
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL =
|
||||
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.26);
|
||||
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = hexColor('#d7ff8d', 0.26);
|
||||
|
||||
export const PLANE_OUTLINE_COLOR =
|
||||
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.55);
|
||||
export const PLANE_OUTLINE_COLOR = hexColor('#6be8ff', 0.55);
|
||||
|
||||
/**
|
||||
* Card budget while the staggered geometry drain is running — the raised
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
// The CCTV HUD summary shows the CAL badge, source kind and view band in the
|
||||
// UI language; English keeps its codes, and unknown source codes stay codes.
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { setLocale } from '../../i18n/index.js';
|
||||
import { createPresentation } from './presentation.js';
|
||||
|
||||
function summary(sourceKind) {
|
||||
const camera = {
|
||||
id: 'c1',
|
||||
city: 'Austin',
|
||||
name: 'Cam',
|
||||
rangeM: 100,
|
||||
fovDeg: 60,
|
||||
feedType: 'image',
|
||||
};
|
||||
const record = { camera };
|
||||
const presentation = createPresentation({
|
||||
state: {
|
||||
_records: [record],
|
||||
_healthById: new Map(sourceKind ? [['c1', { sourceKind }]] : []),
|
||||
_showProjection: false,
|
||||
_coverageMode: 'sector',
|
||||
},
|
||||
services: {},
|
||||
parts: {
|
||||
selection: { getActiveRecord: () => record },
|
||||
model: {
|
||||
sectorAreaKm2: () => 1,
|
||||
currentViewContext: () => 'street:1:2',
|
||||
},
|
||||
geometry: { coverageNeighborCount: () => 0 },
|
||||
calibration: { deriveCalBadge: () => 'raw-prior' },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
return presentation.buildSummaryText();
|
||||
}
|
||||
|
||||
test('en: CAL, SRC and CONTEXT keep their English codes', () => {
|
||||
setLocale('en');
|
||||
assert.match(summary('upstream'), /CAL RAW PRIOR · SRC UPSTREAM/);
|
||||
assert.match(summary(null), /SRC IMAGE · STREET CONTEXT/);
|
||||
assert.match(summary('upstream-image'), /SRC UPSTREAM-IMAGE/);
|
||||
});
|
||||
|
||||
test('fr: CAL, SRC and CONTEXT values are translated', () => {
|
||||
setLocale('fr');
|
||||
try {
|
||||
assert.match(
|
||||
summary('upstream'),
|
||||
/CAL ESTIM\. INITIALE · SRC AMONT · CONTEXTE RUE/,
|
||||
);
|
||||
assert.match(summary('upstream-image'), /SRC UPSTREAM-IMAGE/);
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
});
|
||||
+122
-20
@@ -1,5 +1,5 @@
|
||||
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
|
||||
import { t } from '../../i18n/index.js';
|
||||
import { isolate, msg, t } from '../../i18n/index.js';
|
||||
import { ACTIVE_FRAME_REFRESH_MS, IDLE_FRAME_REFRESH_MS } from './policy.js';
|
||||
import { headingHudToken, isHeadingEstimated } from './headingConfidence.js';
|
||||
import {
|
||||
@@ -8,6 +8,59 @@ import {
|
||||
isDatasheetFov,
|
||||
} from './modelSpecs.js';
|
||||
|
||||
// The summary line names the CAL badge, the source kind and the view band in
|
||||
// the page language; the codes underneath stay English.
|
||||
const CAL_BADGE_LABELS = Object.freeze({
|
||||
calibrated: msg('CALIBRATED'),
|
||||
curated: msg('CURATED'),
|
||||
'raw-prior': msg('RAW PRIOR'),
|
||||
});
|
||||
|
||||
// The same source-kind words as the CCTV panel (src/ui/cctvFrames.js).
|
||||
const SOURCE_KIND_LABELS = Object.freeze({
|
||||
snapshot: msg('SNAPSHOT'),
|
||||
live: msg('LIVE'),
|
||||
fallback: msg('FALLBACK'),
|
||||
upstream: msg('UPSTREAM'),
|
||||
synthetic: msg('SYNTHETIC'),
|
||||
configured: msg('CONFIGURED'),
|
||||
seed: msg('SEED'),
|
||||
image: msg('IMAGE'),
|
||||
unknown: msg('UNKNOWN'),
|
||||
});
|
||||
|
||||
/** CAL badge id ('raw-prior') as the summary shows it; unknown ids stay codes. */
|
||||
export function summaryCalLabel(badge) {
|
||||
const key = String(badge || '');
|
||||
return CAL_BADGE_LABELS[key]
|
||||
? t(CAL_BADGE_LABELS[key])
|
||||
: key.replace('-', ' ').toUpperCase();
|
||||
}
|
||||
|
||||
/** Source kind ('image', 'snapshot') for the summary; HLS, MJPEG… stay codes. */
|
||||
export function summarySourceLabel(kind) {
|
||||
const key = String(kind || 'image').toLowerCase();
|
||||
return SOURCE_KIND_LABELS[key]
|
||||
? t(SOURCE_KIND_LABELS[key])
|
||||
: key.toUpperCase();
|
||||
}
|
||||
|
||||
/** View band id ('street', 'city'…) as the HUD names it. */
|
||||
export function summaryViewBandLabel(band) {
|
||||
switch (band) {
|
||||
case 'street':
|
||||
return t('STREET', { context: 'view band' });
|
||||
case 'city':
|
||||
return t('CITY', { context: 'view band' });
|
||||
case 'regional':
|
||||
return t('REGIONAL', { context: 'view band' });
|
||||
case 'global':
|
||||
return t('GLOBAL', { context: 'view band' });
|
||||
default:
|
||||
return String(band || '').toUpperCase();
|
||||
}
|
||||
}
|
||||
|
||||
export function createPresentation({
|
||||
state: layerState,
|
||||
services,
|
||||
@@ -44,6 +97,8 @@ export function createPresentation({
|
||||
const health = layerState._healthById.get(active.camera.id) || null;
|
||||
const calBadge = parts.calibration.deriveCalBadge(active.camera);
|
||||
|
||||
// Each part is isolated: in right-to-left text a code keeps its own value
|
||||
// (FOV 44°) instead of trading it with its neighbour.
|
||||
return [
|
||||
t('{city} CCTV', {
|
||||
city: active.camera.city.toUpperCase(),
|
||||
@@ -72,17 +127,13 @@ export function createPresentation({
|
||||
: t('ISOLATED VIEW'),
|
||||
layerState._showProjection ? t('PROJ MONITOR') : t('PROJ OFF'),
|
||||
layerState._coverageMode === 'viewshed' ? t('VIEWSHED') : null,
|
||||
t('CAL {value}', {
|
||||
value: calBadge.replace('-', ' ').toUpperCase(),
|
||||
t('CAL {value}', { value: summaryCalLabel(calBadge) }),
|
||||
t('SRC {value}', {
|
||||
value: summarySourceLabel(
|
||||
health?.sourceKind || active.camera.feedType || 'image',
|
||||
),
|
||||
}),
|
||||
health?.sourceKind
|
||||
? t('SRC {value}', {
|
||||
value: String(health.sourceKind).toUpperCase(),
|
||||
})
|
||||
: t('SRC {value}', {
|
||||
value: String(active.camera.feedType || 'image').toUpperCase(),
|
||||
}),
|
||||
t('{value} CONTEXT', { value: viewBand.toUpperCase() }),
|
||||
t('{value} CONTEXT', { value: summaryViewBandLabel(viewBand) }),
|
||||
// Identified hardware: append the model's datasheet specs + attribution.
|
||||
active.camera.spec
|
||||
? t('{spec} · SPECS: CCTV-DATABASE.COM', {
|
||||
@@ -91,6 +142,7 @@ export function createPresentation({
|
||||
: null,
|
||||
]
|
||||
.filter(Boolean)
|
||||
.map(isolate)
|
||||
.join(' · ');
|
||||
}
|
||||
|
||||
@@ -108,9 +160,14 @@ export function createPresentation({
|
||||
const camera = record.camera;
|
||||
const health = layerState._healthById.get(camera.id) || null;
|
||||
const isActive = camera.id === resolvedActiveId;
|
||||
const refreshMs = isActive
|
||||
const defaultRefreshMs = isActive
|
||||
? ACTIVE_FRAME_REFRESH_MS
|
||||
: IDLE_FRAME_REFRESH_MS;
|
||||
const sourceRefreshMs = Number(camera.frameRefreshMs);
|
||||
const refreshMs =
|
||||
Number.isFinite(sourceRefreshMs) && sourceRefreshMs > 0
|
||||
? Math.max(defaultRefreshMs, sourceRefreshMs)
|
||||
: defaultRefreshMs;
|
||||
return {
|
||||
id: camera.id,
|
||||
name: camera.name,
|
||||
@@ -140,13 +197,18 @@ export function createPresentation({
|
||||
mountHeightM: camera.mountHeightM,
|
||||
active: isActive,
|
||||
feedType: camera.feedType,
|
||||
sourceUrl: camera.sourceUrl || '',
|
||||
browserMediaUrl: camera.browserMediaUrl || '',
|
||||
accuracyM: Number.isFinite(camera.accuracyM) ? camera.accuracyM : null,
|
||||
positionSource: camera.positionSource || '',
|
||||
isVideo:
|
||||
parts.model.isVideoFeedType(camera.feedType) &&
|
||||
parts.model.isVideoFeedCamera(camera) &&
|
||||
record.projection?.mode !== 'image',
|
||||
sourceKind:
|
||||
health?.sourceKind ||
|
||||
camera.sourceKind ||
|
||||
(camera.feedConfigured ? 'configured' : 'seed'),
|
||||
sourceKind: camera.sourceKind?.startsWith('quebec-')
|
||||
? camera.sourceKind
|
||||
: health?.sourceKind ||
|
||||
camera.sourceKind ||
|
||||
(camera.feedConfigured ? 'configured' : 'seed'),
|
||||
sourceStatus: health?.status || 'unknown',
|
||||
sourceMessage: health?.message || '',
|
||||
sourceLabel: health?.label || camera.provider || '',
|
||||
@@ -224,15 +286,55 @@ export function createPresentation({
|
||||
hoverId: layerState._hoverCardId,
|
||||
},
|
||||
activeCameraId: activeId,
|
||||
activeCameraReselection: layerState._activeCameraReselection,
|
||||
activeCamera: active ? getPublicCameraState(active, activeId) : null,
|
||||
cameras: layerState._records.map((record) =>
|
||||
getPublicCameraState(record, activeId),
|
||||
),
|
||||
cameraIndex: cameraIndex(),
|
||||
summary: buildSummaryText(),
|
||||
};
|
||||
// The full per-camera state is built only when a subscriber reads it: a
|
||||
// catalog of tens of thousands would otherwise be rebuilt on every
|
||||
// progress tick for listeners that only want the active camera. It reads
|
||||
// the records live at that moment, and spreading or serializing the
|
||||
// payload builds it, so callers that want a count use `count`.
|
||||
let cameras = null;
|
||||
Object.defineProperty(payload, 'cameras', {
|
||||
enumerable: true,
|
||||
get() {
|
||||
cameras ??= layerState._records.map((record) =>
|
||||
getPublicCameraState(record, activeId),
|
||||
);
|
||||
return cameras;
|
||||
},
|
||||
});
|
||||
return payload;
|
||||
}
|
||||
|
||||
/**
|
||||
* `{ id, city, name }` for the active camera, then every camera the view
|
||||
* pass shows: what the camera picker lists. A whole catalog would put tens
|
||||
* of thousands of options in the DOM and slow every layout. The same array
|
||||
* is returned until the view or the active camera changes, so a consumer
|
||||
* can compare it by identity.
|
||||
* @returns {{id: string, city: string, name: string}[]}
|
||||
*/
|
||||
|
||||
function cameraIndex() {
|
||||
const view = layerState._viewRecords;
|
||||
const active = parts.selection.getActiveRecord();
|
||||
const cached = layerState._cameraIndexCache;
|
||||
if (cached?.view === view && cached.active === active) return cached.list;
|
||||
const records = active
|
||||
? [active, ...view.filter((record) => record !== active)]
|
||||
: view;
|
||||
const list = records.map(({ camera }) => ({
|
||||
id: camera.id,
|
||||
city: camera.city,
|
||||
name: camera.name,
|
||||
}));
|
||||
layerState._cameraIndexCache = { view, active, list };
|
||||
return list;
|
||||
}
|
||||
|
||||
/** Dispatches the current UI state to all registered subscriber callbacks. */
|
||||
|
||||
function notifyListeners() {
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
// The CCTV summary line names the CAL badge, the source kind and the view
|
||||
// band in the page language; unknown codes stay as uppercase codes.
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { setLocale } from '../../i18n/index.js';
|
||||
import {
|
||||
summaryCalLabel,
|
||||
summarySourceLabel,
|
||||
summaryViewBandLabel,
|
||||
} from './presentation.js';
|
||||
|
||||
function inLocale(locale, run) {
|
||||
setLocale(locale);
|
||||
try {
|
||||
return run();
|
||||
} finally {
|
||||
setLocale('en');
|
||||
}
|
||||
}
|
||||
|
||||
test('English keeps the summary codes', () => {
|
||||
assert.equal(summaryCalLabel('raw-prior'), 'RAW PRIOR');
|
||||
assert.equal(summarySourceLabel('image'), 'IMAGE');
|
||||
assert.equal(summarySourceLabel('hls'), 'HLS');
|
||||
assert.equal(summaryViewBandLabel('street'), 'STREET');
|
||||
assert.equal(summaryViewBandLabel('none'), 'NONE');
|
||||
});
|
||||
|
||||
test('Portuguese summary values are translated', () => {
|
||||
inLocale('pt', () => {
|
||||
assert.equal(summaryCalLabel('raw-prior'), 'ESTIMATIVA BRUTA');
|
||||
assert.equal(summaryCalLabel('calibrated'), 'CALIBRADA');
|
||||
assert.equal(summarySourceLabel('IMAGE'), 'IMAGEM');
|
||||
assert.equal(summarySourceLabel('mjpeg'), 'MJPEG');
|
||||
assert.equal(summaryViewBandLabel('street'), 'RUA');
|
||||
assert.equal(summaryViewBandLabel('city'), 'CIDADE');
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,4 @@
|
||||
import { attachCctvVideo } from './videoPlayback.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
|
||||
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
|
||||
@@ -8,6 +7,25 @@ import {
|
||||
PROJECTION_CANVAS_HEIGHT,
|
||||
} from './policy.js';
|
||||
|
||||
/** 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,
|
||||
services,
|
||||
@@ -18,7 +36,7 @@ export function createProjection({
|
||||
|
||||
/**
|
||||
* 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.
|
||||
*/
|
||||
|
||||
@@ -46,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).
|
||||
@@ -55,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(
|
||||
@@ -64,21 +83,33 @@ export function createProjection({
|
||||
record.probeClampRangeM,
|
||||
);
|
||||
const positions =
|
||||
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
|
||||
runtime.planeEntity.position = positions.capCenter;
|
||||
runtime.planeEntity.orientation = parts.model.planeOrientationFor(
|
||||
record.camera,
|
||||
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -102,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(
|
||||
@@ -121,38 +155,34 @@ export function createProjection({
|
||||
}
|
||||
}
|
||||
|
||||
/** Create the native monitor plane plus its cached host-label presentation. */
|
||||
/** A plain white plane image, for a plane with no media (tests). */
|
||||
function plainPlaneSource() {
|
||||
return { image: WHITE_IMAGE };
|
||||
}
|
||||
|
||||
/** 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`,
|
||||
properties: { cctvCameraId: record.camera.id },
|
||||
cameraId: record.camera.id,
|
||||
source: runtime.planeSource || plainPlaneSource(),
|
||||
alpha: PLANE_ALPHA,
|
||||
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
|
||||
show: false,
|
||||
position: positions.capCenter,
|
||||
orientation: parts.model.planeOrientationFor(
|
||||
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,
|
||||
},
|
||||
});
|
||||
return runtime.planeEntity;
|
||||
};
|
||||
placePlane(plane, record.camera, geometry, positions);
|
||||
runtime.plane = plane;
|
||||
parts.drawSets.writePlane(plane);
|
||||
return plane;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -171,6 +201,9 @@ export function createProjection({
|
||||
|
||||
function createProjectionRuntime(record) {
|
||||
if (!layerState._viewer) return null;
|
||||
// Québec 511 denies CORS pixel access; Québec map previews are native DOM
|
||||
// videos positioned over the globe, never Cesium video textures.
|
||||
if (parts.model.isBrowserOverlayCamera(record.camera)) return null;
|
||||
const canvas = document.createElement('canvas');
|
||||
canvas.width = PROJECTION_CANVAS_WIDTH;
|
||||
canvas.height = PROJECTION_CANVAS_HEIGHT;
|
||||
@@ -184,11 +217,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,
|
||||
@@ -219,16 +252,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);
|
||||
@@ -253,7 +287,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();
|
||||
},
|
||||
@@ -276,9 +310,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(
|
||||
@@ -287,12 +320,7 @@ export function createProjection({
|
||||
record.probeClampRangeM,
|
||||
);
|
||||
const positions =
|
||||
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
|
||||
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
|
||||
image: canvas,
|
||||
transparent: true,
|
||||
color: Cesium.Color.WHITE.withAlpha(0.95),
|
||||
});
|
||||
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
|
||||
createProjectionPlane(record, runtime, geometry, positions);
|
||||
|
||||
return runtime;
|
||||
@@ -337,15 +365,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() {
|
||||
@@ -427,6 +455,8 @@ export function createProjection({
|
||||
updatePlanePlacement,
|
||||
clearProjectionOverlay,
|
||||
setPlaneVisible,
|
||||
setPlaneSource,
|
||||
plainPlaneSource,
|
||||
createProjectionPlane,
|
||||
createProjectionRuntime,
|
||||
ensureProjectionRuntime,
|
||||
|
||||
+735
-100
File diff suppressed because it is too large.
Load diff
@@ -2,6 +2,7 @@
|
||||
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon
|
||||
// from the same base color the coverage refresh assigns, so a video-feed camera
|
||||
// stays violet while it dims instead of falling back to the idle cyan.
|
||||
// Teardown lets go of the icon set of the viewer that drew it.
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createRendering } from './rendering.js';
|
||||
@@ -11,65 +12,369 @@ import {
|
||||
LIVE_CAMERA_COLOR,
|
||||
} from './policy.js';
|
||||
import { isVideoFeedType } from '../../sources/cctvTypes.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
|
||||
import { bindRenderer } from '../../render/rendererOf.js';
|
||||
|
||||
const FOCUS_FACTOR = 0.5;
|
||||
|
||||
function assertFadedFrom(actual, base, label) {
|
||||
assert.ok(actual, `${label}: color written`);
|
||||
assert.deepEqual(
|
||||
[actual.red, actual.green, actual.blue],
|
||||
[base.red, base.green, base.blue],
|
||||
`${label}: hue`,
|
||||
);
|
||||
assert.equal(actual.alpha, base.alpha * FOCUS_FACTOR, `${label}: alpha`);
|
||||
function assertKeepsColor(icons, id, base, label) {
|
||||
assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`);
|
||||
assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`);
|
||||
}
|
||||
|
||||
test('focus de-emphasis fades each icon from its own color', () => {
|
||||
const record = (id, feedType) => ({
|
||||
camera: { id, feedType },
|
||||
// No position, so the pass skips screen projection; the focus stub below
|
||||
// decides the factor on its own.
|
||||
billboard: { show: true },
|
||||
position: { x: 6378137, y: 0, z: 0 },
|
||||
});
|
||||
const idleVideo = record('idle-hls', 'hls');
|
||||
const idleStill = record('idle-image', 'image');
|
||||
const activeVideo = record('active-hls', 'hls');
|
||||
const viewer = {};
|
||||
const camera = fakeCameraPort({
|
||||
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
|
||||
});
|
||||
const projected = [];
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera: camera.port,
|
||||
query: {
|
||||
project: (position) => {
|
||||
projected.push(position);
|
||||
return { x: 10, y: 20 };
|
||||
},
|
||||
},
|
||||
});
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_viewer: { scene: {}, camera: {} },
|
||||
_viewer: viewer,
|
||||
_records: [idleVideo, idleStill, activeVideo],
|
||||
_activeCameraId: activeVideo.camera.id,
|
||||
_activeFocusStyleCount: 0,
|
||||
_lastFocusStyleAt: -Infinity,
|
||||
};
|
||||
const distances = [];
|
||||
const focus = {
|
||||
focusNowMs: (nowMs) => nowMs,
|
||||
getFocusTarget: () => ({}),
|
||||
focusPassIsNeeded: () => true,
|
||||
advanceSpriteFocus: () => ({
|
||||
factor: FOCUS_FACTOR,
|
||||
active: true,
|
||||
transitioning: false,
|
||||
}),
|
||||
advanceSpriteFocus: (meta, input) => {
|
||||
distances.push(input.cameraDistance);
|
||||
return { factor: FOCUS_FACTOR, active: true, transitioning: false };
|
||||
},
|
||||
focusAlphaNeedsWrite: () => true,
|
||||
};
|
||||
const { refreshCctvFocusStyles } = createRendering({
|
||||
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
|
||||
createRendering({
|
||||
state,
|
||||
services: { focus },
|
||||
parts: {
|
||||
model: {
|
||||
isVideoFeedType,
|
||||
isVideoFeedCamera: (camera) =>
|
||||
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
|
||||
},
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
const setId = createCameraIcons(viewer);
|
||||
for (const r of state._records) addCameraIcon(r);
|
||||
|
||||
refreshCctvFocusStyles(1000);
|
||||
|
||||
const icons = state._icons;
|
||||
assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video');
|
||||
assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still');
|
||||
assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video');
|
||||
assert.equal(state._activeFocusStyleCount, 3);
|
||||
assert.equal(projected.length, 3, 'each shown icon is projected');
|
||||
assert.deepEqual(distances, [1000, 1000, 1000], 'from the eye');
|
||||
// What the set draws: depth-test-free, held at the mount, shrinking
|
||||
// with distance as before.
|
||||
const drawn = draw.set(setId).items.get('idle-hls');
|
||||
assert.equal(drawn.disableDepthTest, Infinity);
|
||||
assert.deepEqual(drawn.motion, { kind: 'hold' });
|
||||
assert.deepEqual(drawn.pos, idleVideo.position);
|
||||
assert.deepEqual(drawn.size, [24, 24]);
|
||||
assert.deepEqual(drawn.scaleByDistance, {
|
||||
near: 350,
|
||||
nearValue: 1.25,
|
||||
far: 4_000_000,
|
||||
farValue: 0.42,
|
||||
});
|
||||
assert.equal(drawn.focus, FOCUS_FACTOR);
|
||||
assert.equal(draw.set(setId).spec.horizonCull, true);
|
||||
// Hidden until enable() has culled and thinned the cameras: the layer
|
||||
// waits on its health check between drawing them and that pass.
|
||||
assert.equal(draw.set(setId).show, false);
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('the icons go with the viewer that drew them, whichever tears down', () => {
|
||||
const first = {};
|
||||
const second = {};
|
||||
const one = bindFakeDraw(first);
|
||||
const two = bindFakeDraw(second);
|
||||
const state = { _viewer: first };
|
||||
const { createCameraIcons, destroyCameraIcons } = createRendering({
|
||||
state,
|
||||
services: { focus },
|
||||
parts: { model: { isVideoFeedType } },
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
const old = createCameraIcons(first);
|
||||
state._viewer = second;
|
||||
const current = createCameraIcons(second);
|
||||
assert.notEqual(old, current);
|
||||
assert.equal(one.draw.sets.get(old).disposed, true, 'a re-init lets go');
|
||||
assert.equal(two.draw.sets.get(current).disposed, false);
|
||||
|
||||
refreshCctvFocusStyles(1000);
|
||||
destroyCameraIcons();
|
||||
assert.equal(two.draw.sets.get(current).disposed, true);
|
||||
assert.equal(state._icons, null);
|
||||
} finally {
|
||||
one.unbind();
|
||||
two.unbind();
|
||||
}
|
||||
});
|
||||
|
||||
assertFadedFrom(idleVideo.billboard.color, LIVE_CAMERA_COLOR, 'idle video');
|
||||
assertFadedFrom(idleStill.billboard.color, IDLE_CAMERA_COLOR, 'idle still');
|
||||
assertFadedFrom(
|
||||
activeVideo.billboard.color,
|
||||
ACTIVE_CAMERA_COLOR,
|
||||
'active video',
|
||||
test('the obstruction probe casts one ray through the query port', async () => {
|
||||
const calls = [];
|
||||
const viewer = {};
|
||||
const unbind = bindRenderer(viewer, {
|
||||
query: {
|
||||
rayCast: async (ray, options) => {
|
||||
calls.push({ ray, options });
|
||||
return { x: 1, y: 2, z: 3 };
|
||||
},
|
||||
},
|
||||
});
|
||||
const state = { _viewer: viewer };
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
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(
|
||||
await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
|
||||
null,
|
||||
);
|
||||
assert.equal(state._activeFocusStyleCount, 3);
|
||||
});
|
||||
|
||||
test('cards go only where the horizon lets the camera see', () => {
|
||||
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000);
|
||||
const front = Cesium.Cartesian3.fromDegrees(0, 0);
|
||||
const back = Cesium.Cartesian3.fromDegrees(180, 0);
|
||||
const viewer = {};
|
||||
const camera = fakeCameraPort({
|
||||
pose: { position: { x: eye.x, y: eye.y, z: eye.z } },
|
||||
});
|
||||
const unbind = bindRenderer(viewer, {
|
||||
camera: camera.port,
|
||||
canvas: { clientWidth: 800, clientHeight: 0, height: 600 },
|
||||
query: { project: () => ({ x: 10, y: 20 }) },
|
||||
});
|
||||
try {
|
||||
const view = createRendering({
|
||||
state: { _viewer: viewer },
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
}).cardView();
|
||||
assert.equal(view.width, 800);
|
||||
assert.equal(view.height, 600);
|
||||
assert.deepEqual(view.screenOf(front), { x: 10, y: 20 });
|
||||
assert.equal(view.screenOf(back), null);
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('the projection tiles are ready only when drawn and settled', () => {
|
||||
const viewer = {};
|
||||
let globeVisible = true;
|
||||
let settled = true;
|
||||
const unbind = bindRenderer(viewer, {
|
||||
globe: {
|
||||
isGlobeVisible: () => globeVisible,
|
||||
isSettled: (kind) => kind === 'tiles' && settled,
|
||||
},
|
||||
});
|
||||
try {
|
||||
const { projectionTilesReady } = createRendering({
|
||||
state: { _viewer: viewer },
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
assert.equal(projectionTilesReady(), false, 'a globe stack hides them');
|
||||
globeVisible = false;
|
||||
assert.equal(projectionTilesReady(), true);
|
||||
settled = false;
|
||||
assert.equal(projectionTilesReady(), false, 'still streaming');
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
const bare = createRendering({
|
||||
state: { _viewer: {} },
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
});
|
||||
assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles');
|
||||
});
|
||||
|
||||
test('a view pass writes only the icons it changes, in one write', () => {
|
||||
const viewer = {};
|
||||
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 2000);
|
||||
const down = Cesium.Cartesian3.normalize(
|
||||
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
|
||||
new Cesium.Cartesian3(),
|
||||
);
|
||||
const camera = fakeCameraPort({
|
||||
pose: {
|
||||
position: { x: eye.x, y: eye.y, z: eye.z },
|
||||
direction: { x: down.x, y: down.y, z: down.z },
|
||||
up: { x: 0, y: 0, z: 1 },
|
||||
fovy: Math.PI / 3,
|
||||
aspectRatio: 4 / 3,
|
||||
near: 0.1,
|
||||
far: 5e8,
|
||||
},
|
||||
});
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera: camera.port,
|
||||
canvas: { clientWidth: 800, clientHeight: 600 },
|
||||
});
|
||||
const record = (id, lon) => {
|
||||
const p = Cesium.Cartesian3.fromDegrees(lon, 0, 10);
|
||||
return {
|
||||
camera: { id, lat: 0, lon },
|
||||
position: { x: p.x, y: p.y, z: p.z },
|
||||
};
|
||||
};
|
||||
// One in view, one far off it.
|
||||
const near = record('near', 0);
|
||||
const far = record('far', 1);
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_viewer: viewer,
|
||||
_records: [near, far],
|
||||
_viewRecords: [],
|
||||
_healthById: new Map(),
|
||||
_scratchViewScreen: { x: 0, y: 0 },
|
||||
};
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: {
|
||||
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
|
||||
drawSets: { roleOfSet: () => null },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
const setId = rendering.createCameraIcons(viewer);
|
||||
for (const r of state._records) rendering.addCameraIcon(r);
|
||||
const set = draw.set(setId);
|
||||
const writes = set.writes;
|
||||
|
||||
assert.equal(rendering.refreshHorizonCulling(), true);
|
||||
assert.equal(set.writes, writes + 1, 'one write for the pass');
|
||||
assert.equal(set.items.get('near').show, true);
|
||||
assert.equal(set.items.get('far').show, false);
|
||||
|
||||
assert.equal(rendering.refreshHorizonCulling(), false);
|
||||
assert.equal(set.writes, writes + 1, 'an unchanged view writes nothing');
|
||||
|
||||
// Another layer on the same viewer draws its icons in a set of its own.
|
||||
const other = createRendering({
|
||||
state: { _viewer: viewer },
|
||||
services: { focus: {} },
|
||||
parts: {},
|
||||
source: {},
|
||||
});
|
||||
const otherId = other.createCameraIcons(viewer);
|
||||
assert.notEqual(otherId, setId);
|
||||
assert.equal(
|
||||
rendering.extractPickedCameraId({ set: otherId, id: 'near' }),
|
||||
null,
|
||||
"the other layer's icon is not this layer's camera",
|
||||
);
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('a pose with no perspective field of view is projected by the renderer', () => {
|
||||
const viewer = {};
|
||||
const camera = fakeCameraPort({
|
||||
pose: { position: { x: 7e6, y: 0, z: 0 }, fovy: undefined },
|
||||
});
|
||||
const asked = [];
|
||||
const { draw, unbind } = bindFakeDraw(viewer, {
|
||||
camera: camera.port,
|
||||
canvas: { clientWidth: 800, clientHeight: 600 },
|
||||
query: {
|
||||
project: (position) => {
|
||||
asked.push(position.y);
|
||||
return position.y === 0 ? { x: 400, y: 300 } : null;
|
||||
},
|
||||
},
|
||||
});
|
||||
// On the ground under the eye, in cells of their own.
|
||||
const record = (id, y) => ({
|
||||
camera: { id, lat: 0, lon: y / 1000 },
|
||||
position: { x: 6378137, y, z: 0 },
|
||||
});
|
||||
const state = {
|
||||
_enabled: true,
|
||||
_viewer: viewer,
|
||||
_records: [record('on', 0), record('off', 1000)],
|
||||
_viewRecords: [],
|
||||
_healthById: new Map(),
|
||||
_scratchViewScreen: { x: 0, y: 0 },
|
||||
};
|
||||
const rendering = createRendering({
|
||||
state,
|
||||
services: { focus: {} },
|
||||
parts: {
|
||||
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
try {
|
||||
const setId = rendering.createCameraIcons(viewer);
|
||||
for (const r of state._records) rendering.addCameraIcon(r);
|
||||
rendering.refreshHorizonCulling();
|
||||
const set = draw.set(setId);
|
||||
assert.deepEqual(asked.sort(), [0, 1000]);
|
||||
assert.equal(set.items.get('on').show, true);
|
||||
assert.equal(set.items.get('off').show, false);
|
||||
} finally {
|
||||
unbind();
|
||||
}
|
||||
});
|
||||
|
||||
test('focus release restores video hue and alpha after the style throttle', () => {
|
||||
|
||||
@@ -1,8 +1,4 @@
|
||||
import {
|
||||
bindTrackingClickGesture,
|
||||
isTrackingClickGesture,
|
||||
} from '../../data/trackingClickGesture.js';
|
||||
import * as Cesium from 'cesium';
|
||||
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
|
||||
|
||||
export function createSelection({
|
||||
state: layerState,
|
||||
@@ -34,24 +30,19 @@ export function createSelection({
|
||||
}
|
||||
|
||||
/**
|
||||
* Bind CCTV activation to clean taps while preserving the layer's hover-move
|
||||
* callback on the shared Cesium handler. Drag-like and long-press gestures do
|
||||
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
|
||||
* not reach camera activation or focus dispatch.
|
||||
* @param {Cesium.ScreenSpaceEventHandler|Object} handler - Input handler.
|
||||
* @param {(click: Object) => void} onClick - Accepted CCTV click callback.
|
||||
* @param {Object} [options] - Gesture test seams and optional onMouseMove hook.
|
||||
* @returns {void}
|
||||
* @param {import('../../input/dispatcher.js').InputDispatcher} input
|
||||
* @param {(event: import('../../input/dispatcher.js').ClickEvent) => void} onClick
|
||||
* Accepted CCTV click callback.
|
||||
* @returns {() => void} Unsubscribe.
|
||||
*/
|
||||
|
||||
function bindCctvWorldClickGesture(handler, onClick, options = {}) {
|
||||
bindTrackingClickGesture(
|
||||
handler,
|
||||
(click, gesture) => {
|
||||
if (!isTrackingClickGesture(gesture)) return;
|
||||
onClick(click);
|
||||
},
|
||||
options,
|
||||
);
|
||||
function bindCctvWorldClickGesture(input, onClick) {
|
||||
return input.onClick((event) => {
|
||||
if (!isTrackingClickGesture(event.gesture)) return;
|
||||
onClick(event);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -79,10 +70,17 @@ export function createSelection({
|
||||
record,
|
||||
)
|
||||
) {
|
||||
// Browser-only feeds have a separate player; a reselect retries it
|
||||
// without re-running activation or touching the projection geometry.
|
||||
if (parts.model.isBrowserOverlayCamera(record.camera)) {
|
||||
layerState._activeCameraReselection += 1;
|
||||
parts.presentation.notifyListeners();
|
||||
}
|
||||
return CCTV_ACTIVATION_RESULT.UNCHANGED;
|
||||
}
|
||||
layerState._activeCameraId = cameraId;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = false;
|
||||
// A real activation creates projection work — wake the self-stopping loop.
|
||||
parts.projection.startProjectionLoop();
|
||||
if (previousActiveRecord && previousActiveRecord !== record) {
|
||||
@@ -112,12 +110,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
|
||||
@@ -141,6 +140,11 @@ export function createSelection({
|
||||
void parts.ground.resolveFootprintGround(record);
|
||||
record.activationDone = true;
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
// The active camera's icon always shows; the previously active one
|
||||
// competes for its cell again. Its coverage neighbours join the working
|
||||
// set and are queued for grounding.
|
||||
parts.rendering.refreshHorizonCulling();
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
// The newly active camera leaves the ambient ring (its monitor plane takes
|
||||
// over); the freed slot re-fills on this same pass.
|
||||
parts.cards.refreshAmbientCards();
|
||||
@@ -164,6 +168,7 @@ export function createSelection({
|
||||
if (!record) return false;
|
||||
layerState._activeCameraId = null;
|
||||
layerState._autoHopSuspended = true;
|
||||
layerState._openingCameraProvisional = false;
|
||||
record.activationDone = false;
|
||||
parts.geometry.clearProbeClampOnDeactivation(record, (previous) => {
|
||||
parts.geometry.applyFrustumGeometry(
|
||||
@@ -171,7 +176,9 @@ export function createSelection({
|
||||
parts.ground.groundAltFor(previous),
|
||||
);
|
||||
});
|
||||
parts.rendering.refreshHorizonCulling();
|
||||
parts.rendering.refreshCoverageStyles();
|
||||
parts.geometryQueue.enqueueViewGeometry();
|
||||
parts.cards.refreshAmbientCards();
|
||||
layerState._gizmo?.refresh();
|
||||
parts.presentation.notifyListeners();
|
||||
@@ -199,57 +206,14 @@ export function createSelection({
|
||||
}
|
||||
|
||||
/**
|
||||
* Extracts a camera ID from a Cesium pick result by checking billboard IDs,
|
||||
* primitive IDs, and entity cctvCameraId properties.
|
||||
* @param {Object|null} picked - Result from scene.pick().
|
||||
* @returns {string|null} Camera ID, or null if the pick is not a CCTV entity.
|
||||
* The camera a scene pick result is, or null: read by the rendering part,
|
||||
* which owns the scene objects the pick names.
|
||||
* @param {Object|null} picked - Result from a scene pick.
|
||||
* @returns {string|null}
|
||||
*/
|
||||
|
||||
function extractPickedCameraId(picked) {
|
||||
if (!picked) return null;
|
||||
|
||||
const entity = picked.id?.properties
|
||||
? picked.id
|
||||
: picked.primitive?.id?.properties
|
||||
? picked.primitive.id
|
||||
: null;
|
||||
const maybeProp = entity?.properties?.cctvCameraId;
|
||||
if (maybeProp) {
|
||||
const value =
|
||||
typeof maybeProp.getValue === 'function'
|
||||
? maybeProp.getValue(Cesium.JulianDate.now())
|
||||
: maybeProp;
|
||||
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;
|
||||
}
|
||||
|
||||
// Camera billboard IDs are intentionally the upstream camera ID, so a
|
||||
// sibling may legitimately use the same string. A bare ID match is not
|
||||
// ownership proof: require this layer's billboard collection or the exact
|
||||
// billboard stored on the record.
|
||||
const directId =
|
||||
typeof picked.id === 'string'
|
||||
? picked.id
|
||||
: typeof picked.primitive?.id === 'string'
|
||||
? picked.primitive.id
|
||||
: null;
|
||||
const record =
|
||||
directId === null ? null : layerState._recordById.get(directId);
|
||||
if (!record) return null;
|
||||
return picked.primitive === layerState._billboards ||
|
||||
picked.primitive === record.billboard
|
||||
? directId
|
||||
: null;
|
||||
return parts.rendering.extractPickedCameraId(picked);
|
||||
}
|
||||
return {
|
||||
getActiveRecord,
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
import { test } from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
|
||||
import { createSelection } from './selection.js';
|
||||
|
||||
function makeSelection(sourceKind) {
|
||||
const camera = { id: 'same-camera', sourceKind };
|
||||
const record = { camera };
|
||||
const state = {
|
||||
_activeCameraId: camera.id,
|
||||
_activeCameraReselection: 0,
|
||||
_recordById: new Map([[camera.id, record]]),
|
||||
};
|
||||
let notifications = 0;
|
||||
const selection = createSelection({
|
||||
state,
|
||||
services: {
|
||||
activation: { CCTV_ACTIVATION_RESULT },
|
||||
picking: { resolvePickId: () => null },
|
||||
},
|
||||
parts: {
|
||||
model: {
|
||||
cctvRecordNeedsActivation: () => false,
|
||||
isBrowserOverlayCamera: (value) =>
|
||||
String(value?.sourceKind || '').startsWith('quebec-'),
|
||||
},
|
||||
presentation: { notifyListeners: () => notifications++ },
|
||||
},
|
||||
source: {},
|
||||
});
|
||||
return { selection, state, notifications: () => notifications };
|
||||
}
|
||||
|
||||
test('same-camera selection does not notify or mutate snapshot-feed state', () => {
|
||||
const fixture = makeSelection('tripcheck-odot');
|
||||
|
||||
assert.equal(
|
||||
fixture.selection.setActiveCamera('same-camera'),
|
||||
CCTV_ACTIVATION_RESULT.UNCHANGED,
|
||||
);
|
||||
assert.equal(fixture.state._activeCameraReselection, 0);
|
||||
assert.equal(fixture.notifications(), 0);
|
||||
});
|
||||
|
||||
test('same-camera selection notifies browser-overlay feeds so playback can retry', () => {
|
||||
const fixture = makeSelection('quebec-511-browser');
|
||||
|
||||
assert.equal(
|
||||
fixture.selection.setActiveCamera('same-camera'),
|
||||
CCTV_ACTIVATION_RESULT.UNCHANGED,
|
||||
);
|
||||
assert.equal(fixture.state._activeCameraReselection, 1);
|
||||
assert.equal(fixture.notifications(), 1);
|
||||
});
|
||||
@@ -1,6 +1,7 @@
|
||||
import test from 'node:test';
|
||||
import assert from 'node:assert/strict';
|
||||
import { createCctvSource, createCctvLayer } from './index.js';
|
||||
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
|
||||
|
||||
const camera = {
|
||||
id: 'pack/camera ?x',
|
||||
@@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
|
||||
setOverlayEntries: noop,
|
||||
setOverlaySourceVisible: noop,
|
||||
},
|
||||
sprites: { registerSpriteCollection: noop },
|
||||
sprites: {},
|
||||
activation: {},
|
||||
locations: {},
|
||||
picking: { unregisterPickOwner: noop },
|
||||
@@ -134,9 +135,9 @@ test('camera construction is inert and destruction cancels a pending catalog and
|
||||
const a = createCctvLayer({ services, source });
|
||||
const b = createCctvLayer({ services, source });
|
||||
assert.equal(listeners.size, 0);
|
||||
const viewer = {
|
||||
scene: { primitives: { add: (value) => value, remove: () => true } },
|
||||
};
|
||||
const viewer = {};
|
||||
const { unbind } = bindFakeDraw(viewer);
|
||||
t.after(unbind);
|
||||
const initializing = a.init(viewer);
|
||||
assert.equal(listeners.size, 1);
|
||||
assert.equal(signal.aborted, false);
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
export const FRAME_ENDPOINT = '/api/cctv/frame';
|
||||
|
||||
export const SOURCE_ENDPOINT = '/api/cctv/sources';
|
||||
|
||||
export const HEALTH_ENDPOINT = '/api/cctv/health';
|
||||
|
||||
export const MEDIA_ENDPOINT = '/api/cctv/media';
|
||||
|
||||
export const ACTIVE_FRAME_REFRESH_MS = 10000;
|
||||
+72
-15
@@ -1,5 +1,3 @@
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
export function createState({ services }) {
|
||||
const {
|
||||
clearOverlaySource,
|
||||
@@ -15,7 +13,8 @@ export function createState({ services }) {
|
||||
|
||||
layerState._viewer = null;
|
||||
|
||||
layerState._billboards = null;
|
||||
/** The catalog's camera icons: the icon book over their draw set. */
|
||||
layerState._icons = null;
|
||||
|
||||
layerState._records = [];
|
||||
|
||||
@@ -29,6 +28,10 @@ export function createState({ services }) {
|
||||
|
||||
layerState._activeCameraId = null;
|
||||
|
||||
// Advances when a user reselects the already-active camera. The geometry
|
||||
// activation remains a no-op, but browser-only camera UI can retry playback.
|
||||
layerState._activeCameraReselection = 0;
|
||||
|
||||
layerState._coverageMode = 'on';
|
||||
// 'off' | 'on' (wireframes) | 'viewshed' (color-coded volumes)
|
||||
|
||||
@@ -36,6 +39,12 @@ export function createState({ services }) {
|
||||
|
||||
layerState._autoHop = false;
|
||||
|
||||
// True while the active camera is the one enable() opened on and nobody has
|
||||
// chosen a camera since: each settled move then re-picks the one nearest
|
||||
// the view, so a share flight that lands after enable still opens nearby.
|
||||
|
||||
layerState._openingCameraProvisional = false;
|
||||
|
||||
// An explicit empty-space deselect keeps AUTO HOP configured but prevents its
|
||||
// timer from silently choosing a replacement. A later explicit activation or
|
||||
// AUTO HOP toggle-on releases the hold.
|
||||
@@ -48,7 +57,7 @@ export function createState({ services }) {
|
||||
|
||||
layerState._lastViewContext = '';
|
||||
|
||||
layerState._clickHandler = null;
|
||||
layerState._clickSubscription = null;
|
||||
|
||||
layerState._count = 0;
|
||||
|
||||
@@ -74,7 +83,61 @@ export function createState({ services }) {
|
||||
|
||||
layerState._activeFocusStyleCount = 0;
|
||||
|
||||
layerState._scratchFocusScreen = new Cesium.Cartesian2();
|
||||
// The view pass's screen-point scratch: its projection writes only x and y.
|
||||
layerState._scratchViewScreen = { x: 0, y: 0 };
|
||||
|
||||
// Counts view passes; a record shown by the latest pass carries its number.
|
||||
|
||||
layerState._viewPassId = 0;
|
||||
|
||||
// Records whose icons the last view pass showed (see refreshHorizonCulling):
|
||||
// geometry refinement, the tiles-ready completion pass and ambient cards
|
||||
// work over these, not the whole catalog.
|
||||
|
||||
layerState._viewRecords = [];
|
||||
|
||||
// Coverage ids refreshCoverageStyles last drew: part of the geometry
|
||||
// working set even when their icons are thinned out.
|
||||
|
||||
layerState._coverageVisibleIds = new Set();
|
||||
|
||||
// View pass triggers besides camera settle: an interval while the camera
|
||||
// moves, and a canvas resize observer.
|
||||
|
||||
layerState._viewMotionTimer = 0;
|
||||
|
||||
layerState._viewResizeObserver = null;
|
||||
|
||||
layerState._viewResizeCanvas = null;
|
||||
|
||||
// The camera port the moveStart/moveEnd listeners are on.
|
||||
|
||||
layerState._viewListenerCamera = null;
|
||||
|
||||
// A motion pass changed the shown set and the settle pass has not yet told
|
||||
// subscribers; the camera pose the last view pass ran at.
|
||||
|
||||
layerState._viewUnpublished = false;
|
||||
|
||||
layerState._viewPose = null;
|
||||
|
||||
// { at, ms } — when the last motion pass ran and what it cost.
|
||||
|
||||
layerState._viewMotionPass = null;
|
||||
|
||||
// Retries the view geometry a drain left unresolved, once cells warm.
|
||||
|
||||
layerState._viewGeometryRetryTimer = 0;
|
||||
|
||||
// { key, count } — the active camera's coverage-overlap count, which the
|
||||
// summary reads on every notification.
|
||||
|
||||
layerState._neighborCountCache = null;
|
||||
|
||||
// { view, active, list } — the camera picker's index uiState publishes,
|
||||
// rebuilt only when the view pass or the active camera changes.
|
||||
|
||||
layerState._cameraIndexCache = null;
|
||||
|
||||
// Staggered geometry-load queue state (see startGeometryLoadQueue).
|
||||
|
||||
@@ -107,16 +170,9 @@ export function createState({ services }) {
|
||||
|
||||
layerState._lastTransientNotifyAt = 0;
|
||||
|
||||
// Cached handle on the active Google Photorealistic 3D Tileset, discovered
|
||||
// lazily from scene.primitives. Shared mesh-floor sampling is gated on its
|
||||
// tilesLoaded flag so a coarse-LOD miss is never baked in. Cleared when the
|
||||
// tileset is destroyed / the layer tears down.
|
||||
|
||||
layerState._activeTileset = null;
|
||||
|
||||
// Task 5: last surface regime the record geometry was recomputed for. The
|
||||
// map-stack change listener compares the CURRENT regime (derived live from
|
||||
// scene.globe.show) against this so bing→osm switches (same 'terrain-globe'
|
||||
// whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe'
|
||||
// regime) don't trigger a pointless full-catalog rewrite.
|
||||
|
||||
layerState._lastAppliedRegime = null;
|
||||
@@ -126,8 +182,8 @@ export function createState({ services }) {
|
||||
|
||||
layerState._mapStackListener = null;
|
||||
|
||||
// Field-test fix (2026-07-06): camera.moveEnd handle for the horizon-culling
|
||||
// pass (removed in destroy). Event-driven only — never a per-frame loop, so
|
||||
// Field-test fix (2026-07-06): the Off of the camera's moveEnd listener for
|
||||
// the horizon-culling pass (called in destroy). Event-driven only — never a per-frame loop, so
|
||||
// the zero-steady-state-work invariant holds.
|
||||
|
||||
layerState._horizonCullListener = null;
|
||||
@@ -202,6 +258,7 @@ export function createState({ services }) {
|
||||
|
||||
layerState._cameraMoving = false;
|
||||
|
||||
// The Off of the camera's moveStart listener.
|
||||
layerState._moveStartListener = null;
|
||||
layerState._sourceAbort = null;
|
||||
return layerState;
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
import * as Cesium from 'cesium';
|
||||
import { createIconBook } from '../../render/motion/iconBook.js';
|
||||
|
||||
/** A draw set that draws nothing, for the icon book the tests read. */
|
||||
const testIconSet = () => ({
|
||||
id: 'cctv:test:icons',
|
||||
show: true,
|
||||
upsert() {},
|
||||
remove() {},
|
||||
dispose() {},
|
||||
});
|
||||
|
||||
export function createTesting({ state: layerState, services, parts, source }) {
|
||||
/** Test seam: republishes host entries through the real push path, so tests
|
||||
@@ -19,7 +28,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.
|
||||
*/
|
||||
@@ -34,15 +43,16 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
record.probeClampRangeM,
|
||||
);
|
||||
const positions =
|
||||
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
|
||||
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
|
||||
record.frustumGeometry = geometry;
|
||||
record.frustumPositions = positions;
|
||||
const runtime = {
|
||||
cameraId: String(record.camera.id),
|
||||
planeEntity: null,
|
||||
labelPosition: new Cesium.Cartesian3(),
|
||||
plane: null,
|
||||
// createProjectionPlane gives it its label position.
|
||||
labelPosition: null,
|
||||
overlayEntry: null,
|
||||
planeMaterial: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
|
||||
planeSource: parts.projection.plainPlaneSource(),
|
||||
};
|
||||
parts.projection.createProjectionPlane(
|
||||
record,
|
||||
@@ -79,6 +89,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
* @param {boolean} [options.enabled=true] Layer enabled state.
|
||||
* @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode.
|
||||
* @param {boolean} [options.showProjection=false] Projection visibility.
|
||||
* @param {Map<string, Object>} [options.healthById] Health rows by camera id.
|
||||
* @returns {void}
|
||||
*/
|
||||
|
||||
@@ -89,6 +100,8 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
enabled = true,
|
||||
coverageMode = 'on',
|
||||
showProjection = false,
|
||||
healthById = new Map(),
|
||||
openingCameraProvisional = false,
|
||||
} = {}) {
|
||||
layerState._viewer = viewer;
|
||||
layerState._records = Array.isArray(records) ? records : [];
|
||||
@@ -99,15 +112,56 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
);
|
||||
layerState._coverageEntities = [];
|
||||
layerState._projectionEntities = [];
|
||||
layerState._billboards = null;
|
||||
layerState._activeCameraId = activeCameraId;
|
||||
layerState._autoHopSuspended = false;
|
||||
layerState._openingCameraProvisional = !!openingCameraProvisional;
|
||||
layerState._enabled = !!enabled;
|
||||
layerState._coverageMode = parts.model.normalizeCoverageMode(
|
||||
coverageMode,
|
||||
'on',
|
||||
);
|
||||
layerState._showProjection = !!showProjection;
|
||||
layerState._healthById = healthById;
|
||||
layerState._viewRecords = [];
|
||||
layerState._cameraIndexCache = null;
|
||||
layerState._coverageVisibleIds = new Set();
|
||||
layerState._neighborCountCache = null;
|
||||
// A real book (over a set that draws nothing): every record gets its
|
||||
// icon as init adds it.
|
||||
layerState._icons = createIconBook(testIconSet());
|
||||
for (const record of layerState._records)
|
||||
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
|
||||
}
|
||||
|
||||
/**
|
||||
* 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() {
|
||||
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 book, for tests that read what the icons draw. */
|
||||
|
||||
function _cctvIconsForTest() {
|
||||
return layerState._icons;
|
||||
}
|
||||
return {
|
||||
_pushAmbientCardEntriesForTest,
|
||||
@@ -116,5 +170,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
|
||||
_updateCctvProjectionPlaneForTest,
|
||||
_extractPickedCameraIdForTest,
|
||||
_setCctvCoverageStateForTest,
|
||||
_cctvIconsForTest,
|
||||
_cctvDrawnForTest,
|
||||
};
|
||||
}
|
||||
Reference in new issue
Block a user