mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Fly the camera through the renderer's camera port
The Cesium camera port moves into render/cesium/camera.js, with the listener list and position conversion shared from common.js. It now covers flights (flyTo, flyToBounds, cancelFlight, flying), lookAt and release, command hooks, and a flightEnd event for the flights it starts. A flight's end that Cesium raises inside one of the port's own calls is delivered once Cesium's call returns, so its callback sees the flight let go of. A flight Cesium declines to start, mid scene-mode morph, ends as cancelled instead of never settling. Flight traces run in Node on the recorder's headless camera with a virtual clock; the browser harness keeps the instant traces. The startup fly-in, landmark and viewport flights, share-link restore and the shell's camera state now go through the port. camera.js and sharelink.js leave the Cesium allow-list.
This commit is contained in:
1 parent
b5900b4178
commit
46a53bb49c
20 files changed
+846
-305
No files matched your search
@@ -318,7 +318,6 @@ test('the application refuses a renderer it cannot run on, and destroys it', asy
|
||||
});
|
||||
|
||||
const EXPECTED_MISSING = [
|
||||
'camera.cancelFlight',
|
||||
'camera.controls',
|
||||
'camera.controls.coast',
|
||||
'camera.controls.coast.drag',
|
||||
@@ -334,9 +333,6 @@ const EXPECTED_MISSING = [
|
||||
'camera.controls.suspend',
|
||||
'camera.controls.zoomFactor',
|
||||
'camera.controls.zoomInputs',
|
||||
'camera.flyTo',
|
||||
'camera.flyToBounds',
|
||||
'camera.flying',
|
||||
'camera.follow',
|
||||
'camera.followFramed',
|
||||
'camera.followOffset',
|
||||
@@ -344,11 +340,8 @@ const EXPECTED_MISSING = [
|
||||
'camera.followOffset.set',
|
||||
'camera.followed',
|
||||
'camera.look',
|
||||
'camera.lookAt',
|
||||
'camera.matrices',
|
||||
'camera.move',
|
||||
'camera.onCommand',
|
||||
'camera.release',
|
||||
'camera.rotateAround',
|
||||
'camera.setFov',
|
||||
'camera.zoom',
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
/**
|
||||
* @module render/cesium/camera
|
||||
* @description The Cesium renderer's camera port over a Cesium camera:
|
||||
* poses, views, flights, `lookAt`, events and command hooks, each mapped
|
||||
* onto Cesium's own camera call.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { createCameraEvents } from '../camera/events.js';
|
||||
import { listenerList, toCartesian } from './common.js';
|
||||
import { cameraFlightActive } from './internals.js';
|
||||
|
||||
/** The contract's easings as Cesium's. */
|
||||
export const EASINGS = Object.freeze({
|
||||
linear: Cesium.EasingFunction.LINEAR_NONE,
|
||||
quadraticInOut: Cesium.EasingFunction.QUADRATIC_IN_OUT,
|
||||
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
|
||||
cubicOut: Cesium.EasingFunction.CUBIC_OUT,
|
||||
quinticInOut: Cesium.EasingFunction.QUINTIC_IN_OUT,
|
||||
});
|
||||
|
||||
/** A contract destination as Cesium's: a Cartesian3, or a Rectangle. */
|
||||
export function toDestination(d) {
|
||||
if ('rect' in d) {
|
||||
const r = d.rect;
|
||||
return Cesium.Rectangle.fromDegrees(r.west, r.south, r.east, r.north);
|
||||
}
|
||||
return toCartesian(d);
|
||||
}
|
||||
|
||||
/**
|
||||
* A contract orientation as Cesium's; omitted angles are heading 0, pitch
|
||||
* straight down and roll 0, as the contract says.
|
||||
*/
|
||||
export function toOrientation(o = {}) {
|
||||
if ('direction' in o)
|
||||
return { direction: toCartesian(o.direction), up: toCartesian(o.up) };
|
||||
return {
|
||||
heading: o.heading ?? 0,
|
||||
pitch: o.pitch ?? -Math.PI / 2,
|
||||
roll: o.roll ?? 0,
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* @param {{scene: object, camera: object, report: (error: unknown) => void}}
|
||||
* options `scene` gives `requestRender` and the `postUpdate` tick
|
||||
* `changed` is measured on.
|
||||
* @returns {{port: import('../contract/camera').CameraPort, dispose: () => void}}
|
||||
*/
|
||||
export function createCesiumCamera({ scene, camera, report }) {
|
||||
const removers = [];
|
||||
// Camera events: Cesium's own moveStart and moveEnd (500 ms after the
|
||||
// last change, never while following), and `changed` measured per
|
||||
// listener on every tick, where Cesium measures its single threshold.
|
||||
const cameraEvents = createCameraEvents({
|
||||
pose: () => cameraPort.pose(),
|
||||
report,
|
||||
});
|
||||
removers.push(
|
||||
scene.postUpdate.addEventListener(() => cameraEvents.stepChanged()),
|
||||
camera.moveStart.addEventListener(() => cameraEvents.emit('moveStart')),
|
||||
camera.moveEnd.addEventListener(() => cameraEvents.emit('moveEnd')),
|
||||
);
|
||||
|
||||
// Camera commands: hooks run before each one, so an owner can yield.
|
||||
const commandHooks = listenerList(report);
|
||||
const command = (kind) => commandHooks.fire({ kind });
|
||||
|
||||
// The flight this port started, while it is in progress. Cesium cancels
|
||||
// a flight in progress when another starts, including one started on
|
||||
// its camera directly, and runs the callbacks inside the call or frame
|
||||
// that ends it. `flying` sees every Cesium flight; `flightEnd` comes for
|
||||
// the flights this port started (the application's flights all move onto
|
||||
// the port with the camera family).
|
||||
let flight = null;
|
||||
|
||||
// A flight's end that Cesium raises inside one of this port's own calls
|
||||
// waits until Cesium's call returns, still inside the port's call: Cesium
|
||||
// runs a cancelled flight's callback before it lets go of that flight, so
|
||||
// the callback would read `flying` wrong, and a flight it started would
|
||||
// be let go of with the old one.
|
||||
let inCesiumCall = 0;
|
||||
const pendingEnds = [];
|
||||
function cesiumCall(fn) {
|
||||
inCesiumCall += 1;
|
||||
try {
|
||||
return fn();
|
||||
} finally {
|
||||
inCesiumCall -= 1;
|
||||
if (inCesiumCall === 0)
|
||||
for (const deliver of pendingEnds.splice(0)) deliver();
|
||||
}
|
||||
}
|
||||
|
||||
function startFlight(start, options) {
|
||||
let resolve;
|
||||
const done = new Promise((r) => (resolve = r));
|
||||
let ended = false;
|
||||
const handle = {
|
||||
done,
|
||||
cancel() {
|
||||
if (flight === handle) cesiumCall(() => camera.cancelFlight());
|
||||
},
|
||||
};
|
||||
const end = (outcome) => {
|
||||
if (ended) return;
|
||||
ended = true;
|
||||
if (flight === handle) flight = null;
|
||||
const deliver = () => {
|
||||
const cb =
|
||||
outcome === 'complete' ? options.onComplete : options.onCancel;
|
||||
try {
|
||||
cb?.();
|
||||
} catch (error) {
|
||||
report(error);
|
||||
}
|
||||
resolve(outcome);
|
||||
cameraEvents.emit('flightEnd');
|
||||
};
|
||||
if (inCesiumCall) pendingEnds.push(deliver);
|
||||
else deliver();
|
||||
};
|
||||
flight = handle;
|
||||
cesiumCall(() =>
|
||||
start({
|
||||
complete: () => end('complete'),
|
||||
cancel: () => end('cancelled'),
|
||||
}),
|
||||
);
|
||||
// Cesium starts nothing mid scene-mode morph, and calls neither back.
|
||||
if (!ended && !cameraFlightActive(camera)) end('cancelled');
|
||||
scene.requestRender();
|
||||
return handle;
|
||||
}
|
||||
|
||||
const cameraPort = {
|
||||
on: (event, cb, options) => cameraEvents.on(event, cb, options),
|
||||
onCommand: (cb) => commandHooks.on(cb),
|
||||
setView(spec) {
|
||||
command('setView');
|
||||
const d = spec.destination;
|
||||
camera.setView({
|
||||
...(d ? { destination: toDestination(d) } : {}),
|
||||
orientation: toOrientation(spec.orientation),
|
||||
});
|
||||
scene.requestRender();
|
||||
},
|
||||
flyTo(destination, options = {}) {
|
||||
command('flyTo');
|
||||
return startFlight(
|
||||
(callbacks) =>
|
||||
camera.flyTo({
|
||||
destination: toDestination(destination),
|
||||
orientation: toOrientation(options.orientation),
|
||||
duration: options.durationS,
|
||||
easingFunction: options.easing && EASINGS[options.easing],
|
||||
maximumHeight: options.maxHeight,
|
||||
pitchAdjustHeight: options.pitchAdjustHeight,
|
||||
endTransform:
|
||||
options.endFrame === 'world'
|
||||
? Cesium.Matrix4.IDENTITY
|
||||
: undefined,
|
||||
...callbacks,
|
||||
}),
|
||||
options,
|
||||
);
|
||||
},
|
||||
flyToBounds(sphere, options = {}) {
|
||||
command('flyToBounds');
|
||||
const o = options.offset ?? {};
|
||||
return startFlight(
|
||||
(callbacks) =>
|
||||
camera.flyToBoundingSphere(
|
||||
new Cesium.BoundingSphere(
|
||||
toCartesian(sphere.center),
|
||||
sphere.radius,
|
||||
),
|
||||
{
|
||||
offset: new Cesium.HeadingPitchRange(
|
||||
o.heading ?? 0,
|
||||
o.pitch ?? -Math.PI / 4,
|
||||
o.range ?? 0,
|
||||
),
|
||||
duration: options.durationS,
|
||||
...callbacks,
|
||||
},
|
||||
),
|
||||
options,
|
||||
);
|
||||
},
|
||||
cancelFlight() {
|
||||
command('cancelFlight');
|
||||
cesiumCall(() => camera.cancelFlight());
|
||||
},
|
||||
get flying() {
|
||||
return cameraFlightActive(camera);
|
||||
},
|
||||
lookAt(target, offset) {
|
||||
command('lookAt');
|
||||
camera.lookAt(
|
||||
toCartesian(target),
|
||||
new Cesium.HeadingPitchRange(
|
||||
offset.heading,
|
||||
offset.pitch,
|
||||
offset.range,
|
||||
),
|
||||
);
|
||||
scene.requestRender();
|
||||
},
|
||||
release() {
|
||||
command('release');
|
||||
camera.lookAtTransform(Cesium.Matrix4.IDENTITY);
|
||||
scene.requestRender();
|
||||
},
|
||||
viewRectangle() {
|
||||
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
|
||||
if (!rect) return null;
|
||||
const deg = Cesium.Math.toDegrees;
|
||||
return {
|
||||
west: deg(rect.west),
|
||||
south: deg(rect.south),
|
||||
east: deg(rect.east),
|
||||
north: deg(rect.north),
|
||||
};
|
||||
},
|
||||
pose() {
|
||||
const v = (c) => ({ x: c.x, y: c.y, z: c.z });
|
||||
// Cesium has no cartographic position for an eye at the earth's
|
||||
// centre; the pose then says so with NaN.
|
||||
const carto = camera.positionCartographic ?? {
|
||||
longitude: NaN,
|
||||
latitude: NaN,
|
||||
height: NaN,
|
||||
};
|
||||
return {
|
||||
lon: Cesium.Math.toDegrees(carto.longitude),
|
||||
lat: Cesium.Math.toDegrees(carto.latitude),
|
||||
position: v(camera.positionWC),
|
||||
direction: v(camera.directionWC),
|
||||
up: v(camera.upWC),
|
||||
right: v(camera.rightWC),
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
height: carto.height,
|
||||
fovy: camera.frustum.fovy,
|
||||
aspectRatio: camera.frustum.aspectRatio,
|
||||
near: camera.frustum.near,
|
||||
far: camera.frustum.far,
|
||||
frameIsIdentity: Cesium.Matrix4.equals(
|
||||
camera.transform,
|
||||
Cesium.Matrix4.IDENTITY,
|
||||
),
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
return {
|
||||
port: cameraPort,
|
||||
dispose() {
|
||||
for (const off of removers.splice(0)) off();
|
||||
cameraEvents.clear();
|
||||
commandHooks.clear();
|
||||
},
|
||||
};
|
||||
}
|
||||
@@ -19,9 +19,10 @@ import {
|
||||
import { runCameraScript } from '../conformance/cameraRunner.js';
|
||||
import { updateCameraChanged } from './internals.js';
|
||||
|
||||
const FRAME_MS = 1000 / 60;
|
||||
|
||||
/** The contract's easings as Cesium's. */
|
||||
/**
|
||||
* The contract's easings as Cesium's, kept here rather than taken from the
|
||||
* port: the traces are the reference the port is checked against.
|
||||
*/
|
||||
const EASINGS = {
|
||||
linear: Cesium.EasingFunction.LINEAR_NONE,
|
||||
quadraticInOut: Cesium.EasingFunction.QUADRATIC_IN_OUT,
|
||||
@@ -30,8 +31,11 @@ const EASINGS = {
|
||||
quinticInOut: Cesium.EasingFunction.QUINTIC_IN_OUT,
|
||||
};
|
||||
|
||||
/** One frame of the virtual clock, ms. */
|
||||
export const FRAME_MS = 1000 / 60;
|
||||
|
||||
/** Run `fn` with `performance.now()` reading the virtual clock. */
|
||||
async function withVirtualClock(fn) {
|
||||
export async function withVirtualClock(fn) {
|
||||
const real = Object.getOwnPropertyDescriptor(globalThis, 'performance');
|
||||
const clock = { now: 0 };
|
||||
Object.defineProperty(globalThis, 'performance', {
|
||||
@@ -45,7 +49,8 @@ async function withVirtualClock(fn) {
|
||||
}
|
||||
}
|
||||
|
||||
function headlessCamera() {
|
||||
/** A Cesium camera on a scene with no globe, sized as the scripts' viewport. */
|
||||
export function headlessCamera() {
|
||||
const scene = {
|
||||
canvas: {
|
||||
clientWidth: SCRIPT_VIEWPORT.width,
|
||||
|
||||
@@ -0,0 +1,210 @@
|
||||
/**
|
||||
* The Cesium port's camera commands against the reference traces: the
|
||||
* conformance camera checks run on the port over the same headless camera
|
||||
* and virtual clock the traces were recorded with, so a mapping of the
|
||||
* contract onto Cesium that differs from the recorder's shows.
|
||||
*/
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import * as Cesium from 'cesium';
|
||||
import {
|
||||
CAMERA_SCRIPTS,
|
||||
DEFAULT_TOLERANCE,
|
||||
runConformance,
|
||||
} from '../conformance/index.js';
|
||||
import { FRAME_MS, headlessCamera, withVirtualClock } from './cameraGoldens.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { createCesiumPorts } from './ports.js';
|
||||
|
||||
/** Records the headless scene cannot answer: they need the query port. */
|
||||
const QUERY_RECORDS = new Set([
|
||||
'project',
|
||||
'pickEllipsoid',
|
||||
'pickRay',
|
||||
'occluded',
|
||||
]);
|
||||
/** Commands and records the port does not have yet. */
|
||||
const MISSING = new Set(['move', 'look', 'rotateAround', 'zoom', 'matrices']);
|
||||
|
||||
const runnable = CAMERA_SCRIPTS.filter((script) =>
|
||||
script.steps.every(
|
||||
(step) =>
|
||||
!MISSING.has(step.do) &&
|
||||
!MISSING.has(step.record) &&
|
||||
!QUERY_RECORDS.has(step.record),
|
||||
),
|
||||
).map((script) => `camera.trace.${script.name}`);
|
||||
|
||||
const CHECKS = new Set([...runnable, 'camera.flight.callbacks']);
|
||||
|
||||
function headlessHarness(clock) {
|
||||
return {
|
||||
name: 'cesium (headless camera)',
|
||||
async create() {
|
||||
const { scene } = headlessCamera();
|
||||
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
|
||||
scene[name] = new Cesium.Event();
|
||||
scene.primitives = { add() {}, remove() {} };
|
||||
scene.requestRender = () => {};
|
||||
clock.now = 0;
|
||||
const ports = createCesiumPorts(
|
||||
{ scene, clock: { currentTime: Cesium.JulianDate.now() } },
|
||||
{ capabilities: new Set() },
|
||||
);
|
||||
return {
|
||||
camera: ports.camera,
|
||||
query: ports.query,
|
||||
destroy: () => ports.dispose(),
|
||||
frameScene() {
|
||||
clock.now += FRAME_MS;
|
||||
scene.tweens.update();
|
||||
scene.postUpdate.raiseEvent(scene);
|
||||
},
|
||||
};
|
||||
},
|
||||
frame: async (r) => r.frameScene(),
|
||||
now: () => clock.now,
|
||||
toEcef: (p) => {
|
||||
const e =
|
||||
'lon' in p
|
||||
? Cesium.Cartesian3.fromDegrees(p.lon, p.lat, p.height ?? 0)
|
||||
: p;
|
||||
return { x: e.x, y: e.y, z: e.z };
|
||||
},
|
||||
tolerance: DEFAULT_TOLERANCE,
|
||||
flightPaths: 'trace',
|
||||
};
|
||||
}
|
||||
|
||||
test('the camera port retraces the reference flights, views and frames', async () => {
|
||||
assert.ok(runnable.length >= 10, `only ${runnable.length} scripts run`);
|
||||
const report = await withVirtualClock((clock) =>
|
||||
runConformance(headlessHarness(clock), { only: (id) => CHECKS.has(id) }),
|
||||
);
|
||||
const failed = report.results.filter((r) => r.status === 'fail');
|
||||
assert.deepEqual(
|
||||
failed.map((r) => `${r.id}: ${r.detail}`),
|
||||
[],
|
||||
);
|
||||
assert.equal(report.passed, CHECKS.size);
|
||||
});
|
||||
|
||||
test('a cancelled flight has let go before its callbacks, so they can fly again', async () => {
|
||||
await withVirtualClock(async (clock) => {
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
scene.requestRender = () => {};
|
||||
const port = createCesiumCamera({
|
||||
scene,
|
||||
camera,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}).port;
|
||||
const seen = [];
|
||||
let replacement = null;
|
||||
port.flyTo(
|
||||
{ lon: 0, lat: 0, height: 1e6 },
|
||||
{
|
||||
durationS: 1,
|
||||
onCancel: () => {
|
||||
seen.push(['cancelled, flying', port.flying]);
|
||||
replacement = port.flyTo(
|
||||
{ lon: 1, lat: 1, height: 1e6 },
|
||||
{ durationS: 0.2, onComplete: () => seen.push(['replaced']) },
|
||||
);
|
||||
},
|
||||
},
|
||||
);
|
||||
port.cancelFlight();
|
||||
assert.deepEqual(seen, [['cancelled, flying', false]]);
|
||||
assert.ok(port.flying, 'the replacement flies');
|
||||
for (let i = 0; i < 30 && port.flying; i++) {
|
||||
clock.now += FRAME_MS;
|
||||
scene.tweens.update();
|
||||
}
|
||||
assert.equal(await replacement.done, 'complete');
|
||||
assert.deepEqual(seen.at(-1), ['replaced']);
|
||||
|
||||
// Superseded by a new flyTo: the old one's onCancel still runs inside
|
||||
// that call, and sees the new flight flying.
|
||||
const order = [];
|
||||
port.flyTo(
|
||||
{ lon: 2, lat: 2, height: 1e6 },
|
||||
{
|
||||
durationS: 1,
|
||||
onCancel: () => order.push(['old cancelled', port.flying]),
|
||||
},
|
||||
);
|
||||
port.flyTo({ lon: 3, lat: 3, height: 1e6 }, { durationS: 1 });
|
||||
assert.deepEqual(order, [['old cancelled', true]]);
|
||||
});
|
||||
});
|
||||
|
||||
function headlessPort() {
|
||||
const { scene, camera } = headlessCamera();
|
||||
scene.postUpdate = new Cesium.Event();
|
||||
scene.requestRender = () => {};
|
||||
const port = createCesiumCamera({
|
||||
scene,
|
||||
camera,
|
||||
report: (error) => {
|
||||
throw error;
|
||||
},
|
||||
}).port;
|
||||
return { scene, camera, port };
|
||||
}
|
||||
|
||||
test('commands announce themselves first; flights raise flightEnd once each', () => {
|
||||
const { port } = headlessPort();
|
||||
const seen = [];
|
||||
const off = port.onCommand((c) => seen.push(c.kind));
|
||||
port.on('flightEnd', () => seen.push('flightEnd'));
|
||||
const target = Cesium.Cartesian3.fromDegrees(0, 0, 0);
|
||||
port.setView({ destination: { lon: 0, lat: 0, height: 1e6 } });
|
||||
port.lookAt(target, { heading: 0, pitch: -0.5, range: 1000 });
|
||||
port.release();
|
||||
port.flyTo({ lon: 1, lat: 1, height: 1e6 }, { durationS: 1 });
|
||||
port.flyToBounds({ center: target, radius: 10 }, { durationS: 1 });
|
||||
port.cancelFlight();
|
||||
off();
|
||||
port.setView({ destination: { lon: 0, lat: 0, height: 1e6 } });
|
||||
assert.deepEqual(seen, [
|
||||
'setView',
|
||||
'lookAt',
|
||||
'release',
|
||||
'flyTo',
|
||||
'flyToBounds',
|
||||
'flightEnd',
|
||||
'cancelFlight',
|
||||
'flightEnd',
|
||||
]);
|
||||
});
|
||||
|
||||
test('endFrame world ends a flight out of a lookAt frame', async () => {
|
||||
await withVirtualClock(async (clock) => {
|
||||
const { scene, port } = headlessPort();
|
||||
const target = Cesium.Cartesian3.fromDegrees(0, 0, 0);
|
||||
port.lookAt(target, { heading: 0, pitch: -0.5, range: 1000 });
|
||||
assert.equal(port.pose().frameIsIdentity, false);
|
||||
const flight = port.flyTo(
|
||||
{ lon: 1, lat: 1, height: 5000 },
|
||||
{ durationS: 0.2, endFrame: 'world' },
|
||||
);
|
||||
for (let i = 0; i < 30 && port.flying; i++) {
|
||||
clock.now += FRAME_MS;
|
||||
scene.tweens.update();
|
||||
}
|
||||
assert.equal(await flight.done, 'complete');
|
||||
assert.equal(port.pose().frameIsIdentity, true);
|
||||
});
|
||||
});
|
||||
|
||||
test('a flight Cesium does not start ends cancelled rather than never', async () => {
|
||||
const { camera, port } = headlessPort();
|
||||
// Mid scene-mode morph Cesium returns without flying or calling back.
|
||||
camera._mode = Cesium.SceneMode.MORPHING;
|
||||
const flight = port.flyTo({ lon: 1, lat: 1, height: 1e6 }, { durationS: 1 });
|
||||
assert.equal(await flight.done, 'cancelled');
|
||||
assert.equal(port.flying, false);
|
||||
});
|
||||
@@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @module render/cesium/common
|
||||
* @description What the Cesium ports share: the contract's listener rules
|
||||
* and its positions as Cesium's.
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
|
||||
/**
|
||||
* One subscription list under the contract's listener rules: subscription
|
||||
* order, one removed during delivery does not run, one added during
|
||||
* delivery waits for the next event, and a throw goes to `onThrow` while
|
||||
* the rest still run. Each subscription is its own entry, so a callback
|
||||
* subscribed twice runs twice.
|
||||
* @param {(error: unknown) => void} onThrow
|
||||
*/
|
||||
export function listenerList(onThrow) {
|
||||
const entries = [];
|
||||
return {
|
||||
get size() {
|
||||
return entries.length;
|
||||
},
|
||||
on(cb) {
|
||||
const entry = { cb, live: true };
|
||||
entries.push(entry);
|
||||
return () => {
|
||||
entry.live = false;
|
||||
const i = entries.indexOf(entry);
|
||||
if (i >= 0) entries.splice(i, 1);
|
||||
};
|
||||
},
|
||||
fire(...args) {
|
||||
for (const entry of entries.slice()) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb(...args);
|
||||
} catch (error) {
|
||||
onThrow(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
for (const entry of entries) entry.live = false;
|
||||
entries.length = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** A contract position as ECEF. */
|
||||
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);
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
* `CESIUM_CHECKS` lists the checks of the ports the Cesium renderer has.
|
||||
* Each migration adds the checks of the members it brings, so the suite
|
||||
* shows how far the renderer is through the contract; every other check is
|
||||
* left out of the run rather than failed.
|
||||
* left out of the run rather than failed. Camera flights are checked in
|
||||
* Node instead (`cameraPort.test.mjs`): a page's frames come on the real
|
||||
* clock at the display's rate, where the reference traces step 1/60 s.
|
||||
*/
|
||||
import { DEFAULT_TOLERANCE } from '../conformance/index.js';
|
||||
import { toEcef } from '../stub/math.js';
|
||||
@@ -14,6 +16,11 @@ import { createCesiumSceneRenderer, pointerFeedOf } from './sceneRenderer.js';
|
||||
|
||||
/** @type {ReadonlySet<string>} */
|
||||
export const CESIUM_CHECKS = new Set([
|
||||
'camera.trace.setView angles',
|
||||
'camera.trace.setView keeps the position when only orientation is given',
|
||||
'camera.trace.lookAt sweep and release',
|
||||
'camera.trace.flyTo with a duration of 0 completes inside the call',
|
||||
'camera.trace.flyTo where the camera already is completes inside the call',
|
||||
'camera.viewRectangle',
|
||||
'draw.drillPick',
|
||||
'draw.ids',
|
||||
|
||||
+7
-122
@@ -13,7 +13,8 @@
|
||||
*/
|
||||
import * as Cesium from 'cesium';
|
||||
import { heightsFor } from '../../queries/heights.js';
|
||||
import { createCameraEvents } from '../camera/events.js';
|
||||
import { createCesiumCamera } from './camera.js';
|
||||
import { listenerList, toCartesian } from './common.js';
|
||||
import {
|
||||
atEndOfTick,
|
||||
billboardLoadError,
|
||||
@@ -22,6 +23,8 @@ import {
|
||||
renderPending,
|
||||
} from './internals.js';
|
||||
|
||||
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
|
||||
@@ -37,46 +40,6 @@ function uncaught(error) {
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* One subscription list under the contract's listener rules: subscription
|
||||
* order, one removed during delivery does not run, one added during
|
||||
* delivery waits for the next event, and a throw goes to `onThrow` while
|
||||
* the rest still run. Each subscription is its own entry, so a callback
|
||||
* subscribed twice runs twice.
|
||||
* @param {(error: unknown) => void} onThrow
|
||||
*/
|
||||
export function listenerList(onThrow) {
|
||||
const entries = [];
|
||||
return {
|
||||
get size() {
|
||||
return entries.length;
|
||||
},
|
||||
on(cb) {
|
||||
const entry = { cb, live: true };
|
||||
entries.push(entry);
|
||||
return () => {
|
||||
entry.live = false;
|
||||
const i = entries.indexOf(entry);
|
||||
if (i >= 0) entries.splice(i, 1);
|
||||
};
|
||||
},
|
||||
fire(...args) {
|
||||
for (const entry of entries.slice()) {
|
||||
if (!entry.live) continue;
|
||||
try {
|
||||
entry.cb(...args);
|
||||
} catch (error) {
|
||||
onThrow(error);
|
||||
}
|
||||
}
|
||||
},
|
||||
clear() {
|
||||
for (const entry of entries) entry.live = false;
|
||||
entries.length = 0;
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
/** The contract's colour as Cesium's. */
|
||||
export function toColor(color, alpha = 1) {
|
||||
if (color === undefined || color === null)
|
||||
@@ -97,12 +60,6 @@ export function toImage(image) {
|
||||
throw new Error('the Cesium renderer takes URL, SVG and canvas images only');
|
||||
}
|
||||
|
||||
/** A contract position as ECEF. */
|
||||
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);
|
||||
}
|
||||
|
||||
const ANCHORS = {
|
||||
center: Cesium.VerticalOrigin.CENTER,
|
||||
bottom: Cesium.VerticalOrigin.BOTTOM,
|
||||
@@ -789,80 +746,8 @@ export function createCesiumPorts(widget, { capabilities }) {
|
||||
models: (spec) => makeSet('models', { ...spec }, buildModels),
|
||||
};
|
||||
|
||||
// Camera events: Cesium's own moveStart and moveEnd (500 ms after the
|
||||
// last change, never while following), and `changed` measured per
|
||||
// listener on every tick, where Cesium measures its single threshold.
|
||||
const cameraEvents = createCameraEvents({
|
||||
pose: () => cameraPort.pose(),
|
||||
report,
|
||||
});
|
||||
removers.push(
|
||||
scene.postUpdate.addEventListener(() => {
|
||||
if (!disposed) cameraEvents.stepChanged();
|
||||
}),
|
||||
camera.moveStart.addEventListener(() => cameraEvents.emit('moveStart')),
|
||||
camera.moveEnd.addEventListener(() => cameraEvents.emit('moveEnd')),
|
||||
);
|
||||
|
||||
const cameraPort = {
|
||||
on: (event, cb, options) => cameraEvents.on(event, cb, options),
|
||||
setView(spec) {
|
||||
const d = spec.destination;
|
||||
if (d && 'rect' in d)
|
||||
throw new Error('the Cesium renderer takes position destinations only');
|
||||
const o = spec.orientation ?? {};
|
||||
camera.setView({
|
||||
...(d ? { destination: toCartesian(d) } : {}),
|
||||
orientation: {
|
||||
heading: o.heading ?? 0,
|
||||
pitch: o.pitch ?? -Math.PI / 2,
|
||||
roll: o.roll ?? 0,
|
||||
},
|
||||
});
|
||||
scene.requestRender();
|
||||
},
|
||||
viewRectangle() {
|
||||
const rect = camera.computeViewRectangle(Cesium.Ellipsoid.WGS84);
|
||||
if (!rect) return null;
|
||||
const deg = Cesium.Math.toDegrees;
|
||||
return {
|
||||
west: deg(rect.west),
|
||||
south: deg(rect.south),
|
||||
east: deg(rect.east),
|
||||
north: deg(rect.north),
|
||||
};
|
||||
},
|
||||
pose() {
|
||||
const v = (c) => ({ x: c.x, y: c.y, z: c.z });
|
||||
// Cesium has no cartographic position for an eye at the earth's
|
||||
// centre; the pose then says so with NaN.
|
||||
const carto = camera.positionCartographic ?? {
|
||||
longitude: NaN,
|
||||
latitude: NaN,
|
||||
height: NaN,
|
||||
};
|
||||
return {
|
||||
lon: Cesium.Math.toDegrees(carto.longitude),
|
||||
lat: Cesium.Math.toDegrees(carto.latitude),
|
||||
position: v(camera.positionWC),
|
||||
direction: v(camera.directionWC),
|
||||
up: v(camera.upWC),
|
||||
right: v(camera.rightWC),
|
||||
heading: camera.heading,
|
||||
pitch: camera.pitch,
|
||||
roll: camera.roll,
|
||||
height: carto.height,
|
||||
fovy: camera.frustum.fovy,
|
||||
aspectRatio: camera.frustum.aspectRatio,
|
||||
near: camera.frustum.near,
|
||||
far: camera.frustum.far,
|
||||
frameIsIdentity: Cesium.Matrix4.equals(
|
||||
camera.transform,
|
||||
Cesium.Matrix4.IDENTITY,
|
||||
),
|
||||
};
|
||||
},
|
||||
};
|
||||
const cameraPart = createCesiumCamera({ scene, camera, report });
|
||||
const cameraPort = cameraPart.port;
|
||||
|
||||
// --- Query -----------------------------------------------------------------
|
||||
|
||||
@@ -1220,7 +1105,7 @@ export function createCesiumPorts(widget, { capabilities }) {
|
||||
// A listener that disposes the renderer stops the rest of its event.
|
||||
for (const list of Object.values(rendererListeners)) list.clear();
|
||||
for (const list of Object.values(frameListeners)) list.clear();
|
||||
cameraEvents.clear();
|
||||
cameraPart.dispose();
|
||||
for (const done of [...pendingRenders]) done();
|
||||
// Late model loads find no host and destroy themselves.
|
||||
for (const record of sets.values()) record.host = null;
|
||||
|
||||
@@ -8,7 +8,6 @@
|
||||
"src/app/embed.js",
|
||||
"src/app/scene.js",
|
||||
"src/app/viewer.js",
|
||||
"src/camera.js",
|
||||
"src/cameraGroundGuard.js",
|
||||
"src/cameraVerbs.js",
|
||||
"src/celestialRing.js",
|
||||
@@ -218,7 +217,6 @@
|
||||
"src/scenes/director.js",
|
||||
"src/services/groundSnap.js",
|
||||
"src/services/meshFloorSampler.js",
|
||||
"src/sharelink.js",
|
||||
"src/sky/starrySky.js",
|
||||
"src/ui/applicationShell.js",
|
||||
"src/ui/cameraOrientationControls.js",
|
||||
|
||||
@@ -27,3 +27,15 @@ export function bindRenderer(host, renderer) {
|
||||
* @returns {object|null} The renderer bound to `host`, or null.
|
||||
*/
|
||||
export const rendererOf = (host) => (host && renderers.get(host)) || null;
|
||||
|
||||
/**
|
||||
* The camera port of the renderer bound to `host`.
|
||||
* @param {object} host
|
||||
* @returns {import('./contract/camera').CameraPort}
|
||||
* @throws When no renderer is bound to `host`.
|
||||
*/
|
||||
export function cameraOf(host) {
|
||||
const camera = rendererOf(host)?.camera;
|
||||
if (!camera) throw new Error('This scene has no renderer camera');
|
||||
return camera;
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
import assert from 'node:assert/strict';
|
||||
import test from 'node:test';
|
||||
import { bindRenderer, rendererOf } from './rendererOf.js';
|
||||
import { bindRenderer, cameraOf, rendererOf } from './rendererOf.js';
|
||||
|
||||
test('a scene finds its renderer until it is unbound', () => {
|
||||
const scene = {};
|
||||
@@ -23,3 +23,12 @@ test('a stale unbind leaves a later binding alone', () => {
|
||||
unbindFirst();
|
||||
assert.equal(rendererOf(scene), second);
|
||||
});
|
||||
|
||||
test('cameraOf names the missing renderer instead of returning nothing', () => {
|
||||
const scene = {};
|
||||
assert.throws(() => cameraOf(scene), /no renderer camera/);
|
||||
const camera = { pose() {} };
|
||||
const unbind = bindRenderer(scene, { camera });
|
||||
assert.equal(cameraOf(scene), camera);
|
||||
unbind();
|
||||
});
|
||||
Reference in new issue
Block a user