From 52ebd8ac9409dda562678ea11779cf70bca1eee9 Mon Sep 17 00:00:00 2001 From: bassem chagra Date: Sat, 24 Oct 2026 13:50:03 +0200 Subject: [PATCH 01/56] feat(alpr): show datasheet specs for mapped ALPR camera models Read the OSM `model` tag on ALPR records and resolve it, with the `manufacturer` tag, against 16 vendored CCTV Camera Database records (v2.29.0): Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC. A resolved camera's card gains a SPEC line; an unknown or mis-attributed model shows nothing, and the raw tag text never reaches the card or the voice tools. The CCTV matcher becomes createModelSpecLookup(records) so both layers share one set of matching rules, and specSummary falls back to pixel size or megapixels when a record has no resolution label. 459 of the 1,567 OSM ALPR nodes with a model tag resolve. The hourly extract the layer reads by default has no model field yet, so tile records carry it only once the extract publishes it. --- DATA_SOURCES.md | 7 + docs/CURRENT-STATE.md | 7 + scripts/package-boundaries.json | 4 + src/data/alprCameras.test.mjs | 1 + src/layers/alpr/modelSpecs.js | 257 ++++++++++++++++++++++++++++ src/layers/alpr/modelSpecs.test.mjs | 100 +++++++++++ src/layers/alpr/records.js | 2 + src/layers/alpr/tileRecords.js | 2 + src/layers/alpr/visuals.js | 10 +- src/layers/cctv/modelSpecs.js | 115 +++++++------ 10 files changed, 452 insertions(+), 53 deletions(-) create mode 100644 src/layers/alpr/modelSpecs.js create mode 100644 src/layers/alpr/modelSpecs.test.mjs diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 3557c4137b..13c3dbac80 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -234,6 +234,13 @@ commercial use with attribution and applicable database share-alike/access obligations; it does not license the application code. Trimmed test-only tile fixtures retain their provenance in `src/data/fixtures/README.md`. +A mapped `model` tag that names datasheet hardware adds a spec line to the +selected card. The specs are 16 verbatim CC0-1.0 records from the CCTV Camera +Database model-enrichment extract (v2.29.0), compiled into +`src/layers/alpr/modelSpecs.js`; nothing is fetched at runtime, and an +unrecognised tag is never displayed. The hourly extract does not carry `model` +yet, so only an Overpass-backed source shows these lines today. + ### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`) The CCTV layer's hardware-model specs are a small verbatim extract (v2.26.0) of the diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index ede889fdc7..fddce328ae 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -788,6 +788,13 @@ The row count explicitly says **nearby**: loaded records can be outside the screen. Cyan camera badges use Manjunath's camera artwork; selection switches to a larger coral badge with corner brackets and an animated tactical card. Numeric mapped bearings draw illustrative 90 m direction wedges (not measured coverage). +A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant, +Genetec AutoVu SharpV, Axis, Verkada, Bosch MIC; 459 of the 1,567 tagged cameras +in October 2026) gets a `SPEC` line on its card from vendored datasheet records +(`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's +`createModelSpecLookup`). A `manufacturer` naming another maker rejects the +match, and the raw tag text is never shown. The hourly extract has no `model` +field yet, so only an Overpass-backed source fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 3970a1ee2d..3787b57b1e 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1497,6 +1497,8 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", + "src/layers/cctv/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/data/inputOwnership.js", @@ -1927,6 +1929,7 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", @@ -2717,6 +2720,7 @@ "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", + "src/layers/alpr/modelSpecs.js", "src/layers/alpr/overlay.js", "src/layers/alpr/source.js", "src/layers/awareness/controls.js", diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index 5a50220d54..8867739a10 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -54,6 +54,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { longitude: -97.7431, operator: 'Flock Safety', manufacturer: null, + model: null, cameraType: 'fixed', zone: 'traffic', directionDeg: 270, diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js new file mode 100644 index 0000000000..789b6fc4a5 --- /dev/null +++ b/src/layers/alpr/modelSpecs.js @@ -0,0 +1,257 @@ +/** + * @module alprModelSpecs + * + * Datasheet specs for the ALPR hardware that OpenStreetMap mappers name. + * + * 1,567 mapped ALPR cameras carry a `model` tag (October 2026). This module + * vendors the records for the models among them that the CCTV Camera Database + * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — + * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, + * which resolve 459 of those cameras — and resolves a camera's `model` (with + * its `manufacturer`) through the CCTV layer's matcher. The hourly extract the + * layer reads by default does not publish `model` yet, so today only an + * Overpass-backed source shows these specs. Flock Safety publishes no + * datasheet resolution, so Flock models stay unresolved; an unknown model + * never implies anything. + * + * Scope guardrail: records describe camera PRODUCTS (optics, resolution, + * night vision) — never endpoints, operators or what a camera records. + */ + +import { createModelSpecLookup } from '../cctv/modelSpecs.js'; + +/** + * Verbatim records from the dataset's model-enrichment extract (v2.29.0). + * Mappers tag the bare product code ("L6Q", "MIC-7522-Z30B") where the + * datasheet names the product line too ("Vigilant L6Q"), so each record also + * lists its bare code as an alias. + */ +const RECORDS = [ + { + id: 'motorola-solutions-l5f', + brand: 'Motorola Solutions', + model: 'Vigilant L5F', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5f/', + aliases: ['L5F', 'L5F Fixed LPR Camera System'], + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l5m', + brand: 'Motorola Solutions', + model: 'Vigilant L5M', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5m/', + aliases: [ + 'L5M', + 'L5M Mobile LPR Camera System', + 'L5M Mobile ANPR Camera System', + ], + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l5q', + brand: 'Motorola Solutions', + model: 'Vigilant L5Q', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l5q/', + aliases: ['L5Q', 'L5Q Quick Deploy LPR Camera System'], + resolution: { mp: 3 }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l6d', + brand: 'Motorola Solutions', + model: 'Vigilant L6D', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l6d/', + aliases: [ + 'L6D', + 'L6D Dual-Purpose LPR Camera', + 'VSM-L6D-8IR', + 'VSM-L6D-7IR', + ], + fov_deg: '52-3 horizontal', + resolution: { mp: 1.6, w: 1440, h: 1080 }, + lens_count: 2, + varifocal: true, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'motorola-solutions-l6q', + brand: 'Motorola Solutions', + model: 'Vigilant L6Q', + type: 'box', + url: 'https://www.cctv-database.com/camera/motorola-solutions-l6q/', + aliases: ['L6Q', 'L6Q Quick-Deploy LPR Camera System'], + resolution: { mp: 2.1, w: 1920, h: 1080, label: '1080p' }, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpv', + brand: 'Genetec', + model: 'AutoVu SharpV', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/', + aliases: [ + 'AutoVu SharpV G3', + 'AU-V-WS850-LC-G3-000', + 'AU-V-BS850-LC-G3-0M0', + 'AU-V-BS850-LC-G3-0M1', + ], + resolution: { mp: 2.3, w: 1920, h: 1200, label: '1920x1200' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpv-g2', + brand: 'Genetec', + model: 'AutoVu SharpV G2', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv-g2/', + aliases: ['AutoVu SharpV G1', 'AU-V-WS850-LC-G2', 'AU-V-WS850-LC'], + resolution: { mp: 1.2, w: 1280, h: 960, label: '1280x960' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpx', + brand: 'Genetec', + model: 'AutoVu SharpX', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/', + // i18n-ignore: datasheet label + resolution: { mp: 1, w: 1024, h: 946, label: 'XGA (1024x946)' }, + lens_count: 2, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'genetec-autovu-sharpz3', + brand: 'Genetec', + model: 'AutoVu SharpZ3', + type: 'box', + url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpz3/', + resolution: { mp: 1.6, w: 1456, h: 1088, label: '1456x1088' }, + lens_count: 3, + night_vision: { type: 'ir' }, + environment: ['outdoor'], + }, + { + id: 'axis-q1700-le', + brand: 'Axis', + model: 'Q1700-LE', + type: 'box', + url: 'https://www.cctv-database.com/camera/axis-q1700-le/', + fov_deg: '16-2.3 horizontal / 9.6-1.3 vertical', + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 50 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'axis-q1800-le', + brand: 'Axis', + model: 'Q1800-LE', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/axis-q1800-le/', + aliases: ['03107-001', 'Q1800-LE-3 (License Plate Verifier kit)'], + fov_deg: '38-2.3 horizontal', + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 40 }, + environment: ['indoor', 'outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cb62-te-f', + brand: 'Verkada', + model: 'CB62-TE-F', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/verkada-cb62-te-f/', + fov_deg: '42 to 17 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 50 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-ch52-e-f', + brand: 'Verkada', + model: 'CH52-E-F', + type: 'panoramic', + url: 'https://www.cctv-database.com/camera/verkada-ch52-e-f/', + fov_deg: '89 to 37 H (per sensor); up to 328 combined', + // i18n-ignore: datasheet label + resolution: { mp: 5, w: 2688, h: 1944, label: '4 x 5MP (20MP)' }, + lens_count: 4, + varifocal: true, + night_vision: { type: 'ir', range_m: 30 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cp63-e', + brand: 'Verkada', + model: 'CP63-E', + type: 'ptz', + url: 'https://www.cctv-database.com/camera/verkada-cp63-e/', + fov_deg: '64 to 2 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + ptz: true, + varifocal: true, + night_vision: { type: 'ir', range_m: 100 }, + environment: ['outdoor'], + ndaa_compliant: true, + }, + { + id: 'verkada-cr63-e', + brand: 'Verkada', + model: 'CR63-E', + type: 'bullet', + url: 'https://www.cctv-database.com/camera/verkada-cr63-e/', + fov_deg: '109 to 49 H', + resolution: { mp: 8.3, w: 3840, h: 2160, label: '4K' }, + varifocal: true, + night_vision: { type: 'ir', range_m: 20 }, + environment: ['indoor', 'outdoor'], + }, + { + id: 'bosch-mic-7522-z30b', + brand: 'Bosch', + model: 'MIC IP starlight 7100i (MIC-7522-Z30B)', + type: 'ptz', + url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/', + aliases: ['MIC-7522-Z30B'], + fov_deg: '2.1-58.3', + // i18n-ignore: datasheet label + resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' }, + ptz: true, + varifocal: true, + night_vision: { type: 'color' }, + environment: ['outdoor'], + ndaa_compliant: true, + }, +]; + +/** + * Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer` + * naming another maker rejects the match, so a "Flock Safety" camera tagged + * "L6Q" stays unresolved rather than borrowing Motorola's specs. + * @param {string|null} model - The OSM `model` tag. + * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. + * @returns {Object|null} The verbatim spec record, or null when unknown. + */ +export const lookupAlprModelSpec = createModelSpecLookup(RECORDS); diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs new file mode 100644 index 0000000000..b33c1d879b --- /dev/null +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -0,0 +1,100 @@ +// src/layers/alpr/modelSpecs.test.mjs +// Mapped ALPR model tags resolve to vendored datasheets, and never guess. +import { test } from 'node:test'; +import assert from 'node:assert/strict'; + +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { normalizeAlprNode } from './records.js'; +import { alprLabelDetails } from './visuals.js'; + +const OSM = { attribution: { name: 'OpenStreetMap' } }; + +test('the model tags mappers write resolve to their datasheet record', () => { + // [model tag, manufacturer tag, record id] as they appear on OSM nodes. + for (const [model, manufacturer, id] of [ + ['L6Q', 'Motorola Solutions', 'motorola-solutions-l6q'], + ['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'], + ['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'], + ['L6Q', null, 'motorola-solutions-l6q'], + ['AutoVu SharpV', 'Genetec', 'genetec-autovu-sharpv'], + ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], + ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], + ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], + ['CB62-TE-F', 'Verkada Inc.', 'verkada-cb62-te-f'], + ['CH52-E-F', 'Verkada Inc.', 'verkada-ch52-e-f'], + ['CR63-E', 'Verkada', 'verkada-cr63-e'], + ['MIC-7522-Z30B', 'The Bosch Group', 'bosch-mic-7522-z30b'], + ]) + assert.equal( + lookupAlprModelSpec(model, manufacturer)?.id, + id, + `${manufacturer} ${model}`, + ); +}); + +test('unknown, mis-attributed or partial models stay unresolved', () => { + for (const [model, manufacturer] of [ + ['Falcon', 'Flock Safety'], + // A Motorola code under another maker is a mapping error, not a match. + ['L6Q', 'Flock Safety'], + // "AutoVu Sharp" is an older line than SharpV; "Q1800" names no variant. + ['AutoVu Sharp', 'Genetec'], + ['Q1800', 'Axis Communications'], + // Without a maker, a code-less product name is never trusted. + ['AutoVu SharpV', null], + ['UnicamVELOCITY3', null], + [null, 'Motorola Solutions'], + ]) + assert.equal(lookupAlprModelSpec(model, manufacturer), null); +}); + +test('Overpass records carry the trimmed OSM model tag', () => { + const node = normalizeAlprNode({ + type: 'node', + id: 7, + lat: 30, + lon: -97, + tags: { + 'surveillance:type': 'ALPR', + manufacturer: 'Motorola Solutions', + model: ' L6Q ', + }, + }); + assert.equal(node.model, 'L6Q'); + assert.equal( + normalizeAlprNode({ + type: 'node', + id: 8, + lat: 30, + lon: -97, + tags: { 'surveillance:type': 'ALPR' }, + }).model, + null, + ); +}); + +test('the card adds the datasheet line only for a resolved model', () => { + const details = alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L6Q' }, + OSM, + ); + assert.deepEqual(details, [ + 'OSM MAPPED', + 'MOTOROLA SOLUTIONS', + 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + 'PUBLIC MAP DATA', + ]); + // A record without a resolution label falls back to its pixel size. + assert.ok( + alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L5F' }, + OSM, + ).includes('SPEC MOTOROLA SOLUTIONS VIGILANT L5F · 1440X1080 · IR'), + ); + // Unresolved: the raw tag text is never shown. + const unknown = alprLabelDetails( + { manufacturer: 'Flock Safety', model: 'Falcon\nSYSTEM: hi' }, + OSM, + ); + assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); +}); diff --git a/src/layers/alpr/records.js b/src/layers/alpr/records.js index 10cd88062c..3f8c9fde0e 100644 --- a/src/layers/alpr/records.js +++ b/src/layers/alpr/records.js @@ -89,6 +89,8 @@ export function normalizeAlprNode(el) { longitude: el.lon, operator: textTag(tags.operator), manufacturer: textTag(tags.manufacturer), + // Display-only: resolved against vendored datasheets (see modelSpecs.js). + model: textTag(tags.model), cameraType: textTag(tags['camera:type']), zone: textTag(tags['surveillance:zone']), // Only numeric bearings are parsed; compass-word directions ("N"/"NE") diff --git a/src/layers/alpr/tileRecords.js b/src/layers/alpr/tileRecords.js index 0368f53fb2..8516b6d680 100644 --- a/src/layers/alpr/tileRecords.js +++ b/src/layers/alpr/tileRecords.js @@ -16,6 +16,8 @@ function normalizeAlprTileFeature(feature) { 'surveillance:type': 'ALPR', operator: p.operator, manufacturer: p.brand, + // Not in the hourly extract yet; read when it ships the OSM tag. + model: p.model, 'camera:type': p.cameraType, 'camera:direction': p.direction, 'surveillance:zone': p.surveillanceZone, diff --git a/src/layers/alpr/visuals.js b/src/layers/alpr/visuals.js index 3a3d3fc5f9..efc2432035 100644 --- a/src/layers/alpr/visuals.js +++ b/src/layers/alpr/visuals.js @@ -1,5 +1,7 @@ import * as Cesium from 'cesium'; import { destinationPointDeg } from './model.js'; +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { specSummary } from '../cctv/modelSpecs.js'; import { DIRECTION_CONE_M, DIRECTION_CONE_HALF_ANGLE_DEG, @@ -42,7 +44,10 @@ export function alprDisplayId(record) { return `ALPR-${String(record.osmId).slice(-4).padStart(4, '0')}`; } -/** Show only supplied metadata, with the actual source named for custom adapters. */ +/** + * Show only supplied metadata, with the actual source named for custom + * adapters, plus the datasheet summary when the mapped model is known. + */ export function alprLabelDetails(record, source) { const sourceName = source.attribution?.name || source.label || 'Camera source'; @@ -63,6 +68,9 @@ export function alprLabelDetails(record, source) { ), ]; if (equipment.length) details.push(equipment.join(' · ')); + // Only a datasheet match is shown: the raw OSM `model` text never is. + const spec = lookupAlprModelSpec(record.model, record.manufacturer); + if (spec) details.push(`SPEC ${specSummary(spec).toUpperCase()}`); if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA'); return details; } diff --git a/src/layers/cctv/modelSpecs.js b/src/layers/cctv/modelSpecs.js index 2d93166a72..128f30d6fd 100644 --- a/src/layers/cctv/modelSpecs.js +++ b/src/layers/cctv/modelSpecs.js @@ -387,33 +387,67 @@ const BRAND_ALIASES = { Hikvision: ['hiwatch'], }; -function brandWords(record) { - return new Set([ - ...words(record.brand), - ...(BRAND_ALIASES[record.brand] || []), - ]); -} - /** - * One entry per record name (model + aliases). `required` is every - * non-generic word of the name — all must appear in a query, so a generation - * or suffix ("Mk II", "7000i" vs "7000") is never dropped. `hasCode` marks - * names carrying a letter+digit model code; names without one ("3950", - * "01959-004", "AUTODOME 800 Series") match only when the brand does. + * Builds a model lookup over a record table, so another layer can resolve its + * own vendored records with the same matching rules (see lookupModelSpec). + * @param {Object[]} records - Spec records in this module's shape. + * @param {Object} [brandAliases] - Extra manufacturer words + * accepted per record brand. + * @returns {(model: string, manufacturer?: string) => (Object|null)} Lookup. */ -const NAME_INDEX = RECORDS.flatMap((record) => { - const brand = brandWords(record); - return [record.model, ...(record.aliases || [])].map((name) => { - const nameWords = words(name); - return { - record, - brand, - allowed: new Set(nameWords), - required: nameWords.filter((word) => !isGeneric(word)), - hasCode: nameWords.some(isModelCode), - }; +export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { + /** + * One entry per record name (model + aliases). `required` is every + * non-generic word of the name — all must appear in a query, so a + * generation or suffix ("Mk II", "7000i" vs "7000") is never dropped. + * `hasCode` marks names carrying a letter+digit model code; names without + * one ("3950", "01959-004", "AUTODOME 800 Series") match only when the + * brand does. + */ + const nameIndex = records.flatMap((record) => { + const brand = new Set([ + ...words(record.brand), + ...(brandAliases[record.brand] || []), + ]); + return [record.model, ...(record.aliases || [])].map((name) => { + const nameWords = words(name); + return { + record, + brand, + allowed: new Set(nameWords), + required: nameWords.filter((word) => !isGeneric(word)), + hasCode: nameWords.some(isModelCode), + }; + }); }); -}); + return (model, manufacturer) => { + const query = words(model).map(stripVariantSuffix); + if (!query.length) return null; + const maker = words(manufacturer); + const found = new Set(); + for (const entry of nameIndex) { + const makerMatches = maker.some((word) => entry.brand.has(word)); + if (maker.length && !makerMatches) continue; + if ( + !entry.hasCode && + !makerMatches && + !query.some((word) => entry.brand.has(word)) + ) + continue; + if (!entry.required.length) continue; + if (!entry.required.every((word) => query.includes(word))) continue; + if ( + !query.every( + (word) => + entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word), + ) + ) + continue; + found.add(entry.record); + } + return found.size === 1 ? [...found][0] : null; + }; +} /** * Looks up a spec record for a hardware-model string. @@ -433,33 +467,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => { * @param {string} [manufacturer] - The source's manufacturer, when published. * @returns {Object|null} The verbatim spec record, or null when unknown. */ -export function lookupModelSpec(model, manufacturer) { - const query = words(model).map(stripVariantSuffix); - if (!query.length) return null; - const maker = words(manufacturer); - const found = new Set(); - for (const entry of NAME_INDEX) { - const makerMatches = maker.some((word) => entry.brand.has(word)); - if (maker.length && !makerMatches) continue; - if ( - !entry.hasCode && - !makerMatches && - !query.some((word) => entry.brand.has(word)) - ) - continue; - if (!entry.required.length) continue; - if (!entry.required.every((word) => query.includes(word))) continue; - if ( - !query.every( - (word) => - entry.allowed.has(word) || entry.brand.has(word) || isGeneric(word), - ) - ) - continue; - found.add(entry.record); - } - return found.size === 1 ? [...found][0] : null; -} +export const lookupModelSpec = createModelSpecLookup(RECORDS); /** * Datasheet horizontal FOV as the range the hardware can cover. Only @@ -539,7 +547,10 @@ export function specFovCapabilityToken( export function specSummary(spec) { if (!spec) return ''; const parts = [`${spec.brand} ${spec.model}`]; - if (spec.resolution?.label) parts.push(spec.resolution.label); + const { label, w, h, mp } = spec.resolution || {}; + if (label) parts.push(label); + else if (w && h) parts.push(`${w}x${h}`); + else if (mp) parts.push(`${mp}MP`); if (spec.night_vision) { parts.push( `${spec.night_vision.type.toUpperCase()}${spec.night_vision.range_m ? ` ${spec.night_vision.range_m}m` : ''}`, From 434fc1b852c9fdeaabca0a47c617dad9d923377a Mon Sep 17 00:00:00 2001 From: bassem chagra Date: Sat, 24 Oct 2026 13:54:35 +0200 Subject: [PATCH 02/56] docs(changelog): add fragment for #1360 --- changelog.d/1360-alpr-model-specs.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 changelog.d/1360-alpr-model-specs.md diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md new file mode 100644 index 0000000000..2e34f02168 --- /dev/null +++ b/changelog.d/1360-alpr-model-specs.md @@ -0,0 +1,5 @@ +- Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware + (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show + a datasheet spec line on their card, from 16 vendored CCTV Camera Database + records; unknown or mis-attributed models show nothing (bassem chagra, + @ch-bas, #1360). From 71d853dff0d98fe76b24c515240dbc73677e22f2 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Tue, 3 Nov 2026 16:26:48 +0000 Subject: [PATCH 03/56] chore: adopt ALPR model spec tests into format scope --- scripts/format-scope.json | 1 + 1 file changed, 1 insertion(+) diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 2852445270..b59bf0e42e 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -579,6 +579,7 @@ "src/data/dataCredits.test.mjs", "src/layers/alpr/index.js", "src/layers/alpr/model.js", + "src/layers/alpr/modelSpecs.test.mjs", "src/layers/alpr/policy.js", "src/layers/alpr/presentation.js", "src/layers/alpr/visuals.js", From 5371f3ee70f936ffcdbf67dc4dfde1efd09fefec Mon Sep 17 00:00:00 2001 From: Kevin Rajan <7121943+kvnloo@users.noreply.github.com> Date: Fri, 13 Nov 2026 03:19:15 -0600 Subject: [PATCH 04/56] fix(alpr): require explicit SharpV G3 before showing G3 specs Address gekh's P2 review of ch-bas's ALPR datasheet feature. Keep the vendored records verbatim, reject generation-ambiguous SharpV model tags, and cover G1/G2/G3 matching and the rendered card with node:test. Update the documented matched-camera count and changelog, preserving original author ch-bas and existing attribution. --- changelog.d/1360-alpr-model-specs.md | 4 ++-- docs/CURRENT-STATE.md | 7 ++++--- src/layers/alpr/modelSpecs.js | 19 ++++++++++++++++--- src/layers/alpr/modelSpecs.test.mjs | 22 +++++++++++++++++++++- 4 files changed, 43 insertions(+), 9 deletions(-) diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md index 2e34f02168..90addb2adb 100644 --- a/changelog.d/1360-alpr-model-specs.md +++ b/changelog.d/1360-alpr-model-specs.md @@ -1,5 +1,5 @@ - Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show a datasheet spec line on their card, from 16 vendored CCTV Camera Database - records; unknown or mis-attributed models show nothing (bassem chagra, - @ch-bas, #1360). + records; unknown, generation-ambiguous or mis-attributed models show nothing + (bassem chagra, @ch-bas, #1360). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index dd5dfab20a..f1f2201e93 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -971,12 +971,13 @@ screen. Cyan camera badges use Manjunath's camera artwork; selection switches to larger coral badge with corner brackets and an animated tactical card. Numeric mapped bearings draw illustrative 90 m direction wedges (not measured coverage). A camera whose OSM `model` tag names known hardware (Motorola Solutions Vigilant, -Genetec AutoVu SharpV, Axis, Verkada, Bosch MIC; 459 of the 1,567 tagged cameras +Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras in October 2026) gets a `SPEC` line on its card from vendored datasheet records (`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's `createModelSpecLookup`). A `manufacturer` naming another maker rejects the -match, and the raw tag text is never shown. The hourly extract has no `model` -field yet, so only an Overpass-backed source fills it. +match, and the raw tag text is never shown. Unversioned `AutoVu SharpV` tags +cannot choose between G1/G2/G3 datasheets and show no specs. The hourly extract +has no `model` field yet, so only an Overpass-backed source fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js index 789b6fc4a5..33314531c1 100644 --- a/src/layers/alpr/modelSpecs.js +++ b/src/layers/alpr/modelSpecs.js @@ -7,8 +7,9 @@ * vendors the records for the models among them that the CCTV Camera Database * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, - * which resolve 459 of those cameras — and resolves a camera's `model` (with - * its `manufacturer`) through the CCTV layer's matcher. The hourly extract the + * which resolve 408 of those cameras (excluding unversioned SharpV tags) — + * and resolves a camera's `model` (with its `manufacturer`) through the CCTV + * layer's matcher. The hourly extract the * layer reads by default does not publish `model` yet, so today only an * Overpass-backed source shows these specs. Flock Safety publishes no * datasheet resolution, so Flock models stay unresolved; an unknown model @@ -254,4 +255,16 @@ const RECORDS = [ * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. * @returns {Object|null} The verbatim spec record, or null when unknown. */ -export const lookupAlprModelSpec = createModelSpecLookup(RECORDS); +const lookupDatasheetSpec = createModelSpecLookup(RECORDS); + +export function lookupAlprModelSpec(model, manufacturer) { + const spec = lookupDatasheetSpec(model, manufacturer); + // The dataset's unversioned SharpV label is tied to G3 hardware, but OSM + // tags may name G1 or G2. Require an explicit G3 or a G3 part number. + if ( + spec?.id === 'genetec-autovu-sharpv' && + !/\bg3\b/i.test(String(model || '')) + ) + return null; + return spec; +} diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs index b33c1d879b..fb6d8fbd49 100644 --- a/src/layers/alpr/modelSpecs.test.mjs +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -16,7 +16,10 @@ test('the model tags mappers write resolve to their datasheet record', () => { ['L5F', 'Motorola Solutions', 'motorola-solutions-l5f'], ['L6D', 'Motorola Solutions', 'motorola-solutions-l6d'], ['L6Q', null, 'motorola-solutions-l6q'], - ['AutoVu SharpV', 'Genetec', 'genetec-autovu-sharpv'], + ['AutoVu SharpV G3', 'Genetec', 'genetec-autovu-sharpv'], + ['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'], + ['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'], + ['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'], ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], @@ -42,6 +45,9 @@ test('unknown, mis-attributed or partial models stay unresolved', () => { ['Q1800', 'Axis Communications'], // Without a maker, a code-less product name is never trusted. ['AutoVu SharpV', null], + ['AutoVu SharpV', 'Genetec'], + ['AutoVu SharpV HD', 'Genetec'], + ['Genetec AutoVu SharpV', 'Genetec'], ['UnicamVELOCITY3', null], [null, 'Motorola Solutions'], ]) @@ -98,3 +104,17 @@ test('the card adds the datasheet line only for a resolved model', () => { ); assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); }); + +test('unversioned SharpV does not display G3 specs on an ALPR card', () => { + const ambiguous = alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV' }, + OSM, + ); + assert.deepEqual(ambiguous, ['OSM MAPPED', 'GENETEC', 'PUBLIC MAP DATA']); + + const g3 = alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, + OSM, + ); + assert.ok(g3.includes('SPEC GENETEC AUTOVU SHARPV · 1920X1200 · IR')); +}); From 607796737cc377f315fb4fe939fcf60d17466ced Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 14:26:37 +0400 Subject: [PATCH 05/56] 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. --- docs/CURRENT-STATE.md | 20 +- scripts/format-scope.json | 2 + scripts/package-boundaries.json | 6 + src/data/cctvCellCounts.js | 161 ++++++++ src/data/cctvCellCounts.test.mjs | 49 +++ src/data/cctvViewThinning.test.mjs | 418 ++++++++++++++++++-- src/layers/cctv/cards.js | 2 +- src/layers/cctv/countMarkers.js | 120 ++++++ src/layers/cctv/lifecycle.js | 4 + src/layers/cctv/navigation.js | 27 +- src/layers/cctv/policy.js | 9 + src/layers/cctv/presentation.js | 2 +- src/layers/cctv/rendering.js | 130 ++++-- src/layers/cctv/rendering.test.mjs | 6 + src/layers/cctv/selection.js | 8 +- src/layers/cctv/selection.test.mjs | 43 ++ src/layers/cctv/state.js | 4 + src/layers/cctv/testing.js | 8 + src/render/cesium/screenModulation.js | 7 + src/render/cesium/screenModulation.test.mjs | 16 + 20 files changed, 965 insertions(+), 77 deletions(-) create mode 100644 src/data/cctvCellCounts.js create mode 100644 src/data/cctvCellCounts.test.mjs create mode 100644 src/layers/cctv/countMarkers.js diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5a2114a0b8..5d3441608c 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1952,14 +1952,18 @@ directory. Every `/api/cctv` route refuses cross-site browser requests but accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. -The CCTV layer draws only the cameras on or near the screen. Zoomed out, it -keeps one camera per ground cell sized to the view, preferring a healthy feed, -and the cells are anchored to the ground so a pan keeps the same cameras. The -active camera always shows. Ground placement and coverage geometry load only -for the cameras in view, with at most two attempts per camera and view regime. -The view pass reruns while the camera moves, paced by its own cost. The camera -picker lists the cameras in view, active camera first, and closes with the -count of cameras outside the view. +The CCTV layer draws only the cameras on or near the screen. Zoomed out, a +ground cell containing multiple cameras shows a cyan count at their centre. +The count includes cameras beyond the screen edge and excludes cameras beyond +the horizon. Counts that would overlap on screen merge into one that carries +their sum. Clicking a count zooms to its group. Single cameras keep their icons, +and the active camera has its own icon and is excluded from the count. Close +up, even co-located cameras show individually. Ambient cards and coverage +attach to individual cameras. Ground placement has at most two attempts per +camera and view regime. The view pass reruns while the camera moves, paced by +its own cost. The camera picker lists the active camera first, keeps one +representative per visible cell, preferring healthy feeds, and closes with +the count of cameras outside the view. Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 76d86f698d..429862c7c7 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -625,6 +625,8 @@ "src/layers/cctv/health.js", "src/data/cctv.js", "src/data/cctvCatalogCap.test.mjs", + "src/data/cctvCellCounts.test.mjs", + "src/data/cctvViewThinning.test.mjs", "src/data/cctvDisplayCode.test.mjs", "src/data/cctvFootprint.js", "src/data/cctvGroundHeights.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a5a719033b..93ccb828cb 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3282,6 +3282,8 @@ "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/iconOrientation.js", "src/data/screenRotation.js", @@ -4233,6 +4235,8 @@ "src/data/cctvFootprint.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/cockpitAirLod.js", "src/data/cockpitContactDot.js", @@ -5559,6 +5563,8 @@ "src/data/cctvFootprint.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cctvCellCounts.js", + "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", "src/data/cockpitAirLod.js", "src/data/cockpitContactDot.js", diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js new file mode 100644 index 0000000000..8c4c7a226b --- /dev/null +++ b/src/data/cctvCellCounts.js @@ -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; +} diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs new file mode 100644 index 0000000000..bfa421bd91 --- /dev/null +++ b/src/data/cctvCellCounts.test.mjs @@ -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, + ); + } +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index bf5a3edf5b..1820ee8050 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -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], + ); +}); diff --git a/src/layers/cctv/cards.js b/src/layers/cctv/cards.js index 203d64e400..ad95d085a5 100644 --- a/src/layers/cctv/cards.js +++ b/src/layers/cctv/cards.js @@ -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, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js new file mode 100644 index 0000000000..8ebdba5142 --- /dev/null +++ b/src/layers/cctv/countMarkers.js @@ -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 }; +} diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index 233a2b38e7..b20592d396 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -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(); }, diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index eaa9a888fc..8e69d9e5e8 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -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, diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index ee7e1baf44..e728d5707d 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -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. diff --git a/src/layers/cctv/presentation.js b/src/layers/cctv/presentation.js index f23c007334..ed8a715ebd 100644 --- a/src/layers/cctv/presentation.js +++ b/src/layers/cctv/presentation.js @@ -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; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index b0e964c1be..7dc1c2f956 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -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'; diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 00bdb33397..8092ec0557 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -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(); diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 5676c045bc..a1f9683847 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -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. diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 92ee536706..34d18271da 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -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(); + } +}); diff --git a/src/layers/cctv/state.js b/src/layers/cctv/state.js index d33453873c..a6778de8f3 100644 --- a/src/layers/cctv/state.js +++ b/src/layers/cctv/state.js @@ -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 diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index 3a024f7767..65afc5cb61 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -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, diff --git a/src/render/cesium/screenModulation.js b/src/render/cesium/screenModulation.js index 45c2c4bffa..53fee1bca5 100644 --- a/src/render/cesium/screenModulation.js +++ b/src/render/cesium/screenModulation.js @@ -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 diff --git a/src/render/cesium/screenModulation.test.mjs b/src/render/cesium/screenModulation.test.mjs index 62927bbe2d..c88c74b3e2 100644 --- a/src/render/cesium/screenModulation.test.mjs +++ b/src/render/cesium/screenModulation.test.mjs @@ -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(); + } +}); From 87bff9957b8d05442a24af034e8bff5bd5b3bd50 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:02:07 +0400 Subject: [PATCH 06/56] fix(cctv): draw the count marker's ring cleanly The ring was three texture pixels wide and touched the sprite edge, so at screen size it came out one jagged pixel wide with a clipped top and bottom, and the sharpen pass pushed it towards white with an orange fringe over bright ground. Draw it two screen pixels wide, inset from the sprite edge so its outer edge antialiases, with a dark rim outside it. Labels of up to three digits always stay in a circle; longer ones get a pill with room for its rounded ends. --- src/layers/cctv/countMarkers.js | 27 +++++++++++++++++++++++---- 1 file changed, 23 insertions(+), 4 deletions(-) diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 8ebdba5142..6577c2904a 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -24,15 +24,34 @@ export function createCountMarkers(set) { const canvas = document.createElement('canvas'); const size = COUNT_MARKER_PX * 2; const ctx = canvas.getContext('2d'); - const font = 'bold 26px sans-serif'; + const font = 'bold 24px sans-serif'; ctx.font = font; - canvas.width = Math.max(size, Math.ceil(ctx.measureText(text).width) + 24); + // A two-pixel ring survives the halving to screen size, and the clear + // margin leaves its outer edge room to antialias inside the sprite. + const ring = 4; + const margin = 4; + const inset = margin + ring / 2; + // Up to three digits sit inside the circle; a longer label gets a pill + // with room for its rounded ends. + const textWidth = Math.ceil(ctx.measureText(text).width); + const fitsCircle = textWidth <= size - 2 * (margin + ring) - 4; + canvas.width = fitsCircle ? size : textWidth + 2 * (margin + ring + 12); canvas.height = size; ctx.beginPath(); - ctx.roundRect(2, 2, canvas.width - 4, size - 4, size / 2 - 2); + ctx.roundRect( + inset, + inset, + canvas.width - 2 * inset, + size - 2 * inset, + size / 2 - inset, + ); + // A dark rim outside the ring keeps it off bright ground. + ctx.lineWidth = ring + 4; + ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; + ctx.stroke(); ctx.fillStyle = '#0e1720'; ctx.fill(); - ctx.lineWidth = 3; + ctx.lineWidth = ring; ctx.strokeStyle = '#75e7ff'; ctx.stroke(); ctx.fillStyle = ctx.strokeStyle; From aabfa5e08494a78742e73f281d9dd77e687aec54 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 15:31:20 +0400 Subject: [PATCH 07/56] fix(cctv): paint count markers on the world overlay canvas The scene renders at CSS resolution and is stretched on a high-density display, so a count marker drawn as a scene sprite looked coarse next to the camera callouts, which the world overlay paints at device density. Paint the markers through the overlay's custom paint lane instead, in the callouts' typeface. Each paint reprojects the group centres; a click is resolved against the rectangles painted in the last frame and still zooms to the group without choosing a camera. A marker that would cover HUD chrome is skipped, as overlay entries are. With no aggregate sprites left, the contact sweep no longer needs to skip them, so that exclusion is removed. --- docs/CURRENT-STATE.md | 3 +- src/data/cctvViewThinning.test.mjs | 341 +++++++++++++++----- src/layers/cctv/countMarkers.js | 287 ++++++++++------ src/layers/cctv/rendering.js | 79 +++-- src/layers/cctv/rendering.test.mjs | 62 +++- src/layers/cctv/selection.js | 3 +- src/layers/cctv/selection.test.mjs | 12 +- src/layers/cctv/testing.js | 14 +- src/overlays/worldOverlay.js | 3 + src/overlays/worldOverlay.test.mjs | 5 + src/render/cesium/screenModulation.js | 7 - src/render/cesium/screenModulation.test.mjs | 16 - 12 files changed, 583 insertions(+), 249 deletions(-) diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 5d3441608c..f79aa705fd 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,7 +1953,8 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows a cyan count at their centre. +ground cell containing multiple cameras shows a cyan count at their centre, +drawn on the world overlay at the same resolution as camera callouts. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 1820ee8050..ac134670e8 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -10,7 +10,6 @@ import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, - _extractPickedCameraIdForTest, bindCctvWorldClickGesture, applyCctvFocusDeemphasis, reopenNearestCamera, @@ -90,27 +89,113 @@ function viewerAt(heightM, lonDeg = 0, flights = []) { /** The renderers bound for the running test, let go when it ends. */ const bindings = []; -const paintedLabels = new Map(); +let painter; +let paintRequests; +let measured; +let glyphWidth; +let ctx; +const fonts = new EventTarget(); + +function seedCoverage(options) { + _setCctvCoverageStateForTest({ + ...options, + registerPaintLane(_lane, paint) { + painter = paint; + return { + requestPaint() { + paintRequests++; + }, + setActive() {}, + unregister() {}, + }; + }, + }); +} + beforeEach(() => { + paintRequests = 0; + measured = 0; + glyphWidth = 8; globalThis.document = { + fonts, createElement: () => ({ getContext: () => ({ - beginPath() {}, - arc() {}, - roundRect() {}, - measureText: (text) => ({ width: text.length * 15 }), - fill() {}, - stroke() {}, - fillText(text, x, y, maxWidth) { - paintedLabels.set(text, maxWidth ?? Infinity); + measureText(text) { + measured++; + return { width: text.length * glyphWidth }; }, }), }), }; + let savedState; + ctx = { + font: 'initial', + globalAlpha: 1, + fillStyle: 'initial', + strokeStyle: 'initial', + textAlign: 'start', + textBaseline: 'top', + lineWidth: 1, + labels: [], + shapes: [], + save() { + savedState = { ...this }; + }, + restore() { + Object.assign(this, savedState); + }, + beginPath() {}, + fill() {}, + stroke() {}, + roundRect(...args) { + this.shapes.push(args); + }, + fillText(text, x, y) { + this.labels.push({ + text, + x, + y, + alpha: this.globalAlpha, + font: this.font, + }); + }, + }; }); +/** Reproject on each paint in CSS pixels, as the host does. */ +function paint(overrides = {}) { + ctx.labels.length = ctx.shapes.length = 0; + painter({ + ctx, + width: WIDTH, + height: HEIGHT, + dpr: 2, + viewProjectionMatrix: new Float64Array([ + 0, + 0, + 0, + 0, + 2 / (30 * WIDTH), + 0, + 0, + 0, + 0, + 2 / (30 * HEIGHT), + 0, + 0, + 0, + 0, + 0, + 1, + ]), + occluder: { isPointVisible: () => true }, + overlapsHardUi: () => false, + ...overrides, + }); + return ctx.labels; +} + afterEach(() => { - paintedLabels.clear(); delete globalThis.document; for (const unbind of bindings.splice(0)) unbind(); }); @@ -131,36 +216,38 @@ const CLUSTER = [ [0.2, 0], ]; -/** Count billboards the layer currently shows. */ +/** Groups from the latest view pass. */ function markers() { - const book = cctvLayer._cctvDrawnForTest().counts; - return book.show - ? book - .ids() - .map(book.item) - .filter((item) => item.show) - : []; + return cctvLayer._cctvDrawnForTest().counts.markers; } -/** Send a clean count-marker click through the layer's world click handler. */ +/** Click the CSS position of the painted count with a camera underneath it. */ 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'); + const { x, y } = paint().find((label) => label.text === marker.text); + const hit = { set: _cctvIconsForTest().setId, id: 'cam-0' }; + let fallback; + const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, (event) => { + fallback = event.drawHit; }); - click({ drawHit: hit, gesture: { travelPx: 0, durationMs: 20 } }); + const gesture = { travelPx: 0, durationMs: 20 }; + click({ drawHit: hit, screenPosition: { x, y }, gesture }); + assert.equal(fallback, undefined); + click({ + drawHit: hit, + screenPosition: { x: x + marker.width / 2 + 1, y }, + gesture, + }); + assert.equal(fallback, hit); } test('a crowded cell shows its count and a singleton keeps its icon', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ 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), + markers().map((item) => item.cell.count), [3], ); assert.deepEqual( @@ -171,7 +258,7 @@ test('a crowded cell shows its count and a singleton keeps its icon', () => { test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, }); @@ -180,7 +267,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => 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]) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, shiftM / 111_320), records, }); @@ -191,7 +278,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => `pan by ${shiftM} m`, ); } - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); @@ -200,7 +287,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () => test('a small zoom within one cell size keeps the same winners', () => { const { records } = recordsAt(CLUSTER); const shownAt = (heightM) => { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(heightM), records, }); @@ -217,7 +304,7 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( // Whichever camera the id order would pick, the healthy one must win. let first; for (const id of ['cam-0', 'cam-1']) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, healthById: new Map([[id, { status: 'ok' }]]), @@ -239,14 +326,14 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( test('the active camera always shows, even in a crowded cell', () => { const { records } = recordsAt(CLUSTER.slice(0, 3)); for (const active of records) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, activeCameraId: active.camera.id, }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [2], ); const icons = _cctvIconsForTest(); @@ -264,7 +351,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () => [0.0001, 0], [0.01, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, }); @@ -274,7 +361,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () => test('a disabled layer skips the view pass', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000), records, enabled: false, @@ -285,7 +372,7 @@ test('a disabled layer skips the view pass', () => { test('UI state builds the full camera list only when it is read', () => { const { records } = recordsAt(CLUSTER.slice(0, 2)); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, }); @@ -322,7 +409,7 @@ test('the camera picker lists the view, with the active camera first', () => { [0.01, 0], [0.0002, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(300), records, activeCameraId: 'cam-1', @@ -344,10 +431,10 @@ test('panning a cell across the padded screen edge keeps its full count', () => [0.29, 0], ]); for (const lon of [0.015, 0]) { - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000, lon), records }); + seedCoverage({ viewer: viewerAt(20_000, lon), records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [3], ); if (lon === 0) @@ -377,10 +464,10 @@ test('only members on the near side of the horizon count', () => { query: { project: () => ({ x: 400, y: 300 }) }, }), ); - _setCctvCoverageStateForTest({ viewer, records }); + seedCoverage({ viewer, records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((item) => item.meta.count), + markers().map((item) => item.cell.count), [2], ); }); @@ -390,7 +477,7 @@ test('co-located cameras separate below the minimum cell size', () => { [0, 0], [0, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(300), records }); + seedCoverage({ viewer: viewerAt(300), records }); refreshHorizonCulling(); assert.deepEqual(shownIds(records), ['cam-0', 'cam-1']); assert.deepEqual(markers(), []); @@ -404,7 +491,7 @@ test('a count click frames its members and preserves an explicit camera choice', [spread, 0], [0.2, 0], ]); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, 0, flights), records, activeCameraId: 'cam-2', @@ -430,7 +517,7 @@ test('a count click frames its members and preserves an explicit camera choice', ); assert.equal(reopenNearestCamera(), false); assert.equal(cctvLayer.getUIState().activeCameraId, 'cam-2'); - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: destination, records, activeCameraId: 'cam-2', @@ -443,11 +530,13 @@ test('a count click frames its members and preserves an explicit camera choice', test('disabling the layer hides its counts', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.equal(markers().length, 1); + const [label] = paint(); cctvLayer.disable(); - assert.deepEqual(markers(), []); + assert.deepEqual(paint(), []); + assert.equal(cctvLayer._cctvDrawnForTest().counts.pickedCell(label), null); }); test('coverage leaves grouped neighbors and returns when their icons separate', () => { @@ -459,7 +548,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', // 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' }); + seedCoverage({ viewer, records, activeCameraId: 'cam-0' }); refreshCoverageStyles(); refreshHorizonCulling(); assert.deepEqual( @@ -478,7 +567,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', test('count markers share the camera focus fade and recover on release', () => { const { records } = recordsAt(CLUSTER); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); const target = { screenRect: { left: 40, top: 40, right: 60, bottom: 60 }, @@ -499,10 +588,10 @@ test('count markers share the camera focus fade and recover on release', () => { }; tick(0, target); tick(params.attackMs + 1, target); - assert.equal(markers()[0].focus, params.dimFloor); + assert.equal(paint()[0].alpha, params.dimFloor); tick(params.attackMs + 2, null); tick(params.attackMs + params.releaseMs + 3, null); - assert.equal(markers()[0].focus, 1); + assert.equal(paint()[0].alpha, 1); }); test('overlapping cells merge at their weighted centre and keep every camera in the flight bounds', () => { @@ -524,7 +613,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in [0, records], [0.003, [...records].reverse()], ]) { - _setCctvCoverageStateForTest({ + seedCoverage({ viewer: viewerAt(20_000, pan, flights), records: order, activeCameraId: 'cam-7', @@ -534,21 +623,21 @@ test('overlapping cells merge at their weighted centre and keep every camera in const shown = markers(); assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']); assert.equal( - shown.reduce((sum, m) => sum + m.meta.count, 0), + shown.reduce((sum, m) => sum + m.cell.count, 0), 7, ); assert.deepEqual( - shown.map((m) => m.meta.count).sort((a, b) => a - b), + shown.map((m) => m.cell.count).sort((a, b) => a - b), [2, 5], ); - const merged = shown.find((m) => m.meta.count === 5); + const merged = shown.find((m) => m.cell.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]); + const positions = shown.map((m) => [m.cell.key, m.pos]); if (previous) assert.deepEqual(positions, previous); previous = positions; clickMarker(merged); @@ -569,7 +658,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in } }); -test('long localized labels use their measured width on the canvas and billboard', () => { +test('the overlay paints short counts as circles and long localized labels as pills', () => { const locale = getLocale(); try { setLocale('ru'); @@ -578,25 +667,38 @@ test('long localized labels use their measured width on the canvas and billboard [0.06, 0], [0.06, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ 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 short = markers().find((m) => m.cell.count === 2); + const long = markers().find((m) => m.cell.count === 1300); + const measurements = measured; + assert.equal(measurements, 1); + const labels = paint(); + refreshHorizonCulling(); + assert.equal(measured, measurements); 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', - ); + assert.equal(labels.length, 2); + assert.equal(ctx.shapes.length, labels.length); + const [sx, sy, sw, sh] = + ctx.shapes[labels.findIndex((l) => l.text === '2')]; + const [lx, ly, lw, lh] = + ctx.shapes[labels.findIndex((l) => l.text === text)]; + assert.equal(sw, sh); + assert.ok(lw > text.length * glyphWidth); + assert.equal(lh, sh); + // The four-pixel outer stroke extends two pixels on each side of the path. + assert.equal(sw + 4, short.width); + assert.equal(lw + 4, long.width); + assert.equal(sy + sh / 2, HEIGHT / 2); + assert.equal(ly + lh / 2, HEIGHT / 2); + assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); + assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); + assert.match(labels[0].font, /JetBrains Mono/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); + assert.equal(ctx.lineWidth, 1); } finally { setLocale(locale); } @@ -613,9 +715,9 @@ test('a wider localized pill merges a horizontal neighbor beyond the circle diam [0.008, 0], [0.008, 0], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - return markers().map((m) => m.meta.count); + return markers().map((m) => m.cell.count); }; assert.deepEqual(at(2), [2, 2]); assert.deepEqual(at(1300), [1302]); @@ -635,10 +737,95 @@ test('a merged centre can pick up a third count marker', () => { [0, -0.0126], [0, -0.0126], ]); - _setCctvCoverageStateForTest({ viewer: viewerAt(20_000), records }); + seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); assert.deepEqual( - markers().map((m) => m.meta.count), + markers().map((m) => m.cell.count), [6], ); }); + +test('each paint follows the overlay projection, horizon and hard HUD exclusions', () => { + const { records } = recordsAt([ + [-0.001, 0], + [-0.001, 0], + [0.001, 0], + [0.001, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const counts = cctvLayer._cctvDrawnForTest().counts; + assert.ok(paintRequests > 0); + const requests = paintRequests; + const widths = measured; + assert.deepEqual( + paint().map(({ text, x, y }) => [text, x, y]), + [['4', 400, 300]], + ); + const first = { x: 400, y: 300 }; + assert.equal(counts.pickedCell(first).count, 4); + const at = (x) => { + const matrix = new Float64Array(16); + matrix[12] = (2 * x) / WIDTH - 1; + matrix[15] = 1; + return { viewProjectionMatrix: matrix }; + }; + assert.equal(paint(at(100))[0].x, 100); + assert.equal(counts.pickedCell(first), null); + assert.deepEqual(paint(at(-100)), []); + assert.deepEqual(paint({ occluder: { isPointVisible: () => false } }), []); + assert.deepEqual(paint({ overlapsHardUi: () => true }), []); + assert.equal(counts.pickedCell(first), null); + refreshHorizonCulling(); + assert.equal(measured, widths); + assert.equal(paintRequests, requests); +}); + +test('loaded font metrics remerge visible cells without waiting for a move', () => { + const locale = getLocale(); + try { + setLocale('ru'); + glyphWidth = 3; + const { records } = recordsAt([ + ...Array(1300).fill([-0.009, 0]), + [0.009, 0], + [0.009, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.equal(markers().length, 2); + glyphWidth = 12; + fonts.dispatchEvent(new Event('loadingdone')); + assert.deepEqual( + markers().map((m) => m.cell.count), + [1302], + ); + assert.equal(paint().length, 1); + } finally { + setLocale(locale); + } +}); + +test('hits follow paint order and keep the last painted group until the overlay clears', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + [0.05, 0], + [0.05, 0], + [0.05, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const point = { x: WIDTH / 2, y: HEIGHT / 2 }; + const matrix = new Float64Array(16); + matrix[15] = 1; + const labels = paint({ viewProjectionMatrix: matrix }); + const counts = cctvLayer._cctvDrawnForTest().counts; + assert.equal(labels.length, 2); + const top = counts.pickedCell(point); + assert.equal(String(top.count), labels.at(-1).text); + counts.update([], () => null); + assert.equal(counts.pickedCell(point), top); + assert.deepEqual(paint(), []); + assert.equal(counts.pickedCell(point), null); +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 6577c2904a..740519b132 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -1,80 +1,62 @@ -import { createIconBook } from '../../render/motion/iconBook.js'; import { cellCenter, formatCameraCount, mergeCountCells, } from '../../data/cctvCellCounts.js'; -import { getLocale } from '../../i18n/index.js'; +import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.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; +const FONT = WORLD_OVERLAY_STYLE.fontTitle; +const RING = '#75e7ff'; - /** 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 24px sans-serif'; - ctx.font = font; - // A two-pixel ring survives the halving to screen size, and the clear - // margin leaves its outer edge room to antialias inside the sprite. - const ring = 4; - const margin = 4; - const inset = margin + ring / 2; - // Up to three digits sit inside the circle; a longer label gets a pill - // with room for its rounded ends. - const textWidth = Math.ceil(ctx.measureText(text).width); - const fitsCircle = textWidth <= size - 2 * (margin + ring) - 4; - canvas.width = fitsCircle ? size : textWidth + 2 * (margin + ring + 12); - canvas.height = size; - ctx.beginPath(); - ctx.roundRect( - inset, - inset, - canvas.width - 2 * inset, - size - 2 * inset, - size / 2 - inset, - ); - // A dark rim outside the ring keeps it off bright ground. - ctx.lineWidth = ring + 4; - ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; - ctx.stroke(); - ctx.fillStyle = '#0e1720'; - ctx.fill(); - ctx.lineWidth = ring; - 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; +/** Merged camera groups and their last painted hit rectangles in CSS pixels. */ +export function createCountMarkers(registerPaintLane, id, refreshView) { + const markers = []; + const hits = []; + const widths = new Map(); + const fonts = globalThis.document?.fonts; + let measureCtx; + let hitCount = 0; + const lane = registerPaintLane?.('ambient-label', paint, { + id, + active: false, + target: 'shared', + }); + fonts?.addEventListener?.('loadingdone', fontsLoaded); + + /** Font changes can widen a pill enough to merge it with its neighbor. */ + function fontsLoaded() { + widths.clear(); + if (!markers.length) return; + refreshView(); + lane?.requestPaint(); } - /** Reuse the first slots for visible cells and hide the unused tail. */ + /** Short labels fit the circle. A longer label leaves room for rounded ends. */ + function widthForText(text) { + if (text.length <= 3) return COUNT_MARKER_PX; + let width = widths.get(text); + if (width === undefined) { + measureCtx ??= document.createElement('canvas').getContext('2d'); + measureCtx.font = FONT; + width = Math.max( + COUNT_MARKER_PX + 1, + Math.ceil(measureCtx.measureText(text).width) + 20, + ); + widths.set(text, width); + } + return width; + } + + /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ 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; @@ -83,57 +65,160 @@ export function createCountMarkers(set) { const merged = mergeCountCells( visible, project, - widthFor, + (count) => widthForText(formatCameraCount(count)), 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. + let changed = visible.length !== markers.length; + for (let i = 0; i < visible.length; i++) { + const cell = visible[i]; + const marker = markers[i] ?? (markers[i] = { focus: 1 }); + const last = marker.cell; + const text = formatCameraCount(cell.count); + const width = widthForText(text); if ( - nextLocale === locale && - last?.count === cell.count && - last.lonSum === cell.lonSum && - last.latSum === cell.latSum && - last.heightSum === cell.heightSum + !last || + last.count !== cell.count || + last.latSum !== cell.latSum || + last.lonSum !== cell.lonSum || + last.heightSum !== cell.heightSum + ) { + marker.pos = cellCenter(cell); + changed = true; + } else if ( + last.west !== cell.west || + last.east !== cell.east || + last.south !== cell.south || + last.north !== cell.north || + last.low !== cell.low || + last.high !== cell.high + ) { + changed = true; + } + changed ||= text !== marker.text || width !== marker.width; + marker.cell = cell; + marker.text = text; + marker.width = width; + // Paint never grows the hit buffer, even when a pan reveals every group. + hits[i] ??= {}; + } + markers.length = visible.length; + // Keep the last frame pickable until the host clears its pixels. + lane?.setActive(markers.length > 0 || hitCount > 0); + if (changed) lane?.requestPaint(); + } + + /** Draw at device density using the host's CSS-pixel transform and projection. */ + function paint(frame) { + if (!markers.length) { + // Deactivating invalidates the host, so finish the shared frame first. + if (hitCount) queueMicrotask(deactivateIfEmpty); + hitCount = 0; + return; + } + hitCount = 0; + const { ctx, occluder, viewProjectionMatrix: m } = frame; + const height = COUNT_MARKER_PX; + ctx.save(); + try { + ctx.font = FONT; + ctx.textAlign = 'center'; + ctx.textBaseline = 'middle'; + for (let i = 0; i < markers.length; i++) { + const marker = markers[i]; + const { x: px, y: py, z: pz } = marker.pos; + const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; + if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) + continue; + const x = + (0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) * + frame.width; + const y = + (0.5 - (0.5 * (m[1] * px + m[5] * py + m[9] * pz + m[13])) / w) * + frame.height; + const rect = hits[hitCount]; + rect.x = x - marker.width / 2; + rect.y = y - height / 2; + rect.w = marker.width; + rect.h = height; + if ( + rect.x >= frame.width || + rect.y >= frame.height || + rect.x + rect.w <= 0 || + rect.y + rect.h <= 0 || + frame.overlapsHardUi(rect) + ) + continue; + ctx.globalAlpha = marker.focus; + ctx.beginPath(); + ctx.roundRect( + rect.x + 2, + rect.y + 2, + rect.w - 4, + height - 4, + height / 2 - 2, + ); + ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; + ctx.lineWidth = 4; + ctx.stroke(); + ctx.fillStyle = '#0e1720'; + ctx.fill(); + ctx.strokeStyle = RING; + ctx.lineWidth = 2; + ctx.stroke(); + ctx.fillStyle = RING; + ctx.fillText(marker.text, x, y); + rect.cell = marker.cell; + hitCount++; + } + } finally { + ctx.restore(); + } + } + + /** Resolve the topmost group actually painted at this screen position. */ + function pickedCell(point) { + if (!point) return null; + for (let i = hitCount - 1; i >= 0; i--) { + const rect = hits[i]; + if ( + point.x >= rect.x && + point.x <= rect.x + rect.w && + point.y >= rect.y && + point.y <= rect.y + rect.h ) - 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, - }); + return rect.cell; } - 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; + return null; } - /** 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; + + /** A new group may already have arrived since the empty frame. */ + function deactivateIfEmpty() { + if (!markers.length) lane?.setActive(false); } - return { book, update, pickedCell }; + + /** Release the visible groups and clear their hit targets immediately. */ + function hide() { + markers.length = hits.length = hitCount = 0; + lane?.setActive(false); + } + + /** Unhook this viewer's painter and its font listener. */ + function dispose() { + markers.length = hits.length = hitCount = 0; + fonts?.removeEventListener?.('loadingdone', fontsLoaded); + lane?.unregister(); + } + + return { + markers, + update, + pickedCell, + hide, + dispose, + requestPaint: () => lane?.requestPaint(), + }; } diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 7dc1c2f956..d041a1c681 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -13,6 +13,7 @@ import { IDLE_COVERAGE_EDGE_MUTED, ACTIVE_COVERAGE_EDGE_DEPTHFAIL, IDLE_COVERAGE_COLOR, + COUNT_MARKER_PX, VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, @@ -142,12 +143,9 @@ export function createRendering({ 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, - }), + services.overlays?.registerWorldOverlayPaintLane, + `cctv:${iconSets}:counts`, + refreshHorizonCulling, ); return set.id; } @@ -156,7 +154,7 @@ export function createRendering({ function destroyCameraIcons() { layerState._icons?.dispose(); layerState._icons = null; - layerState._counts?.book.dispose(); + layerState._counts?.dispose(); layerState._counts = null; } @@ -288,38 +286,52 @@ export function createRendering({ let writes = 0; let transitioning = false; let activeCount = 0; - /** 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, { - // Keep hidden icons in the state/release pass so the active count cannot - // drop while a stale dim alpha remains waiting to reappear. - screenPosition: - item.show === false || !position ? null : screenPositionFor(position), + /** A changed focus factor for a camera icon or a painted count. */ + function changedFocus(owner, position, shown, width, height, current) { + const focus = advanceSpriteFocus(owner, { + screenPosition: shown && position ? screenPositionFor(position) : null, cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, target, params, - spriteHalfWidthPx: item.size[0] * scale * 0.5, - spriteHalfHeightPx: item.size[1] * scale * 0.5, + spriteHalfWidthPx: width / 2, + spriteHalfHeightPx: height / 2, }); transitioning ||= focus.transitioning; - 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(book.focus(id), focus.factor, params)) { - book.setFocus(id, focus.factor); - writes += 1; - } + if (focus.active) activeCount++; + if (!focusAlphaNeedsWrite(current, focus.factor, params)) return null; + writes++; + return focus.factor; } - 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); + for (const record of records || []) { + const id = record.camera?.id; + const item = icons?.item(id); + if (!item) continue; + const scale = item.scale ?? 1; + const factor = changedFocus( + item.meta, + record.position, + item.show !== false, + item.size[0] * scale, + item.size[1] * scale, + icons.focus(id), + ); + if (factor !== null) icons.setFocus(id, factor); + } + const counts = layerState._counts; + const iconWrites = writes; + for (const marker of counts?.markers ?? []) { + const factor = changedFocus( + marker, + marker.pos, + true, + marker.width, + COUNT_MARKER_PX, + marker.focus, + ); + if (factor !== null) marker.focus = factor; + } + if (writes > iconWrites) counts.requestPaint(); return { writes, transitioning, activeCount, ran: true }; } @@ -567,7 +579,7 @@ export function createRendering({ ); parts.projection.clearProjectionOverlay(); if (layerState._icons) layerState._icons.show = false; - if (layerState._counts) layerState._counts.book.show = false; + layerState._counts?.hide(); parts.projection.pauseInactiveProjectionFeeds(null); } @@ -911,6 +923,7 @@ export function createRendering({ * @returns {string|null} */ function pickCameraIdAt(position) { + if (layerState._counts?.pickedCell(position)) return null; let hit = null; try { hit = findQuery(layerState._viewer)?.pick(position.x, position.y) ?? null; diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 8092ec0557..aa53c5ab0c 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -120,28 +120,46 @@ test('the icons go with the viewer that drew them, whichever tears down', () => const one = bindFakeDraw(first); const two = bindFakeDraw(second); const state = { _viewer: first }; + const lanes = []; + const overlays = { + registerWorldOverlayPaintLane(name, paint, options) { + const lane = { + name, + paint, + options, + unregister() { + this.disposed = true; + }, + }; + lanes.push(lane); + return lane; + }, + }; const { createCameraIcons, destroyCameraIcons } = createRendering({ state, - services: { focus: {} }, + services: { focus: {}, overlays }, parts: {}, source: {}, }); try { const old = createCameraIcons(first); - const oldCounts = state._counts.book.setId; + assert.equal(one.draw.sets.size, 1); + assert.equal(lanes[0].name, 'ambient-label'); + assert.equal(lanes[0].options.target, 'shared'); + assert.equal(lanes[0].options.active, false); 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); + assert.equal(lanes[0].disposed, true); + lanes[0].paint({}); destroyCameraIcons(); assert.equal(two.draw.sets.get(current).disposed, true); assert.equal(state._icons, null); - assert.equal(counts.disposed, true); + assert.equal(lanes[1].disposed, true); + lanes[1].paint({}); assert.equal(state._counts, null); } finally { one.unbind(); @@ -382,3 +400,35 @@ test('a pose with no perspective field of view is projected by the renderer', () unbind(); } }); + +test('hover picks the underlying camera only outside a painted count', () => { + const viewer = {}; + const icon = { set: 'icons', id: 'camera' }; + let picks = 0; + const unbind = bindRenderer(viewer, { + query: { + pick() { + picks++; + return icon; + }, + }, + }); + try { + const state = { + _viewer: viewer, + _counts: { pickedCell: ({ x }) => (x <= 17 ? {} : null) }, + _icons: { setId: icon.set, has: () => true }, + _recordById: new Map([[icon.id, {}]]), + }; + const rendering = createRendering({ + state, + services: { focus: {} }, + parts: {}, + }); + assert.equal(rendering.pickCameraIdAt({ x: 17, y: 0 }), null); + assert.equal(picks, 0); + assert.equal(rendering.pickCameraIdAt({ x: 18, y: 0 }), icon.id); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index a1f9683847..6948b2a8a2 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -42,7 +42,8 @@ export function createSelection({ return input.onClick((event) => { if (!isTrackingClickGesture(event.gesture)) return; const cell = - layerState._enabled && layerState._counts?.pickedCell(event.drawHit); + layerState._enabled && + layerState._counts?.pickedCell(event.screenPosition); if (cell) { parts.navigation.zoomToCell(cell); return; diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 34d18271da..f03ded5ceb 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -72,7 +72,9 @@ test('a count click preserves the provisional opening pick until the view settle _viewer: viewer, _openingCameraProvisional: true, _activeCameraId: 'opening', - _counts: { pickedCell: () => cell }, + _counts: { + pickedCell: (point) => (point?.x === 14 && point.y === 26 ? cell : null), + }, }; const parts = {}; parts.navigation = createNavigation({ state, parts }); @@ -87,7 +89,13 @@ test('a count click preserves the provisional opening pick until the view settle assert.fail('a count click reached activation or deselection'); }, ); - click({ drawHit: {}, gesture: { travelPx: 0, durationMs: 20 } }); + click({ + screenPosition: { x: 14, y: 26 }, + get drawHit() { + assert.fail('the camera underneath was picked'); + }, + gesture: { travelPx: 0, durationMs: 20 }, + }); assert.equal(flights.length, 1); assert.equal(state._activeCameraId, 'opening'); assert.equal(state._openingCameraProvisional, true); diff --git a/src/layers/cctv/testing.js b/src/layers/cctv/testing.js index 65afc5cb61..f616ab0b19 100644 --- a/src/layers/cctv/testing.js +++ b/src/layers/cctv/testing.js @@ -91,6 +91,7 @@ export function createTesting({ state: layerState, services, parts, source }) { * @param {'off'|'on'|'viewshed'} [options.coverageMode='on'] Coverage mode. * @param {boolean} [options.showProjection=false] Projection visibility. * @param {Map} [options.healthById] Health rows by camera id. + * @param {Function} [options.registerPaintLane] Receives the count painter. * @returns {void} */ @@ -103,6 +104,7 @@ export function createTesting({ state: layerState, services, parts, source }) { showProjection = false, healthById = new Map(), openingCameraProvisional = false, + registerPaintLane, } = {}) { layerState._viewer = viewer; layerState._records = Array.isArray(records) ? records : []; @@ -132,10 +134,12 @@ export function createTesting({ state: layerState, services, parts, source }) { // 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', - }); + layerState._counts?.dispose(); + layerState._counts = createCountMarkers( + registerPaintLane, + 'cctv:test:counts', + parts.rendering.refreshHorizonCulling, + ); for (const record of layerState._records) if (record?.camera?.id) parts.rendering.addCameraIcon(record); } @@ -155,7 +159,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, + counts: layerState._counts, gizmo: layerState._gizmo?.partsForTest() ?? {}, coverage, planes, diff --git a/src/overlays/worldOverlay.js b/src/overlays/worldOverlay.js index 39a3f626cc..451e04812b 100644 --- a/src/overlays/worldOverlay.js +++ b/src/overlays/worldOverlay.js @@ -243,6 +243,9 @@ const _customPaintFrame = { cameraHeight: Number.NaN, occluder: null, keyhole: null, + // Anchored custom glyphs yield to the same below-host chrome as entries. + overlapsHardUi: (rect) => + overlayRectIntersectsAnyHard(rect, _uiOcclusionRects), uiRects: _uiOcclusionRects, uiRectCount: 0, layoutRevision: 0, diff --git a/src/overlays/worldOverlay.test.mjs b/src/overlays/worldOverlay.test.mjs index 4b27e73aeb..ac04274210 100644 --- a/src/overlays/worldOverlay.test.mjs +++ b/src/overlays/worldOverlay.test.mjs @@ -1514,9 +1514,14 @@ test('a placement is only ever kept under chrome that composites ABOVE the host' const paintedUnder = (occluders) => { const env = installMockEnvironment({ width: 400, height: 300, dpr: 1, occluders }); initWorldOverlay(env.viewer); + let hardUi; + registerWorldOverlayPaintLane('ambient-label', (frame) => { + hardUi = frame.overlapsHardUi({ x: 180, y: 130, w: 40, h: 40 }); + }, { id: 'anchored-label', active: true }); setOverlayEntries('ambient', [selectedEntry('CONTACT')]); env.postRender.raise(); const { paintedCount } = getWorldOverlayDiagnostics(); + assert.equal(hardUi, paintedCount === 0); env.cleanup(); return paintedCount; }; diff --git a/src/render/cesium/screenModulation.js b/src/render/cesium/screenModulation.js index 53fee1bca5..45c2c4bffa 100644 --- a/src/render/cesium/screenModulation.js +++ b/src/render/cesium/screenModulation.js @@ -485,13 +485,6 @@ 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 diff --git a/src/render/cesium/screenModulation.test.mjs b/src/render/cesium/screenModulation.test.mjs index c88c74b3e2..62927bbe2d 100644 --- a/src/render/cesium/screenModulation.test.mjs +++ b/src/render/cesium/screenModulation.test.mjs @@ -606,19 +606,3 @@ 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(); - } -}); From c536d22ff09ac8cd08799d64a3a0e815f7d1dad0 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 20:48:33 +0400 Subject: [PATCH 08/56] feat(cctv): green count markers that grow with the count and carry a camera icon A count marker now says what it counts and how much: - Its height grows with the count, from 40 px for two cameras to 58 px for several thousand, with clear fill around the digits. - A small single-camera map icon sits under the top of the ring and the number just below the centre, so the two never touch. The icon is built from the same sprite as a single camera on the map. - Thousands print as 1.7K or 12K in every UI language. - The camera layer is green: count markers and idle single cameras share the colour, the active camera stays gold and live-video cameras violet. --- changelog.d/1808-cctv-camera-counts.md | 7 + docs/CURRENT-STATE.md | 8 +- src/data/cctv.test.mjs | 16 +- src/data/cctvCellCounts.js | 45 +-- src/data/cctvCellCounts.test.mjs | 65 +++- src/data/cctvViewThinning.test.mjs | 518 +++++++++++++++++++------ src/layers/cctv/countMarkers.js | 246 ++++++++++-- src/layers/cctv/policy.js | 65 +++- src/layers/cctv/rendering.js | 23 +- src/layers/cctv/rendering.test.mjs | 28 +- 10 files changed, 806 insertions(+), 215 deletions(-) create mode 100644 changelog.d/1808-cctv-camera-counts.md diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md new file mode 100644 index 0000000000..7ffb4bd262 --- /dev/null +++ b/changelog.d/1808-cctv-camera-counts.md @@ -0,0 +1,7 @@ +- Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a + ground cell with two or more cameras is one round marker with a small camera + icon and the count (`999`, `1.7K`, `12K` in every language); it grows with + the count, merges with a neighbour it would overlap, and a click zooms in + until the group splits. The camera layer's colour is now green: count + markers and idle single cameras share it, the active camera stays gold and + live-video cameras stay violet (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index f79aa705fd..4c1669a931 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,8 +1953,10 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows a cyan count at their centre, -drawn on the world overlay at the same resolution as camera callouts. +ground cell containing multiple cameras shows, at their centre, a marker with +a small green camera pictogram under its top edge and the count just below its +middle. The marker grows with the count and is drawn on the world overlay at +the same resolution as camera callouts. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, @@ -7339,7 +7341,7 @@ silently demoting every later lookup for the session. ground clamp now lifts the cap _center_ only so the wireframe stays a true pyramid welded to the plane (was a flattened fan / the ~47.5 m divergence — RESOLVED), re-selecting the active camera is a no-op (killed a click-flash), and texture swaps gate on canvas content (killed a - periodic white flash). Camera icons are cyan for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` + periodic white flash). Camera icons are green for stills, violet for cameras with a video feed, and amber for the active camera. Coverage is now **metro-wide: 250 cameras** (`CCTV_AUSTIN_MAX_SOURCES` default 36 → 250, hard bound 300), filtered to `camera_status === TURNED_ON` (~815 live of 1,003 rows). City packs (2026-07-04): Caltrans (districts 4/7/11/3 — SF, LA, San Diego, Sacramento; cap 300) and TfL London JamCams (cap 250) join Austin (cap 250) as keyless default diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index 35a634c6cf..fa9ee0eea1 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -85,6 +85,7 @@ import { } from '../cctvFocusRequest.js'; import { ACTIVE_CAMERA_COLOR, + CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; @@ -353,7 +354,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu } }); -test('camera icons are violet for video feeds, cyan for stills, amber when active', () => { +test('camera icons are violet for video feeds, green for stills, amber when active', () => { const record = (id, feedType) => ({ camera: { ...UNCLAMPED_CAMERA, id, feedType, groundElevationM: 0 }, // Every catalog record is placed as it is made, and drawn there. @@ -385,6 +386,19 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ assert.deepEqual(color(activeVideo), ACTIVE_CAMERA_COLOR); assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); assert.equal(icons.item(idleVideo.camera.id).scale, 1); + const image = (record) => icons.item(record.camera.id).image; + assert.deepEqual(IDLE_CAMERA_COLOR, [93 / 255, 1, 143 / 255, 1]); + const idleImage = image(idleStill); + assert.match(atob(idleImage.split(',')[1]), /stroke="#fff"/); + assert.equal(image(activeVideo), CAMERA_ICON); + assert.equal(image(idleVideo), CAMERA_ICON); + idleStill.camera.feedType = 'hls'; + refreshCoverageStyles(); + assert.equal(image(idleStill), CAMERA_ICON); + idleStill.camera.feedType = 'image'; + refreshCoverageStyles(); + assert.equal(image(idleStill), idleImage); + } finally { _setCctvCoverageStateForTest({ enabled: false }); unbind(); diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 8c4c7a226b..0543925ed2 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -1,12 +1,11 @@ -import { formatNumber } from '../i18n/index.js'; import { fromDegrees } from '../geo/ellipsoid.js'; -/** Exact small counts and compact thousands in the current UI locale. */ +/** Exact camera counts below a thousand, then rounded thousands with a K suffix. */ export function formatCameraCount(count) { - return formatNumber( - count, - count < 1000 ? undefined : { notation: 'compact' }, - ); + if (count < 1000) return String(count); + const thousands = + count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000); + return `${thousands}K`; } /** An empty cell and its on-screen picker candidate. */ @@ -86,17 +85,18 @@ function addCell(target, cell) { } /** Claim the touching pills in this marker's bucket and its eight neighbors. */ -function collectNeighbors(marker, grid, members, height, mergeDistance) { +function collectNeighbors(marker, grid, members, gap) { 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 extra = marker.halfSegment + other.halfSegment; 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; + const reach = marker.radius + other.radius + gap; + if (dx * dx + dy * dy >= reach * reach) continue; bucket.delete(other); members.push(other); } @@ -109,27 +109,28 @@ function collectNeighbors(marker, grid, members, height, mergeDistance) { * 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; +export function mergeCountCells(cells, project, sizeFor, gap) { + let columnWidth = 0; + let rowHeight = 0; const markers = cells.map((cell) => { const screen = project(cellCenter(cell)); - const width = widthFor(cell.count); + const { width, height } = sizeFor(cell.count); columnWidth = Math.max(columnWidth, width + gap); + rowHeight = Math.max(rowHeight, height + gap); // The view projector reuses its result object. - return { cell, x: screen?.x, y: screen?.y, width }; + return { + cell, + x: screen?.x, + y: screen?.y, + halfSegment: (width - height) / 2, + radius: height / 2, + }; }); 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); + marker.row = Math.floor(marker.y / rowHeight); const key = `${marker.col},${marker.row}`; if (!grid.has(key)) grid.set(key, new Set()); marker.bucket = grid.get(key); @@ -147,7 +148,7 @@ export function mergeCountCells( members.length = 0; members.push(seed); for (let i = 0; i < members.length; i++) - collectNeighbors(members[i], grid, members, height, mergeDistance); + collectNeighbors(members[i], grid, members, gap); if (members.length === 1) { groups.push(seed.cell); diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index bfa421bd91..49eb59faaf 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -9,20 +9,28 @@ import { cellCenter, cellBounds, formatCameraCount, + mergeCountCells, } from './cctvCellCounts.js'; -test('camera counts are exact through 999 and compact in the active locale', () => { +test('camera counts use the same Latin digits and K notation in every UI language', () => { const previous = getLocale(); + const examples = [ + [2, '2'], + [999, '999'], + [1000, '1K'], + [1150, '1.2K'], + [1687, '1.7K'], + [9960, '10K'], + [10000, '10K'], + [12345, '12K'], + [12500, '13K'], + [1000000, '1000K'], + ]; try { - for (const locale of ['en', 'fr', 'ja']) { + for (const locale of ['en', 'ru', 'ja', 'ar']) { 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)); - } + for (const [count, label] of examples) + assert.equal(formatCameraCount(count), label, `${locale}: ${count}`); } } finally { setLocale(previous); @@ -47,3 +55,42 @@ test('the marker mean weights every mount and the flight bounds cover the outlie ); } }); + +test('stadiums merge by their own radii and segment lengths across grid boundaries', () => { + const sizes = { + 2: { width: 28, height: 28 }, + 7350: { width: 80, height: 48 }, + }; + const gap = 4; + const check = (counts, positions, expected) => { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + gap, + ); + assert.deepEqual( + groups.map((cell) => cell.count), + expected, + ); + assert.equal( + groups.reduce((sum, cell) => sum + cell.count, 0), + counts[0] + counts[1], + ); + }; + const origin = { x: 35, y: 37 }; + // Mixed radii sum to 38. At 42 pixels vertically the gap is exactly clear. + check([2, 7350], [origin, { x: 35, y: 78 }], [7352]); + check([2, 7350], [origin, { x: 35, y: 79 }], [2, 7350]); + // The large pill's centre segment extends 16 pixels towards the circle. + check([7350, 2], [origin, { x: 92, y: 37 }], [7352]); + check([7350, 2], [origin, { x: 92, y: 49 }], [7350, 2]); + check([2, 2], [origin, { x: 70, y: 37 }], [2, 2]); + // Large pills can reach across a row boundary at their full diameter. + check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index ac134670e8..e78810b87a 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -4,7 +4,9 @@ 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 { CAMERA_GREEN } from '../layers/cctv/policy.js'; +import { createCameraGlyphCache } from '../layers/cctv/countMarkers.js'; +import { createCameraCell } from './cctvCellCounts.js'; import { bindRenderer } from '../render/rendererOf.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; @@ -93,8 +95,59 @@ let painter; let paintRequests; let measured; let glyphWidth; +let inkHalfHeight; let ctx; const fonts = new EventTarget(); +let rasters; +let spriteImages; + +/** Model the sprite’s neutral highlights, dark fills and translucent edges. */ +function markerCanvas() { + const canvas = {}; + const context = { + measureText(text) { + measured++; + return { + width: text.length * glyphWidth, + actualBoundingBoxAscent: inkHalfHeight, + actualBoundingBoxDescent: inkHalfHeight, + }; + }, + drawImage(image, x, y, width, height) { + assert.equal(image.loaded, true); + assert.deepEqual( + [x, y, width, height], + [0, 0, canvas.width, canvas.height], + ); + canvas.source = image.src; + const h = Math.floor(height / 2); + canvas.ink = [2, 3, Math.floor(h * 1.5), h]; + rasters.push(canvas); + }, + getImageData() { + const data = new Uint8ClampedArray(canvas.width * canvas.height * 4); + const [left, top, width, height] = canvas.ink; + for (let y = top; y < top + height; y++) { + for (let x = left; x < left + width; x++) { + const shade = x === left ? 255 : 64; + data.set( + [shade, shade, shade, y === top ? 1 : 255], + (y * canvas.width + x) * 4, + ); + } + } + return { data }; + }, + putImageData({ data }) { + const [left, top] = canvas.ink; + const start = (top * canvas.width + left) * 4; + canvas.stroke = [...data.slice(start, start + 4)]; + canvas.fill = [...data.slice(start + 4, start + 8)]; + }, + }; + canvas.getContext = () => context; + return canvas; +} function seedCoverage(options) { _setCctvCoverageStateForTest({ @@ -113,21 +166,23 @@ function seedCoverage(options) { } beforeEach(() => { + spriteImages = []; + globalThis.Image = class { + constructor() { + spriteImages.push(this); + } + finish() { + this.loaded = true; + this.onload(); + } + }; paintRequests = 0; measured = 0; glyphWidth = 8; - globalThis.document = { - fonts, - createElement: () => ({ - getContext: () => ({ - measureText(text) { - measured++; - return { width: text.length * glyphWidth }; - }, - }), - }), - }; - let savedState; + inkHalfHeight = 4; + rasters = []; + globalThis.document = { fonts, createElement: markerCanvas }; + const stack = []; ctx = { font: 'initial', globalAlpha: 1, @@ -136,17 +191,32 @@ beforeEach(() => { textAlign: 'start', textBaseline: 'top', lineWidth: 1, + glyphs: [], + rings: [], labels: [], shapes: [], save() { - savedState = { ...this }; + stack.push({ ...this }); }, restore() { - Object.assign(this, savedState); + Object.assign(this, stack.pop()); }, beginPath() {}, fill() {}, - stroke() {}, + drawImage(image, left, top, sw, sh, x, y, width, height) { + assert.deepEqual([left, top, sw, sh], image.ink); + assert.ok(Math.abs(width / height - sw / sh) < 1e-9); + this.glyphs.push({ + image, + x: x + width / 2, + y: y + height / 2, + width, + height, + }); + }, + stroke() { + this.rings.push(this.strokeStyle); + }, roundRect(...args) { this.shapes.push(args); }, @@ -155,6 +225,7 @@ beforeEach(() => { text, x, y, + color: this.fillStyle, alpha: this.globalAlpha, font: this.font, }); @@ -164,12 +235,16 @@ beforeEach(() => { /** Reproject on each paint in CSS pixels, as the host does. */ function paint(overrides = {}) { - ctx.labels.length = ctx.shapes.length = 0; + ctx.glyphs.length = + ctx.rings.length = + ctx.labels.length = + ctx.shapes.length = + 0; painter({ ctx, width: WIDTH, height: HEIGHT, - dpr: 2, + dpr: 1, viewProjectionMatrix: new Float64Array([ 0, 0, @@ -196,6 +271,7 @@ function paint(overrides = {}) { } afterEach(() => { + delete globalThis.Image; delete globalThis.document; for (const unbind of bindings.splice(0)) unbind(); }); @@ -314,7 +390,8 @@ test('the picker prefers the healthy camera and the marker stays at the mean', ( cctvLayer.getUIState().cameraIndex.map((c) => c.id), [id], ); - const { pos } = markers()[0]; + const { pos, height } = markers()[0]; + assert.equal(height, 40); const center = Cesium.Cartesian3.fromDegrees(0.0005, 0, 10); assert.ok(Cesium.Cartesian3.distance(pos, center) < 0.02); if (first) assert.deepEqual(pos, first); @@ -637,7 +714,7 @@ test('overlapping cells merge at their weighted centre and keep every camera in Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), ) < 0.01, ); - const positions = shown.map((m) => [m.cell.key, m.pos]); + const positions = shown.map((m) => [m.cell.key, m.pos, m.height, m.width]); if (previous) assert.deepEqual(positions, previous); previous = positions; clickMarker(merged); @@ -658,84 +735,137 @@ test('overlapping cells merge at their weighted centre and keep every camera in } }); -test('the overlay paints short counts as circles and long localized labels as pills', () => { - const locale = getLocale(); - try { - setLocale('ru'); +test('the overlay paints narrow count labels as circles and wide labels as pills', () => { + glyphWidth = 10; + const { records } = recordsAt([ + ...Array(1300).fill([-0.008, 0]), + ...Array(99).fill([0.06, 0]), + [0.1, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + const short = markers().find((m) => m.cell.count === 99); + const long = markers().find((m) => m.cell.count === 1300); + const measurements = measured; + assert.equal(measurements, 2); + const pending = paint().map(({ text, x, y }) => [text, x, y]); + const pendingShapes = [...ctx.shapes]; + const requests = paintRequests; + assert.equal(ctx.glyphs.length, 0); + assert.equal(spriteImages.length, 1); + spriteImages[0].finish(); + assert.equal(paintRequests, requests + 1); + const labels = paint(); + assert.deepEqual( + labels.map(({ text, x, y }) => [text, x, y]), + pending, + ); + assert.deepEqual(ctx.shapes, pendingShapes); + refreshHorizonCulling(); + assert.equal(measured, measurements); + const text = '1.3K'; + assert.equal(labels.length, 2); + assert.equal(ctx.shapes.length, labels.length); + const [sx, sy, sw, sh] = ctx.shapes[labels.findIndex((l) => l.text === '99')]; + const [lx, ly, lw, lh] = ctx.shapes[labels.findIndex((l) => l.text === text)]; + assert.equal(sw, sh); + assert.ok(lw > lh); + assert.ok(lw > text.length * glyphWidth); + assert.equal(sh + 4, 48); + assert.equal(lh + 4, 54); + // The four-pixel outer stroke extends two pixels on each side of the path. + assert.equal(sw + 4, short.width); + assert.equal(lw + 4, long.width); + assert.equal(sy + sh / 2, HEIGHT / 2); + assert.equal(ly + lh / 2, HEIGHT / 2); + assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); + assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); + assert.equal(ctx.glyphs.length, labels.length); + assert.equal(CAMERA_GREEN, '#5dff8f'); + assert.deepEqual( + ctx.rings.filter((_, i) => i % 2 === 1), + labels.map(() => CAMERA_GREEN), + ); + for (const [i, label] of labels.entries()) { + const glyph = ctx.glyphs[i]; + const [left, top, w, h] = ctx.shapes[i]; + const cx = left + w / 2, + cy = top + h / 2; + assert.equal(glyph.x, cx); + assert.equal(label.x, cx); + assert.deepEqual(glyph.image.stroke, [93, 255, 143, 1]); + assert.deepEqual(glyph.image.fill, [23, 64, 36, 1]); + assert.equal(label.color, CAMERA_GREEN); + const radius = h / 2 - 1; + // 48 and 54 px markers: the glyph and its top gap grow with the marker. + const grown = (h + 4 - 40) / 18; + assert.ok(Math.abs(glyph.height - (7.5 + 2.5 * grown)) < 1e-9); + assert.ok( + Math.abs(glyph.y - glyph.height / 2 - (cy - radius + 3 + grown)) < 1e-9, + ); + // The middle of the digits sits a fifth of the inner radius below centre. + assert.ok(Math.abs(label.y - (cy + 0.2 * radius)) < 1e-9); + assert.ok(label.y - inkHalfHeight - (glyph.y + glyph.height / 2) >= 5); + for (const [width, edgeY, padding] of [ + [glyph.width, glyph.y - glyph.height / 2, 2], + [label.text.length * glyphWidth, label.y + inkHalfHeight, 6], + ]) { + const chord = 2 * Math.sqrt(radius ** 2 - (edgeY - cy) ** 2); + assert.ok((w - h + chord - width) / 2 >= padding - 1e-9); + } + } + const builds = rasters.length; + const images = ctx.glyphs.map((glyph) => glyph.image); + assert.notEqual(images[0], images[1]); + const idleCamera = _cctvIconsForTest().item(records.at(-1).camera.id); + assert.equal(idleCamera.show, true); + for (const image of images) assert.equal(image.source, idleCamera.image); + paint(); + assert.deepEqual( + ctx.glyphs.map((glyph) => glyph.image), + images, + ); + assert.equal(rasters.length, builds); + assert.equal(paintRequests, requests + 1); + assert.match(labels[0].font, /JetBrains Mono/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); + assert.equal(ctx.lineWidth, 1); + ctx.drawImage = () => { + throw new Error('glyph paint failed'); + }; + assert.throws(() => paint(), /glyph paint failed/); + assert.equal(ctx.font, 'initial'); + assert.equal(ctx.fillStyle, 'initial'); +}); + +test('a wide count label merges a horizontal neighbor beyond the circle diameter', () => { + glyphWidth = 12; + // The centers are 56 CSS pixels apart. Only the pill reaches its neighbor. + const at = (count) => { const { records } = recordsAt([ - ...Array(1300).fill([-0.008, 0]), - [0.06, 0], - [0.06, 0], + ...Array(count).fill([-0.0097, 0]), + [0.0097, 0], + [0.0097, 0], ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - const short = markers().find((m) => m.cell.count === 2); - const long = markers().find((m) => m.cell.count === 1300); - const measurements = measured; - assert.equal(measurements, 1); - const labels = paint(); - refreshHorizonCulling(); - assert.equal(measured, measurements); - const text = new Intl.NumberFormat('ru', { notation: 'compact' }).format( - 1300, - ); - assert.equal(labels.length, 2); - assert.equal(ctx.shapes.length, labels.length); - const [sx, sy, sw, sh] = - ctx.shapes[labels.findIndex((l) => l.text === '2')]; - const [lx, ly, lw, lh] = - ctx.shapes[labels.findIndex((l) => l.text === text)]; - assert.equal(sw, sh); - assert.ok(lw > text.length * glyphWidth); - assert.equal(lh, sh); - // The four-pixel outer stroke extends two pixels on each side of the path. - assert.equal(sw + 4, short.width); - assert.equal(lw + 4, long.width); - assert.equal(sy + sh / 2, HEIGHT / 2); - assert.equal(ly + lh / 2, HEIGHT / 2); - assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); - assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); - assert.match(labels[0].font, /JetBrains Mono/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); - assert.equal(ctx.lineWidth, 1); - } 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], - ]); - seedCoverage({ viewer: viewerAt(20_000), records }); - refreshHorizonCulling(); - return markers().map((m) => m.cell.count); - }; - assert.deepEqual(at(2), [2, 2]); - assert.deepEqual(at(1300), [1302]); - } finally { - setLocale(locale); - } + return markers().map((m) => m.cell.count); + }; + assert.deepEqual(at(2), [2, 2]); + assert.deepEqual(at(1300), [1302]); }); 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. + // The northern pair is 42 px apart. Its centre is 44.5 px from the + // southern group, within reach only after the count grows from two to four. const { records } = recordsAt([ - [-0.006, 0], - [-0.006, 0], - [0.006, 0], - [0.006, 0], - [0, -0.0126], - [0, -0.0126], + [-0.0073, 0], + [-0.0073, 0], + [0.0073, 0], + [0.0073, 0], + [0, -0.0154], + [0, -0.0154], ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); @@ -758,10 +888,10 @@ test('each paint follows the overlay projection, horizon and hard HUD exclusions assert.ok(paintRequests > 0); const requests = paintRequests; const widths = measured; - assert.deepEqual( - paint().map(({ text, x, y }) => [text, x, y]), - [['4', 400, 300]], - ); + const [label] = paint(); + assert.equal(label.text, '4'); + assert.equal(label.x, 400); + assert.ok(label.y > 300); const first = { x: 400, y: 300 }; assert.equal(counts.pickedCell(first).count, 4); const at = (x) => { @@ -782,28 +912,22 @@ test('each paint follows the overlay projection, horizon and hard HUD exclusions }); test('loaded font metrics remerge visible cells without waiting for a move', () => { - const locale = getLocale(); - try { - setLocale('ru'); - glyphWidth = 3; - const { records } = recordsAt([ - ...Array(1300).fill([-0.009, 0]), - [0.009, 0], - [0.009, 0], - ]); - seedCoverage({ viewer: viewerAt(20_000), records }); - refreshHorizonCulling(); - assert.equal(markers().length, 2); - glyphWidth = 12; - fonts.dispatchEvent(new Event('loadingdone')); - assert.deepEqual( - markers().map((m) => m.cell.count), - [1302], - ); - assert.equal(paint().length, 1); - } finally { - setLocale(locale); - } + glyphWidth = 3; + const { records } = recordsAt([ + ...Array(1300).fill([-0.0097, 0]), + [0.0097, 0], + [0.0097, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.equal(markers().length, 2); + glyphWidth = 14; + fonts.dispatchEvent(new Event('loadingdone')); + assert.deepEqual( + markers().map((m) => m.cell.count), + [1302], + ); + assert.equal(paint().length, 1); }); test('hits follow paint order and keep the last painted group until the overlay clears', () => { @@ -829,3 +953,165 @@ test('hits follow paint order and keep the last painted group until the overlay assert.deepEqual(paint(), []); assert.equal(counts.pickedCell(point), null); }); + +test('paint, HUD exclusions and hit rectangles use the count-scaled height', () => { + seedCoverage({ viewer: viewerAt(20_000) }); + const counts = cctvLayer._cctvDrawnForTest().counts; + for (const [count, height] of [ + [2, 40], + [10, 44], + [100, 48], + [1000, 54], + [3162, 56], + [3163, 56], + [7350, 58], + [1e8, 58], + ]) { + const cell = { ...createCameraCell('cell'), count }; + for (const lon of [0, 0.025]) { + counts.update( + [{ ...cell, lonSum: Math.round(lon * 1e7) * count }], + () => null, + ); + if (!spriteImages[0]?.loaded) spriteImages[0].finish(); + let rect; + const [label] = paint({ + overlapsHardUi(value) { + rect = { ...value }; + return false; + }, + }); + if (height === 40 || height === 58) + assert.equal(ctx.glyphs[0].height, height === 40 ? 7.5 : 10); + const marker = markers()[0]; + assert.equal(marker.height, height); + assert.equal(rect.h, height); + assert.equal(rect.w, marker.width); + const [x, y, w, h] = ctx.shapes[0]; + assert.deepEqual( + [x - 2, y - 2, w + 4, h + 4], + [rect.x, rect.y, rect.w, rect.h], + ); + for (const sign of [-1, 1]) { + const edgeY = rect.y + height / 2 + (sign * height) / 2; + assert.equal(counts.pickedCell({ x: label.x, y: edgeY }).count, count); + assert.equal( + counts.pickedCell({ x: label.x, y: edgeY + sign * 0.1 }), + null, + ); + } + } + // Centred 23 px above the canvas: the taller badges still cross the edge. + const matrix = new Float64Array(16); + matrix[13] = 1 + 46 / HEIGHT; + matrix[15] = 1; + assert.equal( + paint({ viewProjectionMatrix: matrix }).length, + height > 46 ? 1 : 0, + ); + } +}); + +test('measured ink width selects the circle or pill and clears the curved ring', () => { + const { records } = recordsAt(Array(99).fill([0, 0])); + seedCoverage({ viewer: viewerAt(20_000), records }); + for (const [width, extent, circle] of [ + [7, 4, true], + [25, 4, false], + // Width-only metrics reserve the full type height below the baseline. + [6, undefined, true], + ]) { + glyphWidth = width; + inkHalfHeight = extent; + fonts.dispatchEvent(new Event('loadingdone')); + refreshHorizonCulling(); + const [label] = paint(); + const [, top, pathWidth, pathHeight] = ctx.shapes[0]; + assert.equal(pathHeight + 4, 48); + assert.equal(pathWidth === pathHeight, circle); + // At the top of the ink, the circle ends narrow the usable inner width. + const innerRadius = pathHeight / 2 - 1; + const edge = label.y + (extent ?? 6) - (top + pathHeight / 2); + const clearWidth = + pathWidth - pathHeight + 2 * Math.sqrt(innerRadius ** 2 - edge ** 2); + assert.ok((clearWidth - label.text.length * width) / 2 >= 6); + } +}); + +test('equal-size camera groups share a camera sprite and follow overlay pixel density', () => { + const { records } = recordsAt([ + [0, 0], + [0, 0], + [0.05, 0], + [0.05, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + spriteImages[0].finish(); + paint({ dpr: 1 }); + const low = ctx.glyphs[0].image; + assert.equal(ctx.glyphs[1].image, low); + const builds = rasters.length; + paint({ dpr: 2 }); + const high = ctx.glyphs[0].image; + assert.equal(ctx.glyphs[1].image, high); + assert.notEqual(high, low); + // The raster follows the device density; the painted size does not. + assert.deepEqual([low.width, high.width], [16, 30]); + assert.equal(ctx.glyphs[0].height, 7.5); + paint({ dpr: 2 }); + assert.equal(rasters.length, builds + 1); + paint({ dpr: 1 }); + assert.equal(ctx.glyphs[0].image, low); + assert.equal(rasters.length, builds + 1); +}); + +test('the glyph cache draws its supplied map sprite and multiplies its colours', () => { + const source = + 'data:image/svg+xml,' + + encodeURIComponent( + '', + ); + const glyphFor = createCameraGlyphCache(markerCanvas, source); + assert.equal(glyphFor(12, 2, CAMERA_GREEN), null); + assert.equal(spriteImages[0].src, source); + spriteImages[0].finish(); + const green = glyphFor(12, 2, CAMERA_GREEN); + assert.equal(glyphFor(12, 2, CAMERA_GREEN), green); + const white = glyphFor(12, 2, '#ffffff'); + assert.notEqual(white, green); + assert.deepEqual( + rasters.map(({ source: drawn }) => drawn), + [source, source], + ); + assert.deepEqual(white.canvas.stroke, [255, 255, 255, 1]); + assert.deepEqual(white.canvas.fill, [64, 64, 64, 1]); +}); + +test('a sprite that loads after disposal does not request a paint', () => { + const { records } = recordsAt(CLUSTER); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + cctvLayer._cctvDrawnForTest().counts.dispose(); + const requests = paintRequests; + spriteImages[0].finish(); + assert.equal(rasters.length, 0); + assert.equal(paintRequests, requests); +}); + +test('counts still paint when an offscreen 2D context is unavailable', () => { + document.createElement = () => ({ getContext: () => null }); + const { records } = recordsAt([ + [0, 0], + [0, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + spriteImages[0].finish(); + assert.deepEqual( + paint().map((label) => label.text), + ['2'], + ); + assert.equal(ctx.glyphs.length, 0); + assert.equal(ctx.shapes.length, 1); +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 740519b132..b6f38e7fe7 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -5,19 +5,112 @@ import { } from '../../data/cctvCellCounts.js'; import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { - COUNT_MARKER_PX, - COUNT_MERGE_DISTANCE_PX, + CAMERA_GREEN, + IDLE_CAMERA_ICON, + COUNT_BASE_PX, + COUNT_PX_PER_DECADE, + COUNT_MIN_HEIGHT_PX, + COUNT_MAX_HEIGHT_PX, + COUNT_TEXT_PADDING_PX, + COUNT_GLYPH_MIN_PX, + COUNT_GLYPH_MAX_PX, + COUNT_GLYPH_TOP_MIN_PX, + COUNT_GLYPH_TOP_MAX_PX, + COUNT_GLYPH_PADDING_PX, + COUNT_LABEL_DROP, + COUNT_MERGE_GAP_PX, COUNT_MERGE_PASSES, } from './policy.js'; const FONT = WORLD_OVERLAY_STYLE.fontTitle; -const RING = '#75e7ff'; +// Reserve the camera's landscape slot even while the map sprite is loading. +const GLYPH_ASPECT = 1.5; +const RING_PX = 2; +const RIM_PX = 1; +const STROKE_INSET = RIM_PX + RING_PX / 2; + +/** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ +function rasterizeGlyph(canvas, image, size, dpr, color) { + if (!canvas) return null; + // The artwork occupies just over half the height of the square SVG viewport. + const side = 2 * Math.ceil(size * dpr); + canvas.width = canvas.height = side; + const ctx = canvas.getContext('2d'); + if (!ctx) return null; + ctx.drawImage(image, 0, 0, side, side); + const pixels = ctx.getImageData(0, 0, side, side); + const { data } = pixels; + const rgb = Number.parseInt(color.slice(1), 16); + const red = (rgb >> 16) / 255; + const green = ((rgb >> 8) & 255) / 255; + const blue = (rgb & 255) / 255; + let left = side, + top = side, + right = -1, + bottom = -1; + for (let y = 0; y < side; y++) { + for (let x = 0; x < side; x++) { + const i = (y * side + x) * 4; + if (!data[i + 3]) continue; + data[i] *= red; + data[i + 1] *= green; + data[i + 2] *= blue; + left = Math.min(left, x); + right = Math.max(right, x); + top = Math.min(top, y); + bottom = y; + } + } + if (right < 0) return null; + ctx.putImageData(pixels, 0, 0); + const width = right - left + 1; + const height = bottom - top + 1; + const scale = Math.min(size / height, (size * GLYPH_ASPECT) / width); + return { + canvas, + left, + top, + width, + height, + drawWidth: width * scale, + drawHeight: height * scale, + }; +} + +/** Load the map artwork once, then share each tinted device-density raster. */ +export function createCameraGlyphCache(createCanvas, source, onLoad) { + const glyphs = new Map(); + let image; + let ready = false; + return (size, dpr, color) => { + if (!image && typeof Image !== 'undefined') { + image = new Image(); + image.onload = () => { + ready = true; + onLoad?.(); + }; + image.src = source; + } + if (!ready) return null; + const key = `${size}:${dpr}:${color}`; + if (!glyphs.has(key)) { + glyphs.set(key, rasterizeGlyph(createCanvas(), image, size, dpr, color)); + } + return glyphs.get(key); + }; +} /** Merged camera groups and their last painted hit rectangles in CSS pixels. */ -export function createCountMarkers(registerPaintLane, id, refreshView) { +export function createCountMarkers( + registerPaintLane, + id, + refreshView, + createCanvas = () => globalThis.document?.createElement('canvas'), +) { + let dpr = Math.max(1, Number(globalThis.window?.devicePixelRatio) || 1); const markers = []; const hits = []; - const widths = new Map(); + const textMetrics = new Map(); const fonts = globalThis.document?.fonts; let measureCtx; let hitCount = 0; @@ -26,30 +119,81 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { active: false, target: 'shared', }); + const glyphFor = createCameraGlyphCache( + createCanvas, + IDLE_CAMERA_ICON, + () => { + if (!markers.length) return; + refreshGlyphs(); + lane?.requestPaint(); + }, + ); fonts?.addEventListener?.('loadingdone', fontsLoaded); /** Font changes can widen a pill enough to merge it with its neighbor. */ function fontsLoaded() { - widths.clear(); + textMetrics.clear(); if (!markers.length) return; refreshView(); lane?.requestPaint(); } - /** Short labels fit the circle. A longer label leaves room for rounded ends. */ - function widthForText(text) { - if (text.length <= 3) return COUNT_MARKER_PX; - let width = widths.get(text); - if (width === undefined) { - measureCtx ??= document.createElement('canvas').getContext('2d'); - measureCtx.font = FONT; - width = Math.max( - COUNT_MARKER_PX + 1, - Math.ceil(measureCtx.measureText(text).width) + 20, - ); - widths.set(text, width); + /** Seat the glyph under the top of the ring and the count just below centre. */ + function sizeFor(count) { + const text = formatCameraCount(count); + let metrics = textMetrics.get(text); + if (!metrics) { + measureCtx ??= createCanvas()?.getContext('2d'); + if (measureCtx) { + measureCtx.font = FONT; + measureCtx.textBaseline = 'middle'; + metrics = measureCtx.measureText(text); + } else { + metrics = { width: text.length * 8 }; + } + textMetrics.set(text, metrics); } - return width; + const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count); + const clamped = Math.max( + COUNT_MIN_HEIGHT_PX, + Math.min(COUNT_MAX_HEIGHT_PX, diameter), + ); + const height = 2 * Math.round(clamped / 2); + const grown = + (height - COUNT_MIN_HEIGHT_PX) / + (COUNT_MAX_HEIGHT_PX - COUNT_MIN_HEIGHT_PX); + const glyphHeight = + COUNT_GLYPH_MIN_PX + (COUNT_GLYPH_MAX_PX - COUNT_GLYPH_MIN_PX) * grown; + const radius = height / 2 - RIM_PX - RING_PX; + const glyphTop = + COUNT_GLYPH_TOP_MIN_PX + + (COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown - + radius; + // Width-only metrics use half the 12 px type size on each side of the baseline. + const ascent = metrics.actualBoundingBoxAscent ?? 6; + const descent = metrics.actualBoundingBoxDescent ?? 6; + const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2; + // Each row must clear the ring at the edge where the circle is narrowest. + const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2)); + const extra = Math.max( + 0, + Math.ceil( + Math.max( + metrics.width + 2 * COUNT_TEXT_PADDING_PX - chordAt(labelY + descent), + glyphHeight * GLYPH_ASPECT + + 2 * COUNT_GLYPH_PADDING_PX - + chordAt(glyphTop), + ), + ), + ); + return { + text, + width: height + extra, + height, + glyphHeight, + glyphBottom: glyphTop + glyphHeight, + labelY, + }; } /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ @@ -65,9 +209,8 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { const merged = mergeCountCells( visible, project, - (count) => widthForText(formatCameraCount(count)), - COUNT_MARKER_PX, - COUNT_MERGE_DISTANCE_PX, + sizeFor, + COUNT_MERGE_GAP_PX, ); if (merged.length === visible.length) break; visible = merged; @@ -77,8 +220,7 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { const cell = visible[i]; const marker = markers[i] ?? (markers[i] = { focus: 1 }); const last = marker.cell; - const text = formatCameraCount(cell.count); - const width = widthForText(text); + const size = sizeFor(cell.count); if ( !last || last.count !== cell.count || @@ -98,10 +240,14 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ) { changed = true; } - changed ||= text !== marker.text || width !== marker.width; + changed ||= + size.text !== marker.text || + size.width !== marker.width || + size.glyphBottom !== marker.glyphBottom || + size.labelY !== marker.labelY; marker.cell = cell; - marker.text = text; - marker.width = width; + Object.assign(marker, size); + marker.glyph = glyphFor(size.glyphHeight, dpr, CAMERA_GREEN); // Paint never grows the hit buffer, even when a pan reveals every group. hits[i] ??= {}; } @@ -111,6 +257,12 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { if (changed) lane?.requestPaint(); } + /** Attach the raster for the current overlay density to each visible group. */ + function refreshGlyphs() { + for (const marker of markers) + marker.glyph = glyphFor(marker.glyphHeight, dpr, CAMERA_GREEN); + } + /** Draw at device density using the host's CSS-pixel transform and projection. */ function paint(frame) { if (!markers.length) { @@ -121,7 +273,10 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { } hitCount = 0; const { ctx, occluder, viewProjectionMatrix: m } = frame; - const height = COUNT_MARKER_PX; + if (dpr !== frame.dpr) { + dpr = frame.dpr; + refreshGlyphs(); + } ctx.save(); try { ctx.font = FONT; @@ -129,6 +284,7 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ctx.textBaseline = 'middle'; for (let i = 0; i < markers.length; i++) { const marker = markers[i]; + const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) @@ -155,22 +311,36 @@ export function createCountMarkers(registerPaintLane, id, refreshView) { ctx.globalAlpha = marker.focus; ctx.beginPath(); ctx.roundRect( - rect.x + 2, - rect.y + 2, - rect.w - 4, - height - 4, - height / 2 - 2, + rect.x + STROKE_INSET, + rect.y + STROKE_INSET, + rect.w - 2 * STROKE_INSET, + height - 2 * STROKE_INSET, + height / 2 - STROKE_INSET, ); ctx.strokeStyle = 'rgba(8, 14, 20, 0.85)'; - ctx.lineWidth = 4; + ctx.lineWidth = RING_PX + 2 * RIM_PX; ctx.stroke(); ctx.fillStyle = '#0e1720'; ctx.fill(); - ctx.strokeStyle = RING; - ctx.lineWidth = 2; + ctx.strokeStyle = CAMERA_GREEN; + ctx.lineWidth = RING_PX; ctx.stroke(); - ctx.fillStyle = RING; - ctx.fillText(marker.text, x, y); + ctx.fillStyle = CAMERA_GREEN; + const glyph = marker.glyph; + if (glyph) { + ctx.drawImage( + glyph.canvas, + glyph.left, + glyph.top, + glyph.width, + glyph.height, + x - glyph.drawWidth / 2, + y + marker.glyphBottom - glyph.drawHeight, + glyph.drawWidth, + glyph.drawHeight, + ); + } + ctx.fillText(marker.text, x, y + marker.labelY); rect.cell = marker.cell; hitCount++; } diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index e728d5707d..17ed1ae561 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -71,11 +71,38 @@ 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; +// Diameter at one camera before applying the size limits, in CSS pixels. +export const COUNT_BASE_PX = 38; -// Separation of two circular counts, including a four-pixel gap between rings. -export const COUNT_MERGE_DISTANCE_PX = COUNT_MARKER_PX + 4; +// Extra diameter for each tenfold increase in camera count. +export const COUNT_PX_PER_DECADE = 5; + +// Minimum height of a count marker in CSS pixels. +export const COUNT_MIN_HEIGHT_PX = 40; + +// Maximum height of a count marker in CSS pixels. +export const COUNT_MAX_HEIGHT_PX = 58; + +// Clear fill between the count and the inside of the ring, in CSS pixels. +export const COUNT_TEXT_PADDING_PX = 6; + +// Height of the camera glyph in the smallest and the largest marker. +export const COUNT_GLYPH_MIN_PX = 7.5; +export const COUNT_GLYPH_MAX_PX = 10; + +// Clear fill above the glyph in the smallest and the largest marker. +export const COUNT_GLYPH_TOP_MIN_PX = 3; +export const COUNT_GLYPH_TOP_MAX_PX = 4; + +// Clear fill between the glyph's top corners and the inside of the ring. +export const COUNT_GLYPH_PADDING_PX = 2; + +// The middle of the digits sits this share of the inner radius below the +// marker's centre, which leaves the glyph clear of the count. +export const COUNT_LABEL_DROP = 0.2; + +// Minimum gap between the outer rims of two separate markers. +export const COUNT_MERGE_GAP_PX = 4; // Recheck moved centres and wider labels while bounding work on motion ticks. export const COUNT_MERGE_PASSES = 3; @@ -194,25 +221,30 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({ * 2× display draws it at 60 device px, and it stays sharp there. */ -export const CAMERA_ICON = (() => { +function cameraIcon(neutral) { + const tone = (original, gray) => (neutral ? gray : original); + const stroke = tone('#75e7ff', '#fff'); const svg = ` - - - + + + - - - - - + + + + + `; return 'data:image/svg+xml;base64,' + btoa(svg); -})(); +} + +export const CAMERA_ICON = cameraIcon(false); +export const IDLE_CAMERA_ICON = cameraIcon(true); /** * Seed camera definitions used when no live sources are available. @@ -450,7 +482,10 @@ export const CAMERA_SEEDS = [ // Visual style constants: renderer colours, [r, g, b, a] in 0..1 // --------------------------------------------------------------------------- -export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88); +/** Shared accent for idle still cameras and grouped cameras. */ +export const CAMERA_GREEN = '#5dff8f'; + +export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN); export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95); diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index d041a1c681..c794519295 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -4,6 +4,7 @@ import { isHeadingEstimated } from './headingConfidence.js'; import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, + IDLE_CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, ACTIVE_COVERAGE_CENTER, @@ -13,7 +14,6 @@ import { IDLE_COVERAGE_EDGE_MUTED, ACTIVE_COVERAGE_EDGE_DEPTHFAIL, IDLE_COVERAGE_COLOR, - COUNT_MARKER_PX, VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, @@ -33,6 +33,10 @@ import { poseProjector } from '../../geo/frustum.js'; import { horizonFrom } from '../../geo/horizon.js'; import { distance } from '../../geo/vector.js'; +const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR }; +const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR }; +const LIVE_ICON_STYLE = { image: CAMERA_ICON, color: LIVE_CAMERA_COLOR }; + /** An RGBA colour with another alpha. */ const withAlpha = (color, alpha) => [color[0], color[1], color[2], alpha]; @@ -164,9 +168,8 @@ export function createRendering({ return { id, pos: copyPoint(record.position), - image: CAMERA_ICON, + ...cameraIconStyleFor(record), size: [CAMERA_ICON_PX, CAMERA_ICON_PX], - color: cameraColorFor(record), scale: 1, scaleByDistance: CAMERA_SCALE_BY_DISTANCE, disableDepthTest: Infinity, @@ -215,12 +218,12 @@ export function createRendering({ icons.put({ ...item, pos: copyPoint(record.position) }); } - /** Icon color: active wins, then live-capable video feeds, then idle stills. */ - function cameraColorFor(record) { + /** Select the sprite and tint together when a camera changes state. */ + function cameraIconStyleFor(record) { if (record.camera.id === layerState._activeCameraId) - return ACTIVE_CAMERA_COLOR; - if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_CAMERA_COLOR; - return IDLE_CAMERA_COLOR; + return ACTIVE_ICON_STYLE; + if (parts.model.isVideoFeedCamera(record.camera)) return LIVE_ICON_STYLE; + return IDLE_ICON_STYLE; } const { @@ -326,7 +329,7 @@ export function createRendering({ marker.pos, true, marker.width, - COUNT_MARKER_PX, + marker.height, marker.focus, ); if (factor !== null) marker.focus = factor; @@ -611,7 +614,7 @@ export function createRendering({ for (const record of layerState._records) { const isActive = record.camera.id === activeId; const icon = patchedCameraIcon(record.camera.id, { - color: cameraColorFor(record), + ...cameraIconStyleFor(record), scale: isActive ? 1.25 : 1.0, }); if (icon) restyled.push(icon); diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index aa53c5ab0c..6d4600ec3b 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -1,7 +1,7 @@ // src/layers/cctv/rendering.test.mjs // Icon colors under focus de-emphasis (#1200): the focus pass fades each icon // from the same base color the coverage refresh assigns, so a video-feed camera -// stays violet while it dims instead of falling back to the idle cyan. +// stays violet while it dims instead of falling back to the idle green. // Teardown lets go of the icon set of the viewer that drew it. import { test } from 'node:test'; import assert from 'node:assert/strict'; @@ -114,6 +114,32 @@ test('focus de-emphasis fades each icon from its own color', () => { } }); +test('focus uses the painted half-width and half-height of each count', () => { + const markers = [ + { width: 40, height: 40 }, + { width: 72, height: 58 }, + ]; + const sizes = []; + const rendering = createRendering({ + state: { _counts: { markers } }, + services: { + focus: { + focusPassIsNeeded: () => true, + advanceSpriteFocus(_owner, { spriteHalfWidthPx, spriteHalfHeightPx }) { + sizes.push([spriteHalfWidthPx, spriteHalfHeightPx]); + return { factor: 1 }; + }, + focusAlphaNeedsWrite: () => false, + }, + }, + }); + rendering.applyCctvFocusDeemphasis({}); + assert.deepEqual(sizes, [ + [20, 20], + [36, 29], + ]); +}); + test('the icons go with the viewer that drew them, whichever tears down', () => { const first = {}; const second = {}; From 65942008bf1b23b1ff2a88046bee9d9934f87141 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 21:23:41 +0400 Subject: [PATCH 09/56] fix(cctv): count a lone camera in the marker it sits against A ground cell with one camera always drew its icon, so at some zooms a camera poked out from under a count marker with its own callout. An icon closer than the merge gap to a count marker now joins that marker: the count grows by one and the icon, its callout and its card are not drawn. Two lone cameras with no count beside them stay two icons, and the active camera always keeps its own icon. --- changelog.d/1808-cctv-camera-counts.md | 9 ++-- docs/CURRENT-STATE.md | 4 +- src/data/cctvCellCounts.js | 4 ++ src/data/cctvCellCounts.test.mjs | 41 ++++++++++++++++++ src/data/cctvViewThinning.test.mjs | 60 ++++++++++++++++++++------ src/layers/cctv/countMarkers.js | 18 ++++++-- src/layers/cctv/policy.js | 4 ++ src/layers/cctv/rendering.js | 9 ++-- 8 files changed, 125 insertions(+), 24 deletions(-) diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 7ffb4bd262..8de3034801 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -1,7 +1,8 @@ - Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a ground cell with two or more cameras is one round marker with a small camera icon and the count (`999`, `1.7K`, `12K` in every language); it grows with - the count, merges with a neighbour it would overlap, and a click zooms in - until the group splits. The camera layer's colour is now green: count - markers and idle single cameras share it, the active camera stays gold and - live-video cameras stay violet (gekh, #1808). + the count, merges with a neighbour it would overlap, takes in a lone camera + whose icon would sit against it, and a click zooms in until the group + splits. The camera layer's colour is now green: count markers and idle + single cameras share it, the active camera stays gold and live-video cameras + stay violet (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4c1669a931..a6069e262b 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1956,7 +1956,9 @@ The CCTV layer draws only the cameras on or near the screen. Zoomed out, a ground cell containing multiple cameras shows, at their centre, a marker with a small green camera pictogram under its top edge and the count just below its middle. The marker grows with the count and is drawn on the world overlay at -the same resolution as camera callouts. +the same resolution as camera callouts. A lone camera whose icon would sit +within 4 px of a marker is counted in that marker instead of being drawn; the +active camera always keeps its own icon. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 0543925ed2..bf746f6e1a 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -91,6 +91,8 @@ function collectNeighbors(marker, grid, members, gap) { const bucket = grid.get(`${marker.col + col},${marker.row + row}`); if (!bucket) continue; for (const other of bucket) { + // Lone cameras join a count beside them, never each other. + if (marker.cell.count === 1 && other.cell.count === 1) continue; // Distance between the horizontal centre segments of the two pills. const extra = marker.halfSegment + other.halfSegment; const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); @@ -107,6 +109,8 @@ function collectNeighbors(marker, grid, members, gap) { /** * Merge connected groups of overlapping horizontal pills. Each marker occupies * one grid bucket. Even the widest pill can only touch its eight neighbors. + * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and + * joins a count it touches; two such cells alone stay apart. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index 49eb59faaf..66d9702c36 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -94,3 +94,44 @@ test('stadiums merge by their own radii and segment lengths across grid boundari // Large pills can reach across a row boundary at their full diameter. check([7350, 7350], [origin, { x: 35, y: 88 }], [14700]); }); + +test('a lone camera joins a count it touches, and lone cameras alone stay apart', () => { + const sizes = { + 1: { width: 24, height: 24 }, + 9: { width: 40, height: 40 }, + }; + const gap = 4; + const check = (counts, positions, expected) => { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + gap, + ); + assert.deepEqual( + groups.map((cell) => cell.count), + expected, + ); + // A lone camera that stays apart is still its own cell object. + assert.deepEqual( + groups.filter((cell) => cell.count === 1), + cells.filter((cell) => groups.includes(cell) && cell.count === 1), + ); + }; + const at = (x, y = 100) => ({ x, y }); + // Radii 20 and 12: the four-pixel gap is clear at 36 pixels. + check([9, 1], [at(100), at(135)], [10]); + check([9, 1], [at(100), at(136)], [9, 1]); + check([1, 9], [at(135), at(100)], [10]); + // Overlapping icons with no count beside them stay two icons. + check([1, 1], [at(100), at(110)], [1, 1]); + // A count takes every lone camera it touches, on either side. + check([1, 9, 1], [at(70), at(100), at(130)], [11]); + // A lone camera that only touches another lone camera is left alone. + check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index e78810b87a..0b0be24703 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -332,6 +332,43 @@ test('a crowded cell shows its count and a singleton keeps its icon', () => { ); }); +test('a lone camera beside a count joins it, unless it is the active camera', () => { + // Three cameras north of a cell boundary, one 111 m away south of it. + const { records } = recordsAt([ + [0.0005, 0.0005], + [0.0006, 0.0005], + [0.0007, 0.0005], + [0.0006, -0.0005], + [0.2, 0], + ]); + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-4']); + assert.deepEqual(_viewRecordIdsForTest(), ['cam-4']); + assert.deepEqual( + markers().map((item) => item.cell.count), + [4], + ); + assert.deepEqual( + cctvLayer.getDetectableObjects().map((o) => o.sourceId), + ['cam-4'], + ); + // The picker still offers one camera from each ground cell. + assert.equal(cctvLayer.getUIState().cameraIndex.length, 3); + + seedCoverage({ + viewer: viewerAt(20_000), + records, + activeCameraId: 'cam-3', + }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-3', 'cam-4']); + assert.deepEqual( + markers().map((item) => item.cell.count), + [3], + ); +}); + test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ @@ -698,20 +735,22 @@ test('overlapping cells merge at their weighted centre and keep every camera in }); refreshHorizonCulling(); const shown = markers(); - assert.deepEqual(shownIds(records), ['cam-7', 'cam-8']); + // The lone camera 111 m south sits under the merged marker and joins it; + // the active one beside it keeps its own icon. + assert.deepEqual(shownIds(records), ['cam-7']); assert.equal( shown.reduce((sum, m) => sum + m.cell.count, 0), - 7, + 8, ); assert.deepEqual( shown.map((m) => m.cell.count).sort((a, b) => a - b), - [2, 5], + [2, 6], ); - const merged = shown.find((m) => m.cell.count === 5); + const merged = shown.find((m) => m.cell.count === 6); assert.ok( Cesium.Cartesian3.distance( merged.pos, - Cesium.Cartesian3.fromDegrees(0.0008, 0, 10), + Cesium.Cartesian3.fromDegrees(0.004 / 6, -0.001 / 6, 10), ) < 0.01, ); const positions = shown.map((m) => [m.cell.key, m.pos, m.height, m.width]); @@ -720,13 +759,10 @@ test('overlapping cells merge at their weighted centre and keep every camera in clickMarker(merged); const { bounds } = flights.at(-1); assert.ok( - records - .slice(0, 5) - .every( - (r) => - Cesium.Cartesian3.distance(r.position, bounds.center) < - bounds.radius, - ), + [...records.slice(0, 5), records[8]].every( + (r) => + Cesium.Cartesian3.distance(r.position, bounds.center) < bounds.radius, + ), ); assert.ok( bounds.radius < 300, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index b6f38e7fe7..84831c12d4 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -19,6 +19,7 @@ import { COUNT_GLYPH_PADDING_PX, COUNT_LABEL_DROP, COUNT_MERGE_GAP_PX, + COUNT_SINGLE_ICON_PX, COUNT_MERGE_PASSES, } from './policy.js'; @@ -28,6 +29,10 @@ const GLYPH_ASPECT = 1.5; const RING_PX = 2; const RIM_PX = 1; const STROKE_INSET = RIM_PX + RING_PX / 2; +const SINGLE_ICON = Object.freeze({ + width: COUNT_SINGLE_ICON_PX, + height: COUNT_SINGLE_ICON_PX, +}); /** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ function rasterizeGlyph(canvas, image, size, dpr, color) { @@ -198,9 +203,9 @@ export function createCountMarkers( /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ function update(cells, project) { - let visible = cells - .filter((cell) => cell.count > 1) - .sort((a, b) => a.key.localeCompare(b.key)); + // Lone cameras take part so that one beside a count joins it. + let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); + const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); for ( let pass = 0; pass < COUNT_MERGE_PASSES && visible.length > 1; @@ -209,12 +214,17 @@ export function createCountMarkers( const merged = mergeCountCells( visible, project, - sizeFor, + footprint, COUNT_MERGE_GAP_PX, ); if (merged.length === visible.length) break; visible = merged; } + // A lone camera that is no longer its own entry now counts in a marker. + const apart = new Set(visible); + for (const cell of cells) + if (cell.count === 1) cell.absorbed = !apart.has(cell); + visible = visible.filter((cell) => cell.count > 1); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 17ed1ae561..06fc5788fd 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -104,6 +104,10 @@ export const COUNT_LABEL_DROP = 0.2; // Minimum gap between the outer rims of two separate markers. export const COUNT_MERGE_GAP_PX = 4; +// On-screen size of a lone camera's icon when testing it against a count +// marker: an icon closer than the merge gap joins that count. +export const COUNT_SINGLE_ICON_PX = 24; + // Recheck moved centres and wider labels while bounding work on motion ticks. export const COUNT_MERGE_PASSES = 3; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index c794519295..2d50592ac3 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -435,23 +435,26 @@ export function createRendering({ cell.rank = rank; } } + // Marks each lone camera that a count marker beside it has taken in. + layerState._counts?.update(visibleCells, project); for (const cell of visibleCells) { const record = cell.winner; picker.push(record); record.pickerPass = pass; - if (cell.count === 1) { + if (cell.count === 1 && !cell.absorbed) { 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); + const grouped = Boolean( + cell?.winner && (cell.count > 1 || cell.absorbed), + ); if (grouped !== !!record.viewGrouped) { const id = record.camera.id; coverageChanged ||= layerState._coverageCohort?.has(id); From 2e18673df89e52644da634967239f11b018b5ae8 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 00:03:34 +0400 Subject: [PATCH 10/56] fix(cctv): stand cameras and count markers on the drawn terrain When the terrain height batch loses a chunk to the rate limit, the cameras in it keep a sea-level fallback height. In the mountains that put them far under the surface, so the view pass judged them by a point that was not where they are drawn: a tilted view dropped the count marker, a click on the marker framed empty ground, and icons drifted on tilt and pan. - A camera with no real ground height takes the height of the terrain the globe draws once it is near the screen (up to 300 reads a pass, through the height service), and a later answer from the batch replaces it. - A count marker is anchored to the drawn terrain under its centre, and a click frames that ground. - Cameras on one mount draw side by side, 30 px apart, each with its own callout, instead of as one icon with several callouts. The photoreal map stack is not covered: terrain is not the surface there. --- changelog.d/1808-cctv-camera-counts.md | 5 +- docs/CURRENT-STATE.md | 12 +- src/data/cctvCellCounts.js | 28 +++- src/data/cctvViewThinning.test.mjs | 187 ++++++++++++++++++++++++- src/layers/cctv/controls.js | 3 +- src/layers/cctv/countMarkers.js | 25 +++- src/layers/cctv/ground.js | 115 +++++++++------ src/layers/cctv/policy.js | 8 ++ src/layers/cctv/rendering.js | 139 ++++++++++++++++-- 9 files changed, 453 insertions(+), 69 deletions(-) diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 8de3034801..6b565362f9 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -5,4 +5,7 @@ whose icon would sit against it, and a click zooms in until the group splits. The camera layer's colour is now green: count markers and idle single cameras share it, the active camera stays gold and live-video cameras - stay violet (gekh, #1808). + stay violet. Cameras that share one mount draw side by side instead of as + one icon with several callouts, and a camera the terrain height service + never answered for stands on the drawn terrain instead of drifting under + it (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index a6069e262b..585f3e1138 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1958,7 +1958,17 @@ a small green camera pictogram under its top edge and the count just below its middle. The marker grows with the count and is drawn on the world overlay at the same resolution as camera callouts. A lone camera whose icon would sit within 4 px of a marker is counted in that marker instead of being drawn; the -active camera always keeps its own icon. +active camera always keeps its own icon. On a globe map a marker stands on +the drawn terrain under its cameras' mean position, and a click frames that +ground. A camera the terrain height batch never answered for (no prior, or +the geoid fallback a failed or rate-limited chunk leaves) takes the terrain +the globe draws under it as its ground once it is near the screen, up to 300 +cameras a view pass, and reads it again from less than half as far; a batch +answer that arrives later replaces it. Without this such a camera sits near +sea level, drifts across mountain terrain as the view tilts or pans, and +never leaves its count. Cameras on one mount (the same point to about a +metre) draw side by side, 30 px apart, once they show as icons; their records +keep the mount's position. The count includes cameras beyond the screen edge and excludes cameras beyond the horizon. Counts that would overlap on screen merge into one that carries their sum. Clicking a count zooms to its group. Single cameras keep their icons, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index bf746f6e1a..bbafd051ad 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -43,12 +43,28 @@ export function addCellCamera(cell, camera) { cell.high = Math.max(cell.high, height); } -/** Geographic mean on the globe surface at the mean mount height. */ +/** Mean longitude and latitude of a cell's mounts, in degrees. */ +export function cellLonLat(cell) { + return { + lon: cell.lonSum / (1e7 * cell.count), + lat: cell.latSum / (1e7 * cell.count), + }; +} + +/** + * Geographic mean of the mounts. Its height is the drawn ground under it + * when the cell carries one (`groundM`), since a camera nobody has looked at + * yet may still hold a catalog height far from the terrain; otherwise the + * mean mount height. + */ export function cellCenter(cell) { + const { lon, lat } = cellLonLat(cell); return fromDegrees( - cell.lonSum / (1e7 * cell.count), - cell.latSum / (1e7 * cell.count), - cell.heightSum / (100 * cell.count), + lon, + lat, + Number.isFinite(cell.groundM) + ? cell.groundM + : cell.heightSum / (100 * cell.count), ); } @@ -56,7 +72,9 @@ export function cellCenter(cell) { 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; + const height = Number.isFinite(cell.groundM) + ? cell.groundM + : (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. diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 0b0be24703..7293e1aac8 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -55,7 +55,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, flights = []) { +function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); const down = Cesium.Cartesian3.normalize( Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), @@ -84,6 +84,7 @@ function viewerAt(heightM, lonDeg = 0, flights = []) { bindRenderer(viewer, { camera: port, canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + ...ports, }), ); return viewer; @@ -369,6 +370,190 @@ test('a lone camera beside a count joins it, unless it is the active camera', () ); }); +test('cameras the height batch never answered for take the drawn terrain', () => { + // Two mounts on one pole in the mountains and a lone camera. The batch + // answered for none of them, so they hold the catalog height (10 m), far + // under the terrain; a fourth camera has its answer and keeps it. + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.2, 0], + [0.3, 0], + ]); + // A failed chunk leaves the geoid fallback; a real answer is 'reearth'. + records[2].groundPrior = { ellipsoid: -20, source: 'geoid-fallback' }; + records[3].groundPrior = { ellipsoid: 2, source: 'reearth' }; + const flights = []; + const samples = []; + let terrain = 1872.4; + let globeShown = true; + const ports = { + globe: { isGlobeVisible: () => globeShown }, + query: { + sampleHeightNow(point, options) { + samples.push([point, options]); + return terrain; + }, + }, + }; + const heightOf = (position) => + Cesium.Cartographic.fromCartesian(position).height; + const icon = (i) => _cctvIconsForTest().item(records[i].camera.id); + seedCoverage({ viewer: viewerAt(20_000, 0, flights, ports), records }); + + // The photoreal stack hides the globe: terrain is not the surface there. + globeShown = false; + refreshHorizonCulling(); + assert.equal(samples.length, 0); + assert.ok(Math.abs(heightOf(records[0].position) - 10) < 0.01); + + // Terrain that has not loaded leaves a camera where it is, to be read again. + globeShown = true; + terrain = null; + refreshHorizonCulling(); + assert.ok(samples.length >= 3); + assert.ok(samples.every(([, options]) => options.against === 'terrain')); + assert.equal(records[0].groundPrior, undefined); + assert.ok(Math.abs(heightOf(markers()[0].pos) - 10) < 0.01); + + terrain = 1872.4; + refreshHorizonCulling(); + // Each unanswered camera stands its mount height above the drawn terrain. + for (const i of [0, 1, 2]) { + assert.equal(records[i].groundPrior.source, 'drawn-terrain'); + assert.ok(Math.abs(records[i].camera.absoluteHeightM - 1880.4) < 1e-9); + assert.ok(Math.abs(heightOf(records[i].position) - 1880.4) < 0.01); + assert.ok(Math.abs(heightOf(icon(i).pos) - 1880.4) < 0.01); + } + // The answered one is left alone. + assert.equal(records[3].groundPrior.source, 'reearth'); + assert.ok(Math.abs(heightOf(records[3].position) - 10) < 0.01); + // The count stands on the terrain and its click frames the ground there. + const [marker] = markers(); + assert.equal(marker.cell.count, 2); + assert.ok(Math.abs(heightOf(marker.pos) - 1872) < 0.01); + clickMarker(marker); + assert.ok(Math.abs(heightOf(flights.at(-1).bounds.center) - 1872) < 0.01); + + // Read once: the same view does not read a camera's terrain again. + samples.length = 0; + refreshHorizonCulling(); + assert.ok(samples.every(([point]) => Math.abs(point.lat - 0.0005) < 1e-9)); + + // From less than half as far the finer terrain is read and replaces it. + terrain = 1890; + seedCoverage({ viewer: viewerAt(9_000, 0, flights, ports), records }); + refreshHorizonCulling(); + assert.ok(Math.abs(records[0].camera.absoluteHeightM - 1898) < 1e-9); + assert.equal(records[3].groundPrior.source, 'reearth'); +}); + +test('a tilted view keeps the count of cameras that stood under the terrain', () => { + // The same pole seen from 200 m above the terrain and 1 km away, a view + // 11 degrees below the horizontal. Projected from its catalog height the + // pole falls below the padded screen and its count vanishes; on the + // terrain it is in the middle of the view. + const { records } = recordsAt([ + [0, 0], + [0, 0], + ]); + const ground = 1872; + const eye = Cesium.Cartesian3.fromDegrees(0, -0.009, ground + 200); + const target = Cesium.Cartesian3.fromDegrees(0, 0, ground); + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + const plain = ({ x, y, z }) => ({ x, y, z }); + const { port } = fakeCameraPort({ + pose: { + lon: 0, + lat: -0.009, + height: ground + 200, + position: plain(eye), + direction: plain(direction), + up: plain(up), + right: plain(right), + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, + }, + }); + let terrain = null; + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, + canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + globe: { isGlobeVisible: () => true }, + query: { sampleHeightNow: () => terrain }, + }), + ); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal(markers().length, 0, 'under the terrain it is off the screen'); + terrain = ground; + refreshHorizonCulling(); + assert.deepEqual( + markers().map((item) => item.cell.count), + [2], + ); +}); + +test('cameras on one mount draw side by side once they show as icons', () => { + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + // Close enough that every camera shows: about 0.87 m a pixel. + seedCoverage({ viewer: viewerAt(460), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), ['cam-0', 'cam-1', 'cam-2']); + const icons = _cctvIconsForTest(); + const [a, b, c] = records.map((record) => icons.item(record.camera.id).pos); + // 30 px apart along the screen's horizontal, centred on the shared mount. + const metres = Cesium.Cartesian3.distance(a, b); + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; + assert.ok(Math.abs(metres / metresPerPixel - 30) < 0.5); + const middle = Cesium.Cartesian3.midpoint(a, b, new Cesium.Cartesian3()); + assert.ok(Cesium.Cartesian3.distance(middle, records[0].position) < 1e-6); + // The third camera, 11 m away, has a mount of its own. + assert.ok(Cesium.Cartesian3.distance(c, records[2].position) < 1e-6); + // The records keep the mount; callouts follow the drawn icons. + assert.ok( + Cesium.Cartesian3.distance(records[0].position, records[1].position) < 1e-9, + ); + const callouts = cctvLayer.getDetectableObjects(); + for (const [i, pos] of [a, b].entries()) { + const callout = callouts.find((o) => o.sourceId === `cam-${i}`); + assert.ok(Cesium.Cartesian3.distance(callout.position, pos) < 1e-9); + } + // An unchanged view writes nothing more. + const before = [a, b]; + refreshHorizonCulling(); + assert.equal(icons.item('cam-0').pos, before[0]); + assert.equal(icons.item('cam-1').pos, before[1]); + + // Grouped again, both icons are back on the mount for their next showing. + seedCoverage({ viewer: viewerAt(20_000), records }); + refreshHorizonCulling(); + assert.deepEqual(shownIds(records), []); + for (const i of [0, 1]) + assert.ok( + Cesium.Cartesian3.distance( + _cctvIconsForTest().item(`cam-${i}`).pos, + records[i].position, + ) < 1e-6, + ); +}); + test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ diff --git a/src/layers/cctv/controls.js b/src/layers/cctv/controls.js index 1f83b7468a..09ba71f72b 100644 --- a/src/layers/cctv/controls.js +++ b/src/layers/cctv/controls.js @@ -219,7 +219,8 @@ export function createControls({ state: layerState, services, parts, source }) { for (let i = start; i < records.length; i += stride) { const camera = records[i].camera; objects.push({ - position: records[i].position, + // A camera sharing its mount is drawn beside its mates. + position: records[i].spreadPosition ?? records[i].position, sourceId: camera.id, // Short semantic code where the id is opaque (see cameraDisplayCode). id: `CAM-${camera.code || camera.id}`, diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 84831c12d4..89fa278bb5 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -1,5 +1,6 @@ import { cellCenter, + cellLonLat, formatCameraCount, mergeCountCells, } from '../../data/cctvCellCounts.js'; @@ -201,16 +202,32 @@ export function createCountMarkers( }; } - /** Reuse marker slots in ground-key order, and invalidate only changed frames. */ - function update(cells, project) { + /** + * Reuse marker slots in ground-key order, and invalidate only changed frames. + * `groundHeight(lon, lat)` answers the drawn terrain height in metres, or + * null where it is not loaded; with it a count stands on the ground it + * marks whatever heights its cameras hold. + */ + function update(cells, project, groundHeight = null) { // Lone cameras take part so that one beside a count joins it. let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); + /** A lone camera keeps its icon's own position; a count goes to ground. */ + const ground = (list) => { + if (!groundHeight) return; + for (const cell of list) { + if (cell.count === 1 || cell.groundM !== undefined) continue; + const { lon, lat } = cellLonLat(cell); + const height = groundHeight(lon, lat); + cell.groundM = Number.isFinite(height) ? Math.round(height) : null; + } + }; for ( let pass = 0; pass < COUNT_MERGE_PASSES && visible.length > 1; pass++ ) { + ground(visible); const merged = mergeCountCells( visible, project, @@ -225,6 +242,7 @@ export function createCountMarkers( for (const cell of cells) if (cell.count === 1) cell.absorbed = !apart.has(cell); visible = visible.filter((cell) => cell.count > 1); + ground(visible); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; @@ -236,7 +254,8 @@ export function createCountMarkers( last.count !== cell.count || last.latSum !== cell.latSum || last.lonSum !== cell.lonSum || - last.heightSum !== cell.heightSum + last.heightSum !== cell.heightSum || + last.groundM !== cell.groundM ) { marker.pos = cellCenter(cell); changed = true; diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 0b57cba135..84db00b13e 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -214,56 +214,82 @@ export function createGround({ state: layerState, services, parts, source }) { let applied = 0; let moved = 0; for (let i = 0; i < records.length && i < priors.length; i++) { - const record = records[i]; - const prior = priors[i]; - if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue; - // Stale-record guard: init() may have re-run (destroy/init cycle) while - // the batch was in flight — only touch records still live in the map. - if (layerState._recordById.get(record.camera.id) !== record) continue; - record.groundPrior = prior; - // Keep the cheap pre-enable altitude consistent for records whose - // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). - if (!record.frustumPositions) { - record.camera.absoluteHeightM = - prior.ellipsoid + record.camera.mountHeightM; - } - // Cameras without geometry only move their icon onto the prior, so the - // view pass projects the right point; their frustums are built when - // they enter the view, as recomputing the whole catalog here would - // stall a large one. - if (!record.frustumGeometry) { - if (record.position) { - // In place: the record keeps its position object. - const { x, y, z } = fromDegrees( - record.camera.lon, - record.camera.lat, - record.camera.absoluteHeightM, - ); - record.position.x = x; - record.position.y = y; - record.position.z = z; - parts.rendering.moveCameraIcon(record); - moved += 1; - } - continue; - } - const regime = currentSurfaceRegime(); - if (regime === 'terrain-globe') { - // Prior IS the resolution — re-latch onto the fresh value. - parts.geometry.updateRecordGeometry(record, { sampleGround: false }); - applied += 1; - } else if (!Number.isFinite(record.groundSamples['google-3d'])) { - // Still awaiting the shared floor: snap interim geometry onto the exact - // prior (pure recompute; the shared cell may refine later). - parts.geometry.applyFrustumGeometry(record, prior.ellipsoid); - applied += 1; - } + const outcome = applyGroundPrior(records[i], priors[i]); + if (outcome === 'moved') moved += 1; + else if (outcome === 'applied') applied += 1; } if (moved && parts.rendering.refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); if (applied || moved) parts.presentation.notifyListeners(); } + /** + * Gives one live record a ground prior: `'moved'` when only its icon went + * onto the prior in place, `'applied'` when its geometry was recomputed, + * null when nothing changed. Pure recomputes, no scene queries. + */ + function applyGroundPrior(record, prior) { + if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null; + // Stale-record guard: init() may have re-run (destroy/init cycle) while + // the batch was in flight — only touch records still live in the map. + if (layerState._recordById.get(record.camera.id) !== record) return null; + record.groundPrior = prior; + // Keep the cheap pre-enable altitude consistent for records whose + // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). + if (!record.frustumPositions) { + record.camera.absoluteHeightM = + prior.ellipsoid + record.camera.mountHeightM; + } + // Cameras without geometry only move their icon onto the prior, so the + // view pass projects the right point; their frustums are built when + // they enter the view, as recomputing the whole catalog here would + // stall a large one. + if (!record.frustumGeometry) { + if (!record.position) return null; + // In place: the record keeps its position object. + const { x, y, z } = fromDegrees( + record.camera.lon, + record.camera.lat, + record.camera.absoluteHeightM, + ); + record.position.x = x; + record.position.y = y; + record.position.z = z; + parts.rendering.moveCameraIcon(record); + return 'moved'; + } + const regime = currentSurfaceRegime(); + if (regime === 'terrain-globe') { + // Prior IS the resolution — re-latch onto the fresh value. + parts.geometry.updateRecordGeometry(record, { sampleGround: false }); + return 'applied'; + } + if (!Number.isFinite(record.groundSamples['google-3d'])) { + // Still awaiting the shared floor: snap interim geometry onto the exact + // prior (pure recompute; the shared cell may refine later). + parts.geometry.applyFrustumGeometry(record, prior.ellipsoid); + return 'applied'; + } + return null; + } + + /** + * A camera the height batch never answered for (a failed or rate-limited + * chunk leaves it on the catalog's fabricated ground) takes the terrain + * the globe draws under it as its prior, so that it stands on the surface + * the user sees. `rangeM` is how far the eye was when the terrain was + * read: a closer look reads finer terrain and replaces it, and so does a + * batch answer that arrives later. + * @returns {'moved'|'applied'|null} As `applyGroundPrior`. + */ + function adoptDrawnGround(record, heightM, rangeM) { + return applyGroundPrior(record, { + ellipsoid: heightM, + source: 'drawn-terrain', + rangeM, + }); + } + /** * Task 5: surface-regime change handler ('gev:map-stack-changed' * CustomEvent, dispatched by main.js from MapStackController.onChange). The @@ -399,6 +425,7 @@ export function createGround({ state: layerState, services, parts, source }) { resolveCommittedGroundAnchor, resolveGroundPriors, applyLateGroundPriors, + adoptDrawnGround, handleMapStackChanged, }; } diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 06fc5788fd..87fdaf4c32 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -71,6 +71,14 @@ export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; +// Cameras on one mount (the same point to about a metre) draw side by side, +// this many pixels apart, once they show as icons. +export const VIEW_SITE_SPREAD_PX = 30; + +// Cameras without a ground height that one view pass may read from the drawn +// terrain. The rest wait for the next pass. +export const VIEW_GROUND_READS = 300; + // Diameter at one camera before applying the size limits, in CSS pixels. export const COUNT_BASE_PX = 38; diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 2d50592ac3..a2d5a7663c 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -17,6 +17,8 @@ import { VIEW_CELL_PX, VIEW_ICON_MARGIN, VIEW_MIN_CELL_M, + VIEW_SITE_SPREAD_PX, + VIEW_GROUND_READS, } from './policy.js'; import { createIconBook } from '../../render/motion/iconBook.js'; import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js'; @@ -27,6 +29,7 @@ import { findGlobe, findQuery, } from '../../render/rendererOf.js'; +import { heightsOf } from '../../queries/heights.js'; import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js'; import { eastNorthUp } from '../../geo/frames.js'; import { poseProjector } from '../../geo/frustum.js'; @@ -383,6 +386,16 @@ export function createRendering({ const picker = []; const cells = new Map(); const visibleCells = []; + // The terrain the globe draws, where it is the surface (not on the + // photoreal stack) and loaded: null elsewhere. + const heights = heightsOf(layerState._viewer); + const groundHeight = + findQuery(layerState._viewer) && + findGlobe(layerState._viewer)?.isGlobeVisible?.() === true + ? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' }) + : null; + let groundReads = groundHeight ? VIEW_GROUND_READS : 0; + const regrounded = []; for (const record of layerState._records) { const position = record.position; if (!position) continue; @@ -397,20 +410,49 @@ export function createRendering({ (vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared ) continue; - const screen = project(position); + let screen = project(position); + let range = distance(position, viewer); + // A camera the height batch never answered for (no prior, or the + // geoid fallback a failed chunk leaves) sits near sea level, which can + // be kilometres under the terrain: it would project to the wrong + // place, drift as the view moves and measure too far for its cell. + // Anywhere near the screen, it takes the drawn terrain. + const prior = record.groundPrior; + const drawn = prior?.source === 'drawn-terrain'; + if ( + groundReads > 0 && + (!prior || + prior.source === 'geoid-fallback' || + (drawn && prior.rangeM > 2 * range)) && + screen && + screen.x >= -width && + screen.x <= 2 * width && + screen.y >= -height && + screen.y <= 2 * height + ) { + groundReads--; + const ground = groundHeight(record.camera.lon, record.camera.lat); + if (Number.isFinite(ground)) { + if (drawn && Math.abs(ground - prior.ellipsoid) < 1) { + prior.rangeM = range; + } else if (record.frustumGeometry) { + // Recomputing geometry writes draw sets: after this pass. + regrounded.push([record, ground, range]); + } else if ( + parts.ground.adoptDrawnGround(record, ground, range) === 'moved' + ) { + screen = project(position); + range = distance(position, viewer); + } + } + } 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; - const cellM = - VIEW_CELL_PX * - metresPerPixelPerMetre * - Math.sqrt(dx * dx + dy * dy + dz * dz); + const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range; if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) { if (!nearScreen) continue; record.viewPass = record.pickerPass = pass; @@ -435,8 +477,10 @@ export function createRendering({ cell.rank = rank; } } - // Marks each lone camera that a count marker beside it has taken in. - layerState._counts?.update(visibleCells, project); + // A count stands on the drawn terrain too: its cell may be too far for + // its cameras to have been read. Marks each lone camera that a count + // marker beside it has taken in. + layerState._counts?.update(visibleCells, project, groundHeight); for (const cell of visibleCells) { const record = cell.winner; picker.push(record); @@ -446,6 +490,7 @@ export function createRendering({ shown.push(record); } } + spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; let cardsChanged = false; @@ -462,12 +507,21 @@ export function createRendering({ layerState._cardIds?.has(id) || layerState._hoverCardId === id; } record.viewGrouped = grouped; - const item = patchedCameraIcon(record.camera.id, { - show: record.viewPass === pass, - }); + const fields = { show: record.viewPass === pass }; + if (record.spreadPass === pass) { + const drawn = layerState._icons?.item(record.camera.id)?.pos; + if (!drawn || !samePoint(drawn, record.spreadPosition)) + fields.pos = copyPoint(record.spreadPosition); + } else if (record.spreadPosition) { + // No longer beside a mount mate: back onto its own position. + record.spreadPosition = null; + fields.pos = copyPoint(record.position); + } + const item = patchedCameraIcon(record.camera.id, fields); if (item) writes.push(item); } writeCameraIcons(writes); + if (regrounded.length) queueMicrotask(() => reground(regrounded)); const previous = layerState._viewRecords; const changed = previous.length !== shown.length || @@ -483,6 +537,65 @@ export function createRendering({ return changed || pickerChanged; } + /** + * Cameras that have geometry take the drawn terrain after the pass that + * read it, then the view is passed again from their new positions. + */ + function reground(entries) { + let changed = false; + for (const [record, ground, range] of entries) + changed = + parts.ground.adoptDrawnGround(record, ground, range) !== null || + changed; + if (!changed) return; + if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); + parts.presentation.notifyListeners(); + } + + /** + * Cameras on one mount would draw as one icon with several callouts. Among + * the cameras shown, those that share a point to about a metre get draw + * positions side by side along the screen's horizontal, in id order, + * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The + * record's own position is untouched: geometry and cards keep the mount. + */ + function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { + const { right, direction, position: eye } = pose; + if (!right || !direction || shown.length < 2) return; + const mounts = new Map(); + for (const record of shown) { + const { lat, lon } = record.camera; + const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`; + const mates = mounts.get(key); + if (mates) mates.push(record); + else mounts.set(key, [record]); + } + for (const mates of mounts.values()) { + if (mates.length < 2) continue; + mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id)); + for (let i = 0; i < mates.length; i++) { + const record = mates[i]; + const p = record.position; + // A pixel's width on the ground grows with depth along the view. + const depth = + (p.x - eye.x) * direction.x + + (p.y - eye.y) * direction.y + + (p.z - eye.z) * direction.z; + const metres = + (i - (mates.length - 1) / 2) * + VIEW_SITE_SPREAD_PX * + metresPerPixelPerMetre * + depth; + record.spreadPosition = { + x: p.x + right.x * metres, + y: p.y + right.y * metres, + z: p.z + right.z * metres, + }; + record.spreadPass = pass; + } + } + } + /** * Canvas coordinates for world positions, from the eye's pose by the * renderer's perspective projection (geo/frustum.js): one pose read per From 81fe7f88cc7bb0b3b39b6c9463fafabef4ecd63c Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 03:07:04 +0400 Subject: [PATCH 11/56] fix(cctv): settle the review of the count markers Bugs: - Cameras on one mount stay side by side after their geometry is built, so a click or a settled view no longer folds them back into one icon. - A count click yields to a card drawn over the marker and to another layer's object under it, waits while the cockpit or tracking holds the view, and flies at most halfway, so a long chain of cameras still splits. - The active camera's icon is never covered by a count, transparent corners of the marker no longer catch clicks, and a count hidden under the HUD keeps its lone cameras. - A lone camera joins only its nearest count and never bridges two; cameras close enough to draw as icons take part too, at their drawn icon size. - Groups across the antimeridian keep their longitude; the flight frames the highest mount; markers on ground below the ellipsoid stay visible; counts fade outside the Scope circle. - Mounts less than a metre apart count as one mount. - A drawn-terrain height survives a late fallback answer, is read for an unresolved camera and for one projected off the window, is re-read when the terrain under it finishes loading or the terrain source changes, and the read budget no longer goes to the same misses each pass. Cleanup: the glyph draws from one green SVG sprite instead of recolouring pixels, marker-only constants move next to their use, layout tests check behaviour rather than formulas, and docs and comments match the code. docs/I18N.md names the one fixed notation of count badges as an exception. --- changelog.d/1808-cctv-camera-counts.md | 19 +- docs/CURRENT-STATE.md | 47 +- docs/I18N.md | 1 + scripts/format-scope.json | 3 + scripts/package-boundaries.json | 1 + src/app/layers/cctv.js | 3 +- src/data/cameraFraming.js | 2 +- src/data/cctv.test.mjs | 4 +- src/data/cctvCellCounts.js | 114 +++-- src/data/cctvCellCounts.test.mjs | 139 ++++-- src/data/cctvViewPass.test.mjs | 254 +++++++++++ src/data/cctvViewThinning.test.mjs | 572 ++++++++++++++++--------- src/layers/cctv/countMarkers.js | 284 ++++++------ src/layers/cctv/countMarkers.test.mjs | 136 ++++++ src/layers/cctv/ground.js | 28 +- src/layers/cctv/ground.test.mjs | 64 +++ src/layers/cctv/lifecycle.js | 34 +- src/layers/cctv/lifecycle.test.mjs | 34 ++ src/layers/cctv/navigation.js | 33 +- src/layers/cctv/policy.js | 106 +++-- src/layers/cctv/presentation.js | 19 +- src/layers/cctv/rendering.js | 261 ++++++++--- src/layers/cctv/rendering.test.mjs | 1 + src/layers/cctv/selection.js | 28 +- src/layers/cctv/selection.test.mjs | 47 ++ src/layers/cctv/state.js | 12 +- 26 files changed, 1608 insertions(+), 638 deletions(-) create mode 100644 src/data/cctvViewPass.test.mjs create mode 100644 src/layers/cctv/countMarkers.test.mjs create mode 100644 src/layers/cctv/ground.test.mjs diff --git a/changelog.d/1808-cctv-camera-counts.md b/changelog.d/1808-cctv-camera-counts.md index 6b565362f9..7c87538cd1 100644 --- a/changelog.d/1808-cctv-camera-counts.md +++ b/changelog.d/1808-cctv-camera-counts.md @@ -1,11 +1,8 @@ -- Show how many cameras stand behind a thinned CCTV marker. Zoomed out, a - ground cell with two or more cameras is one round marker with a small camera - icon and the count (`999`, `1.7K`, `12K` in every language); it grows with - the count, merges with a neighbour it would overlap, takes in a lone camera - whose icon would sit against it, and a click zooms in until the group - splits. The camera layer's colour is now green: count markers and idle - single cameras share it, the active camera stays gold and live-video cameras - stay violet. Cameras that share one mount draw side by side instead of as - one icon with several callouts, and a camera the terrain height service - never answered for stands on the drawn terrain instead of drifting under - it (gekh, #1808). +- Zoomed out, a CCTV ground cell with two or more cameras is now one round + marker with a camera icon and the count (`999`, `1.7K`, `12K` in every + language). It grows with the count, merges with markers it would overlap, + takes in a lone camera right beside it, and zooms in on click until the + group splits. Idle cameras and markers are green. The active camera stays + amber and video cameras violet. Cameras on one mount draw side by side, and + a camera the terrain height service never answered for stands on the drawn + terrain (gekh, #1808). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 585f3e1138..cef2a2699d 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1953,32 +1953,27 @@ accepts forwarding headers, so cameras work behind a reverse proxy; a forwarded request skips the key-bearing Street View fallback and gets the placeholder. The CCTV layer draws only the cameras on or near the screen. Zoomed out, a -ground cell containing multiple cameras shows, at their centre, a marker with -a small green camera pictogram under its top edge and the count just below its -middle. The marker grows with the count and is drawn on the world overlay at -the same resolution as camera callouts. A lone camera whose icon would sit -within 4 px of a marker is counted in that marker instead of being drawn; the -active camera always keeps its own icon. On a globe map a marker stands on -the drawn terrain under its cameras' mean position, and a click frames that -ground. A camera the terrain height batch never answered for (no prior, or -the geoid fallback a failed or rate-limited chunk leaves) takes the terrain -the globe draws under it as its ground once it is near the screen, up to 300 -cameras a view pass, and reads it again from less than half as far; a batch -answer that arrives later replaces it. Without this such a camera sits near -sea level, drifts across mountain terrain as the view tilts or pans, and -never leaves its count. Cameras on one mount (the same point to about a -metre) draw side by side, 30 px apart, once they show as icons; their records -keep the mount's position. -The count includes cameras beyond the screen edge and excludes cameras beyond -the horizon. Counts that would overlap on screen merge into one that carries -their sum. Clicking a count zooms to its group. Single cameras keep their icons, -and the active camera has its own icon and is excluded from the count. Close -up, even co-located cameras show individually. Ambient cards and coverage -attach to individual cameras. Ground placement has at most two attempts per -camera and view regime. The view pass reruns while the camera moves, paced by -its own cost. The camera picker lists the active camera first, keeps one -representative per visible cell, preferring healthy feeds, and closes with -the count of cameras outside the view. +ground cell with two or more cameras shows one marker at their mean position. A +green camera pictogram sits under its top edge and the count just below its +middle. The marker grows with the count and paints on the world overlay at +callout resolution. The count covers the whole cell up to the horizon, including +its off-screen cameras. Overlapping markers merge and add their counts. A lone +camera whose icon would touch a marker joins the nearest one, unless the HUD +hides that marker. The active camera keeps its own icon beside any marker that +would cover it and stays out of the count. A click on a marker zooms in on its +group, at least halving the distance each time. The view stays put while the +cockpit or a tracked object holds it. Ambient cards and coverage attach only to +cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A +camera the height batch never answered for takes the drawn terrain as its ground +once it is near the screen. It reads that height again from much closer, once +the terrain in view has loaded, or when the terrain source changes. A later +Re:Earth answer replaces it. A fallback preserves it. Close up every camera +shows. Cameras on one mount draw side by side and their records keep the mount. +Ground placement has at most two attempts per camera and view regime. The view +pass reruns while the camera moves, paced by its own cost, and when the terrain +in view finishes loading. The camera picker lists the active camera first, then +one camera per visible cell, preferring healthy feeds. It ends with the count of +catalog cameras missing from the list. Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. diff --git a/docs/I18N.md b/docs/I18N.md index 4799cded25..efad640373 100644 --- a/docs/I18N.md +++ b/docs/I18N.md @@ -107,6 +107,7 @@ Call it before views render. `onLocaleChange` listeners word their text again at - **Translate the label, not the value.** Layer ids, enums, share-link parameters, API fields, voice tool schemas and feed data (callsigns, vessel and place names) stay as they are; translate only the text shown for them. - **No `t()` at module top level.** Keep the English in `msg()` and call `t()` when rendering. - **Numbers and dates** go through `formatNumber`, `formatDate`, `formatRelativeTime` and `formatUtcDayMonth` from `src/i18n/index.js`, which follow the active language. + Compact CCTV count badges painted on the map use Latin digits, a decimal point and a `K` suffix for thousands (`999`, `1.7K`, `12K`). Each badge keeps its width and reads the same across locales. Format these badges only with `formatCameraCount` in `src/data/cctvCellCounts.js`. - **Identical English means identical translation,** unless you give it a context: `t('CLEAR', { context: 'action' })` (a button) is its own catalog entry, `action|CLEAR`, while `t('CLEAR')` (the sky) stays separate. English output is the same. - **Text that should stay English** (a brand, a code, a unit symbol) is simply not wrapped. diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 429862c7c7..ca63034fd1 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -626,6 +626,7 @@ "src/data/cctv.js", "src/data/cctvCatalogCap.test.mjs", "src/data/cctvCellCounts.test.mjs", + "src/data/cctvViewPass.test.mjs", "src/data/cctvViewThinning.test.mjs", "src/data/cctvDisplayCode.test.mjs", "src/data/cctvFootprint.js", @@ -645,6 +646,8 @@ "src/data/cctvTxdotSource.test.mjs", "src/layers/cctv/source.test.mjs", "src/layers/cctv/frames.test.mjs", + "src/layers/cctv/countMarkers.test.mjs", + "src/layers/cctv/ground.test.mjs", "src/layers/cctv/rendering.test.mjs", "src/data/alprCameras.js", "src/data/alprCameras.test.mjs", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 93ccb828cb..0a617d4732 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3282,6 +3282,7 @@ "src/data/cctvCards.js", "src/data/cctvGizmo.js", "src/data/cctvLod.js", + "src/data/cameraFraming.js", "src/data/cctvCellCounts.js", "src/layers/cctv/countMarkers.js", "src/data/cctvViewshed.js", diff --git a/src/app/layers/cctv.js b/src/app/layers/cctv.js index 99bf3fa6fd..8c599c6166 100644 --- a/src/app/layers/cctv.js +++ b/src/app/layers/cctv.js @@ -2,6 +2,7 @@ import { createCctvLayer } from '../../layers/cctv/index.js'; import * as credits from '../../data/dataCredits.js'; import * as sprites from '../../data/spriteOrder.js'; import * as activation from '../../cctvFocusRequest.js'; +import { keyholeLabelAlphaFromGeometry } from '../../celestialRing.js'; import * as overlays from '../../overlays/worldOverlay.js'; import { CITY_POIS } from '../../cityPois.js'; import * as picking from '../../data/pickRegistry.js'; @@ -17,7 +18,7 @@ export function createApplicationCctv({ surface, source }) { credits, sprites, activation, - overlays, + overlays: { ...overlays, keyholeAlpha: keyholeLabelAlphaFromGeometry }, locations: { CITY_POIS }, picking, terrain, diff --git a/src/data/cameraFraming.js b/src/data/cameraFraming.js index af2ee7fc5f..26ac769eea 100644 --- a/src/data/cameraFraming.js +++ b/src/data/cameraFraming.js @@ -1,4 +1,4 @@ -import { toRadians } from '../geo/index.js'; +import { toRadians } from '../geo/vector.js'; import { findCamera } from '../render/rendererOf.js'; /** The camera port's pose, or null when there is none to read. */ diff --git a/src/data/cctv.test.mjs b/src/data/cctv.test.mjs index fa9ee0eea1..a2306e6efd 100644 --- a/src/data/cctv.test.mjs +++ b/src/data/cctv.test.mjs @@ -87,6 +87,7 @@ import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, IDLE_CAMERA_COLOR, + IDLE_CAMERA_ICON, LIVE_CAMERA_COLOR, } from '../layers/cctv/policy.js'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; @@ -387,9 +388,8 @@ test('camera icons are violet for video feeds, green for stills, amber when acti assert.equal(icons.item(activeVideo.camera.id).scale, 1.25); assert.equal(icons.item(idleVideo.camera.id).scale, 1); const image = (record) => icons.item(record.camera.id).image; - assert.deepEqual(IDLE_CAMERA_COLOR, [93 / 255, 1, 143 / 255, 1]); const idleImage = image(idleStill); - assert.match(atob(idleImage.split(',')[1]), /stroke="#fff"/); + assert.equal(idleImage, IDLE_CAMERA_ICON); assert.equal(image(activeVideo), CAMERA_ICON); assert.equal(image(idleVideo), CAMERA_ICON); idleStill.camera.feedType = 'hls'; diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index bbafd051ad..9a551413a8 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -1,6 +1,6 @@ import { fromDegrees } from '../geo/ellipsoid.js'; -/** Exact camera counts below a thousand, then rounded thousands with a K suffix. */ +/** Exact below 1,000, then K with one decimal below 10K. Uses Latin digits in every locale. */ export function formatCameraCount(count) { if (count < 1000) return String(count); const thousands = @@ -43,10 +43,12 @@ export function addCellCamera(cell, camera) { cell.high = Math.max(cell.high, height); } +const wrapLongitude = (lon) => ((((lon + 180) % 360) + 360) % 360) - 180; + /** Mean longitude and latitude of a cell's mounts, in degrees. */ export function cellLonLat(cell) { return { - lon: cell.lonSum / (1e7 * cell.count), + lon: wrapLongitude(cell.lonSum / (1e7 * cell.count)), lat: cell.latSum / (1e7 * cell.count), }; } @@ -68,57 +70,62 @@ export function cellCenter(cell) { ); } -/** A padded sphere around the group's geographic rectangle and mount heights. */ +/** A padded sphere over the rectangle and every mount, centred at groundM + * when set, otherwise at the mid mount height. */ export function cellBounds(cell) { const lat = (cell.north + cell.south) / 2; - const lon = (cell.east + cell.west) / 2; + const lon = wrapLongitude((cell.east + cell.west) / 2); const height = Number.isFinite(cell.groundM) ? cell.groundM : (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 * + const halfWidth = + 0.5 * Math.hypot( (cell.east - cell.west) * 111_320 * Math.cos(parallel), (cell.north - cell.south) * 111_320, - cell.high - cell.low, ); + const vertical = Math.max(cell.high - height, height - cell.low); + const radius = 1.2 * Math.hypot(halfWidth, vertical); 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) { + // Across the antimeridian a cell joins on the side of the group's mean. + const shift = target.count + ? 360 * + Math.round( + (target.lonSum / target.count - cell.lonSum / cell.count) / 3.6e9, + ) + : 0; target.count += cell.count; target.latSum += cell.latSum; - target.lonSum += cell.lonSum; + target.lonSum += cell.lonSum + shift * 1e7 * cell.count; 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.west = Math.min(target.west, cell.west + shift); + target.east = Math.max(target.east, cell.east + shift); 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, gap) { +/** Visit the touching pills in this marker's bucket and its eight neighbors. */ +function visitNeighbors(marker, grid, gap, visit) { 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) { - // Lone cameras join a count beside them, never each other. - if (marker.cell.count === 1 && other.cell.count === 1) continue; // Distance between the horizontal centre segments of the two pills. const extra = marker.halfSegment + other.halfSegment; const dx = Math.max(0, Math.abs(marker.x - other.x) - extra); const dy = marker.y - other.y; const reach = marker.radius + other.radius + gap; if (dx * dx + dy * dy >= reach * reach) continue; - bucket.delete(other); - members.push(other); + visit(other, dx * dx + dy * dy, reach); } } } @@ -128,7 +135,8 @@ function collectNeighbors(marker, grid, members, gap) { * Merge connected groups of overlapping horizontal pills. Each marker occupies * one grid bucket. Even the widest pill can only touch its eight neighbors. * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and - * joins a count it touches; two such cells alone stay apart. + * joins the nearest count it touches. Lone cameras never join each other + * or bridge two counts. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { @@ -136,7 +144,7 @@ export function mergeCountCells(cells, project, sizeFor, gap) { let rowHeight = 0; const markers = cells.map((cell) => { const screen = project(cellCenter(cell)); - const { width, height } = sizeFor(cell.count); + const { width, height } = sizeFor(cell.count, cell); columnWidth = Math.max(columnWidth, width + gap); rowHeight = Math.max(rowHeight, height + gap); // The view projector reuses its result object. @@ -156,29 +164,57 @@ export function mergeCountCells(cells, project, sizeFor, gap) { const key = `${marker.col},${marker.row}`; if (!grid.has(key)) grid.set(key, new Set()); marker.bucket = grid.get(key); - marker.bucket.add(marker); + if (marker.cell.count > 1) marker.bucket.add(marker); + } + + for (const marker of markers) { + if (marker.cell.count !== 1 || !marker.bucket) continue; + let best = Infinity; + visitNeighbors(marker, grid, gap, (other, distanceSquared, reach) => { + const clearance = Math.sqrt(distanceSquared) - reach; + if (clearance < best) { + best = clearance; + marker.nearest = other; + } + }); + } + + // Only counts were candidates for nearest. Now they can claim lone cameras. + for (const marker of markers) + if (marker.cell.count === 1) marker.bucket?.add(marker); + + const members = []; + for (const seed of markers) { + if (seed.cell.count === 1 || !seed.bucket?.delete(seed)) continue; + members.length = 0; + members.push(seed); + for (const marker of members) { + if (marker.cell.count === 1) continue; + visitNeighbors(marker, grid, gap, (other) => { + if (other.cell.count === 1 && other.nearest !== marker) return; + other.bucket.delete(other); + members.push(other); + }); + } + if (members.length === 1) { + seed.result = seed.cell; + } else { + const group = createCameraCell(seed.cell.key); + group.lone = []; + for (const { cell } of members) { + addCell(group, cell); + if (cell.count === 1) group.lone.push(cell); + else if (cell.lone) group.lone.push(...cell.lone); + } + seed.result = group; + } } 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, gap); - - 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); - } + for (const marker of markers) { + if (marker.result) groups.push(marker.result); + else if (!marker.bucket || marker.bucket.has(marker)) + groups.push(marker.cell); } return groups; } diff --git a/src/data/cctvCellCounts.test.mjs b/src/data/cctvCellCounts.test.mjs index 66d9702c36..1a42b37280 100644 --- a/src/data/cctvCellCounts.test.mjs +++ b/src/data/cctvCellCounts.test.mjs @@ -12,7 +12,7 @@ import { mergeCountCells, } from './cctvCellCounts.js'; -test('camera counts use the same Latin digits and K notation in every UI language', () => { +test('camera counts use Latin digits and K notation whatever the UI language', () => { const previous = getLocale(); const examples = [ [2, '2'], @@ -27,11 +27,9 @@ test('camera counts use the same Latin digits and K notation in every UI languag [1000000, '1000K'], ]; try { - for (const locale of ['en', 'ru', 'ja', 'ar']) { - setLocale(locale); - for (const [count, label] of examples) - assert.equal(formatCameraCount(count), label, `${locale}: ${count}`); - } + setLocale('ar'); + for (const [count, label] of examples) + assert.equal(formatCameraCount(count), label); } finally { setLocale(previous); } @@ -56,24 +54,28 @@ test('the marker mean weights every mount and the flight bounds cover the outlie } }); +function mergeCounts(sizes, counts, positions) { + const cells = counts.map((count, i) => ({ + ...createCameraCell(String(i)), + count, + })); + let i = 0; + const groups = mergeCountCells( + cells, + () => positions[i++], + (count) => sizes[count], + 4, + ); + return { cells, groups }; +} + test('stadiums merge by their own radii and segment lengths across grid boundaries', () => { const sizes = { 2: { width: 28, height: 28 }, 7350: { width: 80, height: 48 }, }; - const gap = 4; const check = (counts, positions, expected) => { - const cells = counts.map((count, i) => ({ - ...createCameraCell(String(i)), - count, - })); - let i = 0; - const groups = mergeCountCells( - cells, - () => positions[i++], - (count) => sizes[count], - gap, - ); + const { groups } = mergeCounts(sizes, counts, positions); assert.deepEqual( groups.map((cell) => cell.count), expected, @@ -100,19 +102,8 @@ test('a lone camera joins a count it touches, and lone cameras alone stay apart' 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 }, }; - const gap = 4; const check = (counts, positions, expected) => { - const cells = counts.map((count, i) => ({ - ...createCameraCell(String(i)), - count, - })); - let i = 0; - const groups = mergeCountCells( - cells, - () => positions[i++], - (count) => sizes[count], - gap, - ); + const { cells, groups } = mergeCounts(sizes, counts, positions); assert.deepEqual( groups.map((cell) => cell.count), expected, @@ -135,3 +126,91 @@ test('a lone camera joins a count it touches, and lone cameras alone stay apart' // A lone camera that only touches another lone camera is left alone. check([1, 1, 9], [at(40), at(70), at(100)], [1, 10]); }); + +test('cells merged across the antimeridian stay at the antimeridian', () => { + for (const lon of [179.9, 179.99, 179.999]) { + for (const reversed of [false, true]) { + const east = createCameraCell('e'); + const west = createCameraCell('w'); + for (let i = 0; i < 2; i++) { + addCellCamera(east, { lon, lat: 0, absoluteHeightM: 0 }); + addCellCamera(west, { lon: -lon, lat: 0, absoluteHeightM: 0 }); + } + const cells = reversed ? [west, east] : [east, west]; + const screens = [ + { x: 100, y: 100 }, + { x: 120, y: 100 }, + ]; + let i = 0; + const [group, ...rest] = mergeCountCells( + cells, + () => screens[i++], + () => ({ width: 40, height: 40 }), + 4, + ); + assert.equal(rest.length, 0); + assert.equal(group.count, 4); + const expected = fromDegrees(180, 0, 0); + assert.ok(distance(cellCenter(group), expected) < 1000, `${lon}: centre`); + const bounds = cellBounds(group); + assert.ok(bounds.radius < 15_000, `${lon}: radius ${bounds.radius}`); + for (const l of [lon, -lon]) + assert.ok( + distance(bounds.center, fromDegrees(l, 0, 0)) <= bounds.radius, + ); + } + } +}); + +test('flight bounds on drawn ground still contain every mount', () => { + // Flat ellipsoid terrain (Re:Earth terrain failed), mounts at 1,800 m. + const flat = createCameraCell('k'); + addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 }); + addCellCamera(flat, { lon: 10, lat: 46, absoluteHeightM: 1800 }); + flat.groundM = 0; + const fb = cellBounds(flat); + assert.ok( + distance(fromDegrees(10, 46, 1800), fb.center) <= fb.radius, + 'flat', + ); + // Ravine: mounts 200 m apart at 600 m, the floor at 0 m between them. + const east = 10 + 200 / (111_320 * Math.cos((46 * Math.PI) / 180)); + const ravine = createCameraCell('r'); + addCellCamera(ravine, { lon: 10, lat: 46, absoluteHeightM: 600 }); + addCellCamera(ravine, { lon: east, lat: 46, absoluteHeightM: 600 }); + ravine.groundM = 0; + const rb = cellBounds(ravine); + for (const lon of [10, east]) + assert.ok( + distance(fromDegrees(lon, 46, 600), rb.center) <= rb.radius, + 'ravine', + ); +}); + +test('a lone camera between two counts joins one of them and does not merge them', () => { + const sizes = { 1: { width: 24, height: 24 }, 9: { width: 40, height: 40 } }; + const run = (counts, xs) => + mergeCounts( + sizes, + counts, + xs.map((x) => ({ x, y: 100 })), + ) + .groups.map((cell) => cell.count) + .sort((a, b) => a - b); + assert.deepEqual(run([9, 9], [70, 130]), [9, 9]); + for (const [counts, xs] of [ + [ + [9, 1, 9], + [70, 100, 130], + ], + [ + [1, 9, 9], + [100, 70, 130], + ], + [ + [9, 9, 1], + [70, 130, 100], + ], + ]) + assert.deepEqual(run(counts, xs), [9, 10], String(counts)); +}); diff --git a/src/data/cctvViewPass.test.mjs b/src/data/cctvViewPass.test.mjs new file mode 100644 index 0000000000..07e49ec1cd --- /dev/null +++ b/src/data/cctvViewPass.test.mjs @@ -0,0 +1,254 @@ +import { afterEach, beforeEach, test } from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { bindRenderer } from '../render/rendererOf.js'; +import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; +import cctvLayer, { + _cctvIconsForTest, + _setCctvCoverageStateForTest, + refreshHorizonCulling, +} from './cctv.js'; + +const WIDTH = 800; +const HEIGHT = 600; +const bindings = []; +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + measureText: (text) => ({ + width: text.length * 8, + actualBoundingBoxAscent: 4, + actualBoundingBoxDescent: 4, + }), + }), + }), + }; +}); +afterEach(() => { + delete globalThis.document; + for (const unbind of bindings.splice(0)) unbind(); +}); + +function recordsAt(lonLats, height = 10) { + return lonLats.map(([lon, lat], index) => { + const position = Cesium.Cartesian3.fromDegrees(lon, lat, height); + return { + camera: { + id: `cam-${String(index).padStart(4, '0')}`, + name: `Camera ${index}`, + city: 'Test', + lat, + lon, + headingDeg: 0, + pitchDeg: -18, + fovDeg: 44, + rangeM: 145, + mountHeightM: 8, + absoluteHeightM: height, + }, + position: { x: position.x, y: position.y, z: position.z }, + groundSamples: {}, + groundResolved: {}, + coverageEntities: [], + projection: null, + }; + }); +} + +const plain = ({ x, y, z }) => ({ x, y, z }); + +function lookingAt(eye, target, ports = {}) { + const direction = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const right = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3()); + return { + viewer: viewerWithAxes(eye, direction, right, up, ports), + direction, + right, + up, + }; +} + +function topDown(height, ports = {}) { + const eye = Cesium.Cartesian3.fromDegrees(0, 0, height); + return viewerWithAxes( + eye, + { x: -1, y: 0, z: 0 }, + { x: 0, y: 1, z: 0 }, + { x: 0, y: 0, z: 1 }, + ports, + ); +} + +function viewerWithAxes(eye, direction, right, up, ports) { + const carto = Cesium.Cartographic.fromCartesian(eye); + const { port } = fakeCameraPort({ + pose: { + lon: Cesium.Math.toDegrees(carto.longitude), + lat: Cesium.Math.toDegrees(carto.latitude), + height: carto.height, + position: plain(eye), + direction: plain(direction), + up: plain(up), + right: plain(right), + fovy: Math.PI / 3, + aspectRatio: WIDTH / HEIGHT, + near: 0.1, + far: 5e8, + }, + }); + const viewer = {}; + bindings.push( + bindRenderer(viewer, { + camera: port, + canvas: { clientWidth: WIDTH, clientHeight: HEIGHT }, + draw: fakeDrawPort(), + ...ports, + }), + ); + return viewer; +} + +/** Pinhole projection, as the layer's projector. */ +function project(view, eye, point) { + const d = Cesium.Cartesian3.subtract(point, eye, new Cesium.Cartesian3()); + const z = Cesium.Cartesian3.dot(d, view.direction); + const t = Math.tan(Math.PI / 6); + const x = Cesium.Cartesian3.dot(d, view.right) / z / (t * (WIDTH / HEIGHT)); + const y = Cesium.Cartesian3.dot(d, view.up) / z / t; + return { x: (0.5 + x / 2) * WIDTH, y: (0.5 - y / 2) * HEIGHT, z }; +} + +for (const [label, horizontalM, aboveM] of [ + ['100 m approach', 100, 4], + ['800 m approach', 800, 50], +]) { + test(`a camera with a stale height is read even when it projects off the screen at ${label}`, () => { + const ground = 1872; + const records = recordsAt([ + [0, 0], + [0, 0], + ]); + // geoid fallback after a 429 + for (const r of records) + r.groundPrior = { ellipsoid: 2, source: 'geoid-fallback' }; + const mount = Cesium.Cartesian3.fromDegrees(0, 0, ground + 8); + const eye = Cesium.Cartesian3.fromDegrees( + 0, + -horizontalM / 111_320, + ground + 8 + aboveM, + ); + const reads = []; + const view = lookingAt(eye, mount, { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + reads.push(point); + return ground; + }, + }, + }); + _setCctvCoverageStateForTest({ viewer: view.viewer, records }); + const stale = project(view, eye, records[0].position); + const truth = project(view, eye, mount); + + assert.ok(stale.y > HEIGHT * 2); + assert.ok(truth.y > 0 && truth.y < HEIGHT); + refreshHorizonCulling(); + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, ground); + + assert.ok(reads.length > 0, 'the stale camera was never read'); + }); +} + +test('cameras off the visible screen cannot spend the whole terrain read budget', () => { + // 300 cameras with no prior around the screen edge, tiles not loaded; the + // 301st at the screen centre over a loaded tile. + const lonLats = []; + for (let i = 0; i < 300; i++) { + const a = (i / 300) * 2 * Math.PI; + // ~ 0.8 screen widths out at 200 m altitude (screen ~ 307 m wide) + lonLats.push([ + (Math.cos(a) * 250) / 111_320, + (Math.sin(a) * 190) / 111_320, + ]); + } + lonLats.push([0, 0]); + const records = recordsAt(lonLats); + const perPass = []; + let reads; + const viewer = topDown(200, { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + reads.push(point); + return Math.abs(point.lon) < 1e-9 && Math.abs(point.lat) < 1e-9 + ? 40 + : null; + }, + }, + }); + _setCctvCoverageStateForTest({ viewer, records }); + for (let pass = 0; pass < 3; pass++) { + reads = []; + refreshHorizonCulling(); + perPass.push(reads.length); + } + const last = records.at(-1); + + assert.equal(last.groundPrior?.ellipsoid, 40); + assert.ok(perPass.every((n) => n <= 300)); +}); + +test("the active camera's icon moves beside a count that would cover it", () => { + const records = recordsAt([ + [0, 0], + [0, 0], + [0, 0], + ]); + const viewer = topDown(20_000); + _setCctvCoverageStateForTest({ viewer, records, activeCameraId: 'cam-0000' }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const [marker] = cctvLayer._cctvDrawnForTest().counts.markers; + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 19_990; + const apartPx = + Cesium.Cartesian3.distance(marker.pos, icons.item('cam-0000').pos) / + metresPerPixel; + + assert.ok(apartPx > marker.width / 2, 'the marker covers the active icon'); +}); + +test('a lone camera just inside the grouping threshold joins the count beside it', () => { + const h = 740; + // mounts at 8 m mount height above a 0 m ground: positions at 10 m, eye at h+10 + const records = recordsAt([ + [0, 235 / 111_320], + [0, 255 / 111_320], + [0, 255 / 111_320], + ]); + for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' }; + const viewer = topDown(h + 10); + _setCctvCoverageStateForTest({ viewer, records }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const markers = cctvLayer._cctvDrawnForTest().counts.markers; + assert.deepEqual( + markers.map((marker) => marker.cell.count), + [3], + ); + assert.equal( + icons.item('cam-0000').show, + false, + 'the near singleton still draws beside the count', + ); +}); diff --git a/src/data/cctvViewThinning.test.mjs b/src/data/cctvViewThinning.test.mjs index 7293e1aac8..b3ef110926 100644 --- a/src/data/cctvViewThinning.test.mjs +++ b/src/data/cctvViewThinning.test.mjs @@ -1,17 +1,20 @@ // src/data/cctvViewThinning.test.mjs — the CCTV view pass: only cameras on or -// near the screen show, a zoomed-out view groups neighboring cameras, 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, beforeEach, test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { CAMERA_GREEN } from '../layers/cctv/policy.js'; -import { createCameraGlyphCache } from '../layers/cctv/countMarkers.js'; +import { CAMERA_GREEN, COUNT_CAMERA_ICON } from '../layers/cctv/policy.js'; +import { fakeDrawPort } from '../testSupport/fakeDrawPort.mjs'; import { createCameraCell } from './cctvCellCounts.js'; -import { bindRenderer } from '../render/rendererOf.js'; +import { bindRenderer, findCamera } from '../render/rendererOf.js'; import { DEFAULT_FOCUS_DEEMPHASIS_PARAMS } from './focusDeemphasis.js'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import cctvLayer, { _cctvIconsForTest, + focusCctvRecord, + CCTV_FOCUS_RESULT, bindCctvWorldClickGesture, applyCctvFocusDeemphasis, reopenNearestCamera, @@ -55,7 +58,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, flights = [], ports = {}) { +function poseAt(heightM, lonDeg) { const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM); const down = Cesium.Cartesian3.normalize( Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()), @@ -63,23 +66,25 @@ function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { ); 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, - }, - }); + return { + 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, + }; +} + +function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) { + const { port, setPose } = fakeCameraPort({ pose: poseAt(heightM, lonDeg) }); port.flyToBounds = (bounds, options) => flights.push({ bounds, options }); - const viewer = {}; + const viewer = { moveTo: (lon) => setPose(poseAt(heightM, lon)) }; bindings.push( bindRenderer(viewer, { camera: port, @@ -99,12 +104,9 @@ let glyphWidth; let inkHalfHeight; let ctx; const fonts = new EventTarget(); -let rasters; let spriteImages; -/** Model the sprite’s neutral highlights, dark fills and translucent edges. */ function markerCanvas() { - const canvas = {}; const context = { measureText(text) { measured++; @@ -114,40 +116,8 @@ function markerCanvas() { actualBoundingBoxDescent: inkHalfHeight, }; }, - drawImage(image, x, y, width, height) { - assert.equal(image.loaded, true); - assert.deepEqual( - [x, y, width, height], - [0, 0, canvas.width, canvas.height], - ); - canvas.source = image.src; - const h = Math.floor(height / 2); - canvas.ink = [2, 3, Math.floor(h * 1.5), h]; - rasters.push(canvas); - }, - getImageData() { - const data = new Uint8ClampedArray(canvas.width * canvas.height * 4); - const [left, top, width, height] = canvas.ink; - for (let y = top; y < top + height; y++) { - for (let x = left; x < left + width; x++) { - const shade = x === left ? 255 : 64; - data.set( - [shade, shade, shade, y === top ? 1 : 255], - (y * canvas.width + x) * 4, - ); - } - } - return { data }; - }, - putImageData({ data }) { - const [left, top] = canvas.ink; - const start = (top * canvas.width + left) * 4; - canvas.stroke = [...data.slice(start, start + 4)]; - canvas.fill = [...data.slice(start + 4, start + 8)]; - }, }; - canvas.getContext = () => context; - return canvas; + return { getContext: () => context }; } function seedCoverage(options) { @@ -181,7 +151,6 @@ beforeEach(() => { measured = 0; glyphWidth = 8; inkHalfHeight = 4; - rasters = []; globalThis.document = { fonts, createElement: markerCanvas }; const stack = []; ctx = { @@ -205,7 +174,7 @@ beforeEach(() => { beginPath() {}, fill() {}, drawImage(image, left, top, sw, sh, x, y, width, height) { - assert.deepEqual([left, top, sw, sh], image.ink); + assert.ok(image.loaded); assert.ok(Math.abs(width / height - sw / sh) < 1e-9); this.glyphs.push({ image, @@ -556,27 +525,22 @@ test('cameras on one mount draw side by side once they show as icons', () => { test('a pan keeps the same winners, and an unchanged view keeps its list', () => { const { records } = recordsAt(CLUSTER); - seedCoverage({ - viewer: viewerAt(20_000), - records, - }); + const viewer = viewerAt(20_000); + seedCoverage({ viewer, records }); refreshHorizonCulling(); 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]) { - seedCoverage({ - viewer: viewerAt(20_000, shiftM / 111_320), - records, - }); + viewer.moveTo(shiftM / 111_320); refreshHorizonCulling(); - assert.deepEqual( + assert.equal( cctvLayer.getUIState().cameraIndex, before, `pan by ${shiftM} m`, ); } - seedCoverage({ viewer: viewerAt(20_000), records }); + viewer.moveTo(0); refreshHorizonCulling(); assert.equal(refreshHorizonCulling(), false, 'the same view changes nothing'); assert.deepEqual(_viewRecordIdsForTest(), list); @@ -864,7 +828,7 @@ test('coverage leaves grouped neighbors and returns when their icons separate', assert.deepEqual(markers(), []); }); -test('count markers share the camera focus fade and recover on release', () => { +test('a dimmed count keeps its alpha when its cell changes and recovers on release', () => { const { records } = recordsAt(CLUSTER); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); @@ -888,8 +852,20 @@ test('count markers share the camera focus fade and recover on release', () => { tick(0, target); tick(params.attackMs + 1, target); assert.equal(paint()[0].alpha, params.dimFloor); - tick(params.attackMs + 2, null); - tick(params.attackMs + params.releaseMs + 3, null); + + const record = records[0]; + record.camera.lon += 2 / 111_320; + record.position = Cesium.Cartesian3.fromDegrees( + record.camera.lon, + record.camera.lat, + record.camera.absoluteHeightM, + ); + refreshHorizonCulling(); + tick(params.attackMs + 2, target); + assert.equal(paint()[0].alpha, params.dimFloor); + + tick(params.attackMs + 3, null); + tick(params.attackMs + params.releaseMs + 4, null); assert.equal(paint()[0].alpha, 1); }); @@ -992,72 +968,21 @@ test('the overlay paints narrow count labels as circles and wide labels as pills assert.equal(sw, sh); assert.ok(lw > lh); assert.ok(lw > text.length * glyphWidth); - assert.equal(sh + 4, 48); - assert.equal(lh + 4, 54); - // The four-pixel outer stroke extends two pixels on each side of the path. - assert.equal(sw + 4, short.width); - assert.equal(lw + 4, long.width); assert.equal(sy + sh / 2, HEIGHT / 2); assert.equal(ly + lh / 2, HEIGHT / 2); assert.ok(Math.abs(sx + sw / 2 - (WIDTH / 2 + short.pos.y / 30)) < 1e-9); assert.ok(Math.abs(lx + lw / 2 - (WIDTH / 2 + long.pos.y / 30)) < 1e-9); assert.equal(ctx.glyphs.length, labels.length); - assert.equal(CAMERA_GREEN, '#5dff8f'); assert.deepEqual( ctx.rings.filter((_, i) => i % 2 === 1), labels.map(() => CAMERA_GREEN), ); for (const [i, label] of labels.entries()) { const glyph = ctx.glyphs[i]; - const [left, top, w, h] = ctx.shapes[i]; - const cx = left + w / 2, - cy = top + h / 2; - assert.equal(glyph.x, cx); - assert.equal(label.x, cx); - assert.deepEqual(glyph.image.stroke, [93, 255, 143, 1]); - assert.deepEqual(glyph.image.fill, [23, 64, 36, 1]); + assert.equal(glyph.x, label.x); assert.equal(label.color, CAMERA_GREEN); - const radius = h / 2 - 1; - // 48 and 54 px markers: the glyph and its top gap grow with the marker. - const grown = (h + 4 - 40) / 18; - assert.ok(Math.abs(glyph.height - (7.5 + 2.5 * grown)) < 1e-9); - assert.ok( - Math.abs(glyph.y - glyph.height / 2 - (cy - radius + 3 + grown)) < 1e-9, - ); - // The middle of the digits sits a fifth of the inner radius below centre. - assert.ok(Math.abs(label.y - (cy + 0.2 * radius)) < 1e-9); - assert.ok(label.y - inkHalfHeight - (glyph.y + glyph.height / 2) >= 5); - for (const [width, edgeY, padding] of [ - [glyph.width, glyph.y - glyph.height / 2, 2], - [label.text.length * glyphWidth, label.y + inkHalfHeight, 6], - ]) { - const chord = 2 * Math.sqrt(radius ** 2 - (edgeY - cy) ** 2); - assert.ok((w - h + chord - width) / 2 >= padding - 1e-9); - } + assert.ok(label.y - inkHalfHeight >= glyph.y + glyph.height / 2); } - const builds = rasters.length; - const images = ctx.glyphs.map((glyph) => glyph.image); - assert.notEqual(images[0], images[1]); - const idleCamera = _cctvIconsForTest().item(records.at(-1).camera.id); - assert.equal(idleCamera.show, true); - for (const image of images) assert.equal(image.source, idleCamera.image); - paint(); - assert.deepEqual( - ctx.glyphs.map((glyph) => glyph.image), - images, - ); - assert.equal(rasters.length, builds); - assert.equal(paintRequests, requests + 1); - assert.match(labels[0].font, /JetBrains Mono/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); - assert.equal(ctx.lineWidth, 1); - ctx.drawImage = () => { - throw new Error('glyph paint failed'); - }; - assert.throws(() => paint(), /glyph paint failed/); - assert.equal(ctx.font, 'initial'); - assert.equal(ctx.fillStyle, 'initial'); }); test('a wide count label merges a horizontal neighbor beyond the circle diameter', () => { @@ -1169,6 +1094,12 @@ test('hits follow paint order and keep the last painted group until the overlay assert.equal(labels.length, 2); const top = counts.pickedCell(point); assert.equal(String(top.count), labels.at(-1).text); + const replacements = counts.markers.map((marker) => ({ + ...marker.cell, + count: 7, + })); + counts.update(replacements, () => null); + assert.equal(counts.pickedCell(point), top); counts.update([], () => null); assert.equal(counts.pickedCell(point), top); assert.deepEqual(paint(), []); @@ -1178,16 +1109,8 @@ test('hits follow paint order and keep the last painted group until the overlay test('paint, HUD exclusions and hit rectangles use the count-scaled height', () => { seedCoverage({ viewer: viewerAt(20_000) }); const counts = cctvLayer._cctvDrawnForTest().counts; - for (const [count, height] of [ - [2, 40], - [10, 44], - [100, 48], - [1000, 54], - [3162, 56], - [3163, 56], - [7350, 58], - [1e8, 58], - ]) { + let previous = 0; + for (const count of [2, 10, 100, 1000, 3162, 3163, 7350, 1e8]) { const cell = { ...createCameraCell('cell'), count }; for (const lon of [0, 0.025]) { counts.update( @@ -1202,10 +1125,11 @@ test('paint, HUD exclusions and hit rectangles use the count-scaled height', () return false; }, }); - if (height === 40 || height === 58) - assert.equal(ctx.glyphs[0].height, height === 40 ? 7.5 : 10); const marker = markers()[0]; - assert.equal(marker.height, height); + const height = marker.height; + assert.ok(height >= previous); + if (count === 2) assert.equal(height, 40); + previous = height; assert.equal(rect.h, height); assert.equal(rect.w, marker.width); const [x, y, w, h] = ctx.shapes[0]; @@ -1222,44 +1146,28 @@ test('paint, HUD exclusions and hit rectangles use the count-scaled height', () ); } } - // Centred 23 px above the canvas: the taller badges still cross the edge. - const matrix = new Float64Array(16); - matrix[13] = 1 + 46 / HEIGHT; - matrix[15] = 1; - assert.equal( - paint({ viewProjectionMatrix: matrix }).length, - height > 46 ? 1 : 0, - ); } + assert.equal(previous, 58); }); -test('measured ink width selects the circle or pill and clears the curved ring', () => { +test('measured ink width selects the circle or pill', () => { const { records } = recordsAt(Array(99).fill([0, 0])); seedCoverage({ viewer: viewerAt(20_000), records }); for (const [width, extent, circle] of [ [7, 4, true], [25, 4, false], - // Width-only metrics reserve the full type height below the baseline. - [6, undefined, true], ]) { glyphWidth = width; inkHalfHeight = extent; fonts.dispatchEvent(new Event('loadingdone')); refreshHorizonCulling(); - const [label] = paint(); - const [, top, pathWidth, pathHeight] = ctx.shapes[0]; - assert.equal(pathHeight + 4, 48); + paint(); + const [, , pathWidth, pathHeight] = ctx.shapes[0]; assert.equal(pathWidth === pathHeight, circle); - // At the top of the ink, the circle ends narrow the usable inner width. - const innerRadius = pathHeight / 2 - 1; - const edge = label.y + (extent ?? 6) - (top + pathHeight / 2); - const clearWidth = - pathWidth - pathHeight + 2 * Math.sqrt(innerRadius ** 2 - edge ** 2); - assert.ok((clearWidth - label.text.length * width) / 2 >= 6); } }); -test('equal-size camera groups share a camera sprite and follow overlay pixel density', () => { +test('count markers draw the green camera sprite once it has loaded', () => { const { records } = recordsAt([ [0, 0], [0, 0], @@ -1268,45 +1176,18 @@ test('equal-size camera groups share a camera sprite and follow overlay pixel de ]); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - spriteImages[0].finish(); - paint({ dpr: 1 }); - const low = ctx.glyphs[0].image; - assert.equal(ctx.glyphs[1].image, low); - const builds = rasters.length; - paint({ dpr: 2 }); - const high = ctx.glyphs[0].image; - assert.equal(ctx.glyphs[1].image, high); - assert.notEqual(high, low); - // The raster follows the device density; the painted size does not. - assert.deepEqual([low.width, high.width], [16, 30]); - assert.equal(ctx.glyphs[0].height, 7.5); - paint({ dpr: 2 }); - assert.equal(rasters.length, builds + 1); - paint({ dpr: 1 }); - assert.equal(ctx.glyphs[0].image, low); - assert.equal(rasters.length, builds + 1); -}); - -test('the glyph cache draws its supplied map sprite and multiplies its colours', () => { - const source = - 'data:image/svg+xml,' + - encodeURIComponent( - '', - ); - const glyphFor = createCameraGlyphCache(markerCanvas, source); - assert.equal(glyphFor(12, 2, CAMERA_GREEN), null); - assert.equal(spriteImages[0].src, source); - spriteImages[0].finish(); - const green = glyphFor(12, 2, CAMERA_GREEN); - assert.equal(glyphFor(12, 2, CAMERA_GREEN), green); - const white = glyphFor(12, 2, '#ffffff'); - assert.notEqual(white, green); + paint(); + assert.equal(ctx.glyphs.length, 0); + const requests = paintRequests; + const [image] = spriteImages; + assert.equal(image.src, COUNT_CAMERA_ICON); + image.finish(); + assert.equal(paintRequests, requests + 1); + paint(); assert.deepEqual( - rasters.map(({ source: drawn }) => drawn), - [source, source], + ctx.glyphs.map((glyph) => glyph.image), + [image, image], ); - assert.deepEqual(white.canvas.stroke, [255, 255, 255, 1]); - assert.deepEqual(white.canvas.fill, [64, 64, 64, 1]); }); test('a sprite that loads after disposal does not request a paint', () => { @@ -1316,23 +1197,302 @@ test('a sprite that loads after disposal does not request a paint', () => { cctvLayer._cctvDrawnForTest().counts.dispose(); const requests = paintRequests; spriteImages[0].finish(); - assert.equal(rasters.length, 0); assert.equal(paintRequests, requests); }); -test('counts still paint when an offscreen 2D context is unavailable', () => { - document.createElement = () => ({ getContext: () => null }); +test('cameras less than a metre apart spread even across a rounding boundary', () => { + const { records } = recordsAt([ + [0.000004, 0], + [0.000006, 0], + ]); + seedCoverage({ viewer: viewerAt(460), records }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; + const apart = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + assert.ok(Math.abs(apart / metresPerPixel - 30) < 0.5); +}); + +test('a drawn height read before the terrain settled, or on another surface, is read again', () => { const { records } = recordsAt([ [0, 0], - [0, 0], + [0.2, 0], ]); + records[0].groundPrior = { ellipsoid: -20, source: 'geoid-fallback' }; + let settled = false, + version = 1, + terrain = 100; + const ports = { + globe: { + isGlobeVisible: () => true, + isSettled: () => settled, + surfaceVersion: () => version, + }, + query: { sampleHeightNow: () => terrain }, + }; + seedCoverage({ viewer: viewerAt(20000, 0, [], ports), records }); + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 100); + assert.equal(records[0].groundPrior.settled, false); + terrain = 150; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 100); + settled = true; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 150); + terrain = 0; + version++; + refreshHorizonCulling(); + assert.equal(records[0].groundPrior.ellipsoid, 0); +}); + +test('a camera with geometry takes the drawn terrain once, after the pass that read it', async () => { + const { records } = recordsAt([ + [0, 0], + [0.2, 0], + ]); + records[1].groundPrior = { ellipsoid: 2, source: 'reearth' }; + const record = records[0]; + Object.assign(record, { + groundPrior: { ellipsoid: -20, source: 'geoid-fallback' }, + groundSamples: {}, + groundResolved: {}, + }); + const samples = []; + const ports = { + globe: { isGlobeVisible: () => true }, + query: { + sampleHeightNow(point) { + samples.push(point); + return 1872; + }, + }, + draw: fakeDrawPort(), + }; + seedCoverage({ + viewer: viewerAt(2200, 0, [], ports), + records, + activeCameraId: 'cam-0', + }); + refreshCoverageStyles(); + assert.ok(record.frustumGeometry); + samples.length = 0; + refreshHorizonCulling(); + refreshHorizonCulling(); + assert.equal( + samples.filter((point) => point.lon === 0 && point.lat === 0).length, + 1, + ); + assert.equal(record.groundPrior.source, 'geoid-fallback'); + await Promise.resolve(); + assert.equal(record.groundPrior.source, 'drawn-terrain'); + for (const pos of [record.position, _cctvIconsForTest().item('cam-0').pos]) + assert.ok( + Math.abs(Cesium.Cartographic.fromCartesian(pos).height - 1880) < 0.01, + ); +}); + +/** Painted centre of a count marker in CSS px. */ +function markerCentre(marker) { + const label = paint().find((l) => l.text === marker.text); + return { x: label.x, y: label.y - marker.labelY }; +} + +test('building geometry for spread mount mates keeps their icons beside the mount', () => { + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + const draw = fakeDrawPort(); + seedCoverage({ + viewer: viewerAt(460, 0, [], { draw }), + records, + activeCameraId: 'cam-2', + }); + refreshHorizonCulling(); + const icons = _cctvIconsForTest(); + const before = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + + assert.ok(before > 10); + refreshCoverageStyles(); + + const after = Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ); + const callouts = cctvLayer.getDetectableObjects(); + const ca = callouts.find((o) => o.sourceId === 'cam-0').position; + + assert.ok(after > 10, 'icons stay side by side after geometry is built'); + assert.ok( + Cesium.Cartesian3.distance(icons.item('cam-0').pos, ca) < 1e-6, + 'icon and callout agree', + ); +}); + +test('a count click does not fly while the cockpit or a followed target owns the camera', () => { + const { records } = recordsAt(CLUSTER); + // Cockpit + let flights = []; + globalThis.document.body = { + classList: { contains: (c) => c === 'cockpit-mode' }, + }; + let viewer = viewerAt(20_000, 0, flights); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal( + focusCctvRecord(viewer, records[0]), + CCTV_FOCUS_RESULT.COCKPIT_ACTIVE, + ); + assert.equal(flights.length, 0); + clickMarker(markers()[0]); + + assert.equal(flights.length, 0, 'count click must not fly in cockpit mode'); + // Tracking + delete globalThis.document.body; + flights = []; + viewer = viewerAt(20_000, 0, flights); + Object.defineProperty(findCamera(viewer), 'followed', { + value: { key: 'flights:abc' }, + configurable: true, + }); + seedCoverage({ viewer, records }); + refreshHorizonCulling(); + assert.equal( + focusCctvRecord(viewer, records[0]), + CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW, + ); + assert.equal(flights.length, 0); + clickMarker(markers()[0]); + + assert.equal(flights.length, 0, 'count click must not fly while tracking'); +}); + +test('each click on a long dense chain flies closer than the last', () => { + const lons = []; + const n = 200; + const step = 50 / 111_320; + for (let i = 0; i < n; i++) lons.push([(i - (n - 1) / 2) * step, 0]); + const { records } = recordsAt(lons); + const flights = []; + seedCoverage({ viewer: viewerAt(24_000, 0, flights), records }); + refreshHorizonCulling(); + + let marker = markers().find((m) => m.cell.count === n); + assert.ok(marker, 'one count of 200'); + const clickAt = (m) => { + const { x, y } = markerCentre(m); + const click = bindCctvWorldClickGesture({ onClick: (fn) => fn }, () => {}); + click({ + screenPosition: { x, y }, + gesture: { travelPx: 0, durationMs: 20 }, + }); + }; + clickAt(marker); + const first = flights.at(-1); + const c1 = Cesium.Cartographic.fromCartesian(first.bounds.center); + + seedCoverage({ + viewer: viewerAt( + c1.height + first.options.offset.range, + Cesium.Math.toDegrees(c1.longitude), + flights, + ), + records, + }); + refreshHorizonCulling(); + + marker = markers().find((m) => m.cell.count === n); + assert.ok(marker, 'the full count of 200 reforms at the destination'); + clickAt(marker); + const second = flights.at(-1); + + assert.ok( + second.options.offset.range < first.options.offset.range - 1, + 'second click makes progress', + ); +}); + +test("a click outside a round count's circle does not hit it", () => { + const { records } = recordsAt(CLUSTER); seedCoverage({ viewer: viewerAt(20_000), records }); refreshHorizonCulling(); - spriteImages[0].finish(); - assert.deepEqual( - paint().map((label) => label.text), - ['2'], + const [marker] = markers(); + assert.equal(marker.width, marker.height, 'a round marker'); + const c = markerCentre(marker); + const counts = cctvLayer._cctvDrawnForTest().counts; + const r = marker.height / 2; + const corner = { x: c.x + r - 1, y: c.y + r - 1 }; + const dist = Math.hypot(r - 1, r - 1); + + assert.ok(dist > r, 'corner is outside the painted circle'); + assert.equal( + counts.pickedCell(corner), + null, + 'a click outside the painted circle must not hit the count', ); - assert.equal(ctx.glyphs.length, 0); - assert.equal(ctx.shapes.length, 1); +}); + +test('an unresolved batch result takes the drawn terrain', () => { + const { records } = recordsAt([ + [0, 0], + [0.2, 0], + ]); + records[0].groundPrior = { ellipsoid: null, source: 'unresolved' }; + const ports = { + globe: { isGlobeVisible: () => true }, + query: { sampleHeightNow: () => 1872 }, + }; + seedCoverage({ viewer: viewerAt(20_000, 0, [], ports), records }); + refreshHorizonCulling(); + const h = (r) => Cesium.Cartographic.fromCartesian(r.position).height; + + assert.ok( + Math.abs(h(records[0]) - 1880) < 0.01, + 'an unresolved camera takes the drawn terrain', + ); + assert.equal(records[1].groundPrior.source, 'drawn-terrain'); +}); + +const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450; +const separationPx = () => { + const icons = _cctvIconsForTest(); + return ( + Cesium.Cartesian3.distance( + icons.item('cam-0').pos, + icons.item('cam-1').pos, + ) / metresPerPixel + ); +}; + +test('shared-mount icons stay spread after coverage geometry is built', () => { + // cam-0/cam-1 share a mount, cam-2 is active 11 m away. + const { records } = recordsAt([ + [0.001, 0.0005], + [0.001, 0.0005], + [0.0011, 0.0005], + ]); + for (const r of records) r.groundPrior = { ellipsoid: 2, source: 'reearth' }; + seedCoverage({ + viewer: viewerAt(460, 0, [], { draw: fakeDrawPort() }), + records, + activeCameraId: 'cam-2', + coverageMode: 'on', + }); + refreshHorizonCulling(); + const before = separationPx(); + + // selection.setActiveCamera order: refreshHorizonCulling, then refreshCoverageStyles. + refreshCoverageStyles(); + const after = separationPx(); + + assert.ok(Math.abs(before - 30) < 0.5); + assert.ok(Math.abs(after - 30) < 0.5, `icons collapsed to ${after} px`); }); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index 89fa278bb5..e071f07238 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -7,113 +7,65 @@ import { import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { CAMERA_GREEN, - IDLE_CAMERA_ICON, - COUNT_BASE_PX, - COUNT_PX_PER_DECADE, - COUNT_MIN_HEIGHT_PX, - COUNT_MAX_HEIGHT_PX, - COUNT_TEXT_PADDING_PX, - COUNT_GLYPH_MIN_PX, - COUNT_GLYPH_MAX_PX, - COUNT_GLYPH_TOP_MIN_PX, - COUNT_GLYPH_TOP_MAX_PX, - COUNT_GLYPH_PADDING_PX, - COUNT_LABEL_DROP, + COUNT_CAMERA_ICON, + CAMERA_ICON_PX, COUNT_MERGE_GAP_PX, - COUNT_SINGLE_ICON_PX, - COUNT_MERGE_PASSES, } from './policy.js'; +import { liftedForHorizon } from '../../geo/horizon.js'; +// Diameter at one camera before applying the size limits, in CSS pixels. +const COUNT_BASE_PX = 38; + +// Extra diameter for each tenfold increase in camera count. +const COUNT_PX_PER_DECADE = 5; + +// Minimum height of a count marker in CSS pixels. +const COUNT_MIN_HEIGHT_PX = 40; + +// Maximum height of a count marker in CSS pixels. +const COUNT_MAX_HEIGHT_PX = 58; + +// Clear fill between the count and the inside of the ring, in CSS pixels. +const COUNT_TEXT_PADDING_PX = 6; + +// Height of the camera glyph in the smallest and the largest marker. +const COUNT_GLYPH_MIN_PX = 7.5; +const COUNT_GLYPH_MAX_PX = 10; + +// Clear fill above the glyph in the smallest and the largest marker. +const COUNT_GLYPH_TOP_MIN_PX = 3; +const COUNT_GLYPH_TOP_MAX_PX = 4; + +// Clear fill between the glyph's top corners and the inside of the ring. +const COUNT_GLYPH_PADDING_PX = 2; + +// The middle of the digits sits this share of the inner radius below the +// marker's centre, which leaves the glyph clear of the count. +const COUNT_LABEL_DROP = 0.2; + +// Merge passes per view. A merged centre and wider label can reach a further +// marker. The cap bounds work on motion ticks. +const COUNT_MERGE_PASSES = 3; const FONT = WORLD_OVERLAY_STYLE.fontTitle; // Reserve the camera's landscape slot even while the map sprite is loading. const GLYPH_ASPECT = 1.5; const RING_PX = 2; const RIM_PX = 1; const STROKE_INSET = RIM_PX + RING_PX / 2; -const SINGLE_ICON = Object.freeze({ - width: COUNT_SINGLE_ICON_PX, - height: COUNT_SINGLE_ICON_PX, -}); - -/** Apply the billboard's RGB tint to the sprite and find its painted bounds. */ -function rasterizeGlyph(canvas, image, size, dpr, color) { - if (!canvas) return null; - // The artwork occupies just over half the height of the square SVG viewport. - const side = 2 * Math.ceil(size * dpr); - canvas.width = canvas.height = side; - const ctx = canvas.getContext('2d'); - if (!ctx) return null; - ctx.drawImage(image, 0, 0, side, side); - const pixels = ctx.getImageData(0, 0, side, side); - const { data } = pixels; - const rgb = Number.parseInt(color.slice(1), 16); - const red = (rgb >> 16) / 255; - const green = ((rgb >> 8) & 255) / 255; - const blue = (rgb & 255) / 255; - let left = side, - top = side, - right = -1, - bottom = -1; - for (let y = 0; y < side; y++) { - for (let x = 0; x < side; x++) { - const i = (y * side + x) * 4; - if (!data[i + 3]) continue; - data[i] *= red; - data[i + 1] *= green; - data[i + 2] *= blue; - left = Math.min(left, x); - right = Math.max(right, x); - top = Math.min(top, y); - bottom = y; - } - } - if (right < 0) return null; - ctx.putImageData(pixels, 0, 0); - const width = right - left + 1; - const height = bottom - top + 1; - const scale = Math.min(size / height, (size * GLYPH_ASPECT) / width); - return { - canvas, - left, - top, - width, - height, - drawWidth: width * scale, - drawHeight: height * scale, - }; -} - -/** Load the map artwork once, then share each tinted device-density raster. */ -export function createCameraGlyphCache(createCanvas, source, onLoad) { - const glyphs = new Map(); - let image; - let ready = false; - return (size, dpr, color) => { - if (!image && typeof Image !== 'undefined') { - image = new Image(); - image.onload = () => { - ready = true; - onLoad?.(); - }; - image.src = source; - } - if (!ready) return null; - const key = `${size}:${dpr}:${color}`; - if (!glyphs.has(key)) { - glyphs.set(key, rasterizeGlyph(createCanvas(), image, size, dpr, color)); - } - return glyphs.get(key); - }; -} +// Painted bounds of the camera art, scaled from its viewBox to source pixels. +const GLYPH_SOURCE = [3.4, 13.4, 28.1, 19.5].map((v) => (v * 48) / 36); +const GLYPH_SOURCE_ASPECT = 28.1 / 19.5; /** Merged camera groups and their last painted hit rectangles in CSS pixels. */ export function createCountMarkers( registerPaintLane, id, refreshView, - createCanvas = () => globalThis.document?.createElement('canvas'), + keyholeAlpha, ) { - let dpr = Math.max(1, Number(globalThis.window?.devicePixelRatio) || 1); + let hardUi = null; + let sprite = null; + let spriteReady = false; const markers = []; const hits = []; const textMetrics = new Map(); @@ -125,15 +77,15 @@ export function createCountMarkers( active: false, target: 'shared', }); - const glyphFor = createCameraGlyphCache( - createCanvas, - IDLE_CAMERA_ICON, - () => { - if (!markers.length) return; - refreshGlyphs(); - lane?.requestPaint(); - }, - ); + function loadSprite() { + if (sprite || typeof Image === 'undefined') return; + sprite = new Image(); + sprite.onload = () => { + spriteReady = true; + if (markers.length) lane?.requestPaint(); + }; + sprite.src = COUNT_CAMERA_ICON; + } fonts?.addEventListener?.('loadingdone', fontsLoaded); /** Font changes can widen a pill enough to merge it with its neighbor. */ @@ -149,14 +101,12 @@ export function createCountMarkers( const text = formatCameraCount(count); let metrics = textMetrics.get(text); if (!metrics) { - measureCtx ??= createCanvas()?.getContext('2d'); - if (measureCtx) { - measureCtx.font = FONT; - measureCtx.textBaseline = 'middle'; - metrics = measureCtx.measureText(text); - } else { - metrics = { width: text.length * 8 }; - } + measureCtx ??= globalThis.document + .createElement('canvas') + .getContext('2d'); + measureCtx.font = FONT; + measureCtx.textBaseline = 'middle'; + metrics = measureCtx.measureText(text); textMetrics.set(text, metrics); } const diameter = COUNT_BASE_PX + COUNT_PX_PER_DECADE * Math.log10(count); @@ -175,9 +125,8 @@ export function createCountMarkers( COUNT_GLYPH_TOP_MIN_PX + (COUNT_GLYPH_TOP_MAX_PX - COUNT_GLYPH_TOP_MIN_PX) * grown - radius; - // Width-only metrics use half the 12 px type size on each side of the baseline. - const ascent = metrics.actualBoundingBoxAscent ?? 6; - const descent = metrics.actualBoundingBoxDescent ?? 6; + const ascent = metrics.actualBoundingBoxAscent; + const descent = metrics.actualBoundingBoxDescent; const labelY = COUNT_LABEL_DROP * radius + (ascent - descent) / 2; // Each row must clear the ring at the edge where the circle is narrowest. const chordAt = (y) => 2 * Math.sqrt(Math.max(0, radius ** 2 - y ** 2)); @@ -204,14 +153,18 @@ export function createCountMarkers( /** * Reuse marker slots in ground-key order, and invalidate only changed frames. - * `groundHeight(lon, lat)` answers the drawn terrain height in metres, or - * null where it is not loaded; with it a count stands on the ground it - * marks whatever heights its cameras hold. + * `groundHeight(lon, lat)` gives the drawn terrain in metres, or a non-finite + * value where it has not loaded. A count stands on that ground when available + * and otherwise uses its cameras' mean mount height. */ function update(cells, project, groundHeight = null) { // Lone cameras take part so that one beside a count joins it. let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key)); - const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON); + const footprint = (count, cell) => { + if (count > 1) return sizeFor(count); + const px = cell.iconPx ?? CAMERA_ICON_PX; + return { width: px, height: px }; + }; /** A lone camera keeps its icon's own position; a count goes to ground. */ const ground = (list) => { if (!groundHeight) return; @@ -224,7 +177,9 @@ export function createCountMarkers( }; for ( let pass = 0; - pass < COUNT_MERGE_PASSES && visible.length > 1; + pass < COUNT_MERGE_PASSES && + visible.length > 1 && + visible.some((cell) => cell.count > 1); pass++ ) { ground(visible); @@ -246,7 +201,7 @@ export function createCountMarkers( let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { const cell = visible[i]; - const marker = markers[i] ?? (markers[i] = { focus: 1 }); + const marker = (markers[i] ??= { focus: 1 }); const last = marker.cell; const size = sizeFor(cell.count); if ( @@ -258,16 +213,23 @@ export function createCountMarkers( last.groundM !== cell.groundM ) { marker.pos = cellCenter(cell); + marker.cullPos = liftedForHorizon(marker.pos); + marker.hudHidden = undefined; changed = true; - } else if ( - last.west !== cell.west || - last.east !== cell.east || - last.south !== cell.south || - last.north !== cell.north || - last.low !== cell.low || - last.high !== cell.high - ) { - changed = true; + } + // A count hidden by the HUD leaves its lone cameras visible as icons. + if (hardUi && cell.lone?.length) { + const at = project(marker.pos); + if ( + at && + hardUi({ + x: at.x - size.width / 2, + y: at.y - size.height / 2, + w: size.width, + h: size.height, + }) + ) + for (const lone of cell.lone) lone.absorbed = false; } changed ||= size.text !== marker.text || @@ -276,24 +238,19 @@ export function createCountMarkers( size.labelY !== marker.labelY; marker.cell = cell; Object.assign(marker, size); - marker.glyph = glyphFor(size.glyphHeight, dpr, CAMERA_GREEN); // Paint never grows the hit buffer, even when a pan reveals every group. hits[i] ??= {}; } markers.length = visible.length; + if (markers.length) loadSprite(); // Keep the last frame pickable until the host clears its pixels. lane?.setActive(markers.length > 0 || hitCount > 0); if (changed) lane?.requestPaint(); } - /** Attach the raster for the current overlay density to each visible group. */ - function refreshGlyphs() { - for (const marker of markers) - marker.glyph = glyphFor(marker.glyphHeight, dpr, CAMERA_GREEN); - } - /** Draw at device density using the host's CSS-pixel transform and projection. */ function paint(frame) { + hardUi = frame.overlapsHardUi ?? hardUi; if (!markers.length) { // Deactivating invalidates the host, so finish the shared frame first. if (hitCount) queueMicrotask(deactivateIfEmpty); @@ -302,10 +259,7 @@ export function createCountMarkers( } hitCount = 0; const { ctx, occluder, viewProjectionMatrix: m } = frame; - if (dpr !== frame.dpr) { - dpr = frame.dpr; - refreshGlyphs(); - } + let refresh = false; ctx.save(); try { ctx.font = FONT; @@ -316,7 +270,7 @@ export function createCountMarkers( const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; - if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.pos))) + if (!(w > 0) || (occluder && !occluder.isPointVisible(marker.cullPos))) continue; const x = (0.5 + (0.5 * (m[0] * px + m[4] * py + m[8] * pz + m[12])) / w) * @@ -333,11 +287,22 @@ export function createCountMarkers( rect.x >= frame.width || rect.y >= frame.height || rect.x + rect.w <= 0 || - rect.y + rect.h <= 0 || - frame.overlapsHardUi(rect) + rect.y + rect.h <= 0 ) continue; - ctx.globalAlpha = marker.focus; + const hidden = Boolean(hardUi?.(rect)); + if (marker.hudHidden !== hidden) { + marker.hudHidden = hidden; + // A first frame or moving HUD can change which lone icons must show. + refresh ||= marker.cell.lone?.some( + (cell) => cell.absorbed === hidden, + ); + } + if (hidden) continue; + const fade = + frame.keyhole && keyholeAlpha ? keyholeAlpha(x, y, frame.keyhole) : 1; + if (!(fade > 0)) continue; + ctx.globalAlpha = marker.focus * fade; ctx.beginPath(); ctx.roundRect( rect.x + STROKE_INSET, @@ -355,18 +320,15 @@ export function createCountMarkers( ctx.lineWidth = RING_PX; ctx.stroke(); ctx.fillStyle = CAMERA_GREEN; - const glyph = marker.glyph; - if (glyph) { + if (spriteReady) { + const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT; ctx.drawImage( - glyph.canvas, - glyph.left, - glyph.top, - glyph.width, - glyph.height, - x - glyph.drawWidth / 2, - y + marker.glyphBottom - glyph.drawHeight, - glyph.drawWidth, - glyph.drawHeight, + sprite, + ...GLYPH_SOURCE, + x - width / 2, + y + marker.glyphBottom - marker.glyphHeight, + width, + marker.glyphHeight, ); } ctx.fillText(marker.text, x, y + marker.labelY); @@ -376,6 +338,7 @@ export function createCountMarkers( } finally { ctx.restore(); } + if (refresh) queueMicrotask(refreshView); } /** Resolve the topmost group actually painted at this screen position. */ @@ -383,13 +346,14 @@ export function createCountMarkers( if (!point) return null; for (let i = hitCount - 1; i >= 0; i--) { const rect = hits[i]; - if ( - point.x >= rect.x && - point.x <= rect.x + rect.w && - point.y >= rect.y && - point.y <= rect.y + rect.h - ) - return rect.cell; + const radius = rect.h / 2; + // Distance from the pill's horizontal centre segment. + const dx = Math.max( + 0, + Math.abs(point.x - (rect.x + rect.w / 2)) - (rect.w - rect.h) / 2, + ); + const dy = point.y - (rect.y + radius); + if (dx * dx + dy * dy <= radius * radius) return rect.cell; } return null; } @@ -407,7 +371,7 @@ export function createCountMarkers( /** Unhook this viewer's painter and its font listener. */ function dispose() { - markers.length = hits.length = hitCount = 0; + hide(); fonts?.removeEventListener?.('loadingdone', fontsLoaded); lane?.unregister(); } diff --git a/src/layers/cctv/countMarkers.test.mjs b/src/layers/cctv/countMarkers.test.mjs new file mode 100644 index 0000000000..f3b2398a99 --- /dev/null +++ b/src/layers/cctv/countMarkers.test.mjs @@ -0,0 +1,136 @@ +import { test, beforeEach, afterEach } from 'node:test'; +import assert from 'node:assert/strict'; +import { createCountMarkers } from './countMarkers.js'; +import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; + +const W = 800; +const H = 600; +const A = 6378137; +// Screen x = W/2 + ecefY/30, y = H/2 - ecefZ/30 (as the view-thinning fixture). +const project = (p) => ({ x: W / 2 + p.y / 30, y: H / 2 - p.z / 30 }); +const lonFor = (x) => (Math.asin(((x - W / 2) * 30) / A) * 180) / Math.PI; +const matrix = new Float64Array([ + 0, + 0, + 0, + 0, + 2 / (30 * W), + 0, + 0, + 0, + 0, + 2 / (30 * H), + 0, + 0, + 0, + 0, + 0, + 1, +]); + +function cellAt(key, x, count, height = 0) { + const cell = createCameraCell(key); + for (let i = 0; i < count; i++) + addCellCamera(cell, { lon: lonFor(x), lat: 0, absoluteHeightM: height }); + return cell; +} + +let painter; +function makeCtx() { + return { + labels: [], + globalAlpha: 1, + save() {}, + restore() {}, + beginPath() {}, + roundRect() {}, + stroke() {}, + fill() {}, + drawImage() {}, + fillText(text, x, y) { + this.labels.push({ text, x, y, alpha: this.globalAlpha }); + }, + }; +} +function paint(overrides = {}) { + const ctx = makeCtx(); + painter({ + ctx, + width: W, + height: H, + dpr: 1, + viewProjectionMatrix: matrix, + occluder: { isPointVisible: () => true }, + overlapsHardUi: () => false, + ...overrides, + }); + return ctx.labels; +} +function counts(refresh = () => {}, keyholeAlpha) { + return createCountMarkers( + (_lane, paintFn) => { + painter = paintFn; + return { requestPaint() {}, setActive() {}, unregister() {} }; + }, + 'counts', + refresh, + keyholeAlpha, + ); +} + +beforeEach(() => { + globalThis.document = { + createElement: () => ({ + getContext: () => ({ + measureText: (text) => ({ + width: text.length * 7, + actualBoundingBoxAscent: 4, + actualBoundingBoxDescent: 4, + }), + }), + }), + }; +}); +afterEach(() => { + delete globalThis.document; +}); +test('a count on ground below the ellipsoid stays painted while its mounts are above the horizon', () => { + const m = counts(); + m.update([cellAt('a', 400, 2, -20)], project, () => -30); + const eye = fromDegrees(-0.009, 0, 30); // about 1 km away, 30 m above the ellipsoid + const horizon = horizonFrom(eye); + assert.equal(horizon.isPointVisible(fromDegrees(lonFor(400), 0, -20)), true); + assert.equal(paint({ occluder: horizon }).length, 1); +}); + +test('a lone camera clear of the HUD keeps its icon when the count beside it is hidden', async () => { + const hud = { overlapsHardUi: (rect) => rect.x < 200 }; + for (const paintedFirst of [true, false]) { + const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)]; + const m = counts(() => m.update(cells, project)); + if (paintedFirst) paint(hud); + m.update(cells, project); + const labels = paint(hud); + await Promise.resolve(); + assert.ok(!cells[1].absorbed || labels.length > 0); + // Moving the HUD at rest also changes whether the lone icon is needed. + paint(); + await Promise.resolve(); + assert.equal(cells[1].absorbed, true); + paint(hud); + await Promise.resolve(); + assert.equal(cells[1].absorbed, false); + m.dispose(); + } +}); + +test('counts fade with the Scope keyhole like the callouts', () => { + const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha); + m.update([cellAt('a', 400, 2)], project); + assert.equal(paint({ keyhole: { alpha: 0.25 } })[0].alpha, 0.25); + assert.deepEqual(paint({ keyhole: { alpha: 0 } }), []); + assert.equal(m.pickedCell({ x: 400, y: 300 }), null); + assert.equal(paint()[0].alpha, 1); +}); diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 84db00b13e..194be38cc0 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -1,4 +1,4 @@ -import { fromDegrees } from '../../geo/ellipsoid.js'; +import { fromDegreesInto } from '../../geo/ellipsoid.js'; import { findGlobe } from '../../render/rendererOf.js'; import { SUPPORT_KEYS, @@ -233,6 +233,12 @@ export function createGround({ state: layerState, services, parts, source }) { // Stale-record guard: init() may have re-run (destroy/init cycle) while // the batch was in flight — only touch records still live in the map. if (layerState._recordById.get(record.camera.id) !== record) return null; + // The drawn terrain beats a fallback. Only a real batch answer replaces it. + if ( + prior.source === 'geoid-fallback' && + record.groundPrior?.source === 'drawn-terrain' + ) + return null; record.groundPrior = prior; // Keep the cheap pre-enable altitude consistent for records whose // geometry hasn't been applied yet (applyFrustumGeometry overwrites it). @@ -247,14 +253,12 @@ export function createGround({ state: layerState, services, parts, source }) { if (!record.frustumGeometry) { if (!record.position) return null; // In place: the record keeps its position object. - const { x, y, z } = fromDegrees( + fromDegreesInto( record.camera.lon, record.camera.lat, record.camera.absoluteHeightM, + record.position, ); - record.position.x = x; - record.position.y = y; - record.position.z = z; parts.rendering.moveCameraIcon(record); return 'moved'; } @@ -274,19 +278,17 @@ export function createGround({ state: layerState, services, parts, source }) { } /** - * A camera the height batch never answered for (a failed or rate-limited - * chunk leaves it on the catalog's fabricated ground) takes the terrain - * the globe draws under it as its prior, so that it stands on the surface - * the user sees. `rangeM` is how far the eye was when the terrain was - * read: a closer look reads finer terrain and replaces it, and so does a - * batch answer that arrives later. + * Applies drawn terrain as a drawn-terrain prior. The read records the eye + * distance (rangeM), globe surface version (surface) and whether terrain + * loading had finished (settled). Reading from under half that range or + * receiving a later Re:Earth answer replaces the height. * @returns {'moved'|'applied'|null} As `applyGroundPrior`. */ - function adoptDrawnGround(record, heightM, rangeM) { + function adoptDrawnGround(record, heightM, read) { return applyGroundPrior(record, { ellipsoid: heightM, source: 'drawn-terrain', - rangeM, + ...read, }); } diff --git a/src/layers/cctv/ground.test.mjs b/src/layers/cctv/ground.test.mjs new file mode 100644 index 0000000000..c804460f19 --- /dev/null +++ b/src/layers/cctv/ground.test.mjs @@ -0,0 +1,64 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createGround } from './ground.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; + +function setup(record) { + const calls = { culling: 0, geometry: [], notify: 0 }; + const state = { + _viewer: null, + _recordById: new Map([[record.camera.id, record]]), + }; + const parts = { + rendering: { + refreshHorizonCulling: () => (calls.culling++, true), + moveCameraIcon() {}, + }, + geometryQueue: { enqueueViewGeometry() {} }, + presentation: { notifyListeners: () => calls.notify++ }, + geometry: { + // Same choice as geometry.updateRecordGeometry on a globe with a cold floor cell. + updateRecordGeometry(r) { + calls.geometry.push( + ground.groundPriorAltFor(r) + r.camera.mountHeightM, + ); + }, + }, + }; + const ground = createGround({ + state, + services: { + ground: { resolveGroundFloorCells: async () => {} }, + terrain: { resolveEllipsoidalGround: async () => [] }, + }, + parts, + }); + return { ground, calls }; +} + +test('a late geoid fallback leaves a drawn-terrain height in place', () => { + const camera = { + id: 'a', + lat: 42, + lon: -118, + mountHeightM: 8, + absoluteHeightM: 1880, + }; + const record = { + camera, + position: fromDegrees(camera.lon, camera.lat, 1880), + frustumGeometry: {}, + frustumPositions: {}, + groundSamples: {}, + groundResolved: {}, + groundPrior: { ellipsoid: 1872, source: 'drawn-terrain', rangeM: 2000 }, + }; + const { ground, calls } = setup(record); + ground.applyLateGroundPriors( + [record], + [{ ellipsoid: 0, source: 'geoid-fallback' }], + ); + + assert.equal(record.groundPrior.source, 'drawn-terrain'); + assert.ok(!calls.geometry.includes(8), 'mount not lowered to the fallback'); +}); diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index b20592d396..7dbdcc0fca 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -1,6 +1,6 @@ import { fromDegrees } from '../../geo/ellipsoid.js'; import { distance, dot } from '../../geo/vector.js'; -import { canvasOf, findCamera } from '../../render/rendererOf.js'; +import { canvasOf, findCamera, findGlobe } from '../../render/rendererOf.js'; import { viewshedColors, cameraHue } from '../../data/cctvViewshed.js'; import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { GIZMO_ID_PREFIX } from '../../data/cctvGizmo.js'; @@ -103,6 +103,30 @@ export function createLifecycle({ * listeners to its camera; one against the same viewer keeps them. */ function attachViewListeners() { + const globe = findGlobe(layerState._viewer); + if (layerState._surfaceListenerGlobe !== globe) { + layerState._surfaceListener?.(); + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = globe; + } + if (!layerState._surfaceListener && globe?.on) { + // Refresh drawn heights when terrain finishes loading or the surface changes. + let version = globe.surfaceVersion?.(); + let terrainPending = globe.isSettled?.('terrain') === false ? 1 : 0; + layerState._surfaceListener = globe.on('progress', (progress) => { + const next = globe.surfaceVersion?.(); + const loaded = progress?.terrainPending === 0 && terrainPending !== 0; + const swapped = next !== version; + version = next; + terrainPending = progress?.terrainPending ?? terrainPending; + if ( + (loaded || swapped) && + layerState._enabled && + !layerState._cameraMoving + ) + settleView(); + }); + } const viewCamera = findCamera(layerState._viewer); if ( layerState._viewListenerCamera && @@ -140,6 +164,9 @@ export function createLifecycle({ /** Drop the move listeners; nothing reports the end of a move after it. */ function detachViewListeners() { + layerState._surfaceListener?.(); + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = null; layerState._horizonCullListener?.(); layerState._horizonCullListener = null; layerState._moveStartListener?.(); @@ -287,9 +314,8 @@ export function createLifecycle({ coverageEntities: [], projection: null, // Task 5 (height-datum fix): regime-aware ground resolution state. - // groundPrior — { ellipsoid, source } from the Re:Earth batch - // (null until a late batch lands). The prior applies in EVERY - // regime and is the terrain-globe resolution outright. + // groundPrior — { ellipsoid, source } from the Re:Earth batch, or + // drawn-terrain with its read conditions for an unanswered camera. // groundResolved — PER-REGIME one-shot latch (regime key → // boolean): true once this record's resolution completed for that // regime; such records are excluded from the completion pass so diff --git a/src/layers/cctv/lifecycle.test.mjs b/src/layers/cctv/lifecycle.test.mjs index 205997721b..080fbcfb47 100644 --- a/src/layers/cctv/lifecycle.test.mjs +++ b/src/layers/cctv/lifecycle.test.mjs @@ -72,3 +72,37 @@ test('the view listeners follow the camera port and let go on teardown', () => { assert.deepEqual(counts(second.camera), [0, 0]); assert.equal(state._viewListenerCamera, null); }); + +test('terrain loading and surface changes rerun the view pass', () => { + const viewer = {}; + let version = 1, + progress, + removed = false; + bindRenderer(viewer, { + camera: fakeCameraPort().port, + globe: { + surfaceVersion: () => version, + on(event, cb) { + assert.equal(event, 'progress'); + progress = cb; + return () => { + removed = true; + }; + }, + }, + }); + const { lifecycle, passes } = lifecycleFor({ + _viewer: viewer, + _enabled: true, + }); + lifecycle.attachViewListeners(); + progress({ terrainPending: 2 }); + assert.equal(passes.length, 0); + progress({ terrainPending: 0 }); + assert.equal(passes.length, 1); + version++; + progress({ terrainPending: 0 }); + assert.equal(passes.length, 2); + lifecycle.detachViewListeners(); + assert.ok(removed); +}); diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index 8e69d9e5e8..a52d419782 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,3 +1,5 @@ +import { distance } from '../../geo/vector.js'; +import { rangeForBoundingSphere } from '../../data/cameraFraming.js'; import { isFollowing } from '../../data/followed.js'; import { cellBounds } from '../../data/cctvCellCounts.js'; import { CCTV_FOCUS_RESULT, VIEW_CELL_PX, VIEW_MIN_CELL_M } from './policy.js'; @@ -64,6 +66,16 @@ export function createNavigation({ return true; } + /** What holds the view instead of a CCTV flight, or null when it is free. */ + function viewHeldBy(viewer) { + if ( + typeof document !== 'undefined' && + document.body?.classList.contains('cockpit-mode') + ) + return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE; + return isFollowing(viewer) ? CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW : null; + } + /** * Flies the viewer's camera to frame the specified CCTV camera, * looking along its heading from above. @@ -75,14 +87,12 @@ export function createNavigation({ function focusCctvRecord(viewer, record, duration = 2.2) { if (!viewer || !record) return CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA; - if ( - typeof document !== 'undefined' && - document.body?.classList.contains('cockpit-mode') - ) { + const held = viewHeldBy(viewer); + if (held === CCTV_FOCUS_RESULT.COCKPIT_ACTIVE) { console.debug('[Data:CCTV] focus ignored while cockpit owns the camera'); return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE; } - if (isFollowing(viewer)) { + if (held === CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW) { console.debug( '[Data:CCTV] focus ignored while a tracked entity owns the camera', ); @@ -108,17 +118,24 @@ export function createNavigation({ /** Frame a group's padded bounds from above, including coincident mounts. */ function zoomToCell(cell) { const viewer = layerState._viewer; + if (!viewer || viewHeldBy(viewer)) return; 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. + // Half the range where cells stop grouping, so even coincident mounts split. const closeRange = (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); - const range = Math.max(closeRange, bounds.radius / Math.sin(halfFov)); + // Approach long groups in halves so every click gets closer. + const halfway = pose.position + ? distance(pose.position, bounds.center) / 2 + : Infinity; + const range = Math.min( + halfway, + Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)), + ); camera.flyToBounds(bounds, { offset: { heading: 0, pitch: -Math.PI / 2, range }, durationS: 1.2, diff --git a/src/layers/cctv/policy.js b/src/layers/cctv/policy.js index 87fdaf4c32..291cea53e8 100644 --- a/src/layers/cctv/policy.js +++ b/src/layers/cctv/policy.js @@ -60,65 +60,38 @@ export const GEO_PROGRESS_NOTIFY_INTERVAL_MS = 300; export const GEO_PROGRESS_NOTIFY_BATCH_LIMIT = 10; -// View thinning: camera icons show only on or near the screen, and each -// camera competes for a world-anchored grid cell sized to about VIEW_CELL_PX -// at its distance from the viewer (in power-of-two metre steps, so a pan -// keeps the same winners until a camera's distance crosses a step). Cells -// smaller than VIEW_MIN_CELL_M do not thin: -// close up every camera shows, co-located ones included. +// View thinning groups cameras into world-anchored cells of about VIEW_CELL_PX +// at their distance. Power-of-two metre steps keep cells stable during a pan. +// A cell with several cameras draws one count. Its best-ranked camera represents +// it in the picker. Cells smaller than VIEW_MIN_CELL_M do not group, so +// every camera shows close up. export const VIEW_CELL_PX = 40; export const VIEW_MIN_CELL_M = 60; -// Cameras on one mount (the same point to about a metre) draw side by side, +// Cameras within this horizontal distance in metres share a mount. +export const VIEW_SITE_M = 1.5; + +// Cameras on one mount (VIEW_SITE_M) draw side by side, // this many pixels apart, once they show as icons. export const VIEW_SITE_SPREAD_PX = 30; -// Cameras without a ground height that one view pass may read from the drawn -// terrain. The rest wait for the next pass. +// Drawn-terrain reads per view pass for unanswered cameras and for re-reads +// of drawn heights. Off-screen cameras can use at most half of the budget. +// Remaining reads wait for the next pass. export const VIEW_GROUND_READS = 300; -// Diameter at one camera before applying the size limits, in CSS pixels. -export const COUNT_BASE_PX = 38; - -// Extra diameter for each tenfold increase in camera count. -export const COUNT_PX_PER_DECADE = 5; - -// Minimum height of a count marker in CSS pixels. -export const COUNT_MIN_HEIGHT_PX = 40; - -// Maximum height of a count marker in CSS pixels. -export const COUNT_MAX_HEIGHT_PX = 58; - -// Clear fill between the count and the inside of the ring, in CSS pixels. -export const COUNT_TEXT_PADDING_PX = 6; - -// Height of the camera glyph in the smallest and the largest marker. -export const COUNT_GLYPH_MIN_PX = 7.5; -export const COUNT_GLYPH_MAX_PX = 10; - -// Clear fill above the glyph in the smallest and the largest marker. -export const COUNT_GLYPH_TOP_MIN_PX = 3; -export const COUNT_GLYPH_TOP_MAX_PX = 4; - -// Clear fill between the glyph's top corners and the inside of the ring. -export const COUNT_GLYPH_PADDING_PX = 2; - -// The middle of the digits sits this share of the inner radius below the -// marker's centre, which leaves the glyph clear of the count. -export const COUNT_LABEL_DROP = 0.2; +/** + * The camera icon's drawn size (px). Its SVG is 48 px: 1.25× + * near scale on a 2× display draws it at 60 device px, so it is rasterised + * past the drawn size to stay sharp there. + */ +export const CAMERA_ICON_PX = 24; // Minimum gap between the outer rims of two separate markers. export const COUNT_MERGE_GAP_PX = 4; -// On-screen size of a lone camera's icon when testing it against a count -// marker: an icon closer than the merge gap joins that count. -export const COUNT_SINGLE_ICON_PX = 24; - -// 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. @@ -230,33 +203,51 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({ /** * 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. + * 2× display draws it at 60 device px, and it stays sharp there. Active and + * live cameras use cyan art with a billboard tint. Idle cameras use white + * and gray art so the billboard green shows true. The overlay draws the + * green variant directly. */ -function cameraIcon(neutral) { - const tone = (original, gray) => (neutral ? gray : original); - const stroke = tone('#75e7ff', '#fff'); +function cameraIcon(tint = null) { + function tone(original, gray) { + if (!tint) return original; + const shade = parseInt(gray.slice(1, 3), 16) / 255; + return ( + '#' + + tint + .slice(1) + .match(/../g) + .map((channel) => + Math.round(parseInt(channel, 16) * shade) + .toString(16) + .padStart(2, '0'), + ) + .join('') + ); + } + const stroke = tone('#75e7ff', '#ffffff'); const svg = ` - - - + + + - - + + - + `; return 'data:image/svg+xml;base64,' + btoa(svg); } -export const CAMERA_ICON = cameraIcon(false); -export const IDLE_CAMERA_ICON = cameraIcon(true); +export const CAMERA_ICON = cameraIcon(); +export const IDLE_CAMERA_ICON = cameraIcon('#ffffff'); /** * Seed camera definitions used when no live sources are available. @@ -496,6 +487,7 @@ export const CAMERA_SEEDS = [ /** Shared accent for idle still cameras and grouped cameras. */ export const CAMERA_GREEN = '#5dff8f'; +export const COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN); export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN); diff --git a/src/layers/cctv/presentation.js b/src/layers/cctv/presentation.js index ed8a715ebd..1b25cef84d 100644 --- a/src/layers/cctv/presentation.js +++ b/src/layers/cctv/presentation.js @@ -229,9 +229,12 @@ export function createPresentation({ // separately from the currently applied frustum ground. Google-3D may // legitimately refine the latter to the rendered mesh, so callers must // not infer the prior by subtracting mount height from live geometry. - groundPriorM: Number.isFinite(record.groundPrior?.ellipsoid) - ? record.groundPrior.ellipsoid - : null, + // A height read from drawn terrain is unavailable as a Re:Earth prior. + groundPriorM: + Number.isFinite(record.groundPrior?.ellipsoid) && + record.groundPrior.source !== 'drawn-terrain' + ? record.groundPrior.ellipsoid + : null, intrinsics: camera.intrinsics ? { ...camera.intrinsics } : null, extrinsics: camera.extrinsics ? { ...camera.extrinsics } : null, anchor: camera.anchor ? { ...camera.anchor } : null, @@ -310,11 +313,11 @@ export function createPresentation({ } /** - * `{ id, city, name }` for the active camera, then every camera the view - * pass shows: what the camera picker lists. A whole catalog would put tens - * of thousands of options in the DOM and slow every layout. The same array - * is returned until the view or the active camera changes, so a consumer - * can compare it by identity. + * `{ id, city, name }` for the active camera, then each camera shown as an + * icon and the best-ranked camera of each visible group. A whole catalog + * would put tens of thousands of options in the DOM and slow every layout. + * Consumers can compare the array by identity until the picker records or + * active camera change. * @returns {{id: string, city: string, name: string}[]} */ diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index a2d5a7663c..4fee5ce9cb 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -4,6 +4,9 @@ import { isHeadingEstimated } from './headingConfidence.js'; import { ACTIVE_CAMERA_COLOR, CAMERA_ICON, + CAMERA_ICON_PX, + COUNT_MERGE_GAP_PX, + VIEW_SITE_M, IDLE_CAMERA_ICON, IDLE_CAMERA_COLOR, LIVE_CAMERA_COLOR, @@ -30,11 +33,16 @@ import { findQuery, } from '../../render/rendererOf.js'; import { heightsOf } from '../../queries/heights.js'; -import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js'; +import { + fromDegrees, + fromDegreesInto, + toLonLatH, + WGS84, +} from '../../geo/ellipsoid.js'; import { eastNorthUp } from '../../geo/frames.js'; import { poseProjector } from '../../geo/frustum.js'; import { horizonFrom } from '../../geo/horizon.js'; -import { distance } from '../../geo/vector.js'; +import { add, distance, dot, scale, sub } from '../../geo/vector.js'; const IDLE_ICON_STYLE = { image: IDLE_CAMERA_ICON, color: IDLE_CAMERA_COLOR }; const ACTIVE_ICON_STYLE = { image: CAMERA_ICON, color: ACTIVE_CAMERA_COLOR }; @@ -56,12 +64,6 @@ const samePoint = (a, b) => /** Degrees to radians. */ const toRadians = (degrees) => (degrees * Math.PI) / 180; -/** - * The camera icon's drawn size (px). Its SVG is 48 px (policy.js): 1.25× - * near scale on a 2× display draws it at 60 device px, so it is rasterised - * past the drawn size to stay sharp there. - */ -const CAMERA_ICON_PX = 24; const CAMERA_SCALE_BY_DISTANCE = Object.freeze({ near: 350, nearValue: 1.25, @@ -153,6 +155,7 @@ export function createRendering({ services.overlays?.registerWorldOverlayPaintLane, `cctv:${iconSets}:counts`, refreshHorizonCulling, + services.overlays?.keyholeAlpha, ); return set.id; } @@ -170,7 +173,7 @@ export function createRendering({ const id = record.camera.id; return { id, - pos: copyPoint(record.position), + pos: copyPoint(record.spreadPosition ?? record.position), ...cameraIconStyleFor(record), size: [CAMERA_ICON_PX, CAMERA_ICON_PX], scale: 1, @@ -211,14 +214,18 @@ export function createRendering({ function moveCameraIcon(record) { const icons = layerState._icons; if (!icons || !record.position) return; + // A camera drawn beside its mount mates keeps its offset from the mount. + if (record.spreadOffset) + record.spreadPosition = add(record.position, record.spreadOffset); + const pos = record.spreadPosition ?? record.position; const item = icons.item(record.camera.id); // A camera whose icon waited for a position is drawn now. if (!item) { icons.put(cameraIconItem(record)); return; } - if (samePoint(item.pos, record.position)) return; - icons.put({ ...item, pos: copyPoint(record.position) }); + if (samePoint(item.pos, pos)) return; + icons.put({ ...item, pos: copyPoint(pos) }); } /** Select the sprite and tint together when a camera changes state. */ @@ -235,7 +242,10 @@ export function createRendering({ focusPassIsNeeded, advanceSpriteFocus, focusAlphaNeedsWrite, + nearFarScalarValueAtDistance, } = services.focus; + const iconScaleAt = (range) => + nearFarScalarValueAtDistance?.(CAMERA_SCALE_BY_DISTANCE, range) ?? 1; /** * Focus modulation rides the layer's existing animation loop; no additional @@ -292,9 +302,14 @@ export function createRendering({ let writes = 0; let transitioning = false; let activeCount = 0; - /** A changed focus factor for a camera icon or a painted count. */ + /** + * A changed focus factor for an icon or count. CCTV publishes no tracked + * focus target, so every icon is ambient. + */ function changedFocus(owner, position, shown, width, height, current) { const focus = advanceSpriteFocus(owner, { + // Keep hidden owners in the active count until their dim alpha clears, + // so the focus pass keeps running while they recover. screenPosition: shown && position ? screenPositionFor(position) : null, cameraDistance: position ? cameraDistanceFor(position) : Number.NaN, nowMs, @@ -342,13 +357,16 @@ export function createRendering({ } /** - * 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. + * Cull far-side cameras on the CPU because the hidden globe writes no depth. + * Group the rest by ground cell. _viewRecords holds the active camera and + * every nearby icon outside a count for geometry and cards. Cells smaller + * than VIEW_MIN_CELL_M do not form groups. _pickerRecords adds the + * best-ranked camera of each visible cell. Both arrays keep their identity + * while their contents are unchanged. * * Runs on camera settle, throttled during motion, on resize, enable and * activation changes — never per frame. - * @returns {boolean} Whether the shown set changed. + * @returns {boolean} Whether the shown set or the picker list changed. */ function refreshHorizonCulling() { @@ -386,15 +404,26 @@ export function createRendering({ const picker = []; const cells = new Map(); const visibleCells = []; - // The terrain the globe draws, where it is the surface (not on the - // photoreal stack) and loaded: null elsewhere. + // Drawn terrain where the globe is the surface. The photoreal stack has + // no reader, and unloaded tiles return a non-finite height. const heights = heightsOf(layerState._viewer); + const globe = findGlobe(layerState._viewer); const groundHeight = - findQuery(layerState._viewer) && - findGlobe(layerState._viewer)?.isGlobeVisible?.() === true + findQuery(layerState._viewer) && globe?.isGlobeVisible?.() === true ? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' }) : null; + const surface = globe?.surfaceVersion?.() ?? 0; + const terrainSettled = globe?.isSettled?.('terrain') ?? true; let groundReads = groundHeight ? VIEW_GROUND_READS : 0; + let offscreenReads = groundReads / 2; + let eyeGround; + const column = { x: 0, y: 0, z: 0 }; + const inReadWindow = (s) => + s && + s.x >= -width && + s.x <= 2 * width && + s.y >= -height && + s.y <= 2 * height; const regrounded = []; for (const record of layerState._records) { const position = record.position; @@ -412,39 +441,66 @@ export function createRendering({ continue; let screen = project(position); let range = distance(position, viewer); - // A camera the height batch never answered for (no prior, or the - // geoid fallback a failed chunk leaves) sits near sea level, which can - // be kilometres under the terrain: it would project to the wrong - // place, drift as the view moves and measure too far for its cell. - // Anywhere near the screen, it takes the drawn terrain. + // Missing, unresolved and fallback priors can put a mount kilometres + // below the terrain, shifting its projection and inflating its cell. + // Read nearby mounts again from under half the range, on finer terrain + // after loading, or on a different surface. const prior = record.groundPrior; const drawn = prior?.source === 'drawn-terrain'; + const unanswered = + !Number.isFinite(prior?.ellipsoid) || prior.source === 'geoid-fallback'; if ( groundReads > 0 && - (!prior || - prior.source === 'geoid-fallback' || - (drawn && prior.rangeM > 2 * range)) && - screen && - screen.x >= -width && - screen.x <= 2 * width && - screen.y >= -height && - screen.y <= 2 * height + !record.regroundPending && + (unanswered || + (drawn && + (prior.rangeM > 2 * range || + prior.surface !== surface || + (!prior.settled && terrainSettled)))) ) { - groundReads--; - const ground = groundHeight(record.camera.lon, record.camera.lat); - if (Number.isFinite(ground)) { - if (drawn && Math.abs(ground - prior.ellipsoid) < 1) { - prior.rangeM = range; - } else if (record.frustumGeometry) { - // Recomputing geometry writes draw sets: after this pass. - regrounded.push([record, ground, range]); - } else if ( - parts.ground.adoptDrawnGround(record, ground, range) === 'moved' - ) { - screen = project(position); - range = distance(position, viewer); + let probe = inReadWindow(screen) ? screen : null; + if (!probe && unanswered) { + // Its height is a guess. Try the ground under the eye instead. + if (eyeGround === undefined) { + const eye = toLonLatH(viewer); + eyeGround = eye ? (groundHeight(eye.lon, eye.lat) ?? null) : null; + groundReads--; + } + if (Number.isFinite(eyeGround)) { + fromDegreesInto( + record.camera.lon, + record.camera.lat, + eyeGround + (record.camera.mountHeightM || 0), + column, + ); + const at = project(column); + if (inReadWindow(at)) probe = at; } } + const onScreen = + probe && + probe.x >= 0 && + probe.x <= width && + probe.y >= 0 && + probe.y <= height; + if (probe && groundReads > 0 && (onScreen || offscreenReads > 0)) { + groundReads--; + if (!onScreen) offscreenReads--; + const ground = groundHeight(record.camera.lon, record.camera.lat); + if (Number.isFinite(ground)) { + const read = { rangeM: range, surface, settled: terrainSettled }; + if (drawn && Math.abs(ground - prior.ellipsoid) < 1) + Object.assign(prior, read); + else if (record.frustumGeometry) { + // Recomputing geometry writes draw sets after this pass. + record.regroundPending = true; + regrounded.push([record, ground, read]); + } else parts.ground.adoptDrawnGround(record, ground, read); + } + } + // The probe reuses the projector's result, and the mount may have moved. + screen = project(position); + range = distance(position, viewer); } const nearScreen = screen && @@ -453,13 +509,25 @@ export function createRendering({ screen.y >= minY && screen.y <= maxY; const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range; - if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) { + if (record.camera.id === activeId) { if (!nearScreen) continue; record.viewPass = record.pickerPass = pass; shown.push(record); picker.push(record); continue; } + if (!(cellM >= VIEW_MIN_CELL_M)) { + if (!nearScreen) continue; + // Too close to group, but a count beside it can still take it in. + const cell = createCameraCell(`near:${record.camera.id}`); + addCellCamera(cell, record.camera); + cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range); + cell.winner = record; + cell.rank = 0; + record.viewCell = cell; + visibleCells.push(cell); + continue; + } const key = worldCellKey(record, cellM); let cell = cells.get(key); if (!cell) { @@ -467,6 +535,7 @@ export function createRendering({ cells.set(key, cell); } addCellCamera(cell, record.camera); + if (cell.count === 1) cell.iconPx = CAMERA_ICON_PX * iconScaleAt(range); record.viewCell = cell; if (!nearScreen) continue; // The picker ranks only candidates that were in its padded viewport. @@ -491,6 +560,7 @@ export function createRendering({ } } spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); + clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; let cardsChanged = false; @@ -514,6 +584,7 @@ export function createRendering({ fields.pos = copyPoint(record.spreadPosition); } else if (record.spreadPosition) { // No longer beside a mount mate: back onto its own position. + record.spreadOffset = null; record.spreadPosition = null; fields.pos = copyPoint(record.position); } @@ -543,10 +614,11 @@ export function createRendering({ */ function reground(entries) { let changed = false; - for (const [record, ground, range] of entries) + for (const [record, ground, read] of entries) { + record.regroundPending = false; changed = - parts.ground.adoptDrawnGround(record, ground, range) !== null || - changed; + parts.ground.adoptDrawnGround(record, ground, read) !== null || changed; + } if (!changed) return; if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry(); parts.presentation.notifyListeners(); @@ -554,7 +626,7 @@ export function createRendering({ /** * Cameras on one mount would draw as one icon with several callouts. Among - * the cameras shown, those that share a point to about a metre get draw + * the cameras shown, those within VIEW_SITE_M horizontally get draw * positions side by side along the screen's horizontal, in id order, * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The * record's own position is untouched: geometry and cards keep the mount. @@ -562,15 +634,31 @@ export function createRendering({ function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { const { right, direction, position: eye } = pose; if (!right || !direction || shown.length < 2) return; - const mounts = new Map(); + const grid = new Map(); + const mounts = []; + const axes = eastNorthUp(eye); for (const record of shown) { - const { lat, lon } = record.camera; - const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`; - const mates = mounts.get(key); - if (mates) mates.push(record); - else mounts.set(key, [record]); + // Sea-level coordinates compare horizontal distance across longitude + // and latitude boundaries, including the antimeridian. + const p = fromDegrees(record.camera.lon, record.camera.lat, 0); + const col = Math.floor(dot(p, axes.x) / VIEW_SITE_M); + const row = Math.floor(dot(p, axes.y) / VIEW_SITE_M); + let mount; + for (let i = col - 1; !mount && i <= col + 1; i++) + for (let j = row - 1; !mount && j <= row + 1; j++) + mount = grid + .get(`${i}:${j}`) + ?.find((site) => distance(p, site.p) <= VIEW_SITE_M); + if (!mount) { + mount = { p, mates: [] }; + mounts.push(mount); + const key = `${col}:${row}`; + if (!grid.has(key)) grid.set(key, []); + grid.get(key).push(mount); + } + mount.mates.push(record); } - for (const mates of mounts.values()) { + for (const { mates } of mounts) { if (mates.length < 2) continue; mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id)); for (let i = 0; i < mates.length; i++) { @@ -586,16 +674,63 @@ export function createRendering({ VIEW_SITE_SPREAD_PX * metresPerPixelPerMetre * depth; - record.spreadPosition = { - x: p.x + right.x * metres, - y: p.y + right.y * metres, - z: p.z + right.z * metres, - }; + record.spreadOffset = scale(right, metres); + record.spreadPosition = add(p, record.spreadOffset); record.spreadPass = pass; } } } + /** Move the active camera's icon beside any count marker that would cover it. */ + function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) { + if (!layerState._activeCameraId) return; + const record = layerState._recordById.get(layerState._activeCameraId); + const markers = layerState._counts?.markers; + if ( + record?.viewPass !== pass || + !markers?.length || + !pose.right || + !pose.direction + ) + return; + const spread = record.spreadPass === pass; + const p = spread ? record.spreadPosition : record.position; + const screen = project(p); + if (!screen) return; + const { x, y } = screen; + const half = + (CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2; + const spans = []; + for (const marker of markers) { + const at = project(marker.pos); + if ( + !at || + Math.abs(y - at.y) >= marker.height / 2 + half + COUNT_MERGE_GAP_PX + ) + continue; + const reach = marker.width / 2 + half + COUNT_MERGE_GAP_PX; + spans.push([at.x - reach, at.x + reach]); + } + // Leave the entire overlapping interval, including an adjacent count. + spans.sort((a, b) => a[0] - b[0]); + let left = Infinity, + right = -Infinity; + for (const [start, end] of spans) { + if (start >= right) { + if (left < x && x < right) break; + left = start; + right = end; + } else right = Math.max(right, end); + } + if (!(left < x && x < right)) return; + const shift = x - left < right - x ? left - x : right - x; + const depth = dot(sub(p, pose.position), pose.direction); + const offset = scale(pose.right, shift * metresPerPixelPerMetre * depth); + record.spreadOffset = spread ? add(record.spreadOffset, offset) : offset; + record.spreadPosition = add(record.position, record.spreadOffset); + record.spreadPass = pass; + } + /** * Canvas coordinates for world positions, from the eye's pose by the * renderer's perspective projection (geo/frustum.js): one pose read per diff --git a/src/layers/cctv/rendering.test.mjs b/src/layers/cctv/rendering.test.mjs index 6d4600ec3b..f2548d9aff 100644 --- a/src/layers/cctv/rendering.test.mjs +++ b/src/layers/cctv/rendering.test.mjs @@ -153,6 +153,7 @@ test('the icons go with the viewer that drew them, whichever tears down', () => name, paint, options, + setActive() {}, unregister() { this.disposed = true; }, diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 6948b2a8a2..9364911537 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -1,3 +1,4 @@ +import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; import { isTrackingClickGesture } from '../../data/trackingClickGesture.js'; export function createSelection({ @@ -7,7 +8,7 @@ export function createSelection({ source, }) { const { CCTV_ACTIVATION_RESULT } = services.activation; - const { resolvePickId } = services.picking; + const { resolvePickId, findPickOwner } = services.picking; /** * Returns the camera record for the currently active camera. A stale ID falls @@ -29,6 +30,23 @@ export function createSelection({ return fallback; } + /** A card painted above the count, or another layer's object, owns the click. */ + function countYields(event) { + const { x, y } = event.screenPosition; + if ( + layerState._cctvOverlayHost?.hitTest(x, y, { + sourceId: CCTV_OVERLAY_SOURCE_ID, + })?.entryId + ) + return true; + const top = event.topHit; + if (!top) return false; + const drawHit = event.drawHit; + if (drawHit) return !parts.rendering.extractPickedCameraId(drawHit); + const id = resolvePickId(top); + return id !== null && findPickOwner?.(id) !== 'cctv'; + } + /** * Bind CCTV activation to clean taps. Drag-like and long-press gestures do * not reach camera activation or focus dispatch. @@ -44,7 +62,7 @@ export function createSelection({ const cell = layerState._enabled && layerState._counts?.pickedCell(event.screenPosition); - if (cell) { + if (cell && !countYields(event)) { parts.navigation.zoomToCell(cell); return; } @@ -146,9 +164,9 @@ export function createSelection({ // is looking at ever asks. void parts.ground.resolveFootprintGround(record); record.activationDone = true; - // 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. + // The active icon always shows and the previous one rejoins its cell. + // Restyle coverage after the view pass sets grouping. Its coverage + // neighbours join the working set and are queued for grounding. parts.rendering.refreshHorizonCulling(); parts.rendering.refreshCoverageStyles(); parts.geometryQueue.enqueueViewGeometry(); diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index f03ded5ceb..297a2f674f 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -1,3 +1,4 @@ +import * as picking from '../../data/pickRegistry.js'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js'; @@ -103,3 +104,49 @@ test('a count click preserves the provisional opening pick until the view settle unbind(); } }); + +test("a count click yields to a card above it and to another layer's object, not to a CCTV icon", () => { + let zooms = 0, + clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: () => ({}) }, + _cctvOverlayHost: { + hitTest: (x) => (x === 14 ? { entryId: 'cam-1' } : null), + }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { + extractPickedCameraId: (hit) => + hit?.set === 'cctv-icons' ? hit.id : null, + }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + picking.registerPickOwner('cctv', (id) => id.startsWith('cam-')); + try { + for (const [x, topHit, expected] of [ + [14, null, [0, 1]], + [20, { set: 'flights', id: 'abc' }, [0, 2]], + [20, { set: 'cctv-icons', id: 'cam-2' }, [1, 2]], + [20, null, [2, 2]], + [20, { set: 'flights', id: 'cam-2' }, [2, 3]], + ]) { + click({ + screenPosition: { x, y: 26 }, + topHit, + drawHit: topHit, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.deepEqual([zooms, clicks], expected); + } + } finally { + picking.unregisterPickOwner('cctv'); + } +}); diff --git a/src/layers/cctv/state.js b/src/layers/cctv/state.js index a6778de8f3..95c08e2f13 100644 --- a/src/layers/cctv/state.js +++ b/src/layers/cctv/state.js @@ -96,13 +96,14 @@ export function createState({ services }) { // work over these, not the whole catalog. layerState._viewRecords = []; - // Includes a health-ranked representative for each visible group. + // The view records plus the best-ranked camera of each visible cell. layerState._pickerRecords = []; - // Coverage ids refreshCoverageStyles last drew: part of the geometry - // working set even when their icons are thinned out. - + // The active camera's coverage neighbours, including grouped ones. A + // grouping change in this cohort requires a coverage refresh. layerState._coverageCohort = null; + // The cohort minus grouped cameras, last drawn by refreshCoverageStyles. + // These belong to the geometry working set even off screen. layerState._coverageVisibleIds = new Set(); // View pass triggers besides camera settle: an interval while the camera @@ -117,6 +118,9 @@ export function createState({ services }) { // The camera port the moveStart/moveEnd listeners are on. layerState._viewListenerCamera = null; + // Reruns the view pass when terrain loads or the surface changes. + layerState._surfaceListener = null; + layerState._surfaceListenerGlobe = null; // A motion pass changed the shown set and the settle pass has not yet told // subscribers; the camera pose the last view pass ran at. From f6982dc934e7e7c8062ad44662504486eed9fa93 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 17:52:50 +0400 Subject: [PATCH 12/56] fix(cctv): a count click yields to what is on top and keeps its group in frame - A count click stands aside when an overlay label or another layer's card already took the click, and CCTV now claims a count click in the shared pick registry, so the flights layer no longer reads it as an empty-map click and keeps tracking its aircraft. - The flight to a group halves the distance only while the group stays in frame; otherwise it flies to the nearest ground cell of the group, so a tilted click no longer ends with no camera on screen. - Counts hidden under the HUD no longer push the active icon aside, and a lone camera that would move a merged count under the HUD leaves the original count and its icon as they were. - Cameras on one mount are spread before counts merge, so a spread icon no longer slides under a neighbouring count. - The ground module comment says how a camera without a batch height takes the drawn terrain. --- docs/CURRENT-STATE.md | 16 +++-- scripts/format-scope.json | 2 + src/data/cctvCards.js | 2 + src/data/cctvCellCounts.js | 17 ++++- src/data/pickRegistry.js | 40 ++++++++++-- src/data/pickRegistry.test.mjs | 41 ++++++++++++ src/layers/cctv/countMarkers.js | 51 +++++++++------ src/layers/cctv/countMarkers.test.mjs | 19 ++++++ src/layers/cctv/count_click_framing.test.mjs | 67 ++++++++++++++++++++ src/layers/cctv/count_click_overlay.test.mjs | 65 +++++++++++++++++++ src/layers/cctv/ground.js | 5 +- src/layers/cctv/lifecycle.js | 13 +++- src/layers/cctv/navigation.js | 37 ++++++++--- src/layers/cctv/rendering.js | 31 +++++---- src/layers/cctv/selection.js | 55 +++++++++++----- src/layers/cctv/selection.test.mjs | 61 ++++++++++++++++++ 16 files changed, 452 insertions(+), 70 deletions(-) create mode 100644 src/layers/cctv/count_click_framing.test.mjs create mode 100644 src/layers/cctv/count_click_overlay.test.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 4f2b6e34a6..76c142c7b3 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1998,10 +1998,13 @@ middle. The marker grows with the count and paints on the world overlay at callout resolution. The count covers the whole cell up to the horizon, including its off-screen cameras. Overlapping markers merge and add their counts. A lone camera whose icon would touch a marker joins the nearest one, unless the HUD -hides that marker. The active camera keeps its own icon beside any marker that -would cover it and stays out of the count. A click on a marker zooms in on its -group, at least halving the distance each time. The view stays put while the -cockpit or a tracked object holds it. Ambient cards and coverage attach only to +hides the merged marker. In that case the lone camera keeps its icon and the +count stays where it was before the merge. The active camera keeps its own icon +beside any marker that would cover it and stays out of the count. A click on a +marker zooms in on its group, at least halving the distance each time. If halving +would leave the group wider than the frame, the view zooms in on the group's +ground cell nearest the eye. The cockpit or a tracked object holds the view +in place. Ambient cards and coverage attach only to cameras drawn as icons. On a globe map a marker stands on the drawn terrain. A camera the height batch never answered for takes the drawn terrain as its ground once it is near the screen. It reads that height again from much closer, once @@ -2131,7 +2134,10 @@ trail, a route. A layer under another layer's card or label (`isUnderOtherCard`) does nothing: it neither acts on its item there nor treats the click as empty space, so a tracked aircraft stays tracked and a selection stays selected. Context (`src/ui/entityContextBridge.js`) names -nothing under a card. With no card on top, the scene rules are unchanged. +nothing under a card. A layer can claim a target it paints outside the overlay's +entries (`registerClickClaim`) where no card or label is on top. A CCTV count +claims each click that zooms to it, so a tracked aircraft stays tracked. +With no card or claim on top, the scene rules are unchanged. World-overlay hit rectangles are what is painted on screen until the next paint: an overlay change (a click subscriber publishing its selection card) no longer clears them mid-click, and a paint that draws nothing clears them diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 3cfaf54072..8f1f106931 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -662,6 +662,8 @@ "src/layers/cctv/source.test.mjs", "src/layers/cctv/frames.test.mjs", "src/layers/cctv/countMarkers.test.mjs", + "src/layers/cctv/count_click_overlay.test.mjs", + "src/layers/cctv/count_click_framing.test.mjs", "src/layers/cctv/ground.test.mjs", "src/layers/cctv/rendering.test.mjs", "src/data/alprCameras.js", diff --git a/src/data/cctvCards.js b/src/data/cctvCards.js index 63b08fa441..caa13c9dfe 100644 --- a/src/data/cctvCards.js +++ b/src/data/cctvCards.js @@ -86,6 +86,8 @@ const RETRY_BASE_MS = 15_000; const RETRY_MAX_MS = 5 * 60 * 1000; export const CCTV_OVERLAY_SOURCE_ID = 'cctv'; +/** The source a CCTV count marker takes clicks as. */ +export const CCTV_COUNT_CARD_SOURCE_ID = 'cctv-count'; export const CCTV_THUMBNAIL_ALTITUDE_SCALE = Object.freeze({ fullEnd: CCTV_CARD_SCALE_FULL_M, midEnd: CCTV_CARD_SCALE_MID_M, diff --git a/src/data/cctvCellCounts.js b/src/data/cctvCellCounts.js index 9a551413a8..558f675b61 100644 --- a/src/data/cctvCellCounts.js +++ b/src/data/cctvCellCounts.js @@ -136,7 +136,8 @@ function visitNeighbors(marker, grid, gap, visit) { * one grid bucket. Even the widest pill can only touch its eight neighbors. * A cell with one camera takes the footprint `sizeFor(1)` gives its icon and * joins the nearest count it touches. Lone cameras never join each other - * or bridge two counts. + * or bridge two counts. A spread icon's `offsetPx` shifts its footprint sideways. + * A merged group lists its ground cells in `parts`. * Ground cells stay intact for the camera picker and individual-icon pass. */ export function mergeCountCells(cells, project, sizeFor, gap) { @@ -150,7 +151,7 @@ export function mergeCountCells(cells, project, sizeFor, gap) { // The view projector reuses its result object. return { cell, - x: screen?.x, + x: screen ? screen.x + (cell.offsetPx ?? 0) : undefined, y: screen?.y, halfSegment: (width - height) / 2, radius: height / 2, @@ -201,8 +202,10 @@ export function mergeCountCells(cells, project, sizeFor, gap) { } else { const group = createCameraCell(seed.cell.key); group.lone = []; + group.parts = []; for (const { cell } of members) { addCell(group, cell); + group.parts.push(...(cell.parts ?? [cell])); if (cell.count === 1) group.lone.push(cell); else if (cell.lone) group.lone.push(...cell.lone); } @@ -218,3 +221,13 @@ export function mergeCountCells(cells, project, sizeFor, gap) { } return groups; } + +/** Rebuild a group's count under its original key, excluding lone cameras. */ +export function withoutLoneCameras(group) { + const counts = (group.parts ?? []).filter((cell) => cell.count > 1); + if (!counts.length) return null; + const core = createCameraCell(group.key); + core.parts = counts; + for (const cell of counts) addCell(core, cell); + return core; +} diff --git a/src/data/pickRegistry.js b/src/data/pickRegistry.js index f11f6e8553..f9868e90df 100644 --- a/src/data/pickRegistry.js +++ b/src/data/pickRegistry.js @@ -154,6 +154,24 @@ export function pickContact(query, position, options = {}) { let _overlayHitTest = null; /** @type {WeakMap} */ const clickCards = new WeakMap(); +const _clickClaims = new Map(); + +/** + * Register a target drawn outside the world overlay's entries, such as a CCTV + * count. A claim runs once per click where no card or label is painted above + * it and must not call `clickCard`. + * @param {string} layerId + * @param {(click: object) => ({sourceId: string, entryId: string}|null)} claim + */ +export function registerClickClaim(layerId, claim) { + if (!layerId || typeof claim !== 'function') return; + _clickClaims.set(layerId, claim); +} + +/** Remove a layer's claim when it is disabled or destroyed. */ +export function unregisterClickClaim(layerId) { + _clickClaims.delete(layerId); +} /** * Sets (or with null, clears) the hit test that names the card or label @@ -166,8 +184,8 @@ export function setClickCardHitTest(hitTest) { } /** - * The topmost interactive card or label painted at a click, read once per - * click so every handler of it sees the same one whatever ran first. + * The topmost interactive card or label painted at a click, or a target a + * layer claims (`registerClickClaim`). All handlers share one result per click. * @param {{screenPosition?: {x: number, y: number}}|null|undefined} click * @returns {{sourceId: string, entryId: string}|null} */ @@ -179,14 +197,28 @@ export function clickCard(click) { try { card = _overlayHitTest?.(at?.x, at?.y) ?? null; } catch { - // a broken hit test must never break click handling + clickCards.set(click, null); + return null; + } + if (!card) { + // A claim that reads this click again cannot re-enter the claims loop. + clickCards.set(click, null); + for (const claim of _clickClaims.values()) { + try { + card = claim(click) ?? null; + } catch { + card = null; + } + if (card) break; + } } clickCards.set(click, card); return card; } /** - * True when another layer's card or label is painted on top at a click. The + * True when another layer has the top card, label, or claimed target + * (`registerClickClaim`) at a click. The * card on top takes the click: a scene item under it does not act, and is * not empty space either, so the layer leaves its selection alone. * @param {object} click The shared dispatcher event. diff --git a/src/data/pickRegistry.test.mjs b/src/data/pickRegistry.test.mjs index eb3347fe8c..90b4d3824c 100644 --- a/src/data/pickRegistry.test.mjs +++ b/src/data/pickRegistry.test.mjs @@ -20,6 +20,8 @@ import { clickCard, isUnderOtherCard, setClickCardHitTest, + registerClickClaim, + unregisterClickClaim, } from './pickRegistry.js'; // --------------------------------------------------------------------------- @@ -237,3 +239,42 @@ test("the card on top is read once per click, and only another layer's card coun setClickCardHitTest(null); } }); + +test('a click claim is the card on top only where no card or label is painted', () => { + const event = (x) => ({ screenPosition: { x, y: 5 } }); + let calls = 0; + registerClickClaim('counts', (click) => { + calls++; + return click.screenPosition.x === 4 + ? { sourceId: 'counts', entryId: 'k' } + : null; + }); + try { + registerClickClaim('counts', null); + const click = event(4); + assert.equal(isUnderOtherCard(click), true); + assert.equal(isUnderOtherCard(click, ['counts']), false); + assert.equal(calls, 1); + assert.equal(clickCard(event(9)), null); + const quake = { sourceId: 'quake-card', entryId: 'q1' }; + setClickCardHitTest(() => quake); + assert.deepEqual(clickCard(event(4)), quake); + assert.equal(calls, 2); + setClickCardHitTest(() => { + throw new Error('broken overlay hit test'); + }); + assert.equal(clickCard(event(4)), null); + assert.equal(calls, 2); + setClickCardHitTest(null); + + unregisterClickClaim('counts'); + assert.equal(clickCard(event(4)), null); + registerClickClaim('counts', () => { + throw new Error('broken claim'); + }); + assert.equal(clickCard(event(4)), null); + } finally { + unregisterClickClaim('counts'); + setClickCardHitTest(null); + } +}); diff --git a/src/layers/cctv/countMarkers.js b/src/layers/cctv/countMarkers.js index e071f07238..20cc73174d 100644 --- a/src/layers/cctv/countMarkers.js +++ b/src/layers/cctv/countMarkers.js @@ -3,6 +3,7 @@ import { cellLonLat, formatCameraCount, mergeCountCells, + withoutLoneCameras, } from '../../data/cctvCellCounts.js'; import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js'; import { @@ -200,7 +201,27 @@ export function createCountMarkers( ground(visible); let changed = visible.length !== markers.length; for (let i = 0; i < visible.length; i++) { - const cell = visible[i]; + let cell = visible[i]; + // If the merged count is under the HUD, restore the count and its lone icons. + if (hardUi && cell.lone?.length) { + const at = project(cellCenter(cell)); + const { width, height } = sizeFor(cell.count); + const rect = at && { + x: at.x - width / 2, + y: at.y - height / 2, + w: width, + h: height, + }; + if (rect && hardUi(rect)) { + for (const lone of cell.lone) lone.absorbed = false; + const core = withoutLoneCameras(cell); + if (core) { + core.releasedAt = rect; + ground([core]); + cell = core; + } + } + } const marker = (markers[i] ??= { focus: 1 }); const last = marker.cell; const size = sizeFor(cell.count); @@ -217,20 +238,6 @@ export function createCountMarkers( marker.hudHidden = undefined; changed = true; } - // A count hidden by the HUD leaves its lone cameras visible as icons. - if (hardUi && cell.lone?.length) { - const at = project(marker.pos); - if ( - at && - hardUi({ - x: at.x - size.width / 2, - y: at.y - size.height / 2, - w: size.width, - h: size.height, - }) - ) - for (const lone of cell.lone) lone.absorbed = false; - } changed ||= size.text !== marker.text || size.width !== marker.width || @@ -267,6 +274,8 @@ export function createCountMarkers( ctx.textBaseline = 'middle'; for (let i = 0; i < markers.length; i++) { const marker = markers[i]; + // The core can stay visible while the HUD uncovers the merged count. + if (marker.cell.releasedAt) refresh ||= !hardUi(marker.cell.releasedAt); const { height } = marker; const { x: px, y: py, z: pz } = marker.pos; const w = m[3] * px + m[7] * py + m[11] * pz + m[15]; @@ -291,12 +300,14 @@ export function createCountMarkers( ) continue; const hidden = Boolean(hardUi?.(rect)); - if (marker.hudHidden !== hidden) { + const previous = marker.hudHidden; + if (previous !== hidden) { marker.hudHidden = hidden; - // A first frame or moving HUD can change which lone icons must show. - refresh ||= marker.cell.lone?.some( - (cell) => cell.absorbed === hidden, - ); + // The active icon steps aside only for visible counts. + refresh ||= + hidden || + previous !== undefined || + marker.cell.lone?.some((cell) => cell.absorbed === hidden); } if (hidden) continue; const fade = diff --git a/src/layers/cctv/countMarkers.test.mjs b/src/layers/cctv/countMarkers.test.mjs index f3b2398a99..b3d3461b71 100644 --- a/src/layers/cctv/countMarkers.test.mjs +++ b/src/layers/cctv/countMarkers.test.mjs @@ -126,6 +126,25 @@ test('a lone camera clear of the HUD keeps its icon when the count beside it is } }); +test('a count stays visible when a lone camera would move it under the HUD', async () => { + const cells = [cellAt('a', 200, 2), cellAt('b', 234, 1)]; + const hud = { overlapsHardUi: (rect) => rect.x + rect.w > 225 }; + const m = counts(() => m.update(cells, project)); + paint(hud); + m.update(cells, project); + assert.equal(paint(hud)[0]?.text, '2'); + assert.equal(cells[1].absorbed, false); + await Promise.resolve(); + paint(hud); + await Promise.resolve(); + + paint(); + await Promise.resolve(); + assert.equal(cells[1].absorbed, true); + assert.equal(paint()[0]?.text, '3'); + m.dispose(); +}); + test('counts fade with the Scope keyhole like the callouts', () => { const m = counts(undefined, (_x, _y, keyhole) => keyhole.alpha); m.update([cellAt('a', 400, 2)], project); diff --git a/src/layers/cctv/count_click_framing.test.mjs b/src/layers/cctv/count_click_framing.test.mjs new file mode 100644 index 0000000000..5667d51c99 --- /dev/null +++ b/src/layers/cctv/count_click_framing.test.mjs @@ -0,0 +1,67 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { distance } from '../../geo/vector.js'; +import { + addCellCamera, + createCameraCell, + mergeCountCells, +} from '../../data/cctvCellCounts.js'; +import { createNavigation } from './navigation.js'; + +// A count of four merged in a tilted view: two pairs 10 km and 40 km north of +// an eye 800 m up. After the click, at least one member must be in frame. +test('a count click from a tilted view keeps the group members in the frame', () => { + const viewer = {}; + const flights = []; + const fovy = Math.PI / 3; + const aspectRatio = 800 / 600; + const unbind = bindRenderer(viewer, { + camera: { + pose: () => ({ fovy, aspectRatio, position: fromDegrees(0, 0, 800) }), + flyToBounds: (bounds, options) => flights.push({ bounds, options }), + }, + canvas: { clientHeight: 600, clientWidth: 800 }, + }); + try { + const metresPerDegree = 111_320; + const members = []; + const cells = [10_000, 40_000].map((start) => { + const cell = createCameraCell(String(start)); + for (const northM of [start, start + 10]) { + const lat = northM / metresPerDegree; + addCellCamera(cell, { lat, lon: 0, absoluteHeightM: 8 }); + members.push(fromDegrees(0, lat, 8)); + } + return cell; + }); + const screens = [ + { x: 400, y: 300 }, + { x: 433, y: 300 }, + ]; + const groups = mergeCountCells( + cells, + () => screens.shift(), + () => ({ width: 40, height: 40 }), + 2, + ); + assert.equal(groups.length, 1); + assert.equal(groups[0].count, 4); + const state = { _viewer: viewer }; + const navigation = createNavigation({ state, parts: {} }); + navigation.zoomToCell(groups[0]); + assert.equal(flights.length, 1); + const { range, pitch } = flights[0].options.offset; + assert.equal(pitch, -Math.PI / 2); + const { center } = flights[0].bounds; + const halfSpanM = range * Math.tan(fovy / 2); + assert.ok( + members.some((point) => distance(point, center) <= halfSpanM), + 'no member of the group is in the final frame', + ); + assert.ok(range < distance(fromDegrees(0, 0, 800), center)); + } finally { + unbind(); + } +}); diff --git a/src/layers/cctv/count_click_overlay.test.mjs b/src/layers/cctv/count_click_overlay.test.mjs new file mode 100644 index 0000000000..69fb55d541 --- /dev/null +++ b/src/layers/cctv/count_click_overlay.test.mjs @@ -0,0 +1,65 @@ +import * as picking from '../../data/pickRegistry.js'; +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import { createSelection } from './selection.js'; + +function setup() { + let zooms = 0, + clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: () => ({}) }, + _cctvOverlayHost: { hitTest: () => null }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { extractPickedCameraId: () => null }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + return { click, counts: () => [zooms, clicks] }; +} + +test('a click a painted overlay target took (Space Missions label) does not fly to the count', () => { + const { click, counts } = setup(); + // What the dispatcher hands subscribers after an onOverlayClick handler returned true. + click({ + screenPosition: { x: 20, y: 26 }, + overlay: true, + topHit: { set: '', id: null, surface: false }, + drawHit: null, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.equal( + counts()[0], + 0, + 'count flight ran although an overlay target handled the click', + ); +}); + +test("another layer's world-overlay card on top (clickCard) takes the click from the count", () => { + const { click, counts } = setup(); + picking.setClickCardHitTest(() => ({ + sourceId: 'earthquakes', + entryId: 'eq-1', + })); + try { + click({ + screenPosition: { x: 20, y: 26 }, + topHit: null, + drawHit: null, + gesture: { travelPx: 0, durationMs: 20 }, + }); + assert.ok( + picking.isUnderOtherCard({ screenPosition: { x: 1, y: 1 } }, ['cctv']), + ); + assert.equal(counts()[0], 0, 'count flight ran under another layer card'); + } finally { + picking.setClickCardHitTest(null); + } +}); diff --git a/src/layers/cctv/ground.js b/src/layers/cctv/ground.js index 194be38cc0..cec1798036 100644 --- a/src/layers/cctv/ground.js +++ b/src/layers/cctv/ground.js @@ -22,11 +22,12 @@ export function createGround({ state: layerState, services, parts, source }) { * - `google-3d` — photoreal stack: globe hidden, the visible Google 3D * tileset IS the surface → one-shot scene sampling refines. * - `terrain-globe` — any globe stack: the Re:Earth point-height prior IS the - * resolution (zero scene queries). + * resolution. A camera the batch left unanswered takes the + * drawn terrain from the view pass (`adoptDrawnGround`). * * Only an explicit `false` (the photoreal stack hides the globe) selects * `google-3d`; undefined/null (no viewer / torn down) must fall to the regime - * that never touches the scene. Pure — exported for the unit suite. + * that never samples the scene's tiles. Pure — exported for the unit suite. * @param {boolean|undefined|null} globeShow - Whether the renderer shows the * globe (`globe.isGlobeVisible()`). * @returns {'google-3d'|'terrain-globe'} diff --git a/src/layers/cctv/lifecycle.js b/src/layers/cctv/lifecycle.js index bfe194197b..8230b7457c 100644 --- a/src/layers/cctv/lifecycle.js +++ b/src/layers/cctv/lifecycle.js @@ -23,8 +23,14 @@ export function createLifecycle({ source, }) { const { activateCctvCameraFromWorldClick } = services.activation; - const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } = - services.picking; + const { + resolvePickId, + registerPickOwner, + unregisterPickOwner, + clickCard, + registerClickClaim, + unregisterClickClaim, + } = services.picking; const { onFocusTargetAppear } = services.focus; const { releaseContinuousRender } = services.render; @@ -510,6 +516,7 @@ export function createLifecycle({ ); return Boolean(coverage && layerState._recordById.has(coverage[1])); }); + registerClickClaim?.('cctv', parts.selection.countClickCard); if (!layerState._activeCameraId && layerState._records.length) { layerState._activeCameraId = parts.navigation.openingCameraId(); layerState._autoHopSuspended = false; @@ -546,6 +553,7 @@ export function createLifecycle({ services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv'); layerState._enabled = false; unregisterPickOwner('cctv'); + unregisterClickClaim?.('cctv'); // ADJUST mode does not survive a layer toggle — predictable re-entry. layerState._calibrationMode = false; releaseContinuousRender('cctv-adjust'); @@ -580,6 +588,7 @@ export function createLifecycle({ parts.cards.handleVisibilityChange, ); unregisterPickOwner('cctv'); + unregisterClickClaim?.('cctv'); if (layerState._mapStackListener && typeof window !== 'undefined') { window.removeEventListener( 'gev:map-stack-changed', diff --git a/src/layers/cctv/navigation.js b/src/layers/cctv/navigation.js index 6590cc32da..9bd0014a80 100644 --- a/src/layers/cctv/navigation.js +++ b/src/layers/cctv/navigation.js @@ -1,7 +1,7 @@ import { distance } from '../../geo/vector.js'; import { rangeForBoundingSphere } from '../../data/cameraFraming.js'; import { isFollowing } from '../../data/followed.js'; -import { cellBounds } from '../../data/cctvCellCounts.js'; +import { cellBounds, cellCenter } 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'; @@ -131,6 +131,20 @@ export function createNavigation({ return CCTV_FOCUS_RESULT.FOCUSED; } + /** The ground cell of a group nearest the eye, or the group itself if unmerged. */ + function nearestPart(cell, eye) { + let nearest = cell; + let best = Infinity; + for (const part of cell.parts ?? []) { + const d = distance(eye, cellCenter(part)); + if (d < best) { + best = d; + nearest = part; + } + } + return nearest; + } + /** Frame a group's padded bounds from above, including coincident mounts. */ function zoomToCell(cell) { const viewer = layerState._viewer; @@ -140,18 +154,23 @@ export function createNavigation({ const tanHalfY = Math.tan((pose.fovy || Math.PI / 3) / 2); const canvas = canvasOf(viewer); const height = canvas?.clientHeight || canvas?.height || 1; - const bounds = cellBounds(cell); // Half the range where cells stop grouping, so even coincident mounts split. const closeRange = (VIEW_MIN_CELL_M * height) / (4 * VIEW_CELL_PX * tanHalfY); + const fitRange = (bounds) => + Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)); // Approach long groups in halves so every click gets closer. - const halfway = pose.position - ? distance(pose.position, bounds.center) / 2 - : Infinity; - const range = Math.min( - halfway, - Math.max(closeRange, rangeForBoundingSphere(viewer, bounds.radius)), - ); + const halfway = (bounds) => + pose.position ? distance(pose.position, bounds.center) / 2 : Infinity; + let bounds = cellBounds(cell); + const fit = fitRange(bounds); + let range = Math.min(halfway(bounds), fit); + // If the group exceeds the narrower side of the frame, approach its nearest part. + const tanHalf = tanHalfY * Math.min(1, pose.aspectRatio || 1); + if (range < fit && range * tanHalf < bounds.radius) { + bounds = cellBounds(nearestPart(cell, pose.position)); + range = Math.min(halfway(bounds), fitRange(bounds)); + } camera.flyToBounds(bounds, { offset: { heading: 0, pitch: -Math.PI / 2, range }, durationS: 1.2, diff --git a/src/layers/cctv/rendering.js b/src/layers/cctv/rendering.js index 4fee5ce9cb..2d5166d395 100644 --- a/src/layers/cctv/rendering.js +++ b/src/layers/cctv/rendering.js @@ -546,6 +546,17 @@ export function createRendering({ cell.rank = rank; } } + // Check each mount mate against counts where its icon will be drawn. + const lone = visibleCells.filter((cell) => cell.count === 1); + spreadSharedMounts( + shown.concat(lone.map((cell) => cell.winner)), + pose, + metresPerPixelPerMetre, + pass, + ); + for (const cell of lone) + cell.offsetPx = + cell.winner.spreadPass === pass ? cell.winner.spreadPx : 0; // A count stands on the drawn terrain too: its cell may be too far for // its cameras to have been read. Marks each lone camera that a count // marker beside it has taken in. @@ -559,7 +570,6 @@ export function createRendering({ shown.push(record); } } - spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass); clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass); const writes = []; let coverageChanged = false; @@ -626,10 +636,10 @@ export function createRendering({ /** * Cameras on one mount would draw as one icon with several callouts. Among - * the cameras shown, those within VIEW_SITE_M horizontally get draw - * positions side by side along the screen's horizontal, in id order, - * `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The - * record's own position is untouched: geometry and cards keep the mount. + * icon candidates, those within VIEW_SITE_M horizontally get draw positions + * side by side in id order, `VIEW_SITE_SPREAD_PX` apart on screen. A mate + * absorbed by a count keeps its place in the row. Geometry and cards stay + * on the mount. */ function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) { const { right, direction, position: eye } = pose; @@ -669,11 +679,9 @@ export function createRendering({ (p.x - eye.x) * direction.x + (p.y - eye.y) * direction.y + (p.z - eye.z) * direction.z; - const metres = - (i - (mates.length - 1) / 2) * - VIEW_SITE_SPREAD_PX * - metresPerPixelPerMetre * - depth; + const px = (i - (mates.length - 1) / 2) * VIEW_SITE_SPREAD_PX; + record.spreadPx = px; + const metres = px * metresPerPixelPerMetre * depth; record.spreadOffset = scale(right, metres); record.spreadPosition = add(p, record.spreadOffset); record.spreadPass = pass; @@ -681,7 +689,7 @@ export function createRendering({ } } - /** Move the active camera's icon beside any count marker that would cover it. */ + /** Only counts visible outside the HUD push the active icon aside. */ function clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass) { if (!layerState._activeCameraId) return; const record = layerState._recordById.get(layerState._activeCameraId); @@ -702,6 +710,7 @@ export function createRendering({ (CAMERA_ICON_PX * 1.25 * iconScaleAt(distance(p, pose.position))) / 2; const spans = []; for (const marker of markers) { + if (marker.hudHidden) continue; const at = project(marker.pos); if ( !at || diff --git a/src/layers/cctv/selection.js b/src/layers/cctv/selection.js index 9364911537..a8cb724abe 100644 --- a/src/layers/cctv/selection.js +++ b/src/layers/cctv/selection.js @@ -1,4 +1,7 @@ -import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js'; +import { + CCTV_COUNT_CARD_SOURCE_ID, + CCTV_OVERLAY_SOURCE_ID, +} from '../../data/cctvCards.js'; import { isTrackingClickGesture } from '../../data/trackingClickGesture.js'; export function createSelection({ @@ -8,7 +11,8 @@ export function createSelection({ source, }) { const { CCTV_ACTIVATION_RESULT } = services.activation; - const { resolvePickId, findPickOwner } = services.picking; + const { resolvePickId, findPickOwner, isUnderOtherCard } = services.picking; + const OWN_CARD_SOURCES = [CCTV_OVERLAY_SOURCE_ID, CCTV_COUNT_CARD_SOURCE_ID]; /** * Returns the camera record for the currently active camera. A stale ID falls @@ -30,15 +34,8 @@ export function createSelection({ return fallback; } - /** A card painted above the count, or another layer's object, owns the click. */ - function countYields(event) { - const { x, y } = event.screenPosition; - if ( - layerState._cctvOverlayHost?.hitTest(x, y, { - sourceId: CCTV_OVERLAY_SOURCE_ID, - })?.entryId - ) - return true; + /** Whether another layer's scene object owns the click at this count. */ + function sceneTakesCountClick(event) { const top = event.topHit; if (!top) return false; const drawHit = event.drawHit; @@ -47,6 +44,34 @@ export function createSelection({ return id !== null && findPickOwner?.(id) !== 'cctv'; } + /** Leave other layers' cards to the caller since clickCard also calls this. */ + function clickedCount(event) { + if ( + !isTrackingClickGesture(event.gesture) || + !layerState._enabled || + event.overlay + ) + return null; + const cell = layerState._counts?.pickedCell(event.screenPosition); + if (!cell) return null; + const { x, y } = event.screenPosition; + if ( + layerState._cctvOverlayHost?.hitTest(x, y, { + sourceId: CCTV_OVERLAY_SOURCE_ID, + })?.entryId + ) + return null; + return sceneTakesCountClick(event) ? null : cell; + } + + /** The count marker as the card on top of a click it takes, for every layer's clickCard. */ + function countClickCard(event) { + const cell = clickedCount(event); + return cell + ? { sourceId: CCTV_COUNT_CARD_SOURCE_ID, entryId: String(cell.key ?? '') } + : null; + } + /** * Bind CCTV activation to clean taps. Drag-like and long-press gestures do * not reach camera activation or focus dispatch. @@ -59,10 +84,9 @@ export function createSelection({ function bindCctvWorldClickGesture(input, onClick) { return input.onClick((event) => { if (!isTrackingClickGesture(event.gesture)) return; - const cell = - layerState._enabled && - layerState._counts?.pickedCell(event.screenPosition); - if (cell && !countYields(event)) { + const cell = clickedCount(event); + // Another layer's card or label painted above the count takes the click. + if (cell && !isUnderOtherCard?.(event, OWN_CARD_SOURCES)) { parts.navigation.zoomToCell(cell); return; } @@ -243,6 +267,7 @@ export function createSelection({ return { getActiveRecord, bindCctvWorldClickGesture, + countClickCard, setActiveCamera, deactivateActiveCamera, cctvEmptyClickDeselects, diff --git a/src/layers/cctv/selection.test.mjs b/src/layers/cctv/selection.test.mjs index 297a2f674f..6882eeff53 100644 --- a/src/layers/cctv/selection.test.mjs +++ b/src/layers/cctv/selection.test.mjs @@ -1,4 +1,5 @@ import * as picking from '../../data/pickRegistry.js'; +import { CCTV_COUNT_CARD_SOURCE_ID } from '../../data/cctvCards.js'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js'; @@ -150,3 +151,63 @@ test("a count click yields to a card above it and to another layer's object, not picking.unregisterPickOwner('cctv'); } }); + +test('a count click is the card on top for every layer, unless the count yields', () => { + let zooms = 0; + let clicks = 0; + const selection = createSelection({ + services: { activation: {}, picking }, + state: { + _enabled: true, + _counts: { pickedCell: (p) => (p?.x === 20 ? { key: 'g' } : null) }, + _cctvOverlayHost: { hitTest: () => null }, + }, + parts: { + navigation: { zoomToCell: () => zooms++ }, + rendering: { + extractPickedCameraId: (hit) => + hit?.set === 'cctv-icons' ? hit.id : null, + }, + }, + }); + const click = selection.bindCctvWorldClickGesture( + { onClick: (fn) => fn }, + () => clicks++, + ); + const event = (topHit = null, x = 20, durationMs = 20) => ({ + screenPosition: { x, y: 26 }, + topHit, + drawHit: topHit, + gesture: { travelPx: 0, durationMs }, + }); + picking.registerClickClaim('cctv', selection.countClickCard); + try { + const aircraftFirst = event(); + assert.equal(picking.isUnderOtherCard(aircraftFirst), true); + assert.deepEqual(picking.clickCard(aircraftFirst), { + sourceId: CCTV_COUNT_CARD_SOURCE_ID, + entryId: 'g', + }); + click(aircraftFirst); + assert.deepEqual([zooms, clicks], [1, 0]); + + const cctvFirst = event(); + click(cctvFirst); + assert.equal(picking.isUnderOtherCard(cctvFirst), true); + assert.deepEqual([zooms, clicks], [2, 0]); + + for (const [e, claimed, expected] of [ + [event({ set: 'flights', id: 'abc' }), false, [2, 1]], + [event({ set: 'cctv-icons', id: 'cam-2' }), true, [3, 1]], + [event(null, 20, 1000), false, [3, 1]], + [event(null, 60), false, [3, 2]], + [{ ...event(), overlay: true }, false, [3, 3]], + ]) { + assert.equal(picking.isUnderOtherCard(e), claimed); + click(e); + assert.deepEqual([zooms, clicks], expected); + } + } finally { + picking.unregisterClickClaim('cctv'); + } +}); From 77fe8299d79840983059b710d858c91ec838b352 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Thu, 19 Nov 2026 18:24:10 +0400 Subject: [PATCH 13/56] fix(alpr): tighten model spec matching and card text - Name the G3 record "AutoVu SharpV G3" and the SharpX record "XGA", so a bare SharpV or SharpX tag shows no specs without a separate wrapper. - Reuse the CCTV layer's Bosch MIC-7522-Z30 record instead of a copy. - Drop the brand from the SPEC line when the equipment line already names it, so long lines fit the card; pass the summary to entity properties. - Fall back to the OSM `brand` tag when `manufacturer` is missing. - Reject non-string or overlong model/manufacturer values before matching. - Remove the unused `brandAliases` parameter; shorten JSDoc and comments. - Cover the tile `model` path and the megapixel summary in tests; fold duplicate tests into existing ones. - Docs and changelog: the default hourly extract has no `model`; any source that supplies it shows the SPEC line. --- DATA_SOURCES.md | 16 ++-- changelog.d/1360-alpr-model-specs.md | 4 +- docs/CURRENT-STATE.md | 8 +- src/data/alprCameras.test.mjs | 3 +- src/layers/alpr/index.js | 4 +- src/layers/alpr/modelSpecs.js | 68 ++++++---------- src/layers/alpr/modelSpecs.test.mjs | 115 ++++++++++++++++++--------- src/layers/alpr/presentation.js | 6 ++ src/layers/alpr/records.js | 2 +- src/layers/alpr/visuals.js | 13 +-- src/layers/cctv/modelSpecs.js | 22 +++-- 11 files changed, 147 insertions(+), 114 deletions(-) diff --git a/DATA_SOURCES.md b/DATA_SOURCES.md index 57ffcbe313..d5b4300932 100644 --- a/DATA_SOURCES.md +++ b/DATA_SOURCES.md @@ -425,7 +425,7 @@ The [Bhote Koshi event pack](public/events/bhote-koshi-2026/README.md), under `p | **Yale Bright Star Catalogue** (9,096 stars, sky background) | `sky/` | **Public domain** | ✅ (no restrictions) | "Yale Bright Star Catalogue (Hoffleit & Warren, via CDS)" (courtesy credit) | | **ESO Milky Way panorama** (eso0932a, blurred cube map, sky background) | `sky/` | **CC BY 4.0** | ✅ (attribution; changes stated) | "ESO/S. Brunier" | | **CCTV ground heights** (3,445 cameras) | `cctv_ground_heights/` | Precomputed camera placement heights, aligned to work with Google Photorealistic 3D Tiles (folder README) | — | — | -| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 camera-model records) | `src/layers/cctv/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) | +| **CCTV Camera Database** model-enrichment extract v2.26.0 + v2.29.0 (20 CCTV and 15 ALPR camera-model records) | `src/layers/cctv/modelSpecs.js`, `src/layers/alpr/modelSpecs.js` | **CC0-1.0** (public domain dedication) | ✅ (no restrictions) | "Specs: cctv-database.com" (courtesy — not legally required) | ### ⚠️ TeleGeography is bundled but NonCommercial @@ -452,11 +452,15 @@ obligations; it does not license the application code. Trimmed test-only tile fixtures retain their provenance in `src/data/fixtures/README.md`. A mapped `model` tag that names datasheet hardware adds a spec line to the -selected card. The specs are 16 verbatim CC0-1.0 records from the CCTV Camera -Database model-enrichment extract (v2.29.0), compiled into -`src/layers/alpr/modelSpecs.js`; nothing is fetched at runtime, and an -unrecognised tag is never displayed. The hourly extract does not carry `model` -yet, so only an Overpass-backed source shows these lines today. +selected card. The specs are 16 CC0-1.0 records from the CCTV Camera Database +model-enrichment extract (v2.29.0): 15 compiled into +`src/layers/alpr/modelSpecs.js`, with the bare product codes mappers tag added +as aliases and the SharpV G3 and SharpX XGA titles naming their variant, plus +the CCTV layer's Bosch MIC-7522-Z30 record. Nothing is fetched at runtime, and +an unrecognised tag is never displayed. The default hourly extract does not +carry `model` yet, so the line appears only with a source that supplies it: an +Overpass-backed source or a custom adapter whose records include the optional +`model` field. ### CCTV Camera Database (`src/layers/cctv/modelSpecs.js`) diff --git a/changelog.d/1360-alpr-model-specs.md b/changelog.d/1360-alpr-model-specs.md index 90addb2adb..a7db9817c5 100644 --- a/changelog.d/1360-alpr-model-specs.md +++ b/changelog.d/1360-alpr-model-specs.md @@ -1,5 +1,7 @@ - Mapped ALPR cameras whose OpenStreetMap `model` tag names known hardware (Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada, Bosch MIC) show a datasheet spec line on their card, from 16 vendored CCTV Camera Database - records; unknown, generation-ambiguous or mis-attributed models show nothing + records, when their source supplies `model` (an Overpass-backed source or an + integration adapter; the default hourly extract does not yet); unknown, + generation-ambiguous or mis-attributed models show nothing (bassem chagra, @ch-bas, #1360). diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 7772983cee..3402746489 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1508,9 +1508,11 @@ Genetec AutoVu, Axis, Verkada, Bosch MIC; 408 of the 1,567 tagged cameras in October 2026) gets a `SPEC` line on its card from vendored datasheet records (`src/layers/alpr/modelSpecs.js`, matched with the CCTV layer's `createModelSpecLookup`). A `manufacturer` naming another maker rejects the -match, and the raw tag text is never shown. Unversioned `AutoVu SharpV` tags -cannot choose between G1/G2/G3 datasheets and show no specs. The hourly extract -has no `model` field yet, so only an Overpass-backed source fills it. +match, and the raw tag text is never shown. +Unversioned `AutoVu SharpV` and `AutoVu SharpX` tags show no specs; G1/G2 +tags show the G2 (1280x960) record and G3 tags the G3 record. The default +hourly extract has no `model` field yet; an Overpass-backed source or a custom +adapter record's optional `model` fills it. The shared overlay paints gradients for at most 64 nearby cameras, promoting the selected camera; farther cameras keep native Cesium badges without wedges. Native ground-clamped wedges (a ground polyline plus a classification polygon per diff --git a/src/data/alprCameras.test.mjs b/src/data/alprCameras.test.mjs index bee648a443..05ed7d06ec 100644 --- a/src/data/alprCameras.test.mjs +++ b/src/data/alprCameras.test.mjs @@ -43,6 +43,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { 'surveillance:type': 'ALPR', operator: 'Flock Safety', 'camera:type': 'fixed', + model: ' L6Q ', 'surveillance:zone': 'traffic', 'camera:direction': '270', ref: 'ATX-001', @@ -56,7 +57,7 @@ test('normalizeAlprNode: maps a full OSM node to a plain record', () => { longitude: -97.7431, operator: 'Flock Safety', manufacturer: null, - model: null, + model: 'L6Q', cameraType: 'fixed', zone: 'traffic', directionDeg: 270, diff --git a/src/layers/alpr/index.js b/src/layers/alpr/index.js index 474ec1de03..cbd3cda3fb 100644 --- a/src/layers/alpr/index.js +++ b/src/layers/alpr/index.js @@ -23,7 +23,9 @@ import { t, tn, msg } from '../../i18n/index.js'; * records fully cover, reused for later views inside it) and `zoom` (their * tile precision; `source.detailZoom(box)` names the zoom a view needs). Records use stable string ids and latitude / * longitude in degrees; optional directionDeg is a compass bearing [0, 360). - * Manufacturer, operator and cameraType are optional display fields. + * Manufacturer, operator, cameraType and model are optional display fields; + * model only selects a vendored datasheet line (modelSpecs.js), never shown + * as text. * Source label and attribution { name, description, text, href } identify the * actual provider; href must be HTTPS. Provider payload parsing stays in source. * Context services remove obsolete records with diff --git a/src/layers/alpr/modelSpecs.js b/src/layers/alpr/modelSpecs.js index 33314531c1..1e71789f28 100644 --- a/src/layers/alpr/modelSpecs.js +++ b/src/layers/alpr/modelSpecs.js @@ -1,17 +1,9 @@ /** * @module alprModelSpecs * - * Datasheet specs for the ALPR hardware that OpenStreetMap mappers name. - * - * 1,567 mapped ALPR cameras carry a `model` tag (October 2026). This module - * vendors the records for the models among them that the CCTV Camera Database - * (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) covers — - * Motorola Solutions Vigilant, Genetec AutoVu, Axis, Verkada and Bosch MIC, - * which resolve 408 of those cameras (excluding unversioned SharpV tags) — - * and resolves a camera's `model` (with its `manufacturer`) through the CCTV - * layer's matcher. The hourly extract the - * layer reads by default does not publish `model` yet, so today only an - * Overpass-backed source shows these specs. Flock Safety publishes no + * Datasheet specs for the ALPR hardware that OpenStreetMap `model` tags name, + * vendored from the CCTV Camera Database (CC0-1.0) and matched with the CCTV + * layer's rules; DATA_SOURCES.md has the provenance. Flock Safety publishes no * datasheet resolution, so Flock models stay unresolved; an unknown model * never implies anything. * @@ -19,13 +11,15 @@ * night vision) — never endpoints, operators or what a camera records. */ -import { createModelSpecLookup } from '../cctv/modelSpecs.js'; +import { createModelSpecLookup, lookupModelSpec } from '../cctv/modelSpecs.js'; /** - * Verbatim records from the dataset's model-enrichment extract (v2.29.0). - * Mappers tag the bare product code ("L6Q", "MIC-7522-Z30B") where the - * datasheet names the product line too ("Vigilant L6Q"), so each record also - * lists its bare code as an alias. + * Records from the dataset's model-enrichment extract (v2.29.0), with the + * bare product codes mappers tag ("L6Q") added as aliases where the title + * names the product line ("Vigilant L6Q"). A tag without a generation or + * variant could name any of them, so the SharpV G3 and SharpX XGA titles + * carry theirs. Fields the card does not read (type, url, fov_deg, …) stay as + * in the dataset, like the CCTV records. */ const RECORDS = [ { @@ -99,11 +93,10 @@ const RECORDS = [ { id: 'genetec-autovu-sharpv', brand: 'Genetec', - model: 'AutoVu SharpV', + model: 'AutoVu SharpV G3', type: 'box', url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpv/', aliases: [ - 'AutoVu SharpV G3', 'AU-V-WS850-LC-G3-000', 'AU-V-BS850-LC-G3-0M0', 'AU-V-BS850-LC-G3-0M1', @@ -128,7 +121,7 @@ const RECORDS = [ { id: 'genetec-autovu-sharpx', brand: 'Genetec', - model: 'AutoVu SharpX', + model: 'AutoVu SharpX XGA', type: 'box', url: 'https://www.cctv-database.com/camera/genetec-autovu-sharpx/', // i18n-ignore: datasheet label @@ -229,42 +222,29 @@ const RECORDS = [ night_vision: { type: 'ir', range_m: 20 }, environment: ['indoor', 'outdoor'], }, - { - id: 'bosch-mic-7522-z30b', - brand: 'Bosch', - model: 'MIC IP starlight 7100i (MIC-7522-Z30B)', - type: 'ptz', - url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/', - aliases: ['MIC-7522-Z30B'], - fov_deg: '2.1-58.3', - // i18n-ignore: datasheet label - resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' }, - ptz: true, - varifocal: true, - night_vision: { type: 'color' }, - environment: ['outdoor'], - ndaa_compliant: true, - }, + // The CCTV layer's record: one colour-neutral title for the B/G/W variants. + lookupModelSpec('MIC-7522-Z30B', 'Bosch'), ]; +const lookupDatasheetSpec = createModelSpecLookup(RECORDS); + /** * Datasheet record for a mapped ALPR camera's `model` tag. A `manufacturer` * naming another maker rejects the match, so a "Flock Safety" camera tagged * "L6Q" stays unresolved rather than borrowing Motorola's specs. * @param {string|null} model - The OSM `model` tag. * @param {string|null} [manufacturer] - The OSM `manufacturer` tag. - * @returns {Object|null} The verbatim spec record, or null when unknown. + * @returns {Object|null} The spec record, or null when unknown. */ -const lookupDatasheetSpec = createModelSpecLookup(RECORDS); - export function lookupAlprModelSpec(model, manufacturer) { - const spec = lookupDatasheetSpec(model, manufacturer); - // The dataset's unversioned SharpV label is tied to G3 hardware, but OSM - // tags may name G1 or G2. Require an explicit G3 or a G3 part number. + // Adapter records arrive unnormalized and the matcher's word trim is + // quadratic on long punctuation runs: match only tag-sized strings (the + // built-in sources keep 180 characters). + if (typeof model !== 'string' || model.length > 180) return null; if ( - spec?.id === 'genetec-autovu-sharpv' && - !/\bg3\b/i.test(String(model || '')) + manufacturer != null && + (typeof manufacturer !== 'string' || manufacturer.length > 180) ) return null; - return spec; + return lookupDatasheetSpec(model, manufacturer); } diff --git a/src/layers/alpr/modelSpecs.test.mjs b/src/layers/alpr/modelSpecs.test.mjs index fb6d8fbd49..dd2c8c20c6 100644 --- a/src/layers/alpr/modelSpecs.test.mjs +++ b/src/layers/alpr/modelSpecs.test.mjs @@ -2,9 +2,10 @@ // Mapped ALPR model tags resolve to vendored datasheets, and never guess. import { test } from 'node:test'; import assert from 'node:assert/strict'; +import { PbfWriter } from 'pbf'; import { lookupAlprModelSpec } from './modelSpecs.js'; -import { normalizeAlprNode } from './records.js'; +import { decodeAlprTile } from './tileRecords.js'; import { alprLabelDetails } from './visuals.js'; const OSM = { attribution: { name: 'OpenStreetMap' } }; @@ -20,6 +21,7 @@ test('the model tags mappers write resolve to their datasheet record', () => { ['AU-V-WS850-LC-G3-000', 'Genetec', 'genetec-autovu-sharpv'], ['AutoVu SharpV G2', 'Genetec', 'genetec-autovu-sharpv-g2'], ['AutoVu SharpV G1', 'Genetec', 'genetec-autovu-sharpv-g2'], + ['AutoVu SharpX XGA', 'Genetec', 'genetec-autovu-sharpx'], ['Q1700-LE', 'Axis Communications', 'axis-q1700-le'], ['Q1800-LE', 'Axis Communications', 'axis-q1800-le'], ['CP63-E', 'Verkada Inc.', 'verkada-cp63-e'], @@ -45,37 +47,61 @@ test('unknown, mis-attributed or partial models stay unresolved', () => { ['Q1800', 'Axis Communications'], // Without a maker, a code-less product name is never trusted. ['AutoVu SharpV', null], + // A SharpV without its generation could be G1, G2 or G3, and a SharpX + // without XGA could be the VGA model. ['AutoVu SharpV', 'Genetec'], ['AutoVu SharpV HD', 'Genetec'], ['Genetec AutoVu SharpV', 'Genetec'], + ['AutoVu SharpX', 'Genetec'], ['UnicamVELOCITY3', null], [null, 'Motorola Solutions'], + // Adapter text is matched only as a string of tag size. + [['L6Q'], 'Motorola Solutions'], + ['L6Q' + ' IP'.repeat(60), 'Motorola Solutions'], ]) assert.equal(lookupAlprModelSpec(model, manufacturer), null); }); -test('Overpass records carry the trimmed OSM model tag', () => { - const node = normalizeAlprNode({ - type: 'node', - id: 7, - lat: 30, - lon: -97, - tags: { - 'surveillance:type': 'ALPR', - manufacturer: 'Motorola Solutions', - model: ' L6Q ', - }, +/** A one-point `cameras` vector tile (z0) with string attributes. */ +function cameraTile(properties) { + const tile = new PbfWriter(); + tile.writeMessage(3, (_, layer) => { + layer.writeVarintField(15, 2); + layer.writeStringField(1, 'cameras'); + layer.writeVarintField(5, 4096); + const keys = Object.keys(properties); + layer.writeMessage(2, (_, feature) => { + feature.writePackedVarint( + 2, + keys.flatMap((_, i) => [i, i]), + ); + feature.writeVarintField(3, 1); // Point + feature.writePackedVarint(4, [9, 4096, 4096]); // MoveTo(2048, 2048) + }); + for (const key of keys) layer.writeStringField(3, key); + for (const key of keys) + layer.writeMessage(4, (_, value) => + value.writeStringField(1, String(properties[key])), + ); }); - assert.equal(node.model, 'L6Q'); - assert.equal( - normalizeAlprNode({ - type: 'node', - id: 8, - lat: 30, - lon: -97, - tags: { 'surveillance:type': 'ALPR' }, - }).model, - null, + return tile.finish(); +} + +test('extract tiles carry the model tag to the card', () => { + const [record] = decodeAlprTile( + cameraTile({ + osmType: 'node', + osmId: '7', + brand: 'Motorola Solutions', + model: 'L6Q', + }), + 0, + 0, + 0, + ); + assert.equal(record.model, 'L6Q'); + assert.ok( + alprLabelDetails(record, OSM).includes('SPEC VIGILANT L6Q · 1080P · IR'), ); }); @@ -87,15 +113,40 @@ test('the card adds the datasheet line only for a resolved model', () => { assert.deepEqual(details, [ 'OSM MAPPED', 'MOTOROLA SOLUTIONS', - 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + 'SPEC VIGILANT L6Q · 1080P · IR', 'PUBLIC MAP DATA', ]); - // A record without a resolution label falls back to its pixel size. + // Without a maker on the equipment line, the spec line names it. + assert.ok( + alprLabelDetails({ model: 'L6Q' }, OSM).includes( + 'SPEC MOTOROLA SOLUTIONS VIGILANT L6Q · 1080P · IR', + ), + ); + // A record without a resolution label falls back to its pixel size, then + // to megapixels. assert.ok( alprLabelDetails( { manufacturer: 'Motorola Solutions', model: 'L5F' }, OSM, - ).includes('SPEC MOTOROLA SOLUTIONS VIGILANT L5F · 1440X1080 · IR'), + ).includes('SPEC VIGILANT L5F · 1440X1080 · IR'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'Motorola Solutions', model: 'L5Q' }, + OSM, + ).includes('SPEC VIGILANT L5Q · 3MP'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, + OSM, + ).includes('SPEC AUTOVU SHARPV G3 · 1920X1200 · IR'), + ); + assert.ok( + alprLabelDetails( + { manufacturer: 'The Bosch Group', model: 'MIC-7522-Z30B' }, + OSM, + ).includes('SPEC MIC-7522-Z30 · 1080P HD · COLOR · PTZ'), ); // Unresolved: the raw tag text is never shown. const unknown = alprLabelDetails( @@ -104,17 +155,3 @@ test('the card adds the datasheet line only for a resolved model', () => { ); assert.ok(unknown.every((line) => !/FALCON|SYSTEM|SPEC/.test(line))); }); - -test('unversioned SharpV does not display G3 specs on an ALPR card', () => { - const ambiguous = alprLabelDetails( - { manufacturer: 'Genetec', model: 'AutoVu SharpV' }, - OSM, - ); - assert.deepEqual(ambiguous, ['OSM MAPPED', 'GENETEC', 'PUBLIC MAP DATA']); - - const g3 = alprLabelDetails( - { manufacturer: 'Genetec', model: 'AutoVu SharpV G3' }, - OSM, - ); - assert.ok(g3.includes('SPEC GENETEC AUTOVU SHARPV · 1920X1200 · IR')); -}); diff --git a/src/layers/alpr/presentation.js b/src/layers/alpr/presentation.js index c7343d5738..9d378160d9 100644 --- a/src/layers/alpr/presentation.js +++ b/src/layers/alpr/presentation.js @@ -16,6 +16,8 @@ import { boxContains } from './model.js'; import { msg } from '../../i18n/index.js'; import { createAlprFloorResolver } from './floors.js'; import { createAlprOverlay } from './overlay.js'; +import { lookupAlprModelSpec } from './modelSpecs.js'; +import { specSummary } from '../cctv/modelSpecs.js'; import { MARKER_IMAGE, SELECTED_IMAGE, @@ -458,6 +460,10 @@ export function createAlprPresentation({ state, services, source }) { properties: { operator: record.operator, manufacturer: record.manufacturer, + spec: + specSummary( + lookupAlprModelSpec(record.model, record.manufacturer), + ) || null, cameraType: record.cameraType, zone: record.zone, directionDeg: record.directionDeg, diff --git a/src/layers/alpr/records.js b/src/layers/alpr/records.js index 391884536e..c85ca35785 100644 --- a/src/layers/alpr/records.js +++ b/src/layers/alpr/records.js @@ -89,7 +89,7 @@ export function normalizeAlprNode(el) { latitude: el.lat, longitude: el.lon, operator: textTag(tags.operator), - manufacturer: textTag(tags.manufacturer), + manufacturer: textTag(tags.manufacturer) ?? textTag(tags.brand), // Display-only: resolved against vendored datasheets (see modelSpecs.js). model: textTag(tags.model), cameraType: textTag(tags['camera:type']), diff --git a/src/layers/alpr/visuals.js b/src/layers/alpr/visuals.js index 748fcf1074..f9dab5b4ab 100644 --- a/src/layers/alpr/visuals.js +++ b/src/layers/alpr/visuals.js @@ -45,10 +45,7 @@ export function alprDisplayId(record) { return `ALPR-${String(record.osmId).slice(-4).padStart(4, '0')}`; } -/** - * Show only supplied metadata, with the actual source named for custom - * adapters, plus the datasheet summary when the mapped model is known. - */ +/** Show only supplied metadata, with the actual source named for custom adapters. */ export function alprLabelDetails(record, source) { const sourceName = source.attribution?.name || source.label || 'Camera source'; @@ -71,7 +68,13 @@ export function alprLabelDetails(record, source) { if (equipment.length) details.push(equipment.join(' · ')); // Only a datasheet match is shown: the raw OSM `model` text never is. const spec = lookupAlprModelSpec(record.model, record.manufacturer); - if (spec) details.push(`SPEC ${specSummary(spec).toUpperCase()}`); + if (spec) { + // The equipment line usually names the maker already; the card does not wrap. + const withBrand = !equipment.some((line) => + line.includes(spec.brand.toUpperCase()), + ); + details.push(`SPEC ${specSummary(spec, { withBrand }).toUpperCase()}`); + } if (sourceName === 'OpenStreetMap') details.push('PUBLIC MAP DATA'); return details; } diff --git a/src/layers/cctv/modelSpecs.js b/src/layers/cctv/modelSpecs.js index be0e316c1c..4be78de085 100644 --- a/src/layers/cctv/modelSpecs.js +++ b/src/layers/cctv/modelSpecs.js @@ -456,15 +456,8 @@ const BRAND_ALIASES = { Hikvision: ['hiwatch'], }; -/** - * Builds a model lookup over a record table, so another layer can resolve its - * own vendored records with the same matching rules (see lookupModelSpec). - * @param {Object[]} records - Spec records in this module's shape. - * @param {Object} [brandAliases] - Extra manufacturer words - * accepted per record brand. - * @returns {(model: string, manufacturer?: string) => (Object|null)} Lookup. - */ -export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { +/** A model lookup over `records` with this module's matching rules (see lookupModelSpec). */ +export function createModelSpecLookup(records) { /** * One entry per record name (model + aliases). `required` is every * non-generic word of the name — all must appear in a query, so a @@ -476,7 +469,7 @@ export function createModelSpecLookup(records, brandAliases = BRAND_ALIASES) { const nameIndex = records.flatMap((record) => { const brand = new Set([ ...words(record.brand), - ...(brandAliases[record.brand] || []), + ...(BRAND_ALIASES[record.brand] || []), ]); return [record.model, ...(record.aliases || [])].map((name) => { const nameWords = words(name); @@ -610,12 +603,15 @@ export function specFovCapabilityToken( /** * One-line spec summary for HUD meta text. - * @param {Object} spec - A record from this module. + * @param {Object} spec - A spec record (CCTV or ALPR). Resolution falls back + * from label to WxH to NMP. + * @param {{withBrand?: boolean}} [options] - `withBrand: false` leaves the + * brand out. * @returns {string} e.g. 'Axis Q6135-LE · 1080p · IR 250m · PTZ' ('' for null). */ -export function specSummary(spec) { +export function specSummary(spec, { withBrand = true } = {}) { if (!spec) return ''; - const parts = [`${spec.brand} ${spec.model}`]; + const parts = [withBrand ? `${spec.brand} ${spec.model}` : spec.model]; const { label, w, h, mp } = spec.resolution || {}; if (label) parts.push(label); else if (w && h) parts.push(`${w}x${h}`); From 8b122dc25927dcb3ca62098f7ea37caa3d846fc0 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Thu, 19 Nov 2026 19:18:31 +0000 Subject: [PATCH 14/56] fix(render): wheel zoom no longer stalls with an icon under the canvas centre Below 150 km Cesium sizes a zoom step from the depth it picks at the canvas centre. Since #1835 an icon drawn over depth wrote a depth just past the near plane, which that pick took for a surface a near plane's distance from the camera: zooming in returned early and zooming out moved by centimetres. Over-depth rows now write a depth of exactly 0 in the fragment shader. It is never discarded (the flicker #1835 fixed stays fixed) and the depth pick reads it as nothing drawn, keeping the ground under the icon. Adds scripts/qa-zoom-under-icon.mjs (real browser) and a source-level unit test. --- docs/CURRENT-STATE.md | 10 + scripts/format-scope.json | 1 + scripts/qa-zoom-under-icon.mjs | 214 ++++++++++++++++++++ src/render/cesium/iconSetPrimitive.js | 25 ++- src/render/cesium/iconSetPrimitive.test.mjs | 27 +++ 5 files changed, 268 insertions(+), 9 deletions(-) create mode 100644 scripts/qa-zoom-under-icon.mjs diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 51dd971fe0..3f28e60806 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -93,6 +93,16 @@ settling. Oblique views below 300 km are left alone. `QA_BASE_URL=http://localhost:4173 node scripts/qa-zoom-out-guard.mjs` exercises the real browser controller at desktop and phone widths with keyless fixtures. +Below 150 km Cesium sizes a wheel or pinch zoom step from the depth it picks at +the canvas centre. Icons drawn over depth (aircraft, vessels and most markers: +`disableDepthTest: Infinity`) sit on the near plane and write a depth of +exactly 0 there (`src/render/cesium/iconSetPrimitive.js`), which that pick +reads as nothing drawn, so it keeps the ground under the icon. Any depth past +the near plane would be taken for a surface a near plane's distance from the +camera, and the zoom would stop while an icon is under the centre. +`QA_BASE_URL=http://localhost:5173 node scripts/qa-zoom-under-icon.mjs` checks +this against a dev server (`npm run dev`). + Cesium's free look (Shift+drag, which turns the camera in place) works only below 1,000 km. Above that height a few drags could turn the whole planet out of frame and leave only stars, so Shift+drag does nothing there. Cesium also turns diff --git a/scripts/format-scope.json b/scripts/format-scope.json index 9cbc1bda9a..d5b0aea10f 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1290,6 +1290,7 @@ "src/render/cesium/zoomOutGuard.test.mjs", "src/app/controls.test.mjs", "scripts/qa-zoom-out-guard.mjs", + "scripts/qa-zoom-under-icon.mjs", "src/hudSummaryGate.test.mjs", "src/hudSummaryLine.test.mjs", "src/testSupport/stubMgrs.mjs", diff --git a/scripts/qa-zoom-under-icon.mjs b/scripts/qa-zoom-under-icon.mjs new file mode 100644 index 0000000000..2ae7f5366b --- /dev/null +++ b/scripts/qa-zoom-under-icon.mjs @@ -0,0 +1,214 @@ +#!/usr/bin/env node +/** + * Real-app regression: the wheel zooms with an over-depth icon under the + * centre of the canvas. Start a dev server (`npm run dev`), then run this + * file with QA_BASE_URL set to it. + * + * Below 150 km Cesium sizes a zoom step from the depth it picks at the canvas + * centre. An icon drawn over depth must leave nothing there for that pick, or + * the camera takes the icon (a metre away, on the near plane) for the ground + * and stops zooming. + */ +import assert from 'node:assert/strict'; +import puppeteer from 'puppeteer'; + +const origin = process.env.QA_BASE_URL || 'http://localhost:4173'; +const CAMERA_HEIGHT_M = 15_000; +const browser = await puppeteer.launch({ + headless: true, + args: [ + '--no-sandbox', + ...(process.platform === 'darwin' + ? ['--use-angle=metal', '--enable-gpu'] + : [ + '--use-gl=angle', + '--use-angle=swiftshader', + '--enable-unsafe-swiftshader', + ]), + ], + protocolTimeout: 120_000, +}); +const errors = []; +try { + const page = await browser.newPage(); + page.on('pageerror', (error) => errors.push(error.message)); + const viewport = { width: 1200, height: 800 }; + await page.setViewport(viewport); + await page.goto(`${origin}/?welcome=0`, { waitUntil: 'domcontentloaded' }); + await page.waitForFunction( + () => + window.__godsEyeView?.viewer && + window.__godsEyeView.viewer.scene.screenSpaceCameraController + .enableInputs && + document.getElementById('loading-screen')?.classList.contains('hidden'), + { timeout: 90_000 }, + ); + const setup = await page.evaluate(async (cameraHeight) => { + const C = await import('/node_modules/cesium/Build/Cesium/index.js'); + const { drawOf } = await import('/src/render/rendererOf.js'); + const viewer = window.__godsEyeView.viewer; + const scene = viewer.scene; + viewer.camera.cancelFlight(); + viewer.trackedEntity = undefined; + // Explicit real renders make each gesture independent of host frame rate. + viewer.useDefaultRenderLoop = false; + const controller = scene.screenSpaceCameraController; + controller.inertiaZoom = 0; + controller.inertiaSpin = 0; + const lon = -30; + const lat = 40; // open Atlantic: nothing else of the app's draws here + const icons = drawOf(viewer).icons({ id: 'qa-zoom-under-icon' }); + const item = { + id: 'qa-icon', + pos: C.Cartesian3.fromDegrees(lon, lat, 100), + // Held in place on the GPU, as a live aircraft or vessel icon is. + motion: { kind: 'hold', courseDeg: 0 }, + image: `data:image/svg+xml;charset=utf-8,${encodeURIComponent( + '', + )}`, + size: [64, 64], + disableDepthTest: Infinity, + }; + const centre = () => + new C.Cartesian2( + scene.canvas.clientWidth / 2, + scene.canvas.clientHeight / 2, + ); + const frame = () => { + scene.requestRender(); + viewer.render(); + }; + const qa = { + height: () => viewer.camera.positionCartographic.height, + setIcon(shown) { + icons.set(shown ? [item] : []); + }, + reset() { + viewer.camera.cancelFlight(); + viewer.camera.lookAtTransform(C.Matrix4.IDENTITY); + viewer.camera.setView({ + destination: C.Cartesian3.fromDegrees(lon, lat, cameraHeight), + orientation: { heading: 0, pitch: -C.Math.PI_OVER_TWO, roll: 0 }, + }); + frame(); + }, + async frames(count) { + for (let i = 0; i < count; i++) { + frame(); + await new Promise((resolve) => setTimeout(resolve, 0)); + } + return qa.height(); + }, + /** Whether the icon is what a click at the canvas centre picks. */ + iconAtCentre() { + const picked = scene.pick(centre()); + return JSON.stringify(picked?.id ?? null).includes('qa-icon'); + }, + /** Metres from the camera to what the depth pick finds at the centre. */ + centreDepthM() { + frame(); + const point = scene.pickPositionWorldCoordinates(centre()); + return point + ? C.Cartesian3.distance(point, viewer.camera.positionWC) + : null; + }, + }; + window.__zoomUnderIconQa = qa; + const gl = scene.context._gl; + const debug = gl.getExtension('WEBGL_debug_renderer_info'); + return { + renderer: gl.getParameter( + debug ? debug.UNMASKED_RENDERER_WEBGL : gl.RENDERER, + ), + logDepth: scene.logarithmicDepthBuffer, + pickPosition: scene.pickPositionSupported, + }; + }, CAMERA_HEIGHT_M); + console.log( + `[INFO] WebGL renderer: ${setup.renderer}; log depth ${setup.logDepth}`, + ); + assert.ok(setup.pickPosition, 'the context must support depth picks'); + + const qa = (method, ...args) => + page.evaluate( + (name, rest) => window.__zoomUnderIconQa[name](...rest), + method, + args, + ); + const x = viewport.width / 2; + const y = viewport.height / 2; + await page.mouse.move(x, y); + /** Wheel `deltaY` at the canvas centre, then the settled camera height. */ + const wheel = async (deltaY) => { + await qa('reset'); + await page.evaluate( + ({ x, y, deltaY }) => { + window.__godsEyeView.viewer.canvas.dispatchEvent( + new WheelEvent('wheel', { + deltaY, + clientX: x, + clientY: y, + bubbles: true, + cancelable: true, + }), + ); + }, + { x, y, deltaY }, + ); + return qa('frames', 40); + }; + + // The ground alone: what the icon must not change. + await qa('setIcon', false); + await qa('reset'); + await qa('frames', 10); + const groundDepth = await qa('centreDepthM'); + const groundIn = await wheel(-600); + const groundOut = await wheel(600); + console.log( + `[INFO] no icon: centre depth ${groundDepth?.toFixed(1)} m, wheel in to ${groundIn.toFixed(0)} m, out to ${groundOut.toFixed(0)} m`, + ); + assert.ok(groundIn < CAMERA_HEIGHT_M * 0.95, 'control: wheel in zooms in'); + assert.ok(groundOut > CAMERA_HEIGHT_M * 1.05, 'control: wheel out zooms out'); + + await qa('setIcon', true); + await qa('reset'); + await page.waitForFunction( + async () => { + await window.__zoomUnderIconQa.frames(1); + return window.__zoomUnderIconQa.iconAtCentre(); + }, + { timeout: 30_000 }, + ); + console.log('[PASS] the icon draws under the canvas centre'); + + const depth = await qa('centreDepthM'); + const zoomedIn = await wheel(-600); + const zoomedOut = await wheel(600); + console.log( + `[INFO] icon at centre: depth pick ${depth === null ? 'finds nothing' : `${depth.toFixed(3)} m away`}, wheel in to ${zoomedIn.toFixed(0)} m, out to ${zoomedOut.toFixed(0)} m`, + ); + assert.ok( + depth === null || depth > 100, + `the depth pick must not land on the icon (${depth} m from the camera)`, + ); + console.log('[PASS] the depth pick at the centre ignores the icon'); + assert.ok( + zoomedIn < CAMERA_HEIGHT_M * 0.95, + `wheel in must zoom in under an icon (height ${zoomedIn.toFixed(1)} m)`, + ); + console.log('[PASS] wheel in zooms in'); + assert.ok( + zoomedOut > CAMERA_HEIGHT_M * 1.05, + `wheel out must zoom out under an icon (height ${zoomedOut.toFixed(1)} m)`, + ); + console.log('[PASS] wheel out zooms out'); + + assert.ok(await qa('iconAtCentre'), 'the icon must still pick by click'); + console.log('[PASS] the icon still picks by click'); + + assert.deepEqual(errors, [], 'no JavaScript page errors'); + console.log('[PASS] no JavaScript page errors'); +} finally { + await browser.close(); +} diff --git a/src/render/cesium/iconSetPrimitive.js b/src/render/cesium/iconSetPrimitive.js index 432f78ffd1..581fb95f46 100644 --- a/src/render/cesium/iconSetPrimitive.js +++ b/src/render/cesium/iconSetPrimitive.js @@ -92,6 +92,7 @@ out vec2 v_uv; out vec4 v_color; out vec4 v_pickColor; out float v_proxy; +out float v_overDepth; // 1 for a row drawn over depth, on the near plane // The row's anchor in clip space before screen offsets, for effects that wrap // main() (sonar) and must not change geometry or picks. @@ -125,6 +126,7 @@ void main() { v_uv = vec2(0.0); v_color = vec4(0.0); v_proxy = 0.0; + v_overDepth = 0.0; gl_Position = vec4(0.0, 0.0, 2.0, 1.0); // outside the clip volume: not drawn float flags = style1.z; @@ -260,14 +262,9 @@ void main() { distanceSq < style3.w * style3.w; if (overDepth && zclip >= -1.0 && zclip <= 1.0) { gl_Position.z = -gl_Position.w; -#ifdef LOG_DEPTH - // Just past the near plane, not on it: czm_writeLogDepth discards a - // fragment at or below 0.9999999, and 1.0 interpolated across the quad - // can arrive a rounding step or two under that, dropping the icon for a - // frame as it moves (flicker). 1e-4 m past the near plane is still in - // front of everything the scene draws. - v_depthFromNearPlusOne = 1.0001; -#endif + // With a log depth buffer the fragment shader writes the near plane's + // depth itself. + v_overDepth = 1.0; } v_uv = mix(rect.xy, rect.zw, vec2(corner.x * 0.5 + 0.5, 0.5 - corner.y * 0.5)); @@ -282,6 +279,7 @@ in vec2 v_uv; in vec4 v_color; in vec4 v_pickColor; in float v_proxy; +in float v_overDepth; void main() { vec4 color = czm_gammaCorrect(texture(u_atlas, v_uv)); @@ -296,7 +294,16 @@ void main() { #endif out_FragColor = color; #ifdef LOG_DEPTH - czm_writeLogDepth(v_depthFromNearPlusOne); + // Over depth: exactly the near plane's depth, written here and not through + // czm_writeLogDepth. That function discards a fragment whose interpolated + // depth arrives a rounding step under the near plane (the icon drops for a + // frame as it moves), and any depth past the near plane is a surface to + // Cesium's depth pick: the camera controller then sizes a zoom step from an + // icon under the canvas centre, a near plane's distance away, and the wheel + // stops zooming. The pick reads a depth of 0 as nothing drawn, and keeps + // the depth of the ground under the icon. + if (v_overDepth > 0.5) gl_FragDepth = 0.0; + else czm_writeLogDepth(v_depthFromNearPlusOne); #endif } `; diff --git a/src/render/cesium/iconSetPrimitive.test.mjs b/src/render/cesium/iconSetPrimitive.test.mjs index 511acf676e..562a125a61 100644 --- a/src/render/cesium/iconSetPrimitive.test.mjs +++ b/src/render/cesium/iconSetPrimitive.test.mjs @@ -1,5 +1,6 @@ import assert from 'node:assert/strict'; import test from 'node:test'; +import fs from 'node:fs'; import * as Cesium from 'cesium'; import { createIconSet } from '../../data/iconSet.js'; import { IconSetPrimitive } from './iconSetPrimitive.js'; @@ -58,3 +59,29 @@ test('by default the set draws an opaque pass and a translucent one, and draws n assert.equal(translucent.renderState.depthMask, false); assert.equal(primitive.drawsBlend('translucent'), false); }); + +test('an over-depth row writes a depth of exactly 0, which a depth pick ignores', () => { + // Shaders do not compile under node: this reads the fragment shader's + // source. A depth past the near plane (as 1.0001 through + // czm_writeLogDepth was) is a surface to Cesium's depth pick, a near + // plane's distance from the camera, and the wheel stops zooming with an + // icon under the canvas centre (scripts/qa-zoom-under-icon.mjs). + const source = fs.readFileSync( + new URL('./iconSetPrimitive.js', import.meta.url), + 'utf8', + ); + const [vertex, fragment] = source + .slice(source.indexOf('const VERTEX_SHADER')) + .split('const FRAGMENT_SHADER') + .map((shader) => shader.replace(/\/\/.*$/gm, '')); // comments out + assert.match( + fragment, + /if \(v_overDepth > 0\.5\) gl_FragDepth = 0\.0;\s+else czm_writeLogDepth\(v_depthFromNearPlusOne\);/, + ); + // The vertex shader flags the row and leaves its log depth alone. + assert.match( + vertex, + /gl_Position\.z = -gl_Position\.w;[^}]*v_overDepth = 1\.0;/, + ); + assert.doesNotMatch(vertex, /v_depthFromNearPlusOne\s*=/); +}); From 0fd9a7ed573445d905ed917710a33332e7934199 Mon Sep 17 00:00:00 2001 From: Said Turksever Date: Thu, 19 Nov 2026 19:19:03 +0000 Subject: [PATCH 15/56] docs(changelog): zoom freeze under icons (#1857) --- changelog.d/1857-zoom-freeze-under-icons.md | 3 +++ 1 file changed, 3 insertions(+) create mode 100644 changelog.d/1857-zoom-freeze-under-icons.md diff --git a/changelog.d/1857-zoom-freeze-under-icons.md b/changelog.d/1857-zoom-freeze-under-icons.md new file mode 100644 index 0000000000..6816fdfa88 --- /dev/null +++ b/changelog.d/1857-zoom-freeze-under-icons.md @@ -0,0 +1,3 @@ +- Wheel and trackpad zoom no longer freeze below 150 km while an aircraft or + vessel icon is under the centre of the view: icons drawn over depth write a + depth of exactly 0, which the camera's depth pick ignores (asturksever, #1857). From 8359a23e9d3e4c47078218f7458ff83d1f7b30d0 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Thu, 19 Nov 2026 12:19:06 -0800 Subject: [PATCH 16/56] Vue kit: the chat panel's and voice control's buttons and glyphs are kit controls Every hand-written button in the AI chat panel (Settings, the quick prompts, an attachment's remove, Attach layer, Attach a file, Expand conversation, the command suggestions, Expand chat, Add attachment and Send / Stop reply) and in the voice control (Open AI chat, Back to chat, Back to voice, the Preview and Settings tabs and the error tray's DISMISS) is a ghost UiButton keeping its id, classes, aria and data attributes, title and listeners. The Settings and tab Material glyphs are UiIcons with :size="null", so voice-cost.css and voice-card.css still size them. The tabs keep role="tab" and aria-selected; DISMISS is a text button, so it stays a UiButton rather than a UiCloseButton. The inline SVG glyphs, the message box, the file picker and the minutes field stay as they are. src/ui/kit/chatVoiceControls.test.mjs pins it: no hand-written button or Material span in the chat, voice, voice card, panel layout and visualizer templates, kit counts per file, the pressed toggles through :pressed, the icons' :size="null", the native fields left, and no button built in script by the voice modules. docs/VUE-MIGRATION.md describes the surface. Co-authored-by: Manjunath Paparaju --- docs/VUE-MIGRATION.md | 17 +++ scripts/format-scope.json | 1 + src/ui/kit/chatVoiceControls.test.mjs | 150 ++++++++++++++++++++++++++ src/ui/views/panels/ChatPanel.vue | 22 ++-- src/ui/views/panels/VoiceControl.vue | 13 +-- 5 files changed, 187 insertions(+), 16 deletions(-) create mode 100644 src/ui/kit/chatVoiceControls.test.mjs diff --git a/docs/VUE-MIGRATION.md b/docs/VUE-MIGRATION.md index d82f798808..9a54cd9452 100644 --- a/docs/VUE-MIGRATION.md +++ b/docs/VUE-MIGRATION.md @@ -158,6 +158,23 @@ while a query is typed. The Filter button opens a disclosure and carries a `UiIcon` with `:size="null"`, so `layer-finder.css` still sizes them (`src/ui/kit/layerFinderControls.test.mjs` pins it); the search field's magnifier is `UiSearchField`'s own span. +The AI chat panel's and the voice control's buttons are ghost +`UiButton`s: the chat's Settings, quick prompts, attachment removes, +Attach layer, Attach a file, Expand conversation, command suggestions, +Expand chat, Add attachment and Send (a submit button that turns into +Stop reply), and the voice control's Open AI chat, Back to chat, Back to +voice, its Preview and Settings tabs and the error tray's DISMISS, beside +the tier button, the mic and the dock and minimize buttons, which already +were. The tier button and dock are pressed toggles; the mic is one only +while its owner has a state for it; the tabs keep `role="tab"` and +`aria-selected`. DISMISS is a text button, not a cross, so it is not a +`UiCloseButton`. The Settings and tab glyphs are `UiIcon`s with +`:size="null"`, so voice-cost.css and voice-card.css still size them +(`src/ui/kit/chatVoiceControls.test.mjs` pins it). The chat bubble, +globe, attach, send and stop, expand and Back glyphs stay inline SVG, +since no Material symbol the page loads draws them the same, and the +message box, file picker and inactivity minutes stay native fields, which +the kit has none of. The voice modules build no controls in script. `UiSelect` renders the bare native select (Core's labels sit outside it or come as an `aria-label`) with `v-model`, `options` and `disabled`; options that carry their own attributes come through the slot, a caller's diff --git a/scripts/format-scope.json b/scripts/format-scope.json index ebfa59916f..4f918bae17 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -1350,6 +1350,7 @@ "src/ui/kit/welcomeControls.test.mjs", "src/ui/kit/omnibarControls.test.mjs", "src/ui/kit/storiesControls.test.mjs", + "src/ui/kit/chatVoiceControls.test.mjs", "src/ui/styles/chip.css", "src/ui/styles/empty-state.css", "src/ui/rail/RailChips.vue", diff --git a/src/ui/kit/chatVoiceControls.test.mjs b/src/ui/kit/chatVoiceControls.test.mjs new file mode 100644 index 0000000000..b1716157ca --- /dev/null +++ b/src/ui/kit/chatVoiceControls.test.mjs @@ -0,0 +1,150 @@ +// The AI chat panel's and the voice control's buttons and Material glyphs +// are the kit's: neither their templates nor the voice card and panel +// layout buttons they render hand-write a + @@ -76,7 +78,7 @@ const quickPrompts = () => [t('Fly to Tokyo'), t('Show live flights')];

{{ t('Explore with a question') }}

{{ t('Find a place, explore live data, or change your view.') }}

- + {{ prompt }}
{{ message.role === 'user' ? t('YOU') : ASSISTANT_NAME }}{{ message.text }} @@ -86,7 +88,7 @@ const quickPrompts = () => [t('Fly to Tokyo'), t('Show live flights')];

{{ props.view.chat.authNote }}

- + {{ item.name }} ×
@@ -95,27 +97,27 @@ const quickPrompts = () => [t('Fly to Tokyo'), t('Show live flights')]; - + {{ t('Attach layer') }}
- + {{ t('Attach a file') }}

{{ t('TXT, Markdown, CSV, JSON or GeoJSON · up to 10 KB in total. Attachments are sent to your AI provider with your message.') }}

{{ group.label }} - + {{ command }}
- - + + - +
diff --git a/src/ui/views/panels/VoiceControl.vue b/src/ui/views/panels/VoiceControl.vue index bcbce56b87..ba7c04907f 100644 --- a/src/ui/views/panels/VoiceControl.vue +++ b/src/ui/views/panels/VoiceControl.vue @@ -11,6 +11,7 @@ import PanelLayoutButtons from './PanelLayoutButtons.vue'; import UiButton from '../../kit/UiButton.vue'; import UiCheckbox from '../../kit/UiCheckbox.vue'; import UiCloseButton from '../../kit/UiCloseButton.vue'; +import UiIcon from '../../kit/UiIcon.vue'; import UiSelect from '../../kit/UiSelect.js'; // The voice control in the command dock, as its presenter @@ -79,7 +80,7 @@ const frameStyle = (panel) => ({ {{ view.mic.text }} - + {{ t('CHAT') }} @@ -94,12 +95,12 @@ const frameStyle = (panel) => ({
- - + {{ t('Back to chat') }} + {{ t('Back to voice') }} {{ t('VOICE') }}
- - + +
@@ -158,7 +159,7 @@ const frameStyle = (panel) => ({