fix(globe): tighten the Cesium engine after review

Map sources are applied through one src/maps/sceneApply.js helper shared by MapSourceController and engine.maps (live layer kept for an unchanged provider, providers cached per source). The contract gains flyTo endTransform and rectangle destinations, flyToSphere easing, drillPick width/height and pick content, with Cesium's own flyToSphere range. Input skips listeners removed during dispatch and stays inert after destroy.
This commit is contained in:
German Khokhlov committed 2026-10-15 17:55:00 +04:00
1 parent d831cbd23a
commit ab2368f3f3
18 files changed
+658 -117

No files matched your search

+23 -16
View File
@@ -7,7 +7,6 @@ import { bridgeEvent } from './events.js';
import { toCesium2, toCesium3, toGeo3 } from './convert.js';
const { math } = geo;
const MINIMUM_SPHERE_RANGE = 100; // Cesium's MINIMUM_ZOOM for flyToBoundingSphere
const EASINGS = {
cubicInOut: Cesium.EasingFunction.CUBIC_IN_OUT,
sinusoidalInOut: Cesium.EasingFunction.SINUSOIDAL_IN_OUT,
@@ -31,6 +30,19 @@ function cesiumOrientation(orientation) {
return { heading, pitch, roll };
}
// A Cartesian3, or a {west, south, east, north} rectangle in radians.
const cesiumDestination = (destination) =>
'west' in destination
? new Cesium.Rectangle(
destination.west,
destination.south,
destination.east,
destination.north,
)
: toCesium3(destination);
const cesiumEasing = (easing) => (easing ? EASINGS[easing] : undefined);
// A HeadingPitchRange or a Cartesian offset, as Cesium's lookAt takes them.
const cesiumOffset = (offset) =>
'heading' in offset
@@ -102,7 +114,7 @@ export function createCesiumCamera(viewer) {
if (!view?.destination)
throw new TypeError('setView needs a destination');
cesium.setView({
destination: toCesium3(view.destination),
destination: cesiumDestination(view.destination),
orientation: cesiumOrientation(view.orientation),
});
},
@@ -111,27 +123,21 @@ export function createCesiumCamera(viewer) {
throw new TypeError('flyTo needs a destination');
startFlight(options, ({ complete, cancel }) =>
cesium.flyTo({
destination: toCesium3(options.destination),
destination: cesiumDestination(options.destination),
orientation: cesiumOrientation(options.orientation),
duration: options.duration,
easingFunction: options.easing ? EASINGS[options.easing] : undefined,
easingFunction: cesiumEasing(options.easing),
endTransform: options.endTransform
? Cesium.Matrix4.fromArray(options.endTransform)
: undefined,
complete,
cancel,
}),
);
},
flyToSphere(sphere, options = {}) {
let range = options.range;
if (!range) {
const { fovy, aspectRatio } = cesium.frustum;
const tanPhi = Math.tan(fovy / 2);
const tanTheta = aspectRatio * tanPhi;
range = Math.max(
MINIMUM_SPHERE_RANGE,
sphere.radius / tanTheta,
sphere.radius / tanPhi,
);
}
// A missing or 0 range is Cesium's own: it fits the sphere in view and
// clamps to the camera controller's zoom distances.
startFlight(options, ({ complete, cancel }) =>
cesium.flyToBoundingSphere(
new Cesium.BoundingSphere(toCesium3(sphere.center), sphere.radius),
@@ -139,9 +145,10 @@ export function createCesiumCamera(viewer) {
offset: new Cesium.HeadingPitchRange(
options.heading ?? 0,
options.pitch ?? -Math.PI / 4,
range,
options.range ?? 0,
),
duration: options.duration,
easingFunction: cesiumEasing(options.easing),
complete,
cancel,
},
+52 -11
View File
@@ -149,7 +149,7 @@ test('a newer flight cancels the previous one and stays active', () => {
});
test('flyToSphere builds a BoundingSphere and an offset with Cesium defaults', () => {
const { viewer, camera, cesium } = setup();
const { viewer, camera } = setup();
const center = geo.cartesian3.fromDegrees(2.35, 48.85, 100);
let done = false;
camera.flyToSphere(
@@ -166,24 +166,26 @@ test('flyToSphere builds a BoundingSphere and an offset with Cesium defaults', (
assert.ok(options.offset instanceof Cesium.HeadingPitchRange);
assert.equal(options.offset.heading, 0);
assert.equal(options.offset.pitch, -Math.PI / 4);
const tanPhi = Math.tan(cesium.frustum.fovy / 2);
const tanTheta = cesium.frustum.aspectRatio * tanPhi;
assert.equal(
options.offset.range,
Math.max(100, 1000 / tanTheta, 1000 / tanPhi),
0,
"a missing range is left to Cesium's own fit and zoom-distance clamp",
);
assert.equal(options.duration, 0);
assert.equal(options.easingFunction, undefined);
camera.flyToSphere({ center, radius: 0 }, { duration: 0 });
assert.equal(
viewer.callsOf('camera.flyToBoundingSphere')[1].args[1].offset.range,
100,
);
camera.flyToSphere(
{ center, radius: 10 },
{ heading: 0.3, pitch: -0.5, range: 5000, duration: 2 },
{
heading: 0.3,
pitch: -0.5,
range: 5000,
duration: 2,
easing: 'linear',
},
);
const explicit = viewer.callsOf('camera.flyToBoundingSphere')[2].args[1];
const explicit = viewer.callsOf('camera.flyToBoundingSphere')[1].args[1];
assert.equal(explicit.easingFunction, Cesium.EasingFunction.LINEAR_NONE);
assert.deepEqual(
[explicit.offset.heading, explicit.offset.pitch, explicit.offset.range],
[0.3, -0.5, 5000],
@@ -305,3 +307,42 @@ test('destroy cancels the engine flight and drops Cesium subscriptions', () => {
assert.deepEqual(outcome, ['cancel']);
assert.equal(cesium.changed.numberOfListeners, 0);
});
test('flyTo passes endTransform as a Cesium Matrix4', () => {
const { viewer, camera } = setup();
camera.flyTo({
destination: geo.cartesian3.fromDegrees(0, 0, 1e6),
duration: 0,
endTransform: geo.matrix4.IDENTITY,
});
const [options] = viewer.callsOf('camera.flyTo')[0].args;
assert.ok(options.endTransform instanceof Cesium.Matrix4);
assert.deepEqual(Cesium.Matrix4.toArray(options.endTransform), [
...geo.matrix4.IDENTITY,
]);
camera.flyTo({ destination: geo.cartesian3.fromDegrees(0, 0, 1e6) });
assert.equal(
viewer.callsOf('camera.flyTo')[1].args[0].endTransform,
undefined,
);
});
test('rectangle destinations become a Cesium.Rectangle in flyTo and setView', () => {
const { viewer, camera } = setup();
const rectangle = { west: -0.2, south: 0.6, east: -0.1, north: 0.7 };
camera.flyTo({ destination: rectangle, duration: 0 });
camera.setView({ destination: rectangle });
for (const name of ['camera.flyTo', 'camera.setView']) {
const { destination } = viewer.callsOf(name)[0].args[0];
assert.ok(destination instanceof Cesium.Rectangle, name);
assert.deepEqual(
[
destination.west,
destination.south,
destination.east,
destination.north,
],
[-0.2, 0.6, -0.1, 0.7],
);
}
});
+4
View File
@@ -23,6 +23,10 @@ import { createCesiumSurface } from './surface.js';
* loadPhotorealTileset?: Function,
* }} [options] `requestRender` defaults to the render governor; the
* `create*`/`load*` options are test seams.
*
* `render.setContinuous` takes a hold on the app's singleton renderGovernor
* (src/renderGovernor.js), which governs the one viewer it was installed on;
* so one Cesium engine per page, on that viewer.
* @returns {import('../contract.js').GlobeEngine}
*/
export function createCesiumEngine(viewer, options = {}) {
+5 -1
View File
@@ -39,6 +39,7 @@ export function createCesiumInput(
) {
const { scene } = viewer;
let handler = null;
let destroyed = false;
const groups = new Map();
const input = {
@@ -47,6 +48,7 @@ export function createCesiumInput(
throw new TypeError(`Unknown input type: ${type}`);
if (modifier !== undefined && !MODIFIERS.includes(modifier))
throw new TypeError(`Unknown input modifier: ${modifier}`);
if (destroyed) return () => {};
handler ??= createEventHandler(scene.canvas);
const key = `${type}:${modifier}`;
let listeners = groups.get(key);
@@ -56,7 +58,8 @@ export function createCesiumInput(
handler.setInputAction(
(event) => {
const converted = toEvent(event);
for (const entry of [...listeners]) entry.listener(converted);
for (const entry of [...listeners])
if (listeners.has(entry)) entry.listener(converted);
},
TYPES[type],
KEYS[modifier],
@@ -78,6 +81,7 @@ export function createCesiumInput(
return {
input,
destroy() {
destroyed = true;
groups.clear();
handler?.destroy();
handler = null;
+25
View File
@@ -111,3 +111,28 @@ test('destroy destroys the handler', () => {
destroy();
assert.equal(handlers[0].destroyed, true);
});
test('a listener removed during dispatch is not called', () => {
const { handlers, input } = setup();
const seen = [];
let offB;
input.on('click', () => {
seen.push('a');
offB();
});
offB = input.on('click', () => seen.push('b'));
handlers[0].fire(Type.LEFT_CLICK, { position: new Cesium.Cartesian2() });
assert.deepEqual(seen, ['a']);
});
test('on() after destroy() creates no handler', () => {
const { handlers, input, destroy } = setup();
destroy();
const off = input.on('click', () => {});
assert.equal(handlers.length, 0);
off();
off();
input.on('click', () => {});
destroy();
assert.equal(handlers.length, 0);
});
+38 -26
View File
@@ -5,7 +5,7 @@
import * as Cesium from 'cesium';
import { loadPhotorealisticTileset } from '../../maps/google3d.js';
import { createMapCredits } from '../../maps/credits.js';
import { createMapScene } from '../../maps/sceneApply.js';
import {
ESRI_ATTRIBUTION_HTML,
imageryFactoryFor,
@@ -22,6 +22,10 @@ function imageryCreator(source) {
return imageryFactoryFor(descriptor, source.accessToken);
}
// Registry sources are stable by id; plain descriptions by kind and style.
const imageryKey = (source) =>
source?.descriptor?.id ?? `${source?.kind}:${source?.style ?? ''}`;
function imageryCredit(source) {
if (source?.credit !== undefined) return source.credit;
const kind = (source?.descriptor ?? source)?.kind;
@@ -74,8 +78,8 @@ export function createCesiumMaps(
} = {},
) {
const abort = new AbortController();
let credits = null;
let layer = null;
const mapScene = createMapScene(viewer, { createImageryLayer });
const providers = new Map();
let ownedTileset = null;
let shownTileset = null;
const generations = { imagery: 0, terrain: 0, photoreal: 0 };
@@ -88,25 +92,29 @@ export function createCesiumMaps(
[startupTileset(), shownTileset, ownedTileset].filter(
(tileset, index, all) => tileset && all.indexOf(tileset) === index,
);
const showCredit = (html) => {
credits ??= createMapCredits(viewer);
credits.show(html);
};
// One provider per source, as MapSourceController caches them, so applying
// the same source again keeps the live layer. Failures are not cached.
function providerFor(source) {
const key = imageryKey(source);
if (providers.has(key)) return providers.get(key);
const promise = Promise.resolve()
.then(() => imageryCreator(source)({ signal: abort.signal }))
.catch((error) => {
if (providers.get(key) === promise) providers.delete(key);
throw error;
});
providers.set(key, promise);
return promise;
}
const maps = {
async setBaseImagery(source) {
const generation = ++generations.imagery;
const create = imageryCreator(source);
const provider = await create({ signal: abort.signal });
if (destroyed || generation !== generations.imagery) {
dispose(provider);
return;
}
const next = createImageryLayer(provider);
viewer.imageryLayers.add(next, 0);
if (layer) viewer.imageryLayers.remove(layer, true);
layer = next;
showCredit(imageryCredit(source));
const provider = await providerFor(source);
if (destroyed || generation !== generations.imagery) return;
mapScene.showBaseImagery(provider);
mapScene.showCredit(imageryCredit(source));
requestRender('map-imagery');
},
async setTerrain(source) {
@@ -120,9 +128,9 @@ export function createCesiumMaps(
const generation = ++generations.photoreal;
const { scene } = viewer;
if (source == null) {
for (const tileset of tilesets()) tileset.show = false;
mapScene.showTileset(null, tilesets());
shownTileset = null;
scene.globe.show = true;
mapScene.showGlobe(true);
requestRender('map-photoreal');
return;
}
@@ -148,10 +156,13 @@ export function createCesiumMaps(
ownedTileset = tileset;
}
if (!scene.primitives.contains(tileset)) scene.primitives.add(tileset);
for (const other of tilesets()) other.show = other === tileset;
tileset.show = true;
// As MapSourceController activates a 3D stack: no base layer, the
// source's credit, one tileset shown and the globe hidden.
mapScene.removeBaseImagery();
mapScene.showCredit(source.credit);
shownTileset = tileset;
scene.globe.show = false;
mapScene.showTileset(tileset, tilesets());
mapScene.showGlobe(false);
requestRender('map-photoreal');
},
photorealActive: () => tilesets().some((tileset) => tileset.show === true),
@@ -163,9 +174,10 @@ export function createCesiumMaps(
if (destroyed) return;
destroyed = true;
abort.abort();
if (layer) viewer.imageryLayers.remove(layer, true);
layer = null;
credits?.destroy();
mapScene.destroy();
for (const promise of providers.values())
void promise.then(dispose, () => {});
providers.clear();
if (ownedTileset) {
viewer.scene.primitives.remove(ownedTileset);
dispose(ownedTileset);
+55 -2
View File
@@ -103,7 +103,7 @@ test('every catalog globe stack works as a registry source', async () => {
});
test('a superseded imagery switch is dropped', async () => {
const { viewer, maps } = setup();
const { viewer, maps, destroy } = setup();
let release;
const slow = new Promise((resolve) => (release = resolve));
const first = maps.setBaseImagery({
@@ -127,7 +127,60 @@ test('a superseded imagery switch is dropped', async () => {
viewer.imageryList.map((layer) => layer.provider.name),
['fast'],
);
assert.equal(stale.destroyed, true, 'the stale provider is disposed');
assert.equal(stale.destroyed, false, 'the stale provider stays cached');
destroy();
await new Promise((resolve) => setImmediate(resolve));
assert.equal(stale.destroyed, true, 'destroy disposes cached providers');
});
test('re-applying the same source keeps the live layer and its provider', async () => {
const { viewer, maps } = setup();
let built = 0;
const esri = {
descriptor: { id: 'esri-imagery', kind: 'esri-imagery' },
imagery: async () => ({ name: `esri ${++built}` }),
credit: ESRI_ATTRIBUTION_HTML,
};
await maps.setBaseImagery(esri);
const live = viewer.imageryList[0];
await maps.setBaseImagery(esri);
assert.equal(built, 1, 'the provider is cached per source');
assert.equal(viewer.imageryList[0], live, 'no bare-globe rebuild');
assert.equal(viewer.callsOf('imageryLayers.add').length, 1);
assert.equal(viewer.callsOf('imageryLayers.remove').length, 0);
await maps.setBaseImagery({
descriptor: { id: 'osm', kind: 'osm' },
imagery: () => ({ name: 'osm' }),
});
await maps.setBaseImagery(esri);
assert.equal(built, 1);
assert.equal(viewer.imageryList[0].provider.name, 'esri 1');
});
test('a failed provider keeps the current layer and can be retried', async () => {
const { viewer, maps } = setup();
await maps.setBaseImagery({
descriptor: { id: 'osm', kind: 'osm' },
imagery: () => ({ name: 'osm' }),
});
let attempts = 0;
const flaky = {
descriptor: { id: 'esri-imagery', kind: 'esri-imagery' },
imagery: async () => {
if (++attempts === 1) throw new Error('Esri metadata refused');
return { name: 'esri' };
},
credit: ESRI_ATTRIBUTION_HTML,
};
await assert.rejects(maps.setBaseImagery(flaky), /metadata refused/);
assert.deepEqual(
viewer.imageryList.map((layer) => layer.provider.name),
['osm'],
);
assert.deepEqual(viewer.staticCredits, []);
await maps.setBaseImagery(flaky);
assert.equal(attempts, 2, 'the failure was not cached');
assert.equal(viewer.imageryList[0].provider.name, 'esri');
});
test('setTerrain applies provider and terrain results', async () => {
+13 -6
View File
@@ -1,13 +1,18 @@
// GlobePicker on a Cesium scene. Pick results keep Cesium's `id` and
// `primitive`; the untouched Cesium result rides along as `object` for
// Cesium-only callers.
// GlobePicker on a Cesium scene. Pick results keep Cesium's `id`,
// `primitive` and `content` (3D tile content, read by surface-pick checks);
// the untouched Cesium result rides along as `object` for Cesium-only callers.
import { toCesium2, toGeo3 } from './convert.js';
const normalise = (picked) =>
picked == null
? undefined
: { id: picked.id, primitive: picked.primitive, object: picked };
: {
id: picked.id,
primitive: picked.primitive,
content: picked.content,
object: picked,
};
/**
* @param {Cesium.Viewer} viewer
@@ -19,8 +24,10 @@ export function createCesiumPicker(viewer) {
pick(screen, width, height) {
return normalise(scene.pick(toCesium2(screen), width, height));
},
drillPick(screen, limit) {
return scene.drillPick(toCesium2(screen), limit).map(normalise);
drillPick(screen, limit, width, height) {
return scene
.drillPick(toCesium2(screen), limit, width, height)
.map(normalise);
},
pickPosition(screen) {
if (!scene.pickPositionSupported) return undefined;
+17 -3
View File
@@ -36,7 +36,7 @@ test('drillPick passes the limit and normalises every result', () => {
viewer.calls.push({ name: 'scene.drillPick', args });
return [{ id: 'a', primitive: 1 }, { primitive: 2 }];
};
const drilled = picker.drillPick(geo.cartesian2.create(1, 1), 3);
const drilled = picker.drillPick(geo.cartesian2.create(1, 1), 3, 5, 7);
assert.deepEqual(
drilled.map(({ id, primitive }) => [id, primitive]),
[
@@ -45,9 +45,10 @@ test('drillPick passes the limit and normalises every result', () => {
],
);
assert.ok('id' in drilled[1]);
const [screen, limit] = viewer.callsOf('scene.drillPick')[0].args;
const [screen, limit, width, height] =
viewer.callsOf('scene.drillPick')[0].args;
assert.ok(screen instanceof Cesium.Cartesian2);
assert.equal(limit, 3);
assert.deepEqual([limit, width, height], [3, 5, 7]);
});
test('pickPosition passes a new Cesium.Cartesian2 per call and returns geo', () => {
@@ -78,3 +79,16 @@ test('pickPositionSupported follows the scene', () => {
assert.equal(picker.pickPositionSupported, false);
assert.equal(picker.pickPosition(geo.cartesian2.create(1, 1)), undefined);
});
test('pick results carry 3D tile content for surface checks', () => {
const { picker, scene } = setup();
const content = { name: 'tile content' };
const tileset = { isCesium3DTileset: true };
scene.pick = () => ({ content, primitive: tileset });
const picked = picker.pick(geo.cartesian2.create(1, 1));
assert.equal(picked.content, content);
assert.equal(picked.id, undefined);
assert.equal(picked.primitive, tileset);
scene.pick = () => ({ id: 'entity', primitive: {} });
assert.equal(picker.pick(geo.cartesian2.create(1, 1)).content, undefined);
});