Merge remote-tracking branch 'origin/main' into german/cctv-camera-counts

# Conflicts:
#	src/layers/cctv/lifecycle.test.mjs
This commit is contained in:
German Khokhlov committed 2026-11-19 14:34:39 +04:00
commit 2b7a6b0c63
1463 files changed
+48705 -10313

No files matched your search

+19
View File
@@ -336,6 +336,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={}]
+20 -24
View File
@@ -23,7 +23,7 @@ export function createLifecycle({
source,
}) {
const { activateCctvCameraFromWorldClick } = services.activation;
const { resolvePickId, registerPickOwner, unregisterPickOwner } =
const { resolvePickId, registerPickOwner, unregisterPickOwner, clickCard } =
services.picking;
const { onFocusTargetAppear } = services.focus;
const { releaseContinuousRender } = services.render;
@@ -420,6 +420,20 @@ export function createLifecycle({
(event) => {
if (!layerState._enabled) return;
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,
);
@@ -430,29 +444,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. Click positions
// and the recorded rects are both CSS px — direct comparison.
const cardId = layerState._cctvOverlayHost.hitTest(
event.screenPosition.x,
event.screenPosition.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,
+266
View File
@@ -1,6 +1,10 @@
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';
@@ -106,3 +110,265 @@ test('terrain loading and surface changes rerun the view pass', () => {
lifecycle.detachViewListeners();
assert.ok(removed);
});
/** 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']);
});
+24 -7
View File
@@ -12,14 +12,20 @@ export function createNavigation({
source,
}) {
/**
* Finds the camera closest to the 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 pose = parts.model.eyePose();
if (!pose || !layerState._records.length) return null;
const { lat, lon } = pose;
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) {
@@ -36,6 +42,16 @@ export function createNavigation({
return best?.id || null;
}
/**
* 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.
@@ -214,6 +230,7 @@ export function createNavigation({
return (((Math.floor(currentIdx) + delta) % total) + total) % total;
}
return {
nearestCameraIdToPoint,
nearestCameraIdToViewer,
openingCameraId,
reopenNearestCamera,
+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);
}
});