Compare commits

...
Author SHA1 Message Date
German Khokhlov 81fe7f88cc 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.
2026-11-19 03:07:04 +04:00
German Khokhlov 2e18673df8 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.
2026-11-19 00:03:34 +04:00
German Khokhlov 65942008bf 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.
2026-11-18 21:23:41 +04:00
German Khokhlov c536d22ff0 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.
2026-11-18 20:48:33 +04:00
German Khokhlov aabfa5e084 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.
2026-11-18 15:31:20 +04:00
German Khokhlov 87bff9957b 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.
2026-11-18 15:02:07 +04:00
German Khokhlov 607796737c 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.
2026-11-18 14:26:37 +04:00
31 changed files with 3533 additions and 246 deletions

No files matched your search

+8
View File
@@ -0,0 +1,8 @@
- 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).
+23 -9
View File
@@ -1952,14 +1952,28 @@ 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 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.
@@ -7334,7 +7348,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
+1
View File
@@ -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.
+5
View File
@@ -625,6 +625,9 @@
"src/layers/cctv/health.js",
"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",
"src/data/cctvGroundHeights.test.mjs",
@@ -643,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",
+7
View File
@@ -3282,6 +3282,9 @@
"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",
"src/data/iconOrientation.js",
"src/data/screenRotation.js",
@@ -4233,6 +4236,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 +5564,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",
+2 -1
View File
@@ -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,
+1 -1
View File
@@ -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. */
+15 -1
View File
@@ -85,7 +85,9 @@ import {
} from '../cctvFocusRequest.js';
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';
@@ -353,7 +355,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 +387,18 @@ 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;
const idleImage = image(idleStill);
assert.equal(idleImage, IDLE_CAMERA_ICON);
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();
+220
View File
@@ -0,0 +1,220 @@
import { fromDegrees } from '../geo/ellipsoid.js';
/** 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 =
count < 10000 ? Math.round(count / 100) / 10 : Math.round(count / 1000);
return `${thousands}K`;
}
/** 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);
}
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: wrapLongitude(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(
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
/** 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 = 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;
const halfWidth =
0.5 *
Math.hypot(
(cell.east - cell.west) * 111_320 * Math.cos(parallel),
(cell.north - cell.south) * 111_320,
);
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 + 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 + 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);
}
/** 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) {
// 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;
visit(other, dx * dx + dy * dy, reach);
}
}
}
}
/**
* 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 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) {
let columnWidth = 0;
let rowHeight = 0;
const markers = cells.map((cell) => {
const screen = project(cellCenter(cell));
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.
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 / rowHeight);
const key = `${marker.col},${marker.row}`;
if (!grid.has(key)) grid.set(key, new Set());
marker.bucket = grid.get(key);
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 = [];
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;
}
+216
View File
@@ -0,0 +1,216 @@
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,
mergeCountCells,
} from './cctvCellCounts.js';
test('camera counts use Latin digits and K notation whatever the 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 {
setLocale('ar');
for (const [count, label] of examples)
assert.equal(formatCameraCount(count), label);
} 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,
);
}
});
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 check = (counts, positions, expected) => {
const { groups } = mergeCounts(sizes, counts, positions);
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]);
});
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 check = (counts, positions, expected) => {
const { cells, groups } = mergeCounts(sizes, counts, positions);
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]);
});
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));
});
+254
View File
@@ -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',
);
});
File diff suppressed because it is too large. Load diff
+1 -1
View File
@@ -229,7 +229,7 @@ export function createCards({ state: layerState, services, parts, source }) {
let rank = 0;
const push = (id, { pinned = false, active = false } = {}) => {
const record = layerState._recordById.get(id);
if (!record?.position) return;
if (!record?.position || (!active && record.viewGrouped)) return;
entries.push(
createCctvThumbnailOverlayEntry({
id,
+2 -1
View File
@@ -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}`,
+387
View File
@@ -0,0 +1,387 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
import { WORLD_OVERLAY_STYLE } from '../../overlays/worldOverlayTokens.js';
import {
CAMERA_GREEN,
COUNT_CAMERA_ICON,
CAMERA_ICON_PX,
COUNT_MERGE_GAP_PX,
} 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;
// 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,
keyholeAlpha,
) {
let hardUi = null;
let sprite = null;
let spriteReady = false;
const markers = [];
const hits = [];
const textMetrics = new Map();
const fonts = globalThis.document?.fonts;
let measureCtx;
let hitCount = 0;
const lane = registerPaintLane?.('ambient-label', paint, {
id,
active: false,
target: 'shared',
});
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. */
function fontsLoaded() {
textMetrics.clear();
if (!markers.length) return;
refreshView();
lane?.requestPaint();
}
/** 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 ??= 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);
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;
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));
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.
* `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, 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;
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 &&
visible.some((cell) => cell.count > 1);
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
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);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
const cell = visible[i];
const marker = (markers[i] ??= { focus: 1 });
const last = marker.cell;
const size = sizeFor(cell.count);
if (
!last ||
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM
) {
marker.pos = cellCenter(cell);
marker.cullPos = liftedForHorizon(marker.pos);
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 ||
size.glyphBottom !== marker.glyphBottom ||
size.labelY !== marker.labelY;
marker.cell = cell;
Object.assign(marker, size);
// 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();
}
/** 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);
hitCount = 0;
return;
}
hitCount = 0;
const { ctx, occluder, viewProjectionMatrix: m } = frame;
let refresh = false;
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 { 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.cullPos)))
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
)
continue;
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,
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 = RING_PX + 2 * RIM_PX;
ctx.stroke();
ctx.fillStyle = '#0e1720';
ctx.fill();
ctx.strokeStyle = CAMERA_GREEN;
ctx.lineWidth = RING_PX;
ctx.stroke();
ctx.fillStyle = CAMERA_GREEN;
if (spriteReady) {
const width = marker.glyphHeight * GLYPH_SOURCE_ASPECT;
ctx.drawImage(
sprite,
...GLYPH_SOURCE,
x - width / 2,
y + marker.glyphBottom - marker.glyphHeight,
width,
marker.glyphHeight,
);
}
ctx.fillText(marker.text, x, y + marker.labelY);
rect.cell = marker.cell;
hitCount++;
}
} finally {
ctx.restore();
}
if (refresh) queueMicrotask(refreshView);
}
/** 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];
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;
}
/** A new group may already have arrived since the empty frame. */
function deactivateIfEmpty() {
if (!markers.length) lane?.setActive(false);
}
/** 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() {
hide();
fonts?.removeEventListener?.('loadingdone', fontsLoaded);
lane?.unregister();
}
return {
markers,
update,
pickedCell,
hide,
dispose,
requestPaint: () => lane?.requestPaint(),
};
}
+136
View File
@@ -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);
});
+74 -45
View File
@@ -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,
@@ -214,56 +214,84 @@ 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;
// 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).
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.
fromDegreesInto(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
record.position,
);
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;
}
/**
* 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, read) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
...read,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +427,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+64
View File
@@ -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');
});
+34 -4
View File
@@ -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?.();
@@ -163,9 +190,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;
@@ -285,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
@@ -386,6 +414,7 @@ export function createLifecycle({
parts.rendering.refreshHorizonCulling();
const input = inputFor(layerState._viewer);
layerState._clickSubscription?.();
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
@@ -536,6 +565,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();
},
+34
View File
@@ -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);
});
+47 -7
View File
@@ -1,6 +1,9 @@
import { distance } from '../../geo/vector.js';
import { rangeForBoundingSphere } from '../../data/cameraFraming.js';
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,
@@ -63,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.
@@ -74,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',
);
@@ -104,6 +115,34 @@ 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;
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 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);
// 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,
easing: 'cubicInOut',
});
}
function focusCamera(cameraId, duration = 2.2) {
return focusCctvRecord(
layerState._viewer,
@@ -179,6 +218,7 @@ export function createNavigation({
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
zoomToCell,
focusCamera,
maybeAutoHop,
cctvCycleIndex,
+66 -18
View File
@@ -60,17 +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 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;
// 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;
/**
* 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;
// 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.
@@ -182,28 +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.
*/
export const CAMERA_ICON = (() => {
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 = `<svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 36 36">
<defs>
<linearGradient id="lens" x1="0" y1="0" x2="1" y2="1">
<stop offset="0%" stop-color="#c9f6ff"/>
<stop offset="45%" stop-color="#6fd9ff"/>
<stop offset="100%" stop-color="#1a5f78"/>
<stop offset="0%" stop-color="${tone('#c9f6ff', '#ffffff')}"/>
<stop offset="45%" stop-color="${tone('#6fd9ff', '#dddddd')}"/>
<stop offset="100%" stop-color="${tone('#1a5f78', '#666666')}"/>
</linearGradient>
</defs>
<g transform="translate(4 6)">
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="#0e1720" stroke="#75e7ff" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="#132433" stroke="#75e7ff" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="#dbfbff" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="#10212d" stroke="#75e7ff" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="#0b151d" stroke="#4ecde7" stroke-width="0.8"/>
<rect x="0" y="8" width="20" height="9" rx="2.5" fill="${tone('#0e1720', '#181818')}" stroke="${stroke}" stroke-width="1.2"/>
<rect x="17" y="10" width="10" height="5" rx="1.5" fill="${tone('#132433', '#222222')}" stroke="${stroke}" stroke-width="1"/>
<circle cx="24" cy="12.5" r="3.1" fill="url(#lens)" stroke="${tone('#dbfbff', '#ffffff')}" stroke-width="0.8"/>
<rect x="6.4" y="17" width="4.2" height="8.5" rx="1.2" fill="${tone('#10212d', '#202020')}" stroke="${stroke}" stroke-width="1"/>
<rect x="4.2" y="24" width="8.6" height="2.5" rx="1.1" fill="${tone('#0b151d', '#151515')}" stroke="${tone('#4ecde7', '#cccccc')}" stroke-width="0.8"/>
</g>
</svg>`;
return 'data:image/svg+xml;base64,' + btoa(svg);
})();
}
export const CAMERA_ICON = cameraIcon();
export const IDLE_CAMERA_ICON = cameraIcon('#ffffff');
/**
* Seed camera definitions used when no live sources are available.
@@ -441,7 +485,11 @@ 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 COUNT_CAMERA_ICON = cameraIcon(CAMERA_GREEN);
export const IDLE_CAMERA_COLOR = hexColor(CAMERA_GREEN);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
+12 -9
View File
@@ -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,16 +313,16 @@ 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}[]}
*/
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;
+400 -87
View File
@@ -1,7 +1,13 @@
import { createCountMarkers } from './countMarkers.js';
import { addCellCamera, createCameraCell } from '../../data/cctvCellCounts.js';
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,
ACTIVE_COVERAGE_CENTER,
@@ -14,6 +20,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';
@@ -24,11 +32,21 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { heightsOf } from '../../queries/heights.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 };
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];
@@ -46,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,
@@ -139,6 +151,12 @@ export function createRendering({
// with its first camera.
set.setColumns?.({ ids: [] });
layerState._icons = createIconBook(set);
layerState._counts = createCountMarkers(
services.overlays?.registerWorldOverlayPaintLane,
`cctv:${iconSets}:counts`,
refreshHorizonCulling,
services.overlays?.keyholeAlpha,
);
return set.id;
}
@@ -146,6 +164,8 @@ export function createRendering({
function destroyCameraIcons() {
layerState._icons?.dispose();
layerState._icons = null;
layerState._counts?.dispose();
layerState._counts = null;
}
/** The icon item a camera record draws, idle and shown, at its position. */
@@ -153,10 +173,9 @@ export function createRendering({
const id = record.camera.id;
return {
id,
pos: copyPoint(record.position),
image: CAMERA_ICON,
pos: copyPoint(record.spreadPosition ?? record.position),
...cameraIconStyleFor(record),
size: [CAMERA_ICON_PX, CAMERA_ICON_PX],
color: cameraColorFor(record),
scale: 1,
scaleByDistance: CAMERA_SCALE_BY_DISTANCE,
disableDepthTest: Infinity,
@@ -195,22 +214,26 @@ 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) });
}
/** 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 {
@@ -219,11 +242,14 @@ 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
* 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,61 +302,71 @@ 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;
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 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,
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(icons.focus(id), focus.factor, params)) {
icons.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 || []) {
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,
marker.height,
marker.focus,
);
if (factor !== null) marker.focus = factor;
}
if (writes > iconWrites) counts.requestPaint();
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.
* 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() {
@@ -365,7 +401,30 @@ 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 = [];
// 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) && 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;
if (!position) continue;
@@ -380,48 +439,296 @@ 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);
// 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 (
!screen ||
!(screen.x >= minX && screen.x <= maxX) ||
!(screen.y >= minY && screen.y <= maxY)
)
continue;
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);
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
record.viewPass = pass;
groundReads > 0 &&
!record.regroundPending &&
(unanswered ||
(drawn &&
(prior.rangeM > 2 * range ||
prior.surface !== surface ||
(!prior.settled && terrainSettled))))
) {
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 &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
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) {
cell = createCameraCell(key);
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.
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);
// 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);
record.pickerPass = pass;
if (cell.count === 1 && !cell.absorbed) {
record.viewPass = pass;
shown.push(record);
}
}
spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass);
clearActiveOfCounts(project, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
for (const record of layerState._records) {
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const cell = record.viewCell;
record.viewCell = null;
const grouped = Boolean(
cell?.winner && (cell.count > 1 || cell.absorbed),
);
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 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.spreadOffset = null;
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 ||
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;
}
/**
* 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, read] of entries) {
record.regroundPending = false;
changed =
parts.ground.adoptDrawnGround(record, ground, read) !== 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 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.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const grid = new Map();
const mounts = [];
const axes = eastNorthUp(eye);
for (const record of shown) {
// 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) {
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.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;
}
/**
@@ -526,6 +833,7 @@ export function createRendering({
);
parts.projection.clearProjectionOverlay();
if (layerState._icons) layerState._icons.show = false;
layerState._counts?.hide();
parts.projection.pauseInactiveProjectionFeeds(null);
}
@@ -535,8 +843,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';
@@ -553,7 +865,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);
@@ -865,6 +1177,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;
+85 -2
View File
@@ -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,29 +114,80 @@ 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 = {};
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,
setActive() {},
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);
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(lanes[0].disposed, true);
lanes[0].paint({});
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
assert.equal(lanes[1].disposed, true);
lanes[1].paint({});
assert.equal(state._counts, null);
} finally {
one.unbind();
two.unbind();
@@ -376,3 +427,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();
}
});
+30 -5
View File
@@ -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.
@@ -41,6 +59,13 @@ 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)) {
parts.navigation.zoomToCell(cell);
return;
}
onClick(event);
});
}
@@ -139,11 +164,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.
// 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();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
+98
View File
@@ -1,6 +1,9 @@
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';
import { bindRenderer } from '../../render/rendererOf.js';
import { createNavigation } from './navigation.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
@@ -52,3 +55,98 @@ 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: (point) => (point?.x === 14 && point.y === 26 ? cell : null),
},
};
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({
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);
} finally {
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');
}
});
+11 -3
View File
@@ -15,6 +15,7 @@ export function createState({ services }) {
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._counts = null;
layerState._records = [];
@@ -95,10 +96,14 @@ export function createState({ services }) {
// work over these, not the whole catalog.
layerState._viewRecords = [];
// 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
@@ -113,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.
+12
View File
@@ -1,3 +1,4 @@
import { createCountMarkers } from './countMarkers.js';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
@@ -90,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<string, Object>} [options.healthById] Health rows by camera id.
* @param {Function} [options.registerPaintLane] Receives the count painter.
* @returns {void}
*/
@@ -102,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 : [];
@@ -123,12 +126,20 @@ 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?.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);
}
@@ -148,6 +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,
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
+3
View File
@@ -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,
+5
View File
@@ -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;
};