Draw the ALPR layer's markers through the renderer's ports

The ALPR badges were Cesium entities whose billboards the layer changed in
place: the canvas overlay swapped a badge to a faint pick target at its
anchor, selection swapped the image, and unresolved floors clamped to the
ground. They are now one icon set from the draw port, updated in place
through upsert, so selection and the overlay swap change the same
billboard without a rebuild or a blink. Badges keep their scale by
distance, ground clamping and depth-test settings.

Marker state lives in the app (markerState.js): a plain carrier per camera,
registered as the camera's context entity, and a marker set that batches
changes and sends only the icons that draw differently. Clicks on native
badges come from the dispatcher's draw hit. Projection, the on-screen
count, height samples (excluding the layer's own set), the screen-centre
ellipsoid pick and the camera reach the renderer through the query,
camera and frame ports. A resync of the overlay now hands back only the
cameras that leave it, so kept ones are not written twice.

index.js, overlay.js and presentation.js leave the Cesium allow-list; the
layer's entry is Cesium-free, and a caller's own viewer loads the
unbound factories.

Differences the contract does not let us avoid:
- Double-clicking a badge no longer starts the viewer's entity follow,
  since draw items are not entities.
- The terrain fallback for anchors is no longer skipped while the globe
  is hidden: the globe port has no visibility getter.
- Without depth support the query port answers no heights, terrain
  included, so anchors wait for a cached floor there.
- On a viewer with no renderer bound, the surface counts as settled
  when anchors are refined.
This commit is contained in:
Sameh Khamis committed 2026-11-06 23:28:43 -08:00
1 parent faded8a418
commit 2592289612
11 files changed
+719 -534

No files matched your search

+1
View File
@@ -2473,6 +2473,7 @@
"src/layers/alpr/model.js", "src/layers/alpr/model.js",
"src/layers/alpr/policy.js", "src/layers/alpr/policy.js",
"src/layers/alpr/presentation.js", "src/layers/alpr/presentation.js",
"src/geo/horizon.js",
"src/render/cesium/camera.js", "src/render/cesium/camera.js",
"src/render/cesium/frame.js", "src/render/cesium/frame.js",
"src/render/cesium/query.js", "src/render/cesium/query.js",
+97 -111
View File
@@ -4,6 +4,7 @@ import { test } from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs';
import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs';
import alprCamerasLayer, { import alprCamerasLayer, {
createAlprCamerasLayer, createAlprCamerasLayer,
configureAlprSource, configureAlprSource,
@@ -311,7 +312,7 @@ function cameraHarness(layer = alprCamerasLayer) {
}, },
}); });
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 }; let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let source, click, picked; let click, picked;
const credits = new Set(); const credits = new Set();
const viewer = { const viewer = {
creditDisplay: { creditDisplay: {
@@ -336,14 +337,9 @@ function cameraHarness(layer = alprCamerasLayer) {
postRender: new Cesium.Event(), postRender: new Cesium.Event(),
pick: () => picked, pick: () => picked,
}, },
dataSources: {
add: (value) => {
source = value;
},
remove() {},
},
}; };
bindFakeCesiumCamera(viewer); const ports = fakeScenePorts(viewer);
bindFakeCesiumCamera(viewer, ports);
// The renderer's camera port relays moveEnd; the layer's own come on top. // The renderer's camera port relays moveEnd; the layer's own come on top.
const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners; const portMoveEndListeners = viewer.camera.moveEnd.numberOfListeners;
const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction; const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
@@ -366,14 +362,22 @@ function cameraHarness(layer = alprCamerasLayer) {
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput; Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput;
} }
layer.enable(); layer.enable();
const icons = () => {
const set = [...ports.draw.sets.values()].find(
(candidate) => candidate.kind === 'icons' && !candidate.disposed,
);
return set && { ...set, id: set.spec.id };
};
const marker = (id) =>
icons()?.items.has(id)
? getContextStore().entities.get(id)?.entity
: undefined;
return { return {
viewer, viewer,
ports,
portMoveEndListeners, portMoveEndListeners,
requests, requests,
credits, credits,
get source() {
return source;
},
setFetch(fn) { setFetch(fn) {
response = fn; response = fn;
}, },
@@ -386,9 +390,16 @@ function cameraHarness(layer = alprCamerasLayer) {
advance(ms) { advance(ms) {
now += ms; now += ms;
}, },
/** The layer's icon set, as the fake draw port holds it. */
icons,
/** The icon drawn for a camera, or undefined. */
icon: (id) => icons()?.items.get(id),
/** The drawn markers' carriers (their context entities), in draw order. */
markers: () => [...(icons()?.items.keys() ?? [])].map((id) => marker(id)),
marker,
click(id) { click(id) {
const entity = typeof id === 'string' ? source.entities.getById(id) : id; const item = typeof id === 'string' ? icons()?.items.get(id) : null;
picked = entity ? { id: entity } : undefined; picked = item ? { id: { set: icons().id, id: item.id } } : undefined;
click({ position: new Cesium.Cartesian2() }); click({ position: new Cesium.Cartesian2() });
}, },
restore() { restore() {
@@ -452,14 +463,14 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
]), ]),
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
const entities = h.source.entities.values; const entities = h.markers();
assert.equal(alprCamerasLayer.name, 'ALPR Cameras'); assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual( assert.deepEqual(
entities.map((entity) => readEntityRecord(entity)?.labelModel.title), entities.map((entity) => readEntityRecord(entity)?.labelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'], ['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
); );
assert.equal( assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size, new Set(entities.map((entity) => h.icon(entity.id).image)).size,
1, 1,
); );
assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [ assert.deepEqual(readEntityRecord(entities[0])?.labelModel.details, [
@@ -498,7 +509,7 @@ test('the camera label stays English data in a translated interface', async () =
]), ]),
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
h.click(h.source.entities.values[0].id); h.click(h.markers()[0].id);
assert.equal(getSelectedEntityContext().label, 'ALPR camera'); assert.equal(getSelectedEntityContext().label, 'ALPR camera');
assert.equal( assert.equal(
shownEntityLabel(getSelectedEntityContext().label), shownEntityLabel(getSelectedEntityContext().label),
@@ -535,10 +546,7 @@ test('clicking the selected camera or empty map deselects, including after refre
h.expire(); h.expire();
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null); assert.equal(getSelectedEntityContext(), null);
assert.equal( assert.equal(h.icon('alpr:42').size[0], 38);
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
} }
} finally { } finally {
h.restore(); h.restore();
@@ -594,10 +602,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n
alprCamerasLayer.enable(); alprCamerasLayer.enable();
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null); assert.equal(getSelectedEntityContext(), null);
assert.equal( assert.equal(h.icon('alpr:42').size[0], 38);
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
} finally { } finally {
h.restore(); h.restore();
} }
@@ -686,7 +691,7 @@ test('duplicate nodes render once with a count that agrees with the entity set',
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'ready'); assert.equal(alprCamerasLayer.getStats().status, 'ready');
assert.equal(alprCamerasLayer.getStats().count, 1); assert.equal(alprCamerasLayer.getStats().count, 1);
assert.equal(h.source.entities.values.length, 1); assert.equal(h.icons().items.size, 1);
} finally { } finally {
h.restore(); h.restore();
} }
@@ -702,7 +707,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(alprCamerasLayer.getStats().count, 0); assert.equal(alprCamerasLayer.getStats().count, 0);
assert.equal(getSelectedEntityContext(), null); assert.equal(getSelectedEntityContext(), null);
assert.equal(h.source.entities.values.length, 0); assert.equal(h.icons().items.size, 0);
assert.equal(h.requests.length, 1); assert.equal(h.requests.length, 1);
} finally { } finally {
h.restore(); h.restore();
@@ -762,7 +767,7 @@ test('nearby camera moves reuse the snapped query but count and register only in
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(h.requests.length, 1); assert.equal(h.requests.length, 1);
assert.deepEqual( assert.deepEqual(
h.source.entities.values.map((e) => e.id), h.markers().map((e) => e.id),
['alpr:43'], ['alpr:43'],
); );
assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']); assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']);
@@ -809,9 +814,8 @@ test('selected readout samples the rendered ground, not zero elevation or the di
try { try {
let samples = 0; let samples = 0;
h.viewer.scene.sampleHeightSupported = true; h.viewer.scene.sampleHeightSupported = true;
h.viewer.scene.sampleHeight = (point, excluded) => { h.viewer.scene.sampleHeight = () => {
samples += 1; samples += 1;
assert.equal(excluded[0].id, 'alpr:42');
return 187; return 187;
}; };
h.setFetch(async () => h.setFetch(async () =>
@@ -823,7 +827,7 @@ test('selected readout samples the rendered ground, not zero elevation or the di
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
h.click('alpr:42'); h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42'); const entity = h.marker('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian( const anchor = Cesium.Cartographic.fromCartesian(
readEntityRecord(entity)?.displayPosition(), readEntityRecord(entity)?.displayPosition(),
); );
@@ -871,6 +875,7 @@ test('a late network failure after disable cannot resurrect retries or an error
}); });
test('two factories keep their requests, records and destruction independent', async () => { test('two factories keep their requests, records and destruction independent', async () => {
const carriers = new Map();
const services = { const services = {
render: { governorRequestRender() {} }, render: { governorRequestRender() {} },
picking: { registerPickOwner() {}, unregisterPickOwner() {} }, picking: { registerPickOwner() {}, unregisterPickOwner() {} },
@@ -884,7 +889,9 @@ test('two factories keep their requests, records and destruction independent', a
getSelectedEntityContext() { getSelectedEntityContext() {
return null; return null;
}, },
registerEntityContext() {}, registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {}, removeEntityContextsForLayer() {},
selectEntityContext() {}, selectEntityContext() {},
}, },
@@ -930,11 +937,11 @@ test('two factories keep their requests, records and destruction independent', a
await pending; await pending;
assert.equal(first.getStats().count, 0); assert.equal(first.getStats().count, 0);
assert.equal(second.getStats().count, 1); assert.equal(second.getStats().count, 1);
assert.equal(b.source.entities.values[0].id, 'directory:99'); assert.deepEqual([...b.icons().items.keys()], ['directory:99']);
assert.equal(second.source, 'Test camera directory'); assert.equal(second.source, 'Test camera directory');
assert.ok( assert.ok(
readEntityRecord( readEntityRecord(
b.source.entities.values[0], carriers.get('directory:99'),
)?.labelModel.details.includes('Source: Test directory'), )?.labelModel.details.includes('Source: Test directory'),
); );
assert.equal( assert.equal(
@@ -952,6 +959,7 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
// Ground clamping re-samples every marker whenever a photoreal tile streams // Ground clamping re-samples every marker whenever a photoreal tile streams
// in; a whole-city view (about 1,000 cameras) stuttered while zooming. // in; a whole-city view (about 1,000 cameras) stuttered while zooming.
const floors = new Map([['30.2672', 150]]); const floors = new Map([['30.2672', 150]]);
const carriers = new Map();
let resolveCalls = 0; let resolveCalls = 0;
let releaseResolve; let releaseResolve;
const services = { const services = {
@@ -972,7 +980,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
getSelectedEntityContext() { getSelectedEntityContext() {
return null; return null;
}, },
registerEntityContext() {}, registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {}, removeEntityContextsForLayer() {},
selectEntityContext() {}, selectEntityContext() {},
}, },
@@ -993,38 +1003,29 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
const h = cameraHarness(layer); const h = cameraHarness(layer);
try { try {
await layer.update(); await layer.update();
const known = h.source.entities.getById('directory:1'); const known = h.icon('directory:1');
const unknown = h.source.entities.getById('directory:2'); const unknown = () => h.icon('directory:2');
assert.equal( const unknownCarrier = carriers.get('directory:2');
known.billboard.heightReference.getValue(), assert.equal(known.height, 'absolute');
Cesium.HeightReference.NONE,
);
assert.ok( assert.ok(
Math.abs( Math.abs(Cesium.Cartographic.fromCartesian(known.pos).height - 151.5) <
Cesium.Cartographic.fromCartesian(known.position.getValue()).height - 0.01,
151.5,
) < 0.01,
);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
); );
assert.equal(unknown().height, 'clampGround');
assert.equal(resolveCalls, 1); assert.equal(resolveCalls, 1);
const writes = h.icons().writes;
releaseResolve(); releaseResolve();
await new Promise((resolve) => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal( assert.equal(unknown().height, 'absolute');
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.ok( assert.ok(
Math.abs( Math.abs(
Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height - Cesium.Cartographic.fromCartesian(unknown().pos).height - 161.5,
161.5,
) < 0.01, ) < 0.01,
); );
assert.equal(h.icons().writes, writes + 1, 'one write for the move');
assert.equal( assert.equal(
h.source.entities.getById('directory:2'), carriers.get('directory:2'),
unknown, unknownCarrier,
'placed in place, not rebuilt', 'placed in place, not rebuilt',
); );
} finally { } finally {
@@ -1076,23 +1077,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
h.click('alpr:42'); h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42'); const entity = h.marker('alpr:42');
const position = entity.position, const icon = h.icon('alpr:42');
line = entity.polyline;
// Ground-clamped native wedges cost ~40 ms per frame for a downtown view; // Ground-clamped native wedges cost ~40 ms per frame for a downtown view;
// bearings are painted by the overlay for the nearest cameras instead. // bearings are painted by the overlay for the nearest cameras instead.
assert.equal(line, undefined); assert.equal(h.ports.draw.sets.size, 1, 'icons only, no wedge geometry');
assert.equal(entity.polygon, undefined);
let selections = 0, let selections = 0,
clears = 0, clears = 0;
collectionChanges = 0;
window.addEventListener('gev:entity-selected', () => selections++); window.addEventListener('gev:entity-selected', () => selections++);
window.addEventListener('gev:entity-selection-cleared', () => clears++); window.addEventListener('gev:entity-selection-cleared', () => clears++);
h.source.entities.collectionChanged.addEventListener( const writes = h.icons().writes;
(_collection, added, removed) => {
collectionChanges += added.length + removed.length;
},
);
h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 }); h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 });
await alprCamerasLayer.update(); await alprCamerasLayer.update();
h.expire(); h.expire();
@@ -1108,30 +1102,26 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
]), ]),
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity); assert.equal(h.marker('alpr:42'), entity);
assert.equal(entity.position, position); assert.equal(h.icon('alpr:42'), icon, 'the icon is not sent again');
assert.equal(entity.polyline, line);
assert.equal( assert.equal(
getSelectedEntityContext().properties.operator, getSelectedEntityContext().properties.operator,
'Updated directory', 'Updated directory',
); );
assert.equal(selections, 0); assert.equal(selections, 0);
assert.equal(clears, 0); assert.equal(clears, 0);
assert.equal(collectionChanges, 0); assert.equal(h.icons().writes, writes, 'no icon added or removed');
assert.equal(h.requests.length, 2, 'only expiry needs another request'); assert.equal(h.requests.length, 2, 'only expiry needs another request');
h.expire(); h.expire();
h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })])); h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })]));
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity); assert.equal(h.marker('alpr:42'), entity);
assert.equal(
entity.polyline,
undefined,
'removed direction must not persist',
);
assert.ok( assert.ok(
Cesium.Cartesian3.equals( Cesium.Cartesian3.equalsEpsilon(
entity.position.getValue(), h.icon('alpr:42').pos,
Cesium.Cartesian3.fromDegrees(-97.742, 30.2672), Cesium.Cartesian3.fromDegrees(-97.742, 30.2672),
0,
1e-6,
), ),
); );
} finally { } finally {
@@ -1171,7 +1161,7 @@ test('moves inside a pending query do not restart it; moving to another city can
resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })])); resolve(cameraResponse([cameraNode(43, { lat: 51.495, lon: -0.13 })]));
await second; await second;
assert.deepEqual( assert.deepEqual(
h.source.entities.values.map((e) => e.id), h.markers().map((e) => e.id),
['alpr:43'], ['alpr:43'],
); );
} finally { } finally {
@@ -1189,12 +1179,12 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200); camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200);
try { try {
await alprCamerasLayer.update(); await alprCamerasLayer.update();
const entity = h.source.entities.getById('alpr:42'); const entity = h.marker('alpr:42');
h.click('alpr:42'); h.click('alpr:42');
for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) { for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) {
h.setBox(box); h.setBox(box);
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity); assert.equal(h.marker('alpr:42'), entity);
assert.equal(getSelectedEntityContext().id, 'alpr:42'); assert.equal(getSelectedEntityContext().id, 'alpr:42');
assert.equal(h.requests.length, 1); assert.equal(h.requests.length, 1);
} }
@@ -1205,7 +1195,7 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
); );
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.source.entities.values.length, 0); assert.equal(h.icons().items.size, 0);
camera.pickEllipsoid = () => undefined; camera.pickEllipsoid = () => undefined;
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in'); assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
@@ -1400,7 +1390,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an
requests[1].release(); requests[1].release();
await new Promise((done) => setTimeout(done, 0)); await new Promise((done) => setTimeout(done, 0));
assert.equal(requests.length, 2, 'queued final cells are discarded'); assert.equal(requests.length, 2, 'queued final cells are discarded');
assert.equal(h.source.entities.values.length, 0); assert.equal(h.icons().items.size, 0);
layer.enable(); layer.enable();
await layer.update(); await layer.update();
assert.equal( assert.equal(
@@ -1419,10 +1409,11 @@ test('slow ALPR floors share real terrain requests across preparation, render an
} }
}); });
test('map-source changes reposition all ALPR entities and saved native appearances in place', async () => { test('map-source changes reposition all ALPR markers, those under canvas badges too, in place', async () => {
let floor = 180; let floor = 180;
let listener; let listener;
let removed = 0; let removed = 0;
const carriers = new Map();
const records = Array.from({ length: 70 }, (_, i) => ({ const records = Array.from({ length: 70 }, (_, i) => ({
id: `surface:${i}`, id: `surface:${i}`,
latitude: 30.2672 + i * 0.00001, latitude: 30.2672 + i * 0.00001,
@@ -1448,7 +1439,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
context: { context: {
clearSelectedEntityContextForLayer() {}, clearSelectedEntityContextForLayer() {},
getSelectedEntityContext() {}, getSelectedEntityContext() {},
registerEntityContext() {}, registerEntityContext(entity, metadata) {
carriers.set(metadata.id, entity);
},
removeEntityContextsForLayer() {}, removeEntityContextsForLayer() {},
selectEntityContext() {}, selectEntityContext() {},
}, },
@@ -1457,40 +1450,33 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
const h = cameraHarness(layer); const h = cameraHarness(layer);
try { try {
await layer.update(); await layer.update();
const entities = [...h.source.entities.values]; const entities = [...carriers.values()];
// One marker under a canvas badge: its icon is the faint pick target.
const saved = entities[1]; const saved = entities[1];
alprMarkers.write(saved).nativeAppearance = { Object.assign(alprMarkers.write(saved), {
position: saved.position, canvasOwned: true,
heightReference: saved.billboard.heightReference, canvasPosition: Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190),
}; });
saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190);
alprMarkers.write(saved).pickPosition = saved.position;
for (const next of [150, 120, null, 180]) { for (const next of [150, 120, null, 180]) {
floor = next; floor = next;
// Includes a provider switch with the same globe.show value.
h.viewer.scene.globe.show = next !== 180;
listener({ detail: { status: 'ready' } }); listener({ detail: { status: 'ready' } });
for (const entity of entities) { for (const entity of entities) {
assert.equal(h.source.entities.getById(entity.id), entity); const icon = h.icon(entity.id);
assert.ok( assert.ok(
Math.abs( Math.abs(
Cesium.Cartographic.fromCartesian(entity.position.getValue()) Cesium.Cartographic.fromCartesian(icon.pos).height -
.height - (next == null ? 0 : next + 1.5), (next == null ? 0 : next + 1.5),
) < 0.01, ) < 0.01,
`${entity.id} refreshes at ${next}`, `${entity.id} refreshes at ${next}`,
); );
assert.equal( assert.equal(icon.height, next == null ? 'clampGround' : 'absolute');
entity.billboard.heightReference.getValue(), assert.equal(icon.color, undefined, 'drawn as a badge');
next == null
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
);
assert.equal(alprMarkers.read(entity)?.canvasPosition, null); assert.equal(alprMarkers.read(entity)?.canvasPosition, null);
} }
assert.equal( assert.equal(
alprMarkers.read(saved)?.nativeAppearance, alprMarkers.read(saved)?.canvasOwned,
null, false,
'saved appearance restores at the new floor', 'the badge comes back at the new floor',
); );
} }
} finally { } finally {
@@ -1503,7 +1489,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const h = cameraHarness(); const h = cameraHarness();
try { try {
await alprCamerasLayer.update(); await alprCamerasLayer.update();
const previous = h.source.entities.getById('alpr:42'); const previous = h.marker('alpr:42');
const revision = alprCamerasLayer.getStats().renderRevision; const revision = alprCamerasLayer.getStats().renderRevision;
let release; let release;
h.setFetch( h.setFetch(
@@ -1516,7 +1502,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const pending = alprCamerasLayer.update(); const pending = alprCamerasLayer.update();
await alprCamerasLayer.update(); await alprCamerasLayer.update();
assert.equal( assert.equal(
h.source.entities.getById('alpr:42'), h.marker('alpr:42'),
previous, previous,
'do not show an intermediate filtered snapshot while the new query prepares', 'do not show an intermediate filtered snapshot while the new query prepares',
); );
@@ -1526,7 +1512,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
await pending; await pending;
assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1); assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1);
assert.deepEqual( assert.deepEqual(
h.source.entities.values.map((e) => e.id), h.markers().map((e) => e.id),
['alpr:43'], ['alpr:43'],
); );
} finally { } finally {
+25 -31
View File
@@ -1,6 +1,6 @@
import { isFollowing } from '../../data/followed.js'; import { isFollowing } from '../../data/followed.js';
import { isUnavailableCapability } from '../../sources/capability.js'; import { isUnavailableCapability } from '../../sources/capability.js';
import * as Cesium from 'cesium'; import { cameraOf, drawOf, findFrame } from '../../render/rendererOf.js';
import { import {
LAYER_ID, LAYER_ID,
REQUEST_DEBOUNCE_MS, REQUEST_DEBOUNCE_MS,
@@ -15,8 +15,11 @@ import {
alprCredit, alprCredit,
} from './model.js'; } from './model.js';
import { createAlprPresentation } from './presentation.js'; import { createAlprPresentation } from './presentation.js';
import { createAlprMarkerSet } from './markerState.js';
import { t, tn, msg } from '../../i18n/index.js'; import { t, tn, msg } from '../../i18n/index.js';
let instances = 0;
/** /**
* Own one layer's requests, records, display and viewer subscriptions. * Own one layer's requests, records, display and viewer subscriptions.
* A source fetches a bounded box with an AbortSignal and resolves * A source fetches a bounded box with an AbortSignal and resolves
@@ -40,7 +43,8 @@ export function createAlprCamerasLayer({ source, services } = {}) {
const state = { const state = {
viewer: null, viewer: null,
dataSource: null, /** The camera markers, drawn as one icon set. */
markers: createAlprMarkerSet(),
credit: null, credit: null,
creditTimer: null, creditTimer: null,
creditPresented: false, creditPresented: false,
@@ -184,9 +188,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
} }
renderRecords(); renderRecords();
state.retrying = false; state.retrying = false;
setAlprStatus( setAlprStatus(state.markers.size ? 'ready' : 'empty');
state.dataSource.entities.values.length ? 'ready' : 'empty',
);
return; return;
} }
// A move inside an in-flight query must not abort and restart that query. // A move inside an in-flight query must not abort and restart that query.
@@ -254,13 +256,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
// Stale and saturated are independent facts; a cached response that also // Stale and saturated are independent facts; a cached response that also
// hit the cap must still warn about coverage, not just about freshness. // hit the cap must still warn about coverage, not just about freshness.
renderRecords(); renderRecords();
setAlprStatus( setAlprStatus(state.markers.size ? (stale ? 'stale' : 'ready') : 'empty');
state.dataSource.entities.values.length
? stale
? 'stale'
: 'ready'
: 'empty',
);
} catch (error) { } catch (error) {
if ( if (
error?.name === 'AbortError' || error?.name === 'AbortError' ||
@@ -297,13 +293,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
init(viewer) { init(viewer) {
if (state.viewer) throw new Error('ALPR layer is already initialized'); if (state.viewer) throw new Error('ALPR layer is already initialized');
state.viewer = viewer; state.viewer = viewer;
state.dataSource = new Cesium.CustomDataSource('alpr-cameras'); state.markers.attach(
drawOf(viewer).icons({
id: `${LAYER_ID}:${++instances}:markers`,
show: state.enabled,
}),
);
state.credit = alprCredit(source.attribution); state.credit = alprCredit(source.attribution);
viewer.dataSources.add(state.dataSource); state.moveEndRemove = cameraOf(viewer).on('moveEnd', scheduleLoad);
state.moveEndRemove =
viewer.camera.moveEnd.addEventListener(scheduleLoad);
state.postRenderRemove = state.postRenderRemove =
viewer.scene.postRender?.addEventListener(updateSelectedAnchor); findFrame(viewer)?.on('postRender', () => updateSelectedAnchor()) ??
null;
initOverlay(); initOverlay();
installInteraction(viewer); installInteraction(viewer);
}, },
@@ -312,7 +312,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.enabled = true; state.enabled = true;
state.creditPresented = false; state.creditPresented = false;
registerPickOwner(LAYER_ID, (id) => state.recordById.has(id)); 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. // DataLayerManager calls update() right after enable(); it owns the first fetch.
}, },
disable() { disable() {
@@ -326,7 +326,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.pendingQueryBox = null; state.pendingQueryBox = null;
state.loading = false; state.loading = false;
state.retrying = false; state.retrying = false;
if (state.dataSource) state.dataSource.show = false; if (state.markers.icons) state.markers.icons.show = false;
clearSelection(); clearSelection();
clearRendered(); clearRendered();
setAlprStatus('idle'); setAlprStatus('idle');
@@ -345,9 +345,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.clickSubscription?.(); state.clickSubscription?.();
state.clickSubscription = null; state.clickSubscription = null;
clearRendered(); clearRendered();
if (state.dataSource && viewer) state.markers.dispose();
viewer.dataSources.remove(state.dataSource, true);
state.dataSource = null;
state.credit = null; state.credit = null;
state.creditPresented = false; state.creditPresented = false;
state.records = []; state.records = [];
@@ -362,7 +360,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
state.viewer = null; state.viewer = null;
}, },
getRowControls() { getRowControls() {
const count = state.dataSource?.entities.values.length || 0; const count = state.markers.size;
return { return {
chips: [ chips: [
{ {
@@ -422,21 +420,17 @@ export function createAlprCamerasLayer({ source, services } = {}) {
}, },
getStats() { getStats() {
return { return {
count: state.dataSource?.entities.values.length || 0, count: state.markers.size,
countLabel: countLabel:
state.enabled && !state.noCoverage && state.status !== 'zoom-in' state.enabled && !state.noCoverage && state.status !== 'zoom-in'
? Number.isInteger(state.onScreen) ? Number.isInteger(state.onScreen)
? tn( ? tn(
state.dataSource?.entities.values.length || 0, state.markers.size,
'{count} nearby · {onScreen} on screen', '{count} nearby · {onScreen} on screen',
'{count} nearby · {onScreen} on screen', '{count} nearby · {onScreen} on screen',
{ onScreen: state.onScreen }, { onScreen: state.onScreen },
) )
: tn( : tn(state.markers.size, '{count} nearby', '{count} nearby')
state.dataSource?.entities.values.length || 0,
'{count} nearby',
'{count} nearby',
)
: '', : '',
noCoverage: Boolean(state.noCoverage), noCoverage: Boolean(state.noCoverage),
lastUpdate: state.lastUpdate, lastUpdate: state.lastUpdate,
@@ -444,7 +438,7 @@ export function createAlprCamerasLayer({ source, services } = {}) {
saturated: state.saturated || state.renderSaturated, saturated: state.saturated || state.renderSaturated,
renderRevision: state.renderRevision, renderRevision: state.renderRevision,
onScreen: state.onScreen ?? null, onScreen: state.onScreen ?? null,
shown: state.dataSource?.entities.values.length || 0, shown: state.markers.size,
error: state.error, error: state.error,
status: state.status, status: state.status,
loading: state.loading, loading: state.loading,
+164 -5
View File
@@ -1,14 +1,173 @@
/** /**
* @module alpr/markerState * @module alpr/markerState
* @description The ALPR layer's own per-marker state, held in the app rather than on the * @description The ALPR layer's markers: one icon per camera in a draw set,
* Cesium entities it draws: * 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. * - `record`: the camera record the marker shows.
* - `clamped`: whether the marker sits on the surface rather than at its height. * - `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. * - `canvasPosition`, `displayPosition`: the canvas anchor and the position the card reads.
* - `wedge`: the direction wedge's positions, plain ECEF. * - `wedge`: the direction wedge's positions, plain ECEF.
* - `nativeAppearance`, `pickPosition`: the native look saved while the canvas draws it. * - `canvasOwned`: the overlay canvas draws the badge; the icon stays as a
* - `shown`, `surfaceCheckedFor`: the last visibility applied and the anchor last checked. * 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 { 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(); 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,
...(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;
},
};
}
+109 -143
View File
@@ -1,4 +1,3 @@
import * as Cesium from 'cesium';
import { import {
MAX_CANVAS_FRUSTUMS, MAX_CANVAS_FRUSTUMS,
MARKER_ICON_SIZE, MARKER_ICON_SIZE,
@@ -19,9 +18,18 @@ import {
validAlprGroundHeight, validAlprGroundHeight,
} from './visuals.js'; } from './visuals.js';
import { alprMarkers } from './markerState.js'; import { alprMarkers } from './markerState.js';
import { heightsFor } from '../../queries/heights.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({ export function createAlprOverlay({
state, state,
services, services,
@@ -40,76 +48,55 @@ export function createAlprOverlay({
if (!destroyed && state.enabled) lane?.requestPaint(); if (!destroyed && state.enabled) lane?.requestPaint();
}; };
function nativeVisible(entity, visible) { const markers = state.markers;
if (!entity) return;
canvasOwned(entity, !visible); function nativeVisible(carrier, visible) {
setShown(entity, 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) { * Swap a marker between its native look and a faint canvas pick target.
const visible = !owned; * The faint icon stays under the canvas badge, at its anchor, so sibling
const billboard = entity.billboard; * layer handlers recognize ALPR ownership instead of treating the click
const marker = alprMarkers.write(entity); * as empty.
// Keep a faint native pick target under the canvas badge so sibling layer */
// handlers recognize ALPR ownership instead of treating the click as empty. function canvasOwned(carrier, owned) {
if (!visible && !marker.nativeAppearance) { const marker = alprMarkers.write(carrier);
marker.nativeAppearance = { if (Boolean(marker.canvasOwned) === owned) return;
position: entity.position, marker.canvasOwned = owned;
heightReference: billboard.heightReference, markers.changed(carrier);
scaleByDistance: billboard.scaleByDistance,
color: billboard.color,
};
entity.position = marker.canvasPosition;
marker.pickPosition = entity.position;
billboard.heightReference = Cesium.HeightReference.NONE;
billboard.scaleByDistance = undefined;
billboard.color = Cesium.Color.WHITE.withAlpha(0.01);
} else if (visible && marker.nativeAppearance) {
const saved = marker.nativeAppearance;
if (entity.position === marker.pickPosition)
entity.position = saved.position;
billboard.heightReference = saved.heightReference;
billboard.scaleByDistance = saved.scaleByDistance;
billboard.color = saved.color;
marker.nativeAppearance = null;
marker.pickPosition = null;
}
} }
// Assign only on change: each Entity property write mints a new property // Changed only on change: the icon is sent again only when it draws
// and raises definitionChanged, which paint used to do for every overlay // differently.
// camera on every frame. function setShown(carrier, visible) {
function setShown(entity, visible) { const marker = alprMarkers.write(carrier);
const marker = alprMarkers.write(entity); if ((marker.shown ?? true) === visible) return;
if (marker.shown === visible) return;
marker.shown = visible; marker.shown = visible;
entity.billboard.show = visible; markers.changed(carrier);
if (entity.polyline) entity.polyline.show = visible;
if (entity.polygon) entity.polygon.show = visible;
} }
function resetAnchors() { function resetAnchors() {
for (const entity of state.dataSource.entities.values) { for (const carrier of markers.values()) {
const marker = alprMarkers.write(entity); const marker = alprMarkers.write(carrier);
marker.canvasPosition = null; marker.canvasPosition = null;
marker.wedge = null; marker.wedge = null;
marker.displayPosition = null; marker.displayPosition = null;
nativeVisible(entity, true); nativeVisible(carrier, true);
} }
markers.flush();
state.lastAnchorSampleAt = 0; state.lastAnchorSampleAt = 0;
retryUntil = Date.now() + 15000; retryUntil = Date.now() + 15000;
requestPaint(); requestPaint();
} }
function anchorFor(record, entity, budget) { function anchorFor(record, carrier, budget) {
const cached = alprMarkers.read(entity)?.canvasPosition; const cached = alprMarkers.read(carrier)?.canvasPosition;
if (cached) return cached; if (cached) return cached;
const scene = state.viewer.scene; const query = findQuery(state.viewer);
const location = Cesium.Cartographic.fromDegrees( const point = { lon: record.longitude, lat: record.latitude };
record.longitude,
record.latitude,
);
// A floor-placed marker anchors where its native badge sits; only a // A floor-placed marker anchors where its native badge sits; only a
// marker still waiting for its floor samples the rendered surface, and // marker still waiting for its floor samples the rendered surface, and
// each paint samples a few at most (each sample is a depth render). // each paint samples a few at most (each sample is a depth render).
@@ -119,17 +106,17 @@ export function createAlprOverlay({
record.longitude, record.longitude,
); );
if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M; if (validAlprGroundHeight(floor)) height = floor + MARKER_FLOOR_LIFT_M;
else if (scene.sampleHeightSupported) { else if (query) {
if (budget.samples <= 0) return null; if (budget.samples <= 0) return null;
budget.samples -= 1; budget.samples -= 1;
// A miss is tiles still streaming. // A miss is tiles still streaming.
height = heightsFor(scene).now(location, { exclude: [entity] }); height = query.sampleHeightNow(point, { exclude: [markers.icons?.id] });
} }
if (!validAlprGroundHeight(height) && scene.globe.show) if (!validAlprGroundHeight(height))
height = heightsFor(scene).now(location, { against: 'terrain' }); height = query?.sampleHeightNow(point, { against: 'terrain' });
if (!validAlprGroundHeight(height)) return null; if (!validAlprGroundHeight(height)) return null;
setAnchor(record, entity, height); setAnchor(record, carrier, height);
return alprMarkers.read(entity)?.canvasPosition; return alprMarkers.read(carrier)?.canvasPosition;
} }
function floorHeightAt(latitude, longitude) { function floorHeightAt(latitude, longitude) {
@@ -137,24 +124,23 @@ export function createAlprOverlay({
return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null; return validAlprGroundHeight(floor) ? floor + MARKER_FLOOR_LIFT_M : null;
} }
function setAnchor(record, entity, height) { function setAnchor(record, carrier, height) {
const marker = alprMarkers.write(entity); const marker = alprMarkers.write(carrier);
marker.canvasPosition = Cesium.Cartesian3.fromDegrees( marker.canvasPosition = fromDegrees(
record.longitude, record.longitude,
record.latitude, record.latitude,
height, height,
); );
marker.wedge = 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. */ /** Whether the visible photoreal tiles (or globe) have finished streaming. */
function surfaceSettled(scene) { function surfaceSettled() {
if (scene.globe?.show) return scene.globe.tilesLoaded !== false; const globe = rendererOf(state.viewer)?.globe;
for (let i = 0; i < (scene.primitives?.length || 0); i++) { // A viewer with no renderer of its own cannot say; its samples are
const primitive = scene.primitives.get(i); // still checked against the floor.
if (primitive?.show && primitive.tilesLoaded === false) return false; return !globe || (globe.isSettled('terrain') && globe.isSettled('tiles'));
}
return true;
} }
/** /**
@@ -165,47 +151,34 @@ export function createAlprOverlay({
* samples far outside the floor prior (a roof or a streaming tile) are * samples far outside the floor prior (a roof or a streaming tile) are
* rejected. Returns whether anchors remain to check. * rejected. Returns whether anchors remain to check.
*/ */
function refineAnchors(budget) { function refineAnchors(budget, pose) {
const camera = state.viewer.camera;
const scene = state.viewer.scene;
const still = const still =
lastCamera && lastCamera &&
camera.positionWC && near(pose.position, lastCamera.position, 0.05) &&
Cesium.Cartesian3.equalsEpsilon( near(pose.direction, lastCamera.direction, 1e-6);
camera.positionWC,
lastCamera.position,
0,
0.05,
) &&
Cesium.Cartesian3.equalsEpsilon(
camera.directionWC,
lastCamera.direction,
0,
1e-6,
);
if (camera.positionWC && camera.directionWC)
lastCamera = { lastCamera = {
position: Cesium.Cartesian3.clone(camera.positionWC), position: { ...pose.position },
direction: Cesium.Cartesian3.clone(camera.directionWC), direction: { ...pose.direction },
}; };
if (!scene.sampleHeightSupported) return false; const query = findQuery(state.viewer);
if (!query) return false;
let pending = false; let pending = false;
for (const record of records) { for (const record of records) {
const entity = state.dataSource.entities.getById(record.id); const carrier = markers.get(record.id);
const marker = alprMarkers.read(entity); const marker = alprMarkers.read(carrier);
const anchor = marker?.canvasPosition; const anchor = marker?.canvasPosition;
if (!anchor || marker.surfaceCheckedFor === anchor) continue; if (!anchor || marker.surfaceCheckedFor === anchor) continue;
if (!still || !surfaceSettled(scene) || budget.samples <= 0) { if (!still || !surfaceSettled() || budget.samples <= 0) {
pending = true; pending = true;
continue; continue;
} }
budget.samples -= 1; budget.samples -= 1;
// A miss is tiles still streaming. // A miss is tiles still streaming.
const sample = heightsFor(scene).now( const sample = query.sampleHeightNow(
{ lon: record.longitude, lat: record.latitude }, { lon: record.longitude, lat: record.latitude },
{ exclude: [entity] }, { exclude: [markers.icons?.id] },
); );
const current = Cesium.Cartographic.fromCartesian(anchor).height; const current = toLonLatH(anchor)?.height;
const floor = services.groundFloor.cachedGroundFloor( const floor = services.groundFloor.cachedGroundFloor(
record.latitude, record.latitude,
record.longitude, record.longitude,
@@ -216,10 +189,10 @@ export function createAlprOverlay({
(sample >= floor - SURFACE_BELOW_FLOOR_M && (sample >= floor - SURFACE_BELOW_FLOOR_M &&
sample <= floor + SURFACE_ABOVE_FLOOR_M)); sample <= floor + SURFACE_ABOVE_FLOOR_M));
if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1) if (accepted && Math.abs(sample + MARKER_FLOOR_LIFT_M - current) > 1)
setAnchor(record, entity, sample + MARKER_FLOOR_LIFT_M); setAnchor(record, carrier, sample + MARKER_FLOOR_LIFT_M);
// setAnchor rewrote the same record, so this is the new anchor. // setAnchor rewrote the same record, so this is the new anchor.
marker.surfaceCheckedFor = marker.canvasPosition; marker.surfaceCheckedFor = marker.canvasPosition;
if (entity.id === state.selectedId) if (carrier.id === state.selectedId)
marker.displayPosition = marker.canvasPosition; marker.displayPosition = marker.canvasPosition;
} }
return pending; return pending;
@@ -231,9 +204,11 @@ export function createAlprOverlay({
let unresolved = false; let unresolved = false;
const painted = []; const painted = [];
const budget = { samples: ANCHOR_SAMPLES_PER_PAINT }; const budget = { samples: ANCHOR_SAMPLES_PER_PAINT };
const pose = cameraOf(state.viewer).pose();
const query = findQuery(state.viewer);
for (const record of records) { for (const record of records) {
const entity = state.dataSource.entities.getById(record.id); const carrier = markers.get(record.id);
if (!entity) continue; if (!carrier) continue;
const selected = record.id === state.selectedId; const selected = record.id === state.selectedId;
const image = images[selected ? 1 : 0]; const image = images[selected ? 1 : 0];
if ( if (
@@ -241,45 +216,35 @@ export function createAlprOverlay({
!image.naturalWidth || !image.naturalWidth ||
(selected && !images[2]?.naturalWidth) (selected && !images[2]?.naturalWidth)
) { ) {
nativeVisible(entity, true); nativeVisible(carrier, true);
continue; continue;
} }
const anchor = anchorFor(record, entity, budget); const anchor = anchorFor(record, carrier, budget);
if (!anchor) { if (!anchor) {
nativeVisible(entity, true); nativeVisible(carrier, true);
unresolved = true; unresolved = true;
continue; continue;
} }
canvasOwned(entity, true); canvasOwned(carrier, true);
if (occluder && !occluder.isPointVisible(anchor)) { if (occluder && !occluder.isPointVisible(anchor)) {
setShown(entity, false); setShown(carrier, false);
continue; continue;
} }
const scene = state.viewer.scene; const origin = query?.project(anchor);
const origin = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
anchor,
);
if (!origin) { if (!origin) {
setShown(entity, false); setShown(carrier, false);
continue; continue;
} }
const alpha = const alpha =
services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1; services.overlays.keyholeAlpha?.(origin.x, origin.y, keyhole) ?? 1;
if (!(alpha > 0)) { if (!(alpha > 0)) {
setShown(entity, false); setShown(carrier, false);
continue; continue;
} }
const wedge = alprMarkers.read(entity)?.wedge; const wedge = alprMarkers.read(carrier)?.wedge;
if (wedge) { if (wedge) {
const left = Cesium.SceneTransforms.worldToWindowCoordinates( const left = query.project(wedge[1]);
scene, const right = query.project(wedge[2]);
wedge[1],
);
const right = Cesium.SceneTransforms.worldToWindowCoordinates(
scene,
wedge[2],
);
if (left && right) { if (left && right) {
ctx.save(); ctx.save();
ctx.globalAlpha *= alpha; ctx.globalAlpha *= alpha;
@@ -293,21 +258,19 @@ export function createAlprOverlay({
origin.y < -60 || origin.y < -60 ||
origin.y > height + 60 origin.y > height + 60
) { ) {
setShown(entity, false); setShown(carrier, false);
continue; continue;
} }
setShown(entity, true); setShown(carrier, true);
painted.push({ painted.push({
record, record,
origin, origin,
selected, selected,
image, image,
alpha, alpha,
scale: markerScale( scale: markerScale(distance(pose.position, anchor)),
Cesium.Cartesian3.distance(state.viewer.camera.positionWC, anchor),
),
}); });
if (selected) alprMarkers.write(entity).displayPosition = anchor; if (selected) alprMarkers.write(carrier).displayPosition = anchor;
} }
// Paint all glyphs after the wedges so one camera's cone cannot wash out another. // 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) { for (const { record, origin, selected, image, alpha, scale } of painted) {
@@ -333,9 +296,11 @@ export function createAlprOverlay({
ctx.restore(); ctx.restore();
hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 }); hits.push({ id: record.id, x: origin.x, y: origin.y, radius: size / 2 });
} }
const refining = refineAnchors({ const refining = refineAnchors(
samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT), { samples: Math.min(budget.samples, SURFACE_SAMPLES_PER_PAINT) },
}); pose,
);
markers.flush();
if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) { if ((unresolved || refining) && !retryTimer && Date.now() < retryUntil) {
retryTimer = setTimeout(() => { retryTimer = setTimeout(() => {
retryTimer = null; retryTimer = null;
@@ -356,7 +321,7 @@ export function createAlprOverlay({
if (!services.overlays?.registerPaintLane || typeof Image === 'undefined') if (!services.overlays?.registerPaintLane || typeof Image === 'undefined')
return; return;
lane = services.overlays.registerPaintLane('selected', paint, { lane = services.overlays.registerPaintLane('selected', paint, {
id: `alpr-${Cesium.createGuid()}`, id: `alpr-${++lanes}`,
active: false, active: false,
}); });
images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => { images = [MARKER_IMAGE, SELECTED_IMAGE, BRACKETS_IMAGE].map((src) => {
@@ -369,9 +334,8 @@ export function createAlprOverlay({
}, },
sync(visible) { sync(visible) {
if (!lane) return; if (!lane) return;
for (const record of records) const previous = records;
nativeVisible(state.dataSource.entities.getById(record.id), true); const position = cameraOf(state.viewer).pose().position;
const position = state.viewer.camera.positionWC;
records = visible records = visible
.filter( .filter(
(record) => (record) =>
@@ -381,13 +345,10 @@ export function createAlprOverlay({
.map((record) => ({ .map((record) => ({
record, record,
distance: position distance: position
? Cesium.Cartesian3.distanceSquared( ? distance(
position, position,
Cesium.Cartesian3.fromDegrees( fromDegrees(record.longitude, record.latitude),
record.longitude, ) ** 2
record.latitude,
),
)
: 0, : 0,
})) }))
.sort((a, b) => a.distance - b.distance) .sort((a, b) => a.distance - b.distance)
@@ -398,6 +359,11 @@ export function createAlprOverlay({
if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop(); if (records.length >= MAX_CANVAS_FRUSTUMS) records.pop();
records.push(selected); 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 = []; hits = [];
retryUntil = Date.now() + 15000; retryUntil = Date.now() + 15000;
lane.setActive(state.enabled && records.length > 0); lane.setActive(state.enabled && records.length > 0);
@@ -419,8 +385,8 @@ export function createAlprOverlay({
clear() { clear() {
clearTimeout(retryTimer); clearTimeout(retryTimer);
retryTimer = null; retryTimer = null;
for (const record of records) for (const record of records) nativeVisible(markers.get(record.id), true);
nativeVisible(state.dataSource?.entities.getById(record.id), true); markers.flush();
records = []; records = [];
hits = []; hits = [];
lane?.setActive(false); lane?.setActive(false);
+66 -34
View File
@@ -8,7 +8,9 @@ import {
alprLabelDetails, alprLabelDetails,
markerScale, markerScale,
} from './visuals.js'; } from './visuals.js';
import { alprMarkers } from './markerState.js'; import { alprMarkers, createAlprMarkerSet } from './markerState.js';
import { fakeDrawPort } from '../../testSupport/fakeDrawPort.mjs';
import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs';
function harness(t, count = 2, { floor = null } = {}) { function harness(t, count = 2, { floor = null } = {}) {
const previousImage = globalThis.Image; const previousImage = globalThis.Image;
@@ -24,23 +26,29 @@ function harness(t, count = 2, { floor = null } = {}) {
longitude: -97, longitude: -97,
directionDeg: 90, 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) for (const record of records)
entities.add({ Object.assign(alprMarkers.write(markers.add(record.id)), {
id: record.id, record,
billboard: { image: 'fallback', show: true }, position: Cesium.Cartesian3.fromDegrees(
polyline: { show: true }, record.longitude,
polygon: { show: true }, record.latitude,
),
}); });
markers.flush();
const state = { const state = {
enabled: true, enabled: true,
selectedId: null, selectedId: null,
dataSource: { entities }, markers,
viewer: { viewer: {
camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500) }, camera: { positionWC: Cesium.Cartesian3.fromDegrees(-97, 30, 500) },
scene: { globe: { show: true, getHeight: () => 150 } }, scene: { globe: { show: true, getHeight: () => 150 } },
}, },
}; };
const { unbind } = bindFakeCesiumScene(state.viewer, { draw: drawPort });
let paint, let paint,
mapListener, mapListener,
active, active,
@@ -81,6 +89,7 @@ function harness(t, count = 2, { floor = null } = {}) {
if (previousImage === undefined) delete globalThis.Image; if (previousImage === undefined) delete globalThis.Image;
else globalThis.Image = previousImage; else globalThis.Image = previousImage;
Cesium.SceneTransforms.worldToWindowCoordinates = project; Cesium.SceneTransforms.worldToWindowCoordinates = project;
unbind();
}); });
const draw = []; const draw = [];
const ctx = { const ctx = {
@@ -104,7 +113,11 @@ function harness(t, count = 2, { floor = null } = {}) {
state, state,
records, records,
overlay, 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, draw,
paint: (occluder) => paint({ ctx, width: 800, height: 600, occluder }), paint: (occluder) => paint({ ctx, width: 800, height: 600, occluder }),
mapChanged() { mapChanged() {
@@ -132,21 +145,19 @@ 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[0].endsWith('alpr-marker-selected.png'));
assert.ok(h.draw[1].endsWith('alpr-marker-selected-brackets.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.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( assert.equal(h.icon('camera:0').color[3], 0.01, 'a faint pick target');
h.entities.getById('camera:0').billboard.color.getValue().alpha,
0.01,
);
assert.equal(directionWedgePositions(h.records[0]), null); assert.equal(directionWedgePositions(h.records[0]), null);
}); });
test('the overlay bounds its cohort and promotes selection while leaving farther cameras native', (t) => { 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.state.selectedId = 'camera:69';
h.overlay.sync(h.records); h.overlay.sync(h.records);
h.paint(); h.paint();
const hidden = h.entities.values.filter( const hidden = [...h.markers.values()].filter(
(e) => alprMarkers.read(e)?.nativeAppearance, (carrier) => alprMarkers.read(carrier)?.canvasOwned,
); );
assert.equal(hidden.length, 64); assert.equal(hidden.length, 64);
assert.ok(hidden.some((e) => e.id === 'camera:69')); assert.ok(hidden.some((e) => e.id === 'camera:69'));
@@ -163,24 +174,25 @@ test('surface changes invalidate cached anchors, and disable/disposal release pa
const h = harness(t, 1); const h = harness(t, 1);
h.overlay.sync(h.records); h.overlay.sync(h.records);
h.paint(); h.paint();
const entity = h.entities.getById('camera:0'); const carrier = h.carrier('camera:0');
const first = alprMarkers.read(entity)?.canvasPosition; const first = alprMarkers.read(carrier)?.canvasPosition;
h.paint(); h.paint();
assert.equal( assert.equal(
alprMarkers.read(entity)?.canvasPosition, alprMarkers.read(carrier)?.canvasPosition,
first, first,
'stable anchor across frames', 'stable anchor across frames',
); );
h.state.viewer.scene.globe.show = false; h.state.viewer.scene.globe.show = false;
h.mapChanged(); h.mapChanged();
assert.equal(alprMarkers.read(entity)?.canvasPosition, null); assert.equal(alprMarkers.read(carrier)?.canvasPosition, null);
h.state.enabled = false; h.state.enabled = false;
h.overlay.clear(); h.overlay.clear();
assert.equal(h.active, false); assert.equal(h.active, false);
assert.equal(h.overlay.pick({ x: 100, y: 100 }), null); assert.equal(h.overlay.pick({ x: 100, y: 100 }), null);
assert.equal(entity.billboard.show.getValue(), true); const icon = h.icon('camera:0');
assert.equal(entity.billboard.color, undefined); assert.equal(icon.show, true);
assert.equal(entity.position, undefined); assert.equal(icon.color, undefined, 'the native badge again');
assert.equal(icon.pos, alprMarkers.read(carrier).position);
h.overlay.destroy(); h.overlay.destroy();
assert.equal(h.removed, 1); assert.equal(h.removed, 1);
}); });
@@ -190,7 +202,8 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
h.state.viewer.scene.globe.getHeight = () => -15000; h.state.viewer.scene.globe.getHeight = () => -15000;
h.overlay.sync(h.records); h.overlay.sync(h.records);
h.paint(); 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); assert.equal(h.draw.length, 0);
h.state.viewer.scene.globe.getHeight = () => 150; h.state.viewer.scene.globe.getHeight = () => 150;
h.paint({ isPointVisible: () => false }); h.paint({ isPointVisible: () => false });
@@ -198,18 +211,37 @@ test('an unresolved surface preserves the native marker; the horizon removes ove
assert.equal(h.draw.length, 0); assert.equal(h.draw.length, 0);
}); });
test('repeated paints of a still view never rewrite marker properties', (t) => { test('repeated paints of a still view never rewrite markers', (t) => {
// Each Entity write raises definitionChanged; paint used to hide then show // Paint used to hide then show every overlay camera's native marker on
// every overlay camera's native marker on every frame. // every frame.
const h = harness(t, 3); const h = harness(t, 3);
h.overlay.sync(h.records); h.overlay.sync(h.records);
h.paint(); h.paint();
let changes = 0; h.paint();
for (const entity of h.entities.values) const writes = h.iconSet.writes;
entity.definitionChanged.addEventListener(() => changes++);
for (let i = 0; i < 5; i++) h.paint(); for (let i = 0; i < 5; i++) h.paint();
assert.equal(changes, 0); assert.equal(h.iconSet.writes, writes);
assert.equal(h.entities.getById('camera:0').billboard.show.getValue(), true); 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', () => { test('adapter labels never claim a custom source is public OSM data', () => {
@@ -263,7 +295,7 @@ test('a still view replaces floor anchors with the rendered surface, within the
h.paint(); h.paint();
const height = (id) => const height = (id) =>
Cesium.Cartographic.fromCartesian( Cesium.Cartographic.fromCartesian(
alprMarkers.read(h.entities.getById(id))?.canvasPosition, alprMarkers.read(h.carrier(id))?.canvasPosition,
).height; ).height;
assert.equal( assert.equal(
samples, samples,
+151 -206
View File
@@ -1,34 +1,35 @@
import { isFollowing } from '../../data/followed.js'; import { isFollowing } from '../../data/followed.js';
import * as Cesium from 'cesium';
import { inputFor } from '../../input/dispatcher.js'; import { inputFor } from '../../input/dispatcher.js';
import { distance, fromDegrees, toLonLatH } from '../../geo/index.js';
import { import {
LAYER_ID, LAYER_ID,
MAX_VIEWPORT_DEGREES, MAX_VIEWPORT_DEGREES,
MAX_RENDERED, MAX_RENDERED,
ALPR_COLOR, ALPR_COLOR,
ALPR_SELECTED_COLOR, ALPR_SELECTED_COLOR,
MARKER_ICON_SIZE,
SELECTED_MARKER_ICON_SIZE, SELECTED_MARKER_ICON_SIZE,
CREDIT_DISPLAY_MS, CREDIT_DISPLAY_MS,
MARKER_FLOOR_LIFT_M, MARKER_FLOOR_LIFT_M,
MARKER_SCALE_BY_DISTANCE,
} from './policy.js'; } from './policy.js';
import { boxContains } from './model.js'; import { boxContains } from './model.js';
import { msg } from '../../i18n/index.js'; import { msg } from '../../i18n/index.js';
import { createAlprFloorResolver } from './floors.js'; import { createAlprFloorResolver } from './floors.js';
import { createAlprOverlay } from './overlay.js'; import { createAlprOverlay } from './overlay.js';
import { import {
MARKER_IMAGE,
SELECTED_IMAGE,
alprDisplayId, alprDisplayId,
alprLabelDetails, alprLabelDetails,
validAlprGroundHeight, validAlprGroundHeight,
} from './visuals.js'; } from './visuals.js';
import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js';
import { alprMarkers } from './markerState.js'; import { alprIconPosition, alprMarkers } from './markerState.js';
import { heightsFor } from '../../queries/heights.js'; import { horizonFrom } from '../../geo/horizon.js';
import { cameraOf } from '../../render/cesium/camera.js'; import { cameraOf, findCredits, findQuery } from '../../render/rendererOf.js';
import { findCredits } 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 }) { export function createAlprPresentation({ state, services, source }) {
const { governorRequestRender } = services.render; const { governorRequestRender } = services.render;
@@ -41,6 +42,7 @@ export function createAlprPresentation({ state, services, source }) {
} = services.context; } = services.context;
const { cachedGroundFloor } = services.groundFloor; const { cachedGroundFloor } = services.groundFloor;
const markers = state.markers;
const overlay = createAlprOverlay({ const overlay = createAlprOverlay({
state, state,
services, services,
@@ -48,11 +50,35 @@ export function createAlprPresentation({ state, services, source }) {
}); });
let visibleRecords = []; let visibleRecords = [];
let selectionStartedAt = 0; 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(); const clampedMarkers = new Map();
let floorResolve = null; let floorResolve = null;
const floors = createAlprFloorResolver(services.groundFloor); 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 * Marker placement from the cached ground floor (validated mesh or DEM, the
* ellipsoidal datum every layer shares). Ground clamping on photoreal tiles * ellipsoidal datum every layer shares). Ground clamping on photoreal tiles
@@ -60,14 +86,14 @@ export function createAlprPresentation({ state, services, source }) {
* whole-city view stutter while zooming, so it is only the placeholder for * whole-city view stutter while zooming, so it is only the placeholder for
* a cell that has not resolved yet. * a cell that has not resolved yet.
* @param {{latitude:number, longitude:number}} record Camera. * @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) { function markerPlacement(record) {
const floor = cachedGroundFloor(record.latitude, record.longitude); const floor = cachedGroundFloor(record.latitude, record.longitude);
const clamped = !validAlprGroundHeight(floor); const clamped = !validAlprGroundHeight(floor);
return { return {
clamped, clamped,
position: Cesium.Cartesian3.fromDegrees( position: fromDegrees(
record.longitude, record.longitude,
record.latitude, record.latitude,
clamped ? 0 : floor + MARKER_FLOOR_LIFT_M, clamped ? 0 : floor + MARKER_FLOOR_LIFT_M,
@@ -136,25 +162,18 @@ export function createAlprPresentation({ state, services, source }) {
* @returns {number|null} Count, or null without a scene to project into. * @returns {number|null} Count, or null without a scene to project into.
*/ */
function countOnScreen() { function countOnScreen() {
const scene = state.viewer?.scene; const canvas = state.viewer?.scene?.canvas;
const canvas = scene?.canvas;
const width = canvas?.clientWidth || canvas?.width; const width = canvas?.clientWidth || canvas?.width;
const height = canvas?.clientHeight || canvas?.height; const height = canvas?.clientHeight || canvas?.height;
const camera = state.viewer?.camera; const query = findQuery(state.viewer);
if (!scene || !width || !height || !camera?.positionWC) return null; if (!query || !width || !height) return null;
const occluder = new Cesium.EllipsoidalOccluder(
Cesium.Ellipsoid.WGS84,
camera.positionWC,
);
let count = 0; let count = 0;
try { try {
for (const entity of state.dataSource.entities.values) { const horizon = horizonFrom(cameraOf(state.viewer).pose().position);
const position = entity.position?.getValue?.(Cesium.JulianDate.now()); for (const carrier of markers.values()) {
if (!position || !occluder.isPointVisible(position)) continue; const position = alprIconPosition(carrier);
const point = Cesium.SceneTransforms.worldToWindowCoordinates( if (!position || !horizon.isPointVisible(position)) continue;
scene, const point = query.project(position);
position,
);
if ( if (
point && point &&
point.x >= 0 && point.x >= 0 &&
@@ -171,33 +190,26 @@ export function createAlprPresentation({ state, services, source }) {
return count; return count;
} }
/** Write a marker position, respecting the overlay's pick-target swap. */ /** Write a marker's native placement; the canvas anchor is left alone. */
function setMarkerPosition(entity, position, clamped) { function setMarkerPosition(carrier, position, clamped) {
const heightReference = clamped const marker = alprMarkers.write(carrier);
? Cesium.HeightReference.CLAMP_TO_GROUND marker.position = position;
: Cesium.HeightReference.NONE; marker.clamped = clamped;
const saved = alprMarkers.read(entity)?.nativeAppearance; markers.changed(carrier);
if (saved) {
saved.position = position;
saved.heightReference = heightReference;
} else {
entity.position = position;
entity.billboard.heightReference = heightReference;
}
alprMarkers.write(entity).clamped = clamped;
} }
/** Refresh all native placements, including the appearances held by the canvas. */ /** Refresh all native placements, including those under canvas badges. */
function refreshMarkerPlacements() { function refreshMarkerPlacements() {
if (!state.enabled || !state.dataSource) return; if (!state.enabled || !markers.icons) return;
clampedMarkers.clear(); clampedMarkers.clear();
for (const entity of state.dataSource.entities.values) { for (const carrier of markers.values()) {
const { position, clamped } = markerPlacement( const { position, clamped } = markerPlacement(
alprMarkers.read(entity)?.record, alprMarkers.read(carrier)?.record,
); );
setMarkerPosition(entity, position, clamped); setMarkerPosition(carrier, position, clamped);
if (clamped) clampedMarkers.set(entity.id, entity); if (clamped) clampedMarkers.set(carrier.id, carrier);
} }
markers.flush();
resolveClampedFloors(); resolveClampedFloors();
governorRequestRender('alpr-surface'); governorRequestRender('alpr-surface');
} }
@@ -210,8 +222,8 @@ export function createAlprPresentation({ state, services, source }) {
const batch = [...clampedMarkers.values()]; const batch = [...clampedMarkers.values()];
const request = Promise.resolve( const request = Promise.resolve(
floors.resolve( floors.resolve(
batch.map((entity) => { batch.map((carrier) => {
const { record } = alprMarkers.read(entity); const { record } = alprMarkers.read(carrier);
return { lat: record.latitude, lon: record.longitude }; return { lat: record.latitude, lon: record.longitude };
}), }),
), ),
@@ -220,65 +232,55 @@ export function createAlprPresentation({ state, services, source }) {
.then(() => { .then(() => {
if (floorResolve !== request) return; if (floorResolve !== request) return;
floorResolve = null; floorResolve = null;
if (!state.enabled || !state.dataSource) return; if (!state.enabled || !markers.icons) return;
let moved = false; let moved = false;
for (const entity of batch) { for (const carrier of batch) {
if (clampedMarkers.get(entity.id) !== entity) continue; if (clampedMarkers.get(carrier.id) !== carrier) continue;
clampedMarkers.delete(entity.id); clampedMarkers.delete(carrier.id);
const { position, clamped } = markerPlacement( const { position, clamped } = markerPlacement(
alprMarkers.read(entity)?.record, alprMarkers.read(carrier)?.record,
); );
if (clamped) continue; if (clamped) continue;
setMarkerPosition(entity, position, false); setMarkerPosition(carrier, position, false);
moved = true; moved = true;
} }
markers.flush();
if (moved) governorRequestRender('alpr-floor'); if (moved) governorRequestRender('alpr-floor');
// Cells that never resolved stay clamped; later renders retry them. // Cells that never resolved stay clamped; later renders retry them.
}); });
floorResolve = request; floorResolve = request;
} }
function updateAppearance(entity, selected) { function updateAppearance(carrier, selected) {
const color = Cesium.Color.fromCssColorString( alprMarkers.write(carrier).selected = selected;
selected ? ALPR_SELECTED_COLOR : ALPR_COLOR, markers.changed(carrier);
); const labelModel = readEntityRecord(carrier)?.labelModel;
entity.billboard.image = selected ? SELECTED_IMAGE : MARKER_IMAGE;
entity.billboard.width = entity.billboard.height = selected
? SELECTED_MARKER_ICON_SIZE
: MARKER_ICON_SIZE;
const labelModel = readEntityRecord(entity)?.labelModel;
if (labelModel) { if (labelModel) {
labelModel.accent = color.toCssColorString(); labelModel.accent = cssRgb(selected ? ALPR_SELECTED_COLOR : ALPR_COLOR);
labelModel.leaderAnimationStartedAt = selected ? selectionStartedAt : 0; 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 horizon rectangle is unstable during low-angle orbits and can exclude
// the ground point in the center of the screen. Bound nearby coverage around // 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. // that point instead; the camera-to-ground range keeps zoom-out queries capped.
function viewportBox(viewer) { function viewportBox(viewer) {
const camera = viewer?.camera; const query = findQuery(viewer);
const canvas = viewer?.scene.canvas; const canvas = viewer?.scene?.canvas;
if (typeof camera?.pickEllipsoid === 'function' && canvas) { if (typeof query?.pickEllipsoid === 'function' && canvas) {
const width = canvas.clientWidth || canvas.width; const width = canvas.clientWidth || canvas.width;
const height = canvas.clientHeight || canvas.height; const height = canvas.clientHeight || canvas.height;
if (!width || !height) return null; if (!width || !height) return null;
const focus = camera.pickEllipsoid( const focus = query.pickEllipsoid(width / 2, height / 2);
new Cesium.Cartesian2(width / 2, height / 2),
viewer.scene.globe.ellipsoid,
);
if (!focus) return null; if (!focus) return null;
const location = Cesium.Cartographic.fromCartesian(focus); const location = toLonLatH(focus);
const range = Cesium.Cartesian3.distance(camera.positionWC, focus); if (!location) return null;
const range = distance(cameraOf(viewer).pose().position, focus);
const radius = Math.max(1000, 2 * range); const radius = Math.max(1000, 2 * range);
const latitude = Cesium.Math.toDegrees(location.latitude); const latitude = location.lat;
const longitude = Cesium.Math.toDegrees(location.longitude); const longitude = location.lon;
const latSpan = radius / 111000; const latSpan = radius / 111000;
const lonSpan = latSpan / Math.cos(location.latitude); const lonSpan = latSpan / Math.cos((latitude * Math.PI) / 180);
if ( if (
!Number.isFinite(latSpan + lonSpan) || !Number.isFinite(latSpan + lonSpan) ||
2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES || 2 * Math.max(latSpan, lonSpan) > MAX_VIEWPORT_DEGREES ||
@@ -294,14 +296,9 @@ export function createAlprPresentation({ state, services, source }) {
}; };
} }
// Rectangle-only viewers retain the same bounded-area contract. // Rectangle-only viewers retain the same bounded-area contract.
const rectangle = viewer?.camera?.computeViewRectangle( const rectangle = viewer ? cameraOf(viewer).viewRectangle() : null;
viewer.scene.globe.ellipsoid,
);
if (!rectangle) return null; if (!rectangle) return null;
const south = Cesium.Math.toDegrees(rectangle.south); const { south, north, west, east } = rectangle;
const north = Cesium.Math.toDegrees(rectangle.north);
const west = Cesium.Math.toDegrees(rectangle.west);
const east = Cesium.Math.toDegrees(rectangle.east);
if ( if (
!Number.isFinite(south + north + west + east) || !Number.isFinite(south + north + west + east) ||
east <= west || east <= west ||
@@ -319,7 +316,7 @@ export function createAlprPresentation({ state, services, source }) {
overlay.clear(); overlay.clear();
visibleRecords = []; visibleRecords = [];
clampedMarkers.clear(); clampedMarkers.clear();
if (state.dataSource?.entities) state.dataSource.entities.removeAll(); markers.clear();
removeEntityContextsForLayer(LAYER_ID); removeEntityContextsForLayer(LAYER_ID);
} }
@@ -369,62 +366,45 @@ export function createAlprPresentation({ state, services, source }) {
governorRequestRender('alpr-render'); governorRequestRender('alpr-render');
const visibleIds = new Set(visible.map((record) => record.id)); const visibleIds = new Set(visible.map((record) => record.id));
let changed = false; let changed = false;
state.dataSource.entities.suspendEvents(); const gone = [];
for (const entity of [...state.dataSource.entities.values]) { for (const carrier of markers.values())
if (!visibleIds.has(entity.id)) { if (!visibleIds.has(carrier.id)) gone.push(carrier.id);
state.dataSource.entities.remove(entity); if (gone.length) {
clampedMarkers.delete(entity.id); markers.remove(gone);
for (const id of gone) clampedMarkers.delete(id);
changed = true; changed = true;
} }
}
removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds }); removeEntityContextsForLayer(LAYER_ID, { retainIds: visibleIds });
for (const record of visible) { for (const record of visible) {
const existing = state.dataSource.entities.getById(record.id); const existing = markers.get(record.id);
if (alprMarkers.read(existing)?.record === record) { if (alprMarkers.read(existing)?.record === record) {
updateAppearance(existing, record.id === state.selectedId); updateAppearance(existing, record.id === state.selectedId);
continue; continue;
} }
const color = markerColor();
const selected = record.id === state.selectedId; const selected = record.id === state.selectedId;
const { position, clamped } = markerPlacement(record); const { position, clamped } = markerPlacement(record);
// Direction wedges are painted by the overlay for the nearest cameras. // Direction wedges are painted by the overlay for the nearest cameras.
// Native ground-clamped wedges (a ground polyline plus a classification // Native ground-clamped wedges (a ground polyline plus a classification
// polygon per camera) cost ~40 ms per frame for 200 downtown cameras on // polygon per camera) cost ~40 ms per frame for 200 downtown cameras on
// photoreal tiles, so markers stay billboards only. // photoreal tiles, so markers stay icons only.
const entityDef = { let carrier = existing;
id: record.id, // Keep the marker and its icon while its geometry is unchanged.
position, // Updating metadata must not rebuild the marker.
billboard: { const previous = alprMarkers.read(carrier)?.record;
image: selected ? SELECTED_IMAGE : MARKER_IMAGE, if (!carrier) {
width: selected ? SELECTED_MARKER_ICON_SIZE : MARKER_ICON_SIZE, carrier = markers.add(record.id);
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 = alprMarkers.read(entity)?.record;
if (!entity) {
entity = state.dataSource.entities.add(entityDef);
changed = true; changed = true;
} }
const marker = alprMarkers.write(entity); const marker = alprMarkers.write(carrier);
if (!existing) { if (!existing) {
marker.position = position;
marker.clamped = clamped; marker.clamped = clamped;
} else { } else {
if ( if (
previous.latitude !== record.latitude || previous.latitude !== record.latitude ||
previous.longitude !== record.longitude previous.longitude !== record.longitude
) { ) {
setMarkerPosition(entity, position, clamped); setMarkerPosition(carrier, position, clamped);
marker.canvasPosition = null; marker.canvasPosition = null;
marker.displayPosition = null; marker.displayPosition = null;
} }
@@ -438,16 +418,16 @@ export function createAlprPresentation({ state, services, source }) {
} }
} }
marker.record = record; marker.record = record;
entityRecord(entity).trackedId = record.id; entityRecord(carrier).trackedId = record.id;
// The mapped camera datum has no elevation; it is not the clamped marker's // The mapped camera datum has no elevation; it is not the clamped marker's
// visual anchor. Only the selected marker samples the rendered surface, // visual anchor. Only the selected marker samples the rendered surface,
// at most once per second, through Cesium's public height APIs. // at most once per second, through the renderer's height queries.
marker.displayPosition ??= null; marker.displayPosition ??= null;
entityRecord(entity).displayPosition = () => marker.displayPosition; entityRecord(carrier).displayPosition = () => marker.displayPosition;
entityRecord(entity).labelModel = { entityRecord(carrier).labelModel = {
title: alprDisplayId(record), title: alprDisplayId(record),
details: alprLabelDetails(record, source), details: alprLabelDetails(record, source),
accent: color.toCssColorString(), accent: cssRgb(ALPR_COLOR),
cardStyle: 'tactical', cardStyle: 'tactical',
selected: true, selected: true,
leaderStyle: 'elbow', leaderStyle: 'elbow',
@@ -457,11 +437,12 @@ export function createAlprPresentation({ state, services, source }) {
anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2, anchorRadiusPx: SELECTED_MARKER_ICON_SIZE / 2,
anchorRadiusScale: null, anchorRadiusScale: null,
}; };
updateAppearance(entity, selected); updateAppearance(carrier, selected);
registerEntityContext(entity, { registerEntityContext(carrier, {
id: record.id, id: record.id,
layerId: LAYER_ID, layerId: LAYER_ID,
dataSource: state.dataSource, // Hidden with the layer: the context store reads its `show`.
dataSource: markers.icons,
layerName: 'ALPR Cameras', layerName: 'ALPR Cameras',
source: source:
source.attribution?.description || source.label || 'Camera source', source.attribution?.description || source.label || 'Camera source',
@@ -481,64 +462,46 @@ export function createAlprPresentation({ state, services, source }) {
}, },
}); });
} }
state.dataSource.entities.resumeEvents();
if (changed) state.renderRevision += 1; if (changed) state.renderRevision += 1;
state.onScreen = countOnScreen(); state.onScreen = countOnScreen();
for (const entity of state.dataSource.entities.values) for (const carrier of markers.values())
if (alprMarkers.read(entity)?.clamped) if (alprMarkers.read(carrier)?.clamped)
clampedMarkers.set(entity.id, entity); clampedMarkers.set(carrier.id, carrier);
resolveClampedFloors(); resolveClampedFloors();
const selectedEntity = state.selectedId const selectedCarrier = state.selectedId
? state.dataSource.entities.getById(state.selectedId) ? markers.get(state.selectedId)
: null; : null;
if (!selectedEntity) state.selectedId = null; if (!selectedCarrier) state.selectedId = null;
updateSelectedAnchor(); updateSelectedAnchor();
overlay.sync(visible); 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. // Keep the on-map credit tied to displayed data, not loading or zoom prompts.
if (visible.length) presentOnMapCredit(); if (visible.length) presentOnMapCredit();
else hideOnMapCredit(); else hideOnMapCredit();
} }
function focusNearest() { function focusNearest() {
const camera = state.viewer?.camera; if (!state.enabled || !state.viewer || isFollowing(state.viewer))
if (!state.enabled || !camera?.positionWC || isFollowing(state.viewer))
return false; return false;
const port = cameraOf(state.viewer);
const eye = port.pose().position;
let nearest = null, let nearest = null,
distance = Infinity; best = Infinity;
for (const entity of state.dataSource.entities.values) { for (const carrier of markers.values()) {
const position = entity.position.getValue(Cesium.JulianDate.now()); const position = alprIconPosition(carrier);
const candidate = Cesium.Cartesian3.distanceSquared( if (!position) continue;
camera.positionWC, const candidate = distance(eye, position);
position, if (candidate < best) {
); nearest = carrier;
if (candidate < distance) { best = candidate;
nearest = entity;
distance = candidate;
} }
} }
if (!nearest) return false; if (!nearest) return false;
const record = state.recordById.get(nearest.id); const record = state.recordById.get(nearest.id);
const location = Cesium.Cartographic.fromDegrees( const height = groundHeight(record);
record.longitude, const center = fromDegrees(record.longitude, record.latitude, height ?? 0);
record.latitude,
);
const heights = heightsFor(state.viewer.scene);
// A miss is tiles still streaming.
let height = state.viewer.scene.sampleHeightSupported
? heights.now(location, { exclude: [nearest] })
: null;
if (!validAlprGroundHeight(height) && state.viewer.scene.globe.show)
height = heights.now(location, { against: 'terrain' });
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
const center = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
validAlprGroundHeight(height) ? height : 0,
);
if (!selectRecord(nearest.id)) return false; if (!selectRecord(nearest.id)) return false;
const port = cameraOf(state.viewer);
port.flyToBounds( port.flyToBounds(
{ center, radius: 30 }, { center, radius: 30 },
{ {
@@ -555,29 +518,29 @@ export function createAlprPresentation({ state, services, source }) {
} }
function selectRecord(id) { function selectRecord(id) {
const entity = state.dataSource?.entities.getById(id); const carrier = markers.get(id);
if (!entity || !state.recordById.has(id)) return false; if (!carrier || !state.recordById.has(id)) return false;
clearSelection(); clearSelection();
state.selectedId = id; state.selectedId = id;
selectionStartedAt = globalThis.performance?.now?.() ?? Date.now(); selectionStartedAt = globalThis.performance?.now?.() ?? Date.now();
updateAppearance(entity, true); updateAppearance(carrier, true);
state.lastAnchorSampleAt = 0; state.lastAnchorSampleAt = 0;
selectEntityContext(entity); selectEntityContext(carrier);
updateSelectedAnchor(); updateSelectedAnchor();
overlay.sync(visibleRecords); overlay.sync(visibleRecords);
markers.flush();
governorRequestRender('alpr-selection'); governorRequestRender('alpr-selection');
return true; return true;
} }
function clearSelection() { function clearSelection() {
const entity = state.selectedId const carrier = state.selectedId ? markers.get(state.selectedId) : null;
? state.dataSource?.entities.getById(state.selectedId)
: null;
const record = state.recordById.get(state.selectedId); const record = state.recordById.get(state.selectedId);
if (entity && record) updateAppearance(entity, false); if (carrier && record) updateAppearance(carrier, false);
state.selectedId = null; state.selectedId = null;
selectionStartedAt = 0; selectionStartedAt = 0;
overlay.sync(visibleRecords); overlay.sync(visibleRecords);
markers.flush();
clearSelectedEntityContextForLayer(LAYER_ID); clearSelectedEntityContextForLayer(LAYER_ID);
governorRequestRender('alpr-selection'); governorRequestRender('alpr-selection');
} }
@@ -589,39 +552,22 @@ export function createAlprPresentation({ state, services, source }) {
clearSelection(); clearSelection();
return; return;
} }
const entity = state.dataSource?.entities.getById(state.selectedId); const carrier = markers.get(state.selectedId);
const record = state.recordById.get(state.selectedId); const record = state.recordById.get(state.selectedId);
const marker = alprMarkers.read(entity); const marker = alprMarkers.read(carrier);
if (marker?.canvasPosition) { if (marker?.canvasPosition) {
marker.displayPosition = marker.canvasPosition; marker.displayPosition = marker.canvasPosition;
return; return;
} }
if (!entity || !record || Date.now() - state.lastAnchorSampleAt < 1000) if (!carrier || !record || Date.now() - state.lastAnchorSampleAt < 1000)
return; return;
state.lastAnchorSampleAt = Date.now(); state.lastAnchorSampleAt = Date.now();
const scene = state.viewer.scene; const height = groundHeight(record);
const location = Cesium.Cartographic.fromDegrees( if (height === null) return;
record.longitude, const next = fromDegrees(record.longitude, record.latitude, height);
record.latitude,
);
const heights = heightsFor(scene);
// A miss is tiles still streaming.
let height = scene.sampleHeightSupported
? heights.now(location, { exclude: [entity] })
: null;
if (!validAlprGroundHeight(height) && scene.globe.show)
height = heights.now(location, { against: 'terrain' });
if (!validAlprGroundHeight(height))
height = cachedGroundFloor(record.latitude, record.longitude);
if (!validAlprGroundHeight(height)) return;
const next = Cesium.Cartesian3.fromDegrees(
record.longitude,
record.latitude,
height,
);
const shown = marker?.displayPosition; const shown = marker?.displayPosition;
if (!shown || Cesium.Cartesian3.distance(next, shown) > 0.1) { if (!shown || distance(next, shown) > 0.1) {
alprMarkers.write(entity).displayPosition = next; alprMarkers.write(carrier).displayPosition = next;
governorRequestRender('alpr-anchor'); governorRequestRender('alpr-anchor');
} }
} }
@@ -631,10 +577,10 @@ export function createAlprPresentation({ state, services, source }) {
state.clickSubscription = inputFor(viewer).onClick((event) => { state.clickSubscription = inputFor(viewer).onClick((event) => {
if (!state.enabled) return; if (!state.enabled) return;
// The painted overlay answers first; the scene is picked only if not. // The painted overlay answers first; the scene is picked only if not.
const pickedId = event.pick?.id?.id; const hit = event.drawHit;
const id = const id =
overlay.pick(event.screenPosition) || overlay.pick(event.screenPosition) ||
(typeof pickedId === 'string' ? pickedId : null); (hit && hit.set === markers.icons?.id ? hit.id : null);
if ( if (
id && id &&
state.recordById.has(id) && state.recordById.has(id) &&
@@ -647,7 +593,6 @@ export function createAlprPresentation({ state, services, source }) {
return { return {
initOverlay: () => overlay.init(), initOverlay: () => overlay.init(),
destroyOverlay: () => overlay.destroy(), destroyOverlay: () => overlay.destroy(),
markerColor,
viewportBox, viewportBox,
clearRendered, clearRendered,
hideOnMapCredit, hideOnMapCredit,
+82
View File
@@ -1193,6 +1193,88 @@ test('the installations layer draws its named markers as outlined point primitiv
assert.equal(scene.added.includes(host), false); assert.equal(scene.added.includes(host), false);
}); });
test('the ALPR layer draws its badges as icons that follow the ground, restyled in place', async () => {
const { alprMarkers, createAlprMarkerSet } =
await import('../../layers/alpr/markerState.js');
const { MARKER_IMAGE, SELECTED_IMAGE } =
await import('../../layers/alpr/visuals.js');
const scene = fakeScene();
const part = createCesiumDraw({
scene,
report: (error) => assert.fail(error),
});
const markers = createAlprMarkerSet();
markers.attach(part.port.icons({ id: 'alpr-cameras:1:markers' }));
const place = (id, lon, clamped) => {
const carrier = markers.add(id);
Object.assign(alprMarkers.write(carrier), {
position: Cesium.Cartesian3.fromDegrees(lon, 30, clamped ? 0 : 150),
clamped,
});
return carrier;
};
const a = place('alpr:a', -97, true);
place('alpr:b', -97.01, false);
markers.flush();
const [host] = scene.added;
assert.ok(host instanceof Cesium.BillboardCollection);
assert.equal(host.length, 2);
const badge = host.get(0);
assert.equal(badge.id.id, 'alpr:a');
assert.equal(badge.id.set, 'alpr-cameras:1:markers');
assert.equal(badge.heightReference, Cesium.HeightReference.CLAMP_TO_GROUND);
assert.equal(
host.get(1).heightReference,
Cesium.HeightReference.NONE,
'a marker on its floor sits at its height',
);
assert.equal(badge.image, MARKER_IMAGE);
assert.equal(badge.width, 38);
assert.equal(badge.disableDepthTestDistance, Infinity);
assert.ok(
Cesium.NearFarScalar.equals(
badge.scaleByDistance,
new Cesium.NearFarScalar(500, 1.15, 40000, 0.45),
),
);
// Selection swaps the image on the same billboard: no blink.
alprMarkers.write(a).selected = true;
markers.changed(a);
markers.flush();
assert.equal(scene.added[0], host);
assert.equal(host.get(0), badge);
assert.equal(badge.image, SELECTED_IMAGE);
assert.equal(badge.width, 60);
// Under a canvas badge: a faint pick target at the canvas anchor.
const anchor = Cesium.Cartesian3.fromDegrees(-97, 30, 172);
Object.assign(alprMarkers.write(a), {
canvasOwned: true,
canvasPosition: anchor,
});
markers.changed(a);
markers.flush();
assert.equal(host.get(0), badge, 'still the same billboard');
assert.equal(badge.color.alpha, 0.01);
assert.equal(badge.heightReference, Cesium.HeightReference.NONE);
assert.equal(badge.scaleByDistance, undefined);
assert.ok(Cesium.Cartesian3.equalsEpsilon(badge.position, anchor, 0, 1e-6));
// A marker that arrives later joins the same collection.
place('alpr:c', -97.02, false);
markers.flush();
assert.equal(scene.added[0], host, 'appended, not rebuilt');
assert.equal(host.get(0), badge);
assert.equal(host.length, 3);
markers.remove(['alpr:b']);
assert.equal(scene.added[0], host);
assert.equal(host.length, 2);
markers.dispose();
assert.equal(scene.added.length, 0);
});
/** Run `fn` with the image classes Cesium's materials test uniforms against. */ /** Run `fn` with the image classes Cesium's materials test uniforms against. */
function withImageClasses(fn) { function withImageClasses(fn) {
const names = [ const names = [
-3
View File
@@ -40,9 +40,6 @@
"src/input/dispatcher.js", "src/input/dispatcher.js",
"src/input/sensorPick.js", "src/input/sensorPick.js",
"src/layers/airQuality/index.js", "src/layers/airQuality/index.js",
"src/layers/alpr/index.js",
"src/layers/alpr/overlay.js",
"src/layers/alpr/presentation.js",
"src/layers/cctv/cards.js", "src/layers/cctv/cards.js",
"src/layers/cctv/geometry.js", "src/layers/cctv/geometry.js",
"src/layers/cctv/geometryQueue.js", "src/layers/cctv/geometryQueue.js",
+1
View File
@@ -77,6 +77,7 @@ const DRAW_FROM_CALLER = new Set([
'./layers/perimeters', './layers/perimeters',
'./layers/awareness', './layers/awareness',
'./layers/submarine-cables', './layers/submarine-cables',
'./layers/alpr',
]); ]);
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
+23 -1
View File
@@ -9,7 +9,9 @@
* `positionCartographic`; `viewRectangle()` from its * `positionCartographic`; `viewRectangle()` from its
* `computeViewRectangle()`, in degrees; events from its own `moveEnd`, * `computeViewRectangle()`, in degrees; events from its own `moveEnd`,
* `moveStart` and `changed`. * `moveStart` and `changed`.
* - query: `project` (and `projectMany`) through `Cesium.SceneTransforms.worldToWindowCoordinates` * - query: `sampleHeightNow` through the scene's height service;
* `pickEllipsoid` through the double camera's, when it has one; `project`
* (and `projectMany`) through `Cesium.SceneTransforms.worldToWindowCoordinates`
* (which a test may stub), `isOccluded` against the ellipsoid's horizon * (which a test may stub), `isOccluded` against the ellipsoid's horizon
* from the camera's `positionWC` (never occluded without one). * from the camera's `positionWC` (never occluded without one).
* - frame: phases from the scene's own `preUpdate`, `preRender` and * - frame: phases from the scene's own `preUpdate`, `preRender` and
@@ -18,6 +20,7 @@
*/ */
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { bindRenderer } from '../render/rendererOf.js'; import { bindRenderer } from '../render/rendererOf.js';
import { heightsFor } from '../queries/heights.js';
import { fakeDrawPort } from './fakeDrawPort.mjs'; import { fakeDrawPort } from './fakeDrawPort.mjs';
const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z); const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z);
@@ -51,6 +54,15 @@ export function fakeSceneQuery(viewer) {
); );
return s ? { x: s.x, y: s.y } : null; return s ? { x: s.x, y: s.y } : null;
}, },
/** The double camera's own, when it has one. */
get pickEllipsoid() {
const camera = cameraOfDouble(viewer);
if (typeof camera?.pickEllipsoid !== 'function') return undefined;
return (x, y) => {
const hit = camera.pickEllipsoid(new Cesium.Cartesian2(x, y));
return hit ? plain(hit) : null;
};
},
projectMany(source, out) { projectMany(source, out) {
for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) { for (let i = 0, j = 0; i + 2 < source.length; i += 3, j += 2) {
const s = this.project({ const s = this.project({
@@ -62,6 +74,16 @@ export function fakeSceneQuery(viewer) {
out[j + 1] = s ? s.y : Number.NaN; out[j + 1] = s ? s.y : Number.NaN;
} }
}, },
// The scene's own height service, the surface only where the scene has
// depth support. Unlike the Cesium port it samples terrain without depth
// support too, and sees through nothing (`exclude` is ignored).
sampleHeightNow(point, { against = 'surface' } = {}) {
if (against === 'terrain')
return heightsFor(viewer.scene).now(point, { against: 'terrain' });
return viewer.scene?.sampleHeightSupported
? heightsFor(viewer.scene).now(point)
: null;
},
isOccluded(position) { isOccluded(position) {
const eye = cameraOfDouble(viewer)?.positionWC; const eye = cameraOfDouble(viewer)?.positionWC;
if (!eye) return false; if (!eye) return false;