From c536d22ff09ac8cd08799d64a3a0e815f7d1dad0 Mon Sep 17 00:00:00 2001 From: German Khokhlov Date: Wed, 18 Nov 2026 20:48:33 +0400 Subject: [PATCH] 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 = {};