diff --git a/CHANGELOG.md b/CHANGELOG.md index 076ca2a14..6d27f317a 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,13 @@ `event.native` (and `event.pick` and `event.pickWindow`). A viewer of your own with no renderer bound needs `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- `gods-eye-view/application/operations` no longer reaches Cesium: ground + snapping and mesh floor sampling ask the renderer's globe, camera and query + ports, and see through the caller's draw sets by id (the raw + `excludeObjects` option and exclusion callbacks are gone). A viewer of your + own with no renderer bound needs `gods-eye-view/render/cesium/unbound` + loaded once first, or location framing throws and snaps answer nothing + (samehkhamis). ## [0.3.0] — 2026-10-27 — Street Level, On Your Phone, in Your Language diff --git a/docs/CODE-BOUNDARIES.md b/docs/CODE-BOUNDARIES.md index 7e95f7203..3e4378fe2 100644 --- a/docs/CODE-BOUNDARIES.md +++ b/docs/CODE-BOUNDARIES.md @@ -569,6 +569,13 @@ separate from standalone setup. Scene construction returns these operations; the catalog and controls use the same surface owner. Layers still own their individual ground-snap caches and model resources. +The entry is Cesium-free: ground snapping and mesh floor sampling ask the +renderer's globe (`isSettled`), camera (`pose`) and query (heights) ports, and +see through the caller's draw sets by id. A viewer with no renderer bound needs +the Cesium adapter's factories loaded (`gods-eye-view/render/cesium/unbound`) +first; until then the snap and the sampler answer nothing and location framing +throws, naming that export. + Terrain cancellation rejects late replies before caching, clears floor queues and removes the map-stack listener. Annotation lookup caches are instance-owned and cleared on cancellation. Geometry selection and floor policies are unchanged. diff --git a/docs/CURRENT-STATE.md b/docs/CURRENT-STATE.md index 3f9c5a881..2737c0d71 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1148,6 +1148,16 @@ Red Line trains on the Longfellow Bridge 6–9 m under the deck. Residual: the probe is vertical, so a vehicle directly under a deck or a roof overhang reads the structure above it. +The sampler and the aircraft ground snap (`src/services/groundSnap.js`) reach +the renderer only through its ports: the camera's `pose()` for the probe +height gate, the globe's `isGlobeVisible()` (the sampler runs only with +the globe hidden) and `isSettled('surface')` (sampler) and +`isSettled('tiles')` with `isSettled('surface')` (snap) for whether the tiles +have streamed, and the query +port's heights, seeing through the caller's draw sets by id. Cockpit's ground +probe names the tracked contact's icon and model sets, which the flights and +military layers keep on its entity record (`groundSets`). + ## Vessel components and sources `src/data/aisLiveVessels.js` assembles `createVesselLayer` from the diff --git a/src/data/entityRecords.js b/src/data/entityRecords.js index 7c49c7e10..1f2c14a31 100644 --- a/src/data/entityRecords.js +++ b/src/data/entityRecords.js @@ -14,6 +14,8 @@ * - `selectionOrigin`: what started the selection (`'user'`, …). * - `sprite`: a tracked billboard's pushed `{ width, height, scale, scaleByDistance }`, for * the close-range camera guard and the screen annotations' tracked footprint. + * - `groundSets()`: the draw set ids a height sample under the contact sees through (its own + * icons and models), for Cockpit's ground probe. * * A layer's private per-entity state goes in its own store ({@link createEntityStore}). */ diff --git a/src/data/flights.test.mjs b/src/data/flights.test.mjs index 4b09b0761..e9a2428d3 100644 --- a/src/data/flights.test.mjs +++ b/src/data/flights.test.mjs @@ -526,6 +526,10 @@ test('real civil track path creates no native label and publishes every cached h ); assert.ok(entity.position, 'Cockpit sees a contact it can fly'); assert.equal(readEntityRecord(entity).drawn(), true); + assert.ok( + Array.isArray(readEntityRecord(entity).groundSets()), + 'Cockpit asks which draw sets its ground probe sees through', + ); assert.equal(entity.show, true); assert.equal(entity.label, undefined); assert.ok( diff --git a/src/data/meshFloorSampler.test.mjs b/src/data/meshFloorSampler.test.mjs index b15c7f782..666122b06 100644 --- a/src/data/meshFloorSampler.test.mjs +++ b/src/data/meshFloorSampler.test.mjs @@ -4,7 +4,7 @@ // The sampler's acceptance rule was previously covered only through // `reportValidatedMeshFloorCell` directly, which proves the gate but not the // decision that feeds it. These tests call `sampleMeshFloorCells` with a fake -// scene whose `sampleHeight` returns exactly what Cesium can return — a number, +// renderer whose height query returns what a renderer can return — a number, // `undefined`, NaN, or a throw — and assert that a cell latches if and only if // a REAL DEM prior exists and the sample fits its window. // @@ -47,20 +47,35 @@ async function seedDem(cell, ellipsoid) { } } -/** A scene the sampler accepts: low camera, one visible tileset reporting - * tilesLoaded, and a `sampleHeight` under the test's control. */ -function fakeScene(sampleHeight, { cameraHeightM = 900, tilesLoaded = true, show = true } = {}) { - // instanceof-compatible without running Cesium's constructor; `tilesLoaded` is - // a prototype getter, so it has to be shadowed with an own data property. - const tileset = Object.create(Cesium.Cesium3DTileset.prototype); - Object.defineProperty(tileset, 'tilesLoaded', { value: tilesLoaded, configurable: true }); - Object.defineProperty(tileset, 'show', { value: show, configurable: true }); - return { - sampleHeightSupported: true, - sampleHeight, - camera: { positionCartographic: { height: cameraHeightM } }, - primitives: { length: 1, get: () => tileset }, - }; +/** A viewer the sampler accepts: bound to a renderer with a low camera, + * drawn tiles that have settled, and heights under the test's control + * (`sampleHeight` is handed the point in radians, as a cartographic). + * Clearing `sampleHeightSupported` takes the renderer's `sampleHeight` + * capability away; `asked` records each probe. */ +function fakeScene( + sampleHeight, + { cameraHeightM = 900, tilesLoaded = true, show = true, globeShown = false } = {}, +) { + const viewer = { sampleHeightSupported: true, asked: [] }; + bindRenderer(viewer, { + capabilities: { has: (name) => name === 'sampleHeight' && viewer.sampleHeightSupported }, + camera: { pose: () => ({ lon: 0, lat: 0, height: cameraHeightM }) }, + globe: { + isGlobeVisible: () => globeShown, + // The globe's terrain while it is shown, else the drawn tiles. + isSettled: (kind) => kind !== 'surface' || (globeShown || (show && tilesLoaded)), + }, + query: { + sampleHeightNow(point, options) { + viewer.asked.push({ point: { ...point }, options }); + return sampleHeight({ + longitude: Cesium.Math.toRadians(point.lon), + latitude: Cesium.Math.toRadians(point.lat), + }); + }, + }, + }); + return viewer; } function reset() { @@ -117,6 +132,10 @@ test('sampler: a high camera or unloaded tiles produce no records at all', async assert.equal(cachedMeshFloor(cell.lat, cell.lon), null, 'coarse LOD under a high camera'); sampleMeshFloorCells(fakeScene(() => 138.0, { tilesLoaded: false }), [cell], opts); assert.equal(cachedMeshFloor(cell.lat, cell.lon), null, 'mid-stream tiles read coarse'); + sampleMeshFloorCells(fakeScene(() => 138.0, { show: false }), [cell], opts); + assert.equal(cachedMeshFloor(cell.lat, cell.lon), null, 'no drawn surface, nothing to read'); + sampleMeshFloorCells(fakeScene(() => 121.0, { globeShown: true }), [cell], opts); + assert.equal(cachedMeshFloor(cell.lat, cell.lon), null, 'the globe is not the mesh'); }); test('sampler: outside the google-3d regime nothing is sampled at all', () => { @@ -140,7 +159,7 @@ test('sampler: a cell just across the antimeridian is still near the viewer', () assert.equal(calls, 2, 'about 200 m apart, so both cells are probed'); }); -test('sampler: a scene without depth-texture support is never probed', async () => { +test('sampler: a renderer without depth-texture support is never probed', async () => { reset(); const cell = nextSite(); await seedDem(cell, 120.0); @@ -155,24 +174,12 @@ test('sampler: a scene without depth-texture support is never probed', async () assert.equal(cachedMeshFloor(cell.lat, cell.lon), null); }); -test('sampler: with `sets` the probe asks the query port, naming those sets', async () => { +test('sampler: the probe sees through the caller’s `sets`', async () => { reset(); const cell = nextSite(); await seedDem(cell, 120.0); - const scene = fakeScene(() => { - throw new Error('the scene is not asked when sets are named'); - }); - const viewer = { scene }; - const asked = []; - bindRenderer(viewer, { - capabilities: new Set(['sampleHeight']), - query: { - sampleHeightNow(point, options) { - asked.push({ point: { ...point }, options }); - return 138.0; - }, - }, - }); + const viewer = fakeScene(() => 138.0); + const { asked } = viewer; sampleMeshFloorCells(viewer, [cell], { sets: ['flights-models:1', 'flights-icons:1'], viewerLat: cell.lat, diff --git a/src/data/militaryFlights.test.mjs b/src/data/militaryFlights.test.mjs index e2d9a889a..ef84b1895 100644 --- a/src/data/militaryFlights.test.mjs +++ b/src/data/militaryFlights.test.mjs @@ -448,6 +448,10 @@ test('real military track path creates no native label and publishes every cache ); assert.ok(entity.position, 'Cockpit sees a contact it can fly'); assert.equal(readEntityRecord(entity).drawn(), true); + assert.ok( + Array.isArray(readEntityRecord(entity).groundSets()), + 'Cockpit asks which draw sets its ground probe sees through', + ); assert.equal(entity.show, true); assert.equal(entity.label, undefined); assert.ok( diff --git a/src/data/radioProxy.test.mjs b/src/data/radioProxy.test.mjs index b2a1694c6..47dc30cae 100644 --- a/src/data/radioProxy.test.mjs +++ b/src/data/radioProxy.test.mjs @@ -4,6 +4,9 @@ import https from 'node:https'; import { Readable } from 'node:stream'; import test from 'node:test'; import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +// A viewer of the test's own, with no renderer bound: its factories load +// as the package's `./render/cesium/unbound` export loads them. +import '../render/cesium/unbound.js'; import { fetchPinnedRadioResponse } from '../../server/providers/radio/transport.js'; import { createRadioProxyMiddleware, diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index c903218eb..8da3a1a33 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -164,7 +164,8 @@ if (typeof globalThis.window === 'undefined') { /** A viewer stub whose camera altitude the test can move between evaluations. * Its renderer has a fake draw port (`viewer.draw`) the layer's model sets - * are made on, and a query port whose height samples are `sampleHeight`'s. */ + * are made on, a globe whose drawn tiles settle as `viewer.tileset` says, and + * a query port whose height samples are `sampleHeight`'s. */ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undefined } = {}) { const tileset = { show: true, tilesLoaded }; const draw = fakeDrawPort(); @@ -177,7 +178,6 @@ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undef scene: { canvas: { clientHeight: 900 }, frameState: { frameNumber: 1 }, - primitives: { length: 1, get() { return tileset; } }, sampleHeight, }, tileset, @@ -187,6 +187,7 @@ function viewerAtHeight(height, { tilesLoaded = true, sampleHeight = () => undef }; return bindFakeCesiumCamera(viewer, { draw, + globe: { isSettled: (kind) => kind !== 'tiles' || tileset.tilesLoaded }, query: { sampleHeightNow: () => sampleHeight() }, canvas: viewer.scene.canvas, }); diff --git a/src/layers/firms/cells.test.mjs b/src/layers/firms/cells.test.mjs index 2e97026c4..c72b00a06 100644 --- a/src/layers/firms/cells.test.mjs +++ b/src/layers/firms/cells.test.mjs @@ -6,6 +6,9 @@ import { unregisterSpriteCollection } from '../../data/spriteOrder.js'; import { fakeInput } from '../../input/testDoubles.mjs'; import { bindRenderer } from '../../render/rendererOf.js'; import { bindFakeCesiumScene } from '../../testSupport/fakeCesiumScene.mjs'; +// Ports built over a viewer of the test's own, with no renderer bound: the +// adapter's factories load as `./render/cesium/unbound` loads them. +import '../../render/cesium/unbound.js'; const raw = (lat, lon, frp) => ({ lat, diff --git a/src/layers/flights/tracking.js b/src/layers/flights/tracking.js index dbdc42e86..946ff0859 100644 --- a/src/layers/flights/tracking.js +++ b/src/layers/flights/tracking.js @@ -932,6 +932,13 @@ export function createTracking({ ); flightState._trackedEntity = holder; entityRecord(holder).drawn = () => flightState._trackedEntity === holder; + // The draw sets a height sample under the contact sees through (its + // icons and models), for Cockpit's ground probe. + entityRecord(holder).groundSets = () => { + const sets = [...parts.rendering._groundSampleExclusions().sets]; + if (trackedIcon.setId) sets.push(trackedIcon.setId); + return sets; + }; trackedIcon.show({ id: icao24, image: _trackedBillboardImage(), diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 4bd8227b2..49308c545 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -893,6 +893,13 @@ export function createTracking({ ); flightState._trackedEntity = holder; entityRecord(holder).drawn = () => flightState._trackedEntity === holder; + // The draw sets a height sample under the contact sees through (its + // icons and models), for Cockpit's ground probe. + entityRecord(holder).groundSets = () => { + const sets = [...parts.rendering._groundSampleExclusions().sets]; + if (trackedIcon.setId) sets.push(trackedIcon.setId); + return sets; + }; trackedIcon.show({ id: icao24, image: _trackedBillboardImage(), diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index eec8e3b92..0a0fa27e2 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -17,8 +17,6 @@ "src/maps/google3d.js", "src/maps/imagery.js", "src/maps/terrain.js", - "src/services/groundSnap.js", - "src/services/meshFloorSampler.js", "src/sky/starrySky.js", "src/ui/applicationShell.js" ] diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 08d243df6..ad171fa22 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -123,8 +123,8 @@ const DRAW_FROM_CALLER = new Set([ // Its moving and still vehicle icons draw through `drawOf`; it projects, // culls, follows and samples floors through the ports. './layers/transit', - // Not Cesium-free (its legacy mesh floor sampler is), but its layer draws - // and reads the view through the ports alone. + // Its layer draws and reads the view through the ports alone, and its mesh + // floor sampler asks the camera, globe and query ports. './layers/transit/standalone', ]); @@ -153,6 +153,9 @@ const CAMERA_FROM_CALLER = new Set([ // renderer the application gives it (`rendering.js`, which draws the box // preview through `drawOf`) is Cesium-free too. './layers/recent-imagery', + // Its ground snap, mesh floor sampler, annotation resolver and location + // framing ask the camera, globe and query ports; it loads no factory. + './application/operations', ]); const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8')); diff --git a/src/services/groundSnap.js b/src/services/groundSnap.js index bf9125c4e..b3eee67f9 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -46,15 +46,10 @@ * are per-layer, keyed by that layer's icao space). */ -import * as Cesium from 'cesium'; -import { heightsFor } from '../render/cesium/heights.js'; +import { scaleToGeodeticSurface, toLonLatH } from '../geo/ellipsoid.js'; +import { distanceSquared } from '../geo/vector.js'; import { heightsOf } from '../queries/heights.js'; -// The application operations entry reaches the annotation resolver and -// locations.js, whose flights and heights go through the camera and query -// ports and which cannot load the Cesium adapter themselves; this listed -// module, on the same entry, loads the factories a viewer with no renderer -// bound gets them from. -import '../render/cesium/camera.js'; +import { findGlobe } from '../render/rendererOf.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 @@ -139,40 +134,32 @@ const SAMPLE_BUDGET_PER_WINDOW = 4; const SAMPLE_WINDOW_MS = 250; /** - * True when the active photoreal tileset has finished streaming the tiles in - * view (the pattern CCTV's projectionTilesReady once used: first - * Cesium3DTileset found in scene.primitives, duck-typed via its boolean - * tilesLoaded). Sampling before that both blows the frame budget on forced - * synchronous loads and produces misses that would burn retry backoff for - * nothing. With NO tileset present - * (OSM fallback) this returns true so the sample path is not permanently - * blocked — the sample just misses and backs off. - * @param {Cesium.Viewer} viewer + * True when the drawn surface has finished streaming what is in view: the + * base tiles (the globe port's `tiles` settle kind) and whatever surface + * heights answer from (`surface`: the globe's terrain while it is shown, + * otherwise every shown 3D tileset, whoever added it). Sampling + * before that both blows the frame budget on forced synchronous loads and + * produces misses that would burn retry backoff for nothing. With the globe + * hidden and NO tiles drawn the sample could only miss, and this says not + * ready, which is the same miss and backoff without the probe. False + * without a globe port to ask. + * @param {object} viewer * @returns {boolean} */ function _tilesReady(viewer) { - const prims = viewer?.scene?.primitives; - if (!prims) return false; - for (let i = 0; i < prims.length; i++) { - let p = null; - try { - p = prims.get(i); - } catch { - continue; - } - if (p && p.show !== false && typeof p.tilesLoaded === 'boolean') { - return p.tilesLoaded === true; - } + try { + const globe = findGlobe(viewer); + return globe?.isSettled('tiles') === true && globe.isSettled('surface'); + } catch { + return false; // mid-teardown } - return true; } /** * Create a per-layer ground-snap cache. * @returns {{ - * heightFor: (viewer: Cesium.Viewer, icao: string, pos: Cesium.Cartesian3, - * getExclusions?: (() => Array)|{sets: string[]}) - * => number|null, + * heightFor: (viewer: object, icao: string, pos: {x: number, y: number, z: number}, + * exclusions?: {sets: string[]}) => number|null, * forget: (icao: string) => void, * clear: () => void, * }} @@ -180,7 +167,7 @@ function _tilesReady(viewer) { export function createGroundSnap({ groundFloor }) { const { cachedMeshFloor, meshFloorPreferred, reportValidatedMeshFloorCell } = groundFloor; - /** @type {Map} Per-icao snap state: * the sampled height and the surface point it was measured at, whether that * pair is still the fresh answer or has been demoted to a bounded last-known @@ -188,13 +175,6 @@ export function createGroundSnap({ groundFloor }) { const entries = new Map(); let windowStartMs = 0; let windowCount = 0; - const scratchCarto = new Cesium.Cartographic(); - const scratchSurfacePos = new Cesium.Cartesian3(); - /** Separate from `scratchCarto`: the held-evidence check runs on paths that - * return BEFORE the sample writes `scratchCarto`, and on the sampling path it - * must not disturb the cartographic that `reportValidatedMeshFloorCell` reads - * back after the sample lands. */ - const scratchHeldCarto = new Cesium.Cartographic(); /** * The last measurement for a contact whose fresh snap has been demoted — it @@ -207,15 +187,15 @@ export function createGroundSnap({ groundFloor }) { * moved does not change with time, so what invalidates the value is the * contact MOVING, which is exactly what this measures. * - * @param {{h: number|null, samplePos: Cesium.Cartesian3|null, held: boolean}|undefined} entry - * @param {Cesium.Cartesian3} surfacePos - Contact's position on the ellipsoid. + * @param {{h: number|null, samplePos: {x: number, y: number, z: number}|null, held: boolean}|undefined} entry + * @param {{x: number, y: number, z: number}} surfacePos - Contact's position on the ellipsoid (ECEF). * @returns {number|null} */ function heldSnapM(entry, surfacePos) { if (!entry || !entry.held || entry.h == null || !entry.samplePos) return null; if ( - Cesium.Cartesian3.distanceSquared(surfacePos, entry.samplePos) > + distanceSquared(surfacePos, entry.samplePos) > HELD_SNAP_MAX_DRIFT_M * HELD_SNAP_MAX_DRIFT_M ) { return dropHold(entry); @@ -259,20 +239,13 @@ export function createGroundSnap({ groundFloor }) { * to answer from a single sample — and borrowing one to DISCARD a real * measurement would let a roof cell hide a correctly placed model. * - * @param {Cesium.Cartesian3} surfacePos - Contact's position on the ellipsoid. + * @param {{x: number, y: number, z: number}} surfacePos - Contact's position on the ellipsoid (ECEF). * @returns {number|null} */ function freshMeasuredFloorAt(surfacePos) { - const carto = Cesium.Cartographic.fromCartesian( - surfacePos, - Cesium.Ellipsoid.WGS84, - scratchHeldCarto, - ); - if (!carto) return null; - return cachedMeshFloor( - Cesium.Math.toDegrees(carto.latitude), - Cesium.Math.toDegrees(carto.longitude), - ); + const at = toLonLatH(surfacePos); + if (!at) return null; + return cachedMeshFloor(at.lat, at.lon); } /** @@ -282,30 +255,26 @@ export function createGroundSnap({ groundFloor }) { * A contact that HAS resolved once keeps that answer through a resample outage; * see `heldSnapM`. * - * @param {Cesium.Viewer} viewer - Live viewer (sampling + tiles-ready check). + * @param {object} viewer - Live viewer (sampling + tiles-ready check). * @param {string} icao - Cache key (per-layer icao space). - * @param {Cesium.Cartesian3} pos - Current display position. Cache movement - * is measured after projecting this input to the WGS84 ellipsoid, so a - * poll-time altitude/datum change cannot invalidate a stationary snap. - * @param {(() => Array)|undefined} getExclusions - Lazily builds the - * scene.sampleHeight objectsToExclude list (own billboards/models/entities — - * the vertical pick ray at a plane's OWN lat/lon lands on its icon/model - * otherwise). Only invoked when a sample actually fires. `{sets}` (draw - * set ids) instead samples through the renderer's query port + * @param {{x: number, y: number, z: number}} pos - Current display position + * (ECEF). Cache movement is measured after projecting this input to the + * WGS84 ellipsoid, so a poll-time altitude/datum change cannot invalidate + * a stationary snap. + * @param {{sets?: string[]}} [exclusions] - The caller's own draw set ids + * (its markers and models). The sample asks the renderer's query port * (`heightsOf`), which sees through every draw set not drawn as ground - * and these: for a caller whose markers and models are on the draw port. + * and these: the vertical ray at a plane's OWN lat/lon would otherwise + * land on its icon or model. * @returns {number|null} */ - function heightFor(viewer, icao, pos, getExclusions) { - const surfacePos = Cesium.Ellipsoid.WGS84.scaleToGeodeticSurface( - pos, - scratchSurfacePos, - ); + function heightFor(viewer, icao, pos, exclusions) { + const surfacePos = scaleToGeodeticSurface(pos); if (!surfacePos) return null; const cached = entries.get(icao); if (cached && cached.h != null && cached.samplePos && !cached.held) { if ( - Cesium.Cartesian3.distanceSquared(surfacePos, cached.samplePos) <= + distanceSquared(surfacePos, cached.samplePos) <= MOVE_INVALIDATE_M * MOVE_INVALIDATE_M ) { return cached.h; @@ -360,35 +329,22 @@ export function createGroundSnap({ groundFloor }) { }; if (!_tilesReady(viewer)) return miss(); windowCount += 1; - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - scratchCarto, - ); - // Draw-set exclusions ask the renderer's query port, which sees through - // every draw set not drawn as ground (the caller's markers and models). - const sampled = !carto - ? null - : Array.isArray(getExclusions?.sets) - ? heightsOf(viewer).now(carto, { exclude: getExclusions.sets }) - : heightsFor(viewer.scene).now(carto, { - exclude: getExclusions ? getExclusions() : undefined, - }); + const at = toLonLatH(pos); + const exclude = Array.isArray(exclusions?.sets) + ? exclusions.sets + : undefined; + const sampled = !at ? null : heightsOf(viewer).now(at, { exclude }); // Same sanity floor as cctv.js's sampleGroundHeight: a hit far below the // ellipsoid is pick garbage, not ground. if (!Number.isFinite(sampled) || sampled < -150) return miss(); if (meshFloorPreferred()) { - reportValidatedMeshFloorCell( - Cesium.Math.toDegrees(scratchCarto.latitude), - Cesium.Math.toDegrees(scratchCarto.longitude), - sampled, - ); + reportValidatedMeshFloorCell(at.lat, at.lon, sampled); } // A fresh sample RELEASES any hold: this is a measurement of where the // contact is now, and it outranks a memory of where it was. entries.set(icao, { h: sampled, - samplePos: Cesium.Cartesian3.clone(surfacePos), + samplePos: surfacePos, held: false, nextRetryMs: 0, misses: 0, diff --git a/src/services/groundSnap.test.mjs b/src/services/groundSnap.test.mjs index ddbcf2427..37478ba53 100644 --- a/src/services/groundSnap.test.mjs +++ b/src/services/groundSnap.test.mjs @@ -1,8 +1,8 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import * as Cesium from 'cesium'; import { createGroundSnap } from './groundSnap.js'; import { bindRenderer } from '../render/rendererOf.js'; +import { fromDegrees } from '../geo/ellipsoid.js'; const groundFloor = { cachedMeshFloor: () => null, @@ -10,24 +10,34 @@ const groundFloor = { reportValidatedMeshFloorCell: () => {}, }; -/** A viewer whose ground is a loaded 3D tileset, counting height samples. */ +/** + * A viewer bound to a fake renderer whose drawn tiles settle as `tileset` says, + * counting height samples. + */ function makeViewer() { const calls = { samples: 0 }; const tileset = { show: true, tilesLoaded: true }; - return { - calls, - scene: { - primitives: { length: 1, get: () => tileset }, - sampleHeight() { + const asked = []; + const viewer = { calls, tileset, asked, surfaceLoaded: true }; + bindRenderer(viewer, { + globe: { + isSettled: (kind) => + kind === 'tiles' + ? tileset.tilesLoaded + : kind !== 'surface' || viewer.surfaceLoaded, + }, + query: { + sampleHeightNow(point, options) { calls.samples += 1; + asked.push({ point, options }); return 1650; }, - globe: { getHeight: () => 1600 }, }, - }; + }); + return viewer; } -const atDenverAirport = Cesium.Cartesian3.fromDegrees(-104.6737, 39.8561, 0); +const atDenverAirport = fromDegrees(-104.6737, 39.8561, 0); test('a clock that steps back opens a new sample window instead of denying samples until it catches up', (t) => { t.mock.timers.enable({ apis: ['Date'], now: 1_000_000 }); @@ -48,7 +58,7 @@ test('a clock that steps back opens a new sample window instead of denying sampl test('a retry backoff stamped before the clock stepped back does not wait for it to catch up', (t) => { t.mock.timers.enable({ apis: ['Date'], now: 10_000_000 }); const viewer = makeViewer(); - const tileset = viewer.scene.primitives.get(0); + const { tileset } = viewer; const snap = createGroundSnap({ groundFloor }); // Tiles still streaming: a miss, backed off for 2 s. tileset.tilesLoaded = false; @@ -62,25 +72,91 @@ test('a retry backoff stamped before the clock stepped back does not wait for it assert.equal(viewer.calls.samples, 1); }); -test('draw-set exclusions sample through the renderer’s query port', () => { +test('the sample asks the query port, seeing through the caller’s draw sets', () => { const viewer = makeViewer(); - const asked = []; - bindRenderer(viewer, { - query: { - sampleHeightNow(point, options) { - asked.push({ point, options }); - return 1655; - }, - }, - }); const snap = createGroundSnap({ groundFloor }); assert.equal( snap.heightFor(viewer, 'a00001', atDenverAirport, { sets: ['mine:models'], }), - 1655, + 1650, ); - assert.equal(viewer.calls.samples, 0, 'not the scene’s own sample'); - assert.deepEqual(asked[0].options, { exclude: ['mine:models'] }); - assert.ok(Math.abs(asked[0].point.lon + 104.6737) < 1e-6); + assert.equal(viewer.calls.samples, 1); + assert.deepEqual(viewer.asked[0].options, { exclude: ['mine:models'] }); + assert.ok(Math.abs(viewer.asked[0].point.lon + 104.6737) < 1e-6); + assert.ok(Math.abs(viewer.asked[0].point.lat - 39.8561) < 1e-6); +}); + +test('a snap waits while the drawn tiles are still streaming', () => { + const viewer = makeViewer(); + viewer.tileset.tilesLoaded = false; + const snap = createGroundSnap({ groundFloor }); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(viewer.calls.samples, 0); +}); + +test('a snap waits while a shown tileset outside the base is still streaming', () => { + const viewer = makeViewer(); + viewer.surfaceLoaded = false; + const snap = createGroundSnap({ groundFloor }); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(viewer.calls.samples, 0); +}); + +test('without a globe port to ask, a snap is a miss', () => { + const viewer = {}; + let samples = 0; + bindRenderer(viewer, { + query: { + sampleHeightNow() { + samples += 1; + return 1650; + }, + }, + }); + const snap = createGroundSnap({ groundFloor }); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(samples, 0); +}); + +test('through the Cesium globe port, a streaming tileset the port did not load holds the snap', async () => { + const Cesium = await import('cesium'); + const { createCesiumGlobe } = await import('../render/cesium/globe.js'); + const tileset = Object.create(Cesium.Cesium3DTileset.prototype); + Object.defineProperties(tileset, { + show: { value: true, writable: true }, + tilesLoaded: { value: false, writable: true }, + }); + tileset.isDestroyed = () => false; + const scene = { + globe: { show: false, tilesLoaded: true }, + imageryLayers: new Cesium.ImageryLayerCollection(), + primitives: { length: 1, get: () => tileset }, + preUpdate: new Cesium.Event(), + }; + const { port } = createCesiumGlobe( + { scene }, + { + capabilities: new Set(['globeVisibility', 'surfaceIdentity']), + requestRender() {}, + }, + ); + let samples = 0; + const viewer = {}; + bindRenderer(viewer, { + globe: port, + query: { + sampleHeightNow() { + samples += 1; + return 1650; + }, + }, + }); + const snap = createGroundSnap({ groundFloor }); + assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), null); + assert.equal(samples, 0, 'not while the tileset streams'); + tileset.tilesLoaded = true; + const later = createGroundSnap({ groundFloor }); + assert.equal(later.heightFor(viewer, 'a00001', atDenverAirport), 1650); + assert.equal(samples, 1); }); diff --git a/src/services/meshFloorSampler.js b/src/services/meshFloorSampler.js index 3f85a2b16..093b88dce 100644 --- a/src/services/meshFloorSampler.js +++ b/src/services/meshFloorSampler.js @@ -1,7 +1,6 @@ -import * as Cesium from 'cesium'; import { approxDistanceKm } from '../data/approxDistance.js'; -import { heightsFor } from '../render/cesium/heights.js'; import { heightsOf } from '../queries/heights.js'; +import { findCamera, findGlobe } from '../render/rendererOf.js'; /** Construct an instance-owned meshFloorSampler service with explicit dependencies. */ export function createMeshFloorSampler({ @@ -64,8 +63,8 @@ export function createMeshFloorSampler({ /** @type {Map>} Points probed * per cell that returned a reading. */ const _probedPoints = new Map(); - /** @type {Cesium.Cartographic} Scratch for probe coordinates. */ - const _scratchProbe = new Cesium.Cartographic(); + /** Scratch for probe coordinates (degrees). */ + const _scratchProbe = { lon: 0, lat: 0 }; // Regime tracking: mesh cells only apply while the photoreal (google-3d) // stack renders. main.js re-dispatches MapStackController.onChange as this @@ -74,22 +73,22 @@ export function createMeshFloorSampler({ // bundle, and the subscription is idempotent for the app's lifetime. /** - * True when a VISIBLE 3D tileset in the scene reports its streaming queue - * drained (tilesLoaded) — as CCTV's projectionTilesReady once did (it now - * asks the globe port whether its drawn photoreal tiles have settled). - * Walks top-level primitives only (a handful; once per poll). - * @param {Cesium.Scene} scene + * True when the globe is hidden (the google-3d regime draws the mesh + * alone) and the drawn 3D tiles have loaded what is in view; false with + * the globe shown or no tiles drawn. Asked of the globe port once per poll. + * The globe check matters on its own: the regime flag can still say + * photoreal while a switch to a globe stack is loading, or after a silent + * one, and a probe of the globe there would latch terrain as mesh. + * @param {object} viewer * @returns {boolean} */ - function _visibleTilesetLoaded(scene) { + function _surfaceSettled(viewer) { try { - const prims = scene.primitives; - for (let i = 0; i < prims.length; i++) { - const p = prims.get(i); - if (p instanceof Cesium.Cesium3DTileset && p.show) { - return !!p.tilesLoaded; - } - } + const globe = findGlobe(viewer); + return ( + globe?.isGlobeVisible?.() === false && + globe.isSettled('surface') === true + ); } catch { /* mid-teardown */ } @@ -99,48 +98,44 @@ export function createMeshFloorSampler({ /** * Samples the rendered mesh height for the coarse cells containing `points`, * a few probes per cell, budget-capped, viewer-proximity-gated. Call ONCE per - * layer poll (never per contact, never per frame). Synchronous — Cesium's + * layer poll (never per contact, never per frame). Synchronous — the renderer's * sampleHeight is a CPU-side query against loaded tiles. * - * @param {Cesium.Scene|object|undefined} host - The scene, or the viewer - * whose scene it is (skipped when absent/torn down). + * @param {object|undefined} viewer - The viewer whose renderer draws the + * mesh (skipped when absent/torn down). The probe asks its query port + * (`heightsOf`), which sees through every draw set not drawn as ground. * @param {Array<{lat: number, lon: number}>} points - Contact/waypoint coords. * @param {object} [options] - * @param {Array} [options.excludeObjects] - Own billboards/models to - * exclude from the probe (Cesium matches instances/.primitive/.id — pass - * Billboard and Model instances, NOT collections). - * @param {string[]} [options.sets] - Own draw set ids to see through. When - * given, `host` must be the viewer and the probe asks the renderer's - * query port (`heightsOf`), which sees through every draw set not drawn - * as ground; `excludeObjects` is then unused. + * @param {string[]} [options.sets] - The caller's own draw set ids, seen + * through as well. * @param {number} [options.viewerLat] @param {number} [options.viewerLon] * Viewer subpoint (computed once by the caller's poll). */ function sampleMeshFloorCells( - host, + viewer, points, - { excludeObjects = [], sets, viewerLat, viewerLon } = {}, + { sets, viewerLat, viewerLon } = {}, ) { - const scene = host?.scene ?? host; if (!meshFloorPreferred()) return; - const bySets = Array.isArray(sets); - const heights = !scene - ? null - : bySets - ? heightsOf(host) - : heightsFor(scene); - const exclude = bySets ? sets : excludeObjects; + if (!viewer || viewer.isDestroyed?.()) return; + const heights = heightsOf(viewer); + const exclude = Array.isArray(sets) ? sets : undefined; // Without depth-texture support every probe throws: nothing to latch. if (!heights?.supported().surface) return; if (!Array.isArray(points) || !points.length) return; // Round-5 hardening (the CCTV projectionTilesReady lesson, ported late): // while tiles are MID-STREAM a probe returns coarse-LOD heights — real // numbers, wildly wrong — and the one-shot latch made them permanent. - // Only sample when the visible Google tileset reports tilesLoaded AND the + // Only sample when the drawn tiles report they have settled AND the // camera is low enough that the streamed LOD near it is fine-grained. - const camH = scene.camera?.positionCartographic?.height; + let camH; + try { + camH = findCamera(viewer)?.pose().height; + } catch { + return; // mid-teardown + } if (!Number.isFinite(camH) || camH > MAX_CAMERA_HEIGHT_M) return; - if (!_visibleTilesetLoaded(scene)) return; + if (!_surfaceSettled(viewer)) return; let sampled = 0; const attempted = new Set(); for (const p of points) { @@ -174,10 +169,9 @@ export function createMeshFloorSampler({ } // Probe where the caller's point is, not at the cell's centre: a // centre that falls on a roof would lift everything in the cell. - const height = heights.now( - Cesium.Cartographic.fromDegrees(p.lon, p.lat, 0, _scratchProbe), - { exclude }, - ); + _scratchProbe.lon = p.lon; + _scratchProbe.lat = p.lat; + const height = heights.now(_scratchProbe, { exclude }); // A miss counts against the budget whatever its cause: past the support // gate a probe only throws mid-teardown, when every later cell would too. sampled += 1; diff --git a/src/testSupport/radioLayerHarness.mjs b/src/testSupport/radioLayerHarness.mjs index 3aadedc10..e6d4f7ee8 100644 --- a/src/testSupport/radioLayerHarness.mjs +++ b/src/testSupport/radioLayerHarness.mjs @@ -1,6 +1,9 @@ import { radioLayer } from '../data/radio.js'; import { bindRenderer } from '../render/rendererOf.js'; import { bindFakeDraw } from './fakeDrawPort.mjs'; +// The layer's clicks and floors take a viewer of the test's own, as a +// renderer bound: its factories load as `./render/cesium/unbound` loads them. +import '../render/cesium/unbound.js'; export function radioStationRow(overrides = {}) { return { diff --git a/src/ui/cockpitCamera.js b/src/ui/cockpitCamera.js index d6ba6b6f7..9abdef324 100644 --- a/src/ui/cockpitCamera.js +++ b/src/ui/cockpitCamera.js @@ -1,6 +1,7 @@ /** Camera placement, ground acquisition and motion correction for the Cockpit controller. */ import { cameraOf, findFrame } from '../render/rendererOf.js'; import { followedPosition } from '../data/followed.js'; +import { readEntityRecord } from '../data/entityRecords.js'; import { trackedEntityDrawn } from './cockpitTrackingController.js'; import { add, @@ -179,7 +180,7 @@ export function update() { this.lastGroundProbeMs = nowMs; const eye = cameraOf(this.viewer).pose(); this.services.sampleMeshFloorCells(this.viewer, groundPoint, { - excludeObjects: [this.trackedEntity], + sets: readEntityRecord(this.trackedEntity)?.groundSets?.() ?? [], viewerLat: eye.lat, viewerLon: eye.lon, }); diff --git a/src/ui/cockpitController.test.mjs b/src/ui/cockpitController.test.mjs index 6befee304..70adace2a 100644 --- a/src/ui/cockpitController.test.mjs +++ b/src/ui/cockpitController.test.mjs @@ -517,6 +517,10 @@ test('a grounded Cockpit probes the mesh from the camera and keeps the eye above GROUND_FLOOR_LIFT_M: 0, }, }); + // The tracked contact names the draw sets its probe sees through. + withEntityRecord(owner.trackedEntity, { + groundSets: () => ['flights-models:1', 'flights-tracked-icon:1'], + }); // The surface wait is over: Cockpit flies on the ground floor. owner.surfaceWaitStartedMs = -1e9; owner.update(); @@ -525,7 +529,7 @@ test('a grounded Cockpit probes the mesh from the camera and keeps the eye above assert.equal(host, viewer); assert.deepEqual(points, [{ lat: 30.19, lon: -97.67 }]); assert.deepEqual(options, { - excludeObjects: [owner.trackedEntity], + sets: ['flights-models:1', 'flights-tracked-icon:1'], viewerLat: 30.2, viewerLon: -97.7, });