From 7ab969599c540f1100bf1c2a99fb693fc5bd7049 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 02:39:58 -0800 Subject: [PATCH] Fly to places, landmarks and imported files through the camera and query ports The camera ground guard reads the eye from the camera port's pose, the flight state from the port, and the surface under it from the query port's heights, and lifts through the port. Place and landmark flights read the terrain height from the query port and build their targets with geo. Framing ranges read the field of view from the pose (the frustum's wider-side angle, as it read before). An imported file's flight frames its footprint, plain lon/lat/height points, with geo's bounding sphere and the port's flyToBounds; walking the file's Cesium data source for those points moves into the file importer, which stays on the Cesium allow-list. The Cesium query port answers terrain heights without depth textures, as the height service always has: only the drawn surface needs them. cameraGroundGuard, locations, cameraFraming and flyToDataSource leave the allow-list. The annotation resolver, still listed, loads the camera factory for the application operations entry, which reached it through locations before. --- src/annotations/resolver.js | 5 ++ src/cameraGroundGuard.js | 119 +++++++++++-------------- src/cameraGroundGuard.test.mjs | 8 +- src/data/cameraFraming.js | 27 +++++- src/data/cameraFraming.test.mjs | 36 ++++++++ src/data/geoFileImport.js | 65 ++++++++++++++ src/locations.js | 40 ++++----- src/render/cesium/query.js | 6 +- src/render/cesium/query.test.mjs | 17 ++++ src/render/cesiumAllowList.json | 4 - src/testSupport/fakeCameraPort.mjs | 3 + src/ui/flyToDataSource.js | 137 ++++++++--------------------- src/ui/flyToDataSource.test.mjs | 43 ++++++--- src/ui/geoFileImport.js | 7 +- 14 files changed, 303 insertions(+), 214 deletions(-) create mode 100644 src/data/cameraFraming.test.mjs diff --git a/src/annotations/resolver.js b/src/annotations/resolver.js index ac9401720..dfee8c009 100644 --- a/src/annotations/resolver.js +++ b/src/annotations/resolver.js @@ -46,6 +46,11 @@ import { createOutlineRungs } from './outlineRungs.js'; import { unavailablePlaceSearch } from '../search/placeSearch.js'; import { isPickedWorldPosition } from '../data/scenePick.js'; import { heightsFor } from '../queries/heights.js'; +// The application operations entry reaches locations.js, whose flights go +// through the camera and query ports and which cannot load the Cesium adapter +// itself; this listed module loads the factories a viewer with no renderer +// bound gets them from. +import '../render/cesium/camera.js'; /** Prepare only local dateline outlines for planar admission and centering. */ function localOutlineFrame(fp) { diff --git a/src/cameraGroundGuard.js b/src/cameraGroundGuard.js index 220918dd0..a93456d18 100644 --- a/src/cameraGroundGuard.js +++ b/src/cameraGroundGuard.js @@ -15,11 +15,9 @@ * held, so the correction reads as the shot settling. */ import { onFollowChanged } from './data/followed.js'; -import * as Cesium from 'cesium'; import { ownCameraArrival } from './data/cameraArrival.js'; -import { heightsFor } from './queries/heights.js'; -import { cameraOf } from './render/cesium/camera.js'; -import { cameraFlightActive } from './render/cesium/internals.js'; +import { distance, dot, fromDegrees, toLonLatH } from './geo/index.js'; +import { findCamera, findQuery } from './render/rendererOf.js'; /** Minimum eye height above the rendered surface for a usable view. */ export const MIN_EYE_CLEARANCE_M = 120; @@ -32,71 +30,71 @@ const GUARD_EPSILON_M = 2; const MOVED_M = 0.01; const TURNED_COS = 1 - 1e-9; -const groundScratch = new Cesium.Cartesian3(); - -const probeScratch = new Cesium.Cartographic(); - /** * Highest rendered surface across a few cells, with how many cells answered. * A cell whose tiles are not streamed yet contributes nothing. - * @param {Cesium.Scene} scene Live scene. + * @param {object|null} query The scene's query port. * @param {Array<{lat: number, lon: number}>} cells Cells to probe. * @returns {{heightM: number, sampled: number}} Reading. */ -function sampleSurfaceM(scene, cells) { +function sampleSurfaceM(query, cells) { let heightM = Number.NaN; let sampled = 0; - if (!scene) return { heightM, sampled }; - const heights = heightsFor(scene); + if (!query) return { heightM, sampled }; for (const cell of cells) { // A miss is a cell whose tiles are not ready. - const height = heights.now( - Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, probeScratch), - ); - if (height === null) continue; + const height = query.sampleHeightNow({ lon: cell.lon, lat: cell.lat }); + if (!Number.isFinite(height)) continue; sampled += 1; heightM = Number.isFinite(heightM) ? Math.max(heightM, height) : height; } return { heightM, sampled }; } +/** + * The eye as the camera port poses it: where it is (from its position) and + * which way it looks; null when the pose cannot be read. + */ +function eyeOf(camera) { + try { + const pose = camera?.pose(); + const at = pose?.position && toLonLatH(pose.position); + if (!at || !pose.direction || !pose.up) return null; + return { ...pose, lon: at.lon, lat: at.lat, height: at.height }; + } catch { + return null; + } +} + /** The eye's ground point (height 0), its height, and which way it looks. */ -function poseOf(camera) { - const carto = - camera?.positionWC && Cesium.Cartographic.fromCartesian(camera.positionWC); - if (!carto || !camera.directionWC || !camera.upWC) return null; +function poseOf(eye) { + if (!eye) return null; return { - ground: Cesium.Cartesian3.fromRadians(carto.longitude, carto.latitude), - height: carto.height, - direction: Cesium.Cartesian3.clone(camera.directionWC), - up: Cesium.Cartesian3.clone(camera.upWC), + ground: fromDegrees(eye.lon, eye.lat), + height: eye.height, + direction: { ...eye.direction }, + up: { ...eye.up }, }; } /** * Whether another owner has moved the camera off `pose`: across the ground, - * down, or around. A pure rise is not one: Cesium's terrain collision lifts a - * buried eye straight up as tiles load, which is the case the guard exists - * for, so `pose` follows the highest eye seen and the guard keeps measuring. + * down, or around. A pure rise is not one: the renderer's terrain collision + * lifts a buried eye straight up as tiles load, which is the case the guard + * exists for, so `pose` follows the highest eye seen and the guard keeps + * measuring. */ -function moved(camera, pose) { - const carto = Cesium.Cartographic.fromCartesian(camera.positionWC); - if (!carto) return true; - const ground = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - 0, - undefined, - groundScratch, - ); +function moved(now, pose) { + if (!now) return true; + const ground = fromDegrees(now.lon, now.lat); if ( - Cesium.Cartesian3.distance(ground, pose.ground) > MOVED_M || - carto.height < pose.height - MOVED_M || - Cesium.Cartesian3.dot(camera.directionWC, pose.direction) < TURNED_COS || - Cesium.Cartesian3.dot(camera.upWC, pose.up) < TURNED_COS + distance(ground, pose.ground) > MOVED_M || + now.height < pose.height - MOVED_M || + dot(now.direction, pose.direction) < TURNED_COS || + dot(now.up, pose.up) < TURNED_COS ) return true; - pose.height = Math.max(pose.height, carto.height); + pose.height = Math.max(pose.height, now.height); return false; } @@ -127,7 +125,7 @@ export function groundClearanceDeficitM( * newer arrival owns the camera, or any other caller moving the camera or * starting a flight in the meantime: the guard only ever corrects the pose it * was started on. - * @param {Cesium.Viewer} viewer Live viewer. + * @param {object} viewer Live viewer. * @param {{lat: number, lon: number}} at Destination being framed. * @param {{clearanceM?: number, attempts?: number, intervalMs?: number, * isStale?: () => boolean, onLift?: (liftM: number) => void}} [options] @@ -145,7 +143,7 @@ export function guardCameraAboveGround(viewer, at, options = {}) { return () => {}; // Without a readable pose the guard could not tell a later owner's move. - const arrival = poseOf(viewer.camera); + const arrival = poseOf(eyeOf(findCamera(viewer))); if (!arrival) return () => {}; let timer = null; @@ -175,39 +173,28 @@ export function guardCameraAboveGround(viewer, at, options = {}) { const attempt = () => { if (done) return; if (isStale() || viewer.isDestroyed?.()) return stop(); - const camera = viewer.camera; + const camera = findCamera(viewer); + const now = eyeOf(camera); // Another caller owns the camera now; lifting would undo its move. - if (cameraFlightActive(camera) || moved(camera, arrival)) return stop(); + if (!camera || camera.flying || moved(now, arrival)) return stop(); remaining -= 1; - const carto = camera.positionCartographic; // The eye must clear both the framed target and the ground beneath it. - const below = { - lat: Cesium.Math.toDegrees(carto.latitude), - lon: Cesium.Math.toDegrees(carto.longitude), - }; - const { heightM, sampled } = sampleSurfaceM(viewer.scene, [ + const below = { lat: now.lat, lon: now.lon }; + const { heightM, sampled } = sampleSurfaceM(findQuery(viewer), [ { lat: at.lat, lon: at.lon }, below, ]); if (sampled > 0 && Number.isFinite(heightM)) { - const deficit = groundClearanceDeficitM( - carto.height, - heightM, - clearanceM, - ); + const deficit = groundClearanceDeficitM(now.height, heightM, clearanceM); if (deficit > 0) { stop(); - cameraOf(viewer).flyTo( - Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - carto.height + deficit, - ), + camera.flyTo( + { lon: now.lon, lat: now.lat, height: now.height + deficit }, { orientation: { - heading: camera.heading, - pitch: camera.pitch, - roll: camera.roll, + heading: now.heading, + pitch: now.pitch, + roll: now.roll, }, durationS: 0.9, easing: 'cubicInOut', diff --git a/src/cameraGroundGuard.test.mjs b/src/cameraGroundGuard.test.mjs index 8503594c4..11fc8760f 100644 --- a/src/cameraGroundGuard.test.mjs +++ b/src/cameraGroundGuard.test.mjs @@ -4,6 +4,7 @@ // works from a predicted ground height. The guard measures the real surface // after arrival and lifts the eye; these tests pin when it acts. import { bindFakeCesiumCamera } from './testSupport/fakeCameraPort.mjs'; +import { fakeSceneQuery } from './testSupport/fakeCesiumScene.mjs'; import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; @@ -55,10 +56,11 @@ function fakeViewer({ cameraHeightM, surfaceM }) { 30.3141, cameraHeightM, ); - return bindFakeCesiumCamera({ + const viewer = { flights, scene: { canvas: null, + sampleHeightSupported: true, sampleHeight: (carto) => typeof surfaceM === 'function' ? surfaceM(carto) : surfaceM, }, @@ -71,12 +73,14 @@ function fakeViewer({ cameraHeightM, surfaceM }) { pitch: -0.55, roll: 0, // As Cesium does: a flight is under way until it completes. + _currentFlight: undefined, flyTo(options) { flights.push(options); this._currentFlight = {}; }, }, - }); + }; + return bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) }); } test('the guard lifts a buried arrival once the surface answers', async () => { diff --git a/src/data/cameraFraming.js b/src/data/cameraFraming.js index a2d38b5ec..af2ee7fc5 100644 --- a/src/data/cameraFraming.js +++ b/src/data/cameraFraming.js @@ -1,10 +1,29 @@ -import * as Cesium from 'cesium'; +import { toRadians } from '../geo/index.js'; +import { findCamera } from '../render/rendererOf.js'; + +/** The camera port's pose, or null when there is none to read. */ +function poseOf(viewer) { + try { + return findCamera(viewer)?.pose() ?? null; + } catch { + return null; + } +} /** Camera range with breathing room in both viewport dimensions. */ export function rangeForBoundingSphere(viewer, radius) { - const frustum = viewer.camera?.frustum; - const verticalFov = Number(frustum?.fov) || Cesium.Math.toRadians(60); - const aspectRatio = Math.max(0.5, Number(frustum?.aspectRatio) || 1); + const pose = poseOf(viewer); + const fovy = Number(pose?.fovy); + const aspect = Number(pose?.aspectRatio); + // The frustum's field of view: along its wider side. + const fov = + fovy > 0 && aspect > 1 + ? 2 * Math.atan(Math.tan(fovy / 2) * aspect) + : fovy > 0 + ? fovy + : NaN; + const verticalFov = fov || toRadians(60); + const aspectRatio = Math.max(0.5, aspect || 1); const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio); const limitingFov = Math.min(verticalFov, horizontalFov); // Target 57% sphere occupancy so perspective still leaves at least 40% diff --git a/src/data/cameraFraming.test.mjs b/src/data/cameraFraming.test.mjs new file mode 100644 index 000000000..55da2fa80 --- /dev/null +++ b/src/data/cameraFraming.test.mjs @@ -0,0 +1,36 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { rangeForBoundingSphere } from './cameraFraming.js'; + +/** The range as it was read from Cesium's frustum before the camera port. */ +function rangeFromFrustum(frustum, radius) { + const verticalFov = frustum.fov; + const aspectRatio = Math.max(0.5, frustum.aspectRatio); + const horizontalFov = 2 * Math.atan(Math.tan(verticalFov / 2) * aspectRatio); + const limitingFov = Math.min(verticalFov, horizontalFov); + return (radius / Math.sin((limitingFov * 0.57) / 2)) * 1.05; +} + +for (const aspectRatio of [16 / 9, 390 / 844, 1]) { + test(`framing reads the frustum's field of view through the camera port (aspect ${aspectRatio.toFixed(2)})`, () => { + const frustum = new Cesium.PerspectiveFrustum({ + fov: Math.PI / 3, + aspectRatio, + near: 1, + far: 1e8, + }); + const viewer = bindFakeCesiumCamera({ camera: { frustum } }); + const range = rangeForBoundingSphere(viewer, 250); + assert.ok( + Math.abs(range - rangeFromFrustum(frustum, 250)) < 1e-6, + `${range} vs ${rangeFromFrustum(frustum, 250)}`, + ); + }); +} + +test('framing without a camera assumes a 60 degree square view', () => { + const expected = rangeFromFrustum({ fov: Math.PI / 3, aspectRatio: 1 }, 100); + assert.ok(Math.abs(rangeForBoundingSphere({}, 100) - expected) < 1e-9); +}); diff --git a/src/data/geoFileImport.js b/src/data/geoFileImport.js index a80909b91..8e36ebcc5 100644 --- a/src/data/geoFileImport.js +++ b/src/data/geoFileImport.js @@ -1528,3 +1528,68 @@ export async function loadGeoFile( ).then(() => pins.sync()), }; } + +/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */ +export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) { + const points = []; + const add = (position, grounded = false) => { + if ( + !position || + ![position.x, position.y, position.z].every(Number.isFinite) + ) + return; + const c = Cesium.Cartographic.fromCartesian(position); + if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude)) + points.push([ + Cesium.Math.toDegrees(c.longitude), + Cesium.Math.toDegrees(c.latitude), + grounded ? 0 : c.height, + ]); + }; + if (dataSource?.show === false) return points; + for (const entity of dataSource?.importedEntities ?? + dataSource?.entities?.values ?? + []) { + if (entity.isShowing === false) continue; + add( + entity.position?.getValue?.(time), + entity.billboard?.heightReference?.getValue?.(time) === + Cesium.HeightReference.CLAMP_TO_GROUND, + ); + for (const graphic of [entity.polyline, entity.wall]) + for (const position of graphic?.positions?.getValue?.(time) || []) + add(position, graphic.clampToGround?.getValue?.(time) === true); + const rings = [entity.polygon?.hierarchy?.getValue?.(time)]; + while (rings.length) { + const ring = rings.pop(); + for (const position of ring?.positions || []) + add( + position, + entity.polygon?.perPositionHeight?.getValue?.(time) !== true, + ); + for (const hole of ring?.holes || []) rings.push(hole); + } + const rectangle = entity.rectangle?.coordinates?.getValue?.(time); + if (rectangle) { + const bounds = Cesium.RectangleGeometry.computeRectangle({ + rectangle, + rotation: entity.rectangle.rotation?.getValue?.(time) || 0, + }); + for (const corner of [ + 'southwest', + 'southeast', + 'northwest', + 'northeast', + ]) { + const c = Cesium.Rectangle[corner](bounds); + if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude)) + points.push([ + Cesium.Math.toDegrees(c.longitude), + Cesium.Math.toDegrees(c.latitude), + entity.rectangle.height?.getValue?.(time) || 0, + ]); + } + } + } + return points; +} diff --git a/src/locations.js b/src/locations.js index 501070a65..9857f156d 100644 --- a/src/locations.js +++ b/src/locations.js @@ -2,7 +2,6 @@ import { rangeForBoundingSphere } from './data/cameraFraming.js'; import { isUnavailableCapability } from './sources/capability.js'; import { createOverpassFeatureSource } from './sources/overpassFeatures.js'; import { applicationServices } from './services/application.js'; -import * as Cesium from 'cesium'; import { greatCircleKm } from './geoDistance.js'; import { viewportBias, @@ -12,8 +11,8 @@ import { unavailablePlaceSearch } from './search/placeSearch.js'; import { cancelCameraArrival } from './data/cameraArrival.js'; import { guardCameraAboveGround } from './cameraGroundGuard.js'; import { CITY_POIS } from './cityPois.js'; -import { heightsFor } from './queries/heights.js'; -import { cameraOf } from './render/cesium/camera.js'; +import { fromDegrees, toRadians } from './geo/index.js'; +import { cameraOf, findQuery } from './render/rendererOf.js'; /** Newest landmark arrival; an older post-arrival ground guard yields to it. */ let arrivalGeneration = 0; @@ -33,7 +32,7 @@ export const GLOBE_VIEW = Object.freeze({ /** * Fly straight out to the full-earth globe view, keeping the current sub-camera * point centered so the user's continent stays in front of them. - * @param {Cesium.Viewer} viewer + * @param {object} viewer * @param {{duration?: number, onComplete?: Function, onCancel?: Function}} options * @returns {{latitude: number, longitude: number, heightM: number}} */ @@ -46,7 +45,7 @@ export function flyToGlobeView(viewer, options = {}) { { orientation: { heading: 0, - pitch: Cesium.Math.toRadians(GLOBE_VIEW.pitchDeg), + pitch: toRadians(GLOBE_VIEW.pitchDeg), roll: 0, }, durationS: finitePositive(options.duration) || GLOBE_VIEW.durationS, @@ -72,7 +71,7 @@ export const LOCATIONS = Object.entries(CITY_POIS).map(([id, city]) => ({ * Fly the camera to a landmark using lookAt-based targeting. * Guarantees the target is centered in viewport via flyToBoundingSphere + lookAt. * - * @param {Cesium.Viewer} viewer + * @param {object} viewer * @param {number} lat - Latitude in degrees * @param {number} lon - Longitude in degrees * @param {object} options @@ -84,7 +83,7 @@ export const LOCATIONS = Object.entries(CITY_POIS).map(([id, city]) => ({ * @param {number} options.duration - Flight duration in seconds (default 3.0) * @param {{cachedGroundFloor?: Function, warmGroundFloor?: Function}} [options.ground] - * Optional ground-floor service; its cached elevation outranks `groundElevation` - * @returns {{ targetPosition: Cesium.Cartesian3 }} The computed target for orbit use + * @returns {{ targetPosition: {x: number, y: number, z: number} }} The computed target for orbit use */ export function flyToLandmark(viewer, lat, lon, options = {}) { cancelCameraArrival(viewer); @@ -103,10 +102,9 @@ export function flyToLandmark(viewer, lat, lon, options = {}) { } = options; // Sample terrain height (sync — uses loaded tiles; 0 if globe/terrain not ready) - const targetCartographic = Cesium.Cartographic.fromDegrees(lon, lat); - const sampledHeight = heightsFor(viewer.scene).now(targetCartographic, { - against: 'terrain', - }); + const sampledHeight = + findQuery(viewer)?.sampleHeightNow({ lon, lat }, { against: 'terrain' }) ?? + null; // Use sampled height if available, otherwise the cached ground-floor // elevation (same ellipsoidal datum), then the pre-baked city elevation. @@ -132,7 +130,7 @@ export function flyToLandmark(viewer, lat, lon, options = {}) { const targetHeight = bounds ? terrainHeight + bounds.height / 2 : terrainHeight + buildingHeight; - const targetPosition = Cesium.Cartesian3.fromDegrees(lon, lat, targetHeight); + const targetPosition = fromDegrees(lon, lat, targetHeight); const boundingRadius = bounds ? buildingBoundingRadius(bounds) : 0; const framingRange = bounds ? Math.max( @@ -142,8 +140,8 @@ export function flyToLandmark(viewer, lat, lon, options = {}) { : range; const hpr = { - heading: Cesium.Math.toRadians(heading), - pitch: Cesium.Math.toRadians(pitch), + heading: toRadians(heading), + pitch: toRadians(pitch), range: framingRange, }; @@ -586,8 +584,7 @@ export function viewportMetrics(viewport) { if (centerLng > 180) centerLng -= 360; const latSpanKm = Math.abs(latSpanDeg) * KM_PER_DEGREE; - const lonSpanKm = - lonSpanDeg * KM_PER_DEGREE * Math.cos(Cesium.Math.toRadians(centerLat)); + const lonSpanKm = lonSpanDeg * KM_PER_DEGREE * Math.cos(toRadians(centerLat)); return { latSpanDeg, lonSpanDeg, @@ -688,7 +685,7 @@ export function placeFramingViewport( const latHalfDeg = PLACE_FALLBACK_HALF_SPAN_KM / KM_PER_DEGREE; // Guard the cosine so a near-polar anchor cannot blow the longitude half-extent up. - const cosLat = Math.max(0.05, Math.cos(Cesium.Math.toRadians(anchorLat))); + const cosLat = Math.max(0.05, Math.cos(toRadians(anchorLat))); const lngHalfDeg = PLACE_FALLBACK_HALF_SPAN_KM / (KM_PER_DEGREE * cosLat); const wrapLng = (lng) => ((((lng + 180) % 360) + 360) % 360) - 180; return { @@ -831,11 +828,7 @@ function flyToViewportBounds(viewer, viewport, options = {}) { // Same short-way-round rule for the reported centre: averaging raw longitudes // puts a dateline-crossing box's centre on the opposite side of the planet. return { - targetPosition: Cesium.Cartesian3.fromDegrees( - metrics.centerLng, - metrics.centerLat, - 0, - ), + targetPosition: fromDegrees(metrics.centerLng, metrics.centerLat, 0), boundingRadius: 0, range: null, viewBounds: viewport, @@ -1005,8 +998,7 @@ function pointInPolygon(lon, lat, coordinates) { function approximateDistanceM(latA, lonA, latB, lonB) { const latitudeScale = 111320; - const longitudeScale = - latitudeScale * Math.cos(Cesium.Math.toRadians((latA + latB) / 2)); + const longitudeScale = latitudeScale * Math.cos(toRadians((latA + latB) / 2)); return Math.hypot( (latB - latA) * latitudeScale, (lonB - lonA) * longitudeScale, diff --git a/src/render/cesium/query.js b/src/render/cesium/query.js index 616e9063c..166f390a7 100644 --- a/src/render/cesium/query.js +++ b/src/render/cesium/query.js @@ -253,11 +253,15 @@ export function createCesiumQuery({ return !occluder.isPointVisible(toCartesian(position)); }, sampleHeightNow(point, { against = 'surface', exclude } = {}) { + // Terrain answers from the globe's own tiles, without depth textures. + if (against === 'terrain') return heightNow(point, against); if (!can('sampleHeight')) return null; return heightNow(point, against, seeThrough(exclude)); }, sampleHeightNowMany(points, out, { against = 'surface', exclude } = {}) { - const excluded = can('sampleHeight') && seeThrough(exclude); + // Terrain sees through nothing, so it needs no sets to see through. + const excluded = + against === 'terrain' || (can('sampleHeight') && seeThrough(exclude)); const point = { lon: 0, lat: 0 }; for (let i = 0; i < out.length; i++) { point.lon = points[i * 2]; diff --git a/src/render/cesium/query.test.mjs b/src/render/cesium/query.test.mjs index 70e53fd1b..cb9dedea6 100644 --- a/src/render/cesium/query.test.mjs +++ b/src/render/cesium/query.test.mjs @@ -99,6 +99,23 @@ test('a viewer of its own, with no renderer bound, is queried through a built po other.dispose(); }); +test('terrain heights answer without depth textures; the drawn surface does not', () => { + const viewer = fakeViewer(); + viewer.scene.sampleHeightSupported = false; + viewer.scene.globe = { getHeight: () => 2600 }; + const query = queryOf(viewer); + const point = { lon: 1, lat: 2 }; + assert.equal(query.sampleHeightNow(point, { against: 'terrain' }), 2600); + assert.equal(query.sampleHeightNow(point), null); + const out = new Float64Array(1); + query.sampleHeightNowMany(new Float64Array([1, 2]), out, { + against: 'terrain', + }); + assert.equal(out[0], 2600); + query.sampleHeightNowMany(new Float64Array([1, 2]), out); + assert.ok(Number.isNaN(out[0])); +}); + test('nothing to query, no port', () => { assert.equal(findQuery({ scene: {} }), null); assert.throws(() => queryOf({ scene: {} }), /no renderer to query/); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 192191966..85018a9e5 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -8,7 +8,6 @@ "src/app/embed.js", "src/app/scene.js", "src/app/viewer.js", - "src/cameraGroundGuard.js", "src/cameraVerbs.js", "src/celestialRing.js", "src/cockpitCloudEffects.js", @@ -20,7 +19,6 @@ "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiEvent.js", "src/data/bhoteKoshiLocator.js", - "src/data/cameraFraming.js", "src/data/cctvGizmo.js", "src/data/contactTrailRenderer.js", "src/data/detection.js", @@ -97,7 +95,6 @@ "src/layers/wind/gpuRendering.js", "src/layers/wind/relief.js", "src/layers/wind/rendering.js", - "src/locations.js", "src/maps/catalog.js", "src/maps/controller.js", "src/maps/google3d.js", @@ -117,7 +114,6 @@ "src/ui/cockpitCamera.js", "src/ui/cockpitContext.js", "src/ui/cockpitController.js", - "src/ui/flyToDataSource.js", "src/ui/imageryBoxTool.js", "src/ui/shareFollow.js", "src/voice/gevActions.js" diff --git a/src/testSupport/fakeCameraPort.mjs b/src/testSupport/fakeCameraPort.mjs index bcf52c815..53b1f5b61 100644 --- a/src/testSupport/fakeCameraPort.mjs +++ b/src/testSupport/fakeCameraPort.mjs @@ -156,6 +156,9 @@ export function bindFakeCesiumCamera(viewer, ports = {}) { ...(Number.isFinite(fake.frustum?.fovy) ? { fovy: fake.frustum.fovy } : {}), + ...(Number.isFinite(fake.frustum?.aspectRatio) + ? { aspectRatio: fake.frustum.aspectRatio } + : {}), lon: c ? toDegrees(c.longitude) : NaN, lat: c ? toDegrees(c.latitude) : NaN, height: c ? c.height : NaN, diff --git a/src/ui/flyToDataSource.js b/src/ui/flyToDataSource.js index 30cd98227..b929f7dbd 100644 --- a/src/ui/flyToDataSource.js +++ b/src/ui/flyToDataSource.js @@ -1,96 +1,38 @@ /** Frame the complete finite footprint of a session-local file. */ -import * as Cesium from 'cesium'; import { guardCameraAboveGround } from '../cameraGroundGuard.js'; import { rangeForBoundingSphere } from '../data/cameraFraming.js'; import { cancelCameraArrival } from '../data/cameraArrival.js'; -import { heightsFor } from '../queries/heights.js'; +import { distance, fromDegrees, toLonLatH } from '../geo/index.js'; +import { sphereFromPoints } from '../geo/sphere.js'; +import { findCamera, findQuery } from '../render/rendererOf.js'; -/** All visible positions, path vertices, polygon rings, walls and overlay bounds. */ -export function dataSourcePoints(dataSource, time = Cesium.JulianDate.now()) { - const points = []; - const add = (position, grounded = false) => { - if ( - !position || - ![position.x, position.y, position.z].every(Number.isFinite) - ) - return; - const c = Cesium.Cartographic.fromCartesian(position); - if (c && Number.isFinite(c.longitude) && Number.isFinite(c.latitude)) - points.push([ - Cesium.Math.toDegrees(c.longitude), - Cesium.Math.toDegrees(c.latitude), - grounded ? 0 : c.height, - ]); - }; - if (dataSource?.show === false) return points; - for (const entity of dataSource?.importedEntities ?? - dataSource?.entities?.values ?? - []) { - if (entity.isShowing === false) continue; - add( - entity.position?.getValue?.(time), - entity.billboard?.heightReference?.getValue?.(time) === - Cesium.HeightReference.CLAMP_TO_GROUND, - ); - for (const graphic of [entity.polyline, entity.wall]) - for (const position of graphic?.positions?.getValue?.(time) || []) - add(position, graphic.clampToGround?.getValue?.(time) === true); - const rings = [entity.polygon?.hierarchy?.getValue?.(time)]; - while (rings.length) { - const ring = rings.pop(); - for (const position of ring?.positions || []) - add( - position, - entity.polygon?.perPositionHeight?.getValue?.(time) !== true, - ); - for (const hole of ring?.holes || []) rings.push(hole); - } - const rectangle = entity.rectangle?.coordinates?.getValue?.(time); - if (rectangle) { - const bounds = Cesium.RectangleGeometry.computeRectangle({ - rectangle, - rotation: entity.rectangle.rotation?.getValue?.(time) || 0, - }); - for (const corner of [ - 'southwest', - 'southeast', - 'northwest', - 'northeast', - ]) { - const c = Cesium.Rectangle[corner](bounds); - if (Number.isFinite(c.longitude) && Number.isFinite(c.latitude)) - points.push([ - Cesium.Math.toDegrees(c.longitude), - Cesium.Math.toDegrees(c.latitude), - entity.rectangle.height?.getValue?.(time) || 0, - ]); - } - } - } - return points; -} - -/** Fly synchronously to the footprint; later navigation always owns its camera. */ -export function flyToDataSource( +/** + * Fly synchronously to a footprint, `[lon, lat, height]` points (degrees, + * metres) such as a file's (`dataSourcePoints`); later navigation always + * owns its camera. False when there is nothing to frame or no camera. + */ +export function flyToFootprint( viewer, - dataSource, + points, { duration = 1.5, ground = null } = {}, ) { - const points = dataSourcePoints(dataSource); - if (!points.length) return false; + if (!points?.length) return false; + const camera = findCamera(viewer); + if (!camera) return false; cancelCameraArrival(viewer); const positions = points.map(([lon, lat, height]) => - Cesium.Cartesian3.fromDegrees(lon, lat, height), + fromDegrees(lon, lat, height), ); - const sphere = Cesium.BoundingSphere.fromPoints(positions); - const center = - Cesium.Cartographic.fromCartesian(sphere.center) || - Cesium.Cartographic.fromDegrees(points[0][0], points[0][1]); - const lat = Cesium.Math.toDegrees(center.latitude), - lon = Cesium.Math.toDegrees(center.longitude); - const terrain = viewer.scene - ? heightsFor(viewer.scene).now(center, { against: 'terrain' }) - : null; + const sphere = sphereFromPoints(positions); + const center = toLonLatH(sphere.center) || { + lon: points[0][0], + lat: points[0][1], + height: 0, + }; + const { lat, lon } = center; + const terrain = + findQuery(viewer)?.sampleHeightNow({ lon, lat }, { against: 'terrain' }) ?? + null; const cached = ground?.cachedGroundFloor?.(lat, lon); const height = Number.isFinite(terrain) && terrain > 0 @@ -101,25 +43,20 @@ export function flyToDataSource( ? terrain : 0; ground?.warmGroundFloor?.([{ lat, lon }]); - sphere.center = Cesium.Cartesian3.fromRadians( - center.longitude, - center.latitude, - Math.max(0, height, center.height), - ); - sphere.radius = 0; + const framed = { + center: fromDegrees(lon, lat, Math.max(0, height, center.height)), + radius: 0, + }; for (const position of positions) - sphere.radius = Math.max( - sphere.radius, - Cesium.Cartesian3.distance(sphere.center, position), - ); - viewer.camera?.flyToBoundingSphere?.(sphere, { - offset: new Cesium.HeadingPitchRange( - viewer.camera.heading || 0, - -Math.PI / 2, - Math.max(800, rangeForBoundingSphere(viewer, sphere.radius)), - ), - duration, - complete: () => guardCameraAboveGround(viewer, { lat, lon }), + framed.radius = Math.max(framed.radius, distance(framed.center, position)); + camera.flyToBounds(framed, { + offset: { + heading: camera.pose().heading || 0, + pitch: -Math.PI / 2, + range: Math.max(800, rangeForBoundingSphere(viewer, framed.radius)), + }, + durationS: duration, + onComplete: () => guardCameraAboveGround(viewer, { lat, lon }), }); return true; } diff --git a/src/ui/flyToDataSource.test.mjs b/src/ui/flyToDataSource.test.mjs index 62f6073a6..141d9f594 100644 --- a/src/ui/flyToDataSource.test.mjs +++ b/src/ui/flyToDataSource.test.mjs @@ -1,8 +1,22 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; -import { cancelCameraArrival } from '../data/cameraArrival.js'; -import { dataSourcePoints, flyToDataSource } from './flyToDataSource.js'; +import { + cancelCameraArrival, + ownCameraArrival, +} from '../data/cameraArrival.js'; +import { dataSourcePoints } from '../data/geoFileImport.js'; +import { bindFakeCesiumCamera } from '../testSupport/fakeCameraPort.mjs'; +import { fakeSceneQuery } from '../testSupport/fakeCesiumScene.mjs'; +import { flyToFootprint } from './flyToDataSource.js'; + +/** As the file import flies to one of its files. */ +const flyToDataSource = (viewer, dataSource) => + flyToFootprint(viewer, dataSourcePoints(dataSource)); + +/** A Cesium-shaped viewer double, bound to the camera and query ports. */ +const bound = (viewer) => + bindFakeCesiumCamera(viewer, { query: fakeSceneQuery(viewer) }); function source() { const ds = new Cesium.CustomDataSource('t'); @@ -36,22 +50,27 @@ test('points come from positions, lines and polygons, as lon/lat only', () => { test('the camera frames the footprint at the surface, never a buried center', () => { const calls = []; - const viewer = { + const viewer = bound({ + scene: {}, camera: { heading: 0, + positionWC: Cesium.Cartesian3.fromDegrees(-122.49, 37.77, 900), + directionWC: new Cesium.Cartesian3(0, 0, -1), + upWC: new Cesium.Cartesian3(0, 1, 0), flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }), }, flyTo: () => calls.push('viewer.flyTo'), - }; + }); assert.equal(flyToDataSource(viewer, source()), true); const center = Cesium.Cartographic.fromCartesian(calls[0].sphere.center); assert.ok(Math.abs(center.height) < 50, `center height ${center.height}`); assert.ok(calls[0].options.offset.range >= 800); - assert.equal( - typeof calls[0].options.complete, - 'function', - 'the ground guard runs on landing', - ); + // Landing starts the ground guard, which takes over the arrival. + let handedOver = false; + ownCameraArrival(viewer, () => (handedOver = true)); + calls[0].options.complete(); + assert.equal(handedOver, true, 'the ground guard runs on landing'); + cancelCameraArrival(viewer); assert.equal( flyToDataSource(viewer, new Cesium.CustomDataSource('empty')), false, @@ -113,13 +132,13 @@ test('portrait framing accounts for FOV, high ground and symmetric extents', () }, }); const calls = []; - const viewer = { + const viewer = bound({ scene: { globe: { getHeight: () => 2600 } }, camera: { - frustum: { fov: Math.PI / 3, aspectRatio: 390 / 844 }, + frustum: { fovy: Math.PI / 3, aspectRatio: 390 / 844 }, flyToBoundingSphere: (sphere, options) => calls.push({ sphere, options }), }, - }; + }); flyToDataSource(viewer, ds); assert.ok( Math.abs( diff --git a/src/ui/geoFileImport.js b/src/ui/geoFileImport.js index cf57eb5e1..ee204c2ae 100644 --- a/src/ui/geoFileImport.js +++ b/src/ui/geoFileImport.js @@ -2,10 +2,15 @@ import { GeoImportError, MAX_IMPORTED_FILES, + dataSourcePoints, loadGeoFile, } from '../data/geoFileImport.js'; import { formatNumber, t, tn, translateKnown } from '../i18n/index.js'; -import { flyToDataSource } from './flyToDataSource.js'; +import { flyToFootprint } from './flyToDataSource.js'; + +/** Fly to the whole footprint of one imported file's data source. */ +const flyToDataSource = (viewer, dataSource, options) => + flyToFootprint(viewer, dataSourcePoints(dataSource), options); // One color per file, in import order, from the whiteboard palette. const COLORS = ['#39d0ff', '#ffb547', '#5dff9f', '#ff6b6b', '#8be9ff'];