Merge branch 'sameh/renderer-exit' into sameh/renderer-seam

This commit is contained in:
Sameh Khamis committed 2026-11-09 13:17:24 -08:00
commit 657ef94f77
51 files changed
+899 -377

No files matched your search

+16
View File
@@ -468,6 +468,13 @@ release listeners; pending action feedback is limited to its current owner.
rendering, HUD and share operations. `src/standalone/controls.js` provides the running rendering, HUD and share operations. `src/standalone/controls.js` provides the running
application's instances. The shell application's instances. The shell
imports no standalone bootstrap or concrete live layer implementation. imports no standalone bootstrap or concrete live layer implementation.
The shell reaches the renderer through its ports alone, and loads no
renderer: given a viewer with no renderer bound, load
`./render/cesium/unbound` once first, which also provides the celestial
ring's precise ICRF rotation (`src/sky/icrf.js`; until then the ring uses
the TEME approximation). Whether Cockpit's aircraft is an entity of the
viewer's own is the `viewerDrawsEntity` service's to say; the application
scene supplies it.
Panel layout, position/drag, notices, recording and deferred UI work have separate Panel layout, position/drag, notices, recording and deferred UI work have separate
owners with synchronous cleanup. Existing scene, share and HUD engines retain owners with synchronous cleanup. Existing scene, share and HUD engines retain
their entry points. `ui/styles` loads the ordered stylesheet entry; component their entry points. `ui/styles` loads the ordered stylesheet entry; component
@@ -505,6 +512,15 @@ perform no network requests and discover no additional modules.
standard sources and their setup/fallback policy. The standalone facade wires standard sources and their setup/fallback policy. The standalone facade wires
these to the application's render governor. these to the application's render governor.
`maps/imagery`, `maps/terrain` and `maps/3d` are the Cesium renderer's
(`src/render/cesium/`). `maps/controller` and `maps/defaults` are
Cesium-free: they make their scene changes and build their providers
through the map engine the renderer provides as it loads
(`src/maps/engine.js`). The application's renderer provides it; with a
viewer with no renderer bound, load `./render/cesium/unbound` once first, or pass the
engine as the controller's and `createDefaultMapSources`' `engine` option.
Without one, constructing a controller throws, naming that export.
A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`. A registry supplies `sources`, `defaultId`, `unknownId` and optional `recoveryId`.
Each source has a user-facing `descriptor`, availability/reason, and either an Each source has a user-facing `descriptor`, availability/reason, and either an
`imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`. `imagery({ signal })` factory or a supplied `tileset`/`createTileset({ signal })`.
+21 -6
View File
@@ -558,7 +558,7 @@ Keyless terrain tiles retry when Re:Earth throttles them. The browser fetches
`terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no `terrain.reearth.land/cesium-mesh/ellipsoid/{z}/{x}/{y}.terrain` directly; no
proxy in this repository sees those requests (`/api/terrain/heights` is the proxy in this repository sees those requests (`/api/terrain/heights` is the
separate point-height endpoint), and the upstream edge answers zoom-out bursts separate point-height endpoint), and the upstream edge answers zoom-out bursts
with HTTP 429 under load. `src/maps/terrain.js` hands Cesium a `Resource` with HTTP 429 under load. `src/render/cesium/mapTerrain.js` hands Cesium a `Resource`
whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch whose retry policy (`src/maps/terrainRetry.js`) every derived tile fetch
inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms inherits: 429, 502, 503 and 504 replies retry up to three times, 750 ms
doubling to a 15 s cap, with every retry waiting behind one shared cooldown doubling to a 15 s cap, with every retry waiting behind one shared cooldown
@@ -881,7 +881,9 @@ unchanged.
Polled layer refreshes and the HUD's camera readout pause while the page is 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 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 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 `app/embed.js`). same rule the render loop follows (`keepPanelRendering` in
`render/cesium/panelRendering.js`, which the application scene hands the embed
views).
Application scene setup owns request services, terrain/floor caches and annotation Application scene setup owns request services, terrain/floor caches and annotation
lookup state. Controls, layers and voice share those owners, and cancellation lookup state. Controls, layers and voice share those owners, and cancellation
@@ -1128,8 +1130,9 @@ port's `preUpdate`, with the shared geo maths, and no longer loads the Cesium
camera factory: a caller handing it a Cesium viewer, with no camera factory: a caller handing it a Cesium viewer, with no
renderer bound, loads the `./render/cesium/unbound` export once first, or its renderer bound, loads the `./render/cesium/unbound` export once first, or its
controller throws naming it. Whether the aircraft it flies still draws comes controller throws naming it. Whether the aircraft it flies still draws comes
from its `trackedEntityDrawn` service (the application asks the viewer's from its `trackedEntityDrawn` service (the shell asks the entity's record,
entities); without one, Cockpit takes the aircraft as drawn. and the application scene's `viewerDrawsEntity` for an entity of the viewer's
own); without one, Cockpit takes the aircraft as drawn.
## Rendered-mesh floor cells — November 8, 2026 ## Rendered-mesh floor cells — November 8, 2026
@@ -1502,10 +1505,11 @@ The clear control presents busy state while its existing action owns the transac
## Sky background ## Sky background
`src/sky/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale `src/render/cesium/starrySky.js` fills Cesium's `Scene#skyBox` slot with 9,096 Yale
Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers Bright Star Catalogue stars and a soft ESO/S. Brunier Milky Way. Both layers
rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with rotate from ICRF/J2000 into the Earth-fixed frame at the scene clock, with
a TEME fallback while Cesium's IAU 2006 tables load. Bundled assets and a TEME fallback while Cesium's IAU 2006 tables load. The precise rotation reaches
Cesium-free code (the celestial ring) through `src/sky/icrf.js`. Bundled assets and
their provenance are documented in `src/data/local_data/sky/README.md`. their provenance are documented in `src/data/local_data/sky/README.md`.
Anime fades out the Milky Way with its style intensity to avoid cel-shaded Anime fades out the Milky Way with its style intensity to avoid cel-shaded
@@ -6650,6 +6654,17 @@ request HTTPS tiles even on HTTP localhost, with the existing Content Security
Policy unchanged. Ion attribution and Bing's per-tile credits are preserved; Policy unchanged. Ion attribution and Bing's per-tile credits are preserved;
other ion imagery assets continue through the SDK's standard ion factory. other ion imagery assets continue through the SDK's standard ion factory.
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
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.
The controller accepts other source registries without adding provider branches. The controller accepts other source registries without adding provider branches.
Each instance caches source construction, ignores superseded scene changes and Each instance caches source construction, ignores superseded scene changes and
releases imagery layers/listeners on replacement. Destroy invalidates pending releases imagery layers/listeners on replacement. Destroy invalidates pending
+7 -1
View File
@@ -153,7 +153,13 @@ back to Cesium. Both lists only ever shrink.
- `src/render/cesiumAllowList.json` lists the files outside the Cesium - `src/render/cesiumAllowList.json` lists the files outside the Cesium
adapter (`src/render/cesium/`) that may still import or be handed Cesium adapter (`src/render/cesium/`) that may still import or be handed Cesium
(`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list (`src/render/noCesiumOutsideRender.test.mjs`). A file leaves the list
when it no longer drives Cesium at all; nothing is added. when it no longer drives Cesium at all; nothing is added. Two files name
the adapter by design and are not on it: the application scene
(`src/app/scene.js`), the composition root that picks the Cesium renderer,
may import `src/render/cesium/application.js` and nothing else of the
adapter; the conformance page (`dev/conformance/main.js`) may import the
adapter's harness and scene renderer. The test names both
(`ADAPTER_ENTRIES`), and that list is never grown.
- `src/render/viewerAccessAllowList.json` counts, per file off that list, - `src/render/viewerAccessAllowList.json` counts, per file off that list,
the Cesium-shaped accesses through the viewer it still makes the Cesium-shaped accesses through the viewer it still makes
(`src/render/viewerAccess.test.mjs`): the viewer's `entities`, (`src/render/viewerAccess.test.mjs`): the viewer's `entities`,
+4 -4
View File
@@ -89,7 +89,7 @@
"./infrastructure/geojson": "./src/data/localGeojsonCore.js", "./infrastructure/geojson": "./src/data/localGeojsonCore.js",
"./infrastructure/lod": "./src/data/localGeojsonLod.js", "./infrastructure/lod": "./src/data/localGeojsonLod.js",
"./application": "./src/app/application.js", "./application": "./src/app/application.js",
"./application/viewer": "./src/app/viewer.js", "./application/viewer": "./src/render/cesium/applicationViewer.js",
"./build/vite": { "./build/vite": {
"node": "./build/vite.js" "node": "./build/vite.js"
}, },
@@ -197,9 +197,9 @@
"./geography/neighborhoods": "./src/data/neighborhoodPolygons.js", "./geography/neighborhoods": "./src/data/neighborhoodPolygons.js",
"./maps/controller": "./src/maps/controller.js", "./maps/controller": "./src/maps/controller.js",
"./maps/catalog": "./src/maps/catalog.js", "./maps/catalog": "./src/maps/catalog.js",
"./maps/imagery": "./src/maps/imagery.js", "./maps/imagery": "./src/render/cesium/mapImagery.js",
"./maps/terrain": "./src/maps/terrain.js", "./maps/terrain": "./src/render/cesium/mapTerrain.js",
"./maps/3d": "./src/maps/google3d.js", "./maps/3d": "./src/render/cesium/google3d.js",
"./maps/defaults": "./src/maps/defaultSources.js", "./maps/defaults": "./src/maps/defaultSources.js",
"./voice/controller": "./src/voice/realtimeController.js", "./voice/controller": "./src/voice/realtimeController.js",
"./voice/control": "./src/voice/control.js", "./voice/control": "./src/voice/control.js",
+14 -6
View File
@@ -84,7 +84,8 @@
"src/app/application.test.mjs", "src/app/application.test.mjs",
"src/app/mapLifecycle.test.mjs", "src/app/mapLifecycle.test.mjs",
"src/app/startupCamera.test.mjs", "src/app/startupCamera.test.mjs",
"src/app/viewer.js", "src/render/cesium/applicationViewer.js",
"src/sky/icrf.js",
"src/app/atmosphereCompat.test.mjs", "src/app/atmosphereCompat.test.mjs",
"src/standalone/application.js", "src/standalone/application.js",
"src/standalone/controls.js", "src/standalone/controls.js",
@@ -665,10 +666,14 @@
"src/maps/imageryComparison.js", "src/maps/imageryComparison.js",
"src/maps/credits.js", "src/maps/credits.js",
"src/maps/defaultSources.js", "src/maps/defaultSources.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/maps/imagery.js", "src/render/cesium/mapImagery.js",
"src/maps/registry.js", "src/maps/registry.js",
"src/maps/terrain.js", "src/render/cesium/mapTerrain.js",
"src/maps/engine.js",
"src/maps/startupRoute.js",
"src/maps/attribution.js",
"src/render/cesium/mapEngine.js",
"src/maps/terrainRetry.js", "src/maps/terrainRetry.js",
"src/maps/terrainRetry.test.mjs", "src/maps/terrainRetry.test.mjs",
"src/mapStackController.js", "src/mapStackController.js",
@@ -676,7 +681,7 @@
"src/mapStackChips.test.mjs", "src/mapStackChips.test.mjs",
"src/mapStackUnavailableReason.test.mjs", "src/mapStackUnavailableReason.test.mjs",
"src/mapStartup.test.mjs", "src/mapStartup.test.mjs",
"src/maps/sourceFactories.test.mjs", "src/render/cesium/mapSources.test.mjs",
"src/search/geospatial.js", "src/search/geospatial.js",
"src/search/http.js", "src/search/http.js",
"src/search/defaults.js", "src/search/defaults.js",
@@ -1125,6 +1130,9 @@
"src/view/index.test.mjs", "src/view/index.test.mjs",
"src/tools/views.test.mjs", "src/tools/views.test.mjs",
"src/app/embed.test.mjs", "src/app/embed.test.mjs",
"src/render/cesium/panelRendering.js",
"src/render/cesium/application.js",
"src/render/cesium/panelRendering.test.mjs",
"src/tools/globePanel.test.mjs", "src/tools/globePanel.test.mjs",
"src/costEndpointThrottle.test.mjs", "src/costEndpointThrottle.test.mjs",
"src/sources/gbfsStations.test.mjs", "src/sources/gbfsStations.test.mjs",
@@ -1141,7 +1149,7 @@
"scripts/build-bright-stars.mjs", "scripts/build-bright-stars.mjs",
"scripts/build-milky-way.mjs", "scripts/build-milky-way.mjs",
"src/sky/stars.test.mjs", "src/sky/stars.test.mjs",
"src/sky/starrySky.test.mjs", "src/render/cesium/starrySky.test.mjs",
"src/tooling/skyAssets.test.mjs", "src/tooling/skyAssets.test.mjs",
"src/tooling/skyAssets.paintOut.test.mjs", "src/tooling/skyAssets.paintOut.test.mjs",
"scripts/qa-anime-sky.mjs", "scripts/qa-anime-sky.mjs",
+45 -21
View File
@@ -204,12 +204,13 @@
"viewer": { "viewer": {
"exports": ["./application/viewer"], "exports": ["./application/viewer"],
"modules": [ "modules": [
"src/app/viewer.js", "src/render/cesium/applicationViewer.js",
"src/app/atmosphereCompat.js", "src/app/atmosphereCompat.js",
"src/sky/starrySky.js", "src/render/cesium/starrySky.js",
"src/sky/stars.js", "src/sky/stars.js",
"src/data/bundledJson.js", "src/data/bundledJson.js",
"src/renderGovernor.js" "src/renderGovernor.js",
"src/sky/icrf.js"
], ],
"external": ["cesium"] "external": ["cesium"]
}, },
@@ -1045,14 +1046,14 @@
"src/styles/surveillance.js", "src/styles/surveillance.js",
"src/styles/thermal.js", "src/styles/thermal.js",
"src/ui/applicationShell.js", "src/ui/applicationShell.js",
"src/sky/starrySky.js",
"src/render/cesium/effects.js", "src/render/cesium/effects.js",
"src/render/cesium/screenModulation.js", "src/render/cesium/screenModulation.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/baseTilesets.js", "src/render/baseTilesets.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/maps/startupRoute.js",
"src/sky/stars.js", "src/sky/stars.js",
"src/renderGovernor.js", "src/renderGovernor.js",
"src/data/bundledJson.js", "src/data/bundledJson.js",
@@ -1285,7 +1286,8 @@
"src/render/cesium/input.js", "src/render/cesium/input.js",
"src/render/input/wheel.js", "src/render/input/wheel.js",
"src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/ctrlWheelZoom.js",
"src/render/input/router.js" "src/render/input/router.js",
"src/sky/icrf.js"
], ],
"external": ["cesium", "vue", "pinia", "vue-i18n"] "external": ["cesium", "vue", "pinia", "vue-i18n"]
}, },
@@ -1839,7 +1841,7 @@
"src/render/cesium/unbound.js", "src/render/cesium/unbound.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/baseTilesets.js", "src/render/baseTilesets.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/render/cesium/iconSetPrimitive.js", "src/render/cesium/iconSetPrimitive.js",
@@ -1892,7 +1894,19 @@
"src/render/cesium/nativeClick.js", "src/render/cesium/nativeClick.js",
"src/render/input/router.js", "src/render/input/router.js",
"src/render/input/wheel.js", "src/render/input/wheel.js",
"src/render/cesium/input.js" "src/render/cesium/input.js",
"src/maps/engine.js",
"src/maps/attribution.js",
"src/maps/startupRoute.js",
"src/render/cesium/mapImagery.js",
"src/maps/terrainRetry.js",
"src/render/cesium/mapTerrain.js",
"src/render/cesium/mapEngine.js",
"src/data/bundledJson.js",
"src/renderGovernor.js",
"src/sky/icrf.js",
"src/sky/stars.js",
"src/render/cesium/starrySky.js"
], ],
"external": ["cesium"] "external": ["cesium"]
}, },
@@ -2398,7 +2412,7 @@
"src/layers/traffic/lifecycle.js", "src/layers/traffic/lifecycle.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/baseTilesets.js", "src/render/baseTilesets.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/layers/traffic/model.js", "src/layers/traffic/model.js",
@@ -2538,7 +2552,7 @@
"cctv-layer": { "cctv-layer": {
"exports": ["./layers/cctv"], "exports": ["./layers/cctv"],
"modules": [ "modules": [
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/render/cesium/globe.js", "src/render/cesium/globe.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
@@ -3092,10 +3106,10 @@
"src/render/creditMarkup.js", "src/render/creditMarkup.js",
"src/maps/defaultSources.js", "src/maps/defaultSources.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/maps/imagery.js", "src/render/cesium/mapImagery.js",
"src/maps/registry.js", "src/maps/registry.js",
"src/maps/terrain.js", "src/render/cesium/mapTerrain.js",
"src/maps/terrainRetry.js", "src/maps/terrainRetry.js",
"src/keySetupCore.mjs", "src/keySetupCore.mjs",
"src/localRequestGate.mjs", "src/localRequestGate.mjs",
@@ -3120,7 +3134,10 @@
"src/data/pickRegistry.js", "src/data/pickRegistry.js",
"src/render/cesium/input.js", "src/render/cesium/input.js",
"src/render/cesium/pickMemo.js", "src/render/cesium/pickMemo.js",
"src/render/cesium/nativeClick.js" "src/render/cesium/nativeClick.js",
"src/maps/attribution.js",
"src/maps/startupRoute.js",
"src/maps/engine.js"
], ],
"external": ["cesium"] "external": ["cesium"]
}, },
@@ -3331,9 +3348,9 @@
"src/app/surfaceServices.js", "src/app/surfaceServices.js",
"src/app/tools.js", "src/app/tools.js",
"src/data/followed.js", "src/data/followed.js",
"src/app/viewer.js", "src/render/cesium/applicationViewer.js",
"src/render/cesium/ctrlWheelZoom.js", "src/render/cesium/ctrlWheelZoom.js",
"src/sky/starrySky.js", "src/render/cesium/starrySky.js",
"src/sky/stars.js", "src/sky/stars.js",
"src/app/atmosphereCompat.js", "src/app/atmosphereCompat.js",
"src/bloom.js", "src/bloom.js",
@@ -3733,10 +3750,10 @@
"src/maps/credits.js", "src/maps/credits.js",
"src/maps/defaultSources.js", "src/maps/defaultSources.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/maps/imagery.js", "src/render/cesium/mapImagery.js",
"src/maps/registry.js", "src/maps/registry.js",
"src/maps/terrain.js", "src/render/cesium/mapTerrain.js",
"src/maps/terrainRetry.js", "src/maps/terrainRetry.js",
"src/navigationPolicy.js", "src/navigationPolicy.js",
"src/orbit.js", "src/orbit.js",
@@ -4273,7 +4290,14 @@
"src/render/cesium/internals.js", "src/render/cesium/internals.js",
"src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.js",
"src/render/cesium/nativeClick.js", "src/render/cesium/nativeClick.js",
"src/render/cesium/pickMemo.js" "src/render/cesium/pickMemo.js",
"src/maps/startupRoute.js",
"src/maps/engine.js",
"src/maps/attribution.js",
"src/render/cesium/mapEngine.js",
"src/sky/icrf.js",
"src/render/cesium/panelRendering.js",
"src/render/cesium/application.js"
], ],
"external": [ "external": [
"hls.js", "hls.js",
@@ -4331,7 +4355,7 @@
"src/render/cesium/gpuIcons.js", "src/render/cesium/gpuIcons.js",
"src/render/motion/iconMotion.js", "src/render/motion/iconMotion.js",
"src/render/cesium/imagery.js", "src/render/cesium/imagery.js",
"src/maps/google3d.js", "src/render/cesium/google3d.js",
"src/render/cesium/cameraControls.js", "src/render/cesium/cameraControls.js",
"src/render/cesium/follow.js", "src/render/cesium/follow.js",
"src/data/bhoteKoshiIncidentPlaces.js", "src/data/bhoteKoshiIncidentPlaces.js",
+4 -2
View File
@@ -32,13 +32,15 @@ try {
const results = await page.evaluate(async () => { const results = await page.evaluate(async () => {
window.CESIUM_BASE_URL = '/cesium/'; window.CESIUM_BASE_URL = '/cesium/';
// Use StarrySky's exact Vite dependency URL, including its version query. // Use StarrySky's exact Vite dependency URL, including its version query.
const source = await fetch('/src/sky/starrySky.js').then((r) => r.text()); const source = await fetch('/src/render/cesium/starrySky.js').then((r) =>
r.text(),
);
const cesiumUrl = source.match( const cesiumUrl = source.match(
/from ["']([^"']*\/cesium\.js[^"']*)["']/, /from ["']([^"']*\/cesium\.js[^"']*)["']/,
)?.[1]; )?.[1];
if (!cesiumUrl) throw new Error('run against the Vite dev server'); if (!cesiumUrl) throw new Error('run against the Vite dev server');
const C = await import(cesiumUrl); const C = await import(cesiumUrl);
const { StarrySky } = await import('/src/sky/starrySky.js'); const { StarrySky } = await import('/src/render/cesium/starrySky.js');
const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z'); const time = C.JulianDate.fromIso8601('2026-10-19T00:00:00Z');
const results = {}; const results = {};
for (const kind of ['black', 'starry', 'white']) { for (const kind of ['black', 'starry', 'white']) {
+1 -1
View File
@@ -8,7 +8,7 @@
* answers HTTP 429 for most of them. This harness drives that burst, counts the * answers HTTP 429 for most of them. This harness drives that burst, counts the
* throttled responses, keeps the first 429's headers as evidence, and then * throttled responses, keeps the first 429's headers as evidence, and then
* checks whether every throttled tile eventually loaded — the contract the * checks whether every throttled tile eventually loaded — the contract the
* client-side retry in `src/maps/terrain.js` provides. * client-side retry in `src/render/cesium/mapTerrain.js` provides.
* *
* Run against a keyless dev server (no Google or ion credentials): * Run against a keyless dev server (no Google or ion credentials):
* env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180 * env -u GOOGLE_MAPS_API_KEY -u CESIUM_ION_TOKEN npm run dev -- --port 4180
+3 -2
View File
@@ -222,8 +222,9 @@ test('the separate viewer export imports without constructing a browser viewer',
}); });
test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => { test('the viewer gets the starry sky as an option, which keeps the Sun and Moon', async () => {
const { applicationViewerOptions } = await import('./viewer.js'); const { applicationViewerOptions } =
const { StarrySky } = await import('../sky/starrySky.js'); await import('../render/cesium/applicationViewer.js');
const { StarrySky } = await import('../render/cesium/starrySky.js');
const creditContainer = {}; const creditContainer = {};
const options = applicationViewerOptions(creditContainer); const options = applicationViewerOptions(creditContainer);
// CesiumWidget skips scene.sun and scene.moon when skyBox is false. // CesiumWidget skips scene.sun and scene.moon when skyBox is false.
+4 -2
View File
@@ -8,10 +8,10 @@ import { t } from '../i18n/index.js';
* Construct the existing controls and camera presentation. `initialShareCode` * Construct the existing controls and camera presentation. `initialShareCode`
* opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host * opens a share code (the `<code>` of `/share/<code>`) at start-up, for a host
* whose address does not carry one. `localePicker: false` removes the language * whose address does not carry one. `localePicker: false` removes the language
* picker, for a host that does not initialize Core's locale. * picker, for a page that does not initialize the app's locale.
*/ */
export function createApplicationControls({ export function createApplicationControls({
scene: { viewer, mapStackController, operations }, scene: { viewer, mapStackController, operations, viewerDrawsEntity },
loaderStatus, loaderStatus,
Controls = StyleManager, Controls = StyleManager,
services, services,
@@ -30,6 +30,8 @@ export function createApplicationControls({
fetchRegionalBrief: (...args) => fetchRegionalBrief: (...args) =>
operations.requests.regional.getBrief(...args), operations.requests.regional.getBrief(...args),
...catalogControlServices(catalog), ...catalogControlServices(catalog),
// Whether an entity is one of the viewer's own; the scene answers it.
viewerDrawsEntity: viewerDrawsEntity ?? services?.viewerDrawsEntity,
}, },
requestServices: operations.requests, requestServices: operations.requests,
mapStackController, mapStackController,
+1 -1
View File
@@ -15,7 +15,7 @@ export function createApplicationData({
const dataManager = new LayerLifecycle(viewer, { const dataManager = new LayerLifecycle(viewer, {
allowQaRegistration, allowQaRegistration,
// A panel's host may report it hidden while it is on screen; its layers // A panel's host may report it hidden while it is on screen; its layers
// keep polling (see keepPanelRendering in embed.js). // keep polling (see keepPanelRendering in render/cesium/panelRendering.js).
visibilityTarget: panelAwareVisibility(document), visibilityTarget: panelAwareVisibility(document),
getSourceAvailability: catalog?.getSourceAvailability, getSourceAvailability: catalog?.getSourceAvailability,
}); });
+14 -78
View File
@@ -11,16 +11,9 @@
* embedded or not. * embedded or not.
*/ */
import * as Cesium from 'cesium';
import { announceNavigationAuthority } from '../navigationPolicy.js'; import { announceNavigationAuthority } from '../navigationPolicy.js';
import { cameraOf } from '../render/cesium/camera.js'; import { toRadians } from '../geo/index.js';
// The application's tools reach `findGlobe` callers too (the Recent Imagery import { cameraOf } from '../render/rendererOf.js';
// panel, Import and others): a viewer with no renderer bound gets its globe
// port from here, as it gets its camera.
import '../render/cesium/globe.js';
// The application's data reaches `findEffects` (the cyber contact sweep):
// such a viewer gets its effects port from here too.
import '../render/cesium/effects.js';
import { annotationsFromParams, createView } from '../view/index.js'; import { annotationsFromParams, createView } from '../view/index.js';
const EMBED_VIEW_MESSAGE = 'gev:view'; const EMBED_VIEW_MESSAGE = 'gev:view';
@@ -55,7 +48,8 @@ export function isEmbeddedInline() {
/** /**
* `doc`'s visibility for work that pauses in a hidden page. A panel's host * `doc`'s visibility for work that pauses in a hidden page. A panel's host
* may report it hidden while it is on screen (see keepPanelRendering), so an * may report it hidden while it is on screen (see keepPanelRendering in
* render/cesium/panelRendering.js), so an
* inline panel always reads as visible. * inline panel always reads as visible.
*/ */
export function panelAwareVisibility(doc = globalThis.document) { export function panelAwareVisibility(doc = globalThis.document) {
@@ -75,69 +69,6 @@ export function panelAwareVisibility(doc = globalThis.document) {
}; };
} }
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep the globe drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* Cesium's render loop; while frames stop arriving, draw from a timer.
* Returns a function that stops it.
*/
export function keepPanelRendering(
viewer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
// Cesium stops drawing after a render error, and so does the timer.
// Report the error in full: workers report plain objects, which Cesium
// prints as [object Object].
let failed = false;
const removeErrorListener = viewer.scene?.renderError?.addEventListener(
(_scene, error) => {
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
},
);
const timer = windowRef.setInterval(() => {
if (
failed ||
now() - lastFrame < MISSED_FRAMES_MS ||
viewer.isDestroyed?.()
)
return;
viewer.resize();
viewer.render();
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
removeErrorListener?.();
};
}
const delay = (ms, signal) => const delay = (ms, signal) =>
new Promise((resolve) => { new Promise((resolve) => {
const timer = setTimeout(resolve, ms); const timer = setTimeout(resolve, ms);
@@ -159,8 +90,8 @@ function flyTo(viewer, camera) {
{ lon: camera.lon, lat: camera.lat, height: camera.altitude_m }, { lon: camera.lon, lat: camera.lat, height: camera.altitude_m },
{ {
orientation: { orientation: {
heading: Cesium.Math.toRadians(camera.heading_deg), heading: toRadians(camera.heading_deg),
pitch: Cesium.Math.toRadians(camera.pitch_deg), pitch: toRadians(camera.pitch_deg),
roll: 0, roll: 0,
}, },
durationS: FLIGHT_SECONDS, durationS: FLIGHT_SECONDS,
@@ -249,6 +180,9 @@ export async function applyView(
/** /**
* Install embed mode when the page asks for it, and draw any annotations the * Install embed mode when the page asks for it, and draw any annotations the
* opening link carries. Returns a function that removes the message handler. * opening link carries. Returns a function that removes the message handler.
* `keepRendering({windowRef})` keeps the globe drawing in an inline panel
* whose host stops animation frames, and returns a function that stops it;
* the application scene gives it (`keepPanelRendering`).
*/ */
export function installViews({ export function installViews({
shell, shell,
@@ -256,6 +190,7 @@ export function installViews({
dataManager, dataManager,
run, run,
signal, signal,
keepRendering = null,
location = globalThis.location, location = globalThis.location,
windowRef = globalThis.window, windowRef = globalThis.window,
}) { }) {
@@ -271,9 +206,10 @@ export function installViews({
windowRef.document.body.classList.add('ui-embed'); windowRef.document.body.classList.add('ui-embed');
shell.setCleanView?.(true); shell.setCleanView?.(true);
const stopRendering = isEmbeddedInline() const stopRendering =
? keepPanelRendering(viewer, { windowRef }) isEmbeddedInline() && keepRendering
: () => {}; ? keepRendering({ windowRef })
: () => {};
// A framing page talks to the app across frames; an inline panel shares // A framing page talks to the app across frames; an inline panel shares
// the page with it and talks through the page's own window. // the page with it and talks through the page's own window.
const peer = isEmbeddedInline() ? windowRef : windowRef.parent; const peer = isEmbeddedInline() ? windowRef : windowRef.parent;
+8 -68
View File
@@ -5,7 +5,6 @@ import {
applyView, applyView,
installViews, installViews,
isEmbedded, isEmbedded,
keepPanelRendering,
panelAwareVisibility, panelAwareVisibility,
} from './embed.js'; } from './embed.js';
import { LayerLifecycle } from '../data/lifecycle.js'; import { LayerLifecycle } from '../data/lifecycle.js';
@@ -203,6 +202,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
globalThis.GEV_EMBED_INLINE = true; globalThis.GEV_EMBED_INLINE = true;
try { try {
assert.equal(isEmbedded({ search: '' }), true); assert.equal(isEmbedded({ search: '' }), true);
const kept = [];
const remove = installViews({ const remove = installViews({
shell: { initialRestorePromise: Promise.resolve() }, shell: { initialRestorePromise: Promise.resolve() },
viewer: fakeViewer(), viewer: fakeViewer(),
@@ -210,7 +210,13 @@ test('an app loaded inline into a panel page talks through its own window', asyn
run: recorder().run, run: recorder().run,
location: { search: '', hash: '' }, location: { search: '', hash: '' },
windowRef, windowRef,
// The scene's panel rendering, kept on while the views are installed.
keepRendering: (options) => {
kept.push(options.windowRef === windowRef);
return () => kept.push('stopped');
},
}); });
assert.deepEqual(kept, [true]);
await new Promise((resolve) => setTimeout(resolve, 0)); await new Promise((resolve) => setTimeout(resolve, 0));
assert.deepEqual(posted, [{ type: 'gev:ready' }]); assert.deepEqual(posted, [{ type: 'gev:ready' }]);
const event = new Event('message'); const event = new Event('message');
@@ -223,6 +229,7 @@ test('an app loaded inline into a panel page talks through its own window', asyn
assert.equal(posted[1].id, 7); assert.equal(posted[1].id, 7);
assert.equal(posted[1].ok, true); assert.equal(posted[1].ok, true);
remove(); remove();
assert.deepEqual(kept, [true, 'stopped']);
} finally { } finally {
delete globalThis.GEV_EMBED_INLINE; delete globalThis.GEV_EMBED_INLINE;
} }
@@ -301,73 +308,6 @@ test('annotations in a link are drawn after it restores, embedded or not', async
]); ]);
}); });
test('a panel keeps drawing from a timer while animation frames stop', () => {
let clock = 0;
let tick = null;
let frame = null;
const windowRef = {
requestAnimationFrame: (fn) => ((frame = fn), 1),
cancelAnimationFrame: () => (frame = null),
setInterval: (fn) => ((tick = fn), 1),
clearInterval: () => (tick = null),
};
const drawn = [];
const viewer = {
resize: () => drawn.push('resize'),
render: () => drawn.push('render'),
};
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
// Frames arrive: the render loop draws, so the timer does nothing.
clock = 100;
frame();
tick();
assert.deepEqual(drawn, []);
// Frames stop, as in a panel its host reports hidden: the timer draws.
clock = 400;
tick();
assert.deepEqual(drawn, ['resize', 'render']);
stop();
assert.equal(tick, null);
assert.equal(frame, null);
});
test('a panel reports a render error in full and stops drawing', () => {
let listener = null;
let tick = null;
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const drawn = [];
const viewer = {
resize() {},
render: () => drawn.push('render'),
scene: {
renderError: {
addEventListener: (fn) => ((listener = fn), () => (listener = null)),
},
},
};
const logged = [];
const original = console.error;
console.error = (...args) => logged.push(args.join(' '));
try {
let clock = 0;
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
listener(viewer.scene, { name: 'RuntimeError', message: 'worker failed' });
assert.match(logged[0], /render error: .*"message":"worker failed"/);
clock = 1000;
tick();
assert.deepEqual(drawn, []);
stop();
assert.equal(listener, null);
} finally {
console.error = original;
}
});
test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => { test('a followed aircraft owns the camera, and cockpit view is entered after it', async () => {
const viewer = fakeViewer(); const viewer = fakeViewer();
const { calls, run } = recorder(); const { calls, run } = recorder();
+1
View File
@@ -1,6 +1,7 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { MapStackController } from '../mapStackController.js'; import { MapStackController } from '../mapStackController.js';
import '../render/cesium/mapEngine.js';
import { import {
installRenderGovernor, installRenderGovernor,
uninstallRenderGovernor, uninstallRenderGovernor,
+13 -14
View File
@@ -1,14 +1,17 @@
import { createApplicationOperations } from './operations.js'; import { createApplicationOperations } from './operations.js';
import * as Cesium from 'cesium'; // The application's composition root: it picks the Cesium renderer, and
// this is the only part of the adapter it imports.
import { import {
applicationViewerHooks,
cesiumRenderer, cesiumRenderer,
cesiumViewerOf, cesiumViewerOf,
} from '../render/cesium/appRenderer.js'; loadApplicationPhotoreal,
import { trimStaleSceneCommands } from '../render/cesium/sceneCommandRelease.js'; releaseApplicationPhotoreal,
showApplicationPhotoreal,
} from '../render/cesium/application.js';
import { registerDataCredits } from '../data/dataCredits.js'; import { registerDataCredits } from '../data/dataCredits.js';
import { configureCreditKeyboardAccess } from '../creditKeyboard.js'; import { configureCreditKeyboardAccess } from '../creditKeyboard.js';
import { MapStackController } from '../mapStackController.js'; import { MapStackController } from '../mapStackController.js';
import { loadPhotorealisticTileset } from '../mapStartup.js';
import { initLogoGaze } from '../logoGaze.js'; import { initLogoGaze } from '../logoGaze.js';
import { inputFor } from '../input/dispatcher.js'; import { inputFor } from '../input/dispatcher.js';
import { import {
@@ -96,21 +99,17 @@ export async function createApplicationScene({
googleApiKey || googleTokens || cesiumToken googleApiKey || googleTokens || cesiumToken
? t('Loading Google 3D Tiles...') ? t('Loading Google 3D Tiles...')
: t('Loading the keyless globe...'); : t('Loading the keyless globe...');
const photoreal = await loadPhotorealisticTileset(Cesium, { const photoreal = await loadApplicationPhotoreal({
googleApiKey, googleApiKey,
googleTokens, googleTokens,
cesiumToken, cesiumToken,
}); });
const tileset = photoreal.tileset; const tileset = photoreal.tileset;
// A provider can finish after cancellation; retain ownership of its result. // A provider can finish after cancellation; retain ownership of its result.
defer(() => { defer(() => releaseApplicationPhotoreal(viewer, tileset));
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
});
signal.throwIfAborted(); signal.throwIfAborted();
if (tileset) { if (tileset) {
viewer.scene.primitives.add(tileset); showApplicationPhotoreal(viewer, tileset);
// NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom. // NOTE: Cesium World Terrain intentionally disabled — conflicts with Google 3D Tiles at high zoom.
// Google Photorealistic 3D Tiles provide their own terrain/elevation. // Google Photorealistic 3D Tiles provide their own terrain/elevation.
renderer.globe.setGlobeVisible(false); renderer.globe.setGlobeVisible(false);
@@ -166,8 +165,8 @@ export async function createApplicationScene({
mapStackController, mapStackController,
operations, operations,
input, input,
// Drops the draw commands the scene keeps after it stops drawing them; // Trims stale draw commands, keeps an inline panel drawing, and says
// run after a drawn frame (see src/sceneCommandRelease.js). // whether an entity is the viewer's own (render/cesium/application.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene), ...applicationViewerHooks(viewer),
}; };
} }
+2 -1
View File
@@ -165,7 +165,7 @@ export function createApplicationTools({
// the loop, refresh the one DOM surface we gated, render a frame. // the loop, refresh the one DOM surface we gated, render a frame.
const syncVisibilitySuspension = () => { const syncVisibilitySuspension = () => {
// A panel's host may report it hidden while it is on screen; the panel // A panel's host may report it hidden while it is on screen; the panel
// keeps drawing itself (see keepPanelRendering in embed.js). // keeps drawing itself (see keepPanelRendering in render/cesium/panelRendering.js).
const hidden = document.hidden && !isEmbeddedInline(); const hidden = document.hidden && !isEmbeddedInline();
renderer.frame.suspend(hidden); renderer.frame.suspend(hidden);
cockpitCloudEffects?.setSuspended?.(hidden); cockpitCloudEffects?.setSuspended?.(hidden);
@@ -232,6 +232,7 @@ export function createApplicationTools({
dataManager, dataManager,
run: (name, args) => voiceCommands.runner(name, args, { signal }), run: (name, args) => voiceCommands.runner(name, args, { signal }),
signal, signal,
keepRendering: scene.keepPanelRendering,
}), }),
); );
return { sceneDirector, annotations, voiceCommands }; return { sceneDirector, annotations, voiceCommands };
+1 -1
View File
@@ -1,6 +1,6 @@
# Sky background # Sky background
Catalogue stars over a soft Milky Way, drawn by `src/sky/starrySky.js` in Catalogue stars over a soft Milky Way, drawn by `src/render/cesium/starrySky.js` in
place of Cesium's blocky Tycho-2 sky box. place of Cesium's blocky Tycho-2 sky box.
| File | Content | Size | | File | Content | Size |
@@ -5,6 +5,8 @@ import * as Cesium from 'cesium';
import { MAP_STACKS } from '../mapStackController.js'; import { MAP_STACKS } from '../mapStackController.js';
import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js';
import { bindRenderer } from '../render/rendererOf.js'; import { bindRenderer } from '../render/rendererOf.js';
// A viewer with no renderer bound reads its globe through the unbound port.
import '../render/cesium/globe.js';
import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs';
import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs'; import { fakeCameraPort } from '../testSupport/fakeCameraPort.mjs';
import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs'; import { fakeSceneFrame } from '../testSupport/fakeCesiumScene.mjs';
+1 -1
View File
@@ -441,7 +441,7 @@ export class IntelHUD {
// Camera-derived data — 4 updates/second (250ms). Skipped in a hidden // Camera-derived data — 4 updates/second (250ms). Skipped in a hidden
// page, except an inline panel, whose host may report it hidden while it // page, except an inline panel, whose host may report it hidden while it
// is on screen (see keepPanelRendering in app/embed.js). // is on screen (see keepPanelRendering in render/cesium/panelRendering.js).
this._updateInterval = setInterval(() => { this._updateInterval = setInterval(() => {
if (!this._visible || (document.hidden && !isEmbeddedInline())) return; if (!this._visible || (document.hidden && !isEmbeddedInline())) return;
this._updateCameraData(); this._updateCameraData();
+1
View File
@@ -4,6 +4,7 @@ import assert from 'node:assert/strict';
import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js'; import { NO_IMAGERY_HOST } from '../../maps/imageryHost.js';
import { acquireImageryComparison } from '../../maps/imageryComparison.js'; import { acquireImageryComparison } from '../../maps/imageryComparison.js';
import { MapSourceController } from '../../maps/controller.js'; import { MapSourceController } from '../../maps/controller.js';
import '../../render/cesium/mapEngine.js';
import { createDefaultMapSources } from '../../maps/defaultSources.js'; import { createDefaultMapSources } from '../../maps/defaultSources.js';
import { resetPointerOwnership } from '../../data/inputOwnership.js'; import { resetPointerOwnership } from '../../data/inputOwnership.js';
import { initImageryBoxTool } from '../../ui/imageryBoxTool.js'; import { initImageryBoxTool } from '../../ui/imageryBoxTool.js';
+1 -4
View File
@@ -1,4 +1 @@
export { export { selectMapStartupRoute } from './maps/startupRoute.js';
selectMapStartupRoute,
loadPhotorealisticTileset,
} from './maps/google3d.js';
+2 -4
View File
@@ -3,10 +3,8 @@ import assert from 'node:assert/strict';
import { readFileSync } from 'node:fs'; import { readFileSync } from 'node:fs';
import vm from 'node:vm'; import vm from 'node:vm';
import { createGoogleTokenSource } from './maps/googleTokens.js'; import { createGoogleTokenSource } from './maps/googleTokens.js';
import { import { selectMapStartupRoute } from './mapStartup.js';
loadPhotorealisticTileset, import { loadPhotorealisticTileset } from './render/cesium/google3d.js';
selectMapStartupRoute,
} from './mapStartup.js';
function fakeCesium(outcomes = []) { function fakeCesium(outcomes = []) {
const calls = []; const calls = [];
+8
View File
@@ -0,0 +1,8 @@
/**
* @module maps/attribution
* @description The on-map credits of the map stacks' sources.
*/
// Attribution and service rights are documented in DATA_SOURCES.md.
export const ESRI_ATTRIBUTION_HTML =
'<a href="https://www.esri.com" target="_blank" rel="noopener">Powered by Esri</a>';
+7 -3
View File
@@ -1,4 +1,8 @@
import * as Cesium from 'cesium'; /**
* The map stacks the maps panel offers, free of renderer code: an `ion` stack's
* `style` is the Cesium ion world imagery asset it shows (2, aerial; 3,
* aerial with labels), the values of Cesium's `IonWorldImageryStyle`.
*/
export const MAP_STACKS = [ export const MAP_STACKS = [
{ {
id: 'photoreal', id: 'photoreal',
@@ -12,7 +16,7 @@ export const MAP_STACKS = [
label: 'Bing Aerial', // i18n-ignore: imagery product name label: 'Bing Aerial', // i18n-ignore: imagery product name
shortLabel: 'Aerial', shortLabel: 'Aerial',
kind: 'ion', kind: 'ion',
style: Cesium.IonWorldImageryStyle.AERIAL, style: 2,
requiresIon: true, requiresIon: true,
}, },
{ {
@@ -20,7 +24,7 @@ export const MAP_STACKS = [
label: 'Bing Labels', // i18n-ignore: imagery product name label: 'Bing Labels', // i18n-ignore: imagery product name
shortLabel: 'Labels', shortLabel: 'Labels',
kind: 'ion', kind: 'ion',
style: Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS, style: 3,
requiresIon: true, requiresIon: true,
}, },
{ {
+73 -62
View File
@@ -1,10 +1,7 @@
import { indexMapSources } from './registry.js'; import { indexMapSources } from './registry.js';
import * as Cesium from 'cesium';
import { createMapCredits } from './credits.js'; import { createMapCredits } from './credits.js';
// A viewer of a caller's own gets its credits port (and camera) from the import { mapEngine } from './engine.js';
// factories this loads. import { markBaseTileset } from '../render/baseTilesets.js';
import '../render/cesium/camera.js';
import { markBaseTileset } from '../render/cesium/globe.js';
import { acquireImageryComparison } from './imageryComparison.js'; import { acquireImageryComparison } from './imageryComparison.js';
/** /**
@@ -25,7 +22,12 @@ const resolved = (provider, effectiveStackId) => ({
fallbackMessage: null, fallbackMessage: null,
}); });
/** Coordinate source lifetimes and scene changes; the registry owns provider choices. */ /**
* 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.
*/
export class MapSourceController { export class MapSourceController {
constructor( constructor(
viewer, viewer,
@@ -34,11 +36,13 @@ export class MapSourceController {
initialStack, initialStack,
onChange = null, onChange = null,
onError = null, onError = null,
requestRender = () => viewer?.scene?.requestRender?.(), engine = mapEngine(),
createImageryLayer = (provider) => new Cesium.ImageryLayer(provider), requestRender = () => engine.requestRender(viewer),
createImageryLayer = (provider) => engine.createImageryLayer(provider),
}, },
) { ) {
this.viewer = viewer; this.viewer = viewer;
this._engine = engine;
this._registry = registry; this._registry = registry;
this._sources = indexMapSources(registry.sources); this._sources = indexMapSources(registry.sources);
this._activeId = this.isStackAvailable(initialStack) this._activeId = this.isStackAvailable(initialStack)
@@ -110,10 +114,11 @@ export class MapSourceController {
/** Return the shown supplied or controller-owned tileset, if any. */ /** Return the shown supplied or controller-owned tileset, if any. */
getImageryHostTileset() { getImageryHostTileset() {
if (this._destroyed) return null; if (this._destroyed) return null;
const shown = this._engine.tilesetShown;
for (const source of this._sources.values()) for (const source of this._sources.values())
if (source.tileset?.show === true) return source.tileset; if (shown(source.tileset)) return source.tileset;
for (const tileset of this._ownedTilesets) for (const tileset of this._ownedTilesets)
if (tileset.show === true) return tileset; if (shown(tileset)) return tileset;
return null; return null;
} }
/** /**
@@ -124,9 +129,9 @@ export class MapSourceController {
*/ */
getDrapeSurface() { getDrapeSurface() {
if (this._destroyed) return null; if (this._destroyed) return null;
if (this.viewer?.scene?.globe?.show === true) return 'globe'; if (this._engine.globeShown(this.viewer)) return 'globe';
const tileset = this.getImageryHostTileset(); const tileset = this.getImageryHostTileset();
return tileset && !tileset.isDestroyed?.() ? 'tileset' : 'none'; return tileset && !this._engine.isDestroyed(tileset) ? 'tileset' : 'none';
} }
getActiveId() { getActiveId() {
return this._activeId; return this._activeId;
@@ -285,23 +290,24 @@ export class MapSourceController {
} }
if (gen !== this._switchGen) return; if (gen !== this._switchGen) return;
if (!source.tileset && !this._ownedTilesets.has(tileset)) { if (!source.tileset && !this._ownedTilesets.has(tileset)) {
tileset.show = false; this._engine.showTileset(tileset, false);
markBaseTileset(tileset); markBaseTileset(tileset);
this.viewer.scene.primitives.add(tileset); this._engine.addTileset(this.viewer, tileset);
this._ownedTilesets.add(tileset); this._ownedTilesets.add(tileset);
} }
this._removeImageryLayer(); this._removeImageryLayer();
this._credits.show(source.credit || null); this._credits.show(source.credit || null);
this._showTileset(tileset); this._showTileset(tileset);
this.viewer.scene.globe.show = false; this._engine.setGlobeShown(this.viewer, false);
// Terrain is intentionally untouched while the globe is hidden. // Terrain is intentionally untouched while the globe is hidden.
} }
_showTileset(active) { _showTileset(active) {
const show = this._engine.showTileset;
for (const source of this._sources.values()) for (const source of this._sources.values())
if (source.tileset) source.tileset.show = source.tileset === active; if (source.tileset) show(source.tileset, source.tileset === active);
for (const tileset of this._ownedTilesets) for (const tileset of this._ownedTilesets)
tileset.show = tileset === active; show(tileset, tileset === active);
} }
async _activateGlobeStack(stack, gen) { async _activateGlobeStack(stack, gen) {
@@ -317,7 +323,7 @@ export class MapSourceController {
this._removeImageryLayer(); this._removeImageryLayer();
this._imageryLayer = this._createImageryLayer(resolution.provider); this._imageryLayer = this._createImageryLayer(resolution.provider);
this._activeImageryProvider = resolution.provider; this._activeImageryProvider = resolution.provider;
this.viewer.imageryLayers.add(this._imageryLayer, 0); this._engine.addImageryLayer(this.viewer, this._imageryLayer, 0);
} }
const source = this._sources.get(resolution.effectiveStackId); const source = this._sources.get(resolution.effectiveStackId);
this._credits.show(source?.credit || null); this._credits.show(source?.credit || null);
@@ -327,7 +333,7 @@ export class MapSourceController {
this._removeImageryErrorListener = null; this._removeImageryErrorListener = null;
this._watchProvider(resolution, gen); this._watchProvider(resolution, gen);
this._showTileset(null); this._showTileset(null);
this.viewer.scene.globe.show = true; this._engine.setGlobeShown(this.viewer, true);
this._activeId = resolution.effectiveStackId; this._activeId = resolution.effectiveStackId;
this._activeResolution = resolution; this._activeResolution = resolution;
if (source?.terrain && source.terrain.id !== this._terrainMode) { if (source?.terrain && source.terrain.id !== this._terrainMode) {
@@ -349,8 +355,7 @@ export class MapSourceController {
} }
_applyTerrain(result) { _applyTerrain(result) {
if (result.terrain) this.viewer.scene.setTerrain(result.terrain); this._engine.applyTerrain(this.viewer, result);
else this.viewer.terrainProvider = result.provider;
this._terrainFallback = result.fallback ? result : null; this._terrainFallback = result.fallback ? result : null;
if (this._replacedTerrain && this._replacedTerrain !== result) { if (this._replacedTerrain && this._replacedTerrain !== result) {
this._dispose(this._replacedTerrain.provider); this._dispose(this._replacedTerrain.provider);
@@ -379,7 +384,9 @@ export class MapSourceController {
async _retryFallbacks() { async _retryFallbacks() {
const resolution = this._activeResolution; const resolution = this._activeResolution;
const flat = this.viewer.scene.globe.show ? this._terrainFallback : null; const flat = this._engine.globeShown(this.viewer)
? this._terrainFallback
: null;
const id = resolution?.fallbackFor; const id = resolution?.fallbackFor;
let terrain = flat && this._sources.get(this._activeId)?.terrain; let terrain = flat && this._sources.get(this._activeId)?.terrain;
if (terrain?.id !== this._terrainMode) terrain = null; if (terrain?.id !== this._terrainMode) terrain = null;
@@ -460,7 +467,10 @@ export class MapSourceController {
return Boolean(real && !real.fallback); return Boolean(real && !real.fallback);
} }
this._terrainProviders.set(terrain.id, Promise.resolve(real)); this._terrainProviders.set(terrain.id, Promise.resolve(real));
if (this._terrainFallback === flat && this.viewer.scene.globe.show) { if (
this._terrainFallback === flat &&
this._engine.globeShown(this.viewer)
) {
this._applyTerrain(real); this._applyTerrain(real);
this._dispose(flat.provider); this._dispose(flat.provider);
this._requestRender('map-stack'); this._requestRender('map-stack');
@@ -540,50 +550,52 @@ export class MapSourceController {
const fallback = this._sources.get( const fallback = this._sources.get(
resolution.effectiveStackId, resolution.effectiveStackId,
)?.tileFailureFallback; )?.tileFailureFallback;
const errorEvent = resolution.provider?.errorEvent; if (!fallback) return;
if (!fallback || !errorEvent?.addEventListener) return;
let failures = 0; let failures = 0;
let pending = false; let pending = false;
this._removeImageryErrorListener = errorEvent.addEventListener((error) => { this._removeImageryErrorListener = this._engine.onTileError(
if ( resolution.provider,
gen !== this._switchGen || (error) => {
this._activeImageryProvider !== resolution.provider if (
) gen !== this._switchGen ||
return; this._activeImageryProvider !== resolution.provider
const retryCount = Number(error?.timesRetried); )
failures = return;
Number.isInteger(retryCount) && retryCount >= 0 const retryCount = Number(error?.timesRetried);
? Math.max(failures + 1, retryCount + 1) failures =
: failures + 1; Number.isInteger(retryCount) && retryCount >= 0
if (failures < fallback.threshold || pending) return; ? Math.max(failures + 1, retryCount + 1)
pending = true; : failures + 1;
this._onError?.( if (failures < fallback.threshold || pending) return;
fallback.message, pending = true;
this.getStack(resolution.effectiveStackId), this._onError?.(
); fallback.message,
const expectedGen = this._switchGen + 1; this.getStack(resolution.effectiveStackId),
void this.setStack(fallback.id, { silent: true, [AUTOMATIC]: true }) );
.then((state) => { const expectedGen = this._switchGen + 1;
if ( void this.setStack(fallback.id, { silent: true, [AUTOMATIC]: true })
!this._destroyed && .then((state) => {
this._switchGen === expectedGen && if (
state?.activeId === fallback.id !this._destroyed &&
) { this._switchGen === expectedGen &&
this._lastError = fallback.message; state?.activeId === fallback.id
this._emitChange('error'); ) {
} this._lastError = fallback.message;
}) this._emitChange('error');
.finally(() => { }
pending = false; })
}); .finally(() => {
}); pending = false;
});
},
);
} }
_removeImageryLayer() { _removeImageryLayer() {
this._removeImageryErrorListener?.(); this._removeImageryErrorListener?.();
this._removeImageryErrorListener = null; this._removeImageryErrorListener = null;
if (this._imageryLayer) if (this._imageryLayer)
this.viewer.imageryLayers.remove(this._imageryLayer, true); this._engine.removeImageryLayer(this.viewer, this._imageryLayer);
this._imageryLayer = null; this._imageryLayer = null;
this._activeImageryProvider = null; this._activeImageryProvider = null;
this._activeResolution = null; this._activeResolution = null;
@@ -591,8 +603,7 @@ export class MapSourceController {
_dispose(value) { _dispose(value) {
if (!value || this._disposed.has(value)) return; if (!value || this._disposed.has(value)) return;
this._disposed.add(value); this._disposed.add(value);
if (typeof value.destroy === 'function' && !value.isDestroyed?.()) this._engine.release(value);
value.destroy();
} }
destroy() { destroy() {
if (this._destroyed) return; if (this._destroyed) return;
@@ -620,7 +631,7 @@ export class MapSourceController {
() => {}, () => {},
); );
for (const tileset of this._ownedTilesets) { for (const tileset of this._ownedTilesets) {
this.viewer.scene.primitives.remove(tileset); this._engine.removeTileset(this.viewer, tileset);
this._dispose(tileset); this._dispose(tileset);
} }
for (const promise of this._tilesets.values()) for (const promise of this._tilesets.values())
+2
View File
@@ -1,6 +1,8 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { MapSourceController } from './controller.js'; import { MapSourceController } from './controller.js';
// The controller switches stacks through the Cesium map engine.
import '../render/cesium/mapEngine.js';
import { createDefaultMapSources } from './defaultSources.js'; import { createDefaultMapSources } from './defaultSources.js';
import { bindRenderer } from '../render/rendererOf.js'; import { bindRenderer } from '../render/rendererOf.js';
+16 -13
View File
@@ -2,28 +2,31 @@ import { MAP_STACKS } from './catalog.js';
import { photorealUnavailableReason } from './availability.js'; import { photorealUnavailableReason } from './availability.js';
import { keySetupRequirementEnvVars } from '../keySetupCore.mjs'; import { keySetupRequirementEnvVars } from '../keySetupCore.mjs';
import { t } from '../i18n/index.js'; import { t } from '../i18n/index.js';
import { import { mapEngine } from './engine.js';
createOsmImagery, import { ESRI_ATTRIBUTION_HTML } from './attribution.js';
createEsriImagery,
createIonImagery,
ESRI_ATTRIBUTION_HTML,
} from './imagery.js';
import { createWorldTerrain, createKeylessTerrain } from './terrain.js';
/** Select sources and setup guidance without putting provider branches in the controller. */ /**
* 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.
*/
export function createDefaultMapSources({ export function createDefaultMapSources({
googleTileset = null, googleTileset = null,
cesiumToken = '', cesiumToken = '',
googleApiKey = '', 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 ionToken = String(cesiumToken || '').trim();
const hasIon = Boolean(ionToken); const hasIon = Boolean(ionToken);
const hasGoogle = Boolean(String(googleApiKey || '').trim()); const hasGoogle = Boolean(String(googleApiKey || '').trim());
const terrain = { const terrain = {
id: hasIon ? 'world' : 'keyless', id: hasIon ? 'world' : 'keyless',
create: hasIon create: hasIon
? (request) => createWorldTerrain(ionToken, request) ? (request) => engineOf().terrain.world(ionToken, request)
: createKeylessTerrain, : () => engineOf().terrain.keyless(),
}; };
return { return {
defaultId: googleTileset ? 'photoreal' : 'esri-imagery', defaultId: googleTileset ? 'photoreal' : 'esri-imagery',
@@ -52,10 +55,10 @@ export function createDefaultMapSources({
}; };
const imagery = const imagery =
descriptor.kind === 'ion' descriptor.kind === 'ion'
? () => createIonImagery(descriptor.style, ionToken) ? () => engineOf().imagery.ion(descriptor.style, ionToken)
: descriptor.id === 'osm' : descriptor.id === 'osm'
? createOsmImagery ? () => engineOf().imagery.osm()
: createEsriImagery; : () => engineOf().imagery.esri();
return { return {
...common, ...common,
imagery, imagery,
+33
View File
@@ -0,0 +1,33 @@
/**
* @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.
*/
let provided = null;
/**
* Provide the map engine; a later call replaces it.
* @param {object} engine
*/
export function provideMapEngine(engine) {
provided = engine;
}
/**
* The map engine the renderer adapter provided.
* @returns {object}
* @throws {Error} When no adapter has provided one yet.
*/
export function mapEngine() {
if (!provided)
throw new Error(
'No map engine: load the renderer, or the package export ./render/cesium/unbound, first',
);
return provided;
}
@@ -1,6 +1,8 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { MapSourceController } from './controller.js'; import { MapSourceController } from './controller.js';
// The controller switches stacks through the Cesium map engine.
import '../render/cesium/mapEngine.js';
function fixture() { function fixture() {
return new MapSourceController( return new MapSourceController(
{ {
+20
View File
@@ -0,0 +1,20 @@
/**
* @module maps/startupRoute
* @description Which route the photoreal base starts on, from the
* credentials configured; Cesium-free.
*/
const clean = (value) => String(value || '').trim();
/**
* Decide which map provider can deliver the best startup experience.
* @param {{googleApiKey?: string, cesiumToken?: string}} credentials
* @returns {'google-direct'|'google-ion'|'osm'}
*/
export function selectMapStartupRoute({
googleApiKey = '',
cesiumToken = '',
} = {}) {
if (clean(googleApiKey)) return 'google-direct';
if (clean(cesiumToken)) return 'google-ion';
return 'osm';
}
+1 -1
View File
@@ -12,7 +12,7 @@ import {
import { import {
KEYLESS_TERRAIN_URL, KEYLESS_TERRAIN_URL,
createKeylessTerrainResource, createKeylessTerrainResource,
} from './terrain.js'; } from '../render/cesium/mapTerrain.js';
const START = 1_700_000_000_000; const START = 1_700_000_000_000;
+3 -1
View File
@@ -17,11 +17,13 @@
* crosses the contract and each call marks code still to port. Ported code * crosses the contract and each call marks code still to port. Ported code
* that still holds the viewer reaches the renderer through `rendererOf`. * that still holds the viewer reaches the renderer through `rendererOf`.
*/ */
import { createApplicationViewer } from '../../app/viewer.js'; import { createApplicationViewer } from './applicationViewer.js';
import { CONTRACT_VERSION } from '../contract/index.js'; import { CONTRACT_VERSION } from '../contract/index.js';
import { bindRenderer } from '../rendererOf.js'; import { bindRenderer } from '../rendererOf.js';
import { createCesiumInput } from './input.js'; import { createCesiumInput } from './input.js';
import { cesiumCapabilities, createCesiumPorts } from './ports.js'; import { cesiumCapabilities, createCesiumPorts } from './ports.js';
// The application's map stacks switch through the Cesium map engine.
import './mapEngine.js';
/** @typedef {import('../contract/renderer').Renderer} TransitionalRenderer */ /** @typedef {import('../contract/renderer').Renderer} TransitionalRenderer */
+59
View File
@@ -0,0 +1,59 @@
/**
* @module render/cesium/application
* @description The Cesium adapter's side of the application scene
* (`src/app/scene.js`), its composition root: the default renderer plugin,
* the viewer behind a renderer it made, the photoreal base tileset the scene
* loads into that viewer, and the viewer hooks the scene hands the
* application (stale command trimming, inline panel rendering, whether an
* entity is the viewer's own). The scene imports this module and no other
* part of the adapter (`src/render/noCesiumOutsideRender.test.mjs`).
*/
import * as Cesium from 'cesium';
import { cesiumRenderer, cesiumViewerOf } from './appRenderer.js';
import { loadPhotorealisticTileset } from './google3d.js';
import { keepPanelRendering } from './panelRendering.js';
import { trimStaleSceneCommands } from './sceneCommandRelease.js';
export { cesiumRenderer, cesiumViewerOf };
/**
* Load Google Photorealistic 3D Tiles for the application, by the best route
* the credentials allow (`google3d.js`).
* @param {{googleApiKey?: string, googleTokens?: object|null, cesiumToken?: string}} credentials
* @returns {Promise<{tileset: object|null, route: string, errors: Error[]}>}
*/
export const loadApplicationPhotoreal = (credentials) =>
loadPhotorealisticTileset(Cesium, credentials);
/** Draw the loaded photoreal tileset in `viewer`. */
export function showApplicationPhotoreal(viewer, tileset) {
viewer.scene.primitives.add(tileset);
}
/**
* Release the photoreal tileset: out of `viewer`, which destroys it, or
* destroyed by itself when the viewer never held it.
*/
export function releaseApplicationPhotoreal(viewer, tileset) {
if (tileset && !tileset.isDestroyed()) {
if (!viewer.scene.primitives.remove(tileset)) tileset.destroy();
}
}
/**
* What the application scene hands the application about its viewer.
* @param {object} viewer
*/
export function applicationViewerHooks(viewer) {
return {
// Drops the draw commands the scene keeps after it stops drawing them;
// run after a drawn frame (see sceneCommandRelease.js).
trimStaleCommands: () => trimStaleSceneCommands(viewer.scene),
// Keeps the globe drawing in an inline panel whose host stops animation
// frames (embed mode, src/app/embed.js).
keepPanelRendering: (options) => keepPanelRendering(viewer, options),
// Whether an entity is one of the viewer's own (Cockpit asks whether
// the aircraft it flies still draws).
viewerDrawsEntity: (entity) => viewer.entities.contains(entity),
};
}
@@ -1,6 +1,6 @@
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { applyModelAtmosphereWorkaround } from './atmosphereCompat.js'; import { applyModelAtmosphereWorkaround } from '../../app/atmosphereCompat.js';
import { StarrySky } from '../sky/starrySky.js'; import { StarrySky } from './starrySky.js';
// Dev convenience: expose the app's Cesium instance for console/preview probing // Dev convenience: expose the app's Cesium instance for console/preview probing
// (single shared module instance — avoids dual-Cesium state bugs when testing). // (single shared module instance — avoids dual-Cesium state bugs when testing).
+1 -1
View File
@@ -15,7 +15,7 @@
* the scene has no part for (stars without a sky box, say) is kept as set. * the scene has no part for (stars without a sky box, say) is kept as set.
*/ */
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { loadPhotorealisticTileset } from '../../maps/google3d.js'; import { loadPhotorealisticTileset } from './google3d.js';
import { provideUnboundGlobe } from '../rendererOf.js'; import { provideUnboundGlobe } from '../rendererOf.js';
import { isBaseTileset, markBaseTileset } from '../baseTilesets.js'; import { isBaseTileset, markBaseTileset } from '../baseTilesets.js';
import { listenerList, uncaught } from './common.js'; import { listenerList, uncaught } from './common.js';
@@ -1,18 +1,11 @@
const clean = (value) => String(value || '').trim();
/** /**
* Decide which map provider can deliver the best startup experience. * @module render/cesium/google3d
* @param {{googleApiKey?: string, cesiumToken?: string}} credentials * @description Google Photorealistic 3D Tiles for the Cesium renderer, by
* @returns {'google-direct'|'google-ion'|'osm'} * the routes `selectMapStartupRoute` (`src/maps/startupRoute.js`) names.
*/ */
export function selectMapStartupRoute({ export { selectMapStartupRoute } from '../../maps/startupRoute.js';
googleApiKey = '',
cesiumToken = '', const clean = (value) => String(value || '').trim();
} = {}) {
if (clean(googleApiKey)) return 'google-direct';
if (clean(cesiumToken)) return 'google-ion';
return 'osm';
}
/** /**
* Load Google Photorealistic 3D Tiles through direct Google access when * Load Google Photorealistic 3D Tiles through direct Google access when
+80
View File
@@ -0,0 +1,80 @@
/**
* @module render/cesium/mapEngine
* @description The Cesium map engine (`src/maps/engine.js`): the providers
* the map stacks' imagery and terrain come from (`mapImagery.js`,
* `mapTerrain.js`), and the viewer operations the map source controller
* switches stacks with. Provided as this module loads.
*/
import * as Cesium from 'cesium';
import { provideMapEngine } from '../../maps/engine.js';
import {
createEsriImagery,
createIonImagery,
createOsmImagery,
} from './mapImagery.js';
import { createKeylessTerrain, createWorldTerrain } from './mapTerrain.js';
export const cesiumMapEngine = Object.freeze({
imagery: Object.freeze({
osm: createOsmImagery,
esri: createEsriImagery,
/** `style`: the ion world imagery asset (`MAP_STACKS`' `style`). */
ion: createIonImagery,
}),
terrain: Object.freeze({
world: createWorldTerrain,
keyless: createKeylessTerrain,
}),
/** The layer a globe stack's imagery provider draws through. */
createImageryLayer: (provider) => new Cesium.ImageryLayer(provider),
requestRender(viewer) {
viewer?.scene?.requestRender?.();
},
globeShown: (viewer) => viewer?.scene?.globe?.show === true,
setGlobeShown(viewer, shown) {
viewer.scene.globe.show = shown;
},
addTileset(viewer, tileset) {
viewer.scene.primitives.add(tileset);
},
removeTileset(viewer, tileset) {
viewer.scene.primitives.remove(tileset);
},
tilesetShown: (tileset) => tileset?.show === true,
showTileset(tileset, shown) {
tileset.show = shown;
},
/** Below every other imagery layer, at `index`. */
addImageryLayer(viewer, layer, index) {
viewer.imageryLayers.add(layer, index);
},
/** Removed and destroyed. */
removeImageryLayer(viewer, layer) {
viewer.imageryLayers.remove(layer, true);
},
/** A terrain factory's result: `{terrain}` or `{provider}`. */
applyTerrain(viewer, result) {
if (result.terrain) viewer.scene.setTerrain(result.terrain);
else viewer.terrainProvider = result.provider;
},
/**
* Hear an imagery provider's failed tile requests, each with the times
* Cesium retried it; null when the provider reports none.
* @returns {(() => void) | null} Stop hearing them.
*/
onTileError(provider, listener) {
const errorEvent = provider?.errorEvent;
if (!errorEvent?.addEventListener) return null;
return errorEvent.addEventListener((error) =>
listener({ timesRetried: error?.timesRetried }),
);
},
isDestroyed: (value) => value?.isDestroyed?.() === true,
/** Destroy a provider or tileset unless it is already destroyed. */
release(value) {
if (typeof value?.destroy === 'function' && !value.isDestroyed?.())
value.destroy();
},
});
provideMapEngine(cesiumMapEngine);
@@ -1,8 +1,11 @@
/**
* @module render/cesium/mapImagery
* @description The map stacks' imagery for the Cesium renderer: OSM, Esri
* World Imagery and Cesium ion's world imagery (Bing over HTTPS).
*/
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
// Attribution and service rights are documented in DATA_SOURCES.md. export { ESRI_ATTRIBUTION_HTML } from '../../maps/attribution.js';
export const ESRI_ATTRIBUTION_HTML =
'<a href="https://www.esri.com" target="_blank" rel="noopener">Powered by Esri</a>';
export function createOsmImagery() { export function createOsmImagery() {
return new Cesium.OpenStreetMapImageryProvider({ return new Cesium.OpenStreetMapImageryProvider({
@@ -1,9 +1,29 @@
import test from 'node:test'; import test from 'node:test';
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createIonImagery } from './imagery.js'; import { createIonImagery } from './mapImagery.js';
import { createWorldTerrain, createKeylessTerrain } from './terrain.js'; import { createWorldTerrain, createKeylessTerrain } from './mapTerrain.js';
import { createDefaultMapSources } from './defaultSources.js'; import { createDefaultMapSources } from '../../maps/defaultSources.js';
import { MAP_STACKS } from '../../maps/catalog.js';
import { mapEngine } from '../../maps/engine.js';
import { cesiumMapEngine } from './mapEngine.js';
test('loading the Cesium map engine provides it to the map stacks', () => {
assert.equal(mapEngine(), cesiumMapEngine);
});
test('ion stacks name the Cesium ion world imagery assets', () => {
const styles = Object.fromEntries(
MAP_STACKS.filter(({ kind }) => kind === 'ion').map(({ id, style }) => [
id,
style,
]),
);
assert.deepEqual(styles, {
'bing-aerial': Cesium.IonWorldImageryStyle.AERIAL,
'bing-labels': Cesium.IonWorldImageryStyle.AERIAL_WITH_LABELS,
});
});
test('Esri uses Re:Earth without keys and preserves ion terrain when configured', async () => { test('Esri uses Re:Earth without keys and preserves ion terrain when configured', async () => {
const originalTerrain = Cesium.CesiumTerrainProvider.fromUrl; const originalTerrain = Cesium.CesiumTerrainProvider.fromUrl;
@@ -22,7 +42,6 @@ test('Esri uses Re:Earth without keys and preserves ion terrain when configured'
); );
assert.equal(esri.available, true); assert.equal(esri.available, true);
assert.equal(esri.terrain.id, 'keyless'); assert.equal(esri.terrain.id, 'keyless');
assert.equal(esri.terrain.create, createKeylessTerrain);
await esri.terrain.create(); await esri.terrain.create();
// A Resource, not a bare URL: the retry policy rides on it (terrainRetry.js). // A Resource, not a bare URL: the retry policy rides on it (terrainRetry.js).
assert.equal(calls.length, 1); assert.equal(calls.length, 1);
@@ -1,5 +1,11 @@
/**
* @module render/cesium/mapTerrain
* @description The map stacks' terrain for the Cesium renderer: Cesium
* World Terrain through ion, or Re:Earth's keyless terrain with its tile
* retry policy (`src/maps/terrainRetry.js`).
*/
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { createTerrainRetryPolicy } from './terrainRetry.js'; import { createTerrainRetryPolicy } from '../../maps/terrainRetry.js';
/** Re:Earth / Mapterhorn ellipsoidal quantized mesh, CC BY 4.0. */ /** Re:Earth / Mapterhorn ellipsoidal quantized mesh, CC BY 4.0. */
export const KEYLESS_TERRAIN_URL = export const KEYLESS_TERRAIN_URL =
+69
View File
@@ -0,0 +1,69 @@
/**
* @module render/cesium/panelRendering
* @description Keeping the Cesium viewer drawing in an inline panel whose
* host stops animation frames (`src/app/embed.js`, embed mode). The
* application scene hands it to the embed views (`src/app/scene.js`).
*/
// A panel keeps drawing at about this rate when its host stops animation
// frames; see keepPanelRendering.
const PANEL_FRAME_MS = 33;
const MISSED_FRAMES_MS = 250;
/** A render error's details, including the plain objects workers report. */
function describeError(error) {
if (error instanceof Error)
return `${error.name}: ${error.message}\n${error.stack}`;
try {
return JSON.stringify(error, Object.getOwnPropertyNames(error ?? {}));
} catch {
return String(error);
}
}
/**
* Keep the globe drawing in an inline panel. Some hosts report a panel on
* screen as hidden, which stops the browser's animation frames and with them
* Cesium's render loop; while frames stop arriving, draw from a timer.
* Returns a function that stops it.
*/
export function keepPanelRendering(
viewer,
{ windowRef = globalThis.window, now = () => performance.now() } = {},
) {
let lastFrame = now();
let frameRequest = null;
const onFrame = () => {
lastFrame = now();
frameRequest = windowRef.requestAnimationFrame(onFrame);
};
frameRequest = windowRef.requestAnimationFrame(onFrame);
// Cesium stops drawing after a render error, and so does the timer.
// Report the error in full: workers report plain objects, which Cesium
// prints as [object Object].
let failed = false;
const removeErrorListener = viewer.scene?.renderError?.addEventListener(
(_scene, error) => {
failed = true;
console.error(
"[God's Eye View panel] render error:",
describeError(error),
);
},
);
const timer = windowRef.setInterval(() => {
if (
failed ||
now() - lastFrame < MISSED_FRAMES_MS ||
viewer.isDestroyed?.()
)
return;
viewer.resize();
viewer.render();
}, PANEL_FRAME_MS);
return () => {
windowRef.clearInterval(timer);
windowRef.cancelAnimationFrame(frameRequest);
removeErrorListener?.();
};
}
+70
View File
@@ -0,0 +1,70 @@
import assert from 'node:assert/strict';
import test from 'node:test';
import { keepPanelRendering } from './panelRendering.js';
test('a panel keeps drawing from a timer while animation frames stop', () => {
let clock = 0;
let tick = null;
let frame = null;
const windowRef = {
requestAnimationFrame: (fn) => ((frame = fn), 1),
cancelAnimationFrame: () => (frame = null),
setInterval: (fn) => ((tick = fn), 1),
clearInterval: () => (tick = null),
};
const drawn = [];
const viewer = {
resize: () => drawn.push('resize'),
render: () => drawn.push('render'),
};
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
// Frames arrive: the render loop draws, so the timer does nothing.
clock = 100;
frame();
tick();
assert.deepEqual(drawn, []);
// Frames stop, as in a panel its host reports hidden: the timer draws.
clock = 400;
tick();
assert.deepEqual(drawn, ['resize', 'render']);
stop();
assert.equal(tick, null);
assert.equal(frame, null);
});
test('a panel reports a render error in full and stops drawing', () => {
let listener = null;
let tick = null;
const windowRef = {
requestAnimationFrame: () => 1,
cancelAnimationFrame() {},
setInterval: (fn) => ((tick = fn), 1),
clearInterval() {},
};
const drawn = [];
const viewer = {
resize() {},
render: () => drawn.push('render'),
scene: {
renderError: {
addEventListener: (fn) => ((listener = fn), () => (listener = null)),
},
},
};
const logged = [];
const original = console.error;
console.error = (...args) => logged.push(args.join(' '));
try {
let clock = 0;
const stop = keepPanelRendering(viewer, { windowRef, now: () => clock });
listener(viewer.scene, { name: 'RuntimeError', message: 'worker failed' });
assert.match(logged[0], /render error: .*"message":"worker failed"/);
clock = 1000;
tick();
assert.deepEqual(drawn, []);
stop();
assert.equal(listener, null);
} finally {
console.error = original;
}
});
@@ -1,7 +1,8 @@
import * as Cesium from 'cesium'; import * as Cesium from 'cesium';
import { loadBundledJson } from '../data/bundledJson.js'; import { loadBundledJson } from '../../data/bundledJson.js';
import { governorRequestRender } from '../renderGovernor.js'; import { governorRequestRender } from '../../renderGovernor.js';
import { buildStarVertices, STAR_VERTEX_FLOATS } from './stars.js'; import { buildStarVertices, STAR_VERTEX_FLOATS } from '../../sky/stars.js';
import { provideIcrfToFixed } from '../../sky/icrf.js';
/** /**
* Space background in the `Scene#skyBox` slot: catalogue stars as point * Space background in the `Scene#skyBox` slot: catalogue stars as point
@@ -18,32 +19,32 @@ export const MILKY_WAY_INTENSITY = 0.4;
export const SKY_ROTATION_EPSILON_SECONDS = 1; export const SKY_ROTATION_EPSILON_SECONDS = 1;
const STAR_PACK_URL = new URL( const STAR_PACK_URL = new URL(
'../data/local_data/sky/bright_stars.json', '../../data/local_data/sky/bright_stars.json',
import.meta.url, import.meta.url,
); );
const MILKY_WAY_FACE_URLS = Object.freeze({ const MILKY_WAY_FACE_URLS = Object.freeze({
positiveX: new URL( positiveX: new URL(
'../data/local_data/sky/milkyway_px.webp', '../../data/local_data/sky/milkyway_px.webp',
import.meta.url, import.meta.url,
), ),
negativeX: new URL( negativeX: new URL(
'../data/local_data/sky/milkyway_nx.webp', '../../data/local_data/sky/milkyway_nx.webp',
import.meta.url, import.meta.url,
), ),
positiveY: new URL( positiveY: new URL(
'../data/local_data/sky/milkyway_py.webp', '../../data/local_data/sky/milkyway_py.webp',
import.meta.url, import.meta.url,
), ),
negativeY: new URL( negativeY: new URL(
'../data/local_data/sky/milkyway_ny.webp', '../../data/local_data/sky/milkyway_ny.webp',
import.meta.url, import.meta.url,
), ),
positiveZ: new URL( positiveZ: new URL(
'../data/local_data/sky/milkyway_pz.webp', '../../data/local_data/sky/milkyway_pz.webp',
import.meta.url, import.meta.url,
), ),
negativeZ: new URL( negativeZ: new URL(
'../data/local_data/sky/milkyway_nz.webp', '../../data/local_data/sky/milkyway_nz.webp',
import.meta.url, import.meta.url,
), ),
}); });
@@ -151,6 +152,9 @@ export function icrfToFixedAxes(ms) {
}; };
} }
// Cesium-free code asks for it through `src/sky/icrf.js`.
provideIcrfToFixed(icrfToFixedAxes);
/** Whether a cached rotation at `cachedTime` still serves `time`. */ /** Whether a cached rotation at `cachedTime` still serves `time`. */
export function isSkyRotationCurrent(cachedTime, time) { export function isSkyRotationCurrent(cachedTime, time) {
return ( return (
@@ -10,6 +10,7 @@ import {
icrfToFixedAxes, icrfToFixedAxes,
isSkyRotationCurrent, isSkyRotationCurrent,
} from './starrySky.js'; } from './starrySky.js';
import * as neutral from '../../sky/icrf.js';
const close = (actual, expected, epsilon = 1e-9) => const close = (actual, expected, epsilon = 1e-9) =>
assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} vs ${expected}`); assert.ok(Math.abs(actual - expected) <= epsilon, `${actual} vs ${expected}`);
@@ -221,3 +222,26 @@ test('the precise frame is given as its axes once its tables answer', (t) => {
); );
assert.equal(icrfToFixedAxes(ms), null); assert.equal(icrfToFixedAxes(ms), null);
}); });
test('loading the sky provides its precise rotation to Cesium-free code', () => {
const ms = Date.parse('2026-10-19T00:00:00Z');
const original = Cesium.Transforms.computeIcrfToFixedMatrix;
Cesium.Transforms.computeIcrfToFixedMatrix = (_time, result) =>
Cesium.Matrix3.clone(Cesium.Matrix3.fromRotationZ(0.3), result);
try {
const axes = neutral.icrfToFixedAxes(ms);
assert.notEqual(axes, null);
assert.deepEqual(axes, icrfToFixedAxes(ms));
} finally {
Cesium.Transforms.computeIcrfToFixedMatrix = original;
}
});
test('the neutral rotation answers null with nothing provided', () => {
neutral.provideIcrfToFixed(null);
try {
assert.equal(neutral.icrfToFixedAxes(0), null);
} finally {
neutral.provideIcrfToFixed(icrfToFixedAxes);
}
});
+6 -2
View File
@@ -3,13 +3,17 @@
* @description What to load, once, before handing the Cesium-free * @description What to load, once, before handing the Cesium-free
* layers a Cesium viewer with no renderer bound: the factories * layers a Cesium viewer with no renderer bound: the factories
* that build a camera, credits, effects, draw, frame, globe, input and query * that build a camera, credits, effects, draw, frame, globe, input and query
* port over such a viewer when code first asks for one, and a click's own * port over such a viewer when code first asks for one, a click's own
* Cesium picks (`rendererOf.js`). * Cesium picks (`rendererOf.js`), the map engine the map stacks switch
* through (`src/maps/engine.js`), and the sky's precise ICRF rotation
* (`src/sky/icrf.js`).
*/ */
import './camera.js'; import './camera.js';
import './effects.js'; import './effects.js';
import './frame.js'; import './frame.js';
import './globe.js'; import './globe.js';
import './input.js'; import './input.js';
import './mapEngine.js';
import './nativeClick.js'; import './nativeClick.js';
import './query.js'; import './query.js';
import './starrySky.js';
+1 -14
View File
@@ -1,14 +1 @@
[ ["src/data/geoImportPins.js"]
"dev/conformance/main.js",
"src/app/embed.js",
"src/app/scene.js",
"src/app/viewer.js",
"src/data/geoImportPins.js",
"src/maps/catalog.js",
"src/maps/controller.js",
"src/maps/google3d.js",
"src/maps/imagery.js",
"src/maps/terrain.js",
"src/sky/starrySky.js",
"src/ui/applicationShell.js"
]
+139 -9
View File
@@ -19,6 +19,9 @@
* file. Any name `cesium` counts, so a config field of that name would * file. Any name `cesium` counts, so a config field of that name would
* over-report rather than slip through. * over-report rather than slip through.
* *
* Two files name the adapter by design and are not on the list:
* `ADAPTER_ENTRIES` below allows each exactly the adapter modules it needs.
*
* Runtime code is every `.js`, `.mjs`, `.cjs` and `.vue` file under `src/`, * Runtime code is every `.js`, `.mjs`, `.cjs` and `.vue` file under `src/`,
* `server/` and `dev/`, except tests and test support. */ * `server/` and `dev/`, except tests and test support. */
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
@@ -52,6 +55,25 @@ const isTestSupport = (file) =>
TEST_ONLY.has(file); TEST_ONLY.has(file);
const isAdapter = (file) => file.startsWith('src/render/cesium/'); const isAdapter = (file) => file.startsWith('src/render/cesium/');
/**
* The two places outside the adapter that name it by design, each limited
* to the adapter modules listed here; any other way they reach Cesium
* counts as above. Neither is a file still to port, so neither is on the
* allow-list; this list is never grown.
* - The application scene is the composition root: it picks the Cesium
* renderer as the default and takes the viewer hooks it hands the
* application from the adapter's application module.
* - The conformance page runs the suite on the Cesium adapter's harness
* and draws the reference scenes on its scene renderer.
*/
const ADAPTER_ENTRIES = {
'src/app/scene.js': ['src/render/cesium/application.js'],
'dev/conformance/main.js': [
'src/render/cesium/harness.js',
'src/render/cesium/sceneRenderer.js',
],
};
const git = (...args) => const git = (...args) =>
execFileSync('git', args, { cwd: root, encoding: 'utf8' }); execFileSync('git', args, { cwd: root, encoding: 'utf8' });
const tracked = git( const tracked = git(
@@ -70,19 +92,27 @@ const runtimeFiles = tracked.filter(
/\.(?:[cm]?js|vue)$/.test(file) && !isTestSupport(file) && !isAdapter(file), /\.(?:[cm]?js|vue)$/.test(file) && !isTestSupport(file) && !isAdapter(file),
); );
/** Whether an import specifier from `file` reaches Cesium. */ /**
function reachesCesium(file, specifier) { * The repository path a relative or root-relative specifier names. Vite
* reads `/x` from the project root, not the filesystem's.
*/
function targetOf(file, specifier) {
const bare = specifier.replace(/[?#].*$/, ''); const bare = specifier.replace(/[?#].*$/, '');
if (/^(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(bare)) return true; if (!bare.startsWith('.') && !bare.startsWith('/')) return null;
if (!bare.startsWith('.') && !bare.startsWith('/')) return false;
// Vite reads `/x` from the project root, not the filesystem's.
const from = bare.startsWith('/') const from = bare.startsWith('/')
? root ? root
: path.join(root, path.dirname(file)); : path.join(root, path.dirname(file));
const target = path return path.relative(root, path.join(from, bare)).split(path.sep).join('/');
.relative(root, path.join(from, bare)) }
.split(path.sep)
.join('/'); /** Whether an import specifier from `file` reaches Cesium. */
function reachesCesium(file, specifier) {
const allowed = ADAPTER_ENTRIES[file];
if (allowed?.includes(targetOf(file, specifier))) return false;
const bare = specifier.replace(/[?#].*$/, '');
if (/^(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(bare)) return true;
const target = targetOf(file, specifier);
if (target === null) return false;
return ( return (
isAdapter(target) || isAdapter(target) ||
/^node_modules\/(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(target) /^node_modules\/(?:cesium|@cesium\/[^/]+)(?:\/|$)/.test(target)
@@ -233,6 +263,106 @@ test('every allow-listed file still reaches Cesium', () => {
assert.deepEqual(stale, [], `Remove these from ${LIST}.`); assert.deepEqual(stale, [], `Remove these from ${LIST}.`);
}); });
test('the files that name the adapter by design import exactly what they are allowed', () => {
const present = new Set(runtimeFiles);
for (const [file, modules] of Object.entries(ADAPTER_ENTRIES)) {
assert.ok(present.has(file), `${file} is gone: drop it from the list`);
assert.ok(!allowList.includes(file), `${file} is on ${LIST} too`);
const { imports } = scan(readFileSync(path.join(root, file), 'utf8'));
const named = new Set(imports.map((s) => targetOf(file, s)));
for (const module of modules)
assert.ok(named.has(module), `${file} no longer imports ${module}`);
}
});
/** Every node under `node`, with its parent. */
function* nodesOf(node, parent = null) {
if (!node || typeof node !== 'object') return;
if (Array.isArray(node)) {
for (const child of node) yield* nodesOf(child, parent);
return;
}
if (typeof node.type === 'string') yield [node, parent];
for (const [key, value] of Object.entries(node))
if (!['loc', 'comments', 'tokens', 'extra'].includes(key))
yield* nodesOf(value, typeof node.type === 'string' ? node : parent);
}
test('the files that name the adapter by design take named exports, never Cesium itself', () => {
for (const [file, modules] of Object.entries(ADAPTER_ENTRIES)) {
const parsed = parsers.babel.parse(
readFileSync(path.join(root, file), 'utf8'),
);
// A static import by name only: no namespace or default binding, no
// dynamic import, and no forwarding of the module.
for (const [node] of nodesOf(parsed.program)) {
const source = node.source?.value;
if (typeof source !== 'string') continue;
if (!modules.includes(targetOf(file, source))) continue;
assert.equal(
node.type,
'ImportDeclaration',
`${file} must import ${source} statically and not forward it`,
);
assert.deepEqual(
node.specifiers
.filter((s) => s.type !== 'ImportSpecifier')
.map((s) => s.local.name),
[],
`${file} must import ${source} by name`,
);
}
// The allowed modules hand out no Cesium namespace: no export from the
// package, and no exported value that is the namespace itself (members
// of it, such as `Cesium.Math`, are the adapter's own business).
for (const module of modules) {
const program = parsers.babel.parse(
readFileSync(path.join(root, module), 'utf8'),
).program;
const fromCesium = ({ source }) => {
if (typeof source?.value !== 'string') return false;
const bare = source.value.replace(/[?#].*$/, '');
const target = targetOf(module, bare) ?? '';
return /^(?:(?:node_modules\/)?(?:cesium|@cesium\/[^/]+))(?:\/|$)/.test(
target || bare,
);
};
const namespaces = new Set(
program.body
.filter((n) => n.type === 'ImportDeclaration' && fromCesium(n))
.flatMap((n) => n.specifiers.map((s) => s.local.name)),
);
for (const node of program.body) {
if (!node.type.startsWith('Export')) continue;
assert.ok(!fromCesium(node), `${module} must not re-export Cesium`);
for (const [inner, parent] of nodesOf(node)) {
if (inner.type !== 'Identifier' || !namespaces.has(inner.name))
continue;
// Handing the namespace to the adapter's own functions is fine;
// giving it out as a value is not.
const handedOut =
[
'ExportSpecifier',
'ExportDefaultDeclaration',
'ReturnStatement',
'SpreadElement',
'ArrayExpression',
].includes(parent?.type) ||
(parent?.type === 'VariableDeclarator' && parent.init === inner) ||
(parent?.type === 'ObjectProperty' && parent.value === inner) ||
(parent?.type === 'ArrowFunctionExpression' &&
parent.body === inner) ||
(parent?.type === 'AssignmentExpression' && parent.right === inner);
assert.ok(
!handedOut,
`${module} must not export ${inner.name} itself`,
);
}
}
}
}
});
test('the allow-list only shrinks', (t) => { test('the allow-list only shrinks', (t) => {
// Any git failure fails the check: only the list's confirmed absence on // Any git failure fails the check: only the list's confirmed absence on
// origin/main (before it lands) skips it. // origin/main (before it lands) skips it.
+23 -8
View File
@@ -49,13 +49,11 @@ const UNBOUND = 'src/render/cesium/unbound.js';
/** /**
* Entries that take their Cesium code injected: the module named here is * Entries that take their Cesium code injected: the module named here is
* GEV's Cesium side for them, and must load the factories. Given another, the * GEV's Cesium side for them, and must load the factories. Given another, the
* entry's flight finds no camera (`findCamera`) and does nothing. Visual * entry's flight finds no camera (`findCamera`) and does nothing. None is
* settings are given their viewer by the application shell, which loads * left: visual settings, once given their viewer by the application shell,
* both factories; without it, their styles keep records and draw nothing. * now leave the factories to their caller as the shell does.
*/ */
const INJECTED = { const INJECTED = {};
'./ui/visual-settings': 'src/ui/applicationShell.js',
};
/** /**
* Modules whose use of the bridge holds up without the factory: with no * Modules whose use of the bridge holds up without the factory: with no
@@ -141,6 +139,10 @@ const DRAW_FROM_CALLER = new Set([
// eye and shade the globe through the ports alone. // eye and shade the globe through the ports alone.
'./application/layers', './application/layers',
'./standalone/catalog', './standalone/catalog',
// The application's tools (scene director, annotations, embed views):
// they draw, fly and take clicks through the ports; only Import's pins
// (`src/data/geoImportPins.js`, still on the Cesium list) drive Cesium.
'./application/tools',
]); ]);
/** /**
@@ -171,6 +173,19 @@ const CAMERA_FROM_CALLER = new Set([
// Its ground snap, mesh floor sampler, annotation resolver and location // Its ground snap, mesh floor sampler, annotation resolver and location
// framing ask the camera, globe and query ports; it loads no factory. // framing ask the camera, globe and query ports; it loads no factory.
'./application/operations', './application/operations',
// It shows its source's credit through `findCredits`, and switches stacks
// through the map engine that `./render/cesium/unbound` provides too.
'./maps/controller',
// The application shell and what assembles it: their controls fly, read
// the eye, shade the globe and set styles through the ports alone; the
// application's renderer is bound to its viewer, and a viewer of the
// renderer bound gets its ports from `./render/cesium/unbound`.
'./ui/shell',
'./ui/composition',
'./ui/hud',
'./ui/visual-settings',
'./application/controls',
'./application/data',
]); ]);
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
@@ -340,8 +355,8 @@ function checkLookupFactory(
); );
} }
test('every public entry that reaches a findEffects caller loads the unbound effects factory', () => { test('every public entry that reaches a findEffects caller loads the unbound effects factory, or its caller can', () => {
checkLookupFactory('findEffects', EFFECTS_FACTORY); checkLookupFactory('findEffects', EFFECTS_FACTORY, { fromCaller: true });
}); });
test('every public entry that reaches a findGlobe caller loads the unbound globe factory', () => { test('every public entry that reaches a findGlobe caller loads the unbound globe factory', () => {
+28
View File
@@ -0,0 +1,28 @@
/**
* @module sky/icrf
* @description The precise ICRF-to-fixed rotation, from the renderer that
* has the tables for it (the Cesium adapter's starry sky provides it as it
* loads, `src/render/cesium/starrySky.js`). Cesium-free: with none
* provided, or before its tables load, it answers null and callers fall
* back to `temeToPseudoFixed` (`src/geo/frames.js`).
*/
let provided = null;
/**
* Provide the precise rotation; a later call replaces it.
* @param {(ms: number) => ({x: object, y: object, z: object} | null)} axesAt
*/
export function provideIcrfToFixed(axesAt) {
provided = axesAt;
}
/**
* The precise ICRF-to-fixed rotation at `ms` (epoch milliseconds) as its
* axes (the matrix's columns), or null while it is unknown.
* @param {number} ms
* @returns {{x: object, y: object, z: object} | null}
*/
export function icrfToFixedAxes(ms) {
return provided ? provided(ms) : null;
}
+9 -12
View File
@@ -32,13 +32,9 @@ import {
} from './cyberSonarControls.js'; } from './cyberSonarControls.js';
import { toDegrees, toRadians } from '../geo/index.js'; import { toDegrees, toRadians } from '../geo/index.js';
import { cameraOf, findCamera } from '../render/cesium/camera.js'; // A viewer with no renderer bound gets its ports (camera, effects, globe)
// Loads the effects factory, so visual settings on a viewer with no renderer // once its owner has loaded the package's `./render/cesium/unbound` export.
// bound still get an effects port. Loading the camera and effects factories, import { cameraOf, canvasOf, findCamera } from '../render/rendererOf.js';
// and asking the viewer's entities whether Cockpit's aircraft still draws,
// keep this module on the Cesium allow-list.
import '../render/cesium/effects.js';
import '../render/cesium/globe.js';
import { aircraftTrackingTarget } from '../cockpitTracking.js'; import { aircraftTrackingTarget } from '../cockpitTracking.js';
@@ -63,7 +59,7 @@ import { applicationPinia, createUiRuntime } from './vueRuntime.js';
import { useContextStore } from './stores/context.js'; import { useContextStore } from './stores/context.js';
import { useMissionReplayStore } from './stores/missionReplay.js'; import { useMissionReplayStore } from './stores/missionReplay.js';
import { useCelestialRingStore } from './stores/celestialRing.js'; import { useCelestialRingStore } from './stores/celestialRing.js';
import { icrfToFixedAxes } from '../sky/starrySky.js'; import { icrfToFixedAxes } from '../sky/icrf.js';
import { useWorldOverlayActionsStore } from './stores/worldOverlayActions.js'; import { useWorldOverlayActionsStore } from './stores/worldOverlayActions.js';
import { useAwarenessDirectionStore } from './stores/awarenessDirection.js'; import { useAwarenessDirectionStore } from './stores/awarenessDirection.js';
import { useHudStore } from './stores/hud.js'; import { useHudStore } from './stores/hud.js';
@@ -380,10 +376,11 @@ export class StyleManager extends ShellFacade {
warmGroundFloor: services.warmGroundFloor, warmGroundFloor: services.warmGroundFloor,
sampleMeshFloorCells: services.sampleMeshFloorCells, sampleMeshFloorCells: services.sampleMeshFloorCells,
// Whether the aircraft Cockpit flies still draws: an entity of the // Whether the aircraft Cockpit flies still draws: an entity of the
// viewer's own, or a tracked contact whose layer draws it through // viewer's own (the scene's `viewerDrawsEntity` says), or a tracked
// the draw port and says so in its entity record. // contact whose layer draws it through the draw port and says so in
// its entity record.
trackedEntityDrawn: (entity) => trackedEntityDrawn: (entity) =>
viewer.entities.contains(entity) || services.viewerDrawsEntity?.(entity) === true ||
readEntityRecord(entity)?.drawn?.() === true, readEntityRecord(entity)?.drawn?.() === true,
holdContinuousRender: services.holdContinuousRender, holdContinuousRender: services.holdContinuousRender,
releaseContinuousRender: services.releaseContinuousRender, releaseContinuousRender: services.releaseContinuousRender,
@@ -1030,7 +1027,7 @@ export class StyleManager extends ShellFacade {
_radioVolumeValue: this._radioVolumeValue, _radioVolumeValue: this._radioVolumeValue,
}, },
radio: radioLayer, radio: radioLayer,
canvas: this.viewer?.canvas, canvas: canvasOf(this.viewer) ?? undefined,
actions: { actions: {
isRegistered: () => this._dataManager?.layers?.has('radio'), isRegistered: () => this._dataManager?.layers?.has('radio'),
isEnabled: () => this._dataManager?.isEnabled('radio'), isEnabled: () => this._dataManager?.isEnabled('radio'),
+1 -1
View File
@@ -4,7 +4,7 @@ import { VisualEffects } from './visualEffects.js';
import { createCesiumEffects } from '../render/cesium/effects.js'; import { createCesiumEffects } from '../render/cesium/effects.js';
import { styleStagesOf } from '../styles/styleStages.js'; import { styleStagesOf } from '../styles/styleStages.js';
import { createCesiumGlobe } from '../render/cesium/globe.js'; import { createCesiumGlobe } from '../render/cesium/globe.js';
import { MILKY_WAY_INTENSITY, StarrySky } from '../sky/starrySky.js'; import { MILKY_WAY_INTENSITY, StarrySky } from '../render/cesium/starrySky.js';
import { import {
GLOBAL_POST_DEFAULTS, GLOBAL_POST_DEFAULTS,
STYLE_PRESET_DEFAULTS, STYLE_PRESET_DEFAULTS,