feat(globe): follow camera on both engines

camera.follow({ position, viewFrom, minRange = 150, native? }) keeps a
moving target centred at an east-north-up offset the user may turn and
zoom; camera.following() and camera.followChanged report it; stop() frees
the camera and a camera command (setView, flyTo, flyToSphere, lookAt,
cancelFlight) ends it.

Probe ruling: Navara 0.2.1's cameraFollow holds the target but ignores the
user's drag and wheel, the aircraft sits ~13 px off centre with 7.6 px of
spread, and calling it without an offset each frame gives a NaN camera.
So Navara (and the fake engine) follow with src/globe/follow.js: each
frame, before Navara draws, the offset is re-read from where the user put
the camera relative to the previous target, kept outside the minimum
range and carried to the new target.

Cesium follows with viewer.trackedEntity: the layer's own Entity
(`native`) or a proxy Entity at position() with a 1 px transparent point,
since EntityView moves the camera only for an entity with a bounding
sphere. applyTrackedCameraFrame and the zoom limits moved to
src/globe/cesium/follow.js; src/data/trackedCamera.js keeps the pure parts
(the range clamp now lives in src/globe/follow.js). following() also
reports an entity the app tracked itself. Camera sensitivity claims made
on a viewer's Cesium camera now share the engine camera's ledger, and the
orientation controls and the world jump read the follow from the engine.

Contract (both engines): a target flying at 250 m/s stays within 3 px of
the centre for 2 s, zoomIn through it stops at 150 m, stop() and setView
end the follow. Cesium 71/71, Navara 77/77; shell 23/25/4.
This commit is contained in:
German Khokhlov committed 2026-10-16 20:26:43 +04:00
1 parent a89719aba9
commit f640890cf6
24 files changed
+1226 -218

No files matched your search

+10 -6
View File
@@ -24,6 +24,8 @@
* for, only that nobody's answer is taken away while they still need it.
*/
import { engineFromViewer } from '../globe/cesium/engineFromViewer.js';
/** @type {WeakMap<object, {base: number, claims: Map<string, number>}>} */
const _cameras = new WeakMap();
@@ -31,10 +33,13 @@ const _cameras = new WeakMap();
const DEFAULT_PERCENTAGE_CHANGED = 0.5;
/**
* A globe engine (or a viewer) claims through its camera; anything else is
* the camera itself (a camera has no `camera` of its own).
* One key per camera: the engine's camera. A globe engine claims through its
* camera; a Cesium viewer or its camera through the engine registered for
* that viewer (engineFromViewer); anything else is the camera itself (a
* camera has no `camera` of its own).
*/
const cameraOf = (target) => target?.camera ?? target;
const cameraOf = (target) =>
engineFromViewer(target)?.camera ?? target?.camera ?? target;
function ledgerFor(camera) {
let ledger = _cameras.get(camera);
@@ -60,9 +65,8 @@ function applyLedger(camera, ledger) {
/**
* Ask for a camera-change sensitivity at least as fine as `value`.
* @param {object|null|undefined} target A globe engine, its camera, or a
* Cesium camera (anything with `percentageChanged`). Layers still pass the
* viewer's Cesium camera until phase 1c; that is a separate claimant from
* the engine's camera, so one camera must not be claimed both ways.
* Cesium viewer or camera (anything with `percentageChanged`). A viewer
* with a registered engine, and its camera, claim on the engine camera.
* @param {string} owner Stable claim name, usually the layer id.
* @param {number} value Requested `percentageChanged`.
* @returns {number|null} The value now in force, or null when there is no camera.
+28
View File
@@ -25,3 +25,31 @@ test('claims on a globe engine set its camera sensitivity and share one ledger',
assert.equal(engine.camera.percentageChanged, 0.5);
assert.deepEqual(cameraSensitivityClaims(engine), []);
});
test("a Cesium viewer's camera claims on the same key as its engine's camera", async () => {
const { createFakeViewer } =
await import('../globe/cesium/testing/fakeViewer.mjs');
const { createCesiumEngine } =
await import('../globe/cesium/createCesiumEngine.js');
const { registerViewerEngine } =
await import('../globe/cesium/engineFromViewer.js');
const viewer = createFakeViewer();
const engine = createCesiumEngine(viewer, { requestRender: () => {} });
const unregister = registerViewerEngine(viewer, engine);
try {
claimCameraSensitivity(viewer.camera, 'traffic', 0.05);
claimCameraSensitivity(engine, 'transit', 0.05);
// One ledger: both claims are on it, and releasing one keeps the other.
assert.deepEqual(cameraSensitivityClaims(viewer).sort(), [
'traffic',
'transit',
]);
releaseCameraSensitivity(engine, 'transit');
assert.equal(viewer.camera.percentageChanged, 0.05);
releaseCameraSensitivity(viewer.camera, 'traffic');
assert.equal(viewer.camera.percentageChanged, 0.5);
} finally {
unregister();
engine.destroy();
}
});
+5 -175
View File
@@ -1,8 +1,10 @@
// The pure parts of the tracked aircraft camera. The Cesium follow itself
// (the one-off tracked frame, the zoom limits) is the engine's:
// src/globe/cesium/follow.js; the range clamp is src/globe/follow.js.
import * as geo from '../geo/index.js';
const MAX_FRAME_ATTEMPTS = 120;
const MIN_TRACKED_RANGE_M = 150;
const ZOOM_INERTIA_STATES = new WeakMap();
export { clampTrackedCameraPosition } from '../globe/follow.js';
/**
* Preserve real-world model scale except when a very close tracked camera
@@ -62,175 +64,3 @@ export function trackedDisplayPositionForCamera(entity, time, result) {
? geo.cartesian3.clone(displayedPosition, result)
: entity?.position?.getValue(time, result);
}
function acquireStableTrackedZoom(controller, entity) {
if (!controller) return () => {};
let state = ZOOM_INERTIA_STATES.get(controller);
if (!state) {
state = {
originalInertiaZoom: controller.inertiaZoom,
originalMinimumZoomDistance: controller.minimumZoomDistance,
owners: new Set(),
};
ZOOM_INERTIA_STATES.set(controller, state);
}
state.owners.add(entity);
controller.inertiaZoom = 0;
controller.minimumZoomDistance = Math.max(
state.originalMinimumZoomDistance,
MIN_TRACKED_RANGE_M,
);
return () => {
const current = ZOOM_INERTIA_STATES.get(controller);
if (!current) return;
current.owners.delete(entity);
if (current.owners.size > 0) return;
controller.inertiaZoom = current.originalInertiaZoom;
controller.minimumZoomDistance = current.originalMinimumZoomDistance;
ZOOM_INERTIA_STATES.delete(controller);
};
}
/**
* Keep a tracked-frame camera on the same side of its target and outside the
* minimum readable range.
*
* @param {{position: Cesium.Cartesian3, direction: Cesium.Cartesian3}} camera Camera-like object.
* @param {Cesium.Cartesian3} previousPosition Previous tracked-frame camera position.
* @param {number} [minimumRangeM=MIN_TRACKED_RANGE_M] Minimum target range.
* @returns {boolean} Whether the camera position was corrected.
*/
export function clampTrackedCameraPosition(
camera,
previousPosition,
minimumRangeM = MIN_TRACKED_RANGE_M,
) {
const crossedOrigin =
geo.cartesian3.dot(camera.position, previousPosition) <= 0;
const forwardDistance = -geo.cartesian3.dot(
camera.position,
camera.direction,
);
const rangeSquared = geo.cartesian3.magnitudeSquared(camera.position);
if (crossedOrigin) {
geo.cartesian3.normalize(previousPosition, camera.position);
geo.cartesian3.multiplyByScalar(
camera.position,
minimumRangeM,
camera.position,
);
return true;
}
if (
forwardDistance < minimumRangeM ||
rangeSquared < minimumRangeM * minimumRangeM
) {
geo.cartesian3.multiplyByScalar(
camera.direction,
-minimumRangeM,
camera.position,
);
return true;
}
return false;
}
/**
* Apply an entity's requested follow offset once, then let Cesium's ENU
* EntityView exclusively own continuous following.
*
* Cesium can retain the previous world-space camera position when tracking
* switches across a large distance. The view then only rotates toward the new
* aircraft, and the next zoom can drive the camera through the ellipsoid.
* Applying the exact frame for the handoff makes selection deterministic. We
* deliberately do not rebuild it every frame: Cesium's EntityView already
* follows the same ENU entity, and two writers create sub-pixel camera jitter
* that becomes visible at minimum range.
*
* @param {Cesium.Viewer} viewer Active viewer.
* @param {Cesium.Entity} entity Newly tracked entity.
* @param {Cesium.Cartesian3} viewFrom Desired camera offset in the tracked frame.
* @returns {(() => void)|undefined} Disposer for this one tracked-frame owner.
*/
export function applyTrackedCameraFrame(viewer, entity, viewFrom) {
if (!viewer || !entity || !viewFrom) return;
let attempts = 0;
const trackedTransform = geo.matrix4.create();
const trackedPosition = geo.cartesian3.create();
const resolvedViewFrom = geo.cartesian3.create();
const cameraOffset = geo.cartesian3.create();
const previousCameraPosition = geo.cartesian3.create();
let framed = false;
const restoreZoomInertia = acquireStableTrackedZoom(
viewer.scene.screenSpaceCameraController,
entity,
);
let stopped = false;
let remove = null;
const stop = () => {
if (stopped) return;
stopped = true;
remove?.();
restoreZoomInertia();
};
// preUpdate is deliberate. preRender fires after Cesium has prepared
// billboard/model draw state, so changing the tracked transform there makes
// the camera and target visual disagree for one frame (visible as a
// front/back oscillation). The controller then enforces the minimum range
// during the same update pass.
remove = viewer.scene.preUpdate.addEventListener(() => {
if (viewer.isDestroyed() || viewer.trackedEntity !== entity) {
stop();
return;
}
attempts += framed ? 0 : 1;
// Prefer the display cache exposed by the flight layer. Calling the
// CallbackProperty from preUpdate can advance dead reckoning again while
// Cesium's billboard/label still holds the prior visualizer sample. At a
// 150 m follow range that sub-frame difference becomes visible as the
// label swinging around the icon during an orbit, especially immediately
// after a 2D→3D→2D handoff.
if (!framed) {
const position = trackedDisplayPositionForCamera(
entity,
viewer.clock.currentTime,
trackedPosition,
);
if (!position) {
if (attempts >= MAX_FRAME_ATTEMPTS) stop();
return;
}
const transform = geo.transforms.eastNorthUpToFixedFrame(
position,
geo.ellipsoid.WGS84,
trackedTransform,
);
const offset =
typeof viewFrom.getValue === 'function'
? viewFrom.getValue(viewer.clock.currentTime, resolvedViewFrom)
: geo.cartesian3.clone(viewFrom, resolvedViewFrom);
if (
!offset ||
geo.cartesian3.magnitudeSquared(offset) < geo.math.EPSILON12
) {
stop();
return;
}
viewer.camera.lookAtTransform(transform, offset);
geo.cartesian3.clone(viewer.camera.position, previousCameraPosition);
framed = true;
return;
}
// Normal frames are intentionally read-only: EntityView is the sole
// continuous camera writer. Only a programmatic zoom that bypasses the
// controller's minimumZoomDistance needs correction.
if (clampTrackedCameraPosition(viewer.camera, previousCameraPosition)) {
geo.cartesian3.clone(viewer.camera.position, cameraOffset);
viewer.camera.lookAtTransform(viewer.camera.transform, cameraOffset);
}
geo.cartesian3.clone(viewer.camera.position, previousCameraPosition);
});
return stop;
}