diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index 20641b98f..aad5932ec 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -3473,6 +3473,7 @@ "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -4243,6 +4244,7 @@ "src/layers/perimeters/inciweb.js", "src/app/layers/gnss.js", "src/layers/gnss/index.js", + "src/geo/rectangle.js", "src/layers/gnss/source.js", "src/layers/gnss/records.js", "src/app/layers/ghostMaps.js", @@ -5382,6 +5384,11 @@ "exports": ["./layers/gnss"], "modules": [ "src/layers/gnss/index.js", + "src/render/color.js", + "src/geo/rectangle.js", + "src/geo/ellipsoid.js", + "src/geo/vector.js", + "src/render/rendererOf.js", "src/sources/httpBody.js", "src/i18n/marker.js", "src/layers/gnss/source.js", diff --git a/scripts/qa-gnss.mjs b/scripts/qa-gnss.mjs index 41933141e..7e4186bf7 100644 --- a/scripts/qa-gnss.mjs +++ b/scripts/qa-gnss.mjs @@ -9,7 +9,7 @@ * stub that route in the page so they are deterministic. * * (i) LIVE — over Poland and the southern Baltic the layer settles with no error, - * one geometry per cell and legend band counts that sum to the cell + * its cells drawn and legend band counts that sum to the cell * count; cells are required only when the returned rows, binned * with the layer's own rules, reach the per-cell minimum (live * traffic varies by hour). Requires a non-stale response no older than 60 s. @@ -24,7 +24,7 @@ * CAMERA/GLOBE verify automatic sampling and the screen-centre anchor. * (iii) FAILURE — the route stubbed to 502: stats.error is set and the * cells already on the globe are kept. - * (iv) DISABLE — owned ground primitives are hidden. + * (iv) DISABLE — the cells' ground primitives are hidden. * (v) KEYBOARD — the row's toggle button, focused, turns the layer on * with Enter and off with Space, keeps focus and names its state. * (vi) VIEWPORT — at a 390x844 phone viewport the open row and its legend @@ -114,10 +114,34 @@ async function boot(page, { lon, lat, height }) { ); } +/** + * In the page: the GNSS cells' ground primitives, each with the collection + * drawing it. The layer draws them through the renderer's draw port as + * ground fills that never take part in picks, the only such fills the app + * draws, so they are found by that. + */ +function gnssGround() { + const out = []; + const walk = (collection) => { + for (let i = 0; i < collection.length; i++) { + const item = collection.get(i); + if (typeof item?.length === 'number' && typeof item.get === 'function') + walk(item); + else if ( + item?.allowPicking === false && + item.classificationType !== undefined + ) + out.push({ primitive: item, host: collection }); + } + }; + walk(window.__godsEyeView.viewer.scene.primitives); + return out; +} + /** Enable (or refresh) the layer and poll until it settles. */ async function enableAndSettle(page, { refresh = false } = {}) { return page.evaluate( - async (id, again) => { + async (id, again, findGround) => { const dm = window.__godsEyeView.dataManager; const layer = dm.layers.get(id).module; if (again) await dm.refreshLayer(id); @@ -129,22 +153,21 @@ async function enableAndSettle(page, { refresh = false } = {}) { const rowName = document.querySelector(`[data-layer-id="${id}"] .data-name`) ?.textContent ?? ''; - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); + // eslint-disable-next-line no-new-func + const ground = new Function(`return (${findGround})()`)(); return { stats, legend, blurb, rowName, name: layer.name, - entities: ds?.get(0)?.geometryInstances.length ?? 0, - shown: ds?.show ?? null, + drawn: ground.length > 0, + shown: ground[0]?.host.show ?? null, }; }, LAYER_ID, refresh, + String(gnssGround), ); } @@ -184,31 +207,21 @@ async function shoot(page, name) { await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) }); } -/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */ -function cellStates(id) { - const { viewer } = window.__godsEyeView; - const all = viewer.scene.groundPrimitives; - const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - ); - if (!ds?.length) return []; - return [ds.get(0).ready ? 0 : 1]; -} +/** Build state of every GNSS ground primitive: DONE = 0, PENDING = 1. */ +const cellStates = `() => (${gnssGround})().map(({ primitive }) => (primitive.ready ? 0 : 1))`; /** Wait until every GNSS cell's ground rectangle has finished building. */ async function waitForBuiltCells(page, timeoutMs = 60000) { const built = await page - .waitForFunction( - `(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`, - { timeout: timeoutMs, polling: 250 }, - ) + .waitForFunction(`(${cellStates})().every((state) => state === 0)`, { + timeout: timeoutMs, + polling: 250, + }) .then( () => true, () => false, ); - const states = await page.evaluate( - `(${cellStates})(${JSON.stringify(LAYER_ID)})`, - ); + const states = await page.evaluate(`(${cellStates})()`); return { built, detail: `states=${JSON.stringify(states)}` }; } @@ -417,9 +430,9 @@ async function main() { } const expectedCells = binGnssCells(expectedStore).length; record( - 'LIVE: no error, one geometry per cell', - !l.stats.error && l.entities === l.stats.count, - `cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`, + 'LIVE: no error, cells drawn when there are any', + !l.stats.error && l.drawn === l.stats.count > 0, + `cells=${l.stats.count} drawn=${l.drawn} error=${JSON.stringify(l.stats.error)}`, ); if (expectedCells > 0) { record( @@ -463,8 +476,8 @@ async function main() { f.legend.find(({ label }) => label.startsWith(prefix))?.count; record( 'BANDS: 4 cells shown, the 2-aircraft cell withheld', - f.stats.count === 4 && f.entities === 4, - `cells=${f.stats.count} entities=${f.entities}`, + f.stats.count === 4 && f.drawn, + `cells=${f.stats.count} drawn=${f.drawn}`, ); record( 'BANDS: 5/10 is high, 2/30 is medium, 1/3 and 0/4 are low', @@ -769,20 +782,22 @@ async function main() { const e = await enableAndSettle(page, { refresh: true }); record( 'FAILURE: error surfaced, cells kept', - Boolean(e.stats.error) && e.stats.count === 4 && e.entities === 4, + Boolean(e.stats.error) && e.stats.count === 4 && e.drawn, `error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`, ); await shoot(page, 'failure'); // ── (iv) DISABLE ────────────────────────────────────────────────────── console.log('\n(iv) DISABLE...'); - const shown = await page.evaluate(async (id) => { - await window.__godsEyeView.dataManager.setEnabled(id, false); - const all = window.__godsEyeView.viewer.scene.groundPrimitives; - return Array.from({ length: all.length }, (_, i) => all.get(i)).find( - (item) => item.id === id, - )?.show; - }, LAYER_ID); + const shown = await page.evaluate( + async (id, findGround) => { + await window.__godsEyeView.dataManager.setEnabled(id, false); + // eslint-disable-next-line no-new-func + return new Function(`return (${findGround})()`)()[0]?.host.show; + }, + LAYER_ID, + String(gnssGround), + ); record('DISABLE: data source hidden', shown === false, `show=${shown}`); await shoot(page, 'disabled'); @@ -948,8 +963,8 @@ async function main() { const old = await enableAndSettle(aged, {}); record( 'AGE: a snapshot observed 31 min ago adds no cells and is not an error', - old.stats.count === 0 && old.entities === 0 && !old.stats.error, - `cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`, + old.stats.count === 0 && !old.drawn && !old.stats.error, + `cells=${old.stats.count} drawn=${old.drawn} error=${JSON.stringify(old.stats.error)}`, ); await aged.evaluate(() => { window.__gnssQaAgeMs = 29 * 60_000; @@ -957,8 +972,8 @@ async function main() { const recent = await enableAndSettle(aged, { refresh: true }); record( 'AGE: the same snapshot observed 29 min ago is still inside the window', - recent.stats.count === 4 && recent.entities === 4, - `cells=${recent.stats.count} entities=${recent.entities}`, + recent.stats.count === 4 && recent.drawn, + `cells=${recent.stats.count} drawn=${recent.drawn}`, ); await aged.close(); record( diff --git a/src/geo/rectangle.js b/src/geo/rectangle.js new file mode 100644 index 000000000..7d941e461 --- /dev/null +++ b/src/geo/rectangle.js @@ -0,0 +1,23 @@ +/** + * @module geo/rectangle + * @description Geodetic rectangles `{west, south, east, north}` in radians, + * as the default renderer measures them: a rectangle whose east is less + * than its west crosses the antimeridian. + */ +import { TWO_PI, negativePiToPi } from './vector.js'; + +/** East-west extent, radians, across the antimeridian too. */ +export function rectangleWidth({ west, east }) { + return (east < west ? east + TWO_PI : east) - west; +} + +/** North-south extent, radians. */ +export const rectangleHeight = ({ south, north }) => north - south; + +/** The middle `{lon, lat}`, radians, across the antimeridian too. */ +export function rectangleCenter({ west, south, east, north }) { + return { + lon: negativePiToPi((west + (east < west ? east + TWO_PI : east)) / 2), + lat: (south + north) / 2, + }; +} diff --git a/src/geo/rectangle.test.mjs b/src/geo/rectangle.test.mjs new file mode 100644 index 000000000..accd277c2 --- /dev/null +++ b/src/geo/rectangle.test.mjs @@ -0,0 +1,70 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { rayEllipsoid, fromDegrees } from './ellipsoid.js'; +import { + rectangleCenter, + rectangleHeight, + rectangleWidth, +} from './rectangle.js'; + +const near = (a, b, eps = 1e-12) => + assert.ok(Math.abs(a - b) <= eps, `${a} != ${b}`); + +test('rectangle extents and middle match the default renderer, across the antimeridian too', () => { + for (const [w, s, e, n] of [ + [20, 40, 22, 42], + [170, -10, -170, 10], + [175, 40, -165, 42], + [-180, -90, 180, 90], + ]) { + const rect = Cesium.Rectangle.fromDegrees(w, s, e, n); + near(rectangleWidth(rect), Cesium.Rectangle.computeWidth(rect)); + near(rectangleHeight(rect), Cesium.Rectangle.computeHeight(rect)); + const mine = rectangleCenter(rect); + const theirs = Cesium.Rectangle.center(rect); + near(mine.lon, theirs.longitude); + near(mine.lat, theirs.latitude); + } +}); + +test('a ray meets the ellipsoid where the default renderer says', () => { + const origin = fromDegrees(-97, 30, 2e7); + for (const target of [fromDegrees(-97, 30), fromDegrees(-90, 35)]) { + const d = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.subtract( + new Cesium.Cartesian3(target.x, target.y, target.z), + new Cesium.Cartesian3(origin.x, origin.y, origin.z), + new Cesium.Cartesian3(), + ), + new Cesium.Cartesian3(), + ); + const ray = new Cesium.Ray( + new Cesium.Cartesian3(origin.x, origin.y, origin.z), + d, + ); + const hit = Cesium.IntersectionTests.rayEllipsoid( + ray, + Cesium.Ellipsoid.WGS84, + ); + const theirs = Cesium.Ray.getPoint(ray, hit.start); + const mine = rayEllipsoid({ origin, direction: d }); + near(mine.x, theirs.x, 1e-6); + near(mine.y, theirs.y, 1e-6); + near(mine.z, theirs.z, 1e-6); + } + // Looking away, and from inside. + assert.equal( + rayEllipsoid({ + origin: fromDegrees(0, 0, 1e7), + direction: { x: 1, y: 0, z: 0 }, + }), + null, + 'pointing straight away misses', + ); + const inside = rayEllipsoid({ + origin: { x: 0, y: 0, z: 0 }, + direction: { x: 1, y: 0, z: 0 }, + }); + near(inside.x, 6378137, 1e-6); +}); diff --git a/src/layers/gnss/index.js b/src/layers/gnss/index.js index ba0e9ff5d..b8aeec267 100644 --- a/src/layers/gnss/index.js +++ b/src/layers/gnss/index.js @@ -1,4 +1,8 @@ -import * as Cesium from 'cesium'; +import { rayEllipsoid, toLonLatH } from '../../geo/ellipsoid.js'; +import { rectangleCenter } from '../../geo/rectangle.js'; +import { toDegrees, toRadians } from '../../geo/vector.js'; +import { drawOf, findCamera } from '../../render/rendererOf.js'; +import { hexColor } from '../../render/color.js'; import { formatNumber, msg, t } from '../../i18n/index.js'; import { translateFeedError } from '../../ui/statusText.js'; import { @@ -14,15 +18,11 @@ export * from './records.js'; export { createAdsbGnssSource } from './source.js'; /** - * GroundPrimitive allowPicking:false suppresses ids but still submits stencil - * commands in Cesium's pick pass, erasing picks of overlapping ground geometry. - * This fill participates only in rendering, so sibling polygons remain pickable. + * The draw set the cells are drawn in starts with this; each layer has its + * own (`gnss-integrity:1`, …), so several can share a renderer. */ -class GnssGroundFill extends Cesium.GroundPrimitive { - update(frameState) { - if (!frameState.passes.pick) super.update(frameState); - } -} +export const GNSS_SET_PREFIX = 'gnss-integrity'; +let instances = 0; /** Low stays visible over land so coverage reads apart from no data. */ const FILL_ALPHA = Object.freeze({ low: 0.3, medium: 0.42, high: 0.55 }); @@ -32,29 +32,41 @@ const LEVEL_LABELS = Object.freeze({ high: msg('Low-accuracy score > 10%'), }); -/** Degrees at the centre of the current view, or null before the camera settles. */ +/** The middle of a degree rectangle, across the antimeridian too. */ +function degreesCentre(rect) { + const { lon, lat } = rectangleCenter({ + west: toRadians(rect.west), + south: toRadians(rect.south), + east: toRadians(rect.east), + north: toRadians(rect.north), + }); + return { lon: toDegrees(lon), lat: toDegrees(lat) }; +} + +/** + * Degrees at the centre of the current view, or null before the camera + * settles: where the eye's line of sight (the ray through the screen + * centre) meets the ellipsoid, else the middle of the view rectangle, else + * the point under the eye. + */ export function defaultGnssViewAnchor(viewer) { - const canvas = viewer?.scene?.canvas; - const ellipsoid = viewer?.scene?.globe?.ellipsoid; + const camera = findCamera(viewer); + if (!camera) return null; + const pose = camera.pose(); // At globe scale the visible rectangle can be the whole world, whose // midpoint is unrelated to the place under the screen centre. - const centre = - canvas?.clientWidth > 0 && - canvas.clientHeight > 0 && - viewer.camera?.pickEllipsoid?.( - new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2), - ellipsoid, - ); - const rectangle = - !centre && viewer?.camera?.computeViewRectangle?.(ellipsoid); - const carto = centre - ? (ellipsoid || Cesium.Ellipsoid.WGS84).cartesianToCartographic(centre) + const centre = rayEllipsoid({ + origin: pose.position, + direction: pose.direction, + }); + const rectangle = !centre && camera.viewRectangle(); + const at = centre + ? toLonLatH(centre) : rectangle - ? Cesium.Rectangle.center(rectangle) - : viewer?.camera?.positionCartographic; - if (!carto) return null; - const latitude = Cesium.Math.toDegrees(carto.latitude); - const longitude = Cesium.Math.toDegrees(carto.longitude); + ? degreesCentre(rectangle) + : pose; + const latitude = at?.lat; + const longitude = at?.lon; return Number.isFinite(latitude) && Number.isFinite(longitude) ? { latitude, longitude } : null; @@ -81,7 +93,7 @@ export function createGnssIntegrityLayer({ ? requestedWindowMs : GNSS_WINDOW_MS; let _viewer = null; - let _primitives = null; + let _fills = null; let _request = null; let _enabled = false; let _cells = []; @@ -109,7 +121,7 @@ export function createGnssIntegrityLayer({ : null; function scheduleCameraRefresh() { - if (!_enabled || !_primitives) return; + if (!_enabled || !_fills) return; if (now() < _retryAt) return; const key = queryKey(viewAnchor(_viewer)); if (!key || key === _lastQueryKey) return; @@ -175,44 +187,22 @@ export function createGnssIntegrityLayer({ ); if (signature === _signature) return; _signature = signature; - _primitives.removeAll(); - if (_cells.length) { - _primitives.add( - new GnssGroundFill({ - geometryInstances: _cells.map( - (cell) => - new Cesium.GeometryInstance({ - id: `${layer.id}:${cell.id}`, - geometry: new Cesium.RectangleGeometry({ - rectangle: Cesium.Rectangle.fromDegrees( - cell.west, - cell.south, - cell.east, - cell.north, - ), - vertexFormat: Cesium.PerInstanceColorAppearance.VERTEX_FORMAT, - }), - attributes: { - color: Cesium.ColorGeometryInstanceAttribute.fromColor( - Cesium.Color.fromCssColorString( - GNSS_LEVEL_COLORS[cell.level], - ).withAlpha(FILL_ALPHA[cell.level]), - ), - }, - }), - ), - appearance: new Cesium.PerInstanceColorAppearance({ - flat: true, - translucent: true, - }), - classificationType: Cesium.ClassificationType.BOTH, - allowPicking: false, - // Retain the compact rectangle descriptors for inspection, not Entity visualizers. - releaseGeometryInstances: false, - }), - ); - } - _viewer?.scene?.requestRender?.(); + _fills.set( + _cells.map((cell) => ({ + id: `${layer.id}:${cell.id}`, + geometry: { + kind: 'rectangle', + rect: { + west: cell.west, + south: cell.south, + east: cell.east, + north: cell.north, + }, + }, + fill: hexColor(GNSS_LEVEL_COLORS[cell.level], FILL_ALPHA[cell.level]), + height: 'clampGround', + })), + ); } const layer = { @@ -231,25 +221,27 @@ export function createGnssIntegrityLayer({ init(viewer) { if (_viewer) throw new Error('GNSS integrity layer is already initialized'); + // The cells never take part in picks: ground geometry under them + // (another layer's polygons) stays pickable. + _fills = drawOf(viewer).shapes({ + id: `${GNSS_SET_PREFIX}:${++instances}`, + clampTo: 'both', + pickable: false, + show: false, + }); _viewer = viewer; - _primitives = new Cesium.PrimitiveCollection(); - _primitives.id = layer.id; - _primitives.show = false; - viewer.scene.groundPrimitives.add(_primitives); - _removeCameraEnd = viewer.camera?.moveEnd?.addEventListener( - scheduleCameraRefresh, - ); - _removeCameraChanged = viewer.camera?.changed?.addEventListener( - scheduleCameraRefresh, - ); + const camera = findCamera(viewer); + _removeCameraEnd = camera?.on('moveEnd', scheduleCameraRefresh) ?? null; + _removeCameraChanged = + camera?.on('changed', scheduleCameraRefresh) ?? null; }, enable() { _enabled = true; // Cells left from before a long disable must not reappear past the window. - if (_primitives) { + if (_fills) { expire(); - _primitives.show = true; + _fills.show = true; } }, @@ -263,11 +255,11 @@ export function createGnssIntegrityLayer({ _request?.abort(); _request = null; _enabled = false; - if (_primitives) _primitives.show = false; + if (_fills) _fills.show = false; }, async update(_viewerArg, { signal } = {}) { - if (!_enabled || !_primitives || signal?.aborted) return false; + if (!_enabled || !_fills || signal?.aborted) return false; if (now() < _retryAt) { expire(); scheduleRetry(); @@ -352,7 +344,7 @@ export function createGnssIntegrityLayer({ } }, - destroy(viewer = _viewer) { + destroy() { layer.disable(); _removeCameraEnd?.(); _removeCameraChanged?.(); @@ -361,10 +353,8 @@ export function createGnssIntegrityLayer({ _observations.clear(); _cells = []; _signature = null; - if (_primitives) { - viewer.scene.groundPrimitives.remove(_primitives); - _primitives = null; - } + _fills?.dispose(); + _fills = null; _viewer = null; _lastUpdate = null; _lastError = null; diff --git a/src/layers/gnss/ownership.test.mjs b/src/layers/gnss/ownership.test.mjs index 713e44889..c897cd204 100644 --- a/src/layers/gnss/ownership.test.mjs +++ b/src/layers/gnss/ownership.test.mjs @@ -1,9 +1,12 @@ import assert from 'node:assert/strict'; import test from 'node:test'; -import * as Cesium from 'cesium'; import { createGnssIntegrityLayer, defaultGnssViewAnchor } from './index.js'; import { LayerLifecycle } from '../../data/lifecycle.js'; import { layerFeedState } from '../../data/feedState.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { bindRenderer } from '../../render/rendererOf.js'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; const row = (hex, lat, degraded) => ({ hex, @@ -23,22 +26,12 @@ function harness( } = {}, ) { let anchor = initialAnchor; - const sources = []; - const viewer = { - camera: { moveEnd: new Cesium.Event(), changed: new Cesium.Event() }, - scene: { - globe: { show: true }, - groundPrimitives: { - add(value) { - sources.push(value); - }, - remove(value) { - sources.splice(sources.indexOf(value), 1); - value.destroy(); - }, - }, - }, - }; + const viewer = { scene: { globe: { show: true } } }; + const camera = fakeCameraPort(); + const { draw } = bindFakeDraw(viewer, { camera: camera.port }); + // The layer's one live set, or undefined once it is disposed. + const fills = () => + [...draw.sets.values()].find((record) => !record.disposed); let clock = 1_000; const anchors = []; const layer = createGnssIntegrityLayer({ @@ -59,7 +52,8 @@ function harness( if (initialize) layer.init(viewer); return { layer, - sources, + fills, + camera, anchors, viewer, advance(ms) { @@ -82,25 +76,61 @@ const threeHealthy = () => [ const flush = () => new Promise((resolve) => setImmediate(resolve)); test('a globe-wide rectangle uses the visible screen centre as the query anchor', () => { - const anchor = defaultGnssViewAnchor({ - scene: { - canvas: { clientWidth: 1000, clientHeight: 800 }, - globe: { ellipsoid: Cesium.Ellipsoid.WGS84 }, - }, - camera: { - pickEllipsoid(pixel) { - assert.deepEqual(pixel, new Cesium.Cartesian2(500, 400)); - return Cesium.Cartesian3.fromDegrees(-97, 30); - }, - computeViewRectangle: () => { - throw new Error('centre hit must not compute a rectangle'); + const viewer = {}; + // The eye high over (-97, 30), looking straight down. + const eye = fromDegrees(-97, 30, 2e7); + const ground = fromDegrees(-97, 30, 0); + const length = Math.hypot( + eye.x - ground.x, + eye.y - ground.y, + eye.z - ground.z, + ); + const camera = fakeCameraPort({ + pose: { + lon: 0, + lat: 0, + position: eye, + direction: { + x: (ground.x - eye.x) / length, + y: (ground.y - eye.y) / length, + z: (ground.z - eye.z) / length, }, }, }); + camera.port.viewRectangle = () => { + throw new Error('centre hit must not compute a rectangle'); + }; + bindRenderer(viewer, { camera: camera.port }); + const anchor = defaultGnssViewAnchor(viewer); assert.ok(Math.abs(anchor.latitude - 30) < 1e-8); assert.ok(Math.abs(anchor.longitude + 97) < 1e-8); }); +test('a line of sight that misses the globe falls back to the view rectangle, then the point under the eye', () => { + const viewer = {}; + // The eye over (10, 20), looking straight up. + const eye = fromDegrees(10, 20, 1e6); + const length = Math.hypot(eye.x, eye.y, eye.z); + const camera = fakeCameraPort({ + pose: { + lon: 10, + lat: 20, + position: eye, + direction: { x: eye.x / length, y: eye.y / length, z: eye.z / length }, + }, + }); + let rectangle = { west: 170, south: -10, east: -170, north: 10 }; + camera.port.viewRectangle = () => rectangle; + bindRenderer(viewer, { camera: camera.port }); + const across = defaultGnssViewAnchor(viewer); + assert.ok(Math.abs(across.latitude) < 1e-8); + assert.ok(Math.abs(Math.abs(across.longitude) - 180) < 1e-8); + rectangle = null; + const under = defaultGnssViewAnchor(viewer); + assert.ok(Math.abs(under.latitude - 20) < 1e-8); + assert.ok(Math.abs(under.longitude - 10) < 1e-8); +}); + test('pan and zoom refresh through the manager without toggling; nearby changes are coalesced', async (t) => { t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }); let calls = 0; @@ -118,9 +148,9 @@ test('pan and zoom refresh through the manager without toggling; nearby changes manager.subscribe((change) => changes.push(change.type)); await manager.setEnabled(h.layer.id, true); h.setAnchor({ latitude: 54, longitude: 19 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.setAnchor({ latitude: 55, longitude: 20 }); - h.viewer.camera.moveEnd.raiseEvent(); + h.camera.emit('moveEnd'); h.advance(2500); t.mock.timers.tick(2500); await flush(); @@ -137,14 +167,14 @@ test('pan and zoom refresh through the manager without toggling; nearby changes }); assert.match(h.layer.getRowControls().info, /Regional sample.*250 nm radius/); h.setAnchor({ latitude: 55.1, longitude: 20.1 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.advance(5000); t.mock.timers.tick(5000); await flush(); assert.equal(calls, 2, 'nearby views reuse the same query region'); await manager.destroyAll(); - assert.equal(h.viewer.camera.moveEnd.numberOfListeners, 0); - assert.equal(h.viewer.camera.changed.numberOfListeners, 0); + assert.equal(h.camera.listenerCount('moveEnd'), 0); + assert.equal(h.camera.listenerCount('changed'), 0); }); test('movement during a pending refresh follows up at the newest view; disable cancels queued work', async (t) => { @@ -162,12 +192,12 @@ test('movement during a pending refresh follows up at the newest view; disable c h.layer.enable(); await h.layer.update(); h.setAnchor({ latitude: 54, longitude: 19 }); - h.viewer.camera.moveEnd.raiseEvent(); + h.camera.emit('moveEnd'); h.advance(2500); t.mock.timers.tick(2500); await flush(); h.setAnchor({ latitude: 35, longitude: 140 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.advance(2500); t.mock.timers.tick(2500); await flush(); @@ -180,7 +210,7 @@ test('movement during a pending refresh follows up at the newest view; disable c assert.equal(calls.length, 3); assert.deepEqual(calls.at(-1), { latitude: 35, longitude: 140 }); h.setAnchor({ latitude: 10, longitude: 10 }); - h.viewer.camera.moveEnd.raiseEvent(); + h.camera.emit('moveEnd'); h.layer.disable(); h.advance(5000); t.mock.timers.tick(5000); @@ -196,7 +226,7 @@ test('the layer requires a snapshot source and cannot be initialized twice', () }); test('an enabled refresh bins the snapshot into coloured ground cells', async () => { - const { layer, sources, anchors } = harness(async (anchor, { signal }) => { + const { layer, fills, anchors } = harness(async (anchor, { signal }) => { assert.deepEqual(anchor, { latitude: 50, longitude: 30 }); assert.ok(signal instanceof AbortSignal); return { @@ -213,13 +243,17 @@ test('an enabled refresh bins the snapshot into coloured ground cells', async () assert.equal(await layer.update(), false, 'disabled layers do not fetch'); assert.equal(anchors.length, 0); layer.enable(); - assert.equal(sources[0].show, true); + assert.equal(fills().show, true); assert.equal(await layer.update(), true); - const entities = sources[0].get(0).geometryInstances; - assert.equal(entities.length, 1, 'the one-aircraft cell is withheld'); - assert.equal(entities[0].id, 'gnss-integrity:280:420'); - assert.ok(entities[0].geometry instanceof Cesium.RectangleGeometry); - assert.equal(sources[0].get(0).allowPicking, false); + const cells = [...fills().items.values()]; + assert.equal(cells.length, 1, 'the one-aircraft cell is withheld'); + assert.equal(cells[0].id, 'gnss-integrity:280:420'); + assert.deepEqual(cells[0].geometry, { + kind: 'rectangle', + rect: { west: 30, south: 50, east: 30.5, north: 50.5 }, + }); + assert.equal(cells[0].height, 'clampGround'); + assert.equal(fills().spec.pickable, false, 'cells never take part in picks'); const stats = layer.getStats(); assert.equal(stats.count, 1); assert.equal(stats.error, null); @@ -272,7 +306,7 @@ test('the visible layer leads with low navigation accuracy and exposes its prove test('a failed refresh keeps the last cells and reports the error', async () => { let fail = false; - const { layer, sources } = harness(async () => { + const { layer, fills } = harness(async () => { if (fail) throw new Error('adsb.lol HTTP 502'); return { rows: [ @@ -288,14 +322,14 @@ test('a failed refresh keeps the last cells and reports the error', async () => assert.equal(layer.getStats().stale, true); fail = true; assert.equal(await layer.update(), true); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 1); + assert.equal(fills().items.size, 1); assert.equal(layer.getStats().error, 'adsb.lol HTTP 502'); assert.equal(layer.getStats().count, 1); }); test('observations expire with the window, and disable aborts the request in flight', async () => { let pending; - const { layer, sources, advance } = harness( + const { layer, fills, advance } = harness( (anchor, { signal }) => new Promise((resolve, reject) => { pending = { resolve }; @@ -315,17 +349,17 @@ test('observations expire with the window, and disable aborts the request in fli pending.resolve({ rows: [] }); assert.equal(await result, true); assert.equal(layer.getStats().count, 0); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); + assert.equal(fills().items.size, 0); result = layer.update(); layer.disable(); assert.equal(await result, false); - assert.equal(sources[0].show, false); + assert.equal(fills().show, false); }); test('no view anchor means no request, and destroy releases the data source', async () => { let calls = 0; - const { layer, sources } = harness( + const { layer, fills } = harness( async () => { calls += 1; return { rows: [] }; @@ -341,13 +375,13 @@ test('no view anchor means no request, and destroy releases the data source', as assert.equal(calls, 0); assert.equal(layer.getStats().error, null); layer.destroy(); - assert.equal(sources.length, 0); + assert.equal(fills(), undefined, 'destroy disposes the set'); assert.equal(layer.getStats().count, 0); }); test('a replayed stale snapshot keeps its observation age and expires on time', async () => { // The proxy keeps answering with the snapshot it observed at t=1000. - const { layer, sources, advance, now } = harness(async () => ({ + const { layer, fills, advance, now } = harness(async () => ({ rows: threeHealthy(), ageMs: now() - 1_000, stale: true, @@ -369,12 +403,12 @@ test('a replayed stale snapshot keeps its observation age and expires on time', 0, 'the replay did not restart the window', ); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); + assert.equal(fills().items.size, 0); }); test('cells expire during prolonged fetch failures', async () => { let fail = false; - const { layer, sources, advance } = harness(async () => { + const { layer, fills, advance } = harness(async () => { if (fail) throw new Error('adsb.lol HTTP 502'); return { rows: threeHealthy() }; }); @@ -387,13 +421,13 @@ test('cells expire during prolonged fetch failures', async () => { advance(11 * MIN); assert.equal(await layer.update(), true); assert.equal(layer.getStats().count, 0); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); + assert.equal(fills().items.size, 0); assert.equal(layer.getStats().error, 'adsb.lol HTTP 502'); }); test('cells expire while no view anchor is available', async () => { let calls = 0; - const { layer, sources, advance, setAnchor } = harness(async () => { + const { layer, fills, advance, setAnchor } = harness(async () => { calls += 1; return { rows: threeHealthy() }; }); @@ -407,36 +441,36 @@ test('cells expire while no view anchor is available', async () => { assert.equal(await layer.update(), true); assert.equal(calls, 1, 'no anchor means no request'); assert.equal(layer.getStats().count, 0); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); + assert.equal(fills().items.size, 0); assert.equal(layer.getStats().error, null); }); test('re-enabling after a long disable does not show cells past the window', async () => { - const { layer, sources, advance } = harness(async () => ({ + const { layer, fills, advance } = harness(async () => ({ rows: threeHealthy(), })); layer.enable(); await layer.update(); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 1); + assert.equal(fills().items.size, 1); layer.disable(); advance(31 * MIN); layer.enable(); assert.equal(layer.getStats().count, 0); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); + assert.equal(fills().items.size, 0); }); const threeCells = () => ({ rows: [row('a1', 50.1, true), row('a2', 50.1, true), row('a3', 50.2, false)], }); -test('an identical snapshot leaves the drawn entities untouched', async () => { - const { layer, sources } = harness(async () => threeCells()); +test('an identical snapshot draws nothing again', async () => { + const { layer, fills } = harness(async () => threeCells()); layer.enable(); await layer.update(); - const first = sources[0].get(0); + const writes = fills().writes; await layer.update(); - assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 1); - assert.equal(sources[0].get(0), first); + assert.equal(fills().items.size, 1); + assert.equal(fills().writes, writes); }); test('an initial feed failure stays enabled, reports unavailable, and recovers automatically', async (t) => { @@ -496,7 +530,7 @@ test('provider cooldown is preserved across movement and toggling; disable cance h.layer.enable(); await h.layer.update(); h.setAnchor({ latitude: 10, longitude: 20 }); - h.viewer.camera.moveEnd.raiseEvent(); + h.camera.emit('moveEnd'); h.advance(30000); t.mock.timers.tick(30000); await flush(); @@ -583,7 +617,7 @@ test('GERMAN: camera debounce and minimum request gap are pinned', async (t) => h.layer.enable(); await h.layer.update(); h.setAnchor({ latitude: 51, longitude: 31 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.advance(2499); t.mock.timers.tick(2499); await flush(); @@ -594,7 +628,7 @@ test('GERMAN: camera debounce and minimum request gap are pinned', async (t) => assert.equal(calls, 2); h.advance(3000); h.setAnchor({ latitude: 52, longitude: 32 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.advance(599); t.mock.timers.tick(599); await flush(); @@ -619,7 +653,7 @@ test('camera movement during initial activation waits for acquisition before fol h.layer.enable(); const initial = h.layer.update(); h.setAnchor({ latitude: 51, longitude: 31 }); - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); h.advance(2500); t.mock.timers.tick(2500); await flush(); @@ -658,7 +692,7 @@ test('monotonic camera scheduling is unaffected by wall-clock rollback', async ( wall -= 3600000; mono = 3000; anchor = { latitude: 51, longitude: 31 }; - h.viewer.camera.changed.raiseEvent(); + h.camera.emit('changed'); mono += 600; t.mock.timers.tick(600); await flush(); @@ -666,35 +700,34 @@ test('monotonic camera scheduling is unaffected by wall-clock rollback', async ( layer.destroy(); }); -test('GNSS fill emits no pick-pass commands but keeps normal rendering', async (t) => { - const h = harness(async () => ({ rows: threeHealthy() })); - h.layer.enable(); - await h.layer.update(); - const fill = h.sources[0].get(0); - let updates = 0; - t.mock.method(Cesium.GroundPrimitive.prototype, 'update', () => updates++); - fill.update({ passes: { pick: true } }); - assert.equal(updates, 0); - fill.update({ passes: { render: true, pick: false } }); - assert.equal(updates, 1); - h.layer.destroy(); - assert.equal(fill.isDestroyed(), true); -}); - test('view anchor falls back to rectangle, then nadir, then no camera', () => { assert.equal(defaultGnssViewAnchor({}), null); - const viewer = { - camera: { - computeViewRectangle: () => Cesium.Rectangle.fromDegrees(20, 40, 22, 42), + const viewer = { scene: {} }; + // Looking away from the globe: the line of sight misses it. + const camera = fakeCameraPort({ + pose: { + lon: 21, + lat: 41, + position: fromDegrees(21, 41, 1e7), + direction: { x: 0, y: 0, z: 1 }, }, - }; + viewRectangle: { west: 20, south: 40, east: 22, north: 42 }, + }); + bindRenderer(viewer, { camera: camera.port }); const rectangleAnchor = defaultGnssViewAnchor(viewer); assert.ok(Math.abs(rectangleAnchor.latitude - 41) < 1e-10); assert.ok(Math.abs(rectangleAnchor.longitude - 21) < 1e-10); - viewer.camera = { - positionCartographic: Cesium.Cartographic.fromDegrees(21, 41), - }; + // Across the antimeridian, the middle is on it. + camera.setViewRectangle({ west: 170, south: 40, east: -170, north: 42 }); + assert.ok( + Math.abs(Math.abs(defaultGnssViewAnchor(viewer).longitude) - 180) < 1e-10, + ); + camera.setViewRectangle({ west: 175, south: 40, east: -165, north: 42 }); + assert.ok(Math.abs(defaultGnssViewAnchor(viewer).longitude + 175) < 1e-10); + camera.setViewRectangle(null); const nadirAnchor = defaultGnssViewAnchor(viewer); assert.ok(Math.abs(nadirAnchor.latitude - 41) < 1e-10); assert.ok(Math.abs(nadirAnchor.longitude - 21) < 1e-10); + camera.setPose({ lon: NaN, lat: NaN }); + assert.equal(defaultGnssViewAnchor(viewer), null, 'no settled camera'); }); diff --git a/src/layers/gnss/sourceErrorLocale.test.mjs b/src/layers/gnss/sourceErrorLocale.test.mjs index a09019164..fd485f702 100644 --- a/src/layers/gnss/sourceErrorLocale.test.mjs +++ b/src/layers/gnss/sourceErrorLocale.test.mjs @@ -2,9 +2,10 @@ // card's info line shows them in the UI language, the HTTP form included. import assert from 'node:assert/strict'; import test from 'node:test'; -import * as Cesium from 'cesium'; import { setLocale } from '../../i18n/index.js'; import { createGnssIntegrityLayer } from './index.js'; +import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; +import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs'; async function failedLayer(message) { const layer = createGnssIntegrityLayer({ @@ -20,13 +21,9 @@ async function failedLayer(message) { now: () => 1_000, monotonicNow: () => 1_000, }); - layer.init({ - camera: { moveEnd: new Cesium.Event(), changed: new Cesium.Event() }, - scene: { - globe: { show: true }, - groundPrimitives: { add() {}, remove() {} }, - }, - }); + const viewer = { scene: { globe: { show: true } } }; + bindFakeDraw(viewer, { camera: fakeCameraPort().port }); + layer.init(viewer); layer.enable(); await layer.update(); return layer; diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index 1125c91d3..ae4ab4761 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -800,3 +800,54 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o layer.destroy(); assert.equal(scene.added.length, 0); }); + +test('the GNSS layer draws its cells as ground fills that stay out of the pick pass', async (t) => { + const { createGnssIntegrityLayer } = + await import('../../layers/gnss/index.js'); + const scene = fakeScene(); + const viewer = { scene }; + const row = (hex, lat, degraded) => ({ + hex, + lat, + lon: 30.2, + nic: degraded ? 0 : 8, + nacp: degraded ? 0 : 10, + gpsLost: false, + degraded, + }); + const layer = createGnssIntegrityLayer({ + source: { + getSnapshot: async () => ({ + ageMs: 0, + rows: [row('a1', 50.1, true), row('a2', 50.1, true), row('a3', 50.2)], + }), + }, + viewAnchor: () => ({ latitude: 50, longitude: 30 }), + }); + layer.init(viewer); + layer.enable(); + assert.equal(await layer.update(), true); + const host = scene.added[0]; + const grounds = []; + for (let i = 0; i < host.length; i++) + if (host.get(i) instanceof Cesium.GroundPrimitive) + grounds.push(host.get(i)); + assert.equal(grounds.length, 1); + const [fill] = grounds; + assert.equal(fill.allowPicking, false); + assert.equal(fill.classificationType, Cesium.ClassificationType.BOTH); + const [instance] = fill.geometryInstances; + assert.ok(instance.geometry instanceof Cesium.RectangleGeometry); + assert.equal(instance.id.id, 'gnss-integrity:280:420'); + // A ground primitive draws its stencil in the pick pass even unpickable, + // erasing picks of ground geometry under it; these skip that pass. + let updates = 0; + t.mock.method(Cesium.GroundPrimitive.prototype, 'update', () => updates++); + fill.update({ passes: { pick: true } }); + assert.equal(updates, 0); + fill.update({ passes: { render: true, pick: false } }); + assert.equal(updates, 1); + t.mock.restoreAll(); + layer.destroy(); + assert.equal(scene.added.length, 0); +}); diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 2fd40e8ec..1e18ab80c 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -84,7 +84,6 @@ "src/layers/flights/testing.js", "src/layers/flights/tracking.js", "src/layers/ghostMaps/index.js", - "src/layers/gnss/index.js", "src/layers/installations/controls.js", "src/layers/installations/lifecycle.js", "src/layers/installations/model.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index d054518e0..c321e3215 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -67,6 +67,7 @@ const FALLS_BACK = new Set(['src/data/followed.js']); const DRAW_FROM_CALLER = new Set([ './layers/earthquakes', './layers/bikeshare', + './layers/gnss', './layers/perimeters', ]);