Merge branch 'sameh/renderer-cctv' into sameh/renderer-seam

This commit is contained in:
Sameh Khamis committed 2026-11-08 09:45:47 -08:00
commit 3fa1ad0283
41 files changed
+3099 -1227

No files matched your search

+37 -3
View File
@@ -1063,6 +1063,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -1836,6 +1838,8 @@
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/effects.js", "src/render/cesium/effects.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -1927,6 +1931,8 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2022,6 +2028,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2091,6 +2099,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2178,6 +2188,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2383,6 +2395,8 @@
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/cameraInput.js", "src/render/cesium/cameraInput.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2504,6 +2518,7 @@
"src/layers/cctv/health.js", "src/layers/cctv/health.js",
"src/layers/cctv/hover.js", "src/layers/cctv/hover.js",
"src/layers/cctv/index.js", "src/layers/cctv/index.js",
"src/layers/cctv/drawSets.js",
"src/geo/frames.js", "src/geo/frames.js",
"src/layers/cctv/ingestion.js", "src/layers/cctv/ingestion.js",
"src/layers/cctv/lifecycle.js", "src/layers/cctv/lifecycle.js",
@@ -2517,6 +2532,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2539,6 +2556,8 @@
"src/layers/cctv/projection.js", "src/layers/cctv/projection.js",
"src/layers/cctv/videoPlayback.js", "src/layers/cctv/videoPlayback.js",
"src/layers/cctv/rendering.js", "src/layers/cctv/rendering.js",
"src/render/motion/iconBook.js",
"src/geo/frustum.js",
"src/render/cesium/iconOrientation.js", "src/render/cesium/iconOrientation.js",
"src/render/cesium/iconSetPrimitive.js", "src/render/cesium/iconSetPrimitive.js",
"src/data/iconSet.js", "src/data/iconSet.js",
@@ -2548,7 +2567,6 @@
"src/data/aircraftRecession.js", "src/data/aircraftRecession.js",
"src/data/motionModel.js", "src/data/motionModel.js",
"src/layers/cctv/selection.js", "src/layers/cctv/selection.js",
"src/layers/cctv/pickState.js",
"src/layers/cctv/source.js", "src/layers/cctv/source.js",
"src/layers/cctv/state.js", "src/layers/cctv/state.js",
"src/layers/cctv/testing.js", "src/layers/cctv/testing.js",
@@ -2806,6 +2824,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/queries/heights.js", "src/queries/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -2984,6 +3004,8 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -3214,6 +3236,8 @@
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/quality.js", "src/render/cesium/quality.js",
@@ -3437,6 +3461,7 @@
"src/layers/cctv/health.js", "src/layers/cctv/health.js",
"src/layers/cctv/hover.js", "src/layers/cctv/hover.js",
"src/layers/cctv/index.js", "src/layers/cctv/index.js",
"src/layers/cctv/drawSets.js",
"src/layers/launches/geometry.js", "src/layers/launches/geometry.js",
"src/layers/cctv/ingestion.js", "src/layers/cctv/ingestion.js",
"src/layers/cctv/lifecycle.js", "src/layers/cctv/lifecycle.js",
@@ -3449,7 +3474,6 @@
"src/layers/cctv/videoPlayback.js", "src/layers/cctv/videoPlayback.js",
"src/layers/cctv/rendering.js", "src/layers/cctv/rendering.js",
"src/layers/cctv/selection.js", "src/layers/cctv/selection.js",
"src/layers/cctv/pickState.js",
"src/layers/cctv/source.js", "src/layers/cctv/source.js",
"src/layers/cctv/state.js", "src/layers/cctv/state.js",
"src/layers/cctv/testing.js", "src/layers/cctv/testing.js",
@@ -4221,6 +4245,8 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -4398,6 +4424,7 @@
"src/layers/cctv/health.js", "src/layers/cctv/health.js",
"src/layers/cctv/hover.js", "src/layers/cctv/hover.js",
"src/layers/cctv/index.js", "src/layers/cctv/index.js",
"src/layers/cctv/drawSets.js",
"src/layers/launches/geometry.js", "src/layers/launches/geometry.js",
"src/layers/cctv/ingestion.js", "src/layers/cctv/ingestion.js",
"src/layers/cctv/lifecycle.js", "src/layers/cctv/lifecycle.js",
@@ -4411,7 +4438,6 @@
"src/layers/cctv/rendering.js", "src/layers/cctv/rendering.js",
"src/render/cesium/iconOrientation.js", "src/render/cesium/iconOrientation.js",
"src/layers/cctv/selection.js", "src/layers/cctv/selection.js",
"src/layers/cctv/pickState.js",
"src/layers/cctv/source.js", "src/layers/cctv/source.js",
"src/layers/cctv/state.js", "src/layers/cctv/state.js",
"src/layers/cctv/testing.js", "src/layers/cctv/testing.js",
@@ -4909,6 +4935,8 @@
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/render/cesium/drawHit.js", "src/render/cesium/drawHit.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -5586,6 +5614,8 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -5737,6 +5767,8 @@
"src/render/cesium/credits.js", "src/render/cesium/credits.js",
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
@@ -5996,6 +6028,8 @@
"src/render/cesium/query.js", "src/render/cesium/query.js",
"src/render/cesium/heights.js", "src/render/cesium/heights.js",
"src/render/cesium/draw.js", "src/render/cesium/draw.js",
"src/render/cesium/drawQuads.js",
"src/render/cesium/drawMeshes.js",
"src/render/cesium/drawModels.js", "src/render/cesium/drawModels.js",
"src/geo/polyline.js", "src/geo/polyline.js",
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
+61 -67
View File
@@ -263,32 +263,30 @@ function installRenderFramesHelper(page) {
// In-page helper (stringified and re-defined inside each evaluate that needs // In-page helper (stringified and re-defined inside each evaluate that needs
// it, since functions can't cross the puppeteer boundary): serializes the // it, since functions can't cross the puppeteer boundary): serializes the
// 5 frustum polylines + plane position/orientation/dimensions for a camera // 5 frustum lines + plane position/orientation/dimensions for a camera
// into plain arrays of numbers, using only the camera's own clock time (no // into plain arrays of numbers, from what the layer reports it draws.
// Cesium namespace needed — Property.getValue just needs *a* JulianDate,
// and the viewer's own clock.currentTime is a valid live instance of one).
const SERIALIZE_GEOM_SRC = ` const SERIALIZE_GEOM_SRC = `
function serializeGeom(camId) { function serializeGeom(camId) {
const viewer = window.__godsEyeView.viewer; const drawn = window.__godsEyeView.dataManager.layers
const time = viewer.clock.currentTime; .get('cctv')
.module._cctvDrawnForTest();
const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap']; const roles = ['ray-tl', 'ray-tr', 'ray-br', 'ray-bl', 'cap'];
const poly = {}; const poly = {};
for (const role of roles) { for (const role of roles) {
const ent = viewer.entities.getById('cctv-' + camId + '-' + role); const line = drawn.coverage['cctv-' + camId + '-' + role];
poly[role] = ent && ent.polyline poly[role] = line?.positions
? ent.polyline.positions.getValue(time).map((p) => [p.x, p.y, p.z]) ? line.positions.map((p) => [p.x, p.y, p.z])
: null; : null;
} }
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); const quad = drawn.planes['cctv-' + camId + '-plane'];
let plane = null; let plane = null;
if (planeEnt) { if (quad) {
const pos = planeEnt.position.getValue(time); const pos = quad.center;
const orient = planeEnt.orientation.getValue(time); const orient = quad.orientation;
const dims = planeEnt.plane.dimensions.getValue(time);
plane = { plane = {
position: [pos.x, pos.y, pos.z], position: [pos.x, pos.y, pos.z],
orientation: [orient.x, orient.y, orient.z, orient.w], orientation: [orient.x, orient.y, orient.z, orient.w],
dimensions: [dims.x, dims.y], dimensions: [quad.size[0], quad.size[1]],
}; };
} }
return { poly, plane }; return { poly, plane };
@@ -695,10 +693,9 @@ async function main() {
const camera = dataManager.layers const camera = dataManager.layers
.get('cctv') .get('cctv')
.module.getUIState().activeCamera; .module.getUIState().activeCamera;
const ray = viewer.entities.getById(`cctv-${camera.id}-ray-tl`); const ray = dataManager.layers.get('cctv').module._cctvDrawnForTest()
const mount = ray?.polyline?.positions.getValue( .coverage[`cctv-${camera.id}-ray-tl`];
viewer.clock.currentTime, const mount = ray?.positions?.[0];
)?.[0];
const height = const height =
mount && mount &&
viewer.scene.globe.ellipsoid.cartesianToCartographic(mount) viewer.scene.globe.ellipsoid.cartesianToCartographic(mount)
@@ -849,8 +846,10 @@ async function main() {
// source. Assert the migrated surface via the host diagnostics. // source. Assert the migrated surface via the host diagnostics.
const diag = window.__gevWorldOverlay?.getDiagnostics?.(); const diag = window.__gevWorldOverlay?.getDiagnostics?.();
g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1; g.hasLabel = (diag?.entriesBySource?.['cctv-projection'] || 0) >= 1;
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); const quad = window.__godsEyeView.dataManager.layers
g.planeShow = planeEnt ? planeEnt.show : null; .get('cctv')
.module._cctvDrawnForTest().planes['cctv-' + camId + '-plane'];
g.planeShow = quad ? quad.show : null;
return g; return g;
})(${JSON.stringify(activeId)})`); })(${JSON.stringify(activeId)})`);
@@ -1212,26 +1211,22 @@ async function main() {
console.log( console.log(
'Checking frame-loop health (placeholder -> frame swap, URL family)...', 'Checking frame-loop health (placeholder -> frame swap, URL family)...',
); );
// The plane's material.image is always defined (placeholder canvas from // The plane's image is always defined (placeholder canvas from the
// the moment the runtime is created, real frame content painted onto the // moment the runtime is created, real frame content painted onto the
// same canvas/video reference once the fetch resolves) — assert it's // same canvas/video reference once the fetch resolves) — assert it's
// never null/undefined once the runtime exists, i.e. there's no gap where // never null/undefined once the runtime exists, i.e. there's no gap where
// the plane shows nothing. // the plane shows nothing.
const materialInfo = await page.evaluate((camId) => { const materialInfo = await page.evaluate((camId) => {
const viewer = window.__godsEyeView.viewer; const quad = window.__godsEyeView.dataManager.layers
const time = viewer.clock.currentTime; .get('cctv')
const planeEnt = viewer.entities.getById('cctv-' + camId + '-plane'); .module._cctvDrawnForTest().planes['cctv-' + camId + '-plane'];
const mat = planeEnt?.plane?.material; const source = quad?.source;
const image = mat?.image; const resolved = source?.video || source?.canvas || source?.image;
const resolved =
image && typeof image.getValue === 'function'
? image.getValue(time)
: image;
return { return {
hasMaterial: !!mat, hasMaterial: !!source,
hasImage: !!resolved, hasImage: !!resolved,
tagName: resolved?.tagName || null, tagName: resolved?.tagName || null,
show: planeEnt?.show, show: quad?.show,
}; };
}, activeId); }, activeId);
record( record(
@@ -1665,14 +1660,12 @@ async function main() {
'Checking viewshed mode (coverage tri-state + color-coded volumes)...', 'Checking viewshed mode (coverage tri-state + color-coded volumes)...',
); );
const countVolumes = () => const countVolumes = () =>
page.evaluate(() => { page.evaluate(
const prims = window.__godsEyeView.viewer.scene.primitives; () =>
let n = 0; window.__godsEyeView.dataManager.layers
for (let i = 0; i < prims.length; i++) { .get('cctv')
if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) n += 1; .module._cctvDrawnForTest().viewsheds.length,
} );
return n;
});
const cBeforeViewshed = await readCounters(); const cBeforeViewshed = await readCounters();
const modeAfterSet = await page.evaluate(() => { const modeAfterSet = await page.evaluate(() => {
@@ -1725,26 +1718,26 @@ async function main() {
mod.setParams({ coverageMode: 'viewshed' }); mod.setParams({ coverageMode: 'viewshed' });
}); });
await sleep(400); await sleep(400);
await page.evaluate(() => { // Volumes are draw-port mesh items: "no churn" is no volume written.
const prims = window.__godsEyeView.viewer.scene.primitives; const drawnViewsheds = () =>
window.__qaViewshedRefs = []; page.evaluate(() => {
for (let i = 0; i < prims.length; i++) { const drawn = window.__godsEyeView.dataManager.layers
if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) .get('cctv')
window.__qaViewshedRefs.push(prims.get(i)); .module._cctvDrawnForTest();
} return { ids: drawn.viewsheds, writes: drawn.viewshedWrites };
}); });
const viewshedsBefore = await drawnViewsheds();
await sleep(8000); await sleep(8000);
const viewshedIdle = await page.evaluate(() => { const viewshedsAfter = await drawnViewsheds();
const prims = window.__godsEyeView.viewer.scene.primitives; const viewshedIdle = (() => {
const now = []; const sameCount =
for (let i = 0; i < prims.length; i++) { viewshedsAfter.ids.length === viewshedsBefore.ids.length;
if (window.__godsEyeView.entityRecords.read(prims.get(i))?.viewshedCameraId) now.push(prims.get(i)); const sameIdentity =
} sameCount &&
const before = window.__qaViewshedRefs || []; viewshedsBefore.ids.every((id) => viewshedsAfter.ids.includes(id)) &&
const sameCount = now.length === before.length; viewshedsAfter.writes === viewshedsBefore.writes;
const sameIdentity = sameCount && before.every((p) => now.includes(p)); return { sameCount, sameIdentity, count: viewshedsAfter.ids.length };
return { sameCount, sameIdentity, count: now.length }; })();
});
const cAfterViewshed = await readCounters(); const cAfterViewshed = await readCounters();
const lateFloorSamples = const lateFloorSamples =
cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight; cAfterViewshed.sampleHeight - cBeforeViewshed.sampleHeight;
@@ -1785,9 +1778,9 @@ async function main() {
const gizmoStates = await page.evaluate((parts) => { const gizmoStates = await page.evaluate((parts) => {
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
mod.setParams({ calibrationMode: true }); mod.setParams({ calibrationMode: true });
const viewer = window.__godsEyeView.viewer; const drawn = mod._cctvDrawnForTest().gizmo;
return parts.map((p) => { return parts.map((p) => {
const e = viewer.entities.getById('cctv-gizmo-' + p); const e = drawn['cctv-gizmo-' + p];
return e ? (e.show ? 'shown' : 'hidden') : 'missing'; return e ? (e.show ? 'shown' : 'hidden') : 'missing';
}); });
}, GIZMO_PARTS); }, GIZMO_PARTS);
@@ -1802,9 +1795,10 @@ async function main() {
// stay frozen until release, with no transient sampleHeight calls. // stay frozen until release, with no transient sampleHeight calls.
const eastDrag = await page.evaluate(() => { const eastDrag = await page.evaluate(() => {
const viewer = window.__godsEyeView.viewer; const viewer = window.__godsEyeView.viewer;
const e = viewer.entities.getById('cctv-gizmo-move-east'); const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
const e = mod._cctvDrawnForTest().gizmo['cctv-gizmo-move-east'];
if (!e) return null; if (!e) return null;
const pts = e.polyline.positions.getValue(viewer.clock.currentTime); const pts = e.positions;
const scene = viewer.scene; const scene = viewer.scene;
const w = scene.canvas.clientWidth; const w = scene.canvas.clientWidth;
const h = scene.canvas.clientHeight; const h = scene.canvas.clientHeight;
@@ -2082,9 +2076,9 @@ async function main() {
const mod = window.__godsEyeView.dataManager.layers.get('cctv').module; const mod = window.__godsEyeView.dataManager.layers.get('cctv').module;
mod.setParams({ calibrationMode: false }); mod.setParams({ calibrationMode: false });
mod.setParams({ calibration: { reset: true } }); mod.setParams({ calibration: { reset: true } });
const viewer = window.__godsEyeView.viewer; const drawn = mod._cctvDrawnForTest().gizmo;
return parts.map((p) => { return parts.map((p) => {
const e = viewer.entities.getById('cctv-gizmo-' + p); const e = drawn['cctv-gizmo-' + p];
return e ? (e.show ? 'shown' : 'hidden') : 'missing'; return e ? (e.show ? 'shown' : 'hidden') : 'missing';
}); });
}, GIZMO_PARTS); }, GIZMO_PARTS);
+117 -77
View File
@@ -81,7 +81,7 @@ import {
IDLE_CAMERA_COLOR, IDLE_CAMERA_COLOR,
LIVE_CAMERA_COLOR, LIVE_CAMERA_COLOR,
} from '../layers/cctv/policy.js'; } from '../layers/cctv/policy.js';
import { cctvPicks } from '../layers/cctv/pickState.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
const ASPECT = 16 / 9; const ASPECT = 16 / 9;
@@ -277,15 +277,9 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
coverageEntities: [], coverageEntities: [],
projection: null, projection: null,
})); }));
const inserted = []; const viewer = {};
const viewer = { const { draw, unbind } = bindFakeDraw(viewer);
entities: { const inserted = () => draw.find('cctv:')?.items ?? new Map();
add(entity) {
inserted.push(entity);
return entity;
},
},
};
const activeRecord = records.at(-1); const activeRecord = records.at(-1);
try { try {
@@ -300,10 +294,16 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
(record) => record.coverageEntities.length > 0, (record) => record.coverageEntities.length > 0,
); );
assert.equal( assert.equal(
inserted.length, inserted().size,
14 * 5, 14 * 5,
'default COVERAGE ON builds the 14-camera visible cohort', 'default COVERAGE ON builds the 14-camera visible cohort',
); );
assert.ok(
[...inserted().keys()].every((id) =>
/^cctv-cam-\d+-(ray-..|cap)$/.test(id),
),
'coverage lines keep the cctv-<id>-<role> ids',
);
assert.equal(materialized.length, 14); assert.equal(materialized.length, 14);
assert.equal( assert.equal(
activeRecord.coverageEntities.length, activeRecord.coverageEntities.length,
@@ -319,7 +319,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
...records[0], ...records[0],
camera: { ...records[0].camera, id: 'projection-only' }, camera: { ...records[0].camera, id: 'projection-only' },
coverageEntities: [], coverageEntities: [],
projection: { planeEntity: { show: false } }, projection: { plane: { show: false } },
}; };
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer, viewer,
@@ -334,21 +334,31 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
projectionOnly.coverageEntities.every((entity) => entity.show), projectionOnly.coverageEntities.every((entity) => entity.show),
'COVERAGE OFF keeps the active projection frustum materialized and visible', 'COVERAGE OFF keeps the active projection frustum materialized and visible',
); );
assert.ok(
projectionOnly.coverageEntities.every(
(entity) => inserted().get(entity.id)?.show === true,
),
'and draws it',
);
} finally { } finally {
_setCctvCoverageStateForTest({ enabled: false }); _setCctvCoverageStateForTest({ enabled: false });
unbind();
} }
}); });
test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { test('camera icons are violet for video feeds, cyan for stills, amber when active', () => {
const record = (id, feedType) => ({ const record = (id, feedType) => ({
camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 },
// Every catalog record is placed as it is made, and drawn there.
position: { x: 6378137, y: 0, z: 0 },
coverageEntities: [], coverageEntities: [],
projection: null, projection: null,
}); });
const idleVideo = record('idle-hls', 'hls'); const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image'); const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls'); const activeVideo = record('active-hls', 'hls');
const viewer = { entities: { add: (entity) => entity } }; const viewer = {};
const { unbind } = bindFakeDraw(viewer);
try { try {
// Disabled keeps the active video camera from opening a real projection; // Disabled keeps the active video camera from opening a real projection;
@@ -362,20 +372,15 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
}); });
refreshCoverageStyles(); refreshCoverageStyles();
const icons = _cctvIconsForTest(); const icons = _cctvIconsForTest();
const color = (record) => icons.color(icons.row(record.camera.id)); const color = (record) => icons.item(record.camera.id).color;
const bytes = (c) => assert.deepEqual(color(idleVideo), LIVE_CAMERA_COLOR);
[c.red, c.green, c.blue, c.alpha].map(Cesium.Color.floatToByte); assert.deepEqual(color(idleStill), IDLE_CAMERA_COLOR);
const policyBytes = (rgba) => rgba.map(Cesium.Color.floatToByte); assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR);
assert.deepEqual(bytes(color(idleVideo)), policyBytes(LIVE_CAMERA_COLOR)); assert.equal(icons.item(activeVideo.camera.id).scale, 1.25);
assert.deepEqual(bytes(color(idleStill)), policyBytes(IDLE_CAMERA_COLOR)); assert.equal(icons.item(idleVideo.camera.id).scale, 1);
assert.deepEqual(
bytes(color(activeVideo)),
policyBytes(ACTIVE_CAMERA_COLOR),
);
assert.equal(icons.scale(icons.row(activeVideo.camera.id)), 1.25);
assert.equal(icons.scale(icons.row(idleVideo.camera.id)), 1);
} finally { } finally {
_setCctvCoverageStateForTest({ enabled: false }); _setCctvCoverageStateForTest({ enabled: false });
unbind();
} }
}); });
@@ -679,15 +684,15 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
activationDone: true, activationDone: true,
probeClampRangeM: 105, probeClampRangeM: 105,
coverageEntities: [{ show: true }, { show: true }], coverageEntities: [{ show: true }, { show: true }],
projection: { planeEntity: { show: true } }, projection: { plane: { show: true } },
viewshedPrimitive: viewshedA, viewshedVolume: viewshedA,
}, },
{ {
camera: { id: 'b' }, camera: { id: 'b' },
activationDone: true, activationDone: true,
probeClampRangeM: 146, probeClampRangeM: 146,
projection: null, projection: null,
viewshedPrimitive: viewshedB, viewshedVolume: viewshedB,
}, },
]; ];
const destroyed = []; const destroyed = [];
@@ -696,7 +701,7 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
records, records,
(record) => { (record) => {
destroyed.push(record.camera.id); destroyed.push(record.camera.id);
record.viewshedPrimitive = null; record.viewshedVolume = null;
}, },
'a', 'a',
); );
@@ -707,10 +712,10 @@ test('CCTV disable hide sweep hides record visuals and destroys viewsheds withou
), ),
[false, false], [false, false],
); );
assert.equal(records[0].projection.planeEntity.show, false); assert.equal(records[0].projection.plane.show, false);
assert.deepEqual(destroyed, ['a', 'b']); assert.deepEqual(destroyed, ['a', 'b']);
assert.equal(records[0].viewshedPrimitive, null); assert.equal(records[0].viewshedVolume, null);
assert.equal(records[1].viewshedPrimitive, null); assert.equal(records[1].viewshedVolume, null);
assert.deepEqual( assert.deepEqual(
records.map((record) => record.probeClampRangeM), records.map((record) => record.probeClampRangeM),
[null, null], [null, null],
@@ -728,7 +733,8 @@ test('real active monitor plane owns one protected host label and no native labe
setVisible: (...args) => calls.push(['visible', ...args]), setVisible: (...args) => calls.push(['visible', ...args]),
clearSource: (...args) => calls.push(['clear', ...args]), clearSource: (...args) => calls.push(['clear', ...args]),
}; };
const viewer = { entities: new Cesium.EntityCollection() }; const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const record = { const record = {
camera: { camera: {
...UNCLAMPED_CAMERA, ...UNCLAMPED_CAMERA,
@@ -752,17 +758,23 @@ test('real active monitor plane owns one protected host label and no native labe
}); });
refreshCoverageStyles(); refreshCoverageStyles();
assert.ok(runtime.plane, 'runtime guard requires a real monitor plane');
const planes = draw.find('cctv:')
? [...draw.sets.values()].filter((set) => set.kind === 'quads')
: [];
assert.equal(planes.length, 1, 'the plane draws as a quad');
const quad = planes[0].items.get(`cctv-${record.camera.id}-plane`);
assert.ok(quad, 'under its cctv-<id>-plane id');
assert.equal(quad.alpha, 0.95);
assert.deepEqual(quad.size, [
record.frustumGeometry.halfW * 2,
record.frustumGeometry.halfH * 2,
]);
assert.ok(quad.outline, 'with its outline');
assert.equal(quad.meta.cameraId, record.camera.id);
assert.ok( assert.ok(
runtime.planeEntity, [...draw.sets.values()].every((set) => set.kind !== 'labels'),
'runtime guard requires a real monitor-plane entity', 'and no native label',
);
assert.equal(runtime.planeEntity.label, undefined);
assert.ok(
runtime.planeEntity.plane,
'monitor plane geometry remains native',
);
assert.ok(
viewer.entities.values.every((entity) => entity.label === undefined),
); );
const publication = calls.find( const publication = calls.find(
([type, sourceId]) => ([type, sourceId]) =>
@@ -778,7 +790,8 @@ test('real active monitor plane owns one protected host label and no native labe
assert.equal(entry.position(), runtime.labelPosition); assert.equal(entry.position(), runtime.labelPosition);
assert.equal(entry.protected, true); assert.equal(entry.protected, true);
assert.equal(entry.paintLane, 'selected'); assert.equal(entry.paintLane, 'selected');
assert.equal(runtime.planeEntity.show, true); assert.equal(runtime.plane.show, true);
assert.equal(quad.show, true, 'shown once projected');
const cachedPosition = runtime.labelPosition; const cachedPosition = runtime.labelPosition;
record.frustumPositions.label = Cesium.Cartesian3.add( record.frustumPositions.label = Cesium.Cartesian3.add(
@@ -806,7 +819,8 @@ test('real active monitor plane owns one protected host label and no native labe
showProjection: false, showProjection: false,
}); });
refreshCoverageStyles(); refreshCoverageStyles();
assert.equal(runtime.planeEntity.show, false); assert.equal(runtime.plane.show, false);
assert.equal(planes[0].items.get(quad.id).show, false);
assert.deepEqual(calls.slice(-2), [ assert.deepEqual(calls.slice(-2), [
['clear', 'cctv-projection'], ['clear', 'cctv-projection'],
['visible', 'cctv-projection', false], ['visible', 'cctv-projection', false],
@@ -814,6 +828,7 @@ test('real active monitor plane owns one protected host label and no native labe
} finally { } finally {
_setCctvCoverageStateForTest({ enabled: false }); _setCctvCoverageStateForTest({ enabled: false });
_setCctvOverlayHostForTest(); _setCctvOverlayHostForTest();
unbind();
} }
}); });
@@ -1002,8 +1017,7 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
// ─── Empty-space deselection and stable null-active state ────────────────── // ─── Empty-space deselection and stable null-active state ──────────────────
function makeDeselectViewer() { function makeDeselectViewer() {
return { const viewer = {
entities: new Cesium.EntityCollection(),
isDestroyed: () => false, isDestroyed: () => false,
trackedEntity: { id: 'sibling-track-owner' }, trackedEntity: { id: 'sibling-track-owner' },
camera: { camera: {
@@ -1028,6 +1042,9 @@ function makeDeselectViewer() {
requestRender() {}, requestRender() {},
}, },
}; };
// The layer's lines and plane draw through this.
viewer.draw = bindFakeDraw(viewer).draw;
return viewer;
} }
function makeDeselectRecord(id, index = 0) { function makeDeselectRecord(id, index = 0) {
@@ -1118,63 +1135,86 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
}); });
test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => { test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => {
const ownedCoverageEntity = { id: 'cctv-shared-id-cap' }; const viewer = {};
cctvPicks.write(ownedCoverageEntity).cameraId = 'shared-id'; const { draw, unbind } = bindFakeDraw(viewer);
const strayEntity = { id: 'cctv-shared-id-stray' }; const record = makeDeselectRecord('shared-id');
cctvPicks.write(strayEntity).cameraId = 'shared-id';
const record = {
...makeDeselectRecord('shared-id'),
coverageEntities: [ownedCoverageEntity],
};
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer,
records: [record], records: [record],
activeCameraId: 'shared-id', activeCameraId: 'shared-id',
}); });
try { try {
refreshCoverageStyles();
const coverage = [...draw.sets.values()].find(
(set) => set.kind === 'lines' && set.spec.id.startsWith('cctv:'),
);
assert.ok(coverage.items.has('cctv-shared-id-cap'));
const lineHit = (set, id) => ({
set,
id,
meta: { cameraId: 'shared-id' },
surface: false,
});
assert.equal( assert.equal(
_extractPickedCameraIdForTest({ _extractPickedCameraIdForTest({
set: _cctvIconsForTest().setId,
id: 'shared-id', id: 'shared-id',
iconSet: _cctvIconsForTest(), surface: false,
primitive: { id: 'shared-id' },
}), }),
'shared-id', 'shared-id',
); );
assert.equal( assert.equal(
_extractPickedCameraIdForTest({ _extractPickedCameraIdForTest({
set: 'sibling:1:icons',
id: 'shared-id', id: 'shared-id',
iconSet: {}, surface: false,
primitive: { id: 'shared-id' },
}), }),
null, null,
'a sibling primitive with the same canonical ID cannot activate CCTV', "a sibling set's icon with the same canonical ID cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({ id: { id: 'shared-id' } }),
null,
'a sibling Entity with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: ownedCoverageEntity }),
'shared-id',
'an exact stored CCTV coverage Entity retains activation ownership',
); );
assert.equal( assert.equal(
_extractPickedCameraIdForTest({ _extractPickedCameraIdForTest({
id: { set: _cctvIconsForTest().setId,
id: 'sibling-entity', id: 'not-a-camera',
properties: { cctvCameraId: 'shared-id' }, surface: false,
}, }),
null,
'an id the icon book does not draw is not a camera',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-cap'),
),
'shared-id',
'a coverage line the record draws retains activation ownership',
);
assert.equal(
_extractPickedCameraIdForTest(
lineHit('sibling:1:lines', 'cctv-shared-id-cap'),
),
null,
"a sibling set's item with a CCTV id and meta cannot activate CCTV",
);
assert.equal(
_extractPickedCameraIdForTest({
set: 'sibling:1:entities',
id: 'sibling-entity',
meta: { cctvCameraId: 'shared-id', cameraId: 'shared-id' },
surface: false,
}), }),
null, null,
'a sibling cannot impersonate CCTV by copying its property shape', 'a sibling cannot impersonate CCTV by copying its property shape',
); );
assert.equal( assert.equal(
_extractPickedCameraIdForTest({ id: strayEntity }), _extractPickedCameraIdForTest(
lineHit(coverage.spec.id, 'cctv-shared-id-stray'),
),
null, null,
'a camera id alone is not ownership: the record must hold the entity', 'a camera id alone is not ownership: the record must draw the item',
); );
} finally { } finally {
_setCctvCoverageStateForTest({ enabled: false }); _setCctvCoverageStateForTest({ enabled: false });
unbind();
} }
}); });
@@ -1228,7 +1268,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(publications.at(-1).activeCameraId, null); assert.equal(publications.at(-1).activeCameraId, null);
assert.equal(publications.at(-1).activeCamera, null); assert.equal(publications.at(-1).activeCamera, null);
assert.equal(publications.at(-1).enabled, true); assert.equal(publications.at(-1).enabled, true);
assert.equal(runtime.planeEntity.show, false); assert.equal(runtime.plane.show, false);
assert.equal(record.probeClampRangeM, null); assert.equal(record.probeClampRangeM, null);
assert.equal(record.activationDone, false); assert.equal(record.activationDone, false);
assert.deepEqual(viewer.camera.positionWC, pose.positionWC); assert.deepEqual(viewer.camera.positionWC, pose.positionWC);
+220 -206
View File
@@ -8,7 +8,7 @@
* - Pure drag math (this top section): ray↔axis closest-point, ray↔plane * - Pure drag math (this top section): ray↔axis closest-point, ray↔plane
* intersection with a grazing-angle guard, ring angles. All unit-tested * intersection with a grazing-angle guard, ring angles. All unit-tested
* under node:test with zero scene dependencies. * under node:test with zero scene dependencies.
* - createCalibrationGizmo (below): the entity + pointer-input * - createCalibrationGizmo (below): the draw-set + pointer-input
* controller that renders grab-able handles on the ACTIVE camera and turns * controller that renders grab-able handles on the ACTIVE camera and turns
* drags into calibration patches through a narrow callback interface. It * drags into calibration patches through a narrow callback interface. It
* never touches the layer's records/stores directly. * never touches the layer's records/stores directly.
@@ -23,8 +23,10 @@
* throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query * throttled hover picks while ADJUST mode is on) — the layer's zero-steady-state-query
* invariant is untouched. * invariant is untouched.
*/ */
import * as Cesium from 'cesium';
import { inputFor } from '../input/dispatcher.js'; import { inputFor } from '../input/dispatcher.js';
import { canvasOf, drawOf, findQuery } from '../render/rendererOf.js';
import { eastNorthUp } from '../geo/frames.js';
import { add, dot, scale, sub } from '../geo/vector.js';
// Grazing guard (spec §5): reject plane intersections when the view ray is // Grazing guard (spec §5): reject plane intersections when the view ray is
// nearly parallel to the constraint plane — the hit point races to infinity // nearly parallel to the constraint plane — the hit point races to infinity
@@ -33,8 +35,6 @@ const GRAZING_DOT_MIN = 0.08;
// Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²). // Near-parallel guard for ray/axis closest-point (denominator 1 - (d·a)²).
const PARALLEL_EPS = 1e-6; const PARALLEL_EPS = 1e-6;
const scratchW = new Cesium.Cartesian3();
/** /**
* Parameter t (metres) along an axis line of the point on that axis closest * Parameter t (metres) along an axis line of the point on that axis closest
* to a mouse ray. Both directions must be normalized. * to a mouse ray. Both directions must be normalized.
@@ -43,60 +43,52 @@ const scratchW = new Cesium.Cartesian3();
* t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin, * t = (e − b·d) / (1 − b²) with b = rayDir·axisDir, w = rayOrigin − axisOrigin,
* d = rayDir·w, e = axisDir·w. * d = rayDir·w, e = axisDir·w.
* *
* @param {Cesium.Cartesian3} rayOrigin * Vectors are ECEF `{x, y, z}`.
* @param {Cesium.Cartesian3} rayDir - Unit. * @param {{x: number, y: number, z: number}} rayOrigin
* @param {Cesium.Cartesian3} axisOrigin * @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {Cesium.Cartesian3} axisDir - Unit. * @param {{x: number, y: number, z: number}} axisOrigin
* @param {{x: number, y: number, z: number}} axisDir - Unit.
* @returns {number|null} Axis parameter in metres, or null when near-parallel. * @returns {number|null} Axis parameter in metres, or null when near-parallel.
*/ */
export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) { export function closestParamOnAxis(rayOrigin, rayDir, axisOrigin, axisDir) {
const b = Cesium.Cartesian3.dot(rayDir, axisDir); const b = dot(rayDir, axisDir);
const denom = 1 - b * b; const denom = 1 - b * b;
if (Math.abs(denom) < PARALLEL_EPS) return null; if (Math.abs(denom) < PARALLEL_EPS) return null;
const w = Cesium.Cartesian3.subtract(rayOrigin, axisOrigin, scratchW); const w = sub(rayOrigin, axisOrigin);
const d = Cesium.Cartesian3.dot(rayDir, w); const d = dot(rayDir, w);
const e = Cesium.Cartesian3.dot(axisDir, w); const e = dot(axisDir, w);
return (e - b * d) / denom; return (e - b * d) / denom;
} }
/** /**
* Intersects a mouse ray with a plane, refusing grazing configurations * Intersects a mouse ray with a plane, refusing grazing configurations
* (|rayDir·normal| < 0.08) and hits behind the ray origin. * (|rayDir·normal| < 0.08) and hits behind the ray origin.
* @param {Cesium.Cartesian3} rayOrigin * @param {{x: number, y: number, z: number}} rayOrigin
* @param {Cesium.Cartesian3} rayDir - Unit. * @param {{x: number, y: number, z: number}} rayDir - Unit.
* @param {Cesium.Cartesian3} planeOrigin * @param {{x: number, y: number, z: number}} planeOrigin
* @param {Cesium.Cartesian3} planeNormal - Unit. * @param {{x: number, y: number, z: number}} planeNormal - Unit.
* @returns {Cesium.Cartesian3|null} Hit point (new instance), or null. * @returns {{x: number, y: number, z: number}|null} Hit point (new), or null.
*/ */
export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) { export function rayPlaneIntersect(rayOrigin, rayDir, planeOrigin, planeNormal) {
const denom = Cesium.Cartesian3.dot(rayDir, planeNormal); const denom = dot(rayDir, planeNormal);
if (Math.abs(denom) < GRAZING_DOT_MIN) return null; if (Math.abs(denom) < GRAZING_DOT_MIN) return null;
const toPlane = Cesium.Cartesian3.subtract(planeOrigin, rayOrigin, scratchW); const s = dot(sub(planeOrigin, rayOrigin), planeNormal) / denom;
const s = Cesium.Cartesian3.dot(toPlane, planeNormal) / denom;
if (s < 0) return null; if (s < 0) return null;
const hit = Cesium.Cartesian3.multiplyByScalar( return add(rayOrigin, scale(rayDir, s));
rayDir,
s,
new Cesium.Cartesian3(),
);
return Cesium.Cartesian3.add(rayOrigin, hit, hit);
} }
/** /**
* Angle (radians, atan2 convention) of a point around a ring center in the * Angle (radians, atan2 convention) of a point around a ring center in the
* plane spanned by two orthonormal basis vectors. * plane spanned by two orthonormal basis vectors.
* @param {Cesium.Cartesian3} hitPoint - Point on/near the ring plane. * @param {{x: number, y: number, z: number}} hitPoint - Point on/near the ring plane.
* @param {Cesium.Cartesian3} center - Ring center. * @param {{x: number, y: number, z: number}} center - Ring center.
* @param {Cesium.Cartesian3} basisA - In-plane unit vector (angle 0). * @param {{x: number, y: number, z: number}} basisA - In-plane unit vector (angle 0).
* @param {Cesium.Cartesian3} basisB - In-plane unit vector (angle +90°). * @param {{x: number, y: number, z: number}} basisB - In-plane unit vector (angle +90°).
* @returns {number} Angle in (−π, π]. * @returns {number} Angle in (−π, π].
*/ */
export function ringAngle(hitPoint, center, basisA, basisB) { export function ringAngle(hitPoint, center, basisA, basisB) {
const v = Cesium.Cartesian3.subtract(hitPoint, center, scratchW); const v = sub(hitPoint, center);
return Math.atan2( return Math.atan2(dot(v, basisB), dot(v, basisA));
Cesium.Cartesian3.dot(v, basisB),
Cesium.Cartesian3.dot(v, basisA),
);
} }
/** /**
@@ -117,8 +109,8 @@ export function signedAngleDelta(fromRad, toRad) {
// Gizmo controller // Gizmo controller
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/** Entity id prefix for every gizmo part — the layer's pick-owner regex and /** Item id prefix for every gizmo part — the layer's pick-owner regex and
* click-to-select guard key off this. Gizmo entities NEVER get a camera id in * click-to-select guard key off this. Gizmo parts NEVER get a camera id in
* the layer's pick store, so the layer's selection path ignores them. */ * the layer's pick store, so the layer's selection path ignores them. */
export const GIZMO_ID_PREFIX = 'cctv-gizmo-'; export const GIZMO_ID_PREFIX = 'cctv-gizmo-';
@@ -130,42 +122,46 @@ const ARROW_LENGTH_FACTOR = 1.6;
const DRAG_THROTTLE_MS = 16; const DRAG_THROTTLE_MS = 16;
const HOVER_THROTTLE_MS = 120; const HOVER_THROTTLE_MS = 120;
const COLOR_RING_HEADING = Cesium.Color.fromCssColorString('#35d8ff'); /** A `#rrggbb` colour at `alpha`, as the renderer's 0..1 RGBA. */
const COLOR_RING_PITCH = Cesium.Color.fromCssColorString('#ff5fd0'); function rgba(hex, alpha = 1) {
const COLOR_MOVE_EAST = Cesium.Color.fromCssColorString('#ff5252'); const n = Number.parseInt(hex.slice(1), 16);
const COLOR_MOVE_NORTH = Cesium.Color.fromCssColorString('#52ff7a'); return [
const COLOR_MOVE_UP = Cesium.Color.fromCssColorString('#5b8cff'); ((n >> 16) & 255) / 255,
const COLOR_HANDLE = Cesium.Color.fromCssColorString('#ffd97a'); ((n >> 8) & 255) / 255,
(n & 255) / 255,
alpha,
];
}
const COLOR_RING_HEADING = '#35d8ff';
const COLOR_RING_PITCH = '#ff5fd0';
const COLOR_MOVE_EAST = '#ff5252';
const COLOR_MOVE_NORTH = '#52ff7a';
const COLOR_MOVE_UP = '#5b8cff';
const COLOR_HANDLE = '#ffd97a';
const HANDLE_OUTLINE = [0, 0, 0, 0.7];
const toRadians = (deg) => (deg * Math.PI) / 180; const toRadians = (deg) => (deg * Math.PI) / 180;
const toDeg = (rad) => (rad * 180) / Math.PI; const toDeg = (rad) => (rad * 180) / Math.PI;
/** /**
* Local ENU unit axes at an ECEF position. * Local ENU unit axes at an ECEF position.
* @param {Cesium.Cartesian3} position * @param {{x: number, y: number, z: number}} position
* @returns {{east: Cesium.Cartesian3, north: Cesium.Cartesian3, up: Cesium.Cartesian3}} * @returns {{east: object, north: object, up: object}}
*/ */
function enuAxes(position) { function enuAxes(position) {
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(position); const frame = eastNorthUp(position);
const rot = Cesium.Matrix4.getMatrix3(frame, new Cesium.Matrix3()); return { east: frame.x, north: frame.y, up: frame.z };
return {
east: Cesium.Matrix3.getColumn(rot, 0, new Cesium.Cartesian3()),
north: Cesium.Matrix3.getColumn(rot, 1, new Cesium.Cartesian3()),
up: Cesium.Matrix3.getColumn(rot, 2, new Cesium.Cartesian3()),
};
} }
/** a*sa + b*sb (fresh Cartesian3). */ /** a*sa + b*sb. */
function combine2(a, sa, b, sb) { function combine2(a, sa, b, sb) {
const out = Cesium.Cartesian3.multiplyByScalar( return add(scale(a, sa), scale(b, sb));
a,
sa,
new Cesium.Cartesian3(),
);
const t = Cesium.Cartesian3.multiplyByScalar(b, sb, new Cesium.Cartesian3());
return Cesium.Cartesian3.add(out, t, out);
} }
/** The midpoint of two points. */
const midpoint = (a, b) => scale(add(a, b), 0.5);
/** /**
* View-frame unit vectors for a pose within a local ENU frame: horizontal * View-frame unit vectors for a pose within a local ENU frame: horizontal
* forward, viewer-right, and the full pitched view axis. * forward, viewer-right, and the full pitched view axis.
@@ -192,25 +188,57 @@ function ringPositions(center, radius, basisA, basisB) {
const positions = []; const positions = [];
for (let i = 0; i <= RING_SEGMENTS; i++) { for (let i = 0; i <= RING_SEGMENTS; i++) {
const angle = (i / RING_SEGMENTS) * 2 * Math.PI; const angle = (i / RING_SEGMENTS) * 2 * Math.PI;
const offset = combine2( positions.push(
basisA, add(
Math.cos(angle) * radius, center,
basisB, combine2(
Math.sin(angle) * radius, basisA,
Math.cos(angle) * radius,
basisB,
Math.sin(angle) * radius,
),
),
); );
positions.push(Cesium.Cartesian3.add(center, offset, offset));
} }
return positions; return positions;
} }
/** The ring and arrow parts: their colour, width and whether an arrow. */
const LINE_PARTS = Object.freeze([
['ring-heading', COLOR_RING_HEADING, 3, false],
['ring-pitch', COLOR_RING_PITCH, 3, false],
['move-east', COLOR_MOVE_EAST, 12, true],
['move-north', COLOR_MOVE_NORTH, 12, true],
['move-up', COLOR_MOVE_UP, 12, true],
]);
/** The point parts (an arrow's tip included): colour and first size. */
const POINT_PARTS = Object.freeze([
['move-east', COLOR_MOVE_EAST, 14],
['move-north', COLOR_MOVE_NORTH, 14],
['move-up', COLOR_MOVE_UP, 14],
['handle-range', COLOR_HANDLE, 13],
['handle-fov-l', COLOR_HANDLE, 10],
['handle-fov-r', COLOR_HANDLE, 10],
]);
/** Every part a pick can grab. */
const PARTS = new Set([
...LINE_PARTS.map(([part]) => part),
...POINT_PARTS.map(([part]) => part),
]);
let gizmoInstances = 0;
/** /**
* Creates the calibration gizmo controller (design §3c). Renders grab-able * Creates the calibration gizmo controller (design §3c). Renders grab-able
* handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags * handles for the ACTIVE camera's 7 calibration DOF and turns pointer drags
* into calibration patches through a narrow callback interface — the gizmo * into calibration patches through a narrow callback interface — the gizmo
* never touches layer records/stores directly. * never touches layer records/stores directly. It draws through the
* renderer's draw port (a line set for the rings and arrows, a point set
* for the handles and arrow tips, each item `cctv-gizmo-<part>`) and picks
* and casts rays through its query port.
* *
* @param {Object} deps * @param {Object} deps
* @param {Cesium.Viewer} deps.viewer * @param {object} deps.viewer - The viewer whose renderer draws it.
* @param {function(): Object|null} deps.getActiveRecord - Returns the record * @param {function(): Object|null} deps.getActiveRecord - Returns the record
* the gizmo should attach to, or null to hide (layer decides: enabled + * the gizmo should attach to, or null to hide (layer decides: enabled +
* calibration mode + active camera). * calibration mode + active camera).
@@ -221,7 +249,7 @@ function ringPositions(center, radius, basisA, basisB) {
* end, for the PINNED drag record. * end, for the PINNED drag record.
* @returns {{setEnabled: function(boolean): void, refresh: function(): void, * @returns {{setEnabled: function(boolean): void, refresh: function(): void,
* destroy: function(): void, isDragging: function(): boolean, * destroy: function(): void, isDragging: function(): boolean,
* isEnabled: function(): boolean}} * isEnabled: function(): boolean, partsForTest: function(): Object}}
*/ */
export function createCalibrationGizmo({ export function createCalibrationGizmo({
viewer, viewer,
@@ -234,74 +262,70 @@ export function createCalibrationGizmo({
let hoveredId = null; let hoveredId = null;
let lastDragAt = 0; let lastDragAt = 0;
let lastHoverAt = 0; let lastHoverAt = 0;
const entities = new Map(); // part -> Entity // Whether the parts are drawn now, and each point part's pixel size.
let shown = false;
const pointSizes = new Map(POINT_PARTS.map(([part, , size]) => [part, size]));
// The parts' geometry as last drawn: ECEF line positions and point spots.
const linePositions = new Map();
const pointPositions = new Map();
const scene = viewer.scene;
const input = inputFor(viewer); const input = inputFor(viewer);
let releaseCamera = null; let releaseCamera = null;
/** Adds (or re-adds) a gizmo entity, clearing any stale duplicate id. */ const instance = ++gizmoInstances;
function addEntity(part, options) { const draw = drawOf(viewer);
const id = `${GIZMO_ID_PREFIX}${part}`; const lines = draw.lines({ id: `cctv-gizmo:${instance}:lines` });
const stale = viewer.entities.getById(id); const points = draw.points({ id: `cctv-gizmo:${instance}:points` });
if (stale) viewer.entities.remove(stale);
const entity = viewer.entities.add({ id, show: false, ...options });
entities.set(part, entity);
return entity;
}
function polylinePart(part, color, width, arrow = false) { /** The rings and arrows as they now are. */
addEntity(part, { function lineItems() {
...(arrow const items = [];
? { for (const [part, color, widthPx, arrow] of LINE_PARTS) {
position: Cesium.Cartesian3.ZERO, const positions = linePositions.get(part);
point: { if (!positions) continue;
pixelSize: 14, items.push({
color, id: `${GIZMO_ID_PREFIX}${part}`,
outlineColor: Cesium.Color.BLACK.withAlpha(0.7), positions,
outlineWidth: 2, widthPx,
disableDepthTestDistance: Number.POSITIVE_INFINITY, mode: '3d',
}, style: arrow
} ? { kind: 'arrow', color: rgba(color) }
: {}), : { kind: 'solid', color: rgba(color, 0.9) },
polyline: {
positions: [],
width,
material: arrow
? new Cesium.PolylineArrowMaterialProperty(color)
: color.withAlpha(0.9),
// Standard gizmo convention: parts behind geometry stay clearly // Standard gizmo convention: parts behind geometry stay clearly
// visible, just dimmed (a street-level mount buries half the heading // visible, just dimmed (a street-level mount buries half the heading
// ring in sloped photogrammetry tiles — smoke-tested 2026-07-05). // ring in sloped photogrammetry tiles — smoke-tested 2026-07-05).
depthFailMaterial: color.withAlpha(0.45), depthFailColor: rgba(color, 0.45),
}, show: shown,
}); });
}
return items;
} }
function pointPart(part, color, pixelSize) { /** The handles and arrow tips as they now are. */
addEntity(part, { function pointItems() {
position: Cesium.Cartesian3.ZERO, const items = [];
point: { for (const [part, color] of POINT_PARTS) {
pixelSize, const pos = pointPositions.get(part);
color, if (!pos) continue;
outlineColor: Cesium.Color.BLACK.withAlpha(0.7), items.push({
id: `${GIZMO_ID_PREFIX}${part}`,
pos,
pixelSize: pointSizes.get(part),
color: rgba(color),
outlineColor: HANDLE_OUTLINE,
outlineWidth: 2, outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY, disableDepthTest: Number.POSITIVE_INFINITY,
}, show: shown,
}); });
}
return items;
} }
polylinePart('ring-heading', COLOR_RING_HEADING, 3);
polylinePart('ring-pitch', COLOR_RING_PITCH, 3);
polylinePart('move-east', COLOR_MOVE_EAST, 12, true);
polylinePart('move-north', COLOR_MOVE_NORTH, 12, true);
polylinePart('move-up', COLOR_MOVE_UP, 12, true);
pointPart('handle-range', COLOR_HANDLE, 13);
pointPart('handle-fov-l', COLOR_HANDLE, 10);
pointPart('handle-fov-r', COLOR_HANDLE, 10);
function hideAll() { function hideAll() {
for (const entity of entities.values()) entity.show = false; if (!shown) return;
shown = false;
lines.upsert(lineItems());
points.upsert(pointItems());
} }
/** Recomputes every handle's geometry from the active record's CURRENT pose /** Recomputes every handle's geometry from the active record's CURRENT pose
@@ -329,69 +353,52 @@ export function createCalibrationGizmo({
); );
const arrowLen = radius * ARROW_LENGTH_FACTOR; const arrowLen = radius * ARROW_LENGTH_FACTOR;
entities.get('ring-heading').polyline.positions = ringPositions( linePositions.set(
mount, 'ring-heading',
radius, ringPositions(mount, radius, axes.north, axes.east),
axes.north,
axes.east,
); );
entities.get('ring-pitch').polyline.positions = ringPositions( linePositions.set(
mount, 'ring-pitch',
radius, ringPositions(mount, radius, forwardHoriz, axes.up),
forwardHoriz,
axes.up,
); );
const arrowTo = (dir) => [ const arrowTo = (dir) => [mount, add(mount, scale(dir, arrowLen))];
mount, for (const [part, dir] of [
Cesium.Cartesian3.add( ['move-east', axes.east],
mount, ['move-north', axes.north],
Cesium.Cartesian3.multiplyByScalar( ['move-up', axes.up],
dir, ]) {
arrowLen, const arrow = arrowTo(dir);
new Cesium.Cartesian3(), linePositions.set(part, arrow);
), pointPositions.set(part, arrow[1]);
new Cesium.Cartesian3(), }
), pointPositions.set('handle-range', positions.capCenter);
]; pointPositions.set('handle-fov-l', midpoint(positions.tl, positions.bl));
const eastArrow = arrowTo(axes.east); pointPositions.set('handle-fov-r', midpoint(positions.tr, positions.br));
const northArrow = arrowTo(axes.north); shown = true;
const upArrow = arrowTo(axes.up); lines.upsert(lineItems());
entities.get('move-east').polyline.positions = eastArrow; points.upsert(pointItems());
entities.get('move-east').position = eastArrow[1];
entities.get('move-north').polyline.positions = northArrow;
entities.get('move-north').position = northArrow[1];
entities.get('move-up').polyline.positions = upArrow;
entities.get('move-up').position = upArrow[1];
entities.get('handle-range').position = positions.capCenter;
entities.get('handle-fov-l').position = Cesium.Cartesian3.midpoint(
positions.tl,
positions.bl,
new Cesium.Cartesian3(),
);
entities.get('handle-fov-r').position = Cesium.Cartesian3.midpoint(
positions.tr,
positions.br,
new Cesium.Cartesian3(),
);
for (const entity of entities.values()) entity.show = true;
} }
/** Extracts a gizmo part name from a pick result, or null. */ /** The gizmo part a pick hit is, or null. */
function gizmoPartFrom(picked) { function gizmoPartFrom(hit) {
const id = picked?.id?.id ?? picked?.id; if (!hit || (hit.set !== lines.id && hit.set !== points.id)) return null;
const id = hit.id;
if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null; if (typeof id !== 'string' || !id.startsWith(GIZMO_ID_PREFIX)) return null;
return id.slice(GIZMO_ID_PREFIX.length); const part = id.slice(GIZMO_ID_PREFIX.length);
return PARTS.has(part) ? part : null;
} }
function pickGizmoPart(windowPosition) { function pickGizmoPart(windowPosition) {
const query = findQuery(viewer);
if (!query || !windowPosition) return null;
const { x, y } = windowPosition;
// Gizmo primitives render depth-test-free and should be the topmost pick. // Gizmo primitives render depth-test-free and should be the topmost pick.
// Take the cheap single-result path first: a full drillPick can stall for // Take the cheap single-result path first: a full drillPick can stall for
// tens of seconds under software GL even when its first result is already // tens of seconds under software GL even when its first result is already
// the gizmo. Retain drillPick for uncommon overlap/fallback cases. // the gizmo. Retain drillPick for uncommon overlap/fallback cases.
try { try {
const picked = scene.pick(windowPosition, 14, 14); const part = gizmoPartFrom(query.pick(x, y, { width: 14, height: 14 }));
const part = gizmoPartFrom(picked); if (part && shown) return part;
if (part && entities.get(part)?.show) return part;
} catch (err) { } catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] pick threw:', err?.message || err); console.debug('[CCTV:gizmo] pick threw:', err?.message || err);
@@ -400,7 +407,8 @@ export function createCalibrationGizmo({
let results = []; let results = [];
try { try {
results = scene.drillPick(windowPosition, 6, 14, 14) || []; results =
query.drillPick(x, y, { limit: 6, width: 14, height: 14 }) || [];
} catch (err) { } catch (err) {
if (typeof window !== 'undefined' && window.__gevGizmoDebug) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err); console.debug('[CCTV:gizmo] drillPick threw:', err?.message || err);
@@ -410,52 +418,54 @@ export function createCalibrationGizmo({
if (typeof window !== 'undefined' && window.__gevGizmoDebug) { if (typeof window !== 'undefined' && window.__gevGizmoDebug) {
console.debug( console.debug(
'[CCTV:gizmo] drillPick @', '[CCTV:gizmo] drillPick @',
windowPosition?.x, x,
windowPosition?.y, y,
'→', '→',
JSON.stringify( JSON.stringify(
results.map((r) => results.map((hit) =>
String(r?.id?.id ?? r?.id ?? r?.primitive?.constructor?.name), hit.surface ? '(surface)' : `${hit.set}/${hit.id}`,
), ),
), ),
); );
} }
for (const picked of results) { for (const hit of results) {
const part = gizmoPartFrom(picked); const part = gizmoPartFrom(hit);
if (part && entities.get(part)?.show) return part; if (part && shown) return part;
} }
return null; return null;
} }
function pickRay(windowPosition) { function pickRay(windowPosition) {
try { try {
return viewer.camera.getPickRay(windowPosition) || null; return (
findQuery(viewer)?.pickRay(windowPosition.x, windowPosition.y) || null
);
} catch { } catch {
return null; return null;
} }
} }
function setCursor(value) { function setCursor(value) {
if (scene.canvas?.style) scene.canvas.style.cursor = value; const style = canvasOf(viewer)?.style;
if (style) style.cursor = value;
} }
function setHovered(part) { function setHovered(part) {
const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null; const nextId = part ? `${GIZMO_ID_PREFIX}${part}` : null;
if (nextId === hoveredId) return; if (nextId === hoveredId) return;
hoveredId = nextId; hoveredId = nextId;
// Hover feedback must NEVER touch polyline geometry: a width change makes // Hover feedback must NEVER touch line geometry: a width change rebuilds
// Cesium rebuild the batched polyline primitive, and until the next render // the line, and until the next render the part vanishes from the pick
// the part vanishes from the pick buffer — so the very hover that finds a // buffer — so the very hover that finds a ring makes the following
// ring makes the following LEFT_DOWN miss it (root-caused via the QA // LEFT_DOWN miss it (root-caused via the QA harness's synthetic drag,
// harness's synthetic drag, 2026-07-05). Rings/arrows get cursor feedback // 2026-07-05). Rings/arrows get cursor feedback only; point handles
// only; point handles are PointPrimitives (live-updatable, no rebuild), so // (an arrow's tip included) change size in place, so they keep the size
// they keep the size bump. // bump.
for (const [name, entity] of entities.entries()) { for (const [name] of POINT_PARTS) {
if (!entity.point) continue;
const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`; const hot = hoveredId === `${GIZMO_ID_PREFIX}${name}`;
entity.point.pixelSize = pointSizes.set(name, (name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0));
(name === 'handle-range' ? 13 : 10) + (hot ? 4 : 0);
} }
points.upsert(pointItems());
setCursor(hoveredId ? 'grab' : ''); setCursor(hoveredId ? 'grab' : '');
} }
@@ -469,8 +479,8 @@ export function createCalibrationGizmo({
const ray = pickRay(windowPosition); const ray = pickRay(windowPosition);
if (!ray) return false; if (!ray) return false;
const mount = Cesium.Cartesian3.clone(positions.mount); const mount = { ...positions.mount };
const capCenter = Cesium.Cartesian3.clone(positions.capCenter); const capCenter = { ...positions.capCenter };
const axes = enuAxes(mount); const axes = enuAxes(mount);
const { forwardHoriz, right, view } = viewAxesFor( const { forwardHoriz, right, view } = viewAxesFor(
camera.headingDeg, camera.headingDeg,
@@ -595,12 +605,7 @@ export function createCalibrationGizmo({
if (part === 'handle-fov-l' || part === 'handle-fov-r') { if (part === 'handle-fov-l' || part === 'handle-fov-r') {
const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view); const hit = rayPlaneIntersect(ray.origin, ray.direction, capCenter, view);
if (!hit) return null; if (!hit) return null;
const lateral = Math.abs( const lateral = Math.abs(dot(sub(hit, capCenter), right));
Cesium.Cartesian3.dot(
Cesium.Cartesian3.subtract(hit, capCenter, new Cesium.Cartesian3()),
right,
),
);
const halfW = Math.max(0.5, lateral); const halfW = Math.max(0.5, lateral);
const fovDeg = toDeg( const fovDeg = toDeg(
2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)), 2 * Math.atan(halfW / Math.max(1, drag.effectiveRangeM)),
@@ -692,13 +697,22 @@ export function createCalibrationGizmo({
offDown(); offDown();
offMove(); offMove();
offUp(); offUp();
for (const entity of entities.values()) { lines.dispose();
viewer.entities.remove(entity); points.dispose();
}
entities.clear();
setCursor(''); setCursor('');
}, },
isDragging: () => !!drag, isDragging: () => !!drag,
isEnabled: () => enabled, isEnabled: () => enabled,
/**
* The parts as last drawn, by item id, for the QA harness: whether each
* shows, a line's `positions` and a point's `pos` (an arrow has both).
*/
partsForTest() {
const parts = {};
for (const item of [...lineItems(), ...pointItems()])
parts[item.id] = { ...parts[item.id], ...item };
for (const item of lineItems()) parts[item.id].show = item.show;
return parts;
},
}; };
} }
+272 -65
View File
@@ -12,7 +12,6 @@
// - the controller ends an open drag, and its camera hold, on the next press. // - the controller ends an open drag, and its camera hold, on the next press.
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { import {
GIZMO_ID_PREFIX, GIZMO_ID_PREFIX,
closestParamOnAxis, closestParamOnAxis,
@@ -22,8 +21,11 @@ import {
signedAngleDelta, signedAngleDelta,
} from './cctvGizmo.js'; } from './cctvGizmo.js';
import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs'; import { FAKE_EVENT_TYPES, fakeInput } from '../input/testDoubles.mjs';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fromDegrees } from '../geo/ellipsoid.js';
import { add, distance, negate, normalize, scale } from '../geo/vector.js';
const c3 = (x, y, z) => new Cesium.Cartesian3(x, y, z); const c3 = (x, y, z) => ({ x, y, z });
test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => { test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', () => {
// Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5): // Axis along +X from origin. Ray shooting straight down (-Z) from (10, 0, 5):
@@ -40,10 +42,7 @@ test('closestParamOnAxis: perpendicular ray hits the axis at its own offset', ()
test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => { test('closestParamOnAxis: skew ray resolves to the geometric closest point', () => {
// Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the // Axis +X. Ray from (0, 10, 0) toward (1, -1, 0)/√2 passes closest to the
// axis around x=10 (it reaches y=0 at x=10). // axis around x=10 (it reaches y=0 at x=10).
const dir = Cesium.Cartesian3.normalize( const dir = normalize(c3(1, -1, 0));
c3(1, -1, 0),
new Cesium.Cartesian3(),
);
const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0)); const t = closestParamOnAxis(c3(0, 10, 0), dir, c3(0, 0, 0), c3(1, 0, 0));
assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`); assert.ok(Math.abs(t - 10) < 1e-6, `expected ~10, got ${t}`);
}); });
@@ -63,10 +62,7 @@ test('closestParamOnAxis: near-parallel ray/axis returns null', () => {
closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)), closestParamOnAxis(c3(0, 1, 0), c3(1, 0, 0), c3(0, 0, 0), c3(1, 0, 0)),
null, null,
); );
const nearly = Cesium.Cartesian3.normalize( const nearly = normalize(c3(1, 1e-9, 0));
c3(1, 1e-9, 0),
new Cesium.Cartesian3(),
);
assert.equal( assert.equal(
closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)), closestParamOnAxis(c3(0, 1, 0), nearly, c3(0, 0, 0), c3(1, 0, 0)),
null, null,
@@ -81,25 +77,19 @@ test('rayPlaneIntersect: straight-on hit lands at the expected point', () => {
c3(0, 0, 1), c3(0, 0, 1),
); );
assert.ok(hit, 'expected a hit'); assert.ok(hit, 'expected a hit');
assert.ok(Cesium.Cartesian3.distance(hit, c3(0, 0, 0)) < 1e-9); assert.ok(distance(hit, c3(0, 0, 0)) < 1e-9);
}); });
test('rayPlaneIntersect: oblique hit resolves correctly', () => { test('rayPlaneIntersect: oblique hit resolves correctly', () => {
const dir = Cesium.Cartesian3.normalize( const dir = normalize(c3(1, 0, -1));
c3(1, 0, -1),
new Cesium.Cartesian3(),
);
const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)); const hit = rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1));
assert.ok(hit); assert.ok(hit);
assert.ok(Cesium.Cartesian3.distance(hit, c3(5, 0, 0)) < 1e-9, `got ${hit}`); assert.ok(distance(hit, c3(5, 0, 0)) < 1e-9, `got ${JSON.stringify(hit)}`);
}); });
test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => { test('rayPlaneIntersect: grazing ray (|dir·n| < 0.08) returns null', () => {
// dir almost in-plane: z component 0.05 < 0.08 threshold. // dir almost in-plane: z component 0.05 < 0.08 threshold.
const dir = Cesium.Cartesian3.normalize( const dir = normalize(c3(1, 0, -0.05));
c3(1, 0, -0.05),
new Cesium.Cartesian3(),
);
assert.equal( assert.equal(
rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)), rayPlaneIntersect(c3(0, 0, 5), dir, c3(0, 0, 0), c3(0, 0, 1)),
null, null,
@@ -136,60 +126,133 @@ test('signedAngleDelta: shortest-path wrap', () => {
assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9); assert.ok(Math.abs(signedAngleDelta(d2r(10), d2r(30)) - d2r(20)) < 1e-9);
}); });
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => { /**
* A viewer double drawing through a fake draw port, whose query port picks
* `picked` and casts the ray `ray` (a ray,
* or a function of the window position).
*/
function gizmoViewer(t, { picked, ray }) {
const viewer = { const viewer = {
entities: {
byId: new Map(),
getById(id) {
return this.byId.get(id);
},
add(options) {
this.byId.set(options.id, options);
return options;
},
remove(entity) {
this.byId.delete(entity.id);
},
},
scene: { scene: {
canvas: { style: {} }, canvas: { style: {} },
screenSpaceCameraController: { enableInputs: true }, screenSpaceCameraController: { enableInputs: true },
pick: () => ({ id: { id: `${GIZMO_ID_PREFIX}move-up` } }),
drillPick: () => [],
}, },
}; };
const mount = Cesium.Cartesian3.fromDegrees(0, 0, 10); const queries = [];
const east = new Cesium.Cartesian3(0, 1, 0); // east at lon 0, lat 0 const { draw, unbind } = bindFakeDraw(viewer, {
viewer.camera = { query: {
getPickRay: () => ({ pick: (x, y, window) => (queries.push(['pick', window]), picked()),
origin: Cesium.Cartesian3.add( drillPick: (x, y, options) => (queries.push(['drill', options]), []),
mount, pickRay: (x, y) => (typeof ray === 'function' ? ray(x, y) : ray),
Cesium.Cartesian3.multiplyByScalar(east, 100, new Cesium.Cartesian3()), },
new Cesium.Cartesian3(), });
), t.after(unbind);
direction: Cesium.Cartesian3.negate(east, new Cesium.Cartesian3()), return { viewer, draw, queries };
}
const mount = fromDegrees(0, 0, 10);
const east = c3(0, 1, 0); // east at lon 0, lat 0
const gizmoRecord = () => ({
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
});
test('the gizmo draws its parts through the draw port, shown in ADJUST mode only', (t) => {
const { viewer, draw } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
const lines = draw.find('cctv-gizmo:');
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
assert.equal(lines.kind, 'lines');
assert.equal(lines.items.size, 0, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
assert.deepEqual(
[...lines.items.keys()],
['ring-heading', 'ring-pitch', 'move-east', 'move-north', 'move-up'].map(
(part) => GIZMO_ID_PREFIX + part,
),
);
assert.deepEqual(
[...points.items.keys()],
[
'move-east',
'move-north',
'move-up',
'handle-range',
'handle-fov-l',
'handle-fov-r',
].map((part) => GIZMO_ID_PREFIX + part),
);
const ring = lines.items.get(`${GIZMO_ID_PREFIX}ring-heading`);
assert.equal(ring.mode, '3d');
assert.equal(ring.widthPx, 3);
assert.equal(ring.positions.length, 97, 'a closed 96-segment ring');
assert.ok(Math.abs(ring.style.color[3] - 0.9) < 1e-12);
assert.ok(Math.abs(ring.depthFailColor[3] - 0.45) < 1e-12);
const arrow = lines.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.equal(arrow.style.kind, 'arrow');
assert.equal(arrow.widthPx, 12);
// The up arrow runs 1.6 ring radii (6 m minimum at a 50 m range) up.
assert.ok(
distance(arrow.positions[1], add(mount, scale(c3(1, 0, 0), 9.6))) < 1e-6,
);
const tip = points.items.get(`${GIZMO_ID_PREFIX}move-up`);
assert.deepEqual(tip.pos, arrow.positions[1]);
assert.equal(tip.pixelSize, 14);
assert.equal(tip.disableDepthTest, Number.POSITIVE_INFINITY);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => item.show,
),
);
gizmo.setEnabled(false);
assert.ok(
[...lines.items.values(), ...points.items.values()].every(
(item) => !item.show,
),
'hidden off ADJUST',
);
gizmo.destroy();
assert.equal(lines.disposed, true);
assert.equal(points.disposed, true);
});
test('a press after a release Cesium never reported ends the open drag and its camera hold', (t) => {
let lineSet = null;
const { viewer, draw, queries } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-up`,
surface: false,
}), }),
}; ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer); const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy()); t.after(() => input.destroy());
const record = { const record = gizmoRecord();
frustumPositions: {
mount,
capCenter: mount,
tl: mount,
tr: mount,
bl: mount,
br: mount,
},
frustumGeometry: { rangeM: 50 },
camera: {
headingDeg: 0,
pitchDeg: 0,
rangeM: 50,
calibration: {},
basePose: {},
},
};
const ended = []; const ended = [];
const gizmo = createCalibrationGizmo({ const gizmo = createCalibrationGizmo({
viewer, viewer,
@@ -198,11 +261,13 @@ test('a press after a release Cesium never reported ends the open drag and its c
endPatch: (r) => ended.push(r), endPatch: (r) => ended.push(r),
}); });
t.after(() => gizmo.destroy()); t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true); gizmo.setEnabled(true);
const controller = viewer.scene.screenSpaceCameraController; const controller = viewer.scene.screenSpaceCameraController;
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true); assert.equal(gizmo.isDragging(), true);
assert.deepEqual(queries[0], ['pick', { width: 14, height: 14 }]);
assert.equal(controller.enableInputs, false); assert.equal(controller.enableInputs, false);
// The release came with a modifier key held: Cesium raised no LEFT_UP. // The release came with a modifier key held: Cesium raised no LEFT_UP.
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } }); handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
@@ -211,3 +276,145 @@ test('a press after a release Cesium never reported ends the open drag and its c
assert.equal(gizmo.isDragging(), false); assert.equal(gizmo.isDragging(), false);
assert.equal(controller.enableInputs, true, 'no hold was stranded'); assert.equal(controller.enableInputs, true, 'no hold was stranded');
}); });
test('a pick of another set or a stray id is no gizmo part', (t) => {
let picked = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => picked,
ray: { origin: add(mount, scale(east, 100)), direction: negate(east) },
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
gizmo.setEnabled(true);
picked = { set: 'other', id: `${GIZMO_ID_PREFIX}move-up`, surface: false };
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'another set');
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 5, y: 5 } });
picked = {
set: draw.find('cctv-gizmo:').spec.id,
id: `${GIZMO_ID_PREFIX}nothing`,
surface: false,
};
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), false, 'no such part');
});
test('dragging the east arrow moves the camera east by what the pointer travelled', (t) => {
const up = c3(1, 0, 0); // up at lon 0, lat 0
let lineSet = null;
const { viewer, draw } = gizmoViewer(t, {
picked: () => ({
set: lineSet,
id: `${GIZMO_ID_PREFIX}move-east`,
surface: false,
}),
// Straight down onto the east axis, `x` metres east of the mount.
ray: (x) => ({
origin: add(add(mount, scale(east, x)), scale(up, 100)),
direction: negate(up),
}),
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
record.camera.calibration = { offsetEastM: 2 };
const patches = [];
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch: (patch, pinned) => patches.push([patch, pinned]),
endPatch() {},
});
t.after(() => gizmo.destroy());
lineSet = draw.find('cctv-gizmo:').spec.id;
gizmo.setEnabled(true);
handler.fire(FAKE_EVENT_TYPES.LEFT_DOWN, { position: { x: 5, y: 5 } });
assert.equal(gizmo.isDragging(), true);
assert.equal(viewer.scene.canvas.style.cursor, 'grabbing');
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 12, y: 5 },
});
assert.equal(patches.length, 1);
const [patch, pinned] = patches[0];
assert.equal(pinned, record, 'patched on the record dragged');
assert.ok(Math.abs(patch.offsetEastM - 9) < 1e-6, `${patch.offsetEastM}`);
handler.fire(FAKE_EVENT_TYPES.LEFT_UP, { position: { x: 12, y: 5 } });
assert.equal(gizmo.isDragging(), false);
});
test('hovering a handle grows it and shows the grab cursor', (t) => {
let pointSet = null;
let over = true;
const { viewer, draw } = gizmoViewer(t, {
picked: () =>
over
? {
set: pointSet,
id: `${GIZMO_ID_PREFIX}handle-range`,
surface: false,
}
: null,
ray: null,
});
const { input, handler } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
const points = [...draw.sets.values()].find(
(set) => set.kind === 'points' && set.spec.id.startsWith('cctv-gizmo:'),
);
pointSet = points.spec.id;
gizmo.setEnabled(true);
const size = () =>
points.items.get(`${GIZMO_ID_PREFIX}handle-range`).pixelSize;
assert.equal(size(), 13);
handler.fire(FAKE_EVENT_TYPES.MOUSE_MOVE, {
startPosition: { x: 5, y: 5 },
endPosition: { x: 6, y: 5 },
});
assert.equal(size(), 17);
assert.equal(viewer.scene.canvas.style.cursor, 'grab');
});
test('the harness reads each part as drawn, an arrow with its line and tip', (t) => {
const { viewer } = gizmoViewer(t, { picked: () => null, ray: null });
const { input } = fakeInput(viewer);
t.after(() => input.destroy());
const record = gizmoRecord();
const gizmo = createCalibrationGizmo({
viewer,
getActiveRecord: () => record,
applyPatch() {},
endPatch() {},
});
t.after(() => gizmo.destroy());
assert.deepEqual(gizmo.partsForTest(), {}, 'nothing drawn before ADJUST');
gizmo.setEnabled(true);
const parts = gizmo.partsForTest();
const arrow = parts[`${GIZMO_ID_PREFIX}move-east`];
assert.equal(arrow.positions.length, 2, 'its line');
assert.deepEqual(arrow.pos, arrow.positions[1], 'its tip');
assert.equal(arrow.show, true);
assert.equal(parts[`${GIZMO_ID_PREFIX}ring-heading`].show, true);
assert.ok(parts[`${GIZMO_ID_PREFIX}handle-range`].pos);
gizmo.setEnabled(false);
assert.ok(
Object.values(gizmo.partsForTest()).every((part) => part.show === false),
);
});
+83 -75
View File
@@ -2,9 +2,11 @@
// near the screen show, a zoomed-out view keeps one camera per world-anchored // near the screen show, a zoomed-out view keeps one camera per world-anchored
// cell, and the layer's UI state never rebuilds every camera for a listener // cell, and the layer's UI state never rebuilds every camera for a listener
// that does not read the list. // that does not read the list.
import { test } from 'node:test'; import { afterEach, test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import cctvLayer, { import cctvLayer, {
_cctvIconsForTest, _cctvIconsForTest,
_setCctvCoverageStateForTest, _setCctvCoverageStateForTest,
@@ -15,18 +17,10 @@ import cctvLayer, {
const WIDTH = 800; const WIDTH = 800;
const HEIGHT = 600; const HEIGHT = 600;
/** /** Records at the given [lon, lat] degrees near the origin. */
* Records at the given [lon, lat] degrees near the origin, each drawn at the function recordsAt(lonLats) {
* screen point `screenAt` gives it (default: the middle of the screen).
*/
function recordsAt(
lonLats,
screenAt = () => ({ x: WIDTH / 2, y: HEIGHT / 2 }),
) {
const screenByPosition = new Map();
const records = lonLats.map(([lon, lat], index) => { const records = lonLats.map(([lon, lat], index) => {
const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10); const position = Cesium.Cartesian3.fromDegrees(lon, lat, 10);
screenByPosition.set(position, screenAt(index));
return { return {
camera: { camera: {
id: `cam-${index}`, id: `cam-${index}`,
@@ -40,42 +34,62 @@ function recordsAt(
rangeM: 145, rangeM: 145,
mountHeightM: 8, mountHeightM: 8,
}, },
position, position: { x: position.x, y: position.y, z: position.z },
coverageEntities: [], coverageEntities: [],
projection: null, projection: null,
}; };
}); });
return { records, screenByPosition }; return { records };
} }
function viewerAt(heightM, screenByPosition, shiftX = 0) { /**
return { * A viewer looking straight down from `heightM` over `lonDeg` on the
isDestroyed: () => false, * equator, north up, through a camera port: the view pass projects the
camera: { * cameras from its pose.
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM), */
positionCartographic: { latitude: 0, longitude: 0, height: heightM }, function viewerAt(heightM, lonDeg = 0) {
frustum: { fovy: Math.PI / 3 }, const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const north = { x: 0, y: 0, z: 1 };
const right = Cesium.Cartesian3.cross(down, north, new Cesium.Cartesian3());
const { port } = fakeCameraPort({
pose: {
lon: lonDeg,
lat: 0,
height: heightM,
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: north,
right: { x: right.x, y: right.y, z: right.z },
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
}, },
scene: { });
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
cartesianToCanvasCoordinates: (position) => { }),
// Match by value: a record's position may be a copy of the fixture's. );
const key = [...screenByPosition.keys()].find((candidate) => return viewer;
Cesium.Cartesian3.equals(candidate, position),
);
const screen = screenByPosition.get(key);
return screen && { x: screen.x + shiftX, y: screen.y };
},
},
};
} }
/** The renderers bound for the running test, let go when it ends. */
const bindings = [];
afterEach(() => {
for (const unbind of bindings.splice(0)) unbind();
});
function shownIds(records) { function shownIds(records) {
const icons = _cctvIconsForTest();
return records return records
.filter((record) => { .filter((record) => icons.item(record.camera.id)?.show === true)
const icons = _cctvIconsForTest();
return icons.shown(icons.row(record.camera.id));
})
.map((record) => record.camera.id) .map((record) => record.camera.id)
.sort(); .sort();
} }
@@ -89,9 +103,9 @@ const CLUSTER = [
]; ];
test('zoomed out, cameras sharing a ground cell show one icon', () => { test('zoomed out, cameras sharing a ground cell show one icon', () => {
const { records, screenByPosition } = recordsAt(CLUSTER); const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition), viewer: viewerAt(20_000),
records, records,
}); });
assert.equal( assert.equal(
@@ -106,34 +120,34 @@ test('zoomed out, cameras sharing a ground cell show one icon', () => {
}); });
test('a pan keeps the same winners, and an unchanged view keeps its list', () => { test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
const { records, screenByPosition } = recordsAt(CLUSTER, (index) => ({ const { records } = recordsAt(CLUSTER);
x: 100 + index * 7,
y: 300,
}));
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition), viewer: viewerAt(20_000),
records, records,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
const before = shownIds(records); const before = shownIds(records);
const list = _viewRecordIdsForTest(); const list = _viewRecordIdsForTest();
for (const shiftX of [3, 11, 20, 37]) { // A pan of a few to some 40 px (a pixel is about 30 m from 20 km up).
for (const shiftM of [90, 330, 600, 1110]) {
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition, shiftX), viewer: viewerAt(20_000, shiftM / 111_320),
records, records,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
assert.deepEqual(shownIds(records), before, `pan by ${shiftX} px`); assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`);
} }
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing');
assert.deepEqual(_viewRecordIdsForTest(), list); assert.deepEqual(_viewRecordIdsForTest(), list);
}); });
test('a small zoom within one cell size keeps the same winners', () => { test('a small zoom within one cell size keeps the same winners', () => {
const { records, screenByPosition } = recordsAt(CLUSTER); const { records } = recordsAt(CLUSTER);
const shownAt = (heightM) => { const shownAt = (heightM) => {
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(heightM, screenByPosition), viewer: viewerAt(heightM),
records, records,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
@@ -145,11 +159,11 @@ test('a small zoom within one cell size keeps the same winners', () => {
}); });
test('a healthy camera wins its cell over an unknown one', () => { test('a healthy camera wins its cell over an unknown one', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); const { records } = recordsAt(CLUSTER.slice(0, 2));
// Whichever camera the id order would pick, the healthy one must win. // Whichever camera the id order would pick, the healthy one must win.
for (const id of ['cam-0', 'cam-1']) { for (const id of ['cam-0', 'cam-1']) {
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition), viewer: viewerAt(20_000),
records, records,
healthById: new Map([[id, { status: 'ok' }]]), healthById: new Map([[id, { status: 'ok' }]]),
}); });
@@ -159,34 +173,31 @@ test('a healthy camera wins its cell over an unknown one', () => {
}); });
test('the active camera always shows, even in a crowded cell', () => { test('the active camera always shows, even in a crowded cell', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3)); const { records } = recordsAt(CLUSTER.slice(0, 3));
for (const active of records) { for (const active of records) {
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition), viewer: viewerAt(20_000),
records, records,
activeCameraId: active.camera.id, activeCameraId: active.camera.id,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
const icons = _cctvIconsForTest(); const icons = _cctvIconsForTest();
assert.ok( assert.ok(
icons.shown(icons.row(active.camera.id)), icons.item(active.camera.id).show,
`${active.camera.id} shows while active`, `${active.camera.id} shows while active`,
); );
} }
}); });
test('close up, every camera near the screen shows and far-off ones hide', () => { test('close up, every camera near the screen shows and far-off ones hide', () => {
const { records, screenByPosition } = recordsAt( // From 300 m up the screen spans some 460 m: the third camera is 1.1 km off.
[ const { records } = recordsAt([
[0, 0], [0, 0],
[0.0001, 0], [0.0001, 0],
[0.0002, 0], [0.01, 0],
], ]);
(index) =>
index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 },
);
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition), viewer: viewerAt(300),
records, records,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
@@ -194,9 +205,9 @@ test('close up, every camera near the screen shows and far-off ones hide', () =>
}); });
test('a disabled layer skips the view pass', () => { test('a disabled layer skips the view pass', () => {
const { records, screenByPosition } = recordsAt(CLUSTER); const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition), viewer: viewerAt(20_000),
records, records,
enabled: false, enabled: false,
}); });
@@ -205,9 +216,9 @@ test('a disabled layer skips the view pass', () => {
}); });
test('UI state builds the full camera list only when it is read', () => { test('UI state builds the full camera list only when it is read', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2)); const { records } = recordsAt(CLUSTER.slice(0, 2));
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition), viewer: viewerAt(300),
records, records,
}); });
refreshHorizonCulling(); refreshHorizonCulling();
@@ -238,16 +249,13 @@ test('UI state builds the full camera list only when it is read', () => {
}); });
test('the camera picker lists the view, with the active camera first', () => { test('the camera picker lists the view, with the active camera first', () => {
const { records, screenByPosition } = recordsAt( const { records } = recordsAt([
[ [0, 0],
[0, 0], [0.01, 0],
[0.0001, 0], [0.0002, 0],
[0.0002, 0], ]);
],
(index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }),
);
_setCctvCoverageStateForTest({ _setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition), viewer: viewerAt(300),
records, records,
activeCameraId: 'cam-1', activeCameraId: 'cam-1',
}); });
+9 -6
View File
@@ -4,7 +4,7 @@ import { applyVesselFocusDeemphasis } from './aisLiveVessels.js';
import { applyCctvFocusDeemphasis } from './cctv.js'; import { applyCctvFocusDeemphasis } from './cctv.js';
import { applySatellitePointFocusDeemphasis } from './satellites.js'; import { applySatellitePointFocusDeemphasis } from './satellites.js';
import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js';
import { createIconSet } from './iconSet.js'; import { createIconBook } from '../render/motion/iconBook.js';
import { createVesselIconBook } from '../layers/vessels/iconBook.js'; import { createVesselIconBook } from '../layers/vessels/iconBook.js';
const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 }; const params = { ...DEFAULT_FOCUS_DEEMPHASIS_PARAMS, paddingPx: 0 };
@@ -88,10 +88,13 @@ assertResumeGate('vessel', () => {
}); });
assertResumeGate('CCTV', () => { assertResumeGate('CCTV', () => {
const icons = createIconSet(); const icons = createIconBook();
const row = icons.add('cam-1', { id: 'cam-1' }); icons.put({
icons.setSize(row, 24, 24); id: 'cam-1',
icons.setShown(row, true); pos: { x: 1, y: 2, z: 3 },
size: [24, 24],
meta: { id: 'cam-1' },
});
const record = { camera: { id: 'cam-1' }, position: { x: 1, y: 2, z: 3 } }; const record = { camera: { id: 'cam-1' }, position: { x: 1, y: 2, z: 3 } };
return { return {
pass: ({ nowMs, target: focusTarget, previousActiveCount }) => pass: ({ nowMs, target: focusTarget, previousActiveCount }) =>
@@ -105,7 +108,7 @@ assertResumeGate('CCTV', () => {
cameraDistanceFor: () => 1200, cameraDistanceFor: () => 1200,
params, params,
}), }),
readAlpha: () => icons.focus(icons.row('cam-1')), readAlpha: () => icons.focus('cam-1'),
}; };
}); });
+39
View File
@@ -60,3 +60,42 @@ export function sphereOutside(planes, center, radius) {
if (dot(normal, center) + w < -radius) return true; if (dot(normal, center) + w < -radius) return true;
return false; return false;
} }
/**
* Canvas coordinates (CSS px, origin top left) of world points on a `width`
* by `height` canvas, as the default renderer projects them from `pose`
* (its frustum's projection matrix times its view matrix, centred, no
* offset): one pose read for many points, rather than a renderer call per
* point. Null behind the eye and before the projection's clip plane at
* `2·far·near / (far + near)` (a little past `near`; `2·near` with no far
* plane), where the renderer's own projection answers nothing.
* @param {{position: object, direction: object, up: object, fovy: number,
* aspectRatio: number, near: number, far: number}} pose
* @param {number} width
* @param {number} height
* @param {{x: number, y: number}} [out] Written and returned by every call.
* @returns {(p: {x: number, y: number, z: number}) =>
* ({x: number, y: number}|null)}
*/
export function poseProjector(pose, width, height, out = { x: 0, y: 0 }) {
const { position: e, direction: d, up: u, near, far } = pose;
const r = cross(d, u);
const tanY = Math.tan(0.5 * pose.fovy);
const tanX = pose.aspectRatio * tanY;
// With no far plane the clip plane is at twice `near`, its limit.
const clipDepth = Number.isFinite(far)
? (2 * far * near) / (far + near)
: 2 * near;
return (p) => {
const vx = p.x - e.x;
const vy = p.y - e.y;
const vz = p.z - e.z;
const depth = vx * d.x + vy * d.y + vz * d.z;
if (!(depth > 0) || depth < clipDepth) return null;
const x = (vx * r.x + vy * r.y + vz * r.z) / (depth * tanX);
const y = (vx * u.x + vy * u.y + vz * u.z) / (depth * tanY);
out.x = (x + 1) * 0.5 * width;
out.y = (1 - y) * 0.5 * height;
return out;
};
}
+108 -1
View File
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { frustumPlanes, sphereOutside } from './frustum.js'; import { frustumPlanes, poseProjector, sphereOutside } from './frustum.js';
/** A camera pose and the Cesium frustum it describes. */ /** A camera pose and the Cesium frustum it describes. */
function camera({ position, direction, up, fovy, aspectRatio, near, far }) { function camera({ position, direction, up, fovy, aspectRatio, near, far }) {
@@ -72,3 +72,110 @@ test('the frustum culls spheres as the default renderer does', () => {
assert.equal(sphereOutside(planes, behind, 1), true); assert.equal(sphereOutside(planes, behind, 1), true);
} }
}); });
test('points project to the canvas as the default renderer projects them', () => {
const eye = Cesium.Cartesian3.fromDegrees(-0.12, 51.5, 600);
const target = Cesium.Cartesian3.fromDegrees(-0.11, 51.505, 0);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const east = unit(-eye.y, eye.x, 0);
const up = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(east, direction, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
// Landscape and portrait canvases, each at a near and a far `near`.
for (const [width, height, near] of [
[1280, 720, 0.1],
[1280, 720, 25],
[600, 900, 0.1],
]) {
const { pose } = camera({
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: direction.x, y: direction.y, z: direction.z },
up: { x: up.x, y: up.y, z: up.z },
fovy: 0.9,
aspectRatio: width / height,
near,
far: 5e8,
});
// The renderer's view-projection: its frustum's projection matrix times
// the view matrix of the eye's right, up and direction.
const frustum = new Cesium.PerspectiveFrustum({
// Cesium's `fov` is across the canvas's wider side.
fov:
pose.aspectRatio <= 1
? pose.fovy
: 2 * Math.atan(Math.tan(pose.fovy / 2) * pose.aspectRatio),
aspectRatio: pose.aspectRatio,
near,
far: pose.far,
});
const right = Cesium.Cartesian3.cross(
direction,
up,
new Cesium.Cartesian3(),
);
const view = Cesium.Matrix4.computeView(
eye,
direction,
up,
right,
new Cesium.Matrix4(),
);
const m = Cesium.Matrix4.multiply(
frustum.projectionMatrix,
view,
new Cesium.Matrix4(),
);
const project = poseProjector(pose, width, height);
let shown = 0;
for (let i = 0; i < 400; i++) {
const p = Cesium.Cartesian3.fromDegrees(
-0.12 + ((i % 20) - 10) * 0.002,
51.5 + (Math.floor(i / 20) - 10) * 0.002,
(i % 9) * 80,
);
const clip = Cesium.Matrix4.multiplyByVector(
m,
new Cesium.Cartesian4(p.x, p.y, p.z, 1),
new Cesium.Cartesian4(),
);
const ours = project(p);
if (!(clip.w > 0) || clip.z < 0) {
assert.equal(ours, null, `${i} is not drawn`);
continue;
}
shown += 1;
const x = (clip.x / clip.w + 1) * 0.5 * width;
const y = (1 - clip.y / clip.w) * 0.5 * height;
// Off-screen points land far out: compared to a part in 1e9.
const close = (a, b) => Math.abs(a - b) <= 1e-6 + 1e-9 * Math.abs(b);
assert.ok(close(ours.x, x), `${i} x`);
assert.ok(close(ours.y, y), `${i} y`);
}
assert.ok(shown > 0 && shown < 400, 'some points in front, some not');
}
// Just before the clip plane past `near`: nothing, as the renderer.
const { pose } = camera({
position: { x: 0, y: 0, z: 0 },
direction: { x: 1, y: 0, z: 0 },
up: { x: 0, y: 0, z: 1 },
fovy: 1,
aspectRatio: 1,
near: 10,
far: 1000,
});
const project = poseProjector(pose, 100, 100);
const clipDepth = (2 * 1000 * 10) / 1010;
assert.equal(project({ x: clipDepth - 1e-6, y: 0, z: 0 }), null);
assert.deepEqual(project({ x: clipDepth + 1e-6, y: 0, z: 0 }), {
x: 50,
y: 50,
});
// An infinite far plane clips at twice `near`, the limit of the finite rule.
const endless = poseProjector({ ...pose, far: Infinity }, 100, 100);
assert.equal(endless({ x: 20 - 1e-6, y: 0, z: 0 }), null);
assert.deepEqual(endless({ x: 20 + 1e-6, y: 0, z: 0 }), { x: 50, y: 50 });
});
+2
View File
@@ -261,6 +261,8 @@ export function createCalibration({
// §9.1: touching range takes manual control — clear the activation clamp. // §9.1: touching range takes manual control — clear the activation clamp.
if ('rangeScale' in patch) { if ('rangeScale' in patch) {
record.probeClampRangeM = null; record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
} }
const anchorMoved = calibrationPatchMovesAnchor(patch); const anchorMoved = calibrationPatchMovesAnchor(patch);
if (options.transient === true && anchorMoved) { if (options.transient === true && anchorMoved) {
+188
View File
@@ -0,0 +1,188 @@
/**
* @module layers/cctv/drawSets
* @description The CCTV layer's draw sets: the frustum wireframes
* (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the
* active camera's monitor plane (`plane`, a quad), made through the draw
* port of the viewer the layer is on. They are made when first drawn into
* and made again on another viewer. Item ids keep the layer's
* `cctv-<cameraId>-<role>` scheme the shared pick registry reads, and each
* line's and plane's `meta.cameraId` names its camera (volumes are never
* picked and carry none).
*
* Coverage lines and the plane are written from handles the layer keeps
* (a record's `coverageEntities`, a projection runtime's `plane`): plain
* objects the layer changes and then writes, only what changed reaching
* the set.
*/
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
let instances = 0;
/** A line handle's item, or null for a handle that names no line yet. */
function lineItemOf(handle) {
if (!handle?.id || !Array.isArray(handle.positions)) return null;
const color = handle.color;
return {
id: handle.id,
positions: handle.positions,
widthPx: handle.widthPx,
// As a polyline entity runs: along the ellipsoid between its positions.
mode: 'geodesic',
style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color },
depthFailColor: handle.depthFailColor ?? null,
meta: { cameraId: handle.cameraId },
show: handle.show !== false,
};
}
/** What a line item draws, as a key: an unchanged key is not written. */
const lineKey = (item) =>
[
item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'),
item.widthPx,
item.style.kind,
item.style.color.join(','),
item.depthFailColor ? item.depthFailColor.join(',') : '',
item.show,
].join('|');
/** The plane handle's quad item. */
function quadItemOf(plane) {
return {
id: plane.id,
center: plane.center,
orientation: plane.orientation,
size: plane.size,
source: plane.source,
alpha: plane.alpha,
outline: plane.outline,
meta: { cameraId: plane.cameraId },
show: plane.show === true,
};
}
export function createDrawSets({ state: layerState }) {
/** The live sets and the viewer they draw on, or null. */
let current = null;
/** Viewshed volumes written, ever (the QA harness checks for churn). */
let volumeWrites = 0;
/** The layer's sets on its viewer now, made if need be; null with none. */
function sets() {
const viewer = layerState._viewer;
if (!viewer) return null;
if (current?.viewer === viewer) return current;
dispose();
const draw = drawOf(viewer);
const n = ++instances;
current = {
viewer,
coverage: draw.lines({ id: `cctv:${n}:coverage` }),
viewshed: draw.meshes({ id: `cctv:${n}:viewshed`, pickable: false }),
plane: draw.quads({ id: `cctv:${n}:plane` }),
// What each line item was last written as, by id.
lineKeys: new Map(),
};
return current;
}
/** The live sets, without making them. */
const live = () =>
current && current.viewer === layerState._viewer ? current : null;
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set.dispose();
} catch {
// Its viewer went first.
}
current = null;
}
/** The ids of the sets that draw the layer's lines and plane. */
function pickableSetIds() {
const s = live();
return s ? [s.coverage.id, s.plane.id] : [];
}
/** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */
function roleOfSet(setId) {
const s = live();
if (!s) return null;
if (setId === s.coverage.id) return 'coverage';
if (setId === s.plane.id) return 'plane';
return null;
}
/** Write line handles that changed since they were last written. */
function writeLines(handles) {
if (!handles?.length) return;
const s = handles.some((h) => h?.id) ? sets() : null;
if (!s) return;
const changed = [];
for (const handle of handles) {
const item = lineItemOf(handle);
if (!item) continue;
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
}
/** Take every line out. */
function clearLines() {
const s = live();
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
sets()?.plane.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
if (plane?.id) live()?.plane.remove([plane.id]);
}
/** Write a viewshed volume. */
function writeVolume(item) {
const s = sets();
if (!s) return;
s.viewshed.upsert([item]);
volumeWrites += 1;
}
/** Take a viewshed volume out. */
function removeVolume(id) {
if (id) live()?.viewshed.remove([id]);
}
/** How many viewshed volumes were written, for the QA harness. */
const volumeWritesForTest = () => volumeWrites;
return {
sets,
dispose,
pickableSetIds,
roleOfSet,
writeLines,
clearLines,
writePlane,
removePlane,
writeVolume,
removeVolume,
volumeWritesForTest,
};
}
+110
View File
@@ -0,0 +1,110 @@
// The CCTV layer's draw sets: lines written only as they change, dashed for
// an estimated bearing, the depth-fail colour passed as it is; the sets made
// again on another viewer and let go on dispose.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDrawSets } from './drawSets.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const line = (id, fields = {}) => ({
id,
cameraId: 'cam',
role: 'edge',
positions: [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
],
widthPx: 1.2,
color: [0.1, 0.2, 0.3, 0.4],
dashed: false,
depthFailColor: null,
show: true,
...fields,
});
test('lines are written as they change, and drawn as their handles say', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
const a = line('cctv-cam-ray-tl');
const b = line('cctv-cam-cap', { role: 'cap' });
drawSets.writeLines([a, b]);
const coverage = draw.find('cctv:');
assert.equal(coverage.kind, 'lines');
assert.equal(coverage.writes, 1);
assert.deepEqual(coverage.items.get(a.id), {
id: a.id,
positions: a.positions,
widthPx: 1.2,
mode: 'geodesic',
style: { kind: 'solid', color: a.color },
depthFailColor: null,
meta: { cameraId: 'cam' },
show: true,
});
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 1, 'unchanged handles write nothing');
b.dashed = true;
b.depthFailColor = [1, 1, 1, 0.2];
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 2);
const cap = coverage.items.get(b.id);
assert.deepEqual(cap.style, {
kind: 'dash',
color: b.color,
length: 16,
pattern16: 255,
});
assert.deepEqual(cap.depthFailColor, [1, 1, 1, 0.2]);
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null);
drawSets.clearLines();
assert.equal(coverage.items.size, 0);
drawSets.writeLines([a]);
assert.ok(coverage.items.has(a.id), 'a cleared line is written again');
} finally {
unbind();
}
});
test('another viewer gets sets of its own; dispose lets them go', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
const old = one.draw.find('cctv:');
assert.equal(drawSets.volumeWritesForTest(), 1);
state._viewer = second;
assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet');
drawSets.writeLines([a]);
assert.ok(old.disposed, 'the old viewer’s sets are let go');
const now = two.draw.find('cctv:');
assert.ok(now.items.has(a.id), 'the line is written anew');
const [coverage, plane] = drawSets.pickableSetIds();
assert.equal(two.draw.set(coverage).kind, 'lines');
assert.equal(two.draw.set(plane).kind, 'quads');
assert.equal(drawSets.roleOfSet(plane), 'plane');
drawSets.dispose();
assert.ok(
[...two.draw.sets.values()].every((set) => set.disposed),
'every set is let go',
);
assert.equal(drawSets.roleOfSet(coverage), null);
} finally {
one.unbind();
two.unbind();
}
});
+8 -8
View File
@@ -106,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Blits the latest projection canvas into the next of two alternating * Blits the latest projection canvas into the next of two alternating
* offscreen buffer canvases and returns it (H5). * offscreen buffer canvases and returns it (H5).
* *
* Two buffers are required because Cesium's Material image path re-uploads a * Two buffers are required because the plane re-uploads a canvas texture
* canvas texture only when the uniform receives a NEW object reference — * only when it is given a NEW canvas — redrawing the same canvas in place
* redrawing the same canvas in place is invisible to the GPU. Alternating * is invisible to the GPU. Alternating
* references forces a texture recreate, which at <=1Hz and 1080p is cheap. * references forces a texture recreate, which at <=1Hz and 1080p is cheap.
* *
* @param {Object} runtime - Projection runtime with `.canvas`. * @param {Object} runtime - Projection runtime with `.canvas`.
@@ -139,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Pushes fresh pixels into the monitor plane material. Called every * Pushes fresh pixels into the monitor plane material. Called every
* projection tick. * projection tick.
* *
* Video feeds are skipped entirely — their HTMLVideoElement uniform is * Video feeds are skipped entirely — the renderer reads their
* updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap * HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap
* the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS. * the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS.
* *
* @param {Object} record - Camera record with an initialized projection runtime. * @param {Object} record - Camera record with an initialized projection runtime.
@@ -156,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
) )
return; return;
const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial); const planeShowing = !!runtime.plane?.show;
if (!planeShowing) return; if (!planeShowing) return;
// Only swap when the canvas content actually changed since the last swap. // Only swap when the canvas content actually changed since the last swap.
@@ -170,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
if (!buffer) return; if (!buffer) return;
runtime.lastTextureSwapAt = now; runtime.lastTextureSwapAt = now;
runtime.lastSwappedCanvasStamp = runtime.canvasStamp; runtime.lastSwappedCanvasStamp = runtime.canvasStamp;
runtime.planeMaterial.image = buffer; parts.projection.setPlaneSource(runtime, { canvas: buffer });
} }
/** /**
@@ -346,7 +346,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
// camera republished once in 5 minutes, an Austin one not at all. // camera republished once in 5 minutes, an Austin one not at all.
// Redrawing regardless bumped canvasStamp, which forced a buffer swap // Redrawing regardless bumped canvasStamp, which forced a buffer swap
// and a fresh 1920x1080 texture upload; the plane renders its white // 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 // two Cesium needs to rebind, which IS the periodic white flash from the
// owner field tests (2026-07-04 and 2026-07-30). // owner field tests (2026-07-04 and 2026-07-30).
const fit = fitToProjection( const fit = fitToProjection(
+46 -37
View File
@@ -314,30 +314,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.position = positions.mount; record.position = positions.mount;
record.camera.absoluteHeightM = geometry.mount.alt; record.camera.absoluteHeightM = geometry.mount.alt;
parts.rendering.moveCameraIcon(record); parts.rendering.moveCameraIcon(record);
record.groundAltM = groundAltM;
if (record.coverageEntities?.length >= 5) { if (record.coverageEntities?.length >= 5) {
record.coverageEntities[0].polyline.positions = [ parts.rendering.placeCoverageLines(record.coverageEntities, positions);
positions.mount, parts.drawSets.writeLines(record.coverageEntities);
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,
];
} }
// A live viewshed volume tracks its wireframe: rebuild from the SAME fresh // A live viewshed volume tracks its wireframe: rebuild from the SAME fresh
// positions (weld invariant). Only records currently showing a volume pay // positions (weld invariant). Only records currently showing a volume pay
@@ -345,7 +325,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
// Tint derives from the live active id, not the cached viewshedActiveTint — // Tint derives from the live active id, not the cached viewshedActiveTint —
// during an activation switch this runs BEFORE refreshCoverageStyles, and // during an activation switch this runs BEFORE refreshCoverageStyles, and
// the cache is stale for exactly that window. // the cache is stale for exactly that window.
if (record.viewshedPrimitive) { if (record.viewshedVolume) {
parts.rendering.rebuildViewshedVolume( parts.rendering.rebuildViewshedVolume(
record, record,
record.camera.id === layerState._activeCameraId, record.camera.id === layerState._activeCameraId,
@@ -420,11 +400,9 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.groundMeshSampleRequestCount = record.groundMeshSampleRequestCount =
(record.groundMeshSampleRequestCount || 0) + 1; (record.groundMeshSampleRequestCount || 0) + 1;
const eye = parts.model.eyePose(); const eye = parts.model.eyePose();
const excludeObjects = [...(record.coverageEntities || [])]; // The layer's own lines and plane are not ground; named all the same.
if (record.projection?.planeEntity) sampleMeshFloorCells(layerState._viewer, [point], {
excludeObjects.push(record.projection.planeEntity); sets: parts.drawSets.pickableSetIds(),
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
excludeObjects: excludeObjects.filter(Boolean),
viewerLat: eye ? eye.lat : undefined, viewerLat: eye ? eye.lat : undefined,
viewerLon: eye ? eye.lon : undefined, viewerLon: eye ? eye.lon : undefined,
}); });
@@ -526,7 +504,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
/** /**
* §9.1 activation obstruction probe (LOCKED owner decision): on camera * §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 * (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 * 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. * "big and dramatic" true end cap never clips into downtown buildings.
@@ -535,28 +513,58 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* never per-frame (the zero-raycast invariant applies to steady state). The * 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 * per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range. * probe entirely. Probe failure/miss keeps the unclamped range.
*
* The cast is made now, against the scene as it is, and answers a
* microtask later: the clamp then lands by rewriting the geometry from the
* ground it was last written at, before the next frame draws. A newer
* activation, or the camera's deactivation, drops an answer still to come.
* @param {Object} record - Camera record being activated. * @param {Object} record - Camera record being activated.
* @returns {Promise<void>} Settled once the clamp (if any) has landed.
*/ */
function runActivationObstructionProbe(record) { function runActivationObstructionProbe(record) {
record.probeClampRangeM = null; record.probeClampRangeM = null;
if (!parts.rendering.canPickFromRay()) return; const token = (record.probeToken = (record.probeToken || 0) + 1);
const viewer = layerState._viewer;
if (!parts.rendering.canPickFromRay()) return Promise.resolve();
const camera = record.camera; const camera = record.camera;
const rangeScale = parts.calibration.normalizeCalibration( const rangeScale = parts.calibration.normalizeCalibration(
camera.calibration, camera.calibration,
).rangeScale; ).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 { try {
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM; const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt); const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
const { dir } = frustumFrameEcef(camera, mountPos); const { dir } = frustumFrameEcef(camera, mountPos);
// The rendering part sees through everything the layer draws. // The cast sees through everything the layer draws.
const hit = parts.rendering.obstructionHit(mountPos, dir); return Promise.resolve(parts.rendering.obstructionHit(mountPos, dir))
if (!hit?.position) return; .then((hit) => {
const dist = distance(mountPos, hit.position); if (!hit || record.probeToken !== token) return;
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist); if (record.camera.id !== layerState._activeCameraId) return;
// A layer torn down or re-initialised since (another viewer, or
// a new record for the same camera) is not the one it asked for.
if (layerState._viewer !== viewer) return;
if (layerState._recordById?.get(record.camera.id) !== record) return;
const dist = distance(mountPos, hit);
const clamp = activationProbeClampRange(camera.rangeM, dist);
if (!Number.isFinite(clamp)) return;
record.probeClampRangeM = clamp;
if (Number.isFinite(record.groundAltM))
applyFrustumGeometry(record, record.groundAltM);
// The activation asked for the ground under the unclamped plane's
// footprint; the clamped plane's is asked for now, and the layer
// restyles and tells its listeners, as that answer will.
void parts.ground.resolveFootprintGround(record);
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
})
.catch(() => {
// probe failure → keep the unclamped range
});
} catch { } catch {
// probe failure → keep the unclamped range // probe failure → keep the unclamped range
return Promise.resolve();
} }
} }
@@ -569,6 +577,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
*/ */
function clearProbeClampOnDeactivation(record, rewriteGeometry) { function clearProbeClampOnDeactivation(record, rewriteGeometry) {
if (record) record.probeToken = (record.probeToken || 0) + 1;
if (!record || !Number.isFinite(record.probeClampRangeM)) return false; if (!record || !Number.isFinite(record.probeClampRangeM)) return false;
record.probeClampRangeM = null; record.probeClampRangeM = null;
rewriteGeometry?.(record); rewriteGeometry?.(record);
+88
View File
@@ -92,3 +92,91 @@ test('the frustum axis and plane orientation match the renderer transforms exact
assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]); 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);
});
+3
View File
@@ -18,6 +18,7 @@ import { createHealth } from './health.js';
import { createControls } from './controls.js'; import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js'; import { createIngestion } from './ingestion.js';
import { createState } from './state.js'; import { createState } from './state.js';
import { createDrawSets } from './drawSets.js';
/** Construct one layer with its own scene state and supplied application services. */ /** Construct one layer with its own scene state and supplied application services. */
export function createCctvLayer({ services, source }) { export function createCctvLayer({ services, source }) {
@@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) {
const state = createState({ services }); const state = createState({ services });
const parts = {}; const parts = {};
const context = { state, services, parts, source }; const context = { state, services, parts, source };
parts.drawSets = createDrawSets(context);
parts.calibration = createCalibration(context); parts.calibration = createCalibration(context);
parts.testing = createTesting(context); parts.testing = createTesting(context);
parts.projection = createProjection(context); parts.projection = createProjection(context);
@@ -111,6 +113,7 @@ export function createCctvLayer({ services, source }) {
parts.testing._extractPickedCameraIdForTest, parts.testing._extractPickedCameraIdForTest,
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest, _setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
_cctvIconsForTest: parts.testing._cctvIconsForTest, _cctvIconsForTest: parts.testing._cctvIconsForTest,
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
focusCctvRecord: parts.navigation.focusCctvRecord, focusCctvRecord: parts.navigation.focusCctvRecord,
maybeAutoHop: parts.navigation.maybeAutoHop, maybeAutoHop: parts.navigation.maybeAutoHop,
cctvCycleIndex: parts.navigation.cctvCycleIndex, cctvCycleIndex: parts.navigation.cctvCycleIndex,
+2 -2
View File
@@ -29,8 +29,8 @@ export function createIngestion({
layerState._tilesReadyReenqueued = true; layerState._tilesReadyReenqueued = true;
// Per-regime resolution (Task 5): only records unresolved for the // Per-regime resolution (Task 5): only records unresolved for the
// CURRENT surface regime need the completion pass. On globe stacks // CURRENT surface regime need the completion pass. On globe stacks
// projectionTilesReady() is false while a (hidden) Google tileset // projectionTilesReady() is false (only drawn photoreal tiles can be
// exists, so this latch effectively fires for the google-3d regime — // ready), so this latch fires for the google-3d regime alone —
// terrain-globe records resolve from the prior in their drain pass. // terrain-globe records resolve from the prior in their drain pass.
const unresolved = parts.geometryQueue const unresolved = parts.geometryQueue
.geometryWorkingSet() .geometryWorkingSet()
+13 -10
View File
@@ -22,7 +22,7 @@ export function createLifecycle({
parts, parts,
source, source,
}) { }) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites; const { registerSpriteSet, restoreSpriteOrder } = services.sprites;
const { activateCctvCameraFromWorldClick } = services.activation; const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } = const { resolvePickId, registerPickOwner, unregisterPickOwner } =
services.picking; services.picking;
@@ -157,6 +157,9 @@ export function createLifecycle({
// Idempotent — also covers a re-init without a prior destroy(). // Idempotent — also covers a re-init without a prior destroy().
parts.cards.teardownAmbientCards(); parts.cards.teardownAmbientCards();
parts.projection.clearProjectionOverlay(); 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._records = [];
layerState._recordById = new Map(); layerState._recordById = new Map();
layerState._viewRecords = []; layerState._viewRecords = [];
@@ -173,9 +176,6 @@ export function createLifecycle({
layerState._lastError = null; layerState._lastError = null;
layerState._lastFocusStyleAt = 0; layerState._lastFocusStyleAt = 0;
layerState._activeFocusStyleCount = 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 // Task 5: the applied-regime tracker is record-set-scoped — a fresh init
// recomputes it against the then-current scene. // recomputes it against the then-current scene.
layerState._lastAppliedRegime = null; layerState._lastAppliedRegime = null;
@@ -205,10 +205,10 @@ export function createLifecycle({
layerState._lastViewContext = ''; layerState._lastViewContext = '';
layerState._calibrationById = parts.calibration.loadCalibrationStore(); layerState._calibrationById = parts.calibration.loadCalibrationStore();
registerSpriteCollection( // A host without the sprite order still draws the icons, in the
'cctv', // order they were added.
parts.rendering.createCameraIcons(layerState._viewer), const iconSetId = parts.rendering.createCameraIcons(layerState._viewer);
); registerSpriteSet?.('cctv', iconSetId);
const sources = await parts.catalog.loadCameraSources(); const sources = await parts.catalog.loadCameraSources();
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources); const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
@@ -317,7 +317,7 @@ export function createLifecycle({
viewshedColors: viewshedColors( viewshedColors: viewshedColors(
cameraHue(hueIndexById.get(camera.id) ?? 0), cameraHue(hueIndexById.get(camera.id) ?? 0),
), ),
viewshedPrimitive: null, viewshedVolume: null,
viewshedActiveTint: false, viewshedActiveTint: false,
}; };
layerState._records.push(record); layerState._records.push(record);
@@ -396,7 +396,9 @@ export function createLifecycle({
(event) => { (event) => {
if (!layerState._enabled) return; if (!layerState._enabled) return;
const picked = event.pick; const picked = event.pick;
const cameraId = parts.selection.extractPickedCameraId(picked); const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
if (cameraId) { if (cameraId) {
activateCctvCameraFromWorldClick( activateCctvCameraFromWorldClick(
cameraId, cameraId,
@@ -582,6 +584,7 @@ export function createLifecycle({
parts.cards.teardownAmbientCards(); parts.cards.teardownAmbientCards();
parts.geometry.destroyCoverageEntities(); parts.geometry.destroyCoverageEntities();
parts.rendering.destroyCameraIcons(); parts.rendering.destroyCameraIcons();
parts.drawSets.dispose();
clearRuntimeState(); clearRuntimeState();
layerState._viewer = null; layerState._viewer = null;
layerState._enabled = false; layerState._enabled = false;
-7
View File
@@ -1,7 +0,0 @@
import { createEntityStore } from '../../data/entityRecords.js';
/**
* The camera a picked coverage ray or projection plane belongs to: `cameraId`
* is the upstream camera id. Gizmo entities never get one.
*/
export const cctvPicks = createEntityStore();
+6 -2
View File
@@ -179,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
heightM: 0, heightM: 0,
}); });
/** Base64-encoded SVG camera icon for the camera icon rows. */ /**
* 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 = (() => { 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> <defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1"> <linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/> <stop offset="0%" stop-color="#c9f6ff"/>
+86 -72
View File
@@ -1,16 +1,30 @@
import { attachCctvVideo } from './videoPlayback.js'; import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import { import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID, CCTV_PROJECTION_OVERLAY_SOURCE_ID,
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS, CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
PLANE_OUTLINE_COLOR as PLANE_OUTLINE_RGBA, PLANE_OUTLINE_COLOR,
PROJECTION_CANVAS_WIDTH, PROJECTION_CANVAS_WIDTH,
PROJECTION_CANVAS_HEIGHT, PROJECTION_CANVAS_HEIGHT,
} from './policy.js'; } from './policy.js';
import { cctvPicks } from './pickState.js';
import { toColor } from '../../render/cesium/draw.js';
const PLANE_OUTLINE_COLOR = toColor(PLANE_OUTLINE_RGBA); /** The monitor plane's alpha over its frame, as its image material had it. */
const PLANE_ALPHA = 0.95;
/** A plain white image, for a plane with no media (tests). */
const WHITE_IMAGE =
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">' +
'<rect width="1" height="1" fill="#fff"/></svg>',
);
/** Copy a position's coordinates into `out`. */
function copyPosition(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
export function createProjection({ export function createProjection({
state: layerState, state: layerState,
@@ -20,15 +34,9 @@ export function createProjection({
}) { }) {
const { holdContinuousRender, releaseContinuousRender } = services.render; const { holdContinuousRender, releaseContinuousRender } = services.render;
/** The monitor plane's orientation, as the Cesium quaternion its entity takes. */
function planeOrientation(camera, capCenter) {
const q = parts.model.planeOrientationFor(camera, capCenter);
return new Cesium.Quaternion(q.x, q.y, q.z, q.w);
}
/** /**
* Build the protected label associated with one active monitor plane. * 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. * @returns {Object} Shared-host presentation entry.
*/ */
@@ -56,7 +64,7 @@ export function createProjection({
} }
/** /**
* Re-derives the monitor plane entity's placement (position, orientation, * Re-derives the monitor plane's placement (position, orientation,
* dimensions) + label from the record's current frustum geometry, so the plane * dimensions) + label from the record's current frustum geometry, so the plane
* always caps the wireframe exactly (corner rays terminate on its corners). * 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). * No-op when the record has no plane runtime (idle neighbors have no plane).
@@ -65,7 +73,8 @@ export function createProjection({
function updatePlanePlacement(record) { function updatePlanePlacement(record) {
const runtime = record?.projection; const runtime = record?.projection;
if (!runtime?.planeEntity) return; const plane = runtime?.plane;
if (!plane) return;
const geometry = const geometry =
record.frustumGeometry || record.frustumGeometry ||
parts.geometry.computeFrustumGeometry( parts.geometry.computeFrustumGeometry(
@@ -75,20 +84,32 @@ export function createProjection({
); );
const positions = const positions =
record.frustumPositions || parts.rendering.frustumCartesians(geometry); record.frustumPositions || parts.rendering.frustumCartesians(geometry);
runtime.planeEntity.position = positions.capCenter; placePlane(plane, record.camera, geometry, positions);
runtime.planeEntity.orientation = planeOrientation( if (runtime.labelPosition)
record.camera, 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, positions.capCenter,
); );
if (runtime.planeEntity.plane) { plane.size = [geometry.halfW * 2, geometry.halfH * 2];
runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2( }
geometry.halfW * 2,
geometry.halfH * 2, /**
); * Give the monitor plane another image: a canvas, or the video element.
} * @param {Object} runtime - Projection runtime.
if (runtime.labelPosition) { * @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition); */
} function setPlaneSource(runtime, source) {
runtime.planeSource = source;
if (!runtime.plane) return;
runtime.plane.source = source;
parts.drawSets.writePlane(runtime.plane);
} }
/** /**
@@ -112,7 +133,10 @@ export function createProjection({
function setPlaneVisible(runtime, visible) { function setPlaneVisible(runtime, visible) {
if (!runtime) return; 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 (visible && runtime.overlayEntry && runtime.cameraId) {
if (layerState._projectionOverlayOwnerId !== runtime.cameraId) { if (layerState._projectionOverlayOwnerId !== runtime.cameraId) {
layerState._cctvOverlayHost.setEntries( layerState._cctvOverlayHost.setEntries(
@@ -131,40 +155,34 @@ export function createProjection({
} }
} }
/** A plain white plane material, for a plane with no media (tests). */ /** A plain white plane image, for a plane with no media (tests). */
function plainPlaneMaterial() { function plainPlaneSource() {
return new Cesium.ColorMaterialProperty(Cesium.Color.WHITE); return { image: WHITE_IMAGE };
} }
/** Create the native monitor plane plus its cached host-label presentation. */ /** Create the monitor plane plus its cached host-label presentation. */
function createProjectionPlane(record, runtime, geometry, positions) { function createProjectionPlane(record, runtime, geometry, positions) {
runtime.labelPosition ||= new Cesium.Cartesian3(); runtime.labelPosition ||= { x: 0, y: 0, z: 0 };
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition); copyPosition(positions.label, runtime.labelPosition);
runtime.cameraId = String(record.camera.id); runtime.cameraId = String(record.camera.id);
runtime.overlayEntry = createCctvProjectionOverlayEntry({ runtime.overlayEntry = createCctvProjectionOverlayEntry({
cameraId: runtime.cameraId, cameraId: runtime.cameraId,
name: record.camera.name, name: record.camera.name,
position: () => runtime.labelPosition, position: () => runtime.labelPosition,
}); });
runtime.planeEntity = layerState._viewer.entities.add({ const plane = {
id: `cctv-${record.camera.id}-plane`, id: `cctv-${record.camera.id}-plane`,
cameraId: record.camera.id,
source: runtime.planeSource || plainPlaneSource(),
alpha: PLANE_ALPHA,
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
show: false, show: false,
position: positions.capCenter, };
orientation: planeOrientation(record.camera, positions.capCenter), placePlane(plane, record.camera, geometry, positions);
plane: { runtime.plane = plane;
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0), parts.drawSets.writePlane(plane);
dimensions: new Cesium.Cartesian2( return plane;
geometry.halfW * 2,
geometry.halfH * 2,
),
material: runtime.planeMaterial,
outline: true,
outlineColor: PLANE_OUTLINE_COLOR,
},
});
cctvPicks.write(runtime.planeEntity).cameraId = record.camera.id;
return runtime.planeEntity;
} }
/** /**
@@ -196,11 +214,11 @@ export function createProjection({
ctx, ctx,
image: null, image: null,
video: null, video: null,
planeEntity: null, plane: null,
cameraId: String(record.camera.id), cameraId: String(record.camera.id),
labelPosition: new Cesium.Cartesian3(), labelPosition: { x: 0, y: 0, z: 0 },
overlayEntry: null, overlayEntry: null,
planeMaterial: null, planeSource: { canvas },
buffers: null, buffers: null,
bufferIndex: 0, bufferIndex: 0,
lastTextureSwapAt: 0, lastTextureSwapAt: 0,
@@ -231,16 +249,17 @@ export function createProjection({
video.playsInline = true; video.playsInline = true;
video.crossOrigin = 'anonymous'; video.crossOrigin = 'anonymous';
video.preload = 'auto'; video.preload = 'auto';
// Cesium sizes the video texture from the element's width/height // The plane shows the video once it knows its size (the element's
// attributes at first upload. Set them from the real stream dimensions // width/height follow the real stream dimensions); the renderer reads
// and rebind on any resolution change (camera switch, adaptive source). // it at a new size on any later resolution change (camera switch,
// adaptive source).
const bindVideoTexture = () => { const bindVideoTexture = () => {
if (runtime.video !== video || !runtime.planeMaterial) return; if (runtime.video !== video || runtime.disposed) return;
if (!(video.videoWidth > 0 && video.videoHeight > 0)) return; if (!(video.videoWidth > 0 && video.videoHeight > 0)) return;
video.width = video.videoWidth; video.width = video.videoWidth;
video.height = video.videoHeight; video.height = video.videoHeight;
runtime.planeMaterial.image = runtime.canvas; if (runtime.planeSource?.video !== video)
runtime.planeMaterial.image = video; setPlaneSource(runtime, { video });
}; };
video.addEventListener('loadedmetadata', bindVideoTexture); video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture); video.addEventListener('resize', bindVideoTexture);
@@ -265,7 +284,7 @@ export function createProjection({
runtime.imageLoading = false; runtime.imageLoading = false;
runtime.imageReady = false; runtime.imageReady = false;
}; };
runtime.planeMaterial.image = runtime.canvas; setPlaneSource(runtime, { canvas: runtime.canvas });
parts.frames.refreshProjectionImage(record, true); parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners(); parts.presentation.notifyListeners();
}, },
@@ -288,9 +307,8 @@ export function createProjection({
} }
// Monitor plane = the frustum's far cap: video feeds bind the video element // Monitor plane = the frustum's far cap: video feeds bind the video element
// directly (Cesium updates video-backed entity materials per frame); image // directly (the renderer reads it every frame); image feeds start on the
// feeds start on the placeholder canvas and switch to double-buffer swaps // placeholder canvas and switch to double-buffer swaps at <=1Hz.
// at <=1Hz.
const geometry = const geometry =
record.frustumGeometry || record.frustumGeometry ||
parts.geometry.computeFrustumGeometry( parts.geometry.computeFrustumGeometry(
@@ -300,11 +318,6 @@ export function createProjection({
); );
const positions = const positions =
record.frustumPositions || parts.rendering.frustumCartesians(geometry); record.frustumPositions || parts.rendering.frustumCartesians(geometry);
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
image: canvas,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
createProjectionPlane(record, runtime, geometry, positions); createProjectionPlane(record, runtime, geometry, positions);
return runtime; return runtime;
@@ -349,15 +362,15 @@ export function createProjection({
runtime.video.removeAttribute('src'); runtime.video.removeAttribute('src');
runtime.video.load(); runtime.video.load();
} }
if (runtime.planeEntity && layerState._viewer) { if (runtime.plane) {
layerState._viewer.entities.remove(runtime.planeEntity); parts.drawSets.removePlane(runtime.plane);
runtime.planeEntity = null; runtime.plane = null;
} }
if (layerState._projectionOverlayOwnerId === runtime.cameraId) if (layerState._projectionOverlayOwnerId === runtime.cameraId)
clearProjectionOverlay(); clearProjectionOverlay();
runtime.overlayEntry = null; runtime.overlayEntry = null;
runtime.labelPosition = null; runtime.labelPosition = null;
runtime.planeMaterial = null; runtime.planeSource = null;
} }
function startProjectionLoop() { function startProjectionLoop() {
@@ -439,7 +452,8 @@ export function createProjection({
updatePlanePlacement, updatePlanePlacement,
clearProjectionOverlay, clearProjectionOverlay,
setPlaneVisible, setPlaneVisible,
plainPlaneMaterial, setPlaneSource,
plainPlaneSource,
createProjectionPlane, createProjectionPlane,
createProjectionRuntime, createProjectionRuntime,
ensureProjectionRuntime, ensureProjectionRuntime,
File diff suppressed because it is too large. Load diff
+292 -99
View File
@@ -2,7 +2,7 @@
// Icon colors under focus de-emphasis (#1200): the focus pass fades each icon // 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 // 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. // stays violet while it dims instead of falling back to the idle cyan.
// Teardown takes the icons out of the scene that holds them. // Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test'; import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createRendering } from './rendering.js'; import { createRendering } from './rendering.js';
@@ -13,85 +13,103 @@ import {
} from './policy.js'; } from './policy.js';
import { isVideoFeedType } from '../../sources/cctvTypes.js'; import { isVideoFeedType } from '../../sources/cctvTypes.js';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createIconSet } from '../../data/iconSet.js'; import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
const FOCUS_FACTOR = 0.5; const FOCUS_FACTOR = 0.5;
function assertKeepsColor(icons, id, base, label) { function assertKeepsColor(icons, id, base, label) {
const row = icons.row(id); assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`);
const actual = icons.color(row); assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`);
assert.deepEqual(
[actual.red, actual.green, actual.blue, actual.alpha].map(
Cesium.Color.floatToByte,
),
base.map(Cesium.Color.floatToByte),
`${label}: base color kept`,
);
assert.equal(icons.focus(row), FOCUS_FACTOR, `${label}: focus`);
} }
test('focus de-emphasis fades each icon from its own color', () => { test('focus de-emphasis fades each icon from its own color', () => {
const record = (id, feedType) => ({ const record = (id, feedType) => ({
camera: { id, feedType }, camera: { id, feedType },
// No position, so the pass skips screen projection; the focus stub below position: { x: 6378137, y: 0, z: 0 },
// decides the factor on its own.
}); });
const idleVideo = record('idle-hls', 'hls'); const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image'); const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls'); 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 = { const state = {
_enabled: true, _enabled: true,
_viewer: { scene: {}, camera: {} }, _viewer: viewer,
_records: [idleVideo, idleStill, activeVideo], _records: [idleVideo, idleStill, activeVideo],
_activeCameraId: activeVideo.camera.id, _activeCameraId: activeVideo.camera.id,
_activeFocusStyleCount: 0, _activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity, _lastFocusStyleAt: -Infinity,
_icons: createIconSet(),
}; };
const distances = [];
const focus = { const focus = {
focusNowMs: (nowMs) => nowMs, focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => ({}), getFocusTarget: () => ({}),
focusPassIsNeeded: () => true, focusPassIsNeeded: () => true,
advanceSpriteFocus: () => ({ advanceSpriteFocus: (meta, input) => {
factor: FOCUS_FACTOR, distances.push(input.cameraDistance);
active: true, return { factor: FOCUS_FACTOR, active: true, transitioning: false };
transitioning: false, },
}),
focusAlphaNeedsWrite: () => true, focusAlphaNeedsWrite: () => true,
}; };
const { addCameraIcon, refreshCctvFocusStyles } = createRendering({ const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
state, createRendering({
services: { focus }, state,
parts: { model: { isVideoFeedType } }, services: { focus },
source: {}, parts: { model: { isVideoFeedType } },
}); source: {},
for (const r of state._records) addCameraIcon(r); });
try {
const setId = createCameraIcons(viewer);
for (const r of state._records) addCameraIcon(r);
refreshCctvFocusStyles(1000); refreshCctvFocusStyles(1000);
const icons = state._icons; const icons = state._icons;
assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video'); assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video');
assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still'); assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still');
assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video'); assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video');
assert.equal(state._activeFocusStyleCount, 3); 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);
} finally {
unbind();
}
}); });
test('icons leave the scene they were added to, whichever viewer tears down', () => { test('the icons go with the viewer that drew them, whichever tears down', () => {
const viewer = () => { const first = {};
const held = new Set(); const second = {};
return { const one = bindFakeDraw(first);
held, const two = bindFakeDraw(second);
scene: {
requestRender() {},
primitives: {
add: (p) => held.add(p),
remove: (p) => held.delete(p),
},
},
};
};
const first = viewer();
const second = viewer();
const state = { _viewer: first }; const state = { _viewer: first };
const { createCameraIcons, destroyCameraIcons } = createRendering({ const { createCameraIcons, destroyCameraIcons } = createRendering({
state, state,
@@ -99,53 +117,62 @@ test('icons leave the scene they were added to, whichever viewer tears down', ()
parts: {}, parts: {},
source: {}, 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);
const old = createCameraIcons(first); destroyCameraIcons();
state._viewer = second; assert.equal(two.draw.sets.get(current).disposed, true);
const current = createCameraIcons(second); assert.equal(state._icons, null);
assert.equal(first.held.has(old), false, 'a re-init takes out the old icons'); } finally {
assert.equal(old.isDestroyed(), true); one.unbind();
two.unbind();
destroyCameraIcons(); }
assert.equal(second.held.has(current), false);
assert.equal(current.isDestroyed(), true);
assert.equal(state._icons, null);
}); });
test('the obstruction probe sees through the layer and needs a ray pick', () => { test('the obstruction probe casts one ray through the query port', async () => {
const coverage = [{ id: 'cov' }];
const plane = { id: 'plane' };
const calls = []; const calls = [];
const state = { const viewer = {};
_viewer: { const unbind = bindRenderer(viewer, {
scene: { query: {
pickFromRay(ray, exclude) { rayCast: async (ray, options) => {
calls.push({ ray, exclude }); calls.push({ ray, options });
return { position: { x: 1, y: 2, z: 3 } }; return { x: 1, y: 2, z: 3 };
},
}, },
}, },
_coverageEntities: coverage, });
_projectionEntities: [{ planeEntity: plane }, null, {}], const state = { _viewer: viewer };
};
const rendering = createRendering({ const rendering = createRendering({
state, state,
services: { focus: {} }, services: { focus: {} },
parts: {}, parts: {},
}); });
assert.equal(rendering.canPickFromRay(), true); try {
const hit = rendering.obstructionHit( assert.equal(rendering.canPickFromRay(), true);
{ x: 0, y: 0, z: 0 }, const origin = { x: 0, y: 0, z: 0 };
{ x: 1, y: 0, z: 0 }, const direction = { x: 1, y: 0, z: 0 };
); assert.deepEqual(await rendering.obstructionHit(origin, direction), {
assert.deepEqual(hit.position, { x: 1, y: 2, z: 3 }); x: 1,
assert.deepEqual(calls[0].exclude, [...coverage, plane]); y: 2,
assert.ok(calls[0].ray instanceof Cesium.Ray); z: 3,
state._viewer = { scene: {} }; });
// The layer's own sets are not ground: the cast sees through them
// without naming them.
assert.deepEqual(calls, [
{ ray: { origin, direction }, options: { against: 'surface' } },
]);
} finally {
unbind();
}
state._viewer = {};
assert.equal(rendering.canPickFromRay(), false); assert.equal(rendering.canPickFromRay(), false);
assert.equal( assert.equal(
rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }), await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
undefined, null,
); );
}); });
@@ -153,22 +180,188 @@ test('cards go only where the horizon lets the camera see', () => {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000); const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000);
const front = Cesium.Cartesian3.fromDegrees(0, 0); const front = Cesium.Cartesian3.fromDegrees(0, 0);
const back = Cesium.Cartesian3.fromDegrees(180, 0); const back = Cesium.Cartesian3.fromDegrees(180, 0);
const state = { const viewer = {};
_viewer: { const camera = fakeCameraPort({
camera: { positionWC: eye }, pose: { position: { x: eye.x, y: eye.y, z: eye.z } },
scene: { });
canvas: { clientWidth: 800, clientHeight: 0, height: 600 }, const unbind = bindRenderer(viewer, {
cartesianToCanvasCoordinates: () => ({ x: 10, y: 20 }), 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,
}, },
}; });
const view = createRendering({ try {
state, 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: {} }, services: { focus: {} },
parts: {}, parts: {},
}).cardView(); });
assert.equal(view.width, 800); assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles');
assert.equal(view.height, 600); });
assert.deepEqual(view.screenOf(front), { x: 10, y: 20 });
assert.equal(view.screenOf(back), null); 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 },
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 } },
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();
}
}); });
+7 -6
View File
@@ -103,12 +103,13 @@ export function createSelection({
layerState._geoQueue.splice(queueIdx, 1); layerState._geoQueue.splice(queueIdx, 1);
layerState._geoQueue.unshift(record); layerState._geoQueue.unshift(record);
} }
// §9.1: one obstruction probe per activation, BEFORE the geometry pass so // §9.1: one obstruction probe per activation, cast before the geometry
// the range clamp lands in the same rewrite. A FIRST-EVER activation (no // pass; its range clamp lands a microtask later, before the next frame,
// real ground sample yet) probes from the catalog-prior altitude — if that // rewriting the geometry and asking again for the footprint ground. A
// prior is off, the clamp is measured from a shifted origin, but a // FIRST-EVER activation (no real ground sample yet) probes from the
// re-activation after the one-shot snap lands re-probes from real ground, // catalog-prior altitude — if that prior is off, the clamp is measured
// so it self-corrects. // 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); parts.geometry.runActivationObstructionProbe(record);
// Coverage is activation-lazy even while the mode is OFF: the active // Coverage is activation-lazy even while the mode is OFF: the active
// camera's projection representation must be ready without materializing // camera's projection representation must be ready without materializing
+5 -4
View File
@@ -1,6 +1,7 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { createCctvSource, createCctvLayer } from './index.js'; import { createCctvSource, createCctvLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const camera = { const camera = {
id: 'pack/camera ?x', id: 'pack/camera ?x',
@@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
setOverlayEntries: noop, setOverlayEntries: noop,
setOverlaySourceVisible: noop, setOverlaySourceVisible: noop,
}, },
sprites: { registerSpriteCollection: noop }, sprites: { registerSpriteSet: noop },
activation: {}, activation: {},
locations: {}, locations: {},
picking: { unregisterPickOwner: noop }, 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 a = createCctvLayer({ services, source });
const b = createCctvLayer({ services, source }); const b = createCctvLayer({ services, source });
assert.equal(listeners.size, 0); assert.equal(listeners.size, 0);
const viewer = { const viewer = {};
scene: { primitives: { add: (value) => value, remove: () => true } }, const { unbind } = bindFakeDraw(viewer);
}; t.after(unbind);
const initializing = a.init(viewer); const initializing = a.init(viewer);
assert.equal(listeners.size, 1); assert.equal(listeners.size, 1);
assert.equal(signal.aborted, false); assert.equal(signal.aborted, false);
+2 -15
View File
@@ -13,9 +13,8 @@ export function createState({ services }) {
layerState._viewer = null; layerState._viewer = null;
/** The catalog's icon set and the primitive that draws it. */ /** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null; layerState._icons = null;
layerState._iconPrimitive = null;
layerState._records = []; layerState._records = [];
@@ -74,14 +73,9 @@ export function createState({ services }) {
layerState._activeFocusStyleCount = 0; layerState._activeFocusStyleCount = 0;
// Screen-point scratches: the projections that fill them write only x and y. // The view pass's screen-point scratch: its projection writes only x and y.
layerState._scratchFocusScreen = { x: 0, y: 0 };
layerState._scratchViewScreen = { x: 0, y: 0 }; layerState._scratchViewScreen = { x: 0, y: 0 };
/** The view pass's view-projection matrix, column-major. */
layerState._scratchViewProjection = new Float64Array(16);
// Counts view passes; a record shown by the latest pass carries its number. // Counts view passes; a record shown by the latest pass carries its number.
layerState._viewPassId = 0; layerState._viewPassId = 0;
@@ -166,13 +160,6 @@ export function createState({ services }) {
layerState._lastTransientNotifyAt = 0; 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 // Task 5: last surface regime the record geometry was recomputed for. The
// map-stack change listener compares the CURRENT regime (derived live from // map-stack change listener compares the CURRENT regime (derived live from
// whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe' // whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe'
+43 -8
View File
@@ -1,4 +1,13 @@
import { createIconSet } from '../../data/iconSet.js'; 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 }) { export function createTesting({ state: layerState, services, parts, source }) {
/** Test seam: republishes host entries through the real push path, so tests /** 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. * 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. * @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime. * @returns {Object} Projection runtime.
*/ */
@@ -39,11 +48,11 @@ export function createTesting({ state: layerState, services, parts, source }) {
record.frustumPositions = positions; record.frustumPositions = positions;
const runtime = { const runtime = {
cameraId: String(record.camera.id), cameraId: String(record.camera.id),
planeEntity: null, plane: null,
// createProjectionPlane gives it its label position. // createProjectionPlane gives it its label position.
labelPosition: null, labelPosition: null,
overlayEntry: null, overlayEntry: null,
planeMaterial: parts.projection.plainPlaneMaterial(), planeSource: parts.projection.plainPlaneSource(),
}; };
parts.projection.createProjectionPlane( parts.projection.createProjectionPlane(
record, record,
@@ -102,7 +111,6 @@ export function createTesting({ state: layerState, services, parts, source }) {
); );
layerState._coverageEntities = []; layerState._coverageEntities = [];
layerState._projectionEntities = []; layerState._projectionEntities = [];
layerState._iconPrimitive = null;
layerState._activeCameraId = activeCameraId; layerState._activeCameraId = activeCameraId;
layerState._autoHopSuspended = false; layerState._autoHopSuspended = false;
layerState._enabled = !!enabled; layerState._enabled = !!enabled;
@@ -116,13 +124,39 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._cameraIndexCache = null; layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set(); layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null; layerState._neighborCountCache = null;
// A real set (no primitive): every record gets its row as init adds it. // A real book (over a set that draws nothing): every record gets its
layerState._icons = createIconSet(); // icon as init adds it.
layerState._icons = createIconBook(testIconSet());
for (const record of layerState._records) for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record); if (record?.camera?.id) parts.rendering.addCameraIcon(record);
} }
/** The layer's icon set, for tests that read what the rows draw. */ /**
* 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() { function _cctvIconsForTest() {
return layerState._icons; return layerState._icons;
@@ -135,5 +169,6 @@ export function createTesting({ state: layerState, services, parts, source }) {
_extractPickedCameraIdForTest, _extractPickedCameraIdForTest,
_setCctvCoverageStateForTest, _setCctvCoverageStateForTest,
_cctvIconsForTest, _cctvIconsForTest,
_cctvDrawnForTest,
}; };
} }
+35 -3
View File
@@ -37,6 +37,8 @@ import { provideUnboundDraw } from '../rendererOf.js';
import { listenerList, toCartesian, uncaught } from './common.js'; import { listenerList, toCartesian, uncaught } from './common.js';
import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js'; import { createGpuIcons, GPU_ICON_CAPABILITIES } from './gpuIcons.js';
import { createModelSets } from './drawModels.js'; import { createModelSets } from './drawModels.js';
import { createMeshSets } from './drawMeshes.js';
import { createQuadSets } from './drawQuads.js';
/** The contract's colour as Cesium's. */ /** The contract's colour as Cesium's. */
export function toColor(color, alpha = 1) { export function toColor(color, alpha = 1) {
@@ -395,7 +397,9 @@ export function createCesiumDraw({
if ( if (
patchLines(record, list) || patchLines(record, list) ||
patchShapes(record, list) || patchShapes(record, list) ||
(kind === 'models' && modelSets.upsert(record, list)) (kind === 'models' && modelSets.upsert(record, list)) ||
(kind === 'quads' && quadSets.upsert(record, list)) ||
(kind === 'meshes' && meshSets.upsert(record, list))
) { ) {
for (const item of list) items.set(item.id, item); for (const item of list) items.set(item.id, item);
if (kind === 'lines') noteFlows(record); if (kind === 'lines') noteFlows(record);
@@ -449,7 +453,10 @@ export function createCesiumDraw({
if ( if (
(kind !== 'models' && spec.clampTo !== clampTo) || (kind !== 'models' && spec.clampTo !== clampTo) ||
((kind === 'points' || kind === 'icons') && spec.blend !== blend) || ((kind === 'points' || kind === 'icons') && spec.blend !== blend) ||
((kind === 'shapes' || kind === 'lines') && ((kind === 'shapes' ||
kind === 'lines' ||
kind === 'quads' ||
kind === 'meshes') &&
(spec.pickable !== false) !== pickable) (spec.pickable !== false) !== pickable)
) )
rebuild(); rebuild();
@@ -2994,6 +3001,24 @@ export function createCesiumDraw({
requestRender, requestRender,
}); });
const buildModels = (record) => modelSets.build(record); const buildModels = (record) => modelSets.build(record);
const lineWidth = (px) =>
typeof scene.clampLineWidth === 'function'
? scene.clampLineWidth(px)
: Math.min(px, scene.maximumAliasedLineWidth ?? 1);
const quadSets = createQuadSets({
toColor,
toImage,
pickId,
replaceHost,
lineWidth,
requestRender,
});
const meshSets = createMeshSets({
toColor,
pickId,
replaceHost,
requestRender,
});
/** The 3D tilesets in the scene, shown or not. */ /** The 3D tilesets in the scene, shown or not. */
function tilesets() { function tilesets() {
@@ -3032,6 +3057,10 @@ export function createCesiumDraw({
lines: (spec) => makeSet('lines', { ...spec }, buildLines), lines: (spec) => makeSet('lines', { ...spec }, buildLines),
shapes: (spec) => makeSet('shapes', { ...spec }, buildShapes), shapes: (spec) => makeSet('shapes', { ...spec }, buildShapes),
models: (spec) => makeSet('models', { ...spec }, buildModels), models: (spec) => makeSet('models', { ...spec }, buildModels),
quads: (spec) =>
makeSet('quads', { ...spec }, (record) => quadSets.build(record)),
meshes: (spec) =>
makeSet('meshes', { ...spec }, (record) => meshSets.build(record)),
clampState, clampState,
on(event, cb) { on(event, cb) {
if (event !== 'clampState') return () => {}; if (event !== 'clampState') return () => {};
@@ -3075,6 +3104,7 @@ export function createCesiumDraw({
cullHorizon(); cullHorizon();
runFlows(); runFlows();
modelSets.beforeRender(sets.values()); modelSets.beforeRender(sets.values());
quadSets.beforeRender(sets.values());
}, },
/** Each frame, after it drew: clamp state, and ground swaps. */ /** Each frame, after it drew: clamp state, and ground swaps. */
afterRender() { afterRender() {
@@ -3091,9 +3121,11 @@ export function createCesiumDraw({
} }
// Rows moving on a live clock, and flowing lines, draw on in the // Rows moving on a live clock, and flowing lines, draw on in the
// frames that follow. // frames that follow.
const playing = quadSets.afterRender(sets.values());
if ( if (
[...sets.values()].some((record) => record.gpu?.animating()) || [...sets.values()].some((record) => record.gpu?.animating()) ||
flowing() flowing() ||
playing
) )
requestRender(); requestRender();
}, },
+265
View File
@@ -5163,3 +5163,268 @@ test('a raised polygon outlines its holes as well as its outer ring', () =>
} }
set.dispose(); set.dispose();
})); }));
test('quads draw a posed plane and its outline, changed in place', () =>
withImageClasses(() => {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.quads({ id: 'monitors' });
const canvas = { width: 4, height: 4 };
const other = { width: 4, height: 4 };
const center = { x: 6378137, y: 10, z: 20 };
const quad = (extra = {}) => ({
id: 'q',
center,
orientation: { x: 0, y: 0, z: 0, w: 1 },
size: [40, 20],
source: { canvas },
alpha: 0.95,
outline: { color: [0.4, 0.9, 1, 0.55], widthPx: 1 },
meta: { camera: 'c1' },
...extra,
});
set.set([quad()]);
const host = scene.added[0];
assert.equal(host.length, 2, 'the plane and its outline');
const [fill, outline] = [host.get(0), host.get(1)];
assert.ok(fill.geometryInstances.geometry instanceof Cesium.PlaneGeometry);
assert.ok(
outline.geometryInstances.geometry instanceof Cesium.PlaneOutlineGeometry,
);
assert.deepEqual(fill.geometryInstances.id, {
set: 'monitors',
id: 'q',
meta: { camera: 'c1' },
lodGroup: undefined,
});
// Scaled to its size about its centre, as a plane entity's matrix is.
const scale = Cesium.Matrix4.getScale(
fill.modelMatrix,
new Cesium.Cartesian3(),
);
assert.deepEqual([scale.x, scale.y, scale.z], [40, 20, 1]);
const at = Cesium.Matrix4.getTranslation(
fill.modelMatrix,
new Cesium.Cartesian3(),
);
assert.deepEqual({ x: at.x, y: at.y, z: at.z }, center);
const material = fill.appearance.material;
assert.equal(material.type, 'Image');
assert.equal(material.uniforms.image, canvas);
assert.ok(Math.abs(material.uniforms.color.alpha - 0.95) < 1e-12);
assert.equal(fill.appearance.translucent, true);
// Moved, resized, faded, hidden and given another canvas: the same plane.
set.upsert([
quad({
center: { x: 6378137, y: 30, z: 20 },
size: [80, 45],
alpha: 0.5,
show: false,
source: { canvas: other },
meta: { camera: 'c2' },
}),
]);
assert.equal(host.get(0), fill, 'changed where it is');
Cesium.Matrix4.getScale(fill.modelMatrix, scale);
assert.deepEqual([scale.x, scale.y], [80, 45]);
assert.ok(
Cesium.Matrix4.equals(fill.modelMatrix, outline.modelMatrix),
'the outline follows',
);
assert.equal(fill.show, false);
assert.equal(outline.show, false);
assert.equal(material.uniforms.image, other, 'the new canvas is read');
assert.ok(Math.abs(material.uniforms.color.alpha - 0.5) < 1e-12);
assert.deepEqual(fill.geometryInstances.id.meta, { camera: 'c2' });
// Unpickable, or without an outline: built anew.
set.upsert([quad({ outline: null, pickable: false })]);
assert.equal(host.length, 1, 'no outline');
assert.notEqual(host.get(0), fill);
assert.equal(host.get(0).allowPicking, false);
set.remove(['q']);
assert.equal(host.length, 0);
set.dispose();
assert.equal(scene.added.length, 0);
}));
test('a video quad keeps frames coming while it plays, read anew at a new size', () =>
withImageClasses(() => {
const realVideo = globalThis.HTMLVideoElement;
globalThis.HTMLVideoElement = class extends EventTarget {};
try {
const scene = fakeScene();
let renders = 0;
scene.requestRender = () => (renders += 1);
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.quads({ id: 'feeds' });
const video = Object.assign(new globalThis.HTMLVideoElement(), {
readyState: 4,
paused: false,
ended: false,
videoWidth: 640,
videoHeight: 360,
});
set.set([
{
id: 'v',
center: { x: 6378137, y: 0, z: 0 },
orientation: { x: 0, y: 0, z: 0, w: 1 },
size: [16, 9],
source: { video },
alpha: 0.95,
},
]);
const fill = scene.added[0].get(0);
const first = fill.appearance.material;
assert.equal(first.uniforms.image, video);
part.beforeRender();
renders = 0;
part.afterRender();
assert.ok(renders > 0, 'a playing video asks for the next frame');
// Past the frames a new image needs, a paused video asks for none.
part.afterRender();
part.afterRender();
video.paused = true;
renders = 0;
part.afterRender();
assert.equal(renders, 0, 'a paused video draws no more frames');
// A new size: a new material reads it, the old one freed once drawn.
video.videoWidth = 1280;
video.videoHeight = 720;
part.beforeRender();
assert.notEqual(fill.appearance.material, first);
assert.equal(fill.appearance.material.uniforms.image, video);
assert.equal(first.isDestroyed(), false, 'kept until the frame drew');
part.afterRender();
assert.equal(first.isDestroyed(), true);
// Paused, it draws again as it plays, with no frame asked for.
renders = 0;
video.dispatchEvent(new Event('playing'));
assert.equal(renders, 1, 'playing again asks for a frame');
// From the video to a canvas: a material of its own.
const sized = fill.appearance.material;
const canvas = { width: 4, height: 4 };
const quad = {
id: 'v',
center: { x: 6378137, y: 0, z: 0 },
orientation: { x: 0, y: 0, z: 0, w: 1 },
size: [16, 9],
source: { canvas },
alpha: 0.95,
};
set.upsert([{ ...quad, show: false }]);
assert.notEqual(fill.appearance.material, sized);
assert.equal(fill.appearance.material.uniforms.image, canvas);
renders = 0;
video.dispatchEvent(new Event('playing'));
assert.equal(renders, 0, 'the video it left is no longer heard');
// Hidden, the frames its image needs wait until it shows.
part.afterRender();
part.afterRender();
part.afterRender();
set.upsert([quad]);
renders = 0;
part.afterRender();
assert.ok(renders > 0, 'shown, it asks for the frames its image needs');
set.dispose();
} finally {
globalThis.HTMLVideoElement = realVideo;
}
}));
test('meshes draw their triangles in the frame at their origin', () =>
withImageClasses(() => {
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const set = part.port.meshes({ id: 'volumes', pickable: false });
const positions = new Float32Array([0, 0, 0, 10, 0, 0, 0, 10, 0, 0, 0, 10]);
const indices = new Uint16Array([0, 1, 2, 0, 1, 3]);
const origin = Cesium.Cartesian3.fromDegrees(-97.74, 30.27, 200);
const mesh = (extra = {}) => ({
id: 'm',
origin: { x: origin.x, y: origin.y, z: origin.z },
positions,
indices,
color: [0.2, 0.8, 1, 0.2],
flat: true,
...extra,
});
set.set([mesh()]);
const host = scene.added[0];
assert.equal(host.length, 1);
const primitive = host.get(0);
const geometry = primitive.geometryInstances.geometry;
assert.equal(
geometry.attributes.position.componentDatatype,
Cesium.ComponentDatatype.DOUBLE,
);
// In the Earth-fixed frame: the east-north-up offsets about the origin.
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(origin);
const values = geometry.attributes.position.values;
for (let i = 0; i < positions.length; i += 3) {
const want = Cesium.Matrix4.multiplyByPoint(
frame,
new Cesium.Cartesian3(positions[i], positions[i + 1], positions[i + 2]),
new Cesium.Cartesian3(),
);
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
new Cesium.Cartesian3(values[i], values[i + 1], values[i + 2]),
want,
0,
1e-6,
),
`vertex ${i / 3} in place`,
);
}
assert.equal(geometry.indices, indices);
assert.equal(primitive.allowPicking, false, 'an unpickable set');
assert.equal(primitive.appearance.flat, true);
assert.equal(primitive.appearance.translucent, true);
assert.equal(
primitive.appearance.renderState.cull.enabled,
false,
'both faces',
);
// Hidden: the same primitive.
set.upsert([mesh({ show: false })]);
assert.equal(host.get(0), primitive);
assert.equal(primitive.show, false);
// Moved: built anew where it now is.
const moved = Cesium.Cartesian3.fromDegrees(-97.73, 30.27, 200);
set.upsert([mesh({ origin: { x: moved.x, y: moved.y, z: moved.z } })]);
assert.equal(host.length, 1);
const rebuilt = host.get(0);
assert.notEqual(rebuilt, primitive);
const first = rebuilt.geometryInstances.geometry.attributes.position.values;
assert.ok(
Cesium.Cartesian3.equalsEpsilon(
new Cesium.Cartesian3(first[0], first[1], first[2]),
moved,
0,
1e-6,
),
'its origin vertex is the new origin',
);
// A new colour builds it anew.
set.upsert([mesh({ color: '#ff0000' })]);
assert.equal(host.length, 1);
assert.notEqual(host.get(0), rebuilt);
// Lit meshes are closed: their back faces culled.
set.upsert([mesh({ flat: false })]);
assert.equal(host.get(0).appearance.closed, true);
set.clear();
assert.equal(host.length, 0);
set.dispose();
}));
+182
View File
@@ -0,0 +1,182 @@
/**
* @module render/cesium/drawMeshes
* @description The Cesium draw port's `meshes` sets: each item one
* primitive of its triangles, in the east-north-up frame at its `origin`,
* in its colour. `flat` draws it unlit with both faces (a translucent
* volume seen from inside or behind); otherwise it is lit by its own
* normals and its back faces are culled. Its vertices are placed in the
* Earth-fixed frame when it is built (a primitive whose own vertices sit at
* its frame's origin cannot be projected for the 2D views Cesium prepares),
* so any change but `show` builds it anew, at once, and it draws in the
* frame it replaces the old one. `positions` and `indices` are compared by
* identity: give new arrays to change a shape.
*/
import * as Cesium from 'cesium';
/** A colour as a key: a CSS string as it is, an RGBA array joined. */
const colorKey = (color) =>
typeof color === 'string' ? color : Array.from(color).join(',');
/**
* The meshes part of a Cesium draw port.
* @param {{toColor: Function, pickId: Function, replaceHost: Function,
* requestRender: () => void}} options From the draw port.
*/
export function createMeshSets({
toColor,
pickId,
replaceHost,
requestRender,
}) {
/** The set's host, made once: its meshes are changed where they are. */
function hostOf(record) {
if (record.host && !record.host.isDestroyed?.()) return record.host;
const host = new Cesium.PrimitiveCollection();
record.meshes = new Map();
replaceHost(record, host);
return host;
}
function notePickIds(record) {
record.pickIds = [];
for (const entry of record.meshes.values())
record.pickIds.push(entry.pickId);
}
const pickableOf = (record, item) =>
record.spec.pickable !== false && item.pickable !== false;
const scratchFrame = new Cesium.Matrix4();
const scratchPoint = new Cesium.Cartesian3();
/** The item's east-north-up positions, in the Earth-fixed frame. */
function fixedPositions(item) {
const { origin, positions } = item;
const frame = Cesium.Transforms.eastNorthUpToFixedFrame(
new Cesium.Cartesian3(origin.x, origin.y, origin.z),
Cesium.Ellipsoid.WGS84,
scratchFrame,
);
const out = new Float64Array(positions.length);
for (let i = 0; i + 2 < positions.length; i += 3) {
scratchPoint.x = positions[i];
scratchPoint.y = positions[i + 1];
scratchPoint.z = positions[i + 2];
Cesium.Matrix4.multiplyByPoint(frame, scratchPoint, scratchPoint);
out[i] = scratchPoint.x;
out[i + 1] = scratchPoint.y;
out[i + 2] = scratchPoint.z;
}
return out;
}
/** What an entry's primitive is built from: equal keys need no rebuild. */
const shapeKey = (record, item) => ({
origin: `${item.origin.x},${item.origin.y},${item.origin.z}`,
positions: item.positions,
indices: item.indices,
color: colorKey(item.color),
flat: item.flat === true,
pickable: pickableOf(record, item),
});
const sameShape = (a, b) =>
a.origin === b.origin &&
a.positions === b.positions &&
a.indices === b.indices &&
a.color === b.color &&
a.flat === b.flat &&
a.pickable === b.pickable;
function primitiveOf(record, item, entry) {
const values = fixedPositions(item);
const geometry = new Cesium.Geometry({
attributes: {
position: new Cesium.GeometryAttribute({
componentDatatype: Cesium.ComponentDatatype.DOUBLE,
componentsPerAttribute: 3,
values,
}),
},
indices: item.indices,
primitiveType: Cesium.PrimitiveType.TRIANGLES,
boundingSphere: Cesium.BoundingSphere.fromVertices(Array.from(values)),
});
const flat = item.flat === true;
if (!flat) Cesium.GeometryPipeline.computeNormal(geometry);
const color = toColor(item.color);
return new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry,
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
id: entry.pickId,
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat,
translucent: color.alpha < 1,
// Flat: both faces. Lit: a closed shape, its back faces culled.
closed: !flat,
...(flat ? { renderState: { cull: { enabled: false } } } : {}),
}),
allowPicking: pickableOf(record, item),
asynchronous: false,
show: item.show !== false,
});
}
function put(record, item) {
const host = record.host;
let entry = record.meshes.get(item.id);
if (!entry) {
entry = {
item,
pickId: pickId(record, item),
key: null,
primitive: null,
};
record.meshes.set(item.id, entry);
}
entry.item = item;
entry.pickId.meta = item.meta;
const key = shapeKey(record, item);
if (entry.primitive && entry.key && sameShape(entry.key, key)) {
entry.primitive.show = item.show !== false;
return;
}
const next = host.add(primitiveOf(record, item, entry));
if (entry.primitive) host.remove(entry.primitive);
entry.primitive = next;
entry.key = key;
}
function drop(record, id) {
const entry = record.meshes.get(id);
if (!entry) return;
record.meshes.delete(id);
const host = record.host;
if (entry.primitive && host && !host.isDestroyed())
host.remove(entry.primitive);
}
/** Add or change items, by id; true once handled (always, for meshes). */
function upsert(record, list) {
hostOf(record);
for (const item of list) put(record, item);
notePickIds(record);
requestRender();
return true;
}
/** The set's items as they are now: meshes gone dropped, the rest kept. */
function build(record) {
hostOf(record);
for (const id of [...record.meshes.keys()])
if (!record.items.has(id)) drop(record, id);
for (const item of record.items.values()) put(record, item);
notePickIds(record);
}
return { build, upsert };
}
+350
View File
@@ -0,0 +1,350 @@
/**
* @module render/cesium/drawQuads
* @description The Cesium draw port's `quads` sets: each item a unit plane
* primitive scaled to its `size`, posed by its `center` and `orientation`
* (the plane lies in the orientation's local x–y plane, width along x,
* height along y, its face toward local +z), textured with its image,
* video or canvas, and its outline beside it, as a Cesium plane entity
* draws them. An update moves, turns, resizes, shows or retextures the
* plane where it is; only a change of pickability or of outline rebuilds
* it.
*
* Choices the contract leaves open, taken conservatively:
* - `orientation` turns the plane in the Earth-fixed frame.
* - A canvas is read when an item first names it, as a Cesium material
* reads one: to show new pixels, name another canvas (two canvases in
* turn, say). The material takes a new image on the frame after it is
* named, so the two drawn frames after a change are asked for (asked
* for again once a hidden quad shows).
* - A video is read every drawn frame, and keeps frames coming while it
* plays and its quad shows (starting again as it plays, seeks or has
* data again); a video whose size changes is read at its new size. A
* change between a video and another source makes a new material, so
* neither reads into the other's texture.
* - Quads are lit by the scene's light and always draw translucent, their
* image's own alpha read, as a plane entity's transparent image material
* does.
*/
import * as Cesium from 'cesium';
import { toCartesian } from './common.js';
const scratchQuaternion = new Cesium.Quaternion();
const scratchScale = new Cesium.Cartesian3();
/** What a quad's material shows: an element, or an image's URL. */
function sourceOf(source, toImage) {
if (source?.video) return source.video;
if (source?.canvas) return source.canvas;
if (source && 'image' in source) return toImage(source.image);
throw new Error('a quad takes an image, a video or a canvas');
}
/** An outline as a key; '' for none. */
const outlineKey = (outline) =>
outline
? `${typeof outline.color === 'string' ? outline.color : outline.color.join(',')}|${outline.widthPx}`
: '';
/**
* The quads part of a Cesium draw port.
* @param {{toColor: Function, toImage: Function,
* pickId: Function, replaceHost: Function, lineWidth: (px: number) => number,
* requestRender: () => void}} options From the draw port.
*/
export function createQuadSets({
toColor,
toImage,
pickId,
replaceHost,
lineWidth,
requestRender,
}) {
/** Materials replaced this frame, destroyed once it has drawn. */
let retired = [];
/** Media events after which a video draws again, with no frame asked. */
const VIDEO_EVENTS = ['play', 'playing', 'canplay', 'loadeddata', 'seeked'];
/** Ask for frames on the entry's video's events, while it shows one. */
function watchVideo(entry) {
unwatchVideo(entry);
const video = entry.source;
if (!isVideo(video)) return;
const wake = () => requestRender();
for (const name of VIDEO_EVENTS) video.addEventListener?.(name, wake);
entry.unwatch = () => {
for (const name of VIDEO_EVENTS) video.removeEventListener?.(name, wake);
};
}
function unwatchVideo(entry) {
entry.unwatch?.();
entry.unwatch = null;
}
/** The set's host, made once: its quads are changed where they are. */
function hostOf(record) {
if (record.host && !record.host.isDestroyed?.()) return record.host;
const host = new Cesium.PrimitiveCollection();
const quads = new Map();
// Materials hold their textures, which primitives leave alone: the
// host destroys them as it goes.
const destroyHost = host.destroy.bind(host);
host.destroy = () => {
for (const entry of quads.values()) {
freeMaterial(entry.material);
unwatchVideo(entry);
}
quads.clear();
return destroyHost();
};
record.quads = quads;
replaceHost(record, host);
return host;
}
function freeMaterial(material) {
if (material && !material.isDestroyed()) material.destroy();
}
function imageMaterial(source, alpha) {
return Cesium.Material.fromType('Image', {
image: source,
color: Cesium.Color.WHITE.withAlpha(alpha),
});
}
/** Each live entry's pick id, for height queries to see through. */
function notePickIds(record) {
record.pickIds = [];
for (const entry of record.quads.values())
record.pickIds.push(entry.pickId);
}
function matrixOf(item, result) {
const q = item.orientation;
scratchQuaternion.x = q.x;
scratchQuaternion.y = q.y;
scratchQuaternion.z = q.z;
scratchQuaternion.w = q.w;
scratchScale.x = item.size[0];
scratchScale.y = item.size[1];
scratchScale.z = 1;
return Cesium.Matrix4.fromTranslationQuaternionRotationScale(
toCartesian(item.center),
scratchQuaternion,
scratchScale,
result,
);
}
const pickableOf = (record, item) =>
record.spec.pickable !== false && item.pickable !== false;
/** Build an entry's primitives anew (it is new, or picks or outline changed). */
function build(record, entry) {
const host = record.host;
const item = entry.item;
const allowPicking = pickableOf(record, item);
const modelMatrix = matrixOf(item, new Cesium.Matrix4());
entry.source = sourceOf(item.source, toImage);
entry.alpha = item.alpha ?? 1;
entry.material = imageMaterial(entry.source, entry.alpha);
entry.videoSize = null;
entry.fill = host.add(
new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PlaneGeometry({
vertexFormat:
Cesium.MaterialAppearance.MaterialSupport.TEXTURED.vertexFormat,
}),
id: entry.pickId,
}),
appearance: new Cesium.MaterialAppearance({
material: entry.material,
translucent: true,
closed: false,
}),
modelMatrix,
allowPicking,
asynchronous: false,
show: item.show !== false,
}),
);
entry.outline = null;
if (item.outline) {
const color = toColor(item.outline.color);
entry.outline = host.add(
new Cesium.Primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PlaneOutlineGeometry(),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(color),
},
id: entry.pickId,
}),
appearance: new Cesium.PerInstanceColorAppearance({
flat: true,
translucent: color.alpha < 1,
renderState: { lineWidth: lineWidth(item.outline.widthPx ?? 1) },
}),
modelMatrix: Cesium.Matrix4.clone(modelMatrix),
allowPicking,
asynchronous: false,
show: item.show !== false,
}),
);
}
entry.pickable = allowPicking;
entry.outlineKey = outlineKey(item.outline);
entry.uploadFrames = 2;
watchVideo(entry);
}
function drop(record, id) {
const entry = record.quads.get(id);
if (!entry) return;
record.quads.delete(id);
unbuild(record, entry);
}
function unbuild(record, entry) {
const host = record.host;
for (const primitive of [entry.fill, entry.outline])
if (primitive && host && !host.isDestroyed()) host.remove(primitive);
freeMaterial(entry.material);
unwatchVideo(entry);
entry.fill = entry.outline = entry.material = null;
}
/** A new material for an entry, the old one freed once the frame drew. */
function rebind(entry) {
const old = entry.material;
entry.material = imageMaterial(entry.source, entry.alpha);
entry.fill.appearance.material = entry.material;
entry.videoSize = null;
entry.uploadFrames = 2;
if (old) retired.push(old);
}
function put(record, item) {
let entry = record.quads.get(item.id);
if (!entry) {
entry = { item, pickId: pickId(record, item) };
record.quads.set(item.id, entry);
build(record, entry);
return;
}
entry.item = item;
// The pick id is the primitives' own object: changed where it is.
entry.pickId.meta = item.meta;
if (
entry.pickable !== pickableOf(record, item) ||
entry.outlineKey !== outlineKey(item.outline)
) {
unbuild(record, entry);
build(record, entry);
return;
}
const show = item.show !== false;
matrixOf(item, entry.fill.modelMatrix);
entry.fill.show = show;
if (entry.outline) {
Cesium.Matrix4.clone(entry.fill.modelMatrix, entry.outline.modelMatrix);
entry.outline.show = show;
}
const alpha = item.alpha ?? 1;
if (alpha !== entry.alpha) {
entry.alpha = alpha;
entry.material.uniforms.color = Cesium.Color.WHITE.withAlpha(alpha);
}
const source = sourceOf(item.source, toImage);
if (source !== entry.source) {
const video = isVideo(source) || isVideo(entry.source);
entry.source = source;
if (video) {
// To or from a video: a material of its own, so the video's frames
// are not copied into another source's texture, or the other way.
rebind(entry);
watchVideo(entry);
} else {
// Another canvas or URL: the material reads it anew.
entry.material.uniforms.image = source;
entry.uploadFrames = 2;
}
}
}
/** Add or change items, by id; true once handled (always, for quads). */
function upsert(record, list) {
hostOf(record);
for (const item of list) put(record, item);
notePickIds(record);
requestRender();
return true;
}
/** The set's items as they are now: quads gone dropped, the rest kept. */
function rebuild(record) {
hostOf(record);
for (const id of [...record.quads.keys()])
if (!record.items.has(id)) drop(record, id);
for (const item of record.items.values()) put(record, item);
notePickIds(record);
}
const isVideo = (source) =>
typeof globalThis.HTMLVideoElement === 'function' &&
source instanceof globalThis.HTMLVideoElement;
/**
* Each frame, before it draws: a video whose size changed since its
* texture was made is read at its new size.
*/
function beforeRender(sets) {
for (const record of sets) {
if (record.kind !== 'quads' || !record.quads) continue;
for (const entry of record.quads.values()) {
const video = entry.source;
if (!entry.fill || !isVideo(video) || video.readyState < 2) continue;
const size = `${video.videoWidth}x${video.videoHeight}`;
if (entry.videoSize === null) entry.videoSize = size;
else if (entry.videoSize !== size) rebind(entry);
}
}
}
/**
* After a frame drew: the materials it replaced go, and a playing video
* on a shown quad, or an image a material is still to take, asks for the
* next frame. True when one did.
*/
function afterRender(sets) {
for (const material of retired) freeMaterial(material);
retired = [];
let playing = false;
for (const record of sets) {
if (record.kind !== 'quads' || !record.quads) continue;
if (record.spec.show === false || record.host?.show === false) continue;
for (const entry of record.quads.values()) {
if (!entry.fill?.show) continue;
// Only a frame that drew the quad counts toward taking its image.
if (entry.uploadFrames > 0) {
entry.uploadFrames -= 1;
playing = true;
}
const video = entry.source;
if (
isVideo(video) &&
!video.paused &&
!video.ended &&
video.readyState >= 2
)
playing = true;
}
}
return playing;
}
return { build: rebuild, upsert, beforeRender, afterRender };
}
+2
View File
@@ -60,6 +60,8 @@ const GLOBE_CAPABILITIES = [
export function cesiumCapabilities(scene, only) { export function cesiumCapabilities(scene, only) {
const all = [ const all = [
'models', 'models',
'quads',
'meshes',
'followFrame', 'followFrame',
...GPU_ICON_CAPABILITIES, ...GPU_ICON_CAPABILITIES,
'styles', 'styles',
+5 -4
View File
@@ -24,15 +24,16 @@ test('capabilities follow what the scene supports', () => {
'imageHooks', 'imageHooks',
]; ];
const globe = { show: true }; const globe = { show: true };
assert.deepEqual(cesiumCapabilities({}), ['models', ...effects]); const draw = ['models', 'quads', 'meshes'];
assert.deepEqual(cesiumCapabilities({}), [...draw, ...effects]);
// A scene with a globe reads its visibility back. // A scene with a globe reads its visibility back.
assert.deepEqual(cesiumCapabilities({ globe }), [ assert.deepEqual(cesiumCapabilities({ globe }), [
'models', ...draw,
...effects, ...effects,
'globeVisibility', 'globeVisibility',
]); ]);
assert.deepEqual(cesiumCapabilities({ pickPositionSupported: true }), [ assert.deepEqual(cesiumCapabilities({ pickPositionSupported: true }), [
'models', ...draw,
...effects, ...effects,
'pickPosition', 'pickPosition',
]); ]);
@@ -43,7 +44,7 @@ test('capabilities follow what the scene supports', () => {
sampleHeightSupported: true, sampleHeightSupported: true,
}), }),
[ [
'models', ...draw,
...effects, ...effects,
'globeVisibility', 'globeVisibility',
'pickPosition', 'pickPosition',
-3
View File
@@ -7,12 +7,9 @@
"src/cockpitCloudEffects.js", "src/cockpitCloudEffects.js",
"src/cyberSonarGpu.js", "src/cyberSonarGpu.js",
"src/cyberSonarScene.js", "src/cyberSonarScene.js",
"src/data/cctvGizmo.js",
"src/data/geoImportPins.js", "src/data/geoImportPins.js",
"src/input/dispatcher.js", "src/input/dispatcher.js",
"src/input/sensorPick.js", "src/input/sensorPick.js",
"src/layers/cctv/projection.js",
"src/layers/cctv/rendering.js",
"src/layers/firms/rendering.js", "src/layers/firms/rendering.js",
"src/layers/ghostMaps/index.js", "src/layers/ghostMaps/index.js",
"src/layers/installations/rendering.js", "src/layers/installations/rendering.js",
+9
View File
@@ -78,6 +78,15 @@ export function createIconBook(drawSet = null, { capabilities = null } = {}) {
else if (expiresAt !== undefined) expiries.set(item.id, expiresAt); else if (expiresAt !== undefined) expiries.set(item.id, expiresAt);
drawSet?.upsert([item]); drawSet?.upsert([item]);
}, },
/**
* Draw several items at once, as `put` draws one (a restyle: each keeps
* its motion's expiry), in one write to the set.
*/
putMany(list) {
if (!list.length) return;
for (const item of list) items.set(item.id, item);
drawSet?.upsert(list);
},
remove(id) { remove(id) {
expiries.delete(id); expiries.delete(id);
if (items.delete(id)) drawSet?.remove([id]); if (items.delete(id)) drawSet?.remove([id]);
+6
View File
@@ -86,6 +86,9 @@ const DRAW_FROM_CALLER = new Set([
'./layers/street-level/panoramax', './layers/street-level/panoramax',
'./layers/air-quality', './layers/air-quality',
'./layers/directions', './layers/directions',
// Its icons, wireframes, volumes, plane and gizmo draw through `drawOf`;
// it picks, projects and reads the eye and the globe through the ports.
'./layers/cctv',
// Its data packs draw through `drawOf`; its flights ask `cameraOf`, which // Its data packs draw through `drawOf`; its flights ask `cameraOf`, which
// throws until then too. // throws until then too.
'./scenes', './scenes',
@@ -116,6 +119,9 @@ const CAMERA_FROM_CALLER = new Set([
'./ui/navigation', './ui/navigation',
'./voice/commands', './voice/commands',
'./voice/controller', './voice/controller',
// It loaded the camera factory only through the CCTV layer it took a
// constant from.
'./voice/actions',
'./voice/realtime-session', './voice/realtime-session',
]); ]);
-1
View File
@@ -9,7 +9,6 @@
"src/data/followed.js": 5, "src/data/followed.js": 5,
"src/data/pickRegistry.js": 3, "src/data/pickRegistry.js": 3,
"src/data/spriteOrder.js": 2, "src/data/spriteOrder.js": 2,
"src/layers/cctv/geometry.js": 1,
"src/layers/flights/motion.js": 1, "src/layers/flights/motion.js": 1,
"src/layers/military/motion.js": 1, "src/layers/military/motion.js": 1,
"src/layers/streetLevel/view.js": 1, "src/layers/streetLevel/view.js": 1,
+5 -4
View File
@@ -140,10 +140,11 @@ const SAMPLE_WINDOW_MS = 250;
/** /**
* True when the active photoreal tileset has finished streaming the tiles in * True when the active photoreal tileset has finished streaming the tiles in
* view (cctv.js's projectionTilesReady pattern: first Cesium3DTileset found in * view (the pattern CCTV's projectionTilesReady once used: first
* scene.primitives, duck-typed via its boolean tilesLoaded). Sampling before * Cesium3DTileset found in scene.primitives, duck-typed via its boolean
* that both blows the frame budget on forced synchronous loads and produces * tilesLoaded). Sampling before that both blows the frame budget on forced
* misses that would burn retry backoff for nothing. With NO tileset present * synchronous loads and produces misses that would burn retry backoff for
* nothing. With NO tileset present
* (OSM fallback) this returns true so the sample path is not permanently * (OSM fallback) this returns true so the sample path is not permanently
* blocked — the sample just misses and backs off. * blocked — the sample just misses and backs off.
* @param {Cesium.Viewer} viewer * @param {Cesium.Viewer} viewer
+2 -1
View File
@@ -62,7 +62,8 @@ export function createMeshFloorSampler({
/** /**
* True when a VISIBLE 3D tileset in the scene reports its streaming queue * True when a VISIBLE 3D tileset in the scene reports its streaming queue
* drained (tilesLoaded) — the mirror of cctv.js's projectionTilesReady. * drained (tilesLoaded) — as CCTV's projectionTilesReady once did (it now
* asks the globe port whether its drawn photoreal tiles have settled).
* Walks top-level primitives only (a handful; once per poll). * Walks top-level primitives only (a handful; once per poll).
* @param {Cesium.Scene} scene * @param {Cesium.Scene} scene
* @returns {boolean} * @returns {boolean}
+2
View File
@@ -83,6 +83,8 @@ export function fakeDrawPort() {
lines: make('lines'), lines: make('lines'),
shapes: make('shapes'), shapes: make('shapes'),
models: make('models'), models: make('models'),
quads: make('quads'),
meshes: make('meshes'),
/** Fire a models set's `ready` for an item, as a load finishing does. */ /** Fire a models set's `ready` for an item, as a load finishing does. */
ready(setId, id) { ready(setId, id) {
for (const cb of [...(sets.get(setId)?.ready ?? [])]) cb(id); for (const cb of [...(sets.get(setId)?.ready ?? [])]) cb(id);
+1 -1
View File
@@ -48,7 +48,7 @@ import {
getSelectedEntityContext, getSelectedEntityContext,
isContextRecordActive, isContextRecordActive,
} from '../data/contextStore.js'; } from '../data/contextStore.js';
import { CCTV_FOCUS_RESULT } from '../layers/cctv/index.js'; import { CCTV_FOCUS_RESULT } from '../layers/cctv/policy.js';
import { import {
createAnalystEngine, createAnalystEngine,
normalizeAnalystSpec, normalizeAnalystSpec,