Take the input dispatcher off Cesium: pointer input from the renderer's input port, picks from the query port

The dispatcher now builds on renderer.input and the query port, with
positions as plain {x, y}. Its viewer access count is zero and it leaves
the Cesium allow-list. Layers that read the raw engine pick read the Hit,
drawHit or event.native instead, and pickRegistry's resolvePickId and
pickContact take a Hit, with the raw versions kept in the Cesium adapter.

rendererOf gains findInput, provideUnboundInput and provideNativeClick.
event.native carries the engine's pick, drill and pickWindow, and picks
through the follow helper happen inside it. An unbound input port
survives the viewer being bound until it is released.

The query port's pick memo is now per task rather than per frame,
because Cesium's own picks advance the frame number. A click on the sky
skips the depth pass when nothing is on the ray. Touch contact search
keeps its eight-deep drill in a 14x14 window.
This commit is contained in:
Sameh Khamis committed 2026-11-09 00:47:30 -08:00
1 parent 6eb9ceef46
commit 8bcaced6ad
52 files changed
+1836 -484

No files matched your search

+240 -157
View File
@@ -1,17 +1,18 @@
/**
* @module input/dispatcher
* @description The one place the application's layers and tools take
* pointer input over the globe: the scene's input port
* (src/render/cesium/input.js), a click picked once and handed to every
* subscriber, and the camera-input and stock-click holds tools take. Each
* layer family moves onto the renderer's own `input` port as it is ported;
* until then it subscribes here, with the events and shapes it always had.
* pointer input over the globe: the renderer's input port
* (src/render/contract/input.d.ts, `findInput`), a click picked once through
* the renderer's query port and handed to every subscriber, and the
* camera-input and stock-click holds tools take. Each layer family moves
* onto the renderer's own `input` port as it is ported; until then it
* subscribes here, with the events and shapes it always had.
*
* Layers used to bind a handler each and pick the same click again, so one
* click with the usual layers on cost about 25 `scene.pick` passes (each one
* redraws the scene for the pick buffer). Now the dispatcher picks lazily on
* first read and every subscriber reads the same {@link ClickEvent}; what a
* layer does with a click that is not its own stays the layer's decision.
* click with the usual layers on cost about 25 picks (each one redraws the
* scene for the pick buffer). Now the dispatcher picks lazily on first read
* and every subscriber reads the same {@link ClickEvent}; what a layer does
* with a click that is not its own stays the layer's decision.
*
* Who gets the pointer:
* - Ambient subscribers ({@link InputDispatcher.onClick}, and `onPointer`
@@ -25,26 +26,33 @@
* free still ends (and gives its camera hold back).
* - Tool subscribers pass their lease and run only while it is current.
*
* Camera input is suspended by the scene's counted holds
* (src/render/cesium/cameraInput.js), which own the controller's
* `enableInputs`, so a camera flight that ends cannot re-enable input under
* a drag or the cockpit.
* Camera input is suspended through the input port's counted holds
* (`suspendCameraControls`), so a camera flight that ends cannot re-enable
* input under a drag or the cockpit.
*
* A dispatcher is made per scene on first use ({@link inputFor}) and lives
* until {@link InputDispatcher.destroy}; the application scene owns it.
* Positions are plain `{x, y}` CSS pixels. What the renderer's picks cannot
* name, something still drawn outside the draw port, comes from the
* renderer adapter's own picks of the click (`nativeClickOf`), which also
* hangs them on the click as `native` for code still bound to them.
*
* A dispatcher is made per scene object on first use ({@link inputFor}) and
* lives until {@link InputDispatcher.destroy}; the application scene owns
* it.
*/
import { pickThroughFollowHelper } from '../render/cesium/follow.js';
import * as Cesium from 'cesium';
import { isLeaseCurrent, isPointerFree } from '../data/inputOwnership.js';
import { acquireCameraInput } from '../render/cesium/cameraInput.js';
import { cesiumInputOf, createCesiumInput } from '../render/cesium/input.js';
import { drawHitOf } from '../render/cesium/drawHit.js';
import {
findPickOwner,
pickContact,
resolvePickId,
} from '../data/pickRegistry.js';
import { isPickedWorldPosition, isSurfacePick } from '../data/scenePick.js';
import { isPickedWorldPosition } from '../data/scenePick.js';
import {
canvasOf,
findInput,
findQuery,
nativeClickOf,
releaseUnboundInput,
} from '../render/rendererOf.js';
import { sensorPickPosition } from './sensorPick.js';
// A tool takes the pointer with a lease before it subscribes with one.
@@ -60,29 +68,26 @@ export {
* The world position under a screen point: the rendered surface where the
* depth buffer has it, else the ellipsoid; null over the sky.
*
* @param {object} viewer A Cesium viewer.
* @param {object} viewer The scene object.
* @param {{x: number, y: number}} screenPosition
* @returns {{x: number, y: number, z: number}|null} A Cartesian3.
* @returns {{x: number, y: number, z: number}|null} ECEF metres.
*/
export function pickGroundPosition(viewer, screenPosition) {
const scene = viewer?.scene;
return groundAt(findQuery(viewer), screenPosition);
}
/** `pickGroundPosition` through a query port. */
function groundAt(query, { x, y }) {
if (!query) return null;
let position = null;
if (
scene?.pickPositionSupported &&
typeof scene.pickPosition === 'function'
) {
try {
position = scene.pickPosition(screenPosition);
} catch {
position = null;
}
try {
position = query.pickPosition(x, y);
} catch {
position = null;
}
if (
!isPickedWorldPosition(position) &&
typeof viewer?.camera?.pickEllipsoid === 'function'
) {
if (!isPickedWorldPosition(position)) {
try {
position = viewer.camera.pickEllipsoid(screenPosition);
position = query.pickEllipsoid(x, y);
} catch {
position = null;
}
@@ -90,13 +95,6 @@ export function pickGroundPosition(viewer, screenPosition) {
return isPickedWorldPosition(position) ? position : null;
}
/** The handler event types the scene's input port binds, for test doubles. */
export const HANDLER_EVENT_TYPES = Cesium.ScreenSpaceEventType;
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
const DRILL_DEPTH = 16;
const POINTER_TYPES = ['down', 'move', 'up', 'click', 'dblclick'];
/**
@@ -111,9 +109,24 @@ const unmodifiedLeft = (ev) => ev.button === 0 && unmodified(ev);
const leaseOf = (entry) =>
typeof entry.lease === 'function' ? entry.lease() : entry.lease;
/** @type {WeakMap<object, InputDispatcher>} scene -> dispatcher */
/** @type {WeakMap<object, InputDispatcher>} scene object -> dispatcher */
const dispatchers = new WeakMap();
const xy = (p) => ({ x: p.x, y: p.y });
/**
* A draw-set item's hit, or, from what the adapter's own pick found
* (`foreign`), a hit with no set for something drawn outside the draw port
* or the hit of a draw-set item the renderer's sets do not hold; null for
* the map itself or nothing.
*/
function topHitOf(hit, foreign) {
if (hit && !hit.surface) return hit;
const other = foreign();
if (!other) return null;
return other.set ? other : { set: '', id: other.id, surface: false };
}
/**
* @typedef {object} ClickGesture
* @property {number} travelPx Pointer travel during the press, summed per
@@ -121,34 +134,48 @@ const dispatchers = new WeakMap();
* @property {number} durationMs Press time.
*/
/**
* @typedef {import('../render/contract/query').Hit} Hit
*/
/**
* One left click, picked at most once per kind of query. Every getter and
* method is memoized, so subscribers share the passes.
* method is memoized, so subscribers share the passes. Hits are the
* contract's `Hit`; one with `set: ''` is something drawn outside the draw
* port, named by the renderer adapter (its id null when it has none).
* @typedef {object} ClickEvent
* @property {{x: number, y: number}} screenPosition Where the user clicked.
* @property {{x: number, y: number}} position Where that lands in the pick buffer
* (corrected for sensor styles; see sensorPick.js).
* @property {ClickGesture} gesture
* @property {object|undefined} pick `scene.pick` at `position`.
* @property {import('../render/contract/query').Hit|null} drawHit `pick` as
* the contract's `Hit`, when it is an item of a renderer draw set; null
* for anything else. What layers on the draw port read a click by.
* @property {object|undefined} hit `pick`, or on a coarse pointer the first
* registered contact under a surface pick (`pickContact`).
* @property {Hit|null} topHit What is on top under the click: a draw-set
* item, or something drawn outside the draw port; null for the map itself
* (the globe, tiles) or nothing.
* @property {Hit|null} drawHit `topHit` when it is an item of a renderer draw
* set; null for anything else. What layers on the draw port read a click
* by.
* @property {Hit|null} hit `topHit`, or on a coarse pointer the first
* registered contact under the map (`pickContact`).
* @property {string|null} id The hit's canonical pick id.
* @property {string|null} ownerId The layer that registered the hit.
* @property {object|undefined} meta The hit's own metadata, when its pick
* carries any (icon-set rows do).
* @property {boolean} surface Whether the hit is the map itself.
* @property {(width: number, height: number) => object|undefined} pickWindow
* `scene.pick` with a wider window.
* @property {(width: number, height: number) => {id: string|null, drawHit: import('../render/contract/query').Hit|null, surface: boolean}} windowHit
* `pickWindow` read as `id`, `drawHit` and `surface` are: for layers that
* pick wider than the click without reading the renderer's pick.
* @property {(limit?: number, width?: number, height?: number) => object[]} drill
* `scene.drillPick`, at most `limit` hits.
* @property {() => Cesium.Cartesian3|null} ground The world position under
* the click: rendered surface, else ellipsoid; null over the sky.
* @property {object|undefined} meta The hit's own metadata, when it has any.
* @property {boolean} surface Whether the hit is the map itself, or nothing.
* @property {(width: number, height: number) => {id: string|null, drawHit: Hit|null, surface: boolean}} windowHit
* A pick with a wider window, read as `id`, `drawHit` and `surface` are.
* @property {(limit?: number, width?: number, height?: number) => Hit[]} drill
* The draw-set items under the click, nearest first, at most `limit`
* (`query.drillPick`).
* @property {() => {x: number, y: number, z: number}|null} ground The world
* position under the click: rendered surface, else ellipsoid; null over
* the sky.
* @property {import('../render/rendererOf.js').NativeClick['native']|undefined} native
* The renderer adapter's own picks of the click (`pick`, `pickWindow`,
* `drill`), for code still bound to the engine's pick objects; undefined
* when the adapter has none.
* @property {unknown} pick `native.pick`, for code still bound to the
* engine's pick objects that reads it here.
* @property {(width: number, height: number) => unknown} pickWindow
* `native.pickWindow`, the same.
*/
/**
@@ -157,38 +184,41 @@ const dispatchers = new WeakMap();
* Ambient click subscription. Returns its unsubscribe.
* @property {(type: 'down'|'move'|'up'|'click'|'dblclick', fn: Function, options?: {lease?: object|(() => object|null)}) => () => void} onPointer
* Raw pointer subscription: `click` gets the {@link ClickEvent}, the others
* Cesium's event; `move`'s also carries `pickPosition`, its `endPosition`
* corrected for sensor styles as a click's `position` is. With a lease, runs only while that lease is current;
* `{position}` (`move`: `{startPosition, endPosition, pickPosition}`, its
* `pickPosition` its `endPosition` corrected for sensor styles as a
* click's `position` is). With a lease, runs only while that lease is current;
* without one, only while the pointer is free (`move` and `up` always run).
* @property {(reason: string) => () => void} suspendCamera Hold camera input
* off; returns this hold's release.
* @property {() => () => void} suppressStockClicks Take the viewer's stock
* select and double-click-track actions off; returns this hold's release.
* @property {() => () => void} suppressStockClicks Take the renderer's stock
* select and double-click follow off; returns this hold's release.
* @property {(name: 'select'|'dblclickFollow') => boolean} stockEnabled
* Whether the viewer's stock select or follow runs now: it does unless a
* hold is out (or the viewer has none).
* Whether the renderer's stock select or follow runs now: it does unless a
* hold is out (or the renderer has none).
* @property {() => number} subscriberCount Live click and pointer
* subscriptions, for leak checks.
* @property {() => void} destroy
*/
/**
* What is under canvas CSS pixel `x, y` now, as a click would see it (a hit
* on the follow's helper is a hit on its target), for a reader that is not
* handed a click (point-and-ask). Null when nothing is there or the pick
* fails.
* @param {object} viewer
* What is under canvas CSS pixel `x, y` now, as a click's `topHit` would
* see it (a hit on the follow's helper is a hit on its target), for a reader
* that is not handed a click (point-and-ask). Null when nothing but the map
* is there, or the pick fails.
* @param {object} viewer The scene object.
* @param {number} x
* @param {number} y
* @returns {object|null}
* @returns {Hit|null}
*/
export function pickAt(viewer, x, y) {
try {
if (!viewer || viewer.isDestroyed?.()) return null;
const scene = viewer.scene;
if (typeof scene?.pick !== 'function') return null;
return (
pickThroughFollowHelper(scene.pick(new Cesium.Cartesian2(x, y))) ?? null
const query = findQuery(viewer);
if (!query) return null;
const position = { x, y };
return topHitOf(
query.pick(x, y),
() => nativeClickOf(viewer, position)?.foreign() ?? null,
);
} catch {
return null;
@@ -196,40 +226,37 @@ export function pickAt(viewer, x, y) {
}
/**
* The scene's dispatcher, made on first use.
* @param {object} viewer A Cesium viewer (or a test double with `scene`).
* @param {{createHandler?: (canvas: object) => object, now?: () => number, document?: object|null}} [options]
* For the input port it makes when the scene has none (tests pass a fake
* handler); used only by the call that makes it.
* The scene object's dispatcher, made on first use.
* @param {object} viewer The scene object (a Cesium viewer, or a test
* double).
* @param {{createHandler?: (canvas: object) => object, now?: () => number,
* document?: object|null, query?: import('../render/contract/query').QueryPort}} [options]
* For a dispatcher over a viewer with no renderer bound: the input port's
* (`findInput`) when this call builds it, and the query port its clicks
* pick through (tests pass doubles). Used only by the call that makes the
* dispatcher.
* @returns {InputDispatcher}
*/
export function inputFor(viewer, options = {}) {
const scene = viewer.scene;
let dispatcher = dispatchers.get(scene);
let dispatcher = dispatchers.get(viewer);
if (!dispatcher) {
dispatcher = createDispatcher(viewer, options);
dispatchers.set(scene, dispatcher);
dispatchers.set(viewer, dispatcher);
}
return dispatcher;
}
function createDispatcher(viewer, { createHandler, now, document } = {}) {
const scene = viewer.scene;
// The renderer's port when the application made one; a viewer of the
// caller's own gets one for as long as this dispatcher lives.
const shared = cesiumInputOf(scene);
const cesiumInput =
shared ??
createCesiumInput(viewer, {
report: (error) => console.error('Pointer input failed', error),
// The viewer is its owner's: its stock actions stay on its handler.
takeStock: false,
...(createHandler ? { createHandler } : {}),
...(now ? { now } : {}),
...(document !== undefined ? { document } : {}),
});
const { port } = cesiumInput;
const cameraInput = acquireCameraInput(scene);
function createDispatcher(viewer, { query: givenQuery, ...portOptions } = {}) {
const port = findInput(viewer, portOptions);
if (!port)
throw new Error(
viewer?.isDestroyed?.()
? 'This scene has been destroyed'
: 'This scene has no renderer to take input with: bind one, or load ' +
"the Cesium adapter's factories (the ./render/cesium/unbound export) " +
'for a viewer with no renderer bound',
);
const queryOf = () => givenQuery ?? findQuery(viewer);
/** @type {Array<{fn: Function}>} */
const clickSubscribers = [];
/** @type {Record<string, Array<{fn: Function, lease: object|null}>>} */
@@ -237,6 +264,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
POINTER_TYPES.map((type) => [type, []]),
);
const stockHolds = new Set();
const cameraHolds = new Set();
let destroyed = false;
const run = (list, free, arg) => {
@@ -250,30 +278,29 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
}
};
const cartesian = (p) => new Cesium.Cartesian2(p.x, p.y);
// Each type is one port listener; the pointer's owner is read once per
// event, before any subscriber runs.
const offPort = [
port.on('down', (ev) => {
if (!unmodifiedLeft(ev)) return;
run(pointerSubscribers.down, isPointerFree(), {
position: cartesian(ev.position),
position: xy(ev.position),
});
}),
port.on('move', (ev) => {
if (!unmodified(ev)) return;
const endPosition = cartesian(ev.endPosition ?? ev.position);
const endPosition = xy(ev.endPosition ?? ev.position);
let pickPosition;
run(pointerSubscribers.move, true, {
startPosition: cartesian(ev.position),
startPosition: xy(ev.position),
endPosition,
// Where the pointer lands in the pick buffer, as a click's
// `position` is (corrected for sensor styles); made on first read.
get pickPosition() {
pickPosition ??= sensorPickPosition(
viewer.scene,
viewer,
endPosition,
viewer.scene.canvas,
canvasOf(viewer),
);
return pickPosition;
},
@@ -281,14 +308,15 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
}),
port.on('up', (ev) => {
if (!unmodifiedLeft(ev)) return;
run(pointerSubscribers.up, true, { position: cartesian(ev.position) });
run(pointerSubscribers.up, true, { position: xy(ev.position) });
}),
port.on('click', (ev) => {
if (!unmodifiedLeft(ev)) return;
const free = isPointerFree();
const event = createClickEvent(
viewer,
{ position: cartesian(ev.position) },
queryOf,
xy(ev.position),
ev.gesture ?? { travelPx: 0, durationMs: 0 },
);
run(pointerSubscribers.click, free, event);
@@ -297,7 +325,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
port.on('dblclick', (ev) => {
if (!unmodifiedLeft(ev)) return;
run(pointerSubscribers.dblclick, isPointerFree(), {
position: cartesian(ev.position),
position: xy(ev.position),
});
}),
];
@@ -311,7 +339,7 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
};
};
return {
const self = {
onClick(fn) {
return subscribe(clickSubscribers, { fn, lease: null });
},
@@ -324,13 +352,19 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
suspendCamera(reason) {
if (destroyed) return () => {};
return cameraInput.suspend(reason);
const release = port.suspendCameraControls(reason);
const hold = () => {
if (!cameraHolds.delete(hold)) return;
release();
};
cameraHolds.add(hold);
return hold;
},
suppressStockClicks() {
if (destroyed) return () => {};
// Cesium's own select and double-click-track never see the pointer
// lease; the port runs them, and holds them off here.
// The renderer's own select and double-click follow never see the
// pointer lease; the port runs them, and holds them off here.
const releases = [
port.behaviours.select.suppress(),
port.behaviours.dblclickFollow.suppress(),
@@ -355,51 +389,84 @@ function createDispatcher(viewer, { createHandler, now, document } = {}) {
destroy() {
if (destroyed) return;
destroyed = true;
dispatchers.delete(scene);
if (dispatchers.get(viewer) === self) dispatchers.delete(viewer);
clickSubscribers.length = 0;
for (const type of POINTER_TYPES) pointerSubscribers[type].length = 0;
for (const off of offPort) off();
for (const hold of [...stockHolds]) hold();
cameraInput.release();
if (!shared) cesiumInput.dispose();
for (const hold of [...cameraHolds]) hold();
// A port built for this viewer goes with its dispatcher; a
// renderer's own stays.
releaseUnboundInput(viewer, port);
},
};
return self;
}
/** A drill is run at least this deep and sliced, so callers asking for
* different depths on one click share one pass. */
const DRILL_DEPTH = 16;
/**
* @param {object} viewer
* @param {{position: {x: number, y: number}}} click
* @param {() => import('../render/contract/query').QueryPort|null} queryOf
* @param {{x: number, y: number}} at Where the click is, CSS pixels.
* @param {ClickGesture} gesture
* @returns {ClickEvent}
*/
function createClickEvent(viewer, click, gesture) {
const scene = viewer.scene;
const position = sensorPickPosition(scene, click.position, scene.canvas);
function createClickEvent(viewer, queryOf, at, gesture) {
const position = sensorPickPosition(viewer, at, canvasOf(viewer));
const { x, y } = position;
const memo = new Map();
const once = (key, compute) => {
if (!memo.has(key)) memo.set(key, compute());
return memo.get(key);
};
/** @type {Map<string, {limit: number, hits: object[]}>} */
const native = () => once('native', () => nativeClickOf(viewer, position));
const query = () => once('query', queryOf);
/** The renderer's pick, with a window or not; null without a query port. */
const pick = (window) => {
const q = query();
return q ? (q.pick(x, y, window) ?? null) : null;
};
/** @type {Map<string, {limit: number, hits: Hit[]}>} */
const drills = new Map();
return {
screenPosition: click.position,
screenPosition: at,
position,
gesture,
get pick() {
return once('pick', () => pickThroughFollowHelper(scene.pick(position)));
get topHit() {
return once('top', () => {
const hit = pick();
// The adapter's own pick of this click is the renderer's pass, held
// now: read later, it would be another, of a scene drawn since.
void native()?.native.pick;
return topHitOf(hit, () => native()?.foreign() ?? null);
});
},
get drawHit() {
return once('drawHit', () => drawHitOf(this.pick));
const hit = this.topHit;
return hit?.set ? hit : null;
},
get hit() {
return once('hit', () =>
pickContact(scene, position, {
picked: this.pick,
drill: (limit, width, height) => this.drill(limit, width, height),
}),
);
return once('hit', () => {
const q = query();
if (!q) return this.topHit;
return pickContact(q, position, {
picked: this.topHit,
// Everything drawn there, as the adapter sees it, so a contact
// search stops at what is drawn over a contact outside the draw
// port and finds a contact drawn there; the draw-set items alone
// without one.
drill: (limit, width, height) => {
const click = native();
return click
? click.drillHits(limit, width, height)
: this.drill(limit, width, height);
},
});
});
},
get id() {
return once('id', () => resolvePickId(this.hit));
@@ -408,47 +475,63 @@ function createClickEvent(viewer, click, gesture) {
return once('ownerId', () => findPickOwner(this.id));
},
get meta() {
const hit = this.hit;
return hit?.id?.meta ?? hit?.meta;
return this.hit?.meta;
},
get surface() {
return isSurfacePick(this.hit);
},
pickWindow(width, height) {
return once(`window:${width}x${height}`, () =>
pickThroughFollowHelper(scene.pick(position, width, height)),
);
return !this.hit;
},
windowHit(width, height) {
return once(`windowHit:${width}x${height}`, () => {
const picked = this.pickWindow(width, height);
const picked = pick({ width, height });
void native()?.native.pickWindow(width, height);
const hit = topHitOf(
picked,
() => native()?.foreign(width, height) ?? null,
);
return {
id: resolvePickId(picked),
drawHit: drawHitOf(picked),
surface: isSurfacePick(picked),
id: resolvePickId(hit),
drawHit: hit?.set ? hit : null,
surface: !hit,
};
});
},
drill(limit = DRILL_DEPTH, width, height) {
const key = `${width}x${height}`;
const done = drills.get(key);
// A pass that came back short already holds every hit there is.
if (done && (limit <= done.limit || done.hits.length < done.limit))
return done.hits.slice(0, limit);
if (typeof scene.drillPick !== 'function') return [];
// A deeper pass already made holds these. (One that came back short
// may not hold every hit: it drops what is not a draw-set item.)
if (done && limit <= done.limit) return done.hits.slice(0, limit);
const q = query();
if (!q) return [];
// Only the default window is shared between layers; round that one up.
const depth =
width === undefined && height === undefined
? Math.max(limit, DRILL_DEPTH)
: limit;
const hits = (scene.drillPick(position, depth, width, height) || [])
.map(pickThroughFollowHelper)
.filter(Boolean);
const hits = q.drillPick(x, y, {
...(width === undefined ? {} : { width }),
...(height === undefined ? {} : { height }),
limit: depth,
});
drills.set(key, { limit: depth, hits });
return hits.slice(0, limit);
},
ground() {
return once('ground', () => pickGroundPosition(viewer, position));
return once('ground', () => groundAt(query(), position));
},
get native() {
// After the renderer's pick, whose pass the adapter's reuses.
void this.topHit;
return native()?.native;
},
get pick() {
// After the renderer's pick, whose pass the adapter's reuses.
void this.topHit;
return native()?.native.pick;
},
pickWindow(width, height) {
void this.windowHit(width, height);
return native()?.native.pickWindow(width, height);
},
};
}
+227 -10
View File
@@ -1,7 +1,8 @@
import { test } from 'node:test';
import assert from 'node:assert/strict';
import { inputFor } from './dispatcher.js';
import { inputFor, pickAt } from './dispatcher.js';
import { bindRenderer } from '../render/rendererOf.js';
import {
FAKE_EVENT_TYPES,
FakeScreenSpaceEventHandler as FakeHandler,
@@ -26,6 +27,7 @@ function harness({ pick = () => undefined, drillPick = () => [] } = {}) {
stock.setInputAction(stockDouble, TYPES.LEFT_DOUBLE_CLICK);
let clock = 0;
const viewer = {
isDestroyed: () => false,
screenSpaceEventHandler: stock,
camera: { pickEllipsoid: () => null },
scene: {
@@ -331,7 +333,9 @@ test('stock clicks come back by identity after the last hold', (t) => {
});
test('drills of different depths on one click share a pass', (t) => {
const hits = Array.from({ length: 20 }, (_, i) => ({ id: `hit-${i}` }));
const hits = Array.from({ length: 20 }, (_, i) => ({
id: { set: 'test:1', id: `hit-${i}` },
}));
const h = harness({ drillPick: (_p, limit) => hits.slice(0, limit) });
t.after(() => h.input.destroy());
const lengths = [];
@@ -343,7 +347,7 @@ test('drills of different depths on one click share a pass', (t) => {
assert.equal(h.calls.drillPick, 1);
});
test('a touch tap’s contact search is the click’s own drill', (t) => {
function coarsePointer(t) {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');
Object.defineProperty(globalThis, 'matchMedia', {
configurable: true,
@@ -353,26 +357,72 @@ test('a touch tap’s contact search is the click’s own drill', (t) => {
if (previous) Object.defineProperty(globalThis, 'matchMedia', previous);
else delete globalThis.matchMedia;
});
}
test('a touch tap finds the contact under the map, in one drill of its own', (t) => {
coarsePointer(t);
registerPickOwner('test-owner', (id) => id === 'plane-1');
t.after(() => unregisterPickOwner('test-owner'));
const tile = { primitive: { isCesium3DTileset: true } };
const h = harness({ pick: () => tile, drillPick: () => [{ id: 'plane-1' }] });
const drills = [];
const h = harness({
pick: () => tile,
drillPick: (_p, limit, width, height) => {
drills.push([limit, width, height]);
return [tile, { id: { set: 'test:1', id: 'plane-1' } }];
},
});
t.after(() => h.input.destroy());
const seen = [];
h.input.onClick((event) => seen.push(event.id, event.drawHit));
h.click();
assert.deepEqual(seen, ['plane-1', null]);
assert.deepEqual(drills, [[8, 14, 14]], 'eight deep, as before');
});
test('a touch tap finds a contact drawn outside the draw port', (t) => {
coarsePointer(t);
registerPickOwner('test-owner', (id) => id === 'bus-1');
t.after(() => unregisterPickOwner('test-owner'));
const h = harness({
pick: () => undefined,
drillPick: () => [{ primitive: { id: 'bus-1' } }],
});
t.after(() => h.input.destroy());
const seen = [];
h.input.onClick((event) => seen.push(event.id, event.ownerId));
h.click();
assert.deepEqual(seen, ['bus-1', 'test-owner']);
});
test('a touch tap stops at something drawn outside the draw port over a contact', (t) => {
coarsePointer(t);
registerPickOwner('test-owner', (id) => id === 'plane-1');
t.after(() => unregisterPickOwner('test-owner'));
const h = harness({
pick: () => undefined,
drillPick: () => [
{ primitive: { id: 'unowned' } },
{ id: { set: 'test:1', id: 'plane-1' } },
],
});
t.after(() => h.input.destroy());
const seen = [];
h.input.onClick((event) => seen.push(event.id));
h.input.onClick((event) => seen.push(event.drill(8, 14, 14).length));
h.click();
assert.deepEqual(seen, ['plane-1', 1]);
assert.equal(h.calls.drillPick, 1);
assert.deepEqual(seen, [null], 'the map under the tap, as before');
});
test('a short drill answers deeper asks without another pass', (t) => {
const h = harness({ drillPick: () => [{ id: 'only' }] });
test('a deeper ask than a short drill looks again: it held draw-set items only', (t) => {
const h = harness({
drillPick: () => [{ id: { set: 'test:1', id: 'only' } }],
});
t.after(() => h.input.destroy());
h.input.onClick((event) => event.drill(8));
h.input.onClick((event) => event.drill(12));
h.input.onClick((event) => event.drill(40));
h.click();
assert.equal(h.calls.drillPick, 1);
assert.equal(h.calls.drillPick, 2, '16 deep, then 40');
});
test('one failing subscriber does not stop the rest', (t) => {
@@ -456,3 +506,170 @@ test('the dispatcher is the package input export', async () => {
const exported = await import('gods-eye-view/input');
assert.equal(exported.inputFor, inputFor);
});
test('something drawn outside the draw port is the top hit, with no set, and never a draw hit', (t) => {
registerPickOwner('test-owner', (id) => id === 'bus-1');
t.after(() => unregisterPickOwner('test-owner'));
let picked = { primitive: { id: 'bus-1' } };
const h = harness({ pick: () => picked });
t.after(() => h.input.destroy());
const seen = [];
h.input.onClick((event) =>
seen.push({
top: event.topHit,
draw: event.drawHit,
id: event.id,
owner: event.ownerId,
surface: event.surface,
native: event.native.pick,
}),
);
h.click();
assert.equal(h.calls.pick, 1, "the adapter's own pick reuses the renderer's");
assert.deepEqual(seen[0].top, { set: '', id: 'bus-1', surface: false });
assert.equal(seen[0].draw, null);
assert.equal(seen[0].id, 'bus-1');
assert.equal(seen[0].owner, 'test-owner');
assert.equal(seen[0].surface, false);
assert.equal(
seen[0].native,
picked,
"the engine's own pick, for code bound to it",
);
picked = { primitive: { isCesium3DTileset: true } };
h.click();
assert.equal(seen[1].top, null, 'tiles are the map');
assert.equal(seen[1].surface, true);
assert.equal(seen[1].id, null);
});
test('pick and pickWindow still hand over the engine pick objects, one pass each', (t) => {
const picked = { primitive: { id: 'bus-1' } };
const h = harness({ pick: () => picked });
t.after(() => h.input.destroy());
const seen = [];
h.input.onClick((event) =>
seen.push({
pick: event.pick,
window: event.pickWindow(9, 9),
windowId: event.windowHit(9, 9).id,
}),
);
h.click();
assert.equal(seen[0].pick, picked);
assert.equal(seen[0].window, picked);
assert.equal(seen[0].windowId, 'bus-1');
assert.equal(h.calls.pick, 2, 'one pass at 3x3 and one at 9x9');
});
test("a draw-set item the renderer's sets do not hold is still the click's draw hit", (t) => {
const picked = { id: { set: 'kept:1', id: 'a', meta: { k: 1 } } };
const h = harness({ pick: () => picked });
t.after(() => h.input.destroy());
// The renderer's pick names nothing there: its sets do not hold `kept:1`.
t.after(bindRenderer(h.viewer, { query: { pick: () => null } }));
const seen = [];
h.input.onClick((event) => seen.push(event.drawHit?.id, event.meta?.k));
h.click();
assert.deepEqual(seen, ['a', 1]);
});
test("a click's engine pick is the renderer's pass, even when read later", async (t) => {
let picked = { primitive: { id: 'bus-1' } };
const h = harness({ pick: () => picked });
t.after(() => h.input.destroy());
const events = [];
h.input.onClick((event) => events.push(event) && event.topHit);
h.click();
picked = { primitive: { id: 'bus-2' } };
await new Promise((resolve) => setTimeout(resolve, 0));
assert.equal(events[0].topHit.id, 'bus-1');
assert.equal(events[0].pick.primitive.id, 'bus-1');
assert.equal(events[0].native.pick.primitive.id, 'bus-1');
assert.equal(h.calls.pick, 1);
});
test('positions are plain CSS pixels', (t) => {
const h = harness();
t.after(() => h.input.destroy());
const seen = [];
h.input.onPointer('down', (event) => seen.push(event.position));
h.input.onPointer('move', (event) => seen.push(event.endPosition));
h.input.onClick((event) => seen.push(event.screenPosition, event.position));
h.handler.fire(TYPES.MOUSE_MOVE, { endPosition: { x: 3, y: 4 } });
h.click(5, 6);
for (const position of seen) {
assert.equal(Object.getPrototypeOf(position), Object.prototype);
assert.deepEqual(Object.keys(position), ['x', 'y']);
}
assert.deepEqual(seen.at(-1), { x: 5, y: 6 });
});
test("a viewer's renderer gives the dispatcher its input and query ports", (t) => {
const listeners = new Map();
const holds = [];
const port = {
on(type, cb) {
listeners.set(type, cb);
return () => listeners.delete(type);
},
suspendCameraControls(reason) {
holds.push(reason);
return () => holds.splice(holds.indexOf(reason), 1);
},
behaviours: {
select: { enabled: true, suppress: () => () => {} },
dblclickFollow: { enabled: false, suppress: () => () => {} },
},
};
const hit = { set: 'quakes:1', id: 'quake:a', surface: false };
const asked = [];
const query = {
pick: (x, y, window) => (asked.push(['pick', x, y, window]), hit),
drillPick: () => [],
pickPosition: () => ({ x: 6378137, y: 0, z: 0 }),
pickEllipsoid: () => null,
};
const viewer = {};
const unbind = bindRenderer(viewer, { input: port, query });
t.after(unbind);
const input = inputFor(viewer);
t.after(() => input.destroy());
assert.equal(input.stockEnabled('select'), true);
assert.equal(input.stockEnabled('dblclickFollow'), false);
input.suspendCamera('drag');
assert.deepEqual(holds, ['drag']);
const seen = [];
input.onClick((event) => seen.push([event.drawHit, event.ground()]));
listeners.get('click')({
type: 'click',
position: { x: 7, y: 8 },
button: 0,
modifiers: { shift: false, ctrl: false, alt: false, meta: false },
});
assert.equal(seen[0][0], hit);
assert.deepEqual(seen[0][1], { x: 6378137, y: 0, z: 0 });
assert.deepEqual(asked, [['pick', 7, 8, undefined]]);
assert.equal(pickAt(viewer, 1, 2), hit, 'point-and-ask picks the same way');
input.destroy();
assert.deepEqual(holds, [], "destroy gives back the dispatcher's holds");
assert.equal(listeners.size, 0);
});
test('a viewer with no renderer and no adapter factory cannot take input', () => {
// The adapter's factory builds over anything with a scene: this has none.
assert.throws(() => inputFor({}), /no renderer to take input with/);
});
test('point-and-ask: nothing but the map is no hit; a failing pick is none', (t) => {
const surface = { set: '', id: '', surface: true };
const viewer = {};
let pick = () => surface;
t.after(bindRenderer(viewer, { query: { pick: (...a) => pick(...a) } }));
assert.equal(pickAt(viewer, 0, 0), null);
pick = () => {
throw new Error('context lost');
};
assert.equal(pickAt(viewer, 0, 0), null);
assert.equal(pickAt(null, 0, 0), null);
});
+5 -4
View File
@@ -12,17 +12,18 @@ const SENSOR_STYLES = ['thermal', 'surveillance'];
/**
* The pick-buffer position for a screen click.
* @param {object} scene The scene object the styles are recorded on.
* @param {object} host The scene object the styles are recorded on (the
* viewer the application's visual effects are made for).
* @param {{x: number, y: number}} position CSS pixels on the canvas.
* @param {{width: number, height: number, clientWidth: number,
* clientHeight: number}} canvas The canvas the scene draws in.
* @returns {{x: number, y: number}} A new position; the click's own is left
* alone.
*/
export function sensorPickPosition(scene, position, canvas) {
export function sensorPickPosition(host, position, canvas) {
const out = { x: position.x, y: position.y };
const stages = styleStagesOf(scene);
if (!stages) return out;
const stages = styleStagesOf(host);
if (!stages || !canvas) return out;
for (const style of SENSOR_STYLES) {
const stage = stages[style];
if (!stage?.enabled) continue;
+69 -3
View File
@@ -1,12 +1,71 @@
/**
* Test doubles for the input dispatcher: a stand-in for Cesium's
* `ScreenSpaceEventHandler`, and a dispatcher made on it ahead of the code
* under test, so that code's `inputFor(viewer)` gets the fake.
* under test, so that code's `inputFor(viewer)` gets the fake. Imported by
* tests only.
*
* The dispatcher's input port is the Cesium adapter's (`findInput`, over the
* fake handler), and its clicks pick through {@link sceneQuery}: the
* viewer's renderer's query port where it has one that picks, else the
* viewer double's own `scene.pick` and `drillPick`, read as the renderer's
* picks are.
*/
import { HANDLER_EVENT_TYPES, inputFor } from './dispatcher.js';
import * as Cesium from 'cesium';
// The adapter's unbound input port and a click's own Cesium picks.
import '../render/cesium/input.js';
import '../render/cesium/nativeClick.js';
import { rendererOf } from '../render/rendererOf.js';
import { fakeScenePicks } from '../testSupport/fakeCesiumScene.mjs';
import { provideStyleStageAlias } from '../styles/styleStages.js';
import { inputFor } from './dispatcher.js';
/** Cesium's own event types, the ones the input port binds. */
export const FAKE_EVENT_TYPES = HANDLER_EVENT_TYPES;
export const FAKE_EVENT_TYPES = Cesium.ScreenSpaceEventType;
// Tests record sensor styles on the viewer double's scene, as the code under
// them once did: the dispatcher, which looks them up by the viewer, finds
// them there too.
provideStyleStageAlias((viewer) => viewer?.scene ?? null);
/**
* A query port for a viewer double's clicks: its renderer's, where that
* picks; else one over the double's scene (`fakeScenePicks`), with its depth
* and ellipsoid picks.
* @param {object} viewer
*/
export function sceneQuery(viewer) {
const bound = () => {
const query = rendererOf(viewer)?.query;
return typeof query?.pick === 'function' ? query : null;
};
const at = (x, y) => new Cesium.Cartesian2(x, y);
const own = {
...fakeScenePicks(viewer),
pickPosition(x, y) {
const scene = viewer.scene;
if (
!scene?.pickPositionSupported ||
typeof scene.pickPosition !== 'function'
)
return null;
return scene.pickPosition(at(x, y)) ?? null;
},
pickEllipsoid(x, y) {
const camera = viewer.camera ?? viewer.scene?.camera;
return camera?.pickEllipsoid?.(at(x, y)) ?? null;
},
};
return new Proxy(own, {
get(target, key) {
const query = bound();
if (query) {
const value = query[key];
return typeof value === 'function' ? value.bind(query) : value;
}
return target[key];
},
});
}
export class FakeScreenSpaceEventHandler {
constructor() {
@@ -45,9 +104,16 @@ export class FakeScreenSpaceEventHandler {
*/
export function fakeInput(viewer, { now } = {}) {
const handler = new FakeScreenSpaceEventHandler();
// A Cesium viewer's canvas is its scene's.
if (!('canvas' in viewer))
Object.defineProperty(viewer, 'canvas', {
configurable: true,
get: () => viewer.scene?.canvas,
});
const input = inputFor(viewer, {
createHandler: () => handler,
document: null,
query: sceneQuery(viewer),
...(now ? { now } : {}),
});
const T = FAKE_EVENT_TYPES;