diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 166fa590e..5d9d7c2d7 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1139,8 +1139,8 @@ Polled layer refreshes and the HUD's camera readout pause while the page is hidden. An app embedded inline in a panel keeps both running, because the panel's host can report the page as hidden while it is on screen. This is the same rule the render loop follows (`keepPanelRendering` in -`render/cesium/panelRendering.js`, which the application scene hands the embed -views). +`render/cesium/panelRendering.js`, which the Cesium plugin hands the +application and the application scene hands the embed views). Application scene setup owns request services, terrain/floor caches and annotation lookup state. Controls, layers and voice share those owners, and cancellation @@ -3167,7 +3167,8 @@ which embeds the MAP_KEY. > MiB). `src/sceneCommandRelease.js`, installed in `src/app/tools.js`, > requests one frame through `governorRequestRender` after every layer > disable and then has `src/render/cesium/sceneCommandRelease.js` (handed -> over by `src/app/scene.js`) trim those arrays. It reads private Cesium +> handed over by the Cesium plugin through `src/app/scene.js`) trim those +> arrays. It reads private Cesium > fields through `src/render/cesium/internals.js`; > `src/render/cesium/sceneCommandRelease.test.mjs` pins them and fails if > Cesium renames them or changes which passes it truncates. @@ -6530,7 +6531,7 @@ pins and share links already supply complete boxes. - DATA ▸ **Recent Imagery** (`recent-imagery`, `src/layers/recentImagery/`) lists the last 30 UTC days of imagery for a selected box and drapes the days you pick: HLS S30 (Sentinel-2) and L30 (Landsat 8/9) at 30 m, and the VIIRS NOAA-21 daily overview at 250 m. Keyless and browser-direct: NASA CMR for which days have HLS granules in the box (`catalog.js`, both collections concurrently, paged with `CMR-Search-After` up to 2,000 records each, `truncated` against CMR `hits`), GIBS WMTS for tiles, Worldview Snapshots for thumbnails and exports. Worldview's `Data-Present` header is the only availability signal: GIBS answers an empty tile with HTTP 200, and the JPEG overview would drape black, so a day confirmed empty never drapes. - **Box.** SELECT BOX (`src/ui/imageryBoxTool.js`) claims the pointer like Draw, borrows the stock click actions and freezes the camera only mid-drag; USE VIEW takes the camera rectangle; `boxFromPinAt` grows a 10 km box. Boxes must be ≤ 1,000 km a side, on one side of the dateline and inside the Web-Mercator limit (`validateBox`). A refusal (`boxError`, including the tool's own via `reportBoxRefusal`) stays at the top of the panel until a box succeeds; a view over the cap is refused with its size, never shrunk. An oversized box or view (`Box is … km wide · limit 1,000 km`, `View is … wide · …`) sets the hint to `Zoom in or draw a smaller box` and enables ZOOM IN: `zoomToFit()` flies top-down (1.2 s) to the refused box's centre, or the ground under the canvas centre for a view, at the height whose view is about 400 km wide for the canvas aspect and the camera's vertical FOV (`fitViewHeightM`, clamped 5–400 km), and returns that height. - **Modes, pins and the preview.** The mode is explicit: `image` (one pinned day, slot `a`), `basemap` (that day on the left of a swipe, the basemap on the right: slot `a` splits LEFT and there is no second layer) and `ab` (day `a` left, day `b` right). `setAssignment(slot, key | null)` / `toggleAssignment(slot, key)` pin and unpin; a day is in one slot at most (pinning it in the other slot moves it) and an empty day cannot be pinned. `setMode()` keeps both pins; `b` only drapes in `ab`. While the mode's first empty slot exists the focused day previews in it: a click at once, arrow keys after 250 ms of quiet (`FOCUS_DEBOUNCE_MS`, one timer, last day wins); an unprobed day is followed and previews when its probe says present, an empty or unknown day never drapes and the previous preview stays. A pin change drops the preview until focus moves again, and unpinning takes that layer off at once. `rankLatest` picks START HERE coverage first (a present HLS day whose footprints cover the box, or have none, beats a newer sliver), then newest with all granules ≤ 20% known cloud, then newest; slivers only as `partial`; else the newest non-empty VIIRS day; it is focused and previewed after each search when nothing is pinned. Escape clears the preview (`clearPreview()`), then cancels the box tool, then blurs — with SELECT BOX armed too, through the tool's `onEscape` interceptor wired in `createApplicationTools`. Pins, mode, box and split changes made in the panel are published with `adoptLayerParams`, never while a share link is being applied. -- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: `viewer.imageryLayers` while the globe shows, the photoreal tileset's `imageryLayers` while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. +- **Rendering.** `rendering.js` owns at most two GIBS layers on the host `src/maps/imageryHost.js` resolves: the globe port's imagery while the globe shows, the shown photoreal tileset while it is hidden, or none (the panel says so). Layers are rebuilt on a new host, never re-parented. `MapSourceController.subscribe()` fires after every settled stack switch (silent switches and fallbacks included) and the layer rebinds on it. Tile requests pass a six-slot semaphore of our own (Cesium's global limits are untouched). Under `requestRenderMode` a deferred tile needs a later frame, but a deferral must never request one itself or a stalled tile keeps the scene rendering every frame: a request that finds the semaphore full asks for nothing (the settling request asks for one frame), and a tile Cesium itself deferred goes through one coalesced 250 ms retry. Thumbnails: three fetches at once, sixteen decoded images, least-recently-used where a `get` read is never a use; eviction keeps the probe result. The strip's visible window is probed around the focused card; the pinned and previewed days are probed wherever they sit, at the focused card's priority, so a pin restored or assigned off-screen still drapes. - **Esri surface and the swipe.** While any image is on the map (a preview included) the layer holds the map lease (`acquireImageryComparison`, owner `recent-imagery`, `esri-if-photoreal`): on Google 3D the map switches to Esri, because 30 m pixels over 3D buildings do not read, and Cesium's split only works on the globe. The lease is handed back, and Google 3D restored unless the operator changed maps meanwhile, when the last image leaves the map or the layer is disabled; the notice line says so while it holds. While a day is shown the imagery keeps Esri: a manual switch that lands on Google 3D is answered at once with a new lease under the same policy (`keepEsri`), the notice reads `Imagery stays on Esri · CLEAR to use Google 3D`, and the divider never suspends because of a map switch. It re-leases once per switch generation and only for a manual one (`MapSourceController#getSwitchOrigin()` is `manual` for an outside `setStack`, `automatic` for the controller's own fallback or recovery), never for the lease's own switch and never while releasing, so CLEAR and disable still return to Google 3D; a lease another owner holds stays refused. When Esri fails and the controller falls back to Google 3D on its own, the layer lets the lease go without restoring anything, both days drape on the tileset without a swipe and the guidance reads `Esri map unavailable · no swipe`; only the next manual switch to Google 3D takes Esri again, so a failing Esri map is never retried in a loop. Switching between globe stacks (Esri, OSM, Bing) only rebinds. On a tileset host both images drape without a swipe. The split control (`createImagerySplit`, labels A / B, or IMAGE / BASEMAP) exists only while a swipe is live, recentres on every new comparison (not while scrubbing the second day), except once for a split restored from a link. There is no keyboard shortcut (Space is the app's push-to-talk): SWAP (`#ri-swap`, in the controls row, its slot reserved and the button disabled while no swipe is live) trades the two sides, A to the right and B to the left, or the image to the right of the basemap, and a second click restores; the hint reads `Drag the divider · SWAP trades sides`. The swap is not in the share link, and every new comparison starts unswapped. One opacity applies to both drapes. Another owner holding the lease is reported and the images still drape. - **Panel.** `#recent-imagery-panel` is rail markup in the Context view (`src/ui/views/ContextView.vue`) beside `#weather-panel`, registered in `PanelLayoutController`, `PanelChrome` and the share panel state (`ui` token `i`), hidden while the layer is off and opened on first appearance unless a stored or shared collapse choice exists (`dataset.collapsedPreference`). `LayerPanel.attachRecentImagery(factory)` mounts the readout (`createRecentImageryPanel` in `src/ui/recentImagery.js`) into its `data-rail-scroller` body, as the weather readout is mounted. The body is a fixed stack in which no block changes height and no control moves in any state: `#ri-actions` (SELECT BOX · USE VIEW · CLEAR, rail-card actions), `#ri-notice` (one line: `#ri-notice-text` with the refusal, error, CLEAR notice or the Esri note, and `#ri-zoom-in` in a fixed slot at its right end, reserved unless an oversized box or view can be fitted), `#ri-strip` (day cards newest first: thumbnail, date, sensor, cloud, START HERE, PREVIEW, and a SHOW chip or A and B chips; ← → Home End move, S / A / B pin, Enter previews), `#ri-hint` (one line: the next step), `#ri-selection` (`#ri-mode` IMAGE · VS BASEMAP · A / B, then `#ri-slot-a` and `#ri-slot-b` with `#ri-unpin-a` / `#ri-unpin-b` kept in place when empty), `#ri-controls` (`#ri-opacity`, EXPORT / EXPORT A and EXPORT B) and `#ri-details`, a collapsed rail card holding the focused day's acquisition, coverage and granules, catalog notes, the empty-days toggle and the imagery credit. Absent controls are reserved (invisible), never removed. Every render preserves the body's `scrollTop`; opening DETAILS then scrolls its card into view once. - **Share links.** Layer options (token `1`): box edges as integers at degrees × 100000, pins `a` and `b` as compact days (`S20260918`), `m` mode (0 image, 1 basemap, 2 A / B), `p` split percent (share-link only: never stored locally) and `v` for the daily overview. Row chips: `MORE DETAIL · 30 m` (on) and `DAILY OVERVIEW · 250 m` (off). @@ -7464,12 +7465,19 @@ The imagery, terrain and 3D factories are the Cesium renderer's (`src/render/cesium/mapImagery.js`, `mapTerrain.js`, `google3d.js`; the package exports `./maps/imagery`, `./maps/terrain` and `./maps/3d` point there). The catalog, the default registry and the controller are -Cesium-free: they reach those factories, and the viewer operations a +Cesium-free: they reach those factories, and the scene operations a switch makes (imagery layers, terrain, the globe's visibility, tilesets), -through the map engine (`src/maps/engine.js`), which the Cesium renderer -provides as it loads (`src/render/cesium/mapEngine.js`). A viewer with no -renderer bound gets it, with the other unbound ports, from the package's -`./render/cesium/unbound` export. +through the scene's map engine (`mapEngineFor` in `src/maps/engine.js`). The +Cesium plugin hands the application its own engine with each renderer it makes +(`src/render/cesium/mapEngine.js`, through `src/render/applicationHooks.js`), +and the application scene loads the photoreal base through it too. A renderer +whose plugin hands none switches through its globe port +(`src/maps/globeEngine.js`): Esri and OSM as `xyz` imagery, ion's world +imagery as `world` imagery, photoreal as the port's photoreal base (turned off +while hidden, on again when shown), and world terrain, or the ellipsoid where +Cesium uses Re:Earth's keyless terrain (the contract's `TerrainSpec` has no +such kind). A viewer with no renderer bound gets the Cesium engine, with the +other unbound ports, from the package's `./render/cesium/unbound` export. The controller accepts other source registries without adding provider branches. Each instance caches source construction, ignores superseded scene changes and diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 901bae6b3..87f522781 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1404,7 +1404,9 @@ "src/ui/ownerFlagSheet.js", "src/layers/satellites/sensors.js", "src/data/adminBoundaries.js", - "src/data/retryableLoad.js" + "src/data/retryableLoad.js", + "src/maps/imageryHost.js", + "src/render/cesium/viewers.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -2036,7 +2038,10 @@ "src/renderGovernor.js", "src/sky/icrf.js", "src/sky/stars.js", - "src/render/cesium/starrySky.js" + "src/render/cesium/starrySky.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js" ], "external": ["cesium"] }, @@ -2642,7 +2647,8 @@ "src/render/cesium/nativeClick.js", "src/render/input/router.js", "src/render/cesium/ctrlWheelZoom.js", - "src/render/cesium/input.js" + "src/render/cesium/input.js", + "src/render/cesium/viewers.js" ], "external": ["cesium", "pbf", "@mapbox/vector-tile"] }, @@ -3293,7 +3299,10 @@ "src/render/cesium/nativeClick.js", "src/maps/attribution.js", "src/maps/startupRoute.js", - "src/maps/engine.js" + "src/maps/engine.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js" ], "external": ["cesium"] }, @@ -3534,7 +3543,7 @@ "src/cockpitVisionPolicy.js", "src/contactsDetectionPolicy.js", "src/contextModePolicy.js", - "src/creditKeyboard.js", + "src/render/cesium/creditKeyboard.js", "src/data/aircraftClass.js", "src/data/aircraftEmergency.js", "src/data/aircraftIcons.js", @@ -4555,7 +4564,10 @@ "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", - "src/render/cesium/imageryLookAhead.js" + "src/render/cesium/imageryLookAhead.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/render/cesium/viewers.js" ], "external": [ "hls.js", @@ -5297,7 +5309,8 @@ "src/layers/satellites/classes.js", "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", - "src/data/imagingSensors.js" + "src/data/imagingSensors.js", + "src/render/cesium/viewers.js" ], "external": [ "hls.js", @@ -5431,7 +5444,8 @@ "src/render/cesium/ctrlWheelZoom.js", "src/render/input/router.js", "src/render/cesium/nativeClick.js", - "src/render/cesium/input.js" + "src/render/cesium/input.js", + "src/render/cesium/viewers.js" ], "external": [ "cesium", @@ -6199,7 +6213,8 @@ "src/render/cesium/nativeClick.js", "src/data/rioRouteNames.js", "src/overlays/worldOverlayChrome.js", - "src/time/worldClock.js" + "src/time/worldClock.js", + "src/render/cesium/viewers.js" ], "external": ["cesium", "egm96-universal", "pbf"] }, @@ -6306,7 +6321,8 @@ "src/render/cesium/pickMemo.js", "src/render/cesium/nativeClick.js", "src/data/rioRouteNames.js", - "src/time/worldClock.js" + "src/time/worldClock.js", + "src/render/cesium/viewers.js" ], "external": ["cesium", "pbf"] }, @@ -6845,7 +6861,8 @@ "src/contextModePolicy.js", "src/loadingFeedback.js", "src/data/installationFeedback.js", - "src/i18n/marker.js" + "src/i18n/marker.js", + "src/render/rendererOf.js" ], "external": [] }, diff --git a/src/app/scene.js b/src/app/scene.js index d597fec30..1a6ce6627 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -1,17 +1,7 @@ import { createApplicationOperations } from './operations.js'; -// The application's composition root: it picks the Cesium renderer, and -// this is the only part of the adapter it imports. -import { - applicationViewerHooks, - cesiumRenderer, - cesiumViewerOf, - loadApplicationPhotoreal, - releaseApplicationPhotoreal, - showApplicationPhotoreal, -} from '../render/cesium/application.js'; import { registerDataCredits } from '../data/dataCredits.js'; -import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; import { MapStackController } from '../mapStackController.js'; +import { mapEngineFor } from '../maps/engine.js'; import { initLogoGaze } from '../logoGaze.js'; import { inputFor } from '../input/dispatcher.js'; import { @@ -21,19 +11,32 @@ import { governorRequestRender, } from '../renderGovernor.js'; import { describeError } from './errors.js'; -import { FREE_LOOK_MAX_HEIGHT_METERS } from '../globeInView.js'; import { worldClock, worldTimeFor } from '../time/worldClock.js'; import { followWorldTime } from '../time/viewerClock.js'; -import { onLocaleChange, t } from '../i18n/index.js'; +import { t } from '../i18n/index.js'; +import { applicationHooksOf } from '../render/applicationHooks.js'; +import { createSceneHost } from '../render/rendererOf.js'; + +/** + * The application's composition root picks the renderer: the one given, else + * the default (Cesium), loaded only then, so a page on the stub never + * loads it. This is the only part of an adapter the application imports. + */ +async function defaultRenderer() { + const { cesiumRenderer } = await import('../render/cesium/application.js'); + return cesiumRenderer; +} /** * Construct the application globe using the caller's local configuration. * `renderer` is the `RendererPlugin` that draws it (default: Cesium). The - * application still runs on the Cesium viewer until its layers are ported, - * so a plugin whose renderer has none is refused. + * application runs on a renderer with only the contract's required members: + * what a renderer's plugin hands it beside the contract + * (`src/render/applicationHooks.js`) it uses where given, and does without + * where not. */ export async function createApplicationScene({ - renderer: rendererPlugin = cesiumRenderer, + renderer: givenPlugin, requestServices, googleApiKey, googleTokens = null, @@ -60,23 +63,23 @@ export async function createApplicationScene({ }); } loaderStatus.textContent = t('Configuring viewer...'); - // The scene still loads the tiles, so their credentials stay here. + const rendererPlugin = givenPlugin ?? (await defaultRenderer()); + signal.throwIfAborted(); + const container = document.getElementById('cesiumContainer'); const renderer = await rendererPlugin.create({ - container: document.getElementById('cesiumContainer'), + container, + googleApiKey: googleApiKey || undefined, + googleTokens: googleTokens + ? (options) => googleTokens.token(options) + : undefined, + worldDataToken: cesiumToken || undefined, signal, }); - const viewer = cesiumViewerOf(renderer); - if (!viewer) { - const refusal = new Error( - `The ${rendererPlugin.id} renderer cannot run the application yet`, - ); - try { - renderer.destroy(); - } catch (error) { - console.warn('[Init] Refused renderer failed to destroy:', error); - } - throw refusal; - } + // The scene object every layer and tool is handed: the application's own, + // bound to the renderer. + const scene = createSceneHost(renderer, { container }); + const viewer = scene.host; + const hooks = applicationHooksOf(renderer); // The governor keeps its holds on the renderer's frame port. The loop // draws every frame until the application's tools are up (they release // 'boot'), as it did before anything could hold it. @@ -86,11 +89,15 @@ export async function createApplicationScene({ try { uninstallRenderGovernor(renderer.frame); } finally { - renderer.destroy(); + try { + renderer.destroy(); + } finally { + scene.release(); + } } }); // Before any layer binds a click: every layer and tool shares this one. - // Deferred after the viewer, so it is released before the viewer goes. + // Deferred after the renderer, so it is released before the renderer goes. const input = inputFor(viewer); defer(() => input.destroy()); // Ctrl+wheel and trackpad pinches zoom the globe, not the page. @@ -103,28 +110,29 @@ export async function createApplicationScene({ requestRender: () => governorRequestRender('world-time'), }), ); - // What the adapter hands the application about its viewer; free look is - // limited to low heights from the start. - const viewerHooks = applicationViewerHooks(viewer); - defer(viewerHooks.installFreeLookHeightLimit(FREE_LOOK_MAX_HEIGHT_METERS)); registerDataCredits(viewer, credits); - configureCreditKeyboardAccess(document); - defer(onLocaleChange(() => configureCreditKeyboardAccess(document))); loaderStatus.textContent = googleApiKey || googleTokens || cesiumToken ? t('Loading Google 3D Tiles...') : t('Loading the keyless globe...'); - const photoreal = await loadApplicationPhotoreal({ + // The map stacks, and the photoreal base among them, switch through the + // scene's map engine: the renderer's own, or its globe port. + const engine = mapOptions.engine ?? mapEngineFor(viewer); + const photoreal = (await engine.loadPhotoreal?.(viewer, { googleApiKey, googleTokens, cesiumToken, - }); + })) ?? { tileset: null, route: 'none', errors: [] }; const tileset = photoreal.tileset; // A provider can finish after cancellation; retain ownership of its result. - defer(() => releaseApplicationPhotoreal(viewer, tileset)); + defer(() => { + if (!tileset || engine.isDestroyed(tileset)) return; + engine.removeTileset(viewer, tileset); + engine.release(tileset); + }); signal.throwIfAborted(); if (tileset) { - showApplicationPhotoreal(viewer, tileset); + engine.addTileset(viewer, tileset); // NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom. // Google Photorealistic 3D Tiles provide their own terrain/elevation. renderer.globe.setGlobeVisible(false); @@ -152,6 +160,7 @@ export async function createApplicationScene({ const mapStackController = new MapController(viewer, { requestRender: governorRequestRender, ...mapOptions, + engine, googleTileset: tileset, cesiumToken, initialStack: tileset ? 'photoreal' : 'esri-imagery', @@ -180,9 +189,14 @@ export async function createApplicationScene({ mapStackController, operations, input, - // Trims stale draw commands, keeps an inline panel drawing, says - // whether an entity is the viewer's own, and installs the zoom-out - // guard (render/cesium/application.js). - ...viewerHooks, + // What the renderer's plugin hands the application beside the contract, + // each optional: trims stale draw commands, keeps an inline panel + // drawing, says whether an entity is the renderer's own, installs the + // zoom-out guard, and what QA scripts read (render/applicationHooks.js). + trimStaleCommands: hooks.trimStaleCommands, + keepPanelRendering: hooks.keepPanelRendering, + viewerDrawsEntity: hooks.viewerDrawsEntity, + installZoomOutGuard: hooks.installZoomOutGuard, + qaHandles: hooks.qaHandles, }; } diff --git a/src/app/scene.test.mjs b/src/app/scene.test.mjs new file mode 100644 index 000000000..ba9955b96 --- /dev/null +++ b/src/app/scene.test.mjs @@ -0,0 +1,108 @@ +import '../testSupport/registerDom.mjs'; +import test from 'node:test'; +import assert from 'node:assert/strict'; +import { createApplicationScene } from './scene.js'; +import { createApplicationRequestServices } from '../services/requests.js'; +import { createStubRendererPlugin } from '../render/stub/index.js'; +import { rendererOf } from '../render/rendererOf.js'; + +/** Start the scene on a stub renderer with `capabilities`. */ +async function startOnStub(t, { capabilities = [], ...rest } = {}) { + document.body.innerHTML = '
'; + const made = []; + const deferred = []; + t.after(async () => { + for (const fn of deferred.reverse()) await fn(); + }); + const scene = await createApplicationScene({ + renderer: createStubRendererPlugin({ capabilities }, (renderer) => + made.push(renderer), + ), + requestServices: createApplicationRequestServices(), + loaderStatus: { textContent: '' }, + signal: new AbortController().signal, + defer: (fn) => deferred.push(fn), + ...rest, + }); + return { scene, renderer: made[0], deferred }; +} + +test('the scene runs on a renderer with only the required members', async (t) => { + const { scene, renderer, deferred } = await startOnStub(t); + assert.equal(scene.renderer, renderer); + assert.equal(rendererOf(scene.viewer), renderer, 'the scene object is bound'); + assert.equal( + scene.viewer.container, + document.getElementById('cesiumContainer'), + ); + assert.equal(scene.viewer.isDestroyed(), false); + assert.ok( + scene.viewer.container.contains(renderer.canvas), + 'the renderer fills the container', + ); + // Nothing of the engine on the scene object. + assert.deepEqual(Object.keys(scene.viewer).sort(), [ + 'container', + 'isDestroyed', + ]); + // No hooks: each is left out, not faked. + for (const name of [ + 'trimStaleCommands', + 'keepPanelRendering', + 'viewerDrawsEntity', + 'installZoomOutGuard', + 'qaHandles', + ]) + assert.equal(scene[name], undefined, name); + // Keyless, the map stack shows Esri on the globe through the globe port. + assert.equal(scene.tileset, null); + assert.equal(scene.mapStackController.getActiveId(), 'esri-imagery'); + const layers = renderer.globe.imagery.list(); + assert.equal(layers.length, 1, 'one base imagery layer'); + assert.ok( + renderer.testing.calls.some( + (call) => + call.port === 'globe' && + call.member === 'imagery.add' && + call.args[0]?.url?.includes('World_Imagery'), + ), + 'Esri imagery through the port', + ); + assert.equal(scene.mapStackController.getDrapeSurface(), 'globe'); + + // Switching stacks goes through the port too. + await scene.mapStackController.setStack('osm'); + assert.equal(scene.mapStackController.getActiveId(), 'osm'); + assert.equal(renderer.globe.imagery.list().length, 1, 'Esri gave way'); + + for (const fn of deferred.splice(0).reverse()) await fn(); + assert.equal(scene.viewer.isDestroyed(), true); + assert.equal(rendererOf(scene.viewer), null, 'and lets go of the renderer'); + assert.equal(renderer.globe.imagery.list().length, 0, 'imagery released'); +}); + +test('with credentials, the photoreal base loads through the globe port', async (t) => { + const { scene, renderer } = await startOnStub(t, { + capabilities: ['photoreal', 'globeVisibility'], + googleApiKey: 'stub-key', + }); + assert.ok(scene.tileset, 'a photoreal base'); + assert.equal(scene.mapStackController.getActiveId(), 'photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false, 'the globe is hidden'); + const photoreal = renderer.testing.calls.filter( + (call) => call.port === 'globe' && call.member === 'setPhotoreal', + ); + assert.equal(photoreal[0]?.args[0]?.key, 'stub-key'); + + // A globe stack hides photoreal through the port, and shows the globe. + await scene.mapStackController.setStack('esri-imagery'); + assert.equal(renderer.globe.isGlobeVisible(), true); + assert.equal( + renderer.testing.calls + .filter((call) => call.port === 'globe' && call.member === 'setPhotoreal') + .at(-1).args[0], + null, + ); + await scene.mapStackController.setStack('photoreal'); + assert.equal(renderer.globe.isGlobeVisible(), false); +}); diff --git a/src/app/tools.js b/src/app/tools.js index 37752376f..6edf8382c 100644 --- a/src/app/tools.js +++ b/src/app/tools.js @@ -224,6 +224,9 @@ export function createApplicationTools({ surfaceServices: operations.surface, requestRender: governorRequestRender, entityRecords: { read: readEntityRecord, write: entityRecord }, + // What the renderer's plugin lets QA scripts read (the Cesium viewer, + // for the default renderer), in place of the scene object above. + ...scene.qaHandles, }; const debug = window.__godsEyeView; defer(() => { diff --git a/src/mapStackController.js b/src/mapStackController.js index 35fbabddb..a6c767627 100644 --- a/src/mapStackController.js +++ b/src/mapStackController.js @@ -1,5 +1,6 @@ import { MapSourceController } from './maps/controller.js'; import { createDefaultMapSources } from './maps/defaultSources.js'; +import { mapEngineFor } from './maps/engine.js'; import { governorRequestRender } from './renderGovernor.js'; export { MAP_STACKS } from './maps/catalog.js'; export { photorealUnavailableReason } from './maps/availability.js'; @@ -9,9 +10,16 @@ export class MapStackController extends MapSourceController { constructor(viewer, options = {}) { const googleApiKey = typeof window !== 'undefined' ? window.__GOOGLE_MAPS_API_KEY__ : ''; - const registry = createDefaultMapSources({ ...options, googleApiKey }); + // The scene's map engine, unless the caller names one. + const engine = options.engine ?? mapEngineFor(viewer); + const registry = createDefaultMapSources({ + ...options, + googleApiKey, + engine, + }); super(viewer, { registry, + engine, initialStack: options.googleTileset ? options.initialStack || 'photoreal' : registry.defaultId, diff --git a/src/maps/controller.js b/src/maps/controller.js index 97aa9ceb7..7e28699c3 100644 --- a/src/maps/controller.js +++ b/src/maps/controller.js @@ -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), }, diff --git a/src/maps/controller.test.mjs b/src/maps/controller.test.mjs index ccd9ba673..901f5bf29 100644 --- a/src/maps/controller.test.mjs +++ b/src/maps/controller.test.mjs @@ -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, diff --git a/src/maps/defaultSources.js b/src/maps/defaultSources.js index 75b14d78a..8848277a9 100644 --- a/src/maps/defaultSources.js +++ b/src/maps/defaultSources.js @@ -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); diff --git a/src/maps/engine.js b/src/maps/engine.js index 73530852f..d28b030f0 100644 --- a/src/maps/engine.js +++ b/src/maps/engine.js @@ -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; +} diff --git a/src/maps/globeEngine.js b/src/maps/globeEngine.js new file mode 100644 index 000000000..139fc1ea7 --- /dev/null +++ b/src/maps/globeEngine.js @@ -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, +}); diff --git a/src/maps/globeEngine.test.mjs b/src/maps/globeEngine.test.mjs new file mode 100644 index 000000000..2562f6a0e --- /dev/null +++ b/src/maps/globeEngine.test.mjs @@ -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'); +}); diff --git a/src/render/applicationHooks.js b/src/render/applicationHooks.js new file mode 100644 index 000000000..820d0182c --- /dev/null +++ b/src/render/applicationHooks.js @@ -0,0 +1,43 @@ +/** + * @module render/applicationHooks + * @description What a renderer's plugin may hand the application beside the + * contract: behaviour the application uses where a renderer has it, and does + * without where it has none. Nothing here is part of the renderer contract, + * and the application never asks which renderer it runs on: it reads the + * hooks of the renderer it was given, each of them optional. + * + * - `mapEngine`: the renderer's own map engine (`src/maps/engine.js`), which + * the map stacks switch through in place of the globe port + * (`src/maps/globeEngine.js`). + * - `trimStaleCommands()`: drops the draw commands a renderer keeps for a + * while after it stops drawing them; run after a layer turns off. + * - `keepPanelRendering(options)`: keeps the globe drawing in an inline panel + * whose host stops animation frames (embed mode); returns its disposer. + * - `viewerDrawsEntity(entity)`: whether an entity is one the renderer draws + * itself (Cockpit asks whether the aircraft it flies still draws). + * - `installZoomOutGuard(options)`: keeps outward user zooms bounded and the + * Earth framed; returns its disposer. + * - `qaHandles`: values QA scripts read from `window.__godsEyeView`. + */ + +const hooks = new WeakMap(); +const NONE = Object.freeze({}); + +/** + * Hand the application `value`'s hooks for `renderer`. A renderer's plugin + * calls it as it creates the renderer; a later call replaces them. + * @param {object} renderer + * @param {object} value + */ +export function provideApplicationHooks(renderer, value) { + hooks.set(renderer, Object.freeze({ ...value })); +} + +/** + * The hooks `renderer`'s plugin provided; an empty object when it provided + * none, or `renderer` is not an object. + * @param {object|null|undefined} renderer + * @returns {Readonly