Files
gods-eye-view/src/layers/cctv/presentation.js
T
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

374 lines
14 KiB
JavaScript

import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { isolate, msg, t } from '../../i18n/index.js';
import { ACTIVE_FRAME_REFRESH_MS, IDLE_FRAME_REFRESH_MS } from './policy.js';
import { headingHudToken, isHeadingEstimated } from './headingConfidence.js';
import {
specSummary,
specFovCapabilityToken,
isDatasheetFov,
} from './modelSpecs.js';
// The summary line names the CAL badge, the source kind and the view band in
// the page language; the codes underneath stay English.
const CAL_BADGE_LABELS = Object.freeze({
calibrated: msg('CALIBRATED'),
curated: msg('CURATED'),
'raw-prior': msg('RAW PRIOR'),
});
// The same source-kind words as the CCTV panel (src/ui/cctvFrames.js).
const SOURCE_KIND_LABELS = Object.freeze({
snapshot: msg('SNAPSHOT'),
live: msg('LIVE'),
fallback: msg('FALLBACK'),
upstream: msg('UPSTREAM'),
synthetic: msg('SYNTHETIC'),
configured: msg('CONFIGURED'),
seed: msg('SEED'),
image: msg('IMAGE'),
unknown: msg('UNKNOWN'),
});
/** CAL badge id ('raw-prior') as the summary shows it; unknown ids stay codes. */
export function summaryCalLabel(badge) {
const key = String(badge || '');
return CAL_BADGE_LABELS[key]
? t(CAL_BADGE_LABELS[key])
: key.replace('-', ' ').toUpperCase();
}
/** Source kind ('image', 'snapshot') for the summary; HLS, MJPEG… stay codes. */
export function summarySourceLabel(kind) {
const key = String(kind || 'image').toLowerCase();
return SOURCE_KIND_LABELS[key]
? t(SOURCE_KIND_LABELS[key])
: key.toUpperCase();
}
/** View band id ('street', 'city'…) as the HUD names it. */
export function summaryViewBandLabel(band) {
switch (band) {
case 'street':
return t('STREET', { context: 'view band' });
case 'city':
return t('CITY', { context: 'view band' });
case 'regional':
return t('REGIONAL', { context: 'view band' });
case 'global':
return t('GLOBAL', { context: 'view band' });
default:
return String(band || '').toUpperCase();
}
}
export function createPresentation({
state: layerState,
services,
parts,
source,
}) {
/**
* Builds a single-line summary string for the active camera, including city,
* heading, FOV, coverage area, overlap count, projection mode, alignment
* confidence, source type, and view context.
* @returns {string} Summary text separated by mid-dots.
*/
function buildSummaryText() {
const active = parts.selection.getActiveRecord();
if (!active) {
return layerState._records.length
? t(
'{count} CAMERAS STANDING BY · NO CAMERA SELECTED · CLICK A CAMERA TO ACTIVATE',
{
count: layerState._records.length,
},
)
: t('No cameras available in catalog.');
}
const area = parts.model.sectorAreaKm2(
active.camera.rangeM,
active.camera.fovDeg,
);
const overlapCount = parts.geometry.coverageNeighborCount(active);
const viewKey = parts.model.currentViewContext();
const viewBand = viewKey.split(':')[0] || 'global';
const health = layerState._healthById.get(active.camera.id) || null;
const calBadge = parts.calibration.deriveCalBadge(active.camera);
// Each part is isolated: in right-to-left text a code keeps its own value
// (FOV 44°) instead of trading it with its neighbour.
return [
t('{city} CCTV', {
city: active.camera.city.toUpperCase(),
}),
`${active.camera.name.toUpperCase()}`,
// A synthetic bearing (headingConfidence 'low', no human calibration)
// is tagged so a hashed guess never reads as a surveyed facing (#639).
headingHudToken(active.camera),
// Identified hardware labels its FOV as datasheet-sourced (catalog.js)
// only while no manual calibration offset has moved it.
isDatasheetFov(active.camera)
? t('FOV {value}° (DATASHEET)', {
value: Math.round(active.camera.fovDeg),
})
: t('FOV {value}°', {
value: Math.round(active.camera.fovDeg),
}),
// A PTZ/varifocal datasheet range is what the lens can do, not its
// current zoom, so it is shown beside the estimate, never as it.
specFovCapabilityToken(active.camera, (span) =>
t('SPEC FOV {span}° (CAPABILITY)', { span }),
),
t('COVERAGE {value}km²', { value: area.toFixed(2) }),
overlapCount > 0
? t('OVERLAP {count} cams', { count: overlapCount })
: t('ISOLATED VIEW'),
layerState._showProjection ? t('PROJ MONITOR') : t('PROJ OFF'),
layerState._coverageMode === 'viewshed' ? t('VIEWSHED') : null,
t('CAL {value}', { value: summaryCalLabel(calBadge) }),
t('SRC {value}', {
value: summarySourceLabel(
health?.sourceKind || active.camera.feedType || 'image',
),
}),
t('{value} CONTEXT', { value: summaryViewBandLabel(viewBand) }),
// Identified hardware: append the model's datasheet specs + attribution.
active.camera.spec
? t('{spec} · SPECS: CCTV-DATABASE.COM', {
spec: specSummary(active.camera.spec).toUpperCase(),
})
: null,
]
.filter(Boolean)
.map(isolate)
.join(' · ');
}
/**
* Builds a public-facing camera state object for UI consumption.
* Includes all pose, calibration, CAL badge, projection, and feed metadata.
* @param {Object} record - Camera record.
* @param {string|null} [activeId=null] - Active camera ID for the `active` flag.
* @returns {Object} Public camera state.
*/
function getPublicCameraState(record, activeId = null) {
const resolvedActiveId =
activeId || parts.selection.getActiveRecord()?.camera.id || null;
const camera = record.camera;
const health = layerState._healthById.get(camera.id) || null;
const isActive = camera.id === resolvedActiveId;
const defaultRefreshMs = isActive
? ACTIVE_FRAME_REFRESH_MS
: IDLE_FRAME_REFRESH_MS;
const sourceRefreshMs = Number(camera.frameRefreshMs);
const refreshMs =
Number.isFinite(sourceRefreshMs) && sourceRefreshMs > 0
? Math.max(defaultRefreshMs, sourceRefreshMs)
: defaultRefreshMs;
return {
id: camera.id,
name: camera.name,
city: camera.city,
provider: camera.provider,
lat: camera.lat,
lon: camera.lon,
headingDeg: camera.headingDeg,
// Bearing provenance (#639): the pack's confidence flag plus the derived
// "is this a synthetic guess" bit (calibration-aware), so UI consumers
// never have to re-derive it.
headingConfidence: camera.headingConfidence || null,
headingEstimated: isHeadingEstimated(camera),
pitchDeg: camera.pitchDeg,
fovDeg: camera.fovDeg,
// Identified-hardware enrichment passthrough (catalog.js / modelSpecs.js).
fovSource: isDatasheetFov(camera)
? 'datasheet'
: camera.fovSource === 'datasheet'
? 'calibrated'
: camera.fovSource || 'estimated',
specFovMinDeg: camera.specFovMinDeg ?? null,
specFovMaxDeg: camera.specFovMaxDeg ?? null,
spec: camera.spec || null,
rangeM: camera.rangeM,
elevationM: camera.absoluteHeightM,
mountHeightM: camera.mountHeightM,
active: isActive,
feedType: camera.feedType,
sourceUrl: camera.sourceUrl || '',
browserMediaUrl: camera.browserMediaUrl || '',
accuracyM: Number.isFinite(camera.accuracyM) ? camera.accuracyM : null,
positionSource: camera.positionSource || '',
isVideo:
parts.model.isVideoFeedCamera(camera) &&
record.projection?.mode !== 'image',
sourceKind: camera.sourceKind?.startsWith('quebec-')
? camera.sourceKind
: health?.sourceKind ||
camera.sourceKind ||
(camera.feedConfigured ? 'configured' : 'seed'),
sourceStatus: health?.status || 'unknown',
sourceMessage: health?.message || '',
sourceLabel: health?.label || camera.provider || '',
credit: camera.credit || '',
calibration: {
...parts.calibration.normalizeCalibration(camera.calibration),
},
// Save-gated persistence (design §3e): true while the live pose carries
// edits that have not been SAVEd (or RESET). Drives the CAL · EDITED chip.
calDirty: !!record.calDirty,
// Deterministic QA seam: counts commit-grade anchor resolutions (E/N drag
// release, numeric E/N edit, or reset), never transient gizmo moves.
groundResolveCount: record.calibrationGroundResolveCount || 0,
// Per-record QA seam for proving transient gizmo moves never enter the
// shared mesh-floor sampler while unrelated catalog cells finish.
groundMeshSampleRequestCount: record.groundMeshSampleRequestCount || 0,
// Datum QA seam: expose the immutable Re:Earth ellipsoidal prior
// 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.
// 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,
// Panel-only trust signal (design §3b, amended by LOCKED §9.2/§9.3): no
// in-world rendering reads this, no score-based quality math backs it.
calBadge: parts.calibration.deriveCalBadge(camera),
poseSource: camera.poseSource || null,
basePose: camera.basePose ? { ...camera.basePose } : null,
frameUrl: parts.frames.frameUrlFor(camera, refreshMs),
mediaUrl: parts.frames.mediaUrlFor(camera),
};
}
/**
* Assembles the full UI state payload containing layer toggles, camera list,
* active camera details, summary text, and error state.
* @returns {Object} Complete UI state for subscribers.
*/
function uiState() {
const active = parts.selection.getActiveRecord();
const activeId = active?.camera.id || null;
const payload = {
enabled: layerState._enabled,
// Compat boolean + the full tri-state (viewshed design §3b).
showCoverage: layerState._coverageMode !== 'off',
coverageMode: layerState._coverageMode,
showProjection: layerState._showProjection,
calibrationMode: layerState._calibrationMode,
autoHop: layerState._autoHop,
autoHopSuspended: layerState._autoHopSuspended,
autoHopSec: layerState._autoHopSec,
count: layerState._count,
lastUpdate: layerState._lastUpdate,
error: layerState._lastError,
loading: {
active: layerState._geoLoading,
loaded: Math.min(layerState._geoLoadDone, layerState._geoLoadTotal),
total: layerState._geoLoadTotal,
},
// Ambient card tier telemetry (QA harnesses assert the fetch pacing —
// minFrameFetchSpacingMs reads together with fetchMode: cold-fill bursts
// legitimately reach ~250 ms, steady state stays >=1000 ms).
ambientCards: {
count: layerState._cardIds.size,
limit: CCTV_AMBIENT_CARD_MAX,
frameFetches: layerState._cardFetchCount,
minFrameFetchSpacingMs: layerState._cardMinFetchSpacingMs,
fetchMode: layerState._cardFetchMode,
fetchesInFlight: layerState._cardFetchInFlightCount,
// Item B QA seam: the hover-summoned pinned card, if any.
hoverId: layerState._hoverCardId,
},
activeCameraId: activeId,
activeCameraReselection: layerState._activeCameraReselection,
activeCamera: active ? getPublicCameraState(active, activeId) : null,
cameraIndex: cameraIndex(),
summary: buildSummaryText(),
};
// The full per-camera state is built only when a subscriber reads it: a
// catalog of tens of thousands would otherwise be rebuilt on every
// progress tick for listeners that only want the active camera. It reads
// the records live at that moment, and spreading or serializing the
// payload builds it, so callers that want a count use `count`.
let cameras = null;
Object.defineProperty(payload, 'cameras', {
enumerable: true,
get() {
cameras ??= layerState._records.map((record) =>
getPublicCameraState(record, activeId),
);
return cameras;
},
});
return payload;
}
/**
* `{ 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._pickerRecords;
const active = parts.selection.getActiveRecord();
const cached = layerState._cameraIndexCache;
if (cached?.view === view && cached.active === active) return cached.list;
const records = active
? [active, ...view.filter((record) => record !== active)]
: view;
const list = records.map(({ camera }) => ({
id: camera.id,
city: camera.city,
name: camera.name,
}));
layerState._cameraIndexCache = { view, active, list };
return list;
}
/** Dispatches the current UI state to all registered subscriber callbacks. */
function notifyListeners() {
const payload = uiState();
for (const callback of layerState._listeners) {
try {
callback(payload);
} catch (error) {
console.warn('[Data:CCTV] listener error:', error);
}
}
}
/**
* Throttled notifyListeners for transient (mid-drag) calibration patches —
* the panel re-render is DOM-heavy, so live gizmo drags publish state at
* ≤10 Hz while the in-world geometry still tracks every processed move.
*/
function notifyListenersThrottled() {
const now = Date.now();
if (now - layerState._lastTransientNotifyAt < 100) return;
layerState._lastTransientNotifyAt = now;
notifyListeners();
}
return {
buildSummaryText,
getPublicCameraState,
uiState,
notifyListeners,
notifyListenersThrottled,
};
}