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

+4 -2
View File
@@ -12,11 +12,13 @@ import { cameraFlightActive } from './internals.js';
import { createCesiumFollow } from './follow.js';
import { createCesiumControls } from './cameraControls.js';
import { cameraOf, findCamera, provideUnboundCamera } from '../rendererOf.js';
// Loads the factories an unbound viewer gets its credits, draw, frame and
// query ports from.
// Loads the factories an unbound viewer gets its credits, draw, frame,
// input and query ports from, and a click's own Cesium picks.
import './credits.js';
import './draw.js';
import './frame.js';
import './input.js';
import './nativeClick.js';
import './query.js';
/**
+28 -2
View File
@@ -27,6 +27,7 @@ import { createInputRouter } from '../input/router.js';
import { acquireCameraInput } from './cameraInput.js';
import { installTrackpadPinchZoom } from './ctrlWheelZoom.js';
import { wheelLines } from '../input/wheel.js';
import { provideUnboundInput } from '../rendererOf.js';
const T = Cesium.ScreenSpaceEventType;
const MODIFIERS = [
@@ -94,8 +95,7 @@ function pointerTypeOf(dom, otherwise = 'mouse') {
const inputs = new WeakMap();
/**
* The input port made for a scene, while it lives: the application's
* dispatcher (src/input/dispatcher.js) delivers through it.
* The input port made for a scene, while it lives.
* @param {object} scene
* @returns {ReturnType<typeof createCesiumInput> | null}
*/
@@ -477,3 +477,29 @@ export function createCesiumInput(
inputs.set(scene, self);
return self;
}
// A Cesium viewer with no renderer bound to it gets an
// input port over its canvas when code first asks `findInput` for one (the
// application's dispatcher, src/input/dispatcher.js). Its clicks carry no
// picks: the dispatcher makes its own through `findQuery`. The viewer is its
// owner's, so its stock actions stay on its own handler, taken off only
// while suppressed. `options` are the test doubles' (`createHandler`, `now`,
// `document`).
provideUnboundInput((viewer, options = {}) => {
const scene = viewer?.scene;
if (!scene || typeof scene !== 'object') return null;
// A port someone already made for the scene (a harness's): borrowed.
const made = inputs.get(scene);
if (made) return { port: made.port, dispose() {} };
const { createHandler, now, document } = options;
const input = createCesiumInput(viewer, {
report: (error) => console.error('Pointer input failed', error),
takeStock: false,
...(createHandler ? { createHandler } : {}),
...(now ? { now } : {}),
...(document !== undefined ? { document } : {}),
});
// Kept for its dispatcher when a renderer is bound later, as the
// dispatcher's clicks would otherwise stop.
return { port: input.port, dispose: () => input.dispose(), keep: true };
});
+174
View File
@@ -0,0 +1,174 @@
/**
* @module render/cesium/nativeClick
* @description Cesium's own picks of a click, for what the renderer's picks
* do not name (`rendererOf.js` `nativeClickOf`): things drawn outside the
* draw port, and code still bound to Cesium's pick objects. Each pick is
* made at most once per click, and a hit on the follow's helper entity is a
* hit on its target (`pickThroughFollowHelper`).
*
* Also the raw forms of the shared pick-id and contact rules
* (`src/data/pickRegistry.js`, which reads the contract's `Hit`), for code
* that still holds a Cesium pick.
*/
import * as Cesium from 'cesium';
import { findPickOwner } from '../../data/pickRegistry.js';
import { isSurfacePick } from '../../data/scenePick.js';
import { provideNativeClick } from '../rendererOf.js';
import { drawHitOf } from './drawHit.js';
import { pickThroughFollowHelper } from './follow.js';
import { recentPick } from './pickMemo.js';
/** 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;
/**
* A Cesium pick's canonical pick id: its id, or its primitive's, as a
* String (satellites' numeric NORAD ids, an entity's own `id`); null when it
* carries none.
* @param {object|null|undefined} picked What `scene.pick` gave.
* @returns {string|null}
*/
export function nativePickId(picked) {
if (!picked) return null;
const unwrap = (id) => {
if (id === null || id === undefined) return undefined;
if (typeof id === 'object') {
// A Cesium Entity (.id string), or a draw-set item's pick id.
if (typeof id.id === 'string' || typeof id.id === 'number') return id.id;
return undefined;
}
return id;
};
let id = unwrap(picked.id);
if (id === undefined) id = unwrap(picked.primitive?.id);
return typeof id === 'string' || typeof id === 'number' ? String(id) : null;
}
/**
* `pickContact` (`src/data/pickRegistry.js`) over Cesium's own picks: on a
* coarse pointer, the first registered contact under a surface pick.
* @param {object} scene
* @param {{x: number, y: number}} position
* @param {{picked?: object|null, drill?: (limit: number, width: number, height: number) => object[]}} [options]
* @returns {object|null|undefined}
*/
export function nativePickContact(scene, position, options = {}) {
const picked = 'picked' in options ? options.picked : scene.pick(position);
if (
!globalThis.matchMedia?.('(pointer: coarse)').matches ||
findPickOwner(nativePickId(picked)) ||
!isSurfacePick(picked) ||
typeof scene.drillPick !== 'function'
)
return picked;
let hits;
try {
hits =
(options.drill
? options.drill(8, 14, 14)
: scene.drillPick(position, 8, 14, 14)) || [];
} catch {
return picked;
}
for (const hit of hits.slice(0, 8)) {
if (findPickOwner(nativePickId(hit))) return hit;
if (!isSurfacePick(hit)) break;
}
return picked;
}
/**
* What is on top as Cesium sees it, where the renderer's pick names
* nothing: a draw-set item the renderer's sets do not hold (one drawn by a
* draw port a renderer bound since superseded) as its hit, anything else
* but the map by its id; null for the map or nothing.
*/
const foreignOf = (picked) =>
isSurfacePick(picked)
? null
: (drawHitOf(picked) ?? { id: nativePickId(picked) });
/** A Cesium pick as the contract's `Hit`, a foreign one with no set. */
const hitOf = (picked) =>
drawHitOf(picked) ??
(isSurfacePick(picked)
? { set: '', id: '', surface: true }
: { set: '', id: nativePickId(picked), surface: false });
/**
* A click's Cesium picks at a pick-buffer position.
* @param {object} scene
* @param {{x: number, y: number}} at
* @returns {import('../rendererOf.js').NativeClick}
*/
export function createNativeClick(scene, at) {
const position = new Cesium.Cartesian2(at.x, at.y);
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 drills = new Map();
// The query port's pick of this pixel, when it just made one: the click
// reads the renderer's pick first, so its own Cesium pick costs no pass.
const picked = (width, height) => {
const recent = recentPick(scene, at.x, at.y, width ?? 3, height ?? 3);
return recent
? recent.picked
: width === undefined
? scene.pick(position)
: scene.pick(position, width, height);
};
const native = {
/** `scene.pick` at the click. */
get pick() {
return once('pick', () => pickThroughFollowHelper(picked()));
},
/** `scene.pick` with a wider window. */
pickWindow(width, height) {
return once(`window:${width}x${height}`, () =>
pickThroughFollowHelper(picked(width, height)),
);
},
/** `scene.drillPick`, at most `limit` hits. */
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 [];
// Only the default window is shared between callers; 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);
drills.set(key, { limit: depth, hits });
return hits.slice(0, limit);
},
};
return {
native,
drillHits: (limit, width, height) =>
native.drill(limit, width, height).map(hitOf),
foreign: (width, height) =>
foreignOf(
width === undefined && height === undefined
? native.pick
: native.pickWindow(width, height),
),
};
}
// Any Cesium viewer, bound or not, by shape: a caller's may come from
// another copy of Cesium.
provideNativeClick((viewer, at) => {
const scene = viewer?.scene;
if (typeof scene?.pick !== 'function') return null;
return createNativeClick(scene, at);
});
+319
View File
@@ -0,0 +1,319 @@
/**
* The raw forms of the shared pick-id and contact rules, over Cesium's own picks
* (`nativePickId`, `nativePickContact`), and a click's own Cesium picks.
*
* - nativePickId reduces every Cesium pick shape (string ids, numeric NORAD
* ids, Cesium Entity objects, draw-set pick ids) to ONE canonical String id.
*/
import { test } from 'node:test';
import assert from 'node:assert/strict';
import {
registerPickOwner,
unregisterPickOwner,
isOwnedByOtherLayer,
} from '../../data/pickRegistry.js';
import {
createNativeClick,
nativePickContact as pickContact,
nativePickId as resolvePickId,
} from './nativeClick.js';
import { nativeClickOf } from '../rendererOf.js';
import { rememberPick } from './pickMemo.js';
// ---------------------------------------------------------------------------
// resolvePickId — canonical String coercion for every layer's pick shape
// ---------------------------------------------------------------------------
test('resolvePickId: string pick id (flights/military/bikeshare/cctv billboards)', () => {
assert.equal(resolvePickId({ id: 'aaa001' }), 'aaa001');
assert.equal(
resolvePickId({ id: undefined, primitive: { id: 'station:austin:1' } }),
'station:austin:1',
);
});
test('resolvePickId: numeric pick id (satellite NORAD numbers) → String', () => {
assert.equal(resolvePickId({ id: 25544 }), '25544');
assert.equal(
resolvePickId({ id: undefined, primitive: { id: 43013 } }),
'43013',
);
});
test('resolvePickId: Cesium-Entity-like object → its string id', () => {
const entity = { id: 'cctv-atx-cam-3-center', properties: {} };
assert.equal(resolvePickId({ id: entity }), 'cctv-atx-cam-3-center');
});
test('resolvePickId: a draw-set pick id → its item id', () => {
assert.equal(
resolvePickId({ id: { set: 'quakes:1', id: 'quake:a' } }),
'quake:a',
);
});
test('resolvePickId: unresolvable picks → null', () => {
assert.equal(resolvePickId(null), null);
assert.equal(resolvePickId(undefined), null);
assert.equal(resolvePickId({}), null);
assert.equal(resolvePickId({ id: {} }), null); // object with no id
assert.equal(resolvePickId({ primitive: {} }), null);
});
function primaryPointer(t, coarse) {
const previous = Object.getOwnPropertyDescriptor(globalThis, 'matchMedia');
Object.defineProperty(globalThis, 'matchMedia', {
configurable: true,
value: (query) => ({ matches: query === '(pointer: coarse)' && coarse }),
});
t.after(() => {
if (previous) Object.defineProperty(globalThis, 'matchMedia', previous);
else delete globalThis.matchMedia;
});
}
function contactOwners(t) {
registerPickOwner('flights', (id) => id === 'civil');
registerPickOwner('military', (id) => id === 'military');
registerPickOwner('ais-live-vessels', (id) => id === '123456789');
t.after(() => {
for (const id of ['flights', 'military', 'ais-live-vessels'])
unregisterPickOwner(id);
});
}
const mapTile = { primitive: { isCesium3DTileset: true } };
test('touch contact pick expands only a surface miss, bounded to 8 hits in 14 CSS pixels', (t) => {
primaryPointer(t, true);
contactOwners(t);
const position = { x: 30, y: 50 };
const contact = { primitive: { id: 'civil' } };
let drills = 0;
const scene = {
pick(point) {
assert.equal(point, position);
return mapTile;
},
drillPick(...args) {
drills++;
assert.deepEqual(args, [position, 8, 14, 14]);
return [mapTile, contact];
},
};
assert.equal(pickContact(scene, position), contact);
assert.equal(drills, 1);
});
test('touch contact pick returns the first registered sibling, never a caller-specific preference', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const first of [{ id: 'military' }, { id: '123456789' }]) {
const scene = {
pick: () => mapTile,
drillPick: () => [mapTile, first, { id: 'civil' }],
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), first);
}
});
test('touch contact pick does not drill through exact registered or unregistered interactive picks', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const exact of [
{ id: 'military' },
{ id: 'custom-annotation' },
{ primitive: { id: 'custom-gizmo' } },
{ primitive: { id: 'civil', isCesium3DTileset: true } },
]) {
const scene = {
pick: () => exact,
drillPick: () => assert.fail('must keep exact interactive hit'),
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), exact);
}
});
test('touch expansion stops at a non-surface object and respects the drill bound', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const hits of [
[mapTile, { id: 'custom-annotation' }, { id: 'civil' }],
[...Array(8).fill(mapTile), { id: 'civil' }],
[mapTile],
]) {
assert.equal(
pickContact(
{ pick: () => mapTile, drillPick: () => hits },
{ x: 1, y: 1 },
),
mapTile,
);
}
});
test('fine primary pointers keep the existing exact mouse pick without a drill', (t) => {
primaryPointer(t, false);
contactOwners(t);
const scene = {
pick: () => mapTile,
drillPick: () => assert.fail('mouse must not expand'),
};
assert.equal(pickContact(scene, { x: 1, y: 1 }), mapTile);
});
test('touch picking tolerates unavailable or failing drill support and preserves empty sky', (t) => {
primaryPointer(t, true);
contactOwners(t);
for (const drillPick of [
undefined,
() => {
throw new Error('context lost');
},
() => [],
]) {
assert.equal(
pickContact({ pick: () => undefined, drillPick }, { x: 1, y: 1 }),
undefined,
);
}
});
// ---------------------------------------------------------------------------
// A click's own Cesium picks
// ---------------------------------------------------------------------------
function countingScene(picked) {
const calls = { pick: [], drillPick: [] };
return {
calls,
pick(...args) {
calls.pick.push(args);
return typeof picked === 'function' ? picked(...args) : picked;
},
drillPick(...args) {
calls.drillPick.push(args);
return [];
},
};
}
test('a click picks once, at the pick-buffer position, and names what the draw port does not draw', () => {
const scene = countingScene({ id: 'transit:bus-1' });
const click = createNativeClick(scene, { x: 12, y: 34 });
assert.equal(click.native.pick.id, 'transit:bus-1');
assert.equal(click.native.pick, click.native.pick, 'memoized');
assert.deepEqual(click.foreign(), { id: 'transit:bus-1' });
assert.equal(scene.calls.pick.length, 1);
assert.deepEqual(
[scene.calls.pick[0][0].x, scene.calls.pick[0][0].y],
[12, 34],
);
});
test('the map and nothing are not foreign; a draw-set item is its hit', () => {
assert.deepEqual(
createNativeClick(
countingScene({ id: { set: 'quakes:1', id: 'quake:a' } }),
{
x: 0,
y: 0,
},
).foreign(),
{ set: 'quakes:1', id: 'quake:a', surface: false },
'one the renderer pick did not name: drawn by a superseded draw port',
);
for (const picked of [
undefined,
{ primitive: { isCesium3DTileset: true } },
{ content: {} },
])
assert.equal(
createNativeClick(countingScene(picked), { x: 0, y: 0 }).foreign(),
null,
);
assert.deepEqual(
createNativeClick(countingScene({ primitive: {} }), {
x: 0,
y: 0,
}).foreign(),
{ id: null },
'an id-less primitive is something, with no id',
);
});
test("a click's own pick reuses the query port's pass of the same pixel in the same task", async () => {
const picked = { id: 'transit:bus-1' };
const scene = countingScene(picked);
rememberPick(scene, 5, 6, 3, 3, picked);
assert.equal(createNativeClick(scene, { x: 5, y: 6 }).native.pick, picked);
assert.equal(scene.calls.pick.length, 0);
// Another pixel or window picks again.
createNativeClick(scene, { x: 5, y: 7 }).native.pick;
createNativeClick(scene, { x: 5, y: 6 }).native.pickWindow(9, 9);
assert.equal(scene.calls.pick.length, 2);
// So does a later task: the scene may have drawn since.
await Promise.resolve();
createNativeClick(scene, { x: 5, y: 6 }).native.pick;
assert.equal(scene.calls.pick.length, 3);
});
test("the query port's passes of several windows in one task are all reused", () => {
const picked = { id: 'transit:bus-1' };
const wide = { id: 'transit:bus-2' };
const scene = countingScene(picked);
rememberPick(scene, 5, 6, 3, 3, picked);
rememberPick(scene, 5, 6, 9, 9, wide);
const { native } = createNativeClick(scene, { x: 5, y: 6 });
assert.equal(native.pickWindow(9, 9), wide);
assert.equal(native.pick, picked);
assert.equal(scene.calls.pick.length, 0);
});
test("a drill's hits: draw-set items, the map, and the rest with no set", () => {
const scene = countingScene(undefined);
scene.drillPick = () => [
{ id: { set: 'quakes:1', id: 'quake:a' } },
{ primitive: { isCesium3DTileset: true } },
{ primitive: { id: 'bus-1' } },
{ primitive: {} },
];
assert.deepEqual(
createNativeClick(scene, { x: 0, y: 0 })
.drillHits(8, 14, 14)
.map(({ set, id, surface }) => ({ set, id, surface })),
[
{ set: 'quakes:1', id: 'quake:a', surface: false },
{ set: '', id: '', surface: true },
{ set: '', id: 'bus-1', surface: false },
{ set: '', id: null, surface: false },
],
);
});
test('drills of different depths on one click share a pass', () => {
const hits = Array.from({ length: 20 }, (_, i) => ({ id: `hit-${i}` }));
const scene = countingScene(undefined);
scene.drillPick = (...args) => {
scene.calls.drillPick.push(args);
return hits.slice(0, args[1]);
};
const { native } = createNativeClick(scene, { x: 0, y: 0 });
assert.deepEqual(
[native.drill(12).length, native.drill(8).length, native.drill(16).length],
[12, 8, 16],
);
assert.equal(scene.calls.drillPick.length, 1);
});
test('the adapter provides native clicks for a Cesium-shaped viewer only', () => {
const scene = countingScene({ id: 'x' });
assert.equal(nativeClickOf({ scene }, { x: 1, y: 1 }).native.pick.id, 'x');
assert.equal(nativeClickOf({ scene: {} }, { x: 1, y: 1 }), null);
assert.equal(nativeClickOf(null, { x: 1, y: 1 }), null);
assert.equal(
nativeClickOf({ scene, isDestroyed: () => true }, { x: 1, y: 1 }),
null,
);
});
+49
View File
@@ -0,0 +1,49 @@
/**
* @module render/cesium/pickMemo
* @description Each scene's `pick` passes made in the task running now, as
* Cesium gave them, so a click's own Cesium picks (`nativeClick.js`) reuse
* the query port's pick of the same pixel and window rather than draw the
* pick buffer again. Nothing draws between them: they are forgotten once
* the task that made them ends. No imports.
*/
/**
* Each scene's passes in this task, by pixel and window.
* @type {WeakMap<object, Map<string, unknown>>}
*/
let taskPicks = new WeakMap();
let clearing = false;
const keyOf = (x, y, width, height) => `${x},${y},${width},${height}`;
/**
* Note a `pick` pass `scene.pick` just made, for `recentPick`.
* @param {object} scene
*/
export function rememberPick(scene, x, y, width, height, picked) {
let picks = taskPicks.get(scene);
if (!picks) {
picks = new Map();
taskPicks.set(scene, picks);
}
picks.set(keyOf(x, y, width, height), picked);
if (!clearing) {
clearing = true;
queueMicrotask(() => {
clearing = false;
taskPicks = new WeakMap();
});
}
}
/**
* What the query port's `pick` on `scene` found at exactly this pixel and
* window in the task running now; undefined when it made none there.
* @param {object} scene
* @returns {{picked: unknown} | undefined}
*/
export function recentPick(scene, x, y, width = 3, height = 3) {
const picks = taskPicks.get(scene);
const key = keyOf(x, y, width, height);
return picks?.has(key) ? { picked: picks.get(key) } : undefined;
}
+82 -1
View File
@@ -7,6 +7,7 @@ import {
listenerList,
} from './ports.js';
import { updateCameraChanged } from './internals.js';
import { createNativeClick } from './nativeClick.js';
test('capabilities follow what the scene supports', () => {
const effects = [
@@ -121,7 +122,11 @@ function fakeWidget(overrides = {}) {
const calls = [];
const primitives = [];
const scene = {
camera: { moveStart: event(), moveEnd: event() },
camera: {
moveStart: event(),
moveEnd: event(),
pickEllipsoid: () => undefined,
},
primitives: {
add: (p) => primitives.push(p),
remove: (p) => primitives.splice(primitives.indexOf(p), 1),
@@ -221,6 +226,82 @@ test('pick under something unpickable stops at what hides the rest', () => {
ports.dispose();
});
test('a surface hit over the ellipsoid makes its depth pick only when its position is read', () => {
let depthPicks = 0;
const { widget, scene } = fakeWidget({
pickPosition: () => (depthPicks++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => ({ x: 6378137, y: 0, z: 0 });
const ports = createCesiumPorts(widget, { capabilities: all });
const hit = ports.query.pick(1, 1);
assert.equal(hit.surface, true);
assert.equal(depthPicks, 0, 'no depth pass for a click nobody grounds');
assert.equal(hit.position.x, 6378200, 'the rendered surface, once read');
assert.equal(hit.position.x, 6378200);
assert.equal(depthPicks, 1);
// Over the sky the depth pick decides whether there is a surface at all.
scene.camera.pickEllipsoid = () => undefined;
scene.pickPosition = () => undefined;
assert.equal(ports.query.pick(1, 1), null);
ports.dispose();
});
test('a sky pick makes no depth pass unless something may be there', () => {
let depthPicks = 0;
let globeHit = null;
let picked;
const { widget, scene } = fakeWidget({
pick: () => picked,
pickPosition: () => (depthPicks++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => undefined;
scene.camera.getPickRay = () => ({
origin: { x: 7e6, y: 0, z: 0 },
direction: { x: 0, y: 1, z: 0 },
});
scene.globe.pick = () => globeHit;
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.query.pick(1, 1), null, 'nothing there: the sky');
assert.equal(depthPicks, 0);
// A mountain above the horizon: a globe tile on the ray.
globeHit = { x: 6378000, y: 0, z: 0 };
assert.equal(ports.query.pick(1, 1).surface, true);
assert.equal(depthPicks, 1);
// Something drawn outside the sets against the sky.
globeHit = null;
picked = { primitive: {} };
ports.query.pick(1, 1);
assert.equal(depthPicks, 2);
// A failing depth pick finds no surface, so what was picked is still read.
scene.pickPosition = () => {
throw new Error('no depth');
};
assert.equal(ports.query.pick(1, 1), null);
// A throwing camera answers nothing rather than failing the pick.
picked = undefined;
scene.camera.pickEllipsoid = () => {
throw new Error('no camera');
};
assert.equal(ports.query.pick(1, 1), null);
ports.dispose();
});
test("an empty click's renderer pick and its own Cesium pick are one pass", () => {
let passes = 0;
const { widget, scene } = fakeWidget({
pick: () => (passes++, undefined),
pickPosition: () => (passes++, { x: 6378200, y: 0, z: 0 }),
});
scene.camera.pickEllipsoid = () => ({ x: 6378137, y: 0, z: 0 });
const ports = createCesiumPorts(widget, { capabilities: all });
assert.equal(ports.query.pick(4, 5).surface, true);
const click = createNativeClick(scene, { x: 4, y: 5 });
assert.equal(click.foreign(), null);
assert.equal(click.native.pick, undefined);
assert.equal(passes, 1);
ports.dispose();
});
test('rayCast answers against the surface asked for', async () => {
const seen = [];
const { widget } = fakeWidget({
+46 -8
View File
@@ -17,6 +17,7 @@ import { findDraw, provideUnboundQuery } from '../rendererOf.js';
import { toCartesian } from './common.js';
import { unboundDrawPart } from './draw.js';
import { drawHitOf } from './drawHit.js';
import { rememberPick } from './pickMemo.js';
/** The fewest things a bounded drill looks through (`QueryPort.drillPick`). */
const DRILL_DEPTH = 16;
@@ -73,10 +74,45 @@ export function createCesiumQuery({
const hitOf = ({ id }) => drawHitOf({ id });
/** The globe (or ellipsoid) under a pixel, as a surface hit. */
function surfaceHit(x, y) {
const position = query.pickPosition(x, y) ?? query.pickEllipsoid(x, y);
return position ? { set: '', id: '', surface: true, position } : null;
/** A query that throws answers nothing. */
const quietly = (fn) => {
try {
return fn();
} catch {
return null;
}
};
/**
* The globe (or ellipsoid) under a pixel, as a surface hit. Where the
* ellipsoid is under it, its position is the depth pick's (another pass
* over the scene), made when first read. Where it is not, the depth pick
* decides, unless nothing was picked there and no globe tile is on the
* pixel's ray: the sky, with no pass. A depth pick that throws finds no
* surface, so what was picked there is still read.
*/
function surfaceHit(x, y, picked) {
const ellipsoid = quietly(() => query.pickEllipsoid(x, y));
if (!ellipsoid) {
if (
picked == null &&
!quietly(() => query.pickGlobe(query.pickRay(x, y)))
)
return null;
const position = quietly(() => query.pickPosition(x, y));
return position ? { set: '', id: '', surface: true, position } : null;
}
let position;
const hit = { set: '', id: '', surface: true };
Object.defineProperty(hit, 'position', {
enumerable: true,
configurable: true,
get() {
position ??= quietly(() => query.pickPosition(x, y)) ?? ellipsoid;
return position;
},
});
return hit;
}
/**
@@ -270,9 +306,11 @@ export function createCesiumQuery({
const query = {
pick(x, y, window = {}) {
const owner = ownerOf(
scene.pick(screen(x, y), window.width ?? 3, window.height ?? 3),
);
const width = window.width ?? 3;
const height = window.height ?? 3;
const picked = scene.pick(screen(x, y), width, height);
rememberPick(scene, x, y, width, height, picked);
const owner = ownerOf(picked);
if (owner && pickable(owner)) return hitOf(owner);
// Something unpickable is on top: the first pickable item under it,
// unless something else hides it.
@@ -285,7 +323,7 @@ export function createCesiumQuery({
});
if (under) return under;
}
return surfaceHit(x, y);
return surfaceHit(x, y, picked);
},
drillPick: (x, y, options = {}) =>
drill(x, y, { ...options, untilForeign: false }),
+5 -2
View File
@@ -2,11 +2,14 @@
* @module render/cesium/unbound
* @description What to load, once, before handing the Cesium-free
* layers a Cesium viewer with no renderer bound: the factories
* that build a camera, credits, effects, draw, frame, globe and query port over
* such a viewer when code first asks for one (`rendererOf.js`).
* that build a camera, credits, effects, draw, frame, globe, input and query
* port over such a viewer when code first asks for one, and a click's own
* Cesium picks (`rendererOf.js`).
*/
import './camera.js';
import './effects.js';
import './frame.js';
import './globe.js';
import './input.js';
import './nativeClick.js';
import './query.js';