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

+131 -207
View File
@@ -1,11 +1,16 @@
/**
* Box selection for the Recent Imagery layer: press on the world, drag, and
* release to hand the layer a degrees box. Follows the draw tool's ownership
* rules — the pointer is claimed for the session, the viewer's own click
* actions are borrowed and given back, and `destroy()` returns everything —
* and freezes the camera only while a drag is in progress.
* rules — the pointer is claimed for the session and `destroy()` returns
* everything — and freezes the camera only while a drag is in progress.
*
* The same on every engine: the tool takes the pointer events of the
* engine's canvas in the capture phase, ahead of the engine's own handlers,
* so a press that starts a box and the drag it makes reach neither the
* camera nor any click (a layer's, or Cesium's stock select and track).
* Moves outside a drag pass through. The layer draws the preview
* (`onPreview`, a ground cell on engine.ground).
*/
import * as Cesium from 'cesium';
import { pickWorldFromScreen } from '../annotations/annotationResolver.js';
import {
claimPointer,
@@ -18,35 +23,51 @@ import { msg } from '../i18n/index.js';
/** The id this tool claims the pointer under. */
export const IMAGERY_BOX_POINTER_OWNER = 'recent-imagery-box';
/**
* The camera held still until the returned release: the engine's counted
* suspension where it has one (Navara keeps the app's own setCameraInputs
* choice under it), else camera inputs off and on again.
*/
function freezeCamera(input) {
if (typeof input.suspendCameraInputs === 'function')
return input.suspendCameraInputs();
input.setCameraInputs(false);
return () => input.setCameraInputs(true);
}
/**
* Wire the box tool.
* @param {{ viewer: object, onBox: (box: object) => void, onCancel?: (reason: string, message?: string, box?: object) => void, onActive?: (active: boolean) => void, onEscape?: () => boolean, cesium?: object, pickWorld?: Function, documentRef?: object }} deps
* `onEscape` runs before the tool cancels on Escape; returning `true` claims
* the key (it is still consumed) and leaves the tool armed.
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => Promise<void> } | null}
* @param {{ engine: import('../globe/contract.js').GlobeEngine,
* onBox: (box: object) => void, onPreview?: (box: object | null) => void,
* onCancel?: (reason: string, message?: string, box?: object) => void,
* onActive?: (active: boolean) => void, onEscape?: () => boolean,
* pickWorld?: Function, documentRef?: object }} deps
* `onPreview` gets the box being dragged, and null once the drag ends.
* `onEscape` runs before the tool cancels on Escape; returning `true`
* claims the key (it is still consumed) and leaves the tool armed.
* @returns {{ start: () => boolean, cancel: (reason?: string) => void, isActive: () => boolean, destroy: () => void } | null}
*/
export function initImageryBoxTool({
viewer,
engine,
onBox,
onPreview = () => {},
onCancel,
onActive,
onEscape,
cesium = Cesium,
pickWorld = pickWorldFromScreen,
documentRef = globalThis.document,
} = {}) {
if (!viewer?.scene || typeof onBox !== 'function') return null;
const canvas = engine?.host?.canvas;
if (!canvas || typeof onBox !== 'function') return null;
let active = false;
let destroyed = false;
/** Drag corners in degrees; `anchor` is null while no drag is live. */
let anchor = null;
let corner = null;
let handler = null;
let lease = null;
let savedSingleClick = null;
let savedDoubleClick = null;
let savedCameraInputs = null;
let thaw = null;
let pointerId = null;
const dragBox = () =>
anchor && {
@@ -55,241 +76,144 @@ export function initImageryBoxTool({
east: Math.max(anchor.lon, corner.lon),
north: Math.max(anchor.lat, corner.lat),
};
const dataSource = new cesium.CustomDataSource(
'gev-recent-imagery-box-preview',
);
let attaching = Promise.resolve(viewer.dataSources.add(dataSource)).catch(
() => null,
);
const stroke = cesium.Color.fromCssColorString('#8be9ff');
const previewRectangle = () => {
const box = dragBox();
return box
? cesium.Rectangle.fromDegrees(box.west, box.south, box.east, box.north)
: undefined;
};
const previewOutline = () => {
const box = dragBox();
if (!box) return [];
return cesium.Cartesian3.fromDegreesArray([
box.west,
box.south,
box.east,
box.south,
box.east,
box.north,
box.west,
box.north,
box.west,
box.south,
]);
};
const fill = dataSource.entities.add({
show: false,
rectangle: {
coordinates: new cesium.CallbackProperty(previewRectangle, false),
material: stroke.withAlpha(0.12),
classificationType: cesium.ClassificationType.BOTH,
},
});
// A rectangle graphic cannot draw a dashed edge on the ground, so the
// outline is its own draped polyline traced round the same corners.
const outline = dataSource.entities.add({
show: false,
polyline: {
positions: new cesium.CallbackProperty(previewOutline, false),
width: 2,
clampToGround: true,
classificationType: cesium.ClassificationType.BOTH,
material: new cesium.PolylineDashMaterialProperty({
color: stroke.withAlpha(0.95),
dashLength: 12,
}),
},
});
const requestRender = () => viewer.scene.requestRender?.();
const setPreview = (visible) => {
fill.show = visible;
outline.show = visible;
requestRender();
};
const worldAt = (position) => {
if (!position) return null;
const canvas = viewer.scene.canvas;
const w = canvas?.clientWidth || canvas?.width || 1;
const h = canvas?.clientHeight || canvas?.height || 1;
const point = pickWorld(viewer, position.x / w, position.y / h);
const worldAt = (event) => {
const rect = canvas.getBoundingClientRect();
const { width, height } = engine.host.size();
const point = pickWorld(
engine,
(event.clientX - rect.left) / (width || 1),
(event.clientY - rect.top) / (height || 1),
);
const lon = Number(point?.lon);
const lat = Number(point?.lat);
return Number.isFinite(lon) && Number.isFinite(lat) ? { lon, lat } : null;
};
const cameraController = () => viewer.scene.screenSpaceCameraController;
function freezeCamera() {
const controller = cameraController();
if (!controller || savedCameraInputs !== null) return;
savedCameraInputs = controller.enableInputs;
controller.enableInputs = false;
}
function thawCamera() {
const controller = cameraController();
if (controller && savedCameraInputs !== null)
controller.enableInputs = savedCameraInputs;
savedCameraInputs = null;
}
const consume = (event) => {
event.preventDefault?.();
event.stopImmediatePropagation?.();
};
function endDrag() {
anchor = null;
corner = null;
thawCamera();
setPreview(false);
if (pointerId !== null && canvas.hasPointerCapture?.(pointerId))
canvas.releasePointerCapture(pointerId);
pointerId = null;
thaw?.();
thaw = null;
onPreview(null);
}
const onDown = (event) => {
if (!active || destroyed || anchor) return;
const point = worldAt(event.position);
function down(event) {
if (
!active ||
anchor ||
event.button !== 0 ||
event.shiftKey ||
event.ctrlKey ||
event.altKey
)
return;
consume(event);
const point = worldAt(event);
if (!point) {
onCancel?.('sky', msg('Press on the ground, not the sky'));
return;
}
anchor = point;
corner = point;
freezeCamera();
setPreview(true);
};
const onMove = (event) => {
const point = anchor && !destroyed && worldAt(event.endPosition);
if (!point) return;
corner = point;
requestRender();
};
const onUp = (event) => {
if (!anchor || destroyed) return;
corner = worldAt(event.position) || corner;
pointerId = event.pointerId;
thaw = freezeCamera(engine.input);
canvas.setPointerCapture?.(pointerId);
onPreview(dragBox());
}
function move(event) {
if (!anchor || event.pointerId !== pointerId) return;
consume(event);
corner = worldAt(event) || corner;
onPreview(dragBox());
}
function up(event) {
if (!anchor || event.pointerId !== pointerId) return;
consume(event);
corner = worldAt(event) || corner;
const box = dragBox();
const result = validateBox(box);
if (result.reason === 'degenerate')
result.message = msg('Drag to size the box');
endDrag();
setActive(false);
stop();
if (result.ok) onBox(result.box);
else onCancel?.(result.reason, result.message, box);
};
}
// Escape is taken from a document capture listener, ahead of every other
// handler, so the interceptor runs first: when it claims the key (the
// panel exits a live comparison), the tool stays armed and the key still
// goes no further; otherwise Escape cancels the session.
const onKey = (event) => {
if (!active || destroyed || event.key !== 'Escape') return;
event.preventDefault?.();
event.stopImmediatePropagation?.();
if (onEscape?.() === true) return;
cancel('escape');
};
function bindScene() {
if (handler) return;
handler = new cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
handler.setInputAction(onDown, cesium.ScreenSpaceEventType.LEFT_DOWN);
handler.setInputAction(onMove, cesium.ScreenSpaceEventType.MOUSE_MOVE);
handler.setInputAction(onUp, cesium.ScreenSpaceEventType.LEFT_UP);
const stock = viewer.screenSpaceEventHandler;
if (stock) {
savedSingleClick =
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK) || null;
savedDoubleClick =
stock.getInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK) ||
null;
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_CLICK);
stock.removeInputAction(cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK);
}
documentRef?.addEventListener?.('keydown', onKey, true);
documentRef?.body?.classList?.add?.('gev-imagery-box');
function key(event) {
if (!active || event.key !== 'Escape') return;
consume(event);
if (onEscape?.() !== true) cancel('escape');
}
// A drag the browser takes away (a touch turned into a scroll, the window
// losing focus) ends the session and gives the camera back.
function pointerCancel(event) {
if (anchor && event.pointerId === pointerId) cancel('pointer-cancel');
}
const bindings = [
[canvas, 'pointerdown', down],
[documentRef, 'pointermove', move],
[documentRef, 'pointerup', up],
[documentRef, 'pointercancel', pointerCancel],
[documentRef, 'keydown', key],
];
if (documentRef?.defaultView)
bindings.push([documentRef.defaultView, 'blur', () => cancel('blur')]);
function releaseScene() {
if (handler) {
handler.destroy();
handler = null;
}
const stock = viewer.screenSpaceEventHandler;
if (stock && savedSingleClick) {
stock.setInputAction(
savedSingleClick,
cesium.ScreenSpaceEventType.LEFT_CLICK,
);
}
if (stock && savedDoubleClick) {
stock.setInputAction(
savedDoubleClick,
cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK,
);
}
savedSingleClick = null;
savedDoubleClick = null;
documentRef?.removeEventListener?.('keydown', onKey, true);
function stop() {
if (!active) return;
for (const [target, type, listener] of bindings)
target?.removeEventListener?.(type, listener, true);
endDrag();
releasePointer(lease);
lease = null;
active = false;
documentRef?.body?.classList?.remove?.('gev-imagery-box');
}
function setActive(next) {
if (next === active) return active;
if (next) {
lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);
if (!lease) {
onCancel?.(
'pointer-busy',
`${pointerOwner()} is using the pointer — close it first`,
);
return active;
}
active = true;
bindScene();
} else {
if (anchor) endDrag();
releaseScene();
releasePointer(lease);
lease = null;
active = false;
}
onActive?.(active);
return active;
onActive?.(false);
}
function cancel(reason = 'cancel') {
if (!active || destroyed) return;
setActive(false);
stop();
onCancel?.(reason);
}
return {
/** Begin a box session. False when the pointer is held elsewhere. */
start() {
return !destroyed && setActive(true);
if (destroyed) return false;
if (active) return true;
lease = claimPointer(IMAGERY_BOX_POINTER_OWNER);
if (!lease) {
onCancel?.(
'pointer-busy',
`${pointerOwner()} is using the pointer — close it first`,
);
return false;
}
active = true;
for (const [target, type, listener] of bindings)
target?.addEventListener?.(type, listener, true);
documentRef?.body?.classList?.add?.('gev-imagery-box');
onActive?.(true);
return true;
},
cancel,
isActive() {
return active;
},
/** Returns everything; resolves once the preview is detached. */
isActive: () => active,
/** Returns the pointer, the camera and every listener. */
destroy() {
if (destroyed) return attaching;
if (active) setActive(false);
if (destroyed) return;
stop();
destroyed = true;
releaseScene();
releasePointer(lease);
lease = null;
thawCamera();
dataSource.entities.removeAll();
attaching = attaching.then(() => {
try {
viewer.dataSources.remove(dataSource, true);
} catch {
/* viewer already disposed */
}
});
return attaching;
},
};
}