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

+7
View File
@@ -6,6 +6,7 @@ import * as geo from '../../geo/index.js';
import { createEngineEvent } from '../contract.js';
import { bridgeEvent } from './events.js';
import { toCesium2, toCesium3, toGeo3 } from './convert.js';
import { createCesiumFollow } from './follow.js';
const { math } = geo;
const EASINGS = {
@@ -143,6 +144,10 @@ export function createCesiumCamera(viewer) {
moveEnd: bridgeEvent(cesium.moveEnd),
commanded: commandedEvent(viewer, cesium),
};
// camera.follow: the viewer's trackedEntity (follow.js).
const follow = createCesiumFollow(viewer, {
commanded: bridges.commanded.event,
});
// The engine's own flight, so flightActive is exact even for flights that
// completed synchronously (Cesium keeps no current flight for those).
@@ -287,6 +292,7 @@ export function createCesiumCamera(viewer) {
moveStart: bridges.moveStart.event,
moveEnd: bridges.moveEnd.event,
commanded: bridges.commanded.event,
...follow.camera,
get percentageChanged() {
return cesium.percentageChanged;
},
@@ -298,6 +304,7 @@ export function createCesiumCamera(viewer) {
return {
camera,
destroy() {
follow.destroy();
if (flight) camera.cancelFlight();
for (const bridge of Object.values(bridges)) bridge.detach();
},
+2 -1
View File
@@ -112,6 +112,7 @@ test('the viewer clock itself is left alone', () => {
const viewer = createFakeViewer();
viewer.clock.shouldAnimate = false;
viewer.clock.multiplier = 1;
const currentTime = viewer.clock.currentTime.clone();
const { clock } = createCesiumClock(viewer, {
appClock: manualAppClock().appClock,
});
@@ -119,5 +120,5 @@ test('the viewer clock itself is left alone', () => {
cesiumFrame(viewer);
assert.equal(viewer.clock.shouldAnimate, false);
assert.equal(viewer.clock.multiplier, 1);
assert.equal(viewer.clock.currentTime, undefined);
assert.ok(viewer.clock.currentTime.equals(currentTime));
});
+10 -4
View File
@@ -13,15 +13,21 @@ const engines = new WeakMap();
* @returns {() => void} Unregister (only while it is still the registered one).
*/
export function registerViewerEngine(viewer, engine) {
engines.set(viewer, engine);
// The viewer's Cesium camera names the same engine, so callers that hold
// only viewer.camera (camera sensitivity claims) reach the engine camera.
const keys = [viewer, viewer?.camera, viewer?.scene?.camera].filter(
(key, index, all) => key != null && all.indexOf(key) === index,
);
for (const key of keys) engines.set(key, engine);
return () => {
if (engines.get(viewer) === engine) engines.delete(viewer);
for (const key of keys)
if (engines.get(key) === engine) engines.delete(key);
};
}
/**
* @param {object | null | undefined} viewer A Cesium viewer, or an engine
* (returned as is).
* @param {object | null | undefined} viewer A Cesium viewer or its camera,
* or an engine (returned as is).
* @returns {import('../contract.js').GlobeEngine | null} The registered
* engine, or null.
*/
+344
View File
@@ -0,0 +1,344 @@
// camera.follow on Cesium: the viewer's trackedEntity (Cesium's EntityView
// owns the continuous follow, the user turns and zooms around the target).
// With `native` the layer's own Entity is tracked; without it an internal
// proxy Entity whose position is the caller's `position()`. Each follow gets
// one exact tracked frame on preUpdate (applyTrackedCameraFrame) and the
// zoom limits that keep the camera outside the minimum range.
// following() also reports a trackedEntity the app set itself, and
// followChanged is viewer.trackedEntityChanged.
import * as Cesium from 'cesium';
import * as geo from '../../geo/index.js';
import { createEngineEvent } from '../contract.js';
import {
MIN_FOLLOW_RANGE_M,
clampTrackedCameraPosition,
normalizeFollowOptions,
} from '../follow.js';
import { toCesium3 } from './convert.js';
const MAX_FRAME_ATTEMPTS = 120;
const ZOOM_INERTIA_STATES = new WeakMap();
function acquireStableTrackedZoom(controller, owner, minRange) {
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(owner);
controller.inertiaZoom = 0;
controller.minimumZoomDistance = Math.max(
state.originalMinimumZoomDistance ?? 0,
minRange,
);
return () => {
const current = ZOOM_INERTIA_STATES.get(controller);
if (!current) return;
current.owners.delete(owner);
if (current.owners.size > 0) return;
controller.inertiaZoom = current.originalInertiaZoom;
controller.minimumZoomDistance = current.originalMinimumZoomDistance;
ZOOM_INERTIA_STATES.delete(controller);
};
}
// The position the tracked visual already drew (the flight layers' display
// cache), without advancing its CallbackProperty again.
function displayPosition(entity, time, result) {
const displayed = entity?.gevDisplayPosition?.();
return displayed
? geo.cartesian3.clone(displayed, result)
: entity?.position?.getValue(time, result);
}
/**
* 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 | Cesium.Property} viewFrom Desired camera offset
* in the tracked frame.
* @param {{ minRange?: number }} [options]
* @returns {(() => void)|undefined} Disposer for this one tracked-frame owner.
*/
export function applyTrackedCameraFrame(
viewer,
entity,
viewFrom,
{ minRange = MIN_FOLLOW_RANGE_M } = {},
) {
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,
minRange,
);
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 = displayPosition(
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,
minRange,
)
) {
geo.cartesian3.clone(viewer.camera.position, cameraOffset);
viewer.camera.lookAtTransform(viewer.camera.transform, cameraOffset);
}
geo.cartesian3.clone(viewer.camera.position, previousCameraPosition);
});
return stop;
}
/**
* @param {Cesium.Viewer} viewer
* @param {{ commanded: object }} ports The engine camera's commanded event.
*/
export function createCesiumFollow(viewer, { commanded }) {
const followChanged = createEngineEvent();
// The follow this engine started.
let own = null;
// Handles for entities the app tracked itself, one per entity.
const wrapped = new WeakMap();
let switching = false;
const wrap = (entity) => {
let handle = wrapped.get(entity);
if (!handle) {
handle = {
native: entity,
stop() {
if (viewer.trackedEntity === entity) viewer.trackedEntity = undefined;
},
retarget: (next) =>
follow({
native: entity,
position: () =>
displayPosition(entity, viewer.clock.currentTime, undefined),
viewFrom: () =>
entity.viewFrom?.getValue?.(viewer.clock.currentTime) ??
entity.viewFrom,
...next,
}),
};
wrapped.set(entity, handle);
}
return handle;
};
const following = () => {
const entity = viewer.trackedEntity;
if (!entity) return null;
if (own && own.entity === entity) return own.handle;
return wrap(entity);
};
// followChanged rides on trackedEntityChanged, subscribed once something
// listens or follows (creating the engine subscribes nothing).
let removeTracked = null;
const onTracked = () => {
if (switching) return;
if (own && viewer.trackedEntity !== own.entity) release(own);
followChanged.raiseEvent(following());
};
const watchTracking = () => {
if (removeTracked || !viewer.trackedEntityChanged) return;
removeTracked = viewer.trackedEntityChanged.addEventListener(onTracked);
};
const addListener = followChanged.addEventListener;
followChanged.addEventListener = (listener) => {
watchTracking();
return addListener(listener);
};
// Undo what one follow put on the viewer (not trackedEntity itself).
function teardown(state) {
state.stopFrame?.();
state.stopFrame = null;
state.removeCommanded?.();
state.removeCommanded = null;
if (state.proxy) viewer.entities.remove(state.proxy);
state.proxy = null;
}
function release(state) {
if (own !== state) return;
own = null;
teardown(state);
}
function start(state, options) {
state.options = options;
let entity = options.native;
if (!entity) {
const scratch = new Cesium.Cartesian3();
entity = state.proxy = viewer.entities.add({
position: new Cesium.CallbackProperty(() => {
let position;
try {
position = state.options.position();
} catch {
return undefined;
}
return position
? Cesium.Cartesian3.clone(toCesium3(position), scratch)
: undefined;
}, false),
viewFrom: toCesium3(state.options.viewFrom()),
// Cesium's EntityView moves the camera only once the tracked
// entity has a bounding sphere: a 1 px transparent point gives it
// one (an entity without graphics is framed once, then left).
point: { pixelSize: 1, color: Cesium.Color.TRANSPARENT },
});
}
state.entity = entity;
state.handle.native = options.native;
viewer.camera.cancelFlight();
viewer.trackedEntity = entity;
const viewFrom =
options.native?.viewFrom ?? toCesium3(state.options.viewFrom());
state.stopFrame =
applyTrackedCameraFrame(viewer, entity, viewFrom, {
minRange: options.minRange,
}) ?? null;
// A command that takes the camera ends the follow; so does another
// tracked entity (Cesium raises commanded for that too).
state.removeCommanded = commanded.addEventListener(() => {
if (switching || own !== state) return;
if (viewer.trackedEntity === state.entity)
viewer.trackedEntity = undefined;
release(state);
});
viewer.scene.requestRender?.();
}
function follow(input) {
const options = normalizeFollowOptions(input);
watchTracking();
if (own) {
const previous = own;
own = null;
teardown(previous);
}
const state = { entity: null, proxy: null, options, handle: null };
state.handle = {
native: options.native,
stop() {
if (own !== state) return;
if (viewer.trackedEntity === state.entity)
viewer.trackedEntity = undefined;
release(state);
},
retarget(next) {
if (own !== state) return;
const updated = normalizeFollowOptions({ ...state.options, ...next });
switching = true;
try {
teardown(state);
start(state, updated);
} finally {
switching = false;
}
followChanged.raiseEvent(state.handle);
},
};
own = state;
// Assigning trackedEntity raises followChanged with this handle.
start(state, options);
return state.handle;
}
return {
camera: { follow, following, followChanged },
destroy() {
if (own) {
const state = own;
if (viewer.trackedEntity === state.entity)
viewer.trackedEntity = undefined;
release(state);
}
removeTracked?.();
removeTracked = null;
},
};
}
+144
View File
@@ -0,0 +1,144 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import * as geo from '../../geo/index.js';
import { createCesiumCamera } from './camera.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
const TARGET = geo.cartesian3.fromDegrees(-73.78, 40.64, 3000);
function setup() {
const viewer = createFakeViewer();
const { camera, destroy } = createCesiumCamera(viewer);
const changes = [];
camera.followChanged.addEventListener((handle) => changes.push(handle));
const frame = () => viewer.scene.preUpdate.raiseEvent();
return { viewer, camera, destroy, changes, frame };
}
test('follow tracks a native entity: one exact frame, zoom limits, stop restores', () => {
const { viewer, camera, changes, frame } = setup();
const controller = viewer.scene.screenSpaceCameraController;
controller.inertiaZoom = 0.8;
controller.minimumZoomDistance = 1;
const native = new Cesium.Entity({
position: Cesium.Cartesian3.clone(TARGET),
viewFrom: new Cesium.Cartesian3(0, -900, 400),
});
const handle = camera.follow({
native,
position: () => TARGET,
viewFrom: { x: 0, y: -900, z: 400 },
});
assert.equal(viewer.trackedEntity, native);
assert.equal(camera.following(), handle);
assert.equal(handle.native, native);
assert.deepEqual(changes, [handle]);
assert.equal(controller.inertiaZoom, 0);
assert.equal(controller.minimumZoomDistance, 150);
frame();
frame();
const frames = viewer.callsOf('camera.lookAtTransform');
assert.equal(frames.length, 1, 'the tracked frame is applied once');
const [transform, offset] = frames[0].args;
assert.deepEqual([offset.x, offset.y, offset.z], [0, -900, 400]);
const enu = geo.transforms.eastNorthUpToFixedFrame(
TARGET,
geo.ellipsoid.WGS84,
);
for (let i = 0; i < 16; i++)
assert.ok(Math.abs(transform[i] - enu[i]) < 1e-6);
handle.stop();
assert.equal(viewer.trackedEntity, undefined);
assert.equal(camera.following(), null);
assert.deepEqual(changes, [handle, null]);
assert.equal(controller.inertiaZoom, 0.8);
assert.equal(controller.minimumZoomDistance, 1);
});
test('without native the follow tracks a proxy entity at position()', () => {
const { viewer, camera, frame } = setup();
let target = TARGET;
const handle = camera.follow({
position: () => target,
viewFrom: { x: 0, y: -500, z: 200 },
});
const proxy = viewer.trackedEntity;
assert.ok(viewer.entities.contains(proxy));
assert.equal(handle.native, undefined);
const time = viewer.clock.currentTime;
assert.ok(Cesium.Cartesian3.equals(proxy.position.getValue(time), TARGET));
target = geo.cartesian3.fromDegrees(-73.7, 40.6, 3000);
assert.ok(Cesium.Cartesian3.equals(proxy.position.getValue(time), target));
frame();
assert.equal(viewer.callsOf('camera.lookAtTransform').length, 1);
handle.stop();
assert.equal(viewer.entities.contains(proxy), false);
assert.equal(viewer.trackedEntity, undefined);
});
test('a camera command or another tracked entity ends the follow', () => {
const { viewer, camera, changes } = setup();
const options = { position: () => TARGET, viewFrom: { x: 0, y: -500, z: 0 } };
const first = camera.follow(options);
camera.setView({ destination: TARGET });
assert.equal(viewer.trackedEntity, undefined);
assert.equal(camera.following(), null);
assert.equal(viewer.entities.values.length, 0);
camera.follow(options);
const appEntity = new Cesium.Entity({ position: TARGET });
viewer.trackedEntity = appEntity;
assert.equal(viewer.entities.values.length, 0, 'the proxy is gone');
const wrapped = camera.following();
assert.equal(wrapped.native, appEntity);
assert.equal(camera.following(), wrapped, 'one handle per entity');
assert.equal(changes.at(-1), wrapped);
wrapped.stop();
assert.equal(viewer.trackedEntity, undefined);
assert.equal(changes.at(-1), null);
assert.ok(changes.includes(first));
});
test('a programmatic zoom inside the minimum range is pushed back to it', () => {
const { viewer, camera, frame } = setup();
camera.follow({ position: () => TARGET, viewFrom: { x: 0, y: -500, z: 0 } });
frame();
// zoomIn bypasses the controller's minimumZoomDistance.
Cesium.Cartesian3.fromElements(0, -20, 0, viewer.camera.position);
frame();
const range = Cesium.Cartesian3.magnitude(viewer.camera.position);
assert.ok(Math.abs(range - 150) < 1e-6, `range ${range}`);
});
test('retarget switches the tracked entity without ending the follow', () => {
const { viewer, camera, changes } = setup();
const handle = camera.follow({
position: () => TARGET,
viewFrom: { x: 0, y: -500, z: 0 },
});
const proxy = viewer.trackedEntity;
const native = new Cesium.Entity({ position: TARGET });
handle.retarget({ native });
assert.equal(viewer.trackedEntity, native);
assert.equal(viewer.entities.contains(proxy), false);
assert.equal(camera.following(), handle);
assert.deepEqual(changes, [handle, handle]);
});
test('destroy ends an engine follow and leaves an app-tracked entity alone', () => {
const first = setup();
first.camera.follow({
position: () => TARGET,
viewFrom: { x: 0, y: -500, z: 0 },
});
first.destroy();
assert.equal(first.viewer.trackedEntity, undefined);
assert.equal(first.viewer.entities.values.length, 0);
const second = setup();
const appEntity = new Cesium.Entity({ position: TARGET });
second.viewer.trackedEntity = appEntity;
second.destroy();
assert.equal(second.viewer.trackedEntity, appEntity);
});
+48 -6
View File
@@ -14,6 +14,8 @@ export function createFakeViewer({ width = 1024, height = 768 } = {}) {
return typeof value === 'function' ? value(...args) : value;
};
const primitiveList = [];
const entityList = [];
let trackedEntity;
const imageryList = [];
const staticCredits = [];
const creditDisplay = {
@@ -28,6 +30,9 @@ export function createFakeViewer({ width = 1024, height = 768 } = {}) {
const fovy = 2 * Math.atan(Math.tan(Math.PI / 6) * (height / width));
const camera = {
positionWC: new Cesium.Cartesian3(7e6, 1e5, 2e5),
// Position and direction in the camera's transform (identity: world).
position: new Cesium.Cartesian3(7e6, 1e5, 2e5),
direction: new Cesium.Cartesian3(-1, 0, 0),
directionWC: new Cesium.Cartesian3(-1, 0, 0),
upWC: new Cesium.Cartesian3(0, 0, 1),
rightWC: new Cesium.Cartesian3(0, 1, 0),
@@ -81,9 +86,18 @@ export function createFakeViewer({ width = 1024, height = 768 } = {}) {
flight.options.cancel?.();
}),
lookAt: record('camera.lookAt'),
lookAtTransform: record('camera.lookAtTransform', (transform) =>
Cesium.Matrix4.clone(transform, camera.transform),
),
// With an offset (a Cartesian3), the camera sits there in the new frame
// looking at its origin.
lookAtTransform: record('camera.lookAtTransform', (transform, offset) => {
Cesium.Matrix4.clone(transform, camera.transform);
if (offset instanceof Cesium.Cartesian3) {
Cesium.Cartesian3.clone(offset, camera.position);
Cesium.Cartesian3.normalize(
Cesium.Cartesian3.negate(offset, camera.direction),
camera.direction,
);
}
}),
zoomIn: record('camera.zoomIn'),
zoomOut: record('camera.zoomOut'),
computeViewRectangle: record(
@@ -165,9 +179,37 @@ export function createFakeViewer({ width = 1024, height = 768 } = {}) {
staticCredits,
primitiveList,
trackedEntityChanged: new Cesium.Event(),
// The viewer clock: only its tick event (CesiumWidget ticks it right
// before scene.render on every animation frame).
clock: { onTick: new Cesium.Event() },
// Assigning raises trackedEntityChanged, as Cesium's Viewer does.
get trackedEntity() {
return trackedEntity;
},
set trackedEntity(value) {
if (value === trackedEntity) return;
trackedEntity = value;
calls.push({ name: 'trackedEntity', args: [value] });
viewer.trackedEntityChanged.raiseEvent(value);
},
entities: {
values: entityList,
add: record('entities.add', (options) => {
const entity = new Cesium.Entity(options);
entityList.push(entity);
return entity;
}),
remove: record('entities.remove', (entity) => {
const index = entityList.indexOf(entity);
if (index >= 0) entityList.splice(index, 1);
return index >= 0;
}),
contains: (entity) => entityList.includes(entity),
},
isDestroyed: () => false,
// The viewer clock: its tick event (CesiumWidget ticks it right before
// scene.render on every animation frame) and current time.
clock: {
onTick: new Cesium.Event(),
currentTime: Cesium.JulianDate.fromIso8601('2026-10-16T12:00:00Z'),
},
imageryList,
terrainProvider: undefined,
imageryLayers: {