diff --git a/scripts/package-boundaries.json b/scripts/package-boundaries.json index a60549f29..0c66018f5 100644 --- a/scripts/package-boundaries.json +++ b/scripts/package-boundaries.json @@ -1474,6 +1474,7 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/idSwitches.js", "src/data/layerState.js", @@ -1489,12 +1490,15 @@ "src/data/trackingClickGesture.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", + "src/render/color.js", "src/layers/flights/queries.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", @@ -1526,6 +1530,7 @@ "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/geo/index.js", "src/layers/flights/records.js", "src/layers/flights/recordPolicy.js", @@ -1586,6 +1591,7 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/idSwitches.js", "src/data/layerState.js", @@ -1602,7 +1608,9 @@ "src/layers/military/ingestion.js", "src/layers/military/lifecycle.js", "src/layers/military/motion.js", + "src/data/renderedFrames.js", "src/layers/military/policy.js", + "src/render/color.js", "src/layers/military/queries.js", "src/render/cesium/camera.js", "src/render/cesium/frame.js", @@ -1635,6 +1643,7 @@ "src/layers/military/state.js", "src/layers/military/testing.js", "src/layers/military/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/military/records.js", "src/layers/military/recordPolicy.js", "src/layers/military/snapshotRenderer.js", @@ -1689,6 +1698,7 @@ "src/data/cockpitContactDot.js", "src/data/contactMatch.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/idSwitches.js", "src/data/layerState.js", @@ -2458,6 +2468,7 @@ "src/data/cctvLod.js", "src/data/cctvViewshed.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/trackingClickGesture.js", "src/layers/cctv/calibration.js", @@ -2744,6 +2755,7 @@ "exports": ["./layers/radio"], "modules": [ "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/idSwitches.js", "src/data/layerState.js", @@ -3274,6 +3286,7 @@ "src/data/groundFloor.js", "src/data/groundSnap.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", @@ -3437,11 +3450,13 @@ "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", @@ -3449,6 +3464,7 @@ "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", "src/geo/geodesic.js", "src/layers/installations/index.js", @@ -4255,6 +4271,7 @@ "src/data/focusDeemphasis.js", "src/data/geoid.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/infrastructure.js", "src/data/osmOverlays.js", @@ -4392,11 +4409,13 @@ "src/layers/firms/viewport.js", "src/layers/flights/controller.js", "src/layers/flights/enrichment.js", + "src/geo/frustum.js", "src/layers/flights/evidence.js", "src/layers/flights/index.js", "src/layers/flights/ingestion.js", "src/layers/flights/lifecycle.js", "src/layers/flights/motion.js", + "src/data/renderedFrames.js", "src/layers/flights/policy.js", "src/layers/flights/queries.js", "src/layers/flights/rendering.js", @@ -4404,6 +4423,7 @@ "src/layers/flights/state.js", "src/layers/flights/testing.js", "src/layers/flights/tracking.js", + "src/data/trackedAircraftIcon.js", "src/layers/installations/controls.js", "src/geo/geodesic.js", "src/layers/installations/index.js", @@ -5570,6 +5590,7 @@ "src/data/gtfsRealtime.js", "src/geoDistance.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/labelArbiter.js", @@ -5648,6 +5669,7 @@ "modules": [ "src/data/headingDegrees.js", "src/data/iconOrientation.js", + "src/data/screenRotation.js", "src/render/camera/poseSignature.js", "src/data/inputOwnership.js", "src/data/transitFeeds.js", diff --git a/src/data/aircraftEmergencyAnalyst.test.mjs b/src/data/aircraftEmergencyAnalyst.test.mjs index 079dfc663..e5d116904 100644 --- a/src/data/aircraftEmergencyAnalyst.test.mjs +++ b/src/data/aircraftEmergencyAnalyst.test.mjs @@ -1,5 +1,5 @@ -import * as Cesium from 'cesium'; import { TRACKED_ICON_COLOR } from '../layers/military/policy.js'; +import { TRACKED_CYAN } from '../layers/flights/policy.js'; import { createRendering as civilRendering } from '../layers/flights/rendering.js'; import { createRendering as militaryRendering } from '../layers/military/rendering.js'; import { createMilitarySnapshotRenderer } from '../layers/military/snapshotRenderer.js'; @@ -456,7 +456,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do const red = rendering._fleetBillboardColor('civil', { emergency: aircraftEmergency({ squawk: '7700' }), }); - assert.ok(red.red > 0.9 && red.green < 0.5); + assert.ok(red[0] > 0.9 && red[1] < 0.5); flightState.records.data.set('civil', { emergency: aircraftEmergency({ squawk: '7700' }), }); @@ -466,7 +466,7 @@ test('tint priorities cover normal, priority, emergency, tracking and Cockpit do flightState._trackedIcao = 'civil'; assert.equal( rendering._modelColor('civil'), - factory === civilRendering ? Cesium.Color.CYAN : TRACKED_ICON_COLOR, + factory === civilRendering ? TRACKED_CYAN : TRACKED_ICON_COLOR, ); flightState._trackedIcao = null; flightState.records.data.set('civil', { emergency: null }); diff --git a/src/data/flights.test.mjs b/src/data/flights.test.mjs index 9100a140a..4b09b0761 100644 --- a/src/data/flights.test.mjs +++ b/src/data/flights.test.mjs @@ -517,9 +517,16 @@ test('real civil track path creates no native label and publishes every cached h ); const entity = followedOf(viewer)?.entity; assert.ok( - entity instanceof Cesium.Entity, - 'trackById must create the real Cesium entity', + readEntityRecord(entity)?.trackedId, + 'trackById must record the tracked contact', ); + assert.ok( + !(entity instanceof Cesium.Entity), + 'tracking draws through the draw port, not a viewer entity', + ); + assert.ok(entity.position, 'Cockpit sees a contact it can fly'); + assert.equal(readEntityRecord(entity).drawn(), true); + assert.equal(entity.show, true); assert.equal(entity.label, undefined); assert.ok( entities.values.every((candidate) => candidate.label === undefined), @@ -579,8 +586,8 @@ test('real civil track path creates no native label and publishes every cached h assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title); assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details); - const display = entity.position.getValue(now); - assert.ok(display, 'tracked position callback must seed its frame cache'); + const display = followedOf(viewer)?.position(Date.now()); + assert.ok(display, 'the follow target must seed the frame cache'); assert.equal( entry.position(), display, diff --git a/src/data/focusDeemphasis.js b/src/data/focusDeemphasis.js index f3e8792a1..a02323799 100644 --- a/src/data/focusDeemphasis.js +++ b/src/data/focusDeemphasis.js @@ -1,4 +1,5 @@ import * as Cesium from 'cesium'; +import { findCamera, findQuery } from '../render/rendererOf.js'; /** * Focus-aware sprite treatment shared by the live contact layers. @@ -213,6 +214,91 @@ export function publishFocusTargetFromCachedPosition({ displayPosition, _scratchScreen, ); + return publishFocusRect({ + ownerLayer, + id, + screen, + cameraDistance: Cesium.Cartesian3.distance( + camera.positionWC, + displayPosition, + ), + frameNumber: scene.frameState?.frameNumber ?? -1, + widthPx, + heightPx, + params, + }); +} + +/** + * `publishFocusTargetFromCachedPosition` through the renderer bound to + * `viewer`: its query port projects the cached position and its camera's + * pose gives the distance. Same contract: the position must be the one the + * tracking/render path already cached this frame. + * + * @param {object} input + * @param {string} input.ownerLayer + * @param {string|number} input.id + * @param {object} input.viewer The host the renderer is bound to. + * @param {{x: number, y: number, z: number}} input.displayPosition Cached display position. + * @param {number} [input.widthPx=24] + * @param {number} [input.heightPx=24] + * @param {Partial} [input.params] + * @returns {object|null} Published target, or null when it cannot be projected. + */ +export function publishFocusTargetAt({ + ownerLayer, + id, + viewer, + displayPosition, + widthPx = 24, + heightPx = 24, + params, +}) { + const query = viewer ? findQuery(viewer) : null; + let eye = null; + try { + eye = viewer ? (findCamera(viewer)?.pose().position ?? null) : null; + } catch { + eye = null; + } + if ( + !ownerLayer || + id === null || + id === undefined || + !query || + !eye || + !displayPosition + ) { + clearFocusTarget(ownerLayer, id); + return null; + } + return publishFocusRect({ + ownerLayer, + id, + screen: query.project(displayPosition), + cameraDistance: Math.hypot( + displayPosition.x - eye.x, + displayPosition.y - eye.y, + displayPosition.z - eye.z, + ), + frameNumber: -1, + widthPx, + heightPx, + params, + }); +} + +/** Publish the focus rectangle around `screen`, or clear it when there is none. */ +function publishFocusRect({ + ownerLayer, + id, + screen, + cameraDistance, + frameNumber, + widthPx, + heightPx, + params, +}) { if (!screen || !Number.isFinite(screen.x) || !Number.isFinite(screen.y)) { clearFocusTarget(ownerLayer, id); return null; @@ -232,11 +318,8 @@ export function publishFocusTargetFromCachedPosition({ bottom: screen.y + halfHeight + padding, }, paddingPx: padding, - cameraDistance: Cesium.Cartesian3.distance( - camera.positionWC, - displayPosition, - ), - frameNumber: scene.frameState?.frameNumber ?? -1, + cameraDistance, + frameNumber, }; if (appeared) { for (const listener of _focusAppearListeners) { diff --git a/src/data/iconOrientation.js b/src/data/iconOrientation.js index f5058a192..5796bdb48 100644 --- a/src/data/iconOrientation.js +++ b/src/data/iconOrientation.js @@ -23,16 +23,10 @@ */ import * as Cesium from 'cesium'; import { poseSignature } from '../render/camera/poseSignature.js'; - -/** Meters used to give the course vector a stable projection magnitude. */ -const FORWARD_PROBE_M = 2000; -/** - * Minimum camera-plane component before we trust the angle — below this the - * course points almost exactly into/out of the screen and the angle is noise. - */ -const MIN_SCREEN_COMPONENT_M = 0.5; -/** Ignore sub-degree projection noise while retaining deliberate camera-orbit rotation. */ -const ROTATION_DEADBAND_RAD = Cesium.Math.toRadians(0.5); +import { + courseScreenRotation, + stabilizeScreenRotation, +} from './screenRotation.js'; const _scratchEnu = new Cesium.Matrix4(); const _scratchForward = new Cesium.Cartesian3(); @@ -41,7 +35,8 @@ const _scratchWorldForward = new Cesium.Cartesian3(); /** * Computes the billboard rotation (radians, CCW-positive, for * alignedAxis = Cartesian3.ZERO) that points an icon along its real-world - * course in the stable camera-basis approximation described above. + * course in the stable camera-basis approximation described above; the + * scene's camera axes in `screenRotation.js`'s `courseScreenRotation`. * * @param {Cesium.Scene} scene - The scene (projection source). * @param {Cesium.Cartesian3} position - Entity world position. @@ -57,64 +52,15 @@ export function screenProjectedRotation( previous = null, ) { const camera = scene?.camera; - if (!camera?.rightWC || !camera?.upWC || !position) return previous; - - const courseRad = Cesium.Math.toRadians(courseDeg || 0); - Cesium.Cartesian3.fromElements( - Math.sin(courseRad) * FORWARD_PROBE_M, - Math.cos(courseRad) * FORWARD_PROBE_M, - 0, - _scratchForward, - ); - const enu = Cesium.Transforms.eastNorthUpToFixedFrame( + return courseScreenRotation( + camera && { right: camera.rightWC, up: camera.upWC }, position, - Cesium.Ellipsoid.WGS84, - _scratchEnu, + courseDeg, + previous, ); - Cesium.Matrix4.multiplyByPointAsVector( - enu, - _scratchForward, - _scratchWorldForward, - ); - - // Screen x follows camera-right. Window y grows downward, the opposite of - // camera-up. Projecting the vector itself avoids clipping/behind-camera - // failure modes from the old forward-point worldToWindowCoordinates probe. - const dx = Cesium.Cartesian3.dot(_scratchWorldForward, camera.rightWC); - const dy = -Cesium.Cartesian3.dot(_scratchWorldForward, camera.upWC); - if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M) - return previous; - - // Window y grows downward; rotation 0 = icon pointing screen-up. - // Icon direction in window coords after CCW rotation r is (-sin r, -cos r), - // so matching the projected course (dx, dy) gives r = atan2(-dx, -dy). - return Math.atan2(-dx, -dy); } -/** - * Hold a billboard rotation when the newly projected angle differs only by - * sub-degree render noise. The comparison uses the shortest wrapped arc so - * values around ±π do not jump. - * - * @param {number|null} previous Last displayed rotation. - * @param {number|null} next Newly projected rotation. - * @param {number} [deadbandRad=ROTATION_DEADBAND_RAD] Angular hold threshold. - * @returns {number|null} Stable rotation. - */ -export function stabilizeScreenRotation( - previous, - next, - deadbandRad = ROTATION_DEADBAND_RAD, -) { - if (!Number.isFinite(next)) - return Number.isFinite(previous) ? previous : null; - if (!Number.isFinite(previous)) return next; - const delta = Math.atan2( - Math.sin(next - previous), - Math.cos(next - previous), - ); - return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next; -} +export { stabilizeScreenRotation }; const _occluder = new Cesium.EllipsoidalOccluder( Cesium.Ellipsoid.WGS84, diff --git a/src/data/meshFloorSampler.test.mjs b/src/data/meshFloorSampler.test.mjs index 019000314..18fa77135 100644 --- a/src/data/meshFloorSampler.test.mjs +++ b/src/data/meshFloorSampler.test.mjs @@ -21,6 +21,7 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; import * as Cesium from 'cesium'; import { sampleMeshFloorCells } from './meshFloorSampler.js'; +import { bindRenderer } from '../render/rendererOf.js'; import { resolveEllipsoidalGround } from './terrainHeights.js'; import { cachedGroundFloor, cachedMeshFloor, setMeshFloorPreferred, @@ -153,3 +154,32 @@ test('sampler: a scene without depth-texture support is never probed', async () assert.equal(calls, 0); assert.equal(cachedMeshFloor(cell.lat, cell.lon), null); }); + +test('sampler: with `sets` the probe asks the query port, naming those 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; + }, + }, + }); + sampleMeshFloorCells(viewer, [cell], { + sets: ['flights-models:1', 'flights-icons:1'], + viewerLat: cell.lat, + viewerLon: cell.lon, + }); + assert.equal(asked.length, 1); + assert.deepEqual(asked[0].options.exclude, ['flights-models:1', 'flights-icons:1']); + assert.ok(Math.abs(asked[0].point.lat - cell.lat) < 0.05); + assert.equal(cachedMeshFloor(cell.lat, cell.lon), 138.0); +}); diff --git a/src/data/militaryFlights.test.mjs b/src/data/militaryFlights.test.mjs index c6415c43a..e2d9a889a 100644 --- a/src/data/militaryFlights.test.mjs +++ b/src/data/militaryFlights.test.mjs @@ -439,9 +439,16 @@ test('real military track path creates no native label and publishes every cache ); const entity = followedOf(viewer)?.entity; assert.ok( - entity instanceof Cesium.Entity, - 'trackById must create the real Cesium entity', + readEntityRecord(entity)?.trackedId, + 'trackById must record the tracked contact', ); + assert.ok( + !(entity instanceof Cesium.Entity), + 'tracking draws through the draw port, not a viewer entity', + ); + assert.ok(entity.position, 'Cockpit sees a contact it can fly'); + assert.equal(readEntityRecord(entity).drawn(), true); + assert.equal(entity.show, true); assert.equal(entity.label, undefined); assert.ok( entities.values.every((candidate) => candidate.label === undefined), @@ -507,8 +514,8 @@ test('real military track path creates no native label and publishes every cache assert.equal(entry.title, readEntityRecord(entity)?.labelModel.title); assert.deepEqual(entry.details, readEntityRecord(entity)?.labelModel.details); - const display = entity.position.getValue(now); - assert.ok(display, 'tracked position callback must seed its frame cache'); + const display = followedOf(viewer)?.position(Date.now()); + assert.ok(display, 'the follow target must seed the frame cache'); assert.equal( entry.position(), display, diff --git a/src/data/renderedFrames.js b/src/data/renderedFrames.js new file mode 100644 index 000000000..fbda746d9 --- /dev/null +++ b/src/data/renderedFrames.js @@ -0,0 +1,33 @@ +/** + * @module data/renderedFrames + * @description How many frames a viewer's renderer has drawn: a key that + * changes once per drawn frame, after it is drawn, for per-frame caches. + * Everything that reads a cache keyed by it in one tick (the follow camera, + * the frame's `preUpdate` and `preRender` work, the readouts in its + * `postRender`) sees one value; a tick that draws nothing keeps the key, as + * the default renderer's own frame number does. + */ +import { findFrame } from '../render/rendererOf.js'; + +/** Per frame port: `{count}`, counted on its `postRender`. */ +const counters = new WeakMap(); + +/** + * The number of frames drawn so far on `viewer`'s frame port, or -1 when it + * has none. Counting starts on the first call. + * @param {object|null|undefined} viewer + * @returns {number} + */ +export function renderedFrames(viewer) { + const frame = viewer ? findFrame(viewer) : null; + if (!frame) return -1; + let counter = counters.get(frame); + if (!counter) { + counter = { count: 0 }; + counters.set(frame, counter); + frame.on('postRender', () => { + counter.count += 1; + }); + } + return counter.count; +} diff --git a/src/data/renderedFrames.test.mjs b/src/data/renderedFrames.test.mjs new file mode 100644 index 000000000..241c6b330 --- /dev/null +++ b/src/data/renderedFrames.test.mjs @@ -0,0 +1,29 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { bindRenderer } from '../render/rendererOf.js'; +import { renderedFrames } from './renderedFrames.js'; + +test('the key changes once per drawn frame, after it is drawn', () => { + const viewer = {}; + const listeners = { postRender: new Set() }; + bindRenderer(viewer, { + frame: { + on(phase, cb) { + listeners[phase].add(cb); + return () => listeners[phase].delete(cb); + }, + }, + }); + assert.equal(renderedFrames(viewer), 0); + assert.equal(renderedFrames(viewer), 0, 'reading does not advance it'); + assert.equal(listeners.postRender.size, 1); + for (const cb of listeners.postRender) cb({}); + assert.equal(renderedFrames(viewer), 1); + renderedFrames(viewer); + assert.equal(listeners.postRender.size, 1, 'one listener per frame port'); +}); + +test('without a frame port the key is -1', () => { + assert.equal(renderedFrames(null), -1); + assert.equal(renderedFrames({}), -1); +}); diff --git a/src/data/screenRotation.js b/src/data/screenRotation.js new file mode 100644 index 000000000..cbad595b9 --- /dev/null +++ b/src/data/screenRotation.js @@ -0,0 +1,81 @@ +/** + * @module data/screenRotation + * @description The screen rotation that points a camera-facing icon along + * its real-world course, from the camera's right and up axes (a camera + * port pose's `right` and `up`), and the deadband that holds it through + * render noise. See `iconOrientation.js` for why the course is projected + * onto the camera basis. No engine. + */ +import { eastNorthUp, frameVector } from '../geo/frames.js'; +import { dot, toRadians, vec } from '../geo/vector.js'; + +/** Meters used to give the course vector a stable projection magnitude. */ +const FORWARD_PROBE_M = 2000; +/** + * Minimum camera-plane component before we trust the angle — below this the + * course points almost exactly into/out of the screen and the angle is noise. + */ +const MIN_SCREEN_COMPONENT_M = 0.5; +/** Ignore sub-degree projection noise while retaining deliberate camera-orbit rotation. */ +const ROTATION_DEADBAND_RAD = toRadians(0.5); + +/** + * The icon rotation (radians, counter-clockwise on screen, 0 pointing + * screen-up) that points it along `courseDeg` at `position`, projected onto + * the camera's `right` and `up` axes (ECEF). + * @param {{right?: object, up?: object}|null} basis The camera's axes. + * @param {{x: number, y: number, z: number}|null} position ECEF. + * @param {number} courseDeg Degrees clockwise from north. + * @param {number|null} [previous] Kept when the projection is unknown. + * @returns {number|null} + */ +export function courseScreenRotation( + basis, + position, + courseDeg, + previous = null, +) { + if (!basis?.right || !basis?.up || !position) return previous; + const courseRad = toRadians(courseDeg || 0); + const forward = frameVector( + eastNorthUp(position), + vec( + Math.sin(courseRad) * FORWARD_PROBE_M, + Math.cos(courseRad) * FORWARD_PROBE_M, + 0, + ), + ); + // Screen x follows camera-right; window y grows downward, against up. + const dx = dot(forward, basis.right); + const dy = -dot(forward, basis.up); + if (dx * dx + dy * dy < MIN_SCREEN_COMPONENT_M * MIN_SCREEN_COMPONENT_M) + return previous; + // Icon direction in window coords after CCW rotation r is (-sin r, -cos r), + // so matching the projected course (dx, dy) gives r = atan2(-dx, -dy). + return Math.atan2(-dx, -dy); +} + +/** + * Hold a billboard rotation when the newly projected angle differs only by + * sub-degree render noise. The comparison uses the shortest wrapped arc so + * values around ±π do not jump. + * + * @param {number|null} previous Last displayed rotation. + * @param {number|null} next Newly projected rotation. + * @param {number} [deadbandRad=ROTATION_DEADBAND_RAD] Angular hold threshold. + * @returns {number|null} Stable rotation. + */ +export function stabilizeScreenRotation( + previous, + next, + deadbandRad = ROTATION_DEADBAND_RAD, +) { + if (!Number.isFinite(next)) + return Number.isFinite(previous) ? previous : null; + if (!Number.isFinite(previous)) return next; + const delta = Math.atan2( + Math.sin(next - previous), + Math.cos(next - previous), + ); + return Math.abs(delta) < Math.max(0, deadbandRad) ? previous : next; +} diff --git a/src/data/tr3bRegistry.test.mjs b/src/data/tr3bRegistry.test.mjs index 51e19c3bd..883f51178 100644 --- a/src/data/tr3bRegistry.test.mjs +++ b/src/data/tr3bRegistry.test.mjs @@ -250,21 +250,25 @@ test('both flight layers keep a converted contact 2D and visible (render invaria // 3. Every aircraftIcon() CALL SITE routes through the kind resolver, so no // refresh path (poll reconciler, raster swap, presentation, tracked - // entity) can silently revert a conversion. + // billboard) can silently revert a conversion. The tracked billboard's + // sites share one helper; the fleet's live in aircraftIconLayer.js. const code = stripComments(source); const callSites = code.match(/aircraftIcon\(\s*[^;]*?\)/g) || []; - assert.equal(callSites.length >= 4, true, `${name}: expected the known aircraftIcon call sites`); + assert.equal(callSites.length >= 1, true, `${name}: expected the known aircraftIcon call sites`); for (const call of callSites) { assert.match(call, /aircraftIcon\(\s*\s*(?:(?:parts\.)?rendering\.)?_iconKind\(\s*/, `${name}: ${call.replace(/\s+/g, ' ')} must resolve its sprite kind through _iconKind`); } - // 4. Orientation contract is untouched: still a screen-projected rotation - // with alignedAxis ZERO, and no new per-frame CallbackProperty. - assert.match(source, /alignedAxis: Cesium\.Cartesian3\.ZERO/, `${name}: alignedAxis stays ZERO`); - assert.doesNotMatch(source, /isTr3b[\s\S]{0,200}new Cesium\.CallbackProperty/, + // 4. Orientation contract is untouched: the tracked billboard is still a + // screen-rotated icon, and no per-frame CallbackProperty is added. + assert.doesNotMatch(source, /new Cesium\.CallbackProperty/, `${name}: the Easter egg adds no per-frame CallbackProperty`); } + const tracked = stripComments( + await readFile(new URL('./trackedAircraftIcon.js', import.meta.url), 'utf8'), + ); + assert.match(tracked, /rotationMode: 'screen'/, 'the tracked billboard rotates in screen space'); }); test('conversions are session-scoped and no lifecycle path clears them', async () => { diff --git a/src/data/trackedAircraftIcon.js b/src/data/trackedAircraftIcon.js new file mode 100644 index 000000000..ca1a2948c --- /dev/null +++ b/src/data/trackedAircraftIcon.js @@ -0,0 +1,197 @@ +/** + * @module data/trackedAircraftIcon + * @description The tracked aircraft's billboard, for the flights and military + * layers: one icon in an icon set of the renderer's draw port, re-posed, + * re-rotated and recoloured each drawn frame (its `preRender`) from the + * layer's own per-frame display cache, the same value the follow camera + * frames. It is drawn over depth, screen-rotated along the course, and + * sized by eye distance. It is only ever written in `preRender`, so the + * display cache is never sampled between frames; a frame whose icon would + * draw exactly as the last writes nothing, so a parked contact asks for no + * frames. + * + * The set is made on the first `show` and kept for the layer's lifetime; + * `hide` empties it and stops the frame work, `dispose` lets it go. Its + * pick names the set and the contact's id, as the fleet icons' do. + * `visible` hides the icon while it stays shown (Cockpit flies the + * aircraft from its own seat). + */ +import { findDraw, findFrame } from '../render/rendererOf.js'; + +/** Uniquifier for the sets' ids. */ +let instances = 0; + +const sameColor = (a, b) => + a === b || + (Array.isArray(a) && + Array.isArray(b) && + a.length === b.length && + a.every((value, i) => value === b[i])); + +/** + * Whether `setId` names another layer's tracked icon set: a layer must not + * take a pick of that icon for one of its own contacts. + * @param {string} setId A picked draw set's id. + * @param {string} setPrefix The asking layer's prefix, e.g. `military`. + * @returns {boolean} + */ +export function isOtherTrackedIconSet(setId, setPrefix) { + return ( + typeof setId === 'string' && + setId.includes('-tracked-icon:') && + !setId.startsWith(`${setPrefix}-tracked-icon:`) + ); +} + +/** + * @param {object} options + * @param {() => object|null} options.viewer The layer's viewer, read when + * the set is made. + * @param {string} options.setPrefix The set id's prefix, e.g. `flights`. + */ +export function createTrackedAircraftIcon({ viewer, setPrefix }) { + let set = null; + let offFrame = null; + /** What is shown: the id and the per-frame readers. */ + let shown = null; + /** The item last written, to skip a frame that changes nothing. */ + let written = null; + /** Whether the shown icon draws (false while Cockpit hides it). */ + let visible = true; + + /** Ask for a frame, whose `preRender` draws the icon. */ + function requestFrame(reason) { + const host = viewer(); + if (host) findFrame(host)?.requestRender(`${setPrefix}: ${reason}`); + } + + function ensureSet() { + if (set) return set; + const host = viewer(); + const port = host ? findDraw(host) : null; + if (!port) return null; + set = port.icons({ id: `${setPrefix}-tracked-icon:${++instances}` }); + return set; + } + + /** Write the icon as it is drawn this frame, when that changed. */ + function draw() { + if (!shown || !set) return; + const pos = shown.position(); + const item = { + id: shown.id, + pos: pos ? { x: pos.x, y: pos.y, z: pos.z } : { x: 0, y: 0, z: 0 }, + show: Boolean(pos) && visible, + image: shown.image, + size: [shown.sprite.width, shown.sprite.height], + scale: shown.sprite.scale, + scaleByDistance: shown.sprite.scaleByDistance, + color: shown.color(), + rotationMode: 'screen', + rotation: pos ? shown.rotation() : 0, + disableDepthTest: Number.POSITIVE_INFINITY, + }; + if ( + written && + written.id === item.id && + written.show === item.show && + written.pos.x === item.pos.x && + written.pos.y === item.pos.y && + written.pos.z === item.pos.z && + written.image === item.image && + written.scale === item.scale && + written.rotation === item.rotation && + sameColor(written.color, item.color) + ) + return; + written = item; + set.upsert([item]); + } + + return { + /** + * Show the tracked contact `id`'s icon, drawn before each frame from the + * next one on. + * @param {object} target + * @param {string} target.id The contact's id. + * @param {string} target.image + * @param {{width: number, height: number, scale: number, + * scaleByDistance: object}} target.sprite + * @param {() => object|null} target.position ECEF this frame; none hides it. + * @param {() => number} target.rotation Screen radians, counter-clockwise. + * @param {() => object} target.color The tint this frame. + */ + show(target) { + this.hide(); + if (!ensureSet()) return; + shown = { ...target }; + const host = viewer(); + offFrame = (host && findFrame(host)?.on('preRender', draw)) ?? null; + requestFrame('tracked icon'); + }, + + /** Draw it from a new image (the class or conversion changed) next frame. */ + setImage(image) { + if (!shown) return; + shown.image = image; + requestFrame('tracked icon image'); + }, + + /** Whether the shown icon draws. */ + get visible() { + return visible; + }, + + /** Hide or show the icon without letting the contact go. */ + setVisible(value) { + if (visible === Boolean(value)) return; + visible = Boolean(value); + requestFrame('tracked icon visibility'); + }, + + /** The set's id while it is made, for picks and height samples. */ + get setId() { + return set?.id ?? null; + }, + + /** Stop showing the icon. */ + hide() { + offFrame?.(); + offFrame = null; + shown = null; + written = null; + visible = true; + if (set?.size()) set.clear(); + }, + + /** Let the set go (layer teardown). */ + dispose() { + this.hide(); + set?.dispose(); + set = null; + }, + }; +} + +/** + * The tracked contact as its readers see it (the tracked card, Cockpit, + * share links): a plain holder that the layer keeps its entity record on. + * Cockpit reads `position` for whether there is a contact to fly and sets + * `show` to hide the icon while it flies it; the record's `drawn` says + * whether the layer still tracks it. + * @param {string} id e.g. `flights:a1b2c3`. + * @param {ReturnType} icon + * @param {() => object|null} position The contact's display position. + */ +export function trackedContactHolder(id, icon, position) { + return { + id, + position: { getValue: () => position() ?? undefined }, + get show() { + return icon.visible; + }, + set show(value) { + icon.setVisible(value); + }, + }; +} diff --git a/src/data/trackedAircraftIcon.test.mjs b/src/data/trackedAircraftIcon.test.mjs new file mode 100644 index 000000000..d707bebe6 --- /dev/null +++ b/src/data/trackedAircraftIcon.test.mjs @@ -0,0 +1,190 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import { bindFakeDraw } from '../testSupport/fakeDrawPort.mjs'; +import { + createTrackedAircraftIcon, + isOtherTrackedIconSet, + trackedContactHolder, +} from './trackedAircraftIcon.js'; + +/** A viewer double with a fake draw port and a frame port whose preRender the test runs. */ +function harness() { + const viewer = {}; + const listeners = new Set(); + const requests = []; + const frame = { + requestRender(reason) { + requests.push(reason); + }, + on(phase, cb) { + assert.equal(phase, 'preRender'); + listeners.add(cb); + return () => listeners.delete(cb); + }, + }; + const { draw } = bindFakeDraw(viewer, { frame }); + const tick = () => { + for (const cb of [...listeners]) cb({}); + }; + return { viewer, draw, listeners, tick, requests }; +} + +const SPRITE = Object.freeze({ + width: 28, + height: 28, + scale: 1.2, + scaleByDistance: { near: 1000, nearValue: 3, far: 8e6, farValue: 0.5 }, +}); + +test('the tracked billboard is one icon re-posed each frame, and only when it changed', () => { + const { viewer, draw, listeners, tick, requests } = harness(); + const icon = createTrackedAircraftIcon({ + viewer: () => viewer, + setPrefix: 'flights', + }); + assert.equal(icon.setId, null, 'no set before anything is shown'); + let pos = { x: 1, y: 2, z: 3 }; + let rotation = 0.5; + let color = [0, 1, 1, 1]; + icon.show({ + id: 'abc123', + image: 'data:image/svg+xml;base64,AAA', + sprite: SPRITE, + position: () => pos, + rotation: () => rotation, + color: () => color, + }); + const set = draw.find('flights-tracked-icon:'); + assert.ok(set, 'an icon set on the draw port'); + assert.equal(set.kind, 'icons'); + assert.equal(icon.setId, set.spec.id); + assert.equal(listeners.size, 1, 'drawn before each frame'); + assert.equal(set.items.size, 0, 'nothing is drawn between frames'); + assert.equal(requests.length, 1, 'a frame is asked for'); + tick(); + const item = set.items.get('abc123'); + assert.deepEqual(item.pos, { x: 1, y: 2, z: 3 }); + assert.notEqual(item.pos, pos, 'the position is copied'); + assert.deepEqual(item.size, [28, 28]); + assert.equal(item.scale, 1.2); + assert.equal(item.scaleByDistance, SPRITE.scaleByDistance); + assert.equal(item.rotationMode, 'screen'); + assert.equal(item.rotation, 0.5); + assert.deepEqual(item.color, [0, 1, 1, 1]); + assert.equal(item.disableDepthTest, Number.POSITIVE_INFINITY); + assert.equal(item.show, true); + + const writes = set.writes; + color = [0, 1, 1, 1]; + tick(); + assert.equal( + set.writes, + writes, + 'a frame that changes nothing writes nothing', + ); + + pos = { x: 4, y: 5, z: 6 }; + rotation = 1; + color = [0, 1, 1, 0]; + tick(); + assert.equal(set.writes, writes + 1); + assert.deepEqual(set.items.get('abc123').pos, { x: 4, y: 5, z: 6 }); + assert.equal(set.items.get('abc123').rotation, 1); + assert.deepEqual(set.items.get('abc123').color, [0, 1, 1, 0]); + + icon.setImage('data:image/svg+xml;base64,BBB'); + assert.equal(set.items.get('abc123').image, 'data:image/svg+xml;base64,AAA'); + tick(); + assert.equal(set.items.get('abc123').image, 'data:image/svg+xml;base64,BBB'); + + const holder = trackedContactHolder('flights:abc123', icon, () => pos); + assert.equal(holder.show, true); + assert.deepEqual(holder.position.getValue(), { x: 4, y: 5, z: 6 }); + holder.show = false; + tick(); + assert.equal(holder.show, false); + assert.equal(set.items.get('abc123').show, false, 'hidden while kept'); + holder.show = true; + tick(); + assert.equal(set.items.get('abc123').show, true); + + pos = null; + tick(); + assert.equal(set.items.get('abc123').show, false, 'no position hides it'); + + icon.hide(); + assert.equal(set.items.size, 0); + assert.equal(listeners.size, 0, 'no frame work while hidden'); + icon.setImage('ignored'); + assert.equal(set.items.size, 0); + + icon.dispose(); + assert.equal(draw.sets.get(set.spec.id).disposed, true); +}); + +test('each layer lifetime gets its own set id, and showing again replaces the contact', () => { + const { viewer, draw, tick } = harness(); + const a = createTrackedAircraftIcon({ + viewer: () => viewer, + setPrefix: 'military', + }); + const b = createTrackedAircraftIcon({ + viewer: () => viewer, + setPrefix: 'military', + }); + const target = (id) => ({ + id, + image: 'img', + sprite: SPRITE, + position: () => ({ x: 1, y: 1, z: 1 }), + rotation: () => 0, + color: () => [1, 1, 1, 1], + }); + a.show(target('one')); + b.show(target('two')); + tick(); + assert.notEqual(a.setId, b.setId); + a.show(target('three')); + tick(); + assert.deepEqual([...draw.set(a.setId).items.keys()], ['three']); +}); + +test('without a draw port nothing is drawn and nothing throws', () => { + const icon = createTrackedAircraftIcon({ + viewer: () => null, + setPrefix: 'flights', + }); + icon.show({ + id: 'x', + image: 'img', + sprite: SPRITE, + position: () => ({ x: 0, y: 0, z: 1 }), + rotation: () => 0, + color: () => [1, 1, 1, 1], + }); + icon.setVisible(false); + icon.hide(); + icon.dispose(); + assert.equal(icon.setId, null); +}); + +test("a layer tells another layer's tracked icon set from its own sets", () => { + assert.equal( + isOtherTrackedIconSet('flights-tracked-icon:3', 'military'), + true, + ); + assert.equal( + isOtherTrackedIconSet('military-tracked-icon:1', 'flights'), + true, + ); + assert.equal( + isOtherTrackedIconSet('military-tracked-icon:1', 'military'), + false, + ); + assert.equal(isOtherTrackedIconSet('flights-icons:2', 'military'), false); + assert.equal( + isOtherTrackedIconSet('flights-tracked-model:2', 'military'), + false, + ); + assert.equal(isOtherTrackedIconSet(undefined, 'military'), false); +}); diff --git a/src/data/trackedModelRegime.test.mjs b/src/data/trackedModelRegime.test.mjs index 8b1bc0585..b96abbb36 100644 --- a/src/data/trackedModelRegime.test.mjs +++ b/src/data/trackedModelRegime.test.mjs @@ -660,7 +660,7 @@ for (const fixture of LAYERS) { assert.equal(model.show, false, 'the loading model is drawn hidden, not zero-scaled'); assert.equal(tracked.items.get(icao24).show, false); const baseScale = model.scale; - assert.equal(fixture.trackedBillboardColor().alpha, 1, + assert.equal(fixture.trackedBillboardColor()[3], 1, 'the tracked billboard remains opaque while the model lacks safe placement'); assert.equal(sampleCalls, 0, 'cold tiles do not force a synchronous sample'); const loadingDetection = fixture.layer.getDetectableObjects({ maxCount: 50 }) @@ -689,14 +689,14 @@ for (const fixture of LAYERS) { fixture.driveTrackedModel(); assert.equal(sampleCalls, 0, 'the tracked path honors the same retry backoff before sampling'); assert.equal(model.show, false, 'retry backoff keeps the unplaced primitive hidden'); - assert.equal(fixture.trackedBillboardColor().alpha, 1, + assert.equal(fixture.trackedBillboardColor()[3], 1, 'retry backoff leaves the tracked billboard opaque'); now += 1500; fixture.driveTrackedModel(); assert.equal(sampleCalls, 1, 'the first settled turn samples once'); assert.equal(model.show, false, 'terrain alone does not reveal an unready model'); - assert.equal(fixture.trackedBillboardColor().alpha, 1, + assert.equal(fixture.trackedBillboardColor()[3], 1, 'the billboard retains ownership until GPU readiness too'); assert.equal(model.scale, baseScale, 'its scale is left to the pixel-cap driver'); @@ -704,7 +704,7 @@ for (const fixture of LAYERS) { fixture.driveTrackedModel(); assert.equal(model.show, true, 'the model appears only after its snapped matrix is written'); assert.equal(tracked.items.get(icao24).show, true); - assert.equal(fixture.trackedBillboardColor().alpha, 0, + assert.equal(fixture.trackedBillboardColor()[3], 0, 'the billboard becomes transparent only when the model actually owns the visual'); const placed = placedAt(model); const placedHeight = Cesium.Cartographic.fromCartesian(placed).height; @@ -727,7 +727,7 @@ for (const fixture of LAYERS) { fixture.driveTrackedModel(); assert.equal(model.show, true, 'a taxi-invalidated tracked snap is HELD through the resample outage'); - assert.equal(fixture.trackedBillboardColor().alpha, 0, + assert.equal(fixture.trackedBillboardColor()[3], 0, 'the model still owns the visual, so the billboard stays transparent'); assert.equal(sampleCalls, 1, 'the hold costs no extra synchronous sample'); @@ -736,7 +736,7 @@ for (const fixture of LAYERS) { fixture.driveTrackedModel(); assert.equal(model.show, false, 'past HELD_SNAP_MAX_DRIFT_M the hold is released and the model is withheld'); - assert.equal(fixture.trackedBillboardColor().alpha, 1, + assert.equal(fixture.trackedBillboardColor()[3], 1, 'there is no invisible-owner gap while the replacement snap is unavailable'); } finally { Date.now = realNow; diff --git a/src/geo/frustum.js b/src/geo/frustum.js new file mode 100644 index 000000000..f7fd9a7da --- /dev/null +++ b/src/geo/frustum.js @@ -0,0 +1,62 @@ +/** + * @module geo/frustum + * @description The view frustum of a camera pose as the default renderer + * culls with it (`PerspectiveFrustum.computeCullingVolume` and + * `CullingVolume.computeVisibility`, centred, no offset), so code that culls + * by what is on screen agrees with what the renderer draws. No engine. + */ +import { add, cross, dot, normalize, scale, sub } from './vector.js'; + +/** + * The six planes (`{normal, w}`, inside where `normal · p + w ≥ 0`) of the + * frustum `pose` looks through: a camera port pose's `position`, + * `direction`, `up`, `fovy`, `aspectRatio`, `near` and `far`. + * @param {{position: object, direction: object, up: object, fovy: number, + * aspectRatio: number, near: number, far: number}} pose + * @returns {Array<{normal: {x: number, y: number, z: number}, w: number}>} + */ +export function frustumPlanes(pose) { + const { position, direction, up, near, far } = pose; + const t = near * Math.tan(0.5 * pose.fovy); + const b = -t; + const r = pose.aspectRatio * t; + const l = -r; + + const right = cross(direction, up); + const nearCenter = add(position, scale(direction, near)); + const farCenter = add(position, scale(direction, far)); + const plane = (normal) => ({ normal, w: -dot(normal, position) }); + + const left = plane( + normalize( + cross(normalize(sub(add(nearCenter, scale(right, l)), position)), up), + ), + ); + const rightPlane = plane( + normalize(cross(up, sub(add(nearCenter, scale(right, r)), position))), + ); + const bottom = plane( + normalize(cross(right, sub(add(nearCenter, scale(up, b)), position))), + ); + const top = plane( + normalize(cross(sub(add(nearCenter, scale(up, t)), position), right)), + ); + const nearPlane = { normal: direction, w: -dot(direction, nearCenter) }; + const back = scale(direction, -1); + const farPlane = { normal: back, w: -dot(back, farCenter) }; + return [left, rightPlane, bottom, top, nearPlane, farPlane]; +} + +/** + * Whether a sphere is wholly outside `planes` (from `frustumPlanes`), as + * the default renderer's `CullingVolume.computeVisibility` reports + * `Intersect.OUTSIDE`. + * @param {ReturnType} planes + * @param {{x: number, y: number, z: number}} center + * @param {number} radius + */ +export function sphereOutside(planes, center, radius) { + for (const { normal, w } of planes) + if (dot(normal, center) + w < -radius) return true; + return false; +} diff --git a/src/geo/frustum.test.mjs b/src/geo/frustum.test.mjs new file mode 100644 index 000000000..fa5269df8 --- /dev/null +++ b/src/geo/frustum.test.mjs @@ -0,0 +1,74 @@ +import assert from 'node:assert/strict'; +import test from 'node:test'; +import * as Cesium from 'cesium'; +import { frustumPlanes, sphereOutside } from './frustum.js'; + +/** A camera pose and the Cesium frustum it describes. */ +function camera({ position, direction, up, fovy, aspectRatio, near, far }) { + const frustum = new Cesium.PerspectiveFrustum({ + fov: + aspectRatio <= 1 ? fovy : 2 * Math.atan(Math.tan(fovy / 2) * aspectRatio), + aspectRatio, + near, + far, + }); + const volume = frustum.computeCullingVolume( + new Cesium.Cartesian3(position.x, position.y, position.z), + new Cesium.Cartesian3(direction.x, direction.y, direction.z), + new Cesium.Cartesian3(up.x, up.y, up.z), + ); + return { + pose: { position, direction, up, fovy, aspectRatio, near, far }, + volume, + }; +} + +const unit = (x, y, z) => { + const m = Math.hypot(x, y, z); + return { x: x / m, y: y / m, z: z / m }; +}; + +test('the frustum culls spheres as the default renderer does', () => { + const eye = Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 9000); + const down = unit(-eye.x, -eye.y, -eye.z); + const east = unit(-eye.y, eye.x, 0); + const up = Cesium.Cartesian3.normalize( + Cesium.Cartesian3.cross(east, down, new Cesium.Cartesian3()), + new Cesium.Cartesian3(), + ); + for (const aspectRatio of [0.6, 1, 1.8]) { + const { pose, volume } = camera({ + position: { x: eye.x, y: eye.y, z: eye.z }, + direction: down, + up: { x: up.x, y: up.y, z: up.z }, + fovy: 1.0, + aspectRatio, + near: 0.1, + far: 5e8, + }); + const planes = frustumPlanes(pose); + let outside = 0; + for (let i = 0; i < 400; i++) { + const lon = -122.4 + ((i % 20) - 10) * 0.03; + const lat = 37.6 + (Math.floor(i / 20) - 10) * 0.03; + const center = Cesium.Cartesian3.fromDegrees(lon, lat, (i % 7) * 400); + for (const radius of [1, 500]) { + const theirs = + volume.computeVisibility( + new Cesium.BoundingSphere(center, radius), + ) === Cesium.Intersect.OUTSIDE; + assert.equal( + sphereOutside(planes, center, radius), + theirs, + `${i} ${radius}`, + ); + if (theirs) outside += 1; + } + } + // Some in, some out, so both answers are exercised. + assert.ok(outside > 0 && outside < 800); + // Behind the eye. + const behind = Cesium.Cartesian3.fromDegrees(-122.4, 37.6, 20000); + assert.equal(sphereOutside(planes, behind, 1), true); + } +}); diff --git a/src/layers/flights/enrichment.js b/src/layers/flights/enrichment.js index 96fc5ea16..b3f02532f 100644 --- a/src/layers/flights/enrichment.js +++ b/src/layers/flights/enrichment.js @@ -1,6 +1,8 @@ import { classifyAircraft } from '../../data/aircraftClass.js'; -import { horizonOccluder } from '../../data/iconOrientation.js'; -import * as Cesium from 'cesium'; +import { findCamera } from '../../render/rendererOf.js'; +import { frustumPlanes, sphereOutside } from '../../geo/frustum.js'; +import { horizonFrom } from '../../geo/horizon.js'; +import { distanceSquared, vec } from '../../geo/vector.js'; import { ENRICH_MAX_INFLIGHT, ENRICH_DISPATCH_GAP_MS, @@ -10,6 +12,9 @@ import { ENRICH_AMBIENT_PER_SWEEP, } from './policy.js'; +/** A contact counts as on screen while a sphere this big around it is (m). */ +const AMBIENT_CULL_RADIUS_M = 1; + export function createEnrichment({ flightState, services, @@ -183,14 +188,14 @@ export function createEnrichment({ ) return; try { - const camera = flightState._viewer.camera; - const camPos = camera.positionWC; - const occluder = horizonOccluder(camera); - const cull = camera.frustum.computeCullingVolume( - camPos, - camera.directionWC, - camera.upWC, - ); + // What is on screen, from the camera's pose: past the limb or outside + // the view frustum is not looked at. + const pose = findCamera(flightState._viewer)?.pose(); + if (!pose) return; + const camPos = pose.position; + const occluder = horizonFrom(camPos); + const planes = frustumPlanes(pose); + const position = vec(); const cand = []; const icons = flightState._icons; const t = parts.icons._displayMs(); @@ -198,21 +203,10 @@ export function createEnrichment({ if (flightState._enrichSeen.has(`t:${icao24}`)) continue; // answered / queued / negative this session if (!/^[0-9a-f]{6}$/i.test(icao24)) continue; // adsbdb keys are 6-char hex only if (flightState.records.data.get(icao24)?.onGround) continue; // ground traffic never spends ambient budget (click-to-enrich still works) - const position = icons.position( - icao24, - t, - flightState._scratchModelBS.center, - ); + if (!icons.position(icao24, t, position)) continue; if (!occluder.isPointVisible(position)) continue; // beyond the limb - if ( - cull.computeVisibility(flightState._scratchModelBS) === - Cesium.Intersect.OUTSIDE - ) - continue; // off-screen - cand.push([ - icao24, - Cesium.Cartesian3.distanceSquared(camPos, position), - ]); + if (sphereOutside(planes, position, AMBIENT_CULL_RADIUS_M)) continue; // off-screen + cand.push([icao24, distanceSquared(camPos, position)]); } cand.sort((a, b) => a[1] - b[1]); // nearest first — what the user is looking at resolves first const n = Math.min( diff --git a/src/layers/flights/evidence.js b/src/layers/flights/evidence.js index e08749869..5dfe37043 100644 --- a/src/layers/flights/evidence.js +++ b/src/layers/flights/evidence.js @@ -1,4 +1,6 @@ -import * as Cesium from 'cesium'; +import { findCamera, findFrame, findQuery } from '../../render/rendererOf.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { distance, vec } from '../../geo/vector.js'; import { FOCUS_EVIDENCE_DEV } from './policy.js'; import { aircraftRecessionFactors, @@ -21,18 +23,14 @@ export function createEvidence({ cartesian.length >= 3 && cartesian.slice(0, 3).every(Number.isFinite) ) { - return Cesium.Cartesian3.fromElements( - cartesian[0], - cartesian[1], - cartesian[2], - ); + return vec(cartesian[0], cartesian[1], cartesian[2]); } if ( !Number.isFinite(record?.longitude) || !Number.isFinite(record?.latitude) ) return null; - return Cesium.Cartesian3.fromDegrees( + return fromDegrees( record.longitude, record.latitude, Number.isFinite(record.altitudeM) ? record.altitudeM : 3_000, @@ -75,7 +73,7 @@ export function createEvidence({ const klass = record.klass || 'airliner'; const altitudeM = Number.isFinite(record.altitudeM) ? record.altitudeM - : Cesium.Cartographic.fromCartesian(position)?.height || 3_000; + : toLonLatH(position)?.height || 3_000; const meta = { callsign: String(record.callsign || id).toUpperCase(), altitude: altitudeM, @@ -99,7 +97,7 @@ export function createEvidence({ } flightState.feed._count = icons.count; flightState._lastFleetTickMs = 0; - flightState._viewer.scene.requestRender?.(); + findFrame(flightState._viewer)?.requestRender('flights: focus evidence'); return { ok: true, count: flightState.feed._count }; } @@ -127,7 +125,8 @@ export function createEvidence({ moved += 1; } flightState._lastFleetTickMs = 0; - flightState._viewer?.scene?.requestRender?.(); + if (flightState._viewer) + findFrame(flightState._viewer)?.requestRender('flights: focus evidence'); return { ok: true, moved }; } @@ -136,19 +135,19 @@ export function createEvidence({ function _focusEvidenceSnapshot() { if (!FOCUS_EVIDENCE_DEV || !flightState._viewer) return []; const icons = flightState._icons; - const { scene, camera } = flightState._viewer; + const pose = findCamera(flightState._viewer)?.pose(); + const query = findQuery(flightState._viewer); + if (!pose || !query) return []; const occluder = parts.icons._occluder(); - const cameraHeightM = camera.positionCartographic?.height; + const cameraHeightM = pose.height; return [...flightState._focusEvidenceIds].map((id) => { const position = icons?.has(id) - ? parts.icons._iconPosition(id, new Cesium.Cartesian3()) + ? parts.icons._iconPosition(id, vec()) : null; const cameraDistanceM = position - ? Cesium.Cartesian3.distance(camera.positionWC, position) - : null; - const screen = position - ? Cesium.SceneTransforms.worldToWindowCoordinates(scene, position) + ? distance(pose.position, position) : null; + const screen = position ? query.project(position) : null; // What the icon shader composes: base scale × limb taper, and base // alpha × max(floor, focus × limb haze). const factors = position diff --git a/src/layers/flights/lifecycle.js b/src/layers/flights/lifecycle.js index 0875b014b..2d78342d8 100644 --- a/src/layers/flights/lifecycle.js +++ b/src/layers/flights/lifecycle.js @@ -240,6 +240,7 @@ export function createLifecycle({ } parts.rendering._releaseModels(); parts.icons._disposeIcons(); + parts.tracking._disposeTrackedIcon(); parts.rendering._disposeModelSets(); flightState._grounded.clear(); flightState._floorPinned.clear(); diff --git a/src/layers/flights/motion.js b/src/layers/flights/motion.js index 21e0323fc..4072c8029 100644 --- a/src/layers/flights/motion.js +++ b/src/layers/flights/motion.js @@ -1,4 +1,29 @@ -import * as Cesium from 'cesium'; +import { findCamera, rendererOf } from '../../render/rendererOf.js'; +import { renderedFrames } from '../../data/renderedFrames.js'; +import { + fromDegrees, + fromRadians, + toCartographicRadians, + toLonLatH, +} from '../../geo/ellipsoid.js'; +import { eastNorthUp, framePoint } from '../../geo/frames.js'; +import { + addSeconds, + julianLessThan, + julianNow, + secondsDifference, +} from '../../geo/julian.js'; +import { + add, + clamp, + copyInto, + distance, + lerpInto, + scale, + sub, + toDegrees, + vec, +} from '../../geo/vector.js'; import { COURSE_HOLD_SPEED_MPS, lerpAngleDeg, @@ -45,6 +70,9 @@ import { fixTrackDeg, } from '../../data/aircraftMotionRegime.js'; +/** Whether two ECEF points are the same point, component for component. */ +const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z; + /** Where a flights record carries its reported speed and track. */ const RECORD_FIELDS = { speed: 'velocity', track: 'true_track' }; @@ -69,9 +97,27 @@ export function createMotion({ const { nearFarScalarValueAtDistance, clearFocusTarget, - publishFocusTargetFromCachedPosition, + publishFocusTargetAt, } = services.focus; + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + const viewer = flightState._viewer; + try { + return (viewer && findCamera(viewer)?.pose()) ?? null; + } catch { + return null; + } + } + + /** The renderer canvas's CSS height (the viewer's own canvas when no + * renderer is bound), or 0 without either. */ + function _viewportHeightPx() { + const viewer = flightState._viewer; + const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas; + return Number(canvas?.clientHeight) || 0; + } + // Fixes leave the cache with their history; corrected positions invalidate // the local frame even when the existing Cartesian is mutated in place. const fixFrames = new WeakMap(); @@ -112,15 +158,10 @@ export function createMotion({ ) continue; info.renderAltitudeM = lifted; - const position = Cesium.Cartesian3.fromDegrees( - info.rawLon, - info.rawLat, - lifted, - ); + const position = fromDegrees(info.rawLon, info.rawLat, lifted); const history = flightState._positionHistory.get(icao24); const newest = history?.[history.length - 1]; - if (newest) - newest.position = Cesium.Cartesian3.clone(position, newest.position); + if (newest) newest.position = copyInto(position, newest.position); // Above the ellipsoid now (or floors say otherwise next poll). parts.icons._applyIconPresentation(icao24); parts.icons._planIcon(icao24); @@ -139,24 +180,19 @@ export function createMotion({ * position toward the corrected fix before projecting forward. * * @param {string} icao24 - ICAO 24-bit transponder address of the aircraft. - * @returns {Cesium.Cartesian3|null} Estimated ECEF position, or null if no history exists. + * @returns {{x: number, y: number, z: number}|null} Estimated ECEF position, or null if no history exists. */ function _deadReckon(icao24, result, sampledRenderTime) { const info = flightState.records.data.get(icao24); if (FOCUS_EVIDENCE_DEV && flightState._focusEvidenceIds.has(icao24)) { - const position = parts.icons._iconPosition( - icao24, - new Cesium.Cartesian3(), - ); + const position = parts.icons._iconPosition(icao24, vec()); flightState._drCourseDeg = info?.true_track || 0; flightState._drSpeedMps = info?.velocity || 0; flightState._drCourseHold = flightState._drSpeedMps < COURSE_HOLD_SPEED_MPS; flightState._drExtrapolating = false; - return position - ? Cesium.Cartesian3.clone(position, result || new Cesium.Cartesian3()) - : null; + return position ? copyInto(position, result || vec()) : null; } const history = flightState._positionHistory.get(icao24); if (!history || history.length === 0) { @@ -167,13 +203,13 @@ export function createMotion({ return null; } - const out = result || new Cesium.Cartesian3(); + const out = result || vec(); // Render one poll interval behind real time so we interpolate between // two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale). const renderTime = sampledRenderTime ?? - Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(flightState._scratchRenderTime), + addSeconds( + julianNow(flightState._scratchRenderTime), -RENDER_DELAY_SEC, flightState._scratchRenderTime, ); @@ -181,10 +217,7 @@ export function createMotion({ const regime = _motionRegime(history, info, renderTime); if (regime.kind === 'between') { const { a, b, span } = regime; - const t = - span > 0 - ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span - : 1.0; + const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0; const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t); flightState._drCourseDeg = regime.chordCourse != null @@ -193,10 +226,10 @@ export function createMotion({ flightState._drSpeedMps = regime.speed; flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS; flightState._drExtrapolating = false; - return Cesium.Cartesian3.lerp(a.position, b.position, t, out); + return lerpInto(a.position, b.position, t, out); } - const dt = Cesium.Math.clamp( - Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time), + const dt = clamp( + secondsDifference(renderTime, regime.fix.time), regime.minDt, regime.maxDt, ); @@ -238,43 +271,26 @@ export function createMotion({ flightState._drExtrapolating = true; if (speed === 0 || dt === 0) { flightState._drCourseDeg = heading; - return Cesium.Cartesian3.clone(fix.position, out); + return copyInto(fix.position, out); } // Constant-rate-turn arc (straight line when turnRateDps ≈ 0) — a plane in a // standard-rate turn is ~90° of arc wrong per 30 s if extrapolated straight. arcOffsetEnu(speed, heading, turnRateDps, dt, flightState._scratchArc); flightState._drCourseDeg = flightState._scratchArc.endCourseDeg; - Cesium.Cartesian3.fromElements( - flightState._scratchArc.east, - flightState._scratchArc.north, - 0, - flightState._scratchOffset, - ); + const offset = flightState._scratchOffset; + offset.x = flightState._scratchArc.east; + offset.y = flightState._scratchArc.north; + offset.z = 0; let frame = fixFrames.get(fix); if (!frame) { - frame = { - position: new Cesium.Cartesian3(), - matrix: new Cesium.Matrix4(), - }; + frame = { position: vec(), enu: null }; fixFrames.set(fix, frame); } - if ( - !frame.valid || - !Cesium.Cartesian3.equals(frame.position, fix.position) - ) { - Cesium.Transforms.eastNorthUpToFixedFrame( - fix.position, - Cesium.Ellipsoid.WGS84, - frame.matrix, - ); - Cesium.Cartesian3.clone(fix.position, frame.position); - frame.valid = true; + if (!frame.enu || !samePoint(frame.position, fix.position)) { + frame.enu = eastNorthUp(fix.position); + copyInto(fix.position, frame.position); } - return Cesium.Matrix4.multiplyByPoint( - frame.matrix, - flightState._scratchOffset, - out, - ); + return copyInto(framePoint(frame.enu, offset), out); } /** @@ -289,21 +305,21 @@ export function createMotion({ if (!flightState._trackedIcao) return false; const history = flightState._positionHistory.get(flightState._trackedIcao); if (!history || history.length === 0) return true; - const renderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(), + const renderTime = addSeconds( + julianNow(), -RENDER_DELAY_SEC, flightState._scratchWarmupTime, ); - return Cesium.JulianDate.lessThan(renderTime, history[0].time); + return julianLessThan(renderTime, history[0].time); } /** Resolve the selected aircraft's actual rendered square extent this frame. */ function _trackedFocusSizePx(icao24, position) { - const camera = flightState._viewer?.camera; - const scene = flightState._viewer?.scene; - if (!camera?.positionWC || !position || !scene) return 28; - const rangeM = Cesium.Cartesian3.distance(camera.positionWC, position); + const pose = _pose(); + if (!pose || !position) return 28; + const rangeM = distance(pose.position, position); + const viewportHeightPx = _viewportHeightPx(); if (parts.rendering._modelOwnsVisual(icao24)) { const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24)?.klass, @@ -312,12 +328,11 @@ export function createMotion({ baseScale: spec.scale, nativeRadiusM: spec.nativeRadiusM, rangeM, - viewportHeightPx: scene.canvas.clientHeight, - fovyRad: camera.frustum.fovy, + viewportHeightPx, + fovyRad: pose.fovy, maximumPixelSize: TRACKED_MODEL_MAX_PX, }); - const focalLengthPx = - scene.canvas.clientHeight / (2 * Math.tan(camera.frustum.fovy / 2)); + const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = (2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM; return Math.max( @@ -339,16 +354,16 @@ export function createMotion({ } /** - * Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by Cesium - * frame number so the position / rotation / trail-head callbacks share ONE computation + * Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by drawn + * frame (see renderedFrames.js) so the position / rotation / trail-head callbacks share ONE computation * (and one reconciliation-state update) per frame. Returns a stable module holder, or * null when the aircraft has no fix. * @param {string} icao24 - * @returns {Cesium.Cartesian3|null} + * @returns {{x: number, y: number, z: number}|null} */ function _trackedDisplayPosition(icao24) { - const frame = flightState._viewer?.scene?.frameState?.frameNumber ?? -1; + const frame = renderedFrames(flightState._viewer); if ( frame === flightState._cachedDRFrame && icao24 === flightState._drReconcileIcao @@ -379,29 +394,26 @@ export function createMotion({ const speed = (info && info.velocity) || 0; // Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base. const plausible = speed * dtSec * 4 + 25; - if (Cesium.Cartesian3.distance(raw, flightState._drPrevRaw) > plausible) { + if (distance(raw, flightState._drPrevRaw) > plausible) { // Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay. - Cesium.Cartesian3.subtract( - flightState._drPrevDisplay, - raw, + copyInto( + sub(flightState._drPrevDisplay, raw), flightState._drCorrection, ); flightState._drCorrectionStartMs = nowMs; } } else { - Cesium.Cartesian3.fromElements(0, 0, 0, flightState._drCorrection); + copyInto(vec(), flightState._drCorrection); flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed } const elapsed = nowMs - flightState._drCorrectionStartMs; const factor = elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS; - let display = Cesium.Cartesian3.multiplyByScalar( - flightState._drCorrection, - factor, + let display = copyInto( + add(raw, scale(flightState._drCorrection, factor)), flightState._trackedPosHolder, ); - Cesium.Cartesian3.add(raw, display, display); // Same display floor the fleet pass applies — otherwise selecting a correctly // floored grounded billboard swapped it for an unfloored tracked entity and // dropped the cyan target back under the mesh. Applied HERE, at the single @@ -420,8 +432,8 @@ export function createMotion({ nowMs, ); - Cesium.Cartesian3.clone(raw, flightState._drPrevRaw); - Cesium.Cartesian3.clone(display, flightState._drPrevDisplay); + copyInto(raw, flightState._drPrevRaw); + copyInto(display, flightState._drPrevDisplay); flightState._drPrevMs = nowMs; flightState._drReconcileValid = true; flightState._cachedDRPosition = display; @@ -429,14 +441,13 @@ export function createMotion({ icao24, flightState._cachedDRPosition, ); - // Publish only the exact per-frame display cache the tracked entity/camera + // Publish only the exact per-frame display cache the tracked billboard/camera // consumes. Re-running DR from a later frame phase recreates the historical // target-vs-camera jitter bug. - publishFocusTargetFromCachedPosition({ + publishFocusTargetAt({ ownerLayer: 'flights', id: icao24, - scene: flightState._viewer?.scene, - camera: flightState._viewer?.camera, + viewer: flightState._viewer, displayPosition: flightState._cachedDRPosition, widthPx: focusSizePx, heightPx: focusSizePx, @@ -446,7 +457,7 @@ export function createMotion({ /** The tracked plane's current display position WITHOUT recomputing — the exact value the * follow-camera already settled on this frame (in the Viewer _onTick). getDetectableObjects + the - * readout run in postRender at a LATER frameNumber, so calling _trackedDisplayPosition there would + * readout run in postRender, later in the same frame, so calling _trackedDisplayPosition there would * re-run the dead-reckon on a fresh sample and double-advance the reconciliation → the label jitters * against the now-stable plane (the model's jitter fix, resurfacing in the labels). Returns null when * there's no valid fix for the tracked aircraft, so callers fall back to the icon position. */ @@ -509,10 +520,12 @@ export function createMotion({ !parts.rendering._modelOwnsVisual(flightState._trackedIcao) ) return null; - return Cesium.Matrix4.getTranslation( - flightState._trackedModel.matrix, - flightState._scratchTrailClip, - ); + const m = flightState._trackedModel.matrix; + const out = flightState._scratchTrailClip; + out.x = m[12]; + out.y = m[13]; + out.z = m[14]; + return out; } function _trackedModelEnvelopeM() { @@ -747,7 +760,7 @@ export function createMotion({ state.probeMs = null; // re-ground may probe immediately state.out = null; state.effectiveM = null; - Cesium.Cartesian3.clone(Cesium.Cartesian3.ZERO, state.in); // invalidate the memo + copyInto(vec(), state.in); // invalidate the memo } else if (_seedExpired(state, nowMs)) { flightState._displayFloorState.delete(icao24); // airborne long enough to be anywhere } @@ -792,11 +805,11 @@ export function createMotion({ * * @param {string} icao24 - Contact key (owns one `_displayFloorState` entry). * @param {object|null|undefined} info - `_flightData` record for this contact. - * @param {Cesium.Cartesian3|null} pos - Dead-reckoned display position. + * @param {{x: number, y: number, z: number}|null} pos - Dead-reckoned display position. * @param {boolean} modelOwnsVisual - Whether a 3D model is drawing this contact. * @param {number} [nowMs] - Tick clock, passed by both callers so the release * ease advances on the same clock the rest of the tick uses. - * @returns {Cesium.Cartesian3|null} `pos` itself when nothing moves (the common + * @returns {{x: number, y: number, z: number}|null} `pos` itself when nothing moves (the common * case — no allocation, no rebuild), otherwise the lifted position. */ @@ -812,22 +825,18 @@ export function createMotion({ return pos; } const state = flightState._displayFloorState.get(icao24); - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - flightState._scratchDisplayCarto, - ); + const carto = toCartographicRadians(pos); // Boundary hysteresis: a position jittering across a cell edge would flip // floors at fleet-tick rate (see stickyFloorCell). const cell = stickyFloorCell( - Cesium.Math.toDegrees(carto.latitude), - Cesium.Math.toDegrees(carto.longitude), + toDegrees(carto.lat), + toDegrees(carto.lon), state?.cell, ); const floor = cachedGroundFloor(cell.lat, cell.lon); const next = state || { cell, - in: new Cesium.Cartesian3(), + in: vec(), out: null, effectiveM: null, heldM: null, @@ -920,28 +929,21 @@ export function createMotion({ // never adopted. One owned entry per grounded // contact — O(grounded), dropped on eviction, on destroy, and the moment the // contact stops being a grounded billboard. - if ( - state && - state.effectiveM === effective && - Cesium.Cartesian3.equals(pos, state.in) - ) { + if (state && state.effectiveM === effective && samePoint(pos, state.in)) { return state.out || pos; } const lifted = displayFloorHeightM(carto.height, effective); next.cell = cell; next.effectiveM = effective; - Cesium.Cartesian3.clone(pos, next.in); + copyInto(pos, next.in); if (lifted == null) { next.out = null; } else { // The cache OWNS its output: returning a shared scratch would let the next // contact in the fleet loop overwrite a position already handed out. - next.out = Cesium.Cartesian3.fromRadians( - carto.longitude, - carto.latitude, - lifted, - Cesium.Ellipsoid.WGS84, - next.out || new Cesium.Cartesian3(), + next.out = copyInto( + fromRadians(carto.lon, carto.lat, lifted), + next.out || vec(), ); } if (!state) flightState._displayFloorState.set(icao24, next); @@ -1024,13 +1026,10 @@ export function createMotion({ flightState._drCourseDeg != null ? flightState._drCourseDeg : info.true_track || 0; - const c = Cesium.Cartographic.fromCartesian( - dr, - Cesium.Ellipsoid.WGS84, - flightState._scratchCorridorCarto, - ); - const lat = Cesium.Math.toDegrees(c.latitude); - const lon = Cesium.Math.toDegrees(c.longitude); + const c = toLonLatH(dr); + if (!c) continue; + const lat = c.lat; + const lon = c.lon; const cells = corridorFloorCells( corridorPathLatLon({ extrapolating, @@ -1063,7 +1062,7 @@ export function createMotion({ out.push(cell); } } - /** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */ + /** The display instant `epochMs` as a Julian date, for `_motionRegime`. */ const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result); return { diff --git a/src/layers/flights/motion.test.mjs b/src/layers/flights/motion.test.mjs index dcb809d86..878c9a5c6 100644 --- a/src/layers/flights/motion.test.mjs +++ b/src/layers/flights/motion.test.mjs @@ -10,8 +10,8 @@ function fixture() { _positionHistory: new Map(), _focusEvidenceIds: new Set(), _scratchArc: {}, - _scratchOffset: new Cesium.Cartesian3(), - _scratchRenderTime: new Cesium.JulianDate(), + _scratchOffset: { x: 0, y: 0, z: 0 }, + _scratchRenderTime: { dayNumber: 0, secondsOfDay: 0 }, }; const motion = createMotion({ flightState, @@ -35,64 +35,55 @@ function close(actual, expected) { assert.ok(Cesium.Cartesian3.distance(actual, expected) < 1e-8); } -test('extrapolation reuses fixed frames and invalidates corrected coordinates', (t) => { +test('extrapolation follows the fix frame, a corrected or replaced fix included', () => { const { motion } = fixture(); const transform = Cesium.Transforms.eastNorthUpToFixedFrame; - const spy = t.mock.method( - Cesium.Transforms, - 'eastNorthUpToFixedFrame', - transform, - ); const fix = { position: Cesium.Cartesian3.fromDegrees(-97, 30, 200), velocity: 90, track: 70, }; - const out = new Cesium.Cartesian3(); + const out = { x: 0, y: 0, z: 0 }; for (const dt of [-30, 5, 30, 60]) { motion._extrapolateFix(fix, {}, dt, out, 1.5); close(out, expectedPosition(fix, dt, 1.5, transform)); } - assert.equal(spy.mock.callCount(), 1); - // Ground reflooring mutates an existing fix's Cartesian in place. + // Ground reflooring mutates an existing fix's position in place: the + // frame kept for the fix must not answer for the old coordinates. Cesium.Cartesian3.fromDegrees(-97, 30, 350, undefined, fix.position); motion._extrapolateFix(fix, {}, 30, out, 1.5); close(out, expectedPosition(fix, 30, 1.5, transform)); - assert.equal(spy.mock.callCount(), 2); fix.position = Cesium.Cartesian3.fromDegrees(140, 80, 1000); motion._extrapolateFix(fix, {}, 30, out, -2); close(out, expectedPosition(fix, 30, -2, transform)); - assert.equal(spy.mock.callCount(), 3); fix.velocity = 210; fix.track = 359; motion._extrapolateFix(fix, {}, 15, out, -1); close(out, expectedPosition(fix, 15, -1, transform)); - assert.equal(spy.mock.callCount(), 3); const replacement = { ...fix }; motion._extrapolateFix(replacement, {}, 15, out, -1); close(out, expectedPosition(replacement, 15, -1, transform)); - assert.equal(spy.mock.callCount(), 4); }); -test('stationary fixes do not build a frame until motion needs it', (t) => { +test('stationary fixes stay at the fix', () => { const { motion } = fixture(); - const spy = t.mock.method(Cesium.Transforms, 'eastNorthUpToFixedFrame'); const fix = { position: Cesium.Cartesian3.fromDegrees(0, 0, 0), velocity: 0, track: 90, }; - const out = new Cesium.Cartesian3(); + const out = { x: 0, y: 0, z: 0 }; close(motion._extrapolateFix(fix, {}, 30, out), fix.position); fix.velocity = 10; close(motion._extrapolateFix(fix, {}, 0, out), fix.position); - assert.equal(spy.mock.callCount(), 0); - motion._extrapolateFix(fix, {}, 30, out); - assert.equal(spy.mock.callCount(), 1); + close( + motion._extrapolateFix(fix, {}, 30, out), + expectedPosition(fix, 30, 0, Cesium.Transforms.eastNorthUpToFixedFrame), + ); }); test('fleet render time is shared without resampling or mutating the supplied instant', (t) => { @@ -121,7 +112,7 @@ test('fleet render time is shared without resampling or mutating the supplied in flightState.records.data.set(id, { velocity: 100, true_track: 90 }); flightState._positionHistory.set(id, history); } - t.mock.method(Cesium.JulianDate, 'now', () => { + t.mock.method(Date, 'now', () => { throw new Error('unexpected per-contact clock read'); }); const expected = Cesium.Cartesian3.lerp( @@ -156,10 +147,8 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch', flightState.records.data.set('tracked', { velocity: 100, true_track: 90 }); flightState._positionHistory.set('tracked', history); let elapsed = 60; - const spy = t.mock.method(Cesium.JulianDate, 'now', (result) => { - assert.equal(result, flightState._scratchRenderTime); - return Cesium.JulianDate.addSeconds(start, elapsed, result); - }); + const startMs = Cesium.JulianDate.toDate(start).getTime(); + const spy = t.mock.method(Date, 'now', () => startMs + elapsed * 1000); const out = new Cesium.Cartesian3(); close( motion._deadReckon('tracked', out), @@ -181,4 +170,11 @@ test('tracked callers still sample a fresh delayed time without a fleet epoch', ), ); assert.equal(spy.mock.callCount(), 2); + // Sampled into the layer's scratch, not a new date. + assert.ok( + Cesium.JulianDate.equals( + flightState._scratchRenderTime, + Cesium.JulianDate.addSeconds(start, 45, new Cesium.JulianDate()), + ), + ); }); diff --git a/src/layers/flights/ownership.test.mjs b/src/layers/flights/ownership.test.mjs index e4c3343c5..a1c61f283 100644 --- a/src/layers/flights/ownership.test.mjs +++ b/src/layers/flights/ownership.test.mjs @@ -64,7 +64,7 @@ test('flight state owns distinct mutable records, scratch objects and floor samp '_positionHistory', '_displayFloorState', '_groundSnap', - '_scratchCarto', + '_scratchNearbyPos', '_models', 'lifetime', ]) { diff --git a/src/layers/flights/policy.js b/src/layers/flights/policy.js index af594df02..6cc04197e 100644 --- a/src/layers/flights/policy.js +++ b/src/layers/flights/policy.js @@ -1,16 +1,21 @@ -import * as Cesium from 'cesium'; import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js'; +import { cssColor } from '../../render/color.js'; + +/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */ +const rgba = (css, alpha) => + Object.freeze( + alpha === undefined ? cssColor(css) : [...cssColor(css).slice(0, 3), alpha], + ); export const FOCUS_EVIDENCE_DEV = import.meta.env?.DEV === true; /** Amber tint for known-military aircraft rendered by this layer (matches the military layer's icon color). */ -export const MIL_TINT = Cesium.Color.fromCssColorString('#FFB800'); +export const MIL_TINT = rgba('#FFB800'); /** Red tint for aircraft broadcasting an emergency (7500/7600/7700 or ADS-B status). */ -export const EMERGENCY_TINT = - Cesium.Color.fromCssColorString(EMERGENCY_TINT_CSS); +export const EMERGENCY_TINT = rgba(EMERGENCY_TINT_CSS); // --- Ground traffic (owner reversal 2026-07-03: "absolutely we should see planes // taxiing and landing") ----------------------------------------------------------- @@ -90,7 +95,7 @@ export const MODEL_ALL_KEEP_M = 450000; // all: KEEP modeled planes out to 450 km export const MODEL_HEADING_OFFSET_DEG = 180; -// airplane.glb nose is opposite Cesium heading-0 +// airplane.glb nose is opposite the renderer's heading 0 // Owner launch-polish direction: models should read as clean light silhouettes, // with only a weak diffuse contribution from the existing approved textures. @@ -106,22 +111,22 @@ export const MODEL_COLOR_BLEND_AMOUNT = 0.94; export const MODEL_BELLY_OFFSET_NATIVE = 6.719; /** The tracked contact's tint, and its billboard once a model takes over. */ -export const TRACKED_CYAN = Cesium.Color.CYAN; -export const CYAN_TRANSPARENT = Cesium.Color.CYAN.withAlpha(0); +export const TRACKED_CYAN = rgba('#00FFFF'); +export const CYAN_TRANSPARENT = rgba('#00FFFF', 0); /** An ordinary fleet contact's tint. */ -export const FLEET_TINT = Cesium.Color.WHITE; +export const FLEET_TINT = rgba('#FFFFFF'); export const COCKPIT_CONTACT_SIZE_PX = 6; -export const COCKPIT_CIVILIAN_COLOR = - Cesium.Color.fromCssColorString('#DCEEFF'); +export const COCKPIT_CIVILIAN_COLOR = rgba('#DCEEFF'); -export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( - 1000, - 3.0, - 8000000, - 0.5, -); +/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */ +export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({ + near: 1000, + nearValue: 3.0, + far: 8000000, + farValue: 0.5, +}); // --------------------------------------------------------------------------- // Track-history trail state (PRD WS-F F1/F4): a fading polyline behind the diff --git a/src/layers/flights/queries.js b/src/layers/flights/queries.js index 53c10afc0..2e8f326c0 100644 --- a/src/layers/flights/queries.js +++ b/src/layers/flights/queries.js @@ -1,9 +1,9 @@ -import { cameraOf } from '../../render/cesium/camera.js'; +import { cameraOf, findFrame } from '../../render/rendererOf.js'; import { followedOf } from '../../data/followed.js'; import { approxDistanceKm as _approxDistanceKm } from './recordPolicy.js'; import { displayedKinematics } from '../../data/motionModel.js'; -import * as Cesium from 'cesium'; -import { closeRenderLoopLatch } from '../../render/cesium/internals.js'; +import { toLonLatH } from '../../geo/ellipsoid.js'; +import { clone, distance as distanceBetween, vec } from '../../geo/vector.js'; import { isExplicitLayerStateOrigin } from '../../data/layerState.js'; import { modelVisualAnchor } from '../../data/modelVisualAnchor.js'; import { @@ -116,7 +116,7 @@ export function createQueries({ * Build a public descriptor for one aircraft using its best current position * (dead-reckoned when history exists, billboard position otherwise). * @param {string} icao24 - ICAO 24-bit transponder address. - * @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null} + * @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null} * Descriptor with a cloned position, or null if the aircraft is unknown. */ @@ -136,7 +136,7 @@ export function createQueries({ const info = flightState.records.data.get(icao24); const basePos = parts.motion._deadReckon(icao24) || - parts.icons._iconPosition(icao24, new Cesium.Cartesian3()); + parts.icons._iconPosition(icao24, vec()); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -144,18 +144,14 @@ export function createQueries({ reportedSpeedMps: info?.velocity, reportedTrackDeg: info?.true_track, }); - const carto = Cesium.Cartographic.fromCartesian( - basePos, - Cesium.Ellipsoid.WGS84, - flightState._scratchCarto, - ); + const carto = toLonLatH(basePos); if (!carto) return null; return { icao24, callsign: String(info?.callsign || '').trim() || null, - position: Cesium.Cartesian3.clone(basePos), - latitude: Cesium.Math.toDegrees(carto.latitude), - longitude: Cesium.Math.toDegrees(carto.longitude), + position: clone(basePos), + latitude: carto.lat, + longitude: carto.lon, // The cockpit instrument reports aviation altitude, not the Cesium // ellipsoid height of the camera/ground-clamped render position. The // latter can be slightly negative over terrain near the surface. @@ -414,7 +410,7 @@ export function createQueries({ * @param {object} [options] * @param {number} [options.maxCount] - Maximum number of objects to return. * @param {number} [options.seed] - Deterministic offset into the stride pattern. - * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>} + * @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>} */ getDetectableObjects(options = {}) { const icons = flightState._icons; @@ -457,8 +453,8 @@ export function createQueries({ object = { sourceId: icao24, type: 'AIR', - _weldPos: new Cesium.Cartesian3(), - _iconPos: new Cesium.Cartesian3(), + _weldPos: vec(), + _iconPos: vec(), }; flightState._detectionObjects.set(icao24, object); } @@ -485,7 +481,7 @@ export function createQueries({ spec, (view ??= parts.rendering._drawnScaleView()), ), - object._weldPos || (object._weldPos = new Cesium.Cartesian3()), + object._weldPos || (object._weldPos = vec()), ) : icons.position(icao24, t, object._iconPos); // An icon past the horizon is not drawn, so it is not detectable. @@ -533,7 +529,7 @@ export function createQueries({ * Match priority: exact icao24 hex, exact callsign, callsign prefix, * then callsign substring (all case-insensitive, trimmed). * @param {string} query - ICAO24 hex or full/partial callsign. - * @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null} + * @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null} * Best match with a cloned, dead-reckoned position, or null if none. */ findByQuery(query) { @@ -574,12 +570,12 @@ export function createQueries({ /** * Find aircraft near a given ECEF position, sorted ascending by distance. * Return shape mirrors militaryFlightsLayer.getNearby (id/icao24/position/distance). - * @param {Cesium.Cartesian3} center - Reference position in ECEF coordinates. + * @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates. * @param {number} range - Maximum distance in meters (Infinity if not finite). * @param {number} [maxCount=50] - Maximum number of results to return. * @param {object} [options] Query membership options. * @param {boolean} [options.includeHidden=false] Include loaded horizon-hidden aircraft. - * @returns {Array<{id: string, icao24: string, callsign: string|null, position: Cesium.Cartesian3, distance: number, aircraftClass: string|null, altitudeM: number|null, velocityMps: number|null, track: number|null}>} + * @returns {Array<{id: string, icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, distance: number, aircraftClass: string|null, altitudeM: number|null, velocityMps: number|null, track: number|null}>} */ getNearby(center, range, maxCount = 50, { includeHidden = false } = {}) { const icons = flightState._icons; @@ -615,9 +611,9 @@ export function createQueries({ ) continue; - const distance = Cesium.Cartesian3.distance(center, drawn); + const distance = distanceBetween(center, drawn); if (distance > maxRange) continue; - const pos = trackedPos || Cesium.Cartesian3.clone(drawn); + const pos = trackedPos || clone(drawn); const info = flightState.records.data.get(icao24); const callsign = info?.callsign?.trim() || null; @@ -652,7 +648,7 @@ export function createQueries({ * Cheap snapshot for voice-tool framing — drawn icon positions, no * extra dead reckoning. * @param {number} [maxCount=500] - Maximum number of entries to return. - * @returns {Array<{id: string, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>} + * @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>} */ /** * Whether this layer still carries a contact, in O(1). @@ -686,20 +682,16 @@ export function createQueries({ const result = []; for (const icao24 of icons.ids()) { - const pos = icons.position(icao24, t, new Cesium.Cartesian3()); - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - flightState._scratchCarto, - ); + const pos = icons.position(icao24, t, vec()); + const carto = toLonLatH(pos); if (!carto) continue; const info = flightState.records.data.get(icao24); result.push({ id: icao24, // identity (trackById resolves this) label: _contactLabel(icao24, info), position: pos, - latitude: Cesium.Math.toDegrees(carto.latitude), - longitude: Cesium.Math.toDegrees(carto.longitude), + latitude: carto.lat, + longitude: carto.lon, altitudeM: carto.height, airline: info?.airline ?? null, typeName: info?.typeName ?? null, @@ -831,7 +823,6 @@ export function createQueries({ if (!flightState._icons?.has(id)) id = id.toLowerCase(); if ( id !== flightState._trackedIcao || - !flightState._viewer.entities?.contains?.(flightState._trackedEntity) || followedOf(flightState._viewer) !== flightState._followTarget ) return false; @@ -873,7 +864,7 @@ export function createQueries({ /** * Return the current aircraft as a Context subject without changing * tracking or camera ownership. - * @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null} + * @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null} * Detached subject descriptor, or null when no aircraft is tracked. */ getTrackedSubject() { @@ -889,7 +880,7 @@ export function createQueries({ described.callsign || _toCleanText(described.registration) || described.icao24, - position: Cesium.Cartesian3.clone(described.position), + position: clone(described.position), }; }, @@ -914,17 +905,14 @@ export function createQueries({ takeFrameClock(startMs = 1_000_000_000) { if (!flightState._viewer || !Number.isFinite(startMs)) return { ok: false, nowMs: null }; - flightState._viewer.useDefaultRenderLoop = false; + // The loop stops ticking; evidence frames are drawn by hand. + findFrame(flightState._viewer)?.suspend(true); setFocusEvidenceNowMs(startMs); flightState._lastFleetTickMs = startMs - FLEET_DR_INTERVAL_MS; - // Cross a browser task boundary, then close Cesium's pending-loop - // latch. Any already-queued callback still observes the false gate, - // while manual evidence renders can begin without waiting on VSYNC. + // Cross a browser task boundary, so a loop callback already + // queued has seen the stopped loop before manual renders begin. return new Promise((resolve) => - setTimeout(() => { - closeRenderLoopLatch(flightState._viewer); - resolve({ ok: true, nowMs: startMs }); - }, 0), + setTimeout(() => resolve({ ok: true, nowMs: startMs }), 0), ); }, advanceFrameClock(deltaMs = FLEET_DR_INTERVAL_MS) { @@ -933,7 +921,7 @@ export function createQueries({ releaseFrameClock() { setFocusEvidenceNowMs(null); if (flightState._viewer) - flightState._viewer.useDefaultRenderLoop = true; + findFrame(flightState._viewer)?.suspend(false); }, }), } diff --git a/src/layers/flights/queries.test.mjs b/src/layers/flights/queries.test.mjs index 77d2dd492..cc96deeee 100644 --- a/src/layers/flights/queries.test.mjs +++ b/src/layers/flights/queries.test.mjs @@ -79,8 +79,7 @@ function fixture() { formats: () => formats, place, show: (shown) => icons.setShown('abc123', shown), - drawn: () => - parts.icons._iconPosition('abc123', new Cesium.Cartesian3()), + drawn: () => parts.icons._iconPosition('abc123', { x: 0, y: 0, z: 0 }), }; } @@ -92,7 +91,7 @@ test('candidate text follows in-place enrichment without freezing identity or po f.place(new Cesium.Cartesian3(4, 5, 6)); assert.equal(f.queries.getDetectableObjects()[0], first); assert.deepEqual(first.position, f.drawn()); - assert.deepEqual(first.position, new Cesium.Cartesian3(4, 5, 6)); + assert.deepEqual(first.position, { x: 4, y: 5, z: 6 }); assert.equal(f.formats(), 1); f.info.callsign = ' NEW456 '; assert.equal(f.queries.getDetectableObjects()[0].id, 'NEW456'); @@ -141,10 +140,10 @@ test('candidate collection resolves models once and keeps handoffs live', (t) => assert.deepEqual(f.queries.getDetectableObjects(), []); record.ready = true; assert.equal(f.queries.getDetectableObjects()[0], candidate); - assert.deepEqual(candidate.position, new Cesium.Cartesian3(10, 20, 30)); + assert.deepEqual(candidate.position, { x: 10, y: 20, z: 30 }); placeAt(record, new Cesium.Cartesian3(40, 50, 60)); f.queries.getDetectableObjects(); - assert.deepEqual(candidate.position, new Cesium.Cartesian3(40, 50, 60)); + assert.deepEqual(candidate.position, { x: 40, y: 50, z: 60 }); showModel(record, false); assert.deepEqual(f.queries.getDetectableObjects(), []); f.show(true); @@ -175,7 +174,10 @@ test('tracked ownership and live anchors remain independent of fleet models', () ]) { f.flightState._trackedModel = tracked; assert.equal( - f.parts.rendering._modelOwnsVisual('abc123', modelRecord({ ready: true, show: true })), + f.parts.rendering._modelOwnsVisual( + 'abc123', + modelRecord({ ready: true, show: true }), + ), false, ); } diff --git a/src/layers/flights/rendering.js b/src/layers/flights/rendering.js index 8568f18ab..fbc4c80d9 100644 --- a/src/layers/flights/rendering.js +++ b/src/layers/flights/rendering.js @@ -102,19 +102,15 @@ export function createRendering({ /** * Sample the rendered mesh under the collected floor cells (see - * meshFloorSampler.js), leaving this layer's own icons out of the probe so - * it cannot land on an aircraft instead of the pavement. + * meshFloorSampler.js), leaving this layer's own icon and model sets out + * of the probe so it cannot land on an aircraft instead of the pavement. */ function _sampleMeshFloor(points, viewerLat, viewerLon) { - services.meshFloor.sampleMeshFloorCells( - flightState._viewer?.scene, - points, - { - excludeObjects: parts.icons._iconIds(), - viewerLat, - viewerLon, - }, - ); + services.meshFloor.sampleMeshFloorCells(flightState._viewer, points, { + sets: models._groundSampleExclusions().sets, + viewerLat, + viewerLon, + }); } return { diff --git a/src/layers/flights/state.js b/src/layers/flights/state.js index 028b72810..a9838f03c 100644 --- a/src/layers/flights/state.js +++ b/src/layers/flights/state.js @@ -1,6 +1,5 @@ import { FlightRecords } from './records.js'; import { createFlightFeed } from './ingestion.js'; -import * as Cesium from 'cesium'; import { ENRICH_AMBIENT_BUDGET_CEIL } from './policy.js'; export function createFlightState({ source, services }) { @@ -53,11 +52,6 @@ export function createFlightState({ source, services }) { flightState._lastModelCapWarnMs = 0; // throttle the "more planes in view than the cap" console notice - flightState._scratchModelBS = new Cesium.BoundingSphere( - new Cesium.Cartesian3(), - 1.0, - ); - // frustum-visibility test // keep last N positions per aircraft // --------------------------------------------------------------------------- @@ -93,7 +87,7 @@ export function createFlightState({ source, services }) { flightState._focusEvidenceIds = new Set(); - /** @type {Map>} */ + /** @type {Map>} */ flightState._positionHistory = new Map(); @@ -109,7 +103,7 @@ export function createFlightState({ source, services }) { flightState._trackingIntentGeneration = 0; - /** @type {Cesium.Entity|null} Entity used for camera tracking */ + /** @type {object|null} The tracked aircraft's record holder (its entity record is what the app shows; the camera follows a target reading it) */ flightState._trackedEntity = null; @@ -127,7 +121,7 @@ export function createFlightState({ source, services }) { flightState._clickSubscription = null; - /** @type {Cesium.Viewer|null} Cached viewer reference */ + /** @type {object|null} Cached viewer reference */ flightState._viewer = null; @@ -157,7 +151,7 @@ export function createFlightState({ source, services }) { flightState._trailHeadOff = null; - /** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */ + /** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */ flightState._trailPositions = []; @@ -173,17 +167,17 @@ export function createFlightState({ source, services }) { flightState._lastTrackedRotation = 0; - /** @type {Cesium.Event.RemoveCallback|null} preRender listener disposer */ + /** @type {() => void|null} preRender listener disposer */ flightState._preRenderRemove = null; flightState._trackedModelPreUpdateRemove = null; - /** @type {Cesium.Event.RemoveCallback|null} camera.moveEnd listener disposer (arrival rotation pass) */ + /** @type {() => void|null} camera.moveEnd listener disposer (arrival rotation pass) */ flightState._moveEndRemove = null; - /** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */ + /** @type {() => void|null} trackedEntityChanged listener disposer (cross-layer untrack) */ flightState._trackedEntityChangedRemove = null; @@ -195,29 +189,27 @@ export function createFlightState({ source, services }) { // Scratch (reusable) variables — avoid per-frame heap allocation // --------------------------------------------------------------------------- - flightState._scratchOffset = new Cesium.Cartesian3(); - - flightState._scratchCarto = new Cesium.Cartographic(); + flightState._scratchOffset = { x: 0, y: 0, z: 0 }; flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 }; - flightState._scratchRenderTime = new Cesium.JulianDate(); + flightState._scratchRenderTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._scratchFleetRenderTime = new Cesium.JulianDate(); + flightState._scratchFleetRenderTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._scratchFleetPos = new Cesium.Cartesian3(); + flightState._scratchFleetPos = { x: 0, y: 0, z: 0 }; - flightState._scratchCockpitPos = new Cesium.Cartesian3(); + flightState._scratchCockpitPos = { x: 0, y: 0, z: 0 }; - flightState._scratchNearbyPos = new Cesium.Cartesian3(); + flightState._scratchNearbyPos = { x: 0, y: 0, z: 0 }; - flightState._scratchSonarScreen = new Cesium.Cartesian2(); + flightState._scratchSonarScreen = { x: 0, y: 0 }; - flightState._scratchDrRaw = new Cesium.Cartesian3(); + flightState._scratchDrRaw = { x: 0, y: 0, z: 0 }; - flightState._scratchWarmupTime = new Cesium.JulianDate(); + flightState._scratchWarmupTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._trackedPosHolder = new Cesium.Cartesian3(); + flightState._trackedPosHolder = { x: 0, y: 0, z: 0 }; // --------------------------------------------------------------------------- // Per-frame cache for the tracked entity's dead-reckoned position. @@ -225,7 +217,7 @@ export function createFlightState({ source, services }) { // render frame; caching avoids running _deadReckon three times. // --------------------------------------------------------------------------- - /** @type {Cesium.Cartesian3|null} */ + /** @type {{x: number, y: number, z: number}|null} */ flightState._cachedDRPosition = null; @@ -302,13 +294,13 @@ export function createFlightState({ source, services }) { flightState._enrichAmbientRefillAnchorMs = 0; - flightState._drCorrection = new Cesium.Cartesian3(0, 0, 0); + flightState._drCorrection = { x: 0, y: 0, z: 0 }; flightState._drCorrectionStartMs = 0; - flightState._drPrevRaw = new Cesium.Cartesian3(); + flightState._drPrevRaw = { x: 0, y: 0, z: 0 }; - flightState._drPrevDisplay = new Cesium.Cartesian3(); + flightState._drPrevDisplay = { x: 0, y: 0, z: 0 }; flightState._drPrevMs = 0; @@ -318,20 +310,20 @@ export function createFlightState({ source, services }) { flightState._drReconcileIcao = null; - /** @type {Cesium.Cartesian3} Scratch for the tracked model's rendered translation. */ + /** @type {{x: number, y: number, z: number}} Scratch for the tracked model's rendered translation. */ - flightState._trackedVisualPos = new Cesium.Cartesian3(); + flightState._trackedVisualPos = { x: 0, y: 0, z: 0 }; - flightState._trackedTrailPos = new Cesium.Cartesian3(); + flightState._trackedTrailPos = { x: 0, y: 0, z: 0 }; /** Scratch for the tracked model's world-space origin (the envelope centre). */ - flightState._scratchTrailClip = new Cesium.Cartesian3(); + flightState._scratchTrailClip = { x: 0, y: 0, z: 0 }; /** Scratch for the shortened trail-head start. Owned by the head-segment * callback alone, so nothing else can overwrite it mid-frame. */ - flightState._scratchTrailHead = new Cesium.Cartesian3(); + flightState._scratchTrailHead = { x: 0, y: 0, z: 0 }; /** Hysteresis latch for the tracked contact's zoom regime, plus the selection it * belongs to. Scoped per selection so a NEW target re-evaluates against the ENTER @@ -341,12 +333,8 @@ export function createFlightState({ source, services }) { flightState._trackedZoomLatchIcao = null; - /** @type {Cesium.Cartographic} Scratch for the grounded display-floor read. */ - - flightState._scratchDisplayCarto = new Cesium.Cartographic(); - /** @type {Map flightState._viewer, + setPrefix: 'flights', + }); + + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + const viewer = flightState._viewer; + try { + return (viewer && findCamera(viewer)?.pose()) ?? null; + } catch { + return null; + } + } function _emitAwarenessEvent(type, detail) { if ( @@ -81,7 +108,7 @@ export function createTracking({ } function _publishTrackedSelection(icao24, origin = 'programmatic') { - const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3()); + const position = parts.icons._iconPosition(icao24, vec()); const info = flightState.records.data.get(icao24); if (!position || !info) return false; if (flightState._trackedEntity) @@ -169,10 +196,8 @@ export function createTracking({ */ function _refreshCockpitNearContacts() { - if ( - !flightState._cockpitContactMode || - !flightState._viewer?.camera?.positionWC - ) { + const eye = flightState._cockpitContactMode ? _pose()?.position : null; + if (!eye) { if (flightState._cockpitNearContacts.size) flightState._cockpitNearContacts = new Set(); return; @@ -188,13 +213,7 @@ export function createTracking({ t, flightState._scratchCockpitPos, ); - distancesSquared.push([ - icao24, - Cesium.Cartesian3.distanceSquared( - flightState._viewer.camera.positionWC, - position, - ), - ]); + distancesSquared.push([icao24, distanceSquared(eye, position)]); } const next = nextCockpitNearContacts( previous, @@ -291,7 +310,7 @@ export function createTracking({ return false; } flightState._trackedZoomLatched = trackedModelZoomActive( - flightState._viewer?.camera?.positionCartographic?.height, + _pose()?.height, flightState._trackedZoomLatched, ); return flightState._trackedZoomLatched; @@ -303,13 +322,10 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - parts.icons._iconPosition( - flightState._trackedIcao, - new Cesium.Cartesian3(), - ); + parts.icons._iconPosition(flightState._trackedIcao, vec()); if (!pos) return; - const projected = screenProjectedRotation( - flightState._viewer.scene, + const projected = courseScreenRotation( + _pose(), pos, parts.motion._trackedDisplayCourse(), flightState._lastTrackedRotation, @@ -325,7 +341,7 @@ export function createTracking({ /** * Append one fix to the tracked aircraft's trail accumulation and refresh * the rendered trail. Caller passes an owned (cloned) Cartesian3. - * @param {Cesium.Cartesian3} position - New fix position, appended at the head. + * @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head. */ function _appendTrailFix(position) { @@ -361,7 +377,7 @@ export function createTracking({ /** * The live head: the last DISPLAYED body point to the delayed head, or no * positions while there is none. - * @returns {Cesium.Cartesian3[]} + * @returns {Array<{x: number, y: number, z: number}>} */ function _trailHeadPositions() { // Need ≥2 accumulated points: the body draws all-but-newest, so the head must @@ -398,7 +414,7 @@ export function createTracking({ flightState._scratchTrailHead, ); if (!from) return []; - return [from, Cesium.Cartesian3.clone(head)]; + return [from, clone(head)]; } /** Each drawn frame, before it draws: the live head where the aircraft is now. */ @@ -421,14 +437,14 @@ export function createTracking({ // newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them // would draw the trail in front of the plane. They join the trail via _appendTrailFix // as they age past the delay. - const seedRenderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(), + const seedRenderTime = addSeconds( + julianNow(), -RENDER_DELAY_SEC, flightState._scratchWarmupTime, ); for (const fix of history) { - if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) { - flightState._trailPositions.push(Cesium.Cartesian3.clone(fix.position)); + if (julianLessThanOrEquals(fix.time, seedRenderTime)) { + flightState._trailPositions.push(clone(fix.position)); } } if (!flightState._trail && flightState._viewer) { @@ -449,7 +465,7 @@ export function createTracking({ _refreshTrailDisplay(); const oldestFixEpochSec = history.length - ? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000 + ? julianToEpochMs(history[0].time) / 1000 : Infinity; _backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec); } @@ -541,7 +557,7 @@ export function createTracking({ // with nothing to carry keep the old 10 km airborne default. if (altM == null) altM = lastAltM != null ? lastAltM : 10000; lastAltM = altM; - older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM)); + older.push(fromDegrees(lon, lat, altM)); } flightState._trailPositions = older.concat(flightState._trailPositions); @@ -614,18 +630,16 @@ export function createTracking({ // release never flips it. const trackedCourseDeg = flightState._displayCourse.get(clearedIcao); - // Stop tracking and remove the entity. skipViewerUntrack: when ANOTHER layer just grabbed the - // follow-camera, we tear down our own state but must NOT clear the camera's follow (the new owner - // controls it now — clearing it would yank the camera off their plane). Releasing trackedEntity - // does NOT move the camera: Cesium resets the lookAt transform in place, so the view stays where - // the follow left it and the user can immediately orbit/zoom. + // Stop tracking and hide the tracked billboard. skipViewerUntrack: when ANOTHER layer just + // grabbed the follow-camera, we tear down our own state but must NOT clear the camera's follow + // (the new owner controls it now — clearing it would yank the camera off their plane). + // Releasing the follow does NOT move the camera: the view stays where the follow left it and + // the user can immediately orbit/zoom. if (flightState._viewer && !skipViewerUntrack) { stopFollowing(flightState._viewer); } - if (flightState._trackedEntity) { - flightState._viewer.entities.remove(flightState._trackedEntity); - flightState._trackedEntity = null; - } + trackedIcon.hide(); + flightState._trackedEntity = null; parts.rendering._releaseTrackedModel(); _resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped flightState._trackedIcao = null; @@ -756,12 +770,9 @@ export function createTracking({ refreshTrackedSubjectContext(_contextSubjectMetadata(icao24)); } - /** Re-image the tracked entity's billboard from the current class/conversion. */ - - function _syncTrackedBillboardImage() { - if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard) - return; - flightState._trackedEntity.billboard.image = aircraftIcon( + /** The tracked billboard's image, from the current class/conversion. */ + function _trackedBillboardImage() { + return aircraftIcon( parts.rendering._iconKind( flightState._trackedIcao, flightState.records.data.get(flightState._trackedIcao)?.klass, @@ -770,6 +781,13 @@ export function createTracking({ ); } + /** Re-image the tracked billboard from the current class/conversion. */ + + function _syncTrackedBillboardImage() { + if (!flightState._trackedIcao || !flightState._trackedEntity) return; + trackedIcon.setImage(_trackedBillboardImage()); + } + /** * Re-render one contact after its TR-3B conversion (or the active IR style) * changed. Converting drops any 3D model so the triangle owns the visual; the @@ -799,7 +817,8 @@ export function createTracking({ _syncTrackedBillboardImage(); _updateTrackedLabelModel(id); } - flightState._viewer?.scene?.requestRender?.(); + if (flightState._viewer) + findFrame(flightState._viewer)?.requestRender('flights: TR-3B restyle'); return flightState._icons?.has(id) || id === flightState._trackedIcao; } @@ -818,17 +837,13 @@ export function createTracking({ function _routeIsPlausible(icao24, route) { const info = flightState.records.data.get(icao24); - const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3()); + const position = parts.icons._iconPosition(icao24, vec()); if (!info || !position) return true; - const carto = Cesium.Cartographic.fromCartesian( - position, - Cesium.Ellipsoid.WGS84, - flightState._scratchCarto, - ); + const carto = toLonLatH(position); if (!carto) return true; return routePlausible({ - latDeg: Cesium.Math.toDegrees(carto.latitude), - lonDeg: Cesium.Math.toDegrees(carto.longitude), + latDeg: carto.lat, + lonDeg: carto.lon, altitudeM: info.altitude ?? null, verticalRateMps: info.verticalRate ?? null, origin: route.origin, @@ -839,16 +854,12 @@ export function createTracking({ /** * Begin tracking a specific aircraft by ICAO24 address. * - * Clears any existing tracked flight, hides its billboard, and creates a - * new Entity with: - * - A CallbackProperty position driven by dead-reckoning (_deadReckon). - * - A CallbackProperty alignedAxis set to the surface normal at the - * dead-reckoned position (keeps the icon tangent to the earth). - * - A CallbackProperty rotation from the aircraft's true_track heading. - * - An explicit host presentation model with callsign, flight level, speed, - * identity, and plausible route text. - * - * The viewer's trackedEntity is set to this entity so the camera follows it. + * Clears any existing tracked flight, hides its fleet icon, and shows the + * tracked billboard (`createTrackedAircraftIcon`), drawn each frame at the + * dead-reckoned display position, screen-rotated along the displayed + * course. The tracked record carries the host presentation model + * (callsign, flight level, speed, identity, plausible route text), and the + * camera follows a target that reads it. * * @param {string} icao24 - ICAO 24-bit transponder address to track. */ @@ -863,19 +874,14 @@ export function createTracking({ // The tracked limiter continues from the nose the icon was drawn with, and // the entity starts with the rotation the icon had on screen. const t = parts.icons._displayMs(); - const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3()); + const iconPosition = icons.position(icao24, t, vec()); const iconCourse = icons.course(icao24, t); flightState._displayCourse.set(icao24, iconCourse); flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling flightState._cachedDRFrame = -1; flightState._lastTrackedRotation = - screenProjectedRotation( - flightState._viewer.scene, - iconPosition, - iconCourse, - 0, - ) ?? 0; + courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0; // Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its // own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover // fleet model would be orphaned + double-rendered. @@ -890,28 +896,20 @@ export function createTracking({ // the aircraft has no fix. const getTrackedPosition = () => parts.motion._trackedDisplayPosition(icao24) || - parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) || + parts.icons._iconPosition(icao24, vec()) || iconPosition; - // Dead-reckoning position property — smooth continuous motion between API updates. - const positionProperty = new Cesium.CallbackProperty(() => { - return getTrackedPosition(); - }, false); - - // Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the - // TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the - // DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always + // The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed + // in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on + // the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always // resolves into an aircraft. // // The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by - // show=false: it drops its alpha only once the tracked model is drawing, so - // there's neither a billboard+model double-image nor a gap. The camera follows its own target - // through the camera port, so nothing here frames the camera. - // The tracked entity is a PURE BILLBOARD — no label or model graphic. The 3D model for the - // tracked plane is a standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel). - // Keep Cesium's generated entity ID: re-init without destroy can temporarily - // overlap collections, and an explicit ICAO ID would throw on that duplicate. - // What the tracked billboard is drawn at, kept in its entity record so the + // show=false: it drops its alpha only once the tracked model is drawing, so there's neither a + // billboard+model double-image nor a gap. The camera follows its own target through the camera + // port, so nothing here frames the camera. The 3D model for the tracked plane is a draw-set + // item driven by _updateTrackedModel() (see _trackedModel). + // What the tracked billboard is drawn at, kept in its record so the // camera guard and screen annotations size it from the app. const sprite = { width: 28, @@ -922,58 +920,49 @@ export function createTracking({ ] || 1, scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, }; - flightState._trackedEntity = flightState._viewer.entities.add({ - position: positionProperty, - billboard: { - image: aircraftIcon( - parts.rendering._iconKind( - flightState._trackedIcao, - flightState.records.data.get(flightState._trackedIcao)?.klass, - ), - TRACKED_ICON_PX, - ), - width: sprite.width, - height: sprite.height, - scale: sprite.scale, - // Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading); - // transparent once the STANDALONE tracked model is actually up (ready + shown). - color: new Cesium.CallbackProperty( - () => - parts.rendering._modelOwnsVisual(flightState._trackedIcao) - ? CYAN_TRANSPARENT - : Cesium.Color.CYAN, - false, - ), - sizeInMeters: false, - scaleByDistance: sprite.scaleByDistance, - alignedAxis: Cesium.Cartesian3.ZERO, - // The tracked target must never vanish into tile geometry — tracking a - // taxiing plane at street level would otherwise bury the cyan icon inside - // the runway skin, so it draws depth-test-free like the fleet icon set; - // its shared-host tracked card is top-composited separately. - disableDepthTestDistance: Number.POSITIVE_INFINITY, - // Screen-projected rotation, evaluated per frame: exact in tracked-orbit - // mode where camera.heading lives in the entity's reference frame. - rotation: new Cesium.CallbackProperty(() => { - const tracked = flightState.records.data.get( - flightState._trackedIcao, - ); - const pos = getTrackedPosition(); - if (!tracked || !pos || !flightState._viewer) - return flightState._lastTrackedRotation; - const projected = screenProjectedRotation( - flightState._viewer.scene, - pos, - parts.motion._trackedDisplayCourse(), - flightState._lastTrackedRotation, - ); - const rot = stabilizeScreenRotation( - flightState._lastTrackedRotation, - projected, - ); - if (rot !== null) flightState._lastTrackedRotation = rot; + // The tracked contact as its readers see it (the tracked card, Cockpit, share links): a + // plain holder of its entity record, drawn while it is the one tracked. + const holder = trackedContactHolder( + `flights:${icao24}`, + trackedIcon, + parts.motion._trackedDisplayCached, + ); + flightState._trackedEntity = holder; + entityRecord(holder).drawn = () => flightState._trackedEntity === holder; + trackedIcon.show({ + id: icao24, + image: _trackedBillboardImage(), + sprite, + position: getTrackedPosition, + // Solid cyan when the billboard is the visual (zoomed out, 3D off, or model still loading); + // transparent once the tracked model is actually up (ready + shown). + color: () => + parts.rendering._modelOwnsVisual(flightState._trackedIcao) + ? CYAN_TRANSPARENT + : TRACKED_CYAN, + // Screen-projected rotation, evaluated per frame on the camera's own + // axes, so it stays exact through a tracked orbit. The tracked target + // must never vanish into tile geometry — tracking a taxiing plane at + // street level would otherwise bury the cyan icon inside the runway + // skin, so it draws over depth like the fleet icon set; its + // shared-host tracked card is top-composited separately. + rotation: () => { + const tracked = flightState.records.data.get(flightState._trackedIcao); + const pos = getTrackedPosition(); + if (!tracked || !pos || !flightState._viewer) return flightState._lastTrackedRotation; - }, false), + const projected = courseScreenRotation( + _pose(), + pos, + parts.motion._trackedDisplayCourse(), + flightState._lastTrackedRotation, + ); + const rot = stabilizeScreenRotation( + flightState._lastTrackedRotation, + projected, + ); + if (rot !== null) flightState._lastTrackedRotation = rot; + return flightState._lastTrackedRotation; }, }); entityRecord(flightState._trackedEntity).selectionOrigin = origin; @@ -982,22 +971,18 @@ export function createTracking({ entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_trackedLabelText(icao24), '#39d0ff'); - // A billboard has a ~zero bounding sphere, so Cesium's default follow distance is - // far too tight (the user had to scroll out to read the plane). Give the entity a + // A billboard has a ~zero bounding sphere, so the renderer's default follow distance is + // far too tight (the user had to scroll out to read the plane). Give the target a // calibrated viewFrom — behind + above, distance scaled to altitude — for a readable // initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.) const followRange = Math.min( Math.max((info.altitude || 1500) * 1.1 + 2500, 3000), 30000, ); - const viewFrom = new Cesium.Cartesian3( - 0, - -followRange * 0.8, - followRange * 0.55, - ); + const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55); - // Cancel any in-progress camera flight first — otherwise Cesium won't apply the - // tracked entity's viewFrom on the first frame, so voice-initiated tracking (which + // Cancel any in-progress camera flight first — otherwise the camera won't apply the + // follow target's viewFrom on the first frame, so voice-initiated tracking (which // often fires mid-fly_to_location) would follow the plane WITHOUT centering/framing it // the way a click (idle camera) does. // Expose the camera's already-settled position to cross-module HUD consumers (the tracked-target @@ -1092,15 +1077,13 @@ export function createTracking({ } /** - * Install a LEFT_CLICK handler on the scene canvas for flight selection. - * - * Picking logic checks both `picked.primitive` and `picked.id` because - * different CesiumJS versions surface BillboardCollection hits differently. - * Also registers a global keydown listener for the Escape key. + * Install a click handler for flight selection: a pick names a draw-set + * item by the contact's icao (see `aircraftPickId`). Also registers a + * global keydown listener for the Escape key. * * Idempotent — returns immediately if a handler is already installed. * - * @param {Cesium.Viewer} viewer + * @param {object} viewer */ function _installClickHandler(viewer) { @@ -1142,14 +1125,11 @@ export function createTracking({ const picked = event.hit; if (picked) { - // Clicking the tracked entity itself — ignore (don't deselect) - if (picked.id === flightState._trackedEntity) return; - - // Clicking the plane we're ALREADY tracking (its standalone 3D model or - // any pick carrying its icao) — same no-op as the 2D tracked-entity click - // above. H1: the model used to have no pick id, so this fell through to + // Clicking the plane we're ALREADY tracking (its tracked billboard, its + // 3D model, or any pick carrying its icao) — ignore, don't deselect. + // H1: the model used to have no pick id, so this fell through to // "empty space" and deselected the very plane being tracked. - // Its models are draw-set items keyed by icao, like its icons. + // Its billboard and models are draw-set items keyed by icao, like its icons. const pickedIcao = aircraftPickId(picked); if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao) return; @@ -1199,6 +1179,9 @@ export function createTracking({ _backfillTrail, _clearTrail, _destroyTrail, + /** Let the tracked billboard's set go (layer teardown). */ + _disposeTrackedIcon: () => trackedIcon.dispose(), + /** The tracked billboard's set id, or null before one is made. */ _clearTracking, _militaryLayerSuppresses, _applyPendingTrackingRestore, diff --git a/src/layers/military/lifecycle.js b/src/layers/military/lifecycle.js index 3226bbea3..7b0136ea4 100644 --- a/src/layers/military/lifecycle.js +++ b/src/layers/military/lifecycle.js @@ -218,6 +218,7 @@ export function createLifecycle({ } parts.rendering._releaseModels(); parts.icons._disposeIcons(); + parts.tracking._disposeTrackedIcon(); parts.rendering._disposeModelSets(); flightState._iconFocusActive = 0; flightState._detectionObjects.clear(); diff --git a/src/layers/military/motion.js b/src/layers/military/motion.js index 86f3104cd..e4633d8a6 100644 --- a/src/layers/military/motion.js +++ b/src/layers/military/motion.js @@ -1,4 +1,23 @@ -import * as Cesium from 'cesium'; +import { findCamera, rendererOf } from '../../render/rendererOf.js'; +import { renderedFrames } from '../../data/renderedFrames.js'; +import { fromDegrees } from '../../geo/ellipsoid.js'; +import { eastNorthUp, framePoint } from '../../geo/frames.js'; +import { + addSeconds, + julianLessThan, + julianNow, + secondsDifference, +} from '../../geo/julian.js'; +import { + add, + clamp, + copyInto, + distance, + lerpInto, + scale, + sub, + vec, +} from '../../geo/vector.js'; import { lerpAngleDeg, COURSE_HOLD_SPEED_MPS, @@ -37,6 +56,9 @@ import { /** Where a military record carries its reported speed and track. */ const RECORD_FIELDS = { speed: 'speedMps', track: 'track' }; +/** Whether two ECEF points are the same point, component for component. */ +const samePoint = (a, b) => a.x === b.x && a.y === b.y && a.z === b.z; + export function createMotion({ flightState, services, @@ -48,11 +70,33 @@ export function createMotion({ const { nearFarScalarValueAtDistance, clearFocusTarget, - publishFocusTargetFromCachedPosition, + publishFocusTargetAt, } = services.focus; /** `_motionRegime`'s reused result. */ const regime = createMotionRegime(); + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + const viewer = flightState._viewer; + try { + return (viewer && findCamera(viewer)?.pose()) ?? null; + } catch { + return null; + } + } + + /** The renderer canvas's CSS height (the viewer's own canvas when no + * renderer is bound), or 0 without either. */ + function _viewportHeightPx() { + const viewer = flightState._viewer; + const canvas = rendererOf(viewer)?.canvas ?? viewer?.canvas; + return Number(canvas?.clientHeight) || 0; + } + + // Fixes leave the cache with their history; a corrected position + // invalidates the local frame even when the fix's point is changed in place. + const fixFrames = new WeakMap(); + /** * Dead-reckon an aircraft's current position using ENU (East-North-Up) frame math. * @@ -63,8 +107,8 @@ export function createMotion({ * source contact plus a bounded grace window. * * @param {string} icao24 - ICAO hex identifier of the aircraft - * @param {Cesium.Cartesian3} [result] - Optional out-parameter to write into. - * @returns {Cesium.Cartesian3|null} Estimated current ECEF position, or null if no history + * @param {{x: number, y: number, z: number}} [result] - Optional out-parameter to write into. + * @returns {{x: number, y: number, z: number}|null} Estimated current ECEF position, or null if no history */ function _deadReckon(icao24, result) { @@ -77,11 +121,11 @@ export function createMotion({ return null; } - const out = result || new Cesium.Cartesian3(); + const out = result || vec(); // Render one poll interval behind real time so we interpolate between // two KNOWN fixes whenever possible (see RENDER_DELAY_SEC rationale). - const renderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(), + const renderTime = addSeconds( + julianNow(), -RENDER_DELAY_SEC, flightState._scratchRenderTime, ); @@ -89,10 +133,7 @@ export function createMotion({ const regime = _motionRegime(history, info, renderTime); if (regime.kind === 'between') { const { a, b, span } = regime; - const t = - span > 0 - ? Cesium.JulianDate.secondsDifference(renderTime, a.time) / span - : 1.0; + const t = span > 0 ? secondsDifference(renderTime, a.time) / span : 1.0; const trackCourse = lerpAngleDeg(regime.trackFrom, regime.trackTo, t); flightState._drCourseDeg = regime.chordCourse != null @@ -100,10 +141,10 @@ export function createMotion({ : trackCourse; flightState._drSpeedMps = regime.speed; flightState._drCourseHold = regime.speed < COURSE_HOLD_SPEED_MPS; - return Cesium.Cartesian3.lerp(a.position, b.position, t, out); + return lerpInto(a.position, b.position, t, out); } - const dt = Cesium.Math.clamp( - Cesium.JulianDate.secondsDifference(renderTime, regime.fix.time), + const dt = clamp( + secondsDifference(renderTime, regime.fix.time), regime.minDt, regime.maxDt, ); @@ -144,24 +185,26 @@ export function createMotion({ flightState._drCourseHold = speed < COURSE_HOLD_SPEED_MPS; if (speed === 0 || dt === 0) { flightState._drCourseDeg = heading; - return Cesium.Cartesian3.clone(fix.position, out); + return copyInto(fix.position, out); } // Constant-rate-turn arc (straight line when turnRateDps ≈ 0) — a plane in a // standard-rate turn is ~90° of arc wrong per 30 s if extrapolated straight. arcOffsetEnu(speed, heading, turnRateDps, dt, flightState._scratchArc); flightState._drCourseDeg = flightState._scratchArc.endCourseDeg; - Cesium.Cartesian3.fromElements( - flightState._scratchArc.east, - flightState._scratchArc.north, - 0, - flightState._scratchOffset, - ); - const enu = Cesium.Transforms.eastNorthUpToFixedFrame( - fix.position, - Cesium.Ellipsoid.WGS84, - flightState._scratchEnu, - ); - return Cesium.Matrix4.multiplyByPoint(enu, flightState._scratchOffset, out); + const offset = flightState._scratchOffset; + offset.x = flightState._scratchArc.east; + offset.y = flightState._scratchArc.north; + offset.z = 0; + let frame = fixFrames.get(fix); + if (!frame) { + frame = { position: vec(), enu: null }; + fixFrames.set(fix, frame); + } + if (!frame.enu || !samePoint(frame.position, fix.position)) { + frame.enu = eastNorthUp(fix.position); + copyInto(fix.position, frame.position); + } + return copyInto(framePoint(frame.enu, offset), out); } /** @@ -175,21 +218,21 @@ export function createMotion({ if (!flightState._trackedIcao) return false; const history = flightState._positionHistory.get(flightState._trackedIcao); if (!history || history.length === 0) return true; - const renderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(), + const renderTime = addSeconds( + julianNow(), -RENDER_DELAY_SEC, flightState._scratchWarmupTime, ); - return Cesium.JulianDate.lessThan(renderTime, history[0].time); + return julianLessThan(renderTime, history[0].time); } /** Resolve the selected aircraft's actual rendered square extent this frame. */ function _trackedFocusSizePx(icao24, position) { - const camera = flightState._viewer?.camera; - const scene = flightState._viewer?.scene; - if (!camera?.positionWC || !position || !scene) return 28; - const rangeM = Cesium.Cartesian3.distance(camera.positionWC, position); + const pose = _pose(); + if (!pose || !position) return 28; + const rangeM = distance(pose.position, position); + const viewportHeightPx = _viewportHeightPx(); if (parts.rendering._modelOwnsVisual(icao24)) { const spec = parts.rendering._modelSpec( flightState.records.data.get(icao24)?.klass, @@ -198,12 +241,11 @@ export function createMotion({ baseScale: spec.scale, nativeRadiusM: spec.nativeRadiusM, rangeM, - viewportHeightPx: scene.canvas.clientHeight, - fovyRad: camera.frustum.fovy, + viewportHeightPx, + fovyRad: pose.fovy, maximumPixelSize: TRACKED_MODEL_MAX_PX, }); - const focalLengthPx = - scene.canvas.clientHeight / (2 * Math.tan(camera.frustum.fovy / 2)); + const focalLengthPx = viewportHeightPx / (2 * Math.tan(pose.fovy / 2)); const projectedDiameterPx = (2 * spec.nativeRadiusM * scale * focalLengthPx) / rangeM; return Math.max( @@ -226,16 +268,16 @@ export function createMotion({ } /** - * Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by Cesium - * frame number so the position / rotation / trail-head callbacks share ONE computation + * Per-frame-cached, discontinuity-smoothed tracked DISPLAY position. Cached by drawn + * frame (see renderedFrames.js) so the position / rotation / trail-head callbacks share ONE computation * (and one reconciliation-state update) per frame. Returns a stable module holder, or * null when the aircraft has no fix. * @param {string} icao24 - * @returns {Cesium.Cartesian3|null} + * @returns {{x: number, y: number, z: number}|null} */ function _trackedDisplayPosition(icao24) { - const frame = flightState._viewer?.scene?.frameState?.frameNumber ?? -1; + const frame = renderedFrames(flightState._viewer); if ( frame === flightState._cachedDRFrame && icao24 === flightState._drReconcileIcao @@ -266,32 +308,29 @@ export function createMotion({ const speed = (info && info.speedMps) || 0; // Plausible single-frame motion (m): real velocity × frame Δt, ×4 slack + 25 m base. const plausible = speed * dtSec * 4 + 25; - if (Cesium.Cartesian3.distance(raw, flightState._drPrevRaw) > plausible) { + if (distance(raw, flightState._drPrevRaw) > plausible) { // Discontinuity — re-anchor so the DISPLAYED position stays continuous, then decay. - Cesium.Cartesian3.subtract( - flightState._drPrevDisplay, - raw, + copyInto( + sub(flightState._drPrevDisplay, raw), flightState._drCorrection, ); flightState._drCorrectionStartMs = nowMs; } } else { - Cesium.Cartesian3.fromElements(0, 0, 0, flightState._drCorrection); + copyInto(vec(), flightState._drCorrection); flightState._drCorrectionStartMs = nowMs - DR_CORRECTION_MS; // fully decayed } const elapsed = nowMs - flightState._drCorrectionStartMs; const factor = elapsed >= DR_CORRECTION_MS ? 0 : 1 - elapsed / DR_CORRECTION_MS; - const display = Cesium.Cartesian3.multiplyByScalar( - flightState._drCorrection, - factor, + const display = copyInto( + add(raw, scale(flightState._drCorrection, factor)), flightState._trackedPosHolder, ); - Cesium.Cartesian3.add(raw, display, display); - Cesium.Cartesian3.clone(raw, flightState._drPrevRaw); - Cesium.Cartesian3.clone(display, flightState._drPrevDisplay); + copyInto(raw, flightState._drPrevRaw); + copyInto(display, flightState._drPrevDisplay); flightState._drPrevMs = nowMs; flightState._drReconcileValid = true; flightState._cachedDRPosition = display; @@ -299,14 +338,13 @@ export function createMotion({ icao24, flightState._cachedDRPosition, ); - // Publish the exact frame cache shared by entity + follow camera. A second + // Publish the exact frame cache shared by billboard + follow camera. A second // DR sample here would advance reconciliation in a different frame phase // and visibly jitter the focus rectangle against the tracked aircraft. - publishFocusTargetFromCachedPosition({ + publishFocusTargetAt({ ownerLayer: 'militaryFlights', id: icao24, - scene: flightState._viewer?.scene, - camera: flightState._viewer?.camera, + viewer: flightState._viewer, displayPosition: flightState._cachedDRPosition, widthPx: focusSizePx, heightPx: focusSizePx, @@ -315,8 +353,8 @@ export function createMotion({ } /** The tracked plane's display position WITHOUT recomputing — the value the follow-camera already - * settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender at - * a later frameNumber, so recomputing _trackedDisplayPosition there jitters the label against the + * settled on this frame. Mirror of flights.js: getDetectableObjects + the readout run in postRender, + * later in the frame, so recomputing _trackedDisplayPosition there jitters the label against the * now-stable plane. Null when no valid fix (callers fall back to the icon position). */ function _trackedDisplayCached() { @@ -368,10 +406,12 @@ export function createMotion({ !parts.rendering._modelOwnsVisual(flightState._trackedIcao) ) return null; - return Cesium.Matrix4.getTranslation( - flightState._trackedModel.matrix, - flightState._scratchTrailClip, - ); + const m = flightState._trackedModel.matrix; + const out = flightState._scratchTrailClip; + out.x = m[12]; + out.y = m[13]; + out.z = m[14]; + return out; } function _trackedModelEnvelopeM() { @@ -471,7 +511,7 @@ export function createMotion({ flightState._cachedDRHold = false; flightState._trackedCourseMs = 0; } - /** The display instant `epochMs` as a JulianDate, for `_motionRegime`. */ + /** The display instant `epochMs` as a Julian date, for `_motionRegime`. */ const _displayTimeAt = (epochMs, result) => julianAt(epochMs, result); /** @@ -497,15 +537,10 @@ export function createMotion({ ) continue; info.renderAltitudeM = lifted; - const liftedPos = Cesium.Cartesian3.fromDegrees( - info.rawLon, - info.rawLat, - lifted, - ); + const liftedPos = fromDegrees(info.rawLon, info.rawLat, lifted); const hist = flightState._positionHistory.get(icao24); const newest = hist?.[hist.length - 1]; - if (newest) - newest.position = Cesium.Cartesian3.clone(liftedPos, newest.position); + if (newest) newest.position = copyInto(liftedPos, newest.position); if (flightState._icons.has(icao24)) { parts.icons._applyIconPresentation(icao24); parts.icons._planIcon(icao24); @@ -515,19 +550,15 @@ export function createMotion({ /** * Sample the rendered mesh under the collected floor cells (see - * meshFloorSampler.js), leaving this layer's own icons and models out of - * the probe so it cannot land on an aircraft instead of the pavement. + * meshFloorSampler.js), leaving this layer's own icon and model sets out + * of the probe so it cannot land on an aircraft instead of the pavement. */ function _sampleMeshFloor(points, viewerLat, viewerLon) { - services.meshFloor.sampleMeshFloorCells( - flightState._viewer?.scene, - points, - { - excludeObjects: parts.icons._iconIds(), - viewerLat, - viewerLon, - }, - ); + services.meshFloor.sampleMeshFloorCells(flightState._viewer, points, { + sets: parts.rendering._groundSampleExclusions().sets, + viewerLat, + viewerLon, + }); } return { diff --git a/src/layers/military/ownership.test.mjs b/src/layers/military/ownership.test.mjs index 90379cdb0..3915f5d78 100644 --- a/src/layers/military/ownership.test.mjs +++ b/src/layers/military/ownership.test.mjs @@ -90,7 +90,7 @@ test('military state owns separate contact maps, motion scratch and ground sampl '_displayCourse', '_positionHistory', '_groundSnap', - '_scratchCarto', + '_scratchNearbyPos', '_models', 'lifetime', ]) { diff --git a/src/layers/military/policy.js b/src/layers/military/policy.js index a2560eb40..a6d5b4458 100644 --- a/src/layers/military/policy.js +++ b/src/layers/military/policy.js @@ -1,5 +1,11 @@ -import * as Cesium from 'cesium'; import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js'; +import { cssColor } from '../../render/color.js'; + +/** A CSS colour as frozen `[r, g, b, a]`, 0..1 (the renderer's `Color`). */ +const rgba = (css, alpha) => + Object.freeze( + alpha === undefined ? cssColor(css) : [...cssColor(css).slice(0, 3), alpha], + ); /** * @module militaryFlights @@ -21,18 +27,17 @@ import { EMERGENCY_TINT_CSS } from '../../data/aircraftEmergency.js'; export const BILLBOARD_SCALE = 0.7; -/** @constant {Cesium.Color} Default amber tint for untracked military icons */ +/** @constant {number[]} Default amber tint for untracked military icons */ -export const MIL_ICON_COLOR = Cesium.Color.fromCssColorString('#FFB800'); +export const MIL_ICON_COLOR = rgba('#FFB800'); -/** @constant {Cesium.Color} Lighter amber tint applied to the actively tracked aircraft */ +/** @constant {number[]} Lighter amber tint applied to the actively tracked aircraft */ -export const TRACKED_ICON_COLOR = Cesium.Color.fromCssColorString('#FFD166'); +export const TRACKED_ICON_COLOR = rgba('#FFD166'); -/** @constant {Cesium.Color} Red tint for aircraft broadcasting an emergency (mirror of flights) */ +/** @constant {number[]} Red tint for aircraft broadcasting an emergency (mirror of flights) */ -export const EMERGENCY_ICON_COLOR = - Cesium.Color.fromCssColorString(EMERGENCY_TINT_CSS); +export const EMERGENCY_ICON_COLOR = rgba(EMERGENCY_TINT_CSS); // --- Ground traffic (owner reversal 2026-07-03; mirror of flights.js) --------------- // adsb.lol/readsb flags ground traffic with alt_baro === "ground" (no separate @@ -143,16 +148,17 @@ export const MODEL_BELLY_OFFSET_NATIVE = 5.631; /** Amber fade target for the tracked billboard once the model takes over (mirrors flights.js CYAN_TRANSPARENT). */ -export const AMBER_TRANSPARENT = MIL_ICON_COLOR.withAlpha(0); +export const AMBER_TRANSPARENT = rgba('#FFB800', 0); export const COCKPIT_CONTACT_SIZE_PX = 6; -export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = new Cesium.NearFarScalar( - 1000, - 3.0, - 8000000, - 0.5, -); +/** The tracked billboard's size by eye distance (the renderer's `NearFar`). */ +export const TRACKED_BILLBOARD_SCALE_BY_DISTANCE = Object.freeze({ + near: 1000, + nearValue: 3.0, + far: 8000000, + farValue: 0.5, +}); // --------------------------------------------------------------------------- // Track-history trail state (PRD WS-F F2/F4): a fading polyline behind the diff --git a/src/layers/military/queries.js b/src/layers/military/queries.js index 19c1b2ddf..8a79d3f1f 100644 --- a/src/layers/military/queries.js +++ b/src/layers/military/queries.js @@ -1,8 +1,9 @@ -import { cameraOf } from '../../render/cesium/camera.js'; +import { cameraOf } from '../../render/rendererOf.js'; import { followedOf } from '../../data/followed.js'; import { displayedKinematics } from '../../data/motionModel.js'; import { t } from '../../i18n/index.js'; -import * as Cesium from 'cesium'; +import { toLonLatH } from '../../geo/ellipsoid.js'; +import { clone, distance as distanceBetween, vec } from '../../geo/vector.js'; import { isExplicitLayerStateOrigin } from '../../data/layerState.js'; import { aircraftIncludedInNearby } from '../../data/aircraftNearbyPolicy.js'; import { modelVisualAnchor } from '../../data/modelVisualAnchor.js'; @@ -89,7 +90,7 @@ export function createQueries({ * Build a public descriptor for one aircraft using its best current position * (dead-reckoned when history exists, icon position otherwise). * @param {string} icao24 - ICAO hex identifier of the aircraft. - * @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null} + * @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null, verticalRateMps: number|null}|null} * Descriptor with a cloned position, or null if the aircraft is unknown. */ @@ -97,7 +98,7 @@ export function createQueries({ const info = flightState.records.data.get(icao24); const basePos = parts.motion._deadReckon(icao24) || - parts.icons._iconPosition(icao24, new Cesium.Cartesian3()); + parts.icons._iconPosition(icao24, vec()); if (!basePos) return null; const displayed = displayedKinematics({ derivedSpeedMps: flightState._drSpeedMps, @@ -105,11 +106,7 @@ export function createQueries({ reportedSpeedMps: info?.speedMps, reportedTrackDeg: info?.track, }); - const carto = Cesium.Cartographic.fromCartesian( - basePos, - Cesium.Ellipsoid.WGS84, - flightState._scratchCarto, - ); + const carto = toLonLatH(basePos); if (!carto) return null; return { icao24, @@ -118,9 +115,9 @@ export function createQueries({ // getTrackedSubject and the voice narration can read it straight off the // descriptor instead of reaching back into `_flightData`. registration: _toCleanText(info?.registration) || null, - position: Cesium.Cartesian3.clone(basePos), - latitude: Cesium.Math.toDegrees(carto.latitude), - longitude: Cesium.Math.toDegrees(carto.longitude), + position: clone(basePos), + latitude: carto.lat, + longitude: carto.lon, // Keep the cockpit readout on the reported aviation altitude. Render // terrain height is a separate visual datum and may be below zero. altitudeM: Number.isFinite(info?.altitudeM) @@ -342,7 +339,7 @@ export function createQueries({ /** * Find military aircraft near a given ECEF position, sorted by distance. * Used by proximity-based features (e.g. detection overlay, spatial queries). - * @param {Cesium.Cartesian3} center - Reference position in ECEF coordinates + * @param {{x: number, y: number, z: number}} center - Reference position in ECEF coordinates * @param {number} range - Maximum distance in meters (Infinity if not specified) * @param {number} [maxCount=50] - Maximum number of results to return * @param {object} [options] Query membership options. @@ -383,9 +380,9 @@ export function createQueries({ ) continue; - const distance = Cesium.Cartesian3.distance(center, drawn); + const distance = distanceBetween(center, drawn); if (distance > maxRange) continue; - const pos = trackedPos || Cesium.Cartesian3.clone(drawn); + const pos = trackedPos || clone(drawn); const info = flightState.records.data.get(icao24); nearby.push({ @@ -423,7 +420,7 @@ export function createQueries({ * @param {Object} [options={}] - Options * @param {number} [options.maxCount] - Maximum objects to return (defaults to all) * @param {number} [options.seed] - Seed offset for stride sampling (for frame variation) - * @returns {Array<{position: Cesium.Cartesian3, id: string, type: string, skipLabel: boolean}>} + * @returns {Array<{position: {x: number, y: number, z: number}, id: string, type: string, skipLabel: boolean}>} */ getDetectableObjects(options = {}) { const icons = flightState._icons; @@ -464,8 +461,8 @@ export function createQueries({ sourceId: icao24, type: 'AIR', tier: 'military', - _weldPos: new Cesium.Cartesian3(), - _iconPos: new Cesium.Cartesian3(), + _weldPos: vec(), + _iconPos: vec(), }; flightState._detectionObjects.set(icao24, object); } @@ -488,7 +485,7 @@ export function createQueries({ spec, (view ??= parts.rendering._drawnScaleView()), ), - object._weldPos || (object._weldPos = new Cesium.Cartesian3()), + object._weldPos || (object._weldPos = vec()), ) : icons.position(icao24, t, object._iconPos); // An icon past the horizon is not drawn, so it is not detectable. @@ -530,7 +527,7 @@ export function createQueries({ * Match priority: exact icao24 hex, exact callsign, callsign prefix, * then callsign substring (all case-insensitive, trimmed). * @param {string} query - ICAO hex or full/partial callsign. - * @returns {{icao24: string, callsign: string|null, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null} + * @returns {{icao24: string, callsign: string|null, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number, velocityMps: number|null, track: number|null}|null} * Best match with a cloned, dead-reckoned position, or null if none. */ findByQuery(query) { @@ -574,7 +571,7 @@ export function createQueries({ * Cheap snapshot for voice-tool framing — drawn icon positions, no * extra dead reckoning. * @param {number} [maxCount=500] - Maximum number of entries to return. - * @returns {Array<{id: string, label: string, position: Cesium.Cartesian3, latitude: number, longitude: number, altitudeM: number}>} + * @returns {Array<{id: string, label: string, position: {x: number, y: number, z: number}, latitude: number, longitude: number, altitudeM: number}>} */ /** * Whether this layer still carries a contact, in O(1). @@ -606,12 +603,8 @@ export function createQueries({ const result = []; for (const icao24 of icons.ids()) { - const pos = icons.position(icao24, t, new Cesium.Cartesian3()); - const carto = Cesium.Cartographic.fromCartesian( - pos, - Cesium.Ellipsoid.WGS84, - flightState._scratchCarto, - ); + const pos = icons.position(icao24, t, vec()); + const carto = toLonLatH(pos); if (!carto) continue; const info = flightState.records.data.get(icao24); result.push({ @@ -623,8 +616,8 @@ export function createQueries({ _toCleanText(info?.registration) || icao24, position: pos, - latitude: Cesium.Math.toDegrees(carto.latitude), - longitude: Cesium.Math.toDegrees(carto.longitude), + latitude: carto.lat, + longitude: carto.lon, altitudeM: carto.height, }); if (result.length >= limit) break; @@ -735,7 +728,6 @@ export function createQueries({ if (!flightState._icons?.has(id)) id = id.toLowerCase(); if ( id !== flightState._trackedIcao || - !flightState._viewer.entities?.contains?.(flightState._trackedEntity) || followedOf(flightState._viewer) !== flightState._followTarget ) return false; @@ -777,7 +769,7 @@ export function createQueries({ /** * Return the current aircraft as a Context subject without changing * tracking or camera ownership. - * @returns {{layerId: string, id: string, label: string, position: Cesium.Cartesian3}|null} + * @returns {{layerId: string, id: string, label: string, position: {x: number, y: number, z: number}}|null} * Detached subject descriptor, or null when no aircraft is tracked. */ getTrackedSubject() { @@ -790,7 +782,7 @@ export function createQueries({ // Same label chain as getNearby/getDetectableObjects: a callsign-less // contact reads as its registration, never as the raw ICAO hex. label: described.callsign || described.registration || described.icao24, - position: Cesium.Cartesian3.clone(described.position), + position: clone(described.position), }; }, diff --git a/src/layers/military/snapshotRenderer.test.mjs b/src/layers/military/snapshotRenderer.test.mjs index ed170583e..24f66c737 100644 --- a/src/layers/military/snapshotRenderer.test.mjs +++ b/src/layers/military/snapshotRenderer.test.mjs @@ -32,7 +32,11 @@ function harness({ viewer = null, floor = null } = {}) { records: { data: new Map() }, }; const parts = { - rendering: { _modelOwnsVisual: () => false, _syncModelToClass() {} }, + rendering: { + _modelOwnsVisual: () => false, + _syncModelToClass() {}, + _groundSampleExclusions: () => ({ sets: ['fleet-models', 'icons'] }), + }, icons: { _iconIds: () => ['icon-primitive'], _addIcon: (id) => iconIds.add(id), @@ -115,10 +119,10 @@ test('the mesh floor probe takes the camera subpoint from the camera port', () = h.apply(CONTACT, 1_700_000_000_000); assert.equal(h.meshCalls.length, 1); const [call] = h.meshCalls; - assert.equal(call.scene, viewer.scene); + assert.equal(call.scene, viewer); assert.equal(call.options.viewerLat, 30.5); assert.equal(call.options.viewerLon, -97.25); - assert.deepEqual(call.options.excludeObjects, ['icon-primitive']); + assert.deepEqual(call.options.sets, ['fleet-models', 'icons']); }); test('without a viewer the mesh floor probe has no camera subpoint', () => { diff --git a/src/layers/military/state.js b/src/layers/military/state.js index ca2eca5e0..08eee6eda 100644 --- a/src/layers/military/state.js +++ b/src/layers/military/state.js @@ -1,6 +1,5 @@ import { MilitaryFlightRecords } from './records.js'; import { createMilitaryFeed } from './ingestion.js'; -import * as Cesium from 'cesium'; export function createFlightState({ source, services }) { const { createGroundSnap } = services.groundSnap; @@ -50,10 +49,6 @@ export function createFlightState({ source, services }) { flightState._lastModelCapWarnMs = 0; // throttle the "more planes in view than the cap" console notice - flightState._scratchModelBS = new Cesium.BoundingSphere( - new Cesium.Cartesian3(), - 1.0, - ); // --------------------------------------------------------------------------- // Module-level state @@ -72,7 +67,7 @@ export function createFlightState({ source, services }) { flightState._detectionObjects = new Map(); - /** @type {Map>} ICAO hex -> recent position samples for dead reckoning */ + /** @type {Map>} ICAO hex -> recent position samples for dead reckoning */ flightState._positionHistory = new Map(); @@ -85,7 +80,7 @@ export function createFlightState({ source, services }) { flightState._trackingIntentGeneration = 0; - /** @type {Cesium.Entity|null} Entity created for the tracked aircraft (camera follows this) */ + /** @type {object|null} The tracked aircraft's record holder (its entity record is what the app shows; the camera follows a target reading it) */ flightState._trackedEntity = null; @@ -102,7 +97,7 @@ export function createFlightState({ source, services }) { flightState._clickSubscription = null; - /** @type {Cesium.Viewer|null} Cached viewer reference */ + /** @type {object|null} Cached viewer reference */ flightState._viewer = null; @@ -132,7 +127,7 @@ export function createFlightState({ source, services }) { flightState._trailHeadOff = null; - /** @type {Cesium.Cartesian3[]} Chronological tracked-aircraft fixes (oldest first) */ + /** @type {{x: number, y: number, z: number}[]} Chronological tracked-aircraft fixes (oldest first) */ flightState._trailPositions = []; @@ -148,50 +143,46 @@ export function createFlightState({ source, services }) { flightState._lastTrackedRotation = 0; - /** @type {Cesium.Event.RemoveCallback|null} preRender listener disposer */ + /** @type {() => void|null} preRender listener disposer */ flightState._preRenderRemove = null; flightState._trackedModelPreUpdateRemove = null; - /** @type {Cesium.Event.RemoveCallback|null} camera.moveEnd listener disposer (arrival rotation pass) */ + /** @type {() => void|null} camera.moveEnd listener disposer (arrival rotation pass) */ flightState._moveEndRemove = null; - /** @type {Cesium.Event.RemoveCallback|null} trackedEntityChanged listener disposer (cross-layer untrack) */ + /** @type {() => void|null} trackedEntityChanged listener disposer (cross-layer untrack) */ flightState._trackedEntityChangedRemove = null; // -- Scratch variables (reused each frame to avoid GC pressure) -- - flightState._scratchOffset = new Cesium.Cartesian3(); - - flightState._scratchCarto = new Cesium.Cartographic(); - - flightState._scratchEnu = new Cesium.Matrix4(); + flightState._scratchOffset = { x: 0, y: 0, z: 0 }; flightState._scratchArc = { east: 0, north: 0, endCourseDeg: 0 }; - flightState._scratchRenderTime = new Cesium.JulianDate(); + flightState._scratchRenderTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._scratchFleetRenderTime = new Cesium.JulianDate(); + flightState._scratchFleetRenderTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._scratchFleetPos = new Cesium.Cartesian3(); + flightState._scratchFleetPos = { x: 0, y: 0, z: 0 }; - flightState._scratchCockpitPos = new Cesium.Cartesian3(); + flightState._scratchCockpitPos = { x: 0, y: 0, z: 0 }; - flightState._scratchNearbyPos = new Cesium.Cartesian3(); + flightState._scratchNearbyPos = { x: 0, y: 0, z: 0 }; - flightState._scratchSonarScreen = new Cesium.Cartesian2(); + flightState._scratchSonarScreen = { x: 0, y: 0 }; - flightState._scratchDrRaw = new Cesium.Cartesian3(); + flightState._scratchDrRaw = { x: 0, y: 0, z: 0 }; - flightState._scratchWarmupTime = new Cesium.JulianDate(); + flightState._scratchWarmupTime = { dayNumber: 0, secondsOfDay: 0 }; - flightState._trackedPosHolder = new Cesium.Cartesian3(); + flightState._trackedPosHolder = { x: 0, y: 0, z: 0 }; // -- Per-frame dead-reckoning cache for the tracked entity -- - /** @type {Cesium.Cartesian3|null} Cached DR position for the current render frame */ + /** @type {{x: number, y: number, z: number}|null} Cached DR position for the current render frame */ flightState._cachedDRPosition = null; @@ -240,13 +231,13 @@ export function createFlightState({ source, services }) { flightState._displayCourse = new Map(); - flightState._drCorrection = new Cesium.Cartesian3(0, 0, 0); + flightState._drCorrection = { x: 0, y: 0, z: 0 }; flightState._drCorrectionStartMs = 0; - flightState._drPrevRaw = new Cesium.Cartesian3(); + flightState._drPrevRaw = { x: 0, y: 0, z: 0 }; - flightState._drPrevDisplay = new Cesium.Cartesian3(); + flightState._drPrevDisplay = { x: 0, y: 0, z: 0 }; flightState._drPrevMs = 0; @@ -256,20 +247,20 @@ export function createFlightState({ source, services }) { flightState._drReconcileIcao = null; - /** @type {Cesium.Cartesian3} Scratch for the tracked model's rendered translation. */ + /** @type {{x: number, y: number, z: number}} Scratch for the tracked model's rendered translation. */ - flightState._trackedVisualPos = new Cesium.Cartesian3(); + flightState._trackedVisualPos = { x: 0, y: 0, z: 0 }; - flightState._trackedTrailPos = new Cesium.Cartesian3(); + flightState._trackedTrailPos = { x: 0, y: 0, z: 0 }; /** Scratch for the tracked model's world-space origin (the envelope centre). */ - flightState._scratchTrailClip = new Cesium.Cartesian3(); + flightState._scratchTrailClip = { x: 0, y: 0, z: 0 }; /** Scratch for the shortened trail-head start. Owned by the head-segment * callback alone, so nothing else can overwrite it mid-frame. */ - flightState._scratchTrailHead = new Cesium.Cartesian3(); + flightState._scratchTrailHead = { x: 0, y: 0, z: 0 }; /** Hysteresis latch for the tracked contact's zoom regime, plus the selection it * belongs to. Scoped per selection so a NEW target re-evaluates against the ENTER @@ -285,8 +276,5 @@ export function createFlightState({ source, services }) { flightState._irBoost = false; - /** @type {Cesium.Cartographic} Scratch for _trailFloorPosition (per-frame safe). */ - - flightState._scratchTrailCarto = new Cesium.Cartographic(); return flightState; } diff --git a/src/layers/military/tracking.js b/src/layers/military/tracking.js index 30b849ee6..592cf1615 100644 --- a/src/layers/military/tracking.js +++ b/src/layers/military/tracking.js @@ -1,19 +1,30 @@ -import { cameraOf } from '../../render/cesium/camera.js'; -import { findFrame } from '../../render/rendererOf.js'; +import { cameraOf, findCamera, findFrame } from '../../render/rendererOf.js'; import { entityFollowTarget, onFollowChanged, stopFollowing, } from '../../data/followed.js'; -import * as Cesium from 'cesium'; import { t } from '../../i18n/index.js'; import { nextCockpitNearContacts } from '../../data/cockpitAirLod.js'; import { aircraftIcon, TRACKED_ICON_PX } from '../../data/aircraftIcons.js'; import { trackedModelZoomActive } from '../../data/trackedModelRegime.js'; import { - screenProjectedRotation, + courseScreenRotation, stabilizeScreenRotation, -} from '../../data/iconOrientation.js'; +} from '../../data/screenRotation.js'; +import { + createTrackedAircraftIcon, + isOtherTrackedIconSet, + trackedContactHolder, +} from '../../data/trackedAircraftIcon.js'; +import { fromDegrees, toLonLatH } from '../../geo/ellipsoid.js'; +import { + addSeconds, + julianLessThanOrEquals, + julianNow, + julianToEpochMs, +} from '../../geo/julian.js'; +import { clone, distanceSquared, vec } from '../../geo/vector.js'; import { trailHeadStart } from '../../data/modelVisualAnchor.js'; import { CLASS_SCALE_2D } from '../../data/aircraftClass.js'; import { @@ -41,7 +52,7 @@ function aircraftPickId(picked) { const id = picked?.id; if (typeof id === 'string') return id; if (id && typeof id.set === 'string' && typeof id.id === 'string') - return id.id; + return isOtherTrackedIconSet(id.set, 'military') ? undefined : id.id; return picked?.primitive?.id; } @@ -67,6 +78,21 @@ export function createTracking({ const { clearFocusTarget } = services.focus; const { FOLLOW_MIN_RANGE_M } = services.camera; const { resolvePickId, isOwnedByOtherLayer } = services.picking; + /** The tracked contact's billboard (an icon set on the draw port). */ + const trackedIcon = createTrackedAircraftIcon({ + viewer: () => flightState._viewer, + setPrefix: 'military', + }); + + /** The camera's pose, or null without a camera to ask. */ + function _pose() { + const viewer = flightState._viewer; + try { + return (viewer && findCamera(viewer)?.pose()) ?? null; + } catch { + return null; + } + } function _emitAwarenessEvent(type, detail) { if ( @@ -79,7 +105,7 @@ export function createTracking({ } function _publishTrackedSelection(icao24, origin = 'programmatic') { - const position = parts.icons._iconPosition(icao24, new Cesium.Cartesian3()); + const position = parts.icons._iconPosition(icao24, vec()); const info = flightState.records.data.get(icao24); if (!position || !info) return false; if (flightState._trackedEntity) @@ -157,10 +183,8 @@ export function createTracking({ /** Refresh the AIR-only Cockpit near band independently from model admission. */ function _refreshCockpitNearContacts() { - if ( - !flightState._cockpitContactMode || - !flightState._viewer?.camera?.positionWC - ) { + const eye = flightState._cockpitContactMode ? _pose()?.position : null; + if (!eye) { if (flightState._cockpitNearContacts.size) flightState._cockpitNearContacts = new Set(); return; @@ -176,13 +200,7 @@ export function createTracking({ t, flightState._scratchCockpitPos, ); - distancesSquared.push([ - icao24, - Cesium.Cartesian3.distanceSquared( - flightState._viewer.camera.positionWC, - position, - ), - ]); + distancesSquared.push([icao24, distanceSquared(eye, position)]); } const next = nextCockpitNearContacts( previous, @@ -284,12 +302,9 @@ export function createTracking({ refreshTrackedSubjectContext(_contextSubjectMetadata(icao24)); } - /** Re-image the tracked entity's billboard from the current class/conversion. */ - - function _syncTrackedBillboardImage() { - if (!flightState._trackedIcao || !flightState._trackedEntity?.billboard) - return; - flightState._trackedEntity.billboard.image = aircraftIcon( + /** The tracked billboard's image, from the current class/conversion. */ + function _trackedBillboardImage() { + return aircraftIcon( parts.rendering._iconKind( flightState._trackedIcao, flightState.records.data.get(flightState._trackedIcao)?.klass, @@ -298,6 +313,13 @@ export function createTracking({ ); } + /** Re-image the tracked billboard from the current class/conversion. */ + + function _syncTrackedBillboardImage() { + if (!flightState._trackedIcao || !flightState._trackedEntity) return; + trackedIcon.setImage(_trackedBillboardImage()); + } + /** * Re-render one contact after its TR-3B conversion (or the active IR style) * changed. Mirror of flights.js: converting drops any 3D model so the triangle @@ -325,7 +347,8 @@ export function createTracking({ _syncTrackedBillboardImage(); _updateTrackedLabelModel(id); } - flightState._viewer?.scene?.requestRender?.(); + if (flightState._viewer) + findFrame(flightState._viewer)?.requestRender('military: TR-3B restyle'); return flightState._icons?.has(id) || id === flightState._trackedIcao; } @@ -384,7 +407,7 @@ export function createTracking({ return false; } flightState._trackedZoomLatched = trackedModelZoomActive( - flightState._viewer?.camera?.positionCartographic?.height, + _pose()?.height, flightState._trackedZoomLatched, ); return flightState._trackedZoomLatched; @@ -396,13 +419,10 @@ export function createTracking({ if (!flightState._trackedIcao || !flightState._viewer) return; const pos = parts.motion._trackedDisplayCached() || - parts.icons._iconPosition( - flightState._trackedIcao, - new Cesium.Cartesian3(), - ); + parts.icons._iconPosition(flightState._trackedIcao, vec()); if (!pos) return; - const projected = screenProjectedRotation( - flightState._viewer.scene, + const projected = courseScreenRotation( + _pose(), pos, parts.motion._trackedDisplayCourse(), flightState._lastTrackedRotation, @@ -423,31 +443,27 @@ export function createTracking({ * invariant), so every position entering the TRAIL subsystem (seed, append, * per-frame head) goes through this instead — the visible taxi history sits * on the surface without touching the billboard/model machinery. - * @param {Cesium.Cartesian3} position - Owned position (mutated/replaced freely). - * @returns {Cesium.Cartesian3} The same or a lifted position. + * @param {{x: number, y: number, z: number}} position - Owned ECEF position (mutated/replaced freely). + * @returns {{x: number, y: number, z: number}} The same or a lifted position. */ function _trailFloorPosition(position) { - const carto = Cesium.Cartographic.fromCartesian( - position, - Cesium.Ellipsoid.WGS84, - flightState._scratchTrailCarto, - ); + const carto = toLonLatH(position); if (!carto) return position; - const latDeg = Cesium.Math.toDegrees(carto.latitude); - const lonDeg = Cesium.Math.toDegrees(carto.longitude); + const latDeg = carto.lat; + const lonDeg = carto.lon; const floored = floorAltitudeM( carto.height, cachedGroundFloor(latDeg, lonDeg), ); if (floored == null || floored === carto.height) return position; - return Cesium.Cartesian3.fromDegrees(lonDeg, latDeg, floored); + return fromDegrees(lonDeg, latDeg, floored); } /** * Append one fix to the tracked aircraft's trail accumulation and refresh * the rendered trail. Caller passes an owned (cloned) Cartesian3. - * @param {Cesium.Cartesian3} position - New fix position, appended at the head. + * @param {{x: number, y: number, z: number}} position - New ECEF fix, appended at the head. */ function _appendTrailFix(position) { @@ -478,7 +494,7 @@ export function createTracking({ /** * The live head: the last DISPLAYED body point to the delayed head, or no * positions while there is none. - * @returns {Cesium.Cartesian3[]} + * @returns {Array<{x: number, y: number, z: number}>} */ function _trailHeadPositions() { // Need ≥2 accumulated points: the body draws all-but-newest, so the head must @@ -503,7 +519,7 @@ export function createTracking({ // Floor the head too (round 2): a grounded tracked contact's DR // display height is the pre-datum default — without this the last // segment dives underground while taxiing. - const end = _trailFloorPosition(Cesium.Cartesian3.clone(head)); + const end = _trailFloorPosition(clone(head)); // On a contact that has not moved this segment runs from inside the // model out to its own anchor — a line through the fuselage. The END // never gives, so a moving trail still terminates on the tail; the @@ -541,18 +557,18 @@ export function createTracking({ // Seed only fixes at/behind the DELAYED display time (now − RENDER_DELAY_SEC). The // newest ~RENDER_DELAY_SEC of fixes are AHEAD of the displayed icon; including them // would draw the trail in front of the plane. They join via _appendTrailFix as they age. - const seedRenderTime = Cesium.JulianDate.addSeconds( - Cesium.JulianDate.now(), + const seedRenderTime = addSeconds( + julianNow(), -RENDER_DELAY_SEC, flightState._scratchWarmupTime, ); for (const fix of history) { - if (Cesium.JulianDate.lessThanOrEquals(fix.time, seedRenderTime)) { + if (julianLessThanOrEquals(fix.time, seedRenderTime)) { // Floor grounded-history seeds (round 2): a grounded contact's stored // fixes carry the pre-datum default height — the trail copy sits on // the surface instead (pure lift; airborne fixes pass through). flightState._trailPositions.push( - _trailFloorPosition(Cesium.Cartesian3.clone(fix.position)), + _trailFloorPosition(clone(fix.position)), ); } } @@ -574,7 +590,7 @@ export function createTracking({ _refreshTrailDisplay(); const oldestFixEpochSec = history.length - ? Cesium.JulianDate.toDate(history[0].time).getTime() / 1000 + ? julianToEpochMs(history[0].time) / 1000 : Infinity; _backfillTrail(icao24, flightState._trailBackfillToken, oldestFixEpochSec); } @@ -664,7 +680,7 @@ export function createTracking({ // sentinel (an arbitrary placeholder, never a reported altitude). if (altM == null) altM = lastAltM != null ? lastAltM : 50; lastAltM = altM; - older.push(Cesium.Cartesian3.fromDegrees(lon, lat, altM)); + older.push(fromDegrees(lon, lat, altM)); } // Stride-thin the backfill so it plus the live fine segment fit the cap. @@ -749,17 +765,15 @@ export function createTracking({ // release never flips it. const trackedCourseDeg = flightState._displayCourse.get(clearedIcao); - // Stop tracking and remove the entity. skipViewerUntrack: another layer just grabbed the - // follow-camera, so tear down our state but DON'T clear the camera's follow (they own it now). - // Releasing trackedEntity does NOT move the camera: Cesium resets the lookAt transform in - // place, so the view stays where the follow left it and the user can immediately orbit/zoom. + // Stop tracking and hide the tracked billboard. skipViewerUntrack: another layer just grabbed + // the follow-camera, so tear down our state but DON'T clear the camera's follow (they own it + // now). Releasing the follow does NOT move the camera: the view stays where the follow left it + // and the user can immediately orbit/zoom. if (flightState._viewer && !skipViewerUntrack) { stopFollowing(flightState._viewer); } - if (flightState._trackedEntity) { - flightState._viewer.entities.remove(flightState._trackedEntity); - flightState._trackedEntity = null; - } + trackedIcon.hide(); + flightState._trackedEntity = null; parts.rendering._releaseTrackedModel(); _resetTrackedSelectionState(); // the zoom band belongs to the selection we just dropped flightState._trackedIcao = null; @@ -820,19 +834,14 @@ export function createTracking({ // The tracked limiter continues from the nose the icon was drawn with, and // the entity starts with the rotation the icon had on screen. const t = parts.icons._displayMs(); - const iconPosition = icons.position(icao24, t, new Cesium.Cartesian3()); + const iconPosition = icons.position(icao24, t, vec()); const iconCourse = icons.course(icao24, t); flightState._displayCourse.set(icao24, iconCourse); flightState._trackedIcao = icao24; _resetTrackedSelectionState(); // fresh selection: enter at the ENTER ceiling flightState._cachedDRFrame = -1; flightState._lastTrackedRotation = - screenProjectedRotation( - flightState._viewer.scene, - iconPosition, - iconCourse, - 0, - ) ?? 0; + courseScreenRotation(_pose(), iconPosition, iconCourse, 0) ?? 0; // Drop any fleet 3D model for this aircraft — the tracked entity now owns its visual (its // own billboard + model graphic), and the fleet tick skips the tracked icao, so a leftover // fleet model would be orphaned + double-rendered. @@ -847,28 +856,20 @@ export function createTracking({ // aircraft has no fix. const getTrackedPosition = () => parts.motion._trackedDisplayPosition(icao24) || - parts.icons._iconPosition(icao24, new Cesium.Cartesian3()) || + parts.icons._iconPosition(icao24, vec()) || iconPosition; - // Dead-reckoning position property evaluated every render frame. - // isConstant = false so CesiumJS re-evaluates each frame. - const positionProperty = new Cesium.CallbackProperty(() => { - return getTrackedPosition(); - }, false); - - // World-space orientation for the 3D model: nose along the course heading (ENU, pitch/roll 0). - // Create tracked entity: a 2D billboard when zoomed out, a 3D model when zoomed in past the - // TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on the - // DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always + // The tracked billboard: a 2D icon when zoomed out, handing over to the 3D model when zoomed + // in past the TRACKED altitude ceiling. That handoff is DEFAULT behaviour — it does NOT wait on + // the DISPLAY-rail 3D toggle, which arms the FLEET. The plane the user zooms into always // resolves into an aircraft. // // The billboard stays SHOWN at all times and is hidden by going TRANSPARENT (alpha 0), not by - // show=false: it drops its alpha only once the tracked model is drawing, so - // there's neither a billboard+model double-image nor a gap. The camera follows its own target - // through the camera port, so nothing here frames the camera. - // The tracked entity is a PURE BILLBOARD — no label or model graphic. The tracked plane's 3D - // model is the standalone primitive driven by _updateTrackedModel(); it stays off the entity (see _trackedModel). - // What the tracked billboard is drawn at, kept in its entity record so the + // show=false: it drops its alpha only once the tracked model is drawing, so there's neither a + // billboard+model double-image nor a gap. The camera follows its own target through the camera + // port, so nothing here frames the camera. The tracked plane's 3D model is a draw-set item + // driven by _updateTrackedModel() (see _trackedModel). + // What the tracked billboard is drawn at, kept in its record so the // camera guard and screen annotations size it from the app. const sprite = { width: 28, @@ -880,58 +881,49 @@ export function createTracking({ ] || 1), scaleByDistance: TRACKED_BILLBOARD_SCALE_BY_DISTANCE, }; - flightState._trackedEntity = flightState._viewer.entities.add({ - position: positionProperty, - billboard: { - image: aircraftIcon( - parts.rendering._iconKind( - flightState._trackedIcao, - flightState.records.data.get(flightState._trackedIcao)?.klass, - ), - TRACKED_ICON_PX, - ), - width: sprite.width, - height: sprite.height, - scale: sprite.scale, - // Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading); - // transparent once the STANDALONE tracked model is actually up (ready + shown). - color: new Cesium.CallbackProperty( - () => - parts.rendering._modelOwnsVisual(flightState._trackedIcao) - ? AMBER_TRANSPARENT - : TRACKED_ICON_COLOR, - false, - ), - sizeInMeters: false, - scaleByDistance: sprite.scaleByDistance, - alignedAxis: Cesium.Cartesian3.ZERO, - // The tracked target must never vanish into tile geometry — tracking a - // taxiing plane at street level would otherwise bury the amber icon inside - // the runway skin, so it draws depth-test-free like the fleet icon set; - // its shared-host tracked card is top-composited separately. - disableDepthTestDistance: Number.POSITIVE_INFINITY, - // Screen-projected rotation, evaluated per frame: exact in tracked-orbit - // mode where camera.heading lives in the entity's reference frame. - rotation: new Cesium.CallbackProperty(() => { - const tracked = flightState.records.data.get( - flightState._trackedIcao, - ); - const pos = getTrackedPosition(); - if (!tracked || !pos || !flightState._viewer) - return flightState._lastTrackedRotation; - const projected = screenProjectedRotation( - flightState._viewer.scene, - pos, - parts.motion._trackedDisplayCourse(), - flightState._lastTrackedRotation, - ); - const rot = stabilizeScreenRotation( - flightState._lastTrackedRotation, - projected, - ); - if (rot !== null) flightState._lastTrackedRotation = rot; + // The tracked contact as its readers see it (the tracked card, Cockpit, share links): a + // plain holder of its entity record, drawn while it is the one tracked. + const holder = trackedContactHolder( + `military:${icao24}`, + trackedIcon, + parts.motion._trackedDisplayCached, + ); + flightState._trackedEntity = holder; + entityRecord(holder).drawn = () => flightState._trackedEntity === holder; + trackedIcon.show({ + id: icao24, + image: _trackedBillboardImage(), + sprite, + position: getTrackedPosition, + // Solid amber when the billboard is the visual (zoomed out, 3D off, or model still loading); + // transparent once the tracked model is actually up (ready + shown). + color: () => + parts.rendering._modelOwnsVisual(flightState._trackedIcao) + ? AMBER_TRANSPARENT + : TRACKED_ICON_COLOR, + // Screen-projected rotation, evaluated per frame on the camera's own + // axes, so it stays exact through a tracked orbit. The tracked target + // must never vanish into tile geometry — tracking a taxiing plane at + // street level would otherwise bury the amber icon inside the runway + // skin, so it draws over depth like the fleet icon set; its + // shared-host tracked card is top-composited separately. + rotation: () => { + const tracked = flightState.records.data.get(flightState._trackedIcao); + const pos = getTrackedPosition(); + if (!tracked || !pos || !flightState._viewer) return flightState._lastTrackedRotation; - }, false), + const projected = courseScreenRotation( + _pose(), + pos, + parts.motion._trackedDisplayCourse(), + flightState._lastTrackedRotation, + ); + const rot = stabilizeScreenRotation( + flightState._lastTrackedRotation, + projected, + ); + if (rot !== null) flightState._lastTrackedRotation = rot; + return flightState._lastTrackedRotation; }, }); entityRecord(flightState._trackedEntity).selectionOrigin = origin; @@ -940,20 +932,16 @@ export function createTracking({ entityRecord(flightState._trackedEntity).labelModel = trackedLabelModelFromText(_buildTrackedLabel(info, icao24), '#ffd166'); - // A billboard has a ~zero bounding sphere, so Cesium's default follow distance is - // far too tight (the user had to scroll out to read the plane). Give the entity a + // A billboard has a ~zero bounding sphere, so the renderer's default follow distance is + // far too tight (the user had to scroll out to read the plane). Give the target a // calibrated viewFrom — behind + above, distance scaled to altitude — for a readable // initial frame with surrounding context. (ENU: east=+X, north=+Y, up=+Z.) const altM = info?.altitudeFt ? info.altitudeFt * 0.3048 : 1500; const followRange = Math.min(Math.max(altM * 1.1 + 2500, 3000), 30000); - const viewFrom = new Cesium.Cartesian3( - 0, - -followRange * 0.8, - followRange * 0.55, - ); + const viewFrom = vec(0, -followRange * 0.8, followRange * 0.55); - // Cancel any in-progress camera flight first — otherwise Cesium won't apply the tracked - // entity's viewFrom on the first frame, so voice-initiated tracking (which often fires + // Cancel any in-progress camera flight first — otherwise the camera won't apply the follow + // target's viewFrom on the first frame, so voice-initiated tracking (which often fires // mid-fly_to_location) would follow the plane WITHOUT centering it like a click does. // Cross-module HUD consumers (tracked-target readout) read the camera's settled position, not a // postRender recompute, so the label doesn't jitter against the now-stable plane (mirror of flights). @@ -1011,7 +999,7 @@ export function createTracking({ * Clicking a military billboard starts tracking that aircraft; clicking empty * space or a non-military object deselects. Also attaches the Escape key * listener via {@link _onKeyDown}. Idempotent -- no-ops if already installed. - * @param {Cesium.Viewer} viewer - The Cesium viewer instance + * @param {object} viewer - The viewer */ function _installClickHandler(viewer) { @@ -1051,14 +1039,11 @@ export function createTracking({ const picked = event.hit; if (picked) { - // Clicking the tracked entity itself -- ignore (don't deselect) - if (picked.id === flightState._trackedEntity) return; - - // Clicking the plane we're ALREADY tracking (its standalone 3D model or - // any pick carrying its icao) — same no-op as the 2D tracked-entity click - // above. H1: the model used to have no pick id, so this fell through to + // Clicking the plane we're ALREADY tracking (its tracked billboard, its + // 3D model, or any pick carrying its icao) — ignore, don't deselect. + // H1: the model used to have no pick id, so this fell through to // "empty space" and deselected the very plane being tracked. - // Its models are draw-set items keyed by icao, like its icons. + // Its billboard and models are draw-set items keyed by icao, like its icons. const pickedIcao = aircraftPickId(picked); if (flightState._trackedIcao && pickedIcao === flightState._trackedIcao) return; @@ -1114,6 +1099,9 @@ export function createTracking({ _backfillTrail, _clearTrail, _destroyTrail, + /** Let the tracked billboard's set go (layer teardown). */ + _disposeTrackedIcon: () => trackedIcon.dispose(), + /** The tracked billboard's set id, or null before one is made. */ _clearTracking, _applyPendingTrackingRestore, _cancelPendingTrackingRestore, diff --git a/src/render/cesiumAllowList.json b/src/render/cesiumAllowList.json index 72dba8e52..e5b775159 100644 --- a/src/render/cesiumAllowList.json +++ b/src/render/cesiumAllowList.json @@ -21,23 +21,11 @@ "src/layers/cctv/projection.js", "src/layers/cctv/rendering.js", "src/layers/firms/rendering.js", - "src/layers/flights/enrichment.js", - "src/layers/flights/evidence.js", - "src/layers/flights/motion.js", - "src/layers/flights/policy.js", - "src/layers/flights/queries.js", - "src/layers/flights/state.js", - "src/layers/flights/tracking.js", "src/layers/ghostMaps/index.js", "src/layers/installations/rendering.js", "src/layers/launches/launchPad.js", "src/layers/launches/orbitRendering.js", "src/layers/launches/rendering.js", - "src/layers/military/motion.js", - "src/layers/military/policy.js", - "src/layers/military/queries.js", - "src/layers/military/state.js", - "src/layers/military/tracking.js", "src/layers/radio/rendering.js", "src/layers/recentImagery/rendering.js", "src/layers/satellites/rendering.js", diff --git a/src/render/unboundCamera.test.mjs b/src/render/unboundCamera.test.mjs index 3f393cddd..1acdf43ad 100644 --- a/src/render/unboundCamera.test.mjs +++ b/src/render/unboundCamera.test.mjs @@ -91,6 +91,10 @@ const DRAW_FROM_CALLER = new Set([ // Asks `findQuery` instead, and answers null rather than throw until the // caller has loaded the factory. './queries/heights', + // Their fleet icons draw through `drawOf`. Not wholly Cesium-free (pointer + // input still is), but none of their modules loads a factory. + './layers/flights', + './layers/military', ]); /** diff --git a/src/services/meshFloorSampler.js b/src/services/meshFloorSampler.js index 9d0baf9c8..0515c2196 100644 --- a/src/services/meshFloorSampler.js +++ b/src/services/meshFloorSampler.js @@ -1,6 +1,7 @@ import * as Cesium from 'cesium'; import { approxDistanceKm } from '../data/approxDistance.js'; import { heightsFor } from '../render/cesium/heights.js'; +import { heightsOf } from '../queries/heights.js'; /** Construct an instance-owned meshFloorSampler service with explicit dependencies. */ export function createMeshFloorSampler({ @@ -94,18 +95,29 @@ export function createMeshFloorSampler({ * @param {Array} [options.excludeObjects] - Own billboards/models to * exclude from the probe (Cesium matches instances/.primitive/.id — pass * Billboard and Model instances, NOT collections). + * @param {string[]} [options.sets] - Own draw set ids to see through. When + * given, `host` must be the viewer and the probe asks the renderer's + * query port (`heightsOf`), which sees through every draw set not drawn + * as ground; `excludeObjects` is then unused. * @param {number} [options.viewerLat] @param {number} [options.viewerLon] * Viewer subpoint (computed once by the caller's poll). */ function sampleMeshFloorCells( host, points, - { excludeObjects = [], viewerLat, viewerLon } = {}, + { excludeObjects = [], 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; // Without depth-texture support every probe throws: nothing to latch. - if (!scene || !heightsFor(scene).supported().surface) return; + 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 @@ -133,9 +145,9 @@ export function createMeshFloorSampler({ ) { continue; // too far: tiles not streamed there, probe would be a guaranteed miss } - const height = heightsFor(scene).now( + const height = heights.now( Cesium.Cartographic.fromDegrees(cell.lon, cell.lat, 0, _scratchProbe), - { exclude: excludeObjects }, + { 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. diff --git a/src/ui/applicationShell.js b/src/ui/applicationShell.js index b6d318a7e..2b5d61fd1 100644 --- a/src/ui/applicationShell.js +++ b/src/ui/applicationShell.js @@ -1,4 +1,5 @@ import { followedOf } from '../data/followed.js'; +import { readEntityRecord } from '../data/entityRecords.js'; import { nextTick } from 'vue'; import { resolveImageryHost } from '../layers/weather/imageryHost.js'; import { ShellFacade } from './shellFacade.js'; @@ -378,9 +379,12 @@ export class StyleManager extends ShellFacade { meshFloorPreferred: services.meshFloorPreferred, warmGroundFloor: services.warmGroundFloor, sampleMeshFloorCells: services.sampleMeshFloorCells, - // Whether the aircraft entity Cockpit flies still draws: the flight - // layers draw it as an entity of the viewer's own. - trackedEntityDrawn: (entity) => viewer.entities.contains(entity), + // Whether the aircraft Cockpit flies still draws: an entity of the + // viewer's own, or a tracked contact whose layer draws it through + // the draw port and says so in its entity record. + trackedEntityDrawn: (entity) => + viewer.entities.contains(entity) || + readEntityRecord(entity)?.drawn?.() === true, holdContinuousRender: services.holdContinuousRender, releaseContinuousRender: services.releaseContinuousRender, fetchRegionalBrief: services.fetchRegionalBrief,