Draw vessels, satellites, Space Missions, ALPR, bikeshare and OSM Places through one display each

Each layer now has one render/display.js on the globe contract, the same
factory on both engines; its render/cesium* and render/navara* files go.
Cesium's behaviour is the reference, and the logic that was written twice
is written once:

- AIS vessels: atlas chevrons and engine.lines trails. The display
  registers the gev-trail pick claim itself and its trailing visibility
  pass now also runs on Navara.
- Satellites: point banks per look, orbit rings as lines turned by their
  model matrix, and selection and follow through engine.camera.follow.
  The emulated _viewer is gone, and the tracked readout republishes card
  text on Navara too.
- Space Missions: dots, reticle, trajectories and tactical orbits as
  movers and lines. The layer keeps its own records instead of Entities
  and DataSources, and camera work goes through engine.camera. Clicks go
  through the selection dispatcher, and hover keeps Cesium's throttle. The
  pad zone is its rim only: the contract has no surface fill yet.
- ALPR, bikeshare and OSM Places: one display and, for bikeshare, one
  style module each; clicks through engine.input, no
  ScreenSpaceEventHandler or EntityCluster. ALPR keeps Navara's horizon
  cull, and OSM Places points sample the surface where Cesium clamped them.

Coupling: layer renderer lines fall from 4546/11106 to 2638/8735
(Cesium/Navara), `viewer` lines from 2209 to 2014, ScreenSpaceEventHandler
files from 20 to 15.
This commit is contained in:
German Khokhlov committed 2026-11-07 03:34:06 +04:00
1 parent 3e261d1baf
commit f06b93fbc9
120 files changed
+6626 -6998

No files matched your search

+20 -1
View File
@@ -15,7 +15,7 @@ import {
reduceVesselSelection,
vesselDatumHeightM,
_bindVesselInteractionForTest,
_setVesselStateForTest,
_setVesselStateForTest as setVesselStateForTest,
_reconcileVesselsForTest,
_applyAisFeedSnapshotForTest,
_loadLivePositionsForTest,
@@ -39,6 +39,12 @@ import {
presentSelectedVessel,
subscribeSelectedVessel,
} from '../hudReadouts.js';
import { vesselViewerRenderer } from '../testSupport/vesselViewerRenderer.mjs';
// The layer's state over the test's viewer, drawn by the Cesium-shaped test
// renderer (its billboard collection, projection and trackedEntityChanged).
const _setVesselStateForTest = (options = {}) =>
setVesselStateForTest({ renderer: vesselViewerRenderer, ...options });
test('open feed with vessels is healthy (null)', () => {
assert.equal(deriveAisFeedError({ status: 'open', lastMessageAt: 1, error: null }, 42), null);
@@ -944,6 +950,16 @@ function installWireHarness(picked, stateOverrides = {}) {
globalThis.document = {
getElementById: () => null,
};
// The test renderer draws in no scene; the harness viewer's
// trackedEntityChanged is its follow signal.
const followViewer = {
get trackedEntity() {
return viewer.trackedEntity;
},
trackedEntityChanged,
};
const renderer = ({ billboardCollection }) =>
vesselViewerRenderer({ viewer: followViewer, billboardCollection });
_setVesselStateForTest({
records: [record],
selectedRecord: record,
@@ -952,6 +968,7 @@ function installWireHarness(picked, stateOverrides = {}) {
trailPositions: [POS],
interactionHandlerFactory,
interactionKeyTarget: keyTarget,
renderer,
...stateOverrides,
});
_bindVesselInteractionForTest(viewer, handler, keyTarget);
@@ -966,6 +983,7 @@ function installWireHarness(picked, stateOverrides = {}) {
windowTarget,
reinstalledHandlers,
interactionHandlerFactory,
renderer,
cleanup() {
stopReadout();
aisLiveVesselsLayer.destroy();
@@ -1201,6 +1219,7 @@ test('vessel interaction lifecycle: disable detaches input and enable reinstalls
trailPositions: [POS],
interactionHandlerFactory: harness.interactionHandlerFactory,
interactionKeyTarget: harness.keyTarget,
renderer: harness.renderer,
});
disabledClick({ position: { x: 10, y: 20 } });
disabledKeydown({ key: 'Escape' });
+254 -258
View File
@@ -1,9 +1,11 @@
import { createAlprCesiumRenderer } from '../layers/alpr/render/cesium.js';
// src/data/alprCameras.test.mjs
// Pure helpers and actual layer lifecycle with a minimal viewer/input harness.
// Pure helpers and the actual layer lifecycle, drawn by its display on the
// fake engine.
import { test } from 'node:test';
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 { createAlprDisplay } from '../layers/alpr/render/display.js';
import alprCamerasLayer, {
createAlprCamerasLayer,
configureAlprSource,
@@ -252,8 +254,8 @@ const cameraResponse = (elements = [cameraNode()], stale = false) => ({
json: async () => ({ elements }),
});
// Real layer, Cesium entities and context store. Only the DOM, upstream fetch,
// camera rectangle and input event delivery are substituted (no GL in Node).
// Real layer, display and context store on the fake engine. Only the DOM,
// upstream fetch and the view's centre and range are substituted.
function cameraHarness(layer = alprCamerasLayer) {
const originals = {
document: globalThis.document,
@@ -308,80 +310,88 @@ function cameraHarness(layer = alprCamerasLayer) {
};
},
});
let box = { south: 30.26, west: -97.75, north: 30.28, east: -97.73 };
let source, click, picked;
const credits = new Set();
const viewer = {
creditDisplay: {
addStaticCredit: (credit) => credits.add(credit),
removeStaticCredit: (credit) => credits.delete(credit),
},
camera: {
moveEnd: new Cesium.Event(),
computeViewRectangle: () =>
box
? Cesium.Rectangle.fromDegrees(
box.west,
box.south,
box.east,
box.north,
)
: null,
},
scene: {
canvas: { addEventListener() {}, removeEventListener() {} },
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 },
postRender: new Cesium.Event(),
pick: () => picked,
},
dataSources: {
add: (value) => {
source = value;
},
remove() {},
},
const engine = createFakeEngine();
// The view: the ground point at the canvas centre and the camera straight
// above it.
const focus = (latitude, longitude, range) => {
if (latitude == null) {
engine.fake.script('pickEllipsoid', undefined);
return;
}
engine.fake.setPose({
latitude: geo.math.toRadians(latitude),
longitude: geo.math.toRadians(longitude),
height: range,
heading: 0,
pitch: -Math.PI / 2,
roll: 0,
});
engine.fake.script(
'pickEllipsoid',
geo.cartesian3.fromDegrees(longitude, latitude),
);
};
const setInput = Cesium.ScreenSpaceEventHandler.prototype.setInputAction;
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = function (
fn,
type,
modifier,
) {
if (type === Cesium.ScreenSpaceEventType.LEFT_CLICK) click = fn;
return setInput.call(this, fn, type, modifier);
// The camera range whose nearby box (alprFocusBox) spans `box`.
const setBox = (box) => {
if (!box) return focus(null);
const east = box.east < box.west ? box.east + 360 : box.east;
const latitude = (box.south + box.north) / 2;
const longitude = (((box.west + east) / 2 + 540) % 360) - 180;
const halfSpan = Math.max(
(box.north - box.south) / 2,
((east - box.west) / 2) * Math.cos(geo.math.toRadians(latitude)),
);
focus(latitude, longitude, (halfSpan * 111000) / 2);
};
try {
layer.init(viewer);
} finally {
Cesium.ScreenSpaceEventHandler.prototype.setInputAction = setInput;
}
setBox({ south: 30.26, west: -97.75, north: 30.28, east: -97.73 });
let picked;
engine.fake.script('pick', () => picked);
const markerSet = () => engine.fake.moverSet('alpr-cameras');
const selectedSet = () => engine.fake.moverSet('alpr-selected');
const shownIds = () => {
const set = markerSet();
return set ? [...set.store.pickIds].slice(0, set.store.count) : [];
};
layer.init(null, { engine });
layer.enable();
return {
viewer,
engine,
requests,
credits,
get source() {
return source;
},
credits: engine.fake.credits,
focus,
setFetch(fn) {
response = fn;
},
setBox(value) {
box = value;
},
setBox,
expire() {
now += QUERY_REUSE_MS + 1;
},
advance(ms) {
now += ms;
},
click(id) {
const entity = typeof id === 'string' ? source.entities.getById(id) : id;
picked = entity ? { id: entity } : undefined;
click({ position: new Cesium.Cartesian2() });
/** The ids of the displayed badges, in draw order. */
shownIds,
/** A displayed camera's marker handle (its entity context). */
marker: (id) => getContextStore().entities.get(id)?.entity,
/** The size a camera's badge draws at (0 when hidden). */
badgeSize: (id) => {
const chosen = selectedSet()?.store;
if (chosen?.count && chosen.pickIds[0] === id && chosen.shows[0])
return selectedSet().options.sprite.sizePx;
const { store, options } = markerSet();
const index = shownIds().indexOf(id);
return index >= 0 && store.shows[index] ? options.sprite.sizePx : 0;
},
/** A click on a camera's badge (id) or on the map (null). */
click: (id) => {
picked =
typeof id === 'string'
? { id, owner: 'alpr-cameras', instance: shownIds().indexOf(id) }
: undefined;
engine.fake.input('click', { position: { x: 1, y: 1 } });
},
restore() {
layer.destroy(viewer);
layer.destroy();
Date.now = originals.now;
for (const name of ['window', 'document', 'fetch']) {
if (originals[name] === undefined) delete globalThis[name];
@@ -391,24 +401,32 @@ function cameraHarness(layer = alprCamerasLayer) {
};
}
/** A renderer factory that keeps the display it made, for its markers. */
function trackedDisplay() {
const made = { display: null };
made.factory = ({ engine, ...context }) =>
(made.display = createAlprDisplay(engine, context));
return made;
}
test('OSM attribution stays inline while ALPR displays and follows toggles', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout'] });
const h = cameraHarness();
try {
assert.equal(h.credits.size, 0);
assert.equal(h.credits.length, 0);
await alprCamerasLayer.update();
assert.equal(h.credits.size, 1);
assert.equal(h.credits.length, 1);
const [credit] = h.credits;
assert.equal(credit.showOnScreen, true);
assert.equal(credit.onScreen, true);
assert.match(credit.html, />© OpenStreetMap</);
assert.doesNotMatch(credit.html, /OpenMapTiles|Map and place data/);
t.mock.timers.tick(6000);
assert.equal(h.credits.size, 1);
assert.equal(h.credits.length, 1);
alprCamerasLayer.disable();
assert.equal(h.credits.size, 0);
assert.equal(h.credits.length, 0);
alprCamerasLayer.enable();
await alprCamerasLayer.update();
assert.equal(h.credits.size, 1);
assert.equal(h.credits.length, 1);
assert.match(
DATA_CREDITS.find((entry) => entry.key === 'openstreetmap').html,
/OpenStreetMap contributors.*ODbL/,
@@ -441,15 +459,16 @@ test('all manufacturers share one ALPR title and color; only supplied metadata a
]),
);
await alprCamerasLayer.update();
const entities = h.source.entities.values;
const entities = h.shownIds().map(h.marker);
assert.equal(alprCamerasLayer.name, 'ALPR Cameras');
assert.deepEqual(
entities.map((entity) => entity.gevLabelModel.title),
['ALPR-0042', 'ALPR-0043', 'ALPR-0044'],
);
assert.equal(
new Set(entities.map((entity) => entity.billboard.image.getValue())).size,
1,
assert.deepEqual(
h.shownIds().map(h.badgeSize),
[38, 38, 38],
'one badge for every manufacturer',
);
assert.deepEqual(entities[0].gevLabelModel.details, [
'OSM MAPPED',
@@ -487,7 +506,7 @@ test('the camera label stays English data in a translated interface', async () =
]),
);
await alprCamerasLayer.update();
h.click(h.source.entities.values[0].id);
h.click(h.shownIds()[0]);
assert.equal(getSelectedEntityContext().label, 'ALPR camera');
assert.equal(
shownEntityLabel(getSelectedEntityContext().label),
@@ -524,10 +543,7 @@ test('clicking the selected camera or empty map deselects, including after refre
h.expire();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.badgeSize('alpr:42'), 38);
}
} finally {
h.restore();
@@ -583,10 +599,7 @@ test('disable removes contexts and highlight; cache reuse after re-enable does n
alprCamerasLayer.enable();
await alprCamerasLayer.update();
assert.equal(getSelectedEntityContext(), null);
assert.equal(
h.source.entities.getById('alpr:42').billboard.width.getValue(),
38,
);
assert.equal(h.badgeSize('alpr:42'), 38);
} finally {
h.restore();
}
@@ -675,7 +688,7 @@ test('duplicate nodes render once with a count that agrees with the entity set',
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'ready');
assert.equal(alprCamerasLayer.getStats().count, 1);
assert.equal(h.source.entities.values.length, 1);
assert.equal(h.shownIds().length, 1);
} finally {
h.restore();
}
@@ -691,7 +704,7 @@ test('zooming out hides local markers, releases selection and makes no unbounded
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(alprCamerasLayer.getStats().count, 0);
assert.equal(getSelectedEntityContext(), null);
assert.equal(h.source.entities.values.length, 0);
assert.equal(h.shownIds().length, 0);
assert.equal(h.requests.length, 1);
} finally {
h.restore();
@@ -713,7 +726,7 @@ test('state, country and dateline views never request data; returning to the cit
await alprCamerasLayer.update();
assert.equal(h.requests.length, 0, 'fresh wide view must not query');
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.credits.size, 0, 'no data presentation has occurred');
assert.equal(h.credits.length, 0, 'no data presentation has occurred');
}
h.setBox(city);
await alprCamerasLayer.update();
@@ -747,13 +760,11 @@ test('nearby camera moves reuse the snapped query but count and register only in
);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().count, 1);
h.setBox({ south: 30.26, west: -97.72, north: 30.28, east: -97.7 });
// Still inside the snapped query box (east of it at -97.70).
h.setBox({ south: 30.26, west: -97.722, north: 30.28, east: -97.702 });
await alprCamerasLayer.update();
assert.equal(h.requests.length, 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
['alpr:43'],
);
assert.deepEqual(h.shownIds(), ['alpr:43']);
assert.deepEqual([...getContextStore().entities.keys()], ['alpr:43']);
h.expire();
await alprCamerasLayer.update();
@@ -797,12 +808,15 @@ test('selected readout samples the rendered ground, not zero elevation or the di
const h = cameraHarness();
try {
let samples = 0;
h.viewer.scene.sampleHeightSupported = true;
h.viewer.scene.sampleHeight = (point, excluded) => {
h.engine.fake.script('sampleHeight', (point, excluded) => {
samples += 1;
assert.equal(excluded[0].id, 'alpr:42');
assert.deepEqual(
excluded.map((set) => set.id),
['alpr-cameras', 'alpr-selected'],
'the badges are not the ground',
);
return 187;
};
});
h.setFetch(async () =>
cameraResponse([
cameraNode(42, {
@@ -812,25 +826,21 @@ test('selected readout samples the rendered ground, not zero elevation or the di
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const anchor = Cesium.Cartographic.fromCartesian(
entity.gevDisplayPosition(),
);
const entity = h.marker('alpr:42');
const anchor = geo.cartographic.fromCartesian(entity.gevDisplayPosition());
assert.ok(Math.abs(anchor.height - 187) < 0.001);
assert.ok(
Math.abs(Cesium.Math.toDegrees(anchor.longitude) + 97.7431) < 1e-7,
);
assert.ok(Math.abs(geo.math.toDegrees(anchor.longitude) + 97.7431) < 1e-7);
for (let i = 0; i < 60; i++) {
h.viewer.scene.postRender.raiseEvent();
h.engine.fake.frame();
entity.gevDisplayPosition();
}
assert.equal(samples, 1, 'no per-frame raycasts');
h.advance(1000);
h.viewer.scene.postRender.raiseEvent();
h.engine.fake.frame();
assert.equal(samples, 2);
h.click(null);
h.advance(1000);
h.viewer.scene.postRender.raiseEvent();
h.engine.fake.frame();
assert.equal(samples, 2, 'no terrain sampling without a selection');
} finally {
h.restore();
@@ -879,8 +889,9 @@ test('two factories keep their requests, records and destruction independent', a
},
};
let resolveFirst, firstSignal;
const shownB = trackedDisplay();
const first = createAlprCamerasLayer({
rendererFactory: createAlprCesiumRenderer,
rendererFactory: trackedDisplay().factory,
services,
source: {
fetch: (_box, signal) => {
@@ -892,7 +903,7 @@ test('two factories keep their requests, records and destruction independent', a
},
});
const second = createAlprCamerasLayer({
rendererFactory: createAlprCesiumRenderer,
rendererFactory: shownB.factory,
services,
source: {
label: 'Test camera directory',
@@ -921,22 +932,24 @@ test('two factories keep their requests, records and destruction independent', a
await pending;
assert.equal(first.getStats().count, 0);
assert.equal(second.getStats().count, 1);
assert.equal(b.source.entities.values[0].id, 'directory:99');
const [marker] = shownB.display.markers();
assert.equal(marker.id, 'directory:99');
assert.equal(second.source, 'Test camera directory');
assert.ok(
b.source.entities.values[0].gevLabelModel.details.includes(
'Source: Test directory',
),
assert.ok(marker.gevLabelModel.details.includes('Source: Test directory'));
assert.equal(a.engine.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.engine.frames.preRender.numberOfListeners, 0);
assert.deepEqual(
a.engine.movers.list(),
[],
'the destroyed layer leaves no sets',
);
assert.equal(a.viewer.camera.moveEnd.numberOfListeners, 0);
assert.equal(a.viewer.scene.postRender.numberOfListeners, 0);
} finally {
b.restore();
a.restore();
}
});
test('markers sit on the cached floor; unknown floors clamp only until they resolve', async () => {
test('markers sit on the cached floor; unknown floors wait on the terrain until they resolve', async () => {
// Ground clamping re-samples every marker whenever a photoreal tile streams
// in; a whole-city view (about 1,000 cameras) stuttered while zooming.
const floors = new Map([['30.2672', 150]]);
@@ -965,8 +978,9 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
selectEntityContext() {},
},
};
const shown = trackedDisplay();
const layer = createAlprCamerasLayer({
rendererFactory: createAlprCesiumRenderer,
rendererFactory: shown.factory,
services,
source: {
fetch: async () => ({
@@ -980,42 +994,39 @@ test('markers sit on the cached floor; unknown floors clamp only until they reso
},
});
const h = cameraHarness(layer);
h.engine.fake.script('terrainHeight', 140);
const marker = (id) => shown.display.markers().find((m) => m.id === id);
const height = (m) => geo.cartographic.fromCartesian(m.position).height;
try {
await layer.update();
const known = h.source.entities.getById('directory:1');
const unknown = h.source.entities.getById('directory:2');
assert.equal(
known.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(known.position.getValue()).height -
151.5,
) < 0.01,
);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.CLAMP_TO_GROUND,
);
const known = marker('directory:1');
const unknown = marker('directory:2');
assert.equal(known.clamped, false);
assert.ok(Math.abs(height(known) - 151.5) < 0.01);
assert.equal(unknown.clamped, true);
assert.ok(Math.abs(height(unknown) - 141.5) < 0.01, 'on the terrain');
assert.equal(resolveCalls, 1);
releaseResolve();
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(unknown.clamped, false);
assert.ok(Math.abs(height(unknown) - 161.5) < 0.01);
assert.equal(
unknown.billboard.heightReference.getValue(),
Cesium.HeightReference.NONE,
);
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(unknown.position.getValue()).height -
161.5,
) < 0.01,
);
assert.equal(
h.source.entities.getById('directory:2'),
marker('directory:2'),
unknown,
'placed in place, not rebuilt',
);
const { store } = h.engine.fake.moverSet('alpr-cameras');
const index = h.shownIds().indexOf('directory:2');
assert.ok(
Math.abs(
geo.cartographic.fromCartesian({
x: store.positions[index * 3],
y: store.positions[index * 3 + 1],
z: store.positions[index * 3 + 2],
}).height - 161.5,
) < 0.01,
'and its badge with it',
);
} finally {
h.restore();
}
@@ -1025,30 +1036,22 @@ test('loaded cameras outside the view say so instead of looking unloaded', async
// Field review: "nearby" spans twice the camera-to-ground range, so a view
// could hold cameras with none on screen and read as a failed load.
const h = cameraHarness();
const project = Cesium.SceneTransforms.worldToWindowCoordinates;
let inView = false;
Cesium.SceneTransforms.worldToWindowCoordinates = () =>
inView ? new Cesium.Cartesian2(100, 100) : new Cesium.Cartesian2(-500, 100);
h.engine.fake.script('worldToWindow', () =>
inView ? { x: 100, y: 100 } : { x: -500, y: 100 },
);
try {
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7431,
30.2672,
2000,
);
h.viewer.scene.canvas.clientWidth = 800;
h.viewer.scene.canvas.clientHeight = 600;
await alprCamerasLayer.update();
let stats = alprCamerasLayer.getStats();
assert.equal(stats.onScreen, 0);
assert.match(stats.countLabel, /1 nearby · 0 on screen/);
assert.match(stats.loadingLabel, /None on screen/);
inView = true;
h.viewer.camera.moveEnd.raiseEvent();
h.engine.camera.moveEnd.raiseEvent();
stats = alprCamerasLayer.getStats();
assert.equal(stats.onScreen, 1);
assert.doesNotMatch(stats.loadingLabel, /None on screen/);
} finally {
Cesium.SceneTransforms.worldToWindowCoordinates = project;
h.restore();
}
});
@@ -1065,23 +1068,16 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
);
await alprCamerasLayer.update();
h.click('alpr:42');
const entity = h.source.entities.getById('alpr:42');
const position = entity.position,
line = entity.polyline;
const entity = h.marker('alpr:42');
const position = entity.position;
// Ground-clamped native wedges cost ~40 ms per frame for a downtown view;
// bearings are painted by the overlay for the nearest cameras instead.
assert.equal(line, undefined);
assert.equal(entity.polygon, undefined);
assert.deepEqual(h.engine.lines.list(), [], 'no native wedge lines');
let selections = 0,
clears = 0,
collectionChanges = 0;
clears = 0;
const revision = alprCamerasLayer.getStats().renderRevision;
window.addEventListener('gev:entity-selected', () => selections++);
window.addEventListener('gev:entity-selection-cleared', () => clears++);
h.source.entities.collectionChanged.addEventListener(
(_collection, added, removed) => {
collectionChanges += added.length + removed.length;
},
);
h.setBox({ south: 30.261, west: -97.749, north: 30.279, east: -97.731 });
await alprCamerasLayer.update();
h.expire();
@@ -1097,32 +1093,32 @@ test('orbit cache hits and metadata refreshes preserve marker geometry and selec
]),
);
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(entity.polyline, line);
assert.equal(
getSelectedEntityContext().properties.operator,
'Updated directory',
);
assert.equal(selections, 0);
assert.equal(clears, 0);
assert.equal(collectionChanges, 0);
assert.equal(
alprCamerasLayer.getStats().renderRevision,
revision,
'no marker was added or removed',
);
assert.equal(h.requests.length, 2, 'only expiry needs another request');
h.expire();
h.setFetch(async () => cameraResponse([cameraNode(42, { lon: -97.742 })]));
await alprCamerasLayer.update();
assert.equal(h.source.entities.getById('alpr:42'), entity);
assert.equal(h.marker('alpr:42'), entity);
assert.equal(
entity.polyline,
undefined,
entity.gevAlprWedge,
null,
'removed direction must not persist',
);
assert.ok(
Cesium.Cartesian3.equals(
entity.position.getValue(),
Cesium.Cartesian3.fromDegrees(-97.742, 30.2672),
),
);
const moved = geo.cartographic.fromCartesian(entity.position);
assert.ok(Math.abs(geo.math.toDegrees(moved.longitude) + 97.742) < 1e-9);
assert.ok(Math.abs(geo.math.toDegrees(moved.latitude) - 30.2672) < 1e-9);
} finally {
h.restore();
}
@@ -1159,47 +1155,37 @@ 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 })]));
await second;
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
['alpr:43'],
);
assert.deepEqual(h.shownIds(), ['alpr:43']);
} finally {
h.restore();
}
});
test('ground-centered orbits ignore horizon rectangles while sky, distant and dateline views stay bounded', async () => {
test('the nearby box follows the ground under the view centre: horizon rectangles never matter, sky, distant and dateline views stay bounded', async () => {
const h = cameraHarness();
const camera = h.viewer.camera;
const focus = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672);
h.viewer.scene.canvas.clientWidth = 1440;
h.viewer.scene.canvas.clientHeight = 900;
camera.pickEllipsoid = () => focus;
camera.positionWC = Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 1200);
h.focus(30.2672, -97.7431, 1200);
try {
await alprCamerasLayer.update();
const entity = h.source.entities.getById('alpr:42');
const entity = h.marker('alpr:42');
h.click('alpr:42');
for (const box of [null, { south: 31, west: -99, north: 36, east: -95 }]) {
h.setBox(box);
for (const rectangle of [
null,
{ south: 0.54, west: -1.73, north: 0.63, east: -1.66 },
]) {
h.engine.fake.script('viewRectangle', rectangle);
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(h.requests.length, 1);
}
camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7431,
30.2672,
800000,
);
h.focus(30.2672, -97.7431, 800000);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.source.entities.values.length, 0);
camera.pickEllipsoid = () => undefined;
assert.equal(h.shownIds().length, 0);
h.focus(null);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
camera.pickEllipsoid = () => Cesium.Cartesian3.fromDegrees(179.999, 0);
camera.positionWC = Cesium.Cartesian3.fromDegrees(179.999, 0, 1200);
h.focus(0, 179.999, 1200);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().status, 'zoom-in');
assert.equal(h.requests.length, 1);
@@ -1210,47 +1196,52 @@ test('ground-centered orbits ignore horizon rectangles while sky, distant and da
test('nearby count and discovery control frame a real loaded camera without fetching or stealing tracking', async () => {
const h = cameraHarness();
const flights = [];
h.viewer.camera.positionWC = Cesium.Cartesian3.fromDegrees(
-97.7431,
30.2672,
600,
);
h.viewer.camera.flyToBoundingSphere = (sphere, options) =>
flights.push({ sphere, options });
h.viewer.scene.globe.show = true;
h.viewer.scene.globe.getHeight = () => 312;
h.focus(30.2672, -97.7431, 600);
const flights = () =>
h.engine.fake
.callsOf('camera.flyToSphere')
.map(({ args: [sphere, options] }) => ({ sphere, options }));
// A keyless basemap: no rendered tiles under the camera, the globe's terrain.
h.engine.fake.script('terrainHeight', 312);
try {
assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true);
await alprCamerasLayer.update();
assert.equal(alprCamerasLayer.getStats().countLabel, '1 nearby');
assert.equal(
alprCamerasLayer.getStats().countLabel,
'1 nearby · 1 on screen',
);
const controls = alprCamerasLayer.getRowControls();
assert.equal(controls.legend[0].label, 'Camera badges');
assert.equal(controls.chips[0].onClick(), true);
assert.equal(flights.length, 1);
assert.equal(flights().length, 1);
assert.equal(getSelectedEntityContext().id, 'alpr:42');
const center = Cesium.Cartographic.fromCartesian(flights[0].sphere.center);
assert.ok(
Math.abs(Cesium.Math.toDegrees(center.latitude) - 30.2672) < 1e-9,
);
const [flight] = flights();
const center = geo.cartographic.fromCartesian(flight.sphere.center);
assert.ok(Math.abs(geo.math.toDegrees(center.latitude) - 30.2672) < 1e-9);
assert.ok(
Math.abs(center.height - 312) < 1e-6,
'use the rendered globe floor on keyless basemaps',
);
assert.equal(flights[0].options.offset.range, 800);
assert.equal(flight.sphere.radius, 30);
assert.equal(flight.options.range, 800);
assert.equal(flight.options.pitch, -Math.PI / 4);
assert.equal(flight.options.duration, 1.2);
assert.equal(h.requests.length, 1);
h.viewer.trackedEntity = {};
const follow = h.engine.camera.follow({
position: () => geo.cartesian3.fromDegrees(-97.7, 30.2, 3000),
viewFrom: { x: 0, y: -500, z: 300 },
});
assert.equal(alprCamerasLayer.getRowControls().chips[0].disabled, true);
assert.equal(
controls.chips[0].onClick(),
false,
'a stale button cannot steal the follow camera',
);
h.viewer.trackedEntity = undefined;
follow.stop();
alprCamerasLayer.disable();
assert.equal(alprCamerasLayer.getStats().countLabel, '');
assert.equal(controls.chips[0].onClick(), false);
assert.equal(flights.length, 1);
assert.equal(flights().length, 1);
} finally {
h.restore();
}
@@ -1333,8 +1324,9 @@ test('slow ALPR floors share real terrain requests across preparation, render an
latitude: 30.261 + Math.floor(i / 15) * 0.001,
longitude: -97.749 + (i % 15) * 0.001,
}));
const shown = trackedDisplay();
const layer = createAlprCamerasLayer({
rendererFactory: createAlprCesiumRenderer,
rendererFactory: shown.factory,
source: {
fetch: async () => ({ records, stale: false, saturated: false }),
},
@@ -1390,7 +1382,7 @@ test('slow ALPR floors share real terrain requests across preparation, render an
requests[1].release();
await new Promise((done) => setTimeout(done, 0));
assert.equal(requests.length, 2, 'queued final cells are discarded');
assert.equal(h.source.entities.values.length, 0);
assert.equal(shown.display.markers().length, 0);
layer.enable();
await layer.update();
assert.equal(
@@ -1409,7 +1401,7 @@ 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 every ALPR marker in place and return canvas-owned badges at the new floor', async () => {
let floor = 180;
let listener;
let removed = 0;
@@ -1419,8 +1411,9 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
longitude: -97.7431,
directionDeg: i === 0 ? null : 90,
}));
const shown = trackedDisplay();
const layer = createAlprCamerasLayer({
rendererFactory: createAlprCesiumRenderer,
rendererFactory: shown.factory,
source: {
fetch: async () => ({ records, stale: false, saturated: false }),
},
@@ -1446,42 +1439,48 @@ test('map-source changes reposition all ALPR entities and saved native appearanc
},
});
const h = cameraHarness(layer);
h.engine.fake.script('terrainHeight', 90);
const drawnHeight = (marker) => {
const { positions } = h.engine.fake.moverSet('alpr-cameras').store;
const at = marker.index * 3;
return geo.cartographic.fromCartesian({
x: positions[at],
y: positions[at + 1],
z: positions[at + 2],
}).height;
};
try {
await layer.update();
const entities = [...h.source.entities.values];
const saved = entities[1];
saved.gevAlprNativeAppearance = {
position: saved.position,
heightReference: saved.billboard.heightReference,
};
saved.position = Cesium.Cartesian3.fromDegrees(-97.7431, 30.26721, 190);
saved.gevAlprPickPosition = saved.position;
const markers = shown.display.markers();
// The overlay owns one badge: a pick target at its canvas anchor.
const owned = markers[1];
owned.gevAlprCanvasPosition = geo.cartesian3.fromDegrees(
-97.7431,
30.26721,
190,
);
owned.canvasOwned = true;
owned.drawn = null;
for (const next of [150, 120, null, 180]) {
floor = next;
// Includes a provider switch with the same globe.show value.
h.viewer.scene.globe.show = next !== 180;
listener({ detail: { status: 'ready' } });
for (const entity of entities) {
assert.equal(h.source.entities.getById(entity.id), entity);
h.engine.fake.frame();
const expected = (next ?? 90) + 1.5;
assert.deepEqual(shown.display.markers(), markers, 'no marker rebuilt');
for (const marker of markers) {
assert.ok(
Math.abs(
Cesium.Cartographic.fromCartesian(entity.position.getValue())
.height - (next == null ? 0 : next + 1.5),
geo.cartographic.fromCartesian(marker.position).height - expected,
) < 0.01,
`${entity.id} refreshes at ${next}`,
`${marker.id} refreshes at ${next}`,
);
assert.equal(
entity.billboard.heightReference.getValue(),
next == null
? Cesium.HeightReference.CLAMP_TO_GROUND
: Cesium.HeightReference.NONE,
);
assert.equal(entity.gevAlprCanvasPosition, null);
assert.equal(marker.clamped, next == null);
assert.equal(marker.gevAlprCanvasPosition, null);
}
assert.equal(
saved.gevAlprNativeAppearance,
null,
'saved appearance restores at the new floor',
assert.equal(owned.canvasOwned, false);
assert.ok(
Math.abs(drawnHeight(owned) - expected) < 0.01,
'the owned badge returns to its own place at the new floor',
);
}
} finally {
@@ -1494,7 +1493,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const h = cameraHarness();
try {
await alprCamerasLayer.update();
const previous = h.source.entities.getById('alpr:42');
const previous = h.marker('alpr:42');
const revision = alprCamerasLayer.getStats().renderRevision;
let release;
h.setFetch(
@@ -1507,7 +1506,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
const pending = alprCamerasLayer.update();
await alprCamerasLayer.update();
assert.equal(
h.source.entities.getById('alpr:42'),
h.marker('alpr:42'),
previous,
'do not show an intermediate filtered snapshot while the new query prepares',
);
@@ -1516,10 +1515,7 @@ test('a repeated move inside an outstanding query keeps the displayed marker set
release(cameraResponse([cameraNode(43, { lat: 31.01, lon: -97.99 })]));
await pending;
assert.equal(alprCamerasLayer.getStats().renderRevision, revision + 1);
assert.deepEqual(
h.source.entities.values.map((e) => e.id),
['alpr:43'],
);
assert.deepEqual(h.shownIds(), ['alpr:43']);
} finally {
h.restore();
}
+17 -9
View File
@@ -1,6 +1,8 @@
import test from 'node:test';
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 { COLOR_NEUTRAL } from '../layers/bikeshare/policy.js';
import {
BIKESHARE_SELECTED_OVERLAY_SOURCE_OPTIONS,
_clearBikeshareSelectionForTest,
@@ -20,7 +22,9 @@ function makeRecord() {
isRenting: false,
isReturning: true,
point: {
position: Cesium.Cartesian3.fromDegrees(-97.7431, 30.2672, 2),
position: geo.cartesian3.fromDegrees(-97.7431, 30.2672, 2),
pixelSize: 8,
color: COLOR_NEUTRAL,
show: true,
},
};
@@ -44,7 +48,7 @@ test('selected bikeshare entry preserves source copy and protected-lane policy',
assert.equal(entry.horizonCull, false);
});
test('real station select/clear path publishes one card and creates no native label graphic', () => {
test('real station select/clear path publishes one card and draws the highlight as a point', () => {
const calls = [];
const overlayHost = {
setEntries: (...args) => calls.push(['entries', ...args]),
@@ -53,14 +57,18 @@ test('real station select/clear path publishes one card and creates no native la
};
const key = 'austin-capmetro:3790';
const record = makeRecord();
const viewer = { entities: new Cesium.EntityCollection() };
_setBikeshareSelectionStateForTest({ viewer, key, record, overlayHost });
const engine = createFakeEngine();
const highlight = () => engine.fake.moverSet('bikeshare-selected');
_setBikeshareSelectionStateForTest({ engine, key, record, overlayHost });
try {
_selectBikeshareStationForTest(key);
assert.equal(record.point.show, false);
assert.equal(viewer.entities.values.length, 1, 'runtime guard requires a real selected entity');
assert.equal(viewer.entities.values[0].label, undefined);
assert.ok(viewer.entities.values[0].point, 'selected point highlight remains native');
assert.equal(
highlight().options.kind,
'point',
'the selected highlight is a native point, its label the card',
);
assert.equal(highlight().store.pickIds[0], key);
const publication = calls.find(([type]) => type === 'entries');
assert.ok(publication);
@@ -71,7 +79,7 @@ test('real station select/clear path publishes one card and creates no native la
_clearBikeshareSelectionForTest();
assert.equal(record.point.show, true);
assert.equal(viewer.entities.values.length, 0);
assert.equal(highlight().store.count, 0);
assert.deepEqual(calls.at(-1), ['clear', 'bikeshare-selected']);
} finally {
_clearBikeshareSelectionForTest();
+7 -11
View File
@@ -117,27 +117,23 @@ test('every scene click handler consults ownership before it picks', () => {
['src/data/trackingClickGesture.js', 'onClick(click, gesture);'],
['src/data/localGeojsonCore.js', 'viewer.scene.pick(click.position)'],
['src/data/cctvGizmo.js', 'pickGizmoPart(event.position)'],
[
'src/layers/alpr/render/cesiumPresentation.js',
'viewer.scene.pick(click.position)',
],
[
'src/layers/bikeshare/render/cesium/selection.js',
'viewer.scene.pick(click.position)',
],
// ALPR and bikeshare take the engine's click with its pick.
['src/layers/alpr/render/display.js', 'overlay.pick(position) ||'],
['src/layers/bikeshare/render/display.js', 'const picked = event.picked;'],
['src/layers/firms/selection.js', 'scene.pick(click.position)'],
[
'src/layers/installations/render/cesium/selection.js',
'viewer.scene.pick(click.position)',
],
['src/layers/launches/render/cesium.js', 'drillPick(movement.position'],
['src/layers/launches/render/display.js', '[ctx.picked, ...ctx.drilled]'],
[
'src/layers/radio/interaction.js',
'const stationId = pickedRadioStationAt(position);',
],
// Satellites take the engine dispatcher's pick too.
[
'src/layers/satellites/render/cesium.js',
'viewer.scene.pick(click.position)',
'src/layers/satellites/interaction.js',
'getRenderer().isTrackedPick(picked',
],
[
'src/layers/submarineCables/interaction.js',
+97 -91
View File
@@ -2,6 +2,9 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { gstime } from 'satellite.js';
import * as geo from '../geo/index.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import { createCesiumMoversEngine } from '../testSupport/cesiumMoversEngine.mjs';
import { createModel } from '../layers/launches/model.js';
import rocketLaunchesLayer, {
_setRocketMissionOverlayHostForTest,
@@ -1095,13 +1098,40 @@ test('finds a newly launched payload in the active TLE fallback catalog', () =>
assert.equal(typeof track?.positionAt, 'function');
});
test('real mission build, select, refresh, deselect, disable, and destroy paths publish no native labels', async () => {
// The layer on the fake engine and on the Cesium engine over a stub scene:
// a frame, a frame start alone (preUpdate) and the end of the layer's flights.
const MISSION_HARNESSES = [
() => {
const engine = createFakeEngine({ width: 1600, height: 900 });
return {
name: 'the fake engine',
engine,
frame: () => engine.fake.frame(),
frameStart: () => engine.fake.emit('frames.preUpdate', 0),
land: () => engine.fake.frames(400),
};
},
() => {
const { engine, viewer, frame } = createCesiumMoversEngine();
viewer.scene.globe.getHeight = () => 0;
// The stub scene runs no flight tweens: the layer's flights land at once.
const fly = viewer.camera.flyTo.bind(viewer.camera);
viewer.camera.flyTo = (options) => fly({ ...options, duration: 0 });
return {
name: 'the Cesium engine',
engine,
frame,
frameStart: () =>
viewer.scene.preUpdate.raiseEvent(viewer.scene, viewer.clock.currentTime),
land: () => {},
};
},
];
for (const makeHarness of MISSION_HARNESSES)
test(`real mission build, select, refresh, deselect, disable, and destroy paths publish no native labels (${makeHarness().name})`, async () => {
const realDocument = globalThis.document;
const realFetch = globalThis.fetch;
const realHtmlCanvasElement = globalThis.HTMLCanvasElement;
const realHtmlImageElement = globalThis.HTMLImageElement;
const realImageBitmap = globalThis.ImageBitmap;
const realOffscreenCanvas = globalThis.OffscreenCanvas;
const listeners = new Map();
const context = {
strokeStyle: '',
@@ -1156,37 +1186,15 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
addEventListener(type, handler) { listeners.set(`document:${type}`, handler); },
removeEventListener(type) { listeners.delete(`document:${type}`); },
};
const canvas = new FakeElement('canvas');
const dataSources = [];
const camera = {
positionCartographic: null,
positionWC: Cesium.Cartesian3.fromDegrees(-80.604, 28.608, 18_000_000),
cancelFlight() {},
lookAtTransform() {},
};
const scene = {
canvas,
camera,
frameState: { frameNumber: 1 },
postRender: new Cesium.Event(),
preRender: new Cesium.Event(),
preUpdate: new Cesium.Event(),
primitives: { add: (primitive) => primitive, remove: () => true },
drillPick: () => [],
};
const viewer = {
camera,
scene,
dataSources: {
add(dataSource) { dataSources.push(dataSource); return dataSource; },
remove(dataSource) {
const index = dataSources.indexOf(dataSource);
if (index >= 0) dataSources.splice(index, 1);
return index >= 0;
},
},
selectedEntity: undefined,
};
const harness = makeHarness();
const { engine } = harness;
const lookFrom = (lon, lat) =>
engine.camera.setView({ destination: geo.cartesian3.fromDegrees(lon, lat, 18_000_000) });
lookFrom(-80.604, 28.608);
const plain = (p) => (p ? { x: p.x, y: p.y, z: p.z } : null);
const drawnPoint = (id) =>
rocketLaunchesLayer.qaDrawn().points.find((point) => point.id === id);
const element = (id) => rocketLaunchesLayer._missionElementForTest(id);
const hostCalls = [];
const host = {
setEntries: (...args) => hostCalls.push(['entries', ...args]),
@@ -1223,10 +1231,6 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
},
}] });
globalThis.document = document;
globalThis.HTMLCanvasElement = FakeElement;
globalThis.HTMLImageElement = class {};
globalThis.ImageBitmap = class {};
globalThis.OffscreenCanvas = class {};
globalThis.fetch = async (url) => {
if (url === '/api/celestrak/active') {
return { ok: true, text: async () => '' };
@@ -1237,14 +1241,17 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
_setRocketMissionOverlayHostForTest(host);
let initialized = false;
try {
rocketLaunchesLayer.init(viewer);
rocketLaunchesLayer.init(null, { engine });
initialized = true;
await rocketLaunchesLayer.enable();
await rocketLaunchesLayer.update();
// The full-globe entry flight lands before the camera moves.
harness.land();
const entities = dataSources[0].entities.values;
assert.ok(entities.length >= 7, 'runtime guard requires the populated mission build path');
assert.ok(entities.every((entity) => entity.label === undefined));
const drawn = rocketLaunchesLayer.qaDrawn();
assert.ok(drawn.points.length + drawn.paths.length >= 6, 'runtime guard requires the populated mission build path');
// Only dots, the reticle and lines: the labels are the host's.
assert.ok(engine.movers.list().every(({ kind }) => kind === 'point' || kind === 'sprite'));
const ambientPublication = hostCalls.findLast(([type, sourceId]) => (
type === 'entries' && sourceId === ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID
));
@@ -1256,26 +1263,25 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
collisionCapacity: ROCKET_MISSION_AMBIENT_OVERLAY_COLLISION_CAPACITY,
moving: false,
});
const launchEntity = dataSources[0].entities.getById('rocket-launch:mission-runtime');
assert.deepEqual(
ambientPublication[2][0].position,
launchEntity.position.getValue(Cesium.JulianDate.now()),
'ambient host marker must reuse the entity anchor Cartesian',
);
const frameTime = Cesium.JulianDate.now();
scene.preRender.raiseEvent(scene, frameTime);
assert.equal(launchEntity.point.show.getValue(frameTime), true);
camera.positionWC = Cesium.Cartesian3.fromDegrees(99.396, -28.608, 18_000_000);
scene.preRender.raiseEvent(scene, frameTime);
const launchElement = element('rocket-launch:mission-runtime');
assert.equal(
launchEntity.point.show.getValue(frameTime),
ambientPublication[2][0].position,
launchElement.position,
'ambient host marker must reuse the element anchor Cartesian',
);
harness.frame();
assert.equal(drawnPoint('rocket-launch:mission-runtime').show, true);
lookFrom(99.396, -28.608);
harness.frame();
assert.equal(
drawnPoint('rocket-launch:mission-runtime').show,
false,
'pre-render horizon pass must hide a rear-side depth-free mission dot before draw and pick',
);
camera.positionWC = Cesium.Cartesian3.fromDegrees(-80.604, 28.608, 18_000_000);
scene.preRender.raiseEvent(scene, frameTime);
lookFrom(-80.604, 28.608);
harness.frame();
assert.equal(
launchEntity.point.show.getValue(frameTime),
drawnPoint('rocket-launch:mission-runtime').show,
true,
'mission dot must return when its surface anchor faces the camera again',
);
@@ -1301,17 +1307,16 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
&& entry.paintLane === 'selected'
&& entry.edgeFade === 'keyhole'
)));
const satelliteEntity = dataSources[0].entities.getById('rocket-satellite:mission-runtime');
const satellitePosition = satelliteEntity.position.getValue(Cesium.JulianDate.now());
const satellite = element('rocket-satellite:mission-runtime');
assert.equal(
selectedPublication[2][2].position(),
satellitePosition,
satellite.position(),
'payload host getter must return the exact per-frame live-position cache',
);
// Jitter regression net: live-state propagation advances at most once per
// frameNumber, and the host getter is a pure read that never advances it.
// Without both halves, the host label and the native dot can propagate to
// engine frame, and the host getter is a pure read that never advances it.
// Without both halves, the host label and the dot can propagate to
// different wall-clock instants inside one frame — the documented
// label-separation jitter class.
const payloadEntry = selectedPublication[2][2];
@@ -1319,52 +1324,55 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
try {
let nowMs = realDateNow();
Date.now = () => nowMs;
scene.frameState.frameNumber = 41;
const frameA = Cesium.Cartesian3.clone(
satelliteEntity.position.getValue(Cesium.JulianDate.now()),
);
// The frame's dot reads the payload position.
harness.frame();
const frameA = plain(satellite.position());
nowMs += 30_000;
assert.deepEqual(
Cesium.Cartesian3.clone(satelliteEntity.position.getValue(Cesium.JulianDate.now())),
plain(satellite.position()),
frameA,
'a second native read in the same frame must not re-propagate',
'a second read in the same frame must not re-propagate',
);
nowMs += 30_000;
scene.frameState.frameNumber = 42;
// A new frame that nothing has drawn yet.
harness.frameStart();
assert.deepEqual(
Cesium.Cartesian3.clone(payloadEntry.position()),
plain(payloadEntry.position()),
frameA,
'host getter must not advance propagation, even on a new frame',
);
const frameB = Cesium.Cartesian3.clone(
satelliteEntity.position.getValue(Cesium.JulianDate.now()),
);
assert.notDeepEqual(frameB, frameA, 'native read on a new frame propagates (non-vacuous)');
const frameB = plain(satellite.position());
assert.notDeepEqual(frameB, frameA, 'a read on a new frame propagates (non-vacuous)');
assert.deepEqual(
Cesium.Cartesian3.clone(payloadEntry.position()),
plain(payloadEntry.position()),
frameB,
'host getter reads the advanced cache after native propagation',
'host getter reads the advanced cache after propagation',
);
harness.frame();
assert.deepEqual(
plain(drawnPoint('rocket-satellite:mission-runtime').position),
plain(payloadEntry.position()),
'the drawn dot and the host label share the frame position',
);
} finally {
Date.now = realDateNow;
scene.frameState.frameNumber = 1;
}
const reentryEntity = dataSources[0].entities.getById('rocket-reentry:mission-runtime:0');
const reentry = element('rocket-reentry:mission-runtime:0');
assert.deepEqual(
selectedPublication[2][1].position,
reentryEntity.polyline.positions.getValue(Cesium.JulianDate.now())[0],
reentry.positions[0],
're-entry host label must reuse the recovery-path interface Cartesian',
);
const transferEntity = dataSources[0].entities.getById('rocket-transfer:mission-runtime');
const transfer = element('rocket-transfer:mission-runtime');
assert.deepEqual(
selectedPublication[2][3].position,
transferEntity.polyline.positions.getValue(Cesium.JulianDate.now()).at(-1),
transfer.positions.at(-1),
'orbit host label must reuse the insertion Cartesian',
);
launchName = 'Mission Refresh | Gauntlet Payload';
await rocketLaunchesLayer.update();
assert.ok(dataSources[0].entities.values.every((entity) => entity.label === undefined));
assert.ok(engine.movers.list().every(({ kind }) => kind === 'point' || kind === 'sprite'));
const refreshPublication = hostCalls.findLast(([type, sourceId]) => (
type === 'entries' && sourceId === ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID
));
@@ -1385,9 +1393,10 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
['clear', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID],
['visible', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID, false],
]);
await rocketLaunchesLayer.destroy(viewer);
await rocketLaunchesLayer.destroy();
initialized = false;
assert.equal(dataSources.length, 0);
assert.deepEqual(engine.movers.list(), []);
assert.deepEqual(engine.lines.list(), []);
assert.deepEqual(hostCalls.slice(-4), [
['clear', ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID],
['visible', ROCKET_MISSION_AMBIENT_OVERLAY_SOURCE_ID, false],
@@ -1395,14 +1404,11 @@ test('real mission build, select, refresh, deselect, disable, and destroy paths
['visible', ROCKET_MISSION_SELECTED_OVERLAY_SOURCE_ID, false],
]);
} finally {
if (initialized) await rocketLaunchesLayer.destroy(viewer);
if (initialized) await rocketLaunchesLayer.destroy();
engine.destroy();
_setRocketMissionOverlayHostForTest();
globalThis.fetch = realFetch;
globalThis.document = realDocument;
globalThis.HTMLCanvasElement = realHtmlCanvasElement;
globalThis.HTMLImageElement = realHtmlImageElement;
globalThis.ImageBitmap = realImageBitmap;
globalThis.OffscreenCanvas = realOffscreenCanvas;
}
});
-1
View File
@@ -104,7 +104,6 @@ test('satellite getAnalystRecords: core rows beat dense extras under the cap', (
satrec,
entity: {},
point,
viewer: {},
now: () => Date.now(),
neighbours: [
{
+24 -40
View File
@@ -18,6 +18,7 @@ import {
} from './satellites.js';
import satellitesLayer from './satellites.js';
import { createTrackedOverlayEntry } from './trackedReadout.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
const L1 =
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927';
@@ -99,16 +100,9 @@ test('selected satellite params survive delayed arrival and yield to newer expli
outlineWidth: 2,
disableDepthTestDistance: 0,
};
const viewer = {
entities: new Cesium.EntityCollection(),
trackedEntity: undefined,
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
const engine = createFakeEngine();
_setSatelliteLabelLifecycleStateForTest({
viewer,
engine,
satrec: twoline2satrec(L1, L2),
point,
});
@@ -117,7 +111,10 @@ test('selected satellite params survive delayed arrival and yield to newer expli
satellitesLayer.setParams({ selectedSatTrackingId: 25544 }),
);
assert.equal(satellitesLayer.getParams().selectedSatTrackingId, 25544);
assert.equal(viewer.trackedEntity?.gevTrackedId, 'satellites:25544');
assert.equal(
engine.camera.following()?.native.gevTrackedId,
'satellites:25544',
);
satellitesLayer.stopTracking();
_removeSatelliteTrackingCandidateForTest(25544);
@@ -127,7 +124,7 @@ test('selected satellite params survive delayed arrival and yield to newer expli
);
assert.equal(_pendingSatelliteTrackingRestoreForTest(), 25544);
_setSatelliteLabelLifecycleStateForTest({
viewer,
engine,
satrec: twoline2satrec(L1, L2),
point,
preservePending: true,
@@ -163,7 +160,7 @@ test('selected satellite params survive delayed arrival and yield to newer expli
'explicit clear cancels stale restore',
);
_setSatelliteLabelLifecycleStateForTest({
viewer,
engine,
satrec: twoline2satrec(L1, L2),
point,
preservePending: true,
@@ -196,7 +193,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
// members — never unrelated satellites that merely happen to be nearby.
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const point = { position: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
const engine = createFakeEngine();
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
// The tracked satellite moves ~7.6 km/s, so neighbours are defined RELATIVE to
// wherever it is at scan time rather than pinned to a stale sample.
@@ -213,7 +210,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
satrec: twoline2satrec(L1, L2),
entity,
point,
viewer,
engine,
now: () => nowMs,
neighbours: [
{ noradId: 55555, name: 'PROGRESS-MS 34', point: near(120) }, // berthed
@@ -226,7 +223,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
// The cluster scan is throttled, so advance past its interval before the frame
// that must observe the cluster.
nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
engine.fake.frame();
_runSatellitePreRenderForTest();
const details = entity.gevLabelModel.details;
@@ -254,10 +251,7 @@ test('a tracked docked cluster consolidates its companions onto one card', () =>
test('satellite pre-render refreshes the tracked altitude on each propagated frame', () => {
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const point = { position: new Cesium.Cartesian3() };
const viewer = {
camera: null,
scene: { frameState: { frameNumber: 1 } },
};
const engine = createFakeEngine();
const epochs = [Date.UTC(2008, 8, 20, 12, 30), Date.UTC(2008, 8, 20, 13, 0)];
let epochIndex = 0;
_setTrackedSatelliteRefreshStateForTest({
@@ -266,7 +260,7 @@ test('satellite pre-render refreshes the tracked altitude on each propagated fra
satrec: twoline2satrec(L1, L2),
entity,
point,
viewer,
engine,
now: () => epochs[epochIndex],
});
@@ -277,7 +271,7 @@ test('satellite pre-render refreshes the tracked altitude on each propagated fra
assert.equal(entity.gevLabelModel.details[1], '353\u00a0km · NORAD 25544');
epochIndex = 1;
viewer.scene.frameState.frameNumber = 2;
engine.fake.frame();
_runSatellitePreRenderForTest();
assert.equal(entity.gevLabelModel.details[1], '366\u00a0km · NORAD 25544');
assert.equal(
@@ -303,17 +297,10 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
outlineWidth: 2,
disableDepthTestDistance: 0,
};
const viewer = {
entities: new Cesium.EntityCollection(),
trackedEntity: undefined,
scene: {
frameState: { frameNumber: 1 },
primitives: { remove() {} },
},
};
const engine = createFakeEngine();
let cleaned = false;
_setSatelliteLabelLifecycleStateForTest({
viewer,
engine,
satrec: twoline2satrec(L1, L2),
point,
overlayHost,
@@ -339,9 +326,9 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
const trackedEntity = _trackIssForTest();
assert.ok(trackedEntity);
assert.equal(
viewer.entities.values.length,
1,
'runtime guard requires a real tracked entity',
engine.camera.following()?.native,
trackedEntity,
'the follow is of the tracked satellite',
);
assert.equal(trackedEntity.label, undefined);
assert.ok(
@@ -372,7 +359,7 @@ test('ISS ambient and tracked lifecycle uses cached host entries with no native
_clearSatelliteLabelLifecycleForTest();
cleaned = true;
assert.equal(viewer.entities.values.length, 0);
assert.equal(engine.camera.following(), null);
assert.equal(
calls.filter(
([type, sourceId]) =>
@@ -405,17 +392,14 @@ test('the tracked satellite is propagated at the app clock time', async () => {
const { appClock } = await import('../time/clock.js');
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const point = { position: new Cesium.Cartesian3() };
const viewer = {
camera: null,
scene: { frameState: { frameNumber: 1 } },
};
const engine = createFakeEngine();
_setTrackedSatelliteRefreshStateForTest({
noradId: 25544,
name: 'ISS (ZARYA)',
satrec: twoline2satrec(L1, L2),
entity,
point,
viewer,
engine,
now: undefined,
});
try {
@@ -423,7 +407,7 @@ test('the tracked satellite is propagated at the app clock time', async () => {
_runSatellitePreRenderForTest();
assert.equal(entity.gevLabelModel.details[1], '353\u00a0km · NORAD 25544');
appClock.freeze(Date.UTC(2008, 8, 20, 13, 0));
viewer.scene.frameState.frameNumber = 2;
engine.fake.frame();
_runSatellitePreRenderForTest();
assert.equal(entity.gevLabelModel.details[1], '366\u00a0km · NORAD 25544');
} finally {
+4 -3
View File
@@ -8,6 +8,7 @@ import {
_trackedFrameCartesianForTest,
} from './satellites.js';
import { setLocale } from '../i18n/index.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
const L1 =
'1 25544U 98067A 08264.51782528 -.00002182 00000-0 -11606-4 0 2927';
@@ -18,7 +19,7 @@ function run(locale) {
setLocale(locale);
const entity = { gevLabelModel: { title: 'OLD', details: ['? km'] } };
const point = { position: new Cesium.Cartesian3() };
const viewer = { camera: null, scene: { frameState: { frameNumber: 1 } } };
const engine = createFakeEngine();
let nowMs = Date.UTC(2008, 8, 20, 12, 30);
const near = (metres) => ({
get position() {
@@ -32,7 +33,7 @@ function run(locale) {
satrec: twoline2satrec(L1, L2),
entity,
point,
viewer,
engine,
now: () => nowMs,
neighbours: [
{ noradId: 55555, name: 'PROGRESS-MS 34', point: near(120) },
@@ -41,7 +42,7 @@ function run(locale) {
});
_runSatellitePreRenderForTest();
nowMs += 2000;
viewer.scene.frameState.frameNumber = 2;
engine.fake.frame();
_runSatellitePreRenderForTest();
const details = entity.gevLabelModel.details;
setLocale('en');