diff --git a/src/data/aircraftModelLighting.test.mjs b/src/data/aircraftModelLighting.test.mjs index 51fd9d97c..28725e895 100644 --- a/src/data/aircraftModelLighting.test.mjs +++ b/src/data/aircraftModelLighting.test.mjs @@ -19,13 +19,6 @@ const SOURCES = [ name: 'militaryFlights', source: readLayerSource(new URL('./militaryFlights.js', import.meta.url)), }, - { - name: 'localAdsb', - source: readFileSync( - new URL('../layers/localAdsb/models.js', import.meta.url), - 'utf8', - ), - }, ]; test('the shared option turns the dynamic environment map off', () => { @@ -49,3 +42,14 @@ for (const { name, source } of SOURCES) { ); }); } + +test('localAdsb: its draw-port models skip the dynamic environment map', () => { + const source = readFileSync( + new URL('../layers/localAdsb/models.js', import.meta.url), + 'utf8', + ); + assert.match( + source, + /\benvironmentMap:\s*AIRCRAFT_ENVIRONMENT_MAP_OPTIONS\.enabled\b/, + ); +}); diff --git a/src/layers/localAdsb/index.js b/src/layers/localAdsb/index.js index 137707c4e..f9010a588 100644 --- a/src/layers/localAdsb/index.js +++ b/src/layers/localAdsb/index.js @@ -6,7 +6,12 @@ import { } from '../../data/iconOrientation.js'; import { fromDegreesInto, toLonLatH } from '../../geo/ellipsoid.js'; import { hexColor } from '../../render/color.js'; -import { drawOf, findCamera, findFrame } from '../../render/rendererOf.js'; +import { + drawOf, + findCamera, + findFrame, + findQuery, +} from '../../render/rendererOf.js'; import { inputFor } from '../../input/dispatcher.js'; import { pickRenderAltitudeM } from '../../data/renderAltitude.js'; import { routePlausible } from '../../data/routePlausible.js'; @@ -105,8 +110,6 @@ const DEFAULT_DISPLAY = Object.freeze({ * (`createGroundSnap`). * @param {() => number} [options.now] Clock, injectable for tests. * @param {(url: string) => string} [options.resolveAsset] Model URL resolver. - * @param {(options: object) => Promise} [options.loadModel] Model - * loader, injectable for tests. * @returns {object} Data-layer module. */ export function createLocalAdsbLayer({ @@ -115,7 +118,6 @@ export function createLocalAdsbLayer({ services, now = Date.now, resolveAsset = (url) => url, - loadModel, }) { if (typeof receiver?.getState !== 'function') throw new TypeError('Local ADS-B requires a receiver session'); @@ -534,6 +536,7 @@ export function createLocalAdsbLayer({ function showSets(show) { if (sets) for (const set of Object.values(sets)) set.show = show; + if (models) models.show = show; } function updateRenderHold() { @@ -632,12 +635,12 @@ export function createLocalAdsbLayer({ return true; } - /** - * The id under a pick, through the shared pick-id resolver: a draw-set - * item's id (markers, the trail head) or a model's. - */ - function pickedId(picked) { - return services.picking.resolvePickId?.(picked) ?? null; + /** A local aircraft's id when `hit` is one of its markers or models. */ + function ownHit(hit) { + if (!hit || hit.surface || !markers.has(hit.id)) return null; + return hit.set === sets?.markers.id || hit.set === models?.setId + ? hit.id + : null; } function ownedElsewhere(id) { @@ -651,25 +654,35 @@ export function createLocalAdsbLayer({ * * The frontmost pick decides, except that something no layer owns (a * photoreal tile, a ring) or a trail line drawn over or through a local - * aircraft does not hide it: the click looks underneath for the aircraft. + * aircraft does not hide it: the click looks underneath, through the + * renderer's draw-set picks, for the aircraft. */ function clickTarget(event) { - const top = pickedId(event.pick); - if (top && markers.has(top)) return top; - const trail = Boolean(top) && String(top).startsWith(TRAIL_PICK_PREFIX); - if (ownedElsewhere(top) && !trail) return 'other'; + const top = event.drawHit; + const own = ownHit(top); + if (own) return own; + // What is on top when it is no draw-set item: a sibling's contact + // drawn on its own, a tile, or (on a coarse pointer) a contact found + // under the touch. + const topId = top ? top.id : event.id; + if (!top && topId && markers.has(topId)) return topId; + const trail = Boolean(topId) && String(topId).startsWith(TRAIL_PICK_PREFIX); + if (ownedElsewhere(topId) && !trail) return 'other'; let hits = []; try { - hits = event.drill(CLICK_DRILL_LIMIT); + hits = + findQuery(viewer)?.drillPick(event.position.x, event.position.y, { + limit: CLICK_DRILL_LIMIT, + }) ?? []; } catch { hits = []; } for (const hit of hits) { - const id = pickedId(hit); - if (id && markers.has(id)) return id; - if (id && String(id).startsWith(TRAIL_PICK_PREFIX)) continue; + const id = ownHit(hit); + if (id) return id; + if (String(hit.id).startsWith(TRAIL_PICK_PREFIX)) continue; // A sibling layer's contact above ours takes the click. - if (ownedElsewhere(id)) return 'other'; + if (ownedElsewhere(hit.id)) return 'other'; } return trail ? 'trail' : null; } @@ -761,10 +774,13 @@ export function createLocalAdsbLayer({ }; models = createLocalAdsbModels({ viewer, + draw, + camera: findCamera(viewer), + setId: `${prefix}:models`, + seeThrough: [sets.markers.id, sets.rings.id], color: LOCAL_ADSB_COLOR, resolveAsset, groundSnap: services.groundSnap?.createGroundSnap?.() || null, - ...(loadModel ? { loadModel } : {}), }); services.geoid ?.ensureGeoidReady?.() diff --git a/src/layers/localAdsb/index.test.mjs b/src/layers/localAdsb/index.test.mjs index 75f113a73..5fa0fb2db 100644 --- a/src/layers/localAdsb/index.test.mjs +++ b/src/layers/localAdsb/index.test.mjs @@ -12,9 +12,10 @@ import { localAdsbReceiverLine, localAdsbStatus, } from './index.js'; +import { createLocalAdsbModels } from './models.js'; import { entityRecord, readEntityRecord } from '../../data/entityRecords.js'; import { resolvePickId } from '../../data/pickRegistry.js'; -import { toLonLatH } from '../../geo/ellipsoid.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; import { fakeInput } from '../../input/testDoubles.mjs'; import { hexColor } from '../../render/color.js'; import { fakeCameraPort } from '../../testSupport/fakeCameraPort.mjs'; @@ -117,17 +118,21 @@ function fakeServices() { } /** - * A viewer with a fake draw port and a camera port whose screen axes are - * east and north at (0°, 0°); `viewer` adds the Cesium-shaped members the - * 3D models read. + * A viewer with a fake draw port, a camera port whose screen axes are east + * and north at (0°, 0°), and a query port whose drill picks are the + * viewer's `drillHits`; `pose` sets the camera. */ -function fakeViewer(viewer = { scene: {} }) { +function fakeViewer(viewer = { scene: {} }, pose = {}) { const camera = fakeCameraPort({ - pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 } }, + pose: { right: { x: 0, y: 1, z: 0 }, up: { x: 0, y: 0, z: 1 }, ...pose }, }); - const { draw } = bindFakeDraw(viewer, { camera: camera.port }); + const query = { + drillPick: (x, y, { limit } = {}) => + (viewer.drillHits ?? []).slice(0, limit), + }; + const { draw } = bindFakeDraw(viewer, { camera: camera.port, query }); const input = fakeInput(viewer); - return { draw, viewer, input }; + return { draw, viewer, input, camera }; } function record(overrides = {}) { @@ -182,31 +187,16 @@ function fakeFeeds(initial = {}) { }; } -/** A viewer whose camera looks down on (0°, 0°) from 50 km, with primitives. */ -function modelViewer(primitives) { - const camera = { - positionWC: new Cesium.Cartesian3(6_378_137 + 50_000, 0, 0), - positionCartographic: new Cesium.Cartographic(0, 0, 50_000), - directionWC: new Cesium.Cartesian3(-1, 0, 0), - frustum: { - computeCullingVolume: () => ({ - computeVisibility: () => Cesium.Intersect.INSIDE, - }), +/** A viewer whose camera looks down on (0°, 0°) from 50 km. */ +function modelViewer() { + return fakeViewer( + { scene: {} }, + { + height: 50_000, + position: { x: 6_378_137 + 50_000, y: 0, z: 0 }, + direction: { x: -1, y: 0, z: 0 }, }, - }; - return fakeViewer({ - camera, - scene: { - camera, - primitives: { - add(collection) { - primitives.push(collection); - return collection; - }, - remove() {}, - }, - }, - }); + ); } async function enabledLayer(receiver, clock, feeds = null, options = {}) { @@ -217,7 +207,6 @@ async function enabledLayer(receiver, clock, feeds = null, options = {}) { feeds, services: { ...services, ...options.services }, now: () => clock.now, - loadModel: options.loadModel, }); layer.init(viewer); await layer.enable(); @@ -572,65 +561,43 @@ test('adsbdb type, operator and route reach the card for the selected aircraft o test('the DISPLAY 3D toggle gives local aircraft magenta class models', async (t) => { const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; - const loads = []; const display = { models3d: true, models3dMode: 'proximity' }; - const primitives = []; const { layer, draw } = await enabledLayer(receiver, clock, null, { services: { display: { getParams: () => display } }, - viewer: modelViewer(primitives), - loadModel: async (options) => { - const model = { - ...options, - ready: true, - show: true, - modelMatrix: new Cesium.Matrix4(), - destroyed: false, - destroy() { - this.destroyed = true; - }, - isDestroyed() { - return this.destroyed; - }, - update() {}, - }; - loads.push(model); - return model; - }, + viewer: modelViewer(), }); t.after(() => layer.destroy()); receiver.set({ aircraft: [record({ icao: 'a0b702', category: 'A7' })] }); await layer.update(); - await new Promise((resolve) => setImmediate(resolve)); - await layer.update(); - assert.equal(loads.length, 1); - const [model] = loads; - assert.equal( - model.url, - '/models/bell206.glb', - 'the Flights helicopter model', - ); - assert.equal(model.scale, 1); - assert.equal(model.id, 'local-adsb:a0b702'); - assert.ok( - Cesium.Color.equals( - model.color, - Cesium.Color.fromCssColorString('#ff4fd8'), - ), - ); - assert.equal(model.colorBlendMode, Cesium.ColorBlendMode.MIX); - assert.equal(model.colorBlendAmount, 0.94); - assert.equal(model.show, true); + const models = layerSet(draw, ':models'); + const model = () => models.items.get('local-adsb:a0b702'); + assert.ok(model(), 'admitted'); + assert.equal(model().url, '/models/bell206.glb', 'the Flights helicopter'); + assert.equal(model().scale, 1); + assert.deepEqual(model().tint, MAGENTA); + assert.deepEqual(model().colorBlend, { mode: 'mix', amount: 0.94 }); + assert.equal(model().environmentMap, false); const heli = () => iconOf(draw, 'local-adsb:a0b702'); + assert.equal(heli().show, true, 'the icon until the model is ready'); + draw.ready(models.spec.id, 'local-adsb:a0b702'); + await layer.update(); + assert.equal(model().show, true); assert.equal(heli().show, false, 'the model is the visual'); - const origin = Cesium.Matrix4.getTranslation( - model.modelMatrix, - new Cesium.Cartesian3(), + assert.ok( + Math.hypot( + model().pos.x - heli().pos.x, + model().pos.y - heli().pos.y, + model().pos.z - heli().pos.z, + ) < 1, + 'where its icon is', ); - assert.ok(Cesium.Cartesian3.distance(origin, heli().pos) < 1); + const writes = models.writes; + await layer.update(); + assert.ok(models.writes > writes, 'moved in place each frame'); display.models3d = false; await layer.update(); - assert.equal(model.destroyed || !primitives[0].contains(model), true); + assert.equal(models.items.size, 0, 'models dropped'); assert.equal(heli().show, true, 'the icon is back'); }); @@ -895,7 +862,7 @@ test('the layer draws into sets of its own, shown while it is enabled and let go .filter((record) => !record.disposed) .map((record) => record.spec.id); const mine = ids(draw); - assert.equal(mine.length, 2, 'markers and rings'); + assert.equal(mine.length, 3, 'markers, rings and models'); assert.ok( ids(other.draw).every((id) => !mine.includes(id)), 'a second layer has ids of its own', @@ -1107,87 +1074,35 @@ test('row status names two same-band feeds by their ordinal labels', () => { ); }); -function fakeModel(options) { - return { - ...options, - ready: true, - show: true, - modelMatrix: new Cesium.Matrix4(), - destroyed: false, - destroy() { - this.destroyed = true; - }, - isDestroyed() { - return this.destroyed; - }, - update() {}, - }; -} - -test('the last aircraft expiring removes its 3D model and cancels a pending load', async (t) => { +test('the last aircraft expiring removes its 3D model', async (t) => { const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; - const primitives = []; - const loads = []; - const deferred = []; - const { layer } = await enabledLayer(receiver, clock, null, { + const { layer, draw } = await enabledLayer(receiver, clock, null, { services: { display: { getParams: () => ({ models3d: true, models3dMode: 'proximity' }), }, }, - viewer: modelViewer(primitives), - loadModel: (options) => { - const model = fakeModel(options); - loads.push(model); - if (options.id === 'local-adsb:abc123') return Promise.resolve(model); - return new Promise((resolve) => deferred.push(() => resolve(model))); - }, + viewer: modelViewer(), }); t.after(() => layer.destroy()); receiver.set({ aircraft: [record({ category: 'A7' })] }); await layer.update(); - await new Promise((resolve) => setImmediate(resolve)); - await layer.update(); - const [model] = loads; - assert.equal(model.show, true, 'the model is the visual'); - assert.ok(primitives[0].contains(model)); + const models = layerSet(draw, ':models'); + assert.ok(models.items.has('local-adsb:abc123')); // Its position ages out: no markers remain, so no per-frame model pass. clock.now = 160_000; await layer.update(); - assert.equal( - model.destroyed || !primitives[0].contains(model), - true, - 'the expired aircraft leaves no model behind', - ); + assert.equal(models.items.size, 0, 'no model left behind'); - // A load still in flight when its aircraft expires is never admitted. - clock.now = 200_000; - receiver.set({ - aircraft: [ - record({ - icao: 'def456', - lastPositionAt: 200_000, - lastMessageAt: 200_000, - }), - ], - }); - await layer.update(); - clock.now = 260_000; - await layer.update(); - assert.equal(deferred.length, 1, 'a load was in flight'); - deferred[0](); - await new Promise((resolve) => setImmediate(resolve)); - const late = loads.at(-1); - assert.equal(late.id, 'local-adsb:def456'); - assert.equal(primitives[0].contains(late), false); - assert.equal(late.destroyed, true); + layer.destroy(); + assert.equal(models.disposed, true, 'the set goes with the layer'); }); /** A pick on a draw-port icon of the layer's, as the renderer reports it. */ -function iconPick(id) { - return { primitive: {}, id: { set: 'local-adsb:1:markers', id } }; +function iconPick(draw, id) { + return { primitive: {}, id: { set: layerSet(draw, ':markers').spec.id, id } }; } /** A viewer with a canvas and scripted picks, plus the layer's click action. */ @@ -1195,13 +1110,9 @@ function clickHarness() { const scene = { canvas: {}, pickResult: null, - drillResult: [], pick() { return scene.pickResult; }, - drillPick() { - return scene.drillResult; - }, }; const base = fakeViewer({ scene }); return { @@ -1217,13 +1128,13 @@ test('clicking the selected aircraft keeps it selected and republishes its card' const receiver = fakeReceiver({ mode: 'adsb', connected: true }); const clock = { now: 100_000 }; const harness = clickHarness(); - const { layer, calls } = await enabledLayer(receiver, clock, null, { + const { layer, calls, draw } = await enabledLayer(receiver, clock, null, { viewer: harness.viewer, }); t.after(() => layer.destroy()); receiver.set({ aircraft: [record()] }); await layer.update(); - harness.scene.pickResult = iconPick('local-adsb:abc123'); + harness.scene.pickResult = iconPick(draw, 'local-adsb:abc123'); harness.click(); assert.deepEqual(calls.selected, ['local-adsb:abc123']); // Its card may have been displaced (another readout, a camera move): a @@ -1238,7 +1149,7 @@ test('a click on a local aircraft under an unowned or trail pick still selects i const clock = { now: 100_000 }; const harness = clickHarness(); const owners = new Map(); - const { layer, calls } = await enabledLayer(receiver, clock, null, { + const { layer, calls, draw } = await enabledLayer(receiver, clock, null, { viewer: harness.viewer, services: { picking: { @@ -1259,27 +1170,107 @@ test('a click on a local aircraft under an unowned or trail pick still selects i aircraft: [record(), record({ icao: 'def456', lat: 0.01 })], }); await layer.update(); - const [first, second] = ['abc123', 'def456'].map((icao) => - iconPick(`local-adsb:${icao}`), - ); + const hit = (suffix, id) => ({ + set: suffix.startsWith(':') ? layerSet(draw, suffix).spec.id : suffix, + id, + surface: false, + }); + const second = hit(':markers', 'local-adsb:def456'); // A photoreal tile (no pick id) drawn over the 3D model at this pixel. harness.scene.pickResult = { primitive: { tileset: true } }; - harness.scene.drillResult = [ - harness.scene.pickResult, - { primitive: { id: 'local-adsb:abc123' }, id: 'local-adsb:abc123' }, - ]; + harness.viewer.viewer.drillHits = [hit(':models', 'local-adsb:abc123')]; harness.click(); assert.deepEqual(calls.selected, ['local-adsb:abc123']); // The selected aircraft's trail crosses another local aircraft's marker. - harness.scene.pickResult = { id: { id: 'gev-trail:local-adsb-head-1' } }; - harness.scene.drillResult = [harness.scene.pickResult, second]; + const trail = hit('trail:1', 'gev-trail:1:head'); + harness.scene.pickResult = { primitive: {}, id: trail }; + harness.viewer.viewer.drillHits = [trail, second]; harness.click(); assert.deepEqual(calls.selected, ['local-adsb:abc123', 'local-adsb:def456']); // Another layer's own contact on top is that layer's click. harness.scene.pickResult = { id: 'abc123', primitive: {} }; - harness.scene.drillResult = [harness.scene.pickResult, first]; + harness.viewer.viewer.drillHits = [hit(':markers', 'local-adsb:abc123')]; harness.click(); assert.equal(calls.selected.length, 2, 'the Flights contact is not taken'); }); + +test('a grounded aircraft changing class keeps its drawn model on its own belly offset until the new one is ready', () => { + const { draw, viewer, camera } = modelViewer(); + const models = createLocalAdsbModels({ + viewer, + draw, + camera: camera.port, + setId: 'test:models', + color: '#ff00ff', + resolveAsset: (url) => url, + groundSnap: { heightFor: () => 100, forget() {}, clear() {} }, + }); + const marker = { + position: fromDegrees(0, 0, 0), + courseDeg: 0, + klass: 'light', + onGround: true, + }; + const markers = new Map([['a', marker]]); + const display = { models3d: true, models3dMode: 'proximity' }; + const height = () => + toLonLatH(draw.sets.get('test:models').items.get('a').pos).height; + models.frame(markers, display, 100_000); + draw.ready('test:models', 'a'); + models.frame(markers, display, 100_001); + assert.ok(Math.abs(height() - 101.36) < 0.01, 'light: its belly offset'); + marker.klass = 'widebody'; + models.frame(markers, display, 200_000); + assert.equal( + draw.sets.get('test:models').items.get('a').url, + '/models/b789.glb', + ); + assert.ok(Math.abs(height() - 101.36) < 0.01, 'the light model still draws'); + draw.ready('test:models', 'a'); + models.frame(markers, display, 200_001); + assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own'); + models.destroy(); +}); + +test('a class change takes its belly offset with the new model, however soon it is ready; a scale-only change at once', () => { + const { draw, viewer, camera } = modelViewer(); + const models = createLocalAdsbModels({ + viewer, + draw, + camera: camera.port, + setId: 'test:models', + color: '#ff00ff', + resolveAsset: (url) => url, + groundSnap: { heightFor: () => 100, forget() {}, clear() {} }, + }); + const marker = { + position: fromDegrees(0, 0, 0), + courseDeg: 0, + klass: 'narrowbody', + onGround: true, + }; + const markers = new Map([['a', marker]]); + const display = { models3d: true, models3dMode: 'proximity' }; + const item = () => draw.sets.get('test:models').items.get('a'); + const height = () => toLonLatH(item().pos).height; + models.frame(markers, display, 100_000); + draw.ready('test:models', 'a'); + models.frame(markers, display, 100_001); + assert.ok(Math.abs(height() - 106.719) < 0.01, 'narrowbody'); + // The same asset at another scale: no load, no ready. + marker.klass = 'glider'; + models.frame(markers, display, 100_002); + assert.equal(item().url, '/models/airplane.glb'); + assert.equal(item().scale, 0.75); + assert.ok(Math.abs(height() - 105.03925) < 0.01, 'at once'); + // Another asset, ready before the next eligibility pass. + marker.klass = 'widebody'; + models.frame(markers, display, 100_003); + assert.ok(Math.abs(height() - 105.03925) < 0.01, 'the old model draws'); + draw.ready('test:models', 'a'); + models.frame(markers, display, 100_004); + assert.ok(Math.abs(height() - 107.81) < 0.01, 'the widebody, on its own'); + models.destroy(); +}); diff --git a/src/layers/localAdsb/models.js b/src/layers/localAdsb/models.js index 0f8f47911..884c95d18 100644 --- a/src/layers/localAdsb/models.js +++ b/src/layers/localAdsb/models.js @@ -1,6 +1,13 @@ -import * as Cesium from 'cesium'; -import { horizonOccluder } from '../../data/iconOrientation.js'; import { selectModelEligible } from '../../data/modelEligibility.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { + distanceSquared, + dot, + RADIANS_PER_DEGREE, + sub, +} from '../../geo/vector.js'; +import { cssColor } from '../../render/color.js'; import { civilAircraftModelSpec } from '../flights/modelSpec.js'; import { FLEET_DR_INTERVAL_MS, @@ -15,154 +22,147 @@ import { MODEL_PROX_KEEP_M, } from '../flights/policy.js'; import { AIRCRAFT_ENVIRONMENT_MAP_OPTIONS } from '../../data/aircraftModelLighting.js'; -import { - createModelRecord, - placeModel, - showModel, -} from '../../data/modelRecord.js'; -const specKey = (spec) => `${spec.url}@${spec.scale}`; +/** Whether `point` is inside the eye's view cone (`pose`), a metre's slack. */ +function inView(pose, point) { + const v = sub(point, pose.position); + const depth = dot(v, pose.direction); + if (depth < -1) return false; + const tanY = Math.tan(pose.fovy / 2); + const tanX = tanY * pose.aspectRatio; + return ( + Math.abs(dot(v, pose.right)) <= Math.max(0, depth) * tanX + 1 && + Math.abs(dot(v, pose.up)) <= Math.max(0, depth) * tanY + 1 + ); +} /** - * 3D models for Local ADS-B aircraft under the DISPLAY rail's 3D toggle. + * 3D models for Local ADS-B aircraft under the DISPLAY rail's 3D toggle, + * drawn as one `models` set of the renderer's draw port. * * Mirrors the public Flights fleet: models only below the altitude ceiling, * the same proximity/all caps and add/keep radii, the same visible-first * eligibility (`selectModelEligible`), the same per-class asset and scale * (`civilAircraftModelSpec`) and the same tint path (a MIX colour blend, here - * magenta, as Flights tints military amber). Each model owns its matrix. A - * billboard stays the visual until its model is loaded AND placed; a grounded + * magenta, as Flights tints military amber). A billboard stays the visual + * until its model is ready (the set's `ready`) AND placed; a grounded * aircraft's model rides the one-shot ground snap plus the class belly - * offset, and without a resolved ground it stays a billboard. + * offset, and without a resolved ground it stays a billboard. Models move + * and turn in place each frame; only a class change loads another asset. * @param {object} options - * @param {object} options.viewer Cesium viewer. + * @param {object} options.viewer The viewer the layer draws on; the ground + * snap samples through it. + * @param {object} options.draw Draw port (`drawOf(viewer)`). + * @param {object} options.camera Camera port (`findCamera(viewer)`). + * @param {string} options.setId The models set's id. + * @param {string[]} [options.seeThrough] The layer's other set ids ground + * samples see through (its markers). * @param {string} options.color Model tint, a CSS colour. * @param {(url: string) => string} options.resolveAsset * @param {object|null} [options.groundSnap] `createGroundSnap()` instance. - * @param {(options: object) => Promise} [options.loadModel] - * @returns {object|null} Null on a viewer that draws no primitives. + * @returns {object|null} Null where the renderer draws no models. */ export function createLocalAdsbModels({ viewer, + draw, + camera, + setId, + seeThrough = [], color, resolveAsset, groundSnap = null, - loadModel = (options) => Cesium.Model.fromGltfAsync(options), }) { - if (!viewer.scene?.primitives) return null; - const tint = Cesium.Color.fromCssColorString(color); - const collection = new Cesium.PrimitiveCollection(); - viewer.scene.primitives.add(collection); - /** @type {Map} id -> admitted model */ + if (typeof draw?.models !== 'function' || !camera) return null; + const tint = cssColor(color) ?? color; + const set = draw.models({ id: setId, show: false }); + /** What ground samples see through, by set id (with every set not drawn as ground). */ + const groundSets = [setId, ...seeThrough]; + /** + * id -> admitted model. `bellyM` is the offset of the model drawn; + * `nextBellyM` a new asset's, taken once that model is ready (the old one + * draws, at its own offset, until then). `sentUrl` is the asset last + * asked for, `drawnUrl` the one whose model is ready. + * @type {Map} + */ const models = new Map(); - /** @type {Map} id -> generation of an in-flight load */ - const pending = new Map(); - let generation = 0; let destroyed = false; let lastEligibilityAt = 0; let eligible = new Set(); - const scratchHpr = new Cesium.HeadingPitchRoll(); - const scratchMatrix = new Cesium.Matrix4(); - const scratchSphere = new Cesium.BoundingSphere(Cesium.Cartesian3.ZERO, 1); - const scratchCarto = new Cesium.Cartographic(); - const scratchGround = new Cesium.Cartesian3(); - - function release(id) { - pending.delete(id); + const offReady = set.on('ready', (id) => { const record = models.get(id); if (!record) return; - models.delete(id); - if (!collection.isDestroyed()) collection.remove(record.model); - groundSnap?.forget?.(id); + record.ready = true; + record.drawnUrl = record.sentUrl; + if (record.nextBellyM !== null) { + record.bellyM = record.nextBellyM; + record.nextBellyM = null; + } + }); + + function release(ids) { + const gone = []; + for (const id of ids) { + if (!models.delete(id)) continue; + gone.push(id); + groundSnap?.forget?.(id); + } + if (gone.length && !destroyed) set.remove(gone); } function releaseAll() { - for (const id of [...models.keys()]) release(id); - pending.clear(); - generation += 1; + for (const id of models.keys()) groundSnap?.forget?.(id); + if (models.size && !destroyed) set.clear(); + models.clear(); } - async function ensure(id, marker, cap) { - const spec = civilAircraftModelSpec(marker.klass); - const key = specKey(spec); - const current = models.get(id); - if (current?.specKey === key) return; - if (current) release(id); - if (pending.has(id) || models.size + pending.size >= cap) return; - const loadGeneration = generation; - pending.set(id, loadGeneration); - let model; - try { - model = await loadModel({ - url: resolveAsset(spec.url), - asynchronous: false, - environmentMapOptions: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS, - minimumPixelSize: MODEL_MIN_PX, - scale: spec.scale, - color: tint, - colorBlendMode: Cesium.ColorBlendMode.MIX, - colorBlendAmount: spec.blendAmount, - id, - }); - } catch { - if (pending.get(id) === loadGeneration) pending.delete(id); - return; - } - const stale = - destroyed || - pending.get(id) !== loadGeneration || - generation !== loadGeneration || - !eligible.has(id) || - models.has(id) || - specKey(civilAircraftModelSpec(marker.klass)) !== key; - if (pending.get(id) === loadGeneration) pending.delete(id); - if (stale) { - model.destroy?.(); - return; - } - model.id = id; - const record = createModelRecord(model, { - specKey: key, - bellyM: spec.bellyM, + /** + * Admit a model for `id`. One admitted keeps its slot through a class + * change: the frame pass asks for the new asset, loaded in place. + */ + function admit(id, marker, cap) { + if (models.has(id) || models.size >= cap) return; + models.set(id, { + bellyM: civilAircraftModelSpec(marker.klass).bellyM, + nextBellyM: null, + sentUrl: null, + drawnUrl: null, + ready: false, }); - // Admitted, not yet the visual: placement turns it on. - showModel(record, false); - collection.add(model); - models.set(id, record); } - function regime(preferences) { + /** + * The asset `record` is about to ask for: the same model (a scale-only + * class change, or none) takes the offset now; another waits for its + * model's `ready`. + */ + function noteAsset(record, url, bellyM) { + record.sentUrl = url; + if (!record.ready || url === record.drawnUrl) { + record.bellyM = bellyM; + record.nextBellyM = null; + } else { + record.nextBellyM = bellyM; + } + } + + function regime(preferences, pose) { if (!preferences?.models3d) return false; - const height = viewer.camera?.positionCartographic?.height ?? Infinity; - return height < MODEL_ALT_CEIL_M; + return pose.height < MODEL_ALT_CEIL_M; } - function refreshEligibility(markers, preferences) { + function refreshEligibility(markers, preferences, pose) { const all = preferences.models3dMode === 'all'; const cap = all ? MODEL_MAX_ALL : MODEL_MAX; const addM = all ? MODEL_ALL_ADD_M : MODEL_PROX_ADD_M; const keepM = all ? MODEL_ALL_KEEP_M : MODEL_PROX_KEEP_M; - const camera = viewer.camera; - const cameraPosition = camera.positionWC; - const cull = camera.frustum.computeCullingVolume( - cameraPosition, - camera.directionWC, - camera.upWC, - ); const candidates = []; for (const [id, marker] of markers) { if (!marker.position) continue; - const distanceSq = Cesium.Cartesian3.distanceSquared( - cameraPosition, - marker.position, - ); + const distanceSq = distanceSquared(pose.position, marker.position); if (distanceSq > keepM * keepM) continue; - Cesium.Cartesian3.clone(marker.position, scratchSphere.center); - candidates.push([ - id, - distanceSq, - cull.computeVisibility(scratchSphere) !== Cesium.Intersect.OUTSIDE, - ]); + candidates.push([id, distanceSq, inView(pose, marker.position)]); } candidates.sort((a, b) => a[1] - b[1]); eligible = selectModelEligible(candidates, { @@ -170,32 +170,22 @@ export function createLocalAdsbModels({ addDistSq: addM * addM, isModeled: (id) => models.has(id), }); - for (const id of [...models.keys(), ...pending.keys()]) - if (!eligible.has(id)) release(id); - for (const id of eligible) void ensure(id, markers.get(id), cap); + release([...models.keys()].filter((id) => !eligible.has(id))); + for (const id of eligible) admit(id, markers.get(id), cap); } function placement(id, marker) { if (!marker.onGround) return marker.position; const record = models.get(id); - // The vertical sample must hit the tile skin, not this aircraft's own - // model (its icon draws over depth, which height samples pass through). - const height = groundSnap?.heightFor?.(viewer, id, marker.position, () => - [record?.model].filter(Boolean), - ); + // Height samples see through the draw sets (this set and the markers): + // the vertical sample hits the tile skin, not this aircraft. + const height = groundSnap?.heightFor?.(viewer, id, marker.position, { + sets: groundSets, + }); if (!Number.isFinite(height)) return null; - const carto = Cesium.Cartographic.fromCartesian( - marker.position, - Cesium.Ellipsoid.WGS84, - scratchCarto, - ); - return Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - height + (record?.bellyM || 0), - Cesium.Ellipsoid.WGS84, - scratchGround, - ); + const at = toLonLatH(marker.position); + if (!at) return null; + return fromDegrees(at.lon, at.lat, height + (record?.bellyM || 0)); } return { @@ -215,67 +205,66 @@ export function createLocalAdsbModels({ */ frame(markers, preferences, nowMs) { if (destroyed) return; - if (!regime(preferences)) { - if (models.size || pending.size) releaseAll(); + const pose = camera.pose(); + if (!regime(preferences, pose)) { + if (models.size) releaseAll(); eligible = new Set(); for (const marker of markers.values()) marker.modelOwnsVisual = false; return; } if (nowMs - lastEligibilityAt >= FLEET_DR_INTERVAL_MS) { lastEligibilityAt = nowMs; - refreshEligibility(markers, preferences); + refreshEligibility(markers, preferences, pose); } - const occluder = horizonOccluder(viewer.camera); + const horizon = horizonFrom(pose.position); + const items = []; for (const [id, marker] of markers) { const record = models.get(id); marker.modelOwnsVisual = false; if (!record || !marker.position) continue; + const spec = civilAircraftModelSpec(marker.klass); + const url = resolveAsset(spec.url); + noteAsset(record, url, spec.bellyM); const position = placement(id, marker); - if (!position || !occluder.isPointVisible(marker.position)) { - showModel(record, false); - continue; - } - scratchHpr.heading = Cesium.Math.toRadians( - (marker.courseDeg || 0) + MODEL_HEADING_OFFSET_DEG, - ); - scratchHpr.pitch = 0; - scratchHpr.roll = 0; - placeModel( - record, - Cesium.Transforms.headingPitchRollToFixedFrame( - position, - scratchHpr, - Cesium.Ellipsoid.WGS84, - undefined, - scratchMatrix, - ), - ); - if (!record.model.ready) { - showModel(record, false); - continue; - } - showModel(record, true); - marker.modelOwnsVisual = true; + const shown = + Boolean(position) && horizon.isPointVisible(marker.position); + items.push({ + id, + // Unplaced, it waits hidden where it last was (or at the marker). + pos: position ?? marker.position, + url, + orientation: { + heading: + ((marker.courseDeg || 0) + MODEL_HEADING_OFFSET_DEG) * + RADIANS_PER_DEGREE, + pitch: 0, + roll: 0, + }, + scale: spec.scale, + minPixelSize: MODEL_MIN_PX, + tint, + colorBlend: { mode: 'mix', amount: spec.blendAmount }, + environmentMap: AIRCRAFT_ENVIRONMENT_MAP_OPTIONS.enabled, + show: shown, + }); + if (shown && record.ready) marker.modelOwnsVisual = true; } - for (const id of [...models.keys()]) if (!markers.has(id)) release(id); + if (items.length) set.upsert(items); + release([...models.keys()].filter((id) => !markers.has(id))); }, /** - * Drop the model, and any load still in flight, of every aircraft that - * is no longer a marker. The layer calls this whenever markers expire: - * the per-frame pass does not run once the last marker is gone. + * Drop the model of every aircraft that is no longer a marker. The + * layer calls this whenever markers expire: the per-frame pass does not + * run once the last marker is gone. * @param {Map|Set} live Current marker ids. */ retain(live) { if (destroyed) return; - let dropped = false; - for (const id of [...models.keys(), ...pending.keys()]) { - if (live.has(id)) continue; - release(id); - eligible.delete(id); - dropped = true; - } - if (dropped) eligible = new Set(eligible); + const gone = [...models.keys()].filter((id) => !live.has(id)); + if (!gone.length) return; + release(gone); + eligible = new Set([...eligible].filter((id) => live.has(id))); }, /** Drop every model (3D off, layer disabled). */ @@ -286,12 +275,23 @@ export function createLocalAdsbModels({ return models.size; }, + /** The models set's id, for picks and height queries. */ + setId, + + /** Whether the set draws (with the layer). */ + get show() { + return set.show; + }, + set show(value) { + if (!destroyed) set.show = value; + }, + destroy() { - destroyed = true; releaseAll(); + destroyed = true; + offReady(); groundSnap?.clear?.(); - if (!viewer.isDestroyed?.() && !collection.isDestroyed()) - viewer.scene.primitives.remove(collection); + set.dispose(); }, }; } diff --git a/src/render/cesium/draw.test.mjs b/src/render/cesium/draw.test.mjs index ceb91030a..57d9bc8b6 100644 --- a/src/render/cesium/draw.test.mjs +++ b/src/render/cesium/draw.test.mjs @@ -4,6 +4,7 @@ import test from 'node:test'; import { bindRenderer, drawOf, findDraw } from '../rendererOf.js'; import { createCesiumDraw, revealUniform, unboundDrawPart } from './draw.js'; import { drawHitOf } from './drawHit.js'; +import { MODEL_RETRY_MS } from './drawModels.js'; // Node has no WebGL context to report line-width limits. Cesium.ContextLimits._minimumAliasedLineWidth = 1; @@ -3838,6 +3839,52 @@ test('a model load superseded or failed settles once', async () => { } }); +test('a failed model load is tried again on a later update, after a wait', async () => { + const { loads, restore } = fakeModelLoads(); + const realNow = Date.now; + let now = 1_000_000; + Date.now = () => now; + try { + const scene = fakeScene(); + const part = createCesiumDraw({ + scene, + report: (error) => assert.fail(error), + }); + const set = part.port.models({ id: 'm' }); + const item = { + id: 'a', + pos: { lon: 0, lat: 0 }, + url: 'a.glb', + orientation: { heading: 0, pitch: 0, roll: 0 }, + }; + set.upsert([item]); + const host = scene.added[0]; + loads[0].reject(new Error('network')); + await settle(); + assert.equal(host.failed, 1); + now += MODEL_RETRY_MS - 1; + set.upsert([{ ...item }]); + assert.equal(loads.length, 1, 'not before the wait'); + now += 1; + set.upsert([{ ...item }]); + assert.equal(loads.length, 2, 'the same url again'); + assert.equal(host.failed, 0, 'loading again, not failed'); + assert.equal(host.loading, 1); + const ready = []; + set.on('ready', (id) => ready.push(id)); + loads[1].resolve(); + await settle(); + loads[1].ready(); + assert.deepEqual(ready, ['a']); + set.upsert([{ ...item }]); + assert.equal(loads.length, 2, 'a loaded model is not loaded again'); + set.dispose(); + } finally { + Date.now = realNow; + restore(); + } +}); + test('a model past its pixel cap is scaled down each frame; fades and culls too', async () => { const { loads, restore } = fakeModelLoads(); try { diff --git a/src/render/cesium/drawModels.js b/src/render/cesium/drawModels.js index c9e5df414..818fb16a4 100644 --- a/src/render/cesium/drawModels.js +++ b/src/render/cesium/drawModels.js @@ -15,6 +15,9 @@ * measures `minPixelSize`), `scaleByDistance`, `fadeByDistance` (the tint's * alpha) and the set's `horizonCull`. * + * A failed load is tried again when its item is next updated, once + * `MODEL_RETRY_MS` has passed. + * * `shading: 'thermal'` draws the model unlit and white-hot (its texture * left out), then tinted as asked: a hot target, as the thermal views draw * them. Heights are absolute: models clamp nothing. @@ -27,6 +30,13 @@ const BLEND_MODES = { mix: Cesium.ColorBlendMode.MIX, }; +/** + * How long a failed load waits before an update of its item tries the url + * again (a fleet updates every frame; a dropped request or a server + * hiccup should not leave the item without its model for good). + */ +export const MODEL_RETRY_MS = 5000; + /** Cesium's own blend amount, for a `mix` that names none. */ const DEFAULT_MIX = 0.5; @@ -80,8 +90,10 @@ const scratchHpr = new Cesium.HeadingPitchRoll(); const scratchMatrix = new Cesium.Matrix4(); const scratchSphere = new Cesium.BoundingSphere(); const scratchColor = new Cesium.Color(); -/** The colour last written to each model, as a key. */ +/** The colour last written to each model. */ const writtenColors = new WeakMap(); +/** What the per-frame pass found, for a model it does not run on. */ +const STILL = Object.freeze({ scale: 1, alpha: 1, shown: true }); /** An item's position as Cesium's, into `result`. */ function positionOf(pos, result) { @@ -96,6 +108,14 @@ function positionOf(pos, result) { ); } +/** A tint as a key: a CSS string as it is, an RGBA array joined. */ +const tintKey = (tint) => + tint === undefined || tint === null + ? null + : typeof tint === 'string' + ? tint + : tint.join(','); + /** Whether an item needs the per-frame pass. */ const needsFrame = (item, spec) => item.maxPixelSize > 0 || @@ -171,6 +191,7 @@ export function createModelSets({ host.loading -= 1; if (failed && entry.token === token) { entry.failed = true; + entry.failedAt = Date.now(); host.failed += 1; } requestRender(); @@ -284,10 +305,9 @@ export function createModelSets({ if (model.colorBlendAmount !== amount) model.colorBlendAmount = amount; // An empty `displayRange` shows nothing. const hidden = range && !(range[1] > range[0]); - entry.styled = { range: rangeKey }; + if (entry.styled?.range !== rangeKey) entry.styled = { range: rangeKey }; entry.dynamic = needsFrame(item, record.spec); - const frame = entry.frame ?? { scale: 1, alpha: 1, shown: true }; - apply(entry, model, frame, hidden); + apply(entry, model, entry.frame ?? STILL, hidden); } /** @@ -305,9 +325,9 @@ export function createModelSets({ color.alpha *= frame.alpha; // Written only when what is asked changes, so a theme's own write to a // model's colour stands until then. - const key = `${color.red},${color.green},${color.blue},${color.alpha}`; - if (writtenColors.get(model) !== key) { - writtenColors.set(model, key); + const written = writtenColors.get(model); + if (!written || !Cesium.Color.equals(written, color)) { + writtenColors.set(model, Cesium.Color.clone(color, written)); model.color = color; } const show = @@ -334,10 +354,12 @@ export function createModelSets({ model: null, at: new Cesium.Cartesian3(), tint: null, + tintKey: undefined, radius: 0, next: null, token: null, failed: false, + failedAt: 0, settleLoad: null, styled: null, dynamic: false, @@ -352,8 +374,12 @@ export function createModelSets({ entry.pickId.lodGroup = item.lodGroup; } positionOf(item.pos, entry.at); - entry.tint = - item.tint === undefined || item.tint === null ? null : toColor(item.tint); + // A fleet re-poses every frame with the same tint: parsed when it changes. + const tint = tintKey(item.tint); + if (entry.tintKey !== tint) { + entry.tintKey = tint; + entry.tint = tint === null ? null : toColor(item.tint); + } if (entry.url !== item.url && item.url === entry.modelUrl) { // Back to the url it draws: the load in between is not wanted. cancel(record, entry); @@ -362,7 +388,8 @@ export function createModelSets({ // The model it draws keeps up while another loads. for (const model of [entry.model, entry.next]) if (model) style(record, entry, model); - if (entry.url !== item.url) load(record, entry); + const retry = entry.failed && Date.now() - entry.failedAt >= MODEL_RETRY_MS; + if (entry.url !== item.url || retry) load(record, entry); } /** Stop the entry's load in flight, keeping the model it draws. */ diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 5b04b6ba6..d7bf87c9a 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -43,7 +43,6 @@ "src/layers/launches/launchPad.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/rendering.js", - "src/layers/localAdsb/models.js", "src/layers/military/lifecycle.js", "src/layers/military/motion.js", "src/layers/military/policy.js", diff --git a/src/services/groundSnap.js b/src/services/groundSnap.js index 39235923c..012e2ee21 100644 --- a/src/services/groundSnap.js +++ b/src/services/groundSnap.js @@ -48,6 +48,7 @@ import * as Cesium from 'cesium'; import { heightsFor } from '../render/cesium/heights.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 @@ -169,7 +170,8 @@ function _tilesReady(viewer) { * Create a per-layer ground-snap cache. * @returns {{ * heightFor: (viewer: Cesium.Viewer, icao: string, pos: Cesium.Cartesian3, - * getExclusions?: () => Array) => number|null, + * getExclusions?: (() => Array)|{sets: string[]}) + * => number|null, * forget: (icao: string) => void, * clear: () => void, * }} @@ -287,7 +289,10 @@ export function createGroundSnap({ groundFloor }) { * @param {(() => Array)|undefined} getExclusions - Lazily builds the * scene.sampleHeight objectsToExclude list (own billboards/models/entities — * the vertical pick ray at a plane's OWN lat/lon lands on its icon/model - * otherwise). Only invoked when a sample actually fires. + * otherwise). Only invoked when a sample actually fires. `{sets}` (draw + * set ids) instead samples through 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. * @returns {number|null} */ function heightFor(viewer, icao, pos, getExclusions) { @@ -359,11 +364,15 @@ export function createGroundSnap({ groundFloor }) { Cesium.Ellipsoid.WGS84, scratchCarto, ); - const sampled = carto - ? heightsFor(viewer.scene).now(carto, { - exclude: getExclusions ? getExclusions() : undefined, - }) - : null; + // 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, + }); // 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(); diff --git a/src/services/groundSnap.test.mjs b/src/services/groundSnap.test.mjs index 8dfe42c46..ddbcf2427 100644 --- a/src/services/groundSnap.test.mjs +++ b/src/services/groundSnap.test.mjs @@ -2,6 +2,7 @@ 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'; const groundFloor = { cachedMeshFloor: () => null, @@ -60,3 +61,26 @@ test('a retry backoff stamped before the clock stepped back does not wait for it assert.equal(snap.heightFor(viewer, 'a00001', atDenverAirport), 1650); assert.equal(viewer.calls.samples, 1); }); + +test('draw-set exclusions sample through the renderer’s query port', () => { + 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, + ); + 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); +}); diff --git a/src/testSupport/fakeDrawPort.mjs b/src/testSupport/fakeDrawPort.mjs index b8c61ac1e..615809ecd 100644 --- a/src/testSupport/fakeDrawPort.mjs +++ b/src/testSupport/fakeDrawPort.mjs @@ -19,6 +19,7 @@ export function fakeDrawPort() { show: spec.show !== false, disposed: false, writes: 0, + ready: new Set(), }; sets.set(spec.id, record); const write = (fn) => { @@ -53,7 +54,11 @@ export function fakeDrawPort() { set show(value) { record.show = value; }, - on: () => () => {}, + on(event, cb) { + if (event !== 'ready') return () => {}; + record.ready.add(cb); + return () => record.ready.delete(cb); + }, dispose() { record.disposed = true; }, @@ -72,6 +77,11 @@ export function fakeDrawPort() { points: make('points'), lines: make('lines'), shapes: make('shapes'), + models: make('models'), + /** Fire a models set's `ready` for an item, as a load finishing does. */ + ready(setId, id) { + for (const cb of [...(sets.get(setId)?.ready ?? [])]) cb(id); + }, clampState: () => 'draped', on: () => () => {}, atlas() {},