Draw GNSS integrity cells through the renderer's draw port

Cells are clamped rectangle fills in one draw set per layer
(gnss-integrity:N), made with pickable: false so they never hide what is
under them from clicks, as before. The view anchor comes from the camera
port: where the line of sight meets the ellipsoid, else the middle of the
view rectangle, else the point under the eye. Re-anchoring follows the
camera port's moveEnd and changed events. The ray-ellipsoid intersection
moves from the stub renderer into geo/ellipsoid.js for both to use, and
geo/rectangle.js adds the antimeridian-aware width, height and centre of
a radian rectangle. The layer leaves the allow-list; the QA script finds
the cells among the scene's unpickable ground primitives.
This commit is contained in:
Sameh Khamis committed 2026-11-06 20:30:33 -08:00
1 parent 3f9089eccb
commit 6f82f9cc9c
10 files changed
+418 -232

No files matched your search

+7
View File
@@ -3473,6 +3473,7 @@
"src/layers/perimeters/inciweb.js", "src/layers/perimeters/inciweb.js",
"src/app/layers/gnss.js", "src/app/layers/gnss.js",
"src/layers/gnss/index.js", "src/layers/gnss/index.js",
"src/geo/rectangle.js",
"src/layers/gnss/source.js", "src/layers/gnss/source.js",
"src/layers/gnss/records.js", "src/layers/gnss/records.js",
"src/app/layers/ghostMaps.js", "src/app/layers/ghostMaps.js",
@@ -4243,6 +4244,7 @@
"src/layers/perimeters/inciweb.js", "src/layers/perimeters/inciweb.js",
"src/app/layers/gnss.js", "src/app/layers/gnss.js",
"src/layers/gnss/index.js", "src/layers/gnss/index.js",
"src/geo/rectangle.js",
"src/layers/gnss/source.js", "src/layers/gnss/source.js",
"src/layers/gnss/records.js", "src/layers/gnss/records.js",
"src/app/layers/ghostMaps.js", "src/app/layers/ghostMaps.js",
@@ -5382,6 +5384,11 @@
"exports": ["./layers/gnss"], "exports": ["./layers/gnss"],
"modules": [ "modules": [
"src/layers/gnss/index.js", "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/sources/httpBody.js",
"src/i18n/marker.js", "src/i18n/marker.js",
"src/layers/gnss/source.js", "src/layers/gnss/source.js",
+58 -43
View File
@@ -9,7 +9,7 @@
* stub that route in the page so they are deterministic. * stub that route in the page so they are deterministic.
* *
* (i) LIVE — over Poland and the southern Baltic the layer settles with no error, * (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 * count; cells are required only when the returned rows, binned
* with the layer's own rules, reach the per-cell minimum (live * 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. * 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. * CAMERA/GLOBE verify automatic sampling and the screen-centre anchor.
* (iii) FAILURE — the route stubbed to 502: stats.error is set and the * (iii) FAILURE — the route stubbed to 502: stats.error is set and the
* cells already on the globe are kept. * 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 * (v) KEYBOARD — the row's toggle button, focused, turns the layer on
* with Enter and off with Space, keeps focus and names its state. * 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 * (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. */ /** Enable (or refresh) the layer and poll until it settles. */
async function enableAndSettle(page, { refresh = false } = {}) { async function enableAndSettle(page, { refresh = false } = {}) {
return page.evaluate( return page.evaluate(
async (id, again) => { async (id, again, findGround) => {
const dm = window.__godsEyeView.dataManager; const dm = window.__godsEyeView.dataManager;
const layer = dm.layers.get(id).module; const layer = dm.layers.get(id).module;
if (again) await dm.refreshLayer(id); if (again) await dm.refreshLayer(id);
@@ -129,22 +153,21 @@ async function enableAndSettle(page, { refresh = false } = {}) {
const rowName = const rowName =
document.querySelector(`[data-layer-id="${id}"] .data-name`) document.querySelector(`[data-layer-id="${id}"] .data-name`)
?.textContent ?? ''; ?.textContent ?? '';
const all = window.__godsEyeView.viewer.scene.groundPrimitives; // eslint-disable-next-line no-new-func
const ds = Array.from({ length: all.length }, (_, i) => all.get(i)).find( const ground = new Function(`return (${findGround})()`)();
(item) => item.id === id,
);
return { return {
stats, stats,
legend, legend,
blurb, blurb,
rowName, rowName,
name: layer.name, name: layer.name,
entities: ds?.get(0)?.geometryInstances.length ?? 0, drawn: ground.length > 0,
shown: ds?.show ?? null, shown: ground[0]?.host.show ?? null,
}; };
}, },
LAYER_ID, LAYER_ID,
refresh, refresh,
String(gnssGround),
); );
} }
@@ -184,31 +207,21 @@ async function shoot(page, name) {
await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) }); await page.screenshot({ path: path.join(SHOTS_DIR, `gnss-${name}.png`) });
} }
/** Bounding-sphere state of every GNSS cell: DONE = 0, PENDING = 1, FAILED = 2. */ /** Build state of every GNSS ground primitive: DONE = 0, PENDING = 1. */
function cellStates(id) { const cellStates = `() => (${gnssGround})().map(({ primitive }) => (primitive.ready ? 0 : 1))`;
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];
}
/** Wait until every GNSS cell's ground rectangle has finished building. */ /** Wait until every GNSS cell's ground rectangle has finished building. */
async function waitForBuiltCells(page, timeoutMs = 60000) { async function waitForBuiltCells(page, timeoutMs = 60000) {
const built = await page const built = await page
.waitForFunction( .waitForFunction(`(${cellStates})().every((state) => state === 0)`, {
`(${cellStates})(${JSON.stringify(LAYER_ID)}).every((state) => state === 0)`, timeout: timeoutMs,
{ timeout: timeoutMs, polling: 250 }, polling: 250,
) })
.then( .then(
() => true, () => true,
() => false, () => false,
); );
const states = await page.evaluate( const states = await page.evaluate(`(${cellStates})()`);
`(${cellStates})(${JSON.stringify(LAYER_ID)})`,
);
return { built, detail: `states=${JSON.stringify(states)}` }; return { built, detail: `states=${JSON.stringify(states)}` };
} }
@@ -417,9 +430,9 @@ async function main() {
} }
const expectedCells = binGnssCells(expectedStore).length; const expectedCells = binGnssCells(expectedStore).length;
record( record(
'LIVE: no error, one geometry per cell', 'LIVE: no error, cells drawn when there are any',
!l.stats.error && l.entities === l.stats.count, !l.stats.error && l.drawn === l.stats.count > 0,
`cells=${l.stats.count} entities=${l.entities} error=${JSON.stringify(l.stats.error)}`, `cells=${l.stats.count} drawn=${l.drawn} error=${JSON.stringify(l.stats.error)}`,
); );
if (expectedCells > 0) { if (expectedCells > 0) {
record( record(
@@ -463,8 +476,8 @@ async function main() {
f.legend.find(({ label }) => label.startsWith(prefix))?.count; f.legend.find(({ label }) => label.startsWith(prefix))?.count;
record( record(
'BANDS: 4 cells shown, the 2-aircraft cell withheld', 'BANDS: 4 cells shown, the 2-aircraft cell withheld',
f.stats.count === 4 && f.entities === 4, f.stats.count === 4 && f.drawn,
`cells=${f.stats.count} entities=${f.entities}`, `cells=${f.stats.count} drawn=${f.drawn}`,
); );
record( record(
'BANDS: 5/10 is high, 2/30 is medium, 1/3 and 0/4 are low', '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 }); const e = await enableAndSettle(page, { refresh: true });
record( record(
'FAILURE: error surfaced, cells kept', '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}`, `error=${JSON.stringify(e.stats.error)} cells=${e.stats.count}`,
); );
await shoot(page, 'failure'); await shoot(page, 'failure');
// ── (iv) DISABLE ────────────────────────────────────────────────────── // ── (iv) DISABLE ──────────────────────────────────────────────────────
console.log('\n(iv) DISABLE...'); console.log('\n(iv) DISABLE...');
const shown = await page.evaluate(async (id) => { const shown = await page.evaluate(
await window.__godsEyeView.dataManager.setEnabled(id, false); async (id, findGround) => {
const all = window.__godsEyeView.viewer.scene.groundPrimitives; await window.__godsEyeView.dataManager.setEnabled(id, false);
return Array.from({ length: all.length }, (_, i) => all.get(i)).find( // eslint-disable-next-line no-new-func
(item) => item.id === id, return new Function(`return (${findGround})()`)()[0]?.host.show;
)?.show; },
}, LAYER_ID); LAYER_ID,
String(gnssGround),
);
record('DISABLE: data source hidden', shown === false, `show=${shown}`); record('DISABLE: data source hidden', shown === false, `show=${shown}`);
await shoot(page, 'disabled'); await shoot(page, 'disabled');
@@ -948,8 +963,8 @@ async function main() {
const old = await enableAndSettle(aged, {}); const old = await enableAndSettle(aged, {});
record( record(
'AGE: a snapshot observed 31 min ago adds no cells and is not an error', '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, old.stats.count === 0 && !old.drawn && !old.stats.error,
`cells=${old.stats.count} entities=${old.entities} error=${JSON.stringify(old.stats.error)}`, `cells=${old.stats.count} drawn=${old.drawn} error=${JSON.stringify(old.stats.error)}`,
); );
await aged.evaluate(() => { await aged.evaluate(() => {
window.__gnssQaAgeMs = 29 * 60_000; window.__gnssQaAgeMs = 29 * 60_000;
@@ -957,8 +972,8 @@ async function main() {
const recent = await enableAndSettle(aged, { refresh: true }); const recent = await enableAndSettle(aged, { refresh: true });
record( record(
'AGE: the same snapshot observed 29 min ago is still inside the window', 'AGE: the same snapshot observed 29 min ago is still inside the window',
recent.stats.count === 4 && recent.entities === 4, recent.stats.count === 4 && recent.drawn,
`cells=${recent.stats.count} entities=${recent.entities}`, `cells=${recent.stats.count} drawn=${recent.drawn}`,
); );
await aged.close(); await aged.close();
record( record(
+23
View File
@@ -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,
};
}
+70
View File
@@ -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);
});
+77 -87
View File
@@ -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 { formatNumber, msg, t } from '../../i18n/index.js';
import { translateFeedError } from '../../ui/statusText.js'; import { translateFeedError } from '../../ui/statusText.js';
import { import {
@@ -14,15 +18,11 @@ export * from './records.js';
export { createAdsbGnssSource } from './source.js'; export { createAdsbGnssSource } from './source.js';
/** /**
* GroundPrimitive allowPicking:false suppresses ids but still submits stencil * The draw set the cells are drawn in starts with this; each layer has its
* commands in Cesium's pick pass, erasing picks of overlapping ground geometry. * own (`gnss-integrity:1`, …), so several can share a renderer.
* This fill participates only in rendering, so sibling polygons remain pickable.
*/ */
class GnssGroundFill extends Cesium.GroundPrimitive { export const GNSS_SET_PREFIX = 'gnss-integrity';
update(frameState) { let instances = 0;
if (!frameState.passes.pick) super.update(frameState);
}
}
/** Low stays visible over land so coverage reads apart from no data. */ /** 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 }); 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%'), 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) { export function defaultGnssViewAnchor(viewer) {
const canvas = viewer?.scene?.canvas; const camera = findCamera(viewer);
const ellipsoid = viewer?.scene?.globe?.ellipsoid; if (!camera) return null;
const pose = camera.pose();
// At globe scale the visible rectangle can be the whole world, whose // At globe scale the visible rectangle can be the whole world, whose
// midpoint is unrelated to the place under the screen centre. // midpoint is unrelated to the place under the screen centre.
const centre = const centre = rayEllipsoid({
canvas?.clientWidth > 0 && origin: pose.position,
canvas.clientHeight > 0 && direction: pose.direction,
viewer.camera?.pickEllipsoid?.( });
new Cesium.Cartesian2(canvas.clientWidth / 2, canvas.clientHeight / 2), const rectangle = !centre && camera.viewRectangle();
ellipsoid, const at = centre
); ? toLonLatH(centre)
const rectangle =
!centre && viewer?.camera?.computeViewRectangle?.(ellipsoid);
const carto = centre
? (ellipsoid || Cesium.Ellipsoid.WGS84).cartesianToCartographic(centre)
: rectangle : rectangle
? Cesium.Rectangle.center(rectangle) ? degreesCentre(rectangle)
: viewer?.camera?.positionCartographic; : pose;
if (!carto) return null; const latitude = at?.lat;
const latitude = Cesium.Math.toDegrees(carto.latitude); const longitude = at?.lon;
const longitude = Cesium.Math.toDegrees(carto.longitude);
return Number.isFinite(latitude) && Number.isFinite(longitude) return Number.isFinite(latitude) && Number.isFinite(longitude)
? { latitude, longitude } ? { latitude, longitude }
: null; : null;
@@ -81,7 +93,7 @@ export function createGnssIntegrityLayer({
? requestedWindowMs ? requestedWindowMs
: GNSS_WINDOW_MS; : GNSS_WINDOW_MS;
let _viewer = null; let _viewer = null;
let _primitives = null; let _fills = null;
let _request = null; let _request = null;
let _enabled = false; let _enabled = false;
let _cells = []; let _cells = [];
@@ -109,7 +121,7 @@ export function createGnssIntegrityLayer({
: null; : null;
function scheduleCameraRefresh() { function scheduleCameraRefresh() {
if (!_enabled || !_primitives) return; if (!_enabled || !_fills) return;
if (now() < _retryAt) return; if (now() < _retryAt) return;
const key = queryKey(viewAnchor(_viewer)); const key = queryKey(viewAnchor(_viewer));
if (!key || key === _lastQueryKey) return; if (!key || key === _lastQueryKey) return;
@@ -175,44 +187,22 @@ export function createGnssIntegrityLayer({
); );
if (signature === _signature) return; if (signature === _signature) return;
_signature = signature; _signature = signature;
_primitives.removeAll(); _fills.set(
if (_cells.length) { _cells.map((cell) => ({
_primitives.add( id: `${layer.id}:${cell.id}`,
new GnssGroundFill({ geometry: {
geometryInstances: _cells.map( kind: 'rectangle',
(cell) => rect: {
new Cesium.GeometryInstance({ west: cell.west,
id: `${layer.id}:${cell.id}`, south: cell.south,
geometry: new Cesium.RectangleGeometry({ east: cell.east,
rectangle: Cesium.Rectangle.fromDegrees( north: cell.north,
cell.west, },
cell.south, },
cell.east, fill: hexColor(GNSS_LEVEL_COLORS[cell.level], FILL_ALPHA[cell.level]),
cell.north, height: 'clampGround',
), })),
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?.();
} }
const layer = { const layer = {
@@ -231,25 +221,27 @@ export function createGnssIntegrityLayer({
init(viewer) { init(viewer) {
if (_viewer) if (_viewer)
throw new Error('GNSS integrity layer is already initialized'); 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; _viewer = viewer;
_primitives = new Cesium.PrimitiveCollection(); const camera = findCamera(viewer);
_primitives.id = layer.id; _removeCameraEnd = camera?.on('moveEnd', scheduleCameraRefresh) ?? null;
_primitives.show = false; _removeCameraChanged =
viewer.scene.groundPrimitives.add(_primitives); camera?.on('changed', scheduleCameraRefresh) ?? null;
_removeCameraEnd = viewer.camera?.moveEnd?.addEventListener(
scheduleCameraRefresh,
);
_removeCameraChanged = viewer.camera?.changed?.addEventListener(
scheduleCameraRefresh,
);
}, },
enable() { enable() {
_enabled = true; _enabled = true;
// Cells left from before a long disable must not reappear past the window. // Cells left from before a long disable must not reappear past the window.
if (_primitives) { if (_fills) {
expire(); expire();
_primitives.show = true; _fills.show = true;
} }
}, },
@@ -263,11 +255,11 @@ export function createGnssIntegrityLayer({
_request?.abort(); _request?.abort();
_request = null; _request = null;
_enabled = false; _enabled = false;
if (_primitives) _primitives.show = false; if (_fills) _fills.show = false;
}, },
async update(_viewerArg, { signal } = {}) { async update(_viewerArg, { signal } = {}) {
if (!_enabled || !_primitives || signal?.aborted) return false; if (!_enabled || !_fills || signal?.aborted) return false;
if (now() < _retryAt) { if (now() < _retryAt) {
expire(); expire();
scheduleRetry(); scheduleRetry();
@@ -352,7 +344,7 @@ export function createGnssIntegrityLayer({
} }
}, },
destroy(viewer = _viewer) { destroy() {
layer.disable(); layer.disable();
_removeCameraEnd?.(); _removeCameraEnd?.();
_removeCameraChanged?.(); _removeCameraChanged?.();
@@ -361,10 +353,8 @@ export function createGnssIntegrityLayer({
_observations.clear(); _observations.clear();
_cells = []; _cells = [];
_signature = null; _signature = null;
if (_primitives) { _fills?.dispose();
viewer.scene.groundPrimitives.remove(_primitives); _fills = null;
_primitives = null;
}
_viewer = null; _viewer = null;
_lastUpdate = null; _lastUpdate = null;
_lastError = null; _lastError = null;
+126 -93
View File
@@ -1,9 +1,12 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import * as Cesium from 'cesium';
import { createGnssIntegrityLayer, defaultGnssViewAnchor } from './index.js'; import { createGnssIntegrityLayer, defaultGnssViewAnchor } from './index.js';
import { LayerLifecycle } from '../../data/lifecycle.js'; import { LayerLifecycle } from '../../data/lifecycle.js';
import { layerFeedState } from '../../data/feedState.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) => ({ const row = (hex, lat, degraded) => ({
hex, hex,
@@ -23,22 +26,12 @@ function harness(
} = {}, } = {},
) { ) {
let anchor = initialAnchor; let anchor = initialAnchor;
const sources = []; const viewer = { scene: { globe: { show: true } } };
const viewer = { const camera = fakeCameraPort();
camera: { moveEnd: new Cesium.Event(), changed: new Cesium.Event() }, const { draw } = bindFakeDraw(viewer, { camera: camera.port });
scene: { // The layer's one live set, or undefined once it is disposed.
globe: { show: true }, const fills = () =>
groundPrimitives: { [...draw.sets.values()].find((record) => !record.disposed);
add(value) {
sources.push(value);
},
remove(value) {
sources.splice(sources.indexOf(value), 1);
value.destroy();
},
},
},
};
let clock = 1_000; let clock = 1_000;
const anchors = []; const anchors = [];
const layer = createGnssIntegrityLayer({ const layer = createGnssIntegrityLayer({
@@ -59,7 +52,8 @@ function harness(
if (initialize) layer.init(viewer); if (initialize) layer.init(viewer);
return { return {
layer, layer,
sources, fills,
camera,
anchors, anchors,
viewer, viewer,
advance(ms) { advance(ms) {
@@ -82,25 +76,61 @@ const threeHealthy = () => [
const flush = () => new Promise((resolve) => setImmediate(resolve)); const flush = () => new Promise((resolve) => setImmediate(resolve));
test('a globe-wide rectangle uses the visible screen centre as the query anchor', () => { test('a globe-wide rectangle uses the visible screen centre as the query anchor', () => {
const anchor = defaultGnssViewAnchor({ const viewer = {};
scene: { // The eye high over (-97, 30), looking straight down.
canvas: { clientWidth: 1000, clientHeight: 800 }, const eye = fromDegrees(-97, 30, 2e7);
globe: { ellipsoid: Cesium.Ellipsoid.WGS84 }, const ground = fromDegrees(-97, 30, 0);
}, const length = Math.hypot(
camera: { eye.x - ground.x,
pickEllipsoid(pixel) { eye.y - ground.y,
assert.deepEqual(pixel, new Cesium.Cartesian2(500, 400)); eye.z - ground.z,
return Cesium.Cartesian3.fromDegrees(-97, 30); );
}, const camera = fakeCameraPort({
computeViewRectangle: () => { pose: {
throw new Error('centre hit must not compute a rectangle'); 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.latitude - 30) < 1e-8);
assert.ok(Math.abs(anchor.longitude + 97) < 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) => { test('pan and zoom refresh through the manager without toggling; nearby changes are coalesced', async (t) => {
t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] }); t.mock.timers.enable({ apis: ['setTimeout', 'setInterval'] });
let calls = 0; 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)); manager.subscribe((change) => changes.push(change.type));
await manager.setEnabled(h.layer.id, true); await manager.setEnabled(h.layer.id, true);
h.setAnchor({ latitude: 54, longitude: 19 }); h.setAnchor({ latitude: 54, longitude: 19 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.setAnchor({ latitude: 55, longitude: 20 }); h.setAnchor({ latitude: 55, longitude: 20 });
h.viewer.camera.moveEnd.raiseEvent(); h.camera.emit('moveEnd');
h.advance(2500); h.advance(2500);
t.mock.timers.tick(2500); t.mock.timers.tick(2500);
await flush(); 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/); assert.match(h.layer.getRowControls().info, /Regional sample.*250 nm radius/);
h.setAnchor({ latitude: 55.1, longitude: 20.1 }); h.setAnchor({ latitude: 55.1, longitude: 20.1 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.advance(5000); h.advance(5000);
t.mock.timers.tick(5000); t.mock.timers.tick(5000);
await flush(); await flush();
assert.equal(calls, 2, 'nearby views reuse the same query region'); assert.equal(calls, 2, 'nearby views reuse the same query region');
await manager.destroyAll(); await manager.destroyAll();
assert.equal(h.viewer.camera.moveEnd.numberOfListeners, 0); assert.equal(h.camera.listenerCount('moveEnd'), 0);
assert.equal(h.viewer.camera.changed.numberOfListeners, 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) => { 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(); h.layer.enable();
await h.layer.update(); await h.layer.update();
h.setAnchor({ latitude: 54, longitude: 19 }); h.setAnchor({ latitude: 54, longitude: 19 });
h.viewer.camera.moveEnd.raiseEvent(); h.camera.emit('moveEnd');
h.advance(2500); h.advance(2500);
t.mock.timers.tick(2500); t.mock.timers.tick(2500);
await flush(); await flush();
h.setAnchor({ latitude: 35, longitude: 140 }); h.setAnchor({ latitude: 35, longitude: 140 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.advance(2500); h.advance(2500);
t.mock.timers.tick(2500); t.mock.timers.tick(2500);
await flush(); 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.equal(calls.length, 3);
assert.deepEqual(calls.at(-1), { latitude: 35, longitude: 140 }); assert.deepEqual(calls.at(-1), { latitude: 35, longitude: 140 });
h.setAnchor({ latitude: 10, longitude: 10 }); h.setAnchor({ latitude: 10, longitude: 10 });
h.viewer.camera.moveEnd.raiseEvent(); h.camera.emit('moveEnd');
h.layer.disable(); h.layer.disable();
h.advance(5000); h.advance(5000);
t.mock.timers.tick(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 () => { 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.deepEqual(anchor, { latitude: 50, longitude: 30 });
assert.ok(signal instanceof AbortSignal); assert.ok(signal instanceof AbortSignal);
return { 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(await layer.update(), false, 'disabled layers do not fetch');
assert.equal(anchors.length, 0); assert.equal(anchors.length, 0);
layer.enable(); layer.enable();
assert.equal(sources[0].show, true); assert.equal(fills().show, true);
assert.equal(await layer.update(), true); assert.equal(await layer.update(), true);
const entities = sources[0].get(0).geometryInstances; const cells = [...fills().items.values()];
assert.equal(entities.length, 1, 'the one-aircraft cell is withheld'); assert.equal(cells.length, 1, 'the one-aircraft cell is withheld');
assert.equal(entities[0].id, 'gnss-integrity:280:420'); assert.equal(cells[0].id, 'gnss-integrity:280:420');
assert.ok(entities[0].geometry instanceof Cesium.RectangleGeometry); assert.deepEqual(cells[0].geometry, {
assert.equal(sources[0].get(0).allowPicking, false); 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(); const stats = layer.getStats();
assert.equal(stats.count, 1); assert.equal(stats.count, 1);
assert.equal(stats.error, null); 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 () => { test('a failed refresh keeps the last cells and reports the error', async () => {
let fail = false; let fail = false;
const { layer, sources } = harness(async () => { const { layer, fills } = harness(async () => {
if (fail) throw new Error('adsb.lol HTTP 502'); if (fail) throw new Error('adsb.lol HTTP 502');
return { return {
rows: [ rows: [
@@ -288,14 +322,14 @@ test('a failed refresh keeps the last cells and reports the error', async () =>
assert.equal(layer.getStats().stale, true); assert.equal(layer.getStats().stale, true);
fail = true; fail = true;
assert.equal(await layer.update(), 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().error, 'adsb.lol HTTP 502');
assert.equal(layer.getStats().count, 1); assert.equal(layer.getStats().count, 1);
}); });
test('observations expire with the window, and disable aborts the request in flight', async () => { test('observations expire with the window, and disable aborts the request in flight', async () => {
let pending; let pending;
const { layer, sources, advance } = harness( const { layer, fills, advance } = harness(
(anchor, { signal }) => (anchor, { signal }) =>
new Promise((resolve, reject) => { new Promise((resolve, reject) => {
pending = { resolve }; pending = { resolve };
@@ -315,17 +349,17 @@ test('observations expire with the window, and disable aborts the request in fli
pending.resolve({ rows: [] }); pending.resolve({ rows: [] });
assert.equal(await result, true); assert.equal(await result, true);
assert.equal(layer.getStats().count, 0); 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(); result = layer.update();
layer.disable(); layer.disable();
assert.equal(await result, false); 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 () => { test('no view anchor means no request, and destroy releases the data source', async () => {
let calls = 0; let calls = 0;
const { layer, sources } = harness( const { layer, fills } = harness(
async () => { async () => {
calls += 1; calls += 1;
return { rows: [] }; 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(calls, 0);
assert.equal(layer.getStats().error, null); assert.equal(layer.getStats().error, null);
layer.destroy(); layer.destroy();
assert.equal(sources.length, 0); assert.equal(fills(), undefined, 'destroy disposes the set');
assert.equal(layer.getStats().count, 0); assert.equal(layer.getStats().count, 0);
}); });
test('a replayed stale snapshot keeps its observation age and expires on time', async () => { 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. // 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(), rows: threeHealthy(),
ageMs: now() - 1_000, ageMs: now() - 1_000,
stale: true, stale: true,
@@ -369,12 +403,12 @@ test('a replayed stale snapshot keeps its observation age and expires on time',
0, 0,
'the replay did not restart the window', '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 () => { test('cells expire during prolonged fetch failures', async () => {
let fail = false; let fail = false;
const { layer, sources, advance } = harness(async () => { const { layer, fills, advance } = harness(async () => {
if (fail) throw new Error('adsb.lol HTTP 502'); if (fail) throw new Error('adsb.lol HTTP 502');
return { rows: threeHealthy() }; return { rows: threeHealthy() };
}); });
@@ -387,13 +421,13 @@ test('cells expire during prolonged fetch failures', async () => {
advance(11 * MIN); advance(11 * MIN);
assert.equal(await layer.update(), true); assert.equal(await layer.update(), true);
assert.equal(layer.getStats().count, 0); 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'); assert.equal(layer.getStats().error, 'adsb.lol HTTP 502');
}); });
test('cells expire while no view anchor is available', async () => { test('cells expire while no view anchor is available', async () => {
let calls = 0; let calls = 0;
const { layer, sources, advance, setAnchor } = harness(async () => { const { layer, fills, advance, setAnchor } = harness(async () => {
calls += 1; calls += 1;
return { rows: threeHealthy() }; 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(await layer.update(), true);
assert.equal(calls, 1, 'no anchor means no request'); assert.equal(calls, 1, 'no anchor means no request');
assert.equal(layer.getStats().count, 0); 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); assert.equal(layer.getStats().error, null);
}); });
test('re-enabling after a long disable does not show cells past the window', async () => { 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(), rows: threeHealthy(),
})); }));
layer.enable(); layer.enable();
await layer.update(); await layer.update();
assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 1); assert.equal(fills().items.size, 1);
layer.disable(); layer.disable();
advance(31 * MIN); advance(31 * MIN);
layer.enable(); layer.enable();
assert.equal(layer.getStats().count, 0); assert.equal(layer.getStats().count, 0);
assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 0); assert.equal(fills().items.size, 0);
}); });
const threeCells = () => ({ const threeCells = () => ({
rows: [row('a1', 50.1, true), row('a2', 50.1, true), row('a3', 50.2, false)], 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 () => { test('an identical snapshot draws nothing again', async () => {
const { layer, sources } = harness(async () => threeCells()); const { layer, fills } = harness(async () => threeCells());
layer.enable(); layer.enable();
await layer.update(); await layer.update();
const first = sources[0].get(0); const writes = fills().writes;
await layer.update(); await layer.update();
assert.equal(sources[0].get(0)?.geometryInstances.length ?? 0, 1); assert.equal(fills().items.size, 1);
assert.equal(sources[0].get(0), first); assert.equal(fills().writes, writes);
}); });
test('an initial feed failure stays enabled, reports unavailable, and recovers automatically', async (t) => { 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(); h.layer.enable();
await h.layer.update(); await h.layer.update();
h.setAnchor({ latitude: 10, longitude: 20 }); h.setAnchor({ latitude: 10, longitude: 20 });
h.viewer.camera.moveEnd.raiseEvent(); h.camera.emit('moveEnd');
h.advance(30000); h.advance(30000);
t.mock.timers.tick(30000); t.mock.timers.tick(30000);
await flush(); await flush();
@@ -583,7 +617,7 @@ test('GERMAN: camera debounce and minimum request gap are pinned', async (t) =>
h.layer.enable(); h.layer.enable();
await h.layer.update(); await h.layer.update();
h.setAnchor({ latitude: 51, longitude: 31 }); h.setAnchor({ latitude: 51, longitude: 31 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.advance(2499); h.advance(2499);
t.mock.timers.tick(2499); t.mock.timers.tick(2499);
await flush(); await flush();
@@ -594,7 +628,7 @@ test('GERMAN: camera debounce and minimum request gap are pinned', async (t) =>
assert.equal(calls, 2); assert.equal(calls, 2);
h.advance(3000); h.advance(3000);
h.setAnchor({ latitude: 52, longitude: 32 }); h.setAnchor({ latitude: 52, longitude: 32 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.advance(599); h.advance(599);
t.mock.timers.tick(599); t.mock.timers.tick(599);
await flush(); await flush();
@@ -619,7 +653,7 @@ test('camera movement during initial activation waits for acquisition before fol
h.layer.enable(); h.layer.enable();
const initial = h.layer.update(); const initial = h.layer.update();
h.setAnchor({ latitude: 51, longitude: 31 }); h.setAnchor({ latitude: 51, longitude: 31 });
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
h.advance(2500); h.advance(2500);
t.mock.timers.tick(2500); t.mock.timers.tick(2500);
await flush(); await flush();
@@ -658,7 +692,7 @@ test('monotonic camera scheduling is unaffected by wall-clock rollback', async (
wall -= 3600000; wall -= 3600000;
mono = 3000; mono = 3000;
anchor = { latitude: 51, longitude: 31 }; anchor = { latitude: 51, longitude: 31 };
h.viewer.camera.changed.raiseEvent(); h.camera.emit('changed');
mono += 600; mono += 600;
t.mock.timers.tick(600); t.mock.timers.tick(600);
await flush(); await flush();
@@ -666,35 +700,34 @@ test('monotonic camera scheduling is unaffected by wall-clock rollback', async (
layer.destroy(); 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', () => { test('view anchor falls back to rectangle, then nadir, then no camera', () => {
assert.equal(defaultGnssViewAnchor({}), null); assert.equal(defaultGnssViewAnchor({}), null);
const viewer = { const viewer = { scene: {} };
camera: { // Looking away from the globe: the line of sight misses it.
computeViewRectangle: () => Cesium.Rectangle.fromDegrees(20, 40, 22, 42), 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); const rectangleAnchor = defaultGnssViewAnchor(viewer);
assert.ok(Math.abs(rectangleAnchor.latitude - 41) < 1e-10); assert.ok(Math.abs(rectangleAnchor.latitude - 41) < 1e-10);
assert.ok(Math.abs(rectangleAnchor.longitude - 21) < 1e-10); assert.ok(Math.abs(rectangleAnchor.longitude - 21) < 1e-10);
viewer.camera = { // Across the antimeridian, the middle is on it.
positionCartographic: Cesium.Cartographic.fromDegrees(21, 41), 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); const nadirAnchor = defaultGnssViewAnchor(viewer);
assert.ok(Math.abs(nadirAnchor.latitude - 41) < 1e-10); assert.ok(Math.abs(nadirAnchor.latitude - 41) < 1e-10);
assert.ok(Math.abs(nadirAnchor.longitude - 21) < 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');
}); });
+5 -8
View File
@@ -2,9 +2,10 @@
// card's info line shows them in the UI language, the HTTP form included. // card's info line shows them in the UI language, the HTTP form included.
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import test from 'node:test'; import test from 'node:test';
import * as Cesium from 'cesium';
import { setLocale } from '../../i18n/index.js'; import { setLocale } from '../../i18n/index.js';
import { createGnssIntegrityLayer } from './index.js'; import { createGnssIntegrityLayer } from './index.js';
import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs';
import { bindFakeDraw } from '../../testSupport/fakeDrawPort.mjs';
async function failedLayer(message) { async function failedLayer(message) {
const layer = createGnssIntegrityLayer({ const layer = createGnssIntegrityLayer({
@@ -20,13 +21,9 @@ async function failedLayer(message) {
now: () => 1_000, now: () => 1_000,
monotonicNow: () => 1_000, monotonicNow: () => 1_000,
}); });
layer.init({ const viewer = { scene: { globe: { show: true } } };
camera: { moveEnd: new Cesium.Event(), changed: new Cesium.Event() }, bindFakeDraw(viewer, { camera: fakeCameraPort().port });
scene: { layer.init(viewer);
globe: { show: true },
groundPrimitives: { add() {}, remove() {} },
},
});
layer.enable(); layer.enable();
await layer.update(); await layer.update();
return layer; return layer;
+51
View File
@@ -800,3 +800,54 @@ test('the fire perimeters layer draws holed ground fills and draped fire lines o
layer.destroy(); layer.destroy();
assert.equal(scene.added.length, 0); 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);
});
-1
View File
@@ -84,7 +84,6 @@
"src/layers/flights/testing.js", "src/layers/flights/testing.js",
"src/layers/flights/tracking.js", "src/layers/flights/tracking.js",
"src/layers/ghostMaps/index.js", "src/layers/ghostMaps/index.js",
"src/layers/gnss/index.js",
"src/layers/installations/controls.js", "src/layers/installations/controls.js",
"src/layers/installations/lifecycle.js", "src/layers/installations/lifecycle.js",
"src/layers/installations/model.js", "src/layers/installations/model.js",
+1
View File
@@ -67,6 +67,7 @@ const FALLS_BACK = new Set(['src/data/followed.js']);
const DRAW_FROM_CALLER = new Set([ const DRAW_FROM_CALLER = new Set([
'./layers/earthquakes', './layers/earthquakes',
'./layers/bikeshare', './layers/bikeshare',
'./layers/gnss',
'./layers/perimeters', './layers/perimeters',
]); ]);