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

+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,