Draw radio, transit and CCTV through one display each

- Radio: stations, clusters, the selection and its brackets are point
  and sprite sets; clusters come from the layer's engine-neutral screen
  clusterer with Cesium's EntityCluster rules, and clicks go through the
  selection dispatcher. One style module holds the sizes and colours.
- Transit: vehicles are two sprite sets from an up-front atlas, rotated
  with Cesium's projected-rotation maths. The selected vehicle's trail is
  engine.lines in two lanes and 29 age bands, so trails are no longer
  draped over terrain until the contract has ground corridors. The
  Cesium contact trail renderer and its re-export go.
- CCTV: markers, wedges, the plane outline and the calibration gizmo
  (rings, arrows, handles, drags through engine.input) draw on the
  contract. The textured monitor plane and the viewshed volume, which no
  primitive expresses yet, sit behind one seam, render/meshes.js, with a
  Cesium backend and a Navara backend the Navara mode passes in.

Known gaps against Cesium: transit trails are not draped, and the
surveillance-lens click correction runs only where the engine reports
its style stage (Navara).

Coupling: layer renderer lines fall from 2638/8735 to 1636/6953
(Cesium/Navara), ScreenSpaceEventHandler files from 15 to 10, `viewer`
lines from 2014 to 1901.
This commit is contained in:
German Khokhlov committed 2026-11-07 04:29:50 +04:00
1 parent fc75e245a6
commit dc1144b947
68 files changed
+6216 -5326

No files matched your search

+96 -136
View File
@@ -27,6 +27,9 @@ function componentFunctionSource(fn) {
}
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import * as geo from '../geo/index.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import { createCesiumMoversEngine } from '../testSupport/cesiumMoversEngine.mjs';
import cctvLayer, {
CCTV_PROJECTION_OVERLAY_SOURCE_OPTIONS,
_createCctvProjectionPlaneForTest,
@@ -291,29 +294,12 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
coverageEntities: [],
projection: null,
}));
const inserted = [];
const viewer = {
entities: {
add(entity) {
inserted.push(entity);
return entity;
},
getById(id) {
return inserted.find((entity) => entity.id === id);
},
remove(entity) {
const index = inserted.indexOf(entity);
if (index < 0) return false;
inserted.splice(index, 1);
return true;
},
},
};
const engine = createFakeEngine();
const activeRecord = records.at(-1);
try {
_setCctvCoverageStateForTest({
viewer,
engine,
records,
activeCameraId: activeRecord.camera.id,
});
@@ -323,7 +309,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
(record) => record.coverageEntities.length > 0,
);
assert.equal(
inserted.length,
engine.lines.list().length,
14 * 5,
'default COVERAGE ON builds the 14-camera visible cohort',
);
@@ -345,7 +331,7 @@ test('default COVERAGE refresh materializes the active and visible camera frustu
projection: { planeEntity: { show: false } },
};
_setCctvCoverageStateForTest({
viewer,
engine,
records: [projectionOnly],
activeCameraId: projectionOnly.camera.id,
coverageMode: 'off',
@@ -372,13 +358,13 @@ test('camera icons are violet for video feeds, cyan for stills, amber when activ
const idleVideo = record('idle-hls', 'hls');
const idleStill = record('idle-image', 'image');
const activeVideo = record('active-hls', 'hls');
const viewer = { entities: { add: (entity) => entity, getById: () => undefined } };
const engine = createFakeEngine();
try {
// Disabled keeps the active video camera from opening a real projection;
// icon colors are assigned either way.
_setCctvCoverageStateForTest({
viewer,
engine,
records: [idleVideo, idleStill, activeVideo],
activeCameraId: activeVideo.camera.id,
enabled: false,
@@ -751,7 +737,7 @@ test('real active monitor plane owns one protected host label and no native labe
setVisible: (...args) => calls.push(['visible', ...args]),
clearSource: (...args) => calls.push(['clear', ...args]),
};
const viewer = { entities: new Cesium.EntityCollection() };
const { engine, viewer } = createCesiumMoversEngine();
const record = {
camera: {
...UNCLAMPED_CAMERA,
@@ -764,9 +750,9 @@ test('real active monitor plane owns one protected host label and no native labe
};
_setCctvOverlayHostForTest(overlayHost);
try {
const runtime = _createCctvProjectionPlaneForTest(viewer, record);
const runtime = _createCctvProjectionPlaneForTest(engine, record);
_setCctvCoverageStateForTest({
viewer,
engine,
records: [record],
activeCameraId: record.camera.id,
enabled: true,
@@ -777,13 +763,11 @@ test('real active monitor plane owns one protected host label and no native labe
assert.ok(
runtime.planeEntity,
'runtime guard requires a real monitor-plane entity',
);
assert.equal(runtime.planeEntity.label, undefined);
assert.ok(
runtime.planeEntity.plane,
'monitor plane geometry remains native',
'runtime guard requires a real monitor plane',
);
const planeEntity = viewer.entities.getById(runtime.planeEntity.id);
assert.equal(planeEntity.label, undefined);
assert.ok(planeEntity.plane, 'monitor plane geometry remains native');
assert.ok(
viewer.entities.values.every((entity) => entity.label === undefined),
);
@@ -821,7 +805,7 @@ test('real active monitor plane owns one protected host label and no native labe
);
_setCctvCoverageStateForTest({
viewer,
engine,
records: [record],
activeCameraId: null,
enabled: false,
@@ -830,6 +814,7 @@ test('real active monitor plane owns one protected host label and no native labe
});
refreshCoverageStyles();
assert.equal(runtime.planeEntity.show, false);
assert.equal(planeEntity.show, false);
assert.deepEqual(calls.slice(-2), [
['clear', 'cctv-projection'],
['visible', 'cctv-projection', false],
@@ -837,6 +822,7 @@ test('real active monitor plane owns one protected host label and no native labe
} finally {
_setCctvCoverageStateForTest({ enabled: false });
_setCctvOverlayHostForTest();
engine.destroy();
}
});
@@ -886,16 +872,19 @@ test('CCTV disable→enable defers the active-camera re-probe until its next act
);
});
test('CCTV focus distinguishes tracking ownership from a missing active camera', () => {
let flyCalls = 0;
const viewer = {
trackedEntity: { id: 'tracked-flight' },
camera: {
flyToBoundingSphere() {
flyCalls += 1;
},
},
/** A globe engine whose sphere flights are counted, following `following`. */
function focusEngine(following = null) {
const engine = createFakeEngine();
engine.camera.following = () => following;
engine.flights = 0;
engine.camera.flyToSphere = () => {
engine.flights += 1;
};
return engine;
}
test('CCTV focus distinguishes tracking ownership from a missing active camera', () => {
const engine = focusEngine({ name: 'tracked-flight' });
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -904,49 +893,38 @@ test('CCTV focus distinguishes tracking ownership from a missing active camera',
console.debug = () => {};
try {
assert.equal(
focusCctvRecord(viewer, record, 1.9),
focusCctvRecord(engine, record, 1.9),
CCTV_FOCUS_RESULT.TRACKING_HOLDS_VIEW,
);
} finally {
console.debug = originalDebug;
}
assert.equal(flyCalls, 0);
assert.equal(engine.flights, 0);
assert.equal(
focusCctvRecord(viewer, null, 1.9),
focusCctvRecord(engine, null, 1.9),
CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA,
);
assert.equal(
focusCctvRecord(null, record, 1.9),
CCTV_FOCUS_RESULT.NO_ACTIVE_CAMERA,
);
});
test('CCTV focus reports when the camera flight starts', () => {
let flyCalls = 0;
const viewer = {
trackedEntity: null,
camera: {
flyToBoundingSphere() {
flyCalls += 1;
},
},
};
const engine = focusEngine();
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
};
assert.equal(focusCctvRecord(viewer, record, 1.9), CCTV_FOCUS_RESULT.FOCUSED);
assert.equal(flyCalls, 1);
assert.equal(focusCctvRecord(engine, record, 1.9), CCTV_FOCUS_RESULT.FOCUSED);
assert.equal(engine.flights, 1);
assert.equal(engine.movers.list().length + engine.lines.list().length, 0);
});
test('CCTV focus refuses camera flights while cockpit owns the view', () => {
const originalDocument = globalThis.document;
let flyCalls = 0;
const viewer = {
trackedEntity: null,
camera: {
flyToBoundingSphere() {
flyCalls += 1;
},
},
};
const engine = focusEngine();
const record = {
camera: { rangeM: 210, headingDeg: 41 },
position: { x: 1, y: 2, z: 3 },
@@ -959,14 +937,14 @@ test('CCTV focus refuses camera flights while cockpit owns the view', () => {
try {
assert.equal(
focusCctvRecord(viewer, record, 1.9),
focusCctvRecord(engine, record, 1.9),
CCTV_FOCUS_RESULT.COCKPIT_ACTIVE,
);
} finally {
console.debug = originalDebug;
globalThis.document = originalDocument;
}
assert.equal(flyCalls, 0);
assert.equal(engine.flights, 0);
});
// Both initial mount and live engine switches install the same click handler.
@@ -1026,33 +1004,21 @@ test('CCTV repeated in-world clicks dispatch focus only for the one real activat
// ─── Empty-space deselection and stable null-active state ──────────────────
function makeDeselectViewer() {
return {
entities: new Cesium.EntityCollection(),
isDestroyed: () => false,
trackedEntity: { id: 'sibling-track-owner' },
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 4_000),
positionCartographic: Cesium.Cartographic.fromDegrees(
-97.7431,
30.2672,
4_000,
),
heading: 0.4,
pitch: -0.7,
roll: 0.1,
transform: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
flyToBoundingSphere() {
this.flyCalls = (this.flyCalls || 0) + 1;
},
},
scene: {
canvas: { clientWidth: 1200, clientHeight: 800 },
cartesianToCanvasCoordinates: () => undefined,
primitives: { add: (primitive) => primitive, remove: () => true },
requestRender() {},
},
};
/** A globe engine over Austin whose camera a sibling layer follows. */
function makeDeselectEngine() {
const engine = createFakeEngine({
longitude: toRad(-97.7431),
latitude: toRad(30.2672),
altitude: 4_000,
width: 1200,
height: 800,
});
engine.fake.script('worldToWindow', undefined);
engine.camera.follow({
position: () => geo.cartesian3.fromDegrees(-97.7431, 30.2672, 0),
viewFrom: { x: 0, y: -300, z: 300 },
});
return engine;
}
function makeDeselectRecord(id, index = 0) {
@@ -1143,30 +1109,26 @@ test('CCTV empty-click gate excludes every identified scene object, ADJUST, and
});
test('CCTV camera extraction requires layer ownership, not a colliding sibling ID', () => {
const billboard = { id: 'shared-id' };
const ownedCoverageEntity = {
id: 'cctv-shared-id-cap',
properties: { cctvCameraId: 'shared-id' },
};
const record = {
...makeDeselectRecord('shared-id'),
billboard,
coverageEntities: [ownedCoverageEntity],
};
const engine = createFakeEngine();
const record = makeDeselectRecord('shared-id');
_setCctvCoverageStateForTest({
engine,
records: [record],
activeCameraId: 'shared-id',
});
try {
refreshCoverageStyles();
const cap = record.coverageEntities.find(
(line) => line._coverageRole === 'cap',
);
assert.equal(cap.id, 'cctv-shared-id-cap');
assert.equal(
_extractPickedCameraIdForTest({ id: 'shared-id', primitive: billboard }),
_extractPickedCameraIdForTest({ id: 'shared-id', owner: 'cctv' }),
'shared-id',
"a pick of this layer's marker set activates its camera",
);
assert.equal(
_extractPickedCameraIdForTest({
id: 'shared-id',
primitive: { id: 'shared-id' },
}),
_extractPickedCameraIdForTest({ id: 'shared-id', owner: 'sibling' }),
null,
'a sibling primitive with the same canonical ID cannot activate CCTV',
);
@@ -1176,9 +1138,14 @@ test('CCTV camera extraction requires layer ownership, not a colliding sibling I
'a sibling Entity with the same canonical ID cannot activate CCTV',
);
assert.equal(
_extractPickedCameraIdForTest({ id: ownedCoverageEntity }),
_extractPickedCameraIdForTest({ id: cap.id, owner: cap.id }),
'shared-id',
'an exact stored CCTV coverage Entity retains activation ownership',
'an exact stored CCTV coverage line retains activation ownership',
);
assert.equal(
_extractPickedCameraIdForTest({ id: cap.id, owner: 'sibling-line' }),
null,
'a sibling line cannot borrow the coverage pick id',
);
assert.equal(
_extractPickedCameraIdForTest({
@@ -1196,7 +1163,7 @@ test('CCTV camera extraction requires layer ownership, not a colliding sibling I
});
test('CCTV deselect publishes one null state and leaves the complete camera pose unchanged', () => {
const viewer = makeDeselectViewer();
const engine = makeDeselectEngine();
const record = {
...makeDeselectRecord('deselect-me'),
probeClampRangeM: 150,
@@ -1209,9 +1176,9 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
hitTest: () => null,
});
try {
const runtime = _createCctvProjectionPlaneForTest(viewer, record);
const runtime = _createCctvProjectionPlaneForTest(engine, record);
_setCctvCoverageStateForTest({
viewer,
engine,
records: [record],
activeCameraId: record.camera.id,
enabled: true,
@@ -1223,17 +1190,10 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
publications.push(state),
);
const baselinePublications = publications.length;
const pose = {
positionWC: Cesium.Cartesian3.clone(viewer.camera.positionWC),
positionCartographic: Cesium.Cartographic.clone(
viewer.camera.positionCartographic,
),
heading: viewer.camera.heading,
pitch: viewer.camera.pitch,
roll: viewer.camera.roll,
transform: Cesium.Matrix4.clone(viewer.camera.transform),
trackedEntity: viewer.trackedEntity,
};
const pose = engine.camera.pose();
const transform = engine.camera.transform();
const following = engine.camera.following();
engine.fake.resetCalls();
assert.equal(deactivateActiveCamera(), true);
assert.equal(
@@ -1248,17 +1208,17 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
assert.equal(runtime.planeEntity.show, false);
assert.equal(record.probeClampRangeM, null);
assert.equal(record.activationDone, false);
assert.deepEqual(viewer.camera.positionWC, pose.positionWC);
assert.deepEqual(engine.camera.pose(), pose);
assert.deepEqual(engine.camera.transform(), transform);
assert.equal(engine.camera.following(), following);
assert.ok(following, 'the sibling still follows its target');
assert.deepEqual(
viewer.camera.positionCartographic,
pose.positionCartographic,
engine.fake.calls
.map(({ method }) => method)
.filter((method) => method.startsWith('camera.')),
[],
'no camera command',
);
assert.equal(viewer.camera.heading, pose.heading);
assert.equal(viewer.camera.pitch, pose.pitch);
assert.equal(viewer.camera.roll, pose.roll);
assert.deepEqual(viewer.camera.transform, pose.transform);
assert.equal(viewer.trackedEntity, pose.trackedEntity);
assert.equal(viewer.camera.flyCalls || 0, 0);
unsubscribe();
} finally {
_setCctvOverlayHostForTest();
@@ -1267,7 +1227,7 @@ test('CCTV deselect publishes one null state and leaves the complete camera pose
});
test('CCTV null-active coverage, auto-hop, cycling, and panel targets stay honest', () => {
const viewer = makeDeselectViewer();
const engine = makeDeselectEngine();
const records = Array.from({ length: 3 }, (_, index) =>
makeDeselectRecord(`cam-${index}`, index),
);
@@ -1278,7 +1238,7 @@ test('CCTV null-active coverage, auto-hop, cycling, and panel targets stay hones
});
try {
_setCctvCoverageStateForTest({
viewer,
engine,
records,
activeCameraId: records[0].camera.id,
enabled: true,
+23 -26
View File
@@ -5,6 +5,7 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import cctvLayer, {
_setCctvCoverageStateForTest,
_viewRecordIdsForTest,
@@ -48,22 +49,18 @@ function recordsAt(
return { records, screenByPosition };
}
function viewerAt(heightM, screenByPosition, shiftX = 0) {
return {
isDestroyed: () => false,
camera: {
positionWC: Cesium.Cartesian3.fromDegrees(0, 0, heightM),
positionCartographic: { latitude: 0, longitude: 0, height: heightM },
frustum: { fovy: Math.PI / 3 },
},
scene: {
canvas: { clientWidth: WIDTH, clientHeight: HEIGHT },
cartesianToCanvasCoordinates: (position) => {
const screen = screenByPosition.get(position);
return screen && { x: screen.x + shiftX, y: screen.y };
},
},
};
/** A globe engine over lon 0, lat 0 that draws each record where `screenByPosition` says. */
function engineAt(heightM, screenByPosition, shiftX = 0) {
const engine = createFakeEngine({
width: WIDTH,
height: HEIGHT,
altitude: heightM,
});
engine.fake.script('worldToWindow', (position) => {
const screen = screenByPosition.get(position);
return screen && { x: screen.x + shiftX, y: screen.y };
});
return engine;
}
function shownIds(records) {
@@ -84,7 +81,7 @@ const CLUSTER = [
test('zoomed out, cameras sharing a ground cell show one icon', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
engine: engineAt(20_000, screenByPosition),
records,
});
assert.equal(
@@ -104,7 +101,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () =>
y: 300,
}));
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
engine: engineAt(20_000, screenByPosition),
records,
});
refreshHorizonCulling();
@@ -112,7 +109,7 @@ test('a pan keeps the same winners, and an unchanged view keeps its list', () =>
const list = _viewRecordIdsForTest();
for (const shiftX of [3, 11, 20, 37]) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition, shiftX),
engine: engineAt(20_000, screenByPosition, shiftX),
records,
});
refreshHorizonCulling();
@@ -126,7 +123,7 @@ test('a small zoom within one cell size keeps the same winners', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
const shownAt = (heightM) => {
_setCctvCoverageStateForTest({
viewer: viewerAt(heightM, screenByPosition),
engine: engineAt(heightM, screenByPosition),
records,
});
refreshHorizonCulling();
@@ -142,7 +139,7 @@ test('a healthy camera wins its cell over an unknown one', () => {
// Whichever camera the id order would pick, the healthy one must win.
for (const id of ['cam-0', 'cam-1']) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
engine: engineAt(20_000, screenByPosition),
records,
healthById: new Map([[id, { status: 'ok' }]]),
});
@@ -155,7 +152,7 @@ test('the active camera always shows, even in a crowded cell', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 3));
for (const active of records) {
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
engine: engineAt(20_000, screenByPosition),
records,
activeCameraId: active.camera.id,
});
@@ -175,7 +172,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () =>
index === 2 ? { x: WIDTH * 3, y: HEIGHT / 2 } : { x: 100, y: 100 },
);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
engine: engineAt(300, screenByPosition),
records,
});
refreshHorizonCulling();
@@ -185,7 +182,7 @@ test('close up, every camera near the screen shows and far-off ones hide', () =>
test('a disabled layer skips the view pass', () => {
const { records, screenByPosition } = recordsAt(CLUSTER);
_setCctvCoverageStateForTest({
viewer: viewerAt(20_000, screenByPosition),
engine: engineAt(20_000, screenByPosition),
records,
enabled: false,
});
@@ -196,7 +193,7 @@ test('a disabled layer skips the view pass', () => {
test('UI state builds the full camera list only when it is read', () => {
const { records, screenByPosition } = recordsAt(CLUSTER.slice(0, 2));
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
engine: engineAt(300, screenByPosition),
records,
});
refreshHorizonCulling();
@@ -236,7 +233,7 @@ test('the camera picker lists the view, with the active camera first', () => {
(index) => (index === 1 ? { x: WIDTH * 3, y: 0 } : { x: 100, y: 100 }),
);
_setCctvCoverageStateForTest({
viewer: viewerAt(300, screenByPosition),
engine: engineAt(300, screenByPosition),
records,
activeCameraId: 'cam-1',
});
-4
View File
@@ -1,4 +0,0 @@
export {
createContactTrailRenderer,
trailAlpha,
} from './render/cesiumContactTrailRenderer.js';
-357
View File
@@ -1,357 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { readFileSync } from 'node:fs';
import { TRAIL_VERTEX_LIMIT } from '../layers/transit/trails.js';
import {
createContactTrailRenderer,
trailAlpha,
} from './contactTrailRenderer.js';
function fixture(t, ground = false) {
for (const key of [
'HTMLCanvasElement',
'HTMLImageElement',
'ImageBitmap',
'OffscreenCanvas',
]) {
const prior = globalThis[key];
globalThis[key] = class {};
t.after(() => {
if (prior === undefined) delete globalThis[key];
else globalThis[key] = prior;
});
}
const width = Cesium.ContextLimits._maximumAliasedLineWidth;
Cesium.ContextLimits._maximumAliasedLineWidth = 1;
t.after(() => {
Cesium.ContextLimits._maximumAliasedLineWidth = width;
});
const primitives = new Cesium.PrimitiveCollection();
t.after(() => primitives.destroy());
const groundPrimitives = new Cesium.PrimitiveCollection();
t.after(() => groundPrimitives.destroy());
return {
primitives,
groundPrimitives,
frameState: { context: { depthTexture: ground } },
globe: { show: false },
};
}
test('body clips future subdivisions, head ends at exact marker, and frames retain geometry', (t) => {
const scene = fixture(t),
renderer = createContactTrailRenderer(scene);
const positions = [0, 1, 2].map((i) =>
Cesium.Cartesian3.fromDegrees(-71, 42 + i * 0.001, 11.5),
);
renderer.replaceHistory({
revision: 1,
segments: [
{
fromSeq: 0,
toSeq: 1,
fromT: 0,
toT: 10000,
positions: positions.slice(0, 2),
},
{
fromSeq: 0,
toSeq: 1,
fromT: 10000,
toT: 20000,
positions: positions.slice(1, 3),
},
],
});
const { body } = renderer.diagnostics();
assert.equal(body.allowPicking, false);
// The constructor defers this check until shader preparation. Run the real
// Cesium validator without WebGL, including a missing-attribute control.
const source = body.depthFailAppearance.vertexShaderSource;
body._batchTableAttributeIndices = { color: 0 };
assert.throws(
() => Cesium.Primitive._updateColorAttribute(body, source, true),
/depthFailColor/,
);
for (const instance of body.geometryInstances) {
assert.deepEqual(
instance.attributes.depthFailColor.value,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
}
body._batchTableAttributeIndices = { color: 0, depthFailColor: 1 };
assert.doesNotThrow(() =>
Cesium.Primitive._updateColorAttribute(body, source, true),
);
const attributes = new Map(
body.geometryInstances.map((instance) => [
instance.id,
{
show: new Uint8Array([0]),
color: new Uint8Array(4),
depthFailColor: new Uint8Array(4),
},
]),
);
// Simulate Cesium's completed upload; exercise public attribute writes.
body._ready = true;
body.getGeometryInstanceAttributes = (id) => {
const stored = attributes.get(id),
accessor = {};
for (const name of ['show', 'color', 'depthFailColor'])
Object.defineProperty(accessor, name, {
get: () => stored[name].slice(),
set: (value) => {
stored[name] = value.slice();
},
});
return accessor;
};
const marker = Cesium.Cartesian3.lerp(
positions[1],
positions[2],
0.5,
new Cesium.Cartesian3(),
);
const sample = { displayT: 15000, fromSeq: 0, toSeq: 1, fraction: 0.75 };
for (let i = 0; i < 120; i++) renderer.setDisplaySample(sample, marker);
assert.deepEqual(
[...attributes.values()].map((a) => a.show[0]),
[1, 1, 0, 0],
);
for (const a of attributes.values())
assert.deepEqual(
a.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#5EF08A').withAlpha(0.55),
),
);
const result = renderer.diagnostics();
assert.equal(result.body, body);
assert.equal(result.rebuilds, 1);
assert.equal(result.headRebuilds, 1, '120 frames retain head geometry');
assert.equal(result.head.material.uniforms.fraction, 0.5);
assert.equal(result.head.width, 3);
assert.equal(result.backing.width, 5);
assert.ok(Cesium.Cartesian3.equals(result.head.positions.at(-1), marker));
assert.equal(result.head.positions.length, 2);
renderer.setDisplaySample(
{ ...sample, displayT: 5000, fraction: 0.25 },
positions[0],
);
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
'rewind hides future geometry again',
);
renderer.destroy();
assert.equal(scene.primitives.length, 0);
});
test('trail age curve uses the specified four alpha anchors', () => {
assert.equal(trailAlpha(0), 0.8);
assert.equal(trailAlpha(120000), 0.45);
assert.equal(trailAlpha(600000), 0.2);
assert.equal(trailAlpha(900000), 0.08);
assert.ok(Math.abs(trailAlpha(60000) - 0.625) < 1e-10);
});
test('ground body and clipped head stay inside rebuild and frame geometry budgets', async () => {
Cesium.ApproximateTerrainHeights._terrainHeights = JSON.parse(
readFileSync(
new URL(
import.meta
.resolve('@cesium/engine/Source/Assets/approximateTerrainHeights.json'),
),
),
);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
const start = performance.now();
const instances = async (count) =>
Promise.all(
Array.from(
{ length: count },
async (_, i) =>
new Cesium.GeometryInstance({
id: i,
geometry: await Cesium.GroundPolylineGeometry.createGeometry(
new Cesium.GroundPolylineGeometry({
positions,
width: i % 2 ? 3 : 5,
granularity: 0,
}),
),
}),
),
);
const pipelineBytes = async (count) => {
// Match GroundPolylinePrimitive's internal Primitive options and the
// application's morph-capable scene, including batch IDs and encoding.
const result = Cesium.PrimitivePipeline.combineGeometry({
instances: await instances(count),
projection: new Cesium.GeographicProjection(),
ellipsoid: Cesium.Ellipsoid.WGS84,
modelMatrix: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY),
elementIndexUintSupported: true,
scene3DOnly: false,
vertexCacheOptimize: false,
compressVertices: false,
createPickOffsets: false,
});
return result.geometries.reduce(
(sum, geometry) =>
sum +
Object.values(geometry.attributes).reduce(
(n, a) => n + (a?.values?.byteLength || 0),
0,
) +
geometry.indices.byteLength,
0,
);
};
const bytes = await pipelineBytes(1);
const bodyInstances = 2 * (TRAIL_VERTEX_LIMIT - 1);
const bodyBytes = await pipelineBytes(bodyInstances);
assert.equal(bytes, 1576, 'measure final encoded and batched geometry');
assert.equal(bodyBytes, 2014128);
const instanceReserve = 64 * bodyInstances;
assert.ok(bodyBytes + instanceReserve <= 2 * 1024 * 1024);
assert.ok(
bytes <= 2048,
'subdivision crossings stay below 2 KiB of head geometry',
);
console.log(
`trail final pipeline: ${bytes} bytes/head crossing, 0 bytes/ordinary head frame, ${bodyBytes} bytes/body (${bodyInstances} instances), ${instanceReserve} bytes instance reserve; geometry CPU ${(performance.now() - start).toFixed(3)} ms`,
);
});
test('supported scenes drape body and clipped head on 3D tiles and retain head geometry', (t) => {
const scene = fixture(t, true),
renderer = createContactTrailRenderer(scene);
const positions = [
Cesium.Cartesian3.fromDegrees(-97.7431, 30.267),
Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672),
];
renderer.replaceHistory({
revision: 1,
segments: [{ fromSeq: 0, toSeq: 1, fromT: 0, toT: 20000, positions }],
});
const first = renderer.diagnostics();
assert.ok(first.body instanceof Cesium.GroundPolylinePrimitive);
assert.equal(first.body.classificationType, Cesium.ClassificationType.BOTH);
assert.ok(scene.groundPrimitives.contains(first.body));
for (const instance of first.body.geometryInstances)
assert.ok(instance.geometry instanceof Cesium.GroundPolylineGeometry);
for (let i = 1; i <= 120; i++)
renderer.setDisplaySample(
{ displayT: i * 100, fromSeq: 0, toSeq: 1, fraction: i / 200 },
positions[1],
);
const result = renderer.diagnostics();
assert.equal(result.body, first.body);
assert.equal(result.headRebuilds, 1);
assert.ok(result.headPrimitive instanceof Cesium.GroundPolylinePrimitive);
assert.equal(result.head.material.uniforms.fraction, 0.6);
assert.match(result.head.material.shaderSource, /discard/);
for (const stack of ['Google', 'OSM', 'Bing', 'Google']) {
scene.globe.show = stack !== 'Google';
renderer.setDisplaySample(
{ displayT: 12000, fromSeq: 0, toSeq: 1, fraction: 0.6 },
positions[1],
);
const retained = renderer.diagnostics();
assert.equal(retained.body, result.body, `${stack}: retained history`);
assert.equal(retained.headPrimitive, result.headPrimitive);
for (const primitive of [retained.body, retained.headPrimitive]) {
assert.equal(
primitive.classificationType,
Cesium.ClassificationType.BOTH,
stack,
);
assert.equal(primitive.show, true, stack);
}
}
renderer.setVisible(false);
assert.equal(result.body.show, false);
assert.equal(result.headPrimitive.show, false);
renderer.destroy();
assert.equal(scene.groundPrimitives.length, 0);
assert.equal(scene.primitives.length, 0);
});
test('subdivision crossings only write the changed show range and age colors once per second', (t) => {
const renderer = createContactTrailRenderer(fixture(t));
const positions = [
Cesium.Cartesian3.fromDegrees(-71, 42),
Cesium.Cartesian3.fromDegrees(-71, 42.001),
];
renderer.replaceHistory({
revision: 1,
segments: Array.from({ length: 100 }, (_, i) => ({
fromSeq: 0,
toSeq: 1,
fromT: i * 500,
toT: (i + 1) * 500,
positions,
})),
});
const { body } = renderer.diagnostics();
const counts = { show: 0, color: 0, depthFailColor: 0 };
const attributes = new Map(
body.geometryInstances.map((instance) => {
const result = {};
for (const name of Object.keys(counts)) {
let value = instance.attributes[name].value;
Object.defineProperty(result, name, {
get: () => value,
set(next) {
value = next;
counts[name]++;
},
});
}
return [instance.id, result];
}),
);
body._ready = true;
body.getGeometryInstanceAttributes = (id) => attributes.get(id);
const display = (displayT) =>
renderer.setDisplaySample(
{ displayT, fromSeq: 0, toSeq: 1, fraction: 0.1 },
positions[0],
);
const reset = () => {
for (const name of Object.keys(counts)) counts[name] = 0;
};
display(100);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
reset();
display(600);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
reset();
display(100);
assert.deepEqual(counts, { show: 2, color: 0, depthFailColor: 0 });
assert.ok(
[...attributes.values()].every((a) => a.show[0] === 0),
'backward seek hides the completed range',
);
reset();
display(1100);
assert.deepEqual(counts, { show: 4, color: 200, depthFailColor: 200 });
reset();
display(1200);
assert.deepEqual(counts, { show: 0, color: 0, depthFailColor: 0 });
renderer.setStyle('#FF4538');
display(1200);
assert.deepEqual(counts, { show: 0, color: 200, depthFailColor: 200 });
for (const a of attributes.values())
assert.deepEqual(
a.depthFailColor,
Cesium.ColorGeometryInstanceAttribute.toValue(
Cesium.Color.fromCssColorString('#FF4538').withAlpha(0.55),
),
);
});
+28 -46
View File
@@ -52,6 +52,7 @@ import {
stationMatchesRadioCategory,
} from './radio.js';
import { radioStationRow, withRadioLayer } from '../testSupport/radioLayerHarness.mjs';
import { radioSelectedMarker, radioTestEngine } from '../testSupport/radioTestEngine.mjs';
const stations = [
{ id: 'news', tags: ['News', 'Weather Radio', 'air traffic'] },
@@ -393,13 +394,11 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
radioLayer.setLifecyclePresentation({
lifecycleState: 'enabled', enabled: true, uncertain: false,
@@ -424,7 +423,7 @@ test('destroy and re-init reset Radio audio ownership, volume, filter, and telem
assert.equal(getRadioUIState().volume, 0.8);
assert.equal(getRadioUIState().effectiveVolume, 0.8);
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
assert.equal(audioInstances.length, 2, 're-init creates a clean Audio session');
const nextState = getRadioUIState();
for (const eventName of ['playing', 'pause', 'waiting', 'error']) {
@@ -512,13 +511,11 @@ test('late media errors after replacement or Pause cannot mutate the active stat
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
await radioLayer.update();
radioLayer.setLifecyclePresentation({
@@ -643,12 +640,10 @@ test('unusable directory responses preserve warm client state atomically', async
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
globalThis.fetch = async () => new Response(JSON.stringify({
stations: [station],
stale: false,
@@ -762,7 +757,7 @@ test('unusable directory responses preserve warm client state atomically', async
assert.equal(getRadioUIState().stale, true);
assert.equal(getRadioUIState().rejectedStationCount, 10_000);
radioLayer.destroy();
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
assert.equal(getRadioUIState().rejectedStationCount, 0);
assert.equal(getRadioUIState().degraded, false);
} finally {
@@ -776,8 +771,6 @@ test('tuner drag keeps one immutable catalog resolution through refresh and rele
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
const stationA = {
id: '00000000-0000-4000-8000-000000000041',
@@ -820,7 +813,7 @@ test('tuner drag keeps one immutable catalog resolution through refresh and rele
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
await publish(stationA, 1);
assert.equal(radioLayer.beginTuning(), true);
@@ -927,9 +920,12 @@ test('failed exact tuner release cannot consume a stale playback fallback', asyn
test('tuner cancellation restores the frozen start marker after catalog removal', async () => {
const originalFetch = globalThis.fetch;
const originalAudio = globalThis.Audio;
const selectedEntities = new Map();
const engine = radioTestEngine();
const selectedMarker = (id) => {
const marker = radioSelectedMarker(engine);
return marker?.id === `radio:selected:${id}` ? marker : undefined;
};
let playCalls = 0;
let flyToCalls = 0;
globalThis.Audio = class FakeAudio {
constructor() {
this.volume = 0.8;
@@ -944,17 +940,11 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
const viewer = {
camera: {
positionWC: { x: 7_000_000, y: 0, z: 0 },
flyTo() { flyToCalls += 1; },
},
scene: {
canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} },
requestRender() {},
},
dataSources: { add() {}, remove() {} },
entities: {
add(entity) { selectedEntities.set(entity.id, entity); return entity; },
remove(entity) { return selectedEntities.delete(entity?.id); },
},
};
const stationA = {
id: '00000000-0000-4000-8000-000000000051',
@@ -994,7 +984,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine });
radioLayer.enable();
radioLayer.setLifecyclePresentation({
lifecycleState: 'enabled', enabled: true, uncertain: false,
@@ -1004,7 +994,7 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
await publish([stationA, stationB], nextGeneration);
nextGeneration += 1;
assert.equal(radioLayer.selectStation(stationA.id, { autoplay: false, focus: false }), true);
const startMarker = selectedEntities.get(`radio:selected:${stationA.id}`);
const startMarker = selectedMarker(stationA.id);
assert.ok(startMarker);
assert.equal(radioLayer.beginTuning(), true);
assert.equal(radioLayer.previewTuningStation(stationB.id, { rotate: false }), true);
@@ -1012,14 +1002,14 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
nextGeneration += 1;
assert.equal(getRadioUIState().selected, null);
assert.equal(radioLayer.cancelTuning(), true);
const restoredMarker = selectedEntities.get(`radio:selected:${stationA.id}`);
const restoredMarker = selectedMarker(stationA.id);
assert.ok(restoredMarker, 'the frozen start marker remains visible after cancellation');
assert.deepEqual(restoredMarker.position, startMarker.position);
assert.equal(getRadioUIState().tuningRestoredStationId, stationA.id);
assert.equal(getRadioUIState().tuningActive, false);
assert.equal(getRadioUIState().selected, null, 'stale marker never becomes playback authority');
assert.equal(playCalls, 0);
assert.equal(flyToCalls, 0);
assert.equal(engine.fake.callsOf('camera.flyTo').length, 0);
return radioLayer.getAcceptedCatalogSnapshot();
};
@@ -1028,21 +1018,21 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
assert.equal(radioLayer.setFilter(sameFilter), true);
assert.equal(getRadioUIState().filter, sameFilter);
assert.equal(getRadioUIState().tuningRestoredStationId, null);
assert.equal(selectedEntities.has(`radio:selected:${stationA.id}`), false);
assert.equal(Boolean(selectedMarker(stationA.id)), false);
assert.equal(radioLayer.getAcceptedCatalogSnapshot(), sameFilterSnapshot);
assert.equal(getRadioUIState().selected, null);
assert.equal(playCalls, 0);
assert.equal(flyToCalls, 0);
assert.equal(engine.fake.callsOf('camera.flyTo').length, 0);
const changedFilterSnapshot = await restoreRemovedStartMarker();
assert.equal(radioLayer.setFilter('news'), true);
assert.equal(getRadioUIState().filter, 'news');
assert.equal(getRadioUIState().tuningRestoredStationId, null);
assert.equal(selectedEntities.has(`radio:selected:${stationA.id}`), false);
assert.equal(Boolean(selectedMarker(stationA.id)), false);
assert.equal(radioLayer.getAcceptedCatalogSnapshot(), changedFilterSnapshot);
assert.equal(getRadioUIState().selected, null);
assert.equal(playCalls, 0);
assert.equal(flyToCalls, 0);
assert.equal(engine.fake.callsOf('camera.flyTo').length, 0);
const equalGenerationSnapshot = await restoreRemovedStartMarker();
await publish([stationB], equalGenerationSnapshot.generation);
@@ -1051,14 +1041,14 @@ test('tuner cancellation restores the frozen start marker after catalog removal'
null,
'the next accepted equal-generation refresh clears the presentation-only marker',
);
assert.equal(selectedEntities.has(`radio:selected:${stationA.id}`), false);
assert.equal(Boolean(selectedMarker(stationA.id)), false);
assert.equal(radioLayer.getAcceptedCatalogSnapshot(), equalGenerationSnapshot);
assert.equal(playCalls, 0);
assert.equal(flyToCalls, 0);
assert.equal(engine.fake.callsOf('camera.flyTo').length, 0);
assert.equal(radioLayer.selectStation(stationB.id, { autoplay: false, focus: false }), true);
assert.equal(getRadioUIState().tuningRestoredStationId, null);
assert.equal(selectedEntities.has(`radio:selected:${stationA.id}`), false);
assert.equal(Boolean(selectedMarker(stationA.id)), false);
} finally {
globalThis.fetch = originalFetch;
radioLayer.destroy();
@@ -1096,14 +1086,12 @@ test('Radio public tuner, filter, and resume mutations require certain enabled l
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
viewer.scene.requestRender = () => {};
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
await radioLayer.update();
radioLayer.setLifecyclePresentation({
@@ -1149,8 +1137,6 @@ test('tuner refuses a degraded fallback that has no accepted catalog generation'
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
const station = {
id: '00000000-0000-4000-8000-000000000043',
@@ -1178,7 +1164,7 @@ test('tuner refuses a degraded fallback that has no accepted catalog generation'
acceptedGeneration: null,
updatedAt: new Date().toISOString(),
}), { status: 200, headers: { 'Content-Type': 'application/json' } });
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
await radioLayer.update();
@@ -1217,8 +1203,6 @@ test('accepted snapshots allowlist station fields and never regress generation i
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
const serve = (stations, acceptedGeneration, catalogInstance = 'qa-instance-a') => {
globalThis.fetch = async () => new Response(JSON.stringify({
@@ -1233,7 +1217,7 @@ test('accepted snapshots allowlist station fields and never regress generation i
radioLayer.destroy();
try {
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
serve([station], 1);
radioLayer.enable();
await radioLayer.update();
@@ -1318,8 +1302,6 @@ test('update abort, destroy, and re-init invalidate the prior session and reset
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
const lateStation = {
id: '00000000-0000-4000-8000-000000000099',
@@ -1344,7 +1326,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset
requestSignal = options.signal;
return new Promise((resolve) => { resolveFetch = resolve; });
};
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
const pending = radioLayer.update();
assert.equal(getRadioUIState().loading, true);
@@ -1353,7 +1335,7 @@ test('update abort, destroy, and re-init invalidate the prior session and reset
assert.equal(getRadioUIState().loading, false);
radioLayer.destroy();
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
const cleanState = getRadioUIState();
assert.deepEqual({
enabled: cleanState.enabled,
+2 -3
View File
@@ -19,6 +19,7 @@ import {
} from './radio.js';
import { RADIO_REJECTED_STATION_COUNT_MAX as SERVER_REJECTED_MAX } from '../../server/providers/radio/constants.js';
import { RADIO_REJECTED_STATION_COUNT_MAX as CLIENT_REJECTED_MAX } from '../layers/radio/policy.js';
import { radioTestEngine } from '../testSupport/radioTestEngine.mjs';
const UUID = '12345678-1234-4234-8234-123456789abc';
const publicLookup = async () => [{ address: '93.184.216.34', family: 4 }];
@@ -760,8 +761,6 @@ test('server structural rejections reach the client diagnostic without discardin
const viewer = {
camera: { positionWC: { x: 7_000_000, y: 0, z: 0 } },
scene: { canvas: { disableRootEvents: true, onwheel: null, addEventListener() {}, removeEventListener() {} } },
dataSources: { add() {}, remove() {} },
entities: { add(entity) { return entity; }, remove() {} },
};
radioLayer.destroy();
try {
@@ -769,7 +768,7 @@ test('server structural rejections reach the client diagnostic without discardin
status: response.status,
headers: { 'Content-Type': 'application/json' },
});
radioLayer.init(viewer);
radioLayer.init(viewer, { engine: radioTestEngine() });
radioLayer.enable();
await radioLayer.update();
const state = getRadioUIState();
@@ -1,309 +0,0 @@
import * as Cesium from 'cesium';
const ALPHA_STOPS = [
[0, 0.8],
[120000, 0.45],
[600000, 0.2],
[900000, 0.08],
];
export function trailAlpha(ageMs) {
const stops = ALPHA_STOPS;
for (let i = 1; i < stops.length; i++) {
if (ageMs === stops[i][0]) return stops[i][1];
if (ageMs < stops[i][0]) {
const [a, x] = stops[i - 1],
[b, y] = stops[i];
return x + ((y - x) * Math.max(0, ageMs - a)) / (b - a);
}
}
return 0.08;
}
/** One static history batch and one frequently updated head. Never entities. */
export function createContactTrailRenderer(scene) {
const ground =
!!scene.frameState?.context &&
Cesium.GroundPolylinePrimitive.isSupported(scene);
const collection = ground ? scene.groundPrimitives : scene.primitives;
// One 25 m corridor is clipped in material coordinates. Only subdivision
// crossings build geometry; frame updates write a scalar, never vertex buffers.
const headMaterial = (alpha) =>
new Cesium.Material({
fabric: {
type: 'TransitTrailHead',
uniforms: {
color: new Cesium.Color(0.37, 0.94, 0.54, alpha),
fraction: 0,
backing: true,
},
source: `czm_material czm_getMaterial(czm_materialInput materialInput) {
if (materialInput.st.s > fraction) discard;
czm_material m = czm_getDefaultMaterial(materialInput);
bool edge = abs(materialInput.st.t - 0.5) > 0.3;
m.diffuse = czm_gammaCorrect(vec4(edge && backing ? vec3(0.02, 0.03, 0.05) : color.rgb, 1.0)).rgb;
m.alpha = color.a;
return m;
}`,
},
translucent: true,
});
const material = headMaterial(0.8),
depthMaterial = headMaterial(0.55);
depthMaterial.uniforms.backing = false;
const head = { positions: [], show: false, width: 3, material };
const backing = { positions: [], show: false, width: 5 };
let headPrimitive = null,
headRebuilds = 0;
function geometry(positions, width, material = false) {
return ground
? new Cesium.GroundPolylineGeometry({ positions, width, granularity: 0 })
: new Cesium.PolylineGeometry({
positions,
width,
arcType: Cesium.ArcType.NONE,
vertexFormat: material
? Cesium.PolylineMaterialAppearance.VERTEX_FORMAT
: Cesium.PolylineColorAppearance.VERTEX_FORMAT,
});
}
function primitive(instances, appearance, depthFailAppearance) {
return ground
? new Cesium.GroundPolylinePrimitive({
geometryInstances: instances,
appearance,
classificationType: Cesium.ClassificationType.BOTH,
allowPicking: false,
asynchronous: true,
show: visible,
})
: new Cesium.Primitive({
geometryInstances: instances,
appearance,
depthFailAppearance,
allowPicking: false,
asynchronous: false,
show: visible,
});
}
let body = null,
segments = [],
revision = -1,
visible = true,
style = '#5EF08A';
let lastSecond = -1,
completed = -1,
active = null;
const styleColor = Cesium.Color.fromCssColorString(style);
const attributeIds = [];
const color = new Cesium.Color(),
endpoint = new Cesium.Cartesian3();
const headPositions = [new Cesium.Cartesian3(), endpoint];
let rebuilds = 0;
function tint(alpha, dark = false) {
if (dark) {
color.red = 0.02;
color.green = 0.03;
color.blue = 0.05;
} else Cesium.Color.clone(styleColor, color);
color.alpha = alpha;
return color;
}
function replaceHistory(next) {
if (next.revision === revision) return;
revision = next.revision;
segments = next.segments;
completed = -1;
lastSecond = -1;
active = null;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
head.show = backing.show = false;
if (body) collection.remove(body);
body = null;
const instances = [];
attributeIds.length = 0;
for (let i = 0; i < segments.length; i++) {
const segment = segments[i];
attributeIds.push([`${i}:0`, `${i}:1`]);
if (segment.positions.length < 2) continue;
for (let lane = 0; lane < 2; lane++) {
instances.push(
new Cesium.GeometryInstance({
id: `${i}:${lane}`,
geometry: geometry(segment.positions, lane ? 3 : 5),
attributes: {
color: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.8, !lane),
),
depthFailColor: Cesium.ColorGeometryInstanceAttribute.fromColor(
tint(0.55),
),
show: new Cesium.ShowGeometryInstanceAttribute(false),
},
}),
);
}
}
if (instances.length) {
body = collection.add(
primitive(
instances,
new Cesium.PolylineColorAppearance({ translucent: true }),
new Cesium.PolylineColorAppearance({ translucent: true }),
),
);
rebuilds++;
}
}
function setDisplaySample(sample, renderedPosition) {
if (!sample || !renderedPosition) {
head.show = false;
backing.show = false;
if (headPrimitive) headPrimitive.show = false;
return;
}
const second = Math.floor(sample.displayT / 1000);
let lo = 0,
hi = segments.length;
while (lo < hi) {
const mid = (lo + hi) >>> 1;
if (segments[mid].toT <= sample.displayT) lo = mid + 1;
else hi = mid;
}
const done = lo - 1;
const candidate = segments[lo];
const segment =
candidate &&
candidate.fromT <= sample.displayT &&
candidate.fromSeq === sample.fromSeq &&
candidate.toSeq === sample.toSeq
? candidate
: null;
if (body?.ready && done !== completed) {
for (
let i = Math.min(done, completed) + 1;
i <= Math.max(done, completed);
i++
) {
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
// Cesium getters return copies. Write back the array we changed.
const show = attributes.show;
show[0] = i <= done ? 1 : 0;
attributes.show = show;
}
}
completed = done;
}
if (body?.ready && second !== lastSecond) {
for (let i = 0; i < segments.length; i++) {
const alpha = trailAlpha(sample.displayT - segments[i].toT);
for (let lane = 0; lane < 2; lane++) {
const attributes = body.getGeometryInstanceAttributes(
attributeIds[i][lane],
);
if (!attributes) continue;
const rgba = attributes.color;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(alpha, !lane),
rgba,
);
attributes.color = rgba;
if (!ground) {
const depthRgba = attributes.depthFailColor;
Cesium.ColorGeometryInstanceAttribute.toValue(
tint(0.55),
depthRgba,
);
attributes.depthFailColor = depthRgba;
}
}
}
lastSecond = second;
}
const show = visible && !!segment && sample.fraction < 1;
head.show = show;
backing.show = show;
if (headPrimitive) headPrimitive.show = show;
if (!show) return;
if (active !== segment) {
active = segment;
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = collection.add(
primitive(
new Cesium.GeometryInstance({
geometry: geometry(segment.positions, 5, true),
}),
new Cesium.PolylineMaterialAppearance({
material,
translucent: true,
}),
new Cesium.PolylineMaterialAppearance({
material: depthMaterial,
translucent: true,
}),
),
);
headRebuilds++;
headPositions[0] = segment.positions[0];
headPositions[1] = endpoint;
}
Cesium.Cartesian3.clone(renderedPosition, endpoint);
head.positions = headPositions;
backing.positions = headPositions;
material.uniforms.fraction = Math.max(
0,
Math.min(
1,
(sample.displayT - segment.fromT) / (segment.toT - segment.fromT),
),
);
depthMaterial.uniforms.fraction = material.uniforms.fraction;
Cesium.Color.clone(tint(0.8), material.uniforms.color);
Cesium.Color.clone(tint(0.55), depthMaterial.uniforms.color);
}
return {
replaceHistory,
setDisplaySample,
setStyle(next) {
if (next === style) return;
style = next;
Cesium.Color.fromCssColorString(style, styleColor);
lastSecond = -1;
},
setVisible(next) {
visible = next;
if (headPrimitive) headPrimitive.show = next && head.show;
if (body) body.show = next;
},
destroy() {
if (body) collection.remove(body);
if (headPrimitive) collection.remove(headPrimitive);
headPrimitive = null;
material.destroy();
depthMaterial.destroy();
body = null;
segments = [];
},
diagnostics() {
return {
revision,
rebuilds,
segments: segments.length,
body,
head,
backing,
headPrimitive,
headStrategy: ground
? 'draped corridor with material clip'
: 'depth-fail corridor with material clip',
ground,
headRebuilds,
entitiesAdded: 0,
};
},
};
}
+9 -6
View File
@@ -9,7 +9,8 @@ import * as annotations from '../annotations/worldAnnotationRenderer.js';
import { createDirectionsLayer } from '../layers/directions/index.js';
import { createDirectionsSource } from '../layers/directions/source.js';
import { createLifecycle as createCctvLifecycle } from '../layers/cctv/lifecycle.js';
import { createCctvCesiumRenderer } from '../layers/cctv/render/cesium.js';
import { createCctvDisplay } from '../layers/cctv/render/display.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import * as input from './inputOwnership.js';
import { createOverpassAlprSource } from '../layers/alpr/source.js';
@@ -83,15 +84,17 @@ test('Directions introduces the shared OSM credit when the requested route draws
});
test('Warendorf webcam display introduces the shared OSM credit', (t) => {
const v = viewer(t), empty = new Proxy({}, { get: () => noop });
const renderer = createCctvCesiumRenderer({ state: {}, services: { credits: { showOsmCredit, hideOsmCredit }, sprites: empty } });
renderer.attach(v);
const engine = createFakeEngine(), empty = new Proxy({}, { get: () => noop });
const renderer = createCctvDisplay(engine, { state: {}, services: { credits: { showOsmCredit, hideOsmCredit } } });
renderer.attach();
t.after(() => renderer.destroy());
const lifecycle = createCctvLifecycle({ state: { _records: [{ camera: { id: 'warendorf-marktplatz-rathaus', cityId: 'warendorf' } }], _recordById: new Map(), _cctvOverlayHost: overlayHost },
services: { credits: { showOsmCredit, hideOsmCredit }, sprites: empty, activation: empty, picking: empty, focus: empty, render: empty },
parts: { renderer, selection: empty, geometryQueue: empty, rendering: empty, projection: empty, cards: empty, presentation: empty }, source: {} });
lifecycle.methods.enable(); assertCredit(v); lifecycle.methods.disable();
assert.equal(v.credits.filter(c => c.showOnScreen).length, 0);
lifecycle.methods.enable();
assert.ok(engine.fake.credits.some((credit) => credit.onScreen && credit.html.includes('>© OpenStreetMap<')));
lifecycle.methods.disable();
assert.equal(engine.fake.credits.filter((credit) => credit.onScreen).length, 0);
});
test('optional Overpass ALPR adapter uses the shared contributor wording', () => {
+3 -4
View File
@@ -1,7 +1,6 @@
import { createTransitLayer as createLayer } from '../layers/transit/index.js';
import { createTransitCesiumRenderer } from '../layers/transit/render/cesium.js';
import { createTransitDisplay } from '../layers/transit/render/display.js';
import * as render from '../renderGovernor.js';
import * as sprites from './spriteOrder.js';
import * as picking from './pickRegistry.js';
import * as overlays from '../overlays/worldOverlay.js';
import { registerDynamicCredit, transitFeedCredit } from './dataCredits.js';
@@ -16,7 +15,8 @@ import { sampleMeshFloorCells } from './meshFloorSampler.js';
export function createTransitLayer(options) {
return createLayer({
rendererFactory: createTransitCesiumRenderer,
rendererFactory: ({ engine, ...context }) =>
createTransitDisplay(engine, context),
...options,
});
}
@@ -24,7 +24,6 @@ export function createTransitLayer(options) {
const layer = createTransitLayer({
services: {
render,
sprites,
picking,
overlays,
credits: { registerDynamicCredit, transitFeedCredit },