mirror of
https://github.com/bilawalsidhu/gods-eye-view.git
synced 2026-11-16 08:12:24 +00:00
Ground snapping and mesh floor sampling through the renderer ports, off the Cesium list
src/services/groundSnap.js and src/services/meshFloorSampler.js no longer reach Cesium. Whether the surface has streamed comes from the globe port (the snap waits for the 'tiles' and 'surface' settle kinds; the sampler runs only with the globe hidden and 'surface' settled), the camera height gate from camera.pose(), heights from the query port, and the maths from src/geo/ellipsoid.js. The raw exclusion path is gone: callers see through their own 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), instead of the tracked holder object. Probing is unchanged: at the caller's point, up to eight readings per cell about 17 m apart, a read answering from the nearest one. The application operations entry is now Cesium-free: a viewer with no renderer bound needs ./render/cesium/unbound loaded first. Tests that used to get the adapter's factories through ground snapping load it themselves.
This commit is contained in:
1 parent
9d4e438e63
commit
f53f691a80
20 files changed
+296
-199
No files matched your search
@@ -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}).
|
||||
*/
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -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(),
|
||||
|
||||
@@ -17,8 +17,6 @@
|
||||
"src/maps/google3d.js",
|
||||
"src/maps/imagery.js",
|
||||
"src/maps/terrain.js",
|
||||
"src/services/groundSnap.js",
|
||||
"src/services/meshFloorSampler.js",
|
||||
"src/sky/starrySky.js",
|
||||
"src/ui/applicationShell.js"
|
||||
]
|
||||
@@ -123,8 +123,8 @@ const DRAW_FROM_CALLER = new Set([
|
||||
// Its moving and still vehicle icons draw through `drawOf`; it projects,
|
||||
// culls, follows and samples floors through the ports.
|
||||
'./layers/transit',
|
||||
// Not Cesium-free (its legacy mesh floor sampler is), but its layer draws
|
||||
// and reads the view through the ports alone.
|
||||
// Its layer draws and reads the view through the ports alone, and its mesh
|
||||
// floor sampler asks the camera, globe and query ports.
|
||||
'./layers/transit/standalone',
|
||||
]);
|
||||
|
||||
@@ -153,6 +153,9 @@ const CAMERA_FROM_CALLER = new Set([
|
||||
// renderer the application gives it (`rendering.js`, which draws the box
|
||||
// preview through `drawOf`) is Cesium-free too.
|
||||
'./layers/recent-imagery',
|
||||
// Its ground snap, mesh floor sampler, annotation resolver and location
|
||||
// framing ask the camera, globe and query ports; it loads no factory.
|
||||
'./application/operations',
|
||||
]);
|
||||
|
||||
const pkg = JSON.parse(readFileSync(path.join(root, 'package.json'), 'utf8'));
|
||||
|
||||
+47
-91
@@ -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<unknown>)|{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<string, {h: number|null, samplePos: Cesium.Cartesian3|null,
|
||||
/** @type {Map<string, {h: number|null, samplePos: {x: number, y: number, z: number}|null,
|
||||
* held: boolean, nextRetryMs: number, misses: number}>} 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<unknown>)|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,
|
||||
|
||||
@@ -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);
|
||||
});
|
||||
@@ -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<string, Array<{lat: number, lon: number}>>} 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<object>} [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;
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
@@ -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,
|
||||
});
|
||||
|
||||
Reference in new issue
Block a user