Merge main and resolve the CCTV batch conflicts

Main released #1228 and #1233 and deleted their changelog fragments, so they
stay deleted here. Main also rewrote the tracking arrival probe in
scripts/track-regression.mjs, which supersedes this branch's version; main's
file is kept unchanged.
This commit is contained in:
German Khokhlov committed 2026-11-19 17:56:23 +04:00
commit d7db1090fd
4343 files changed
+644447 -86370

No files matched your search

@@ -7,6 +7,7 @@ import { layerNameForId, localizeLayerName } from '../../ui/layerNames.js';
import { LayerPanel } from '../../ui/layerPanel.js';
import { translateFeedError } from '../../ui/statusText.js';
import { createAirQualityLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function inLocale(locale, run) {
setLocale(locale);
@@ -22,7 +23,8 @@ function harness(source) {
source,
overlayHost: { setEntries() {}, setVisible() {}, clearSource() {} },
});
const viewer = { dataSources: { add() {}, remove() {} } };
const viewer = {};
bindFakeDraw(viewer);
layer.init(viewer);
layer.enable(viewer);
return layer;
+59 -62
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { cssColor } from '../../render/color.js';
import { drawOf, findCamera } from '../../render/rendererOf.js';
import { msg, t, tn } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js';
import {
@@ -22,6 +24,15 @@ const STATION_MARKER_RADIUS_M = 6_000;
/** Readings listed in the readout card. */
const READOUT_LIMIT = 5;
export const AIR_QUALITY_MARKER_SET_ID = 'air-quality';
let instances = 0;
/** A reading's colour at `alpha`; an unreadable colour falls back to white. */
function withAlpha(css, alpha) {
const [r, g, b] = cssColor(css) ?? [1, 1, 1];
return [r, g, b, alpha];
}
/** Own one air-quality display, its refresh lifecycle, and its readout card. */
export function createAirQualityLayer({ source, overlayHost } = {}) {
if (typeof source?.getSnapshot !== 'function')
@@ -29,7 +40,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
if (!overlayHost) throw new TypeError('Air quality requires an overlay host');
let _viewer = null;
let _request = null;
let _dataSource = null;
let _markers = null;
let _readings = [];
let _count = 0;
let _lastUpdate = null;
@@ -40,17 +51,8 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
const notify = () => rowControlsListener?.();
/** The camera's lon/lat rectangle in degrees, or null when unresolvable. */
const viewRectangle = () => {
const rectangle = _viewer?.camera?.computeViewRectangle?.();
if (!rectangle) return null;
const toDeg = Cesium.Math.toDegrees;
return {
west: toDeg(rectangle.west),
south: toDeg(rectangle.south),
east: toDeg(rectangle.east),
north: toDeg(rectangle.north),
};
};
const viewRectangle = () =>
_viewer ? (findCamera(_viewer)?.viewRectangle() ?? null) : null;
const layer = {
id: 'air-quality',
@@ -61,10 +63,11 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
init(viewer) {
if (_viewer) throw new Error('Air quality layer is already initialized');
_markers = drawOf(viewer).shapes({
id: `${AIR_QUALITY_MARKER_SET_ID}:${++instances}`,
show: false,
});
_viewer = viewer;
_dataSource = new Cesium.CustomDataSource('air-quality');
_dataSource.show = false;
viewer.dataSources.add(_dataSource);
_readings = [];
_count = 0;
_lastUpdate = null;
@@ -75,7 +78,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
enable() {
_enabled = true;
if (_dataSource) _dataSource.show = true;
if (_markers) _markers.show = true;
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, true);
notify();
},
@@ -85,14 +88,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
_request?.abort();
_request = null;
_enabled = false;
if (_dataSource) _dataSource.show = false;
if (_markers) _markers.show = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
notify();
},
async update() {
if (!_enabled || !_dataSource) return false;
if (!_enabled || !_markers) return false;
_request?.abort();
const request = new AbortController();
_request = request;
@@ -120,47 +123,42 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
/** Rebuild entities and overlay labels from the current readings. */
/** Redraw the station markers and overlay labels from the current readings. */
_render() {
if (!_dataSource) return;
_dataSource.entities.removeAll();
if (!_markers) return;
const markers = [];
const overlayEntries = [];
for (const reading of _readings) {
const position = Cesium.Cartesian3.fromDegrees(
reading.lon,
reading.lat,
);
const color = Cesium.Color.fromCssColorString(reading.color);
_dataSource.entities.add(
new Cesium.Entity({
id: `air-quality:${reading.id}`,
position,
ellipse: {
// Static axes, as in the earthquake layer: a per-frame axis
// re-tessellates the clamped ground primitive every frame.
semiMajorAxis: STATION_MARKER_RADIUS_M,
semiMinorAxis: STATION_MARKER_RADIUS_M,
material: new Cesium.ColorMaterialProperty(color.withAlpha(0.35)),
outline: true,
outlineColor: color.withAlpha(0.9),
outlineWidth: 2,
heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
},
properties: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
}),
);
const position = fromDegrees(reading.lon, reading.lat);
// A filled disc on the ground with static axes, as in the earthquake
// layer: a per-frame axis re-tessellates clamped ground geometry
// every frame. No outline: clamped to the ground, the default
// renderer never drew one.
markers.push({
id: `air-quality:${reading.id}`,
geometry: {
kind: 'ellipse',
center: { lon: reading.lon, lat: reading.lat },
semiMajor: STATION_MARKER_RADIUS_M,
semiMinor: STATION_MARKER_RADIUS_M,
},
fill: withAlpha(reading.color, 0.35),
height: 'clampGround',
clampTo: 'both',
meta: {
provider: reading.provider,
scale: reading.scale,
value: reading.value,
band: reading.band,
name: reading.name,
zone: reading.zone,
risk: reading.risk,
observedMs: reading.observedMs,
note: reading.note,
lat: reading.lat,
lon: reading.lon,
},
});
overlayEntries.push(
createAirQualityOverlayEntry({
id: reading.id,
@@ -171,6 +169,7 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}),
);
}
_markers.set(markers);
if (_enabled) {
overlayHost.setEntries(
AIR_QUALITY_OVERLAY_SOURCE_ID,
@@ -184,16 +183,14 @@ export function createAirQualityLayer({ source, overlayHost } = {}) {
}
},
destroy(viewer = _viewer) {
destroy() {
_request?.abort();
_request = null;
_enabled = false;
overlayHost.clearSource(AIR_QUALITY_OVERLAY_SOURCE_ID);
overlayHost.setVisible(AIR_QUALITY_OVERLAY_SOURCE_ID, false);
if (_dataSource) {
viewer?.dataSources?.remove(_dataSource, true);
_dataSource = null;
}
_markers?.dispose();
_markers = null;
_viewer = null;
_readings = [];
_count = 0;
+66 -17
View File
@@ -3,20 +3,12 @@ import test from 'node:test';
import { createAirQualityLayer } from './index.js';
import { layerFeedState } from '../../data/feedState.js';
import { STALE_AFTER_MS } from './model.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
function harness(source) {
const sources = [];
function harness(source, renderer = {}) {
const events = [];
const viewer = {
dataSources: {
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
},
},
};
const viewer = {};
const { draw } = bindFakeDraw(viewer, renderer);
const layer = createAirQualityLayer({
source,
overlayHost: {
@@ -29,7 +21,8 @@ function harness(source) {
});
layer.init(viewer);
layer.enable(viewer);
return { layer, viewer, sources, events };
const markers = () => draw.find('air-quality:');
return { layer, viewer, draw, markers, events };
}
const reading = (id, value, overrides = {}) => ({
@@ -61,12 +54,68 @@ test('a layer requires both a snapshot source and an overlay host', () => {
);
});
test('initialization is single-use and owns exactly one data source', () => {
const { layer, viewer, sources } = harness(staticSource([]));
assert.equal(sources.length, 1);
test('initialization is single-use and owns exactly one draw set', () => {
const { layer, viewer, draw, markers } = harness(staticSource([]));
const owned = markers();
assert.equal(owned.kind, 'shapes');
assert.equal(
[...draw.sets.values()].filter((set) => !set.disposed).length,
1,
);
assert.throws(() => layer.init(viewer), /already initialized/);
layer.destroy(viewer);
assert.equal(sources.length, 0);
assert.equal(owned.disposed, true);
});
test('stations are ground discs in their band colour, shown only while enabled', async () => {
const { layer, markers } = harness(
staticSource([reading('A', 2), reading('B', 7, { color: '#c1121f' })]),
);
assert.equal(await layer.update(), true);
const set = markers();
assert.equal(set.show, true);
assert.deepEqual(
[...set.items.keys()],
['air-quality:eccc:A', 'air-quality:eccc:B'],
);
const disc = set.items.get('air-quality:eccc:B');
assert.deepEqual(disc.geometry, {
kind: 'ellipse',
center: { lon: -79.38, lat: 43.65 },
semiMajor: 6_000,
semiMinor: 6_000,
});
assert.equal(disc.height, 'clampGround');
assert.equal(disc.clampTo, 'both');
assert.deepEqual(disc.fill, [0xc1 / 255, 0x12 / 255, 0x1f / 255, 0.35]);
assert.equal(disc.outline, undefined);
assert.equal(disc.meta.name, 'B');
assert.equal(disc.meta.value, 7);
layer.disable();
assert.equal(set.show, false);
layer.enable();
assert.equal(set.show, true);
assert.equal(await layer.update(), true);
assert.equal(set.items.size, 2, 'a refresh replaces, not appends');
});
test('the readout lists only readings inside the camera port view rectangle', async () => {
const { layer } = harness(
staticSource([
reading('Toronto', 2),
reading('Vancouver', 4, { lat: 49.28, lon: -123.12 }),
]),
{
camera: {
viewRectangle: () => ({ west: -90, south: 40, east: -70, north: 50 }),
},
},
);
await layer.update();
assert.deepEqual(
layer.getRowControls().list.items.map((item) => item.text),
['Toronto · Low health risk'],
);
});
test('a refresh renders readings and publishes an overlay cohort', async () => {
-1
View File
@@ -14,5 +14,4 @@ export * from '../../data/modelVisualAnchor.js';
export * from '../../data/motionModel.js';
export * from '../../data/renderAltitude.js';
export * from '../../data/routePlausible.js';
export * from '../../data/trackedModelRegime.js';
export * from '../../data/trackingClickGesture.js';
+34 -48
View File
@@ -1,25 +1,25 @@
import { isFollowing } from '../../data/followed.js';
import { isUnavailableCapability } from '../../sources/capability.js';
import * as Cesium from 'cesium';
import { cameraOf, drawOf, findFrame } from '../../render/rendererOf.js';
import {
LAYER_ID,
REQUEST_DEBOUNCE_MS,
QUERY_LIMIT,
MAX_RENDERED,
QUERY_SNAP_DEGREES,
QUERY_REUSE_MS,
ALPR_COLOR,
} from './policy.js';
import {
snapAlprBox,
boxContains,
destinationPointDeg,
alprRetryDelayMs,
validateAlprSnapshot,
alprCreditMarkup,
alprCredit,
} from './model.js';
import { createAlprPresentation } from './presentation.js';
import { createAlprMarkerSet } from './markerState.js';
import { t, tn, msg } from '../../i18n/index.js';
let instances = 0;
/**
* Own one layer's requests, records, display and viewer subscriptions.
* A source fetches a bounded box with an AbortSignal and resolves
@@ -43,10 +43,12 @@ export function createAlprCamerasLayer({ source, services } = {}) {
const state = {
viewer: null,
dataSource: null,
/** The camera markers, drawn as one icon set. */
markers: createAlprMarkerSet(),
credit: null,
creditTimer: null,
creditPresented: false,
creditOff: null,
enabled: false,
records: [],
recordById: new Map(),
@@ -67,7 +69,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
moveEndRemove: null,
postRenderRemove: null,
lastAnchorSampleAt: 0,
clickHandler: null,
clickSubscription: null,
debounceTimer: null,
/** Snapped box of the last successful query; a view still inside it reuses its records. */
lastQueryBox: null,
@@ -84,9 +86,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
viewportBox,
clearRendered,
hideOnMapCredit,
presentOnMapCredit,
renderRecords,
selectRecord,
focusNearest,
clearSelection,
updateSelectedAnchor,
@@ -188,9 +188,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
}
renderRecords();
state.retrying = false;
setAlprStatus(
state.dataSource.entities.values.length ? 'ready' : 'empty',
);
setAlprStatus(state.markers.size ? 'ready' : 'empty');
return;
}
// A move inside an in-flight query must not abort and restart that query.
@@ -258,13 +256,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
// Stale and saturated are independent facts; a cached response that also
// hit the cap must still warn about coverage, not just about freshness.
renderRecords();
setAlprStatus(
state.dataSource.entities.values.length
? stale
? 'stale'
: 'ready'
: 'empty',
);
setAlprStatus(state.markers.size ? (stale ? 'stale' : 'ready') : 'empty');
} catch (error) {
if (
error?.name === 'AbortError' ||
@@ -301,16 +293,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
init(viewer) {
if (state.viewer) throw new Error('ALPR layer is already initialized');
state.viewer = viewer;
state.dataSource = new Cesium.CustomDataSource('alpr-cameras');
const creditMarkup = alprCreditMarkup(source.attribution);
state.credit = creditMarkup
? new Cesium.Credit(creditMarkup, true)
: null;
viewer.dataSources.add(state.dataSource);
state.moveEndRemove =
viewer.camera.moveEnd.addEventListener(scheduleLoad);
state.markers.attach(
drawOf(viewer).icons({
id: `${LAYER_ID}:${++instances}:markers`,
show: state.enabled,
}),
);
state.credit = alprCredit(source.attribution);
state.moveEndRemove = cameraOf(viewer).on('moveEnd', scheduleLoad);
state.postRenderRemove =
viewer.scene.postRender?.addEventListener(updateSelectedAnchor);
findFrame(viewer)?.on('postRender', () => updateSelectedAnchor()) ??
null;
initOverlay();
installInteraction(viewer);
},
@@ -319,7 +312,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.enabled = true;
state.creditPresented = false;
registerPickOwner(LAYER_ID, (id) => state.recordById.has(id));
state.dataSource.show = true;
state.markers.icons.show = true;
// DataLayerManager calls update() right after enable(); it owns the first fetch.
},
disable() {
@@ -333,7 +326,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.pendingQueryBox = null;
state.loading = false;
state.retrying = false;
if (state.dataSource) state.dataSource.show = false;
if (state.markers.icons) state.markers.icons.show = false;
clearSelection();
clearRendered();
setAlprStatus('idle');
@@ -349,12 +342,10 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.moveEndRemove = null;
state.postRenderRemove?.();
state.postRenderRemove = null;
state.clickHandler?.destroy();
state.clickHandler = null;
state.clickSubscription?.();
state.clickSubscription = null;
clearRendered();
if (state.dataSource && viewer)
viewer.dataSources.remove(state.dataSource, true);
state.dataSource = null;
state.markers.dispose();
state.credit = null;
state.creditPresented = false;
state.records = [];
@@ -369,19 +360,18 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.viewer = null;
},
getRowControls() {
const count = state.dataSource?.entities.values.length || 0;
const count = state.markers.size;
return {
chips: [
{
id: 'find-camera',
label: t('SHOW NEAREST'),
title: state.viewer?.trackedEntity
title: isFollowing(state.viewer)
? t(
'Stop following the current object before navigating to a camera',
)
: t('Move to the nearest loaded camera and show its details'),
disabled:
!state.enabled || !count || Boolean(state.viewer?.trackedEntity),
disabled: !state.enabled || !count || isFollowing(state.viewer),
onClick: focusNearest,
},
],
@@ -430,21 +420,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
},
getStats() {
return {
count: state.dataSource?.entities.values.length || 0,
count: state.markers.size,
countLabel:
state.enabled && !state.noCoverage && state.status !== 'zoom-in'
? Number.isInteger(state.onScreen)
? tn(
state.dataSource?.entities.values.length || 0,
state.markers.size,
'{count} nearby · {onScreen} on screen',
'{count} nearby · {onScreen} on screen',
{ onScreen: state.onScreen },
)
: tn(
state.dataSource?.entities.values.length || 0,
'{count} nearby',
'{count} nearby',
)
: tn(state.markers.size, '{count} nearby', '{count} nearby')
: '',
noCoverage: Boolean(state.noCoverage),
lastUpdate: state.lastUpdate,
@@ -452,7 +438,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
saturated: state.saturated || state.renderSaturated,
renderRevision: state.renderRevision,
onScreen: state.onScreen ?? null,
shown: state.dataSource?.entities.values.length || 0,
shown: state.markers.size,
error: state.error,
status: state.status,
loading: state.loading,
+175
View File
@@ -0,0 +1,175 @@
/**
* @module alpr/markerState
* @description The ALPR layer's markers: one icon per camera in a draw set,
* and the layer's own per-marker state, held in the layer. Each marker is a
* plain carrier object (`{ id, show }`) that the layer registers as the
* camera's context entity; its state lives in `alprMarkers`:
* - `record`: the camera record the marker shows.
* - `position`, `clamped`: where the badge is drawn natively, and whether it
* follows the ground there rather than sitting at its height.
* - `selected`: drawn with the selected badge.
* - `canvasPosition`, `displayPosition`: the canvas anchor and the position the card reads.
* - `wedge`: the direction wedge's positions, plain ECEF.
* - `canvasOwned`: the overlay canvas draws the badge; the icon stays as a
* faint pick target at the canvas anchor.
* - `shown`, `surfaceCheckedFor`: whether the icon shows and the anchor last checked.
*/
import { createEntityStore } from '../../data/entityRecords.js';
import {
MARKER_ICON_SIZE,
MARKER_SCALE_BY_DISTANCE,
SELECTED_MARKER_ICON_SIZE,
} from './policy.js';
import { MARKER_IMAGE, SELECTED_IMAGE } from './visuals.js';
export const alprMarkers = createEntityStore();
const [NEAR, NEAR_SCALE, FAR, FAR_SCALE] = MARKER_SCALE_BY_DISTANCE;
/** City-wide views hold hundreds of badges; they shrink with distance. */
const SCALE_BY_DISTANCE = Object.freeze({
near: NEAR,
nearValue: NEAR_SCALE,
far: FAR,
farValue: FAR_SCALE,
});
/** Under the canvas badge: faint, but still picked. */
const PICK_TARGET_COLOR = Object.freeze([1, 1, 1, 0.01]);
/**
* Where a marker's icon is drawn: the canvas anchor while the canvas owns
* it, else its native position.
* @param {{id: string}} carrier
* @returns {import('../../render/contract/common').Ecef|null|undefined}
*/
export function alprIconPosition(carrier) {
const marker = alprMarkers.read(carrier);
if (!marker) return null;
return marker.canvasOwned && marker.canvasPosition
? marker.canvasPosition
: marker.position;
}
/**
* The icon a marker draws now.
* @param {{id: string}} carrier
* @returns {import('../../render/contract/draw').IconItem}
*/
export function alprIconItem(carrier) {
const marker = alprMarkers.read(carrier) ?? {};
const canvas = Boolean(marker.canvasOwned && marker.canvasPosition);
const size = marker.selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE;
return {
id: carrier.id,
pos: canvas ? marker.canvasPosition : marker.position,
// Ground clamping is the placeholder until a marker's floor resolves.
height: !canvas && marker.clamped ? 'clampGround' : 'absolute',
image: marker.selected ? SELECTED_IMAGE : MARKER_IMAGE,
size: [size, size],
disableDepthTest: Number.POSITIVE_INFINITY,
show: marker.shown !== false,
// The context carrier: what a pick hands to point-and-ask.
meta: carrier,
...(canvas
? { color: PICK_TARGET_COLOR }
: { scaleByDistance: SCALE_BY_DISTANCE }),
};
}
/** What tells one drawn icon from another, so unchanged ones are not sent again. */
function itemKey(item) {
const { pos } = item;
return [
pos?.x,
pos?.y,
pos?.z,
item.height,
item.image,
item.size[0],
item.show,
item.color ? 'pick' : 'badge',
].join('|');
}
/**
* The layer's markers, drawn as one icon set: carriers by camera id, and
* the writes to the set, batched until `flush`.
* @returns {object}
*/
export function createAlprMarkerSet() {
const carriers = new Map();
/** The key of each icon last sent to the set, by id. */
const sent = new Map();
const dirty = new Set();
let icons = null;
function flush() {
if (!icons || !dirty.size) return;
const items = [];
for (const carrier of dirty) {
if (carriers.get(carrier.id) !== carrier) continue;
const item = alprIconItem(carrier);
if (!item.pos) continue;
const key = itemKey(item);
if (sent.get(carrier.id) === key) continue;
sent.set(carrier.id, key);
items.push(item);
}
dirty.clear();
if (items.length) icons.upsert(items);
}
return {
/** Draw the markers into `set`, an icon set made for them. */
attach(set) {
icons = set;
},
/** The icon set, while attached. */
get icons() {
return icons;
},
get size() {
return carriers.size;
},
get(id) {
return carriers.get(id) ?? null;
},
values() {
return carriers.values();
},
/** A new marker for `id`, drawn at the next `flush`. */
add(id) {
const carrier = { id, show: true };
carriers.set(id, carrier);
dirty.add(carrier);
return carrier;
},
/** Remove the markers with these ids now. */
remove(ids) {
const gone = [];
for (const id of ids) {
if (!carriers.delete(id)) continue;
sent.delete(id);
gone.push(id);
}
if (gone.length) icons?.remove(gone);
},
/** Redraw `carrier` at the next `flush`, if how it draws changed. */
changed(carrier) {
if (carrier) dirty.add(carrier);
},
flush,
clear() {
carriers.clear();
sent.clear();
dirty.clear();
icons?.clear();
},
dispose() {
carriers.clear();
sent.clear();
dirty.clear();
icons?.dispose();
icons = null;
},
};
}
+13 -21
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { toDegrees, toRadians } from '../../geo/index.js';
import { EARTH_MEAN_RADIUS_M } from './policy.js';
export * from './records.js';
@@ -12,9 +12,9 @@ export * from './records.js';
*/
export function destinationPointDeg(latDeg, lonDeg, bearingDeg, distanceM) {
const angularDistance = distanceM / EARTH_MEAN_RADIUS_M;
const bearing = Cesium.Math.toRadians(bearingDeg);
const lat1 = Cesium.Math.toRadians(latDeg);
const lon1 = Cesium.Math.toRadians(lonDeg);
const bearing = toRadians(bearingDeg);
const lat1 = toRadians(latDeg);
const lon1 = toRadians(lonDeg);
const lat2 = Math.asin(
Math.sin(lat1) * Math.cos(angularDistance) +
Math.cos(lat1) * Math.sin(angularDistance) * Math.cos(bearing),
@@ -26,29 +26,21 @@ export function destinationPointDeg(latDeg, lonDeg, bearingDeg, distanceM) {
Math.cos(angularDistance) - Math.sin(lat1) * Math.sin(lat2),
);
return {
latitude: Cesium.Math.toDegrees(lat2),
longitude: Cesium.Math.toDegrees(lon2),
latitude: toDegrees(lat2),
longitude: toDegrees(lon2),
};
}
/** Build a linked attribution from plain text and an HTTPS URL only. */
export function alprCreditMarkup(attribution) {
/**
* The on-map credit for the renderer's credits port, from plain text and an
* HTTPS URL only; the port escapes it as it shows it.
* @returns {{text: string, href: string, inline: true}|null}
*/
export function alprCredit(attribution) {
if (!attribution?.text || !attribution?.href) return null;
const href = new URL(attribution.href);
if (href.protocol !== 'https:' || href.username || href.password) {
throw new TypeError('Camera attribution requires a public HTTPS link');
}
const escape = (value) =>
String(value).replace(
/[&<>"']/g,
(char) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
'"': '&quot;',
"'": '&#39;',
})[char],
);
return `<span class="gev-alpr-credit">ALPR: <a href="${escape(href.href)}" target="_blank" rel="noopener">${escape(attribution.text)}</a></span>`;
return { text: `ALPR: ${attribution.text}`, href: href.href, inline: true };
}
+145 -163
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
MAX_CANVAS_FRUSTUMS,
MARKER_ICON_SIZE,
@@ -18,8 +17,19 @@ import {
paintDirectionWedge,
validAlprGroundHeight,
} from './visuals.js';
import { alprMarkers } from './markerState.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import { cameraOf, findQuery, rendererOf } from '../../render/rendererOf.js';
/** Per-layer presentation on a caller-owned overlay; Cesium remains the fallback. */
let lanes = 0;
/** Within `epsilon` on every axis. */
const near = (a, b, epsilon) =>
Math.abs(a.x - b.x) <= epsilon &&
Math.abs(a.y - b.y) <= epsilon &&
Math.abs(a.z - b.z) <= epsilon;
/** Per-layer presentation on a caller-owned overlay; the icon set remains the fallback. */
export function createAlprOverlay({
state,
services,
@@ -38,72 +48,55 @@ export function createAlprOverlay({
if (!destroyed && state.enabled) lane?.requestPaint();
};
function nativeVisible(entity, visible) {
if (!entity) return;
canvasOwned(entity, !visible);
setShown(entity, visible);
const markers = state.markers;
function nativeVisible(carrier, visible) {
if (!carrier) return;
canvasOwned(carrier, !visible);
setShown(carrier, visible);
}
/** Swap a marker between its native look and a faint canvas pick target. */
function canvasOwned(entity, owned) {
const visible = !owned;
const billboard = entity.billboard;
// Keep a faint native pick target under the canvas badge so sibling layer
// handlers recognize ALPR ownership instead of treating the click as empty.
if (!visible && !entity.gevAlprNativeAppearance) {
entity.gevAlprNativeAppearance = {
position: entity.position,
heightReference: billboard.heightReference,
scaleByDistance: billboard.scaleByDistance,
color: billboard.color,
};
entity.position = entity.gevAlprCanvasPosition;
entity.gevAlprPickPosition = entity.position;
billboard.heightReference = Cesium.HeightReference.NONE;
billboard.scaleByDistance = undefined;
billboard.color = Cesium.Color.WHITE.withAlpha(0.01);
} else if (visible && entity.gevAlprNativeAppearance) {
const saved = entity.gevAlprNativeAppearance;
if (entity.position === entity.gevAlprPickPosition)
entity.position = saved.position;
billboard.heightReference = saved.heightReference;
billboard.scaleByDistance = saved.scaleByDistance;
billboard.color = saved.color;
entity.gevAlprNativeAppearance = null;
entity.gevAlprPickPosition = null;
}
/**
* Swap a marker between its native look and a faint canvas pick target.
* The faint icon stays under the canvas badge, at its anchor, so sibling
* layer handlers recognize ALPR ownership instead of treating the click
* as empty.
*/
function canvasOwned(carrier, owned) {
const marker = alprMarkers.write(carrier);
if (Boolean(marker.canvasOwned) === owned) return;
marker.canvasOwned = owned;
markers.changed(carrier);
}
// Assign only on change: each Entity property write mints a new property
// and raises definitionChanged, which paint used to do for every overlay
// camera on every frame.
function setShown(entity, visible) {
if (entity.gevAlprShown === visible) return;
entity.gevAlprShown = visible;
entity.billboard.show = visible;
if (entity.polyline) entity.polyline.show = visible;
if (entity.polygon) entity.polygon.show = visible;
// Changed only on change: the icon is sent again only when it draws
// differently.
function setShown(carrier, visible) {
const marker = alprMarkers.write(carrier);
if ((marker.shown ?? true) === visible) return;
marker.shown = visible;
markers.changed(carrier);
}
function resetAnchors() {
for (const entity of state.dataSource.entities.values) {
entity.gevAlprCanvasPosition = null;
entity.gevAlprWedge = null;
entity.gevAlprDisplayPosition = null;
nativeVisible(entity, true);
for (const carrier of markers.values()) {
const marker = alprMarkers.write(carrier);
marker.canvasPosition = null;
marker.wedge = null;
marker.displayPosition = null;
nativeVisible(carrier, true);
}
markers.flush();
state.lastAnchorSampleAt = 0;
retryUntil = Date.now() + 15000;
requestPaint();
}
function anchorFor(record, entity, budget) {
if (entity.gevAlprCanvasPosition) return entity.gevAlprCanvasPosition;
const scene = state.viewer.scene;
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
function anchorFor(record, carrier, budget) {
const cached = alprMarkers.read(carrier)?.canvasPosition;
if (cached) return cached;
const query = findQuery(state.viewer);
const point = { lon: record.longitude, lat: record.latitude };
// A floor-placed marker anchors where its native badge sits; only a
// marker still waiting for its floor samples the rendered surface, and
// each paint samples a few at most (each sample is a depth render).
@@ -113,20 +106,34 @@ export function createAlprOverlay({
record.longitude,
);
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
else if (scene.sampleHeightSupported) {
else if (query && canSampleHeight()) {
if (budget.samples <= 0) return null;
budget.samples -= 1;
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* streaming tiles */
}
// A miss is tiles still streaming.
height = query.sampleHeightNow(point, { exclude: [markers.icons?.id] });
}
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
// The globe's terrain, while the globe is drawn (hidden under photoreal
// tiles, its height is not what shows).
if (!validAlprGroundHeight(height) && globeShown())
height = query?.sampleHeightNow(point, { against: 'terrain' });
if (!validAlprGroundHeight(height)) return null;
setAnchor(record, entity, height);
return entity.gevAlprCanvasPosition;
setAnchor(record, carrier, height);
return alprMarkers.read(carrier)?.canvasPosition;
}
/**
* Whether the renderer samples the drawn surface's height (Cesium needs
* depth textures). Without, nothing is sampled or spent from the budget,
* and a marker with no floor yet anchors on the terrain.
*/
function canSampleHeight() {
const capabilities = rendererOf(state.viewer)?.capabilities;
return !capabilities || capabilities.has('sampleHeight');
}
/** Whether the globe surface is drawn; true where the renderer cannot say. */
function globeShown() {
return rendererOf(state.viewer)?.globe?.isGlobeVisible?.() !== false;
}
function floorHeightAt(latitude, longitude) {
@@ -134,27 +141,24 @@ export function createAlprOverlay({
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
}
function setAnchor(record, entity, height) {
entity.gevAlprCanvasPosition = Cesium.Cartesian3.fromDegrees(
function setAnchor(record, carrier, height) {
const marker = alprMarkers.write(carrier);
marker.canvasPosition = fromDegrees(
record.longitude,
record.latitude,
height,
);
entity.gevAlprWedge = directionWedgePositions(
record,
height,
floorHeightAt,
);
marker.wedge = directionWedgePositions(record, height, floorHeightAt);
if (marker.canvasOwned) markers.changed(carrier);
}
/** Whether the visible photoreal tiles (or globe) have finished streaming. */
function surfaceSettled(scene) {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false;
for (let i = 0; i < (scene.primitives?.length || 0); i++) {
const primitive = scene.primitives.get(i);
if (primitive?.show && primitive.tilesLoaded === false) return false;
}
return true;
function surfaceSettled() {
const globe = rendererOf(state.viewer)?.globe;
// The globe's terrain while it is shown, otherwise the shown 3D tiles.
// A viewer with no renderer of its own cannot say; its samples are
// still checked against the floor.
return !globe || globe.isSettled('surface');
}
/**
@@ -165,50 +169,34 @@ export function createAlprOverlay({
* samples far outside the floor prior (a roof or a streaming tile) are
* rejected. Returns whether anchors remain to check.
*/
function refineAnchors(budget) {
const camera = state.viewer.camera;
const scene = state.viewer.scene;
function refineAnchors(budget, pose) {
const still =
lastCamera &&
camera.positionWC &&
Cesium.Cartesian3.equalsEpsilon(
camera.positionWC,
lastCamera.position,
0,
0.05,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastCamera.direction,
0,
1e-6,
);
if (camera.positionWC && camera.directionWC)
lastCamera = {
position: Cesium.Cartesian3.clone(camera.positionWC),
direction: Cesium.Cartesian3.clone(camera.directionWC),
};
if (!scene.sampleHeightSupported) return false;
near(pose.position, lastCamera.position, 0.05) &&
near(pose.direction, lastCamera.direction, 1e-6);
lastCamera = {
position: { ...pose.position },
direction: { ...pose.direction },
};
const query = findQuery(state.viewer);
if (!query || !canSampleHeight()) return false;
let pending = false;
for (const record of records) {
const entity = state.dataSource.entities.getById(record.id);
const anchor = entity?.gevAlprCanvasPosition;
if (!anchor || entity.gevAlprSurfaceCheckedFor === anchor) continue;
if (!still || !surfaceSettled(scene) || budget.samples <= 0) {
const carrier = markers.get(record.id);
const marker = alprMarkers.read(carrier);
const anchor = marker?.canvasPosition;
if (!anchor || marker.surfaceCheckedFor === anchor) continue;
if (!still || !surfaceSettled() || budget.samples <= 0) {
pending = true;
continue;
}
budget.samples -= 1;
let sample;
try {
sample = scene.sampleHeight(
Cesium.Cartographic.fromDegrees(record.longitude, record.latitude),
[entity],
);
} catch {
/* streaming tiles */
}
const current = Cesium.Cartographic.fromCartesian(anchor).height;
// A miss is tiles still streaming.
const sample = query.sampleHeightNow(
{ lon: record.longitude, lat: record.latitude },
{ exclude: [markers.icons?.id] },
);
const current = toLonLatH(anchor)?.height;
const floor = services.groundFloor.cachedGroundFloor(
record.latitude,
record.longitude,
@@ -219,10 +207,11 @@ export function createAlprOverlay({
(sample >= floor - SURFACE_BELOW_FLOOR_M &&
sample <= floor + SURFACE_ABOVE_FLOOR_M));
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M);
entity.gevAlprSurfaceCheckedFor = entity.gevAlprCanvasPosition;
if (entity.id === state.selectedId)
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
setAnchor(record, carrier, sample + MARKER_FLOOR_LIFT_M);
// setAnchor rewrote the same record, so this is the new anchor.
marker.surfaceCheckedFor = marker.canvasPosition;
if (carrier.id === state.selectedId)
marker.displayPosition = marker.canvasPosition;
}
return pending;
}
@@ -233,9 +222,11 @@ export function createAlprOverlay({
let unresolved = false;
const painted = [];
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
const pose = cameraOf(state.viewer).pose();
const query = findQuery(state.viewer);
for (const record of records) {
const entity = state.dataSource.entities.getById(record.id);
if (!entity) continue;
const carrier = markers.get(record.id);
if (!carrier) continue;
const selected = record.id === state.selectedId;
const image = images[selected ? 1 : 0];
if (
@@ -243,45 +234,35 @@ export function createAlprOverlay({
!image.naturalWidth ||
(selected && !images[2]?.naturalWidth)
) {
nativeVisible(entity, true);
nativeVisible(carrier, true);
continue;
}
const anchor = anchorFor(record, entity, budget);
const anchor = anchorFor(record, carrier, budget);
if (!anchor) {
nativeVisible(entity, true);
nativeVisible(carrier, true);
unresolved = true;
continue;
}
canvasOwned(entity, true);
canvasOwned(carrier, true);
if (occluder && !occluder.isPointVisible(anchor)) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const scene = state.viewer.scene;
const origin = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
anchor,
);
const origin = query?.project(anchor);
if (!origin) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const alpha =
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
if (!(alpha > 0)) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
const wedge = entity.gevAlprWedge;
const wedge = alprMarkers.read(carrier)?.wedge;
if (wedge) {
const left = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
wedge[1],
);
const right = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
wedge[2],
);
const left = query.project(wedge[1]);
const right = query.project(wedge[2]);
if (left && right) {
ctx.save();
ctx.globalAlpha *= alpha;
@@ -295,21 +276,19 @@ export function createAlprOverlay({
origin.y < -60 ||
origin.y > height + 60
) {
setShown(entity, false);
setShown(carrier, false);
continue;
}
setShown(entity, true);
setShown(carrier, true);
painted.push({
record,
origin,
selected,
image,
alpha,
scale: markerScale(
Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor),
),
scale: markerScale(distance(pose.position, anchor)),
});
if (selected) entity.gevAlprDisplayPosition = anchor;
if (selected) alprMarkers.write(carrier).displayPosition = anchor;
}
// Paint all glyphs after the wedges so one camera's cone cannot wash out another.
for (const { record, origin, selected, image, alpha, scale } of painted) {
@@ -335,9 +314,11 @@ export function createAlprOverlay({
ctx.restore();
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
}
const refining = refineAnchors({
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT),
});
const refining = refineAnchors(
{ samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT) },
pose,
);
markers.flush();
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
retryTimer = setTimeout(() => {
retryTimer = null;
@@ -358,7 +339,7 @@ export function createAlprOverlay({
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
return;
lane = services.overlays.registerPaintLane('selected', paint, {
id: `alpr-${Cesium.createGuid()}`,
id: `alpr-${++lanes}`,
active: false,
});
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
@@ -371,9 +352,8 @@ export function createAlprOverlay({
},
sync(visible) {
if (!lane) return;
for (const record of records)
nativeVisible(state.dataSource.entities.getById(record.id), true);
const position = state.viewer.camera.positionWC;
const previous = records;
const position = cameraOf(state.viewer).pose().position;
records = visible
.filter(
(record) =>
@@ -383,13 +363,10 @@ export function createAlprOverlay({
.map((record) => ({
record,
distance: position
? Cesium.Cartesian3.distanceSquared(
? distance(
position,
Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
),
)
fromDegrees(record.longitude, record.latitude),
) ** 2
: 0,
}))
.sort((a, b) => a.distance - b.distance)
@@ -400,6 +377,11 @@ export function createAlprOverlay({
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
records.push(selected);
}
// Cameras that leave the cohort go native; those that stay keep the
// canvas until the next paint, so their icons are not written twice.
const kept = new Set(records.map((record) => record.id));
for (const record of previous)
if (!kept.has(record.id)) nativeVisible(markers.get(record.id), true);
hits = [];
retryUntil = Date.now() + 15000;
lane.setActive(state.enabled && records.length > 0);
@@ -421,8 +403,8 @@ export function createAlprOverlay({
clear() {
clearTimeout(retryTimer);
retryTimer = null;
for (const record of records)
nativeVisible(state.dataSource?.entities.getById(record.id), true);
for (const record of records) nativeVisible(markers.get(record.id), true);
markers.flush();
records = [];
hits = [];
lane?.setActive(false);
+152 -30
View File
@@ -2,11 +2,16 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createAlprOverlay } from './overlay.js';
import { normalizeAlprNode } from './records.js';
import {
directionWedgePositions,
alprLabelDetails,
markerScale,
} from './visuals.js';
import { alprMarkers, createAlprMarkerSet } from './markerState.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { rendererOf } from '../../render/rendererOf.js';
function harness(t, count = 2, { floor = null } = {}) {
const previousImage = globalThis.Image;
@@ -22,23 +27,29 @@ function harness(t, count = 2, { floor = null } = {}) {
longitude: -97,
directionDeg: 90,
}));
const entities = new Cesium.EntityCollection();
const drawPort = fakeDrawPort();
const markers = createAlprMarkerSet();
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
const iconSet = drawPort.set('alpr-cameras:test:markers');
for (const record of records)
entities.add({
id: record.id,
billboard: { image: 'fallback', show: true },
polyline: { show: true },
polygon: { show: true },
Object.assign(alprMarkers.write(markers.add(record.id)), {
record,
position: Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
),
});
markers.flush();
const state = {
enabled: true,
selectedId: null,
dataSource: { entities },
markers,
viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500) },
scene: { globe: { show: true, getHeight: () => 150 } },
},
};
const { unbind } = bindFakeCesiumScene(state.viewer, { draw: drawPort });
let paint,
mapListener,
active,
@@ -79,6 +90,7 @@ function harness(t, count = 2, { floor = null } = {}) {
if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project;
unbind();
});
const draw = [];
const ctx = {
@@ -102,7 +114,11 @@ function harness(t, count = 2, { floor = null } = {}) {
state,
records,
overlay,
entities,
markers,
iconSet,
/** A marker's carrier, and the icon last sent for it. */
carrier: (id) => markers.get(id),
icon: (id) => iconSet.items.get(id),
draw,
paint: (occluder) => paint({ ctx, width: 800, height: 600, occluder }),
mapChanged() {
@@ -130,20 +146,25 @@ test('a selected camera without a bearing gets its badge and brackets, never a f
assert.ok(h.draw[0].endsWith('alpr-marker-selected.png'));
assert.ok(h.draw[1].endsWith('alpr-marker-selected-brackets.png'));
assert.equal(h.overlay.pick({ x: 100, y: 100 }), 'camera:0');
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.icon('camera:0').show, true);
assert.equal(h.icon('camera:0').color[3], 0.01, 'a faint pick target');
assert.equal(
h.entities.getById('camera:0').billboard.color.getValue().alpha,
0.01,
h.icon('camera:0').meta,
h.carrier('camera:0'),
'a pick hands point-and-ask the context carrier',
);
assert.equal(directionWedgePositions(h.records[0]), null);
});
test('the overlay bounds its cohort and promotes selection while leaving farther cameras native', (t) => {
const h = harness(t, 70);
// Floor anchors, so every camera anchors in one paint.
const h = harness(t, 70, { floor: 150 });
h.state.selectedId = 'camera:69';
h.overlay.sync(h.records);
h.paint();
const hidden = h.entities.values.filter((e) => e.gevAlprNativeAppearance);
const hidden = [...h.markers.values()].filter(
(carrier) => alprMarkers.read(carrier)?.canvasOwned,
);
assert.equal(hidden.length, 64);
assert.ok(hidden.some((e) => e.id === 'camera:69'));
assert.equal(
@@ -159,24 +180,25 @@ test('surface changes invalidate cached anchors, and disable/disposal release pa
const h = harness(t, 1);
h.overlay.sync(h.records);
h.paint();
const entity = h.entities.getById('camera:0');
const first = entity.gevAlprCanvasPosition;
const carrier = h.carrier('camera:0');
const first = alprMarkers.read(carrier)?.canvasPosition;
h.paint();
assert.equal(
entity.gevAlprCanvasPosition,
alprMarkers.read(carrier)?.canvasPosition,
first,
'stable anchor across frames',
);
h.state.viewer.scene.globe.show = false;
h.mapChanged();
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(alprMarkers.read(carrier)?.canvasPosition, null);
h.state.enabled = false;
h.overlay.clear();
assert.equal(h.active, false);
assert.equal(h.overlay.pick({ x: 100, y: 100 }), null);
assert.equal(entity.billboard.show.getValue(), true);
assert.equal(entity.billboard.color, undefined);
assert.equal(entity.position, undefined);
const icon = h.icon('camera:0');
assert.equal(icon.show, true);
assert.equal(icon.color, undefined, 'the native badge again');
assert.equal(icon.pos, alprMarkers.read(carrier).position);
h.overlay.destroy();
assert.equal(h.removed, 1);
});
@@ -186,7 +208,8 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
h.state.viewer.scene.globe.getHeight = () => -15000;
h.overlay.sync(h.records);
h.paint();
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.icon('camera:0').show, true);
assert.equal(h.icon('camera:0').color, undefined);
assert.equal(h.draw.length, 0);
h.state.viewer.scene.globe.getHeight = () => 150;
h.paint({ isPointVisible: () => false });
@@ -194,18 +217,37 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
assert.equal(h.draw.length, 0);
});
test('repeated paints of a still view never rewrite marker properties', (t) => {
// Each Entity write raises definitionChanged; paint used to hide then show
// every overlay camera's native marker on every frame.
test('repeated paints of a still view never rewrite markers', (t) => {
// Paint used to hide then show every overlay camera's native marker on
// every frame.
const h = harness(t, 3);
h.overlay.sync(h.records);
h.paint();
let changes = 0;
for (const entity of h.entities.values)
entity.definitionChanged.addEventListener(() => changes++);
h.paint();
const writes = h.iconSet.writes;
for (let i = 0; i < 5; i++) h.paint();
assert.equal(changes, 0);
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true);
assert.equal(h.iconSet.writes, writes);
assert.equal(h.icon('camera:0').show, true);
});
test('a resync hands back only the cameras that leave the overlay', (t) => {
const h = harness(t, 2, { floor: 150 });
h.overlay.sync(h.records);
h.paint();
assert.equal(h.icon('camera:0').color[3], 0.01);
assert.equal(h.icon('camera:1').color[3], 0.01);
const writes = h.iconSet.writes;
h.overlay.sync([h.records[0]]);
h.markers.flush();
assert.equal(h.icon('camera:1').color, undefined, 'native again');
assert.equal(h.icon('camera:0').color[3], 0.01, 'still under the canvas');
assert.equal(
h.iconSet.writes,
writes + 1,
'one write, for the camera that left',
);
h.paint();
assert.equal(h.iconSet.writes, writes + 1, 'the next paint writes nothing');
});
test('adapter labels never claim a custom source is public OSM data', () => {
@@ -218,6 +260,23 @@ test('adapter labels never claim a custom source is public OSM data', () => {
);
});
test('a mapped bearing that rounds up to a whole turn reads 0°, not 360°', () => {
const direction = (tag) =>
alprLabelDetails(
normalizeAlprNode({
type: 'node',
id: 1,
lat: 30,
lon: -97,
tags: { 'surveillance:type': 'ALPR', 'camera:direction': tag },
}),
{ label: 'Custom directory' },
).find((line) => line.startsWith('DIRECTION'));
assert.equal(direction('359.6'), 'DIRECTION 0°');
assert.equal(direction('359.4'), 'DIRECTION 359°');
assert.equal(direction('0.4'), 'DIRECTION 0°');
});
test('overlay glyphs and native badges shrink alike with distance', () => {
assert.equal(markerScale(100), 1.15);
assert.equal(markerScale(40_000), 0.45);
@@ -242,7 +301,7 @@ test('a still view replaces floor anchors with the rendered surface, within the
h.paint();
const height = (id) =>
Cesium.Cartographic.fromCartesian(
h.entities.getById(id).gevAlprCanvasPosition,
alprMarkers.read(h.carrier(id))?.canvasPosition,
).height;
assert.equal(
samples,
@@ -263,3 +322,66 @@ test('a still view replaces floor anchors with the rendered surface, within the
h.paint();
assert.equal(samples, taken, 'each anchor is checked once');
});
test('a bearing wedge is plain ECEF at the apex and its two far corners', () => {
const record = { latitude: 30.26, longitude: -97.74, directionDeg: 90 };
const wedge = directionWedgePositions(record, 150, (lat) =>
lat > 30.26 ? 160 : null,
);
assert.equal(wedge.length, 3);
const apex = Cesium.Cartesian3.fromDegrees(-97.74, 30.26, 150);
assert.deepEqual({ ...wedge[0] }, { x: apex.x, y: apex.y, z: apex.z });
const heights = wedge.map(
(p) =>
Cesium.Cartographic.fromCartesian(new Cesium.Cartesian3(p.x, p.y, p.z))
.height,
);
// The corner north of the apex takes the sampled height; the other falls back.
assert.ok(heights.some((h) => Math.abs(h - 160) < 1e-6));
assert.ok(heights.slice(1).some((h) => Math.abs(h - 150) < 1e-6));
});
test('anchors wait for the surface heights answer from: the globe’s terrain while shown, else the shown 3D tiles', (t) => {
const h = harness(t, 1, { floor: 150 });
const scene = h.state.viewer.scene;
h.state.viewer.camera.directionWC = Cesium.Cartesian3.UNIT_X;
scene.sampleHeightSupported = true;
scene.primitives = { length: 0, get: () => null };
let samples = 0;
scene.sampleHeight = () => (samples++, 172);
// The renderer's own `surface` rule; a non-base tileset still streaming
// over a hidden globe leaves it unsettled.
let surface = false;
const asked = new Set();
rendererOf(h.state.viewer).globe = {
isSettled: (kind) => (asked.add(kind), kind === 'surface' ? surface : true),
};
h.overlay.sync(h.records);
h.paint();
h.paint();
assert.equal(samples, 0, 'no samples while the surface streams');
assert.deepEqual([...asked], ['surface']);
surface = true;
h.paint();
assert.ok(samples > 0, 'sampled once it has loaded');
});
test('without height sampling no sample is spent, and the terrain anchors only while the globe is drawn', (t) => {
for (const shown of [true, false]) {
const h = harness(t, 1);
let samples = 0;
h.state.viewer.scene.sampleHeight = () => (samples++, 172);
const renderer = rendererOf(h.state.viewer);
renderer.capabilities = new Set();
renderer.globe = { isSettled: () => true, isGlobeVisible: () => shown };
h.overlay.sync(h.records);
h.paint();
h.paint();
assert.equal(samples, 0, 'nothing sampled without the capability');
assert.equal(
Boolean(alprMarkers.read(h.carrier('camera:0'))?.canvasPosition),
shown,
shown ? 'anchored on the terrain' : 'no terrain under hidden globe',
);
}
});
+207 -246
View File
@@ -1,28 +1,41 @@
import * as Cesium from 'cesium';
import { isPointerFree } from '../../data/inputOwnership.js';
import { isFollowing } from '../../data/followed.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import {
LAYER_ID,
MAX_VIEWPORT_DEGREES,
MAX_RENDERED,
ALPR_COLOR,
ALPR_SELECTED_COLOR,
MARKER_ICON_SIZE,
SELECTED_MARKER_ICON_SIZE,
CREDIT_DISPLAY_MS,
MARKER_FLOOR_LIFT_M,
MARKER_SCALE_BY_DISTANCE,
} from './policy.js';
import { boxContains } from './model.js';
import { t } from '../../i18n/index.js';
import { msg } from '../../i18n/index.js';
import { createAlprFloorResolver } from './floors.js';
import { createAlprOverlay } from './overlay.js';
import {
MARKER_IMAGE,
SELECTED_IMAGE,
alprDisplayId,
alprLabelDetails,
validAlprGroundHeight,
} from './visuals.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { alprIconPosition, alprMarkers } from './markerState.js';
import { horizonFrom } from '../../geo/horizon.js';
import {
cameraOf,
canvasOf,
findCredits,
findQuery,
} from '../../render/rendererOf.js';
/** A `#rrggbb` colour as `rgb(r,g,b)`, the form the readout card has always had. */
function cssRgb(hex) {
const n = Number.parseInt(hex.slice(1), 16);
return `rgb(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255})`;
}
export function createAlprPresentation({ state, services, source }) {
const { governorRequestRender } = services.render;
@@ -35,6 +48,7 @@ export function createAlprPresentation({ state, services, source }) {
} = services.context;
const { cachedGroundFloor } = services.groundFloor;
const markers = state.markers;
const overlay = createAlprOverlay({
state,
services,
@@ -42,11 +56,35 @@ export function createAlprPresentation({ state, services, source }) {
});
let visibleRecords = [];
let selectionStartedAt = 0;
/** Markers still clamped while their floor cell resolves (id -> entity). */
/** Markers still clamped while their floor cell resolves (id -> carrier). */
const clampedMarkers = new Map();
let floorResolve = null;
const floors = createAlprFloorResolver(services.groundFloor);
/** Heights under a camera now, through the renderer's query port. */
function heightNow(record, against) {
const query = findQuery(state.viewer);
if (!query) return null;
const point = { lon: record.longitude, lat: record.latitude };
// A miss is tiles still streaming. The markers are no ground: the
// height sees through them.
return against === 'terrain'
? query.sampleHeightNow(point, { against: 'terrain' })
: query.sampleHeightNow(point, { exclude: [markers.icons?.id] });
}
/**
* The ground under a camera: the rendered surface, else the terrain,
* else the cached floor; null when none is plausible.
*/
function groundHeight(record) {
let height = heightNow(record);
if (!validAlprGroundHeight(height)) height = heightNow(record, 'terrain');
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
return validAlprGroundHeight(height) ? height : null;
}
/**
* Marker placement from the cached ground floor (validated mesh or DEM, the
* ellipsoidal datum every layer shares). Ground clamping on photoreal tiles
@@ -54,14 +92,14 @@ export function createAlprPresentation({ state, services, source }) {
* whole-city view stutter while zooming, so it is only the placeholder for
* a cell that has not resolved yet.
* @param {{latitude:number, longitude:number}} record Camera.
* @returns {{position: Cesium.Cartesian3, clamped: boolean}} Placement.
* @returns {{position: {x:number, y:number, z:number}, clamped: boolean}} Placement.
*/
function markerPlacement(record) {
const floor = cachedGroundFloor(record.latitude, record.longitude);
const clamped = !validAlprGroundHeight(floor);
return {
clamped,
position: Cesium.Cartesian3.fromDegrees(
position: fromDegrees(
record.longitude,
record.latitude,
clamped ? 0 : floor + MARKER_FLOOR_LIFT_M,
@@ -130,25 +168,18 @@ export function createAlprPresentation({ state, services, source }) {
* @returns {number|null} Count, or null without a scene to project into.
*/
function countOnScreen() {
const scene = state.viewer?.scene;
const canvas = scene?.canvas;
const canvas = canvasOf(state.viewer);
const width = canvas?.clientWidth || canvas?.width;
const height = canvas?.clientHeight || canvas?.height;
const camera = state.viewer?.camera;
if (!scene || !width || !height || !camera?.positionWC) return null;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.positionWC,
);
const query = findQuery(state.viewer);
if (!query || !width || !height) return null;
let count = 0;
try {
for (const entity of state.dataSource.entities.values) {
const position = entity.position?.getValue?.(Cesium.JulianDate.now());
if (!position || !occluder.isPointVisible(position)) continue;
const point = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
position,
);
const horizon = horizonFrom(cameraOf(state.viewer).pose().position);
for (const carrier of markers.values()) {
const position = alprIconPosition(carrier);
if (!position || !horizon.isPointVisible(position)) continue;
const point = query.project(position);
if (
point &&
point.x >= 0 &&
@@ -165,31 +196,26 @@ export function createAlprPresentation({ state, services, source }) {
return count;
}
/** Write a marker position, respecting the overlay's pick-target swap. */
function setMarkerPosition(entity, position, clamped) {
const heightReference = clamped
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE;
const saved = entity.gevAlprNativeAppearance;
if (saved) {
saved.position = position;
saved.heightReference = heightReference;
} else {
entity.position = position;
entity.billboard.heightReference = heightReference;
}
entity.gevAlprClamped = clamped;
/** Write a marker's native placement; the canvas anchor is left alone. */
function setMarkerPosition(carrier, position, clamped) {
const marker = alprMarkers.write(carrier);
marker.position = position;
marker.clamped = clamped;
markers.changed(carrier);
}
/** Refresh all native placements, including the appearances held by the canvas. */
/** Refresh all native placements, including those under canvas badges. */
function refreshMarkerPlacements() {
if (!state.enabled || !state.dataSource) return;
if (!state.enabled || !markers.icons) return;
clampedMarkers.clear();
for (const entity of state.dataSource.entities.values) {
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
setMarkerPosition(entity, position, clamped);
if (clamped) clampedMarkers.set(entity.id, entity);
for (const carrier of markers.values()) {
const { position, clamped } = markerPlacement(
alprMarkers.read(carrier)?.record,
);
setMarkerPosition(carrier, position, clamped);
if (clamped) clampedMarkers.set(carrier.id, carrier);
}
markers.flush();
resolveClampedFloors();
governorRequestRender('alpr-surface');
}
@@ -202,74 +228,65 @@ export function createAlprPresentation({ state, services, source }) {
const batch = [...clampedMarkers.values()];
const request = Promise.resolve(
floors.resolve(
batch.map((entity) => ({
lat: entity.gevAlprRecord.latitude,
lon: entity.gevAlprRecord.longitude,
})),
batch.map((carrier) => {
const { record } = alprMarkers.read(carrier);
return { lat: record.latitude, lon: record.longitude };
}),
),
)
.catch(() => {})
.then(() => {
if (floorResolve !== request) return;
floorResolve = null;
if (!state.enabled || !state.dataSource) return;
if (!state.enabled || !markers.icons) return;
let moved = false;
for (const entity of batch) {
if (clampedMarkers.get(entity.id) !== entity) continue;
clampedMarkers.delete(entity.id);
const { position, clamped } = markerPlacement(entity.gevAlprRecord);
for (const carrier of batch) {
if (clampedMarkers.get(carrier.id) !== carrier) continue;
clampedMarkers.delete(carrier.id);
const { position, clamped } = markerPlacement(
alprMarkers.read(carrier)?.record,
);
if (clamped) continue;
setMarkerPosition(entity, position, false);
setMarkerPosition(carrier, position, false);
moved = true;
}
markers.flush();
if (moved) governorRequestRender('alpr-floor');
// Cells that never resolved stay clamped; later renders retry them.
});
floorResolve = request;
}
function updateAppearance(entity, selected) {
const color = Cesium.Color.fromCssColorString(
selected ? ALPR_SELECTED_COLOR : ALPR_COLOR,
);
entity.billboard.image = selected ? SELECTED_IMAGE : MARKER_IMAGE;
entity.billboard.width = entity.billboard.height = selected
? SELECTED_MARKER_ICON_SIZE
: MARKER_ICON_SIZE;
if (entity.gevLabelModel) {
entity.gevLabelModel.accent = color.toCssColorString();
entity.gevLabelModel.leaderAnimationStartedAt = selected
? selectionStartedAt
: 0;
function updateAppearance(carrier, selected) {
alprMarkers.write(carrier).selected = selected;
markers.changed(carrier);
const labelModel = readEntityRecord(carrier)?.labelModel;
if (labelModel) {
labelModel.accent = cssRgb(selected ? ALPR_SELECTED_COLOR : ALPR_COLOR);
labelModel.leaderAnimationStartedAt = selected ? selectionStartedAt : 0;
}
}
function markerColor() {
return Cesium.Color.fromCssColorString(ALPR_COLOR);
}
// The horizon rectangle is unstable during low-angle orbits and can exclude
// the ground point in the center of the screen. Bound nearby coverage around
// that point instead; the camera-to-ground range keeps zoom-out queries capped.
function viewportBox(viewer) {
const camera = viewer?.camera;
const canvas = viewer?.scene.canvas;
if (typeof camera?.pickEllipsoid === 'function' && canvas) {
const query = findQuery(viewer);
const canvas = canvasOf(viewer);
if (typeof query?.pickEllipsoid === 'function' && canvas) {
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
if (!width || !height) return null;
const focus = camera.pickEllipsoid(
new Cesium.Cartesian2(width / 2, height / 2),
viewer.scene.globe.ellipsoid,
);
const focus = query.pickEllipsoid(width / 2, height / 2);
if (!focus) return null;
const location = Cesium.Cartographic.fromCartesian(focus);
const range = Cesium.Cartesian3.distance(camera.positionWC, focus);
const location = toLonLatH(focus);
if (!location) return null;
const range = distance(cameraOf(viewer).pose().position, focus);
const radius = Math.max(1000, 2 * range);
const latitude = Cesium.Math.toDegrees(location.latitude);
const longitude = Cesium.Math.toDegrees(location.longitude);
const latitude = location.lat;
const longitude = location.lon;
const latSpan = radius / 111000;
const lonSpan = latSpan / Math.cos(location.latitude);
const lonSpan = latSpan / Math.cos((latitude * Math.PI) / 180);
if (
!Number.isFinite(latSpan + lonSpan) ||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
@@ -285,14 +302,9 @@ export function createAlprPresentation({ state, services, source }) {
};
}
// Rectangle-only viewers retain the same bounded-area contract.
const rectangle = viewer?.camera?.computeViewRectangle(
viewer.scene.globe.ellipsoid,
);
const rectangle = viewer ? cameraOf(viewer).viewRectangle() : null;
if (!rectangle) return null;
const south = Cesium.Math.toDegrees(rectangle.south);
const north = Cesium.Math.toDegrees(rectangle.north);
const west = Cesium.Math.toDegrees(rectangle.west);
const east = Cesium.Math.toDegrees(rectangle.east);
const { south, north, west, east } = rectangle;
if (
!Number.isFinite(south + north + west + east) ||
east <= west ||
@@ -310,7 +322,7 @@ export function createAlprPresentation({ state, services, source }) {
overlay.clear();
visibleRecords = [];
clampedMarkers.clear();
if (state.dataSource?.entities) state.dataSource.entities.removeAll();
markers.clear();
removeEntityContextsForLayer(LAYER_ID);
}
@@ -318,8 +330,8 @@ export function createAlprPresentation({ state, services, source }) {
services.credits?.hideOsmCredit?.(state.viewer, LAYER_ID);
clearTimeout(state.creditTimer);
state.creditTimer = null;
if (state.credit)
state.viewer?.creditDisplay?.removeStaticCredit(state.credit);
state.creditOff?.();
state.creditOff = null;
governorRequestRender('alpr-credit');
}
@@ -334,7 +346,8 @@ export function createAlprPresentation({ state, services, source }) {
}
if (!state.enabled || state.creditPresented || !state.credit) return;
state.creditPresented = true;
state.viewer.creditDisplay?.addStaticCredit(state.credit);
state.creditOff =
findCredits(state.viewer)?.addStatic(state.credit) ?? null;
state.creditTimer = setTimeout(hideOnMapCredit, CREDIT_DISPLAY_MS);
governorRequestRender('alpr-credit');
}
@@ -359,82 +372,68 @@ export function createAlprPresentation({ state, services, source }) {
governorRequestRender('alpr-render');
const visibleIds = new Set(visible.map((record) => record.id));
let changed = false;
state.dataSource.entities.suspendEvents();
for (const entity of [...state.dataSource.entities.values]) {
if (!visibleIds.has(entity.id)) {
state.dataSource.entities.remove(entity);
clampedMarkers.delete(entity.id);
changed = true;
}
const gone = [];
for (const carrier of markers.values())
if (!visibleIds.has(carrier.id)) gone.push(carrier.id);
if (gone.length) {
markers.remove(gone);
for (const id of gone) clampedMarkers.delete(id);
changed = true;
}
removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds });
for (const record of visible) {
const existing = state.dataSource.entities.getById(record.id);
if (existing?.gevAlprRecord === record) {
const existing = markers.get(record.id);
if (alprMarkers.read(existing)?.record === record) {
updateAppearance(existing, record.id === state.selectedId);
continue;
}
const color = markerColor();
const selected = record.id === state.selectedId;
const { position, clamped } = markerPlacement(record);
// Direction wedges are painted by the overlay for the nearest cameras.
// Native ground-clamped wedges (a ground polyline plus a classification
// polygon per camera) cost ~40 ms per frame for 200 downtown cameras on
// photoreal tiles, so markers stay billboards only.
const entityDef = {
id: record.id,
position,
billboard: {
image: selected ? SELECTED_IMAGE : MARKER_IMAGE,
width: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
height: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE,
heightReference: clamped
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
// City-wide views hold hundreds of badges; let them shrink.
scaleByDistance: new Cesium.NearFarScalar(
...MARKER_SCALE_BY_DISTANCE,
),
},
};
let entity = existing;
// Keep the Cesium entity and its ground-clamping subscription while its
// geometry is unchanged. Updating metadata must not rebuild the marker.
const previous = entity?.gevAlprRecord;
if (!entity) {
entity = state.dataSource.entities.add(entityDef);
entity.gevAlprClamped = clamped;
// photoreal tiles, so markers stay icons only.
let carrier = existing;
// Keep the marker and its icon while its geometry is unchanged.
// Updating metadata must not rebuild the marker.
const previous = alprMarkers.read(carrier)?.record;
if (!carrier) {
carrier = markers.add(record.id);
changed = true;
}
const marker = alprMarkers.write(carrier);
if (!existing) {
marker.position = position;
marker.clamped = clamped;
} else {
if (
previous.latitude !== record.latitude ||
previous.longitude !== record.longitude
) {
setMarkerPosition(entity, position, clamped);
entity.gevAlprCanvasPosition = null;
entity.gevAlprDisplayPosition = null;
setMarkerPosition(carrier, position, clamped);
marker.canvasPosition = null;
marker.displayPosition = null;
}
if (
previous.latitude !== record.latitude ||
previous.longitude !== record.longitude ||
previous.directionDeg !== record.directionDeg
) {
entity.gevAlprCanvasPosition = null;
entity.gevAlprWedge = null;
marker.canvasPosition = null;
marker.wedge = null;
}
}
entity.gevAlprRecord = record;
entity.gevTrackedId = record.id;
marker.record = record;
entityRecord(carrier).trackedId = record.id;
// The mapped camera datum has no elevation; it is not the clamped marker's
// visual anchor. Only the selected marker samples the rendered surface,
// at most once per second, through Cesium's public height APIs.
entity.gevAlprDisplayPosition ??= null;
entity.gevDisplayPosition = () => entity.gevAlprDisplayPosition;
entity.gevLabelModel = {
// at most once per second, through the renderer's height queries.
marker.displayPosition ??= null;
entityRecord(carrier).displayPosition = () => marker.displayPosition;
entityRecord(carrier).labelModel = {
title: alprDisplayId(record),
details: alprLabelDetails(record, source),
accent: color.toCssColorString(),
accent: cssRgb(ALPR_COLOR),
cardStyle: 'tactical',
selected: true,
leaderStyle: 'elbow',
@@ -444,15 +443,16 @@ export function createAlprPresentation({ state, services, source }) {
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
anchorRadiusScale: null,
};
updateAppearance(entity, selected);
registerEntityContext(entity, {
updateAppearance(carrier, selected);
registerEntityContext(carrier, {
id: record.id,
layerId: LAYER_ID,
dataSource: state.dataSource,
// Hidden with the layer: the context store reads its `show`.
dataSource: markers.icons,
layerName: 'ALPR Cameras',
source:
source.attribution?.description || source.label || 'Camera source',
label: t('ALPR camera'),
label: msg('ALPR camera'),
latitude: record.latitude,
longitude: record.longitude,
properties: {
@@ -468,101 +468,85 @@ export function createAlprPresentation({ state, services, source }) {
},
});
}
state.dataSource.entities.resumeEvents();
if (changed) state.renderRevision += 1;
state.onScreen = countOnScreen();
for (const entity of state.dataSource.entities.values)
if (entity.gevAlprClamped) clampedMarkers.set(entity.id, entity);
for (const carrier of markers.values())
if (alprMarkers.read(carrier)?.clamped)
clampedMarkers.set(carrier.id, carrier);
resolveClampedFloors();
const selectedEntity = state.selectedId
? state.dataSource.entities.getById(state.selectedId)
const selectedCarrier = state.selectedId
? markers.get(state.selectedId)
: null;
if (!selectedEntity) state.selectedId = null;
if (!selectedCarrier) state.selectedId = null;
updateSelectedAnchor();
overlay.sync(visible);
if (selectedEntity) services.overlays?.refreshReadout?.(selectedEntity);
markers.flush();
if (selectedCarrier) services.overlays?.refreshReadout?.(selectedCarrier);
// Keep the on-map credit tied to displayed data, not loading or zoom prompts.
if (visible.length) presentOnMapCredit();
else hideOnMapCredit();
}
function focusNearest() {
const camera = state.viewer?.camera;
if (!state.enabled || !camera?.positionWC || state.viewer.trackedEntity)
if (!state.enabled || !state.viewer || isFollowing(state.viewer))
return false;
const port = cameraOf(state.viewer);
const eye = port.pose().position;
let nearest = null,
distance = Infinity;
for (const entity of state.dataSource.entities.values) {
const position = entity.position.getValue(Cesium.JulianDate.now());
const candidate = Cesium.Cartesian3.distanceSquared(
camera.positionWC,
position,
);
if (candidate < distance) {
nearest = entity;
distance = candidate;
best = Infinity;
for (const carrier of markers.values()) {
const position = alprIconPosition(carrier);
if (!position) continue;
const candidate = distance(eye, position);
if (candidate < best) {
nearest = carrier;
best = candidate;
}
}
if (!nearest) return false;
const record = state.recordById.get(nearest.id);
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
let height;
if (state.viewer.scene.sampleHeightSupported) {
try {
height = state.viewer.scene.sampleHeight(location, [nearest]);
} catch {
/* tiles may still be streaming */
}
}
if (!validAlprGroundHeight(height) && state.viewer.scene.globe.show)
height = state.viewer.scene.globe.getHeight?.(location);
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
const center = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
validAlprGroundHeight(height) ? height : 0,
);
const height = groundHeight(record);
const center = fromDegrees(record.longitude, record.latitude, height ?? 0);
if (!selectRecord(nearest.id)) return false;
camera.flyToBoundingSphere(new Cesium.BoundingSphere(center, 30), {
duration: 1.2,
offset: new Cesium.HeadingPitchRange(
camera.heading || 0,
-Math.PI / 4,
800,
),
});
port.flyToBounds(
{ center, radius: 30 },
{
durationS: 1.2,
offset: {
heading: port.pose().heading || 0,
pitch: -Math.PI / 4,
range: 800,
},
},
);
governorRequestRender('alpr-focus');
return true;
}
function selectRecord(id) {
const entity = state.dataSource?.entities.getById(id);
if (!entity || !state.recordById.has(id)) return false;
const carrier = markers.get(id);
if (!carrier || !state.recordById.has(id)) return false;
clearSelection();
state.selectedId = id;
selectionStartedAt = globalThis.performance?.now?.() ?? Date.now();
updateAppearance(entity, true);
updateAppearance(carrier, true);
state.lastAnchorSampleAt = 0;
selectEntityContext(entity);
selectEntityContext(carrier);
updateSelectedAnchor();
overlay.sync(visibleRecords);
markers.flush();
governorRequestRender('alpr-selection');
return true;
}
function clearSelection() {
const entity = state.selectedId
? state.dataSource?.entities.getById(state.selectedId)
: null;
const carrier = state.selectedId ? markers.get(state.selectedId) : null;
const record = state.recordById.get(state.selectedId);
if (entity && record) updateAppearance(entity, false);
if (carrier && record) updateAppearance(carrier, false);
state.selectedId = null;
selectionStartedAt = 0;
overlay.sync(visibleRecords);
markers.flush();
clearSelectedEntityContextForLayer(LAYER_ID);
governorRequestRender('alpr-selection');
}
@@ -574,60 +558,38 @@ export function createAlprPresentation({ state, services, source }) {
clearSelection();
return;
}
const entity = state.dataSource?.entities.getById(state.selectedId);
const carrier = markers.get(state.selectedId);
const record = state.recordById.get(state.selectedId);
if (entity?.gevAlprCanvasPosition) {
entity.gevAlprDisplayPosition = entity.gevAlprCanvasPosition;
const marker = alprMarkers.read(carrier);
if (marker?.canvasPosition) {
marker.displayPosition = marker.canvasPosition;
return;
}
if (!entity || !record || Date.now() - state.lastAnchorSampleAt < 1000)
if (!carrier || !record || Date.now() - state.lastAnchorSampleAt < 1000)
return;
state.lastAnchorSampleAt = Date.now();
const scene = state.viewer.scene;
const location = Cesium.Cartographic.fromDegrees(
record.longitude,
record.latitude,
);
let height;
if (scene.sampleHeightSupported) {
try {
height = scene.sampleHeight(location, [entity]);
} catch {
/* tiles may still be streaming */
}
}
if (!validAlprGroundHeight(height) && scene.globe.show)
height = scene.globe.getHeight?.(location);
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
if (!validAlprGroundHeight(height)) return;
const next = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
height,
);
if (
!entity.gevAlprDisplayPosition ||
Cesium.Cartesian3.distance(next, entity.gevAlprDisplayPosition) > 0.1
) {
entity.gevAlprDisplayPosition = next;
const height = groundHeight(record);
if (height === null) return;
const next = fromDegrees(record.longitude, record.latitude, height);
const shown = marker?.displayPosition;
if (!shown || distance(next, shown) > 0.1) {
alprMarkers.write(carrier).displayPosition = next;
governorRequestRender('alpr-anchor');
}
}
function installInteraction(viewer) {
if (state.clickHandler) return;
state.clickHandler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas,
);
state.clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
if (state.clickSubscription) return;
state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return;
const picked = viewer.scene.pick(click.position);
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
// The painted overlay answers first; the scene is picked only if not.
const hit = event.drawHit;
const id =
overlay.pick(click.position) ||
(typeof picked?.id?.id === 'string' ? picked.id.id : null);
overlay.pick(event.screenPosition) ||
(hit && hit.set === markers.icons?.id ? hit.id : null);
if (
id &&
state.recordById.has(id) &&
@@ -635,12 +597,11 @@ export function createAlprPresentation({ state, services, source }) {
)
selectRecord(id);
else if (state.selectedId) clearSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
}
return {
initOverlay: () => overlay.init(),
destroyOverlay: () => overlay.destroy(),
markerColor,
viewportBox,
clearRendered,
hideOnMapCredit,
+176
View File
@@ -0,0 +1,176 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
import { createAlprMarkerSet } from './markerState.js';
import { createAlprPresentation } from './presentation.js';
/** One camera drawn and painted at (100, 100), over a viewer whose clicks a
* label may take. */
function harness(t) {
const previousImage = globalThis.Image;
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
globalThis.Image = class {
complete = true;
naturalWidth = 128;
};
Cesium.SceneTransforms.worldToWindowCoordinates = () => ({ x: 100, y: 100 });
const record = {
id: 'camera:0',
latitude: 30,
longitude: -97,
directionDeg: 90,
};
const drawPort = fakeDrawPort();
const markers = createAlprMarkerSet();
markers.attach(drawPort.icons({ id: 'alpr-cameras:test:markers' }));
const viewer = {
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500),
pickEllipsoid: () => Cesium.Cartesian3.fromDegrees(-97, 30),
},
scene: {
canvas: { clientWidth: 800, clientHeight: 600 },
globe: { show: true, getHeight: () => 150 },
pick: () => null,
},
};
const { unbind } = bindFakeCesiumScene(viewer, { draw: drawPort });
const fake = fakeInputUnderLabel(viewer);
const state = {
viewer,
enabled: true,
selectedId: null,
markers,
records: [record],
recordById: new Map([[record.id, record]]),
renderRevision: 0,
lastAnchorSampleAt: 0,
};
let selected = null;
let paint;
const presentation = createAlprPresentation({
state,
source: { label: 'Test cameras' },
services: {
render: { governorRequestRender() {} },
context: {
clearSelectedEntityContextForLayer() {
selected = null;
},
getSelectedEntityContext: () => selected,
registerEntityContext() {},
removeEntityContextsForLayer() {},
selectEntityContext(carrier) {
selected = { id: carrier.id, layerId: 'alpr-cameras' };
},
},
groundFloor: { cachedGroundFloor: () => 150 },
overlays: {
registerPaintLane(_lane, painter) {
paint = painter;
return { setActive() {}, requestPaint() {}, unregister() {} };
},
keyholeAlpha: () => 1,
},
},
});
presentation.initOverlay();
presentation.installInteraction(viewer);
t.after(() => {
presentation.destroyOverlay();
fake.destroy();
unbind();
if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project;
});
presentation.renderRecords();
const ctx = {
globalAlpha: 1,
save() {},
restore() {},
beginPath() {},
moveTo() {},
lineTo() {},
closePath() {},
stroke() {},
fill() {},
createLinearGradient: () => ({ addColorStop() {} }),
drawImage() {},
};
paint({ ctx, width: 800, height: 600 });
return { state, fake, at: { x: 100, y: 100 } };
}
test('a click on a mission label over a camera never selects it, and keeps the selected camera', (t) => {
const h = harness(t);
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, null, 'the camera under the label');
// Off the label, the same click selects the camera.
h.fake.label.over = false;
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0');
// The label on top is its own click: the selection stays.
h.fake.label.over = true;
h.fake.click(h.at);
assert.equal(h.state.selectedId, 'camera:0', 'the selection stays');
});
// The card or label painted on top takes the click: ALPR does not even pick
// under another layer's card, so no camera is selected or released there.
test("another layer's card over an ALPR camera keeps the click", (t) => {
let picks = 0;
const viewer = {
scene: {
canvas: new EventTarget(),
pick: () => {
picks++;
return null;
},
},
};
const input = fakeInput(viewer);
const noop = () => {};
const state = {
enabled: true,
viewer,
clickSubscription: null,
markers: { icons: null },
recordById: new Map(),
selectedId: null,
};
const presentation = createAlprPresentation({
state,
services: {
render: { governorRequestRender: noop },
context: {
clearSelectedEntityContextForLayer: noop,
getSelectedEntityContext: () => null,
registerEntityContext: noop,
removeEntityContextsForLayer: noop,
selectEntityContext: noop,
},
groundFloor: { cachedGroundFloor: () => null },
},
});
presentation.installInteraction(viewer);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => {
setClickCardHitTest(null);
state.clickSubscription?.();
input.destroy();
});
input.tap({ x: 10, y: 10 });
assert.equal(picks, 0, 'covered: the scene under the card is not picked');
top = null;
input.tap({ x: 10, y: 10 });
assert.ok(picks > 0, 'open map: the click reaches the scene');
});
+5 -4
View File
@@ -1,11 +1,12 @@
import { normalizeDisplayText } from '../../data/displayText.js';
import { QUERY_LIMIT, QUERY_SNAP_DEGREES } from './policy.js';
export function textTag(value) {
const t = String(value ?? '').trim();
function textTag(value) {
const t = normalizeDisplayText(value);
return t || null;
}
export function numTag(value) {
function numTag(value) {
// `Number('')` and `Number(' ')` are 0, not NaN — a blank or whitespace-only
// tag value must read as missing, never as a due-north bearing.
if (value == null) return null;
@@ -102,7 +103,7 @@ export function normalizeAlprNode(el) {
};
}
export function normalizeDirection(value) {
function normalizeDirection(value) {
const degrees = numTag(value);
return degrees != null && degrees >= 0 && degrees <= 360
? degrees % 360
+20 -11
View File
@@ -8,7 +8,7 @@ import {
createOverpassAlprSource,
buildOverpassQuery,
} from './source.js';
import { validateAlprSnapshot, alprCreditMarkup } from './model.js';
import { validateAlprSnapshot, alprCredit } from './model.js';
const box = { south: 30, west: -98, north: 30.1, east: -97.9 };
test('the source rejects invalid and unbounded queries before fetching', async () => {
let calls = 0;
@@ -130,19 +130,28 @@ test('source snapshots reject malformed coordinates and duplicate identities', (
);
});
test('provider attribution escapes markup and rejects executable links', () => {
assert.equal(alprCreditMarkup(null), null);
test('provider attribution is plain text with a public HTTPS link only', () => {
assert.equal(alprCredit(null), null);
assert.throws(
() => alprCreditMarkup({ text: 'test', href: 'javascript:alert(1)' }),
() => alprCredit({ text: 'test', href: 'javascript:alert(1)' }),
/HTTPS/,
);
const html = alprCreditMarkup({
text: '<img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
});
assert.ok(html.includes('&lt;img onerror=alert(1)&gt;'));
assert.ok(html.includes('?a=1&amp;b=2'));
assert.ok(!html.includes('<img'));
assert.throws(
() => alprCredit({ text: 'test', href: 'https://user:[email protected]/' }),
/HTTPS/,
);
assert.deepEqual(
alprCredit({
text: '<img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
}),
{
text: 'ALPR: <img onerror=alert(1)>',
href: 'https://example.org/?a=1&b=2',
inline: true,
},
'left as text: the credits port escapes it',
);
});
test('wide detail view returns zoom guidance before any fetch and can retry a smaller view', async () => {
+1 -1
View File
@@ -3,7 +3,7 @@ import { VectorTile } from '@mapbox/vector-tile';
import { normalizeAlprNode } from './records.js';
/** Map extract attributes without treating an OSM edit date as a field verification. */
export function normalizeAlprTileFeature(feature) {
function normalizeAlprTileFeature(feature) {
const p = feature?.properties || {};
if (feature?.geometry?.type !== 'Point' || p.osmType !== 'node') return null;
const [lon, lat] = feature.geometry.coordinates;
+10 -12
View File
@@ -1,14 +1,15 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/index.js';
import { destinationPointDeg } from './model.js';
import {
DIRECTION_CONE_M,
DIRECTION_CONE_HALF_ANGLE_DEG,
MARKER_SCALE_BY_DISTANCE,
} from './policy.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
/**
* Badge scale at a camera distance, matching Cesium's NearFarScalar for the
* native badges (linear between near and far, clamped outside).
* Badge scale at a camera distance, matching the native badges'
* scale-by-distance (linear between near and far, clamped outside).
* @param {number} distanceM Camera-to-marker distance.
* @returns {number} Scale factor.
*/
@@ -50,7 +51,7 @@ export function alprLabelDetails(record, source) {
sourceName === 'OpenStreetMap' ? 'OSM MAPPED' : `Source: ${sourceName}`,
];
if (Number.isFinite(record.directionDeg))
details.push(`DIRECTION ${Math.round(record.directionDeg)}°`);
details.push(`DIRECTION ${roundHeadingDegrees(record.directionDeg)}°`);
const equipment = [
...new Set(
[record.manufacturer, record.operator, record.cameraType]
@@ -74,7 +75,8 @@ export function alprLabelDetails(record, source) {
* @param {function(number, number): (number|null)} [heightAt] Optional height
* for the two far corners (degrees lat, lon), so the wedge follows a slope
* instead of floating level from the apex; falls back to the apex height.
* @returns {Array<Cesium.Cartesian3>|null} Apex, left and right corners.
* @returns {Array<{x: number, y: number, z: number}>|null} Apex, left and
* right corners, ECEF.
*/
export function directionWedgePositions(record, heightM = 0, heightAt = null) {
if (!Number.isFinite(record.directionDeg)) return null;
@@ -95,13 +97,9 @@ export function directionWedgePositions(record, heightM = 0, heightAt = null) {
return Number.isFinite(height) ? height : heightM;
};
return [
Cesium.Cartesian3.fromDegrees(record.longitude, record.latitude, heightM),
Cesium.Cartesian3.fromDegrees(left.longitude, left.latitude, corner(left)),
Cesium.Cartesian3.fromDegrees(
right.longitude,
right.latitude,
corner(right),
),
fromDegrees(record.longitude, record.latitude, heightM),
fromDegrees(left.longitude, left.latitude, corner(left)),
fromDegrees(right.longitude, right.latitude, corner(right)),
];
}
+9 -2
View File
@@ -43,7 +43,11 @@ test('passive Contacts releases its installation anchor and subject refresh cann
const subject = createSubject({ state, services, parts });
subject.refreshSelectedSubject();
assert.equal(anchors.length, 1);
assert.ok(anchors[0] instanceof Cesium.Cartesian3);
assert.deepEqual(
{ ...anchors[0] },
{ x: position.x, y: position.y, z: position.z },
);
assert.notEqual(anchors[0], position, 'a copy, not the subject’s own');
controls.setParams({ passive: true });
assert.equal(anchors.at(-1), null);
const released = anchors.length;
@@ -57,5 +61,8 @@ test('passive Contacts releases its installation anchor and subject refresh cann
controls.setParams({ passive: false });
assert.equal(activations, 1);
subject.refreshSelectedSubject();
assert.ok(anchors.at(-1) instanceof Cesium.Cartesian3);
assert.deepEqual(
{ ...anchors.at(-1) },
{ x: position.x, y: position.y, z: position.z },
);
});
+1
View File
@@ -23,6 +23,7 @@ export function createControls({ state: layerState, services, parts, source }) {
attachDataManager(dataManager) {
layerState.dataManager = dataManager;
parts.dependencies.watchAdoptions(dataManager);
},
setParams(params = {}) {
+36
View File
@@ -17,11 +17,25 @@ export function createDependencies({
parts.subject.refreshSelectedSubject(true);
return;
}
if (adoptSelectedVessel()) return;
if (layerState.autoFocusRetryPending) {
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
}
}
/**
* Take the selected AIS vessel as the subject, as its selection would have
* had Contacts been on. A followed flight is checked first by the callers.
* @returns {boolean} Whether a vessel became the subject.
*/
function adoptSelectedVessel() {
const vessel = parts.subject.currentSelectedVesselSubject?.();
if (!vessel) return false;
layerState.autoFocusRetryPending = false;
parts.subject.selectSubject(vessel);
return Boolean(layerState.subject);
}
async function enableDependencies(activationId = layerState.activationId) {
const aircraftPending = [];
for (const layerId of DEPENDENCIES) {
@@ -79,12 +93,32 @@ export function createDependencies({
});
}
/**
* Give up a dependency the user adopts. A direct selection, or the Cockpit
* riding one of its aircraft, promotes a layer Contacts turned on into the
* user's own (`DataLayerManager.adoptLayerVisibility`). Releasing it when
* Contacts goes off would tear down that track or Cockpit before the
* Context restore could put the layer back.
*/
function relinquishAdoptedDependency(change) {
if (change?.type === 'visibility' && change.adopted && change.enabled)
layerState.ownedDependencies.delete(change.layerId);
}
/** Follow one manager's adoptions; null stops following. */
function watchAdoptions(dataManager) {
layerState.unwatchAdoptions?.();
layerState.unwatchAdoptions =
dataManager?.subscribe?.(relinquishAdoptedDependency) || null;
}
function activateOperationalContext() {
const activationId = ++layerState.activationId;
layerState.autoFocusRetryPending = false;
const initialTrackedSubject = parts.subject.currentTrackedFlightSubject();
if (initialTrackedSubject)
parts.subject.selectSubject(initialTrackedSubject);
else adoptSelectedVessel();
return enableDependencies(activationId)
.then(() => {
if (
@@ -102,6 +136,7 @@ export function createDependencies({
parts.subject.selectSubject(layerState.subject);
return;
}
if (adoptSelectedVessel()) return;
if (layerState.autoFocusAttempted) return;
layerState.autoFocusRetryPending = !parts.focus.focusAttentionTarget();
})
@@ -113,6 +148,7 @@ export function createDependencies({
refreshAfterDeferredDependency,
enableDependencies,
releaseOwnedDependencies,
watchAdoptions,
activateOperationalContext,
};
}
@@ -0,0 +1,190 @@
// src/layers/awareness/directionOverlay.test.mjs — the Global Context compass
// and contact bearings are presented to subscribers and rendered from a store
// inside the viewer's container.
import '../../testSupport/registerDom.mjs';
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createApp, nextTick } from 'vue';
import { createPinia } from 'pinia';
import { useAwarenessDirectionStore } from '../../ui/stores/awarenessDirection.js';
import AwarenessDirection from '../../ui/views/panels/AwarenessDirection.vue';
import { createState } from './state.js';
import { createRendering } from './rendering.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
/** The rendering part over a subject with one military contact due east. */
function overlay(screenAngle) {
const state = createState({ services: {} });
const container = document.body.appendChild(document.createElement('div'));
const subject = Cesium.Cartesian3.fromDegrees(0, 0, 1000);
const camera = fakeCameraPort({
pose: { heading: 0, right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } },
});
const viewer = {
container,
get canvas() {
return this.scene?.canvas;
},
scene: { canvas: { clientWidth: 800, clientHeight: 600 } },
};
bindRenderer(viewer, { camera: camera.port });
Object.assign(state, {
viewer,
enabled: true,
subject: { position: subject, layerId: 'military' },
results: {
cohorts: [
{
id: 'military',
summary: {
nearest: [
{
callsign: 'RCH123',
position: Cesium.Cartesian3.fromDegrees(0.05, 0, 1000),
distanceM: 5500,
track: 90,
},
],
},
},
],
},
cohortPages: new Map(),
});
const rendering = createRendering({
state,
services: {
geometry: {
getKeyholeGeometry: () => ({ centerX: 400, centerY: 300, radius: 250 }),
celestialScreenAngle:
screenAngle ||
((x, y) => ({
angle: Math.atan2(-y, x),
opacity: 1,
stable: true,
})),
},
render: { governorRequestRender() {} },
},
parts: {},
});
return { state, container, rendering, camera };
}
test('the overlay publishes the compass and the nearest contact bearings', () => {
const { rendering, container } = overlay();
const views = [];
rendering.subscribeDirectionOverlay((view) => views.push(view));
assert.deepEqual(views, [null]);
rendering.updateDirectionOverlay();
const view = views.at(-1);
assert.ok(view.container === container);
assert.equal(view.hidden, false);
// The compass sits at 66% of the 250px keyhole: 165px.
assert.equal(view.ring.width, '330px');
assert.equal(view.ring['--compass-rotation'], '0deg');
assert.equal(view.heading.text, 'HDG 000°');
assert.deepEqual(
view.labels.map((label) => label.label),
['N', 'E', 'S', 'W'],
);
assert.equal(view.labels[0].left, '400px');
const [marker, second] = view.markers;
assert.equal(marker.hidden, false);
assert.match(marker.caption.text, /^RCH123 · .+\nBRG 090° · CRS 090°$/);
assert.equal(marker.arrow.opacity, '1');
assert.equal(second.hidden, true);
// An unchanged frame publishes nothing.
const count = views.length;
rendering.updateDirectionOverlay();
assert.equal(views.length, count);
rendering.hideDirectionOverlay();
assert.equal(views.at(-1).hidden, true);
assert.equal(views.at(-1).heading.text, 'HDG 000°', 'placement is kept');
rendering.removeDirectionOverlay();
assert.equal(views.at(-1), null);
});
test('an unstable frame keeps the last stable bearing, until the overlay is removed', () => {
const answers = [
{ angle: 1, opacity: 1, stable: true },
{ angle: 2, opacity: 0.5, stable: false },
];
const previous = [];
const { state, rendering, camera } = overlay((x, y, last) => {
previous.push(last);
return answers.shift() ?? { angle: last ?? 0, opacity: 1, stable: true };
});
rendering.updateDirectionOverlay();
assert.equal(state.directionAngles[0], 1);
// The heading turns, so the next frame recomputes the contact.
camera.setPose({ heading: 0.1 });
rendering.updateDirectionOverlay();
assert.equal(previous[1], 1, 'the unstable frame is given the last angle');
assert.equal(state.directionAngles[0], 1, 'and does not replace it');
rendering.removeDirectionOverlay();
rendering.updateDirectionOverlay();
assert.equal(previous[2], 0, 'a rebuilt overlay starts afresh');
});
test('the scene chrome view renders the published overlay in its container', async (t) => {
document.body.replaceChildren();
const pinia = createPinia();
const store = useAwarenessDirectionStore(pinia);
const app = createApp(AwarenessDirection).use(pinia);
app.mount(document.body.appendChild(document.createElement('div')));
t.after(() => app.unmount());
const { rendering, container } = overlay();
rendering.subscribeDirectionOverlay((view) => store.publish(view));
rendering.ensureDirectionOverlay();
await nextTick();
const root = container.querySelector('#military-awareness-direction-overlay');
assert.equal(root.hidden, true);
assert.equal(root.getAttribute('aria-hidden'), 'true');
assert.deepEqual(
[...root.children].map((child) => child.className),
[
'military-awareness-compass-label cardinal-n',
'military-awareness-compass-label cardinal-e',
'military-awareness-compass-label cardinal-s',
'military-awareness-compass-label cardinal-w',
'military-awareness-compass-ring',
'military-awareness-compass-heading',
'military-awareness-direction-marker',
'military-awareness-direction-marker',
'military-awareness-direction-marker',
],
);
assert.equal(root.children[0].dataset.bearing, '0');
assert.equal(root.children[0].getAttribute('style'), null);
rendering.updateDirectionOverlay();
await nextTick();
assert.equal(root.hidden, false);
const ring = root.querySelector('.military-awareness-compass-ring');
assert.equal(ring.style.getPropertyValue('--compass-rotation'), '0deg');
assert.equal(
root.querySelector('.military-awareness-compass-heading').textContent,
'HDG 000°',
);
const [marker, second] = root.querySelectorAll(
'.military-awareness-direction-marker',
);
assert.equal(marker.hidden, false);
assert.equal(
marker.querySelector('.military-awareness-direction-arrow').textContent,
'➜',
);
assert.match(
marker.querySelector('.military-awareness-direction-label').textContent,
/^RCH123 · /,
);
assert.equal(second.hidden, true);
rendering.removeDirectionOverlay();
await nextTick();
assert.equal(
container.querySelector('#military-awareness-direction-overlay'),
null,
);
});
+14 -16
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { VESSEL_FOCUS_RADIUS_M } from './policy.js';
import { cameraOf, findCamera } from '../../render/rendererOf.js';
import { clone, distance } from '../../geo/index.js';
export function createFocus({ state: layerState, services, parts, source }) {
const flightsLayer = services.flights;
@@ -45,9 +46,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
)
return true;
announceNavigationAuthority('context-vessel-focus');
layerState.viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
{ duration: 1.4 },
cameraOf(layerState.viewer).flyToBounds(
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
{ durationS: 1.4 },
);
return true;
}
@@ -74,7 +75,7 @@ export function createFocus({ state: layerState, services, parts, source }) {
layerId,
id: String(known.id || known.mmsi),
label: known.label || known.name || known.callsign || String(id),
position: Cesium.Cartesian3.clone(known.position),
position: clone(known.position),
});
return true;
}
@@ -106,13 +107,13 @@ export function createFocus({ state: layerState, services, parts, source }) {
/**
* Pick the observed candidate closest to the current view. This is intentionally
* a navigation preference, not a risk, capability, or affiliation calculation.
* @param {Array<{position: Cesium.Cartesian3}>} candidates Observed candidates.
* @param {Array<{position: {x: number, y: number, z: number}}>} candidates Observed candidates.
* @returns {Object|null} The best currently observable candidate.
*/
function closestToCurrentView(candidates) {
if (!Array.isArray(candidates) || !candidates.length) return null;
const cameraPosition = layerState.viewer?.camera?.positionWC;
const cameraPosition = findCamera(layerState.viewer)?.pose()?.position;
if (!cameraPosition)
return candidates.find((candidate) => candidate?.position) || null;
@@ -120,13 +121,10 @@ export function createFocus({ state: layerState, services, parts, source }) {
let closestDistance = Infinity;
for (const candidate of candidates) {
if (!candidate?.position) continue;
const distance = Cesium.Cartesian3.distance(
cameraPosition,
candidate.position,
);
if (Number.isFinite(distance) && distance < closestDistance) {
const metres = distance(cameraPosition, candidate.position);
if (Number.isFinite(metres) && metres < closestDistance) {
closest = candidate;
closestDistance = distance;
closestDistance = metres;
}
}
return closest;
@@ -180,9 +178,9 @@ export function createFocus({ state: layerState, services, parts, source }) {
announceNavigationAuthority('context-vessel-autofocus', {
cancelPendingSelection: false,
});
layerState.viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(vessel.position, VESSEL_FOCUS_RADIUS_M),
{ duration: 1.6 },
cameraOf(layerState.viewer).flyToBounds(
{ center: vessel.position, radius: VESSEL_FOCUS_RADIUS_M },
{ durationS: 1.6 },
);
return true;
}
+1 -1
View File
@@ -150,7 +150,7 @@ export function createHistory({ state: layerState, services, parts, source }) {
return (
items.find(
(item) =>
String(item?.icao24 || item?.mmsi || item?.id) === String(subject.id),
String(item?.icao24 || item?.id || item?.mmsi) === String(subject.id),
) || subject
);
}
+12 -4
View File
@@ -13,7 +13,14 @@ import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
/** Construct one layer with its own scene state and supplied application services. */
/**
* Construct one layer with its own scene state and supplied application services.
*
* Its context rim is a renderer draw set (`drawOf(viewer)`) and its flights
* go through `cameraOf`. Given a Cesium viewer with no
* renderer bound, the caller loads the package's `./render/cesium/unbound`
* export first.
*/
export function createAwarenessLayer({ services, source }) {
const state = createState({ services });
const parts = {};
@@ -51,12 +58,13 @@ export function createAwarenessLayer({ services, source }) {
parts.queries.collectAircraftProximityWindow,
_getAwarenessNavigationStateForTest:
parts.testing._getAwarenessNavigationStateForTest,
_getAwarenessPanelRendersForTest:
parts.testing._getAwarenessPanelRendersForTest,
canNavigateAwarenessNext: parts.navigation.canNavigateAwarenessNext,
historySubjectSnapshot: parts.history.historySubjectSnapshot,
findCompatibleHistoryIndex: parts.history.findCompatibleHistoryIndex,
awarenessPanelControlKey: parts.panel.awarenessPanelControlKey,
captureAwarenessPanelFocus: parts.panel.captureAwarenessPanelFocus,
restoreAwarenessPanelFocus: parts.panel.restoreAwarenessPanelFocus,
subscribePanel: parts.panel.subscribePanel,
subscribeDirectionOverlay: parts.rendering.subscribeDirectionOverlay,
awarenessResultsAreLive: parts.panel.awarenessResultsAreLive,
awarenessNeedsContinuousRender:
parts.model.awarenessNeedsContinuousRender,
+131 -32
View File
@@ -1,4 +1,5 @@
import { cameraPoseSignature } from '../../data/iconOrientation.js';
import { canvasOf, findCamera, findFrame } from '../../render/rendererOf.js';
import { AWARENESS_RANGE_PULSE } from './policy.js';
export function createLifecycle({
state: layerState,
@@ -9,16 +10,102 @@ export function createLifecycle({
const { holdContinuousRender, releaseContinuousRender } = services.render;
/**
* Quantized camera-pose signature, or '' when the camera cannot report a full
* pose yet. An unknown pose reads as PARKED, so a camera that is still coming
* up can never be mistaken for continuous movement.
* @param {Cesium.Camera|null|undefined} camera
* Note the user handling the map's camera (pointer, wheel or touch on the
* renderer's canvas, where its camera controls listen), so a camera move
* the user made can wake the range pulses and one the app made (tracking,
* cockpit, orbit, a fly-to) does not. Keys are left out: the camera
* controls read none, and typing elsewhere must not count. Nor does input
* while the camera controls are suspended: the cockpit (or a gizmo drag,
* or a drawing tool) owns the camera then, and the user's gesture moves
* nothing.
*/
function noteCameraInput(event) {
if (event?.type === 'pointermove' && !event.buttons) return;
if (!cameraInputsEnabled()) return;
layerState.lastCameraInputMs = Date.now();
if (event?.type === 'pointerdown') activePointers.add(event.pointerId);
if (event?.type === 'pointerdown' || event?.type === 'touchstart')
followGesture(true);
}
// A drag can leave the canvas, and the camera controls follow it at
// document level (in Firefox, and wherever there are no pointer events).
// So does this,
// from a gesture's start on the canvas to its end, so a long gesture keeps
// the input window open the whole way.
const GESTURE_MOVE_EVENTS = ['pointermove', 'touchmove'];
const GESTURE_END_EVENTS = [
'pointerup',
'pointercancel',
'touchend',
'touchcancel',
];
let followingGesture = false;
const activePointers = new Set();
function followGesture(on) {
if (followingGesture === on) return;
followingGesture = on;
if (!on) activePointers.clear();
const listen = on ? 'addEventListener' : 'removeEventListener';
for (const type of GESTURE_MOVE_EVENTS)
globalThis.document?.[listen]?.(type, noteCameraInput, { passive: true });
for (const type of GESTURE_END_EVENTS)
globalThis.document?.[listen]?.(type, endGesture, { passive: true });
globalThis[listen]?.('blur', dropGesture);
globalThis.document?.[listen]?.('visibilitychange', dropGesture);
}
// A gesture ends with its last contact: lifting one finger of a pinch
// leaves the camera controls a one-finger drag.
function endGesture(event) {
noteCameraInput(event);
activePointers.delete(event?.pointerId);
if (activePointers.size || event?.touches?.length) return;
followGesture(false);
}
// Losing the window or the page mid-gesture means its end may never
// arrive here, so stop following it and drop its pending input.
function dropGesture(event) {
if (
event?.type === 'visibilitychange' &&
document.visibilityState !== 'hidden'
)
return;
followGesture(false);
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
}
function cameraInputsEnabled() {
return findCamera(layerState.viewer)?.controls?.enabled !== false;
}
const CAMERA_INPUT_EVENTS = [
'pointerdown',
'pointermove',
'pointerup',
'wheel',
'touchstart',
];
/**
* Quantized camera-pose signature (position to ~10 m, angles to ~0.06
* degrees), or '' when the camera cannot report a full pose yet. An unknown
* pose reads as PARKED, so a camera that is still coming up can never be
* mistaken for continuous movement.
* @param {object|null|undefined} viewer
* @returns {string}
*/
function cameraMotionSignature(camera) {
if (!camera?.positionWC || !Number.isFinite(camera.heading)) return '';
return cameraPoseSignature(camera);
function cameraMotionSignature(viewer) {
const pose = findCamera(viewer)?.pose();
const p = pose?.position;
if (!p || !Number.isFinite(pose.heading)) return '';
return (
`${Math.round(p.x / 10)}:${Math.round(p.y / 10)}:${Math.round(p.z / 10)}:` +
`${pose.heading.toFixed(3)}:${pose.pitch.toFixed(3)}:${pose.roll.toFixed(3)}`
);
}
/**
@@ -50,18 +137,34 @@ export function createLifecycle({
'gev:awareness-subject-cleared',
layerState.subjectClearListener,
);
layerState.preRenderRemover =
layerState.viewer.scene.preRender.addEventListener(() => {
const input = canvasOf(layerState.viewer);
for (const type of CAMERA_INPUT_EVENTS)
input?.addEventListener?.(type, noteCameraInput, { passive: true });
layerState.cameraInputTarget = input ?? null;
layerState.preRenderRemover = findFrame(layerState.viewer)?.on(
'preRender',
() => {
if (!layerState.enabled) return;
const now = Date.now();
// "Did the camera move" uses the SAME quantized pose signature the fleet
// rotation pass gates on (iconOrientation.cameraPoseSignature) rather than
// camera.changed, whose granularity is globally degraded by other layers
// mutating camera.percentageChanged.
const poseSig = cameraMotionSignature(layerState.viewer.camera);
// Another owner took the camera: a gesture begun before it did must
// not wake the pulses on that owner's first move.
if (!cameraInputsEnabled())
layerState.lastCameraInputMs = Number.NEGATIVE_INFINITY;
// "Did the camera move" uses the same quantization as the fleet
// rotation pass's cameraPoseSignature (render/cesium/iconOrientation;
// keep the two in step), read from the camera port's pose.
const poseSig = cameraMotionSignature(layerState.viewer);
if (poseSig !== layerState.lastCameraPoseSig) {
layerState.lastCameraPoseSig = poseSig;
layerState.lastCameraPoseChangeMs = now;
// A camera move the user made runs the range pulses again; parked,
// or moved by the app (tracking, cockpit, orbit, a fly-to), they
// rest.
if (
now - layerState.lastCameraInputMs <
AWARENESS_RANGE_PULSE.inputWakeMs
)
parts.rendering.wakePulses();
}
const decision = parts.model.awarenessRefreshDecision({
nowMs: now,
@@ -86,7 +189,8 @@ export function createLifecycle({
} else {
parts.rendering.scheduleDirectionOverlayUpdate();
}
});
},
);
layerState.runtimeListenersAttached = true;
}
@@ -108,6 +212,13 @@ export function createLifecycle({
'gev:awareness-subject-cleared',
layerState.subjectClearListener,
);
for (const type of CAMERA_INPUT_EVENTS)
layerState.cameraInputTarget?.removeEventListener?.(
type,
noteCameraInput,
);
layerState.cameraInputTarget = null;
followGesture(false);
}
layerState.preRenderRemover?.();
layerState.preRenderRemover = null;
@@ -229,27 +340,15 @@ export function createLifecycle({
destroy() {
this.disable();
detachRuntimeListeners();
layerState.panel?.removeEventListener(
'click',
layerState.panelClickListener,
);
layerState.panelClickListener = null;
if (layerState.panelOwned) layerState.panel?.remove();
else if (layerState.panel) layerState.panel.replaceChildren();
layerState.panel = null;
layerState.panelOwned = false;
layerState.directionRoot?.remove();
layerState.directionRoot = null;
layerState.compassRing = null;
layerState.compassLabels = [];
layerState.compassHeading = null;
layerState.directionMarkers = [];
layerState.panelMarkup = '';
parts.panel.clearPanel();
parts.rendering.removeDirectionOverlay();
parts.rendering.disposeVisual();
layerState.subjectListener = null;
layerState.contextListener = null;
layerState.clearListener = null;
layerState.subjectClearListener = null;
layerState.viewer = null;
parts.dependencies.watchAdoptions(null);
layerState.dataManager = null;
},
};
+1
View File
@@ -196,6 +196,7 @@ export function createModel({ state: layerState, services, parts, source }) {
id: cohort.id,
label: cohort.label,
source: cohort.source,
sourceStatus: cohort.sourceStatus || null,
coverage: cohort.coverage || null,
relationship: cohort.summary.relationship,
count: cohort.summary.count,
+172 -165
View File
@@ -2,9 +2,12 @@ import {
formatAwarenessLabel,
AWARENESS_RADIUS_M,
} from '../../data/militaryAwarenessEngine.js';
import { formatNumber, t, translateKnown } from '../../i18n/index.js';
import { formatNumber, onLocaleChange, t } from '../../i18n/index.js';
import { sourceStatusLabel } from '../../ui/layerNames.js';
import { translateStatusMessage } from '../../ui/statusText.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { AWARENESS_PAGE_SIZE, AWARENESS_PAGE_ROTATE_MS } from './policy.js';
import { distanceParts } from '../../data/distanceFormat.js';
/** Format a cohort total without presenting a retained cap as exact. */
export function formatAwarenessCount(summary = {}) {
@@ -25,13 +28,12 @@ function presentAwarenessCount(summary = {}) {
}
/** A distance as the panel shows it: 850 m, 4.6 km, 120 km, in the UI language. */
function presentAwarenessDistance(meters) {
if (!Number.isFinite(meters) || meters < 0) return '—';
if (meters < 1000) return formatQuantity(Math.round(meters), 'm');
const digits = meters < 10000 ? 1 : 0;
return formatQuantity(meters / 1000, 'km', {
minimumFractionDigits: digits,
maximumFractionDigits: digits,
export function presentAwarenessDistance(meters) {
const parts = distanceParts(meters);
if (!parts) return '—';
return formatQuantity(parts.value, parts.unit, {
minimumFractionDigits: parts.digits,
maximumFractionDigits: parts.digits,
});
}
@@ -39,79 +41,98 @@ function presentAwarenessDistance(meters) {
function presentAwarenessReason(summary = {}) {
return summary.reasonTemplate
? t(summary.reasonTemplate, summary.reasonValues)
: translateKnown(summary.reason || '');
: translateStatusMessage(summary.reason || '');
}
export function createPanel({ state: layerState, services, parts, source }) {
/**
* The Contacts panel as a view renders it. The layer presents a plain view
* object (`standby`, `results` or `empty`) and publishes it to subscribers;
* Core's AwarenessPanel component renders it and calls the layer's
* navigation methods. Text arrives in the UI language.
*/
export function createPanel({ state: layerState, parts }) {
/** Publish a fresh view unless it is the one already shown. */
function publish(view) {
const signature = JSON.stringify(view);
if (layerState.panelSignature === signature) return;
layerState.panelSignature = signature;
layerState.panelView = view;
for (const listener of [...layerState.panelListeners]) listener(view);
}
/**
* Receive every published view, starting with the current one.
* @param {(view: object) => void} listener
* @returns {() => void} Unsubscribe.
*/
function subscribePanel(listener) {
layerState.panelListeners.add(listener);
if (layerState.panelView) listener(layerState.panelView);
return () => layerState.panelListeners.delete(listener);
}
/** The panel shows layer views from the first enable or result onwards. */
function ensurePanel() {
if (layerState.panel) return layerState.panel;
const existing = document.getElementById('military-awareness-panel');
const panel = existing || document.createElement('aside');
layerState.panelOwned = !existing;
if (!existing) {
panel.id = 'military-awareness-panel';
}
layerState.panelClickListener = (event) => {
const action = event.target.closest('button[data-awareness-action]');
if (action) {
event.preventDefault();
if (action.dataset.awarenessAction === 'previous')
parts.history.navigateHistory(-1, { origin: 'user' });
if (action.dataset.awarenessAction === 'next')
parts.history.navigateHistory(1, { origin: 'user' });
if (action.dataset.awarenessAction === 'focus')
parts.focus.focusCurrentSubject({ origin: 'user' });
return;
}
const target = event.target.closest(
'button[data-awareness-layer][data-awareness-id]',
);
if (!target) return;
event.preventDefault();
parts.focus.requestFocus(
target.dataset.awarenessLayer,
target.dataset.awarenessId,
false,
{ origin: 'user' },
);
};
panel.addEventListener('click', layerState.panelClickListener);
if (!existing) document.body.appendChild(panel);
layerState.panel = panel;
return panel;
layerState.panelShown = true;
// A shown view is worded again in a new locale.
layerState.offPanelLocale ??= onLocaleChange(() => {
const kind = layerState.panelView?.kind;
if (kind === 'results') renderResults();
else if (kind === 'standby') hidePanel();
});
}
function hidePanel() {
if (layerState.panel) {
const markup = `<div class="military-awareness-standby">
<strong>${layerState.enabled ? t('CONTEXT READY') : t('GLOBAL CONTEXT OFF')}</strong>
<span>${layerState.enabled ? t('SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION') : t('ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY')}</span>
</div>`;
layerState.panel.hidden = false;
if (layerState.panelMarkup !== markup) {
layerState.panel.innerHTML = markup;
layerState.panelMarkup = markup;
}
}
if (layerState.directionRoot) layerState.directionRoot.hidden = true;
if (layerState.panelShown)
publish({
kind: 'standby',
title: layerState.enabled
? t('CONTEXT READY')
: t('GLOBAL CONTEXT OFF'),
text: layerState.enabled
? t('SELECT A FLIGHT, VESSEL, OR MAPPED INSTALLATION')
: t('ENABLE TO LOAD OBSERVED / MAPPED PROXIMITY'),
});
parts.rendering.hideDirectionOverlay();
}
function rowHtml(cohort) {
/** Clear the panel when the layer is destroyed. */
function clearPanel() {
if (layerState.panelShown) publish({ kind: 'empty' });
layerState.offPanelLocale?.();
layerState.offPanelLocale = null;
layerState.panelShown = false;
layerState.panelView = null;
layerState.panelSignature = '';
}
function presentRow(cohort) {
const summary = cohort.summary;
const count = presentAwarenessCount(summary);
const page = layerState.cohortPages.get(cohort.id) || 0;
const nearest = summary.nearest
.slice(page, page + AWARENESS_PAGE_SIZE)
.map((item) => {
.map((item, index) => {
const label = formatAwarenessLabel(item);
const targetId = item.icao24 || item.mmsi || item.id;
if (!targetId) {
return `<li><span class="military-awareness-target unavailable" aria-label="${t('Unavailable')}">${escapeHtml(label)} <span>${presentAwarenessDistance(item.distanceM)}</span></span></li>`;
}
const targetId = item.icao24 || item.id || item.mmsi;
const distance = presentAwarenessDistance(item.distanceM);
if (!targetId)
return {
key: `unavailable:${page + index}`,
label,
distance,
ariaLabel: t('Unavailable'),
};
const accessibleLabel = label === '—' ? t('Unavailable') : label;
return `<li><button type="button" class="military-awareness-target" data-awareness-layer="${escapeHtml(cohort.id)}" data-awareness-id="${escapeHtml(targetId)}" aria-label="${escapeHtml(t('Focus {label}', { label: accessibleLabel }))}">${escapeHtml(label)} <span>${presentAwarenessDistance(item.distanceM)}</span></button>${namedAreasHtml(item.memberNames)}</li>`;
})
.join('');
return {
key: `target:${cohort.id}:${targetId}`,
layer: cohort.id,
targetId: String(targetId),
label,
distance,
ariaLabel: t('Focus {label}', { label: accessibleLabel }),
names: presentNames(item.memberNames),
};
});
const pageCount = Math.max(
1,
Math.ceil(summary.nearest.length / AWARENESS_PAGE_SIZE),
@@ -120,109 +141,99 @@ export function createPanel({ state: layerState, services, parts, source }) {
pageCount > 1
? ` · ${Math.floor(page / AWARENESS_PAGE_SIZE) + 1}/${pageCount}`
: '';
const coverage = cohort.coverage ? ` · ${escapeHtml(cohort.coverage)}` : '';
return `<section class="military-awareness-row ${summary.relationship.toLowerCase()}">
<div><strong>${escapeHtml(cohort.label)}</strong><b aria-live="polite">${count}${pageLabel}</b></div>
<small>${escapeHtml(cohort.source)}${coverage} · ${escapeHtml(presentAwarenessReason(summary))}</small>
${nearest ? `<ul>${nearest}</ul>` : ''}
</section>`;
const coverage = cohort.coverage ? ` · ${cohort.coverage}` : '';
return {
id: cohort.id,
relationship: summary.relationship.toLowerCase(),
label: cohort.label,
count: `${presentAwarenessCount(summary)}${pageLabel}`,
detail: `${sourceStatusLabel(cohort.source, cohort.sourceStatus)}${coverage} · ${presentAwarenessReason(summary)}`,
nearest,
};
}
function navigationControlsHtml() {
const canPrevious = layerState.navigationIndex > 0;
return `<div class="military-awareness-controls" role="group" aria-label="${t('Global Context navigation')}">
<button type="button" data-awareness-action="previous" title="${t('Previous — prior visited contact in the 250 km window')}"${canPrevious ? '' : ' disabled'}>${t('PREVIOUS')}</button>
<button type="button" data-awareness-action="focus">${t('FOCUS')}</button>
<button type="button" data-awareness-action="next" title="${t('Next — nearest unvisited contact in the 250 km window')}"${parts.navigation.canNavigateNext() ? '' : ' disabled'}>${t('NEXT')}</button>
</div>`;
function presentNavigation() {
return {
label: t('Global Context navigation'),
previous: {
text: t('PREVIOUS'),
title: t('Previous — prior visited contact in the 250 km window'),
disabled: !(layerState.navigationIndex > 0),
},
focus: { text: t('FOCUS') },
next: {
text: t('NEXT'),
title: t('Next — nearest unvisited contact in the 250 km window'),
disabled: !parts.navigation.canNavigateNext(),
},
};
}
/** Stable identity for a delegated Contacts-panel button across live repaints. */
function awarenessPanelControlKey(element) {
const control = element?.closest?.(
'button[data-awareness-action], button[data-awareness-layer][data-awareness-id]',
);
if (!control) return null;
if (control.dataset.awarenessAction)
return `action:${control.dataset.awarenessAction}`;
return `target:${control.dataset.awarenessLayer}:${control.dataset.awarenessId}`;
}
/** Capture stable identity so a live repaint can restore only the same control. */
function captureAwarenessPanelFocus(
panel,
activeElement = document.activeElement,
) {
if (!panel?.contains?.(activeElement)) return null;
if (activeElement?.matches?.('[data-awareness-focus-continuation]')) {
return { key: 'continuation' };
}
const key = awarenessPanelControlKey(activeElement);
if (!key) return null;
return { key };
}
/** Restore the same control, or continue beyond the list when it is no longer rendered. */
function restoreAwarenessPanelFocus(panel, snapshot) {
if (!panel || !snapshot) return null;
const continuation = panel.querySelector(
'[data-awareness-focus-continuation]',
);
const controls = [
...panel.querySelectorAll(
'button[data-awareness-action], button[data-awareness-layer][data-awareness-id]',
),
].filter((control) => !control.disabled);
const retained =
snapshot.key === 'continuation'
? continuation
: controls.find(
(control) => awarenessPanelControlKey(control) === snapshot.key,
);
const target = retained || continuation;
target?.focus?.({ preventScroll: true });
return target || null;
}
function escapeHtml(value) {
return String(value ?? '').replace(
/[&<>'"]/g,
(char) =>
({
'&': '&amp;',
'<': '&lt;',
'>': '&gt;',
"'": '&#39;',
'"': '&quot;',
})[char],
);
}
function namedAreasHtml(names) {
function presentNames(names) {
return names?.length
? `<details class="military-awareness-names"><summary>${escapeHtml(t('Named areas ({n})', { n: formatNumber(names.length) }))}</summary><div>${names.map((name) => escapeHtml(name)).join('<br>')}</div></details>`
? {
summary: t('Named areas ({n})', { n: formatNumber(names.length) }),
names: [...names].map((name) => String(name ?? '')),
}
: null;
}
/** The credit line: the photographer, and an open photo's licence. A
* photo whose answer names no photographer shows no photographer. */
function photoCredit(photo) {
if (photo.licence)
return photo.photographer
? t('Photo: {photographer} · {licence}', {
photographer: photo.photographer,
licence: photo.licence,
})
: t('Photo · {licence}', { licence: photo.licence });
return photo.photographer
? t('Photo © {photographer}', { photographer: photo.photographer })
: '';
}
/** The subject's photo with its credit, or null. The subject
* refresh resolves it; only the subject it was resolved for shows it. */
function presentPhoto(subject) {
const held = layerState.subjectPhoto;
if (
!held ||
held.layerId !== subject.layerId ||
String(held.id) !== String(subject.id)
)
return null;
const { photo } = held;
return {
src: photo.src,
width: photo.width ?? null,
height: photo.height ?? null,
link: photo.link,
credit: photoCredit(photo),
};
}
function renderResults() {
if (!layerState.enabled || !layerState.results) return hidePanel();
const panel = ensurePanel();
ensurePanel();
layerState.panelRenders += 1;
const { subject, cohorts } = layerState.results;
const markup = `<div class="military-awareness-subject">${escapeHtml(subject.label)} · ${escapeHtml(t('{distance} FLIGHT / VESSEL WINDOW', { distance: presentAwarenessDistance(AWARENESS_RADIUS_M) }))}</div>
${namedAreasHtml(subject.memberNames)}
${navigationControlsHtml()}
${cohorts.map(rowHtml).join('')}
<p class="military-awareness-note" tabindex="-1" data-awareness-focus-continuation>${t('Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.')}</p>`;
panel.hidden = false;
if (layerState.panelMarkup !== markup) {
const focusSnapshot = captureAwarenessPanelFocus(panel);
panel.innerHTML = markup;
layerState.panelMarkup = markup;
restoreAwarenessPanelFocus(panel, focusSnapshot);
}
const windowLabel = t('{distance} FLIGHT / VESSEL WINDOW', {
distance: presentAwarenessDistance(AWARENESS_RADIUS_M),
});
publish({
kind: 'results',
subject: `${subject.label} · ${windowLabel}`,
subjectIdentity: { layerId: subject.layerId, id: subject.id },
subjectLabel: subject.label,
subjectNames: presentNames(subject.memberNames),
photo: presentPhoto(subject),
navigation: presentNavigation(),
rows: cohorts.map(presentRow),
note: t(
'Open-source mapped/observed context. Missing broadcasts, unloaded map areas, or unmapped sites are not evidence of absence.',
),
});
}
function rotateAwarenessPages() {
@@ -276,14 +287,10 @@ export function createPanel({ state: layerState, services, parts, source }) {
return cohorts.some((cohort) => Number(cohort?.summary?.count) > 0);
}
return {
subscribePanel,
ensurePanel,
hidePanel,
rowHtml,
navigationControlsHtml,
awarenessPanelControlKey,
captureAwarenessPanelFocus,
restoreAwarenessPanelFocus,
escapeHtml,
clearPanel,
renderResults,
rotateAwarenessPages,
startAwarenessPageRotation,
+211
View File
@@ -0,0 +1,211 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createPanel } from './panel.js';
import { createSubject } from './subject.js';
test('a Contacts row names its provider as the Layers panel does, with its feed state', () => {
const cohort = (id, source, sourceStatus) => ({
id,
label: id,
source,
sourceStatus,
summary: { relationship: 'OBSERVED', count: 1, nearest: [], reason: 'observed' },
});
const state = {
enabled: true,
results: {
subject: { label: 'AFR38JF' },
cohorts: [
cohort('flights', 'adsb.lol', 'fallback'),
cohort('military', 'adsb.lol', null),
cohort('ais-live-vessels', 'Datalastic', 'stale'),
],
},
cohortPages: new Map(),
panelListeners: new Set(),
panelSignature: '',
navigationIndex: 0,
};
const parts = {
navigation: { canNavigateNext: () => false },
rendering: { hideDirectionOverlay() {} },
};
createPanel({ state, parts }).renderResults();
assert.deepEqual(
state.panelView.rows.map((row) => row.detail),
['adsb.lol · FALLBACK · observed', 'adsb.lol · observed', 'Datalastic · STALE · observed'],
);
state.offPanelLocale?.();
});
const PHOTO = Object.freeze({
src: 'https://t.plnspttrs.net/1/abc123_280.jpg',
width: 280,
height: 186,
photographer: 'Jane Doe',
link: 'https://www.planespotters.net/photo/1/n123ab',
});
/** The published Contacts view for one subject and the refresh's photo. */
function photoView(subject, subjectPhoto) {
const state = {
enabled: true,
results: { subject, cohorts: [] },
subjectPhoto,
cohortPages: new Map(),
panelListeners: new Set(),
panelSignature: '',
navigationIndex: 0,
};
const parts = {
navigation: { canNavigateNext: () => false },
rendering: { hideDirectionOverlay() {} },
};
createPanel({ state, parts }).renderResults();
state.offPanelLocale?.();
return state.panelView;
}
const FLIGHT = Object.freeze({
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
});
test('the Contacts view carries the tracked flight’s photo with its credit', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: PHOTO,
});
assert.deepEqual(view.photo, {
src: PHOTO.src,
width: 280,
height: 186,
link: PHOTO.link,
credit: 'Photo © Jane Doe',
});
});
test('the Contacts view shows an uncredited photo with no credit line', () => {
const view = photoView(FLIGHT, {
layerId: 'flights',
id: 'abc123',
photo: { ...PHOTO, photographer: '' },
});
assert.equal(view.photo.src, PHOTO.src);
assert.equal(view.photo.link, PHOTO.link);
assert.equal(view.photo.credit, '');
});
test('the Contacts view has no photo without one, or with another subject’s', () => {
assert.equal(photoView(FLIGHT, null).photo, null);
assert.equal(
photoView(FLIGHT, { layerId: 'flights', id: 'def456', photo: PHOTO }).photo,
null,
);
assert.equal(
photoView(
{ layerId: 'ais-live-vessels', id: 'abc123', label: 'VESSEL' },
{ layerId: 'flights', id: 'abc123', photo: PHOTO },
).photo,
null,
);
});
test('the selected vessel shows its own photo, by its id', () => {
const asked = [];
const { resolveSubjectPhoto, subjectFromContext } = createSubject({
state: {},
services: {
flights: {},
military: {},
vessels: {
getVesselPhoto: (id) => {
asked.push(id);
return id === 'uuid-1' ? PHOTO : null;
},
},
installations: {},
},
parts: { navigation: { isFlightLayer: () => false } },
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-1' }),
PHOTO,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'uuid-2' }),
null,
);
assert.deepEqual(asked, ['uuid-1', 'uuid-2']);
const vessel = (label, mmsi) =>
subjectFromContext({
layerId: 'ais-live-vessels',
id: 'ais-uuid-1',
label,
latitude: 38.3,
longitude: -123.05,
properties: { vesselId: 'uuid-1', mmsi },
});
assert.equal(
vessel('USCGC SOCKEYE', '366999709').label,
'USCGC SOCKEYE · MMSI 366999709',
);
assert.equal(vessel('USCGC SOCKEYE', '366999709').id, 'uuid-1');
// A vessel named by its MMSI, or without one, is not given it twice.
assert.equal(vessel('MMSI 366999709', '366999709').label, 'MMSI 366999709');
assert.equal(vessel('USCGC SOCKEYE', null).label, 'USCGC SOCKEYE');
});
test('only the tracked flight has a flight photo: not an installation, a military aircraft or another flight', () => {
const tracked = {
layerId: 'flights',
id: 'abc123',
label: 'N123AB',
photo: PHOTO,
};
let current = tracked;
let lookups = 0;
const flights = {
getTrackedSubject: () => {
lookups += 1;
return current;
},
};
const military = {
getTrackedSubject: () => ({ ...tracked, layerId: 'military' }),
};
const { resolveSubjectPhoto } = createSubject({
state: {},
services: { flights, military, vessels: {}, installations: {} },
parts: {
navigation: {
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
},
});
assert.deepEqual(
resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }),
PHOTO,
);
assert.equal(lookups, 1);
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'def456' }), null);
assert.equal(
resolveSubjectPhoto({ layerId: 'ais-live-vessels', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military-installations', id: 'abc123' }),
null,
);
assert.equal(
resolveSubjectPhoto({ layerId: 'military', id: 'abc123' }),
null,
);
assert.equal(resolveSubjectPhoto(null), null);
current = null;
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
current = { ...tracked, photo: null };
assert.equal(resolveSubjectPhoto({ layerId: 'flights', id: 'abc123' }), null);
});
+91 -4
View File
@@ -1,9 +1,6 @@
export const AIRCRAFT_DEPENDENCIES = ['flights', 'military'];
export const DEFERRED_DEPENDENCIES = [
'ais-live-vessels',
'military-installations',
];
const DEFERRED_DEPENDENCIES = ['ais-live-vessels', 'military-installations'];
export const DEPENDENCIES = [
...AIRCRAFT_DEPENDENCIES,
@@ -47,6 +44,96 @@ export const AWARENESS_MAX_NAVIGATION_EXAMPLES = 10000;
export const CONTEXT_RIM_HEIGHT_M = 2500;
/** @constant The 250 km range ring around the Global Context subject.
* The old 1 px ellipse outline vanished over desert, snow and under
* the FLIR, NVG and CRT styles. A bright core inside a dark halo keeps
* luminance contrast on light and dark ground alike, and luminance is what
* the monochrome styles keep. The core is the Context panel's blue; the halo
* is the map-card ink. Widths are screen pixels; `outlineWidth` is the
* halo's width in all, half on each side.
* It is drawn as an unpickable primitive, so clicks on its edge reach the
* contacts underneath.
* While the sonar pulses run, the ring dims to `restOpacity` and flashes
* to full as each pulse reaches it, fading over `flashMs`. `restOpacity`
* keeps the 250 km edge readable between flashes, in screenshots and for
* low-vision viewers. Once the pulses rest, and without pulses (reduced
* motion, or a scene that cannot animate), it stays on screen at full. */
export const AWARENESS_RANGE_RING_STYLE = Object.freeze({
color: 'rgba(98, 181, 255, 0.95)',
outlineColor: 'rgba(4, 12, 16, 0.8)',
width: 4,
outlineWidth: 1,
segments: 128,
flashMs: 1800,
restOpacity: 0.4,
});
/** @constant Sonar-style pulses that grow slowly from the subject to the
* range ring and are almost gone when they reach it. `count` pulses share
* one `periodMs`, evenly staggered, so a new one starts every
* `periodMs / count`. Each starts at `startFraction` of the radius, fades in
* over `fadeInFraction` of its travel, then fades as (1 - travel) to the
* `fadeOutPower` down to `endOpacityFraction` of `peakOpacity`, so a pulse
* is dim but still visible when it reaches the ring and the ring flashes.
* Each front is a line `width` CSS pixels wide whose outer `outlineWidth`,
* half on each side, is a dark halo, in the ring's colours.
* Behind each line a radial gradient in the same blue fades inward over
* `gradientDepthFraction` of the radius, at most `gradientOpacity` strong,
* painted on a canvas that fills one flat ellipse at the rim. Lines and
* ellipse are unpickable, so pulses never catch a click meant for a
* contact. The ellipse is `gradientRebuildM` wider than the ring and moves
* only after the subject moves that far from where it was built, the
* canvas keeping the band concentric meanwhile; while the pulses rest the
* hidden band is left alone and catches up when they wake. The band is
* hidden while the camera is below its height, where it would sweep the
* sky.
* The pulses run for `activeMs` (three ring flashes) after a selection or
* a camera move, fading in and out over `settleMs`, then rest: the ring
* stays on screen, static, and nothing asks for frames, so a parked view
* goes quiet again. Only a camera move within `inputWakeMs` of the user
* handling the map (pointer, wheel or touch on the canvas, which covers a
* drag's inertia, while the camera controls take input) wakes them; a moving subject and the app's own camera moves
* (tracking, cockpit, orbit, a fly-to) do not. Below the band's height they
* rest too. While they run they never hold
* continuous rendering; each drawn frame arms one more step after the
* sonar's 80 ms cadence, so the two never beat. Fronts and band,
* fixed in the world, step at that cadence however many frames are
* drawn, so they look the same whether the camera moves or not; crossing
* the rim height shows or hides them at once.
* Skipped under prefers-reduced-motion. */
export const AWARENESS_RANGE_PULSE = Object.freeze({
count: 3,
periodMs: 9000,
startFraction: 0.02,
fadeInFraction: 0.08,
fadeOutPower: 1.5,
endOpacityFraction: 0.35,
peakOpacity: 0.6,
width: 3,
outlineWidth: 1,
gradientDepthFraction: 0.35,
gradientOpacity: 0.22,
gradientGranularityDeg: 0.25,
gradientRebuildM: 20000,
activeMs: 9000,
settleMs: 1200,
inputWakeMs: 1500,
});
/** @constant Sonar echoes on contact brackets. When a pulse front reaches a
* flight, military aircraft or AIS vessel in the window, the detection
* overlay draws a second bracket in `color` around that contact's own
* bracket. It starts on the bracket and spreads outward by up to `spreadPx`
* as it fades over `fadeMs`, so the frame pulses. Only `layerIds` echo;
* mapped installations have no detection bracket. */
export const AWARENESS_RANGE_ECHO = Object.freeze({
layerIds: ['flights', 'military', 'ais-live-vessels'],
fadeMs: 1400,
color: 'rgb(98, 181, 255)',
spreadPx: 8,
lineWidth: 1.75,
});
export const VESSEL_FOCUS_RADIUS_M = 3000;
export const SOURCE_LABEL = {
+11
View File
@@ -0,0 +1,11 @@
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
/**
* Format a compass direction for the awareness overlay.
* @param {number} degrees
* @returns {string}
*/
export function formatAwarenessDirection(degrees) {
if (!Number.isFinite(degrees)) return '—';
return String(roundHeadingDegrees(degrees)).padStart(3, '0');
}
@@ -0,0 +1,11 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { formatAwarenessDirection } from './presentation.js';
test('awareness bearings that round through north read 000, not 360', () => {
assert.equal(formatAwarenessDirection(359.4), '359');
assert.equal(formatAwarenessDirection(359.6), '000');
assert.equal(formatAwarenessDirection(0), '000');
assert.equal(formatAwarenessDirection(-0.4), '000');
assert.equal(formatAwarenessDirection(Number.NaN), '—');
});
+1
View File
@@ -91,6 +91,7 @@ export function createQueries({ state: layerState, services, parts, source }) {
stats.count ?? null,
stats.status || null,
stats.error || null,
stats.source || null,
];
})
.map((parts) => parts.join(':'))
+26
View File
@@ -81,3 +81,29 @@ test('Contacts excludes square corners and measures from the current moving subj
assert.equal(moved.reason, 'mapped matches within 100 km of the subject');
assert.deepEqual(installationState.contextAnchor, { latitude: 0, longitude: 0 });
});
test('Contacts cohorts carry the provider and whether it answered as a fallback or stale', () => {
const services = { installations: { getNearby: () => [], getStats: () => ({}) },
flights: { getNearby: () => [] }, military: { getNearby: () => [] }, vessels: { getNearby: () => [] } };
const parts = { navigation: { summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source) } };
parts.queries = createQueries({ state: {}, services, parts });
const subjectOwner = createSubject({ state: {}, services, parts });
const states = {
// The OpenSky proxy answers from adsb.lol when OpenSky fails.
flights: { available: true, stats: { source: 'adsb.lol', coverage: '250nm regional fallback', count: 4, lastUpdate: 1 } },
military: { available: true, stats: { source: 'adsb.lol', fallback: false, count: 2, lastUpdate: 1 } },
'ais-live-vessels': { available: true, stats: { source: 'Datalastic', stale: true, count: 3, lastUpdate: 1 } },
'military-installations': { available: true, stats: { coverage: { kind: 'subject', radiusM: 100000 } } },
};
const { cohorts } = subjectOwner.evaluateSubject({
id: 'subject', layerId: 'flights', position: Cesium.Cartesian3.fromDegrees(0, 0, 10000),
}, states);
const byId = Object.fromEntries(cohorts.map((cohort) => [cohort.id, cohort]));
assert.equal(byId.flights.source, 'adsb.lol');
assert.equal(byId.flights.sourceStatus, 'fallback');
assert.equal(byId.military.sourceStatus, null);
assert.equal(byId['ais-live-vessels'].source, 'Datalastic');
assert.equal(byId['ais-live-vessels'].sourceStatus, 'stale');
assert.equal(byId['military-installations'].sourceStatus, null);
});
+802
View File
@@ -0,0 +1,802 @@
/**
* @module layers/awareness/rangeRing
* @description The Global Context range ring and its sonar pulses, drawn
* through the renderer's draw port. The ring is a haloed line (a solid line
* with an outline) 2.5 km above the ellipsoid. While pulses run, each pulse
* front is a haloed line whose positions move each step, every
* `CYBER_SONAR_RENDER_INTERVAL_MS` whether the camera moves or not. The
* band behind the fronts is one flat ellipse at the same height filled
* with a canvas painted anew each step (a new key for new content). Nothing here is
* pickable, so a click or tap near the ring reaches the contact underneath.
* Under reduced motion, or where the renderer has no frame hooks, the ring
* alone is drawn and stays.
*/
import { CYBER_SONAR_RENDER_INTERVAL_MS } from '../../cyberSonar.js';
import { AWARENESS_RADIUS_M } from '../../data/militaryAwarenessEngine.js';
import {
AWARENESS_RANGE_ECHO,
AWARENESS_RANGE_PULSE,
AWARENESS_RANGE_RING_STYLE,
CONTEXT_RIM_HEIGHT_M,
} from './policy.js';
import {
awarenessEchoStrength,
clearAwarenessEchoField,
setAwarenessEchoField,
} from '../../awarenessEcho.js';
import { WGS84, fromRadians, toLonLatH } from '../../geo/ellipsoid.js';
import { distance, sub } from '../../geo/vector.js';
import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js';
/**
* A closed ring of positions `radiusM` along the surface from `groundCenter`,
* raised to `heightM`. Each bearing steps over a sphere with the ellipsoid's
* radius of curvature in that direction (Euler's formula), which keeps the
* ring within ~50 m of the true geodesic radius at 250 km.
* @param {{x: number, y: number, z: number}} groundCenter Ring centre on the ellipsoid.
* @param {number} radiusM Surface radius in metres.
* @param {number} heightM Height of the ring above the ellipsoid.
* @param {number} [segments] Chords around the ring.
* @returns {{x: number, y: number, z: number}[]} `segments + 1` positions;
* the last repeats the first.
*/
export function awarenessRangeRingPositions(
groundCenter,
radiusM,
heightM,
segments = AWARENESS_RANGE_RING_STYLE.segments,
) {
const { up, bearings } = ringFrame(groundCenter, segments);
const r2 = WGS84.radiiSquared;
const positions = new Array(bearings.length);
for (let i = 0; i < bearings.length; i++) {
const { per, along } = bearings[i];
const angular = radiusM * per;
const cosA = Math.cos(angular);
const sinA = Math.sin(angular);
// The unit vector there on the sphere, taken as the ellipsoid's
// surface normal (its latitude read as geodetic) and raised to
// `heightM` along it, as `fromRadians` places a longitude and latitude.
let nx = up[0] * cosA + along[0] * sinA;
let ny = up[1] * cosA + along[1] * sinA;
let nz = up[2] * cosA + along[2] * sinA;
const length = Math.hypot(nx, ny, nz);
nx /= length;
ny /= length;
nz /= length;
const kx = r2.x * nx;
const ky = r2.y * ny;
const kz = r2.z * nz;
const gamma = Math.sqrt(nx * kx + ny * ky + nz * kz);
positions[i] = {
x: kx / gamma + nx * heightM,
y: ky / gamma + ny * heightM,
z: kz / gamma + nz * heightM,
};
}
return positions;
}
/** The last ring frame made: fronts at one centre share it. */
let lastRingFrame = null;
/**
* What a ring about `groundCenter` needs but its radius: the centre's up
* unit vector and, per bearing, the angle a metre of surface turns
* (Euler's formula) and the unit vector along the great circle. Kept for
* the last centre asked for.
*/
function ringFrame(groundCenter, segments) {
const last = lastRingFrame;
if (
last?.segments === segments &&
last.x === groundCenter.x &&
last.y === groundCenter.y &&
last.z === groundCenter.z
)
return last;
const { lon, lat } = toLonLatH(groundCenter);
const latitude = (lat * Math.PI) / 180;
const longitude = (lon * Math.PI) / 180;
const { x: a, z: b } = WGS84.radii;
const e2 = 1 - (b * b) / (a * a);
const sinLat = Math.sin(latitude);
const cosLat = Math.cos(latitude);
const sinLon = Math.sin(longitude);
const cosLon = Math.cos(longitude);
const w = 1 - e2 * sinLat * sinLat;
const meridional = (a * (1 - e2)) / (w * Math.sqrt(w));
const primeVertical = a / Math.sqrt(w);
// Step along the great circle in 3D from the centre's up, north and east
// unit vectors. Unlike the latitude/longitude destination formula, this
// stays well conditioned at and next to the poles.
const up = [cosLat * cosLon, cosLat * sinLon, sinLat];
const north = [-sinLat * cosLon, -sinLat * sinLon, cosLat];
const east = [-sinLon, cosLon, 0];
const bearings = [];
for (let i = 0; i <= segments; i++) {
const bearing = ((i % segments) / segments) * 2 * Math.PI;
const cosB = Math.cos(bearing);
const sinB = Math.sin(bearing);
bearings.push({
per: (cosB * cosB) / meridional + (sinB * sinB) / primeVertical,
along: north.map((n, k) => n * cosB + east[k] * sinB),
});
}
lastRingFrame = {
x: groundCenter.x,
y: groundCenter.y,
z: groundCenter.z,
segments,
up,
bearings,
};
return lastRingFrame;
}
/**
* Where pulse `index` is at `nowMs`: its radius and opacity. Pulses travel at
* constant speed from `startFraction` of the range to the full range, fade in
* over `fadeInFraction` of the way, then fade as (1 - travel) to the
* `fadeOutPower` down to `endOpacityFraction` of the peak, so each is dim
* but still visible when it reaches the range ring. The opacity already
* includes `peakOpacity`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {number} index Pulse number, 0 to `count - 1`.
* @param {number} [radiusM] Range the pulses grow to.
* @param {object} [pulse] Timing and shape, see `AWARENESS_RANGE_PULSE`.
* @returns {{radiusM: number, alpha: number}}
*/
export function awarenessPulseState(
nowMs,
index,
radiusM = AWARENESS_RADIUS_M,
pulse = AWARENESS_RANGE_PULSE,
) {
const cycle = nowMs / pulse.periodMs + index / pulse.count;
const phase = cycle - Math.floor(cycle);
return {
radiusM:
radiusM * (pulse.startFraction + (1 - pulse.startFraction) * phase),
alpha:
pulse.peakOpacity *
Math.min(1, phase / pulse.fadeInFraction) *
(pulse.endOpacityFraction +
(1 - pulse.endOpacityFraction) * (1 - phase) ** pulse.fadeOutPower),
};
}
const REDUCED_MOTION_QUERY = '(prefers-reduced-motion: reduce)';
/** Whether the viewer asked the system for less motion. */
function prefersReducedMotion() {
return globalThis.matchMedia?.(REDUCED_MOTION_QUERY)?.matches ?? false;
}
/**
* How far the pulses are switched on at `nowMs`: 0 at rest, rising to 1 over
* `settleMs` from `wake.startMs` and falling back to 0 over `settleMs` up to
* `wake.untilMs`.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {{startMs: number, untilMs: number}} wake Window from `wakeAwarenessPulses`.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {number} 0 to 1.
*/
export function awarenessPulseLevel(
nowMs,
wake,
pulse = AWARENESS_RANGE_PULSE,
) {
const level = Math.min(
(nowMs - wake.startMs) / pulse.settleMs,
(wake.untilMs - nowMs) / pulse.settleMs,
);
return Math.max(0, Math.min(1, level));
}
/**
* Run the pulses for `activeMs` from `nowMs`. A wake while they already run
* keeps their current level, so they never jump back to full mid-fade.
* @param {{startMs: number, untilMs: number}} wake Updated in place.
* @param {number} nowMs Monotonic clock in milliseconds.
* @param {object} [pulse] Timing, see `AWARENESS_RANGE_PULSE`.
* @returns {{startMs: number, untilMs: number}} `wake`.
*/
export function wakeAwarenessPulses(
wake,
nowMs,
pulse = AWARENESS_RANGE_PULSE,
) {
wake.startMs =
nowMs - awarenessPulseLevel(nowMs, wake, pulse) * pulse.settleMs;
wake.untilMs = nowMs + pulse.activeMs;
return wake;
}
/**
* How strongly the 250 km ring shows at `nowMs` while pulses run: 1 as a
* pulse front reaches it, fading over `flashMs`, so the ring appears once
* per arriving pulse instead of standing on screen.
* @param {number} nowMs Monotonic clock in milliseconds.
* @returns {number} 0 to 1.
*/
export function awarenessRingFlash(nowMs) {
return awarenessEchoStrength(
nowMs,
AWARENESS_RADIUS_M,
AWARENESS_RADIUS_M,
AWARENESS_RANGE_PULSE,
{ fadeMs: AWARENESS_RANGE_RING_STYLE.flashMs },
);
}
/** `rgba(r, g, b, a)` as a draw-port colour, channels 0 to 1. */
function rgba(css) {
const [r, g, b, a = 1] = css.match(/[\d.]+/g).map(Number);
return [r / 255, g / 255, b / 255, a];
}
/** A colour with its alpha scaled by `alpha`. */
const faded = ([r, g, b, a], alpha) => [r, g, b, a * alpha];
/**
* A haloed line as the draw port draws it: `widthPx` wide, an outer
* `haloPx` in all (half on each side) in the halo's colour, the rest in the
* core's.
* @returns {object} The line item.
*/
const haloedLine = (id, positions, { core, halo, widthPx, haloPx, show }) => ({
id,
positions,
widthPx,
mode: '3d',
style: {
kind: 'solid',
color: core,
outline: { color: halo, widthPx: haloPx },
},
show,
});
/** Side of the band's canvas, pixels: the band is soft, 2 km a pixel. */
export const AWARENESS_BAND_PIXELS = 256;
/**
* The band behind the pulse fronts into `image` (an `ImageData` of
* `size × size`): at each pixel, a fraction `r` of `rangeM` from the
* subject, the sum over pulses of `alpha × t²` where the pulse's front is
* within `gradientDepthFraction` of the range outside it (`t` is 1 at the
* front, 0 that far inward), times `gradientOpacity`, in `rgb`. The canvas
* spans `spanM` either side of its centre; the subject is `offset` metres
* east and north of that centre.
*
* The band depends on the distance from the subject alone: its alpha byte
* is tabulated along the radius, out to the range or the outermost front
* if that is further, finer than a pixel, and each pixel looks it up. Which
* entry each pixel reads changes only with the canvas, its span and the
* subject's offset; `memo`, kept between calls, holds it, so a step that
* only moves the fronts takes no square roots.
* @param {{data: Uint8ClampedArray, width: number}} image
* @param {{radii: number[], alphas: number[], rgb: number[], spanM: number,
* rangeM: number, offset: {east: number, north: number}, pulse?: object}} band
* @param {object} [memo] An object of the caller's, empty at first.
*/
export function paintAwarenessBand(image, band, memo = {}) {
const { radii, alphas, rgb, spanM, rangeM, offset } = band;
const pulse = band.pulse ?? AWARENESS_RANGE_PULSE;
const size = image.width;
const data = image.data;
const depth = pulse.gradientDepthFraction;
const opacity = pulse.gradientOpacity;
let outer = 0;
for (const radius of radii) outer = Math.max(outer, radius);
const reach = Math.max(1, outer);
const bins = 4 * size;
// Past `reach` a pixel reads the last entry, which stays 0.
if (memo.table?.length !== bins + 2) memo.table = new Uint8Array(bins + 2);
const table = memo.table;
for (let bin = 0; bin <= bins; bin++) {
const at = (bin / bins) * reach;
let sum = 0;
for (let i = 0; i < radii.length; i++) {
const inside = radii[i] - at;
if (inside >= 0 && inside <= depth) {
const t = 1 - inside / depth;
sum += alphas[i] * t * t;
}
}
// `Math.round` of a non-negative value.
table[bin] = (Math.min(1, sum * opacity) * 255 + 0.5) | 0;
}
table[bins + 1] = 0;
const key = `${size} ${spanM} ${rangeM} ${reach} ${offset.east} ${offset.north}`;
if (memo.key !== key) {
memo.key = key;
const bin = (memo.bin =
memo.bin?.length === size * size
? memo.bin
: new Uint16Array(size * size));
const perPixel = (2 * spanM) / size / rangeM;
const cx = size / 2 + offset.east / ((2 * spanM) / size);
// Canvas rows run north to south.
const cy = size / 2 - offset.north / ((2 * spanM) / size);
const toBin = bins / reach;
for (let y = 0; y < size; y++) {
const dy = (y + 0.5 - cy) * perPixel;
const dy2 = dy * dy;
for (let x = 0; x < size; x++) {
const dx = (x + 0.5 - cx) * perPixel;
const at = Math.sqrt(dx * dx + dy2);
bin[y * size + x] = at > reach ? bins + 1 : (at * toBin + 0.5) | 0;
}
}
}
const bin = memo.bin;
// Clamped as the image's bytes would clamp them.
const [r, g, b] = rgb.map((c) =>
Math.min(255, Math.max(0, Math.round(c * 255))),
);
// Whole pixels at a time where the bytes line up: each table entry as
// the four bytes it writes, in the platform's byte order.
if (data.byteOffset % 4 === 0 && data.length === bin.length * 4) {
if (memo.pixels?.length !== table.length)
memo.pixels = new Uint32Array(table.length);
const pixels = memo.pixels;
for (let i = 0; i < table.length; i++)
pixels[i] = LITTLE_ENDIAN
? (r | (g << 8) | (b << 16) | (table[i] << 24)) >>> 0
: ((r << 24) | (g << 16) | (b << 8) | table[i]) >>> 0;
const words = new Uint32Array(data.buffer, data.byteOffset, bin.length);
for (let p = 0; p < bin.length; p++) words[p] = pixels[bin[p]];
return;
}
for (let p = 0, k = 0; p < bin.length; p++, k += 4) {
data[k] = r;
data[k + 1] = g;
data[k + 2] = b;
data[k + 3] = table[bin[p]];
}
}
/** Whether this platform stores the low byte of a word first. */
const LITTLE_ENDIAN = new Uint8Array(new Uint32Array([1]).buffer)[0] === 1;
/** `p` in metres east and north of `origin`, in `origin`'s surface frame. */
function eastNorth(origin, p) {
const { lon, lat } = toLonLatH(origin);
const l = (lon * Math.PI) / 180;
const f = (lat * Math.PI) / 180;
const d = sub(p, origin);
return {
east: -Math.sin(l) * d.x + Math.cos(l) * d.y,
north:
-Math.sin(f) * Math.cos(l) * d.x -
Math.sin(f) * Math.sin(l) * d.y +
Math.cos(f) * d.z,
};
}
/** Camera height above the ellipsoid, or NaN when the renderer cannot say. */
function cameraHeightM(viewer) {
return findCamera(viewer)?.pose()?.height ?? Number.NaN;
}
/** Each instance's set ids are its own. */
let instances = 0;
/**
* The range ring and pulses of one awareness layer.
* `layerState.visual` is what is drawn now, or null.
* @param {object} options
* @param {object} options.state
* @param {(reason: string) => void} options.governorRequestRender
* @param {(subject: object) => void} options.redraw Draws the subject's
* ring again (a reduced-motion change).
*/
export function createRangeRing({
state: layerState,
governorRequestRender,
redraw,
}) {
const instance = ++instances;
/** The lines (ring and fronts) and the band's sets, on the viewer they draw on. */
let sets = null;
function setsOn(viewer) {
if (sets?.viewer === viewer) return sets;
disposeSets();
const draw = drawOf(viewer);
sets = {
viewer,
lines: draw.lines({
id: `awareness:${instance}:rim`,
pickable: false,
}),
band: draw.shapes({
id: `awareness:${instance}:band`,
pickable: false,
}),
};
return sets;
}
function disposeSets() {
sets?.lines.dispose();
sets?.band.dispose();
sets = null;
}
/**
* Run the range pulses again for `activeMs`, after a camera move. Call it
* during a frame (lifecycle's preRender): that frame's postRender arms the
* next request, so waking asks for no extra frame of its own. Pulses at
* rest start in this frame; running ones keep their sonar interval,
* however many frames a drag draws.
*/
function wakePulses() {
const visual = layerState.visual;
if (!visual?.wake) return;
const nowMs = performance.now();
wakeAwarenessPulses(visual.wake, nowMs);
if (nowMs - visual.lastStepMs < CYBER_SONAR_RENDER_INTERVAL_MS) return;
visual.lastStepMs = nowMs;
visual.step(nowMs);
}
function clearVisual() {
const visual = layerState.visual;
if (!visual) return;
visual.stopPulses?.();
visual.removeMotionListener?.();
if (sets) {
sets.lines.clear();
sets.band.clear();
}
// Idle mode renders only on request; a removed ring must not linger.
governorRequestRender('awareness-visual');
clearAwarenessEchoField();
layerState.visual = null;
}
/** Let go of the sets too, as the layer goes. */
function disposeVisual() {
clearVisual();
disposeSets();
}
function renderVisual(subject) {
const viewer = layerState.viewer;
if (!viewer || !subject?.position) return;
const location = toLonLatH(subject.position);
if (!location) return;
const groundCenter = fromRadians(
(location.lon * Math.PI) / 180,
(location.lat * Math.PI) / 180,
0,
);
const key = `${subject.layerId}:${subject.id}`;
const reducedMotion = prefersReducedMotion();
const visual = layerState.visual;
// A reduced-motion change rebuilds the visual, with or without pulses;
// so does a ring drawn on another viewer (the layer re-initialized).
if (
visual?.key === key &&
visual.viewer === viewer &&
visual.reducedMotion === reducedMotion
) {
// Move the ring only after a meaningful displacement so live tracking
// does not redraw it for sub-pixel motion every 750 ms.
if (distance(visual.center, groundCenter) >= 250) {
// The echo field reads `visual.center` in place and follows on its
// own.
Object.assign(visual.center, groundCenter);
visual.ringPositions = awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
);
visual.lastStepMs = performance.now();
visual.step(visual.lastStepMs);
// Content actually changed — buy exactly one frame instead of holding.
governorRequestRender('awareness-visual');
}
return;
}
clearVisual();
const { lines, band } = setsOn(viewer);
const frame = findFrame(viewer);
// A renderer without frame hooks gets the static ring only, as the
// sonar scene does. So does a viewer who prefers reduced motion.
const animate = Boolean(!reducedMotion && frame?.on);
// Pulses run from now until `wake.untilMs`, then rest.
const wake = animate
? wakeAwarenessPulses(
{ startMs: -Infinity, untilMs: -Infinity },
performance.now(),
)
: null;
// From a camera below the rim height the band would sweep across the
// sky, so the pulses are hidden there and rest with it: no flash, no
// echoes, no frames.
const belowRim = () => cameraHeightM(viewer) < CONTEXT_RIM_HEIGHT_M;
// One step asks for the level at one time several times over; the
// camera's pose is read once for them.
let levelMemo = { nowMs: NaN, startMs: NaN, untilMs: NaN, level: 0 };
const levelAt = (nowMs) => {
if (!wake) return 0;
const memo = levelMemo;
if (
memo.nowMs === nowMs &&
memo.startMs === wake.startMs &&
memo.untilMs === wake.untilMs
)
return memo.level;
const level = belowRim() ? 0 : awarenessPulseLevel(nowMs, wake);
levelMemo = {
nowMs,
startMs: wake.startMs,
untilMs: wake.untilMs,
level,
};
return level;
};
const ring = AWARENESS_RANGE_RING_STYLE;
const pulse = AWARENESS_RANGE_PULSE;
const core = rgba(ring.color);
const halo = rgba(ring.outlineColor);
// While pulses run, the ring flashes as each one arrives and otherwise
// dims to `restOpacity`; as they settle it returns to full and stays.
const ringAlpha = (nowMs) => {
const pulsed = Math.max(ring.restOpacity, awarenessRingFlash(nowMs));
return 1 - levelAt(nowMs) * (1 - pulsed);
};
const center = { ...groundCenter };
const next = {
key,
viewer,
center,
ringPositions: awarenessRangeRingPositions(
groundCenter,
AWARENESS_RADIUS_M,
CONTEXT_RIM_HEIGHT_M,
),
reducedMotion,
wake,
stopPulses: null,
removeMotionListener: null,
step: () => {},
/** When the pulses were last drawn as they were then. */
lastStepMs: Number.NEGATIVE_INFINITY,
};
/** The ring at `alpha` of its colours. */
const ringItems = (alpha) => [
haloedLine('ring', next.ringPositions, {
core: faded(core, alpha),
halo: faded(halo, alpha),
widthPx: ring.width,
haloPx: ring.outlineWidth,
show: true,
}),
];
if (!animate) {
lines.set(ringItems(1));
next.step = () => lines.upsert(ringItems(1));
} else {
const count = pulse.count;
// The band's ellipse is built around `bandCenter` and stands until
// the subject has moved `gradientRebuildM` from it; meanwhile the
// canvas draws the band about the subject, inside a margin as wide.
const spanM = AWARENESS_RADIUS_M + pulse.gradientRebuildM;
let bandCenter = null;
let bandShown = null;
// Two canvases in turn: a new key draws new content, and a renderer
// that holds a canvas until its next frame never sees it rewritten.
const doc = globalThis.document;
const canvases = [0, 1].map(() => {
const canvas = doc?.createElement?.('canvas');
if (!canvas?.getContext) return null;
canvas.width = canvas.height = AWARENESS_BAND_PIXELS;
const context = canvas.getContext('2d');
if (!context) return null;
return {
canvas,
context,
image: context.createImageData(
AWARENESS_BAND_PIXELS,
AWARENESS_BAND_PIXELS,
),
};
});
const paints = canvases.every(Boolean);
let painted = 0;
let paintedMs = Number.NEGATIVE_INFINITY;
// What each pixel reads, kept while the subject stays put.
const bandMemo = {};
// The image last drawn: a resting band keeps it, hidden, so showing
// it again changes it in place.
let image = null;
const bandItem = (show) => {
const { lon, lat } = toLonLatH(bandCenter);
return {
id: 'band',
geometry: {
kind: 'ellipse',
center: { lon, lat, height: CONTEXT_RIM_HEIGHT_M },
semiMajor: spanM,
semiMinor: spanM,
},
height: 'absolute',
fill: { image },
show,
};
};
/**
* Draw the pulses as they are at `nowMs`, and the ring where it now
* is: the fronts, the band and the ring's flash.
*/
next.step = (nowMs) => {
const level = levelAt(nowMs);
const items = ringItems(ringAlpha(nowMs));
const radii = [];
const alphas = [];
for (let index = 0; index < count; index++) {
const state = awarenessPulseState(nowMs, index);
radii.push(state.radiusM / AWARENESS_RADIUS_M);
alphas.push(state.alpha * level);
const front =
level > 0
? awarenessRangeRingPositions(
center,
state.radiusM,
CONTEXT_RIM_HEIGHT_M,
)
: next.ringPositions;
items.push(
haloedLine(`pulse:${index}`, front, {
core: faded(core, state.alpha * level),
halo: faded(halo, state.alpha * level),
widthPx: pulse.width,
haloPx: pulse.outlineWidth,
show: level > 0,
}),
);
}
lines.upsert(items);
if (!paints) return;
const show = level > 0;
// A resting band stays where it was built, and catches up on wake.
const rebuilt =
show &&
(!bandCenter ||
distance(bandCenter, center) >= pulse.gradientRebuildM);
if (rebuilt) bandCenter = { ...center };
if (!bandCenter) return;
if (!show) {
if (bandShown) band.upsert([bandItem(false)]);
bandShown = false;
return;
}
// The soft band is painted at most once a sonar interval;
// the fronts, crisp lines, move on every step.
if (
bandShown &&
!rebuilt &&
nowMs - paintedMs < CYBER_SONAR_RENDER_INTERVAL_MS
)
return;
paintedMs = nowMs;
const target = canvases[painted % 2];
paintAwarenessBand(
target.image,
{
radii,
alphas,
rgb: core,
spanM,
rangeM: AWARENESS_RADIUS_M,
offset: eastNorth(bandCenter, center),
},
bandMemo,
);
target.context.putImageData(target.image, 0, 0);
painted += 1;
image = {
canvas: target.canvas,
key: `awareness-band:${instance}:${painted}`,
};
band.upsert([bandItem(true)]);
bandShown = true;
};
lines.set(ringItems(1));
/** Draw the pulses at `nowMs` while they run or settle. */
const stepRunning = (nowMs) => {
if (levelAt(nowMs) > 0 || bandShown || ringAlpha(nowMs) < 1) {
next.lastStepMs = nowMs;
next.step(nowMs);
}
};
next.lastStepMs = performance.now();
next.step(next.lastStepMs);
// Whether the camera was below the rim at the last step.
let wasBelow = belowRim();
// The fronts and band are fixed in the world: a camera move needs
// nothing of them, so they step a sonar interval apart however
// many frames are drawn, and look the same parked or moving. Each
// frame checks only whether the camera crossed the rim height, which
// shows or hides them at once. A step asks for the frame that draws
// it, which is no reason to step again: a parked view draws one
// frame each interval, as the timer below asks.
const offPreRender = frame.on('preRender', () => {
const nowMs = performance.now();
const below = belowRim();
if (
below !== wasBelow ||
nowMs - next.lastStepMs >= CYBER_SONAR_RENDER_INTERVAL_MS
) {
// A crossing at the instant of the last step must not reuse
// that step's level.
if (below !== wasBelow) levelMemo.nowMs = Number.NaN;
wasBelow = below;
stepRunning(nowMs);
}
});
// Each drawn frame, whoever asked for it, arms one step a
// sonar interval later, as the sonar scene does, whose changes
// ask for the frame that draws them. Requests never land within
// 80 ms of a frame, so they cannot beat the detection lane's 80 ms
// gate, and they stop once the pulses rest.
let timer = null;
const offPostRender = frame.on('postRender', () => {
globalThis.clearTimeout(timer);
timer = null;
const nowMs = performance.now();
if ((nowMs < wake.untilMs || bandShown) && !belowRim())
timer = globalThis.setTimeout(() => {
timer = null;
stepRunning(performance.now());
governorRequestRender('awareness-pulse');
}, CYBER_SONAR_RENDER_INTERVAL_MS);
});
next.stopPulses = () => {
offPreRender();
offPostRender();
globalThis.clearTimeout(timer);
timer = null;
};
// The detection overlay pulses the brackets of flights and vessels a
// front crosses; it reads the centre in place, so it follows too.
setAwarenessEchoField({
center,
radiusM: AWARENESS_RADIUS_M,
pulse,
echo: AWARENESS_RANGE_ECHO,
level: levelAt,
});
}
// Turning reduced motion on or off mid-session rebuilds the visual.
const motionQuery = globalThis.matchMedia?.(REDUCED_MOTION_QUERY);
const onMotionChange = () => {
if (layerState.subject) redraw(layerState.subject);
};
// Safari before 14 has only the older addListener / removeListener.
if (motionQuery?.addEventListener)
motionQuery.addEventListener('change', onMotionChange);
else motionQuery?.addListener?.(onMotionChange);
next.removeMotionListener = () => {
if (motionQuery?.removeEventListener)
motionQuery.removeEventListener('change', onMotionChange);
else motionQuery?.removeListener?.(onMotionChange);
};
layerState.visual = next;
governorRequestRender('awareness-visual');
}
return { renderVisual, clearVisual, disposeVisual, wakePulses };
}
File diff suppressed because it is too large. Load diff
+183 -171
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import {
createCyberSonarSampler,
@@ -10,7 +9,30 @@ import {
AWARENESS_RADIUS_M,
} from '../../data/militaryAwarenessEngine.js';
import { bearingBetweenCoordinates } from '../../cockpitMath.js';
import { AWARENESS_PAGE_SIZE, CONTEXT_RIM_HEIGHT_M } from './policy.js';
import { AWARENESS_PAGE_SIZE } from './policy.js';
import { createRangeRing } from './rangeRing.js';
import { formatAwarenessDirection } from './presentation.js';
import { canvasOf, findCamera } from '../../render/rendererOf.js';
import {
PI_OVER_TWO,
dot,
normalize,
sub,
toDegrees,
toLonLatH,
toRadians,
} from '../../geo/index.js';
// The ring's and the pulses' own arithmetic, for their tests.
export {
AWARENESS_BAND_PIXELS,
awarenessPulseLevel,
awarenessPulseState,
awarenessRangeRingPositions,
awarenessRingFlash,
paintAwarenessBand,
wakeAwarenessPulses,
} from './rangeRing.js';
export function createRendering({
state: layerState,
@@ -20,56 +42,82 @@ export function createRendering({
}) {
const { getKeyholeGeometry, celestialScreenAngle } = services.geometry;
const { governorRequestRender } = services.render;
/** The range ring with its pulses (`rangeRing.js`). */
const rangeRing = createRangeRing({
state: layerState,
governorRequestRender,
redraw: (subject) => renderVisual(subject),
});
const CARDINALS = [
['N', 0],
['E', 90],
['S', 180],
['W', 270],
];
/**
* The direction overlay as its view renders it: the compass ring, its
* cardinals and heading, and up to three contact markers inside the
* viewer's container. Each part keeps its last placement while hidden.
*/
function ensureDirectionOverlay() {
if (layerState.directionRoot || !layerState.viewer)
return layerState.directionRoot;
const root = document.createElement('div');
root.id = 'military-awareness-direction-overlay';
root.hidden = true;
root.setAttribute('aria-hidden', 'true');
const compass = document.createElement('div');
compass.className = 'military-awareness-compass-ring';
const cardinals = [
['N', 0],
['E', 90],
['S', 180],
['W', 270],
];
layerState.compassLabels = cardinals.map(([label, bearing]) => {
const element = document.createElement('span');
element.className = `military-awareness-compass-label cardinal-${label.toLowerCase()}`;
element.textContent = label;
element.dataset.bearing = String(bearing);
root.appendChild(element);
return element;
if (layerState.directionView || !layerState.viewer)
return layerState.directionView;
presentDirection({
container: layerState.viewer.container,
hidden: true,
ring: null,
heading: { text: '', left: null, top: null },
labels: CARDINALS.map(([label, bearing]) => ({
label,
bearing,
left: null,
top: null,
})),
markers: Array.from({ length: 3 }, () => ({
hidden: false,
style: null,
arrow: null,
caption: { text: '', style: null },
})),
});
const heading = document.createElement('span');
heading.className = 'military-awareness-compass-heading';
root.append(compass, heading);
return layerState.directionView;
}
layerState.directionMarkers = Array.from({ length: 3 }, () => {
const marker = document.createElement('div');
marker.className = 'military-awareness-direction-marker';
const arrow = document.createElement('span');
arrow.className = 'military-awareness-direction-arrow';
arrow.textContent = '➜';
const label = document.createElement('span');
label.className = 'military-awareness-direction-label';
marker.append(arrow, label);
marker._arrow = arrow;
marker._label = label;
marker._lastAngle = 0;
root.appendChild(marker);
return marker;
});
/** Publish a change to the overlay, skipping one that changes nothing. */
function presentDirection(patch) {
const next = patch && { ...layerState.directionView, ...patch };
const signature = JSON.stringify(next, (name, value) =>
name === 'container' ? undefined : value,
);
if (next && signature === layerState.directionSignature) return;
layerState.directionSignature = next ? signature : '';
layerState.directionView = next && Object.freeze(next);
for (const listener of [...layerState.directionListeners])
listener(layerState.directionView);
}
layerState.compassRing = compass;
layerState.compassHeading = heading;
layerState.viewer.container.appendChild(root);
layerState.directionRoot = root;
return root;
/**
* Receive the direction overlay now and after every change.
* @param {(view: ?object) => void} listener
* @returns {() => void} Unsubscribe.
*/
function subscribeDirectionOverlay(listener) {
layerState.directionListeners.add(listener);
listener(layerState.directionView);
return () => layerState.directionListeners.delete(listener);
}
/** Hide the overlay, keeping its last placement. */
function hideDirectionOverlay() {
if (layerState.directionView) presentDirection({ hidden: true });
}
/** Withdraw the overlay when the layer is destroyed. */
function removeDirectionOverlay() {
if (layerState.directionView) presentDirection(null);
layerState.directionAngles = [0, 0, 0];
}
function scheduleDirectionOverlayUpdate(force = false) {
@@ -103,11 +151,11 @@ export function createRendering({
!layerState.subject?.position ||
!layerState.results
) {
if (root) root.hidden = true;
if (root) presentDirection({ hidden: true });
return;
}
const canvas = layerState.viewer.scene.canvas;
const canvas = canvasOf(layerState.viewer);
const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height;
const sonar = isCyberSonarActive()
@@ -115,41 +163,43 @@ export function createRendering({
: null;
const geometry = getKeyholeGeometry(width, height);
if (!(geometry.radius > 0)) {
root.hidden = true;
presentDirection({ hidden: true });
return;
}
root.hidden = false;
// Keep the compass comfortably inside the shader keyhole so its cardinals
// remain visible around the subject instead of hiding under edge panels.
const compassRadius = Math.max(
120,
Math.min(geometry.radius - 48, geometry.radius * 0.66),
);
layerState.compassRing.style.left = `${geometry.centerX - compassRadius}px`;
layerState.compassRing.style.top = `${geometry.centerY - compassRadius}px`;
layerState.compassRing.style.width = `${compassRadius * 2}px`;
layerState.compassRing.style.height = `${compassRadius * 2}px`;
const cameraHeading = layerState.viewer.camera.heading || 0;
const headingDeg =
(Math.round(Cesium.Math.toDegrees(cameraHeading)) + 360) % 360;
layerState.compassRing.style.setProperty(
'--compass-rotation',
`${-headingDeg}deg`,
);
layerState.compassHeading.textContent = t('HDG {value}°', {
value: String(headingDeg).padStart(3, '0'),
});
layerState.compassHeading.style.left = `${geometry.centerX}px`;
layerState.compassHeading.style.top = `${geometry.centerY - compassRadius + 39}px`;
for (const label of layerState.compassLabels) {
const bearing = Cesium.Math.toRadians(Number(label.dataset.bearing));
const angle = bearing - cameraHeading - Cesium.Math.PI_OVER_TWO;
const pose = findCamera(layerState.viewer)?.pose();
const cameraHeading = pose?.heading || 0;
const headingDeg = (Math.round(toDegrees(cameraHeading)) + 360) % 360;
const ring = {
left: `${geometry.centerX - compassRadius}px`,
top: `${geometry.centerY - compassRadius}px`,
width: `${compassRadius * 2}px`,
height: `${compassRadius * 2}px`,
'--compass-rotation': `${-headingDeg}deg`,
};
const heading = {
text: t('HDG {value}°', {
value: String(headingDeg).padStart(3, '0'),
}),
left: `${geometry.centerX}px`,
top: `${geometry.centerY - compassRadius + 39}px`,
};
const labels = root.labels.map((label) => {
const bearing = toRadians(label.bearing);
const angle = bearing - cameraHeading - PI_OVER_TWO;
const labelRadius = compassRadius - 17;
label.style.left = `${geometry.centerX + Math.cos(angle) * labelRadius}px`;
label.style.top = `${geometry.centerY + Math.sin(angle) * labelRadius}px`;
}
return {
...label,
left: `${geometry.centerX + Math.cos(angle) * labelRadius}px`,
top: `${geometry.centerY + Math.sin(angle) * labelRadius}px`,
};
});
const directionalCohort =
layerState.results.cohorts.find(
@@ -162,150 +212,112 @@ export function createRendering({
page,
page + AWARENESS_PAGE_SIZE,
) || [];
for (let index = 0; index < layerState.directionMarkers.length; index++) {
const marker = layerState.directionMarkers[index];
const markers = root.markers.map((marker) => ({ ...marker }));
for (let index = 0; index < markers.length; index++) {
const marker = markers[index];
const item = military[index];
if (!item?.position) {
marker.hidden = true;
continue;
}
const direction = Cesium.Cartesian3.subtract(
item.position,
layerState.subject.position,
layerState.DIRECTION_SCRATCH[index],
);
if (Cesium.Cartesian3.magnitudeSquared(direction) < 1) {
const offset = sub(item.position, layerState.subject.position);
if (dot(offset, offset) < 1 || !pose) {
marker.hidden = true;
continue;
}
Cesium.Cartesian3.normalize(direction, direction);
const direction = normalize(offset);
const projection = celestialScreenAngle(
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.rightWC),
Cesium.Cartesian3.dot(direction, layerState.viewer.camera.upWC),
marker._lastAngle,
dot(direction, pose.right),
dot(direction, pose.up),
layerState.directionAngles[index],
);
if (projection.stable) marker._lastAngle = projection.angle;
if (projection.stable)
layerState.directionAngles[index] = projection.angle;
// Every detected contact shares the compass rim. Keeping the bearing
// markers on one radius makes them read as compass contacts rather than
// unconstrained labels floating over the map.
const markerRadius = compassRadius;
marker.style.left = `${geometry.centerX + Math.cos(projection.angle) * markerRadius}px`;
marker.style.top = `${geometry.centerY + Math.sin(projection.angle) * markerRadius}px`;
marker.style.opacity = String(projection.opacity);
marker.style = {
left: `${geometry.centerX + Math.cos(projection.angle) * markerRadius}px`,
top: `${geometry.centerY + Math.sin(projection.angle) * markerRadius}px`,
opacity: String(projection.opacity),
};
const sonarFactor =
sonar?.at(
geometry.centerX + Math.cos(projection.angle) * markerRadius,
geometry.centerY + Math.sin(projection.angle) * markerRadius,
) ?? 1;
marker._arrow.style.opacity = String(sonarFactor);
marker._label.style.opacity = String(
sonar ? sonar.label(sonarFactor) : 1,
);
marker._arrow.style.transform = `translate(-50%, -50%) rotate(${projection.angle}rad)`;
marker._label.style.transform = `translate(-50%, -50%) translate(${-Math.cos(projection.angle) * 56}px, ${-Math.sin(projection.angle) * 56}px)`;
marker.arrow = {
opacity: String(sonarFactor),
transform: `translate(-50%, -50%) rotate(${projection.angle}rad)`,
};
const labelStyle = {
opacity: String(sonar ? sonar.label(sonarFactor) : 1),
transform: `translate(-50%, -50%) translate(${-Math.cos(projection.angle) * 56}px, ${-Math.sin(projection.angle) * 56}px)`,
};
const label = formatAwarenessLabel(item);
const subjectCartographic = Cesium.Cartographic.fromCartesian(
layerState.subject.position,
undefined,
layerState.SUBJECT_CARTOGRAPHIC_SCRATCH,
);
const targetCartographic = Cesium.Cartographic.fromCartesian(
item.position,
undefined,
layerState.TARGET_CARTOGRAPHIC_SCRATCH[index],
);
const subjectLocation = toLonLatH(layerState.subject.position);
const targetLocation = toLonLatH(item.position);
const bearing =
subjectCartographic && targetCartographic
subjectLocation && targetLocation
? bearingBetweenCoordinates(
Cesium.Math.toDegrees(subjectCartographic.latitude),
Cesium.Math.toDegrees(subjectCartographic.longitude),
Cesium.Math.toDegrees(targetCartographic.latitude),
Cesium.Math.toDegrees(targetCartographic.longitude),
subjectLocation.lat,
subjectLocation.lon,
targetLocation.lat,
targetLocation.lon,
)
: null;
const bearingText = Number.isFinite(bearing)
? t('BRG {value}°', {
value: String(Math.round(bearing)).padStart(3, '0'),
value: formatAwarenessDirection(bearing),
})
: t('BRG —');
const courseText = Number.isFinite(item.track)
? ` · ${t('CRS {value}°', {
value: String(Math.round(item.track)).padStart(3, '0'),
value: formatAwarenessDirection(item.track),
})}`
: '';
marker._label.textContent = `${label} · ${formatAwarenessDistance(item.distanceM)}\n${bearingText}${courseText}`;
marker.caption = {
text: `${label} · ${formatAwarenessDistance(item.distanceM)}\n${bearingText}${courseText}`,
style: labelStyle,
};
marker.hidden = false;
}
presentDirection({ hidden: false, ring, heading, labels, markers });
}
/**
* Run the range pulses again for `activeMs`, after a camera move. Call it
* during a frame (lifecycle's preRender): that frame's postRender arms the
* next request, so waking asks for no extra frame of its own.
*/
function wakePulses() {
rangeRing.wakePulses();
}
function clearVisual() {
if (layerState.visual?.entities && layerState.viewer) {
for (const entity of layerState.visual.entities)
layerState.viewer.entities.remove(entity);
// Idle mode renders only on request; a removed ring must not linger.
governorRequestRender('awareness-visual');
}
layerState.visual = null;
rangeRing.clearVisual();
}
/** Let the ring's draw sets go, as the layer is destroyed. */
function disposeVisual() {
rangeRing.disposeVisual();
}
function renderVisual(subject) {
if (!layerState.viewer || !subject?.position) return;
const cartographic = Cesium.Cartographic.fromCartesian(subject.position);
if (!cartographic) return;
const groundCenter = Cesium.Cartesian3.fromRadians(
cartographic.longitude,
cartographic.latitude,
0,
);
const key = `${subject.layerId}:${subject.id}`;
if (layerState.visual?.key === key) {
// Large ellipse geometry is more reliable as a ConstantPositionProperty.
// Move it only after a meaningful displacement so live tracking does not
// churn ten large geometries for sub-pixel motion every 750 ms.
if (
Cesium.Cartesian3.distance(layerState.visual.center, groundCenter) >=
250
) {
for (const entity of layerState.visual.entities)
entity.position.setValue(groundCenter);
Cesium.Cartesian3.clone(groundCenter, layerState.visual.center);
// Content actually changed — buy exactly one frame instead of holding.
governorRequestRender('awareness-visual');
}
return;
}
clearVisual();
const entities = [];
entities.push(
layerState.viewer.entities.add({
position: groundCenter,
ellipse: {
semiMajorAxis: AWARENESS_RADIUS_M,
semiMinorAxis: AWARENESS_RADIUS_M,
fill: false,
outline: true,
outlineColor:
Cesium.Color.fromCssColorString('#62b5ff').withAlpha(0.72),
height: CONTEXT_RIM_HEIGHT_M,
},
}),
);
layerState.visual = {
key,
entities,
center: Cesium.Cartesian3.clone(groundCenter),
};
governorRequestRender('awareness-visual');
rangeRing.renderVisual(subject);
}
return {
ensureDirectionOverlay,
subscribeDirectionOverlay,
hideDirectionOverlay,
removeDirectionOverlay,
scheduleDirectionOverlayUpdate,
cancelDirectionOverlayUpdate,
updateDirectionOverlay,
clearVisual,
disposeVisual,
renderVisual,
wakePulses,
};
}
@@ -0,0 +1,108 @@
// src/layers/awareness/selectedVessel.test.mjs — Contacts turned on while an
// AIS vessel is selected takes that vessel as its subject.
import test from 'node:test';
import assert from 'node:assert/strict';
import { summarizeAwarenessCohort } from '../../data/militaryAwarenessEngine.js';
import { createState } from './state.js';
import { createModel } from './model.js';
import { createQueries } from './queries.js';
import { createSubject } from './subject.js';
import { createHistory } from './history.js';
import { createDependencies } from './dependencies.js';
const VESSEL_ID = '367000001';
/** Contacts parts over fake sources; focus records each nearest-flight pick. */
function contacts(selection) {
globalThis.document ??= { body: null };
const noAircraft = {
getAllPositions: () => [],
getNearby: () => [],
getTrackedSubject: () => null,
};
const services = {
flights: noAircraft,
military: noAircraft,
vessels: {
getNearby: () => [],
getAllPositions: () => [],
getSelectedInfo: () => selection.vessel,
},
installations: {
getNearby: () => [],
getStats: () => ({}),
setContextAnchor() {},
},
};
const state = createState({ services });
state.enabled = true;
state.passive = false;
state.dataManager = {
isEnabled: () => true,
isEffectivelyEnabled: () => true,
setEnabled: async () => true,
getLayerLifecycleState: () => ({
enabled: true,
lifecycleState: 'enabled',
}),
layers: new Map(),
};
const focused = [];
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {}, startAwarenessPageRotation() {} },
focus: {
focusAttentionTarget() {
focused.push('nearest');
return true;
},
},
};
const context = { state, services, parts };
parts.model = createModel(context);
parts.queries = createQueries(context);
parts.subject = createSubject(context);
parts.history = createHistory(context);
parts.dependencies = createDependencies(context);
return { state, parts, focused };
}
/** The vessel layer's answer for a selected Royal Prince. */
const ROYAL_PRINCE = Object.freeze({
id: VESSEL_ID,
mmsi: VESSEL_ID,
name: 'ROYAL PRINCE',
latitude: 37.8,
longitude: -122.4,
});
test('Contacts turned on with a vessel selected takes it as the subject', async () => {
const { state, parts, focused } = contacts({ vessel: ROYAL_PRINCE });
await parts.dependencies.activateOperationalContext();
assert.deepEqual(focused, [], 'no nearest flight is picked or followed');
assert.equal(state.subject?.layerId, 'ais-live-vessels');
assert.equal(state.subject?.id, VESSEL_ID);
assert.match(state.subject.label, /ROYAL PRINCE/);
});
test('a late source settling keeps the selected vessel, not a nearest flight', () => {
const selection = { vessel: null };
const { state, parts, focused } = contacts(selection);
state.autoFocusRetryPending = true;
selection.vessel = ROYAL_PRINCE;
parts.dependencies.refreshAfterDeferredDependency(state.activationId);
assert.deepEqual(focused, []);
assert.equal(state.subject?.id, VESSEL_ID);
});
test('with no vessel selected, Contacts still picks the nearest flight', async () => {
const { state, parts, focused } = contacts({ vessel: null });
await parts.dependencies.activateOperationalContext();
assert.deepEqual(focused, ['nearest']);
assert.equal(state.subject, null);
});
@@ -0,0 +1,159 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createQueries } from './queries.js';
import { createSubject } from './subject.js';
import { createModel } from './model.js';
import { summarizeAwarenessCohort } from '../../data/militaryAwarenessEngine.js';
import { layerFeedState } from '../../data/feedState.js';
import aisLiveVesselsLayer, {
_setVesselStateForTest,
_beginAisSessionForTest,
_applyAisFeedSnapshotForTest,
_setAisRuntimeForTest,
} from '../../data/aisLiveVessels.js';
test('a poll that returns the same stale AIS snapshot restores STALE on Contacts cohorts', () => {
globalThis.document ??= { body: null };
const services = {
installations: { getNearby: () => [], getStats: () => ({}) },
flights: { getNearby: () => [] },
military: { getNearby: () => [] },
vessels: { getNearby: () => [] },
};
const layerState = {
enabled: true,
passive: true,
sourceRevision: '',
cohortPages: new Map(),
subject: {
id: 'site-1',
layerId: 'military-installations',
label: 'Site',
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
};
let states;
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) =>
summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {} },
};
const realQueries = createQueries({ state: layerState, services, parts });
parts.queries = { ...realQueries, collectSourceStates: () => states };
parts.model = createModel({ state: layerState, services, parts });
const subject = createSubject({ state: layerState, services, parts });
const flights = (lastUpdate) => ({
available: true, enabled: true, stale: false,
stats: { source: 'OpenSky Network', count: 4, lastUpdate },
});
const vessels = (loading) => ({
available: true, enabled: true, stale: true,
stats: { source: 'Datalastic', stale: true, count: 3, lastUpdate: 1000, loading },
});
const rest = {
military: { available: true, enabled: true, stale: false, stats: { source: 'adsb.lol', fallback: false, count: 1, lastUpdate: 1 } },
'military-installations': { available: true, enabled: true, stale: false, stats: { coverage: { kind: 'subject', radiusM: 100000 } } },
};
const ais = () => layerState.results.cohorts.find((c) => c.id === 'ais-live-vessels');
// 1. Stale AIS cache, nothing loading.
states = { flights: flights(1), 'ais-live-vessels': vessels(false), ...rest };
subject.refreshSelectedSubject(true);
assert.equal(ais().sourceStatus, 'stale');
// 2. AIS re-poll in flight while the flights poll lands (revision changes).
states = { flights: flights(2), 'ais-live-vessels': vessels(true), ...rest };
subject.refreshSelectedSubject();
assert.equal(ais().sourceStatus, 'stale', 'a poll in flight keeps the snapshot stale');
// 3. AIS poll returns the same stale snapshot; only loading flips back.
states = { flights: flights(2), 'ais-live-vessels': vessels(false), ...rest };
subject.refreshSelectedSubject();
subject.refreshSelectedSubject();
assert.equal(ais().sourceStatus, 'stale', 'Layers reads STALE again; Contacts/Cockpit must too');
});
function fakeRuntime() {
return {
now: () => 1000,
setTimeout: () => ({}),
clearTimeout() {},
};
}
test('first AIS connect (no snapshot yet) carries no STALE on the Contacts cohort', () => {
globalThis.document ??= { body: null };
_setAisRuntimeForTest(fakeRuntime());
_setVesselStateForTest({ viewer: {}, records: [] });
try {
_beginAisSessionForTest();
// What server/providers/vessels/ais-live.js answers while its socket connects.
_applyAisFeedSnapshotForTest({}, {
rows: [], source: 'AISStream', status: 'connecting', refreshing: true,
});
const vesselStats = aisLiveVesselsLayer.getStats();
assert.equal(vesselStats.loading, true);
assert.equal(vesselStats.stale, true);
assert.equal(vesselStats.lastUpdate, null);
assert.equal(layerFeedState(vesselStats), 'loading', 'Layers chip reads LOADING');
const flightsStats = { source: 'OpenSky Network', count: 2, lastUpdate: 5 };
const militaryStats = { source: 'adsb.lol', fallback: false, count: 1, lastUpdate: 5 };
const installStats = { coverage: { kind: 'subject', radiusM: 100000 } };
const statsById = {
flights: flightsStats,
military: militaryStats,
'ais-live-vessels': vesselStats,
'military-installations': installStats,
};
const services = {
installations: { getNearby: () => [], getStats: () => installStats },
flights: { getNearby: () => [] },
military: { getNearby: () => [] },
vessels: aisLiveVesselsLayer,
};
const layerState = {
enabled: true,
passive: true,
sourceRevision: '',
cohortPages: new Map(),
dataManager: {
isEnabled: () => true,
getLayerLifecycleState: () => ({ enabled: true, lifecycleState: 'enabled' }),
layers: new Map(Object.entries(statsById).map(([id, s]) => [id, { module: { getStats: () => s } }])),
},
subject: {
id: 'site-1',
layerId: 'military-installations',
label: 'Site',
position: Cesium.Cartesian3.fromDegrees(0, 0, 0),
},
};
const parts = {
navigation: {
summarizeAwarenessCohortForNavigation: (items, source) => summarizeAwarenessCohort(items, source),
isFlightLayer: (id) => id === 'flights' || id === 'military',
},
rendering: { renderVisual() {}, scheduleDirectionOverlayUpdate() {} },
panel: { renderResults() {} },
};
parts.queries = createQueries({ state: layerState, services, parts });
parts.model = createModel({ state: layerState, services, parts });
const subject = createSubject({ state: layerState, services, parts });
const vesselsSource = parts.queries.collectSourceStates()['ais-live-vessels'];
assert.equal(vesselsSource.available, false, 'never-answered source is unavailable');
subject.refreshSelectedSubject(true);
const ais = layerState.results.cohorts.find((c) => c.id === 'ais-live-vessels');
assert.equal(ais.sourceStatus, null, 'no snapshot yet: no STALE label, Layers says LOADING');
} finally {
_setVesselStateForTest({ enabled: false });
_setAisRuntimeForTest();
}
});
+22 -23
View File
@@ -1,20 +1,6 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const state = {};
state.DIRECTION_SCRATCH = Array.from(
{ length: 3 },
() => new Cesium.Cartesian3(),
);
state.SUBJECT_CARTOGRAPHIC_SCRATCH = new Cesium.Cartographic();
state.TARGET_CARTOGRAPHIC_SCRATCH = Array.from(
{ length: 3 },
() => new Cesium.Cartographic(),
);
Object.assign(state, {
viewer: null,
dataManager: null,
@@ -26,23 +12,33 @@ export function createState({ services }) {
// layers activate only after Contacts is explicitly selected.
passive: true,
ownedDependencies: new Set(),
/** Stops following the manager's adoptions (see watchAdoptions). */
unwatchAdoptions: null,
subject: null,
/** The tracked flight's photo with the subject it belongs to, or null. */
subjectPhoto: null,
results: null,
visual: null,
panel: null,
panelOwned: false,
/** Whether layer views replace the panel's initial markup yet. */
panelShown: false,
/** The published panel view, its signature and its subscribers. */
panelView: null,
panelSignature: '',
panelListeners: new Set(),
/** Result renders, published or not; tests observe repaint storms. */
panelRenders: 0,
subjectListener: null,
contextListener: null,
clearListener: null,
subjectClearListener: null,
runtimeListenersAttached: false,
preRenderRemover: null,
panelClickListener: null,
directionRoot: null,
compassRing: null,
compassLabels: [],
compassHeading: null,
directionMarkers: [],
/** The published direction overlay, its signature and its subscribers. */
directionView: null,
directionSignature: '',
directionListeners: new Set(),
/** Each marker's last stable screen angle. */
directionAngles: [0, 0, 0],
navigationHistory: [],
navigationVisited: new Set(),
navigationIndex: -1,
@@ -53,11 +49,14 @@ export function createState({ services }) {
lastCameraPoseSig: '',
/** When the pose signature last changed bins (hysteresis anchor). */
lastCameraPoseChangeMs: 0,
/** When the viewer last handled the camera (pointer, wheel, touch, key). */
lastCameraInputMs: Number.NEGATIVE_INFINITY,
/** Element the camera-input listeners are attached to. */
cameraInputTarget: null,
/** Whether the view currently counts as moving (hysteretic, not per-frame). */
cameraMoving: false,
lastEvaluatedPosition: null,
sourceRevision: '',
panelMarkup: '',
directionFrame: null,
lastDirectionUpdateMs: 0,
activationId: 0,
+126 -39
View File
@@ -1,9 +1,11 @@
import { followedOf } from '../../data/followed.js';
import {
AWARENESS_RADIUS_M,
AWARENESS_RELATIONSHIP,
} from '../../data/militaryAwarenessEngine.js';
import * as Cesium from 'cesium';
import { layerFeedState } from '../../data/feedState.js';
import { t } from '../../i18n/index.js';
import { clone, distance, fromDegrees } from '../../geo/index.js';
import {
AWARENESS_QUERY_LIMIT,
SOURCE_LABEL,
@@ -24,6 +26,8 @@ function localizeCoverageLabel(label) {
return label;
}
/** @typedef {import('../../render/contract/common').Ecef} Ecef */
export function createSubject({ state: layerState, services, parts, source }) {
const aisLiveVesselsLayer = services.vessels;
const militaryInstallationsLayer = services.installations;
@@ -52,6 +56,18 @@ export function createSubject({ state: layerState, services, parts, source }) {
const vesselsState = sourceStates['ais-live-vessels'];
const installationsState = sourceStates['military-installations'];
const evaluatedAt = Date.now();
// A poll in flight keeps FALLBACK or STALE: the revision key ignores loading.
// Before the first answer there is no snapshot, so loading stays.
const sourceStatus = (sourceState) => {
const feedState = layerFeedState(
sourceState.available
? { ...sourceState.stats, loading: false }
: sourceState.stats,
);
return feedState === 'fallback' || feedState === 'stale'
? feedState
: null;
};
const retainedProvenance = (id, label, sourceState, fallbackSource) => {
const retainedSource = sourceState.stats.source || fallbackSource;
return {
@@ -72,7 +88,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
.getNearby(position, AWARENESS_RADIUS_M, AWARENESS_QUERY_LIMIT)
.filter(
(item) =>
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'mmsi'),
!parts.queries.isSame(subject, item, 'ais-live-vessels', 'id'),
);
const coverage = installationsState.stats?.coverage;
const installationRadius =
@@ -94,6 +110,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'flights',
label: t('Flights'),
source: flightsState.stats.source || SOURCE_LABEL.flights,
sourceStatus: sourceStatus(flightsState),
provenance: retainedProvenance(
'flights',
'Flights',
@@ -113,6 +130,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'military',
label: t('Military flights'),
source: militaryState.stats.source || SOURCE_LABEL.military,
sourceStatus: sourceStatus(militaryState),
provenance: retainedProvenance(
'military',
'Military flights',
@@ -132,6 +150,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
id: 'ais-live-vessels',
label: t('AIS vessels'),
source: vesselsState.stats.source || SOURCE_LABEL['ais-live-vessels'],
sourceStatus: sourceStatus(vesselsState),
provenance: retainedProvenance(
'ais-live-vessels',
'AIS vessels',
@@ -149,6 +168,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
source:
installationsState.stats.source ||
SOURCE_LABEL['military-installations'],
sourceStatus: sourceStatus(installationsState),
provenance: retainedProvenance(
'military-installations',
'Mapped installations',
@@ -183,17 +203,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
}
/**
* Resolve the source-owned aircraft that currently owns Cesium tracking.
* Resolve the source-owned aircraft that currently owns the follow camera.
* Both flight layers may briefly retain local state during a cross-layer
* handoff, so the viewer's normalized tracked identity is the tie-breaker.
* @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null}
* @returns {{layerId: string, id: string, label: string, position: Ecef}|null}
* Detached awareness subject, or null when no flight owns the follow camera.
*/
function currentTrackedFlightSubject() {
const trackedKey = normalizeContextId(
layerState.viewer?.trackedEntity?.gevTrackedId,
);
const trackedKey = normalizeContextId(followedOf(layerState.viewer)?.key);
if (!trackedKey) return null;
const subjects = [
flightsLayer.getTrackedSubject?.(),
@@ -233,7 +251,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
subject,
parts.history.historySourceItem(subject),
),
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
});
layerState.navigationIndex = layerState.navigationHistory.length - 1;
}
@@ -248,10 +266,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
* Resolve the currently displayed position for a selected live subject. Flight
* tracking owns the motion callback, so awareness consumes its cached display
* position instead of creating a second tracker or extrapolation path.
* @param {{layerId: string, id: string, position: Cesium.Cartesian3}} subject Current subject.
* @param {{layerId: string, id: string, position: Ecef}} subject Current subject.
* @param {object} [options] Position materialization controls.
* @param {boolean} [options.allowCollectionMaterialization=true] Whether a layer-wide fallback may run.
* @returns {Cesium.Cartesian3|null} A cloned live position when one is available.
* @returns {Ecef|null} A cloned live position when one is available.
*/
function resolveSubjectPosition(
@@ -260,16 +278,15 @@ export function createSubject({ state: layerState, services, parts, source }) {
) {
if (!subject?.position) return null;
if (subject.layerId === 'flights' || subject.layerId === 'military') {
const trackedPosition =
layerState.viewer?.trackedEntity?.gevDisplayPosition?.();
const followed = followedOf(layerState.viewer);
const trackedPosition = followed?.displayPosition?.();
if (trackedPosition) {
return {
position: Cesium.Cartesian3.clone(trackedPosition),
position: clone(trackedPosition),
// Only the follow camera's own contact proves presence this way; a
// different tracked entity says nothing about this subject.
presence:
String(layerState.viewer?.trackedEntity?.gevTrackedId || '') ===
subjectKey(subject)
String(followed?.key || '') === subjectKey(subject)
? SUBJECT_PRESENCE.LIVE
: SUBJECT_PRESENCE.UNCHECKED,
};
@@ -279,7 +296,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// awareness position instead of allocating/scanning up to 1,000 contacts.
if (!allowCollectionMaterialization) {
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.UNCHECKED,
};
}
@@ -294,7 +311,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (subject.layerId === 'ais-live-vessels') {
if (!allowCollectionMaterialization) {
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.UNCHECKED,
};
}
@@ -307,7 +324,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
// Mapped installations come from static geometry, not a live feed: there is
// nothing to be culled from.
return {
position: Cesium.Cartesian3.clone(subject.position),
position: clone(subject.position),
presence: SUBJECT_PRESENCE.LIVE,
};
}
@@ -321,10 +338,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
* ~11k contacts against a 1,000-row cap, so "not in the rows" is not "gone".
* The rows are only consulted for a fresher position — a contact past the cap
* keeps its last known position while still reading as present.
* @param {{id: string, position: Cesium.Cartesian3}} subject Current subject.
* @param {Array<{id: string, position: Cesium.Cartesian3}>} rows Live collection rows.
* @param {{id: string, position: Ecef}} subject Current subject.
* @param {Array<{id: string, position: Ecef}>} rows Live collection rows.
* @param {{hasContact?: function}} layer The owning source layer.
* @returns {{position: Cesium.Cartesian3, presence: string}} Position plus presence verdict.
* @returns {{position: Ecef, presence: string}} Position plus presence verdict.
*/
function collectionSubjectPosition(subject, rows, layer) {
@@ -342,8 +359,8 @@ export function createSubject({ state: layerState, services, parts, source }) {
: SUBJECT_PRESENCE.UNCHECKED;
return {
position: current?.position
? Cesium.Cartesian3.clone(current.position)
: Cesium.Cartesian3.clone(subject.position),
? clone(current.position)
: clone(subject.position),
presence,
};
}
@@ -361,19 +378,51 @@ export function createSubject({ state: layerState, services, parts, source }) {
*
* Identity (`subject.id`) is NEVER re-derived — only the rendered string.
* @param {{layerId: string, id: string, label: string}} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it (see trackedSubjectOf).
* @returns {string} The current label, or the cached one when the owning layer
* has no tracked subject (e.g. a cross-layer handoff is in flight).
*/
function resolveSubjectLabel(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId))
return subject?.label;
function resolveSubjectLabel(subject, tracked = trackedSubjectOf(subject)) {
return tracked?.label || subject?.label;
}
/**
* The owning flight layer's tracked-subject descriptor when it describes
* this subject, else null. Built once per refresh and shared by the label
* and the photo.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @returns {?{id: string, label: string, photo?: ?object}}
*/
function trackedSubjectOf(subject) {
if (!parts.navigation.isFlightLayer(subject?.layerId)) return null;
const layer =
subject.layerId === 'flights' ? flightsLayer : militaryFlightsLayer;
const tracked = layer.getTrackedSubject?.();
if (tracked?.label && String(tracked.id) === String(subject.id))
return tracked.label;
return subject.label;
return tracked && String(tracked.id) === String(subject.id)
? tracked
: null;
}
/**
* The subject's photo, for the Contacts panel: the tracked airliner's
* Planespotters photo, or the selected vessel's Open Vessel Photos photo.
*
* The flights layer looks photos up only for the plane it tracks, the
* vessel layer only for the vessel selected; an installation, a military
* aircraft or an untracked flight has none.
* @param {{layerId: string, id: string}|null} subject Current subject.
* @param {?object} [tracked] The subject's tracked descriptor, when the
* caller already has it.
* @returns {?{src: string, width: ?number, height: ?number, photographer: string, link: string, licence?: string}}
*/
function resolveSubjectPhoto(subject, tracked = trackedSubjectOf(subject)) {
if (subject?.layerId === 'ais-live-vessels')
return aisLiveVesselsLayer.getVesselPhoto?.(subject.id) ?? null;
return subject?.layerId === 'flights' && tracked?.photo
? tracked.photo
: null;
}
/** Refresh proximity counts/distances against the subject's current live position. */
@@ -400,11 +449,24 @@ export function createSubject({ state: layerState, services, parts, source }) {
if (presence === SUBJECT_PRESENCE.LIVE) layerState.subjectMissing = false;
else if (presence === SUBJECT_PRESENCE.MISSING)
layerState.subjectMissing = true;
const nextLabel = resolveSubjectLabel(layerState.subject);
const tracked = trackedSubjectOf(layerState.subject);
const nextLabel = resolveSubjectLabel(layerState.subject, tracked);
const labelChanged = nextLabel !== layerState.subject.label;
// The panel reads the photo from here, with the subject it belongs to.
const photo = resolveSubjectPhoto(layerState.subject, tracked);
layerState.subjectPhoto = photo
? {
layerId: layerState.subject.layerId,
id: layerState.subject.id,
photo,
}
: null;
// A photo arriving after selection is render-worthy on its own, as a label.
const photoChanged =
(photo?.src ?? null) !== (layerState.panelView?.photo?.src ?? null);
layerState.subject = { ...layerState.subject, position, label: nextLabel };
const movementM = layerState.lastEvaluatedPosition
? Cesium.Cartesian3.distance(layerState.lastEvaluatedPosition, position)
? distance(layerState.lastEvaluatedPosition, position)
: Infinity;
if (
!parts.model.awarenessRefreshRequired({
@@ -422,16 +484,13 @@ export function createSubject({ state: layerState, services, parts, source }) {
// kept the ICAO hex until unrelated movement, a source-revision bump, or
// page rotation happened to repaint it. Gated on an ACTUAL change so the
// common no-op refresh (every 750 ms) still costs no repaint.
if (labelChanged) parts.panel.renderResults();
if (labelChanged || photoChanged) parts.panel.renderResults();
parts.rendering.scheduleDirectionOverlayUpdate(force);
return;
}
layerState.results = evaluateSubject(layerState.subject, sources);
layerState.sourceRevision = nextSourceRevision;
layerState.lastEvaluatedPosition = Cesium.Cartesian3.clone(
position,
layerState.lastEvaluatedPosition,
);
layerState.lastEvaluatedPosition = clone(position);
for (const cohort of layerState.results.cohorts) {
const maxPage = Math.max(
0,
@@ -458,15 +517,40 @@ export function createSubject({ state: layerState, services, parts, source }) {
const latitude = Number(record.latitude);
const longitude = Number(record.longitude);
if (!Number.isFinite(latitude) || !Number.isFinite(longitude)) return null;
// A vessel reads as its name and MMSI; a vessel named by its MMSI alone
// already carries it.
const label = String(record.label || record.id);
const mmsi = String(record.properties?.mmsi || '');
return {
layerId: record.layerId,
id: record.properties?.mmsi || record.id,
label: record.label || record.id,
id: record.properties?.vesselId || record.id,
// i18n-ignore: MMSI is a radio identity code, as on the vessel card
label: mmsi && !label.includes(mmsi) ? `${label} · MMSI ${mmsi}` : label,
memberNames: record.properties?.memberNames || [],
position: Cesium.Cartesian3.fromDegrees(longitude, latitude, 0),
position: fromDegrees(longitude, latitude, 0),
};
}
/**
* The AIS vessel the user has selected, as a subject. Contacts turned on
* after the selection never heard its `gev:entity-selected`, so activation
* asks the vessel layer and shapes its answer as that event's record.
* @returns {object|null} Detached subject, or null when no vessel is selected.
*/
function currentSelectedVesselSubject() {
const info = aisLiveVesselsLayer.getSelectedInfo?.();
if (!info?.id) return null;
return subjectFromContext({
layerId: 'ais-live-vessels',
id: info.id,
label: info.name || info.mmsi || info.id,
latitude: info.latitude,
longitude: info.longitude,
properties: { vesselId: info.id, mmsi: info.mmsi },
});
}
/**
* Record that the current subject left its feed on its own.
*
@@ -485,6 +569,7 @@ export function createSubject({ state: layerState, services, parts, source }) {
militaryInstallationsLayer.setContextAnchor?.(null);
layerState.autoFocusRetryPending = false;
layerState.subject = null;
layerState.subjectPhoto = null;
layerState.subjectMissing = false;
layerState.results = null;
layerState.navigationHistory = [];
@@ -511,8 +596,10 @@ export function createSubject({ state: layerState, services, parts, source }) {
resolveSubjectPosition,
collectionSubjectPosition,
resolveSubjectLabel,
resolveSubjectPhoto,
refreshSelectedSubject,
subjectFromContext,
currentSelectedVesselSubject,
markSubjectEvicted,
clearAwarenessSubject,
};
+8 -1
View File
@@ -11,5 +11,12 @@ export function createTesting({ state: layerState, services, parts, source }) {
pendingSelectionKey: layerState.pendingSelectionKey,
};
}
return { _getAwarenessNavigationStateForTest };
/** @returns {number} How many result renders ran, published or not. */
function _getAwarenessPanelRendersForTest() {
return layerState.panelRenders;
}
return {
_getAwarenessNavigationStateForTest,
_getAwarenessPanelRendersForTest,
};
}
+38 -5
View File
@@ -1,5 +1,6 @@
import { msg, t } from '../../i18n/index.js';
import { STATUS_POLL_MS } from './policy.js';
import { ACTIVATION_ENTER_ALTITUDE_M, STATUS_POLL_MS } from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
export function createControls({ state: layerState, services, parts, source }) {
const methods = {
@@ -13,10 +14,18 @@ export function createControls({ state: layerState, services, parts, source }) {
updateInterval: STATUS_POLL_MS,
/**
* Kept so camera moves can repaint the row before the next status poll.
* @param {object} dataManager DataLayerManager instance.
*/
attachDataManager(dataManager) {
layerState._dataManager = dataManager;
},
/**
* Return a sampled array of detectable station objects for HUD overlay rendering.
* @param {Object} [options] - Sampling options (maxCount, seed).
* @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>}
* @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>}
*/
getDetectableObjects(options = {}) {
return parts.queries.collectDetectableStations(options);
@@ -57,15 +66,39 @@ export function createControls({ state: layerState, services, parts, source }) {
/**
* Return current layer statistics for the UI status display.
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean }}
* @returns {{ count: number, lastUpdate: number|null, loading: boolean, loadingLabel?: string, error?: string, degraded?: boolean, stale?: boolean, status?: string, statusMessage?: string }}
*/
getStats() {
// A city in range without points is loading even before its fetch
// starts: the row repaints on entry, ahead of beginLoading().
const loading =
layerState._loading ||
[...layerState._activeCityIds].some(
(cityId) =>
!layerState._cityRuntime.has(cityId) &&
!layerState._failedCityIds.has(cityId),
);
const stats = {
count: layerState._count,
lastUpdate: layerState._lastUpdate,
loading: layerState._loading,
loading,
};
if (layerState._loading) {
// No system in range: the camera is too high or no system is near. A
// failed city also leaves range empty and reports its failure below.
if (
layerState._enabled &&
!loading &&
layerState._activeCityIds.size === 0 &&
layerState._failedCityIds.size === 0
) {
// English: the analyst's empty note and the row's prompt, both shown
// through translateStatusMessage (ui/statusText.js).
const note = layerState._altitudeGateEnabled
? `No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`
: `Fly below ${Math.round(ACTIVATION_ENTER_ALTITUDE_M / 1000).toLocaleString('en-US')} km to a covered city`;
return { ...stats, status: 'zoom-in', statusMessage: note };
}
if (loading) {
stats.loadingLabel =
layerState._activeCityIds.size > 0
? t('syncing {count} city feeds...', {
+139
View File
@@ -0,0 +1,139 @@
// Bike Share's covered cities on the globe (HAL-921): above the height
// stations draw at, every system in the registry has a marker, so the globe
// says where bike share is, and a click on one flies down into its city.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createSelection } from './selection.js';
import { createLifecycle } from './lifecycle.js';
import { COVERAGE_FLY_HEIGHT_M } from './policy.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeInput } from '../../input/testDoubles.mjs';
globalThis.document ??= {
addEventListener() {},
removeEventListener() {},
};
function makeLayer() {
const owners = new Map();
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
picking: {
registerPickOwner: (id, owns) => owners.set(id, owns),
unregisterPickOwner: (id) => owners.delete(id),
},
};
const source = { getStations: async () => ({ data: { stations: [] } }) };
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.ingestion = createIngestion(context);
parts.model = createModel(context);
parts.viewport = createViewport(context);
parts.rendering = createRendering(context);
parts.selection = createSelection(context);
parts.queries = { collectDetectableStations: () => [] };
parts.lifecycle = createLifecycle(context);
const camera = { lat: 20, lon: 0, height: 18_000_000 };
const flights = [];
const viewer = { scene: { pick: () => undefined, canvas: {} } };
const { draw } = bindFakeDraw(viewer, {
camera: {
pose: () => ({ ...camera }),
viewRectangle: () => null,
on: () => () => {},
flyTo: (destination, options) => flights.push({ destination, options }),
},
});
// The layer's click subscription, called with a hit as the dispatcher gives it.
const fake = fakeInput(viewer);
const clicks = [];
const subscribe = fake.input.onClick;
fake.input.onClick = (fn) => {
clicks.push(fn);
return subscribe.call(fake.input, () => {});
};
parts.lifecycle.methods.init(viewer);
const coverage = () =>
draw.find('bikeshare:') &&
[...draw.sets.values()].find(
(set) => !set.disposed && set.spec.id.endsWith(':coverage'),
);
return {
state,
parts,
owners,
flights,
coverage,
click: (hit) => clicks.at(-1)({ drawHit: hit }),
async moveTo(height) {
camera.height = height;
await parts.viewport.runProximityCheck();
},
enable: () => parts.lifecycle.methods.enable(viewer),
disable: () => parts.lifecycle.methods.disable(),
};
}
test('every covered city has a marker, shown only while the layer is on and too high for stations', async () => {
const layer = makeLayer();
const set = layer.coverage();
assert.equal(set.items.size, GBFS_CITY_REGISTRY.length);
assert.equal(set.show, false, 'hidden while the layer is off');
layer.enable();
await layer.moveTo(18_000_000);
assert.equal(set.show, true, 'the globe shows where bike share is');
await layer.moveTo(20_000);
assert.equal(
set.show,
false,
'stations take over below the activation height',
);
await layer.moveTo(18_000_000);
assert.equal(set.show, true);
layer.disable();
assert.equal(set.show, false, 'gone with the layer');
});
test('a marker belongs to the layer and its click flies straight down into the city', async () => {
const layer = makeLayer();
layer.enable();
await layer.moveTo(18_000_000);
const city = GBFS_CITY_REGISTRY.find(
(each) => each.id === 'boston-bluebikes',
);
const id = `city:${city.id}`;
assert.equal(layer.owners.get('bikeshare')(id), true);
assert.equal(layer.owners.get('bikeshare')('city:nowhere'), false);
const navigated = [];
layer.parts.lifecycle.methods.attachShellServices({
runNavigation: (navigate) => {
navigated.push('explicit');
return navigate();
},
});
layer.click({ set: layer.coverage().spec.id, id });
assert.deepEqual(navigated, ['explicit'], 'an explicit camera action');
assert.equal(layer.flights.length, 1);
const { destination, options } = layer.flights[0];
assert.deepEqual(destination, {
lon: city.centerLon,
lat: city.centerLat,
height: COVERAGE_FLY_HEIGHT_M,
});
assert.equal(options.orientation.pitch, -Math.PI / 2);
assert.ok(COVERAGE_FLY_HEIGHT_M < 48_000, 'below the activation height');
});
+8 -19
View File
@@ -60,7 +60,7 @@ test('the layer reports failure when a failed city left it with nothing', () =>
});
test('a layer with nothing to draw and nothing failed is not an error', () => {
const { state, methods } = makeLayer();
const { methods } = makeLayer();
// Out of range of every city is empty, not broken.
assert.equal(methods.getStats().error, undefined);
@@ -83,7 +83,8 @@ test('a recovered city clears its own failure', () => {
// drive the real proximity check, status poll and lifecycle against a fake
// GBFS source, so the failure state they read is the state the layer builds.
import * as Cesium from 'cesium';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { CITY_BY_ID } from './registry.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
@@ -175,7 +176,7 @@ function makeLiveLayer() {
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
sprites: {},
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
};
const state = createState({ services });
@@ -195,21 +196,9 @@ function makeLiveLayer() {
parts.lifecycle = createLifecycle(context);
const { methods: controls } = createControls(context);
const camera = { ...BETWEEN, height: LOW_M };
const viewer = {
camera: {
get positionCartographic() {
return Cesium.Cartographic.fromDegrees(
camera.lon,
camera.lat,
camera.height,
);
},
computeViewRectangle: () => undefined,
changed: { addEventListener() {}, removeEventListener() {} },
},
scene: { globe: {}, primitives: { add() {}, remove() {} } },
};
const camera = fakeCameraPort({ pose: { ...BETWEEN, height: LOW_M } });
const viewer = {};
bindFakeDraw(viewer, { camera: camera.port });
parts.lifecycle.methods.init(viewer);
return {
@@ -217,7 +206,7 @@ function makeLiveLayer() {
source,
stats: () => controls.getStats(),
moveTo(place, height = LOW_M) {
Object.assign(camera, place, { height });
camera.setPose({ ...place, height });
return parts.viewport.runProximityCheck();
},
async enable() {
+59 -65
View File
@@ -1,10 +1,9 @@
import * as Cesium from 'cesium';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { BIKESHARE_SELECTED_OVERLAY_SOURCE_ID } from './policy.js';
import {
claimCameraSensitivity,
releaseCameraSensitivity,
} from '../../data/cameraSensitivity.js';
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
CAMERA_CHANGED_THRESHOLD,
} from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createLifecycle({
state: layerState,
@@ -12,28 +11,42 @@ export function createLifecycle({
parts,
source,
}) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { registerPickOwner, unregisterPickOwner } = services.picking;
/** Stop listening to the camera, if the layer is. */
function detachCamera() {
layerState._cameraChangedOff?.();
layerState._cameraChangedOff = null;
}
const methods = {
/**
* Initialize the bikeshare layer. Creates the point primitive collection,
* resets all internal state, and installs the click handler.
* Called once during app bootstrap.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* The shell's services: `runNavigation(navigate)` runs a covered city's
* flight as an explicit camera action, as the other camera controls are.
* @param {{ runNavigation?: Function }|null} shellServices
*/
attachShellServices(shellServices) {
layerState._runNavigation =
typeof shellServices?.runNavigation === 'function'
? shellServices.runNavigation
: null;
},
/**
* Initialize the bikeshare layer. Makes the station draw sets on the
* viewer's renderer (`drawOf`), resets all internal state, and installs
* the click handler. Called once during app bootstrap. Given a Cesium
* viewer with no renderer bound, the caller loads
* the package's `./render/cesium/unbound` export first.
* @param {object} viewer - The viewer the layer draws on.
*/
init(viewer) {
parts.rendering.attachSets(viewer);
layerState._viewer = viewer;
layerState._pointCollection = new Cesium.PointPrimitiveCollection({
blendOption: Cesium.BlendOption.TRANSLUCENT,
});
viewer.scene.primitives.add(layerState._pointCollection);
registerSpriteCollection('bikeshare', layerState._pointCollection);
layerState._pointCollection.show = false;
layerState._enabled = false;
layerState._cameraDebounceTimer = null;
layerState._cameraChangedAttached = false;
detachCamera();
layerState._altitudeGateEnabled = false;
layerState._proximityGeneration = 0;
@@ -44,9 +57,8 @@ export function createLifecycle({
layerState._inFlightInfo = new Map();
layerState._inFlightStatus = new Map();
layerState._stationRenderMap = new Map();
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._selectedKey = null;
layerState._selectedEntity = null;
layerState._count = 0;
layerState._lastUpdate = null;
layerState._loading = false;
@@ -61,8 +73,6 @@ export function createLifecycle({
parts.selection._installClickHandler(viewer);
restoreSpriteOrder(viewer);
console.log(
`[Data:Bikeshare] Initialized with ${GBFS_CITY_REGISTRY.length} cities`,
);
@@ -71,41 +81,42 @@ export function createLifecycle({
/**
* Enable the bikeshare layer. Shows points, attaches the camera listener,
* and triggers an initial proximity check.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
*/
enable(viewer) {
layerState._enabled = true;
layerState._failedCityIds.clear();
layerState._pointCollection.show = true;
layerState._stationSet.show = true;
layerState._overlayHost.setVisible(
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
true,
);
parts.selection._installClickHandler(viewer);
// Pick-ownership (H2): station point ids are string render-map keys.
registerPickOwner('bikeshare', (pickedId) =>
layerState._stationRenderMap.has(pickedId),
registerPickOwner(
'bikeshare',
(pickedId) =>
layerState._stationRenderMap.has(pickedId) ||
parts.selection.coverageCityOf(pickedId) !== null,
);
if (!layerState._cameraChangedAttached) {
viewer.camera.changed.addEventListener(parts.viewport.onCameraChanged);
// Through the shared ledger: this is a single number every layer's
// camera.changed listener shares, and a layer leaving must not hand
// back a coarse default while this one is still driving off it.
claimCameraSensitivity(viewer.camera, 'bikeshare', 0.05);
layerState._cameraChangedAttached = true;
if (!layerState._cameraChangedOff) {
// Its own threshold: the camera measures it for this listener alone.
layerState._cameraChangedOff = cameraOf(viewer).on(
'changed',
parts.viewport.onCameraChanged,
{ threshold: CAMERA_CHANGED_THRESHOLD },
);
}
void parts.viewport.runProximityCheck();
restoreSpriteOrder(viewer);
},
/**
* Disable the bikeshare layer. Hides points, removes event listeners,
* aborts all pending fetches, and tears down all city data.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
*/
disable(viewer) {
disable() {
layerState._enabled = false;
layerState._proximityGeneration++;
layerState._altitudeGateEnabled = false;
@@ -117,58 +128,41 @@ export function createLifecycle({
false,
);
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
document.removeEventListener('keydown', parts.selection._onKeyDown);
unregisterPickOwner('bikeshare');
if (layerState._cameraChangedAttached) {
viewer.camera.changed.removeEventListener(
parts.viewport.onCameraChanged,
);
releaseCameraSensitivity(viewer.camera, 'bikeshare');
layerState._cameraChangedAttached = false;
}
detachCamera();
parts.ingestion.abortAllInFlight();
parts.viewport.deactivateAllCities();
layerState._cityRuntime.clear();
layerState._pointCollection.show = false;
if (layerState._stationSet) layerState._stationSet.show = false;
parts.viewport.showCoverage(false);
layerState._count = 0;
layerState._loading = false;
layerState._loadingOps = 0;
},
/** Permanently release primitives, handlers, and the selected host source. */
destroy(viewer) {
if (layerState._enabled) this.disable(viewer);
/** Permanently release draw sets, handlers, and the selected host source. */
destroy() {
if (layerState._enabled) this.disable();
else {
parts.selection._clearSelection();
layerState._overlayHost.setVisible(
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
false,
);
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
document.removeEventListener('keydown', parts.selection._onKeyDown);
unregisterPickOwner('bikeshare');
}
if (layerState._cameraChangedAttached) {
viewer.camera.changed.removeEventListener(
parts.viewport.onCameraChanged,
);
releaseCameraSensitivity(viewer.camera, 'bikeshare');
layerState._cameraChangedAttached = false;
}
detachCamera();
parts.ingestion.abortAllInFlight();
if (layerState._pointCollection) {
viewer.scene.primitives.remove(layerState._pointCollection);
layerState._pointCollection = null;
}
parts.rendering.detachSets();
layerState._dataManager = null;
layerState._viewer = null;
},
};
+78 -14
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export const BIKESHARE_SELECTED_OVERLAY_SOURCE_ID = 'bikeshare-selected';
export const BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS = Object.freeze({
@@ -11,12 +9,28 @@ export const BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS = Object.freeze({
// --- Activation / display thresholds ---
/** Altitude (m) at which bikeshare layer becomes eligible for display. */
export const ACTIVATION_ALTITUDE_M = 50000;
const ACTIVATION_ALTITUDE_M = 50000;
/** Hysteresis enter threshold — layer activates when camera drops below this. */
export const ACTIVATION_ENTER_ALTITUDE_M = ACTIVATION_ALTITUDE_M - 2000;
/**
* Where a covered city's marker flies to: straight down from this height,
* well inside the activation band, with the city's stations in view.
*/
export const COVERAGE_FLY_HEIGHT_M = 20000;
/** A covered city's marker: the stations' green, larger, ringed in white. */
export const COVERAGE_PIXEL_SIZE = 11;
export const COVERAGE_OUTLINE_WIDTH = 2;
/**
* A marker's height: above the highest covered city's ground, so terrain
* never hides it, while the globe itself hides the markers behind it.
*/
export const COVERAGE_HEIGHT_M = 5000;
/** Hysteresis exit threshold — layer deactivates when camera rises above this. */
export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000;
@@ -25,6 +39,13 @@ export const ACTIVATION_EXIT_ALTITUDE_M = ACTIVATION_ALTITUDE_M + 2000;
export const CAMERA_DEBOUNCE_MS = 340;
/**
* How far the view moves before the camera tells the layer (the camera's
* `changed` threshold): fine, so it notices entering a city's range.
*/
export const CAMERA_CHANGED_THRESHOLD = 0.05;
/** Default radius (km) for determining whether a city is in camera range. */
export const CITY_RANGE_BASE_KM = 100;
@@ -55,31 +76,74 @@ export const POINT_HEIGHT_OFFSET_M = 2.0;
export const MAX_TOTAL_POINTS = 8000;
// --- Availability color palette ---
// Renderer colours, `[r, g, b, a]` in 0..1: the CSS colours below at the
// alphas the points draw them with.
/** A CSS `#rrggbb` colour at `alpha`, as a renderer colour. */
const hex = (css, alpha) =>
Object.freeze([
parseInt(css.slice(1, 3), 16) / 255,
parseInt(css.slice(3, 5), 16) / 255,
parseInt(css.slice(5, 7), 16) / 255,
alpha,
]);
/** Station has >60% bikes available. */
export const COLOR_GREEN =
Cesium.Color.fromCssColorString('#00ff88').withAlpha(0.95);
export const COLOR_GREEN = hex('#00ff88', 0.95);
/** Station has 30-60% bikes available. */
export const COLOR_YELLOW =
Cesium.Color.fromCssColorString('#ffaa00').withAlpha(0.94);
export const COLOR_YELLOW = hex('#ffaa00', 0.94);
/** Station has <30% bikes available. */
export const COLOR_RED =
Cesium.Color.fromCssColorString('#ff4444').withAlpha(0.94);
export const COLOR_RED = hex('#ff4444', 0.94);
/** No status data available for station. */
export const COLOR_NEUTRAL =
Cesium.Color.fromCssColorString('#91a4b4').withAlpha(0.62);
export const COLOR_NEUTRAL = hex('#91a4b4', 0.62);
/** Station is offline (not installed, not renting, or not returning). */
export const COLOR_MUTED =
Cesium.Color.fromCssColorString('#687581').withAlpha(0.48);
export const COLOR_MUTED = hex('#687581', 0.48);
/** Outline color for all station points. */
export const COLOR_OUTLINE = Cesium.Color.BLACK.withAlpha(0.25);
export const COLOR_OUTLINE = Object.freeze([0, 0, 0, 0.25]);
// --- Selected-station highlight ---
/** The selected station's dot: cyan, outlined black, drawn over everything. */
export const SELECTED_POINT_STYLE = Object.freeze({
pixelSize: 14,
color: Object.freeze([0, 1, 1, 1]),
outlineColor: Object.freeze([0, 0, 0, 1]),
outlineWidth: 2,
disableDepthTest: Number.POSITIVE_INFINITY,
});
// --- Station dot distance falloff ---
/** Station dots grow near the eye and shrink far from it. */
export const POINT_SCALE_BY_DISTANCE = Object.freeze({
near: 200,
nearValue: 1.35,
far: 130000,
farValue: 0.4,
});
/** Station dots fade out with distance. */
export const POINT_FADE_BY_DISTANCE = Object.freeze({
near: 200,
nearValue: 1.0,
far: 180000,
farValue: 0.15,
});
/** Station dots draw over the ground within this many metres of the eye. */
export const POINT_DISABLE_DEPTH_TEST_M = 2500;
+65 -1
View File
@@ -10,11 +10,16 @@
// Run with: npm test
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { rm } from 'node:fs/promises';
import { gbfsProxy } from '../../../server/providers/gbfs.js';
import { localProviderPlugins } from '../../../server/providers/local.js';
import { createBikeshareSource } from './source.js';
import { createModel } from './model.js';
import { CITY_BY_ID } from './registry.js';
import { makeFixtureRoot } from '../../tooling/fixtureRoot.mjs';
const nominatimStorageDir = await makeFixtureRoot('gev-gbfs-composition-');
test.after(() => rm(nominatimStorageDir, { recursive: true, force: true }));
const AUSTIN = CITY_BY_ID.get('austin-capmetro');
const OSLO = CITY_BY_ID.get('oslo-bysykkel');
@@ -339,7 +344,7 @@ test('the mounted route still refuses a host outside the allowlist', async () =>
* or from the preview half of it — fails here rather than in a browser.
*/
function composedGbfsPlugin() {
const plugin = localProviderPlugins().find(
const plugin = localProviderPlugins({ nominatimStorageDir }).find(
(entry) => entry.name === 'gbfs-proxy',
);
assert.ok(plugin, 'the application must compose a GBFS provider');
@@ -446,3 +451,62 @@ test('unknown GBFS counts stay unknown through the source, model and station col
assert.equal(model.toNonNegativeInteger('3'), 3);
}
});
test('a station without a published capacity re-derives it from every status poll', async () => {
const { createRendering } = await import('./rendering.js');
const { COLOR_YELLOW } = await import('./policy.js');
const model = createModel({});
const state = {
_cityRuntime: new Map(),
_stationRenderMap: new Map(),
_stationSet: { upsert() {}, remove() {} },
};
const rendering = createRendering({
state,
services: { render: { governorRequestRender() {} } },
parts: { model },
});
const info = model.parseStationInformation({
data: {
stations: [
{ station_id: 'open', name: 'Open', lat: 30.26, lon: -97.74 },
{
station_id: 'fixed',
name: 'Fixed',
lat: 30.27,
lon: -97.75,
capacity: 13,
},
],
},
});
rendering.ensureCityPoints('austin', info);
const poll = (stations) =>
rendering.applyStatusToPoints(
'austin',
model.parseStationStatus({ data: { stations } }),
);
const open = state._stationRenderMap.get('austin:open');
const fixed = state._stationRenderMap.get('austin:fixed');
// The first poll has no row for the station: capacity is a placeholder.
poll([
{
station_id: 'fixed',
num_bikes_available: 4,
num_docks_available: 9,
},
]);
poll([
{ station_id: 'open', num_bikes_available: 10, num_docks_available: 20 },
{ station_id: 'fixed', num_bikes_available: 2, num_docks_available: 3 },
]);
assert.equal(open.capacity, 30, 'the first poll fixed the capacity');
assert.equal(open.color, COLOR_YELLOW, '10 of 30 is not plenty');
assert.equal(fixed.capacity, 13, 'a published capacity is kept');
poll([
{ station_id: 'open', num_bikes_available: 4, num_docks_available: 2 },
]);
assert.equal(open.capacity, 6);
});
+7 -8
View File
@@ -26,24 +26,23 @@ export function createQueries({ state: layerState, services, parts, source }) {
* @param {Object} [options]
* @param {number} [options.maxCount] - Maximum number of detectable objects to return.
* @param {number} [options.seed] - Seed for deterministic stride offset selection.
* @returns {Array<{ position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean }>}
* @returns {Array<{ position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean }>}
*/
function collectDetectableStations(options = {}) {
if (
!layerState._enabled ||
!layerState._pointCollection ||
!layerState._pointCollection.show ||
!layerState._stationSet ||
!layerState._stationSet.show ||
layerState._stationRenderMap.size === 0
)
return [];
// Gather all visible station records (include selected even though its point is hidden)
// Gather all station records (the selected one too, though its own dot
// is hidden under the highlight)
const records = [];
for (const record of layerState._stationRenderMap.values()) {
const isSelected = record.key === layerState._selectedKey;
if ((!record.point?.show && !isSelected) || !record.point?.position)
continue;
if (!record.position) continue;
records.push(record);
}
if (records.length === 0) return [];
@@ -60,7 +59,7 @@ export function createQueries({ state: layerState, services, parts, source }) {
for (let i = start; i < records.length; i += stride) {
const record = records[i];
result.push({
position: record.point.position,
position: record.position,
sourceId: record.key,
id: buildDetectionId(record),
type: 'VEH',
+129 -41
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import {
DEFAULT_CAPACITY,
POINT_SIZE_MIN,
@@ -11,7 +10,28 @@ import {
POINT_HEIGHT_OFFSET_M,
MAX_TOTAL_POINTS,
COLOR_OUTLINE,
POINT_SCALE_BY_DISTANCE,
POINT_FADE_BY_DISTANCE,
POINT_DISABLE_DEPTH_TEST_M,
COVERAGE_PIXEL_SIZE,
COVERAGE_OUTLINE_WIDTH,
COVERAGE_HEIGHT_M,
} from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { heightsOf } from '../../queries/heights.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { drawOf } from '../../render/rendererOf.js';
/**
* The draw sets the stations are drawn in start with this; each layer has
* its own (`bikeshare:1:stations`, `bikeshare:1:selected`), so several can
* share a renderer. Picks name them as `Hit.set`.
*/
export const BIKESHARE_SET_ID = 'bikeshare';
/** A covered city's marker id: its registry id under this prefix. */
export const COVERAGE_ID_PREFIX = 'city:';
let instances = 0;
export function createRendering({
state: layerState,
@@ -21,6 +41,78 @@ export function createRendering({
}) {
const { governorRequestRender } = services.render;
/**
* Make the layer's draw sets on `viewer`'s renderer (`drawOf`): the
* station dots, hidden until the layer is enabled, and the selected
* station's highlight. Sets made before are let go first.
* @param {object} viewer
*/
function attachSets(viewer) {
const draw = drawOf(viewer);
detachSets();
const prefix = `${BIKESHARE_SET_ID}:${++instances}`;
layerState._stationSet = draw.points({
id: `${prefix}:stations`,
blend: 'translucent',
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
});
layerState._selectedSet = draw.points({ id: `${prefix}:selected` });
// One marker per covered city, drawn while the camera is too high for
// stations: the globe shows where bike share is.
layerState._coverageSet = draw.points({
id: `${prefix}:coverage`,
show: false,
drawOrder: services.sprites?.spriteDrawOrder?.('bikeshare') ?? 0,
});
layerState._coverageSet.set(
GBFS_CITY_REGISTRY.map((city) => ({
id: `${COVERAGE_ID_PREFIX}${city.id}`,
pos: fromDegrees(city.centerLon, city.centerLat, COVERAGE_HEIGHT_M),
pixelSize: COVERAGE_PIXEL_SIZE,
color: COLOR_GREEN,
outlineColor: [1, 1, 1, 0.9],
outlineWidth: COVERAGE_OUTLINE_WIDTH,
})),
);
// Drawn from the start, empty, so both take their place in the scene
// now, as the layer's collections did; the stations' place among the
// other sprite layers is their draw order (`spriteDrawOrder`).
layerState._stationSet.set([]);
layerState._selectedSet.set([]);
}
/** Let the layer's draw sets go. */
function detachSets() {
layerState._stationSet?.dispose();
layerState._selectedSet?.dispose();
layerState._coverageSet?.dispose();
layerState._stationSet = null;
layerState._selectedSet = null;
layerState._coverageSet = null;
}
/**
* A station's dot, from its render record; the selected station's own dot
* is hidden while its highlight replaces it.
* @param {Object} record - Render record from _stationRenderMap.
* @returns {import('../../render/contract/draw').PointItem}
*/
function stationItem(record) {
return {
id: record.key,
pos: record.position,
pixelSize: record.pixelSize,
color: record.color,
outlineColor: COLOR_OUTLINE,
outlineWidth: 1,
scaleByDistance: POINT_SCALE_BY_DISTANCE,
fadeByDistance: POINT_FADE_BY_DISTANCE,
disableDepthTest: POINT_DISABLE_DEPTH_TEST_M,
show: record.key !== layerState._selectedKey,
};
}
/**
* Resolve the effective dock capacity for a station.
* Prefers the explicit capacity from station_information; falls back to
@@ -68,7 +160,7 @@ export function createRendering({
* - <30% bikes available: red.
* @param {Object|null} status - Station status object.
* @param {number} capacity - Resolved station capacity.
* @returns {Cesium.Color} Color to apply to the station point.
* @returns {readonly number[]} Renderer colour `[r, g, b, a]` for the station point.
*/
function statusToColor(status, capacity) {
@@ -87,10 +179,10 @@ export function createRendering({
}
/**
* Create a Cartesian3 position for a station, terrain-clamped when possible.
* The ECEF position for a station, on the sampled surface when possible.
* Falls back to a fixed small height offset if terrain sampling is unsupported.
* @param {Object} station - Station info object with lat/lon.
* @returns {Cesium.Cartesian3|null} World position, or null if coordinates are invalid.
* @returns {{x: number, y: number, z: number}|null} ECEF metres, or null if coordinates are invalid.
*/
function createStationPosition(station) {
@@ -100,15 +192,13 @@ export function createRendering({
let height = POINT_HEIGHT_OFFSET_M;
// Sample terrain height so points sit on ground rather than at ellipsoid level
if (layerState._viewer?.scene?.sampleHeightSupported) {
const carto = Cesium.Cartographic.fromDegrees(lon, lat);
const sampled = layerState._viewer.scene.sampleHeight(carto);
if (Number.isFinite(sampled)) {
height = sampled + POINT_HEIGHT_OFFSET_M;
}
const viewer = layerState._viewer;
if (viewer && heightsOf(viewer).supported().surface) {
const sampled = heightsOf(viewer).now({ lon, lat });
if (sampled !== null) height = sampled + POINT_HEIGHT_OFFSET_M;
}
return Cesium.Cartesian3.fromDegrees(lon, lat, height);
return fromDegrees(lon, lat, height);
}
/**
@@ -126,8 +216,8 @@ export function createRendering({
}
/**
* Ensure point primitives exist for all stations in a city.
* Creates new points for stations not yet rendered; skips existing ones.
* Ensure dots exist for all stations in a city.
* Creates new dots for stations not yet rendered; skips existing ones.
* Respects the MAX_TOTAL_POINTS global cap to prevent GPU overload.
* @param {string} cityId - City identifier.
* @param {Map<string, Object>} stationMap - Parsed station info map for the city.
@@ -139,6 +229,7 @@ export function createRendering({
governorRequestRender('bikeshare-points');
const runtime = ensureCityRuntime(cityId);
const added = [];
for (const station of stationMap.values()) {
const key = parts.model.stationKey(cityId, station.stationId);
if (layerState._stationRenderMap.has(key)) {
@@ -160,46 +251,35 @@ export function createRendering({
const position = createStationPosition(station);
if (!position) continue;
// Add a point primitive with distance-based scale and translucency falloff
const point = layerState._pointCollection.add({
position,
pixelSize: capacityToPixelSize(station.capacity),
color: COLOR_NEUTRAL,
outlineColor: COLOR_OUTLINE,
outlineWidth: 1,
scaleByDistance: new Cesium.NearFarScalar(200, 1.35, 130000, 0.4),
translucencyByDistance: new Cesium.NearFarScalar(
200,
1.0,
180000,
0.15,
),
disableDepthTestDistance: 2500,
id: key,
});
layerState._stationRenderMap.set(key, {
const record = {
key,
cityId,
stationId: station.stationId,
stationName: station.name,
point,
position,
pixelSize: capacityToPixelSize(station.capacity),
color: COLOR_NEUTRAL,
capacity: parts.model.toNonNegativeInteger(station.capacity),
publishedCapacity: parts.model.toNonNegativeInteger(station.capacity),
bikesAvailable: null,
docksAvailable: null,
isInstalled: station.isInstalled,
isRenting: station.isRenting,
isReturning: station.isReturning,
});
};
layerState._stationRenderMap.set(key, record);
// A dot with distance-based scale and translucency falloff.
added.push(stationItem(record));
runtime.stationKeys.add(key);
}
if (added.length) layerState._stationSet?.upsert(added);
layerState._count = layerState._stationRenderMap.size;
}
/**
* Remove all rendered point primitives for a city and clean up runtime state.
* Remove all rendered dots for a city and clean up runtime state.
* Also clears any active selection if it belongs to this city.
* @param {string} cityId - City identifier to remove.
*/
@@ -216,12 +296,13 @@ export function createRendering({
parts.selection._clearSelection();
}
const removed = [];
for (const key of runtime.stationKeys) {
const record = layerState._stationRenderMap.get(key);
if (!record) continue;
layerState._pointCollection.remove(record.point);
if (!layerState._stationRenderMap.has(key)) continue;
removed.push(key);
layerState._stationRenderMap.delete(key);
}
if (removed.length) layerState._stationSet?.remove(removed);
layerState._cityRuntime.delete(cityId);
layerState._count = layerState._stationRenderMap.size;
@@ -240,12 +321,14 @@ export function createRendering({
const runtime = layerState._cityRuntime.get(cityId);
if (!runtime) return;
const updated = [];
for (const key of runtime.stationKeys) {
const record = layerState._stationRenderMap.get(key);
if (!record) continue;
const status = statusMap.get(record.stationId) || null;
const capacity = resolveCapacity(record.capacity, status);
// Resolve from the published capacity, not last poll's derived value.
const capacity = resolveCapacity(record.publishedCapacity, status);
record.capacity = capacity;
record.bikesAvailable = parts.model.toNonNegativeInteger(
@@ -265,11 +348,16 @@ export function createRendering({
);
// Update visual properties based on current status
record.point.pixelSize = capacityToPixelSize(capacity);
record.point.color = statusToColor(status, capacity);
record.pixelSize = capacityToPixelSize(capacity);
record.color = statusToColor(status, capacity);
updated.push(stationItem(record));
}
if (updated.length) layerState._stationSet?.upsert(updated);
}
return {
attachSets,
detachSets,
stationItem,
resolveCapacity,
capacityToPixelSize,
statusToColor,
+360
View File
@@ -0,0 +1,360 @@
// Bike Share's Layers row. With no system in range it says why instead of
// "never" and keeps no date for data it no longer draws. After the camera
// settles, the last row the panel painted must match what the layer reports
// now. Each case drives the real viewport,
// ingestion, rendering and controls; the manager is a spy that records the
// row text (LayerPanel._buildMetaText) at every refreshLayerStats() call.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CITY_BY_ID, GBFS_CITY_REGISTRY } from './registry.js';
import { createState } from './state.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createModel } from './model.js';
import { createViewport } from './viewport.js';
import { createRendering } from './rendering.js';
import { createLifecycle } from './lifecycle.js';
import { LayerPanel, layerFeedState } from '../../ui/layerPanel.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const BOSTON_ID = 'boston-bluebikes';
const TORONTO_ID = 'toronto-bike-share';
const BUFFALO_ID = 'buffalo-reddy';
const LONDON = { lat: 51.5072, lon: -0.1276 };
const BOSTON = { lat: 42.3601, lon: -71.0589 };
const BOSTON_NUDGED = { lat: 42.37, lon: -71.05 };
const BETWEEN = { lat: 43.25, lon: -79.1 };
const TORONTO_ONLY = { lat: 43.7, lon: -79.6 };
const LOW_M = 10_000;
globalThis.document ??= {
addEventListener() {},
removeEventListener() {},
};
function deferred() {
let resolve;
const promise = new Promise((res) => {
resolve = res;
});
return { promise, resolve };
}
function makeSource() {
const cityOf = (url) => {
for (const [id, city] of CITY_BY_ID) {
if (url === city.stationInformationUrl) return { id, kind: 'info' };
if (url === city.stationStatusUrl) return { id, kind: 'status' };
}
throw new Error(`unexpected GBFS url ${url}`);
};
const source = {
dead: new Set(),
/** `${cityId}:${kind}` → deferred that gates the answer. */
gates: new Map(),
async getStations(url, { signal } = {}) {
const { id, kind } = cityOf(url);
const gate = source.gates.get(`${id}:${kind}`);
if (gate) {
await new Promise((resolve, reject) => {
gate.promise.then(resolve);
signal?.addEventListener('abort', () =>
reject(Object.assign(new Error('aborted'), { name: 'AbortError' })),
);
});
} else {
await new Promise((resolve) => setTimeout(resolve, 1));
}
signal?.throwIfAborted();
if (source.dead.has(id)) throw new Error('GBFS HTTP 503');
const city = CITY_BY_ID.get(id);
if (kind === 'info') {
return {
data: {
stations: [
{
station_id: `${id}-1`,
name: `${id} dock`,
lat: city.centerLat,
lon: city.centerLon,
capacity: 10,
},
],
},
};
}
return {
data: {
stations: [
{
station_id: `${id}-1`,
num_bikes_available: 3,
num_docks_available: 7,
is_installed: true,
is_renting: true,
is_returning: true,
},
],
},
};
},
};
return source;
}
/** The row as the panel draws it: state chip, count, meta text. */
const rowText = (raw) => {
const stats = {
count: 0,
lastUpdate: null,
...raw,
loading: raw.loading === true,
};
const meta = LayerPanel.prototype._buildMetaText({
id: 'bikeshare',
source: 'GBFS',
enabled: true,
lifecycleState: 'enabled',
stats,
});
return `${layerFeedState(stats)} | ${stats.count || '—'} | ${meta}`;
};
function makeLiveLayer() {
const source = makeSource();
const services = {
render: { governorRequestRender() {} },
overlays: {
setOverlayEntries() {},
setOverlaySourceVisible() {},
clearOverlaySource() {},
},
sprites: { registerSpriteCollection() {}, restoreSpriteOrder() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} },
};
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.ingestion = createIngestion(context);
parts.model = createModel(context);
parts.viewport = createViewport(context);
parts.rendering = createRendering(context);
parts.selection = {
_installClickHandler() {},
_clearSelection() {},
_onKeyDown() {},
};
parts.queries = { collectDetectableStations: () => [] };
parts.lifecycle = createLifecycle(context);
const { methods: controls } = createControls(context);
const camera = { ...LONDON, height: LOW_M };
const viewer = {};
bindFakeDraw(viewer, {
camera: {
pose: () => ({ lon: camera.lon, lat: camera.lat, height: camera.height }),
viewRectangle: () => null,
on: () => () => {},
},
});
parts.lifecycle.methods.init(viewer);
const painted = [];
controls.attachDataManager({
refreshLayerStats() {
painted.push(rowText(controls.getStats()));
},
});
return {
state,
source,
painted,
lastPainted: () => painted.at(-1),
stats: () => controls.getStats(),
live: () => rowText(controls.getStats()),
moveTo(place, height = LOW_M) {
Object.assign(camera, place, { height });
return parts.viewport.runProximityCheck();
},
async enable() {
parts.lifecycle.methods.enable(viewer);
await settle();
},
};
}
async function settle() {
for (let i = 0; i < 5; i += 1)
await new Promise((resolve) => setTimeout(resolve, 2));
}
test('entering a city paints the loading row, not "never"', async () => {
const layer = makeLiveLayer();
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const before = layer.painted.length;
const entering = layer.moveTo(BOSTON);
assert.ok(layer.painted.length > before, 'entering repainted');
const atEntry = layer.lastPainted();
const liveAfter = layer.live();
info.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('re-entering a city with cached station info paints loading', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
await layer.moveTo(LONDON);
await settle();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
const entering = layer.moveTo(BOSTON);
const atEntry = layer.lastPainted();
await Promise.resolve();
await Promise.resolve();
const liveAfter = layer.live();
status.resolve();
await entering;
await settle();
assert.match(liveAfter, /syncing 1 city feeds/);
assert.match(atEntry, /^loading \|/, 'the entry repaint reads loading');
assert.doesNotMatch(atEntry, /never/);
});
test('leaving a city mid-load does not leave the row on LOADING', async () => {
const layer = makeLiveLayer();
layer.source.gates.set(`${BOSTON_ID}:info`, deferred());
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.equal(layer.state._loading, true);
await layer.moveTo(LONDON);
await entering;
await settle();
assert.equal(layer.state._loading, false);
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('a camera nudge during the first load still repaints the drawn stations', async () => {
const layer = makeLiveLayer();
const status = deferred();
layer.source.gates.set(`${BOSTON_ID}:status`, status);
await layer.enable();
const entering = layer.moveTo(BOSTON);
await settle();
assert.ok(layer.state._cityRuntime.has(BOSTON_ID), 'points are drawn');
await layer.moveTo(BOSTON_NUDGED);
status.resolve();
await entering;
await settle();
assert.equal(layer.state._count, 1, 'one station on the map');
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving a city whose load failed repaints the error away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BOSTON_ID);
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.match(layer.lastPainted(), /GBFS fetch error/i);
await layer.moveTo(LONDON);
await settle();
assert.match(layer.live(), /No bike share here yet/);
assert.equal(layer.lastPainted(), layer.live());
});
test('leaving the failed city of two repaints DEGRADED away', async () => {
const layer = makeLiveLayer();
layer.source.dead.add(BUFFALO_ID);
await layer.enable();
await layer.moveTo(BETWEEN);
await settle();
assert.match(layer.lastPainted(), /^degraded/);
await layer.moveTo(TORONTO_ONLY);
await settle();
assert.doesNotMatch(layer.live(), /^degraded/);
assert.equal(layer.lastPainted(), layer.live());
});
test('above the altitude gate the row says how low to fly', async () => {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(LONDON, 2_000_000);
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(stats.statusMessage, 'Fly below 48 km to a covered city');
assert.equal(stats.error, undefined);
});
test('a city with no system says so and counts the ones there are', async () => {
const layer = makeLiveLayer();
await layer.enable();
const stats = layer.stats();
assert.equal(stats.status, 'zoom-in');
assert.equal(
stats.statusMessage,
`No bike share here yet · ${GBFS_CITY_REGISTRY.length} systems available`,
);
assert.equal(stats.count, 0);
});
test('a city in range, loading, failed or a disabled layer gets no prompt', async () => {
const layer = makeLiveLayer();
assert.equal(layer.stats().status, undefined, 'disabled');
const info = deferred();
layer.source.gates.set(`${BOSTON_ID}:info`, info);
await layer.enable();
const entering = layer.moveTo(BOSTON);
assert.equal(layer.stats().status, undefined, 'loading');
info.resolve();
await entering;
await settle();
assert.equal(layer.stats().status, undefined, 'loaded');
// Left mid-load: range is empty, but the aborted load still owns the row.
const leaving = makeLiveLayer();
leaving.source.gates.set(`${BOSTON_ID}:info`, deferred());
await leaving.enable();
const loading = leaving.moveTo(BOSTON);
await settle();
const left = leaving.moveTo(LONDON);
assert.equal(leaving.state._activeCityIds.size, 0);
assert.equal(leaving.stats().loading, true);
assert.equal(leaving.stats().status, undefined, 'leaving mid-load');
await Promise.all([loading, left]);
const failed = makeLiveLayer();
failed.source.dead.add(BOSTON_ID);
await failed.enable();
await failed.moveTo(BOSTON);
await settle();
assert.equal(failed.stats().status, undefined, 'failed');
assert.equal(failed.stats().error, 'GBFS fetch error');
});
test('leaving every system behind drops the date of the data it drew', async () => {
for (const height of [LOW_M, 2_000_000]) {
const layer = makeLiveLayer();
await layer.enable();
await layer.moveTo(BOSTON);
await settle();
assert.ok(layer.stats().lastUpdate, 'Boston is dated');
await layer.moveTo(LONDON, height);
assert.equal(layer.stats().lastUpdate, null, `at ${height} m`);
}
});
+79 -58
View File
@@ -1,10 +1,15 @@
import * as Cesium from 'cesium';
import { t } from '../../i18n/index.js';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import { isUnderOtherCard } from '../../data/pickRegistry.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_ID,
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
SELECTED_POINT_STYLE,
COVERAGE_FLY_HEIGHT_M,
} from './policy.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import { COVERAGE_ID_PREFIX } from './rendering.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createSelection({
state: layerState,
@@ -63,7 +68,7 @@ export function createSelection({
*/
function createBikeshareSelectedOverlayEntry(key, record) {
const position = record?.point?.position;
const position = record?.position;
if (!key || !position) return null;
const [title, ...details] = buildSelectionLabel(record).split('\n');
return {
@@ -91,29 +96,22 @@ export function createSelection({
/**
* Clear the current station selection.
* Re-shows the hidden point primitive and removes the highlight entity.
* Shows the station's own dot again and removes the highlight.
*/
function _clearSelection() {
if (layerState._selectedKey) {
const record = layerState._stationRenderMap.get(layerState._selectedKey);
if (record?.point) {
record.point.show = true;
}
}
if (layerState._selectedEntity && layerState._viewer) {
layerState._viewer.entities.remove(layerState._selectedEntity);
}
const key = layerState._selectedKey;
layerState._selectedKey = null;
layerState._selectedEntity = null;
const record = key ? layerState._stationRenderMap.get(key) : null;
if (record?.position)
layerState._stationSet?.upsert([parts.rendering.stationItem(record)]);
if (layerState._selectedSet?.size()) layerState._selectedSet.clear();
layerState._overlayHost.clearSource(BIKESHARE_SELECTED_OVERLAY_SOURCE_ID);
}
/**
* Select a station by key: hides the original point primitive and adds a
* highlighted cyan entity plus a protected shared-host availability card.
* Select a station by key: hides its own dot and draws a highlighted cyan
* one in its place, plus a protected shared-host availability card.
* @param {string} key - Composite "cityId:stationId" key.
*/
@@ -121,22 +119,14 @@ export function createSelection({
_clearSelection();
const record = layerState._stationRenderMap.get(key);
if (!record || !record.point?.position || !layerState._viewer) return;
if (!record || !record.position || !layerState._stationSet) return;
layerState._selectedKey = key;
// Hide the base point so the highlight entity replaces it visually
record.point.show = false;
layerState._selectedEntity = layerState._viewer.entities.add({
position: record.point.position,
point: {
pixelSize: 14,
color: Cesium.Color.CYAN,
outlineColor: Cesium.Color.BLACK,
outlineWidth: 2,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
},
});
// Hide the base dot so the highlight replaces it visually
layerState._stationSet.upsert([parts.rendering.stationItem(record)]);
layerState._selectedSet?.set([
{ id: 'selected', pos: record.position, ...SELECTED_POINT_STYLE },
]);
const entry = createBikeshareSelectedOverlayEntry(key, record);
if (entry) {
layerState._overlayHost.setEntries(
@@ -151,46 +141,76 @@ export function createSelection({
* Install a screen-space click handler for station selection/deselection.
* Also registers a global keydown listener for Escape-to-deselect.
* Idempotent — does nothing if a handler is already installed.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
*/
/**
* The covered city a marker id names, or null.
* @param {unknown} id
*/
function coverageCityOf(id) {
if (typeof id !== 'string' || !id.startsWith(COVERAGE_ID_PREFIX))
return null;
const cityId = id.slice(COVERAGE_ID_PREFIX.length);
return GBFS_CITY_REGISTRY.find((city) => city.id === cityId) ?? null;
}
/**
* Straight down over a covered city, low enough for its stations, as the
* shell's camera action when it gave one.
* @param {{ centerLat: number, centerLon: number }} city
*/
function flyIntoCity(city) {
const viewer = layerState._viewer;
if (!viewer) return;
const fly = () =>
cameraOf(viewer).flyTo(
{
lon: city.centerLon,
lat: city.centerLat,
height: COVERAGE_FLY_HEIGHT_M,
},
{ orientation: { heading: 0, pitch: -Math.PI / 2, roll: 0 } },
);
if (layerState._runNavigation) layerState._runNavigation(fly);
else fly();
}
function _installClickHandler(viewer) {
if (layerState._clickHandler) return;
if (layerState._clickSubscription) return;
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
viewer.scene.canvas,
);
layerState._clickHandler.setInputAction((click) => {
// A tool owns the pointer (src/data/inputOwnership.js): yield the click.
if (!isPointerFree()) return;
const picked = viewer.scene.pick(click.position);
layerState._clickSubscription = inputFor(viewer).onClick((event) => {
// Another layer's card or label painted on top takes the click: the item
// under it does not act, and the click is not empty space either.
if (isUnderOtherCard(event)) return;
const hit = event.drawHit;
if (picked) {
// Clicking selected entity itself — ignore (don't deselect).
if (picked.id === layerState._selectedEntity) return;
if (hit) {
// Clicking the selected highlight itself — ignore (don't deselect).
if (hit.set === layerState._selectedSet?.id) return;
// Check if the picked primitive or entity id matches a station key
const primitive = picked.primitive;
if (
primitive &&
typeof primitive.id === 'string' &&
layerState._stationRenderMap.has(primitive.id)
) {
_selectStation(primitive.id);
return;
// A covered city's marker: fly down into it.
if (hit.set === layerState._coverageSet?.id) {
const city = coverageCityOf(hit.id);
if (city) {
flyIntoCity(city);
return;
}
}
// A station dot of this layer's own set
if (
typeof picked.id === 'string' &&
layerState._stationRenderMap.has(picked.id)
hit.set === layerState._stationSet?.id &&
layerState._stationRenderMap.has(hit.id)
) {
_selectStation(picked.id);
_selectStation(hit.id);
return;
}
}
// Clicked empty space — deselect.
// Clicked anything else — deselect.
if (layerState._selectedKey) _clearSelection();
}, Cesium.ScreenSpaceEventType.LEFT_CLICK);
});
document.addEventListener('keydown', _onKeyDown);
}
@@ -212,5 +232,6 @@ export function createSelection({
_selectStation,
_installClickHandler,
_onKeyDown,
coverageCityOf,
};
}
+68
View File
@@ -0,0 +1,68 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createSelection } from './selection.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { setClickCardHitTest } from '../../data/pickRegistry.js';
/** A station layer's selection on a viewer whose pick is scripted. */
function harness(t) {
const previousDocument = globalThis.document;
globalThis.document = new EventTarget();
let picked = null;
const viewer = { scene: { canvas: new EventTarget(), pick: () => picked } };
const input = fakeInput(viewer);
const noop = () => {};
const state = {
_selectedKey: null,
_clickSubscription: null,
_stationRenderMap: new Map([['nyc:1', { position: { x: 1, y: 0, z: 0 } }]]),
_stationSet: { id: 'bikeshare:stations', upsert: noop },
_selectedSet: {
id: 'bikeshare:selected',
set: noop,
size: () => 0,
clear: noop,
},
_overlayHost: { setEntries: noop, clearSource: noop },
};
const selection = createSelection({
state,
services: {},
parts: { rendering: { stationItem: () => ({}) } },
});
selection._installClickHandler(viewer);
t.after(() => {
state._clickSubscription?.();
input.destroy();
if (previousDocument === undefined) delete globalThis.document;
else globalThis.document = previousDocument;
});
return {
state,
click(hit) {
picked = hit ? { id: hit } : null;
input.tap({ x: 10, y: 10 });
},
};
}
// The card or label painted on top takes the click: a station under another
// layer's card is neither selected nor let go.
test("another layer's card over a station keeps the click", (t) => {
const h = harness(t);
let top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
setClickCardHitTest(() => top);
t.after(() => setClickCardHitTest(null));
const station = { set: 'bikeshare:stations', id: 'nyc:1' };
h.click(station);
assert.equal(h.state._selectedKey, null, 'covered: not selected');
top = null;
h.click(station);
assert.equal(h.state._selectedKey, 'nyc:1');
top = { sourceId: 'earthquake-card', entryId: 'earthquake-card:ak1' };
h.click(null);
assert.equal(h.state._selectedKey, 'nyc:1', 'covered: kept');
top = null;
h.click(null);
assert.equal(h.state._selectedKey, null, 'open map lets it go');
});
+26 -11
View File
@@ -15,13 +15,32 @@ export function createState({ services }) {
// Module-level mutable state
// ---------------------------------------------------------------------------
/** @type {Cesium.Viewer|null} Active Cesium viewer instance. */
/** @type {object|null} The viewer the layer draws on. */
layerState._viewer = null;
/** @type {Cesium.PointPrimitiveCollection|null} Primitive collection for station dots. */
/** @type {{ refreshLayerStats?: (layerId?: string) => void }|null} Manager that repaints the layer's row. */
layerState._pointCollection = null;
layerState._dataManager = null;
/** Draw set of the station dots (`drawOf(viewer).points`), or null. */
layerState._stationSet = null;
/**
* Draw set of the covered cities' markers, shown above the activation
* height so the globe says where bike share is, or null.
*/
layerState._coverageSet = null;
/** The shell's camera action for a marker's flight (`attachShellServices`), or null. */
layerState._runNavigation = null;
/** Draw set of the selected station's highlight dot, or null. */
layerState._selectedSet = null;
/** Whether the bikeshare layer is currently enabled. */
@@ -31,9 +50,9 @@ export function createState({ services }) {
layerState._cameraDebounceTimer = null;
/** Whether the camera.changed listener is currently attached. */
/** @type {(() => void)|null} Stops the camera `changed` listener, while attached. */
layerState._cameraChangedAttached = false;
layerState._cameraChangedOff = null;
/** Hysteresis flag for altitude-based activation. */
@@ -71,18 +90,14 @@ export function createState({ services }) {
layerState._stationRenderMap = new Map();
/** @type {Cesium.ScreenSpaceEventHandler|null} Click handler for station selection. */
/** @type {(() => void)|null} Unsubscribes the station-selection click. */
layerState._clickHandler = null;
layerState._clickSubscription = null;
/** @type {string|null} Key of the currently selected station, or null. */
layerState._selectedKey = null;
/** @type {Cesium.Entity|null} Entity used to display the selected-station point highlight. */
layerState._selectedEntity = null;
/** Total number of currently rendered station points. */
layerState._count = 0;
+1 -1
View File
@@ -8,9 +8,9 @@ export function createTesting({ state: layerState, services, parts, source }) {
overlayHost,
}) {
layerState._viewer = viewer;
parts.rendering.attachSets(viewer);
layerState._stationRenderMap = new Map([[key, record]]);
layerState._selectedKey = null;
layerState._selectedEntity = null;
layerState._overlayHost = overlayHost || layerState.DEFAULT_OVERLAY_HOST;
}
+59 -23
View File
@@ -1,4 +1,5 @@
import * as Cesium from 'cesium';
import { negativePiToPi, toDegrees, toRadians } from '../../geo/vector.js';
import { findCamera } from '../../render/rendererOf.js';
import { GBFS_CITY_REGISTRY } from './registry.js';
import {
ACTIVATION_EXIT_ALTITUDE_M,
@@ -12,44 +13,42 @@ export function createViewport({ state: layerState, services, parts, source }) {
/**
* Get the camera's current altitude in meters above the ellipsoid.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* @param {object} viewer - The viewer the layer draws on.
* @returns {number} Altitude in meters, or Infinity if unavailable.
*/
function getCameraAltitude(viewer) {
const carto = viewer?.camera?.positionCartographic;
return carto && Number.isFinite(carto.height) ? carto.height : Infinity;
const height = findCamera(viewer)?.pose().height;
return Number.isFinite(height) ? height : Infinity;
}
/**
* Determine the lat/lon the camera is currently looking at.
* Prefers the center of the computed view rectangle; falls back to the
* camera's own cartographic position when the rectangle is unavailable.
* @param {Cesium.Viewer} viewer - Cesium viewer instance.
* Prefers the center of the view rectangle; falls back to the camera's
* own position when the rectangle is unavailable.
* @param {object} viewer - The viewer the layer draws on.
* @returns {{ lat: number, lon: number }|null} Center coordinates in degrees, or null.
*/
function getCameraCenterLatLon(viewer) {
const camera = findCamera(viewer);
// Try view rectangle center first (more accurate for tilted views)
const rect = viewer?.camera?.computeViewRectangle?.(
viewer.scene.globe?.ellipsoid,
);
const rect = camera?.viewRectangle();
if (rect) {
const center = Cesium.Rectangle.center(rect);
// Across the antimeridian the east edge is west of the west one.
let east = toRadians(rect.east);
const west = toRadians(rect.west);
if (east < west) east += 2 * Math.PI;
return {
lat: Cesium.Math.toDegrees(center.latitude),
lon: Cesium.Math.toDegrees(center.longitude),
lat: (rect.south + rect.north) * 0.5,
lon: toDegrees(negativePiToPi((west + east) * 0.5)),
};
}
// Fallback: use the camera's own position
const carto = viewer?.camera?.positionCartographic;
if (carto) {
return {
lat: Cesium.Math.toDegrees(carto.latitude),
lon: Cesium.Math.toDegrees(carto.longitude),
};
}
const pose = camera?.pose();
if (pose && Number.isFinite(pose.lat) && Number.isFinite(pose.lon))
return { lat: pose.lat, lon: pose.lon };
return null;
}
@@ -116,6 +115,23 @@ export function createViewport({ state: layerState, services, parts, source }) {
parts.rendering.removeCityPoints(cityId);
}
/**
* Show the covered cities' markers, or hide them: shown while the layer is
* on and the camera is too high for stations.
* @param {boolean} shown
*/
function showCoverage(shown) {
const set = layerState._coverageSet;
if (!set || set.show === shown) return;
set.show = shown;
governorRequestRender('bikeshare-coverage');
}
/** Repaint the row now: it follows the camera, the manager tick is 60 s. */
function refreshRow() {
layerState._dataManager?.refreshLayerStats?.('bikeshare');
}
/** Deactivate all currently active cities and clear the active set. */
function deactivateAllCities() {
@@ -125,6 +141,8 @@ export function createViewport({ state: layerState, services, parts, source }) {
// A failure belongs to a city in range; none are once everything is off.
layerState._failedCityIds.clear();
layerState._count = 0;
// Nothing is left on the map to date.
layerState._lastUpdate = null;
}
/**
@@ -203,12 +221,16 @@ export function createViewport({ state: layerState, services, parts, source }) {
const generation = ++layerState._proximityGeneration;
const altitude = getCameraAltitude(layerState._viewer);
const wasGateEnabled = layerState._altitudeGateEnabled;
// Altitude gate: disable all cities when camera is too high
if (!shouldActivateAtAltitude(altitude)) {
showCoverage(true);
deactivateAllCities();
if (wasGateEnabled) refreshRow();
return;
}
showCoverage(false);
const center = getCameraCenterLatLon(layerState._viewer);
if (!center) return;
@@ -220,15 +242,25 @@ export function createViewport({ state: layerState, services, parts, source }) {
}
}
// A failure never outlives its city's range.
let failureCleared = false;
for (const cityId of layerState._failedCityIds) {
if (!nextActive.has(cityId)) layerState._failedCityIds.delete(cityId);
if (!nextActive.has(cityId)) {
layerState._failedCityIds.delete(cityId);
failureCleared = true;
}
}
const changed =
!wasGateEnabled ||
failureCleared ||
nextActive.size !== layerState._activeCityIds.size ||
[...nextActive].some((cityId) => !layerState._activeCityIds.has(cityId));
layerState._activeCityIds = nextActive;
if (layerState._activeCityIds.size === 0) {
if (nextActive.size === 0) {
layerState._count = 0;
return;
layerState._lastUpdate = null;
}
if (changed) refreshRow();
// Only activate cities that don't already have rendered points
const toActivate = [];
@@ -240,6 +272,9 @@ export function createViewport({ state: layerState, services, parts, source }) {
await Promise.all(
toActivate.map((cityId) => activateCity(cityId, generation)),
);
// Superseded loads repaint too: a newer check may have painted the row
// while this one was still loading, or found nothing to load itself.
if (layerState._enabled) refreshRow();
}
/** Schedule a debounced proximity check after camera movement. */
@@ -267,6 +302,7 @@ export function createViewport({ state: layerState, services, parts, source }) {
activateCity,
runProximityCheck,
scheduleProximityCheck,
showCoverage,
onCameraChanged,
};
}
+2
View File
@@ -261,6 +261,8 @@ export function createCalibration({
// §9.1: touching range takes manual control — clear the activation clamp.
if ('rangeScale' in patch) {
record.probeClampRangeM = null;
// A probe still to answer no longer lands.
record.probeToken = (record.probeToken || 0) + 1;
}
const anchorMoved = calibrationPatchMovesAnchor(patch);
if (options.transient === true && anchorMoved) {
+39 -34
View File
@@ -1,3 +1,4 @@
import { findFrame } from '../../render/rendererOf.js';
import {
createFrameSlot,
CCTV_OVERLAY_SOURCE_ID,
@@ -8,8 +9,6 @@ import {
CCTV_FRAME_CANVAS_H,
applyFrameResult,
} from '../../data/cctvCards.js';
import * as Cesium from 'cesium';
import { horizonOccluder } from '../../data/iconOrientation.js';
import { selectCctvLod, applyEvictionGrace } from '../../data/cctvLod.js';
import {
CCTV_OVERLAY_SOURCE_OPTIONS,
@@ -35,7 +34,7 @@ export function createCards({ state: layerState, services, parts, source }) {
} = {}) {
layerState._activeCameraCardEnabled = activeCameraCardEnabled === true;
if (layerState._enabled) pushAmbientCardEntries();
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-cards');
return { activeCameraCardEnabled: layerState._activeCameraCardEnabled };
}
@@ -83,44 +82,42 @@ export function createCards({ state: layerState, services, parts, source }) {
);
return;
}
const scene = layerState._viewer.scene;
const carto = layerState._viewer.camera.positionCartographic;
const viewerLat = carto ? Cesium.Math.toDegrees(carto.latitude) : 0;
const viewerLon = carto ? Cesium.Math.toDegrees(carto.longitude) : 0;
// An eye with no geographic position (the earth's centre) measures from 0, 0.
const pose = parts.model.eyePose();
const viewerLat = pose ? pose.lat : 0;
const viewerLon = pose ? pose.lon : 0;
// The active camera is excluded from ambient selection ALWAYS (not just
// after its async activation settles). It is published separately in the
// protected lane below, and grace never applies to it.
const activeId = layerState._activeCameraId;
const occluder = horizonOccluder(layerState._viewer.camera);
const width = scene.canvas.clientWidth || scene.canvas.width || 0;
const height = scene.canvas.clientHeight || scene.canvas.height || 0;
const view = parts.rendering.cardView();
const { width, height } = view;
const marginX = width * CARD_VIEW_MARGIN;
const marginY = height * CARD_VIEW_MARGIN;
const candidates = [];
const screenById = new Map();
for (const record of layerState._records) {
// Cards go only on the icons the view pass shows (refreshHorizonCulling).
for (const record of layerState._viewRecords) {
const id = record.camera.id;
if (id === activeId || !record.position) continue;
let inView = false;
let sx = NaN;
let sy = NaN;
if (occluder.isPointVisible(record.position)) {
const screen = scene.cartesianToCanvasCoordinates(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
const screen = view.screenOf(record.position);
if (
screen &&
Number.isFinite(screen.x) &&
Number.isFinite(screen.y) &&
screen.x >= -marginX &&
screen.x <= width + marginX &&
screen.y >= -marginY &&
screen.y <= height + marginY
) {
inView = true;
sx = screen.x;
sy = screen.y;
screenById.set(id, { sx, sy });
}
candidates.push({
id,
@@ -131,9 +128,11 @@ export function createCards({ state: layerState, services, parts, source }) {
record.camera.lon,
),
inView,
isVideo: parts.model.isVideoFeedType(
parts.model.normalizeFeedType(record.camera.feedType),
),
// Québec's browser-only sources have no registered frame endpoint;
// keep them out of still-card fill just like video feeds.
isVideo:
parts.model.isVideoFeedCamera(record.camera) ||
parts.model.isBrowserOverlayCamera(record.camera),
sx,
sy,
});
@@ -145,7 +144,7 @@ export function createCards({ state: layerState, services, parts, source }) {
// the budget fill through the screen-distribution grid, so periphery
// cells hold cards instead of everything clustering at screen center.
const { cardIds, budgets } = selectCctvLod(candidates, {
cameraHeightM: carto?.height,
cameraHeightM: pose?.height,
incumbentIds: layerState._cardIds,
viewW: width,
viewH: height,
@@ -187,7 +186,14 @@ export function createCards({ state: layerState, services, parts, source }) {
nowMs: Date.now(),
cardLimit: budgets.cardLimit,
});
layerState._cardIds = new Set(retention.keepIds);
// Grace keeps a card briefly after it loses selection, but never on a
// camera whose icon the view pass has hidden.
const shownIds = new Set(
layerState._viewRecords.map((record) => record.camera.id),
);
layerState._cardIds = new Set(
retention.keepIds.filter((id) => shownIds.has(id)),
);
layerState._cardGraceState = retention.graceState;
// Bounded thumbnail LRU: live cards (grace included) never lose their
@@ -325,7 +331,7 @@ export function createCards({ state: layerState, services, parts, source }) {
slot,
applyFrameResult(slot, { ok: !!frame, frame }, Date.now()),
);
layerState._viewer?.scene?.requestRender?.();
findFrame(layerState._viewer)?.requestRender('cctv-card-frame');
};
image.onload = () => settle(true);
image.onerror = () => settle(false);
@@ -371,7 +377,6 @@ export function createCards({ state: layerState, services, parts, source }) {
layerState._cctvOverlayHost.clearSource(CCTV_OVERLAY_SOURCE_ID);
layerState._cctvOverlayHost.setVisible(CCTV_OVERLAY_SOURCE_ID, false);
parts.hover.clearHoverCard();
layerState._cameraMoving = false;
layerState._cardIds = new Set();
layerState._cardGraceState = new Map();
layerState._cardFrameSlots = new Map();
+6 -1
View File
@@ -1,4 +1,4 @@
import { CAMERA_SEEDS, SOURCE_ENDPOINT } from './policy.js';
import { CAMERA_SEEDS } from './policy.js';
import {
lookupModelSpec,
horizontalFovRangeDeg,
@@ -237,9 +237,14 @@ export function createCatalog({ state: layerState, services, parts, source }) {
groundElevationM,
absoluteHeightM: groundElevationM + mountHeightM,
pitchDeg,
frameRefreshMs: parts.model.safeNumber(source.frameRefreshMs, NaN),
license: String(source.license || source.licenseNote || ''),
credit: String(source.credit || ''),
code: String(source.code || ''),
sourceUrl: String(source.sourceUrl || ''),
browserMediaUrl: String(source.browserMediaUrl || ''),
accuracyM: parts.model.safeNumber(source.accuracyM, NaN),
positionSource: String(source.positionSource || ''),
// Shipped precompute (see server/providers/cctv/groundHeights.js).
groundHeights:
source.groundHeights && typeof source.groundHeights === 'object'
+28 -10
View File
@@ -202,25 +202,24 @@ export function createControls({ state: layerState, services, parts, source }) {
* @param {Object} [options={}]
* @param {number} [options.maxCount] - Maximum number of objects to return.
* @param {number} [options.seed] - Offset seed for deterministic stride sampling.
* @returns {{ position: Cesium.Cartesian3, id: string, type: string }[]}
* @returns {{ position: {x: number, y: number, z: number}, id: string, type: string }[]}
*/
getDetectableObjects(options = {}) {
if (!layerState._enabled || layerState._records.length === 0) return [];
// The cameras the view pass shows, not icons it has hidden.
const records = layerState._viewRecords;
if (!layerState._enabled || records.length === 0) return [];
const maxCount = Number.isFinite(options.maxCount)
? Math.max(1, Math.floor(options.maxCount))
: layerState._records.length;
: records.length;
const seed = Number.isFinite(options.seed) ? Math.floor(options.seed) : 0;
const stride = Math.max(
1,
Math.ceil(layerState._records.length / maxCount),
);
const stride = Math.max(1, Math.ceil(records.length / maxCount));
const start = seed % stride;
const objects = [];
for (let i = start; i < layerState._records.length; i += stride) {
const camera = layerState._records[i].camera;
for (let i = start; i < records.length; i += stride) {
const camera = records[i].camera;
objects.push({
position: layerState._records[i].position,
position: records[i].position,
sourceId: camera.id,
// Short semantic code where the id is opaque (see cameraDisplayCode).
id: `CAM-${camera.code || camera.id}`,
@@ -336,6 +335,25 @@ export function createControls({ state: layerState, services, parts, source }) {
return nextId;
},
/**
* Selects the camera nearest a WGS84 point and optionally flies to it.
* @param {number} lat Latitude in degrees.
* @param {number} lon Longitude in degrees.
* @param {Object} [options={}]
* @param {boolean} [options.focus=true] Whether to fly after selection.
* @param {number} [options.durationSec] Fly-to duration in seconds.
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
*/
focusNearestToPoint(lat, lon, options = {}) {
const nearest = parts.navigation.nearestCameraIdToPoint(lat, lon);
if (!nearest) return null;
parts.selection.setActiveCamera(nearest);
if (options.focus !== false) {
parts.navigation.focusCamera(nearest, options.durationSec || 1.8);
}
return nearest;
},
/**
* Selects and flies to the camera nearest the current viewer position.
* @param {Object} [options={}]
+195
View File
@@ -0,0 +1,195 @@
/**
* @module layers/cctv/drawSets
* @description The CCTV layer's draw sets: the frustum wireframes
* (`coverage`, lines), the viewshed volumes (`viewshed`, meshes) and the
* active camera's monitor plane (`plane`, a quad), made through the draw
* port of the viewer the layer is on. They are made when first drawn into
* and made again on another viewer. Item ids keep the layer's
* `cctv-<cameraId>-<role>` scheme the shared pick registry reads, and each
* line's and plane's `meta.cameraId` names its camera (volumes are never
* picked and carry none).
*
* Coverage lines and the plane are written from handles the layer keeps
* (a record's `coverageEntities`, a projection runtime's `plane`): plain
* objects the layer changes and then writes, only what changed reaching
* the set.
*
* Meshes and quads are capabilities: on a renderer without them there are
* no viewshed volumes or monitor plane, and the lines still draw.
*/
import { drawOf } from '../../render/rendererOf.js';
/** Layer instances, for set ids unique to each. */
let instances = 0;
/** A line handle's item, or null for a handle that names no line yet. */
function lineItemOf(handle) {
if (!handle?.id || !Array.isArray(handle.positions)) return null;
const color = handle.color;
return {
id: handle.id,
positions: handle.positions,
widthPx: handle.widthPx,
// As a polyline entity runs: along the ellipsoid between its positions.
mode: 'geodesic',
style: handle.dashed
? { kind: 'dash', color, length: 16, pattern16: 255 }
: { kind: 'solid', color },
depthFail: handle.depthFailColor
? { kind: 'solid', color: handle.depthFailColor }
: null,
meta: { cameraId: handle.cameraId },
show: handle.show !== false,
};
}
/** What a line item draws, as a key: an unchanged key is not written. */
const lineKey = (item) =>
[
item.positions.map((p) => `${p.x},${p.y},${p.z}`).join(';'),
item.widthPx,
item.style.kind,
item.style.color.join(','),
item.depthFail ? item.depthFail.color.join(',') : '',
item.show,
].join('|');
/** The plane handle's quad item. */
function quadItemOf(plane) {
return {
id: plane.id,
center: plane.center,
orientation: plane.orientation,
size: plane.size,
source: plane.source,
alpha: plane.alpha,
outline: plane.outline,
meta: { cameraId: plane.cameraId },
show: plane.show === true,
};
}
export function createDrawSets({ state: layerState }) {
/** The live sets and the viewer they draw on, or null. */
let current = null;
/** Viewshed volumes written, ever (the QA harness checks for churn). */
let volumeWrites = 0;
/** The layer's sets on its viewer now, made if need be; null with none. */
function sets() {
const viewer = layerState._viewer;
if (!viewer) return null;
if (current?.viewer === viewer) return current;
dispose();
const draw = drawOf(viewer);
const n = ++instances;
current = {
viewer,
coverage: draw.lines({ id: `cctv:${n}:coverage` }),
viewshed:
draw.meshes?.({ id: `cctv:${n}:viewshed`, pickable: false }) ?? null,
plane: draw.quads?.({ id: `cctv:${n}:plane` }) ?? null,
// What each line item was last written as, by id.
lineKeys: new Map(),
};
return current;
}
/** The live sets, without making them. */
const live = () =>
current && current.viewer === layerState._viewer ? current : null;
/** Let the sets go (the layer leaves its viewer, or moves to another). */
function dispose() {
if (!current) return;
for (const set of [current.coverage, current.viewshed, current.plane])
try {
set?.dispose();
} catch {
// Its viewer went first.
}
current = null;
}
/** The ids of the sets that draw the layer's lines and plane. */
function pickableSetIds() {
const s = live();
if (!s) return [];
return s.plane ? [s.coverage.id, s.plane.id] : [s.coverage.id];
}
/** Which of the layer's sets a set id is: 'coverage', 'plane' or null. */
function roleOfSet(setId) {
const s = live();
if (!s) return null;
if (setId === s.coverage.id) return 'coverage';
if (setId === s.plane?.id) return 'plane';
return null;
}
/** Write line handles that changed since they were last written. */
function writeLines(handles) {
if (!handles?.length) return;
const s = handles.some((h) => h?.id) ? sets() : null;
if (!s) return;
const changed = [];
for (const handle of handles) {
const item = lineItemOf(handle);
if (!item) continue;
const key = lineKey(item);
if (s.lineKeys.get(item.id) === key) continue;
s.lineKeys.set(item.id, key);
changed.push(item);
}
if (changed.length) s.coverage.upsert(changed);
}
/** Take every line out. */
function clearLines() {
const s = live();
if (!s) return;
s.coverage.clear();
s.lineKeys.clear();
}
/** Write the plane handle as it is now. */
function writePlane(plane) {
if (!plane?.id) return;
sets()?.plane?.upsert([quadItemOf(plane)]);
}
/** Take a plane out. */
function removePlane(plane) {
if (plane?.id) live()?.plane?.remove([plane.id]);
}
/** Write a viewshed volume. */
function writeVolume(item) {
const s = sets();
if (!s?.viewshed) return;
s.viewshed.upsert([item]);
volumeWrites += 1;
}
/** Take a viewshed volume out. */
function removeVolume(id) {
if (id) live()?.viewshed?.remove([id]);
}
/** How many viewshed volumes were written, for the QA harness. */
const volumeWritesForTest = () => volumeWrites;
return {
sets,
dispose,
pickableSetIds,
roleOfSet,
writeLines,
clearLines,
writePlane,
removePlane,
writeVolume,
removeVolume,
volumeWritesForTest,
};
}
+135
View File
@@ -0,0 +1,135 @@
// The CCTV layer's draw sets: lines written only as they change, dashed for
// an estimated bearing, the depth-fail colour passed as it is; the sets made
// again on another viewer and let go on dispose.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createDrawSets } from './drawSets.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const line = (id, fields = {}) => ({
id,
cameraId: 'cam',
role: 'edge',
positions: [
{ x: 1, y: 2, z: 3 },
{ x: 4, y: 5, z: 6 },
],
widthPx: 1.2,
color: [0.1, 0.2, 0.3, 0.4],
dashed: false,
depthFailColor: null,
show: true,
...fields,
});
test('lines are written as they change, and drawn as their handles say', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
const a = line('cctv-cam-ray-tl');
const b = line('cctv-cam-cap', { role: 'cap' });
drawSets.writeLines([a, b]);
const coverage = draw.find('cctv:');
assert.equal(coverage.kind, 'lines');
assert.equal(coverage.writes, 1);
assert.deepEqual(coverage.items.get(a.id), {
id: a.id,
positions: a.positions,
widthPx: 1.2,
mode: 'geodesic',
style: { kind: 'solid', color: a.color },
depthFail: null,
meta: { cameraId: 'cam' },
show: true,
});
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 1, 'unchanged handles write nothing');
b.dashed = true;
b.depthFailColor = [1, 1, 1, 0.2];
drawSets.writeLines([a, b]);
assert.equal(coverage.writes, 2);
const cap = coverage.items.get(b.id);
assert.deepEqual(cap.style, {
kind: 'dash',
color: b.color,
length: 16,
pattern16: 255,
});
assert.deepEqual(cap.depthFail, { kind: 'solid', color: [1, 1, 1, 0.2] });
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
assert.equal(drawSets.roleOfSet('other:1:lines'), null);
drawSets.clearLines();
assert.equal(coverage.items.size, 0);
drawSets.writeLines([a]);
assert.ok(coverage.items.has(a.id), 'a cleared line is written again');
} finally {
unbind();
}
});
test('another viewer gets sets of its own; dispose lets them go', () => {
const first = {};
const second = {};
const one = bindFakeDraw(first);
const two = bindFakeDraw(second);
const state = { _viewer: first };
const drawSets = createDrawSets({ state });
try {
const a = line('cctv-cam-ray-tl');
drawSets.writeLines([a]);
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
const old = one.draw.find('cctv:');
assert.equal(drawSets.volumeWritesForTest(), 1);
state._viewer = second;
assert.deepEqual(drawSets.pickableSetIds(), [], 'none made yet');
drawSets.writeLines([a]);
assert.ok(old.disposed, 'the old viewer’s sets are let go');
const now = two.draw.find('cctv:');
assert.ok(now.items.has(a.id), 'the line is written anew');
const [coverage, plane] = drawSets.pickableSetIds();
assert.equal(two.draw.set(coverage).kind, 'lines');
assert.equal(two.draw.set(plane).kind, 'quads');
assert.equal(drawSets.roleOfSet(plane), 'plane');
drawSets.dispose();
assert.ok(
[...two.draw.sets.values()].every((set) => set.disposed),
'every set is let go',
);
assert.equal(drawSets.roleOfSet(coverage), null);
} finally {
one.unbind();
two.unbind();
}
});
test('a renderer without meshes or quads still draws the lines', () => {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
delete draw.meshes;
delete draw.quads;
const drawSets = createDrawSets({ state: { _viewer: viewer } });
try {
drawSets.writeLines([line('cctv-cam-ray-tl')]);
const coverage = draw.find('cctv:');
assert.equal(coverage.items.size, 1);
// No viewshed volumes and no monitor plane: their writes do nothing.
drawSets.writeVolume({ id: 'cctv-cam-viewshed' });
drawSets.removeVolume('cctv-cam-viewshed');
const plane = { id: 'cctv-cam-plane', cameraId: 'cam', show: true };
drawSets.writePlane(plane);
drawSets.removePlane(plane);
assert.equal(drawSets.volumeWritesForTest(), 0);
assert.deepEqual(drawSets.pickableSetIds(), [coverage.spec.id]);
assert.equal(drawSets.roleOfSet(coverage.spec.id), 'coverage');
drawSets.dispose();
} finally {
unbind();
}
});
+19 -13
View File
@@ -5,9 +5,6 @@ import {
PROJECTION_CANVAS_HEIGHT,
PROJECTION_MATTE_COLOR,
PROJECTION_TEXTURE_SWAP_MS,
ACTIVE_FRAME_REFRESH_MS,
FRAME_ENDPOINT,
MEDIA_ENDPOINT,
PROJECTION_ACTIVE_REFRESH_MS,
PROJECTION_IDLE_REFRESH_MS,
PLACEHOLDER_REPAINT_MS,
@@ -109,9 +106,9 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Blits the latest projection canvas into the next of two alternating
* offscreen buffer canvases and returns it (H5).
*
* Two buffers are required because Cesium's Material image path re-uploads a
* canvas texture only when the uniform receives a NEW object reference —
* redrawing the same canvas in place is invisible to the GPU. Alternating
* Two buffers are required because the plane re-uploads a canvas texture
* only when it is given a NEW canvas — redrawing the same canvas in place
* is invisible to the GPU. Alternating
* references forces a texture recreate, which at <=1Hz and 1080p is cheap.
*
* @param {Object} runtime - Projection runtime with `.canvas`.
@@ -142,8 +139,8 @@ export function createFrames({ state: layerState, services, parts, source }) {
* Pushes fresh pixels into the monitor plane material. Called every
* projection tick.
*
* Video feeds are skipped entirely — their HTMLVideoElement uniform is
* updated per-frame by Cesium natively (H5). Image/webcam-frame feeds swap
* Video feeds are skipped entirely — the renderer reads their
* HTMLVideoElement every frame (H5). Image/webcam-frame feeds swap
* the double-buffer canvas reference, throttled to PROJECTION_TEXTURE_SWAP_MS.
*
* @param {Object} record - Camera record with an initialized projection runtime.
@@ -159,7 +156,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
)
return;
const planeShowing = !!(runtime.planeEntity?.show && runtime.planeMaterial);
const planeShowing = !!runtime.plane?.show;
if (!planeShowing) return;
// Only swap when the canvas content actually changed since the last swap.
@@ -173,7 +170,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
if (!buffer) return;
runtime.lastTextureSwapAt = now;
runtime.lastSwappedCanvasStamp = runtime.canvasStamp;
runtime.planeMaterial.image = buffer;
parts.projection.setPlaneSource(runtime, { canvas: buffer });
}
/**
@@ -258,11 +255,20 @@ export function createFrames({ state: layerState, services, parts, source }) {
// clears this latch so the next normal tick can refresh.
if (runtime.imageLoading) return;
const now = Date.now();
const refreshMs =
const defaultRefreshMs =
record.camera.id === layerState._activeCameraId
? PROJECTION_ACTIVE_REFRESH_MS
: PROJECTION_IDLE_REFRESH_MS;
if (!force && now - runtime.lastImageRefreshAt < refreshMs) return;
const sourceRefreshMs = parts.model.safeNumber(
record.camera.frameRefreshMs,
0,
);
const refreshMs = Math.max(defaultRefreshMs, sourceRefreshMs);
const sinceLastRefresh = now - runtime.lastImageRefreshAt;
// Forced activation may skip the normal active interval, but it cannot
// bypass a provider's explicit minimum between image requests.
if (sourceRefreshMs > 0 && sinceLastRefresh < sourceRefreshMs) return;
if (!force && sinceLastRefresh < refreshMs) return;
runtime.lastImageRefreshAt = now;
const frameUrl = frameUrlFor(record.camera, refreshMs);
@@ -349,7 +355,7 @@ export function createFrames({ state: layerState, services, parts, source }) {
// camera republished once in 5 minutes, an Austin one not at all.
// Redrawing regardless bumped canvasStamp, which forced a buffer swap
// and a fresh 1920x1080 texture upload; the plane renders its white
// base color (planeMaterial color = WHITE, alpha .95) for the frame or
// base color (white, alpha .95) for the frame or
// two Cesium needs to rebind, which IS the periodic white flash from the
// owner field tests (2026-07-04 and 2026-07-30).
const fit = fitToProjection(
+127 -223
View File
@@ -1,13 +1,12 @@
import * as Cesium from 'cesium';
import { createFrustumVolumePrimitive } from '../../data/cctvViewshed.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { eastNorthUp, frameVector } from '../../geo/frames.js';
import { distance, vec } from '../../geo/vector.js';
import {
PROJECTION_VERT_ASPECT,
FRUSTUM_GROUND_CLEARANCE_M,
PROBE_MIN_RANGE_M,
PROBE_CLEARANCE_M,
COVERAGE_NEIGHBOR_RADIUS_KM,
COVERAGE_NEIGHBOR_LIMIT,
IDLE_COVERAGE_COLOR,
PLANE_FOOTPRINT_LIFT_CAP_M,
} from './policy.js';
@@ -262,30 +261,18 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
/**
* Converts a computeFrustumGeometry result into the Cartesian3 positions the
* entities consume. Fresh objects per call (geometry updates are rare —
* slider/save/activation — and entities must never share scratch objects).
* @param {Object} geometry - Result of computeFrustumGeometry.
* @returns {{ mount: Cesium.Cartesian3, capCenter: Cesium.Cartesian3,
* tl: Cesium.Cartesian3, tr: Cesium.Cartesian3, br: Cesium.Cartesian3,
* bl: Cesium.Cartesian3, label: Cesium.Cartesian3 }}
* Distance along a pitched-down view axis to flat ground at the mount's own
* ground height, or null for an axis at or above the horizon.
* @param {number} mountHeightM Mount height above its ground.
* @param {number} pitchDeg Axis pitch (negative looks down).
* @returns {number|null}
*/
function frustumCartesians(geometry) {
const at = (p) => Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.alt);
return {
mount: at(geometry.mount),
capCenter: at(geometry.capCenter),
tl: at(geometry.corners.tl),
tr: at(geometry.corners.tr),
br: at(geometry.corners.br),
bl: at(geometry.corners.bl),
label: Cesium.Cartesian3.fromDegrees(
geometry.topCenter.lon,
geometry.topCenter.lat,
geometry.topCenter.alt + 1.2,
),
};
function flatGroundAxisDistance(mountHeightM, pitchDeg) {
const height = Number(mountHeightM);
const pitch = Number(pitchDeg);
if (!Number.isFinite(height) || height <= 0 || !(pitch < 0)) return null;
return height / Math.sin((Math.min(89, -pitch) * Math.PI) / 180);
}
/**
@@ -293,40 +280,35 @@ export function createGeometry({ state: layerState, services, parts, source }) {
* Used by the plane orientation and the activation obstruction probe — both
* need the UNCLAMPED axis, so it comes from the pose, not from clamped points.
* @param {Object} camera - Camera pose (headingDeg, pitchDeg).
* @param {Cesium.Cartesian3} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: Cesium.Cartesian3, up: Cesium.Cartesian3 }} View axis + the
* @param {{x: number, y: number, z: number}} atPos - ECEF position defining the local ENU frame.
* @returns {{ dir: {x: number, y: number, z: number}, up: {x: number, y: number, z: number} }} View axis + the
* frame's in-plane "up" (both unit, mutually perpendicular).
*/
function frustumFrameEcef(camera, atPos) {
const h = parts.model.toRad(camera.headingDeg);
const p = parts.model.toRad(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const enu = eastNorthUp(atPos);
// ENU components: view axis + the perpendicular "up" of the pitched cap.
const dirEnu = new Cesium.Cartesian3(
const dirEnu = vec(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
const upEnu = vec(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
return {
dir: Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
),
up: Cesium.Matrix3.multiplyByVector(rot, upEnu, new Cesium.Cartesian3()),
dir: frameVector(enu, dirEnu),
up: frameVector(enu, upEnu),
};
}
/**
* Recomputes the pure frustum geometry from the camera pose + the given ground
* altitude and writes it into the scene: billboard position, the 5 wireframe
* altitude and writes it into the scene: icon position, the 5 wireframe
* polylines (4 corner rays + closed far-plane rectangle), and the monitor
* plane placement. This is the ONLY place v2 geometry is written — called on
* slider input / save / activation / the one-shot ground snap, never per frame.
@@ -341,38 +323,16 @@ export function createGeometry({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
footprintGroundFor(record),
);
const positions = frustumCartesians(geometry);
const positions = parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
record.camera.absoluteHeightM = geometry.mount.alt;
if (record.billboard) {
record.billboard.position = positions.mount;
}
parts.rendering.moveCameraIcon(record);
record.groundAltM = groundAltM;
if (record.coverageEntities?.length >= 5) {
record.coverageEntities[0].polyline.positions = [
positions.mount,
positions.tl,
];
record.coverageEntities[1].polyline.positions = [
positions.mount,
positions.tr,
];
record.coverageEntities[2].polyline.positions = [
positions.mount,
positions.br,
];
record.coverageEntities[3].polyline.positions = [
positions.mount,
positions.bl,
];
record.coverageEntities[4].polyline.positions = [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
];
parts.rendering.placeCoverageLines(record.coverageEntities, positions);
parts.drawSets.writeLines(record.coverageEntities);
}
// A live viewshed volume tracks its wireframe: rebuild from the SAME fresh
// positions (weld invariant). Only records currently showing a volume pay
@@ -380,8 +340,8 @@ export function createGeometry({ state: layerState, services, parts, source }) {
// Tint derives from the live active id, not the cached viewshedActiveTint —
// during an activation switch this runs BEFORE refreshCoverageStyles, and
// the cache is stale for exactly that window.
if (record.viewshedPrimitive) {
rebuildViewshedVolume(
if (record.viewshedVolume) {
parts.rendering.rebuildViewshedVolume(
record,
record.camera.id === layerState._activeCameraId,
);
@@ -449,24 +409,17 @@ export function createGeometry({ state: layerState, services, parts, source }) {
}
// Photoreal regime. Sampling is delegated to the shared coarse-cell
// sampler. It remains event-driven, one-shot per cell, and keeps its
// sampler. It remains event-driven, a few probes per cell, and keeps its
// existing acceptance window; CCTV adds no rooftop rejection policy.
if (sampleGround && parts.model.projectionTilesReady()) {
record.groundMeshSampleRequestCount =
(record.groundMeshSampleRequestCount || 0) + 1;
const viewerCarto = layerState._viewer?.camera?.positionCartographic;
const excludeObjects = [...(record.coverageEntities || [])];
if (record.billboard) excludeObjects.push(record.billboard);
if (record.projection?.planeEntity)
excludeObjects.push(record.projection.planeEntity);
sampleMeshFloorCells(layerState._viewer?.scene, [point], {
excludeObjects: excludeObjects.filter(Boolean),
viewerLat: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.latitude)
: undefined,
viewerLon: viewerCarto
? Cesium.Math.toDegrees(viewerCarto.longitude)
: undefined,
const eye = parts.model.eyePose();
// The layer's own lines and plane are not ground; named all the same.
sampleMeshFloorCells(layerState._viewer, [point], {
sets: parts.drawSets.pickableSetIds(),
viewerLat: eye ? eye.lat : undefined,
viewerLon: eye ? eye.lon : undefined,
});
}
@@ -526,52 +479,6 @@ export function createGeometry({ state: layerState, services, parts, source }) {
return new Set(chosen);
}
/**
* Removes (and destroys) a record's viewshed volume primitive, if any.
* @param {Object} record - Camera record.
*/
function destroyViewshedVolume(record) {
if (!record) return;
if (record.viewshedPrimitive && layerState._viewer) {
layerState._viewer.scene.primitives.remove(record.viewshedPrimitive);
}
record.viewshedPrimitive = null;
}
/**
* (Re)builds a record's translucent viewshed volume from its CURRENT
* frustumPositions — the same 5 Cartesians the wireframe draws, so the volume
* is welded to the cone by construction. Called only where the wireframe
* already rewrites (style refresh on mode/visible-set/active changes,
* applyFrustumGeometry on pose edits) — no new update cadence, zero scene
* queries (viewshed design §3b).
* @param {Object} record - Camera record.
* @param {boolean} isActive - Active camera gets the brighter fill.
*/
function rebuildViewshedVolume(record, isActive) {
destroyViewshedVolume(record);
if (
!layerState._viewer ||
!record?.frustumPositions ||
!record.viewshedColors
)
return;
const color = isActive
? record.viewshedColors.fillActive
: record.viewshedColors.fill;
const primitive = createFrustumVolumePrimitive(
record.frustumPositions,
color,
);
// QA tag: the harness counts viewshed volumes by this marker.
primitive._gevViewshed = record.camera.id;
record.viewshedPrimitive =
layerState._viewer.scene.primitives.add(primitive);
record.viewshedActiveTint = !!isActive;
}
/**
* Counts how many other cameras have overlapping coverage with the target.
* Overlap is approximated by comparing inter-camera distance against the
@@ -582,6 +489,13 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function coverageNeighborCount(targetRecord) {
if (!targetRecord) return 0;
// The summary asks on every notification; scan the catalog only when the
// camera, its pose or the catalog changed.
const { id, lat, lon, rangeM } = targetRecord.camera;
const key = `${id}|${lat}|${lon}|${rangeM}|${layerState._records.length}`;
const cached = layerState._neighborCountCache;
if (cached?.key === key && cached.records === layerState._records)
return cached.count;
let count = 0;
for (const record of layerState._records) {
if (record === targetRecord) continue;
@@ -595,52 +509,104 @@ export function createGeometry({ state: layerState, services, parts, source }) {
((targetRecord.camera.rangeM + record.camera.rangeM) / 1000) * 0.92;
if (dKm <= overlapKm) count++;
}
layerState._neighborCountCache = {
key,
records: layerState._records,
count,
};
return count;
}
/**
* §9.1 activation obstruction probe (LOCKED owner decision): on camera
* ACTIVATION only, fire ONE scene.pickFromRay along the frustum axis
* ACTIVATION only, cast ONE ray against the scene along the frustum axis
* (mount → cap-center direction). If it hits the tiles closer than the pose
* range, clamp the plane's effective range just short of the first hit so the
* "big and dramatic" true end cap never clips into downtown buildings.
*
* This is the ONLY raycast in the whole CCTV subsystem — once per activation,
* never per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips the
* probe entirely. Probe failure/miss keeps the unclamped range.
* On a globe map it also casts along the same axis against the globe's
* terrain (flat ground at the mount's ground when terrain is missed or met
* beyond the range) and clamps at the nearer end. These are the ONLY
* raycasts in the whole CCTV subsystem — once per activation, never
* per-frame (the zero-raycast invariant applies to steady state). The
* per-camera range slider overrides the clamp: a user-set rangeScale skips
* the probe entirely. A miss on the photoreal stack or a probe failure
* keeps the unclamped range.
*
* The casts are made now, against the scene as it is, and answer a
* microtask later: the clamp then lands by rewriting the geometry from the
* ground it was last written at, before the next frame draws. A newer
* activation, or the camera's deactivation, drops an answer still to come.
* @param {Object} record - Camera record being activated.
* @returns {Promise<void>} Settled once the clamp (if any) has landed.
*/
function runActivationObstructionProbe(record) {
record.probeClampRangeM = null;
const scene = layerState._viewer?.scene;
if (!scene || typeof scene.pickFromRay !== 'function') return;
const token = (record.probeToken = (record.probeToken || 0) + 1);
const viewer = layerState._viewer;
if (!parts.rendering.canPickFromRay()) return Promise.resolve();
const camera = record.camera;
const rangeScale = parts.calibration.normalizeCalibration(
camera.calibration,
).rangeScale;
if (Math.abs(rangeScale - 1) > 0.0001) return; // slider overrides the clamp
// The slider overrides the clamp.
if (Math.abs(rangeScale - 1) > 0.0001) return Promise.resolve();
try {
const mountAlt = parts.ground.groundAltFor(record) + camera.mountHeightM;
const mountPos = Cesium.Cartesian3.fromDegrees(
camera.lon,
camera.lat,
mountAlt,
);
const mountPos = fromDegrees(camera.lon, camera.lat, mountAlt);
const { dir } = frustumFrameEcef(camera, mountPos);
// Exclude everything the layer itself draws so the probe can only hit the
// world (3D tiles), not our own billboards/polylines/planes.
const exclude = [layerState._billboards, ...layerState._coverageEntities];
for (const runtime of layerState._projectionEntities) {
if (runtime?.planeEntity) exclude.push(runtime.planeEntity);
}
const hit = scene.pickFromRay(new Cesium.Ray(mountPos, dir), exclude);
if (!hit?.position) return;
const dist = Cesium.Cartesian3.distance(mountPos, hit.position);
record.probeClampRangeM = activationProbeClampRange(camera.rangeM, dist);
// The casts see through everything the layer draws. The surface cast
// meets what is drawn on the globe (the photoreal tiles); on a globe
// map the axis also ends on the globe's terrain, the nearer of that and
// any surface hit. A hit at or beyond the range counts as none. Terrain
// still loading at a coarse level can be missed or met beyond the
// range; then flat ground at the mount's own ground stands in for it.
const inRange = (d) => Number.isFinite(d) && d > 0 && d < camera.rangeM;
return Promise.all([
parts.rendering.obstructionHit(mountPos, dir),
parts.rendering.terrainHit?.(mountPos, dir) ?? null,
])
.then(([hit, terrain]) => {
if (record.probeToken !== token) return;
if (record.camera.id !== layerState._activeCameraId) return;
// A layer torn down or re-initialised since (another viewer, or
// a new record for the same camera) is not the one it asked for.
if (layerState._viewer !== viewer) return;
if (layerState._recordById?.get(record.camera.id) !== record) return;
const hitDist = hit ? distance(mountPos, hit) : NaN;
const distances = inRange(hitDist) ? [hitDist] : [];
if (terrain) {
const terrainDist = terrain.hit
? distance(mountPos, terrain.hit)
: NaN;
const ground = inRange(terrainDist)
? terrainDist
: flatGroundAxisDistance(camera.mountHeightM, camera.pitchDeg);
if (Number.isFinite(ground) && ground > 0) distances.push(ground);
}
if (!distances.length) return;
const clamp = activationProbeClampRange(
camera.rangeM,
Math.min(...distances),
);
if (!Number.isFinite(clamp)) return;
record.probeClampRangeM = clamp;
if (Number.isFinite(record.groundAltM))
applyFrustumGeometry(record, record.groundAltM);
// The activation asked for the ground under the unclamped plane's
// footprint; the clamped plane's is asked for now, and the layer
// restyles and tells its listeners, as that answer will.
void parts.ground.resolveFootprintGround(record);
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
})
.catch(() => {
// probe failure → keep the unclamped range
});
} catch {
// probe failure → keep the unclamped range
return Promise.resolve();
}
}
@@ -653,77 +619,17 @@ export function createGeometry({ state: layerState, services, parts, source }) {
*/
function clearProbeClampOnDeactivation(record, rewriteGeometry) {
if (record) record.probeToken = (record.probeToken || 0) + 1;
if (!record || !Number.isFinite(record.probeClampRangeM)) return false;
record.probeClampRangeM = null;
rewriteGeometry?.(record);
return true;
}
/**
* Creates the five Cesium polyline entities that visualize a camera's pitched
* frustum: 4 corner rays (mount → far-plane corner) + the closed far-plane
* rectangle. Entity ids stay in the `cctv-<id>-<role>` scheme (pick-owner
* regex depends on it): roles ray-tl / ray-tr / ray-br / ray-bl / cap.
* @param {Object} record - Camera record.
* @returns {Cesium.Entity[]} Array of five coverage entities.
*/
function buildCoverageEntities(record) {
const { camera } = record;
// Prefer the record's already-refined geometry. Lazy creation commonly
// happens after the staggered ground pass; recomputing from the catalog
// prior here would regress the camera to its pre-sampled datum.
let geometry = record.frustumGeometry;
let positions = record.frustumPositions;
if (!geometry || !positions) {
geometry = computeFrustumGeometry(
camera,
parts.ground.groundPriorAltFor(record),
record.probeClampRangeM,
);
positions = frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
record.position = positions.mount;
}
const addPolyline = (role, linePositions) =>
layerState._viewer.entities.add({
id: `cctv-${camera.id}-${role}`,
properties: { cctvCameraId: camera.id },
polyline: {
positions: linePositions,
width: 1.2,
material: IDLE_COVERAGE_COLOR,
},
});
const entities = [
addPolyline('ray-tl', [positions.mount, positions.tl]),
addPolyline('ray-tr', [positions.mount, positions.tr]),
addPolyline('ray-br', [positions.mount, positions.br]),
addPolyline('ray-bl', [positions.mount, positions.bl]),
addPolyline('cap', [
positions.tl,
positions.tr,
positions.br,
positions.bl,
positions.tl,
]),
];
entities[0]._coverageRole = 'edge';
entities[1]._coverageRole = 'edge';
entities[2]._coverageRole = 'edge';
entities[3]._coverageRole = 'edge';
entities[4]._coverageRole = 'cap';
return entities;
}
/**
* Materializes coverage entities for eligible records exactly once.
* The helper is dependency-injected so unit tests can prove the enable policy
* without constructing Cesium entities.
* without constructing entities.
*
* @param {Object[]} records CCTV runtime records.
* @param {(record: Object) => boolean} [isEligible] Eligibility predicate.
@@ -781,7 +687,10 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function ensureActiveCoverageEntities(record) {
return registerCoverageEntities(
materializeCctvActiveCoverageEntities(record, buildCoverageEntities),
materializeCctvActiveCoverageEntities(
record,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -790,7 +699,7 @@ export function createGeometry({ state: layerState, services, parts, source }) {
materializeCctvVisibleCoverageEntities(
records,
visibleIds,
buildCoverageEntities,
parts.rendering.buildCoverageEntities,
),
);
}
@@ -801,13 +710,11 @@ export function createGeometry({ state: layerState, services, parts, source }) {
function destroyCoverageEntities() {
if (!layerState._viewer) return;
for (const entity of layerState._coverageEntities) {
layerState._viewer.entities.remove(entity);
}
parts.rendering.removeCoverageEntities();
layerState._coverageEntities = [];
for (const record of layerState._records) {
destroyViewshedVolume(record);
parts.rendering.destroyViewshedVolume(record);
}
for (const runtime of layerState._projectionEntities) {
@@ -820,17 +727,14 @@ export function createGeometry({ state: layerState, services, parts, source }) {
hasShippedFootprint,
footprintPose,
activationProbeClampRange,
frustumCartesians,
flatGroundAxisDistance,
frustumFrameEcef,
applyFrustumGeometry,
updateRecordGeometry,
buildCoverageVisibleSet,
destroyViewshedVolume,
rebuildViewshedVolume,
coverageNeighborCount,
runActivationObstructionProbe,
clearProbeClampOnDeactivation,
buildCoverageEntities,
materializeCctvCoverageEntities,
materializeCctvActiveCoverageEntities,
materializeCctvVisibleCoverageEntities,
+182
View File
@@ -0,0 +1,182 @@
// src/layers/cctv/geometry.test.mjs
// The frustum's view axis and the monitor plane's orientation are computed
// with the shared geo helpers; they must give what the renderer's own transforms
// gave, bit for bit, so frustums, probes and planes land where they did.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createGeometry } from './geometry.js';
import { createModel } from './model.js';
function parts() {
const p = {};
const context = {
state: {},
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
p.model = createModel(context);
p.geometry = createGeometry(context);
return p;
}
/** The renderer's own frame, as the layer computed it before. */
function cesiumFrame(camera, atPos) {
const h = Cesium.Math.toRadians(camera.headingDeg);
const p = Cesium.Math.toRadians(camera.pitchDeg);
const enu = Cesium.Transforms.eastNorthUpToFixedFrame(atPos);
const rot = Cesium.Matrix4.getMatrix3(enu, new Cesium.Matrix3());
const dirEnu = new Cesium.Cartesian3(
Math.sin(h) * Math.cos(p),
Math.cos(h) * Math.cos(p),
Math.sin(p),
);
const upEnu = new Cesium.Cartesian3(
-Math.sin(p) * Math.sin(h),
-Math.sin(p) * Math.cos(h),
Math.cos(p),
);
const dir = Cesium.Matrix3.multiplyByVector(
rot,
dirEnu,
new Cesium.Cartesian3(),
);
const up = Cesium.Matrix3.multiplyByVector(
rot,
upEnu,
new Cesium.Cartesian3(),
);
const right = Cesium.Cartesian3.cross(dir, up, new Cesium.Cartesian3());
const normal = Cesium.Cartesian3.negate(dir, new Cesium.Cartesian3());
const orientation = Cesium.Quaternion.fromRotationMatrix(
new Cesium.Matrix3(
right.x,
up.x,
normal.x,
right.y,
up.y,
normal.y,
right.z,
up.z,
normal.z,
),
);
return { dir, up, orientation };
}
const xyz = (v) => [v.x, v.y, v.z];
test('the frustum axis and plane orientation match the renderer transforms exactly', () => {
const { geometry, model } = parts();
let seed = 7;
const random = () => {
seed = (seed * 16807) % 2147483647;
return seed / 2147483647;
};
for (let i = 0; i < 500; i++) {
const camera = {
headingDeg: random() * 360,
pitchDeg: -89 + random() * 120,
};
const atPos = Cesium.Cartesian3.fromDegrees(
-180 + random() * 360,
-89 + random() * 178,
random() * 3000,
);
const expected = cesiumFrame(camera, atPos);
const frame = geometry.frustumFrameEcef(camera, atPos);
assert.deepEqual(xyz(frame.dir), xyz(expected.dir));
assert.deepEqual(xyz(frame.up), xyz(expected.up));
const q = model.planeOrientationFor(camera, atPos);
const e = expected.orientation;
assert.deepEqual([q.x, q.y, q.z, q.w], [e.x, e.y, e.z, e.w]);
}
});
test('the activation probe clamps the range once its ray answers, unless the camera moved on', async () => {
const { createRendering } = await import('./rendering.js');
const p = {};
const state = { _activeCameraId: 'cam', _viewer: {} };
const context = {
state,
services: { ground: {}, mesh: {}, focus: {} },
parts: p,
};
const written = [];
const footprints = [];
let restyles = 0;
let notices = 0;
let hitAtM = 80;
p.model = createModel(context);
p.geometry = createGeometry(context);
p.rendering = {
...createRendering(context),
canPickFromRay: () => true,
refreshCoverageStyles: () => (restyles += 1),
// The first surface `hitAtM` metres along the axis.
obstructionHit: async (origin, direction) => ({
x: origin.x + direction.x * hitAtM,
y: origin.y + direction.y * hitAtM,
z: origin.z + direction.z * hitAtM,
}),
};
p.calibration = { normalizeCalibration: () => ({ rangeScale: 1 }) };
p.ground = {
groundAltFor: () => 100,
resolveFootprintGround: async (r) =>
footprints.push(p.geometry.footprintPose(r)),
};
p.presentation = { notifyListeners: () => (notices += 1) };
p.drawSets = { writeLines: (lines) => written.push(lines) };
p.projection = { updatePlanePlacement() {} };
const record = {
camera: {
id: 'cam',
lon: -97.74,
lat: 30.27,
headingDeg: 90,
pitchDeg: -10,
fovDeg: 60,
rangeM: 200,
mountHeightM: 8,
},
coverageEntities: [],
};
state._recordById = new Map([['cam', record]]);
p.geometry.applyFrustumGeometry(record, 100);
assert.equal(record.frustumGeometry.rangeM, 200, 'unclamped at first');
const landed = p.geometry.runActivationObstructionProbe(record);
assert.equal(record.probeClampRangeM, null, 'the answer is still to come');
await landed;
const clamp = p.geometry.activationProbeClampRange(200, 80);
assert.ok(Math.abs(record.probeClampRangeM - clamp) < 1e-6);
assert.ok(
Math.abs(record.frustumGeometry.rangeM - clamp) < 1e-6,
'the geometry is rewritten at the clamp, from the ground it had',
);
assert.equal(record.frustumGeometry.mount.alt, 108);
assert.deepEqual(
footprints,
[p.geometry.footprintPose(record)],
"the clamped plane's footprint ground is asked for",
);
assert.ok(
Math.abs(footprints[0].rangeM - clamp) < 1e-6,
'at the clamped pose',
);
assert.deepEqual([restyles, notices], [1, 1]);
// A probe whose camera is deactivated before it answers lands nothing.
hitAtM = 50;
const stale = p.geometry.runActivationObstructionProbe(record);
p.geometry.clearProbeClampOnDeactivation(record, () => {});
await stale;
assert.equal(record.probeClampRangeM, null);
// Nor does one whose record a re-init replaced for the same camera.
const replaced = p.geometry.runActivationObstructionProbe(record);
state._recordById = new Map([['cam', { ...record }]]);
await replaced;
assert.equal(record.probeClampRangeM, null);
});
+159 -29
View File
@@ -1,4 +1,4 @@
import * as Cesium from 'cesium';
import { followedOf } from '../../data/followed.js';
import {
GEO_PROGRESS_NOTIFY_INTERVAL_MS,
GEO_PROGRESS_NOTIFY_BATCH_LIMIT,
@@ -6,6 +6,8 @@ import {
GEO_TRACKING_BATCH_DELAY_MS,
GEO_LOAD_BATCH_SIZE,
GEO_LOAD_BATCH_DELAY_MS,
VIEW_GEOMETRY_ATTEMPTS,
VIEW_GEOMETRY_RETRY_MS,
} from './policy.js';
export function createGeometryQueue({
@@ -25,6 +27,8 @@ export function createGeometryQueue({
clearTimeout(layerState._geoQueueTimer);
layerState._geoQueueTimer = 0;
}
clearTimeout(layerState._viewGeometryRetryTimer);
layerState._viewGeometryRetryTimer = 0;
layerState._geoQueue = [];
layerState._geoProgressNotifier = null;
if (clearProgress) {
@@ -121,16 +125,16 @@ export function createGeometryQueue({
* throughput without restarting the queue.
*
* @param {Object} [ownership={}] Current camera-ownership state.
* @param {*} [ownership.trackedEntity] Cesium tracked entity, if any.
* @param {*} [ownership.followed] What the camera follows, if anything.
* @param {boolean} [ownership.cockpitActive] Whether cockpit owns the camera.
* @returns {{ batchSize: number, delayMs: number }} Drain pacing.
*/
function cctvGeometryDrainPacing({
trackedEntity = null,
followed = null,
cockpitActive = false,
} = {}) {
if (trackedEntity || cockpitActive) {
if (followed || cockpitActive) {
return {
batchSize: GEO_TRACKING_BATCH_SIZE,
delayMs: GEO_TRACKING_BATCH_DELAY_MS,
@@ -209,7 +213,7 @@ export function createGeometryQueue({
const batchResult = processCctvGeometryDrainBatch({
queue: layerState._geoQueue,
readOwnership: () => ({
trackedEntity: layerState._viewer.trackedEntity,
followed: followedOf(layerState._viewer),
cockpitActive:
typeof document !== 'undefined' &&
document.body?.classList.contains('cockpit-mode'),
@@ -223,6 +227,7 @@ export function createGeometryQueue({
err?.message || err,
);
}
noteViewAttempt(record);
if (
layerState._geoLoading &&
layerState._geoLoadDone < layerState._geoLoadTotal
@@ -236,14 +241,15 @@ export function createGeometryQueue({
layerState._geoLoading = false;
if (wasInitialLoad) {
layerState._geoLoadDone = layerState._geoLoadTotal;
if (layerState._enabled) {
parts.rendering.refreshCoverageStyles();
// Geometry refinement may have replaced record.position objects — the
// one-shot drain completion re-anchors the card entries (event-driven,
// not a per-frame or timer pass).
parts.cards.refreshAmbientCards();
}
if (layerState._enabled) parts.rendering.refreshCoverageStyles();
}
// Geometry refinement may have replaced record.position objects — every
// drain's completion re-anchors the card entries (event-driven, not a
// per-frame or timer pass).
// While the camera moves, moveEnd reselects them instead.
if (layerState._enabled && !layerState._cameraMoving)
parts.cards.refreshAmbientCards();
scheduleViewGeometryRetry();
// Completion is never coalesced: subscribers must observe the final
// loading state even if the last progress tick just happened.
layerState._geoProgressNotifier?.finish();
@@ -261,16 +267,17 @@ export function createGeometryQueue({
/**
* Appends records to the geometry queue (no progress tracking) and starts
* the batch timer if idle. Used by update()'s ONE-SHOT tiles-ready completion
* pass (records left `!groundResolved` by an enable-time drain that ran while
* tiles were still streaming) so it shares the same stagger machinery as the
* initial load. Fires at most once per enable — never on a recurring timer.
* the batch timer if idle. Used by update()'s one-shot tiles-ready
* completion pass and by enqueueViewGeometry, so both share the initial
* load's stagger machinery. Never driven by a recurring timer.
* @param {Object[]} records - Camera records needing geometry refresh.
*/
function enqueueGeometryRefresh(records) {
const queued = new Set(layerState._geoQueue);
for (const record of records) {
if (!layerState._geoQueue.includes(record)) {
if (!queued.has(record)) {
queued.add(record);
layerState._geoQueue.push(record);
}
}
@@ -283,10 +290,10 @@ export function createGeometryQueue({
}
/**
* Starts the initial staggered load: orders all records active-camera-first,
* then by distance from the current viewer position (nearest first, so
* cameras likely in view refine before off-screen ones), and exposes
* loaded/total progress through uiState()/getStats() while running.
* Starts the initial staggered load over the geometry working set: active
* camera first, then by distance from the current viewer position (nearest
* first), and exposes loaded/total progress through uiState()/getStats()
* while running. Cameras outside the view refine when they come into it.
*/
function startGeometryLoadQueue() {
@@ -296,14 +303,10 @@ export function createGeometryQueue({
layerState._tilesReadyReenqueued = false;
if (!layerState._records.length) return;
const active = parts.selection.getActiveRecord();
const carto = layerState._viewer?.camera?.positionCartographic;
const refLat = carto
? Cesium.Math.toDegrees(carto.latitude)
: (active?.camera.lat ?? 0);
const refLon = carto
? Cesium.Math.toDegrees(carto.longitude)
: (active?.camera.lon ?? 0);
const pending = layerState._records
const pose = parts.model.eyePose();
const refLat = pose ? pose.lat : (active?.camera.lat ?? 0);
const refLon = pose ? pose.lon : (active?.camera.lon ?? 0);
const pending = geometryWorkingSet()
.filter((record) => record !== active)
.map((record) => ({
record,
@@ -325,7 +328,134 @@ export function createGeometryQueue({
);
layerState._geoQueueTimer = setTimeout(processGeometryBatch, 0);
}
/**
* The records whose geometry the view needs: the shown icons, the active
* camera and the coverage cohort drawn around it.
* @returns {Object[]}
*/
function geometryWorkingSet() {
const records = new Set(layerState._viewRecords);
const active = parts.selection.getActiveRecord();
if (active) records.add(active);
for (const id of layerState._coverageVisibleIds) {
const record = layerState._recordById.get(id);
if (record) records.add(record);
}
return [...records];
}
/** The regime key a view attempt counts against: interim while tiles stream. */
function viewAttemptKey() {
const regime = parts.ground.currentSurfaceRegime();
const tilesReady =
regime !== 'google-3d' || parts.model.projectionTilesReady();
return { key: tilesReady ? regime : `${regime}:interim`, tilesReady };
}
/**
* Counts a processed geometry attempt against the current regime key; each
* key keeps its own count, so tile streaming going on and off does not
* reset the ready-tiles budget.
*/
function noteViewAttempt(record) {
const { key } = viewAttemptKey();
record.viewAttempts ??= {};
record.viewAttempts[key] = (record.viewAttempts[key] || 0) + 1;
record.viewAttemptAt = performance.now();
}
/**
* Whether a record may be attempted again under `key`. After a first
* unresolved attempt, the second waits out VIEW_GEOMETRY_RETRY_MS so its
* elevation cell can warm, rather than going to the next motion tick.
*/
/** Whether a record still has an attempt left under the current key. */
function withinViewBudget(record) {
const { key } = viewAttemptKey();
return (record.viewAttempts?.[key] || 0) < VIEW_GEOMETRY_ATTEMPTS;
}
function attemptsLeft(record, key) {
const attempts = record.viewAttempts?.[key] || 0;
if (attempts >= VIEW_GEOMETRY_ATTEMPTS) return false;
return (
attempts === 0 ||
performance.now() - record.viewAttemptAt >= VIEW_GEOMETRY_RETRY_MS
);
}
/**
* After a drain, gives working-set cameras it left ungrounded one more
* attempt once their elevation cells have had time to warm. The timer is
* set for the earliest such camera and re-arms for the rest when it fires.
*/
function scheduleViewGeometryRetry() {
if (!layerState._enabled || layerState._viewGeometryRetryTimer) return;
const { key } = viewAttemptKey();
const active = parts.selection.getActiveRecord();
let due = Infinity;
for (const record of geometryWorkingSet()) {
const attempts = record.viewAttempts?.[key] || 0;
if (
record === active ||
attempts === 0 ||
attempts >= VIEW_GEOMETRY_ATTEMPTS ||
!parts.ground.needsGeometry(record)
)
continue;
due = Math.min(due, record.viewAttemptAt + VIEW_GEOMETRY_RETRY_MS);
}
if (due === Infinity) return;
layerState._viewGeometryRetryTimer = setTimeout(
() => {
layerState._viewGeometryRetryTimer = 0;
enqueueViewGeometry();
// A drain re-arms on completion; with none running, the cameras still
// cooling down need their own timer.
if (!layerState._geoQueueTimer) scheduleViewGeometryRetry();
},
Math.max(0, due - performance.now()),
);
}
/**
* Queues working-set cameras the current surface has not grounded yet,
* after a camera move brings new ones into view. Attempts are counted when
* a record is processed, not queued, so a drain cut short by disable() is
* not lost; each record gets VIEW_GEOMETRY_ATTEMPTS per surface regime,
* spaced by VIEW_GEOMETRY_RETRY_MS, so a sample the shared floor refuses
* (too far, too high) is not retried on every move. While photoreal tiles are still streaming the attempts are
* interim, and the update() completion pass is re-armed to retry these
* records when they land. The active camera is left to selection, which
* owns its re-sampling.
*/
function enqueueViewGeometry() {
if (!layerState._enabled) return;
const { key, tilesReady } = viewAttemptKey();
const active = parts.selection.getActiveRecord();
const pending = [];
let coolingDown = false;
for (const record of geometryWorkingSet()) {
if (record === active || !parts.ground.needsGeometry(record)) continue;
if (!attemptsLeft(record, key)) {
coolingDown ||=
(record.viewAttempts?.[key] || 0) < VIEW_GEOMETRY_ATTEMPTS;
continue;
}
pending.push(record);
}
// A camera back in view during its cooldown still needs its retry timer.
if (coolingDown && !layerState._geoQueueTimer) scheduleViewGeometryRetry();
if (!pending.length) return;
if (!tilesReady) layerState._tilesReadyReenqueued = false;
enqueueGeometryRefresh(pending);
}
return {
enqueueViewGeometry,
withinViewBudget,
geometryWorkingSet,
stopGeometryLoadQueue,
createGeometryProgressNotifier,
processCctvGeometryQueueBatch,
+49 -8
View File
@@ -1,3 +1,5 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { findGlobe } from '../../render/rendererOf.js';
import {
SUPPORT_KEYS,
planeSupportPoints,
@@ -12,7 +14,7 @@ export function createGround({ state: layerState, services, parts, source }) {
const { resolveEllipsoidalGround } = services.terrain;
/**
* Task 5 (height-datum fix): maps the scene's `globe.show` flag to the surface
* Task 5 (height-datum fix): maps whether the renderer shows the globe to the surface
* regime key the per-camera ground cache is keyed by (spec §2 "cache by
* surface regime", collapsed to two keys — ion World Terrain and Re:Earth
* globe terrain get the same handling):
@@ -25,7 +27,8 @@ export function createGround({ state: layerState, services, parts, source }) {
* Only an explicit `false` (the photoreal stack hides the globe) selects
* `google-3d`; undefined/null (no viewer / torn down) must fall to the regime
* that never touches the scene. Pure — exported for the unit suite.
* @param {boolean|undefined|null} globeShow - `viewer.scene.globe.show`.
* @param {boolean|undefined|null} globeShow - Whether the renderer shows the
* globe (`globe.isGlobeVisible()`).
* @returns {'google-3d'|'terrain-globe'}
*/
@@ -35,15 +38,15 @@ export function createGround({ state: layerState, services, parts, source }) {
/**
* Task 5: the surface regime the scene is CURRENTLY rendering, derived live
* from `globe.show` (mapStackController's `_activatePhotoreal` /
* `_activateGlobeStack` flip exactly this flag). Reading scene state directly
* from whether the renderer shows the globe (mapStackController's
* `_activatePhotoreal` / `_activateGlobeStack` flip exactly this). Reading it live
* — rather than caching the map-stack id — means the regime is correct even
* for stack changes this module never got an event for.
* @returns {'google-3d'|'terrain-globe'}
*/
function currentSurfaceRegime() {
return surfaceRegimeKey(layerState._viewer?.scene?.globe?.show);
return surfaceRegimeKey(findGlobe(layerState._viewer)?.isGlobeVisible?.());
}
/**
@@ -78,6 +81,14 @@ export function createGround({ state: layerState, services, parts, source }) {
return record?.groundResolved?.[regime] === true;
}
/**
* True until the record has geometry grounded for the regime. Cameras are
* refined only once they enter the view, so many never have geometry.
*/
function needsGeometry(record, regime = currentSurfaceRegime()) {
return !record?.frustumGeometry || !isGroundResolved(record, regime);
}
/**
* Ground altitude used for pure geometry recomputes: the given regime's
* cached resolution (`record.groundSamples[regime]` — a shared mesh/DEM floor
@@ -184,8 +195,11 @@ export function createGround({ state: layerState, services, parts, source }) {
* Task 5: applies a LATE-arriving ground-prior batch (init's bounded race
* lost — cold proxy cache / slow upstream). Pure recomputes only, no scene
* queries:
* - records without geometry yet: only the icon moves onto the prior;
* the frustum is built when the camera enters the view.
* - terrain-globe regime: the prior IS the resolution → re-run the
* resolution (updateRecordGeometry latches it) for every record.
* resolution (updateRecordGeometry latches it) for every record with
* geometry.
* - google-3d regime: records still awaiting a shared floor move from the
* catalog fallback onto the exact prior; records already holding a shared
* mesh/DEM floor keep it untouched.
@@ -198,6 +212,7 @@ export function createGround({ state: layerState, services, parts, source }) {
function applyLateGroundPriors(records, priors) {
if (!Array.isArray(records) || !Array.isArray(priors)) return;
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];
@@ -212,6 +227,26 @@ export function createGround({ state: layerState, services, parts, source }) {
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.
@@ -224,7 +259,9 @@ export function createGround({ state: layerState, services, parts, source }) {
applied += 1;
}
}
if (applied) parts.presentation.notifyListeners();
if (moved && parts.rendering.refreshHorizonCulling())
parts.geometryQueue.enqueueViewGeometry();
if (applied || moved) parts.presentation.notifyListeners();
}
/**
@@ -234,7 +271,7 @@ export function createGround({ state: layerState, services, parts, source }) {
* deck/building-top in google-3d vs bare Re:Earth DEM on globe stacks), so
* on a REGIME change (photoreal ↔ globe; bing→osm stays 'terrain-globe' and
* no-ops):
* 1. every record's geometry recomputes IMMEDIATELY from the new regime's
* 1. every record that has geometry recomputes IMMEDIATELY from the new regime's
* resolution — cached sample if that regime has one, else the Re:Earth
* prior (never blank, zero scene queries);
* 2. entering google-3d re-arms the one-shot tiles-ready completion latch so
@@ -250,6 +287,9 @@ export function createGround({ state: layerState, services, parts, source }) {
layerState._lastAppliedRegime = regime;
for (const record of layerState._records) {
// Only cameras that already have geometry are rewritten; the rest are
// grounded for the new regime when they enter the view.
if (!record.frustumGeometry) continue;
if (regime === 'terrain-globe') {
// Prior IS the resolution — latch it (zero scene queries).
record.groundSamples['terrain-globe'] = groundPriorAltFor(record);
@@ -353,6 +393,7 @@ export function createGround({ state: layerState, services, parts, source }) {
resolveFootprintGround,
groundPriorAltFor,
isGroundResolved,
needsGeometry,
groundAltFor,
rearmGroundResolution,
resolveCommittedGroundAnchor,
+2 -1
View File
@@ -1,4 +1,5 @@
import { t } from '../../i18n/index.js';
import { roundHeadingDegrees } from '../../data/headingDegrees.js';
/**
* @module headingConfidence
@@ -44,7 +45,7 @@ export function isHeadingEstimated(camera) {
* @returns {string}
*/
export function headingHudToken(camera) {
const hdg = Math.round(Number(camera?.headingDeg) || 0);
const hdg = roundHeadingDegrees(Number(camera?.headingDeg)) ?? 0;
return isHeadingEstimated(camera)
? t('HDG {value}° (ESTIMATED)', { value: hdg })
: t('HDG {value}°', { value: hdg });
@@ -44,6 +44,15 @@ test('HUD token tags a synthetic bearing and rounds the degrees', () => {
);
});
test('HUD token reads a bearing that rounds to north as 0°, not 360°', () => {
assert.equal(headingHudToken({ headingDeg: 359.4 }), 'HDG 359°');
assert.equal(headingHudToken({ headingDeg: 359.6 }), 'HDG 0°');
assert.equal(
headingHudToken({ headingDeg: 359.5, headingConfidence: 'low' }),
'HDG 0° (ESTIMATED)',
);
});
test('HUD token stays untagged for surveyed and calibrated bearings', () => {
assert.equal(
headingHudToken({ headingDeg: 67.5, headingConfidence: 'high' }),
+1 -1
View File
@@ -1,4 +1,4 @@
import { HEALTH_SYNC_INTERVAL_MS, HEALTH_ENDPOINT } from './policy.js';
import { HEALTH_SYNC_INTERVAL_MS } from './policy.js';
export function createHealth({ state: layerState, services, parts, source }) {
/**
+4 -11
View File
@@ -10,7 +10,7 @@ export function createHover({ state: layerState, services, parts, source }) {
* Throttled MOUSE_MOVE hover pass (owner round 2, item B): pointing at a
* camera icon that has no card summons its card immediately. This is
* EVENT-DRIVEN picking on a user gesture, not steady-state work — the
* ≥120 ms throttle caps it at ~8 scene.pick calls/s while the pointer is
* ≥120 ms throttle caps it at ~8 scene picks/s while the pointer is
* actually moving (a still pointer costs nothing), so it can never approach
* per-frame cost. Skipped while the camera is in motion, while ADJUST mode
* owns the pointer (gizmo drags), and while the layer is disabled.
@@ -29,13 +29,7 @@ export function createHover({ state: layerState, services, parts, source }) {
const now = Date.now();
if (now - layerState._hoverLastPickAt < HOVER_PICK_THROTTLE_MS) return;
layerState._hoverLastPickAt = now;
let picked = null;
try {
picked = layerState._viewer.scene.pick(position);
} catch {
picked = null;
}
const cameraId = parts.selection.extractPickedCameraId(picked);
const cameraId = parts.rendering.pickCameraIdAt(position);
if (cameraId && cameraId === layerState._hoverCardId) {
// Still on the hovered camera — keep the card alive.
cancelHoverRelease();
@@ -49,9 +43,8 @@ export function createHover({ state: layerState, services, parts, source }) {
!!record &&
cameraId !== layerState._activeCameraId &&
!layerState._cardIds.has(cameraId) &&
!parts.model.isVideoFeedType(
parts.model.normalizeFeedType(record.camera.feedType),
);
!parts.model.isBrowserOverlayCamera(record.camera) &&
!parts.model.isVideoFeedCamera(record.camera);
if (eligible) {
cancelHoverRelease();
layerState._hoverCardId = cameraId;
+10
View File
@@ -18,6 +18,7 @@ import { createHealth } from './health.js';
import { createControls } from './controls.js';
import { createIngestion } from './ingestion.js';
import { createState } from './state.js';
import { createDrawSets } from './drawSets.js';
/** Construct one layer with its own scene state and supplied application services. */
export function createCctvLayer({ services, source }) {
@@ -30,6 +31,7 @@ export function createCctvLayer({ services, source }) {
const state = createState({ services });
const parts = {};
const context = { state, services, parts, source };
parts.drawSets = createDrawSets(context);
parts.calibration = createCalibration(context);
parts.testing = createTesting(context);
parts.projection = createProjection(context);
@@ -73,6 +75,7 @@ export function createCctvLayer({ services, source }) {
deriveCalBadge: parts.calibration.deriveCalBadge,
computeFrustumGeometry: parts.geometry.computeFrustumGeometry,
activationProbeClampRange: parts.geometry.activationProbeClampRange,
flatGroundAxisDistance: parts.geometry.flatGroundAxisDistance,
frameSignatureFromPixels: parts.frames.frameSignatureFromPixels,
_createCctvProjectionPlaneForTest:
parts.testing._createCctvProjectionPlaneForTest,
@@ -91,6 +94,9 @@ export function createCctvLayer({ services, source }) {
processGeometryBatch: parts.geometryQueue.processGeometryBatch,
hideCctvRecordVisuals: parts.rendering.hideCctvRecordVisuals,
refreshCoverageStyles: parts.rendering.refreshCoverageStyles,
refreshHorizonCulling: parts.rendering.refreshHorizonCulling,
_viewRecordIdsForTest: () =>
state._viewRecords.map((record) => record.camera.id),
clearProbeClampOnDeactivation:
parts.geometry.clearProbeClampOnDeactivation,
cctvRecordNeedsActivation: parts.model.cctvRecordNeedsActivation,
@@ -107,8 +113,12 @@ export function createCctvLayer({ services, source }) {
_extractPickedCameraIdForTest:
parts.testing._extractPickedCameraIdForTest,
_setCctvCoverageStateForTest: parts.testing._setCctvCoverageStateForTest,
_cctvIconsForTest: parts.testing._cctvIconsForTest,
_cctvDrawnForTest: parts.testing._cctvDrawnForTest,
focusCctvRecord: parts.navigation.focusCctvRecord,
maybeAutoHop: parts.navigation.maybeAutoHop,
openingCameraId: parts.navigation.openingCameraId,
reopenNearestCamera: parts.navigation.reopenNearestCamera,
cctvCycleIndex: parts.navigation.cctvCycleIndex,
},
);
+14 -5
View File
@@ -29,16 +29,25 @@ export function createIngestion({
layerState._tilesReadyReenqueued = true;
// Per-regime resolution (Task 5): only records unresolved for the
// CURRENT surface regime need the completion pass. On globe stacks
// projectionTilesReady() is false while a (hidden) Google tileset
// exists, so this latch effectively fires for the google-3d regime —
// projectionTilesReady() is false (only drawn photoreal tiles can be
// ready), so this latch fires for the google-3d regime alone —
// terrain-globe records resolve from the prior in their drain pass.
const unresolved = layerState._records.filter(
(record) => !parts.ground.isGroundResolved(record),
);
const unresolved = parts.geometryQueue
.geometryWorkingSet()
.filter(
(record) =>
!parts.ground.isGroundResolved(record) &&
parts.geometryQueue.withinViewBudget(record),
);
if (unresolved.length)
parts.geometryQueue.enqueueGeometryRefresh(unresolved);
}
await parts.health.syncHealthState();
// New health can change which camera wins a crowded cell.
if (layerState._enabled && parts.rendering.refreshHorizonCulling()) {
parts.geometryQueue.enqueueViewGeometry();
parts.cards.refreshAmbientCards();
}
parts.navigation.maybeAutoHop(now);
parts.presentation.notifyListeners();
},
+246 -129
View File
@@ -1,36 +1,174 @@
import * as Cesium from 'cesium';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { distance, dot } from '../../geo/vector.js';
import { canvasOf, findCamera } 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';
import { inputFor } from '../../input/dispatcher.js';
import {
GROUND_PRIOR_INIT_WAIT_MS,
CAMERA_ICON,
IDLE_CAMERA_COLOR,
CALIBRATION_RANGE_FLOOR_M,
VIEW_MOTION_REFRESH_MS,
VIEW_MOTION_MIN_MOVE_FRACTION,
VIEW_MOTION_MIN_TURN_DEG,
VIEW_MOTION_COST_FACTOR,
} from './policy.js';
const MIN_TURN_COS = Math.cos((VIEW_MOTION_MIN_TURN_DEG * Math.PI) / 180);
export function createLifecycle({
state: layerState,
services,
parts,
source,
}) {
const { registerSpriteCollection, restoreSpriteOrder } = services.sprites;
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
/**
* The settled-view pass: thin the icons, queue the newly visible geometry,
* reselect cards, and tell subscribers (the camera picker) when the shown
* set changed since they were last told, including by motion passes.
*/
function settleView() {
const changed = parts.rendering.refreshHorizonCulling();
noteViewPose();
parts.geometryQueue.enqueueViewGeometry();
parts.cards.refreshAmbientCards();
if (changed || layerState._viewUnpublished) {
layerState._viewUnpublished = false;
parts.presentation.notifyListeners();
}
}
/** Records the camera pose the last view pass ran at. */
function noteViewPose() {
const pose = findCamera(layerState._viewer)?.pose();
if (!pose) return;
layerState._viewPose = {
position: pose.position,
direction: pose.direction,
};
}
/**
* Whether the camera moved or turned enough since the last view pass to
* change what is on screen. A camera that tracks or flies without settling
* would otherwise rerun the full pass on every tick.
*/
function viewPoseChanged() {
const now = findCamera(layerState._viewer)?.pose();
const pose = layerState._viewPose;
if (!pose || !now) return true;
// An eye with no geographic position (the earth's centre) has no height.
const height = Math.max(1, Number.isFinite(now.height) ? now.height : 0);
const moved = distance(now.position, pose.position);
if (moved > height * VIEW_MOTION_MIN_MOVE_FRACTION) return true;
return dot(now.direction, pose.direction) < MIN_TURN_COS;
}
function viewMotionTick() {
if (!layerState._enabled) return;
const now = performance.now();
const pass = layerState._viewMotionPass;
if (pass && now - pass.at < pass.ms * VIEW_MOTION_COST_FACTOR) return;
if (!viewPoseChanged()) return;
if (parts.rendering.refreshHorizonCulling())
layerState._viewUnpublished = true;
noteViewPose();
parts.geometryQueue.enqueueViewGeometry();
layerState._viewMotionPass = { at: now, ms: performance.now() - now };
}
function startViewMotionTimer() {
if (layerState._viewMotionTimer) return;
layerState._viewMotionTimer = setInterval(
viewMotionTick,
VIEW_MOTION_REFRESH_MS,
);
}
function stopViewMotionTimer() {
clearInterval(layerState._viewMotionTimer);
layerState._viewMotionTimer = 0;
}
/**
* Listen for the camera's moves on the viewer's camera port: hover picking
* pauses while it moves, and the view pass reruns on an interval until the
* move ends, then once more. A re-init against a new viewer moves the
* listeners to its camera; one against the same viewer keeps them.
*/
function attachViewListeners() {
const viewCamera = findCamera(layerState._viewer);
if (
layerState._viewListenerCamera &&
layerState._viewListenerCamera !== viewCamera
) {
layerState._horizonCullListener?.();
layerState._moveStartListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener = null;
layerState._cameraMoving = false;
}
layerState._viewListenerCamera = viewCamera;
if (!layerState._horizonCullListener && viewCamera) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = viewCamera.on('moveEnd', () => {
layerState._cameraMoving = false;
stopViewMotionTimer();
parts.navigation.reopenNearestCamera();
settleView();
});
}
if (!layerState._moveStartListener && viewCamera) {
// Item B: hover picking pauses while the camera is in motion. A long
// move (cockpit flight, a drag) never settles, so the view pass also
// reruns on an interval until it does.
layerState._moveStartListener = viewCamera.on('moveStart', () => {
layerState._cameraMoving = true;
// enable() starts it for a move already under way.
if (layerState._enabled) startViewMotionTimer();
});
}
}
/** Drop the move listeners; nothing reports the end of a move after it. */
function detachViewListeners() {
layerState._horizonCullListener?.();
layerState._horizonCullListener = null;
layerState._moveStartListener?.();
layerState._moveStartListener = null;
layerState._cameraMoving = false;
layerState._viewListenerCamera = null;
stopViewMotionTimer();
}
/** Resets all module-scoped runtime state to initial values. */
function clearRuntimeState() {
parts.geometryQueue.stopGeometryLoadQueue();
stopViewMotionTimer();
// Idempotent — also covers a re-init without a prior destroy().
parts.cards.teardownAmbientCards();
parts.projection.clearProjectionOverlay();
// An activation probe still to answer lands on none of these records.
for (const record of layerState._records || [])
if (record) record.probeToken = (record.probeToken || 0) + 1;
layerState._records = [];
layerState._recordById = new Map();
layerState._viewRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
layerState._viewUnpublished = false;
layerState._viewPose = null;
layerState._viewMotionPass = null;
layerState._healthById = new Map();
layerState._count = 0;
layerState._lastUpdate = null;
@@ -38,9 +176,6 @@ export function createLifecycle({
layerState._lastError = null;
layerState._lastFocusStyleAt = 0;
layerState._activeFocusStyleCount = 0;
// FIX ①/③: the discovered tileset handle is scene-scoped — drop it so a fresh
// init re-discovers against the current scene primitives.
layerState._activeTileset = null;
// Task 5: the applied-regime tracker is record-set-scoped — a fresh init
// recomputes it against the then-current scene.
layerState._lastAppliedRegime = null;
@@ -48,9 +183,9 @@ export function createLifecycle({
const methods = {
/**
* Initializes the CCTV layer: loads camera sources, builds the catalog,
* restores calibration from localStorage, creates billboards, sets up click
* restores calibration from localStorage, creates camera icons, sets up click
* handling, and performs initial health sync. Coverage entities stay lazy.
* @param {Cesium.Viewer} viewer - The Cesium viewer instance.
* @param {object} viewer - The viewer.
*/
async init(viewer) {
layerState._sourceAbort?.abort();
@@ -66,13 +201,12 @@ export function createLifecycle({
layerState._enabled = false;
layerState._activeCameraId = null;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
layerState._lastHopAt = 0;
layerState._lastViewContext = '';
layerState._calibrationById = parts.calibration.loadCalibrationStore();
layerState._billboards = new Cesium.BillboardCollection();
layerState._viewer.scene.primitives.add(layerState._billboards);
registerSpriteCollection('cctv', layerState._billboards);
parts.rendering.createCameraIcons(layerState._viewer);
const sources = await parts.catalog.loadCameraSources();
const catalogFromSources = parts.catalog.buildCatalogFromSources(sources);
@@ -140,32 +274,14 @@ export function createLifecycle({
? groundPrior.ellipsoid
: Number(camera.groundElevationM) || 0;
camera.absoluteHeightM = priorGround + camera.mountHeightM;
const position = Cesium.Cartesian3.fromDegrees(
const position = fromDegrees(
camera.lon,
camera.lat,
camera.absoluteHeightM,
);
const billboard = layerState._billboards.add({
id: camera.id,
image: CAMERA_ICON,
position,
color: IDLE_CAMERA_COLOR,
width: 24,
height: 24,
// Field-test fix (2026-07-06): always-on-top. The old finite value
// (1800 m) re-engaged the depth test at far zoom, where the COARSE
// far-LOD Google-3D mesh sits above the true ground and swallowed
// ground-anchored icons ("submerged" pills over SF). Far-side-of-globe
// icons are handled by refreshHorizonCulling() (the flights-layer
// EllipsoidalOccluder pattern), not by the depth test.
disableDepthTestDistance: Number.POSITIVE_INFINITY,
scaleByDistance: new Cesium.NearFarScalar(350, 1.25, 4_000_000, 0.42),
});
const record = {
camera,
position,
billboard,
coverageEntities: [],
projection: null,
// Task 5 (height-datum fix): regime-aware ground resolution state.
@@ -199,19 +315,17 @@ export function createLifecycle({
viewshedColors: viewshedColors(
cameraHue(hueIndexById.get(camera.id) ?? 0),
),
viewshedPrimitive: null,
viewshedVolume: null,
viewshedActiveTint: false,
};
layerState._records.push(record);
layerState._recordById.set(camera.id, record);
parts.rendering.addCameraIcon(record);
}
layerState._count = layerState._records.length;
if (layerState._records.length > 0) {
// Projection runtime + first frame fetch are deferred to enable() so
// initializing the catalog stays render-cheap.
layerState._activeCameraId = layerState._records[0].camera.id;
}
// No camera is picked here: enable() opens on the one nearest the
// viewer, unless restored params selected one first.
// Task 5: if the prior batch lost init's bounded race, apply it post-hoc
// when it lands (pure recomputes — applyLateGroundPriors guards against
@@ -241,41 +355,59 @@ export function createLifecycle({
}
// Field-test fix (2026-07-06): horizon-cull on camera settle (pairs with
// the billboards' always-on-top depth setting) + one initial pass so the
// the icons' always-on-top drawing) + one initial pass so the
// first paint is already culled.
if (!layerState._horizonCullListener) {
// Ambient cards piggyback the same settle event: moveEnd-driven
// reselection only, never per frame (refreshAmbientCards no-ops while
// the layer is disabled).
layerState._horizonCullListener = () => {
layerState._cameraMoving = false;
parts.rendering.refreshHorizonCulling();
parts.cards.refreshAmbientCards();
};
layerState._viewer.camera.moveEnd.addEventListener(
layerState._horizonCullListener,
);
attachViewListeners();
// A resize or rotation changes what is on screen without moving the
// camera.
const canvas = canvasOf(layerState._viewer);
if (layerState._viewResizeCanvas !== canvas) {
// A re-init against a new viewer observes its canvas instead.
layerState._viewResizeObserver?.disconnect();
layerState._viewResizeObserver = null;
layerState._viewResizeCanvas = null;
}
if (!layerState._moveStartListener) {
// Item B: hover picking pauses while the camera is in motion.
layerState._moveStartListener = () => {
layerState._cameraMoving = true;
};
layerState._viewer.camera.moveStart.addEventListener(
layerState._moveStartListener,
);
if (
!layerState._viewResizeObserver &&
typeof ResizeObserver === 'function' &&
canvas
) {
let frame = 0;
layerState._viewResizeObserver = new ResizeObserver(() => {
if (frame || !layerState._enabled) return;
frame = requestAnimationFrame(() => {
frame = 0;
if (layerState._enabled) settleView();
});
});
layerState._viewResizeObserver.observe(canvas);
layerState._viewResizeCanvas = canvas;
}
parts.rendering.refreshHorizonCulling();
layerState._clickHandler = new Cesium.ScreenSpaceEventHandler(
layerState._viewer.scene.canvas,
);
parts.selection.bindCctvWorldClickGesture(
layerState._clickHandler,
(click) => {
const input = inputFor(layerState._viewer);
const unsubscribeClick = parts.selection.bindCctvWorldClickGesture(
input,
(event) => {
if (!layerState._enabled) return;
const picked = layerState._viewer.scene.pick(click.position);
const cameraId = parts.selection.extractPickedCameraId(picked);
const picked = event.topHit;
// The card or label painted on top takes the click, read once per
// click so every layer agrees: a live card of ours acts whatever
// is drawn under it; another layer's is that layer's click.
const top = clickCard?.(event) ?? null;
if (top && top.sourceId !== CCTV_OVERLAY_SOURCE_ID) return;
if (top) {
// A card of ours that is going away is still not the scene.
if (layerState._recordById.has(top.entryId))
activateCctvCameraFromWorldClick(
top.entryId,
parts.selection.setActiveCamera,
);
return;
}
const cameraId = parts.selection.extractPickedCameraId(
event.drawHit ?? null,
);
if (cameraId) {
activateCctvCameraFromWorldClick(
cameraId,
@@ -283,29 +415,11 @@ export function createLifecycle({
);
return;
}
// Any identified scene object owns this click even if its layer does not
// register a shared pick predicate. This keeps selectable siblings ahead
// of an overlapping CCTV card while ID-less globe/terrain/tile surfaces
// remain eligible for true empty-space deselection.
const pickedId = resolvePickId(picked);
if (pickedId !== null) return;
// Item A (owner round 2): the scene pick found no camera — try the
// painted ambient cards. The cards canvas is pointer-events:none (this
// handler owns the events), so a click landing on a card's rect selects
// its camera exactly like a click on the icon. Cesium click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
click.position.x,
click.position.y,
{ sourceId: CCTV_OVERLAY_SOURCE_ID },
)?.entryId;
if (cardId && layerState._recordById.has(cardId)) {
activateCctvCameraFromWorldClick(
cardId,
parts.selection.setActiveCamera,
);
return;
}
// Any identified scene object owns this click even if its layer
// does not register a shared pick predicate. This keeps selectable
// siblings ahead of the CCTV selection while ID-less globe, terrain
// and tile surfaces remain eligible for empty-space deselection.
if (resolvePickId(picked) !== null) return;
if (
parts.selection.cctvEmptyClickDeselects(picked, {
activeCameraId: layerState._activeCameraId,
@@ -315,19 +429,25 @@ export function createLifecycle({
parts.selection.deactivateActiveCamera();
}
},
{
// Item B: hover summons a card on a cardless camera icon. The gesture
// classifier owns MOUSE_MOVE too, so chain hover work through its seam
// instead of replacing the travel accumulator's handler.
onMouseMove: (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
},
);
// Item B: hover summons a card on a cardless camera icon.
const unsubscribeHover = input.onPointer('move', (movement) =>
parts.hover.handleHoverMove(movement?.endPosition),
);
layerState._clickSubscription = () => {
unsubscribeClick();
unsubscribeHover();
};
await parts.health.syncHealthState(true);
// Health ranks crowded cells: thin again now that it has arrived (a
// no-op unless enable() ran while health was loading).
if (parts.rendering.refreshHorizonCulling()) {
parts.geometryQueue.enqueueViewGeometry();
parts.cards.refreshAmbientCards();
}
parts.rendering.refreshCoverageStyles();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
console.log('[Data:CCTV] Initialized with', layerState._count, 'cameras');
},
@@ -346,7 +466,7 @@ export function createLifecycle({
)
services.credits?.showOsmCredit?.(layerState._viewer, 'cctv');
layerState._lastUpdate = Date.now();
// Pick-ownership (H2): camera billboards use the camera id directly;
// Pick-ownership (H2): camera icons use the camera id directly;
// coverage polyline entities use `cctv-<cameraId>-<role>` entity ids.
registerPickOwner('cctv', (pickedId) => {
if (layerState._recordById.has(pickedId)) return true;
@@ -362,14 +482,18 @@ export function createLifecycle({
return Boolean(coverage && layerState._recordById.has(coverage[1]));
});
if (!layerState._activeCameraId && layerState._records.length) {
layerState._activeCameraId = layerState._records[0].camera.id;
layerState._activeCameraId = parts.navigation.openingCameraId();
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = true;
}
const activeRecord = parts.selection.getActiveRecord();
if (activeRecord) {
parts.projection.ensureProjectionRuntime(activeRecord);
parts.frames.refreshProjectionImage(activeRecord, true);
}
parts.rendering.refreshHorizonCulling();
// Re-enabled mid-flight: moveStart has already fired.
if (layerState._cameraMoving) startViewMotionTimer();
parts.geometryQueue.startGeometryLoadQueue();
parts.rendering.refreshCoverageStyles();
parts.projection.startProjectionLoop();
@@ -386,7 +510,6 @@ export function createLifecycle({
parts.cards.startCardFrameLoop();
parts.cards.refreshAmbientCards();
parts.presentation.notifyListeners();
restoreSpriteOrder(layerState._viewer);
},
/** Disables the layer: hides entities, stops the projection loop and load queue. */
@@ -402,19 +525,23 @@ export function createLifecycle({
layerState._removeFocusAppearListener = null;
parts.projection.stopProjectionLoop();
parts.geometryQueue.stopGeometryLoadQueue();
stopViewMotionTimer();
// Ambient cards tear down COMPLETELY on disable (owner design point 6):
// source entries, pacer timer, in-flight handlers, and caches.
parts.cards.teardownAmbientCards();
parts.rendering.hideCctvVisuals();
// Nothing is in view while the layer is off.
layerState._viewRecords = [];
layerState._cameraIndexCache = null;
parts.presentation.notifyListeners();
},
/**
* Tears down the layer: destroys click handler, projection loop, coverage
* entities, billboards, and clears all runtime state and subscribers.
* @param {Cesium.Viewer} [viewer] - Viewer instance (falls back to stored ref).
* entities, icons, and clears all runtime state and subscribers. It
* releases what init attached, whichever viewer it is handed.
*/
destroy(viewer) {
destroy() {
services.credits?.hideOsmCredit?.(layerState._viewer, 'cctv');
layerState._sourceAbort?.abort();
if (typeof document !== 'undefined')
@@ -430,50 +557,40 @@ export function createLifecycle({
);
layerState._mapStackListener = null;
}
const teardownViewer = viewer || layerState._viewer;
if (layerState._horizonCullListener && teardownViewer?.camera?.moveEnd) {
teardownViewer.camera.moveEnd.removeEventListener(
layerState._horizonCullListener,
);
layerState._horizonCullListener = null;
}
if (layerState._moveStartListener && teardownViewer?.camera?.moveStart) {
teardownViewer.camera.moveStart.removeEventListener(
layerState._moveStartListener,
);
layerState._moveStartListener = null;
}
detachViewListeners();
layerState._viewResizeObserver?.disconnect();
layerState._viewResizeObserver = null;
layerState._viewResizeCanvas = null;
if (layerState._gizmo) {
layerState._gizmo.destroy();
layerState._gizmo = null;
}
layerState._calibrationMode = false;
releaseContinuousRender('cctv-adjust');
if (layerState._clickHandler) {
layerState._clickHandler.destroy();
layerState._clickHandler = null;
}
if (teardownViewer?.scene?.screenSpaceCameraController) {
teardownViewer.scene.screenSpaceCameraController.enableInputs = true;
}
layerState._clickSubscription?.();
layerState._clickSubscription = null;
parts.projection.stopProjectionLoop();
parts.geometryQueue.stopGeometryLoadQueue();
parts.cards.teardownAmbientCards();
parts.geometry.destroyCoverageEntities();
if (layerState._billboards && teardownViewer) {
teardownViewer.scene.primitives.remove(layerState._billboards);
layerState._billboards = null;
}
parts.rendering.destroyCameraIcons();
parts.drawSets.dispose();
clearRuntimeState();
layerState._viewer = null;
layerState._enabled = false;
layerState._activeCameraId = null;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
// Clear existing subscribers rather than replacing the Set —
// replacing would silently orphan any unsubscribe() closures
layerState._listeners.clear();
},
};
return { clearRuntimeState, methods };
return {
clearRuntimeState,
attachViewListeners,
detachViewListeners,
methods,
};
}
+340
View File
@@ -0,0 +1,340 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createLifecycle } from './lifecycle.js';
import { createSelection } from './selection.js';
import { CCTV_OVERLAY_SOURCE_ID } from '../../data/cctvCards.js';
import { fakeInput, fakeInputUnderLabel } from '../../input/testDoubles.mjs';
import * as picking from '../../data/pickRegistry.js';
import { bindRenderer } from '../../render/rendererOf.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
function viewerWithCamera() {
const camera = fakeCameraPort();
const viewer = {};
bindRenderer(viewer, { camera: camera.port });
return { viewer, camera };
}
function lifecycleFor(state) {
const passes = [];
const lifecycle = createLifecycle({
state,
services: {
sprites: {},
activation: {},
picking: {},
focus: {},
render: {},
},
parts: {
rendering: {
refreshHorizonCulling: () => {
passes.push('view');
return false;
},
},
geometryQueue: { enqueueViewGeometry() {} },
cards: { refreshAmbientCards() {} },
presentation: { notifyListeners() {} },
navigation: { reopenNearestCamera() {} },
},
});
return { lifecycle, passes };
}
test('the view listeners follow the camera port and let go on teardown', () => {
const first = viewerWithCamera();
const state = { _viewer: first.viewer, _enabled: false };
const { lifecycle, passes } = lifecycleFor(state);
const counts = (camera) => [
camera.listenerCount('moveStart'),
camera.listenerCount('moveEnd'),
];
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
first.camera.emit('moveStart');
assert.equal(state._cameraMoving, true, 'hover pauses while moving');
first.camera.emit('moveEnd');
assert.equal(state._cameraMoving, false);
assert.deepEqual(passes, ['view'], 'a settled move reruns the view pass');
// A re-init on the same viewer keeps its listeners.
lifecycle.attachViewListeners();
assert.deepEqual(counts(first.camera), [1, 1]);
// One on a new viewer moves them to its camera.
const second = viewerWithCamera();
state._viewer = second.viewer;
first.camera.emit('moveStart');
lifecycle.attachViewListeners();
assert.equal(state._cameraMoving, false, 'the old move is forgotten');
assert.deepEqual(counts(first.camera), [0, 0]);
assert.deepEqual(counts(second.camera), [1, 1]);
lifecycle.detachViewListeners();
assert.deepEqual(counts(second.camera), [0, 0]);
assert.equal(state._viewListenerCamera, null);
});
/** A part whose members are `own`'s, and any other a function that does
* nothing. */
const inert = (own = {}) =>
new Proxy(own, {
get: (target, name) => (name in target ? target[name] : () => {}),
});
test("a click on a mission label over a camera's card never turns that camera on, and keeps the active one", async (t) => {
const { viewer } = viewerWithCamera();
viewer.scene = { canvas: {}, pick: () => null };
// The card of camera `cam-1` lies under every click, under the label.
const fake = fakeInputUnderLabel(viewer, {
beneath: () => ({ sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' }),
});
t.after(() => fake.destroy());
const activated = [];
const deactivated = [];
const state = {};
const lifecycle = createLifecycle({
state,
services: {
activation: {
activateCctvCameraFromWorldClick: (id) => activated.push(id),
},
picking,
focus: {},
render: {},
},
parts: {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => null,
},
rendering: inert({ refreshHorizonCulling: () => false }),
health: { syncHealthState: async () => {} },
geometryQueue: inert(),
cards: inert(),
projection: inert(),
presentation: inert(),
navigation: inert(),
hover: inert(),
selection: {
// The camera's own gate takes only clean clicks; these are.
bindCctvWorldClickGesture: (input, onClick) => input.onClick(onClick),
extractPickedCameraId: () => null,
cctvEmptyClickDeselects: (picked, { activeCameraId }) =>
Boolean(activeCameraId) && picking.resolvePickId(picked) === null,
deactivateActiveCamera: () => deactivated.push(state._activeCameraId),
},
},
});
// Init's bounded wait for ground heights never runs out here: they are in.
t.mock.timers.enable({ apis: ['setTimeout'] });
await lifecycle.methods.init(viewer);
t.after(() => state._clickSubscription?.());
state._enabled = true;
state._activeCameraId = 'cam-0';
state._recordById.set('cam-1', {});
fake.label.over = true;
fake.click();
assert.deepEqual(activated, [], 'the camera under the label stays off');
assert.deepEqual(deactivated, [], 'the active camera stays on');
// Off the label, a click on the card turns its camera on.
fake.label.over = false;
fake.click();
assert.deepEqual(activated, ['cam-1']);
});
test('the card painted on top takes world clicks, whatever is drawn under it', async (t) => {
const noop = () => {};
const { viewer } = viewerWithCamera();
let picked = null;
viewer.scene = {
canvas: {},
pick: () => (picked ? { id: picked } : undefined),
drillPick: () => drilled.map((id) => ({ id })),
};
let drilled = [];
const input = fakeInput(viewer);
// An aircraft layer that runs before ours and tracks the plane it was
// clicked on, standing aside under another layer's card.
let tracked = null;
input.input.onClick((event) => {
if (picking.isUnderOtherCard(event)) return;
if (event.hit?.id === 'plane:9') tracked = 'plane:9';
});
const ownCard = { sourceId: CCTV_OVERLAY_SOURCE_ID, entryId: 'cam-1' };
const foreignCard = {
sourceId: 'earthquake-card',
entryId: 'earthquake-card:qa',
};
let painted = [];
const actions = [];
// The card on top at a click, as the host answers the pick registry.
picking.setClickCardHitTest(() => painted[0] ?? null);
const state = {
_cctvOverlayHost: {
hitTest: (_x, _y, options = {}) =>
painted.find(
(hit) => !options.sourceId || hit.sourceId === options.sourceId,
) ?? null,
},
};
const parts = {
calibration: { loadCalibrationStore: () => new Map() },
catalog: {
loadCameraSources: async () => [],
buildCatalogFromSources: () => [],
seedCatalog: () => [],
},
ground: {
resolveGroundPriors: async () => [],
currentSurfaceRegime: () => 'terrain-globe',
},
cards: { teardownAmbientCards: noop },
projection: { clearProjectionOverlay: noop },
geometryQueue: { stopGeometryLoadQueue: noop },
rendering: {
createCameraIcons: noop,
refreshHorizonCulling: () => false,
refreshCoverageStyles: noop,
extractPickedCameraId: (hit) =>
hit?.set === 'cctv:fixture' ? hit.id : null,
},
hover: { handleHoverMove: noop },
health: { syncHealthState: async () => {} },
presentation: { notifyListeners: noop },
};
const services = {
sprites: {},
focus: { onFocusTargetAppear: () => noop },
render: { releaseContinuousRender: noop },
picking,
activation: { activateCctvCameraFromWorldClick: (id) => actions.push(id) },
};
parts.selection = createSelection({ state, services, parts });
parts.selection.deactivateActiveCamera = () => actions.push('clear');
const lifecycle = createLifecycle({ state, services, parts });
t.after(() => {
state._clickSubscription?.();
lifecycle.detachViewListeners();
input.destroy();
picking.setClickCardHitTest(null);
picking.unregisterPickOwner('area-control');
picking.unregisterPickOwner('test-trails');
picking.unregisterPickOwner('test-planes');
picking.unregisterPickOwner('test-tracking');
picking.unregisterPickOwner('test-exact');
});
await lifecycle.methods.init(viewer);
state._enabled = true;
state._activeCameraId = 'cam-1';
state._recordById.set('cam-1', { camera: { id: 'cam-1' } });
const click = (hit, cards, expected) => {
picked = hit;
painted = cards;
actions.length = 0;
input.tap();
assert.deepEqual(actions, expected, JSON.stringify({ hit, cards }));
};
const drone = {
set: 'drone-airspace:1:fills',
id: 'drone-airspace:zone:0',
surface: false,
};
const perimeter = {
set: 'fire-perimeters:1:lines',
id: 'fire-perimeter:incident:0',
surface: false,
};
const quake = { set: 'earthquakes:1', id: 'earthquake:q1', surface: false };
const cable = { set: 'submarine-cables:1:lines', id: 'c:0', surface: false };
const launch = {
set: 'launches:1:markers',
id: 'rocket-x:1',
surface: false,
};
const backgrounds = [drone, perimeter, quake, cable, launch];
for (const area of backgrounds) {
click(area, [ownCard], ['cam-1']);
click(area, [], []);
click(area, [foreignCard, ownCard], []);
}
// The live top card acts over anything drawn under it; with no card an
// identified object is not empty map.
for (const hit of [
{ set: 'flights:1', id: 'aircraft', surface: false },
{ set: '', id: 'unregistered-local-entity', surface: false },
{ ...drone, set: 'unrelated:1:fills' },
{ ...drone, id: 'unregistered-local-entity' },
]) {
click(hit, [ownCard], ['cam-1']);
click(hit, [], []);
}
// A trail under the live top card: the card keeps the click, and with no
// card the owned pick is not empty map.
const trail = { set: 'trails:1', id: 'gev-trail:fl-1:head', surface: false };
picking.registerPickOwner('test-trails', (id) => id === trail.id);
click(trail, [ownCard], ['cam-1']);
click(trail, [], []);
click(trail, [foreignCard, ownCard], []);
picking.unregisterPickOwner('test-trails');
// A coarse tap whose touch contact is an aircraft (a layer that acts on
// nearby contacts) under a live CCTV card is the card's.
const previousMatch = globalThis.matchMedia;
const restoreMatch = () => {
if (previousMatch) globalThis.matchMedia = previousMatch;
else delete globalThis.matchMedia;
};
// Restored below for the fine-pointer clicks that follow; here too, so a
// failing assertion cannot leave the coarse pointer for later tests.
t.after(restoreMatch);
globalThis.matchMedia = () => ({ matches: true });
picking.registerPickOwner('test-planes', (id) => id === 'plane:1');
drilled = ['plane:1'];
click(null, [ownCard], ['cam-1']);
// With no card, the bare tap near the aircraft still deselects.
click(null, [], ['clear']);
// A contact whose layer acts only on exact hits leaves the card its tap.
picking.registerPickOwner('test-exact', (id) => id === 'exact:1');
drilled = ['exact:1'];
click(null, [ownCard], ['cam-1']);
picking.unregisterPickOwner('test-exact');
drilled = [];
click(null, [ownCard], ['cam-1']);
picking.unregisterPickOwner('test-planes');
restoreMatch();
// The live card over an aircraft takes the click; the aircraft layer,
// run first, stands aside and does not track.
picking.registerPickOwner('test-tracking', (id) => id === 'plane:9');
click(
{ set: 'flights:1', id: 'plane:9', surface: false },
[ownCard],
['cam-1'],
);
assert.equal(tracked, null, 'the aircraft did not track');
picking.unregisterPickOwner('test-tracking');
picking.registerPickOwner('area-control', (id) => id === drone.id);
click(drone, [ownCard], ['cam-1']);
picking.unregisterPickOwner('area-control');
click(null, [foreignCard, ownCard], []);
click(null, [ownCard], ['cam-1']);
click(null, [], ['clear']);
click(drone, [{ ...ownCard, entryId: 'stale-camera' }], []);
// A card of ours that is going away is still not the scene under it: no
// camera beneath it activates, and nothing clears.
const staleCard = { ...ownCard, entryId: 'stale-camera' };
click({ set: 'cctv:fixture', id: 'cam-1' }, [staleCard], []);
click(null, [staleCard], []);
// A camera icon under another layer's card is that card's click.
click({ set: 'cctv:fixture', id: 'cam-1' }, [foreignCard, ownCard], []);
click({ set: 'cctv:fixture', id: 'cam-1' }, [], ['cam-1']);
});
+54 -64
View File
@@ -1,4 +1,6 @@
import * as Cesium from 'cesium';
import { cross, negate, toDegrees, toRadians } from '../../geo/vector.js';
import { fromAxes } from '../../geo/quaternion.js';
import { findCamera } from '../../render/rendererOf.js';
import { greatCircleKm } from '../../geoDistance.js';
import { staticFrameRefreshMs } from '../../data/cctvLod.js';
import { frameFetchDue, cardFetchPolicy } from '../../data/cctvCards.js';
@@ -14,7 +16,7 @@ export function createModel({ state: layerState, services, parts, source }) {
*/
function toRad(deg) {
return Cesium.Math.toRadians(deg);
return toRadians(deg);
}
/**
@@ -96,6 +98,19 @@ export function createModel({ state: layerState, services, parts, source }) {
return feedType === 'mp4' || feedType === 'hls' || feedType === 'webm';
}
/** A browser-only source still counts as live-capable for map icon/LOD policy. */
function isVideoFeedCamera(camera) {
return (
isVideoFeedType(normalizeFeedType(camera?.feedType)) ||
Boolean(camera?.browserMediaUrl)
);
}
/** Québec source pages and browser-played MP4s use the DOM overlay path. */
function isBrowserOverlayCamera(camera) {
return String(camera?.sourceKind || '').startsWith('quebec-');
}
/**
* Coerces a value to a finite number or returns the fallback.
*
@@ -295,8 +310,8 @@ export function createModel({ state: layerState, services, parts, source }) {
const lon2 = lon1 + Math.atan2(y, x);
return {
lat: Cesium.Math.toDegrees(lat2),
lon: Cesium.Math.toDegrees(lon2),
lat: toDegrees(lat2),
lon: toDegrees(lon2),
};
}
@@ -332,12 +347,22 @@ export function createModel({ state: layerState, services, parts, source }) {
* @returns {string} Grid key in the form "zoomBucket:latGrid:lonGrid".
*/
/**
* The eye's pose from the camera port, or null when there is no camera or
* the eye has no geographic position (the earth's centre).
* @returns {object|null}
*/
function eyePose() {
const pose = findCamera(layerState._viewer)?.pose();
return Number.isFinite(pose?.lat) ? pose : null;
}
function currentViewContext() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto) return 'none';
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
const alt = carto.height || 0;
const pose = eyePose();
if (!pose) return 'none';
const { lat, lon } = pose;
const alt = pose.height || 0;
const zoomBucket =
alt < 1500
? 'street'
@@ -358,43 +383,13 @@ export function createModel({ state: layerState, services, parts, source }) {
}
/**
* Reports whether the active Google Photorealistic 3D Tileset (if any) has
* finished loading the tiles in view. Shared mesh-floor sampling is gated on
* this so a one-shot cell never bakes in a miss from still-streaming tiles.
* Discovers + caches the tileset lazily from scene
* primitives (the CCTV module holds only a `_viewer` reference). When no
* tileset is present (OSM fallback) this returns true so ground sampling is
* not permanently blocked.
*
* Task 5 (review correction, spec §2): a HIDDEN tileset (`show === false`,
* i.e. a globe stack is active) must NOT report ready — Cesium 1.138's
* the shared sampler can only inspect *visible* 3D tilesets, so a sample taken
* against the hidden Google tileset would silently miss.
*
* @returns {boolean} True when tiles are loaded AND visible (or no tileset
* exists to wait on).
* Whether the photoreal tiles in view have finished loading; the rendering
* part, which reads the scene, answers.
* @returns {boolean}
*/
function projectionTilesReady() {
if (
!layerState._activeTileset ||
layerState._activeTileset.isDestroyed?.()
) {
layerState._activeTileset = null;
const primitives = layerState._viewer?.scene?.primitives;
if (primitives && typeof primitives.get === 'function') {
for (let i = 0; i < primitives.length; i++) {
const p = primitives.get(i);
if (p instanceof Cesium.Cesium3DTileset && !p.isDestroyed?.()) {
layerState._activeTileset = p;
break;
}
}
}
}
if (!layerState._activeTileset) return true;
if (layerState._activeTileset.show === false) return false;
return layerState._activeTileset.tilesLoaded === true;
return parts.rendering.projectionTilesReady();
}
/**
@@ -405,30 +400,17 @@ export function createModel({ state: layerState, services, parts, source }) {
* frame-up, so the 16:9 texture maps upright and unmirrored. Static geometry —
* computed only on slider/save/activation, never per frame (§2b).
* @param {Object} camera - Camera pose.
* @param {Cesium.Cartesian3} capCenterPos - Plane center in ECEF.
* @returns {Cesium.Quaternion}
* @param {{x: number, y: number, z: number}} capCenterPos - Plane center in ECEF.
* @returns {{x: number, y: number, z: number, w: number}} The quaternion.
*/
function planeOrientationFor(camera, capCenterPos) {
const frame = parts.geometry.frustumFrameEcef(camera, capCenterPos);
const right = Cesium.Cartesian3.cross(
frame.dir,
frame.up,
new Cesium.Cartesian3(),
);
const normal = Cesium.Cartesian3.negate(frame.dir, new Cesium.Cartesian3());
const m = new Cesium.Matrix3(
right.x,
frame.up.x,
normal.x,
right.y,
frame.up.y,
normal.y,
right.z,
frame.up.z,
normal.z,
);
return Cesium.Quaternion.fromRotationMatrix(m);
return fromAxes({
x: cross(frame.dir, frame.up),
y: frame.up,
z: negate(frame.dir),
});
}
/**
@@ -447,7 +429,12 @@ export function createModel({ state: layerState, services, parts, source }) {
function projectionLoopIsNeeded() {
if (!layerState._enabled || !layerState._viewer) return false;
if (layerState._showProjection && parts.selection.getActiveRecord())
const active = parts.selection.getActiveRecord();
if (
layerState._showProjection &&
active &&
!isBrowserOverlayCamera(active.camera)
)
return true;
return focusPassIsNeeded(
getFocusTarget(),
@@ -546,6 +533,7 @@ export function createModel({ state: layerState, services, parts, source }) {
return cameraId !== activeCameraId || record?.activationDone !== true;
}
return {
eyePose,
toRad,
normalizeHeading,
clamp,
@@ -553,6 +541,8 @@ export function createModel({ state: layerState, services, parts, source }) {
angularDeltaAbs,
normalizeFeedType,
isVideoFeedType,
isVideoFeedCamera,
isBrowserOverlayCamera,
safeNumber,
headingFromId,
quantize,
+75 -6
View File
@@ -12,20 +12,28 @@
* Cameras without an identified model are untouched — unknown never implies
* anything.
*
* Spec records are vendored verbatim from the CCTV Camera Database
* Specification fields are vendored from the CCTV Camera Database
* (https://github.com/ch-bas/cctv-camera-database, CC0-1.0) — an open dataset
* of 28,000+ camera models transcribed from manufacturer datasheets (84% with
* FOV, as of v2.26.0). This module vendors the records that the currently integrated public
* of 29,000+ camera models transcribed from manufacturer datasheets (76% with
* FOV, as of v2.29.0). This module vendors records that the integrated public
* catalogs publish hardware for — King County WA (Cohu, Bosch AUTODOME, Axis
* Q6135-LE), plus the Bosch AUTODOME and Axis PTZ/multisensor models that
* appear in Sarasota County FL and Sioux Falls SD open data; packs that
* appear in Sarasota County FL and Sioux Falls SD open data, plus the Bosch MIC
* PTZs for the City of Amsterdam camera register proposed in #251; packs that
* publish other hardware models can grow it, or vendor the full extract.
*
* Scope guardrail: records describe camera PRODUCTS (optics, resolution,
* night vision) — never endpoints, stream paths, or access/config data.
*/
/** Verbatim records from the dataset's model-enrichment extract (v2.26.0). */
/**
* Records from the dataset's model-enrichment extract: v2.26.0, plus the Bosch
* MIC records from v2.29.0 with titles shortened to model codes.
* A Bosch MIC order code ends in a colour letter (B, G, W; registries write
* `x`) on one shared datasheet. The colours are aliases of one record whose
* `model` leaves the letter out, so the HUD never names a variant the source
* did not.
*/
const RECORDS = [
{
id: 'axis-q6135-le',
@@ -264,6 +272,67 @@ const RECORDS = [
autotracking: true,
environment: ['outdoor'],
},
{
id: 'bosch-mic-7130-pb4',
brand: 'Bosch',
model: 'MIC-7130-P_4',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-mic-7130-pb4/',
aliases: [
'MIC IP starlight 7000 HD',
'MIC-7130-PB4',
'MIC-7130-PG4',
'MIC-7130-PW4',
'MIC-7130-Px4',
],
fov_deg: '2.1-59',
resolution: { mp: 1, w: 1280, h: 720, label: '720p' },
ptz: true,
autotracking: true,
varifocal: true,
environment: ['outdoor'],
},
{
id: 'bosch-mic-7502-z30b',
brand: 'Bosch',
model: 'MIC-7502-Z30',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-mic-7502-z30b/',
aliases: [
'MIC-7502-Z30B',
'MIC-7502-Z30G',
'MIC-7502-Z30W',
'MIC-7502-Z30x',
],
fov_deg: '2.3-63.7',
resolution: { mp: 2.13, w: 1920, h: 1080, label: '1080p' },
ptz: true,
autotracking: true,
varifocal: true,
night_vision: { type: 'color' },
environment: ['outdoor'],
},
{
id: 'bosch-mic-7522-z30b',
brand: 'Bosch',
model: 'MIC-7522-Z30',
type: 'ptz',
url: 'https://www.cctv-database.com/camera/bosch-mic-7522-z30b/',
aliases: [
'MIC-7522-Z30B',
'MIC-7522-Z30G',
'MIC-7522-Z30W',
'MIC-7522-Z30x',
],
fov_deg: '2.1-58.3',
// i18n-ignore: datasheet label
resolution: { mp: 2, w: 1920, h: 1080, label: '1080p HD' },
ptz: true,
varifocal: true,
night_vision: { type: 'color' },
environment: ['outdoor'],
ndaa_compliant: true,
},
{
id: 'cohu-3920-idome',
brand: 'Cohu',
@@ -431,7 +500,7 @@ const NAME_INDEX = RECORDS.flatMap((record) => {
* guesses).
* @param {string} model - Hardware model as named by a source pack or seed.
* @param {string} [manufacturer] - The source's manufacturer, when published.
* @returns {Object|null} The verbatim spec record, or null when unknown.
* @returns {Object|null} The matched spec record, or null when unknown.
*/
export function lookupModelSpec(model, manufacturer) {
const query = words(model).map(stripVariantSuffix);
+89
View File
@@ -245,6 +245,95 @@ test('King County snapshot model strings still resolve', () => {
);
});
test('Amsterdam camera register model strings resolve', () => {
// The register writes the Bosch MIC colour letter as `x`.
assert.equal(
lookupModelSpec('Bosch MIC-7522-Z30x')?.id,
'bosch-mic-7522-z30b',
);
assert.equal(
lookupModelSpec('Bosch MIC-7502-Z30x')?.id,
'bosch-mic-7502-z30b',
);
assert.equal(lookupModelSpec('Bosch MIC-7130-Px4')?.id, 'bosch-mic-7130-pb4');
assert.equal(lookupModelSpec('MIC-7522-Z30W')?.id, 'bosch-mic-7522-z30b');
// Its ANPR units are not in the table: unknown, never a guess.
assert.equal(lookupModelSpec('CSG-8800'), null);
// The MIC and AUTODOME starlight 7000 HD (code-less names, so the brand
// is needed) stay apart.
assert.equal(
lookupModelSpec('MIC IP starlight 7000 HD', 'Bosch')?.id,
'bosch-mic-7130-pb4',
);
assert.equal(
lookupModelSpec('AUTODOME IP starlight 7000 HD', 'Bosch')?.id,
'bosch-autodome-ip-starlight-7000-hd',
);
// The MIC datasheets state FOV without an axis, so no horizontal range.
assert.equal(horizontalFovRangeDeg(lookupModelSpec('MIC-7522-Z30B')), null);
});
test('Bosch MIC colour aliases resolve without accepting unknown variants', () => {
for (const [pattern, id] of [
['MIC-7130-P?4', 'bosch-mic-7130-pb4'],
['MIC-7502-Z30?', 'bosch-mic-7502-z30b'],
['MIC-7522-Z30?', 'bosch-mic-7522-z30b'],
]) {
for (const colour of ['B', 'G', 'W', 'x']) {
const model = pattern.replace('?', colour);
assert.equal(lookupModelSpec(model)?.id, id, model);
assert.equal(lookupModelSpec(`bosch ${model.toLowerCase()}`)?.id, id);
assert.equal(lookupModelSpec(model, 'Bosch')?.id, id);
assert.equal(lookupModelSpec(model, 'Axis'), null);
assert.equal(lookupModelSpec(`${model}-UNKNOWN`), null);
}
assert.equal(lookupModelSpec(pattern.replace('?', 'R')), null);
}
});
test('Bosch MIC HUD summary never names a colour the source did not', () => {
assert.equal(
specSummary(lookupModelSpec('MIC-7522-Z30W')),
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
);
assert.equal(
specSummary(lookupModelSpec('Bosch MIC-7522-Z30x')),
'Bosch MIC-7522-Z30 · 1080p HD · COLOR · PTZ',
);
for (const pattern of ['MIC-7130-P?4', 'MIC-7502-Z30?', 'MIC-7522-Z30?']) {
for (const colour of ['B', 'G', 'W', 'x']) {
const spec = lookupModelSpec(pattern.replace('?', colour));
const summary = specSummary(spec);
for (const other of ['B', 'G', 'W', 'x']) {
assert.ok(!summary.includes(pattern.replace('?', other)), summary);
}
}
}
});
test('Bosch MIC catalog enrichment preserves estimated and explicit optics', () => {
for (const model of [
'Bosch MIC-7130-Px4',
'Bosch MIC-7502-Z30x',
'Bosch MIC-7522-Z30x',
]) {
for (const pose of [{}, { fovDeg: 44 }, { poseSource: 'curated' }]) {
const [camera] = browserCatalog().buildCatalogFromSources([
{ id: 'amsterdam-mic', lat: 52.37, lon: 4.9, model, ...pose },
]);
assert.ok(camera.spec, model);
assert.equal(camera.fovDeg, pose.fovDeg ?? 74, model);
assert.equal(camera.fovSource, undefined);
assert.equal(camera.specFovMinDeg, undefined);
assert.equal(camera.specFovMaxDeg, undefined);
assert.equal(horizontalFovRangeDeg(camera.spec), null);
assert.equal(fixedHorizontalFovDeg(camera.spec), null);
assert.equal(specFovCapabilityToken(camera), null);
assert.match(specSummary(camera.spec), /^Bosch MIC-.* · PTZ$/);
}
}
});
test('catalog never overwrites an explicit FOV or a curated pose', () => {
const [explicit, curated, cohu, pelco] =
browserCatalog().buildCatalogFromSources([
+69 -23
View File
@@ -1,5 +1,6 @@
import * as Cesium from 'cesium';
import { isFollowing } from '../../data/followed.js';
import { CCTV_FOCUS_RESULT } from './policy.js';
import { cameraOf } from '../../render/rendererOf.js';
export function createNavigation({
state: layerState,
@@ -8,15 +9,20 @@ export function createNavigation({
source,
}) {
/**
* Finds the camera closest to the Cesium viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
* Nearest catalog camera to a WGS84 point.
* @param {number} lat Latitude in degrees.
* @param {number} lon Longitude in degrees.
* @returns {string|null} Camera ID, or null (invalid point, empty catalog).
*/
function nearestCameraIdToViewer() {
const carto = layerState._viewer?.camera?.positionCartographic;
if (!carto || !layerState._records.length) return null;
const lat = Cesium.Math.toDegrees(carto.latitude);
const lon = Cesium.Math.toDegrees(carto.longitude);
function nearestCameraIdToPoint(lat, lon) {
if (
!Number.isFinite(lat) ||
!Number.isFinite(lon) ||
Math.abs(lat) > 90 ||
Math.abs(lon) > 180 ||
!layerState._records.length
)
return null;
let best = null;
for (const record of layerState._records) {
@@ -34,9 +40,49 @@ export function createNavigation({
}
/**
* Flies the Cesium viewer camera to frame the specified CCTV camera,
* Finds the camera closest to the viewer's current position.
* @returns {string|null} Camera ID of the nearest camera, or null.
*/
function nearestCameraIdToViewer() {
const pose = parts.model.eyePose();
if (!pose) return null;
return nearestCameraIdToPoint(pose.lat, pose.lon);
}
/**
* The camera the layer opens on when none is selected: the one nearest the
* viewer, or the first record when the viewer has no position yet.
* @returns {string|null} Camera ID, or null when the catalog is empty.
*/
function openingCameraId() {
return (
nearestCameraIdToViewer() || layerState._records[0]?.camera?.id || null
);
}
/**
* After a settled move, moves the opening camera to the one nearest the
* view, until someone chooses a camera. A shared view's flight lands after
* enable() picked from the startup view.
* @returns {boolean} True when the active camera changed.
*/
function reopenNearestCamera() {
if (!layerState._openingCameraProvisional || !layerState._enabled)
return false;
const nearest = nearestCameraIdToViewer();
if (!nearest || nearest === layerState._activeCameraId) return false;
parts.selection.setActiveCamera(nearest);
// setActiveCamera ends the opening pick; this is still that pick.
layerState._openingCameraProvisional = true;
return true;
}
/**
* Flies the viewer's camera to frame the specified CCTV camera,
* looking along its heading from above.
* @param {Cesium.Viewer|null} viewer Cesium viewer that owns the camera.
* @param {object|null} viewer The viewer that owns the camera.
* @param {Object|null} record CCTV camera runtime record.
* @param {number} [duration=2.2] - Flight duration in seconds.
* @returns {'focused'|'no-active-camera'|'tracking-holds-view'|'cockpit-active'} Focus result.
@@ -51,7 +97,7 @@ export function createNavigation({
console.debug('[Data:CCTV] focus ignored while cockpit owns the camera');
return CCTV_FOCUS_RESULT.COCKPIT_ACTIVE;
}
if (viewer.trackedEntity) {
if (isFollowing(viewer)) {
console.debug(
'[Data:CCTV] focus ignored while a tracked entity owns the camera',
);
@@ -59,19 +105,16 @@ export function createNavigation({
}
const { camera } = record;
const range = Math.max(280, camera.rangeM * 1.18);
viewer.camera.flyToBoundingSphere(
new Cesium.BoundingSphere(
record.position,
Math.max(40, camera.rangeM * 0.36),
),
cameraOf(viewer).flyToBounds(
{ center: record.position, radius: Math.max(40, camera.rangeM * 0.36) },
{
offset: new Cesium.HeadingPitchRange(
parts.model.toRad(camera.headingDeg),
parts.model.toRad(-22),
offset: {
heading: parts.model.toRad(camera.headingDeg),
pitch: parts.model.toRad(-22),
range,
),
duration: Math.max(0.2, duration || 0),
easingFunction: Cesium.EasingFunction.CUBIC_IN_OUT,
},
durationS: Math.max(0.2, duration || 0),
easing: 'cubicInOut',
},
);
return CCTV_FOCUS_RESULT.FOCUSED;
@@ -148,7 +191,10 @@ export function createNavigation({
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
}
return {
nearestCameraIdToPoint,
nearestCameraIdToViewer,
openingCameraId,
reopenNearestCamera,
focusCctvRecord,
focusCamera,
maybeAutoHop,
+53
View File
@@ -0,0 +1,53 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { createNavigation } from './navigation.js';
function fixture() {
const records = [
{ camera: { id: 'west', lat: 40, lon: -120 } },
{ camera: { id: 'east', lat: 40, lon: -100 } },
];
const state = { _records: records };
const parts = {
model: {
eyePose: () => ({ lat: 40, lon: -101 }),
haversineKm(lat1, lon1, lat2, lon2) {
return Math.hypot(lat1 - lat2, lon1 - lon2);
},
},
};
const navigation = createNavigation({
state,
services: {},
parts,
source: {},
});
return { navigation };
}
test('nearest camera can be resolved from an explicit WGS84 target', () => {
const { navigation } = fixture();
assert.equal(navigation.nearestCameraIdToPoint(40, -119), 'west');
assert.equal(navigation.nearestCameraIdToPoint(40, -101), 'east');
});
test('viewer-nearest delegates to the same target-point owner', () => {
const { navigation } = fixture();
assert.equal(navigation.nearestCameraIdToViewer(), 'east');
});
test('invalid target coordinates fail closed', () => {
const { navigation } = fixture();
for (const [lat, lon] of [
[NaN, 0],
[null, 0],
[0, Infinity],
[90.00001, 0],
[-90.00001, 0],
[0, 180.00001],
[0, -180.00001],
]) {
assert.equal(navigation.nearestCameraIdToPoint(lat, lon), null);
}
});
+59 -36
View File
@@ -1,13 +1,7 @@
export {
FRAME_ENDPOINT,
SOURCE_ENDPOINT,
HEALTH_ENDPOINT,
MEDIA_ENDPOINT,
ACTIVE_FRAME_REFRESH_MS,
} from './sourcePolicy.js';
import * as Cesium from 'cesium';
export { ACTIVE_FRAME_REFRESH_MS } from './sourcePolicy.js';
import { CCTV_CARD_FETCH_BURST_SPACING_MS } from '../../data/cctvCards.js';
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { hexColor } from '../../render/color.js';
// ---------------------------------------------------------------------------
// API endpoints
@@ -66,6 +60,45 @@ 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.
export const VIEW_CELL_PX = 40;
export const VIEW_MIN_CELL_M = 60;
// 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.
export const VIEW_ICON_MARGIN = 0.5;
// While the camera moves, the view pass reruns at most this often.
export const VIEW_MOTION_REFRESH_MS = 250;
// A motion tick is skipped unless the camera moved this fraction of its
// ellipsoid height, or turned this many degrees, since the last pass.
export const VIEW_MOTION_MIN_MOVE_FRACTION = 0.01;
export const VIEW_MOTION_MIN_TURN_DEG = 0.5;
// Motion passes are spaced at least this many times the last pass's cost, so
// a large catalog spends at most about a tenth of a long move on them.
export const VIEW_MOTION_COST_FACTOR = 10;
// A view camera's geometry is attempted at most this many times per surface
// regime (a cold elevation cell can leave the first attempt unresolved); the
// retry runs this long after the drain that left it unresolved.
export const VIEW_GEOMETRY_ATTEMPTS = 2;
export const VIEW_GEOMETRY_RETRY_MS = 1500;
// Throttle for placeholder repaints — the projection RAF loop must not
// re-fill a 1080p canvas on every frame while a feed image is still loading.
@@ -90,9 +123,6 @@ export const CCTV_CALIBRATION_STORAGE_KEY_V2 =
export const PROJECTION_TEXTURE_SWAP_MS = 1000;
export const PROJECTION_VERT_ASPECT =
PROJECTION_CANVAS_WIDTH / PROJECTION_CANVAS_HEIGHT;
// V2 frustum geometry (design §2a/§6): the far-cap center + corners never sink
// below groundAlt + this clearance, so a fabricated pitch (-24°) cannot bury
// the monitor plane in the 3D tiles. Exported for the unit suite.
@@ -149,10 +179,14 @@ export const DEFAULT_CAMERA_CALIBRATION = Object.freeze({
heightM: 0,
});
/** Base64-encoded SVG camera icon for billboard rendering. */
/**
* 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.
*/
export const CAMERA_ICON = (() => {
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="36" height="36" viewBox="0 0 36 36">
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"/>
@@ -404,44 +438,33 @@ export const CAMERA_SEEDS = [
];
// ---------------------------------------------------------------------------
// Visual style constants
// Visual style constants: renderer colours, [r, g, b, a] in 0..1
// ---------------------------------------------------------------------------
export const IDLE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.88);
export const IDLE_CAMERA_COLOR = hexColor('#6be8ff', 0.88);
export const ACTIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#ffd97a').withAlpha(0.95);
export const ACTIVE_CAMERA_COLOR = hexColor('#ffd97a', 0.95);
export const LIVE_CAMERA_COLOR =
Cesium.Color.fromCssColorString('#b48cff').withAlpha(0.88);
export const LIVE_CAMERA_COLOR = hexColor('#b48cff', 0.88);
export const IDLE_COVERAGE_COLOR =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.24);
export const IDLE_COVERAGE_COLOR = hexColor('#2fe0ff', 0.24);
export const IDLE_COVERAGE_CENTER_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.2);
export const IDLE_COVERAGE_CENTER_MUTED = hexColor('#2fe0ff', 0.2);
export const IDLE_COVERAGE_EDGE_MUTED =
Cesium.Color.fromCssColorString('#2fe0ff').withAlpha(0.18);
export const IDLE_COVERAGE_EDGE_MUTED = hexColor('#2fe0ff', 0.18);
export const ACTIVE_COVERAGE_EDGE =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.58);
export const ACTIVE_COVERAGE_EDGE = hexColor('#8dff87', 0.58);
export const ACTIVE_COVERAGE_CENTER =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.82);
export const ACTIVE_COVERAGE_CENTER = hexColor('#d7ff8d', 0.82);
// H6: dimmer depth-fail materials let the active frustum wireframe read
// through buildings while in monitor fallback mode.
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL =
Cesium.Color.fromCssColorString('#8dff87').withAlpha(0.18);
export const ACTIVE_COVERAGE_EDGE_DEPTHFAIL = hexColor('#8dff87', 0.18);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL =
Cesium.Color.fromCssColorString('#d7ff8d').withAlpha(0.26);
export const ACTIVE_COVERAGE_CENTER_DEPTHFAIL = hexColor('#d7ff8d', 0.26);
export const PLANE_OUTLINE_COLOR =
Cesium.Color.fromCssColorString('#6be8ff').withAlpha(0.55);
export const PLANE_OUTLINE_COLOR = hexColor('#6be8ff', 0.55);
/**
* Card budget while the staggered geometry drain is running — the raised
@@ -0,0 +1,58 @@
// The CCTV HUD summary shows the CAL badge, source kind and view band in the
// UI language; English keeps its codes, and unknown source codes stay codes.
import test from 'node:test';
import assert from 'node:assert/strict';
import { setLocale } from '../../i18n/index.js';
import { createPresentation } from './presentation.js';
function summary(sourceKind) {
const camera = {
id: 'c1',
city: 'Austin',
name: 'Cam',
rangeM: 100,
fovDeg: 60,
feedType: 'image',
};
const record = { camera };
const presentation = createPresentation({
state: {
_records: [record],
_healthById: new Map(sourceKind ? [['c1', { sourceKind }]] : []),
_showProjection: false,
_coverageMode: 'sector',
},
services: {},
parts: {
selection: { getActiveRecord: () => record },
model: {
sectorAreaKm2: () => 1,
currentViewContext: () => 'street:1:2',
},
geometry: { coverageNeighborCount: () => 0 },
calibration: { deriveCalBadge: () => 'raw-prior' },
},
source: {},
});
return presentation.buildSummaryText();
}
test('en: CAL, SRC and CONTEXT keep their English codes', () => {
setLocale('en');
assert.match(summary('upstream'), /CAL RAW PRIOR · SRC UPSTREAM/);
assert.match(summary(null), /SRC IMAGE · STREET CONTEXT/);
assert.match(summary('upstream-image'), /SRC UPSTREAM-IMAGE/);
});
test('fr: CAL, SRC and CONTEXT values are translated', () => {
setLocale('fr');
try {
assert.match(
summary('upstream'),
/CAL ESTIM\. INITIALE · SRC AMONT · CONTEXTE RUE/,
);
assert.match(summary('upstream-image'), /SRC UPSTREAM-IMAGE/);
} finally {
setLocale('en');
}
});
+122 -20
View File
@@ -1,5 +1,5 @@
import { CCTV_AMBIENT_CARD_MAX } from '../../data/cctvLod.js';
import { t } from '../../i18n/index.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 {
@@ -8,6 +8,59 @@ import {
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,
@@ -44,6 +97,8 @@ export function createPresentation({
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(),
@@ -72,17 +127,13 @@ export function createPresentation({
: t('ISOLATED VIEW'),
layerState._showProjection ? t('PROJ MONITOR') : t('PROJ OFF'),
layerState._coverageMode === 'viewshed' ? t('VIEWSHED') : null,
t('CAL {value}', {
value: calBadge.replace('-', ' ').toUpperCase(),
t('CAL {value}', { value: summaryCalLabel(calBadge) }),
t('SRC {value}', {
value: summarySourceLabel(
health?.sourceKind || active.camera.feedType || 'image',
),
}),
health?.sourceKind
? t('SRC {value}', {
value: String(health.sourceKind).toUpperCase(),
})
: t('SRC {value}', {
value: String(active.camera.feedType || 'image').toUpperCase(),
}),
t('{value} CONTEXT', { value: viewBand.toUpperCase() }),
t('{value} CONTEXT', { value: summaryViewBandLabel(viewBand) }),
// Identified hardware: append the model's datasheet specs + attribution.
active.camera.spec
? t('{spec} · SPECS: CCTV-DATABASE.COM', {
@@ -91,6 +142,7 @@ export function createPresentation({
: null,
]
.filter(Boolean)
.map(isolate)
.join(' · ');
}
@@ -108,9 +160,14 @@ export function createPresentation({
const camera = record.camera;
const health = layerState._healthById.get(camera.id) || null;
const isActive = camera.id === resolvedActiveId;
const refreshMs = isActive
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,
@@ -140,13 +197,18 @@ export function createPresentation({
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.isVideoFeedType(camera.feedType) &&
parts.model.isVideoFeedCamera(camera) &&
record.projection?.mode !== 'image',
sourceKind:
health?.sourceKind ||
camera.sourceKind ||
(camera.feedConfigured ? 'configured' : 'seed'),
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 || '',
@@ -224,15 +286,55 @@ export function createPresentation({
hoverId: layerState._hoverCardId,
},
activeCameraId: activeId,
activeCameraReselection: layerState._activeCameraReselection,
activeCamera: active ? getPublicCameraState(active, activeId) : null,
cameras: layerState._records.map((record) =>
getPublicCameraState(record, activeId),
),
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 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.
* @returns {{id: string, city: string, name: string}[]}
*/
function cameraIndex() {
const view = layerState._viewRecords;
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() {
+38
View File
@@ -0,0 +1,38 @@
// The CCTV summary line names the CAL badge, the source kind and the view
// band in the page language; unknown codes stay as uppercase codes.
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale } from '../../i18n/index.js';
import {
summaryCalLabel,
summarySourceLabel,
summaryViewBandLabel,
} from './presentation.js';
function inLocale(locale, run) {
setLocale(locale);
try {
return run();
} finally {
setLocale('en');
}
}
test('English keeps the summary codes', () => {
assert.equal(summaryCalLabel('raw-prior'), 'RAW PRIOR');
assert.equal(summarySourceLabel('image'), 'IMAGE');
assert.equal(summarySourceLabel('hls'), 'HLS');
assert.equal(summaryViewBandLabel('street'), 'STREET');
assert.equal(summaryViewBandLabel('none'), 'NONE');
});
test('Portuguese summary values are translated', () => {
inLocale('pt', () => {
assert.equal(summaryCalLabel('raw-prior'), 'ESTIMATIVA BRUTA');
assert.equal(summaryCalLabel('calibrated'), 'CALIBRADA');
assert.equal(summarySourceLabel('IMAGE'), 'IMAGEM');
assert.equal(summarySourceLabel('mjpeg'), 'MJPEG');
assert.equal(summaryViewBandLabel('street'), 'RUA');
assert.equal(summaryViewBandLabel('city'), 'CIDADE');
});
});
+93 -63
View File
@@ -1,5 +1,4 @@
import { attachCctvVideo } from './videoPlayback.js';
import * as Cesium from 'cesium';
import {
CCTV_PROJECTION_OVERLAY_SOURCE_ID,
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
@@ -8,6 +7,25 @@ import {
PROJECTION_CANVAS_HEIGHT,
} from './policy.js';
/** The monitor plane's alpha over its frame, as its image material had it. */
const PLANE_ALPHA = 0.95;
/** A plain white image, for a plane with no media (tests). */
const WHITE_IMAGE =
'data:image/svg+xml,' +
encodeURIComponent(
'<svg xmlns="http://www.w3.org/2000/svg" width="1" height="1">' +
'<rect width="1" height="1" fill="#fff"/></svg>',
);
/** Copy a position's coordinates into `out`. */
function copyPosition(from, out) {
out.x = from.x;
out.y = from.y;
out.z = from.z;
return out;
}
export function createProjection({
state: layerState,
services,
@@ -18,7 +36,7 @@ export function createProjection({
/**
* Build the protected label associated with one active monitor plane.
* @param {{cameraId: string, name: string, position: Cesium.Cartesian3|Function}} input
* @param {{cameraId: string, name: string, position: object|Function}} input
* @returns {Object} Shared-host presentation entry.
*/
@@ -46,7 +64,7 @@ export function createProjection({
}
/**
* Re-derives the monitor plane entity's placement (position, orientation,
* Re-derives the monitor plane's placement (position, orientation,
* dimensions) + label from the record's current frustum geometry, so the plane
* always caps the wireframe exactly (corner rays terminate on its corners).
* No-op when the record has no plane runtime (idle neighbors have no plane).
@@ -55,7 +73,8 @@ export function createProjection({
function updatePlanePlacement(record) {
const runtime = record?.projection;
if (!runtime?.planeEntity) return;
const plane = runtime?.plane;
if (!plane) return;
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -64,21 +83,33 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeEntity.position = positions.capCenter;
runtime.planeEntity.orientation = parts.model.planeOrientationFor(
record.camera,
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
placePlane(plane, record.camera, geometry, positions);
if (runtime.labelPosition)
copyPosition(positions.label, runtime.labelPosition);
parts.drawSets.writePlane(plane);
}
/** Pose a plane handle on the frustum's far cap. */
function placePlane(plane, camera, geometry, positions) {
plane.center = positions.capCenter;
plane.orientation = parts.model.planeOrientationFor(
camera,
positions.capCenter,
);
if (runtime.planeEntity.plane) {
runtime.planeEntity.plane.dimensions = new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
);
}
if (runtime.labelPosition) {
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
}
plane.size = [geometry.halfW * 2, geometry.halfH * 2];
}
/**
* Give the monitor plane another image: a canvas, or the video element.
* @param {Object} runtime - Projection runtime.
* @param {{canvas: HTMLCanvasElement}|{video: HTMLVideoElement}} source
*/
function setPlaneSource(runtime, source) {
runtime.planeSource = source;
if (!runtime.plane) return;
runtime.plane.source = source;
parts.drawSets.writePlane(runtime.plane);
}
/**
@@ -102,7 +133,10 @@ export function createProjection({
function setPlaneVisible(runtime, visible) {
if (!runtime) return;
if (runtime.planeEntity) runtime.planeEntity.show = !!visible;
if (runtime.plane && runtime.plane.show !== !!visible) {
runtime.plane.show = !!visible;
parts.drawSets.writePlane(runtime.plane);
}
if (visible && runtime.overlayEntry && runtime.cameraId) {
if (layerState._projectionOverlayOwnerId !== runtime.cameraId) {
layerState._cctvOverlayHost.setEntries(
@@ -121,38 +155,34 @@ export function createProjection({
}
}
/** Create the native monitor plane plus its cached host-label presentation. */
/** A plain white plane image, for a plane with no media (tests). */
function plainPlaneSource() {
return { image: WHITE_IMAGE };
}
/** Create the monitor plane plus its cached host-label presentation. */
function createProjectionPlane(record, runtime, geometry, positions) {
runtime.labelPosition ||= new Cesium.Cartesian3();
Cesium.Cartesian3.clone(positions.label, runtime.labelPosition);
runtime.labelPosition ||= { x: 0, y: 0, z: 0 };
copyPosition(positions.label, runtime.labelPosition);
runtime.cameraId = String(record.camera.id);
runtime.overlayEntry = createCctvProjectionOverlayEntry({
cameraId: runtime.cameraId,
name: record.camera.name,
position: () => runtime.labelPosition,
});
runtime.planeEntity = layerState._viewer.entities.add({
const plane = {
id: `cctv-${record.camera.id}-plane`,
properties: { cctvCameraId: record.camera.id },
cameraId: record.camera.id,
source: runtime.planeSource || plainPlaneSource(),
alpha: PLANE_ALPHA,
outline: { color: PLANE_OUTLINE_COLOR, widthPx: 1 },
show: false,
position: positions.capCenter,
orientation: parts.model.planeOrientationFor(
record.camera,
positions.capCenter,
),
plane: {
plane: new Cesium.Plane(Cesium.Cartesian3.UNIT_Z, 0.0),
dimensions: new Cesium.Cartesian2(
geometry.halfW * 2,
geometry.halfH * 2,
),
material: runtime.planeMaterial,
outline: true,
outlineColor: PLANE_OUTLINE_COLOR,
},
});
return runtime.planeEntity;
};
placePlane(plane, record.camera, geometry, positions);
runtime.plane = plane;
parts.drawSets.writePlane(plane);
return plane;
}
/**
@@ -171,6 +201,9 @@ export function createProjection({
function createProjectionRuntime(record) {
if (!layerState._viewer) return null;
// Québec 511 denies CORS pixel access; Québec map previews are native DOM
// videos positioned over the globe, never Cesium video textures.
if (parts.model.isBrowserOverlayCamera(record.camera)) return null;
const canvas = document.createElement('canvas');
canvas.width = PROJECTION_CANVAS_WIDTH;
canvas.height = PROJECTION_CANVAS_HEIGHT;
@@ -184,11 +217,11 @@ export function createProjection({
ctx,
image: null,
video: null,
planeEntity: null,
plane: null,
cameraId: String(record.camera.id),
labelPosition: new Cesium.Cartesian3(),
labelPosition: { x: 0, y: 0, z: 0 },
overlayEntry: null,
planeMaterial: null,
planeSource: { canvas },
buffers: null,
bufferIndex: 0,
lastTextureSwapAt: 0,
@@ -219,16 +252,17 @@ export function createProjection({
video.playsInline = true;
video.crossOrigin = 'anonymous';
video.preload = 'auto';
// Cesium sizes the video texture from the element's width/height
// attributes at first upload. Set them from the real stream dimensions
// and rebind on any resolution change (camera switch, adaptive source).
// The plane shows the video once it knows its size (the element's
// width/height follow the real stream dimensions); the renderer reads
// it at a new size on any later resolution change (camera switch,
// adaptive source).
const bindVideoTexture = () => {
if (runtime.video !== video || !runtime.planeMaterial) return;
if (runtime.video !== video || runtime.disposed) return;
if (!(video.videoWidth > 0 && video.videoHeight > 0)) return;
video.width = video.videoWidth;
video.height = video.videoHeight;
runtime.planeMaterial.image = runtime.canvas;
runtime.planeMaterial.image = video;
if (runtime.planeSource?.video !== video)
setPlaneSource(runtime, { video });
};
video.addEventListener('loadedmetadata', bindVideoTexture);
video.addEventListener('resize', bindVideoTexture);
@@ -253,7 +287,7 @@ export function createProjection({
runtime.imageLoading = false;
runtime.imageReady = false;
};
runtime.planeMaterial.image = runtime.canvas;
setPlaneSource(runtime, { canvas: runtime.canvas });
parts.frames.refreshProjectionImage(record, true);
parts.presentation.notifyListeners();
},
@@ -276,9 +310,8 @@ export function createProjection({
}
// Monitor plane = the frustum's far cap: video feeds bind the video element
// directly (Cesium updates video-backed entity materials per frame); image
// feeds start on the placeholder canvas and switch to double-buffer swaps
// at <=1Hz.
// directly (the renderer reads it every frame); image feeds start on the
// placeholder canvas and switch to double-buffer swaps at <=1Hz.
const geometry =
record.frustumGeometry ||
parts.geometry.computeFrustumGeometry(
@@ -287,12 +320,7 @@ export function createProjection({
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
runtime.planeMaterial = new Cesium.ImageMaterialProperty({
image: canvas,
transparent: true,
color: Cesium.Color.WHITE.withAlpha(0.95),
});
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
createProjectionPlane(record, runtime, geometry, positions);
return runtime;
@@ -337,15 +365,15 @@ export function createProjection({
runtime.video.removeAttribute('src');
runtime.video.load();
}
if (runtime.planeEntity && layerState._viewer) {
layerState._viewer.entities.remove(runtime.planeEntity);
runtime.planeEntity = null;
if (runtime.plane) {
parts.drawSets.removePlane(runtime.plane);
runtime.plane = null;
}
if (layerState._projectionOverlayOwnerId === runtime.cameraId)
clearProjectionOverlay();
runtime.overlayEntry = null;
runtime.labelPosition = null;
runtime.planeMaterial = null;
runtime.planeSource = null;
}
function startProjectionLoop() {
@@ -427,6 +455,8 @@ export function createProjection({
updatePlanePlacement,
clearProjectionOverlay,
setPlaneVisible,
setPlaneSource,
plainPlaneSource,
createProjectionPlane,
createProjectionRuntime,
ensureProjectionRuntime,
File diff suppressed because it is too large. Load diff
+333 -28
View File
@@ -2,6 +2,7 @@
// 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.
// Teardown lets go of the icon set of the viewer that drew it.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { createRendering } from './rendering.js';
@@ -11,65 +12,369 @@ import {
LIVE_CAMERA_COLOR,
} from './policy.js';
import { isVideoFeedType } from '../../sources/cctvTypes.js';
import * as Cesium from 'cesium';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindRenderer } from '../../render/rendererOf.js';
const FOCUS_FACTOR = 0.5;
function assertFadedFrom(actual, base, label) {
assert.ok(actual, `${label}: color written`);
assert.deepEqual(
[actual.red, actual.green, actual.blue],
[base.red, base.green, base.blue],
`${label}: hue`,
);
assert.equal(actual.alpha, base.alpha * FOCUS_FACTOR, `${label}: alpha`);
function assertKeepsColor(icons, id, base, label) {
assert.deepEqual(icons.item(id).color, base, `${label}: base color kept`);
assert.equal(icons.focus(id), FOCUS_FACTOR, `${label}: focus`);
}
test('focus de-emphasis fades each icon from its own color', () => {
const record = (id, feedType) => ({
camera: { id, feedType },
// No position, so the pass skips screen projection; the focus stub below
// decides the factor on its own.
billboard: { show: true },
position: { x: 6378137, y: 0, z: 0 },
});
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 6378137 + 1000, y: 0, z: 0 } },
});
const projected = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
query: {
project: (position) => {
projected.push(position);
return { x: 10, y: 20 };
},
},
});
const state = {
_enabled: true,
_viewer: { scene: {}, camera: {} },
_viewer: viewer,
_records: [idleVideo, idleStill, activeVideo],
_activeCameraId: activeVideo.camera.id,
_activeFocusStyleCount: 0,
_lastFocusStyleAt: -Infinity,
};
const distances = [];
const focus = {
focusNowMs: (nowMs) => nowMs,
getFocusTarget: () => ({}),
focusPassIsNeeded: () => true,
advanceSpriteFocus: () => ({
factor: FOCUS_FACTOR,
active: true,
transitioning: false,
}),
advanceSpriteFocus: (meta, input) => {
distances.push(input.cameraDistance);
return { factor: FOCUS_FACTOR, active: true, transitioning: false };
},
focusAlphaNeedsWrite: () => true,
};
const { refreshCctvFocusStyles } = createRendering({
const { createCameraIcons, addCameraIcon, refreshCctvFocusStyles } =
createRendering({
state,
services: { focus },
parts: {
model: {
isVideoFeedType,
isVideoFeedCamera: (camera) =>
isVideoFeedType(camera.feedType) || Boolean(camera.browserMediaUrl),
},
},
source: {},
});
try {
const setId = createCameraIcons(viewer);
for (const r of state._records) addCameraIcon(r);
refreshCctvFocusStyles(1000);
const icons = state._icons;
assertKeepsColor(icons, 'idle-hls', LIVE_CAMERA_COLOR, 'idle video');
assertKeepsColor(icons, 'idle-image', IDLE_CAMERA_COLOR, 'idle still');
assertKeepsColor(icons, 'active-hls', ACTIVE_CAMERA_COLOR, 'active video');
assert.equal(state._activeFocusStyleCount, 3);
assert.equal(projected.length, 3, 'each shown icon is projected');
assert.deepEqual(distances, [1000, 1000, 1000], 'from the eye');
// What the set draws: depth-test-free, held at the mount, shrinking
// with distance as before.
const drawn = draw.set(setId).items.get('idle-hls');
assert.equal(drawn.disableDepthTest, Infinity);
assert.deepEqual(drawn.motion, { kind: 'hold' });
assert.deepEqual(drawn.pos, idleVideo.position);
assert.deepEqual(drawn.size, [24, 24]);
assert.deepEqual(drawn.scaleByDistance, {
near: 350,
nearValue: 1.25,
far: 4_000_000,
farValue: 0.42,
});
assert.equal(drawn.focus, FOCUS_FACTOR);
assert.equal(draw.set(setId).spec.horizonCull, true);
// Hidden until enable() has culled and thinned the cameras: the layer
// waits on its health check between drawing them and that pass.
assert.equal(draw.set(setId).show, false);
} finally {
unbind();
}
});
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 { createCameraIcons, destroyCameraIcons } = createRendering({
state,
services: { focus },
parts: { model: { isVideoFeedType } },
services: { focus: {} },
parts: {},
source: {},
});
try {
const old = createCameraIcons(first);
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);
refreshCctvFocusStyles(1000);
destroyCameraIcons();
assert.equal(two.draw.sets.get(current).disposed, true);
assert.equal(state._icons, null);
} finally {
one.unbind();
two.unbind();
}
});
assertFadedFrom(idleVideo.billboard.color, LIVE_CAMERA_COLOR, 'idle video');
assertFadedFrom(idleStill.billboard.color, IDLE_CAMERA_COLOR, 'idle still');
assertFadedFrom(
activeVideo.billboard.color,
ACTIVE_CAMERA_COLOR,
'active video',
test('the obstruction probe casts one ray through the query port', async () => {
const calls = [];
const viewer = {};
const unbind = bindRenderer(viewer, {
query: {
rayCast: async (ray, options) => {
calls.push({ ray, options });
return { x: 1, y: 2, z: 3 };
},
},
});
const state = { _viewer: viewer };
const rendering = createRendering({
state,
services: { focus: {} },
parts: {},
});
try {
assert.equal(rendering.canPickFromRay(), true);
const origin = { x: 0, y: 0, z: 0 };
const direction = { x: 1, y: 0, z: 0 };
assert.deepEqual(await rendering.obstructionHit(origin, direction), {
x: 1,
y: 2,
z: 3,
});
// The layer's own sets are not ground: the cast sees through them
// without naming them.
assert.deepEqual(calls, [
{ ray: { origin, direction }, options: { against: 'surface' } },
]);
} finally {
unbind();
}
state._viewer = {};
assert.equal(rendering.canPickFromRay(), false);
assert.equal(
await rendering.obstructionHit({ x: 0, y: 0, z: 0 }, { x: 1, y: 0, z: 0 }),
null,
);
assert.equal(state._activeFocusStyleCount, 3);
});
test('cards go only where the horizon lets the camera see', () => {
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 20_000_000);
const front = Cesium.Cartesian3.fromDegrees(0, 0);
const back = Cesium.Cartesian3.fromDegrees(180, 0);
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: eye.x, y: eye.y, z: eye.z } },
});
const unbind = bindRenderer(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 0, height: 600 },
query: { project: () => ({ x: 10, y: 20 }) },
});
try {
const view = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
}).cardView();
assert.equal(view.width, 800);
assert.equal(view.height, 600);
assert.deepEqual(view.screenOf(front), { x: 10, y: 20 });
assert.equal(view.screenOf(back), null);
} finally {
unbind();
}
});
test('the projection tiles are ready only when drawn and settled', () => {
const viewer = {};
let globeVisible = true;
let settled = true;
const unbind = bindRenderer(viewer, {
globe: {
isGlobeVisible: () => globeVisible,
isSettled: (kind) => kind === 'tiles' && settled,
},
});
try {
const { projectionTilesReady } = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
});
assert.equal(projectionTilesReady(), false, 'a globe stack hides them');
globeVisible = false;
assert.equal(projectionTilesReady(), true);
settled = false;
assert.equal(projectionTilesReady(), false, 'still streaming');
} finally {
unbind();
}
const bare = createRendering({
state: { _viewer: {} },
services: { focus: {} },
parts: {},
});
assert.equal(bare.projectionTilesReady(), false, 'no globe, no tiles');
});
test('a view pass writes only the icons it changes, in one write', () => {
const viewer = {};
const eye = Cesium.Cartesian3.fromDegrees(0, 0, 2000);
const down = Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(eye, new Cesium.Cartesian3()),
new Cesium.Cartesian3(),
);
const camera = fakeCameraPort({
pose: {
position: { x: eye.x, y: eye.y, z: eye.z },
direction: { x: down.x, y: down.y, z: down.z },
up: { x: 0, y: 0, z: 1 },
fovy: Math.PI / 3,
aspectRatio: 4 / 3,
near: 0.1,
far: 5e8,
},
});
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
});
const record = (id, lon) => {
const p = Cesium.Cartesian3.fromDegrees(lon, 0, 10);
return {
camera: { id, lat: 0, lon },
position: { x: p.x, y: p.y, z: p.z },
};
};
// One in view, one far off it.
const near = record('near', 0);
const far = record('far', 1);
const state = {
_enabled: true,
_viewer: viewer,
_records: [near, far],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
drawSets: { roleOfSet: () => null },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
const set = draw.set(setId);
const writes = set.writes;
assert.equal(rendering.refreshHorizonCulling(), true);
assert.equal(set.writes, writes + 1, 'one write for the pass');
assert.equal(set.items.get('near').show, true);
assert.equal(set.items.get('far').show, false);
assert.equal(rendering.refreshHorizonCulling(), false);
assert.equal(set.writes, writes + 1, 'an unchanged view writes nothing');
// Another layer on the same viewer draws its icons in a set of its own.
const other = createRendering({
state: { _viewer: viewer },
services: { focus: {} },
parts: {},
source: {},
});
const otherId = other.createCameraIcons(viewer);
assert.notEqual(otherId, setId);
assert.equal(
rendering.extractPickedCameraId({ set: otherId, id: 'near' }),
null,
"the other layer's icon is not this layer's camera",
);
} finally {
unbind();
}
});
test('a pose with no perspective field of view is projected by the renderer', () => {
const viewer = {};
const camera = fakeCameraPort({
pose: { position: { x: 7e6, y: 0, z: 0 }, fovy: undefined },
});
const asked = [];
const { draw, unbind } = bindFakeDraw(viewer, {
camera: camera.port,
canvas: { clientWidth: 800, clientHeight: 600 },
query: {
project: (position) => {
asked.push(position.y);
return position.y === 0 ? { x: 400, y: 300 } : null;
},
},
});
// On the ground under the eye, in cells of their own.
const record = (id, y) => ({
camera: { id, lat: 0, lon: y / 1000 },
position: { x: 6378137, y, z: 0 },
});
const state = {
_enabled: true,
_viewer: viewer,
_records: [record('on', 0), record('off', 1000)],
_viewRecords: [],
_healthById: new Map(),
_scratchViewScreen: { x: 0, y: 0 },
};
const rendering = createRendering({
state,
services: { focus: {} },
parts: {
model: { isVideoFeedType: () => false, isVideoFeedCamera: () => false },
},
source: {},
});
try {
const setId = rendering.createCameraIcons(viewer);
for (const r of state._records) rendering.addCameraIcon(r);
rendering.refreshHorizonCulling();
const set = draw.set(setId);
assert.deepEqual(asked.sort(), [0, 1000]);
assert.equal(set.items.get('on').show, true);
assert.equal(set.items.get('off').show, false);
} finally {
unbind();
}
});
test('focus release restores video hue and alpha after the style throttle', () => {
+38 -74
View File
@@ -1,8 +1,4 @@
import {
bindTrackingClickGesture,
isTrackingClickGesture,
} from '../../data/trackingClickGesture.js';
import * as Cesium from 'cesium';
import { isTrackingClickGesture } from '../../data/trackingClickGesture.js';
export function createSelection({
state: layerState,
@@ -34,24 +30,19 @@ export function createSelection({
}
/**
* Bind CCTV activation to clean taps while preserving the layer's hover-move
* callback on the shared Cesium handler. Drag-like and long-press gestures do
* Bind CCTV activation to clean taps. Drag-like and long-press gestures do
* not reach camera activation or focus dispatch.
* @param {Cesium.ScreenSpaceEventHandler|Object} handler - Input handler.
* @param {(click: Object) => void} onClick - Accepted CCTV click callback.
* @param {Object} [options] - Gesture test seams and optional onMouseMove hook.
* @returns {void}
* @param {import('../../input/dispatcher.js').InputDispatcher} input
* @param {(event: import('../../input/dispatcher.js').ClickEvent) => void} onClick
* Accepted CCTV click callback.
* @returns {() => void} Unsubscribe.
*/
function bindCctvWorldClickGesture(handler, onClick, options = {}) {
bindTrackingClickGesture(
handler,
(click, gesture) => {
if (!isTrackingClickGesture(gesture)) return;
onClick(click);
},
options,
);
function bindCctvWorldClickGesture(input, onClick) {
return input.onClick((event) => {
if (!isTrackingClickGesture(event.gesture)) return;
onClick(event);
});
}
/**
@@ -79,10 +70,17 @@ export function createSelection({
record,
)
) {
// Browser-only feeds have a separate player; a reselect retries it
// without re-running activation or touching the projection geometry.
if (parts.model.isBrowserOverlayCamera(record.camera)) {
layerState._activeCameraReselection += 1;
parts.presentation.notifyListeners();
}
return CCTV_ACTIVATION_RESULT.UNCHANGED;
}
layerState._activeCameraId = cameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = false;
// A real activation creates projection work — wake the self-stopping loop.
parts.projection.startProjectionLoop();
if (previousActiveRecord && previousActiveRecord !== record) {
@@ -112,12 +110,13 @@ export function createSelection({
layerState._geoQueue.splice(queueIdx, 1);
layerState._geoQueue.unshift(record);
}
// §9.1: one obstruction probe per activation, BEFORE the geometry pass so
// the range clamp lands in the same rewrite. A FIRST-EVER activation (no
// real ground sample yet) probes from the catalog-prior altitude — if that
// prior is off, the clamp is measured from a shifted origin, but a
// re-activation after the one-shot snap lands re-probes from real ground,
// so it self-corrects.
// §9.1: one obstruction probe per activation, cast before the geometry
// pass; its range clamp lands a microtask later, before the next frame,
// rewriting the geometry and asking again for the footprint ground. A
// FIRST-EVER activation (no real ground sample yet) probes from the
// catalog-prior altitude — if that prior is off, the clamp is measured
// from a shifted origin, but a re-activation after the one-shot snap
// lands re-probes from real ground, so it self-corrects.
parts.geometry.runActivationObstructionProbe(record);
// Coverage is activation-lazy even while the mode is OFF: the active
// camera's projection representation must be ready without materializing
@@ -141,6 +140,11 @@ export function createSelection({
void parts.ground.resolveFootprintGround(record);
record.activationDone = true;
parts.rendering.refreshCoverageStyles();
// The active camera's icon always shows; the previously active one
// competes for its cell again. Its coverage neighbours join the working
// set and are queued for grounding.
parts.rendering.refreshHorizonCulling();
parts.geometryQueue.enqueueViewGeometry();
// The newly active camera leaves the ambient ring (its monitor plane takes
// over); the freed slot re-fills on this same pass.
parts.cards.refreshAmbientCards();
@@ -164,6 +168,7 @@ export function createSelection({
if (!record) return false;
layerState._activeCameraId = null;
layerState._autoHopSuspended = true;
layerState._openingCameraProvisional = false;
record.activationDone = false;
parts.geometry.clearProbeClampOnDeactivation(record, (previous) => {
parts.geometry.applyFrustumGeometry(
@@ -171,7 +176,9 @@ export function createSelection({
parts.ground.groundAltFor(previous),
);
});
parts.rendering.refreshHorizonCulling();
parts.rendering.refreshCoverageStyles();
parts.geometryQueue.enqueueViewGeometry();
parts.cards.refreshAmbientCards();
layerState._gizmo?.refresh();
parts.presentation.notifyListeners();
@@ -199,57 +206,14 @@ export function createSelection({
}
/**
* Extracts a camera ID from a Cesium pick result by checking billboard IDs,
* primitive IDs, and entity cctvCameraId properties.
* @param {Object|null} picked - Result from scene.pick().
* @returns {string|null} Camera ID, or null if the pick is not a CCTV entity.
* The camera a scene pick result is, or null: read by the rendering part,
* which owns the scene objects the pick names.
* @param {Object|null} picked - Result from a scene pick.
* @returns {string|null}
*/
function extractPickedCameraId(picked) {
if (!picked) return null;
const entity = picked.id?.properties
? picked.id
: picked.primitive?.id?.properties
? picked.primitive.id
: null;
const maybeProp = entity?.properties?.cctvCameraId;
if (maybeProp) {
const value =
typeof maybeProp.getValue === 'function'
? maybeProp.getValue(Cesium.JulianDate.now())
: maybeProp;
const record =
typeof value === 'string' ? layerState._recordById.get(value) : null;
const ownsCoverageEntity = Boolean(
record?.coverageEntities?.includes(entity),
);
const ownsProjectionEntity =
record?.projection?.planeEntity === entity ||
layerState._projectionEntities.some(
(runtime) =>
runtime?.cameraId === value && runtime.planeEntity === entity,
);
if (record && (ownsCoverageEntity || ownsProjectionEntity)) return value;
}
// Camera billboard IDs are intentionally the upstream camera ID, so a
// sibling may legitimately use the same string. A bare ID match is not
// ownership proof: require this layer's billboard collection or the exact
// billboard stored on the record.
const directId =
typeof picked.id === 'string'
? picked.id
: typeof picked.primitive?.id === 'string'
? picked.primitive.id
: null;
const record =
directId === null ? null : layerState._recordById.get(directId);
if (!record) return null;
return picked.primitive === layerState._billboards ||
picked.primitive === record.billboard
? directId
: null;
return parts.rendering.extractPickedCameraId(picked);
}
return {
getActiveRecord,
+54
View File
@@ -0,0 +1,54 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { CCTV_ACTIVATION_RESULT } from '../../cctvFocusRequest.js';
import { createSelection } from './selection.js';
function makeSelection(sourceKind) {
const camera = { id: 'same-camera', sourceKind };
const record = { camera };
const state = {
_activeCameraId: camera.id,
_activeCameraReselection: 0,
_recordById: new Map([[camera.id, record]]),
};
let notifications = 0;
const selection = createSelection({
state,
services: {
activation: { CCTV_ACTIVATION_RESULT },
picking: { resolvePickId: () => null },
},
parts: {
model: {
cctvRecordNeedsActivation: () => false,
isBrowserOverlayCamera: (value) =>
String(value?.sourceKind || '').startsWith('quebec-'),
},
presentation: { notifyListeners: () => notifications++ },
},
source: {},
});
return { selection, state, notifications: () => notifications };
}
test('same-camera selection does not notify or mutate snapshot-feed state', () => {
const fixture = makeSelection('tripcheck-odot');
assert.equal(
fixture.selection.setActiveCamera('same-camera'),
CCTV_ACTIVATION_RESULT.UNCHANGED,
);
assert.equal(fixture.state._activeCameraReselection, 0);
assert.equal(fixture.notifications(), 0);
});
test('same-camera selection notifies browser-overlay feeds so playback can retry', () => {
const fixture = makeSelection('quebec-511-browser');
assert.equal(
fixture.selection.setActiveCamera('same-camera'),
CCTV_ACTIVATION_RESULT.UNCHANGED,
);
assert.equal(fixture.state._activeCameraReselection, 1);
assert.equal(fixture.notifications(), 1);
});
+5 -4
View File
@@ -1,6 +1,7 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { createCctvSource, createCctvLayer } from './index.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
const camera = {
id: 'pack/camera ?x',
@@ -110,7 +111,7 @@ test('camera construction is inert and destruction cancels a pending catalog and
setOverlayEntries: noop,
setOverlaySourceVisible: noop,
},
sprites: { registerSpriteCollection: noop },
sprites: {},
activation: {},
locations: {},
picking: { unregisterPickOwner: noop },
@@ -134,9 +135,9 @@ test('camera construction is inert and destruction cancels a pending catalog and
const a = createCctvLayer({ services, source });
const b = createCctvLayer({ services, source });
assert.equal(listeners.size, 0);
const viewer = {
scene: { primitives: { add: (value) => value, remove: () => true } },
};
const viewer = {};
const { unbind } = bindFakeDraw(viewer);
t.after(unbind);
const initializing = a.init(viewer);
assert.equal(listeners.size, 1);
assert.equal(signal.aborted, false);
-4
View File
@@ -1,9 +1,5 @@
export const FRAME_ENDPOINT = '/api/cctv/frame';
export const SOURCE_ENDPOINT = '/api/cctv/sources';
export const HEALTH_ENDPOINT = '/api/cctv/health';
export const MEDIA_ENDPOINT = '/api/cctv/media';
export const ACTIVE_FRAME_REFRESH_MS = 10000;
+72 -15
View File
@@ -1,5 +1,3 @@
import * as Cesium from 'cesium';
export function createState({ services }) {
const {
clearOverlaySource,
@@ -15,7 +13,8 @@ export function createState({ services }) {
layerState._viewer = null;
layerState._billboards = null;
/** The catalog's camera icons: the icon book over their draw set. */
layerState._icons = null;
layerState._records = [];
@@ -29,6 +28,10 @@ export function createState({ services }) {
layerState._activeCameraId = null;
// Advances when a user reselects the already-active camera. The geometry
// activation remains a no-op, but browser-only camera UI can retry playback.
layerState._activeCameraReselection = 0;
layerState._coverageMode = 'on';
// 'off' | 'on' (wireframes) | 'viewshed' (color-coded volumes)
@@ -36,6 +39,12 @@ export function createState({ services }) {
layerState._autoHop = false;
// True while the active camera is the one enable() opened on and nobody has
// chosen a camera since: each settled move then re-picks the one nearest
// the view, so a share flight that lands after enable still opens nearby.
layerState._openingCameraProvisional = false;
// An explicit empty-space deselect keeps AUTO HOP configured but prevents its
// timer from silently choosing a replacement. A later explicit activation or
// AUTO HOP toggle-on releases the hold.
@@ -48,7 +57,7 @@ export function createState({ services }) {
layerState._lastViewContext = '';
layerState._clickHandler = null;
layerState._clickSubscription = null;
layerState._count = 0;
@@ -74,7 +83,61 @@ export function createState({ services }) {
layerState._activeFocusStyleCount = 0;
layerState._scratchFocusScreen = new Cesium.Cartesian2();
// The view pass's screen-point scratch: its projection writes only x and y.
layerState._scratchViewScreen = { x: 0, y: 0 };
// Counts view passes; a record shown by the latest pass carries its number.
layerState._viewPassId = 0;
// Records whose icons the last view pass showed (see refreshHorizonCulling):
// geometry refinement, the tiles-ready completion pass and ambient cards
// work over these, not the whole catalog.
layerState._viewRecords = [];
// Coverage ids refreshCoverageStyles last drew: part of the geometry
// working set even when their icons are thinned out.
layerState._coverageVisibleIds = new Set();
// View pass triggers besides camera settle: an interval while the camera
// moves, and a canvas resize observer.
layerState._viewMotionTimer = 0;
layerState._viewResizeObserver = null;
layerState._viewResizeCanvas = null;
// The camera port the moveStart/moveEnd listeners are on.
layerState._viewListenerCamera = 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.
layerState._viewUnpublished = false;
layerState._viewPose = null;
// { at, ms } — when the last motion pass ran and what it cost.
layerState._viewMotionPass = null;
// Retries the view geometry a drain left unresolved, once cells warm.
layerState._viewGeometryRetryTimer = 0;
// { key, count } — the active camera's coverage-overlap count, which the
// summary reads on every notification.
layerState._neighborCountCache = null;
// { view, active, list } — the camera picker's index uiState publishes,
// rebuilt only when the view pass or the active camera changes.
layerState._cameraIndexCache = null;
// Staggered geometry-load queue state (see startGeometryLoadQueue).
@@ -107,16 +170,9 @@ export function createState({ services }) {
layerState._lastTransientNotifyAt = 0;
// Cached handle on the active Google Photorealistic 3D Tileset, discovered
// lazily from scene.primitives. Shared mesh-floor sampling is gated on its
// tilesLoaded flag so a coarse-LOD miss is never baked in. Cleared when the
// tileset is destroyed / the layer tears down.
layerState._activeTileset = null;
// Task 5: last surface regime the record geometry was recomputed for. The
// map-stack change listener compares the CURRENT regime (derived live from
// scene.globe.show) against this so bing→osm switches (same 'terrain-globe'
// whether the renderer shows the globe) against this so bing→osm switches (same 'terrain-globe'
// regime) don't trigger a pointless full-catalog rewrite.
layerState._lastAppliedRegime = null;
@@ -126,8 +182,8 @@ export function createState({ services }) {
layerState._mapStackListener = null;
// Field-test fix (2026-07-06): camera.moveEnd handle for the horizon-culling
// pass (removed in destroy). Event-driven only — never a per-frame loop, so
// Field-test fix (2026-07-06): the Off of the camera's moveEnd listener for
// the horizon-culling pass (called in destroy). Event-driven only — never a per-frame loop, so
// the zero-steady-state-work invariant holds.
layerState._horizonCullListener = null;
@@ -202,6 +258,7 @@ export function createState({ services }) {
layerState._cameraMoving = false;
// The Off of the camera's moveStart listener.
layerState._moveStartListener = null;
layerState._sourceAbort = null;
return layerState;
+63 -7
View File
@@ -1,4 +1,13 @@
import * as Cesium from 'cesium';
import { createIconBook } from '../../render/motion/iconBook.js';
/** A draw set that draws nothing, for the icon book the tests read. */
const testIconSet = () => ({
id: 'cctv:test:icons',
show: true,
upsert() {},
remove() {},
dispose() {},
});
export function createTesting({ state: layerState, services, parts, source }) {
/** Test seam: republishes host entries through the real push path, so tests
@@ -19,7 +28,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
/**
* Create the production monitor-plane/host-label pair without media setup.
* @param {Object} viewer Cesium viewer seam.
* @param {Object} viewer Viewer whose renderer draws the plane.
* @param {Object} record CCTV runtime record.
* @returns {Object} Projection runtime.
*/
@@ -34,15 +43,16 @@ export function createTesting({ state: layerState, services, parts, source }) {
record.probeClampRangeM,
);
const positions =
record.frustumPositions || parts.geometry.frustumCartesians(geometry);
record.frustumPositions || parts.rendering.frustumCartesians(geometry);
record.frustumGeometry = geometry;
record.frustumPositions = positions;
const runtime = {
cameraId: String(record.camera.id),
planeEntity: null,
labelPosition: new Cesium.Cartesian3(),
plane: null,
// createProjectionPlane gives it its label position.
labelPosition: null,
overlayEntry: null,
planeMaterial: new Cesium.ColorMaterialProperty(Cesium.Color.WHITE),
planeSource: parts.projection.plainPlaneSource(),
};
parts.projection.createProjectionPlane(
record,
@@ -79,6 +89,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
* @param {boolean} [options.enabled=true] Layer enabled state.
* @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.
* @returns {void}
*/
@@ -89,6 +100,8 @@ export function createTesting({ state: layerState, services, parts, source }) {
enabled = true,
coverageMode = 'on',
showProjection = false,
healthById = new Map(),
openingCameraProvisional = false,
} = {}) {
layerState._viewer = viewer;
layerState._records = Array.isArray(records) ? records : [];
@@ -99,15 +112,56 @@ export function createTesting({ state: layerState, services, parts, source }) {
);
layerState._coverageEntities = [];
layerState._projectionEntities = [];
layerState._billboards = null;
layerState._activeCameraId = activeCameraId;
layerState._autoHopSuspended = false;
layerState._openingCameraProvisional = !!openingCameraProvisional;
layerState._enabled = !!enabled;
layerState._coverageMode = parts.model.normalizeCoverageMode(
coverageMode,
'on',
);
layerState._showProjection = !!showProjection;
layerState._healthById = healthById;
layerState._viewRecords = [];
layerState._cameraIndexCache = null;
layerState._coverageVisibleIds = new Set();
layerState._neighborCountCache = null;
// A real book (over a set that draws nothing): every record gets its
// icon as init adds it.
layerState._icons = createIconBook(testIconSet());
for (const record of layerState._records)
if (record?.camera?.id) parts.rendering.addCameraIcon(record);
}
/**
* What the layer draws now, for the QA harness: the gizmo's parts, the
* coverage lines and monitor planes by item id, the viewshed volumes'
* ids, and how many volumes were ever written.
*/
function _cctvDrawnForTest() {
const coverage = {};
for (const record of layerState._records)
for (const line of record.coverageEntities || [])
if (line?.id) coverage[line.id] = line;
const planes = {};
for (const runtime of layerState._projectionEntities)
if (runtime?.plane) planes[runtime.plane.id] = runtime.plane;
return {
gizmo: layerState._gizmo?.partsForTest() ?? {},
coverage,
planes,
viewsheds: layerState._records
.map((record) => record.viewshedVolume)
.filter(Boolean),
viewshedWrites: parts.drawSets.volumeWritesForTest(),
};
}
/** The layer's icon book, for tests that read what the icons draw. */
function _cctvIconsForTest() {
return layerState._icons;
}
return {
_pushAmbientCardEntriesForTest,
@@ -116,5 +170,7 @@ export function createTesting({ state: layerState, services, parts, source }) {
_updateCctvProjectionPlaneForTest,
_extractPickedCameraIdForTest,
_setCctvCoverageStateForTest,
_cctvIconsForTest,
_cctvDrawnForTest,
};
}
+136 -119
View File
@@ -1,8 +1,6 @@
import * as Cesium from 'cesium';
import { hitTestWorldOverlay } from '../../overlays/worldOverlay.js';
import { VESSEL_OVERLAY_SOURCE_ID } from '../../data/vesselLabels.js';
import { isPointerFree } from '../../data/inputOwnership.js';
import { inputFor } from '../../input/dispatcher.js';
import {
clickCard,
registerPickOwner,
unregisterPickOwner,
} from '../../data/pickRegistry.js';
@@ -16,18 +14,22 @@ import {
} from './labels.js';
import {
formatUtcDayMonth,
isolate,
t,
tn,
msg,
translateKnown,
} from '../../i18n/index.js';
import { formatQuantity } from '../../ui/unitLabels.js';
import { cameraOf, canvasOf } from '../../render/rendererOf.js';
// "10-12 15:00 UTC" never breaks across lines: no-break spaces, and a word
// joiner after the hyphen (JetBrains Mono has no U+2011 non-breaking hyphen).
// The clock is isolated (a no-op outside RTL): a no-break space between two
// numbers joins them into one run, which in Arabic split the date around it.
const utc = (value) =>
value
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${value.slice(11, 16)}\u00a0UTC`
? `${formatUtcDayMonth(value).replace('-', '-\u2060')}\u00a0${isolate(value.slice(11, 16))}\u00a0UTC`
: t('Unavailable');
const COVERAGE = msg(
'Atlantic and eastern/central North Pacific; not worldwide cyclone coverage.',
@@ -41,27 +43,43 @@ const ADVISORIES_UNAVAILABLE = msg('Cyclone advisories unavailable');
const SERVER_REASONS = new Set([msg('Cyclone data unavailable')]);
const errorText = (error) =>
error && (SERVER_REASONS.has(error) ? t(error) : translateKnown(error));
// NHC's Tropical Cyclone Status JSON reference: PTC is post-tropical, PC is a
// potential tropical cyclone, and subtropical systems are STS and STD.
const CLASSIFICATION_NAMES = Object.freeze({
PTC: msg('Potential tropical cyclone'),
PC: msg('Potential tropical cyclone'),
PTC: msg('Post-tropical cyclone'),
HU: msg('Hurricane'),
TS: msg('Tropical storm'),
TD: msg('Tropical depression'),
SS: msg('Subtropical storm'),
SD: msg('Subtropical depression'),
STS: msg('Subtropical storm'),
STD: msg('Subtropical depression'),
});
const classificationName = (code) =>
Object.hasOwn(CLASSIFICATION_NAMES, code)
? t(CLASSIFICATION_NAMES[code])
: code;
const number = (value, unit) =>
value === null ? t('Unavailable') : formatQuantity(value, unit);
// A value the advisory leaves out (null) is left out of the line too.
const intensityText = (storm) => {
const has = (value) => value !== null && value !== undefined;
const wind = has(storm.windKt) ? formatQuantity(storm.windKt, 'kt') : null;
const pressure = has(storm.pressureHpa)
? formatQuantity(storm.pressureHpa, 'hPa')
: null;
if (wind && pressure)
return t('Maximum sustained wind: {wind} · Pressure: {pressure}', {
wind,
pressure,
});
if (wind) return t('Maximum sustained wind: {wind}', { wind });
if (pressure) return t('Pressure: {pressure}', { pressure });
return '';
};
/** Advisory status and coherent forecast geometry; selected through the shared row list. */
export function createCyclonesLayer({
feed,
hitTestOverlay = hitTestWorldOverlay,
overlayHost,
cesium = Cesium,
context = null,
createRendering = createCycloneRendering,
matchMedia = globalThis.matchMedia?.bind(globalThis),
openLink = (url) => globalThis.open?.(url, '_blank', 'noopener,noreferrer'),
@@ -76,8 +94,8 @@ export function createCyclonesLayer({
selectedId = null,
selectionIntent = 'auto',
navigationGeneration = 0,
clickHandler = null,
removeClickCapture = null;
selectionOwner = null,
selectedContextStormId = null;
let enabled = false,
loading = false,
error = null,
@@ -86,110 +104,102 @@ export function createCyclonesLayer({
const notify = () => listener?.();
const selected = () =>
snapshot?.storms.find((storm) => storm.id === selectedId) || null;
function clearSelectedContext({ evicted = false } = {}) {
if (selectedContextStormId) {
if (!evicted)
context.clearSelectedEntityContextForLayer('weather-cyclones');
context.removeEntityContextsForLayer('weather-cyclones');
}
selectedContextStormId = null;
}
// Callers publish only while selectedId names a storm in the snapshot.
function publishSelectedContext({ announce = false } = {}) {
const storm = selected();
if (!context) return;
const entity = {};
const contextId = `cyclone:${storm.id}`;
context.registerEntityContext(entity, {
id: contextId,
layerId: 'weather-cyclones',
layerName: 'Cyclone advisories',
source: 'NOAA NHC / CPHC',
label: storm.name,
latitude: storm.position.latitude,
longitude: storm.position.longitude,
// At most 12 properties reach the voice summary; keep the list short.
properties: {
classification: storm.classification,
classificationName: Object.hasOwn(
CLASSIFICATION_NAMES,
storm.classification,
)
? CLASSIFICATION_NAMES[storm.classification]
: undefined,
basin: storm.basin,
advisoryNumber: storm.advisoryNumber,
issuedAt: storm.issuedAt,
positionAt: storm.positionAt,
windKt: storm.windKt,
pressureHpa: storm.pressureHpa,
// Flat scalars: the voice context summary drops nested objects.
movementDirectionDegrees: storm.movement?.directionDegrees,
movementSpeedKt: storm.movement?.speedKt,
advisoryUrl: storm.advisoryUrl,
// Only while the proxy serves its cache because NHC is unreachable.
staleCacheFetchedAt:
snapshot.stale && Number.isFinite(snapshot.fetchedAt)
? new Date(snapshot.fetchedAt).toISOString()
: undefined,
},
});
selectedContextStormId = storm.id;
if (announce) context.selectEntityContext(entity);
context.removeEntityContextsForLayer('weather-cyclones', {
retainIds: new Set([contextId]),
});
}
function select(id) {
if (selectedId !== id) ++navigationGeneration;
selectedId = id;
rendering?.setSelection(id);
}
// Photorealistic 3D Tiles pick as tileset content without an entity id;
// that is empty map, the same as no pick at all on the globe.
const isSurfacePick = (picked) =>
!picked ||
(picked.id === undefined &&
(picked.content !== undefined ||
(typeof cesium.Cesium3DTileset === 'function' &&
picked.primitive instanceof cesium.Cesium3DTileset)));
function installSelection() {
if (
clickHandler ||
!viewer?.scene?.canvas ||
typeof cesium.ScreenSpaceEventHandler !== 'function'
)
return;
const owner = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
clickHandler = owner;
// Snapshot before sibling bubble listeners can rebuild the overlay hit
// rectangles. A vessel selection does that synchronously in the same click.
const canvas = viewer.scene.canvas;
let capturedHit = null;
const overlayHit = (x, y) => {
const hit = hitTestOverlay(x, y);
return { sourceId: hit?.sourceId, entryId: hit?.entryId };
};
const capture = (event) => {
capturedHit = null;
const point = event.changedTouches?.[0] || event;
if (!Number.isFinite(point.clientX) || !Number.isFinite(point.clientY))
if (selectionOwner || !canvasOf(viewer)) return;
const owner = {};
selectionOwner = owner;
const unsubscribe = inputFor(viewer).onClick((event) => {
// Ambient selection yields to draw tools and Director (the dispatcher
// skips a held pointer); it never claims the pointer, camera, or
// tracking state.
const position = event.screenPosition;
if (!enabled || destroyed || selectionOwner !== owner || !position)
return;
const rect = canvas.getBoundingClientRect();
const x = point.clientX - rect.left,
y = point.clientY - rect.top;
capturedHit = { x, y, ...overlayHit(x, y) };
};
const resetCapture = () => {
capturedHit = null;
};
const resetEvents = [
'pointerdown',
'mousedown',
'touchstart',
'pointercancel',
'touchcancel',
];
for (const type of resetEvents)
canvas.addEventListener?.(type, resetCapture, { capture: true });
const events = ['pointerup', 'mouseup', 'touchend'];
for (const type of events)
canvas.addEventListener?.(type, capture, { capture: true });
removeClickCapture = () => {
for (const type of events)
canvas.removeEventListener?.(type, capture, { capture: true });
for (const type of resetEvents)
canvas.removeEventListener?.(type, resetCapture, { capture: true });
capturedHit = null;
};
owner.setInputAction((click) => {
const nativeHit = capturedHit;
capturedHit = null;
// Ambient selection yields to draw tools and Director; it never claims
// the pointer, camera, or tracking state.
if (
!enabled ||
destroyed ||
clickHandler !== owner ||
!isPointerFree() ||
!click?.position
)
return;
// AIS cards paint above the globe on a pointer-events:none canvas. The
// vessel handler resolves this same topmost hit before cyclone geometry.
const captureMatches =
nativeHit &&
Math.abs(nativeHit.x - click.position.x) < 1 &&
Math.abs(nativeHit.y - click.position.y) < 1;
const hit = captureMatches
? nativeHit
: overlayHit(click.position.x, click.position.y);
if (hit.sourceId === VESSEL_OVERLAY_SOURCE_ID) return;
// The card or label painted on top, as it was when the click landed.
const card = clickCard(event);
// Storm cards and lead-hour labels paint on the same canvas; a click on
// one selects its storm. An id from a superseded advisory changes nothing.
if (hit.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(hit.entryId);
if (card?.sourceId === CYCLONE_OVERLAY_SOURCE_ID) {
const id = cycloneStormIdFromEntryId(card.entryId);
if (id) layer.setParams({ stormId: id });
return;
}
const picked = viewer.scene.pick(click.position);
const id = rendering?.pickStorm(picked);
// Another layer's card on top takes the click: the storm under it does
// not act, and the click is not empty map either.
if (card) return;
// A storm's own drawing names it; empty map (the globe, or 3D tiles)
// clears the selection.
const id = rendering?.pickStorm(event.drawHit);
if (id) layer.setParams({ stormId: id });
else if (isSurfacePick(picked)) layer.setParams({ clear: true });
}, cesium.ScreenSpaceEventType.LEFT_CLICK);
else if (!event.topHit) layer.setParams({ clear: true });
});
owner.unsubscribe = unsubscribe;
}
function removeSelection() {
const owner = clickHandler;
clickHandler = null;
removeClickCapture?.();
removeClickCapture = null;
if (owner && !owner.isDestroyed?.()) owner.destroy();
const owner = selectionOwner;
selectionOwner = null;
owner?.unsubscribe?.();
}
const layer = {
id: 'weather-cyclones',
@@ -199,7 +209,7 @@ export function createCyclonesLayer({
updateInterval: 300_000,
init(nextViewer) {
viewer = nextViewer;
rendering = createRendering({ viewer, cesium, overlayHost });
rendering = createRendering({ viewer, overlayHost });
},
attachShellServices(services) {
runNavigation =
@@ -230,6 +240,7 @@ export function createCyclonesLayer({
selectedId = null;
selectionIntent = 'auto';
++navigationGeneration;
clearSelectedContext();
rendering?.clear();
},
async update(_viewer, { signal } = {}) {
@@ -253,6 +264,7 @@ export function createCyclonesLayer({
snapshot = next;
selectedId = null;
++navigationGeneration;
clearSelectedContext({ evicted: true });
error = next.reason || ADVISORIES_UNAVAILABLE;
return true;
}
@@ -275,6 +287,10 @@ export function createCyclonesLayer({
: snapshot.storms[0]?.id || null,
);
else rendering.setSelection(selectedId);
if (selectedContextStormId) {
if (selectedId === selectedContextStormId) publishSelectedContext();
else clearSelectedContext({ evicted: true });
}
return true;
} catch (cause) {
if (controller.signal.aborted || request !== controller) return false;
@@ -284,6 +300,7 @@ export function createCyclonesLayer({
snapshot = null;
selectedId = null;
++navigationGeneration;
clearSelectedContext({ evicted: true });
return true;
} finally {
signal?.removeEventListener('abort', abort);
@@ -299,6 +316,7 @@ export function createCyclonesLayer({
if (params.clear === true || params.stormId === null) {
selectionIntent = 'cleared';
select(null);
clearSelectedContext();
notify();
} else if (
typeof params.stormId === 'string' &&
@@ -306,6 +324,7 @@ export function createCyclonesLayer({
) {
selectionIntent = 'user';
select(params.stormId);
publishSelectedContext({ announce: true });
notify();
}
const storm = selected();
@@ -321,12 +340,15 @@ export function createCyclonesLayer({
selectedId !== storm.id
)
return;
return viewer.camera.flyToBoundingSphere(sphere, {
duration: matchMedia?.('(prefers-reduced-motion: reduce)')
?.matches
? 0
: 1.4,
});
cameraOf(viewer).flyToBounds(
{ center: sphere.center, radius: sphere.radius },
{
durationS: matchMedia?.('(prefers-reduced-motion: reduce)')
?.matches
? 0
: 1.4,
},
);
});
}
}
@@ -364,12 +386,7 @@ export function createCyclonesLayer({
const position = storm
? t('Position as of {time}', { time: utc(storm.positionAt) })
: '';
const intensity = storm
? t('Maximum sustained wind: {wind} · Pressure: {pressure}', {
wind: number(storm.windKt, 'kt'),
pressure: number(storm.pressureHpa, 'hPa'),
})
: '';
const intensity = storm ? intensityText(storm) : '';
const detail = storm
? t('{name} · {classification} · Advisory {number} · issued {time}', {
name: storm.name,
@@ -419,7 +436,7 @@ export function createCyclonesLayer({
text: intensity,
},
{ id: 'geometry', text: geometry, muted: true },
]
].filter((line) => line.text)
: [],
detail,
status,
@@ -451,7 +468,7 @@ export function createCyclonesLayer({
]
: [],
info: storm
? `${detail}\n${position}\n${intensity}\n${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
? `${detail}\n${position}\n${intensity ? intensity + '\n' : ''}${geometry}${status && status !== geometry ? '\n' + status : ''}\n${coverageText(snapshot.coverage)}`
: `${detail}${status ? '\n' + status : ''}\n${coverageText(snapshot?.coverage)}`,
infoTitle: t(
'Select a storm on the map, or choose a storm in the list to select it and move the camera. Click empty map space to clear the selection. NOAA NHC/CPHC advisory context. The cone describes forecast center-track uncertainty, not storm size or the full hazard area. Forecast point labels are source lead hours, not times computed from advisory issuance. Geometry follows the surface; height is not weather altitude. Consult the official advisory.',
@@ -514,7 +531,7 @@ export function createCyclonesLayer({
enabled,
loading,
requestPending: !!request,
selectionActive: clickHandler !== null,
selectionActive: selectionOwner !== null,
selectedId,
selectionIntent,
timerActive: false,
+402 -88
View File
@@ -6,7 +6,43 @@ import {
releasePointer,
isPointerFree,
} from '../../data/inputOwnership.js';
import { isOwnedByOtherLayer } from '../../data/pickRegistry.js';
import {
isOwnedByOtherLayer,
setClickCardHitTest,
} from '../../data/pickRegistry.js';
import { fakeInput } from '../../input/testDoubles.mjs';
import { bindFakeCesiumCamera } from '../../testSupport/fakeCameraPort.mjs';
/** Record each click subscription the layer makes, as the old handler fakes did. */
function recordHandlers(viewer, handlers) {
const fake = fakeInput(viewer);
const subscribe = fake.input.onClick;
fake.input.onClick = (fn) => {
const handler = {
destroyed: false,
// A live subscription hears clicks through the dispatcher; a removed
// one is called directly, as a queued callback would be.
click: (click) =>
handler.destroyed
? fn({
screenPosition: click.position,
get pick() {
return viewer.scene.pick(click.position);
},
})
: fake.click(click.position),
};
handlers.push(handler);
const off = subscribe(fn);
return () => {
handler.destroyed = true;
off();
};
};
}
import * as contextStore from '../../data/contextStore.js';
import { createGevActionRunner } from '../../voice/gevActions.js';
import { fromRadians } from '../../geo/ellipsoid.js';
const time = '2026-09-16T03:00:00.000Z';
const storm = (id = 'ep152026') => ({
@@ -44,10 +80,18 @@ const deferred = () => {
return { promise, resolve };
};
test('map selection yields to pointer owners and owns only its enabled handler', async () => {
test('map selection yields to pointer owners and owns only its enabled handler', async (t) => {
const handlers = [],
pickedEntity = {},
foreignEntity = {};
// A pick of an item in one of the layer's draw sets, and one of another
// layer's set: the dispatcher hands each to pickStorm as a draw hit.
pickedEntity = {
set: 'weather-cyclones:1:points',
id: 'cyclone:ep162026:center',
},
foreignEntity = {
set: 'other-layer:points',
id: 'cyclone:ep162026:center',
};
let picked = { id: pickedEntity },
overlayHit = null,
overlayTests = 0,
@@ -58,42 +102,28 @@ test('map selection yields to pointer owners and owns only its enabled handler',
setSelection() {},
clear() {},
destroy() {},
pickStorm: (value) => (value?.id === pickedEntity ? 'ep162026' : null),
pickStorm: (hit) =>
hit?.set === pickedEntity.set && hit.id === pickedEntity.id
? 'ep162026'
: null,
ownsPickId: (id) => id === 'cyclone:ep162026:center',
getDiagnostics: () => ({}),
};
const cesium = {
ScreenSpaceEventType: { LEFT_CLICK: 'left' },
ScreenSpaceEventHandler: class {
constructor(canvas) {
assert.ok(canvas);
handlers.push(this);
this.destroyed = false;
}
setInputAction(callback, type) {
assert.equal(type, 'left');
this.click = callback;
}
destroy() {
this.destroyed = true;
}
isDestroyed() {
return this.destroyed;
}
},
};
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
cesium,
createRendering: () => rendering,
hitTestOverlay: () => {
overlayTests++;
return overlayHit;
},
});
setClickCardHitTest(() => {
overlayTests++;
return overlayHit;
});
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 100, top: 200 });
const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: {
canvas,
pick() {
@@ -108,6 +138,8 @@ test('map selection yields to pointer owners and owns only its enabled handler',
},
},
};
bindFakeCesiumCamera(viewer);
recordHandlers(viewer, handlers);
layer.init(viewer);
layer.setRowControlsListener(() => notices++);
assert.equal(handlers.length, 0, 'disabled module installs no handler');
@@ -152,41 +184,15 @@ test('map selection yields to pointer owners and owns only its enabled handler',
'foreground AIS card wins before scene picking',
);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// A native capture runs before an earlier sibling handler clears hit rects.
const up = new Event('pointerup');
Object.assign(up, { clientX: 110, clientY: 220 });
canvas.dispatchEvent(up);
overlayHit = null;
// Any other layer's card on top takes the click, not only a vessel's.
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
handlers[0].click(click);
assert.equal(
layer.getDiagnostics().selectedId,
'ep152026',
'captured AIS hit survives synchronous sibling overlay rebuild',
'a camera card over the storm keeps the click',
);
// A captured background hit remains background even if a sibling adds a card.
canvas.dispatchEvent(up);
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
// A new gesture clears an unconsumed release snapshot.
canvas.dispatchEvent(up);
canvas.dispatchEvent(new Event('pointerdown'));
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'ais-live-vessels', entryId: 'vessel:123' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click({ position: { x: 15, y: 25 } });
assert.equal(
layer.getDiagnostics().selectedId,
'ep162026',
'a different click cannot reuse the captured card',
);
layer.setParams({ stormId: 'ep152026' });
overlayHit = { sourceId: 'cctv', entryId: 'camera:1' };
const before = notices;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
@@ -236,13 +242,12 @@ test('map selection yields to pointer owners and owns only its enabled handler',
assert.equal(layer.getDiagnostics().selectionActive, false);
const afterDisable = picks;
const afterDisableOverlay = overlayTests;
canvas.dispatchEvent(up);
handlers[0].click(click);
assert.equal(
overlayTests,
afterDisableOverlay,
'disable removes native capture listeners',
'a disabled layer reads no card',
);
handlers[0].click(click);
assert.equal(picks, afterDisable, 'queued disabled callback is inert');
layer.enable();
await layer.update();
@@ -261,25 +266,13 @@ test('map selection yields to pointer owners and owns only its enabled handler',
);
assert.equal(handlers[1].destroyed, true);
});
test('a click on a storm card or lead-hour label selects that storm without picking', async () => {
test('a click on a storm card or lead-hour label selects that storm without picking', async (t) => {
const handlers = [];
let picks = 0,
overlayHit = null,
hostArgument;
const layer = createCyclonesLayer({
feed: { getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
cesium: {
ScreenSpaceEventType: { LEFT_CLICK: 'left' },
ScreenSpaceEventHandler: class {
constructor() {
handlers.push(this);
}
setInputAction(callback) {
this.click = callback;
}
destroy() {}
},
},
overlayHost: 'host',
createRendering: ({ overlayHost }) => {
hostArgument = overlayHost;
@@ -293,11 +286,15 @@ test('a click on a storm card or lead-hour label selects that storm without pick
getDiagnostics: () => ({}),
};
},
hitTestOverlay: () => overlayHit,
});
setClickCardHitTest(() => overlayHit);
t.after(() => setClickCardHitTest(null));
const canvas = new EventTarget();
canvas.getBoundingClientRect = () => ({ left: 0, top: 0 });
layer.init({
const viewer = {
get canvas() {
return this.scene?.canvas;
},
scene: {
canvas,
pick() {
@@ -305,7 +302,9 @@ test('a click on a storm card or lead-hour label selects that storm without pick
return { content: {} };
},
},
});
};
recordHandlers(viewer, handlers);
layer.init(viewer);
assert.equal(hostArgument, 'host', 'the overlay host reaches the renderer');
layer.enable();
await layer.update();
@@ -322,15 +321,11 @@ test('a click on a storm card or lead-hour label selects that storm without pick
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:al019999' };
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep152026');
// The native release snapshot carries the card identity too.
const up = new Event('pointerup');
Object.assign(up, { clientX: 10, clientY: 20 });
overlayHit = { sourceId: 'weather-cyclones', entryId: 'storm:ep162026' };
canvas.dispatchEvent(up);
overlayHit = null;
handlers[0].click(click);
assert.equal(layer.getDiagnostics().selectedId, 'ep162026');
assert.equal(picks, 0, 'card clicks never fall through to the scene');
overlayHit = null;
handlers[0].click(click);
assert.equal(picks, 1);
assert.equal(layer.getDiagnostics().selectedId, null, 'empty map clears');
@@ -338,7 +333,7 @@ test('a click on a storm card or lead-hour label selects that storm without pick
});
function harness(
feed = { getSnapshot: async () => snapshot() },
{ reducedMotion = false } = {},
{ reducedMotion = false, context = null } = {},
) {
const applied = [],
navigation = [],
@@ -354,7 +349,10 @@ function harness(
setSelection(id) {
selection = id;
},
getFocusSphere: () => ({ radius: 500000 }),
getFocusSphere: () => ({
center: { x: 6378137, y: 0, z: 0 },
radius: 500000,
}),
clear() {
cleared++;
},
@@ -368,6 +366,7 @@ function harness(
};
const layer = createCyclonesLayer({
feed,
context,
createRendering: () => rendering,
matchMedia: () => ({ matches: reducedMotion }),
openLink: (url) => opened.push(url),
@@ -378,6 +377,7 @@ function harness(
navigation.push({ sphere, options }),
},
};
bindFakeCesiumCamera(viewer);
layer.init(viewer);
layer.attachShellServices({
runNavigation: (fn) => {
@@ -401,6 +401,266 @@ function harness(
},
};
}
// Real shared-context store on a stand-in window; the voice runner reads it.
async function withSharedContext(t, body) {
const previousWindow = Object.getOwnPropertyDescriptor(globalThis, 'window');
const host = new EventTarget();
Object.defineProperty(globalThis, 'window', {
configurable: true,
value: host,
});
const layers = [];
t.after(() => {
try {
for (const layer of layers) layer.destroy();
} finally {
if (previousWindow)
Object.defineProperty(globalThis, 'window', previousWindow);
else delete globalThis.window;
}
});
const events = [];
host.addEventListener('gev:entity-selected', ({ detail }) =>
events.push(['selected', detail.id]),
);
host.addEventListener('gev:entity-selection-cleared', ({ detail }) =>
events.push(['cleared', detail.layerId, detail.reason]),
);
// The voice runner bounds its basemap wait with the window timers.
Object.assign(host, { setTimeout, clearTimeout });
const cartographic = {
longitude: (-125.8 * Math.PI) / 180,
latitude: (15.5 * Math.PI) / 180,
height: 5_000_000,
};
const position = fromRadians(
cartographic.longitude,
cartographic.latitude,
cartographic.height,
);
const viewer = bindFakeCesiumCamera({
clock: { onTick: { addEventListener: () => () => {} } },
scene: { canvas: { addEventListener() {}, removeEventListener() {} } },
camera: {
moveEnd: { addEventListener() {} },
positionWC: position,
positionCartographic: cartographic,
heading: 0,
pitch: 0,
},
});
const runner = createGevActionRunner({
viewer,
styleManager: {},
dataManager: {
layers: new Map(),
isEnabled: (id) => id === 'weather-cyclones',
getAll: () => [],
},
});
const selectedProperties = async () => {
const result = await runner('get_entity_context', { scope: 'selected' });
assert.equal(result.scope, 'selected');
return result.selected.properties;
};
const store = contextStore.getContextStore();
const open = (feed) => {
const h = harness(feed, { context: contextStore });
layers.push(h.layer);
return h;
};
await body({ events, selectedProperties, store, open });
}
test('shared cyclone context distinguishes switches, deliberate clears and feed eviction', async (t) => {
await withSharedContext(
t,
async ({ events, selectedProperties, store, open }) => {
let next = snapshot([
{ ...storm(), movement: { directionDegrees: 315, speedKt: 12 } },
{
...storm('ep162026'),
movement: { directionDegrees: 0, speedKt: 10 },
},
]);
const h = open({ getSnapshot: async () => next });
h.layer.enable();
await h.layer.update();
assert.deepEqual(
events,
[],
'the automatic first-storm row selection must not claim shared context',
);
assert.equal(store.entities.size, 0);
h.layer.setParams({ stormId: 'ep152026' });
assert.equal(store.entities.get('cyclone:ep152026').label, 'Fifteen-E');
let properties = await selectedProperties();
assert.equal(properties.classification, 'PTC');
assert.equal(properties.classificationName, 'Post-tropical cyclone');
assert.equal(properties.advisoryNumber, '10');
assert.equal(
properties.movementDirectionDegrees,
'315',
'selected storm movement should survive voice summarization',
);
assert.equal(properties.movementSpeedKt, '12');
assert.equal(
properties.advisoryUrl,
'https://www.nhc.noaa.gov/text/MIATCMEP5.shtml',
);
assert.equal(properties.staleCacheFetchedAt, undefined);
h.layer.setParams({ stormId: 'ep162026' });
properties = await selectedProperties();
assert.equal(
properties.movementDirectionDegrees,
'0',
'a due-north heading is a value, not a missing one',
);
assert.equal(properties.movementSpeedKt, '10');
assert.deepEqual(events, [
['selected', 'cyclone:ep152026'],
['selected', 'cyclone:ep162026'],
]);
assert.deepEqual([...store.entities.keys()], ['cyclone:ep162026']);
next = snapshot([
{ ...storm(), movement: { directionDegrees: 315, speedKt: 12 } },
{ ...storm('ep162026'), movement: { directionDegrees: 0, speedKt: 0 } },
]);
await h.layer.update();
assert.equal(events.length, 2, 'refresh must not announce selection');
properties = await selectedProperties();
assert.equal(
properties.movementSpeedKt,
'0',
'stationary is a value, refreshed into the selected record',
);
h.layer.setParams({ clear: true });
assert.deepEqual(events.at(-1), [
'cleared',
'weather-cyclones',
'deliberate',
]);
assert.equal(store.entities.size, 0);
h.layer.setParams({ stormId: 'ep162026' });
next = snapshot([storm()]);
await h.layer.update();
assert.deepEqual(
events.at(-1),
['cleared', 'weather-cyclones', 'evicted'],
'a vanished user-selected storm must clear instead of transferring context to the fallback row',
);
assert.equal(store.entities.size, 0);
assert.equal(store.selectedEntityId, null);
h.layer.setParams({ stormId: 'ep152026' });
h.layer.disable();
assert.deepEqual(events.at(-1), [
'cleared',
'weather-cyclones',
'deliberate',
]);
assert.equal(store.entities.size, 0);
},
);
});
test('shared cyclone context is evicted when the source fails and marks a stale cache', async (t) => {
await withSharedContext(
t,
async ({ events, selectedProperties, store, open }) => {
let next = snapshot([{ ...storm(), classification: 'XX' }]);
let fail = false;
const h = open({
getSnapshot: async () => {
if (fail) throw new Error('Network unavailable');
return next;
},
});
h.layer.enable();
await h.layer.update();
h.layer.setParams({ stormId: 'ep152026' });
let properties = await selectedProperties();
assert.equal(properties.classification, 'XX');
assert.equal(
properties.classificationName,
undefined,
'an unknown code is not given a guessed meaning',
);
next = { ...snapshot(), stale: true };
await h.layer.update();
properties = await selectedProperties();
assert.equal(properties.staleCacheFetchedAt, time);
assert.equal(events.length, 1, 'refresh must not announce selection');
next = {
...snapshot([]),
unavailable: true,
reason: 'Cyclone data unavailable',
};
await h.layer.update();
assert.deepEqual(events.at(-1), [
'cleared',
'weather-cyclones',
'evicted',
]);
assert.equal(store.entities.size, 0);
next = snapshot();
await h.layer.update();
h.layer.setParams({ stormId: 'ep152026' });
assert.equal(store.selectedEntityId, 'cyclone:ep152026');
fail = true;
await h.layer.update();
assert.deepEqual(events.at(-1), [
'cleared',
'weather-cyclones',
'evicted',
]);
assert.equal(store.entities.size, 0);
assert.equal(store.selectedEntityId, null);
},
);
});
test('cyclone clears leave another layer selection and its records alone', async (t) => {
await withSharedContext(t, async ({ events, store, open }) => {
const h = open({ getSnapshot: async () => snapshot() });
h.layer.enable();
await h.layer.update();
h.layer.setParams({ stormId: 'ep152026' });
const foreign = {};
contextStore.registerEntityContext(foreign, {
id: 'flight:abc123',
layerId: 'flights',
label: 'Foreign',
});
contextStore.selectEntityContext(foreign);
const before = events.length;
h.layer.setParams({ clear: true });
assert.equal(store.selectedEntityId, 'flight:abc123');
assert.ok(store.entities.has('flight:abc123'));
assert.equal(store.entities.has('cyclone:ep152026'), false);
assert.equal(
events.length,
before,
'no clear is reported for a foreign selection',
);
// A cyclone clear does not report a dangling foreign selection as evicted.
store.entities.delete('flight:abc123');
h.layer.disable();
assert.equal(store.selectedEntityId, 'flight:abc123');
assert.equal(events.length, before);
});
});
test('refresh preserves selection intent, including explicit clears and missing storms', async () => {
let next = snapshot([storm(), storm('ep162026')]);
const h = harness({ getSnapshot: async () => next });
@@ -513,12 +773,13 @@ test('only the latest queued focus runs and an unchanged selection survives refr
});
test('classification display expands known codes without altering the source or guessing unknown meanings', async () => {
for (const [code, label] of [
['PTC', 'Potential tropical cyclone'],
['PC', 'Potential tropical cyclone'],
['PTC', 'Post-tropical cyclone'],
['HU', 'Hurricane'],
['TS', 'Tropical storm'],
['TD', 'Tropical depression'],
['SS', 'Subtropical storm'],
['SD', 'Subtropical depression'],
['STS', 'Subtropical storm'],
['STD', 'Subtropical depression'],
['EX', 'EX'],
['UNKNOWN', 'UNKNOWN'],
]) {
@@ -537,6 +798,59 @@ test('classification display expands known codes without altering the source or
}
}
});
// Quantities join number and unit with a no-break space.
const plain = (text) => text?.replace(/\u00a0/g, ' ') ?? null;
test('an advisory without pressure, movement or link leaves those values out', async () => {
const record = {
...storm(),
windKt: 85,
pressureHpa: null,
movement: { directionDegrees: null, speedKt: null },
advisoryUrl: null,
};
const h = harness({ getSnapshot: async () => snapshot([record]) });
try {
h.layer.enable();
await h.layer.update();
const { summary, info } = h.layer.getRowControls();
const intensity = summary.lines.find((line) => line.id === 'intensity');
assert.equal(plain(intensity.text), 'Maximum sustained wind: 85 kt');
assert.deepEqual(
summary.lines.map((line) => line.id),
['position', 'intensity', 'geometry'],
);
assert.deepEqual(summary.actions, [], 'no advisory link to open');
assert.ok(plain(info).includes('Maximum sustained wind: 85 kt\n'));
for (const text of [info, ...summary.lines.map((line) => line.text)])
assert.doesNotMatch(text, /Unavailable|Pressure/);
} finally {
h.layer.destroy();
}
});
test('an advisory with only one of wind and pressure shows that one alone', async () => {
for (const [values, expected] of [
[{ windKt: null, pressureHpa: 990 }, 'Pressure: 990 hPa'],
[
{ windKt: 60, pressureHpa: 990 },
'Maximum sustained wind: 60 kt · Pressure: 990 hPa',
],
[{ windKt: null, pressureHpa: null }, null],
]) {
const h = harness({
getSnapshot: async () => snapshot([{ ...storm(), ...values }]),
});
try {
h.layer.enable();
await h.layer.update();
const { summary, info } = h.layer.getRowControls();
const intensity = summary.lines.find((line) => line.id === 'intensity');
assert.equal(plain(intensity?.text), expected);
assert.doesNotMatch(info, /Unavailable|\n\n/);
} finally {
h.layer.destroy();
}
}
});
test('advisory selection uses accessible row descriptors and shared camera handoff', async () => {
const h = harness(
{ getSnapshot: async () => snapshot([storm(), storm('ep162026')]) },
+2 -2
View File
@@ -64,7 +64,7 @@ const SHARED_CARD = Object.freeze({
* @param {boolean} selected
* @returns {object}
*/
export function cycloneStormEntry(storm, selected) {
function cycloneStormEntry(storm, selected) {
return {
...SHARED_CARD,
...markerClearance(
@@ -92,7 +92,7 @@ export function cycloneStormEntry(storm, selected) {
* @param {{tauHours:number,position:object}} point
* @returns {object}
*/
export function cycloneLeadEntry(stormId, point) {
function cycloneLeadEntry(stormId, point) {
return {
...SHARED_CARD,
...markerClearance(CYCLONE_MARKER_PX.forecast),
+207 -245
View File
@@ -1,3 +1,6 @@
import { fromDegrees } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { drawOf } from '../../render/rendererOf.js';
import {
CYCLONE_ACCENT,
CYCLONE_MARKER_PX,
@@ -5,6 +8,14 @@ import {
createCycloneLabels,
} from './labels.js';
/**
* The draw sets the advisories are drawn in start with this; each rendering
* has its own (`weather-cyclones:1:points`, …), so several can share a
* renderer. Picks name them as `Hit.set`.
*/
export const CYCLONE_SET_PREFIX = 'weather-cyclones';
let renderings = 0;
/** Only geometry from the displayed status advisory is eligible for rendering. */
export function coherentCycloneGeometry(storm) {
return (
@@ -13,299 +24,250 @@ export function coherentCycloneGeometry(storm) {
);
}
/** A `#rrggbb` colour at `alpha`, as CSS. */
function withAlpha(hex, alpha) {
const n = Number.parseInt(hex.slice(1), 16);
return `rgba(${(n >> 16) & 255},${(n >> 8) & 255},${n & 255},${alpha})`;
}
const BLACK = [0, 0, 0, 1];
const WHITE = [1, 1, 1, 1];
/**
* Static Cesium entities with owned horizon culling; no timers or clock.
* Storm names and lead hours are published to the shared overlay host at the
* same anchors the points use.
* Static renderer draw sets with the renderer's horizon cull; no timers or
* clock. Points are clamped and drawn over depth, so the points set culls
* them past the horizon; tracks, cones and their outlines drape on the
* ground, where the globe hides the far side. Storm names and lead hours
* are published to the shared overlay host at the same anchors the points
* use.
*/
export function createCycloneRendering({ viewer, cesium: C, overlayHost }) {
export function createCycloneRendering({ viewer, overlayHost }) {
const labels = createCycloneLabels({ host: overlayHost });
let source = null,
generation = 0,
const draw = drawOf(viewer);
const prefix = `${CYCLONE_SET_PREFIX}:${++renderings}`;
const setIds = new Set(
['points', 'lines', 'cones'].map((kind) => `${prefix}:${kind}`),
);
const points = draw.points({
id: `${prefix}:points`,
horizonCull: true,
clampTo: 'both',
});
const lines = draw.lines({ id: `${prefix}:lines`, clampTo: 'both' });
const cones = draw.shapes({ id: `${prefix}:cones`, clampTo: 'both' });
let committed = false,
selected = null,
destroyed = false;
// Per storm: its center point (redrawn on selection), forecast points and
// focus sphere; per drawn item, the storm it belongs to.
let centers = new Map(),
spheres = new Map();
let entityStorms = new WeakMap();
let entityIds = new Set();
forecasts = [],
spheres = new Map(),
itemStorms = new Map();
let counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
let horizonStorms = [],
removePreRender = null,
pointOccluder = null,
sphereOccluder = null;
const blue = C.Color.fromCssColorString(CYCLONE_ACCENT);
const gold = C.Color.fromCssColorString(CYCLONE_SELECTED_ACCENT);
const white = C.Color.WHITE;
const render = () => {
if (!viewer.isDestroyed?.()) viewer.scene.requestRender();
};
function cullHorizon() {
pointOccluder.cameraPosition = viewer.camera.positionWC;
sphereOccluder.cameraPosition = viewer.camera.positionWC;
let changed = false;
for (let i = 0; i < horizonStorms.length; i++) {
const storm = horizonStorms[i];
for (let j = 0; j < storm.points.length; j++) {
const { entity, position } = storm.points[j];
const show = pointOccluder.isPointVisible(position);
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
if (!storm.shapes.length) continue;
const show = sphereOccluder.isBoundingSphereVisible(storm.sphere);
for (let j = 0; j < storm.shapes.length; j++) {
const entity = storm.shapes[j];
if (entity.show !== show) {
entity.show = show;
changed = true;
}
}
}
if (changed) render();
let itemCount = 0;
function centerItem(storm) {
const chosen = storm.id === selected;
return {
id: `cyclone:${storm.id}:center`,
pos: storm.at,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: chosen ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm,
color: chosen ? CYCLONE_SELECTED_ACCENT : CYCLONE_ACCENT,
outlineColor: BLACK,
outlineWidth: 2,
};
}
function syncHorizonListener() {
if (!horizonStorms.length) {
removePreRender?.();
removePreRender = null;
return;
}
if (removePreRender) return;
pointOccluder ||= new C.EllipsoidalOccluder(
C.Ellipsoid.WGS84,
viewer.camera.positionWC,
);
// EllipsoidalOccluder only tests points. An inscribed WGS84 sphere
// conservatively culls extents, retaining partially visible tracks/cones.
sphereOccluder ||= new C.Occluder(
new C.BoundingSphere(C.Cartesian3.ZERO, C.Ellipsoid.WGS84.minimumRadius),
viewer.camera.positionWC,
);
removePreRender = viewer.scene.preRender.addEventListener(cullHorizon);
}
function remove(value) {
if (!value) return;
if (!viewer.dataSources.isDestroyed?.())
viewer.dataSources.remove(value, true);
value.entities.removeAll();
function drawPoints() {
points.set([...[...centers.values()].map(centerItem), ...forecasts]);
}
// Only the centers show the selection: a change redraws the points set.
function select(id) {
if (destroyed || id === selected) return;
selected = id;
for (const [stormId, entity] of centers) {
entity.point.color = stormId === id ? gold : blue;
entity.point.pixelSize =
stormId === id ? CYCLONE_MARKER_PX.selected : CYCLONE_MARKER_PX.storm;
}
drawPoints();
labels.setSelection(id);
render();
}
return {
async setSnapshot(snapshot, { signal } = {}) {
signal?.throwIfAborted();
if (destroyed) return false;
const owner = ++generation;
const next = new C.CustomDataSource('weather-cyclones');
const nextCenters = new Map(),
nextSpheres = new Map();
const nextEntityStorms = new WeakMap();
const nextEntityIds = new Set();
nextSpheres = new Map(),
nextItemStorms = new Map();
const nextForecasts = [],
nextLines = [],
nextCones = [],
nextLabels = [];
const nextCounts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
const nextHorizonStorms = [];
const nextLabels = [];
const position = ({ longitude, latitude }) =>
C.Cartesian3.fromDegrees(longitude, latitude, 0);
const coordinate = (pair) =>
position({ longitude: pair[0], latitude: pair[1] });
try {
for (const storm of snapshot.storms) {
const horizon = { points: [], shapes: [], sphere: null };
const addEntity = (options) => {
const entity = next.entities.add(options);
if (options.position)
horizon.points.push({ entity, position: options.position });
else horizon.shapes.push(entity);
nextEntityStorms.set(entity, storm.id);
nextEntityIds.add(entity.id);
return entity;
};
const center = position(storm.position),
extent = [center];
const entity = addEntity({
id: `cyclone:${storm.id}:center`,
name: storm.name,
position: center,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.storm,
color: blue,
outlineColor: C.Color.BLACK,
outlineWidth: 2,
},
const lonLat = ({ longitude, latitude }) => ({
lon: longitude,
lat: latitude,
height: 0,
});
const pair = (coordinate) => ({
lon: coordinate[0],
lat: coordinate[1],
height: 0,
});
const ecef = (p) => fromDegrees(p.lon, p.lat, 0);
for (const storm of snapshot.storms) {
const own = (id) => (nextItemStorms.set(id, storm.id), id);
const at = lonLat(storm.position);
const center = ecef(at);
const extent = [center];
own(`cyclone:${storm.id}:center`);
nextCenters.set(storm.id, { id: storm.id, at });
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const tracks =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
tracks.forEach((line, index) => {
// Lines take ECEF (draw.d.ts `LineItem`).
const positions = line.map((c) => ecef(pair(c)));
extent.push(...positions);
nextLines.push({
id: own(`cyclone:${storm.id}:track:${index}`),
positions,
widthPx: 2.5,
mode: 'draped',
style: { kind: 'solid', color: CYCLONE_ACCENT },
});
nextCounts.tracks++;
});
nextCenters.set(storm.id, entity);
const label = {
id: storm.id,
name: storm.name,
classification: storm.classification,
windKt: storm.windKt,
position: center,
forecasts: [],
};
nextLabels.push(label);
nextCounts.storms++;
if (coherentCycloneGeometry(storm)) {
const lines =
storm.track?.type === 'LineString'
? [storm.track.coordinates]
: storm.track?.coordinates || [];
lines.forEach((line, index) => {
const positions = line.map(coordinate);
extent.push(...positions);
addEntity({
id: `cyclone:${storm.id}:track:${index}`,
polyline: {
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
positions,
width: 2.5,
material: blue,
arcType: C.ArcType.GEODESIC,
},
});
nextCounts.tracks++;
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const all = rings.map((ring) => ring.map(pair));
const ecefRings = all.map((ring) => ring.map(ecef));
extent.push(...ecefRings[0]);
nextCones.push({
id: own(`cyclone:${storm.id}:cone:${index}`),
geometry: { kind: 'polygon', rings: all },
fill: withAlpha(CYCLONE_ACCENT, 0.16),
height: 'clampGround',
});
const polygons =
storm.cone?.type === 'Polygon'
? [storm.cone.coordinates]
: storm.cone?.coordinates || [];
polygons.forEach((rings, index) => {
// Each exterior retains its own interior holes. Native geographic
// tessellation handles the antimeridian; never flatten rings.
const exterior = rings[0].map(coordinate);
extent.push(...exterior);
const holes = rings
.slice(1)
.map((ring) => new C.PolygonHierarchy(ring.map(coordinate)));
addEntity({
id: `cyclone:${storm.id}:cone:${index}`,
polygon: {
hierarchy: new C.PolygonHierarchy(exterior, holes),
classificationType: C.ClassificationType.BOTH,
material: blue.withAlpha(0.16),
arcType: C.ArcType.GEODESIC,
ecefRings.forEach((ring, ringIndex) => {
nextLines.push({
id: own(
`cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
),
positions: ring,
widthPx: 1,
mode: 'draped',
style: {
kind: 'solid',
color: withAlpha(CYCLONE_ACCENT, 0.55),
},
});
[exterior, ...holes.map((hole) => hole.positions)].forEach(
(positions, ringIndex) => {
addEntity({
id: `cyclone:${storm.id}:cone:${index}:outline:${ringIndex}`,
polyline: {
positions,
width: 1,
material: blue.withAlpha(0.55),
arcType: C.ArcType.GEODESIC,
clampToGround: true,
classificationType: C.ClassificationType.BOTH,
},
});
},
);
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const p = position(point.position);
extent.push(p);
addEntity({
id: `cyclone:${storm.id}:forecast:${index}`,
position: p,
point: {
heightReference: C.HeightReference.CLAMP_TO_GROUND,
disableDepthTestDistance: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: white,
outlineColor: C.Color.BLACK,
outlineWidth: 1,
},
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
nextCounts.cones++;
});
for (const [index, point] of storm.forecastPoints.entries()) {
if (point.tauHours === 0) continue;
const pos = lonLat(point.position);
const p = ecef(pos);
extent.push(p);
nextForecasts.push({
id: own(`cyclone:${storm.id}:forecast:${index}`),
pos,
height: 'clampGround',
disableDepthTest: Number.POSITIVE_INFINITY,
pixelSize: CYCLONE_MARKER_PX.forecast,
color: WHITE,
outlineColor: BLACK,
outlineWidth: 1,
});
label.forecasts.push({ tauHours: point.tauHours, position: p });
nextCounts.forecastPoints++;
}
const sphere = C.BoundingSphere.fromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
horizon.sphere = sphere;
nextHorizonStorms.push(horizon);
}
await viewer.dataSources.add(next);
if (destroyed || generation !== owner || signal?.aborted) {
remove(next);
return false;
}
remove(source);
source = next;
centers = nextCenters;
spheres = nextSpheres;
entityStorms = nextEntityStorms;
entityIds = nextEntityIds;
counts = nextCounts;
horizonStorms = nextHorizonStorms;
syncHorizonListener();
labels.setSnapshot(nextLabels, selected);
select(selected);
return true;
} catch (error) {
remove(next);
if (signal?.aborted || generation !== owner || destroyed) return false;
throw error;
const sphere = sphereFromPoints(extent);
// A status-only point still has a useful regional camera destination.
sphere.radius = Math.max(sphere.radius, 500_000);
nextSpheres.set(storm.id, sphere);
}
if (destroyed || signal?.aborted) return false;
centers = nextCenters;
forecasts = nextForecasts;
spheres = nextSpheres;
itemStorms = nextItemStorms;
counts = nextCounts;
itemCount = nextItemStorms.size;
committed = true;
lines.set(nextLines);
cones.set(nextCones);
// Every commit redraws the points, an empty advisory included.
drawPoints();
labels.setSnapshot(nextLabels, selected);
return true;
},
setSelection: select,
ownsPickId(id) {
return source !== null && typeof id === 'string' && entityIds.has(id);
return committed && typeof id === 'string' && itemStorms.has(id);
},
pickStorm(picked) {
// Cesium Entity picks carry the exact entity in `id`. IDs/prefixes alone
// cannot establish ownership, especially after an advisory replacement.
const entity = picked?.id;
return source && entity && typeof entity === 'object'
? entityStorms.get(entity) || null
: null;
/**
* The storm a click's draw hit (`Hit`, query.d.ts) belongs to: an item
* of these sets in the advisory drawn now, never an id from another.
*/
pickStorm(hit) {
if (!committed || !hit || hit.surface) return null;
if (!setIds.has(hit.set)) return null;
return itemStorms.get(hit.id) ?? null;
},
getFocusSphere(id) {
return spheres.get(id) || null;
},
clear() {
++generation;
horizonStorms = [];
syncHorizonListener();
pointOccluder = null;
sphereOccluder = null;
remove(source);
source = null;
committed = false;
if (!destroyed) {
points.clear();
lines.clear();
cones.clear();
}
labels.clear();
centers.clear();
spheres.clear();
entityStorms = new WeakMap();
entityIds.clear();
centers = new Map();
forecasts = [];
spheres = new Map();
itemStorms = new Map();
itemCount = 0;
selected = null;
counts = { storms: 0, tracks: 0, cones: 0, forecastPoints: 0 };
render();
},
destroy() {
if (destroyed) return;
this.clear();
destroyed = true;
points.dispose();
lines.dispose();
cones.dispose();
},
getDiagnostics() {
return {
...counts,
dataSources: Number(!!source),
entities: source?.entities.values.length || 0,
// One display: the committed advisory's sets, and the items in them.
dataSources: Number(committed),
entities: itemCount,
selectedId: selected,
timerActive: false,
};
+286 -502
View File
@@ -1,8 +1,15 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createCycloneRendering } from './rendering.js';
import { CYCLONE_OVERLAY_SOURCE_ID } from './labels.js';
import { fromDegrees } from '../../geo/ellipsoid.js';
import { sphereFromPoints } from '../../geo/sphere.js';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
import { CYCLONE_SET_PREFIX, createCycloneRendering } from './rendering.js';
import {
CYCLONE_ACCENT,
CYCLONE_MARKER_PX,
CYCLONE_OVERLAY_SOURCE_ID,
CYCLONE_SELECTED_ACCENT,
} from './labels.js';
/** Records what the renderer publishes to the shared overlay host. */
function overlayRecorder() {
@@ -28,161 +35,40 @@ function overlayRecorder() {
};
}
function harness({ deferred = false } = {}) {
const sources = [],
completions = [],
pointOccluders = [],
sphereOccluders = [];
const listeners = new Set();
const visibility = {
points: new Map(),
spheres: new Map(),
pointCalls: [],
sphereCalls: [],
writes: 0,
};
const color = (value) => ({
value,
withAlpha: (alpha) => ({ value, alpha }),
});
const cesium = {
Color: {
fromCssColorString: color,
WHITE: color('white'),
BLACK: color('black'),
},
Cartesian2: class {
constructor(x, y) {
this.x = x;
this.y = y;
}
},
Cartesian3: {
ZERO: { x: 0, y: 0, z: 0 },
fromDegrees: (lon, lat, height) => ({ lon, lat, height }),
},
Ellipsoid: { WGS84: { minimumRadius: 6356752 } },
EllipsoidalOccluder: class {
constructor(ellipsoid, cameraPosition) {
this.ellipsoid = ellipsoid;
this.cameraPosition = cameraPosition;
pointOccluders.push(this);
}
isPointVisible(position) {
visibility.pointCalls.push(position);
return visibility.points.get(position) ?? true;
}
},
Occluder: class {
constructor(sphere, cameraPosition) {
this.sphere = sphere;
this.cameraPosition = cameraPosition;
sphereOccluders.push(this);
}
isBoundingSphereVisible(sphere) {
visibility.sphereCalls.push(sphere);
return visibility.spheres.get(sphere) ?? true;
}
},
PolygonHierarchy: class {
constructor(positions, holes = []) {
this.positions = positions;
this.holes = holes;
}
},
BoundingSphere: class {
constructor(center, radius) {
this.center = center;
this.radius = radius;
}
static fromPoints(points) {
return { points, radius: 10 };
}
},
LabelStyle: { FILL_AND_OUTLINE: 1 },
HorizontalOrigin: { LEFT: 1 },
ArcType: { GEODESIC: 1 },
HeightReference: Cesium.HeightReference,
ClassificationType: Cesium.ClassificationType,
DistanceDisplayCondition: Cesium.DistanceDisplayCondition,
CustomDataSource: class {
constructor() {
const values = [];
this.entities = {
values,
add: (value) => {
let show = true;
Object.defineProperty(value, 'show', {
get: () => show,
set: (next) => {
show = next;
visibility.writes++;
},
});
values.push(value);
return value;
},
removeAll: () => {
values.length = 0;
},
};
}
},
};
let renders = 0;
/** A rendering on a viewer bound to a fake draw port. */
function harness() {
const viewer = {};
const { draw, unbind } = bindFakeDraw(viewer);
const overlay = overlayRecorder();
const viewer = {
camera: { positionWC: { x: 6378487, y: 0, z: 0 } },
scene: {
requestRender: () => renders++,
preRender: {
addEventListener(listener) {
listeners.add(listener);
return () => listeners.delete(listener);
},
},
},
dataSources: {
add(value) {
if (deferred)
return new Promise((resolve) =>
completions.push(() => {
sources.push(value);
resolve(value);
}),
);
sources.push(value);
return Promise.resolve(value);
},
remove(value) {
const i = sources.indexOf(value);
if (i >= 0) sources.splice(i, 1);
},
},
};
return {
rendering: createCycloneRendering({
viewer,
cesium,
overlayHost: overlay.host,
}),
overlay,
sources,
completions,
const rendering = createCycloneRendering({
viewer,
cesium,
visibility,
pointOccluders,
sphereOccluders,
listeners,
frame() {
for (const listener of listeners) listener();
overlayHost: overlay.host,
});
const sets = {};
for (const kind of ['points', 'lines', 'cones'])
sets[kind] = [...draw.sets.values()].find((record) =>
record.spec.id.endsWith(`:${kind}`),
);
return {
viewer,
draw,
unbind,
overlay,
rendering,
sets,
/** Every item drawn now, across the rendering's sets. */
items() {
return Object.values(sets).flatMap((record) => [
...record.items.values(),
]);
},
get renders() {
return renders;
/** A click's draw hit on the item `id`, in the set of `kind`. */
hit(kind, id) {
return { set: sets[kind].spec.id, id, surface: false };
},
};
}
const storm = () => ({
id: 'ep152026',
name: 'Fifteen-E',
@@ -191,6 +77,7 @@ const storm = () => ({
geometryStatus: 'current',
position: { longitude: 179, latitude: 15 },
forecastPoints: [
{ position: { longitude: 179, latitude: 15 }, tauHours: 0 },
{ position: { longitude: -179, latitude: 16 }, tauHours: 12 },
],
track: {
@@ -231,301 +118,94 @@ const storm = () => ({
},
});
test('horizon culling updates only changed entities and keeps selection independent', async () => {
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near' }],
test('each rendering draws into its own point, line and cone sets', () => {
const a = harness();
const { sets } = a;
assert.match(sets.points.spec.id, new RegExp(`^${CYCLONE_SET_PREFIX}:\\d+:`));
assert.equal(sets.points.kind, 'points');
assert.equal(sets.points.spec.horizonCull, true);
assert.equal(sets.points.spec.clampTo, 'both');
assert.equal(sets.lines.kind, 'lines');
assert.equal(sets.lines.spec.clampTo, 'both');
assert.equal(sets.cones.kind, 'shapes');
assert.equal(sets.cones.spec.clampTo, 'both');
// A second rendering on the same renderer is a separate display.
const viewer = {};
const { draw } = bindFakeDraw(viewer);
const first = createCycloneRendering({
viewer,
overlayHost: overlayRecorder().host,
});
const entities = h.sources[0].entities.values;
const far = entities.filter((e) => e.id.startsWith('cyclone:ep152026:'));
const near = entities.filter((e) => e.id.startsWith('cyclone:near:'));
const forecast = far.find((e) => e.id.endsWith('forecast:0'));
const sphere = h.rendering.getFocusSphere('ep152026');
for (const entity of far)
if (entity.position) h.visibility.points.set(entity.position, false);
h.visibility.spheres.set(sphere, false);
h.rendering.setSelection('ep152026');
const publishes = h.overlay.publishes;
const before = h.renders;
h.frame();
assert.ok(far.every((e) => e.show === false));
assert.ok(near.every((e) => e.show === true));
assert.equal(
h.overlay.entry('lead:ep152026:12').position,
forecast.position,
'the host culls labels at the same anchors the points use',
);
assert.equal(h.overlay.publishes, publishes, 'culling never republishes');
assert.equal(h.renders, before + 1);
assert.equal(h.visibility.writes, far.length);
assert.equal(h.visibility.pointCalls.length, 4);
assert.deepEqual(h.visibility.sphereCalls, [
sphere,
h.rendering.getFocusSphere('near'),
]);
h.frame();
assert.equal(h.renders, before + 1);
assert.equal(h.visibility.writes, far.length);
// A visible portion of the extent keeps all tracks/cones shown even when
// the centre and an individual forecast point remain beyond the horizon.
h.visibility.spheres.set(sphere, true);
h.viewer.camera.positionWC = { x: 0, y: 6378487, z: 0 };
h.frame();
assert.ok(far.filter((e) => !e.position).every((e) => e.show));
assert.ok(far.filter((e) => e.position).every((e) => !e.show));
assert.equal(h.renders, before + 2);
assert.equal(h.pointOccluders.length, 1);
assert.equal(h.sphereOccluders.length, 1);
assert.equal(h.pointOccluders[0].ellipsoid, h.cesium.Ellipsoid.WGS84);
assert.equal(h.pointOccluders[0].cameraPosition, h.viewer.camera.positionWC);
assert.equal(h.sphereOccluders[0].cameraPosition, h.viewer.camera.positionWC);
h.rendering.setSelection('near');
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
assert.equal(
h.overlay.entry('lead:near:12').position,
near.find((e) => e.id.endsWith('forecast:0')).position,
);
h.visibility.points.set(forecast.position, true);
const beforeReveal = h.renders;
const revealPublishes = h.overlay.publishes;
h.frame();
assert.equal(forecast.show, true);
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
assert.equal(h.overlay.publishes, revealPublishes);
assert.equal(far[0].show, false);
assert.equal(h.renders, beforeReveal + 1);
h.rendering.destroy();
});
test('horizon listener follows committed nonempty snapshots and clear/destroy', async () => {
const h = harness();
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [] });
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
const old = [...h.sources[0].entities.values];
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
h.frame();
assert.ok(
h.visibility.pointCalls.every((p) => !old.some((e) => e.position === p)),
);
await h.rendering.setSnapshot({ storms: [] });
assert.equal(h.listeners.size, 0);
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
assert.equal(h.listeners.size, 0);
const before = h.renders;
h.frame();
assert.equal(h.renders, before);
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 1);
h.rendering.destroy();
h.rendering.destroy();
assert.equal(h.listeners.size, 0);
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false);
assert.equal(h.listeners.size, 0);
});
test('late asynchronous additions never restore a cleared or destroyed horizon listener', async () => {
for (const method of ['clear', 'destroy']) {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.listeners.size, 0);
h.rendering[method]();
h.completions.shift()();
assert.equal(await pending, false);
assert.equal(h.listeners.size, 0);
}
});
test('real Cesium culls far storms and retains partially visible extents with either globe visibility', async () => {
for (const globeShow of [true, false]) {
const sources = [];
const viewer = {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(0, 0, 350) },
scene: {
globe: { show: globeShow },
preRender: new Cesium.Event(),
requestRender() {},
},
dataSources: {
async add(source) {
sources.push(source);
},
remove() {},
},
};
const overlay = overlayRecorder();
const rendering = createCycloneRendering({
viewer,
cesium: Cesium,
overlayHost: overlay.host,
});
const at = (id, longitude) => ({
...storm(),
id,
position: { longitude, latitude: 0 },
forecastPoints: [{ position: { longitude, latitude: 0 }, tauHours: 24 }],
track: {
type: 'LineString',
coordinates: [
[longitude, 0],
[longitude, 1],
],
},
cone: {
type: 'Polygon',
coordinates: [
[
[longitude, 0],
[longitude + 1, 0],
[longitude, 1],
[longitude, 0],
],
],
},
});
await rendering.setSnapshot({
storms: [at('near', 0), at('far', 180), at('limb', 5)],
});
rendering.setSelection('near');
viewer.scene.preRender.raiseEvent();
const entities = sources[0].entities.values;
for (const entity of entities.filter((e) => e.position)) {
assert.equal(
entity.point.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
assert.equal(entity.point.disableDepthTestDistance.getValue(), Infinity);
assert.equal(entity.label, undefined, 'no Cesium label graphics');
const published = overlay.entry(
entity.id.includes(':forecast:')
? `lead:${entity.id.split(':')[1]}:24`
: `storm:${entity.id.split(':')[1]}`,
);
if (entity.id.startsWith('cyclone:near:')) {
assert.ok(
Cesium.Cartesian3.equals(
published.position,
entity.position.getValue(),
),
);
assert.equal(published.horizonCull, true);
}
if (entity.id === 'cyclone:near:forecast:0')
assert.equal(published.maxDistance, 4_000_000);
}
assert.ok(
entities
.filter((e) => e.id.startsWith('cyclone:near:'))
.every((e) => e.show),
);
assert.ok(
entities
.filter((e) => e.id.startsWith('cyclone:far:'))
.every((e) => !e.show),
);
const limb = entities.filter((e) => e.id.startsWith('cyclone:limb:'));
assert.ok(limb.filter((e) => e.position).every((e) => !e.show));
assert.ok(limb.filter((e) => !e.position).every((e) => e.show));
rendering.destroy();
assert.equal(viewer.scene.preRender.numberOfListeners, 0);
}
});
test('picking accepts exact current owned entities, never prefixes or superseded identities', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const oldEntities = [...h.sources[0].entities.values];
assert.equal(oldEntities.length, 8);
for (const entity of oldEntities) {
assert.equal(h.rendering.pickStorm({ id: entity }), 'ep152026', entity.id);
assert.equal(h.rendering.ownsPickId(entity.id), true);
assert.equal(
h.rendering.pickStorm({ id: { ...entity } }),
null,
'copied ID is not ownership',
);
assert.equal(
h.rendering.pickStorm({ id: entity.id }),
null,
'string prefix is not ownership',
);
}
assert.equal(h.rendering.pickStorm(undefined), null);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false);
await h.rendering.setSnapshot({ storms: [storm()] });
for (const entity of oldEntities)
assert.equal(h.rendering.pickStorm({ id: entity }), null);
const current = h.sources[0].entities.values[0];
assert.equal(h.rendering.pickStorm({ id: current }), 'ep152026');
h.rendering.clear();
assert.equal(h.rendering.pickStorm({ id: current }), null);
assert.equal(h.rendering.ownsPickId(current.id), false);
h.rendering.destroy();
});
test('registry IDs switch only when the next coherent data source commits', async () => {
const h = harness({ deferred: true });
const first = h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
h.completions.shift()();
await first;
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true);
const next = h.rendering.setSnapshot({
storms: [{ ...storm(), id: 'ep162026' }],
const second = createCycloneRendering({
viewer,
overlayHost: overlayRecorder().host,
});
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), true);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
h.completions.shift()();
await next;
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), true);
h.rendering.destroy();
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
assert.equal(draw.sets.size, 6);
second.destroy();
assert.equal(
[...draw.sets.values()].filter((record) => !record.disposed).length,
3,
);
first.destroy();
a.rendering.destroy();
});
test('static entities preserve polygon parts, holes and geographic seam coordinates', async () => {
test('advisory geometry keeps polygon parts, holes and geographic seam coordinates', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const entities = h.sources[0].entities.values;
const cones = entities.filter((e) => e.polygon);
assert.equal(cones.length, 2);
assert.equal(cones[0].polygon.hierarchy.holes.length, 1);
assert.equal(cones[0].polygon.hierarchy.positions[1].lon, -178);
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), true);
const cones = [...h.sets.cones.items.values()];
assert.deepEqual(
cones.map((cone) => cone.id),
['cyclone:ep152026:cone:0', 'cyclone:ep152026:cone:1'],
);
assert.equal(cones[0].geometry.kind, 'polygon');
assert.equal(cones[0].geometry.rings.length, 2, 'the hole stays');
assert.equal(cones[0].geometry.rings[0][1].lon, -178);
for (const cone of cones) {
assert.equal(
cone.polygon.classificationType,
h.cesium.ClassificationType.BOTH,
);
assert.equal(cone.polygon.height, undefined);
assert.equal(cone.polygon.extrudedHeight, undefined);
assert.equal(cone.polygon.outline, undefined);
assert.equal(cone.height, 'clampGround');
assert.equal(cone.fill, 'rgba(127,230,237,0.16)');
assert.equal(cone.outline, undefined, 'outlines are lines of their own');
assert.equal(cone.extrudedHeight, undefined);
}
const outlines = entities.filter((e) => e.id.includes(':outline:'));
const lines = [...h.sets.lines.items.values()];
const outlines = lines.filter((line) => line.id.includes(':outline:'));
assert.equal(outlines.length, 3);
assert.deepEqual(
outlines.map((e) => e.polyline.positions.map((p) => [p.lon, p.lat])),
storm().cone.coordinates.flat(),
outlines.map((line) => line.positions),
storm()
.cone.coordinates.flat()
.map((ring) => ring.map(([lon, lat]) => fromDegrees(lon, lat, 0))),
'lines take ECEF',
);
for (const outline of outlines) {
assert.deepEqual(outline.polyline.material, {
value: '#7fe6ed',
alpha: 0.55,
assert.equal(outline.widthPx, 1);
assert.deepEqual(outline.style, {
kind: 'solid',
color: 'rgba(127,230,237,0.55)',
});
}
for (const { polyline } of entities.filter((e) => e.polyline)) {
assert.equal(polyline.clampToGround, true);
assert.equal(polyline.classificationType, h.cesium.ClassificationType.BOTH);
assert.ok(polyline.positions.every((p) => p.height === 0));
}
assert.equal(
entities.find((e) => e.polyline).polyline.positions[1].lon,
-179,
const track = lines.find((line) => line.id === 'cyclone:ep152026:track:0');
assert.equal(track.widthPx, 2.5);
assert.deepEqual(track.style, { kind: 'solid', color: CYCLONE_ACCENT });
assert.deepEqual(track.positions[1], fromDegrees(-179, 16, 0));
for (const line of lines) assert.equal(line.mode, 'draped');
const points = [...h.sets.points.items.values()];
assert.deepEqual(
points.map((point) => point.id),
['cyclone:ep152026:center', 'cyclone:ep152026:forecast:1'],
'the zero-hour forecast is the center',
);
for (const point of points) {
assert.equal(point.height, 'clampGround');
assert.equal(point.disableDepthTest, Number.POSITIVE_INFINITY);
assert.deepEqual(point.outlineColor, [0, 0, 0, 1]);
}
assert.deepEqual(points[1].color, [1, 1, 1, 1]);
assert.equal(points[1].pixelSize, CYCLONE_MARKER_PX.forecast);
assert.equal(points[0].pixelSize, CYCLONE_MARKER_PX.storm);
assert.equal(points[1].outlineWidth, 1);
assert.equal(points[0].outlineWidth, 2);
assert.deepEqual(h.rendering.getDiagnostics(), {
storms: 1,
tracks: 1,
@@ -536,17 +216,111 @@ test('static entities preserve polygon parts, holes and geographic seam coordina
selectedId: null,
timerActive: false,
});
h.rendering.setSelection('ep152026');
assert.equal(
h.overlay.entry('lead:ep152026:12').position,
entities.find((e) => e.id.endsWith('forecast:0')).position,
);
assert.ok(entities.every((e) => e.label === undefined));
assert.ok(h.rendering.getFocusSphere('ep152026').radius >= 500000);
h.rendering.destroy();
assert.equal(h.sources.length, 0);
assert.ok(Object.values(h.sets).every((record) => record.disposed));
assert.equal(h.rendering.getDiagnostics().entities, 0);
});
test('selection redraws the centers and labels; an unchanged one is quiet', async () => {
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near', name: 'Near' }],
});
const center = (id) => h.sets.points.items.get(`cyclone:${id}:center`);
assert.equal(center('near').pixelSize, 9);
h.rendering.setSelection('near');
assert.equal(center('near').pixelSize, 12);
assert.equal(center('near').color, CYCLONE_SELECTED_ACCENT);
assert.equal(center('ep152026').pixelSize, 9);
assert.equal(center('ep152026').color, CYCLONE_ACCENT);
assert.ok(h.sets.points.items.has('cyclone:near:forecast:1'));
const pointWrites = h.sets.points.writes;
const lineWrites = h.sets.lines.writes;
const publishes = h.overlay.publishes;
h.rendering.setSelection('near');
assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet');
assert.equal(h.sets.points.writes, pointWrites, 'points are not redrawn');
assert.equal(h.sets.lines.writes, lineWrites, 'tracks are not redrawn');
h.rendering.destroy();
});
test('a click names a storm only through a current item of its own sets', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const items = h.items();
assert.equal(items.length, 8);
for (const kind of ['points', 'lines', 'cones'])
for (const id of h.sets[kind].items.keys()) {
assert.equal(h.rendering.pickStorm(h.hit(kind, id)), 'ep152026', id);
assert.equal(h.rendering.ownsPickId(id), true);
assert.equal(
h.rendering.pickStorm({ set: 'other:points', id, surface: false }),
null,
"another layer's set is not ownership",
);
}
assert.equal(
h.rendering.pickStorm({
...h.hit('points', 'cyclone:ep152026:center'),
surface: true,
}),
null,
);
assert.equal(h.rendering.pickStorm(undefined), null);
assert.equal(h.rendering.pickStorm(null), null);
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026')),
null,
'a prefix is not an item',
);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:unknown'), false);
// A newer advisory without the storm drops its ids at once.
await h.rendering.setSnapshot({ storms: [{ ...storm(), id: 'ep162026' }] });
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep152026:center')),
null,
);
assert.equal(h.rendering.ownsPickId('cyclone:ep152026:center'), false);
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')),
'ep162026',
);
h.rendering.clear();
assert.equal(
h.rendering.pickStorm(h.hit('points', 'cyclone:ep162026:center')),
null,
);
assert.equal(h.rendering.ownsPickId('cyclone:ep162026:center'), false);
h.rendering.destroy();
});
test('focus spheres bound the advisory and never shrink below a region', async () => {
const h = harness();
const statusOnly = {
...storm(),
id: 'status',
geometryStatus: 'pending',
};
await h.rendering.setSnapshot({ storms: [storm(), statusOnly] });
const at = ([lon, lat]) => fromDegrees(lon, lat, 0);
const expected = sphereFromPoints([
at([179, 15]),
...storm().track.coordinates[0].map(at),
...storm().cone.coordinates[0][0].map(at),
...storm().cone.coordinates[1][0].map(at),
at([-179, 16]),
]);
const sphere = h.rendering.getFocusSphere('ep152026');
assert.deepEqual(sphere.center, expected.center);
assert.equal(sphere.radius, Math.max(expected.radius, 500_000));
assert.equal(h.rendering.getFocusSphere('status').radius, 500_000);
assert.equal(h.rendering.getFocusSphere('missing'), null);
h.rendering.clear();
assert.equal(h.rendering.getFocusSphere('ep152026'), null);
h.rendering.destroy();
});
test('pending or mismatched advisory geometry never renders even when supplied', async () => {
for (const changed of [
{ geometryStatus: 'pending' },
@@ -554,60 +328,76 @@ test('pending or mismatched advisory geometry never renders even when supplied',
]) {
const h = harness();
await h.rendering.setSnapshot({ storms: [{ ...storm(), ...changed }] });
assert.equal(h.sources[0].entities.values.length, 1);
assert.deepEqual(
h.items().map((item) => item.id),
['cyclone:ep152026:center'],
);
assert.equal(h.rendering.getDiagnostics().tracks, 0);
h.rendering.destroy();
}
});
test('a data-source add settling after disable is removed, without a new owner', async () => {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
h.completions.shift()();
assert.equal(await pending, false);
assert.equal(h.sources.length, 0);
assert.equal(h.rendering.getDiagnostics().dataSources, 0);
});
test('superseded asynchronous additions cannot replace newer geometry', async () => {
const h = harness({ deferred: true });
const old = h.rendering.setSnapshot({ storms: [storm()] });
const latest = h.rendering.setSnapshot({ storms: [] });
h.completions[1]();
assert.equal(await latest, true);
h.completions[0]();
assert.equal(await old, false);
assert.equal(h.sources.length, 1);
assert.equal(h.rendering.getDiagnostics().storms, 0);
h.rendering.destroy();
});
test('aborting a pending add retains the prior complete source', async () => {
const h = harness({ deferred: true });
const initial = h.rendering.setSnapshot({ storms: [storm()] });
h.completions.shift()();
await initial;
test('an aborted or destroyed update keeps what is drawn', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
const controller = new AbortController();
const update = h.rendering.setSnapshot(
{ storms: [] },
{ signal: controller.signal },
);
controller.abort();
h.completions.shift()();
assert.equal(await update, false);
assert.equal(h.sources.length, 1);
await assert.rejects(
h.rendering.setSnapshot({ storms: [] }, { signal: controller.signal }),
);
assert.equal(h.items().length, 8);
assert.equal(h.rendering.getDiagnostics().storms, 1);
h.rendering.destroy();
h.rendering.destroy();
assert.equal(await h.rendering.setSnapshot({ storms: [storm()] }), false);
assert.ok(Object.values(h.sets).every((record) => record.disposed));
});
test('an empty advisory after a full one leaves nothing drawn', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.setSelection('ep152026');
assert.equal(await h.rendering.setSnapshot({ storms: [] }), true);
assert.deepEqual(h.items(), []);
assert.equal(h.rendering.getDiagnostics().entities, 0);
h.rendering.destroy();
h.rendering.setSelection('ep152026');
});
test('clear empties the sets and a later advisory draws again', async () => {
const h = harness();
await h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.setSelection('ep152026');
h.rendering.clear();
assert.equal(h.items().length, 0);
assert.ok(Object.values(h.sets).every((record) => !record.disposed));
assert.deepEqual(h.rendering.getDiagnostics(), {
storms: 0,
tracks: 0,
cones: 0,
forecastPoints: 0,
dataSources: 0,
entities: 0,
selectedId: null,
timerActive: false,
});
await h.rendering.setSnapshot({ storms: [storm()] });
assert.equal(h.items().length, 8);
assert.equal(
h.sets.points.items.get('cyclone:ep152026:center').pixelSize,
9,
'clear drops the selection',
);
h.rendering.destroy();
});
test('labels publish committed anchors to the shared overlay and follow selection and clear', async () => {
const h = harness({ deferred: true });
const pending = h.rendering.setSnapshot({
const h = harness();
await h.rendering.setSnapshot({
storms: [storm(), { ...storm(), id: 'near', name: 'Near' }],
});
assert.equal(h.overlay.calls.length, 0, 'nothing publishes before commit');
h.completions.shift()();
assert.equal(await pending, true);
const entities = h.sources[0].entities.values;
const center = (id) => entities.find((e) => e.id === `cyclone:${id}:center`);
const anchor = (item) => fromDegrees(item.pos.lon, item.pos.lat, 0);
const point = (id) => h.sets.points.items.get(id);
assert.deepEqual(
h.overlay.calls
.slice(0, 2)
@@ -623,24 +413,27 @@ test('labels publish committed anchors to the shared overlay and follow selectio
'no selection, no lead-hour labels',
);
assert.equal(h.overlay.entry('storm:near').title, 'Near');
assert.equal(h.overlay.entry('storm:near').position, center('near').position);
assert.deepEqual(
h.overlay.entry('storm:near').position,
anchor(point('cyclone:near:center')),
'labels sit at the anchors the points use',
);
assert.equal(h.overlay.entry('storm:near').horizonCull, true);
h.rendering.setSelection('near');
assert.equal(center('near').point.pixelSize, 12);
assert.equal(center('ep152026').point.pixelSize, 9);
assert.equal(h.overlay.entry('storm:near').variant, 'selected');
assert.equal(h.overlay.entry('storm:ep152026').variant, 'card');
assert.ok(h.overlay.entry('lead:near:12'));
const publishes = h.overlay.publishes;
h.rendering.setSelection('near');
assert.equal(h.overlay.publishes, publishes, 'unchanged selection is quiet');
assert.deepEqual(
h.overlay.entry('lead:near:12').position,
anchor(point('cyclone:near:forecast:1')),
);
assert.equal(h.overlay.entry('lead:near:12').maxDistance, 4_000_000);
assert.equal(h.overlay.entry('lead:ep152026:12'), null);
// A refresh republishes the new anchors with the retained selection.
const refresh = h.rendering.setSnapshot({
await h.rendering.setSnapshot({
storms: [{ ...storm(), id: 'near', name: 'Near' }],
});
h.completions.shift()();
await refresh;
assert.deepEqual(
h.overlay.published().map((entry) => [entry.id, entry.variant]),
[
@@ -648,22 +441,13 @@ test('labels publish committed anchors to the shared overlay and follow selectio
['lead:near:12', 'card'],
],
);
assert.equal(
h.overlay.entry('storm:near').position,
h.sources[0].entities.values[0].position,
);
// A superseded addition never publishes, and clear hides the source.
const stale = h.rendering.setSnapshot({ storms: [storm()] });
h.rendering.clear();
const afterClear = h.overlay.calls.slice(-2);
assert.deepEqual(afterClear, [
{ kind: 'clear', source: CYCLONE_OVERLAY_SOURCE_ID },
{ kind: 'visible', source: CYCLONE_OVERLAY_SOURCE_ID, visible: false },
]);
h.completions.shift()();
assert.equal(await stale, false);
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
h.rendering.destroy();
assert.equal(h.overlay.calls.at(-1), afterClear[1]);
});
+6 -2
View File
@@ -1,7 +1,11 @@
import { readResponseJsonCapped } from '../../sources/httpBody.js';
// Shared with the AI tools, so no i18n import: these errors stay English here
// and the cyclones layer translates them where it shows them (translateKnown).
const msg = (text) => text;
export const CYCLONE_RESPONSE_LIMIT = 4 * 1024 * 1024;
const malformed = () => new Error('Malformed cyclone snapshot');
const malformed = () => new Error(msg('Malformed cyclone snapshot'));
const text = (value, max = 160) => {
if (
typeof value !== 'string' ||
@@ -215,7 +219,7 @@ export function createCycloneSource({
const abort = () => controller.abort(signal.reason);
signal?.addEventListener('abort', abort, { once: true });
const timer = setTimeout(
() => controller.abort(new Error('Cyclone request timed out')),
() => controller.abort(new Error(msg('Cyclone request timed out'))),
timeoutMs,
);
try {
File diff suppressed because it is too large. Load diff
+9 -2
View File
@@ -21,7 +21,13 @@ export function createDirectionsSource({
signal,
headers: { Accept: 'application/json' },
});
const payload = await response.json();
// Proxy error pages may not be JSON.
let payload = null;
try {
payload = await response.json();
} catch (error) {
if (response.ok) throw error;
}
signal?.throwIfAborted();
// Failures keep their English message and carry the HTTP status and the
// server's refusal text, so the layer can show them in the language.
@@ -39,7 +45,8 @@ export function createDirectionsSource({
{ status: 429, refusal },
);
}
if (!response.ok && !payload?.error)
// A 5xx body may mislabel an outage as a route refusal.
if (response.status >= 500 || (!response.ok && !payload?.error))
throw Object.assign(
new Error(`Routing unavailable (HTTP ${response.status})`),
{ status: response.status },
+12
View File
@@ -41,3 +41,15 @@ test('route failures are surfaced without fallback requests', async () => {
assert.equal(calls, 1);
}
});
test('a routing outage stays an outage when its body carries an error', async () => {
const source = createDirectionsSource({ fetchImpl: async () =>
Response.json({ ok: false, error: 'routing service unavailable' }, { status: 502 }) });
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
});
test('a routing outage page that is not JSON still reads as an outage', async () => {
const source = createDirectionsSource({ fetchImpl: async () =>
new Response('<html>Bad Gateway</html>', { status: 502, headers: { 'content-type': 'text/html' } }) });
await assert.rejects(source.getRoute(query), { status: 502, message: 'Routing unavailable (HTTP 502)' });
});
+117
View File
@@ -0,0 +1,117 @@
// Directions reports its fixed errors as English data (getStats(), and so the
// layer snapshot the voice tools and the analyst read); the Layers panel row
// shows them in the UI language.
import assert from 'node:assert/strict';
import test from 'node:test';
import { setLocale, t as translate } from '../../i18n/index.js';
import { LayerPanel } from '../../ui/layerPanel.js';
import { directionsStats, presentRoutingFailure } from './index.js';
const idle = {
enabled: true,
mode: 'car',
armed: null,
a: null,
b: null,
status: 'idle',
error: null,
route: null,
lastUpdate: null,
};
const cases = [
[{ ...idle, status: 'error' }, 'No route found'],
[
{ ...idle, status: 'error', error: 'Routing timed out' },
'Routing timed out',
],
];
function rowFor(stats) {
return LayerPanel.prototype._buildMetaText({
id: 'directions',
enabled: true,
stats,
});
}
// Route request failures with the proxy's refusal or an HTTP status in them:
// [the request error, its English row error, the row text in the language]
const failures = () => [
[
{ status: 429, refusal: 'route leg too long' },
'route leg too long — try again in a moment',
translate('{error} — try again in a moment', {
error: translate('route leg too long'),
}),
],
[
{ status: 429, refusal: null },
'Routing is rate limited — try again in a moment',
translate('Routing is rate limited — try again in a moment'),
],
[
{ status: 503 },
'Routing unavailable (HTTP 503)',
translate('Routing unavailable (HTTP {status})', { status: 503 }),
],
[
{ status: 0, message: '' },
'Routing unavailable',
translate('Routing unavailable'),
],
];
for (const locale of ['es', 'ru']) {
test(`${locale}: Directions errors stay English in stats and read translated in the row`, (t) => {
t.after(() => setLocale('en'));
setLocale(locale);
for (const [state, english] of cases) {
const stats = directionsStats(state);
assert.equal(stats.error, english);
const row = rowFor(stats);
assert.ok(row.includes(translate(english)), `${locale}: ${row}`);
assert.ok(!row.includes(english), `${locale}: ${row}`);
}
});
}
for (const locale of ['es', 'ru']) {
test(`${locale}: route request failures stay English in stats and read translated in the row`, (t) => {
t.after(() => setLocale('en'));
setLocale(locale);
for (const [failure, english, shown] of failures()) {
const error = presentRoutingFailure(failure);
assert.equal(error, english);
const stats = directionsStats({ ...idle, status: 'error', error });
assert.equal(stats.error, english);
assert.ok(rowFor(stats).includes(shown), `${locale}: ${rowFor(stats)}`);
assert.notEqual(shown, english);
}
// The proxy's refusal after "Routing failed:", and a text it never sends.
for (const [refusal, shownRefusal] of [
['route too long', translate('route too long')],
['something else', 'something else'],
]) {
const row = rowFor(
directionsStats({
...idle,
status: 'error',
error: `Routing failed: ${refusal}`,
}),
);
assert.ok(
row.includes(
translate('Routing failed: {error}', { error: shownRefusal }),
),
`${locale}: ${row}`,
);
}
});
}
test('en: the Directions row shows the English error', () => {
setLocale('en');
const row = rowFor(directionsStats({ ...idle, status: 'error' }));
assert.match(row, /No route found/);
});
Loaded 100 of 4343 files, more files were not shown because too many files have changed in this diff. Show more