Fly the remaining flights through the camera port, on any viewer

The embed view, the celestial-ring focus, the ground-guard lift, the
Bhote Koshi approach and orbit, launch selection and replay flights, and
the cockpit's view and takeover now drive the renderer's camera port.
The contract gains a sineInOut easing, pinned by a conformance trace.

A viewer with no renderer bound, such as one a caller of a public
export brings, now gets a camera port too, as it already got an input
port: cameraOf builds one over the viewer's own Cesium camera and keeps
it for the viewer's life, until a renderer is bound. The Cesium adapter
provides the factory as it loads; code that reaches Cesium takes cameraOf
from the adapter so the factory comes with it, and findCamera answers
null where a missing camera is not an error (HUD, share link, world
focus, Recent Imagery's ZOOM IN). A test walks every package export and
fails one that can reach the bridge without loading the factory.

A destroyed viewer gets no camera and lets go of a built one, and the
application renderer stays bound until its viewer is destroyed.
This commit is contained in:
Sameh Khamis committed 2026-11-06 08:21:57 -08:00
1 parent c5b716b107
commit 1d4e4ebe90
44 files changed
+1167 -344

No files matched your search

+3 -1
View File
@@ -121,11 +121,13 @@ export function createCesiumRendererPlugin({
},
destroy() {
try {
unbind();
input.dispose();
ports.dispose();
if (!viewer.isDestroyed()) viewer.destroy();
} finally {
// Bound until the viewer is gone: a late `cameraOf` must not
// build a camera of its own over the application's viewer.
unbind();
creditContainer.remove();
}
},
+25 -1
View File
@@ -6,8 +6,15 @@
*/
import * as Cesium from 'cesium';
import { createCameraEvents } from '../camera/events.js';
import { listenerList, toCartesian } from './common.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import { cameraFlightActive } from './internals.js';
import { cameraOf, provideUnboundCamera } from '../rendererOf.js';
/**
* `cameraOf`, for code that already reaches Cesium: importing it from here
* loads the factory a viewer with no renderer bound gets its camera from.
*/
export { cameraOf };
/** The contract's easings as Cesium's. */
export const EASINGS = Object.freeze({
@@ -16,6 +23,7 @@ export const EASINGS = Object.freeze({
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
cubicOut: Cesium.EasingFunction.CUBIC_OUT,
quinticInOut: Cesium.EasingFunction.QUINTIC_IN_OUT,
sineInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
});
/** A contract destination as Cesium's: a Cartesian3, or a Rectangle. */
@@ -265,3 +273,19 @@ export function createCesiumCamera({ scene, camera, report }) {
},
};
}
// A Cesium viewer with no renderer bound to it gets a
// camera port over its camera when code first asks `cameraOf` for one.
provideUnboundCamera((viewer) =>
// By shape, not `instanceof`: the viewer may come from another
// copy of Cesium.
typeof viewer.camera?.flyTo === 'function' &&
typeof viewer.camera.moveStart?.addEventListener === 'function' &&
typeof viewer.scene?.postUpdate?.addEventListener === 'function'
? createCesiumCamera({
scene: viewer.scene,
camera: viewer.camera,
report: uncaught,
})
: null,
);
+1
View File
@@ -29,6 +29,7 @@ const EASINGS = {
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
cubicOut: Cesium.EasingFunction.CUBIC_OUT,
quinticInOut: Cesium.EasingFunction.QUINTIC_IN_OUT,
sineInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
};
/** One frame of the virtual clock, ms. */
+24
View File
@@ -15,6 +15,7 @@ import {
import { FRAME_MS, headlessCamera, withVirtualClock } from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { cameraOf } from '../rendererOf.js';
/** Records the headless scene cannot answer: they need the query port. */
const QUERY_RECORDS = new Set([
@@ -208,3 +209,26 @@ test('a flight Cesium does not start ends cancelled rather than never', async ()
assert.equal(await flight.done, 'cancelled');
assert.equal(port.flying, false);
});
test('a Cesium viewer with no renderer bound gets a camera port over its own camera', async () => {
await withVirtualClock(async () => {
const { scene, camera } = headlessCamera();
scene.postUpdate = new Cesium.Event();
scene.requestRender = () => {};
const viewer = { scene, camera };
const port = cameraOf(viewer);
assert.equal(cameraOf(viewer), port, 'one port per viewer');
let outcome = null;
port.flyTo(
{ lon: 2.35, lat: 48.86, height: 1500 },
{ durationS: 0, onComplete: () => (outcome = 'complete') },
);
assert.equal(outcome, 'complete');
const pose = port.pose();
assert.ok(
Math.abs(pose.lon - 2.35) < 1e-9 && Math.abs(pose.lat - 48.86) < 1e-9,
);
assert.ok(Math.abs(pose.height - 1500) < 1e-6);
assert.throws(() => cameraOf({ scene, camera: {} }), /no renderer camera/);
});
});
+15
View File
@@ -50,3 +50,18 @@ export function toCartesian(pos) {
if ('x' in pos) return new Cesium.Cartesian3(pos.x, pos.y, pos.z);
return Cesium.Cartesian3.fromDegrees(pos.lon, pos.lat, pos.height ?? 0);
}
/**
* Where a listener's throw goes with no `error` listener: the platform's
* `reportError` (or a rethrow on a microtask), as a browser reports an event
* listener's exception, loud, while the frame and the other listeners carry
* on.
*/
export function uncaught(error) {
if (typeof globalThis.reportError === 'function')
globalThis.reportError(error);
else
queueMicrotask(() => {
throw error;
});
}
+1 -16
View File
@@ -14,7 +14,7 @@
import * as Cesium from 'cesium';
import { heightsFor } from '../../queries/heights.js';
import { createCesiumCamera } from './camera.js';
import { listenerList, toCartesian } from './common.js';
import { listenerList, toCartesian, uncaught } from './common.js';
import {
atEndOfTick,
billboardLoadError,
@@ -25,21 +25,6 @@ import {
export { listenerList, toCartesian };
/**
* Where a listener's throw goes with no `error` listener: the platform's
* `reportError` (or a rethrow on a microtask), as a browser reports an event
* listener's exception, loud, while the frame and the other listeners carry
* on.
*/
function uncaught(error) {
if (typeof globalThis.reportError === 'function')
globalThis.reportError(error);
else
queueMicrotask(() => {
throw error;
});
}
/** The contract's colour as Cesium's. */
export function toColor(color, alpha = 1) {
if (color === undefined || color === null)
+23
View File
@@ -392,6 +392,29 @@ export const CAMERA_SCRIPTS = Object.freeze([
{ record: 'pose' },
],
},
{
name: 'flyTo sineInOut',
steps: [
START,
{
do: 'flyTo',
args: [
{ ...AUSTIN, height: 4000 },
{
durationS: 1,
easing: 'sineInOut',
orientation: { heading: 0.3, pitch: -0.5, roll: 0 },
},
],
},
{ do: 'frames', count: 15 },
{ record: 'pose' },
{ do: 'frames', count: 30 },
{ record: 'pose' },
{ do: 'frames', count: 30 },
{ record: 'pose' },
],
},
{
name: 'a cancelled flight stops where it was',
steps: [
+104
View File
@@ -2144,6 +2144,110 @@
}
]
},
"flyTo sineInOut": {
"records": [
{
"step": 3,
"kind": "pose",
"value": {
"position": {
"x": -2264202.3786493177,
"y": -16652052.298267456,
"z": 9785772.494992554
},
"direction": {
"x": 0.1297004555930398,
"y": 0.9146885584650551,
"z": -0.38278274886948277
},
"up": {
"x": 0.08931821646822154,
"y": 0.3736965407891975,
"z": 0.9232405708205872
},
"right": {
"x": 0.9875221759666432,
"y": -0.1539341950812336,
"z": -0.0332297390720854
},
"heading": 0.03852827617838983,
"pitch": -1.433276538096362,
"roll": 6.283185307179586,
"height": 13074099.901429506,
"frameIsIdentity": true
}
},
{
"step": 5,
"kind": "pose",
"value": {
"position": {
"x": -1031979.3952742261,
"y": -7589681.480280083,
"z": 4448442.5808664905
},
"direction": {
"x": 0.31556045134531424,
"y": 0.8875905643040791,
"z": 0.33556607651118137
},
"up": {
"x": 0.10445908107755925,
"y": -0.38397902960887687,
"z": 0.9174139770033249
},
"right": {
"x": 0.9431383259772522,
"y": -0.254446644660509,
"z": -0.21388549061082934
},
"heading": 0.25036959095382905,
"pitch": -0.6771468656798949,
"roll": 6.283185307179586,
"height": 2484858.7135209497,
"frameIsIdentity": true
}
},
{
"step": 7,
"kind": "pose",
"value": {
"position": {
"x": -743292.8811925538,
"y": -5466539.584651379,
"z": 3198007.239048282
},
"direction": {
"x": 0.36970163659367444,
"y": 0.7940777354746522,
"z": 0.48245336554262613
},
"up": {
"x": 0.0693712174939781,
"y": -0.5413817815775576,
"z": 0.8379101388331048
},
"right": {
"x": 0.9265572481413991,
"y": -0.2763083722932726,
"z": -0.2552358699659599
},
"heading": 0.2999999999999998,
"pitch": -0.5,
"roll": 6.283185307179586,
"height": 3999.9999999988663,
"frameIsIdentity": true
}
}
],
"flights": [
{
"step": 1,
"outcome": "complete",
"frames": 62
}
]
},
"a cancelled flight stops where it was": {
"records": [
{
+6 -1
View File
@@ -76,7 +76,12 @@ export interface ViewSpec {
}
export type Easing =
'linear' | 'quadraticInOut' | 'cubicInOut' | 'cubicOut' | 'quinticInOut';
| 'linear'
| 'quadraticInOut'
| 'cubicInOut'
| 'cubicOut'
| 'quinticInOut'
| 'sineInOut';
/**
* A flight's omitted orientation is the same as `setView`'s. Its omitted
+59 -6
View File
@@ -9,13 +9,36 @@
const renderers = new WeakMap();
/**
* Bind a renderer to its scene object.
* Camera ports built for scene objects no renderer is bound to (a viewer of
* a caller's own, say), each `{port, dispose}` and kept for as long as its
* scene object lives, or until a renderer is bound to it.
*/
const unboundCameras = new WeakMap();
let buildUnboundCamera = null;
/**
* Provide the factory `cameraOf` builds a camera port with for a scene
* object no renderer is bound to. The renderer adapter provides it as it
* loads; a later call replaces it.
* @param {(host: object) => ({port: object, dispose: () => void} | null)} build
*/
export function provideUnboundCamera(build) {
buildUnboundCamera = build;
}
/**
* Bind a renderer to its scene object. A camera `cameraOf` built for it
* while it had no renderer is disposed: its listeners hear nothing more,
* and `cameraOf` answers with the renderer's camera from then on.
* @param {object} host The scene object callers hold.
* @param {object} renderer
* @returns {() => void} Unbinds, if the binding is still this one.
*/
export function bindRenderer(host, renderer) {
if (renderers.has(host)) throw new Error('This scene already has a renderer');
// The renderer's camera supersedes one built while there was none.
unboundCameras.get(host)?.dispose();
unboundCameras.delete(host);
renderers.set(host, renderer);
return () => {
if (renderers.get(host) === renderer) renderers.delete(host);
@@ -29,13 +52,43 @@ export function bindRenderer(host, renderer) {
export const rendererOf = (host) => (host && renderers.get(host)) || null;
/**
* The camera port of the renderer bound to `host`.
* The camera port of the renderer bound to `host`; with no renderer bound,
* one built over `host` by the provided factory and kept with it while
* `host` lives.
* @param {object|null|undefined} host
* @returns {import('./contract/camera').CameraPort | null} Null when `host`
* has no renderer and no camera can be built for it, or is destroyed.
*/
export function findCamera(host) {
const camera = rendererOf(host)?.camera;
if (camera) return camera;
if (!host || typeof host !== 'object') return null;
if (host.isDestroyed?.()) {
// Gone with its scene: let the built camera go with it.
unboundCameras.get(host)?.dispose();
unboundCameras.delete(host);
return null;
}
let built = unboundCameras.get(host);
if (!built && buildUnboundCamera) {
built = buildUnboundCamera(host);
if (built) unboundCameras.set(host, built);
}
return built?.port ?? null;
}
/**
* `findCamera`, for code that needs the camera.
* @param {object} host
* @returns {import('./contract/camera').CameraPort}
* @throws When no renderer is bound to `host`.
* @throws When there is no camera for `host`.
*/
export function cameraOf(host) {
const camera = rendererOf(host)?.camera;
if (!camera) throw new Error('This scene has no renderer camera');
return camera;
const camera = findCamera(host);
if (camera) return camera;
throw new Error(
host?.isDestroyed?.()
? 'This scene has been destroyed'
: 'This scene has no renderer camera',
);
}
+56 -1
View File
@@ -1,6 +1,12 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { bindRenderer, cameraOf, rendererOf } from './rendererOf.js';
import {
bindRenderer,
cameraOf,
findCamera,
provideUnboundCamera,
rendererOf,
} from './rendererOf.js';
test('a scene finds its renderer until it is unbound', () => {
const scene = {};
@@ -32,3 +38,52 @@ test('cameraOf names the missing renderer instead of returning nothing', () => {
assert.equal(cameraOf(scene), camera);
unbind();
});
test('with no renderer bound, cameraOf builds one camera per scene until a renderer is bound', (t) => {
t.after(() => provideUnboundCamera(null));
const built = [];
provideUnboundCamera((host) => {
if (!host.camera) return null;
const entry = { port: { id: built.length }, disposed: 0 };
entry.dispose = () => (entry.disposed += 1);
built.push(entry);
return entry;
});
const viewer = { camera: {} };
assert.equal(cameraOf(viewer), built[0].port);
assert.equal(cameraOf(viewer), built[0].port, 'kept, not rebuilt');
assert.equal(built.length, 1);
assert.throws(
() => cameraOf({}),
/no renderer camera/,
'nothing to build over',
);
assert.equal(findCamera({}), null);
assert.equal(findCamera(null), null);
const camera = { pose() {} };
const unbind = bindRenderer(viewer, { camera });
assert.equal(
built[0].disposed,
1,
'the renderer supersedes the built camera',
);
assert.equal(cameraOf(viewer), camera);
unbind();
assert.equal(cameraOf(viewer), built[1].port, 'unbound again: a fresh one');
});
test('a destroyed scene gets no built camera, and lets go of the one it had', (t) => {
t.after(() => provideUnboundCamera(null));
let disposed = 0;
provideUnboundCamera(() => ({ port: {}, dispose: () => (disposed += 1) }));
let destroyed = false;
const viewer = { isDestroyed: () => destroyed };
cameraOf(viewer);
destroyed = true;
assert.throws(() => cameraOf(viewer), /destroyed/);
assert.equal(disposed, 1);
assert.equal(findCamera(viewer), null, 'findCamera answers null instead');
assert.throws(() => cameraOf(viewer), /destroyed/);
assert.equal(disposed, 1, 'once');
});
+1
View File
@@ -61,6 +61,7 @@ const EASINGS = {
cubicInOut: (t) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2),
quinticInOut: (t) => (t < 0.5 ? 16 * t ** 5 : 1 - (-2 * t + 2) ** 5 / 2),
cubicOut: (t) => (t - 1) ** 3 + 1,
sineInOut: (t) => 0.5 * (1 - Math.cos(Math.PI * t)),
};
/** Above this height, a descending flight eases out rather than in and out. */
+146
View File
@@ -0,0 +1,146 @@
/**
* A public entry that reaches the renderer bridge (`rendererOf.js`) may hand
* `cameraOf` a viewer of the caller's own, with no renderer bound. The
* bridge builds a camera port for it with the factory the Cesium adapter
* provides as `render/cesium/camera.js` loads, so every such entry must load
* that module too.
*
* The graph is every static import, re-export and literal dynamic import of
* the entry's module and those it reaches, read by the parsers the Cesium
* ratchet uses; bare specifiers (packages) end the walk.
*/
import assert from 'node:assert/strict';
import { existsSync, readFileSync, statSync } from 'node:fs';
import path from 'node:path';
import test from 'node:test';
import { fileURLToPath } from 'node:url';
import { parsers } from 'prettier/plugins/babel.mjs';
import { parse as parseSfc } from 'vue/compiler-sfc';
const root = path.resolve(
path.dirname(fileURLToPath(import.meta.url)),
'../..',
);
const BRIDGE = 'src/render/rendererOf.js';
const FACTORY = 'src/render/cesium/camera.js';
/**
* Entries that take their Cesium code injected: the module named here is
* GEV's Cesium side for them, and must load the factory. Given another, the
* entry's flight finds no camera (`findCamera`) and does nothing.
*/
const INJECTED = {
'./layers/recent-imagery': 'src/layers/recentImagery/rendering.js',
};
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
/** The browser module an export resolves to, or null for Node-only ones. */
function browserTarget(declaration) {
if (typeof declaration === 'string') return declaration;
if (!declaration || typeof declaration !== 'object') return null;
for (const condition of ['browser', 'import', 'default']) {
const target = browserTarget(declaration[condition]);
if (target) return target;
}
return null;
}
function specifiersOf(file) {
let code = readFileSync(path.join(root, file), 'utf8');
if (file.endsWith('.vue')) {
const { descriptor } = parseSfc(code, { filename: file });
code = [descriptor.script, descriptor.scriptSetup]
.filter(Boolean)
.map((block) => block.content)
.join('\n');
}
const found = [];
const walk = (node) => {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) return node.forEach(walk);
if (
(node.type === 'ImportDeclaration' ||
node.type === 'ExportNamedDeclaration' ||
node.type === 'ExportAllDeclaration') &&
node.source
)
found.push({ specifier: node.source.value, lazy: false });
if (
node.type === 'ImportExpression' &&
node.source?.type === 'StringLiteral'
)
found.push({ specifier: node.source.value, lazy: true });
if (
node.type === 'CallExpression' &&
node.callee?.type === 'Import' &&
node.arguments[0]?.type === 'StringLiteral'
)
found.push({ specifier: node.arguments[0].value, lazy: true });
for (const key of Object.keys(node))
if (key !== 'loc' && key !== 'start' && key !== 'end') walk(node[key]);
};
walk(parsers.babel.parse(code));
return found;
}
/** A relative specifier as a repository file, or null when it is a package. */
function resolve(from, specifier) {
const bare = specifier.split('?')[0];
if (!bare.startsWith('.')) return null;
const base = path.join(path.dirname(from), bare);
const candidates = ['', '.js', '.mjs', '.vue', '/index.js', '/index.mjs'];
for (const suffix of candidates) {
const full = path.join(root, base + suffix);
if (existsSync(full) && statSync(full).isFile())
return path.normalize(base + suffix);
}
// A subgraph dropped here would hide a missing factory.
throw new Error(`${from}: cannot resolve ${specifier}`);
}
/**
* The modules `entry` reaches. With `eager`, only through static imports:
* what has loaded once the entry has, before any lazy import resolves.
*/
function reachable(entry, { eager = false } = {}) {
const seen = new Set([entry]);
const queue = [entry];
while (queue.length) {
const file = queue.pop();
if (!/\.(m?js|vue)$/.test(file)) continue;
for (const { specifier, lazy } of specifiersOf(file)) {
if (eager && lazy) continue;
const next = resolve(file, specifier);
if (next && !seen.has(next)) {
seen.add(next);
queue.push(next);
}
}
}
return seen;
}
test('every public entry that reaches the renderer bridge loads the unbound camera factory', () => {
const missing = [];
let bridged = 0;
for (const [key, declaration] of Object.entries(pkg.exports)) {
const target = browserTarget(declaration);
if (typeof target !== 'string' || !target.startsWith('./src/')) continue;
const entry = path.normalize(target.slice(2));
const graph = reachable(entry);
// Any path to the bridge counts, lazy or not; only an eager one loads
// the factory in time for the first `cameraOf`.
if (!graph.has(BRIDGE)) continue;
bridged += 1;
const carrier = INJECTED[key];
const loads = (file) => reachable(file, { eager: true }).has(FACTORY);
if (!loads(entry) && !(carrier && loads(carrier))) missing.push(key);
}
assert.ok(bridged > 0, 'no entry reaches the bridge: the walk is broken');
assert.deepEqual(
missing,
[],
`These entries can reach cameraOf without ${FACTORY}; import it where the entry first reaches the bridge.`,
);
});