diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 87f522781..217adb847 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1406,7 +1406,10 @@ "src/data/adminBoundaries.js", "src/data/retryableLoad.js", "src/maps/imageryHost.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js" ], "external": ["cesium", "vue", "pinia", "vue-i18n"] }, @@ -2086,7 +2089,10 @@ "src/i18n/locales/zh-CN.json", "src/i18n/locales/zh-Hant.json", "src/ui/unitLabels.js", - "src/layers/recentImagery/display.js" + "src/layers/recentImagery/display.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js" ], "external": ["cesium"] }, @@ -5310,7 +5316,10 @@ "src/layers/satellites/sensors.js", "src/data/ucsSatellites.js", "src/data/imagingSensors.js", - "src/render/cesium/viewers.js" + "src/render/cesium/viewers.js", + "src/render/applicationHooks.js", + "src/maps/globeEngine.js", + "src/maps/engine.js" ], "external": [ "hls.js", diff --git a/src/app/scene.js b/src/app/scene.js index 1a6ce6627..90438f645 100644 --- a/src/app/scene.js +++ b/src/app/scene.js @@ -17,19 +17,28 @@ import { t } from '../i18n/index.js'; import { applicationHooksOf } from '../render/applicationHooks.js'; import { createSceneHost } from '../render/rendererOf.js'; +let defaultLoad = null; + /** * The application's composition root picks the renderer: the one given, else * the default (Cesium), loaded only then, so a page on the stub never - * loads it. This is the only part of an adapter the application imports. + * loads it. This is the only part of an adapter the application imports. A + * page that starts on the default calls this as it starts, so the renderer + * loads beside the rest of the page rather than after it. + * @returns {Promise} The default `RendererPlugin`. */ -async function defaultRenderer() { - const { cesiumRenderer } = await import('../render/cesium/application.js'); - return cesiumRenderer; +export function loadDefaultRenderer() { + defaultLoad ??= (async () => { + const { cesiumRenderer } = await import('../render/cesium/application.js'); + return cesiumRenderer; + })(); + return defaultLoad; } /** * Construct the application globe using the caller's local configuration. - * `renderer` is the `RendererPlugin` that draws it (default: Cesium). The + * `renderer` is the `RendererPlugin` that draws it, or a promise of one + * (default: Cesium, `loadDefaultRenderer`). The * application runs on a renderer with only the contract's required members: * what a renderer's plugin hands it beside the contract * (`src/render/applicationHooks.js`) it uses where given, and does without @@ -63,7 +72,7 @@ export async function createApplicationScene({ }); } loaderStatus.textContent = t('Configuring viewer...'); - const rendererPlugin = givenPlugin ?? (await defaultRenderer()); + const rendererPlugin = (await givenPlugin) ?? (await loadDefaultRenderer()); signal.throwIfAborted(); const container = document.getElementById('cesiumContainer'); const renderer = await rendererPlugin.create({ @@ -96,6 +105,12 @@ export async function createApplicationScene({ } } }); + // The renderer follows its container's size (`Renderer.resize`). + if (typeof ResizeObserver === 'function' && container) { + const resizes = new ResizeObserver(() => renderer.resize()); + resizes.observe(container); + defer(() => resizes.disconnect()); + } // Before any layer binds a click: every layer and tool shares this one. // Deferred after the renderer, so it is released before the renderer goes. const input = inputFor(viewer); diff --git a/src/data/followed.js b/src/data/followed.js index 2f33ed3fd..7f2df9cf1 100644 --- a/src/data/followed.js +++ b/src/data/followed.js @@ -12,7 +12,7 @@ * north-up) read the target's `displayPosition`: a port target without one * is followed by the camera but not shown by them. */ -import { findCamera } from '../render/rendererOf.js'; +import { findCamera, findFrame } from '../render/rendererOf.js'; import { readEntityRecord } from './entityRecords.js'; /** @@ -156,12 +156,17 @@ export function resumeFollowing(viewer, followed) { } /** - * Where `followed` is shown this frame: the layer's display cache; null - * when it has none, or it answers nothing. + * Where `followed` is shown this frame: the layer's display cache, else the + * target's own position at the frame port's scene time; null when neither + * answers. * @param {object} viewer * @param {Followed|null} followed */ export function followedPosition(viewer, followed) { const display = followed?.displayPosition; - return (typeof display === 'function' ? display() : null) || null; + const shown = typeof display === 'function' ? display() : null; + if (shown) return shown; + if (typeof followed?.position !== 'function') return null; + const time = findFrame(viewer)?.time?.(); + return followed.position(Number.isFinite(time) ? time : Date.now()) || null; } diff --git a/src/data/followed.test.mjs b/src/data/followed.test.mjs index ccc0eda13..71e848063 100644 --- a/src/data/followed.test.mjs +++ b/src/data/followed.test.mjs @@ -13,6 +13,7 @@ import { } from './followed.js'; import { bindRenderer } from '../render/rendererOf.js'; import { createCameraEvents } from '../render/camera/events.js'; +import { createStubRenderer } from '../render/stub/index.js'; /** A camera port that follows, for a viewer bound to a renderer. */ function followingPort() { @@ -108,3 +109,21 @@ test('followedPosition reads the display cache', () => { assert.deepEqual(followedPosition({}, view), { x: 7, y: 8, z: 9 }); assert.equal(followedPosition({}, null), null); }); + +test('followedPosition falls back to the target position at scene time', () => { + const renderer = createStubRenderer(); + const viewer = {}; + bindRenderer(viewer, renderer); + renderer.frame.setTime(1234); + const seen = []; + const target = { + key: 't', + frame: 'enu', + viewFrom: { x: 0, y: 0, z: 1 }, + position: (time) => (seen.push(time), { x: 1, y: 2, z: 3 }), + }; + assert.deepEqual(followedPosition(viewer, target), { x: 1, y: 2, z: 3 }); + assert.deepEqual(seen, [1234]); + target.displayPosition = () => ({ x: 4, y: 5, z: 6 }); + assert.deepEqual(followedPosition(viewer, target), { x: 4, y: 5, z: 6 }); +}); diff --git a/src/maps/globeEngine.js b/src/maps/globeEngine.js index 139fc1ea7..56492c7da 100644 --- a/src/maps/globeEngine.js +++ b/src/maps/globeEngine.js @@ -32,15 +32,28 @@ const shownGlobes = new WeakMap(); const credit = (text) => ({ text }); -/** Turn a photoreal handle's base on or off, reporting a failure. */ +/** + * Turn a photoreal handle's base on or off. Turning it on can fail (the + * port answers route `none`, or rejects): the handle is then off again, so + * a later switch tries again, and the globe is shown so the base is not + * left blank. Only the latest switch of a handle settles it. + */ function applyPhotoreal(handle, shown) { if (handle.shown === shown || released.has(handle)) return; handle.shown = shown; - handle.globe - .setPhotoreal(shown ? handle.spec : null) - .catch((error) => - console.warn('[MapStack] photoreal switch failed', error), - ); + const switchId = (handle.switches = (handle.switches ?? 0) + 1); + const failed = (error) => { + if (handle.switches !== switchId || released.has(handle)) return; + console.warn('[MapStack] photoreal switch failed', error); + if (!shown) return; + handle.shown = false; + handle.globe.setGlobeVisible(true); + shownGlobes.set(handle.globe, true); + }; + handle.globe.setPhotoreal(shown ? handle.spec : null).then((status) => { + if (shown && status?.route === 'none') + failed(status.error?.message ?? 'photoreal unavailable'); + }, failed); } /** diff --git a/src/maps/globeEngine.test.mjs b/src/maps/globeEngine.test.mjs index 2562f6a0e..85d81850c 100644 --- a/src/maps/globeEngine.test.mjs +++ b/src/maps/globeEngine.test.mjs @@ -121,3 +121,34 @@ test('a renderer without photoreal reports none, with the reason it gave', async assert.equal(result.tileset, null); assert.equal(result.route, 'none'); }); + +test('photoreal that fails to come back leaves the globe shown, and is tried again', async () => { + const { host, renderer } = scene(['photoreal']); + const loaded = await engine.loadPhotoreal(host, { googleApiKey: 'key' }); + const handle = loaded.tileset; + engine.showTileset(handle, false); + engine.setGlobeShown(host, false); + // The port cannot draw photoreal any more. + renderer.globe.setPhotoreal = async (spec) => ({ + route: 'none', + error: { code: 'refused', message: 'refused' }, + spec, + }); + const warn = console.warn; + console.warn = () => {}; + try { + engine.showTileset(handle, true); + await new Promise((resolve) => setTimeout(resolve, 0)); + } finally { + console.warn = warn; + } + assert.equal(engine.tilesetShown(handle), false, 'off again'); + assert.equal(engine.globeShown(host), true, 'the base is not blank'); + let tried = 0; + renderer.globe.setPhotoreal = async () => { + tried += 1; + return { route: 'google' }; + }; + engine.showTileset(handle, true); + assert.equal(tried, 1, 'a later switch tries again'); +}); diff --git a/src/maps/imageryHost.js b/src/maps/imageryHost.js index e2b2a60ac..954324a52 100644 --- a/src/maps/imageryHost.js +++ b/src/maps/imageryHost.js @@ -7,6 +7,7 @@ import { msg } from '../i18n/marker.js'; import { findGlobe } from '../render/rendererOf.js'; +import { mapEngineFor } from './engine.js'; /** Guidance shown when the active map stack cannot host draped imagery. */ export const NO_IMAGERY_HOST = msg( @@ -20,8 +21,8 @@ const NONE = Object.freeze({ collection: null, kind: 'none' }); * imagery while the globe is shown, else the shown base tileset (the map * stack's `getImageryHostTileset()`), else none. `collection` names the host * (one value per host, so a change of host is a change of it). A renderer - * that does not say whether its globe is shown (no `globeVisibility`) has it - * shown whenever no base tileset is. + * that does not say whether its globe is shown (no `globeVisibility`) is + * answered by the scene's map engine, which shows and hides it. * @param {{ viewer?: object, tileset?: object }} scene * @returns {{ collection: object | null, kind: 'globe' | 'tileset' | 'none' }} */ @@ -29,7 +30,9 @@ export function resolveImageryHost({ viewer, tileset } = {}) { const globe = findGlobe(viewer); const shownTileset = tileset && tileset.isDestroyed?.() !== true ? tileset : null; - const globeShown = globe?.isGlobeVisible?.() ?? (globe && !shownTileset); + const globeShown = + globe && + (globe.isGlobeVisible?.() ?? mapEngineFor(viewer).globeShown(viewer)); if (globe && globeShown) return { collection: globe.imagery, kind: 'globe' }; if (shownTileset) return { collection: shownTileset, kind: 'tileset' }; return NONE; diff --git a/src/maps/imageryHost.test.mjs b/src/maps/imageryHost.test.mjs index 731d85eb4..33eadbf41 100644 --- a/src/maps/imageryHost.test.mjs +++ b/src/maps/imageryHost.test.mjs @@ -3,6 +3,7 @@ import assert from 'node:assert/strict'; import { NO_IMAGERY_HOST, resolveImageryHost } from './imageryHost.js'; import { bindRenderer } from '../render/rendererOf.js'; import { createStubRenderer } from '../render/stub/index.js'; +import { globeMapEngine } from './globeEngine.js'; /** A scene object bound to a stub renderer, its globe shown or hidden. */ function scene({ globeShown, capabilities } = {}) { @@ -28,15 +29,18 @@ test('a hidden globe hands imagery to the shown base tileset', () => { assert.deepEqual(host, { collection: tileset, kind: 'tileset' }); }); -test('without globe visibility, the globe hosts unless a tileset is shown', () => { +test('without globe visibility, the map engine says whether the globe is shown', () => { const { viewer, renderer } = scene({ capabilities: [] }); assert.equal(renderer.globe.isGlobeVisible, undefined); const tileset = { id: 'tiles' }; + globeMapEngine.setGlobeShown(viewer, false); assert.deepEqual(resolveImageryHost({ viewer, tileset }), { collection: tileset, kind: 'tileset', }); - assert.deepEqual(resolveImageryHost({ viewer, tileset: null }), { + // A globe stack shows the globe: a tileset kept from startup is not the host. + globeMapEngine.setGlobeShown(viewer, true); + assert.deepEqual(resolveImageryHost({ viewer, tileset }), { collection: renderer.globe.imagery, kind: 'globe', }); diff --git a/src/render/noCesiumOutsideRender.test.mjs b/src/render/noCesiumOutsideRender.test.mjs index 10077db4b..0ba45e222 100644 --- a/src/render/noCesiumOutsideRender.test.mjs +++ b/src/render/noCesiumOutsideRender.test.mjs @@ -62,8 +62,8 @@ const isAdapter = (file) => file.startsWith('src/render/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. + * renderer as the default, loading the adapter's application module only + * when it is given no renderer (`DYNAMIC_ENTRIES`). * - The conformance page runs the suite on the Cesium adapter's harness * and draws the reference scenes on its scene renderer. */ @@ -75,6 +75,12 @@ const ADAPTER_ENTRIES = { ], }; +/** + * The entries that load their adapter modules on demand: `import()`, its + * result awaited and destructured by name, never kept whole or forwarded. + */ +const DYNAMIC_ENTRIES = new Set(['src/app/scene.js']); + const git = (...args) => execFileSync('git', args, { cwd: root, encoding: 'utf8' }); const tracked = git( @@ -329,11 +335,26 @@ test('the files that name the adapter by design take named exports, never Cesium 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)) { + // dynamic import (but in DYNAMIC_ENTRIES, one destructured by name), and + // no forwarding of the module. + const parents = new Map(nodesOf(parsed.program)); + for (const [node, parent] of parents) { const source = node.source?.value; if (typeof source !== 'string') continue; if (!modules.includes(targetOf(file, source))) continue; + if (node.type === 'ImportExpression' && DYNAMIC_ENTRIES.has(file)) { + const declarator = parents.get(parent); + assert.ok( + parent?.type === 'AwaitExpression' && + declarator?.type === 'VariableDeclarator' && + declarator.id.type === 'ObjectPattern' && + declarator.id.properties.every( + (p) => p.type === 'ObjectProperty' && !p.computed, + ), + `${file} must destructure import(${source}) by name`, + ); + continue; + } assert.equal( node.type, 'ImportDeclaration', diff --git a/src/standalone/application.js b/src/standalone/application.js index f24199763..39e762925 100644 --- a/src/standalone/application.js +++ b/src/standalone/application.js @@ -2,7 +2,7 @@ import { createStandaloneCatalog } from './catalog.js'; import { createStandalonePlaceSearch } from './placeSearch.js'; import { CITY_POIS } from '../cityPois.js'; import { createApplication } from '../app/application.js'; -import { createStandaloneScene } from './scene.js'; +import { createStandaloneScene, loadDefaultRenderer } from './scene.js'; import { createStandaloneControls } from './controls.js'; import { createStandaloneData } from './data.js'; import { createStandaloneTools } from './tools.js'; @@ -36,6 +36,8 @@ export function createStandaloneApplication({ if (constructed) throw new Error('The standalone application already owns this page'); constructed = true; + // The default renderer starts loading now, beside the page's own setup. + const rendererPlugin = renderer ?? loadDefaultRenderer(); // Locale is resolved before any UI initialization so / // and every catalog lookup agree from the first painted frame. Module // scripts execute after parsing, so the DOM is ready here: the views @@ -72,7 +74,7 @@ export function createStandaloneApplication({ const scene = await createStandaloneScene({ ...context, // The renderer plugin; the default (Cesium) when none is given. - renderer, + renderer: rendererPlugin, googleApiKey, // Without a key, Google 3D can still load with tokens from the // app's server when it offers them. diff --git a/src/standalone/scene.js b/src/standalone/scene.js index b4970655a..2d46ccbce 100644 --- a/src/standalone/scene.js +++ b/src/standalone/scene.js @@ -1,5 +1,8 @@ -import { createApplicationScene } from '../app/scene.js'; +import { createApplicationScene, loadDefaultRenderer } from '../app/scene.js'; import { createApplicationRequestServices } from '../services/requests.js'; +/** The default renderer plugin, loading from the first call (`app/scene.js`). */ +export { loadDefaultRenderer }; + /** Supply standalone request services when directly constructing a scene. */ export function createStandaloneScene(options) { return createApplicationScene({ diff --git a/src/testSupport/fakeCameraPort.mjs b/src/testSupport/fakeCameraPort.mjs index 6e7852e43..13d404557 100644 --- a/src/testSupport/fakeCameraPort.mjs +++ b/src/testSupport/fakeCameraPort.mjs @@ -7,6 +7,8 @@ import { toDegrees } from '../geo/index.js'; import { bindRenderer, rendererOf } from '../render/rendererOf.js'; import { createCesiumCamera } from '../render/cesium/camera.js'; import { fakeCesiumCredits } from './fakeCreditsPort.mjs'; +import { entityFollowTarget, followedOf } from '../data/followed.js'; +import * as Cesium from 'cesium'; const DEFAULT_POSE = Object.freeze({ lon: 0, @@ -65,6 +67,62 @@ export function fakeCameraPort({ pose = {}, viewRectangle = null } = {}) { }; } +/** + * Cesium's entity tracking for a fake viewer without entities of its own: + * the follow's helper entity is tracked here, at the fake clock's time. + * @param {object} viewer + */ +function trackingWidget(viewer) { + const entities = new Cesium.EntityCollection(); + const trackedEntityChanged = new Cesium.Event(); + let tracked; + return { + entities, + clock: { + get currentTime() { + return viewer.clock?.currentTime ?? Cesium.JulianDate.now(); + }, + }, + get trackedEntity() { + return tracked; + }, + set trackedEntity(entity) { + if (entity === tracked) return; + tracked = entity; + trackedEntityChanged.raiseEvent(entity); + }, + trackedEntityChanged, + isDestroyed: () => false, + }; +} + +/** + * Follow `entity` through `viewer`'s camera port as a layer does + * (`entityFollowTarget`), at its own position; null stops following. + * Returns the target followed. + * @param {object} viewer + * @param {object|null} entity + */ +export function followEntity(viewer, entity) { + const camera = rendererOf(viewer).camera; + if (!entity) { + camera.follow(null); + return null; + } + const target = entityFollowTarget(entity, { + position: () => entity.position?.getValue?.() ?? null, + frame: 'enu', + viewFrom: { x: 0, y: -1000, z: 500 }, + }); + camera.follow(target); + return target; +} + +/** The entity `viewer`'s camera follows (`followEntity`), if any. */ +export function followedEntity(viewer) { + return followedOf(viewer)?.entity; +} + /** * Bind to a fake viewer the Cesium renderer's own camera port over its * Cesium-shaped fake camera, for tests whose code is half on the port: the @@ -140,12 +198,18 @@ export function bindFakeCesiumCamera(viewer, ports = {}) { }, requestRender: () => viewer.scene?.requestRender?.(), }; - // A fake with Cesium's entity tracking follows as the renderer does. + // A fake with Cesium's entity tracking follows as the renderer does: on + // its own entities, or, where it only answers `contains`, on a tracking + // widget of its own over the fake's clock. const tracks = Boolean(viewer.trackedEntityChanged && viewer.entities); + const widget = + tracks && typeof viewer.entities.add !== 'function' + ? trackingWidget(viewer) + : viewer; const real = createCesiumCamera({ scene, camera, - ...(tracks ? { widget: viewer } : {}), + ...(tracks ? { widget } : {}), report: (error) => { throw error; }, diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs index 7570f9b6e..95067f8d0 100644 --- a/src/testSupport/fakeCesiumScene.mjs +++ b/src/testSupport/fakeCesiumScene.mjs @@ -180,6 +180,13 @@ export function fakeSceneFrame(viewer) { return { on: (phase, cb) => listen(viewer.scene?.[phase], cb), requestRender: () => viewer.scene?.requestRender?.(), + /** Scene time: the fake clock's, else now. */ + time() { + const time = viewer.clock?.currentTime; + return time instanceof Cesium.JulianDate + ? Cesium.JulianDate.toDate(time).getTime() + : Date.now(); + }, }; } diff --git a/src/ui/cockpitBridge.test.mjs b/src/ui/cockpitBridge.test.mjs index 5a5bc12d1..390cbfeab 100644 --- a/src/ui/cockpitBridge.test.mjs +++ b/src/ui/cockpitBridge.test.mjs @@ -11,7 +11,11 @@ import { useCockpitStore } from './stores/cockpit.js'; import CockpitView from './views/CockpitView.vue'; import ContextView from './views/ContextView.vue'; import * as Cesium from 'cesium'; -import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { + bindFakeCesiumCamera, + followEntity, + followedEntity, +} from '../testSupport/fakeCameraPort.mjs'; import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js'; import { VesselRecords } from '../layers/vessels/records.js'; @@ -109,7 +113,10 @@ function sceneQuery(viewer, ports) { return Number.isFinite(height) ? height : null; }, sampleHeight(points, { mostDetailed = false } = {}) { - if (!mostDetailed || typeof scene().sampleHeightMostDetailed !== 'function') + if ( + !mostDetailed || + typeof scene().sampleHeightMostDetailed !== 'function' + ) return Promise.resolve(points.map(() => null)); // Answered as soon as the scene's read lands, as the adapter does. return scene() @@ -156,7 +163,6 @@ function fixture( // Each placed camera: where it is and where it looks. const shots = []; const viewer = { - trackedEntity: undefined, clock: { currentTime: null }, camera: { cancelFlight() {}, @@ -415,10 +421,10 @@ test('tracking an aircraft from the bridge ends it without refocusing the vessel const { cockpit, viewer, vessels, aircraft } = fixture(t); cockpit.enter(); await settle(); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); cockpit.update(); assert.equal(cockpit.active, false); - assert.equal(viewer.trackedEntity, aircraft, 'the aircraft keeps tracking'); + assert.equal(followedEntity(viewer), aircraft, 'the aircraft keeps tracking'); assert.equal(aircraft.show, true, 'the aircraft was never adopted'); assert.deepEqual(vessels.calls, [ ['subject', RECORD.mmsi], @@ -432,7 +438,7 @@ test('following a satellite or a site from the bridge ends it too', async (t) => await settle(); // A satellite's or an installation's follow carrier has no position of // its own (the camera reads the follow target's). - viewer.trackedEntity = { id: 'satellites:25544', noradId: 25544 }; + followEntity(viewer, { id: 'satellites:25544', noradId: 25544 }); cockpit.update(); assert.equal(cockpit.active, false); assert.deepEqual(vessels.calls.at(-1), ['subject', null]); @@ -473,7 +479,7 @@ test("turning off the ridden aircraft's layer ends the cockpit", async (t) => { const { cockpit, viewer, aircraft, disableFlights } = fixture(t, { aircraftInfo, }); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); assert.equal(cockpit.enter({ kind: 'aircraft' }), true); await settle(); cockpit.update(); @@ -876,7 +882,7 @@ test('arrows do nothing new in an aircraft cockpit', async (t) => { const { cockpit, viewer, aircraft, shots, store } = fixture(t, { aircraftInfo, }); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); assert.equal(cockpit.enter({ kind: 'aircraft' }), true); await settle(); assert.equal(cockpit.subjectKind, 'aircraft'); @@ -926,7 +932,7 @@ test('C neither enters nor leaves an aircraft cockpit', async (t) => { onGround: false, }; const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo }); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); const outside = press(cockpit, 'c'); await settle(); assert.equal(cockpit.active, false, 'C does not enter'); @@ -1562,7 +1568,7 @@ test('a followed aircraft keeps its own double-click hit area', async (t) => { onGround: false, }; const { cockpit, viewer, aircraft } = fixture(t, { aircraftInfo }); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); heightSensitiveProjection(viewer); // Drawn at (400, -2700) as the press begins, at (600, -2700) by the // double-click: a click there is not on the aircraft. @@ -1588,7 +1594,7 @@ test("a ship's double-click memory does not carry over to an aircraft followed s // The press finds the ship at (400, 300). cockpit.onScenePointerDown(1000); // Within the memory, an aircraft is followed, drawn elsewhere. - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); heightSensitiveProjection(viewer, { x: 900 }); assert.equal(cockpit.onSceneDoubleClick({ x: 400, y: 300 }, 1250), false); assert.equal(cockpit.active, false); diff --git a/src/ui/cockpitController.test.mjs b/src/ui/cockpitController.test.mjs index 70adace2a..077ed48bb 100644 --- a/src/ui/cockpitController.test.mjs +++ b/src/ui/cockpitController.test.mjs @@ -4,6 +4,7 @@ import { CockpitViewController } from './cockpitController.js'; import { withEntityRecord } from '../data/entityRecords.js'; import { fakeInput } from '../input/testDoubles.mjs'; import { bindRenderer } from '../render/rendererOf.js'; +import { entityFollowTarget, followedOf } from '../data/followed.js'; import { cockpitAnchorCorrectionStep, cockpitGroundSafeHeight, @@ -37,18 +38,30 @@ function environment() { preUpdate: event, screenSpaceCameraController: { enableInputs: true }, }, - trackedEntityChanged: event, - entities: { contains: () => false }, + }; + // What the camera follows, as a layer's follow sets it. + const camera = { + followed: null, + follow(target) { + camera.followed = target; + }, + on: (name, fn) => + name === 'followChanged' ? event.addEventListener(fn) : () => {}, }; // The renderer's frame port: Cockpit moves the camera on its preUpdate. bindRenderer(viewer, { + camera, frame: { on: (phase, fn) => phase === 'preUpdate' ? event.addEventListener(fn) : () => {}, }, }); + /** Follow a holder of an entity record, as a layer's follow does. */ + const follow = (holder) => + camera.follow(holder ? entityFollowTarget(holder, {}) : null); return { viewer, + follow, callbacks, restore() { Object.assign(globalThis, original); @@ -96,7 +109,7 @@ test('disposing an active Cockpit releases the supplied render owner without ret env.viewer.scene.screenSpaceCameraController.enableInputs, true, ); - assert.equal(env.viewer.trackedEntity, undefined); + assert.equal(followedOf(env.viewer), null); assert.equal(owner.active, false); } finally { env.restore(); @@ -122,15 +135,9 @@ test('aircraft identity is read from the supplied layer instances', () => { militaryFlightsLayer: { getTrackedInfo: () => military }, }, }); - env.viewer.trackedEntity = withEntityRecord( - {}, - { trackedId: 'military:def456' }, - ); + env.follow(withEntityRecord({}, { trackedId: 'military:def456' })); assert.deepEqual(owner.readAircraftInfo(), military); - env.viewer.trackedEntity = withEntityRecord( - {}, - { trackedId: 'flights:abc123' }, - ); + env.follow(withEntityRecord({}, { trackedId: 'flights:abc123' })); assert.deepEqual(owner.readAircraftInfo(), civilian); owner.dispose(); } finally { diff --git a/src/ui/cockpitDoubleClick.test.mjs b/src/ui/cockpitDoubleClick.test.mjs index 1c1cf2461..d65af9c40 100644 --- a/src/ui/cockpitDoubleClick.test.mjs +++ b/src/ui/cockpitDoubleClick.test.mjs @@ -11,6 +11,7 @@ import { FAKE_EVENT_TYPES, } from '../input/testDoubles.mjs'; import { bindRenderer } from '../render/rendererOf.js'; +import { entityFollowTarget } from '../data/followed.js'; import { createCesiumInput } from '../render/cesium/input.js'; import { routeSceneDoubleClick, onSceneDoubleClick } from './cockpitInput.js'; import { inputFor } from '../input/dispatcher.js'; @@ -27,13 +28,21 @@ function harness(t, { stock = null } = {}) { const project = () => ({ x: 100, y: 100 }); // With `stock`, the renderer's own input port takes the viewer's stock // double-click follow and runs it as the app's does; else the fake input. - const input = stock ? cesiumInput(viewer, stock, project) : fakeInput(viewer); - if (!stock) bindRenderer(viewer, { query: { project } }); + // The camera port follows the aircraft, as the flights layer's follow does. + const camera = { followed: null, on: () => () => {} }; + const input = stock + ? cesiumInput(viewer, stock, project, camera) + : fakeInput(viewer); + if (!stock) bindRenderer(viewer, { query: { project }, camera }); const entity = { id: 'flights:abc', position: { getValue: () => ({ x: 1, y: 2, z: 3 }) }, }; - viewer.trackedEntity = entity; + camera.followed = entityFollowTarget(entity, { + position: () => entity.position.getValue(), + frame: 'enu', + viewFrom: { x: 0, y: -1000, z: 500 }, + }); const controller = { viewer, active: false, @@ -69,7 +78,7 @@ function harness(t, { stock = null } = {}) { /** The Cesium renderer's input port over a fake handler, with `follow` as * the viewer's stock double-click follow. */ -function cesiumInput(viewer, follow, project) { +function cesiumInput(viewer, follow, project, camera) { const stock = new FakeScreenSpaceEventHandler(); stock.setInputAction(follow, FAKE_EVENT_TYPES.LEFT_DOUBLE_CLICK); viewer.screenSpaceEventHandler = stock; @@ -87,7 +96,7 @@ function cesiumInput(viewer, follow, project) { }, document: null, }); - bindRenderer(viewer, { input: made.port, query }); + bindRenderer(viewer, { input: made.port, query, camera }); const T = FAKE_EVENT_TYPES; const fire = (type) => (position) => handler.fire(type, { position }); return { diff --git a/src/ui/cockpitEntryGate.test.mjs b/src/ui/cockpitEntryGate.test.mjs index 851a581fa..9d7deec6e 100644 --- a/src/ui/cockpitEntryGate.test.mjs +++ b/src/ui/cockpitEntryGate.test.mjs @@ -10,7 +10,10 @@ import { createPinia } from 'pinia'; import { createApp, defineComponent, h, nextTick } from 'vue'; import { DataLayerManager } from '../data/manager.js'; import { withEntityRecord } from '../data/entityRecords.js'; -import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { + bindFakeCesiumCamera, + followEntity, +} from '../testSupport/fakeCameraPort.mjs'; import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import { createDependencies } from '../layers/awareness/dependencies.js'; import { CockpitCoordinator } from './cockpitCoordinator.js'; @@ -90,7 +93,6 @@ function fixture( entities.add(entity); const listeners = () => ({ addEventListener: () => () => {} }); const viewer = { - trackedEntity: tracked ? entity : undefined, clock: { currentTime: null }, camera: { cancelFlight() {}, frustum: { fov: 1, aspectRatio: 1 } }, entities: { contains: (candidate) => entities.has(candidate) }, @@ -102,6 +104,7 @@ function fixture( }; // The Cockpit reads frames, the camera and what it follows through ports. bindFakeCesiumCamera(viewer, fakeScenePorts(viewer)); + if (tracked) followEntity(viewer, entity); const context = { mode: contextMode, changing }; const coordinator = new CockpitCoordinator({ viewer, @@ -175,8 +178,9 @@ function fixture( /** Track another aircraft, as Contacts navigation does mid-session. */ const retrack = (subject) => { tracked = subject; - viewer.trackedEntity = entityFor(subject); - entities.add(viewer.trackedEntity); + const next = entityFor(subject); + entities.add(next); + followEntity(viewer, next); }; const $ = (selector) => document.querySelector(selector); return { $, coordinator, cockpit, store, layers, disable, retrack, pinia }; diff --git a/src/ui/cockpitOrbitalFocus.test.mjs b/src/ui/cockpitOrbitalFocus.test.mjs index c646883c0..54186386d 100644 --- a/src/ui/cockpitOrbitalFocus.test.mjs +++ b/src/ui/cockpitOrbitalFocus.test.mjs @@ -12,7 +12,11 @@ import assert from 'node:assert/strict'; import { createPinia } from 'pinia'; import { createApp, defineComponent, h, nextTick } from 'vue'; import * as Cesium from 'cesium'; -import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { + bindFakeCesiumCamera, + followEntity, + followedEntity, +} from '../testSupport/fakeCameraPort.mjs'; import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import { FAKE_EVENT_TYPES, @@ -210,7 +214,7 @@ function satellitesLayer(viewer) { if (!positions.has(id)) return false; layer.calls.push(['track', id]); layer.tracked = id; - viewer.trackedEntity = { position: { getValue: () => layer.position(id) } }; + followEntity(viewer, { position: { getValue: () => layer.position(id) } }); return true; }, setCockpitSubject(noradId) { @@ -243,7 +247,6 @@ function fixture(t, { reducedMotion = false } = {}) { const shots = []; const picks = new Map(); const viewer = { - trackedEntity: undefined, clock: { currentTime: null }, camera: { frustum: { fov: 1, aspectRatio: ASPECT }, @@ -273,9 +276,7 @@ function fixture(t, { reducedMotion = false } = {}) { handler.stockDouble = ({ position }) => { handler.stockDoubleClicks += 1; const picked = picks.get(`${position.x},${position.y}`); - viewer.trackedEntity = picked - ? { position: { getValue: () => null } } - : undefined; + followEntity(viewer, picked ? { position: { getValue: () => null } } : null); }; // The viewer's stock handler holds them, so the scene's input has them to // hold off. @@ -639,7 +640,7 @@ test('a double-click on a site focuses it and keeps the orbital view', async (t) const { cockpit, viewer, handler } = scene; scene.doubleClick(SITES.alpha.at); assert.equal(handler.stockDoubleClicks, 0, 'Cesium does not track the site'); - assert.equal(viewer.trackedEntity, undefined); + assert.equal(followedEntity(viewer), undefined); scene.frame(); assert.equal(cockpit.active, true, 'still in orbit'); assert.equal(cockpit.orbital.focus.key, SITES.alpha.id); @@ -725,7 +726,7 @@ test('a satellite row rides it, staying in orbit; RETURN goes back', async (t) = assert.equal(newTrack.length, 1); assert.ok(newTrack[0].timestamp > firstTrack.timestamp, 'the new ride’s own time'); assert.deepEqual(satellites.calls.slice(-2), [['track', 49260], ['subject', 49260]]); - assert.equal(viewer.trackedEntity, undefined, 'the Cockpit keeps the camera'); + assert.equal(followedEntity(viewer), undefined, 'the Cockpit keeps the camera'); assert.equal(cockpit.subjectId, 49260); assert.equal(cockpit.orbital.focus, null, 'the focus is reset'); assert.equal(modeEvents.at(-1)?.active, true); diff --git a/src/ui/cockpitOrbitalView.test.mjs b/src/ui/cockpitOrbitalView.test.mjs index cc595b579..6c54de64e 100644 --- a/src/ui/cockpitOrbitalView.test.mjs +++ b/src/ui/cockpitOrbitalView.test.mjs @@ -24,7 +24,11 @@ import { } from '../cockpitOrbital.js'; import { vesselCockpitInfo } from '../layers/vessels/cockpitSubject.js'; import { claimPointer, releasePointer } from '../data/inputOwnership.js'; -import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { + bindFakeCesiumCamera, + followEntity, + followedEntity, +} from '../testSupport/fakeCameraPort.mjs'; import { fakeScenePorts } from '../testSupport/fakeCesiumScene.mjs'; import { fakeInput } from '../input/testDoubles.mjs'; @@ -97,7 +101,7 @@ function stockEventHandler(viewer) { }; actions.set(DOUBLE_CLICK, () => { handler.stockCalls += 1; - viewer.trackedEntity = undefined; + followEntity(viewer, null); }); return handler; } @@ -141,7 +145,6 @@ function fixture( gevTrackedId: aircraftInfo ? `flights:${aircraftInfo.icao24}` : '', }; const viewer = { - trackedEntity: undefined, clock: { currentTime: null }, camera: { // Cesium's frustum: `fov` the wider angle, `fovy` the vertical one. @@ -409,7 +412,7 @@ test('entering takes the camera and shows only the orbital HUD', async (t) => { assert.equal(cockpit.subjectKind, 'satellite'); assert.equal(cockpit.subjectId, ISS.noradId); assert.deepEqual(satellites.calls, [['subject', ISS.noradId]]); - assert.equal(viewer.trackedEntity, undefined); + assert.equal(followedEntity(viewer), undefined); assert.equal(viewer.scene.screenSpaceCameraController.enableInputs, false); assert.ok(document.body.classList.contains('cockpit-mode')); assert.ok(document.body.classList.contains('cockpit-orbit')); @@ -759,11 +762,11 @@ test('losing the satellite ends the view without refocusing it', async (t) => { test('tracking an aircraft from orbit ends the view and keeps that tracking', async (t) => { const { cockpit, viewer, satellites, aircraft, clock } = await orbitAt(t); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); clock.advance(16); cockpit.update(); assert.equal(cockpit.active, false); - assert.equal(viewer.trackedEntity, aircraft); + assert.equal(followedEntity(viewer), aircraft); assert.ok(!satellites.calls.some(([call]) => call === 'refocus')); }); @@ -785,7 +788,7 @@ test('+ and − mean nothing new in an aircraft cockpit or on a bridge', async ( onGround: false, }; const air = fixture(t, { satellite: null, aircraftInfo }); - air.viewer.trackedEntity = air.aircraft; + followEntity(air.viewer, air.aircraft); assert.equal(air.cockpit.enter({ kind: 'aircraft' }), true); for (const key of ['+', '=', '-', '_']) assert.equal(press(air.cockpit, key).defaultPrevented, false, key); @@ -934,7 +937,7 @@ test('a double-click on the followed aircraft model enters instead of untracking }; const scene = fixture(t, { aircraftInfo }); const { viewer, aircraft, store } = scene; - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); // The model is a primitive, not an Entity: Cesium's own double-click // would untrack it. doubleClickNearSatellite(scene, 0); @@ -1058,7 +1061,7 @@ test('a tracked aircraft takes entry before a tracked satellite', async (t) => { onGround: false, }; const { cockpit, viewer, aircraft, store } = fixture(t, { aircraftInfo }); - viewer.trackedEntity = aircraft; + followEntity(viewer, aircraft); cockpit.syncEntry(); assert.equal(store.presence.entryKind, 'aircraft'); }); diff --git a/src/ui/cockpitPresence.test.mjs b/src/ui/cockpitPresence.test.mjs index 7912d8cbe..fa1f4663b 100644 --- a/src/ui/cockpitPresence.test.mjs +++ b/src/ui/cockpitPresence.test.mjs @@ -10,7 +10,10 @@ import { CockpitViewController } from './cockpitController.js'; import { useCockpitStore } from './stores/cockpit.js'; import CockpitView from './views/CockpitView.vue'; import ContextView from './views/ContextView.vue'; -import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { + bindFakeCesiumCamera, + followEntity, +} from '../testSupport/fakeCameraPort.mjs'; const INFO = Object.freeze({ icao24: 'abc123', @@ -43,7 +46,6 @@ function fixture(t) { const listeners = () => ({ addEventListener: () => () => {} }); const entity = { position: {}, show: true }; const viewer = { - trackedEntity: entity, camera: { cancelFlight() {} }, entities: { contains: (candidate) => candidate === entity }, scene: { @@ -53,6 +55,7 @@ function fixture(t) { trackedEntityChanged: listeners(), }; bindFakeCesiumCamera(viewer, { frame: { on: () => () => {} } }); + followEntity(viewer, entity); const cockpit = new CockpitViewController(viewer, { services: { flightsLayer: { getTrackedInfo: () => INFO, refreshTr3b() {} }, diff --git a/src/voice/gevActions.test.mjs b/src/voice/gevActions.test.mjs index beaa9fce2..bfa71f3d5 100644 --- a/src/voice/gevActions.test.mjs +++ b/src/voice/gevActions.test.mjs @@ -36,7 +36,8 @@ import { presentResult } from './resultDisplay.js'; import { withEntityRecord } from '../data/entityRecords.js'; import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; import { fakeSceneQuery } from '../testSupport/fakeCesiumScene.mjs'; -import { cameraOf } from '../render/rendererOf.js'; +import { bindRenderer, cameraOf } from '../render/rendererOf.js'; +import { entityFollowTarget } from '../data/followed.js'; test('every live basemap is reachable by its own id — no enum value without a voice alias', () => { // B1 regression: a stack added to MAP_STACKS (and the set_map_stack enum) @@ -1505,7 +1506,6 @@ test('voice Stop Tracking reports exact layers whose active or durable clear fai getAll: () => [], }; const viewer = { - trackedEntity: withEntityRecord({}, { trackedId: 'flights:active' }), scene: { canvas: { addEventListener() {}, removeEventListener() {} }, preRender: { addEventListener() {} }, @@ -1513,6 +1513,18 @@ test('voice Stop Tracking reports exact layers whose active or durable clear fai camera: { moveEnd: { addEventListener() {} } }, clock: { onTick: { addEventListener() {} } }, }; + // The camera follows the active aircraft through its port. + const camera = { + followed: entityFollowTarget( + withEntityRecord({}, { trackedId: 'flights:active' }), + {}, + ), + follow(target) { + camera.followed = target; + }, + on: () => () => {}, + }; + bindRenderer(viewer, { camera, canvas: viewer.scene.canvas }); const runner = createGevActionRunner({ viewer, styleManager: {}, @@ -1527,8 +1539,8 @@ test('voice Stop Tracking reports exact layers whose active or durable clear fai error: 'Tracking could not be cleared for: flights, military', }); assert.equal( - viewer.trackedEntity, - undefined, + camera.followed, + null, 'camera ownership still releases after partial failure', ); });