feat(cctv): show how many cameras a thinned marker stands for

Zoomed out, the layer keeps one camera per ground cell and drew it as an
ordinary icon, so nothing showed that dozens or hundreds of other cameras
sat behind it. A cell with two or more cameras is now one round marker
with the count inside, at the centre of its cameras. Single cameras and
the active camera keep their icons.

The count covers the whole cell, so it does not change while the cell
crosses the screen edge. Markers that would overlap on screen merge into
one carrying their sum. Counts above 999 use the compact form of the UI
language and widen the marker into a pill. Clicking a marker zooms to
its group and does not choose a camera.

Ambient cards and coverage attach only to cameras drawn as icons; the
camera picker keeps one representative per visible cell as before.
This commit is contained in:
German Khokhlov committed 2026-11-18 14:26:37 +04:00
1 parent c08bd1103d
commit 607796737c
20 files changed
+965 -77

No files matched your search

+161
View File
@@ -0,0 +1,161 @@
import { formatNumber } from '../i18n/index.js';
import { fromDegrees } from '../geo/ellipsoid.js';
/** Exact small counts and compact thousands in the current UI locale. */
export function formatCameraCount(count) {
return formatNumber(
count,
count < 1000 ? undefined : { notation: 'compact' },
);
}
/** An empty cell and its on-screen picker candidate. */
export function createCameraCell(key) {
return {
key,
count: 0,
latSum: 0,
lonSum: 0,
heightSum: 0,
south: Infinity,
north: -Infinity,
west: Infinity,
east: -Infinity,
low: Infinity,
high: -Infinity,
winner: null,
rank: Infinity,
};
}
/** Accumulate one horizon-visible mount in its ground cell. */
export function addCellCamera(cell, camera) {
const { lat, lon, absoluteHeightM: height = 0 } = camera;
cell.count++;
// Integer sums make the mean independent of catalog order, to about a centimetre.
cell.latSum += Math.round(lat * 1e7);
cell.lonSum += Math.round(lon * 1e7);
cell.heightSum += Math.round(height * 100);
cell.south = Math.min(cell.south, lat);
cell.north = Math.max(cell.north, lat);
cell.west = Math.min(cell.west, lon);
cell.east = Math.max(cell.east, lon);
cell.low = Math.min(cell.low, height);
cell.high = Math.max(cell.high, height);
}
/** Geographic mean on the globe surface at the mean mount height. */
export function cellCenter(cell) {
return fromDegrees(
cell.lonSum / (1e7 * cell.count),
cell.latSum / (1e7 * cell.count),
cell.heightSum / (100 * cell.count),
);
}
/** A padded sphere around the group's geographic rectangle and mount heights. */
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = (cell.east + cell.west) / 2;
const height = (cell.high + cell.low) / 2;
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
// Half the diagonal plus 20% padding on every side.
const radius =
0.6 *
Math.hypot(
(cell.east - cell.west) * 111_320 * Math.cos(parallel),
(cell.north - cell.south) * 111_320,
cell.high - cell.low,
);
return { center: fromDegrees(lon, lat, height), radius: Math.max(1, radius) };
}
/** Add a whole ground cell to a marker, retaining the sums for a weighted mean. */
function addCell(target, cell) {
target.count += cell.count;
target.latSum += cell.latSum;
target.lonSum += cell.lonSum;
target.heightSum += cell.heightSum;
target.south = Math.min(target.south, cell.south);
target.north = Math.max(target.north, cell.north);
target.west = Math.min(target.west, cell.west);
target.east = Math.max(target.east, cell.east);
target.low = Math.min(target.low, cell.low);
target.high = Math.max(target.high, cell.high);
}
/** Claim the touching pills in this marker's bucket and its eight neighbors. */
function collectNeighbors(marker, grid, members, height, mergeDistance) {
for (let col = -1; col <= 1; col++) {
for (let row = -1; row <= 1; row++) {
const bucket = grid.get(`${marker.col + col},${marker.row + row}`);
if (!bucket) continue;
for (const other of bucket) {
// Distance between the horizontal centre segments of the two pills.
const extra = (marker.width + other.width) / 2 - height;
const dx = Math.max(0, Math.abs(marker.x - other.x) - extra);
const dy = marker.y - other.y;
if (dx * dx + dy * dy >= mergeDistance * mergeDistance) continue;
bucket.delete(other);
members.push(other);
}
}
}
}
/**
* Merge connected groups of overlapping horizontal pills. Each marker occupies
* one grid bucket. Even the widest pill can only touch its eight neighbors.
* Ground cells stay intact for the camera picker and individual-icon pass.
*/
export function mergeCountCells(
cells,
project,
widthFor,
height,
mergeDistance,
) {
const gap = mergeDistance - height;
let columnWidth = mergeDistance;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
const width = widthFor(cell.count);
columnWidth = Math.max(columnWidth, width + gap);
// The view projector reuses its result object.
return { cell, x: screen?.x, y: screen?.y, width };
});
const grid = new Map();
for (const marker of markers) {
if (!Number.isFinite(marker.x) || !Number.isFinite(marker.y)) continue;
marker.col = Math.floor(marker.x / columnWidth);
marker.row = Math.floor(marker.y / mergeDistance);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
marker.bucket.add(marker);
}
const groups = [];
const members = [];
for (const seed of markers) {
if (!seed.bucket) {
groups.push(seed.cell);
continue;
}
if (!seed.bucket.delete(seed)) continue;
members.length = 0;
members.push(seed);
for (let i = 0; i < members.length; i++)
collectNeighbors(members[i], grid, members, height, mergeDistance);
if (members.length === 1) {
groups.push(seed.cell);
} else {
const group = createCameraCell(seed.cell.key);
for (const member of members) addCell(group, member.cell);
groups.push(group);
}
}
return groups;
}
+49
View File
@@ -0,0 +1,49 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { fromDegrees } from '../geo/ellipsoid.js';
import { distance } from '../geo/vector.js';
import { getLocale, setLocale } from '../i18n/index.js';
import {
createCameraCell,
addCellCamera,
cellCenter,
cellBounds,
formatCameraCount,
} from './cctvCellCounts.js';
test('camera counts are exact through 999 and compact in the active locale', () => {
const previous = getLocale();
try {
for (const locale of ['en', 'fr', 'ja']) {
setLocale(locale);
for (const n of [2, 999, 1000, 12345]) {
const format = new Intl.NumberFormat(
locale,
n < 1000 ? {} : { notation: 'compact' },
);
assert.equal(formatCameraCount(n), format.format(n));
}
}
} finally {
setLocale(previous);
}
});
test('the marker mean weights every mount and the flight bounds cover the outlier', () => {
const cameras = [
{ lon: 12, lat: 52, absoluteHeightM: 30 },
{ lon: 12, lat: 52, absoluteHeightM: 40 },
{ lon: 12.003, lat: 52.006, absoluteHeightM: 50 },
];
const cell = createCameraCell();
for (const camera of cameras) addCellCamera(cell, camera);
const expected = fromDegrees(12.001, 52.002, 40);
assert.ok(distance(cellCenter(cell), expected) < 0.001);
const bounds = cellBounds(cell);
for (const { lon, lat, absoluteHeightM } of cameras) {
assert.ok(
distance(bounds.center, fromDegrees(lon, lat, absoluteHeightM)) <
bounds.radius,
);
}
});
+396 -22
View File
@@ -1,16 +1,22 @@
// src/data/cctvViewThinning.test.mjs — the CCTV view pass: only cameras on or
// 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
// near the screen show, a zoomed-out view groups neighboring cameras, and the layer's UI state never rebuilds every camera for a listener
// that does not read the list.
import { afterEach, test } from 'node:test';
import { afterEach, beforeEach, test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { getLocale, setLocale } from '../i18n/index.js';
import { bindRenderer } from '../render/rendererOf.js';
import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import cctvLayer, {
_cctvIconsForTest,
_extractPickedCameraIdForTest,
bindCctvWorldClickGesture,
applyCctvFocusDeemphasis,
reopenNearestCamera,
_setCctvCoverageStateForTest,
_viewRecordIdsForTest,
refreshCoverageStyles,
refreshHorizonCulling,
} from './cctv.js';
@@ -33,6 +39,7 @@ function recordsAt(lonLats) {
fovDeg: 44,
rangeM: 145,
mountHeightM: 8,
absoluteHeightM: 10,
},
position: { x: position.x, y: position.y, z: position.z },
coverageEntities: [],
@@ -47,7 +54,7 @@ function recordsAt(lonLats) {
* equator, north up, through a camera port: the view pass projects the
* cameras from its pose.
*/
function viewerAt(heightM, lonDeg = 0) {
function viewerAt(heightM, lonDeg = 0, flights = []) {
const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
@@ -70,6 +77,7 @@ function viewerAt(heightM, lonDeg = 0) {
far: 5e8,
},
});
port.flyToBounds = (bounds, options) => flights.push({ bounds, options });
const viewer = {};
bindings.push(
bindRenderer(viewer, {
@@ -82,7 +90,28 @@ function viewerAt(heightM, lonDeg = 0) {
/** The renderers bound for the running test, let go when it ends. */
const bindings = [];
const paintedLabels = new Map();
beforeEach(() => {
globalThis.document = {
createElement: () => ({
getContext: () => ({
beginPath() {},
arc() {},
roundRect() {},
measureText: (text) => ({ width: text.length * 15 }),
fill() {},
stroke() {},
fillText(text, x, y, maxWidth) {
paintedLabels.set(text, maxWidth ?? Infinity);
},
}),
}),
};
});
afterEach(() => {
paintedLabels.clear();
delete globalThis.document;
for (const unbind of bindings.splice(0)) unbind();
});
@@ -102,21 +131,42 @@ const CLUSTER = [
[0.2, 0],
];
test('zoomed out, cameras sharing a ground cell show one icon', () => {
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000),
records,
/** Count billboards the layer currently shows. */
function markers() {
const book = cctvLayer._cctvDrawnForTest().counts;
return book.show
? book
.ids()
.map(book.item)
.filter((item) => item.show)
: [];
}
/** Send a clean count-marker click through the layer's world click handler. */
function clickMarker(marker) {
const set = cctvLayer._cctvDrawnForTest().counts.setId;
const hit = { set, id: marker.id, meta: marker.meta };
assert.equal(_extractPickedCameraIdForTest(hit), null);
const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, () => {
assert.fail('a count click reached activation or empty-click deselection');
});
assert.equal(
refreshHorizonCulling(),
true,
'the first pass changes the view',
click({ drawHit: hit, gesture: { travelPx: 0, durationMs: 20 } });
}
test('a crowded cell shows its count and a singleton keeps its icon', () => {
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
assert.equal(refreshHorizonCulling(), true);
assert.deepEqual(shownIds(records), ['cam-3']);
assert.deepEqual(_viewRecordIdsForTest(), ['cam-3']);
assert.deepEqual(
markers().map((item) => item.meta.count),
[3],
);
assert.deepEqual(
cctvLayer.getDetectableObjects().map((o) => o.sourceId),
['cam-3'],
);
const shown = shownIds(records);
assert.equal(shown.length, 2, 'one for the cluster, one for the far camera');
assert.ok(shown.includes('cam-3'), 'a camera alone in its cell shows');
assert.deepEqual(_viewRecordIdsForTest().sort(), shown);
});
test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
@@ -126,7 +176,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () =>
records,
});
refreshHorizonCulling();
const before = shownIds(records);
const before = cctvLayer.getUIState().cameraIndex;
const list = _viewRecordIdsForTest();
// 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]) {
@@ -135,7 +185,11 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () =>
records,
});
refreshHorizonCulling();
assert.deepEqual(shownIds(records), before, `pan by ${shiftM} m`);
assert.deepEqual(
cctvLayer.getUIState().cameraIndex,
before,
`pan by ${shiftM} m`,
);
}
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
@@ -151,16 +205,17 @@ test('a small zoom within one cell size keeps the same winners', () => {
records,
});
refreshHorizonCulling();
return shownIds(records);
return cctvLayer.getUIState().cameraIndex;
};
// Cells come in power-of-two metre steps: about 1.5 km and 1.6 km cells at
// these heights fall in the same step, so the same cameras win.
assert.deepEqual(shownAt(20_500), shownAt(20_000));
});
test('a healthy camera wins its cell over an unknown one', () => {
test('the picker prefers the healthy camera and the marker stays at the mean', () => {
const { records } = recordsAt(CLUSTER.slice(0, 2));
// Whichever camera the id order would pick, the healthy one must win.
let first;
for (const id of ['cam-0', 'cam-1']) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000),
@@ -168,7 +223,16 @@ test('a healthy camera wins its cell over an unknown one', () => {
healthById: new Map([[id, { status: 'ok' }]]),
});
refreshHorizonCulling();
assert.deepEqual(shownIds(records), [id]);
assert.deepEqual(
cctvLayer.getUIState().cameraIndex.map((c) => c.id),
[id],
);
const { pos } = markers()[0];
const center = Cesium.Cartesian3.fromDegrees(0.0005, 0, 10);
assert.ok(Cesium.Cartesian3.distance(pos, center) < 0.02);
if (first) assert.deepEqual(pos, first);
first = pos;
records.reverse();
}
});
@@ -181,6 +245,10 @@ test('the active camera always shows, even in a crowded cell', () => {
activeCameraId: active.camera.id,
});
refreshHorizonCulling();
assert.deepEqual(
markers().map((item) => item.meta.count),
[2],
);
const icons = _cctvIconsForTest();
assert.ok(
icons.item(active.camera.id).show,
@@ -268,3 +336,309 @@ test('the camera picker lists the view, with the active camera first', () => {
);
assert.equal(state.cameras.length, 3, 'the full list is still every camera');
});
test('panning a cell across the padded screen edge keeps its full count', () => {
const { records } = recordsAt([
[0.277, 0],
[0.28, 0],
[0.29, 0],
]);
for (const lon of [0.015, 0]) {
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000, lon), records });
refreshHorizonCulling();
assert.deepEqual(
markers().map((item) => item.meta.count),
[3],
);
if (lon === 0)
assert.equal(cctvLayer.getUIState().cameraIndex[0].id, 'cam-0');
}
});
test('only members on the near side of the horizon count', () => {
// At 20 km the limb crosses this cell between 4.55 and 4.69 degrees.
// All three mounts project inside the screen in the query-port fixture.
const { records } = recordsAt([
[4.5, 0],
[4.55, 0],
[4.69, 0],
]);
const viewer = {};
const { port } = fakeCameraPort({
pose: {
position: Cesium.Cartesian3.fromDegrees(0, 0, 20_000),
fovy: undefined,
},
});
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { width: WIDTH, height: HEIGHT },
query: { project: () => ({ x: 400, y: 300 }) },
}),
);
_setCctvCoverageStateForTest({ viewer, records });
refreshHorizonCulling();
assert.deepEqual(
markers().map((item) => item.meta.count),
[2],
);
});
test('co-located cameras separate below the minimum cell size', () => {
const { records } = recordsAt([
[0, 0],
[0, 0],
]);
_setCctvCoverageStateForTest({ viewer: viewerAt(300), records });
refreshHorizonCulling();
assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']);
assert.deepEqual(markers(), []);
});
test('a count click frames its members and preserves an explicit camera choice', () => {
for (const spread of [0, 0.01]) {
const flights = [];
const { records } = recordsAt([
[0, 0],
[spread, 0],
[0.2, 0],
]);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, 0, flights),
records,
activeCameraId: 'cam-2',
openingCameraProvisional: false,
});
refreshHorizonCulling();
const marker = markers()[0];
clickMarker(marker);
assert.equal(flights.length, 1);
const { bounds, options } = flights[0];
for (const record of records.slice(0, 2))
assert.ok(
bounds.radius >
Cesium.Cartesian3.distance(bounds.center, record.position),
);
const range = options.offset.range;
assert.ok(range > 0 && range < 10_000);
// Run the same view pass at the requested destination.
const center = Cesium.Cartographic.fromCartesian(bounds.center);
const destination = viewerAt(
center.height + range,
Cesium.Math.toDegrees(center.longitude),
);
assert.equal(reopenNearestCamera(), false);
assert.equal(cctvLayer.getUIState().activeCameraId, 'cam-2');
_setCctvCoverageStateForTest({
viewer: destination,
records,
activeCameraId: 'cam-2',
});
refreshHorizonCulling();
assert.deepEqual(markers(), []);
assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']);
}
});
test('disabling the layer hides its counts', () => {
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.equal(markers().length, 1);
cctvLayer.disable();
assert.deepEqual(markers(), []);
});
test('coverage leaves grouped neighbors and returns when their icons separate', () => {
const { records } = recordsAt([
[0, 0],
[0, 0],
[0, 0],
]);
// Lines already materialised at close zoom.
for (const record of records) record.coverageEntities = [{ show: true }];
const viewer = viewerAt(20_000);
_setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0' });
refreshCoverageStyles();
refreshHorizonCulling();
assert.deepEqual(
records.map((r) => r.coverageEntities[0].show),
[true, false, false],
);
records[1].camera.lon = 0.05;
records[1].position = Cesium.Cartesian3.fromDegrees(0.05, 0, 10);
refreshHorizonCulling();
assert.deepEqual(
records.map((r) => r.coverageEntities[0].show),
[true, true, true],
);
assert.deepEqual(markers(), []);
});
test('count markers share the camera focus fade and recover on release', () => {
const { records } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
const target = {
screenRect: { left: 40, top: 40, right: 60, bottom: 60 },
cameraDistance: 1000,
};
const params = DEFAULT_FOCUS_DEEMPHASIS_PARAMS;
let previousActiveCount = 0;
const tick = (nowMs, target) => {
previousActiveCount = applyCctvFocusDeemphasis({
records,
nowMs,
target,
params,
previousActiveCount,
screenPositionFor: () => ({ x: 50, y: 50 }),
cameraDistanceFor: () => 1200,
}).activeCount;
};
tick(0, target);
tick(params.attackMs + 1, target);
assert.equal(markers()[0].focus, params.dimFloor);
tick(params.attackMs + 2, null);
tick(params.attackMs + params.releaseMs + 3, null);
assert.equal(markers()[0].focus, 1);
});
test('overlapping cells merge at their weighted centre and keep every camera in the flight bounds', () => {
// The meridian separates the two near cells at every grid level.
const { records } = recordsAt([
[-0.001, 0],
[-0.001, 0],
[0.002, 0],
[0.002, 0],
[0.002, 0],
[0.05, 0],
[0.05, 0],
[0, 0.001],
[0, -0.001],
]);
const flights = [];
let previous;
for (const [pan, order] of [
[0, records],
[0.003, [...records].reverse()],
]) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, pan, flights),
records: order,
activeCameraId: 'cam-7',
healthById: new Map([[order[0].camera.id, { status: 'ok' }]]),
});
refreshHorizonCulling();
const shown = markers();
assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']);
assert.equal(
shown.reduce((sum, m) => sum + m.meta.count, 0),
7,
);
assert.deepEqual(
shown.map((m) => m.meta.count).sort((a, b) => a - b),
[2, 5],
);
const merged = shown.find((m) => m.meta.count === 5);
assert.ok(
Cesium.Cartesian3.distance(
merged.pos,
Cesium.Cartesian3.fromDegrees(0.0008, 0, 10),
) < 0.01,
);
const positions = shown.map((m) => [m.id, m.pos]);
if (previous) assert.deepEqual(positions, previous);
previous = positions;
clickMarker(merged);
const { bounds } = flights.at(-1);
assert.ok(
records
.slice(0, 5)
.every(
(r) =>
Cesium.Cartesian3.distance(r.position, bounds.center) <
bounds.radius,
),
);
assert.ok(
bounds.radius < 300,
'the separate cell stays outside the flight bounds',
);
}
});
test('long localized labels use their measured width on the canvas and billboard', () => {
const locale = getLocale();
try {
setLocale('ru');
const { records } = recordsAt([
...Array(1300).fill([-0.008, 0]),
[0.06, 0],
[0.06, 0],
]);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
const short = markers().find((m) => m.meta.count === 2);
const long = markers().find((m) => m.meta.count === 1300);
assert.equal(short.image.canvas.width, short.image.canvas.height);
assert.ok(long.image.canvas.width > long.image.canvas.height);
assert.equal(long.size[1], short.size[1]);
assert.equal(
long.size[0] / long.size[1],
long.image.canvas.width / long.image.canvas.height,
);
const text = new Intl.NumberFormat('ru', { notation: 'compact' }).format(
1300,
);
assert.ok(paintedLabels.get(text) >= text.length * 15);
assert.ok(
long.image.canvas.width > text.length * 15,
'the digits have padding',
);
} finally {
setLocale(locale);
}
});
test('a wider localized pill merges a horizontal neighbor beyond the circle diameter', () => {
const locale = getLocale();
try {
setLocale('ru');
// The centers are 46 CSS pixels apart. Only the pill reaches its neighbor.
const at = (count) => {
const { records } = recordsAt([
...Array(count).fill([-0.008, 0]),
[0.008, 0],
[0.008, 0],
]);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
return markers().map((m) => m.meta.count);
};
assert.deepEqual(at(2), [2, 2]);
assert.deepEqual(at(1300), [1302]);
} finally {
setLocale(locale);
}
});
test('a merged centre can pick up a third count marker', () => {
// The two northern centres are 35 px apart. Each is 40 px from the
// southern one, but their combined centre is only 36 px away.
const { records } = recordsAt([
[-0.006, 0],
[-0.006, 0],
[0.006, 0],
[0.006, 0],
[0, -0.0126],
[0, -0.0126],
]);
_setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.deepEqual(
markers().map((m) => m.meta.count),
[6],
);
});
+1 -1
View File
@@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) {
let rank = 0;
const push = (id, { pinned = false, active = false } = {}) => {
const record = layerState._recordById.get(id);
if (!record?.position) return;
if (!record?.position || (!active && record.viewGrouped)) return;
entries.push(
createCctvThumbnailOverlayEntry({
id,
+120
View File
@@ -0,0 +1,120 @@
import { createIconBook } from '../../render/motion/iconBook.js';
import {
cellCenter,
formatCameraCount,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { getLocale } from '../../i18n/index.js';
import {
COUNT_MARKER_PX,
COUNT_MERGE_DISTANCE_PX,
COUNT_MERGE_PASSES,
} from './policy.js';
/** A pool of static count billboards sharing one canvas for each label. */
export function createCountMarkers(set) {
const book = createIconBook(set);
const images = new Map();
const groups = [];
let locale;
/** Rasterise at twice the CSS size to keep small digits sharp. */
function imageFor(text) {
if (images.has(text)) return images.get(text);
const canvas = document.createElement('canvas');
const size = COUNT_MARKER_PX * 2;
const ctx = canvas.getContext('2d');
const font = 'bold 26px sans-serif';
ctx.font = font;
canvas.width = Math.max(size, Math.ceil(ctx.measureText(text).width) + 24);
canvas.height = size;
ctx.beginPath();
ctx.roundRect(2, 2, canvas.width - 4, size - 4, size / 2 - 2);
ctx.fillStyle = '#0e1720';
ctx.fill();
ctx.lineWidth = 3;
ctx.strokeStyle = '#75e7ff';
ctx.stroke();
ctx.fillStyle = ctx.strokeStyle;
ctx.font = font;
ctx.textAlign = 'center';
ctx.textBaseline = 'middle';
ctx.fillText(text, canvas.width / 2, size / 2);
const image = { canvas, key: `cctv-count:${text}` };
images.set(text, image);
return image;
}
/** Reuse the first slots for visible cells and hide the unused tail. */
function update(cells, project) {
const writes = [];
const nextLocale = getLocale();
let slot = 0;
// Ground-key order keeps the pooled slots stable across pans and health changes.
let visible = cells
.filter((cell) => cell.count > 1)
.sort((a, b) => a.key.localeCompare(b.key));
const widthFor = (count) =>
imageFor(formatCameraCount(count)).canvas.width / 2;
for (
let pass = 0;
pass < COUNT_MERGE_PASSES && visible.length > 1;
pass++
) {
const merged = mergeCountCells(
visible,
project,
widthFor,
COUNT_MARKER_PX,
COUNT_MERGE_DISTANCE_PX,
);
if (merged.length === visible.length) break;
visible = merged;
}
for (const cell of visible) {
const index = slot++;
const last = groups[index];
groups[index] = cell;
// Bounds are live for picking even when the drawn label and mean stay put.
if (
nextLocale === locale &&
last?.count === cell.count &&
last.lonSum === cell.lonSum &&
last.latSum === cell.latSum &&
last.heightSum === cell.heightSum
)
continue;
const id = `cctv-count:${index}`;
const previous = book.item(id);
const pos = cellCenter(cell);
const image = imageFor(formatCameraCount(cell.count));
const meta = previous?.meta ?? { aggregate: true, slot: index };
meta.count = cell.count;
writes.push({
id,
pos,
image,
meta,
size: [image.canvas.width / 2, COUNT_MARKER_PX],
disableDepthTest: Infinity,
show: true,
focus: previous?.focus,
});
}
locale = nextLocale;
groups.length = slot;
for (let i = slot; i < book.size; i++) {
const item = book.item(`cctv-count:${i}`);
if (item.show) writes.push({ ...item, show: false });
}
book.putMany(writes);
if (!book.show) book.show = true;
}
/** Resolve only a visible pooled billboard belonging to this layer. */
function pickedCell(hit) {
if (!book.show || !hit || hit.set !== book.setId) return null;
const item = book.item(hit.id);
return item?.show ? groups[item.meta.slot] : null;
}
return { book, update, pickedCell };
}
+4
View File
@@ -163,9 +163,11 @@ export function createLifecycle({
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
layerState._viewUnpublished = false;
layerState._viewPose = null;
layerState._viewMotionPass = null;
@@ -386,6 +388,7 @@ export function createLifecycle({
parts.rendering.refreshHorizonCulling();
const input = inputFor(layerState._viewer);
layerState._clickSubscription?.();
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
@@ -536,6 +539,7 @@ export function createLifecycle({
parts.rendering.hideCctvVisuals();
// Nothing is in view while the layer is off.
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
parts.presentation.notifyListeners();
},
+25 -2
View File
@@ -1,6 +1,7 @@
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
import { cellBounds } from '../../data/cctvCellCounts.js';
import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -104,6 +105,27 @@ export function createNavigation({
return CCTV_FOCUS_RESULT.FOCUSED;
}
/** Frame a group's padded bounds from above, including coincident mounts. */
function zoomToCell(cell) {
const viewer = layerState._viewer;
const camera = cameraOf(viewer);
const pose = camera.pose();
const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2);
const canvas = canvasOf(viewer);
const height = canvas?.clientHeight || canvas?.height || 1;
const halfFov = Math.atan(tanHalfY * Math.min(1, pose.aspectRatio || 1));
const bounds = cellBounds(cell);
// A tight group lands comfortably inside the individual-icon level.
const closeRange =
(VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY);
const range = Math.max(closeRange, bounds.radius / Math.sin(halfFov));
camera.flyToBounds(bounds, {
offset: { heading: 0, pitch: -Math.PI / 2, range },
durationS: 1.2,
easing: 'cubicInOut',
});
}
function focusCamera(cameraId, duration = 2.2) {
return focusCctvRecord(
layerState._viewer,
@@ -179,6 +201,7 @@ export function createNavigation({
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
zoomToCell,
focusCamera,
maybeAutoHop,
cctvCycleIndex,
+9
View File
@@ -71,6 +71,15 @@ export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Diameter of a grouped camera marker in CSS pixels.
export const COUNT_MARKER_PX = 34;
// Separation of two circular counts, including a four-pixel gap between rings.
export const COUNT_MERGE_DISTANCE_PX = COUNT_MARKER_PX + 4;
// Recheck moved centres and wider labels while bounding work on motion ticks.
export const COUNT_MERGE_PASSES = 3;
// Icons this far past the screen edge (fraction of its size) still show, so
// a pan does not reveal empty ground before the next view pass.
+1 -1
View File
@@ -319,7 +319,7 @@ export function createPresentation({
*/
function cameraIndex() {
const view = layerState._viewRecords;
const view = layerState._pickerRecords;
const active = parts.selection.getActiveRecord();
const cached = layerState._cameraIndexCache;
if (cached?.view === view && cached.active === active) return cached.list;
+88 -42
View File
@@ -1,3 +1,5 @@
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
import { isHeadingEstimated } from './headingConfidence.js';
import {
ACTIVE_CAMERA_COLOR,
@@ -139,6 +141,14 @@ export function createRendering({
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
layerState._counts = createCountMarkers(
drawOf(viewer).icons({
id: `cctv:${iconSets}:counts`,
horizonCull: true,
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('cctv') ?? 0,
}),
);
return set.id;
}
@@ -146,6 +156,8 @@ export function createRendering({
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
layerState._counts?.book.dispose();
layerState._counts = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
@@ -223,7 +235,7 @@ export function createRendering({
/**
* Focus modulation rides the layer's existing animation loop; no additional
* scene listener is installed. Only camera-icon alpha changes here — coverage
* scene listener is installed. Camera and count icons share the fade. Coverage
* geometry and monitor-plane styling retain their established cadence.
*/
@@ -276,11 +288,10 @@ export function createRendering({
let writes = 0;
let transitioning = false;
let activeCount = 0;
for (const record of records || []) {
const id = record.camera?.id;
const item = icons?.item(id);
if (!item) continue;
const position = record.position;
/** Advance one icon or count billboard on the shared focus clock. */
function apply(book, id, position) {
const item = book?.item(id);
if (!item) return;
const scale = item.scale ?? 1;
// CCTV never publishes a tracked focus target, so every icon is ambient.
const focus = advanceSpriteFocus(item.meta, {
@@ -299,34 +310,23 @@ export function createRendering({
if (focus.active) activeCount += 1;
// Order-independent narrow amendment to always-visible icons: CCTV
// contacts retain a non-zero floor while yielding near the tracked target.
if (focusAlphaNeedsWrite(icons.focus(id), focus.factor, params)) {
icons.setFocus(id, focus.factor);
if (focusAlphaNeedsWrite(book.focus(id), focus.factor, params)) {
book.setFocus(id, focus.factor);
writes += 1;
}
}
for (const record of records || [])
apply(icons, record.camera?.id, record.position);
const counts = layerState._counts?.book;
for (const id of counts?.ids() ?? [])
apply(counts, id, counts.item(id).pos);
return { writes, transitioning, activeCount, ran: true };
}
/**
* Updates visual styles (colors, widths, visibility) for all camera icons,
* coverage polylines, viewshed volumes, and projection entities based on which
* camera is active, whether the layer is enabled, and the current
* coverage-mode/projection toggle states.
*/
/**
* Field-test fix (2026-07-06): horizon-culls camera icons on the CPU as the
* icon shader does on the GPU. With the globe hidden (Google-3D
* regime) nothing writes far-side depth and the icons are always-on-top, so
* the shown set (cards, geometry, the picker) must not include London's
* cluster from a US viewpoint.
*
* The same pass thins the view so a large catalog stays readable and cheap:
* icons well off screen hide, and each camera competes for a world-anchored
* cell sized to VIEW_CELL_PX at its distance (healthiest first, then a stable
* id order). The active camera shows whenever it is above the horizon
* and near the screen, even in a crowded cell. The shown records become
* `_viewRecords`, the working set for geometry, cards and the camera picker;
* the array keeps its identity while the shown set is unchanged.
* Group horizon-visible mounts by ground cell. Every cell with a member
* near the screen contributes a representative to the picker. Singletons
* and the active camera also enter the icon, geometry and card working set.
*
* Runs on camera settle, throttled during motion, on resize, enable and
* activation changes — never per frame.
@@ -365,7 +365,9 @@ export function createRendering({
const project = screenProjector(pose, width, height);
const pass = (layerState._viewPassId = (layerState._viewPassId || 0) + 1);
const shown = [];
const picker = [];
const cells = new Map();
const visibleCells = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -381,12 +383,12 @@ export function createRendering({
)
continue;
const screen = project(position);
if (
!screen ||
!(screen.x >= minX && screen.x <= maxX) ||
!(screen.y >= minY && screen.y <= maxY)
)
continue;
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
@@ -395,21 +397,53 @@ export function createRendering({
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
record.viewPass = pass;
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
shown.push(record);
picker.push(record);
continue;
}
const key = worldCellKey(record, cellM);
let cell = cells.get(key);
if (!cell) {
cell = createCameraCell(key);
cells.set(key, cell);
}
addCellCamera(cell, record.camera);
record.viewCell = cell;
if (!nearScreen) continue;
// The picker ranks only candidates that were in its padded viewport.
if (!cell.winner) visibleCells.push(cell);
const rank = viewRank(record);
const holder = cells.get(key);
if (!holder || rank < holder.rank) cells.set(key, { record, rank });
if (rank < cell.rank) {
cell.winner = record;
cell.rank = rank;
}
}
for (const { record } of cells.values()) {
record.viewPass = pass;
shown.push(record);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
record.pickerPass = pass;
if (cell.count === 1) {
record.viewPass = pass;
shown.push(record);
}
}
layerState._counts?.update(visibleCells, project);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
for (const record of layerState._records) {
const cell = record.viewCell;
record.viewCell = null;
const grouped = Boolean(cell?.winner && cell.count > 1);
if (grouped !== !!record.viewGrouped) {
const id = record.camera.id;
coverageChanged ||= layerState._coverageCohort?.has(id);
cardsChanged ||=
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
@@ -421,7 +455,14 @@ export function createRendering({
previous.length !== shown.length ||
previous.some((record) => record.viewPass !== pass);
if (changed) layerState._viewRecords = shown;
return changed;
const oldPicker = layerState._pickerRecords ?? [];
const pickerChanged =
picker.length !== oldPicker.length ||
oldPicker.some((record) => record.pickerPass !== pass);
if (pickerChanged) layerState._pickerRecords = picker;
if (coverageChanged) refreshCoverageStyles();
if (cardsChanged) parts.cards.pushAmbientCardEntries();
return changed || pickerChanged;
}
/**
@@ -526,6 +567,7 @@ export function createRendering({
);
parts.projection.clearProjectionOverlay();
if (layerState._icons) layerState._icons.show = false;
if (layerState._counts) layerState._counts.book.show = false;
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -535,8 +577,12 @@ export function createRendering({
const activeRecord = parts.selection.getActiveRecord();
parts.geometry.ensureActiveCoverageEntities(activeRecord);
const activeId = activeRecord?.camera.id || null;
const coverageVisible =
parts.geometry.buildCoverageVisibleSet(activeRecord);
const cohort = parts.geometry.buildCoverageVisibleSet(activeRecord);
layerState._coverageCohort = cohort;
const coverageVisible = new Set();
for (const id of cohort) {
if (!layerState._recordById.get(id)?.viewGrouped) coverageVisible.add(id);
}
// Drawn coverage needs geometry too (geometryQueue's working set).
layerState._coverageVisibleIds = coverageVisible;
const coverageOn = layerState._coverageMode !== 'off';
+6
View File
@@ -128,15 +128,21 @@ test('the icons go with the viewer that drew them, whichever tears down', () =>
});
try {
const old = createCameraIcons(first);
const oldCounts = state._counts.book.setId;
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);
assert.equal(one.draw.sets.get(oldCounts).disposed, true);
const counts = two.draw.set(state._counts.book.setId);
assert.equal(counts.spec.horizonCull, true);
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
assert.equal(counts.disposed, true);
assert.equal(state._counts, null);
} finally {
one.unbind();
two.unbind();
+7 -1
View File
@@ -41,6 +41,12 @@ export function createSelection({
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
const cell =
layerState._enabled && layerState._counts?.pickedCell(event.drawHit);
if (cell) {
parts.navigation.zoomToCell(cell);
return;
}
onClick(event);
});
}
@@ -139,11 +145,11 @@ export function createSelection({
// is looking at ever asks.
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
parts.rendering.refreshCoverageStyles();
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
+43
View File
@@ -1,6 +1,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { createNavigation } from './navigation.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
@@ -52,3 +54,44 @@ test('same-camera selection notifies browser-overlay feeds so playback can retry
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
test('a count click preserves the provisional opening pick until the view settles', () => {
const viewer = {};
const flights = [];
const unbind = bindRenderer(viewer, {
camera: {
pose: () => ({ fovy: Math.PI / 3, aspectRatio: 1 }),
flyToBounds: (bounds) => flights.push(bounds),
},
canvas: { height: 600 },
});
try {
const cell = { west: 1, east: 2, south: 0, north: 0, low: 0, high: 0 };
const state = {
_enabled: true,
_viewer: viewer,
_openingCameraProvisional: true,
_activeCameraId: 'opening',
_counts: { pickedCell: () => cell },
};
const parts = {};
parts.navigation = createNavigation({ state, parts });
const selection = createSelection({
state,
parts,
services: { activation: {}, picking: {} },
});
const click = selection.bindCctvWorldClickGesture(
{ onClick: (fn) => fn },
() => {
assert.fail('a count click reached activation or deselection');
},
);
click({ drawHit: {}, gesture: { travelPx: 0, durationMs: 20 } });
assert.equal(flights.length, 1);
assert.equal(state._activeCameraId, 'opening');
assert.equal(state._openingCameraProvisional, true);
} finally {
unbind();
}
});
+4
View File
@@ -15,6 +15,7 @@ export function createState({ services }) {
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._counts = null;
layerState._records = [];
@@ -95,10 +96,13 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// Includes a health-ranked representative for each visible group.
layerState._pickerRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
layerState._coverageCohort = null;
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
+8
View File
@@ -1,3 +1,4 @@
import { createCountMarkers } from './countMarkers.js';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
@@ -123,12 +124,18 @@ export function createTesting({ state: layerState, services, parts, source }) {
layerState._showProjection = !!showProjection;
layerState._healthById = healthById;
layerState._viewRecords = [];
layerState._pickerRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._coverageCohort = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
layerState._counts = createCountMarkers({
...testIconSet(),
id: 'cctv:test:counts',
});
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
@@ -148,6 +155,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
counts: layerState._counts?.book,
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
+7
View File
@@ -485,6 +485,13 @@ export function createCesiumScreenModulation(scene, { frame, onChange }) {
? 'icon'
: null;
if (!kind || !native.shaderProgram || !native.uniformMap) continue;
// Aggregate billboards occupy their own collection and represent groups.
if (
kind === 'billboard' &&
native.owner.length &&
native.owner.get(0).id?.meta?.aggregate === true
)
continue;
const source = native.shaderProgram;
// Label backgrounds are non-SDF billboard batches. The version-tested
// engine pick association distinguishes them without enumerating
@@ -606,3 +606,19 @@ test('disposal does not overwrite a successor update owner', () => {
assert.equal(f.primitives.update, successor);
f.primitives.destroy();
});
test('aggregate markers keep their native billboard command during a contact sweep', () => {
const owner = new Cesium.BillboardCollection();
owner.add({ id: { meta: { aggregate: true } } });
const command = { owner, uniformMap: {}, shaderProgram: {} };
const f = fixture({ commands: [command] });
try {
f.part.set(sweep());
assert.equal(f.draw()[0], command);
assert.equal(f.part.stats.supported, true);
} finally {
f.part.dispose();
owner.destroy();
f.primitives.destroy();
}
});