From e34e923ddde0e4577a34e6e716e513ad2a8931b6 Mon Sep 17 00:00:00 2001 From: Sameh Khamis Date: Sat, 7 Nov 2026 02:41:56 -0800 Subject: [PATCH] Ask the renderer's query port for heights through the queries gateway The Cesium scene's height service moves into the Cesium adapter (src/render/cesium/heights.js), where the Cesium query port answers its height members through it; the files still bound to the Cesium scene import it from there. src/queries/heights.js becomes the height gateway over the renderer's query port: heightsOf(viewer) answers now, clampNow, batch, clampBatch and supported as before, a miss is null, a failed or destroyed query rejects, and exclusions are draw set ids. The source scan that keeps height queries in one place still holds: outside the renderer, only the gateway asks for streamed heights. The bikeshare layer samples its station heights through it. Heights leaves the allow-list. --- scripts/format-scope.json | 1 + scripts/package-boundaries.json | 35 ++- src/annotations/resolver.js | 2 +- src/annotations/screenAnnotationRenderer.js | 2 +- src/annotations/worldAnnotationRenderer.js | 2 +- src/cameraVerbs.js | 2 +- src/data/bhoteKoshiEvent.js | 2 +- src/data/geoFileImport.js | 2 +- src/data/localGeojsonCore.js | 2 +- src/layers/bikeshare/rendering.js | 8 +- src/layers/traffic/surface.js | 2 +- src/layers/transit/height.js | 2 +- src/queries/heights.js | 211 ++++++++------- src/queries/heights.test.mjs | 273 ++++++++++---------- src/render/cesium/heights.js | 166 ++++++++++++ src/render/cesium/heights.test.mjs | 191 ++++++++++++++ src/render/cesium/query.js | 2 +- src/render/cesiumAllowList.json | 1 - src/render/unboundCamera.test.mjs | 1 + src/services/groundSnap.js | 2 +- src/services/meshFloorSampler.js | 2 +- src/testSupport/fakeCesiumScene.mjs | 2 +- 22 files changed, 665 insertions(+), 248 deletions(-) create mode 100644 src/render/cesium/heights.js create mode 100644 src/render/cesium/heights.test.mjs diff --git a/scripts/format-scope.json b/scripts/format-scope.json index d0ff323e6..3e0aba992 100644 --- a/scripts/format-scope.json +++ b/scripts/format-scope.json @@ -65,6 +65,7 @@ "src/render/cesium/tileRequests.js", "src/render/cesium/tileRequests.test.mjs", "src/queries/heights.test.mjs", + "src/render/cesium/heights.test.mjs", "docs/CODE-BOUNDARIES.md", "src/main.js", "docs/APPLICATION.md", diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 2e59cc36a..95f1b2f6c 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -8,6 +8,7 @@ "modules": [ "src/data/infrastructure.js", "src/data/localGeojsonCore.js", + "src/render/cesium/heights.js", "src/render/cesium/camera.js", "src/data/iconSetPrimitive.js", "src/data/aircraftRecession.js", @@ -894,6 +895,7 @@ "src/data/iconSegment.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -1039,6 +1041,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -1324,6 +1327,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -1477,6 +1481,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -1580,6 +1585,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -1745,6 +1751,7 @@ "src/geo/quaternion.js", "src/geo/frames.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/credits.js", "src/queries/heights.js", "src/render/creditMarkup.js", @@ -1777,6 +1784,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/drawHit.js", "src/queries/heights.js", "src/render/cesium/effects.js", @@ -1857,6 +1865,7 @@ "src/render/rendererOf.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/camera.js", "src/render/camera/events.js", @@ -1955,6 +1964,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -2020,6 +2030,7 @@ "src/data/iconSegment.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -2103,6 +2114,7 @@ "src/data/iconSegment.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -2277,6 +2289,7 @@ "src/layers/traffic/state.js", "src/layers/traffic/style.js", "src/layers/traffic/surface.js", + "src/render/cesium/heights.js", "src/layers/traffic/timing.js", "src/layers/traffic/viewport.js", "src/render/rendererOf.js", @@ -2423,6 +2436,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -2508,6 +2522,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", @@ -2614,6 +2629,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", "src/render/cesium/credits.js", @@ -2702,6 +2718,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -2770,6 +2787,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/draw.js", "src/render/cesium/cameraControls.js", @@ -2871,6 +2889,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/credits.js", @@ -3051,6 +3070,7 @@ "src/scenes/nepalEvidencePack.js", "src/data/approxDistance.js", "src/data/bhoteKoshiEvent.js", + "src/render/cesium/heights.js", "src/ui/imagerySplit.js", "src/data/bhoteKoshiEmbeddedMedia.js", "src/data/bhoteKoshiLocator.js", @@ -4095,6 +4115,7 @@ "src/render/cesium/camera.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", @@ -4770,6 +4791,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", @@ -4893,6 +4915,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/queries/heights.js", "src/render/cesium/drawHit.js", "src/render/cesium/draw.js", @@ -5439,6 +5462,7 @@ "src/data/iconAtlas.js", "src/render/cesium/frame.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", @@ -5573,6 +5597,7 @@ "src/data/motionModel.js", "src/data/iconAtlas.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/frame.js", "src/render/cesium/camera.js", "src/render/camera/events.js", @@ -5834,6 +5859,7 @@ "src/render/cesium/credits.js", "src/render/creditMarkup.js", "src/render/cesium/query.js", + "src/render/cesium/heights.js", "src/render/cesium/draw.js", "src/render/cesium/gpuIcons.js", "src/render/motion/iconMotion.js", @@ -6095,8 +6121,13 @@ }, "heights": { "exports": ["./queries/heights"], - "modules": ["src/queries/heights.js"], - "external": ["cesium"] + "modules": [ + "src/queries/heights.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js" + ], + "external": [] }, "geo": { "exports": ["./geo"], diff --git a/src/annotations/resolver.js b/src/annotations/resolver.js index dfee8c009..412a4a257 100644 --- a/src/annotations/resolver.js +++ b/src/annotations/resolver.js @@ -45,7 +45,7 @@ import { import { createOutlineRungs } from './outlineRungs.js'; import { unavailablePlaceSearch } from '../search/placeSearch.js'; import { isPickedWorldPosition } from '../data/scenePick.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/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 diff --git a/src/annotations/screenAnnotationRenderer.js b/src/annotations/screenAnnotationRenderer.js index cc45d9f71..634f17539 100644 --- a/src/annotations/screenAnnotationRenderer.js +++ b/src/annotations/screenAnnotationRenderer.js @@ -9,7 +9,7 @@ import { t } from '../i18n/index.js'; import { nextTick } from 'vue'; import { useScreenAnnotationsStore } from '../ui/stores/screenAnnotations.js'; import { applicationPinia } from '../ui/vueRuntime.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; /** A label whose detailed outline could not be resolved. */ function outlineUnavailableLabel(label) { diff --git a/src/annotations/worldAnnotationRenderer.js b/src/annotations/worldAnnotationRenderer.js index 11b96d7ca..17b56de0b 100644 --- a/src/annotations/worldAnnotationRenderer.js +++ b/src/annotations/worldAnnotationRenderer.js @@ -2,7 +2,7 @@ import { recordWorkSlice } from '../sources/phaseTiming.js'; import { ringCentroid } from '../sources/featureGeometry.js'; import * as Cesium from 'cesium'; import { showOsmCredit, hideOsmCredit } from '../data/dataCredits.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; /** * World-space annotation renderer (Direction A). diff --git a/src/cameraVerbs.js b/src/cameraVerbs.js index f0d1c11db..ec5a7afd1 100644 --- a/src/cameraVerbs.js +++ b/src/cameraVerbs.js @@ -30,7 +30,7 @@ import { holdContinuousRender, releaseContinuousRender, } from './renderGovernor.js'; -import { heightsFor } from './queries/heights.js'; +import { heightsFor } from './render/cesium/heights.js'; import { cameraOf } from './render/cesium/camera.js'; import { findCamera } from './render/rendererOf.js'; diff --git a/src/data/bhoteKoshiEvent.js b/src/data/bhoteKoshiEvent.js index 837aac8a6..fe12eb82e 100644 --- a/src/data/bhoteKoshiEvent.js +++ b/src/data/bhoteKoshiEvent.js @@ -28,7 +28,7 @@ import { createImagerySplit } from '../ui/imagerySplit.js'; import { formatDate, t, tn, msg, onLocaleChange } from '../i18n/index.js'; import { useBhoteKoshiPanelStore } from '../ui/stores/bhoteKoshiPanel.js'; import { applicationPinia } from '../ui/vueRuntime.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; import { cameraOf } from '../render/cesium/camera.js'; import { findCamera } from '../render/rendererOf.js'; diff --git a/src/data/geoFileImport.js b/src/data/geoFileImport.js index 8e36ebcc5..7ddaef93f 100644 --- a/src/data/geoFileImport.js +++ b/src/data/geoFileImport.js @@ -3,7 +3,7 @@ import * as Cesium from 'cesium'; import { createImportImageBudget } from './geoImportImages.js'; import { createImportedPins } from './geoImportPins.js'; import { msg } from '../i18n/marker.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; /** Largest file accepted, in bytes. */ const MAX_IMPORT_BYTES = 50 * 1024 * 1024; diff --git a/src/data/localGeojsonCore.js b/src/data/localGeojsonCore.js index bfe1ddf5e..dcc257c0d 100644 --- a/src/data/localGeojsonCore.js +++ b/src/data/localGeojsonCore.js @@ -12,7 +12,7 @@ import { applyInfraEvictionGrace, shouldRecomputeInfraLod, } from './localGeojsonLod.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; const DEFAULT_LABEL_MAX = 900; const DEFAULT_LABEL_GRID_PX = 132; diff --git a/src/layers/bikeshare/rendering.js b/src/layers/bikeshare/rendering.js index 073617359..8135c1df9 100644 --- a/src/layers/bikeshare/rendering.js +++ b/src/layers/bikeshare/rendering.js @@ -14,7 +14,7 @@ import { POINT_FADE_BY_DISTANCE, POINT_DISABLE_DEPTH_TEST_M, } from './policy.js'; -import { heightsFor } from '../../queries/heights.js'; +import { heightsOf } from '../../queries/heights.js'; import { fromDegrees } from '../../geo/ellipsoid.js'; import { drawOf } from '../../render/rendererOf.js'; @@ -175,9 +175,9 @@ export function createRendering({ let height = POINT_HEIGHT_OFFSET_M; // Sample terrain height so points sit on ground rather than at ellipsoid level - const scene = layerState._viewer?.scene; - if (scene?.sampleHeightSupported) { - const sampled = heightsFor(scene).now({ lon, lat }); + const viewer = layerState._viewer; + if (viewer && heightsOf(viewer).supported().surface) { + const sampled = heightsOf(viewer).now({ lon, lat }); if (sampled !== null) height = sampled + POINT_HEIGHT_OFFSET_M; } diff --git a/src/layers/traffic/surface.js b/src/layers/traffic/surface.js index 60251924a..468cdfe07 100644 --- a/src/layers/traffic/surface.js +++ b/src/layers/traffic/surface.js @@ -1,7 +1,7 @@ import { phaseTiming } from '../../sources/phaseTiming.js'; import * as Cesium from 'cesium'; import { DOT_HEIGHT_OFFSET, MAX_WAYPOINTS_PER_ROAD } from './policy.js'; -import { heightsFor } from '../../queries/heights.js'; +import { heightsFor } from '../../render/cesium/heights.js'; function surfaceTilesReady(scene) { if (scene.globe?.show) return scene.globe.tilesLoaded !== false; diff --git a/src/layers/transit/height.js b/src/layers/transit/height.js index a91bb1842..024a5546f 100644 --- a/src/layers/transit/height.js +++ b/src/layers/transit/height.js @@ -7,7 +7,7 @@ import { HEIGHT_SAMPLE_MAX_ALTITUDE_M, withinViewBounds, } from './policy.js'; -import { heightsFor } from '../../queries/heights.js'; +import { heightsFor } from '../../render/cesium/heights.js'; /** Surface preparation off the render path, shared by markers and history. */ export function createHeight({ state, services, parts }) { diff --git a/src/queries/heights.js b/src/queries/heights.js index fad95c524..09fde456a 100644 --- a/src/queries/heights.js +++ b/src/queries/heights.js @@ -1,47 +1,50 @@ /** * @module queries/heights - * @description The one place height queries go: how high the rendered - * surface or the terrain is under a point, now or after streaming. + * @description The one place the app's height queries go: how high the + * rendered surface or the terrain is under a point, now or after streaming, + * asked of the renderer's query port (`src/render/contract/query.d.ts`). * * `now()` answers from what is already loaded and may return `null`: tiles - * not streamed yet, no depth support, a point off screen. Every caller treats - * that as a miss, holding its last value or placing first and patching when - * `batch()` resolves. Cesium answers `now()` synchronously from the scene, - * so nothing changes on screen; a renderer that can only answer from a cache - * or asynchronously plugs in here without touching the callers. + * not streamed yet, no depth support, no renderer, a point off screen. Every + * caller treats that as a miss, holding its last value or placing first and + * patching when `batch()` resolves. `batch()` and `clampBatch()` answer null + * per point they miss, and reject when the query itself fails (a tile + * request error, a destroyed scene), so a caller can tell a failure from + * points that are merely uncovered. * - * `against` picks the surface: `'surface'` is what is drawn (3D tiles and the - * globe), `'terrain'` the loaded terrain tiles alone. `exclude` lists what the - * query must see through, typically the caller's own markers. + * What the renderer cannot answer is a miss: the Cesium renderer answers no + * height, terrain included, without depth textures (its `sampleHeight` + * capability). + * + * `against` picks the surface: `'surface'` is what is drawn (tiles, the + * globe, and draw sets drawn as ground), `'terrain'` the terrain alone, + * `'tiles'` the tiles alone. `exclude` lists draw set ids to see through, of + * those drawn with `includeInHeightQueries`; every other draw set is seen + * through already. */ -import * as Cesium from 'cesium'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { toDegrees } from '../geo/vector.js'; +import { findQuery, rendererOf } from '../render/rendererOf.js'; -/** @typedef {'surface'|'terrain'} HeightSurface */ +/** @typedef {'surface'|'terrain'|'tiles'} HeightSurface */ /** - * A point in degrees, or a `Cesium.Cartographic` in radians. - * @typedef {{lon: number, lat: number}|Cesium.Cartographic} HeightPoint + * A point in degrees, or in radians as `longitude`/`latitude` (a + * cartographic). + * @typedef {{lon: number, lat: number}|{longitude: number, latitude: number}} HeightPoint */ /** * @typedef {object} HeightOptions * @property {HeightSurface} [against] Default `'surface'`. - * @property {object[]} [exclude] Primitives and entities to see through. + * @property {string[]} [exclude] Draw set ids to see through. */ -/** @type {WeakMap} scene -> service */ +/** @type {WeakMap} host -> service */ const services = new WeakMap(); -const scratch = new Cesium.Cartographic(); - /** `supported()` answers, shared so a per-frame check allocates nothing. */ const SUPPORT = [ - [ - Object.freeze({ surface: false, clamp: false }), - Object.freeze({ surface: false, clamp: true }), - ], - [ - Object.freeze({ surface: true, clamp: false }), - Object.freeze({ surface: true, clamp: true }), - ], + Object.freeze({ surface: false, clamp: false }), + Object.freeze({ surface: true, clamp: true }), ]; const NO_OPTIONS = Object.freeze({}); @@ -49,117 +52,135 @@ const NO_OPTIONS = Object.freeze({}); /** Plain finite metres, or null. */ const metres = (height) => (Number.isFinite(height) ? height : null); +/** Finite `x, y, z`. */ +const finite = (p) => + Number.isFinite(p?.x) && Number.isFinite(p?.y) && Number.isFinite(p?.z); + /** - * The point as a Cartographic in radians at height 0. Degrees go through a - * shared scratch unless `result` is given; a Cartographic is used as it is. + * The point in degrees, or null. Degrees go through `result` unless the + * point is already in degrees. * @param {HeightPoint} point - * @param {Cesium.Cartographic} [result] - * @returns {Cesium.Cartographic|null} + * @param {{lon: number, lat: number}} result + * @returns {{lon: number, lat: number}|null} */ -function cartographicOf(point, result = scratch) { - if (Number.isFinite(point?.longitude) && Number.isFinite(point?.latitude)) - return point; +function degreesOf(point, result) { + if (Number.isFinite(point?.longitude) && Number.isFinite(point?.latitude)) { + result.lon = toDegrees(point.longitude); + result.lat = toDegrees(point.latitude); + return result; + } const lon = Number(point?.lon); const lat = Number(point?.lat); if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null; - return Cesium.Cartographic.fromDegrees(lon, lat, 0, result); + if (lon === point.lon && lat === point.lat) return point; + result.lon = lon; + result.lat = lat; + return result; +} + +/** The port's options, with only what the caller gave. */ +function portOptions({ against, exclude } = NO_OPTIONS, extra) { + const options = { ...extra }; + if (against !== undefined) options.against = against; + if (exclude?.length) options.exclude = exclude; + return options; } /** * @typedef {object} HeightService * @property {(point: HeightPoint, options?: HeightOptions) => number|null} now * Height in metres above the ellipsoid from what is loaded, or null. - * @property {(position: Cesium.Cartesian3, options?: {exclude?: object[]}) => Cesium.Cartesian3|null} clampNow - * `position` moved onto the drawn surface along the ellipsoid normal, or null. + * @property {(position: {x: number, y: number, z: number}, options?: {exclude?: string[]}) => {x: number, y: number, z: number}|null} clampNow + * `position` (ECEF) moved onto the drawn surface along the ellipsoid + * normal, or null. * @property {(points: HeightPoint[], options?: HeightOptions) => Promise>} batch - * Heights once the most detailed tiles have streamed; null per miss. A - * failed query (a tile request error, a destroyed scene) rejects, so the - * caller can tell it from points that are merely uncovered. - * @property {(positions: Cesium.Cartesian3[], options?: {exclude?: object[]}) => Promise>} clampBatch + * Heights once the most detailed data has loaded; null per miss. A failed + * query rejects. + * @property {(positions: Array<{x: number, y: number, z: number}>, options?: {exclude?: string[]}) => Promise>} clampBatch * Clamped copies of `positions`; null per miss, rejecting as `batch` does. * @property {() => {surface: boolean, clamp: boolean}} supported - * Whether the drawn surface can be queried at all (Cesium needs depth - * textures); terrain queries are always attempted. + * Whether the drawn surface can be queried at all (the renderer's + * `sampleHeight` capability); a renderer bound to nothing is asked anyway. */ /** - * The scene's height service, made on first use. - * @param {object} scene A Cesium scene (or a test double). + * The height service of the renderer that draws `host` (the scene object + * the caller holds, a viewer), made on first use. The query port is looked + * up on each query, so a renderer bound later answers. + * @param {object} host * @returns {HeightService} */ -export function heightsFor(scene) { - let service = services.get(scene); +export function heightsOf(host) { + let service = services.get(host); if (!service) { - service = createHeights(scene); - services.set(scene, service); + service = createHeights(host); + services.set(host, service); } return service; } -function createHeights(scene) { - const terrainProvider = () => - scene.terrainProvider ?? scene.globe?.terrainProvider; +function createHeights(host) { + const query = () => findQuery(host); + /** The port for an asynchronous query: a destroyed scene fails it. */ + const asyncQuery = () => { + if (host?.isDestroyed?.()) throw new Error('This scene has been destroyed'); + return query(); + }; + const scratch = { lon: 0, lat: 0 }; - return { - now(point, { against = 'surface', exclude } = NO_OPTIONS) { - const carto = cartographicOf(point); - if (!carto) return null; + const service = { + now(point, options = NO_OPTIONS) { + const port = query(); + const at = degreesOf(point, scratch); + if (!port || !at) return null; try { - if (against === 'terrain') - return metres(scene.globe?.getHeight?.(carto)); - // Cesium throws without depth-texture support: that is a miss. - return metres(scene.sampleHeight?.(carto, exclude)); + return metres(port.sampleHeightNow(at, portOptions(options))); } catch { return null; } }, clampNow(position, { exclude } = NO_OPTIONS) { - if (!position) return null; - try { - return scene.clampToHeight?.(position, exclude) ?? null; - } catch { - return null; - } + const at = finite(position) ? toLonLatH(position) : null; + if (!at) return null; + const { lon, lat } = at; + const height = service.now({ lon, lat }, { exclude }); + return height === null ? null : fromDegrees(lon, lat, height); }, - async batch(points, { against = 'surface', exclude } = NO_OPTIONS) { - const cartos = points.map((point) => { - const carto = cartographicOf(point, new Cesium.Cartographic()); - return ( - carto && new Cesium.Cartographic(carto.longitude, carto.latitude) - ); + async batch(points, options = NO_OPTIONS) { + const at = points.map((point) => { + const degrees = degreesOf(point, { lon: 0, lat: 0 }); + return degrees && { lon: degrees.lon, lat: degrees.lat }; }); - const valid = cartos.filter(Boolean); - if (!valid.length) return cartos.map(() => null); - if (against === 'terrain') { - const provider = terrainProvider(); - if (!provider) return cartos.map(() => null); - // An ellipsoid has no tiles to sample (Cesium throws for want of - // their availability): its terrain is the ellipsoid, height 0. - if (provider instanceof Cesium.EllipsoidTerrainProvider) - return cartos.map((carto) => (carto ? 0 : null)); - await Cesium.sampleTerrainMostDetailed(provider, valid); - } else { - if (typeof scene.sampleHeightMostDetailed !== 'function') - return cartos.map(() => null); - await scene.sampleHeightMostDetailed(valid, exclude); - } - return cartos.map((carto) => (carto ? metres(carto.height) : null)); + const valid = at.filter(Boolean); + const port = asyncQuery(); + if (!valid.length || !port) return at.map(() => null); + const samples = await port.sampleHeight( + valid, + portOptions(options, { mostDetailed: true }), + ); + let next = 0; + return at.map((point) => + point ? metres(samples[next++]?.height) : null, + ); }, async clampBatch(positions, { exclude } = NO_OPTIONS) { - if (typeof scene.clampToHeightMostDetailed !== 'function') - return positions.map(() => null); - const clones = positions.map((p) => Cesium.Cartesian3.clone(p)); - const clamped = await scene.clampToHeightMostDetailed(clones, exclude); - return clamped.map((p) => p ?? null); + const port = asyncQuery(); + if (!port) return positions.map(() => null); + const clamped = await port.clampToSurface( + positions.map((p) => ({ x: p.x, y: p.y, z: p.z })), + portOptions({ exclude }), + ); + return clamped.map((p) => (finite(p) ? p : null)); }, supported() { - return SUPPORT[+(scene.sampleHeightSupported === true)][ - +(scene.clampToHeightSupported === true) - ]; + const capabilities = rendererOf(host)?.capabilities; + if (!capabilities) return SUPPORT[+Boolean(query())]; + return SUPPORT[+capabilities.has('sampleHeight')]; }, }; + return service; } diff --git a/src/queries/heights.test.mjs b/src/queries/heights.test.mjs index b0da5eddc..91d3e3f88 100644 --- a/src/queries/heights.test.mjs +++ b/src/queries/heights.test.mjs @@ -3,8 +3,9 @@ import assert from 'node:assert/strict'; import fs from 'node:fs'; import path from 'node:path'; import { fileURLToPath } from 'node:url'; -import * as Cesium from 'cesium'; -import { heightsFor } from './heights.js'; +import { fromDegrees, toLonLatH } from '../geo/ellipsoid.js'; +import { bindRenderer } from '../render/rendererOf.js'; +import { heightsOf } from './heights.js'; const ROOT = path.resolve( path.dirname(fileURLToPath(import.meta.url)), @@ -14,194 +15,200 @@ const ROOT = path.resolve( const AUSTIN = { lon: -97.74, lat: 30.27 }; -function scene(overrides = {}) { +/** + * A viewer double with a fake renderer whose query port answers `height` (a + * number, or a function of the point and options) and records each call. + */ +function bound({ + height = 150, + capabilities = ['sampleHeight'], + ...query +} = {}) { const calls = []; - return { - calls, - sampleHeightSupported: true, - clampToHeightSupported: true, - sampleHeight(carto, exclude) { - calls.push(['sampleHeight', carto, exclude]); - return 150; + const viewer = {}; + const answer = (point, options) => + typeof height === 'function' ? height(point, options) : height; + const port = { + sampleHeightNow(point, options) { + calls.push(['now', { ...point }, options]); + return answer(point, options); }, - clampToHeight(position, exclude) { - calls.push(['clampToHeight', position, exclude]); - return Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 150); + async sampleHeight(points, options) { + calls.push(['sample', points, options]); + return points.map((point) => { + const h = answer(point, options); + return h === null + ? null + : { height: h, confidence: 1, source: 'tiles', lod: 'finest' }; + }); }, - globe: { getHeight: () => 140 }, - ...overrides, + async clampToSurface(positions, options) { + calls.push(['clamp', positions, options]); + return positions.map((p) => { + const { lon, lat } = toLonLatH(p); + const h = answer({ lon, lat }, options); + return h === null ? null : fromDegrees(lon, lat, h); + }); + }, + ...query, }; + bindRenderer(viewer, { query: port, capabilities: new Set(capabilities) }); + return { viewer, calls, port }; } -test('now reads the drawn surface, seeing through what the caller excludes', () => { - const s = scene(); - const own = [{ name: 'own marker' }]; - assert.equal(heightsFor(s).now(AUSTIN, { exclude: own }), 150); - const [[, carto, exclude]] = s.calls; - assert.ok( - Math.abs(Cesium.Math.toDegrees(carto.longitude) - AUSTIN.lon) < 1e-9, - ); - assert.equal(exclude, own); +const near = (a, b, eps = 1e-6) => Math.abs(a - b) < eps; + +test('now asks the query port, seeing through the sets the caller excludes', () => { + const { viewer, calls } = bound(); + assert.equal(heightsOf(viewer).now(AUSTIN, { exclude: ['own:1'] }), 150); + assert.deepEqual(calls, [['now', AUSTIN, { exclude: ['own:1'] }]]); }); -test('now takes a Cartographic as it is', () => { - const s = scene(); - const carto = Cesium.Cartographic.fromDegrees(AUSTIN.lon, AUSTIN.lat); - heightsFor(s).now(carto); - assert.equal(s.calls[0][1], carto); +test('now takes radians as a cartographic gives them', () => { + const { viewer, calls } = bound(); + heightsOf(viewer).now({ + longitude: (AUSTIN.lon * Math.PI) / 180, + latitude: (AUSTIN.lat * Math.PI) / 180, + }); + const [[, point, options]] = calls; + assert.ok(near(point.lon, AUSTIN.lon) && near(point.lat, AUSTIN.lat)); + assert.deepEqual(options, {}); }); test('a miss is null, whatever form it takes', () => { - for (const sampleHeight of [ + for (const height of [ + null, () => undefined, - () => Number.NaN, + Number.NaN, () => { - throw new Error('depth textures unsupported'); + throw new Error('lost context'); }, ]) { - assert.equal(heightsFor(scene({ sampleHeight })).now(AUSTIN), null); + const { viewer } = bound({ height }); + assert.equal(heightsOf(viewer).now(AUSTIN), null); } - assert.equal( - heightsFor(scene({ sampleHeight: undefined })).now(AUSTIN), - null, - ); - assert.equal(heightsFor(scene()).now({ lon: 'x', lat: 1 }), null); + const { viewer, calls } = bound(); + assert.equal(heightsOf(viewer).now({ lon: 'x', lat: 1 }), null); + assert.equal(calls.length, 0, 'a bad point is not asked'); + assert.equal(heightsOf({}).now(AUSTIN), null, 'no renderer, no height'); }); -test('terrain reads the loaded terrain tiles only', () => { - const s = scene(); - assert.equal(heightsFor(s).now(AUSTIN, { against: 'terrain' }), 140); - assert.equal(s.calls.length, 0, 'the drawn surface is not sampled'); - assert.equal( - heightsFor(scene({ globe: undefined })).now(AUSTIN, { against: 'terrain' }), - null, - ); +test('against picks the surface the port samples', () => { + const { viewer, calls } = bound({ + height: (_, { against }) => (against === 'terrain' ? 140 : 150), + }); + assert.equal(heightsOf(viewer).now(AUSTIN, { against: 'terrain' }), 140); + assert.deepEqual(calls[0][2], { against: 'terrain' }); }); test('clampNow moves a position onto the surface, or misses with null', () => { - const s = scene(); - const own = [{}]; - const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); - const clamped = heightsFor(s).clampNow(position, { exclude: own }); - assert.ok( - Math.abs(Cesium.Cartographic.fromCartesian(clamped).height - 150) < 1e-6, - ); - assert.equal(s.calls[0][2], own); + const { viewer, calls } = bound(); + const position = fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); + const clamped = heightsOf(viewer).clampNow(position, { exclude: ['own:1'] }); + const at = toLonLatH(clamped); + assert.ok(near(at.height, 150) && near(at.lon, AUSTIN.lon, 1e-9)); + assert.deepEqual(calls[0][2], { exclude: ['own:1'] }); assert.equal( - heightsFor(scene({ clampToHeight: () => undefined })).clampNow(position), + heightsOf(bound({ height: null }).viewer).clampNow(position), null, ); + assert.equal(heightsOf(viewer).clampNow({ x: Number.NaN, y: 0, z: 0 }), null); + assert.equal(heightsOf(viewer).clampNow({ x: 0, y: 0, z: 0 }), null); }); -test('batch answers each point once the tiles stream, null per miss', async () => { - let seen; - const s = scene({ - async sampleHeightMostDetailed(cartos, exclude) { - seen = exclude; - cartos.forEach((c, i) => (c.height = i === 1 ? undefined : 100 + i)); - return cartos; - }, +test('batch asks for the finest heights, null per miss and per bad point', async () => { + const { viewer, calls } = bound({ + height: (point) => (point.lon === 0 ? null : 100), }); - const own = [{}]; - const heights = await heightsFor(s).batch( + const heights = await heightsOf(viewer).batch( [ AUSTIN, { lon: 0, lat: 0 }, - Cesium.Cartographic.fromDegrees(1, 1, 999), { lon: 'bad' }, + { longitude: 0.1, latitude: 0.1 }, ], - { exclude: own }, + { exclude: ['own:1'] }, ); - assert.deepEqual(heights, [100, null, 102, null]); - assert.equal(seen, own); + assert.deepEqual(heights, [100, null, null, 100]); + const [[, points, options]] = calls; + assert.equal(points.length, 3, 'only valid points are asked'); + assert.deepEqual(options, { exclude: ['own:1'], mostDetailed: true }); }); -test('batch leaves the caller’s Cartographics alone', async () => { - const s = scene({ - async sampleHeightMostDetailed(cartos) { - cartos.forEach((c) => (c.height = 5)); - return cartos; - }, - }); - const carto = Cesium.Cartographic.fromDegrees(1, 1, 999); - await heightsFor(s).batch([carto]); - assert.equal(carto.height, 999); -}); - -test('terrain on an ellipsoid is height 0, without sampling tiles', async () => { - const s = scene({ terrainProvider: new Cesium.EllipsoidTerrainProvider() }); - assert.deepEqual( - await heightsFor(s).batch([AUSTIN, { lon: 'x', lat: 1 }], { - against: 'terrain', - }), - [0, null], - ); -}); - -test('batch misses everything when the scene cannot stream, and rejects when it fails', async () => { - assert.deepEqual(await heightsFor(scene()).batch([AUSTIN]), [null]); - const failing = scene({ - sampleHeightMostDetailed: async () => { +test('batch misses everything without a renderer, and rejects when the query fails', async () => { + assert.deepEqual(await heightsOf({}).batch([AUSTIN]), [null]); + assert.deepEqual(await heightsOf({}).clampBatch([{ x: 1, y: 0, z: 0 }]), [ + null, + ]); + const { viewer } = bound({ + sampleHeight: async () => { throw new Error('scene destroyed'); }, - clampToHeightMostDetailed: async () => { + clampToSurface: async () => { throw new Error('scene destroyed'); }, }); - await assert.rejects(heightsFor(failing).batch([AUSTIN]), /destroyed/); + await assert.rejects(heightsOf(viewer).batch([AUSTIN]), /destroyed/); await assert.rejects( - heightsFor(failing).clampBatch([Cesium.Cartesian3.UNIT_X]), + heightsOf(viewer).clampBatch([{ x: 1, y: 0, z: 0 }]), /destroyed/, ); - assert.deepEqual( - await heightsFor(scene()).batch([AUSTIN], { against: 'terrain' }), - [null], - 'no terrain provider, no terrain heights', +}); + +test('a destroyed scene fails the asynchronous queries', async () => { + const viewer = { isDestroyed: () => true }; + await assert.rejects(heightsOf(viewer).batch([AUSTIN]), /destroyed/); + await assert.rejects( + heightsOf(viewer).clampBatch([{ x: 1, y: 0, z: 0 }]), + /destroyed/, ); + assert.equal(heightsOf(viewer).now(AUSTIN), null); }); test('clampBatch clamps copies and misses per position', async () => { - const s = scene({ - async clampToHeightMostDetailed(positions) { - return positions.map((p, i) => (i === 0 ? p : undefined)); - }, + const { viewer, calls } = bound({ + height: (point) => (point.lon > 0 ? null : 150), }); - const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); - const [first, second] = await heightsFor(s).clampBatch([position, position]); - assert.notEqual(first, position, 'the caller’s position is not mutated'); + const position = fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); + const [first, second] = await heightsOf(viewer).clampBatch([ + position, + fromDegrees(10, 10, 0), + ]); + assert.ok(near(toLonLatH(first).height, 150)); assert.equal(second, null); -}); - -test('supported reports whether the drawn surface can be queried', () => { - assert.deepEqual(heightsFor(scene()).supported(), { - surface: true, - clamp: true, - }); - assert.deepEqual( - heightsFor( - scene({ - sampleHeightSupported: false, - clampToHeightSupported: undefined, - }), - ).supported(), - { surface: false, clamp: false }, + assert.notEqual( + calls[0][1][0], + position, + 'the caller’s position is not passed on', ); }); -test('supported answers without allocating', () => { - const s = scene(); - assert.equal(heightsFor(s).supported(), heightsFor(s).supported()); +test('supported reports the renderer’s sampleHeight capability', () => { + assert.deepEqual(heightsOf(bound().viewer).supported(), { + surface: true, + clamp: true, + }); + assert.deepEqual(heightsOf(bound({ capabilities: [] }).viewer).supported(), { + surface: false, + clamp: false, + }); + assert.deepEqual(heightsOf({}).supported(), { surface: false, clamp: false }); }); -test('one service per scene', () => { - const s = scene(); - assert.equal(heightsFor(s), heightsFor(s)); - assert.notEqual(heightsFor(s), heightsFor(scene())); +test('supported answers without allocating', () => { + const { viewer } = bound(); + assert.equal(heightsOf(viewer).supported(), heightsOf(viewer).supported()); +}); + +test('one service per host', () => { + const { viewer } = bound(); + assert.equal(heightsOf(viewer), heightsOf(viewer)); + assert.notEqual(heightsOf(viewer), heightsOf(bound().viewer)); }); test('height queries go through the service', () => { - // A renderer that answers heights from a cache or asynchronously plugs in - // at src/queries/heights.js; a site that asks Cesium directly bypasses it. + // The app asks the query port through src/queries/heights.js; a site that + // asks the port's height members itself, or Cesium directly, bypasses it. const SERVICE = 'src/queries/heights.js'; // The renderer contract's own height members, and the renderer, stub and suite // that implement and call them: the Cesium adapter answers them through diff --git a/src/render/cesium/heights.js b/src/render/cesium/heights.js new file mode 100644 index 000000000..3973b5bd2 --- /dev/null +++ b/src/render/cesium/heights.js @@ -0,0 +1,166 @@ +/** + * @module render/cesium/heights + * @description The Cesium scene's height service: how high the rendered + * surface or the terrain is under a point, now or after streaming. The + * Cesium query port answers its height members through it; code that + * is still bound to the Cesium scene asks it directly, and code off + * Cesium asks the query port (`src/queries/heights.js`). + * + * `now()` answers from what is already loaded and may return `null`: tiles + * not streamed yet, no depth support, a point off screen. Every caller treats + * that as a miss, holding its last value or placing first and patching when + * `batch()` resolves. + * + * `against` picks the surface: `'surface'` is what is drawn (3D tiles and the + * globe), `'terrain'` the loaded terrain tiles alone. `exclude` lists what the + * query must see through, typically the caller's own markers. + */ +import * as Cesium from 'cesium'; + +/** @typedef {'surface'|'terrain'} HeightSurface */ +/** + * A point in degrees, or a `Cesium.Cartographic` in radians. + * @typedef {{lon: number, lat: number}|Cesium.Cartographic} HeightPoint + */ +/** + * @typedef {object} HeightOptions + * @property {HeightSurface} [against] Default `'surface'`. + * @property {object[]} [exclude] Primitives and entities to see through. + */ + +/** @type {WeakMap} scene -> service */ +const services = new WeakMap(); + +const scratch = new Cesium.Cartographic(); + +/** `supported()` answers, shared so a per-frame check allocates nothing. */ +const SUPPORT = [ + [ + Object.freeze({ surface: false, clamp: false }), + Object.freeze({ surface: false, clamp: true }), + ], + [ + Object.freeze({ surface: true, clamp: false }), + Object.freeze({ surface: true, clamp: true }), + ], +]; + +const NO_OPTIONS = Object.freeze({}); + +/** Plain finite metres, or null. */ +const metres = (height) => (Number.isFinite(height) ? height : null); + +/** + * The point as a Cartographic in radians at height 0. Degrees go through a + * shared scratch unless `result` is given; a Cartographic is used as it is. + * @param {HeightPoint} point + * @param {Cesium.Cartographic} [result] + * @returns {Cesium.Cartographic|null} + */ +function cartographicOf(point, result = scratch) { + if (Number.isFinite(point?.longitude) && Number.isFinite(point?.latitude)) + return point; + const lon = Number(point?.lon); + const lat = Number(point?.lat); + if (!Number.isFinite(lon) || !Number.isFinite(lat)) return null; + return Cesium.Cartographic.fromDegrees(lon, lat, 0, result); +} + +/** + * @typedef {object} HeightService + * @property {(point: HeightPoint, options?: HeightOptions) => number|null} now + * Height in metres above the ellipsoid from what is loaded, or null. + * @property {(position: Cesium.Cartesian3, options?: {exclude?: object[]}) => Cesium.Cartesian3|null} clampNow + * `position` moved onto the drawn surface along the ellipsoid normal, or null. + * @property {(points: HeightPoint[], options?: HeightOptions) => Promise>} batch + * Heights once the most detailed tiles have streamed; null per miss. A + * failed query (a tile request error, a destroyed scene) rejects, so the + * caller can tell it from points that are merely uncovered. + * @property {(positions: Cesium.Cartesian3[], options?: {exclude?: object[]}) => Promise>} clampBatch + * Clamped copies of `positions`; null per miss, rejecting as `batch` does. + * @property {() => {surface: boolean, clamp: boolean}} supported + * Whether the drawn surface can be queried at all (Cesium needs depth + * textures); terrain queries are always attempted. + */ + +/** + * The scene's height service, made on first use. + * @param {object} scene A Cesium scene (or a test double). + * @returns {HeightService} + */ +export function heightsFor(scene) { + let service = services.get(scene); + if (!service) { + service = createHeights(scene); + services.set(scene, service); + } + return service; +} + +function createHeights(scene) { + const terrainProvider = () => + scene.terrainProvider ?? scene.globe?.terrainProvider; + + return { + now(point, { against = 'surface', exclude } = NO_OPTIONS) { + const carto = cartographicOf(point); + if (!carto) return null; + try { + if (against === 'terrain') + return metres(scene.globe?.getHeight?.(carto)); + // Cesium throws without depth-texture support: that is a miss. + return metres(scene.sampleHeight?.(carto, exclude)); + } catch { + return null; + } + }, + + clampNow(position, { exclude } = NO_OPTIONS) { + if (!position) return null; + try { + return scene.clampToHeight?.(position, exclude) ?? null; + } catch { + return null; + } + }, + + async batch(points, { against = 'surface', exclude } = NO_OPTIONS) { + const cartos = points.map((point) => { + const carto = cartographicOf(point, new Cesium.Cartographic()); + return ( + carto && new Cesium.Cartographic(carto.longitude, carto.latitude) + ); + }); + const valid = cartos.filter(Boolean); + if (!valid.length) return cartos.map(() => null); + if (against === 'terrain') { + const provider = terrainProvider(); + if (!provider) return cartos.map(() => null); + // An ellipsoid has no tiles to sample (Cesium throws for want of + // their availability): its terrain is the ellipsoid, height 0. + if (provider instanceof Cesium.EllipsoidTerrainProvider) + return cartos.map((carto) => (carto ? 0 : null)); + await Cesium.sampleTerrainMostDetailed(provider, valid); + } else { + if (typeof scene.sampleHeightMostDetailed !== 'function') + return cartos.map(() => null); + await scene.sampleHeightMostDetailed(valid, exclude); + } + return cartos.map((carto) => (carto ? metres(carto.height) : null)); + }, + + async clampBatch(positions, { exclude } = NO_OPTIONS) { + if (typeof scene.clampToHeightMostDetailed !== 'function') + return positions.map(() => null); + const clones = positions.map((p) => Cesium.Cartesian3.clone(p)); + const clamped = await scene.clampToHeightMostDetailed(clones, exclude); + return clamped.map((p) => p ?? null); + }, + + supported() { + return SUPPORT[+(scene.sampleHeightSupported === true)][ + +(scene.clampToHeightSupported === true) + ]; + }, + }; +} diff --git a/src/render/cesium/heights.test.mjs b/src/render/cesium/heights.test.mjs new file mode 100644 index 000000000..6b8f0de20 --- /dev/null +++ b/src/render/cesium/heights.test.mjs @@ -0,0 +1,191 @@ +import { test } from 'node:test'; +import assert from 'node:assert/strict'; +import * as Cesium from 'cesium'; +import { heightsFor } from './heights.js'; + +const AUSTIN = { lon: -97.74, lat: 30.27 }; + +function scene(overrides = {}) { + const calls = []; + return { + calls, + sampleHeightSupported: true, + clampToHeightSupported: true, + sampleHeight(carto, exclude) { + calls.push(['sampleHeight', carto, exclude]); + return 150; + }, + clampToHeight(position, exclude) { + calls.push(['clampToHeight', position, exclude]); + return Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 150); + }, + globe: { getHeight: () => 140 }, + ...overrides, + }; +} + +test('now reads the drawn surface, seeing through what the caller excludes', () => { + const s = scene(); + const own = [{ name: 'own marker' }]; + assert.equal(heightsFor(s).now(AUSTIN, { exclude: own }), 150); + const [[, carto, exclude]] = s.calls; + assert.ok( + Math.abs(Cesium.Math.toDegrees(carto.longitude) - AUSTIN.lon) < 1e-9, + ); + assert.equal(exclude, own); +}); + +test('now takes a Cartographic as it is', () => { + const s = scene(); + const carto = Cesium.Cartographic.fromDegrees(AUSTIN.lon, AUSTIN.lat); + heightsFor(s).now(carto); + assert.equal(s.calls[0][1], carto); +}); + +test('a miss is null, whatever form it takes', () => { + for (const sampleHeight of [ + () => undefined, + () => Number.NaN, + () => { + throw new Error('depth textures unsupported'); + }, + ]) { + assert.equal(heightsFor(scene({ sampleHeight })).now(AUSTIN), null); + } + assert.equal( + heightsFor(scene({ sampleHeight: undefined })).now(AUSTIN), + null, + ); + assert.equal(heightsFor(scene()).now({ lon: 'x', lat: 1 }), null); +}); + +test('terrain reads the loaded terrain tiles only', () => { + const s = scene(); + assert.equal(heightsFor(s).now(AUSTIN, { against: 'terrain' }), 140); + assert.equal(s.calls.length, 0, 'the drawn surface is not sampled'); + assert.equal( + heightsFor(scene({ globe: undefined })).now(AUSTIN, { against: 'terrain' }), + null, + ); +}); + +test('clampNow moves a position onto the surface, or misses with null', () => { + const s = scene(); + const own = [{}]; + const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); + const clamped = heightsFor(s).clampNow(position, { exclude: own }); + assert.ok( + Math.abs(Cesium.Cartographic.fromCartesian(clamped).height - 150) < 1e-6, + ); + assert.equal(s.calls[0][2], own); + assert.equal( + heightsFor(scene({ clampToHeight: () => undefined })).clampNow(position), + null, + ); +}); + +test('batch answers each point once the tiles stream, null per miss', async () => { + let seen; + const s = scene({ + async sampleHeightMostDetailed(cartos, exclude) { + seen = exclude; + cartos.forEach((c, i) => (c.height = i === 1 ? undefined : 100 + i)); + return cartos; + }, + }); + const own = [{}]; + const heights = await heightsFor(s).batch( + [ + AUSTIN, + { lon: 0, lat: 0 }, + Cesium.Cartographic.fromDegrees(1, 1, 999), + { lon: 'bad' }, + ], + { exclude: own }, + ); + assert.deepEqual(heights, [100, null, 102, null]); + assert.equal(seen, own); +}); + +test('batch leaves the caller’s Cartographics alone', async () => { + const s = scene({ + async sampleHeightMostDetailed(cartos) { + cartos.forEach((c) => (c.height = 5)); + return cartos; + }, + }); + const carto = Cesium.Cartographic.fromDegrees(1, 1, 999); + await heightsFor(s).batch([carto]); + assert.equal(carto.height, 999); +}); + +test('terrain on an ellipsoid is height 0, without sampling tiles', async () => { + const s = scene({ terrainProvider: new Cesium.EllipsoidTerrainProvider() }); + assert.deepEqual( + await heightsFor(s).batch([AUSTIN, { lon: 'x', lat: 1 }], { + against: 'terrain', + }), + [0, null], + ); +}); + +test('batch misses everything when the scene cannot stream, and rejects when it fails', async () => { + assert.deepEqual(await heightsFor(scene()).batch([AUSTIN]), [null]); + const failing = scene({ + sampleHeightMostDetailed: async () => { + throw new Error('scene destroyed'); + }, + clampToHeightMostDetailed: async () => { + throw new Error('scene destroyed'); + }, + }); + await assert.rejects(heightsFor(failing).batch([AUSTIN]), /destroyed/); + await assert.rejects( + heightsFor(failing).clampBatch([Cesium.Cartesian3.UNIT_X]), + /destroyed/, + ); + assert.deepEqual( + await heightsFor(scene()).batch([AUSTIN], { against: 'terrain' }), + [null], + 'no terrain provider, no terrain heights', + ); +}); + +test('clampBatch clamps copies and misses per position', async () => { + const s = scene({ + async clampToHeightMostDetailed(positions) { + return positions.map((p, i) => (i === 0 ? p : undefined)); + }, + }); + const position = Cesium.Cartesian3.fromDegrees(AUSTIN.lon, AUSTIN.lat, 0); + const [first, second] = await heightsFor(s).clampBatch([position, position]); + assert.notEqual(first, position, 'the caller’s position is not mutated'); + assert.equal(second, null); +}); + +test('supported reports whether the drawn surface can be queried', () => { + assert.deepEqual(heightsFor(scene()).supported(), { + surface: true, + clamp: true, + }); + assert.deepEqual( + heightsFor( + scene({ + sampleHeightSupported: false, + clampToHeightSupported: undefined, + }), + ).supported(), + { surface: false, clamp: false }, + ); +}); + +test('supported answers without allocating', () => { + const s = scene(); + assert.equal(heightsFor(s).supported(), heightsFor(s).supported()); +}); + +test('one service per scene', () => { + const s = scene(); + assert.equal(heightsFor(s), heightsFor(s)); + assert.notEqual(heightsFor(s), heightsFor(scene())); +}); diff --git a/src/render/cesium/query.js b/src/render/cesium/query.js index 166f390a7..9f6c45d4d 100644 --- a/src/render/cesium/query.js +++ b/src/render/cesium/query.js @@ -12,7 +12,7 @@ * own sets. */ import * as Cesium from 'cesium'; -import { heightsFor } from '../../queries/heights.js'; +import { heightsFor } from './heights.js'; import { findDraw, provideUnboundQuery } from '../rendererOf.js'; import { toCartesian } from './common.js'; import { unboundDrawPart } from './draw.js'; diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 9f28bc44f..fc8133161 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -91,7 +91,6 @@ "src/maps/imagery.js", "src/maps/terrain.js", "src/overlays/worldOverlay.js", - "src/queries/heights.js", "src/sceneCommandRelease.js", "src/scenes/dataPacks/geometry.js", "src/scenes/dataPacks/presentation.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index de91569b9..60d29df85 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -84,6 +84,7 @@ const DRAW_FROM_CALLER = new Set([ './layers/street-level/kartaview', './layers/street-level/panoramax', './layers/air-quality', + './queries/heights', ]); /** diff --git a/src/services/groundSnap.js b/src/services/groundSnap.js index ba63322fb..4f97463dd 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -47,7 +47,7 @@ */ import * as Cesium from 'cesium'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; /** Taxi threshold: a cached snap answers directly for moves up to this far from * the sampled spot (m). Past it the value is demoted to a held last-known and a diff --git a/src/services/meshFloorSampler.js b/src/services/meshFloorSampler.js index 69e5db4f8..045d22d20 100644 --- a/src/services/meshFloorSampler.js +++ b/src/services/meshFloorSampler.js @@ -1,6 +1,6 @@ import * as Cesium from 'cesium'; import { approxDistanceKm } from '../data/approxDistance.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; /** Construct an instance-owned meshFloorSampler service with explicit dependencies. */ export function createMeshFloorSampler({ diff --git a/src/testSupport/fakeCesiumScene.mjs b/src/testSupport/fakeCesiumScene.mjs index f0ab932f3..a2ddb2676 100644 --- a/src/testSupport/fakeCesiumScene.mjs +++ b/src/testSupport/fakeCesiumScene.mjs @@ -20,7 +20,7 @@ */ import * as Cesium from 'cesium'; import { bindRenderer } from '../render/rendererOf.js'; -import { heightsFor } from '../queries/heights.js'; +import { heightsFor } from '../render/cesium/heights.js'; import { fakeDrawPort } from './fakeDrawPort.mjs'; const toCartesian = (p) => new Cesium.Cartesian3(p.x, p.y, p.z);