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.
This commit is contained in:
German Khokhlov committed 2026-11-19 00:03:34 +04:00
1 parent 65942008bf
commit 2e18673df8
9 files changed
+453 -69

No files matched your search

+4 -1
View File
@@ -5,4 +5,7 @@
whose icon would sit against it, and a click zooms in until the group
splits. The camera layer's colour is now green: count markers and idle
single cameras share it, the active camera stays gold and live-video cameras
stay violet (gekh, #1808).
stay violet. Cameras that share one mount draw side by side instead of as
one icon with several callouts, and a camera the terrain height service
never answered for stands on the drawn terrain instead of drifting under
it (gekh, #1808).
+11 -1
View File
@@ -1958,7 +1958,17 @@ a small green camera pictogram under its top edge and the count just below its
middle. The marker grows with the count and is drawn on the world overlay at
the same resolution as camera callouts. A lone camera whose icon would sit
within 4 px of a marker is counted in that marker instead of being drawn; the
active camera always keeps its own icon.
active camera always keeps its own icon. On a globe map a marker stands on
the drawn terrain under its cameras' mean position, and a click frames that
ground. A camera the terrain height batch never answered for (no prior, or
the geoid fallback a failed or rate-limited chunk leaves) takes the terrain
the globe draws under it as its ground once it is near the screen, up to 300
cameras a view pass, and reads it again from less than half as far; a batch
answer that arrives later replaces it. Without this such a camera sits near
sea level, drifts across mountain terrain as the view tilts or pans, and
never leaves its count. Cameras on one mount (the same point to about a
metre) draw side by side, 30 px apart, once they show as icons; their records
keep the mount's position.
The count includes cameras beyond the screen edge and excludes cameras beyond
the horizon. Counts that would overlap on screen merge into one that carries
their sum. Clicking a count zooms to its group. Single cameras keep their icons,
+23 -5
View File
@@ -43,12 +43,28 @@ export function addCellCamera(cell, camera) {
cell.high = Math.max(cell.high, height);
}
/** Geographic mean on the globe surface at the mean mount height. */
/** Mean longitude and latitude of a cell's mounts, in degrees. */
export function cellLonLat(cell) {
return {
lon: cell.lonSum / (1e7 * cell.count),
lat: cell.latSum / (1e7 * cell.count),
};
}
/**
* Geographic mean of the mounts. Its height is the drawn ground under it
* when the cell carries one (`groundM`), since a camera nobody has looked at
* yet may still hold a catalog height far from the terrain; otherwise the
* mean mount height.
*/
export function cellCenter(cell) {
const { lon, lat } = cellLonLat(cell);
return fromDegrees(
cell.lonSum / (1e7 * cell.count),
cell.latSum / (1e7 * cell.count),
cell.heightSum / (100 * cell.count),
lon,
lat,
Number.isFinite(cell.groundM)
? cell.groundM
: cell.heightSum / (100 * cell.count),
);
}
@@ -56,7 +72,9 @@ export function cellCenter(cell) {
export function cellBounds(cell) {
const lat = (cell.north + cell.south) / 2;
const lon = (cell.east + cell.west) / 2;
const height = (cell.high + cell.low) / 2;
const height = Number.isFinite(cell.groundM)
? cell.groundM
: (cell.high + cell.low) / 2;
// The parallel nearest the equator bounds the width of every row.
const parallel = (Math.max(0, cell.south, -cell.north) * Math.PI) / 180;
// Half the diagonal plus 20% padding on every side.
+186 -1
View File
@@ -55,7 +55,7 @@ function recordsAt(lonLats) {
* equator, north up, through a camera port: the view pass projects the
* cameras from its pose.
*/
function viewerAt(heightM, lonDeg = 0, flights = []) {
function viewerAt(heightM, lonDeg = 0, flights = [], ports = {}) {
const eye = Cesium.Cartesian3.fromDegrees(lonDeg, 0, heightM);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
@@ -84,6 +84,7 @@ function viewerAt(heightM, lonDeg = 0, flights = []) {
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
...ports,
}),
);
return viewer;
@@ -369,6 +370,190 @@ test('a lone camera beside a count joins it, unless it is the active camera', ()
);
});
test('cameras the height batch never answered for take the drawn terrain', () => {
// Two mounts on one pole in the mountains and a lone camera. The batch
// answered for none of them, so they hold the catalog height (10 m), far
// under the terrain; a fourth camera has its answer and keeps it.
const { records } = recordsAt([
[0.001, 0.0005],
[0.001, 0.0005],
[0.2, 0],
[0.3, 0],
]);
// A failed chunk leaves the geoid fallback; a real answer is 'reearth'.
records[2].groundPrior = { ellipsoid: -20, source: 'geoid-fallback' };
records[3].groundPrior = { ellipsoid: 2, source: 'reearth' };
const flights = [];
const samples = [];
let terrain = 1872.4;
let globeShown = true;
const ports = {
globe: { isGlobeVisible: () => globeShown },
query: {
sampleHeightNow(point, options) {
samples.push([point, options]);
return terrain;
},
},
};
const heightOf = (position) =>
Cesium.Cartographic.fromCartesian(position).height;
const icon = (i) => _cctvIconsForTest().item(records[i].camera.id);
seedCoverage({ viewer: viewerAt(20_000, 0, flights, ports), records });
// The photoreal stack hides the globe: terrain is not the surface there.
globeShown = false;
refreshHorizonCulling();
assert.equal(samples.length, 0);
assert.ok(Math.abs(heightOf(records[0].position) - 10) < 0.01);
// Terrain that has not loaded leaves a camera where it is, to be read again.
globeShown = true;
terrain = null;
refreshHorizonCulling();
assert.ok(samples.length >= 3);
assert.ok(samples.every(([, options]) => options.against === 'terrain'));
assert.equal(records[0].groundPrior, undefined);
assert.ok(Math.abs(heightOf(markers()[0].pos) - 10) < 0.01);
terrain = 1872.4;
refreshHorizonCulling();
// Each unanswered camera stands its mount height above the drawn terrain.
for (const i of [0, 1, 2]) {
assert.equal(records[i].groundPrior.source, 'drawn-terrain');
assert.ok(Math.abs(records[i].camera.absoluteHeightM - 1880.4) < 1e-9);
assert.ok(Math.abs(heightOf(records[i].position) - 1880.4) < 0.01);
assert.ok(Math.abs(heightOf(icon(i).pos) - 1880.4) < 0.01);
}
// The answered one is left alone.
assert.equal(records[3].groundPrior.source, 'reearth');
assert.ok(Math.abs(heightOf(records[3].position) - 10) < 0.01);
// The count stands on the terrain and its click frames the ground there.
const [marker] = markers();
assert.equal(marker.cell.count, 2);
assert.ok(Math.abs(heightOf(marker.pos) - 1872) < 0.01);
clickMarker(marker);
assert.ok(Math.abs(heightOf(flights.at(-1).bounds.center) - 1872) < 0.01);
// Read once: the same view does not read a camera's terrain again.
samples.length = 0;
refreshHorizonCulling();
assert.ok(samples.every(([point]) => Math.abs(point.lat - 0.0005) < 1e-9));
// From less than half as far the finer terrain is read and replaces it.
terrain = 1890;
seedCoverage({ viewer: viewerAt(9_000, 0, flights, ports), records });
refreshHorizonCulling();
assert.ok(Math.abs(records[0].camera.absoluteHeightM - 1898) < 1e-9);
assert.equal(records[3].groundPrior.source, 'reearth');
});
test('a tilted view keeps the count of cameras that stood under the terrain', () => {
// The same pole seen from 200 m above the terrain and 1 km away, a view
// 11 degrees below the horizontal. Projected from its catalog height the
// pole falls below the padded screen and its count vanishes; on the
// terrain it is in the middle of the view.
const { records } = recordsAt([
[0, 0],
[0, 0],
]);
const ground = 1872;
const eye = Cesium.Cartesian3.fromDegrees(0, -0.009, ground + 200);
const target = Cesium.Cartesian3.fromDegrees(0, 0, ground);
const direction = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.subtract(target, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.cross(direction, eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const up = Cesium.Cartesian3.cross(right, direction, new Cesium.Cartesian3());
const plain = ({ x, y, z }) => ({ x, y, z });
const { port } = fakeCameraPort({
pose: {
lon: 0,
lat: -0.009,
height: ground + 200,
position: plain(eye),
direction: plain(direction),
up: plain(up),
right: plain(right),
fovy: Math.PI / 3,
aspectRatio: WIDTH / HEIGHT,
near: 0.1,
far: 5e8,
},
});
let terrain = null;
const viewer = {};
bindings.push(
bindRenderer(viewer, {
camera: port,
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
globe: { isGlobeVisible: () => true },
query: { sampleHeightNow: () => terrain },
}),
);
seedCoverage({ viewer, records });
refreshHorizonCulling();
assert.equal(markers().length, 0, 'under the terrain it is off the screen');
terrain = ground;
refreshHorizonCulling();
assert.deepEqual(
markers().map((item) => item.cell.count),
[2],
);
});
test('cameras on one mount draw side by side once they show as icons', () => {
const { records } = recordsAt([
[0.001, 0.0005],
[0.001, 0.0005],
[0.0011, 0.0005],
]);
// Close enough that every camera shows: about 0.87 m a pixel.
seedCoverage({ viewer: viewerAt(460), records });
refreshHorizonCulling();
assert.deepEqual(shownIds(records), ['cam-0', 'cam-1', 'cam-2']);
const icons = _cctvIconsForTest();
const [a, b, c] = records.map((record) => icons.item(record.camera.id).pos);
// 30 px apart along the screen's horizontal, centred on the shared mount.
const metres = Cesium.Cartesian3.distance(a, b);
const metresPerPixel = ((2 * Math.tan(Math.PI / 6)) / HEIGHT) * 450;
assert.ok(Math.abs(metres / metresPerPixel - 30) < 0.5);
const middle = Cesium.Cartesian3.midpoint(a, b, new Cesium.Cartesian3());
assert.ok(Cesium.Cartesian3.distance(middle, records[0].position) < 1e-6);
// The third camera, 11 m away, has a mount of its own.
assert.ok(Cesium.Cartesian3.distance(c, records[2].position) < 1e-6);
// The records keep the mount; callouts follow the drawn icons.
assert.ok(
Cesium.Cartesian3.distance(records[0].position, records[1].position) < 1e-9,
);
const callouts = cctvLayer.getDetectableObjects();
for (const [i, pos] of [a, b].entries()) {
const callout = callouts.find((o) => o.sourceId === `cam-${i}`);
assert.ok(Cesium.Cartesian3.distance(callout.position, pos) < 1e-9);
}
// An unchanged view writes nothing more.
const before = [a, b];
refreshHorizonCulling();
assert.equal(icons.item('cam-0').pos, before[0]);
assert.equal(icons.item('cam-1').pos, before[1]);
// Grouped again, both icons are back on the mount for their next showing.
seedCoverage({ viewer: viewerAt(20_000), records });
refreshHorizonCulling();
assert.deepEqual(shownIds(records), []);
for (const i of [0, 1])
assert.ok(
Cesium.Cartesian3.distance(
_cctvIconsForTest().item(`cam-${i}`).pos,
records[i].position,
) < 1e-6,
);
});
test('a pan keeps the same winners, and an unchanged view keeps its list', () => {
const { records } = recordsAt(CLUSTER);
seedCoverage({
+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}`,
+22 -3
View File
@@ -1,5 +1,6 @@
import {
cellCenter,
cellLonLat,
formatCameraCount,
mergeCountCells,
} from '../../data/cctvCellCounts.js';
@@ -201,16 +202,32 @@ export function createCountMarkers(
};
}
/** Reuse marker slots in ground-key order, and invalidate only changed frames. */
function update(cells, project) {
/**
* Reuse marker slots in ground-key order, and invalidate only changed frames.
* `groundHeight(lon, lat)` answers the drawn terrain height in metres, or
* null where it is not loaded; with it a count stands on the ground it
* marks whatever heights its cameras hold.
*/
function update(cells, project, groundHeight = null) {
// Lone cameras take part so that one beside a count joins it.
let visible = cells.slice().sort((a, b) => a.key.localeCompare(b.key));
const footprint = (count) => (count > 1 ? sizeFor(count) : SINGLE_ICON);
/** A lone camera keeps its icon's own position; a count goes to ground. */
const ground = (list) => {
if (!groundHeight) return;
for (const cell of list) {
if (cell.count === 1 || cell.groundM !== undefined) continue;
const { lon, lat } = cellLonLat(cell);
const height = groundHeight(lon, lat);
cell.groundM = Number.isFinite(height) ? Math.round(height) : null;
}
};
for (
let pass = 0;
pass < COUNT_MERGE_PASSES && visible.length > 1;
pass++
) {
ground(visible);
const merged = mergeCountCells(
visible,
project,
@@ -225,6 +242,7 @@ export function createCountMarkers(
for (const cell of cells)
if (cell.count === 1) cell.absorbed = !apart.has(cell);
visible = visible.filter((cell) => cell.count > 1);
ground(visible);
let changed = visible.length !== markers.length;
for (let i = 0; i < visible.length; i++) {
const cell = visible[i];
@@ -236,7 +254,8 @@ export function createCountMarkers(
last.count !== cell.count ||
last.latSum !== cell.latSum ||
last.lonSum !== cell.lonSum ||
last.heightSum !== cell.heightSum
last.heightSum !== cell.heightSum ||
last.groundM !== cell.groundM
) {
marker.pos = cellCenter(cell);
changed = true;
+71 -44
View File
@@ -214,56 +214,82 @@ export function createGround({ state: layerState, services, parts, source }) {
let applied = 0;
let moved = 0;
for (let i = 0; i < records.length && i < priors.length; i++) {
const record = records[i];
const prior = priors[i];
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) continue;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) continue;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (record.position) {
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
moved += 1;
}
continue;
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
applied += 1;
} else if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
applied += 1;
}
const outcome = applyGroundPrior(records[i], priors[i]);
if (outcome === 'moved') moved += 1;
else if (outcome === 'applied') applied += 1;
}
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
* Gives one live record a ground prior: `'moved'` when only its icon went
* onto the prior in place, `'applied'` when its geometry was recomputed,
* null when nothing changed. Pure recomputes, no scene queries.
*/
function applyGroundPrior(record, prior) {
if (!record || !prior || !Number.isFinite(prior.ellipsoid)) return null;
// Stale-record guard: init() may have re-run (destroy/init cycle) while
// the batch was in flight — only touch records still live in the map.
if (layerState._recordById.get(record.camera.id) !== record) return null;
record.groundPrior = prior;
// Keep the cheap pre-enable altitude consistent for records whose
// geometry hasn't been applied yet (applyFrustumGeometry overwrites it).
if (!record.frustumPositions) {
record.camera.absoluteHeightM =
prior.ellipsoid + record.camera.mountHeightM;
}
// Cameras without geometry only move their icon onto the prior, so the
// view pass projects the right point; their frustums are built when
// they enter the view, as recomputing the whole catalog here would
// stall a large one.
if (!record.frustumGeometry) {
if (!record.position) return null;
// In place: the record keeps its position object.
const { x, y, z } = fromDegrees(
record.camera.lon,
record.camera.lat,
record.camera.absoluteHeightM,
);
record.position.x = x;
record.position.y = y;
record.position.z = z;
parts.rendering.moveCameraIcon(record);
return 'moved';
}
const regime = currentSurfaceRegime();
if (regime === 'terrain-globe') {
// Prior IS the resolution — re-latch onto the fresh value.
parts.geometry.updateRecordGeometry(record, { sampleGround: false });
return 'applied';
}
if (!Number.isFinite(record.groundSamples['google-3d'])) {
// Still awaiting the shared floor: snap interim geometry onto the exact
// prior (pure recompute; the shared cell may refine later).
parts.geometry.applyFrustumGeometry(record, prior.ellipsoid);
return 'applied';
}
return null;
}
/**
* A camera the height batch never answered for (a failed or rate-limited
* chunk leaves it on the catalog's fabricated ground) takes the terrain
* the globe draws under it as its prior, so that it stands on the surface
* the user sees. `rangeM` is how far the eye was when the terrain was
* read: a closer look reads finer terrain and replaces it, and so does a
* batch answer that arrives later.
* @returns {'moved'|'applied'|null} As `applyGroundPrior`.
*/
function adoptDrawnGround(record, heightM, rangeM) {
return applyGroundPrior(record, {
ellipsoid: heightM,
source: 'drawn-terrain',
rangeM,
});
}
/**
* Task 5: surface-regime change handler ('gev:map-stack-changed'
* CustomEvent, dispatched by main.js from MapStackController.onChange). The
@@ -399,6 +425,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveCommittedGroundAnchor,
resolveGroundPriors,
applyLateGroundPriors,
adoptDrawnGround,
handleMapStackChanged,
};
}
+8
View File
@@ -71,6 +71,14 @@ export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// Cameras on one mount (the same point to about a metre) draw side by side,
// this many pixels apart, once they show as icons.
export const VIEW_SITE_SPREAD_PX = 30;
// Cameras without a ground height that one view pass may read from the drawn
// terrain. The rest wait for the next pass.
export const VIEW_GROUND_READS = 300;
// Diameter at one camera before applying the size limits, in CSS pixels.
export const COUNT_BASE_PX = 38;
+126 -13
View File
@@ -17,6 +17,8 @@ import {
VIEW_CELL_PX,
VIEW_ICON_MARGIN,
VIEW_MIN_CELL_M,
VIEW_SITE_SPREAD_PX,
VIEW_GROUND_READS,
} from './policy.js';
import { createIconBook } from '../../render/motion/iconBook.js';
import { frustumVolumeGeometryData } from '../../data/cctvViewshed.js';
@@ -27,6 +29,7 @@ import {
findGlobe,
findQuery,
} from '../../render/rendererOf.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegrees, WGS84 } from '../../geo/ellipsoid.js';
import { eastNorthUp } from '../../geo/frames.js';
import { poseProjector } from '../../geo/frustum.js';
@@ -383,6 +386,16 @@ export function createRendering({
const picker = [];
const cells = new Map();
const visibleCells = [];
// The terrain the globe draws, where it is the surface (not on the
// photoreal stack) and loaded: null elsewhere.
const heights = heightsOf(layerState._viewer);
const groundHeight =
findQuery(layerState._viewer) &&
findGlobe(layerState._viewer)?.isGlobeVisible?.() === true
? (lon, lat) => heights.now({ lon, lat }, { against: 'terrain' })
: null;
let groundReads = groundHeight ? VIEW_GROUND_READS : 0;
const regrounded = [];
for (const record of layerState._records) {
const position = record.position;
if (!position) continue;
@@ -397,20 +410,49 @@ export function createRendering({
(vtDotVc * vtDotVc) / (vx * vx + vy * vy + vz * vz) > limbSquared
)
continue;
const screen = project(position);
let screen = project(position);
let range = distance(position, viewer);
// A camera the height batch never answered for (no prior, or the
// geoid fallback a failed chunk leaves) sits near sea level, which can
// be kilometres under the terrain: it would project to the wrong
// place, drift as the view moves and measure too far for its cell.
// Anywhere near the screen, it takes the drawn terrain.
const prior = record.groundPrior;
const drawn = prior?.source === 'drawn-terrain';
if (
groundReads > 0 &&
(!prior ||
prior.source === 'geoid-fallback' ||
(drawn && prior.rangeM > 2 * range)) &&
screen &&
screen.x >= -width &&
screen.x <= 2 * width &&
screen.y >= -height &&
screen.y <= 2 * height
) {
groundReads--;
const ground = groundHeight(record.camera.lon, record.camera.lat);
if (Number.isFinite(ground)) {
if (drawn && Math.abs(ground - prior.ellipsoid) < 1) {
prior.rangeM = range;
} else if (record.frustumGeometry) {
// Recomputing geometry writes draw sets: after this pass.
regrounded.push([record, ground, range]);
} else if (
parts.ground.adoptDrawnGround(record, ground, range) === 'moved'
) {
screen = project(position);
range = distance(position, viewer);
}
}
}
const nearScreen =
screen &&
screen.x >= minX &&
screen.x <= maxX &&
screen.y >= minY &&
screen.y <= maxY;
const dx = position.x - viewer.x;
const dy = position.y - viewer.y;
const dz = position.z - viewer.z;
const cellM =
VIEW_CELL_PX *
metresPerPixelPerMetre *
Math.sqrt(dx * dx + dy * dy + dz * dz);
const cellM = VIEW_CELL_PX * metresPerPixelPerMetre * range;
if (record.camera.id === activeId || !(cellM >= VIEW_MIN_CELL_M)) {
if (!nearScreen) continue;
record.viewPass = record.pickerPass = pass;
@@ -435,8 +477,10 @@ export function createRendering({
cell.rank = rank;
}
}
// Marks each lone camera that a count marker beside it has taken in.
layerState._counts?.update(visibleCells, project);
// A count stands on the drawn terrain too: its cell may be too far for
// its cameras to have been read. Marks each lone camera that a count
// marker beside it has taken in.
layerState._counts?.update(visibleCells, project, groundHeight);
for (const cell of visibleCells) {
const record = cell.winner;
picker.push(record);
@@ -446,6 +490,7 @@ export function createRendering({
shown.push(record);
}
}
spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass);
const writes = [];
let coverageChanged = false;
let cardsChanged = false;
@@ -462,12 +507,21 @@ export function createRendering({
layerState._cardIds?.has(id) || layerState._hoverCardId === id;
}
record.viewGrouped = grouped;
const item = patchedCameraIcon(record.camera.id, {
show: record.viewPass === pass,
});
const fields = { show: record.viewPass === pass };
if (record.spreadPass === pass) {
const drawn = layerState._icons?.item(record.camera.id)?.pos;
if (!drawn || !samePoint(drawn, record.spreadPosition))
fields.pos = copyPoint(record.spreadPosition);
} else if (record.spreadPosition) {
// No longer beside a mount mate: back onto its own position.
record.spreadPosition = null;
fields.pos = copyPoint(record.position);
}
const item = patchedCameraIcon(record.camera.id, fields);
if (item) writes.push(item);
}
writeCameraIcons(writes);
if (regrounded.length) queueMicrotask(() => reground(regrounded));
const previous = layerState._viewRecords;
const changed =
previous.length !== shown.length ||
@@ -483,6 +537,65 @@ export function createRendering({
return changed || pickerChanged;
}
/**
* Cameras that have geometry take the drawn terrain after the pass that
* read it, then the view is passed again from their new positions.
*/
function reground(entries) {
let changed = false;
for (const [record, ground, range] of entries)
changed =
parts.ground.adoptDrawnGround(record, ground, range) !== null ||
changed;
if (!changed) return;
if (refreshHorizonCulling()) parts.geometryQueue.enqueueViewGeometry();
parts.presentation.notifyListeners();
}
/**
* Cameras on one mount would draw as one icon with several callouts. Among
* the cameras shown, those that share a point to about a metre get draw
* positions side by side along the screen's horizontal, in id order,
* `VIEW_SITE_SPREAD_PX` apart at the distance they are seen from. The
* record's own position is untouched: geometry and cards keep the mount.
*/
function spreadSharedMounts(shown, pose, metresPerPixelPerMetre, pass) {
const { right, direction, position: eye } = pose;
if (!right || !direction || shown.length < 2) return;
const mounts = new Map();
for (const record of shown) {
const { lat, lon } = record.camera;
const key = `${Math.round(lat * 1e5)}:${Math.round(lon * 1e5)}`;
const mates = mounts.get(key);
if (mates) mates.push(record);
else mounts.set(key, [record]);
}
for (const mates of mounts.values()) {
if (mates.length < 2) continue;
mates.sort((a, b) => a.camera.id.localeCompare(b.camera.id));
for (let i = 0; i < mates.length; i++) {
const record = mates[i];
const p = record.position;
// A pixel's width on the ground grows with depth along the view.
const depth =
(p.x - eye.x) * direction.x +
(p.y - eye.y) * direction.y +
(p.z - eye.z) * direction.z;
const metres =
(i - (mates.length - 1) / 2) *
VIEW_SITE_SPREAD_PX *
metresPerPixelPerMetre *
depth;
record.spreadPosition = {
x: p.x + right.x * metres,
y: p.y + right.y * metres,
z: p.z + right.z * metres,
};
record.spreadPass = pass;
}
}
}
/**
* Canvas coordinates for world positions, from the eye's pose by the
* renderer's perspective projection (geo/frustum.js): one pose read per