diff --git a/CHANGELOG.md b/CHANGELOG.md index 076ca2a14..5f1d1211e 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,26 @@ `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). +- `gods-eye-view/layers/traffic` (and `gods-eye-view/application/sources`, + which reaches it) no longer reaches Cesium: the layer keys cached road + heights by the globe port's `surfaceVersion()` and waits on + `isSettled('surface')`. Heat-lines are always asked for draped; a renderer + that cannot drape draws them over the surface instead of the layer + dropping them. A viewer with no renderer bound needs + `gods-eye-view/render/cesium/unbound` loaded once first (samehkhamis). +- Where the Cesium renderer cannot drape (a WebGL context without depth + textures), every draped line now draws over the surface, as the renderer + contract asks: along the surface's curve between its positions, in its + colour where the surface hides it, hidden past the horizon. Segment colours + are dropped (it draws in its style colour) and it runs from its first shown + segment to its last (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..c4476d2bd 100644 --- a/docs/CURRENT-STATE.md +++ b/docs/CURRENT-STATE.md @@ -1041,7 +1041,7 @@ The view pass reruns while the camera moves, paced by its own cost. The camera picker lists the cameras in view, active camera first, and closes with the count of cameras outside the view. -Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and caches surface identity without allocating on unchanged frames. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger; only the surface identity, tile readiness and draped-line support are still read off the Cesium scene. +Traffic owns its rendered-surface observer only while enabled, removes it on disable/destroy, and rebuilds no cached heights on frames where the surface identity is unchanged. Its dots and heat-lines are two renderer draw sets, it animates on the frame port's preRender, and it follows the camera through the camera port at its own 5% threshold rather than the shared `percentageChanged` ledger. The surface identity is the globe port's `surfaceVersion()` and tile readiness its `isSettled('surface')`, so the layer no longer reaches Cesium. Heat-lines are always asked for draped: where the Cesium renderer cannot drape (no depth textures) its draw port draws them (and every other draped line) over the surface, in their colour where the surface hides them and hidden past the horizon, recolouring a line in place when only its colour changes, rather than the layer dropping them. Traffic and bikeshare expose factories through `./layers/traffic` and `./layers/bikeshare`. Traffic separates road requests, ingestion, animation, @@ -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/scripts/package-boundaries.json b/scripts/package-boundaries.json index f9f04b147..eb808bebd 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -2397,7 +2397,6 @@ "src/layers/traffic/policy.js", "src/render/color.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", @@ -3680,7 +3679,6 @@ "src/layers/traffic/model.js", "src/layers/traffic/policy.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", @@ -4646,7 +4644,6 @@ "src/layers/traffic/model.js", "src/layers/traffic/policy.js", "src/layers/traffic/rendering.js", - "src/render/cesium/surfaceState.js", "src/layers/traffic/retention.js", "src/layers/traffic/source.js", "src/layers/traffic/state.js", 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/layers/traffic/heatLines.test.mjs b/src/layers/traffic/heatLines.test.mjs index 39ba6b5cf..87eccda57 100644 --- a/src/layers/traffic/heatLines.test.mjs +++ b/src/layers/traffic/heatLines.test.mjs @@ -22,12 +22,7 @@ const road = (level, length = 100, x = 0) => ({ ], }); -function setup({ - live = true, - heatline = true, - preset = 'normal', - supported = true, -} = {}) { +function setup({ live = true, heatline = true, preset = 'normal' } = {}) { const draw = fakeDrawPort(); const demand = []; const state = { @@ -37,7 +32,6 @@ function setup({ _stylePreset: preset, _heatJam: [], _heatLineCount: 0, - _heatSupported: supported, _heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }), }; const rendering = createRendering({ @@ -144,14 +138,9 @@ test('no heat-lines in simulation or with the mode off, and removal empties the assert.equal(items().length, 0, 'nothing to pulse'); }); -test('where lines cannot drape, no heat-lines are drawn and that is said once', (t) => { - const warn = t.mock.method(console, 'warn', () => {}); - const { state, rendering, items } = setup({ supported: null }); - state._viewer = { scene: {} }; +test('heat-lines are asked for draped whatever the renderer, with no check of their own', () => { + const { rendering, items } = setup(); rendering.rebuildHeatLines([road(0.2)]); - rendering.rebuildHeatLines([road(0.2)]); - assert.equal(items().length, 0); - assert.equal(state._heatSupported, false); - assert.equal(warn.mock.callCount(), 1); - assert.equal(rendering.heatPulsing(), false); + assert.equal(items().length, 1); + assert.equal(items()[0].mode, 'draped'); }); diff --git a/src/layers/traffic/motion.test.mjs b/src/layers/traffic/motion.test.mjs index c0e3e48b5..04f14db20 100644 --- a/src/layers/traffic/motion.test.mjs +++ b/src/layers/traffic/motion.test.mjs @@ -759,7 +759,7 @@ test('selection asks the query port for depth and screen positions, and the came camera: { pose: () => (poses++, { position: { x: eye.x, y: eye.y, z: eye.z } }), }, - globe: { isGlobeVisible: () => true }, + globe: { isGlobeVisible: () => true, isSettled: () => true }, query: { sampleHeightNow: () => 0, pickPosition(x, y) { diff --git a/src/layers/traffic/rendering.js b/src/layers/traffic/rendering.js index 54cb696cd..ce8046203 100644 --- a/src/layers/traffic/rendering.js +++ b/src/layers/traffic/rendering.js @@ -12,20 +12,6 @@ import { } from './policy.js'; import { distance } from '../../geo/vector.js'; import { findCamera } from '../../render/rendererOf.js'; -// The layer's other parts reach the renderer through the unbound camera -// factory (with its query port) and globe factory, loaded here with the -// adapter this file needs. -import '../../render/cesium/camera.js'; -import '../../render/cesium/globe.js'; -// What the dots' surface is, and whether it has loaded, the renderer -// contract cannot say: the Cesium adapter reads it off the scene. -import { - drapesLines, - surfaceTilesReady, - surfaceKey as trafficSurfaceKey, -} from '../../render/cesium/surfaceState.js'; - -export { surfaceTilesReady, trafficSurfaceKey }; export function createRendering({ state: layerState, @@ -66,7 +52,8 @@ export function createRendering({ * on top. Lines of the layer's heat-line draw set, draped on the tiles; * the jam lines pulse together (`pulseHeatLines`). Capped at * HEAT_LINE_CAP (jam first, longest first); overflow is logged. No-op in - * sim mode, when the heatline mode is off, or where lines cannot drape. + * sim mode or when the heatline mode is off. A renderer that cannot drape + * draws them over the surface instead (the draw port's `overlay`). * * @param {Array} roads - Road objects visible in the current render. */ @@ -81,18 +68,6 @@ export function createRendering({ removeHeatLines(); return; } - if (layerState._heatSupported === null) { - layerState._heatSupported = drapesLines(layerState._viewer); - if (!layerState._heatSupported) - console.warn( - '[Data:Traffic] Draped lines unsupported — heat-lines disabled', - ); - } - if (!layerState._heatSupported) { - removeHeatLines(); - return; - } - const candidates = []; for (const road of roads) { const flow = road.flow; diff --git a/src/layers/traffic/state.js b/src/layers/traffic/state.js index ecd643fbc..2554edb3b 100644 --- a/src/layers/traffic/state.js +++ b/src/layers/traffic/state.js @@ -182,10 +182,6 @@ export function createState({ services }) { layerState._heatLineCount = 0; - /** @type {boolean|null} Whether lines can drape here, checked once. */ - - layerState._heatSupported = null; - /** @type {number} Altitude of the last render, for late-flow heat rebuilds. */ layerState._lastRenderAltitude = 0; diff --git a/src/layers/traffic/surface.js b/src/layers/traffic/surface.js index 8541a7c2c..5d8e33053 100644 --- a/src/layers/traffic/surface.js +++ b/src/layers/traffic/surface.js @@ -10,9 +10,27 @@ import { findGlobe, findQuery, } from '../../render/rendererOf.js'; -import { surfaceTilesReady, trafficSurfaceKey } from './rendering.js'; +/** + * What heights are sampled against now: the globe port's surface identity, + * which changes when the base, terrain or photoreal route is swapped or the + * globe is shown or hidden, and never on camera moves or tile loads. A + * renderer without one (`surfaceIdentity`) names a single surface (0), so + * cached heights live as long as the layer's cache. + * @param {object|undefined} viewer + * @returns {number} + */ +export function trafficSurfaceKey(viewer) { + return findGlobe(viewer)?.surfaceVersion?.() ?? 0; +} -export { trafficSurfaceKey }; +/** + * Whether the drawn surface has loaded what is in view: the globe's terrain + * while it is shown, otherwise the shown 3D tiles (false with neither). + * @param {object|undefined} viewer + */ +function surfaceTilesReady(viewer) { + return findGlobe(viewer)?.isSettled('surface') === true; +} /** Whether the globe surface is drawn (else tiles alone are). */ const globeShown = (viewer) => findGlobe(viewer)?.isGlobeVisible?.() === true; diff --git a/src/layers/traffic/surface.test.mjs b/src/layers/traffic/surface.test.mjs index 9b92315b5..a430547d5 100644 --- a/src/layers/traffic/surface.test.mjs +++ b/src/layers/traffic/surface.test.mjs @@ -346,7 +346,7 @@ test('rendered road depth is geographically checked, bounded, and avoids mesh re ); }); -test('surface keys reuse identity without building arrays or strings on unchanged frames', (t) => { +test('surface keys follow the globe port’s surface identity, building nothing on unchanged frames', (t) => { const tiles = [ { show: true, tilesLoaded: true }, { show: true, tilesLoaded: false }, diff --git a/src/render/cesium/draw.js b/src/render/cesium/draw.js index 7ef6edb7d..43b008259 100644 --- a/src/render/cesium/draw.js +++ b/src/render/cesium/draw.js @@ -790,6 +790,7 @@ export function createCesiumDraw({ // eye is hidden, as layers drawn without depth test used to do themselves. let occluder = null; function cullHorizon() { + cullOverlayLines(); for (const record of sets.values()) { if (!record.spec.horizonCull || !record.placed.length) continue; const horizon = horizonNow(); @@ -801,6 +802,26 @@ export function createCesiumDraw({ } } + /** + * Draped lines drawn over the surface (where the scene cannot drape) show + * while any of their ends or middle is this side of the horizon. + */ + function cullOverlayLines() { + let horizon; + for (const record of sets.values()) { + if (!record.overlayLines?.length) continue; + horizon ??= horizonNow(); + for (const line of record.overlayLines) { + // With no horizon (2D) every line shows as it was asked to. + const show = + line.shown && + (!horizon || line.ends.some((p) => horizon.isPointVisible(p))); + if (line.part.deep && line.part.deep.show !== show) + line.part.deep.show = show; + } + } + } + /** The horizon from the eye as it is now; null where there is none (2D). */ function horizonNow() { const eye = scene.camera?.positionWC; @@ -1849,8 +1870,11 @@ export function createCesiumDraw({ width: item.widthPx, vertexFormat: Cesium.PolylineMaterialAppearance.VERTEX_FORMAT, // Straight between the positions, as the collection's lines are - // (geodesic ones come densified). - arcType: Cesium.ArcType.NONE, + // (geodesic ones come densified); one drawn for a draped line + // follows the surface's curve between them, as draping does. + arcType: item.overlaid + ? Cesium.ArcType.GEODESIC + : Cesium.ArcType.NONE, }), id, }), @@ -1958,6 +1982,125 @@ export function createCesiumDraw({ ); } + /** Whether the scene can drape lines (Cesium's ground polylines need + * depth textures, which every WebGL 2 context has). */ + const drapes = () => scene.frameState?.context?.depthTexture !== false; + + /** + * A draped line as drawn where the scene cannot drape: undraped along its + * positions, in its colour where the surface hides it (so it draws over + * the surface), as one colour where it had segments of its own. One with + * segments runs from its first shown segment to its last, and is hidden + * with none shown. + */ + function overlayLine(item) { + if (item.mode !== 'draped') return item; + const { segmentColors, segmentShow, clampTo, ...rest } = item; + const line = { + ...rest, + mode: '3d', + depthFailColor: item.style.color, + overlaid: true, + }; + if (segmentShow?.length) { + const first = segmentShow.indexOf(true); + const last = segmentShow.lastIndexOf(true); + if (first < 0) line.show = false; + else if (first > 0 || last < segmentShow.length - 1) + line.positions = linePositions(item).slice(first, last + 2); + } + return line; + } + + /** + * Recolour, in place, a line drawn over the surface for a draped one whose + * positions are the ones it was built from. False, changing nothing, for + * one that moved or is revealed. + */ + function overlayRecoloured(record, part, item) { + const deep = part.deep; + if (!item.overlaid || !deep || revealed(item)) return false; + if (!flatEquals(item.positions, part.overlayFrom)) return false; + // Only its colour may have changed (`patchLines` checked its look). + deep.appearance.material.uniforms.color = toColor(item.style.color); + deep.depthFailAppearance.material.uniforms.color = toColor( + item.style.color, + ); + const line = record.overlayLines.find((entry) => entry.part === part); + if (line) line.shown = item.show !== false; + else deep.show = item.show !== false; + return true; + } + + /** An overlay line's look but its colours (its depth-fail colour is its + * colour too). */ + const overlayShape = (item) => + lineLook({ ...item, depthFailColor: null }, true); + + /** Stop tracking a line no longer drawn over the surface for a draped + * one. */ + function overlayLeft(record, part) { + const lines = record.overlayLines; + const at = lines ? lines.findIndex((line) => line.part === part) : -1; + if (at >= 0) lines.splice(at, 1); + part.overlayFrom = undefined; + part.overlayShape = undefined; + } + + /** Track a patched overlay line for the horizon cull, as built now. */ + function overlayMoved(record, part, item) { + part.overlayFrom = flatPositions(item.positions); + part.overlayShape = overlayShape(item); + const lines = record.overlayLines; + const at = lines.findIndex((line) => line.part === part); + if (at >= 0) lines.splice(at, 1); + if (!part.deep) return; + lines.push({ + part, + shown: item.show !== false, + ends: overlayEnds(item.positions), + }); + } + + /** + * Points along a line for the horizon test: up to 16 of its positions, + * evenly spread, and between each two the point on the surface's curve + * halfway (so a long arc under the eye is not taken as past the horizon). + */ + function overlayEnds(positions) { + const all = linePositions({ positions }); + if (!all.length) return []; + const picks = Math.min(all.length, 16); + const probes = []; + let previous = null; + for (let k = 0; k < picks; k++) { + const at = + all[Math.round((k * (all.length - 1)) / Math.max(1, picks - 1))]; + if (previous) { + const mid = Cesium.Cartesian3.midpoint( + previous, + at, + new Cesium.Cartesian3(), + ); + const radius = + (Cesium.Cartesian3.magnitude(previous) + + Cesium.Cartesian3.magnitude(at)) / + 2; + if (Cesium.Cartesian3.magnitude(mid) > 0) + probes.push( + Cesium.Cartesian3.multiplyByScalar( + Cesium.Cartesian3.normalize(mid, mid), + radius, + mid, + ), + ); + } + probes.push(at); + previous = at; + } + return probes; + } + function buildLines(record) { // Refused before anything changes, so the set keeps drawing as it was. for (const item of record.items.values()) @@ -1981,6 +2124,14 @@ export function createCesiumDraw({ throw new Error( 'the Cesium renderer colours and shows segments of draped solid lines only', ); + // Where the scene cannot drape at all, draped lines draw over the + // surface instead (`overlay`): undraped, in their own colour where the + // surface hides them, and hidden past the horizon (`cullOverlayLines`). + const overlay = !drapes(); + const items = overlay + ? [...record.items.values()].map(overlayLine) + : [...record.items.values()]; + record.overlayLines = overlay ? [] : null; const polylines = new Cesium.PolylineCollection(); // Lines in the inertial frame, turned with the sky each frame. let inertial = null; @@ -2003,7 +2154,7 @@ export function createCesiumDraw({ // Lines with a depth-fail colour, beside the collection. let deep = null; const looks = lineLooks(); - for (const item of record.items.values()) { + for (const item of items) { if (item.mode === 'draped') { const clampTo = item.clampTo ?? record.spec.clampTo ?? 'both'; const part = { @@ -2047,7 +2198,18 @@ export function createCesiumDraw({ const id = pickId(record, item); const primitive = depthFailLine(record, item, id); if (primitive) deep.add(primitive); - parts.set(item.id, { look: lineLook(item), id, deep: primitive }); + const part = { look: lineLook(item), id, deep: primitive }; + if (item.overlaid) { + part.overlayFrom = flatPositions(item.positions); + part.overlayShape = overlayShape(item); + } + parts.set(item.id, part); + if (item.overlaid && primitive) + record.overlayLines.push({ + part, + shown: item.show !== false, + ends: overlayEnds(item.positions), + }); continue; } const id = pickId(record, item); @@ -2101,7 +2263,7 @@ export function createCesiumDraw({ let own = polylines; // Lines in the collection that can settle into a static batch draw // beside it once they do. - const settling = [...record.items.values()].some(settles); + const settling = items.some(settles); if (deep || settling || inertial) { own = new Cesium.PrimitiveCollection(); own.add(polylines); @@ -2295,6 +2457,17 @@ export function createCesiumDraw({ Boolean((was.polyline || was.batched) && was.shape) && was.shape === looks.shape(item); + /** + * Whether a line drawn over the surface for a draped one changes only its + * colour where it runs: it takes the new one in place + * (`overlayRecoloured`). + */ + const recolourableOverlay = (was, item, looks) => + Boolean(item.overlaid && was.deep && was.overlayShape) && + flatEquals(item.positions, was.overlayFrom) && + !revealed(item) && + was.overlayShape === overlayShape(item); + /** * The colours the glow lines sharing a material that `list` recolours * are given together: each such material and the item whose colour it @@ -2351,6 +2524,10 @@ export function createCesiumDraw({ function patchLines(record, list) { const parts = record.lineParts; if (record.kind !== 'lines' || !parts) return false; + // Where the scene cannot drape, draped lines are patched as the lines + // drawn over the surface for them, each built anew alone where it + // changes (as any line with a depth-fail colour is). + if (record.overlayLines) list = list.map(overlayLine); // Each draped line's positions, flattened once for both passes. const flats = new Map(); // Each item's look, in order: an item sent twice is changed twice. @@ -2364,7 +2541,8 @@ export function createCesiumDraw({ if ( was.look !== look && !recolourable(was, item, lookOf) && - !recolourableSolid(was, item, lookOf) + !recolourableSolid(was, item, lookOf) && + !recolourableOverlay(was, item, lookOf) ) return false; // A viewer destroyed under the set took its batch with it. @@ -2400,7 +2578,7 @@ export function createCesiumDraw({ patchUndraped(record, was, item, looks[k]); continue; } - if (was.look !== looks[k]) { + if (was.look !== looks[k] && was.deep === undefined) { // A line drawing on a shared material took its colour above. if (!was.shared || was.solo) was.material.uniforms.color = toColor(item.style.color); @@ -2408,6 +2586,10 @@ export function createCesiumDraw({ } if (was.deep !== undefined) { was.id.meta = item.meta; + was.look = looks[k]; + // One drawn for a draped line that runs where it ran takes its new + // look in place (heat-lines pulse every frame). + if (overlayRecoloured(record, was, item)) continue; // Built anew where it now runs, under the same pick id. const deep = record.deepLines; const old = was.deep; @@ -2418,6 +2600,8 @@ export function createCesiumDraw({ was.deep = depthFailLine(record, item, was.id); if (was.deep) deep.add(was.deep); if (old) deep.remove(old); + if (item.overlaid) overlayMoved(record, was, item); + else if (was.overlayFrom) overlayLeft(record, was); continue; } was.id.meta = item.meta; @@ -3653,13 +3837,13 @@ export function createCesiumDraw({ * drape them onto 3D tiles yet, so over shown tiles it is `overlay`. * Terrain and the ellipsoid take draped items wherever Cesium drapes at * all: its draped lines and image fills need depth textures, which every - * WebGL 2 context has; without them it says `overlay`. (It still builds - * them as ground primitives there: the overlay drawing itself is not - * built, since only a WebGL 1 context without the extension lacks them.) + * WebGL 2 context has; without them it says `overlay`, and draws draped + * lines over the surface (`overlayLine`). Clamped shapes there are still + * built as ground primitives: only a WebGL 1 context without the + * extension lacks depth textures. */ const clampState = () => - scene.frameState?.context?.depthTexture === false || - tilesets().some((tileset) => tileset.show) + !drapes() || tilesets().some((tileset) => tileset.show) ? 'overlay' : 'draped'; const clampListeners = listenerList(report); diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index c3f4b35bc..95d4d7c8e 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -4594,7 +4594,6 @@ test('the traffic layer drapes its heat-lines on the tiles and pulses the jam on _presetDots: 'off', _heatJam: [], _heatLineCount: 0, - _heatSupported: true, _heatSet: draw.lines({ id: 'traffic:1:heat', clampTo: 'tiles' }), }; const rendering = createRendering({ @@ -4647,6 +4646,237 @@ test('the traffic layer drapes its heat-lines on the tiles and pulses the jam on }); }); +test('where the scene cannot drape, draped lines draw over the surface and hide past the horizon', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw, frame } = drawOver(scene); + assert.equal(draw.clampState(), 'overlay'); + const set = draw.lines({ id: 'heat', clampTo: 'tiles' }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0); + const firstPositions = [at(0), at(0.01)]; + set.set([ + { + id: 'jam', + positions: firstPositions, + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.8], power: 0.25 }, + }, + ]); + const host = scene.added[0]; + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(host); + assert.ok( + !all.some((p) => p instanceof Cesium.GroundPolylinePrimitive), + 'no ground polyline', + ); + const line = all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + assert.ok(line, 'drawn where the surface hides it too'); + const failColor = line.depthFailAppearance.material.uniforms.color; + assert.ok(Math.abs(failColor.red - 1) < 1e-6 && failColor.green === 0); + // The eye over the line's side of the Earth: shown. + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + assert.equal(line.show, true); + // The eye over the far side: past the horizon, hidden. + scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0); + frame(); + assert.equal(line.show, false); + // A recolour where it runs (a pulse) takes the colour in place, and the + // line stays hidden past the horizon: nothing is built anew. + const hostBefore = scene.added[0]; + set.upsert([ + { + id: 'jam', + positions: firstPositions, + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.4], power: 0.25 }, + }, + ]); + frame(); + assert.equal(line.show, false, 'still past the horizon'); + const after = []; + const walkAfter = (p) => { + after.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walkAfter(p.get(i)); + }; + walkAfter(scene.added[0]); + assert.equal(scene.added[0], hostBefore, 'the set is not rebuilt'); + assert.ok(after.includes(line), 'the same line draws'); + assert.ok( + Math.abs(line.appearance.material.uniforms.color.alpha - 0.4) < 1e-6, + ); + assert.ok( + Math.abs(line.depthFailAppearance.material.uniforms.color.alpha - 0.4) < + 1e-6, + ); + // In 2D there is no horizon: it shows as asked. + scene.mode = Cesium.SceneMode.SCENE2D; + frame(); + assert.equal(line.show, true, 'shown in 2D'); + scene.mode = Cesium.SceneMode.SCENE3D; + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + // Moved, it alone is built anew, still over the surface and culled. + set.upsert([ + { + id: 'jam', + positions: [at(0), at(0.02)], + widthPx: 4, + mode: 'draped', + style: { kind: 'glow', color: [1, 0, 0, 0.4], power: 0.25 }, + }, + ]); + assert.equal(scene.added[0], hostBefore, 'patched, not rebuilt'); + const moved = []; + const walkMoved = (p) => { + moved.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walkMoved(p.get(i)); + }; + walkMoved(scene.added[0]); + const rebuilt = moved.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + assert.ok(rebuilt && rebuilt !== line, 'built anew where it moved'); + assert.ok(!moved.includes(line), 'the old line is gone'); + scene.camera.positionWC = new Cesium.Cartesian3(-2e7, 0, 0); + frame(); + assert.equal(rebuilt.show, false); + set.dispose(); + assert.equal(scene.added.length, 0); + })); + +test('where the scene cannot drape, an overlay line is culled by its whole arc, and patched by what its positions hold', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw, frame } = drawOver(scene); + const set = draw.lines({ id: 'arc', clampTo: 'tiles' }); + const find = () => { + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(scene.added[0]); + return all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + }; + // Its ends are past the horizon, but the arc runs under the eye. + const a = Cesium.Cartesian3.fromDegrees(-80, 0, 0); + const b = Cesium.Cartesian3.fromDegrees(80, 0, 0); + const positions = new Float64Array([a.x, a.y, a.z, b.x, b.y, b.z]); + const item = (style) => ({ + id: 'arc', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: style }, + }); + set.set([item([1, 0, 0, 1])]); + scene.camera.positionWC = new Cesium.Cartesian3(2e7, 0, 0); + frame(); + const line = find(); + assert.equal(line.show, true, 'shown: its middle is in view'); + // The same buffer, changed in place: built anew where it now runs. + const c = Cesium.Cartesian3.fromDegrees(10, 0, 0); + positions.set([c.x, c.y, c.z], 3); + set.upsert([item([1, 0, 0, 1])]); + const moved = find(); + assert.notEqual(moved, line, 'built anew'); + // Moved past the horizon, then upserted as an ordinary line in view: + // it is no longer culled by where the overlay was. + const far = new Float64Array(6); + const f1 = Cesium.Cartesian3.fromDegrees(179, 0, 0); + const f2 = Cesium.Cartesian3.fromDegrees(179.5, 0, 0); + far.set([f1.x, f1.y, f1.z, f2.x, f2.y, f2.z]); + set.upsert([{ ...item([1, 0, 0, 1]), positions: far }]); + frame(); + assert.equal(find().show, false, 'past the horizon'); + set.upsert([ + { + id: 'arc', + positions: [ + Cesium.Cartesian3.fromDegrees(0, 0, 0), + Cesium.Cartesian3.fromDegrees(0.5, 0, 0), + ], + widthPx: 2, + mode: '3d', + depthFailColor: [1, 0, 0, 1], + style: { kind: 'solid', color: [1, 0, 0, 1] }, + }, + ]); + const plain = find(); + frame(); + assert.equal(plain.show, true, 'not culled by the overlay it was'); + set.dispose(); + })); + +test('where the scene cannot drape, a segmented draped line runs over its shown segments only', () => + withImageClasses(() => { + const scene = fakeScene(); + scene.frameState.context = { depthTexture: false }; + const { draw } = drawOver(scene); + const set = draw.lines({ id: 'trail', clampTo: 'tiles' }); + const at = (lon) => Cesium.Cartesian3.fromDegrees(lon, 0, 0); + const positions = [at(0), at(0.01), at(0.02), at(0.03)]; + const red = [1, 0, 0, 1]; + const find = () => { + const all = []; + const walk = (p) => { + all.push(p); + if (typeof p?.get === 'function' && Number.isFinite(p.length)) + for (let i = 0; i < p.length; i++) walk(p.get(i)); + }; + walk(scene.added[0]); + return all.find( + (p) => p instanceof Cesium.Primitive && p.depthFailAppearance, + ); + }; + set.set([ + { + id: 'trail', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: red }, + segmentColors: [red, red, red], + segmentShow: [true, true, false], + }, + ]); + const line = find(); + assert.ok(line, 'drawn over the surface'); + const drawn = line.geometryInstances.geometry._positions; + assert.equal(drawn.length, 3, 'up to its last shown segment'); + assert.ok(Cesium.Cartesian3.equals(drawn[2], positions[2])); + set.set([ + { + id: 'trail', + positions, + widthPx: 2, + mode: 'draped', + style: { kind: 'solid', color: red }, + segmentColors: [red, red, red], + segmentShow: [false, false, false], + }, + ]); + assert.equal(find()?.show ?? false, false, 'hidden with none shown'); + set.dispose(); + })); + test('revealFraction draws a line up to that fraction of its length, and changes in place', () => withImageClasses(() => { const { scene, draw } = drawOver(); diff --git a/src/render/cesium/surfaceState.js b/src/render/cesium/surfaceState.js deleted file mode 100644 index d8ee9da5c..000000000 --- a/src/render/cesium/surfaceState.js +++ /dev/null @@ -1,98 +0,0 @@ -/** - * @module render/cesium/surfaceState - * - * What a layer that samples heights off the drawn surface, or drapes lines - * on it, needs to know of it and the renderer contract cannot say: whether - * any 3D tileset is drawn (the globe port's settle states hold for none), - * which surface it is (the contract names no surface identity), and - * whether lines can be draped at all. Read off the Cesium scene. - */ -import * as Cesium from 'cesium'; - -/** - * Whether the scene can drape lines on the surface: Cesium's ground - * polylines need depth textures. - * @param {object|undefined} viewer - */ -export function drapesLines(viewer) { - const scene = viewer?.scene; - return ( - Boolean(scene?.frameState) && - Cesium.GroundPolylinePrimitive.isSupported(scene) - ); -} - -/** - * Whether the drawn surface has loaded what is in view: the - * globe's tiles while it is shown, otherwise every shown 3D tileset (and - * there is one). - * @param {object|undefined} viewer - */ -export function surfaceTilesReady(viewer) { - const scene = viewer?.scene; - if (!scene) return false; - if (scene.globe?.show) return scene.globe.tilesLoaded !== false; - let found = false; - for (let i = 0; i < (scene.primitives?.length || 0); i++) { - const primitive = scene.primitives.get(i); - if (!primitive.show || typeof primitive.tilesLoaded !== 'boolean') continue; - found = true; - if (!primitive.tilesLoaded) return false; - } - return found; -} - -// Stable ids for the objects heights are sampled from (tilesets, terrain). -const surfaceIds = new WeakMap(); -let nextSurfaceId = 1; -const surfaceId = (object) => { - if (!object || typeof object !== 'object') return 0; - if (!surfaceIds.has(object)) surfaceIds.set(object, nextSurfaceId++); - return surfaceIds.get(object); -}; - -/** - * Name what heights are sampled against: the terrain provider when the globe - * is shown, otherwise the set of visible 3D tilesets. A map-provider switch - * changes it and invalidates every cached height. - * @param {object|undefined} viewer - */ -const surfaceKeys = new WeakMap(); -export function surfaceKey(viewer) { - const scene = viewer?.scene; - if (!scene) return ''; - let state = surfaceKeys.get(scene); - if (!state) { - state = { globe: null, terrain: null, tiles: [], key: '' }; - surfaceKeys.set(scene, state); - } - const globe = Boolean(scene.globe?.show); - const terrain = globe ? scene.globe.terrainProvider : null; - let changed = state.globe !== globe || state.terrain !== terrain; - let count = 0; - if (!globe) { - for (let i = 0; i < (scene.primitives?.length || 0); i++) { - const primitive = scene.primitives.get(i); - if (!primitive?.show || typeof primitive.tilesLoaded !== 'boolean') - continue; - if (state.tiles[count] !== primitive) { - state.tiles[count] = primitive; - changed = true; - } - count++; - } - } - if (count !== state.tiles.length) { - state.tiles.length = count; - changed = true; - } - if (changed) { - state.globe = globe; - state.terrain = terrain; - // Allocate only when the actual map surface changes, never per frame. - state.key = globe - ? `globe:${surfaceId(terrain)}` - : `tiles:${state.tiles.map(surfaceId).join(',')}`; - } - return state.key; -} diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index eec8e3b92..958491cd8 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -7,7 +7,6 @@ "src/cyberSonarGpu.js", "src/cyberSonarScene.js", "src/data/geoImportPins.js", - "src/layers/traffic/rendering.js", "src/layers/weather/shellRendering.js", "src/layers/wind/gpuRendering.js", "src/layers/wind/relief.js", @@ -17,8 +16,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..808235462 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -123,9 +123,16 @@ 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', + // Its dots and heat-lines draw through `drawOf`; it reads the eye, the + // surface (its identity and whether it has loaded) and heights through + // the camera, globe and query ports. + './layers/traffic', + // It configures the sources of layers, the traffic layer's among them, + // that draw and read the surface through the ports alone. + './application/sources', ]); /** @@ -153,6 +160,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/fakeSceneSurface.mjs b/src/testSupport/fakeSceneSurface.mjs index 895c92db8..c53f073bd 100644 --- a/src/testSupport/fakeSceneSurface.mjs +++ b/src/testSupport/fakeSceneSurface.mjs @@ -8,7 +8,9 @@ * scene's `sampleHeight` where `sampleHeightSupported`), `project` * (`SceneTransforms.worldToWindowCoordinates`, which a test may mock), * `pickPosition` (the scene's), and null for every other pick. - * - globe: `isGlobeVisible` from `globe.show`. + * - globe: `isGlobeVisible` from `globe.show`; `isSettled('surface')` and + * `surfaceVersion` as the Cesium port reads them, off the double's globe + * and its primitives that say whether their tiles have loaded. * - camera (`withCamera`): `pose().position` from `camera.positionCartographic`, * `matrices()` from `camera.viewMatrix` and `frustum.projectionMatrix` * (undefined without them). @@ -22,6 +24,64 @@ import { fakeDrawPort } from './fakeDrawPort.mjs'; const carto = ({ lon, lat }) => Cesium.Cartographic.fromDegrees(lon, lat); const ecef = (p) => (p ? { x: p.x, y: p.y, z: p.z } : null); +/** + * The double's tilesets: its shown primitives that say whether their tiles + * have loaded. + */ +function* shownTilesets(s) { + const primitives = s.primitives; + for (let i = 0; i < (primitives?.length || 0); i++) { + const primitive = primitives.get(i); + if ( + primitive?.show && + !primitive.isDestroyed?.() && + typeof primitive.tilesLoaded === 'boolean' + ) + yield primitive; + } +} + +/** `isSettled('surface')` as the Cesium globe port answers it. */ +function surfaceLoaded(s) { + if (s.globe?.show) return s.globe.tilesLoaded !== false; + let found = false; + for (const tileset of shownTilesets(s)) { + found = true; + if (!tileset.tilesLoaded) return false; + } + return found; +} + +// `surfaceVersion` as the Cesium globe port keeps it: bumped when the globe +// is shown or hidden, its terrain swapped, or the set of shown tilesets +// changes (whether or not the globe is shown). +const versions = new WeakMap(); +let lastVersion = 0; +function surfaceVersion(s) { + let seen = versions.get(s); + if (!seen) { + seen = { globe: null, terrain: null, tiles: new Set(), version: 0 }; + versions.set(s, seen); + } + const globe = Boolean(s.globe?.show); + const terrain = s.globe?.terrainProvider ?? null; + let changed = + seen.version === 0 || seen.globe !== globe || seen.terrain !== terrain; + let count = 0; + for (const tileset of shownTilesets(s)) { + count++; + if (!seen.tiles.has(tileset)) changed = true; + } + if (count !== seen.tiles.size) changed = true; + if (changed) { + seen.globe = globe; + seen.terrain = terrain; + seen.tiles = new Set(shownTilesets(s)); + seen.version = ++lastVersion; + } + return seen.version; +} + /** The surface ports over `viewer.scene`. */ export function sceneSurfacePorts(viewer, { withCamera = false } = {}) { const scene = () => viewer.scene ?? {}; @@ -55,7 +115,11 @@ export function sceneSurfacePorts(viewer, { withCamera = false } = {}) { }; const ports = { query, - globe: { isGlobeVisible: () => Boolean(scene().globe?.show) }, + globe: { + isGlobeVisible: () => Boolean(scene().globe?.show), + isSettled: (kind) => kind !== 'surface' || surfaceLoaded(scene()), + surfaceVersion: () => surfaceVersion(scene()), + }, frame: { on(phase, cb) { const event = phase === 'postRender' ? scene().postRender : null; 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, });