Hand features the engine instead of guessing it from a viewer

No code outside src/globe calls isGlobeEngine or engineFromViewer any
more (14 calls left before this). The features that still sniffed take
the engine from their caller:

- Projection and surface helpers (focus de-emphasis, icon orientation,
  ground snap, the mesh floor sampler, ground picks) take the engine; the
  engine view's scene carries its projector instead of registering itself
  as a viewer.
- Credits go only through engine.credits, so annotations and layers
  share one OSM credit state on Cesium too (it could show twice).
- The annotation board and the resolver work on the engine: camera
  assists, visibility and picks go through engine.camera,
  engine.projector and src/geo, without Cesium.
- The Recent Imagery box tool has one implementation for both engines,
  on capture-phase canvas pointer events with the layer's engine.ground
  preview; the Navara copy goes. On Cesium the preview outline is solid
  now, as on Navara.
- Scene interactions take the engine, and the render governor has an
  engine variant beside the Cesium one.

Remaining engine-specific features stay behind explicit seams until the
contract covers them: the draw tool's Cesium surface (stock click actions
cannot be suspended), the annotation drapes (animated materials), share
follow, Cesium post effects and cyber sonar, and data packs (meshes).

Coupling: Cesium-importing files fall from 31 to 27, `viewer` lines
from 1367 to 1234, engine sniffing calls from 14 to 0.
This commit is contained in:
German Khokhlov committed 2026-11-07 08:46:30 +04:00
1 parent 406dd9122e
commit f1ec9d4a22
61 files changed
+823 -1230

No files matched your search

+2 -2
View File
@@ -3569,7 +3569,7 @@ export function createBhoteKoshiEventLayer({
else await _viewer.dataSources.add(_floodDataSource);
if (!current()) return;
}
registerDynamicCredit(engine ?? viewer, BHOTE_KOSHI_CREDIT);
registerDynamicCredit(engine, BHOTE_KOSHI_CREDIT);
_scenePathPositionCache.clear();
_lastCinematicProgress = null;
const terrain = syncTerrainComparison();
@@ -3640,7 +3640,7 @@ export function createBhoteKoshiEventLayer({
try {
const event = await loadEvent();
throwIfEnableCancelled(signal, _enabled);
registerDynamicCredit(_engine ?? viewer, BHOTE_KOSHI_CREDIT);
registerDynamicCredit(_engine, BHOTE_KOSHI_CREDIT);
if (_mapStackController) {
_comparisonLease = acquireImageryComparison(_mapStackController, {
owner: BHOTE_KOSHI_LAYER_ID,
+4 -5
View File
@@ -291,7 +291,6 @@ export function createBhoteKoshiLocatorLayer({
let _native = null;
let _pausedApproach = null;
const cameraForScene = () => _engine?.camera ?? _viewer?.camera;
const creditTarget = () => _engine ?? _viewer;
const requestRender = (reason) =>
_engine?.kind === 'navara'
? _engine.render.request(reason)
@@ -1049,8 +1048,8 @@ export function createBhoteKoshiLocatorLayer({
if (!_dataSource) return;
if (_viewer) _viewer.dataSources.add(_dataSource);
else if (_engine) _native = createNativeRenderer(_engine, _dataSource);
registerDynamicCredit(creditTarget(), BHOTE_KOSHI_LOCATOR_CREDIT);
showOsmCredit(creditTarget(), BHOTE_KOSHI_LOCATOR_LAYER_ID);
registerDynamicCredit(_engine, BHOTE_KOSHI_LOCATOR_CREDIT);
showOsmCredit(_engine, BHOTE_KOSHI_LOCATOR_LAYER_ID);
}
function attachRenderer(viewer, { engine = null } = {}) {
@@ -1080,7 +1079,7 @@ export function createBhoteKoshiLocatorLayer({
_native?.destroy();
_native = null;
if (_viewer && _dataSource) _viewer.dataSources.remove(_dataSource, false);
hideOsmCredit(creditTarget(), BHOTE_KOSHI_LOCATOR_LAYER_ID);
hideOsmCredit(_engine, BHOTE_KOSHI_LOCATOR_LAYER_ID);
_engine = _viewer = null;
}
@@ -1137,7 +1136,7 @@ export function createBhoteKoshiLocatorLayer({
}
async function disable() {
hideOsmCredit(creditTarget(), BHOTE_KOSHI_LOCATOR_LAYER_ID);
hideOsmCredit(_engine, BHOTE_KOSHI_LOCATOR_LAYER_ID);
_pausedApproach = null;
_enabled = false;
_boundaryReady = false;
+3 -2
View File
@@ -9,6 +9,7 @@ import * as Cesium from 'cesium';
import { FEATURE_SOURCE_METHODS } from '../sources/featureSource.js';
import { createAnnotationResolver } from '../annotations/resolver.js';
import { createWorldAnnotationRenderer } from '../annotations/worldAnnotationRenderer.js';
import { cameraOnlyEngine } from '../testSupport/viewerEngine.mjs';
const read = (path) => readFileSync(new URL(path, import.meta.url), 'utf8');
@@ -135,8 +136,8 @@ test('drawing bundled place and neighborhood outlines creates no Cesium label',
3000,
);
const resolved = await resolveAnnotationTarget({
// The resolver reads only the camera (no scene to pick from).
viewer: { camera: viewer.camera },
// The resolver reads only the camera (no canvas to pick from).
engine: cameraOnlyEngine({ camera: viewer.camera }),
target,
footprint: true,
deferFootprint: true,
+13 -27
View File
@@ -1,8 +1,5 @@
import { isGlobeEngine } from '../globe/contract.js';
import { createCesiumCredits } from '../globe/cesium/credits.js';
/**
* Per-layer data attribution registered into Cesium's credit display.
* Per-layer data attribution registered into the globe engine's credits.
*
* Legal requirement (see DATA_SOURCES.md, findings H10/H11 in
* docs/pre-ship-audit-2026-07-01.md): every third-party data layer this app can
@@ -13,7 +10,7 @@ import { createCesiumCredits } from '../globe/cesium/credits.js';
*
* These credits are registered ONCE at init as STATIC credits with
* showOnScreen=false, so they live in the expandable bottom-left "Data
* attribution" lightbox (Cesium's credit popover) rather than cluttering the
* attribution" lightbox (the engine's credit popover) rather than cluttering the
* on-globe line. Always-present is intentional and reversible: the lightbox is
* the app's canonical attribution surface and DATA_SOURCES.md is the
* machine-readable index. Strings are copied verbatim from DATA_SOURCES.md — if
@@ -49,29 +46,18 @@ export const ACARTIA_CREDIT = Object.freeze({
const osmDisplays = new WeakMap();
const googlePlacesDisplays = new WeakMap();
const viewerCredits = new WeakMap();
/**
* Credits of a globe engine, or of a Cesium viewer's credit display for
* callers that still hold a viewer (Cesium layers); null without one.
* Credits of a globe engine (engine.credits, shown on its next frame); null
* without one.
* @returns {{ addStatic: Function, request: () => void } | null}
*/
function creditsOf(target) {
if (isGlobeEngine(target))
return {
addStatic: (html, options) => target.credits.addStatic(html, options),
request: () => target.render.request('credits'),
};
if (typeof target?.creditDisplay?.addStaticCredit !== 'function') return null;
let credits = viewerCredits.get(target);
if (!credits) {
credits = {
addStatic: createCesiumCredits(target).credits.addStatic,
request: () => target.scene?.requestRender?.(),
};
viewerCredits.set(target, credits);
}
return credits;
function creditsOf(engine) {
if (typeof engine?.credits?.addStatic !== 'function') return null;
return {
addStatic: (html, options) => engine.credits.addStatic(html, options),
request: () => engine.render?.request('credits'),
};
}
function updateOsmDisplay(credits, state) {
@@ -713,7 +699,7 @@ const dynamicCreditKeys = new WeakMap();
* Register a conditional credit at the moment its data source activates.
* Idempotent per `credit.key`; lands in the same "Data attribution" popover
* as the static credits (showOnScreen=false).
* @param {object} target — the globe engine, or the initialized Cesium viewer
* @param {object} target — the globe engine
* @param {{ key: string, html: string }} credit — e.g. `TOMTOM_CREDIT`
* @returns {boolean} True when the credit is (now) registered.
*/
@@ -730,10 +716,10 @@ export function registerDynamicCredit(target, credit) {
}
/**
* Register every per-layer data credit into the viewer's credit display.
* Register every per-layer data credit into the engine's credit display.
* Idempotent: safe to call once at init. Credits are static and always
* present in the "Data attribution" popover.
* @param {object} target — the globe engine, or the initialized Cesium viewer
* @param {object} target — the globe engine
*/
export function registerDataCredits(target, credits = DATA_CREDITS) {
const display = creditsOf(target);
+27 -17
View File
@@ -56,17 +56,25 @@ test('OpenStreetMap has one generic data credit with separate tile and names dis
);
});
// A Cesium engine's credits over a viewer double's credit display.
async function cesiumCreditsEngine(viewer) {
const { createCesiumCredits } = await import('../globe/cesium/credits.js');
return {
credits: createCesiumCredits(viewer).credits,
render: { request() {} },
};
}
test('inline OSM attribution persists until its last display owner leaves', async (t) => {
const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js');
t.mock.timers.enable({ apis: ['setTimeout'] });
const visible = new Set();
const viewer = {
const viewer = await cesiumCreditsEngine({
creditDisplay: {
addStaticCredit: (c) => visible.add(c),
removeStaticCredit: (c) => visible.delete(c),
},
scene: { requestRender() {} },
};
});
assert.equal(showOsmCredit(viewer, 'alpr'), true);
assert.equal(showOsmCredit(viewer, 'alpr'), false);
assert.equal(visible.size, 1);
@@ -96,29 +104,31 @@ test('inline OSM attribution persists until its last display owner leaves', asyn
assert.equal(visible.size, 1, 'reenabling restores the short credit');
});
test('tile attribution follows source changes and viewers have independent ownership', async () => {
test('tile attribution follows source changes and engines have independent ownership', async () => {
const { showOsmCredit, hideOsmCredit } = await import('./dataCredits.js');
const create = () => {
const create = async () => {
const credits = new Set();
return {
credits,
creditDisplay: {
addStaticCredit: (c) => credits.add(c),
removeStaticCredit: (c) => credits.delete(c),
},
shown: credits,
...(await cesiumCreditsEngine({
creditDisplay: {
addStaticCredit: (c) => credits.add(c),
removeStaticCredit: (c) => credits.delete(c),
},
})),
};
};
const a = create(),
b = create();
const a = await create(),
b = await create();
showOsmCredit(a, 'installations', { openMapTiles: true });
showOsmCredit(b, 'installations');
assert.equal(a.credits.size, 2);
assert.equal(b.credits.size, 1);
assert.equal(a.shown.size, 2);
assert.equal(b.shown.size, 1);
showOsmCredit(a, 'installations');
assert.equal(a.credits.size, 1, 'wide names no longer use tiles');
assert.equal(a.shown.size, 1, 'wide names no longer use tiles');
hideOsmCredit(a, 'installations');
assert.equal(a.credits.size, 0);
assert.equal(b.credits.size, 1);
assert.equal(a.shown.size, 0);
assert.equal(b.shown.size, 1);
});
test('data credits go through the globe engine credits', async () => {
+6 -8
View File
@@ -1,15 +1,13 @@
import { worldToWindowCoordinates } from './render/cesiumProjection.js';
import * as geo from '../geo/index.js';
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
// A window position through the engine's projector when `scene` has a
// registered engine (a Cesium scene in the app, the Navara aircraft
// renderer's scene adapter), else Cesium's SceneTransforms (bare scenes in
// tests). The two agree on Cesium (the engine projector is SceneTransforms).
// A window position through the engine projector the scene carries (the
// layers' engine views, src/layers/shared/render/engineView.js), else
// Cesium's SceneTransforms (a Cesium scene). The two agree on Cesium (the
// engine projector is SceneTransforms).
function worldToWindow(scene, position, result) {
const projector = engineFromViewer(scene)?.projector;
return projector
? projector.worldToWindow(position, result)
return scene.projector
? scene.projector.worldToWindow(position, result)
: worldToWindowCoordinates(scene, position, result);
}
+6 -8
View File
@@ -163,12 +163,9 @@ test('NearFarScalar rendered-size interpolation matches Cesium clamp endpoints',
assert.ok(middle > 0.5 && middle < 3);
});
test('a focus target projects through the engine registered for its scene', async () => {
test('a focus target projects through the projector its scene carries', async () => {
const { publishFocusTargetFromCachedPosition, clearFocusTarget } =
await import('./focusDeemphasis.js');
const { registerViewerEngine } = await import(
'../globe/cesium/engineFromViewer.js'
);
const { createFakeEngine } = await import('../globe/testing/fakeEngine.js');
const engine = createFakeEngine();
const projected = [];
@@ -176,9 +173,11 @@ test('a focus target projects through the engine registered for its scene', asyn
projected.push(position);
return Object.assign(result, { x: 300, y: 200 });
};
// A scene with no Cesium behind it (the Navara renderer's adapter).
const scene = { frameState: { frameNumber: 7 } };
const unregister = registerViewerEngine(scene, engine);
// A scene with no Cesium behind it (a layer's engine view).
const scene = {
frameState: { frameNumber: 7 },
projector: engine.projector,
};
try {
const target = publishFocusTargetFromCachedPosition({
ownerLayer: 'flights',
@@ -201,7 +200,6 @@ test('a focus target projects through the engine registered for its scene', asyn
assert.equal(target.frameNumber, 7);
} finally {
clearFocusTarget('flights');
unregister();
engine.destroy();
}
});
+4 -6
View File
@@ -26,14 +26,12 @@ import {
horizonOccluder,
} from './render/cesiumProjection.js';
import * as geo from '../geo/index.js';
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
// A window position through the engine's projector when `scene` has a
// registered engine (engineFromViewer), else Cesium's SceneTransforms.
// A window position through the engine projector the scene carries (the
// layers' engine views), else Cesium's SceneTransforms (a Cesium scene).
function worldToWindow(scene, position, result) {
const projector = engineFromViewer(scene)?.projector;
return projector
? projector.worldToWindow(position, result)
return scene.projector
? scene.projector.worldToWindow(position, result)
: worldToWindowCoordinates(scene, position, result);
}
+7 -12
View File
@@ -746,13 +746,12 @@ test('the perspective helper is continuous through the sub-pixel band, not a 23
);
});
test('the exact projection asks the engine projector of a registered scene', async () => {
test('the exact projection asks the engine projector its scene carries', async () => {
const geo = await import('../geo/index.js');
const { registerViewerEngine } = await import('../globe/cesium/engineFromViewer.js');
const { perspectiveProjectedRotation: rotation } = await import('./iconOrientation.js');
const scene = { camera: { rightWC: { x: 0, y: 1, z: 0 }, upWC: { x: 0, y: 0, z: 1 } } };
const asked = [];
const unregister = registerViewerEngine({ scene }, {
const scene = {
camera: { rightWC: { x: 0, y: 1, z: 0 }, upWC: { x: 0, y: 0, z: 1 } },
projector: {
// Screen-right for every point further east (the probe), so 90° on screen.
worldToWindow(position, result = geo.cartesian2.create()) {
@@ -760,12 +759,8 @@ test('the exact projection asks the engine projector of a registered scene', asy
return Object.assign(result, { x: asked.length === 1 ? 100 : 120, y: 100 });
},
},
});
try {
const value = rotation(scene, geo.cartesian3.fromDegrees(0, 0, 0), 90, null);
assert.equal(asked.length, 2, 'the anchor and the probe');
assert.ok(Math.abs(value - -Math.PI / 2) < 1e-9, `rotation ${value}`);
} finally {
unregister();
}
};
const value = rotation(scene, geo.cartesian3.fromDegrees(0, 0, 0), 90, null);
assert.equal(asked.length, 2, 'the anchor and the probe');
assert.ok(Math.abs(value - -Math.PI / 2) < 1e-9, `rotation ${value}`);
});
+7 -19
View File
@@ -1,5 +1,3 @@
import { isGlobeEngine } from '../globe/contract.js';
/**
* Validation for positions that came back from a Cesium screen pick.
*
@@ -54,28 +52,18 @@ export function isPickedWorldPosition(position) {
* The world position under a screen point: the rendered surface where the
* depth buffer has it, else the ellipsoid; null over the sky.
*
* @param {object} target The globe engine (`engine.picker.pickPosition`, then
* `engine.camera.pickEllipsoid`), or a Cesium viewer from callers that
* still hold one (`scene.pickPosition`, then `camera.pickEllipsoid`).
* @param {object} engine The globe engine (`engine.picker.pickPosition`,
* then `engine.camera.pickEllipsoid`); without one, null.
* @param {{x: number, y: number}} screenPosition
* @returns {{x: number, y: number, z: number}|null} A Cartesian3.
*/
export function pickGroundPosition(target, screenPosition) {
if (isGlobeEngine(target)) {
const { picker, camera } = target;
return groundUnder(
screenPosition,
picker.pickPositionSupported ? picker : null,
camera,
);
}
const scene = target?.scene;
export function pickGroundPosition(engine, screenPosition) {
if (!engine) return null;
const { picker, camera } = engine;
return groundUnder(
screenPosition,
scene?.pickPositionSupported && typeof scene.pickPosition === 'function'
? scene
: null,
typeof target?.camera?.pickEllipsoid === 'function' ? target.camera : null,
picker.pickPositionSupported ? picker : null,
camera,
);
}
+3 -14
View File
@@ -162,20 +162,6 @@ test('the guard rejects each way Cesium mishandles a degenerate pick', () => {
assert.ok(Math.abs(Cesium.Math.toDegrees(carto.latitude) - 30.2672) < 1e-6);
});
test('the ground under a click: the rendered surface, else the ellipsoid, never the sky', async () => {
const { pickGroundPosition } = await import('./scenePick.js');
const ground = { x: 6378137, y: 0, z: 0 };
const sky = { x: 500, y: 0, z: 0 };
const viewer = (picked, ellipsoid) => ({
scene: { pickPositionSupported: true, pickPosition: () => picked },
camera: { pickEllipsoid: () => ellipsoid },
});
assert.equal(pickGroundPosition(viewer(ground, null), {}), ground);
assert.equal(pickGroundPosition(viewer(sky, ground), {}), ground);
assert.equal(pickGroundPosition(viewer(undefined, undefined), {}), null);
assert.equal(pickGroundPosition(null, {}), null);
});
test('a surface pick is nothing, or Google 3D tile content without an id', async () => {
const { isSurfacePick } = await import('./scenePick.js');
assert.equal(isSurfacePick(undefined), true);
@@ -210,6 +196,9 @@ test('on a globe engine the ground is the picked surface, else the ellipsoid, ne
unsupported.fake.script('pickEllipsoid', ground);
assert.equal(pickGroundPosition(unsupported, screen), ground);
assert.equal(unsupported.fake.callsOf('picker.pickPosition').length, 0);
unsupported.fake.script('pickEllipsoid', undefined);
assert.equal(pickGroundPosition(unsupported, screen), null);
assert.equal(pickGroundPosition(null, screen), null, 'no engine');
});
test('engine pick results classify like the Cesium picks they wrap', async () => {
+8 -2
View File
@@ -10,6 +10,7 @@ import { createDirectionsSource } from '../layers/directions/source.js';
import { createLifecycle as createCctvLifecycle } from '../layers/cctv/lifecycle.js';
import { createCctvDisplay } from '../layers/cctv/render/display.js';
import { createFakeEngine } from '../globe/testing/fakeEngine.js';
import { createCesiumCredits } from '../globe/cesium/credits.js';
import * as input from './inputOwnership.js';
import { createOverpassAlprSource } from '../layers/alpr/source.js';
@@ -34,6 +35,11 @@ function viewer(t) {
};
return v;
}
// The Cesium engine's credits over the viewer double's credit display.
const cesiumCredits = (v) => ({
credits: createCesiumCredits(v).credits,
render: { request: noop },
});
function assertCredit(v) {
assert.ok(v.credits.some((credit) => credit.showOnScreen && credit.html.includes('>© OpenStreetMap<')));
}
@@ -55,13 +61,13 @@ for (const index of [0, 1]) test(`${index ? 'dams' : 'datacenters'} introduce th
test('Nepal locator introduces the shared OSM credit', async (t) => {
const v = viewer(t);
const layer = createBhoteKoshiLocatorLayer({ boundaryResolver: async () => ({ name: 'Nepal', ring: [[80, 26], [88, 26], [88, 30], [80, 30]] }), overlayHost, requestRender: noop, scheduleFrame: () => 1, cancelFrame: noop });
await layer.init(v); await layer.enable(v, { origin: 'scene' });
await layer.init(v, { engine: cesiumCredits(v) }); await layer.enable(v, { origin: 'scene' });
assertCredit(v); await layer.destroy(v);
assert.equal(v.credits.filter(c => c.showOnScreen).length, 0);
});
test('voice route geometry introduces the shared OSM credit', (t) => {
const v = viewer(t), renderer = createWorldAnnotationRenderer(v);
const v = viewer(t), renderer = createWorldAnnotationRenderer(v, { engine: cesiumCredits(v) });
renderer.add({ id: 'route', type: 'route', color: 'primary', anchor: { lat: 0, lon: 0 }, path: [{ lat: 0, lon: 0 }, { lat: 0.01, lon: 0.01 }] });
assertCredit(v); renderer.destroy();
assert.equal(v.credits.filter(c => c.showOnScreen).length, 0);
+2 -2
View File
@@ -173,8 +173,8 @@ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undef
trackedEntity: undefined,
entities: { remove() {} },
};
// The ground snap samples through the viewer's engine (engineFromViewer):
// the engine surface over this stub's tileset and scene.sampleHeight.
// The ground snap samples through the viewer's engine (the test
// renderer's surfaceOwner, engineFromViewer): the engine surface over this stub's tileset and scene.sampleHeight.
registerViewerEngine(viewer, {
isDestroyed: () => false,
surface: {