Start the application through the contract, not on the Cesium viewer

The application scene takes a renderer plugin and no longer refuses one
without a Cesium viewer. It loads the default (Cesium) plugin only when it
is given none, so a page on the stub never loads Cesium.

- Every layer and tool is handed the application's own scene object
  (createSceneHost): the container and isDestroyed(), bound to the
  renderer, the same on Cesium and the stub.
- What only Cesium needs at startup is done in its plugin's create: the
  free-look height limit, and keyboard access to its credits' expand link
  (creditKeyboard.js moves into the adapter).
- What a plugin may hand the application beside the contract goes through
  provideApplicationHooks, each hook optional: Cesium's map engine, stale
  command trimming, inline panel rendering, viewerDrawsEntity, the zoom-out
  guard, and the viewer QA scripts read from window.__godsEyeView.
- The map stacks, and the photoreal base the scene loads, switch through
  the renderer's own map engine (mapEngineFor), else its globe port
  (globeEngine.js). The Cesium engine takes the scene object and changes
  the viewer behind it.
This commit is contained in:
Sameh Khamis committed 2026-11-10 17:18:48 -08:00
1 parent a72d4c3b1f
commit 6daf63d90c
24 files changed
+825 -241

No files matched your search

+6 -5
View File
@@ -1,6 +1,6 @@
import { indexMapSources } from './registry.js';
import { createMapCredits } from './credits.js';
import { mapEngine } from './engine.js';
import { mapEngineFor } from './engine.js';
import { markBaseTileset } from '../render/baseTilesets.js';
import { acquireImageryComparison } from './imageryComparison.js';
@@ -24,9 +24,10 @@ const resolved = (provider, effectiveStackId) => ({
/**
* Coordinate source lifetimes and scene changes; the registry owns provider
* choices. The scene changes go through the renderer's map engine
* (`engine.js`), which a viewer with no renderer bound gets once its owner
* has loaded the package's `./render/cesium/unbound` export.
* choices. The scene changes go through the map engine of the scene's
* renderer (`engine.js`): its own, or its globe port. A viewer with no
* renderer bound gets one once its owner has loaded the package's
* `./render/cesium/unbound` export.
*/
export class MapSourceController {
constructor(
@@ -36,7 +37,7 @@ export class MapSourceController {
initialStack,
onChange = null,
onError = null,
engine = mapEngine(),
engine = mapEngineFor(viewer),
requestRender = () => engine.requestRender(viewer),
createImageryLayer = (provider) => engine.createImageryLayer(provider),
},
+2 -1
View File
@@ -2,7 +2,7 @@ import test from 'node:test';
import assert from 'node:assert/strict';
import { MapSourceController } from './controller.js';
// The controller switches stacks through the Cesium map engine.
import '../render/cesium/mapEngine.js';
import { cesiumMapEngine } from '../render/cesium/mapEngine.js';
import { createDefaultMapSources } from './defaultSources.js';
import { bindRenderer } from '../render/rendererOf.js';
@@ -61,6 +61,7 @@ function fixture(registry, options = {}) {
});
const controller = new MapSourceController(viewer, {
registry,
engine: cesiumMapEngine,
createImageryLayer: (provider) => ({ provider }),
onChange: (state) => changes.push(state),
...options,
+2 -3
View File
@@ -8,8 +8,8 @@ import { ESRI_ATTRIBUTION_HTML } from './attribution.js';
/**
* Select sources and setup guidance without putting provider branches in the
* controller. Each source builds its imagery and terrain through the
* renderer's map engine (`engine.js`), or the `engine` given, when it is
* first shown.
* `engine` given (the scene's map engine, `engine.js`), else the one the
* adapter provided for viewers with no renderer, when it is first shown.
*/
export function createDefaultMapSources({
googleTileset = null,
@@ -17,7 +17,6 @@ export function createDefaultMapSources({
googleApiKey = '',
engine = null,
} = {}) {
// The engine given, else the one the renderer provided, read when used.
const engineOf = () => engine ?? mapEngine();
const ionToken = String(cesiumToken || '').trim();
const hasIon = Boolean(ionToken);
+30 -9
View File
@@ -1,18 +1,25 @@
/**
* @module maps/engine
* @description What the map stacks need from the renderer that no contract
* port gives yet: the providers each stack's imagery and terrain come from,
* and the scene operations the map source controller (`controller.js`)
* switches stacks with. Cesium-free: the renderer adapter provides it
* as it loads (the Cesium one in `src/render/cesium/mapEngine.js`, loaded by
* the application's renderer and by the package's `./render/cesium/unbound`
* export), and the map code asks for it when it first needs it.
* @description What the map stacks switch through: the providers each
* stack's imagery and terrain come from, and the scene operations the map
* source controller (`controller.js`) switches stacks with.
*
* The renderer's plugin may hand the application a map engine of its own
* (`mapEngine` in `src/render/applicationHooks.js`); when it hands none, the
* renderer switches through its globe port (`globeEngine.js`). A viewer
* with no renderer bound uses the engine its adapter
* provided as it loaded (the Cesium one through the package's
* `./render/cesium/unbound` export).
*/
import { applicationHooksOf } from '../render/applicationHooks.js';
import { rendererOf } from '../render/rendererOf.js';
import { globeMapEngine } from './globeEngine.js';
let provided = null;
/**
* Provide the map engine; a later call replaces it.
* Provide the map engine for viewers no renderer is bound to; a later call
* replaces it.
* @param {object} engine
*/
export function provideMapEngine(engine) {
@@ -20,7 +27,8 @@ export function provideMapEngine(engine) {
}
/**
* The map engine the renderer adapter provided.
* The map engine the renderer adapter provided for viewers no renderer is
* bound to.
* @returns {object}
* @throws {Error} When no adapter has provided one yet.
*/
@@ -31,3 +39,16 @@ export function mapEngine() {
);
return provided;
}
/**
* The map engine the map stacks of `host` switch through: its renderer's
* own, else its renderer's globe port, else (no renderer bound) the one the
* adapter provided.
* @param {object} host The scene object.
* @returns {object}
*/
export function mapEngineFor(host) {
const renderer = rendererOf(host);
if (!renderer) return mapEngine();
return applicationHooksOf(renderer).mapEngine ?? globeMapEngine;
}
+188
View File
@@ -0,0 +1,188 @@
/**
* @module maps/globeEngine
* @description The map engine (`engine.js`) over the renderer contract's
* globe port, for when the renderer's plugin hands the application no map
* engine of its own (`src/render/applicationHooks.js`). The map stacks'
* sources become the port's specs: Esri and OSM as `xyz` imagery, Cesium
* ion's world imagery as `world` imagery, the photoreal stack as the port's
* photoreal base, and terrain as `world` terrain (or the ellipsoid where the
* port has no keyless terrain to offer).
*
* What the map stack holds is what this engine hands it: a spec per imagery
* provider, a handle per imagery layer and photoreal base. A hidden
* photoreal base is turned off through the port and on again when shown.
*/
import { findFrame, findGlobe } from '../render/rendererOf.js';
const ESRI_TILES =
'https://services.arcgisonline.com/ArcGIS/rest/services/World_Imagery/MapServer/tile/{z}/{y}/{x}';
const ESRI_CREDIT =
'Powered by Esri — Source: Esri, Maxar, Earthstar Geographics, and the GIS User Community';
const OSM_TILES = 'https://tile.openstreetmap.org/{z}/{x}/{y}.png';
const OSM_CREDIT = '© OpenStreetMap contributors';
/** Cesium ion's world imagery assets (`MAP_STACKS`' `style`). */
const WORLD_STYLES = { 2: 'aerial', 3: 'aerialLabels' };
/** Values this engine released: never used again. */
const released = new WeakSet();
/** The layer an imagery spec is drawn by, while it is drawn. */
const layers = new WeakMap();
/** Whether each globe port's surface is shown, as last set here. */
const shownGlobes = new WeakMap();
const credit = (text) => ({ text });
/** Turn a photoreal handle's base on or off, reporting a failure. */
function applyPhotoreal(handle, shown) {
if (handle.shown === shown || released.has(handle)) return;
handle.shown = shown;
handle.globe
.setPhotoreal(shown ? handle.spec : null)
.catch((error) =>
console.warn('[MapStack] photoreal switch failed', error),
);
}
/**
* Load the photoreal base through `host`'s globe port with the credentials
* the scene holds. The port's own routes decide among them (Google's key or
* session tokens, then the renderer's fallback copy).
* @param {object} host
* @param {{googleApiKey?: string, googleTokens?: {token: Function}|null,
* cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
async function loadPhotoreal(
host,
{ googleApiKey = '', googleTokens = null, cesiumToken = '' } = {},
) {
const globe = findGlobe(host);
const key = String(googleApiKey || '').trim();
const fallback = Boolean(String(cesiumToken || '').trim());
if (!globe || (!key && !googleTokens && !fallback))
return { tileset: null, route: 'none', errors: [] };
const spec = {
provider: 'google',
...(key ? { key } : {}),
...(!key && googleTokens
? { token: (options) => googleTokens.token(options) }
: {}),
fallback,
};
try {
const status = await globe.setPhotoreal(spec);
if (status?.route && status.route !== 'none')
return {
tileset: { spec, globe, shown: true },
route: status.route,
errors: [],
};
const error = status?.error;
return {
tileset: null,
route: 'none',
errors: error ? [new Error(error.message || error.code)] : [],
};
} catch (error) {
return {
tileset: null,
route: 'none',
errors: [error instanceof Error ? error : new Error(String(error))],
};
}
}
export const globeMapEngine = Object.freeze({
imagery: Object.freeze({
osm: () =>
Object.freeze({
kind: 'xyz',
url: OSM_TILES,
tiling: 'webMercator',
maxLevel: 19,
credit: credit(OSM_CREDIT),
}),
esri: () =>
Object.freeze({
kind: 'xyz',
url: ESRI_TILES,
tiling: 'webMercator',
maxLevel: 19,
credit: credit(ESRI_CREDIT),
}),
ion(style, accessToken) {
if (!String(accessToken || '').trim())
throw new Error('Ion imagery requires an explicit token');
return Object.freeze({
kind: 'world',
worldStyle: WORLD_STYLES[style] ?? 'aerial',
});
},
}),
terrain: Object.freeze({
world: async (accessToken) => {
if (!String(accessToken || '').trim())
throw new Error('World terrain requires an explicit ion token');
return {
provider: null,
spec: { kind: 'world', requestVertexNormals: true },
};
},
keyless: async () => ({ provider: null, spec: { kind: 'ellipsoid' } }),
}),
createImageryLayer: (spec) => ({ spec, layer: null }),
requestRender(host) {
findFrame(host)?.requestRender('map-stack');
},
globeShown(host) {
const globe = findGlobe(host);
if (!globe) return false;
return globe.isGlobeVisible?.() ?? shownGlobes.get(globe) ?? true;
},
setGlobeShown(host, shown) {
const globe = findGlobe(host);
if (!globe) return;
globe.setGlobeVisible(shown);
shownGlobes.set(globe, shown);
},
addTileset() {},
removeTileset(host, handle) {
if (handle) applyPhotoreal(handle, false);
},
tilesetShown: (handle) => handle?.shown === true,
showTileset(handle, shown) {
if (handle) applyPhotoreal(handle, shown);
},
addImageryLayer(host, handle, index) {
const globe = findGlobe(host);
if (!globe || released.has(handle)) return;
handle.layer = globe.imagery.add(handle.spec, index);
layers.set(handle.spec, handle.layer);
},
removeImageryLayer(host, handle) {
if (layers.get(handle.spec) === handle.layer) layers.delete(handle.spec);
handle.layer?.remove();
handle.layer = null;
},
applyTerrain(host, result) {
findGlobe(host)
?.setTerrain(result.spec ?? null)
.catch((error) => console.warn('[MapStack] terrain failed', error));
},
/**
* Hear the failed tile requests of the layer drawing `spec`; null while
* none draws it. The port does not say how often a tile was retried.
*/
onTileError(spec, listener) {
const layer = layers.get(spec);
if (!layer) return null;
return layer.on('tileError', () => listener({}));
},
isDestroyed: (value) => Boolean(value) && released.has(value),
release(value) {
if (!value || typeof value !== 'object' || released.has(value)) return;
if (value.globe && value.spec) applyPhotoreal(value, false);
released.add(value);
},
loadPhotoreal,
});
+123
View File
@@ -0,0 +1,123 @@
import test from 'node:test';
import assert from 'node:assert/strict';
import { globeMapEngine as engine } from './globeEngine.js';
import { mapEngineFor, provideMapEngine } from './engine.js';
import { bindRenderer } from '../render/rendererOf.js';
import { provideApplicationHooks } from '../render/applicationHooks.js';
import { createStubRenderer } from '../render/stub/index.js';
function scene(capabilities) {
const renderer = createStubRenderer(capabilities ? { capabilities } : {});
const host = {};
bindRenderer(host, renderer);
return { host, renderer };
}
const calls = (renderer, member) =>
renderer.testing.calls.filter(
(call) => call.port === 'globe' && call.member === member,
);
test('a renderer without a map engine of its own switches through its globe port', () => {
const { host, renderer } = scene();
assert.equal(mapEngineFor(host), engine);
const own = { own: true };
provideApplicationHooks(renderer, { mapEngine: own });
assert.equal(mapEngineFor(host), own, "the plugin's own comes first");
const provided = { provided: true };
provideMapEngine(provided);
assert.equal(mapEngineFor({}), provided, 'a viewer with no renderer');
});
test('imagery layers go through the port, lowest first, and come off again', () => {
const { host, renderer } = scene();
const spec = engine.imagery.esri();
assert.equal(spec.kind, 'xyz');
assert.match(
spec.url,
/World_Imagery\/MapServer\/tile\/\{z\}\/\{y\}\/\{x\}$/,
);
const layer = engine.createImageryLayer(spec);
engine.addImageryLayer(host, layer, 0);
assert.deepEqual(calls(renderer, 'imagery.add')[0].args, [spec, 0]);
assert.equal(renderer.globe.imagery.list().length, 1);
let errors = 0;
const off = engine.onTileError(spec, () => (errors += 1));
assert.equal(typeof off, 'function', 'tile errors are heard');
off();
engine.removeImageryLayer(host, layer);
assert.equal(renderer.globe.imagery.list().length, 0);
assert.equal(
engine.onTileError(spec, () => {}),
null,
'none once removed',
);
assert.equal(errors, 0);
});
test('the globe is shown and hidden through the port, read back without globe visibility', () => {
const { host, renderer } = scene([]);
assert.equal(engine.globeShown(host), true);
engine.setGlobeShown(host, false);
assert.equal(engine.globeShown(host), false);
assert.deepEqual(calls(renderer, 'setGlobeVisible').at(-1).args, [false]);
const visible = scene(['globeVisibility']);
engine.setGlobeShown(visible.host, false);
assert.equal(visible.renderer.globe.isGlobeVisible(), false);
assert.equal(engine.globeShown(visible.host), false);
});
test('terrain is the port’s world terrain, or the ellipsoid without a token', async () => {
const { host, renderer } = scene();
await assert.rejects(engine.terrain.world(''), /ion token/);
const world = await engine.terrain.world('token');
engine.applyTerrain(host, world);
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'world', requestVertexNormals: true },
]);
engine.applyTerrain(host, await engine.terrain.keyless());
assert.deepEqual(calls(renderer, 'setTerrain').at(-1).args, [
{ kind: 'ellipsoid' },
]);
assert.throws(() => engine.imagery.ion(2, ''), /token/);
assert.deepEqual(engine.imagery.ion(3, 'token'), {
kind: 'world',
worldStyle: 'aerialLabels',
});
});
test('photoreal loads through the port, hides and shows, and is released', async () => {
const { host, renderer } = scene(['photoreal']);
const none = await engine.loadPhotoreal(host, {});
assert.deepEqual(none, { tileset: null, route: 'none', errors: [] });
assert.equal(calls(renderer, 'setPhotoreal').length, 0, 'no credentials');
const tokens = { token: async () => 'session' };
const loaded = await engine.loadPhotoreal(host, { googleTokens: tokens });
assert.equal(loaded.route, 'google');
const handle = loaded.tileset;
assert.equal(engine.tilesetShown(handle), true);
const spec = calls(renderer, 'setPhotoreal')[0].args[0];
assert.equal(spec.provider, 'google');
assert.equal(await spec.token(), 'session');
assert.equal(spec.fallback, false);
engine.showTileset(handle, false);
assert.equal(engine.tilesetShown(handle), false);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], null);
engine.showTileset(handle, true);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], spec);
engine.release(handle);
assert.equal(engine.isDestroyed(handle), true);
assert.equal(calls(renderer, 'setPhotoreal').at(-1).args[0], null);
const count = calls(renderer, 'setPhotoreal').length;
engine.showTileset(handle, true);
assert.equal(calls(renderer, 'setPhotoreal').length, count, 'never again');
});
test('a renderer without photoreal reports none, with the reason it gave', async () => {
const { host } = scene([]);
const result = await engine.loadPhotoreal(host, { googleApiKey: 'key' });
assert.equal(result.tileset, null);
assert.equal(result.route, 'none');
});