Cut duplicated and dead code across the engines, the layers and the QA scripts

- src/geo drops the ported debug argument checks and the tests that
  bitExact already covers; package boundaries accept a directory entry,
  so src/geo/ is listed once per group.
- Cesium no longer carries movers and lines nobody draws with: they are
  optional engine capabilities. The fake engine and the Cesium camera use
  the shared cameraMath; unused contract tables, clock.ticked, the
  'finest' surface detail and Navara click statistics are gone.
- ALPR keeps one overlay core and one presentation model for both
  engines, bikeshare one station bookkeeping, the Navara ground effects
  one definition helper; image atlases, view centres, mover banks and
  colours are shared.
- The legacy switch route, the clock offset and rate controls and other
  unused exports are removed.
- The acceptance runs the Navara draw, geo import and scope checks;
  scenarios use the harness switch and page helpers; the main chunk
  check keeps the size budget only and runs once in CI.
This commit is contained in:
German Khokhlov committed 2026-11-05 13:32:39 +04:00
1 parent c502404e1d
commit 7abf74518f
272 files changed
+4828 -10213

No files matched your search

+30 -70
View File
@@ -3,24 +3,17 @@
import * as Cesium from 'cesium';
import * as geo from '../../geo/index.js';
import { createEngineEvent } from '../contract.js';
import { wrapAngle } from '../cameraMath.js';
import { bridgeEvent } from './events.js';
import { toCesium2, toCesium3, toGeo3 } from './convert.js';
import { createCesiumFollow } from './follow.js';
const { math } = geo;
const easings = () => ({
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
sinusoidalInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
linear: Cesium.EasingFunction.LINEAR_NONE,
});
// Cesium reports heading and roll in [0, 2π]; the contract wants [0, 2π).
function wrapAngle(angle) {
const value = math.zeroToTwoPi(angle);
return value < 1e-12 || math.TWO_PI - value < 1e-12 ? 0 : value;
}
function cesiumOrientation(orientation) {
if (!orientation) return undefined;
if (orientation.direction)
@@ -65,70 +58,38 @@ const COMMANDS = Object.freeze([
/**
* camera.commanded: raised before any COMMANDS call on the Cesium camera and
* when the viewer's tracked entity changes. The hooks exist only while the
* event has listeners and then restore each method exactly (unless something
* newer replaced it), so an idle engine leaves the camera untouched.
* event has listeners (bridgeEvent) and then restore each method exactly
* (unless something newer replaced it), so an idle engine leaves the camera
* untouched.
*/
function commandedEvent(viewer, cesium) {
const event = createEngineEvent();
let unhook = null;
const hook = () => {
const removers = [];
for (const name of COMMANDS) {
const original = cesium[name];
if (typeof original !== 'function') continue;
const descriptor = Object.getOwnPropertyDescriptor(cesium, name);
const wrapped = function (...args) {
event.raiseEvent();
return original.apply(this, args);
return bridgeEvent({
addEventListener(raise) {
const removers = [];
for (const name of COMMANDS) {
const original = cesium[name];
if (typeof original !== 'function') continue;
const descriptor = Object.getOwnPropertyDescriptor(cesium, name);
const wrapped = function (...args) {
raise();
return original.apply(this, args);
};
cesium[name] = wrapped;
removers.push(() => {
if (cesium[name] !== wrapped) return;
if (descriptor) Object.defineProperty(cesium, name, descriptor);
else delete cesium[name];
});
}
const removeTracking = viewer.trackedEntityChanged?.addEventListener(() =>
raise(),
);
if (removeTracking) removers.push(removeTracking);
return () => {
for (const remove of removers) remove();
};
cesium[name] = wrapped;
removers.push(() => {
if (cesium[name] !== wrapped) return;
if (descriptor) Object.defineProperty(cesium, name, descriptor);
else delete cesium[name];
});
}
const removeTracking = viewer.trackedEntityChanged?.addEventListener(() =>
event.raiseEvent(),
);
if (removeTracking) removers.push(removeTracking);
return () => {
for (const remove of removers) remove();
};
};
let detached = false;
const sync = () => {
const wanted = !detached && event.numberOfListeners > 0;
if (wanted === (unhook !== null)) return;
if (wanted) unhook = hook();
else {
const remove = unhook;
unhook = null;
remove();
}
};
const add = event.addEventListener;
const remove = event.removeEventListener;
event.addEventListener = (listener) => {
const removeListener = add(listener);
sync();
return () => {
removeListener();
sync();
};
};
event.removeEventListener = (listener) => {
const removed = remove(listener);
sync();
return removed;
};
return {
event,
detach() {
detached = true;
sync();
},
};
});
}
/**
@@ -136,8 +97,7 @@ function commandedEvent(viewer, cesium) {
* @returns {{ camera: import('../contract.js').GlobeCamera, destroy: () => void }}
*/
export function createCesiumCamera(viewer) {
// Viewer.camera is scene.camera; the public alias is what shell callers read.
const cesium = viewer.camera ?? viewer.scene.camera;
const cesium = viewer.camera;
const bridges = {
changed: bridgeEvent(cesium.changed),
moveStart: bridgeEvent(cesium.moveStart),
+3 -10
View File
@@ -15,7 +15,6 @@
// preUpdate instead, attached on first use so creating the engine adds no
// scene listener.
import { createEngineEvent } from '../contract.js';
import { appClock as pageClock } from '../../time/clock.js';
/**
@@ -28,21 +27,16 @@ export function createCesiumClock(viewer, { appClock = pageClock } = {}) {
// A viewer-shaped object without a clock (tests, a bare scene): the
// scene's preUpdate opens the frame instead.
const tickSource = viewer.clock?.onTick ?? viewer.scene.preUpdate;
const ticked = createEngineEvent();
let removeTick = null;
let destroyed = false;
const onTick = () => ticked.raiseValue(appClock.beginFrame());
const onTick = () => {
appClock.beginFrame();
};
const attach = () => {
if (!removeTick && !destroyed)
removeTick = tickSource.addEventListener(onTick);
};
if (viewer.clock?.onTick) attach();
const add = ticked.addEventListener;
ticked.addEventListener = (listener) => {
const remove = add(listener);
attach();
return remove;
};
return {
clock: {
now: () => appClock.now(),
@@ -50,7 +44,6 @@ export function createCesiumClock(viewer, { appClock = pageClock } = {}) {
attach();
return appClock.frameTime();
},
ticked,
},
destroy() {
destroyed = true;
+12 -9
View File
@@ -1,7 +1,6 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { isEngineEvent } from '../contract.js';
import { createAppClock } from '../../time/clock.js';
import { createCesiumClock } from './clock.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
@@ -32,7 +31,6 @@ test('the clock reads the app clock and latches on the viewer clock from creatio
const viewer = createFakeViewer();
const wall = manualAppClock();
const { clock } = createCesiumClock(viewer, { appClock: wall.appClock });
assert.ok(isEngineEvent(clock.ticked));
// Attached at creation, so it runs before onTick listeners added later
// (cameraVerbs installs its own after the engine exists).
assert.equal(viewer.clock.onTick.numberOfListeners, 1);
@@ -51,7 +49,9 @@ test('frameTime is latched on the viewer clock tick, before preUpdate', () => {
const wall = manualAppClock();
const { clock } = createCesiumClock(viewer, { appClock: wall.appClock });
const seen = [];
clock.ticked.addEventListener((time) => seen.push(['ticked', time]));
viewer.clock.onTick.addEventListener(() =>
seen.push(['tick', clock.frameTime()]),
);
// A preUpdate listener the app added before the engine existed still
// reads this frame's time: the latch is on the tick, not on preUpdate.
viewer.scene.preUpdate.addEventListener(() =>
@@ -66,10 +66,10 @@ test('frameTime is latched on the viewer clock tick, before preUpdate', () => {
wall.advance(16);
cesiumFrame(viewer, { draw: false });
assert.deepEqual(seen, [
['ticked', t0],
['tick', t0],
['preUpdate', t0],
['preRender', t0],
['ticked', t0 + 19],
['tick', t0 + 19],
['preUpdate', t0 + 19],
]);
});
@@ -99,11 +99,14 @@ test('a viewer without a clock latches on preUpdate', () => {
const { clock, destroy } = createCesiumClock(viewer, {
appClock: wall.appClock,
});
const seen = [];
clock.ticked.addEventListener((time) => seen.push(time));
// Attached on first use: creating the clock adds no scene listener.
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
const before = clock.frameTime();
assert.equal(viewer.scene.preUpdate.numberOfListeners, 1);
wall.advance(7);
viewer.scene.preUpdate.raiseEvent(viewer.scene);
assert.deepEqual(seen, [wall.appClock.now()]);
wall.advance(2);
assert.equal(clock.frameTime(), before + 7);
destroy();
assert.equal(viewer.scene.preUpdate.numberOfListeners, 0);
});
@@ -116,7 +119,7 @@ test('the viewer clock itself is left alone', () => {
const { clock } = createCesiumClock(viewer, {
appClock: manualAppClock().appClock,
});
clock.ticked.addEventListener(() => {});
clock.frameTime();
cesiumFrame(viewer);
assert.equal(viewer.clock.shouldAnimate, false);
assert.equal(viewer.clock.multiplier, 1);
+1 -1
View File
@@ -18,6 +18,6 @@ export const toCesium3 = (value) =>
/**
* A new Cesium.Cartesian2 for a window position. Always a new instance: Cesium
* caches pickPosition by windowPosition.toString() (phase 1a rule 9).
* caches pickPosition by windowPosition.toString().
*/
export const toCesium2 = (value) => new Cesium.Cartesian2(value.x, value.y);
+4 -32
View File
@@ -10,9 +10,7 @@ import { createCesiumClock } from './clock.js';
import { createCesiumCredits } from './credits.js';
import { createCesiumFrames } from './frames.js';
import { createCesiumInput } from './input.js';
import { createCesiumLines } from './lines.js';
import { createCesiumMaps } from './maps.js';
import { createCesiumMovers } from './movers.js';
import { createCesiumPicker } from './picker.js';
import { createCesiumProjector } from './projector.js';
import { createCesiumRender } from './render.js';
@@ -37,44 +35,18 @@ import { createCesiumSurface } from './surface.js';
*/
export function createCesiumEngine(viewer, options = {}) {
if (!viewer?.scene) throw new TypeError('createCesiumEngine needs a viewer');
// Viewer.canvas is scene.canvas; the engine reads the public alias.
const canvas = viewer.canvas ?? viewer.scene.canvas;
const { canvas } = viewer;
const render = createCesiumRender(viewer, options);
const credits = createCesiumCredits(viewer);
// Picks name the mover set or line they hit (movers and lines exist
// below; the picker asks them when it picks).
let lines = null;
let movers = null;
let projectorPart = null;
const picker = createCesiumPicker(viewer, {
identify: (picked) =>
movers?.identify(picked) ?? lines?.identify(picked) ?? null,
// A mover instance behind the globe is not picked (billboards drawn
// without a depth test reach Cesium's GPU pick through it).
visible: ({ owner, instance }) => {
const position = movers?.instancePosition(owner, instance);
return position ? projectorPart.projector.horizonVisible(position) : true;
},
});
const picker = createCesiumPicker(viewer);
const parts = {
camera: createCesiumCamera(viewer),
picker,
projector: (projectorPart = createCesiumProjector(viewer)),
projector: createCesiumProjector(viewer),
frames: createCesiumFrames(viewer),
clock: createCesiumClock(viewer, options),
lines: (lines = createCesiumLines(viewer, {
requestRender: (reason) => render.render.request(reason),
...(options.lineFactories ? { factories: options.lineFactories } : {}),
})),
movers: (movers = createCesiumMovers(viewer, {
requestRender: (reason) => render.render.request(reason),
...(options.moverFactories ? { factories: options.moverFactories } : {}),
})),
render,
// Mover sets in a surface `exclude` are hidden for the sample.
surface: createCesiumSurface(viewer, {
engineExclude: (entry) => movers?.primitiveOf(entry) ?? null,
}),
surface: createCesiumSurface(viewer),
input: createCesiumInput(viewer, { ...options, picker: picker.picker }),
credits,
maps: createCesiumMaps(viewer, {
+1 -47
View File
@@ -146,57 +146,11 @@ test('the engine clock is the app clock given, latched on the viewer clock tick'
const viewer = createFakeViewer();
const engine = createCesiumEngine(viewer, { appClock });
assert.equal(engine.clock.now(), 1_000_000);
const seen = [];
engine.clock.ticked.addEventListener((time) => seen.push(time));
assert.equal(viewer.clock.onTick.numberOfListeners, 1);
wall += 16;
viewer.clock.onTick.raiseEvent(viewer.clock);
assert.deepEqual(seen, [1_000_016]);
wall += 5;
assert.equal(engine.clock.frameTime(), 1_000_016);
engine.destroy();
assert.equal(viewer.clock.onTick.numberOfListeners, 0);
});
test('picks leave out mover instances behind the horizon and the follow proxy', async () => {
const geo = await import('../../geo/index.js');
const viewer = createFakeViewer();
const engine = createCesiumEngine(viewer, { requestRender: () => {} });
try {
const set = engine.movers.createSet({
id: 'horizon-points',
pickable: true,
kind: 'point',
capacity: 2,
point: { sizePx: 8 },
});
// The fake camera is at x = 7e6 (over 0°, 0°): 0°E is in front, 180° behind.
set.set(0, { position: geo.cartesian3.fromDegrees(0, 1, 0) });
set.set(1, { position: geo.cartesian3.fromDegrees(180, 1, 0) });
set.setCount(2);
set.commit();
const [front, back] = viewer.primitiveList.flatMap((root) =>
collectPoints(root),
);
viewer.scene.drillPick = () => [
{ primitive: back, id: 'back' },
{ primitive: front, id: 'front' },
];
assert.deepEqual(
engine.picker.drillPick({ x: 1, y: 1 }).map(({ id }) => id),
['front'],
);
} finally {
engine.destroy();
}
});
// The PointPrimitives under a primitive collection tree.
function collectPoints(collection) {
const out = [];
for (let i = 0; i < (collection.length ?? 0); i++) {
const item = collection.get(i);
if (item instanceof Cesium.PointPrimitive) out.push(item);
else if (item?.length !== undefined) out.push(...collectPoints(item));
}
return out;
}
+2 -2
View File
@@ -1,5 +1,5 @@
// The bridge for shell callers that still hold only a Cesium viewer (layers
// until phase 1c): the engine registered for that viewer. The app registers
// The bridge for shell callers that hold only a Cesium viewer: the engine
// registered for that viewer. The app registers
// its scene engine (src/app/globeEngine.js) and unregisters it before
// destroying it. Nothing is ever built here, so no engine can outlive its
// viewer without a destroy path: an unregistered or torn-down viewer has none.
-225
View File
@@ -1,225 +0,0 @@
// engine.lines on Cesium: each line is one Primitive of a PolylineGeometry
// (built synchronously, rebuilt when its positions change) with a
// PolylineMaterialAppearance, inside one engine-owned PrimitiveCollection
// added to the scene with the first line. depthFailAlpha adds Cesium's
// depthFailAppearance (the same material, its alpha scaled) for the part
// the scene hides; dashes in pixels are PolylineDash; the tactical dash is
// the launches' selected-orbit pattern along the whole line.
import * as Cesium from 'cesium';
import { createLineRegistry } from '../lines.js';
const TACTICAL_TYPE = 'GevLineTactical';
let tacticalRegistered = false;
// The launches' GevMissionOrbitTactical shader (layers/launches/
// orbitRendering.js), under the engine's own type until Task 15a moves
// launches onto engine.lines.
function registerTactical() {
if (tacticalRegistered) return;
new Cesium.Material({
fabric: {
type: TACTICAL_TYPE,
uniforms: { color: Cesium.Color.CYAN, groupCount: 4, dashCount: 100 },
source: `
czm_material czm_getMaterial(czm_materialInput materialInput) {
czm_material material = czm_getDefaultMaterial(materialInput);
float groupPosition = fract(materialInput.st.s * groupCount);
float markPosition = groupPosition * (dashCount + 1.0);
float markIndex = floor(markPosition);
float localPosition = fract(markPosition);
float centerDistance = abs(localPosition - 0.5);
float edge = max(fwidth(localPosition) * 1.35, 0.012);
float dashAlong = 1.0 - smoothstep(0.27 - edge, 0.27 + edge, centerDistance);
float dashAcross = 1.0 - smoothstep(0.12, 0.24, abs(materialInput.st.t - 0.5));
float dash = dashAlong * dashAcross;
float dotAlong = (localPosition - 0.5) / 0.32;
float dotAcross = (materialInput.st.t - 0.5) / 0.5;
float dot = 1.0 - smoothstep(0.78, 1.0, length(vec2(dotAlong, dotAcross)));
float isDot = 1.0 - step(0.5, markIndex);
float visible = mix(dash, dot, isDot);
material.diffuse = color.rgb;
material.emission = color.rgb * mix(0.07, 0.65, isDot);
material.alpha = color.a * visible * mix(0.58, 1.0, isDot);
return material;
}`,
},
});
tacticalRegistered = true;
}
/** PolylineDash's 16-bit pattern: the dash first, then the gap. */
export function dashPattern(lengthPx, gapPx) {
const on = Math.max(
1,
Math.min(16, Math.round((16 * lengthPx) / (lengthPx + gapPx))),
);
return (0xffff << (16 - on)) & 0xffff;
}
const toColor = ([r, g, b, a], alphaScale = 1) =>
new Cesium.Color(r, g, b, a * alphaScale);
/** The Cesium material type and uniforms of a line (pure, for tests). */
export function materialSpec(options, color, alphaScale = 1) {
if (options.arrow)
return {
type: 'PolylineArrow',
uniforms: { color: toColor(color, alphaScale) },
};
const { dash } = options;
if (dash?.kind === 'pixels')
return {
type: 'PolylineDash',
uniforms: {
color: toColor(color, alphaScale),
gapColor: Cesium.Color.TRANSPARENT,
dashLength: dash.lengthPx + dash.gapPx,
dashPattern: dashPattern(dash.lengthPx, dash.gapPx),
},
};
if (dash?.kind === 'tactical')
return {
type: TACTICAL_TYPE,
uniforms: {
color: toColor(color, alphaScale),
groupCount: dash.groups,
dashCount: dash.dashes,
},
};
return { type: 'Color', uniforms: { color: toColor(color, alphaScale) } };
}
function cesiumMaterial({ type, uniforms }) {
if (type === TACTICAL_TYPE) registerTactical();
return Cesium.Material.fromType(type, uniforms);
}
const DEFAULT_FACTORIES = {
primitive: (options) => new Cesium.Primitive(options),
appearance: (spec) =>
new Cesium.PolylineMaterialAppearance({ material: cesiumMaterial(spec) }),
};
/**
* @param {Cesium.Viewer} viewer
* @param {{ requestRender?: (reason: string) => void, factories?: object }} [options]
* @returns {{ lines: import('../contract.js').GlobeLines, destroy: () => void }}
*/
export function createCesiumLines(
viewer,
{ requestRender = () => viewer.scene.requestRender(), factories = {} } = {},
) {
const make = { ...DEFAULT_FACTORIES, ...factories };
const { scene } = viewer;
let root = null;
const rootCollection = () => {
if (!root) {
root = new Cesium.PrimitiveCollection({ destroyPrimitives: true });
scene.primitives.add(root);
}
return root;
};
const registry = createLineRegistry((options) => {
rootCollection();
let color = options.color;
let modelMatrix = options.modelMatrix
? Cesium.Matrix4.fromArray(options.modelMatrix)
: Cesium.Matrix4.clone(Cesium.Matrix4.IDENTITY);
let shown = true;
let primitive = null;
let appearance = null;
let depthFail = null;
const drop = () => {
if (primitive) root.remove(primitive);
primitive = null;
};
return {
setPositions(flat) {
drop();
if (flat.length < 6) {
requestRender('lines');
return;
}
const positions = [];
for (let index = 0; index < flat.length; index += 3)
positions.push(
new Cesium.Cartesian3(
flat[index],
flat[index + 1],
flat[index + 2],
),
);
appearance = make.appearance(materialSpec(options, color));
depthFail =
options.depthFailAlpha > 0
? make.appearance(
materialSpec(options, color, options.depthFailAlpha),
)
: undefined;
primitive = make.primitive({
geometryInstances: new Cesium.GeometryInstance({
geometry: new Cesium.PolylineGeometry({
positions,
width: options.widthPx,
vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT,
arcType:
options.arc === 'geodesic'
? Cesium.ArcType.GEODESIC
: Cesium.ArcType.NONE,
}),
id: options.pickId,
}),
appearance,
depthFailAppearance: depthFail,
modelMatrix: Cesium.Matrix4.clone(modelMatrix),
show: shown,
asynchronous: false,
});
primitive.gevLine = options.id;
root.add(primitive);
requestRender('lines');
},
setColor(rgba) {
color = rgba;
if (appearance) appearance.material.uniforms.color = toColor(rgba);
if (depthFail)
depthFail.material.uniforms.color = toColor(
rgba,
options.depthFailAlpha,
);
requestRender('lines');
},
setModelMatrix(matrix) {
modelMatrix = Cesium.Matrix4.fromArray(matrix);
if (primitive)
primitive.modelMatrix = Cesium.Matrix4.clone(modelMatrix);
requestRender('lines');
},
show(visible) {
shown = visible;
if (primitive) primitive.show = visible;
requestRender('lines');
},
destroy() {
drop();
requestRender('lines');
},
};
});
return {
lines: registry.lines,
/** The line a Cesium pick result belongs to, or null. */
identify(picked) {
const owner = picked?.primitive?.gevLine;
return owner !== undefined && registry.live.has(owner) ? { owner } : null;
},
destroy() {
registry.destroyAll();
if (root) {
scene.primitives.remove(root);
root = null;
}
},
};
}
-165
View File
@@ -1,165 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createCesiumLines, dashPattern } from './lines.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
function fakePrimitives() {
const made = [];
return {
made,
factories: {
primitive: (options) => {
const primitive = {
...options,
isDestroyed: () => false,
destroy() {
primitive.destroyed = true;
},
};
made.push(primitive);
return primitive;
},
appearance: (spec) => ({
material: { type: spec.type, uniforms: { ...spec.uniforms } },
}),
},
};
}
const points = [
{ x: 6_378_137, y: 0, z: 0 },
{ x: 6_378_137, y: 1000, z: 0 },
{ x: 6_378_137, y: 2000, z: 1000 },
];
test('a dash in pixels becomes PolylineDash with a 16-bit pattern', () => {
assert.equal(dashPattern(16, 16), 0xff00);
assert.equal(dashPattern(12, 4), 0xfff0);
assert.equal(dashPattern(1, 0), 0xffff);
});
test('positions build one polyline primitive; a change rebuilds it', () => {
const viewer = createFakeViewer();
const { factories, made } = fakePrimitives();
const renders = [];
const { lines, destroy } = createCesiumLines(viewer, {
factories,
requestRender: (reason) => renders.push(reason),
});
assert.equal(viewer.scene.primitives.length, 0, 'nothing at creation');
const line = lines.createLine({
id: 'trail',
widthPx: 3,
color: [1, 0, 0, 1],
depthFailAlpha: 0.4,
arc: 'geodesic',
pickId: 'trail-1',
});
assert.equal(viewer.scene.primitives.length, 1);
assert.equal(made.length, 0, 'no primitive without positions');
line.setPositions(points);
assert.equal(made.length, 1);
const [first] = made;
const geometry = first.geometryInstances.geometry;
assert.equal(geometry._width, 3);
assert.equal(geometry._arcType, Cesium.ArcType.GEODESIC);
assert.equal(geometry._positions.length, 3);
assert.equal(first.geometryInstances.id, 'trail-1');
assert.equal(first.asynchronous, false);
assert.ok(first.depthFailAppearance, 'the dimmer copy behind the scene');
assert.ok(
Cesium.Color.equals(
first.depthFailAppearance.material.uniforms.color,
new Cesium.Color(1, 0, 0, 0.4),
),
);
line.setPositions(points.slice(0, 2));
assert.equal(made.length, 2);
assert.equal(first.destroyed, true, 'the old primitive goes');
line.setColor([0, 1, 0, 1]);
assert.ok(
Cesium.Color.equals(
made[1].appearance.material.uniforms.color,
new Cesium.Color(0, 1, 0, 1),
),
);
const turn = Cesium.Matrix4.fromRotation(Cesium.Matrix3.fromRotationZ(0.5));
line.setModelMatrix(Cesium.Matrix4.toArray(turn));
assert.ok(Cesium.Matrix4.equals(made[1].modelMatrix, turn));
line.show(false);
assert.equal(made[1].show, false);
line.setPositions(points);
assert.equal(made[2].show, false, 'a rebuild keeps show and matrix');
assert.ok(Cesium.Matrix4.equals(made[2].modelMatrix, turn));
assert.ok(renders.length >= 4);
line.destroy();
assert.equal(made[2].destroyed, true);
destroy();
assert.equal(viewer.scene.primitives.length, 0);
});
test('dash kinds pick their materials', () => {
const viewer = createFakeViewer();
const { factories, made } = fakePrimitives();
const { lines } = createCesiumLines(viewer, { factories });
lines
.createLine({
id: 'd',
widthPx: 2,
color: [1, 1, 1, 1],
dash: { lengthPx: 12, gapPx: 4 },
})
.setPositions(points);
lines
.createLine({ id: 't', widthPx: 3, color: [0, 1, 1, 1], dash: 'tactical' })
.setPositions(points);
lines
.createLine({ id: 's', widthPx: 1, color: [1, 1, 1, 1] })
.setPositions(points);
assert.equal(made[0].appearance.material.type, 'PolylineDash');
assert.equal(made[0].appearance.material.uniforms.dashLength, 16);
assert.equal(made[0].appearance.material.uniforms.dashPattern, 0xfff0);
assert.equal(made[1].appearance.material.type, 'GevLineTactical');
assert.equal(made[1].appearance.material.uniforms.groupCount, 4);
assert.equal(made[2].appearance.material.type, 'Color');
assert.equal(made[2].depthFailAppearance, undefined);
});
test('a pick of a line primitive names the line', () => {
const viewer = createFakeViewer();
const { factories, made } = fakePrimitives();
const { lines, identify } = createCesiumLines(viewer, { factories });
lines
.createLine({
id: 'orbit-25544',
widthPx: 2,
color: [1, 1, 1, 1],
pickId: 'o',
})
.setPositions(points);
assert.deepEqual(identify({ primitive: made[0], id: 'o' }), {
owner: 'orbit-25544',
});
assert.equal(identify({ primitive: {}, id: 'o' }), null);
});
test('arrow lines retain the native arrow material in both depth passes', () => {
const { factories, made } = fakePrimitives();
const { lines, destroy } = createCesiumLines(createFakeViewer(), {
factories,
});
lines
.createLine({
id: 'arrow',
widthPx: 8,
color: [1, 0, 0, 1],
arrow: true,
depthFailAlpha: 0.45,
})
.setPositions(points);
assert.equal(made[0].appearance.material.type, 'PolylineArrow');
assert.equal(made[0].depthFailAppearance.material.type, 'PolylineArrow');
assert.equal(made[0].depthFailAppearance.material.uniforms.color.alpha, 0.45);
destroy();
});
-365
View File
@@ -1,365 +0,0 @@
// engine.movers on Cesium: one primitive per set inside one engine-owned
// PrimitiveCollection (added to the scene with the first set, in `order`):
// sprites are a BillboardCollection (screen-aligned, rotation in screen
// space, an image per atlas cell), points a PointPrimitiveCollection,
// models one Model per instance in a PrimitiveCollection. commit() writes
// the changed instances and requests a render; nothing else renders.
import * as Cesium from 'cesium';
import { createMoverRegistry } from '../movers.js';
let scratchPosition;
let scratchColor;
let scratchQuaternion;
let scratchRotation;
// Model.modelMatrix and Model.color copy what they are given.
let scratchModelMatrix;
/** The atlas cells as canvases, by key (a DOM canvas or image source). */
async function cropAtlasCells(atlas, keys) {
let image = atlas.canvas;
if (!image) {
image = new Image();
image.crossOrigin = 'anonymous';
image.src = atlas.url;
await image.decode();
}
const width = image.width;
const height = image.height;
const cells = new Map();
for (const key of keys) {
const [u0, v0, u1, v1] = atlas.cells[key];
const canvas = document.createElement('canvas');
canvas.width = Math.max(1, Math.round((u1 - u0) * width));
canvas.height = Math.max(1, Math.round((v1 - v0) * height));
canvas
.getContext('2d')
.drawImage(
image,
u0 * width,
v0 * height,
canvas.width,
canvas.height,
0,
0,
canvas.width,
canvas.height,
);
cells.set(key, canvas);
}
return cells;
}
const DEFAULT_FACTORIES = {
billboards: (scene) => new Cesium.BillboardCollection({ scene }),
points: () => new Cesium.PointPrimitiveCollection(),
models: () => new Cesium.PrimitiveCollection({ destroyPrimitives: true }),
loadModel: (options) => Cesium.Model.fromGltfAsync(options),
cropCells: cropAtlasCells,
};
const depthTestDistance = (depthTest) =>
depthTest === 'always'
? Number.POSITIVE_INFINITY
: depthTest === 'normal'
? 0
: depthTest.disableWithinM;
const nearFar = (value) =>
value ? new Cesium.NearFarScalar(...value) : undefined;
function readPosition(store, index) {
const { positions } = store;
return Cesium.Cartesian3.fromElements(
positions[index * 3],
positions[index * 3 + 1],
positions[index * 3 + 2],
scratchPosition,
);
}
function readColor(store, index) {
const { colors } = store;
scratchColor.red = colors[index * 4];
scratchColor.green = colors[index * 4 + 1];
scratchColor.blue = colors[index * 4 + 2];
scratchColor.alpha = colors[index * 4 + 3];
return scratchColor;
}
function spritePart(scene, options, store, factories, requestRender, owners) {
const collection = factories.billboards(scene);
const { sprite, depthTest, id } = options;
const style = {
width: sprite.sizePx,
height: sprite.sizePx,
scaleByDistance: nearFar(sprite.scaleByDistance),
disableDepthTestDistance: depthTestDistance(depthTest),
};
const billboards = [];
const shownCell = [];
let cells = null;
let destroyed = false;
const apply = (from, to) => {
for (let index = from; index < to; index++) {
let billboard = billboards[index];
if (index >= store.count) {
if (billboard) billboard.show = false;
continue;
}
if (!billboard) {
billboard = collection.add({ ...style });
billboards[index] = billboard;
owners.set(billboard, { owner: id, instance: index });
shownCell[index] = -1;
}
billboard.position = readPosition(store, index);
billboard.rotation = store.rotations[index];
billboard.scale = store.scales[index];
billboard.color = readColor(store, index);
billboard.show = store.shows[index] === 1;
billboard.id = store.pickIds[index];
const cell = store.cells[index];
if (shownCell[index] !== cell) {
const key = store.cellKeys[cell];
billboard.setImage(`${id}:${key}`, cells.get(key));
shownCell[index] = cell;
}
}
};
// Instances wait for the atlas; then everything drawn so far is applied.
factories
.cropCells(sprite.atlas, store.cellKeys)
.then((ready) => {
if (destroyed) return;
cells = ready;
apply(0, Math.max(store.count, billboards.length));
requestRender('movers');
})
.catch((error) => console.warn(`[movers] ${id}: atlas failed`, error));
return {
primitive: collection,
ready: () => cells !== null,
commit(range) {
if (cells && range) apply(range.from, range.to);
requestRender('movers');
},
destroy() {
destroyed = true;
billboards.length = 0;
shownCell.length = 0;
cells = null;
},
};
}
function pointPart(options, store, factories, requestRender, owners) {
const collection = factories.points();
const { point, depthTest } = options;
const style = {
outlineWidth: point.outlinePx,
outlineColor: new Cesium.Color(...point.outlineColor),
scaleByDistance: nearFar(point.scaleByDistance),
translucencyByDistance: nearFar(point.translucencyByDistance),
disableDepthTestDistance: depthTestDistance(depthTest),
};
const points = [];
return {
primitive: collection,
commit(range) {
if (range)
for (let index = range.from; index < range.to; index++) {
let item = points[index];
if (index >= store.count) {
if (item) item.show = false;
continue;
}
if (!item) {
item = collection.add({ ...style });
points[index] = item;
owners.set(item, { owner: options.id, instance: index });
}
item.position = readPosition(store, index);
item.pixelSize = point.sizePx * store.scales[index];
item.color = readColor(store, index);
item.show = store.shows[index] === 1;
item.id = store.pickIds[index];
}
requestRender('movers');
},
destroy() {
points.length = 0;
},
};
}
function modelPart(options, store, factories, requestRender, owners) {
const collection = factories.models();
const { model } = options;
const blendMode =
model.colorBlend?.mode === 'replace'
? Cesium.ColorBlendMode.REPLACE
: Cesium.ColorBlendMode.MIX;
const models = [];
const loading = [];
let destroyed = false;
const place = (item, index) => {
const { orientations } = store;
scratchQuaternion.x = orientations[index * 4];
scratchQuaternion.y = orientations[index * 4 + 1];
scratchQuaternion.z = orientations[index * 4 + 2];
scratchQuaternion.w = orientations[index * 4 + 3];
item.modelMatrix = Cesium.Matrix4.fromRotationTranslation(
Cesium.Matrix3.fromQuaternion(scratchQuaternion, scratchRotation),
readPosition(store, index),
scratchModelMatrix,
);
item.scale = store.scales[index];
item.show = index < store.count && store.shows[index] === 1;
item.id = store.pickIds[index];
if (model.colorBlend) item.color = readColor(store, index);
};
const ensure = (index) => {
if (models[index] || loading[index]) return;
loading[index] = true;
factories
.loadModel({
url: model.url,
minimumPixelSize: model.minimumPixelSize,
maximumScale: Number.isFinite(model.maximumScale)
? model.maximumScale
: undefined,
colorBlendMode: blendMode,
colorBlendAmount: model.colorBlend?.amount ?? 0.5,
...(model.unlit
? {
customShader: new Cesium.CustomShader({
lightingModel: Cesium.LightingModel.UNLIT,
}),
}
: {}),
})
.then((item) => {
if (destroyed) {
item.destroy?.();
return;
}
models[index] = item;
owners.set(item, { owner: options.id, instance: index });
place(item, index);
collection.add(item);
requestRender('movers');
})
.catch((error) =>
console.warn(`[movers] ${options.id}: model failed`, error),
);
};
return {
primitive: collection,
ready() {
for (let index = 0; index < store.count; index++)
if (!models[index]?.ready) return false;
return true;
},
commit(range) {
if (range)
for (let index = range.from; index < range.to; index++) {
if (index < store.count) ensure(index);
if (models[index]) place(models[index], index);
}
requestRender('movers');
},
destroy() {
destroyed = true;
models.length = 0;
loading.length = 0;
},
};
}
/**
* @param {Cesium.Viewer} viewer
* @param {{ requestRender?: (reason: string) => void, factories?: object }} [options]
* `factories` (collections, model loading, atlas cropping) is a test seam.
* @returns {{ movers: import('../contract.js').GlobeMovers, destroy: () => void }}
*/
export function createCesiumMovers(
viewer,
{ requestRender = () => viewer.scene.requestRender(), factories = {} } = {},
) {
scratchPosition ??= new Cesium.Cartesian3();
scratchColor ??= new Cesium.Color();
scratchQuaternion ??= new Cesium.Quaternion();
scratchRotation ??= new Cesium.Matrix3();
scratchModelMatrix ??= new Cesium.Matrix4();
const make = { ...DEFAULT_FACTORIES, ...factories };
const { scene } = viewer;
let root = null;
const ordered = [];
// Billboard, point or model → its set and instance, for picks.
const owners = new WeakMap();
const rootCollection = () => {
if (!root) {
root = new Cesium.PrimitiveCollection({ destroyPrimitives: true });
scene.primitives.add(root);
}
return root;
};
const registry = createMoverRegistry((options, store) => {
const part =
options.kind === 'sprite'
? spritePart(scene, options, store, make, requestRender, owners)
: options.kind === 'point'
? pointPart(options, store, make, requestRender, owners)
: modelPart(options, store, make, requestRender, owners);
const { primitive } = part;
primitive.gevMoverSet = options.id;
// Later (higher) order draws later: after every set of lower or equal order.
const at = ordered.filter((entry) => entry.order <= options.order).length;
ordered.splice(at, 0, { order: options.order, primitive });
rootCollection().add(primitive, at);
return {
primitive,
ready: part.ready,
commit: () => part.commit(store.dirty()),
destroy() {
part.destroy();
ordered.splice(
ordered.findIndex((entry) => entry.primitive === primitive),
1,
);
root.remove(primitive);
requestRender('movers');
},
};
});
return {
movers: registry.movers,
/** Where an instance of a set is (a geo Cartesian3), or null. */
instancePosition(owner, instance) {
const entry = registry.sets.get(owner);
if (!entry || !(instance < entry.store.count)) return null;
const view = entry.store.positionsView();
const at = 3 * instance;
return { x: view[at], y: view[at + 1], z: view[at + 2] };
},
/** The primitive drawing a live mover set of this engine, or null. */
primitiveOf(set) {
const entry = set?.id ? registry.sets.get(set.id) : null;
return entry && entry.set === set ? entry.part.primitive : null;
},
/** The set and instance a Cesium pick result belongs to, or null. */
identify(picked) {
const known = picked?.primitive ? owners.get(picked.primitive) : null;
const entry = known && registry.sets.get(known.owner);
return entry ? { ...known, pickable: entry.options.pickable } : null;
},
destroy() {
registry.destroyAll();
if (root) {
scene.primitives.remove(root);
root = null;
}
},
};
}
-248
View File
@@ -1,248 +0,0 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import * as Cesium from 'cesium';
import { createCesiumMovers } from './movers.js';
import { createFakeViewer } from './testing/fakeViewer.mjs';
// Collections that keep what the engine gives them (Cesium's own need a
// WebGL scene to add billboards).
function fakeFactories() {
const made = [];
const collection = (kind) => {
const items = [];
const value = {
kind,
items,
show: true,
add(options) {
// Cesium's billboards and points copy positions and colours.
let position;
let color;
const item = {
...options,
get position() {
return position;
},
set position(value) {
position = Cesium.Cartesian3.clone(value);
},
get color() {
return color;
},
set color(value) {
color = Cesium.Color.clone(value);
},
images: [],
setImage(id, image) {
this.images.push(id);
this.image = image;
},
};
items.push(item);
return item;
},
remove(item) {
items.splice(items.indexOf(item), 1);
return true;
},
get length() {
return items.length;
},
isDestroyed: () => false,
destroy() {
value.destroyed = true;
},
};
made.push(value);
return value;
};
return {
made,
factories: {
billboards: () => collection('billboards'),
points: () => collection('points'),
models: () => collection('models'),
loadModel: async (options) => ({ ...options, loaded: true }),
cropCells: async (atlas, keys) =>
new Map(keys.map((key) => [key, { cell: key }])),
},
};
}
const atlas = {
canvas: { width: 64, height: 32 },
cells: { jet: [0, 0, 0.5, 1], heli: [0.5, 0, 1, 1] },
};
const at = (x) => ({ x, y: 0, z: 6_400_000 });
const settle = () => new Promise((resolve) => setTimeout(resolve, 0));
test('creating the movers changes nothing; the first set adds one root collection', () => {
const viewer = createFakeViewer();
const { factories } = fakeFactories();
const { movers, destroy } = createCesiumMovers(viewer, { factories });
assert.equal(viewer.scene.primitives.length, 0);
movers.createSet({
id: 'a',
kind: 'point',
capacity: 2,
point: { sizePx: 4 },
});
assert.equal(viewer.scene.primitives.length, 1);
destroy();
assert.equal(viewer.scene.primitives.length, 0);
});
test('sprites become billboards with the set style once the atlas cells are ready', async () => {
const viewer = createFakeViewer();
const { factories, made } = fakeFactories();
const requests = [];
const { movers } = createCesiumMovers(viewer, {
factories,
requestRender: (reason) => requests.push(reason),
});
const set = movers.createSet({
id: 'flights',
kind: 'sprite',
capacity: 3,
depthTest: 'always',
sprite: { atlas, sizePx: 20, scaleByDistance: [1e3, 1, 1e6, 0.5] },
});
set.set(0, { position: at(1), rotation: 0.25, cell: 'heli', pickId: 'x1' });
set.set(1, { position: at(2), color: [1, 0, 0, 0.5], scale: 2, show: false });
set.setCount(2);
set.commit();
const billboards = made.find(
(collection) => collection.kind === 'billboards',
);
assert.equal(billboards.items.length, 0, 'waits for the atlas');
await settle();
assert.equal(billboards.items.length, 2);
const [first, second] = billboards.items;
assert.ok(first.position instanceof Cesium.Cartesian3);
assert.equal(first.position.x, 1);
assert.equal(first.width, 20);
assert.equal(first.height, 20);
assert.equal(first.rotation, 0.25);
assert.equal(first.id, 'x1');
assert.equal(first.disableDepthTestDistance, Number.POSITIVE_INFINITY);
assert.ok(first.scaleByDistance instanceof Cesium.NearFarScalar);
assert.deepEqual(first.images, ['flights:heli']);
assert.equal(first.show, true);
assert.equal(second.show, false);
assert.equal(second.scale, 2);
assert.ok(Cesium.Color.equals(second.color, new Cesium.Color(1, 0, 0, 0.5)));
assert.ok(requests.length >= 1);
// Lowering the count hides the instances past it.
set.setCount(1);
set.commit();
assert.equal(second.show, false);
set.set(0, { cell: 'heli' });
set.commit();
assert.deepEqual(
first.images,
['flights:heli'],
'the same cell is not re-sent',
);
});
test('points take the size, outline and depth test of the set', () => {
const viewer = createFakeViewer();
const { factories, made } = fakeFactories();
const { movers } = createCesiumMovers(viewer, { factories });
const set = movers.createSet({
id: 'sats',
kind: 'point',
capacity: 2,
depthTest: { disableWithinM: 5000 },
point: { sizePx: 4, outlinePx: 1 },
});
set.set(0, { position: at(3), scale: 1.5, color: [0, 1, 0, 1] });
set.setCount(1);
set.commit();
const [point] = made.find((c) => c.kind === 'points').items;
assert.equal(point.pixelSize, 6);
assert.equal(point.outlineWidth, 1);
assert.equal(point.disableDepthTestDistance, 5000);
assert.ok(Cesium.Color.equals(point.color, new Cesium.Color(0, 1, 0, 1)));
});
test('sets are ordered in the root by their order', () => {
const viewer = createFakeViewer();
const { factories } = fakeFactories();
const { movers } = createCesiumMovers(viewer, { factories });
const make = (id, order) =>
movers.createSet({
id,
kind: 'point',
capacity: 1,
order,
point: { sizePx: 2 },
});
make('top', 5);
make('bottom', -1);
make('middle', 0);
const root = viewer.scene.primitives.get(0);
assert.deepEqual(
[0, 1, 2].map((index) => root.get(index).gevMoverSet),
['bottom', 'middle', 'top'],
);
});
test('models load per instance and follow position and orientation', async () => {
const viewer = createFakeViewer();
const { factories, made } = fakeFactories();
const { movers } = createCesiumMovers(viewer, { factories });
const set = movers.createSet({
id: 'models',
kind: 'model',
capacity: 2,
model: {
url: '/models/airplane.glb',
minimumPixelSize: 24,
colorBlend: { mode: 'mix', amount: 0.4 },
},
});
set.set(0, {
position: at(4),
orientation: { x: 0, y: 0, z: 0, w: 1 },
color: [1, 0.5, 0, 1],
});
set.setCount(1);
set.commit();
await settle();
const models = made.find((c) => c.kind === 'models');
assert.equal(models.items.length, 1);
const [model] = models.items;
assert.equal(model.url, '/models/airplane.glb');
assert.equal(model.minimumPixelSize, 24);
assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.MIX);
assert.equal(model.colorBlendAmount, 0.4);
assert.equal(model.modelMatrix[12], 4);
set.destroy();
assert.equal(models.destroyed, true);
});
test('a pick of a billboard or point names its set and instance', async () => {
const viewer = createFakeViewer();
const { factories, made } = fakeFactories();
const { movers, identify } = createCesiumMovers(viewer, { factories });
const set = movers.createSet({
id: 'sats',
kind: 'point',
capacity: 3,
point: { sizePx: 4 },
});
set.set(0, { position: at(1) });
set.set(1, { position: at(2), pickId: 25544 });
set.setCount(2);
set.commit();
const [, second] = made.find((c) => c.kind === 'points').items;
assert.deepEqual(identify({ primitive: second, id: 25544 }), {
owner: 'sats',
instance: 1,
pickable: false,
});
assert.equal(identify({ primitive: {}, id: 'x' }), null);
set.destroy();
assert.equal(identify({ primitive: second, id: 25544 }), null);
});
+4 -31
View File
@@ -6,44 +6,18 @@ import { toCesium2, toGeo3 } from './convert.js';
/**
* @param {Cesium.Viewer} viewer
* @param {{
* identify?: (picked: object) => ({ owner: string, instance?: number, pickable?: boolean } | null),
* visible?: (known: { owner: string, instance?: number }) => boolean,
* }} [options]
* `identify` names the mover set or line (and instance) a pick belongs to;
* `visible` says whether that instance is in front of the horizon
* (Cesium's GPU pick sees billboards drawn without a depth test through
* the globe).
* @returns {{ picker: object, destroy: () => void }}
*/
export function createCesiumPicker(
viewer,
{ identify = () => null, visible = () => true } = {},
) {
export function createCesiumPicker(viewer) {
const normalise = (picked) => {
if (picked == null) return undefined;
// The follow camera's proxy entity (follow.js) is not an object.
if (picked.id?.gevFollowProxy) return undefined;
const known = identify(picked);
// A mover set created with pickable: false is not picked (Cesium's GPU
// pick sees every primitive; Navara's only the pickable ones), nor an
// instance behind the horizon.
if (known?.pickable === false) return undefined;
if (known && known.instance !== undefined && !visible(known))
return undefined;
return {
id: picked.id,
primitive: picked.primitive,
content: picked.content,
object: picked,
...(known
? {
owner: known.owner,
...(known.instance !== undefined
? { instance: known.instance }
: {}),
}
: {}),
};
};
const { scene } = viewer;
@@ -58,8 +32,8 @@ export function createCesiumPicker(
if (top == null) return undefined;
const picked = normalise(top);
if (picked) return picked;
// The top result is filtered: what lies under it, the first with an
// id (an object), else the first kept (map tiles).
// The top result is the follow proxy: what lies under it, the first
// with an id (an object), else the first kept (map tiles).
const under = drill(screen, undefined, width, height);
return under.find((entry) => entry.id !== undefined) ?? under[0];
},
@@ -81,8 +55,7 @@ export function createCesiumPicker(
pickGlobe(screen) {
if (!scene.globe) return undefined;
try {
const camera = viewer.camera ?? scene.camera;
const ray = camera.getPickRay(toCesium2(screen));
const ray = viewer.camera.getPickRay(toCesium2(screen));
return ray ? toGeo3(scene.globe.pick(ray, scene)) : undefined;
} catch {
return undefined;
+7 -81
View File
@@ -114,97 +114,23 @@ test('pickGlobe asks the globe along the camera pick ray and returns geo', () =>
assert.equal(picker.pickGlobe(geo.cartesian2.create(1, 1)), undefined);
});
test('picks of movers and lines name their owner and instance', () => {
test('a follow-proxy top pick falls through to the first pick under it with an id', () => {
const viewer = createFakeViewer();
const billboard = { id: 'ae01ce' };
viewer.scene.pick = () => ({ primitive: billboard, id: 'ae01ce' });
viewer.scene.drillPick = () => [
{ primitive: billboard, id: 'ae01ce' },
{ primitive: {}, id: 'other' },
];
const { picker } = createCesiumPicker(viewer, {
identify: (raw) =>
raw.primitive === billboard ? { owner: 'flights', instance: 7 } : null,
});
const picked = picker.pick({ x: 1, y: 2 });
assert.equal(picked.id, 'ae01ce');
assert.equal(picked.owner, 'flights');
assert.equal(picked.instance, 7);
const drilled = picker.drillPick({ x: 1, y: 2 }, 5);
assert.equal(drilled[0].owner, 'flights');
assert.equal(drilled[1].owner, undefined);
});
test('picks of a mover set made with pickable: false are dropped', () => {
const viewer = createFakeViewer();
const quiet = { id: 'q' };
viewer.scene.pick = () => ({ primitive: quiet, id: 'q' });
viewer.scene.drillPick = () => [
{ primitive: quiet, id: 'q' },
{ primitive: {}, id: 'other' },
];
const { picker } = createCesiumPicker(viewer, {
identify: (raw) =>
raw.primitive === quiet
? { owner: 'quiet', instance: 0, pickable: false }
: null,
});
// The pick falls through to what is under the quiet set.
assert.equal(picker.pick({ x: 1, y: 2 }).id, 'other');
assert.deepEqual(
picker.drillPick({ x: 1, y: 2 }, 5).map(({ id }) => id),
['other'],
);
});
test('a filtered top pick falls through to the first pick under it with an id', () => {
const viewer = createFakeViewer();
const quiet = { primitive: 'quiet-billboard', id: 'q' };
const proxy = { primitive: 'proxy-point', id: { gevFollowProxy: true } };
const tile = { primitive: 'tileset', content: {} };
const flight = { primitive: 'flight-billboard', id: 'ae01ce' };
const { picker } = createCesiumPicker(viewer, {
identify: (picked) =>
picked === quiet
? { owner: 'quiet', instance: 0, pickable: false }
: picked === flight
? { owner: 'flights', instance: 3, pickable: true }
: null,
});
viewer.scene.pick = () => quiet;
viewer.scene.drillPick = () => [quiet, proxy, tile, flight];
const picked = picker.pick(geo.cartesian2.create(1, 1));
assert.equal(picked.id, 'ae01ce');
assert.equal(picked.owner, 'flights');
const { picker } = createCesiumPicker(viewer);
viewer.scene.pick = () => proxy;
viewer.scene.drillPick = () => [proxy, tile, flight];
assert.equal(picker.pick(geo.cartesian2.create(1, 1)).id, 'ae01ce');
assert.deepEqual(
picker.drillPick(geo.cartesian2.create(1, 1)).map((p) => p.primitive),
['tileset', 'flight-billboard'],
'the follow proxy and pickable: false sets are never picked',
'the follow proxy is never picked',
);
// Nothing under it with an id: the first kept result (a tile).
viewer.scene.drillPick = () => [quiet, tile];
viewer.scene.drillPick = () => [proxy, tile];
assert.equal(picker.pick(geo.cartesian2.create(1, 1)).primitive, 'tileset');
viewer.scene.pick = () => proxy;
viewer.scene.drillPick = () => [proxy];
assert.equal(picker.pick(geo.cartesian2.create(1, 1)), undefined);
});
test('drills leave out mover instances behind the horizon', () => {
const viewer = createFakeViewer();
const near = { primitive: 'near', id: 'n' };
const far = { primitive: 'far', id: 'f' };
const { picker } = createCesiumPicker(viewer, {
identify: (picked) => ({
owner: 'flights',
instance: picked === near ? 0 : 1,
}),
visible: (known) => known.instance === 0,
});
viewer.scene.drillPick = () => [far, near];
assert.deepEqual(
picker.drillPick(geo.cartesian2.create(1, 1)).map((p) => p.id),
['n'],
);
viewer.scene.pick = () => far;
assert.equal(picker.pick(geo.cartesian2.create(1, 1)).id, 'n');
});
+1 -3
View File
@@ -15,9 +15,7 @@ export function createCesiumProjector(
worldToWindowCoordinates = Cesium.SceneTransforms.worldToWindowCoordinates,
} = {},
) {
const { scene } = viewer;
// Viewer.camera is scene.camera; the engine reads the public alias.
const camera = viewer.camera ?? scene.camera;
const { scene, camera } = viewer;
const scratchWindow = new Cesium.Cartesian2();
const scratchMatrix = new Cesium.Matrix4();
const occluder = new Cesium.EllipsoidalOccluder(Cesium.Ellipsoid.WGS84);
+5 -43
View File
@@ -1,11 +1,5 @@
// GlobeSurface on a Cesium scene: the rendered-surface queries that
// services/groundSnap and services/meshFloorSampler make.
//
// `exclude` takes the engine's own mover sets (engine.movers) as well as
// Cesium objects: Cesium's sampleHeight matches excluded objects by the
// picked primitive, which for a set is each billboard, point or model, so a
// set is hidden for the sample instead (synchronous: nothing draws in
// between) and shown again after it.
import { firstVisibleTileset } from '../../services/groundSnap.js';
import { normalizeSurfaceOptions } from '../surfaceDetail.js';
@@ -15,46 +9,16 @@ const finite = (value) => (Number.isFinite(value) ? value : undefined);
/**
* @param {Cesium.Viewer} viewer
* @param {{ engineExclude?: (entry: any) => ({ show: boolean } | null) }} [options]
* `engineExclude` maps an engine object (a mover set) to the Cesium
* primitive that draws it, or null for a Cesium object.
* @returns {{ surface: import('../contract.js').GlobeSurface, destroy: () => void }}
*/
export function createCesiumSurface(
viewer,
{ engineExclude = () => null } = {},
) {
export function createCesiumSurface(viewer) {
const { scene } = viewer;
// Runs `query(nativeExclude)` with the engine objects in `exclude` hidden.
function excluding(exclude, query) {
if (!exclude?.length) return query(exclude);
let native = exclude;
const hidden = [];
for (const entry of exclude) {
const primitive = engineExclude(entry);
if (!primitive) continue;
if (native === exclude)
native = exclude.filter((other) => !engineExclude(other));
if (primitive.show) {
primitive.show = false;
hidden.push(primitive);
}
}
try {
return query(native);
} finally {
for (const primitive of hidden) primitive.show = true;
}
}
const sampleHeight = (cartographic, exclude) => {
if (!scene.sampleHeightSupported) return undefined;
try {
// Throws when unsupported (no depth textures); that is a miss.
return excluding(exclude, (native) =>
finite(scene.sampleHeight(cartographic, native)),
);
return finite(scene.sampleHeight(cartographic, exclude));
} catch {
return undefined;
}
@@ -64,8 +28,8 @@ export function createCesiumSurface(
const surface = {
sampleHeight,
// Cesium samples the tiles it has loaded (lod 'finest' cannot do better
// synchronously) and does not say which tile answered.
// Cesium samples the tiles it has loaded and does not say which tile
// answered.
sampleHeightDetailed(cartographic, options) {
const { exclude } = normalizeSurfaceOptions(options);
const height = sampleHeight(cartographic, exclude);
@@ -85,9 +49,7 @@ export function createCesiumSurface(
clampToHeight(position, exclude) {
if (!scene.clampToHeightSupported) return undefined;
try {
return excluding(exclude, (native) =>
toGeo3(scene.clampToHeight(position, native)),
);
return toGeo3(scene.clampToHeight(position, exclude));
} catch {
return undefined;
}
+2 -25
View File
@@ -93,35 +93,12 @@ test('sampleHeightDetailed: tiles from sampleHeight, else terrain; no tile size'
source: 'tiles',
});
scene.sampleHeight = () => undefined;
assert.deepEqual(surface.sampleHeightDetailed(place, { lod: 'finest' }), {
assert.deepEqual(surface.sampleHeightDetailed(place), {
height: 12.5,
source: 'terrain',
});
assert.throws(
() => surface.sampleHeightDetailed(place, { lod: 2 }),
() => surface.sampleHeightDetailed(place, { exclude: 'x' }),
TypeError,
);
});
test('an engine mover set in exclude is hidden for the sample, native objects pass', () => {
const viewer = createFakeViewer();
const collection = { show: true };
const set = { id: 'flights' };
const { surface } = createCesiumSurface(viewer, {
engineExclude: (entry) => (entry === set ? collection : null),
});
const shownDuring = [];
viewer.scene.sampleHeight = (position, excluded) => {
shownDuring.push(collection.show, excluded);
return 30;
};
const native = { primitive: 1 };
const place = geo.cartographic.fromDegrees(20, 10, 0);
assert.equal(surface.sampleHeight(place, [set, native]), 30);
assert.deepEqual(shownDuring, [false, [native]]);
assert.equal(collection.show, true, 'shown again after the sample');
shownDuring.length = 0;
surface.sampleHeightDetailed(place, { exclude: [set] });
assert.deepEqual(shownDuring, [false, []]);
assert.equal(collection.show, true);
});