Add pointer-driven camera scripts with Cesium goldens, and count wheel lines as Cesium does

Five new camera conformance scripts move the camera by user input: a
left drag that coasts, thirty pixel-mode and thirty line-mode wheel
notches from 5 km, a middle-drag tilt, and Shift and Ctrl drags held too
long to coast. The runner turns input steps into pointer events for a
driver: a move starts where the pointer last pressed or moved and carries
the held button. The golden recorder now drives Cesium's own screen-space
camera controller on a stand-in canvas, with Date on the virtual clock so
inertia is deterministic. The existing goldens are unchanged.

A harness that answers pointer input sets cameraInput and a pointer hook.
Harnesses without it, such as the stub, skip the input scripts.

The input port reported a line-mode wheel at 33 1/3 pixels a line. It now
counts lines as the reference does, 40 pixels a line and 3 lines a page,
so a pixel or line wheel converts back to the same pixels.
This commit is contained in:
Sameh Khamis committed 2026-11-08 20:08:56 -08:00
1 parent ef616b7905
commit 90499762f5
16 files changed
+1055 -38

No files matched your search

+129 -7
View File
@@ -10,11 +10,20 @@
* Cesium has one `changed` threshold per camera, where the contract has one
* per listener, so a script that listens at several thresholds is run once
* per threshold and each count is taken from its own run.
*
* A script with `input` steps runs a real `ScreenSpaceCameraController`
* over a stand-in canvas: its pointer and wheel events go to the
* controller's own event handler as the DOM would give them (mouse events,
* Cesium's choice where there are no pointer events), and the controller
* updates each frame where Cesium's scene updates it, after the tweens.
* `Date`, which the controller's inertia reads, runs on the virtual clock
* too.
*/
import * as Cesium from 'cesium';
import {
CAMERA_SCRIPTS,
SCRIPT_VIEWPORT,
usesInput,
} from '../conformance/cameraScripts.js';
import { runCameraScript } from '../conformance/cameraRunner.js';
import { updateCameraChanged } from './internals.js';
@@ -36,23 +45,79 @@ const EASINGS = {
/** One frame of the virtual clock, ms. */
export const FRAME_MS = 1000 / 60;
/** Run `fn` with `performance.now()` reading the virtual clock. */
/** The epoch `Date` reads at virtual time 0. */
const VIRTUAL_EPOCH_MS = Date.UTC(2026, 0, 1);
/** Run `fn` with `performance.now()` and `Date` reading the virtual clock. */
export async function withVirtualClock(fn) {
const real = Object.getOwnPropertyDescriptor(globalThis, 'performance');
const RealDate = globalThis.Date;
const clock = { now: 0 };
Object.defineProperty(globalThis, 'performance', {
configurable: true,
value: { now: () => clock.now, mark() {}, measure() {} },
});
// A function, not a subclass: `Date()` called plainly still gives a
// string, and dates made before stay `instanceof Date`.
function VirtualDate(...args) {
if (!new.target)
return new RealDate(VIRTUAL_EPOCH_MS + clock.now).toString();
return args.length
? new RealDate(...args)
: new RealDate(VIRTUAL_EPOCH_MS + clock.now);
}
Object.setPrototypeOf(VirtualDate, RealDate);
VirtualDate.prototype = RealDate.prototype;
VirtualDate.now = () => VIRTUAL_EPOCH_MS + clock.now;
globalThis.Date = VirtualDate;
try {
return await fn(clock);
} finally {
globalThis.Date = RealDate;
if (real) Object.defineProperty(globalThis, 'performance', real);
}
}
/** A Cesium camera on a scene with no globe, sized as the scripts' viewport. */
export function headlessCamera() {
/**
* A canvas for a controller's event handler: it keeps the listeners the
* handler adds, and `dispatch` calls them as the DOM would. Its root
* events stay on it (`disableRootEvents`), as there is no document; the
* handler still compares its element with one, so a `document` stands in
* while an event is handled, where there is none.
*/
function standInCanvas() {
const listeners = new Map();
return {
clientWidth: SCRIPT_VIEWPORT.width,
clientHeight: SCRIPT_VIEWPORT.height,
disableRootEvents: true,
onwheel: null,
getBoundingClientRect: () => ({ left: 0, top: 0 }),
addEventListener(type, fn) {
if (!listeners.has(type)) listeners.set(type, new Set());
listeners.get(type).add(fn);
},
removeEventListener(type, fn) {
listeners.get(type)?.delete(fn);
},
dispatch(type, event) {
const own = typeof globalThis.document === 'undefined';
if (own) globalThis.document = {};
try {
for (const fn of [...(listeners.get(type) ?? [])]) fn(event);
} finally {
if (own) delete globalThis.document;
}
},
};
}
/**
* A Cesium camera on a scene with no globe, sized as the scripts' viewport.
* With `input`, the scene has a real controller over a stand-in canvas.
* @param {{input?: boolean}} [options]
*/
export function headlessCamera({ input = false } = {}) {
const scene = {
canvas: {
clientWidth: SCRIPT_VIEWPORT.width,
@@ -75,9 +140,58 @@ export function headlessCamera() {
const camera = new Cesium.Camera(scene);
scene.camera = camera;
camera.frustum.aspectRatio = SCRIPT_VIEWPORT.width / SCRIPT_VIEWPORT.height;
if (input) {
scene.canvas = standInCanvas();
// What the controller's update reads off a real scene.
scene.verticalExaggeration = 1;
scene.verticalExaggerationRelativeHeight = 0;
scene.screenSpaceCameraController = new Cesium.ScreenSpaceCameraController(
scene,
);
}
return { scene, camera };
}
/**
* Send a script pointer event (`ScriptPointer`, `cameraRunner.js`) to a
* scene made by `headlessCamera({ input: true })`, as the DOM mouse or
* wheel event Cesium reads.
*/
export function dispatchPointer(scene, ev) {
scene.canvas.dispatch(DOM_TYPES[ev.type], domEvent(ev));
}
function domEvent(ev) {
const at = ev.endPosition ?? ev.position;
return {
button: ev.button,
clientX: at.x,
clientY: at.y,
shiftKey: ev.modifiers.shift,
ctrlKey: ev.modifiers.ctrl,
altKey: ev.modifiers.alt,
metaKey: ev.modifiers.meta,
...(ev.wheel
? {
deltaX: 0,
deltaY: ev.wheel.deltaY,
deltaMode: ev.wheel.deltaMode,
DOM_DELTA_PIXEL: 0,
DOM_DELTA_LINE: 1,
DOM_DELTA_PAGE: 2,
}
: {}),
preventDefault() {},
};
}
const DOM_TYPES = {
down: 'mousedown',
move: 'mousemove',
up: 'mouseup',
wheel: 'wheel',
};
const cart = (p) => new Cesium.Cartesian3(p.x, p.y, p.z);
const toEcef = (p) =>
'lon' in p
@@ -101,8 +215,9 @@ function orientationOf(orientation) {
}
/** A driver for {@link runCameraScript} over a headless Cesium camera. */
function cesiumDriver(clock, threshold) {
const { scene, camera } = headlessCamera();
function cesiumDriver(clock, threshold, input = false) {
const { scene, camera } = headlessCamera({ input });
const controller = input ? scene.screenSpaceCameraController : null;
let flying = false;
let changedCount = 0;
camera.percentageChanged = threshold ?? 0.5;
@@ -223,8 +338,14 @@ function cesiumDriver(clock, threshold) {
frame() {
clock.now += FRAME_MS;
scene.tweens.update();
controller?.update();
updateCameraChanged(camera);
},
...(input
? {
pointer: (ev) => dispatchPointer(scene, ev),
}
: {}),
listen: () => () => changedCount,
pose() {
const c = camera.positionCartographic;
@@ -295,14 +416,15 @@ async function recordScript(script) {
const thresholds = script.steps
.filter((step) => step.do === 'listen')
.map((step) => step.threshold);
const input = usesInput(script);
const base = await withVirtualClock((clock) =>
runCameraScript(cesiumDriver(clock, undefined), script),
runCameraScript(cesiumDriver(clock, undefined, input), script),
);
if (!thresholds.length) return base;
const counts = [];
for (const threshold of thresholds) {
const run = await withVirtualClock((clock) =>
runCameraScript(cesiumDriver(clock, threshold), script),
runCameraScript(cesiumDriver(clock, threshold, input), script),
);
const changed = run.records.find((r) => r.kind === 'changed');
counts.push({ threshold, count: changed.value[0].count });
+58 -10
View File
@@ -11,8 +11,14 @@ import {
CAMERA_SCRIPTS,
DEFAULT_TOLERANCE,
runConformance,
usesInput,
} from '../conformance/index.js';
import { FRAME_MS, headlessCamera, withVirtualClock } from './cameraGoldens.js';
import {
FRAME_MS,
dispatchPointer,
headlessCamera,
withVirtualClock,
} from './cameraGoldens.js';
import { createCesiumCamera } from './camera.js';
import { createCesiumPorts } from './ports.js';
import { cameraOf } from '../rendererOf.js';
@@ -27,14 +33,20 @@ const QUERY_RECORDS = new Set([
/** Commands and records the port does not have yet. */
const MISSING = new Set([]);
const runnable = CAMERA_SCRIPTS.filter((script) =>
script.steps.every(
(step) =>
!MISSING.has(step.do) &&
!MISSING.has(step.record) &&
!QUERY_RECORDS.has(step.record),
),
const runnable = CAMERA_SCRIPTS.filter(
(script) =>
!usesInput(script) &&
script.steps.every(
(step) =>
!MISSING.has(step.do) &&
!MISSING.has(step.record) &&
!QUERY_RECORDS.has(step.record),
),
).map((script) => `camera.trace.${script.name}`);
/** The scripts that drive the camera by pointer and wheel. */
const INPUT_CHECKS = new Set(
CAMERA_SCRIPTS.filter(usesInput).map((s) => `camera.trace.${s.name}`),
);
const CHECKS = new Set([
...runnable,
@@ -42,11 +54,11 @@ const CHECKS = new Set([
'camera.controls.settings',
]);
function headlessHarness(clock) {
function headlessHarness(clock, { input = false } = {}) {
return {
name: 'cesium (headless camera)',
async create() {
const { scene } = headlessCamera();
const { scene } = headlessCamera({ input });
for (const name of ['preUpdate', 'postUpdate', 'preRender', 'postRender'])
scene[name] = new Cesium.Event();
scene.primitives = { add() {}, remove() {} };
@@ -65,10 +77,30 @@ function headlessHarness(clock) {
frameScene() {
clock.now += FRAME_MS;
scene.tweens.update();
if (input) scene.screenSpaceCameraController.update();
scene.postUpdate.raiseEvent(scene);
},
scene,
};
},
...(input
? {
cameraInput: true,
// The contract's event back as the DOM's, a wheel in lines: at 40
// px a line, Cesium reads the pixels the script scrolled.
pointer: (r, type, x, y, extra) =>
dispatchPointer(r.scene, {
type,
position: { x, y },
endPosition: extra.endPosition,
button: extra.button ?? 0,
modifiers: extra.modifiers,
...(type === 'wheel'
? { wheel: { deltaY: extra.delta, deltaMode: 1 } }
: {}),
}),
}
: {}),
frame: async (r) => r.frameScene(),
now: () => clock.now,
toEcef: (p) => {
@@ -96,6 +128,22 @@ test('the camera port retraces the reference flights, views and frames', async (
assert.equal(report.passed, CHECKS.size);
});
test('Cesium’s own controls under the camera port retrace the drags and wheels, each wheel sent back in the input port’s lines', async () => {
assert.ok(INPUT_CHECKS.size >= 4, `only ${INPUT_CHECKS.size} input scripts`);
const report = await withVirtualClock((clock) =>
runConformance(headlessHarness(clock, { input: true }), {
only: (id) => INPUT_CHECKS.has(id),
}),
);
assert.deepEqual(
report.results
.filter((r) => r.status !== 'pass')
.map((r) => `${r.id}: ${r.status} ${r.detail}`),
[],
);
assert.equal(report.passed, INPUT_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();
+3 -9
View File
@@ -26,6 +26,7 @@ import * as Cesium from 'cesium';
import { createInputRouter } from '../input/router.js';
import { acquireCameraInput } from './cameraInput.js';
import { installTrackpadPinchZoom } from './ctrlWheelZoom.js';
import { wheelLines } from '../input/wheel.js';
const T = Cesium.ScreenSpaceEventType;
const MODIFIERS = [
@@ -52,8 +53,6 @@ const DOM_EVENTS = [
'touchcancel',
'dblclick',
];
/** A wheel notch scrolls 100 px in Chrome, which it counts as three lines. */
const PX_PER_LINE = 100 / 3;
/** A drill is run at least this deep and sliced, so asks share one pass. */
const DRILL_DEPTH = 16;
const NO_MODIFIERS = Object.freeze({
@@ -440,16 +439,11 @@ export function createCesiumInput(
const onWheel = (event) => {
const rect = canvas.getBoundingClientRect?.() ?? { left: 0, top: 0 };
const lines =
event.deltaMode === 1
? event.deltaY
: event.deltaMode === 2
? (event.deltaY * (canvas.clientHeight || 0)) / PX_PER_LINE
: event.deltaY / PX_PER_LINE;
deliver(
'wheel',
{ x: event.clientX - rect.left, y: event.clientY - rect.top },
{ delta: lines },
// Lines as the reference counts them (`../input/wheel.js`).
{ delta: wheelLines(event) },
event,
);
};
+10 -2
View File
@@ -240,7 +240,7 @@ test('ctrlWheelZoom installs the zoom and takes it out again', () => {
assert.deepEqual(s.wheelZoom, ['on', 'off', 'on', 'off']);
});
test('wheel is in lines, where the pointer is over the canvas', () => {
test('wheel is in lines as the reference counts them, where the pointer is over the canvas', () => {
const s = setup();
const wheels = [];
s.port.on('wheel', (ev) =>
@@ -259,10 +259,18 @@ test('wheel is in lines, where the pointer is over the canvas', () => {
deltaY: -3,
deltaMode: 1,
});
s.canvas.dispatch('wheel', {
clientX: 10,
clientY: 20,
deltaY: 1,
deltaMode: 2,
});
assert.deepEqual(wheels[0][0], { x: 100, y: 200 });
assert.equal(wheels[0][1], 3);
// 40 px a line, 3 lines a page: Cesium's own 40 px a line and 120 a page.
assert.equal(wheels[0][1], 2.5);
assert.equal(wheels[0][2].ctrl, true);
assert.equal(wheels[1][1], -3);
assert.equal(wheels[2][1], 3);
});
test('a pinch is the scale since the last event, at its midpoint', () => {